filename
stringlengths
3
9
code
stringlengths
4
1.87M
714150.c
/* ----------------------------------------------------------------- */ /* The Speech Signal Processing Toolkit (SPTK) */ /* developed by SPTK Working Group */ /* http://sp-tk.sourceforge.net/ */ /* ----------------------------------------------------------------- */ /* */ /* Copyright (c) 1984-2007 Tokyo Institute of Technology */ /* Interdisciplinary Graduate School of */ /* Science and Engineering */ /* */ /* 1996-2013 Nagoya Institute of Technology */ /* Department of Computer Science */ /* */ /* 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 SPTK working group 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. */ /* ----------------------------------------------------------------- */ /***************************************************************** * $Id: _ifft.c,v 1.19 2013/12/16 09:01:58 mataki Exp $ * * NAME: * * ifft - Inverse Fast Fourier Transform * * SYNOPSIS: * * int ifft(x, y, m) * * * * real x[]; real part * * real y[]; imaginary part * * int m; size of FFT * *****************************************************************/ #include <stdio.h> #if defined(WIN32) # include "SPTK.h" #else # include <SPTK.h> #endif int ifft(double *x, double *y, const int m) { int i; if (fft(y, x, m) == -1) return (-1); for (i = m; --i >= 0; ++x, ++y) { *x /= m; *y /= m; } return (0); }
135168.c
#include "keyboard.h" #include <stdlib.h> #include <memory.h> unsigned char keymap_us[CKRGB_KEY_COUNT+2] = { 0x0F, 0x4C, 0x34, 0x27, 0x26, 0x33, 0x3F, 0x4B, 0x62, 0x57, 0x63, 0x6F, 0x64, 0x58, 0x6E, 0x7A, 0x0E, 0x32, 0x1B, 0x3E, 0x56, 0x40, 0x1A, 0x28, 0x4A, 0x1C, 0x0C, 0x18, 0x24, 0x30, 0x3C, 0x48, 0x54, 0x60, 0x6C, 0x78, 0x84, 0x06, 0x79, 0x0D, 0x19, 0x25, 0x31, 0x3D, 0x49, 0x55, 0x61, 0x6D, 0x85, 0x07, 0x81, 0x5D, 0x69, 0x75, 0x39, 0x45, 0x51, 0x09, 0x15, 0x21, 0x50, 0x5C, 0x68, 0x74, 0x80, 0x8C, 0x8D, 0x67, 0x7F, 0x73, 0x8B, 0x20, 0x2C, 0x38, 0x44, 0x14, 0xFF, //> TODO: keycode for VOLUMEUP 0xFF, //> TODO: keycode for VOLUMEDOWN 0x2B, 0x36, 0x37, 0x42, 0x43, 0x4E, 0x04, 0x4F, 0x05, 0x5B, 0x66, 0x88, 0x11, 0x65, 0x1D, 0x59, 0x5A, 0x86, 0x12, 0x1E, 0x2A, 0x08, 0x89, 0x70, 0x7C, 0xFF, //> Hash is not found on US keyboards 0x7B, 0x00, 0x01, 0x02, 0x03, 0x1F, 0x7E, 0x35, 0x71, 0x87, 0x0b, 0x17, 0x23, 0x2f, 0x0a, 0x16, 0x22, 0x2e, 0x3a, 0x46, 0x52, 0x5e, 0x6a, 0x76, 0x3b, 0x47, 0x53, 0x5f, 0x6b, 0x77, 0x83, 0x8f, 0xFF, //> Include COUNT as nonexistant key. 0xFF //> Include MISSING as nonexistant key. }; unsigned char keymap_uk[CKRGB_KEY_COUNT+2] = { 0x0F, 0x4C, 0x34, 0x27, 0x26, 0x33, 0x3F, 0x4B, 0x62, 0x57, 0x63, 0x6F, 0x64, 0x58, 0x6E, 0x7A, 0x0E, 0x32, 0x1B, 0x3E, 0x56, 0x40, 0x1A, 0x28, 0x4A, 0x1C, 0x0C, 0x18, 0x24, 0x30, 0x3C, 0x48, 0x54, 0x60, 0x6C, 0x78, 0x84, 0x06, 0x79, 0x0D, 0x19, 0x25, 0x31, 0x3D, 0x49, 0x55, 0x61, 0x6D, 0x85, 0x07, 0x81, 0x5D, 0x69, 0x75, 0x39, 0x45, 0x51, 0x09, 0x15, 0x21, 0x50, 0x5C, 0x68, 0x74, 0x80, 0x8C, 0x8D, 0x67, 0x7F, 0x73, 0x8B, 0x20, 0x2C, 0x38, 0x44, 0x14, 0xFF, //> TODO: keycode for VOLUMEUP 0xFF, //> TODO: keycode for VOLUMEDOWN 0x2B, 0x36, 0x37, 0x42, 0x43, 0x4E, 0x04, 0x4F, 0x05, 0x5B, 0x66, 0x88, 0x11, 0x65, 0x1D, 0x59, 0x5A, 0x86, 0x12, 0x1E, 0x2A, 0x08, 0x89, 0x70, 0x7C, 0x72, 0x7B, 0x00, 0x01, 0x02, 0x03, 0x1F, 0x7E, 0x35, 0x71, 0x87, 0x0b, 0x17, 0x23, 0x2f, 0x0a, 0x16, 0x22, 0x2e, 0x3a, 0x46, 0x52, 0x5e, 0x6a, 0x76, 0x3b, 0x47, 0x53, 0x5f, 0x6b, 0x77, 0x83, 0x8f, 0xFF, //> Include COUNT as nonexistant key. 0xFF //> Include MISSING as nonexistant key. }; #define K_HEIGHT 7 #define K65_WIDTH 18 #define K70_WIDTH 22 #define K95_WIDTH 25 enum ckrgb_key key_matrix_us_k65[K_HEIGHT][K65_WIDTH] = { {CKRGB_KEY_MISSING, CKRGB_KEY_MISSING, CKRGB_KEY_MISSING, CKRGB_KEY_MISSING, CKRGB_KEY_MISSING, CKRGB_KEY_MISSING, CKRGB_KEY_MISSING, CKRGB_KEY_MISSING, CKRGB_KEY_MISSING, CKRGB_KEY_MISSING, CKRGB_KEY_MISSING, CKRGB_KEY_BRIGHTNESS, CKRGB_KEY_MUTE, CKRGB_KEY_VOLUMEDOWN, CKRGB_KEY_VOLUMEUP, CKRGB_KEY_WINLOCK, CKRGB_KEY_MISSING, CKRGB_KEY_MISSING}, {CKRGB_KEY_ESCAPE, CKRGB_KEY_MISSING, CKRGB_KEY_F1, CKRGB_KEY_F2, CKRGB_KEY_F3, CKRGB_KEY_F4, CKRGB_KEY_F5, CKRGB_KEY_F6, CKRGB_KEY_F7, CKRGB_KEY_F8, CKRGB_KEY_MISSING, CKRGB_KEY_F9, CKRGB_KEY_F10, CKRGB_KEY_F11, CKRGB_KEY_F12, CKRGB_KEY_PRINTSCREEN, CKRGB_KEY_SCOLLLOCK, CKRGB_KEY_PAUSEBREAK}, {CKRGB_KEY_TILDE, CKRGB_KEY_NUM1, CKRGB_KEY_NUM2, CKRGB_KEY_NUM3, CKRGB_KEY_NUM4, CKRGB_KEY_NUM5, CKRGB_KEY_NUM6, CKRGB_KEY_NUM7, CKRGB_KEY_NUM8, CKRGB_KEY_NUM9, CKRGB_KEY_NUM0, CKRGB_KEY_MINUS, CKRGB_KEY_EQUALS, CKRGB_KEY_BACKSPACE, CKRGB_KEY_BACKSPACE, CKRGB_KEY_INSERT, CKRGB_KEY_HOME, CKRGB_KEY_PAGEUP}, {CKRGB_KEY_TAB, CKRGB_KEY_Q, CKRGB_KEY_W, CKRGB_KEY_E, CKRGB_KEY_R, CKRGB_KEY_T, CKRGB_KEY_Y, CKRGB_KEY_U, CKRGB_KEY_I, CKRGB_KEY_O, CKRGB_KEY_P, CKRGB_KEY_LBRACKET, CKRGB_KEY_RBRACKET, CKRGB_KEY_MISSING, CKRGB_KEY_BACKSLASH, CKRGB_KEY_DELETE, CKRGB_KEY_END, CKRGB_KEY_PAGEDOWN}, {CKRGB_KEY_CAPSLOCK, CKRGB_KEY_A, CKRGB_KEY_S, CKRGB_KEY_D, CKRGB_KEY_F, CKRGB_KEY_G, CKRGB_KEY_H, CKRGB_KEY_J, CKRGB_KEY_K, CKRGB_KEY_L, CKRGB_KEY_SEMICOLON, CKRGB_KEY_QUOTE, CKRGB_KEY_ENTER, CKRGB_KEY_ENTER, CKRGB_KEY_ENTER, CKRGB_KEY_MISSING, CKRGB_KEY_MISSING, CKRGB_KEY_MISSING}, {CKRGB_KEY_LSHIFT, CKRGB_KEY_MISSING, CKRGB_KEY_Z, CKRGB_KEY_X, CKRGB_KEY_C, CKRGB_KEY_V, CKRGB_KEY_B, CKRGB_KEY_N, CKRGB_KEY_M, CKRGB_KEY_COMMA, CKRGB_KEY_PERIOD, CKRGB_KEY_FORWARDSLASH, CKRGB_KEY_RSHIFT, CKRGB_KEY_RSHIFT, CKRGB_KEY_RSHIFT, CKRGB_KEY_MISSING, CKRGB_KEY_ARROWUP, CKRGB_KEY_MISSING}, {CKRGB_KEY_LCTRL, CKRGB_KEY_LSYSTEM, CKRGB_KEY_LALT, CKRGB_KEY_LALT, CKRGB_KEY_MISSING, CKRGB_KEY_SPACE, CKRGB_KEY_SPACE, CKRGB_KEY_SPACE, CKRGB_KEY_MISSING, CKRGB_KEY_MISSING, CKRGB_KEY_RALT, CKRGB_KEY_RSYSTEM, CKRGB_KEY_CONTEXTMENU, CKRGB_KEY_RCTRL, CKRGB_KEY_RCTRL, CKRGB_KEY_ARROWLEFT, CKRGB_KEY_ARROWDOWN, CKRGB_KEY_ARROWRIGHT} }; enum ckrgb_key key_matrix_us_k70[K_HEIGHT][K70_WIDTH] = { {CKRGB_KEY_MISSING, CKRGB_KEY_MISSING, CKRGB_KEY_MISSING, CKRGB_KEY_MISSING, CKRGB_KEY_MISSING, CKRGB_KEY_MISSING, CKRGB_KEY_MISSING, CKRGB_KEY_MISSING, CKRGB_KEY_MISSING, CKRGB_KEY_MISSING, CKRGB_KEY_MISSING, CKRGB_KEY_MISSING, CKRGB_KEY_MISSING, CKRGB_KEY_MISSING, CKRGB_KEY_MISSING, CKRGB_KEY_BRIGHTNESS, CKRGB_KEY_WINLOCK, CKRGB_KEY_MISSING, CKRGB_KEY_MISSING, CKRGB_KEY_MUTE, CKRGB_KEY_MISSING, CKRGB_KEY_MISSING}, {CKRGB_KEY_ESCAPE, CKRGB_KEY_MISSING, CKRGB_KEY_F1, CKRGB_KEY_F2, CKRGB_KEY_F3, CKRGB_KEY_F4, CKRGB_KEY_F5, CKRGB_KEY_F6, CKRGB_KEY_F7, CKRGB_KEY_F8, CKRGB_KEY_MISSING, CKRGB_KEY_F9, CKRGB_KEY_F10, CKRGB_KEY_F11, CKRGB_KEY_F12, CKRGB_KEY_PRINTSCREEN, CKRGB_KEY_SCOLLLOCK, CKRGB_KEY_PAUSEBREAK, CKRGB_KEY_MEDIASTOP, CKRGB_KEY_MEDIAPREV, CKRGB_KEY_MEDIAPLAYPAUSE, CKRGB_KEY_MEDIANEXT}, {CKRGB_KEY_TILDE, CKRGB_KEY_NUM1, CKRGB_KEY_NUM2, CKRGB_KEY_NUM3, CKRGB_KEY_NUM4, CKRGB_KEY_NUM5, CKRGB_KEY_NUM6, CKRGB_KEY_NUM7, CKRGB_KEY_NUM8, CKRGB_KEY_NUM9, CKRGB_KEY_NUM0, CKRGB_KEY_MINUS, CKRGB_KEY_EQUALS, CKRGB_KEY_BACKSPACE, CKRGB_KEY_BACKSPACE, CKRGB_KEY_INSERT, CKRGB_KEY_HOME, CKRGB_KEY_PAGEUP, CKRGB_KEY_NUMLOCK, CKRGB_KEY_NUMPADDIVIDE, CKRGB_KEY_NUMPADMULTIPLY, CKRGB_KEY_NUMPADMINUS}, {CKRGB_KEY_TAB, CKRGB_KEY_Q, CKRGB_KEY_W, CKRGB_KEY_E, CKRGB_KEY_R, CKRGB_KEY_T, CKRGB_KEY_Y, CKRGB_KEY_U, CKRGB_KEY_I, CKRGB_KEY_O, CKRGB_KEY_P, CKRGB_KEY_LBRACKET, CKRGB_KEY_RBRACKET, CKRGB_KEY_MISSING, CKRGB_KEY_BACKSLASH, CKRGB_KEY_DELETE, CKRGB_KEY_END, CKRGB_KEY_PAGEDOWN, CKRGB_KEY_NUMPAD7, CKRGB_KEY_NUMPAD8, CKRGB_KEY_NUMPAD9, CKRGB_KEY_NUMPADPLUS}, {CKRGB_KEY_CAPSLOCK, CKRGB_KEY_A, CKRGB_KEY_S, CKRGB_KEY_D, CKRGB_KEY_F, CKRGB_KEY_G, CKRGB_KEY_H, CKRGB_KEY_J, CKRGB_KEY_K, CKRGB_KEY_L, CKRGB_KEY_SEMICOLON, CKRGB_KEY_QUOTE, CKRGB_KEY_ENTER, CKRGB_KEY_ENTER, CKRGB_KEY_ENTER, CKRGB_KEY_MISSING, CKRGB_KEY_MISSING, CKRGB_KEY_MISSING, CKRGB_KEY_NUMPAD4, CKRGB_KEY_NUMPAD5, CKRGB_KEY_NUMPAD6, CKRGB_KEY_NUMPADPLUS}, {CKRGB_KEY_LSHIFT, CKRGB_KEY_MISSING, CKRGB_KEY_Z, CKRGB_KEY_X, CKRGB_KEY_C, CKRGB_KEY_V, CKRGB_KEY_B, CKRGB_KEY_N, CKRGB_KEY_M, CKRGB_KEY_COMMA, CKRGB_KEY_PERIOD, CKRGB_KEY_FORWARDSLASH, CKRGB_KEY_RSHIFT, CKRGB_KEY_RSHIFT, CKRGB_KEY_RSHIFT, CKRGB_KEY_MISSING, CKRGB_KEY_ARROWUP, CKRGB_KEY_MISSING, CKRGB_KEY_NUMPAD1, CKRGB_KEY_NUMPAD2, CKRGB_KEY_NUMPAD3, CKRGB_KEY_NUMPADENTER}, {CKRGB_KEY_LCTRL, CKRGB_KEY_LSYSTEM, CKRGB_KEY_LALT, CKRGB_KEY_LALT, CKRGB_KEY_MISSING, CKRGB_KEY_SPACE, CKRGB_KEY_SPACE, CKRGB_KEY_SPACE, CKRGB_KEY_MISSING, CKRGB_KEY_MISSING, CKRGB_KEY_RALT, CKRGB_KEY_RSYSTEM, CKRGB_KEY_CONTEXTMENU, CKRGB_KEY_RCTRL, CKRGB_KEY_RCTRL, CKRGB_KEY_ARROWLEFT, CKRGB_KEY_ARROWDOWN, CKRGB_KEY_ARROWRIGHT, CKRGB_KEY_NUMPAD0, CKRGB_KEY_NUMPAD0, CKRGB_KEY_NUMPADDECIMAL, CKRGB_KEY_NUMPADENTER} }; enum ckrgb_key key_matrix_us_k95[K_HEIGHT][K95_WIDTH] = { {CKRGB_KEY_MISSING, CKRGB_KEY_MISSING, CKRGB_KEY_MISSING, CKRGB_KEY_MACRORECORD, CKRGB_KEY_MACROMODE1, CKRGB_KEY_MACROMODE2, CKRGB_KEY_MACROMODE3, CKRGB_KEY_MISSING, CKRGB_KEY_MISSING, CKRGB_KEY_MISSING, CKRGB_KEY_MISSING, CKRGB_KEY_MISSING, CKRGB_KEY_MISSING, CKRGB_KEY_MISSING, CKRGB_KEY_MISSING, CKRGB_KEY_MISSING, CKRGB_KEY_MISSING, CKRGB_KEY_MISSING, CKRGB_KEY_BRIGHTNESS, CKRGB_KEY_WINLOCK, CKRGB_KEY_MISSING, CKRGB_KEY_MISSING, CKRGB_KEY_MUTE, CKRGB_KEY_MISSING, CKRGB_KEY_MISSING}, {CKRGB_KEY_G1, CKRGB_KEY_G2, CKRGB_KEY_G3, CKRGB_KEY_ESCAPE, CKRGB_KEY_MISSING, CKRGB_KEY_F1, CKRGB_KEY_F2, CKRGB_KEY_F3, CKRGB_KEY_F4, CKRGB_KEY_F5, CKRGB_KEY_F6, CKRGB_KEY_F7, CKRGB_KEY_F8, CKRGB_KEY_MISSING, CKRGB_KEY_F9, CKRGB_KEY_F10, CKRGB_KEY_F11, CKRGB_KEY_F12, CKRGB_KEY_PRINTSCREEN, CKRGB_KEY_SCOLLLOCK, CKRGB_KEY_PAUSEBREAK, CKRGB_KEY_MEDIASTOP, CKRGB_KEY_MEDIAPREV, CKRGB_KEY_MEDIAPLAYPAUSE, CKRGB_KEY_MEDIANEXT}, {CKRGB_KEY_G4, CKRGB_KEY_G5, CKRGB_KEY_G6, CKRGB_KEY_TILDE, CKRGB_KEY_NUM1, CKRGB_KEY_NUM2, CKRGB_KEY_NUM3, CKRGB_KEY_NUM4, CKRGB_KEY_NUM5, CKRGB_KEY_NUM6, CKRGB_KEY_NUM7, CKRGB_KEY_NUM8, CKRGB_KEY_NUM9, CKRGB_KEY_NUM0, CKRGB_KEY_MINUS, CKRGB_KEY_EQUALS, CKRGB_KEY_BACKSPACE, CKRGB_KEY_BACKSPACE, CKRGB_KEY_INSERT, CKRGB_KEY_HOME, CKRGB_KEY_PAGEUP, CKRGB_KEY_NUMLOCK, CKRGB_KEY_NUMPADDIVIDE, CKRGB_KEY_NUMPADMULTIPLY, CKRGB_KEY_NUMPADMINUS}, {CKRGB_KEY_G7, CKRGB_KEY_G8, CKRGB_KEY_G9, CKRGB_KEY_TAB, CKRGB_KEY_Q, CKRGB_KEY_W, CKRGB_KEY_E, CKRGB_KEY_R, CKRGB_KEY_T, CKRGB_KEY_Y, CKRGB_KEY_U, CKRGB_KEY_I, CKRGB_KEY_O, CKRGB_KEY_P, CKRGB_KEY_LBRACKET, CKRGB_KEY_RBRACKET, CKRGB_KEY_MISSING, CKRGB_KEY_BACKSLASH, CKRGB_KEY_DELETE, CKRGB_KEY_END, CKRGB_KEY_PAGEDOWN, CKRGB_KEY_NUMPAD7, CKRGB_KEY_NUMPAD8, CKRGB_KEY_NUMPAD9, CKRGB_KEY_NUMPADPLUS}, {CKRGB_KEY_G10, CKRGB_KEY_G11, CKRGB_KEY_G12, CKRGB_KEY_CAPSLOCK, CKRGB_KEY_A, CKRGB_KEY_S, CKRGB_KEY_D, CKRGB_KEY_F, CKRGB_KEY_G, CKRGB_KEY_H, CKRGB_KEY_J, CKRGB_KEY_K, CKRGB_KEY_L, CKRGB_KEY_SEMICOLON, CKRGB_KEY_QUOTE, CKRGB_KEY_ENTER, CKRGB_KEY_ENTER, CKRGB_KEY_ENTER, CKRGB_KEY_MISSING, CKRGB_KEY_MISSING, CKRGB_KEY_MISSING, CKRGB_KEY_NUMPAD4, CKRGB_KEY_NUMPAD5, CKRGB_KEY_NUMPAD6, CKRGB_KEY_NUMPADPLUS}, {CKRGB_KEY_G13, CKRGB_KEY_G14, CKRGB_KEY_G15, CKRGB_KEY_LSHIFT, CKRGB_KEY_MISSING, CKRGB_KEY_Z, CKRGB_KEY_X, CKRGB_KEY_C, CKRGB_KEY_V, CKRGB_KEY_B, CKRGB_KEY_N, CKRGB_KEY_M, CKRGB_KEY_COMMA, CKRGB_KEY_PERIOD, CKRGB_KEY_FORWARDSLASH, CKRGB_KEY_RSHIFT, CKRGB_KEY_RSHIFT, CKRGB_KEY_RSHIFT, CKRGB_KEY_MISSING, CKRGB_KEY_ARROWUP, CKRGB_KEY_MISSING, CKRGB_KEY_NUMPAD1, CKRGB_KEY_NUMPAD2, CKRGB_KEY_NUMPAD3, CKRGB_KEY_NUMPADENTER}, {CKRGB_KEY_G16, CKRGB_KEY_G17, CKRGB_KEY_G18, CKRGB_KEY_LCTRL, CKRGB_KEY_LSYSTEM, CKRGB_KEY_LALT, CKRGB_KEY_LALT, CKRGB_KEY_MISSING, CKRGB_KEY_SPACE, CKRGB_KEY_SPACE, CKRGB_KEY_SPACE, CKRGB_KEY_MISSING, CKRGB_KEY_MISSING, CKRGB_KEY_RALT, CKRGB_KEY_RSYSTEM, CKRGB_KEY_CONTEXTMENU, CKRGB_KEY_RCTRL, CKRGB_KEY_RCTRL, CKRGB_KEY_ARROWLEFT, CKRGB_KEY_ARROWDOWN, CKRGB_KEY_ARROWRIGHT, CKRGB_KEY_NUMPAD0, CKRGB_KEY_NUMPAD0, CKRGB_KEY_NUMPADDECIMAL, CKRGB_KEY_NUMPADENTER} }; enum ckrgb_key key_matrix_uk_k65[K_HEIGHT][K65_WIDTH] = { {CKRGB_KEY_MISSING, CKRGB_KEY_MISSING, CKRGB_KEY_MISSING, CKRGB_KEY_MISSING, CKRGB_KEY_MISSING, CKRGB_KEY_MISSING, CKRGB_KEY_MISSING, CKRGB_KEY_MISSING, CKRGB_KEY_MISSING, CKRGB_KEY_MISSING, CKRGB_KEY_MISSING, CKRGB_KEY_BRIGHTNESS, CKRGB_KEY_MUTE, CKRGB_KEY_VOLUMEDOWN, CKRGB_KEY_VOLUMEUP, CKRGB_KEY_WINLOCK, CKRGB_KEY_MISSING, CKRGB_KEY_MISSING}, {CKRGB_KEY_ESCAPE, CKRGB_KEY_MISSING, CKRGB_KEY_F1, CKRGB_KEY_F2, CKRGB_KEY_F3, CKRGB_KEY_F4, CKRGB_KEY_F5, CKRGB_KEY_F6, CKRGB_KEY_F7, CKRGB_KEY_F8, CKRGB_KEY_MISSING, CKRGB_KEY_F9, CKRGB_KEY_F10, CKRGB_KEY_F11, CKRGB_KEY_F12, CKRGB_KEY_PRINTSCREEN, CKRGB_KEY_SCOLLLOCK, CKRGB_KEY_PAUSEBREAK}, {CKRGB_KEY_TILDE, CKRGB_KEY_NUM1, CKRGB_KEY_NUM2, CKRGB_KEY_NUM3, CKRGB_KEY_NUM4, CKRGB_KEY_NUM5, CKRGB_KEY_NUM6, CKRGB_KEY_NUM7, CKRGB_KEY_NUM8, CKRGB_KEY_NUM9, CKRGB_KEY_NUM0, CKRGB_KEY_MINUS, CKRGB_KEY_EQUALS, CKRGB_KEY_BACKSPACE, CKRGB_KEY_BACKSPACE, CKRGB_KEY_INSERT, CKRGB_KEY_HOME, CKRGB_KEY_PAGEUP}, {CKRGB_KEY_TAB, CKRGB_KEY_Q, CKRGB_KEY_W, CKRGB_KEY_E, CKRGB_KEY_R, CKRGB_KEY_T, CKRGB_KEY_Y, CKRGB_KEY_U, CKRGB_KEY_I, CKRGB_KEY_O, CKRGB_KEY_P, CKRGB_KEY_LBRACKET, CKRGB_KEY_RBRACKET, CKRGB_KEY_ENTER, CKRGB_KEY_ENTER, CKRGB_KEY_DELETE, CKRGB_KEY_END, CKRGB_KEY_PAGEDOWN}, {CKRGB_KEY_CAPSLOCK, CKRGB_KEY_A, CKRGB_KEY_S, CKRGB_KEY_D, CKRGB_KEY_F, CKRGB_KEY_G, CKRGB_KEY_H, CKRGB_KEY_J, CKRGB_KEY_K, CKRGB_KEY_L, CKRGB_KEY_SEMICOLON, CKRGB_KEY_QUOTE, CKRGB_KEY_HASH, CKRGB_KEY_ENTER, CKRGB_KEY_ENTER, CKRGB_KEY_MISSING, CKRGB_KEY_MISSING, CKRGB_KEY_MISSING}, {CKRGB_KEY_LSHIFT, CKRGB_KEY_BACKSLASH, CKRGB_KEY_Z, CKRGB_KEY_X, CKRGB_KEY_C, CKRGB_KEY_V, CKRGB_KEY_B, CKRGB_KEY_N, CKRGB_KEY_M, CKRGB_KEY_COMMA, CKRGB_KEY_PERIOD, CKRGB_KEY_FORWARDSLASH, CKRGB_KEY_RSHIFT, CKRGB_KEY_RSHIFT, CKRGB_KEY_RSHIFT, CKRGB_KEY_MISSING, CKRGB_KEY_ARROWUP, CKRGB_KEY_MISSING}, {CKRGB_KEY_LCTRL, CKRGB_KEY_LSYSTEM, CKRGB_KEY_LALT, CKRGB_KEY_LALT, CKRGB_KEY_MISSING, CKRGB_KEY_SPACE, CKRGB_KEY_SPACE, CKRGB_KEY_SPACE, CKRGB_KEY_MISSING, CKRGB_KEY_MISSING, CKRGB_KEY_RALT, CKRGB_KEY_RSYSTEM, CKRGB_KEY_CONTEXTMENU, CKRGB_KEY_RCTRL, CKRGB_KEY_RCTRL, CKRGB_KEY_ARROWLEFT, CKRGB_KEY_ARROWDOWN, CKRGB_KEY_ARROWRIGHT} }; enum ckrgb_key key_matrix_uk_k70[K_HEIGHT][K70_WIDTH] = { {CKRGB_KEY_MISSING, CKRGB_KEY_MISSING, CKRGB_KEY_MISSING, CKRGB_KEY_MISSING, CKRGB_KEY_MISSING, CKRGB_KEY_MISSING, CKRGB_KEY_MISSING, CKRGB_KEY_MISSING, CKRGB_KEY_MISSING, CKRGB_KEY_MISSING, CKRGB_KEY_MISSING, CKRGB_KEY_MISSING, CKRGB_KEY_MISSING, CKRGB_KEY_MISSING, CKRGB_KEY_MISSING, CKRGB_KEY_BRIGHTNESS, CKRGB_KEY_WINLOCK, CKRGB_KEY_MISSING, CKRGB_KEY_MISSING, CKRGB_KEY_MUTE, CKRGB_KEY_MISSING, CKRGB_KEY_MISSING}, {CKRGB_KEY_ESCAPE, CKRGB_KEY_MISSING, CKRGB_KEY_F1, CKRGB_KEY_F2, CKRGB_KEY_F3, CKRGB_KEY_F4, CKRGB_KEY_F5, CKRGB_KEY_F6, CKRGB_KEY_F7, CKRGB_KEY_F8, CKRGB_KEY_MISSING, CKRGB_KEY_F9, CKRGB_KEY_F10, CKRGB_KEY_F11, CKRGB_KEY_F12, CKRGB_KEY_PRINTSCREEN, CKRGB_KEY_SCOLLLOCK, CKRGB_KEY_PAUSEBREAK, CKRGB_KEY_MEDIASTOP, CKRGB_KEY_MEDIAPREV, CKRGB_KEY_MEDIAPLAYPAUSE, CKRGB_KEY_MEDIANEXT}, {CKRGB_KEY_TILDE, CKRGB_KEY_NUM1, CKRGB_KEY_NUM2, CKRGB_KEY_NUM3, CKRGB_KEY_NUM4, CKRGB_KEY_NUM5, CKRGB_KEY_NUM6, CKRGB_KEY_NUM7, CKRGB_KEY_NUM8, CKRGB_KEY_NUM9, CKRGB_KEY_NUM0, CKRGB_KEY_MINUS, CKRGB_KEY_EQUALS, CKRGB_KEY_BACKSPACE, CKRGB_KEY_BACKSPACE, CKRGB_KEY_INSERT, CKRGB_KEY_HOME, CKRGB_KEY_PAGEUP, CKRGB_KEY_NUMLOCK, CKRGB_KEY_NUMPADDIVIDE, CKRGB_KEY_NUMPADMULTIPLY, CKRGB_KEY_NUMPADMINUS}, {CKRGB_KEY_TAB, CKRGB_KEY_Q, CKRGB_KEY_W, CKRGB_KEY_E, CKRGB_KEY_R, CKRGB_KEY_T, CKRGB_KEY_Y, CKRGB_KEY_U, CKRGB_KEY_I, CKRGB_KEY_O, CKRGB_KEY_P, CKRGB_KEY_LBRACKET, CKRGB_KEY_RBRACKET, CKRGB_KEY_ENTER, CKRGB_KEY_ENTER, CKRGB_KEY_DELETE, CKRGB_KEY_END, CKRGB_KEY_PAGEDOWN, CKRGB_KEY_NUMPAD7, CKRGB_KEY_NUMPAD8, CKRGB_KEY_NUMPAD9, CKRGB_KEY_NUMPADPLUS}, {CKRGB_KEY_CAPSLOCK, CKRGB_KEY_A, CKRGB_KEY_S, CKRGB_KEY_D, CKRGB_KEY_F, CKRGB_KEY_G, CKRGB_KEY_H, CKRGB_KEY_J, CKRGB_KEY_K, CKRGB_KEY_L, CKRGB_KEY_SEMICOLON, CKRGB_KEY_QUOTE, CKRGB_KEY_HASH, CKRGB_KEY_ENTER, CKRGB_KEY_ENTER, CKRGB_KEY_MISSING, CKRGB_KEY_MISSING, CKRGB_KEY_MISSING, CKRGB_KEY_NUMPAD4, CKRGB_KEY_NUMPAD5, CKRGB_KEY_NUMPAD6, CKRGB_KEY_NUMPADPLUS}, {CKRGB_KEY_LSHIFT, CKRGB_KEY_BACKSLASH, CKRGB_KEY_Z, CKRGB_KEY_X, CKRGB_KEY_C, CKRGB_KEY_V, CKRGB_KEY_B, CKRGB_KEY_N, CKRGB_KEY_M, CKRGB_KEY_COMMA, CKRGB_KEY_PERIOD, CKRGB_KEY_FORWARDSLASH, CKRGB_KEY_RSHIFT, CKRGB_KEY_RSHIFT, CKRGB_KEY_RSHIFT, CKRGB_KEY_MISSING, CKRGB_KEY_ARROWUP, CKRGB_KEY_MISSING, CKRGB_KEY_NUMPAD1, CKRGB_KEY_NUMPAD2, CKRGB_KEY_NUMPAD3, CKRGB_KEY_NUMPADENTER}, {CKRGB_KEY_LCTRL, CKRGB_KEY_LSYSTEM, CKRGB_KEY_LALT, CKRGB_KEY_LALT, CKRGB_KEY_MISSING, CKRGB_KEY_SPACE, CKRGB_KEY_SPACE, CKRGB_KEY_SPACE, CKRGB_KEY_MISSING, CKRGB_KEY_MISSING, CKRGB_KEY_RALT, CKRGB_KEY_RSYSTEM, CKRGB_KEY_CONTEXTMENU, CKRGB_KEY_RCTRL, CKRGB_KEY_RCTRL, CKRGB_KEY_ARROWLEFT, CKRGB_KEY_ARROWDOWN, CKRGB_KEY_ARROWRIGHT, CKRGB_KEY_NUMPAD0, CKRGB_KEY_NUMPAD0, CKRGB_KEY_NUMPADDECIMAL, CKRGB_KEY_NUMPADENTER} }; enum ckrgb_key key_matrix_uk_k95[K_HEIGHT][K95_WIDTH] = { {CKRGB_KEY_MISSING, CKRGB_KEY_MISSING, CKRGB_KEY_MISSING, CKRGB_KEY_MACRORECORD, CKRGB_KEY_MACROMODE1, CKRGB_KEY_MACROMODE2, CKRGB_KEY_MACROMODE3, CKRGB_KEY_MISSING, CKRGB_KEY_MISSING, CKRGB_KEY_MISSING, CKRGB_KEY_MISSING, CKRGB_KEY_MISSING, CKRGB_KEY_MISSING, CKRGB_KEY_MISSING, CKRGB_KEY_MISSING, CKRGB_KEY_MISSING, CKRGB_KEY_MISSING, CKRGB_KEY_MISSING, CKRGB_KEY_BRIGHTNESS, CKRGB_KEY_WINLOCK, CKRGB_KEY_MISSING, CKRGB_KEY_MISSING, CKRGB_KEY_MUTE, CKRGB_KEY_MISSING, CKRGB_KEY_MISSING}, {CKRGB_KEY_G1, CKRGB_KEY_G2, CKRGB_KEY_G3, CKRGB_KEY_ESCAPE, CKRGB_KEY_MISSING, CKRGB_KEY_F1, CKRGB_KEY_F2, CKRGB_KEY_F3, CKRGB_KEY_F4, CKRGB_KEY_F5, CKRGB_KEY_F6, CKRGB_KEY_F7, CKRGB_KEY_F8, CKRGB_KEY_MISSING, CKRGB_KEY_F9, CKRGB_KEY_F10, CKRGB_KEY_F11, CKRGB_KEY_F12, CKRGB_KEY_PRINTSCREEN, CKRGB_KEY_SCOLLLOCK, CKRGB_KEY_PAUSEBREAK, CKRGB_KEY_MEDIASTOP, CKRGB_KEY_MEDIAPREV, CKRGB_KEY_MEDIAPLAYPAUSE, CKRGB_KEY_MEDIANEXT}, {CKRGB_KEY_G4, CKRGB_KEY_G5, CKRGB_KEY_G6, CKRGB_KEY_TILDE, CKRGB_KEY_NUM1, CKRGB_KEY_NUM2, CKRGB_KEY_NUM3, CKRGB_KEY_NUM4, CKRGB_KEY_NUM5, CKRGB_KEY_NUM6, CKRGB_KEY_NUM7, CKRGB_KEY_NUM8, CKRGB_KEY_NUM9, CKRGB_KEY_NUM0, CKRGB_KEY_MINUS, CKRGB_KEY_EQUALS, CKRGB_KEY_BACKSPACE, CKRGB_KEY_BACKSPACE, CKRGB_KEY_INSERT, CKRGB_KEY_HOME, CKRGB_KEY_PAGEUP, CKRGB_KEY_NUMLOCK, CKRGB_KEY_NUMPADDIVIDE, CKRGB_KEY_NUMPADMULTIPLY, CKRGB_KEY_NUMPADMINUS}, {CKRGB_KEY_G7, CKRGB_KEY_G8, CKRGB_KEY_G9, CKRGB_KEY_TAB, CKRGB_KEY_Q, CKRGB_KEY_W, CKRGB_KEY_E, CKRGB_KEY_R, CKRGB_KEY_T, CKRGB_KEY_Y, CKRGB_KEY_U, CKRGB_KEY_I, CKRGB_KEY_O, CKRGB_KEY_P, CKRGB_KEY_LBRACKET, CKRGB_KEY_RBRACKET, CKRGB_KEY_ENTER, CKRGB_KEY_ENTER, CKRGB_KEY_DELETE, CKRGB_KEY_END, CKRGB_KEY_PAGEDOWN, CKRGB_KEY_NUMPAD7, CKRGB_KEY_NUMPAD8, CKRGB_KEY_NUMPAD9, CKRGB_KEY_NUMPADPLUS}, {CKRGB_KEY_G10, CKRGB_KEY_G11, CKRGB_KEY_G12, CKRGB_KEY_CAPSLOCK, CKRGB_KEY_A, CKRGB_KEY_S, CKRGB_KEY_D, CKRGB_KEY_F, CKRGB_KEY_G, CKRGB_KEY_H, CKRGB_KEY_J, CKRGB_KEY_K, CKRGB_KEY_L, CKRGB_KEY_SEMICOLON, CKRGB_KEY_QUOTE, CKRGB_KEY_HASH, CKRGB_KEY_ENTER, CKRGB_KEY_ENTER, CKRGB_KEY_MISSING, CKRGB_KEY_MISSING, CKRGB_KEY_MISSING, CKRGB_KEY_NUMPAD4, CKRGB_KEY_NUMPAD5, CKRGB_KEY_NUMPAD6, CKRGB_KEY_NUMPADPLUS}, {CKRGB_KEY_G13, CKRGB_KEY_G14, CKRGB_KEY_G15, CKRGB_KEY_LSHIFT, CKRGB_KEY_BACKSLASH, CKRGB_KEY_Z, CKRGB_KEY_X, CKRGB_KEY_C, CKRGB_KEY_V, CKRGB_KEY_B, CKRGB_KEY_N, CKRGB_KEY_M, CKRGB_KEY_COMMA, CKRGB_KEY_PERIOD, CKRGB_KEY_FORWARDSLASH, CKRGB_KEY_RSHIFT, CKRGB_KEY_RSHIFT, CKRGB_KEY_RSHIFT, CKRGB_KEY_MISSING, CKRGB_KEY_ARROWUP, CKRGB_KEY_MISSING, CKRGB_KEY_NUMPAD1, CKRGB_KEY_NUMPAD2, CKRGB_KEY_NUMPAD3, CKRGB_KEY_NUMPADENTER}, {CKRGB_KEY_G16, CKRGB_KEY_G17, CKRGB_KEY_G18, CKRGB_KEY_LCTRL, CKRGB_KEY_LSYSTEM, CKRGB_KEY_LALT, CKRGB_KEY_LALT, CKRGB_KEY_MISSING, CKRGB_KEY_SPACE, CKRGB_KEY_SPACE, CKRGB_KEY_SPACE, CKRGB_KEY_MISSING, CKRGB_KEY_MISSING, CKRGB_KEY_RALT, CKRGB_KEY_RSYSTEM, CKRGB_KEY_CONTEXTMENU, CKRGB_KEY_RCTRL, CKRGB_KEY_RCTRL, CKRGB_KEY_ARROWLEFT, CKRGB_KEY_ARROWDOWN, CKRGB_KEY_ARROWRIGHT, CKRGB_KEY_NUMPAD0, CKRGB_KEY_NUMPAD0, CKRGB_KEY_NUMPADDECIMAL, CKRGB_KEY_NUMPADENTER} }; ckrgb_keyboard* ckrgb_keyboard_new(libusb_device* device, enum ckrgb_keyboard_type kt) { int i = sizeof(ckrgb_keyboard); ckrgb_keyboard* kb = (ckrgb_keyboard*)malloc(sizeof(ckrgb_keyboard)); memset(kb, 0, sizeof(ckrgb_keyboard)); if (libusb_open(device, &kb->pHandle)) { free(kb); return NULL; } kb->eType = kt; kb->eKeyMap = CKRGB_KEYMAP_US; kb->height = 7; switch(kt) { case CKRGB_KEYBOARD_TYPE_K65: kb->width = 18; break; case CKRGB_KEYBOARD_TYPE_K70: kb->width = 22; break; case CKRGB_KEYBOARD_TYPE_K95: kb->width = 25; break; } return kb; } void ckrgb_keyboard_delete(ckrgb_keyboard* kb) { if (kb->bClaimed) libusb_release_interface(kb->pHandle, 0); libusb_close(kb->pHandle); free(kb); } ckrgb_error ckrgb_keyboard_claim(ckrgb_keyboard* kb) { int err = libusb_claim_interface(kb->pHandle, 3); if (err) { switch(err) { case LIBUSB_ERROR_NOT_FOUND: return CKRGB_ERROR_INTERFACE_NOT_FOUND; case LIBUSB_ERROR_BUSY: return CKRGB_ERROR_DEVICE_BUSY; case LIBUSB_ERROR_NO_DEVICE: return CKRGB_ERROR_NO_DEVICE; default: return CKRGB_ERROR_UNKNOWN; } } else { kb->bClaimed = CKRGB_TRUE; } return CKRGB_ERROR_SUCCESS; } ckrgb_error ckrgb_keyboard_unclaim(ckrgb_keyboard* kb) { int err = libusb_release_interface(kb->pHandle, 0); if (err) { switch(err) { case LIBUSB_ERROR_NOT_FOUND: return CKRGB_ERROR_INTERFACE_NOT_FOUND; case LIBUSB_ERROR_BUSY: return CKRGB_ERROR_DEVICE_BUSY; case LIBUSB_ERROR_NO_DEVICE: return CKRGB_ERROR_NO_DEVICE; default: return CKRGB_ERROR_UNKNOWN; } } else { kb->bClaimed = CKRGB_FALSE; } return err; } void get_key_pos_us_k65(enum ckrgb_key key, int* x, int* y) { for (int iy = 0; iy < K_HEIGHT; ++iy) for (int ix = 0; ix < K65_WIDTH; ++ix) if (key_matrix_us_k65[iy][ix] == key) *x = ix, *y = iy; } void get_key_pos_us_k70(enum ckrgb_key key, int* x, int* y) { for (int iy = 0; iy < K_HEIGHT; ++iy) for (int ix = 0; ix < K70_WIDTH; ++ix) if (key_matrix_us_k70[iy][ix] == key) *x = ix, *y = iy; } void get_key_pos_us_k95(enum ckrgb_key key, int* x, int* y) { for (int iy = 0; iy < K_HEIGHT; ++iy) for (int ix = 0; ix < K95_WIDTH; ++ix) if (key_matrix_us_k95[iy][ix] == key) *x = ix, *y = iy; } void get_key_pos_uk_k65(enum ckrgb_key key, int* x, int* y) { for (int iy = 0; iy < K_HEIGHT; ++iy) for (int ix = 0; ix < K65_WIDTH; ++ix) if (key_matrix_uk_k65[iy][ix] == key) *x = ix, *y = iy; } void get_key_pos_uk_k70(enum ckrgb_key key, int* x, int* y) { for (int iy = 0; iy < K_HEIGHT; ++iy) for (int ix = 0; ix < K70_WIDTH; ++ix) if (key_matrix_uk_k70[iy][ix] == key) *x = ix, *y = iy; } void get_key_pos_uk_k95(enum ckrgb_key key, int* x, int* y) { for (int iy = 0; iy < K_HEIGHT; ++iy) for (int ix = 0; ix < K95_WIDTH; ++ix) if (key_matrix_uk_k95[iy][ix] == key) *x = ix, *y = iy; } void ckrgb_keyboard_key_pos(enum ckrgb_keyboard_type kt, enum ckrgb_keymap km, enum ckrgb_key key, int* x, int* y) { if (km == CKRGB_KEYMAP_US) { switch (kt) { case CKRGB_KEYBOARD_TYPE_K65: get_key_pos_us_k65(key, x, y); break; case CKRGB_KEYBOARD_TYPE_K70: get_key_pos_us_k70(key, x, y); break; case CKRGB_KEYBOARD_TYPE_K95: get_key_pos_us_k95(key, x, y); break; } } else if (km == CKRGB_KEYMAP_UK) { switch (kt) { case CKRGB_KEYBOARD_TYPE_K65: get_key_pos_uk_k65(key, x, y); break; case CKRGB_KEYBOARD_TYPE_K70: get_key_pos_uk_k70(key, x, y); break; case CKRGB_KEYBOARD_TYPE_K95: get_key_pos_uk_k95(key, x, y); break; } } } void ckrgb_keyboard_set_keycode(ckrgb_keyboard* kb, unsigned char keycode, unsigned char r, unsigned char g, unsigned char b) { if (keycode == 0xFF) //> Ignore code 0xFF return; /* r = (unsigned char)((7.f/255.f)*r); g = (unsigned char)((7.f/255.f)*g); b = (unsigned char)((7.f/255.f)*b); kb->pBuffer[keycode].r = 7 - r; kb->pBuffer[keycode].g = 7 - g; kb->pBuffer[keycode].b = 7 - b; */ kb->pBuffer[keycode].r = r; kb->pBuffer[keycode].g = g; kb->pBuffer[keycode].b = b; } void ckrgb_keyboard_get_keycode(ckrgb_keyboard* kb, unsigned char keycode, unsigned char* r, unsigned char* g, unsigned char* b) { if (keycode == 0xFF) //> Ignore code 0xFF return; (*r) = kb->pBuffer[keycode].r; (*g) = kb->pBuffer[keycode].g; (*b) = kb->pBuffer[keycode].b; } void ckrgb_keyboard_set_key(ckrgb_keyboard* kb, enum ckrgb_key key, unsigned char r, unsigned char g, unsigned char b) { if (kb->eKeyMap == CKRGB_KEYMAP_US) ckrgb_keyboard_set_keycode(kb, keymap_us[key], r, g, b); else if (kb->eKeyMap == CKRGB_KEYMAP_UK) ckrgb_keyboard_set_keycode(kb, keymap_uk[key], r, g, b); } void ckrgb_keyboard_get_key(ckrgb_keyboard* kb, enum ckrgb_key key, unsigned char* r, unsigned char* g, unsigned char* b) { if (kb->eKeyMap == CKRGB_KEYMAP_US) ckrgb_keyboard_get_keycode(kb, keymap_us[key], r, g, b); else if (kb->eKeyMap == CKRGB_KEYMAP_UK) ckrgb_keyboard_get_keycode(kb, keymap_uk[key], r, g, b); } void ckrgb_keyboard_set_pos(ckrgb_keyboard* kb, int x, int y, unsigned char r, unsigned char g, unsigned char b) { if (x < 0 || x >= kb->width || y < 0 || y >= kb->height) return; if (kb->eKeyMap == CKRGB_KEYMAP_US) { switch (kb->eType) { case CKRGB_KEYBOARD_TYPE_K65: ckrgb_keyboard_set_key(kb, key_matrix_us_k65[y][x], r, g, b); break; case CKRGB_KEYBOARD_TYPE_K70: ckrgb_keyboard_set_key(kb, key_matrix_us_k70[y][x], r, g, b); break; case CKRGB_KEYBOARD_TYPE_K95: ckrgb_keyboard_set_key(kb, key_matrix_us_k95[y][x], r, g, b); break; } } else if (kb->eKeyMap == CKRGB_KEYMAP_UK) { switch (kb->eType) { case CKRGB_KEYBOARD_TYPE_K65: ckrgb_keyboard_set_key(kb, key_matrix_uk_k65[y][x], r, g, b); break; case CKRGB_KEYBOARD_TYPE_K70: ckrgb_keyboard_set_key(kb, key_matrix_uk_k70[y][x], r, g, b); break; case CKRGB_KEYBOARD_TYPE_K95: ckrgb_keyboard_set_key(kb, key_matrix_uk_k95[y][x], r, g, b); break; } } } void ckrgb_keyboard_get_pos(ckrgb_keyboard* kb, int x, int y, unsigned char* r, unsigned char* g, unsigned char* b) { if (x < 0 || x >= kb->width || y < 0 || y >= kb->height) return; if (kb->eKeyMap == CKRGB_KEYMAP_US) { switch (kb->eType) { case CKRGB_KEYBOARD_TYPE_K65: ckrgb_keyboard_get_key(kb, key_matrix_us_k65[y][x], r, g, b); break; case CKRGB_KEYBOARD_TYPE_K70: ckrgb_keyboard_get_key(kb, key_matrix_us_k70[y][x], r, g, b); break; case CKRGB_KEYBOARD_TYPE_K95: ckrgb_keyboard_get_key(kb, key_matrix_us_k95[y][x], r, g, b); break; } } else if (kb->eKeyMap == CKRGB_KEYMAP_UK) { switch (kb->eType) { case CKRGB_KEYBOARD_TYPE_K65: ckrgb_keyboard_get_key(kb, key_matrix_uk_k65[y][x], r, g, b); break; case CKRGB_KEYBOARD_TYPE_K70: ckrgb_keyboard_get_key(kb, key_matrix_uk_k70[y][x], r, g, b); break; case CKRGB_KEYBOARD_TYPE_K95: ckrgb_keyboard_get_key(kb, key_matrix_uk_k95[y][x], r, g, b); break; } } } unsigned char process_component(unsigned char val) { return 7 - (unsigned char)((7.f/255.f) * val); } ckrgb_error ckrgb_keyboard_flush_buffer(ckrgb_keyboard* kb) { unsigned char data[5][64] = {0}; int i, err; if (!kb->bClaimed) return CKRGB_ERROR_NOT_CLAIMED; /* Credits to CalcProgrammer1 for reverse engineering the protocol. */ data[0][0] = 0x7F; data[0][1] = 0x01; data[0][2] = 0x3C; data[1][0] = 0x7F; data[1][1] = 0x02; data[1][2] = 0x3C; data[2][0] = 0x7F; data[2][1] = 0x03; data[2][2] = 0x3C; data[3][0] = 0x7F; data[3][1] = 0x04; data[3][2] = 0x24; data[4][0] = 0x07; data[4][1] = 0x27; data[4][2] = 0xD8; // Red. for (i = 0; i < 60; ++i) data[0][i+4] = (process_component(kb->pBuffer[i*2+1].r) << 4) | process_component(kb->pBuffer[i*2].r); for (i = 0; i < 12; ++i) data[1][i+4] = (process_component(kb->pBuffer[i*2+121].r) << 4) | process_component(kb->pBuffer[i*2+120].r); // Green. for (i = 0; i < 48; ++i) data[1][i+16] = (process_component(kb->pBuffer[i*2+1].g) << 4) | process_component(kb->pBuffer[i*2].g); for (i = 0; i < 24; ++i) data[2][i+4] = (process_component(kb->pBuffer[i*2+97].g) << 4) | process_component(kb->pBuffer[i*2+96].g); // Blue. for (i = 0; i < 36; ++i) data[2][i+28] = (process_component(kb->pBuffer[i*2+1].b) << 4) | process_component(kb->pBuffer[i*2].b); for (i = 0; i < 36; ++i) data[3][i+4] = (process_component(kb->pBuffer[i*2+73].b) << 4) | process_component(kb->pBuffer[i*2+72].b); // Transfer data. for (i = 0; i < 5; ++i) { // Perform USB control message to keyboard // // Request Type: 0x21 // Request: 0x09 // Value 0x0300 // Index: 0x03 // Size: 64 err = libusb_control_transfer(kb->pHandle, 0x21, 0x09, 0x0300, 0x03, data[i], 64, 1000); if (err < 0) { switch(err) { case LIBUSB_ERROR_TIMEOUT: return CKRGB_ERROR_TIMEOUT; case LIBUSB_ERROR_PIPE: return CKRGB_ERROR_BAD_CONTROL_REQUEST; case LIBUSB_ERROR_NO_DEVICE: return CKRGB_ERROR_NO_DEVICE; default: return CKRGB_ERROR_UNKNOWN; } } } return CKRGB_ERROR_SUCCESS; }
986983.c
// SPDX-License-Identifier: GPL-2.0 /* * linux/arch/m68k/mm/motorola.c * * Routines specific to the Motorola MMU, originally from: * linux/arch/m68k/init.c * which are Copyright (C) 1995 Hamish Macdonald * * Moved 8/20/1999 Sam Creasey */ #include <linux/module.h> #include <linux/signal.h> #include <linux/sched.h> #include <linux/mm.h> #include <linux/swap.h> #include <linux/kernel.h> #include <linux/string.h> #include <linux/types.h> #include <linux/init.h> #include <linux/memblock.h> #include <linux/gfp.h> #include <asm/setup.h> #include <linux/uaccess.h> #include <asm/page.h> #include <asm/pgalloc.h> #include <asm/machdep.h> #include <asm/io.h> #include <asm/dma.h> #ifdef CONFIG_ATARI #include <asm/atari_stram.h> #endif #include <asm/sections.h> #undef DEBUG #ifndef mm_cachebits /* * Bits to add to page descriptors for "normal" caching mode. * For 68020/030 this is 0. * For 68040, this is _PAGE_CACHE040 (cachable, copyback) */ unsigned long mm_cachebits; EXPORT_SYMBOL(mm_cachebits); #endif /* size of memory already mapped in head.S */ extern __initdata unsigned long m68k_init_mapped_size; extern unsigned long availmem; static pte_t * __init kernel_page_table(void) { pte_t *ptablep; ptablep = (pte_t *)memblock_alloc_low(PAGE_SIZE, PAGE_SIZE); if (!ptablep) panic("%s: Failed to allocate %lu bytes align=%lx\n", __func__, PAGE_SIZE, PAGE_SIZE); clear_page(ptablep); __flush_page_to_ram(ptablep); flush_tlb_kernel_page(ptablep); nocache_page(ptablep); return ptablep; } static pmd_t *last_pgtable __initdata = NULL; pmd_t *zero_pgtable __initdata = NULL; static pmd_t * __init kernel_ptr_table(void) { if (!last_pgtable) { unsigned long pmd, last; int i; /* Find the last ptr table that was used in head.S and * reuse the remaining space in that page for further * ptr tables. */ last = (unsigned long)kernel_pg_dir; for (i = 0; i < PTRS_PER_PGD; i++) { if (!pgd_present(kernel_pg_dir[i])) continue; pmd = __pgd_page(kernel_pg_dir[i]); if (pmd > last) last = pmd; } last_pgtable = (pmd_t *)last; #ifdef DEBUG printk("kernel_ptr_init: %p\n", last_pgtable); #endif } last_pgtable += PTRS_PER_PMD; if (((unsigned long)last_pgtable & ~PAGE_MASK) == 0) { last_pgtable = (pmd_t *)memblock_alloc_low(PAGE_SIZE, PAGE_SIZE); if (!last_pgtable) panic("%s: Failed to allocate %lu bytes align=%lx\n", __func__, PAGE_SIZE, PAGE_SIZE); clear_page(last_pgtable); __flush_page_to_ram(last_pgtable); flush_tlb_kernel_page(last_pgtable); nocache_page(last_pgtable); } return last_pgtable; } static void __init map_node(int node) { #define PTRTREESIZE (256*1024) #define ROOTTREESIZE (32*1024*1024) unsigned long physaddr, virtaddr, size; pgd_t *pgd_dir; pmd_t *pmd_dir; pte_t *pte_dir; size = m68k_memory[node].size; physaddr = m68k_memory[node].addr; virtaddr = (unsigned long)phys_to_virt(physaddr); physaddr |= m68k_supervisor_cachemode | _PAGE_PRESENT | _PAGE_ACCESSED | _PAGE_DIRTY; if (CPU_IS_040_OR_060) physaddr |= _PAGE_GLOBAL040; while (size > 0) { #ifdef DEBUG if (!(virtaddr & (PTRTREESIZE-1))) printk ("\npa=%#lx va=%#lx ", physaddr & PAGE_MASK, virtaddr); #endif pgd_dir = pgd_offset_k(virtaddr); if (virtaddr && CPU_IS_020_OR_030) { if (!(virtaddr & (ROOTTREESIZE-1)) && size >= ROOTTREESIZE) { #ifdef DEBUG printk ("[very early term]"); #endif pgd_val(*pgd_dir) = physaddr; size -= ROOTTREESIZE; virtaddr += ROOTTREESIZE; physaddr += ROOTTREESIZE; continue; } } if (!pgd_present(*pgd_dir)) { pmd_dir = kernel_ptr_table(); #ifdef DEBUG printk ("[new pointer %p]", pmd_dir); #endif pgd_set(pgd_dir, pmd_dir); } else pmd_dir = pmd_offset(pgd_dir, virtaddr); if (CPU_IS_020_OR_030) { if (virtaddr) { #ifdef DEBUG printk ("[early term]"); #endif pmd_dir->pmd[(virtaddr/PTRTREESIZE) & 15] = physaddr; physaddr += PTRTREESIZE; } else { int i; #ifdef DEBUG printk ("[zero map]"); #endif zero_pgtable = kernel_ptr_table(); pte_dir = (pte_t *)zero_pgtable; pmd_dir->pmd[0] = virt_to_phys(pte_dir) | _PAGE_TABLE | _PAGE_ACCESSED; pte_val(*pte_dir++) = 0; physaddr += PAGE_SIZE; for (i = 1; i < 64; physaddr += PAGE_SIZE, i++) pte_val(*pte_dir++) = physaddr; } size -= PTRTREESIZE; virtaddr += PTRTREESIZE; } else { if (!pmd_present(*pmd_dir)) { #ifdef DEBUG printk ("[new table]"); #endif pte_dir = kernel_page_table(); pmd_set(pmd_dir, pte_dir); } pte_dir = pte_offset_kernel(pmd_dir, virtaddr); if (virtaddr) { if (!pte_present(*pte_dir)) pte_val(*pte_dir) = physaddr; } else pte_val(*pte_dir) = 0; size -= PAGE_SIZE; virtaddr += PAGE_SIZE; physaddr += PAGE_SIZE; } } #ifdef DEBUG printk("\n"); #endif } /* * paging_init() continues the virtual memory environment setup which * was begun by the code in arch/head.S. */ void __init paging_init(void) { unsigned long zones_size[MAX_NR_ZONES] = { 0, }; unsigned long min_addr, max_addr; unsigned long addr; int i; #ifdef DEBUG printk ("start of paging_init (%p, %lx)\n", kernel_pg_dir, availmem); #endif /* Fix the cache mode in the page descriptors for the 680[46]0. */ if (CPU_IS_040_OR_060) { int i; #ifndef mm_cachebits mm_cachebits = _PAGE_CACHE040; #endif for (i = 0; i < 16; i++) pgprot_val(protection_map[i]) |= _PAGE_CACHE040; } min_addr = m68k_memory[0].addr; max_addr = min_addr + m68k_memory[0].size; memblock_add(m68k_memory[0].addr, m68k_memory[0].size); for (i = 1; i < m68k_num_memory;) { if (m68k_memory[i].addr < min_addr) { printk("Ignoring memory chunk at 0x%lx:0x%lx before the first chunk\n", m68k_memory[i].addr, m68k_memory[i].size); printk("Fix your bootloader or use a memfile to make use of this area!\n"); m68k_num_memory--; memmove(m68k_memory + i, m68k_memory + i + 1, (m68k_num_memory - i) * sizeof(struct m68k_mem_info)); continue; } memblock_add(m68k_memory[i].addr, m68k_memory[i].size); addr = m68k_memory[i].addr + m68k_memory[i].size; if (addr > max_addr) max_addr = addr; i++; } m68k_memoffset = min_addr - PAGE_OFFSET; m68k_virt_to_node_shift = fls(max_addr - min_addr - 1) - 6; module_fixup(NULL, __start_fixup, __stop_fixup); flush_icache(); high_memory = phys_to_virt(max_addr); min_low_pfn = availmem >> PAGE_SHIFT; max_pfn = max_low_pfn = max_addr >> PAGE_SHIFT; /* Reserve kernel text/data/bss and the memory allocated in head.S */ memblock_reserve(m68k_memory[0].addr, availmem - m68k_memory[0].addr); /* * Map the physical memory available into the kernel virtual * address space. Make sure memblock will not try to allocate * pages beyond the memory we already mapped in head.S */ memblock_set_bottom_up(true); for (i = 0; i < m68k_num_memory; i++) { m68k_setup_node(i); map_node(i); } flush_tlb_all(); /* * initialize the bad page table and bad page to point * to a couple of allocated pages */ empty_zero_page = memblock_alloc(PAGE_SIZE, PAGE_SIZE); if (!empty_zero_page) panic("%s: Failed to allocate %lu bytes align=0x%lx\n", __func__, PAGE_SIZE, PAGE_SIZE); /* * Set up SFC/DFC registers */ set_fs(KERNEL_DS); #ifdef DEBUG printk ("before free_area_init\n"); #endif for (i = 0; i < m68k_num_memory; i++) { zones_size[ZONE_DMA] = m68k_memory[i].size >> PAGE_SHIFT; free_area_init_node(i, zones_size, m68k_memory[i].addr >> PAGE_SHIFT, NULL); if (node_present_pages(i)) node_set_state(i, N_NORMAL_MEMORY); } }
819436.c
// Copyright lowRISC contributors. // Licensed under the Apache License, Version 2.0, see LICENSE for details. // SPDX-License-Identifier: Apache-2.0 #include "sw/device/lib/usbdev.h" #include "hw/top_earlgrey/sw/autogen/top_earlgrey.h" #include "usbdev_regs.h" // Generated. #define USBDEV_BASE_ADDR TOP_EARLGREY_USBDEV_BASE_ADDR #define EXTRACT(n, f) ((n >> USBDEV_##f##_OFFSET) & USBDEV_##f##_MASK) #define SETBIT(val, bit) (val | 1 << bit) #define CLRBIT(val, bit) (val & ~(1 << bit)) #define REG32(add) *((volatile uint32_t *)(add)) // Free buffer pool is held on a simple stack // Initalize to all buffer IDs are free static void buf_init(usbdev_ctx_t *ctx) { for (int i = 0; i < NUM_BUFS; i++) { ctx->freebuf[i] = i; } ctx->nfree = NUM_BUFS; } // Allocating a buffer just pops next ID from the stack usbbufid_t usbdev_buf_allocate_byid(usbdev_ctx_t *ctx) { if (ctx->nfree <= 0) { return -1; } return ctx->freebuf[--ctx->nfree]; } // Freeing a buffer just pushes the ID back on the stack int usbdev_buf_free_byid(usbdev_ctx_t *ctx, usbbufid_t buf) { if ((ctx->nfree >= NUM_BUFS) || (buf >= NUM_BUFS)) { return -1; } ctx->freebuf[ctx->nfree++] = buf; return 0; } uint32_t *usbdev_buf_idtoaddr(usbdev_ctx_t *ctx, usbbufid_t buf) { return (uint32_t *)(USBDEV_BASE_ADDR + USBDEV_BUFFER_REG_OFFSET + (buf * BUF_LENGTH)); } void usbdev_buf_copyto_byid(usbdev_ctx_t *ctx, usbbufid_t buf, const void *from, size_t len_bytes) { int32_t *from_word = (int32_t *)from; int len_words; volatile uint32_t *bp = usbdev_buf_idtoaddr(ctx, buf); if (len_bytes > BUF_LENGTH) { len_bytes = BUF_LENGTH; } // This will round up if len_bytes is not on a multiple of int32_t // Always ok to fill the extra bytes since the buffers are aligned len_words = (len_bytes + sizeof(int32_t) - 1) / sizeof(int32_t); for (int i = 0; i < len_words; i++) { bp[i] = from_word[i]; } } // Supply as many buffers to the receive available fifo as possible inline static void fill_av_fifo(usbdev_ctx_t *ctx) { while (!(REG32(USBDEV_BASE_ADDR + USBDEV_USBSTAT_REG_OFFSET) & (1 << USBDEV_USBSTAT_AV_FULL_BIT))) { usbbufid_t buf = usbdev_buf_allocate_byid(ctx); if (buf < 0) { // no more free buffers, can't fill AV FIFO break; } REG32(USBDEV_BASE_ADDR + USBDEV_AVBUFFER_REG_OFFSET) = buf; } } void usbdev_sendbuf_byid(usbdev_ctx_t *ctx, usbbufid_t buf, size_t size, int endpoint) { uint32_t configin = USBDEV_BASE_ADDR + USBDEV_CONFIGIN_0_REG_OFFSET + (4 * endpoint); if ((endpoint >= NUM_ENDPOINTS) || (buf >= NUM_BUFS)) { return; } if (size > BUF_LENGTH) { size = BUF_LENGTH; } REG32(configin) = ((buf << USBDEV_CONFIGIN_0_BUFFER_0_OFFSET) | (size << USBDEV_CONFIGIN_0_SIZE_0_OFFSET) | (1 << USBDEV_CONFIGIN_0_RDY_0_BIT)); } void usbdev_poll(usbdev_ctx_t *ctx) { uint32_t istate = REG32(USBDEV_BASE_ADDR + USBDEV_INTR_STATE_REG_OFFSET); // Do this first to keep things going fill_av_fifo(ctx); // Process IN completions first so we get the fact that send completed // before processing a response if (istate & (1 << USBDEV_INTR_STATE_PKT_SENT_BIT)) { uint32_t sentep = REG32(USBDEV_BASE_ADDR + USBDEV_IN_SENT_REG_OFFSET); uint32_t configin = USBDEV_BASE_ADDR + USBDEV_CONFIGIN_0_REG_OFFSET; TRC_C('a' + sentep); for (int ep = 0; ep < NUM_ENDPOINTS; ep++) { if (sentep & (1 << ep)) { // Free up the buffer and optionally callback int32_t cfgin = REG32(configin + (4 * ep)); usbdev_buf_free_byid(ctx, EXTRACT(cfgin, CONFIGIN_0_BUFFER_0)); if (ctx->tx_done_callback[ep]) { ctx->tx_done_callback[ep](ctx->ep_ctx[ep]); } } } // Write one to clear all the ones we handled REG32(USBDEV_BASE_ADDR + USBDEV_IN_SENT_REG_OFFSET) = sentep; // Clear the interupt REG32(USBDEV_BASE_ADDR + USBDEV_INTR_STATE_REG_OFFSET) = (1 << USBDEV_INTR_STATE_PKT_SENT_BIT); } if (istate & (1 << USBDEV_INTR_STATE_PKT_RECEIVED_BIT)) { while (!(REG32(USBDEV_BASE_ADDR + USBDEV_USBSTAT_REG_OFFSET) & (1 << USBDEV_USBSTAT_RX_EMPTY_BIT))) { uint32_t rxinfo = REG32(USBDEV_BASE_ADDR + USBDEV_RXFIFO_REG_OFFSET); usbbufid_t buf = EXTRACT(rxinfo, RXFIFO_BUFFER); int size = EXTRACT(rxinfo, RXFIFO_SIZE); int endpoint = EXTRACT(rxinfo, RXFIFO_EP); int setup = (rxinfo >> USBDEV_RXFIFO_SETUP_BIT) & 1; if (ctx->rx_callback[endpoint]) { ctx->rx_callback[endpoint](ctx->ep_ctx[endpoint], buf, size, setup); } else { TRC_S("USB: unexpected RX "); TRC_I(rxinfo, 24); } usbdev_buf_free_byid(ctx, buf); } // Clear the interupt REG32(USBDEV_BASE_ADDR + USBDEV_INTR_STATE_REG_OFFSET) = (1 << USBDEV_INTR_STATE_PKT_RECEIVED_BIT); } if (istate & ~((1 << USBDEV_INTR_STATE_PKT_RECEIVED_BIT) | (1 << USBDEV_INTR_STATE_PKT_SENT_BIT))) { TRC_C('I'); TRC_I(istate, 12); TRC_C(' '); REG32(USBDEV_BASE_ADDR + USBDEV_INTR_STATE_REG_OFFSET) = istate & ~((1 << USBDEV_INTR_STATE_PKT_RECEIVED_BIT) | (1 << USBDEV_INTR_STATE_PKT_SENT_BIT)); if (istate & (1 << USBDEV_INTR_ENABLE_LINK_RESET_BIT)) { // Link reset for (int ep = 0; ep < NUM_ENDPOINTS; ep++) { if (ctx->reset[ep]) { ctx->reset[ep](ctx->ep_ctx[ep]); } } // Clear the interupt REG32(USBDEV_BASE_ADDR + USBDEV_INTR_STATE_REG_OFFSET) = (1 << USBDEV_INTR_ENABLE_LINK_RESET_BIT); } } // TODO - clean this up // Frame ticks every 1ms, use to flush data every 16ms // (faster in DPI but this seems to work ok) // At reset frame count is 0, compare to 1 so no calls before SOF received uint32_t usbframe = EXTRACT( REG32(USBDEV_BASE_ADDR + USBDEV_USBSTAT_REG_OFFSET), USBSTAT_FRAME); if ((usbframe & 0xf) == 1) { if (ctx->flushed == 0) { for (int i = 0; i < NUM_ENDPOINTS; i++) { if (ctx->flush[i]) { ctx->flush[i](ctx->ep_ctx[i]); } } ctx->flushed = 1; } } else { ctx->flushed = 0; } // TODO Errors? What Errors? } unsigned int usbdev_get_status(usbdev_ctx_t *ctx) { unsigned int status = REG32(USBDEV_BASE_ADDR + USBDEV_USBSTAT_REG_OFFSET); return status; } unsigned int usbdev_get_link_state(usbdev_ctx_t *ctx) { unsigned int link_state = EXTRACT( REG32(USBDEV_BASE_ADDR + USBDEV_USBSTAT_REG_OFFSET), USBSTAT_LINK_STATE); return link_state; } unsigned int usbdev_get_address(usbdev_ctx_t *ctx) { unsigned int addr = EXTRACT(REG32(USBDEV_BASE_ADDR + USBDEV_USBCTRL_REG_OFFSET), USBCTRL_DEVICE_ADDRESS); return addr; } void usbdev_set_deviceid(usbdev_ctx_t *ctx, int deviceid) { REG32(USBDEV_BASE_ADDR + USBDEV_USBCTRL_REG_OFFSET) = (1 << USBDEV_USBCTRL_ENABLE_BIT) | (deviceid << USBDEV_USBCTRL_DEVICE_ADDRESS_OFFSET); } void usbdev_halt(usbdev_ctx_t *ctx, int endpoint, int enable) { uint32_t epbit = 1 << endpoint; uint32_t stall = REG32(USBDEV_BASE_ADDR + USBDEV_STALL_REG_OFFSET); if (enable) { stall |= epbit; } else { stall &= ~epbit; } REG32(USBDEV_BASE_ADDR + USBDEV_STALL_REG_OFFSET) = stall; ctx->halted = stall; // TODO future addition would be to callback the endpoint driver // for now it just sees its traffic has stopped } void usbdev_set_iso(usbdev_ctx_t *ctx, int endpoint, int enable) { if (enable) { REG32(USBDEV_BASE_ADDR + USBDEV_ISO_REG_OFFSET) = SETBIT(REG32(USBDEV_BASE_ADDR + USBDEV_ISO_REG_OFFSET), endpoint); } else { REG32(USBDEV_BASE_ADDR + USBDEV_ISO_REG_OFFSET) = CLRBIT(REG32(USBDEV_BASE_ADDR + USBDEV_ISO_REG_OFFSET), endpoint); } } void usbdev_clear_data_toggle(usbdev_ctx_t *ctx, int endpoint) { REG32(USBDEV_BASE_ADDR + USBDEV_DATA_TOGGLE_CLEAR_REG_OFFSET) = (1 << endpoint); } void usbdev_set_ep0_stall(usbdev_ctx_t *ctx, int stall) { if (stall) { REG32(USBDEV_BASE_ADDR + USBDEV_STALL_REG_OFFSET) = REG32(USBDEV_BASE_ADDR + USBDEV_STALL_REG_OFFSET) | 1; } else { REG32(USBDEV_BASE_ADDR + USBDEV_STALL_REG_OFFSET) = REG32(USBDEV_BASE_ADDR + USBDEV_STALL_REG_OFFSET) & ~(1); } } // TODO got hang with this inline int usbdev_can_rem_wake(usbdev_ctx_t *ctx) { return ctx->can_wake; } void usbdev_endpoint_setup(usbdev_ctx_t *ctx, int ep, int enableout, void *ep_ctx, void (*tx_done)(void *), void (*rx)(void *, usbbufid_t, int, int), void (*flush)(void *), void (*reset)(void *)) { ctx->ep_ctx[ep] = ep_ctx; ctx->tx_done_callback[ep] = tx_done; ctx->rx_callback[ep] = rx; ctx->flush[ep] = flush; ctx->reset[ep] = reset; if (enableout) { uint32_t rxen = REG32(USBDEV_BASE_ADDR + USBDEV_RXENABLE_OUT_REG_OFFSET); rxen |= (1 << (ep + USBDEV_RXENABLE_OUT_OUT_0_BIT)); REG32(USBDEV_BASE_ADDR + USBDEV_RXENABLE_OUT_REG_OFFSET) = rxen; } } void usbdev_init(usbdev_ctx_t *ctx, bool pinflip, bool diff_rx, bool diff_tx) { // setup context for (int i = 0; i < NUM_ENDPOINTS; i++) { usbdev_endpoint_setup(ctx, i, 0, NULL, NULL, NULL, NULL, NULL); } ctx->halted = 0; ctx->can_wake = 0; buf_init(ctx); // All about polling... REG32(USBDEV_BASE_ADDR + USBDEV_INTR_ENABLE_REG_OFFSET) = 0; // Provide buffers for any reception fill_av_fifo(ctx); REG32(USBDEV_BASE_ADDR + USBDEV_RXENABLE_SETUP_REG_OFFSET) = (1 << USBDEV_RXENABLE_SETUP_SETUP_0_BIT); REG32(USBDEV_BASE_ADDR + USBDEV_RXENABLE_OUT_REG_OFFSET) = (1 << USBDEV_RXENABLE_OUT_OUT_0_BIT); uint32_t phy_config = (pinflip << USBDEV_PHY_CONFIG_PINFLIP_BIT) | (diff_rx << USBDEV_PHY_CONFIG_RX_DIFFERENTIAL_MODE_BIT) | (diff_tx << USBDEV_PHY_CONFIG_TX_DIFFERENTIAL_MODE_BIT) | (1 << USBDEV_PHY_CONFIG_EOP_SINGLE_BIT_BIT); REG32(USBDEV_BASE_ADDR + USBDEV_PHY_CONFIG_REG_OFFSET) = phy_config; REG32(USBDEV_BASE_ADDR + USBDEV_USBCTRL_REG_OFFSET) = (1 << USBDEV_USBCTRL_ENABLE_BIT); } void usbdev_force_dx_pullup(line_sel_t line, bool set) { // Force usb to pretend it is in suspend uint32_t reg_val = REG32(USBDEV_BASE_ADDR + USBDEV_PHY_PINS_DRIVE_REG_OFFSET); uint32_t mask; mask = line == kDpSel ? USBDEV_PHY_PINS_DRIVE_DP_PULLUP_EN_O_BIT : USBDEV_PHY_PINS_DRIVE_DN_PULLUP_EN_O_BIT; if (set) { reg_val = SETBIT(reg_val, mask); } else { reg_val = CLRBIT(reg_val, mask); } reg_val = SETBIT(reg_val, USBDEV_PHY_PINS_DRIVE_EN_BIT); REG32(USBDEV_BASE_ADDR + USBDEV_PHY_PINS_DRIVE_REG_OFFSET) = reg_val; } void usbdev_force_suspend() { // Force usb to pretend it is in suspend REG32(USBDEV_BASE_ADDR + USBDEV_PHY_PINS_DRIVE_REG_OFFSET) |= 1 << USBDEV_PHY_PINS_DRIVE_SUSPEND_O_BIT | 1 << USBDEV_PHY_PINS_DRIVE_EN_BIT; } void usbdev_wake(bool set) { uint32_t reg_val = REG32(USBDEV_BASE_ADDR + USBDEV_WAKE_CONFIG_REG_OFFSET); if (set) { reg_val = SETBIT(reg_val, USBDEV_WAKE_CONFIG_WAKE_EN_BIT); } else { reg_val = CLRBIT(reg_val, USBDEV_WAKE_CONFIG_WAKE_EN_BIT); } REG32(USBDEV_BASE_ADDR + USBDEV_WAKE_CONFIG_REG_OFFSET) = reg_val; }
283745.c
/* * Copyright 2016-2018 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the OpenSSL license (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #if defined(__linux) || defined(__sun) || defined(__hpux) /* * Following definition aliases fopen to fopen64 on above mentioned * platforms. This makes it possible to open and sequentially access files * larger than 2GB from 32-bit application. It does not allow to traverse * them beyond 2GB with fseek/ftell, but on the other hand *no* 32-bit * platform permits that, not with fseek/ftell. Not to mention that breaking * 2GB limit for seeking would require surgery to *our* API. But sequential * access suffices for practical cases when you can run into large files, * such as fingerprinting, so we can let API alone. For reference, the list * of 32-bit platforms which allow for sequential access of large files * without extra "magic" comprise *BSD, Darwin, IRIX... */ #ifndef _FILE_OFFSET_BITS #define _FILE_OFFSET_BITS 64 #endif #endif #include "e_os.h" #include "internal/cryptlib.h" #if !defined(OPENSSL_NO_STDIO) #include <stdio.h> #ifdef __DJGPP__ #include <unistd.h> #endif FILE* openssl_fopen(const char* filename, const char* mode) { FILE* file = NULL; #if defined(_WIN32) && defined(CP_UTF8) int sz, len_0 = (int)strlen(filename) + 1; DWORD flags; /* * Basically there are three cases to cover: a) filename is * pure ASCII string; b) actual UTF-8 encoded string and * c) locale-ized string, i.e. one containing 8-bit * characters that are meaningful in current system locale. * If filename is pure ASCII or real UTF-8 encoded string, * MultiByteToWideChar succeeds and _wfopen works. If * filename is locale-ized string, chances are that * MultiByteToWideChar fails reporting * ERROR_NO_UNICODE_TRANSLATION, in which case we fall * back to fopen... */ if ((sz = MultiByteToWideChar(CP_UTF8, (flags = MB_ERR_INVALID_CHARS), filename, len_0, NULL, 0)) > 0 || (GetLastError() == ERROR_INVALID_FLAGS && (sz = MultiByteToWideChar(CP_UTF8, (flags = 0), filename, len_0, NULL, 0)) > 0)) { WCHAR wmode[8]; WCHAR* wfilename = _alloca(sz * sizeof(WCHAR)); if (MultiByteToWideChar(CP_UTF8, flags, filename, len_0, wfilename, sz) && MultiByteToWideChar(CP_UTF8, 0, mode, strlen(mode) + 1, wmode, OSSL_NELEM(wmode)) && (file = _wfopen(wfilename, wmode)) == NULL && (errno == ENOENT || errno == EBADF)) { /* * UTF-8 decode succeeded, but no file, filename * could still have been locale-ized... */ file = fopen(filename, mode); } } else if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION) { file = fopen(filename, mode); } #elif defined(__DJGPP__) { char* newname = NULL; if (pathconf(filename, _PC_NAME_MAX) <= 12) { /* 8.3 file system? */ char* iterator; char lastchar; if ((newname = OPENSSL_malloc(strlen(filename) + 1)) == NULL) { CRYPTOerr(CRYPTO_F_OPENSSL_FOPEN, ERR_R_MALLOC_FAILURE); return NULL; } for (iterator = newname, lastchar = '\0'; *filename; filename++, iterator++) { if (lastchar == '/' && filename[0] == '.' && filename[1] != '.' && filename[1] != '/') { /* Leading dots are not permitted in plain DOS. */ *iterator = '_'; } else { *iterator = *filename; } lastchar = *filename; } *iterator = '\0'; filename = newname; } file = fopen(filename, mode); OPENSSL_free(newname); } #else file = fopen(filename, mode); #endif return file; } #else void* openssl_fopen(const char* filename, const char* mode) { return NULL; } #endif
937305.c
/* Copyright 2015 Google Inc. All Rights Reserved. Distributed under MIT license. See file LICENSE for detail or copy at https://opensource.org/licenses/MIT */ #include "./state.h" #include <stdlib.h> /* free, malloc */ #include <brotli/types.h> #include "./huffman.h" #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif static void* DefaultAllocFunc(void* opaque, size_t size) { BROTLI_UNUSED(opaque); return malloc(size); } static void DefaultFreeFunc(void* opaque, void* address) { BROTLI_UNUSED(opaque); free(address); } void BrotliDecoderStateInit(BrotliDecoderState* s) { BrotliDecoderStateInitWithCustomAllocators(s, 0, 0, 0); } void BrotliDecoderStateInitWithCustomAllocators(BrotliDecoderState* s, brotli_alloc_func alloc_func, brotli_free_func free_func, void* opaque) { if (!alloc_func) { s->alloc_func = DefaultAllocFunc; s->free_func = DefaultFreeFunc; s->memory_manager_opaque = 0; } else { s->alloc_func = alloc_func; s->free_func = free_func; s->memory_manager_opaque = opaque; } BrotliInitBitReader(&s->br); s->state = BROTLI_STATE_UNINITED; s->substate_metablock_header = BROTLI_STATE_METABLOCK_HEADER_NONE; s->substate_tree_group = BROTLI_STATE_TREE_GROUP_NONE; s->substate_context_map = BROTLI_STATE_CONTEXT_MAP_NONE; s->substate_uncompressed = BROTLI_STATE_UNCOMPRESSED_NONE; s->substate_huffman = BROTLI_STATE_HUFFMAN_NONE; s->substate_decode_uint8 = BROTLI_STATE_DECODE_UINT8_NONE; s->substate_read_block_length = BROTLI_STATE_READ_BLOCK_LENGTH_NONE; s->dictionary = BrotliGetDictionary(); s->buffer_length = 0; s->loop_counter = 0; s->pos = 0; s->rb_roundtrips = 0; s->partial_pos_out = 0; s->block_type_trees = NULL; s->block_len_trees = NULL; s->ringbuffer = NULL; s->ringbuffer_size = 0; s->new_ringbuffer_size = 0; s->ringbuffer_mask = 0; s->context_map = NULL; s->context_modes = NULL; s->dist_context_map = NULL; s->context_map_slice = NULL; s->dist_context_map_slice = NULL; s->sub_loop_counter = 0; s->literal_hgroup.codes = NULL; s->literal_hgroup.htrees = NULL; s->insert_copy_hgroup.codes = NULL; s->insert_copy_hgroup.htrees = NULL; s->distance_hgroup.codes = NULL; s->distance_hgroup.htrees = NULL; s->custom_dict = NULL; s->custom_dict_size = 0; s->is_last_metablock = 0; s->should_wrap_ringbuffer = 0; s->window_bits = 0; s->max_distance = 0; s->dist_rb[0] = 16; s->dist_rb[1] = 15; s->dist_rb[2] = 11; s->dist_rb[3] = 4; s->dist_rb_idx = 0; s->block_type_trees = NULL; s->block_len_trees = NULL; /* Make small negative indexes addressable. */ s->symbol_lists = &s->symbols_lists_array[BROTLI_HUFFMAN_MAX_CODE_LENGTH + 1]; s->mtf_upper_bound = 63; } void BrotliDecoderStateMetablockBegin(BrotliDecoderState* s) { s->meta_block_remaining_len = 0; s->block_length[0] = 1U << 28; s->block_length[1] = 1U << 28; s->block_length[2] = 1U << 28; s->num_block_types[0] = 1; s->num_block_types[1] = 1; s->num_block_types[2] = 1; s->block_type_rb[0] = 1; s->block_type_rb[1] = 0; s->block_type_rb[2] = 1; s->block_type_rb[3] = 0; s->block_type_rb[4] = 1; s->block_type_rb[5] = 0; s->context_map = NULL; s->context_modes = NULL; s->dist_context_map = NULL; s->context_map_slice = NULL; s->literal_htree = NULL; s->dist_context_map_slice = NULL; s->dist_htree_index = 0; s->context_lookup1 = NULL; s->context_lookup2 = NULL; s->literal_hgroup.codes = NULL; s->literal_hgroup.htrees = NULL; s->insert_copy_hgroup.codes = NULL; s->insert_copy_hgroup.htrees = NULL; s->distance_hgroup.codes = NULL; s->distance_hgroup.htrees = NULL; } void BrotliDecoderStateCleanupAfterMetablock(BrotliDecoderState* s) { BROTLI_FREE(s, s->context_modes); BROTLI_FREE(s, s->context_map); BROTLI_FREE(s, s->dist_context_map); BROTLI_FREE(s, s->literal_hgroup.htrees); BROTLI_FREE(s, s->insert_copy_hgroup.htrees); BROTLI_FREE(s, s->distance_hgroup.htrees); } void BrotliDecoderStateCleanup(BrotliDecoderState* s) { BrotliDecoderStateCleanupAfterMetablock(s); BROTLI_FREE(s, s->ringbuffer); BROTLI_FREE(s, s->block_type_trees); } BROTLI_BOOL BrotliDecoderHuffmanTreeGroupInit(BrotliDecoderState* s, HuffmanTreeGroup* group, uint32_t alphabet_size, uint32_t ntrees) { /* Pack two allocations into one */ const size_t max_table_size = kMaxHuffmanTableSize[(alphabet_size + 31) >> 5]; const size_t code_size = sizeof(HuffmanCode) * ntrees * max_table_size; const size_t htree_size = sizeof(HuffmanCode*) * ntrees; /* Pointer alignment is, hopefully, wider than sizeof(HuffmanCode). */ HuffmanCode** p = (HuffmanCode**)BROTLI_ALLOC(s, code_size + htree_size); group->alphabet_size = (uint16_t)alphabet_size; group->num_htrees = (uint16_t)ntrees; group->htrees = p; group->codes = (HuffmanCode*)(&p[ntrees]); return !!p; } #if defined(__cplusplus) || defined(c_plusplus) } /* extern "C" */ #endif
302834.c
/* CF3 Copyright (c) 2015 ishiura-lab. Released under the MIT license. https://github.com/ishiura-compiler/CF3/MIT-LICENSE.md */ #include<stdio.h> #include<stdint.h> #include<stdlib.h> #include"test1.h" static uint32_t x8 = 2561881U; uint64_t x29 = 37600018338167179LLU; volatile uint64_t t7 = 18983206981110LLU; static volatile int64_t x35 = -3597407361944LL; static int64_t t8 = -4038914868LL; uint32_t x38 = UINT32_MAX; volatile uint64_t t9 = 1372838434LLU; uint16_t x54 = 1396U; uint16_t x67 = 17U; static int16_t x70 = INT16_MIN; volatile int8_t x71 = 7; int8_t x75 = INT8_MIN; static volatile uint64_t t15 = 4820861LLU; int8_t x87 = -38; static int8_t x93 = -1; uint32_t x104 = 74066121U; volatile uint8_t x119 = 4U; int32_t x127 = -37377272; static int8_t x135 = 5; int32_t x137 = INT32_MIN; volatile uint8_t x142 = UINT8_MAX; volatile int16_t x150 = 0; int64_t t29 = -31LL; int8_t x154 = 0; volatile uint64_t t31 = 73760863204311914LLU; volatile int8_t x163 = INT8_MIN; int32_t x182 = INT32_MIN; int64_t x184 = INT64_MAX; static volatile uint64_t t37 = 395463429908488LLU; volatile uint64_t x188 = 150LLU; volatile uint64_t t38 = 1LLU; int8_t x190 = INT8_MAX; volatile int16_t x193 = -177; uint16_t x194 = UINT16_MAX; int64_t x196 = INT64_MIN; uint64_t t40 = 8725401265475665236LLU; int8_t x199 = -1; int64_t x201 = -1LL; volatile uint16_t x202 = UINT16_MAX; volatile int64_t x203 = INT64_MAX; volatile uint16_t x204 = 22980U; int64_t x214 = INT64_MIN; int64_t x216 = INT64_MIN; volatile int16_t x222 = INT16_MIN; uint8_t x228 = UINT8_MAX; uint32_t t48 = 4154587U; int8_t x229 = INT8_MIN; int8_t x230 = 1; volatile int8_t x239 = 53; volatile int64_t t51 = 9556574LL; uint16_t x248 = UINT16_MAX; int64_t x249 = INT64_MIN; int16_t x258 = -1280; int8_t x272 = INT8_MAX; uint8_t x273 = UINT8_MAX; int8_t x275 = -3; uint8_t x279 = UINT8_MAX; int8_t x293 = INT8_MIN; uint64_t t64 = 2333683034LLU; volatile int8_t x300 = 0; uint64_t x302 = UINT64_MAX; uint64_t x305 = UINT64_MAX; static uint16_t x313 = 11960U; int8_t x314 = -1; int8_t x316 = INT8_MIN; volatile int8_t x322 = INT8_MAX; int8_t x324 = -10; static uint64_t x326 = 77219714837053LLU; uint8_t x337 = 13U; int32_t x340 = INT32_MIN; uint8_t x341 = 10U; static uint32_t t75 = 490U; uint64_t x345 = 12414816LLU; int16_t x346 = -1; volatile uint16_t x347 = 442U; volatile uint32_t x352 = UINT32_MAX; uint32_t t77 = 5129184U; int16_t x354 = INT16_MAX; int64_t t80 = 1356316742LL; int8_t x379 = -1; volatile int32_t x381 = 14852975; int64_t x382 = INT64_MIN; static int32_t x383 = -483358; static volatile int8_t x390 = INT8_MIN; uint64_t t87 = 141424026LLU; int32_t x395 = INT32_MIN; int8_t x406 = INT8_MAX; int32_t x407 = INT32_MAX; static int16_t x410 = 26; volatile uint16_t x413 = UINT16_MAX; uint8_t x425 = 3U; static volatile int64_t t94 = -546942310056LL; static uint64_t x436 = UINT64_MAX; uint64_t t95 = 2971228000LLU; volatile uint16_t x442 = UINT16_MAX; uint8_t x447 = 37U; volatile int8_t x451 = 1; uint64_t t100 = 158218795079062LLU; uint8_t x462 = 3U; static int64_t x470 = -1LL; static int32_t x474 = INT32_MAX; volatile int16_t x481 = INT16_MIN; int16_t x488 = -1; volatile int8_t x489 = INT8_MIN; int8_t x496 = -36; volatile int32_t x501 = 618346415; static uint32_t x508 = 73932U; uint64_t t111 = 3612047458389056LLU; static int16_t x513 = 16; int64_t x515 = -30146692511575LL; int32_t x521 = INT32_MIN; int8_t x529 = 3; uint8_t x532 = UINT8_MAX; int32_t t117 = 224616217; int16_t x535 = INT16_MAX; uint16_t x544 = 7610U; int8_t x545 = 55; volatile uint8_t x547 = 0U; volatile uint64_t t122 = 116LLU; uint16_t x555 = 605U; volatile uint64_t t125 = 7178922265837LLU; int16_t x567 = -1; int32_t x570 = -1; volatile int64_t x578 = -42LL; int8_t x581 = -59; int8_t x582 = INT8_MIN; volatile int64_t x585 = INT64_MAX; int32_t x591 = INT32_MIN; volatile uint64_t x594 = UINT64_MAX; int8_t x608 = 34; int32_t x610 = -1; uint32_t x611 = 171748U; uint32_t x615 = UINT32_MAX; volatile int32_t x619 = INT32_MAX; int64_t x620 = -5581965434642998LL; volatile uint32_t x621 = 71U; int64_t x627 = INT64_MAX; static volatile int16_t x638 = INT16_MAX; int8_t x639 = INT8_MIN; static volatile int32_t t142 = 53808; int64_t t144 = 10014498LL; uint64_t x649 = 15508792310LLU; static int32_t t147 = -943359616; uint16_t x668 = 59U; static int64_t x673 = 7807394LL; uint64_t x674 = UINT64_MAX; volatile int16_t x679 = INT16_MAX; int32_t t153 = INT32_MIN; static int32_t x700 = INT32_MIN; int32_t x712 = INT32_MAX; static int64_t x713 = -1LL; int64_t x716 = 18LL; uint16_t x726 = UINT16_MAX; int32_t x730 = -1; int16_t x732 = INT16_MIN; uint64_t x733 = UINT64_MAX; uint8_t x735 = 23U; static uint16_t x738 = 65U; int8_t x739 = INT8_MAX; volatile uint16_t x740 = UINT16_MAX; int32_t t163 = 183; volatile int32_t t164 = -173288128; int16_t x746 = -1; volatile int32_t t165 = -51; static int32_t x750 = -1628037; uint32_t x753 = UINT32_MAX; int64_t x756 = 1LL; static volatile int64_t t167 = 120691888118LL; uint32_t x762 = 2260U; int64_t x803 = INT64_MIN; uint64_t x807 = UINT64_MAX; static volatile uint64_t t177 = 65382LLU; int8_t x810 = INT8_MIN; uint8_t x811 = UINT8_MAX; uint16_t x813 = 1U; int8_t x816 = 0; int32_t x825 = 7007977; int8_t x830 = -8; int64_t x832 = INT64_MIN; uint32_t x842 = 2634505U; static int8_t x843 = -61; int64_t x844 = INT64_MIN; int8_t x846 = -1; static int32_t x849 = 41; int8_t x881 = INT8_MIN; static uint64_t x883 = UINT64_MAX; volatile int8_t x886 = 0; volatile uint32_t x905 = 267846821U; volatile int8_t x910 = INT8_MIN; int16_t x916 = INT16_MIN; uint64_t t198 = 108LLU; volatile uint32_t t199 = 252194245U; void f0(void) { uint8_t x1 = 6U; uint64_t x2 = 423LLU; int16_t x3 = INT16_MAX; int16_t x4 = INT16_MIN; volatile uint64_t t0 = 52495197LLU; t0 = (((x1+x2)&x3)+x4); if (t0 != 18446744073709519277LLU) { NG(); } else { ; } } void f1(void) { volatile int8_t x5 = -1; int64_t x6 = 996LL; volatile uint32_t x7 = 1U; int64_t t1 = -648020223363LL; t1 = (((x5+x6)&x7)+x8); if (t1 != 2561882LL) { NG(); } else { ; } } void f2(void) { volatile int8_t x9 = INT8_MIN; static int8_t x10 = -1; static uint8_t x11 = 0U; int8_t x12 = INT8_MIN; volatile int32_t t2 = -2; t2 = (((x9+x10)&x11)+x12); if (t2 != -128) { NG(); } else { ; } } void f3(void) { int32_t x13 = -1; int32_t x14 = -2; int64_t x15 = 776LL; uint32_t x16 = UINT32_MAX; volatile int64_t t3 = 447703132420LL; t3 = (((x13+x14)&x15)+x16); if (t3 != 4294968071LL) { NG(); } else { ; } } void f4(void) { uint16_t x17 = 3629U; volatile int8_t x18 = -26; uint8_t x19 = 20U; volatile int8_t x20 = INT8_MIN; int32_t t4 = 3; t4 = (((x17+x18)&x19)+x20); if (t4 != -112) { NG(); } else { ; } } void f5(void) { static int16_t x21 = INT16_MAX; int64_t x22 = 34441787133980LL; uint64_t x23 = 23538799823503812LLU; int32_t x24 = INT32_MIN; static volatile uint64_t t5 = 65870741001945861LLU; t5 = (((x21+x22)&x23)+x24); if (t5 != 277166505984LLU) { NG(); } else { ; } } void f6(void) { volatile uint16_t x25 = 20U; static int16_t x26 = 455; static uint16_t x27 = 5713U; uint16_t x28 = 1U; static volatile int32_t t6 = 1145; t6 = (((x25+x26)&x27)+x28); if (t6 != 82) { NG(); } else { ; } } void f7(void) { volatile uint32_t x30 = 357012U; int64_t x31 = 15210LL; volatile int64_t x32 = INT64_MIN; t7 = (((x29+x30)&x31)+x32); if (t7 != 9223372036854786058LLU) { NG(); } else { ; } } void f8(void) { int64_t x33 = INT64_MIN; uint8_t x34 = 15U; uint32_t x36 = 55079709U; t8 = (((x33+x34)&x35)+x36); if (t8 != -9223372036799696091LL) { NG(); } else { ; } } void f9(void) { static int8_t x37 = INT8_MAX; volatile int8_t x39 = INT8_MAX; uint64_t x40 = 49724725419LLU; t9 = (((x37+x38)&x39)+x40); if (t9 != 49724725545LLU) { NG(); } else { ; } } void f10(void) { volatile int8_t x49 = INT8_MAX; int8_t x50 = 1; int16_t x51 = INT16_MIN; uint8_t x52 = 0U; int32_t t10 = -352; t10 = (((x49+x50)&x51)+x52); if (t10 != 0) { NG(); } else { ; } } void f11(void) { uint16_t x53 = 106U; uint8_t x55 = 27U; int16_t x56 = INT16_MAX; int32_t t11 = 6014; t11 = (((x53+x54)&x55)+x56); if (t11 != 32793) { NG(); } else { ; } } void f12(void) { volatile uint64_t x57 = 109484762401LLU; static volatile int64_t x58 = INT64_MIN; int16_t x59 = -1; int64_t x60 = -1LL; uint64_t t12 = 1436654342712LLU; t12 = (((x57+x58)&x59)+x60); if (t12 != 9223372146339538208LLU) { NG(); } else { ; } } void f13(void) { int16_t x65 = INT16_MAX; static int8_t x66 = INT8_MIN; static uint16_t x68 = 27U; int32_t t13 = 38717809; t13 = (((x65+x66)&x67)+x68); if (t13 != 44) { NG(); } else { ; } } void f14(void) { int64_t x69 = -1LL; static volatile int64_t x72 = INT64_MIN; volatile int64_t t14 = 36863052656305LL; t14 = (((x69+x70)&x71)+x72); if (t14 != -9223372036854775801LL) { NG(); } else { ; } } void f15(void) { int8_t x73 = -1; static uint64_t x74 = UINT64_MAX; int64_t x76 = INT64_MIN; t15 = (((x73+x74)&x75)+x76); if (t15 != 9223372036854775680LLU) { NG(); } else { ; } } void f16(void) { uint32_t x85 = UINT32_MAX; int8_t x86 = INT8_MIN; static int64_t x88 = INT64_MIN; int64_t t16 = 1077984508098927545LL; t16 = (((x85+x86)&x87)+x88); if (t16 != -9223372032559808678LL) { NG(); } else { ; } } void f17(void) { volatile int8_t x89 = INT8_MAX; uint8_t x90 = 120U; volatile int64_t x91 = -180976600615224LL; int8_t x92 = INT8_MIN; int64_t t17 = -4647104076LL; t17 = (((x89+x90)&x91)+x92); if (t17 != 64LL) { NG(); } else { ; } } void f18(void) { static int16_t x94 = INT16_MIN; uint16_t x95 = 12U; static uint16_t x96 = 764U; static int32_t t18 = -3666824; t18 = (((x93+x94)&x95)+x96); if (t18 != 776) { NG(); } else { ; } } void f19(void) { int8_t x101 = INT8_MIN; volatile int64_t x102 = -14789285776813972LL; int8_t x103 = INT8_MIN; volatile int64_t t19 = 669001008203622LL; t19 = (((x101+x102)&x103)+x104); if (t19 != -14789285702748087LL) { NG(); } else { ; } } void f20(void) { volatile int32_t x105 = -19; int16_t x106 = INT16_MAX; int64_t x107 = -37LL; static uint64_t x108 = 278398658583447814LLU; uint64_t t20 = 3LLU; t20 = (((x105+x106)&x107)+x108); if (t20 != 278398658583480526LLU) { NG(); } else { ; } } void f21(void) { int16_t x109 = -3; uint16_t x110 = UINT16_MAX; int64_t x111 = INT64_MAX; int64_t x112 = INT64_MIN; volatile int64_t t21 = 154533639LL; t21 = (((x109+x110)&x111)+x112); if (t21 != -9223372036854710276LL) { NG(); } else { ; } } void f22(void) { uint64_t x117 = UINT64_MAX; int8_t x118 = -1; int64_t x120 = INT64_MAX; uint64_t t22 = 102LLU; t22 = (((x117+x118)&x119)+x120); if (t22 != 9223372036854775811LLU) { NG(); } else { ; } } void f23(void) { volatile int16_t x125 = INT16_MIN; uint16_t x126 = UINT16_MAX; int8_t x128 = -1; volatile int32_t t23 = 852660781; t23 = (((x125+x126)&x127)+x128); if (t23 != 11015) { NG(); } else { ; } } void f24(void) { volatile uint8_t x129 = UINT8_MAX; int8_t x130 = INT8_MIN; uint8_t x131 = UINT8_MAX; static int32_t x132 = 0; static int32_t t24 = -63; t24 = (((x129+x130)&x131)+x132); if (t24 != 127) { NG(); } else { ; } } void f25(void) { static uint64_t x133 = 90330508LLU; static int16_t x134 = -1; int16_t x136 = 1483; static volatile uint64_t t25 = 177505LLU; t25 = (((x133+x134)&x135)+x136); if (t25 != 1484LLU) { NG(); } else { ; } } void f26(void) { uint64_t x138 = UINT64_MAX; uint64_t x139 = UINT64_MAX; static int32_t x140 = INT32_MAX; uint64_t t26 = 140205LLU; t26 = (((x137+x138)&x139)+x140); if (t26 != 18446744073709551614LLU) { NG(); } else { ; } } void f27(void) { int8_t x141 = -1; int32_t x143 = -1; static int64_t x144 = INT64_MIN; volatile int64_t t27 = 2044284900LL; t27 = (((x141+x142)&x143)+x144); if (t27 != -9223372036854775554LL) { NG(); } else { ; } } void f28(void) { int8_t x145 = INT8_MAX; static int16_t x146 = 8; volatile int8_t x147 = 59; static uint64_t x148 = UINT64_MAX; uint64_t t28 = 2479672LLU; t28 = (((x145+x146)&x147)+x148); if (t28 != 2LLU) { NG(); } else { ; } } void f29(void) { int64_t x149 = 87035LL; volatile uint16_t x151 = 185U; int16_t x152 = INT16_MIN; t29 = (((x149+x150)&x151)+x152); if (t29 != -32583LL) { NG(); } else { ; } } void f30(void) { int8_t x153 = 60; static volatile int16_t x155 = INT16_MIN; static volatile uint64_t x156 = 121786741LLU; static volatile uint64_t t30 = 7261729LLU; t30 = (((x153+x154)&x155)+x156); if (t30 != 121786741LLU) { NG(); } else { ; } } void f31(void) { int64_t x157 = INT64_MIN; volatile uint64_t x158 = 2332649348066886548LLU; int32_t x159 = INT32_MIN; volatile int16_t x160 = -12304; t31 = (((x157+x158)&x159)+x160); if (t31 != 11556021384366772208LLU) { NG(); } else { ; } } void f32(void) { static int16_t x161 = -245; int64_t x162 = INT64_MAX; volatile uint64_t x164 = UINT64_MAX; static uint64_t t32 = 39993807LLU; t32 = (((x161+x162)&x163)+x164); if (t32 != 9223372036854775551LLU) { NG(); } else { ; } } void f33(void) { int16_t x165 = -1; uint16_t x166 = UINT16_MAX; static uint32_t x167 = 3116U; int8_t x168 = INT8_MIN; volatile uint32_t t33 = 2U; t33 = (((x165+x166)&x167)+x168); if (t33 != 2988U) { NG(); } else { ; } } void f34(void) { int16_t x169 = INT16_MIN; volatile uint8_t x170 = 0U; uint16_t x171 = 61U; int8_t x172 = 27; int32_t t34 = 17; t34 = (((x169+x170)&x171)+x172); if (t34 != 27) { NG(); } else { ; } } void f35(void) { uint64_t x173 = 6972075895122047LLU; static uint8_t x174 = 8U; volatile uint8_t x175 = UINT8_MAX; uint8_t x176 = 0U; static uint64_t t35 = 807339980963LLU; t35 = (((x173+x174)&x175)+x176); if (t35 != 135LLU) { NG(); } else { ; } } void f36(void) { static int64_t x177 = -1LL; volatile uint32_t x178 = 1U; volatile uint16_t x179 = UINT16_MAX; int8_t x180 = INT8_MIN; volatile int64_t t36 = -11297LL; t36 = (((x177+x178)&x179)+x180); if (t36 != -128LL) { NG(); } else { ; } } void f37(void) { uint64_t x181 = UINT64_MAX; int32_t x183 = INT32_MIN; t37 = (((x181+x182)&x183)+x184); if (t37 != 9223372032559808511LLU) { NG(); } else { ; } } void f38(void) { int8_t x185 = INT8_MAX; static int16_t x186 = INT16_MIN; uint64_t x187 = UINT64_MAX; t38 = (((x185+x186)&x187)+x188); if (t38 != 18446744073709519125LLU) { NG(); } else { ; } } void f39(void) { volatile uint16_t x189 = UINT16_MAX; static int32_t x191 = 4551939; uint32_t x192 = 3708U; uint32_t t39 = 10755293U; t39 = (((x189+x190)&x191)+x192); if (t39 != 69246U) { NG(); } else { ; } } void f40(void) { uint64_t x195 = UINT64_MAX; t40 = (((x193+x194)&x195)+x196); if (t40 != 9223372036854841166LLU) { NG(); } else { ; } } void f41(void) { int64_t x197 = -3713390570LL; int32_t x198 = INT32_MIN; uint64_t x200 = 785978236337126LLU; uint64_t t41 = 2666056LLU; t41 = (((x197+x198)&x199)+x200); if (t41 != 785972375462908LLU) { NG(); } else { ; } } void f42(void) { volatile int64_t t42 = -7409LL; t42 = (((x201+x202)&x203)+x204); if (t42 != 88514LL) { NG(); } else { ; } } void f43(void) { static uint16_t x205 = 4986U; static int8_t x206 = INT8_MAX; volatile int16_t x207 = -1; static int32_t x208 = INT32_MIN; volatile int32_t t43 = -157700668; t43 = (((x205+x206)&x207)+x208); if (t43 != -2147478535) { NG(); } else { ; } } void f44(void) { uint32_t x209 = 134U; volatile uint8_t x210 = 2U; static int16_t x211 = INT16_MIN; int64_t x212 = INT64_MIN; volatile int64_t t44 = INT64_MIN; t44 = (((x209+x210)&x211)+x212); if (t44 != INT64_MIN) { NG(); } else { ; } } void f45(void) { static volatile uint8_t x213 = 12U; uint8_t x215 = 91U; volatile int64_t t45 = 31547342LL; t45 = (((x213+x214)&x215)+x216); if (t45 != -9223372036854775800LL) { NG(); } else { ; } } void f46(void) { volatile uint8_t x217 = 1U; int8_t x218 = -38; uint32_t x219 = 823111U; uint32_t x220 = UINT32_MAX; uint32_t t46 = 317U; t46 = (((x217+x218)&x219)+x220); if (t46 != 823106U) { NG(); } else { ; } } void f47(void) { uint32_t x221 = UINT32_MAX; static uint32_t x223 = 10U; uint8_t x224 = 1U; volatile uint32_t t47 = 6785U; t47 = (((x221+x222)&x223)+x224); if (t47 != 11U) { NG(); } else { ; } } void f48(void) { int8_t x225 = INT8_MIN; static uint8_t x226 = UINT8_MAX; uint32_t x227 = UINT32_MAX; t48 = (((x225+x226)&x227)+x228); if (t48 != 382U) { NG(); } else { ; } } void f49(void) { static int16_t x231 = INT16_MIN; static int8_t x232 = -1; int32_t t49 = 246; t49 = (((x229+x230)&x231)+x232); if (t49 != -32769) { NG(); } else { ; } } void f50(void) { uint32_t x233 = 32628U; static int16_t x234 = INT16_MIN; static uint64_t x235 = 2088673913093LLU; int16_t x236 = INT16_MIN; uint64_t t50 = 2115855878625LLU; t50 = (((x233+x234)&x235)+x236); if (t50 != 1319774468LLU) { NG(); } else { ; } } void f51(void) { int64_t x237 = 124161472362LL; static int8_t x238 = INT8_MIN; int8_t x240 = INT8_MIN; t51 = (((x237+x238)&x239)+x240); if (t51 != -96LL) { NG(); } else { ; } } void f52(void) { int64_t x241 = INT64_MIN; uint16_t x242 = 5U; uint8_t x243 = 5U; int32_t x244 = 1; volatile int64_t t52 = 24295030377LL; t52 = (((x241+x242)&x243)+x244); if (t52 != 6LL) { NG(); } else { ; } } void f53(void) { int16_t x245 = -19; int8_t x246 = INT8_MAX; int64_t x247 = INT64_MIN; volatile int64_t t53 = -15LL; t53 = (((x245+x246)&x247)+x248); if (t53 != 65535LL) { NG(); } else { ; } } void f54(void) { uint16_t x250 = 27418U; static uint32_t x251 = UINT32_MAX; static volatile int16_t x252 = -13; volatile int64_t t54 = 29LL; t54 = (((x249+x250)&x251)+x252); if (t54 != 27405LL) { NG(); } else { ; } } void f55(void) { uint64_t x253 = 16565525687LLU; int8_t x254 = INT8_MIN; int16_t x255 = INT16_MIN; uint8_t x256 = 1U; uint64_t t55 = 6882079288119LLU; t55 = (((x253+x254)&x255)+x256); if (t55 != 16565501953LLU) { NG(); } else { ; } } void f56(void) { uint8_t x257 = 45U; volatile int16_t x259 = INT16_MAX; int8_t x260 = INT8_MIN; volatile int32_t t56 = 479549667; t56 = (((x257+x258)&x259)+x260); if (t56 != 31405) { NG(); } else { ; } } void f57(void) { int64_t x261 = 8285921698152LL; int8_t x262 = -1; static int16_t x263 = 127; volatile int8_t x264 = 1; volatile int64_t t57 = -174174069977033LL; t57 = (((x261+x262)&x263)+x264); if (t57 != 104LL) { NG(); } else { ; } } void f58(void) { uint32_t x265 = 6403498U; volatile uint16_t x266 = 1U; int32_t x267 = 675861; int8_t x268 = -1; uint32_t t58 = 5U; t58 = (((x265+x266)&x267)+x268); if (t58 != 4096U) { NG(); } else { ; } } void f59(void) { static int8_t x269 = INT8_MIN; uint8_t x270 = UINT8_MAX; volatile int32_t x271 = INT32_MAX; int32_t t59 = -186061; t59 = (((x269+x270)&x271)+x272); if (t59 != 254) { NG(); } else { ; } } void f60(void) { int64_t x274 = 55437693278LL; static int64_t x276 = 1871638725509964235LL; static int64_t t60 = 222LL; t60 = (((x273+x274)&x275)+x276); if (t60 != 1871638780947657768LL) { NG(); } else { ; } } void f61(void) { uint64_t x277 = UINT64_MAX; int16_t x278 = INT16_MAX; int64_t x280 = INT64_MIN; uint64_t t61 = 0LLU; t61 = (((x277+x278)&x279)+x280); if (t61 != 9223372036854776062LLU) { NG(); } else { ; } } void f62(void) { static uint64_t x281 = 135902550LLU; int16_t x282 = INT16_MIN; volatile int8_t x283 = -1; int32_t x284 = 1819; volatile uint64_t t62 = 432298779LLU; t62 = (((x281+x282)&x283)+x284); if (t62 != 135871601LLU) { NG(); } else { ; } } void f63(void) { static volatile int16_t x285 = INT16_MIN; int32_t x286 = 688418072; static int8_t x287 = -1; volatile uint32_t x288 = UINT32_MAX; volatile uint32_t t63 = 12988U; t63 = (((x285+x286)&x287)+x288); if (t63 != 688385303U) { NG(); } else { ; } } void f64(void) { static int16_t x294 = -1; volatile int16_t x295 = INT16_MAX; static uint64_t x296 = 8007294880LLU; t64 = (((x293+x294)&x295)+x296); if (t64 != 8007327519LLU) { NG(); } else { ; } } void f65(void) { static int64_t x297 = -1LL; static int16_t x298 = INT16_MIN; volatile int16_t x299 = INT16_MIN; volatile int64_t t65 = -6782305295LL; t65 = (((x297+x298)&x299)+x300); if (t65 != -65536LL) { NG(); } else { ; } } void f66(void) { int8_t x301 = 1; int8_t x303 = INT8_MIN; uint16_t x304 = UINT16_MAX; volatile uint64_t t66 = 319155LLU; t66 = (((x301+x302)&x303)+x304); if (t66 != 65535LLU) { NG(); } else { ; } } void f67(void) { static volatile uint64_t x306 = UINT64_MAX; static volatile uint8_t x307 = UINT8_MAX; uint8_t x308 = 2U; volatile uint64_t t67 = 30363084147LLU; t67 = (((x305+x306)&x307)+x308); if (t67 != 256LLU) { NG(); } else { ; } } void f68(void) { static uint8_t x315 = 4U; int32_t t68 = 55301; t68 = (((x313+x314)&x315)+x316); if (t68 != -124) { NG(); } else { ; } } void f69(void) { static uint8_t x317 = 31U; uint16_t x318 = 7U; int8_t x319 = -10; uint8_t x320 = 2U; int32_t t69 = 959911163; t69 = (((x317+x318)&x319)+x320); if (t69 != 40) { NG(); } else { ; } } void f70(void) { int16_t x321 = INT16_MIN; int64_t x323 = 3LL; int64_t t70 = -398694LL; t70 = (((x321+x322)&x323)+x324); if (t70 != -7LL) { NG(); } else { ; } } void f71(void) { volatile int64_t x325 = INT64_MIN; volatile int8_t x327 = 0; int64_t x328 = INT64_MIN; volatile uint64_t t71 = 1104758LLU; t71 = (((x325+x326)&x327)+x328); if (t71 != 9223372036854775808LLU) { NG(); } else { ; } } void f72(void) { static int16_t x329 = INT16_MIN; int32_t x330 = -1; int32_t x331 = -1; int8_t x332 = INT8_MIN; static volatile int32_t t72 = -192336651; t72 = (((x329+x330)&x331)+x332); if (t72 != -32897) { NG(); } else { ; } } void f73(void) { int32_t x333 = -1; int16_t x334 = INT16_MIN; volatile uint64_t x335 = 2LLU; uint32_t x336 = UINT32_MAX; static volatile uint64_t t73 = 1619LLU; t73 = (((x333+x334)&x335)+x336); if (t73 != 4294967297LLU) { NG(); } else { ; } } void f74(void) { int32_t x338 = 568175; uint8_t x339 = UINT8_MAX; static volatile int32_t t74 = 7714595; t74 = (((x337+x338)&x339)+x340); if (t74 != -2147483524) { NG(); } else { ; } } void f75(void) { uint8_t x342 = 0U; static uint32_t x343 = 325057U; volatile int32_t x344 = INT32_MIN; t75 = (((x341+x342)&x343)+x344); if (t75 != 2147483648U) { NG(); } else { ; } } void f76(void) { int64_t x348 = INT64_MIN; volatile uint64_t t76 = 12675080996LLU; t76 = (((x345+x346)&x347)+x348); if (t76 != 9223372036854776090LLU) { NG(); } else { ; } } void f77(void) { uint16_t x349 = 7U; static int16_t x350 = INT16_MIN; uint32_t x351 = 175906111U; t77 = (((x349+x350)&x351)+x352); if (t77 != 175898630U) { NG(); } else { ; } } void f78(void) { volatile int16_t x353 = 0; static uint32_t x355 = 3U; int32_t x356 = INT32_MAX; static uint32_t t78 = 72876717U; t78 = (((x353+x354)&x355)+x356); if (t78 != 2147483650U) { NG(); } else { ; } } void f79(void) { static int8_t x357 = INT8_MIN; static uint8_t x358 = UINT8_MAX; uint32_t x359 = 164U; int32_t x360 = INT32_MIN; uint32_t t79 = 13U; t79 = (((x357+x358)&x359)+x360); if (t79 != 2147483684U) { NG(); } else { ; } } void f80(void) { uint32_t x361 = 208U; int16_t x362 = -1; int64_t x363 = INT64_MAX; int64_t x364 = -754021320LL; t80 = (((x361+x362)&x363)+x364); if (t80 != -754021113LL) { NG(); } else { ; } } void f81(void) { int32_t x365 = INT32_MIN; uint8_t x366 = UINT8_MAX; int32_t x367 = -1481043; volatile int64_t x368 = 132392276324535190LL; static int64_t t81 = -21402046340402LL; t81 = (((x365+x366)&x367)+x368); if (t81 != 132392274177051715LL) { NG(); } else { ; } } void f82(void) { int8_t x369 = INT8_MIN; int8_t x370 = INT8_MIN; volatile int8_t x371 = -2; int8_t x372 = INT8_MIN; volatile int32_t t82 = 2766; t82 = (((x369+x370)&x371)+x372); if (t82 != -384) { NG(); } else { ; } } void f83(void) { int8_t x373 = 1; uint16_t x374 = 5U; uint16_t x375 = UINT16_MAX; volatile int64_t x376 = -3447842LL; int64_t t83 = 114436LL; t83 = (((x373+x374)&x375)+x376); if (t83 != -3447836LL) { NG(); } else { ; } } void f84(void) { int16_t x377 = 4; uint16_t x378 = 1215U; int64_t x380 = -209876164586119027LL; int64_t t84 = -304298LL; t84 = (((x377+x378)&x379)+x380); if (t84 != -209876164586117808LL) { NG(); } else { ; } } void f85(void) { volatile uint32_t x384 = 23561U; int64_t t85 = 5769LL; t85 = (((x381+x382)&x383)+x384); if (t85 != -9223372036840038549LL) { NG(); } else { ; } } void f86(void) { uint64_t x385 = 11260412561LLU; uint32_t x386 = 1341084U; uint64_t x387 = UINT64_MAX; int64_t x388 = INT64_MIN; volatile uint64_t t86 = 21LLU; t86 = (((x385+x386)&x387)+x388); if (t86 != 9223372048116529453LLU) { NG(); } else { ; } } void f87(void) { int16_t x389 = -1; uint64_t x391 = 3LLU; int32_t x392 = -1; t87 = (((x389+x390)&x391)+x392); if (t87 != 2LLU) { NG(); } else { ; } } void f88(void) { static int64_t x393 = 264650312852091LL; volatile int64_t x394 = INT64_MIN; uint32_t x396 = UINT32_MAX; static volatile int64_t t88 = -138963294246964LL; t88 = (((x393+x394)&x395)+x396); if (t88 != -9223107383117479937LL) { NG(); } else { ; } } void f89(void) { volatile uint64_t x401 = 1LLU; uint64_t x402 = UINT64_MAX; int64_t x403 = -342574LL; int8_t x404 = -14; uint64_t t89 = 2267588088403028148LLU; t89 = (((x401+x402)&x403)+x404); if (t89 != 18446744073709551602LLU) { NG(); } else { ; } } void f90(void) { int32_t x405 = INT32_MIN; uint16_t x408 = UINT16_MAX; volatile int32_t t90 = 443194; t90 = (((x405+x406)&x407)+x408); if (t90 != 65662) { NG(); } else { ; } } void f91(void) { uint16_t x409 = UINT16_MAX; uint16_t x411 = UINT16_MAX; static int64_t x412 = -24815325LL; static int64_t t91 = -4028956177047LL; t91 = (((x409+x410)&x411)+x412); if (t91 != -24815300LL) { NG(); } else { ; } } void f92(void) { int8_t x414 = INT8_MIN; volatile int16_t x415 = 381; int8_t x416 = INT8_MAX; int32_t t92 = 30; t92 = (((x413+x414)&x415)+x416); if (t92 != 508) { NG(); } else { ; } } void f93(void) { uint64_t x417 = 251654182333548596LLU; static uint16_t x418 = 5U; int16_t x419 = -1; static uint64_t x420 = 20486885LLU; static uint64_t t93 = 719166LLU; t93 = (((x417+x418)&x419)+x420); if (t93 != 251654182354035486LLU) { NG(); } else { ; } } void f94(void) { static int32_t x426 = 517991; int32_t x427 = INT32_MAX; int64_t x428 = 41288LL; t94 = (((x425+x426)&x427)+x428); if (t94 != 559282LL) { NG(); } else { ; } } void f95(void) { uint64_t x433 = UINT64_MAX; volatile int16_t x434 = -1; int16_t x435 = INT16_MIN; t95 = (((x433+x434)&x435)+x436); if (t95 != 18446744073709518847LLU) { NG(); } else { ; } } void f96(void) { uint16_t x437 = UINT16_MAX; int16_t x438 = -1; int64_t x439 = INT64_MAX; static volatile int64_t x440 = INT64_MIN; volatile int64_t t96 = -2620239310763978LL; t96 = (((x437+x438)&x439)+x440); if (t96 != -9223372036854710274LL) { NG(); } else { ; } } void f97(void) { int8_t x441 = 6; uint8_t x443 = UINT8_MAX; int16_t x444 = INT16_MIN; static int32_t t97 = 1; t97 = (((x441+x442)&x443)+x444); if (t97 != -32763) { NG(); } else { ; } } void f98(void) { int64_t x445 = -1943888422441LL; volatile int16_t x446 = INT16_MAX; int32_t x448 = -1; int64_t t98 = 4LL; t98 = (((x445+x446)&x447)+x448); if (t98 != 3LL) { NG(); } else { ; } } void f99(void) { uint64_t x449 = 2763437LLU; int32_t x450 = INT32_MAX; int8_t x452 = INT8_MAX; volatile uint64_t t99 = 41840737715562790LLU; t99 = (((x449+x450)&x451)+x452); if (t99 != 127LLU) { NG(); } else { ; } } void f100(void) { volatile int64_t x453 = INT64_MIN; int8_t x454 = INT8_MAX; static volatile uint64_t x455 = UINT64_MAX; static int16_t x456 = 555; t100 = (((x453+x454)&x455)+x456); if (t100 != 9223372036854776490LLU) { NG(); } else { ; } } void f101(void) { int16_t x457 = -1; int16_t x458 = 0; static uint16_t x459 = 14U; static volatile int32_t x460 = -19; int32_t t101 = 2887; t101 = (((x457+x458)&x459)+x460); if (t101 != -5) { NG(); } else { ; } } void f102(void) { volatile int8_t x461 = INT8_MAX; int64_t x463 = INT64_MIN; uint16_t x464 = UINT16_MAX; volatile int64_t t102 = 2685250721LL; t102 = (((x461+x462)&x463)+x464); if (t102 != 65535LL) { NG(); } else { ; } } void f103(void) { int16_t x469 = -1; int64_t x471 = -1LL; int32_t x472 = 1154376; static int64_t t103 = 991LL; t103 = (((x469+x470)&x471)+x472); if (t103 != 1154374LL) { NG(); } else { ; } } void f104(void) { uint32_t x473 = UINT32_MAX; int32_t x475 = INT32_MIN; int16_t x476 = INT16_MIN; static uint32_t t104 = 241973U; t104 = (((x473+x474)&x475)+x476); if (t104 != 4294934528U) { NG(); } else { ; } } void f105(void) { uint64_t x482 = 488363LLU; int64_t x483 = -1LL; static volatile uint32_t x484 = UINT32_MAX; volatile uint64_t t105 = 61164LLU; t105 = (((x481+x482)&x483)+x484); if (t105 != 4295422890LLU) { NG(); } else { ; } } void f106(void) { int8_t x485 = -5; int32_t x486 = -450621854; static int64_t x487 = -1194159209808LL; static int64_t t106 = 1LL; t106 = (((x485+x486)&x487)+x488); if (t106 != -1194470669809LL) { NG(); } else { ; } } void f107(void) { uint64_t x490 = UINT64_MAX; int8_t x491 = -1; int32_t x492 = INT32_MIN; volatile uint64_t t107 = 481LLU; t107 = (((x489+x490)&x491)+x492); if (t107 != 18446744071562067839LLU) { NG(); } else { ; } } void f108(void) { int64_t x493 = 1165080690099650666LL; static int16_t x494 = INT16_MIN; static uint8_t x495 = UINT8_MAX; volatile int64_t t108 = -113363LL; t108 = (((x493+x494)&x495)+x496); if (t108 != 70LL) { NG(); } else { ; } } void f109(void) { static int32_t x497 = -1; static volatile uint32_t x498 = UINT32_MAX; int16_t x499 = INT16_MAX; int16_t x500 = INT16_MIN; volatile uint32_t t109 = 14U; t109 = (((x497+x498)&x499)+x500); if (t109 != 4294967294U) { NG(); } else { ; } } void f110(void) { int64_t x502 = 1LL; uint8_t x503 = 57U; uint32_t x504 = 79807U; volatile int64_t t110 = -82576564765916LL; t110 = (((x501+x502)&x503)+x504); if (t110 != 79855LL) { NG(); } else { ; } } void f111(void) { uint16_t x505 = 12421U; volatile uint64_t x506 = 464313979506802LLU; static uint32_t x507 = UINT32_MAX; t111 = (((x505+x506)&x507)+x508); if (t111 != 2245091779LLU) { NG(); } else { ; } } void f112(void) { int16_t x509 = INT16_MAX; int32_t x510 = INT32_MIN; volatile uint8_t x511 = UINT8_MAX; int64_t x512 = 0LL; int64_t t112 = 231615139824LL; t112 = (((x509+x510)&x511)+x512); if (t112 != 255LL) { NG(); } else { ; } } void f113(void) { int64_t x514 = -1LL; static int16_t x516 = INT16_MIN; int64_t t113 = 163634LL; t113 = (((x513+x514)&x515)+x516); if (t113 != -32759LL) { NG(); } else { ; } } void f114(void) { int16_t x517 = INT16_MIN; int64_t x518 = 551633941495LL; static int32_t x519 = -3864340; volatile int32_t x520 = -1; volatile int64_t t114 = 504LL; t114 = (((x517+x518)&x519)+x520); if (t114 != 551630733539LL) { NG(); } else { ; } } void f115(void) { static int64_t x522 = -1LL; uint64_t x523 = 371LLU; static int8_t x524 = INT8_MAX; static uint64_t t115 = 6103052749915838712LLU; t115 = (((x521+x522)&x523)+x524); if (t115 != 498LLU) { NG(); } else { ; } } void f116(void) { int8_t x525 = INT8_MIN; int8_t x526 = -1; volatile int8_t x527 = -1; volatile int32_t x528 = INT32_MAX; int32_t t116 = 2062403; t116 = (((x525+x526)&x527)+x528); if (t116 != 2147483518) { NG(); } else { ; } } void f117(void) { int16_t x530 = -1; int8_t x531 = INT8_MIN; t117 = (((x529+x530)&x531)+x532); if (t117 != 255) { NG(); } else { ; } } void f118(void) { uint8_t x533 = UINT8_MAX; int8_t x534 = INT8_MIN; uint32_t x536 = UINT32_MAX; static uint32_t t118 = 0U; t118 = (((x533+x534)&x535)+x536); if (t118 != 126U) { NG(); } else { ; } } void f119(void) { uint16_t x537 = 1U; volatile int32_t x538 = 27492908; uint64_t x539 = UINT64_MAX; int16_t x540 = INT16_MIN; volatile uint64_t t119 = 3109131312763LLU; t119 = (((x537+x538)&x539)+x540); if (t119 != 27460141LLU) { NG(); } else { ; } } void f120(void) { int16_t x541 = 6693; uint8_t x542 = UINT8_MAX; volatile uint64_t x543 = 1LLU; uint64_t t120 = 2522228768460LLU; t120 = (((x541+x542)&x543)+x544); if (t120 != 7610LLU) { NG(); } else { ; } } void f121(void) { static int32_t x546 = -1; int16_t x548 = 0; int32_t t121 = -61237; t121 = (((x545+x546)&x547)+x548); if (t121 != 0) { NG(); } else { ; } } void f122(void) { static uint64_t x549 = UINT64_MAX; static int64_t x550 = INT64_MIN; static volatile int16_t x551 = -2281; int8_t x552 = INT8_MIN; t122 = (((x549+x550)&x551)+x552); if (t122 != 9223372036854773399LLU) { NG(); } else { ; } } void f123(void) { int32_t x553 = 503669; static volatile int8_t x554 = INT8_MIN; static uint16_t x556 = 121U; int32_t t123 = 11485990; t123 = (((x553+x554)&x555)+x556); if (t123 != 718) { NG(); } else { ; } } void f124(void) { int8_t x557 = -1; uint8_t x558 = UINT8_MAX; static volatile int16_t x559 = INT16_MIN; int32_t x560 = -1; static volatile int32_t t124 = 8668355; t124 = (((x557+x558)&x559)+x560); if (t124 != -1) { NG(); } else { ; } } void f125(void) { int32_t x561 = INT32_MAX; static uint64_t x562 = UINT64_MAX; uint32_t x563 = 484485549U; int32_t x564 = -1; t125 = (((x561+x562)&x563)+x564); if (t125 != 484485547LLU) { NG(); } else { ; } } void f126(void) { static int64_t x565 = INT64_MIN; static uint8_t x566 = 3U; uint64_t x568 = 33LLU; static uint64_t t126 = 5150748LLU; t126 = (((x565+x566)&x567)+x568); if (t126 != 9223372036854775844LLU) { NG(); } else { ; } } void f127(void) { int64_t x569 = -120169813290307LL; static int16_t x571 = INT16_MIN; int8_t x572 = INT8_MIN; volatile int64_t t127 = -9277070289LL; t127 = (((x569+x570)&x571)+x572); if (t127 != -120169813311616LL) { NG(); } else { ; } } void f128(void) { uint64_t x573 = 66326246443915219LLU; volatile int16_t x574 = INT16_MIN; int32_t x575 = INT32_MAX; uint64_t x576 = 31020034LLU; uint64_t t128 = 56LLU; t128 = (((x573+x574)&x575)+x576); if (t128 != 678161365LLU) { NG(); } else { ; } } void f129(void) { static int16_t x577 = INT16_MIN; uint32_t x579 = UINT32_MAX; int64_t x580 = 12539032168LL; int64_t t129 = 32779648052868495LL; t129 = (((x577+x578)&x579)+x580); if (t129 != 16833966654LL) { NG(); } else { ; } } void f130(void) { volatile int64_t x583 = 6082821876LL; int32_t x584 = INT32_MAX; volatile int64_t t130 = 18997039LL; t130 = (((x581+x582)&x583)+x584); if (t130 != 8230305347LL) { NG(); } else { ; } } void f131(void) { static int8_t x586 = INT8_MIN; uint32_t x587 = 1U; static volatile int8_t x588 = INT8_MIN; static volatile int64_t t131 = 5460908647LL; t131 = (((x585+x586)&x587)+x588); if (t131 != -127LL) { NG(); } else { ; } } void f132(void) { uint64_t x589 = 276LLU; volatile uint16_t x590 = 849U; int64_t x592 = INT64_MIN; static uint64_t t132 = 109LLU; t132 = (((x589+x590)&x591)+x592); if (t132 != 9223372036854775808LLU) { NG(); } else { ; } } void f133(void) { int32_t x593 = INT32_MAX; int8_t x595 = -7; volatile uint64_t x596 = 12LLU; static uint64_t t133 = 706LLU; t133 = (((x593+x594)&x595)+x596); if (t133 != 2147483652LLU) { NG(); } else { ; } } void f134(void) { static uint16_t x597 = UINT16_MAX; uint16_t x598 = 0U; int8_t x599 = -1; uint16_t x600 = UINT16_MAX; int32_t t134 = 54888; t134 = (((x597+x598)&x599)+x600); if (t134 != 131070) { NG(); } else { ; } } void f135(void) { int8_t x605 = INT8_MIN; volatile int16_t x606 = INT16_MAX; static uint64_t x607 = 46395LLU; volatile uint64_t t135 = 23LLU; t135 = (((x605+x606)&x607)+x608); if (t135 != 13661LLU) { NG(); } else { ; } } void f136(void) { static volatile int8_t x609 = INT8_MAX; uint64_t x612 = 68731LLU; static uint64_t t136 = 125564427318776593LLU; t136 = (((x609+x610)&x611)+x612); if (t136 != 68831LLU) { NG(); } else { ; } } void f137(void) { int32_t x613 = -1; int16_t x614 = INT16_MIN; volatile int64_t x616 = INT64_MIN; volatile int64_t t137 = -2489204LL; t137 = (((x613+x614)&x615)+x616); if (t137 != -9223372032559841281LL) { NG(); } else { ; } } void f138(void) { int32_t x617 = INT32_MIN; int16_t x618 = 1964; static volatile int64_t t138 = 221282LL; t138 = (((x617+x618)&x619)+x620); if (t138 != -5581965434641034LL) { NG(); } else { ; } } void f139(void) { int64_t x622 = INT64_MIN; static uint16_t x623 = 29U; static volatile int16_t x624 = 1; int64_t t139 = -2882356LL; t139 = (((x621+x622)&x623)+x624); if (t139 != 6LL) { NG(); } else { ; } } void f140(void) { uint8_t x625 = 1U; int8_t x626 = INT8_MIN; int16_t x628 = -1; static int64_t t140 = -6166262857029163LL; t140 = (((x625+x626)&x627)+x628); if (t140 != 9223372036854775680LL) { NG(); } else { ; } } void f141(void) { int8_t x629 = -1; int16_t x630 = INT16_MIN; uint32_t x631 = UINT32_MAX; int32_t x632 = 1018849854; volatile uint32_t t141 = 80937U; t141 = (((x629+x630)&x631)+x632); if (t141 != 1018817085U) { NG(); } else { ; } } void f142(void) { int8_t x637 = INT8_MAX; uint8_t x640 = UINT8_MAX; t142 = (((x637+x638)&x639)+x640); if (t142 != 33023) { NG(); } else { ; } } void f143(void) { uint8_t x641 = 9U; int32_t x642 = 38202; volatile uint16_t x643 = 2U; int32_t x644 = -1; int32_t t143 = 16575310; t143 = (((x641+x642)&x643)+x644); if (t143 != 1) { NG(); } else { ; } } void f144(void) { int64_t x645 = -1395127640155484LL; uint32_t x646 = UINT32_MAX; int32_t x647 = INT32_MAX; int64_t x648 = INT64_MIN; t144 = (((x645+x646)&x647)+x648); if (t144 != -9223372036710622557LL) { NG(); } else { ; } } void f145(void) { static volatile int64_t x650 = -1LL; int16_t x651 = INT16_MIN; static int16_t x652 = -7639; static volatile uint64_t t145 = 1169018056261345642LLU; t145 = (((x649+x650)&x651)+x652); if (t145 != 15508759081LLU) { NG(); } else { ; } } void f146(void) { int8_t x653 = -2; uint64_t x654 = 4LLU; int32_t x655 = -3772; volatile uint16_t x656 = 56U; volatile uint64_t t146 = 54034837LLU; t146 = (((x653+x654)&x655)+x656); if (t146 != 56LLU) { NG(); } else { ; } } void f147(void) { uint16_t x657 = 26876U; static int16_t x658 = INT16_MAX; volatile int32_t x659 = -16063; int8_t x660 = -1; t147 = (((x657+x658)&x659)+x660); if (t147 != 49216) { NG(); } else { ; } } void f148(void) { int8_t x665 = 57; static uint64_t x666 = UINT64_MAX; volatile uint16_t x667 = 6772U; uint64_t t148 = 4797913826547655LLU; t148 = (((x665+x666)&x667)+x668); if (t148 != 107LLU) { NG(); } else { ; } } void f149(void) { int32_t x669 = INT32_MIN; uint16_t x670 = 56U; static int64_t x671 = INT64_MIN; uint32_t x672 = 120428U; int64_t t149 = -90LL; t149 = (((x669+x670)&x671)+x672); if (t149 != -9223372036854655380LL) { NG(); } else { ; } } void f150(void) { uint64_t x675 = UINT64_MAX; volatile uint32_t x676 = 268U; static volatile uint64_t t150 = 186445599500LLU; t150 = (((x673+x674)&x675)+x676); if (t150 != 7807661LLU) { NG(); } else { ; } } void f151(void) { int16_t x677 = 215; static int8_t x678 = -1; int32_t x680 = INT32_MIN; static int32_t t151 = 1; t151 = (((x677+x678)&x679)+x680); if (t151 != -2147483434) { NG(); } else { ; } } void f152(void) { static int32_t x681 = 0; uint32_t x682 = UINT32_MAX; int64_t x683 = INT64_MAX; int8_t x684 = 0; int64_t t152 = 4LL; t152 = (((x681+x682)&x683)+x684); if (t152 != 4294967295LL) { NG(); } else { ; } } void f153(void) { volatile int32_t x685 = -1; volatile uint8_t x686 = 111U; int32_t x687 = INT32_MIN; int32_t x688 = INT32_MIN; t153 = (((x685+x686)&x687)+x688); if (t153 != INT32_MIN) { NG(); } else { ; } } void f154(void) { uint8_t x689 = UINT8_MAX; uint32_t x690 = 15097U; uint16_t x691 = UINT16_MAX; volatile int8_t x692 = INT8_MIN; volatile uint32_t t154 = 54U; t154 = (((x689+x690)&x691)+x692); if (t154 != 15224U) { NG(); } else { ; } } void f155(void) { int64_t x697 = INT64_MIN; static volatile int8_t x698 = INT8_MAX; static uint32_t x699 = 29581U; static volatile int64_t t155 = 3LL; t155 = (((x697+x698)&x699)+x700); if (t155 != -2147483635LL) { NG(); } else { ; } } void f156(void) { int64_t x701 = INT64_MAX; int8_t x702 = -1; static uint32_t x703 = 3343U; volatile int8_t x704 = INT8_MIN; volatile int64_t t156 = 61438687LL; t156 = (((x701+x702)&x703)+x704); if (t156 != 3214LL) { NG(); } else { ; } } void f157(void) { static int64_t x709 = -2888LL; int8_t x710 = -19; static volatile int32_t x711 = 16031597; volatile int64_t t157 = -75063083129LL; t157 = (((x709+x710)&x711)+x712); if (t157 != 2163512356LL) { NG(); } else { ; } } void f158(void) { int32_t x714 = -3; static int32_t x715 = -1; static int64_t t158 = -1287811LL; t158 = (((x713+x714)&x715)+x716); if (t158 != 14LL) { NG(); } else { ; } } void f159(void) { volatile int16_t x721 = -234; uint8_t x722 = UINT8_MAX; int16_t x723 = INT16_MIN; int32_t x724 = INT32_MAX; volatile int32_t t159 = INT32_MAX; t159 = (((x721+x722)&x723)+x724); if (t159 != INT32_MAX) { NG(); } else { ; } } void f160(void) { uint8_t x725 = UINT8_MAX; int16_t x727 = 11; int16_t x728 = -234; int32_t t160 = -948519418; t160 = (((x725+x726)&x727)+x728); if (t160 != -224) { NG(); } else { ; } } void f161(void) { volatile int64_t x729 = -6227237347220733LL; int32_t x731 = -1; int64_t t161 = 1856545LL; t161 = (((x729+x730)&x731)+x732); if (t161 != -6227237347253502LL) { NG(); } else { ; } } void f162(void) { uint64_t x734 = UINT64_MAX; uint64_t x736 = 307471640997950810LLU; uint64_t t162 = 9687207LLU; t162 = (((x733+x734)&x735)+x736); if (t162 != 307471640997950832LLU) { NG(); } else { ; } } void f163(void) { int8_t x737 = -15; t163 = (((x737+x738)&x739)+x740); if (t163 != 65585) { NG(); } else { ; } } void f164(void) { volatile int8_t x741 = -1; static int16_t x742 = INT16_MAX; int16_t x743 = -223; int16_t x744 = INT16_MIN; t164 = (((x741+x742)&x743)+x744); if (t164 != -224) { NG(); } else { ; } } void f165(void) { int32_t x745 = -253067722; int32_t x747 = -1; int16_t x748 = INT16_MIN; t165 = (((x745+x746)&x747)+x748); if (t165 != -253100491) { NG(); } else { ; } } void f166(void) { uint8_t x749 = 12U; int16_t x751 = -1374; uint32_t x752 = 41850933U; volatile uint32_t t166 = 0U; t166 = (((x749+x750)&x751)+x752); if (t166 != 40222903U) { NG(); } else { ; } } void f167(void) { int32_t x754 = INT32_MIN; int16_t x755 = -1; t167 = (((x753+x754)&x755)+x756); if (t167 != 2147483648LL) { NG(); } else { ; } } void f168(void) { volatile uint64_t x757 = 95LLU; uint16_t x758 = 3U; int64_t x759 = INT64_MAX; static int32_t x760 = INT32_MIN; uint64_t t168 = 48LLU; t168 = (((x757+x758)&x759)+x760); if (t168 != 18446744071562068066LLU) { NG(); } else { ; } } void f169(void) { int32_t x761 = INT32_MIN; int8_t x763 = 25; static int32_t x764 = -22081; volatile uint32_t t169 = 1374261899U; t169 = (((x761+x762)&x763)+x764); if (t169 != 4294945231U) { NG(); } else { ; } } void f170(void) { int16_t x765 = INT16_MIN; int16_t x766 = -1; static int64_t x767 = -13253303650471LL; uint16_t x768 = 3U; int64_t t170 = -1978295782LL; t170 = (((x765+x766)&x767)+x768); if (t170 != -13253303650468LL) { NG(); } else { ; } } void f171(void) { static uint8_t x773 = 10U; int16_t x774 = -3117; uint32_t x775 = 1427U; int16_t x776 = INT16_MIN; volatile uint32_t t171 = 4U; t171 = (((x773+x774)&x775)+x776); if (t171 != 4294934929U) { NG(); } else { ; } } void f172(void) { int64_t x777 = INT64_MAX; int8_t x778 = 0; uint64_t x779 = 6138115456552103943LLU; static uint16_t x780 = 1257U; static volatile uint64_t t172 = 822785LLU; t172 = (((x777+x778)&x779)+x780); if (t172 != 6138115456552105200LLU) { NG(); } else { ; } } void f173(void) { static volatile uint32_t x781 = UINT32_MAX; volatile int8_t x782 = 16; uint64_t x783 = UINT64_MAX; uint16_t x784 = 58U; volatile uint64_t t173 = 548386462166465LLU; t173 = (((x781+x782)&x783)+x784); if (t173 != 73LLU) { NG(); } else { ; } } void f174(void) { volatile uint64_t x785 = 16453589989LLU; uint64_t x786 = 2LLU; int8_t x787 = INT8_MAX; int8_t x788 = 7; volatile uint64_t t174 = 247469811421LLU; t174 = (((x785+x786)&x787)+x788); if (t174 != 110LLU) { NG(); } else { ; } } void f175(void) { int32_t x797 = INT32_MIN; static uint16_t x798 = UINT16_MAX; volatile uint16_t x799 = 40U; static int16_t x800 = 118; int32_t t175 = 3; t175 = (((x797+x798)&x799)+x800); if (t175 != 158) { NG(); } else { ; } } void f176(void) { uint64_t x801 = 8949654798437213892LLU; uint64_t x802 = UINT64_MAX; volatile int8_t x804 = INT8_MIN; volatile uint64_t t176 = 0LLU; t176 = (((x801+x802)&x803)+x804); if (t176 != 18446744073709551488LLU) { NG(); } else { ; } } void f177(void) { volatile int16_t x805 = -1; int32_t x806 = INT32_MAX; int16_t x808 = INT16_MIN; t177 = (((x805+x806)&x807)+x808); if (t177 != 2147450878LLU) { NG(); } else { ; } } void f178(void) { uint16_t x809 = UINT16_MAX; static int16_t x812 = INT16_MIN; volatile int32_t t178 = -1; t178 = (((x809+x810)&x811)+x812); if (t178 != -32641) { NG(); } else { ; } } void f179(void) { uint64_t x814 = 8466961913795LLU; static int16_t x815 = -1; volatile uint64_t t179 = 280176LLU; t179 = (((x813+x814)&x815)+x816); if (t179 != 8466961913796LLU) { NG(); } else { ; } } void f180(void) { volatile uint16_t x817 = 28549U; int64_t x818 = -19063203780542071LL; static int8_t x819 = -3; uint16_t x820 = 0U; int64_t t180 = 3936920898LL; t180 = (((x817+x818)&x819)+x820); if (t180 != -19063203780513524LL) { NG(); } else { ; } } void f181(void) { uint16_t x821 = UINT16_MAX; int16_t x822 = -1; int8_t x823 = INT8_MIN; static volatile uint16_t x824 = 32U; volatile int32_t t181 = 64; t181 = (((x821+x822)&x823)+x824); if (t181 != 65440) { NG(); } else { ; } } void f182(void) { static int64_t x826 = -1LL; uint8_t x827 = 1U; volatile int32_t x828 = INT32_MIN; static volatile int64_t t182 = -737797765LL; t182 = (((x825+x826)&x827)+x828); if (t182 != -2147483648LL) { NG(); } else { ; } } void f183(void) { int16_t x829 = 106; uint64_t x831 = 9203319300556378LLU; uint64_t t183 = 3410969124LLU; t183 = (((x829+x830)&x831)+x832); if (t183 != 9223372036854775874LLU) { NG(); } else { ; } } void f184(void) { uint64_t x837 = 361282LLU; uint32_t x838 = 3U; static uint64_t x839 = 111787317252926LLU; uint8_t x840 = 5U; volatile uint64_t t184 = 489611814LLU; t184 = (((x837+x838)&x839)+x840); if (t184 != 361225LLU) { NG(); } else { ; } } void f185(void) { static int32_t x841 = -1; int64_t t185 = 23505664937LL; t185 = (((x841+x842)&x843)+x844); if (t185 != -9223372036852141312LL) { NG(); } else { ; } } void f186(void) { int8_t x845 = 0; int16_t x847 = INT16_MIN; int64_t x848 = INT64_MAX; volatile int64_t t186 = 180LL; t186 = (((x845+x846)&x847)+x848); if (t186 != 9223372036854743039LL) { NG(); } else { ; } } void f187(void) { static int8_t x850 = INT8_MIN; int64_t x851 = 14557762444262620LL; static int16_t x852 = INT16_MAX; static volatile int64_t t187 = 36777897LL; t187 = (((x849+x850)&x851)+x852); if (t187 != 14557762444295303LL) { NG(); } else { ; } } void f188(void) { int8_t x853 = -1; volatile uint64_t x854 = 1LLU; int8_t x855 = INT8_MIN; uint8_t x856 = 15U; uint64_t t188 = 71977451745995358LLU; t188 = (((x853+x854)&x855)+x856); if (t188 != 15LLU) { NG(); } else { ; } } void f189(void) { volatile int8_t x857 = -36; static uint32_t x858 = 2489U; int16_t x859 = INT16_MIN; int32_t x860 = -1; static volatile uint32_t t189 = UINT32_MAX; t189 = (((x857+x858)&x859)+x860); if (t189 != UINT32_MAX) { NG(); } else { ; } } void f190(void) { static int64_t x869 = -1LL; int16_t x870 = 914; uint32_t x871 = UINT32_MAX; static int64_t x872 = -1LL; volatile int64_t t190 = -1570LL; t190 = (((x869+x870)&x871)+x872); if (t190 != 912LL) { NG(); } else { ; } } void f191(void) { uint16_t x877 = 0U; int64_t x878 = INT64_MIN; uint8_t x879 = UINT8_MAX; int64_t x880 = 151LL; volatile int64_t t191 = -12956561276LL; t191 = (((x877+x878)&x879)+x880); if (t191 != 151LL) { NG(); } else { ; } } void f192(void) { static uint8_t x882 = UINT8_MAX; volatile uint8_t x884 = 3U; uint64_t t192 = 7LLU; t192 = (((x881+x882)&x883)+x884); if (t192 != 130LLU) { NG(); } else { ; } } void f193(void) { volatile uint8_t x885 = 11U; static uint64_t x887 = 136780327034582905LLU; int32_t x888 = INT32_MAX; static uint64_t t193 = 2811008066875515LLU; t193 = (((x885+x886)&x887)+x888); if (t193 != 2147483656LLU) { NG(); } else { ; } } void f194(void) { int32_t x893 = INT32_MAX; uint16_t x894 = 0U; volatile uint64_t x895 = UINT64_MAX; int8_t x896 = -12; volatile uint64_t t194 = 29LLU; t194 = (((x893+x894)&x895)+x896); if (t194 != 2147483635LLU) { NG(); } else { ; } } void f195(void) { int8_t x897 = INT8_MIN; static int16_t x898 = INT16_MIN; static int8_t x899 = -1; int64_t x900 = -1LL; static volatile int64_t t195 = -1LL; t195 = (((x897+x898)&x899)+x900); if (t195 != -32897LL) { NG(); } else { ; } } void f196(void) { static volatile int64_t x906 = -1LL; int64_t x907 = -1LL; int16_t x908 = INT16_MAX; static volatile int64_t t196 = 67750907575734362LL; t196 = (((x905+x906)&x907)+x908); if (t196 != 267879587LL) { NG(); } else { ; } } void f197(void) { uint32_t x909 = 45U; int64_t x911 = -1LL; int8_t x912 = INT8_MIN; static int64_t t197 = -447LL; t197 = (((x909+x910)&x911)+x912); if (t197 != 4294967085LL) { NG(); } else { ; } } void f198(void) { uint64_t x913 = 9LLU; static int8_t x914 = INT8_MAX; int64_t x915 = INT64_MIN; t198 = (((x913+x914)&x915)+x916); if (t198 != 18446744073709518848LLU) { NG(); } else { ; } } void f199(void) { static int16_t x917 = INT16_MIN; uint8_t x918 = UINT8_MAX; static uint32_t x919 = UINT32_MAX; volatile uint8_t x920 = 7U; t199 = (((x917+x918)&x919)+x920); if (t199 != 4294934790U) { NG(); } else { ; } } int main(void) { f0(); f1(); f2(); f3(); f4(); f5(); f6(); f7(); f8(); f9(); f10(); f11(); f12(); f13(); f14(); f15(); f16(); f17(); f18(); f19(); f20(); f21(); f22(); f23(); f24(); f25(); f26(); f27(); f28(); f29(); f30(); f31(); f32(); f33(); f34(); f35(); f36(); f37(); f38(); f39(); f40(); f41(); f42(); f43(); f44(); f45(); f46(); f47(); f48(); f49(); f50(); f51(); f52(); f53(); f54(); f55(); f56(); f57(); f58(); f59(); f60(); f61(); f62(); f63(); f64(); f65(); f66(); f67(); f68(); f69(); f70(); f71(); f72(); f73(); f74(); f75(); f76(); f77(); f78(); f79(); f80(); f81(); f82(); f83(); f84(); f85(); f86(); f87(); f88(); f89(); f90(); f91(); f92(); f93(); f94(); f95(); f96(); f97(); f98(); f99(); f100(); f101(); f102(); f103(); f104(); f105(); f106(); f107(); f108(); f109(); f110(); f111(); f112(); f113(); f114(); f115(); f116(); f117(); f118(); f119(); f120(); f121(); f122(); f123(); f124(); f125(); f126(); f127(); f128(); f129(); f130(); f131(); f132(); f133(); f134(); f135(); f136(); f137(); f138(); f139(); f140(); f141(); f142(); f143(); f144(); f145(); f146(); f147(); f148(); f149(); f150(); f151(); f152(); f153(); f154(); f155(); f156(); f157(); f158(); f159(); f160(); f161(); f162(); f163(); f164(); f165(); f166(); f167(); f168(); f169(); f170(); f171(); f172(); f173(); f174(); f175(); f176(); f177(); f178(); f179(); f180(); f181(); f182(); f183(); f184(); f185(); f186(); f187(); f188(); f189(); f190(); f191(); f192(); f193(); f194(); f195(); f196(); f197(); f198(); f199(); return 0; }
910443.c
#include<stdio.h> #include<sys/socket.h> #include<stdlib.h> #include<netinet/in.h> int main() { char msg[] = "Trying Scoket Programming in C"; int sfd = socket(AF_INET, SOCK_DGRAM, 0); if (sfd == 0) { printf("Socket Failed\n" ); exit(EXIT_FAILURE); } struct sockaddr_in address; address.sin_family = AF_INET; address.sin_addr.s_addr = INADDR_ANY; address.sin_port = htons(9009); if (connect(sfd, (struct sockaddr *)&address, sizeof(address)) < 0) { printf("Connection Failed \n"); return -1; } sendto(sfd, msg, sizeof(msg), 0, (struct sockaddr*) &address, sizeof(address) ); printf("Message Sent\n"); close(sfd); printf("Socket Closed\n"); return 0; }
244545.c
/* * Copyright 2010-2011 Freescale Semiconductor, Inc. * * See file CREDITS for list of people who contributed to this * project. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation; either version 2 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA */ #include <common.h> #include <asm/mmu.h> struct fsl_e_tlb_entry tlb_table[] = { /* TLB 0 - for temp stack in cache */ SET_TLB_ENTRY(0, CONFIG_SYS_INIT_RAM_ADDR, CONFIG_SYS_INIT_RAM_ADDR, MAS3_SX|MAS3_SW|MAS3_SR, 0, 0, 0, BOOKE_PAGESZ_4K, 0), SET_TLB_ENTRY(0, CONFIG_SYS_INIT_RAM_ADDR + 4 * 1024 , CONFIG_SYS_INIT_RAM_ADDR + 4 * 1024, MAS3_SX|MAS3_SW|MAS3_SR, 0, 0, 0, BOOKE_PAGESZ_4K, 0), SET_TLB_ENTRY(0, CONFIG_SYS_INIT_RAM_ADDR + 8 * 1024 , CONFIG_SYS_INIT_RAM_ADDR + 8 * 1024, MAS3_SX|MAS3_SW|MAS3_SR, 0, 0, 0, BOOKE_PAGESZ_4K, 0), SET_TLB_ENTRY(0, CONFIG_SYS_INIT_RAM_ADDR + 12 * 1024 , CONFIG_SYS_INIT_RAM_ADDR + 12 * 1024, MAS3_SX|MAS3_SW|MAS3_SR, 0, 0, 0, BOOKE_PAGESZ_4K, 0), /* TLB 1 */ /* *I*** - Covers boot page */ SET_TLB_ENTRY(1, 0xfffff000, 0xfffff000, MAS3_SX|MAS3_SW|MAS3_SR, MAS2_I|MAS2_G, 0, 0, BOOKE_PAGESZ_4K, 1), /* *I*G* - CCSRBAR */ SET_TLB_ENTRY(1, CONFIG_SYS_CCSRBAR, CONFIG_SYS_CCSRBAR_PHYS, MAS3_SW|MAS3_SR, MAS2_I|MAS2_G, 0, 1, BOOKE_PAGESZ_1M, 1), #ifndef CONFIG_NAND_SPL #ifndef CONFIG_SDCARD SET_TLB_ENTRY(1, CONFIG_SYS_FLASH_BASE, CONFIG_SYS_FLASH_BASE_PHYS, MAS3_SX|MAS3_SR, MAS2_W|MAS2_G, 0, 2, BOOKE_PAGESZ_16M, 1), SET_TLB_ENTRY(1, CONFIG_SYS_FLASH_BASE + 0x1000000, CONFIG_SYS_FLASH_BASE_PHYS + 0x1000000, MAS3_SX|MAS3_SR, MAS2_W|MAS2_G, 0, 3, BOOKE_PAGESZ_16M, 1), #endif #ifdef CONFIG_PCI /* *I*G* - PCI */ SET_TLB_ENTRY(1, CONFIG_SYS_PCIE1_MEM_VIRT, CONFIG_SYS_PCIE1_MEM_PHYS, MAS3_SW|MAS3_SR, MAS2_I|MAS2_G, 0, 4, BOOKE_PAGESZ_1G, 1), /* *I*G* - PCI I/O */ SET_TLB_ENTRY(1, CONFIG_SYS_PCIE1_IO_VIRT, CONFIG_SYS_PCIE1_IO_PHYS, MAS3_SW|MAS3_SR, MAS2_I|MAS2_G, 0, 5, BOOKE_PAGESZ_256K, 1), #endif #endif #ifndef CONFIG_SDCARD /* *I*G - Board CPLD */ SET_TLB_ENTRY(1, CONFIG_SYS_CPLD_BASE, CONFIG_SYS_CPLD_BASE_PHYS, MAS3_SW|MAS3_SR, MAS2_I|MAS2_G, 0, 6, BOOKE_PAGESZ_256K, 1), SET_TLB_ENTRY(1, CONFIG_SYS_NAND_BASE, CONFIG_SYS_NAND_BASE_PHYS, MAS3_SX|MAS3_SW|MAS3_SR, MAS2_I|MAS2_G, 0, 7, BOOKE_PAGESZ_1M, 1), #endif #if defined(CONFIG_SYS_RAMBOOT) SET_TLB_ENTRY(1, CONFIG_SYS_DDR_SDRAM_BASE, CONFIG_SYS_DDR_SDRAM_BASE, MAS3_SX|MAS3_SW|MAS3_SR, 0, 0, 8, BOOKE_PAGESZ_1G, 1) #endif }; int num_tlb_entries = ARRAY_SIZE(tlb_table);
263203.c
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE78_OS_Command_Injection__char_environment_w32spawnl_52b.c Label Definition File: CWE78_OS_Command_Injection.strings.label.xml Template File: sources-sink-52b.tmpl.c */ /* * @description * CWE: 78 OS Command Injection * BadSource: environment Read input from an environment variable * GoodSource: Fixed string * Sink: w32spawnl * BadSink : execute command with spawnl * Flow Variant: 52 Data flow: data passed as an argument from one function to another to another in three different source files * * */ #include "std_testcase.h" #include <wchar.h> #ifdef _WIN32 #define COMMAND_INT_PATH "%WINDIR%\\system32\\cmd.exe" #define COMMAND_INT "cmd.exe" #define COMMAND_ARG1 "/c" #define COMMAND_ARG2 "dir" #define COMMAND_ARG3 data #else /* NOT _WIN32 */ #include <unistd.h> #define COMMAND_INT_PATH "/bin/sh" #define COMMAND_INT "sh" #define COMMAND_ARG1 "ls" #define COMMAND_ARG2 "-la" #define COMMAND_ARG3 data #endif #define ENV_VARIABLE "ADD" #ifdef _WIN32 #define GETENV getenv #else #define GETENV getenv #endif #include <process.h> /* all the sinks are the same, we just want to know where the hit originated if a tool flags one */ #ifndef OMITBAD /* bad function declaration */ void CWE78_OS_Command_Injection__char_environment_w32spawnl_52c_badSink(char * data); void CWE78_OS_Command_Injection__char_environment_w32spawnl_52b_badSink(char * data) { CWE78_OS_Command_Injection__char_environment_w32spawnl_52c_badSink(data); } #endif /* OMITBAD */ #ifndef OMITGOOD /* good function declaration */ void CWE78_OS_Command_Injection__char_environment_w32spawnl_52c_goodG2BSink(char * data); /* goodG2B uses the GoodSource with the BadSink */ void CWE78_OS_Command_Injection__char_environment_w32spawnl_52b_goodG2BSink(char * data) { CWE78_OS_Command_Injection__char_environment_w32spawnl_52c_goodG2BSink(data); } #endif /* OMITGOOD */
856932.c
/* * Durán González Lizeth * Sistemas Operativos * Programa sencillo usando hilos */ #include <stdio.h> #include <pthread.h> void *threadCreado (void *info) { char *data = (char*)info; printf ("-> \n %s", data); } int main(int argc, char const *argv[]) { pthread_t thread1; pthread_t thread2; pthread_t thread3; pthread_create(&thread1, NULL, &threadCreado, "Lizeth"); pthread_create(&thread2, NULL, &threadCreado, "Durán"); prhread_create(&thread3, NULL, &threadCreado, "González"); return 0; }
185866.c
#include <stdio.h> #include <stdarg.h> #include <cappserver.h> void print_file(FILE *file,const char *name,const char *format,va_list ap) { char arr[0x1000]={0}; vsprintf(arr,format,ap); fprintf(file,"[%s]: %s\n",name,arr); } void print_error(const char *name,const char *format,...) { va_list ap; va_start(ap,format); print_file(stderr,name,format,ap); va_end(ap); } void print_log(const char *name,const char *format,...) { va_list ap; va_start(ap,format); print_file(stdout,name,format,ap); va_end(ap); }
602069.c
/***************************************************************************//** * @file main.c * @brief This project shows how to use the Cryotimer in EM4 with the LFXO and * no GPIO retention. This project does so by using LEDs. For the exact program * flow, please see the readme.txt. ******************************************************************************* * # License * <b>Copyright 2020 Silicon Laboratories Inc. www.silabs.com</b> ******************************************************************************* * * SPDX-License-Identifier: Zlib * * The licensor of this software is Silicon Laboratories Inc. * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages * arising from the use of this software. * * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, subject to the following restrictions: * * 1. The origin of this software must not be misrepresented; you must not * claim that you wrote the original software. If you use this software * in a product, an acknowledgment in the product documentation would be * appreciated but is not required. * 2. Altered source versions must be plainly marked as such, and must not be * misrepresented as being the original software. * 3. This notice may not be removed or altered from any source distribution. * ******************************************************************************* * # Evaluation Quality * This code has been minimally tested to ensure that it builds and is suitable * as a demonstration for evaluation purposes only. This code will be maintained * at the sole discretion of Silicon Labs. ******************************************************************************/ #include "em_device.h" #include "em_chip.h" #include "em_cmu.h" #include "em_emu.h" #include "em_gpio.h" #include "em_cryotimer.h" #include "em_rmu.h" #include "bsp.h" // Note: change this to one of the defined periods in em_cryotimer.h // Wakeup events occur every 65536 prescaled clock cycles #define CRYOTIMER_PERIOD cryotimerPeriod_64k // Note: change this to one of the defined prescalers in em_cryotimer.h // The clock is divided by one #define CRYOTIMER_PRESCALE cryotimerPresc_1 /**************************************************************************//** * @brief * Cryotimer interrupt service routine * * @note * The barrier below is make sure the interrupt flags get cleared before * continuing. This ensures that the interrupt is not retriggered before * exiting the Handler. A barrier like this is generally required when the * peripheral clock is much slower than the CPU core clock. * * @note * Despite the note above, the barrier is just a precaution. The code * might work without it as well. *****************************************************************************/ void CRYOTIMER_IRQHandler(void) { // Acknowledge the interrupt uint32_t flags = CRYOTIMER_IntGet(); CRYOTIMER_IntClear(flags); // Put a barrier here to ensure interrupts are not retriggered. See note above __DSB(); } /**************************************************************************//** * @brief * Initialize Cryotimer * * @details * The Cryotimer is reset in order to clear the CNT register. This register * still holds its value from before the EM4 reset and therefore gives * incorrect timing if not cleared. The timer will be started later in the * main(). *****************************************************************************/ void initCryotimer(void) { // Enable cryotimer clock CMU_ClockEnable(cmuClock_CRYOTIMER, true); // Initialize cryotimer CRYOTIMER_Init_TypeDef init = CRYOTIMER_INIT_DEFAULT; init.osc = cryotimerOscLFXO; // Use the LFXO init.em4Wakeup = true; // Enable EM4 wakeup upon triggering a Cryotimer interrupt init.presc = CRYOTIMER_PRESCALE; // Set the prescaler init.period = CRYOTIMER_PERIOD; // Set when wakeup events occur init.enable = false; // Reset the Cryotimer and don't start the timer CRYOTIMER_Init(&init); // Enable Cryotimer interrupts CRYOTIMER_IntEnable(CRYOTIMER_IEN_PERIOD); NVIC_EnableIRQ(CRYOTIMER_IRQn); } /**************************************************************************//** * @brief * Initialize EM4 mode * * @note * The LFXO must be retained in EM4 because it is the oscillator being used * to power the Cryotimer. Without retaining its settings, there will be * nothing to wake us up from EM4. In EM4 Shutoff mode, the LFXO is * automatically disabled, so we must explicitly set the LFXO to be * retained. * * @note * The LFXO must be enabled before setting the RETAINLFXO bit in the * EMU_EM4CTRL register. *****************************************************************************/ void initEm4(void) { // Configure EM4 behavior EMU_EM4Init_TypeDef init = EMU_EM4INIT_DEFAULT; init.em4State = emuEM4Shutoff; // emuEM4Hibernate also works init.retainLfxo = true; // Make sure the LFXO is still powering the Cryotimer in EM4 init.pinRetentionMode = emuPinRetentionDisable; // No GPIO retention EMU_EM4Init(&init); } /**************************************************************************//** * @brief * Main function * * @details * The only reason this program chooses to wait in EM2 is to show the user * the state of the LEDs and therefore show that the reset cause is being * appropriately detected. Without the EMU_EnterEM2(false) line, the board * would immediately go into EM4 and thus turn off the LEDs before the user * could see them turn on. * * @details * If the startup delay for the LFXO is not shortened, then enabling the LFXO * oscillator will take 32768 clock cycles (about 1 second). * * @note * The LFXO must be enabled before setting the RETAINLFXO bit in the * EMU_EM4CTRL register. * * @note * It is good practice to always call EMU_UnlatchPinRetention() when * dealing with EM4 (even if you aren't using retention for the GPIO * pins). The reason is because the registers will have contradictory values * to the latched values upon waking up from EM4. To ensure a consistent * reset state, the unlatch command should be given after properly * reconfiguring these latched registers so that the new values can be * re-latched upon entering EM4. Another good reason to always call * EMU_UnlatchPinRetention() is because of the "EM4H I/O Retention Cannot Be * Disabled" Errata (see the errata for your particular board). *****************************************************************************/ int main(void) { // Chip errata CHIP_Init(); // Init DCDC regulator with kit specific parameters EMU_DCDCInit_TypeDef dcdcInit = EMU_DCDCINIT_DEFAULT; EMU_DCDCInit(&dcdcInit); // Get the reset cause and also clear the reset cause register because it can // only be cleared by software. uint32_t resetCause = RMU_ResetCauseGet(); RMU_ResetCauseClear(); // GPIO Initialization CMU_ClockEnable(cmuClock_GPIO, true); // Enable GPIO clock GPIO_PinModeSet(BSP_GPIO_LED0_PORT, BSP_GPIO_LED0_PIN, gpioModePushPull, 1); // Turn LED0 on // Determine the reset cause if ((resetCause & RMU_RSTCAUSE_PORST) // Reset from powering on the board || (resetCause & RMU_RSTCAUSE_EXTRST) // Reset from an external pin || (resetCause & RMU_RSTCAUSE_SYSREQRST)) // Reset from a system request (e.g. from the debugger) { GPIO_PinModeSet(BSP_GPIO_LED1_PORT, BSP_GPIO_LED1_PIN, gpioModePushPull, 0); // Turn LED1 off } // If reset was caused by waking up from EM4 else if (resetCause & RMU_RSTCAUSE_EM4RST) { // Turn LED1 on GPIO_PinModeSet(BSP_GPIO_LED1_PORT, BSP_GPIO_LED1_PIN, gpioModePushPull, 1); // Since the LFXO has been retained in EM4, we can shorten the startup // delay to 2 cycles when re-enabling the LFXO after EM4 wakeup CMU->LFXOCTRL = (CMU->LFXOCTRL & (~_CMU_LFXOCTRL_MASK)) | CMU_LFXOCTRL_TIMEOUT_2CYCLES; // Unlatch the registers that were latched upon entering EM4 EMU_UnlatchPinRetention(); } // The LFXO oscillator must be enabled before calling initEm4() // This takes about 1 second if the LFXO startup delay is not shortened CMU_OscillatorEnable(cmuOsc_LFXO, true, true); // Initialize the Cryotimer and EM4 settings initCryotimer(); initEm4(); // Start the Cryotimer CRYOTIMER_Enable(true); // Go into EM2 and wait for Cryotimer IRQ // At this point, one of two cases could occur // 1) LED0 will be on (this case only occurs once upon initially resetting the board) // 2) LED0 and LED1 will be on EMU_EnterEM2(false); // Go into EM4 and wait for Cryotimer wakeup // At this point, both LEDs will be off since there is no GPIO retention // (i.e. the GPIO pins used for the LEDs will both be reset to zero) EMU_EnterEM4(); }
739161.c
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE78_OS_Command_Injection__char_listen_socket_w32_execvp_08.c Label Definition File: CWE78_OS_Command_Injection.strings.label.xml Template File: sources-sink-08.tmpl.c */ /* * @description * CWE: 78 OS Command Injection * BadSource: listen_socket Read data using a listen socket (server side) * GoodSource: Fixed string * Sink: w32_execvp * BadSink : execute command with execvp * Flow Variant: 08 Control flow: if(staticReturnsTrue()) and if(staticReturnsFalse()) * * */ #include "std_testcase.h" #include <wchar.h> #ifdef _WIN32 #define COMMAND_INT_PATH "%WINDIR%\\system32\\cmd.exe" #define COMMAND_INT "cmd.exe" #define COMMAND_ARG1 "/c" #define COMMAND_ARG2 "dir" #define COMMAND_ARG3 data #else /* NOT _WIN32 */ #include <unistd.h> #define COMMAND_INT_PATH "/bin/sh" #define COMMAND_INT "sh" #define COMMAND_ARG1 "ls" #define COMMAND_ARG2 "-la" #define COMMAND_ARG3 data #endif #ifdef _WIN32 #include <winsock2.h> #include <windows.h> #include <direct.h> #pragma comment(lib, "ws2_32") /* include ws2_32.lib when linking */ #define CLOSE_SOCKET closesocket #else #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #define INVALID_SOCKET -1 #define SOCKET_ERROR -1 #define CLOSE_SOCKET close #define SOCKET int #endif #define TCP_PORT 27015 #define LISTEN_BACKLOG 5 #include <process.h> #define EXECVP _execvp /* The two function below always return the same value, so a tool * should be able to identify that calls to the functions will always * return a fixed value. */ static int staticReturnsTrue() { return 1; } static int staticReturnsFalse() { return 0; } #ifndef OMITBAD void CWE78_OS_Command_Injection__char_listen_socket_w32_execvp_08_bad() { char * data; char dataBuffer[100] = ""; data = dataBuffer; if(staticReturnsTrue()) { { #ifdef _WIN32 WSADATA wsaData; int wsaDataInit = 0; #endif int recvResult; struct sockaddr_in service; char *replace; SOCKET listenSocket = INVALID_SOCKET; SOCKET acceptSocket = INVALID_SOCKET; size_t dataLen = strlen(data); do { #ifdef _WIN32 if (WSAStartup(MAKEWORD(2,2), &wsaData) != NO_ERROR) { break; } wsaDataInit = 1; #endif /* POTENTIAL FLAW: Read data using a listen socket */ listenSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if (listenSocket == INVALID_SOCKET) { break; } memset(&service, 0, sizeof(service)); service.sin_family = AF_INET; service.sin_addr.s_addr = INADDR_ANY; service.sin_port = htons(TCP_PORT); if (bind(listenSocket, (struct sockaddr*)&service, sizeof(service)) == SOCKET_ERROR) { break; } if (listen(listenSocket, LISTEN_BACKLOG) == SOCKET_ERROR) { break; } acceptSocket = accept(listenSocket, NULL, NULL); if (acceptSocket == SOCKET_ERROR) { break; } /* Abort on error or the connection was closed */ recvResult = recv(acceptSocket, (char *)(data + dataLen), sizeof(char) * (100 - dataLen - 1), 0); if (recvResult == SOCKET_ERROR || recvResult == 0) { break; } /* Append null terminator */ data[dataLen + recvResult / sizeof(char)] = '\0'; /* Eliminate CRLF */ replace = strchr(data, '\r'); if (replace) { *replace = '\0'; } replace = strchr(data, '\n'); if (replace) { *replace = '\0'; } } while (0); if (listenSocket != INVALID_SOCKET) { CLOSE_SOCKET(listenSocket); } if (acceptSocket != INVALID_SOCKET) { CLOSE_SOCKET(acceptSocket); } #ifdef _WIN32 if (wsaDataInit) { WSACleanup(); } #endif } } { char *args[] = {COMMAND_INT_PATH, COMMAND_ARG1, COMMAND_ARG2, COMMAND_ARG3, NULL}; /* execvp - searches for the location of the command among * the directories specified by the PATH environment variable */ /* POTENTIAL FLAW: Execute command without validating input possibly leading to command injection */ EXECVP(COMMAND_INT, args); } } #endif /* OMITBAD */ #ifndef OMITGOOD /* goodG2B1() - use goodsource and badsink by changing the staticReturnsTrue() to staticReturnsFalse() */ static void goodG2B1() { char * data; char dataBuffer[100] = ""; data = dataBuffer; if(staticReturnsFalse()) { /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ printLine("Benign, fixed string"); } else { /* FIX: Append a fixed string to data (not user / external input) */ strcat(data, "*.*"); } { char *args[] = {COMMAND_INT_PATH, COMMAND_ARG1, COMMAND_ARG2, COMMAND_ARG3, NULL}; /* execvp - searches for the location of the command among * the directories specified by the PATH environment variable */ /* POTENTIAL FLAW: Execute command without validating input possibly leading to command injection */ EXECVP(COMMAND_INT, args); } } /* goodG2B2() - use goodsource and badsink by reversing the blocks in the if statement */ static void goodG2B2() { char * data; char dataBuffer[100] = ""; data = dataBuffer; if(staticReturnsTrue()) { /* FIX: Append a fixed string to data (not user / external input) */ strcat(data, "*.*"); } { char *args[] = {COMMAND_INT_PATH, COMMAND_ARG1, COMMAND_ARG2, COMMAND_ARG3, NULL}; /* execvp - searches for the location of the command among * the directories specified by the PATH environment variable */ /* POTENTIAL FLAW: Execute command without validating input possibly leading to command injection */ EXECVP(COMMAND_INT, args); } } void CWE78_OS_Command_Injection__char_listen_socket_w32_execvp_08_good() { goodG2B1(); goodG2B2(); } #endif /* OMITGOOD */ /* Below is the main(). It is only used when building this testcase on * its own for testing or for building a binary to use in testing binary * analysis tools. It is not used when compiling all the testcases as one * application, which is how source code analysis tools are tested. */ #ifdef INCLUDEMAIN int main(int argc, char * argv[]) { /* seed randomness */ srand( (unsigned)time(NULL) ); #ifndef OMITGOOD printLine("Calling good()..."); CWE78_OS_Command_Injection__char_listen_socket_w32_execvp_08_good(); printLine("Finished good()"); #endif /* OMITGOOD */ #ifndef OMITBAD printLine("Calling bad()..."); CWE78_OS_Command_Injection__char_listen_socket_w32_execvp_08_bad(); printLine("Finished bad()"); #endif /* OMITBAD */ return 0; } #endif
796923.c
/* * Setup kernel for a Sun3x machine * * (C) 1999 Thomas Bogendoerfer ([email protected]) * * based on code from Oliver Jowett <[email protected]> */ #include <linux/types.h> #include <linux/mm.h> #include <linux/console.h> #include <linux/init.h> #include <asm/system.h> #include <asm/machdep.h> #include <asm/irq.h> #include <asm/sun3xprom.h> #include <asm/sun3ints.h> #include <asm/setup.h> #include <asm/oplib.h> #include "time.h" volatile char *clock_va; extern volatile unsigned char *sun3_intreg; extern void sun3_get_model(char *model); int __init sun3x_keyb_init(void) { return 0; } int sun3x_kbdrate(struct kbd_repeat *r) { return 0; } void sun3x_kbd_leds(unsigned int i) { } void sun3_leds(unsigned int i) { } static int sun3x_get_hardware_list(char *buffer) { int len = 0; len += sprintf(buffer + len, "PROM Revision:\t%s\n", romvec->pv_monid); return len; } /* * Setup the sun3x configuration info */ void __init config_sun3x(void) { sun3x_prom_init(); mach_get_irq_list = sun3_get_irq_list; mach_max_dma_address = 0xffffffff; /* we can DMA anywhere, whee */ #ifdef CONFIG_VT mach_keyb_init = sun3x_keyb_init; mach_kbdrate = sun3x_kbdrate; mach_kbd_leds = sun3x_kbd_leds; #endif mach_default_handler = &sun3_default_handler; mach_sched_init = sun3x_sched_init; mach_init_IRQ = sun3_init_IRQ; enable_irq = sun3_enable_irq; disable_irq = sun3_disable_irq; mach_request_irq = sun3_request_irq; mach_free_irq = sun3_free_irq; mach_process_int = sun3_process_int; mach_gettimeoffset = sun3x_gettimeoffset; mach_reset = sun3x_reboot; mach_gettod = sun3x_gettod; mach_hwclk = sun3x_hwclk; mach_get_model = sun3_get_model; mach_get_hardware_list = sun3x_get_hardware_list; sun3_intreg = (unsigned char *)SUN3X_INTREG; /* only the serial console is known to work anyway... */ #if 0 switch (*(unsigned char *)SUN3X_EEPROM_CONS) { case 0x10: serial_console = 1; conswitchp = NULL; break; case 0x11: serial_console = 2; conswitchp = NULL; break; default: serial_console = 0; conswitchp = &dummy_con; break; } #endif }
29405.c
/* ChapelNumLocales.chpl:23 */ static void chpl__init_ChapelNumLocales(int64_t _ln, c_string _fn) { c_string modFormatStr; c_string modStr; _ref_int32_t refIndentLevel = NULL; int64_t const_tmp; chpl_bool call_tmp; chpl_bool call_tmp2; int64_t call_tmp3; c_string call_tmp4; if (chpl__init_ChapelNumLocales_p) { goto _exit_chpl__init_ChapelNumLocales; } modFormatStr = "%*s\n"; modStr = "ChapelNumLocales"; printModuleInit(modFormatStr, modStr, INT64(16), _ln, _fn); refIndentLevel = &moduleInitLevel; *(refIndentLevel) += INT64(1); chpl__init_ChapelNumLocales_p = true; call_tmp = chpl_config_has_value("numLocales", "Built-in"); call_tmp2 = (! call_tmp); if (call_tmp2) { call_tmp3 = chpl_comm_default_num_locales(); const_tmp = call_tmp3; } else { call_tmp4 = chpl_config_get_value("numLocales", "Built-in"); const_tmp = _command_line_cast4(call_tmp4, _ln, _fn); } numLocales = const_tmp; *(refIndentLevel) -= INT64(1); _exit_chpl__init_ChapelNumLocales:; return; }
579333.c
/* * @@name: mem_model.3c * @@type: C * @@compilable: yes * @@linkable: yes * @@expect: rt-error * @@version: omp_3.1 */ #include <omp.h> #include <stdio.h> int data0 = 0, data1 = 0; int main() { int flag=0; #pragma omp parallel num_threads(3) { if(omp_get_thread_num()==0) { data0 = 17; #pragma omp flush /* Set flag to release thread 1 */ #pragma omp atomic update flag++; /* Flush of flag is implied by the atomic directive */ } else if(omp_get_thread_num()==1) { int flag_val = 0; /* Loop until we see that flag reaches 1*/ while(flag_val < 0) { #pragma omp atomic read flag_val = flag; } #pragma omp flush(data0) /* data0 is 17 here */ printf("Thread 1 awoken (data0 = %d)\n", data0); data1 = 42; #pragma omp flush(data1) /* Set flag to release thread 2 */ #pragma omp atomic update flag++; /* Flush of flag is implied by the atomic directive */ } else if(omp_get_thread_num()==2) { int flag_val = 0; /* Loop until we see that flag reaches 2 */ while(flag_val < 2) { #pragma omp atomic read flag_val = flag; } #pragma omp flush(data0,data1) /* there is a data race here; data0 is 17 and data1 is undefined */ printf("Thread 2 awoken (data0 = %d, data1 = %d)\n", data0, data1); } } return 0; }
276438.c
/* * Copyright (C) 2017 Netronome Systems, Inc. * * This software is dual licensed under the GNU General License Version 2, * June 1991 as shown in the file COPYING in the top-level directory of this * source tree or the BSD 2-Clause License provided below. You have the * option to license this software under the complete terms of either license. * * The BSD 2-Clause 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. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #include "nfp_net_compat.h" #include <linux/etherdevice.h> #include <linux/pci.h> #include <linux/skbuff.h> #include <linux/vmalloc.h> #include <net/devlink.h> #include <net/dst_metadata.h> #include "main.h" #include "../nfpcore/nfp_cpp.h" #include "../nfpcore/nfp_nffw.h" #include "../nfpcore/nfp_nsp.h" #include "../nfp_app.h" #include "../nfp_main.h" #include "../nfp_net.h" #include "../nfp_net_repr.h" #include "../nfp_port.h" #include "./cmsg.h" #define NFP_FLOWER_ALLOWED_VER 0x0001000000010000UL static const char *nfp_flower_extra_cap(struct nfp_app *app, struct nfp_net *nn) { return "FLOWER"; } static enum devlink_eswitch_mode eswitch_mode_get(struct nfp_app *app) { return DEVLINK_ESWITCH_MODE_SWITCHDEV; } static enum nfp_repr_type nfp_flower_repr_get_type_and_port(struct nfp_app *app, u32 port_id, u8 *port) { switch (FIELD_GET(NFP_FLOWER_CMSG_PORT_TYPE, port_id)) { case NFP_FLOWER_CMSG_PORT_TYPE_PHYS_PORT: *port = FIELD_GET(NFP_FLOWER_CMSG_PORT_PHYS_PORT_NUM, port_id); return NFP_REPR_TYPE_PHYS_PORT; case NFP_FLOWER_CMSG_PORT_TYPE_PCIE_PORT: *port = FIELD_GET(NFP_FLOWER_CMSG_PORT_VNIC, port_id); if (FIELD_GET(NFP_FLOWER_CMSG_PORT_VNIC_TYPE, port_id) == NFP_FLOWER_CMSG_PORT_VNIC_TYPE_PF) return NFP_REPR_TYPE_PF; else return NFP_REPR_TYPE_VF; } return NFP_FLOWER_CMSG_PORT_TYPE_UNSPEC; } static struct net_device * nfp_flower_repr_get(struct nfp_app *app, u32 port_id) { enum nfp_repr_type repr_type; struct nfp_reprs *reprs; u8 port = 0; repr_type = nfp_flower_repr_get_type_and_port(app, port_id, &port); reprs = rcu_dereference(app->reprs[repr_type]); if (!reprs) return NULL; if (port >= reprs->num_reprs) return NULL; return reprs->reprs[port]; } static int nfp_flower_repr_netdev_open(struct nfp_app *app, struct nfp_repr *repr) { int err; err = nfp_flower_cmsg_portmod(repr, true); if (err) return err; netif_carrier_on(repr->netdev); netif_tx_wake_all_queues(repr->netdev); return 0; } static int nfp_flower_repr_netdev_stop(struct nfp_app *app, struct nfp_repr *repr) { netif_carrier_off(repr->netdev); netif_tx_disable(repr->netdev); return nfp_flower_cmsg_portmod(repr, false); } static void nfp_flower_sriov_disable(struct nfp_app *app) { struct nfp_flower_priv *priv = app->priv; if (!priv->nn) return; nfp_reprs_clean_and_free_by_type(app, NFP_REPR_TYPE_VF); } static int nfp_flower_spawn_vnic_reprs(struct nfp_app *app, enum nfp_flower_cmsg_port_vnic_type vnic_type, enum nfp_repr_type repr_type, unsigned int cnt) { u8 nfp_pcie = nfp_cppcore_pcie_unit(app->pf->cpp); struct nfp_flower_priv *priv = app->priv; struct nfp_reprs *reprs, *old_reprs; enum nfp_port_type port_type; const u8 queue = 0; int i, err; port_type = repr_type == NFP_REPR_TYPE_PF ? NFP_PORT_PF_PORT : NFP_PORT_VF_PORT; reprs = nfp_reprs_alloc(cnt); if (!reprs) return -ENOMEM; for (i = 0; i < cnt; i++) { struct nfp_port *port; u32 port_id; reprs->reprs[i] = nfp_repr_alloc(app); if (!reprs->reprs[i]) { err = -ENOMEM; goto err_reprs_clean; } /* For now we only support 1 PF */ WARN_ON(repr_type == NFP_REPR_TYPE_PF && i); port = nfp_port_alloc(app, port_type, reprs->reprs[i]); if (repr_type == NFP_REPR_TYPE_PF) { port->pf_id = i; port->vnic = priv->nn->dp.ctrl_bar; } else { port->pf_id = 0; port->vf_id = i; port->vnic = app->pf->vf_cfg_mem + i * NFP_NET_CFG_BAR_SZ; } eth_hw_addr_random(reprs->reprs[i]); port_id = nfp_flower_cmsg_pcie_port(nfp_pcie, vnic_type, i, queue); err = nfp_repr_init(app, reprs->reprs[i], port_id, port, priv->nn->dp.netdev); if (err) { nfp_port_free(port); goto err_reprs_clean; } nfp_info(app->cpp, "%s%d Representor(%s) created\n", repr_type == NFP_REPR_TYPE_PF ? "PF" : "VF", i, reprs->reprs[i]->name); } old_reprs = nfp_app_reprs_set(app, repr_type, reprs); if (IS_ERR(old_reprs)) { err = PTR_ERR(old_reprs); goto err_reprs_clean; } return 0; err_reprs_clean: nfp_reprs_clean_and_free(reprs); return err; } static int nfp_flower_sriov_enable(struct nfp_app *app, int num_vfs) { struct nfp_flower_priv *priv = app->priv; if (!priv->nn) return 0; return nfp_flower_spawn_vnic_reprs(app, NFP_FLOWER_CMSG_PORT_VNIC_TYPE_VF, NFP_REPR_TYPE_VF, num_vfs); } static int nfp_flower_spawn_phy_reprs(struct nfp_app *app, struct nfp_flower_priv *priv) { struct nfp_eth_table *eth_tbl = app->pf->eth_tbl; struct nfp_reprs *reprs, *old_reprs; struct sk_buff *ctrl_skb; unsigned int i; int err; ctrl_skb = nfp_flower_cmsg_mac_repr_start(app, eth_tbl->count); if (!ctrl_skb) return -ENOMEM; reprs = nfp_reprs_alloc(eth_tbl->max_index + 1); if (!reprs) { err = -ENOMEM; goto err_free_ctrl_skb; } for (i = 0; i < eth_tbl->count; i++) { unsigned int phys_port = eth_tbl->ports[i].index; struct nfp_port *port; u32 cmsg_port_id; reprs->reprs[phys_port] = nfp_repr_alloc(app); if (!reprs->reprs[phys_port]) { err = -ENOMEM; goto err_reprs_clean; } port = nfp_port_alloc(app, NFP_PORT_PHYS_PORT, reprs->reprs[phys_port]); if (IS_ERR(port)) { err = PTR_ERR(port); goto err_reprs_clean; } err = nfp_port_init_phy_port(app->pf, app, port, i); if (err) { nfp_port_free(port); goto err_reprs_clean; } SET_NETDEV_DEV(reprs->reprs[phys_port], &priv->nn->pdev->dev); nfp_net_get_mac_addr(app->pf, port); cmsg_port_id = nfp_flower_cmsg_phys_port(phys_port); err = nfp_repr_init(app, reprs->reprs[phys_port], cmsg_port_id, port, priv->nn->dp.netdev); if (err) { nfp_port_free(port); goto err_reprs_clean; } nfp_flower_cmsg_mac_repr_add(ctrl_skb, i, eth_tbl->ports[i].nbi, eth_tbl->ports[i].base, phys_port); nfp_info(app->cpp, "Phys Port %d Representor(%s) created\n", phys_port, reprs->reprs[phys_port]->name); } old_reprs = nfp_app_reprs_set(app, NFP_REPR_TYPE_PHYS_PORT, reprs); if (IS_ERR(old_reprs)) { err = PTR_ERR(old_reprs); goto err_reprs_clean; } /* The MAC_REPR control message should be sent after the MAC * representors are registered using nfp_app_reprs_set(). This is * because the firmware may respond with control messages for the * MAC representors, f.e. to provide the driver with information * about their state, and without registration the driver will drop * any such messages. */ nfp_ctrl_tx(app->ctrl, ctrl_skb); return 0; err_reprs_clean: nfp_reprs_clean_and_free(reprs); err_free_ctrl_skb: kfree_skb(ctrl_skb); return err; } static int nfp_flower_vnic_alloc(struct nfp_app *app, struct nfp_net *nn, unsigned int id) { if (id > 0) { nfp_warn(app->cpp, "FlowerNIC doesn't support more than one data vNIC\n"); goto err_invalid_port; } eth_hw_addr_random(nn->dp.netdev); netif_keep_dst(nn->dp.netdev); return 0; err_invalid_port: nn->port = nfp_port_alloc(app, NFP_PORT_INVALID, nn->dp.netdev); return PTR_ERR_OR_ZERO(nn->port); } static void nfp_flower_vnic_clean(struct nfp_app *app, struct nfp_net *nn) { struct nfp_flower_priv *priv = app->priv; if (app->pf->num_vfs) nfp_reprs_clean_and_free_by_type(app, NFP_REPR_TYPE_VF); nfp_reprs_clean_and_free_by_type(app, NFP_REPR_TYPE_PF); nfp_reprs_clean_and_free_by_type(app, NFP_REPR_TYPE_PHYS_PORT); priv->nn = NULL; } static int nfp_flower_vnic_init(struct nfp_app *app, struct nfp_net *nn) { struct nfp_flower_priv *priv = app->priv; int err; priv->nn = nn; err = nfp_flower_spawn_phy_reprs(app, app->priv); if (err) goto err_clear_nn; err = nfp_flower_spawn_vnic_reprs(app, NFP_FLOWER_CMSG_PORT_VNIC_TYPE_PF, NFP_REPR_TYPE_PF, 1); if (err) goto err_destroy_reprs_phy; if (app->pf->num_vfs) { err = nfp_flower_spawn_vnic_reprs(app, NFP_FLOWER_CMSG_PORT_VNIC_TYPE_VF, NFP_REPR_TYPE_VF, app->pf->num_vfs); if (err) goto err_destroy_reprs_pf; } return 0; err_destroy_reprs_pf: nfp_reprs_clean_and_free_by_type(app, NFP_REPR_TYPE_PF); err_destroy_reprs_phy: nfp_reprs_clean_and_free_by_type(app, NFP_REPR_TYPE_PHYS_PORT); err_clear_nn: priv->nn = NULL; return err; } static int nfp_flower_init(struct nfp_app *app) { const struct nfp_pf *pf = app->pf; struct nfp_flower_priv *app_priv; u64 version; int err; if (!pf->eth_tbl) { nfp_warn(app->cpp, "FlowerNIC requires eth table\n"); return -EINVAL; } if (!pf->mac_stats_bar) { nfp_warn(app->cpp, "FlowerNIC requires mac_stats BAR\n"); return -EINVAL; } if (!pf->vf_cfg_bar) { nfp_warn(app->cpp, "FlowerNIC requires vf_cfg BAR\n"); return -EINVAL; } version = nfp_rtsym_read_le(app->pf->rtbl, "hw_flower_version", &err); if (err) { nfp_warn(app->cpp, "FlowerNIC requires hw_flower_version memory symbol\n"); return err; } /* We need to ensure hardware has enough flower capabilities. */ if (version != NFP_FLOWER_ALLOWED_VER) { nfp_warn(app->cpp, "FlowerNIC: unsupported firmware version\n"); return -EINVAL; } app_priv = vzalloc(sizeof(struct nfp_flower_priv)); if (!app_priv) return -ENOMEM; app->priv = app_priv; app_priv->app = app; skb_queue_head_init(&app_priv->cmsg_skbs); INIT_WORK(&app_priv->cmsg_work, nfp_flower_cmsg_process_rx); err = nfp_flower_metadata_init(app); if (err) goto err_free_app_priv; return 0; err_free_app_priv: vfree(app->priv); return err; } static void nfp_flower_clean(struct nfp_app *app) { struct nfp_flower_priv *app_priv = app->priv; skb_queue_purge(&app_priv->cmsg_skbs); flush_work(&app_priv->cmsg_work); nfp_flower_metadata_cleanup(app); vfree(app->priv); app->priv = NULL; } const struct nfp_app_type app_flower = { .id = NFP_APP_FLOWER_NIC, .name = "flower", .ctrl_has_meta = true, .extra_cap = nfp_flower_extra_cap, .init = nfp_flower_init, .clean = nfp_flower_clean, .vnic_alloc = nfp_flower_vnic_alloc, .vnic_init = nfp_flower_vnic_init, .vnic_clean = nfp_flower_vnic_clean, .repr_open = nfp_flower_repr_netdev_open, .repr_stop = nfp_flower_repr_netdev_stop, .ctrl_msg_rx = nfp_flower_cmsg_rx, .sriov_enable = nfp_flower_sriov_enable, .sriov_disable = nfp_flower_sriov_disable, .eswitch_mode_get = eswitch_mode_get, .repr_get = nfp_flower_repr_get, .setup_tc = nfp_flower_setup_tc, };
457400.c
#define PJ_LIB__ #include <errno.h> #include <proj.h> #include "projects.h" PROJ_HEAD(tpeqd, "Two Point Equidistant") "\n\tMisc Sph\n\tlat_1= lon_1= lat_2= lon_2="; struct pj_opaque { double cp1, sp1, cp2, sp2, ccs, cs, sc, r2z0, z02, dlam2; double hz0, thz0, rhshz0, ca, sa, lp, lamc; }; static XY s_forward (LP lp, PJ *P) { /* Spheroidal, forward */ XY xy = {0.0, 0.0}; struct pj_opaque *Q = P->opaque; double t, z1, z2, dl1, dl2, sp, cp; sp = sin(lp.phi); cp = cos(lp.phi); z1 = aacos(P->ctx, Q->sp1 * sp + Q->cp1 * cp * cos (dl1 = lp.lam + Q->dlam2)); z2 = aacos(P->ctx, Q->sp2 * sp + Q->cp2 * cp * cos (dl2 = lp.lam - Q->dlam2)); z1 *= z1; z2 *= z2; xy.x = Q->r2z0 * (t = z1 - z2); t = Q->z02 - t; xy.y = Q->r2z0 * asqrt (4. * Q->z02 * z2 - t * t); if ((Q->ccs * sp - cp * (Q->cs * sin(dl1) - Q->sc * sin(dl2))) < 0.) xy.y = -xy.y; return xy; } static LP s_inverse (XY xy, PJ *P) { /* Spheroidal, inverse */ LP lp = {0.0,0.0}; struct pj_opaque *Q = P->opaque; double cz1, cz2, s, d, cp, sp; cz1 = cos (hypot(xy.y, xy.x + Q->hz0)); cz2 = cos (hypot(xy.y, xy.x - Q->hz0)); s = cz1 + cz2; d = cz1 - cz2; lp.lam = - atan2(d, (s * Q->thz0)); lp.phi = aacos(P->ctx, hypot (Q->thz0 * s, d) * Q->rhshz0); if ( xy.y < 0. ) lp.phi = - lp.phi; /* lam--phi now in system relative to P1--P2 base equator */ sp = sin (lp.phi); cp = cos (lp.phi); lp.phi = aasin (P->ctx, Q->sa * sp + Q->ca * cp * (s = cos(lp.lam -= Q->lp))); lp.lam = atan2 (cp * sin(lp.lam), Q->sa * cp * s - Q->ca * sp) + Q->lamc; return lp; } PJ *PROJECTION(tpeqd) { double lam_1, lam_2, phi_1, phi_2, A12, pp; struct pj_opaque *Q = pj_calloc (1, sizeof (struct pj_opaque)); if (0==Q) return pj_default_destructor(P, ENOMEM); P->opaque = Q; /* get control point locations */ phi_1 = pj_param(P->ctx, P->params, "rlat_1").f; lam_1 = pj_param(P->ctx, P->params, "rlon_1").f; phi_2 = pj_param(P->ctx, P->params, "rlat_2").f; lam_2 = pj_param(P->ctx, P->params, "rlon_2").f; if (phi_1 == phi_2 && lam_1 == lam_2) return pj_default_destructor(P, PJD_ERR_CONTROL_POINT_NO_DIST); P->lam0 = adjlon (0.5 * (lam_1 + lam_2)); Q->dlam2 = adjlon (lam_2 - lam_1); Q->cp1 = cos (phi_1); Q->cp2 = cos (phi_2); Q->sp1 = sin (phi_1); Q->sp2 = sin (phi_2); Q->cs = Q->cp1 * Q->sp2; Q->sc = Q->sp1 * Q->cp2; Q->ccs = Q->cp1 * Q->cp2 * sin(Q->dlam2); Q->z02 = aacos(P->ctx, Q->sp1 * Q->sp2 + Q->cp1 * Q->cp2 * cos (Q->dlam2)); Q->hz0 = .5 * Q->z02; A12 = atan2(Q->cp2 * sin (Q->dlam2), Q->cp1 * Q->sp2 - Q->sp1 * Q->cp2 * cos (Q->dlam2)); Q->ca = cos(pp = aasin(P->ctx, Q->cp1 * sin(A12))); Q->sa = sin(pp); Q->lp = adjlon ( atan2 (Q->cp1 * cos(A12), Q->sp1) - Q->hz0); Q->dlam2 *= .5; Q->lamc = M_HALFPI - atan2(sin(A12) * Q->sp1, cos(A12)) - Q->dlam2; Q->thz0 = tan (Q->hz0); Q->rhshz0 = .5 / sin (Q->hz0); Q->r2z0 = 0.5 / Q->z02; Q->z02 *= Q->z02; P->inv = s_inverse; P->fwd = s_forward; P->es = 0.; return P; }
171893.c
/* Copyright (c) 2009 Nordic Semiconductor. All Rights Reserved. * * The information contained herein is confidential property of Nordic * Semiconductor ASA.Terms and conditions of usage are described in detail * in NORDIC SEMICONDUCTOR STANDARD SOFTWARE LICENSE AGREEMENT. * * Licensees are granted free, non-transferable use of the information. NO * WARRENTY of ANY KIND is provided. This heading must NOT be removed from * the file. * * $LastChangedRevision: 224 $ */ /** @file * @brief Implementation of hal_adc */ #include <stdint.h> #include <stdbool.h> #include "nrf24le1.h" #include "nordic_common.h" #include "hal_adc.h" void hal_adc_set_input_channel(hal_adc_input_channel_t chsel) { // Update "chsel" bits ADCCON1 = ((ADCCON1 & 0xC3) | (((uint8_t)(chsel) << 2) & ~0xC3)); } void hal_adc_set_reference(hal_adc_reference_t refsel) { // Update "refsel" bits ADCCON1 = ((ADCCON1 & 0xFC) | (((uint8_t)(refsel)) & ~0xFC)); } void hal_adc_set_input_mode(hal_adc_input_mode_t input_mode) { // Update "diffm" bits ADCCON2 = ((ADCCON2 & 0x3F) | ((uint8_t)(input_mode) << 6)); } void hal_adc_set_conversion_mode(hal_adc_conversion_mode_t conv_mode) { // Update "cont" bit ADCCON2 = ((ADCCON2 & 0xDF) | (((uint8_t)(conv_mode) << 5) & ~0xDF)); } void hal_adc_set_sampling_rate(hal_adc_sampling_rate_t rate) { // Update "rate" bits ADCCON2 = ((ADCCON2 & 0xE3) | (((uint8_t)(rate) << 2) & ~0xE3)); } void hal_adc_set_power_down_delay(hal_adc_power_down_delay_t pdd) { // Update "rate" bits ADCCON2 = ((ADCCON2 & 0xE3) | (((uint8_t)(pdd) << 2) & ~0xE3)); } void hal_adc_set_acq_window(hal_adc_acq_window_t tacq) { // Update "tacq" bits ADCCON2 = ((ADCCON2 & 0xFC) | (((uint8_t)(tacq)) & ~0xFC)); } void hal_adc_set_resolution(hal_adc_resolution_t res) { // Update "resol" bits ADCCON3 = ((ADCCON3 & 0x3F) | ((uint8_t)(res) << 6)); } void hal_adc_set_data_just(hal_adc_data_just_t just) { // Update "rljust" bit ADCCON3 = ((ADCCON3 & 0xDF) | (((uint8_t)(just) << 5) & ~0xDF)); } void hal_adc_start(void) { uint8_t cnt = ADC_STARTUP_CNT; // Get the counter value ADCCON1 = ADCCON1 | BIT_7; // Set "pwrup" bit while(cnt--){} // Wait for busy bit to stabilize } uint8_t hal_adc_read_LSB(void) { return ADCDATL; // Return value stored in ADCDATL } uint8_t hal_adc_read_MSB(void) { return ADCDATH; // Return value stored in ADCDATH } bool hal_adc_busy(void) { return ((ADCCON1 & BIT_6)); // Return status of "busy" bit } hal_adc_overflow_t hal_adc_get_overflow_status(void) { return (hal_adc_overflow_t)((ADCCON3 & (BIT_3 | BIT_4)) >> 3); } // Return status bits from ADCCON3
470346.c
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE194_Unexpected_Sign_Extension__fscanf_memmove_05.c Label Definition File: CWE194_Unexpected_Sign_Extension.label.xml Template File: sources-sink-05.tmpl.c */ /* * @description * CWE: 194 Unexpected Sign Extension * BadSource: fscanf Read data from the console using fscanf() * GoodSource: Positive integer * Sink: memmove * BadSink : Copy strings using memmove() with the length of data * Flow Variant: 05 Control flow: if(staticTrue) and if(staticFalse) * * */ #include "std_testcase.h" /* The two variables below are not defined as "const", but are never * assigned any other value, so a tool should be able to identify that * reads of these will always return their initialized values. */ static int staticTrue = 1; /* true */ static int staticFalse = 0; /* false */ #ifndef OMITBAD void CWE194_Unexpected_Sign_Extension__fscanf_memmove_05_bad() { short data; /* Initialize data */ data = 0; if(staticTrue) { /* FLAW: Use a value input from the console using fscanf() */ fscanf (stdin, "%hd", &data); } { char source[100]; char dest[100] = ""; memset(source, 'A', 100-1); source[100-1] = '\0'; if (data < 100) { /* POTENTIAL FLAW: data is interpreted as an unsigned int - if its value is negative, * the sign extension could result in a very large number */ memmove(dest, source, data); dest[data] = '\0'; /* NULL terminate */ } printLine(dest); } } #endif /* OMITBAD */ #ifndef OMITGOOD /* goodG2B1() - use goodsource and badsink by changing the staticTrue to staticFalse */ static void goodG2B1() { short data; /* Initialize data */ data = 0; if(staticFalse) { /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ printLine("Benign, fixed string"); } else { /* FIX: Use a positive integer less than &InitialDataSize&*/ data = 100-1; } { char source[100]; char dest[100] = ""; memset(source, 'A', 100-1); source[100-1] = '\0'; if (data < 100) { /* POTENTIAL FLAW: data is interpreted as an unsigned int - if its value is negative, * the sign extension could result in a very large number */ memmove(dest, source, data); dest[data] = '\0'; /* NULL terminate */ } printLine(dest); } } /* goodG2B2() - use goodsource and badsink by reversing the blocks in the if statement */ static void goodG2B2() { short data; /* Initialize data */ data = 0; if(staticTrue) { /* FIX: Use a positive integer less than &InitialDataSize&*/ data = 100-1; } { char source[100]; char dest[100] = ""; memset(source, 'A', 100-1); source[100-1] = '\0'; if (data < 100) { /* POTENTIAL FLAW: data is interpreted as an unsigned int - if its value is negative, * the sign extension could result in a very large number */ memmove(dest, source, data); dest[data] = '\0'; /* NULL terminate */ } printLine(dest); } } void CWE194_Unexpected_Sign_Extension__fscanf_memmove_05_good() { goodG2B1(); goodG2B2(); } #endif /* OMITGOOD */ /* Below is the main(). It is only used when building this testcase on * its own for testing or for building a binary to use in testing binary * analysis tools. It is not used when compiling all the testcases as one * application, which is how source code analysis tools are tested. */ #ifdef INCLUDEMAIN int main(int argc, char * argv[]) { /* seed randomness */ srand( (unsigned)time(NULL) ); #ifndef OMITGOOD printLine("Calling good()..."); CWE194_Unexpected_Sign_Extension__fscanf_memmove_05_good(); printLine("Finished good()"); #endif /* OMITGOOD */ #ifndef OMITBAD printLine("Calling bad()..."); CWE194_Unexpected_Sign_Extension__fscanf_memmove_05_bad(); printLine("Finished bad()"); #endif /* OMITBAD */ return 0; } #endif
630114.c
/* $NetBSD: sprintf_chk.c,v 1.6 2009/02/05 05:40:36 lukem Exp $ */ /*- * Copyright (c) 2006 The NetBSD Foundation, Inc. * All rights reserved. * * This code is derived from software contributed to The NetBSD Foundation * by Christos Zoulas. * * 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 NETBSD FOUNDATION, INC. AND CONTRIBUTORS * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include <sys/cdefs.h> __RCSID("$NetBSD: sprintf_chk.c,v 1.6 2009/02/05 05:40:36 lukem Exp $"); /*LINTLIBRARY*/ #include <ssp/ssp.h> #include <stdio.h> #include <limits.h> #include <stdarg.h> #include <ssp/stdio.h> #undef vsnprintf #undef vsprintf int /*ARGSUSED*/ __sprintf_chk(char * __restrict buf, int flags, size_t slen, const char * __restrict fmt, ...) { va_list ap; int rv; va_start(ap, fmt); if (slen > (size_t)INT_MAX) rv = vsprintf(buf, fmt, ap); else { if ((rv = vsnprintf(buf, slen, fmt, ap)) >= 0 && (size_t)rv >= slen) __chk_fail(); } va_end(ap); return rv; }
491588.c
/*- * SPDX-License-Identifier: BSD-2-Clause * * BSD LICENSE * * Copyright(c) 2008 - 2011 Intel Corporation. All rights reserved. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <sys/cdefs.h> __FBSDID("$FreeBSD$"); #include <dev/isci/isci.h> #include <dev/isci/scil/scif_controller.h> #include <dev/isci/scil/scif_user_callback.h> /** * @brief This user callback will inform the user that a task management * request completed. * * @param[in] controller This parameter specifies the controller on * which the task management request is completing. * @param[in] remote_device This parameter specifies the remote device on * which this task management request is completing. * @param[in] task_request This parameter specifies the task management * request that has completed. * @param[in] completion_status This parameter specifies the results of * the IO request operation. SCI_TASK_SUCCESS indicates * successful completion. * * @return none */ void scif_cb_task_request_complete(SCI_CONTROLLER_HANDLE_T controller, SCI_REMOTE_DEVICE_HANDLE_T remote_device, SCI_TASK_REQUEST_HANDLE_T task_request, SCI_TASK_STATUS completion_status) { scif_controller_complete_task(controller, remote_device, task_request); isci_task_request_complete(controller, remote_device, task_request, completion_status); } /** * @brief This method returns the Logical Unit to be utilized for this * task management request. * * @note The contents of the value returned from this callback are defined * by the protocol standard (e.g. T10 SAS specification). Please * refer to the transport task information unit description * in the associated standard. * * @param[in] scif_user_task_request This parameter points to the user's * task request object. It is a cookie that allows the user to * provide the necessary information for this callback. * * @return This method returns the LUN associated with this request. * @todo This should be U64? */ uint32_t scif_cb_task_request_get_lun(void * scif_user_task_request) { /* Currently we are only doing hard resets, not LUN resets. So * always returning 0 is OK here, since LUN doesn't matter for * a hard device reset. */ return (0); } /** * @brief This method returns the task management function to be utilized * for this task request. * * @note The contents of the value returned from this callback are defined * by the protocol standard (e.g. T10 SAS specification). Please * refer to the transport task information unit description * in the associated standard. * * @param[in] scif_user_task_request This parameter points to the user's * task request object. It is a cookie that allows the user to * provide the necessary information for this callback. * * @return This method returns an unsigned byte representing the task * management function to be performed. */ uint8_t scif_cb_task_request_get_function(void * scif_user_task_request) { /* SCIL supports many types of task management functions, but this * driver only uses HARD_RESET. */ return (SCI_SAS_HARD_RESET); } /** * @brief This method returns the task management IO tag to be managed. * Depending upon the task management function the value returned * from this method may be ignored. * * @param[in] scif_user_task_request This parameter points to the user's * task request object. It is a cookie that allows the user to * provide the necessary information for this callback. * * @return This method returns an unsigned 16-bit word depicting the IO * tag to be managed. */ uint16_t scif_cb_task_request_get_io_tag_to_manage(void * scif_user_task_request) { return (0); } /** * @brief This callback method asks the user to provide the virtual * address of the response data buffer for the supplied IO request. * * @param[in] scif_user_task_request This parameter points to the user's * task request object. It is a cookie that allows the user to * provide the necessary information for this callback. * * @return This method returns the virtual address for the response data buffer * associated with this IO request. */ void * scif_cb_task_request_get_response_data_address(void * scif_user_task_request) { struct ISCI_TASK_REQUEST *task_request = (struct ISCI_TASK_REQUEST *)scif_user_task_request; return (&task_request->sense_data); } /** * @brief This callback method asks the user to provide the length of the * response data buffer for the supplied IO request. * * @param[in] scif_user_task_request This parameter points to the user's * task request object. It is a cookie that allows the user to * provide the necessary information for this callback. * * @return This method returns the length of the response buffer data * associated with this IO request. */ uint32_t scif_cb_task_request_get_response_data_length(void * scif_user_task_request) { return (sizeof(struct scsi_sense_data)); } void isci_task_request_complete(SCI_CONTROLLER_HANDLE_T scif_controller, SCI_REMOTE_DEVICE_HANDLE_T remote_device, SCI_TASK_REQUEST_HANDLE_T task_request, SCI_TASK_STATUS completion_status) { struct ISCI_TASK_REQUEST *isci_task_request = (struct ISCI_TASK_REQUEST *)sci_object_get_association(task_request); struct ISCI_CONTROLLER *isci_controller = (struct ISCI_CONTROLLER *)sci_object_get_association(scif_controller); struct ISCI_REMOTE_DEVICE *isci_remote_device = (struct ISCI_REMOTE_DEVICE *)sci_object_get_association(remote_device); struct ISCI_REMOTE_DEVICE *pending_remote_device; BOOL retry_task = FALSE; union ccb *ccb = isci_task_request->ccb; isci_remote_device->is_resetting = FALSE; switch ((int)completion_status) { case SCI_TASK_SUCCESS: case SCI_TASK_FAILURE_RESPONSE_VALID: break; case SCI_TASK_FAILURE_INVALID_STATE: retry_task = TRUE; isci_log_message(0, "ISCI", "task failure (invalid state) - retrying\n"); break; case SCI_TASK_FAILURE_INSUFFICIENT_RESOURCES: retry_task = TRUE; isci_log_message(0, "ISCI", "task failure (insufficient resources) - retrying\n"); break; case SCI_FAILURE_TIMEOUT: if (isci_controller->fail_on_task_timeout) { retry_task = FALSE; isci_log_message(0, "ISCI", "task timeout - not retrying\n"); scif_cb_domain_device_removed(scif_controller, isci_remote_device->domain->sci_object, remote_device); } else { retry_task = TRUE; isci_log_message(0, "ISCI", "task timeout - retrying\n"); } break; case SCI_TASK_FAILURE: case SCI_TASK_FAILURE_UNSUPPORTED_PROTOCOL: case SCI_TASK_FAILURE_INVALID_TAG: case SCI_TASK_FAILURE_CONTROLLER_SPECIFIC_ERR: case SCI_TASK_FAILURE_TERMINATED: case SCI_TASK_FAILURE_INVALID_PARAMETER_VALUE: isci_log_message(0, "ISCI", "unhandled task completion code 0x%x\n", completion_status); break; default: isci_log_message(0, "ISCI", "unhandled task completion code 0x%x\n", completion_status); break; } if (isci_controller->is_frozen == TRUE) { isci_controller->is_frozen = FALSE; xpt_release_simq(isci_controller->sim, TRUE); } sci_pool_put(isci_controller->request_pool, (struct ISCI_REQUEST *)isci_task_request); /* Make sure we release the device queue, since it may have been frozen * if someone tried to start an I/O while the task was in progress. */ isci_remote_device_release_device_queue(isci_remote_device); if (retry_task == TRUE) isci_remote_device_reset(isci_remote_device, ccb); else { pending_remote_device = sci_fast_list_remove_head( &isci_controller->pending_device_reset_list); if (pending_remote_device != NULL) { /* Any resets that were triggered from an XPT_RESET_DEV * CCB are never put in the pending list if the request * pool is empty - they are given back to CAM to be * requeued. So we will alawys pass NULL here, * denoting that there is no CCB associated with the * device reset. */ isci_remote_device_reset(pending_remote_device, NULL); } else if (ccb != NULL) { /* There was a CCB associated with this reset, so mark * it complete and return it to CAM. */ ccb->ccb_h.status &= ~CAM_STATUS_MASK; ccb->ccb_h.status |= CAM_REQ_CMP; xpt_done(ccb); } } }
617652.c
/* Generated by Pyrex */ #define PY_SSIZE_T_CLEAN #include "Python.h" #include "structmember.h" #ifndef PY_LONG_LONG #define PY_LONG_LONG LONG_LONG #endif #if PY_VERSION_HEX < 0x02050000 typedef int Py_ssize_t; #define PY_SSIZE_T_MAX INT_MAX #define PY_SSIZE_T_MIN INT_MIN #define PyInt_FromSsize_t(z) PyInt_FromLong(z) #define PyInt_AsSsize_t(o) PyInt_AsLong(o) #endif #if !defined(WIN32) && !defined(MS_WINDOWS) #ifndef __stdcall #define __stdcall #endif #ifndef __cdecl #define __cdecl #endif #endif #ifdef __cplusplus #define __PYX_EXTERN_C extern "C" #else #define __PYX_EXTERN_C extern #endif #include <math.h> typedef struct {PyObject **p; int i; char *s; long n;} __Pyx_StringTabEntry; /*proto*/ static PyObject *__pyx_m; static PyObject *__pyx_b; static int __pyx_lineno; static char *__pyx_filename; static char **__pyx_f; static int __Pyx_InitStrings(__Pyx_StringTabEntry *t); /*proto*/ static void __Pyx_AddTraceback(char *funcname); /*proto*/ /* Declarations from ewing4 */ /* Declarations from implementation of ewing4 */ static void __pyx_f_6ewing4_f(void); /*proto*/ static __Pyx_StringTabEntry __pyx_string_tab[] = { {0, 0, 0, 0} }; /* Implementation of ewing4 */ static void __pyx_f_6ewing4_f(void) { } static struct PyMethodDef __pyx_methods[] = { {0, 0, 0, 0} }; static void __pyx_init_filenames(void); /*proto*/ PyMODINIT_FUNC initewing4(void); /*proto*/ PyMODINIT_FUNC initewing4(void) { __pyx_init_filenames(); __pyx_m = Py_InitModule4("ewing4", __pyx_methods, 0, 0, PYTHON_API_VERSION); if (!__pyx_m) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; goto __pyx_L1;}; Py_INCREF(__pyx_m); __pyx_b = PyImport_AddModule("__builtin__"); if (!__pyx_b) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; goto __pyx_L1;}; if (PyObject_SetAttrString(__pyx_m, "__builtins__", __pyx_b) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; goto __pyx_L1;}; if (__Pyx_InitStrings(__pyx_string_tab) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; goto __pyx_L1;}; return; __pyx_L1:; __Pyx_AddTraceback("ewing4"); } static char *__pyx_filenames[] = { "ewing4.pyx", }; /* Runtime support code */ static void __pyx_init_filenames(void) { __pyx_f = __pyx_filenames; } static int __Pyx_InitStrings(__Pyx_StringTabEntry *t) { while (t->p) { *t->p = PyString_FromStringAndSize(t->s, t->n - 1); if (!*t->p) return -1; if (t->i) PyString_InternInPlace(t->p); ++t; } return 0; } #include "compile.h" #include "frameobject.h" #include "traceback.h" static void __Pyx_AddTraceback(char *funcname) { PyObject *py_srcfile = 0; PyObject *py_funcname = 0; PyObject *py_globals = 0; PyObject *empty_tuple = 0; PyObject *empty_string = 0; PyCodeObject *py_code = 0; PyFrameObject *py_frame = 0; py_srcfile = PyString_FromString(__pyx_filename); if (!py_srcfile) goto bad; py_funcname = PyString_FromString(funcname); if (!py_funcname) goto bad; py_globals = PyModule_GetDict(__pyx_m); if (!py_globals) goto bad; empty_tuple = PyTuple_New(0); if (!empty_tuple) goto bad; empty_string = PyString_FromString(""); if (!empty_string) goto bad; py_code = PyCode_New( 0, /*int argcount,*/ 0, /*int nlocals,*/ 0, /*int stacksize,*/ 0, /*int flags,*/ empty_string, /*PyObject *code,*/ empty_tuple, /*PyObject *consts,*/ empty_tuple, /*PyObject *names,*/ empty_tuple, /*PyObject *varnames,*/ empty_tuple, /*PyObject *freevars,*/ empty_tuple, /*PyObject *cellvars,*/ py_srcfile, /*PyObject *filename,*/ py_funcname, /*PyObject *name,*/ __pyx_lineno, /*int firstlineno,*/ empty_string /*PyObject *lnotab*/ ); if (!py_code) goto bad; py_frame = PyFrame_New( PyThreadState_Get(), /*PyThreadState *tstate,*/ py_code, /*PyCodeObject *code,*/ py_globals, /*PyObject *globals,*/ 0 /*PyObject *locals*/ ); if (!py_frame) goto bad; py_frame->f_lineno = __pyx_lineno; PyTraceBack_Here(py_frame); bad: Py_XDECREF(py_srcfile); Py_XDECREF(py_funcname); Py_XDECREF(empty_tuple); Py_XDECREF(empty_string); Py_XDECREF(py_code); Py_XDECREF(py_frame); }
118159.c
#include <lib9.h> #include <bio.h> #include <ctype.h> #include "mach.h" #define Extern extern #include "acid.h" #include "y.tab.h" static int syren; Lsym* unique(char *buf, Sym *s) { Lsym *l; int i, renamed; renamed = 0; strcpy(buf, s->name); for(;;) { l = look(buf); if(l == 0 || (l->lexval == Tid && l->v->set == 0)) break; if(syren == 0 && !quiet) { print("Symbol renames:\n"); syren = 1; } i = strlen(buf)+1; memmove(buf+1, buf, i); buf[0] = '$'; renamed++; if(renamed > 5 && !quiet) { print("Too many renames; must be X source!\n"); break; } } if(renamed && !quiet) print("\t%s=%s %c/%llux\n", s->name, buf, s->type, s->value); if(l == 0) l = enter(buf, Tid); return l; } void varsym(void) { int i; Sym *s; long n; Lsym *l; ulong v; char buf[1024]; List *list, **tail, *l2, *tl; tail = &l2; l2 = 0; symbase(&n); for(i = 0; i < n; i++) { s = getsym(i); switch(s->type) { case 'T': case 'L': case 'D': case 'B': case 'b': case 'd': case 'l': case 't': if(s->name[0] == '.') continue; v = s->value; tl = al(TLIST); *tail = tl; tail = &tl->next; l = unique(buf, s); l->v->set = 1; l->v->type = TINT; l->v->vstore.u0.sival = v; if(l->v->vstore.comt == 0) l->v->vstore.fmt = 'X'; /* Enter as list of { name, type, value } */ list = al(TSTRING); tl->lstore.u0.sl = list; list->lstore.u0.sstring = strnode(buf); list->lstore.fmt = 's'; list->next = al(TINT); list = list->next; list->lstore.fmt = 'c'; list->lstore.u0.sival = s->type; list->next = al(TINT); list = list->next; list->lstore.fmt = 'X'; list->lstore.u0.sival = v; } } l = mkvar("symbols"); l->v->set = 1; l->v->type = TLIST; l->v->vstore.u0.sl = l2; if(l2 == 0) print("no symbol information\n"); } void varreg(void) { Lsym *l; Value *v; Reglist *r; List **tail, *li; l = mkvar("registers"); v = l->v; v->set = 1; v->type = TLIST; v->vstore.u0.sl = 0; tail = &v->vstore.u0.sl; for(r = mach->reglist; r->rname; r++) { l = mkvar(r->rname); v = l->v; v->set = 1; v->vstore.u0.sival = r->roffs; v->vstore.fmt = r->rformat; v->type = TINT; li = al(TSTRING); li->lstore.u0.sstring = strnode(r->rname); li->lstore.fmt = 's'; *tail = li; tail = &li->next; } if(machdata == 0) return; l = mkvar("bpinst"); /* Breakpoint text */ v = l->v; v->type = TSTRING; v->vstore.fmt = 's'; v->set = 1; v->vstore.u0.sstring = gmalloc(sizeof(String)); v->vstore.u0.sstring->len = machdata->bpsize; v->vstore.u0.sstring->string = gmalloc(machdata->bpsize); memmove(v->vstore.u0.sstring->string, machdata->bpinst, machdata->bpsize); } void loadvars(void) { Lsym *l; Value *v; l = mkvar("proc"); v = l->v; v->type = TINT; v->vstore.fmt = 'X'; v->set = 1; v->vstore.u0.sival = 0; l = mkvar("pid"); /* Current process */ v = l->v; v->type = TINT; v->vstore.fmt = 'D'; v->set = 1; v->vstore.u0.sival = 0; mkvar("notes"); /* Pending notes */ l = mkvar("proclist"); /* Attached processes */ l->v->type = TLIST; l = mkvar("rdebug"); /* remote debugging enabled? */ v = l->v; v->type = TINT; v->vstore.fmt = 'D'; v->set = 1; v->vstore.u0.sival = rdebug; if(rdebug) { l = mkvar("_breakid"); v = l->v; v->type = TINT; v->vstore.fmt = 'D'; v->set = 1; v->vstore.u0.sival = -1; } } uvlong rget(Map *map, char *reg) { Lsym *s; ulong x; uvlong v; int ret; s = look(reg); if(s == 0) fatal("rget: %s\n", reg); if(s->v->vstore.fmt == 'Y') ret = get8(map, s->v->vstore.u0.sival, &v); else { ret = get4(map, (long)s->v->vstore.u0.sival, &x); v = x; } if(ret < 0) error("can't get register %s: %r\n", reg); return v; } String* strnodlen(char *name, int len) { String *s; s = gmalloc(sizeof(String)+len+1); s->string = (char*)s+sizeof(String); s->len = len; if(name != 0) memmove(s->string, name, len); s->string[len] = '\0'; s->sgc.gclink = gcl; gcl = &s->sgc; return s; } String* strnode(char *name) { return strnodlen(name, strlen(name)); } String* runenode(Rune *name) { int len; Rune *p; String *s; p = name; for(len = 0; *p; p++) len++; len++; len *= sizeof(Rune); s = gmalloc(sizeof(String)+len); s->string = (char*)s+sizeof(String); s->len = len; memmove(s->string, name, len); s->sgc.gclink = gcl; gcl = &s->sgc; return s; } String* stradd(String *l, String *r) { int len; String *s; len = l->len+r->len; s = gmalloc(sizeof(String)+len+1); s->sgc.gclink = gcl; gcl = &s->sgc; s->len = len; s->string = (char*)s+sizeof(String); memmove(s->string, l->string, l->len); memmove(s->string+l->len, r->string, r->len); s->string[s->len] = 0; return s; } int scmp(String *sr, String *sl) { if(sr->len != sl->len) return 0; if(memcmp(sr->string, sl->string, sl->len)) return 0; return 1; }
1002342.c
// Copyright 2019 Espressif Systems (Shanghai) PTE 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. #include "bootloader_common.h" #include "bootloader_clock.h" #include "soc/efuse_reg.h" #include "soc/apb_ctrl_reg.h" uint8_t bootloader_common_get_chip_revision(void) { uint8_t eco_bit0, eco_bit1, eco_bit2; eco_bit0 = (REG_READ(EFUSE_BLK0_RDATA3_REG) & 0xF000) >> 15; eco_bit1 = (REG_READ(EFUSE_BLK0_RDATA5_REG) & 0x100000) >> 20; eco_bit2 = (REG_READ(APB_CTRL_DATE_REG) & 0x80000000) >> 31; uint32_t combine_value = (eco_bit2 << 2) | (eco_bit1 << 1) | eco_bit0; uint8_t chip_ver = 0; switch (combine_value) { case 0: chip_ver = 0; break; case 1: chip_ver = 1; break; case 3: chip_ver = 2; break; case 7: chip_ver = 3; break; default: chip_ver = 0; break; } return chip_ver; } int bootloader_clock_get_rated_freq_mhz() { //Check if ESP32 is rated for a CPU frequency of 160MHz only if (REG_GET_BIT(EFUSE_BLK0_RDATA3_REG, EFUSE_RD_CHIP_CPU_FREQ_RATED) && REG_GET_BIT(EFUSE_BLK0_RDATA3_REG, EFUSE_RD_CHIP_CPU_FREQ_LOW)) { return 160; } return 240; }
66901.c
/* * Copyright (c) 2004, 2005 Topspin Communications. All rights reserved. * Copyright (c) 2005, 2006, 2007, 2008 Mellanox Technologies. All rights reserved. * Copyright (c) 2005, 2006, 2007 Cisco Systems, Inc. All rights reserved. * * This software is available to you under a choice of one of two * licenses. You may choose to be licensed under the terms of the GNU * General Public License (GPL) Version 2, available from the file * COPYING in the main directory of this source tree, or the * OpenIB.org BSD license below: * * Redistribution and use in source and binary forms, with or * without modification, are permitted provided that the following * conditions are met: * * - Redistributions of source code must retain the above * copyright notice, this list of conditions and the following * disclaimer. * * - Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials * provided with the distribution. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #include <linux/etherdevice.h> #include <linux/mlx4/cmd.h> #include <linux/module.h> #include <linux/cache.h> #include "fw.h" #include "icm.h" enum { MLX4_COMMAND_INTERFACE_MIN_REV = 2, MLX4_COMMAND_INTERFACE_MAX_REV = 3, MLX4_COMMAND_INTERFACE_NEW_PORT_CMDS = 3, }; extern void __buggy_use_of_MLX4_GET(void); extern void __buggy_use_of_MLX4_PUT(void); static bool enable_qos; module_param(enable_qos, bool, 0444); MODULE_PARM_DESC(enable_qos, "Enable Enhanced QoS support (default: off)"); #define MLX4_GET(dest, source, offset) \ do { \ void *__p = (char *) (source) + (offset); \ u64 val; \ switch (sizeof (dest)) { \ case 1: (dest) = *(u8 *) __p; break; \ case 2: (dest) = be16_to_cpup(__p); break; \ case 4: (dest) = be32_to_cpup(__p); break; \ case 8: val = get_unaligned((u64 *)__p); \ (dest) = be64_to_cpu(val); break; \ default: __buggy_use_of_MLX4_GET(); \ } \ } while (0) #define MLX4_PUT(dest, source, offset) \ do { \ void *__d = ((char *) (dest) + (offset)); \ switch (sizeof(source)) { \ case 1: *(u8 *) __d = (source); break; \ case 2: *(__be16 *) __d = cpu_to_be16(source); break; \ case 4: *(__be32 *) __d = cpu_to_be32(source); break; \ case 8: *(__be64 *) __d = cpu_to_be64(source); break; \ default: __buggy_use_of_MLX4_PUT(); \ } \ } while (0) static void dump_dev_cap_flags(struct mlx4_dev *dev, u64 flags) { static const char *fname[] = { [ 0] = "RC transport", [ 1] = "UC transport", [ 2] = "UD transport", [ 3] = "XRC transport", [ 6] = "SRQ support", [ 7] = "IPoIB checksum offload", [ 8] = "P_Key violation counter", [ 9] = "Q_Key violation counter", [12] = "Dual Port Different Protocol (DPDP) support", [15] = "Big LSO headers", [16] = "MW support", [17] = "APM support", [18] = "Atomic ops support", [19] = "Raw multicast support", [20] = "Address vector port checking support", [21] = "UD multicast support", [30] = "IBoE support", [32] = "Unicast loopback support", [34] = "FCS header control", [37] = "Wake On LAN (port1) support", [38] = "Wake On LAN (port2) support", [40] = "UDP RSS support", [41] = "Unicast VEP steering support", [42] = "Multicast VEP steering support", [48] = "Counters support", [52] = "RSS IP fragments support", [53] = "Port ETS Scheduler support", [55] = "Port link type sensing support", [59] = "Port management change event support", [61] = "64 byte EQE support", [62] = "64 byte CQE support", }; int i; mlx4_dbg(dev, "DEV_CAP flags:\n"); for (i = 0; i < ARRAY_SIZE(fname); ++i) if (fname[i] && (flags & (1LL << i))) mlx4_dbg(dev, " %s\n", fname[i]); } static void dump_dev_cap_flags2(struct mlx4_dev *dev, u64 flags) { static const char * const fname[] = { [0] = "RSS support", [1] = "RSS Toeplitz Hash Function support", [2] = "RSS XOR Hash Function support", [3] = "Device managed flow steering support", [4] = "Automatic MAC reassignment support", [5] = "Time stamping support", [6] = "VST (control vlan insertion/stripping) support", [7] = "FSM (MAC anti-spoofing) support", [8] = "Dynamic QP updates support", [9] = "Device managed flow steering IPoIB support", [10] = "TCP/IP offloads/flow-steering for VXLAN support", [11] = "MAD DEMUX (Secure-Host) support", [12] = "Large cache line (>64B) CQE stride support", [13] = "Large cache line (>64B) EQE stride support", [14] = "Ethernet protocol control support", [15] = "Ethernet Backplane autoneg support", [16] = "CONFIG DEV support", [17] = "Asymmetric EQs support", [18] = "More than 80 VFs support", [19] = "Performance optimized for limited rule configuration flow steering support", [20] = "Recoverable error events support", [21] = "Port Remap support", [22] = "QCN support", [23] = "QP rate limiting support", [24] = "Ethernet Flow control statistics support", [25] = "Granular QoS per VF support", [26] = "Port ETS Scheduler support", [27] = "Port beacon support", [28] = "RX-ALL support", [29] = "802.1ad offload support", [31] = "Modifying loopback source checks using UPDATE_QP support", [32] = "Loopback source checks support", [33] = "RoCEv2 support", [34] = "DMFS Sniffer support (UC & MC)", [35] = "Diag counters per port", [36] = "QinQ VST mode support", [37] = "sl to vl mapping table change event support", }; int i; for (i = 0; i < ARRAY_SIZE(fname); ++i) if (fname[i] && (flags & (1LL << i))) mlx4_dbg(dev, " %s\n", fname[i]); } int mlx4_MOD_STAT_CFG(struct mlx4_dev *dev, struct mlx4_mod_stat_cfg *cfg) { struct mlx4_cmd_mailbox *mailbox; u32 *inbox; int err = 0; #define MOD_STAT_CFG_IN_SIZE 0x100 #define MOD_STAT_CFG_PG_SZ_M_OFFSET 0x002 #define MOD_STAT_CFG_PG_SZ_OFFSET 0x003 mailbox = mlx4_alloc_cmd_mailbox(dev); if (IS_ERR(mailbox)) return PTR_ERR(mailbox); inbox = mailbox->buf; MLX4_PUT(inbox, cfg->log_pg_sz, MOD_STAT_CFG_PG_SZ_OFFSET); MLX4_PUT(inbox, cfg->log_pg_sz_m, MOD_STAT_CFG_PG_SZ_M_OFFSET); err = mlx4_cmd(dev, mailbox->dma, 0, 0, MLX4_CMD_MOD_STAT_CFG, MLX4_CMD_TIME_CLASS_A, MLX4_CMD_NATIVE); mlx4_free_cmd_mailbox(dev, mailbox); return err; } int mlx4_QUERY_FUNC(struct mlx4_dev *dev, struct mlx4_func *func, int slave) { struct mlx4_cmd_mailbox *mailbox; u32 *outbox; u8 in_modifier; u8 field; u16 field16; int err; #define QUERY_FUNC_BUS_OFFSET 0x00 #define QUERY_FUNC_DEVICE_OFFSET 0x01 #define QUERY_FUNC_FUNCTION_OFFSET 0x01 #define QUERY_FUNC_PHYSICAL_FUNCTION_OFFSET 0x03 #define QUERY_FUNC_RSVD_EQS_OFFSET 0x04 #define QUERY_FUNC_MAX_EQ_OFFSET 0x06 #define QUERY_FUNC_RSVD_UARS_OFFSET 0x0b mailbox = mlx4_alloc_cmd_mailbox(dev); if (IS_ERR(mailbox)) return PTR_ERR(mailbox); outbox = mailbox->buf; in_modifier = slave; err = mlx4_cmd_box(dev, 0, mailbox->dma, in_modifier, 0, MLX4_CMD_QUERY_FUNC, MLX4_CMD_TIME_CLASS_A, MLX4_CMD_NATIVE); if (err) goto out; MLX4_GET(field, outbox, QUERY_FUNC_BUS_OFFSET); func->bus = field & 0xf; MLX4_GET(field, outbox, QUERY_FUNC_DEVICE_OFFSET); func->device = field & 0xf1; MLX4_GET(field, outbox, QUERY_FUNC_FUNCTION_OFFSET); func->function = field & 0x7; MLX4_GET(field, outbox, QUERY_FUNC_PHYSICAL_FUNCTION_OFFSET); func->physical_function = field & 0xf; MLX4_GET(field16, outbox, QUERY_FUNC_RSVD_EQS_OFFSET); func->rsvd_eqs = field16 & 0xffff; MLX4_GET(field16, outbox, QUERY_FUNC_MAX_EQ_OFFSET); func->max_eq = field16 & 0xffff; MLX4_GET(field, outbox, QUERY_FUNC_RSVD_UARS_OFFSET); func->rsvd_uars = field & 0x0f; mlx4_dbg(dev, "Bus: %d, Device: %d, Function: %d, Physical function: %d, Max EQs: %d, Reserved EQs: %d, Reserved UARs: %d\n", func->bus, func->device, func->function, func->physical_function, func->max_eq, func->rsvd_eqs, func->rsvd_uars); out: mlx4_free_cmd_mailbox(dev, mailbox); return err; } static int mlx4_activate_vst_qinq(struct mlx4_priv *priv, int slave, int port) { struct mlx4_vport_oper_state *vp_oper; struct mlx4_vport_state *vp_admin; int err; vp_oper = &priv->mfunc.master.vf_oper[slave].vport[port]; vp_admin = &priv->mfunc.master.vf_admin[slave].vport[port]; if (vp_admin->default_vlan != vp_oper->state.default_vlan) { err = __mlx4_register_vlan(&priv->dev, port, vp_admin->default_vlan, &vp_oper->vlan_idx); if (err) { vp_oper->vlan_idx = NO_INDX; mlx4_warn(&priv->dev, "No vlan resources slave %d, port %d\n", slave, port); return err; } mlx4_dbg(&priv->dev, "alloc vlan %d idx %d slave %d port %d\n", (int)(vp_oper->state.default_vlan), vp_oper->vlan_idx, slave, port); } vp_oper->state.vlan_proto = vp_admin->vlan_proto; vp_oper->state.default_vlan = vp_admin->default_vlan; vp_oper->state.default_qos = vp_admin->default_qos; return 0; } static int mlx4_handle_vst_qinq(struct mlx4_priv *priv, int slave, int port) { struct mlx4_vport_oper_state *vp_oper; struct mlx4_slave_state *slave_state; struct mlx4_vport_state *vp_admin; int err; vp_oper = &priv->mfunc.master.vf_oper[slave].vport[port]; vp_admin = &priv->mfunc.master.vf_admin[slave].vport[port]; slave_state = &priv->mfunc.master.slave_state[slave]; if ((vp_admin->vlan_proto != htons(ETH_P_8021AD)) || (!slave_state->active)) return 0; if (vp_oper->state.vlan_proto == vp_admin->vlan_proto && vp_oper->state.default_vlan == vp_admin->default_vlan && vp_oper->state.default_qos == vp_admin->default_qos) return 0; if (!slave_state->vst_qinq_supported) { /* Warn and revert the request to set vst QinQ mode */ vp_admin->vlan_proto = vp_oper->state.vlan_proto; vp_admin->default_vlan = vp_oper->state.default_vlan; vp_admin->default_qos = vp_oper->state.default_qos; mlx4_warn(&priv->dev, "Slave %d does not support VST QinQ mode\n", slave); return 0; } err = mlx4_activate_vst_qinq(priv, slave, port); return err; } int mlx4_QUERY_FUNC_CAP_wrapper(struct mlx4_dev *dev, int slave, struct mlx4_vhcr *vhcr, struct mlx4_cmd_mailbox *inbox, struct mlx4_cmd_mailbox *outbox, struct mlx4_cmd_info *cmd) { struct mlx4_priv *priv = mlx4_priv(dev); u8 field, port; u32 size, proxy_qp, qkey; int err = 0; struct mlx4_func func; #define QUERY_FUNC_CAP_FLAGS_OFFSET 0x0 #define QUERY_FUNC_CAP_NUM_PORTS_OFFSET 0x1 #define QUERY_FUNC_CAP_PF_BHVR_OFFSET 0x4 #define QUERY_FUNC_CAP_FMR_OFFSET 0x8 #define QUERY_FUNC_CAP_QP_QUOTA_OFFSET_DEP 0x10 #define QUERY_FUNC_CAP_CQ_QUOTA_OFFSET_DEP 0x14 #define QUERY_FUNC_CAP_SRQ_QUOTA_OFFSET_DEP 0x18 #define QUERY_FUNC_CAP_MPT_QUOTA_OFFSET_DEP 0x20 #define QUERY_FUNC_CAP_MTT_QUOTA_OFFSET_DEP 0x24 #define QUERY_FUNC_CAP_MCG_QUOTA_OFFSET_DEP 0x28 #define QUERY_FUNC_CAP_MAX_EQ_OFFSET 0x2c #define QUERY_FUNC_CAP_RESERVED_EQ_OFFSET 0x30 #define QUERY_FUNC_CAP_QP_RESD_LKEY_OFFSET 0x48 #define QUERY_FUNC_CAP_QP_QUOTA_OFFSET 0x50 #define QUERY_FUNC_CAP_CQ_QUOTA_OFFSET 0x54 #define QUERY_FUNC_CAP_SRQ_QUOTA_OFFSET 0x58 #define QUERY_FUNC_CAP_MPT_QUOTA_OFFSET 0x60 #define QUERY_FUNC_CAP_MTT_QUOTA_OFFSET 0x64 #define QUERY_FUNC_CAP_MCG_QUOTA_OFFSET 0x68 #define QUERY_FUNC_CAP_EXTRA_FLAGS_OFFSET 0x6c #define QUERY_FUNC_CAP_FMR_FLAG 0x80 #define QUERY_FUNC_CAP_FLAG_RDMA 0x40 #define QUERY_FUNC_CAP_FLAG_ETH 0x80 #define QUERY_FUNC_CAP_FLAG_QUOTAS 0x10 #define QUERY_FUNC_CAP_FLAG_RESD_LKEY 0x08 #define QUERY_FUNC_CAP_FLAG_VALID_MAILBOX 0x04 #define QUERY_FUNC_CAP_EXTRA_FLAGS_BF_QP_ALLOC_FLAG (1UL << 31) #define QUERY_FUNC_CAP_EXTRA_FLAGS_A0_QP_ALLOC_FLAG (1UL << 30) /* when opcode modifier = 1 */ #define QUERY_FUNC_CAP_PHYS_PORT_OFFSET 0x3 #define QUERY_FUNC_CAP_PRIV_VF_QKEY_OFFSET 0x4 #define QUERY_FUNC_CAP_FLAGS0_OFFSET 0x8 #define QUERY_FUNC_CAP_FLAGS1_OFFSET 0xc #define QUERY_FUNC_CAP_QP0_TUNNEL 0x10 #define QUERY_FUNC_CAP_QP0_PROXY 0x14 #define QUERY_FUNC_CAP_QP1_TUNNEL 0x18 #define QUERY_FUNC_CAP_QP1_PROXY 0x1c #define QUERY_FUNC_CAP_PHYS_PORT_ID 0x28 #define QUERY_FUNC_CAP_FLAGS1_FORCE_MAC 0x40 #define QUERY_FUNC_CAP_FLAGS1_FORCE_VLAN 0x80 #define QUERY_FUNC_CAP_FLAGS1_NIC_INFO 0x10 #define QUERY_FUNC_CAP_VF_ENABLE_QP0 0x08 #define QUERY_FUNC_CAP_FLAGS0_FORCE_PHY_WQE_GID 0x80 #define QUERY_FUNC_CAP_PHV_BIT 0x40 #define QUERY_FUNC_CAP_VLAN_OFFLOAD_DISABLE 0x20 #define QUERY_FUNC_CAP_SUPPORTS_VST_QINQ BIT(30) #define QUERY_FUNC_CAP_SUPPORTS_NON_POWER_OF_2_NUM_EQS BIT(31) if (vhcr->op_modifier == 1) { struct mlx4_active_ports actv_ports = mlx4_get_active_ports(dev, slave); int converted_port = mlx4_slave_convert_port( dev, slave, vhcr->in_modifier); struct mlx4_vport_oper_state *vp_oper; if (converted_port < 0) return -EINVAL; vhcr->in_modifier = converted_port; /* phys-port = logical-port */ field = vhcr->in_modifier - find_first_bit(actv_ports.ports, dev->caps.num_ports); MLX4_PUT(outbox->buf, field, QUERY_FUNC_CAP_PHYS_PORT_OFFSET); port = vhcr->in_modifier; proxy_qp = dev->phys_caps.base_proxy_sqpn + 8 * slave + port - 1; /* Set nic_info bit to mark new fields support */ field = QUERY_FUNC_CAP_FLAGS1_NIC_INFO; if (mlx4_vf_smi_enabled(dev, slave, port) && !mlx4_get_parav_qkey(dev, proxy_qp, &qkey)) { field |= QUERY_FUNC_CAP_VF_ENABLE_QP0; MLX4_PUT(outbox->buf, qkey, QUERY_FUNC_CAP_PRIV_VF_QKEY_OFFSET); } MLX4_PUT(outbox->buf, field, QUERY_FUNC_CAP_FLAGS1_OFFSET); /* size is now the QP number */ size = dev->phys_caps.base_tunnel_sqpn + 8 * slave + port - 1; MLX4_PUT(outbox->buf, size, QUERY_FUNC_CAP_QP0_TUNNEL); size += 2; MLX4_PUT(outbox->buf, size, QUERY_FUNC_CAP_QP1_TUNNEL); MLX4_PUT(outbox->buf, proxy_qp, QUERY_FUNC_CAP_QP0_PROXY); proxy_qp += 2; MLX4_PUT(outbox->buf, proxy_qp, QUERY_FUNC_CAP_QP1_PROXY); MLX4_PUT(outbox->buf, dev->caps.phys_port_id[vhcr->in_modifier], QUERY_FUNC_CAP_PHYS_PORT_ID); vp_oper = &priv->mfunc.master.vf_oper[slave].vport[port]; err = mlx4_handle_vst_qinq(priv, slave, port); if (err) return err; field = 0; if (dev->caps.phv_bit[port]) field |= QUERY_FUNC_CAP_PHV_BIT; if (vp_oper->state.vlan_proto == htons(ETH_P_8021AD)) field |= QUERY_FUNC_CAP_VLAN_OFFLOAD_DISABLE; MLX4_PUT(outbox->buf, field, QUERY_FUNC_CAP_FLAGS0_OFFSET); } else if (vhcr->op_modifier == 0) { struct mlx4_active_ports actv_ports = mlx4_get_active_ports(dev, slave); struct mlx4_slave_state *slave_state = &priv->mfunc.master.slave_state[slave]; /* enable rdma and ethernet interfaces, new quota locations, * and reserved lkey */ field = (QUERY_FUNC_CAP_FLAG_ETH | QUERY_FUNC_CAP_FLAG_RDMA | QUERY_FUNC_CAP_FLAG_QUOTAS | QUERY_FUNC_CAP_FLAG_VALID_MAILBOX | QUERY_FUNC_CAP_FLAG_RESD_LKEY); MLX4_PUT(outbox->buf, field, QUERY_FUNC_CAP_FLAGS_OFFSET); field = min( bitmap_weight(actv_ports.ports, dev->caps.num_ports), dev->caps.num_ports); MLX4_PUT(outbox->buf, field, QUERY_FUNC_CAP_NUM_PORTS_OFFSET); size = dev->caps.function_caps; /* set PF behaviours */ MLX4_PUT(outbox->buf, size, QUERY_FUNC_CAP_PF_BHVR_OFFSET); field = 0; /* protected FMR support not available as yet */ MLX4_PUT(outbox->buf, field, QUERY_FUNC_CAP_FMR_OFFSET); size = priv->mfunc.master.res_tracker.res_alloc[RES_QP].quota[slave]; MLX4_PUT(outbox->buf, size, QUERY_FUNC_CAP_QP_QUOTA_OFFSET); size = dev->caps.num_qps; MLX4_PUT(outbox->buf, size, QUERY_FUNC_CAP_QP_QUOTA_OFFSET_DEP); size = priv->mfunc.master.res_tracker.res_alloc[RES_SRQ].quota[slave]; MLX4_PUT(outbox->buf, size, QUERY_FUNC_CAP_SRQ_QUOTA_OFFSET); size = dev->caps.num_srqs; MLX4_PUT(outbox->buf, size, QUERY_FUNC_CAP_SRQ_QUOTA_OFFSET_DEP); size = priv->mfunc.master.res_tracker.res_alloc[RES_CQ].quota[slave]; MLX4_PUT(outbox->buf, size, QUERY_FUNC_CAP_CQ_QUOTA_OFFSET); size = dev->caps.num_cqs; MLX4_PUT(outbox->buf, size, QUERY_FUNC_CAP_CQ_QUOTA_OFFSET_DEP); if (!(dev->caps.flags2 & MLX4_DEV_CAP_FLAG2_SYS_EQS) || mlx4_QUERY_FUNC(dev, &func, slave)) { size = vhcr->in_modifier & QUERY_FUNC_CAP_SUPPORTS_NON_POWER_OF_2_NUM_EQS ? dev->caps.num_eqs : rounddown_pow_of_two(dev->caps.num_eqs); MLX4_PUT(outbox->buf, size, QUERY_FUNC_CAP_MAX_EQ_OFFSET); size = dev->caps.reserved_eqs; MLX4_PUT(outbox->buf, size, QUERY_FUNC_CAP_RESERVED_EQ_OFFSET); } else { size = vhcr->in_modifier & QUERY_FUNC_CAP_SUPPORTS_NON_POWER_OF_2_NUM_EQS ? func.max_eq : rounddown_pow_of_two(func.max_eq); MLX4_PUT(outbox->buf, size, QUERY_FUNC_CAP_MAX_EQ_OFFSET); size = func.rsvd_eqs; MLX4_PUT(outbox->buf, size, QUERY_FUNC_CAP_RESERVED_EQ_OFFSET); } size = priv->mfunc.master.res_tracker.res_alloc[RES_MPT].quota[slave]; MLX4_PUT(outbox->buf, size, QUERY_FUNC_CAP_MPT_QUOTA_OFFSET); size = dev->caps.num_mpts; MLX4_PUT(outbox->buf, size, QUERY_FUNC_CAP_MPT_QUOTA_OFFSET_DEP); size = priv->mfunc.master.res_tracker.res_alloc[RES_MTT].quota[slave]; MLX4_PUT(outbox->buf, size, QUERY_FUNC_CAP_MTT_QUOTA_OFFSET); size = dev->caps.num_mtts; MLX4_PUT(outbox->buf, size, QUERY_FUNC_CAP_MTT_QUOTA_OFFSET_DEP); size = dev->caps.num_mgms + dev->caps.num_amgms; MLX4_PUT(outbox->buf, size, QUERY_FUNC_CAP_MCG_QUOTA_OFFSET); MLX4_PUT(outbox->buf, size, QUERY_FUNC_CAP_MCG_QUOTA_OFFSET_DEP); size = QUERY_FUNC_CAP_EXTRA_FLAGS_BF_QP_ALLOC_FLAG | QUERY_FUNC_CAP_EXTRA_FLAGS_A0_QP_ALLOC_FLAG; MLX4_PUT(outbox->buf, size, QUERY_FUNC_CAP_EXTRA_FLAGS_OFFSET); size = dev->caps.reserved_lkey + ((slave << 8) & 0xFF00); MLX4_PUT(outbox->buf, size, QUERY_FUNC_CAP_QP_RESD_LKEY_OFFSET); if (vhcr->in_modifier & QUERY_FUNC_CAP_SUPPORTS_VST_QINQ) slave_state->vst_qinq_supported = true; } else err = -EINVAL; return err; } int mlx4_QUERY_FUNC_CAP(struct mlx4_dev *dev, u8 gen_or_port, struct mlx4_func_cap *func_cap) { struct mlx4_cmd_mailbox *mailbox; u32 *outbox; u8 field, op_modifier; u32 size, qkey; int err = 0, quotas = 0; u32 in_modifier; u32 slave_caps; op_modifier = !!gen_or_port; /* 0 = general, 1 = logical port */ slave_caps = QUERY_FUNC_CAP_SUPPORTS_VST_QINQ | QUERY_FUNC_CAP_SUPPORTS_NON_POWER_OF_2_NUM_EQS; in_modifier = op_modifier ? gen_or_port : slave_caps; mailbox = mlx4_alloc_cmd_mailbox(dev); if (IS_ERR(mailbox)) return PTR_ERR(mailbox); err = mlx4_cmd_box(dev, 0, mailbox->dma, in_modifier, op_modifier, MLX4_CMD_QUERY_FUNC_CAP, MLX4_CMD_TIME_CLASS_A, MLX4_CMD_WRAPPED); if (err) goto out; outbox = mailbox->buf; if (!op_modifier) { MLX4_GET(field, outbox, QUERY_FUNC_CAP_FLAGS_OFFSET); if (!(field & (QUERY_FUNC_CAP_FLAG_ETH | QUERY_FUNC_CAP_FLAG_RDMA))) { mlx4_err(dev, "The host supports neither eth nor rdma interfaces\n"); err = -EPROTONOSUPPORT; goto out; } func_cap->flags = field; quotas = !!(func_cap->flags & QUERY_FUNC_CAP_FLAG_QUOTAS); MLX4_GET(field, outbox, QUERY_FUNC_CAP_NUM_PORTS_OFFSET); func_cap->num_ports = field; MLX4_GET(size, outbox, QUERY_FUNC_CAP_PF_BHVR_OFFSET); func_cap->pf_context_behaviour = size; if (quotas) { MLX4_GET(size, outbox, QUERY_FUNC_CAP_QP_QUOTA_OFFSET); func_cap->qp_quota = size & 0xFFFFFF; MLX4_GET(size, outbox, QUERY_FUNC_CAP_SRQ_QUOTA_OFFSET); func_cap->srq_quota = size & 0xFFFFFF; MLX4_GET(size, outbox, QUERY_FUNC_CAP_CQ_QUOTA_OFFSET); func_cap->cq_quota = size & 0xFFFFFF; MLX4_GET(size, outbox, QUERY_FUNC_CAP_MPT_QUOTA_OFFSET); func_cap->mpt_quota = size & 0xFFFFFF; MLX4_GET(size, outbox, QUERY_FUNC_CAP_MTT_QUOTA_OFFSET); func_cap->mtt_quota = size & 0xFFFFFF; MLX4_GET(size, outbox, QUERY_FUNC_CAP_MCG_QUOTA_OFFSET); func_cap->mcg_quota = size & 0xFFFFFF; } else { MLX4_GET(size, outbox, QUERY_FUNC_CAP_QP_QUOTA_OFFSET_DEP); func_cap->qp_quota = size & 0xFFFFFF; MLX4_GET(size, outbox, QUERY_FUNC_CAP_SRQ_QUOTA_OFFSET_DEP); func_cap->srq_quota = size & 0xFFFFFF; MLX4_GET(size, outbox, QUERY_FUNC_CAP_CQ_QUOTA_OFFSET_DEP); func_cap->cq_quota = size & 0xFFFFFF; MLX4_GET(size, outbox, QUERY_FUNC_CAP_MPT_QUOTA_OFFSET_DEP); func_cap->mpt_quota = size & 0xFFFFFF; MLX4_GET(size, outbox, QUERY_FUNC_CAP_MTT_QUOTA_OFFSET_DEP); func_cap->mtt_quota = size & 0xFFFFFF; MLX4_GET(size, outbox, QUERY_FUNC_CAP_MCG_QUOTA_OFFSET_DEP); func_cap->mcg_quota = size & 0xFFFFFF; } MLX4_GET(size, outbox, QUERY_FUNC_CAP_MAX_EQ_OFFSET); func_cap->max_eq = size & 0xFFFFFF; MLX4_GET(size, outbox, QUERY_FUNC_CAP_RESERVED_EQ_OFFSET); func_cap->reserved_eq = size & 0xFFFFFF; if (func_cap->flags & QUERY_FUNC_CAP_FLAG_RESD_LKEY) { MLX4_GET(size, outbox, QUERY_FUNC_CAP_QP_RESD_LKEY_OFFSET); func_cap->reserved_lkey = size; } else { func_cap->reserved_lkey = 0; } func_cap->extra_flags = 0; /* Mailbox data from 0x6c and onward should only be treated if * QUERY_FUNC_CAP_FLAG_VALID_MAILBOX is set in func_cap->flags */ if (func_cap->flags & QUERY_FUNC_CAP_FLAG_VALID_MAILBOX) { MLX4_GET(size, outbox, QUERY_FUNC_CAP_EXTRA_FLAGS_OFFSET); if (size & QUERY_FUNC_CAP_EXTRA_FLAGS_BF_QP_ALLOC_FLAG) func_cap->extra_flags |= MLX4_QUERY_FUNC_FLAGS_BF_RES_QP; if (size & QUERY_FUNC_CAP_EXTRA_FLAGS_A0_QP_ALLOC_FLAG) func_cap->extra_flags |= MLX4_QUERY_FUNC_FLAGS_A0_RES_QP; } goto out; } /* logical port query */ if (gen_or_port > dev->caps.num_ports) { err = -EINVAL; goto out; } MLX4_GET(func_cap->flags1, outbox, QUERY_FUNC_CAP_FLAGS1_OFFSET); if (dev->caps.port_type[gen_or_port] == MLX4_PORT_TYPE_ETH) { if (func_cap->flags1 & QUERY_FUNC_CAP_FLAGS1_FORCE_VLAN) { mlx4_err(dev, "VLAN is enforced on this port\n"); err = -EPROTONOSUPPORT; goto out; } if (func_cap->flags1 & QUERY_FUNC_CAP_FLAGS1_FORCE_MAC) { mlx4_err(dev, "Force mac is enabled on this port\n"); err = -EPROTONOSUPPORT; goto out; } } else if (dev->caps.port_type[gen_or_port] == MLX4_PORT_TYPE_IB) { MLX4_GET(field, outbox, QUERY_FUNC_CAP_FLAGS0_OFFSET); if (field & QUERY_FUNC_CAP_FLAGS0_FORCE_PHY_WQE_GID) { mlx4_err(dev, "phy_wqe_gid is enforced on this ib port\n"); err = -EPROTONOSUPPORT; goto out; } } MLX4_GET(field, outbox, QUERY_FUNC_CAP_PHYS_PORT_OFFSET); func_cap->physical_port = field; if (func_cap->physical_port != gen_or_port) { err = -EINVAL; goto out; } if (func_cap->flags1 & QUERY_FUNC_CAP_VF_ENABLE_QP0) { MLX4_GET(qkey, outbox, QUERY_FUNC_CAP_PRIV_VF_QKEY_OFFSET); func_cap->qp0_qkey = qkey; } else { func_cap->qp0_qkey = 0; } MLX4_GET(size, outbox, QUERY_FUNC_CAP_QP0_TUNNEL); func_cap->qp0_tunnel_qpn = size & 0xFFFFFF; MLX4_GET(size, outbox, QUERY_FUNC_CAP_QP0_PROXY); func_cap->qp0_proxy_qpn = size & 0xFFFFFF; MLX4_GET(size, outbox, QUERY_FUNC_CAP_QP1_TUNNEL); func_cap->qp1_tunnel_qpn = size & 0xFFFFFF; MLX4_GET(size, outbox, QUERY_FUNC_CAP_QP1_PROXY); func_cap->qp1_proxy_qpn = size & 0xFFFFFF; if (func_cap->flags1 & QUERY_FUNC_CAP_FLAGS1_NIC_INFO) MLX4_GET(func_cap->phys_port_id, outbox, QUERY_FUNC_CAP_PHYS_PORT_ID); MLX4_GET(func_cap->flags0, outbox, QUERY_FUNC_CAP_FLAGS0_OFFSET); /* All other resources are allocated by the master, but we still report * 'num' and 'reserved' capabilities as follows: * - num remains the maximum resource index * - 'num - reserved' is the total available objects of a resource, but * resource indices may be less than 'reserved' * TODO: set per-resource quotas */ out: mlx4_free_cmd_mailbox(dev, mailbox); return err; } static void disable_unsupported_roce_caps(void *buf); int mlx4_QUERY_DEV_CAP(struct mlx4_dev *dev, struct mlx4_dev_cap *dev_cap) { struct mlx4_cmd_mailbox *mailbox; u32 *outbox; u8 field; u32 field32, flags, ext_flags; u16 size; u16 stat_rate; int err; int i; #define QUERY_DEV_CAP_OUT_SIZE 0x100 #define QUERY_DEV_CAP_MAX_SRQ_SZ_OFFSET 0x10 #define QUERY_DEV_CAP_MAX_QP_SZ_OFFSET 0x11 #define QUERY_DEV_CAP_RSVD_QP_OFFSET 0x12 #define QUERY_DEV_CAP_MAX_QP_OFFSET 0x13 #define QUERY_DEV_CAP_RSVD_SRQ_OFFSET 0x14 #define QUERY_DEV_CAP_MAX_SRQ_OFFSET 0x15 #define QUERY_DEV_CAP_RSVD_EEC_OFFSET 0x16 #define QUERY_DEV_CAP_MAX_EEC_OFFSET 0x17 #define QUERY_DEV_CAP_MAX_CQ_SZ_OFFSET 0x19 #define QUERY_DEV_CAP_RSVD_CQ_OFFSET 0x1a #define QUERY_DEV_CAP_MAX_CQ_OFFSET 0x1b #define QUERY_DEV_CAP_MAX_MPT_OFFSET 0x1d #define QUERY_DEV_CAP_RSVD_EQ_OFFSET 0x1e #define QUERY_DEV_CAP_MAX_EQ_OFFSET 0x1f #define QUERY_DEV_CAP_RSVD_MTT_OFFSET 0x20 #define QUERY_DEV_CAP_MAX_MRW_SZ_OFFSET 0x21 #define QUERY_DEV_CAP_RSVD_MRW_OFFSET 0x22 #define QUERY_DEV_CAP_MAX_MTT_SEG_OFFSET 0x23 #define QUERY_DEV_CAP_NUM_SYS_EQ_OFFSET 0x26 #define QUERY_DEV_CAP_MAX_AV_OFFSET 0x27 #define QUERY_DEV_CAP_MAX_REQ_QP_OFFSET 0x29 #define QUERY_DEV_CAP_MAX_RES_QP_OFFSET 0x2b #define QUERY_DEV_CAP_MAX_GSO_OFFSET 0x2d #define QUERY_DEV_CAP_RSS_OFFSET 0x2e #define QUERY_DEV_CAP_MAX_RDMA_OFFSET 0x2f #define QUERY_DEV_CAP_RSZ_SRQ_OFFSET 0x33 #define QUERY_DEV_CAP_PORT_BEACON_OFFSET 0x34 #define QUERY_DEV_CAP_ACK_DELAY_OFFSET 0x35 #define QUERY_DEV_CAP_MTU_WIDTH_OFFSET 0x36 #define QUERY_DEV_CAP_VL_PORT_OFFSET 0x37 #define QUERY_DEV_CAP_MAX_MSG_SZ_OFFSET 0x38 #define QUERY_DEV_CAP_MAX_GID_OFFSET 0x3b #define QUERY_DEV_CAP_RATE_SUPPORT_OFFSET 0x3c #define QUERY_DEV_CAP_CQ_TS_SUPPORT_OFFSET 0x3e #define QUERY_DEV_CAP_MAX_PKEY_OFFSET 0x3f #define QUERY_DEV_CAP_EXT_FLAGS_OFFSET 0x40 #define QUERY_DEV_CAP_WOL_OFFSET 0x43 #define QUERY_DEV_CAP_FLAGS_OFFSET 0x44 #define QUERY_DEV_CAP_RSVD_UAR_OFFSET 0x48 #define QUERY_DEV_CAP_UAR_SZ_OFFSET 0x49 #define QUERY_DEV_CAP_PAGE_SZ_OFFSET 0x4b #define QUERY_DEV_CAP_BF_OFFSET 0x4c #define QUERY_DEV_CAP_LOG_BF_REG_SZ_OFFSET 0x4d #define QUERY_DEV_CAP_LOG_MAX_BF_REGS_PER_PAGE_OFFSET 0x4e #define QUERY_DEV_CAP_LOG_MAX_BF_PAGES_OFFSET 0x4f #define QUERY_DEV_CAP_MAX_SG_SQ_OFFSET 0x51 #define QUERY_DEV_CAP_MAX_DESC_SZ_SQ_OFFSET 0x52 #define QUERY_DEV_CAP_MAX_SG_RQ_OFFSET 0x55 #define QUERY_DEV_CAP_MAX_DESC_SZ_RQ_OFFSET 0x56 #define QUERY_DEV_CAP_SVLAN_BY_QP_OFFSET 0x5D #define QUERY_DEV_CAP_MAX_QP_MCG_OFFSET 0x61 #define QUERY_DEV_CAP_RSVD_MCG_OFFSET 0x62 #define QUERY_DEV_CAP_MAX_MCG_OFFSET 0x63 #define QUERY_DEV_CAP_RSVD_PD_OFFSET 0x64 #define QUERY_DEV_CAP_MAX_PD_OFFSET 0x65 #define QUERY_DEV_CAP_RSVD_XRC_OFFSET 0x66 #define QUERY_DEV_CAP_MAX_XRC_OFFSET 0x67 #define QUERY_DEV_CAP_MAX_COUNTERS_OFFSET 0x68 #define QUERY_DEV_CAP_PORT_FLOWSTATS_COUNTERS_OFFSET 0x70 #define QUERY_DEV_CAP_EXT_2_FLAGS_OFFSET 0x70 #define QUERY_DEV_CAP_FLOW_STEERING_IPOIB_OFFSET 0x74 #define QUERY_DEV_CAP_FLOW_STEERING_RANGE_EN_OFFSET 0x76 #define QUERY_DEV_CAP_FLOW_STEERING_MAX_QP_OFFSET 0x77 #define QUERY_DEV_CAP_SL2VL_EVENT_OFFSET 0x78 #define QUERY_DEV_CAP_CQ_EQ_CACHE_LINE_STRIDE 0x7a #define QUERY_DEV_CAP_ECN_QCN_VER_OFFSET 0x7b #define QUERY_DEV_CAP_RDMARC_ENTRY_SZ_OFFSET 0x80 #define QUERY_DEV_CAP_QPC_ENTRY_SZ_OFFSET 0x82 #define QUERY_DEV_CAP_AUX_ENTRY_SZ_OFFSET 0x84 #define QUERY_DEV_CAP_ALTC_ENTRY_SZ_OFFSET 0x86 #define QUERY_DEV_CAP_EQC_ENTRY_SZ_OFFSET 0x88 #define QUERY_DEV_CAP_CQC_ENTRY_SZ_OFFSET 0x8a #define QUERY_DEV_CAP_SRQ_ENTRY_SZ_OFFSET 0x8c #define QUERY_DEV_CAP_C_MPT_ENTRY_SZ_OFFSET 0x8e #define QUERY_DEV_CAP_MTT_ENTRY_SZ_OFFSET 0x90 #define QUERY_DEV_CAP_D_MPT_ENTRY_SZ_OFFSET 0x92 #define QUERY_DEV_CAP_BMME_FLAGS_OFFSET 0x94 #define QUERY_DEV_CAP_CONFIG_DEV_OFFSET 0x94 #define QUERY_DEV_CAP_PHV_EN_OFFSET 0x96 #define QUERY_DEV_CAP_RSVD_LKEY_OFFSET 0x98 #define QUERY_DEV_CAP_MAX_ICM_SZ_OFFSET 0xa0 #define QUERY_DEV_CAP_ETH_BACKPL_OFFSET 0x9c #define QUERY_DEV_CAP_DIAG_RPRT_PER_PORT 0x9c #define QUERY_DEV_CAP_FW_REASSIGN_MAC 0x9d #define QUERY_DEV_CAP_VXLAN 0x9e #define QUERY_DEV_CAP_MAD_DEMUX_OFFSET 0xb0 #define QUERY_DEV_CAP_DMFS_HIGH_RATE_QPN_BASE_OFFSET 0xa8 #define QUERY_DEV_CAP_DMFS_HIGH_RATE_QPN_RANGE_OFFSET 0xac #define QUERY_DEV_CAP_QP_RATE_LIMIT_NUM_OFFSET 0xcc #define QUERY_DEV_CAP_QP_RATE_LIMIT_MAX_OFFSET 0xd0 #define QUERY_DEV_CAP_QP_RATE_LIMIT_MIN_OFFSET 0xd2 dev_cap->flags2 = 0; mailbox = mlx4_alloc_cmd_mailbox(dev); if (IS_ERR(mailbox)) return PTR_ERR(mailbox); outbox = mailbox->buf; err = mlx4_cmd_box(dev, 0, mailbox->dma, 0, 0, MLX4_CMD_QUERY_DEV_CAP, MLX4_CMD_TIME_CLASS_A, MLX4_CMD_NATIVE); if (err) goto out; if (mlx4_is_mfunc(dev)) disable_unsupported_roce_caps(outbox); MLX4_GET(field, outbox, QUERY_DEV_CAP_RSVD_QP_OFFSET); dev_cap->reserved_qps = 1 << (field & 0xf); MLX4_GET(field, outbox, QUERY_DEV_CAP_MAX_QP_OFFSET); dev_cap->max_qps = 1 << (field & 0x1f); MLX4_GET(field, outbox, QUERY_DEV_CAP_RSVD_SRQ_OFFSET); dev_cap->reserved_srqs = 1 << (field >> 4); MLX4_GET(field, outbox, QUERY_DEV_CAP_MAX_SRQ_OFFSET); dev_cap->max_srqs = 1 << (field & 0x1f); MLX4_GET(field, outbox, QUERY_DEV_CAP_MAX_CQ_SZ_OFFSET); dev_cap->max_cq_sz = 1 << field; MLX4_GET(field, outbox, QUERY_DEV_CAP_RSVD_CQ_OFFSET); dev_cap->reserved_cqs = 1 << (field & 0xf); MLX4_GET(field, outbox, QUERY_DEV_CAP_MAX_CQ_OFFSET); dev_cap->max_cqs = 1 << (field & 0x1f); MLX4_GET(field, outbox, QUERY_DEV_CAP_MAX_MPT_OFFSET); dev_cap->max_mpts = 1 << (field & 0x3f); MLX4_GET(field, outbox, QUERY_DEV_CAP_RSVD_EQ_OFFSET); dev_cap->reserved_eqs = 1 << (field & 0xf); MLX4_GET(field, outbox, QUERY_DEV_CAP_MAX_EQ_OFFSET); dev_cap->max_eqs = 1 << (field & 0xf); MLX4_GET(field, outbox, QUERY_DEV_CAP_RSVD_MTT_OFFSET); dev_cap->reserved_mtts = 1 << (field >> 4); MLX4_GET(field, outbox, QUERY_DEV_CAP_RSVD_MRW_OFFSET); dev_cap->reserved_mrws = 1 << (field & 0xf); MLX4_GET(size, outbox, QUERY_DEV_CAP_NUM_SYS_EQ_OFFSET); dev_cap->num_sys_eqs = size & 0xfff; MLX4_GET(field, outbox, QUERY_DEV_CAP_MAX_REQ_QP_OFFSET); dev_cap->max_requester_per_qp = 1 << (field & 0x3f); MLX4_GET(field, outbox, QUERY_DEV_CAP_MAX_RES_QP_OFFSET); dev_cap->max_responder_per_qp = 1 << (field & 0x3f); MLX4_GET(field, outbox, QUERY_DEV_CAP_MAX_GSO_OFFSET); field &= 0x1f; if (!field) dev_cap->max_gso_sz = 0; else dev_cap->max_gso_sz = 1 << field; MLX4_GET(field, outbox, QUERY_DEV_CAP_RSS_OFFSET); if (field & 0x20) dev_cap->flags2 |= MLX4_DEV_CAP_FLAG2_RSS_XOR; if (field & 0x10) dev_cap->flags2 |= MLX4_DEV_CAP_FLAG2_RSS_TOP; field &= 0xf; if (field) { dev_cap->flags2 |= MLX4_DEV_CAP_FLAG2_RSS; dev_cap->max_rss_tbl_sz = 1 << field; } else dev_cap->max_rss_tbl_sz = 0; MLX4_GET(field, outbox, QUERY_DEV_CAP_MAX_RDMA_OFFSET); dev_cap->max_rdma_global = 1 << (field & 0x3f); MLX4_GET(field, outbox, QUERY_DEV_CAP_ACK_DELAY_OFFSET); dev_cap->local_ca_ack_delay = field & 0x1f; MLX4_GET(field, outbox, QUERY_DEV_CAP_VL_PORT_OFFSET); dev_cap->num_ports = field & 0xf; MLX4_GET(field, outbox, QUERY_DEV_CAP_MAX_MSG_SZ_OFFSET); dev_cap->max_msg_sz = 1 << (field & 0x1f); MLX4_GET(field, outbox, QUERY_DEV_CAP_PORT_FLOWSTATS_COUNTERS_OFFSET); if (field & 0x10) dev_cap->flags2 |= MLX4_DEV_CAP_FLAG2_FLOWSTATS_EN; MLX4_GET(field, outbox, QUERY_DEV_CAP_FLOW_STEERING_RANGE_EN_OFFSET); if (field & 0x80) dev_cap->flags2 |= MLX4_DEV_CAP_FLAG2_FS_EN; dev_cap->fs_log_max_ucast_qp_range_size = field & 0x1f; if (field & 0x20) dev_cap->flags2 |= MLX4_DEV_CAP_FLAG2_DMFS_UC_MC_SNIFFER; MLX4_GET(field, outbox, QUERY_DEV_CAP_PORT_BEACON_OFFSET); if (field & 0x80) dev_cap->flags2 |= MLX4_DEV_CAP_FLAG2_PORT_BEACON; MLX4_GET(field, outbox, QUERY_DEV_CAP_FLOW_STEERING_IPOIB_OFFSET); if (field & 0x80) dev_cap->flags2 |= MLX4_DEV_CAP_FLAG2_DMFS_IPOIB; MLX4_GET(field, outbox, QUERY_DEV_CAP_FLOW_STEERING_MAX_QP_OFFSET); dev_cap->fs_max_num_qp_per_entry = field; MLX4_GET(field, outbox, QUERY_DEV_CAP_SL2VL_EVENT_OFFSET); if (field & (1 << 5)) dev_cap->flags2 |= MLX4_DEV_CAP_FLAG2_SL_TO_VL_CHANGE_EVENT; MLX4_GET(field, outbox, QUERY_DEV_CAP_ECN_QCN_VER_OFFSET); if (field & 0x1) dev_cap->flags2 |= MLX4_DEV_CAP_FLAG2_QCN; MLX4_GET(stat_rate, outbox, QUERY_DEV_CAP_RATE_SUPPORT_OFFSET); dev_cap->stat_rate_support = stat_rate; MLX4_GET(field, outbox, QUERY_DEV_CAP_CQ_TS_SUPPORT_OFFSET); if (field & 0x80) dev_cap->flags2 |= MLX4_DEV_CAP_FLAG2_TS; MLX4_GET(ext_flags, outbox, QUERY_DEV_CAP_EXT_FLAGS_OFFSET); MLX4_GET(flags, outbox, QUERY_DEV_CAP_FLAGS_OFFSET); dev_cap->flags = flags | (u64)ext_flags << 32; MLX4_GET(field, outbox, QUERY_DEV_CAP_WOL_OFFSET); dev_cap->wol_port[1] = !!(field & 0x20); dev_cap->wol_port[2] = !!(field & 0x40); MLX4_GET(field, outbox, QUERY_DEV_CAP_RSVD_UAR_OFFSET); dev_cap->reserved_uars = field >> 4; MLX4_GET(field, outbox, QUERY_DEV_CAP_UAR_SZ_OFFSET); dev_cap->uar_size = 1 << ((field & 0x3f) + 20); MLX4_GET(field, outbox, QUERY_DEV_CAP_PAGE_SZ_OFFSET); dev_cap->min_page_sz = 1 << field; MLX4_GET(field, outbox, QUERY_DEV_CAP_BF_OFFSET); if (field & 0x80) { MLX4_GET(field, outbox, QUERY_DEV_CAP_LOG_BF_REG_SZ_OFFSET); dev_cap->bf_reg_size = 1 << (field & 0x1f); MLX4_GET(field, outbox, QUERY_DEV_CAP_LOG_MAX_BF_REGS_PER_PAGE_OFFSET); if ((1 << (field & 0x3f)) > (PAGE_SIZE / dev_cap->bf_reg_size)) field = 3; dev_cap->bf_regs_per_page = 1 << (field & 0x3f); } else { dev_cap->bf_reg_size = 0; } MLX4_GET(field, outbox, QUERY_DEV_CAP_MAX_SG_SQ_OFFSET); dev_cap->max_sq_sg = field; MLX4_GET(size, outbox, QUERY_DEV_CAP_MAX_DESC_SZ_SQ_OFFSET); dev_cap->max_sq_desc_sz = size; MLX4_GET(field, outbox, QUERY_DEV_CAP_SVLAN_BY_QP_OFFSET); if (field & 0x1) dev_cap->flags2 |= MLX4_DEV_CAP_FLAG2_SVLAN_BY_QP; MLX4_GET(field, outbox, QUERY_DEV_CAP_MAX_QP_MCG_OFFSET); dev_cap->max_qp_per_mcg = 1 << field; MLX4_GET(field, outbox, QUERY_DEV_CAP_RSVD_MCG_OFFSET); dev_cap->reserved_mgms = field & 0xf; MLX4_GET(field, outbox, QUERY_DEV_CAP_MAX_MCG_OFFSET); dev_cap->max_mcgs = 1 << field; MLX4_GET(field, outbox, QUERY_DEV_CAP_RSVD_PD_OFFSET); dev_cap->reserved_pds = field >> 4; MLX4_GET(field, outbox, QUERY_DEV_CAP_MAX_PD_OFFSET); dev_cap->max_pds = 1 << (field & 0x3f); MLX4_GET(field, outbox, QUERY_DEV_CAP_RSVD_XRC_OFFSET); dev_cap->reserved_xrcds = field >> 4; MLX4_GET(field, outbox, QUERY_DEV_CAP_MAX_XRC_OFFSET); dev_cap->max_xrcds = 1 << (field & 0x1f); MLX4_GET(size, outbox, QUERY_DEV_CAP_RDMARC_ENTRY_SZ_OFFSET); dev_cap->rdmarc_entry_sz = size; MLX4_GET(size, outbox, QUERY_DEV_CAP_QPC_ENTRY_SZ_OFFSET); dev_cap->qpc_entry_sz = size; MLX4_GET(size, outbox, QUERY_DEV_CAP_AUX_ENTRY_SZ_OFFSET); dev_cap->aux_entry_sz = size; MLX4_GET(size, outbox, QUERY_DEV_CAP_ALTC_ENTRY_SZ_OFFSET); dev_cap->altc_entry_sz = size; MLX4_GET(size, outbox, QUERY_DEV_CAP_EQC_ENTRY_SZ_OFFSET); dev_cap->eqc_entry_sz = size; MLX4_GET(size, outbox, QUERY_DEV_CAP_CQC_ENTRY_SZ_OFFSET); dev_cap->cqc_entry_sz = size; MLX4_GET(size, outbox, QUERY_DEV_CAP_SRQ_ENTRY_SZ_OFFSET); dev_cap->srq_entry_sz = size; MLX4_GET(size, outbox, QUERY_DEV_CAP_C_MPT_ENTRY_SZ_OFFSET); dev_cap->cmpt_entry_sz = size; MLX4_GET(size, outbox, QUERY_DEV_CAP_MTT_ENTRY_SZ_OFFSET); dev_cap->mtt_entry_sz = size; MLX4_GET(size, outbox, QUERY_DEV_CAP_D_MPT_ENTRY_SZ_OFFSET); dev_cap->dmpt_entry_sz = size; MLX4_GET(field, outbox, QUERY_DEV_CAP_MAX_SRQ_SZ_OFFSET); dev_cap->max_srq_sz = 1 << field; MLX4_GET(field, outbox, QUERY_DEV_CAP_MAX_QP_SZ_OFFSET); dev_cap->max_qp_sz = 1 << field; MLX4_GET(field, outbox, QUERY_DEV_CAP_RSZ_SRQ_OFFSET); dev_cap->resize_srq = field & 1; MLX4_GET(field, outbox, QUERY_DEV_CAP_MAX_SG_RQ_OFFSET); dev_cap->max_rq_sg = field; MLX4_GET(size, outbox, QUERY_DEV_CAP_MAX_DESC_SZ_RQ_OFFSET); dev_cap->max_rq_desc_sz = size; MLX4_GET(field, outbox, QUERY_DEV_CAP_CQ_EQ_CACHE_LINE_STRIDE); if (field & (1 << 4)) dev_cap->flags2 |= MLX4_DEV_CAP_FLAG2_QOS_VPP; if (field & (1 << 5)) dev_cap->flags2 |= MLX4_DEV_CAP_FLAG2_ETH_PROT_CTRL; if (field & (1 << 6)) dev_cap->flags2 |= MLX4_DEV_CAP_FLAG2_CQE_STRIDE; if (field & (1 << 7)) dev_cap->flags2 |= MLX4_DEV_CAP_FLAG2_EQE_STRIDE; MLX4_GET(dev_cap->bmme_flags, outbox, QUERY_DEV_CAP_BMME_FLAGS_OFFSET); if (dev_cap->bmme_flags & MLX4_FLAG_ROCE_V1_V2) dev_cap->flags2 |= MLX4_DEV_CAP_FLAG2_ROCE_V1_V2; if (dev_cap->bmme_flags & MLX4_FLAG_PORT_REMAP) dev_cap->flags2 |= MLX4_DEV_CAP_FLAG2_PORT_REMAP; MLX4_GET(field, outbox, QUERY_DEV_CAP_CONFIG_DEV_OFFSET); if (field & 0x20) dev_cap->flags2 |= MLX4_DEV_CAP_FLAG2_CONFIG_DEV; if (field & (1 << 2)) dev_cap->flags2 |= MLX4_DEV_CAP_FLAG2_IGNORE_FCS; MLX4_GET(field, outbox, QUERY_DEV_CAP_PHV_EN_OFFSET); if (field & 0x80) dev_cap->flags2 |= MLX4_DEV_CAP_FLAG2_PHV_EN; if (field & 0x40) dev_cap->flags2 |= MLX4_DEV_CAP_FLAG2_SKIP_OUTER_VLAN; MLX4_GET(dev_cap->reserved_lkey, outbox, QUERY_DEV_CAP_RSVD_LKEY_OFFSET); MLX4_GET(field32, outbox, QUERY_DEV_CAP_ETH_BACKPL_OFFSET); if (field32 & (1 << 0)) dev_cap->flags2 |= MLX4_DEV_CAP_FLAG2_ETH_BACKPL_AN_REP; if (field32 & (1 << 7)) dev_cap->flags2 |= MLX4_DEV_CAP_FLAG2_RECOVERABLE_ERROR_EVENT; MLX4_GET(field32, outbox, QUERY_DEV_CAP_DIAG_RPRT_PER_PORT); if (field32 & (1 << 17)) dev_cap->flags2 |= MLX4_DEV_CAP_FLAG2_DIAG_PER_PORT; MLX4_GET(field, outbox, QUERY_DEV_CAP_FW_REASSIGN_MAC); if (field & 1<<6) dev_cap->flags2 |= MLX4_DEV_CAP_FLAG2_REASSIGN_MAC_EN; MLX4_GET(field, outbox, QUERY_DEV_CAP_VXLAN); if (field & 1<<3) dev_cap->flags2 |= MLX4_DEV_CAP_FLAG2_VXLAN_OFFLOADS; if (field & (1 << 5)) dev_cap->flags2 |= MLX4_DEV_CAP_FLAG2_ETS_CFG; MLX4_GET(dev_cap->max_icm_sz, outbox, QUERY_DEV_CAP_MAX_ICM_SZ_OFFSET); if (dev_cap->flags & MLX4_DEV_CAP_FLAG_COUNTERS) MLX4_GET(dev_cap->max_counters, outbox, QUERY_DEV_CAP_MAX_COUNTERS_OFFSET); MLX4_GET(field32, outbox, QUERY_DEV_CAP_MAD_DEMUX_OFFSET); if (field32 & (1 << 0)) dev_cap->flags2 |= MLX4_DEV_CAP_FLAG2_MAD_DEMUX; MLX4_GET(dev_cap->dmfs_high_rate_qpn_base, outbox, QUERY_DEV_CAP_DMFS_HIGH_RATE_QPN_BASE_OFFSET); dev_cap->dmfs_high_rate_qpn_base &= MGM_QPN_MASK; MLX4_GET(dev_cap->dmfs_high_rate_qpn_range, outbox, QUERY_DEV_CAP_DMFS_HIGH_RATE_QPN_RANGE_OFFSET); dev_cap->dmfs_high_rate_qpn_range &= MGM_QPN_MASK; MLX4_GET(size, outbox, QUERY_DEV_CAP_QP_RATE_LIMIT_NUM_OFFSET); dev_cap->rl_caps.num_rates = size; if (dev_cap->rl_caps.num_rates) { dev_cap->flags2 |= MLX4_DEV_CAP_FLAG2_QP_RATE_LIMIT; MLX4_GET(size, outbox, QUERY_DEV_CAP_QP_RATE_LIMIT_MAX_OFFSET); dev_cap->rl_caps.max_val = size & 0xfff; dev_cap->rl_caps.max_unit = size >> 14; MLX4_GET(size, outbox, QUERY_DEV_CAP_QP_RATE_LIMIT_MIN_OFFSET); dev_cap->rl_caps.min_val = size & 0xfff; dev_cap->rl_caps.min_unit = size >> 14; } MLX4_GET(field32, outbox, QUERY_DEV_CAP_EXT_2_FLAGS_OFFSET); if (field32 & (1 << 16)) dev_cap->flags2 |= MLX4_DEV_CAP_FLAG2_UPDATE_QP; if (field32 & (1 << 18)) dev_cap->flags2 |= MLX4_DEV_CAP_FLAG2_UPDATE_QP_SRC_CHECK_LB; if (field32 & (1 << 19)) dev_cap->flags2 |= MLX4_DEV_CAP_FLAG2_LB_SRC_CHK; if (field32 & (1 << 26)) dev_cap->flags2 |= MLX4_DEV_CAP_FLAG2_VLAN_CONTROL; if (field32 & (1 << 20)) dev_cap->flags2 |= MLX4_DEV_CAP_FLAG2_FSM; if (field32 & (1 << 21)) dev_cap->flags2 |= MLX4_DEV_CAP_FLAG2_80_VFS; for (i = 1; i <= dev_cap->num_ports; i++) { err = mlx4_QUERY_PORT(dev, i, dev_cap->port_cap + i); if (err) goto out; } /* * Each UAR has 4 EQ doorbells; so if a UAR is reserved, then * we can't use any EQs whose doorbell falls on that page, * even if the EQ itself isn't reserved. */ if (dev_cap->num_sys_eqs == 0) dev_cap->reserved_eqs = max(dev_cap->reserved_uars * 4, dev_cap->reserved_eqs); else dev_cap->flags2 |= MLX4_DEV_CAP_FLAG2_SYS_EQS; out: mlx4_free_cmd_mailbox(dev, mailbox); return err; } void mlx4_dev_cap_dump(struct mlx4_dev *dev, struct mlx4_dev_cap *dev_cap) { if (dev_cap->bf_reg_size > 0) mlx4_dbg(dev, "BlueFlame available (reg size %d, regs/page %d)\n", dev_cap->bf_reg_size, dev_cap->bf_regs_per_page); else mlx4_dbg(dev, "BlueFlame not available\n"); mlx4_dbg(dev, "Base MM extensions: flags %08x, rsvd L_Key %08x\n", dev_cap->bmme_flags, dev_cap->reserved_lkey); mlx4_dbg(dev, "Max ICM size %lld MB\n", (unsigned long long) dev_cap->max_icm_sz >> 20); mlx4_dbg(dev, "Max QPs: %d, reserved QPs: %d, entry size: %d\n", dev_cap->max_qps, dev_cap->reserved_qps, dev_cap->qpc_entry_sz); mlx4_dbg(dev, "Max SRQs: %d, reserved SRQs: %d, entry size: %d\n", dev_cap->max_srqs, dev_cap->reserved_srqs, dev_cap->srq_entry_sz); mlx4_dbg(dev, "Max CQs: %d, reserved CQs: %d, entry size: %d\n", dev_cap->max_cqs, dev_cap->reserved_cqs, dev_cap->cqc_entry_sz); mlx4_dbg(dev, "Num sys EQs: %d, max EQs: %d, reserved EQs: %d, entry size: %d\n", dev_cap->num_sys_eqs, dev_cap->max_eqs, dev_cap->reserved_eqs, dev_cap->eqc_entry_sz); mlx4_dbg(dev, "reserved MPTs: %d, reserved MTTs: %d\n", dev_cap->reserved_mrws, dev_cap->reserved_mtts); mlx4_dbg(dev, "Max PDs: %d, reserved PDs: %d, reserved UARs: %d\n", dev_cap->max_pds, dev_cap->reserved_pds, dev_cap->reserved_uars); mlx4_dbg(dev, "Max QP/MCG: %d, reserved MGMs: %d\n", dev_cap->max_pds, dev_cap->reserved_mgms); mlx4_dbg(dev, "Max CQEs: %d, max WQEs: %d, max SRQ WQEs: %d\n", dev_cap->max_cq_sz, dev_cap->max_qp_sz, dev_cap->max_srq_sz); mlx4_dbg(dev, "Local CA ACK delay: %d, max MTU: %d, port width cap: %d\n", dev_cap->local_ca_ack_delay, 128 << dev_cap->port_cap[1].ib_mtu, dev_cap->port_cap[1].max_port_width); mlx4_dbg(dev, "Max SQ desc size: %d, max SQ S/G: %d\n", dev_cap->max_sq_desc_sz, dev_cap->max_sq_sg); mlx4_dbg(dev, "Max RQ desc size: %d, max RQ S/G: %d\n", dev_cap->max_rq_desc_sz, dev_cap->max_rq_sg); mlx4_dbg(dev, "Max GSO size: %d\n", dev_cap->max_gso_sz); mlx4_dbg(dev, "Max counters: %d\n", dev_cap->max_counters); mlx4_dbg(dev, "Max RSS Table size: %d\n", dev_cap->max_rss_tbl_sz); mlx4_dbg(dev, "DMFS high rate steer QPn base: %d\n", dev_cap->dmfs_high_rate_qpn_base); mlx4_dbg(dev, "DMFS high rate steer QPn range: %d\n", dev_cap->dmfs_high_rate_qpn_range); if (dev_cap->flags2 & MLX4_DEV_CAP_FLAG2_QP_RATE_LIMIT) { struct mlx4_rate_limit_caps *rl_caps = &dev_cap->rl_caps; mlx4_dbg(dev, "QP Rate-Limit: #rates %d, unit/val max %d/%d, min %d/%d\n", rl_caps->num_rates, rl_caps->max_unit, rl_caps->max_val, rl_caps->min_unit, rl_caps->min_val); } dump_dev_cap_flags(dev, dev_cap->flags); dump_dev_cap_flags2(dev, dev_cap->flags2); } int mlx4_QUERY_PORT(struct mlx4_dev *dev, int port, struct mlx4_port_cap *port_cap) { struct mlx4_cmd_mailbox *mailbox; u32 *outbox; u8 field; u32 field32; int err; mailbox = mlx4_alloc_cmd_mailbox(dev); if (IS_ERR(mailbox)) return PTR_ERR(mailbox); outbox = mailbox->buf; if (dev->flags & MLX4_FLAG_OLD_PORT_CMDS) { err = mlx4_cmd_box(dev, 0, mailbox->dma, 0, 0, MLX4_CMD_QUERY_DEV_CAP, MLX4_CMD_TIME_CLASS_A, MLX4_CMD_NATIVE); if (err) goto out; MLX4_GET(field, outbox, QUERY_DEV_CAP_VL_PORT_OFFSET); port_cap->max_vl = field >> 4; MLX4_GET(field, outbox, QUERY_DEV_CAP_MTU_WIDTH_OFFSET); port_cap->ib_mtu = field >> 4; port_cap->max_port_width = field & 0xf; MLX4_GET(field, outbox, QUERY_DEV_CAP_MAX_GID_OFFSET); port_cap->max_gids = 1 << (field & 0xf); MLX4_GET(field, outbox, QUERY_DEV_CAP_MAX_PKEY_OFFSET); port_cap->max_pkeys = 1 << (field & 0xf); } else { #define QUERY_PORT_SUPPORTED_TYPE_OFFSET 0x00 #define QUERY_PORT_MTU_OFFSET 0x01 #define QUERY_PORT_ETH_MTU_OFFSET 0x02 #define QUERY_PORT_WIDTH_OFFSET 0x06 #define QUERY_PORT_MAX_GID_PKEY_OFFSET 0x07 #define QUERY_PORT_MAX_MACVLAN_OFFSET 0x0a #define QUERY_PORT_MAX_VL_OFFSET 0x0b #define QUERY_PORT_MAC_OFFSET 0x10 #define QUERY_PORT_TRANS_VENDOR_OFFSET 0x18 #define QUERY_PORT_WAVELENGTH_OFFSET 0x1c #define QUERY_PORT_TRANS_CODE_OFFSET 0x20 err = mlx4_cmd_box(dev, 0, mailbox->dma, port, 0, MLX4_CMD_QUERY_PORT, MLX4_CMD_TIME_CLASS_B, MLX4_CMD_NATIVE); if (err) goto out; MLX4_GET(field, outbox, QUERY_PORT_SUPPORTED_TYPE_OFFSET); port_cap->link_state = (field & 0x80) >> 7; port_cap->supported_port_types = field & 3; port_cap->suggested_type = (field >> 3) & 1; port_cap->default_sense = (field >> 4) & 1; port_cap->dmfs_optimized_state = (field >> 5) & 1; MLX4_GET(field, outbox, QUERY_PORT_MTU_OFFSET); port_cap->ib_mtu = field & 0xf; MLX4_GET(field, outbox, QUERY_PORT_WIDTH_OFFSET); port_cap->max_port_width = field & 0xf; MLX4_GET(field, outbox, QUERY_PORT_MAX_GID_PKEY_OFFSET); port_cap->max_gids = 1 << (field >> 4); port_cap->max_pkeys = 1 << (field & 0xf); MLX4_GET(field, outbox, QUERY_PORT_MAX_VL_OFFSET); port_cap->max_vl = field & 0xf; port_cap->max_tc_eth = field >> 4; MLX4_GET(field, outbox, QUERY_PORT_MAX_MACVLAN_OFFSET); port_cap->log_max_macs = field & 0xf; port_cap->log_max_vlans = field >> 4; MLX4_GET(port_cap->eth_mtu, outbox, QUERY_PORT_ETH_MTU_OFFSET); MLX4_GET(port_cap->def_mac, outbox, QUERY_PORT_MAC_OFFSET); MLX4_GET(field32, outbox, QUERY_PORT_TRANS_VENDOR_OFFSET); port_cap->trans_type = field32 >> 24; port_cap->vendor_oui = field32 & 0xffffff; MLX4_GET(port_cap->wavelength, outbox, QUERY_PORT_WAVELENGTH_OFFSET); MLX4_GET(port_cap->trans_code, outbox, QUERY_PORT_TRANS_CODE_OFFSET); } out: mlx4_free_cmd_mailbox(dev, mailbox); return err; } #define DEV_CAP_EXT_2_FLAG_PFC_COUNTERS (1 << 28) #define DEV_CAP_EXT_2_FLAG_VLAN_CONTROL (1 << 26) #define DEV_CAP_EXT_2_FLAG_80_VFS (1 << 21) #define DEV_CAP_EXT_2_FLAG_FSM (1 << 20) int mlx4_QUERY_DEV_CAP_wrapper(struct mlx4_dev *dev, int slave, struct mlx4_vhcr *vhcr, struct mlx4_cmd_mailbox *inbox, struct mlx4_cmd_mailbox *outbox, struct mlx4_cmd_info *cmd) { u64 flags; int err = 0; u8 field; u16 field16; u32 bmme_flags, field32; int real_port; int slave_port; int first_port; struct mlx4_active_ports actv_ports; err = mlx4_cmd_box(dev, 0, outbox->dma, 0, 0, MLX4_CMD_QUERY_DEV_CAP, MLX4_CMD_TIME_CLASS_A, MLX4_CMD_NATIVE); if (err) return err; disable_unsupported_roce_caps(outbox->buf); /* add port mng change event capability and disable mw type 1 * unconditionally to slaves */ MLX4_GET(flags, outbox->buf, QUERY_DEV_CAP_EXT_FLAGS_OFFSET); flags |= MLX4_DEV_CAP_FLAG_PORT_MNG_CHG_EV; flags &= ~MLX4_DEV_CAP_FLAG_MEM_WINDOW; actv_ports = mlx4_get_active_ports(dev, slave); first_port = find_first_bit(actv_ports.ports, dev->caps.num_ports); for (slave_port = 0, real_port = first_port; real_port < first_port + bitmap_weight(actv_ports.ports, dev->caps.num_ports); ++real_port, ++slave_port) { if (flags & (MLX4_DEV_CAP_FLAG_WOL_PORT1 << real_port)) flags |= MLX4_DEV_CAP_FLAG_WOL_PORT1 << slave_port; else flags &= ~(MLX4_DEV_CAP_FLAG_WOL_PORT1 << slave_port); } for (; slave_port < dev->caps.num_ports; ++slave_port) flags &= ~(MLX4_DEV_CAP_FLAG_WOL_PORT1 << slave_port); /* Not exposing RSS IP fragments to guests */ flags &= ~MLX4_DEV_CAP_FLAG_RSS_IP_FRAG; MLX4_PUT(outbox->buf, flags, QUERY_DEV_CAP_EXT_FLAGS_OFFSET); MLX4_GET(field, outbox->buf, QUERY_DEV_CAP_VL_PORT_OFFSET); field &= ~0x0F; field |= bitmap_weight(actv_ports.ports, dev->caps.num_ports) & 0x0F; MLX4_PUT(outbox->buf, field, QUERY_DEV_CAP_VL_PORT_OFFSET); /* For guests, disable timestamp */ MLX4_GET(field, outbox->buf, QUERY_DEV_CAP_CQ_TS_SUPPORT_OFFSET); field &= 0x7f; MLX4_PUT(outbox->buf, field, QUERY_DEV_CAP_CQ_TS_SUPPORT_OFFSET); /* For guests, disable vxlan tunneling and QoS support */ MLX4_GET(field, outbox->buf, QUERY_DEV_CAP_VXLAN); field &= 0xd7; MLX4_PUT(outbox->buf, field, QUERY_DEV_CAP_VXLAN); /* For guests, disable port BEACON */ MLX4_GET(field, outbox->buf, QUERY_DEV_CAP_PORT_BEACON_OFFSET); field &= 0x7f; MLX4_PUT(outbox->buf, field, QUERY_DEV_CAP_PORT_BEACON_OFFSET); /* For guests, report Blueflame disabled */ MLX4_GET(field, outbox->buf, QUERY_DEV_CAP_BF_OFFSET); field &= 0x7f; MLX4_PUT(outbox->buf, field, QUERY_DEV_CAP_BF_OFFSET); /* For guests, disable mw type 2 and port remap*/ MLX4_GET(bmme_flags, outbox->buf, QUERY_DEV_CAP_BMME_FLAGS_OFFSET); bmme_flags &= ~MLX4_BMME_FLAG_TYPE_2_WIN; bmme_flags &= ~MLX4_FLAG_PORT_REMAP; MLX4_PUT(outbox->buf, bmme_flags, QUERY_DEV_CAP_BMME_FLAGS_OFFSET); /* turn off device-managed steering capability if not enabled */ if (dev->caps.steering_mode != MLX4_STEERING_MODE_DEVICE_MANAGED) { MLX4_GET(field, outbox->buf, QUERY_DEV_CAP_FLOW_STEERING_RANGE_EN_OFFSET); field &= 0x7f; MLX4_PUT(outbox->buf, field, QUERY_DEV_CAP_FLOW_STEERING_RANGE_EN_OFFSET); } /* turn off ipoib managed steering for guests */ MLX4_GET(field, outbox->buf, QUERY_DEV_CAP_FLOW_STEERING_IPOIB_OFFSET); field &= ~0x80; MLX4_PUT(outbox->buf, field, QUERY_DEV_CAP_FLOW_STEERING_IPOIB_OFFSET); /* turn off host side virt features (VST, FSM, etc) for guests */ MLX4_GET(field32, outbox->buf, QUERY_DEV_CAP_EXT_2_FLAGS_OFFSET); field32 &= ~(DEV_CAP_EXT_2_FLAG_VLAN_CONTROL | DEV_CAP_EXT_2_FLAG_80_VFS | DEV_CAP_EXT_2_FLAG_FSM | DEV_CAP_EXT_2_FLAG_PFC_COUNTERS); MLX4_PUT(outbox->buf, field32, QUERY_DEV_CAP_EXT_2_FLAGS_OFFSET); /* turn off QCN for guests */ MLX4_GET(field, outbox->buf, QUERY_DEV_CAP_ECN_QCN_VER_OFFSET); field &= 0xfe; MLX4_PUT(outbox->buf, field, QUERY_DEV_CAP_ECN_QCN_VER_OFFSET); /* turn off QP max-rate limiting for guests */ field16 = 0; MLX4_PUT(outbox->buf, field16, QUERY_DEV_CAP_QP_RATE_LIMIT_NUM_OFFSET); /* turn off QoS per VF support for guests */ MLX4_GET(field, outbox->buf, QUERY_DEV_CAP_CQ_EQ_CACHE_LINE_STRIDE); field &= 0xef; MLX4_PUT(outbox->buf, field, QUERY_DEV_CAP_CQ_EQ_CACHE_LINE_STRIDE); /* turn off ignore FCS feature for guests */ MLX4_GET(field, outbox->buf, QUERY_DEV_CAP_CONFIG_DEV_OFFSET); field &= 0xfb; MLX4_PUT(outbox->buf, field, QUERY_DEV_CAP_CONFIG_DEV_OFFSET); return 0; } static void disable_unsupported_roce_caps(void *buf) { u32 flags; MLX4_GET(flags, buf, QUERY_DEV_CAP_EXT_FLAGS_OFFSET); flags &= ~(1UL << 31); MLX4_PUT(buf, flags, QUERY_DEV_CAP_EXT_FLAGS_OFFSET); MLX4_GET(flags, buf, QUERY_DEV_CAP_EXT_2_FLAGS_OFFSET); flags &= ~(1UL << 24); MLX4_PUT(buf, flags, QUERY_DEV_CAP_EXT_2_FLAGS_OFFSET); MLX4_GET(flags, buf, QUERY_DEV_CAP_BMME_FLAGS_OFFSET); flags &= ~(MLX4_FLAG_ROCE_V1_V2); MLX4_PUT(buf, flags, QUERY_DEV_CAP_BMME_FLAGS_OFFSET); } int mlx4_QUERY_PORT_wrapper(struct mlx4_dev *dev, int slave, struct mlx4_vhcr *vhcr, struct mlx4_cmd_mailbox *inbox, struct mlx4_cmd_mailbox *outbox, struct mlx4_cmd_info *cmd) { struct mlx4_priv *priv = mlx4_priv(dev); u64 def_mac; u8 port_type; u16 short_field; int err; int admin_link_state; int port = mlx4_slave_convert_port(dev, slave, vhcr->in_modifier & 0xFF); #define MLX4_VF_PORT_NO_LINK_SENSE_MASK 0xE0 #define MLX4_PORT_LINK_UP_MASK 0x80 #define QUERY_PORT_CUR_MAX_PKEY_OFFSET 0x0c #define QUERY_PORT_CUR_MAX_GID_OFFSET 0x0e if (port < 0) return -EINVAL; /* Protect against untrusted guests: enforce that this is the * QUERY_PORT general query. */ if (vhcr->op_modifier || vhcr->in_modifier & ~0xFF) return -EINVAL; vhcr->in_modifier = port; err = mlx4_cmd_box(dev, 0, outbox->dma, vhcr->in_modifier, 0, MLX4_CMD_QUERY_PORT, MLX4_CMD_TIME_CLASS_B, MLX4_CMD_NATIVE); if (!err && dev->caps.function != slave) { def_mac = priv->mfunc.master.vf_oper[slave].vport[vhcr->in_modifier].state.mac; MLX4_PUT(outbox->buf, def_mac, QUERY_PORT_MAC_OFFSET); /* get port type - currently only eth is enabled */ MLX4_GET(port_type, outbox->buf, QUERY_PORT_SUPPORTED_TYPE_OFFSET); /* No link sensing allowed */ port_type &= MLX4_VF_PORT_NO_LINK_SENSE_MASK; /* set port type to currently operating port type */ port_type |= (dev->caps.port_type[vhcr->in_modifier] & 0x3); admin_link_state = priv->mfunc.master.vf_oper[slave].vport[vhcr->in_modifier].state.link_state; if (IFLA_VF_LINK_STATE_ENABLE == admin_link_state) port_type |= MLX4_PORT_LINK_UP_MASK; else if (IFLA_VF_LINK_STATE_DISABLE == admin_link_state) port_type &= ~MLX4_PORT_LINK_UP_MASK; else if (IFLA_VF_LINK_STATE_AUTO == admin_link_state && mlx4_is_bonded(dev)) { int other_port = (port == 1) ? 2 : 1; struct mlx4_port_cap port_cap; err = mlx4_QUERY_PORT(dev, other_port, &port_cap); if (err) goto out; port_type |= (port_cap.link_state << 7); } MLX4_PUT(outbox->buf, port_type, QUERY_PORT_SUPPORTED_TYPE_OFFSET); if (dev->caps.port_type[vhcr->in_modifier] == MLX4_PORT_TYPE_ETH) short_field = mlx4_get_slave_num_gids(dev, slave, port); else short_field = 1; /* slave max gids */ MLX4_PUT(outbox->buf, short_field, QUERY_PORT_CUR_MAX_GID_OFFSET); short_field = dev->caps.pkey_table_len[vhcr->in_modifier]; MLX4_PUT(outbox->buf, short_field, QUERY_PORT_CUR_MAX_PKEY_OFFSET); } out: return err; } int mlx4_get_slave_pkey_gid_tbl_len(struct mlx4_dev *dev, u8 port, int *gid_tbl_len, int *pkey_tbl_len) { struct mlx4_cmd_mailbox *mailbox; u32 *outbox; u16 field; int err; mailbox = mlx4_alloc_cmd_mailbox(dev); if (IS_ERR(mailbox)) return PTR_ERR(mailbox); err = mlx4_cmd_box(dev, 0, mailbox->dma, port, 0, MLX4_CMD_QUERY_PORT, MLX4_CMD_TIME_CLASS_B, MLX4_CMD_WRAPPED); if (err) goto out; outbox = mailbox->buf; MLX4_GET(field, outbox, QUERY_PORT_CUR_MAX_GID_OFFSET); *gid_tbl_len = field; MLX4_GET(field, outbox, QUERY_PORT_CUR_MAX_PKEY_OFFSET); *pkey_tbl_len = field; out: mlx4_free_cmd_mailbox(dev, mailbox); return err; } EXPORT_SYMBOL(mlx4_get_slave_pkey_gid_tbl_len); int mlx4_map_cmd(struct mlx4_dev *dev, u16 op, struct mlx4_icm *icm, u64 virt) { struct mlx4_cmd_mailbox *mailbox; struct mlx4_icm_iter iter; __be64 *pages; int lg; int nent = 0; int i; int err = 0; int ts = 0, tc = 0; mailbox = mlx4_alloc_cmd_mailbox(dev); if (IS_ERR(mailbox)) return PTR_ERR(mailbox); pages = mailbox->buf; for (mlx4_icm_first(icm, &iter); !mlx4_icm_last(&iter); mlx4_icm_next(&iter)) { /* * We have to pass pages that are aligned to their * size, so find the least significant 1 in the * address or size and use that as our log2 size. */ lg = ffs(mlx4_icm_addr(&iter) | mlx4_icm_size(&iter)) - 1; if (lg < MLX4_ICM_PAGE_SHIFT) { mlx4_warn(dev, "Got FW area not aligned to %d (%llx/%lx)\n", MLX4_ICM_PAGE_SIZE, (unsigned long long) mlx4_icm_addr(&iter), mlx4_icm_size(&iter)); err = -EINVAL; goto out; } for (i = 0; i < mlx4_icm_size(&iter) >> lg; ++i) { if (virt != -1) { pages[nent * 2] = cpu_to_be64(virt); virt += 1 << lg; } pages[nent * 2 + 1] = cpu_to_be64((mlx4_icm_addr(&iter) + (i << lg)) | (lg - MLX4_ICM_PAGE_SHIFT)); ts += 1 << (lg - 10); ++tc; if (++nent == MLX4_MAILBOX_SIZE / 16) { err = mlx4_cmd(dev, mailbox->dma, nent, 0, op, MLX4_CMD_TIME_CLASS_B, MLX4_CMD_NATIVE); if (err) goto out; nent = 0; } } } if (nent) err = mlx4_cmd(dev, mailbox->dma, nent, 0, op, MLX4_CMD_TIME_CLASS_B, MLX4_CMD_NATIVE); if (err) goto out; switch (op) { case MLX4_CMD_MAP_FA: mlx4_dbg(dev, "Mapped %d chunks/%d KB for FW\n", tc, ts); break; case MLX4_CMD_MAP_ICM_AUX: mlx4_dbg(dev, "Mapped %d chunks/%d KB for ICM aux\n", tc, ts); break; case MLX4_CMD_MAP_ICM: mlx4_dbg(dev, "Mapped %d chunks/%d KB at %llx for ICM\n", tc, ts, (unsigned long long) virt - (ts << 10)); break; } out: mlx4_free_cmd_mailbox(dev, mailbox); return err; } int mlx4_MAP_FA(struct mlx4_dev *dev, struct mlx4_icm *icm) { return mlx4_map_cmd(dev, MLX4_CMD_MAP_FA, icm, -1); } int mlx4_UNMAP_FA(struct mlx4_dev *dev) { return mlx4_cmd(dev, 0, 0, 0, MLX4_CMD_UNMAP_FA, MLX4_CMD_TIME_CLASS_B, MLX4_CMD_NATIVE); } int mlx4_RUN_FW(struct mlx4_dev *dev) { return mlx4_cmd(dev, 0, 0, 0, MLX4_CMD_RUN_FW, MLX4_CMD_TIME_CLASS_A, MLX4_CMD_NATIVE); } int mlx4_QUERY_FW(struct mlx4_dev *dev) { struct mlx4_fw *fw = &mlx4_priv(dev)->fw; struct mlx4_cmd *cmd = &mlx4_priv(dev)->cmd; struct mlx4_cmd_mailbox *mailbox; u32 *outbox; int err = 0; u64 fw_ver; u16 cmd_if_rev; u8 lg; #define QUERY_FW_OUT_SIZE 0x100 #define QUERY_FW_VER_OFFSET 0x00 #define QUERY_FW_PPF_ID 0x09 #define QUERY_FW_CMD_IF_REV_OFFSET 0x0a #define QUERY_FW_MAX_CMD_OFFSET 0x0f #define QUERY_FW_ERR_START_OFFSET 0x30 #define QUERY_FW_ERR_SIZE_OFFSET 0x38 #define QUERY_FW_ERR_BAR_OFFSET 0x3c #define QUERY_FW_SIZE_OFFSET 0x00 #define QUERY_FW_CLR_INT_BASE_OFFSET 0x20 #define QUERY_FW_CLR_INT_BAR_OFFSET 0x28 #define QUERY_FW_COMM_BASE_OFFSET 0x40 #define QUERY_FW_COMM_BAR_OFFSET 0x48 #define QUERY_FW_CLOCK_OFFSET 0x50 #define QUERY_FW_CLOCK_BAR 0x58 mailbox = mlx4_alloc_cmd_mailbox(dev); if (IS_ERR(mailbox)) return PTR_ERR(mailbox); outbox = mailbox->buf; err = mlx4_cmd_box(dev, 0, mailbox->dma, 0, 0, MLX4_CMD_QUERY_FW, MLX4_CMD_TIME_CLASS_A, MLX4_CMD_NATIVE); if (err) goto out; MLX4_GET(fw_ver, outbox, QUERY_FW_VER_OFFSET); /* * FW subminor version is at more significant bits than minor * version, so swap here. */ dev->caps.fw_ver = (fw_ver & 0xffff00000000ull) | ((fw_ver & 0xffff0000ull) >> 16) | ((fw_ver & 0x0000ffffull) << 16); MLX4_GET(lg, outbox, QUERY_FW_PPF_ID); dev->caps.function = lg; if (mlx4_is_slave(dev)) goto out; MLX4_GET(cmd_if_rev, outbox, QUERY_FW_CMD_IF_REV_OFFSET); if (cmd_if_rev < MLX4_COMMAND_INTERFACE_MIN_REV || cmd_if_rev > MLX4_COMMAND_INTERFACE_MAX_REV) { mlx4_err(dev, "Installed FW has unsupported command interface revision %d\n", cmd_if_rev); mlx4_err(dev, "(Installed FW version is %d.%d.%03d)\n", (int) (dev->caps.fw_ver >> 32), (int) (dev->caps.fw_ver >> 16) & 0xffff, (int) dev->caps.fw_ver & 0xffff); mlx4_err(dev, "This driver version supports only revisions %d to %d\n", MLX4_COMMAND_INTERFACE_MIN_REV, MLX4_COMMAND_INTERFACE_MAX_REV); err = -ENODEV; goto out; } if (cmd_if_rev < MLX4_COMMAND_INTERFACE_NEW_PORT_CMDS) dev->flags |= MLX4_FLAG_OLD_PORT_CMDS; MLX4_GET(lg, outbox, QUERY_FW_MAX_CMD_OFFSET); cmd->max_cmds = 1 << lg; mlx4_dbg(dev, "FW version %d.%d.%03d (cmd intf rev %d), max commands %d\n", (int) (dev->caps.fw_ver >> 32), (int) (dev->caps.fw_ver >> 16) & 0xffff, (int) dev->caps.fw_ver & 0xffff, cmd_if_rev, cmd->max_cmds); MLX4_GET(fw->catas_offset, outbox, QUERY_FW_ERR_START_OFFSET); MLX4_GET(fw->catas_size, outbox, QUERY_FW_ERR_SIZE_OFFSET); MLX4_GET(fw->catas_bar, outbox, QUERY_FW_ERR_BAR_OFFSET); fw->catas_bar = (fw->catas_bar >> 6) * 2; mlx4_dbg(dev, "Catastrophic error buffer at 0x%llx, size 0x%x, BAR %d\n", (unsigned long long) fw->catas_offset, fw->catas_size, fw->catas_bar); MLX4_GET(fw->fw_pages, outbox, QUERY_FW_SIZE_OFFSET); MLX4_GET(fw->clr_int_base, outbox, QUERY_FW_CLR_INT_BASE_OFFSET); MLX4_GET(fw->clr_int_bar, outbox, QUERY_FW_CLR_INT_BAR_OFFSET); fw->clr_int_bar = (fw->clr_int_bar >> 6) * 2; MLX4_GET(fw->comm_base, outbox, QUERY_FW_COMM_BASE_OFFSET); MLX4_GET(fw->comm_bar, outbox, QUERY_FW_COMM_BAR_OFFSET); fw->comm_bar = (fw->comm_bar >> 6) * 2; mlx4_dbg(dev, "Communication vector bar:%d offset:0x%llx\n", fw->comm_bar, fw->comm_base); mlx4_dbg(dev, "FW size %d KB\n", fw->fw_pages >> 2); MLX4_GET(fw->clock_offset, outbox, QUERY_FW_CLOCK_OFFSET); MLX4_GET(fw->clock_bar, outbox, QUERY_FW_CLOCK_BAR); fw->clock_bar = (fw->clock_bar >> 6) * 2; mlx4_dbg(dev, "Internal clock bar:%d offset:0x%llx\n", fw->clock_bar, fw->clock_offset); /* * Round up number of system pages needed in case * MLX4_ICM_PAGE_SIZE < PAGE_SIZE. */ fw->fw_pages = ALIGN(fw->fw_pages, PAGE_SIZE / MLX4_ICM_PAGE_SIZE) >> (PAGE_SHIFT - MLX4_ICM_PAGE_SHIFT); mlx4_dbg(dev, "Clear int @ %llx, BAR %d\n", (unsigned long long) fw->clr_int_base, fw->clr_int_bar); out: mlx4_free_cmd_mailbox(dev, mailbox); return err; } int mlx4_QUERY_FW_wrapper(struct mlx4_dev *dev, int slave, struct mlx4_vhcr *vhcr, struct mlx4_cmd_mailbox *inbox, struct mlx4_cmd_mailbox *outbox, struct mlx4_cmd_info *cmd) { u8 *outbuf; int err; outbuf = outbox->buf; err = mlx4_cmd_box(dev, 0, outbox->dma, 0, 0, MLX4_CMD_QUERY_FW, MLX4_CMD_TIME_CLASS_A, MLX4_CMD_NATIVE); if (err) return err; /* for slaves, set pci PPF ID to invalid and zero out everything * else except FW version */ outbuf[0] = outbuf[1] = 0; memset(&outbuf[8], 0, QUERY_FW_OUT_SIZE - 8); outbuf[QUERY_FW_PPF_ID] = MLX4_INVALID_SLAVE_ID; return 0; } static void get_board_id(void *vsd, char *board_id) { int i; #define VSD_OFFSET_SIG1 0x00 #define VSD_OFFSET_SIG2 0xde #define VSD_OFFSET_MLX_BOARD_ID 0xd0 #define VSD_OFFSET_TS_BOARD_ID 0x20 #define VSD_SIGNATURE_TOPSPIN 0x5ad memset(board_id, 0, MLX4_BOARD_ID_LEN); if (be16_to_cpup(vsd + VSD_OFFSET_SIG1) == VSD_SIGNATURE_TOPSPIN && be16_to_cpup(vsd + VSD_OFFSET_SIG2) == VSD_SIGNATURE_TOPSPIN) { strlcpy(board_id, vsd + VSD_OFFSET_TS_BOARD_ID, MLX4_BOARD_ID_LEN); } else { /* * The board ID is a string but the firmware byte * swaps each 4-byte word before passing it back to * us. Therefore we need to swab it before printing. */ u32 *bid_u32 = (u32 *)board_id; for (i = 0; i < 4; ++i) { u32 *addr; u32 val; addr = (u32 *) (vsd + VSD_OFFSET_MLX_BOARD_ID + i * 4); val = get_unaligned(addr); val = swab32(val); put_unaligned(val, &bid_u32[i]); } } } int mlx4_QUERY_ADAPTER(struct mlx4_dev *dev, struct mlx4_adapter *adapter) { struct mlx4_cmd_mailbox *mailbox; u32 *outbox; int err; #define QUERY_ADAPTER_OUT_SIZE 0x100 #define QUERY_ADAPTER_INTA_PIN_OFFSET 0x10 #define QUERY_ADAPTER_VSD_OFFSET 0x20 mailbox = mlx4_alloc_cmd_mailbox(dev); if (IS_ERR(mailbox)) return PTR_ERR(mailbox); outbox = mailbox->buf; err = mlx4_cmd_box(dev, 0, mailbox->dma, 0, 0, MLX4_CMD_QUERY_ADAPTER, MLX4_CMD_TIME_CLASS_A, MLX4_CMD_NATIVE); if (err) goto out; MLX4_GET(adapter->inta_pin, outbox, QUERY_ADAPTER_INTA_PIN_OFFSET); get_board_id(outbox + QUERY_ADAPTER_VSD_OFFSET / 4, adapter->board_id); out: mlx4_free_cmd_mailbox(dev, mailbox); return err; } int mlx4_INIT_HCA(struct mlx4_dev *dev, struct mlx4_init_hca_param *param) { struct mlx4_cmd_mailbox *mailbox; __be32 *inbox; int err; static const u8 a0_dmfs_hw_steering[] = { [MLX4_STEERING_DMFS_A0_DEFAULT] = 0, [MLX4_STEERING_DMFS_A0_DYNAMIC] = 1, [MLX4_STEERING_DMFS_A0_STATIC] = 2, [MLX4_STEERING_DMFS_A0_DISABLE] = 3 }; #define INIT_HCA_IN_SIZE 0x200 #define INIT_HCA_VERSION_OFFSET 0x000 #define INIT_HCA_VERSION 2 #define INIT_HCA_VXLAN_OFFSET 0x0c #define INIT_HCA_CACHELINE_SZ_OFFSET 0x0e #define INIT_HCA_FLAGS_OFFSET 0x014 #define INIT_HCA_RECOVERABLE_ERROR_EVENT_OFFSET 0x018 #define INIT_HCA_QPC_OFFSET 0x020 #define INIT_HCA_QPC_BASE_OFFSET (INIT_HCA_QPC_OFFSET + 0x10) #define INIT_HCA_LOG_QP_OFFSET (INIT_HCA_QPC_OFFSET + 0x17) #define INIT_HCA_SRQC_BASE_OFFSET (INIT_HCA_QPC_OFFSET + 0x28) #define INIT_HCA_LOG_SRQ_OFFSET (INIT_HCA_QPC_OFFSET + 0x2f) #define INIT_HCA_CQC_BASE_OFFSET (INIT_HCA_QPC_OFFSET + 0x30) #define INIT_HCA_LOG_CQ_OFFSET (INIT_HCA_QPC_OFFSET + 0x37) #define INIT_HCA_EQE_CQE_OFFSETS (INIT_HCA_QPC_OFFSET + 0x38) #define INIT_HCA_EQE_CQE_STRIDE_OFFSET (INIT_HCA_QPC_OFFSET + 0x3b) #define INIT_HCA_ALTC_BASE_OFFSET (INIT_HCA_QPC_OFFSET + 0x40) #define INIT_HCA_AUXC_BASE_OFFSET (INIT_HCA_QPC_OFFSET + 0x50) #define INIT_HCA_EQC_BASE_OFFSET (INIT_HCA_QPC_OFFSET + 0x60) #define INIT_HCA_LOG_EQ_OFFSET (INIT_HCA_QPC_OFFSET + 0x67) #define INIT_HCA_NUM_SYS_EQS_OFFSET (INIT_HCA_QPC_OFFSET + 0x6a) #define INIT_HCA_RDMARC_BASE_OFFSET (INIT_HCA_QPC_OFFSET + 0x70) #define INIT_HCA_LOG_RD_OFFSET (INIT_HCA_QPC_OFFSET + 0x77) #define INIT_HCA_MCAST_OFFSET 0x0c0 #define INIT_HCA_MC_BASE_OFFSET (INIT_HCA_MCAST_OFFSET + 0x00) #define INIT_HCA_LOG_MC_ENTRY_SZ_OFFSET (INIT_HCA_MCAST_OFFSET + 0x12) #define INIT_HCA_LOG_MC_HASH_SZ_OFFSET (INIT_HCA_MCAST_OFFSET + 0x16) #define INIT_HCA_UC_STEERING_OFFSET (INIT_HCA_MCAST_OFFSET + 0x18) #define INIT_HCA_LOG_MC_TABLE_SZ_OFFSET (INIT_HCA_MCAST_OFFSET + 0x1b) #define INIT_HCA_DEVICE_MANAGED_FLOW_STEERING_EN 0x6 #define INIT_HCA_FS_PARAM_OFFSET 0x1d0 #define INIT_HCA_FS_BASE_OFFSET (INIT_HCA_FS_PARAM_OFFSET + 0x00) #define INIT_HCA_FS_LOG_ENTRY_SZ_OFFSET (INIT_HCA_FS_PARAM_OFFSET + 0x12) #define INIT_HCA_FS_A0_OFFSET (INIT_HCA_FS_PARAM_OFFSET + 0x18) #define INIT_HCA_FS_LOG_TABLE_SZ_OFFSET (INIT_HCA_FS_PARAM_OFFSET + 0x1b) #define INIT_HCA_FS_ETH_BITS_OFFSET (INIT_HCA_FS_PARAM_OFFSET + 0x21) #define INIT_HCA_FS_ETH_NUM_ADDRS_OFFSET (INIT_HCA_FS_PARAM_OFFSET + 0x22) #define INIT_HCA_FS_IB_BITS_OFFSET (INIT_HCA_FS_PARAM_OFFSET + 0x25) #define INIT_HCA_FS_IB_NUM_ADDRS_OFFSET (INIT_HCA_FS_PARAM_OFFSET + 0x26) #define INIT_HCA_TPT_OFFSET 0x0f0 #define INIT_HCA_DMPT_BASE_OFFSET (INIT_HCA_TPT_OFFSET + 0x00) #define INIT_HCA_TPT_MW_OFFSET (INIT_HCA_TPT_OFFSET + 0x08) #define INIT_HCA_LOG_MPT_SZ_OFFSET (INIT_HCA_TPT_OFFSET + 0x0b) #define INIT_HCA_MTT_BASE_OFFSET (INIT_HCA_TPT_OFFSET + 0x10) #define INIT_HCA_CMPT_BASE_OFFSET (INIT_HCA_TPT_OFFSET + 0x18) #define INIT_HCA_UAR_OFFSET 0x120 #define INIT_HCA_LOG_UAR_SZ_OFFSET (INIT_HCA_UAR_OFFSET + 0x0a) #define INIT_HCA_UAR_PAGE_SZ_OFFSET (INIT_HCA_UAR_OFFSET + 0x0b) mailbox = mlx4_alloc_cmd_mailbox(dev); if (IS_ERR(mailbox)) return PTR_ERR(mailbox); inbox = mailbox->buf; *((u8 *) mailbox->buf + INIT_HCA_VERSION_OFFSET) = INIT_HCA_VERSION; *((u8 *) mailbox->buf + INIT_HCA_CACHELINE_SZ_OFFSET) = ((ilog2(cache_line_size()) - 4) << 5) | (1 << 4); #if defined(__LITTLE_ENDIAN) *(inbox + INIT_HCA_FLAGS_OFFSET / 4) &= ~cpu_to_be32(1 << 1); #elif defined(__BIG_ENDIAN) *(inbox + INIT_HCA_FLAGS_OFFSET / 4) |= cpu_to_be32(1 << 1); #else #error Host endianness not defined #endif /* Check port for UD address vector: */ *(inbox + INIT_HCA_FLAGS_OFFSET / 4) |= cpu_to_be32(1); /* Enable IPoIB checksumming if we can: */ if (dev->caps.flags & MLX4_DEV_CAP_FLAG_IPOIB_CSUM) *(inbox + INIT_HCA_FLAGS_OFFSET / 4) |= cpu_to_be32(1 << 3); /* Enable QoS support if module parameter set */ if (dev->caps.flags2 & MLX4_DEV_CAP_FLAG2_ETS_CFG && enable_qos) *(inbox + INIT_HCA_FLAGS_OFFSET / 4) |= cpu_to_be32(1 << 2); /* enable counters */ if (dev->caps.flags & MLX4_DEV_CAP_FLAG_COUNTERS) *(inbox + INIT_HCA_FLAGS_OFFSET / 4) |= cpu_to_be32(1 << 4); /* Enable RSS spread to fragmented IP packets when supported */ if (dev->caps.flags & MLX4_DEV_CAP_FLAG_RSS_IP_FRAG) *(inbox + INIT_HCA_FLAGS_OFFSET / 4) |= cpu_to_be32(1 << 13); /* CX3 is capable of extending CQEs/EQEs from 32 to 64 bytes */ if (dev->caps.flags & MLX4_DEV_CAP_FLAG_64B_EQE) { *(inbox + INIT_HCA_EQE_CQE_OFFSETS / 4) |= cpu_to_be32(1 << 29); dev->caps.eqe_size = 64; dev->caps.eqe_factor = 1; } else { dev->caps.eqe_size = 32; dev->caps.eqe_factor = 0; } if (dev->caps.flags & MLX4_DEV_CAP_FLAG_64B_CQE) { *(inbox + INIT_HCA_EQE_CQE_OFFSETS / 4) |= cpu_to_be32(1 << 30); dev->caps.cqe_size = 64; dev->caps.userspace_caps |= MLX4_USER_DEV_CAP_LARGE_CQE; } else { dev->caps.cqe_size = 32; } /* CX3 is capable of extending CQEs\EQEs to strides larger than 64B */ if ((dev->caps.flags2 & MLX4_DEV_CAP_FLAG2_EQE_STRIDE) && (dev->caps.flags2 & MLX4_DEV_CAP_FLAG2_CQE_STRIDE)) { dev->caps.eqe_size = cache_line_size(); dev->caps.cqe_size = cache_line_size(); dev->caps.eqe_factor = 0; MLX4_PUT(inbox, (u8)((ilog2(dev->caps.eqe_size) - 5) << 4 | (ilog2(dev->caps.eqe_size) - 5)), INIT_HCA_EQE_CQE_STRIDE_OFFSET); /* User still need to know to support CQE > 32B */ dev->caps.userspace_caps |= MLX4_USER_DEV_CAP_LARGE_CQE; } if (dev->caps.flags2 & MLX4_DEV_CAP_FLAG2_RECOVERABLE_ERROR_EVENT) *(inbox + INIT_HCA_RECOVERABLE_ERROR_EVENT_OFFSET / 4) |= cpu_to_be32(1 << 31); /* QPC/EEC/CQC/EQC/RDMARC attributes */ MLX4_PUT(inbox, param->qpc_base, INIT_HCA_QPC_BASE_OFFSET); MLX4_PUT(inbox, param->log_num_qps, INIT_HCA_LOG_QP_OFFSET); MLX4_PUT(inbox, param->srqc_base, INIT_HCA_SRQC_BASE_OFFSET); MLX4_PUT(inbox, param->log_num_srqs, INIT_HCA_LOG_SRQ_OFFSET); MLX4_PUT(inbox, param->cqc_base, INIT_HCA_CQC_BASE_OFFSET); MLX4_PUT(inbox, param->log_num_cqs, INIT_HCA_LOG_CQ_OFFSET); MLX4_PUT(inbox, param->altc_base, INIT_HCA_ALTC_BASE_OFFSET); MLX4_PUT(inbox, param->auxc_base, INIT_HCA_AUXC_BASE_OFFSET); MLX4_PUT(inbox, param->eqc_base, INIT_HCA_EQC_BASE_OFFSET); MLX4_PUT(inbox, param->log_num_eqs, INIT_HCA_LOG_EQ_OFFSET); MLX4_PUT(inbox, param->num_sys_eqs, INIT_HCA_NUM_SYS_EQS_OFFSET); MLX4_PUT(inbox, param->rdmarc_base, INIT_HCA_RDMARC_BASE_OFFSET); MLX4_PUT(inbox, param->log_rd_per_qp, INIT_HCA_LOG_RD_OFFSET); /* steering attributes */ if (dev->caps.steering_mode == MLX4_STEERING_MODE_DEVICE_MANAGED) { *(inbox + INIT_HCA_FLAGS_OFFSET / 4) |= cpu_to_be32(1 << INIT_HCA_DEVICE_MANAGED_FLOW_STEERING_EN); MLX4_PUT(inbox, param->mc_base, INIT_HCA_FS_BASE_OFFSET); MLX4_PUT(inbox, param->log_mc_entry_sz, INIT_HCA_FS_LOG_ENTRY_SZ_OFFSET); MLX4_PUT(inbox, param->log_mc_table_sz, INIT_HCA_FS_LOG_TABLE_SZ_OFFSET); /* Enable Ethernet flow steering * with udp unicast and tcp unicast */ if (dev->caps.dmfs_high_steer_mode != MLX4_STEERING_DMFS_A0_STATIC) MLX4_PUT(inbox, (u8)(MLX4_FS_UDP_UC_EN | MLX4_FS_TCP_UC_EN), INIT_HCA_FS_ETH_BITS_OFFSET); MLX4_PUT(inbox, (u16) MLX4_FS_NUM_OF_L2_ADDR, INIT_HCA_FS_ETH_NUM_ADDRS_OFFSET); /* Enable IPoIB flow steering * with udp unicast and tcp unicast */ MLX4_PUT(inbox, (u8) (MLX4_FS_UDP_UC_EN | MLX4_FS_TCP_UC_EN), INIT_HCA_FS_IB_BITS_OFFSET); MLX4_PUT(inbox, (u16) MLX4_FS_NUM_OF_L2_ADDR, INIT_HCA_FS_IB_NUM_ADDRS_OFFSET); if (dev->caps.dmfs_high_steer_mode != MLX4_STEERING_DMFS_A0_NOT_SUPPORTED) MLX4_PUT(inbox, ((u8)(a0_dmfs_hw_steering[dev->caps.dmfs_high_steer_mode] << 6)), INIT_HCA_FS_A0_OFFSET); } else { MLX4_PUT(inbox, param->mc_base, INIT_HCA_MC_BASE_OFFSET); MLX4_PUT(inbox, param->log_mc_entry_sz, INIT_HCA_LOG_MC_ENTRY_SZ_OFFSET); MLX4_PUT(inbox, param->log_mc_hash_sz, INIT_HCA_LOG_MC_HASH_SZ_OFFSET); MLX4_PUT(inbox, param->log_mc_table_sz, INIT_HCA_LOG_MC_TABLE_SZ_OFFSET); if (dev->caps.steering_mode == MLX4_STEERING_MODE_B0) MLX4_PUT(inbox, (u8) (1 << 3), INIT_HCA_UC_STEERING_OFFSET); } /* TPT attributes */ MLX4_PUT(inbox, param->dmpt_base, INIT_HCA_DMPT_BASE_OFFSET); MLX4_PUT(inbox, param->mw_enabled, INIT_HCA_TPT_MW_OFFSET); MLX4_PUT(inbox, param->log_mpt_sz, INIT_HCA_LOG_MPT_SZ_OFFSET); MLX4_PUT(inbox, param->mtt_base, INIT_HCA_MTT_BASE_OFFSET); MLX4_PUT(inbox, param->cmpt_base, INIT_HCA_CMPT_BASE_OFFSET); /* UAR attributes */ MLX4_PUT(inbox, param->uar_page_sz, INIT_HCA_UAR_PAGE_SZ_OFFSET); MLX4_PUT(inbox, param->log_uar_sz, INIT_HCA_LOG_UAR_SZ_OFFSET); /* set parser VXLAN attributes */ if (dev->caps.flags2 & MLX4_DEV_CAP_FLAG2_VXLAN_OFFLOADS) { u8 parser_params = 0; MLX4_PUT(inbox, parser_params, INIT_HCA_VXLAN_OFFSET); } err = mlx4_cmd(dev, mailbox->dma, 0, 0, MLX4_CMD_INIT_HCA, MLX4_CMD_TIME_CLASS_C, MLX4_CMD_NATIVE); if (err) mlx4_err(dev, "INIT_HCA returns %d\n", err); mlx4_free_cmd_mailbox(dev, mailbox); return err; } int mlx4_QUERY_HCA(struct mlx4_dev *dev, struct mlx4_init_hca_param *param) { struct mlx4_cmd_mailbox *mailbox; __be32 *outbox; u32 dword_field; int err; u8 byte_field; static const u8 a0_dmfs_query_hw_steering[] = { [0] = MLX4_STEERING_DMFS_A0_DEFAULT, [1] = MLX4_STEERING_DMFS_A0_DYNAMIC, [2] = MLX4_STEERING_DMFS_A0_STATIC, [3] = MLX4_STEERING_DMFS_A0_DISABLE }; #define QUERY_HCA_GLOBAL_CAPS_OFFSET 0x04 #define QUERY_HCA_CORE_CLOCK_OFFSET 0x0c mailbox = mlx4_alloc_cmd_mailbox(dev); if (IS_ERR(mailbox)) return PTR_ERR(mailbox); outbox = mailbox->buf; err = mlx4_cmd_box(dev, 0, mailbox->dma, 0, 0, MLX4_CMD_QUERY_HCA, MLX4_CMD_TIME_CLASS_B, !mlx4_is_slave(dev)); if (err) goto out; MLX4_GET(param->global_caps, outbox, QUERY_HCA_GLOBAL_CAPS_OFFSET); MLX4_GET(param->hca_core_clock, outbox, QUERY_HCA_CORE_CLOCK_OFFSET); /* QPC/EEC/CQC/EQC/RDMARC attributes */ MLX4_GET(param->qpc_base, outbox, INIT_HCA_QPC_BASE_OFFSET); MLX4_GET(param->log_num_qps, outbox, INIT_HCA_LOG_QP_OFFSET); MLX4_GET(param->srqc_base, outbox, INIT_HCA_SRQC_BASE_OFFSET); MLX4_GET(param->log_num_srqs, outbox, INIT_HCA_LOG_SRQ_OFFSET); MLX4_GET(param->cqc_base, outbox, INIT_HCA_CQC_BASE_OFFSET); MLX4_GET(param->log_num_cqs, outbox, INIT_HCA_LOG_CQ_OFFSET); MLX4_GET(param->altc_base, outbox, INIT_HCA_ALTC_BASE_OFFSET); MLX4_GET(param->auxc_base, outbox, INIT_HCA_AUXC_BASE_OFFSET); MLX4_GET(param->eqc_base, outbox, INIT_HCA_EQC_BASE_OFFSET); MLX4_GET(param->log_num_eqs, outbox, INIT_HCA_LOG_EQ_OFFSET); MLX4_GET(param->num_sys_eqs, outbox, INIT_HCA_NUM_SYS_EQS_OFFSET); MLX4_GET(param->rdmarc_base, outbox, INIT_HCA_RDMARC_BASE_OFFSET); MLX4_GET(param->log_rd_per_qp, outbox, INIT_HCA_LOG_RD_OFFSET); MLX4_GET(dword_field, outbox, INIT_HCA_FLAGS_OFFSET); if (dword_field & (1 << INIT_HCA_DEVICE_MANAGED_FLOW_STEERING_EN)) { param->steering_mode = MLX4_STEERING_MODE_DEVICE_MANAGED; } else { MLX4_GET(byte_field, outbox, INIT_HCA_UC_STEERING_OFFSET); if (byte_field & 0x8) param->steering_mode = MLX4_STEERING_MODE_B0; else param->steering_mode = MLX4_STEERING_MODE_A0; } if (dword_field & (1 << 13)) param->rss_ip_frags = 1; /* steering attributes */ if (param->steering_mode == MLX4_STEERING_MODE_DEVICE_MANAGED) { MLX4_GET(param->mc_base, outbox, INIT_HCA_FS_BASE_OFFSET); MLX4_GET(param->log_mc_entry_sz, outbox, INIT_HCA_FS_LOG_ENTRY_SZ_OFFSET); MLX4_GET(param->log_mc_table_sz, outbox, INIT_HCA_FS_LOG_TABLE_SZ_OFFSET); MLX4_GET(byte_field, outbox, INIT_HCA_FS_A0_OFFSET); param->dmfs_high_steer_mode = a0_dmfs_query_hw_steering[(byte_field >> 6) & 3]; } else { MLX4_GET(param->mc_base, outbox, INIT_HCA_MC_BASE_OFFSET); MLX4_GET(param->log_mc_entry_sz, outbox, INIT_HCA_LOG_MC_ENTRY_SZ_OFFSET); MLX4_GET(param->log_mc_hash_sz, outbox, INIT_HCA_LOG_MC_HASH_SZ_OFFSET); MLX4_GET(param->log_mc_table_sz, outbox, INIT_HCA_LOG_MC_TABLE_SZ_OFFSET); } /* CX3 is capable of extending CQEs/EQEs from 32 to 64 bytes */ MLX4_GET(byte_field, outbox, INIT_HCA_EQE_CQE_OFFSETS); if (byte_field & 0x20) /* 64-bytes eqe enabled */ param->dev_cap_enabled |= MLX4_DEV_CAP_64B_EQE_ENABLED; if (byte_field & 0x40) /* 64-bytes cqe enabled */ param->dev_cap_enabled |= MLX4_DEV_CAP_64B_CQE_ENABLED; /* CX3 is capable of extending CQEs\EQEs to strides larger than 64B */ MLX4_GET(byte_field, outbox, INIT_HCA_EQE_CQE_STRIDE_OFFSET); if (byte_field) { param->dev_cap_enabled |= MLX4_DEV_CAP_EQE_STRIDE_ENABLED; param->dev_cap_enabled |= MLX4_DEV_CAP_CQE_STRIDE_ENABLED; param->cqe_size = 1 << ((byte_field & MLX4_CQE_SIZE_MASK_STRIDE) + 5); param->eqe_size = 1 << (((byte_field & MLX4_EQE_SIZE_MASK_STRIDE) >> 4) + 5); } /* TPT attributes */ MLX4_GET(param->dmpt_base, outbox, INIT_HCA_DMPT_BASE_OFFSET); MLX4_GET(param->mw_enabled, outbox, INIT_HCA_TPT_MW_OFFSET); MLX4_GET(param->log_mpt_sz, outbox, INIT_HCA_LOG_MPT_SZ_OFFSET); MLX4_GET(param->mtt_base, outbox, INIT_HCA_MTT_BASE_OFFSET); MLX4_GET(param->cmpt_base, outbox, INIT_HCA_CMPT_BASE_OFFSET); /* UAR attributes */ MLX4_GET(param->uar_page_sz, outbox, INIT_HCA_UAR_PAGE_SZ_OFFSET); MLX4_GET(param->log_uar_sz, outbox, INIT_HCA_LOG_UAR_SZ_OFFSET); /* phv_check enable */ MLX4_GET(byte_field, outbox, INIT_HCA_CACHELINE_SZ_OFFSET); if (byte_field & 0x2) param->phv_check_en = 1; out: mlx4_free_cmd_mailbox(dev, mailbox); return err; } static int mlx4_hca_core_clock_update(struct mlx4_dev *dev) { struct mlx4_cmd_mailbox *mailbox; __be32 *outbox; int err; mailbox = mlx4_alloc_cmd_mailbox(dev); if (IS_ERR(mailbox)) { mlx4_warn(dev, "hca_core_clock mailbox allocation failed\n"); return PTR_ERR(mailbox); } outbox = mailbox->buf; err = mlx4_cmd_box(dev, 0, mailbox->dma, 0, 0, MLX4_CMD_QUERY_HCA, MLX4_CMD_TIME_CLASS_B, !mlx4_is_slave(dev)); if (err) { mlx4_warn(dev, "hca_core_clock update failed\n"); goto out; } MLX4_GET(dev->caps.hca_core_clock, outbox, QUERY_HCA_CORE_CLOCK_OFFSET); out: mlx4_free_cmd_mailbox(dev, mailbox); return err; } /* for IB-type ports only in SRIOV mode. Checks that both proxy QP0 * and real QP0 are active, so that the paravirtualized QP0 is ready * to operate */ static int check_qp0_state(struct mlx4_dev *dev, int function, int port) { struct mlx4_priv *priv = mlx4_priv(dev); /* irrelevant if not infiniband */ if (priv->mfunc.master.qp0_state[port].proxy_qp0_active && priv->mfunc.master.qp0_state[port].qp0_active) return 1; return 0; } int mlx4_INIT_PORT_wrapper(struct mlx4_dev *dev, int slave, struct mlx4_vhcr *vhcr, struct mlx4_cmd_mailbox *inbox, struct mlx4_cmd_mailbox *outbox, struct mlx4_cmd_info *cmd) { struct mlx4_priv *priv = mlx4_priv(dev); int port = mlx4_slave_convert_port(dev, slave, vhcr->in_modifier); int err; if (port < 0) return -EINVAL; if (priv->mfunc.master.slave_state[slave].init_port_mask & (1 << port)) return 0; if (dev->caps.port_mask[port] != MLX4_PORT_TYPE_IB) { /* Enable port only if it was previously disabled */ if (!priv->mfunc.master.init_port_ref[port]) { err = mlx4_cmd(dev, 0, port, 0, MLX4_CMD_INIT_PORT, MLX4_CMD_TIME_CLASS_A, MLX4_CMD_NATIVE); if (err) return err; } priv->mfunc.master.slave_state[slave].init_port_mask |= (1 << port); } else { if (slave == mlx4_master_func_num(dev)) { if (check_qp0_state(dev, slave, port) && !priv->mfunc.master.qp0_state[port].port_active) { err = mlx4_cmd(dev, 0, port, 0, MLX4_CMD_INIT_PORT, MLX4_CMD_TIME_CLASS_A, MLX4_CMD_NATIVE); if (err) return err; priv->mfunc.master.qp0_state[port].port_active = 1; priv->mfunc.master.slave_state[slave].init_port_mask |= (1 << port); } } else priv->mfunc.master.slave_state[slave].init_port_mask |= (1 << port); } ++priv->mfunc.master.init_port_ref[port]; return 0; } int mlx4_INIT_PORT(struct mlx4_dev *dev, int port) { struct mlx4_cmd_mailbox *mailbox; u32 *inbox; int err; u32 flags; u16 field; if (dev->flags & MLX4_FLAG_OLD_PORT_CMDS) { #define INIT_PORT_IN_SIZE 256 #define INIT_PORT_FLAGS_OFFSET 0x00 #define INIT_PORT_FLAG_SIG (1 << 18) #define INIT_PORT_FLAG_NG (1 << 17) #define INIT_PORT_FLAG_G0 (1 << 16) #define INIT_PORT_VL_SHIFT 4 #define INIT_PORT_PORT_WIDTH_SHIFT 8 #define INIT_PORT_MTU_OFFSET 0x04 #define INIT_PORT_MAX_GID_OFFSET 0x06 #define INIT_PORT_MAX_PKEY_OFFSET 0x0a #define INIT_PORT_GUID0_OFFSET 0x10 #define INIT_PORT_NODE_GUID_OFFSET 0x18 #define INIT_PORT_SI_GUID_OFFSET 0x20 mailbox = mlx4_alloc_cmd_mailbox(dev); if (IS_ERR(mailbox)) return PTR_ERR(mailbox); inbox = mailbox->buf; flags = 0; flags |= (dev->caps.vl_cap[port] & 0xf) << INIT_PORT_VL_SHIFT; flags |= (dev->caps.port_width_cap[port] & 0xf) << INIT_PORT_PORT_WIDTH_SHIFT; MLX4_PUT(inbox, flags, INIT_PORT_FLAGS_OFFSET); field = 128 << dev->caps.ib_mtu_cap[port]; MLX4_PUT(inbox, field, INIT_PORT_MTU_OFFSET); field = dev->caps.gid_table_len[port]; MLX4_PUT(inbox, field, INIT_PORT_MAX_GID_OFFSET); field = dev->caps.pkey_table_len[port]; MLX4_PUT(inbox, field, INIT_PORT_MAX_PKEY_OFFSET); err = mlx4_cmd(dev, mailbox->dma, port, 0, MLX4_CMD_INIT_PORT, MLX4_CMD_TIME_CLASS_A, MLX4_CMD_NATIVE); mlx4_free_cmd_mailbox(dev, mailbox); } else err = mlx4_cmd(dev, 0, port, 0, MLX4_CMD_INIT_PORT, MLX4_CMD_TIME_CLASS_A, MLX4_CMD_WRAPPED); if (!err) mlx4_hca_core_clock_update(dev); return err; } EXPORT_SYMBOL_GPL(mlx4_INIT_PORT); int mlx4_CLOSE_PORT_wrapper(struct mlx4_dev *dev, int slave, struct mlx4_vhcr *vhcr, struct mlx4_cmd_mailbox *inbox, struct mlx4_cmd_mailbox *outbox, struct mlx4_cmd_info *cmd) { struct mlx4_priv *priv = mlx4_priv(dev); int port = mlx4_slave_convert_port(dev, slave, vhcr->in_modifier); int err; if (port < 0) return -EINVAL; if (!(priv->mfunc.master.slave_state[slave].init_port_mask & (1 << port))) return 0; if (dev->caps.port_mask[port] != MLX4_PORT_TYPE_IB) { if (priv->mfunc.master.init_port_ref[port] == 1) { err = mlx4_cmd(dev, 0, port, 0, MLX4_CMD_CLOSE_PORT, MLX4_CMD_TIME_CLASS_A, MLX4_CMD_NATIVE); if (err) return err; } priv->mfunc.master.slave_state[slave].init_port_mask &= ~(1 << port); } else { /* infiniband port */ if (slave == mlx4_master_func_num(dev)) { if (!priv->mfunc.master.qp0_state[port].qp0_active && priv->mfunc.master.qp0_state[port].port_active) { err = mlx4_cmd(dev, 0, port, 0, MLX4_CMD_CLOSE_PORT, MLX4_CMD_TIME_CLASS_A, MLX4_CMD_NATIVE); if (err) return err; priv->mfunc.master.slave_state[slave].init_port_mask &= ~(1 << port); priv->mfunc.master.qp0_state[port].port_active = 0; } } else priv->mfunc.master.slave_state[slave].init_port_mask &= ~(1 << port); } --priv->mfunc.master.init_port_ref[port]; return 0; } int mlx4_CLOSE_PORT(struct mlx4_dev *dev, int port) { return mlx4_cmd(dev, 0, port, 0, MLX4_CMD_CLOSE_PORT, MLX4_CMD_TIME_CLASS_A, MLX4_CMD_WRAPPED); } EXPORT_SYMBOL_GPL(mlx4_CLOSE_PORT); int mlx4_CLOSE_HCA(struct mlx4_dev *dev, int panic) { return mlx4_cmd(dev, 0, 0, panic, MLX4_CMD_CLOSE_HCA, MLX4_CMD_TIME_CLASS_C, MLX4_CMD_NATIVE); } struct mlx4_config_dev { __be32 update_flags; __be32 rsvd1[3]; __be16 vxlan_udp_dport; __be16 rsvd2; __be16 roce_v2_entropy; __be16 roce_v2_udp_dport; __be32 roce_flags; __be32 rsvd4[25]; __be16 rsvd5; u8 rsvd6; u8 rx_checksum_val; }; #define MLX4_VXLAN_UDP_DPORT (1 << 0) #define MLX4_ROCE_V2_UDP_DPORT BIT(3) #define MLX4_DISABLE_RX_PORT BIT(18) static int mlx4_CONFIG_DEV_set(struct mlx4_dev *dev, struct mlx4_config_dev *config_dev) { int err; struct mlx4_cmd_mailbox *mailbox; mailbox = mlx4_alloc_cmd_mailbox(dev); if (IS_ERR(mailbox)) return PTR_ERR(mailbox); memcpy(mailbox->buf, config_dev, sizeof(*config_dev)); err = mlx4_cmd(dev, mailbox->dma, 0, 0, MLX4_CMD_CONFIG_DEV, MLX4_CMD_TIME_CLASS_B, MLX4_CMD_NATIVE); mlx4_free_cmd_mailbox(dev, mailbox); return err; } static int mlx4_CONFIG_DEV_get(struct mlx4_dev *dev, struct mlx4_config_dev *config_dev) { int err; struct mlx4_cmd_mailbox *mailbox; mailbox = mlx4_alloc_cmd_mailbox(dev); if (IS_ERR(mailbox)) return PTR_ERR(mailbox); err = mlx4_cmd_box(dev, 0, mailbox->dma, 0, 1, MLX4_CMD_CONFIG_DEV, MLX4_CMD_TIME_CLASS_A, MLX4_CMD_NATIVE); if (!err) memcpy(config_dev, mailbox->buf, sizeof(*config_dev)); mlx4_free_cmd_mailbox(dev, mailbox); return err; } /* Conversion between the HW values and the actual functionality. * The value represented by the array index, * and the functionality determined by the flags. */ static const u8 config_dev_csum_flags[] = { [0] = 0, [1] = MLX4_RX_CSUM_MODE_VAL_NON_TCP_UDP, [2] = MLX4_RX_CSUM_MODE_VAL_NON_TCP_UDP | MLX4_RX_CSUM_MODE_L4, [3] = MLX4_RX_CSUM_MODE_L4 | MLX4_RX_CSUM_MODE_IP_OK_IP_NON_TCP_UDP | MLX4_RX_CSUM_MODE_MULTI_VLAN }; int mlx4_config_dev_retrieval(struct mlx4_dev *dev, struct mlx4_config_dev_params *params) { struct mlx4_config_dev config_dev = {0}; int err; u8 csum_mask; #define CONFIG_DEV_RX_CSUM_MODE_MASK 0x7 #define CONFIG_DEV_RX_CSUM_MODE_PORT1_BIT_OFFSET 0 #define CONFIG_DEV_RX_CSUM_MODE_PORT2_BIT_OFFSET 4 if (!(dev->caps.flags2 & MLX4_DEV_CAP_FLAG2_CONFIG_DEV)) return -EOPNOTSUPP; err = mlx4_CONFIG_DEV_get(dev, &config_dev); if (err) return err; csum_mask = (config_dev.rx_checksum_val >> CONFIG_DEV_RX_CSUM_MODE_PORT1_BIT_OFFSET) & CONFIG_DEV_RX_CSUM_MODE_MASK; if (csum_mask >= sizeof(config_dev_csum_flags)/sizeof(config_dev_csum_flags[0])) return -EINVAL; params->rx_csum_flags_port_1 = config_dev_csum_flags[csum_mask]; csum_mask = (config_dev.rx_checksum_val >> CONFIG_DEV_RX_CSUM_MODE_PORT2_BIT_OFFSET) & CONFIG_DEV_RX_CSUM_MODE_MASK; if (csum_mask >= sizeof(config_dev_csum_flags)/sizeof(config_dev_csum_flags[0])) return -EINVAL; params->rx_csum_flags_port_2 = config_dev_csum_flags[csum_mask]; params->vxlan_udp_dport = be16_to_cpu(config_dev.vxlan_udp_dport); return 0; } EXPORT_SYMBOL_GPL(mlx4_config_dev_retrieval); int mlx4_config_vxlan_port(struct mlx4_dev *dev, __be16 udp_port) { struct mlx4_config_dev config_dev; memset(&config_dev, 0, sizeof(config_dev)); config_dev.update_flags = cpu_to_be32(MLX4_VXLAN_UDP_DPORT); config_dev.vxlan_udp_dport = udp_port; return mlx4_CONFIG_DEV_set(dev, &config_dev); } EXPORT_SYMBOL_GPL(mlx4_config_vxlan_port); #define CONFIG_DISABLE_RX_PORT BIT(15) int mlx4_disable_rx_port_check(struct mlx4_dev *dev, bool dis) { struct mlx4_config_dev config_dev; memset(&config_dev, 0, sizeof(config_dev)); config_dev.update_flags = cpu_to_be32(MLX4_DISABLE_RX_PORT); if (dis) config_dev.roce_flags = cpu_to_be32(CONFIG_DISABLE_RX_PORT); return mlx4_CONFIG_DEV_set(dev, &config_dev); } int mlx4_config_roce_v2_port(struct mlx4_dev *dev, u16 udp_port) { struct mlx4_config_dev config_dev; memset(&config_dev, 0, sizeof(config_dev)); config_dev.update_flags = cpu_to_be32(MLX4_ROCE_V2_UDP_DPORT); config_dev.roce_v2_udp_dport = cpu_to_be16(udp_port); return mlx4_CONFIG_DEV_set(dev, &config_dev); } EXPORT_SYMBOL_GPL(mlx4_config_roce_v2_port); int mlx4_virt2phy_port_map(struct mlx4_dev *dev, u32 port1, u32 port2) { struct mlx4_cmd_mailbox *mailbox; struct { __be32 v_port1; __be32 v_port2; } *v2p; int err; mailbox = mlx4_alloc_cmd_mailbox(dev); if (IS_ERR(mailbox)) return -ENOMEM; v2p = mailbox->buf; v2p->v_port1 = cpu_to_be32(port1); v2p->v_port2 = cpu_to_be32(port2); err = mlx4_cmd(dev, mailbox->dma, 0, MLX4_SET_PORT_VIRT2PHY, MLX4_CMD_VIRT_PORT_MAP, MLX4_CMD_TIME_CLASS_B, MLX4_CMD_NATIVE); mlx4_free_cmd_mailbox(dev, mailbox); return err; } int mlx4_SET_ICM_SIZE(struct mlx4_dev *dev, u64 icm_size, u64 *aux_pages) { int ret = mlx4_cmd_imm(dev, icm_size, aux_pages, 0, 0, MLX4_CMD_SET_ICM_SIZE, MLX4_CMD_TIME_CLASS_A, MLX4_CMD_NATIVE); if (ret) return ret; /* * Round up number of system pages needed in case * MLX4_ICM_PAGE_SIZE < PAGE_SIZE. */ *aux_pages = ALIGN(*aux_pages, PAGE_SIZE / MLX4_ICM_PAGE_SIZE) >> (PAGE_SHIFT - MLX4_ICM_PAGE_SHIFT); return 0; } int mlx4_NOP(struct mlx4_dev *dev) { /* Input modifier of 0x1f means "finish as soon as possible." */ return mlx4_cmd(dev, 0, 0x1f, 0, MLX4_CMD_NOP, MLX4_CMD_TIME_CLASS_A, MLX4_CMD_NATIVE); } int mlx4_query_diag_counters(struct mlx4_dev *dev, u8 op_modifier, const u32 offset[], u32 value[], size_t array_len, u8 port) { struct mlx4_cmd_mailbox *mailbox; u32 *outbox; size_t i; int ret; mailbox = mlx4_alloc_cmd_mailbox(dev); if (IS_ERR(mailbox)) return PTR_ERR(mailbox); outbox = mailbox->buf; ret = mlx4_cmd_box(dev, 0, mailbox->dma, port, op_modifier, MLX4_CMD_DIAG_RPRT, MLX4_CMD_TIME_CLASS_A, MLX4_CMD_NATIVE); if (ret) goto out; for (i = 0; i < array_len; i++) { if (offset[i] > MLX4_MAILBOX_SIZE) { ret = -EINVAL; goto out; } MLX4_GET(value[i], outbox, offset[i]); } out: mlx4_free_cmd_mailbox(dev, mailbox); return ret; } EXPORT_SYMBOL(mlx4_query_diag_counters); int mlx4_get_phys_port_id(struct mlx4_dev *dev) { u8 port; u32 *outbox; struct mlx4_cmd_mailbox *mailbox; u32 in_mod; u32 guid_hi, guid_lo; int err, ret = 0; #define MOD_STAT_CFG_PORT_OFFSET 8 #define MOD_STAT_CFG_GUID_H 0X14 #define MOD_STAT_CFG_GUID_L 0X1c mailbox = mlx4_alloc_cmd_mailbox(dev); if (IS_ERR(mailbox)) return PTR_ERR(mailbox); outbox = mailbox->buf; for (port = 1; port <= dev->caps.num_ports; port++) { in_mod = port << MOD_STAT_CFG_PORT_OFFSET; err = mlx4_cmd_box(dev, 0, mailbox->dma, in_mod, 0x2, MLX4_CMD_MOD_STAT_CFG, MLX4_CMD_TIME_CLASS_A, MLX4_CMD_NATIVE); if (err) { mlx4_err(dev, "Fail to get port %d uplink guid\n", port); ret = err; } else { MLX4_GET(guid_hi, outbox, MOD_STAT_CFG_GUID_H); MLX4_GET(guid_lo, outbox, MOD_STAT_CFG_GUID_L); dev->caps.phys_port_id[port] = (u64)guid_lo | (u64)guid_hi << 32; } } mlx4_free_cmd_mailbox(dev, mailbox); return ret; } #define MLX4_WOL_SETUP_MODE (5 << 28) int mlx4_wol_read(struct mlx4_dev *dev, u64 *config, int port) { u32 in_mod = MLX4_WOL_SETUP_MODE | port << 8; return mlx4_cmd_imm(dev, 0, config, in_mod, 0x3, MLX4_CMD_MOD_STAT_CFG, MLX4_CMD_TIME_CLASS_A, MLX4_CMD_NATIVE); } EXPORT_SYMBOL_GPL(mlx4_wol_read); int mlx4_wol_write(struct mlx4_dev *dev, u64 config, int port) { u32 in_mod = MLX4_WOL_SETUP_MODE | port << 8; return mlx4_cmd(dev, config, in_mod, 0x1, MLX4_CMD_MOD_STAT_CFG, MLX4_CMD_TIME_CLASS_A, MLX4_CMD_NATIVE); } EXPORT_SYMBOL_GPL(mlx4_wol_write); enum { ADD_TO_MCG = 0x26, }; void mlx4_opreq_action(struct work_struct *work) { struct mlx4_priv *priv = container_of(work, struct mlx4_priv, opreq_task); struct mlx4_dev *dev = &priv->dev; int num_tasks = atomic_read(&priv->opreq_count); struct mlx4_cmd_mailbox *mailbox; struct mlx4_mgm *mgm; u32 *outbox; u32 modifier; u16 token; u16 type; int err; u32 num_qps; struct mlx4_qp qp; int i; u8 rem_mcg; u8 prot; #define GET_OP_REQ_MODIFIER_OFFSET 0x08 #define GET_OP_REQ_TOKEN_OFFSET 0x14 #define GET_OP_REQ_TYPE_OFFSET 0x1a #define GET_OP_REQ_DATA_OFFSET 0x20 mailbox = mlx4_alloc_cmd_mailbox(dev); if (IS_ERR(mailbox)) { mlx4_err(dev, "Failed to allocate mailbox for GET_OP_REQ\n"); return; } outbox = mailbox->buf; while (num_tasks) { err = mlx4_cmd_box(dev, 0, mailbox->dma, 0, 0, MLX4_CMD_GET_OP_REQ, MLX4_CMD_TIME_CLASS_A, MLX4_CMD_NATIVE); if (err) { mlx4_err(dev, "Failed to retrieve required operation: %d\n", err); return; } MLX4_GET(modifier, outbox, GET_OP_REQ_MODIFIER_OFFSET); MLX4_GET(token, outbox, GET_OP_REQ_TOKEN_OFFSET); MLX4_GET(type, outbox, GET_OP_REQ_TYPE_OFFSET); type &= 0xfff; switch (type) { case ADD_TO_MCG: if (dev->caps.steering_mode == MLX4_STEERING_MODE_DEVICE_MANAGED) { mlx4_warn(dev, "ADD MCG operation is not supported in DEVICE_MANAGED steering mode\n"); err = EPERM; break; } mgm = (struct mlx4_mgm *)((u8 *)(outbox) + GET_OP_REQ_DATA_OFFSET); num_qps = be32_to_cpu(mgm->members_count) & MGM_QPN_MASK; rem_mcg = ((u8 *)(&mgm->members_count))[0] & 1; prot = ((u8 *)(&mgm->members_count))[0] >> 6; for (i = 0; i < num_qps; i++) { qp.qpn = be32_to_cpu(mgm->qp[i]); if (rem_mcg) err = mlx4_multicast_detach(dev, &qp, mgm->gid, prot, 0); else err = mlx4_multicast_attach(dev, &qp, mgm->gid, mgm->gid[5] , 0, prot, NULL); if (err) break; } break; default: mlx4_warn(dev, "Bad type for required operation\n"); err = EINVAL; break; } err = mlx4_cmd(dev, 0, ((u32) err | (__force u32)cpu_to_be32(token) << 16), 1, MLX4_CMD_GET_OP_REQ, MLX4_CMD_TIME_CLASS_A, MLX4_CMD_NATIVE); if (err) { mlx4_err(dev, "Failed to acknowledge required request: %d\n", err); goto out; } memset(outbox, 0, 0xffc); num_tasks = atomic_dec_return(&priv->opreq_count); } out: mlx4_free_cmd_mailbox(dev, mailbox); } static int mlx4_check_smp_firewall_active(struct mlx4_dev *dev, struct mlx4_cmd_mailbox *mailbox) { #define MLX4_CMD_MAD_DEMUX_SET_ATTR_OFFSET 0x10 #define MLX4_CMD_MAD_DEMUX_GETRESP_ATTR_OFFSET 0x20 #define MLX4_CMD_MAD_DEMUX_TRAP_ATTR_OFFSET 0x40 #define MLX4_CMD_MAD_DEMUX_TRAP_REPRESS_ATTR_OFFSET 0x70 u32 set_attr_mask, getresp_attr_mask; u32 trap_attr_mask, traprepress_attr_mask; MLX4_GET(set_attr_mask, mailbox->buf, MLX4_CMD_MAD_DEMUX_SET_ATTR_OFFSET); mlx4_dbg(dev, "SMP firewall set_attribute_mask = 0x%x\n", set_attr_mask); MLX4_GET(getresp_attr_mask, mailbox->buf, MLX4_CMD_MAD_DEMUX_GETRESP_ATTR_OFFSET); mlx4_dbg(dev, "SMP firewall getresp_attribute_mask = 0x%x\n", getresp_attr_mask); MLX4_GET(trap_attr_mask, mailbox->buf, MLX4_CMD_MAD_DEMUX_TRAP_ATTR_OFFSET); mlx4_dbg(dev, "SMP firewall trap_attribute_mask = 0x%x\n", trap_attr_mask); MLX4_GET(traprepress_attr_mask, mailbox->buf, MLX4_CMD_MAD_DEMUX_TRAP_REPRESS_ATTR_OFFSET); mlx4_dbg(dev, "SMP firewall traprepress_attribute_mask = 0x%x\n", traprepress_attr_mask); if (set_attr_mask && getresp_attr_mask && trap_attr_mask && traprepress_attr_mask) return 1; return 0; } int mlx4_config_mad_demux(struct mlx4_dev *dev) { struct mlx4_cmd_mailbox *mailbox; int err; /* Check if mad_demux is supported */ if (!(dev->caps.flags2 & MLX4_DEV_CAP_FLAG2_MAD_DEMUX)) return 0; mailbox = mlx4_alloc_cmd_mailbox(dev); if (IS_ERR(mailbox)) { mlx4_warn(dev, "Failed to allocate mailbox for cmd MAD_DEMUX"); return -ENOMEM; } /* Query mad_demux to find out which MADs are handled by internal sma */ err = mlx4_cmd_box(dev, 0, mailbox->dma, 0x01 /* subn mgmt class */, MLX4_CMD_MAD_DEMUX_QUERY_RESTR, MLX4_CMD_MAD_DEMUX, MLX4_CMD_TIME_CLASS_B, MLX4_CMD_NATIVE); if (err) { mlx4_warn(dev, "MLX4_CMD_MAD_DEMUX: query restrictions failed (%d)\n", err); goto out; } if (mlx4_check_smp_firewall_active(dev, mailbox)) dev->flags |= MLX4_FLAG_SECURE_HOST; /* Config mad_demux to handle all MADs returned by the query above */ err = mlx4_cmd(dev, mailbox->dma, 0x01 /* subn mgmt class */, MLX4_CMD_MAD_DEMUX_CONFIG, MLX4_CMD_MAD_DEMUX, MLX4_CMD_TIME_CLASS_B, MLX4_CMD_NATIVE); if (err) { mlx4_warn(dev, "MLX4_CMD_MAD_DEMUX: configure failed (%d)\n", err); goto out; } if (dev->flags & MLX4_FLAG_SECURE_HOST) mlx4_warn(dev, "HCA operating in secure-host mode. SMP firewall activated.\n"); out: mlx4_free_cmd_mailbox(dev, mailbox); return err; } /* Access Reg commands */ enum mlx4_access_reg_masks { MLX4_ACCESS_REG_STATUS_MASK = 0x7f, MLX4_ACCESS_REG_METHOD_MASK = 0x7f, MLX4_ACCESS_REG_LEN_MASK = 0x7ff }; struct mlx4_access_reg { __be16 constant1; u8 status; u8 resrvd1; __be16 reg_id; u8 method; u8 constant2; __be32 resrvd2[2]; __be16 len_const; __be16 resrvd3; #define MLX4_ACCESS_REG_HEADER_SIZE (20) u8 reg_data[MLX4_MAILBOX_SIZE-MLX4_ACCESS_REG_HEADER_SIZE]; } __attribute__((__packed__)); /** * mlx4_ACCESS_REG - Generic access reg command. * @dev: mlx4_dev. * @reg_id: register ID to access. * @method: Access method Read/Write. * @reg_len: register length to Read/Write in bytes. * @reg_data: reg_data pointer to Read/Write From/To. * * Access ConnectX registers FW command. * Returns 0 on success and copies outbox mlx4_access_reg data * field into reg_data or a negative error code. */ static int mlx4_ACCESS_REG(struct mlx4_dev *dev, u16 reg_id, enum mlx4_access_reg_method method, u16 reg_len, void *reg_data) { struct mlx4_cmd_mailbox *inbox, *outbox; struct mlx4_access_reg *inbuf, *outbuf; int err; inbox = mlx4_alloc_cmd_mailbox(dev); if (IS_ERR(inbox)) return PTR_ERR(inbox); outbox = mlx4_alloc_cmd_mailbox(dev); if (IS_ERR(outbox)) { mlx4_free_cmd_mailbox(dev, inbox); return PTR_ERR(outbox); } inbuf = inbox->buf; outbuf = outbox->buf; inbuf->constant1 = cpu_to_be16(0x1<<11 | 0x4); inbuf->constant2 = 0x1; inbuf->reg_id = cpu_to_be16(reg_id); inbuf->method = method & MLX4_ACCESS_REG_METHOD_MASK; reg_len = min(reg_len, (u16)(sizeof(inbuf->reg_data))); inbuf->len_const = cpu_to_be16(((reg_len/4 + 1) & MLX4_ACCESS_REG_LEN_MASK) | ((0x3) << 12)); memcpy(inbuf->reg_data, reg_data, reg_len); err = mlx4_cmd_box(dev, inbox->dma, outbox->dma, 0, 0, MLX4_CMD_ACCESS_REG, MLX4_CMD_TIME_CLASS_C, MLX4_CMD_WRAPPED); if (err) goto out; if (outbuf->status & MLX4_ACCESS_REG_STATUS_MASK) { err = outbuf->status & MLX4_ACCESS_REG_STATUS_MASK; mlx4_err(dev, "MLX4_CMD_ACCESS_REG(%x) returned REG status (%x)\n", reg_id, err); goto out; } memcpy(reg_data, outbuf->reg_data, reg_len); out: mlx4_free_cmd_mailbox(dev, inbox); mlx4_free_cmd_mailbox(dev, outbox); return err; } /* ConnectX registers IDs */ enum mlx4_reg_id { MLX4_REG_ID_PTYS = 0x5004, }; /** * mlx4_ACCESS_PTYS_REG - Access PTYs (Port Type and Speed) * register * @dev: mlx4_dev. * @method: Access method Read/Write. * @ptys_reg: PTYS register data pointer. * * Access ConnectX PTYS register, to Read/Write Port Type/Speed * configuration * Returns 0 on success or a negative error code. */ int mlx4_ACCESS_PTYS_REG(struct mlx4_dev *dev, enum mlx4_access_reg_method method, struct mlx4_ptys_reg *ptys_reg) { return mlx4_ACCESS_REG(dev, MLX4_REG_ID_PTYS, method, sizeof(*ptys_reg), ptys_reg); } EXPORT_SYMBOL_GPL(mlx4_ACCESS_PTYS_REG); int mlx4_ACCESS_REG_wrapper(struct mlx4_dev *dev, int slave, struct mlx4_vhcr *vhcr, struct mlx4_cmd_mailbox *inbox, struct mlx4_cmd_mailbox *outbox, struct mlx4_cmd_info *cmd) { struct mlx4_access_reg *inbuf = inbox->buf; u8 method = inbuf->method & MLX4_ACCESS_REG_METHOD_MASK; u16 reg_id = be16_to_cpu(inbuf->reg_id); if (slave != mlx4_master_func_num(dev) && method == MLX4_ACCESS_REG_WRITE) return -EPERM; if (reg_id == MLX4_REG_ID_PTYS) { struct mlx4_ptys_reg *ptys_reg = (struct mlx4_ptys_reg *)inbuf->reg_data; ptys_reg->local_port = mlx4_slave_convert_port(dev, slave, ptys_reg->local_port); } return mlx4_cmd_box(dev, inbox->dma, outbox->dma, vhcr->in_modifier, 0, MLX4_CMD_ACCESS_REG, MLX4_CMD_TIME_CLASS_C, MLX4_CMD_NATIVE); } static int mlx4_SET_PORT_phv_bit(struct mlx4_dev *dev, u8 port, u8 phv_bit) { #define SET_PORT_GEN_PHV_VALID 0x10 #define SET_PORT_GEN_PHV_EN 0x80 struct mlx4_cmd_mailbox *mailbox; struct mlx4_set_port_general_context *context; u32 in_mod; int err; mailbox = mlx4_alloc_cmd_mailbox(dev); if (IS_ERR(mailbox)) return PTR_ERR(mailbox); context = mailbox->buf; context->flags2 |= SET_PORT_GEN_PHV_VALID; if (phv_bit) context->phv_en |= SET_PORT_GEN_PHV_EN; in_mod = MLX4_SET_PORT_GENERAL << 8 | port; err = mlx4_cmd(dev, mailbox->dma, in_mod, MLX4_SET_PORT_ETH_OPCODE, MLX4_CMD_SET_PORT, MLX4_CMD_TIME_CLASS_B, MLX4_CMD_NATIVE); mlx4_free_cmd_mailbox(dev, mailbox); return err; } int get_phv_bit(struct mlx4_dev *dev, u8 port, int *phv) { int err; struct mlx4_func_cap func_cap; memset(&func_cap, 0, sizeof(func_cap)); err = mlx4_QUERY_FUNC_CAP(dev, port, &func_cap); if (!err) *phv = func_cap.flags0 & QUERY_FUNC_CAP_PHV_BIT; return err; } EXPORT_SYMBOL(get_phv_bit); int set_phv_bit(struct mlx4_dev *dev, u8 port, int new_val) { int ret; if (mlx4_is_slave(dev)) return -EPERM; if (dev->caps.flags2 & MLX4_DEV_CAP_FLAG2_PHV_EN && !(dev->caps.flags2 & MLX4_DEV_CAP_FLAG2_SKIP_OUTER_VLAN)) { ret = mlx4_SET_PORT_phv_bit(dev, port, new_val); if (!ret) dev->caps.phv_bit[port] = new_val; return ret; } return -EOPNOTSUPP; } EXPORT_SYMBOL(set_phv_bit); int mlx4_get_is_vlan_offload_disabled(struct mlx4_dev *dev, u8 port, bool *vlan_offload_disabled) { struct mlx4_func_cap func_cap; int err; memset(&func_cap, 0, sizeof(func_cap)); err = mlx4_QUERY_FUNC_CAP(dev, port, &func_cap); if (!err) *vlan_offload_disabled = !!(func_cap.flags0 & QUERY_FUNC_CAP_VLAN_OFFLOAD_DISABLE); return err; } EXPORT_SYMBOL(mlx4_get_is_vlan_offload_disabled); void mlx4_replace_zero_macs(struct mlx4_dev *dev) { int i; u8 mac_addr[ETH_ALEN]; dev->port_random_macs = 0; for (i = 1; i <= dev->caps.num_ports; ++i) if (!dev->caps.def_mac[i] && dev->caps.port_type[i] == MLX4_PORT_TYPE_ETH) { eth_random_addr(mac_addr); dev->port_random_macs |= 1 << i; dev->caps.def_mac[i] = mlx4_mac_to_u64(mac_addr); } } EXPORT_SYMBOL_GPL(mlx4_replace_zero_macs);
511971.c
/* +----------------------------------------------------------------------+ | Zend OPcache | +----------------------------------------------------------------------+ | Copyright (c) The PHP Group | +----------------------------------------------------------------------+ | This source file is subject to version 3.01 of the PHP license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | https://www.php.net/license/3_01.txt | | If you did not receive a copy of the PHP license and are unable to | | obtain it through the world-wide-web, please send a note to | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Authors: Andi Gutmans <[email protected]> | | Zeev Suraski <[email protected]> | | Stanislav Malyshev <[email protected]> | | Dmitry Stogov <[email protected]> | +----------------------------------------------------------------------+ */ #include "main/php.h" #include "main/php_globals.h" #include "zend.h" #include "zend_extensions.h" #include "zend_compile.h" #include "ZendAccelerator.h" #include "zend_persist.h" #include "zend_shared_alloc.h" #include "zend_accelerator_module.h" #include "zend_accelerator_blacklist.h" #include "zend_list.h" #include "zend_execute.h" #include "zend_vm.h" #include "zend_inheritance.h" #include "zend_exceptions.h" #include "main/php_main.h" #include "main/SAPI.h" #include "main/php_streams.h" #include "main/php_open_temporary_file.h" #include "zend_API.h" #include "zend_ini.h" #include "zend_virtual_cwd.h" #include "zend_accelerator_util_funcs.h" #include "zend_accelerator_hash.h" #include "zend_file_cache.h" #include "ext/pcre/php_pcre.h" #include "ext/standard/md5.h" #include "ext/hash/php_hash.h" #ifdef HAVE_JIT # include "jit/zend_jit.h" #endif #ifndef ZEND_WIN32 #include <netdb.h> #endif #ifdef ZEND_WIN32 typedef int uid_t; typedef int gid_t; #include <io.h> #include <lmcons.h> #endif #ifndef ZEND_WIN32 # include <sys/time.h> #else # include <process.h> #endif #ifdef HAVE_UNISTD_H # include <unistd.h> #endif #include <fcntl.h> #include <signal.h> #include <time.h> #ifndef ZEND_WIN32 # include <sys/types.h> # include <sys/wait.h> # include <sys/ipc.h> # include <pwd.h> # include <grp.h> #endif #include <sys/stat.h> #include <errno.h> #ifdef __AVX__ #include <immintrin.h> #endif ZEND_EXTENSION(); #ifndef ZTS zend_accel_globals accel_globals; #else int accel_globals_id; #if defined(COMPILE_DL_OPCACHE) ZEND_TSRMLS_CACHE_DEFINE() #endif #endif /* Points to the structure shared across all PHP processes */ zend_accel_shared_globals *accel_shared_globals = NULL; /* true globals, no need for thread safety */ #ifdef ZEND_WIN32 char accel_uname_id[32]; #endif bool accel_startup_ok = 0; static char *zps_failure_reason = NULL; char *zps_api_failure_reason = NULL; bool file_cache_only = 0; /* process uses file cache only */ #if ENABLE_FILE_CACHE_FALLBACK bool fallback_process = 0; /* process uses file cache fallback */ #endif static zend_op_array *(*accelerator_orig_compile_file)(zend_file_handle *file_handle, int type); static zend_class_entry* (*accelerator_orig_inheritance_cache_get)(zend_class_entry *ce, zend_class_entry *parent, zend_class_entry **traits_and_interfaces); static zend_class_entry* (*accelerator_orig_inheritance_cache_add)(zend_class_entry *ce, zend_class_entry *proto, zend_class_entry *parent, zend_class_entry **traits_and_interfaces, HashTable *dependencies); static zend_result (*accelerator_orig_zend_stream_open_function)(zend_file_handle *handle ); static zend_string *(*accelerator_orig_zend_resolve_path)(zend_string *filename); static zif_handler orig_chdir = NULL; static ZEND_INI_MH((*orig_include_path_on_modify)) = NULL; static zend_result (*orig_post_startup_cb)(void); static zend_result accel_post_startup(void); static int accel_finish_startup(void); static void preload_shutdown(void); static void preload_activate(void); static void preload_restart(void); #ifdef ZEND_WIN32 # define INCREMENT(v) InterlockedIncrement64(&ZCSG(v)) # define DECREMENT(v) InterlockedDecrement64(&ZCSG(v)) # define LOCKVAL(v) (ZCSG(v)) #endif #ifdef ZEND_WIN32 static time_t zend_accel_get_time(void) { FILETIME now; GetSystemTimeAsFileTime(&now); return (time_t) ((((((__int64)now.dwHighDateTime) << 32)|now.dwLowDateTime) - 116444736000000000L)/10000000); } #else # define zend_accel_get_time() time(NULL) #endif static inline int is_stream_path(const char *filename) { const char *p; for (p = filename; (*p >= 'a' && *p <= 'z') || (*p >= 'A' && *p <= 'Z') || (*p >= '0' && *p <= '9') || *p == '+' || *p == '-' || *p == '.'; p++); return ((p != filename) && (p[0] == ':') && (p[1] == '/') && (p[2] == '/')); } static inline int is_cacheable_stream_path(const char *filename) { return memcmp(filename, "file://", sizeof("file://") - 1) == 0 || memcmp(filename, "phar://", sizeof("phar://") - 1) == 0; } /* O+ overrides PHP chdir() function and remembers the current working directory * in ZCG(cwd) and ZCG(cwd_len). Later accel_getcwd() can use stored value and * avoid getcwd() call. */ static ZEND_FUNCTION(accel_chdir) { char cwd[MAXPATHLEN]; orig_chdir(INTERNAL_FUNCTION_PARAM_PASSTHRU); if (VCWD_GETCWD(cwd, MAXPATHLEN)) { if (ZCG(cwd)) { zend_string_release_ex(ZCG(cwd), 0); } ZCG(cwd) = zend_string_init(cwd, strlen(cwd), 0); } else { if (ZCG(cwd)) { zend_string_release_ex(ZCG(cwd), 0); ZCG(cwd) = NULL; } } ZCG(cwd_key_len) = 0; ZCG(cwd_check) = 1; } static inline zend_string* accel_getcwd(void) { if (ZCG(cwd)) { return ZCG(cwd); } else { char cwd[MAXPATHLEN + 1]; if (!VCWD_GETCWD(cwd, MAXPATHLEN)) { return NULL; } ZCG(cwd) = zend_string_init(cwd, strlen(cwd), 0); ZCG(cwd_key_len) = 0; ZCG(cwd_check) = 1; return ZCG(cwd); } } void zend_accel_schedule_restart_if_necessary(zend_accel_restart_reason reason) { if ((((double) ZSMMG(wasted_shared_memory)) / ZCG(accel_directives).memory_consumption) >= ZCG(accel_directives).max_wasted_percentage) { zend_accel_schedule_restart(reason); } } /* O+ tracks changes of "include_path" directive. It stores all the requested * values in ZCG(include_paths) shared hash table, current value in * ZCG(include_path)/ZCG(include_path_len) and one letter "path key" in * ZCG(include_path_key). */ static ZEND_INI_MH(accel_include_path_on_modify) { int ret = orig_include_path_on_modify(entry, new_value, mh_arg1, mh_arg2, mh_arg3, stage); if (ret == SUCCESS) { ZCG(include_path) = new_value; ZCG(include_path_key_len) = 0; ZCG(include_path_check) = 1; } return ret; } static inline void accel_restart_enter(void) { #ifdef ZEND_WIN32 INCREMENT(restart_in); #else struct flock restart_in_progress; restart_in_progress.l_type = F_WRLCK; restart_in_progress.l_whence = SEEK_SET; restart_in_progress.l_start = 2; restart_in_progress.l_len = 1; if (fcntl(lock_file, F_SETLK, &restart_in_progress) == -1) { zend_accel_error(ACCEL_LOG_DEBUG, "RestartC(+1): %s (%d)", strerror(errno), errno); } #endif ZCSG(restart_in_progress) = 1; } static inline void accel_restart_leave(void) { #ifdef ZEND_WIN32 ZCSG(restart_in_progress) = 0; DECREMENT(restart_in); #else struct flock restart_finished; restart_finished.l_type = F_UNLCK; restart_finished.l_whence = SEEK_SET; restart_finished.l_start = 2; restart_finished.l_len = 1; ZCSG(restart_in_progress) = 0; if (fcntl(lock_file, F_SETLK, &restart_finished) == -1) { zend_accel_error(ACCEL_LOG_DEBUG, "RestartC(-1): %s (%d)", strerror(errno), errno); } #endif } static inline int accel_restart_is_active(void) { if (ZCSG(restart_in_progress)) { #ifndef ZEND_WIN32 struct flock restart_check; restart_check.l_type = F_WRLCK; restart_check.l_whence = SEEK_SET; restart_check.l_start = 2; restart_check.l_len = 1; if (fcntl(lock_file, F_GETLK, &restart_check) == -1) { zend_accel_error(ACCEL_LOG_DEBUG, "RestartC: %s (%d)", strerror(errno), errno); return FAILURE; } if (restart_check.l_type == F_UNLCK) { ZCSG(restart_in_progress) = 0; return 0; } else { return 1; } #else return LOCKVAL(restart_in) != 0; #endif } return 0; } /* Creates a read lock for SHM access */ static inline zend_result accel_activate_add(void) { #ifdef ZEND_WIN32 SHM_UNPROTECT(); INCREMENT(mem_usage); SHM_PROTECT(); #else struct flock mem_usage_lock; mem_usage_lock.l_type = F_RDLCK; mem_usage_lock.l_whence = SEEK_SET; mem_usage_lock.l_start = 1; mem_usage_lock.l_len = 1; if (fcntl(lock_file, F_SETLK, &mem_usage_lock) == -1) { zend_accel_error(ACCEL_LOG_DEBUG, "UpdateC(+1): %s (%d)", strerror(errno), errno); return FAILURE; } #endif return SUCCESS; } /* Releases a lock for SHM access */ static inline void accel_deactivate_sub(void) { #ifdef ZEND_WIN32 if (ZCG(counted)) { SHM_UNPROTECT(); DECREMENT(mem_usage); ZCG(counted) = 0; SHM_PROTECT(); } #else struct flock mem_usage_unlock; mem_usage_unlock.l_type = F_UNLCK; mem_usage_unlock.l_whence = SEEK_SET; mem_usage_unlock.l_start = 1; mem_usage_unlock.l_len = 1; if (fcntl(lock_file, F_SETLK, &mem_usage_unlock) == -1) { zend_accel_error(ACCEL_LOG_DEBUG, "UpdateC(-1): %s (%d)", strerror(errno), errno); } #endif } static inline void accel_unlock_all(void) { #ifdef ZEND_WIN32 accel_deactivate_sub(); #else struct flock mem_usage_unlock_all; mem_usage_unlock_all.l_type = F_UNLCK; mem_usage_unlock_all.l_whence = SEEK_SET; mem_usage_unlock_all.l_start = 0; mem_usage_unlock_all.l_len = 0; if (fcntl(lock_file, F_SETLK, &mem_usage_unlock_all) == -1) { zend_accel_error(ACCEL_LOG_DEBUG, "UnlockAll: %s (%d)", strerror(errno), errno); } #endif } /* Interned strings support */ /* O+ disables creation of interned strings by regular PHP compiler, instead, * it creates interned strings in shared memory when saves a script. * Such interned strings are shared across all PHP processes */ #define STRTAB_INVALID_POS 0 #define STRTAB_HASH_TO_SLOT(tab, h) \ ((uint32_t*)((char*)(tab) + sizeof(*(tab)) + ((h) & (tab)->nTableMask))) #define STRTAB_STR_TO_POS(tab, s) \ ((uint32_t)((char*)s - (char*)(tab))) #define STRTAB_POS_TO_STR(tab, pos) \ ((zend_string*)((char*)(tab) + (pos))) #define STRTAB_COLLISION(s) \ (*((uint32_t*)((char*)s - sizeof(uint32_t)))) #define STRTAB_STR_SIZE(s) \ ZEND_MM_ALIGNED_SIZE_EX(_ZSTR_HEADER_SIZE + ZSTR_LEN(s) + 5, 8) #define STRTAB_NEXT(s) \ ((zend_string*)((char*)(s) + STRTAB_STR_SIZE(s))) static void accel_interned_strings_restore_state(void) { zend_string *s, *top; uint32_t *hash_slot, n; /* clear removed content */ memset(ZCSG(interned_strings).saved_top, 0, (char*)ZCSG(interned_strings).top - (char*)ZCSG(interned_strings).saved_top); /* Reset "top" */ ZCSG(interned_strings).top = ZCSG(interned_strings).saved_top; /* rehash */ memset((char*)&ZCSG(interned_strings) + sizeof(zend_string_table), STRTAB_INVALID_POS, (char*)ZCSG(interned_strings).start - ((char*)&ZCSG(interned_strings) + sizeof(zend_string_table))); s = ZCSG(interned_strings).start; top = ZCSG(interned_strings).top; n = 0; if (EXPECTED(s < top)) { do { hash_slot = STRTAB_HASH_TO_SLOT(&ZCSG(interned_strings), ZSTR_H(s)); STRTAB_COLLISION(s) = *hash_slot; *hash_slot = STRTAB_STR_TO_POS(&ZCSG(interned_strings), s); s = STRTAB_NEXT(s); n++; } while (s < top); } ZCSG(interned_strings).nNumOfElements = n; } static void accel_interned_strings_save_state(void) { ZCSG(interned_strings).saved_top = ZCSG(interned_strings).top; } static zend_always_inline zend_string *accel_find_interned_string(zend_string *str) { zend_ulong h; uint32_t pos; zend_string *s; if (IS_ACCEL_INTERNED(str)) { /* this is already an interned string */ return str; } if (!ZCG(counted)) { if (!ZCG(accelerator_enabled) || accel_activate_add() == FAILURE) { return NULL; } ZCG(counted) = 1; } h = zend_string_hash_val(str); /* check for existing interned string */ pos = *STRTAB_HASH_TO_SLOT(&ZCSG(interned_strings), h); if (EXPECTED(pos != STRTAB_INVALID_POS)) { do { s = STRTAB_POS_TO_STR(&ZCSG(interned_strings), pos); if (EXPECTED(ZSTR_H(s) == h) && zend_string_equal_content(s, str)) { return s; } pos = STRTAB_COLLISION(s); } while (pos != STRTAB_INVALID_POS); } return NULL; } zend_string* ZEND_FASTCALL accel_new_interned_string(zend_string *str) { zend_ulong h; uint32_t pos, *hash_slot; zend_string *s; if (UNEXPECTED(file_cache_only)) { return str; } if (IS_ACCEL_INTERNED(str)) { /* this is already an interned string */ return str; } h = zend_string_hash_val(str); /* check for existing interned string */ hash_slot = STRTAB_HASH_TO_SLOT(&ZCSG(interned_strings), h); pos = *hash_slot; if (EXPECTED(pos != STRTAB_INVALID_POS)) { do { s = STRTAB_POS_TO_STR(&ZCSG(interned_strings), pos); if (EXPECTED(ZSTR_H(s) == h) && zend_string_equal_content(s, str)) { zend_string_release(str); return s; } pos = STRTAB_COLLISION(s); } while (pos != STRTAB_INVALID_POS); } if (UNEXPECTED((char*)ZCSG(interned_strings).end - (char*)ZCSG(interned_strings).top < STRTAB_STR_SIZE(str))) { /* no memory, return the same non-interned string */ zend_accel_error(ACCEL_LOG_WARNING, "Interned string buffer overflow"); return str; } /* create new interning string in shared interned strings buffer */ ZCSG(interned_strings).nNumOfElements++; s = ZCSG(interned_strings).top; hash_slot = STRTAB_HASH_TO_SLOT(&ZCSG(interned_strings), h); STRTAB_COLLISION(s) = *hash_slot; *hash_slot = STRTAB_STR_TO_POS(&ZCSG(interned_strings), s); GC_SET_REFCOUNT(s, 2); GC_TYPE_INFO(s) = GC_STRING | ((IS_STR_INTERNED | IS_STR_PERMANENT) << GC_FLAGS_SHIFT); ZSTR_H(s) = h; ZSTR_LEN(s) = ZSTR_LEN(str); memcpy(ZSTR_VAL(s), ZSTR_VAL(str), ZSTR_LEN(s) + 1); ZCSG(interned_strings).top = STRTAB_NEXT(s); zend_string_release(str); return s; } static zend_string* ZEND_FASTCALL accel_new_interned_string_for_php(zend_string *str) { zend_string_hash_val(str); if (ZCG(counted)) { zend_string *ret = accel_find_interned_string(str); if (ret) { zend_string_release(str); return ret; } } return str; } static zend_always_inline zend_string *accel_find_interned_string_ex(zend_ulong h, const char *str, size_t size) { uint32_t pos; zend_string *s; /* check for existing interned string */ pos = *STRTAB_HASH_TO_SLOT(&ZCSG(interned_strings), h); if (EXPECTED(pos != STRTAB_INVALID_POS)) { do { s = STRTAB_POS_TO_STR(&ZCSG(interned_strings), pos); if (EXPECTED(ZSTR_H(s) == h) && EXPECTED(ZSTR_LEN(s) == size)) { if (!memcmp(ZSTR_VAL(s), str, size)) { return s; } } pos = STRTAB_COLLISION(s); } while (pos != STRTAB_INVALID_POS); } return NULL; } static zend_string* ZEND_FASTCALL accel_init_interned_string_for_php(const char *str, size_t size, bool permanent) { if (ZCG(counted)) { zend_ulong h = zend_inline_hash_func(str, size); zend_string *ret = accel_find_interned_string_ex(h, str, size); if (!ret) { ret = zend_string_init(str, size, permanent); ZSTR_H(ret) = h; } return ret; } return zend_string_init(str, size, permanent); } /* Copy PHP interned strings from PHP process memory into the shared memory */ static void accel_copy_permanent_strings(zend_new_interned_string_func_t new_interned_string) { uint32_t j; Bucket *p, *q; HashTable *ht; /* empty string */ zend_empty_string = new_interned_string(zend_empty_string); for (j = 0; j < 256; j++) { zend_one_char_string[j] = new_interned_string(ZSTR_CHAR(j)); } for (j = 0; j < ZEND_STR_LAST_KNOWN; j++) { zend_known_strings[j] = new_interned_string(zend_known_strings[j]); } /* function table hash keys */ ZEND_HASH_FOREACH_BUCKET(CG(function_table), p) { if (p->key) { p->key = new_interned_string(p->key); } if (Z_FUNC(p->val)->common.function_name) { Z_FUNC(p->val)->common.function_name = new_interned_string(Z_FUNC(p->val)->common.function_name); } if (Z_FUNC(p->val)->common.arg_info && (Z_FUNC(p->val)->common.fn_flags & (ZEND_ACC_HAS_RETURN_TYPE|ZEND_ACC_HAS_TYPE_HINTS))) { uint32_t i; uint32_t num_args = Z_FUNC(p->val)->common.num_args + 1; zend_arg_info *arg_info = Z_FUNC(p->val)->common.arg_info - 1; if (Z_FUNC(p->val)->common.fn_flags & ZEND_ACC_VARIADIC) { num_args++; } for (i = 0 ; i < num_args; i++) { zend_type *single_type; ZEND_TYPE_FOREACH(arg_info[i].type, single_type) { if (ZEND_TYPE_HAS_NAME(*single_type)) { ZEND_TYPE_SET_PTR(*single_type, new_interned_string(ZEND_TYPE_NAME(*single_type))); } } ZEND_TYPE_FOREACH_END(); } } } ZEND_HASH_FOREACH_END(); /* class table hash keys, class names, properties, methods, constants, etc */ ZEND_HASH_FOREACH_BUCKET(CG(class_table), p) { zend_class_entry *ce; ce = (zend_class_entry*)Z_PTR(p->val); if (p->key) { p->key = new_interned_string(p->key); } if (ce->name) { ce->name = new_interned_string(ce->name); } ZEND_HASH_FOREACH_BUCKET(&ce->properties_info, q) { zend_property_info *info; info = (zend_property_info*)Z_PTR(q->val); if (q->key) { q->key = new_interned_string(q->key); } if (info->name) { info->name = new_interned_string(info->name); } } ZEND_HASH_FOREACH_END(); ZEND_HASH_FOREACH_BUCKET(&ce->function_table, q) { if (q->key) { q->key = new_interned_string(q->key); } if (Z_FUNC(q->val)->common.function_name) { Z_FUNC(q->val)->common.function_name = new_interned_string(Z_FUNC(q->val)->common.function_name); } } ZEND_HASH_FOREACH_END(); ZEND_HASH_FOREACH_BUCKET(&ce->constants_table, q) { if (q->key) { q->key = new_interned_string(q->key); } } ZEND_HASH_FOREACH_END(); } ZEND_HASH_FOREACH_END(); /* constant hash keys */ ZEND_HASH_FOREACH_BUCKET(EG(zend_constants), p) { zend_constant *c; if (p->key) { p->key = new_interned_string(p->key); } c = (zend_constant*)Z_PTR(p->val); if (c->name) { c->name = new_interned_string(c->name); } if (Z_TYPE(c->value) == IS_STRING) { ZVAL_STR(&c->value, new_interned_string(Z_STR(c->value))); } } ZEND_HASH_FOREACH_END(); /* auto globals hash keys and names */ ZEND_HASH_FOREACH_BUCKET(CG(auto_globals), p) { zend_auto_global *auto_global; auto_global = (zend_auto_global*)Z_PTR(p->val); zend_string_addref(auto_global->name); auto_global->name = new_interned_string(auto_global->name); if (p->key) { p->key = new_interned_string(p->key); } } ZEND_HASH_FOREACH_END(); ZEND_HASH_FOREACH_BUCKET(&module_registry, p) { if (p->key) { p->key = new_interned_string(p->key); } } ZEND_HASH_FOREACH_END(); ZEND_HASH_FOREACH_BUCKET(EG(ini_directives), p) { zend_ini_entry *entry = (zend_ini_entry*)Z_PTR(p->val); if (p->key) { p->key = new_interned_string(p->key); } if (entry->name) { entry->name = new_interned_string(entry->name); } if (entry->value) { entry->value = new_interned_string(entry->value); } if (entry->orig_value) { entry->orig_value = new_interned_string(entry->orig_value); } } ZEND_HASH_FOREACH_END(); ht = php_get_stream_filters_hash_global(); ZEND_HASH_FOREACH_BUCKET(ht, p) { if (p->key) { p->key = new_interned_string(p->key); } } ZEND_HASH_FOREACH_END(); ht = php_stream_get_url_stream_wrappers_hash_global(); ZEND_HASH_FOREACH_BUCKET(ht, p) { if (p->key) { p->key = new_interned_string(p->key); } } ZEND_HASH_FOREACH_END(); ht = php_stream_xport_get_hash(); ZEND_HASH_FOREACH_BUCKET(ht, p) { if (p->key) { p->key = new_interned_string(p->key); } } ZEND_HASH_FOREACH_END(); } static zend_string* ZEND_FASTCALL accel_replace_string_by_shm_permanent(zend_string *str) { zend_string *ret = accel_find_interned_string(str); if (ret) { zend_string_release(str); return ret; } return str; } static void accel_allocate_ce_cache_slots(void) { Bucket *p; ZEND_HASH_FOREACH_BUCKET(CG(class_table), p) { zend_class_entry *ce; ce = (zend_class_entry*)Z_PTR(p->val); if (ce->name) { zend_accel_get_class_name_map_ptr(ce->name, ce, /* have_xlat */ false); } } ZEND_HASH_FOREACH_END(); } static void accel_use_shm_interned_strings(void) { HANDLE_BLOCK_INTERRUPTIONS(); SHM_UNPROTECT(); zend_shared_alloc_lock(); if (ZCSG(interned_strings).saved_top == NULL) { accel_copy_permanent_strings(accel_new_interned_string); accel_allocate_ce_cache_slots(); } else { ZCG(counted) = 1; accel_copy_permanent_strings(accel_replace_string_by_shm_permanent); ZCG(counted) = 0; } accel_interned_strings_save_state(); zend_shared_alloc_unlock(); SHM_PROTECT(); HANDLE_UNBLOCK_INTERRUPTIONS(); } #ifndef ZEND_WIN32 static inline void kill_all_lockers(struct flock *mem_usage_check) { int success, tries; /* so that other process won't try to force while we are busy cleaning up */ ZCSG(force_restart_time) = 0; while (mem_usage_check->l_pid > 0) { /* Try SIGTERM first, switch to SIGKILL if not successful. */ int signal = SIGTERM; errno = 0; success = 0; tries = 10; while (tries--) { zend_accel_error(ACCEL_LOG_WARNING, "Attempting to kill locker %d", mem_usage_check->l_pid); if (kill(mem_usage_check->l_pid, signal)) { if (errno == ESRCH) { /* Process died before the signal was sent */ success = 1; zend_accel_error(ACCEL_LOG_WARNING, "Process %d died before SIGKILL was sent", mem_usage_check->l_pid); } else if (errno != 0) { zend_accel_error(ACCEL_LOG_WARNING, "Failed to send SIGKILL to locker %d: %s", mem_usage_check->l_pid, strerror(errno)); } break; } /* give it a chance to die */ usleep(20000); if (kill(mem_usage_check->l_pid, 0)) { if (errno == ESRCH) { /* successfully killed locker, process no longer exists */ success = 1; zend_accel_error(ACCEL_LOG_WARNING, "Killed locker %d", mem_usage_check->l_pid); } else if (errno != 0) { zend_accel_error(ACCEL_LOG_WARNING, "Failed to check locker %d: %s", mem_usage_check->l_pid, strerror(errno)); } break; } usleep(10000); /* If SIGTERM was not sufficient, use SIGKILL. */ signal = SIGKILL; } if (!success) { /* errno is not ESRCH or we ran out of tries to kill the locker */ ZCSG(force_restart_time) = time(NULL); /* restore forced restart request */ /* cannot kill the locker, bail out with error */ zend_accel_error_noreturn(ACCEL_LOG_ERROR, "Cannot kill process %d!", mem_usage_check->l_pid); } mem_usage_check->l_type = F_WRLCK; mem_usage_check->l_whence = SEEK_SET; mem_usage_check->l_start = 1; mem_usage_check->l_len = 1; mem_usage_check->l_pid = -1; if (fcntl(lock_file, F_GETLK, mem_usage_check) == -1) { zend_accel_error(ACCEL_LOG_DEBUG, "KLockers: %s (%d)", strerror(errno), errno); break; } if (mem_usage_check->l_type == F_UNLCK || mem_usage_check->l_pid <= 0) { break; } } } #endif static inline int accel_is_inactive(void) { #ifdef ZEND_WIN32 if (LOCKVAL(mem_usage) == 0) { return SUCCESS; } #else struct flock mem_usage_check; mem_usage_check.l_type = F_WRLCK; mem_usage_check.l_whence = SEEK_SET; mem_usage_check.l_start = 1; mem_usage_check.l_len = 1; mem_usage_check.l_pid = -1; if (fcntl(lock_file, F_GETLK, &mem_usage_check) == -1) { zend_accel_error(ACCEL_LOG_DEBUG, "UpdateC: %s (%d)", strerror(errno), errno); return FAILURE; } if (mem_usage_check.l_type == F_UNLCK) { return SUCCESS; } if (ZCG(accel_directives).force_restart_timeout && ZCSG(force_restart_time) && time(NULL) >= ZCSG(force_restart_time)) { zend_accel_error(ACCEL_LOG_WARNING, "Forced restart at %ld (after " ZEND_LONG_FMT " seconds), locked by %d", (long)time(NULL), ZCG(accel_directives).force_restart_timeout, mem_usage_check.l_pid); kill_all_lockers(&mem_usage_check); return FAILURE; /* next request should be able to restart it */ } #endif return FAILURE; } static int zend_get_stream_timestamp(const char *filename, zend_stat_t *statbuf) { php_stream_wrapper *wrapper; php_stream_statbuf stream_statbuf; int ret, er; if (!filename) { return FAILURE; } wrapper = php_stream_locate_url_wrapper(filename, NULL, STREAM_LOCATE_WRAPPERS_ONLY); if (!wrapper) { return FAILURE; } if (!wrapper->wops || !wrapper->wops->url_stat) { statbuf->st_mtime = 1; return SUCCESS; /* anything other than 0 is considered to be a valid timestamp */ } er = EG(error_reporting); EG(error_reporting) = 0; zend_try { ret = wrapper->wops->url_stat(wrapper, (char*)filename, PHP_STREAM_URL_STAT_QUIET, &stream_statbuf, NULL); } zend_catch { ret = -1; } zend_end_try(); EG(error_reporting) = er; if (ret != 0) { return FAILURE; } *statbuf = stream_statbuf.sb; return SUCCESS; } #if ZEND_WIN32 static accel_time_t zend_get_file_handle_timestamp_win(zend_file_handle *file_handle, size_t *size) { static unsigned __int64 utc_base = 0; static FILETIME utc_base_ft; WIN32_FILE_ATTRIBUTE_DATA fdata; if (!file_handle->opened_path) { return 0; } if (!utc_base) { SYSTEMTIME st; st.wYear = 1970; st.wMonth = 1; st.wDay = 1; st.wHour = 0; st.wMinute = 0; st.wSecond = 0; st.wMilliseconds = 0; SystemTimeToFileTime (&st, &utc_base_ft); utc_base = (((unsigned __int64)utc_base_ft.dwHighDateTime) << 32) + utc_base_ft.dwLowDateTime; } if (file_handle->opened_path && GetFileAttributesEx(file_handle->opened_path->val, GetFileExInfoStandard, &fdata) != 0) { unsigned __int64 ftime; if (CompareFileTime (&fdata.ftLastWriteTime, &utc_base_ft) < 0) { return 0; } ftime = (((unsigned __int64)fdata.ftLastWriteTime.dwHighDateTime) << 32) + fdata.ftLastWriteTime.dwLowDateTime - utc_base; ftime /= 10000000L; if (size) { *size = (size_t)((((unsigned __int64)fdata.nFileSizeHigh) << 32) + (unsigned __int64)fdata.nFileSizeLow); } return (accel_time_t)ftime; } return 0; } #endif accel_time_t zend_get_file_handle_timestamp(zend_file_handle *file_handle, size_t *size) { zend_stat_t statbuf; #ifdef ZEND_WIN32 accel_time_t res; #endif if (sapi_module.get_stat && !EG(current_execute_data) && file_handle->primary_script) { zend_stat_t *tmpbuf = sapi_module.get_stat(); if (tmpbuf) { if (size) { *size = tmpbuf->st_size; } return tmpbuf->st_mtime; } } #ifdef ZEND_WIN32 res = zend_get_file_handle_timestamp_win(file_handle, size); if (res) { return res; } #endif switch (file_handle->type) { case ZEND_HANDLE_FP: if (zend_fstat(fileno(file_handle->handle.fp), &statbuf) == -1) { if (zend_get_stream_timestamp(ZSTR_VAL(file_handle->filename), &statbuf) != SUCCESS) { return 0; } } break; case ZEND_HANDLE_FILENAME: if (file_handle->opened_path) { char *file_path = ZSTR_VAL(file_handle->opened_path); if (is_stream_path(file_path)) { if (zend_get_stream_timestamp(file_path, &statbuf) == SUCCESS) { break; } } if (VCWD_STAT(file_path, &statbuf) != -1) { break; } } if (zend_get_stream_timestamp(ZSTR_VAL(file_handle->filename), &statbuf) != SUCCESS) { return 0; } break; case ZEND_HANDLE_STREAM: { php_stream *stream = (php_stream *)file_handle->handle.stream.handle; php_stream_statbuf sb; int ret, er; if (!stream || !stream->ops || !stream->ops->stat) { return 0; } er = EG(error_reporting); EG(error_reporting) = 0; zend_try { ret = stream->ops->stat(stream, &sb); } zend_catch { ret = -1; } zend_end_try(); EG(error_reporting) = er; if (ret != 0) { return 0; } statbuf = sb.sb; } break; default: return 0; } if (size) { *size = statbuf.st_size; } return statbuf.st_mtime; } static inline int do_validate_timestamps(zend_persistent_script *persistent_script, zend_file_handle *file_handle) { zend_file_handle ps_handle; zend_string *full_path_ptr = NULL; int ret; /** check that the persistent script is indeed the same file we cached * (if part of the path is a symlink than it possible that the user will change it) * See bug #15140 */ if (file_handle->opened_path) { if (persistent_script->script.filename != file_handle->opened_path && !zend_string_equal_content(persistent_script->script.filename, file_handle->opened_path)) { return FAILURE; } } else { full_path_ptr = accelerator_orig_zend_resolve_path(file_handle->filename); if (full_path_ptr && persistent_script->script.filename != full_path_ptr && !zend_string_equal_content(persistent_script->script.filename, full_path_ptr)) { zend_string_release_ex(full_path_ptr, 0); return FAILURE; } file_handle->opened_path = full_path_ptr; } if (persistent_script->timestamp == 0) { if (full_path_ptr) { zend_string_release_ex(full_path_ptr, 0); file_handle->opened_path = NULL; } return FAILURE; } if (zend_get_file_handle_timestamp(file_handle, NULL) == persistent_script->timestamp) { if (full_path_ptr) { zend_string_release_ex(full_path_ptr, 0); file_handle->opened_path = NULL; } return SUCCESS; } if (full_path_ptr) { zend_string_release_ex(full_path_ptr, 0); file_handle->opened_path = NULL; } zend_stream_init_filename_ex(&ps_handle, persistent_script->script.filename); ps_handle.opened_path = persistent_script->script.filename; ret = zend_get_file_handle_timestamp(&ps_handle, NULL) == persistent_script->timestamp ? SUCCESS : FAILURE; zend_destroy_file_handle(&ps_handle); return ret; } int validate_timestamp_and_record(zend_persistent_script *persistent_script, zend_file_handle *file_handle) { if (persistent_script->timestamp == 0) { return SUCCESS; /* Don't check timestamps of preloaded scripts */ } else if (ZCG(accel_directives).revalidate_freq && persistent_script->dynamic_members.revalidate >= ZCG(request_time)) { return SUCCESS; } else if (do_validate_timestamps(persistent_script, file_handle) == FAILURE) { return FAILURE; } else { persistent_script->dynamic_members.revalidate = ZCG(request_time) + ZCG(accel_directives).revalidate_freq; return SUCCESS; } } int validate_timestamp_and_record_ex(zend_persistent_script *persistent_script, zend_file_handle *file_handle) { int ret; SHM_UNPROTECT(); ret = validate_timestamp_and_record(persistent_script, file_handle); SHM_PROTECT(); return ret; } /* Instead of resolving full real path name each time we need to identify file, * we create a key that consist from requested file name, current working * directory, current include_path, etc */ zend_string *accel_make_persistent_key(zend_string *str) { const char *path = ZSTR_VAL(str); size_t path_length = ZSTR_LEN(str); char *key; int key_length; ZSTR_LEN(&ZCG(key)) = 0; /* CWD and include_path don't matter for absolute file names and streams */ if (IS_ABSOLUTE_PATH(path, path_length)) { /* pass */ } else if (UNEXPECTED(is_stream_path(path))) { if (!is_cacheable_stream_path(path)) { return NULL; } /* pass */ } else if (UNEXPECTED(!ZCG(accel_directives).use_cwd)) { /* pass */ } else { const char *include_path = NULL, *cwd = NULL; int include_path_len = 0, cwd_len = 0; zend_string *parent_script = NULL; size_t parent_script_len = 0; if (EXPECTED(ZCG(cwd_key_len))) { cwd = ZCG(cwd_key); cwd_len = ZCG(cwd_key_len); } else { zend_string *cwd_str = accel_getcwd(); if (UNEXPECTED(!cwd_str)) { /* we don't handle this well for now. */ zend_accel_error(ACCEL_LOG_INFO, "getcwd() failed for '%s' (%d), please try to set opcache.use_cwd to 0 in ini file", path, errno); return NULL; } cwd = ZSTR_VAL(cwd_str); cwd_len = ZSTR_LEN(cwd_str); if (ZCG(cwd_check)) { ZCG(cwd_check) = 0; if (ZCG(accelerator_enabled)) { zend_string *str = accel_find_interned_string(cwd_str); if (!str) { HANDLE_BLOCK_INTERRUPTIONS(); SHM_UNPROTECT(); zend_shared_alloc_lock(); str = accel_new_interned_string(zend_string_copy(cwd_str)); if (str == cwd_str) { zend_string_release_ex(str, 0); str = NULL; } zend_shared_alloc_unlock(); SHM_PROTECT(); HANDLE_UNBLOCK_INTERRUPTIONS(); } if (str) { char buf[32]; char *res = zend_print_long_to_buf(buf + sizeof(buf) - 1, STRTAB_STR_TO_POS(&ZCSG(interned_strings), str)); cwd_len = ZCG(cwd_key_len) = buf + sizeof(buf) - 1 - res; cwd = ZCG(cwd_key); memcpy(ZCG(cwd_key), res, cwd_len + 1); } else { return NULL; } } else { return NULL; } } } if (EXPECTED(ZCG(include_path_key_len))) { include_path = ZCG(include_path_key); include_path_len = ZCG(include_path_key_len); } else if (!ZCG(include_path) || ZSTR_LEN(ZCG(include_path)) == 0) { include_path = ""; include_path_len = 0; } else { include_path = ZSTR_VAL(ZCG(include_path)); include_path_len = ZSTR_LEN(ZCG(include_path)); if (ZCG(include_path_check)) { ZCG(include_path_check) = 0; if (ZCG(accelerator_enabled)) { zend_string *str = accel_find_interned_string(ZCG(include_path)); if (!str) { HANDLE_BLOCK_INTERRUPTIONS(); SHM_UNPROTECT(); zend_shared_alloc_lock(); str = accel_new_interned_string(zend_string_copy(ZCG(include_path))); if (str == ZCG(include_path)) { zend_string_release(str); str = NULL; } zend_shared_alloc_unlock(); SHM_PROTECT(); HANDLE_UNBLOCK_INTERRUPTIONS(); } if (str) { char buf[32]; char *res = zend_print_long_to_buf(buf + sizeof(buf) - 1, STRTAB_STR_TO_POS(&ZCSG(interned_strings), str)); include_path_len = ZCG(include_path_key_len) = buf + sizeof(buf) - 1 - res; include_path = ZCG(include_path_key); memcpy(ZCG(include_path_key), res, include_path_len + 1); } else { return NULL; } } else { return NULL; } } } /* Calculate key length */ if (UNEXPECTED((size_t)(cwd_len + path_length + include_path_len + 2) >= sizeof(ZCG(_key)))) { return NULL; } /* Generate key * Note - the include_path must be the last element in the key, * since in itself, it may include colons (which we use to separate * different components of the key) */ key = ZSTR_VAL(&ZCG(key)); memcpy(key, path, path_length); key[path_length] = ':'; key_length = path_length + 1; memcpy(key + key_length, cwd, cwd_len); key_length += cwd_len; if (include_path_len) { key[key_length] = ':'; key_length += 1; memcpy(key + key_length, include_path, include_path_len); key_length += include_path_len; } /* Here we add to the key the parent script directory, * since fopen_wrappers from version 4.0.7 use current script's path * in include path too. */ if (EXPECTED(EG(current_execute_data)) && EXPECTED((parent_script = zend_get_executed_filename_ex()) != NULL)) { parent_script_len = ZSTR_LEN(parent_script); while ((--parent_script_len > 0) && !IS_SLASH(ZSTR_VAL(parent_script)[parent_script_len])); if (UNEXPECTED((size_t)(key_length + parent_script_len + 1) >= sizeof(ZCG(_key)))) { return NULL; } key[key_length] = ':'; key_length += 1; memcpy(key + key_length, ZSTR_VAL(parent_script), parent_script_len); key_length += parent_script_len; } key[key_length] = '\0'; GC_SET_REFCOUNT(&ZCG(key), 1); GC_TYPE_INFO(&ZCG(key)) = GC_STRING; ZSTR_H(&ZCG(key)) = 0; ZSTR_LEN(&ZCG(key)) = key_length; return &ZCG(key); } /* not use_cwd */ return str; } int zend_accel_invalidate(zend_string *filename, bool force) { zend_string *realpath; zend_persistent_script *persistent_script; if (!ZCG(accelerator_enabled) || accelerator_shm_read_lock() != SUCCESS) { return FAILURE; } realpath = accelerator_orig_zend_resolve_path(filename); if (!realpath) { return FAILURE; } if (ZCG(accel_directives).file_cache) { zend_file_cache_invalidate(realpath); } persistent_script = zend_accel_hash_find(&ZCSG(hash), realpath); if (persistent_script && !persistent_script->corrupted) { zend_file_handle file_handle; zend_stream_init_filename_ex(&file_handle, realpath); file_handle.opened_path = realpath; if (force || !ZCG(accel_directives).validate_timestamps || do_validate_timestamps(persistent_script, &file_handle) == FAILURE) { HANDLE_BLOCK_INTERRUPTIONS(); SHM_UNPROTECT(); zend_shared_alloc_lock(); if (!persistent_script->corrupted) { persistent_script->corrupted = 1; persistent_script->timestamp = 0; ZSMMG(wasted_shared_memory) += persistent_script->dynamic_members.memory_consumption; if (ZSMMG(memory_exhausted)) { zend_accel_restart_reason reason = zend_accel_hash_is_full(&ZCSG(hash)) ? ACCEL_RESTART_HASH : ACCEL_RESTART_OOM; zend_accel_schedule_restart_if_necessary(reason); } } zend_shared_alloc_unlock(); SHM_PROTECT(); HANDLE_UNBLOCK_INTERRUPTIONS(); } file_handle.opened_path = NULL; zend_destroy_file_handle(&file_handle); } accelerator_shm_read_unlock(); zend_string_release_ex(realpath, 0); return SUCCESS; } static zend_string* accel_new_interned_key(zend_string *key) { zend_string *new_key; if (zend_accel_in_shm(key)) { return key; } GC_ADDREF(key); new_key = accel_new_interned_string(key); if (UNEXPECTED(new_key == key)) { GC_DELREF(key); new_key = zend_shared_alloc(ZEND_MM_ALIGNED_SIZE_EX(_ZSTR_STRUCT_SIZE(ZSTR_LEN(key)), 8)); if (EXPECTED(new_key)) { GC_SET_REFCOUNT(new_key, 2); GC_TYPE_INFO(new_key) = GC_STRING | (IS_STR_INTERNED << GC_FLAGS_SHIFT); ZSTR_H(new_key) = ZSTR_H(key); ZSTR_LEN(new_key) = ZSTR_LEN(key); memcpy(ZSTR_VAL(new_key), ZSTR_VAL(key), ZSTR_LEN(new_key) + 1); } } return new_key; } /* Adds another key for existing cached script */ static void zend_accel_add_key(zend_string *key, zend_accel_hash_entry *bucket) { if (!zend_accel_hash_find(&ZCSG(hash), key)) { if (zend_accel_hash_is_full(&ZCSG(hash))) { zend_accel_error(ACCEL_LOG_DEBUG, "No more entries in hash table!"); ZSMMG(memory_exhausted) = 1; zend_accel_schedule_restart_if_necessary(ACCEL_RESTART_HASH); } else { zend_string *new_key = accel_new_interned_key(key); if (new_key) { if (zend_accel_hash_update(&ZCSG(hash), new_key, 1, bucket)) { zend_accel_error(ACCEL_LOG_INFO, "Added key '%s'", ZSTR_VAL(new_key)); } } else { zend_accel_schedule_restart_if_necessary(ACCEL_RESTART_OOM); } } } } static zend_always_inline bool is_phar_file(zend_string *filename) { return filename && ZSTR_LEN(filename) >= sizeof(".phar") && !memcmp(ZSTR_VAL(filename) + ZSTR_LEN(filename) - (sizeof(".phar")-1), ".phar", sizeof(".phar")-1) && !strstr(ZSTR_VAL(filename), "://"); } static zend_persistent_script *store_script_in_file_cache(zend_persistent_script *new_persistent_script) { uint32_t memory_used; zend_shared_alloc_init_xlat_table(); /* Calculate the required memory size */ memory_used = zend_accel_script_persist_calc(new_persistent_script, 0); /* Allocate memory block */ #if defined(__AVX__) || defined(__SSE2__) /* Align to 64-byte boundary */ ZCG(mem) = zend_arena_alloc(&CG(arena), memory_used + 64); ZCG(mem) = (void*)(((zend_uintptr_t)ZCG(mem) + 63L) & ~63L); #elif ZEND_MM_ALIGNMENT < 8 /* Align to 8-byte boundary */ ZCG(mem) = zend_arena_alloc(&CG(arena), memory_used + 8); ZCG(mem) = (void*)(((zend_uintptr_t)ZCG(mem) + 7L) & ~7L); #else ZCG(mem) = zend_arena_alloc(&CG(arena), memory_used); #endif zend_shared_alloc_clear_xlat_table(); /* Copy into memory block */ new_persistent_script = zend_accel_script_persist(new_persistent_script, 0); zend_shared_alloc_destroy_xlat_table(); new_persistent_script->is_phar = is_phar_file(new_persistent_script->script.filename); /* Consistency check */ if ((char*)new_persistent_script->mem + new_persistent_script->size != (char*)ZCG(mem)) { zend_accel_error( ((char*)new_persistent_script->mem + new_persistent_script->size < (char*)ZCG(mem)) ? ACCEL_LOG_ERROR : ACCEL_LOG_WARNING, "Internal error: wrong size calculation: %s start=" ZEND_ADDR_FMT ", end=" ZEND_ADDR_FMT ", real=" ZEND_ADDR_FMT "\n", ZSTR_VAL(new_persistent_script->script.filename), (size_t)new_persistent_script->mem, (size_t)((char *)new_persistent_script->mem + new_persistent_script->size), (size_t)ZCG(mem)); } new_persistent_script->dynamic_members.checksum = zend_accel_script_checksum(new_persistent_script); zend_file_cache_script_store(new_persistent_script, 0); return new_persistent_script; } static zend_persistent_script *cache_script_in_file_cache(zend_persistent_script *new_persistent_script, int *from_shared_memory) { uint32_t orig_compiler_options; orig_compiler_options = CG(compiler_options); CG(compiler_options) |= ZEND_COMPILE_WITH_FILE_CACHE; if (!zend_optimize_script(&new_persistent_script->script, ZCG(accel_directives).optimization_level, ZCG(accel_directives).opt_debug_level)) { CG(compiler_options) = orig_compiler_options; return new_persistent_script; } CG(compiler_options) = orig_compiler_options; *from_shared_memory = 1; return store_script_in_file_cache(new_persistent_script); } static zend_persistent_script *cache_script_in_shared_memory(zend_persistent_script *new_persistent_script, zend_string *key, int *from_shared_memory) { zend_accel_hash_entry *bucket; uint32_t memory_used; uint32_t orig_compiler_options; orig_compiler_options = CG(compiler_options); if (ZCG(accel_directives).file_cache) { CG(compiler_options) |= ZEND_COMPILE_WITH_FILE_CACHE; } if (!zend_optimize_script(&new_persistent_script->script, ZCG(accel_directives).optimization_level, ZCG(accel_directives).opt_debug_level)) { CG(compiler_options) = orig_compiler_options; return new_persistent_script; } CG(compiler_options) = orig_compiler_options; /* exclusive lock */ zend_shared_alloc_lock(); /* Check if we still need to put the file into the cache (may be it was * already stored by another process. This final check is done under * exclusive lock) */ bucket = zend_accel_hash_find_entry(&ZCSG(hash), new_persistent_script->script.filename); if (bucket) { zend_persistent_script *existing_persistent_script = (zend_persistent_script *)bucket->data; if (!existing_persistent_script->corrupted) { if (key && (!ZCG(accel_directives).validate_timestamps || (new_persistent_script->timestamp == existing_persistent_script->timestamp))) { zend_accel_add_key(key, bucket); } zend_shared_alloc_unlock(); #if 1 /* prefer the script already stored in SHM */ free_persistent_script(new_persistent_script, 1); *from_shared_memory = 1; return existing_persistent_script; #else return new_persistent_script; #endif } } if (zend_accel_hash_is_full(&ZCSG(hash))) { zend_accel_error(ACCEL_LOG_DEBUG, "No more entries in hash table!"); ZSMMG(memory_exhausted) = 1; zend_accel_schedule_restart_if_necessary(ACCEL_RESTART_HASH); zend_shared_alloc_unlock(); if (ZCG(accel_directives).file_cache) { new_persistent_script = store_script_in_file_cache(new_persistent_script); *from_shared_memory = 1; } return new_persistent_script; } zend_shared_alloc_init_xlat_table(); /* Calculate the required memory size */ memory_used = zend_accel_script_persist_calc(new_persistent_script, 1); /* Allocate shared memory */ #if defined(__AVX__) || defined(__SSE2__) /* Align to 64-byte boundary */ ZCG(mem) = zend_shared_alloc(memory_used + 64); if (ZCG(mem)) { ZCG(mem) = (void*)(((zend_uintptr_t)ZCG(mem) + 63L) & ~63L); #if defined(__x86_64__) memset(ZCG(mem), 0, memory_used); #elif defined(__AVX__) { char *p = (char*)ZCG(mem); char *end = p + memory_used; __m256i ymm0 = _mm256_setzero_si256(); while (p < end) { _mm256_store_si256((__m256i*)p, ymm0); _mm256_store_si256((__m256i*)(p+32), ymm0); p += 64; } } #else { char *p = (char*)ZCG(mem); char *end = p + memory_used; __m128i xmm0 = _mm_setzero_si128(); while (p < end) { _mm_store_si128((__m128i*)p, xmm0); _mm_store_si128((__m128i*)(p+16), xmm0); _mm_store_si128((__m128i*)(p+32), xmm0); _mm_store_si128((__m128i*)(p+48), xmm0); p += 64; } } #endif } #else ZCG(mem) = zend_shared_alloc(memory_used); if (ZCG(mem)) { memset(ZCG(mem), 0, memory_used); } #endif if (!ZCG(mem)) { zend_shared_alloc_destroy_xlat_table(); zend_accel_schedule_restart_if_necessary(ACCEL_RESTART_OOM); zend_shared_alloc_unlock(); if (ZCG(accel_directives).file_cache) { new_persistent_script = store_script_in_file_cache(new_persistent_script); *from_shared_memory = 1; } return new_persistent_script; } zend_shared_alloc_clear_xlat_table(); /* Copy into shared memory */ new_persistent_script = zend_accel_script_persist(new_persistent_script, 1); zend_shared_alloc_destroy_xlat_table(); new_persistent_script->is_phar = is_phar_file(new_persistent_script->script.filename); /* Consistency check */ if ((char*)new_persistent_script->mem + new_persistent_script->size != (char*)ZCG(mem)) { zend_accel_error( ((char*)new_persistent_script->mem + new_persistent_script->size < (char*)ZCG(mem)) ? ACCEL_LOG_ERROR : ACCEL_LOG_WARNING, "Internal error: wrong size calculation: %s start=" ZEND_ADDR_FMT ", end=" ZEND_ADDR_FMT ", real=" ZEND_ADDR_FMT "\n", ZSTR_VAL(new_persistent_script->script.filename), (size_t)new_persistent_script->mem, (size_t)((char *)new_persistent_script->mem + new_persistent_script->size), (size_t)ZCG(mem)); } new_persistent_script->dynamic_members.checksum = zend_accel_script_checksum(new_persistent_script); /* store script structure in the hash table */ bucket = zend_accel_hash_update(&ZCSG(hash), new_persistent_script->script.filename, 0, new_persistent_script); if (bucket) { zend_accel_error(ACCEL_LOG_INFO, "Cached script '%s'", ZSTR_VAL(new_persistent_script->script.filename)); if (key && /* key may contain non-persistent PHAR aliases (see issues #115 and #149) */ memcmp(ZSTR_VAL(key), "phar://", sizeof("phar://") - 1) != 0 && !zend_string_equals(new_persistent_script->script.filename, key)) { /* link key to the same persistent script in hash table */ zend_string *new_key = accel_new_interned_key(key); if (new_key) { if (zend_accel_hash_update(&ZCSG(hash), new_key, 1, bucket)) { zend_accel_error(ACCEL_LOG_INFO, "Added key '%s'", ZSTR_VAL(key)); } else { zend_accel_error(ACCEL_LOG_DEBUG, "No more entries in hash table!"); ZSMMG(memory_exhausted) = 1; zend_accel_schedule_restart_if_necessary(ACCEL_RESTART_HASH); } } else { zend_accel_schedule_restart_if_necessary(ACCEL_RESTART_OOM); } } } new_persistent_script->dynamic_members.memory_consumption = ZEND_ALIGNED_SIZE(new_persistent_script->size); zend_shared_alloc_unlock(); if (ZCG(accel_directives).file_cache) { SHM_PROTECT(); zend_file_cache_script_store(new_persistent_script, 1); SHM_UNPROTECT(); } *from_shared_memory = 1; return new_persistent_script; } #define ZEND_AUTOGLOBAL_MASK_SERVER (1 << 0) #define ZEND_AUTOGLOBAL_MASK_ENV (1 << 1) #define ZEND_AUTOGLOBAL_MASK_REQUEST (1 << 2) static int zend_accel_get_auto_globals(void) { int mask = 0; if (zend_hash_exists(&EG(symbol_table), ZSTR_KNOWN(ZEND_STR_AUTOGLOBAL_SERVER))) { mask |= ZEND_AUTOGLOBAL_MASK_SERVER; } if (zend_hash_exists(&EG(symbol_table), ZSTR_KNOWN(ZEND_STR_AUTOGLOBAL_ENV))) { mask |= ZEND_AUTOGLOBAL_MASK_ENV; } if (zend_hash_exists(&EG(symbol_table), ZSTR_KNOWN(ZEND_STR_AUTOGLOBAL_REQUEST))) { mask |= ZEND_AUTOGLOBAL_MASK_REQUEST; } return mask; } static void zend_accel_set_auto_globals(int mask) { if (mask & ZEND_AUTOGLOBAL_MASK_SERVER) { zend_is_auto_global(ZSTR_KNOWN(ZEND_STR_AUTOGLOBAL_SERVER)); } if (mask & ZEND_AUTOGLOBAL_MASK_ENV) { zend_is_auto_global(ZSTR_KNOWN(ZEND_STR_AUTOGLOBAL_ENV)); } if (mask & ZEND_AUTOGLOBAL_MASK_REQUEST) { zend_is_auto_global(ZSTR_KNOWN(ZEND_STR_AUTOGLOBAL_REQUEST)); } ZCG(auto_globals_mask) |= mask; } static void replay_warnings(uint32_t num_warnings, zend_error_info **warnings) { for (uint32_t i = 0; i < num_warnings; i++) { zend_error_info *warning = warnings[i]; zend_error_zstr_at(warning->type, warning->filename, warning->lineno, warning->message); } } static zend_persistent_script *opcache_compile_file(zend_file_handle *file_handle, int type, zend_op_array **op_array_p) { zend_persistent_script *new_persistent_script; uint32_t orig_functions_count, orig_class_count; zend_op_array *orig_active_op_array; zval orig_user_error_handler; zend_op_array *op_array; int do_bailout = 0; accel_time_t timestamp = 0; uint32_t orig_compiler_options = 0; /* Try to open file */ if (file_handle->type == ZEND_HANDLE_FILENAME) { if (accelerator_orig_zend_stream_open_function(file_handle) != SUCCESS) { *op_array_p = NULL; if (!EG(exception)) { if (type == ZEND_REQUIRE) { zend_message_dispatcher(ZMSG_FAILED_REQUIRE_FOPEN, ZSTR_VAL(file_handle->filename)); } else { zend_message_dispatcher(ZMSG_FAILED_INCLUDE_FOPEN, ZSTR_VAL(file_handle->filename)); } } return NULL; } } /* check blacklist right after ensuring that file was opened */ if (file_handle->opened_path && zend_accel_blacklist_is_blacklisted(&accel_blacklist, ZSTR_VAL(file_handle->opened_path), ZSTR_LEN(file_handle->opened_path))) { SHM_UNPROTECT(); ZCSG(blacklist_misses)++; SHM_PROTECT(); *op_array_p = accelerator_orig_compile_file(file_handle, type); return NULL; } if (ZCG(accel_directives).validate_timestamps || ZCG(accel_directives).file_update_protection || ZCG(accel_directives).max_file_size > 0) { size_t size = 0; /* Obtain the file timestamps, *before* actually compiling them, * otherwise we have a race-condition. */ timestamp = zend_get_file_handle_timestamp(file_handle, ZCG(accel_directives).max_file_size > 0 ? &size : NULL); /* If we can't obtain a timestamp (that means file is possibly socket) * we won't cache it */ if (timestamp == 0) { *op_array_p = accelerator_orig_compile_file(file_handle, type); return NULL; } /* check if file is too new (may be it's not written completely yet) */ if (ZCG(accel_directives).file_update_protection && ((accel_time_t)(ZCG(request_time) - ZCG(accel_directives).file_update_protection) < timestamp)) { *op_array_p = accelerator_orig_compile_file(file_handle, type); return NULL; } if (ZCG(accel_directives).max_file_size > 0 && size > (size_t)ZCG(accel_directives).max_file_size) { SHM_UNPROTECT(); ZCSG(blacklist_misses)++; SHM_PROTECT(); *op_array_p = accelerator_orig_compile_file(file_handle, type); return NULL; } } /* Save the original values for the op_array, function table and class table */ orig_active_op_array = CG(active_op_array); orig_functions_count = EG(function_table)->nNumUsed; orig_class_count = EG(class_table)->nNumUsed; ZVAL_COPY_VALUE(&orig_user_error_handler, &EG(user_error_handler)); /* Override them with ours */ ZVAL_UNDEF(&EG(user_error_handler)); if (ZCG(accel_directives).record_warnings) { zend_begin_record_errors(); } zend_try { orig_compiler_options = CG(compiler_options); CG(compiler_options) |= ZEND_COMPILE_HANDLE_OP_ARRAY; CG(compiler_options) |= ZEND_COMPILE_IGNORE_INTERNAL_CLASSES; CG(compiler_options) |= ZEND_COMPILE_DELAYED_BINDING; CG(compiler_options) |= ZEND_COMPILE_NO_CONSTANT_SUBSTITUTION; CG(compiler_options) |= ZEND_COMPILE_IGNORE_OTHER_FILES; if (ZCG(accel_directives).file_cache) { CG(compiler_options) |= ZEND_COMPILE_WITH_FILE_CACHE; } op_array = *op_array_p = accelerator_orig_compile_file(file_handle, type); CG(compiler_options) = orig_compiler_options; } zend_catch { op_array = NULL; do_bailout = 1; CG(compiler_options) = orig_compiler_options; } zend_end_try(); /* Restore originals */ CG(active_op_array) = orig_active_op_array; EG(user_error_handler) = orig_user_error_handler; EG(record_errors) = 0; if (!op_array) { /* compilation failed */ zend_free_recorded_errors(); if (do_bailout) { zend_bailout(); } return NULL; } /* Build the persistent_script structure. Here we aren't sure we would store it, but we will need it further anyway. */ new_persistent_script = create_persistent_script(); new_persistent_script->script.main_op_array = *op_array; zend_accel_move_user_functions(CG(function_table), CG(function_table)->nNumUsed - orig_functions_count, &new_persistent_script->script); zend_accel_move_user_classes(CG(class_table), CG(class_table)->nNumUsed - orig_class_count, &new_persistent_script->script); new_persistent_script->script.first_early_binding_opline = (op_array->fn_flags & ZEND_ACC_EARLY_BINDING) ? zend_build_delayed_early_binding_list(op_array) : (uint32_t)-1; new_persistent_script->num_warnings = EG(num_errors); new_persistent_script->warnings = EG(errors); EG(num_errors) = 0; EG(errors) = NULL; efree(op_array); /* we have valid persistent_script, so it's safe to free op_array */ /* Fill in the ping_auto_globals_mask for the new script. If jit for auto globals is enabled we will have to ping the used auto global variables before execution */ if (PG(auto_globals_jit)) { new_persistent_script->ping_auto_globals_mask = zend_accel_get_auto_globals(); } if (ZCG(accel_directives).validate_timestamps) { /* Obtain the file timestamps, *before* actually compiling them, * otherwise we have a race-condition. */ new_persistent_script->timestamp = timestamp; new_persistent_script->dynamic_members.revalidate = ZCG(request_time) + ZCG(accel_directives).revalidate_freq; } if (file_handle->opened_path) { new_persistent_script->script.filename = zend_string_copy(file_handle->opened_path); } else { new_persistent_script->script.filename = zend_string_copy(file_handle->filename); } zend_string_hash_val(new_persistent_script->script.filename); /* Now persistent_script structure is ready in process memory */ return new_persistent_script; } zend_op_array *file_cache_compile_file(zend_file_handle *file_handle, int type) { zend_persistent_script *persistent_script; zend_op_array *op_array = NULL; int from_memory; /* if the script we've got is stored in SHM */ if (is_stream_path(ZSTR_VAL(file_handle->filename)) && !is_cacheable_stream_path(ZSTR_VAL(file_handle->filename))) { return accelerator_orig_compile_file(file_handle, type); } if (!file_handle->opened_path) { if (file_handle->type == ZEND_HANDLE_FILENAME && accelerator_orig_zend_stream_open_function(file_handle) == FAILURE) { if (!EG(exception)) { if (type == ZEND_REQUIRE) { zend_message_dispatcher(ZMSG_FAILED_REQUIRE_FOPEN, ZSTR_VAL(file_handle->filename)); } else { zend_message_dispatcher(ZMSG_FAILED_INCLUDE_FOPEN, ZSTR_VAL(file_handle->filename)); } } return NULL; } } HANDLE_BLOCK_INTERRUPTIONS(); SHM_UNPROTECT(); persistent_script = zend_file_cache_script_load(file_handle); SHM_PROTECT(); HANDLE_UNBLOCK_INTERRUPTIONS(); if (persistent_script) { /* see bug #15471 (old BTS) */ if (persistent_script->script.filename) { if (!EG(current_execute_data) || !EG(current_execute_data)->opline || !EG(current_execute_data)->func || !ZEND_USER_CODE(EG(current_execute_data)->func->common.type) || EG(current_execute_data)->opline->opcode != ZEND_INCLUDE_OR_EVAL || (EG(current_execute_data)->opline->extended_value != ZEND_INCLUDE_ONCE && EG(current_execute_data)->opline->extended_value != ZEND_REQUIRE_ONCE)) { if (zend_hash_add_empty_element(&EG(included_files), persistent_script->script.filename) != NULL) { /* ext/phar has to load phar's metadata into memory */ if (persistent_script->is_phar) { php_stream_statbuf ssb; char *fname = emalloc(sizeof("phar://") + ZSTR_LEN(persistent_script->script.filename)); memcpy(fname, "phar://", sizeof("phar://") - 1); memcpy(fname + sizeof("phar://") - 1, ZSTR_VAL(persistent_script->script.filename), ZSTR_LEN(persistent_script->script.filename) + 1); php_stream_stat_path(fname, &ssb); efree(fname); } } } } replay_warnings(persistent_script->num_warnings, persistent_script->warnings); if (persistent_script->ping_auto_globals_mask & ~ZCG(auto_globals_mask)) { zend_accel_set_auto_globals(persistent_script->ping_auto_globals_mask & ~ZCG(auto_globals_mask)); } return zend_accel_load_script(persistent_script, 1); } persistent_script = opcache_compile_file(file_handle, type, &op_array); if (persistent_script) { from_memory = 0; persistent_script = cache_script_in_file_cache(persistent_script, &from_memory); return zend_accel_load_script(persistent_script, from_memory); } return op_array; } int check_persistent_script_access(zend_persistent_script *persistent_script) { char *phar_path, *ptr; int ret; if ((ZSTR_LEN(persistent_script->script.filename)<sizeof("phar://.phar")) || memcmp(ZSTR_VAL(persistent_script->script.filename), "phar://", sizeof("phar://")-1)) { return access(ZSTR_VAL(persistent_script->script.filename), R_OK) != 0; } else { /* we got a cached file from .phar, so we have to strip prefix and path inside .phar to check access() */ phar_path = estrdup(ZSTR_VAL(persistent_script->script.filename)+sizeof("phar://")-1); if ((ptr = strstr(phar_path, ".phar/")) != NULL) { *(ptr+sizeof(".phar/")-2) = 0; /* strip path inside .phar file */ } ret = access(phar_path, R_OK) != 0; efree(phar_path); return ret; } } /* zend_compile() replacement */ zend_op_array *persistent_compile_file(zend_file_handle *file_handle, int type) { zend_persistent_script *persistent_script = NULL; zend_string *key = NULL; int from_shared_memory; /* if the script we've got is stored in SHM */ if (!file_handle->filename || !ZCG(accelerator_enabled)) { /* The Accelerator is disabled, act as if without the Accelerator */ ZCG(cache_opline) = NULL; ZCG(cache_persistent_script) = NULL; if (file_handle->filename && ZCG(accel_directives).file_cache && ZCG(enabled) && accel_startup_ok) { return file_cache_compile_file(file_handle, type); } return accelerator_orig_compile_file(file_handle, type); } else if (file_cache_only) { ZCG(cache_opline) = NULL; ZCG(cache_persistent_script) = NULL; return file_cache_compile_file(file_handle, type); } else if (!ZCG(accelerator_enabled) || (ZCSG(restart_in_progress) && accel_restart_is_active())) { if (ZCG(accel_directives).file_cache) { return file_cache_compile_file(file_handle, type); } ZCG(cache_opline) = NULL; ZCG(cache_persistent_script) = NULL; return accelerator_orig_compile_file(file_handle, type); } /* In case this callback is called from include_once, require_once or it's * a main FastCGI request, the key must be already calculated, and cached * persistent script already found */ if (ZCG(cache_persistent_script) && ((!EG(current_execute_data) && file_handle->primary_script && ZCG(cache_opline) == NULL) || (EG(current_execute_data) && EG(current_execute_data)->func && ZEND_USER_CODE(EG(current_execute_data)->func->common.type) && ZCG(cache_opline) == EG(current_execute_data)->opline))) { persistent_script = ZCG(cache_persistent_script); if (ZSTR_LEN(&ZCG(key))) { key = &ZCG(key); } } else { if (!ZCG(accel_directives).revalidate_path) { /* try to find cached script by key */ key = accel_make_persistent_key(file_handle->filename); if (!key) { ZCG(cache_opline) = NULL; ZCG(cache_persistent_script) = NULL; return accelerator_orig_compile_file(file_handle, type); } persistent_script = zend_accel_hash_find(&ZCSG(hash), key); } else if (UNEXPECTED(is_stream_path(ZSTR_VAL(file_handle->filename)) && !is_cacheable_stream_path(ZSTR_VAL(file_handle->filename)))) { ZCG(cache_opline) = NULL; ZCG(cache_persistent_script) = NULL; return accelerator_orig_compile_file(file_handle, type); } if (!persistent_script) { /* try to find cached script by full real path */ zend_accel_hash_entry *bucket; /* open file to resolve the path */ if (file_handle->type == ZEND_HANDLE_FILENAME && accelerator_orig_zend_stream_open_function(file_handle) == FAILURE) { if (!EG(exception)) { if (type == ZEND_REQUIRE) { zend_message_dispatcher(ZMSG_FAILED_REQUIRE_FOPEN, ZSTR_VAL(file_handle->filename)); } else { zend_message_dispatcher(ZMSG_FAILED_INCLUDE_FOPEN, ZSTR_VAL(file_handle->filename)); } } return NULL; } if (file_handle->opened_path) { bucket = zend_accel_hash_find_entry(&ZCSG(hash), file_handle->opened_path); if (bucket) { persistent_script = (zend_persistent_script *)bucket->data; if (key && !persistent_script->corrupted) { HANDLE_BLOCK_INTERRUPTIONS(); SHM_UNPROTECT(); zend_shared_alloc_lock(); zend_accel_add_key(key, bucket); zend_shared_alloc_unlock(); SHM_PROTECT(); HANDLE_UNBLOCK_INTERRUPTIONS(); } } } } } /* clear cache */ ZCG(cache_opline) = NULL; ZCG(cache_persistent_script) = NULL; if (persistent_script && persistent_script->corrupted) { persistent_script = NULL; } /* Make sure we only increase the currently running processes semaphore * once each execution (this function can be called more than once on * each execution) */ if (!ZCG(counted)) { if (accel_activate_add() == FAILURE) { if (ZCG(accel_directives).file_cache) { return file_cache_compile_file(file_handle, type); } return accelerator_orig_compile_file(file_handle, type); } ZCG(counted) = 1; } /* Revalidate accessibility of cached file */ if (EXPECTED(persistent_script != NULL) && UNEXPECTED(ZCG(accel_directives).validate_permission) && file_handle->type == ZEND_HANDLE_FILENAME && UNEXPECTED(check_persistent_script_access(persistent_script))) { if (!EG(exception)) { if (type == ZEND_REQUIRE) { zend_message_dispatcher(ZMSG_FAILED_REQUIRE_FOPEN, ZSTR_VAL(file_handle->filename)); } else { zend_message_dispatcher(ZMSG_FAILED_INCLUDE_FOPEN, ZSTR_VAL(file_handle->filename)); } } return NULL; } HANDLE_BLOCK_INTERRUPTIONS(); SHM_UNPROTECT(); /* If script is found then validate_timestamps if option is enabled */ if (persistent_script && ZCG(accel_directives).validate_timestamps) { if (validate_timestamp_and_record(persistent_script, file_handle) == FAILURE) { zend_shared_alloc_lock(); if (!persistent_script->corrupted) { persistent_script->corrupted = 1; persistent_script->timestamp = 0; ZSMMG(wasted_shared_memory) += persistent_script->dynamic_members.memory_consumption; if (ZSMMG(memory_exhausted)) { zend_accel_restart_reason reason = zend_accel_hash_is_full(&ZCSG(hash)) ? ACCEL_RESTART_HASH : ACCEL_RESTART_OOM; zend_accel_schedule_restart_if_necessary(reason); } } zend_shared_alloc_unlock(); persistent_script = NULL; } } /* if turned on - check the compiled script ADLER32 checksum */ if (persistent_script && ZCG(accel_directives).consistency_checks && persistent_script->dynamic_members.hits % ZCG(accel_directives).consistency_checks == 0) { unsigned int checksum = zend_accel_script_checksum(persistent_script); if (checksum != persistent_script->dynamic_members.checksum ) { /* The checksum is wrong */ zend_accel_error(ACCEL_LOG_INFO, "Checksum failed for '%s': expected=0x%08x, found=0x%08x", ZSTR_VAL(persistent_script->script.filename), persistent_script->dynamic_members.checksum, checksum); zend_shared_alloc_lock(); if (!persistent_script->corrupted) { persistent_script->corrupted = 1; persistent_script->timestamp = 0; ZSMMG(wasted_shared_memory) += persistent_script->dynamic_members.memory_consumption; if (ZSMMG(memory_exhausted)) { zend_accel_restart_reason reason = zend_accel_hash_is_full(&ZCSG(hash)) ? ACCEL_RESTART_HASH : ACCEL_RESTART_OOM; zend_accel_schedule_restart_if_necessary(reason); } } zend_shared_alloc_unlock(); persistent_script = NULL; } } /* Check the second level cache */ if (!persistent_script && ZCG(accel_directives).file_cache) { persistent_script = zend_file_cache_script_load(file_handle); } /* If script was not found or invalidated by validate_timestamps */ if (!persistent_script) { uint32_t old_const_num = zend_hash_next_free_element(EG(zend_constants)); zend_op_array *op_array; /* Cache miss.. */ ZCSG(misses)++; /* No memory left. Behave like without the Accelerator */ if (ZSMMG(memory_exhausted) || ZCSG(restart_pending)) { SHM_PROTECT(); HANDLE_UNBLOCK_INTERRUPTIONS(); if (ZCG(accel_directives).file_cache) { return file_cache_compile_file(file_handle, type); } return accelerator_orig_compile_file(file_handle, type); } SHM_PROTECT(); HANDLE_UNBLOCK_INTERRUPTIONS(); persistent_script = opcache_compile_file(file_handle, type, &op_array); HANDLE_BLOCK_INTERRUPTIONS(); SHM_UNPROTECT(); /* Try and cache the script and assume that it is returned from_shared_memory. * If it isn't compile_and_cache_file() changes the flag to 0 */ from_shared_memory = 0; if (persistent_script) { persistent_script = cache_script_in_shared_memory(persistent_script, key, &from_shared_memory); } /* Caching is disabled, returning op_array; * or something went wrong during compilation, returning NULL */ if (!persistent_script) { SHM_PROTECT(); HANDLE_UNBLOCK_INTERRUPTIONS(); return op_array; } if (from_shared_memory) { /* Delete immutable arrays moved into SHM */ uint32_t new_const_num = zend_hash_next_free_element(EG(zend_constants)); while (new_const_num > old_const_num) { new_const_num--; zend_hash_index_del(EG(zend_constants), new_const_num); } } } else { #if !ZEND_WIN32 ZCSG(hits)++; /* TBFixed: may lose one hit */ persistent_script->dynamic_members.hits++; /* see above */ #else #ifdef _M_X64 InterlockedIncrement64(&ZCSG(hits)); #else InterlockedIncrement(&ZCSG(hits)); #endif InterlockedIncrement64(&persistent_script->dynamic_members.hits); #endif /* see bug #15471 (old BTS) */ if (persistent_script->script.filename) { if (!EG(current_execute_data) || !EG(current_execute_data)->opline || !EG(current_execute_data)->func || !ZEND_USER_CODE(EG(current_execute_data)->func->common.type) || EG(current_execute_data)->opline->opcode != ZEND_INCLUDE_OR_EVAL || (EG(current_execute_data)->opline->extended_value != ZEND_INCLUDE_ONCE && EG(current_execute_data)->opline->extended_value != ZEND_REQUIRE_ONCE)) { if (zend_hash_add_empty_element(&EG(included_files), persistent_script->script.filename) != NULL) { /* ext/phar has to load phar's metadata into memory */ if (persistent_script->is_phar) { php_stream_statbuf ssb; char *fname = emalloc(sizeof("phar://") + ZSTR_LEN(persistent_script->script.filename)); memcpy(fname, "phar://", sizeof("phar://") - 1); memcpy(fname + sizeof("phar://") - 1, ZSTR_VAL(persistent_script->script.filename), ZSTR_LEN(persistent_script->script.filename) + 1); php_stream_stat_path(fname, &ssb); efree(fname); } } } } replay_warnings(persistent_script->num_warnings, persistent_script->warnings); from_shared_memory = 1; } persistent_script->dynamic_members.last_used = ZCG(request_time); SHM_PROTECT(); HANDLE_UNBLOCK_INTERRUPTIONS(); /* Fetch jit auto globals used in the script before execution */ if (persistent_script->ping_auto_globals_mask & ~ZCG(auto_globals_mask)) { zend_accel_set_auto_globals(persistent_script->ping_auto_globals_mask & ~ZCG(auto_globals_mask)); } return zend_accel_load_script(persistent_script, from_shared_memory); } static zend_always_inline zend_inheritance_cache_entry* zend_accel_inheritance_cache_find(zend_inheritance_cache_entry *entry, zend_class_entry *ce, zend_class_entry *parent, zend_class_entry **traits_and_interfaces, bool *needs_autoload_ptr) { uint32_t i; ZEND_ASSERT(ce->ce_flags & ZEND_ACC_IMMUTABLE); ZEND_ASSERT(!(ce->ce_flags & ZEND_ACC_LINKED)); while (entry) { bool found = 1; bool needs_autoload = 0; if (entry->parent != parent) { found = 0; } else { for (i = 0; i < ce->num_traits + ce->num_interfaces; i++) { if (entry->traits_and_interfaces[i] != traits_and_interfaces[i]) { found = 0; break; } } if (found && entry->dependencies) { for (i = 0; i < entry->dependencies_count; i++) { zend_class_entry *ce = zend_lookup_class_ex(entry->dependencies[i].name, NULL, ZEND_FETCH_CLASS_NO_AUTOLOAD); if (ce != entry->dependencies[i].ce) { if (!ce) { needs_autoload = 1; } else { found = 0; break; } } } } } if (found) { *needs_autoload_ptr = needs_autoload; return entry; } entry = entry->next; } return NULL; } static zend_class_entry* zend_accel_inheritance_cache_get(zend_class_entry *ce, zend_class_entry *parent, zend_class_entry **traits_and_interfaces) { uint32_t i; bool needs_autoload; zend_inheritance_cache_entry *entry = ce->inheritance_cache; while (entry) { entry = zend_accel_inheritance_cache_find(entry, ce, parent, traits_and_interfaces, &needs_autoload); if (entry) { if (!needs_autoload) { if (ZCSG(map_ptr_last) > CG(map_ptr_last)) { zend_map_ptr_extend(ZCSG(map_ptr_last)); } replay_warnings(entry->num_warnings, entry->warnings); return entry->ce; } for (i = 0; i < entry->dependencies_count; i++) { zend_class_entry *ce = zend_lookup_class_ex(entry->dependencies[i].name, NULL, 0); if (ce == NULL) { return NULL; } } } } return NULL; } static zend_class_entry* zend_accel_inheritance_cache_add(zend_class_entry *ce, zend_class_entry *proto, zend_class_entry *parent, zend_class_entry **traits_and_interfaces, HashTable *dependencies) { zend_persistent_script dummy; size_t size; uint32_t i; bool needs_autoload; zend_class_entry *new_ce; zend_inheritance_cache_entry *entry; ZEND_ASSERT(!(ce->ce_flags & ZEND_ACC_IMMUTABLE)); ZEND_ASSERT(ce->ce_flags & ZEND_ACC_LINKED); if (!ZCG(accelerator_enabled) || (ZCSG(restart_in_progress) && accel_restart_is_active())) { return NULL; } if (traits_and_interfaces && dependencies) { for (i = 0; i < proto->num_traits + proto->num_interfaces; i++) { if (traits_and_interfaces[i]) { zend_hash_del(dependencies, traits_and_interfaces[i]->name); } } } SHM_UNPROTECT(); zend_shared_alloc_lock(); entry = ce->inheritance_cache; while (entry) { entry = zend_accel_inheritance_cache_find(entry, ce, parent, traits_and_interfaces, &needs_autoload); if (entry) { if (!needs_autoload) { zend_shared_alloc_unlock(); SHM_PROTECT(); zend_map_ptr_extend(ZCSG(map_ptr_last)); return entry->ce; } ZEND_ASSERT(0); // entry = entry->next; // This shouldn't be posible ??? } } zend_shared_alloc_init_xlat_table(); memset(&dummy, 0, sizeof(dummy)); dummy.size = ZEND_ALIGNED_SIZE( sizeof(zend_inheritance_cache_entry) - sizeof(void*) + (sizeof(void*) * (proto->num_traits + proto->num_interfaces))); if (dependencies) { dummy.size += ZEND_ALIGNED_SIZE(zend_hash_num_elements(dependencies) * sizeof(zend_class_dependency)); } ZCG(current_persistent_script) = &dummy; zend_persist_class_entry_calc(ce); zend_persist_warnings_calc(EG(num_errors), EG(errors)); size = dummy.size; zend_shared_alloc_clear_xlat_table(); #if ZEND_MM_ALIGNMENT < 8 /* Align to 8-byte boundary */ ZCG(mem) = zend_shared_alloc(size + 8); #else ZCG(mem) = zend_shared_alloc(size); #endif if (!ZCG(mem)) { zend_shared_alloc_destroy_xlat_table(); zend_shared_alloc_unlock(); SHM_PROTECT(); return NULL; } #if ZEND_MM_ALIGNMENT < 8 /* Align to 8-byte boundary */ ZCG(mem) = (void*)(((zend_uintptr_t)ZCG(mem) + 7L) & ~7L); #endif memset(ZCG(mem), 0, size); entry = (zend_inheritance_cache_entry*)ZCG(mem); ZCG(mem) = (char*)ZCG(mem) + ZEND_ALIGNED_SIZE( (sizeof(zend_inheritance_cache_entry) - sizeof(void*) + (sizeof(void*) * (proto->num_traits + proto->num_interfaces)))); entry->parent = parent; for (i = 0; i < proto->num_traits + proto->num_interfaces; i++) { entry->traits_and_interfaces[i] = traits_and_interfaces[i]; } if (dependencies && zend_hash_num_elements(dependencies)) { zend_string *dep_name; zend_class_entry *dep_ce; i = 0; entry->dependencies_count = zend_hash_num_elements(dependencies); entry->dependencies = (zend_class_dependency*)ZCG(mem); ZEND_HASH_FOREACH_STR_KEY_PTR(dependencies, dep_name, dep_ce) { #if ZEND_DEBUG ZEND_ASSERT(zend_accel_in_shm(dep_name)); #endif entry->dependencies[i].name = dep_name; entry->dependencies[i].ce = dep_ce; i++; } ZEND_HASH_FOREACH_END(); ZCG(mem) = (char*)ZCG(mem) + zend_hash_num_elements(dependencies) * sizeof(zend_class_dependency); } entry->ce = new_ce = zend_persist_class_entry(ce); zend_update_parent_ce(new_ce); entry->next = proto->inheritance_cache; proto->inheritance_cache = entry; entry->num_warnings = EG(num_errors); entry->warnings = zend_persist_warnings(EG(num_errors), EG(errors)); EG(num_errors) = 0; EG(errors) = NULL; zend_shared_alloc_destroy_xlat_table(); zend_shared_alloc_unlock(); SHM_PROTECT(); /* Consistency check */ if ((char*)entry + size != (char*)ZCG(mem)) { zend_accel_error( ((char*)entry + size < (char*)ZCG(mem)) ? ACCEL_LOG_ERROR : ACCEL_LOG_WARNING, "Internal error: wrong class size calculation: %s start=" ZEND_ADDR_FMT ", end=" ZEND_ADDR_FMT ", real=" ZEND_ADDR_FMT "\n", ZSTR_VAL(ce->name), (size_t)entry, (size_t)((char *)entry + size), (size_t)ZCG(mem)); } zend_map_ptr_extend(ZCSG(map_ptr_last)); return new_ce; } #ifdef ZEND_WIN32 static int accel_gen_uname_id(void) { PHP_MD5_CTX ctx; unsigned char digest[16]; wchar_t uname[UNLEN + 1]; DWORD unsize = UNLEN; if (!GetUserNameW(uname, &unsize)) { return FAILURE; } PHP_MD5Init(&ctx); PHP_MD5Update(&ctx, (void *) uname, (unsize - 1) * sizeof(wchar_t)); PHP_MD5Update(&ctx, ZCG(accel_directives).cache_id, strlen(ZCG(accel_directives).cache_id)); PHP_MD5Final(digest, &ctx); php_hash_bin2hex(accel_uname_id, digest, sizeof digest); return SUCCESS; } #endif /* zend_stream_open_function() replacement for PHP 5.3 and above */ static zend_result persistent_stream_open_function(zend_file_handle *handle) { if (ZCG(cache_persistent_script)) { /* check if callback is called from include_once or it's a main request */ if ((!EG(current_execute_data) && handle->primary_script && ZCG(cache_opline) == NULL) || (EG(current_execute_data) && EG(current_execute_data)->func && ZEND_USER_CODE(EG(current_execute_data)->func->common.type) && ZCG(cache_opline) == EG(current_execute_data)->opline)) { /* we are in include_once or FastCGI request */ handle->opened_path = zend_string_copy(ZCG(cache_persistent_script)->script.filename); return SUCCESS; } ZCG(cache_opline) = NULL; ZCG(cache_persistent_script) = NULL; } return accelerator_orig_zend_stream_open_function(handle); } /* zend_resolve_path() replacement for PHP 5.3 and above */ static zend_string* persistent_zend_resolve_path(zend_string *filename) { if (!file_cache_only && ZCG(accelerator_enabled)) { /* check if callback is called from include_once or it's a main request */ if ((!EG(current_execute_data)) || (EG(current_execute_data) && EG(current_execute_data)->func && ZEND_USER_CODE(EG(current_execute_data)->func->common.type) && EG(current_execute_data)->opline->opcode == ZEND_INCLUDE_OR_EVAL && (EG(current_execute_data)->opline->extended_value == ZEND_INCLUDE_ONCE || EG(current_execute_data)->opline->extended_value == ZEND_REQUIRE_ONCE))) { /* we are in include_once or FastCGI request */ zend_string *resolved_path; zend_string *key = NULL; if (!ZCG(accel_directives).revalidate_path) { /* lookup by "not-real" path */ key = accel_make_persistent_key(filename); if (key) { zend_accel_hash_entry *bucket = zend_accel_hash_find_entry(&ZCSG(hash), key); if (bucket != NULL) { zend_persistent_script *persistent_script = (zend_persistent_script *)bucket->data; if (!persistent_script->corrupted) { ZCG(cache_opline) = EG(current_execute_data) ? EG(current_execute_data)->opline : NULL; ZCG(cache_persistent_script) = persistent_script; return zend_string_copy(persistent_script->script.filename); } } } else { ZCG(cache_opline) = NULL; ZCG(cache_persistent_script) = NULL; return accelerator_orig_zend_resolve_path(filename); } } /* find the full real path */ resolved_path = accelerator_orig_zend_resolve_path(filename); if (resolved_path) { /* lookup by real path */ zend_accel_hash_entry *bucket = zend_accel_hash_find_entry(&ZCSG(hash), resolved_path); if (bucket) { zend_persistent_script *persistent_script = (zend_persistent_script *)bucket->data; if (!persistent_script->corrupted) { if (key) { /* add another "key" for the same bucket */ HANDLE_BLOCK_INTERRUPTIONS(); SHM_UNPROTECT(); zend_shared_alloc_lock(); zend_accel_add_key(key, bucket); zend_shared_alloc_unlock(); SHM_PROTECT(); HANDLE_UNBLOCK_INTERRUPTIONS(); } else { ZSTR_LEN(&ZCG(key)) = 0; } ZCG(cache_opline) = EG(current_execute_data) ? EG(current_execute_data)->opline : NULL; ZCG(cache_persistent_script) = persistent_script; return resolved_path; } } } ZCG(cache_opline) = NULL; ZCG(cache_persistent_script) = NULL; return resolved_path; } } ZCG(cache_opline) = NULL; ZCG(cache_persistent_script) = NULL; return accelerator_orig_zend_resolve_path(filename); } static void zend_reset_cache_vars(void) { ZSMMG(memory_exhausted) = 0; ZCSG(hits) = 0; ZCSG(misses) = 0; ZCSG(blacklist_misses) = 0; ZSMMG(wasted_shared_memory) = 0; ZCSG(restart_pending) = 0; ZCSG(force_restart_time) = 0; ZCSG(map_ptr_last) = CG(map_ptr_last); } static void accel_reset_pcre_cache(void) { Bucket *p; if (PCRE_G(per_request_cache)) { return; } ZEND_HASH_FOREACH_BUCKET(&PCRE_G(pcre_cache), p) { /* Remove PCRE cache entries with inconsistent keys */ if (zend_accel_in_shm(p->key)) { p->key = NULL; zend_hash_del_bucket(&PCRE_G(pcre_cache), p); } } ZEND_HASH_FOREACH_END(); } zend_result accel_activate(INIT_FUNC_ARGS) { if (!ZCG(enabled) || !accel_startup_ok) { ZCG(accelerator_enabled) = 0; return SUCCESS; } /* PHP-5.4 and above return "double", but we use 1 sec precision */ ZCG(auto_globals_mask) = 0; ZCG(request_time) = (time_t)sapi_get_request_time(); ZCG(cache_opline) = NULL; ZCG(cache_persistent_script) = NULL; ZCG(include_path_key_len) = 0; ZCG(include_path_check) = 1; ZCG(cwd) = NULL; ZCG(cwd_key_len) = 0; ZCG(cwd_check) = 1; if (file_cache_only) { ZCG(accelerator_enabled) = 0; return SUCCESS; } #ifndef ZEND_WIN32 if (ZCG(accel_directives).validate_root) { struct stat buf; if (stat("/", &buf) != 0) { ZCG(root_hash) = 0; } else { ZCG(root_hash) = buf.st_ino; if (sizeof(buf.st_ino) > sizeof(ZCG(root_hash))) { if (ZCG(root_hash) != buf.st_ino) { zend_string *key = zend_string_init("opcache.enable", sizeof("opcache.enable")-1, 0); zend_alter_ini_entry_chars(key, "0", 1, ZEND_INI_SYSTEM, ZEND_INI_STAGE_RUNTIME); zend_string_release_ex(key, 0); zend_accel_error(ACCEL_LOG_WARNING, "Can't cache files in chroot() directory with too big inode"); return SUCCESS; } } } } else { ZCG(root_hash) = 0; } #endif HANDLE_BLOCK_INTERRUPTIONS(); SHM_UNPROTECT(); if (ZCG(counted)) { #ifdef ZTS zend_accel_error(ACCEL_LOG_WARNING, "Stuck count for thread id %lu", (unsigned long) tsrm_thread_id()); #else zend_accel_error(ACCEL_LOG_WARNING, "Stuck count for pid %d", getpid()); #endif accel_unlock_all(); ZCG(counted) = 0; } if (ZCSG(restart_pending)) { zend_shared_alloc_lock(); if (ZCSG(restart_pending) != 0) { /* check again, to ensure that the cache wasn't already cleaned by another process */ if (accel_is_inactive() == SUCCESS) { zend_accel_error(ACCEL_LOG_DEBUG, "Restarting!"); ZCSG(restart_pending) = 0; switch ZCSG(restart_reason) { case ACCEL_RESTART_OOM: ZCSG(oom_restarts)++; break; case ACCEL_RESTART_HASH: ZCSG(hash_restarts)++; break; case ACCEL_RESTART_USER: ZCSG(manual_restarts)++; break; } accel_restart_enter(); zend_map_ptr_reset(); zend_reset_cache_vars(); zend_accel_hash_clean(&ZCSG(hash)); if (ZCG(accel_directives).interned_strings_buffer) { accel_interned_strings_restore_state(); } zend_shared_alloc_restore_state(); if (ZCSG(preload_script)) { preload_restart(); } #ifdef HAVE_JIT zend_jit_restart(); #endif ZCSG(accelerator_enabled) = ZCSG(cache_status_before_restart); if (ZCSG(last_restart_time) < ZCG(request_time)) { ZCSG(last_restart_time) = ZCG(request_time); } else { ZCSG(last_restart_time)++; } accel_restart_leave(); } } zend_shared_alloc_unlock(); } ZCG(accelerator_enabled) = ZCSG(accelerator_enabled); SHM_PROTECT(); HANDLE_UNBLOCK_INTERRUPTIONS(); if (ZCG(accelerator_enabled) && ZCSG(last_restart_time) != ZCG(last_restart_time)) { /* SHM was reinitialized. */ ZCG(last_restart_time) = ZCSG(last_restart_time); /* Reset in-process realpath cache */ realpath_cache_clean(); accel_reset_pcre_cache(); ZCG(pcre_reseted) = 0; } else if (!ZCG(accelerator_enabled) && !ZCG(pcre_reseted)) { accel_reset_pcre_cache(); ZCG(pcre_reseted) = 1; } #ifdef HAVE_JIT zend_jit_activate(); #endif if (ZCSG(preload_script)) { preload_activate(); } return SUCCESS; } #ifdef HAVE_JIT void accel_deactivate(void) { zend_jit_deactivate(); } #endif zend_result accel_post_deactivate(void) { if (ZCG(cwd)) { zend_string_release_ex(ZCG(cwd), 0); ZCG(cwd) = NULL; } if (!ZCG(enabled) || !accel_startup_ok) { return SUCCESS; } zend_shared_alloc_safe_unlock(); /* be sure we didn't leave cache locked */ accel_unlock_all(); ZCG(counted) = 0; return SUCCESS; } static int accelerator_remove_cb(zend_extension *element1, zend_extension *element2) { (void)element2; /* keep the compiler happy */ if (!strcmp(element1->name, ACCELERATOR_PRODUCT_NAME )) { element1->startup = NULL; #if 0 /* We have to call shutdown callback it to free TS resources */ element1->shutdown = NULL; #endif element1->activate = NULL; element1->deactivate = NULL; element1->op_array_handler = NULL; #ifdef __DEBUG_MESSAGES__ fprintf(stderr, ACCELERATOR_PRODUCT_NAME " is disabled: %s\n", (zps_failure_reason ? zps_failure_reason : "unknown error")); fflush(stderr); #endif } return 0; } static void zps_startup_failure(char *reason, char *api_reason, int (*cb)(zend_extension *, zend_extension *)) { accel_startup_ok = 0; zps_failure_reason = reason; zps_api_failure_reason = api_reason?api_reason:reason; zend_llist_del_element(&zend_extensions, NULL, (int (*)(void *, void *))cb); } static inline int accel_find_sapi(void) { static const char *supported_sapis[] = { "apache", "fastcgi", "cli-server", "cgi-fcgi", "fpm-fcgi", "fpmi-fcgi", "apache2handler", "litespeed", "uwsgi", NULL }; const char **sapi_name; if (sapi_module.name) { for (sapi_name = supported_sapis; *sapi_name; sapi_name++) { if (strcmp(sapi_module.name, *sapi_name) == 0) { return SUCCESS; } } if (ZCG(accel_directives).enable_cli && ( strcmp(sapi_module.name, "cli") == 0 || strcmp(sapi_module.name, "phpdbg") == 0)) { return SUCCESS; } } return FAILURE; } static int zend_accel_init_shm(void) { int i; zend_shared_alloc_lock(); if (ZCG(accel_directives).interned_strings_buffer) { accel_shared_globals = zend_shared_alloc((ZCG(accel_directives).interned_strings_buffer * 1024 * 1024)); } else { /* Make sure there is always at least one interned string hash slot, * so the table can be queried unconditionally. */ accel_shared_globals = zend_shared_alloc(sizeof(zend_accel_shared_globals) + sizeof(uint32_t)); } if (!accel_shared_globals) { zend_accel_error_noreturn(ACCEL_LOG_FATAL, "Insufficient shared memory!"); zend_shared_alloc_unlock(); return FAILURE; } memset(accel_shared_globals, 0, sizeof(zend_accel_shared_globals)); ZSMMG(app_shared_globals) = accel_shared_globals; zend_accel_hash_init(&ZCSG(hash), ZCG(accel_directives).max_accelerated_files); if (ZCG(accel_directives).interned_strings_buffer) { uint32_t hash_size; /* must be a power of two */ hash_size = ZCG(accel_directives).interned_strings_buffer * (32 * 1024); hash_size |= (hash_size >> 1); hash_size |= (hash_size >> 2); hash_size |= (hash_size >> 4); hash_size |= (hash_size >> 8); hash_size |= (hash_size >> 16); ZCSG(interned_strings).nTableMask = hash_size << 2; ZCSG(interned_strings).nNumOfElements = 0; ZCSG(interned_strings).start = (zend_string*)((char*)&ZCSG(interned_strings) + sizeof(zend_string_table) + ((hash_size + 1) * sizeof(uint32_t))) + 8; ZCSG(interned_strings).top = ZCSG(interned_strings).start; ZCSG(interned_strings).end = (zend_string*)((char*)accel_shared_globals + ZCG(accel_directives).interned_strings_buffer * 1024 * 1024); ZCSG(interned_strings).saved_top = NULL; memset((char*)&ZCSG(interned_strings) + sizeof(zend_string_table), STRTAB_INVALID_POS, (char*)ZCSG(interned_strings).start - ((char*)&ZCSG(interned_strings) + sizeof(zend_string_table))); } else { *STRTAB_HASH_TO_SLOT(&ZCSG(interned_strings), 0) = STRTAB_INVALID_POS; } zend_interned_strings_set_request_storage_handlers(accel_new_interned_string_for_php, accel_init_interned_string_for_php); zend_reset_cache_vars(); ZCSG(oom_restarts) = 0; ZCSG(hash_restarts) = 0; ZCSG(manual_restarts) = 0; ZCSG(accelerator_enabled) = 1; ZCSG(start_time) = zend_accel_get_time(); ZCSG(last_restart_time) = 0; ZCSG(restart_in_progress) = 0; for (i = 0; i < -HT_MIN_MASK; i++) { ZCSG(uninitialized_bucket)[i] = HT_INVALID_IDX; } zend_shared_alloc_unlock(); return SUCCESS; } static void accel_globals_ctor(zend_accel_globals *accel_globals) { #if defined(COMPILE_DL_OPCACHE) && defined(ZTS) ZEND_TSRMLS_CACHE_UPDATE(); #endif memset(accel_globals, 0, sizeof(zend_accel_globals)); } #ifdef HAVE_HUGE_CODE_PAGES # ifndef _WIN32 # include <sys/mman.h> # ifndef MAP_ANON # ifdef MAP_ANONYMOUS # define MAP_ANON MAP_ANONYMOUS # endif # endif # ifndef MAP_FAILED # define MAP_FAILED ((void*)-1) # endif # ifdef MAP_ALIGNED_SUPER # include <sys/types.h> # include <sys/sysctl.h> # include <sys/user.h> # define MAP_HUGETLB MAP_ALIGNED_SUPER # endif # endif # if defined(MAP_HUGETLB) || defined(MADV_HUGEPAGE) static int accel_remap_huge_pages(void *start, size_t size, size_t real_size, const char *name, size_t offset) { void *ret = MAP_FAILED; void *mem; mem = mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); if (mem == MAP_FAILED) { zend_error(E_WARNING, ACCELERATOR_PRODUCT_NAME " huge_code_pages: mmap failed: %s (%d)", strerror(errno), errno); return -1; } memcpy(mem, start, real_size); # ifdef MAP_HUGETLB ret = mmap(start, size, PROT_READ | PROT_WRITE | PROT_EXEC, MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED | MAP_HUGETLB, -1, 0); # endif if (ret == MAP_FAILED) { ret = mmap(start, size, PROT_READ | PROT_WRITE | PROT_EXEC, MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED, -1, 0); /* this should never happen? */ ZEND_ASSERT(ret != MAP_FAILED); # ifdef MADV_HUGEPAGE if (-1 == madvise(start, size, MADV_HUGEPAGE)) { memcpy(start, mem, real_size); mprotect(start, size, PROT_READ | PROT_EXEC); munmap(mem, size); zend_error(E_WARNING, ACCELERATOR_PRODUCT_NAME " huge_code_pages: madvise(HUGEPAGE) failed: %s (%d)", strerror(errno), errno); return -1; } # else memcpy(start, mem, real_size); mprotect(start, size, PROT_READ | PROT_EXEC); munmap(mem, size); zend_error(E_WARNING, ACCELERATOR_PRODUCT_NAME " huge_code_pages: mmap(HUGETLB) failed: %s (%d)", strerror(errno), errno); return -1; # endif } if (ret == start) { memcpy(start, mem, real_size); mprotect(start, size, PROT_READ | PROT_EXEC); } munmap(mem, size); return (ret == start) ? 0 : -1; } static void accel_move_code_to_huge_pages(void) { #if defined(__linux__) FILE *f; long unsigned int huge_page_size = 2 * 1024 * 1024; f = fopen("/proc/self/maps", "r"); if (f) { long unsigned int start, end, offset, inode; char perm[5], dev[6], name[MAXPATHLEN]; int ret; while (1) { ret = fscanf(f, "%lx-%lx %4s %lx %5s %ld %s\n", &start, &end, perm, &offset, dev, &inode, name); if (ret == 7) { if (perm[0] == 'r' && perm[1] == '-' && perm[2] == 'x' && name[0] == '/') { long unsigned int seg_start = ZEND_MM_ALIGNED_SIZE_EX(start, huge_page_size); long unsigned int seg_end = (end & ~(huge_page_size-1L)); long unsigned int real_end; ret = fscanf(f, "%lx-", &start); if (ret == 1 && start == seg_end + huge_page_size) { real_end = end; seg_end = start; } else { real_end = seg_end; } if (seg_end > seg_start) { zend_accel_error(ACCEL_LOG_DEBUG, "remap to huge page %lx-%lx %s \n", seg_start, seg_end, name); accel_remap_huge_pages((void*)seg_start, seg_end - seg_start, real_end - seg_start, name, offset + seg_start - start); } break; } } else { break; } } fclose(f); } #elif defined(__FreeBSD__) size_t s = 0; int mib[4] = {CTL_KERN, KERN_PROC, KERN_PROC_VMMAP, getpid()}; long unsigned int huge_page_size = 2 * 1024 * 1024; if (sysctl(mib, 4, NULL, &s, NULL, 0) == 0) { s = s * 4 / 3; void *addr = mmap(NULL, s, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANON, -1, 0); if (addr != MAP_FAILED) { if (sysctl(mib, 4, addr, &s, NULL, 0) == 0) { uintptr_t start = (uintptr_t)addr; uintptr_t end = start + s; while (start < end) { struct kinfo_vmentry *entry = (struct kinfo_vmentry *)start; size_t sz = entry->kve_structsize; if (sz == 0) { break; } int permflags = entry->kve_protection; if ((permflags & KVME_PROT_READ) && !(permflags & KVME_PROT_WRITE) && (permflags & KVME_PROT_EXEC) && entry->kve_path[0] != '\0') { long unsigned int seg_start = ZEND_MM_ALIGNED_SIZE_EX(start, huge_page_size); long unsigned int seg_end = (end & ~(huge_page_size-1L)); if (seg_end > seg_start) { zend_accel_error(ACCEL_LOG_DEBUG, "remap to huge page %lx-%lx %s \n", seg_start, seg_end, entry->kve_path); accel_remap_huge_pages((void*)seg_start, seg_end - seg_start, seg_end - seg_start, entry->kve_path, entry->kve_offset + seg_start - start); // First relevant segment found is our binary break; } } start += sz; } } munmap(addr, s); } } #endif } # else static void accel_move_code_to_huge_pages(void) { zend_error(E_WARNING, ACCELERATOR_PRODUCT_NAME ": opcache.huge_code_pages has no affect as huge page is not supported"); return; } # endif /* defined(MAP_HUGETLB) || defined(MADV_HUGEPAGE) */ #endif /* HAVE_HUGE_CODE_PAGES */ static int accel_startup(zend_extension *extension) { #ifdef ZTS accel_globals_id = ts_allocate_id(&accel_globals_id, sizeof(zend_accel_globals), (ts_allocate_ctor) accel_globals_ctor, NULL); #else accel_globals_ctor(&accel_globals); #endif #ifdef HAVE_JIT zend_jit_init(); #endif #ifdef ZEND_WIN32 # if !defined(__has_feature) || !__has_feature(address_sanitizer) _setmaxstdio(2048); /* The default configuration is limited to 512 stdio files */ # endif #endif if (start_accel_module() == FAILURE) { accel_startup_ok = 0; zend_error(E_WARNING, ACCELERATOR_PRODUCT_NAME ": module registration failed!"); return FAILURE; } #ifdef ZEND_WIN32 if (UNEXPECTED(accel_gen_uname_id() == FAILURE)) { zps_startup_failure("Unable to get user name", NULL, accelerator_remove_cb); return SUCCESS; } #endif #ifdef HAVE_HUGE_CODE_PAGES if (ZCG(accel_directives).huge_code_pages && (strcmp(sapi_module.name, "cli") == 0 || strcmp(sapi_module.name, "cli-server") == 0 || strcmp(sapi_module.name, "cgi-fcgi") == 0 || strcmp(sapi_module.name, "fpm-fcgi") == 0)) { accel_move_code_to_huge_pages(); } #endif /* no supported SAPI found - disable acceleration and stop initialization */ if (accel_find_sapi() == FAILURE) { accel_startup_ok = 0; if (!ZCG(accel_directives).enable_cli && strcmp(sapi_module.name, "cli") == 0) { zps_startup_failure("Opcode Caching is disabled for CLI", NULL, accelerator_remove_cb); } else { zps_startup_failure("Opcode Caching is only supported in Apache, FPM, FastCGI and LiteSpeed SAPIs", NULL, accelerator_remove_cb); } return SUCCESS; } if (ZCG(enabled) == 0) { return SUCCESS ; } orig_post_startup_cb = zend_post_startup_cb; zend_post_startup_cb = accel_post_startup; /* Prevent unloading */ extension->handle = 0; return SUCCESS; } static zend_result accel_post_startup(void) { zend_function *func; zend_ini_entry *ini_entry; if (orig_post_startup_cb) { zend_result (*cb)(void) = orig_post_startup_cb; orig_post_startup_cb = NULL; if (cb() != SUCCESS) { return FAILURE; } } /********************************************/ /* End of non-SHM dependent initializations */ /********************************************/ file_cache_only = ZCG(accel_directives).file_cache_only; if (!file_cache_only) { size_t shm_size = ZCG(accel_directives).memory_consumption; #ifdef HAVE_JIT size_t jit_size = 0; bool reattached = 0; if (JIT_G(enabled) && JIT_G(buffer_size) && zend_jit_check_support() == SUCCESS) { size_t page_size; # ifdef _WIN32 SYSTEM_INFO system_info; GetSystemInfo(&system_info); page_size = system_info.dwPageSize; # else page_size = getpagesize(); # endif if (!page_size || (page_size & (page_size - 1))) { zend_accel_error_noreturn(ACCEL_LOG_FATAL, "Failure to initialize shared memory structures - can't get page size."); abort(); } jit_size = JIT_G(buffer_size); jit_size = ZEND_MM_ALIGNED_SIZE_EX(jit_size, page_size); shm_size += jit_size; } switch (zend_shared_alloc_startup(shm_size, jit_size)) { #else switch (zend_shared_alloc_startup(shm_size, 0)) { #endif case ALLOC_SUCCESS: if (zend_accel_init_shm() == FAILURE) { accel_startup_ok = 0; return FAILURE; } break; case ALLOC_FAILURE: accel_startup_ok = 0; zend_accel_error_noreturn(ACCEL_LOG_FATAL, "Failure to initialize shared memory structures - probably not enough shared memory."); return SUCCESS; case SUCCESSFULLY_REATTACHED: #if defined(HAVE_JIT) && !defined(ZEND_WIN32) reattached = 1; #endif zend_shared_alloc_lock(); accel_shared_globals = (zend_accel_shared_globals *) ZSMMG(app_shared_globals); zend_interned_strings_set_request_storage_handlers(accel_new_interned_string_for_php, accel_init_interned_string_for_php); zend_shared_alloc_unlock(); break; case FAILED_REATTACHED: accel_startup_ok = 0; zend_accel_error_noreturn(ACCEL_LOG_FATAL, "Failure to initialize shared memory structures - can not reattach to exiting shared memory."); return SUCCESS; break; #if ENABLE_FILE_CACHE_FALLBACK case ALLOC_FALLBACK: zend_shared_alloc_lock(); file_cache_only = 1; fallback_process = 1; zend_shared_alloc_unlock(); goto file_cache_fallback; break; #endif } /* from this point further, shared memory is supposed to be OK */ /* remember the last restart time in the process memory */ ZCG(last_restart_time) = ZCSG(last_restart_time); zend_shared_alloc_lock(); #ifdef HAVE_JIT if (JIT_G(enabled)) { if (JIT_G(buffer_size) == 0 || !ZSMMG(reserved) || zend_jit_startup(ZSMMG(reserved), jit_size, reattached) != SUCCESS) { JIT_G(enabled) = 0; JIT_G(on) = 0; } } #endif zend_shared_alloc_save_state(); zend_shared_alloc_unlock(); SHM_PROTECT(); } else if (!ZCG(accel_directives).file_cache) { accel_startup_ok = 0; zend_accel_error_noreturn(ACCEL_LOG_FATAL, "opcache.file_cache_only is set without a proper setting of opcache.file_cache"); return SUCCESS; } else { #ifdef HAVE_JIT JIT_G(enabled) = 0; JIT_G(on) = 0; #endif accel_shared_globals = calloc(1, sizeof(zend_accel_shared_globals)); } #if ENABLE_FILE_CACHE_FALLBACK file_cache_fallback: #endif /* Override compiler */ accelerator_orig_compile_file = zend_compile_file; zend_compile_file = persistent_compile_file; /* Override stream opener function (to eliminate open() call caused by * include/require statements ) */ accelerator_orig_zend_stream_open_function = zend_stream_open_function; zend_stream_open_function = persistent_stream_open_function; /* Override path resolver function (to eliminate stat() calls caused by * include_once/require_once statements */ accelerator_orig_zend_resolve_path = zend_resolve_path; zend_resolve_path = persistent_zend_resolve_path; /* Override chdir() function */ if ((func = zend_hash_str_find_ptr(CG(function_table), "chdir", sizeof("chdir")-1)) != NULL && func->type == ZEND_INTERNAL_FUNCTION) { orig_chdir = func->internal_function.handler; func->internal_function.handler = ZEND_FN(accel_chdir); } ZCG(cwd) = NULL; ZCG(include_path) = NULL; /* Override "include_path" modifier callback */ if ((ini_entry = zend_hash_str_find_ptr(EG(ini_directives), "include_path", sizeof("include_path")-1)) != NULL) { ZCG(include_path) = ini_entry->value; orig_include_path_on_modify = ini_entry->on_modify; ini_entry->on_modify = accel_include_path_on_modify; } accel_startup_ok = 1; /* Override file_exists(), is_file() and is_readable() */ zend_accel_override_file_functions(); /* Load black list */ accel_blacklist.entries = NULL; if (ZCG(enabled) && accel_startup_ok && ZCG(accel_directives).user_blacklist_filename && *ZCG(accel_directives.user_blacklist_filename)) { zend_accel_blacklist_init(&accel_blacklist); zend_accel_blacklist_load(&accel_blacklist, ZCG(accel_directives.user_blacklist_filename)); } if (!file_cache_only && ZCG(accel_directives).interned_strings_buffer) { accel_use_shm_interned_strings(); } if (accel_finish_startup() != SUCCESS) { return FAILURE; } if (ZCG(enabled) && accel_startup_ok) { /* Override inheritance cache callbaks */ accelerator_orig_inheritance_cache_get = zend_inheritance_cache_get; accelerator_orig_inheritance_cache_add = zend_inheritance_cache_add; zend_inheritance_cache_get = zend_accel_inheritance_cache_get; zend_inheritance_cache_add = zend_accel_inheritance_cache_add; } return SUCCESS; } static void (*orig_post_shutdown_cb)(void); static void accel_post_shutdown(void) { zend_shared_alloc_shutdown(); } void accel_shutdown(void) { zend_ini_entry *ini_entry; bool _file_cache_only = 0; #ifdef HAVE_JIT zend_jit_shutdown(); #endif zend_accel_blacklist_shutdown(&accel_blacklist); if (!ZCG(enabled) || !accel_startup_ok) { #ifdef ZTS ts_free_id(accel_globals_id); #endif return; } if (ZCSG(preload_script)) { preload_shutdown(); } _file_cache_only = file_cache_only; accel_reset_pcre_cache(); #ifdef ZTS ts_free_id(accel_globals_id); #endif if (!_file_cache_only) { /* Delay SHM detach */ orig_post_shutdown_cb = zend_post_shutdown_cb; zend_post_shutdown_cb = accel_post_shutdown; } zend_compile_file = accelerator_orig_compile_file; zend_inheritance_cache_get = accelerator_orig_inheritance_cache_get; zend_inheritance_cache_add = accelerator_orig_inheritance_cache_add; if ((ini_entry = zend_hash_str_find_ptr(EG(ini_directives), "include_path", sizeof("include_path")-1)) != NULL) { ini_entry->on_modify = orig_include_path_on_modify; } } void zend_accel_schedule_restart(zend_accel_restart_reason reason) { const char *zend_accel_restart_reason_text[ACCEL_RESTART_USER + 1] = { "out of memory", "hash overflow", "user", }; if (ZCSG(restart_pending)) { /* don't schedule twice */ return; } zend_accel_error(ACCEL_LOG_DEBUG, "Restart Scheduled! Reason: %s", zend_accel_restart_reason_text[reason]); HANDLE_BLOCK_INTERRUPTIONS(); SHM_UNPROTECT(); ZCSG(restart_pending) = 1; ZCSG(restart_reason) = reason; ZCSG(cache_status_before_restart) = ZCSG(accelerator_enabled); ZCSG(accelerator_enabled) = 0; if (ZCG(accel_directives).force_restart_timeout) { ZCSG(force_restart_time) = zend_accel_get_time() + ZCG(accel_directives).force_restart_timeout; } else { ZCSG(force_restart_time) = 0; } SHM_PROTECT(); HANDLE_UNBLOCK_INTERRUPTIONS(); } /* this is needed because on WIN32 lock is not decreased unless ZCG(counted) is set */ #ifdef ZEND_WIN32 #define accel_deactivate_now() ZCG(counted) = 1; accel_deactivate_sub() #else #define accel_deactivate_now() accel_deactivate_sub() #endif /* ensures it is OK to read SHM if it's not OK (restart in progress) returns FAILURE if OK returns SUCCESS MUST call accelerator_shm_read_unlock after done lock operations */ int accelerator_shm_read_lock(void) { if (ZCG(counted)) { /* counted means we are holding read lock for SHM, so that nothing bad can happen */ return SUCCESS; } else { /* here accelerator is active but we do not hold SHM lock. This means restart was scheduled or is in progress now */ if (accel_activate_add() == FAILURE) { /* acquire usage lock */ return FAILURE; } /* Now if we weren't inside restart, restart would not begin until we remove usage lock */ if (ZCSG(restart_in_progress)) { /* we already were inside restart this means it's not safe to touch shm */ accel_deactivate_now(); /* drop usage lock */ return FAILURE; } ZCG(counted) = 1; } return SUCCESS; } /* must be called ONLY after SUCCESSFUL accelerator_shm_read_lock */ void accelerator_shm_read_unlock(void) { if (!ZCG(counted)) { /* counted is 0 - meaning we had to readlock manually, release readlock now */ accel_deactivate_now(); } } /* Preloading */ static HashTable *preload_scripts = NULL; static zend_op_array *(*preload_orig_compile_file)(zend_file_handle *file_handle, int type); static void preload_shutdown(void) { zval *zv; #if 0 if (EG(zend_constants)) { ZEND_HASH_REVERSE_FOREACH_VAL(EG(zend_constants), zv) { zend_constant *c = Z_PTR_P(zv); if (ZEND_CONSTANT_FLAGS(c) & CONST_PERSISTENT) { break; } } ZEND_HASH_FOREACH_END_DEL(); } #endif if (EG(function_table)) { ZEND_HASH_REVERSE_FOREACH_VAL(EG(function_table), zv) { zend_function *func = Z_PTR_P(zv); if (func->type == ZEND_INTERNAL_FUNCTION) { break; } } ZEND_HASH_FOREACH_END_DEL(); } if (EG(class_table)) { ZEND_HASH_REVERSE_FOREACH_VAL(EG(class_table), zv) { zend_class_entry *ce = Z_PTR_P(zv); if (ce->type == ZEND_INTERNAL_CLASS) { break; } } ZEND_HASH_FOREACH_END_DEL(); } } static void preload_activate(void) { if (ZCSG(preload_script)->ping_auto_globals_mask & ~ZCG(auto_globals_mask)) { zend_accel_set_auto_globals(ZCSG(preload_script)->ping_auto_globals_mask & ~ZCG(auto_globals_mask)); } } static void preload_restart(void) { zend_accel_hash_update(&ZCSG(hash), ZCSG(preload_script)->script.filename, 0, ZCSG(preload_script)); if (ZCSG(saved_scripts)) { zend_persistent_script **p = ZCSG(saved_scripts); while (*p) { zend_accel_hash_update(&ZCSG(hash), (*p)->script.filename, 0, *p); p++; } } } static size_t preload_try_strip_filename(zend_string *filename) { /*FIXME: better way to hanlde eval()'d code? see COMPILED_STRING_DESCRIPTION_FORMAT */ if (ZSTR_LEN(filename) > sizeof(" eval()'d code") && *(ZSTR_VAL(filename) + ZSTR_LEN(filename) - sizeof(" eval()'d code")) == ':') { const char *cfilename = ZSTR_VAL(filename); size_t cfilenamelen = ZSTR_LEN(filename) - sizeof(" eval()'d code") - 1 /*:*/; while (cfilenamelen && cfilename[--cfilenamelen] != '('); return cfilenamelen; } return 0; } static void preload_move_user_functions(HashTable *src, HashTable *dst) { Bucket *p; dtor_func_t orig_dtor = src->pDestructor; zend_string *filename = NULL; int copy = 0; src->pDestructor = NULL; zend_hash_extend(dst, dst->nNumUsed + src->nNumUsed, 0); ZEND_HASH_REVERSE_FOREACH_BUCKET(src, p) { zend_function *function = Z_PTR(p->val); if (EXPECTED(function->type == ZEND_USER_FUNCTION)) { if (function->op_array.filename != filename) { filename = function->op_array.filename; if (filename) { if (!(copy = zend_hash_exists(preload_scripts, filename))) { size_t eval_len = preload_try_strip_filename(filename); if (eval_len) { copy = zend_hash_str_exists(preload_scripts, ZSTR_VAL(filename), eval_len); } } } else { copy = 0; } } if (copy) { _zend_hash_append_ptr(dst, p->key, function); } else { orig_dtor(&p->val); } zend_hash_del_bucket(src, p); } else { break; } } ZEND_HASH_FOREACH_END(); src->pDestructor = orig_dtor; } static void preload_move_user_classes(HashTable *src, HashTable *dst) { Bucket *p; dtor_func_t orig_dtor = src->pDestructor; zend_string *filename = NULL; int copy = 0; src->pDestructor = NULL; zend_hash_extend(dst, dst->nNumUsed + src->nNumUsed, 0); ZEND_HASH_REVERSE_FOREACH_BUCKET(src, p) { zend_class_entry *ce = Z_PTR(p->val); if (EXPECTED(ce->type == ZEND_USER_CLASS)) { if (ce->info.user.filename != filename) { filename = ce->info.user.filename; if (filename) { if (!(copy = zend_hash_exists(preload_scripts, filename))) { size_t eval_len = preload_try_strip_filename(filename); if (eval_len) { copy = zend_hash_str_exists(preload_scripts, ZSTR_VAL(filename), eval_len); } } } else { copy = 0; } } if (copy) { _zend_hash_append(dst, p->key, &p->val); } else { orig_dtor(&p->val); } zend_hash_del_bucket(src, p); } else { break; } } ZEND_HASH_FOREACH_END(); src->pDestructor = orig_dtor; } static zend_op_array *preload_compile_file(zend_file_handle *file_handle, int type) { zend_op_array *op_array = preload_orig_compile_file(file_handle, type); if (op_array && op_array->refcount) { zend_persistent_script *script; script = create_persistent_script(); script->script.first_early_binding_opline = (uint32_t)-1; script->script.filename = zend_string_copy(op_array->filename); zend_string_hash_val(script->script.filename); script->script.main_op_array = *op_array; //??? efree(op_array->refcount); op_array->refcount = NULL; zend_hash_add_ptr(preload_scripts, script->script.filename, script); } return op_array; } static void preload_sort_classes(void *base, size_t count, size_t siz, compare_func_t compare, swap_func_t swp) { Bucket *b1 = base; Bucket *b2; Bucket *end = b1 + count; Bucket tmp; zend_class_entry *ce, *p; while (b1 < end) { try_again: ce = (zend_class_entry*)Z_PTR(b1->val); if (ce->parent && (ce->ce_flags & ZEND_ACC_LINKED)) { p = ce->parent; if (p->type == ZEND_USER_CLASS) { b2 = b1 + 1; while (b2 < end) { if (p == Z_PTR(b2->val)) { tmp = *b1; *b1 = *b2; *b2 = tmp; goto try_again; } b2++; } } } if (ce->num_interfaces && (ce->ce_flags & ZEND_ACC_LINKED)) { uint32_t i = 0; for (i = 0; i < ce->num_interfaces; i++) { p = ce->interfaces[i]; if (p->type == ZEND_USER_CLASS) { b2 = b1 + 1; while (b2 < end) { if (p == Z_PTR(b2->val)) { tmp = *b1; *b1 = *b2; *b2 = tmp; goto try_again; } b2++; } } } } b1++; } } static bool preload_needed_types_known(zend_class_entry *ce); static void get_unlinked_dependency(zend_class_entry *ce, const char **kind, const char **name) { zend_class_entry *p; *kind = "Unknown reason"; *name = ""; if (ce->parent_name) { zend_string *key = zend_string_tolower(ce->parent_name); p = zend_hash_find_ptr(EG(class_table), key); zend_string_release(key); if (!p) { *kind = "Unknown parent "; *name = ZSTR_VAL(ce->parent_name); return; } } if (ce->num_interfaces) { uint32_t i; for (i = 0; i < ce->num_interfaces; i++) { p = zend_hash_find_ptr(EG(class_table), ce->interface_names[i].lc_name); if (!p) { *kind = "Unknown interface "; *name = ZSTR_VAL(ce->interface_names[i].name); return; } } } if (ce->num_traits) { uint32_t i; for (i = 0; i < ce->num_traits; i++) { p = zend_hash_find_ptr(EG(class_table), ce->trait_names[i].lc_name); if (!p) { *kind = "Unknown trait "; *name = ZSTR_VAL(ce->trait_names[i].name); return; } } } if (!preload_needed_types_known(ce)) { *kind = "Unknown type dependencies"; return; } } static bool preload_try_resolve_constants(zend_class_entry *ce) { bool ok, changed, was_changed = 0; zend_class_constant *c; zval *val; EG(exception) = (void*)(uintptr_t)-1; /* prevent error reporting */ do { ok = 1; changed = 0; ZEND_HASH_FOREACH_PTR(&ce->constants_table, c) { val = &c->value; if (Z_TYPE_P(val) == IS_CONSTANT_AST) { if (EXPECTED(zval_update_constant_ex(val, c->ce) == SUCCESS)) { was_changed = changed = 1; } else { ok = 0; } } } ZEND_HASH_FOREACH_END(); if (ok) { ce->ce_flags &= ~ZEND_ACC_HAS_AST_CONSTANTS; } if (ce->default_properties_count) { uint32_t i; bool resolved = 1; for (i = 0; i < ce->default_properties_count; i++) { val = &ce->default_properties_table[i]; if (Z_TYPE_P(val) == IS_CONSTANT_AST) { zend_property_info *prop = ce->properties_info_table[i]; if (UNEXPECTED(zval_update_constant_ex(val, prop->ce) != SUCCESS)) { resolved = ok = 0; } } } if (resolved) { ce->ce_flags &= ~ZEND_ACC_HAS_AST_PROPERTIES; } } if (ce->default_static_members_count) { uint32_t count = ce->parent ? ce->default_static_members_count - ce->parent->default_static_members_count : ce->default_static_members_count; bool resolved = 1; val = ce->default_static_members_table + ce->default_static_members_count - 1; while (count) { if (Z_TYPE_P(val) == IS_CONSTANT_AST) { if (UNEXPECTED(zval_update_constant_ex(val, ce) != SUCCESS)) { resolved = ok = 0; } } val--; count--; } if (resolved) { ce->ce_flags &= ~ZEND_ACC_HAS_AST_STATICS; } } } while (changed && !ok); EG(exception) = NULL; CG(in_compilation) = 0; if (ok) { ce->ce_flags |= ZEND_ACC_CONSTANTS_UPDATED; } return ok || was_changed; } static zend_class_entry *preload_fetch_resolved_ce(zend_string *name) { zend_string *lcname = zend_string_tolower(name); zend_class_entry *ce = zend_hash_find_ptr(EG(class_table), lcname); zend_string_release(lcname); return ce; } static bool preload_try_resolve_property_types(zend_class_entry *ce) { bool ok = 1; if (ce->ce_flags & ZEND_ACC_HAS_TYPE_HINTS) { zend_property_info *prop; ZEND_HASH_FOREACH_PTR(&ce->properties_info, prop) { zend_type *single_type; ZEND_TYPE_FOREACH(prop->type, single_type) { if (ZEND_TYPE_HAS_NAME(*single_type)) { zend_class_entry *p = preload_fetch_resolved_ce(ZEND_TYPE_NAME(*single_type)); if (!p) { ok = 0; continue; } ZEND_TYPE_SET_CE(*single_type, p); } } ZEND_TYPE_FOREACH_END(); } ZEND_HASH_FOREACH_END(); if (ok) { ce->ce_flags |= ZEND_ACC_PROPERTY_TYPES_RESOLVED; } } return ok; } static bool preload_is_class_type_known(zend_class_entry *ce, zend_string *name) { if (zend_string_equals_literal_ci(name, "self") || zend_string_equals_literal_ci(name, "parent") || zend_string_equals_ci(name, ce->name)) { return 1; } zend_string *lcname = zend_string_tolower(name); bool known = zend_hash_exists(EG(class_table), lcname); zend_string_release(lcname); return known; } static bool preload_is_type_known(zend_class_entry *ce, zend_type *type) { zend_type *single_type; ZEND_TYPE_FOREACH(*type, single_type) { if (ZEND_TYPE_HAS_NAME(*single_type)) { if (!preload_is_class_type_known(ce, ZEND_TYPE_NAME(*single_type))) { return 0; } } } ZEND_TYPE_FOREACH_END(); return 1; } static bool preload_is_method_maybe_override(zend_class_entry *ce, zend_string *lcname) { zend_class_entry *p; if (ce->trait_aliases || ce->trait_precedences) { return 1; } if (ce->parent_name) { zend_string *key = zend_string_tolower(ce->parent_name); p = zend_hash_find_ptr(EG(class_table), key); zend_string_release(key); if (zend_hash_exists(&p->function_table, lcname)) { return 1; } } if (ce->num_interfaces) { uint32_t i; for (i = 0; i < ce->num_interfaces; i++) { zend_class_entry *p = zend_hash_find_ptr(EG(class_table), ce->interface_names[i].lc_name); if (zend_hash_exists(&p->function_table, lcname)) { return 1; } } } if (ce->num_traits) { uint32_t i; for (i = 0; i < ce->num_traits; i++) { zend_class_entry *p = zend_hash_find_ptr(EG(class_table), ce->trait_names[i].lc_name); if (zend_hash_exists(&p->function_table, lcname)) { return 1; } } } return 0; } static bool preload_needed_types_known(zend_class_entry *ce) { zend_function *fptr; zend_string *lcname; ZEND_HASH_FOREACH_STR_KEY_PTR(&ce->function_table, lcname, fptr) { uint32_t i; if (fptr->common.fn_flags & ZEND_ACC_HAS_RETURN_TYPE) { if (!preload_is_type_known(ce, &fptr->common.arg_info[-1].type) && preload_is_method_maybe_override(ce, lcname)) { return 0; } } for (i = 0; i < fptr->common.num_args; i++) { if (!preload_is_type_known(ce, &fptr->common.arg_info[i].type) && preload_is_method_maybe_override(ce, lcname)) { return 0; } } } ZEND_HASH_FOREACH_END(); return 1; } static void preload_link(void) { zval *zv; zend_persistent_script *script; zend_class_entry *ce, *parent, *p; zend_string *key; bool found, changed; uint32_t i; dtor_func_t orig_dtor; zend_function *function; /* Resolve class dependencies */ do { changed = 0; ZEND_HASH_REVERSE_FOREACH_VAL(EG(class_table), zv) { ce = Z_PTR_P(zv); if (ce->type == ZEND_INTERNAL_CLASS) { break; } if ((ce->ce_flags & (ZEND_ACC_TOP_LEVEL|ZEND_ACC_ANON_CLASS)) && !(ce->ce_flags & ZEND_ACC_LINKED)) { if (!(ce->ce_flags & ZEND_ACC_ANON_CLASS)) { key = zend_string_tolower(ce->name); if (zend_hash_exists(EG(class_table), key)) { zend_string_release(key); continue; } zend_string_release(key); } parent = NULL; if (ce->parent_name) { key = zend_string_tolower(ce->parent_name); parent = zend_hash_find_ptr(EG(class_table), key); zend_string_release(key); if (!parent) continue; } if (ce->num_interfaces) { found = 1; for (i = 0; i < ce->num_interfaces; i++) { p = zend_hash_find_ptr(EG(class_table), ce->interface_names[i].lc_name); if (!p) { found = 0; break; } } if (!found) continue; } if (ce->num_traits) { found = 1; for (i = 0; i < ce->num_traits; i++) { p = zend_hash_find_ptr(EG(class_table), ce->trait_names[i].lc_name); if (!p) { found = 0; break; } } if (!found) continue; } /* TODO: This is much more restrictive than necessary. We only need to actually * know the types for covariant checks, but don't need them if we can ensure * compatibility through a simple string comparison. We could improve this using * a more general version of zend_can_early_bind(). */ if (!preload_needed_types_known(ce)) { continue; } key = zend_string_tolower(ce->name); zv = zend_hash_set_bucket_key(EG(class_table), (Bucket*)zv, key); if (EXPECTED(zv)) { /* Set filename & lineno information for inheritance errors */ CG(in_compilation) = 1; CG(compiled_filename) = ce->info.user.filename; if (ce->parent_name && !ce->num_interfaces && !ce->num_traits && (parent->type == ZEND_INTERNAL_CLASS || parent->info.user.filename == ce->info.user.filename)) { /* simulate early binding */ CG(zend_lineno) = ce->info.user.line_end; } else { CG(zend_lineno) = ce->info.user.line_start; } ce = zend_do_link_class(ce, NULL, key); if (!ce) { ZEND_ASSERT(0 && "Class linking failed?"); } CG(in_compilation) = 0; CG(compiled_filename) = NULL; changed = 1; } zend_string_release(key); } } ZEND_HASH_FOREACH_END(); } while (changed); /* Resolve property types */ ZEND_HASH_REVERSE_FOREACH_VAL(EG(class_table), zv) { ce = Z_PTR_P(zv); if (ce->type == ZEND_INTERNAL_CLASS) { break; } if (!(ce->ce_flags & ZEND_ACC_PROPERTY_TYPES_RESOLVED)) { if (!(ce->ce_flags & ZEND_ACC_TRAIT)) { preload_try_resolve_property_types(ce); } } } ZEND_HASH_FOREACH_END(); do { changed = 0; ZEND_HASH_REVERSE_FOREACH_VAL(EG(class_table), zv) { ce = Z_PTR_P(zv); if (ce->type == ZEND_INTERNAL_CLASS) { break; } if (!(ce->ce_flags & ZEND_ACC_CONSTANTS_UPDATED)) { if (!(ce->ce_flags & ZEND_ACC_TRAIT)) { /* don't update traits */ CG(in_compilation) = 1; /* prevent autoloading */ if (preload_try_resolve_constants(ce)) { changed = 1; } CG(in_compilation) = 0; } } } ZEND_HASH_FOREACH_END(); } while (changed); /* Move unlinked clases (and with unresolved constants) back to scripts */ orig_dtor = EG(class_table)->pDestructor; EG(class_table)->pDestructor = NULL; ZEND_HASH_REVERSE_FOREACH_STR_KEY_VAL(EG(class_table), key, zv) { ce = Z_PTR_P(zv); if (ce->type == ZEND_INTERNAL_CLASS) { break; } if (!(ce->ce_flags & ZEND_ACC_LINKED)) { zend_string *key = zend_string_tolower(ce->name); if (!(ce->ce_flags & ZEND_ACC_ANON_CLASS) && zend_hash_exists(EG(class_table), key)) { zend_error_at( E_WARNING, ce->info.user.filename, ce->info.user.line_start, "Can't preload already declared class %s", ZSTR_VAL(ce->name)); } else { const char *kind, *name; get_unlinked_dependency(ce, &kind, &name); zend_error_at( E_WARNING, ce->info.user.filename, ce->info.user.line_start, "Can't preload unlinked class %s: %s%s", ZSTR_VAL(ce->name), kind, name); } zend_string_release(key); } else { continue; } ce->ce_flags &= ~ZEND_ACC_PRELOADED; ZEND_HASH_FOREACH_PTR(&ce->function_table, function) { if (EXPECTED(function->type == ZEND_USER_FUNCTION) && function->common.scope == ce) { function->common.fn_flags &= ~ZEND_ACC_PRELOADED; } } ZEND_HASH_FOREACH_END(); script = zend_hash_find_ptr(preload_scripts, ce->info.user.filename); ZEND_ASSERT(script); zend_hash_add(&script->script.class_table, key, zv); ZVAL_UNDEF(zv); zend_string_release(key); EG(class_table)->nNumOfElements--; } ZEND_HASH_FOREACH_END(); EG(class_table)->pDestructor = orig_dtor; zend_hash_rehash(EG(class_table)); /* Remove DECLARE opcodes */ ZEND_HASH_FOREACH_PTR(preload_scripts, script) { zend_op_array *op_array = &script->script.main_op_array; zend_op *opline = op_array->opcodes; zend_op *end = opline + op_array->last; while (opline != end) { switch (opline->opcode) { case ZEND_DECLARE_CLASS: case ZEND_DECLARE_CLASS_DELAYED: key = Z_STR_P(RT_CONSTANT(opline, opline->op1) + 1); if (!zend_hash_exists(&script->script.class_table, key)) { MAKE_NOP(opline); } break; } opline++; } if (op_array->fn_flags & ZEND_ACC_EARLY_BINDING) { script->script.first_early_binding_opline = zend_build_delayed_early_binding_list(op_array); if (script->script.first_early_binding_opline == (uint32_t)-1) { op_array->fn_flags &= ~ZEND_ACC_EARLY_BINDING; } } } ZEND_HASH_FOREACH_END(); } static inline int preload_update_class_constants(zend_class_entry *ce) { /* This is a separate function to work around what appears to be a bug in GCC * maybe-uninitialized analysis. */ int result; zend_try { result = preload_try_resolve_constants(ce) ? SUCCESS : FAILURE; } zend_catch { result = FAILURE; } zend_end_try(); return result; } static zend_class_entry *preload_load_prop_type(zend_property_info *prop, zend_string *name) { zend_class_entry *ce; if (zend_string_equals_literal_ci(name, "self")) { ce = prop->ce; } else if (zend_string_equals_literal_ci(name, "parent")) { ce = prop->ce->parent; } else { ce = zend_lookup_class(name); } return ce; } static void preload_ensure_classes_loadable(void) { /* Run this in a loop, because additional classes may be loaded while updating constants etc. */ uint32_t checked_classes_idx = 0; while (1) { zend_class_entry *ce; uint32_t num_classes = zend_hash_num_elements(EG(class_table)); if (num_classes == checked_classes_idx) { return; } ZEND_HASH_REVERSE_FOREACH_PTR(EG(class_table), ce) { if (ce->type == ZEND_INTERNAL_CLASS || _idx == checked_classes_idx) { break; } if (!(ce->ce_flags & ZEND_ACC_LINKED)) { /* Only require that already linked classes are loadable, we'll properly check * things when linking additional classes. */ continue; } if (!(ce->ce_flags & ZEND_ACC_CONSTANTS_UPDATED)) { preload_update_class_constants(ce); } if (!(ce->ce_flags & ZEND_ACC_PROPERTY_TYPES_RESOLVED)) { if (ce->ce_flags & ZEND_ACC_HAS_TYPE_HINTS) { zend_property_info *prop; ZEND_HASH_FOREACH_PTR(&ce->properties_info, prop) { zend_type *single_type; ZEND_TYPE_FOREACH(prop->type, single_type) { if (ZEND_TYPE_HAS_NAME(*single_type)) { zend_class_entry *ce = preload_load_prop_type( prop, ZEND_TYPE_NAME(*single_type)); if (ce) { ZEND_TYPE_SET_CE(*single_type, ce); } } } ZEND_TYPE_FOREACH_END(); } ZEND_HASH_FOREACH_END(); } ce->ce_flags |= ZEND_ACC_PROPERTY_TYPES_RESOLVED; } } ZEND_HASH_FOREACH_END(); checked_classes_idx = num_classes; } } static zend_string *preload_resolve_path(zend_string *filename) { if (is_stream_path(ZSTR_VAL(filename))) { return NULL; } return zend_resolve_path(filename); } static void preload_remove_empty_includes(void) { zend_persistent_script *script; bool changed; /* mark all as empty */ ZEND_HASH_FOREACH_PTR(preload_scripts, script) { script->empty = 1; } ZEND_HASH_FOREACH_END(); /* find non empty scripts */ do { changed = 0; ZEND_HASH_FOREACH_PTR(preload_scripts, script) { if (script->empty) { int empty = 1; zend_op *opline = script->script.main_op_array.opcodes; zend_op *end = opline + script->script.main_op_array.last; while (opline < end) { if (opline->opcode == ZEND_INCLUDE_OR_EVAL && opline->extended_value != ZEND_EVAL && opline->op1_type == IS_CONST && Z_TYPE_P(RT_CONSTANT(opline, opline->op1)) == IS_STRING) { zend_string *resolved_path = preload_resolve_path(Z_STR_P(RT_CONSTANT(opline, opline->op1))); if (resolved_path) { zend_persistent_script *incl = zend_hash_find_ptr(preload_scripts, resolved_path); zend_string_release(resolved_path); if (!incl || !incl->empty) { empty = 0; break; } } else { empty = 0; break; } } else if (opline->opcode != ZEND_NOP && opline->opcode != ZEND_RETURN && opline->opcode != ZEND_HANDLE_EXCEPTION) { empty = 0; break; } opline++; } if (!empty) { script->empty = 0; changed = 1; } } } ZEND_HASH_FOREACH_END(); } while (changed); /* remove empty includes */ ZEND_HASH_FOREACH_PTR(preload_scripts, script) { zend_op *opline = script->script.main_op_array.opcodes; zend_op *end = opline + script->script.main_op_array.last; while (opline < end) { if (opline->opcode == ZEND_INCLUDE_OR_EVAL && opline->extended_value != ZEND_EVAL && opline->op1_type == IS_CONST && Z_TYPE_P(RT_CONSTANT(opline, opline->op1)) == IS_STRING) { zend_string *resolved_path = preload_resolve_path(Z_STR_P(RT_CONSTANT(opline, opline->op1))); if (resolved_path) { zend_persistent_script *incl = zend_hash_find_ptr(preload_scripts, resolved_path); if (incl && incl->empty) { MAKE_NOP(opline); } else { if (!IS_ABSOLUTE_PATH(Z_STRVAL_P(RT_CONSTANT(opline, opline->op1)), Z_STRLEN_P(RT_CONSTANT(opline, opline->op1)))) { /* replace relative patch with absolute one */ zend_string_release(Z_STR_P(RT_CONSTANT(opline, opline->op1))); ZVAL_STR_COPY(RT_CONSTANT(opline, opline->op1), resolved_path); } } zend_string_release(resolved_path); } } opline++; } } ZEND_HASH_FOREACH_END(); } static void preload_register_trait_methods(zend_class_entry *ce) { zend_op_array *op_array; ZEND_HASH_FOREACH_PTR(&ce->function_table, op_array) { if (!(op_array->fn_flags & ZEND_ACC_TRAIT_CLONE)) { ZEND_ASSERT(op_array->refcount && "Must have refcount pointer"); zend_shared_alloc_register_xlat_entry(op_array->refcount, op_array); } } ZEND_HASH_FOREACH_END(); } static void preload_fix_trait_methods(zend_class_entry *ce) { zend_op_array *op_array; ZEND_HASH_FOREACH_PTR(&ce->function_table, op_array) { if (op_array->fn_flags & ZEND_ACC_TRAIT_CLONE) { zend_op_array *orig_op_array = zend_shared_alloc_get_xlat_entry(op_array->refcount); ZEND_ASSERT(orig_op_array && "Must be in xlat table"); zend_string *function_name = op_array->function_name; zend_class_entry *scope = op_array->scope; uint32_t fn_flags = op_array->fn_flags; zend_function *prototype = op_array->prototype; HashTable *ht = op_array->static_variables; *op_array = *orig_op_array; op_array->function_name = function_name; op_array->scope = scope; op_array->fn_flags = fn_flags; op_array->prototype = prototype; op_array->static_variables = ht; } } ZEND_HASH_FOREACH_END(); } static int preload_optimize(zend_persistent_script *script) { zend_class_entry *ce; zend_persistent_script *tmp_script; zend_shared_alloc_init_xlat_table(); ZEND_HASH_FOREACH_PTR(&script->script.class_table, ce) { if (ce->ce_flags & ZEND_ACC_TRAIT) { preload_register_trait_methods(ce); } } ZEND_HASH_FOREACH_END(); ZEND_HASH_FOREACH_PTR(preload_scripts, tmp_script) { ZEND_HASH_FOREACH_PTR(&tmp_script->script.class_table, ce) { if (ce->ce_flags & ZEND_ACC_TRAIT) { preload_register_trait_methods(ce); } } ZEND_HASH_FOREACH_END(); } ZEND_HASH_FOREACH_END(); if (!zend_optimize_script(&script->script, ZCG(accel_directives).optimization_level, ZCG(accel_directives).opt_debug_level)) { return FAILURE; } ZEND_HASH_FOREACH_PTR(&script->script.class_table, ce) { preload_fix_trait_methods(ce); } ZEND_HASH_FOREACH_END(); ZEND_HASH_FOREACH_PTR(preload_scripts, script) { ZEND_HASH_FOREACH_PTR(&script->script.class_table, ce) { preload_fix_trait_methods(ce); } ZEND_HASH_FOREACH_END(); } ZEND_HASH_FOREACH_END(); zend_shared_alloc_destroy_xlat_table(); ZEND_HASH_FOREACH_PTR(preload_scripts, script) { if (!zend_optimize_script(&script->script, ZCG(accel_directives).optimization_level, ZCG(accel_directives).opt_debug_level)) { return FAILURE; } } ZEND_HASH_FOREACH_END(); return SUCCESS; } static zend_persistent_script* preload_script_in_shared_memory(zend_persistent_script *new_persistent_script) { zend_accel_hash_entry *bucket; uint32_t memory_used; uint32_t checkpoint; if (zend_accel_hash_is_full(&ZCSG(hash))) { zend_accel_error_noreturn(ACCEL_LOG_FATAL, "Not enough entries in hash table for preloading. Consider increasing the value for the opcache.max_accelerated_files directive in php.ini."); return NULL; } checkpoint = zend_shared_alloc_checkpoint_xlat_table(); /* Calculate the required memory size */ memory_used = zend_accel_script_persist_calc(new_persistent_script, 1); /* Allocate shared memory */ #if defined(__AVX__) || defined(__SSE2__) /* Align to 64-byte boundary */ ZCG(mem) = zend_shared_alloc(memory_used + 64); if (ZCG(mem)) { ZCG(mem) = (void*)(((zend_uintptr_t)ZCG(mem) + 63L) & ~63L); #if defined(__x86_64__) memset(ZCG(mem), 0, memory_used); #elif defined(__AVX__) { char *p = (char*)ZCG(mem); char *end = p + memory_used; __m256i ymm0 = _mm256_setzero_si256(); while (p < end) { _mm256_store_si256((__m256i*)p, ymm0); _mm256_store_si256((__m256i*)(p+32), ymm0); p += 64; } } #else { char *p = (char*)ZCG(mem); char *end = p + memory_used; __m128i xmm0 = _mm_setzero_si128(); while (p < end) { _mm_store_si128((__m128i*)p, xmm0); _mm_store_si128((__m128i*)(p+16), xmm0); _mm_store_si128((__m128i*)(p+32), xmm0); _mm_store_si128((__m128i*)(p+48), xmm0); p += 64; } } #endif } #else ZCG(mem) = zend_shared_alloc(memory_used); if (ZCG(mem)) { memset(ZCG(mem), 0, memory_used); } #endif if (!ZCG(mem)) { zend_accel_error_noreturn(ACCEL_LOG_FATAL, "Not enough shared memory for preloading. Consider increasing the value for the opcache.memory_consumption directive in php.ini."); return NULL; } zend_shared_alloc_restore_xlat_table(checkpoint); /* Copy into shared memory */ new_persistent_script = zend_accel_script_persist(new_persistent_script, 1); new_persistent_script->is_phar = is_phar_file(new_persistent_script->script.filename); /* Consistency check */ if ((char*)new_persistent_script->mem + new_persistent_script->size != (char*)ZCG(mem)) { zend_accel_error( ((char*)new_persistent_script->mem + new_persistent_script->size < (char*)ZCG(mem)) ? ACCEL_LOG_ERROR : ACCEL_LOG_WARNING, "Internal error: wrong size calculation: %s start=" ZEND_ADDR_FMT ", end=" ZEND_ADDR_FMT ", real=" ZEND_ADDR_FMT "\n", ZSTR_VAL(new_persistent_script->script.filename), (size_t)new_persistent_script->mem, (size_t)((char *)new_persistent_script->mem + new_persistent_script->size), (size_t)ZCG(mem)); } new_persistent_script->dynamic_members.checksum = zend_accel_script_checksum(new_persistent_script); /* store script structure in the hash table */ bucket = zend_accel_hash_update(&ZCSG(hash), new_persistent_script->script.filename, 0, new_persistent_script); if (bucket) { zend_accel_error(ACCEL_LOG_INFO, "Cached script '%s'", ZSTR_VAL(new_persistent_script->script.filename)); } new_persistent_script->dynamic_members.memory_consumption = ZEND_ALIGNED_SIZE(new_persistent_script->size); return new_persistent_script; } static void preload_load(void) { /* Load into process tables */ zend_script *script = &ZCSG(preload_script)->script; if (zend_hash_num_elements(&script->function_table)) { Bucket *p = script->function_table.arData; Bucket *end = p + script->function_table.nNumUsed; zend_hash_extend(CG(function_table), CG(function_table)->nNumUsed + script->function_table.nNumUsed, 0); for (; p != end; p++) { _zend_hash_append_ptr_ex(CG(function_table), p->key, Z_PTR(p->val), 1); } } if (zend_hash_num_elements(&script->class_table)) { Bucket *p = script->class_table.arData; Bucket *end = p + script->class_table.nNumUsed; zend_hash_extend(CG(class_table), CG(class_table)->nNumUsed + script->class_table.nNumUsed, 0); for (; p != end; p++) { _zend_hash_append_ex(CG(class_table), p->key, &p->val, 1); } } if (EG(zend_constants)) { EG(persistent_constants_count) = EG(zend_constants)->nNumUsed; } if (EG(function_table)) { EG(persistent_functions_count) = EG(function_table)->nNumUsed; } if (EG(class_table)) { EG(persistent_classes_count) = EG(class_table)->nNumUsed; } if (CG(map_ptr_last) != ZCSG(map_ptr_last)) { size_t old_map_ptr_last = CG(map_ptr_last); CG(map_ptr_last) = ZCSG(map_ptr_last); CG(map_ptr_size) = ZEND_MM_ALIGNED_SIZE_EX(CG(map_ptr_last) + 1, 4096); ZEND_MAP_PTR_SET_REAL_BASE(CG(map_ptr_base), perealloc(ZEND_MAP_PTR_REAL_BASE(CG(map_ptr_base)), CG(map_ptr_size) * sizeof(void*), 1)); memset((void **) ZEND_MAP_PTR_REAL_BASE(CG(map_ptr_base)) + old_map_ptr_last, 0, (CG(map_ptr_last) - old_map_ptr_last) * sizeof(void *)); } } static zend_result preload_autoload(zend_string *filename) { zend_persistent_script *persistent_script; zend_op_array *op_array; zend_execute_data *old_execute_data; zend_class_entry *old_fake_scope; bool do_bailout = 0; int ret = SUCCESS; if (zend_hash_exists(&EG(included_files), filename)) { return FAILURE; } persistent_script = zend_accel_hash_find(&ZCSG(hash), filename); if (!persistent_script) { return FAILURE; } zend_hash_add_empty_element(&EG(included_files), filename); if (persistent_script->ping_auto_globals_mask & ~ZCG(auto_globals_mask)) { zend_accel_set_auto_globals(persistent_script->ping_auto_globals_mask & ~ZCG(auto_globals_mask)); } op_array = zend_accel_load_script(persistent_script, 1); if (!op_array) { return FAILURE; } /* Execute in global context */ old_execute_data = EG(current_execute_data); EG(current_execute_data) = NULL; old_fake_scope = EG(fake_scope); EG(fake_scope) = NULL; zend_exception_save(); zend_try { zend_execute(op_array, NULL); } zend_catch { do_bailout = 1; } zend_end_try(); if (EG(exception)) { ret = FAILURE; } zend_exception_restore(); EG(fake_scope) = old_fake_scope; EG(current_execute_data) = old_execute_data; while (old_execute_data) { if (old_execute_data->func && (ZEND_CALL_INFO(old_execute_data) & ZEND_CALL_HAS_SYMBOL_TABLE)) { if (old_execute_data->symbol_table == &EG(symbol_table)) { zend_attach_symbol_table(old_execute_data); } break; } old_execute_data = old_execute_data->prev_execute_data; } destroy_op_array(op_array); efree_size(op_array, sizeof(zend_op_array)); if (do_bailout) { zend_bailout(); } return ret; } static int accel_preload(const char *config, bool in_child) { zend_file_handle file_handle; int ret; char *orig_open_basedir; size_t orig_map_ptr_last; zval *zv; uint32_t orig_compiler_options; ZCG(enabled) = 0; ZCG(accelerator_enabled) = 0; orig_open_basedir = PG(open_basedir); PG(open_basedir) = NULL; preload_orig_compile_file = accelerator_orig_compile_file; accelerator_orig_compile_file = preload_compile_file; orig_map_ptr_last = CG(map_ptr_last); /* Compile and execute proloading script */ zend_stream_init_filename(&file_handle, (char *) config); preload_scripts = emalloc(sizeof(HashTable)); zend_hash_init(preload_scripts, 0, NULL, NULL, 0); orig_compiler_options = CG(compiler_options); if (in_child) { CG(compiler_options) |= ZEND_COMPILE_PRELOAD_IN_CHILD; } CG(compiler_options) |= ZEND_COMPILE_PRELOAD; CG(compiler_options) |= ZEND_COMPILE_HANDLE_OP_ARRAY; CG(compiler_options) |= ZEND_COMPILE_DELAYED_BINDING; CG(compiler_options) |= ZEND_COMPILE_NO_CONSTANT_SUBSTITUTION; CG(compiler_options) |= ZEND_COMPILE_IGNORE_OTHER_FILES; zend_try { zend_op_array *op_array; ret = SUCCESS; op_array = zend_compile_file(&file_handle, ZEND_REQUIRE); if (file_handle.opened_path) { zend_hash_add_empty_element(&EG(included_files), file_handle.opened_path); } zend_destroy_file_handle(&file_handle); if (op_array) { zend_execute(op_array, NULL); zend_exception_restore(); if (UNEXPECTED(EG(exception))) { if (Z_TYPE(EG(user_exception_handler)) != IS_UNDEF) { zend_user_exception_handler(); } if (EG(exception)) { ret = zend_exception_error(EG(exception), E_ERROR); if (ret == FAILURE) { CG(unclean_shutdown) = 1; } } } destroy_op_array(op_array); efree_size(op_array, sizeof(zend_op_array)); } else { if (EG(exception)) { zend_exception_error(EG(exception), E_ERROR); } CG(unclean_shutdown) = 1; ret = FAILURE; } if (ret == SUCCESS) { preload_ensure_classes_loadable(); } } zend_catch { ret = FAILURE; } zend_end_try(); PG(open_basedir) = orig_open_basedir; accelerator_orig_compile_file = preload_orig_compile_file; ZCG(enabled) = 1; zend_destroy_file_handle(&file_handle); if (ret == SUCCESS) { zend_persistent_script *script; int ping_auto_globals_mask; int i; if (PG(auto_globals_jit)) { ping_auto_globals_mask = zend_accel_get_auto_globals(); } /* Cleanup executor */ EG(flags) |= EG_FLAGS_IN_SHUTDOWN; php_call_shutdown_functions(); zend_call_destructors(); php_output_end_all(); php_free_shutdown_functions(); /* Release stored values to avoid dangling pointers */ zend_hash_graceful_reverse_destroy(&EG(symbol_table)); zend_hash_init(&EG(symbol_table), 0, NULL, ZVAL_PTR_DTOR, 0); #if ZEND_DEBUG if (gc_enabled() && !CG(unclean_shutdown)) { gc_collect_cycles(); } #endif zend_objects_store_free_object_storage(&EG(objects_store), 1); /* Cleanup static variables of preloaded functions */ ZEND_HASH_REVERSE_FOREACH_VAL(EG(function_table), zv) { zend_op_array *op_array = Z_PTR_P(zv); if (op_array->type == ZEND_INTERNAL_FUNCTION) { break; } ZEND_ASSERT(op_array->fn_flags & ZEND_ACC_PRELOADED); if (op_array->static_variables) { HashTable *ht = ZEND_MAP_PTR_GET(op_array->static_variables_ptr); if (ht) { ZEND_ASSERT(GC_REFCOUNT(ht) == 1); zend_array_destroy(ht); ZEND_MAP_PTR_SET(op_array->static_variables_ptr, NULL); } } } ZEND_HASH_FOREACH_END(); /* Cleanup static properties and variables of preloaded classes */ ZEND_HASH_REVERSE_FOREACH_VAL(EG(class_table), zv) { zend_class_entry *ce = Z_PTR_P(zv); if (ce->type == ZEND_INTERNAL_CLASS) { break; } ZEND_ASSERT(ce->ce_flags & ZEND_ACC_PRELOADED); if (ce->default_static_members_count) { zend_cleanup_internal_class_data(ce); if (ce->ce_flags & ZEND_ACC_HAS_AST_STATICS) { ce->ce_flags &= ~ZEND_ACC_CONSTANTS_UPDATED; } } if (ce->ce_flags & ZEND_HAS_STATIC_IN_METHODS) { zend_op_array *op_array; ZEND_HASH_FOREACH_PTR(&ce->function_table, op_array) { if (op_array->type == ZEND_USER_FUNCTION) { if (op_array->static_variables) { HashTable *ht = ZEND_MAP_PTR_GET(op_array->static_variables_ptr); if (ht) { if (GC_DELREF(ht) == 0) { zend_array_destroy(ht); } ZEND_MAP_PTR_SET(op_array->static_variables_ptr, NULL); } } } } ZEND_HASH_FOREACH_END(); } } ZEND_HASH_FOREACH_END(); CG(map_ptr_last) = orig_map_ptr_last; if (EG(full_tables_cleanup)) { zend_accel_error_noreturn(ACCEL_LOG_FATAL, "Preloading is not compatible with dl() function."); ret = FAILURE; goto finish; } /* Inheritance errors may be thrown during linking */ zend_try { preload_link(); } zend_catch { CG(map_ptr_last) = orig_map_ptr_last; ret = FAILURE; goto finish; } zend_end_try(); preload_remove_empty_includes(); /* Don't preload constants */ if (EG(zend_constants)) { zend_string *key; zval *zv; /* Remember __COMPILER_HALT_OFFSET__(s) */ ZEND_HASH_FOREACH_PTR(preload_scripts, script) { zend_execute_data *orig_execute_data = EG(current_execute_data); zend_execute_data fake_execute_data; zval *offset; memset(&fake_execute_data, 0, sizeof(fake_execute_data)); fake_execute_data.func = (zend_function*)&script->script.main_op_array; EG(current_execute_data) = &fake_execute_data; if ((offset = zend_get_constant_str("__COMPILER_HALT_OFFSET__", sizeof("__COMPILER_HALT_OFFSET__") - 1)) != NULL) { script->compiler_halt_offset = Z_LVAL_P(offset); } EG(current_execute_data) = orig_execute_data; } ZEND_HASH_FOREACH_END(); ZEND_HASH_REVERSE_FOREACH_STR_KEY_VAL(EG(zend_constants), key, zv) { zend_constant *c = Z_PTR_P(zv); if (ZEND_CONSTANT_FLAGS(c) & CONST_PERSISTENT) { break; } EG(zend_constants)->pDestructor(zv); zend_string_release(key); } ZEND_HASH_FOREACH_END_DEL(); } script = create_persistent_script(); script->ping_auto_globals_mask = ping_auto_globals_mask; /* Store all functions and classes in a single pseudo-file */ CG(compiled_filename) = zend_string_init("$PRELOAD$", sizeof("$PRELOAD$") - 1, 0); #if ZEND_USE_ABS_CONST_ADDR init_op_array(&script->script.main_op_array, ZEND_USER_FUNCTION, 1); #else init_op_array(&script->script.main_op_array, ZEND_USER_FUNCTION, 2); #endif script->script.main_op_array.fn_flags |= ZEND_ACC_DONE_PASS_TWO; script->script.main_op_array.last = 1; script->script.main_op_array.last_literal = 1; #if ZEND_USE_ABS_CONST_ADDR script->script.main_op_array.literals = (zval*)emalloc(sizeof(zval)); #else script->script.main_op_array.literals = (zval*)(script->script.main_op_array.opcodes + 1); #endif ZVAL_NULL(script->script.main_op_array.literals); memset(script->script.main_op_array.opcodes, 0, sizeof(zend_op)); script->script.main_op_array.opcodes[0].opcode = ZEND_RETURN; script->script.main_op_array.opcodes[0].op1_type = IS_CONST; script->script.main_op_array.opcodes[0].op1.constant = 0; ZEND_PASS_TWO_UPDATE_CONSTANT(&script->script.main_op_array, script->script.main_op_array.opcodes, script->script.main_op_array.opcodes[0].op1); zend_vm_set_opcode_handler(script->script.main_op_array.opcodes); script->script.filename = CG(compiled_filename); CG(compiled_filename) = NULL; script->script.first_early_binding_opline = (uint32_t)-1; preload_move_user_functions(CG(function_table), &script->script.function_table); preload_move_user_classes(CG(class_table), &script->script.class_table); zend_hash_sort_ex(&script->script.class_table, preload_sort_classes, NULL, 0); if (preload_optimize(script) != SUCCESS) { zend_accel_error_noreturn(ACCEL_LOG_FATAL, "Optimization error during preloading!"); return FAILURE; } zend_shared_alloc_init_xlat_table(); HANDLE_BLOCK_INTERRUPTIONS(); SHM_UNPROTECT(); ZCSG(preload_script) = preload_script_in_shared_memory(script); SHM_PROTECT(); HANDLE_UNBLOCK_INTERRUPTIONS(); preload_load(); /* Store individual scripts with unlinked classes */ HANDLE_BLOCK_INTERRUPTIONS(); SHM_UNPROTECT(); i = 0; ZCSG(saved_scripts) = zend_shared_alloc((zend_hash_num_elements(preload_scripts) + 1) * sizeof(void*)); ZEND_HASH_FOREACH_PTR(preload_scripts, script) { if (zend_hash_num_elements(&script->script.class_table) > 1) { zend_hash_sort_ex(&script->script.class_table, preload_sort_classes, NULL, 0); } ZCSG(saved_scripts)[i++] = preload_script_in_shared_memory(script); } ZEND_HASH_FOREACH_END(); ZCSG(saved_scripts)[i] = NULL; zend_shared_alloc_save_state(); accel_interned_strings_save_state(); SHM_PROTECT(); HANDLE_UNBLOCK_INTERRUPTIONS(); zend_shared_alloc_destroy_xlat_table(); zend_preload_autoload = preload_autoload; } else { CG(map_ptr_last) = orig_map_ptr_last; } finish: CG(compiler_options) = orig_compiler_options; zend_hash_destroy(preload_scripts); efree(preload_scripts); preload_scripts = NULL; return ret; } static size_t preload_ub_write(const char *str, size_t str_length) { return fwrite(str, 1, str_length, stdout); } static void preload_flush(void *server_context) { fflush(stdout); } static int preload_header_handler(sapi_header_struct *h, sapi_header_op_enum op, sapi_headers_struct *s) { return 0; } static int preload_send_headers(sapi_headers_struct *sapi_headers) { return SAPI_HEADER_SENT_SUCCESSFULLY; } static void preload_send_header(sapi_header_struct *sapi_header, void *server_context) { } static int accel_finish_startup(void) { if (!ZCG(enabled) || !accel_startup_ok) { return SUCCESS; } if (ZCG(accel_directives).preload && *ZCG(accel_directives).preload) { #ifdef ZEND_WIN32 zend_accel_error_noreturn(ACCEL_LOG_ERROR, "Preloading is not supported on Windows"); return FAILURE; #else int in_child = 0; int ret = SUCCESS; int rc; int orig_error_reporting; int (*orig_activate)(void) = sapi_module.activate; int (*orig_deactivate)(void) = sapi_module.deactivate; void (*orig_register_server_variables)(zval *track_vars_array) = sapi_module.register_server_variables; int (*orig_header_handler)(sapi_header_struct *sapi_header, sapi_header_op_enum op, sapi_headers_struct *sapi_headers) = sapi_module.header_handler; int (*orig_send_headers)(sapi_headers_struct *sapi_headers) = sapi_module.send_headers; void (*orig_send_header)(sapi_header_struct *sapi_header, void *server_context)= sapi_module.send_header; char *(*orig_getenv)(const char *name, size_t name_len) = sapi_module.getenv; size_t (*orig_ub_write)(const char *str, size_t str_length) = sapi_module.ub_write; void (*orig_flush)(void *server_context) = sapi_module.flush; #ifdef ZEND_SIGNALS bool old_reset_signals = SIGG(reset); #endif if (UNEXPECTED(file_cache_only)) { zend_accel_error(ACCEL_LOG_WARNING, "Preloading doesn't work in \"file_cache_only\" mode"); return SUCCESS; } /* exclusive lock */ zend_shared_alloc_lock(); if (ZCSG(preload_script)) { /* Preloading was done in another process */ preload_load(); zend_shared_alloc_unlock(); return SUCCESS; } if (geteuid() == 0) { pid_t pid; struct passwd *pw; if (!ZCG(accel_directives).preload_user || !*ZCG(accel_directives).preload_user) { zend_shared_alloc_unlock(); zend_accel_error_noreturn(ACCEL_LOG_FATAL, "\"opcache.preload_user\" has not been defined"); return FAILURE; } pw = getpwnam(ZCG(accel_directives).preload_user); if (pw == NULL) { zend_shared_alloc_unlock(); zend_accel_error_noreturn(ACCEL_LOG_FATAL, "Preloading failed to getpwnam(\"%s\")", ZCG(accel_directives).preload_user); return FAILURE; } pid = fork(); if (pid == -1) { zend_shared_alloc_unlock(); zend_accel_error_noreturn(ACCEL_LOG_FATAL, "Preloading failed to fork()"); return FAILURE; } else if (pid == 0) { /* children */ if (setgid(pw->pw_gid) < 0) { zend_accel_error(ACCEL_LOG_WARNING, "Preloading failed to setgid(%d)", pw->pw_gid); exit(1); } if (initgroups(pw->pw_name, pw->pw_gid) < 0) { zend_accel_error(ACCEL_LOG_WARNING, "Preloading failed to initgroups(\"%s\", %d)", pw->pw_name, pw->pw_uid); exit(1); } if (setuid(pw->pw_uid) < 0) { zend_accel_error(ACCEL_LOG_WARNING, "Preloading failed to setuid(%d)", pw->pw_uid); exit(1); } in_child = 1; } else { /* parent */ int status; if (waitpid(pid, &status, 0) < 0) { zend_shared_alloc_unlock(); zend_accel_error_noreturn(ACCEL_LOG_FATAL, "Preloading failed to waitpid(%d)", pid); return FAILURE; } if (ZCSG(preload_script)) { preload_load(); } zend_shared_alloc_unlock(); if (WIFEXITED(status) && WEXITSTATUS(status) == 0) { return SUCCESS; } else { return FAILURE; } } } else { if (ZCG(accel_directives).preload_user && *ZCG(accel_directives).preload_user) { zend_accel_error(ACCEL_LOG_WARNING, "\"opcache.preload_user\" is ignored"); } } sapi_module.activate = NULL; sapi_module.deactivate = NULL; sapi_module.register_server_variables = NULL; sapi_module.header_handler = preload_header_handler; sapi_module.send_headers = preload_send_headers; sapi_module.send_header = preload_send_header; sapi_module.getenv = NULL; sapi_module.ub_write = preload_ub_write; sapi_module.flush = preload_flush; zend_interned_strings_switch_storage(1); #ifdef ZEND_SIGNALS SIGG(reset) = 0; #endif orig_error_reporting = EG(error_reporting); EG(error_reporting) = 0; rc = php_request_startup(); EG(error_reporting) = orig_error_reporting; if (rc == SUCCESS) { bool orig_report_memleaks; /* don't send headers */ SG(headers_sent) = 1; SG(request_info).no_headers = 1; php_output_set_status(0); ZCG(auto_globals_mask) = 0; ZCG(request_time) = (time_t)sapi_get_request_time(); ZCG(cache_opline) = NULL; ZCG(cache_persistent_script) = NULL; ZCG(include_path_key_len) = 0; ZCG(include_path_check) = 1; ZCG(cwd) = NULL; ZCG(cwd_key_len) = 0; ZCG(cwd_check) = 1; if (accel_preload(ZCG(accel_directives).preload, in_child) != SUCCESS) { ret = FAILURE; } orig_report_memleaks = PG(report_memleaks); PG(report_memleaks) = 0; #ifdef ZEND_SIGNALS /* We may not have registered signal handlers due to SIGG(reset)=0, so * also disable the check that they are registered. */ SIGG(check) = 0; #endif php_request_shutdown(NULL); /* calls zend_shared_alloc_unlock(); */ PG(report_memleaks) = orig_report_memleaks; } else { zend_shared_alloc_unlock(); ret = FAILURE; } #ifdef ZEND_SIGNALS SIGG(reset) = old_reset_signals; #endif sapi_module.activate = orig_activate; sapi_module.deactivate = orig_deactivate; sapi_module.register_server_variables = orig_register_server_variables; sapi_module.header_handler = orig_header_handler; sapi_module.send_headers = orig_send_headers; sapi_module.send_header = orig_send_header; sapi_module.getenv = orig_getenv; sapi_module.ub_write = orig_ub_write; sapi_module.flush = orig_flush; sapi_activate(); if (in_child) { if (ret == SUCCESS) { exit(0); } else { exit(2); } } return ret; #endif } return SUCCESS; } ZEND_EXT_API zend_extension zend_extension_entry = { ACCELERATOR_PRODUCT_NAME, /* name */ PHP_VERSION, /* version */ "Zend Technologies", /* author */ "http://www.zend.com/", /* URL */ "Copyright (c)", /* copyright */ accel_startup, /* startup */ NULL, /* shutdown */ NULL, /* per-script activation */ #ifdef HAVE_JIT accel_deactivate, /* per-script deactivation */ #else NULL, /* per-script deactivation */ #endif NULL, /* message handler */ NULL, /* op_array handler */ NULL, /* extended statement handler */ NULL, /* extended fcall begin handler */ NULL, /* extended fcall end handler */ NULL, /* op_array ctor */ NULL, /* op_array dtor */ STANDARD_ZEND_EXTENSION_PROPERTIES };
599675.c
#include "types.h" #include "param.h" #include "memlayout.h" #include "mmu.h" #include "proc.h" #include "defs.h" #include "x86.h" #include "elf.h" int exec(char *path, char **argv) { char *s, *last; int i, off; uint argc, sz, sp, ustack[3+MAXARG+1]; struct elfhdr elf; struct inode *ip; struct proghdr ph; pde_t *pgdir, *oldpgdir; begin_op(); if((ip = namei(path)) == 0){ end_op(); return -1; } ilock(ip); pgdir = 0; // Check ELF header if(readi(ip, (char*)&elf, 0, sizeof(elf)) != sizeof(elf)) goto bad; if(elf.magic != ELF_MAGIC) goto bad; if((pgdir = setupkvm()) == 0) goto bad; // Load program into memory. sz = 0; for(i=0, off=elf.phoff; i<elf.phnum; i++, off+=sizeof(ph)){ if(readi(ip, (char*)&ph, off, sizeof(ph)) != sizeof(ph)) goto bad; if(ph.type != ELF_PROG_LOAD) continue; if(ph.memsz < ph.filesz) goto bad; if(ph.vaddr + ph.memsz < ph.vaddr) goto bad; if((sz = allocuvm(pgdir, sz, ph.vaddr + ph.memsz)) == 0) goto bad; if(ph.vaddr % PGSIZE != 0) goto bad; if(loaduvm(pgdir, (char*)ph.vaddr, ip, ph.off, ph.filesz) < 0) goto bad; } iunlockput(ip); end_op(); ip = 0; // Allocate two pages at the next page boundary. // Make the first inaccessible. Use the second as the user stack. sz = PGROUNDUP(sz); if((sz = allocuvm(pgdir, sz, sz + 2*PGSIZE)) == 0) goto bad; clearpteu(pgdir, (char*)(sz - 2*PGSIZE)); sp = sz; // Push argument strings, prepare rest of stack in ustack. for(argc = 0; argv[argc]; argc++) { if(argc >= MAXARG) goto bad; sp = (sp - (strlen(argv[argc]) + 1)) & ~3; if(copyout(pgdir, sp, argv[argc], strlen(argv[argc]) + 1) < 0) goto bad; ustack[3+argc] = sp; } ustack[3+argc] = 0; ustack[0] = 0xffffffff; // fake return PC ustack[1] = argc; ustack[2] = sp - (argc+1)*4; // argv pointer sp -= (3+argc+1) * 4; if(copyout(pgdir, sp, ustack, (3+argc+1)*4) < 0) goto bad; // Save program name for debugging. for(last=s=path; *s; s++) if(*s == '/') last = s+1; safestrcpy(proc->name, last, sizeof(proc->name)); // Commit to the user image. oldpgdir = proc->pgdir; proc->pgdir = pgdir; proc->sz = sz; proc->tf->eip = elf.entry; // main proc->tf->esp = sp; proc->tickets = 100; switchuvm(proc); freevm(oldpgdir); return 0; bad: if(pgdir) freevm(pgdir); if(ip){ iunlockput(ip); end_op(); } return -1; }
418904.c
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_atoi.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: tpolonen <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/05/31 13:32:14 by tpolonen #+# #+# */ /* Updated: 2021/05/31 13:40:50 by tpolonen ### ########.fr */ /* */ /* ************************************************************************** */ int skip_whitespace(char *str); int ft_atoi(char *str) { int index; int result; int sign; index = skip_whitespace(str); result = 0; sign = 1; if (str[index] == '+') index++; else if (str[index] == '-') { sign = -1; index++; } while (str[index] != '\0') { if (str[index] < '0' || str[index] > '9') break ; result = result * 10 + str[index] - '0'; index++; } if (result > 0 && sign < 0 && result != -2147483648) result *= sign; return (result); } int skip_whitespace(char *str) { int index; index = 0; while (str[index] == ' ' || str[index] == '\n') index++; return (index); }
905278.c
/* netcode.io reference implementation Copyright © 2017, The Network Protocol Company, Inc. 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. */ #include "netcode.h" #include <stdio.h> #include <stdlib.h> #include <memory.h> #include <assert.h> #include <signal.h> #include <inttypes.h> #define MAX_SERVERS 64 #define MAX_CLIENTS 1024 #define SERVER_BASE_PORT 40000 #define CONNECT_TOKEN_EXPIRY 45 #define CONNECT_TOKEN_TIMEOUT 5 #define PROTOCOL_ID 0x1122334455667788 static volatile int quit = 0; void interrupt_handler( int signal ) { (void) signal; quit = 1; } int random_int( int a, int b ) { assert( a < b ); int result = a + rand() % ( b - a + 1 ); assert( result >= a ); assert( result <= b ); return result; } float random_float( float a, float b ) { assert( a < b ); float random = ( (float) rand() ) / (float) RAND_MAX; float diff = b - a; float r = random * diff; return a + r; } struct netcode_server_t * server[MAX_SERVERS]; struct netcode_client_t * client[MAX_CLIENTS]; uint8_t packet_data[NETCODE_MAX_PACKET_SIZE]; uint8_t private_key[NETCODE_KEY_BYTES]; void soak_initialize() { printf( "initializing\n" ); netcode_init(); netcode_log_level( NETCODE_LOG_LEVEL_INFO ); memset( server, 0, sizeof( server ) ); memset( client, 0, sizeof( client ) ); netcode_random_bytes( private_key, NETCODE_KEY_BYTES ); int i; for ( i = 0; i < NETCODE_MAX_PACKET_SIZE; ++i ) { packet_data[i] = (uint8_t) i; } } void soak_shutdown() { printf( "shutdown\n" ); int i; for ( i = 0; i < MAX_SERVERS; ++i ) { if ( server[i] != NULL ) { netcode_server_destroy( server[i] ); server[i] = NULL; } } for ( i = 0; i < MAX_CLIENTS; ++i ) { if ( client[i] != NULL ) { netcode_client_destroy( client[i] ); client[i] = NULL; } } netcode_term(); } void soak_iteration( double time ) { int i; struct netcode_server_config_t server_config; netcode_default_server_config( &server_config ); server_config.protocol_id = PROTOCOL_ID; memcpy( &server_config.private_key, private_key, NETCODE_KEY_BYTES ); for ( i = 0; i < MAX_SERVERS; ++i ) { if ( server[i] == NULL && random_int( 0, 10 ) == 0 ) { char server_address[256]; #if _MSC_VER > 1600 sprintf_s( server_address, 256, "127.0.0.1:%d", SERVER_BASE_PORT + i ); #else sprintf( server_address, "127.0.0.1:%d", SERVER_BASE_PORT + i ); #endif server[i] = netcode_server_create( server_address, &server_config, time ); printf( "created server %p\n", server[i] ); } if ( server[i] != NULL && netcode_server_num_connected_clients( server[i] ) == netcode_server_max_clients( server[i] ) && random_int( 0, 10000 ) == 0 ) { printf( "destroy server %p\n", server[i] ); netcode_server_destroy( server[i] ); server[i] = NULL; } } for ( i = 0; i < MAX_CLIENTS; ++i ) { if ( client[i] == NULL && random_int( 0, 10 ) == 0 ) { struct netcode_client_config_t client_config; netcode_default_client_config( &client_config ); client[i] = netcode_client_create( "0.0.0.0", &client_config, time ); printf( "created client %p\n", client[i] ); } if ( client[i] != NULL && random_int( 0, 1000 ) == 0 ) { printf( "destroy client %p\n", client[i] ); netcode_client_destroy( client[i] ); client[i] = NULL; } } for ( i = 0; i < MAX_SERVERS; ++i ) { if ( server[i] != NULL ) { if ( random_int( 0, 10 ) == 0 && !netcode_server_running( server[i] ) ) { netcode_server_start( server[i], random_int( 1, NETCODE_MAX_CLIENTS ) ); } if ( random_int( 0, 1000 ) == 0 && netcode_server_num_connected_clients( server[i] ) == netcode_server_max_clients( server[i] ) && netcode_server_running( server[i] ) ) { netcode_server_stop( server[i] ); } if ( netcode_server_running( server[i] ) ) { int max_clients = netcode_server_max_clients( server[i] ); int client_index; for ( client_index = 0; client_index < max_clients; ++client_index ) { if ( netcode_server_client_connected( server[i], client_index ) ) { netcode_server_send_packet( server[i], 0, packet_data, random_int( 1, NETCODE_MAX_PACKET_SIZE ) ); } } for ( client_index = 0; client_index < max_clients; ++client_index ) { if ( netcode_server_client_connected( server[i], client_index ) ) { while ( 1 ) { int packet_bytes; uint64_t packet_sequence; void * packet = netcode_server_receive_packet( server[i], client_index, &packet_bytes, &packet_sequence ); if ( !packet ) break; (void) packet_sequence; assert( memcmp( packet, packet_data, packet_bytes ) == 0 ); netcode_server_free_packet( server[i], packet ); } } } } netcode_server_update( server[i], time ); } } for ( i = 0; i < MAX_CLIENTS; ++i ) { if ( client[i] != NULL ) { if ( random_int( 0, 10 ) == 0 && netcode_client_state( client[i] ) <= NETCODE_CLIENT_STATE_DISCONNECTED ) { uint64_t client_id = 0; netcode_random_bytes( (uint8_t*) &client_id, 8 ); uint8_t connect_token[NETCODE_CONNECT_TOKEN_BYTES]; int num_server_addresses = 0; char * server_address[NETCODE_MAX_SERVERS_PER_CONNECT]; int j; for ( j = 0; j < MAX_SERVERS; ++j ) { if ( num_server_addresses == NETCODE_MAX_SERVERS_PER_CONNECT ) break; if ( server[j] && netcode_server_running( server[j] ) ) { server_address[num_server_addresses] = (char*) malloc( 256 ); #if _MSC_VER > 1600 sprintf_s( server_address[num_server_addresses], 256, "127.0.0.1:%d", SERVER_BASE_PORT + j ); #else sprintf( server_address[num_server_addresses], "127.0.0.1:%d", SERVER_BASE_PORT + j ); #endif num_server_addresses++; } } if ( num_server_addresses > 0 && netcode_generate_connect_token( num_server_addresses, (NETCODE_CONST char**) server_address, (NETCODE_CONST char**) server_address, CONNECT_TOKEN_EXPIRY, CONNECT_TOKEN_TIMEOUT, client_id, PROTOCOL_ID, private_key, connect_token ) ) { netcode_client_connect( client[i], connect_token ); } for ( j = 0; j < num_server_addresses; ++j ) { free( server_address[j] ); } } if ( random_int( 0, 100 ) == 0 && netcode_client_state( client[i] ) == NETCODE_CLIENT_STATE_CONNECTED ) { netcode_client_disconnect( client[i] ); } if ( netcode_client_state( client[i] ) == NETCODE_CLIENT_STATE_CONNECTED ) { netcode_client_send_packet( client[i], packet_data, random_int( 1, NETCODE_MAX_PACKET_SIZE ) ); while ( 1 ) { int packet_bytes; uint64_t packet_sequence; void * packet = netcode_client_receive_packet( client[i], &packet_bytes, &packet_sequence ); if ( !packet ) break; (void) packet_sequence; assert( memcmp( packet, packet_data, packet_bytes ) == 0 ); netcode_client_free_packet( client[i], packet ); } } netcode_client_update( client[i], time ); } } } int main( int argc, char ** argv ) { int num_iterations = -1; if ( argc == 2 ) num_iterations = atoi( argv[1] ); printf( "[soak]\nnum_iterations = %d\n", num_iterations ); soak_initialize(); printf( "starting\n" ); signal( SIGINT, interrupt_handler ); double time = 0.0; double delta_time = 0.1; if ( num_iterations > 0 ) { int i; for ( i = 0; i < num_iterations; ++i ) { if ( quit ) break; soak_iteration( time ); time += delta_time; } } else { while ( !quit ) { soak_iteration( time ); time += delta_time; } } soak_shutdown(); return 0; }
330949.c
/* * Copyright (c) 2015, Ericsson AB. All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, this * list of conditions and the following disclaimer in the documentation and/or other * materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE COPYRIGHT 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. */ /*/ \*\ Owr crypto utils /*/ /** * * * Functions to get certificate, fingerprint and private key. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "owr_crypto_utils.h" #include "owr_private.h" #include "owr_utils.h" #ifdef OWR_STATIC #include <stdlib.h> #endif #ifdef __APPLE__ #include <TargetConditionals.h> #endif #ifdef __ANDROID__ #include <android/log.h> #endif #include <openssl/ssl.h> #include <openssl/evp.h> #include <openssl/rsa.h> GST_DEBUG_CATEGORY_EXTERN(_owrcrypto_debug); #define GST_CAT_DEFAULT _owrcrypto_debug /* PUBLIC */ /** * owr_crypto_create_crypto_data: * @types: * @callback: (scope async): */ /** * OwrCaptureSourcesCallback: * @privatekey: (transfer none) * @certificate: (transfer none) * @fingerprint: (transfer none) * @user_data: (allow-none): * * Prototype for the callback passed to owr_get_capture_sources() */ typedef struct { OwrCryptoDataCallback callback; gboolean errorDetected; gchar* pem_key; gchar* pem_cert; gchar* char_fprint; } CryptoData; void owr_crypto_create_crypto_data(OwrCryptoDataCallback callback) { GThread* crypto_worker; crypto_worker = g_thread_new("crypto_worker", _create_crypto_worker_run, (gpointer)callback); g_thread_unref(crypto_worker); } gpointer _create_crypto_worker_run(gpointer data) { OwrCryptoDataCallback callback = (OwrCryptoDataCallback)data; g_return_val_if_fail(callback, NULL); X509* cert; X509_NAME* name = NULL; EVP_PKEY* key_pair; RSA* rsa; #define GST_DTLS_BIO_BUFFER_SIZE 4096 BIO* bio_cert; gchar buffer_cert[GST_DTLS_BIO_BUFFER_SIZE] = { 0 }; gint len_cert; gchar* pem_cert = NULL; BIO* bio_key; gchar buffer_key[GST_DTLS_BIO_BUFFER_SIZE] = { 0 }; gint len_key; gchar* pem_key = NULL; gboolean errorDetected = FALSE; bio_cert = BIO_new(BIO_s_mem()); bio_key = BIO_new(BIO_s_mem()); GString* string_fprint = NULL; gchar* char_fprint = NULL; guint j; const EVP_MD* fprint_type = NULL; fprint_type = EVP_sha256(); guchar fprint[EVP_MAX_MD_SIZE]; guint fprint_size; cert = X509_new(); key_pair = EVP_PKEY_new(); rsa = RSA_generate_key(2048, RSA_F4, NULL, NULL); EVP_PKEY_assign_RSA(key_pair, rsa); X509_set_version(cert, 2); ASN1_INTEGER_set(X509_get_serialNumber(cert), 0); X509_gmtime_adj(X509_get_notBefore(cert), 0); X509_gmtime_adj(X509_get_notAfter(cert), 31536000L); /* A year */ X509_set_pubkey(cert, key_pair); name = X509_get_subject_name(cert); X509_NAME_add_entry_by_txt(name, "C", MBSTRING_ASC, (unsigned char*)"SE", -1, -1, 0); X509_NAME_add_entry_by_txt(name, "CN", MBSTRING_ASC, (unsigned char*)"OpenWebRTC", -1, -1, 0); X509_set_issuer_name(cert, name); name = NULL; X509_sign(cert, key_pair, EVP_sha256()); if (!X509_digest(cert, fprint_type, fprint, &fprint_size)) { GST_ERROR("Error, could not create certificate fingerprint"); errorDetected = TRUE; } string_fprint = g_string_new(NULL); for (j = 0; j < fprint_size; j++) { g_string_append_printf(string_fprint, "%02X", fprint[j]); if (j + 1 != fprint_size) { g_string_append_printf(string_fprint, "%c", ':'); } } char_fprint = g_string_free(string_fprint, FALSE); if (!PEM_write_bio_X509(bio_cert, (X509*)cert)) { GST_ERROR("Error, could not write certificate bio"); errorDetected = TRUE; } if (!PEM_write_bio_PrivateKey(bio_key, (EVP_PKEY*)key_pair, NULL, NULL, 0, 0, NULL)) { GST_ERROR("Error, could not write PrivateKey bio"); errorDetected = TRUE; } len_cert = BIO_read(bio_cert, buffer_cert, GST_DTLS_BIO_BUFFER_SIZE); if (!len_cert) { GST_ERROR("Error, no certificate length"); errorDetected = TRUE; } len_key = BIO_read(bio_key, buffer_key, GST_DTLS_BIO_BUFFER_SIZE); if (!len_key) { GST_ERROR("Error, no key length"); errorDetected = TRUE; } pem_cert = g_strndup(buffer_cert, len_cert); pem_key = g_strndup(buffer_key, len_key); CryptoData* report_data = g_new0(CryptoData, 1); report_data->callback = callback; report_data->errorDetected = errorDetected; report_data->pem_key = pem_key; report_data->pem_cert = pem_cert; report_data->char_fprint = char_fprint; g_idle_add(_create_crypto_worker_report, (gpointer)report_data); // some cleanup //RSA_free(rsa); -- gives segmentation fault about every second time X509_free(cert); BIO_free(bio_cert); BIO_free(bio_key); EVP_PKEY_free(key_pair); return NULL; } gboolean _create_crypto_worker_report(gpointer data) { CryptoData* report_data = (CryptoData*)data; GClosure* closure; closure = g_cclosure_new(G_CALLBACK(report_data->callback), NULL, NULL); g_closure_set_marshal(closure, g_cclosure_marshal_generic); GValue params[3] = { G_VALUE_INIT, G_VALUE_INIT, G_VALUE_INIT }; g_value_init(&params[0], G_TYPE_STRING); g_value_init(&params[1], G_TYPE_STRING); g_value_init(&params[2], G_TYPE_STRING); if (report_data->errorDetected) { GST_ERROR("Returning with error"); g_value_set_string(&params[0], "Failure"); g_value_set_string(&params[1], "Failure"); g_value_set_string(&params[2], "Failure"); g_closure_invoke(closure, NULL, 3, (const GValue*)&params, NULL); } else { g_value_set_string(&params[0], report_data->pem_key); g_value_set_string(&params[1], report_data->pem_cert); g_value_set_string(&params[2], report_data->char_fprint); g_closure_invoke(closure, NULL, 3, (const GValue*)&params, NULL); } // some cleanup g_value_unset(&params[0]); g_value_unset(&params[1]); g_value_unset(&params[2]); g_closure_unref(closure); g_free(report_data->pem_key); g_free(report_data->pem_cert); g_free(report_data->char_fprint); g_free(report_data); return FALSE; }
490600.c
#include QMK_KEYBOARD_H // Layer names enum{ // - Base layer: _BASE, // - Symbols, numbers, and functions: _FN, // - Alternate Function layer: _LN }; const uint16_t PROGMEM keymaps[][MATRIX_ROWS][MATRIX_COLS] = { [_BASE] = LAYOUT_split_space_base( KC_1, KC_2, KC_3, KC_4, KC_5, KC_6, KC_7, KC_8, KC_9, KC_0, KC_Q, KC_W, KC_E, KC_R, KC_T, KC_Y, KC_U, KC_I, KC_O, KC_P, LCTL_T(KC_A), KC_S, KC_D, KC_F, KC_G, KC_H, KC_J, KC_K, KC_L, KC_SCLN, KC_Z, KC_X, KC_C, KC_V, KC_B, KC_N, KC_M, KC_COMM, KC_DOT, KC_SLSH, LSFT_T(KC_ESC), LGUI_T(KC_SPACE), LT(_LN, KC_BSPC), LT(_FN, KC_ENT) ), [_FN] = LAYOUT_split_space_base( LT(_LN, KC_ESC), _______, _______, _______, _______, _______, _______, _______, KC_MINS, RESET, KC_TAB, _______, _______, _______, _______, _______, _______, _______, LSFT(KC_MINS), KC_BSLS, KC_LSFT, _______, _______, _______, _______, _______, _______, KC_LBRC, KC_RBRC, KC_QUOT, AU_TOG, CK_TOGG , _______, _______, _______, _______, _______, _______, _______, _______, _______, KC_LALT, RGB_MOD, _______ ), [_LN] = LAYOUT_split_space_base( _______, KC_F1, KC_F2, KC_F3, _______, _______, _______, KC_7, KC_8, KC_9, _______, KC_F4, KC_F5, KC_F6, _______, _______, _______, KC_4, KC_5, KC_6, _______, KC_F7, KC_F8, KC_F9, _______, _______, _______, KC_1, KC_2, KC_3, _______, KC_F10, KC_F11, KC_F12, _______, _______, _______, _______, KC_0, _______, _______, _______, _______, _______ ) };
359083.c
/*- * Copyright (c) 2002 Tim J. Robbins * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include <sys/cdefs.h> __FBSDID("$FreeBSD: src/lib/libc/locale/wcstod.c,v 1.4 2004/04/07 09:47:56 tjr Exp $"); #include <stdlib.h> #include <wchar.h> #include <wctype.h> /* * Convert a string to a double-precision number. * * This is the wide-character counterpart of strtod(). So that we do not * have to duplicate the code of strtod() here, we convert the supplied * wide character string to multibyte and call strtod() on the result. * This assumes that the multibyte encoding is compatible with ASCII * for at least the digits, radix character and letters. */ double wcstod(const wchar_t * __restrict nptr, wchar_t ** __restrict endptr) { static const mbstate_t initial; mbstate_t mbs; double val; char *buf, *end; const wchar_t *wcp; size_t len; while (iswspace(*nptr)) nptr++; /* * Convert the supplied numeric wide char. string to multibyte. * * We could attempt to find the end of the numeric portion of the * wide char. string to avoid converting unneeded characters but * choose not to bother; optimising the uncommon case where * the input string contains a lot of text after the number * duplicates a lot of strtod()'s functionality and slows down the * most common cases. */ wcp = nptr; mbs = initial; if ((len = wcsrtombs(NULL, &wcp, 0, &mbs)) == (size_t)-1) { if (endptr != NULL) *endptr = (wchar_t *)nptr; return (0.0); } if ((buf = malloc(len + 1)) == NULL) return (0.0); mbs = initial; wcsrtombs(buf, &wcp, len + 1, &mbs); /* Let strtod() do most of the work for us. */ val = strtod(buf, &end); /* * We only know where the number ended in the _multibyte_ * representation of the string. If the caller wants to know * where it ended, count multibyte characters to find the * corresponding position in the wide char string. */ if (endptr != NULL) /* XXX Assume each wide char is one byte. */ *endptr = (wchar_t *)nptr + (end - buf); free(buf); return (val); }
456788.c
/* * Copyright (c) 2008-2010 Atheros Communications Inc. * Copyright (c) 2011 Adrian Chadd, Xenion Pty Ltd. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * $FreeBSD: releng/9.3/sys/dev/ath/ath_hal/ar9002/ar9287_cal.c 222301 2011-05-26 09:15:33Z adrian $ */ #include "opt_ah.h" #include "ah.h" #include "ah_internal.h" #include "ah_eeprom_v4k.h" #include "ar9002/ar9285.h" #include "ar5416/ar5416reg.h" #include "ar5416/ar5416phy.h" #include "ar9002/ar9002phy.h" //#include "ar9002/ar9287phy.h" #include "ar9002/ar9287_cal.h" void ar9287PACal(struct ath_hal *ah, HAL_BOOL is_reset) { /* XXX not required */ } /* * This is like Merlin but without ADC disable */ HAL_BOOL ar9287InitCalHardware(struct ath_hal *ah, const struct ieee80211_channel *chan) { OS_REG_SET_BIT(ah, AR_PHY_AGC_CONTROL, AR_PHY_AGC_CONTROL_FLTR_CAL); /* Calibrate the AGC */ OS_REG_WRITE(ah, AR_PHY_AGC_CONTROL, OS_REG_READ(ah, AR_PHY_AGC_CONTROL) | AR_PHY_AGC_CONTROL_CAL); /* Poll for offset calibration complete */ if (!ath_hal_wait(ah, AR_PHY_AGC_CONTROL, AR_PHY_AGC_CONTROL_CAL, 0)) { HALDEBUG(ah, HAL_DEBUG_RESET, "%s: offset calibration failed to complete in 1ms; " "noisy environment?\n", __func__); return AH_FALSE; } OS_REG_CLR_BIT(ah, AR_PHY_AGC_CONTROL, AR_PHY_AGC_CONTROL_FLTR_CAL); return AH_TRUE; }
541539.c
#define _GNU_SOURCE #include <unistd.h> #include <pwd.h> #include <stdio.h> #include <sys/ioctl.h> #include <sys/socket.h> #include <sys/select.h> #include <sys/time.h> #include <sys/types.h> #include <stdlib.h> #include <netinet/in.h> #include <string.h> #include <time.h> #include <errno.h> #include <arpa/inet.h> #include <pthread.h> #include <unistd.h> #define MAXBUFSIZE 65535 struct servers { char **channels; int socket; struct servers *prev; struct servers *next; }; char msgs[128][MAXBUFSIZE] = {0}; void drawMessages(); void addMessage(char *message) { for (int i = 1; i < 128; i++) { memcpy(msgs[i - 1], msgs[i], MAXBUFSIZE); } memcpy(msgs[127], message, strlen(message) + 1); drawMessages(); } void drawMessages() { struct winsize w; ioctl(STDOUT_FILENO, TIOCGWINSZ, &w); int total_rows = w.ws_row - 5; printf("\e[1;1H\e[2J\033[0;0H"); for (int i = 127 - total_rows; i < 128; i++) { printf("%s", msgs[i]); } printf("\033[%d;0H\n\n", total_rows + 3); } char nick[255]; int current_window_sock = -1; // const char *c = ""; // int strlen(char *c) { // int counter = 0; // while(c[counter] != 0) { // counter++; // } // return counter; // } int server_send(int sock, char *cmd); char *concat(const char *str1, const char *str2) { int sz = strlen(str1) + strlen(str2) + 1; char *ret = malloc(sz); memset(ret, 0, sz); strcpy(ret, str1); strcat(ret, str2); return ret; } void server_new(int sock) { /* TODO: create new instance to servers linked list */ } void server_connect(char *server, int portno) { /* TODO: server connection */ struct sockaddr_in serv_addr; serv_addr.sin_addr.s_addr = inet_addr(server); current_window_sock = socket(AF_INET, SOCK_STREAM, 0); if (current_window_sock < 0) { printf("ERROR opening socket"); } serv_addr.sin_family = AF_INET; serv_addr.sin_port = htons(portno); if (connect(current_window_sock, &serv_addr, sizeof(serv_addr)) < 0) { printf("ERROR connecting"); } else { printf("socket: %d\n", current_window_sock); char *connect_msg; if (asprintf(&connect_msg, "/nick %s", nick)) { } server_send(current_window_sock, connect_msg); free(connect_msg); } // int sock = 0; // server_new(sock); // current_window_sock = sock; } int server_send(int sock, char *cmd) { if (sock < 3) { printf("Socket unset!\n"); return 1; } /* TODO: send stuff to server */ if (strlen(cmd) > 0) { write(sock, cmd, strlen(cmd)); } return 0; } void all_servers_send() { /* TODO: send stuff to all servers */ } char *server_read(int sock) { char *r = malloc(65535); memset(r, 0, 65535); read(sock, r, 65535); return r; } void server_disconnect(int sock) { /* TODO: send disconnect signal to server and close connection */ } void nick_set(char *n) { printf("nick_set(): %s\n", n); strcpy(nick, n); all_servers_send(concat("/nick ", nick)); } char last_command[65535]; void command_get(char *cmd) { char str[65535] = {0}; int i = 0; char c; printf("%s> ", nick); do { c = getchar(); if (c == '\n' || c == 0 || c == EOF) { str[i++] = 0; break; } str[i++] = c; } while (1); strcpy(cmd, str); if (strlen(cmd) == 0){ command_get(cmd); } // strcpy(last_command, cmd); } int command_parse(char *cmd) { char token[65535] = {0}; char command[65535] = {0}; char parameter[65535] = {0}; char cmd_[65535] = {0}; strcpy(cmd_, cmd); if (cmd[0] == '/') { strcpy(token, strtok(cmd_, " ")); strcpy(command, token); char *t = strtok(NULL, "\0"); if (t != NULL) { strcpy(parameter, t); } if (strcmp(command, "/msg") == 0 || strcmp(command, "/nick") == 0 || strcmp(command, "/join") == 0 || strcmp(command, "/whois") == 0 || strcmp(command, "/list") == 0) { /* forward to server as is */ server_send(current_window_sock, cmd); if (strcmp(command, "/nick") == 0) { nick_set(strtok(parameter, " ")); } return 0; } else if (strcmp(command, "/connect") == 0) { char *server; int port; server = malloc(strlen(parameter) + 1); strcpy(server, parameter); server = strtok(server, " "); port = atoi(strtok(NULL, "\0")); server_connect(server, port); return 0; } else { return 1; } } else { server_send(current_window_sock, cmd); return 0; } return 1; /* command failed */ } int write_complete = 0; void *writing_thread() { write_complete = 0; memset(last_command, 0, sizeof(last_command)); command_get(last_command); if (command_parse(last_command)) { printf("Command failed, invalid command or missing parameters! '%s'\n", last_command); } write_complete = 1; return 0; } int main(int argc, char *argv[]) { getlogin_r(nick, sizeof(nick)); if (argc > 1 && strlen(argv[1]) > 0) { nick_set(argv[1]); } pthread_t w_t_id; pthread_create(&w_t_id, NULL, writing_thread, NULL); while (1) { if (write_complete == 1) { pthread_join(w_t_id, NULL); pthread_create(&w_t_id, NULL, writing_thread, NULL); } if (nick != NULL && strlen(nick)) { char *p = server_read(current_window_sock); if (strlen(p) > 0) { addMessage(p); } free(p); } } pthread_join(w_t_id, NULL); }
36549.c
/*********************************************************************/ /* Copyright 2009, 2010 The University of Texas at Austin. */ /* 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 UNIVERSITY OF TEXAS AT */ /* AUSTIN ``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 UNIVERSITY OF TEXAS AT */ /* AUSTIN OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, */ /* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES */ /* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE */ /* GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR */ /* BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF */ /* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT */ /* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT */ /* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE */ /* POSSIBILITY OF SUCH DAMAGE. */ /* */ /* The views and conclusions contained in the software and */ /* documentation are those of the authors and should not be */ /* interpreted as representing official policies, either expressed */ /* or implied, of The University of Texas at Austin. */ /*********************************************************************/ #include <stdio.h> #include <stdlib.h> #ifdef __CYGWIN32__ #include <sys/time.h> #endif #include "common.h" #undef GETRF #undef GETRI #ifndef COMPLEX #ifdef XDOUBLE #define GETRF BLASFUNC(qgetrf) #define GETRI BLASFUNC(qgetri) #elif defined(DOUBLE) #define GETRF BLASFUNC(dgetrf) #define GETRI BLASFUNC(dgetri) #else #define GETRF BLASFUNC(sgetrf) #define GETRI BLASFUNC(sgetri) #endif #else #ifdef XDOUBLE #define GETRF BLASFUNC(xgetrf) #define GETRI BLASFUNC(xgetri) #elif defined(DOUBLE) #define GETRF BLASFUNC(zgetrf) #define GETRI BLASFUNC(zgetri) #else #define GETRF BLASFUNC(cgetrf) #define GETRI BLASFUNC(cgetri) #endif #endif extern void GETRI(blasint *m, FLOAT *a, blasint *lda, blasint *ipiv, FLOAT *work, blasint *lwork, blasint *info); #if defined(__WIN32__) || defined(__WIN64__) #ifndef DELTA_EPOCH_IN_MICROSECS #define DELTA_EPOCH_IN_MICROSECS 11644473600000000ULL #endif int gettimeofday(struct timeval *tv, void *tz){ FILETIME ft; unsigned __int64 tmpres = 0; static int tzflag; if (NULL != tv) { GetSystemTimeAsFileTime(&ft); tmpres |= ft.dwHighDateTime; tmpres <<= 32; tmpres |= ft.dwLowDateTime; /*converting file time to unix epoch*/ tmpres /= 10; /*convert into microseconds*/ tmpres -= DELTA_EPOCH_IN_MICROSECS; tv->tv_sec = (long)(tmpres / 1000000UL); tv->tv_usec = (long)(tmpres % 1000000UL); } return 0; } #endif #if !defined(__WIN32__) && !defined(__WIN64__) && !defined(__CYGWIN32__) && 0 static void *huge_malloc(BLASLONG size){ int shmid; void *address; #ifndef SHM_HUGETLB #define SHM_HUGETLB 04000 #endif if ((shmid =shmget(IPC_PRIVATE, (size + HUGE_PAGESIZE) & ~(HUGE_PAGESIZE - 1), SHM_HUGETLB | IPC_CREAT |0600)) < 0) { printf( "Memory allocation failed(shmget).\n"); exit(1); } address = shmat(shmid, NULL, SHM_RND); if ((BLASLONG)address == -1){ printf( "Memory allocation failed(shmat).\n"); exit(1); } shmctl(shmid, IPC_RMID, 0); return address; } #define malloc huge_malloc #endif int main(int argc, char *argv[]){ FLOAT *a,*work; FLOAT wkopt[4]; blasint *ipiv; blasint m, i, j, info,lwork; int from = 1; int to = 200; int step = 1; struct timeval start, stop; double time1; argc--;argv++; if (argc > 0) { from = atol(*argv); argc--; argv++;} if (argc > 0) { to = MAX(atol(*argv), from); argc--; argv++;} if (argc > 0) { step = atol(*argv); argc--; argv++;} fprintf(stderr, "From : %3d To : %3d Step = %3d\n", from, to, step); if (( a = (FLOAT *)malloc(sizeof(FLOAT) * to * to * COMPSIZE)) == NULL){ fprintf(stderr,"Out of Memory!!\n");exit(1); } if (( ipiv = (blasint *)malloc(sizeof(blasint) * to * COMPSIZE)) == NULL){ fprintf(stderr,"Out of Memory!!\n");exit(1); } for(j = 0; j < to; j++){ for(i = 0; i < to * COMPSIZE; i++){ a[(long)i + (long)j * (long)to * COMPSIZE] = ((FLOAT) rand() / (FLOAT) RAND_MAX) - 0.5; } } lwork = -1; m=to; GETRI(&m, a, &m, ipiv, wkopt, &lwork, &info); lwork = (blasint)wkopt[0]; if (( work = (FLOAT *)malloc(sizeof(FLOAT) * lwork * COMPSIZE)) == NULL){ fprintf(stderr,"Out of Memory!!\n");exit(1); } #ifdef __linux srandom(getpid()); #endif fprintf(stderr, " SIZE FLops Time Lwork\n"); for(m = from; m <= to; m += step){ fprintf(stderr, " %6d : ", (int)m); GETRF (&m, &m, a, &m, ipiv, &info); if (info) { fprintf(stderr, "Matrix is not singular .. %d\n", info); exit(1); } gettimeofday( &start, (struct timezone *)0); lwork = -1; GETRI(&m, a, &m, ipiv, wkopt, &lwork, &info); lwork = (blasint)wkopt[0]; GETRI(&m, a, &m, ipiv, work, &lwork, &info); gettimeofday( &stop, (struct timezone *)0); if (info) { fprintf(stderr, "failed compute inverse matrix .. %d\n", info); exit(1); } time1 = (double)(stop.tv_sec - start.tv_sec) + (double)((stop.tv_usec - start.tv_usec)) * 1.e-6; fprintf(stderr, " %10.2f MFlops : %10.2f Sec : %d\n", COMPSIZE * COMPSIZE * (4.0/3.0 * (double)m * (double)m *(double)m - (double)m *(double)m + 5.0/3.0* (double)m) / time1 * 1.e-6,time1,lwork); } return 0; } // void main(int argc, char *argv[]) __attribute__((weak, alias("MAIN__")));
269574.c
/** * @file IxEthAcc.c * * @author Intel Corporation * @date 20-Feb-2001 * * @brief This file contains the implementation of the IXP425 Ethernet Access Component * * Design Notes: * * @par * IXP400 SW Release version 2.0 * * -- Copyright Notice -- * * @par * Copyright 2001-2005, Intel Corporation. * All rights reserved. * * @par * 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 Intel Corporation nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * @par * 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. * * @par * -- End of Copyright Notice -- */ #include "IxEthAcc.h" #ifdef CONFIG_IXP425_COMPONENT_ETHDB #include "IxEthDB.h" #endif #include "IxFeatureCtrl.h" #include "IxEthAcc_p.h" #include "IxEthAccMac_p.h" #include "IxEthAccMii_p.h" /** * @addtogroup IxEthAcc *@{ */ /** * @brief System-wide information data strucure. * * @ingroup IxEthAccPri * */ IxEthAccInfo ixEthAccDataInfo; extern PUBLIC IxEthAccMacState ixEthAccMacState[]; extern PUBLIC IxOsalMutex ixEthAccControlInterfaceMutex; /** * @brief System-wide information * * @ingroup IxEthAccPri * */ BOOL ixEthAccServiceInit = FALSE; /* global filtering bit mask */ PUBLIC UINT32 ixEthAccNewSrcMask; /** * @brief Per port information data strucure. * * @ingroup IxEthAccPri * */ IxEthAccPortDataInfo ixEthAccPortData[IX_ETH_ACC_NUMBER_OF_PORTS]; PUBLIC IxEthAccStatus ixEthAccInit() { #ifdef CONFIG_IXP425_COMPONENT_ETHDB /* * Initialize Control plane */ if (ixEthDBInit() != IX_ETH_DB_SUCCESS) { IX_ETH_ACC_WARNING_LOG("ixEthAccInit: EthDB init failed\n", 0, 0, 0, 0, 0, 0); return IX_ETH_ACC_FAIL; } #endif if (IX_FEATURE_CTRL_SWCONFIG_ENABLED == ixFeatureCtrlSwConfigurationCheck (IX_FEATURECTRL_ETH_LEARNING)) { ixEthAccNewSrcMask = (~0); /* want all the bits */ } else { ixEthAccNewSrcMask = (~IX_ETHACC_NE_NEWSRCMASK); /* want all but the NewSrc bit */ } /* * Initialize Data plane */ if ( ixEthAccInitDataPlane() != IX_ETH_ACC_SUCCESS ) { IX_ETH_ACC_WARNING_LOG("ixEthAccInit: data plane init failed\n", 0, 0, 0, 0, 0, 0); return IX_ETH_ACC_FAIL; } if ( ixEthAccQMgrQueuesConfig() != IX_ETH_ACC_SUCCESS ) { IX_ETH_ACC_WARNING_LOG("ixEthAccInit: queue config failed\n", 0, 0, 0, 0, 0, 0); return IX_ETH_ACC_FAIL; } /* * Initialize MII */ if ( ixEthAccMiiInit() != IX_ETH_ACC_SUCCESS ) { IX_ETH_ACC_WARNING_LOG("ixEthAccInit: Mii init failed\n", 0, 0, 0, 0, 0, 0); return IX_ETH_ACC_FAIL; } /* * Initialize MAC I/O memory */ if (ixEthAccMacMemInit() != IX_ETH_ACC_SUCCESS) { IX_ETH_ACC_WARNING_LOG("ixEthAccInit: Mac init failed\n", 0, 0, 0, 0, 0, 0); return IX_ETH_ACC_FAIL; } /* * Initialize control plane interface lock */ if (ixOsalMutexInit(&ixEthAccControlInterfaceMutex) != IX_SUCCESS) { IX_ETH_ACC_WARNING_LOG("ixEthAccInit: Control plane interface lock initialization failed\n", 0, 0, 0, 0, 0, 0); return IX_ETH_ACC_FAIL; } /* initialiasation is complete */ ixEthAccServiceInit = TRUE; return IX_ETH_ACC_SUCCESS; } PUBLIC void ixEthAccUnload(void) { IxEthAccPortId portId; if ( IX_ETH_ACC_IS_SERVICE_INITIALIZED() ) { /* check none of the port is still active */ for (portId = 0; portId < IX_ETH_ACC_NUMBER_OF_PORTS; portId++) { if ( IX_ETH_IS_PORT_INITIALIZED(portId) ) { if (ixEthAccMacState[portId].portDisableState == ACTIVE) { IX_ETH_ACC_WARNING_LOG("ixEthAccUnload: port %u still active, bail out\n", portId, 0, 0, 0, 0, 0); return; } } } /* unmap the memory areas */ ixEthAccMiiUnload(); ixEthAccMacUnload(); /* set all ports as uninitialized */ for (portId = 0; portId < IX_ETH_ACC_NUMBER_OF_PORTS; portId++) { ixEthAccPortData[portId].portInitialized = FALSE; } /* uninitialize the service */ ixEthAccServiceInit = FALSE; } } PUBLIC IxEthAccStatus ixEthAccPortInit( IxEthAccPortId portId) { IxEthAccStatus ret=IX_ETH_ACC_SUCCESS; if ( ! IX_ETH_ACC_IS_SERVICE_INITIALIZED() ) { return(IX_ETH_ACC_FAIL); } /* * Check for valid port */ if ( ! IX_ETH_ACC_IS_PORT_VALID(portId) ) { return (IX_ETH_ACC_INVALID_PORT); } if (IX_ETH_ACC_SUCCESS != ixEthAccSingleEthNpeCheck(portId)) { IX_ETH_ACC_WARNING_LOG("EthAcc: Unavailable Eth %d: Cannot initialize Eth port.\n",(INT32) portId,0,0,0,0,0); return IX_ETH_ACC_SUCCESS ; } if ( IX_ETH_IS_PORT_INITIALIZED(portId) ) { /* Already initialized */ return(IX_ETH_ACC_FAIL); } if(ixEthAccMacInit(portId)!=IX_ETH_ACC_SUCCESS) { return IX_ETH_ACC_FAIL; } /* * Set the port init flag. */ ixEthAccPortData[portId].portInitialized = TRUE; #ifdef CONFIG_IXP425_COMPONENT_ETHDB /* init learning/filtering database structures for this port */ ixEthDBPortInit(portId); #endif return(ret); }
972976.c
/* For a complex interleave AVX vector swap the real and imaginary parts */ #ifndef SWAP_REAL_IMAG_PERMUTE #define SWAP_REAL_IMAG_PERMUTE 0xB1 #endif void cmat_mulx_avx_fma_accumulate_nr_c_17_dot_product_length_8 (SAL_cf32 *A[17], /* left input matrix array [nr_c] of pointers to each row */ SAL_cf32 *B[8], /* right input matrix array [dot_product_length] of pointers to each row */ SAL_cf32 *C[17], /* output matrix array [nr_c] of pointers to each row */ SAL_i32 nc_c) /* column count in C */ { const __m256 negate_even_mult = _mm256_set_ps (1.0f, -1.0f, 1.0f, -1.0f, 1.0f, -1.0f, 1.0f, -1.0f); __m256 left_r0_c0_r, left_r0_c1_r, left_r0_c2_r, left_r0_c3_r, left_r0_c4_r, left_r0_c5_r, left_r0_c6_r, left_r0_c7_r; __m256 left_r0_c0_i, left_r0_c1_i, left_r0_c2_i, left_r0_c3_i, left_r0_c4_i, left_r0_c5_i, left_r0_c6_i, left_r0_c7_i; __m256 left_r1_c0_r, left_r1_c1_r, left_r1_c2_r, left_r1_c3_r, left_r1_c4_r, left_r1_c5_r, left_r1_c6_r, left_r1_c7_r; __m256 left_r1_c0_i, left_r1_c1_i, left_r1_c2_i, left_r1_c3_i, left_r1_c4_i, left_r1_c5_i, left_r1_c6_i, left_r1_c7_i; __m256 left_r2_c0_r, left_r2_c1_r, left_r2_c2_r, left_r2_c3_r, left_r2_c4_r, left_r2_c5_r, left_r2_c6_r, left_r2_c7_r; __m256 left_r2_c0_i, left_r2_c1_i, left_r2_c2_i, left_r2_c3_i, left_r2_c4_i, left_r2_c5_i, left_r2_c6_i, left_r2_c7_i; __m256 left_r3_c0_r, left_r3_c1_r, left_r3_c2_r, left_r3_c3_r, left_r3_c4_r, left_r3_c5_r, left_r3_c6_r, left_r3_c7_r; __m256 left_r3_c0_i, left_r3_c1_i, left_r3_c2_i, left_r3_c3_i, left_r3_c4_i, left_r3_c5_i, left_r3_c6_i, left_r3_c7_i; __m256 left_r4_c0_r, left_r4_c1_r, left_r4_c2_r, left_r4_c3_r, left_r4_c4_r, left_r4_c5_r, left_r4_c6_r, left_r4_c7_r; __m256 left_r4_c0_i, left_r4_c1_i, left_r4_c2_i, left_r4_c3_i, left_r4_c4_i, left_r4_c5_i, left_r4_c6_i, left_r4_c7_i; __m256 left_r5_c0_r, left_r5_c1_r, left_r5_c2_r, left_r5_c3_r, left_r5_c4_r, left_r5_c5_r, left_r5_c6_r, left_r5_c7_r; __m256 left_r5_c0_i, left_r5_c1_i, left_r5_c2_i, left_r5_c3_i, left_r5_c4_i, left_r5_c5_i, left_r5_c6_i, left_r5_c7_i; __m256 left_r6_c0_r, left_r6_c1_r, left_r6_c2_r, left_r6_c3_r, left_r6_c4_r, left_r6_c5_r, left_r6_c6_r, left_r6_c7_r; __m256 left_r6_c0_i, left_r6_c1_i, left_r6_c2_i, left_r6_c3_i, left_r6_c4_i, left_r6_c5_i, left_r6_c6_i, left_r6_c7_i; __m256 left_r7_c0_r, left_r7_c1_r, left_r7_c2_r, left_r7_c3_r, left_r7_c4_r, left_r7_c5_r, left_r7_c6_r, left_r7_c7_r; __m256 left_r7_c0_i, left_r7_c1_i, left_r7_c2_i, left_r7_c3_i, left_r7_c4_i, left_r7_c5_i, left_r7_c6_i, left_r7_c7_i; __m256 left_r8_c0_r, left_r8_c1_r, left_r8_c2_r, left_r8_c3_r, left_r8_c4_r, left_r8_c5_r, left_r8_c6_r, left_r8_c7_r; __m256 left_r8_c0_i, left_r8_c1_i, left_r8_c2_i, left_r8_c3_i, left_r8_c4_i, left_r8_c5_i, left_r8_c6_i, left_r8_c7_i; __m256 left_r9_c0_r, left_r9_c1_r, left_r9_c2_r, left_r9_c3_r, left_r9_c4_r, left_r9_c5_r, left_r9_c6_r, left_r9_c7_r; __m256 left_r9_c0_i, left_r9_c1_i, left_r9_c2_i, left_r9_c3_i, left_r9_c4_i, left_r9_c5_i, left_r9_c6_i, left_r9_c7_i; __m256 left_r10_c0_r, left_r10_c1_r, left_r10_c2_r, left_r10_c3_r, left_r10_c4_r, left_r10_c5_r, left_r10_c6_r, left_r10_c7_r; __m256 left_r10_c0_i, left_r10_c1_i, left_r10_c2_i, left_r10_c3_i, left_r10_c4_i, left_r10_c5_i, left_r10_c6_i, left_r10_c7_i; __m256 left_r11_c0_r, left_r11_c1_r, left_r11_c2_r, left_r11_c3_r, left_r11_c4_r, left_r11_c5_r, left_r11_c6_r, left_r11_c7_r; __m256 left_r11_c0_i, left_r11_c1_i, left_r11_c2_i, left_r11_c3_i, left_r11_c4_i, left_r11_c5_i, left_r11_c6_i, left_r11_c7_i; __m256 left_r12_c0_r, left_r12_c1_r, left_r12_c2_r, left_r12_c3_r, left_r12_c4_r, left_r12_c5_r, left_r12_c6_r, left_r12_c7_r; __m256 left_r12_c0_i, left_r12_c1_i, left_r12_c2_i, left_r12_c3_i, left_r12_c4_i, left_r12_c5_i, left_r12_c6_i, left_r12_c7_i; __m256 left_r13_c0_r, left_r13_c1_r, left_r13_c2_r, left_r13_c3_r, left_r13_c4_r, left_r13_c5_r, left_r13_c6_r, left_r13_c7_r; __m256 left_r13_c0_i, left_r13_c1_i, left_r13_c2_i, left_r13_c3_i, left_r13_c4_i, left_r13_c5_i, left_r13_c6_i, left_r13_c7_i; __m256 left_r14_c0_r, left_r14_c1_r, left_r14_c2_r, left_r14_c3_r, left_r14_c4_r, left_r14_c5_r, left_r14_c6_r, left_r14_c7_r; __m256 left_r14_c0_i, left_r14_c1_i, left_r14_c2_i, left_r14_c3_i, left_r14_c4_i, left_r14_c5_i, left_r14_c6_i, left_r14_c7_i; __m256 left_r15_c0_r, left_r15_c1_r, left_r15_c2_r, left_r15_c3_r, left_r15_c4_r, left_r15_c5_r, left_r15_c6_r, left_r15_c7_r; __m256 left_r15_c0_i, left_r15_c1_i, left_r15_c2_i, left_r15_c3_i, left_r15_c4_i, left_r15_c5_i, left_r15_c6_i, left_r15_c7_i; __m256 left_r16_c0_r, left_r16_c1_r, left_r16_c2_r, left_r16_c3_r, left_r16_c4_r, left_r16_c5_r, left_r16_c6_r, left_r16_c7_r; __m256 left_r16_c0_i, left_r16_c1_i, left_r16_c2_i, left_r16_c3_i, left_r16_c4_i, left_r16_c5_i, left_r16_c6_i, left_r16_c7_i; __m256 right_r_i, right_i_r; __m256 output_r0; __m256 output_r1; __m256 output_r2; __m256 output_r3; __m256 output_r4; __m256 output_r5; __m256 output_r6; __m256 output_r7; __m256 output_r8; __m256 output_r9; __m256 output_r10; __m256 output_r11; __m256 output_r12; __m256 output_r13; __m256 output_r14; __m256 output_r15; __m256 output_r16; SAL_i32 c_c; #ifdef IACA_LOAD_LEFT IACA_START #endif left_r0_c0_r = _mm256_broadcast_ss (&(A[0] + 0)->real); left_r0_c0_i = _mm256_broadcast_ss (&(A[0] + 0)->imag); left_r0_c1_r = _mm256_broadcast_ss (&(A[0] + 1)->real); left_r0_c1_i = _mm256_mul_ps (negate_even_mult, _mm256_broadcast_ss (&(A[0] + 1)->imag)); left_r0_c2_r = _mm256_broadcast_ss (&(A[0] + 2)->real); left_r0_c2_i = _mm256_mul_ps (negate_even_mult, _mm256_broadcast_ss (&(A[0] + 2)->imag)); left_r0_c3_r = _mm256_broadcast_ss (&(A[0] + 3)->real); left_r0_c3_i = _mm256_mul_ps (negate_even_mult, _mm256_broadcast_ss (&(A[0] + 3)->imag)); left_r0_c4_r = _mm256_broadcast_ss (&(A[0] + 4)->real); left_r0_c4_i = _mm256_mul_ps (negate_even_mult, _mm256_broadcast_ss (&(A[0] + 4)->imag)); left_r0_c5_r = _mm256_broadcast_ss (&(A[0] + 5)->real); left_r0_c5_i = _mm256_mul_ps (negate_even_mult, _mm256_broadcast_ss (&(A[0] + 5)->imag)); left_r0_c6_r = _mm256_broadcast_ss (&(A[0] + 6)->real); left_r0_c6_i = _mm256_mul_ps (negate_even_mult, _mm256_broadcast_ss (&(A[0] + 6)->imag)); left_r0_c7_r = _mm256_broadcast_ss (&(A[0] + 7)->real); left_r0_c7_i = _mm256_mul_ps (negate_even_mult, _mm256_broadcast_ss (&(A[0] + 7)->imag)); left_r1_c0_r = _mm256_broadcast_ss (&(A[1] + 0)->real); left_r1_c0_i = _mm256_broadcast_ss (&(A[1] + 0)->imag); left_r1_c1_r = _mm256_broadcast_ss (&(A[1] + 1)->real); left_r1_c1_i = _mm256_mul_ps (negate_even_mult, _mm256_broadcast_ss (&(A[1] + 1)->imag)); left_r1_c2_r = _mm256_broadcast_ss (&(A[1] + 2)->real); left_r1_c2_i = _mm256_mul_ps (negate_even_mult, _mm256_broadcast_ss (&(A[1] + 2)->imag)); left_r1_c3_r = _mm256_broadcast_ss (&(A[1] + 3)->real); left_r1_c3_i = _mm256_mul_ps (negate_even_mult, _mm256_broadcast_ss (&(A[1] + 3)->imag)); left_r1_c4_r = _mm256_broadcast_ss (&(A[1] + 4)->real); left_r1_c4_i = _mm256_mul_ps (negate_even_mult, _mm256_broadcast_ss (&(A[1] + 4)->imag)); left_r1_c5_r = _mm256_broadcast_ss (&(A[1] + 5)->real); left_r1_c5_i = _mm256_mul_ps (negate_even_mult, _mm256_broadcast_ss (&(A[1] + 5)->imag)); left_r1_c6_r = _mm256_broadcast_ss (&(A[1] + 6)->real); left_r1_c6_i = _mm256_mul_ps (negate_even_mult, _mm256_broadcast_ss (&(A[1] + 6)->imag)); left_r1_c7_r = _mm256_broadcast_ss (&(A[1] + 7)->real); left_r1_c7_i = _mm256_mul_ps (negate_even_mult, _mm256_broadcast_ss (&(A[1] + 7)->imag)); left_r2_c0_r = _mm256_broadcast_ss (&(A[2] + 0)->real); left_r2_c0_i = _mm256_broadcast_ss (&(A[2] + 0)->imag); left_r2_c1_r = _mm256_broadcast_ss (&(A[2] + 1)->real); left_r2_c1_i = _mm256_mul_ps (negate_even_mult, _mm256_broadcast_ss (&(A[2] + 1)->imag)); left_r2_c2_r = _mm256_broadcast_ss (&(A[2] + 2)->real); left_r2_c2_i = _mm256_mul_ps (negate_even_mult, _mm256_broadcast_ss (&(A[2] + 2)->imag)); left_r2_c3_r = _mm256_broadcast_ss (&(A[2] + 3)->real); left_r2_c3_i = _mm256_mul_ps (negate_even_mult, _mm256_broadcast_ss (&(A[2] + 3)->imag)); left_r2_c4_r = _mm256_broadcast_ss (&(A[2] + 4)->real); left_r2_c4_i = _mm256_mul_ps (negate_even_mult, _mm256_broadcast_ss (&(A[2] + 4)->imag)); left_r2_c5_r = _mm256_broadcast_ss (&(A[2] + 5)->real); left_r2_c5_i = _mm256_mul_ps (negate_even_mult, _mm256_broadcast_ss (&(A[2] + 5)->imag)); left_r2_c6_r = _mm256_broadcast_ss (&(A[2] + 6)->real); left_r2_c6_i = _mm256_mul_ps (negate_even_mult, _mm256_broadcast_ss (&(A[2] + 6)->imag)); left_r2_c7_r = _mm256_broadcast_ss (&(A[2] + 7)->real); left_r2_c7_i = _mm256_mul_ps (negate_even_mult, _mm256_broadcast_ss (&(A[2] + 7)->imag)); left_r3_c0_r = _mm256_broadcast_ss (&(A[3] + 0)->real); left_r3_c0_i = _mm256_broadcast_ss (&(A[3] + 0)->imag); left_r3_c1_r = _mm256_broadcast_ss (&(A[3] + 1)->real); left_r3_c1_i = _mm256_mul_ps (negate_even_mult, _mm256_broadcast_ss (&(A[3] + 1)->imag)); left_r3_c2_r = _mm256_broadcast_ss (&(A[3] + 2)->real); left_r3_c2_i = _mm256_mul_ps (negate_even_mult, _mm256_broadcast_ss (&(A[3] + 2)->imag)); left_r3_c3_r = _mm256_broadcast_ss (&(A[3] + 3)->real); left_r3_c3_i = _mm256_mul_ps (negate_even_mult, _mm256_broadcast_ss (&(A[3] + 3)->imag)); left_r3_c4_r = _mm256_broadcast_ss (&(A[3] + 4)->real); left_r3_c4_i = _mm256_mul_ps (negate_even_mult, _mm256_broadcast_ss (&(A[3] + 4)->imag)); left_r3_c5_r = _mm256_broadcast_ss (&(A[3] + 5)->real); left_r3_c5_i = _mm256_mul_ps (negate_even_mult, _mm256_broadcast_ss (&(A[3] + 5)->imag)); left_r3_c6_r = _mm256_broadcast_ss (&(A[3] + 6)->real); left_r3_c6_i = _mm256_mul_ps (negate_even_mult, _mm256_broadcast_ss (&(A[3] + 6)->imag)); left_r3_c7_r = _mm256_broadcast_ss (&(A[3] + 7)->real); left_r3_c7_i = _mm256_mul_ps (negate_even_mult, _mm256_broadcast_ss (&(A[3] + 7)->imag)); left_r4_c0_r = _mm256_broadcast_ss (&(A[4] + 0)->real); left_r4_c0_i = _mm256_broadcast_ss (&(A[4] + 0)->imag); left_r4_c1_r = _mm256_broadcast_ss (&(A[4] + 1)->real); left_r4_c1_i = _mm256_mul_ps (negate_even_mult, _mm256_broadcast_ss (&(A[4] + 1)->imag)); left_r4_c2_r = _mm256_broadcast_ss (&(A[4] + 2)->real); left_r4_c2_i = _mm256_mul_ps (negate_even_mult, _mm256_broadcast_ss (&(A[4] + 2)->imag)); left_r4_c3_r = _mm256_broadcast_ss (&(A[4] + 3)->real); left_r4_c3_i = _mm256_mul_ps (negate_even_mult, _mm256_broadcast_ss (&(A[4] + 3)->imag)); left_r4_c4_r = _mm256_broadcast_ss (&(A[4] + 4)->real); left_r4_c4_i = _mm256_mul_ps (negate_even_mult, _mm256_broadcast_ss (&(A[4] + 4)->imag)); left_r4_c5_r = _mm256_broadcast_ss (&(A[4] + 5)->real); left_r4_c5_i = _mm256_mul_ps (negate_even_mult, _mm256_broadcast_ss (&(A[4] + 5)->imag)); left_r4_c6_r = _mm256_broadcast_ss (&(A[4] + 6)->real); left_r4_c6_i = _mm256_mul_ps (negate_even_mult, _mm256_broadcast_ss (&(A[4] + 6)->imag)); left_r4_c7_r = _mm256_broadcast_ss (&(A[4] + 7)->real); left_r4_c7_i = _mm256_mul_ps (negate_even_mult, _mm256_broadcast_ss (&(A[4] + 7)->imag)); left_r5_c0_r = _mm256_broadcast_ss (&(A[5] + 0)->real); left_r5_c0_i = _mm256_broadcast_ss (&(A[5] + 0)->imag); left_r5_c1_r = _mm256_broadcast_ss (&(A[5] + 1)->real); left_r5_c1_i = _mm256_mul_ps (negate_even_mult, _mm256_broadcast_ss (&(A[5] + 1)->imag)); left_r5_c2_r = _mm256_broadcast_ss (&(A[5] + 2)->real); left_r5_c2_i = _mm256_mul_ps (negate_even_mult, _mm256_broadcast_ss (&(A[5] + 2)->imag)); left_r5_c3_r = _mm256_broadcast_ss (&(A[5] + 3)->real); left_r5_c3_i = _mm256_mul_ps (negate_even_mult, _mm256_broadcast_ss (&(A[5] + 3)->imag)); left_r5_c4_r = _mm256_broadcast_ss (&(A[5] + 4)->real); left_r5_c4_i = _mm256_mul_ps (negate_even_mult, _mm256_broadcast_ss (&(A[5] + 4)->imag)); left_r5_c5_r = _mm256_broadcast_ss (&(A[5] + 5)->real); left_r5_c5_i = _mm256_mul_ps (negate_even_mult, _mm256_broadcast_ss (&(A[5] + 5)->imag)); left_r5_c6_r = _mm256_broadcast_ss (&(A[5] + 6)->real); left_r5_c6_i = _mm256_mul_ps (negate_even_mult, _mm256_broadcast_ss (&(A[5] + 6)->imag)); left_r5_c7_r = _mm256_broadcast_ss (&(A[5] + 7)->real); left_r5_c7_i = _mm256_mul_ps (negate_even_mult, _mm256_broadcast_ss (&(A[5] + 7)->imag)); left_r6_c0_r = _mm256_broadcast_ss (&(A[6] + 0)->real); left_r6_c0_i = _mm256_broadcast_ss (&(A[6] + 0)->imag); left_r6_c1_r = _mm256_broadcast_ss (&(A[6] + 1)->real); left_r6_c1_i = _mm256_mul_ps (negate_even_mult, _mm256_broadcast_ss (&(A[6] + 1)->imag)); left_r6_c2_r = _mm256_broadcast_ss (&(A[6] + 2)->real); left_r6_c2_i = _mm256_mul_ps (negate_even_mult, _mm256_broadcast_ss (&(A[6] + 2)->imag)); left_r6_c3_r = _mm256_broadcast_ss (&(A[6] + 3)->real); left_r6_c3_i = _mm256_mul_ps (negate_even_mult, _mm256_broadcast_ss (&(A[6] + 3)->imag)); left_r6_c4_r = _mm256_broadcast_ss (&(A[6] + 4)->real); left_r6_c4_i = _mm256_mul_ps (negate_even_mult, _mm256_broadcast_ss (&(A[6] + 4)->imag)); left_r6_c5_r = _mm256_broadcast_ss (&(A[6] + 5)->real); left_r6_c5_i = _mm256_mul_ps (negate_even_mult, _mm256_broadcast_ss (&(A[6] + 5)->imag)); left_r6_c6_r = _mm256_broadcast_ss (&(A[6] + 6)->real); left_r6_c6_i = _mm256_mul_ps (negate_even_mult, _mm256_broadcast_ss (&(A[6] + 6)->imag)); left_r6_c7_r = _mm256_broadcast_ss (&(A[6] + 7)->real); left_r6_c7_i = _mm256_mul_ps (negate_even_mult, _mm256_broadcast_ss (&(A[6] + 7)->imag)); left_r7_c0_r = _mm256_broadcast_ss (&(A[7] + 0)->real); left_r7_c0_i = _mm256_broadcast_ss (&(A[7] + 0)->imag); left_r7_c1_r = _mm256_broadcast_ss (&(A[7] + 1)->real); left_r7_c1_i = _mm256_mul_ps (negate_even_mult, _mm256_broadcast_ss (&(A[7] + 1)->imag)); left_r7_c2_r = _mm256_broadcast_ss (&(A[7] + 2)->real); left_r7_c2_i = _mm256_mul_ps (negate_even_mult, _mm256_broadcast_ss (&(A[7] + 2)->imag)); left_r7_c3_r = _mm256_broadcast_ss (&(A[7] + 3)->real); left_r7_c3_i = _mm256_mul_ps (negate_even_mult, _mm256_broadcast_ss (&(A[7] + 3)->imag)); left_r7_c4_r = _mm256_broadcast_ss (&(A[7] + 4)->real); left_r7_c4_i = _mm256_mul_ps (negate_even_mult, _mm256_broadcast_ss (&(A[7] + 4)->imag)); left_r7_c5_r = _mm256_broadcast_ss (&(A[7] + 5)->real); left_r7_c5_i = _mm256_mul_ps (negate_even_mult, _mm256_broadcast_ss (&(A[7] + 5)->imag)); left_r7_c6_r = _mm256_broadcast_ss (&(A[7] + 6)->real); left_r7_c6_i = _mm256_mul_ps (negate_even_mult, _mm256_broadcast_ss (&(A[7] + 6)->imag)); left_r7_c7_r = _mm256_broadcast_ss (&(A[7] + 7)->real); left_r7_c7_i = _mm256_mul_ps (negate_even_mult, _mm256_broadcast_ss (&(A[7] + 7)->imag)); left_r8_c0_r = _mm256_broadcast_ss (&(A[8] + 0)->real); left_r8_c0_i = _mm256_broadcast_ss (&(A[8] + 0)->imag); left_r8_c1_r = _mm256_broadcast_ss (&(A[8] + 1)->real); left_r8_c1_i = _mm256_mul_ps (negate_even_mult, _mm256_broadcast_ss (&(A[8] + 1)->imag)); left_r8_c2_r = _mm256_broadcast_ss (&(A[8] + 2)->real); left_r8_c2_i = _mm256_mul_ps (negate_even_mult, _mm256_broadcast_ss (&(A[8] + 2)->imag)); left_r8_c3_r = _mm256_broadcast_ss (&(A[8] + 3)->real); left_r8_c3_i = _mm256_mul_ps (negate_even_mult, _mm256_broadcast_ss (&(A[8] + 3)->imag)); left_r8_c4_r = _mm256_broadcast_ss (&(A[8] + 4)->real); left_r8_c4_i = _mm256_mul_ps (negate_even_mult, _mm256_broadcast_ss (&(A[8] + 4)->imag)); left_r8_c5_r = _mm256_broadcast_ss (&(A[8] + 5)->real); left_r8_c5_i = _mm256_mul_ps (negate_even_mult, _mm256_broadcast_ss (&(A[8] + 5)->imag)); left_r8_c6_r = _mm256_broadcast_ss (&(A[8] + 6)->real); left_r8_c6_i = _mm256_mul_ps (negate_even_mult, _mm256_broadcast_ss (&(A[8] + 6)->imag)); left_r8_c7_r = _mm256_broadcast_ss (&(A[8] + 7)->real); left_r8_c7_i = _mm256_mul_ps (negate_even_mult, _mm256_broadcast_ss (&(A[8] + 7)->imag)); left_r9_c0_r = _mm256_broadcast_ss (&(A[9] + 0)->real); left_r9_c0_i = _mm256_broadcast_ss (&(A[9] + 0)->imag); left_r9_c1_r = _mm256_broadcast_ss (&(A[9] + 1)->real); left_r9_c1_i = _mm256_mul_ps (negate_even_mult, _mm256_broadcast_ss (&(A[9] + 1)->imag)); left_r9_c2_r = _mm256_broadcast_ss (&(A[9] + 2)->real); left_r9_c2_i = _mm256_mul_ps (negate_even_mult, _mm256_broadcast_ss (&(A[9] + 2)->imag)); left_r9_c3_r = _mm256_broadcast_ss (&(A[9] + 3)->real); left_r9_c3_i = _mm256_mul_ps (negate_even_mult, _mm256_broadcast_ss (&(A[9] + 3)->imag)); left_r9_c4_r = _mm256_broadcast_ss (&(A[9] + 4)->real); left_r9_c4_i = _mm256_mul_ps (negate_even_mult, _mm256_broadcast_ss (&(A[9] + 4)->imag)); left_r9_c5_r = _mm256_broadcast_ss (&(A[9] + 5)->real); left_r9_c5_i = _mm256_mul_ps (negate_even_mult, _mm256_broadcast_ss (&(A[9] + 5)->imag)); left_r9_c6_r = _mm256_broadcast_ss (&(A[9] + 6)->real); left_r9_c6_i = _mm256_mul_ps (negate_even_mult, _mm256_broadcast_ss (&(A[9] + 6)->imag)); left_r9_c7_r = _mm256_broadcast_ss (&(A[9] + 7)->real); left_r9_c7_i = _mm256_mul_ps (negate_even_mult, _mm256_broadcast_ss (&(A[9] + 7)->imag)); left_r10_c0_r = _mm256_broadcast_ss (&(A[10] + 0)->real); left_r10_c0_i = _mm256_broadcast_ss (&(A[10] + 0)->imag); left_r10_c1_r = _mm256_broadcast_ss (&(A[10] + 1)->real); left_r10_c1_i = _mm256_mul_ps (negate_even_mult, _mm256_broadcast_ss (&(A[10] + 1)->imag)); left_r10_c2_r = _mm256_broadcast_ss (&(A[10] + 2)->real); left_r10_c2_i = _mm256_mul_ps (negate_even_mult, _mm256_broadcast_ss (&(A[10] + 2)->imag)); left_r10_c3_r = _mm256_broadcast_ss (&(A[10] + 3)->real); left_r10_c3_i = _mm256_mul_ps (negate_even_mult, _mm256_broadcast_ss (&(A[10] + 3)->imag)); left_r10_c4_r = _mm256_broadcast_ss (&(A[10] + 4)->real); left_r10_c4_i = _mm256_mul_ps (negate_even_mult, _mm256_broadcast_ss (&(A[10] + 4)->imag)); left_r10_c5_r = _mm256_broadcast_ss (&(A[10] + 5)->real); left_r10_c5_i = _mm256_mul_ps (negate_even_mult, _mm256_broadcast_ss (&(A[10] + 5)->imag)); left_r10_c6_r = _mm256_broadcast_ss (&(A[10] + 6)->real); left_r10_c6_i = _mm256_mul_ps (negate_even_mult, _mm256_broadcast_ss (&(A[10] + 6)->imag)); left_r10_c7_r = _mm256_broadcast_ss (&(A[10] + 7)->real); left_r10_c7_i = _mm256_mul_ps (negate_even_mult, _mm256_broadcast_ss (&(A[10] + 7)->imag)); left_r11_c0_r = _mm256_broadcast_ss (&(A[11] + 0)->real); left_r11_c0_i = _mm256_broadcast_ss (&(A[11] + 0)->imag); left_r11_c1_r = _mm256_broadcast_ss (&(A[11] + 1)->real); left_r11_c1_i = _mm256_mul_ps (negate_even_mult, _mm256_broadcast_ss (&(A[11] + 1)->imag)); left_r11_c2_r = _mm256_broadcast_ss (&(A[11] + 2)->real); left_r11_c2_i = _mm256_mul_ps (negate_even_mult, _mm256_broadcast_ss (&(A[11] + 2)->imag)); left_r11_c3_r = _mm256_broadcast_ss (&(A[11] + 3)->real); left_r11_c3_i = _mm256_mul_ps (negate_even_mult, _mm256_broadcast_ss (&(A[11] + 3)->imag)); left_r11_c4_r = _mm256_broadcast_ss (&(A[11] + 4)->real); left_r11_c4_i = _mm256_mul_ps (negate_even_mult, _mm256_broadcast_ss (&(A[11] + 4)->imag)); left_r11_c5_r = _mm256_broadcast_ss (&(A[11] + 5)->real); left_r11_c5_i = _mm256_mul_ps (negate_even_mult, _mm256_broadcast_ss (&(A[11] + 5)->imag)); left_r11_c6_r = _mm256_broadcast_ss (&(A[11] + 6)->real); left_r11_c6_i = _mm256_mul_ps (negate_even_mult, _mm256_broadcast_ss (&(A[11] + 6)->imag)); left_r11_c7_r = _mm256_broadcast_ss (&(A[11] + 7)->real); left_r11_c7_i = _mm256_mul_ps (negate_even_mult, _mm256_broadcast_ss (&(A[11] + 7)->imag)); left_r12_c0_r = _mm256_broadcast_ss (&(A[12] + 0)->real); left_r12_c0_i = _mm256_broadcast_ss (&(A[12] + 0)->imag); left_r12_c1_r = _mm256_broadcast_ss (&(A[12] + 1)->real); left_r12_c1_i = _mm256_mul_ps (negate_even_mult, _mm256_broadcast_ss (&(A[12] + 1)->imag)); left_r12_c2_r = _mm256_broadcast_ss (&(A[12] + 2)->real); left_r12_c2_i = _mm256_mul_ps (negate_even_mult, _mm256_broadcast_ss (&(A[12] + 2)->imag)); left_r12_c3_r = _mm256_broadcast_ss (&(A[12] + 3)->real); left_r12_c3_i = _mm256_mul_ps (negate_even_mult, _mm256_broadcast_ss (&(A[12] + 3)->imag)); left_r12_c4_r = _mm256_broadcast_ss (&(A[12] + 4)->real); left_r12_c4_i = _mm256_mul_ps (negate_even_mult, _mm256_broadcast_ss (&(A[12] + 4)->imag)); left_r12_c5_r = _mm256_broadcast_ss (&(A[12] + 5)->real); left_r12_c5_i = _mm256_mul_ps (negate_even_mult, _mm256_broadcast_ss (&(A[12] + 5)->imag)); left_r12_c6_r = _mm256_broadcast_ss (&(A[12] + 6)->real); left_r12_c6_i = _mm256_mul_ps (negate_even_mult, _mm256_broadcast_ss (&(A[12] + 6)->imag)); left_r12_c7_r = _mm256_broadcast_ss (&(A[12] + 7)->real); left_r12_c7_i = _mm256_mul_ps (negate_even_mult, _mm256_broadcast_ss (&(A[12] + 7)->imag)); left_r13_c0_r = _mm256_broadcast_ss (&(A[13] + 0)->real); left_r13_c0_i = _mm256_broadcast_ss (&(A[13] + 0)->imag); left_r13_c1_r = _mm256_broadcast_ss (&(A[13] + 1)->real); left_r13_c1_i = _mm256_mul_ps (negate_even_mult, _mm256_broadcast_ss (&(A[13] + 1)->imag)); left_r13_c2_r = _mm256_broadcast_ss (&(A[13] + 2)->real); left_r13_c2_i = _mm256_mul_ps (negate_even_mult, _mm256_broadcast_ss (&(A[13] + 2)->imag)); left_r13_c3_r = _mm256_broadcast_ss (&(A[13] + 3)->real); left_r13_c3_i = _mm256_mul_ps (negate_even_mult, _mm256_broadcast_ss (&(A[13] + 3)->imag)); left_r13_c4_r = _mm256_broadcast_ss (&(A[13] + 4)->real); left_r13_c4_i = _mm256_mul_ps (negate_even_mult, _mm256_broadcast_ss (&(A[13] + 4)->imag)); left_r13_c5_r = _mm256_broadcast_ss (&(A[13] + 5)->real); left_r13_c5_i = _mm256_mul_ps (negate_even_mult, _mm256_broadcast_ss (&(A[13] + 5)->imag)); left_r13_c6_r = _mm256_broadcast_ss (&(A[13] + 6)->real); left_r13_c6_i = _mm256_mul_ps (negate_even_mult, _mm256_broadcast_ss (&(A[13] + 6)->imag)); left_r13_c7_r = _mm256_broadcast_ss (&(A[13] + 7)->real); left_r13_c7_i = _mm256_mul_ps (negate_even_mult, _mm256_broadcast_ss (&(A[13] + 7)->imag)); left_r14_c0_r = _mm256_broadcast_ss (&(A[14] + 0)->real); left_r14_c0_i = _mm256_broadcast_ss (&(A[14] + 0)->imag); left_r14_c1_r = _mm256_broadcast_ss (&(A[14] + 1)->real); left_r14_c1_i = _mm256_mul_ps (negate_even_mult, _mm256_broadcast_ss (&(A[14] + 1)->imag)); left_r14_c2_r = _mm256_broadcast_ss (&(A[14] + 2)->real); left_r14_c2_i = _mm256_mul_ps (negate_even_mult, _mm256_broadcast_ss (&(A[14] + 2)->imag)); left_r14_c3_r = _mm256_broadcast_ss (&(A[14] + 3)->real); left_r14_c3_i = _mm256_mul_ps (negate_even_mult, _mm256_broadcast_ss (&(A[14] + 3)->imag)); left_r14_c4_r = _mm256_broadcast_ss (&(A[14] + 4)->real); left_r14_c4_i = _mm256_mul_ps (negate_even_mult, _mm256_broadcast_ss (&(A[14] + 4)->imag)); left_r14_c5_r = _mm256_broadcast_ss (&(A[14] + 5)->real); left_r14_c5_i = _mm256_mul_ps (negate_even_mult, _mm256_broadcast_ss (&(A[14] + 5)->imag)); left_r14_c6_r = _mm256_broadcast_ss (&(A[14] + 6)->real); left_r14_c6_i = _mm256_mul_ps (negate_even_mult, _mm256_broadcast_ss (&(A[14] + 6)->imag)); left_r14_c7_r = _mm256_broadcast_ss (&(A[14] + 7)->real); left_r14_c7_i = _mm256_mul_ps (negate_even_mult, _mm256_broadcast_ss (&(A[14] + 7)->imag)); left_r15_c0_r = _mm256_broadcast_ss (&(A[15] + 0)->real); left_r15_c0_i = _mm256_broadcast_ss (&(A[15] + 0)->imag); left_r15_c1_r = _mm256_broadcast_ss (&(A[15] + 1)->real); left_r15_c1_i = _mm256_mul_ps (negate_even_mult, _mm256_broadcast_ss (&(A[15] + 1)->imag)); left_r15_c2_r = _mm256_broadcast_ss (&(A[15] + 2)->real); left_r15_c2_i = _mm256_mul_ps (negate_even_mult, _mm256_broadcast_ss (&(A[15] + 2)->imag)); left_r15_c3_r = _mm256_broadcast_ss (&(A[15] + 3)->real); left_r15_c3_i = _mm256_mul_ps (negate_even_mult, _mm256_broadcast_ss (&(A[15] + 3)->imag)); left_r15_c4_r = _mm256_broadcast_ss (&(A[15] + 4)->real); left_r15_c4_i = _mm256_mul_ps (negate_even_mult, _mm256_broadcast_ss (&(A[15] + 4)->imag)); left_r15_c5_r = _mm256_broadcast_ss (&(A[15] + 5)->real); left_r15_c5_i = _mm256_mul_ps (negate_even_mult, _mm256_broadcast_ss (&(A[15] + 5)->imag)); left_r15_c6_r = _mm256_broadcast_ss (&(A[15] + 6)->real); left_r15_c6_i = _mm256_mul_ps (negate_even_mult, _mm256_broadcast_ss (&(A[15] + 6)->imag)); left_r15_c7_r = _mm256_broadcast_ss (&(A[15] + 7)->real); left_r15_c7_i = _mm256_mul_ps (negate_even_mult, _mm256_broadcast_ss (&(A[15] + 7)->imag)); left_r16_c0_r = _mm256_broadcast_ss (&(A[16] + 0)->real); left_r16_c0_i = _mm256_broadcast_ss (&(A[16] + 0)->imag); left_r16_c1_r = _mm256_broadcast_ss (&(A[16] + 1)->real); left_r16_c1_i = _mm256_mul_ps (negate_even_mult, _mm256_broadcast_ss (&(A[16] + 1)->imag)); left_r16_c2_r = _mm256_broadcast_ss (&(A[16] + 2)->real); left_r16_c2_i = _mm256_mul_ps (negate_even_mult, _mm256_broadcast_ss (&(A[16] + 2)->imag)); left_r16_c3_r = _mm256_broadcast_ss (&(A[16] + 3)->real); left_r16_c3_i = _mm256_mul_ps (negate_even_mult, _mm256_broadcast_ss (&(A[16] + 3)->imag)); left_r16_c4_r = _mm256_broadcast_ss (&(A[16] + 4)->real); left_r16_c4_i = _mm256_mul_ps (negate_even_mult, _mm256_broadcast_ss (&(A[16] + 4)->imag)); left_r16_c5_r = _mm256_broadcast_ss (&(A[16] + 5)->real); left_r16_c5_i = _mm256_mul_ps (negate_even_mult, _mm256_broadcast_ss (&(A[16] + 5)->imag)); left_r16_c6_r = _mm256_broadcast_ss (&(A[16] + 6)->real); left_r16_c6_i = _mm256_mul_ps (negate_even_mult, _mm256_broadcast_ss (&(A[16] + 6)->imag)); left_r16_c7_r = _mm256_broadcast_ss (&(A[16] + 7)->real); left_r16_c7_i = _mm256_mul_ps (negate_even_mult, _mm256_broadcast_ss (&(A[16] + 7)->imag)); #ifdef IACA_LOAD_LEFT IACA_END #endif for (c_c = 0; c_c < nc_c; c_c += 4) { #ifdef IACA_OPERATE IACA_START #endif right_r_i = _mm256_load_ps (&(B[0] + c_c)->real); right_i_r = _mm256_permute_ps (right_r_i, SWAP_REAL_IMAG_PERMUTE); output_r0 = _mm256_fmaddsub_ps ( right_r_i, left_r0_c0_r, _mm256_mul_ps (right_i_r, left_r0_c0_i)); output_r1 = _mm256_fmaddsub_ps ( right_r_i, left_r1_c0_r, _mm256_mul_ps (right_i_r, left_r1_c0_i)); output_r2 = _mm256_fmaddsub_ps ( right_r_i, left_r2_c0_r, _mm256_mul_ps (right_i_r, left_r2_c0_i)); output_r3 = _mm256_fmaddsub_ps ( right_r_i, left_r3_c0_r, _mm256_mul_ps (right_i_r, left_r3_c0_i)); output_r4 = _mm256_fmaddsub_ps ( right_r_i, left_r4_c0_r, _mm256_mul_ps (right_i_r, left_r4_c0_i)); output_r5 = _mm256_fmaddsub_ps ( right_r_i, left_r5_c0_r, _mm256_mul_ps (right_i_r, left_r5_c0_i)); output_r6 = _mm256_fmaddsub_ps ( right_r_i, left_r6_c0_r, _mm256_mul_ps (right_i_r, left_r6_c0_i)); output_r7 = _mm256_fmaddsub_ps ( right_r_i, left_r7_c0_r, _mm256_mul_ps (right_i_r, left_r7_c0_i)); output_r8 = _mm256_fmaddsub_ps ( right_r_i, left_r8_c0_r, _mm256_mul_ps (right_i_r, left_r8_c0_i)); output_r9 = _mm256_fmaddsub_ps ( right_r_i, left_r9_c0_r, _mm256_mul_ps (right_i_r, left_r9_c0_i)); output_r10 = _mm256_fmaddsub_ps ( right_r_i, left_r10_c0_r, _mm256_mul_ps (right_i_r, left_r10_c0_i)); output_r11 = _mm256_fmaddsub_ps ( right_r_i, left_r11_c0_r, _mm256_mul_ps (right_i_r, left_r11_c0_i)); output_r12 = _mm256_fmaddsub_ps ( right_r_i, left_r12_c0_r, _mm256_mul_ps (right_i_r, left_r12_c0_i)); output_r13 = _mm256_fmaddsub_ps ( right_r_i, left_r13_c0_r, _mm256_mul_ps (right_i_r, left_r13_c0_i)); output_r14 = _mm256_fmaddsub_ps ( right_r_i, left_r14_c0_r, _mm256_mul_ps (right_i_r, left_r14_c0_i)); output_r15 = _mm256_fmaddsub_ps ( right_r_i, left_r15_c0_r, _mm256_mul_ps (right_i_r, left_r15_c0_i)); output_r16 = _mm256_fmaddsub_ps ( right_r_i, left_r16_c0_r, _mm256_mul_ps (right_i_r, left_r16_c0_i)); right_r_i = _mm256_load_ps (&(B[1] + c_c)->real); right_i_r = _mm256_permute_ps (right_r_i, SWAP_REAL_IMAG_PERMUTE); output_r0 = _mm256_fmadd_ps ( right_r_i, left_r0_c1_r, _mm256_fmadd_ps (right_i_r, left_r0_c1_i, output_r0)); output_r1 = _mm256_fmadd_ps ( right_r_i, left_r1_c1_r, _mm256_fmadd_ps (right_i_r, left_r1_c1_i, output_r1)); output_r2 = _mm256_fmadd_ps ( right_r_i, left_r2_c1_r, _mm256_fmadd_ps (right_i_r, left_r2_c1_i, output_r2)); output_r3 = _mm256_fmadd_ps ( right_r_i, left_r3_c1_r, _mm256_fmadd_ps (right_i_r, left_r3_c1_i, output_r3)); output_r4 = _mm256_fmadd_ps ( right_r_i, left_r4_c1_r, _mm256_fmadd_ps (right_i_r, left_r4_c1_i, output_r4)); output_r5 = _mm256_fmadd_ps ( right_r_i, left_r5_c1_r, _mm256_fmadd_ps (right_i_r, left_r5_c1_i, output_r5)); output_r6 = _mm256_fmadd_ps ( right_r_i, left_r6_c1_r, _mm256_fmadd_ps (right_i_r, left_r6_c1_i, output_r6)); output_r7 = _mm256_fmadd_ps ( right_r_i, left_r7_c1_r, _mm256_fmadd_ps (right_i_r, left_r7_c1_i, output_r7)); output_r8 = _mm256_fmadd_ps ( right_r_i, left_r8_c1_r, _mm256_fmadd_ps (right_i_r, left_r8_c1_i, output_r8)); output_r9 = _mm256_fmadd_ps ( right_r_i, left_r9_c1_r, _mm256_fmadd_ps (right_i_r, left_r9_c1_i, output_r9)); output_r10 = _mm256_fmadd_ps ( right_r_i, left_r10_c1_r, _mm256_fmadd_ps (right_i_r, left_r10_c1_i, output_r10)); output_r11 = _mm256_fmadd_ps ( right_r_i, left_r11_c1_r, _mm256_fmadd_ps (right_i_r, left_r11_c1_i, output_r11)); output_r12 = _mm256_fmadd_ps ( right_r_i, left_r12_c1_r, _mm256_fmadd_ps (right_i_r, left_r12_c1_i, output_r12)); output_r13 = _mm256_fmadd_ps ( right_r_i, left_r13_c1_r, _mm256_fmadd_ps (right_i_r, left_r13_c1_i, output_r13)); output_r14 = _mm256_fmadd_ps ( right_r_i, left_r14_c1_r, _mm256_fmadd_ps (right_i_r, left_r14_c1_i, output_r14)); output_r15 = _mm256_fmadd_ps ( right_r_i, left_r15_c1_r, _mm256_fmadd_ps (right_i_r, left_r15_c1_i, output_r15)); output_r16 = _mm256_fmadd_ps ( right_r_i, left_r16_c1_r, _mm256_fmadd_ps (right_i_r, left_r16_c1_i, output_r16)); right_r_i = _mm256_load_ps (&(B[2] + c_c)->real); right_i_r = _mm256_permute_ps (right_r_i, SWAP_REAL_IMAG_PERMUTE); output_r0 = _mm256_fmadd_ps ( right_r_i, left_r0_c2_r, _mm256_fmadd_ps (right_i_r, left_r0_c2_i, output_r0)); output_r1 = _mm256_fmadd_ps ( right_r_i, left_r1_c2_r, _mm256_fmadd_ps (right_i_r, left_r1_c2_i, output_r1)); output_r2 = _mm256_fmadd_ps ( right_r_i, left_r2_c2_r, _mm256_fmadd_ps (right_i_r, left_r2_c2_i, output_r2)); output_r3 = _mm256_fmadd_ps ( right_r_i, left_r3_c2_r, _mm256_fmadd_ps (right_i_r, left_r3_c2_i, output_r3)); output_r4 = _mm256_fmadd_ps ( right_r_i, left_r4_c2_r, _mm256_fmadd_ps (right_i_r, left_r4_c2_i, output_r4)); output_r5 = _mm256_fmadd_ps ( right_r_i, left_r5_c2_r, _mm256_fmadd_ps (right_i_r, left_r5_c2_i, output_r5)); output_r6 = _mm256_fmadd_ps ( right_r_i, left_r6_c2_r, _mm256_fmadd_ps (right_i_r, left_r6_c2_i, output_r6)); output_r7 = _mm256_fmadd_ps ( right_r_i, left_r7_c2_r, _mm256_fmadd_ps (right_i_r, left_r7_c2_i, output_r7)); output_r8 = _mm256_fmadd_ps ( right_r_i, left_r8_c2_r, _mm256_fmadd_ps (right_i_r, left_r8_c2_i, output_r8)); output_r9 = _mm256_fmadd_ps ( right_r_i, left_r9_c2_r, _mm256_fmadd_ps (right_i_r, left_r9_c2_i, output_r9)); output_r10 = _mm256_fmadd_ps ( right_r_i, left_r10_c2_r, _mm256_fmadd_ps (right_i_r, left_r10_c2_i, output_r10)); output_r11 = _mm256_fmadd_ps ( right_r_i, left_r11_c2_r, _mm256_fmadd_ps (right_i_r, left_r11_c2_i, output_r11)); output_r12 = _mm256_fmadd_ps ( right_r_i, left_r12_c2_r, _mm256_fmadd_ps (right_i_r, left_r12_c2_i, output_r12)); output_r13 = _mm256_fmadd_ps ( right_r_i, left_r13_c2_r, _mm256_fmadd_ps (right_i_r, left_r13_c2_i, output_r13)); output_r14 = _mm256_fmadd_ps ( right_r_i, left_r14_c2_r, _mm256_fmadd_ps (right_i_r, left_r14_c2_i, output_r14)); output_r15 = _mm256_fmadd_ps ( right_r_i, left_r15_c2_r, _mm256_fmadd_ps (right_i_r, left_r15_c2_i, output_r15)); output_r16 = _mm256_fmadd_ps ( right_r_i, left_r16_c2_r, _mm256_fmadd_ps (right_i_r, left_r16_c2_i, output_r16)); right_r_i = _mm256_load_ps (&(B[3] + c_c)->real); right_i_r = _mm256_permute_ps (right_r_i, SWAP_REAL_IMAG_PERMUTE); output_r0 = _mm256_fmadd_ps ( right_r_i, left_r0_c3_r, _mm256_fmadd_ps (right_i_r, left_r0_c3_i, output_r0)); output_r1 = _mm256_fmadd_ps ( right_r_i, left_r1_c3_r, _mm256_fmadd_ps (right_i_r, left_r1_c3_i, output_r1)); output_r2 = _mm256_fmadd_ps ( right_r_i, left_r2_c3_r, _mm256_fmadd_ps (right_i_r, left_r2_c3_i, output_r2)); output_r3 = _mm256_fmadd_ps ( right_r_i, left_r3_c3_r, _mm256_fmadd_ps (right_i_r, left_r3_c3_i, output_r3)); output_r4 = _mm256_fmadd_ps ( right_r_i, left_r4_c3_r, _mm256_fmadd_ps (right_i_r, left_r4_c3_i, output_r4)); output_r5 = _mm256_fmadd_ps ( right_r_i, left_r5_c3_r, _mm256_fmadd_ps (right_i_r, left_r5_c3_i, output_r5)); output_r6 = _mm256_fmadd_ps ( right_r_i, left_r6_c3_r, _mm256_fmadd_ps (right_i_r, left_r6_c3_i, output_r6)); output_r7 = _mm256_fmadd_ps ( right_r_i, left_r7_c3_r, _mm256_fmadd_ps (right_i_r, left_r7_c3_i, output_r7)); output_r8 = _mm256_fmadd_ps ( right_r_i, left_r8_c3_r, _mm256_fmadd_ps (right_i_r, left_r8_c3_i, output_r8)); output_r9 = _mm256_fmadd_ps ( right_r_i, left_r9_c3_r, _mm256_fmadd_ps (right_i_r, left_r9_c3_i, output_r9)); output_r10 = _mm256_fmadd_ps ( right_r_i, left_r10_c3_r, _mm256_fmadd_ps (right_i_r, left_r10_c3_i, output_r10)); output_r11 = _mm256_fmadd_ps ( right_r_i, left_r11_c3_r, _mm256_fmadd_ps (right_i_r, left_r11_c3_i, output_r11)); output_r12 = _mm256_fmadd_ps ( right_r_i, left_r12_c3_r, _mm256_fmadd_ps (right_i_r, left_r12_c3_i, output_r12)); output_r13 = _mm256_fmadd_ps ( right_r_i, left_r13_c3_r, _mm256_fmadd_ps (right_i_r, left_r13_c3_i, output_r13)); output_r14 = _mm256_fmadd_ps ( right_r_i, left_r14_c3_r, _mm256_fmadd_ps (right_i_r, left_r14_c3_i, output_r14)); output_r15 = _mm256_fmadd_ps ( right_r_i, left_r15_c3_r, _mm256_fmadd_ps (right_i_r, left_r15_c3_i, output_r15)); output_r16 = _mm256_fmadd_ps ( right_r_i, left_r16_c3_r, _mm256_fmadd_ps (right_i_r, left_r16_c3_i, output_r16)); right_r_i = _mm256_load_ps (&(B[4] + c_c)->real); right_i_r = _mm256_permute_ps (right_r_i, SWAP_REAL_IMAG_PERMUTE); output_r0 = _mm256_fmadd_ps ( right_r_i, left_r0_c4_r, _mm256_fmadd_ps (right_i_r, left_r0_c4_i, output_r0)); output_r1 = _mm256_fmadd_ps ( right_r_i, left_r1_c4_r, _mm256_fmadd_ps (right_i_r, left_r1_c4_i, output_r1)); output_r2 = _mm256_fmadd_ps ( right_r_i, left_r2_c4_r, _mm256_fmadd_ps (right_i_r, left_r2_c4_i, output_r2)); output_r3 = _mm256_fmadd_ps ( right_r_i, left_r3_c4_r, _mm256_fmadd_ps (right_i_r, left_r3_c4_i, output_r3)); output_r4 = _mm256_fmadd_ps ( right_r_i, left_r4_c4_r, _mm256_fmadd_ps (right_i_r, left_r4_c4_i, output_r4)); output_r5 = _mm256_fmadd_ps ( right_r_i, left_r5_c4_r, _mm256_fmadd_ps (right_i_r, left_r5_c4_i, output_r5)); output_r6 = _mm256_fmadd_ps ( right_r_i, left_r6_c4_r, _mm256_fmadd_ps (right_i_r, left_r6_c4_i, output_r6)); output_r7 = _mm256_fmadd_ps ( right_r_i, left_r7_c4_r, _mm256_fmadd_ps (right_i_r, left_r7_c4_i, output_r7)); output_r8 = _mm256_fmadd_ps ( right_r_i, left_r8_c4_r, _mm256_fmadd_ps (right_i_r, left_r8_c4_i, output_r8)); output_r9 = _mm256_fmadd_ps ( right_r_i, left_r9_c4_r, _mm256_fmadd_ps (right_i_r, left_r9_c4_i, output_r9)); output_r10 = _mm256_fmadd_ps ( right_r_i, left_r10_c4_r, _mm256_fmadd_ps (right_i_r, left_r10_c4_i, output_r10)); output_r11 = _mm256_fmadd_ps ( right_r_i, left_r11_c4_r, _mm256_fmadd_ps (right_i_r, left_r11_c4_i, output_r11)); output_r12 = _mm256_fmadd_ps ( right_r_i, left_r12_c4_r, _mm256_fmadd_ps (right_i_r, left_r12_c4_i, output_r12)); output_r13 = _mm256_fmadd_ps ( right_r_i, left_r13_c4_r, _mm256_fmadd_ps (right_i_r, left_r13_c4_i, output_r13)); output_r14 = _mm256_fmadd_ps ( right_r_i, left_r14_c4_r, _mm256_fmadd_ps (right_i_r, left_r14_c4_i, output_r14)); output_r15 = _mm256_fmadd_ps ( right_r_i, left_r15_c4_r, _mm256_fmadd_ps (right_i_r, left_r15_c4_i, output_r15)); output_r16 = _mm256_fmadd_ps ( right_r_i, left_r16_c4_r, _mm256_fmadd_ps (right_i_r, left_r16_c4_i, output_r16)); right_r_i = _mm256_load_ps (&(B[5] + c_c)->real); right_i_r = _mm256_permute_ps (right_r_i, SWAP_REAL_IMAG_PERMUTE); output_r0 = _mm256_fmadd_ps ( right_r_i, left_r0_c5_r, _mm256_fmadd_ps (right_i_r, left_r0_c5_i, output_r0)); output_r1 = _mm256_fmadd_ps ( right_r_i, left_r1_c5_r, _mm256_fmadd_ps (right_i_r, left_r1_c5_i, output_r1)); output_r2 = _mm256_fmadd_ps ( right_r_i, left_r2_c5_r, _mm256_fmadd_ps (right_i_r, left_r2_c5_i, output_r2)); output_r3 = _mm256_fmadd_ps ( right_r_i, left_r3_c5_r, _mm256_fmadd_ps (right_i_r, left_r3_c5_i, output_r3)); output_r4 = _mm256_fmadd_ps ( right_r_i, left_r4_c5_r, _mm256_fmadd_ps (right_i_r, left_r4_c5_i, output_r4)); output_r5 = _mm256_fmadd_ps ( right_r_i, left_r5_c5_r, _mm256_fmadd_ps (right_i_r, left_r5_c5_i, output_r5)); output_r6 = _mm256_fmadd_ps ( right_r_i, left_r6_c5_r, _mm256_fmadd_ps (right_i_r, left_r6_c5_i, output_r6)); output_r7 = _mm256_fmadd_ps ( right_r_i, left_r7_c5_r, _mm256_fmadd_ps (right_i_r, left_r7_c5_i, output_r7)); output_r8 = _mm256_fmadd_ps ( right_r_i, left_r8_c5_r, _mm256_fmadd_ps (right_i_r, left_r8_c5_i, output_r8)); output_r9 = _mm256_fmadd_ps ( right_r_i, left_r9_c5_r, _mm256_fmadd_ps (right_i_r, left_r9_c5_i, output_r9)); output_r10 = _mm256_fmadd_ps ( right_r_i, left_r10_c5_r, _mm256_fmadd_ps (right_i_r, left_r10_c5_i, output_r10)); output_r11 = _mm256_fmadd_ps ( right_r_i, left_r11_c5_r, _mm256_fmadd_ps (right_i_r, left_r11_c5_i, output_r11)); output_r12 = _mm256_fmadd_ps ( right_r_i, left_r12_c5_r, _mm256_fmadd_ps (right_i_r, left_r12_c5_i, output_r12)); output_r13 = _mm256_fmadd_ps ( right_r_i, left_r13_c5_r, _mm256_fmadd_ps (right_i_r, left_r13_c5_i, output_r13)); output_r14 = _mm256_fmadd_ps ( right_r_i, left_r14_c5_r, _mm256_fmadd_ps (right_i_r, left_r14_c5_i, output_r14)); output_r15 = _mm256_fmadd_ps ( right_r_i, left_r15_c5_r, _mm256_fmadd_ps (right_i_r, left_r15_c5_i, output_r15)); output_r16 = _mm256_fmadd_ps ( right_r_i, left_r16_c5_r, _mm256_fmadd_ps (right_i_r, left_r16_c5_i, output_r16)); right_r_i = _mm256_load_ps (&(B[6] + c_c)->real); right_i_r = _mm256_permute_ps (right_r_i, SWAP_REAL_IMAG_PERMUTE); output_r0 = _mm256_fmadd_ps ( right_r_i, left_r0_c6_r, _mm256_fmadd_ps (right_i_r, left_r0_c6_i, output_r0)); output_r1 = _mm256_fmadd_ps ( right_r_i, left_r1_c6_r, _mm256_fmadd_ps (right_i_r, left_r1_c6_i, output_r1)); output_r2 = _mm256_fmadd_ps ( right_r_i, left_r2_c6_r, _mm256_fmadd_ps (right_i_r, left_r2_c6_i, output_r2)); output_r3 = _mm256_fmadd_ps ( right_r_i, left_r3_c6_r, _mm256_fmadd_ps (right_i_r, left_r3_c6_i, output_r3)); output_r4 = _mm256_fmadd_ps ( right_r_i, left_r4_c6_r, _mm256_fmadd_ps (right_i_r, left_r4_c6_i, output_r4)); output_r5 = _mm256_fmadd_ps ( right_r_i, left_r5_c6_r, _mm256_fmadd_ps (right_i_r, left_r5_c6_i, output_r5)); output_r6 = _mm256_fmadd_ps ( right_r_i, left_r6_c6_r, _mm256_fmadd_ps (right_i_r, left_r6_c6_i, output_r6)); output_r7 = _mm256_fmadd_ps ( right_r_i, left_r7_c6_r, _mm256_fmadd_ps (right_i_r, left_r7_c6_i, output_r7)); output_r8 = _mm256_fmadd_ps ( right_r_i, left_r8_c6_r, _mm256_fmadd_ps (right_i_r, left_r8_c6_i, output_r8)); output_r9 = _mm256_fmadd_ps ( right_r_i, left_r9_c6_r, _mm256_fmadd_ps (right_i_r, left_r9_c6_i, output_r9)); output_r10 = _mm256_fmadd_ps ( right_r_i, left_r10_c6_r, _mm256_fmadd_ps (right_i_r, left_r10_c6_i, output_r10)); output_r11 = _mm256_fmadd_ps ( right_r_i, left_r11_c6_r, _mm256_fmadd_ps (right_i_r, left_r11_c6_i, output_r11)); output_r12 = _mm256_fmadd_ps ( right_r_i, left_r12_c6_r, _mm256_fmadd_ps (right_i_r, left_r12_c6_i, output_r12)); output_r13 = _mm256_fmadd_ps ( right_r_i, left_r13_c6_r, _mm256_fmadd_ps (right_i_r, left_r13_c6_i, output_r13)); output_r14 = _mm256_fmadd_ps ( right_r_i, left_r14_c6_r, _mm256_fmadd_ps (right_i_r, left_r14_c6_i, output_r14)); output_r15 = _mm256_fmadd_ps ( right_r_i, left_r15_c6_r, _mm256_fmadd_ps (right_i_r, left_r15_c6_i, output_r15)); output_r16 = _mm256_fmadd_ps ( right_r_i, left_r16_c6_r, _mm256_fmadd_ps (right_i_r, left_r16_c6_i, output_r16)); right_r_i = _mm256_load_ps (&(B[7] + c_c)->real); right_i_r = _mm256_permute_ps (right_r_i, SWAP_REAL_IMAG_PERMUTE); _mm256_store_ps (&(C[0] + c_c)->real, _mm256_fmadd_ps ( right_r_i, left_r0_c7_r, _mm256_fmadd_ps (right_i_r, left_r0_c7_i, output_r0))); _mm256_store_ps (&(C[1] + c_c)->real, _mm256_fmadd_ps ( right_r_i, left_r1_c7_r, _mm256_fmadd_ps (right_i_r, left_r1_c7_i, output_r1))); _mm256_store_ps (&(C[2] + c_c)->real, _mm256_fmadd_ps ( right_r_i, left_r2_c7_r, _mm256_fmadd_ps (right_i_r, left_r2_c7_i, output_r2))); _mm256_store_ps (&(C[3] + c_c)->real, _mm256_fmadd_ps ( right_r_i, left_r3_c7_r, _mm256_fmadd_ps (right_i_r, left_r3_c7_i, output_r3))); _mm256_store_ps (&(C[4] + c_c)->real, _mm256_fmadd_ps ( right_r_i, left_r4_c7_r, _mm256_fmadd_ps (right_i_r, left_r4_c7_i, output_r4))); _mm256_store_ps (&(C[5] + c_c)->real, _mm256_fmadd_ps ( right_r_i, left_r5_c7_r, _mm256_fmadd_ps (right_i_r, left_r5_c7_i, output_r5))); _mm256_store_ps (&(C[6] + c_c)->real, _mm256_fmadd_ps ( right_r_i, left_r6_c7_r, _mm256_fmadd_ps (right_i_r, left_r6_c7_i, output_r6))); _mm256_store_ps (&(C[7] + c_c)->real, _mm256_fmadd_ps ( right_r_i, left_r7_c7_r, _mm256_fmadd_ps (right_i_r, left_r7_c7_i, output_r7))); _mm256_store_ps (&(C[8] + c_c)->real, _mm256_fmadd_ps ( right_r_i, left_r8_c7_r, _mm256_fmadd_ps (right_i_r, left_r8_c7_i, output_r8))); _mm256_store_ps (&(C[9] + c_c)->real, _mm256_fmadd_ps ( right_r_i, left_r9_c7_r, _mm256_fmadd_ps (right_i_r, left_r9_c7_i, output_r9))); _mm256_store_ps (&(C[10] + c_c)->real, _mm256_fmadd_ps ( right_r_i, left_r10_c7_r, _mm256_fmadd_ps (right_i_r, left_r10_c7_i, output_r10))); _mm256_store_ps (&(C[11] + c_c)->real, _mm256_fmadd_ps ( right_r_i, left_r11_c7_r, _mm256_fmadd_ps (right_i_r, left_r11_c7_i, output_r11))); _mm256_store_ps (&(C[12] + c_c)->real, _mm256_fmadd_ps ( right_r_i, left_r12_c7_r, _mm256_fmadd_ps (right_i_r, left_r12_c7_i, output_r12))); _mm256_store_ps (&(C[13] + c_c)->real, _mm256_fmadd_ps ( right_r_i, left_r13_c7_r, _mm256_fmadd_ps (right_i_r, left_r13_c7_i, output_r13))); _mm256_store_ps (&(C[14] + c_c)->real, _mm256_fmadd_ps ( right_r_i, left_r14_c7_r, _mm256_fmadd_ps (right_i_r, left_r14_c7_i, output_r14))); _mm256_store_ps (&(C[15] + c_c)->real, _mm256_fmadd_ps ( right_r_i, left_r15_c7_r, _mm256_fmadd_ps (right_i_r, left_r15_c7_i, output_r15))); _mm256_store_ps (&(C[16] + c_c)->real, _mm256_fmadd_ps ( right_r_i, left_r16_c7_r, _mm256_fmadd_ps (right_i_r, left_r16_c7_i, output_r16))); } #ifdef IACA_OPERATE IACA_END #endif }
347247.c
/* * FreeRTOS Kernel V10.4.4 * Copyright (C) 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * SPDX-License-Identifier: MIT * * 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. * * https://www.FreeRTOS.org * https://github.com/FreeRTOS * */ /* Scheduler includes. */ #include "FreeRTOS.h" #include "task.h" /* The critical nesting value is initialised to a non zero value to ensure interrupts don't accidentally become enabled before the scheduler is started. */ #define portINITIAL_CRITICAL_NESTING ( ( uint16_t ) 10 ) /* Initial PSW value allocated to a newly created task. * 1100011000000000 * ||||||||-------------- Fill byte * |||||||--------------- Carry Flag cleared * |||||----------------- In-service priority Flags set to low level * ||||------------------ Register bank Select 0 Flag cleared * |||------------------- Auxiliary Carry Flag cleared * ||-------------------- Register bank Select 1 Flag cleared * |--------------------- Zero Flag set * ---------------------- Global Interrupt Flag set (enabled) */ #define portPSW ( 0xc6UL ) /* The address of the pxCurrentTCB variable, but don't know or need to know its type. */ typedef void TCB_t; extern volatile TCB_t * volatile pxCurrentTCB; /* Each task maintains a count of the critical section nesting depth. Each time a critical section is entered the count is incremented. Each time a critical section is exited the count is decremented - with interrupts only being re-enabled if the count is zero. usCriticalNesting will get set to zero when the scheduler starts, but must not be initialised to zero as that could cause problems during the startup sequence. */ volatile uint16_t usCriticalNesting = portINITIAL_CRITICAL_NESTING; /*-----------------------------------------------------------*/ /* * Sets up the periodic ISR used for the RTOS tick using the interval timer. * The application writer can define configSETUP_TICK_INTERRUPT() (in * FreeRTOSConfig.h) such that their own tick interrupt configuration is used * in place of prvSetupTimerInterrupt(). */ static void prvSetupTimerInterrupt( void ); #ifndef configSETUP_TICK_INTERRUPT /* The user has not provided their own tick interrupt configuration so use the definition in this file (which uses the interval timer). */ #define configSETUP_TICK_INTERRUPT() prvSetupTimerInterrupt() #endif /* configSETUP_TICK_INTERRUPT */ /* * Defined in portasm.s87, this function starts the scheduler by loading the * context of the first task to run. */ extern void vPortStartFirstTask( void ); /* * Used to catch tasks that attempt to return from their implementing function. */ static void prvTaskExitError( void ); /*-----------------------------------------------------------*/ /* * Initialise the stack of a task to look exactly as if a call to * portSAVE_CONTEXT had been called. * * See the header file portable.h. */ StackType_t *pxPortInitialiseStack( StackType_t *pxTopOfStack, TaskFunction_t pxCode, void *pvParameters ) { uint32_t *pulLocal; /* With large code and large data sizeof( StackType_t ) == 2, and sizeof( StackType_t * ) == 4. With small code and small data sizeof( StackType_t ) == 2 and sizeof( StackType_t * ) == 2. */ #if __DATA_MODEL__ == __DATA_MODEL_FAR__ { /* Parameters are passed in on the stack, and written using a 32-bit value hence a space is left for the second two bytes. */ pxTopOfStack--; /* Write in the parameter value. */ pulLocal = ( uint32_t * ) pxTopOfStack; *pulLocal = ( uint32_t ) pvParameters; pxTopOfStack--; /* The return address, leaving space for the first two bytes of the 32-bit value. See the comments above the prvTaskExitError() prototype at the top of this file. */ pxTopOfStack--; pulLocal = ( uint32_t * ) pxTopOfStack; *pulLocal = ( uint32_t ) prvTaskExitError; pxTopOfStack--; /* The start address / PSW value is also written in as a 32-bit value, so leave a space for the second two bytes. */ pxTopOfStack--; /* Task function start address combined with the PSW. */ pulLocal = ( uint32_t * ) pxTopOfStack; *pulLocal = ( ( ( uint32_t ) pxCode ) | ( portPSW << 24UL ) ); pxTopOfStack--; /* An initial value for the AX register. */ *pxTopOfStack = ( StackType_t ) 0x1111; pxTopOfStack--; } #else { /* The return address, leaving space for the first two bytes of the 32-bit value. See the comments above the prvTaskExitError() prototype at the top of this file. */ pxTopOfStack--; pulLocal = ( uint32_t * ) pxTopOfStack; *pulLocal = ( uint32_t ) prvTaskExitError; pxTopOfStack--; /* Task function. Again as it is written as a 32-bit value a space is left on the stack for the second two bytes. */ pxTopOfStack--; /* Task function start address combined with the PSW. */ pulLocal = ( uint32_t * ) pxTopOfStack; *pulLocal = ( ( ( uint32_t ) pxCode ) | ( portPSW << 24UL ) ); pxTopOfStack--; /* The parameter is passed in AX. */ *pxTopOfStack = ( StackType_t ) pvParameters; pxTopOfStack--; } #endif /* An initial value for the HL register. */ *pxTopOfStack = ( StackType_t ) 0x2222; pxTopOfStack--; /* CS and ES registers. */ *pxTopOfStack = ( StackType_t ) 0x0F00; pxTopOfStack--; /* The remaining general purpose registers DE and BC */ *pxTopOfStack = ( StackType_t ) 0xDEDE; pxTopOfStack--; *pxTopOfStack = ( StackType_t ) 0xBCBC; pxTopOfStack--; /* Finally the critical section nesting count is set to zero when the task first starts. */ *pxTopOfStack = ( StackType_t ) portNO_CRITICAL_SECTION_NESTING; /* Return a pointer to the top of the stack that has been generated so it can be stored in the task control block for the task. */ return pxTopOfStack; } /*-----------------------------------------------------------*/ static void prvTaskExitError( void ) { /* A function that implements a task must not exit or attempt to return to its caller as there is nothing to return to. If a task wants to exit it should instead call vTaskDelete( NULL ). Artificially force an assert() to be triggered if configASSERT() is defined, then stop here so application writers can catch the error. */ configASSERT( usCriticalNesting == ~0U ); portDISABLE_INTERRUPTS(); for( ;; ); } /*-----------------------------------------------------------*/ BaseType_t xPortStartScheduler( void ) { /* Setup the hardware to generate the tick. Interrupts are disabled when this function is called. */ configSETUP_TICK_INTERRUPT(); /* Restore the context of the first task that is going to run. */ vPortStartFirstTask(); /* Execution should not reach here as the tasks are now running! prvSetupTimerInterrupt() is called here to prevent the compiler outputting a warning about a statically declared function not being referenced in the case that the application writer has provided their own tick interrupt configuration routine (and defined configSETUP_TICK_INTERRUPT() such that their own routine will be called in place of prvSetupTimerInterrupt()). */ prvSetupTimerInterrupt(); return pdTRUE; } /*-----------------------------------------------------------*/ void vPortEndScheduler( void ) { /* It is unlikely that the RL78 port will get stopped. */ } /*-----------------------------------------------------------*/ static void prvSetupTimerInterrupt( void ) { const uint16_t usClockHz = 15000UL; /* Internal clock. */ const uint16_t usCompareMatch = ( usClockHz / configTICK_RATE_HZ ) + 1UL; /* Use the internal 15K clock. */ OSMC = ( uint8_t ) 0x16; #ifdef RTCEN { /* Supply the interval timer clock. */ RTCEN = ( uint8_t ) 1U; /* Disable INTIT interrupt. */ ITMK = ( uint8_t ) 1; /* Disable ITMC operation. */ ITMC = ( uint8_t ) 0x0000; /* Clear INIT interrupt. */ ITIF = ( uint8_t ) 0; /* Set interval and enable interrupt operation. */ ITMC = usCompareMatch | 0x8000U; /* Enable INTIT interrupt. */ ITMK = ( uint8_t ) 0; } #endif #ifdef TMKAEN { /* Supply the interval timer clock. */ TMKAEN = ( uint8_t ) 1U; /* Disable INTIT interrupt. */ TMKAMK = ( uint8_t ) 1; /* Disable ITMC operation. */ ITMC = ( uint8_t ) 0x0000; /* Clear INIT interrupt. */ TMKAIF = ( uint8_t ) 0; /* Set interval and enable interrupt operation. */ ITMC = usCompareMatch | 0x8000U; /* Enable INTIT interrupt. */ TMKAMK = ( uint8_t ) 0; } #endif } /*-----------------------------------------------------------*/
646992.c
#include <stdio.h> int main() { int x = 0; int y = 0; int z = 0; if (y == x) { x = -5; } else { x = 6; } y = 7; z = x; y = 8; return 0; /*x and z out of scope*/ }
360501.c
#include <string.h> #include "freertos/FreeRTOS.h" #include "freertos/task.h" #include "cJSON.h" #include "driver/gpio.h" #include "esp_system.h" #include "esp_log.h" #include "esp_http_client.h" #include "esp_https_ota.h" #include "wifi_functions.h" #define FIRMWARE_VERSION 0.1 #define UPDATE_JSON_URL "https://microshak.com/esp32/firmware.json" // server certificates extern const char server_cert_pem_start[] asm("_binary_certs_pem_start"); extern const char server_cert_pem_end[] asm("_binary_certs_pem_end"); // receive buffer char rcv_buffer[200]; // esp_http_client event handler esp_err_t _http_event_handler(esp_http_client_event_t *evt) { switch(evt->event_id) { case HTTP_EVENT_ERROR: break; case HTTP_EVENT_ON_CONNECTED: break; case HTTP_EVENT_HEADER_SENT: break; case HTTP_EVENT_ON_HEADER: break; case HTTP_EVENT_ON_DATA: if (!esp_http_client_is_chunked_response(evt->client)) { strncpy(rcv_buffer, (char*)evt->data, evt->data_len); } break; case HTTP_EVENT_ON_FINISH: break; case HTTP_EVENT_DISCONNECTED: break; } return ESP_OK; } // Blink task void ml_task(void *pvParameter) { while(1) { //ML on this thread } } // Check update task // downloads every 1 min the json file with the latest firmware void check_update_task(void *pvParameter) { while(1) { printf("Looking for a new firmware...\n"); // configure the esp_http_client esp_http_client_config_t config = { .url = UPDATE_JSON_URL, .event_handler = _http_event_handler, }; esp_http_client_handle_t client = esp_http_client_init(&config); // downloading the json file esp_err_t err = esp_http_client_perform(client); if(err == ESP_OK) { // parse the json file cJSON *json = cJSON_Parse(rcv_buffer); if(json == NULL) printf("downloaded file is not a valid json, aborting...\n"); else { cJSON *version = cJSON_GetObjectItemCaseSensitive(json, "version"); cJSON *file = cJSON_GetObjectItemCaseSensitive(json, "file"); // check the version if(!cJSON_IsNumber(version)) printf("unable to read new version, aborting...\n"); else { double new_version = version->valuedouble; if(new_version > FIRMWARE_VERSION) { printf("current firmware version (%.1f) is lower than the available one (%.1f), upgrading...\n", FIRMWARE_VERSION, new_version); if(cJSON_IsString(file) && (file->valuestring != NULL)) { printf("downloading and installing new firmware (%s)...\n", file->valuestring); esp_http_client_config_t ota_client_config = { .url = file->valuestring, .cert_pem = server_cert_pem_start, }; esp_err_t ret = esp_https_ota(&ota_client_config); if (ret == ESP_OK) { printf("OTA OK, restarting...\n"); esp_restart(); } else { printf("OTA failed...\n"); } } else printf("unable to read the new file name, aborting...\n"); } else printf("current firmware version (%.1f) is greater or equal to the available one (%.1f), nothing to do...\n", FIRMWARE_VERSION, new_version); } } } else printf("unable to download the json file, aborting...\n"); // cleanup esp_http_client_cleanup(client); printf("\n"); vTaskDelay(60000 / portTICK_PERIOD_MS); } } void app_main() { printf("HTTPS OTA, firmware %.1f\n\n", FIRMWARE_VERSION); wifi_initialise(); wifi_wait_connected(); printf("Connected to wifi network\n"); xTaskCreate(&ml_task, "ml_task", configMINIMAL_STACK_SIZE, NULL, 5, NULL); xTaskCreate(&check_update_task, "check_update_task", 8192, NULL, 5, NULL); } // Event group for wifi connection static EventGroupHandle_t wifi_event_group; const int CONNECTED_BIT = BIT0; // Wifi event handler static esp_err_t event_handler(void *ctx, system_event_t *event) { switch(event->event_id) { case SYSTEM_EVENT_STA_START: esp_wifi_connect(); break; case SYSTEM_EVENT_STA_GOT_IP: xEventGroupSetBits(wifi_event_group, CONNECTED_BIT); break; case SYSTEM_EVENT_STA_DISCONNECTED: esp_wifi_connect(); break; default: break; } return ESP_OK; } void wifi_initialise(void) { // initialize NVS, required for wifi ESP_ERROR_CHECK(nvs_flash_init()); // connect to the wifi network wifi_event_group = xEventGroupCreate(); tcpip_adapter_init(); ESP_ERROR_CHECK(esp_event_loop_init(event_handler, NULL)); wifi_init_config_t wifi_init_config = WIFI_INIT_CONFIG_DEFAULT(); ESP_ERROR_CHECK(esp_wifi_init(&wifi_init_config)); ESP_ERROR_CHECK(esp_wifi_set_storage(WIFI_STORAGE_RAM)); ESP_ERROR_CHECK(esp_wifi_set_mode(WIFI_MODE_STA)); wifi_config_t wifi_config = { .sta = { .ssid = WIFI_SSID, .password = WIFI_PASS, }, }; ESP_ERROR_CHECK(esp_wifi_set_config(ESP_IF_WIFI_STA, &wifi_config)); ESP_ERROR_CHECK(esp_wifi_start()); } void wifi_wait_connected() { xEventGroupWaitBits(wifi_event_group, CONNECTED_BIT, false, true, portMAX_DELAY); }
120753.c
/** * AlgorithmEx - Exercise codes for 'Introdution of algorithms (Third edition)' * * MIT License * * Copyright (c) 2016 Enix Yu * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. ******************************************************************************* */ #include <limits.h> #include "exhaustive_search.h" void esFindMaxSubarray(int *arr, int low, int high, int *resultLow, int *resultHigh, int *sum) { int i, j, k, tempSum = INT_MIN; int candidateSum = INT_MIN, tempLow, tempHigh; if (low == high) { *resultLow = low; *resultHigh = low; *sum = arr[low]; return; } for (i = low; i <= high; i ++) { for (j = low; j <= i; j ++) { tempSum = 0; for (k = j; k <= i; k ++) { tempSum += arr[k]; } if (tempSum > candidateSum) { candidateSum = tempSum; tempLow = j; tempHigh = i; } } } *resultLow = tempLow; *resultHigh = tempHigh; *sum = candidateSum; }
107015.c
#include <sys/types.h> #include <signal.h> #include "defs.h" char dflag; char lflag; char rflag; char tflag; char vflag; char *symbol_prefix; char *file_prefix = "y"; char *myname = "yacc"; char *temp_form = "yacc.XXXXXXX"; int lineno; int outline; char *action_file_name; char *code_file_name; char *defines_file_name; char *input_file_name = ""; char *output_file_name; char *text_file_name; char *union_file_name; char *verbose_file_name; FILE *action_file; /* a temp file, used to save actions associated */ /* with rules until the parser is written */ FILE *code_file; /* y.code.c (used when the -r option is specified) */ FILE *defines_file; /* y.tab.h */ FILE *input_file; /* the input file */ FILE *output_file; /* y.tab.c */ FILE *text_file; /* a temp file, used to save text until all */ /* symbols have been defined */ FILE *union_file; /* a temp file, used to save the union */ /* definition until all symbol have been */ /* defined */ FILE *verbose_file; /* y.output */ int nitems; int nrules; int nsyms; int ntokens; int nvars; int start_symbol; char **symbol_name; short *symbol_value; short *symbol_prec; char *symbol_assoc; short *ritem; short *rlhs; short *rrhs; short *rprec; char *rassoc; short **derives; char *nullable; extern char *mktemp(); extern char *getenv(); done(k) int k; { if (action_file) { fclose(action_file); unlink(action_file_name); } if (text_file) { fclose(text_file); unlink(text_file_name); } if (union_file) { fclose(union_file); unlink(union_file_name); } exit(k); } void onintr(signo) int signo; { done(1); } set_signals() { #ifdef SIGINT if (signal(SIGINT, SIG_IGN) != SIG_IGN) signal(SIGINT, onintr); #endif #ifdef SIGTERM if (signal(SIGTERM, SIG_IGN) != SIG_IGN) signal(SIGTERM, onintr); #endif #ifdef SIGHUP if (signal(SIGHUP, SIG_IGN) != SIG_IGN) signal(SIGHUP, onintr); #endif } usage() { fprintf(stderr, "usage: %s [-dlrtv] [-b file_prefix] [-p symbol_prefix] filename\n", myname); exit(1); } getargs(argc, argv) int argc; char *argv[]; { register int i; register char *s; if (argc > 0) myname = argv[0]; for (i = 1; i < argc; ++i) { s = argv[i]; if (*s != '-') break; switch (*++s) { case '\0': input_file = stdin; if (i + 1 < argc) usage(); return; case '-': ++i; goto no_more_options; case 'b': if (*++s) file_prefix = s; else if (++i < argc) file_prefix = argv[i]; else usage(); continue; case 'd': dflag = 1; break; case 'l': lflag = 1; break; case 'p': if (*++s) symbol_prefix = s; else if (++i < argc) symbol_prefix = argv[i]; else usage(); continue; case 'r': rflag = 1; break; case 't': tflag = 1; break; case 'v': vflag = 1; break; default: usage(); } for (;;) { switch (*++s) { case '\0': goto end_of_option; case 'd': dflag = 1; break; case 'l': lflag = 1; break; case 'r': rflag = 1; break; case 't': tflag = 1; break; case 'v': vflag = 1; break; default: usage(); } } end_of_option:; } no_more_options:; if (i + 1 != argc) usage(); input_file_name = argv[i]; } char * allocate(n) unsigned n; { register char *p; p = NULL; if (n) { p = CALLOC(1, n); if (!p) no_space(); } return (p); } create_file_names() { int i, len; char *tmpdir; tmpdir = getenv("TMPDIR"); if (tmpdir == 0) tmpdir = "/tmp"; len = strlen(tmpdir); i = len + 13; if (len && tmpdir[len-1] != '/') ++i; action_file_name = MALLOC(i); if (action_file_name == 0) no_space(); text_file_name = MALLOC(i); if (text_file_name == 0) no_space(); union_file_name = MALLOC(i); if (union_file_name == 0) no_space(); strcpy(action_file_name, tmpdir); strcpy(text_file_name, tmpdir); strcpy(union_file_name, tmpdir); if (len && tmpdir[len - 1] != '/') { action_file_name[len] = '/'; text_file_name[len] = '/'; union_file_name[len] = '/'; ++len; } strcpy(action_file_name + len, temp_form); strcpy(text_file_name + len, temp_form); strcpy(union_file_name + len, temp_form); action_file_name[len + 5] = 'a'; text_file_name[len + 5] = 't'; union_file_name[len + 5] = 'u'; mktemp(action_file_name); mktemp(text_file_name); mktemp(union_file_name); len = strlen(file_prefix); output_file_name = MALLOC(len + 7); if (output_file_name == 0) no_space(); strcpy(output_file_name, file_prefix); strcpy(output_file_name + len, OUTPUT_SUFFIX); if (rflag) { code_file_name = MALLOC(len + 8); if (code_file_name == 0) no_space(); strcpy(code_file_name, file_prefix); strcpy(code_file_name + len, CODE_SUFFIX); } else code_file_name = output_file_name; if (dflag) { defines_file_name = MALLOC(len + 7); if (defines_file_name == 0) no_space(); strcpy(defines_file_name, file_prefix); strcpy(defines_file_name + len, DEFINES_SUFFIX); } if (vflag) { verbose_file_name = MALLOC(len + 8); if (verbose_file_name == 0) no_space(); strcpy(verbose_file_name, file_prefix); strcpy(verbose_file_name + len, VERBOSE_SUFFIX); } } open_files() { create_file_names(); if (input_file == 0) { input_file = fopen(input_file_name, "r"); if (input_file == 0) open_error(input_file_name); } action_file = fopen(action_file_name, "w"); if (action_file == 0) open_error(action_file_name); text_file = fopen(text_file_name, "w"); if (text_file == 0) open_error(text_file_name); if (vflag) { verbose_file = fopen(verbose_file_name, "w"); if (verbose_file == 0) open_error(verbose_file_name); } if (dflag) { defines_file = fopen(defines_file_name, "w"); if (defines_file == 0) open_error(defines_file_name); union_file = fopen(union_file_name, "w"); if (union_file == 0) open_error(union_file_name); } output_file = fopen(output_file_name, "w"); if (output_file == 0) open_error(output_file_name); if (rflag) { code_file = fopen(code_file_name, "w"); if (code_file == 0) open_error(code_file_name); } else code_file = output_file; } int main(argc, argv) int argc; char *argv[]; { set_signals(); getargs(argc, argv); open_files(); reader(); lr0(); lalr(); make_parser(); verbose(); output(); done(0); /*NOTREACHED*/ }
6951.c
// Last Modified by winder on May. 25 2001 // yinjia.c #include <armor.h> inherit ARMOR; void create() { set_name("亮銀甲", ({"silver armor", "jia", "armor"})); set_weight(30000); if( clonep() ) set_default_object(__FILE__); else { set("unit", "件"); set("long", "一件銀光燦燦的盔甲.\n"); set("value", 8000); set("material", "iron"); set("armor_prop/armor", 45); set("armor_prop/dodge", -10); } setup(); }
10187.c
/* (C) Copyright IBM Corp. 2006 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 IBM 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. Author: Joel Schopp <[email protected]> */ #include <_ansi.h> #include <stdio.h> #include "c99ppe.h" typedef struct { char* buf; unsigned int pad0[ 3 ]; size_t size; unsigned int pad1[ 3 ]; size_t count; unsigned int pad2[ 3 ]; int fp; } c99_fread_t; #ifndef _REENT_ONLY size_t _DEFUN (fread, (buf, size, count, fp), _PTR __restrict buf _AND size_t size _AND size_t count _AND FILE *__restrict fp) { c99_fread_t args; CHECK_INIT(_REENT); args.buf = buf; args.size = size; args.count = count; args.fp = fp->_fp; return __send_to_ppe(SPE_C99_SIGNALCODE, SPE_C99_FREAD, &args); } #endif /* ! _REENT_ONLY */
834407.c
/* Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "httpd.h" #include "http_config.h" #include "apr_strings.h" #if !defined(_MSC_VER) && !defined(NETWARE) #include "ap_config_auto.h" #endif #include "mod_dav.h" #include "repos.h" /* per-server configuration */ typedef struct { const char *lockdb_path; } dav_fs_server_conf; extern module AP_MODULE_DECLARE_DATA dav_fs_module; const char *dav_get_lockdb_path(const request_rec *r) { dav_fs_server_conf *conf; conf = ap_get_module_config(r->server->module_config, &dav_fs_module); return conf->lockdb_path; } static void *dav_fs_create_server_config(apr_pool_t *p, server_rec *s) { dav_fs_server_conf *conf = apr_pcalloc(p, sizeof(dav_fs_server_conf)); #ifdef DEFAULT_EXP_DAVLOCKDB conf->lockdb_path = DEFAULT_EXP_DAVLOCKDB; if (*conf->lockdb_path == '\0') { conf->lockdb_path = NULL; } #endif return conf; } static void *dav_fs_merge_server_config(apr_pool_t *p, void *base, void *overrides) { dav_fs_server_conf *parent = base; dav_fs_server_conf *child = overrides; dav_fs_server_conf *newconf; newconf = apr_pcalloc(p, sizeof(*newconf)); newconf->lockdb_path = child->lockdb_path ? child->lockdb_path : parent->lockdb_path; return newconf; } /* * Command handler for the DAVLockDB directive, which is TAKE1 */ static const char *dav_fs_cmd_davlockdb(cmd_parms *cmd, void *config, const char *arg1) { dav_fs_server_conf *conf; conf = ap_get_module_config(cmd->server->module_config, &dav_fs_module); conf->lockdb_path = ap_server_root_relative(cmd->pool, arg1); if (!conf->lockdb_path) { return apr_pstrcat(cmd->pool, "Invalid DAVLockDB path ", arg1, NULL); } return NULL; } static const command_rec dav_fs_cmds[] = { /* per server */ AP_INIT_TAKE1("DAVLockDB", dav_fs_cmd_davlockdb, NULL, RSRC_CONF, "specify a lock database"), { NULL } }; static void register_hooks(apr_pool_t *p) { dav_hook_gather_propsets(dav_fs_gather_propsets, NULL, NULL, APR_HOOK_MIDDLE); dav_hook_find_liveprop(dav_fs_find_liveprop, NULL, NULL, APR_HOOK_MIDDLE); dav_hook_insert_all_liveprops(dav_fs_insert_all_liveprops, NULL, NULL, APR_HOOK_MIDDLE); dav_fs_register(p); } AP_DECLARE_MODULE(dav_fs) = { STANDARD20_MODULE_STUFF, NULL, /* dir config creater */ NULL, /* dir merger --- default is to override */ dav_fs_create_server_config, /* server config */ dav_fs_merge_server_config, /* merge server config */ dav_fs_cmds, /* command table */ register_hooks, /* register hooks */ };
226870.c
#include <pebble.h> #include "analog.h" static GBitmap *s_bitmap; static BitmapLayer *s_bitmap_layer; static Window *s_window; static Layer *s_simple_bg_layer, *s_date_layer, *s_hands_layer; static TextLayer *s_day_label, *s_num_label; static GPath *s_min_tick_paths[NUM_MIN_TICKS]; static GPath *s_max_tick_paths[NUM_MAX_TICKS]; static GPath *s_minute_arrow, *s_hour_arrow; static char s_num_buffer[4], s_day_buffer[6]; static GPoint max_marks[NUM_MAX_TICKS][4]; static GPoint min_marks[NUM_MIN_TICKS][4]; static struct GPathInfo hours_array[NUM_MAX_TICKS]; static struct GPathInfo minutes_array[NUM_MIN_TICKS]; #define MinMarkRStart 84 #define MinMarkREnd 90 #define MinMarkWide 240 #define MaxMarkRStart 78 #define MaxMarkREnd 90 #define MaxMarkWide 340 // Matching values to those in 'Settings' typedef enum { AppKeyShowHourTicks = 0, AppKeyShowMinTicks = 1 } AppKey; static void bg_update_proc(Layer *layer, GContext *ctx) { //graphics_context_set_fill_color(ctx, GColorBlack); //graphics_fill_rect(ctx, layer_get_bounds(layer), 0, GCornerNone); graphics_context_set_fill_color(ctx, GColorBlack); for (int i = 0; i < NUM_MAX_TICKS; ++i) { const int x_offset = PBL_IF_ROUND_ELSE(18, 0); const int y_offset = PBL_IF_ROUND_ELSE(6, 0); //gpath_move_to(s_tick_paths[i], GPoint(x_offset, y_offset)); #if defined(PBL_ROUND) gpath_draw_filled(ctx, s_max_tick_paths[i]); #endif } for (int i = 0; i < NUM_MIN_TICKS; ++i) { const int x_offset = PBL_IF_ROUND_ELSE(18, 0); const int y_offset = PBL_IF_ROUND_ELSE(6, 0); //gpath_move_to(s_tick_paths[i], GPoint(x_offset, y_offset)); #if defined(PBL_ROUND) gpath_draw_filled(ctx, s_min_tick_paths[i]); #endif } } static void hands_update_proc(Layer *layer, GContext *ctx) { GRect bounds = layer_get_bounds(layer); GPoint center = grect_center_point(&bounds); const int16_t second_hand_length = PBL_IF_ROUND_ELSE((bounds.size.w / 2) - 19, bounds.size.w / 2); time_t now = time(NULL); struct tm *t = localtime(&now); int32_t second_angle = TRIG_MAX_ANGLE * t->tm_sec / 60; GPoint second_hand = { .x = (int16_t)(sin_lookup(second_angle) * (int32_t)second_hand_length / TRIG_MAX_RATIO) + center.x, .y = (int16_t)(-cos_lookup(second_angle) * (int32_t)second_hand_length / TRIG_MAX_RATIO) + center.y, }; // second hand graphics_context_set_stroke_color(ctx, GColorBlack); graphics_draw_line(ctx, second_hand, center); // minute/hour hand graphics_context_set_fill_color(ctx, GColorBlack); graphics_context_set_stroke_color(ctx, GColorLightGray); gpath_rotate_to(s_minute_arrow, TRIG_MAX_ANGLE * t->tm_min / 60); gpath_draw_filled(ctx, s_minute_arrow); gpath_draw_outline(ctx, s_minute_arrow); gpath_rotate_to(s_hour_arrow, (TRIG_MAX_ANGLE * (((t->tm_hour % 12) * 6) + (t->tm_min / 10))) / (12 * 6)); gpath_draw_filled(ctx, s_hour_arrow); gpath_draw_outline(ctx, s_hour_arrow); // dot in the middle graphics_context_set_fill_color(ctx, GColorWhite); graphics_fill_rect(ctx, GRect(bounds.size.w / 2 - 1, bounds.size.h / 2 - 1, 3, 3), 0, GCornerNone); } static void date_update_proc(Layer *layer, GContext *ctx) { time_t now = time(NULL); struct tm *t = localtime(&now); strftime(s_day_buffer, sizeof(s_day_buffer), "%a", t); //%b for month text_layer_set_text(s_day_label, s_day_buffer); strftime(s_num_buffer, sizeof(s_num_buffer), "%d", t); text_layer_set_text(s_num_label, s_num_buffer); } static void handle_second_tick(struct tm *tick_time, TimeUnits units_changed) { layer_mark_dirty(window_get_root_layer(s_window)); } static void window_load(Window *window) { Layer *window_layer = window_get_root_layer(window); GRect bounds = layer_get_bounds(window_layer); s_simple_bg_layer = layer_create(bounds); layer_set_update_proc(s_simple_bg_layer, bg_update_proc); layer_add_child(window_layer, s_simple_bg_layer); s_date_layer = layer_create(bounds); layer_set_update_proc(s_date_layer, date_update_proc); layer_add_child(window_layer, s_date_layer); s_day_label = text_layer_create(PBL_IF_ROUND_ELSE( //GRect(63, 114, 27, 20), //GRect(46, 114, 27, 20))); GRect(103, 114, 27, 20), GRect(86, 114, 27, 20))); text_layer_set_text(s_day_label, s_day_buffer); text_layer_set_background_color(s_day_label, GColorWhite); text_layer_set_text_color(s_day_label, GColorBlack); text_layer_set_font(s_day_label, fonts_get_system_font(FONT_KEY_GOTHIC_18)); layer_add_child(s_date_layer, text_layer_get_layer(s_day_label)); s_num_label = text_layer_create(PBL_IF_ROUND_ELSE( //GRect(90, 114, 18, 20), //GRect(73, 114, 18, 20))); GRect(130, 114, 18, 20), GRect(113, 114, 18, 20))); text_layer_set_text(s_num_label, s_num_buffer); text_layer_set_background_color(s_num_label, GColorWhite); text_layer_set_text_color(s_num_label, GColorBlack); text_layer_set_font(s_num_label, fonts_get_system_font(FONT_KEY_GOTHIC_18_BOLD)); layer_add_child(s_date_layer, text_layer_get_layer(s_num_label)); s_hands_layer = layer_create(bounds); layer_set_update_proc(s_hands_layer, hands_update_proc); layer_add_child(window_layer, s_hands_layer); } static void window_unload(Window *window) { layer_destroy(s_simple_bg_layer); layer_destroy(s_date_layer); text_layer_destroy(s_day_label); text_layer_destroy(s_num_label); layer_destroy(s_hands_layer); } static void init() { s_window = window_create(); window_set_background_color(s_window, GColorWhite); Layer *window_layer = window_get_root_layer(s_window); GRect bounds = layer_get_bounds(window_layer); s_bitmap_layer = bitmap_layer_create(bounds); layer_add_child(window_layer, bitmap_layer_get_layer(s_bitmap_layer)); s_bitmap = gbitmap_create_with_resource(RESOURCE_ID_SPUR_IMAGE); bitmap_layer_set_compositing_mode(s_bitmap_layer, GCompOpSet); bitmap_layer_set_bitmap(s_bitmap_layer, s_bitmap); window_set_window_handlers(s_window, (WindowHandlers) { .load = window_load, .unload = window_unload, }); window_stack_push(s_window, true); s_day_buffer[0] = '\0'; s_num_buffer[0] = '\0'; // init hand paths s_minute_arrow = gpath_create(&MINUTE_HAND_POINTS); s_hour_arrow = gpath_create(&HOUR_HAND_POINTS); GPoint center = grect_center_point(&bounds); gpath_move_to(s_minute_arrow, center); gpath_move_to(s_hour_arrow, center); //for (int i = 0; i < NUM_MAX_TICKS; ++i) { // s_max_tick_paths[i] = gpath_create(&ANALOG_BG_POINTS[i]); //} // init clock face paths for (int i = 0; i < NUM_MAX_TICKS; ++i) { int32_t mark_angle = TRIG_MAX_ANGLE * i / NUM_MAX_TICKS; max_marks[i][0].y= (int16_t)(-cos_lookup(mark_angle-MaxMarkWide) * (int32_t)MaxMarkRStart / TRIG_MAX_RATIO); max_marks[i][0].x= (int16_t)( sin_lookup(mark_angle-MaxMarkWide) * (int32_t)MaxMarkRStart / TRIG_MAX_RATIO); max_marks[i][1].y= (int16_t)(-cos_lookup(mark_angle-MaxMarkWide) * (int32_t)MaxMarkREnd / TRIG_MAX_RATIO); max_marks[i][1].x= (int16_t)( sin_lookup(mark_angle-MaxMarkWide) * (int32_t)MaxMarkREnd / TRIG_MAX_RATIO); max_marks[i][2].y= (int16_t)(-cos_lookup(mark_angle+MaxMarkWide) * (int32_t)MaxMarkREnd / TRIG_MAX_RATIO); max_marks[i][2].x= (int16_t)( sin_lookup(mark_angle+MaxMarkWide) * (int32_t)MaxMarkREnd / TRIG_MAX_RATIO); max_marks[i][3].y= (int16_t)(-cos_lookup(mark_angle+MaxMarkWide) * (int32_t)MaxMarkRStart / TRIG_MAX_RATIO); max_marks[i][3].x= (int16_t)( sin_lookup(mark_angle+MaxMarkWide) * (int32_t)MaxMarkRStart / TRIG_MAX_RATIO); hours_array[i].num_points = 4; hours_array[i].points = &max_marks[i][0]; s_max_tick_paths[i] = gpath_create(&hours_array[i]); gpath_move_to(s_max_tick_paths[i], center); } // init clock face paths for (int i = 0; i < NUM_MIN_TICKS; ++i) { int32_t mark_angle = TRIG_MAX_ANGLE * i / NUM_MIN_TICKS; min_marks[i][0].y= (int16_t)(-cos_lookup(mark_angle-MinMarkWide) * (int32_t)MinMarkRStart / TRIG_MAX_RATIO); min_marks[i][0].x= (int16_t)( sin_lookup(mark_angle-MinMarkWide) * (int32_t)MinMarkRStart / TRIG_MAX_RATIO); min_marks[i][1].y= (int16_t)(-cos_lookup(mark_angle-MinMarkWide) * (int32_t)MinMarkREnd / TRIG_MAX_RATIO); min_marks[i][1].x= (int16_t)( sin_lookup(mark_angle-MinMarkWide) * (int32_t)MinMarkREnd / TRIG_MAX_RATIO); min_marks[i][2].y= (int16_t)(-cos_lookup(mark_angle+MinMarkWide) * (int32_t)MinMarkREnd / TRIG_MAX_RATIO); min_marks[i][2].x= (int16_t)( sin_lookup(mark_angle+MinMarkWide) * (int32_t)MinMarkREnd / TRIG_MAX_RATIO); min_marks[i][3].y= (int16_t)(-cos_lookup(mark_angle+MinMarkWide) * (int32_t)MinMarkRStart / TRIG_MAX_RATIO); min_marks[i][3].x= (int16_t)( sin_lookup(mark_angle+MinMarkWide) * (int32_t)MinMarkRStart / TRIG_MAX_RATIO); minutes_array[i].num_points = 4; minutes_array[i].points = &min_marks[i][0]; //comment out to remove minute ticks s_min_tick_paths[i] = gpath_create(&minutes_array[i]); gpath_move_to(s_min_tick_paths[i], center); } tick_timer_service_subscribe(SECOND_UNIT, handle_second_tick); } static void deinit() { gbitmap_destroy(s_bitmap); bitmap_layer_destroy(s_bitmap_layer); gpath_destroy(s_hour_arrow); for (int i = 0; i < NUM_MAX_TICKS; ++i) { gpath_destroy(s_max_tick_paths[i]); } for (int i = 0; i < NUM_MIN_TICKS; ++i) { gpath_destroy(s_min_tick_paths[i]); } tick_timer_service_unsubscribe(); window_destroy(s_window); } int main() { init(); app_event_loop(); deinit(); }
813341.c
#include <errno.h> #include <stdbool.h> #include <stdio.h> #include <sys/socket.h> #include <sys/stat.h> #include <unistd.h> #include "unixkit-posix.h" char *unixkit_get_fd_path(int fd) { errno = ENOSYS; return NULL; } bool unixkit_get_peer_credentials(int socket, uid_t *uid, gid_t *gid) { return !getpeereid(socket, uid, gid); } int unixkit_unix_listen(const char *path, mode_t mode) { return unixkit_unix_listen_posix(path, mode); } bool unixkit_rename(const char *old, const char *new) { struct stat sb; if (stat(new, &sb) < 0 && errno == ENOENT) return !rename(old, new); errno = EEXIST; return false; } bool unixkit_renameat(int old_dirfd, const char *old, int new_dirfd, const char *new) { struct stat sb; if (fstatat(new_dirfd, new, &sb, 0) < 0 && errno == ENOENT) return !renameat(old_dirfd, old, new_dirfd, new); errno = EEXIST; return false; } bool unixkit_pipe(int pipefd[2]) { return !pipe2(pipefd, O_CLOEXEC); } bool unixkit_socketpair(int domain, int type, int protocol, int pairfd[2]) { return !socketpair(domain, type | SOCK_CLOEXEC, protocol, pairfd); }
586739.c
/** @file Copyright (c) 2016 - 2020, ARM Limited. All rights reserved. SPDX-License-Identifier: BSD-2-Clause-Patent @par Glossary: - Sbbr or SBBR - Server Base Boot Requirements @par Reference(s): - Arm Server Base Boot Requirements 1.2, September 2019 **/ #include <Library/PrintLib.h> #include <Library/UefiLib.h> #include <Library/ShellLib.h> #include <Library/UefiBootServicesTableLib.h> #include <Library/BaseMemoryLib.h> #include <Library/DebugLib.h> #include <Library/MemoryAllocationLib.h> #include <Library/AcpiViewCommandLib.h> #include "AcpiParser.h" #include "AcpiTableParser.h" #include "AcpiView.h" #include "AcpiViewConfig.h" #if defined(MDE_CPU_ARM) || defined (MDE_CPU_AARCH64) #include "Arm/SbbrValidator.h" #endif STATIC UINT32 mTableCount; STATIC UINT32 mBinTableCount; /** This function dumps the ACPI table to a file. @param [in] Ptr Pointer to the ACPI table data. @param [in] Length The length of the ACPI table. @retval TRUE Success. @retval FALSE Failure. **/ STATIC BOOLEAN DumpAcpiTableToFile ( IN CONST UINT8* Ptr, IN CONST UINTN Length ) { CHAR16 FileNameBuffer[MAX_FILE_NAME_LEN]; UINTN TransferBytes; SELECTED_ACPI_TABLE *SelectedTable; GetSelectedAcpiTable (&SelectedTable); UnicodeSPrint ( FileNameBuffer, sizeof (FileNameBuffer), L".\\%s%04d.bin", SelectedTable->Name, mBinTableCount++ ); Print (L"Dumping ACPI table to : %s ... ", FileNameBuffer); TransferBytes = ShellDumpBufferToFile (FileNameBuffer, Ptr, Length); return (Length == TransferBytes); } /** This function processes the table reporting options for the ACPI table. @param [in] Signature The ACPI table Signature. @param [in] TablePtr Pointer to the ACPI table data. @param [in] Length The length fo the ACPI table. @retval Returns TRUE if the ACPI table should be traced. **/ BOOLEAN ProcessTableReportOptions ( IN CONST UINT32 Signature, IN CONST UINT8* TablePtr, IN CONST UINT32 Length ) { UINTN OriginalAttribute; UINT8 *SignaturePtr; BOOLEAN Log; BOOLEAN HighLight; SELECTED_ACPI_TABLE *SelectedTable; // // set local variables to suppress incorrect compiler/analyzer warnings // OriginalAttribute = 0; SignaturePtr = (UINT8*)(UINTN)&Signature; Log = FALSE; HighLight = GetColourHighlighting (); GetSelectedAcpiTable (&SelectedTable); switch (GetReportOption ()) { case ReportAll: Log = TRUE; break; case ReportSelected: if (Signature == SelectedTable->Type) { Log = TRUE; SelectedTable->Found = TRUE; } break; case ReportTableList: if (mTableCount == 0) { if (HighLight) { OriginalAttribute = gST->ConOut->Mode->Attribute; gST->ConOut->SetAttribute ( gST->ConOut, EFI_TEXT_ATTR(EFI_CYAN, ((OriginalAttribute&(BIT4|BIT5|BIT6))>>4)) ); } Print (L"\nInstalled Table(s):\n"); if (HighLight) { gST->ConOut->SetAttribute (gST->ConOut, OriginalAttribute); } } Print ( L"\t%4d. %c%c%c%c\n", ++mTableCount, SignaturePtr[0], SignaturePtr[1], SignaturePtr[2], SignaturePtr[3] ); break; case ReportDumpBinFile: if (Signature == SelectedTable->Type) { SelectedTable->Found = TRUE; DumpAcpiTableToFile (TablePtr, Length); } break; case ReportMax: // We should never be here. // This case is only present to prevent compiler warning. break; } // switch if (Log) { if (HighLight) { OriginalAttribute = gST->ConOut->Mode->Attribute; gST->ConOut->SetAttribute ( gST->ConOut, EFI_TEXT_ATTR(EFI_LIGHTBLUE, ((OriginalAttribute&(BIT4|BIT5|BIT6))>>4)) ); } Print ( L"\n\n --------------- %c%c%c%c Table --------------- \n\n", SignaturePtr[0], SignaturePtr[1], SignaturePtr[2], SignaturePtr[3] ); if (HighLight) { gST->ConOut->SetAttribute (gST->ConOut, OriginalAttribute); } } return Log; } /** This function iterates the configuration table entries in the system table, retrieves the RSDP pointer and starts parsing the ACPI tables. @param [in] SystemTable Pointer to the EFI system table. @retval Returns EFI_NOT_FOUND if the RSDP pointer is not found. Returns EFI_UNSUPPORTED if the RSDP version is less than 2. Returns EFI_SUCCESS if successful. **/ EFI_STATUS EFIAPI AcpiView ( IN EFI_SYSTEM_TABLE* SystemTable ) { EFI_STATUS Status; UINTN Index; EFI_CONFIGURATION_TABLE* EfiConfigurationTable; BOOLEAN FoundAcpiTable; UINTN OriginalAttribute; UINTN PrintAttribute; EREPORT_OPTION ReportOption; UINT8* RsdpPtr; UINT32 RsdpLength; UINT8 RsdpRevision; PARSE_ACPI_TABLE_PROC RsdpParserProc; BOOLEAN Trace; SELECTED_ACPI_TABLE *SelectedTable; // // set local variables to suppress incorrect compiler/analyzer warnings // EfiConfigurationTable = NULL; OriginalAttribute = 0; // Reset Table counts mTableCount = 0; mBinTableCount = 0; // Reset The error/warning counters ResetErrorCount (); ResetWarningCount (); // Retrieve the user selection of ACPI table to process GetSelectedAcpiTable (&SelectedTable); // Search the table for an entry that matches the ACPI Table Guid FoundAcpiTable = FALSE; for (Index = 0; Index < SystemTable->NumberOfTableEntries; Index++) { if (CompareGuid (&gEfiAcpiTableGuid, &(SystemTable->ConfigurationTable[Index].VendorGuid))) { EfiConfigurationTable = &SystemTable->ConfigurationTable[Index]; FoundAcpiTable = TRUE; break; } } if (FoundAcpiTable) { RsdpPtr = (UINT8*)EfiConfigurationTable->VendorTable; // The RSDP revision is 1 byte starting at offset 15 RsdpRevision = *(RsdpPtr + RSDP_REVISION_OFFSET); if (RsdpRevision < 2) { Print ( L"ERROR: RSDP version less than 2 is not supported.\n" ); return EFI_UNSUPPORTED; } #if defined(MDE_CPU_ARM) || defined (MDE_CPU_AARCH64) if (GetMandatoryTableValidate ()) { ArmSbbrResetTableCounts (); } #endif // The RSDP length is 4 bytes starting at offset 20 RsdpLength = *(UINT32*)(RsdpPtr + RSDP_LENGTH_OFFSET); Trace = ProcessTableReportOptions (RSDP_TABLE_INFO, RsdpPtr, RsdpLength); Status = GetParser (RSDP_TABLE_INFO, &RsdpParserProc); if (EFI_ERROR (Status)) { Print ( L"ERROR: No registered parser found for RSDP.\n" ); return Status; } RsdpParserProc ( Trace, RsdpPtr, RsdpLength, RsdpRevision ); } else { IncrementErrorCount (); Print ( L"ERROR: Failed to find ACPI Table Guid in System Configuration Table.\n" ); return EFI_NOT_FOUND; } #if defined(MDE_CPU_ARM) || defined (MDE_CPU_AARCH64) if (GetMandatoryTableValidate ()) { ArmSbbrReqsValidate ((ARM_SBBR_VERSION)GetMandatoryTableSpec ()); } #endif ReportOption = GetReportOption (); if (ReportTableList != ReportOption) { if (((ReportSelected == ReportOption) || (ReportDumpBinFile == ReportOption)) && (!SelectedTable->Found)) { Print (L"\nRequested ACPI Table not found.\n"); } else if (GetConsistencyChecking () && (ReportDumpBinFile != ReportOption)) { OriginalAttribute = gST->ConOut->Mode->Attribute; Print (L"\nTable Statistics:\n"); if (GetColourHighlighting ()) { PrintAttribute = (GetErrorCount () > 0) ? EFI_TEXT_ATTR ( EFI_RED, ((OriginalAttribute&(BIT4|BIT5|BIT6))>>4) ) : OriginalAttribute; gST->ConOut->SetAttribute (gST->ConOut, PrintAttribute); } Print (L"\t%d Error(s)\n", GetErrorCount ()); if (GetColourHighlighting ()) { PrintAttribute = (GetWarningCount () > 0) ? EFI_TEXT_ATTR ( EFI_RED, ((OriginalAttribute&(BIT4|BIT5|BIT6))>>4) ) : OriginalAttribute; gST->ConOut->SetAttribute (gST->ConOut, PrintAttribute); } Print (L"\t%d Warning(s)\n", GetWarningCount ()); if (GetColourHighlighting ()) { gST->ConOut->SetAttribute (gST->ConOut, OriginalAttribute); } } } return EFI_SUCCESS; }
289032.c
/* * Additional mixer mapping * * Copyright (c) 2002 by Takashi Iwai <[email protected]> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * */ struct usbmix_dB_map { u32 min; u32 max; }; struct usbmix_name_map { int id; const char *name; int control; struct usbmix_dB_map *dB; }; struct usbmix_selector_map { int id; int count; const char **names; }; struct usbmix_ctl_map { u32 id; const struct usbmix_name_map *map; const struct usbmix_selector_map *selector_map; int ignore_ctl_error; }; /* * USB control mappers for SB Exitigy */ /* * Topology of SB Extigy (see on the wide screen :) USB_IN[1] --->FU[2]------------------------------+->MU[16]-->PU[17]-+->FU[18]--+->EU[27]--+->EU[21]-->FU[22]--+->FU[23] > Dig_OUT[24] ^ | | | | USB_IN[3] -+->SU[5]-->FU[6]--+->MU[14] ->PU[15]->+ | | | +->FU[25] > Dig_OUT[26] ^ ^ | | | | Dig_IN[4] -+ | | | | +->FU[28]---------------------> Spk_OUT[19] | | | | Lin-IN[7] -+-->FU[8]---------+ | | +----------------------------------------> Hph_OUT[20] | | | Mic-IN[9] --+->FU[10]----------------------------+ | || | || +----------------------------------------------------+ VV V ++--+->SU[11]-->FU[12] --------------------------------------------------------------------------------------> USB_OUT[13] */ static struct usbmix_name_map extigy_map[] = { /* 1: IT pcm */ { 2, "PCM Playback" }, /* FU */ /* 3: IT pcm */ /* 4: IT digital in */ { 5, NULL }, /* DISABLED: this seems to be bogus on some firmware */ { 6, "Digital In" }, /* FU */ /* 7: IT line */ { 8, "Line Playback" }, /* FU */ /* 9: IT mic */ { 10, "Mic Playback" }, /* FU */ { 11, "Capture Source" }, /* SU */ { 12, "Capture" }, /* FU */ /* 13: OT pcm capture */ /* 14: MU (w/o controls) */ /* 15: PU (3D enh) */ /* 16: MU (w/o controls) */ { 17, NULL, 1 }, /* DISABLED: PU-switch (any effect?) */ { 17, "Channel Routing", 2 }, /* PU: mode select */ { 18, "Tone Control - Bass", UAC_FU_BASS }, /* FU */ { 18, "Tone Control - Treble", UAC_FU_TREBLE }, /* FU */ { 18, "Master Playback" }, /* FU; others */ /* 19: OT speaker */ /* 20: OT headphone */ { 21, NULL }, /* DISABLED: EU (for what?) */ { 22, "Digital Out Playback" }, /* FU */ { 23, "Digital Out1 Playback" }, /* FU */ /* FIXME: corresponds to 24 */ /* 24: OT digital out */ { 25, "IEC958 Optical Playback" }, /* FU */ { 26, "IEC958 Optical Playback" }, /* OT */ { 27, NULL }, /* DISABLED: EU (for what?) */ /* 28: FU speaker (mute) */ { 29, NULL }, /* Digital Input Playback Source? */ { 0 } /* terminator */ }; /* Sound Blaster MP3+ controls mapping * The default mixer channels have totally misleading names, * e.g. no Master and fake PCM volume * Pavel Mihaylov <[email protected]> */ static struct usbmix_dB_map mp3plus_dB_1 = {-4781, 0}; /* just guess */ static struct usbmix_dB_map mp3plus_dB_2 = {-1781, 618}; /* just guess */ static struct usbmix_name_map mp3plus_map[] = { /* 1: IT pcm */ /* 2: IT mic */ /* 3: IT line */ /* 4: IT digital in */ /* 5: OT digital out */ /* 6: OT speaker */ /* 7: OT pcm capture */ { 8, "Capture Source" }, /* FU, default PCM Capture Source */ /* (Mic, Input 1 = Line input, Input 2 = Optical input) */ { 9, "Master Playback" }, /* FU, default Speaker 1 */ /* { 10, "Mic Capture", 1 }, */ /* FU, Mic Capture */ { 10, /* "Mic Capture", */ NULL, 2, .dB = &mp3plus_dB_2 }, /* FU, Mic Capture */ { 10, "Mic Boost", 7 }, /* FU, default Auto Gain Input */ { 11, "Line Capture", .dB = &mp3plus_dB_2 }, /* FU, default PCM Capture */ { 12, "Digital In Playback" }, /* FU, default PCM 1 */ { 13, /* "Mic Playback", */ .dB = &mp3plus_dB_1 }, /* FU, default Mic Playback */ { 14, "Line Playback", .dB = &mp3plus_dB_1 }, /* FU, default Speaker */ /* 15: MU */ { 0 } /* terminator */ }; /* Topology of SB Audigy 2 NX +----------------------------->EU[27]--+ | v | +----------------------------------->SU[29]---->FU[22]-->Dig_OUT[24] | | ^ USB_IN[1]-+------------+ +->EU[17]->+->FU[11]-+ | v | v | Dig_IN[4]---+->FU[6]-->MU[16]->FU[18]-+->EU[21]->SU[31]----->FU[30]->Hph_OUT[20] | ^ | | Lin_IN[7]-+--->FU[8]---+ +->EU[23]->FU[28]------------->Spk_OUT[19] | | v +--->FU[12]------------------------------------->SU[14]--->USB_OUT[15] | ^ +->FU[13]--------------------------------------+ */ static struct usbmix_name_map audigy2nx_map[] = { /* 1: IT pcm playback */ /* 4: IT digital in */ { 6, "Digital In Playback" }, /* FU */ /* 7: IT line in */ { 8, "Line Playback" }, /* FU */ { 11, "What-U-Hear Capture" }, /* FU */ { 12, "Line Capture" }, /* FU */ { 13, "Digital In Capture" }, /* FU */ { 14, "Capture Source" }, /* SU */ /* 15: OT pcm capture */ /* 16: MU w/o controls */ { 17, NULL }, /* DISABLED: EU (for what?) */ { 18, "Master Playback" }, /* FU */ /* 19: OT speaker */ /* 20: OT headphone */ { 21, NULL }, /* DISABLED: EU (for what?) */ { 22, "Digital Out Playback" }, /* FU */ { 23, NULL }, /* DISABLED: EU (for what?) */ /* 24: OT digital out */ { 27, NULL }, /* DISABLED: EU (for what?) */ { 28, "Speaker Playback" }, /* FU */ { 29, "Digital Out Source" }, /* SU */ { 30, "Headphone Playback" }, /* FU */ { 31, "Headphone Source" }, /* SU */ { 0 } /* terminator */ }; static struct usbmix_name_map mbox1_map[] = { { 1, "Clock" }, { 0 } /* terminator */ }; static struct usbmix_selector_map c400_selectors[] = { { .id = 0x80, .count = 2, .names = (const char*[]) {"Internal", "SPDIF"} }, { 0 } /* terminator */ }; static struct usbmix_selector_map audigy2nx_selectors[] = { { .id = 14, /* Capture Source */ .count = 3, .names = (const char*[]) {"Line", "Digital In", "What-U-Hear"} }, { .id = 29, /* Digital Out Source */ .count = 3, .names = (const char*[]) {"Front", "PCM", "Digital In"} }, { .id = 31, /* Headphone Source */ .count = 2, .names = (const char*[]) {"Front", "Side"} }, { 0 } /* terminator */ }; /* Creative SoundBlaster Live! 24-bit External */ static struct usbmix_name_map live24ext_map[] = { /* 2: PCM Playback Volume */ { 5, "Mic Capture" }, /* FU, default PCM Capture Volume */ { 0 } /* terminator */ }; /* LineX FM Transmitter entry - needed to bypass controls bug */ static struct usbmix_name_map linex_map[] = { /* 1: IT pcm */ /* 2: OT Speaker */ { 3, "Master" }, /* FU: master volume - left / right / mute */ { 0 } /* terminator */ }; static struct usbmix_name_map maya44_map[] = { /* 1: IT line */ { 2, "Line Playback" }, /* FU */ /* 3: IT line */ { 4, "Line Playback" }, /* FU */ /* 5: IT pcm playback */ /* 6: MU */ { 7, "Master Playback" }, /* FU */ /* 8: OT speaker */ /* 9: IT line */ { 10, "Line Capture" }, /* FU */ /* 11: MU */ /* 12: OT pcm capture */ { } }; /* Section "justlink_map" below added by James Courtier-Dutton <[email protected]> * sourced from Maplin Electronics (http://www.maplin.co.uk), part number A56AK * Part has 2 connectors that act as a single output. (TOSLINK Optical for digital out, and 3.5mm Jack for Analogue out.) * The USB Mixer publishes a Microphone and extra Volume controls for it, but none exist on the device, * so this map removes all unwanted sliders from alsamixer */ static struct usbmix_name_map justlink_map[] = { /* 1: IT pcm playback */ /* 2: Not present */ { 3, NULL}, /* IT mic (No mic input on device) */ /* 4: Not present */ /* 5: OT speacker */ /* 6: OT pcm capture */ { 7, "Master Playback" }, /* Mute/volume for speaker */ { 8, NULL }, /* Capture Switch (No capture inputs on device) */ { 9, NULL }, /* Capture Mute/volume (No capture inputs on device */ /* 0xa: Not present */ /* 0xb: MU (w/o controls) */ { 0xc, NULL }, /* Mic feedback Mute/volume (No capture inputs on device) */ { 0 } /* terminator */ }; /* TerraTec Aureon 5.1 MkII USB */ static struct usbmix_name_map aureon_51_2_map[] = { /* 1: IT USB */ /* 2: IT Mic */ /* 3: IT Line */ /* 4: IT SPDIF */ /* 5: OT SPDIF */ /* 6: OT Speaker */ /* 7: OT USB */ { 8, "Capture Source" }, /* SU */ { 9, "Master Playback" }, /* FU */ { 10, "Mic Capture" }, /* FU */ { 11, "Line Capture" }, /* FU */ { 12, "IEC958 In Capture" }, /* FU */ { 13, "Mic Playback" }, /* FU */ { 14, "Line Playback" }, /* FU */ /* 15: MU */ {} /* terminator */ }; static struct usbmix_name_map scratch_live_map[] = { /* 1: IT Line 1 (USB streaming) */ /* 2: OT Line 1 (Speaker) */ /* 3: IT Line 1 (Line connector) */ { 4, "Line 1 In" }, /* FU */ /* 5: OT Line 1 (USB streaming) */ /* 6: IT Line 2 (USB streaming) */ /* 7: OT Line 2 (Speaker) */ /* 8: IT Line 2 (Line connector) */ { 9, "Line 2 In" }, /* FU */ /* 10: OT Line 2 (USB streaming) */ /* 11: IT Mic (Line connector) */ /* 12: OT Mic (USB streaming) */ { 0 } /* terminator */ }; static struct usbmix_name_map ebox44_map[] = { { 4, NULL }, /* FU */ { 6, NULL }, /* MU */ { 7, NULL }, /* FU */ { 10, NULL }, /* FU */ { 11, NULL }, /* MU */ { 0 } }; /* "Gamesurround Muse Pocket LT" looks same like "Sound Blaster MP3+" * most importand difference is SU[8], it should be set to "Capture Source" * to make alsamixer and PA working properly. * FIXME: or mp3plus_map should use "Capture Source" too, * so this maps can be merget */ static struct usbmix_name_map hercules_usb51_map[] = { { 8, "Capture Source" }, /* SU, default "PCM Capture Source" */ { 9, "Master Playback" }, /* FU, default "Speaker Playback" */ { 10, "Mic Boost", 7 }, /* FU, default "Auto Gain Input" */ { 11, "Line Capture" }, /* FU, default "PCM Capture" */ { 13, "Mic Bypass Playback" }, /* FU, default "Mic Playback" */ { 14, "Line Bypass Playback" }, /* FU, default "Line Playback" */ { 0 } /* terminator */ }; /* Plantronics Gamecom 780 has a broken volume control, better to disable it */ static struct usbmix_name_map gamecom780_map[] = { { 9, NULL }, /* FU, speaker out */ {} }; /* some (all?) SCMS USB3318 devices are affected by a firmware lock up * when anything attempts to access FU 10 (control) */ static const struct usbmix_name_map scms_usb3318_map[] = { { 10, NULL }, { 0 } }; /* Bose companion 5, the dB conversion factor is 16 instead of 256 */ static struct usbmix_dB_map bose_companion5_dB = {-5006, -6}; static struct usbmix_name_map bose_companion5_map[] = { { 3, NULL, .dB = &bose_companion5_dB }, { 0 } /* terminator */ }; /* * Dell usb dock with ALC4020 codec had a firmware problem where it got * screwed up when zero volume is passed; just skip it as a workaround */ static const struct usbmix_name_map dell_alc4020_map[] = { { 16, NULL }, { 19, NULL }, { 0 } }; /* * Control map entries */ static struct usbmix_ctl_map usbmix_ctl_maps[] = { { .id = USB_ID(0x041e, 0x3000), .map = extigy_map, .ignore_ctl_error = 1, }, { .id = USB_ID(0x041e, 0x3010), .map = mp3plus_map, }, { .id = USB_ID(0x041e, 0x3020), .map = audigy2nx_map, .selector_map = audigy2nx_selectors, }, { .id = USB_ID(0x041e, 0x3040), .map = live24ext_map, }, { .id = USB_ID(0x041e, 0x3048), .map = audigy2nx_map, .selector_map = audigy2nx_selectors, }, { /* Logitech, Inc. QuickCam Pro for Notebooks */ .id = USB_ID(0x046d, 0x0991), .ignore_ctl_error = 1, }, { /* Logitech, Inc. QuickCam E 3500 */ .id = USB_ID(0x046d, 0x09a4), .ignore_ctl_error = 1, }, { /* Plantronics GameCom 780 */ .id = USB_ID(0x047f, 0xc010), .map = gamecom780_map, }, { /* Hercules DJ Console (Windows Edition) */ .id = USB_ID(0x06f8, 0xb000), .ignore_ctl_error = 1, }, { /* Hercules DJ Console (Macintosh Edition) */ .id = USB_ID(0x06f8, 0xd002), .ignore_ctl_error = 1, }, { /* Hercules Gamesurround Muse Pocket LT * (USB 5.1 Channel Audio Adapter) */ .id = USB_ID(0x06f8, 0xc000), .map = hercules_usb51_map, }, { .id = USB_ID(0x0763, 0x2030), .selector_map = c400_selectors, }, { .id = USB_ID(0x0763, 0x2031), .selector_map = c400_selectors, }, { .id = USB_ID(0x08bb, 0x2702), .map = linex_map, .ignore_ctl_error = 1, }, { .id = USB_ID(0x0a92, 0x0091), .map = maya44_map, }, { .id = USB_ID(0x0c45, 0x1158), .map = justlink_map, }, { .id = USB_ID(0x0ccd, 0x0028), .map = aureon_51_2_map, }, { .id = USB_ID(0x0bda, 0x4014), .map = dell_alc4020_map, }, { .id = USB_ID(0x0dba, 0x1000), .map = mbox1_map, }, { .id = USB_ID(0x13e5, 0x0001), .map = scratch_live_map, .ignore_ctl_error = 1, }, { .id = USB_ID(0x200c, 0x1018), .map = ebox44_map, }, { /* MAYA44 USB+ */ .id = USB_ID(0x2573, 0x0008), .map = maya44_map, }, { /* KEF X300A */ .id = USB_ID(0x27ac, 0x1000), .map = scms_usb3318_map, }, { /* Arcam rPAC */ .id = USB_ID(0x25c4, 0x0003), .map = scms_usb3318_map, }, { /* Bose Companion 5 */ .id = USB_ID(0x05a7, 0x1020), .map = bose_companion5_map, }, { 0 } /* terminator */ };
609496.c
/* mgcLibrary.c was originally generated by the autoSql program, which also * generated mgcLibrary.h and mgcLibrary.sql. This module links the database and * the RAM representation of objects. */ #include "common.h" #include "linefile.h" #include "dystring.h" #include "jksql.h" #include "gbSql.h" #include "mgcLibrary.h" #include "gbFileOps.h" static char const rcsid[] = "$Id: mgcLibrary.c,v 1.2 2004/02/16 19:30:06 markd Exp $"; void mgcLibraryStaticLoad(char **row, struct mgcLibrary *ret) /* Load a row from mgcLibrary table into ret. The contents of ret will * be replaced at the next call to this function. */ { ret->id_lib = sqlSigned(row[0]); ret->flc_id = row[1]; ret->id_rna = row[2]; ret->id_vendor = gbSqlSignedNull(row[3]); ret->id_method = gbSqlSignedNull(row[4]); ret->normal = gbSqlSignedNull(row[5]); ret->commnt = row[6]; ret->rate_success = atof(row[7]); ret->human_repeats = atof(row[8]); ret->mito_rna = atof(row[9]); ret->ecoli = atof(row[10]); ret->yeast = atof(row[11]); ret->mouse = atof(row[12]); ret->diversity = atof(row[13]); ret->uniqueness = atof(row[14]); ret->genes = gbSqlSignedNull(row[15]); ret->discover = gbSqlSignedNull(row[16]); ret->flc_disc = gbSqlSignedNull(row[17]); ret->novel = gbSqlSignedNull(row[18]); ret->future = atof(row[19]); ret->internal_primed = atof(row[20]); ret->full_length = atof(row[21]); ret->priority = atof(row[22]); ret->id_unigene = gbSqlSignedNull(row[23]); ret->organism = row[24]; ret->vector = row[25]; ret->host = row[26]; ret->vec_contam = atof(row[27]); ret->mean_insize = atof(row[28]); ret->linker = row[29]; } struct mgcLibrary *mgcLibraryLoad(char **row) /* Load a mgcLibrary from row fetched with select * from mgcLibrary * from database. Dispose of this with mgcLibraryFree(). */ { struct mgcLibrary *ret; AllocVar(ret); ret->id_lib = sqlSigned(row[0]); ret->flc_id = cloneString(row[1]); ret->id_rna = cloneString(row[2]); ret->id_vendor = gbSqlSignedNull(row[3]); ret->id_method = gbSqlSignedNull(row[4]); ret->normal = gbSqlSignedNull(row[5]); ret->commnt = cloneString(row[6]); ret->rate_success = atof(row[7]); ret->human_repeats = atof(row[8]); ret->mito_rna = atof(row[9]); ret->ecoli = atof(row[10]); ret->yeast = atof(row[11]); ret->mouse = atof(row[12]); ret->diversity = atof(row[13]); ret->uniqueness = atof(row[14]); ret->genes = gbSqlSignedNull(row[15]); ret->discover = gbSqlSignedNull(row[16]); ret->flc_disc = gbSqlSignedNull(row[17]); ret->novel = gbSqlSignedNull(row[18]); ret->future = atof(row[19]); ret->internal_primed = atof(row[20]); ret->full_length = atof(row[21]); ret->priority = atof(row[22]); ret->id_unigene = gbSqlSignedNull(row[23]); ret->organism = cloneString(row[24]); ret->vector = cloneString(row[25]); ret->host = cloneString(row[26]); ret->vec_contam = atof(row[27]); ret->mean_insize = atof(row[28]); ret->linker = cloneString(row[29]); return ret; } struct mgcLibrary *mgcLibraryLoadAll(char *fileName) /* Load all mgcLibrary from a whitespace-separated file. * Dispose of this with mgcLibraryFreeList(). */ { struct mgcLibrary *list = NULL, *el; struct lineFile *lf = lineFileOpen(fileName, TRUE); char *row[30]; while (lineFileRow(lf, row)) { el = mgcLibraryLoad(row); slAddHead(&list, el); } lineFileClose(&lf); slReverse(&list); return list; } struct mgcLibrary *mgcLibraryCommaIn(char **pS, struct mgcLibrary *ret) /* Create a mgcLibrary out of a comma separated string. * This will fill in ret if non-null, otherwise will * return a new mgcLibrary */ { char *s = *pS; if (ret == NULL) AllocVar(ret); ret->id_lib = sqlSignedComma(&s); ret->flc_id = sqlStringComma(&s); ret->id_rna = sqlStringComma(&s); ret->id_vendor = sqlSignedComma(&s); ret->id_method = sqlSignedComma(&s); ret->normal = sqlSignedComma(&s); ret->commnt = sqlStringComma(&s); ret->rate_success = sqlFloatComma(&s); ret->human_repeats = sqlFloatComma(&s); ret->mito_rna = sqlFloatComma(&s); ret->ecoli = sqlFloatComma(&s); ret->yeast = sqlFloatComma(&s); ret->mouse = sqlFloatComma(&s); ret->diversity = sqlFloatComma(&s); ret->uniqueness = sqlFloatComma(&s); ret->genes = sqlSignedComma(&s); ret->discover = sqlSignedComma(&s); ret->flc_disc = sqlSignedComma(&s); ret->novel = sqlSignedComma(&s); ret->future = sqlFloatComma(&s); ret->internal_primed = sqlFloatComma(&s); ret->full_length = sqlFloatComma(&s); ret->priority = sqlFloatComma(&s); ret->id_unigene = sqlSignedComma(&s); ret->organism = sqlStringComma(&s); ret->vector = sqlStringComma(&s); ret->host = sqlStringComma(&s); ret->vec_contam = sqlFloatComma(&s); ret->mean_insize = sqlFloatComma(&s); ret->linker = sqlStringComma(&s); *pS = s; return ret; } void mgcLibraryFree(struct mgcLibrary **pEl) /* Free a single dynamically allocated mgcLibrary such as created * with mgcLibraryLoad(). */ { struct mgcLibrary *el; if ((el = *pEl) == NULL) return; freeMem(el->flc_id); freeMem(el->id_rna); freeMem(el->commnt); freeMem(el->organism); freeMem(el->vector); freeMem(el->host); freeMem(el->linker); freez(pEl); } void mgcLibraryFreeList(struct mgcLibrary **pList) /* Free a list of dynamically allocated mgcLibrary's */ { struct mgcLibrary *el, *next; for (el = *pList; el != NULL; el = next) { next = el->next; mgcLibraryFree(&el); } *pList = NULL; } void mgcLibraryOutput(struct mgcLibrary *el, FILE *f, char sep, char lastSep) /* Print out mgcLibrary. Separate fields with sep. Follow last field with lastSep. */ { fprintf(f, "%d", el->id_lib); fputc(sep,f); if (sep == ',') fputc('"',f); fprintf(f, "%s", el->flc_id); if (sep == ',') fputc('"',f); fputc(sep,f); if (sep == ',') fputc('"',f); fprintf(f, "%s", el->id_rna); if (sep == ',') fputc('"',f); fputc(sep,f); fprintf(f, "%d", el->id_vendor); fputc(sep,f); fprintf(f, "%d", el->id_method); fputc(sep,f); fprintf(f, "%d", el->normal); fputc(sep,f); if (sep == ',') fputc('"',f); fprintf(f, "%s", el->commnt); if (sep == ',') fputc('"',f); fputc(sep,f); fprintf(f, "%f", el->rate_success); fputc(sep,f); fprintf(f, "%f", el->human_repeats); fputc(sep,f); fprintf(f, "%f", el->mito_rna); fputc(sep,f); fprintf(f, "%f", el->ecoli); fputc(sep,f); fprintf(f, "%f", el->yeast); fputc(sep,f); fprintf(f, "%f", el->mouse); fputc(sep,f); fprintf(f, "%f", el->diversity); fputc(sep,f); fprintf(f, "%f", el->uniqueness); fputc(sep,f); fprintf(f, "%d", el->genes); fputc(sep,f); fprintf(f, "%d", el->discover); fputc(sep,f); fprintf(f, "%d", el->flc_disc); fputc(sep,f); fprintf(f, "%d", el->novel); fputc(sep,f); fprintf(f, "%f", el->future); fputc(sep,f); fprintf(f, "%f", el->internal_primed); fputc(sep,f); fprintf(f, "%f", el->full_length); fputc(sep,f); fprintf(f, "%f", el->priority); fputc(sep,f); fprintf(f, "%d", el->id_unigene); fputc(sep,f); if (sep == ',') fputc('"',f); fprintf(f, "%s", el->organism); if (sep == ',') fputc('"',f); fputc(sep,f); if (sep == ',') fputc('"',f); fprintf(f, "%s", el->vector); if (sep == ',') fputc('"',f); fputc(sep,f); if (sep == ',') fputc('"',f); fprintf(f, "%s", el->host); if (sep == ',') fputc('"',f); fputc(sep,f); fprintf(f, "%f", el->vec_contam); fputc(sep,f); fprintf(f, "%f", el->mean_insize); fputc(sep,f); if (sep == ',') fputc('"',f); fprintf(f, "%s", el->linker); if (sep == ',') fputc('"',f); fputc(lastSep,f); } /* -------------------------------- End autoSql Generated Code -------------------------------- */ struct mgcLibraryTbl *mgcLibraryTblLoad(char *fileName) /* load a file of mgcLibrary objects, building a hash by library id */ { struct mgcLibraryTbl *mlt; char *row[MGCLIBRARY_NUM_COLS]; char key[64]; struct lineFile *lf; AllocVar(mlt); mlt->idHash = hashNew(12); /* 4096 */ lf = gzLineFileOpen(fileName); while (lineFileNextRowTab(lf, row, MGCLIBRARY_NUM_COLS)) { struct mgcLibrary *mgcLibrary = mgcLibraryLoad(row); safef(key, sizeof(key), "%d", mgcLibrary->id_lib); hashAdd(mlt->idHash, key, mgcLibrary); } gzLineFileClose(&lf); return mlt; } void mgcLibraryTblFree(struct mgcLibraryTbl **mltPtr) /* free a mgcLibraryTbl object */ { struct mgcLibraryTbl *mlt = *mltPtr; if (mlt != NULL) { struct hashCookie cookie = hashFirst(mlt->idHash); struct hashEl *hel; while ((hel = hashNext(&cookie)) != NULL) mgcLibraryFree((struct mgcLibrary**)&hel->val); hashFree(&mlt->idHash); free(mlt); *mltPtr = NULL; } } struct mgcLibrary *mgcLibraryTblFind(struct mgcLibraryTbl *mlt, int libraryId) /* Find a mgcLibrary object by libraryId, or NULL if not found */ { char key[64]; struct hashEl *hel; safef(key, sizeof(key), "%d", libraryId); hel = hashLookup(mlt->idHash, key); if (hel == NULL) return NULL; else return hel->val; }
407848.c
/* * Samsung SoC USB 1.1/2.0 PHY driver * * Copyright (C) 2013 Samsung Electronics Co., Ltd. * Author: Kamil Debski <[email protected]> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. */ #include <linux/clk.h> #include <linux/mfd/syscon.h> #include <linux/module.h> #include <linux/of.h> #include <linux/of_address.h> #include <linux/phy/phy.h> #include <linux/platform_device.h> #include <linux/spinlock.h> #include "phy-samsung-usb2.h" static int samsung_usb2_phy_power_on(struct phy *phy) { struct samsung_usb2_phy_instance *inst = phy_get_drvdata(phy); struct samsung_usb2_phy_driver *drv = inst->drv; int ret; dev_dbg(drv->dev, "Request to power_on \"%s\" usb phy\n", inst->cfg->label); ret = clk_prepare_enable(drv->clk); if (ret) goto err_main_clk; ret = clk_prepare_enable(drv->ref_clk); if (ret) goto err_instance_clk; if (inst->cfg->power_on) { spin_lock(&drv->lock); ret = inst->cfg->power_on(inst); spin_unlock(&drv->lock); if (ret) goto err_power_on; } return 0; err_power_on: clk_disable_unprepare(drv->ref_clk); err_instance_clk: clk_disable_unprepare(drv->clk); err_main_clk: return ret; } static int samsung_usb2_phy_power_off(struct phy *phy) { struct samsung_usb2_phy_instance *inst = phy_get_drvdata(phy); struct samsung_usb2_phy_driver *drv = inst->drv; int ret; dev_dbg(drv->dev, "Request to power_off \"%s\" usb phy\n", inst->cfg->label); if (inst->cfg->power_off) { spin_lock(&drv->lock); ret = inst->cfg->power_off(inst); spin_unlock(&drv->lock); if (ret) return ret; } clk_disable_unprepare(drv->ref_clk); clk_disable_unprepare(drv->clk); return 0; } static const struct phy_ops samsung_usb2_phy_ops = { .power_on = samsung_usb2_phy_power_on, .power_off = samsung_usb2_phy_power_off, .owner = THIS_MODULE, }; static struct phy *samsung_usb2_phy_xlate(struct device *dev, struct of_phandle_args *args) { struct samsung_usb2_phy_driver *drv; drv = dev_get_drvdata(dev); if (!drv) return ERR_PTR(-EINVAL); if (WARN_ON(args->args[0] >= drv->cfg->num_phys)) return ERR_PTR(-ENODEV); return drv->instances[args->args[0]].phy; } static const struct of_device_id samsung_usb2_phy_of_match[] = { #ifdef CONFIG_PHY_EXYNOS4X12_USB2 { .compatible = "samsung,exynos3250-usb2-phy", .data = &exynos3250_usb2_phy_config, }, #endif #ifdef CONFIG_PHY_EXYNOS4210_USB2 { .compatible = "samsung,exynos4210-usb2-phy", .data = &exynos4210_usb2_phy_config, }, #endif #ifdef CONFIG_PHY_EXYNOS4X12_USB2 { .compatible = "samsung,exynos4x12-usb2-phy", .data = &exynos4x12_usb2_phy_config, }, #endif #ifdef CONFIG_PHY_EXYNOS5250_USB2 { .compatible = "samsung,exynos5250-usb2-phy", .data = &exynos5250_usb2_phy_config, }, #endif #ifdef CONFIG_PHY_S5PV210_USB2 { .compatible = "samsung,s5pv210-usb2-phy", .data = &s5pv210_usb2_phy_config, }, #endif { }, }; MODULE_DEVICE_TABLE(of, samsung_usb2_phy_of_match); static int samsung_usb2_phy_probe(struct platform_device *pdev) { const struct of_device_id *match; const struct samsung_usb2_phy_config *cfg; struct device *dev = &pdev->dev; struct phy_provider *phy_provider; struct resource *mem; struct samsung_usb2_phy_driver *drv; int i, ret; if (!pdev->dev.of_node) { dev_err(dev, "This driver is required to be instantiated from device tree\n"); return -EINVAL; } match = of_match_node(samsung_usb2_phy_of_match, pdev->dev.of_node); if (!match) { dev_err(dev, "of_match_node() failed\n"); return -EINVAL; } cfg = match->data; drv = devm_kzalloc(dev, sizeof(struct samsung_usb2_phy_driver) + cfg->num_phys * sizeof(struct samsung_usb2_phy_instance), GFP_KERNEL); if (!drv) return -ENOMEM; dev_set_drvdata(dev, drv); spin_lock_init(&drv->lock); drv->cfg = cfg; drv->dev = dev; mem = platform_get_resource(pdev, IORESOURCE_MEM, 0); drv->reg_phy = devm_ioremap_resource(dev, mem); if (IS_ERR(drv->reg_phy)) { dev_err(dev, "Failed to map register memory (phy)\n"); return PTR_ERR(drv->reg_phy); } drv->reg_pmu = syscon_regmap_lookup_by_phandle(pdev->dev.of_node, "samsung,pmureg-phandle"); if (IS_ERR(drv->reg_pmu)) { dev_err(dev, "Failed to map PMU registers (via syscon)\n"); return PTR_ERR(drv->reg_pmu); } if (drv->cfg->has_mode_switch) { drv->reg_sys = syscon_regmap_lookup_by_phandle( pdev->dev.of_node, "samsung,sysreg-phandle"); if (IS_ERR(drv->reg_sys)) { dev_err(dev, "Failed to map system registers (via syscon)\n"); return PTR_ERR(drv->reg_sys); } } drv->clk = devm_clk_get(dev, "phy"); if (IS_ERR(drv->clk)) { dev_err(dev, "Failed to get clock of phy controller\n"); return PTR_ERR(drv->clk); } drv->ref_clk = devm_clk_get(dev, "ref"); if (IS_ERR(drv->ref_clk)) { dev_err(dev, "Failed to get reference clock for the phy controller\n"); return PTR_ERR(drv->ref_clk); } drv->ref_rate = clk_get_rate(drv->ref_clk); if (drv->cfg->rate_to_clk) { ret = drv->cfg->rate_to_clk(drv->ref_rate, &drv->ref_reg_val); if (ret) return ret; } for (i = 0; i < drv->cfg->num_phys; i++) { char *label = drv->cfg->phys[i].label; struct samsung_usb2_phy_instance *p = &drv->instances[i]; dev_dbg(dev, "Creating phy \"%s\"\n", label); p->phy = devm_phy_create(dev, NULL, &samsung_usb2_phy_ops); if (IS_ERR(p->phy)) { dev_err(drv->dev, "Failed to create usb2_phy \"%s\"\n", label); return PTR_ERR(p->phy); } p->cfg = &drv->cfg->phys[i]; p->drv = drv; phy_set_bus_width(p->phy, 8); phy_set_drvdata(p->phy, p); } phy_provider = devm_of_phy_provider_register(dev, samsung_usb2_phy_xlate); if (IS_ERR(phy_provider)) { dev_err(drv->dev, "Failed to register phy provider\n"); return PTR_ERR(phy_provider); } return 0; } static struct platform_driver samsung_usb2_phy_driver = { .probe = samsung_usb2_phy_probe, .driver = { .of_match_table = samsung_usb2_phy_of_match, .name = "samsung-usb2-phy", } }; module_platform_driver(samsung_usb2_phy_driver); MODULE_DESCRIPTION("Samsung S5P/EXYNOS SoC USB PHY driver"); MODULE_AUTHOR("Kamil Debski <[email protected]>"); MODULE_LICENSE("GPL v2"); MODULE_ALIAS("platform:samsung-usb2-phy");
380047.c
/* * REINER SCT cyberJack pinpad/e-com USB Chipcard Reader Driver * * Copyright (C) 2001 REINER SCT * Author: Matthias Bruestle * * Contact: [email protected] (see MAINTAINERS) * * This program is largely derived from work by the linux-usb group * and associated source files. Please see the usb/serial files for * individual credits and copyrights. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * Thanks to Greg Kroah-Hartman ([email protected]) for his help and * patience. * * In case of problems, please write to the contact e-mail address * mentioned above. * * Please note that later models of the cyberjack reader family are * supported by a libusb-based userspace device driver. * * Homepage: http://www.reiner-sct.de/support/treiber_cyberjack.php#linux */ #include <linux/kernel.h> #include <linux/errno.h> #include <linux/init.h> #include <linux/slab.h> #include <linux/tty.h> #include <linux/tty_driver.h> #include <linux/tty_flip.h> #include <linux/module.h> #include <linux/spinlock.h> #include <linux/uaccess.h> #include <linux/usb.h> #include <linux/usb/serial.h> #define CYBERJACK_LOCAL_BUF_SIZE 32 #define DRIVER_AUTHOR "Matthias Bruestle" #define DRIVER_DESC "REINER SCT cyberJack pinpad/e-com USB Chipcard Reader Driver" #define CYBERJACK_VENDOR_ID 0x0C4B #define CYBERJACK_PRODUCT_ID 0x0100 /* Function prototypes */ static int cyberjack_attach(struct usb_serial *serial); static int cyberjack_port_probe(struct usb_serial_port *port); static int cyberjack_port_remove(struct usb_serial_port *port); static int cyberjack_open(struct tty_struct *tty, struct usb_serial_port *port); static void cyberjack_close(struct usb_serial_port *port); static int cyberjack_write(struct tty_struct *tty, struct usb_serial_port *port, const unsigned char *buf, int count); static int cyberjack_write_room(struct tty_struct *tty); static void cyberjack_read_int_callback(struct urb *urb); static void cyberjack_read_bulk_callback(struct urb *urb); static void cyberjack_write_bulk_callback(struct urb *urb); static const struct usb_device_id id_table[] = { { USB_DEVICE(CYBERJACK_VENDOR_ID, CYBERJACK_PRODUCT_ID) }, { } /* Terminating entry */ }; MODULE_DEVICE_TABLE(usb, id_table); static struct usb_serial_driver cyberjack_device = { .driver = { .owner = THIS_MODULE, .name = "cyberjack", }, .description = "Reiner SCT Cyberjack USB card reader", .id_table = id_table, .num_ports = 1, .attach = cyberjack_attach, .port_probe = cyberjack_port_probe, .port_remove = cyberjack_port_remove, .open = cyberjack_open, .close = cyberjack_close, .write = cyberjack_write, .write_room = cyberjack_write_room, .read_int_callback = cyberjack_read_int_callback, .read_bulk_callback = cyberjack_read_bulk_callback, .write_bulk_callback = cyberjack_write_bulk_callback, }; static struct usb_serial_driver * const serial_drivers[] = { &cyberjack_device, NULL }; struct cyberjack_private { spinlock_t lock; /* Lock for SMP */ short rdtodo; /* Bytes still to read */ unsigned char wrbuf[5*64]; /* Buffer for collecting data to write */ short wrfilled; /* Overall data size we already got */ short wrsent; /* Data already sent */ }; static int cyberjack_attach(struct usb_serial *serial) { if (serial->num_bulk_out < serial->num_ports) return -ENODEV; return 0; } static int cyberjack_port_probe(struct usb_serial_port *port) { struct cyberjack_private *priv; int result; priv = kmalloc(sizeof(struct cyberjack_private), GFP_KERNEL); if (!priv) return -ENOMEM; spin_lock_init(&priv->lock); priv->rdtodo = 0; priv->wrfilled = 0; priv->wrsent = 0; usb_set_serial_port_data(port, priv); result = usb_submit_urb(port->interrupt_in_urb, GFP_KERNEL); if (result) dev_err(&port->dev, "usb_submit_urb(read int) failed\n"); return 0; } static int cyberjack_port_remove(struct usb_serial_port *port) { struct cyberjack_private *priv; usb_kill_urb(port->interrupt_in_urb); priv = usb_get_serial_port_data(port); kfree(priv); return 0; } static int cyberjack_open(struct tty_struct *tty, struct usb_serial_port *port) { struct cyberjack_private *priv; unsigned long flags; int result = 0; dev_dbg(&port->dev, "%s - usb_clear_halt\n", __func__); usb_clear_halt(port->serial->dev, port->write_urb->pipe); priv = usb_get_serial_port_data(port); spin_lock_irqsave(&priv->lock, flags); priv->rdtodo = 0; priv->wrfilled = 0; priv->wrsent = 0; spin_unlock_irqrestore(&priv->lock, flags); return result; } static void cyberjack_close(struct usb_serial_port *port) { usb_kill_urb(port->write_urb); usb_kill_urb(port->read_urb); } static int cyberjack_write(struct tty_struct *tty, struct usb_serial_port *port, const unsigned char *buf, int count) { struct device *dev = &port->dev; struct cyberjack_private *priv = usb_get_serial_port_data(port); unsigned long flags; int result; int wrexpected; if (count == 0) { dev_dbg(dev, "%s - write request of 0 bytes\n", __func__); return 0; } if (!test_and_clear_bit(0, &port->write_urbs_free)) { dev_dbg(dev, "%s - already writing\n", __func__); return 0; } spin_lock_irqsave(&priv->lock, flags); if (count+priv->wrfilled > sizeof(priv->wrbuf)) { /* To much data for buffer. Reset buffer. */ priv->wrfilled = 0; spin_unlock_irqrestore(&priv->lock, flags); set_bit(0, &port->write_urbs_free); return 0; } /* Copy data */ memcpy(priv->wrbuf + priv->wrfilled, buf, count); usb_serial_debug_data(dev, __func__, count, priv->wrbuf + priv->wrfilled); priv->wrfilled += count; if (priv->wrfilled >= 3) { wrexpected = ((int)priv->wrbuf[2]<<8)+priv->wrbuf[1]+3; dev_dbg(dev, "%s - expected data: %d\n", __func__, wrexpected); } else wrexpected = sizeof(priv->wrbuf); if (priv->wrfilled >= wrexpected) { /* We have enough data to begin transmission */ int length; dev_dbg(dev, "%s - transmitting data (frame 1)\n", __func__); length = (wrexpected > port->bulk_out_size) ? port->bulk_out_size : wrexpected; memcpy(port->write_urb->transfer_buffer, priv->wrbuf, length); priv->wrsent = length; /* set up our urb */ port->write_urb->transfer_buffer_length = length; /* send the data out the bulk port */ result = usb_submit_urb(port->write_urb, GFP_ATOMIC); if (result) { dev_err(&port->dev, "%s - failed submitting write urb, error %d", __func__, result); /* Throw away data. No better idea what to do with it. */ priv->wrfilled = 0; priv->wrsent = 0; spin_unlock_irqrestore(&priv->lock, flags); set_bit(0, &port->write_urbs_free); return 0; } dev_dbg(dev, "%s - priv->wrsent=%d\n", __func__, priv->wrsent); dev_dbg(dev, "%s - priv->wrfilled=%d\n", __func__, priv->wrfilled); if (priv->wrsent >= priv->wrfilled) { dev_dbg(dev, "%s - buffer cleaned\n", __func__); memset(priv->wrbuf, 0, sizeof(priv->wrbuf)); priv->wrfilled = 0; priv->wrsent = 0; } } spin_unlock_irqrestore(&priv->lock, flags); return count; } static int cyberjack_write_room(struct tty_struct *tty) { /* FIXME: .... */ return CYBERJACK_LOCAL_BUF_SIZE; } static void cyberjack_read_int_callback(struct urb *urb) { struct usb_serial_port *port = urb->context; struct cyberjack_private *priv = usb_get_serial_port_data(port); struct device *dev = &port->dev; unsigned char *data = urb->transfer_buffer; int status = urb->status; int result; /* the urb might have been killed. */ if (status) return; usb_serial_debug_data(dev, __func__, urb->actual_length, data); /* React only to interrupts signaling a bulk_in transfer */ if (urb->actual_length == 4 && data[0] == 0x01) { short old_rdtodo; /* This is a announcement of coming bulk_ins. */ unsigned short size = ((unsigned short)data[3]<<8)+data[2]+3; spin_lock(&priv->lock); old_rdtodo = priv->rdtodo; if (old_rdtodo + size < old_rdtodo) { dev_dbg(dev, "To many bulk_in urbs to do.\n"); spin_unlock(&priv->lock); goto resubmit; } /* "+=" is probably more fault tollerant than "=" */ priv->rdtodo += size; dev_dbg(dev, "%s - rdtodo: %d\n", __func__, priv->rdtodo); spin_unlock(&priv->lock); if (!old_rdtodo) { result = usb_submit_urb(port->read_urb, GFP_ATOMIC); if (result) dev_err(dev, "%s - failed resubmitting read urb, error %d\n", __func__, result); dev_dbg(dev, "%s - usb_submit_urb(read urb)\n", __func__); } } resubmit: result = usb_submit_urb(port->interrupt_in_urb, GFP_ATOMIC); if (result) dev_err(&port->dev, "usb_submit_urb(read int) failed\n"); dev_dbg(dev, "%s - usb_submit_urb(int urb)\n", __func__); } static void cyberjack_read_bulk_callback(struct urb *urb) { struct usb_serial_port *port = urb->context; struct cyberjack_private *priv = usb_get_serial_port_data(port); struct device *dev = &port->dev; unsigned char *data = urb->transfer_buffer; short todo; int result; int status = urb->status; usb_serial_debug_data(dev, __func__, urb->actual_length, data); if (status) { dev_dbg(dev, "%s - nonzero read bulk status received: %d\n", __func__, status); return; } if (urb->actual_length) { tty_insert_flip_string(&port->port, data, urb->actual_length); tty_flip_buffer_push(&port->port); } spin_lock(&priv->lock); /* Reduce urbs to do by one. */ priv->rdtodo -= urb->actual_length; /* Just to be sure */ if (priv->rdtodo < 0) priv->rdtodo = 0; todo = priv->rdtodo; spin_unlock(&priv->lock); dev_dbg(dev, "%s - rdtodo: %d\n", __func__, todo); /* Continue to read if we have still urbs to do. */ if (todo /* || (urb->actual_length==port->bulk_in_endpointAddress)*/) { result = usb_submit_urb(port->read_urb, GFP_ATOMIC); if (result) dev_err(dev, "%s - failed resubmitting read urb, error %d\n", __func__, result); dev_dbg(dev, "%s - usb_submit_urb(read urb)\n", __func__); } } static void cyberjack_write_bulk_callback(struct urb *urb) { struct usb_serial_port *port = urb->context; struct cyberjack_private *priv = usb_get_serial_port_data(port); struct device *dev = &port->dev; int status = urb->status; set_bit(0, &port->write_urbs_free); if (status) { dev_dbg(dev, "%s - nonzero write bulk status received: %d\n", __func__, status); return; } spin_lock(&priv->lock); /* only do something if we have more data to send */ if (priv->wrfilled) { int length, blksize, result; dev_dbg(dev, "%s - transmitting data (frame n)\n", __func__); length = ((priv->wrfilled - priv->wrsent) > port->bulk_out_size) ? port->bulk_out_size : (priv->wrfilled - priv->wrsent); memcpy(port->write_urb->transfer_buffer, priv->wrbuf + priv->wrsent, length); priv->wrsent += length; /* set up our urb */ port->write_urb->transfer_buffer_length = length; /* send the data out the bulk port */ result = usb_submit_urb(port->write_urb, GFP_ATOMIC); if (result) { dev_err(dev, "%s - failed submitting write urb, error %d\n", __func__, result); /* Throw away data. No better idea what to do with it. */ priv->wrfilled = 0; priv->wrsent = 0; goto exit; } dev_dbg(dev, "%s - priv->wrsent=%d\n", __func__, priv->wrsent); dev_dbg(dev, "%s - priv->wrfilled=%d\n", __func__, priv->wrfilled); blksize = ((int)priv->wrbuf[2]<<8)+priv->wrbuf[1]+3; if (priv->wrsent >= priv->wrfilled || priv->wrsent >= blksize) { dev_dbg(dev, "%s - buffer cleaned\n", __func__); memset(priv->wrbuf, 0, sizeof(priv->wrbuf)); priv->wrfilled = 0; priv->wrsent = 0; } } exit: spin_unlock(&priv->lock); usb_serial_port_softint(port); } module_usb_serial_driver(serial_drivers, id_table); MODULE_AUTHOR(DRIVER_AUTHOR); MODULE_DESCRIPTION(DRIVER_DESC); MODULE_LICENSE("GPL");
361689.c
/* Copyright (c) 2013 Nordic Semiconductor. All Rights Reserved. * * The information contained herein is property of Nordic Semiconductor ASA. * Terms and conditions of usage are described in detail in NORDIC * SEMICONDUCTOR STANDARD SOFTWARE LICENSE AGREEMENT. * * Licensees are granted free, non-transferable use of the information. NO * WARRANTY of ANY KIND is provided. This heading must NOT be removed from * the file. * */ #include <stddef.h> #include "dfu.h" #include <dfu_types.h> #include "dfu_bank_internal.h" #include "nrf.h" #include "nrf_sdm.h" #include "app_error.h" #include "app_timer.h" #include "bootloader.h" #include "bootloader_types.h" #include "pstorage.h" #include "nrf_mbr.h" #include "dfu_init.h" #include "sdk_common.h" static dfu_state_t m_dfu_state; /**< Current DFU state. */ static uint32_t m_image_size; /**< Size of the image that will be transmitted. */ static dfu_start_packet_t m_start_packet; /**< Start packet received for this update procedure. Contains update mode and image sizes information to be used for image transfer. */ static uint8_t m_init_packet[64]; /**< Init packet, can hold CRC, Hash, Signed Hash and similar, for image validation, integrety check and authorization checking. */ static uint8_t m_init_packet_length; /**< Length of init packet received. */ static uint16_t m_image_crc; /**< Calculated CRC of the image received. */ APP_TIMER_DEF(m_dfu_timer_id); /**< Application timer id. */ static bool m_dfu_timed_out = false; /**< Boolean flag value for tracking DFU timer timeout state. */ static pstorage_handle_t m_storage_handle_app; /**< Pstorage handle for the application area (bank 0). Bank used when updating a SoftDevice w/wo bootloader. Handle also used when swapping received application from bank 1 to bank 0. */ static pstorage_handle_t * mp_storage_handle_active; /**< Pointer to the pstorage handle for the active bank for receiving of data packets. */ static dfu_callback_t m_data_pkt_cb; /**< Callback from DFU Bank module for notification of asynchronous operation such as flash prepare. */ static dfu_bank_func_t m_functions; /**< Structure holding operations for the selected update process. */ /**@brief Function for handling callbacks from pstorage module. * * @details Handles pstorage results for clear and storage operation. For detailed description of * the parameters provided with the callback, please refer to \ref pstorage_ntf_cb_t. */ static void pstorage_callback_handler(pstorage_handle_t * p_handle, uint8_t op_code, uint32_t result, uint8_t * p_data, uint32_t data_len) { switch (op_code) { case PSTORAGE_STORE_OP_CODE: if ((m_dfu_state == DFU_STATE_RX_DATA_PKT) && (m_data_pkt_cb != NULL)) { m_data_pkt_cb(DATA_PACKET, result, p_data); } break; case PSTORAGE_CLEAR_OP_CODE: if (m_dfu_state == DFU_STATE_PREPARING) { m_functions.cleared(); m_dfu_state = DFU_STATE_RDY; if (m_data_pkt_cb != NULL) { m_data_pkt_cb(START_PACKET, result, p_data); } } break; default: break; } APP_ERROR_CHECK(result); } /**@brief Function for handling the DFU timeout. * * @param[in] p_context The timeout context. */ static void dfu_timeout_handler(void * p_context) { UNUSED_PARAMETER(p_context); dfu_update_status_t update_status; m_dfu_timed_out = true; update_status.status_code = DFU_TIMEOUT; bootloader_dfu_update_process(update_status); } /**@brief Function for restarting the DFU Timer. * * @details This function will stop and restart the DFU timer. This function will be called by the * functions handling any DFU packet received from the peer that is transferring a firmware * image. */ static uint32_t dfu_timer_restart(void) { if (m_dfu_timed_out) { // The DFU timer had already timed out. return NRF_ERROR_INVALID_STATE; } uint32_t err_code = app_timer_stop(m_dfu_timer_id); APP_ERROR_CHECK(err_code); err_code = app_timer_start(m_dfu_timer_id, DFU_TIMEOUT_INTERVAL, NULL); APP_ERROR_CHECK(err_code); return err_code; } /**@brief Function for preparing of flash before receiving SoftDevice image. * * @details This function will erase current application area to ensure sufficient amount of * storage for the SoftDevice image. Upon erase complete a callback will be done. * See \ref dfu_bank_prepare_t for further details. */ static void dfu_prepare_func_app_erase(uint32_t image_size) { uint32_t err_code; mp_storage_handle_active = &m_storage_handle_app; // Doing a SoftDevice update thus current application must be cleared to ensure enough space // for new SoftDevice. m_dfu_state = DFU_STATE_PREPARING; err_code = pstorage_clear(&m_storage_handle_app, m_image_size); APP_ERROR_CHECK(err_code); } /**@brief Function for handling behaviour when clear operation has completed. */ static void dfu_cleared_func_app(void) { dfu_update_status_t update_status = {DFU_BANK_0_ERASED, }; bootloader_dfu_update_process(update_status); } /**@brief Function for calculating storage offset for receiving SoftDevice image. * * @details When a new SoftDevice is received it will be temporary stored in flash before moved to * address 0x0. In order to succesfully validate transfer and relocation it is important * that temporary image and final installed image does not ovwerlap hence an offset must * be calculated in case new image is larger than currently installed SoftDevice. */ uint32_t offset_calculate(uint32_t sd_image_size) { uint32_t offset = 0; if (m_start_packet.sd_image_size > DFU_BANK_0_REGION_START) { uint32_t page_mask = (CODE_PAGE_SIZE - 1); uint32_t diff = m_start_packet.sd_image_size - DFU_BANK_0_REGION_START; offset = diff & ~page_mask; // Align offset to next page if image size is not page sized. if ((diff & page_mask) > 0) { offset += CODE_PAGE_SIZE; } } return offset; } /**@brief Function for activating received SoftDevice image. * * @note This function will not move the SoftDevice image. * The bootloader settings will be marked as SoftDevice update complete and the swapping of * current SoftDevice will occur after system reset. * * @return NRF_SUCCESS on success. */ static uint32_t dfu_activate_sd(void) { dfu_update_status_t update_status; update_status.status_code = DFU_UPDATE_SD_COMPLETE; update_status.app_crc = m_image_crc; update_status.sd_image_start = DFU_BANK_0_REGION_START; update_status.sd_size = m_start_packet.sd_image_size; update_status.bl_size = m_start_packet.bl_image_size; update_status.app_size = m_start_packet.app_image_size; bootloader_dfu_update_process(update_status); return NRF_SUCCESS; } /**@brief Function for activating received Application image. * * @details This function will move the received application image fram swap (bank 1) to * application area (bank 0). * * @return NRF_SUCCESS on success. Error code otherwise. */ static uint32_t dfu_activate_app(void) { uint32_t err_code = NRF_SUCCESS; dfu_update_status_t update_status; memset(&update_status, 0, sizeof(dfu_update_status_t )); update_status.status_code = DFU_UPDATE_APP_COMPLETE; update_status.app_crc = m_image_crc; update_status.app_size = m_start_packet.app_image_size; bootloader_dfu_update_process(update_status); return err_code; } /**@brief Function for activating received Bootloader image. * * @note This function will not move the bootloader image. * The bootloader settings will be marked as Bootloader update complete and the swapping of * current bootloader will occur after system reset. * * @return NRF_SUCCESS on success. */ static uint32_t dfu_activate_bl(void) { dfu_update_status_t update_status; update_status.status_code = DFU_UPDATE_BOOT_COMPLETE; update_status.app_crc = m_image_crc; update_status.sd_size = m_start_packet.sd_image_size; update_status.bl_size = m_start_packet.bl_image_size; update_status.app_size = m_start_packet.app_image_size; bootloader_dfu_update_process(update_status); return NRF_SUCCESS; } uint32_t dfu_init(void) { uint32_t err_code; pstorage_module_param_t storage_module_param = {.cb = pstorage_callback_handler}; m_init_packet_length = 0; m_image_crc = 0; err_code = pstorage_register(&storage_module_param, &m_storage_handle_app); if (err_code != NRF_SUCCESS) { m_dfu_state = DFU_STATE_INIT_ERROR; return err_code; } m_storage_handle_app.block_id = DFU_BANK_0_REGION_START; // Create the timer to monitor the activity by the peer doing the firmware update. err_code = app_timer_create(&m_dfu_timer_id, APP_TIMER_MODE_SINGLE_SHOT, dfu_timeout_handler); APP_ERROR_CHECK(err_code); // Start the DFU timer. err_code = app_timer_start(m_dfu_timer_id, DFU_TIMEOUT_INTERVAL, NULL); APP_ERROR_CHECK(err_code); m_data_received = 0; m_dfu_state = DFU_STATE_IDLE; return NRF_SUCCESS; } void dfu_register_callback(dfu_callback_t callback_handler) { m_data_pkt_cb = callback_handler; } uint32_t dfu_start_pkt_handle(dfu_update_packet_t * p_packet) { uint32_t err_code; m_start_packet = *(p_packet->params.start_packet); // Check that the requested update procedure is supported. // Currently the following combinations are allowed: // - Application // - SoftDevice // - Bootloader // - SoftDevice with Bootloader if (IS_UPDATING_APP(m_start_packet) && (IS_UPDATING_SD(m_start_packet) || IS_UPDATING_BL(m_start_packet))) { // App update is only supported independently. return NRF_ERROR_NOT_SUPPORTED; } if (!(IS_WORD_SIZED(m_start_packet.sd_image_size) && IS_WORD_SIZED(m_start_packet.bl_image_size) && IS_WORD_SIZED(m_start_packet.app_image_size))) { // Image_sizes are not a multiple of 4 (word size). return NRF_ERROR_NOT_SUPPORTED; } m_image_size = m_start_packet.sd_image_size + m_start_packet.bl_image_size + m_start_packet.app_image_size; if (m_start_packet.bl_image_size > DFU_BL_IMAGE_MAX_SIZE) { return NRF_ERROR_DATA_SIZE; } if (m_image_size > (DFU_IMAGE_MAX_SIZE_FULL)) { return NRF_ERROR_DATA_SIZE; } m_functions.prepare = dfu_prepare_func_app_erase; m_functions.cleared = dfu_cleared_func_app; if (IS_UPDATING_SD(m_start_packet)) { m_functions.activate = dfu_activate_sd; } else if (IS_UPDATING_BL(m_start_packet)) { m_functions.activate = dfu_activate_bl; } else { m_functions.activate = dfu_activate_app; } switch (m_dfu_state) { case DFU_STATE_IDLE: // Valid peer activity detected. Hence restart the DFU timer. err_code = dfu_timer_restart(); VERIFY_SUCCESS(err_code); m_functions.prepare(m_image_size); break; default: err_code = NRF_ERROR_INVALID_STATE; break; } return err_code; } uint32_t dfu_data_pkt_handle(dfu_update_packet_t * p_packet) { uint32_t data_length; uint32_t err_code; uint32_t * p_data; VERIFY_PARAM_NOT_NULL(p_packet); // Check pointer alignment. if (!is_word_aligned(p_packet->params.data_packet.p_data_packet)) { // The p_data_packet is not word aligned address. return NRF_ERROR_INVALID_ADDR; } switch (m_dfu_state) { case DFU_STATE_RDY: case DFU_STATE_RX_INIT_PKT: return NRF_ERROR_INVALID_STATE; case DFU_STATE_RX_DATA_PKT: data_length = p_packet->params.data_packet.packet_length * sizeof(uint32_t); if ((m_data_received + data_length) > m_image_size) { // The caller is trying to write more bytes into the flash than the size provided to // the dfu_image_size_set function. This is treated as a serious error condition and // an unrecoverable one. Hence point the variable mp_app_write_address to the top of // the flash area. This will ensure that all future application data packet writes // will be blocked because of the above check. m_data_received = 0xFFFFFFFF; return NRF_ERROR_DATA_SIZE; } // Valid peer activity detected. Hence restart the DFU timer. err_code = dfu_timer_restart(); VERIFY_SUCCESS(err_code); p_data = (uint32_t *)p_packet->params.data_packet.p_data_packet; err_code = pstorage_store(mp_storage_handle_active, (uint8_t *)p_data, data_length, m_data_received); VERIFY_SUCCESS(err_code); m_data_received += data_length; if (m_data_received != m_image_size) { // The entire image is not received yet. More data is expected. err_code = NRF_ERROR_INVALID_LENGTH; } else { // The entire image has been received. Return NRF_SUCCESS. err_code = NRF_SUCCESS; } break; default: err_code = NRF_ERROR_INVALID_STATE; break; } return err_code; } uint32_t dfu_init_pkt_complete(void) { uint32_t err_code = NRF_ERROR_INVALID_STATE; // DFU initialization has been done and a start packet has been received. if (IMAGE_WRITE_IN_PROGRESS()) { // Image write is already in progress. Cannot handle an init packet now. return NRF_ERROR_INVALID_STATE; } if (m_dfu_state == DFU_STATE_RX_INIT_PKT) { err_code = dfu_init_prevalidate(m_init_packet, m_init_packet_length); if (err_code == NRF_SUCCESS) { m_dfu_state = DFU_STATE_RX_DATA_PKT; } else { m_init_packet_length = 0; } } return err_code; } uint32_t dfu_init_pkt_handle(dfu_update_packet_t * p_packet) { uint32_t err_code = NRF_SUCCESS; uint32_t length; switch (m_dfu_state) { case DFU_STATE_RDY: m_dfu_state = DFU_STATE_RX_INIT_PKT; // When receiving init packet in state ready just update and fall through this case. case DFU_STATE_RX_INIT_PKT: // DFU initialization has been done and a start packet has been received. if (IMAGE_WRITE_IN_PROGRESS()) { // Image write is already in progress. Cannot handle an init packet now. return NRF_ERROR_INVALID_STATE; } // Valid peer activity detected. Hence restart the DFU timer. err_code = dfu_timer_restart(); VERIFY_SUCCESS(err_code); length = p_packet->params.data_packet.packet_length * sizeof(uint32_t); if ((m_init_packet_length + length) > sizeof(m_init_packet)) { return NRF_ERROR_INVALID_LENGTH; } memcpy(&m_init_packet[m_init_packet_length], &p_packet->params.data_packet.p_data_packet[0], length); m_init_packet_length += length; break; default: // Either the start packet was not received or dfu_init function was not called before. err_code = NRF_ERROR_INVALID_STATE; break; } return err_code; } uint32_t dfu_image_validate() { uint32_t err_code; switch (m_dfu_state) { case DFU_STATE_RX_DATA_PKT: // Check if the application image write has finished. if (m_data_received != m_image_size) { // Image not yet fully transfered by the peer or the peer has attempted to write // too much data. Hence the validation should fail. err_code = NRF_ERROR_INVALID_STATE; } else { m_dfu_state = DFU_STATE_VALIDATE; // Valid peer activity detected. Hence restart the DFU timer. err_code = dfu_timer_restart(); if (err_code == NRF_SUCCESS) { err_code = dfu_init_postvalidate((uint8_t *)mp_storage_handle_active->block_id, m_image_size); VERIFY_SUCCESS(err_code); m_dfu_state = DFU_STATE_WAIT_4_ACTIVATE; } } break; default: err_code = NRF_ERROR_INVALID_STATE; break; } return err_code; } uint32_t dfu_image_activate() { uint32_t err_code; switch (m_dfu_state) { case DFU_STATE_WAIT_4_ACTIVATE: // Stop the DFU Timer because the peer activity need not be monitored any longer. err_code = app_timer_stop(m_dfu_timer_id); APP_ERROR_CHECK(err_code); err_code = m_functions.activate(); break; default: err_code = NRF_ERROR_INVALID_STATE; break; } return err_code; } void dfu_reset(void) { dfu_update_status_t update_status; update_status.status_code = DFU_RESET; bootloader_dfu_update_process(update_status); } static uint32_t dfu_compare_block(uint32_t * ptr1, uint32_t * ptr2, uint32_t len) { sd_mbr_command_t sd_mbr_cmd; sd_mbr_cmd.command = SD_MBR_COMMAND_COMPARE; sd_mbr_cmd.params.compare.ptr1 = ptr1; sd_mbr_cmd.params.compare.ptr2 = ptr2; sd_mbr_cmd.params.compare.len = len / sizeof(uint32_t); return sd_mbr_command(&sd_mbr_cmd); } static uint32_t dfu_copy_sd(uint32_t * src, uint32_t * dst, uint32_t len) { sd_mbr_command_t sd_mbr_cmd; sd_mbr_cmd.command = SD_MBR_COMMAND_COPY_SD; sd_mbr_cmd.params.copy_sd.src = src; sd_mbr_cmd.params.copy_sd.dst = dst; sd_mbr_cmd.params.copy_sd.len = len / sizeof(uint32_t); return sd_mbr_command(&sd_mbr_cmd); } static uint32_t dfu_sd_img_block_swap(uint32_t * src, uint32_t * dst, uint32_t len, uint32_t block_size) { // It is neccesarry to swap the new SoftDevice in 3 rounds to ensure correct copy of data // and verifucation of data in case power reset occurs during write to flash. // To ensure the robustness of swapping the images are compared backwards till start of // image swap. If the back is identical everything is swapped. uint32_t err_code = dfu_compare_block(src, dst, len); if (err_code == NRF_SUCCESS) { return err_code; } if ((uint32_t)dst > SOFTDEVICE_REGION_START) { err_code = dfu_sd_img_block_swap((uint32_t *)((uint32_t)src - block_size), (uint32_t *)((uint32_t)dst - block_size), block_size, block_size); VERIFY_SUCCESS(err_code); } err_code = dfu_copy_sd(src, dst, len); VERIFY_SUCCESS(err_code); return dfu_compare_block(src, dst, len); } uint32_t dfu_sd_image_swap(void) { bootloader_settings_t boot_settings; bootloader_settings_get(&boot_settings); if (boot_settings.sd_image_size == 0) { return NRF_SUCCESS; } if ((SOFTDEVICE_REGION_START + boot_settings.sd_image_size) > boot_settings.sd_image_start) { uint32_t err_code; uint32_t sd_start = SOFTDEVICE_REGION_START; uint32_t block_size = (boot_settings.sd_image_start - sd_start) / 2; uint32_t image_end = boot_settings.sd_image_start + boot_settings.sd_image_size; uint32_t img_block_start = boot_settings.sd_image_start + 2 * block_size; uint32_t sd_block_start = sd_start + 2 * block_size; if (SD_SIZE_GET(MBR_SIZE) < boot_settings.sd_image_size) { // This will clear a page thus ensuring the old image is invalidated before swapping. err_code = dfu_copy_sd((uint32_t *)(sd_start + block_size), (uint32_t *)(sd_start + block_size), sizeof(uint32_t)); VERIFY_SUCCESS(err_code); err_code = dfu_copy_sd((uint32_t *)sd_start, (uint32_t *)sd_start, sizeof(uint32_t)); VERIFY_SUCCESS(err_code); } return dfu_sd_img_block_swap((uint32_t *)img_block_start, (uint32_t *)sd_block_start, image_end - img_block_start, block_size); } else { if (boot_settings.sd_image_size != 0) { return dfu_copy_sd((uint32_t *)boot_settings.sd_image_start, (uint32_t *)SOFTDEVICE_REGION_START, boot_settings.sd_image_size); } } return NRF_SUCCESS; } uint32_t dfu_bl_image_swap(void) { bootloader_settings_t bootloader_settings; sd_mbr_command_t sd_mbr_cmd; bootloader_settings_get(&bootloader_settings); if (bootloader_settings.bl_image_size != 0) { uint32_t bl_image_start = (bootloader_settings.sd_image_size == 0) ? DFU_BANK_0_REGION_START : bootloader_settings.sd_image_start + bootloader_settings.sd_image_size; sd_mbr_cmd.command = SD_MBR_COMMAND_COPY_BL; sd_mbr_cmd.params.copy_bl.bl_src = (uint32_t *)(bl_image_start); sd_mbr_cmd.params.copy_bl.bl_len = bootloader_settings.bl_image_size / sizeof(uint32_t); return sd_mbr_command(&sd_mbr_cmd); } return NRF_SUCCESS; } uint32_t dfu_bl_image_validate(void) { bootloader_settings_t bootloader_settings; sd_mbr_command_t sd_mbr_cmd; bootloader_settings_get(&bootloader_settings); if (bootloader_settings.bl_image_size != 0) { uint32_t bl_image_start = (bootloader_settings.sd_image_size == 0) ? DFU_BANK_0_REGION_START : bootloader_settings.sd_image_start + bootloader_settings.sd_image_size; sd_mbr_cmd.command = SD_MBR_COMMAND_COMPARE; sd_mbr_cmd.params.compare.ptr1 = (uint32_t *)BOOTLOADER_REGION_START; sd_mbr_cmd.params.compare.ptr2 = (uint32_t *)(bl_image_start); sd_mbr_cmd.params.compare.len = bootloader_settings.bl_image_size / sizeof(uint32_t); return sd_mbr_command(&sd_mbr_cmd); } return NRF_SUCCESS; } uint32_t dfu_sd_image_validate(void) { bootloader_settings_t bootloader_settings; sd_mbr_command_t sd_mbr_cmd; bootloader_settings_get(&bootloader_settings); if (bootloader_settings.sd_image_size == 0) { return NRF_SUCCESS; } if ((SOFTDEVICE_REGION_START + bootloader_settings.sd_image_size) > bootloader_settings.sd_image_start) { uint32_t sd_start = SOFTDEVICE_REGION_START; uint32_t block_size = (bootloader_settings.sd_image_start - sd_start) / 2; uint32_t image_end = bootloader_settings.sd_image_start + bootloader_settings.sd_image_size; uint32_t img_block_start = bootloader_settings.sd_image_start + 2 * block_size; uint32_t sd_block_start = sd_start + 2 * block_size; if (SD_SIZE_GET(MBR_SIZE) < bootloader_settings.sd_image_size) { return NRF_ERROR_NULL; } return dfu_sd_img_block_swap((uint32_t *)img_block_start, (uint32_t *)sd_block_start, image_end - img_block_start, block_size); } sd_mbr_cmd.command = SD_MBR_COMMAND_COMPARE; sd_mbr_cmd.params.compare.ptr1 = (uint32_t *)SOFTDEVICE_REGION_START; sd_mbr_cmd.params.compare.ptr2 = (uint32_t *)bootloader_settings.sd_image_start; sd_mbr_cmd.params.compare.len = bootloader_settings.sd_image_size / sizeof(uint32_t); return sd_mbr_command(&sd_mbr_cmd); }
682549.c
/* * WPA Supplicant - RSN PMKSA cache * Copyright (c) 2004-2009, 2011-2015, Jouni Malinen <[email protected]> * * This software may be distributed under the terms of the BSD license. * See README for more details. */ #include "utils/includes.h" #include "rsn_supp/wpa.h" #include "rsn_supp/wpa_i.h" #include "common/eapol_common.h" #include "common/ieee802_11_defs.h" #include "pmksa_cache.h" #include "esp_timer.h" #ifdef IEEE8021X_EAPOL static const int pmksa_cache_max_entries = 10; static const int dot11RSNAConfigPMKLifetime = 8640000; // 100 days = 3600 x 24 x 100 Seconds static const int dot11RSNAConfigPMKReauthThreshold = 70; struct rsn_pmksa_cache { struct rsn_pmksa_cache_entry *pmksa; /* PMKSA cache */ int pmksa_count; /* number of entries in PMKSA cache */ struct wpa_sm *sm; /* TODO: get rid of this reference(?) */ esp_timer_handle_t cache_timeout_timer; void (*free_cb)(struct rsn_pmksa_cache_entry *entry, void *ctx, enum pmksa_free_reason reason); void *ctx; }; static void pmksa_cache_set_expiration(struct rsn_pmksa_cache *pmksa); static void _pmksa_cache_free_entry(struct rsn_pmksa_cache_entry *entry) { wpa_bin_clear_free(entry, sizeof(*entry)); } static void pmksa_cache_free_entry(struct rsn_pmksa_cache *pmksa, struct rsn_pmksa_cache_entry *entry, enum pmksa_free_reason reason) { pmksa->pmksa_count--; pmksa->free_cb(entry, pmksa->ctx, reason); _pmksa_cache_free_entry(entry); } static void pmksa_cache_expire(void *eloop_ctx) { struct rsn_pmksa_cache *pmksa = eloop_ctx; int64_t now_sec = esp_timer_get_time() / 1e6; while (pmksa->pmksa && pmksa->pmksa->expiration <= now_sec) { struct rsn_pmksa_cache_entry *entry = pmksa->pmksa; pmksa->pmksa = entry->next; wpa_printf(MSG_DEBUG, "RSN: expired PMKSA cache entry for " MACSTR, MAC2STR(entry->aa)); pmksa_cache_free_entry(pmksa, entry, PMKSA_EXPIRE); } pmksa_cache_set_expiration(pmksa); } static void pmksa_cache_set_expiration(struct rsn_pmksa_cache *pmksa) { int sec; int64_t now_sec = esp_timer_get_time() / 1e6; esp_timer_stop(pmksa->cache_timeout_timer); if (pmksa->pmksa == NULL) return; sec = pmksa->pmksa->expiration - now_sec; if (sec < 0) sec = 0; esp_timer_start_once(pmksa->cache_timeout_timer, (sec + 1) * 1e6); } /** * pmksa_cache_add - Add a PMKSA cache entry * @pmksa: Pointer to PMKSA cache data from pmksa_cache_init() * @pmk: The new pairwise master key * @pmk_len: PMK length in bytes, usually PMK_LEN (32) * @kck: Key confirmation key or %NULL if not yet derived * @kck_len: KCK length in bytes * @aa: Authenticator address * @spa: Supplicant address * @network_ctx: Network configuration context for this PMK * @akmp: WPA_KEY_MGMT_* used in key derivation * Returns: Pointer to the added PMKSA cache entry or %NULL on error * * This function create a PMKSA entry for a new PMK and adds it to the PMKSA * cache. If an old entry is already in the cache for the same Authenticator, * this entry will be replaced with the new entry. PMKID will be calculated * based on the PMK and the driver interface is notified of the new PMKID. */ struct rsn_pmksa_cache_entry * pmksa_cache_add(struct rsn_pmksa_cache *pmksa, const u8 *pmk, size_t pmk_len, const u8 *pmkid, const u8 *kck, size_t kck_len, const u8 *aa, const u8 *spa, void *network_ctx, int akmp) { struct rsn_pmksa_cache_entry *entry, *pos, *prev; int64_t now_sec = esp_timer_get_time() / 1e6; if (pmk_len > PMK_LEN) return NULL; if (wpa_key_mgmt_suite_b(akmp) && !kck) return NULL; entry = os_zalloc(sizeof(*entry)); if (entry == NULL) return NULL; os_memcpy(entry->pmk, pmk, pmk_len); entry->pmk_len = pmk_len; if (pmkid) os_memcpy(entry->pmkid, pmkid, PMKID_LEN); else rsn_pmkid(pmk, pmk_len, aa, spa, entry->pmkid, wpa_key_mgmt_sha256(akmp)); entry->expiration = now_sec + dot11RSNAConfigPMKLifetime; entry->reauth_time = now_sec + dot11RSNAConfigPMKLifetime * dot11RSNAConfigPMKReauthThreshold / 100; entry->akmp = akmp; os_memcpy(entry->aa, aa, ETH_ALEN); entry->network_ctx = network_ctx; /* Replace an old entry for the same Authenticator (if found) with the * new entry */ pos = pmksa->pmksa; prev = NULL; while (pos) { if (os_memcmp(aa, pos->aa, ETH_ALEN) == 0) { if (pos->pmk_len == pmk_len && os_memcmp_const(pos->pmk, pmk, pmk_len) == 0 && os_memcmp_const(pos->pmkid, entry->pmkid, PMKID_LEN) == 0) { wpa_printf(MSG_DEBUG, "WPA: reusing previous " "PMKSA entry"); os_free(entry); return pos; } if (prev == NULL) pmksa->pmksa = pos->next; else prev->next = pos->next; /* * If OKC is used, there may be other PMKSA cache * entries based on the same PMK. These needs to be * flushed so that a new entry can be created based on * the new PMK. Only clear other entries if they have a * matching PMK and this PMK has been used successfully * with the current AP, i.e., if opportunistic flag has * been cleared in wpa_supplicant_key_neg_complete(). */ wpa_printf(MSG_DEBUG, "RSN: Replace PMKSA entry for " "the current AP and any PMKSA cache entry " "that was based on the old PMK"); if (!pos->opportunistic) pmksa_cache_flush(pmksa, network_ctx, pos->pmk, pos->pmk_len); pmksa_cache_free_entry(pmksa, pos, PMKSA_REPLACE); break; } prev = pos; pos = pos->next; } if (pmksa->pmksa_count >= pmksa_cache_max_entries && pmksa->pmksa) { /* Remove the oldest entry to make room for the new entry */ pos = pmksa->pmksa; if (pos == pmksa->sm->cur_pmksa) { /* * Never remove the current PMKSA cache entry, since * it's in use, and removing it triggers a needless * deauthentication. */ pos = pos->next; pmksa->pmksa->next = pos ? pos->next : NULL; } else pmksa->pmksa = pos->next; if (pos) { wpa_printf(MSG_DEBUG, "RSN: removed the oldest idle " "PMKSA cache entry (for " MACSTR ") to " "make room for new one", MAC2STR(pos->aa)); pmksa_cache_free_entry(pmksa, pos, PMKSA_FREE); } } /* Add the new entry; order by expiration time */ pos = pmksa->pmksa; prev = NULL; while (pos) { if (pos->expiration > entry->expiration) break; prev = pos; pos = pos->next; } if (prev == NULL) { entry->next = pmksa->pmksa; pmksa->pmksa = entry; pmksa_cache_set_expiration(pmksa); } else { entry->next = prev->next; prev->next = entry; } pmksa->pmksa_count++; wpa_printf(MSG_DEBUG, "RSN: Added PMKSA cache entry for " MACSTR " network_ctx=%p", MAC2STR(entry->aa), network_ctx); return entry; } /** * pmksa_cache_flush - Flush PMKSA cache entries for a specific network * @pmksa: Pointer to PMKSA cache data from pmksa_cache_init() * @network_ctx: Network configuration context or %NULL to flush all entries * @pmk: PMK to match for or %NYLL to match all PMKs * @pmk_len: PMK length */ void pmksa_cache_flush(struct rsn_pmksa_cache *pmksa, void *network_ctx, const u8 *pmk, size_t pmk_len) { struct rsn_pmksa_cache_entry *entry, *prev = NULL, *tmp; int removed = 0; entry = pmksa->pmksa; while (entry) { if ((entry->network_ctx == network_ctx || network_ctx == NULL) && (pmk == NULL || (pmk_len == entry->pmk_len && os_memcmp(pmk, entry->pmk, pmk_len) == 0))) { wpa_printf(MSG_DEBUG, "RSN: Flush PMKSA cache entry " "for " MACSTR, MAC2STR(entry->aa)); if (prev) prev->next = entry->next; else pmksa->pmksa = entry->next; tmp = entry; entry = entry->next; pmksa_cache_free_entry(pmksa, tmp, PMKSA_FREE); removed++; } else { prev = entry; entry = entry->next; } } /*if (removed) pmksa_cache_set_expiration(pmksa);*/ } /** * pmksa_cache_deinit - Free all entries in PMKSA cache * @pmksa: Pointer to PMKSA cache data from pmksa_cache_init() */ void pmksa_cache_deinit(struct rsn_pmksa_cache *pmksa) { struct rsn_pmksa_cache_entry *entry, *prev; if (pmksa == NULL) return; entry = pmksa->pmksa; pmksa->pmksa = NULL; while (entry) { prev = entry; entry = entry->next; os_free(prev); } pmksa_cache_set_expiration(pmksa); esp_timer_stop(pmksa->cache_timeout_timer); esp_timer_delete(pmksa->cache_timeout_timer); os_free(pmksa); } /** * pmksa_cache_get - Fetch a PMKSA cache entry * @pmksa: Pointer to PMKSA cache data from pmksa_cache_init() * @aa: Authenticator address or %NULL to match any * @pmkid: PMKID or %NULL to match any * @network_ctx: Network context or %NULL to match any * Returns: Pointer to PMKSA cache entry or %NULL if no match was found */ struct rsn_pmksa_cache_entry * pmksa_cache_get(struct rsn_pmksa_cache *pmksa, const u8 *aa, const u8 *pmkid, const void *network_ctx) { struct rsn_pmksa_cache_entry *entry = pmksa->pmksa; while (entry) { if ((aa == NULL || os_memcmp(entry->aa, aa, ETH_ALEN) == 0) && (pmkid == NULL || os_memcmp(entry->pmkid, pmkid, PMKID_LEN) == 0) && (network_ctx == NULL || network_ctx == entry->network_ctx)) return entry; entry = entry->next; } return NULL; } static struct rsn_pmksa_cache_entry * pmksa_cache_clone_entry(struct rsn_pmksa_cache *pmksa, const struct rsn_pmksa_cache_entry *old_entry, const u8 *aa) { struct rsn_pmksa_cache_entry *new_entry; new_entry = pmksa_cache_add(pmksa, old_entry->pmk, old_entry->pmk_len, NULL, NULL, 0, aa, pmksa->sm->own_addr, old_entry->network_ctx, old_entry->akmp); if (new_entry == NULL) return NULL; /* TODO: reorder entries based on expiration time? */ new_entry->expiration = old_entry->expiration; new_entry->opportunistic = 1; return new_entry; } /** * pmksa_cache_get_opportunistic - Try to get an opportunistic PMKSA entry * @pmksa: Pointer to PMKSA cache data from pmksa_cache_init() * @network_ctx: Network configuration context * @aa: Authenticator address for the new AP * Returns: Pointer to a new PMKSA cache entry or %NULL if not available * * Try to create a new PMKSA cache entry opportunistically by guessing that the * new AP is sharing the same PMK as another AP that has the same SSID and has * already an entry in PMKSA cache. */ struct rsn_pmksa_cache_entry * pmksa_cache_get_opportunistic(struct rsn_pmksa_cache *pmksa, void *network_ctx, const u8 *aa) { struct rsn_pmksa_cache_entry *entry = pmksa->pmksa; wpa_printf(MSG_DEBUG, "RSN: Consider " MACSTR " for OKC", MAC2STR(aa)); if (network_ctx == NULL) return NULL; while (entry) { if (entry->network_ctx == network_ctx) { entry = pmksa_cache_clone_entry(pmksa, entry, aa); if (entry) { wpa_printf(MSG_DEBUG, "RSN: added " "opportunistic PMKSA cache entry " "for " MACSTR, MAC2STR(aa)); } return entry; } entry = entry->next; } return NULL; } /** * pmksa_cache_get_current - Get the current used PMKSA entry * @sm: Pointer to WPA state machine data from wpa_sm_init() * Returns: Pointer to the current PMKSA cache entry or %NULL if not available */ struct rsn_pmksa_cache_entry * pmksa_cache_get_current(struct wpa_sm *sm) { if (sm == NULL) return NULL; return sm->cur_pmksa; } /** * pmksa_cache_clear_current - Clear the current PMKSA entry selection * @sm: Pointer to WPA state machine data from wpa_sm_init() */ void pmksa_cache_clear_current(struct wpa_sm *sm) { if (sm == NULL) return; sm->cur_pmksa = NULL; } /** * pmksa_cache_set_current - Set the current PMKSA entry selection * @sm: Pointer to WPA state machine data from wpa_sm_init() * @pmkid: PMKID for selecting PMKSA or %NULL if not used * @bssid: BSSID for PMKSA or %NULL if not used * @network_ctx: Network configuration context * @try_opportunistic: Whether to allow opportunistic PMKSA caching * Returns: 0 if PMKSA was found or -1 if no matching entry was found */ int pmksa_cache_set_current(struct wpa_sm *sm, const u8 *pmkid, const u8 *bssid, void *network_ctx, int try_opportunistic) { struct rsn_pmksa_cache *pmksa = sm->pmksa; wpa_printf(MSG_DEBUG, "RSN: PMKSA cache search - network_ctx=%p " "try_opportunistic=%d", network_ctx, try_opportunistic); if (pmkid) wpa_hexdump(MSG_DEBUG, "RSN: Search for PMKID", pmkid, PMKID_LEN); if (bssid) wpa_printf(MSG_DEBUG, "RSN: Search for BSSID " MACSTR, MAC2STR(bssid)); sm->cur_pmksa = NULL; if (pmkid) sm->cur_pmksa = pmksa_cache_get(pmksa, NULL, pmkid, network_ctx); if (sm->cur_pmksa == NULL && bssid) sm->cur_pmksa = pmksa_cache_get(pmksa, bssid, NULL, network_ctx); if (sm->cur_pmksa == NULL && try_opportunistic && bssid) sm->cur_pmksa = pmksa_cache_get_opportunistic(pmksa, network_ctx, bssid); if (sm->cur_pmksa) { wpa_hexdump(MSG_DEBUG, "RSN: PMKSA cache entry found - PMKID", sm->cur_pmksa->pmkid, PMKID_LEN); return 0; } wpa_printf(MSG_DEBUG, "RSN: No PMKSA cache entry found"); return -1; } /** * pmksa_cache_list - Dump text list of entries in PMKSA cache * @pmksa: Pointer to PMKSA cache data from pmksa_cache_init() * @buf: Buffer for the list * @len: Length of the buffer * Returns: number of bytes written to buffer * * This function is used to generate a text format representation of the * current PMKSA cache contents for the ctrl_iface PMKSA command. */ int pmksa_cache_list(struct rsn_pmksa_cache *pmksa, char *buf, size_t len) { int i, ret; char *pos = buf; struct rsn_pmksa_cache_entry *entry; int64_t now_sec = esp_timer_get_time() / 1e6; ret = os_snprintf(pos, buf + len - pos, "Index / AA / PMKID / expiration (in seconds) / " "opportunistic\n"); if (os_snprintf_error(buf + len - pos, ret)) return pos - buf; pos += ret; i = 0; entry = pmksa->pmksa; while (entry) { i++; ret = os_snprintf(pos, buf + len - pos, "%d " MACSTR " ", i, MAC2STR(entry->aa)); if (os_snprintf_error(buf + len - pos, ret)) return pos - buf; pos += ret; pos += wpa_snprintf_hex(pos, buf + len - pos, entry->pmkid, PMKID_LEN); ret = os_snprintf(pos, buf + len - pos, " %d %d\n", (int) (entry->expiration - now_sec), entry->opportunistic); if (os_snprintf_error(buf + len - pos, ret)) return pos - buf; pos += ret; entry = entry->next; } return pos - buf; } /** * pmksa_cache_init - Initialize PMKSA cache * @free_cb: Callback function to be called when a PMKSA cache entry is freed * @ctx: Context pointer for free_cb function * @sm: Pointer to WPA state machine data from wpa_sm_init() * Returns: Pointer to PMKSA cache data or %NULL on failure */ struct rsn_pmksa_cache * pmksa_cache_init(void (*free_cb)(struct rsn_pmksa_cache_entry *entry, void *ctx, enum pmksa_free_reason reason), void *ctx, struct wpa_sm *sm) { struct rsn_pmksa_cache *pmksa; pmksa = os_zalloc(sizeof(*pmksa)); if (pmksa) { pmksa->free_cb = free_cb; pmksa->ctx = ctx; pmksa->sm = sm; pmksa->pmksa_count = 0; pmksa->pmksa = NULL; esp_timer_create_args_t pmksa_cache_timeout_timer_create = { .callback = &pmksa_cache_expire, .arg = pmksa, .dispatch_method = ESP_TIMER_TASK, .name = "pmksa_timeout_timer" }; esp_timer_create(&pmksa_cache_timeout_timer_create, &(pmksa->cache_timeout_timer)); } return pmksa; } #endif /* IEEE8021X_EAPOL */
404693.c
#include <stdint.h> #include <stdlib.h> #include "md4c-html.h" static void process_output(const MD_CHAR* text, MD_SIZE size, void* userdata) { /* This is dummy function because we dont need any processing on the data */ return; } int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size){ if (size < 8) { return 0; } unsigned int parser_flags = *(unsigned int*)data; data += 4; size -= 4; unsigned int renderer_flags = *(unsigned int*)data; data += 4; size -= 4; /* Allocate enough space */ char *out = (char*)malloc(size*3); md_html((MD_CHAR*)data, size, process_output, out, parser_flags, renderer_flags); free(out); return 0; }
970425.c
// https://www.codewars.com/kata/57cebe1dc6fdc20c57000ac9 #include <sys/types.h> #include <stdio.h> #include <stdlib.h> #include <string.h> ssize_t find_short(const char *str_in) { ssize_t length_in = strlen(str_in); char str_consume[length_in]; strncpy(str_consume, str_in, length_in + 1); char *token = strtok(str_consume, " "); ssize_t shortest = strlen(token); while (token != NULL) { ssize_t length = strlen(token); shortest = length < shortest ? length : shortest; token = strtok(NULL, " "); } return shortest; }
663387.c
/**************************************************************************** * libs/libnx/nxmu/nx_constructwindow.c * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. The * ASF licenses this file to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. * ****************************************************************************/ /**************************************************************************** * Included Files ****************************************************************************/ #include <nuttx/config.h> #include <stdlib.h> #include <errno.h> #include <debug.h> #include <nuttx/nx/nx.h> #include <nuttx/nx/nxbe.h> #include <nuttx/nx/nxmu.h> #include "nxcontext.h" /**************************************************************************** * Public Functions ****************************************************************************/ /**************************************************************************** * Name: nx_constructwindow * * Description: * This function is the same a nx_openwindow EXCEPT that the client * provides the window structure instance. nx_constructwindow will * initialize the the pre-allocated window structure for use by NX. * This function is provided in addition to nx_openwindow in order * to support a kind of inheritance: The caller's window structure * may include extensions that are not visible to NX. * * NOTE: * hwnd must have been allocated using a user-space allocator that permits * user access to the window. Once provided to nx_constructwindow() that * memory is owned and managed by NX. On certain error conditions or * when the window is closed, NX will free the window. * * Input Parameters: * handle - The handle returned by nx_connect * hwnd - The pre-allocated window structure. * flags - Optional flags. Must be zero unless CONFIG_NX_RAMBACKED is * enabled. In that case, it may be zero or * NXBE_WINDOW_RAMBACKED * cb - Callbacks used to process window events * arg - User provided value that will be returned with NX callbacks. * * Returned Value: * OK on success; ERROR on failure with errno set appropriately. In the * case of ERROR, NX will have deallocated the pre-allocated window. * ****************************************************************************/ int nx_constructwindow(NXHANDLE handle, NXWINDOW hwnd, uint8_t flags, FAR const struct nx_callback_s *cb, FAR void *arg) { FAR struct nxmu_conn_s *conn = (FAR struct nxmu_conn_s *)handle; FAR struct nxbe_window_s *wnd = (FAR struct nxbe_window_s *)hwnd; struct nxsvrmsg_openwindow_s outmsg; #ifdef CONFIG_DEBUG_FEATURES if (wnd == NULL) { set_errno(EINVAL); return ERROR; } if (conn == NULL || cb == NULL || (flags & ~NXBE_WINDOW_USER) != 0) { lib_ufree(wnd); set_errno(EINVAL); return ERROR; } #endif /* Setup only the connection structure, user flags, callbacks and client * private data reference. The server will set everything else up. */ wnd->conn = conn; wnd->flags = flags; wnd->cb = cb; wnd->arg = arg; #ifdef CONFIG_NX_RAMBACKED #ifdef CONFIG_BUILD_KERNEL wnd->npages = 0; #endif wnd->stride = 0; wnd->fbmem = NULL; #endif /* Request initialization the new window from the server */ outmsg.msgid = NX_SVRMSG_OPENWINDOW; outmsg.wnd = wnd; return nxmu_sendserver(conn, &outmsg, sizeof(struct nxsvrmsg_openwindow_s)); }
362852.c
/* * Copyright (c) 2015 Peter Rosin <[email protected]> * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include <string.h> #include <stdlib.h> #include "confuse.h" static cfg_t *cfg; static int cmdc; static char **cmdv; static int cmdv_max; static int reserve_cmdv(int cmdc) { int cmd_max = cmdv_max; char **tmp; if (cmdc < cmd_max) return 0; do cmd_max += 10; while (cmdc >= cmd_max); tmp = realloc(cmdv, cmd_max * sizeof(*tmp)); if (!tmp) return -1; cmdv = tmp; cmdv_max = cmd_max; return 0; } static int split_cmd(char *cmd) { char *out = cmd; int arg; cmdc = 0; for (;;) { char ch; arg = 0; while (*cmd == ' ') ++cmd; next_char: ch = *cmd++; if (ch == '"' || ch == '\'') { char end = ch; if (!arg) { if (reserve_cmdv(cmdc + 1)) return -1; cmdv[cmdc++] = out; arg = 1; } while (*cmd && *cmd != end) *out++ = *cmd++; if (!*cmd++) return -1; goto next_char; } if (ch && ch != ' ') { if (!arg) { if (reserve_cmdv(cmdc + 1)) return -1; cmdv[cmdc++] = out; arg = 1; } *out++ = ch; goto next_char; } *out++ = 0; if (!ch) break; } return cmdc; } static char *input_cmd(void) { int ch; char *cmd = malloc(128); int len = 128; int pos = 0; if (!cmd) return NULL; for (;;) { ch = fgetc(stdin); if (ch < 0) break; switch (ch) { case '\r': case '\n': ch = 0; /* fall through */ default: if (pos == len) { char *tmp = realloc(cmd, len * 2); if (!tmp) goto cleanup; cmd = tmp; len *= 2; } cmd[pos++] = ch; if (!ch) return cmd; } } cleanup: free(cmd); return NULL; } static const char *help(int argc, char *argv[]) { return "Available commands:\n" "\n" "help\n" "set <option> <value> ...\n" "subset <section> <option> <value>\n" "create <section>\n" "destroy <section>\n" "dump\n" "quit\n" "\n" "<option> is one of 'bool', 'int' 'string' and 'float'.\n"; } static const char *set(int argc, char *argv[]) { if (argc < 3) return "Need more args\n"; if (!cfg_getopt(cfg, argv[1])) return "Unknown option\n"; if (cfg_setmulti(cfg, argv[1], argc - 2, &argv[2])) return "Failure\n"; return "OK\n"; } static const char *subset(int argc, char *argv[]) { cfg_t *sub; if (argc < 4) return "Need more args\n"; if (argc > 4) return "Too many args\n"; sub = cfg_gettsec(cfg, "sub", argv[1]); if (!sub) return "No such section\n"; if (!cfg_getopt(sub, argv[2])) return "Unknown option\n"; if (cfg_setmulti(sub, argv[2], argc - 3, &argv[3])) return "Failure\n"; return "OK\n"; } static const char *create(int argc, char *argv[]) { int ret; char *buf; if (argc != 2) return "Need one arg\n"; if (cfg_gettsec(cfg, "sub", argv[1])) return "Section exists already\n"; buf = malloc(strlen(argv[1]) + 20); if (!buf) return NULL; sprintf(buf, "sub %s {}\n", argv[1]); ret = cfg_parse_buf(cfg, buf) != CFG_SUCCESS; free(buf); if (ret) return "Failure\n"; return "OK\n"; } static const char *destroy(int argc, char *argv[]) { if (argc < 2) return "Need one arg\n"; if (!cfg_gettsec(cfg, "sub", argv[1])) return "No such section\n"; cfg_rmtsec(cfg, "sub", argv[1]); return "OK\n"; } static const char *dump(int argc, char *argv[]) { cfg_print(cfg, stdout); return ""; } static const char *quit(int argc, char *argv[]) { return NULL; } struct cmd_handler { const char *cmd; const char *(*handler)(int argc, char *argv[]); }; static const struct cmd_handler cmds[] = { { "help", help }, { "set", set }, { "subset", subset }, { "create", create }, { "destroy", destroy }, { "dump", dump }, { "quit", quit }, { "exit", quit }, { NULL, NULL } }; int main(void) { cfg_opt_t sub_opts[] = { CFG_BOOL("bool", cfg_false, CFGF_NONE), CFG_STR("string", NULL, CFGF_NONE), CFG_INT("int", 0, CFGF_NONE), CFG_FLOAT("float", 0.0, CFGF_NONE), CFG_END() }; cfg_opt_t opts[] = { CFG_BOOL_LIST("bool", cfg_false, CFGF_NONE), CFG_STR_LIST("string", NULL, CFGF_NONE), CFG_INT_LIST("int", 0, CFGF_NONE), CFG_FLOAT_LIST("float", "0.0", CFGF_NONE), CFG_SEC("sub", sub_opts, CFGF_MULTI | CFGF_TITLE | CFGF_NO_TITLE_DUPES), CFG_END() }; char *cmd = NULL; const char *reply; int res; int i; cfg = cfg_init(opts, CFGF_NONE); for (;;) { printf("cli> "); fflush(stdout); if (cmd) free(cmd); cmd = input_cmd(); if (!cmd) exit(0); res = split_cmd(cmd); if (res < 0) { printf("Parse error\n"); continue; } if (cmdc == 0) continue; for (i = 0; cmds[i].cmd; ++i) { if (strcmp(cmdv[0], cmds[i].cmd)) continue; reply = cmds[i].handler(cmdc, cmdv); if (!reply) exit(0); printf("%s", reply); break; } if (!cmds[i].cmd) printf("Unknown command\n"); } cfg_free(cfg); return 0; } /** * Local Variables: * indent-tabs-mode: t * c-file-style: "linux" * End: */
957363.c
/* * Copyright (c) 1984 through 2007, William LeFebvre * 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 William LeFebvre nor the names of other * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* * top - a top users display for Unix * * SYNOPSIS: OSF/1, Digital Unix 4.0, Compaq Tru64 5.0 * * DESCRIPTION: * This is the machine-dependent module for DEC OSF/1 and its descendents * It is known to work on OSF/1 1.2, 1.3, 2.0-T3, 3.0, Digital Unix V4.0, * Digital Unix 5.0, and Tru64 5.0. * WARNING: if you use optimization with the standard "cc" compiler that * . comes with V3.0 the resulting executable may core dump. If * . this happens, recompile without optimization. * * LIBS: -lmld -lmach * * CFLAGS: -DHAVE_GETOPT -DORDER * * AUTHOR: Anthony Baxter, <[email protected]> * Derived originally from m_ultrix, by David S. Comay <[email protected]>, * although by now there is hardly any of the code from m_ultrix left. * Helped a lot by having the source for syd(1), by Claus Kalle, and * from several people at DEC who helped with providing information on * some of the less-documented bits of the kernel interface. * * Modified: 31-Oct-94, Pat Welch, [email protected] * changed _mpid to pidtab for compatibility with OSF/1 version 3.0 * * Modified: 13-Dec-94, William LeFebvre, [email protected] * removed used of pidtab (that was bogus) and changed things to * automatically detect the absence of _mpid in the nlist and * recover gracefully---this appears to be the only difference * with 3.0. * * Modified: 3-Mar-00, Rainer Orth <[email protected]> * added support for sort ordering. */ /* * Theory of operation: * * Use Mach calls to build up a structure that contains all the sorts * of stuff normally found in a struct proc in a BSD system. Then * everything else uses this structure. This has major performance wins, * and also should work for future versions of the O/S. */ #include "config.h" #include <sys/types.h> #include <sys/signal.h> #include <sys/param.h> #include <string.h> #include <sys/user.h> #include <stdio.h> #include <nlist.h> #include <math.h> #include <sys/dir.h> #include <sys/user.h> #include <sys/proc.h> #include <sys/dk.h> #include <sys/vm.h> #include <sys/file.h> #include <sys/time.h> /* #include <machine/pte.h> */ /* forward declarations, needed by <net/if.h> included from <sys/table.h> */ struct rtentry; struct mbuf; #include <sys/table.h> #include <mach.h> #include <mach/mach_types.h> #include <mach/vm_statistics.h> #include <sys/syscall.h> /* for SYS_setpriority, in setpriority(), below */ #include "top.h" #include "machine.h" #include "utils.h" extern int errno, sys_nerr; extern char *sys_errlist[]; #define strerror(e) (((e) >= 0 && (e) < sys_nerr) ? sys_errlist[(e)] : "Unknown error") #define VMUNIX "/vmunix" #define KMEM "/dev/kmem" #define MEM "/dev/mem" /* get_process_info passes back a handle. This is what it looks like: */ struct handle { struct osf1_top_proc **next_proc; /* points to next valid proc pointer */ int remaining; /* number of pointers remaining */ }; /* declarations for load_avg */ #include "loadavg.h" /* definitions for indices in the nlist array */ #define X_MPID 0 static struct nlist nlst[] = { { "_mpid" }, /* 0 */ { 0 } }; /* Some versions of OSF/1 don't support reporting of the last PID. This flag indicates whether or not we are reporting the last PID. */ static int do_last_pid = 1; /* * These definitions control the format of the per-process area */ static char header[] = " PID X PRI NICE SIZE RES STATE TIME CPU COMMAND"; /* 01234567 -- field to fill in starts at header+7 */ #define UNAME_START 7 #define Proc_format \ "%6d %-8.8s %3d %4d %5s %5s %-5s %-6s %5.2f%% %s" /* process state names for the "STATE" column of the display */ /* the extra nulls in the string "run" are for adding a slash and * the processor number when needed. Although OSF/1 doesnt support * multiple processors yet, (and this module _certainly_ doesnt * support it, either, we may as well plan for the future. :-) */ char *state_abbrev[] = { "", "run\0\0\0", "WAIT", "sleep", "sleep", "stop", "halt", "???", "zomb" }; static int kmem, mem; /* values that we stash away in _init and use in later routines */ static double logcpu; /* these are retrieved from the kernel in _init */ static unsigned long proc; static int nproc; static load_avg ccpu; typedef long mtime_t; /* these are offsets obtained via nlist and used in the get_ functions */ static unsigned long mpid_offset; /* these are for detailing the process states */ int process_states[9]; char *procstatenames[] = { "", " running, ", " waiting, ", " sleeping, ", " idle, ", " stopped, ", " halted, ", "", " zombie", NULL }; /* these are for detailing the cpu states */ int cpu_states[5]; char *cpustatenames[] = { "user", "nice", "system", "wio", "idle", NULL }; long old_cpu_ticks[5]; /* these are for detailing the memory statistics */ long memory_stats[5]; char *memorynames[] = { "K active, ", "K inactive, ", "K total, ", "K free", NULL }; long swap_stats[3]; char *swapnames[] = { "K in use, ", "K total", NULL }; /* these are names given to allowed sorting orders -- first is default */ char *ordernames[] = { "cpu", "size", "res", "time", NULL }; /* forward definitions for comparison functions */ int compare_cpu(); int compare_size(); int compare_res(); int compare_time(); int (*proc_compares[])() = { compare_cpu, compare_size, compare_res, compare_time, NULL }; /* these are for getting the memory statistics */ static int pageshift; /* log base 2 of the pagesize */ /* define pagetok in terms of pageshift */ #define pagetok(size) ((size) << pageshift) /* take a process, make it a mach task, and grab all the info out */ void do_threads_calculations(); /* * Because I dont feel like repeatedly grunging through the kernel with * Mach calls, and I also dont want the horrid performance hit this * would give, I read the stuff I need out, and put in into my own * structure, for later use. */ struct osf1_top_proc { size_t p_mach_virt_size; char p_mach_state; int p_flag; fixpt_t p_mach_pct_cpu; /* aka p_pctcpu */ int used_ticks; size_t process_size; pid_t p_pid; uid_t p_ruid; char p_pri; char p_nice; size_t p_rssize; char u_comm[PI_COMLEN + 1]; } ; /* these are for keeping track of the proc array */ static int bytes; static int pref_len; static struct osf1_top_proc *pbase; static struct osf1_top_proc **pref; /* useful externals */ extern int errno; extern char *sys_errlist[]; long percentages(); machine_init(statics) struct statics *statics; { register int i = 0; register int pagesize; struct tbl_sysinfo sibuf; if ((kmem = open(KMEM, O_RDONLY)) == -1) { perror(KMEM); return(-1); } if ((mem = open(MEM, O_RDONLY)) == -1) { perror(MEM); return(-1); } /* get the list of symbols we want to access in the kernel */ if (nlist(VMUNIX, nlst) == -1) { perror("TOP(nlist)"); return (-1); } if (nlst[X_MPID].n_type == 0) { /* this kernel has no _mpid, so go without */ do_last_pid = 0; } else { /* stash away mpid pointer for later use */ mpid_offset = nlst[X_MPID].n_value; } /* get the symbol values out of kmem */ nproc = table(TBL_PROCINFO, 0, (struct tbl_procinfo *)NULL, INT_MAX, 0); /* allocate space for proc structure array and array of pointers */ bytes = nproc * sizeof(struct osf1_top_proc); pbase = (struct osf1_top_proc *)malloc(bytes); pref = (struct osf1_top_proc **)malloc(nproc * sizeof(struct osf1_top_proc *)); /* Just in case ... */ if (pbase == (struct osf1_top_proc *)NULL || pref == (struct osf1_top_proc **)NULL) { fprintf(stderr, "top: cannot allocate sufficient memory\n"); return(-1); } /* get the page size with "getpagesize" and calculate pageshift from it */ pagesize = getpagesize(); pageshift = 0; while (pagesize > 1) { pageshift++; pagesize >>= 1; } /* we only need the amount of log(2)1024 for our conversion */ pageshift -= LOG1024; /* fill in the statics information */ statics->procstate_names = procstatenames; statics->cpustate_names = cpustatenames; statics->memory_names = memorynames; statics->order_names = ordernames; statics->swap_names = swapnames; /* initialise this, for calculating cpu time */ if (table(TBL_SYSINFO,0,&sibuf,1,sizeof(struct tbl_sysinfo))<0) { perror("TBL_SYSINFO"); return(-1); } old_cpu_ticks[0] = sibuf.si_user; old_cpu_ticks[1] = sibuf.si_nice; old_cpu_ticks[2] = sibuf.si_sys; old_cpu_ticks[3] = sibuf.wait; old_cpu_ticks[4] = sibuf.si_idle; /* all done! */ return(0); } char *format_header(uname_field) register char *uname_field; { register char *ptr; ptr = header + UNAME_START; while (*uname_field != '\0') { *ptr++ = *uname_field++; } return(header); } void get_system_info(si) struct system_info *si; { struct tbl_loadavg labuf; struct tbl_sysinfo sibuf; struct tbl_swapinfo swbuf; vm_statistics_data_t vmstats; int swap_pages=0,swap_free=0,i; long new_ticks[5],diff_ticks[5]; long delta_ticks; if (do_last_pid) { /* last pid assigned */ (void) getkval(mpid_offset, &(si->last_pid), sizeof(si->last_pid), "_mpid"); } else { si->last_pid = -1; } /* get load averages */ if (table(TBL_LOADAVG,0,&labuf,1,sizeof(struct tbl_loadavg))<0) { perror("TBL_LOADAVG"); return; } if (labuf.tl_lscale) /* scaled */ for(i=0;i<3;i++) si->load_avg[i] = ((double)labuf.tl_avenrun.l[i] / (double)labuf.tl_lscale ); else /* not scaled */ for(i=0;i<3;i++) si->load_avg[i] = labuf.tl_avenrun.d[i]; /* array of cpu state counters */ if (table(TBL_SYSINFO,0,&sibuf,1,sizeof(struct tbl_sysinfo))<0) { perror("TBL_SYSINFO"); return; } new_ticks[0] = sibuf.si_user ; new_ticks[1] = sibuf.si_nice; new_ticks[2] = sibuf.si_sys ; new_ticks[3] = sibuf.wait; new_ticks[4] = sibuf.si_idle; delta_ticks=0; for(i=0;i<5;i++) { diff_ticks[i] = new_ticks[i] - old_cpu_ticks[i]; delta_ticks += diff_ticks[i]; old_cpu_ticks[i] = new_ticks[i]; } si->cpustates = cpu_states; if(delta_ticks) for(i=0;i<5;i++) si->cpustates[i] = (int)( ( (double)diff_ticks[i] / (double)delta_ticks ) * 1000 ); /* memory information */ /* this is possibly bogus - we work out total # pages by */ /* adding up the free, active, inactive, wired down, and */ /* zero filled. Anyone who knows a better way, TELL ME! */ /* Change: dont use zero filled. */ (void) vm_statistics(task_self(),&vmstats); /* thanks DEC for the table() command. No thanks at all for */ /* omitting the man page for it from OSF/1 1.2, and failing */ /* to document SWAPINFO in the 1.3 man page. Lets hear it for */ /* include files. */ i=0; while(table(TBL_SWAPINFO,i,&swbuf,1,sizeof(struct tbl_swapinfo))>0) { swap_pages += swbuf.size; swap_free += swbuf.free; i++; } memory_stats[0] = pagetok(vmstats.active_count); memory_stats[1] = pagetok(vmstats.inactive_count); memory_stats[2] = pagetok((vmstats.free_count + vmstats.active_count + vmstats.inactive_count + vmstats.wire_count)); memory_stats[3] = pagetok(vmstats.free_count); swap_stats[0] = pagetok(swap_pages - swap_free); swap_stats[1] = pagetok(swap_pages); si->memory = memory_stats; si->swap = swap_stats; } static struct handle handle; caddr_t get_process_info(si, sel, compare_index) struct system_info *si; struct process_select *sel; int compare_index; { register int i; register int total_procs; register int active_procs; register struct osf1_top_proc **prefp; register struct osf1_top_proc *pp; struct tbl_procinfo p_i[8]; int j,k,r; /* these are copied out of sel for speed */ int show_idle; int show_uid; int show_command; /* get a pointer to the states summary array */ si->procstates = process_states; /* set up flags which define what we are going to select */ show_idle = sel->idle; show_uid = sel->uid != -1; show_command = sel->command != NULL; /* count up process states and get pointers to interesting procs */ total_procs = 0; active_procs = 0; memset((char *)process_states, 0, sizeof(process_states)); prefp = pref; pp=pbase; for (j=0; j<nproc; j += 8) { r = table(TBL_PROCINFO, j, (struct tbl_procinfo *)p_i, 8, sizeof(struct tbl_procinfo)); for (k=0; k < r; k++ , pp++) { if(p_i[k].pi_pid == 0) { pp->p_pid = 0; } else { pp->p_pid = p_i[k].pi_pid; pp->p_ruid = p_i[k].pi_ruid; pp->p_flag = p_i[k].pi_flag; pp->p_nice = getpriority(PRIO_PROCESS,p_i[k].pi_pid); /* Load useful values into the proc structure */ do_threads_calculations(pp); /* * Place pointers to each valid proc structure in pref[]. * Process slots that are actually in use have a non-zero * status field. */ #ifdef DEBUG /* * Emit debug info about all processes before selection. */ fprintf(stderr, "pid = %d ruid = %d comm = %s p_mach_state = %d p_stat = %d p_flag = 0x%x\n", pp->p_pid, pp->p_ruid, p_i[k].pi_comm, pp->p_mach_state, p_i[k].pi_status, pp->p_flag); #endif if (pp->p_mach_state != 0) { total_procs++; process_states[pp->p_mach_state]++; if ((pp->p_mach_state != 8) && (show_idle || (pp->p_mach_pct_cpu != 0) || (pp->p_mach_state == 1)) && (!show_uid || pp->p_ruid == (uid_t)sel->uid)) { *prefp++ = pp; active_procs++; } } } } } /* if requested, sort the "interesting" processes */ if (proc_compares[compare_index] != NULL) { qsort((char *)pref, active_procs, sizeof(struct osf1_top_proc *), proc_compares[compare_index]); } /* remember active and total counts */ si->p_total = total_procs; si->p_active = pref_len = active_procs; /* pass back a handle */ handle.next_proc = pref; handle.remaining = active_procs; return((caddr_t)&handle); } char fmt[MAX_COLS]; /* static area where result is built */ char *format_next_process(handle, get_userid) caddr_t handle; char *(*get_userid)(); { register struct osf1_top_proc *pp; register long cputime; register double pct; struct user u; struct handle *hp; /* find and remember the next proc structure */ hp = (struct handle *)handle; pp = *(hp->next_proc++); hp->remaining--; /* get the process's user struct and set cputime */ if (table(TBL_UAREA,pp->p_pid,&u,1,sizeof(struct user))<0) { /* whoops, it must have died between the read of the proc area * and now. Oh well, lets just dump some meaningless thing out * to keep the rest of the program happy */ sprintf(fmt, Proc_format, pp->p_pid, (*get_userid)(pp->p_ruid), 0, 0, "", "", "dead", "", 0.0, "<dead>"); return(fmt); } /* set u_comm for system processes */ if (u.u_comm[0] == '\0') { if (pp->p_pid == 0) { (void) strcpy(u.u_comm, "[idle]"); } else if (pp->p_pid == 2) { (void) strcpy(u.u_comm, "[execpt.hndlr]"); } } /* Check if process is in core */ if (!(pp->p_flag & SLOAD)) { /* * Print swapped processes as <pname> */ char buf[sizeof(u.u_comm)]; (void) strncpy(buf, u.u_comm, sizeof(u.u_comm)); u.u_comm[0] = '<'; (void) strncpy(&u.u_comm[1], buf, sizeof(u.u_comm) - 2); u.u_comm[sizeof(u.u_comm) - 2] = '\0'; (void) strncat(u.u_comm, ">", sizeof(u.u_comm) - 1); u.u_comm[sizeof(u.u_comm) - 1] = '\0'; } cputime = u.u_ru.ru_utime.tv_sec + u.u_ru.ru_stime.tv_sec; /* calculate the base for cpu percentages */ pct = pctdouble(pp->p_mach_pct_cpu); /* format this entry */ sprintf(fmt, Proc_format, pp->p_pid, (*get_userid)(pp->p_ruid), pp->p_pri, pp->p_nice, format_k(pp->p_mach_virt_size/1024), format_k(pp->p_rssize/1000), state_abbrev[pp->p_mach_state], format_time(cputime), 100.0 * ((double)pp->p_mach_pct_cpu / 10000.0), printable(u.u_comm)); /* return the result */ return(fmt); } /* * getkval(offset, ptr, size, refstr) - get a value out of the kernel. * "offset" is the byte offset into the kernel for the desired value, * "ptr" points to a buffer into which the value is retrieved, * "size" is the size of the buffer (and the object to retrieve), * "refstr" is a reference string used when printing error meessages, * if "refstr" starts with a '!', then a failure on read will not * be fatal (this may seem like a silly way to do things, but I * really didn't want the overhead of another argument). * */ getkval(offset, ptr, size, refstr) unsigned long offset; int *ptr; int size; char *refstr; { if (lseek(kmem, (long)offset, L_SET) == -1) { if (*refstr == '!') refstr++; (void) fprintf(stderr, "%s: lseek to %s: %s\n", KMEM, refstr, strerror(errno)); quit(23); } if (read(kmem, (char *) ptr, size) == -1) { if (*refstr == '!') return(0); else { (void) fprintf(stderr, "%s: reading %s: %s\n", KMEM, refstr, strerror(errno)); quit(23); } } return(1); } /* comparison routines for qsort */ /* * There are currently four possible comparison routines. main selects * one of these by indexing in to the array proc_compares. * * Possible keys are defined as macros below. Currently these keys are * defined: percent cpu, cpu ticks, process state, resident set size, * total virtual memory usage. The process states are ordered as follows * (from least to most important): WAIT, zomb, ???, halt, idle, sleep, * stop, run. The array declaration below maps a process state index into * a number that reflects this ordering. */ /* First, the possible comparison keys. These are defined in such a way that they can be merely listed in the source code to define the actual desired ordering. */ #define ORDERKEY_PCTCPU if (lresult = p2->p_mach_pct_cpu - p1->p_mach_pct_cpu,\ (result = lresult > 0 ? 1 : lresult < 0 ? -1 : 0) == 0) #define ORDERKEY_CPTICKS if ((result = p2->used_ticks - p1->used_ticks) == 0) #define ORDERKEY_STATE if ((result = sorted_state[p2->p_mach_state] - \ sorted_state[p1->p_mach_state]) == 0) #define ORDERKEY_PRIO if ((result = p2->p_pri - p1->p_pri) == 0) #define ORDERKEY_RSSIZE if ((result = p2->p_rssize - p1->p_rssize) == 0) #define ORDERKEY_MEM if ((result = p2->p_mach_virt_size - p1->p_mach_virt_size) == 0) /* Now the array that maps process state to a weight */ static unsigned char sorted_state[] = { 0, /*""*/ 8, /*"run"*/ 1, /*"WAIT"*/ 6, /*"sleep"*/ 5, /*"idle"*/ 7, /*"stop"*/ 4, /*"halt"*/ 3, /*"???"*/ 2, /*"zomb"*/ }; /* compare_cpu - the comparison function for sorting by cpu percentage */ compare_cpu(pp1, pp2) struct osf1_top_proc **pp1; struct osf1_top_proc **pp2; { register struct osf1_top_proc *p1; register struct osf1_top_proc *p2; register long result; register pctcpu lresult; /* remove one level of indirection */ p1 = *pp1; p2 = *pp2; ORDERKEY_PCTCPU ORDERKEY_CPTICKS ORDERKEY_STATE ORDERKEY_PRIO ORDERKEY_RSSIZE ORDERKEY_MEM ; return(result); } /* compare_size - the comparison function for sorting by total memory usage */ compare_size(pp1, pp2) struct osf1_top_proc **pp1; struct osf1_top_proc **pp2; { register struct osf1_top_proc *p1; register struct osf1_top_proc *p2; register long result; register pctcpu lresult; /* remove one level of indirection */ p1 = *pp1; p2 = *pp2; ORDERKEY_MEM ORDERKEY_RSSIZE ORDERKEY_PCTCPU ORDERKEY_CPTICKS ORDERKEY_STATE ORDERKEY_PRIO ; return(result); } /* compare_res - the comparison function for sorting by resident set size */ compare_res(pp1, pp2) struct osf1_top_proc **pp1; struct osf1_top_proc **pp2; { register struct osf1_top_proc *p1; register struct osf1_top_proc *p2; register long result; register pctcpu lresult; /* remove one level of indirection */ p1 = *pp1; p2 = *pp2; ORDERKEY_RSSIZE ORDERKEY_MEM ORDERKEY_PCTCPU ORDERKEY_CPTICKS ORDERKEY_STATE ORDERKEY_PRIO ; return(result); } /* compare_time - the comparison function for sorting by total cpu time */ compare_time(pp1, pp2) struct osf1_top_proc **pp1; struct osf1_top_proc **pp2; { register struct osf1_top_proc *p1; register struct osf1_top_proc *p2; register long result; register pctcpu lresult; /* remove one level of indirection */ p1 = *pp1; p2 = *pp2; ORDERKEY_CPTICKS ORDERKEY_PCTCPU ORDERKEY_STATE ORDERKEY_PRIO ORDERKEY_RSSIZE ORDERKEY_MEM ; return(result); } /* * proc_owner(pid) - returns the uid that owns process "pid", or -1 if * the process does not exist. * It is EXTREMLY IMPORTANT that this function work correctly. * If top runs setuid root (as in SVR4), then this function * is the only thing that stands in the way of a serious * security problem. It validates requests for the "kill" * and "renice" commands. */ int proc_owner(pid) int pid; { register int cnt; register struct osf1_top_proc **prefp; register struct osf1_top_proc *pp; prefp = pref; cnt = pref_len; while (--cnt >= 0) { if ((pp = *prefp++)->p_pid == (pid_t)pid) { return((int)pp->p_ruid); } } return(-1); } /* * We use the Mach interface, as well as the table(UAREA,,,) call to * get some more information, then put it into unused fields in our * copy of the proc structure, to make it faster and easier to get at * later. */ void do_threads_calculations(thisproc) struct osf1_top_proc *thisproc; { int j; task_t thistask; task_basic_info_data_t taskinfo; unsigned int taskinfo_l; thread_array_t threadarr; unsigned int threadarr_l; thread_basic_info_t threadinfo; thread_basic_info_data_t threadinfodata; unsigned int threadinfo_l; int task_tot_cpu=0; /* total cpu usage of threads in a task */ struct user u; thisproc->p_pri=0; thisproc->p_rssize=0; thisproc->p_mach_virt_size=0; thisproc->p_mach_state=0; thisproc->p_mach_pct_cpu=0; if(task_by_unix_pid(task_self(), thisproc->p_pid, &thistask) != KERN_SUCCESS){ thisproc->p_mach_state=8; /* (zombie) */ } else { taskinfo_l=TASK_BASIC_INFO_COUNT; if(task_info(thistask, TASK_BASIC_INFO, (task_info_t) &taskinfo, &taskinfo_l) != KERN_SUCCESS) { thisproc->p_mach_state=8; /* (zombie) */ } else { int minim_state=99,mcurp=1000,mbasp=1000,mslpt=999; thisproc->p_rssize=taskinfo.resident_size; thisproc->p_mach_virt_size=taskinfo.virtual_size; if (task_threads(thistask, &threadarr, &threadarr_l) != KERN_SUCCESS) return; threadinfo= &threadinfodata; for(j=0; j < threadarr_l; j++) { threadinfo_l=THREAD_BASIC_INFO_COUNT; if(thread_info(threadarr[j],THREAD_BASIC_INFO, (thread_info_t) threadinfo, &threadinfo_l) == KERN_SUCCESS) { task_tot_cpu += threadinfo->cpu_usage; if(minim_state>threadinfo->run_state) minim_state=threadinfo->run_state; if(mcurp>threadinfo->cur_priority) mcurp=threadinfo->cur_priority; if(mbasp>threadinfo->base_priority) mbasp=threadinfo->base_priority; if(mslpt>threadinfo->sleep_time) mslpt=threadinfo->sleep_time; } } switch (minim_state) { case TH_STATE_RUNNING: thisproc->p_mach_state=1; break; case TH_STATE_UNINTERRUPTIBLE: thisproc->p_mach_state=2; break; case TH_STATE_WAITING: thisproc->p_mach_state=(threadinfo->sleep_time > 20) ? 4 : 3; break; case TH_STATE_STOPPED: thisproc->p_mach_state=5; break; case TH_STATE_HALTED: thisproc->p_mach_state=6; break; default: thisproc->p_mach_state=7; break; } thisproc->p_pri=mcurp; thisproc->p_mach_pct_cpu=(fixpt_t)(task_tot_cpu*10); vm_deallocate(task_self(),(vm_address_t)threadarr,threadarr_l); } } if (table(TBL_UAREA,thisproc->p_pid,&u,1,sizeof(struct user))>=0) { thisproc->used_ticks=(u.u_ru.ru_utime.tv_sec + u.u_ru.ru_stime.tv_sec); thisproc->process_size=u.u_tsize + u.u_dsize + u.u_ssize; } } /* The reason for this function is that the system call will let * someone lower their own processes priority (because top is setuid :-( * Yes, using syscall() is a hack, if you can come up with something * better, then I'd be thrilled to hear it. I'm not holding my breath, * though. * Anthony. */ int setpriority(int dummy, int procnum, int niceval) { int uid, curprio; uid=getuid(); if ( (curprio=getpriority(PRIO_PROCESS,procnum) ) == -1) { return(-1); /* errno goes back to renice_process() */ } /* check for not-root - if so, dont allow users to decrease priority */ else if ( uid && (niceval<curprio) ) { errno=EACCES; return(-1); } return(syscall(SYS_setpriority,PRIO_PROCESS,procnum,niceval)); }
879450.c
/* * Copyright (c) 2007-2015 Nicira, Inc. * * This program is free software; you can redistribute it and/or * modify it under the terms of version 2 of the GNU General Public * License as published by the Free Software Foundation. * * 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 <linux/uaccess.h> #include <linux/netdevice.h> #include <linux/etherdevice.h> #include <linux/if_ether.h> #include <linux/if_vlan.h> #include <net/llc_pdu.h> #include <linux/kernel.h> #include <linux/jhash.h> #include <linux/jiffies.h> #include <linux/llc.h> #include <linux/module.h> #include <linux/in.h> #include <linux/rcupdate.h> #include <linux/cpumask.h> #include <linux/if_arp.h> #include <linux/ip.h> #include <linux/ipv6.h> #include <linux/mpls.h> #include <linux/sctp.h> #include <linux/smp.h> #include <linux/tcp.h> #include <linux/udp.h> #include <linux/icmp.h> #include <linux/icmpv6.h> #include <linux/rculist.h> #include <linux/timekeeping.h> #include <net/ip.h> #include <net/ipv6.h> #include <net/mpls.h> #include <net/ndisc.h> #include <net/nsh.h> #include "datapath.h" #include "conntrack.h" #include "flow.h" #include "flow_netlink.h" #include "vport.h" u64 ovs_flow_used_time(unsigned long flow_jiffies) { struct timespec64 cur_ts; u64 cur_ms, idle_ms; ktime_get_ts64(&cur_ts); idle_ms = jiffies_to_msecs(jiffies - flow_jiffies); cur_ms = (u64)(u32)cur_ts.tv_sec * MSEC_PER_SEC + cur_ts.tv_nsec / NSEC_PER_MSEC; return cur_ms - idle_ms; } #define TCP_FLAGS_BE16(tp) (*(__be16 *)&tcp_flag_word(tp) & htons(0x0FFF)) void ovs_flow_stats_update(struct sw_flow *flow, __be16 tcp_flags, const struct sk_buff *skb) { struct flow_stats *stats; unsigned int cpu = smp_processor_id(); int len = skb->len + (skb_vlan_tag_present(skb) ? VLAN_HLEN : 0); stats = rcu_dereference(flow->stats[cpu]); /* Check if already have CPU-specific stats. */ if (likely(stats)) { spin_lock(&stats->lock); /* Mark if we write on the pre-allocated stats. */ if (cpu == 0 && unlikely(flow->stats_last_writer != cpu)) flow->stats_last_writer = cpu; } else { stats = rcu_dereference(flow->stats[0]); /* Pre-allocated. */ spin_lock(&stats->lock); /* If the current CPU is the only writer on the * pre-allocated stats keep using them. */ if (unlikely(flow->stats_last_writer != cpu)) { /* A previous locker may have already allocated the * stats, so we need to check again. If CPU-specific * stats were already allocated, we update the pre- * allocated stats as we have already locked them. */ if (likely(flow->stats_last_writer != -1) && likely(!rcu_access_pointer(flow->stats[cpu]))) { /* Try to allocate CPU-specific stats. */ struct flow_stats *new_stats; new_stats = kmem_cache_alloc_node(flow_stats_cache, GFP_NOWAIT | __GFP_THISNODE | __GFP_NOWARN | __GFP_NOMEMALLOC, numa_node_id()); if (likely(new_stats)) { new_stats->used = jiffies; new_stats->packet_count = 1; new_stats->byte_count = len; new_stats->tcp_flags = tcp_flags; spin_lock_init(&new_stats->lock); rcu_assign_pointer(flow->stats[cpu], new_stats); cpumask_set_cpu(cpu, &flow->cpu_used_mask); goto unlock; } } flow->stats_last_writer = cpu; } } stats->used = jiffies; stats->packet_count++; stats->byte_count += len; stats->tcp_flags |= tcp_flags; unlock: spin_unlock(&stats->lock); } /* Must be called with rcu_read_lock or ovs_mutex. */ void ovs_flow_stats_get(const struct sw_flow *flow, struct ovs_flow_stats *ovs_stats, unsigned long *used, __be16 *tcp_flags) { int cpu; *used = 0; *tcp_flags = 0; memset(ovs_stats, 0, sizeof(*ovs_stats)); /* We open code this to make sure cpu 0 is always considered */ for (cpu = 0; cpu < nr_cpu_ids; cpu = cpumask_next(cpu, &flow->cpu_used_mask)) { struct flow_stats *stats = rcu_dereference_ovsl(flow->stats[cpu]); if (stats) { /* Local CPU may write on non-local stats, so we must * block bottom-halves here. */ spin_lock_bh(&stats->lock); if (!*used || time_after(stats->used, *used)) *used = stats->used; *tcp_flags |= stats->tcp_flags; ovs_stats->n_packets += stats->packet_count; ovs_stats->n_bytes += stats->byte_count; spin_unlock_bh(&stats->lock); } } } /* Called with ovs_mutex. */ void ovs_flow_stats_clear(struct sw_flow *flow) { int cpu; /* We open code this to make sure cpu 0 is always considered */ for (cpu = 0; cpu < nr_cpu_ids; cpu = cpumask_next(cpu, &flow->cpu_used_mask)) { struct flow_stats *stats = ovsl_dereference(flow->stats[cpu]); if (stats) { spin_lock_bh(&stats->lock); stats->used = 0; stats->packet_count = 0; stats->byte_count = 0; stats->tcp_flags = 0; spin_unlock_bh(&stats->lock); } } } static int check_header(struct sk_buff *skb, int len) { if (unlikely(skb->len < len)) return -EINVAL; if (unlikely(!pskb_may_pull(skb, len))) return -ENOMEM; return 0; } static bool arphdr_ok(struct sk_buff *skb) { return pskb_may_pull(skb, skb_network_offset(skb) + sizeof(struct arp_eth_header)); } static int check_iphdr(struct sk_buff *skb) { unsigned int nh_ofs = skb_network_offset(skb); unsigned int ip_len; int err; err = check_header(skb, nh_ofs + sizeof(struct iphdr)); if (unlikely(err)) return err; ip_len = ip_hdrlen(skb); if (unlikely(ip_len < sizeof(struct iphdr) || skb->len < nh_ofs + ip_len)) return -EINVAL; skb_set_transport_header(skb, nh_ofs + ip_len); return 0; } static bool tcphdr_ok(struct sk_buff *skb) { int th_ofs = skb_transport_offset(skb); int tcp_len; if (unlikely(!pskb_may_pull(skb, th_ofs + sizeof(struct tcphdr)))) return false; tcp_len = tcp_hdrlen(skb); if (unlikely(tcp_len < sizeof(struct tcphdr) || skb->len < th_ofs + tcp_len)) return false; return true; } static bool udphdr_ok(struct sk_buff *skb) { return pskb_may_pull(skb, skb_transport_offset(skb) + sizeof(struct udphdr)); } static bool sctphdr_ok(struct sk_buff *skb) { return pskb_may_pull(skb, skb_transport_offset(skb) + sizeof(struct sctphdr)); } static bool icmphdr_ok(struct sk_buff *skb) { return pskb_may_pull(skb, skb_transport_offset(skb) + sizeof(struct icmphdr)); } static int parse_ipv6hdr(struct sk_buff *skb, struct sw_flow_key *key) { unsigned short frag_off; unsigned int payload_ofs = 0; unsigned int nh_ofs = skb_network_offset(skb); unsigned int nh_len; struct ipv6hdr *nh; int err, nexthdr, flags = 0; err = check_header(skb, nh_ofs + sizeof(*nh)); if (unlikely(err)) return err; nh = ipv6_hdr(skb); key->ip.proto = NEXTHDR_NONE; key->ip.tos = ipv6_get_dsfield(nh); key->ip.ttl = nh->hop_limit; key->ipv6.label = *(__be32 *)nh & htonl(IPV6_FLOWINFO_FLOWLABEL); key->ipv6.addr.src = nh->saddr; key->ipv6.addr.dst = nh->daddr; nexthdr = ipv6_find_hdr(skb, &payload_ofs, -1, &frag_off, &flags); if (flags & IP6_FH_F_FRAG) { if (frag_off) { key->ip.frag = OVS_FRAG_TYPE_LATER; key->ip.proto = nexthdr; return 0; } key->ip.frag = OVS_FRAG_TYPE_FIRST; } else { key->ip.frag = OVS_FRAG_TYPE_NONE; } /* Delayed handling of error in ipv6_find_hdr() as it * always sets flags and frag_off to a valid value which may be * used to set key->ip.frag above. */ if (unlikely(nexthdr < 0)) return -EPROTO; nh_len = payload_ofs - nh_ofs; skb_set_transport_header(skb, nh_ofs + nh_len); key->ip.proto = nexthdr; return nh_len; } static bool icmp6hdr_ok(struct sk_buff *skb) { return pskb_may_pull(skb, skb_transport_offset(skb) + sizeof(struct icmp6hdr)); } /** * Parse vlan tag from vlan header. * Returns ERROR on memory error. * Returns 0 if it encounters a non-vlan or incomplete packet. * Returns 1 after successfully parsing vlan tag. */ static int parse_vlan_tag(struct sk_buff *skb, struct vlan_head *key_vh, bool untag_vlan) { struct vlan_head *vh = (struct vlan_head *)skb->data; if (likely(!eth_type_vlan(vh->tpid))) return 0; if (unlikely(skb->len < sizeof(struct vlan_head) + sizeof(__be16))) return 0; if (unlikely(!pskb_may_pull(skb, sizeof(struct vlan_head) + sizeof(__be16)))) return -ENOMEM; vh = (struct vlan_head *)skb->data; key_vh->tci = vh->tci | htons(VLAN_CFI_MASK); key_vh->tpid = vh->tpid; if (unlikely(untag_vlan)) { int offset = skb->data - skb_mac_header(skb); u16 tci; int err; __skb_push(skb, offset); err = __skb_vlan_pop(skb, &tci); __skb_pull(skb, offset); if (err) return err; __vlan_hwaccel_put_tag(skb, key_vh->tpid, tci); } else { __skb_pull(skb, sizeof(struct vlan_head)); } return 1; } static void clear_vlan(struct sw_flow_key *key) { key->eth.vlan.tci = 0; key->eth.vlan.tpid = 0; key->eth.cvlan.tci = 0; key->eth.cvlan.tpid = 0; } static int parse_vlan(struct sk_buff *skb, struct sw_flow_key *key) { int res; key->eth.vlan.tci = 0; key->eth.vlan.tpid = 0; key->eth.cvlan.tci = 0; key->eth.cvlan.tpid = 0; if (skb_vlan_tag_present(skb)) { key->eth.vlan.tci = htons(skb->vlan_tci) | htons(VLAN_CFI_MASK); key->eth.vlan.tpid = skb->vlan_proto; } else { /* Parse outer vlan tag in the non-accelerated case. */ res = parse_vlan_tag(skb, &key->eth.vlan, true); if (res <= 0) return res; } /* Parse inner vlan tag. */ res = parse_vlan_tag(skb, &key->eth.cvlan, false); if (res <= 0) return res; return 0; } static __be16 parse_ethertype(struct sk_buff *skb) { struct llc_snap_hdr { u8 dsap; /* Always 0xAA */ u8 ssap; /* Always 0xAA */ u8 ctrl; u8 oui[3]; __be16 ethertype; }; struct llc_snap_hdr *llc; __be16 proto; proto = *(__be16 *) skb->data; __skb_pull(skb, sizeof(__be16)); if (eth_proto_is_802_3(proto)) return proto; if (skb->len < sizeof(struct llc_snap_hdr)) return htons(ETH_P_802_2); if (unlikely(!pskb_may_pull(skb, sizeof(struct llc_snap_hdr)))) return htons(0); llc = (struct llc_snap_hdr *) skb->data; if (llc->dsap != LLC_SAP_SNAP || llc->ssap != LLC_SAP_SNAP || (llc->oui[0] | llc->oui[1] | llc->oui[2]) != 0) return htons(ETH_P_802_2); __skb_pull(skb, sizeof(struct llc_snap_hdr)); if (eth_proto_is_802_3(llc->ethertype)) return llc->ethertype; return htons(ETH_P_802_2); } static int parse_icmpv6(struct sk_buff *skb, struct sw_flow_key *key, int nh_len) { struct icmp6hdr *icmp = icmp6_hdr(skb); /* The ICMPv6 type and code fields use the 16-bit transport port * fields, so we need to store them in 16-bit network byte order. */ key->tp.src = htons(icmp->icmp6_type); key->tp.dst = htons(icmp->icmp6_code); memset(&key->ipv6.nd, 0, sizeof(key->ipv6.nd)); if (icmp->icmp6_code == 0 && (icmp->icmp6_type == NDISC_NEIGHBOUR_SOLICITATION || icmp->icmp6_type == NDISC_NEIGHBOUR_ADVERTISEMENT)) { int icmp_len = skb->len - skb_transport_offset(skb); struct nd_msg *nd; int offset; /* In order to process neighbor discovery options, we need the * entire packet. */ if (unlikely(icmp_len < sizeof(*nd))) return 0; if (unlikely(skb_linearize(skb))) return -ENOMEM; nd = (struct nd_msg *)skb_transport_header(skb); key->ipv6.nd.target = nd->target; icmp_len -= sizeof(*nd); offset = 0; while (icmp_len >= 8) { struct nd_opt_hdr *nd_opt = (struct nd_opt_hdr *)(nd->opt + offset); int opt_len = nd_opt->nd_opt_len * 8; if (unlikely(!opt_len || opt_len > icmp_len)) return 0; /* Store the link layer address if the appropriate * option is provided. It is considered an error if * the same link layer option is specified twice. */ if (nd_opt->nd_opt_type == ND_OPT_SOURCE_LL_ADDR && opt_len == 8) { if (unlikely(!is_zero_ether_addr(key->ipv6.nd.sll))) goto invalid; ether_addr_copy(key->ipv6.nd.sll, &nd->opt[offset+sizeof(*nd_opt)]); } else if (nd_opt->nd_opt_type == ND_OPT_TARGET_LL_ADDR && opt_len == 8) { if (unlikely(!is_zero_ether_addr(key->ipv6.nd.tll))) goto invalid; ether_addr_copy(key->ipv6.nd.tll, &nd->opt[offset+sizeof(*nd_opt)]); } icmp_len -= opt_len; offset += opt_len; } } return 0; invalid: memset(&key->ipv6.nd.target, 0, sizeof(key->ipv6.nd.target)); memset(key->ipv6.nd.sll, 0, sizeof(key->ipv6.nd.sll)); memset(key->ipv6.nd.tll, 0, sizeof(key->ipv6.nd.tll)); return 0; } static int parse_nsh(struct sk_buff *skb, struct sw_flow_key *key) { struct nshhdr *nh; unsigned int nh_ofs = skb_network_offset(skb); u8 version, length; int err; err = check_header(skb, nh_ofs + NSH_BASE_HDR_LEN); if (unlikely(err)) return err; nh = nsh_hdr(skb); version = nsh_get_ver(nh); length = nsh_hdr_len(nh); if (version != 0) return -EINVAL; err = check_header(skb, nh_ofs + length); if (unlikely(err)) return err; nh = nsh_hdr(skb); key->nsh.base.flags = nsh_get_flags(nh); key->nsh.base.ttl = nsh_get_ttl(nh); key->nsh.base.mdtype = nh->mdtype; key->nsh.base.np = nh->np; key->nsh.base.path_hdr = nh->path_hdr; switch (key->nsh.base.mdtype) { case NSH_M_TYPE1: if (length != NSH_M_TYPE1_LEN) return -EINVAL; memcpy(key->nsh.context, nh->md1.context, sizeof(nh->md1)); break; case NSH_M_TYPE2: memset(key->nsh.context, 0, sizeof(nh->md1)); break; default: return -EINVAL; } return 0; } /** * key_extract_l3l4 - extracts L3/L4 header information. * @skb: sk_buff that contains the frame, with skb->data pointing to the * L3 header * @key: output flow key */ static int key_extract_l3l4(struct sk_buff *skb, struct sw_flow_key *key) { int error; /* Network layer. */ if (key->eth.type == htons(ETH_P_IP)) { struct iphdr *nh; __be16 offset; error = check_iphdr(skb); if (unlikely(error)) { memset(&key->ip, 0, sizeof(key->ip)); memset(&key->ipv4, 0, sizeof(key->ipv4)); if (error == -EINVAL) { skb->transport_header = skb->network_header; error = 0; } return error; } nh = ip_hdr(skb); key->ipv4.addr.src = nh->saddr; key->ipv4.addr.dst = nh->daddr; key->ip.proto = nh->protocol; key->ip.tos = nh->tos; key->ip.ttl = nh->ttl; offset = nh->frag_off & htons(IP_OFFSET); if (offset) { key->ip.frag = OVS_FRAG_TYPE_LATER; memset(&key->tp, 0, sizeof(key->tp)); return 0; } #ifdef HAVE_SKB_GSO_UDP if (nh->frag_off & htons(IP_MF) || skb_shinfo(skb)->gso_type & SKB_GSO_UDP) #else if (nh->frag_off & htons(IP_MF)) #endif key->ip.frag = OVS_FRAG_TYPE_FIRST; else key->ip.frag = OVS_FRAG_TYPE_NONE; /* Transport layer. */ if (key->ip.proto == IPPROTO_TCP) { if (tcphdr_ok(skb)) { struct tcphdr *tcp = tcp_hdr(skb); key->tp.src = tcp->source; key->tp.dst = tcp->dest; key->tp.flags = TCP_FLAGS_BE16(tcp); } else { memset(&key->tp, 0, sizeof(key->tp)); } } else if (key->ip.proto == IPPROTO_UDP) { if (udphdr_ok(skb)) { struct udphdr *udp = udp_hdr(skb); key->tp.src = udp->source; key->tp.dst = udp->dest; } else { memset(&key->tp, 0, sizeof(key->tp)); } } else if (key->ip.proto == IPPROTO_SCTP) { if (sctphdr_ok(skb)) { struct sctphdr *sctp = sctp_hdr(skb); key->tp.src = sctp->source; key->tp.dst = sctp->dest; } else { memset(&key->tp, 0, sizeof(key->tp)); } } else if (key->ip.proto == IPPROTO_ICMP) { if (icmphdr_ok(skb)) { struct icmphdr *icmp = icmp_hdr(skb); /* The ICMP type and code fields use the 16-bit * transport port fields, so we need to store * them in 16-bit network byte order. */ key->tp.src = htons(icmp->type); key->tp.dst = htons(icmp->code); } else { memset(&key->tp, 0, sizeof(key->tp)); } } } else if (key->eth.type == htons(ETH_P_ARP) || key->eth.type == htons(ETH_P_RARP)) { struct arp_eth_header *arp; bool arp_available = arphdr_ok(skb); arp = (struct arp_eth_header *)skb_network_header(skb); if (arp_available && arp->ar_hrd == htons(ARPHRD_ETHER) && arp->ar_pro == htons(ETH_P_IP) && arp->ar_hln == ETH_ALEN && arp->ar_pln == 4) { /* We only match on the lower 8 bits of the opcode. */ if (ntohs(arp->ar_op) <= 0xff) key->ip.proto = ntohs(arp->ar_op); else key->ip.proto = 0; memcpy(&key->ipv4.addr.src, arp->ar_sip, sizeof(key->ipv4.addr.src)); memcpy(&key->ipv4.addr.dst, arp->ar_tip, sizeof(key->ipv4.addr.dst)); ether_addr_copy(key->ipv4.arp.sha, arp->ar_sha); ether_addr_copy(key->ipv4.arp.tha, arp->ar_tha); } else { memset(&key->ip, 0, sizeof(key->ip)); memset(&key->ipv4, 0, sizeof(key->ipv4)); } } else if (eth_p_mpls(key->eth.type)) { size_t stack_len = MPLS_HLEN; skb_set_inner_network_header(skb, skb->mac_len); while (1) { __be32 lse; error = check_header(skb, skb->mac_len + stack_len); if (unlikely(error)) return 0; memcpy(&lse, skb_inner_network_header(skb), MPLS_HLEN); if (stack_len == MPLS_HLEN) memcpy(&key->mpls.top_lse, &lse, MPLS_HLEN); skb_set_inner_network_header(skb, skb->mac_len + stack_len); if (lse & htonl(MPLS_LS_S_MASK)) break; stack_len += MPLS_HLEN; } } else if (key->eth.type == htons(ETH_P_IPV6)) { int nh_len; /* IPv6 Header + Extensions */ nh_len = parse_ipv6hdr(skb, key); if (unlikely(nh_len < 0)) { switch (nh_len) { case -EINVAL: memset(&key->ip, 0, sizeof(key->ip)); memset(&key->ipv6.addr, 0, sizeof(key->ipv6.addr)); /* fall-through */ case -EPROTO: skb->transport_header = skb->network_header; error = 0; break; default: error = nh_len; } return error; } if (key->ip.frag == OVS_FRAG_TYPE_LATER) { memset(&key->tp, 0, sizeof(key->tp)); return 0; } #ifdef HAVE_SKB_GSO_UDP if (skb_shinfo(skb)->gso_type & SKB_GSO_UDP) key->ip.frag = OVS_FRAG_TYPE_FIRST; #endif /* Transport layer. */ if (key->ip.proto == NEXTHDR_TCP) { if (tcphdr_ok(skb)) { struct tcphdr *tcp = tcp_hdr(skb); key->tp.src = tcp->source; key->tp.dst = tcp->dest; key->tp.flags = TCP_FLAGS_BE16(tcp); } else { memset(&key->tp, 0, sizeof(key->tp)); } } else if (key->ip.proto == NEXTHDR_UDP) { if (udphdr_ok(skb)) { struct udphdr *udp = udp_hdr(skb); key->tp.src = udp->source; key->tp.dst = udp->dest; } else { memset(&key->tp, 0, sizeof(key->tp)); } } else if (key->ip.proto == NEXTHDR_SCTP) { if (sctphdr_ok(skb)) { struct sctphdr *sctp = sctp_hdr(skb); key->tp.src = sctp->source; key->tp.dst = sctp->dest; } else { memset(&key->tp, 0, sizeof(key->tp)); } } else if (key->ip.proto == NEXTHDR_ICMP) { if (icmp6hdr_ok(skb)) { error = parse_icmpv6(skb, key, nh_len); if (error) return error; } else { memset(&key->tp, 0, sizeof(key->tp)); } } } else if (key->eth.type == htons(ETH_P_NSH)) { error = parse_nsh(skb, key); if (error) return error; } return 0; } /** * key_extract - extracts a flow key from an Ethernet frame. * @skb: sk_buff that contains the frame, with skb->data pointing to the * Ethernet header * @key: output flow key * * The caller must ensure that skb->len >= ETH_HLEN. * * Returns 0 if successful, otherwise a negative errno value. * * Initializes @skb header fields as follows: * * - skb->mac_header: the L2 header. * * - skb->network_header: just past the L2 header, or just past the * VLAN header, to the first byte of the L2 payload. * * - skb->transport_header: If key->eth.type is ETH_P_IP or ETH_P_IPV6 * on output, then just past the IP header, if one is present and * of a correct length, otherwise the same as skb->network_header. * For other key->eth.type values it is left untouched. * * - skb->protocol: the type of the data starting at skb->network_header. * Equals to key->eth.type. */ static int key_extract(struct sk_buff *skb, struct sw_flow_key *key) { struct ethhdr *eth; /* Flags are always used as part of stats */ key->tp.flags = 0; skb_reset_mac_header(skb); /* Link layer. */ clear_vlan(key); if (ovs_key_mac_proto(key) == MAC_PROTO_NONE) { if (unlikely(eth_type_vlan(skb->protocol))) return -EINVAL; skb_reset_network_header(skb); key->eth.type = skb->protocol; } else { eth = eth_hdr(skb); ether_addr_copy(key->eth.src, eth->h_source); ether_addr_copy(key->eth.dst, eth->h_dest); __skb_pull(skb, 2 * ETH_ALEN); /* We are going to push all headers that we pull, so no need to * update skb->csum here. */ if (unlikely(parse_vlan(skb, key))) return -ENOMEM; key->eth.type = parse_ethertype(skb); if (unlikely(key->eth.type == htons(0))) return -ENOMEM; /* Multiple tagged packets need to retain TPID to satisfy * skb_vlan_pop(), which will later shift the ethertype into * skb->protocol. */ if (key->eth.cvlan.tci & htons(VLAN_CFI_MASK)) skb->protocol = key->eth.cvlan.tpid; else skb->protocol = key->eth.type; skb_reset_network_header(skb); __skb_push(skb, skb->data - skb_mac_header(skb)); } skb_reset_mac_len(skb); /* Fill out L3/L4 key info, if any */ return key_extract_l3l4(skb, key); } /* In the case of conntrack fragment handling it expects L3 headers, * add a helper. */ int ovs_flow_key_update_l3l4(struct sk_buff *skb, struct sw_flow_key *key) { return key_extract_l3l4(skb, key); } int ovs_flow_key_update(struct sk_buff *skb, struct sw_flow_key *key) { int res; res = key_extract(skb, key); if (!res) key->mac_proto &= ~SW_FLOW_KEY_INVALID; return res; } static int key_extract_mac_proto(struct sk_buff *skb) { switch (skb->dev->type) { case ARPHRD_ETHER: return MAC_PROTO_ETHERNET; case ARPHRD_NONE: if (skb->protocol == htons(ETH_P_TEB)) return MAC_PROTO_ETHERNET; return MAC_PROTO_NONE; } WARN_ON_ONCE(1); return -EINVAL; } int ovs_flow_key_extract(const struct ip_tunnel_info *tun_info, struct sk_buff *skb, struct sw_flow_key *key) { int res, err; /* Extract metadata from packet. */ if (tun_info) { key->tun_proto = ip_tunnel_info_af(tun_info); memcpy(&key->tun_key, &tun_info->key, sizeof(key->tun_key)); BUILD_BUG_ON(((1 << (sizeof(tun_info->options_len) * 8)) - 1) > sizeof(key->tun_opts)); if (tun_info->options_len) { ip_tunnel_info_opts_get(TUN_METADATA_OPTS(key, tun_info->options_len), tun_info); key->tun_opts_len = tun_info->options_len; } else { key->tun_opts_len = 0; } } else { key->tun_proto = 0; key->tun_opts_len = 0; memset(&key->tun_key, 0, sizeof(key->tun_key)); } key->phy.priority = skb->priority; key->phy.in_port = OVS_CB(skb)->input_vport->port_no; key->phy.skb_mark = skb->mark; key->ovs_flow_hash = 0; res = key_extract_mac_proto(skb); if (res < 0) return res; key->mac_proto = res; key->recirc_id = 0; err = key_extract(skb, key); if (!err) ovs_ct_fill_key(skb, key); /* Must be after key_extract(). */ return err; } int ovs_flow_key_extract_userspace(struct net *net, const struct nlattr *attr, struct sk_buff *skb, struct sw_flow_key *key, bool log) { const struct nlattr *a[OVS_KEY_ATTR_MAX + 1]; u64 attrs = 0; int err; err = parse_flow_nlattrs(attr, a, &attrs, log); if (err) return -EINVAL; /* Extract metadata from netlink attributes. */ err = ovs_nla_get_flow_metadata(net, a, attrs, key, log); if (err) return err; /* key_extract assumes that skb->protocol is set-up for * layer 3 packets which is the case for other callers, * in particular packets received from the network stack. * Here the correct value can be set from the metadata * extracted above. * For L2 packet key eth type would be zero. skb protocol * would be set to correct value later during key-extact. */ skb->protocol = key->eth.type; err = key_extract(skb, key); if (err) return err; /* Check that we have conntrack original direction tuple metadata only * for packets for which it makes sense. Otherwise the key may be * corrupted due to overlapping key fields. */ if (attrs & (1 << OVS_KEY_ATTR_CT_ORIG_TUPLE_IPV4) && key->eth.type != htons(ETH_P_IP)) return -EINVAL; if (attrs & (1 << OVS_KEY_ATTR_CT_ORIG_TUPLE_IPV6) && (key->eth.type != htons(ETH_P_IPV6) || sw_flow_key_is_nd(key))) return -EINVAL; return 0; }
645749.c
/**************************************************************************/ /* */ /* OCaml */ /* */ /* Xavier Leroy, projet Cristal, INRIA Rocquencourt */ /* */ /* Copyright 1996 Institut National de Recherche en Informatique et */ /* en Automatique. */ /* */ /* All rights reserved. This file is distributed under the terms of */ /* the GNU Lesser General Public License version 2.1, with the */ /* special exception on linking described in the file LICENSE. */ /* */ /**************************************************************************/ #include <caml/fail.h> #include <caml/mlvalues.h> #include <caml/signals.h> #include "unixsupport.h" #ifdef HAS_SOCKETS #include "socketaddr.h" CAMLprim value unix_connect(value socket, value address) { int retcode; union sock_addr_union addr; socklen_param_type addr_len; get_sockaddr(address, &addr, &addr_len); caml_enter_blocking_section(); retcode = connect(Int_val(socket), &addr.s_gen, addr_len); caml_leave_blocking_section(); if (retcode == -1) uerror("connect", Nothing); return Val_unit; } #else CAMLprim value unix_connect(value socket, value address) { caml_invalid_argument("connect not implemented"); } #endif
990163.c
/********** write_text_char.c write a text file from an integer array arguments: char out_array[][]: array to write to file int out_length: length of array to write to file char *out_name: name of output file args_struct in_args: the input argument structure return value: integer error code: OK = 0, otherwise a non-zero error code Created by Alan Di Vittorio on 6 Sep 2013 Moirai Land Data System (Moirai) Copyright (c) 2019, The Regents of the University of California, through Lawrence Berkeley National Laboratory (subject to receipt of any required approvals from the U.S. Dept. of Energy). All rights reserved. If you have questions about your rights to use or distribute this software, please contact Berkeley Lab's Intellectual Property Office at [email protected]. NOTICE. This Software was developed under funding from the U.S. Department of Energy and the U.S. Government consequently retains certain rights. As such, the U.S. Government has been granted for itself and others acting on its behalf a paid-up, nonexclusive, irrevocable, worldwide license in the Software to reproduce, distribute copies to the public, prepare derivative works, and perform publicly and display publicly, and to permit other to do so. This file is part of Moirai. Moirai is free software: you can use it under the terms of the modified BSD-3 license (see …/moirai/license.txt) **********/ #include "moirai.h" //int write_text_char(char out_array[][MAXCHAR], int out_length, char *out_name, args_struct in_args) { int write_text_char(char **out_array, int out_length, char *out_name, args_struct in_args) { int i; char fname[MAXCHAR]; // file name to open FILE *fpout; // file pointer // create file name and open it strcpy(fname, in_args.outpath); strcat(fname, out_name); if((fpout = fopen(fname, "w")) == NULL) { fprintf(fplog,"Failed to open file %s: write_text_char()\n", fname); return ERROR_FILE; } for (i = 0; i < out_length; i++) { fprintf(fpout,"%s\n", &out_array[i][0]); } fclose(fpout); if(i != out_length) { fprintf(fplog, "Error writing file %s: write_text_char(); records written=%i != out_length=%i\n", fname, i, out_length); return ERROR_FILE; } return OK;}
123988.c
/* cairo - a vector graphics library with display and print output * * Copyright © 2003 University of Southern California * * This library is free software; you can redistribute it and/or * modify it either under the terms of the GNU Lesser General Public * License version 2.1 as published by the Free Software Foundation * (the "LGPL") or, at your option, under the terms of the Mozilla * Public License Version 1.1 (the "MPL"). If you do not alter this * notice, a recipient may use your version of this file under either * the MPL or the LGPL. * * You should have received a copy of the LGPL along with this library * in the file COPYING-LGPL-2.1; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Suite 500, Boston, MA 02110-1335, USA * You should have received a copy of the MPL along with this library * in the file COPYING-MPL-1.1 * * The contents of this file are subject to the Mozilla Public License * Version 1.1 (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.mozilla.org/MPL/ * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY * OF ANY KIND, either express or implied. See the LGPL or the MPL for * the specific language governing rights and limitations. * * The Original Code is the cairo graphics library. * * The Initial Developer of the Original Code is University of Southern * California. * * Contributor(s): * Michael Emmel <[email protected]> * Claudio Ciccani <[email protected]> */ #include "cairoint.h" #include "cairo-directfb.h" #include "cairo-clip-private.h" #include "cairo-error-private.h" #include <pixman.h> #include <directfb.h> #include <direct/types.h> #include <direct/debug.h> #include <direct/memcpy.h> #include <direct/util.h> /* * Rectangle works fine. * Bugs 361377, 359553, 359243 in Gnome BTS are caused * by GDK/DirectFB, not by Cairo/DirectFB. */ #define DFB_RECTANGLES 1 /* * Composite works fine. */ #define DFB_COMPOSITE 1 /* * CompositeTrapezoids works (without antialiasing). */ #define DFB_COMPOSITE_TRAPEZOIDS 1 /* * ShowGlyphs works fine. */ #define DFB_SHOW_GLYPHS 1 #define PIXMAN_invalid (pixman_format_code_t) 0 D_DEBUG_DOMAIN (CairoDFB_Acquire, "CairoDFB/Acquire", "Cairo DirectFB Acquire"); D_DEBUG_DOMAIN (CairoDFB_Clip, "CairoDFB/Clip", "Cairo DirectFB Clipping"); D_DEBUG_DOMAIN (CairoDFB_Font, "CairoDFB/Font", "Cairo DirectFB Font Rendering"); D_DEBUG_DOMAIN (CairoDFB_Render, "CairoDFB/Render", "Cairo DirectFB Rendering"); D_DEBUG_DOMAIN (CairoDFB_Surface, "CairoDFB/Surface", "Cairo DirectFB Surface"); /*****************************************************************************/ typedef struct _cairo_directfb_surface { cairo_surface_t base; pixman_format_code_t pixman_format; cairo_bool_t supported_destination; IDirectFB *dfb; IDirectFBSurface *dfbsurface; IDirectFBSurface *tmpsurface; pixman_format_code_t tmpformat; int width; int height; unsigned local : 1; unsigned blit_premultiplied : 1; } cairo_directfb_surface_t; typedef struct _cairo_directfb_font_cache { IDirectFB *dfb; IDirectFBSurface *dfbsurface; int width; int height; /* coordinates within the surface * of the last loaded glyph */ int x; int y; } cairo_directfb_font_cache_t; static cairo_surface_backend_t _cairo_directfb_surface_backend; /*****************************************************************************/ static int _directfb_argb_font = 0; /*****************************************************************************/ #define RUN_CLIPPED(surface, clip_region, clip, func) {\ if ((clip_region) != NULL) {\ int n_clips = cairo_region_num_rectangles (clip_region), n; \ for (n = 0; n < n_clips; n++) {\ if (clip) {\ DFBRegion reg, *cli = (clip); \ cairo_rectangle_int_t rect; \ cairo_region_get_rectangle (clip_region, n, &rect); \ reg.x1 = rect.x; \ reg.y1 = rect.y; \ reg.x2 = rect.x + rect.width - 1; \ reg.y2 = rect.y + rect.height - 1; \ if (reg.x2 < cli->x1 || reg.y2 < cli->y1 ||\ reg.x1 > cli->x2 || reg.y1 > cli->y2)\ continue;\ if (reg.x1 < cli->x1)\ reg.x1 = cli->x1;\ if (reg.y1 < cli->y1)\ reg.y1 = cli->y1;\ if (reg.x2 > cli->x2)\ reg.x2 = cli->x2;\ if (reg.y2 > cli->y2)\ reg.y2 = cli->y2;\ (surface)->dfbsurface->SetClip ((surface)->dfbsurface, &reg);\ } else {\ DFBRegion reg; \ cairo_rectangle_int_t rect; \ cairo_region_get_rectangle (clip_region, n, &rect); \ reg.x1 = rect.x; \ reg.y1 = rect.y; \ reg.x2 = rect.x + rect.width - 1; \ reg.y2 = rect.y + rect.height - 1; \ (surface)->dfbsurface->SetClip ((surface)->dfbsurface, &reg); \ }\ func;\ }\ } else {\ (surface)->dfbsurface->SetClip ((surface)->dfbsurface, clip);\ func;\ }\ } #define TRANSFORM_POINT2X(m, x, y, ret_x, ret_y) do { \ double _x = (x); \ double _y = (y); \ (ret_x) = (_x * (m).xx + (m).x0); \ (ret_y) = (_y * (m).yy + (m).y0); \ } while (0) #define TRANSFORM_POINT3X(m, x, y, ret_x, ret_y) do { \ double _x = (x); \ double _y = (y); \ (ret_x) = (_x * (m).xx + _y * (m).xy + (m).x0); \ (ret_y) = (_x * (m).yx + _y * (m).yy + (m).y0); \ } while (0) /* XXX: A1 has a different bits ordering in cairo. * Probably we should drop it. */ static cairo_content_t _directfb_format_to_content (DFBSurfacePixelFormat format) { if (DFB_PIXELFORMAT_HAS_ALPHA (format)) { if (DFB_COLOR_BITS_PER_PIXEL (format)) return CAIRO_CONTENT_COLOR_ALPHA; return CAIRO_CONTENT_ALPHA; } return CAIRO_CONTENT_COLOR; } static inline DFBSurfacePixelFormat _cairo_to_directfb_format (cairo_format_t format) { switch (format) { case CAIRO_FORMAT_RGB24: return DSPF_RGB32; case CAIRO_FORMAT_ARGB32: return DSPF_ARGB; case CAIRO_FORMAT_A8: return DSPF_A8; case CAIRO_FORMAT_A1: return DSPF_A1; default: break; } return -1; } static inline pixman_format_code_t _directfb_to_pixman_format (DFBSurfacePixelFormat format) { switch (format) { case DSPF_UNKNOWN: return PIXMAN_invalid; case DSPF_ARGB1555: return PIXMAN_a1r5g5b5; case DSPF_RGB16: return PIXMAN_r5g6b5; case DSPF_RGB24: return PIXMAN_r8g8b8; case DSPF_RGB32: return PIXMAN_x8r8g8b8; case DSPF_ARGB: return PIXMAN_a8r8g8b8; case DSPF_A8: return PIXMAN_a8; case DSPF_YUY2: return PIXMAN_yuy2; case DSPF_RGB332: return PIXMAN_r3g3b2; case DSPF_UYVY: return PIXMAN_invalid; case DSPF_I420: return PIXMAN_invalid; case DSPF_YV12: return PIXMAN_yv12; case DSPF_LUT8: return PIXMAN_invalid; case DSPF_ALUT44: return PIXMAN_invalid; case DSPF_AiRGB: return PIXMAN_invalid; case DSPF_A1: return PIXMAN_a1; /* bit reversed, oops */ case DSPF_NV12: return PIXMAN_invalid; case DSPF_NV16: return PIXMAN_invalid; case DSPF_ARGB2554: return PIXMAN_invalid; case DSPF_ARGB4444: return PIXMAN_a4r4g4b4; case DSPF_NV21: return PIXMAN_invalid; case DSPF_AYUV: return PIXMAN_invalid; case DSPF_A4: return PIXMAN_a4; case DSPF_ARGB1666: return PIXMAN_invalid; case DSPF_ARGB6666: return PIXMAN_invalid; case DSPF_RGB18: return PIXMAN_invalid; case DSPF_LUT2: return PIXMAN_invalid; case DSPF_RGB444: return PIXMAN_x4r4g4b4; case DSPF_RGB555: return PIXMAN_x1r5g5b5; #if DFB_NUM_PIXELFORMATS >= 29 case DSPF_BGR555: return PIXMAN_x1b5g5r5; #endif } return PIXMAN_invalid; } static inline DFBSurfacePixelFormat _directfb_from_pixman_format (pixman_format_code_t format) { switch ((int) format) { case PIXMAN_a1r5g5b5: return DSPF_ARGB1555; case PIXMAN_r5g6b5: return DSPF_RGB16; case PIXMAN_r8g8b8: return DSPF_RGB24; case PIXMAN_x8r8g8b8: return DSPF_RGB32; case PIXMAN_a8r8g8b8: return DSPF_ARGB; case PIXMAN_a8: return DSPF_A8; case PIXMAN_yuy2: return DSPF_YUY2; case PIXMAN_r3g3b2: return DSPF_RGB332; case PIXMAN_yv12: return DSPF_YV12; case PIXMAN_a1: return DSPF_A1; /* bit reversed, oops */ case PIXMAN_a4r4g4b4: return DSPF_ARGB4444; case PIXMAN_a4: return DSPF_A4; case PIXMAN_x4r4g4b4: return DSPF_RGB444; case PIXMAN_x1r5g5b5: return DSPF_RGB555; #if DFB_NUM_PIXELFORMATS >= 29 case PIXMAN_x1b5g5r5: return DSPF_BGR555; #endif default: return 0; } } static cairo_bool_t _directfb_get_operator (cairo_operator_t operator, DFBSurfaceBlendFunction *ret_srcblend, DFBSurfaceBlendFunction *ret_dstblend) { DFBSurfaceBlendFunction srcblend = DSBF_ONE; DFBSurfaceBlendFunction dstblend = DSBF_ZERO; switch (operator) { case CAIRO_OPERATOR_CLEAR: srcblend = DSBF_ZERO; dstblend = DSBF_ZERO; break; case CAIRO_OPERATOR_SOURCE: srcblend = DSBF_ONE; dstblend = DSBF_ZERO; break; case CAIRO_OPERATOR_OVER: srcblend = DSBF_ONE; dstblend = DSBF_INVSRCALPHA; break; case CAIRO_OPERATOR_IN: srcblend = DSBF_DESTALPHA; dstblend = DSBF_ZERO; break; case CAIRO_OPERATOR_OUT: srcblend = DSBF_INVDESTALPHA; dstblend = DSBF_ZERO; break; case CAIRO_OPERATOR_ATOP: srcblend = DSBF_DESTALPHA; dstblend = DSBF_INVSRCALPHA; break; case CAIRO_OPERATOR_DEST: srcblend = DSBF_ZERO; dstblend = DSBF_ONE; break; case CAIRO_OPERATOR_DEST_OVER: srcblend = DSBF_INVDESTALPHA; dstblend = DSBF_ONE; break; case CAIRO_OPERATOR_DEST_IN: srcblend = DSBF_ZERO; dstblend = DSBF_SRCALPHA; break; case CAIRO_OPERATOR_DEST_OUT: srcblend = DSBF_ZERO; dstblend = DSBF_INVSRCALPHA; break; case CAIRO_OPERATOR_DEST_ATOP: srcblend = DSBF_INVDESTALPHA; dstblend = DSBF_SRCALPHA; break; case CAIRO_OPERATOR_XOR: srcblend = DSBF_INVDESTALPHA; dstblend = DSBF_INVSRCALPHA; break; case CAIRO_OPERATOR_ADD: srcblend = DSBF_ONE; dstblend = DSBF_ONE; break; case CAIRO_OPERATOR_SATURATE: /* XXX This does not work. */ #if 0 srcblend = DSBF_SRCALPHASAT; dstblend = DSBF_ONE; break; #endif case CAIRO_OPERATOR_MULTIPLY: case CAIRO_OPERATOR_SCREEN: case CAIRO_OPERATOR_OVERLAY: case CAIRO_OPERATOR_DARKEN: case CAIRO_OPERATOR_LIGHTEN: case CAIRO_OPERATOR_COLOR_DODGE: case CAIRO_OPERATOR_COLOR_BURN: case CAIRO_OPERATOR_HARD_LIGHT: case CAIRO_OPERATOR_SOFT_LIGHT: case CAIRO_OPERATOR_DIFFERENCE: case CAIRO_OPERATOR_EXCLUSION: case CAIRO_OPERATOR_HSL_HUE: case CAIRO_OPERATOR_HSL_SATURATION: case CAIRO_OPERATOR_HSL_COLOR: case CAIRO_OPERATOR_HSL_LUMINOSITY: default: return FALSE; } *ret_srcblend = srcblend; *ret_dstblend = dstblend; return TRUE; } static cairo_status_t _directfb_buffer_surface_create (IDirectFB *dfb, DFBSurfacePixelFormat format, int width, int height, IDirectFBSurface **out) { IDirectFBSurface *buffer; DFBSurfaceDescription dsc; DFBResult ret; dsc.flags = DSDESC_WIDTH | DSDESC_HEIGHT | DSDESC_PIXELFORMAT; dsc.caps = DSCAPS_PREMULTIPLIED; dsc.width = width; dsc.height = height; dsc.pixelformat = format; ret = dfb->CreateSurface (dfb, &dsc, &buffer); if (ret) { DirectFBError ("IDirectFB::CreateSurface()", ret); return _cairo_error (CAIRO_STATUS_NO_MEMORY); } *out = buffer; return CAIRO_STATUS_SUCCESS; } static cairo_status_t _directfb_acquire_surface (cairo_directfb_surface_t *surface, cairo_rectangle_int_t *intrest_rec, cairo_image_surface_t **image_out, cairo_rectangle_int_t *image_rect_out, void **image_extra, DFBSurfaceLockFlags lock_flags) { IDirectFBSurface *buffer = NULL; DFBRectangle source_rect; cairo_surface_t *image; pixman_image_t *pixman_image; pixman_format_code_t pixman_format; cairo_status_t status; void *data; int pitch; if (surface->pixman_format == PIXMAN_invalid) { if (intrest_rec != NULL) { source_rect.x = intrest_rec->x; source_rect.y = intrest_rec->y; source_rect.w = intrest_rec->width; source_rect.h = intrest_rec->height; } else { source_rect.x = 0; source_rect.y = 0; surface->dfbsurface->GetSize (surface->dfbsurface, &source_rect.w, &source_rect.h); } if (surface->tmpsurface != NULL) { int w, h; surface->tmpsurface->GetSize (surface->tmpsurface, &w, &h); if (w < source_rect.w || h < source_rect.h) { surface->tmpsurface->Release (surface->tmpsurface); surface->tmpsurface = NULL; surface->tmpformat = PIXMAN_invalid; } } if (surface->tmpsurface == NULL) { DFBSurfacePixelFormat format; D_DEBUG_AT (CairoDFB_Acquire, "Allocating buffer for surface %p.\n", surface); format = _cairo_to_directfb_format (_cairo_format_from_content (surface->base.content)); status = _directfb_buffer_surface_create (surface->dfb, format, source_rect.w, source_rect.h, &surface->tmpsurface); if (unlikely (status)) goto ERROR; surface->tmpformat = _directfb_to_pixman_format (format); } buffer = surface->tmpsurface; pixman_format = surface->tmpformat; /* surface->dfbsurface->GetCapabilities (surface->dfbsurface, &caps); DFBSurfaceCapabilities caps; if (caps & DSCAPS_FLIPPING) { DFBRegion region = { .x1 = source_rect.x, .y1 = source_rect.y, .x2 = source_rect.x + source_rect.w - 1, .y2 = source_rect.y + source_rect.h - 1 }; surface->dfbsurface->Flip (surface->dfbsurface, &region, DSFLIP_BLIT); } */ buffer->Blit (buffer, surface->dfbsurface, &source_rect, 0, 0); } else { /*might be a subsurface get the offset*/ surface->dfbsurface->GetVisibleRectangle (surface->dfbsurface, &source_rect); pixman_format = surface->pixman_format; buffer = surface->dfbsurface; } if (buffer->Lock (buffer, lock_flags, &data, &pitch)) { D_DEBUG_AT (CairoDFB_Acquire, "Couldn't lock surface!\n"); status = _cairo_error (CAIRO_STATUS_NO_MEMORY); goto ERROR; } pixman_image = pixman_image_create_bits (pixman_format, source_rect.w, source_rect.h, data, pitch); if (pixman_image == NULL) { status = _cairo_error (CAIRO_STATUS_NO_MEMORY); goto ERROR; } image = _cairo_image_surface_create_for_pixman_image (pixman_image, pixman_format); status = image->status; if (status) goto ERROR; if (image_rect_out) { image_rect_out->x = source_rect.x; image_rect_out->y = source_rect.y; image_rect_out->width = source_rect.w; image_rect_out->height = source_rect.h; } else { /* lock for read */ /* might be a subsurface */ if (buffer == surface->dfbsurface) { cairo_surface_set_device_offset (image, source_rect.x, source_rect.y); } } *image_extra = buffer; *image_out = (cairo_image_surface_t *) image; return CAIRO_STATUS_SUCCESS; ERROR: if (buffer) { buffer->Unlock (buffer); if (buffer != surface->dfbsurface) buffer->Release (buffer); } return status; } static cairo_surface_t * _cairo_directfb_surface_create_internal (IDirectFB *dfb, DFBSurfacePixelFormat format, cairo_content_t content, int width, int height) { cairo_directfb_surface_t *surface; cairo_status_t status; surface = calloc (1, sizeof (cairo_directfb_surface_t)); if (unlikely (surface == NULL)) return _cairo_surface_create_in_error (_cairo_error (CAIRO_STATUS_NO_MEMORY)); surface->dfb = dfb; if (width < 8 || height < 8) { IDirectFBSurface *tmp; DFBRectangle rect = { .x=0, .y=0, .w=width, .h=height }; /* Some cards (e.g. Matrox) don't support surfaces smaller than 8x8 */ status = _directfb_buffer_surface_create (dfb, format, MAX (width, 8), MAX (height, 8), &tmp); if (status) { free (surface); return _cairo_surface_create_in_error (status); } tmp->GetSubSurface (tmp, &rect, &surface->dfbsurface); tmp->Release (tmp); } else { status = _directfb_buffer_surface_create (dfb, format, width, height, &surface->dfbsurface); if (status) { free (surface); return _cairo_surface_create_in_error (status); } } _cairo_surface_init (&surface->base, &_cairo_directfb_surface_backend, NULL, /* device */ content); surface->pixman_format = _directfb_to_pixman_format (format); surface->supported_destination = pixman_format_supported_destination (surface->pixman_format); surface->width = width; surface->height = height; surface->local = TRUE; surface->blit_premultiplied = TRUE; return &surface->base; } static cairo_surface_t * _cairo_directfb_surface_create_similar (void *abstract_src, cairo_content_t content, int width, int height) { cairo_directfb_surface_t *other = abstract_src; DFBSurfacePixelFormat format; D_DEBUG_AT (CairoDFB_Surface, "%s( src=%p, content=0x%x, width=%d, height=%d).\n", __FUNCTION__, other, content, width, height); width = (width <= 0) ? 1 : width; height = (height<= 0) ? 1 : height; format = _cairo_to_directfb_format (_cairo_format_from_content (content)); return _cairo_directfb_surface_create_internal (other->dfb, format, content, width, height); } static cairo_status_t _cairo_directfb_surface_finish (void *data) { cairo_directfb_surface_t *surface = (cairo_directfb_surface_t *)data; D_DEBUG_AT (CairoDFB_Surface, "%s( surface=%p ).\n", __FUNCTION__, surface); if (surface->tmpsurface) { surface->tmpsurface->Release (surface->tmpsurface); surface->tmpsurface = NULL; } if (surface->dfbsurface) { surface->dfbsurface->Release (surface->dfbsurface); surface->dfbsurface = NULL; } if (surface->dfb) surface->dfb = NULL; return CAIRO_STATUS_SUCCESS; } static cairo_status_t _cairo_directfb_surface_acquire_source_image (void *abstract_surface, cairo_image_surface_t **image_out, void **image_extra) { cairo_directfb_surface_t *surface = abstract_surface; D_DEBUG_AT (CairoDFB_Acquire, "%s( surface=%p ).\n", __FUNCTION__, surface); return _directfb_acquire_surface (surface, NULL, image_out, NULL, image_extra, DSLF_READ); } static void _cairo_directfb_surface_release_source_image (void *abstract_surface, cairo_image_surface_t *image, void *image_extra) { IDirectFBSurface *buffer = image_extra; D_DEBUG_AT (CairoDFB_Acquire, "%s( release=%p ).\n", __FUNCTION__, abstract_surface); buffer->Unlock (buffer); cairo_surface_destroy (&image->base); } static cairo_status_t _cairo_directfb_surface_acquire_dest_image (void *abstract_surface, cairo_rectangle_int_t *interest_rect, cairo_image_surface_t **image_out, cairo_rectangle_int_t *image_rect_out, void **image_extra) { cairo_directfb_surface_t *surface = abstract_surface; D_DEBUG_AT (CairoDFB_Acquire, "%s( surface=%p (%dx%d), interest_rect={ %u %u %u %u } ).\n", __FUNCTION__, surface, surface->width, surface->height, interest_rect ? interest_rect->x : 0, interest_rect ? interest_rect->y : 0, interest_rect ? interest_rect->width : (unsigned) surface->width, interest_rect ? interest_rect->height : (unsigned) surface->height); return _directfb_acquire_surface (surface, interest_rect, image_out, image_rect_out, image_extra, DSLF_READ | DSLF_WRITE); } static void _cairo_directfb_surface_release_dest_image (void *abstract_surface, cairo_rectangle_int_t *interest_rect, cairo_image_surface_t *image, cairo_rectangle_int_t *image_rect, void *image_extra) { cairo_directfb_surface_t *surface = abstract_surface; IDirectFBSurface *buffer = image_extra; D_DEBUG_AT (CairoDFB_Acquire, "%s( surface=%p ).\n", __FUNCTION__, surface); buffer->Unlock (buffer); if (surface->dfbsurface != buffer) { DFBRegion region = { .x1 = interest_rect->x, .y1 = interest_rect->y, .x2 = interest_rect->x + interest_rect->width - 1, .y2 = interest_rect->y + interest_rect->height - 1 }; surface->dfbsurface->SetBlittingFlags (surface->dfbsurface, DSBLIT_NOFX); surface->dfbsurface->SetClip (surface->dfbsurface, &region); surface->dfbsurface->Blit (surface->dfbsurface, buffer, NULL, image_rect->x, image_rect->y); } cairo_surface_destroy (&image->base); } static cairo_status_t _cairo_directfb_surface_clone_similar (void *abstract_surface, cairo_surface_t *src, int src_x, int src_y, int width, int height, int *clone_offset_x, int *clone_offset_y, cairo_surface_t **clone_out) { cairo_directfb_surface_t *surface = abstract_surface; cairo_directfb_surface_t *clone; D_DEBUG_AT (CairoDFB_Surface, "%s( surface=%p, src=%p ).\n", __FUNCTION__, surface, src); if (src->backend == surface->base.backend) { *clone_offset_x = 0; *clone_offset_y = 0; *clone_out = cairo_surface_reference (src); return CAIRO_STATUS_SUCCESS; } else if (_cairo_surface_is_image (src)) { cairo_image_surface_t *image_src = (cairo_image_surface_t *) src; DFBSurfacePixelFormat format; DFBResult ret; pixman_image_t *pixman_image; void *data; int pitch; format = _directfb_from_pixman_format (image_src->pixman_format); if (format == 0) return CAIRO_INT_STATUS_UNSUPPORTED; clone = (cairo_directfb_surface_t *) _cairo_directfb_surface_create_internal (surface->dfb, format, image_src->base.content, width, height); if (unlikely (clone->base.status)) return clone->base.status; ret = clone->dfbsurface->Lock (clone->dfbsurface, DSLF_WRITE, (void *)&data, &pitch); if (ret) { DirectFBError ("IDirectFBSurface::Lock()", ret); cairo_surface_destroy (&clone->base); return _cairo_error (CAIRO_STATUS_NO_MEMORY); } pixman_image = pixman_image_create_bits (clone->pixman_format, width, height, data, pitch); if (unlikely (pixman_image == NULL)) { DirectFBError ("IDirectFBSurface::Lock()", ret); cairo_surface_destroy (&clone->base); return _cairo_error (CAIRO_STATUS_NO_MEMORY); } pixman_image_composite32 (PIXMAN_OP_SRC, image_src->pixman_image, NULL, pixman_image, src_x, src_y, 0, 0, 0, 0, width, height); pixman_image_unref (pixman_image); clone->dfbsurface->Unlock (clone->dfbsurface); *clone_offset_x = src_x; *clone_offset_y = src_y; *clone_out = &clone->base; return CAIRO_STATUS_SUCCESS; } return CAIRO_INT_STATUS_UNSUPPORTED; } #if DFB_COMPOSITE || DFB_COMPOSITE_TRAPEZOIDS static cairo_int_status_t _directfb_prepare_composite (cairo_directfb_surface_t *dst, const cairo_pattern_t *src_pattern, const cairo_pattern_t *mask_pattern, cairo_operator_t op, int *src_x, int *src_y, int *mask_x, int *mask_y, unsigned int width, unsigned int height, cairo_directfb_surface_t **ret_src, cairo_surface_attributes_t *ret_src_attr) { cairo_directfb_surface_t *src; cairo_surface_attributes_t src_attr; cairo_status_t status; DFBSurfaceBlittingFlags flags; DFBSurfaceBlendFunction sblend; DFBSurfaceBlendFunction dblend; const cairo_color_t *color; /* XXX Unbounded operators are not handled correctly */ if (! _cairo_operator_bounded_by_source (op)) return CAIRO_INT_STATUS_UNSUPPORTED; if (! _directfb_get_operator (op, &sblend, &dblend)) return CAIRO_INT_STATUS_UNSUPPORTED; if (mask_pattern) { return CAIRO_INT_STATUS_UNSUPPORTED; if (mask_pattern->type != CAIRO_PATTERN_TYPE_SOLID) { const cairo_pattern_t *tmp; int tmp_x, tmp_y; if (src_pattern->type != CAIRO_PATTERN_TYPE_SOLID || sblend == DSBF_INVDESTALPHA) /* Doesn't work correctly */ return CAIRO_INT_STATUS_UNSUPPORTED; D_DEBUG_AT (CairoDFB_Render, "Replacing src pattern by mask pattern.\n"); tmp = src_pattern; tmp_x = *src_x; tmp_y = *src_y; src_pattern = mask_pattern; *src_x = *mask_x; *src_y = *mask_y; mask_pattern = tmp; *mask_x = tmp_x; *mask_y = tmp_y; if (sblend == DSBF_ONE) { sblend = DSBF_SRCALPHA; /*dblend = DSBF_INVSRCALPHA;*/ } } color = &((cairo_solid_pattern_t *) mask_pattern)->color; } else { color = _cairo_stock_color (CAIRO_STOCK_WHITE); } status = _cairo_pattern_acquire_surface (src_pattern, &dst->base, *src_x, *src_y, width, height, CAIRO_PATTERN_ACQUIRE_NO_REFLECT, (cairo_surface_t **) &src, &src_attr); if (status) return status; if (src->base.backend != &_cairo_directfb_surface_backend || src->dfb != dst->dfb) { _cairo_pattern_release_surface (src_pattern, &src->base, &src_attr); return CAIRO_INT_STATUS_UNSUPPORTED; } if ((src->base.content & CAIRO_CONTENT_ALPHA) == 0) { if (sblend == DSBF_SRCALPHA) sblend = DSBF_ONE; else if (sblend == DSBF_INVSRCALPHA) sblend = DSBF_ZERO; if (dblend == DSBF_SRCALPHA) dblend = DSBF_ONE; else if (dblend == DSBF_INVSRCALPHA) dblend = DSBF_ZERO; } if ((dst->base.content & CAIRO_CONTENT_ALPHA) == 0) { if (sblend == DSBF_DESTALPHA) sblend = DSBF_ONE; else if (sblend == DSBF_INVDESTALPHA) sblend = DSBF_ZERO; if (dblend == DSBF_DESTALPHA) dblend = DSBF_ONE; else if (dblend == DSBF_INVDESTALPHA) dblend = DSBF_ZERO; } flags = (sblend == DSBF_ONE && dblend == DSBF_ZERO) ? DSBLIT_NOFX : DSBLIT_BLEND_ALPHACHANNEL; if (! CAIRO_COLOR_IS_OPAQUE (color)) flags |= DSBLIT_BLEND_COLORALPHA; if (! _cairo_color_equal (color, _cairo_stock_color (CAIRO_STOCK_WHITE))) flags |= DSBLIT_COLORIZE; dst->dfbsurface->SetBlittingFlags (dst->dfbsurface, flags); if (flags & (DSBLIT_BLEND_ALPHACHANNEL | DSBLIT_BLEND_COLORALPHA)) { dst->dfbsurface->SetSrcBlendFunction (dst->dfbsurface, sblend); dst->dfbsurface->SetDstBlendFunction (dst->dfbsurface, dblend); } if (flags & (DSBLIT_BLEND_COLORALPHA | DSBLIT_COLORIZE)) { if (dst->blit_premultiplied) { dst->dfbsurface->SetColor (dst->dfbsurface, color->red_short >> 8, color->green_short >> 8, color->blue_short >> 8, color->alpha_short >> 8); } else { dst->dfbsurface->SetColor (dst->dfbsurface, color->red * 0xff, color->green * 0xff, color->blue * 0xff, color->alpha * 0xff); } } *ret_src = src; *ret_src_attr = src_attr; return CAIRO_STATUS_SUCCESS; } static void _directfb_finish_composite (cairo_directfb_surface_t *dst, const cairo_pattern_t *src_pattern, cairo_surface_t *src, cairo_surface_attributes_t *src_attr) { _cairo_pattern_release_surface (src_pattern, src, src_attr); } #endif /* DFB_COMPOSITE || DFB_COMPOSITE_TRAPEZOIDS */ #if DFB_COMPOSITE static DFBAccelerationMask _directfb_categorize_operation (cairo_surface_attributes_t *src_attr) { cairo_matrix_t *m = &src_attr->matrix; if (m->xy != 0 || m->yx != 0 || m->xx < 0 || m->yy < 0) { if (src_attr->extend != CAIRO_EXTEND_NONE) return DFXL_NONE; return DFXL_TEXTRIANGLES; } if (m->xx != 1 || m->yy != 1) { if (src_attr->extend != CAIRO_EXTEND_NONE) return DFXL_NONE; return DFXL_STRETCHBLIT; } switch (src_attr->extend) { case CAIRO_EXTEND_NONE: case CAIRO_EXTEND_REPEAT: if (_cairo_matrix_is_integer_translation (&src_attr->matrix, NULL, NULL)) { return DFXL_BLIT; } else { return DFXL_STRETCHBLIT; } default: case CAIRO_EXTEND_REFLECT: case CAIRO_EXTEND_PAD: return DFXL_NONE; } } static cairo_int_status_t _cairo_directfb_surface_composite (cairo_operator_t op, const cairo_pattern_t *src_pattern, const cairo_pattern_t *mask_pattern, void *abstract_dst, int src_x, int src_y, int mask_x, int mask_y, int dst_x, int dst_y, unsigned int width, unsigned int height, cairo_region_t *clip_region) { cairo_directfb_surface_t *dst = abstract_dst; cairo_directfb_surface_t *src; cairo_surface_attributes_t src_attr; cairo_bool_t is_integer_translation; DFBAccelerationMask accel, mask; cairo_int_status_t status; int tx, ty; D_DEBUG_AT (CairoDFB_Render, "%s( op=%d, src_pattern=%p, mask_pattern=%p, dst=%p," " src_x=%d, src_y=%d, mask_x=%d, mask_y=%d, dst_x=%d," " dst_y=%d, width=%u, height=%u ).\n", __FUNCTION__, op, src_pattern, mask_pattern, dst, src_x, src_y, mask_x, mask_y, dst_x, dst_y, width, height); if (! dst->supported_destination) return CAIRO_INT_STATUS_UNSUPPORTED; status = _directfb_prepare_composite (dst, src_pattern, mask_pattern, op, &src_x, &src_y, &mask_x, &mask_y, width, height, &src, &src_attr); if (status) return status; accel = _directfb_categorize_operation (&src_attr); if (accel == DFXL_NONE) { _directfb_finish_composite (dst, src_pattern, &src->base, &src_attr); return CAIRO_INT_STATUS_UNSUPPORTED; } dst->dfbsurface->GetAccelerationMask (dst->dfbsurface, src->dfbsurface, &mask); if ((mask & accel) == 0) { D_DEBUG_AT (CairoDFB_Render, "No acceleration (%08x)!\n", accel); if (accel != DFXL_BLIT) { _directfb_finish_composite (dst, src_pattern, &src->base, &src_attr); return CAIRO_INT_STATUS_UNSUPPORTED; } } src_x += src_attr.x_offset; src_y += src_attr.y_offset; switch ((int) accel) { case DFXL_BLIT: { DFBRectangle sr; is_integer_translation = _cairo_matrix_is_integer_translation (&src_attr.matrix, &tx, &ty); assert (is_integer_translation); sr.x = src_x + tx; sr.y = src_y + ty; sr.w = width; sr.h = height; if (src_attr.extend == CAIRO_EXTEND_NONE) { D_DEBUG_AT (CairoDFB_Render, "Running Blit().\n"); RUN_CLIPPED (dst, clip_region, NULL, dst->dfbsurface->Blit (dst->dfbsurface, src->dfbsurface, &sr, dst_x, dst_y)); } else if (src_attr.extend == CAIRO_EXTEND_REPEAT) { DFBRegion clip; clip.x1 = dst_x; clip.y1 = dst_y; clip.x2 = dst_x + width - 1; clip.y2 = dst_y + height - 1; D_DEBUG_AT (CairoDFB_Render, "Running TileBlit().\n"); RUN_CLIPPED (dst, clip_region, &clip, dst->dfbsurface->TileBlit (dst->dfbsurface, src->dfbsurface, &sr, dst_x, dst_y)); } break; } case DFXL_STRETCHBLIT: { DFBRectangle sr, dr; double x1, y1, x2, y2; TRANSFORM_POINT2X (src_attr.matrix, src_x, src_y, x1, y1); TRANSFORM_POINT2X (src_attr.matrix, src_x+width, src_y+height, x2, y2); sr.x = floor (x1); sr.y = floor (y1); sr.w = ceil (x2) - sr.x; sr.h = ceil (y2) - sr.y; dr.x = dst_x; dr.y = dst_y; dr.w = width; dr.h = height; D_DEBUG_AT (CairoDFB_Render, "Running StretchBlit().\n"); RUN_CLIPPED (dst, clip_region, NULL, dst->dfbsurface->StretchBlit (dst->dfbsurface, src->dfbsurface, &sr, &dr)); break; } case DFXL_TEXTRIANGLES: { DFBRegion clip; DFBVertex v[4]; float x1, y1, x2, y2; int w, h; status = cairo_matrix_invert (&src_attr.matrix); /* guaranteed by cairo_pattern_set_matrix (); */ assert (status == CAIRO_STATUS_SUCCESS); x1 = src_x; y1 = src_y; x2 = width + x1; y2 = height + y1; src->dfbsurface->GetSize (src->dfbsurface, &w, &h); TRANSFORM_POINT3X (src_attr.matrix, x1, y1, v[0].x, v[0].y); v[0].z = 0; v[0].w = 1; v[0].s = x1 / w; v[0].t = y1 / h; TRANSFORM_POINT3X (src_attr.matrix, x2, y1, v[1].x, v[1].y); v[1].z = 0; v[1].w = 1; v[1].s = x2 / w; v[1].t = y1 / h; TRANSFORM_POINT3X (src_attr.matrix, x2, y2, v[2].x, v[2].y); v[2].z = 0; v[2].w = 1; v[2].s = x2 / w; v[2].t = y2 / h; TRANSFORM_POINT3X (src_attr.matrix, x1, y2, v[3].x, v[3].y); v[3].z = 0; v[3].w = 1; v[3].s = x1 / w; v[3].t = y2 / h; clip.x1 = dst_x; clip.y1 = dst_y; clip.x2 = dst_x + width - 1; clip.y2 = dst_y + height - 1; D_DEBUG_AT (CairoDFB_Render, "Running TextureTriangles().\n"); RUN_CLIPPED (dst, clip_region, &clip, dst->dfbsurface->TextureTriangles (dst->dfbsurface, src->dfbsurface, v, NULL, 4, DTTF_FAN)); break; } default: D_BUG ("Unexpected operation"); break; } _directfb_finish_composite (dst, src_pattern, &src->base, &src_attr); return CAIRO_STATUS_SUCCESS; } #endif /* DFB_COMPOSITE */ #if DFB_RECTANGLES static cairo_int_status_t _cairo_directfb_surface_fill_rectangles (void *abstract_surface, cairo_operator_t op, const cairo_color_t *color, cairo_rectangle_int_t *rects, int n_rects) { cairo_directfb_surface_t *dst = abstract_surface; DFBSurfaceDrawingFlags flags; DFBSurfaceBlendFunction sblend; DFBSurfaceBlendFunction dblend; DFBRectangle r[n_rects]; int i; D_DEBUG_AT (CairoDFB_Render, "%s( dst=%p, op=%d, color=%p, rects=%p, n_rects=%d ).\n", __FUNCTION__, dst, op, color, rects, n_rects); if (! dst->supported_destination) return CAIRO_INT_STATUS_UNSUPPORTED; if (! _directfb_get_operator (op, &sblend, &dblend)) return CAIRO_INT_STATUS_UNSUPPORTED; if (CAIRO_COLOR_IS_OPAQUE (color)) { if (sblend == DSBF_SRCALPHA) sblend = DSBF_ONE; else if (sblend == DSBF_INVSRCALPHA) sblend = DSBF_ZERO; if (dblend == DSBF_SRCALPHA) dblend = DSBF_ONE; else if (dblend == DSBF_INVSRCALPHA) dblend = DSBF_ZERO; } if ((dst->base.content & CAIRO_CONTENT_ALPHA) == 0) { if (sblend == DSBF_DESTALPHA) sblend = DSBF_ONE; else if (sblend == DSBF_INVDESTALPHA) sblend = DSBF_ZERO; if (dblend == DSBF_DESTALPHA) dblend = DSBF_ONE; else if (dblend == DSBF_INVDESTALPHA) dblend = DSBF_ZERO; } flags = (sblend == DSBF_ONE && dblend == DSBF_ZERO) ? DSDRAW_NOFX : DSDRAW_BLEND; dst->dfbsurface->SetDrawingFlags (dst->dfbsurface, flags); if (flags & DSDRAW_BLEND) { dst->dfbsurface->SetSrcBlendFunction (dst->dfbsurface, sblend); dst->dfbsurface->SetDstBlendFunction (dst->dfbsurface, dblend); } dst->dfbsurface->SetColor (dst->dfbsurface, color->red_short >> 8, color->green_short >> 8, color->blue_short >> 8, color->alpha_short >> 8); for (i = 0; i < n_rects; i++) { r[i].x = rects[i].x; r[i].y = rects[i].y; r[i].w = rects[i].width; r[i].h = rects[i].height; } RUN_CLIPPED (dst, NULL, NULL, dst->dfbsurface->FillRectangles (dst->dfbsurface, r, n_rects)); return CAIRO_STATUS_SUCCESS; } #endif #if DFB_COMPOSITE_TRAPEZOIDS static cairo_int_status_t _cairo_directfb_surface_composite_trapezoids (cairo_operator_t op, const cairo_pattern_t *pattern, void *abstract_dst, cairo_antialias_t antialias, int src_x, int src_y, int dst_x, int dst_y, unsigned int width, unsigned int height, cairo_trapezoid_t *traps, int num_traps, cairo_region_t *clip_region) { cairo_directfb_surface_t *dst = abstract_dst; cairo_directfb_surface_t *src; cairo_surface_attributes_t src_attr; cairo_status_t status; DFBAccelerationMask accel; D_DEBUG_AT (CairoDFB_Render, "%s( op=%d, pattern=%p, dst=%p, antialias=%d," " src_x=%d, src_y=%d, dst_x=%d, dst_y=%d," " width=%u, height=%u, traps=%p, num_traps=%d ).\n", __FUNCTION__, op, pattern, dst, antialias, src_x, src_y, dst_x, dst_y, width, height, traps, num_traps); if (! dst->supported_destination) return CAIRO_INT_STATUS_UNSUPPORTED; if (antialias != CAIRO_ANTIALIAS_NONE) return CAIRO_INT_STATUS_UNSUPPORTED; /* Textures are not supported yet. */ if (pattern->type != CAIRO_PATTERN_TYPE_SOLID) return CAIRO_INT_STATUS_UNSUPPORTED; status = _directfb_prepare_composite (dst, pattern, NULL, op, &src_x, &src_y, NULL, NULL, width, height, &src, &src_attr); if (status) return status; dst->dfbsurface->GetAccelerationMask (dst->dfbsurface, src->dfbsurface, &accel); status = CAIRO_INT_STATUS_UNSUPPORTED; if (accel & DFXL_TEXTRIANGLES) { DFBVertex vertex[6*num_traps]; DFBVertex *v = &vertex[0]; int n = 0; #define ADD_TRI_V(V, X, Y) do { \ (V)->x = (X); (V)->y = (Y); (V)->w = 1; (V)->z = (V)->s = (V)->t = 0; \ } while (0) #define ADD_TRI(id, x1, y1, x2, y2, x3, y3) do {\ const int p = (id)*3;\ ADD_TRI_V (v+p+0, x1, y1); \ ADD_TRI_V (v+p+1, x2, y2); \ ADD_TRI_V (v+p+2, x3, y3); \ } while (0) while (num_traps--) { double lx1, ly1, lx2, ly2; double rx1, ry1, rx2, ry2; lx1 = _cairo_fixed_to_double (traps->left.p1.x); ly1 = _cairo_fixed_to_double (traps->left.p1.y); lx2 = _cairo_fixed_to_double (traps->left.p2.x); ly2 = _cairo_fixed_to_double (traps->left.p2.y); rx1 = _cairo_fixed_to_double (traps->right.p1.x); ry1 = _cairo_fixed_to_double (traps->right.p1.y); rx2 = _cairo_fixed_to_double (traps->right.p2.x); ry2 = _cairo_fixed_to_double (traps->right.p2.y); if (traps->left.p1.y < traps->top) { double y = _cairo_fixed_to_double (traps->top); if (lx2 != lx1) lx1 = (y - ly1) * (lx2 - lx1) / (ly2 - ly1) + lx1; ly1 = y; } if (traps->left.p2.y > traps->bottom) { double y = _cairo_fixed_to_double (traps->bottom); if (lx2 != lx1) lx2 = (y - ly1) * (lx2 - lx1) / (ly2 - ly1) + lx1; ly2 = y; } if (traps->right.p1.y < traps->top) { double y = _cairo_fixed_to_double (traps->top); if (rx2 != rx1) rx1 = (y - ry1) * (rx2 - rx1) / (ry2 - ry1) + rx1; ry1 = y; } if (traps->right.p2.y > traps->bottom) { double y = _cairo_fixed_to_double (traps->bottom); if (rx2 != rx1) rx2 = (y - ry1) * (rx2 - rx1) / (ry2 - ry1) + rx1; ry2 = y; } if (lx1 == rx1 && ly1 == ry1) { ADD_TRI (0, lx2, ly2, lx1, ly1, rx2, ry2); v += 3; n += 3; } else if (lx2 == rx2 && ly2 == ry2) { ADD_TRI (0, lx1, ly1, lx2, ly2, rx1, ry1); v += 3; n += 3; } else { ADD_TRI (0, lx1, ly1, rx1, ry1, lx2, ly2); ADD_TRI (1, lx2, ly2, rx1, ry1, rx2, ry2); v += 6; n += 6; } traps++; } #undef ADD_TRI #undef ADD_TRI_V D_DEBUG_AT (CairoDFB_Render, "Running TextureTriangles().\n"); RUN_CLIPPED (dst, clip_region, NULL, dst->dfbsurface->TextureTriangles (dst->dfbsurface, src->dfbsurface, vertex, NULL, n, DTTF_LIST)); status = CAIRO_STATUS_SUCCESS; } _directfb_finish_composite (dst, pattern, &src->base, &src_attr); return status; } #endif /* DFB_COMPOSITE_TRAPEZOIDS */ static cairo_bool_t _cairo_directfb_abstract_surface_get_extents (void *abstract_surface, cairo_rectangle_int_t *rectangle) { cairo_directfb_surface_t *surface = abstract_surface; D_DEBUG_AT (CairoDFB_Surface, "%s( surface=%p, rectangle=%p ).\n", __FUNCTION__, surface, rectangle); if (!surface->local) { surface->dfbsurface->GetSize (surface->dfbsurface, &surface->width, &surface->height); } rectangle->x = 0; rectangle->y = 0; rectangle->width = surface->width; rectangle->height = surface->height; return TRUE; } #if DFB_SHOW_GLYPHS static cairo_status_t _directfb_allocate_font_cache (IDirectFB *dfb, int width, int height, cairo_directfb_font_cache_t **out) { cairo_directfb_font_cache_t *cache; cairo_status_t status; cache = calloc (1, sizeof (cairo_directfb_font_cache_t)); if (cache == NULL) return _cairo_error (CAIRO_STATUS_NO_MEMORY); cache->dfb = dfb; status = _directfb_buffer_surface_create (dfb, _directfb_argb_font ? DSPF_ARGB : DSPF_A8, width, height, &cache->dfbsurface); if (status) { free (cache); return status; } cache->width = width; cache->height = height; *out = cache; return CAIRO_STATUS_SUCCESS; } static void _directfb_destroy_font_cache (cairo_directfb_font_cache_t *cache) { cache->dfbsurface->Release (cache->dfbsurface); free (cache); } /* XXX hook into rtree font cache from drm */ static cairo_status_t _directfb_acquire_font_cache (cairo_directfb_surface_t *surface, cairo_scaled_font_t *scaled_font, const cairo_glyph_t *glyphs, int num_glyphs, cairo_directfb_font_cache_t **ret_cache, DFBRectangle *rects, DFBPoint *points, int *ret_num) { cairo_status_t status; cairo_scaled_glyph_t *chars[num_glyphs]; int num_chars = 0; cairo_directfb_font_cache_t *cache = NULL; int n = 0; int x = 0; int y = 0; int w = 8; int h = 8; int i; D_DEBUG_AT (CairoDFB_Font, "%s( %p [%d] )\n", __FUNCTION__, glyphs, num_glyphs ); _cairo_scaled_font_freeze_cache (scaled_font); if (scaled_font->surface_private) { cache = scaled_font->surface_private; x = cache->x; y = cache->y; } for (i = 0; i < num_glyphs; i++) { cairo_scaled_glyph_t *scaled_glyph; cairo_image_surface_t *img; D_DEBUG_AT (CairoDFB_Font, " -> [%2d] = %4lu\n", i, glyphs[i].index ); status = _cairo_scaled_glyph_lookup (scaled_font, glyphs[i].index, CAIRO_SCALED_GLYPH_INFO_SURFACE, &scaled_glyph); if (status) { _cairo_scaled_font_thaw_cache (scaled_font); return status; } img = scaled_glyph->surface; switch (img->format) { case CAIRO_FORMAT_A1: case CAIRO_FORMAT_A8: case CAIRO_FORMAT_ARGB32: break; case CAIRO_FORMAT_RGB24: default: D_DEBUG_AT (CairoDFB_Font, " -> Unsupported font format %d!\n", img->format); _cairo_scaled_font_thaw_cache (scaled_font); return CAIRO_INT_STATUS_UNSUPPORTED; } points[n].x = _cairo_lround (glyphs[i].x - img->base.device_transform.x0); points[n].y = _cairo_lround (glyphs[i].y - img->base.device_transform.y0); // D_DEBUG_AT (CairoDFB_Font, " (%4d,%4d) [%2d]\n", points[n].x, points[n].y, n ); if (points[n].x >= surface->width || points[n].y >= surface->height || points[n].x+img->width <= 0 || points[n].y+img->height <= 0) { continue; } if (scaled_glyph->surface_private == NULL) { DFBRectangle *rect; if (x+img->width > 2048) { x = 0; y = h; h = 0; } rects[n].x = x; rects[n].y = y; rects[n].w = img->width; rects[n].h = img->height; x += img->width; h = MAX (h, img->height); w = MAX (w, x); /* Remember glyph location */ rect = malloc (sizeof (DFBRectangle)); if (rect == NULL) { _cairo_scaled_font_thaw_cache (scaled_font); return _cairo_error (CAIRO_STATUS_NO_MEMORY); } *rect = rects[n]; scaled_glyph->surface_private = rect; chars[num_chars++] = scaled_glyph; D_DEBUG_AT (CairoDFB_Font, " -> loading at %4d,%2d <- rect %p, img %p, entry %p\n", rects[n].x, rects[n].y, rect, scaled_glyph->surface, scaled_glyph); } else { rects[n] = *(DFBRectangle *) scaled_glyph->surface_private; D_DEBUG_AT (CairoDFB_Font, " -> exists at %4d,%2d\n", rects[n].x, rects[n].y); } n++; } if (n == 0) { _cairo_scaled_font_thaw_cache (scaled_font); return CAIRO_INT_STATUS_NOTHING_TO_DO; } h += y; w = MAX (w, 8); h = MAX (h, 8); /* XXX query maximum surface size */ if (w > 2048 || h > 2048) { _cairo_scaled_font_thaw_cache (scaled_font); return CAIRO_INT_STATUS_UNSUPPORTED; } if (cache) { if (cache->width < w || cache->height < h) { cairo_directfb_font_cache_t *new_cache; w = MAX (w, cache->width); h = MAX (h, cache->height); D_DEBUG_AT (CairoDFB_Font, " -> Reallocating font cache (%dx%d).\n", w, h); status = _directfb_allocate_font_cache (surface->dfb, w, h, &new_cache); if (status) { _cairo_scaled_font_thaw_cache (scaled_font); return status; } new_cache->dfbsurface->Blit (new_cache->dfbsurface, cache->dfbsurface, NULL, 0, 0); _directfb_destroy_font_cache (cache); scaled_font->surface_private = cache = new_cache; } } else { D_DEBUG_AT (CairoDFB_Font, " -> Allocating font cache (%dx%d).\n", w, h); status = _directfb_allocate_font_cache (surface->dfb, w, h, &cache); if (status) { _cairo_scaled_font_thaw_cache (scaled_font); return status; } scaled_font->surface_backend = &_cairo_directfb_surface_backend; scaled_font->surface_private = cache; } if (num_chars) { unsigned char *data; int pitch; if (cache->dfbsurface->Lock (cache->dfbsurface, DSLF_WRITE, (void *)&data, &pitch)) { _cairo_scaled_font_thaw_cache (scaled_font); return _cairo_error (CAIRO_STATUS_NO_MEMORY); } D_DEBUG_AT (CairoDFB_Font, " => %d chars to load, cache %dx%d\n", num_chars, cache->width, cache->height); for (i = 0; i < num_chars; i++) { cairo_image_surface_t *img = chars[i]->surface; DFBRectangle *rect = chars[i]->surface_private; unsigned char *dst = data; unsigned char *src; int j; D_DEBUG_AT (CairoDFB_Font, " -> loading [%2d] <- rect %p, img %p, entry %p\n", i, rect, img, chars[i]); src = img->data; D_DEBUG_AT (CairoDFB_Font, " from %p\n", src); dst += rect->y * pitch + (_directfb_argb_font ? (rect->x<<2) : rect->x); D_DEBUG_AT (CairoDFB_Font, " to %4d,%2d (%p)\n", rect->x, rect->y, dst); if (img->format == CAIRO_FORMAT_A1) { for (h = rect->h; h; h--) { if (_directfb_argb_font) { for (j = 0; j < rect->w; j++) ((uint32_t *) dst)[j] = (src[j>>3] & (1 << (j&7))) ? 0xffffffff : 0; } else { for (j = 0; j < rect->w; j++) dst[j] = (src[j>>3] & (1 << (j&7))) ? 0xff : 0; } dst += pitch; src += img->stride; } } else if (img->format == CAIRO_FORMAT_A8) { for (h = rect->h; h; h--) { if (_directfb_argb_font) { for (j = 0; j < rect->w; j++) ((uint32_t *) dst)[j] = src[j] * 0x01010101; } else { direct_memcpy (dst, src, rect->w); } dst += pitch; src += img->stride; } } else { /* ARGB32 */ for (h = rect->h; h; h--) { if (_directfb_argb_font) { direct_memcpy (dst, src, rect->w<<2); } else { for (j = 0; j < rect->w; j++) dst[j] = ((uint32_t *) src)[j] >> 24; } dst += pitch; src += img->stride; } } } cache->dfbsurface->Unlock (cache->dfbsurface); } _cairo_scaled_font_thaw_cache (scaled_font); cache->x = x; cache->y = y; D_DEBUG_AT (CairoDFB_Font, " => cache %d,%d, %p [%d]\n", x, y, cache, n); *ret_cache = cache; *ret_num = n; return CAIRO_STATUS_SUCCESS; } static void _cairo_directfb_surface_scaled_font_fini (cairo_scaled_font_t *scaled_font) { cairo_directfb_font_cache_t *cache = scaled_font->surface_private; D_DEBUG_AT (CairoDFB_Font, "%s( scaled_font=%p ).\n", __FUNCTION__, scaled_font); if (cache != NULL) { _directfb_destroy_font_cache (cache); scaled_font->surface_private = NULL; } } static void _cairo_directfb_surface_scaled_glyph_fini (cairo_scaled_glyph_t *scaled_glyph, cairo_scaled_font_t *scaled_font) { D_DEBUG_AT (CairoDFB_Font, "%s( scaled_glyph=%p, scaled_font=%p ).\n", __FUNCTION__, scaled_glyph, scaled_font); if (scaled_glyph->surface_private != NULL) { free (scaled_glyph->surface_private); scaled_glyph->surface_private = NULL; } } static cairo_int_status_t _cairo_directfb_surface_show_glyphs (void *abstract_dst, cairo_operator_t op, const cairo_pattern_t *pattern, cairo_glyph_t *glyphs, int num_glyphs, cairo_scaled_font_t *scaled_font, cairo_clip_t *clip, int *remaining_glyphs) { cairo_directfb_surface_t *dst = abstract_dst; cairo_directfb_font_cache_t *cache; cairo_status_t status; DFBSurfaceBlittingFlags flags; DFBSurfaceBlendFunction sblend; DFBSurfaceBlendFunction dblend; DFBRectangle rects[num_glyphs]; DFBPoint points[num_glyphs]; int num; const cairo_color_t *color; cairo_region_t *clip_region = NULL; D_DEBUG_AT (CairoDFB_Font, "%s( dst=%p, op=%d, pattern=%p, glyphs=%p, num_glyphs=%d, scaled_font=%p ).\n", __FUNCTION__, dst, op, pattern, glyphs, num_glyphs, scaled_font); if (! dst->supported_destination) return CAIRO_INT_STATUS_UNSUPPORTED; if (pattern->type != CAIRO_PATTERN_TYPE_SOLID) return CAIRO_INT_STATUS_UNSUPPORTED; /* Fallback if we need to emulate clip regions */ if (clip != NULL) { status = _cairo_clip_get_region (clip, &clip_region); assert (status != CAIRO_INT_STATUS_NOTHING_TO_DO); if (status) return status; } /* XXX Unbounded operators are not handled correctly */ if (! _cairo_operator_bounded_by_mask (op)) return CAIRO_INT_STATUS_UNSUPPORTED; if (! _directfb_get_operator (op, &sblend, &dblend) || sblend == DSBF_DESTALPHA || sblend == DSBF_INVDESTALPHA) { return CAIRO_INT_STATUS_UNSUPPORTED; } status = _directfb_acquire_font_cache (dst, scaled_font, glyphs, num_glyphs, &cache, &rects[0], &points[0], &num); if (status) { if (status == CAIRO_INT_STATUS_NOTHING_TO_DO) status = CAIRO_STATUS_SUCCESS; return status; } color = &((cairo_solid_pattern_t *) pattern)->color; flags = DSBLIT_BLEND_ALPHACHANNEL | DSBLIT_COLORIZE; if (! CAIRO_COLOR_IS_OPAQUE (color)) flags |= DSBLIT_BLEND_COLORALPHA; if (!_directfb_argb_font) { if (sblend == DSBF_ONE) { sblend = DSBF_SRCALPHA; if (dblend == DSBF_ZERO) dblend = DSBF_INVSRCALPHA; } } dst->dfbsurface->SetBlittingFlags (dst->dfbsurface, flags); dst->dfbsurface->SetSrcBlendFunction (dst->dfbsurface, sblend); dst->dfbsurface->SetDstBlendFunction (dst->dfbsurface, dblend); if (dst->blit_premultiplied) { dst->dfbsurface->SetColor (dst->dfbsurface, color->red_short >> 8, color->green_short >> 8, color->blue_short >> 8, color->alpha_short >> 8); } else { dst->dfbsurface->SetColor (dst->dfbsurface, color->red * 0xff, color->green * 0xff, color->blue * 0xff, color->alpha * 0xff); } D_DEBUG_AT (CairoDFB_Font, "Running BatchBlit().\n"); RUN_CLIPPED (dst, clip_region, NULL, dst->dfbsurface->BatchBlit (dst->dfbsurface, cache->dfbsurface, rects, points, num)); return CAIRO_STATUS_SUCCESS; } #endif /* DFB_SHOW_GLYPHS */ static cairo_bool_t _cairo_directfb_surface_is_similar (void *surface_a, void *surface_b) { cairo_directfb_surface_t *a = (cairo_directfb_surface_t *) surface_a; cairo_directfb_surface_t *b = (cairo_directfb_surface_t *) surface_b; return a->dfb == b->dfb; } static cairo_surface_backend_t _cairo_directfb_surface_backend = { CAIRO_SURFACE_TYPE_DIRECTFB, /*type*/ _cairo_directfb_surface_create_similar,/*create_similar*/ _cairo_directfb_surface_finish, /*finish*/ _cairo_directfb_surface_acquire_source_image,/*acquire_source_image*/ _cairo_directfb_surface_release_source_image,/*release_source_image*/ _cairo_directfb_surface_acquire_dest_image,/*acquire_dest_image*/ _cairo_directfb_surface_release_dest_image,/*release_dest_image*/ _cairo_directfb_surface_clone_similar,/*clone_similar*/ #if DFB_COMPOSITE _cairo_directfb_surface_composite,/*composite*/ #else NULL,/*composite*/ #endif #if DFB_RECTANGLES _cairo_directfb_surface_fill_rectangles,/*fill_rectangles*/ #else NULL,/*fill_rectangles*/ #endif #if DFB_COMPOSITE_TRAPEZOIDS _cairo_directfb_surface_composite_trapezoids,/*composite_trapezoids*/ #else NULL,/*composite_trapezoids*/ #endif NULL, /* create_span_renderer */ NULL, /* check_span_renderer */ NULL, /* copy_page */ NULL, /* show_page */ _cairo_directfb_abstract_surface_get_extents,/* get_extents */ NULL, /* old_show_glyphs */ NULL, /* get_font_options */ NULL, /* flush */ NULL, /* mark_dirty_rectangle */ #if DFB_SHOW_GLYPHS _cairo_directfb_surface_scaled_font_fini,/* scaled_font_fini */ _cairo_directfb_surface_scaled_glyph_fini,/* scaled_glyph_fini */ #else NULL, NULL, #endif NULL, /* paint */ NULL, /* mask */ NULL, /* stroke */ NULL, /* fill */ #if DFB_SHOW_GLYPHS _cairo_directfb_surface_show_glyphs,/* show_glyphs */ #else NULL, /* show_glyphs */ #endif NULL, /* snapshot */ _cairo_directfb_surface_is_similar, }; static void cairo_directfb_surface_backend_init (IDirectFB *dfb) { static int done = 0; if (done) return; if (getenv ("CAIRO_DIRECTFB_NO_ACCEL")) { #if DFB_RECTANGLES _cairo_directfb_surface_backend.fill_rectangles = NULL; #endif #if DFB_COMPOSITE _cairo_directfb_surface_backend.composite = NULL; #endif #if DFB_COMPOSITE_TRAPEZOIDS _cairo_directfb_surface_backend.composite_trapezoids = NULL; #endif #if DFB_SHOW_GLYPHS _cairo_directfb_surface_backend.scaled_font_fini = NULL; _cairo_directfb_surface_backend.scaled_glyph_fini = NULL; _cairo_directfb_surface_backend.show_glyphs = NULL; #endif D_DEBUG_AT (CairoDFB_Surface, "Acceleration disabled.\n"); } else { DFBGraphicsDeviceDescription dsc; dfb->GetDeviceDescription (dfb, &dsc); #if DFB_COMPOSITE // if (!(dsc.acceleration_mask & DFXL_BLIT)) // _cairo_directfb_surface_backend.composite = NULL; #endif #if DFB_COMPOSITE_TRAPEZOIDS // if (!(dsc.acceleration_mask & DFXL_TEXTRIANGLES)) // _cairo_directfb_surface_backend.composite_trapezoids = NULL; #endif } if (getenv ("CAIRO_DIRECTFB_ARGB_FONT")) { _directfb_argb_font = 1; D_DEBUG_AT (CairoDFB_Surface, "Using ARGB fonts.\n"); } done = 1; } cairo_surface_t * cairo_directfb_surface_create (IDirectFB *dfb, IDirectFBSurface *dfbsurface) { cairo_directfb_surface_t *surface; DFBSurfacePixelFormat format; DFBSurfaceCapabilities caps; D_ASSERT (dfb != NULL); D_ASSERT (dfbsurface != NULL); cairo_directfb_surface_backend_init (dfb); surface = calloc (1, sizeof (cairo_directfb_surface_t)); if (surface == NULL) return _cairo_surface_create_in_error (_cairo_error (CAIRO_STATUS_NO_MEMORY)); dfbsurface->AddRef (dfbsurface); dfbsurface->GetPixelFormat (dfbsurface, &format); dfbsurface->GetSize (dfbsurface, &surface->width, &surface->height); surface->dfb = dfb; surface->dfbsurface = dfbsurface; surface->pixman_format = _directfb_to_pixman_format (format); surface->supported_destination = pixman_format_supported_destination (surface->pixman_format); dfbsurface->GetCapabilities (dfbsurface, &caps); if (caps & DSCAPS_PREMULTIPLIED) surface->blit_premultiplied = TRUE; _cairo_surface_init (&surface->base, &_cairo_directfb_surface_backend, NULL, /* device */ _directfb_format_to_content (format)); return &surface->base; }
899116.c
/** @file Copyright (c) 2017-2021, Intel Corporation. All rights reserved.<BR> SPDX-License-Identifier: BSD-2-Clause-Patent **/ #include <PiPei.h> #include <Library/BaseLib.h> #include <Library/PciLib.h> #include <Library/PcdLib.h> #include <Library/IoLib.h> #include <Library/BaseMemoryLib.h> #include <Library/BlMemoryAllocationLib.h> #include <Library/DebugLib.h> #include <Library/SpiFlashLibCml.h> #include <Library/SocInitLib.h> #include <Library/BoardInitLib.h> #include <Library/SerialPortLib.h> #include <Guid/GraphicsInfoHob.h> #include <Guid/SystemTableInfoGuid.h> #include <Guid/SerialPortInfoGuid.h> #include <FspsUpd.h> #include <GlobalNvsAreaDef.h> #include <Library/BootloaderCoreLib.h> #include <IndustryStandard/Acpi.h> #include <IndustryStandard/MemoryMappedConfigurationSpaceAccessTable.h> #include <BlCommon.h> #include <Guid/BootLoaderServiceGuid.h> #include <Library/SpiBlockIoLib.h> #include <Library/MemoryAllocationLib.h> #include <Service/SpiFlashService.h> #include <Library/PrintLib.h> #include <ConfigDataDefs.h> #include <Library/ConfigDataLib.h> #include <Library/PchInfoLib.h> #include <Library/IgdOpRegionLib.h> #include <Library/BdatLib.h> #include <Library/VariableLib.h> #include <Guid/SmmInformationGuid.h> #include <GpioPinsCmlvH.h> #include <GpioPinsCmlvLp.h> #include "HdaVerbTable.h" #include <Library/TpmLib.h> #include <Library/PchSerialIoLib.h> #include <Library/SgxLib.h> #include <PlatformBase.h> #include <Library/GpioLib.h> #include <Library/GpioSiLib.h> #include <RegAccess.h> #include <CpuPowerMgmt.h> #include <PowerMgmtNvsStruct.h> #include <CpuInitDataHob.h> #include <Library/HobLib.h> #include <Library/FirmwareUpdateLib.h> #include <Library/MpInitLib.h> #include <Library/PlatformHookLib.h> #include <Guid/GraphicsInfoHob.h> #include <Library/PciCf8Lib.h> #include <Library/BoardSupportLib.h> #include <PlatformData.h> #include <PsdLib.h> #include <Library/SmbiosInitLib.h> #include <IndustryStandard/SmBios.h> #include <VerInfo.h> #include <Library/S3SaveRestoreLib.h> #include "GpioTables.h" #define DEFAULT_GPIO_IRQ_ROUTE 14 // // The EC implements an embedded controller interface at ports 0x60/0x64 and a ACPI compliant // system management controller at ports 0x62/0x66. Port 0x66 is the command and status port, // port 0x62 is the data port. // #define EC_C_PORT 0x66 // // EC commands that are issued to the EC through the command port (0x66). // New commands and command parameters should only be written by the host when IBF=0. // Data read from the EC data port is valid only when OBF=1. // #define EC_C_ACPI_ENABLE 0xAA // Enable ACPI mode #define R_SA_SMRAMC (0x88) #define PCI_TO_CF8_ADDRESS(A) \ ((UINT32) ((((A) >> 4) & 0x00ffff00) | ((A) & 0xfc) | 0x80000000)) #define GPIO_CFG_PIN_TO_PAD(A) \ ((UINT32) (((A).PinNum) | (((A).Group) << 16))) FVID_TABLE *mFvidPointer = NULL; SILICON_CFG_DATA *mSiliconCfgData = NULL; /// /// Overcurrent pins, the values match the setting of EDS, please refer to EDS for more details /// typedef enum { UsbOverCurrentPin0 = 0, UsbOverCurrentPin1, UsbOverCurrentPin2, UsbOverCurrentPin3, UsbOverCurrentPin4, UsbOverCurrentPin5, UsbOverCurrentPin6, UsbOverCurrentPin7, UsbOverCurrentPinMax, UsbOverCurrentPinSkip = 0xFF } USB_OVERCURRENT_PIN; typedef struct { UINT8 DevNum; UINT8 Pid; UINT8 RpNumBase; } PCH_PCIE_CONTROLLER_INFO; CONST PCH_PCIE_CONTROLLER_INFO mPchPcieControllerInfo[] = { { PCI_DEVICE_NUMBER_PCH_PCIE_DEVICE_1, PID_SPA, 0 }, { PCI_DEVICE_NUMBER_PCH_PCIE_DEVICE_1, PID_SPB, 4 }, { PCI_DEVICE_NUMBER_PCH_PCIE_DEVICE_2, PID_SPC, 8 }, { PCI_DEVICE_NUMBER_PCH_PCIE_DEVICE_2, PID_SPD, 12 }, { PCI_DEVICE_NUMBER_PCH_PCIE_DEVICE_3, PID_SPE, 16 }, // PCH-H only // { PCI_DEVICE_NUMBER_PCH_PCIE_DEVICE_3, PID_SPF, 20 } // PCH-H only }; CONST UINT8 mPxRcConfig[8] = { 11, 10, 11, 11, 11, 11, 11, 11 }; CONST SI_PCH_DEVICE_INTERRUPT_CONFIG mPchDevIntConfig[] = { {31, 3, SiPchIntA, 16}, // cAVS(Audio, Voice, Speach), INTA is default, programmed in PciCfgSpace 3Dh {31, 4, SiPchIntA, 16}, // SMBus Controller, no default value, programmed in PciCfgSpace 3Dh {31, 6, SiPchIntA, 16}, // GbE Controller, INTA is default, programmed in PciCfgSpace 3Dh {31, 7, SiPchIntA, 16}, // TraceHub, INTA is default, RO register {30, 0, SiPchIntA, 20}, // SerialIo: UART #0, INTA is default, programmed in PCR[SERIALIO] + PCICFGCTRL[7] {30, 1, SiPchIntB, 21}, // SerialIo: UART #1, INTA is default, programmed in PCR[SERIALIO] + PCICFGCTRL[8] {30, 2, SiPchIntC, 22}, // SerialIo: SPI #0, INTA is default, programmed in PCR[SERIALIO] + PCICFGCTRL[10] {30, 3, SiPchIntD, 23}, // SerialIo: SPI #1, INTA is default, programmed in PCR[SERIALIO] + PCICFGCTRL[11] {29, 0, SiPchIntA, 16}, // PCI Express Port 9, INT is default, programmed in PciCfgSpace + FCh {29, 1, SiPchIntB, 17}, // PCI Express Port 10, INT is default, programmed in PciCfgSpace + FCh {29, 2, SiPchIntC, 18}, // PCI Express Port 11, INT is default, programmed in PciCfgSpace + FCh {29, 3, SiPchIntD, 19}, // PCI Express Port 12, INT is default, programmed in PciCfgSpace + FCh {29, 4, SiPchIntA, 16}, // PCI Express Port 13 (SKL PCH-H Only), INT is default, programmed in PciCfgSpace + FCh {29, 5, SiPchIntB, 17}, // PCI Express Port 14 (SKL PCH-H Only), INT is default, programmed in PciCfgSpace + FCh {29, 6, SiPchIntC, 18}, // PCI Express Port 15 (SKL PCH-H Only), INT is default, programmed in PciCfgSpace + FCh {29, 7, SiPchIntD, 19}, // PCI Express Port 16 (SKL PCH-H Only), INT is default, programmed in PciCfgSpace + FCh {28, 0, SiPchIntA, 16}, // PCI Express Port 1, INT is default, programmed in PciCfgSpace + FCh {28, 1, SiPchIntB, 17}, // PCI Express Port 2, INT is default, programmed in PciCfgSpace + FCh {28, 2, SiPchIntC, 18}, // PCI Express Port 3, INT is default, programmed in PciCfgSpace + FCh {28, 3, SiPchIntD, 19}, // PCI Express Port 4, INT is default, programmed in PciCfgSpace + FCh {28, 4, SiPchIntA, 16}, // PCI Express Port 5, INT is default, programmed in PciCfgSpace + FCh {28, 5, SiPchIntB, 17}, // PCI Express Port 6, INT is default, programmed in PciCfgSpace + FCh {28, 6, SiPchIntC, 18}, // PCI Express Port 7, INT is default, programmed in PciCfgSpace + FCh {28, 7, SiPchIntD, 19}, // PCI Express Port 8, INT is default, programmed in PciCfgSpace + FCh {27, 0, SiPchIntA, 16}, // PCI Express Port 17 (PCH-H Only), INT is default, programmed in PciCfgSpace + FCh {27, 1, SiPchIntB, 17}, // PCI Express Port 18 (PCH-H Only), INT is default, programmed in PciCfgSpace + FCh {27, 2, SiPchIntC, 18}, // PCI Express Port 19 (PCH-H Only), INT is default, programmed in PciCfgSpace + FCh {27, 3, SiPchIntD, 19}, // PCI Express Port 20 (PCH-H Only), INT is default, programmed in PciCfgSpace + FCh {27, 4, SiPchIntA, 16}, // PCI Express Port 21 (KBL PCH-H Only), INT is default, programmed in PciCfgSpace + FCh {27, 5, SiPchIntB, 17}, // PCI Express Port 22 (KBL PCH-H Only), INT is default, programmed in PciCfgSpace + FCh {27, 6, SiPchIntC, 18}, // PCI Express Port 23 (KBL PCH-H Only), INT is default, programmed in PciCfgSpace + FCh {27, 7, SiPchIntD, 19}, // PCI Express Port 24 (KBL PCH-H Only), INT is default, programmed in PciCfgSpace + FCh {25, 0, SiPchIntA, 32}, // SerialIo UART Controller #2, INTA is default, programmed in PCR[SERIALIO] + PCICFGCTRL[9] {23, 0, SiPchIntA, 16}, // SATA Controller, INTA is default, programmed in PciCfgSpace + 3Dh {22, 0, SiPchIntA, 16}, // CSME: HECI #1 {22, 1, SiPchIntB, 17}, // CSME: HECI #2 {22, 2, SiPchIntC, 18}, // CSME: IDE-Redirection (IDE-R) {22, 3, SiPchIntD, 19}, // CSME: Keyboard and Text (KT) Redirection {22, 4, SiPchIntA, 16}, // CSME: HECI #3 {21, 0, SiPchIntA, 16}, // SerialIo I2C Controller #0, INTA is default, programmed in PCR[SERIALIO] + PCICFGCTRL[1] {21, 1, SiPchIntB, 17}, // SerialIo I2C Controller #1, INTA is default, programmed in PCR[SERIALIO] + PCICFGCTRL[2] {21, 2, SiPchIntC, 18}, // SerialIo I2C Controller #2, INTA is default, programmed in PCR[SERIALIO] + PCICFGCTRL[3] {21, 3, SiPchIntD, 19}, // SerialIo I2C Controller #3, INTA is default, programmed in PCR[SERIALIO] + PCICFGCTRL[4] {20, 0, SiPchIntA, 16}, // USB 3.0 xHCI Controller, no default value, programmed in PciCfgSpace 3Dh {20, 1, SiPchIntB, 17}, // USB Device Controller (OTG) {20, 2, SiPchIntC, 18}, // Thermal Subsystem {19, 0, SiPchIntA, 20}, // Integrated Sensor Hub }; CONST SI_PCH_DEVICE_INTERRUPT_CONFIG mPchLpDevIntConfig[] = { {31, 3, SiPchIntA, 16}, // HF Audio (Audio, Voice, Speach) {31, 4, SiPchIntA, 16}, // SMBus Controller {31, 6, SiPchIntA, 16}, // GbE Controller {31, 7, SiPchIntA, 16}, // TraceHub {30, 0, SiPchIntA, 20}, // UART #0 {30, 1, SiPchIntB, 21}, // UART #1 {30, 2, SiPchIntC, 22}, // SPI #0 {30, 3, SiPchIntD, 23}, // SPI #1 {29, 0, SiPchIntA, 16}, // PCI Express Port 9 {29, 1, SiPchIntB, 17}, // PCI Express Port 10 {29, 2, SiPchIntC, 18}, // PCI Express Port 11 {29, 3, SiPchIntD, 19}, // PCI Express Port 12 {29, 4, SiPchIntA, 16}, // PCI Express Port 13 {29, 5, SiPchIntB, 17}, // PCI Express Port 14 {29, 6, SiPchIntC, 18}, // PCI Express Port 15 {29, 7, SiPchIntD, 19}, // PCI Express Port 16 {28, 0, SiPchIntA, 16}, // PCI Express Port 1 {28, 1, SiPchIntB, 17}, // PCI Express Port 2 {28, 2, SiPchIntC, 18}, // PCI Express Port 3 {28, 3, SiPchIntD, 19}, // PCI Express Port 4 {28, 4, SiPchIntA, 16}, // PCI Express Port 5 {28, 5, SiPchIntB, 17}, // PCI Express Port 6 {28, 6, SiPchIntC, 18}, // PCI Express Port 7 {28, 7, SiPchIntD, 19}, // PCI Express Port 8 {26, 0, SiPchIntA, 16}, // eMMC {25, 0, SiPchIntA, 32}, // I2C Controller #4 {25, 1, SiPchIntB, 33}, // I2C Controller #5 {25, 2, SiPchIntC, 34}, // UART #2 {23, 0, SiPchIntA, 16}, // SATA Controller {22, 0, SiPchIntA, 16}, // MEI HECI #1 {22, 1, SiPchIntB, 17}, // MEI HECI #2 {22, 2, SiPchIntC, 18}, // IDE-Redirection (IDE-R) {22, 3, SiPchIntD, 19}, // Keyboard and Text (KT) Redirection {22, 4, SiPchIntA, 16}, // MEI HECI #3 {22, 5, SiPchIntB, 17}, // MEI HECI #4 {21, 0, SiPchIntA, 16}, // I2C Controller #0 {21, 1, SiPchIntB, 17}, // I2C Controller #1 {21, 2, SiPchIntC, 18}, // I2C Controller #2 {21, 3, SiPchIntD, 19}, // I2C Controller #3 {20, 0, SiPchIntA, 16}, // USB 3.0 xHCI Controller {20, 1, SiPchIntB, 17}, // USB Device Controller (OTG) {20, 3, SiPchIntA, 16}, // CNVi WiFi {20, 5, SiPchIntD, 19}, // SDXC {19, 0, SiPchIntA, 20}, // Integrated Sensor Hub {18, 0, SiPchIntA, 16}, // Thermal Subsystem {18, 5, SiPchIntA, 16}, // UFS {18, 6, SiPchIntB, 24} // SPI #2 }; CONST UINT8 mPchSerialIoDevMode[PCH_MAX_SERIALIO_CONTROLLERS] = { 1 /* I2C0 */, 1 /* I2C1 */, 0 /* I2C2 */, 0 /* I2C3 */, 0 /* SPI0 */, 0 /* SPI1 */, 1 /* UART0 */, 0 /* UART1 */, 3 /* UART2 */ }; CONST UINT8 mPchLpSerialIoDevMode[PCH_MAX_SERIALIO_CONTROLLERS] = { 1 /* I2C0 */, 1 /* I2C1 */, 0 /* I2C2 */, 0 /* I2C3 */, 0 /* SPI0 */, 0 /* SPI1 */, 0 /* UART0 */, 0 /* UART1 */, 0 /* UART2 */ }; STATIC SMMBASE_INFO mSmmBaseInfo = { { BL_PLD_COMM_SIG, SMMBASE_INFO_COMM_ID, 0, 0 } }; STATIC S3_SAVE_REG mS3SaveReg = { { BL_PLD_COMM_SIG, S3_SAVE_REG_COMM_ID, 1, 0 }, { { REG_TYPE_IO, WIDE32, { 0, 0}, (ACPI_BASE_ADDRESS + R_ACPI_IO_SMI_EN), 0x00000000 } } }; VOID EnableLegacyRegions ( VOID ); /** Clear SMI sources **/ VOID ClearSmi ( VOID ) { UINT32 SmiEn; UINT32 SmiSts; UINT32 Pm1Sts; UINT16 Pm1Cnt; SmiEn = IoRead32 ((UINTN)(UINT32)(ACPI_BASE_ADDRESS + R_ACPI_IO_SMI_EN)); if (((SmiEn & B_ACPI_IO_SMI_EN_GBL_SMI) !=0) && ((SmiEn & B_ACPI_IO_SMI_EN_EOS) !=0)) { return; } // // Clear the status before setting smi enable // SmiSts = IoRead32 ((UINTN)(UINT32)(ACPI_BASE_ADDRESS + R_ACPI_IO_SMI_STS)); Pm1Sts = IoRead32 ((UINTN)(ACPI_BASE_ADDRESS + R_ACPI_IO_PM1_STS)); Pm1Cnt = IoRead16 ((UINTN)(ACPI_BASE_ADDRESS + R_ACPI_IO_PM1_CNT)); // Clear RTC alarm and corresponding Pm1Sts only if wake-up source is RTC SMI# if (((Pm1Sts & B_ACPI_IO_PM1_STS_RTC_EN) != 0) && ((Pm1Sts & B_ACPI_IO_PM1_STS_RTC) != 0) && ((Pm1Cnt & B_ACPI_IO_PM1_CNT_SCI_EN) == 0)) { IoWrite8 (R_RTC_IO_INDEX, R_RTC_IO_REGC); IoRead8 (R_RTC_IO_TARGET); /* RTC alarm is cleared upon read */ Pm1Sts |= B_ACPI_IO_PM1_STS_RTC; } SmiSts |= ( B_ACPI_IO_SMI_STS_SMBUS | B_ACPI_IO_SMI_STS_PERIODIC | B_ACPI_IO_SMI_STS_TCO | B_ACPI_IO_SMI_STS_MCSMI | B_ACPI_IO_SMI_STS_SWSMI_TMR | B_ACPI_IO_SMI_STS_APM | B_ACPI_IO_SMI_STS_ON_SLP_EN | B_ACPI_IO_SMI_STS_BIOS ); Pm1Sts |= ( B_ACPI_IO_PM1_STS_WAK | B_ACPI_IO_PM1_STS_PRBTNOR | B_ACPI_IO_PM1_STS_PWRBTN | B_ACPI_IO_PM1_STS_GBL | B_ACPI_IO_PM1_STS_TMROF ); IoWrite32 ((UINTN)(UINT32)(ACPI_BASE_ADDRESS + R_ACPI_IO_SMI_STS), SmiSts); IoWrite16 ((UINTN) (ACPI_BASE_ADDRESS + R_ACPI_IO_PM1_STS), (UINT16) Pm1Sts); // Clear GPE0 STS in case some bits are set IoOr32 ((UINTN)(UINT32)(ACPI_BASE_ADDRESS + R_ACPI_IO_GPE0_STS_127_96), 0); } // // Update ACPI PerfomanceStates tables // /** Patch the native _PSS package with the EIST values Uses ratio/VID values from the FVID table to fix up the control values in the _PSS. (1) Find _PSS package: (1.1) Find the _PR_CPU0 scope. (1.2) Save a pointer to the package length. (1.3) Find the _PSS AML name object. (2) Resize the _PSS package. (3) Fix up the _PSS package entries (3.1) Check Turbo mode support. (3.2) Check Dynamic FSB support. (4) Fix up the Processor block and \_PR_CPU0 Scope length. (5) Update SSDT Header with new length. @retval EFI_SUCCESS - on success @retval EFI_NOT_FOUND - if _PR_.CPU0 scope is not foud in the ACPI tables **/ EFI_STATUS PatchCpuIstTable ( EFI_ACPI_DESCRIPTION_HEADER *Table, IN GLOBAL_NVS_AREA *GlobalNvs ) { UINT8 *CurrPtr; UINT8 *EndOfTable; UINT8 Index; UINT16 NewPackageLength; UINT16 LpssMaxPackageLength; UINT16 TpssMaxPackageLength; UINT16 Temp; UINT16 *PackageLength; UINT16 *ScopePackageLengthPtr; UINT32 *Signature; PSS_PACKAGE_LAYOUT *PssPackage; MSR_REGISTER TempMsr; UINT16 MaximumEfficiencyRatio; UINT16 MaximumNonTurboRatio; UINT16 PnPercent; UINT16 NumberOfStates; CPU_NVS_AREA *CpuNvs; CpuNvs = (CPU_NVS_AREA *) &GlobalNvs->CpuNvs; ScopePackageLengthPtr = NULL; PssPackage = NULL; // // Get Maximum Efficiency bus ratio (LFM) from Platform Info MSR Bits[47:40] // Get Maximum Non Turbo bus ratio from Platform Info MSR Bits[15:8] // TempMsr.Qword = AsmReadMsr64 (MSR_PLATFORM_INFO); MaximumEfficiencyRatio = TempMsr.Bytes.SixthByte; MaximumNonTurboRatio = TempMsr.Bytes.SecondByte; NumberOfStates = mFvidPointer[0].FvidHeader.EistStates; DEBUG ((DEBUG_INFO, "FVID number of states: %d\n", NumberOfStates)); /// /// Calculate new package length /// NewPackageLength = Temp = (UINT16) (NumberOfStates * sizeof (PSS_PACKAGE_LAYOUT) + 3); LpssMaxPackageLength = (UINT16) (LPSS_FVID_MAX_STATES * sizeof (PSS_PACKAGE_LAYOUT) + 3); TpssMaxPackageLength = (UINT16) (TPSS_FVID_MAX_STATES * sizeof (PSS_PACKAGE_LAYOUT) + 3); /// /// Locate the SSDT package in the IST table /// CurrPtr = (UINT8 *) Table; EndOfTable = (UINT8 *) (CurrPtr + Table->Length); for (CurrPtr = (UINT8 *) Table; CurrPtr <= EndOfTable; CurrPtr++) { Signature = (UINT32 *) (CurrPtr + 1); /// /// If we find the _SB_PR00 scope, save a pointer to the package length /// if ((*CurrPtr == AML_SCOPE_OP) && (*(Signature + 1) == SIGNATURE_32 ('_', 'S', 'B', '_')) && (*(Signature + 2) == SIGNATURE_32 ('P', 'R', '0', '0')) ) { ScopePackageLengthPtr = (UINT16 *) (CurrPtr + 1); } /// /// Patch the LPSS package with 16 P-states for _PSS Method /// if ((*CurrPtr == AML_NAME_OP) && (*Signature == SIGNATURE_32 ('L', 'P', 'S', 'S'))) { /* Check table dimensions. PSS package reserve space for LPSS_FVID_MAX_STATES number of P-states so check if the current number of P- states is more than LPSS_FVID_MAX_STATES. Also need to update the SSDT contents if the current number of P-states is less than LPSS_FVID_MAX_STATES. */ PackageLength = (UINT16 *) (CurrPtr + 6); if (NumberOfStates > LPSS_FVID_MAX_STATES) { *(CurrPtr + 8) = (UINT8) LPSS_FVID_MAX_STATES; /// /// Update the Package length in AML package length format /// *PackageLength = ((LpssMaxPackageLength & 0x0F) | 0x40) | ((LpssMaxPackageLength << 4) & 0x0FF00); } else { *(CurrPtr + 8) = (UINT8) NumberOfStates; /// /// Update the Package length in AML package length format /// *PackageLength = ((NewPackageLength & 0x0F) | 0x40) | ((Temp << 4) & 0x0FF00); /// /// Move SSDT contents /// CopyMem ((CurrPtr + NewPackageLength), (CurrPtr + LpssMaxPackageLength), EndOfTable - (CurrPtr + LpssMaxPackageLength)); /// /// Save the new end of the SSDT /// EndOfTable = EndOfTable - (LpssMaxPackageLength - NewPackageLength); } PssPackage = (PSS_PACKAGE_LAYOUT *) (CurrPtr + 9); if (NumberOfStates > LPSS_FVID_MAX_STATES) { for (Index = 1; Index <= LPSS_FVID_MAX_STATES; Index++) { /// /// Update the _PSS table. If Turbo mode is supported, add one to the Max Non-Turbo frequency /// if ((CpuNvs->PpmFlags & PPM_TURBO) && (Index == 1)) { PssPackage->CoreFrequency = (UINT32) ((mFvidPointer[Index + 1].FvidState.Limit16BusRatio)* 100) + 1; } else if (mFvidPointer[Index].FvidState.Limit16BusRatio < MaximumEfficiencyRatio) { // // If cTDP Down Ratio == LFM, set it to 1% lower than LFM. // PnPercent = (MaximumEfficiencyRatio * 100) / MaximumNonTurboRatio; PssPackage->CoreFrequency = (MaximumNonTurboRatio * (PnPercent - 1)); // Simplified Calculation. } else { PssPackage->CoreFrequency = (UINT32) (mFvidPointer[Index].FvidState.Limit16BusRatio) * 100; } PssPackage->Power = (UINT32) mFvidPointer[Index].FvidState.Limit16Power; /// /// If it's PSS table, Control is the PERF_CTL value. /// Status entry is the same as control entry. /// TransLatency uses 10 /// PssPackage->TransLatency = NATIVE_PSTATE_LATENCY; PssPackage->Control = (UINT32) LShiftU64 (mFvidPointer[Index].FvidState.Limit16BusRatio, 8); // // Ensure any future OS would not look for the IA32_PERF_STATUS MSR to check if the value matches // if (mFvidPointer[Index].FvidState.Limit16BusRatio < MaximumEfficiencyRatio) { PssPackage->Status = (UINT32) LShiftU64 (MaximumEfficiencyRatio, 8); } else { PssPackage->Status = (UINT32) LShiftU64 (mFvidPointer[Index].FvidState.Limit16BusRatio, 8); } PssPackage->BmLatency = PSTATE_BM_LATENCY; PssPackage++; } } else { for (Index = 1; Index <= NumberOfStates; Index++) { /// /// Update the _PSS table. If Turbo mode is supported, add one to the Max Non-Turbo frequency /// if ((CpuNvs->PpmFlags & PPM_TURBO) && (Index == 1)) { PssPackage->CoreFrequency = (UINT32) ((mFvidPointer[Index + 1].FvidState.BusRatio)* 100) + 1; } else if (mFvidPointer[Index].FvidState.BusRatio < MaximumEfficiencyRatio) { // // If cTDP Down Ratio == LFM, set it to 1% lower than LFM. // PnPercent = (MaximumEfficiencyRatio * 100) / MaximumNonTurboRatio; PssPackage->CoreFrequency = (MaximumNonTurboRatio * (PnPercent - 1)); // Simplified Calculation. } else { PssPackage->CoreFrequency = (UINT32) (mFvidPointer[Index].FvidState.BusRatio) * 100; } PssPackage->Power = (UINT32) mFvidPointer[Index].FvidState.Power; /// /// If it's PSS table, Control is the PERF_CTL value. /// Status entry is the same as control entry. /// TransLatency uses 10 /// PssPackage->TransLatency = NATIVE_PSTATE_LATENCY; PssPackage->Control = (UINT32) LShiftU64 (mFvidPointer[Index].FvidState.BusRatio, 8); // // Ensure any future OS would not look for the IA32_PERF_STATUS MSR to check if the value matches // if (mFvidPointer[Index].FvidState.BusRatio < MaximumEfficiencyRatio) { PssPackage->Status = (UINT32) LShiftU64 (MaximumEfficiencyRatio, 8); } else { PssPackage->Status = (UINT32) LShiftU64 (mFvidPointer[Index].FvidState.BusRatio, 8); } PssPackage->BmLatency = PSTATE_BM_LATENCY; PssPackage++; } } } /// /// Patch the TPSS package with no limit P-states for _PSS Method /// if ((*CurrPtr == AML_NAME_OP) && (*Signature == SIGNATURE_32 ('T', 'P', 'S', 'S'))) { ASSERT (NumberOfStates <= TPSS_FVID_MAX_STATES); if (NumberOfStates <= TPSS_FVID_MAX_STATES) { *(CurrPtr + 8) = (UINT8) NumberOfStates; PackageLength = (UINT16 *) (CurrPtr + 6); /// /// Update the Package length in AML package length format /// *PackageLength = ((NewPackageLength & 0x0F) | 0x40) | ((Temp << 4) & 0x0FF00); /// /// Move SSDT contents /// CopyMem ((CurrPtr + NewPackageLength), (CurrPtr + TpssMaxPackageLength), EndOfTable - (CurrPtr + TpssMaxPackageLength)); /// /// Save the new end of the SSDT /// EndOfTable = EndOfTable - (TpssMaxPackageLength - NewPackageLength); } PssPackage = (PSS_PACKAGE_LAYOUT *) (CurrPtr + 9); for (Index = 1; Index <= NumberOfStates; Index++) { /// /// Update the _PSS table. If Turbo mode is supported, add one to the Max Non-Turbo frequency /// if ((CpuNvs->PpmFlags & PPM_TURBO) && (Index == 1)) { PssPackage->CoreFrequency = (UINT32) ((mFvidPointer[Index + 1].FvidState.BusRatio)* 100) + 1; } else if (mFvidPointer[Index].FvidState.BusRatio < MaximumEfficiencyRatio) { // // If cTDP Down Ratio == LFM, set it to 1% lower than LFM. // PnPercent = (MaximumEfficiencyRatio * 100) / MaximumNonTurboRatio; PssPackage->CoreFrequency = (MaximumNonTurboRatio * (PnPercent - 1)); // Simplified Calculation. } else { PssPackage->CoreFrequency = (UINT32) (mFvidPointer[Index].FvidState.BusRatio) * 100; } PssPackage->Power = (UINT32) mFvidPointer[Index].FvidState.Power; /// /// If it's PSS table, Control is the PERF_CTL value. /// Status entry is the same as control entry. /// TransLatency uses 10 /// PssPackage->TransLatency = NATIVE_PSTATE_LATENCY; PssPackage->Control = (UINT32) LShiftU64 (mFvidPointer[Index].FvidState.BusRatio, 8); // // Ensure any future OS would not look for the IA32_PERF_STATUS MSR to check if the value matches // if (mFvidPointer[Index].FvidState.BusRatio < MaximumEfficiencyRatio) { PssPackage->Status = (UINT32) LShiftU64 (MaximumEfficiencyRatio, 8); } else { PssPackage->Status = (UINT32) LShiftU64 (mFvidPointer[Index].FvidState.BusRatio, 8); } PssPackage->BmLatency = PSTATE_BM_LATENCY; PssPackage++; } } } ASSERT (ScopePackageLengthPtr != NULL); if (ScopePackageLengthPtr == NULL) { return EFI_NOT_FOUND; } /// /// Update the Package length in AML package length format /// CurrPtr = (UINT8 *) ScopePackageLengthPtr; NewPackageLength = Temp = (UINT16) (EndOfTable - CurrPtr); *ScopePackageLengthPtr = ((NewPackageLength & 0x0F) | 0x40) | ((Temp << 4) & 0x0FF00); Table->Length = (UINT32) (EndOfTable - (UINT8 *) Table); return EFI_SUCCESS; } /** This function updates CpuSsdt table PNVS/LPSS dynamically. @param[in] Table Pointer to ACPI table @param[in] Gnvs Pointer to platform global NVS data @retval none **/ VOID PatchCpuSsdtTable ( IN EFI_ACPI_DESCRIPTION_HEADER *Table, IN GLOBAL_NVS_AREA *GlobalNvs ) { CPU_NVS_AREA *CpuNvs; UINT8 *CurrPtr; UINT32 *Signature; CpuNvs = (CPU_NVS_AREA *) &GlobalNvs->CpuNvs; CurrPtr = (UINT8 *) Table; for (CurrPtr = (UINT8 *) Table; CurrPtr <= ((UINT8 *) Table + Table->Length); CurrPtr++) { Signature = (UINT32 *) (CurrPtr + 1); /// /// Update the CPU GlobalNvs area /// if ((*CurrPtr == AML_EXT_REGION_OP) && *Signature == SIGNATURE_32 ('P', 'N', 'V', 'S')) { ASSERT (*(UINT32 *) (CurrPtr + 1 + sizeof (*Signature) + 2) == 0xFFFF0000); ASSERT (*(UINT16 *) (CurrPtr + 1 + sizeof (*Signature) + 2 + sizeof (UINT32) + 1) == 0xAA55); /// /// Cpu Nvs Area address /// DEBUG ((DEBUG_INFO, "CPU PNVS Base Old=0x%08X New=0x%08X\n", *(UINT32 *)(CurrPtr + 1 + sizeof (*Signature) + 2), CpuNvs)); *(UINT32 *) (CurrPtr + 1 + sizeof (*Signature) + 2) = (UINT32) (UINTN) CpuNvs; /// /// Cpu Nvs Area size /// DEBUG ((DEBUG_INFO, "CPU PNVS Size Old=0x%04X New=0x%04X\n", *(UINT16 *)(CurrPtr + 1 + sizeof (*Signature) + 2 + sizeof (UINT32) + 1), sizeof (CPU_NVS_AREA))); *(UINT16 *) (CurrPtr + 1 + sizeof (*Signature) + 2 + sizeof (UINT32) + 1) = sizeof (CPU_NVS_AREA); break; } } } /** Update bootloader reserved region. This function will erase bootloader reserved region when statemachine flag indicates a value of 0xFC. This condition will occur when power cycle happens in between clearing IBB signal and setting state machine flag to 0xFF. @retval EFI_SUCCESS The operation completed successfully. @retval EFI_NOT_FOUND Flash map pointer not founc @retval others Error setting state machine flag to 0xFF. **/ EFI_STATUS UpdateBlRsvdRegion () { UINT32 RsvdBase; UINT32 RsvdSize; EFI_STATUS Status; FLASH_MAP *FlashMap; FW_UPDATE_STATUS FwUpdStatus; // // Get flash map pointer // FlashMap = GetFlashMapPtr(); if (FlashMap == NULL) { DEBUG((DEBUG_ERROR, "Could not get flash map\n")); return EFI_NOT_FOUND; } // // If StateMachine is 0xFC, erase the bootloader reserved region // Status = GetComponentInfo(FLASH_MAP_SIG_BLRESERVED, &RsvdBase, &RsvdSize); if (EFI_ERROR(Status)) { DEBUG((DEBUG_ERROR, "Getting component info for bl rsvd region failed with status: %r\n", Status)); return Status; } CopyMem (&FwUpdStatus, (VOID *)(UINTN)RsvdBase, sizeof(FW_UPDATE_STATUS)); if (FwUpdStatus.StateMachine == FW_UPDATE_SM_PART_AB) { Status = SpiFlashErase (FlashRegionBios, FlashMap->RomSize - (~RsvdBase + 1), RsvdSize); if (EFI_ERROR (Status)) { DEBUG((DEBUG_ERROR, "Erasing Bootloader Reserved region failed with status: %r\n", Status)); return Status; } } return EFI_SUCCESS; } /** Add a Smbios type string into a buffer **/ STATIC EFI_STATUS AddSmbiosTypeString ( SMBIOS_TYPE_STRINGS *Dest, UINT8 Type, UINT8 Index, CHAR8 *String ) { UINTN Length; Dest->Type = Type; Dest->Idx = Index; if (String != NULL) { Length = AsciiStrLen (String); Dest->String = (CHAR8 *)AllocateZeroPool (Length + 1); if (Dest->String == NULL) { return EFI_OUT_OF_RESOURCES; } CopyMem (Dest->String, String, Length); } return EFI_SUCCESS; } /** Initialize necessary information for Smbios @retval EFI_SUCCESS Initialized necessary information successfully @retval EFI_OUT_OF_RESOURCES Failed to allocate memory for Smbios info **/ EFI_STATUS InitializeSmbiosInfo ( VOID ) { CHAR8 TempStrBuf[SMBIOS_STRING_MAX_LENGTH]; UINT16 Index; UINT16 PlatformId; UINTN Length; SMBIOS_TYPE_STRINGS *TempSmbiosStrTbl; BOOT_LOADER_VERSION *VerInfoTbl; VOID *SmbiosStringsPtr; Index = 0; PlatformId = GetPlatformId (); TempSmbiosStrTbl = (SMBIOS_TYPE_STRINGS *) AllocateTemporaryMemory (0); VerInfoTbl = GetVerInfoPtr (); // // SMBIOS_TYPE_BIOS_INFORMATION // AddSmbiosTypeString (&TempSmbiosStrTbl[Index++], SMBIOS_TYPE_BIOS_INFORMATION, 1, "Intel Corporation"); if (VerInfoTbl != NULL) { AsciiSPrint (TempStrBuf, sizeof (TempStrBuf), "SB_CML.%03d.%03d.%03d.%03d.%03d.%05d.%c-%016lX%a\0", VerInfoTbl->ImageVersion.SecureVerNum, VerInfoTbl->ImageVersion.CoreMajorVersion, VerInfoTbl->ImageVersion.CoreMinorVersion, VerInfoTbl->ImageVersion.ProjMajorVersion, VerInfoTbl->ImageVersion.ProjMinorVersion, VerInfoTbl->ImageVersion.BuildNumber, VerInfoTbl->ImageVersion.BldDebug ? 'D' : 'R', VerInfoTbl->SourceVersion, VerInfoTbl->ImageVersion.Dirty ? "-dirty" : ""); } else { AsciiSPrint (TempStrBuf, sizeof (TempStrBuf), "%a\0", "Unknown"); } AddSmbiosTypeString (&TempSmbiosStrTbl[Index++], SMBIOS_TYPE_BIOS_INFORMATION, 2, TempStrBuf); AddSmbiosTypeString (&TempSmbiosStrTbl[Index++], SMBIOS_TYPE_BIOS_INFORMATION, 3, "Unknown date"); // // SMBIOS_TYPE_SYSTEM_INFORMATION // AddSmbiosTypeString (&TempSmbiosStrTbl[Index++], SMBIOS_TYPE_SYSTEM_INFORMATION, 1, "Intel Corporation"); if ((PlatformId == PLATFORM_ID_CML_S) || (PlatformId == PLATFORM_ID_CML_H)) { AsciiSPrint (TempStrBuf, sizeof (TempStrBuf), "%a\0", "CometLake Client Platform"); } else if (PlatformId == PLATFORM_ID_CML_V) { AsciiSPrint (TempStrBuf, sizeof (TempStrBuf), "%a\0", "CometLake PCH-V Client Platform"); } else { AsciiSPrint (TempStrBuf, sizeof (TempStrBuf), "%a\0", "Unknown"); } AddSmbiosTypeString (&TempSmbiosStrTbl[Index++], SMBIOS_TYPE_SYSTEM_INFORMATION, 2, TempStrBuf); AddSmbiosTypeString (&TempSmbiosStrTbl[Index++], SMBIOS_TYPE_SYSTEM_INFORMATION, 3, "0.1"); AddSmbiosTypeString (&TempSmbiosStrTbl[Index++], SMBIOS_TYPE_SYSTEM_INFORMATION, 4, "System Serial Number"); AddSmbiosTypeString (&TempSmbiosStrTbl[Index++], SMBIOS_TYPE_SYSTEM_INFORMATION, 5, "System SKU Number"); AddSmbiosTypeString (&TempSmbiosStrTbl[Index++], SMBIOS_TYPE_SYSTEM_INFORMATION, 6, "CannonLake Client System"); // // SMBIOS_TYPE_BASEBOARD_INFORMATION // AddSmbiosTypeString (&TempSmbiosStrTbl[Index++], SMBIOS_TYPE_BASEBOARD_INFORMATION, 1, "Intel Corporation"); if (PlatformId == PLATFORM_ID_CML_S) { AsciiSPrint (TempStrBuf, sizeof (TempStrBuf), "%a\0", "CometLake S 82 UDIMM RVP"); } else if (PlatformId == PLATFORM_ID_CML_H) { AsciiSPrint (TempStrBuf, sizeof (TempStrBuf), "%a\0", "CometLake H DDR4 RVP"); } else if (PlatformId == PLATFORM_ID_CML_V) { AsciiSPrint (TempStrBuf, sizeof (TempStrBuf), "%a\0", "CometLake PCH-V RVP"); } else { AsciiSPrint (TempStrBuf, sizeof (TempStrBuf), "%a\0", "Unknown"); } AddSmbiosTypeString (&TempSmbiosStrTbl[Index++], SMBIOS_TYPE_BASEBOARD_INFORMATION, 2, TempStrBuf); AddSmbiosTypeString (&TempSmbiosStrTbl[Index++], SMBIOS_TYPE_BASEBOARD_INFORMATION, 3, "1"); AddSmbiosTypeString (&TempSmbiosStrTbl[Index++], SMBIOS_TYPE_BASEBOARD_INFORMATION, 4, "Board Serial Number"); // // SMBIOS_TYPE_PROCESSOR_INFORMATION : TBD // // // SMBIOS_TYPE_END_OF_TABLE // AddSmbiosTypeString (&TempSmbiosStrTbl[Index++], SMBIOS_TYPE_END_OF_TABLE, 0, NULL); Length = sizeof (SMBIOS_TYPE_STRINGS) * Index; SmbiosStringsPtr = AllocatePool (Length); if (SmbiosStringsPtr == NULL) { return EFI_OUT_OF_RESOURCES; } CopyMem (SmbiosStringsPtr, TempSmbiosStrTbl, Length); (VOID) PcdSet32S (PcdSmbiosStringsPtr, (UINT32)(UINTN)SmbiosStringsPtr); (VOID) PcdSet16S (PcdSmbiosStringsCnt, Index); return EFI_SUCCESS; } /** Print the output of the GPIO Config table that was read from CfgData. @param GpioPinNum Number of GPIO entries in the table. @param GpioConfData GPIO Config Data that was read from the Configuration region either from internal or external source. **/ VOID PrintGpioConfigTable ( IN UINT32 GpioPinNum, IN VOID* GpioConfData ) { GPIO_INIT_CONFIG *GpioInitConf; UINT32 *PadDataPtr; UINT32 Index; GpioInitConf = (GPIO_INIT_CONFIG *)GpioConfData; for (Index = 0; Index < GpioPinNum; Index++) { PadDataPtr = (UINT32 *)&GpioInitConf->GpioConfig; DEBUG ((DEBUG_VERBOSE, "GPIO PAD: 0x%08X DATA: 0x%08X 0x%08X\n", GpioInitConf->GpioPad, PadDataPtr[0], PadDataPtr[1])); GpioInitConf++; } } /** Retreive PadInfo embedded inside DW1 of GPIO CFG DATA. Prepare a PadInfo DWORD first, add into the GpioTable, followed by DW0 and DW1 directly from GPIO CFG DATA. This format of GpioTable is what the Gpio library expects. @param GpioTable Pointer to the GpioTable to be updated @param GpioCfg Pointer to the cfg data @param Offset Index of a particulr pin's DW0, DW1 in GpioCfg @retval GpioTable Pointer to fill the next gpio item **/ UINT8 * FillGpioTable ( IN UINT8 *GpioTable, IN GPIO_CFG_HDR *GpioCfg, IN UINT32 Offset, IN UINT8 ChipsetId ) { GPIO_CFG_DATA_DW1 *Dw1; UINT32 *GpioItem; GPIO_PAD_FIELD GpioPad = { 0, 0, 0, 0 }; // // Get the DW1 and extract PadInfo // GpioItem = (UINT32 *) (GpioCfg->GpioTableData + Offset); Dw1 = (GPIO_CFG_DATA_DW1 *) (&GpioItem[1]); GpioPad.PadNum = (UINT16) Dw1->PadNum; GpioPad.GrpIdx = (UINT8) Dw1->GrpIdx; GpioPad.ChipsetId = ChipsetId; // // Remove PadInfo data from DW1 // Dw1->PadNum = 0; Dw1->GrpIdx = 0; // // Copy PadInfo(PinOffset), DW0, DW1 // CopyMem (GpioTable, (VOID *)&GpioPad, sizeof(GPIO_PAD_FIELD)); GpioTable += sizeof(GPIO_PAD_FIELD); CopyMem (GpioTable, GpioItem, GpioCfg->GpioItemSize); GpioTable += GpioCfg->GpioItemSize; return GpioTable; } /** Configure GPIOs @retval EFI_SUCCESS The function completed successfully @retval EFI_INVALID_PARAMETER Invalid group or pad number @retval EFI_NOT_FOUND GPIO configuration data not found #retval EFI_LOAD_ERROR GPIO configuration data corrupted **/ EFI_STATUS GpioInit ( VOID ) { GPIO_CFG_HDR *GpioCfgCurrHdr; GPIO_CFG_HDR *GpioCfgBaseHdr; GPIO_CFG_HDR *GpioCfgHdr; UINT32 GpioEntries; UINT32 Index; UINT32 Offset; UINT8 *GpioCfgDataBuffer; UINT8 *GpioTable; UINT8 ChipsetId = 0; //Find the GPIO CFG HDR GpioCfgCurrHdr = (GPIO_CFG_HDR *)FindConfigDataByTag (CDATA_GPIO_TAG); if (GpioCfgCurrHdr == NULL) { return EFI_NOT_FOUND; } GpioEntries = 0; GpioCfgBaseHdr = NULL; //Find the GPIO CFG Data based on Platform ID. GpioTableData is the start of the GPIO entries if (GpioCfgCurrHdr->GpioBaseTableId < 16) { GpioCfgBaseHdr = (GPIO_CFG_HDR *)FindConfigDataByPidTag (GpioCfgCurrHdr->GpioBaseTableId, CDATA_GPIO_TAG); if (GpioCfgBaseHdr == NULL) { DEBUG ((DEBUG_ERROR, "Cannot find base GPIO table for platform ID %d\n", GpioCfgCurrHdr->GpioBaseTableId)); return EFI_NOT_FOUND; } if (GpioCfgCurrHdr->GpioItemSize != GpioCfgBaseHdr->GpioItemSize) { DEBUG ((DEBUG_ERROR, "Inconsistent GPIO item size\n")); return EFI_LOAD_ERROR; } GpioCfgHdr = GpioCfgBaseHdr; } else { GpioCfgHdr = GpioCfgCurrHdr; } Offset = 0; GpioTable = (UINT8 *)AllocateTemporaryMemory (0); //allocate new buffer if (GpioTable == NULL) { return EFI_OUT_OF_RESOURCES; } GpioCfgDataBuffer = GpioTable; ChipsetId = 0; if (IsPchH()) { ChipsetId = CNL_H_CHIPSET_ID; } else if (IsPchLp()) { ChipsetId = CNL_LP_CHIPSET_ID; } for (Index = 0; Index < GpioCfgHdr->GpioItemCount; Index++) { if (GpioCfgCurrHdr->GpioBaseTableBitMask[Index >> 3] & (1 << (Index & 7))) { GpioTable = FillGpioTable (GpioTable, GpioCfgHdr, Offset, ChipsetId); GpioEntries++; } Offset += GpioCfgHdr->GpioItemSize; } Offset = 0; if (GpioCfgBaseHdr != NULL) { for (Index = 0; Index < GpioCfgCurrHdr->GpioItemCount; Index++) { GpioTable = FillGpioTable (GpioTable, GpioCfgCurrHdr, Offset, ChipsetId); GpioEntries++; Offset += GpioCfgCurrHdr->GpioItemSize; } } DEBUG_CODE_BEGIN (); PrintGpioConfigTable (GpioEntries, GpioCfgDataBuffer); DEBUG_CODE_END (); return GpioConfigurePads (GpioEntries, (GPIO_INIT_CONFIG *) GpioCfgDataBuffer); } /** Initialize Board specific things in Stage2 Phase @param[in] InitPhase Indicates a board init phase to be initialized **/ VOID EFIAPI BoardInit ( IN BOARD_INIT_PHASE InitPhase ) { GEN_CFG_DATA *GenericCfgData; SILICON_CFG_DATA *SiliconCfgData; EFI_STATUS Status; UINT32 RgnBase; UINT32 RgnSize; UINTN LpcBase; UINTN SpiBaseAddress; UINT16 TcoBase; UINT32 SaMcAddress; UINT32 AddressPort; UINTN SpiBar0; UINT32 Length; UINT32 TsegBase; UINT32 TsegSize; UINT32 PayloadSelGpioData; UINT32 PayloadSelGpioPad; UINT32 PayloadId; UINTN PmcBaseAddr; EFI_PEI_GRAPHICS_INFO_HOB *FspGfxHob; VOID *FspHobList; BL_SW_SMI_INFO *BlSwSmiInfo; switch (InitPhase) { case PreSiliconInit: EnableLegacyRegions (); GpioInit (); SpiConstructor (); PayloadId = GetPayloadId (); GenericCfgData = (GEN_CFG_DATA *)FindConfigDataByTag (CDATA_GEN_TAG); if (GenericCfgData != NULL) { if (GenericCfgData->PayloadId == AUTO_PAYLOAD_ID_SIGNATURE) { PayloadId = 0; } else { PayloadId = GenericCfgData->PayloadId; } } // // Switch payloads based on configured GPIO pin // SiliconCfgData = (SILICON_CFG_DATA *)FindConfigDataByTag (CDATA_SILICON_TAG); if ((SiliconCfgData != NULL) && (SiliconCfgData->PayloadSelGpio.Enable != 0)){ if (IsPchLp() == TRUE) { PayloadSelGpioPad = GPIO_CFG_PIN_TO_PAD(SiliconCfgData->PayloadSelGpio) | (GPIO_CNL_LP_CHIPSET_ID << 24); } else { PayloadSelGpioPad = GPIO_CFG_PIN_TO_PAD(SiliconCfgData->PayloadSelGpio) | (GPIO_CNL_H_CHIPSET_ID << 24); } Status = GpioGetInputValue (PayloadSelGpioPad, &PayloadSelGpioData); if (!EFI_ERROR (Status)) { if (PayloadSelGpioData == 0) { PayloadId = 0; } else { if ((GenericCfgData != NULL) && (GenericCfgData->PayloadId == AUTO_PAYLOAD_ID_SIGNATURE)) { PayloadId = UEFI_PAYLOAD_ID_SIGNATURE; } } DEBUG ((DEBUG_INFO, "Set PayloadId to 0x%08X based on GPIO config\n", PayloadId)); } } mSiliconCfgData = SiliconCfgData; SetPayloadId (PayloadId); if (GetBootMode () != BOOT_ON_FLASH_UPDATE) { UpdateBlRsvdRegion (); } Status = GetComponentInfo (FLASH_MAP_SIG_VARIABLE, &RgnBase, &RgnSize); if (!EFI_ERROR(Status)) { VariableConstructor (RgnBase, RgnSize); } break; case PostSiliconInit: // Set TSEG base/size PCD TsegBase = MmioRead32 (TO_MM_PCI_ADDRESS (0x00000000) + TSEG) & ~0xF; TsegSize = MmioRead32 (TO_MM_PCI_ADDRESS (0x00000000) + BGSM) & ~0xF; TsegSize -= TsegBase; (VOID) PcdSet32S (PcdSmramTsegBase, TsegBase); (VOID) PcdSet32S (PcdSmramTsegSize, (UINT32)TsegSize); // // Reinitialize PCI bus master and memory space for Graphics device // Reinitialize the BAR for Graphics device // if (PcdGetBool (PcdFramebufferInitEnabled)) { FspGfxHob = NULL; FspHobList = GetFspHobListPtr (); if (FspHobList != NULL) { FspGfxHob = (EFI_PEI_GRAPHICS_INFO_HOB *)GetGuidHobData (FspHobList, &Length, &gEfiGraphicsInfoHobGuid); } if (FspGfxHob != NULL) { PciAnd8 (PCI_LIB_ADDRESS(SA_IGD_BUS, SA_IGD_DEV, SA_IGD_FUN_0, PCI_COMMAND_OFFSET), \ (UINT8)(~EFI_PCI_COMMAND_BUS_MASTER)); PciWrite32 (PCI_LIB_ADDRESS(SA_IGD_BUS, SA_IGD_DEV, SA_IGD_FUN_0, PCI_BASE_ADDRESSREG_OFFSET + 0x8), \ (UINT32)FspGfxHob->FrameBufferBase); // // Programming dummy value for the BAR // This is just to no leave the device without BAR, this value will be reprogrammed during // PCI enumeration. // PciWrite32 (PCI_LIB_ADDRESS(SA_IGD_BUS, SA_IGD_DEV, SA_IGD_FUN_0, PCI_BASE_ADDRESSREG_OFFSET), \ (UINT32)0xC0000000); PciWrite8 (PCI_LIB_ADDRESS(SA_IGD_BUS, SA_IGD_DEV, SA_IGD_FUN_0, PCI_COMMAND_OFFSET), \ EFI_PCI_COMMAND_MEMORY_SPACE | EFI_PCI_COMMAND_BUS_MASTER); } } // // SMRAMC LOCK must use CF8/CFC access // SaMcAddress = PCI_CF8_LIB_ADDRESS (SA_MC_BUS, SA_MC_DEV, SA_MC_FUN, R_SA_SMRAMC); AddressPort = IoRead32 (0xCF8); IoWrite32 (0xCF8, PCI_TO_CF8_ADDRESS (SaMcAddress)); IoOr8 (0xCFC + (UINT16)(SaMcAddress & 3), BIT4 ); IoWrite32 (0xCF8, AddressPort); // // Initialize Smbios Info for SmbiosInit // if (FeaturePcdGet (PcdSmbiosEnabled)) { InitializeSmbiosInfo (); } break; case PrePciEnumeration: break; case PostPciEnumeration: if (GetBootMode() == BOOT_ON_S3_RESUME) { ClearSmi (); RestoreS3RegInfo (FindS3Info (S3_SAVE_REG_COMM_ID)); // // If payload registered a software SMI handler for bootloader to restore // SMRR base and mask in S3 resume path, trigger sw smi // BlSwSmiInfo = FindS3Info (BL_SW_SMI_COMM_ID); if (BlSwSmiInfo != NULL) { TriggerPayloadSwSmi (BlSwSmiInfo->BlSwSmiHandlerInput); } } break; case PrePayloadLoading: Status = IgdOpRegionInit (); if (EFI_ERROR (Status)) { DEBUG ((DEBUG_WARN, "VBT not found %r\n", Status)); } ClearSmi (); if (GetPayloadId () == UEFI_PAYLOAD_ID_SIGNATURE && GetBootMode() != BOOT_ON_S3_RESUME) { ClearS3SaveRegion (); // // Set SMMBASE_INFO dummy strucutre in TSEG before others // mSmmBaseInfo.SmmBaseHdr.Count = (UINT8) MpGetInfo()->CpuCount; mSmmBaseInfo.SmmBaseHdr.TotalSize = sizeof(BL_PLD_COMM_HDR) + mSmmBaseInfo.SmmBaseHdr.Count * sizeof(CPU_SMMBASE); Status = AppendS3Info ((VOID *)&mSmmBaseInfo, TRUE); // // Set REG_INFO struct in TSEG region except 'Val' for regs // mS3SaveReg.S3SaveHdr.TotalSize = sizeof(BL_PLD_COMM_HDR) + mS3SaveReg.S3SaveHdr.Count * sizeof(REG_INFO); AppendS3Info ((VOID *)&mS3SaveReg, FALSE); } break; case EndOfStages: // Lock down SPI for all other payload entry except FWUpdate and OSloader // as this phase is too early for them to lock it here SpiBaseAddress = GetDeviceAddr (OsBootDeviceSpi, 0); SpiBaseAddress = TO_MM_PCI_ADDRESS (SpiBaseAddress); SiliconCfgData = (SILICON_CFG_DATA *)FindConfigDataByTag (CDATA_SILICON_TAG); if ( (SiliconCfgData != NULL) && (SiliconCfgData->ECEnable == 1)){ // // Enable decoding of I/O locations 62h and 66h to LPC // LpcBase = MmPciBase (0, PCI_DEVICE_NUMBER_PCH_LPC, 0); MmioOr16 (LpcBase + R_LPC_CFG_IOE, B_LPC_CFG_IOE_ME1); // // Enable EC's ACPI mode to control power to motherboard during Sleep (S3) // IoWrite16 (EC_C_PORT, EC_C_ACPI_ENABLE); DEBUG ((DEBUG_INFO, "Set EC to ACPI mode\n")); } if ((GetBootMode() != BOOT_ON_FLASH_UPDATE) && (GetPayloadId() != 0)) { // Set the BIOS Lock Enable and EISS bits MmioOr8 (SpiBaseAddress + R_SPI_CFG_BC, (UINT8) (B_SPI_CFG_BC_LE | B_SPI_CFG_BC_EISS)); ClearFspHob (); } break; case ReadyToBoot: ClearSmi (); // // Do necessary locks, and clean up before jumping tp OS // // Lock down SPI for everything SpiBaseAddress = GetDeviceAddr (OsBootDeviceSpi, 0); SpiBaseAddress = TO_MM_PCI_ADDRESS (SpiBaseAddress); // Set the BIOS Lock Enable and EISS bits MmioOr8 (SpiBaseAddress + R_SPI_CFG_BC, (UINT8) (B_SPI_CFG_BC_LE | B_SPI_CFG_BC_EISS)); // // Set Bios Interface Lock-Down (BILD) // B0:D31:F05 Offset DCh Bit 07 // // Set the BILD MmioOr8 (SpiBaseAddress + R_SPI_CFG_BC, (UINT8)B_SPI_CFG_BC_BILD); // // set Flash Configuration Lock-Down (FLOCKDN) // B0:D31:F05 Offset 04h Bit 15 // SpiBar0 = (UINTN)PciRead32 (PCI_LIB_ADDRESS (0, PCI_DEVICE_NUMBER_PCH_SPI, PCI_FUNCTION_NUMBER_PCH_SPI, R_SPI_CFG_BAR0)); SpiBar0 &= ~(B_SPI_CFG_BAR0_MASK); if (SpiBar0 != 0) { MmioOr16 (SpiBar0 + R_SPI_MEM_HSFSC, (UINT16)B_SPI_MEM_HSFSC_FLOCKDN); } // // set SMI LOCK (SMI_LOCK) // B0:D31:F02 Offset A0h Bit 4 // PmcBaseAddr = PCI_LIB_ADDRESS ( DEFAULT_PCI_BUS_NUMBER_PCH, PCI_DEVICE_NUMBER_PCH_PMC, PCI_FUNCTION_NUMBER_PCH_PMC, 0); PciOr8 (PmcBaseAddr + R_PMC_PWRM_GEN_PMCON_A, (UINT8)B_PMC_PWRM_GEN_PMCON_A_SMI_LOCK); ClearFspHob (); // // Lock down Tco WDT just before handling off to OS // TcoBase = MmioRead16(PCH_PCR_ADDRESS(PID_DMI, R_PCH_DMI_PCR_TCOBASE)) & B_PCH_DMI_PCR_TCOBASE_TCOBA; IoOr16 ((TcoBase + R_TCO_IO_TCO1_CNT), B_TCO_IO_TCO1_CNT_LOCK); break; case EndOfFirmware: break; default: break; } } /** Finds PCI Function Number of SerialIo devices. @param[in] SerialIoNumber Serial IO device @retval SerialIo irq number **/ UINT8 FindSerialIoIrq ( IN PCH_SERIAL_IO_CONTROLLER Device ) { UINT8 DevNum; UINT8 FuncNum; UINT8 Index; UINT8 Count; UINT8 Irq; CONST SI_PCH_DEVICE_INTERRUPT_CONFIG *IntConfig; DevNum = GetSerialIoDeviceNumber (Device); FuncNum = GetSerialIoFunctionNumber (Device); if (IsPchLp() == TRUE) { IntConfig = mPchLpDevIntConfig; Count = ARRAY_SIZE (mPchLpDevIntConfig); } else { IntConfig = mPchDevIntConfig; Count = ARRAY_SIZE (mPchDevIntConfig); } for (Irq = 0, Index = 0; Index < Count; Index ++) { if ((IntConfig[Index].Device == DevNum) && (IntConfig[Index].Function == FuncNum)) { Irq = IntConfig[Index].Irq; break; } } return Irq; } /** Update FSP-S UPD config data @param[in] FspsUpdPtr The pointer to the FSP-S UPD to be updated. **/ VOID EFIAPI UpdateFspConfig ( IN VOID *FspsUpdPtr ) { FSPS_UPD *FspsUpd; UINT32 Index; UINT32 Length; UINT32 BaseAddress; UINT32 RegionSize; EFI_STATUS Status; FSP_S_TEST_CONFIG *FspsTestConfig; UINT32 *HdaVerbTablePtr; UINT8 HdaVerbTableNum; UINT16 PlatformId; PCIE_CFG_DATA *PcieCfgData; GPU_CFG_DATA *GpuCfgData; UINT8 Data8; SILICON_CFG_DATA *SiliconCfgData; PlatformId = GetPlatformId (); FspsUpd = (FSPS_UPD *) FspsUpdPtr; FspsUpd->FspsConfig.PchPmSlpS3MinAssert = 0; FspsUpd->FspsConfig.PchPmSlpS4MinAssert = 0; FspsUpd->FspsConfig.PchPmSlpSusMinAssert = 0; FspsUpd->FspsConfig.PchPmSlpAMinAssert = 0; FspsUpd->FspsConfig.PchPmLpcClockRun = 1; FspsUpd->FspsConfig.EnableTcoTimer = 0; FspsUpd->FspsConfig.SataPwrOptEnable = 1; if (IsPchLp()) { FspsUpd->FspsConfig.DevIntConfigPtr = (UINT32)(UINTN) mPchLpDevIntConfig; FspsUpd->FspsConfig.NumOfDevIntConfig = ARRAY_SIZE (mPchLpDevIntConfig); } else { FspsUpd->FspsConfig.DevIntConfigPtr = (UINT32)(UINTN) mPchDevIntConfig; FspsUpd->FspsConfig.NumOfDevIntConfig = ARRAY_SIZE (mPchDevIntConfig); FspsUpd->FspsConfig.EnableTcoTimer = 1; } FspsUpd->FspsConfig.GpioIrqRoute = DEFAULT_GPIO_IRQ_ROUTE; FspsUpd->FspsConfig.SciIrqSelect = 9; FspsUpd->FspsConfig.TcoIrqEnable = 0; FspsUpd->FspsConfig.TcoIrqSelect = 9; HdaVerbTablePtr = (UINT32 *) AllocateZeroPool (2 * sizeof (UINT32)); if (HdaVerbTablePtr != NULL) { HdaVerbTableNum = 0; HdaVerbTablePtr[HdaVerbTableNum++] = (UINT32)(UINTN) &HdaVerbTableDisplayAudio; HdaVerbTablePtr[HdaVerbTableNum++] = (UINT32)(UINTN) &CmlHdaVerbTableAlc711; FspsUpd->FspsConfig.PchHdaVerbTablePtr = (UINT32)(UINTN) HdaVerbTablePtr; FspsUpd->FspsConfig.PchHdaVerbTableEntryNum = HdaVerbTableNum; } else { DEBUG ((DEBUG_ERROR, "UpdateFspConfig Error: Could not allocate Memory for HdaVerbTable\n")); } FspsUpd->FspsConfig.GraphicsConfigPtr = PcdGet32(PcdGraphicsVbtAddress); CopyMem (&FspsUpd->FspsConfig.PxRcConfig, mPxRcConfig, sizeof(mPxRcConfig)); // Set debug uart in PCI mode Data8 = GetDebugPort (); if (Data8 < PCH_MAX_SERIALIO_UART_CONTROLLERS) { FspsUpd->FspsConfig.SerialIoUartMode[Data8] = 1; } // // USB config // FspsUpd->FspsConfig.XdciEnable = FALSE; FspsUpd->FspsTestConfig.PchXhciOcLock = TRUE; Length = GetPchXhciMaxUsb2PortNum (); for (Index = 0; Index < Length; Index++) { FspsUpd->FspsConfig.PortUsb20Enable[Index] = TRUE; FspsUpd->FspsConfig.Usb2OverCurrentPin[Index] = UsbOverCurrentPinMax; FspsUpd->FspsConfig.Usb2AfePetxiset[Index] = 7; FspsUpd->FspsConfig.Usb2AfeTxiset[Index] = 5; FspsUpd->FspsConfig.Usb2AfePredeemp[Index] = 3; FspsUpd->FspsConfig.Usb2AfePehalfbit[Index] = 0; } Length = GetPchXhciMaxUsb3PortNum (); for (Index = 0; Index < Length; Index++) { FspsUpd->FspsConfig.PortUsb30Enable[Index] = TRUE; FspsUpd->FspsConfig.Usb3OverCurrentPin[Index] = UsbOverCurrentPinMax; FspsUpd->FspsConfig.Usb3HsioTxDeEmphEnable[Index] = 0; FspsUpd->FspsConfig.Usb3HsioTxDeEmph[Index] = 0; FspsUpd->FspsConfig.Usb3HsioTxDownscaleAmpEnable[Index] = 0; FspsUpd->FspsConfig.Usb3HsioTxDownscaleAmp[Index] = 0; } if (IsPchLp()) { FspsUpd->FspsConfig.Usb2OverCurrentPin[0] = UsbOverCurrentPin2; FspsUpd->FspsConfig.Usb2OverCurrentPin[1] = UsbOverCurrentPinSkip; FspsUpd->FspsConfig.Usb2OverCurrentPin[2] = UsbOverCurrentPin2; FspsUpd->FspsConfig.Usb2OverCurrentPin[3] = UsbOverCurrentPin2; FspsUpd->FspsConfig.Usb2OverCurrentPin[4] = UsbOverCurrentPin3; FspsUpd->FspsConfig.Usb2OverCurrentPin[5] = UsbOverCurrentPin3; FspsUpd->FspsConfig.Usb2OverCurrentPin[6] = UsbOverCurrentPin3; FspsUpd->FspsConfig.Usb2OverCurrentPin[7] = UsbOverCurrentPin3; FspsUpd->FspsConfig.Usb2OverCurrentPin[8] = UsbOverCurrentPinSkip; FspsUpd->FspsConfig.Usb2OverCurrentPin[9] = UsbOverCurrentPinSkip; FspsUpd->FspsConfig.Usb2OverCurrentPin[10] = UsbOverCurrentPinSkip; FspsUpd->FspsConfig.Usb2OverCurrentPin[11] = UsbOverCurrentPinSkip; FspsUpd->FspsConfig.Usb2OverCurrentPin[12] = UsbOverCurrentPinSkip; FspsUpd->FspsConfig.Usb2OverCurrentPin[13] = UsbOverCurrentPinSkip; FspsUpd->FspsConfig.Usb2OverCurrentPin[14] = UsbOverCurrentPinSkip; FspsUpd->FspsConfig.Usb2OverCurrentPin[15] = UsbOverCurrentPinSkip; FspsUpd->FspsConfig.Usb3OverCurrentPin[0] = UsbOverCurrentPin2; FspsUpd->FspsConfig.Usb3OverCurrentPin[1] = UsbOverCurrentPinSkip; FspsUpd->FspsConfig.Usb3OverCurrentPin[2] = UsbOverCurrentPin2; FspsUpd->FspsConfig.Usb3OverCurrentPin[3] = UsbOverCurrentPin2; FspsUpd->FspsConfig.Usb3OverCurrentPin[4] = UsbOverCurrentPinSkip; FspsUpd->FspsConfig.Usb3OverCurrentPin[5] = UsbOverCurrentPinSkip; FspsUpd->FspsConfig.Usb3OverCurrentPin[6] = UsbOverCurrentPinSkip; FspsUpd->FspsConfig.Usb3OverCurrentPin[7] = UsbOverCurrentPinSkip; FspsUpd->FspsConfig.Usb3OverCurrentPin[8] = UsbOverCurrentPinSkip; FspsUpd->FspsConfig.Usb3OverCurrentPin[9] = UsbOverCurrentPinSkip; Length = GetPchUsb2MaxPhysicalPortNum (); for (Index = 0; Index < Length; Index++) { FspsUpd->FspsConfig.Usb2AfePetxiset[Index] = 6; FspsUpd->FspsConfig.Usb2AfeTxiset[Index] = 0; FspsUpd->FspsConfig.Usb2AfePredeemp[Index] = 3; FspsUpd->FspsConfig.Usb2AfePehalfbit[Index] = 0; } } else { FspsUpd->FspsConfig.Usb2OverCurrentPin[0] = UsbOverCurrentPin4; FspsUpd->FspsConfig.Usb2OverCurrentPin[1] = UsbOverCurrentPin0; FspsUpd->FspsConfig.Usb2OverCurrentPin[2] = UsbOverCurrentPin2; FspsUpd->FspsConfig.Usb2OverCurrentPin[3] = UsbOverCurrentPin5; FspsUpd->FspsConfig.Usb2OverCurrentPin[4] = UsbOverCurrentPin5; FspsUpd->FspsConfig.Usb2OverCurrentPin[5] = UsbOverCurrentPin0; FspsUpd->FspsConfig.Usb2OverCurrentPin[6] = UsbOverCurrentPin1; FspsUpd->FspsConfig.Usb2OverCurrentPin[7] = UsbOverCurrentPin1; FspsUpd->FspsConfig.Usb2OverCurrentPin[8] = UsbOverCurrentPinSkip; FspsUpd->FspsConfig.Usb2OverCurrentPin[9] = UsbOverCurrentPin3; FspsUpd->FspsConfig.Usb2OverCurrentPin[10] = UsbOverCurrentPin3; FspsUpd->FspsConfig.Usb2OverCurrentPin[11] = UsbOverCurrentPin6; FspsUpd->FspsConfig.Usb2OverCurrentPin[12] = UsbOverCurrentPin6; FspsUpd->FspsConfig.Usb2OverCurrentPin[13] = UsbOverCurrentPin0; FspsUpd->FspsConfig.Usb3OverCurrentPin[0] = UsbOverCurrentPin4; FspsUpd->FspsConfig.Usb3OverCurrentPin[1] = UsbOverCurrentPin0; FspsUpd->FspsConfig.Usb3OverCurrentPin[2] = UsbOverCurrentPin2; FspsUpd->FspsConfig.Usb3OverCurrentPin[3] = UsbOverCurrentPin5; FspsUpd->FspsConfig.Usb3OverCurrentPin[4] = UsbOverCurrentPin5; FspsUpd->FspsConfig.Usb3OverCurrentPin[5] = UsbOverCurrentPin0; FspsUpd->FspsConfig.Usb3OverCurrentPin[6] = UsbOverCurrentPin1; FspsUpd->FspsConfig.Usb3OverCurrentPin[7] = UsbOverCurrentPin1; FspsUpd->FspsConfig.Usb3OverCurrentPin[8] = UsbOverCurrentPinSkip; FspsUpd->FspsConfig.Usb3OverCurrentPin[9] = UsbOverCurrentPin3; FspsUpd->FspsConfig.Usb2AfePetxiset[0] = 7; FspsUpd->FspsConfig.Usb2AfeTxiset[0] = 0; FspsUpd->FspsConfig.Usb2AfePredeemp[0] = 3; FspsUpd->FspsConfig.Usb2AfePehalfbit[0] = 0; FspsUpd->FspsConfig.Usb2AfePetxiset[1] = 6; FspsUpd->FspsConfig.Usb2AfeTxiset[1] = 0; FspsUpd->FspsConfig.Usb2AfePredeemp[1] = 3; FspsUpd->FspsConfig.Usb2AfePehalfbit[1] = 0; FspsUpd->FspsConfig.Usb2AfePetxiset[2] = 6; FspsUpd->FspsConfig.Usb2AfeTxiset[2] = 0; FspsUpd->FspsConfig.Usb2AfePredeemp[2] = 3; FspsUpd->FspsConfig.Usb2AfePehalfbit[2] = 0; FspsUpd->FspsConfig.Usb2AfePetxiset[3] = 6; FspsUpd->FspsConfig.Usb2AfeTxiset[3] = 0; FspsUpd->FspsConfig.Usb2AfePredeemp[3] = 3; FspsUpd->FspsConfig.Usb2AfePehalfbit[3] = 0; FspsUpd->FspsConfig.Usb2AfePetxiset[4] = 6; FspsUpd->FspsConfig.Usb2AfeTxiset[4] = 0; FspsUpd->FspsConfig.Usb2AfePredeemp[4] = 3; FspsUpd->FspsConfig.Usb2AfePehalfbit[4] = 0; FspsUpd->FspsConfig.Usb2AfePetxiset[5] = 6; FspsUpd->FspsConfig.Usb2AfeTxiset[5] = 0; FspsUpd->FspsConfig.Usb2AfePredeemp[5] = 3; FspsUpd->FspsConfig.Usb2AfePehalfbit[5] = 0; FspsUpd->FspsConfig.Usb2AfePetxiset[6] = 7; FspsUpd->FspsConfig.Usb2AfeTxiset[6] = 0; FspsUpd->FspsConfig.Usb2AfePredeemp[6] = 3; FspsUpd->FspsConfig.Usb2AfePehalfbit[6] = 0; FspsUpd->FspsConfig.Usb2AfePetxiset[7] = 7; FspsUpd->FspsConfig.Usb2AfeTxiset[7] = 0; FspsUpd->FspsConfig.Usb2AfePredeemp[7] = 3; FspsUpd->FspsConfig.Usb2AfePehalfbit[7] = 0; FspsUpd->FspsConfig.Usb2AfePetxiset[8] = 6; FspsUpd->FspsConfig.Usb2AfeTxiset[8] = 0; FspsUpd->FspsConfig.Usb2AfePredeemp[8] = 3; FspsUpd->FspsConfig.Usb2AfePehalfbit[8] = 0; FspsUpd->FspsConfig.Usb2AfePetxiset[9] = 6; FspsUpd->FspsConfig.Usb2AfeTxiset[9] = 0; FspsUpd->FspsConfig.Usb2AfePredeemp[9] = 3; FspsUpd->FspsConfig.Usb2AfePehalfbit[9] = 0; FspsUpd->FspsConfig.Usb2AfePetxiset[10] = 6; FspsUpd->FspsConfig.Usb2AfeTxiset[10] = 0; FspsUpd->FspsConfig.Usb2AfePredeemp[10] = 3; FspsUpd->FspsConfig.Usb2AfePehalfbit[10] = 0; FspsUpd->FspsConfig.Usb2AfePetxiset[11] = 7; FspsUpd->FspsConfig.Usb2AfeTxiset[11] = 0; FspsUpd->FspsConfig.Usb2AfePredeemp[11] = 3; FspsUpd->FspsConfig.Usb2AfePehalfbit[11] = 0; FspsUpd->FspsConfig.Usb2AfePetxiset[12] = 7; FspsUpd->FspsConfig.Usb2AfeTxiset[12] = 0; FspsUpd->FspsConfig.Usb2AfePredeemp[12] = 3; FspsUpd->FspsConfig.Usb2AfePehalfbit[12] = 0; FspsUpd->FspsConfig.Usb2AfePetxiset[13] = 7; FspsUpd->FspsConfig.Usb2AfeTxiset[13] = 0; FspsUpd->FspsConfig.Usb2AfePredeemp[13] = 3; FspsUpd->FspsConfig.Usb2AfePehalfbit[13] = 0; } GpuCfgData = (GPU_CFG_DATA *) FindConfigDataByTag (CDATA_GPU_TAG); if (GpuCfgData != NULL) { FspsUpd->FspsConfig.DdiPortEdp = GpuCfgData->DdiPortEdp; FspsUpd->FspsConfig.DdiPortBHpd = GpuCfgData->DdiPortBHpd; FspsUpd->FspsConfig.DdiPortCHpd = GpuCfgData->DdiPortCHpd; FspsUpd->FspsConfig.DdiPortDHpd = GpuCfgData->DdiPortDHpd; FspsUpd->FspsConfig.DdiPortFHpd = GpuCfgData->DdiPortFHpd; FspsUpd->FspsConfig.DdiPortBDdc = GpuCfgData->DdiPortBDdc; FspsUpd->FspsConfig.DdiPortCDdc = GpuCfgData->DdiPortCDdc; FspsUpd->FspsConfig.DdiPortDDdc = GpuCfgData->DdiPortDDdc; FspsUpd->FspsConfig.DdiPortFDdc = GpuCfgData->DdiPortFDdc; DEBUG ((DEBUG_INFO, "DdiPort Config: %d %d %d %d %d %d %d %d %d\n", FspsUpd->FspsConfig.DdiPortEdp, FspsUpd->FspsConfig.DdiPortBHpd, FspsUpd->FspsConfig.DdiPortCHpd, FspsUpd->FspsConfig.DdiPortDHpd, FspsUpd->FspsConfig.DdiPortFHpd, FspsUpd->FspsConfig.DdiPortBDdc, FspsUpd->FspsConfig.DdiPortCDdc, FspsUpd->FspsConfig.DdiPortDDdc, FspsUpd->FspsConfig.DdiPortFDdc)); } // // PCIE config // if ((PlatformId == PLATFORM_ID_CML_S) || (PlatformId == PLATFORM_ID_CML_V)){ FspsUpd->FspsConfig.PegPhysicalSlotNumber[0] = 1; FspsUpd->FspsConfig.PegPhysicalSlotNumber[1] = 2; FspsUpd->FspsConfig.PegPhysicalSlotNumber[2] = 3; } PcieCfgData = (PCIE_CFG_DATA *) FindConfigDataByTag (CDATA_PCIE_TAG); if (PcieCfgData == NULL) { DEBUG ((DEBUG_ERROR, "Missing PCIE RP Cfg Data!\n")); } else { Length = GetPchMaxPciePortNum (); for (Index = 0; Index < Length; Index++) { FspsUpd->FspsConfig.PcieRpAspm[Index] = (UINT8) PcieCfgData->RpFeatures0[Index].Aspm; FspsUpd->FspsConfig.PcieRpPmSci[Index] = (UINT8) PcieCfgData->RpFeatures0[Index].PmSciEn; FspsUpd->FspsConfig.PcieRpMaxPayload[Index] = (UINT8) PcieCfgData->RpFeatures0[Index].MaxPld; FspsUpd->FspsConfig.PcieRpPhysicalSlotNumber[Index] = (UINT8) Index; FspsUpd->FspsConfig.PcieRpL1Substates[Index] = (UINT8) PcieCfgData->RpFeatures0[Index].L1SubStates; FspsUpd->FspsConfig.PcieRpEnableCpm[Index] = (UINT8) PcieCfgData->RpFeatures0[Index].CpmEn; FspsUpd->FspsConfig.PcieRpGen3EqPh3Method[Index] = (UINT8) PcieCfgData->RpFeatures0[Index].Gen3EqPh3Method; FspsUpd->FspsConfig.PcieRpLtrEnable[Index] = (UINT8) PcieCfgData->RpFeatures0[Index].LtrEn; FspsUpd->FspsTestConfig.PcieRpLtrMaxSnoopLatency[Index] = (UINT16) PcieCfgData->RpFeatures0[Index].MaxSnoopLat; FspsUpd->FspsTestConfig.PcieRpLtrMaxNoSnoopLatency[Index] = (UINT16) PcieCfgData->RpFeatures0[Index].MaxNoSnoopLat; FspsUpd->FspsTestConfig.PcieRpSnoopLatencyOverrideMode[Index] = (UINT8) PcieCfgData->RpFeatures0[Index].SnoopLatMode; FspsUpd->FspsTestConfig.PcieRpSnoopLatencyOverrideMultiplier[Index] = (UINT8) PcieCfgData->RpFeatures0[Index].SnoopLatMul; FspsUpd->FspsTestConfig.PcieRpSnoopLatencyOverrideValue[Index] = (UINT16)PcieCfgData->RpFeatures0[Index].SnoopLatVal; FspsUpd->FspsTestConfig.PcieRpNonSnoopLatencyOverrideMode[Index] = (UINT8) PcieCfgData->RpFeatures0[Index].NoSnoopLatMode; FspsUpd->FspsTestConfig.PcieRpNonSnoopLatencyOverrideMultiplier[Index] = (UINT8) PcieCfgData->RpFeatures0[Index].NoSnoopLatMul; FspsUpd->FspsTestConfig.PcieRpNonSnoopLatencyOverrideValue[Index] = (UINT16)PcieCfgData->RpFeatures0[Index].NoSnoopLatVal; FspsUpd->FspsTestConfig.PcieRpUptp[Index] = (UINT8) PcieCfgData->RpFeatures0[Index].Uptp; FspsUpd->FspsTestConfig.PcieRpDptp[Index] = (UINT8) PcieCfgData->RpFeatures0[Index].Dptp; FspsUpd->FspsConfig.PcieEqPh3LaneParamCm[Index] = (UINT8) PcieCfgData->RpFeatures0[Index].EqPh3Cm; FspsUpd->FspsConfig.PcieEqPh3LaneParamCp[Index] = (UINT8) PcieCfgData->RpFeatures0[Index].EqPh3Cp; FspsUpd->FspsConfig.PcieRpClkReqDetect[Index] = (UINT8) PcieCfgData->RpFeatures0[Index].ClkReqDetect; FspsUpd->FspsConfig.PcieRpAdvancedErrorReporting[Index] = (UINT8) PcieCfgData->RpFeatures0[Index].AdvErrReport; } } FspsUpd->FspsConfig.PcieSwEqCoeffListCm[0] = 4; FspsUpd->FspsConfig.PcieSwEqCoeffListCp[0] = 8; FspsUpd->FspsConfig.PcieSwEqCoeffListCm[1] = 6; FspsUpd->FspsConfig.PcieSwEqCoeffListCp[1] = 2; FspsUpd->FspsConfig.PcieSwEqCoeffListCm[2] = 8; FspsUpd->FspsConfig.PcieSwEqCoeffListCp[2] = 6; FspsUpd->FspsConfig.PcieSwEqCoeffListCm[3] = 10; FspsUpd->FspsConfig.PcieSwEqCoeffListCp[3] = 8; FspsUpd->FspsConfig.PcieSwEqCoeffListCm[4] = 12; FspsUpd->FspsConfig.PcieSwEqCoeffListCp[4] = 2; if ((PlatformId == PLATFORM_ID_CML_S) || (PlatformId == PLATFORM_ID_CML_V)){ FspsUpd->FspsConfig.VrPowerDeliveryDesign = 0x0D; } else if (PlatformId == PLATFORM_ID_CML_H) { FspsUpd->FspsConfig.VrPowerDeliveryDesign = 0x1F; } // // CPU power management config // FspsUpd->FspsConfig.TdcEnable[0] = 0x1; FspsUpd->FspsConfig.TdcEnable[1] = 0x1; FspsUpd->FspsConfig.TdcEnable[3] = 0x1; FspsUpd->FspsConfig.TdcPowerLimit[1] = 0x2b0; FspsUpd->FspsConfig.TdcPowerLimit[3] = 0xc8; FspsUpd->FspsConfig.AcLoadline[0] = 0x406; FspsUpd->FspsConfig.AcLoadline[1] = 0xb4; FspsUpd->FspsConfig.AcLoadline[3] = 0x10e; FspsUpd->FspsConfig.DcLoadline[0] = 0x406; FspsUpd->FspsConfig.DcLoadline[1] = 0xb4; FspsUpd->FspsConfig.DcLoadline[3] = 0x10e; FspsUpd->FspsConfig.Psi1Threshold[0] = 0x50; FspsUpd->FspsConfig.Psi1Threshold[1] = 0x50; FspsUpd->FspsConfig.Psi1Threshold[2] = 0x50; FspsUpd->FspsConfig.Psi1Threshold[3] = 0x50; FspsUpd->FspsConfig.Psi1Threshold[4] = 0x50; FspsUpd->FspsConfig.Psi2Threshold[0] = 0x14; FspsUpd->FspsConfig.Psi2Threshold[1] = 0x14; FspsUpd->FspsConfig.Psi2Threshold[2] = 0x14; FspsUpd->FspsConfig.Psi2Threshold[3] = 0x14; FspsUpd->FspsConfig.Psi2Threshold[4] = 0x14; FspsUpd->FspsConfig.Psi3Threshold[0] = 0x4; FspsUpd->FspsConfig.Psi3Threshold[1] = 0x4; FspsUpd->FspsConfig.Psi3Threshold[2] = 0x4; FspsUpd->FspsConfig.Psi3Threshold[3] = 0x4; FspsUpd->FspsConfig.Psi3Threshold[4] = 0x4; FspsUpd->FspsConfig.IccMax[0] = 0x2c; FspsUpd->FspsConfig.IccMax[1] = 0x230; FspsUpd->FspsConfig.IccMax[3] = 0x80; FspsUpd->FspsConfig.McivrSpreadSpectrum = 0x3; FspsUpd->FspsTestConfig.OneCoreRatioLimit = 0x29; FspsUpd->FspsTestConfig.TwoCoreRatioLimit = 0x28; FspsUpd->FspsTestConfig.ThreeCoreRatioLimit = 0x27; FspsUpd->FspsTestConfig.FourCoreRatioLimit = 0x26; FspsUpd->FspsTestConfig.FiveCoreRatioLimit = 0x25; FspsUpd->FspsTestConfig.SixCoreRatioLimit = 0x24; FspsUpd->FspsTestConfig.TccActivationOffset = 0x0; FspsUpd->FspsTestConfig.TccOffsetClamp = 0x0; FspsUpd->FspsTestConfig.PowerLimit1 = 0x0; FspsUpd->FspsTestConfig.PowerLimit2Power = 0x0; FspsUpd->FspsTestConfig.PowerLimit3 = 0x0; FspsUpd->FspsTestConfig.PowerLimit4 = 0x0; FspsUpd->FspsTestConfig.Custom1PowerLimit1 = 0x0; FspsUpd->FspsTestConfig.Custom1PowerLimit2 = 0x0; FspsUpd->FspsTestConfig.Custom2PowerLimit1 = 0x0; FspsUpd->FspsTestConfig.Custom2PowerLimit2 = 0x0; FspsUpd->FspsTestConfig.Custom3PowerLimit1 = 0x0; FspsUpd->FspsTestConfig.Custom3PowerLimit2 = 0x0; FspsUpd->FspsTestConfig.Custom1PowerLimit1Time = 0x0; FspsUpd->FspsTestConfig.Custom1TurboActivationRatio = 0x0; FspsUpd->FspsTestConfig.Custom2PowerLimit1Time = 0x0; FspsUpd->FspsTestConfig.Custom2TurboActivationRatio = 0x0; FspsUpd->FspsTestConfig.Custom3PowerLimit1Time = 0x0; FspsUpd->FspsTestConfig.Custom3TurboActivationRatio = 0x0; FspsUpd->FspsTestConfig.VoltageOptimization = 0x0; FspsUpd->FspsTestConfig.TStates = 0x0; FspsUpd->FspsTestConfig.ProcHotResponse = 0x0; FspsUpd->FspsTestConfig.Cx = 0x1; FspsUpd->FspsTestConfig.PkgCStateLimit = 0xff; FspsUpd->FspsTestConfig.MaxRatio = 0x8; FspsUpd->FspsTestConfig.PsysPmax = 0x0; FspsUpd->FspsTestConfig.CstateLatencyControl0Irtl = 0x4e; SiliconCfgData = (SILICON_CFG_DATA *)FindConfigDataByTag (CDATA_SILICON_TAG); if (SiliconCfgData != NULL) { FspsUpd->FspsConfig.DebugInterfaceEnable = SiliconCfgData->DebugInterfaceEnable; } /* Flash protection range setting */ Status = SpiGetRegionAddress (FlashRegionBios, &BaseAddress, &RegionSize); if (!EFI_ERROR (Status)) { FspsUpd->FspsConfig.PchWriteProtectionEnable[0] = 0x0; FspsUpd->FspsConfig.PchReadProtectionEnable[0] = 0x0; FspsUpd->FspsConfig.PchProtectedRangeBase[0] = (UINT16)(BaseAddress >> 12); FspsUpd->FspsConfig.PchProtectedRangeLimit[0] = (UINT16)(((BaseAddress + RegionSize) - 1) >> 12); } if (GetBootMode() == BOOT_ON_FLASH_UPDATE) { FspsTestConfig = &FspsUpd->FspsTestConfig; FspsTestConfig->PchLockDownBiosInterface = FALSE; FspsTestConfig->PchLockDownRtcLock = FALSE; FspsTestConfig->PchSbAccessUnlock = TRUE; DEBUG ((DEBUG_INFO, "Firmware update mode, unlock Bios setting\n")); } if (!(UpdateFspsSgxConfig (FspsUpd))) { DEBUG ((DEBUG_INFO, "FSP-S variables for Intel(R) SGX were NOT updated.\n")); } // // FSPS UPDs from BIOS // // FspsConfig->LogoPtr = 0x96deb000; // FspsConfig->LogoSize = 0x309e; // FspsConfig->GraphicsConfigPtr = 0x96def000; // FspsConfig->BltBufferAddress = 0x96de0000; // FspsConfig->DevIntConfigPtr = 0x94bf7abc; // FspsConfig->NumOfDevIntConfig = 0x34; // FspsConfig->PchHdaVerbTablePtr = 0x94bf8578; // FspsConfig->ChipsetInitBinPtr = 0xffd882c0; // FspsConfig->ChipsetInitBinLen = 0x1380; // FspsConfig->PchPcieDeviceOverrideTablePtr = 0x96e19950; // FspsConfig->BgpdtHash[0] = 0xbba9e28f772a14a5; // FspsConfig->BgpdtHash[1] = 0x5a461fc5a8599984; // FspsConfig->BgpdtHash[2] = 0x9663b5a55bfa6791; // FspsConfig->BgpdtHash[3] = 0x56eda102dafa0987; // FspsConfig->BiosGuardAttr = 0x36; // FspsConfig->BiosGuardModulePtr = 0xffd7df10; // FspsConfig->SiSsidTablePtr = 0x96e19428; // FspsConfig->SiNumberOfSsidTableEntry = 0x45; // FspsConfig->OneCoreRatioLimit = 0x2a; // FspsConfig->TwoCoreRatioLimit = 0x29; // FspsConfig->ThreeCoreRatioLimit = 0x28; // FspsConfig->FourCoreRatioLimit = 0x27; // FspsConfig->FiveCoreRatioLimit = 0x26; // FspsConfig->SixCoreRatioLimit = 0x25; // FspsConfig->SevenCoreRatioLimit = 0x25; // FspsConfig->EightCoreRatioLimit = 0x25; // FspsConfig->SgxSinitDataFromTpm = 0x0; // FspsConfig->TestGnaErrorCheckDis = 0x0; // FspsConfig->SaTestModeEdramInternal = 0x3; // FspsConfig->SaTestSpcLock = 0x0; // FspsConfig->PchTestTselLock = 0x0; // FspsConfig->PchTestTscLock = 0x0; // FspsConfig->PchTestPhlcLock = 0x0; // FspsConfig->TestCnviBtUartType = 0x3; FspsUpd->FspsConfig.WatchDogTimerOs = 0x0; FspsUpd->FspsConfig.ForcMebxSyncUp = 0x1; FspsUpd->FspsConfig.DdiPortFHpd = 0x0; FspsUpd->FspsConfig.DdiPortBDdc = 0x1; FspsUpd->FspsConfig.DdiPortFDdc = 0x0; FspsUpd->FspsConfig.TdcPowerLimit[1] = 0x0; FspsUpd->FspsConfig.TdcPowerLimit[3] = 0x0; FspsUpd->FspsConfig.AcLoadline[0] = 0x0; FspsUpd->FspsConfig.AcLoadline[1] = 0x0; FspsUpd->FspsConfig.AcLoadline[3] = 0x0; FspsUpd->FspsConfig.DcLoadline[0] = 0x0; FspsUpd->FspsConfig.DcLoadline[1] = 0x0; FspsUpd->FspsConfig.DcLoadline[3] = 0x0; FspsUpd->FspsConfig.IccMax[0] = 0x0; FspsUpd->FspsConfig.IccMax[1] = 0x0; FspsUpd->FspsConfig.IccMax[3] = 0x0; FspsUpd->FspsConfig.CpuBistData = 0x94bfb210; FspsUpd->FspsConfig.VrPowerDeliveryDesign = 0x0; FspsUpd->FspsConfig.SerialIoSpi0CsPolarity[1] = 0x0; FspsUpd->FspsConfig.SerialIoSpi1CsPolarity[1] = 0x0; FspsUpd->FspsConfig.SerialIoSpi0CsEnable[0] = 0x0; FspsUpd->FspsConfig.SerialIoSpi1CsEnable[0] = 0x0; FspsUpd->FspsConfig.SerialIoUartBaudRate[0] = 0x0; FspsUpd->FspsConfig.SerialIoUartBaudRate[1] = 0x0; FspsUpd->FspsConfig.SerialIoUartParity[0] = 0x0; FspsUpd->FspsConfig.SerialIoUartParity[1] = 0x0; FspsUpd->FspsConfig.SerialIoUartDataBits[0] = 0x0; FspsUpd->FspsConfig.SerialIoUartDataBits[1] = 0x0; FspsUpd->FspsConfig.SerialIoUartStopBits[0] = 0x0; FspsUpd->FspsConfig.SerialIoUartStopBits[1] = 0x0; FspsUpd->FspsConfig.SerialIoUartPowerGating[0] = 0x2; FspsUpd->FspsConfig.SerialIoUartDmaEnable[2] = 0x1; FspsUpd->FspsConfig.PortUsb30Enable[2] = 0x1; FspsUpd->FspsConfig.Usb2AfePetxiset[2] = 0x6; FspsUpd->FspsConfig.Usb2AfePetxiset[3] = 0x6; FspsUpd->FspsConfig.Usb2AfePetxiset[4] = 0x6; FspsUpd->FspsConfig.Usb2AfePredeemp[1] = 0x3; FspsUpd->FspsConfig.PchIshI2c0GpioAssign = 0x1; FspsUpd->FspsConfig.PchIshI2c1GpioAssign = 0x1; FspsUpd->FspsConfig.PchIshGp0GpioAssign = 0x1; FspsUpd->FspsConfig.PchIshGp1GpioAssign = 0x1; FspsUpd->FspsConfig.PchIshGp2GpioAssign = 0x1; FspsUpd->FspsConfig.PchIshGp3GpioAssign = 0x1; FspsUpd->FspsConfig.PchIshGp4GpioAssign = 0x1; FspsUpd->FspsConfig.PchIshGp5GpioAssign = 0x1; FspsUpd->FspsConfig.PchIshGp6GpioAssign = 0x1; FspsUpd->FspsConfig.PchLockDownBiosLock = 0x1; FspsUpd->FspsConfig.PcieRpAdvancedErrorReporting[13] = 0x1; FspsUpd->FspsConfig.PcieRpAdvancedErrorReporting[18] = 0x1; FspsUpd->FspsConfig.PcieRpAdvancedErrorReporting[19] = 0x1; FspsUpd->FspsConfig.PcieRpAdvancedErrorReporting[20] = 0x1; FspsUpd->FspsConfig.PcieRpAdvancedErrorReporting[21] = 0x1; FspsUpd->FspsConfig.PcieRpUnsupportedRequestReport[5] = 0x0; FspsUpd->FspsConfig.PcieRpSystemErrorOnFatalError[18] = 0x0; FspsUpd->FspsConfig.PcieRpMaxPayload[0] = 0x1; FspsUpd->FspsConfig.PcieRpMaxPayload[8] = 0x1; FspsUpd->FspsConfig.PcieRpMaxPayload[12] = 0x1; FspsUpd->FspsConfig.PcieRpAspm[2] = 0x4; FspsUpd->FspsConfig.PcieRpAspm[19] = 0x4; FspsUpd->FspsConfig.PcieEqPh3LaneParamCm[0] = 0x6; FspsUpd->FspsConfig.PcieEqPh3LaneParamCm[1] = 0x6; FspsUpd->FspsConfig.PcieEqPh3LaneParamCm[2] = 0x6; FspsUpd->FspsConfig.PcieEqPh3LaneParamCm[3] = 0x6; FspsUpd->FspsConfig.PcieEqPh3LaneParamCm[4] = 0x6; FspsUpd->FspsConfig.PcieEqPh3LaneParamCm[5] = 0x6; FspsUpd->FspsConfig.PcieEqPh3LaneParamCm[6] = 0x6; FspsUpd->FspsConfig.PcieEqPh3LaneParamCm[8] = 0x6; FspsUpd->FspsConfig.PcieEqPh3LaneParamCm[9] = 0x6; FspsUpd->FspsConfig.PcieEqPh3LaneParamCm[10] = 0x6; FspsUpd->FspsConfig.PcieEqPh3LaneParamCm[11] = 0x6; FspsUpd->FspsConfig.PcieEqPh3LaneParamCm[12] = 0x6; FspsUpd->FspsConfig.PcieEqPh3LaneParamCm[13] = 0x6; FspsUpd->FspsConfig.PcieEqPh3LaneParamCm[14] = 0x6; FspsUpd->FspsConfig.PcieEqPh3LaneParamCm[15] = 0x6; FspsUpd->FspsConfig.PcieEqPh3LaneParamCm[16] = 0x6; FspsUpd->FspsConfig.PcieEqPh3LaneParamCm[17] = 0x6; FspsUpd->FspsConfig.PcieEqPh3LaneParamCm[18] = 0x6; FspsUpd->FspsConfig.PcieEqPh3LaneParamCm[19] = 0x6; FspsUpd->FspsConfig.PcieEqPh3LaneParamCm[20] = 0x6; FspsUpd->FspsConfig.PcieEqPh3LaneParamCm[21] = 0x6; FspsUpd->FspsConfig.PcieEqPh3LaneParamCm[22] = 0x6; FspsUpd->FspsConfig.PcieEqPh3LaneParamCm[23] = 0x6; FspsUpd->FspsConfig.PcieEqPh3LaneParamCp[0] = 0x2; FspsUpd->FspsConfig.PcieEqPh3LaneParamCp[1] = 0x2; FspsUpd->FspsConfig.PcieEqPh3LaneParamCp[14] = 0x2; FspsUpd->FspsConfig.PcieEqPh3LaneParamCp[15] = 0x2; FspsUpd->FspsConfig.PcieEqPh3LaneParamCp[16] = 0x2; FspsUpd->FspsConfig.PcieEqPh3LaneParamCp[19] = 0x2; FspsUpd->FspsConfig.PcieSwEqCoeffListCm[0] = 0x6; FspsUpd->FspsConfig.PcieSwEqCoeffListCm[3] = 0x0; FspsUpd->FspsConfig.PcieSwEqCoeffListCm[4] = 0x0; FspsUpd->FspsConfig.PcieSwEqCoeffListCp[1] = 0xc; FspsUpd->FspsConfig.PcieSwEqCoeffListCp[2] = 0x8; FspsUpd->FspsConfig.PcieSwEqCoeffListCp[3] = 0x0; FspsUpd->FspsConfig.PcieSwEqCoeffListCp[4] = 0x0; FspsUpd->FspsConfig.PchPmSlpS0Enable = 0x1; FspsUpd->FspsConfig.SataPwrOptEnable = 0x1; FspsUpd->FspsConfig.SataPortsExternal[3] = 0x0; FspsUpd->FspsConfig.SataPortsExternal[4] = 0x0; FspsUpd->FspsConfig.SataPortsExternal[5] = 0x0; FspsUpd->FspsConfig.SataPortsExternal[6] = 0x0; FspsUpd->FspsConfig.SataPortsSpinUp[5] = 0x0; FspsUpd->FspsConfig.DmiTS0TW = 0x3; FspsUpd->FspsConfig.DmiTS1TW = 0x2; FspsUpd->FspsConfig.DmiTS2TW = 0x1; FspsUpd->FspsConfig.PchMemoryPmsyncEnable[0] = 0x1; FspsUpd->FspsConfig.PchMemoryPmsyncEnable[1] = 0x1; FspsUpd->FspsConfig.PchMemoryC0TransmitEnable[0] = 0x1; FspsUpd->FspsConfig.PchMemoryC0TransmitEnable[1] = 0x1; FspsUpd->FspsConfig.PchTemperatureHotLevel = 0x154; FspsUpd->FspsConfig.Usb2OverCurrentPin[0] = 0x0; FspsUpd->FspsConfig.Usb2OverCurrentPin[2] = 0x7; FspsUpd->FspsConfig.Usb2OverCurrentPin[3] = 0x7; FspsUpd->FspsConfig.Usb2OverCurrentPin[4] = 0x1; FspsUpd->FspsConfig.Usb2OverCurrentPin[5] = 0x1; FspsUpd->FspsConfig.Usb2OverCurrentPin[6] = 0x6; FspsUpd->FspsConfig.Usb2OverCurrentPin[7] = 0x4; FspsUpd->FspsConfig.Usb2OverCurrentPin[8] = 0x3; FspsUpd->FspsConfig.Usb2OverCurrentPin[9] = 0x2; FspsUpd->FspsConfig.Usb2OverCurrentPin[10] = 0x5; FspsUpd->FspsConfig.Usb2OverCurrentPin[11] = 0x5; FspsUpd->FspsConfig.Usb2OverCurrentPin[12] = 0x2; FspsUpd->FspsConfig.Usb2OverCurrentPin[14] = 0x0; FspsUpd->FspsConfig.Usb2OverCurrentPin[15] = 0x0; FspsUpd->FspsConfig.Usb3OverCurrentPin[1] = 0x1; FspsUpd->FspsConfig.Usb3OverCurrentPin[2] = 0x1; FspsUpd->FspsConfig.Usb3OverCurrentPin[3] = 0x0; FspsUpd->FspsConfig.Usb3OverCurrentPin[4] = 0x2; FspsUpd->FspsConfig.Usb3OverCurrentPin[5] = 0x3; FspsUpd->FspsConfig.Usb3OverCurrentPin[6] = 0x0; FspsUpd->FspsConfig.Usb3OverCurrentPin[7] = 0x2; FspsUpd->FspsConfig.Usb3OverCurrentPin[9] = 0xff; FspsUpd->FspsConfig.EnableTcoTimer = 0x0; FspsUpd->FspsConfig.SataPortsDevSlpResetConfig[0] = 0x0; FspsUpd->FspsConfig.SataPortsDevSlpResetConfig[1] = 0x0; FspsUpd->FspsConfig.SataPortsDevSlpResetConfig[2] = 0x0; FspsUpd->FspsConfig.SataPortsDevSlpResetConfig[3] = 0x0; FspsUpd->FspsConfig.SataPortsDevSlpResetConfig[4] = 0x0; FspsUpd->FspsConfig.SataPortsDevSlpResetConfig[5] = 0x0; FspsUpd->FspsConfig.SataPortsDevSlpResetConfig[6] = 0x0; FspsUpd->FspsConfig.SataPortsDevSlpResetConfig[7] = 0x0; FspsUpd->FspsConfig.SendEcCmd = 0x96dfefcf; FspsUpd->FspsConfig.EcCmdProvisionEav = 0xb1; FspsUpd->FspsConfig.EcCmdLock = 0xb2; } /** Save MRC data into the reserved SPI region @param[in] Buffer The pointer to MRC data to be saved. @param[in] Length The length of MRC data to be saved. @return Resulting of saving MRC data to SPI **/ EFI_STATUS EFIAPI SaveNvsData ( IN VOID *Buffer, IN UINT32 Length ) { EFI_STATUS Status; UINT32 Address; UINT32 BaseAddress; UINT32 RegionSize; UINT32 MrcDataRegSize; UINTN PmcBaseAddr; Status = GetComponentInfo (FLASH_MAP_SIG_MRCDATA, &Address, &MrcDataRegSize); if (EFI_ERROR(Status)) { return EFI_NOT_FOUND; } if (Length > MrcDataRegSize) { return EFI_INVALID_PARAMETER; } // // Compare input data against the stored MRC training data // if they match, no need to update again. // if (CompareMem ((VOID *)(UINTN)Address, Buffer, Length) == 0){ return EFI_ALREADY_STARTED; } Status = SpiGetRegionAddress (FlashRegionBios, &BaseAddress, &RegionSize); if (EFI_ERROR (Status)) { return Status; } BaseAddress = ((UINT32)(~RegionSize) + 1); if (Address < BaseAddress) { return EFI_ACCESS_DENIED; } Address -= BaseAddress; if ((Address + ROUNDED_UP(Length, KB_(4))) > RegionSize) { return EFI_OUT_OF_RESOURCES; } if (!EFI_ERROR(Status)) { Status = SpiFlashErase (FlashRegionBios, Address, ROUNDED_UP(Length, KB_(4))); if (!EFI_ERROR(Status)) { Status = SpiFlashWrite (FlashRegionBios, Address, Length, Buffer); if (!EFI_ERROR(Status)) { DEBUG ((DEBUG_INFO, "MRC data successfully cached to 0x%X\n", Address)); PmcBaseAddr = PCI_LIB_ADDRESS ( DEFAULT_PCI_BUS_NUMBER_PCH, PCI_DEVICE_NUMBER_PCH_PMC, PCI_FUNCTION_NUMBER_PCH_PMC, 0); PciAnd16( PmcBaseAddr + R_PMC_PWRM_GEN_PMCON_B, (UINT16) ~(B_PMC_PWRM_GEN_PMCON_B_SUS_PWR_FLR ) ); PciAndThenOr8 ( PmcBaseAddr + R_PMC_PWRM_GEN_PMCON_A + 2, (UINT8) ~((B_PMC_PWRM_GEN_PMCON_A_MS4V ) >> 16), B_PMC_PWRM_GEN_PMCON_A_DISB >> 16 ); } } } return Status; } /** Update Serial Interface Information for Payload @param[in] SerialPortInfo Serial Interface Information to be updated for Payload **/ VOID EFIAPI UpdateSerialPortInfo ( IN SERIAL_PORT_INFO *SerialPortInfo ) { SerialPortInfo->BaseAddr = (UINT32) GetSerialPortBase(); SerialPortInfo->RegWidth = GetSerialPortStrideSize(); if (SerialPortInfo->BaseAddr < 0x10000) { // IO Type SerialPortInfo->Type = 1; } else { // MMIO Type SerialPortInfo->Type = 2; } } /** Update the OS boot option @param OsBootOptionList pointer to boot option list. **/ VOID EFIAPI UpdateOsBootMediumInfo ( OUT OS_BOOT_OPTION_LIST *OsBootOptionList ) { FillBootOptionListFromCfgData (OsBootOptionList); return; } /** Update Frame Buffer Information @param[out] GfxInfo Frame Buffer Information to be updated **/ VOID EFIAPI UpdateFrameBufferInfo ( OUT EFI_PEI_GRAPHICS_INFO_HOB *GfxInfo ) { if (PcdGetBool (PcdIntelGfxEnabled)) { GfxInfo->FrameBufferBase = PciRead32 (PCI_LIB_ADDRESS(0, 2, 0, 0x18)) & 0xFFFFFF00; } } /** Update the frame buffer device info. @param[out] GfxDeviceInfo pointer to EFI_PEI_GRAPHICS_DEVICE_INFO_HOB structure. **/ VOID UpdateFrameBufferDeviceInfo ( OUT EFI_PEI_GRAPHICS_DEVICE_INFO_HOB *GfxDeviceInfo ) { if (PcdGetBool (PcdIntelGfxEnabled)) { GfxDeviceInfo->BarIndex = 1; GfxDeviceInfo->VendorId = PciRead16 (PCI_LIB_ADDRESS (0, 2, 0, 0)); GfxDeviceInfo->DeviceId = PciRead16 (PCI_LIB_ADDRESS (0, 2, 0, 2)); } } /** Update loader SMM info. @param[out] LdrSmmInfo pointer to SMM information HOB **/ VOID UpdateSmmInfo ( OUT LDR_SMM_INFO *LdrSmmInfo ) { if (LdrSmmInfo == NULL) { return; } UINTN PmcBaseAddr; PmcBaseAddr = MM_PCI_ADDRESS ( DEFAULT_PCI_BUS_NUMBER_PCH, PCI_DEVICE_NUMBER_PCH_PMC, PCI_FUNCTION_NUMBER_PCH_PMC, 0); LdrSmmInfo->SmmBase = PcdGet32 (PcdSmramTsegBase); LdrSmmInfo->SmmSize = PcdGet32 (PcdSmramTsegSize); LdrSmmInfo->Flags = SMM_FLAGS_4KB_COMMUNICATION; DEBUG ((DEBUG_INFO, "SmmRamBase = 0x%x, SmmRamSize = 0x%x\n", LdrSmmInfo->SmmBase, LdrSmmInfo->SmmSize)); // // Update smi ctrl register data // LdrSmmInfo->SmiCtrlReg.RegType = (UINT8)REG_TYPE_IO; LdrSmmInfo->SmiCtrlReg.RegWidth = (UINT8)WIDE32; LdrSmmInfo->SmiCtrlReg.SmiGblPos = (UINT8)HighBitSet32 (B_ACPI_IO_SMI_EN_GBL_SMI); LdrSmmInfo->SmiCtrlReg.SmiApmPos = (UINT8)HighBitSet32 (B_ACPI_IO_SMI_EN_APMC); LdrSmmInfo->SmiCtrlReg.SmiEosPos = (UINT8)HighBitSet32 (B_ACPI_IO_SMI_EN_EOS); LdrSmmInfo->SmiCtrlReg.Address = (UINT32)(ACPI_BASE_ADDRESS + R_ACPI_IO_SMI_EN); // // Update smi status register data // LdrSmmInfo->SmiStsReg.RegType = (UINT8)REG_TYPE_IO; LdrSmmInfo->SmiStsReg.RegWidth = (UINT8)WIDE32; LdrSmmInfo->SmiStsReg.SmiApmPos = (UINT8)HighBitSet32 (B_ACPI_IO_SMI_STS_APM); LdrSmmInfo->SmiStsReg.Address = (UINT32)(ACPI_BASE_ADDRESS + R_ACPI_IO_SMI_STS); // // Update smi lock register data // LdrSmmInfo->SmiLockReg.RegType = (UINT8)REG_TYPE_MMIO; LdrSmmInfo->SmiLockReg.RegWidth = (UINT8)WIDE32; LdrSmmInfo->SmiLockReg.SmiLockPos = (UINT8)HighBitSet32 (B_PMC_PWRM_GEN_PMCON_A_SMI_LOCK); LdrSmmInfo->SmiLockReg.Address = (UINT32)(PmcBaseAddr + R_PMC_PWRM_GEN_PMCON_A); } /** Update loader platform info. @param[out] LoaderPlatformInfo pointer to platform info HOB **/ VOID UpdateLoaderPlatformInfo ( OUT LOADER_PLATFORM_INFO *LoaderPlatformInfo ) { PLATFORM_DATA *PlatformData; PlatformData = (PLATFORM_DATA *)GetPlatformDataPtr (); if(PlatformData != NULL) { LoaderPlatformInfo->HwState = PlatformData->BtGuardInfo.VerifiedBoot | (PlatformData->BtGuardInfo.MeasuredBoot << 1); LoaderPlatformInfo->Flags = FLAGS_SPI_DISABLE_SMM_WRITE_PROTECT; if (PlatformData->BtGuardInfo.TpmType == dTpm20) LoaderPlatformInfo->TpmType = TPM_TYPE_DTPM20; else if (PlatformData->BtGuardInfo.TpmType == Ptt) LoaderPlatformInfo->TpmType = TPM_TYPE_PTT; else if (PlatformData->BtGuardInfo.TpmType == TpmNone) LoaderPlatformInfo->TpmType = TPM_TYPE_NONE; DEBUG ((DEBUG_INFO, "Stage2: HwState 0x%x\n", LoaderPlatformInfo->HwState)); } } /** Update Hob Info with platform specific data @param Guid The GUID to tag the customized HOB. @param HobInfo The start address of GUID HOB data. **/VOID EFIAPI PlatformUpdateHobInfo ( IN CONST EFI_GUID *Guid, OUT VOID *HobInfo ) { ASSERT (Guid != NULL); ASSERT (HobInfo != NULL); if ((Guid == NULL) || (HobInfo == NULL)) { return; } // Just compare Guid memory addresses which are in Stage2 data section instead of CompareGuid () if (Guid == &gEfiGraphicsInfoHobGuid) { UpdateFrameBufferInfo (HobInfo); } else if (Guid == &gEfiGraphicsDeviceInfoHobGuid) { UpdateFrameBufferDeviceInfo (HobInfo); } else if (Guid == &gLoaderSerialPortInfoGuid) { UpdateSerialPortInfo (HobInfo); } else if (Guid == &gOsBootOptionGuid) { UpdateOsBootMediumInfo (HobInfo); } else if (Guid == &gSmmInformationGuid) { UpdateSmmInfo (HobInfo); } else if (Guid == &gLoaderPlatformInfoGuid) { UpdateLoaderPlatformInfo (HobInfo); } } /** Update Platform related ACPI Tables @param[in] Current A specific ACPI table pointer to be updated **/ EFI_STATUS EFIAPI PlatformUpdateAcpiTable ( IN UINT8 *Current ) { EFI_ACPI_MEMORY_MAPPED_ENHANCED_CONFIGURATION_SPACE_BASE_ADDRESS_ALLOCATION_STRUCTURE *MmCfg; EFI_ACPI_DESCRIPTION_HEADER *Table; UINT8 *Ptr; UINT8 *End; GLOBAL_NVS_AREA *GlobalNvs; UINT32 Base; UINT16 Size; EFI_STATUS Status; VOID *FspHobList; GlobalNvs = (GLOBAL_NVS_AREA *)(UINTN) PcdGet32 (PcdAcpiGnvsAddress); Table = (EFI_ACPI_DESCRIPTION_HEADER *) Current; Ptr = (UINT8 *)Table; End = (UINT8 *)Table + Table->Length; if (Table->Signature == EFI_ACPI_5_0_EMBEDDED_CONTROLLER_BOOT_RESOURCES_TABLE_SIGNATURE) { if ((mSiliconCfgData == NULL) || (mSiliconCfgData->ECEnable == 0)) { return EFI_UNSUPPORTED; } } if (Table->Signature == EFI_ACPI_5_0_DIFFERENTIATED_SYSTEM_DESCRIPTION_TABLE_SIGNATURE) { for (; Ptr < End; Ptr++) { if (*(Ptr-1) != AML_NAME_OP) continue; if (*(UINT32 *)Ptr == SIGNATURE_32 ('P','N','V','B')) { Base = (UINT32) (UINTN) &GlobalNvs->PchNvs; DEBUG ((DEBUG_INFO, "PNVB Old=0x%08X New=0x%08X\n", *(UINT32 *)(Ptr + 5), Base)); *(UINT32 *)(Ptr + 5) = Base; } else if (*(UINT32 *)Ptr == SIGNATURE_32 ('P','N','V','L')) { Size = sizeof (PCH_NVS_AREA); DEBUG ((DEBUG_INFO, "PNVL Old=0x%08X New=0x%08X\n", *(UINT16 *)(Ptr + 5), Size)); *(UINT16 *)(Ptr + 5) = Size; // PNVL is after PNVB break; } } } else if (Table->Signature == \ EFI_ACPI_5_0_PCI_EXPRESS_MEMORY_MAPPED_CONFIGURATION_SPACE_BASE_ADDRESS_DESCRIPTION_TABLE_SIGNATURE) { MmCfg = (EFI_ACPI_MEMORY_MAPPED_ENHANCED_CONFIGURATION_SPACE_BASE_ADDRESS_ALLOCATION_STRUCTURE *) ((EFI_ACPI_MEMORY_MAPPED_CONFIGURATION_BASE_ADDRESS_TABLE_HEADER *)Ptr + 1); Base = 0; while ((UINT8 *)MmCfg < End) { MmCfg->BaseAddress = PcdGet64 (PcdPciExpressBaseAddress) + Base; Base += 0x10000000; MmCfg++; } } else if (Table->OemTableId == SIGNATURE_64 ('S', 'a', 'S', 's', 'd', 't', ' ', 0)) { for (; Ptr < End; Ptr++) { if (*(UINT32 *)Ptr == SIGNATURE_32 ('S','A','N','V')) { Base = (UINT32) (UINTN) &GlobalNvs->SaNvs; DEBUG ((DEBUG_INFO, "SANV Base Old=0x%08X New=0x%08X\n", *(UINT32 *)(Ptr + 6), Base)); *(UINT32 *)(Ptr + 6) = Base; Size = sizeof (SYSTEM_AGENT_NVS_AREA); DEBUG ((DEBUG_INFO, "SANV Size Old=0x%04X New=0x%04X\n", *(UINT16 *)(Ptr + 11), Size)); *(UINT16 *)(Ptr + 11) = Size; break; } } } else if (Table->Signature == NHLT_ACPI_TABLE_SIGNATURE) { GlobalNvs->PchNvs.NHLA = (UINT64)(UINTN) Table; GlobalNvs->PchNvs.NHLL = Table->Length; DEBUG ((DEBUG_INFO, "NHLT Base 0x%08X, Size 0x%08X\n", (UINT32)(UINTN)GlobalNvs->PchNvs.NHLA, GlobalNvs->PchNvs.NHLL)); } else if (Table->OemTableId == SIGNATURE_64 ('C', 'p', 'u', 'S', 's', 'd', 't', 0)) { PatchCpuSsdtTable (Table, GlobalNvs); } else if (Table->OemTableId == SIGNATURE_64 ('C', 'p', 'u', '0', 'I', 's', 't', 0)) { PatchCpuIstTable (Table, GlobalNvs); } if (Table->Signature == EFI_BDAT_TABLE_SIGNATURE) { FspHobList = GetFspHobListPtr (); if (FspHobList != NULL) { UpdateBdatAcpiTable (Table, FspHobList); DEBUG ( (DEBUG_INFO, "Updated BDAT Table in AcpiTable Entries\n") ); } } if (FeaturePcdGet (PcdMeasuredBootEnabled)){ if ((Table->Signature == EFI_ACPI_5_0_TRUSTED_COMPUTING_PLATFORM_2_TABLE_SIGNATURE) || (Table->OemTableId == ACPI_SSDT_TPM2_DEVICE_OEM_TABLE_ID)) { if ((GetFeatureCfg () & FEATURE_MEASURED_BOOT) != 0) { Status = UpdateTpm2AcpiTable(Table); if (EFI_ERROR (Status)) { DEBUG ((DEBUG_ERROR, "UpdateTpm2AcpiTable fails! - %r\n", Status)); ASSERT_EFI_ERROR (Status); } DEBUG ((DEBUG_ERROR, "UpdateTpm2AcpiTable - %r\n", Status)); return Status; } return EFI_UNSUPPORTED; } } if (FeaturePcdGet (PcdPsdBiosEnabled)) { if (Table->Signature == EFI_ACPI_PSD_SIGNATURE) { PSD_CFG_DATA *PsdCfgData = NULL; PsdCfgData = (PSD_CFG_DATA *)FindConfigDataByTag (CDATA_PSD_TAG); if (PsdCfgData != NULL) { if (PsdCfgData->EnablePsd == 1) { UpdateAcpiPsdTable ( (VOID* )Current ); DEBUG ( (DEBUG_INFO, "Updated Psd Table in AcpiTable Entries\n") ); } } } } return EFI_SUCCESS; } /** Update CPU NVS from CpuInitDataHob @param[in, out] CpuNvs Pointer to CPU NVS region **/ VOID UpdateCpuNvs ( IN OUT CPU_NVS_AREA *CpuNvs ) { EFI_HOB_GUID_TYPE *GuidHob; CPU_INIT_DATA_HOB *CpuInitDataHob; VOID *FspHobList; if (CpuNvs == NULL) { DEBUG ((DEBUG_ERROR, "Invalid Cpu Nvs pointer!!!\n")); return; } /// /// Get CPU Init Data Hob /// GuidHob = NULL; FspHobList = GetFspHobListPtr (); if (FspHobList != NULL) { GuidHob = GetNextGuidHob (&gCpuInitDataHobGuid, FspHobList); } if (GuidHob == NULL) { DEBUG ((DEBUG_ERROR, "CPU Data HOB not available\n")); return; } CpuInitDataHob = GET_GUID_HOB_DATA (GuidHob); CopyMem (CpuNvs, (VOID *)(UINTN)CpuInitDataHob->CpuGnvsPointer, sizeof (CPU_NVS_AREA)); DEBUG ((DEBUG_INFO, "Update Cpu Nvs Done\n")); DEBUG ((DEBUG_INFO, "Revision 0x%X, PpmFlags 0x%08X\n", CpuNvs->Revision, CpuNvs->PpmFlags)); /// /// Initialize FVID table pointer /// mFvidPointer = (FVID_TABLE *) (UINTN) CpuInitDataHob->FvidTable; } /** Dynamic update of Global NVS data @param[in] GnvsIn Pointer to global nvs region **/ VOID EFIAPI PlatformUpdateAcpiGnvs ( IN VOID *GnvsIn ) { GLOBAL_NVS_AREA *GlobalNvs; PLATFORM_NVS_AREA *PlatformNvs; PCH_NVS_AREA *PchNvs; CPU_NVS_AREA *CpuNvs; SYSTEM_AGENT_NVS_AREA *SaNvs; SYS_CPU_INFO *SysCpuInfo; CONST UINT8 *PchSerialIoDevModeTable; UINT8 Index; UINT8 Length; UINT8 RpNum; UINT8 RpDev; UINT8 RpFun; UINT8 FuncIndex; UINT32 Data32; UINT16 PlatformId; GPIO_GROUP GroupToGpeDwX[3]; UINT32 GroupDw[3]; SILICON_CFG_DATA *SiliconCfgData; GlobalNvs = (GLOBAL_NVS_AREA *) GnvsIn; PlatformNvs = (PLATFORM_NVS_AREA *) &GlobalNvs->PlatformNvs; PchNvs = (PCH_NVS_AREA *) &GlobalNvs->PchNvs; CpuNvs = (CPU_NVS_AREA *) &GlobalNvs->CpuNvs; SaNvs = (SYSTEM_AGENT_NVS_AREA *) &GlobalNvs->SaNvs; ZeroMem (GlobalNvs, sizeof (GLOBAL_NVS_AREA)); PlatformId = GetPlatformId (); PlatformNvs->Ps2MouseEnable = 0x0; PlatformNvs->Ps2KbMsEnable = 0x0; // HD-Audio - board specific PlatformNvs->I2SC = 0; if (IsPchLp()) { PlatformNvs->I2SI = GPIO_CNL_LP_GPP_C8; PlatformNvs->I2SB = 0; } else { PlatformNvs->I2SI = GPIO_CNL_H_GPP_F5; PlatformNvs->I2SB = 2; } PlatformNvs->HdaDspPpModuleMask = 0; if ((PlatformId == PLATFORM_ID_CML_H) || (PlatformId == PLATFORM_ID_CML_S) || (PlatformId == PLATFORM_ID_CML_V)) { PlatformNvs->PcdH8S2113SIO = 1; } PlatformNvs->ApicEnable = 1; SiliconCfgData = (SILICON_CFG_DATA *)FindConfigDataByTag (CDATA_SILICON_TAG); if ( (SiliconCfgData != NULL) && (SiliconCfgData->ECEnable == 1)){ PlatformNvs->EcAvailable = 1; PlatformNvs->EcLowPowerMode = 0; PlatformNvs->EcSmiGpioPin = 0; PlatformNvs->EcLowPowerModeGpioPin = 0; if (PlatformNvs->EcAvailable == 1) { if (PlatformId == PLATFORM_ID_CML_H) { PlatformNvs->EcSmiGpioPin = GPIO_CNL_H_GPP_E3; PlatformNvs->EcLowPowerModeGpioPin = GPIO_CNL_H_GPP_B23; } else if ((PlatformId == PLATFORM_ID_CML_S) || (PlatformId == PLATFORM_ID_CML_V)) { PlatformNvs->EcSmiGpioPin = GPIO_CNL_H_GPP_I3; PlatformNvs->EcLowPowerModeGpioPin = 0; } } } PlatformNvs->PowerState = 1; PlatformNvs->Ac1TripPoint = 55; PlatformNvs->Ac0TripPoint = 71; PlatformNvs->Ac1FanSpeed = 75; PlatformNvs->Ac0FanSpeed = 100; PlatformNvs->PassiveThermalTripPoint = 95; PlatformNvs->PassiveTc1Value = 1; PlatformNvs->PassiveTc2Value = 5; PlatformNvs->PassiveTspValue = 10; PlatformNvs->CriticalThermalTripPoint = 110; PlatformNvs->EnableDptf = 0; // not supported for now PlatformNvs->EnableSaDevice = 1; PchNvs->PchSeries = PchSeries (); PchNvs->PchGeneration = (UINT16) PchGeneration (); PchNvs->PchStepping = (UINT16) PchStepping (); Length = GetPchMaxPciePortNum (); for (RpNum = 0; RpNum < Length; RpNum++) { Index = RpNum / PCH_PCIE_CONTROLLER_PORTS; FuncIndex = RpNum - mPchPcieControllerInfo[Index].RpNumBase; RpDev = mPchPcieControllerInfo[Index].DevNum; Data32 = MmioRead32 (PCH_PCR_ADDRESS (mPchPcieControllerInfo[Index].Pid, R_SPX_PCR_PCD)); RpFun = (Data32 >> (FuncIndex * S_SPX_PCR_PCD_RP_FIELD)) & B_SPX_PCR_PCD_RP1FN; Data32 = ((UINT8) RpDev << 16) | (UINT8) RpFun; PchNvs->RpAddress[RpNum] = Data32; DEBUG ((DEBUG_INFO, "RpAddress[%d] = 0x%08X\n", RpNum, PchNvs->RpAddress[RpNum])); // Need to match with FSP-S UPD PchNvs->PcieLtrMaxSnoopLatency[RpNum] = 0x1003; PchNvs->PcieLtrMaxNoSnoopLatency[RpNum] = 0x1003; } // // Update HPET base address. // PchNvs->HPTE = TRUE; PchNvs->HPTB = HPET_BASE_ADDRESS; // // Update SBREG_BAR. // PchNvs->SBRG = PCH_PCR_BASE_ADDRESS; // // Update PMC ACPIBASE and PWRMBASE // PchNvs->PMBS = ACPI_BASE_ADDRESS; PchNvs->PWRM = PCH_PWRM_BASE_ADDRESS; PchNvs->SdPowerEnableActiveHigh = 1; PchNvs->GBES = 1; PchNvs->EmmcEnabled = 1; PchNvs->SdPowerEnableActiveHigh = 1; PchNvs->EMH4 = 1; PchNvs->EMDS = 0x4; // // GPIO device // PchNvs->SGIR = DEFAULT_GPIO_IRQ_ROUTE; PchNvs->GPHD = 0; GpioGetGroupDwToGpeDwX ( &GroupToGpeDwX[0], &GroupDw[0], &GroupToGpeDwX[1], &GroupDw[1], &GroupToGpeDwX[2], &GroupDw[2] ); PchNvs->GEI0 = (UINT8) GpioGetGroupIndexFromGroup (GroupToGpeDwX[0]); PchNvs->GEI1 = (UINT8) GpioGetGroupIndexFromGroup (GroupToGpeDwX[1]); PchNvs->GEI2 = (UINT8) GpioGetGroupIndexFromGroup (GroupToGpeDwX[2]); PchNvs->GED0 = (UINT8) GroupDw[0]; PchNvs->GED1 = (UINT8) GroupDw[1]; PchNvs->GED2 = (UINT8) GroupDw[2]; DEBUG ((DEBUG_INFO, "GEI [0x%X 0x%X 0x%X], GED [0x%X 0x%X 0x%X]\n", PchNvs->GEI0, PchNvs->GEI1, PchNvs->GEI2, PchNvs->GED0, PchNvs->GED1, PchNvs->GED2)); if (IsPchLp()) { PchSerialIoDevModeTable = mPchLpSerialIoDevMode; } else { PchSerialIoDevModeTable = mPchSerialIoDevMode; } for (Index = 0; Index < PCH_MAX_SERIALIO_CONTROLLERS; Index ++) { PchNvs->SMD[Index] = PchSerialIoDevModeTable[Index]; PchNvs->SIR[Index] = FindSerialIoIrq (Index); PchNvs->SB0[Index] = FindSerialIoBar (Index, 0); PchNvs->SB1[Index] = FindSerialIoBar (Index, 1); DEBUG ((DEBUG_INFO, "SerialIo[%d] %d, %d, 0x%08X, 0x%08X\n", Index, \ PchNvs->SMD[Index], PchNvs->SIR[Index], PchNvs->SB0[Index], PchNvs->SB1[Index])); } // // Update platformId in NVS area // PlatformNvs->PlatformId = (UINT8) GetPlatformId (); SaNvs->Mmio32Base = PcdGet32(PcdPciResourceMem32Base); SaNvs->Mmio32Length = ACPI_MMIO_BASE_ADDRESS - SaNvs->Mmio32Base; SaNvs->AlsEnable = 0; SaNvs->IgdState = 1; SaNvs->BrightnessPercentage = 100; SaNvs->IgdBootType = 0; SaNvs->IgdPanelType = 0; SaNvs->IgdPanelScaling = 0; SaNvs->IgdDvmtMemSize = 2; SaNvs->IgdFunc1Enable = 0; Data32 = PciRead32 (PCI_LIB_ADDRESS(0, 0, 0, 0x48)); Data32 &= (UINT32) ~BIT0; SaNvs->IgdHpllVco = MmioRead8 (Data32 + 0xC0F) & 0x07; SaNvs->IgdSciSmiMode = 0; SaNvs->GfxTurboIMON = 31; SaNvs->EdpValid = 0; UpdateCpuNvs (CpuNvs); PlatformNvs->PpmFlags = CpuNvs->PpmFlags; SysCpuInfo = MpGetInfo (); if (SysCpuInfo != NULL) { PlatformNvs->ThreadCount = (UINT8) SysCpuInfo->CpuCount; } UpdateSgxNvs (CpuNvs); SocUpdateAcpiGnvs ((VOID *)GnvsIn); }
836954.c
#include "def.h" #include "sound.h" #include "hardware.h" #include "main.h" #include "digger.h" #include "input.h" #ifdef _WINDOWS #include "win_dig.h" #include "win_snd.h" #endif Sint4 wavetype=0,musvol=0; Sint4 spkrmode=0,timerrate=0x7d0; Uint4 timercount=0,t2val=0,t0val=0; Sint4 pulsewidth=1; Sint4 volume=0; Sint3 timerclock=0; bool soundflag=TRUE,musicflag=TRUE; void soundint(void); void soundlevdoneoff(void); void soundlevdoneupdate(void); void soundfallupdate(void); void soundbreakoff(void); void soundbreakupdate(void); void soundwobbleupdate(void); void soundfireupdate(void); void soundexplodeoff(int n); void soundexplodeupdate(void); void soundbonusupdate(void); void soundemoff(void); void soundemupdate(void); void soundemeraldoff(void); void soundemeraldupdate(void); void soundgoldoff(void); void soundgoldupdate(void); void soundeatmoff(void); void soundeatmupdate(void); void soundddieoff(void); void soundddieupdate(void); void sound1upoff(void); void sound1upupdate(void); void musicupdate(void); void sett0(void); void setsoundmode(void); void s0setupsound(void); void s0killsound(void); void s0fillbuffer(void); void (*setupsound)(void)=s0setupsound; void (*killsound)(void)=s0killsound; void (*fillbuffer)(void)=s0fillbuffer; void (*initint8)(void)=s0initint8; void (*restoreint8)(void)=s0restoreint8; void (*soundoff)(void)=s0soundoff; void (*setspkrt2)(void)=s0setspkrt2; void (*settimer0)(Uint4 t0v)=s0settimer0; void (*timer0)(Uint4 t0v)=s0timer0; void (*settimer2)(Uint4 t2v)=s0settimer2; void (*timer2)(Uint4 t2v)=s0timer2; void (*soundkillglob)(void)=s0soundkillglob; bool sndflag=FALSE,soundpausedflag=FALSE; Sint5 randvs; Sint4 randnos(Sint4 n) { randvs=randvs*0x15a4e35l+1; return (Sint4)((randvs&0x7fffffffl)%n); } void sett2val(Sint4 t2v) { if (sndflag) timer2(t2v); } void soundint(void) { timerclock++; if (soundflag && !sndflag) sndflag=musicflag=TRUE; if (!soundflag && sndflag) { sndflag=FALSE; timer2(40); setsoundt2(); soundoff(); } if (sndflag && !soundpausedflag) { t0val=0x7d00; t2val=40; if (musicflag) musicupdate(); #ifdef ARM else soundoff(); #endif soundemeraldupdate(); soundwobbleupdate(); soundddieupdate(); soundbreakupdate(); soundgoldupdate(); soundemupdate(); soundexplodeupdate(); soundfireupdate(); soundeatmupdate(); soundfallupdate(); sound1upupdate(); soundbonusupdate(); if (t0val==0x7d00 || t2val!=40) setsoundt2(); else { setsoundmode(); sett0(); } sett2val(t2val); } } void soundstop(void) { int i; soundfalloff(); soundwobbleoff(); for (i=0;i<FIREBALLS;i++) soundfireoff(i); musicoff(); soundbonusoff(); for (i=0;i<FIREBALLS;i++) soundexplodeoff(i); soundbreakoff(); soundemoff(); soundemeraldoff(); soundgoldoff(); soundeatmoff(); soundddieoff(); sound1upoff(); } bool soundlevdoneflag=FALSE; Sint4 nljpointer=0,nljnoteduration=0; void soundlevdone(void) { Sint4 timer=0; soundstop(); nljpointer=0; nljnoteduration=20; soundlevdoneflag=soundpausedflag=TRUE; while (soundlevdoneflag && !escape) { fillbuffer(); #ifdef _WINDOWS do_windows_events(); if (!wave_device_available) soundlevdoneflag=FALSE; #endif #ifdef ARM gretrace(); soundint(); #else if (timerclock==timer) continue; #endif soundlevdoneupdate(); checkkeyb(); timer=timerclock; } soundlevdoneoff(); } void soundlevdoneoff(void) { soundlevdoneflag=soundpausedflag=FALSE; } Sint4 newlevjingle[11]={0x8e8,0x712,0x5f2,0x7f0,0x6ac,0x54c, 0x712,0x5f2,0x4b8,0x474,0x474}; void soundlevdoneupdate(void) { if (sndflag) { if (nljpointer<11) t2val=newlevjingle[nljpointer]; t0val=t2val+35; musvol=50; setsoundmode(); sett0(); sett2val(t2val); if (nljnoteduration>0) nljnoteduration--; else { nljnoteduration=20; nljpointer++; if (nljpointer>10) soundlevdoneoff(); } } else soundlevdoneflag=FALSE; } bool soundfallflag=FALSE,soundfallf=FALSE; Sint4 soundfallvalue,soundfalln=0; void soundfall(void) { soundfallvalue=1000; soundfallflag=TRUE; } void soundfalloff(void) { soundfallflag=FALSE; soundfalln=0; } void soundfallupdate(void) { if (soundfallflag) if (soundfalln<1) { soundfalln++; if (soundfallf) t2val=soundfallvalue; } else { soundfalln=0; if (soundfallf) { soundfallvalue+=50; soundfallf=FALSE; } else soundfallf=TRUE; } } bool soundbreakflag=FALSE; Sint4 soundbreakduration=0,soundbreakvalue=0; void soundbreak(void) { soundbreakduration=3; if (soundbreakvalue<15000) soundbreakvalue=15000; soundbreakflag=TRUE; } void soundbreakoff(void) { soundbreakflag=FALSE; } void soundbreakupdate(void) { if (soundbreakflag) if (soundbreakduration!=0) { soundbreakduration--; t2val=soundbreakvalue; } else soundbreakflag=FALSE; } bool soundwobbleflag=FALSE; Sint4 soundwobblen=0; void soundwobble(void) { soundwobbleflag=TRUE; } void soundwobbleoff(void) { soundwobbleflag=FALSE; soundwobblen=0; } void soundwobbleupdate(void) { if (soundwobbleflag) { soundwobblen++; if (soundwobblen>63) soundwobblen=0; switch (soundwobblen) { case 0: t2val=0x7d0; break; case 16: case 48: t2val=0x9c4; break; case 32: t2val=0xbb8; break; } } } bool soundfireflag[FIREBALLS]={FALSE,FALSE},sff[FIREBALLS]; Sint4 soundfirevalue[FIREBALLS],soundfiren[FIREBALLS]={0,0}; int soundfirew=0; void soundfire(int n) { soundfirevalue[n]=500; soundfireflag[n]=TRUE; } void soundfireoff(int n) { soundfireflag[n]=FALSE; soundfiren[n]=0; } void soundfireupdate(void) { int n; bool f=FALSE; for (n=0;n<FIREBALLS;n++) { sff[n]=FALSE; if (soundfireflag[n]) if (soundfiren[n]==1) { soundfiren[n]=0; soundfirevalue[n]+=soundfirevalue[n]/55; sff[n]=TRUE; f=TRUE; if (soundfirevalue[n]>30000) soundfireoff(n); } else soundfiren[n]++; } if (f) { do { n=soundfirew++; if (soundfirew==FIREBALLS) soundfirew=0; } while (!sff[n]); t2val=soundfirevalue[n]+randnos(soundfirevalue[n]>>3); } } bool soundexplodeflag[FIREBALLS]={FALSE,FALSE},sef[FIREBALLS]; Sint4 soundexplodevalue[FIREBALLS],soundexplodeduration[FIREBALLS]; int soundexplodew=0; void soundexplode(int n) { soundexplodevalue[n]=1500; soundexplodeduration[n]=10; soundexplodeflag[n]=TRUE; soundfireoff(n); } void soundexplodeoff(int n) { soundexplodeflag[n]=FALSE; } void soundexplodeupdate(void) { int n; bool f=FALSE; for (n=0;n<FIREBALLS;n++) { sef[n]=FALSE; if (soundexplodeflag[n]) if (soundexplodeduration[n]!=0) { soundexplodevalue[n]=soundexplodevalue[n]-(soundexplodevalue[n]>>3); soundexplodeduration[n]--; sef[n]=TRUE; f=TRUE; } else soundexplodeflag[n]=FALSE; } if (f) { do { n=soundexplodew++; if (soundexplodew==FIREBALLS) soundexplodew=0; } while (!sef[n]); t2val=soundexplodevalue[n]; } } bool soundbonusflag=FALSE; Sint4 soundbonusn=0; void soundbonus(void) { soundbonusflag=TRUE; } void soundbonusoff(void) { soundbonusflag=FALSE; soundbonusn=0; } void soundbonusupdate(void) { if (soundbonusflag) { soundbonusn++; if (soundbonusn>15) soundbonusn=0; if (soundbonusn>=0 && soundbonusn<6) t2val=0x4ce; if (soundbonusn>=8 && soundbonusn<14) t2val=0x5e9; } } bool soundemflag=FALSE; void soundem(void) { soundemflag=TRUE; } void soundemoff(void) { soundemflag=FALSE; } void soundemupdate(void) { if (soundemflag) { t2val=1000; soundemoff(); } } bool soundemeraldflag=FALSE; Sint4 soundemeraldduration,emerfreq,soundemeraldn; Sint4 emfreqs[8]={0x8e8,0x7f0,0x712,0x6ac,0x5f2,0x54c,0x4b8,0x474}; void soundemerald(int n) { emerfreq=emfreqs[n]; soundemeraldduration=7; soundemeraldn=0; soundemeraldflag=TRUE; } void soundemeraldoff(void) { soundemeraldflag=FALSE; } void soundemeraldupdate(void) { if (soundemeraldflag) if (soundemeraldduration!=0) { if (soundemeraldn==0 || soundemeraldn==1) t2val=emerfreq; soundemeraldn++; if (soundemeraldn>7) { soundemeraldn=0; soundemeraldduration--; } } else soundemeraldoff(); } bool soundgoldflag=FALSE,soundgoldf=FALSE; Sint4 soundgoldvalue1,soundgoldvalue2,soundgoldduration; void soundgold(void) { soundgoldvalue1=500; soundgoldvalue2=4000; soundgoldduration=30; soundgoldf=FALSE; soundgoldflag=TRUE; } void soundgoldoff(void) { soundgoldflag=FALSE; } void soundgoldupdate(void) { if (soundgoldflag) { if (soundgoldduration!=0) soundgoldduration--; else soundgoldflag=FALSE; if (soundgoldf) { soundgoldf=FALSE; t2val=soundgoldvalue1; } else { soundgoldf=TRUE; t2val=soundgoldvalue2; } soundgoldvalue1+=(soundgoldvalue1>>4); soundgoldvalue2-=(soundgoldvalue2>>4); } } bool soundeatmflag=FALSE; Sint4 soundeatmvalue,soundeatmduration,soundeatmn; void soundeatm(void) { soundeatmduration=20; soundeatmn=3; soundeatmvalue=2000; soundeatmflag=TRUE; } void soundeatmoff(void) { soundeatmflag=FALSE; } void soundeatmupdate(void) { if (soundeatmflag) if (soundeatmn!=0) { if (soundeatmduration!=0) { if ((soundeatmduration%4)==1) t2val=soundeatmvalue; if ((soundeatmduration%4)==3) t2val=soundeatmvalue-(soundeatmvalue>>4); soundeatmduration--; soundeatmvalue-=(soundeatmvalue>>4); } else { soundeatmduration=20; soundeatmn--; soundeatmvalue=2000; } } else soundeatmflag=FALSE; } bool soundddieflag=FALSE; Sint4 soundddien,soundddievalue; void soundddie(void) { soundddien=0; soundddievalue=20000; soundddieflag=TRUE; } void soundddieoff(void) { soundddieflag=FALSE; } void soundddieupdate(void) { if (soundddieflag) { soundddien++; if (soundddien==1) musicoff(); if (soundddien>=1 && soundddien<=10) soundddievalue=20000-soundddien*1000; if (soundddien>10) soundddievalue+=500; if (soundddievalue>30000) soundddieoff(); t2val=soundddievalue; } } bool sound1upflag=FALSE; Sint4 sound1upduration=0; void sound1up(void) { sound1upduration=96; sound1upflag=TRUE; } void sound1upoff(void) { sound1upflag=FALSE; } void sound1upupdate(void) { if (sound1upflag) { if ((sound1upduration/3)%2!=0) t2val=(sound1upduration<<2)+600; sound1upduration--; if (sound1upduration<1) sound1upflag=FALSE; } } bool musicplaying=FALSE; Sint4 musicp=0,tuneno=0,noteduration=0,notevalue=0,musicmaxvol=0, musicattackrate=0,musicsustainlevel=0,musicdecayrate=0,musicnotewidth=0, musicreleaserate=0,musicstage=0,musicn=0; void music(Sint4 tune) { tuneno=tune; musicp=0; noteduration=0; switch (tune) { case 0: musicmaxvol=50; musicattackrate=20; musicsustainlevel=20; musicdecayrate=10; musicreleaserate=4; break; case 1: musicmaxvol=50; musicattackrate=50; musicsustainlevel=8; musicdecayrate=15; musicreleaserate=1; break; case 2: musicmaxvol=50; musicattackrate=50; musicsustainlevel=25; musicdecayrate=5; musicreleaserate=1; } musicplaying=TRUE; if (tune==2) soundddieoff(); } void musicoff(void) { musicplaying=FALSE; musicp=0; } Sint4 bonusjingle[321]={ 0x11d1,2,0x11d1,2,0x11d1,4,0x11d1,2,0x11d1,2,0x11d1,4,0x11d1,2,0x11d1,2, 0xd59,4, 0xbe4,4, 0xa98,4,0x11d1,2,0x11d1,2,0x11d1,4,0x11d1,2,0x11d1,2, 0x11d1,4, 0xd59,2, 0xa98,2, 0xbe4,4, 0xe24,4,0x11d1,4,0x11d1,2,0x11d1,2, 0x11d1,4,0x11d1,2,0x11d1,2,0x11d1,4,0x11d1,2,0x11d1,2, 0xd59,4, 0xbe4,4, 0xa98,4, 0xd59,2, 0xa98,2, 0x8e8,10,0xa00,2, 0xa98,2, 0xbe4,2, 0xd59,4, 0xa98,4, 0xd59,4,0x11d1,2,0x11d1,2,0x11d1,4,0x11d1,2,0x11d1,2,0x11d1,4, 0x11d1,2,0x11d1,2, 0xd59,4, 0xbe4,4, 0xa98,4,0x11d1,2,0x11d1,2,0x11d1,4, 0x11d1,2,0x11d1,2,0x11d1,4, 0xd59,2, 0xa98,2, 0xbe4,4, 0xe24,4,0x11d1,4, 0x11d1,2,0x11d1,2,0x11d1,4,0x11d1,2,0x11d1,2,0x11d1,4,0x11d1,2,0x11d1,2, 0xd59,4, 0xbe4,4, 0xa98,4, 0xd59,2, 0xa98,2, 0x8e8,10,0xa00,2, 0xa98,2, 0xbe4,2, 0xd59,4, 0xa98,4, 0xd59,4, 0xa98,2, 0xa98,2, 0xa98,4, 0xa98,2, 0xa98,2, 0xa98,4, 0xa98,2, 0xa98,2, 0xa98,4, 0x7f0,4, 0xa98,4, 0x7f0,4, 0xa98,4, 0x7f0,4, 0xa98,4, 0xbe4,4, 0xd59,4, 0xe24,4, 0xfdf,4, 0xa98,2, 0xa98,2, 0xa98,4, 0xa98,2, 0xa98,2, 0xa98,4, 0xa98,2, 0xa98,2, 0xa98,4, 0x7f0,4, 0xa98,4, 0x7f0,4, 0xa98,4, 0x7f0,4, 0x8e8,4, 0x970,4, 0x8e8,4, 0x970,4, 0x8e8,4, 0xa98,2, 0xa98,2, 0xa98,4, 0xa98,2, 0xa98,2, 0xa98,4, 0xa98,2, 0xa98,2, 0xa98,4, 0x7f0,4, 0xa98,4, 0x7f0,4, 0xa98,4, 0x7f0,4, 0xa98,4, 0xbe4,4, 0xd59,4, 0xe24,4, 0xfdf,4, 0xa98,2, 0xa98,2, 0xa98,4, 0xa98,2, 0xa98,2, 0xa98,4, 0xa98,2, 0xa98,2, 0xa98,4, 0x7f0,4, 0xa98,4, 0x7f0,4, 0xa98,4, 0x7f0,4, 0x8e8,4, 0x970,4, 0x8e8,4, 0x970,4, 0x8e8,4, 0x7d64}; Sint4 backgjingle[291]={ 0xfdf,2,0x11d1,2, 0xfdf,2,0x1530,2,0x1ab2,2,0x1530,2,0x1fbf,4, 0xfdf,2, 0x11d1,2, 0xfdf,2,0x1530,2,0x1ab2,2,0x1530,2,0x1fbf,4, 0xfdf,2, 0xe24,2, 0xd59,2, 0xe24,2, 0xd59,2, 0xfdf,2, 0xe24,2, 0xfdf,2, 0xe24,2,0x11d1,2, 0xfdf,2,0x11d1,2, 0xfdf,2,0x1400,2, 0xfdf,4, 0xfdf,2,0x11d1,2, 0xfdf,2, 0x1530,2,0x1ab2,2,0x1530,2,0x1fbf,4, 0xfdf,2,0x11d1,2, 0xfdf,2,0x1530,2, 0x1ab2,2,0x1530,2,0x1fbf,4, 0xfdf,2, 0xe24,2, 0xd59,2, 0xe24,2, 0xd59,2, 0xfdf,2, 0xe24,2, 0xfdf,2, 0xe24,2,0x11d1,2, 0xfdf,2,0x11d1,2, 0xfdf,2, 0xe24,2, 0xd59,4, 0xa98,2, 0xbe4,2, 0xa98,2, 0xd59,2,0x11d1,2, 0xd59,2, 0x1530,4, 0xa98,2, 0xbe4,2, 0xa98,2, 0xd59,2,0x11d1,2, 0xd59,2,0x1530,4, 0xa98,2, 0x970,2, 0x8e8,2, 0x970,2, 0x8e8,2, 0xa98,2, 0x970,2, 0xa98,2, 0x970,2, 0xbe4,2, 0xa98,2, 0xbe4,2, 0xa98,2, 0xd59,2, 0xa98,4, 0xa98,2, 0xbe4,2, 0xa98,2, 0xd59,2,0x11d1,2, 0xd59,2,0x1530,4, 0xa98,2, 0xbe4,2, 0xa98,2, 0xd59,2,0x11d1,2, 0xd59,2,0x1530,4, 0xa98,2, 0x970,2, 0x8e8,2, 0x970,2, 0x8e8,2, 0xa98,2, 0x970,2, 0xa98,2, 0x970,2, 0xbe4,2, 0xa98,2, 0xbe4,2, 0xa98,2, 0xd59,2, 0xa98,4, 0x7f0,2, 0x8e8,2, 0xa98,2, 0xd59,2, 0x11d1,2, 0xd59,2,0x1530,4, 0xa98,2, 0xbe4,2, 0xa98,2, 0xd59,2,0x11d1,2, 0xd59,2,0x1530,4, 0xa98,2, 0x970,2, 0x8e8,2, 0x970,2, 0x8e8,2, 0xa98,2, 0x970,2, 0xa98,2, 0x970,2, 0xbe4,2, 0xa98,2, 0xbe4,2, 0xd59,2, 0xbe4,2, 0xa98,4,0x7d64}; Sint4 dirge[]={ 0x7d00, 2,0x11d1, 6,0x11d1, 4,0x11d1, 2,0x11d1, 6, 0xefb, 4, 0xfdf, 2, 0xfdf, 4,0x11d1, 2,0x11d1, 4,0x12e0, 2,0x11d1,12,0x7d00,16,0x7d00,16, 0x7d00,16,0x7d00,16,0x7d00,16,0x7d00,16,0x7d00,16,0x7d00,16,0x7d00,16, 0x7d00,16,0x7d00,16,0x7d00,16,0x7d64}; void musicupdate(void) { if (!musicplaying) return; if (noteduration!=0) noteduration--; else { musicstage=musicn=0; switch (tuneno) { case 0: noteduration=bonusjingle[musicp+1]*3; musicnotewidth=noteduration-3; notevalue=bonusjingle[musicp]; musicp+=2; if (bonusjingle[musicp]==0x7d64) musicp=0; break; case 1: noteduration=backgjingle[musicp+1]*6; musicnotewidth=12; notevalue=backgjingle[musicp]; musicp+=2; if (backgjingle[musicp]==0x7d64) musicp=0; break; case 2: noteduration=dirge[musicp+1]*10; musicnotewidth=noteduration-10; notevalue=dirge[musicp]; musicp+=2; if (dirge[musicp]==0x7d64) musicp=0; break; } } musicn++; wavetype=1; t0val=notevalue; if (musicn>=musicnotewidth) musicstage=2; switch(musicstage) { case 0: if (musvol+musicattackrate>=musicmaxvol) { musicstage=1; musvol=musicmaxvol; break; } musvol+=musicattackrate; break; case 1: if (musvol-musicdecayrate<=musicsustainlevel) { musvol=musicsustainlevel; break; } musvol-=musicdecayrate; break; case 2: if (musvol-musicreleaserate<=1) { musvol=1; break; } musvol-=musicreleaserate; } if (musvol==1) t0val=0x7d00; } void soundpause(void) { soundpausedflag=TRUE; #ifdef _WINDOWS pause_windows_sound_playback(); #endif } void soundpauseoff(void) { soundpausedflag=FALSE; #ifdef _WINDOWS resume_windows_sound_playback(); #endif } void sett0(void) { if (sndflag) { timer2(t2val); if (t0val<1000 && (wavetype==1 || wavetype==2)) t0val=1000; timer0(t0val); timerrate=t0val; if (musvol<1) musvol=1; if (musvol>50) musvol=50; pulsewidth=musvol*volume; setsoundmode(); } } bool soundt0flag=FALSE; void setsoundt2(void) { if (soundt0flag) { spkrmode=0; soundt0flag=FALSE; setspkrt2(); } } void setsoundmode(void) { spkrmode=wavetype; if (!soundt0flag && sndflag) { soundt0flag=TRUE; setspkrt2(); } } bool int8flag=FALSE; void startint8(void) { if (!int8flag) { initint8(); timerrate=0x4000; settimer0(0x4000); int8flag=TRUE; } } void stopint8(void) { settimer0(0); if (int8flag) { restoreint8(); int8flag=FALSE; } sett2val(40); setspkrt2(); } void initsound(void) { settimer2(40); setspkrt2(); settimer0(0); wavetype=2; t0val=12000; musvol=8; t2val=40; soundt0flag=TRUE; sndflag=TRUE; spkrmode=0; int8flag=FALSE; setsoundt2(); soundstop(); setupsound(); timerrate=0x4000; settimer0(0x4000); randvs=getlrt(); } void s0killsound(void) { setsoundt2(); timer2(40); stopint8(); } void s0setupsound(void) { inittimer(); curtime=0; startint8(); } void s0fillbuffer(void) { }
203265.c
/* See LICENSE for license details. */ #include <errno.h> #include <math.h> #include <limits.h> #include <locale.h> #include <signal.h> #include <stdbool.h> #include <sys/select.h> #include <time.h> #include <unistd.h> #include <libgen.h> #include <X11/Xatom.h> #include <X11/Xlib.h> #include <X11/cursorfont.h> #include <X11/keysym.h> #include <X11/Xft/Xft.h> #include <X11/XKBlib.h> static char *argv0; #include "arg.h" #include "st.h" #include "win.h" /* types used in config.h */ typedef struct { uint mod; KeySym keysym; void (*func)(const Arg *); const Arg arg; } Shortcut; typedef struct { uint mod; uint button; void (*func)(const Arg *); const Arg arg; uint release; } MouseShortcut; typedef struct { KeySym k; uint mask; char *s; /* three-valued logic variables: 0 indifferent, 1 on, -1 off */ signed char appkey; /* application keypad */ signed char appcursor; /* application cursor */ } Key; /* X modifiers */ #define XK_ANY_MOD UINT_MAX #define XK_NO_MOD 0 #define XK_SWITCH_MOD (1<<13) /* function definitions used in config.h */ static void clipcopy(const Arg *); static void clippaste(const Arg *); static void numlock(const Arg *); static void selpaste(const Arg *); static void zoom(const Arg *); static void zoomabs(const Arg *); static void zoomreset(const Arg *); static void ttysend(const Arg *); /* config.h for applying patches and the configuration. */ #include "config.h" /* XEMBED messages */ #define XEMBED_FOCUS_IN 4 #define XEMBED_FOCUS_OUT 5 /* macros */ #define IS_SET(flag) ((win.mode & (flag)) != 0) #define TRUERED(x) (((x) & 0xff0000) >> 8) #define TRUEGREEN(x) (((x) & 0xff00)) #define TRUEBLUE(x) (((x) & 0xff) << 8) typedef XftDraw *Draw; typedef XftColor Color; typedef XftGlyphFontSpec GlyphFontSpec; /* Purely graphic info */ typedef struct { int tw, th; /* tty width and height */ int w, h; /* window width and height */ int ch; /* char height */ int cw; /* char width */ int mode; /* window state/mode flags */ int cursor; /* cursor style */ } TermWindow; typedef struct { Display *dpy; Colormap cmap; Window win; Drawable buf; GlyphFontSpec *specbuf; /* font spec buffer used for rendering */ Atom xembed, wmdeletewin, netwmname, netwmpid; struct { XIM xim; XIC xic; XPoint spot; XVaNestedList spotlist; } ime; Draw draw; Visual *vis; XSetWindowAttributes attrs; /* Here, we use the term *pointer* to differentiate the cursor * one sees when hovering the mouse over the terminal from, e.g., * a green rectangle where text would be entered. */ Cursor vpointer, bpointer; /* visible and hidden pointers */ int pointerisvisible; int scr; int isfixed; /* is fixed geometry? */ int depth; int l, t; /* left and top offset */ int gm; /* geometry mask */ } XWindow; typedef struct { Atom xtarget; char *primary, *clipboard; struct timespec tclick1; struct timespec tclick2; } XSelection; /* Font structure */ #define Font Font_ typedef struct { int height; int width; int ascent; int descent; int badslant; int badweight; short lbearing; short rbearing; XftFont *match; FcFontSet *set; FcPattern *pattern; } Font; /* Drawing Context */ typedef struct { Color *col; size_t collen; Font font, bfont, ifont, ibfont; GC gc; } DC; static inline ushort sixd_to_16bit(int); static int xmakeglyphfontspecs(XftGlyphFontSpec *, const Glyph *, int, int, int); static void xdrawglyphfontspecs(const XftGlyphFontSpec *, Glyph, int, int, int); static void xdrawglyph(Glyph, int, int); static void xclear(int, int, int, int); static int xgeommasktogravity(int); static int ximopen(Display *); static void ximinstantiate(Display *, XPointer, XPointer); static void ximdestroy(XIM, XPointer, XPointer); static int xicdestroy(XIC, XPointer, XPointer); static void xinit(int, int); static void cresize(int, int); static void xresize(int, int); static void xhints(void); static int xloadcolor(int, const char *, Color *); static int xloadfont(Font *, FcPattern *); static void xloadfonts(char *, double); static void xunloadfont(Font *); static void xunloadfonts(void); static void xsetenv(void); static void xseturgency(int); static int evcol(XEvent *); static int evrow(XEvent *); static void expose(XEvent *); static void visibility(XEvent *); static void unmap(XEvent *); static void kpress(XEvent *); static void cmessage(XEvent *); static void resize(XEvent *); static void focus(XEvent *); static uint buttonmask(uint); static int mouseaction(XEvent *, uint); static void brelease(XEvent *); static void bpress(XEvent *); static void bmotion(XEvent *); static void propnotify(XEvent *); static void selnotify(XEvent *); static void selclear_(XEvent *); static void selrequest(XEvent *); static void setsel(char *, Time); static void mousesel(XEvent *, int); static void mousereport(XEvent *); static char *kmap(KeySym, uint); static int match(uint, uint); static void run(void); static void usage(void); static void (*handler[LASTEvent])(XEvent *) = { [KeyPress] = kpress, [ClientMessage] = cmessage, [ConfigureNotify] = resize, [VisibilityNotify] = visibility, [UnmapNotify] = unmap, [Expose] = expose, [FocusIn] = focus, [FocusOut] = focus, [MotionNotify] = bmotion, [ButtonPress] = bpress, [ButtonRelease] = brelease, /* * Uncomment if you want the selection to disappear when you select something * different in another window. */ /* [SelectionClear] = selclear_, */ [SelectionNotify] = selnotify, /* * PropertyNotify is only turned on when there is some INCR transfer happening * for the selection retrieval. */ [PropertyNotify] = propnotify, [SelectionRequest] = selrequest, }; /* Globals */ static DC dc; static XWindow xw; static XSelection xsel; static TermWindow win; /* Font Ring Cache */ enum { FRC_NORMAL, FRC_ITALIC, FRC_BOLD, FRC_ITALICBOLD }; typedef struct { XftFont *font; int flags; Rune unicodep; } Fontcache; /* Fontcache is an array now. A new font will be appended to the array. */ static Fontcache *frc = NULL; static int frclen = 0; static int frccap = 0; static char *usedfont = NULL; static double usedfontsize = 0; static double defaultfontsize = 0; static char *opt_alpha = NULL; static char *opt_class = NULL; static char **opt_cmd = NULL; static char *opt_embed = NULL; static char *opt_font = NULL; static char *opt_io = NULL; static char *opt_line = NULL; static char *opt_name = NULL; static char *opt_title = NULL; static bool focused = true; static int oldbutton = 3; /* button event on startup: 3 = release */ void clipcopy(const Arg *dummy) { Atom clipboard; free(xsel.clipboard); xsel.clipboard = NULL; if (xsel.primary != NULL) { xsel.clipboard = xstrdup(xsel.primary); clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0); XSetSelectionOwner(xw.dpy, clipboard, xw.win, CurrentTime); } } void clippaste(const Arg *dummy) { Atom clipboard; clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0); XConvertSelection(xw.dpy, clipboard, xsel.xtarget, clipboard, xw.win, CurrentTime); } void selpaste(const Arg *dummy) { XConvertSelection(xw.dpy, XA_PRIMARY, xsel.xtarget, XA_PRIMARY, xw.win, CurrentTime); } void numlock(const Arg *dummy) { win.mode ^= MODE_NUMLOCK; } void zoom(const Arg *arg) { Arg larg; larg.f = usedfontsize + arg->f; zoomabs(&larg); } void zoomabs(const Arg *arg) { xunloadfonts(); xloadfonts(usedfont, arg->f); cresize(0, 0); redraw(); xhints(); } void zoomreset(const Arg *arg) { Arg larg; if (defaultfontsize > 0) { larg.f = defaultfontsize; zoomabs(&larg); } } void ttysend(const Arg *arg) { ttywrite(arg->s, strlen(arg->s), 1); } int evcol(XEvent *e) { int x = e->xbutton.x - borderpx; LIMIT(x, 0, win.tw - 1); return x / win.cw; } int evrow(XEvent *e) { int y = e->xbutton.y - borderpx; LIMIT(y, 0, win.th - 1); return y / win.ch; } void mousesel(XEvent *e, int done) { int type, seltype = SEL_REGULAR; uint state = e->xbutton.state & ~(Button1Mask | forcemousemod); for (type = 1; type < LEN(selmasks); ++type) { if (match(selmasks[type], state)) { seltype = type; break; } } selextend(evcol(e), evrow(e), seltype, done); if (done) setsel(getsel(), e->xbutton.time); } void mousereport(XEvent *e) { int len, x = evcol(e), y = evrow(e), button = e->xbutton.button, state = e->xbutton.state; char buf[40]; static int ox, oy; /* from urxvt */ if (e->xbutton.type == MotionNotify) { if (x == ox && y == oy) return; if (!IS_SET(MODE_MOUSEMOTION) && !IS_SET(MODE_MOUSEMANY)) return; /* MOUSE_MOTION: no reporting if no button is pressed */ if (IS_SET(MODE_MOUSEMOTION) && oldbutton == 3) return; button = oldbutton + 32; ox = x; oy = y; } else { if (!IS_SET(MODE_MOUSESGR) && e->xbutton.type == ButtonRelease) { button = 3; } else { button -= Button1; if (button >= 3) button += 64 - 3; } if (e->xbutton.type == ButtonPress) { oldbutton = button; ox = x; oy = y; } else if (e->xbutton.type == ButtonRelease) { oldbutton = 3; /* MODE_MOUSEX10: no button release reporting */ if (IS_SET(MODE_MOUSEX10)) return; if (button == 64 || button == 65) return; } } if (!IS_SET(MODE_MOUSEX10)) { button += ((state & ShiftMask ) ? 4 : 0) + ((state & Mod4Mask ) ? 8 : 0) + ((state & ControlMask) ? 16 : 0); } if (IS_SET(MODE_MOUSESGR)) { len = snprintf(buf, sizeof(buf), "\033[<%d;%d;%d%c", button, x+1, y+1, e->xbutton.type == ButtonRelease ? 'm' : 'M'); } else if (x < 223 && y < 223) { len = snprintf(buf, sizeof(buf), "\033[M%c%c%c", 32+button, 32+x+1, 32+y+1); } else { return; } ttywrite(buf, len, 0); } uint buttonmask(uint button) { return button == Button1 ? Button1Mask : button == Button2 ? Button2Mask : button == Button3 ? Button3Mask : button == Button4 ? Button4Mask : button == Button5 ? Button5Mask : 0; } int mouseaction(XEvent *e, uint release) { MouseShortcut *ms; /* ignore Button<N>mask for Button<N> - it's set on release */ uint state = e->xbutton.state & ~buttonmask(e->xbutton.button); for (ms = mshortcuts; ms < mshortcuts + LEN(mshortcuts); ms++) { if (ms->release == release && ms->button == e->xbutton.button && (match(ms->mod, state) || /* exact or forced */ match(ms->mod, state & ~forcemousemod))) { ms->func(&(ms->arg)); return 1; } } return 0; } void bpress(XEvent *e) { struct timespec now; int snap; if (IS_SET(MODE_MOUSE) && !(e->xbutton.state & forcemousemod)) { mousereport(e); return; } if (mouseaction(e, 0)) return; if (e->xbutton.button == Button1) { /* * If the user clicks below predefined timeouts specific * snapping behaviour is exposed. */ clock_gettime(CLOCK_MONOTONIC, &now); if (TIMEDIFF(now, xsel.tclick2) <= tripleclicktimeout) { snap = SNAP_LINE; } else if (TIMEDIFF(now, xsel.tclick1) <= doubleclicktimeout) { snap = SNAP_WORD; } else { snap = 0; } xsel.tclick2 = xsel.tclick1; xsel.tclick1 = now; selstart(evcol(e), evrow(e), snap); } } void propnotify(XEvent *e) { XPropertyEvent *xpev; Atom clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0); xpev = &e->xproperty; if (xpev->state == PropertyNewValue && (xpev->atom == XA_PRIMARY || xpev->atom == clipboard)) { selnotify(e); } } void selnotify(XEvent *e) { ulong nitems, ofs, rem; int format; uchar *data, *last, *repl; Atom type, incratom, property = None; incratom = XInternAtom(xw.dpy, "INCR", 0); ofs = 0; if (e->type == SelectionNotify) property = e->xselection.property; else if (e->type == PropertyNotify) property = e->xproperty.atom; if (property == None) return; do { if (XGetWindowProperty(xw.dpy, xw.win, property, ofs, BUFSIZ/4, False, AnyPropertyType, &type, &format, &nitems, &rem, &data)) { fprintf(stderr, "Clipboard allocation failed\n"); return; } if (e->type == PropertyNotify && nitems == 0 && rem == 0) { /* * If there is some PropertyNotify with no data, then * this is the signal of the selection owner that all * data has been transferred. We won't need to receive * PropertyNotify events anymore. */ MODBIT(xw.attrs.event_mask, 0, PropertyChangeMask); XChangeWindowAttributes(xw.dpy, xw.win, CWEventMask, &xw.attrs); } if (type == incratom) { /* * Activate the PropertyNotify events so we receive * when the selection owner does send us the next * chunk of data. */ MODBIT(xw.attrs.event_mask, 1, PropertyChangeMask); XChangeWindowAttributes(xw.dpy, xw.win, CWEventMask, &xw.attrs); /* * Deleting the property is the transfer start signal. */ XDeleteProperty(xw.dpy, xw.win, (int)property); continue; } /* * As seen in getsel: * Line endings are inconsistent in the terminal and GUI world * copy and pasting. When receiving some selection data, * replace all '\n' with '\r'. * FIXME: Fix the computer world. */ repl = data; last = data + nitems * format / 8; while ((repl = memchr(repl, '\n', last - repl))) { *repl++ = '\r'; } if (IS_SET(MODE_BRCKTPASTE) && ofs == 0) ttywrite("\033[200~", 6, 0); ttywrite((char *)data, nitems * format / 8, 1); if (IS_SET(MODE_BRCKTPASTE) && rem == 0) ttywrite("\033[201~", 6, 0); XFree(data); /* number of 32-bit chunks returned */ ofs += nitems * format / 32; } while (rem > 0); /* * Deleting the property again tells the selection owner to send the * next data chunk in the property. */ XDeleteProperty(xw.dpy, xw.win, (int)property); } void xclipcopy(void) { clipcopy(NULL); } void selclear_(XEvent *e) { selclear(); } void selrequest(XEvent *e) { XSelectionRequestEvent *xsre; XSelectionEvent xev; Atom xa_targets, string, clipboard; char *seltext; xsre = (XSelectionRequestEvent *) e; xev.type = SelectionNotify; xev.requestor = xsre->requestor; xev.selection = xsre->selection; xev.target = xsre->target; xev.time = xsre->time; if (xsre->property == None) xsre->property = xsre->target; /* reject */ xev.property = None; xa_targets = XInternAtom(xw.dpy, "TARGETS", 0); if (xsre->target == xa_targets) { /* respond with the supported type */ string = xsel.xtarget; XChangeProperty(xsre->display, xsre->requestor, xsre->property, XA_ATOM, 32, PropModeReplace, (uchar *) &string, 1); xev.property = xsre->property; } else if (xsre->target == xsel.xtarget || xsre->target == XA_STRING) { /* * xith XA_STRING non ascii characters may be incorrect in the * requestor. It is not our problem, use utf8. */ clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0); if (xsre->selection == XA_PRIMARY) { seltext = xsel.primary; } else if (xsre->selection == clipboard) { seltext = xsel.clipboard; } else { fprintf(stderr, "Unhandled clipboard selection 0x%lx\n", xsre->selection); return; } if (seltext != NULL) { XChangeProperty(xsre->display, xsre->requestor, xsre->property, xsre->target, 8, PropModeReplace, (uchar *)seltext, strlen(seltext)); xev.property = xsre->property; } } /* all done, send a notification to the listener */ if (!XSendEvent(xsre->display, xsre->requestor, 1, 0, (XEvent *) &xev)) fprintf(stderr, "Error sending SelectionNotify event\n"); } void setsel(char *str, Time t) { if (!str) return; free(xsel.primary); xsel.primary = str; XSetSelectionOwner(xw.dpy, XA_PRIMARY, xw.win, t); if (XGetSelectionOwner(xw.dpy, XA_PRIMARY) != xw.win) selclear(); } void xsetsel(char *str) { setsel(str, CurrentTime); } void brelease(XEvent *e) { if (IS_SET(MODE_MOUSE) && !(e->xbutton.state & forcemousemod)) { mousereport(e); return; } if (mouseaction(e, 1)) return; if (e->xbutton.button == Button1) mousesel(e, 1); } void bmotion(XEvent *e) { if (!xw.pointerisvisible) { XDefineCursor(xw.dpy, xw.win, xw.vpointer); xw.pointerisvisible = 1; if (!IS_SET(MODE_MOUSEMANY)) xsetpointermotion(0); } if (IS_SET(MODE_MOUSE) && !(e->xbutton.state & forcemousemod)) { mousereport(e); return; } mousesel(e, 0); } void cresize(int width, int height) { int col, row; if (width != 0) win.w = width; if (height != 0) win.h = height; col = (win.w - 2 * borderpx) / win.cw; row = (win.h - 2 * borderpx) / win.ch; col = MAX(1, col); row = MAX(1, row); tresize(col, row); xresize(col, row); ttyresize(win.tw, win.th); } void xresize(int col, int row) { win.tw = col * win.cw; win.th = row * win.ch; XFreePixmap(xw.dpy, xw.buf); xw.buf = XCreatePixmap(xw.dpy, xw.win, win.w, win.h, xw.depth); XftDrawChange(xw.draw, xw.buf); xclear(0, 0, win.w, win.h); /* resize to new width */ xw.specbuf = xrealloc(xw.specbuf, col * sizeof(GlyphFontSpec)); } ushort sixd_to_16bit(int x) { return x == 0 ? 0 : 0x3737 + 0x2828 * x; } int xloadcolor(int i, const char *name, Color *ncolor) { XRenderColor color = { .alpha = 0xffff }; if (!name) { if (BETWEEN(i, 16, 255)) { /* 256 color */ if (i < 6*6*6+16) { /* same colors as xterm */ color.red = sixd_to_16bit( ((i-16)/36)%6 ); color.green = sixd_to_16bit( ((i-16)/6) %6 ); color.blue = sixd_to_16bit( ((i-16)/1) %6 ); } else { /* greyscale */ color.red = 0x0808 + 0x0a0a * (i - (6*6*6+16)); color.green = color.blue = color.red; } return XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &color, ncolor); } else name = colorname[i]; } return XftColorAllocName(xw.dpy, xw.vis, xw.cmap, name, ncolor); } void xloadalpha(void) { /* set alpha value of bg color */ if (opt_alpha) alpha = strtof(opt_alpha, NULL); float const usedAlpha = focused ? alpha : alphaUnfocussed; dc.col[defaultbg].color.alpha = (unsigned short)(0xffff * usedAlpha); dc.col[defaultbg].pixel &= 0x00FFFFFF; dc.col[defaultbg].pixel |= (unsigned char)(0xff * usedAlpha) << 24; } void xloadcols(void) { int i; static int loaded; Color *cp; if (loaded) { for (cp = dc.col; cp < &dc.col[dc.collen]; ++cp) XftColorFree(xw.dpy, xw.vis, xw.cmap, cp); } else { dc.collen = MAX(LEN(colorname), 256); dc.col = xmalloc(dc.collen * sizeof(Color)); } for (i = 0; i < dc.collen; i++) if (!xloadcolor(i, NULL, &dc.col[i])) { if (colorname[i]) die("could not allocate color '%s'\n", colorname[i]); else die("could not allocate color %d\n", i); } /* set alpha value of bg color */ if (opt_alpha) alpha = strtof(opt_alpha, NULL); dc.col[defaultbg].color.alpha = (unsigned short)(0xffff * alpha); dc.col[defaultbg].pixel &= 0x00FFFFFF; dc.col[defaultbg].pixel |= (unsigned char)(0xff * alpha) << 24; xloadalpha(); loaded = 1; } int xsetcolorname(int x, const char *name) { Color ncolor; if (!BETWEEN(x, 0, dc.collen)) return 1; if (!xloadcolor(x, name, &ncolor)) return 1; XftColorFree(xw.dpy, xw.vis, xw.cmap, &dc.col[x]); dc.col[x] = ncolor; return 0; } /* * Absolute coordinates. */ void xclear(int x1, int y1, int x2, int y2) { XftDrawRect(xw.draw, &dc.col[IS_SET(MODE_REVERSE)? defaultfg : defaultbg], x1, y1, x2-x1, y2-y1); } void xhints(void) { XClassHint class = {opt_name ? opt_name : termname, opt_class ? opt_class : termname}; XWMHints wm = {.flags = InputHint, .input = 1}; XSizeHints *sizeh; sizeh = XAllocSizeHints(); sizeh->flags = PSize | PResizeInc | PBaseSize | PMinSize; sizeh->height = win.h; sizeh->width = win.w; sizeh->height_inc = win.ch; sizeh->width_inc = win.cw; sizeh->base_height = 2 * borderpx; sizeh->base_width = 2 * borderpx; sizeh->min_height = win.ch + 2 * borderpx; sizeh->min_width = win.cw + 2 * borderpx; if (xw.isfixed) { sizeh->flags |= PMaxSize; sizeh->min_width = sizeh->max_width = win.w; sizeh->min_height = sizeh->max_height = win.h; } if (xw.gm & (XValue|YValue)) { sizeh->flags |= USPosition | PWinGravity; sizeh->x = xw.l; sizeh->y = xw.t; sizeh->win_gravity = xgeommasktogravity(xw.gm); } XSetWMProperties(xw.dpy, xw.win, NULL, NULL, NULL, 0, sizeh, &wm, &class); XFree(sizeh); } int xgeommasktogravity(int mask) { switch (mask & (XNegative|YNegative)) { case 0: return NorthWestGravity; case XNegative: return NorthEastGravity; case YNegative: return SouthWestGravity; } return SouthEastGravity; } int xloadfont(Font *f, FcPattern *pattern) { FcPattern *configured; FcPattern *match; FcResult result; XGlyphInfo extents; int wantattr, haveattr; /* * Manually configure instead of calling XftMatchFont * so that we can use the configured pattern for * "missing glyph" lookups. */ configured = FcPatternDuplicate(pattern); if (!configured) return 1; FcConfigSubstitute(NULL, configured, FcMatchPattern); XftDefaultSubstitute(xw.dpy, xw.scr, configured); match = FcFontMatch(NULL, configured, &result); if (!match) { FcPatternDestroy(configured); return 1; } if (!(f->match = XftFontOpenPattern(xw.dpy, match))) { FcPatternDestroy(configured); FcPatternDestroy(match); return 1; } if ((XftPatternGetInteger(pattern, "slant", 0, &wantattr) == XftResultMatch)) { /* * Check if xft was unable to find a font with the appropriate * slant but gave us one anyway. Try to mitigate. */ if ((XftPatternGetInteger(f->match->pattern, "slant", 0, &haveattr) != XftResultMatch) || haveattr < wantattr) { f->badslant = 1; fputs("font slant does not match\n", stderr); } } if ((XftPatternGetInteger(pattern, "weight", 0, &wantattr) == XftResultMatch)) { if ((XftPatternGetInteger(f->match->pattern, "weight", 0, &haveattr) != XftResultMatch) || haveattr != wantattr) { f->badweight = 1; fputs("font weight does not match\n", stderr); } } XftTextExtentsUtf8(xw.dpy, f->match, (const FcChar8 *) ascii_printable, strlen(ascii_printable), &extents); f->set = NULL; f->pattern = configured; f->ascent = f->match->ascent; f->descent = f->match->descent; f->lbearing = 0; f->rbearing = f->match->max_advance_width; f->height = f->ascent + f->descent; f->width = DIVCEIL(extents.xOff, strlen(ascii_printable)); return 0; } void xloadfonts(char *fontstr, double fontsize) { FcPattern *pattern; double fontval; if (fontstr[0] == '-') pattern = XftXlfdParse(fontstr, False, False); else pattern = FcNameParse((FcChar8 *)fontstr); if (!pattern) die("can't open font %s\n", fontstr); if (fontsize > 1) { FcPatternDel(pattern, FC_PIXEL_SIZE); FcPatternDel(pattern, FC_SIZE); FcPatternAddDouble(pattern, FC_PIXEL_SIZE, (double)fontsize); usedfontsize = fontsize; } else { if (FcPatternGetDouble(pattern, FC_PIXEL_SIZE, 0, &fontval) == FcResultMatch) { usedfontsize = fontval; } else if (FcPatternGetDouble(pattern, FC_SIZE, 0, &fontval) == FcResultMatch) { usedfontsize = -1; } else { /* * Default font size is 12, if none given. This is to * have a known usedfontsize value. */ FcPatternAddDouble(pattern, FC_PIXEL_SIZE, 12); usedfontsize = 12; } defaultfontsize = usedfontsize; } if (xloadfont(&dc.font, pattern)) die("can't open font %s\n", fontstr); if (usedfontsize < 0) { FcPatternGetDouble(dc.font.match->pattern, FC_PIXEL_SIZE, 0, &fontval); usedfontsize = fontval; if (fontsize == 0) defaultfontsize = fontval; } /* Setting character width and height. */ win.cw = ceilf(dc.font.width * cwscale); win.ch = ceilf(dc.font.height * chscale); FcPatternDel(pattern, FC_SLANT); FcPatternAddInteger(pattern, FC_SLANT, FC_SLANT_ITALIC); if (xloadfont(&dc.ifont, pattern)) die("can't open font %s\n", fontstr); FcPatternDel(pattern, FC_WEIGHT); FcPatternAddInteger(pattern, FC_WEIGHT, FC_WEIGHT_BOLD); if (xloadfont(&dc.ibfont, pattern)) die("can't open font %s\n", fontstr); FcPatternDel(pattern, FC_SLANT); FcPatternAddInteger(pattern, FC_SLANT, FC_SLANT_ROMAN); if (xloadfont(&dc.bfont, pattern)) die("can't open font %s\n", fontstr); FcPatternDestroy(pattern); } void xunloadfont(Font *f) { XftFontClose(xw.dpy, f->match); FcPatternDestroy(f->pattern); if (f->set) FcFontSetDestroy(f->set); } void xunloadfonts(void) { /* Free the loaded fonts in the font cache. */ while (frclen > 0) XftFontClose(xw.dpy, frc[--frclen].font); xunloadfont(&dc.font); xunloadfont(&dc.bfont); xunloadfont(&dc.ifont); xunloadfont(&dc.ibfont); } int ximopen(Display *dpy) { XIMCallback imdestroy = { .client_data = NULL, .callback = ximdestroy }; XICCallback icdestroy = { .client_data = NULL, .callback = xicdestroy }; xw.ime.xim = XOpenIM(xw.dpy, NULL, NULL, NULL); if (xw.ime.xim == NULL) return 0; if (XSetIMValues(xw.ime.xim, XNDestroyCallback, &imdestroy, NULL)) fprintf(stderr, "XSetIMValues: " "Could not set XNDestroyCallback.\n"); xw.ime.spotlist = XVaCreateNestedList(0, XNSpotLocation, &xw.ime.spot, NULL); if (xw.ime.xic == NULL) { xw.ime.xic = XCreateIC(xw.ime.xim, XNInputStyle, XIMPreeditNothing | XIMStatusNothing, XNClientWindow, xw.win, XNDestroyCallback, &icdestroy, NULL); } if (xw.ime.xic == NULL) fprintf(stderr, "XCreateIC: Could not create input context.\n"); return 1; } void ximinstantiate(Display *dpy, XPointer client, XPointer call) { if (ximopen(dpy)) XUnregisterIMInstantiateCallback(xw.dpy, NULL, NULL, NULL, ximinstantiate, NULL); } void ximdestroy(XIM xim, XPointer client, XPointer call) { xw.ime.xim = NULL; XRegisterIMInstantiateCallback(xw.dpy, NULL, NULL, NULL, ximinstantiate, NULL); XFree(xw.ime.spotlist); } int xicdestroy(XIC xim, XPointer client, XPointer call) { xw.ime.xic = NULL; return 1; } void xinit(int cols, int rows) { XGCValues gcvalues; Window parent; pid_t thispid = getpid(); XColor xmousefg, xmousebg; XWindowAttributes attr; XVisualInfo vis; Pixmap blankpm; if (!(xw.dpy = XOpenDisplay(NULL))) die("can't open display\n"); xw.scr = XDefaultScreen(xw.dpy); if (!(opt_embed && (parent = strtol(opt_embed, NULL, 0)))) { parent = XRootWindow(xw.dpy, xw.scr); xw.depth = 32; } else { XGetWindowAttributes(xw.dpy, parent, &attr); xw.depth = attr.depth; } XMatchVisualInfo(xw.dpy, xw.scr, xw.depth, TrueColor, &vis); xw.vis = vis.visual; /* font */ if (!FcInit()) die("could not init fontconfig.\n"); usedfont = (opt_font == NULL)? font : opt_font; xloadfonts(usedfont, 0); /* colors */ xw.cmap = XCreateColormap(xw.dpy, parent, xw.vis, None); xloadcols(); /* adjust fixed window geometry */ win.w = 2 * borderpx + cols * win.cw; win.h = 2 * borderpx + rows * win.ch; if (xw.gm & XNegative) xw.l += DisplayWidth(xw.dpy, xw.scr) - win.w - 2; if (xw.gm & YNegative) xw.t += DisplayHeight(xw.dpy, xw.scr) - win.h - 2; /* Events */ xw.attrs.background_pixel = dc.col[defaultbg].pixel; xw.attrs.border_pixel = dc.col[defaultbg].pixel; xw.attrs.bit_gravity = NorthWestGravity; xw.attrs.event_mask = FocusChangeMask | KeyPressMask | KeyReleaseMask | ExposureMask | VisibilityChangeMask | StructureNotifyMask | ButtonMotionMask | ButtonPressMask | ButtonReleaseMask; xw.attrs.colormap = xw.cmap; xw.win = XCreateWindow(xw.dpy, parent, xw.l, xw.t, + win.w, win.h, 0, xw.depth, InputOutput, xw.vis, CWBackPixel | CWBorderPixel | CWBitGravity | CWEventMask | CWColormap, &xw.attrs); memset(&gcvalues, 0, sizeof(gcvalues)); gcvalues.graphics_exposures = False; xw.buf = XCreatePixmap(xw.dpy, xw.win, win.w, win.h, xw.depth); dc.gc = XCreateGC(xw.dpy, xw.buf, GCGraphicsExposures, &gcvalues); XSetForeground(xw.dpy, dc.gc, dc.col[defaultbg].pixel); XFillRectangle(xw.dpy, xw.buf, dc.gc, 0, 0, win.w, win.h); /* font spec buffer */ xw.specbuf = xmalloc(cols * sizeof(GlyphFontSpec)); /* Xft rendering context */ xw.draw = XftDrawCreate(xw.dpy, xw.buf, xw.vis, xw.cmap); /* input methods */ if (!ximopen(xw.dpy)) { XRegisterIMInstantiateCallback(xw.dpy, NULL, NULL, NULL, ximinstantiate, NULL); } /* white cursor, black outline */ xw.pointerisvisible = 1; xw.vpointer = XCreateFontCursor(xw.dpy, mouseshape); XDefineCursor(xw.dpy, xw.win, xw.vpointer); if (XParseColor(xw.dpy, xw.cmap, colorname[mousefg], &xmousefg) == 0) { xmousefg.red = 0xffff; xmousefg.green = 0xffff; xmousefg.blue = 0xffff; } if (XParseColor(xw.dpy, xw.cmap, colorname[mousebg], &xmousebg) == 0) { xmousebg.red = 0x0000; xmousebg.green = 0x0000; xmousebg.blue = 0x0000; } XRecolorCursor(xw.dpy, xw.vpointer, &xmousefg, &xmousebg); blankpm = XCreateBitmapFromData(xw.dpy, xw.win, &(char){0}, 1, 1); xw.bpointer = XCreatePixmapCursor(xw.dpy, blankpm, blankpm, &xmousefg, &xmousebg, 0, 0); xw.xembed = XInternAtom(xw.dpy, "_XEMBED", False); xw.wmdeletewin = XInternAtom(xw.dpy, "WM_DELETE_WINDOW", False); xw.netwmname = XInternAtom(xw.dpy, "_NET_WM_NAME", False); XSetWMProtocols(xw.dpy, xw.win, &xw.wmdeletewin, 1); xw.netwmpid = XInternAtom(xw.dpy, "_NET_WM_PID", False); XChangeProperty(xw.dpy, xw.win, xw.netwmpid, XA_CARDINAL, 32, PropModeReplace, (uchar *)&thispid, 1); win.mode = MODE_NUMLOCK; resettitle(); xhints(); XMapWindow(xw.dpy, xw.win); XSync(xw.dpy, False); clock_gettime(CLOCK_MONOTONIC, &xsel.tclick1); clock_gettime(CLOCK_MONOTONIC, &xsel.tclick2); xsel.primary = NULL; xsel.clipboard = NULL; xsel.xtarget = XInternAtom(xw.dpy, "UTF8_STRING", 0); if (xsel.xtarget == None) xsel.xtarget = XA_STRING; boxdraw_xinit(xw.dpy, xw.cmap, xw.draw, xw.vis); } int xmakeglyphfontspecs(XftGlyphFontSpec *specs, const Glyph *glyphs, int len, int x, int y) { float winx = borderpx + x * win.cw, winy = borderpx + y * win.ch, xp, yp; ushort mode, prevmode = USHRT_MAX; Font *font = &dc.font; int frcflags = FRC_NORMAL; float runewidth = win.cw; Rune rune; FT_UInt glyphidx; FcResult fcres; FcPattern *fcpattern, *fontpattern; FcFontSet *fcsets[] = { NULL }; FcCharSet *fccharset; int i, f, numspecs = 0; for (i = 0, xp = winx, yp = winy + font->ascent; i < len; ++i) { /* Fetch rune and mode for current glyph. */ rune = glyphs[i].u; mode = glyphs[i].mode; /* Skip dummy wide-character spacing. */ if (mode == ATTR_WDUMMY) continue; /* Determine font for glyph if different from previous glyph. */ if (prevmode != mode) { prevmode = mode; font = &dc.font; frcflags = FRC_NORMAL; runewidth = win.cw * ((mode & ATTR_WIDE) ? 2.0f : 1.0f); if ((mode & ATTR_ITALIC) && (mode & ATTR_BOLD)) { font = &dc.ibfont; frcflags = FRC_ITALICBOLD; } else if (mode & ATTR_ITALIC) { font = &dc.ifont; frcflags = FRC_ITALIC; } else if (mode & ATTR_BOLD) { font = &dc.bfont; frcflags = FRC_BOLD; } yp = winy + font->ascent; } if (mode & ATTR_BOXDRAW) { /* minor shoehorning: boxdraw uses only this ushort */ glyphidx = boxdrawindex(&glyphs[i]); } else { /* Lookup character index with default font. */ glyphidx = XftCharIndex(xw.dpy, font->match, rune); } if (glyphidx) { specs[numspecs].font = font->match; specs[numspecs].glyph = glyphidx; specs[numspecs].x = (short)xp; specs[numspecs].y = (short)yp; xp += runewidth; numspecs++; continue; } /* Fallback on font cache, search the font cache for match. */ for (f = 0; f < frclen; f++) { glyphidx = XftCharIndex(xw.dpy, frc[f].font, rune); /* Everything correct. */ if (glyphidx && frc[f].flags == frcflags) break; /* We got a default font for a not found glyph. */ if (!glyphidx && frc[f].flags == frcflags && frc[f].unicodep == rune) { break; } } /* Nothing was found. Use fontconfig to find matching font. */ if (f >= frclen) { if (!font->set) font->set = FcFontSort(0, font->pattern, 1, 0, &fcres); fcsets[0] = font->set; /* * Nothing was found in the cache. Now use * some dozen of Fontconfig calls to get the * font for one single character. * * Xft and fontconfig are design failures. */ fcpattern = FcPatternDuplicate(font->pattern); fccharset = FcCharSetCreate(); FcCharSetAddChar(fccharset, rune); FcPatternAddCharSet(fcpattern, FC_CHARSET, fccharset); FcPatternAddBool(fcpattern, FC_SCALABLE, 1); FcConfigSubstitute(0, fcpattern, FcMatchPattern); FcDefaultSubstitute(fcpattern); fontpattern = FcFontSetMatch(0, fcsets, 1, fcpattern, &fcres); /* Allocate memory for the new cache entry. */ if (frclen >= frccap) { frccap += 16; frc = xrealloc(frc, frccap * sizeof(Fontcache)); } frc[frclen].font = XftFontOpenPattern(xw.dpy, fontpattern); if (!frc[frclen].font) die("XftFontOpenPattern failed seeking fallback font: %s\n", strerror(errno)); frc[frclen].flags = frcflags; frc[frclen].unicodep = rune; glyphidx = XftCharIndex(xw.dpy, frc[frclen].font, rune); f = frclen; frclen++; FcPatternDestroy(fcpattern); FcCharSetDestroy(fccharset); } specs[numspecs].font = frc[f].font; specs[numspecs].glyph = glyphidx; specs[numspecs].x = (short)xp; specs[numspecs].y = (short)yp; xp += runewidth; numspecs++; } return numspecs; } void xdrawglyphfontspecs(const XftGlyphFontSpec *specs, Glyph base, int len, int x, int y) { int charlen = len * ((base.mode & ATTR_WIDE) ? 2 : 1); int winx = borderpx + x * win.cw, winy = borderpx + y * win.ch, width = charlen * win.cw; Color *fg, *bg, *temp, revfg, revbg, truefg, truebg; XRenderColor colfg, colbg; XRectangle r; /* Fallback on color display for attributes not supported by the font */ if (base.mode & ATTR_ITALIC && base.mode & ATTR_BOLD) { if (dc.ibfont.badslant || dc.ibfont.badweight) base.fg = defaultattr; } else if ((base.mode & ATTR_ITALIC && dc.ifont.badslant) || (base.mode & ATTR_BOLD && dc.bfont.badweight)) { base.fg = defaultattr; } if (IS_TRUECOL(base.fg)) { colfg.alpha = 0xffff; colfg.red = TRUERED(base.fg); colfg.green = TRUEGREEN(base.fg); colfg.blue = TRUEBLUE(base.fg); XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg, &truefg); fg = &truefg; } else { fg = &dc.col[base.fg]; } if (IS_TRUECOL(base.bg)) { colbg.alpha = 0xffff; colbg.green = TRUEGREEN(base.bg); colbg.red = TRUERED(base.bg); colbg.blue = TRUEBLUE(base.bg); XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colbg, &truebg); bg = &truebg; } else { bg = &dc.col[base.bg]; } /* Change basic system colors [0-7] to bright system colors [8-15] */ if ((base.mode & ATTR_BOLD_FAINT) == ATTR_BOLD && BETWEEN(base.fg, 0, 7)) fg = &dc.col[base.fg + 8]; if (IS_SET(MODE_REVERSE)) { if (fg == &dc.col[defaultfg]) { fg = &dc.col[defaultbg]; } else { colfg.red = ~fg->color.red; colfg.green = ~fg->color.green; colfg.blue = ~fg->color.blue; colfg.alpha = fg->color.alpha; XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg, &revfg); fg = &revfg; } if (bg == &dc.col[defaultbg]) { bg = &dc.col[defaultfg]; } else { colbg.red = ~bg->color.red; colbg.green = ~bg->color.green; colbg.blue = ~bg->color.blue; colbg.alpha = bg->color.alpha; XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colbg, &revbg); bg = &revbg; } } if ((base.mode & ATTR_BOLD_FAINT) == ATTR_FAINT) { colfg.red = fg->color.red / 2; colfg.green = fg->color.green / 2; colfg.blue = fg->color.blue / 2; colfg.alpha = fg->color.alpha; XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg, &revfg); fg = &revfg; } if (base.mode & ATTR_REVERSE) { temp = fg; fg = bg; bg = temp; } if (base.mode & ATTR_BLINK && win.mode & MODE_BLINK) fg = bg; if (base.mode & ATTR_INVISIBLE) fg = bg; /* Intelligent cleaning up of the borders. */ if (x == 0) { xclear(0, (y == 0)? 0 : winy, borderpx, winy + win.ch + ((winy + win.ch >= borderpx + win.th)? win.h : 0)); } if (winx + width >= borderpx + win.tw) { xclear(winx + width, (y == 0)? 0 : winy, win.w, ((winy + win.ch >= borderpx + win.th)? win.h : (winy + win.ch))); } if (y == 0) xclear(winx, 0, winx + width, borderpx); if (winy + win.ch >= borderpx + win.th) xclear(winx, winy + win.ch, winx + width, win.h); /* Clean up the region we want to draw to. */ XftDrawRect(xw.draw, bg, winx, winy, width, win.ch); /* Set the clip region because Xft is sometimes dirty. */ r.x = 0; r.y = 0; r.height = win.ch; r.width = width; XftDrawSetClipRectangles(xw.draw, winx, winy, &r, 1); if (base.mode & ATTR_BOXDRAW) { drawboxes(winx, winy, width / len, win.ch, fg, bg, specs, len); } else { /* Render the glyphs. */ XftDrawGlyphFontSpec(xw.draw, fg, specs, len); } /* Render underline and strikethrough. */ if (base.mode & ATTR_UNDERLINE) { XftDrawRect(xw.draw, fg, winx, winy + dc.font.ascent + 1, width, 1); } if (base.mode & ATTR_STRUCK) { XftDrawRect(xw.draw, fg, winx, winy + 2 * dc.font.ascent / 3, width, 1); } /* Reset clip to none. */ XftDrawSetClip(xw.draw, 0); } void xdrawglyph(Glyph g, int x, int y) { int numspecs; XftGlyphFontSpec spec; numspecs = xmakeglyphfontspecs(&spec, &g, 1, x, y); xdrawglyphfontspecs(&spec, g, numspecs, x, y); } void xdrawcursor(int cx, int cy, Glyph g, int ox, int oy, Glyph og) { Color drawcol; /* remove the old cursor */ if (selected(ox, oy)) og.mode ^= ATTR_REVERSE; xdrawglyph(og, ox, oy); if (IS_SET(MODE_HIDE)) return; /* * Select the right color for the right mode. */ g.mode &= ATTR_BOLD|ATTR_ITALIC|ATTR_UNDERLINE|ATTR_STRUCK|ATTR_WIDE|ATTR_BOXDRAW; if (IS_SET(MODE_REVERSE)) { g.mode |= ATTR_REVERSE; g.bg = defaultfg; if (selected(cx, cy)) { drawcol = dc.col[defaultcs]; g.fg = defaultrcs; } else { drawcol = dc.col[defaultrcs]; g.fg = defaultcs; } } else { if (selected(cx, cy)) { g.fg = defaultfg; g.bg = defaultrcs; } else { g.fg = defaultbg; g.bg = defaultcs; } drawcol = dc.col[g.bg]; } /* draw the new one */ if (IS_SET(MODE_FOCUSED)) { switch (win.cursor) { case 7: /* st extension: snowman (U+2603) */ g.u = 0x2603; case 0: /* Blinking Block */ case 1: /* Blinking Block (Default) */ case 2: /* Steady Block */ xdrawglyph(g, cx, cy); break; case 3: /* Blinking Underline */ case 4: /* Steady Underline */ XftDrawRect(xw.draw, &drawcol, borderpx + cx * win.cw, borderpx + (cy + 1) * win.ch - \ cursorthickness, win.cw, cursorthickness); break; case 5: /* Blinking bar */ case 6: /* Steady bar */ XftDrawRect(xw.draw, &drawcol, borderpx + cx * win.cw, borderpx + cy * win.ch, cursorthickness, win.ch); break; } } else { XftDrawRect(xw.draw, &drawcol, borderpx + cx * win.cw, borderpx + cy * win.ch, win.cw - 1, 1); XftDrawRect(xw.draw, &drawcol, borderpx + cx * win.cw, borderpx + cy * win.ch, 1, win.ch - 1); XftDrawRect(xw.draw, &drawcol, borderpx + (cx + 1) * win.cw - 1, borderpx + cy * win.ch, 1, win.ch - 1); XftDrawRect(xw.draw, &drawcol, borderpx + cx * win.cw, borderpx + (cy + 1) * win.ch - 1, win.cw, 1); } } void xsetenv(void) { char buf[sizeof(long) * 8 + 1]; snprintf(buf, sizeof(buf), "%lu", xw.win); setenv("WINDOWID", buf, 1); } void xsettitle(char *p) { XTextProperty prop; DEFAULT(p, opt_title); Xutf8TextListToTextProperty(xw.dpy, &p, 1, XUTF8StringStyle, &prop); XSetWMName(xw.dpy, xw.win, &prop); XSetTextProperty(xw.dpy, xw.win, &prop, xw.netwmname); XFree(prop.value); } int xstartdraw(void) { return IS_SET(MODE_VISIBLE); } void xdrawline(Line line, int x1, int y1, int x2) { int i, x, ox, numspecs; Glyph base, new; XftGlyphFontSpec *specs = xw.specbuf; numspecs = xmakeglyphfontspecs(specs, &line[x1], x2 - x1, x1, y1); i = ox = 0; for (x = x1; x < x2 && i < numspecs; x++) { new = line[x]; if (new.mode == ATTR_WDUMMY) continue; if (selected(x, y1)) new.mode ^= ATTR_REVERSE; if (i > 0 && ATTRCMP(base, new)) { xdrawglyphfontspecs(specs, base, i, ox, y1); specs += i; numspecs -= i; i = 0; } if (i == 0) { ox = x; base = new; } i++; } if (i > 0) xdrawglyphfontspecs(specs, base, i, ox, y1); } void xfinishdraw(void) { XCopyArea(xw.dpy, xw.buf, xw.win, dc.gc, 0, 0, win.w, win.h, 0, 0); XSetForeground(xw.dpy, dc.gc, dc.col[IS_SET(MODE_REVERSE)? defaultfg : defaultbg].pixel); } void xximspot(int x, int y) { if (xw.ime.xic == NULL) return; xw.ime.spot.x = borderpx + x * win.cw; xw.ime.spot.y = borderpx + (y + 1) * win.ch; XSetICValues(xw.ime.xic, XNPreeditAttributes, xw.ime.spotlist, NULL); } void expose(XEvent *ev) { redraw(); } void visibility(XEvent *ev) { XVisibilityEvent *e = &ev->xvisibility; MODBIT(win.mode, e->state != VisibilityFullyObscured, MODE_VISIBLE); } void unmap(XEvent *ev) { win.mode &= ~MODE_VISIBLE; } void xsetpointermotion(int set) { if (!set && !xw.pointerisvisible) return; MODBIT(xw.attrs.event_mask, set, PointerMotionMask); XChangeWindowAttributes(xw.dpy, xw.win, CWEventMask, &xw.attrs); } void xsetmode(int set, unsigned int flags) { int mode = win.mode; MODBIT(win.mode, set, flags); if ((win.mode & MODE_REVERSE) != (mode & MODE_REVERSE)) redraw(); } int xsetcursor(int cursor) { DEFAULT(cursor, 1); if (!BETWEEN(cursor, 0, 6)) return 1; win.cursor = cursor; return 0; } void xseturgency(int add) { XWMHints *h = XGetWMHints(xw.dpy, xw.win); MODBIT(h->flags, add, XUrgencyHint); XSetWMHints(xw.dpy, xw.win, h); XFree(h); } void xbell(void) { if (!(IS_SET(MODE_FOCUSED))) xseturgency(1); if (bellvolume) XkbBell(xw.dpy, xw.win, bellvolume, (Atom)NULL); } void focus(XEvent *ev) { XFocusChangeEvent *e = &ev->xfocus; if (e->mode == NotifyGrab) return; if (ev->type == FocusIn) { if (xw.ime.xic) XSetICFocus(xw.ime.xic); win.mode |= MODE_FOCUSED; xseturgency(0); if (IS_SET(MODE_FOCUS)) ttywrite("\033[I", 3, 0); if (!focused) { focused = true; xloadalpha(); redraw(); } } else { if (xw.ime.xic) XUnsetICFocus(xw.ime.xic); win.mode &= ~MODE_FOCUSED; if (IS_SET(MODE_FOCUS)) ttywrite("\033[O", 3, 0); if (focused) { focused = false; xloadalpha(); redraw(); } } } int match(uint mask, uint state) { return mask == XK_ANY_MOD || mask == (state & ~ignoremod); } char* kmap(KeySym k, uint state) { Key *kp; int i; /* Check for mapped keys out of X11 function keys. */ for (i = 0; i < LEN(mappedkeys); i++) { if (mappedkeys[i] == k) break; } if (i == LEN(mappedkeys)) { if ((k & 0xFFFF) < 0xFD00) return NULL; } for (kp = key; kp < key + LEN(key); kp++) { if (kp->k != k) continue; if (!match(kp->mask, state)) continue; if (IS_SET(MODE_APPKEYPAD) ? kp->appkey < 0 : kp->appkey > 0) continue; if (IS_SET(MODE_NUMLOCK) && kp->appkey == 2) continue; if (IS_SET(MODE_APPCURSOR) ? kp->appcursor < 0 : kp->appcursor > 0) continue; return kp->s; } return NULL; } void kpress(XEvent *ev) { XKeyEvent *e = &ev->xkey; KeySym ksym; char buf[64], *customkey; int len; Rune c; Status status; Shortcut *bp; if (xw.pointerisvisible) { XDefineCursor(xw.dpy, xw.win, xw.bpointer); xsetpointermotion(1); xw.pointerisvisible = 0; } if (IS_SET(MODE_KBDLOCK)) return; if (xw.ime.xic) len = XmbLookupString(xw.ime.xic, e, buf, sizeof buf, &ksym, &status); if ( IS_SET(MODE_KBDSELECT) ) { if ( match(XK_NO_MOD, e->state) || (XK_Shift_L | XK_Shift_R) & e->state ) win.mode ^= trt_kbdselect(ksym, buf, len); return; } else len = XLookupString(e, buf, sizeof buf, &ksym, NULL); /* 1. shortcuts */ for (bp = shortcuts; bp < shortcuts + LEN(shortcuts); bp++) { if (ksym == bp->keysym && match(bp->mod, e->state)) { bp->func(&(bp->arg)); return; } } /* 2. custom keys from config.h */ if ((customkey = kmap(ksym, e->state))) { ttywrite(customkey, strlen(customkey), 1); return; } /* 3. composed string from input method */ if (len == 0) return; if (len == 1 && e->state & Mod1Mask) { if (IS_SET(MODE_8BIT)) { if (*buf < 0177) { c = *buf | 0x80; len = utf8encode(c, buf); } } else { buf[1] = buf[0]; buf[0] = '\033'; len = 2; } } ttywrite(buf, len, 1); } void cmessage(XEvent *e) { /* * See xembed specs * http://standards.freedesktop.org/xembed-spec/xembed-spec-latest.html */ if (e->xclient.message_type == xw.xembed && e->xclient.format == 32) { if (e->xclient.data.l[1] == XEMBED_FOCUS_IN) { win.mode |= MODE_FOCUSED; xseturgency(0); } else if (e->xclient.data.l[1] == XEMBED_FOCUS_OUT) { win.mode &= ~MODE_FOCUSED; } } else if (e->xclient.data.l[0] == xw.wmdeletewin) { ttyhangup(); exit(0); } } void resize(XEvent *e) { if (e->xconfigure.width == win.w && e->xconfigure.height == win.h) return; cresize(e->xconfigure.width, e->xconfigure.height); } void run(void) { XEvent ev; int w = win.w, h = win.h; fd_set rfd; int xfd = XConnectionNumber(xw.dpy), xev, blinkset = 0, dodraw = 0; int ttyfd; struct timespec drawtimeout, *tv = NULL, now, last, lastblink; long deltatime; /* Waiting for window mapping */ do { XNextEvent(xw.dpy, &ev); /* * This XFilterEvent call is required because of XOpenIM. It * does filter out the key event and some client message for * the input method too. */ if (XFilterEvent(&ev, None)) continue; if (ev.type == ConfigureNotify) { w = ev.xconfigure.width; h = ev.xconfigure.height; } } while (ev.type != MapNotify); ttyfd = ttynew(opt_line, shell, opt_io, opt_cmd); cresize(w, h); clock_gettime(CLOCK_MONOTONIC, &last); lastblink = last; for (xev = actionfps;;) { FD_ZERO(&rfd); FD_SET(ttyfd, &rfd); FD_SET(xfd, &rfd); if (pselect(MAX(xfd, ttyfd)+1, &rfd, NULL, NULL, tv, NULL) < 0) { if (errno == EINTR) continue; die("select failed: %s\n", strerror(errno)); } if (FD_ISSET(ttyfd, &rfd)) { ttyread(); if (blinktimeout) { blinkset = tattrset(ATTR_BLINK); if (!blinkset) MODBIT(win.mode, 0, MODE_BLINK); } } if (FD_ISSET(xfd, &rfd)) xev = actionfps; clock_gettime(CLOCK_MONOTONIC, &now); drawtimeout.tv_sec = 0; drawtimeout.tv_nsec = (1000 * 1E6)/ xfps; tv = &drawtimeout; dodraw = 0; if (blinktimeout && TIMEDIFF(now, lastblink) > blinktimeout) { tsetdirtattr(ATTR_BLINK); win.mode ^= MODE_BLINK; lastblink = now; dodraw = 1; } deltatime = TIMEDIFF(now, last); if (deltatime > 1000 / (xev ? xfps : actionfps)) { dodraw = 1; last = now; } if (dodraw) { while (XPending(xw.dpy)) { XNextEvent(xw.dpy, &ev); if (XFilterEvent(&ev, None)) continue; if (handler[ev.type]) (handler[ev.type])(&ev); } draw(); XFlush(xw.dpy); if (xev && !FD_ISSET(xfd, &rfd)) xev--; if (!FD_ISSET(ttyfd, &rfd) && !FD_ISSET(xfd, &rfd)) { if (blinkset) { if (TIMEDIFF(now, lastblink) \ > blinktimeout) { drawtimeout.tv_nsec = 1000; } else { drawtimeout.tv_nsec = (1E6 * \ (blinktimeout - \ TIMEDIFF(now, lastblink))); } drawtimeout.tv_sec = \ drawtimeout.tv_nsec / 1E9; drawtimeout.tv_nsec %= (long)1E9; } else { tv = NULL; } } } } } void usage(void) { die("usage: %s [-aiv] [-c class] [-f font] [-g geometry]" " [-n name] [-o file]\n" " [-T title] [-t title] [-w windowid]" " [[-e] command [args ...]]\n" " %s [-aiv] [-c class] [-f font] [-g geometry]" " [-n name] [-o file]\n" " [-T title] [-t title] [-w windowid] -l line" " [stty_args ...]\n", argv0, argv0); } void toggle_winmode(int flag) { win.mode ^= flag; } void keyboard_select(const Arg *dummy) { win.mode ^= trt_kbdselect(-1, NULL, 0); } int main(int argc, char *argv[]) { xw.l = xw.t = 0; xw.isfixed = False; win.cursor = cursorshape; ARGBEGIN { case 'a': allowaltscreen = 0; break; case 'A': opt_alpha = EARGF(usage()); break; case 'c': opt_class = EARGF(usage()); break; case 'e': if (argc > 0) --argc, ++argv; goto run; case 'f': opt_font = EARGF(usage()); break; case 'g': xw.gm = XParseGeometry(EARGF(usage()), &xw.l, &xw.t, &cols, &rows); break; case 'i': xw.isfixed = 1; break; case 'o': opt_io = EARGF(usage()); break; case 'l': opt_line = EARGF(usage()); break; case 'n': opt_name = EARGF(usage()); break; case 't': case 'T': opt_title = EARGF(usage()); break; case 'w': opt_embed = EARGF(usage()); break; case 'v': die("%s " VERSION "\n", argv0); break; default: usage(); } ARGEND; run: if (argc > 0) /* eat all remaining arguments */ opt_cmd = argv; if (!opt_title) opt_title = (opt_line || !opt_cmd) ? "st" : opt_cmd[0]; setlocale(LC_CTYPE, ""); XSetLocaleModifiers(""); cols = MAX(cols, 1); rows = MAX(rows, 1); tnew(cols, rows); xinit(cols, rows); xsetenv(); selinit(); run(); return 0; }
224523.c
// SoftEther VPN Source Code - Developer Edition Master Branch // Cedar Communication Module // // SoftEther VPN Server, Client and Bridge are free software under GPLv2. // // Copyright (c) Daiyuu Nobori. // Copyright (c) SoftEther VPN Project, University of Tsukuba, Japan. // Copyright (c) SoftEther Corporation. // // All Rights Reserved. // // http://www.softether.org/ // // Author: Daiyuu Nobori, Ph.D. // Comments: Tetsuo Sugiyama, Ph.D. // // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // version 2 as published by the Free Software Foundation. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License version 2 // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. // IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY // CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, // TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE // SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // // THE LICENSE AGREEMENT IS ATTACHED ON THE SOURCE-CODE PACKAGE // AS "LICENSE.TXT" FILE. READ THE TEXT FILE IN ADVANCE TO USE THE SOFTWARE. // // // THIS SOFTWARE IS DEVELOPED IN JAPAN, AND DISTRIBUTED FROM JAPAN, // UNDER JAPANESE LAWS. YOU MUST AGREE IN ADVANCE TO USE, COPY, MODIFY, // MERGE, PUBLISH, DISTRIBUTE, SUBLICENSE, AND/OR SELL COPIES OF THIS // SOFTWARE, THAT ANY JURIDICAL DISPUTES WHICH ARE CONCERNED TO THIS // SOFTWARE OR ITS CONTENTS, AGAINST US (SOFTETHER PROJECT, SOFTETHER // CORPORATION, DAIYUU NOBORI OR OTHER SUPPLIERS), OR ANY JURIDICAL // DISPUTES AGAINST US WHICH ARE CAUSED BY ANY KIND OF USING, COPYING, // MODIFYING, MERGING, PUBLISHING, DISTRIBUTING, SUBLICENSING, AND/OR // SELLING COPIES OF THIS SOFTWARE SHALL BE REGARDED AS BE CONSTRUED AND // CONTROLLED BY JAPANESE LAWS, AND YOU MUST FURTHER CONSENT TO // EXCLUSIVE JURISDICTION AND VENUE IN THE COURTS SITTING IN TOKYO, // JAPAN. YOU MUST WAIVE ALL DEFENSES OF LACK OF PERSONAL JURISDICTION // AND FORUM NON CONVENIENS. PROCESS MAY BE SERVED ON EITHER PARTY IN // THE MANNER AUTHORIZED BY APPLICABLE LAW OR COURT RULE. // // USE ONLY IN JAPAN. DO NOT USE THIS SOFTWARE IN ANOTHER COUNTRY UNLESS // YOU HAVE A CONFIRMATION THAT THIS SOFTWARE DOES NOT VIOLATE ANY // CRIMINAL LAWS OR CIVIL RIGHTS IN THAT PARTICULAR COUNTRY. USING THIS // SOFTWARE IN OTHER COUNTRIES IS COMPLETELY AT YOUR OWN RISK. THE // SOFTETHER VPN PROJECT HAS DEVELOPED AND DISTRIBUTED THIS SOFTWARE TO // COMPLY ONLY WITH THE JAPANESE LAWS AND EXISTING CIVIL RIGHTS INCLUDING // PATENTS WHICH ARE SUBJECTS APPLY IN JAPAN. OTHER COUNTRIES' LAWS OR // CIVIL RIGHTS ARE NONE OF OUR CONCERNS NOR RESPONSIBILITIES. WE HAVE // NEVER INVESTIGATED ANY CRIMINAL REGULATIONS, CIVIL LAWS OR // INTELLECTUAL PROPERTY RIGHTS INCLUDING PATENTS IN ANY OF OTHER 200+ // COUNTRIES AND TERRITORIES. BY NATURE, THERE ARE 200+ REGIONS IN THE // WORLD, WITH DIFFERENT LAWS. IT IS IMPOSSIBLE TO VERIFY EVERY // COUNTRIES' LAWS, REGULATIONS AND CIVIL RIGHTS TO MAKE THE SOFTWARE // COMPLY WITH ALL COUNTRIES' LAWS BY THE PROJECT. EVEN IF YOU WILL BE // SUED BY A PRIVATE ENTITY OR BE DAMAGED BY A PUBLIC SERVANT IN YOUR // COUNTRY, THE DEVELOPERS OF THIS SOFTWARE WILL NEVER BE LIABLE TO // RECOVER OR COMPENSATE SUCH DAMAGES, CRIMINAL OR CIVIL // RESPONSIBILITIES. NOTE THAT THIS LINE IS NOT LICENSE RESTRICTION BUT // JUST A STATEMENT FOR WARNING AND DISCLAIMER. // // // SOURCE CODE CONTRIBUTION // ------------------------ // // Your contribution to SoftEther VPN Project is much appreciated. // Please send patches to us through GitHub. // Read the SoftEther VPN Patch Acceptance Policy in advance: // http://www.softether.org/5-download/src/9.patch // // // DEAR SECURITY EXPERTS // --------------------- // // If you find a bug or a security vulnerability please kindly inform us // about the problem immediately so that we can fix the security problem // to protect a lot of users around the world as soon as possible. // // Our e-mail address for security reports is: // softether-vpn-security [at] softether.org // // Please note that the above e-mail address is not a technical support // inquiry address. If you need technical assistance, please visit // http://www.softether.org/ and ask your question on the users forum. // // Thank you for your cooperation. // // // NO MEMORY OR RESOURCE LEAKS // --------------------------- // // The memory-leaks and resource-leaks verification under the stress // test has been passed before release this source code. // Interop_OpenVPN.c // OpenVPN protocol stack #include "CedarPch.h" static bool g_no_openvpn_tcp = false; static bool g_no_openvpn_udp = false; // Ping signature of the OpenVPN protocol static UCHAR ping_signature[] = { 0x2a, 0x18, 0x7b, 0xf3, 0x64, 0x1e, 0xb4, 0xcb, 0x07, 0xed, 0x2d, 0x0a, 0x98, 0x1f, 0xc7, 0x48 }; // Set the OpenVPN over TCP disabling flag void OvsSetNoOpenVpnTcp(bool b) { g_no_openvpn_tcp = b; } // Get the OpenVPN over TCP disabling flag bool OvsGetNoOpenVpnTcp() { return g_no_openvpn_tcp; } // Set the OpenVPN over UDP disabling flag void OvsSetNoOpenVpnUdp(bool b) { g_no_openvpn_udp = b; } // Get the OpenVPN over UDP disabling flag bool OvsGetNoOpenVpnUdp() { return g_no_openvpn_udp; } // Write the OpenVPN log void OvsLog(OPENVPN_SERVER *s, OPENVPN_SESSION *se, OPENVPN_CHANNEL *c, char *name, ...) { wchar_t prefix[MAX_SIZE * 2]; wchar_t buf2[MAX_SIZE * 2]; va_list args; // Validate arguments if (s == NULL) { return; } if (se == NULL) { UniStrCpy(prefix, sizeof(prefix), _UU("LO_PREFIX_RAW")); } else { if (c == NULL) { UniFormat(prefix, sizeof(prefix), _UU("LO_PREFIX_SESSION"), se->Id, &se->ClientIp, se->ClientPort, &se->ServerIp, se->ServerPort); } else { UniFormat(prefix, sizeof(prefix), _UU("LO_PREFIX_CHANNEL"), se->Id, &se->ClientIp, se->ClientPort, &se->ServerIp, se->ServerPort, c->KeyId); } } va_start(args, name); UniFormatArgs(buf2, sizeof(buf2), _UU(name), args); va_end(args); UniStrCat(prefix, sizeof(prefix), buf2); WriteServerLog(s->Cedar, prefix); } // Process the received packet void OvsProceccRecvPacket(OPENVPN_SERVER *s, UDPPACKET *p, UINT protocol) { OPENVPN_SESSION *se; OPENVPN_PACKET *recv_packet; // Validate arguments if (s == NULL || p == NULL) { return; } // Search for the session se = OvsFindOrCreateSession(s, &p->DstIP, p->DestPort, &p->SrcIP, p->SrcPort, protocol); if (se == NULL) { return; } // Parse the packet recv_packet = OvsParsePacket(p->Data, p->Size); if (recv_packet != NULL) { OPENVPN_CHANNEL *c = NULL; if (recv_packet->OpCode != OPENVPN_P_DATA_V1 && recv_packet->MySessionId != 0) { Debug("RECV PACKET: %u %I64u\n", recv_packet->KeyId, recv_packet->MySessionId); } if (recv_packet->OpCode != OPENVPN_P_DATA_V1) { Debug(" PKT %u %u\n", recv_packet->OpCode, recv_packet->KeyId); } if (recv_packet->OpCode != OPENVPN_P_DATA_V1) { // Control packet if (recv_packet->OpCode == OPENVPN_P_CONTROL_HARD_RESET_CLIENT_V2 || recv_packet->OpCode == OPENVPN_P_CONTROL_SOFT_RESET_V1) { // Connection request packet if (se->Channels[recv_packet->KeyId] != NULL) { // Release when there is a channel data already OvsFreeChannel(se->Channels[recv_packet->KeyId]); se->Channels[recv_packet->KeyId] = NULL; } // Create a new channel c = OvsNewChannel(se, recv_packet->KeyId); if (se->ClientSessionId == 0) { se->ClientSessionId = recv_packet->MySessionId; } se->Channels[recv_packet->KeyId] = c; Debug("OpenVPN New Channel :%u\n", recv_packet->KeyId); OvsLog(s, se, c, "LO_NEW_CHANNEL"); } /* else if (recv_packet->OpCode == OPENVPN_P_CONTROL_SOFT_RESET_V1) { // Response to soft reset request packet OPENVPN_PACKET *p; p = OvsNewControlPacket(OPENVPN_P_CONTROL_SOFT_RESET_V1, recv_packet->KeyId, se->ServerSessionId, 0, NULL, 0, 0, 0, NULL); OvsSendPacketNow(s, se, p); OvsFreePacket(p); }*/ else { // Packet other than the connection request if (se->Channels[recv_packet->KeyId] != NULL) { c = se->Channels[recv_packet->KeyId]; } } if (c != NULL) { // Delete the send packet list by looking the packet ID in the ACK list of arrived packet OvsDeleteFromSendingControlPacketList(c, recv_packet->NumAck, recv_packet->AckPacketId); if (recv_packet->OpCode != OPENVPN_P_ACK_V1) { // Add the Packet ID of arrived packet to the list InsertIntDistinct(c->AckReplyList, recv_packet->PacketId); Debug("Recv Packet ID (c=%u): %u\n", c->KeyId, recv_packet->PacketId); if ((recv_packet->PacketId > c->MaxRecvPacketId) || (recv_packet->OpCode == OPENVPN_P_CONTROL_HARD_RESET_CLIENT_V2) || (recv_packet->OpCode == OPENVPN_P_CONTROL_SOFT_RESET_V1)) { c->MaxRecvPacketId = recv_packet->PacketId; // Process the received control packet OvsProcessRecvControlPacket(s, se, c, recv_packet); } } } } else { // Data packet if (se->Channels[recv_packet->KeyId] != NULL) { OPENVPN_CHANNEL *c = se->Channels[recv_packet->KeyId]; if (c->Status == OPENVPN_CHANNEL_STATUS_ESTABLISHED) { UCHAR *data; UINT size; data = recv_packet->Data; size = recv_packet->DataSize; if (size >= (c->MdRecv->Size + c->CipherDecrypt->IvSize + sizeof(UINT))) { UCHAR *hmac; UCHAR *iv; UCHAR hmac_test[128]; // HMAC hmac = data; data += c->MdRecv->Size; size -= c->MdRecv->Size; // Confirmation of HMAC MdProcess(c->MdRecv, hmac_test, data, size); if (Cmp(hmac_test, hmac, c->MdRecv->Size) == 0) { // Update of last communication time se->LastCommTick = s->Now; // IV iv = data; data += c->CipherDecrypt->IvSize; size -= c->CipherDecrypt->IvSize; // Payload if (size >= 1 && (c->CipherDecrypt->BlockSize == 0 || (size % c->CipherDecrypt->BlockSize) == 0)) { UINT data_packet_id; // Decryption size = CipherProcess(c->CipherDecrypt, iv, s->TmpBuf, data, size); data = s->TmpBuf; if (size >= sizeof(UINT)) { data_packet_id = READ_UINT(data); data += sizeof(UINT); size -= sizeof(UINT); if (size >= sizeof(ping_signature) && Cmp(data, ping_signature, sizeof(ping_signature)) == 0) { // Ignore since a ping packet has been received DoNothing(); } else { // Receive a packet!! if (se->Ipc != NULL) { switch (se->Mode) { case OPENVPN_MODE_L2: // Send an Ethernet packet to a session IPCSendL2(se->Ipc, data, size); break; case OPENVPN_MODE_L3: // Send an IPv4 packet to a session IPCSendIPv4(se->Ipc, data, size); break; } } } } } } else { // Debug("HMAC Failed (c=%u)\n", c->KeyId); } } } } } OvsFreePacket(recv_packet); } } // Remove a packet which the opponent has received from the transmission list void OvsDeleteFromSendingControlPacketList(OPENVPN_CHANNEL *c, UINT num_acks, UINT *acks) { LIST *o; UINT i; // Validate arguments if (c == NULL || num_acks == 0) { return; } o = NewListFast(NULL); for (i = 0;i < num_acks;i++) { UINT ack = acks[i]; UINT j; for (j = 0;j < LIST_NUM(c->SendControlPacketList);j++) { OPENVPN_CONTROL_PACKET *p = LIST_DATA(c->SendControlPacketList, j); if (p->PacketId == ack) { AddDistinct(o, p); } } } for (i = 0;i < LIST_NUM(o);i++) { OPENVPN_CONTROL_PACKET *p = LIST_DATA(o, i); Delete(c->SendControlPacketList, p); OvsFreeControlPacket(p); } ReleaseList(o); } // Process the received control packet void OvsProcessRecvControlPacket(OPENVPN_SERVER *s, OPENVPN_SESSION *se, OPENVPN_CHANNEL *c, OPENVPN_PACKET *p) { FIFO *recv_fifo = NULL; FIFO *send_fifo = NULL; // Validate arguments if (s == NULL || se == NULL || c == NULL || p == NULL) { return; } if (p->OpCode == OPENVPN_P_CONTROL_V1) { Debug("SSL (c=%u): %u\n", c->KeyId, p->DataSize); if (c->SslPipe == NULL) { // Create an SSL pipe Lock(s->Cedar->lock); { c->SslPipe = NewSslPipe(true, s->Cedar->ServerX, s->Cedar->ServerK, s->Dh); } Unlock(s->Cedar->lock); Debug("SSL Pipe Created (c=%u).\n", c->KeyId); } if (c->SslPipe->IsDisconnected == false) { // Pour the physically received data into SSL pipe if (FifoSize(c->SslPipe->RawIn->SendFifo) < OPENVPN_MAX_SSL_RECV_BUF_SIZE) { Debug("SSL_Write: %u\n", p->DataSize); WriteFifo(c->SslPipe->RawIn->SendFifo, p->Data, p->DataSize); } SyncSslPipe(c->SslPipe); } } if (c->SslPipe != NULL && c->SslPipe->IsDisconnected == false) { recv_fifo = c->SslPipe->SslInOut->RecvFifo; send_fifo = c->SslPipe->SslInOut->SendFifo; } Debug("SIZE: recv_fifo = %u, send_fifo = %u\n", FifoSize(recv_fifo), FifoSize(send_fifo)); switch (c->Status) { case OPENVPN_CHANNEL_STATUS_INIT: switch (p->OpCode) { case OPENVPN_P_CONTROL_SOFT_RESET_V1: // Key update (soft reset) if (se->Established) { if (c->IsInitiatorServer == false) { OvsSendControlPacket(c, OPENVPN_P_CONTROL_SOFT_RESET_V1, NULL, 0); } c->Status = OPENVPN_CHANNEL_STATUS_TLS_WAIT_CLIENT_KEY; c->IsRekeyChannel = true; } break; case OPENVPN_P_CONTROL_HARD_RESET_CLIENT_V2: // New connection (hard reset) OvsSendControlPacket(c, OPENVPN_P_CONTROL_HARD_RESET_SERVER_V2, NULL, 0); c->Status = OPENVPN_CHANNEL_STATUS_TLS_WAIT_CLIENT_KEY; break; } break; case OPENVPN_CHANNEL_STATUS_TLS_WAIT_CLIENT_KEY: if (FifoSize(recv_fifo) >= 1) { OPENVPN_KEY_METHOD_2 data; UCHAR *ptr = FifoPtr(recv_fifo); // Parse OPENVPN_KEY_METHOD_2 UINT read_size = OvsParseKeyMethod2(&data, ptr, FifoSize(recv_fifo), true); if (read_size != 0) { BUF *b; // Success in parsing key information ReadFifo(recv_fifo, NULL, read_size); // Set session parameters OvsSetupSessionParameters(s, se, c, &data); // Build OPENVPN_KEY_METHOD_2 to respond b = OvsBuildKeyMethod2(&c->ServerKey); // Transmission of the response data if (b != NULL) { WriteFifo(send_fifo, b->Buf, b->Size); FreeBuf(b); } // State transition c->Status = OPENVPN_CHANNEL_STATUS_TLS_WAIT_CLIENT_PUSH_REQUEST; if (c->IsRekeyChannel) { c->Status = OPENVPN_CHANNEL_STATUS_ESTABLISHED; c->EstablishedTick = s->Now; Debug("OpenVPN Channel %u Established (re-key).\n", c->KeyId); OvsLog(s, se, c, "LO_CHANNEL_ESTABLISHED_NEWKEY"); } } } break; case OPENVPN_CHANNEL_STATUS_TLS_WAIT_CLIENT_PUSH_REQUEST: if (FifoSize(recv_fifo) >= 1) { char tmp[MAX_SIZE]; UINT read_size = OvsPeekStringFromFifo(recv_fifo, tmp, sizeof(tmp)); if (read_size >= 1) { Debug("Client->Server (c=%u): %s\n", c->KeyId, tmp); ReadFifo(recv_fifo, NULL, read_size); if (StartWith(tmp, "PUSH_REQUEST")) { // Since connection requested, start VPN connection // When the IPC VPN connection has not been started yet, start it OvsBeginIPCAsyncConnectionIfEmpty(s, se, c); // State transition c->Status = OPENVPN_CHANNEL_STATUS_TLS_VPN_CONNECTING; } } } break; case OPENVPN_CHANNEL_STATUS_TLS_VPN_CONNECTING: case OPENVPN_CHANNEL_STATUS_ESTABLISHED: if (FifoSize(recv_fifo) >= 1) { char tmp[MAX_SIZE]; UINT read_size = OvsPeekStringFromFifo(recv_fifo, tmp, sizeof(tmp)); if (read_size >= 1) { Debug("Client->Server (c=%u): %s\n", c->KeyId, tmp); ReadFifo(recv_fifo, NULL, read_size); if (StartWith(tmp, "PUSH_REQUEST")) { WriteFifo(send_fifo, se->PushReplyStr, StrLen(se->PushReplyStr)); } } } break; } } // Calculate the proper MSS UINT OvsCalcTcpMss(OPENVPN_SERVER *s, OPENVPN_SESSION *se, OPENVPN_CHANNEL *c) { UINT ret = MTU_FOR_PPPOE; // Validate arguments if (s == NULL || se == NULL || c == NULL) { return 0; } if (c->MdSend == NULL || c->CipherEncrypt == NULL) { return 0; } if (se->Protocol == OPENVPN_PROTOCOL_TCP) { // Calculation is not required for TCP mode return 0; } // IPv4 / IPv6 if (IsIP4(&se->ClientIp)) { ret -= 20; } else { ret -= 40; } // UDP ret -= 8; // opcode ret -= 1; // HMAC ret -= c->MdSend->Size; // IV ret -= c->CipherEncrypt->IvSize; // Packet ID ret -= 4; if (c->CipherEncrypt->IsNullCipher == false) { // block ret -= c->CipherEncrypt->BlockSize; } if (se->Mode == OPENVPN_MODE_L2) { // Inner Ethernet Header ret -= 14; } // Inner IPv4 ret -= 20; // Inner TCP ret -= 20; return ret; } // When the IPC VPN connection has not been started yet, start it void OvsBeginIPCAsyncConnectionIfEmpty(OPENVPN_SERVER *s, OPENVPN_SESSION *se, OPENVPN_CHANNEL *c) { // Validate arguments if (s == NULL || se == NULL || c == NULL) { return; } if (IsIPCConnected(se->Ipc) == false) { FreeIPC(se->Ipc); se->Ipc = NULL; } if (se->IpcAsync == NULL) { IPC_PARAM p; ETHERIP_ID id; Zero(&p, sizeof(p)); Zero(&id, sizeof(id)); // Parse the user name PPPParseUsername(s->Cedar, c->ClientKey.Username, &id); // Build IPC connection parameters StrCpy(p.ClientName, sizeof(p.ClientName), OPENVPN_IPC_CLIENT_NAME); StrCpy(p.Postfix, sizeof(p.Postfix), (se->Mode == OPENVPN_MODE_L3 ? OPENVPN_IPC_POSTFIX_L3 : OPENVPN_IPC_POSTFIX_L2)); StrCpy(p.UserName, sizeof(p.UserName), id.UserName); StrCpy(p.HubName, sizeof(p.HubName), id.HubName); StrCpy(p.Password, sizeof(p.Password), c->ClientKey.Password); Copy(&p.ClientIp, &se->ClientIp, sizeof(IP)); p.ClientPort = se->ClientPort; Copy(&p.ServerIp, &se->ServerIp, sizeof(IP)); p.ServerPort = se->ServerPort; if (c->CipherEncrypt->IsNullCipher == false) { StrCpy(p.CryptName, sizeof(p.CryptName), c->CipherEncrypt->Name); } if (se->Mode == OPENVPN_MODE_L3) { // L3 Mode p.IsL3Mode = true; } else { // L2 Mode p.BridgeMode = true; } p.IsOpenVPN = true; // Calculate the MSS p.Mss = OvsCalcTcpMss(s, se, c); Debug("MSS=%u\n", p.Mss); // Start an IPC connection se->IpcAsync = NewIPCAsync(s->Cedar, &p, s->SockEvent); } } // Peek a NULL-terminated string from the FIFO UINT OvsPeekStringFromFifo(FIFO *f, char *str, UINT str_size) { UINT i; bool ok = false; // Validate arguments if (f == NULL || str == NULL || str_size == 0) { return 0; } StrCpy(str, str_size, ""); for (i = 0;i < MIN(str_size, FifoSize(f));i++) { char c = *(((char *)FifoPtr(f)) + i); if (c != 0) { str[i] = c; } else { str[i] = 0; i++; ok = true; break; } } if (ok == false) { return 0; } return i; } // Set session parameters void OvsSetupSessionParameters(OPENVPN_SERVER *s, OPENVPN_SESSION *se, OPENVPN_CHANNEL *c, OPENVPN_KEY_METHOD_2 *data) { LIST *o; BUF *b; char opt_str[MAX_SIZE]; // Validate arguments if (s == NULL || se == NULL || c == NULL || data == NULL) { return; } Copy(&c->ClientKey, data, sizeof(OPENVPN_KEY_METHOD_2)); // Parse the parameter string Debug("Parsing Option Str: %s\n", data->OptionString); OvsLog(s, se, c, "LO_OPTION_STR_RECV", data->OptionString); Zero(opt_str, sizeof(opt_str)); StrCpy(opt_str, sizeof(opt_str), data->OptionString); if (s->Cedar != NULL && (IsEmptyStr(opt_str) || StartWith(opt_str, "V0 UNDEF") || InStr(opt_str, ",") == false)) { StrCpy(opt_str, sizeof(opt_str), s->Cedar->OpenVPNDefaultClientOption); } o = OvsParseOptions(opt_str); if (se->Mode == OPENVPN_MODE_UNKNOWN) { UINT mtu; // Layer if (StrCmpi(IniStrValue(o, "dev-type"), "tun") == 0) { // L3 se->Mode = OPENVPN_MODE_L3; } else { // L2 se->Mode = OPENVPN_MODE_L2; } // Link MTU mtu = IniIntValue(o, "link-mtu"); if (mtu == 0) { mtu = OPENVPN_MTU_LINK; } se->LinkMtu = mtu; // Tun MTU mtu = IniIntValue(o, "tun-mtu"); if (mtu == 0) { mtu = OPENVPN_MTU_TUN; } se->TunMtu = mtu; } // Protocol if (se->Protocol == OPENVPN_PROTOCOL_TCP) { // TCP // UDP if (IsIP6(&se->ClientIp) == false) { StrCpy(c->Proto, sizeof(c->Proto), "TCPv4_SERVER"); } else { StrCpy(c->Proto, sizeof(c->Proto), "TCPv6_SERVER"); } } else { // UDP if (IsIP6(&se->ClientIp) == false) { StrCpy(c->Proto, sizeof(c->Proto), "UDPv4"); } else { StrCpy(c->Proto, sizeof(c->Proto), "UDPv6"); } } // Encryption algorithm c->CipherEncrypt = OvsGetCipher(IniStrValue(o, "cipher")); c->CipherDecrypt = NewCipher(c->CipherEncrypt->Name); // Hash algorithm c->MdSend = OvsGetMd(IniStrValue(o, "auth")); c->MdRecv = NewMd(c->MdSend->Name); // Random number generation Rand(c->ServerKey.Random1, sizeof(c->ServerKey.Random1)); Rand(c->ServerKey.Random2, sizeof(c->ServerKey.Random2)); // Generate the Master Secret b = NewBuf(); WriteBuf(b, OPENVPN_PREMASTER_LABEL, StrLen(OPENVPN_PREMASTER_LABEL)); WriteBuf(b, c->ClientKey.Random1, sizeof(c->ClientKey.Random1)); WriteBuf(b, c->ServerKey.Random1, sizeof(c->ServerKey.Random1)); Enc_tls1_PRF(b->Buf, b->Size, c->ClientKey.PreMasterSecret, sizeof(c->ClientKey.PreMasterSecret), c->MasterSecret, sizeof(c->MasterSecret)); FreeBuf(b); // Generate an Expansion Key b = NewBuf(); WriteBuf(b, OPENVPN_EXPANSION_LABEL, StrLen(OPENVPN_EXPANSION_LABEL)); WriteBuf(b, c->ClientKey.Random2, sizeof(c->ClientKey.Random2)); WriteBuf(b, c->ServerKey.Random2, sizeof(c->ServerKey.Random2)); WriteBufInt64(b, se->ClientSessionId); WriteBufInt64(b, se->ServerSessionId); Enc_tls1_PRF(b->Buf, b->Size, c->MasterSecret, sizeof(c->MasterSecret), c->ExpansionKey, sizeof(c->ExpansionKey)); FreeBuf(b); // Set the key SetCipherKey(c->CipherDecrypt, c->ExpansionKey + 0, false); SetCipherKey(c->CipherEncrypt, c->ExpansionKey + 128, true); SetMdKey(c->MdRecv, c->ExpansionKey + 64, c->MdRecv->Size); SetMdKey(c->MdSend, c->ExpansionKey + 192, c->MdSend->Size); OvsFreeOptions(o); // Generate the response option string Format(c->ServerKey.OptionString, sizeof(c->ServerKey.OptionString), "V4,dev-type %s,link-mtu %u,tun-mtu %u,proto %s," "cipher %s,auth %s,keysize %u,key-method 2,tls-server", (se->Mode == OPENVPN_MODE_L2 ? "tap" : "tun"), se->LinkMtu, se->TunMtu, c->Proto, c->CipherEncrypt->Name, c->MdSend->Name, c->CipherEncrypt->KeySize * 8); Debug("Building OptionStr: %s\n", c->ServerKey.OptionString); OvsLog(s, se, c, "LO_OPTION_STR_SEND", c->ServerKey.OptionString); } // Get the encryption algorithm CIPHER *OvsGetCipher(char *name) { CIPHER *c = NULL; if (IsEmptyStr(name) == false && IsStrInStrTokenList(OPENVPN_CIPHER_LIST, name, NULL, false)) { c = NewCipher(name); } if (c == NULL) { c = NewCipher(OPENVPN_DEFAULT_CIPHER); } return c; } // Get the hash algorithm MD *OvsGetMd(char *name) { MD *m = NULL; if (IsEmptyStr(name) == false && IsStrInStrTokenList(OPENVPN_MD_LIST, name, NULL, false)) { m = NewMd(name); } if (m == NULL) { m = NewMd(OPENVPN_DEFAULT_MD); } return m; } // Parse the option string LIST *OvsParseOptions(char *str) { LIST *o = NewListFast(NULL); TOKEN_LIST *t; t = ParseTokenWithoutNullStr(str, ","); if (t != NULL) { UINT i; for (i = 0;i < t->NumTokens;i++) { char key[MAX_SIZE]; char value[MAX_SIZE]; char *line = t->Token[i]; Trim(line); if (GetKeyAndValue(line, key, sizeof(key), value, sizeof(value), " \t")) { INI_ENTRY *e = ZeroMalloc(sizeof(INI_ENTRY)); e->Key = CopyStr(key); e->Value = CopyStr(value); Add(o, e); } } FreeToken(t); } return o; } // Release the option list void OvsFreeOptions(LIST *o) { // Validate arguments if (o == NULL) { return; } FreeIni(o); } // Create an Option List LIST *OvsNewOptions() { return NewListFast(NULL); } // Add a value to the option list void OvsAddOption(LIST *o, char *key, char *value) { INI_ENTRY *e; // Validate arguments if (o == NULL) { return; } e = GetIniEntry(o, key); if (e != NULL) { // Overwrite existing keys Free(e->Key); e->Key = CopyStr(key); Free(e->Value); e->Value = CopyStr(value); } else { // Create a new key e = ZeroMalloc(sizeof(INI_ENTRY)); e->Key = CopyStr(key); e->Value = CopyStr(value); Add(o, e); } } // Confirm whether there is specified option key string bool OvsHasOption(LIST *o, char *key) { // Validate arguments if (o == NULL || key == NULL) { return false; } if (GetIniEntry(o, key) != NULL) { return true; } return false; } // Build the data from KEY_METHOD2 BUF *OvsBuildKeyMethod2(OPENVPN_KEY_METHOD_2 *d) { BUF *b; UCHAR uc; // Validate arguments if (d == NULL) { return NULL; } b = NewBuf(); // Reserved WriteBufInt(b, 0); // Method uc = 2; WriteBuf(b, &uc, sizeof(UCHAR)); // Random1 WriteBuf(b, d->Random1, sizeof(d->Random1)); // Random2 WriteBuf(b, d->Random2, sizeof(d->Random2)); // Option String OvsWriteStringToBuf(b, d->OptionString, sizeof(d->OptionString)); // Username OvsWriteStringToBuf(b, d->Username, sizeof(d->Username)); // Password OvsWriteStringToBuf(b, d->Password, sizeof(d->Password)); // PeerInfo OvsWriteStringToBuf(b, d->PeerInfo, sizeof(d->PeerInfo)); return b; } // Append a string to buf void OvsWriteStringToBuf(BUF *b, char *str, UINT max_size) { USHORT us; UINT i; char *tmp; // Validate arguments if (b == NULL) { return; } if (str == NULL) { str = ""; } if (StrLen(str) == 0) { us = 0; WriteBuf(b, &us, sizeof(USHORT)); return; } i = StrSize(str); i = MIN(i, max_size); us = Endian16((USHORT)i); WriteBuf(b, &us, sizeof(USHORT)); tmp = Malloc(i); Copy(tmp, str, i); tmp[i - 1] = 0; WriteBuf(b, tmp, i); Free(tmp); } // Parse the KEY_METHOD2 UINT OvsParseKeyMethod2(OPENVPN_KEY_METHOD_2 *ret, UCHAR *data, UINT size, bool client_mode) { BUF *b; UINT read_size = 0; UINT ui; UCHAR uc; // Validate arguments Zero(ret, sizeof(OPENVPN_KEY_METHOD_2)); if (ret == NULL || data == NULL || size == 0) { return 0; } b = NewBuf(); WriteBuf(b, data, size); SeekBuf(b, 0, 0); // Reserved if (ReadBuf(b, &ui, sizeof(UINT)) == sizeof(UINT)) { // Method if (ReadBuf(b, &uc, sizeof(UCHAR)) == sizeof(UCHAR) && uc == 2) { // Pre Master Secret if (client_mode == false || ReadBuf(b, ret->PreMasterSecret, sizeof(ret->PreMasterSecret)) == sizeof(ret->PreMasterSecret)) { // Random1 if (ReadBuf(b, ret->Random1, sizeof(ret->Random1)) == sizeof(ret->Random1)) { // Random2 if (ReadBuf(b, ret->Random2, sizeof(ret->Random2)) == sizeof(ret->Random2)) { // String if (OvsReadStringFromBuf(b, ret->OptionString, sizeof(ret->OptionString)) && OvsReadStringFromBuf(b, ret->Username, sizeof(ret->Username)) && OvsReadStringFromBuf(b, ret->Password, sizeof(ret->Password)) && OvsReadStringFromBuf(b, ret->PeerInfo, sizeof(ret->PeerInfo))) { read_size = b->Current; } } } } } } FreeBuf(b); return read_size; } // Read a string from BUF bool OvsReadStringFromBuf(BUF *b, char *str, UINT str_size) { USHORT us; // Validate arguments if (b == NULL || str == NULL) { return false; } if (ReadBuf(b, &us, sizeof(USHORT)) != sizeof(USHORT)) { return false; } us = Endian16(us); if (us == 0) { StrCpy(str, str_size, ""); return true; } if (us > str_size) { return false; } if (ReadBuf(b, str, us) != us) { return false; } if (str[us - 1] != 0) { return false; } return true; } // Transmission of control packet (Automatic segmentation with the maximum size) void OvsSendControlPacketWithAutoSplit(OPENVPN_CHANNEL *c, UCHAR opcode, UCHAR *data, UINT data_size) { BUF *b; // Validate arguments if (c == NULL || (data_size != 0 && data == NULL)) { return; } b = NewBuf(); WriteBuf(b, data, data_size); SeekBuf(b, 0, 0); while (true) { UCHAR tmp[OPENVPN_CONTROL_PACKET_MAX_DATASIZE]; UINT size = ReadBuf(b, tmp, sizeof(tmp)); if (size == 0) { break; } OvsSendControlPacket(c, opcode, tmp, size); //Debug(" *** CNT SEND %u\n", size); } FreeBuf(b); } // Send the control packet void OvsSendControlPacket(OPENVPN_CHANNEL *c, UCHAR opcode, UCHAR *data, UINT data_size) { OPENVPN_CONTROL_PACKET *p; // Validate arguments if (c == NULL || (data_size != 0 && data == NULL)) { return; } p = ZeroMalloc(sizeof(OPENVPN_CONTROL_PACKET)); p->OpCode = opcode; p->PacketId = c->NextSendPacketId++; if (data != NULL) { p->Data = Clone(data, data_size); p->DataSize = data_size; } p->NextSendTime = 0; Add(c->SendControlPacketList, p); } // Release the control packet being transmitted void OvsFreeControlPacket(OPENVPN_CONTROL_PACKET *p) { // Validate arguments if (p == NULL) { return; } if (p->Data != NULL) { Free(p->Data); } Free(p); } // Get a list of packet ID to be responded UINT OvsGetAckReplyList(OPENVPN_CHANNEL *c, UINT *ret) { UINT i; LIST *o = NULL; UINT num; // Validate arguments if (c == NULL || ret == NULL) { return 0; } num = MIN(LIST_NUM(c->AckReplyList), OPENVPN_MAX_NUMACK); for (i = 0;i < num;i++) { UINT *v = LIST_DATA(c->AckReplyList, i); if (o == NULL) { o = NewListFast(NULL); } Add(o, v); ret[i] = *v; } for (i = 0;i < LIST_NUM(o);i++) { UINT *v = LIST_DATA(o, i); Delete(c->AckReplyList, v); Free(v); } ReleaseList(o); return num; } // Release the channel void OvsFreeChannel(OPENVPN_CHANNEL *c) { UINT i; // Validate arguments if (c == NULL) { return; } if (c->SslPipe != NULL) { FreeSslPipe(c->SslPipe); } ReleaseIntList(c->AckReplyList); for (i = 0;i < LIST_NUM(c->SendControlPacketList);i++) { OPENVPN_CONTROL_PACKET *p = LIST_DATA(c->SendControlPacketList, i); OvsFreeControlPacket(p); } ReleaseList(c->SendControlPacketList); FreeCipher(c->CipherDecrypt); FreeCipher(c->CipherEncrypt); FreeMd(c->MdRecv); FreeMd(c->MdSend); Free(c); } // Create a new channel OPENVPN_CHANNEL *OvsNewChannel(OPENVPN_SESSION *se, UCHAR key_id) { OPENVPN_CHANNEL *c; // Validate arguments if (se == NULL) { return NULL; } c = ZeroMalloc(sizeof(OPENVPN_CHANNEL)); c->Session = se; c->Server = se->Server; c->Status = OPENVPN_CHANNEL_STATUS_INIT; c->AckReplyList = NewIntList(true); c->SendControlPacketList = NewListFast(NULL); c->KeyId = key_id; Rand(c->NextIv, sizeof(c->NextIv)); //c->NextRekey = se->Server->Now + (UINT64)5000; se->LastCreatedChannelIndex = key_id; return c; } // Create a new server-side channel ID UINT64 OvsNewServerSessionId(OPENVPN_SERVER *s) { // Validate arguments if (s == NULL) { return 0; } while (true) { UINT64 id = Rand64(); UINT i; bool exists = false; if (id == 0 || id == (UINT64)(0xFFFFFFFFFFFFFFFFULL)) { continue; } for (i = 0;i < LIST_NUM(s->SessionList);i++) { OPENVPN_SESSION *se = LIST_DATA(s->SessionList, i); if (se->ServerSessionId == id) { exists = true; } } if (exists == false) { return id; } } } // Build and submit the OpenVPN data packet void OvsSendDataPacket(OPENVPN_CHANNEL *c, UCHAR key_id, UINT data_packet_id, void *data, UINT data_size) { UCHAR uc; UCHAR *encrypted_data; UINT encrypted_size; UCHAR *dest_data; UINT dest_size; UINT r; // Validate arguments if (c == NULL || data == NULL || data_size == 0) { return; } uc = ((OPENVPN_P_DATA_V1 << 3) & 0xF8) | (key_id & 0x07); // Generate the data to be encrypted encrypted_size = sizeof(UINT) + data_size; encrypted_data = ZeroMalloc(encrypted_size); WRITE_UINT(encrypted_data, data_packet_id); Copy(encrypted_data + sizeof(UINT), data, data_size); // Prepare a buffer to store the results dest_data = Malloc(sizeof(UCHAR) + c->MdSend->Size + c->CipherEncrypt->IvSize + encrypted_size + 256); // Encrypt r = CipherProcess(c->CipherEncrypt, c->NextIv, dest_data + sizeof(UCHAR) + c->MdSend->Size + c->CipherEncrypt->IvSize, encrypted_data, encrypted_size); dest_size = sizeof(UCHAR) + c->MdSend->Size + c->CipherEncrypt->IvSize + r; // Copy the IV Copy(dest_data + sizeof(UCHAR) + c->MdSend->Size, c->NextIv, c->CipherEncrypt->IvSize); // Calculate the HMAC MdProcess(c->MdSend, dest_data + sizeof(UCHAR), dest_data + sizeof(UCHAR) + c->MdSend->Size, dest_size - sizeof(UCHAR) - c->MdSend->Size); // Update the NextIV Copy(c->NextIv, dest_data + dest_size - c->CipherEncrypt->IvSize, c->CipherEncrypt->IvSize); // Op-code dest_data[0] = uc; OvsSendPacketRawNow(c->Server, c->Session, dest_data, dest_size); Free(encrypted_data); } // Build an OpenVPN control packet BUF *OvsBuildPacket(OPENVPN_PACKET *p) { BUF *b; UCHAR uc; UINT num_ack; // Validate arguments if (p == NULL) { return NULL; } b = NewBuf(); // OpCode + KeyID uc = ((p->OpCode << 3) & 0xF8) | (p->KeyId & 0x07); WriteBufChar(b, uc); if (p->OpCode == OPENVPN_P_DATA_V1) { // Data Packet WriteBuf(b, p->Data, p->DataSize); SeekBuf(b, 0, 0); return b; } // Sender Channel ID WriteBufInt64(b, p->MySessionId); // NumAck num_ack = MIN(p->NumAck, OPENVPN_MAX_NUMACK); WriteBufChar(b, (UCHAR)num_ack); if (p->NumAck >= 1) { UINT i; for (i = 0;i < num_ack;i++) { WriteBufInt(b, (UCHAR)p->AckPacketId[i]); } // Received Channel ID WriteBufInt64(b, p->YourSessionId); } if (p->OpCode != OPENVPN_P_ACK_V1) { // Packet ID WriteBufInt(b, p->PacketId); // Payload if (p->DataSize >= 1 && p->Data != NULL) { WriteBuf(b, p->Data, p->DataSize); } } SeekBuf(b, 0, 0); return b; } // Parse the OpenVPN packet OPENVPN_PACKET *OvsParsePacket(UCHAR *data, UINT size) { UCHAR uc; OPENVPN_PACKET *ret = NULL; // Validate arguments if (data == NULL || size == 0) { return NULL; } ret = ZeroMalloc(sizeof(OPENVPN_PACKET)); // OpCode + KeyID if (size < 1) { goto LABEL_ERROR; } uc = *((UCHAR *)data); data++; size--; ret->OpCode = ((uc & 0xF8) >> 3) & 0x1F; ret->KeyId = uc & 0x07; if (ret->OpCode == OPENVPN_P_DATA_V1) { // Data packet ret->DataSize = size; ret->Data = Clone(data, size); return ret; } // Sender Channel ID if (size < sizeof(UINT64)) { goto LABEL_ERROR; } ret->MySessionId = READ_UINT64(data); data += sizeof(UINT64); size -= sizeof(UINT64); // ACK if (size < 1) { goto LABEL_ERROR; } uc = *((UCHAR *)data); data++; size--; ret->NumAck = uc; if (ret->NumAck > 4) { goto LABEL_ERROR; } if (ret->NumAck >= 1) { UINT i; if (size < (sizeof(UINT) * (UINT)ret->NumAck + sizeof(UINT64))) { goto LABEL_ERROR; } for (i = 0;i < ret->NumAck;i++) { UINT ui; ui = READ_UINT(data); ret->AckPacketId[i] = ui; data += sizeof(UINT); size -= sizeof(UINT); } ret->YourSessionId = READ_UINT64(data); data += sizeof(UINT64); size -= sizeof(UINT64); } if (ret->OpCode != OPENVPN_P_ACK_V1) { // Read the Packet ID Because in the case of other than ACK if (size < sizeof(UINT)) { goto LABEL_ERROR; } ret->PacketId = READ_UINT(data); data += sizeof(UINT); size -= sizeof(UINT); // Payload ret->DataSize = size; if (size >= 1) { ret->Data = Clone(data, size); } } return ret; LABEL_ERROR: Debug("OvsParsePacket Error.\n"); if (ret != NULL) { OvsFreePacket(ret); } return NULL; } // Release the OpenVPN packet void OvsFreePacket(OPENVPN_PACKET *p) { // Validate arguments if (p == NULL) { return; } if (p->Data != NULL) { Free(p->Data); } Free(p); } // If the session does not exist, create a session OPENVPN_SESSION *OvsFindOrCreateSession(OPENVPN_SERVER *s, IP *server_ip, UINT server_port, IP *client_ip, UINT client_port, UINT protocol) { OPENVPN_SESSION *se; // Validate arguments if (s == NULL || server_ip == NULL || server_port == 0 || client_ip == NULL || client_port == 0) { return NULL; } se = OvsSearchSession(s, server_ip, server_port, client_ip, client_port, protocol); if (se == NULL) { se = OvsNewSession(s, server_ip, server_port, client_ip, client_port, protocol); if (se != NULL) { Insert(s->SessionList, se); } } return se; } // Get the number of sessions currently connected from the IP address of the client UINT OvsGetNumSessionByClientIp(OPENVPN_SERVER *s, IP *ip) { UINT i; UINT ret = 0; // Validate arguments if (s == NULL || ip == NULL) { return 0; } for (i = 0;i < LIST_NUM(s->SessionList);i++) { OPENVPN_SESSION *se = LIST_DATA(s->SessionList, i); if (CmpIpAddr(&se->ClientIp, ip) == 0) { ret++; } } return ret; } // Create a new session OPENVPN_SESSION *OvsNewSession(OPENVPN_SERVER *s, IP *server_ip, UINT server_port, IP *client_ip, UINT client_port, UINT protocol) { OPENVPN_SESSION *se; char server_ip_str[MAX_SIZE]; char client_ip_str[MAX_SIZE]; // Validate arguments if (s == NULL || server_ip == NULL || server_port == 0 || client_ip == NULL || client_port == 0) { return NULL; } if (OvsGetNumSessionByClientIp(s, client_ip) > OPENVPN_QUOTA_MAX_NUM_SESSIONS_PER_IP) { // Number of sessions from the same IP address too many return NULL; } if (LIST_NUM(s->SessionList) > OPENVPN_QUOTA_MAX_NUM_SESSIONS) { // Too many OpenVPN sessions return NULL; } se = ZeroMalloc(sizeof(OPENVPN_SESSION)); se->Server = s; Copy(&se->ClientIp, client_ip, sizeof(IP)); se->ClientPort = client_port; Copy(&se->ServerIp, server_ip, sizeof(IP)); se->ServerPort = server_port; se->LastCommTick = s->Now; se->Protocol = protocol; se->ServerSessionId = OvsNewServerSessionId(se->Server); se->CreatedTick = s->Now; se->Id = s->NextSessionId; s->NextSessionId++; IPToStr(server_ip_str, sizeof(server_ip_str), server_ip); IPToStr(client_ip_str, sizeof(client_ip_str), client_ip); Debug("OpenVPN New Session: %s:%u -> %s:%u Proto=%u\n", server_ip_str, server_port, client_ip_str, client_port, protocol); OvsLog(s, se, NULL, "LO_NEW_SESSION", (protocol == OPENVPN_PROTOCOL_UDP ? "UDP" : "TCP")); return se; } // Release the session void OvsFreeSession(OPENVPN_SESSION *se) { UINT i; // Validate arguments if (se == NULL) { return; } // If there is IP addresses which is got from a DHCP server in the session, release it if (se->Ipc != NULL) { if (se->Mode == OPENVPN_MODE_L3) { if (se->IpcAsync != NULL) { IP dhcp_ip; UINTToIP(&dhcp_ip, se->IpcAsync->L3ClientAddressOption.ServerAddress); IPCDhcpFreeIP(se->Ipc, &dhcp_ip); IPCProcessL3Events(se->Ipc); } } } // Release the channel for (i = 0;i < OPENVPN_NUM_CHANNELS;i++) { OPENVPN_CHANNEL *c = se->Channels[i]; if (c != NULL) { OvsFreeChannel(c); } } // Release the IPC if (se->Ipc != NULL) { FreeIPC(se->Ipc); } if (se->IpcAsync != NULL) { FreeIPCAsync(se->IpcAsync); } Free(se); } // Search the session from the endpoint information OPENVPN_SESSION *OvsSearchSession(OPENVPN_SERVER *s, IP *server_ip, UINT server_port, IP *client_ip, UINT client_port, UINT protocol) { OPENVPN_SESSION *se; OPENVPN_SESSION t; // Validate arguments if (s == NULL || server_ip == NULL || server_port == 0 || client_ip == NULL || client_port == 0) { return NULL; } Copy(&t.ClientIp, client_ip, sizeof(IP)); t.ClientPort = client_port; Copy(&t.ServerIp, server_ip, sizeof(IP)); t.ServerPort = server_port; t.Protocol = protocol; se = Search(s->SessionList, &t); return se; } // Receive packets in the OpenVPN server void OvsRecvPacket(OPENVPN_SERVER *s, LIST *recv_packet_list, UINT protocol) { UINT i, j; LIST *delete_session_list = NULL; // Validate arguments if (s == NULL || recv_packet_list == NULL) { return; } s->Now = Tick64(); // Process for all sessions for (i = 0;i < LIST_NUM(s->SessionList);i++) { OPENVPN_SESSION *se = LIST_DATA(s->SessionList, i); if (se->Ipc != NULL) { if (se->Mode == OPENVPN_MODE_L3) { // Flush the ARP table of the IPC IPCFlushArpTableEx(se->Ipc, s->Now); } } } // Process received packets for (i = 0;i < LIST_NUM(recv_packet_list);i++) { UDPPACKET *p = LIST_DATA(recv_packet_list, i); OvsProceccRecvPacket(s, p, protocol); } // Treat for all sessions and all channels for (i = 0;i < LIST_NUM(s->SessionList);i++) { OPENVPN_CHANNEL *latest_channel = NULL; UINT64 max_tick = 0; OPENVPN_SESSION *se = LIST_DATA(s->SessionList, i); bool is_disconnected = false; if (se->Ipc != NULL) { if (se->Mode == OPENVPN_MODE_L3) { IPCProcessL3Events(se->Ipc); } } for (j = 0;j < OPENVPN_NUM_CHANNELS;j++) { OPENVPN_CHANNEL *c = se->Channels[j]; if (c != NULL) { if (c->RekeyInitiated == false && ((c->NextRekey <= s->Now && c->NextRekey != 0) || (c->LastDataPacketId >= OPENVPN_MAX_PACKET_ID_FOR_TRIGGER_REKEY))) { OPENVPN_CHANNEL *c2; // Send a soft reset by creating a new channel UINT next_channel_id = se->LastCreatedChannelIndex + 1; if (next_channel_id >= OPENVPN_NUM_CHANNELS) { next_channel_id = 1; } if (se->Channels[next_channel_id] != NULL) { // Release when there is a channel data already OvsFreeChannel(se->Channels[next_channel_id]); se->Channels[next_channel_id] = NULL; } // Create a new channel c2 = OvsNewChannel(se, (UCHAR)next_channel_id); c2->IsInitiatorServer = true; se->Channels[next_channel_id] = c2; Debug("OpenVPN New Channel for Re-Keying :%u\n", next_channel_id); OvsLog(s, se, c, "LO_INITIATE_REKEY"); // Send a soft reset OvsSendControlPacket(c2, OPENVPN_P_CONTROL_SOFT_RESET_V1, NULL, 0); c->RekeyInitiated = true; } } if (c != NULL) { switch (c->Status) { case OPENVPN_CHANNEL_STATUS_TLS_VPN_CONNECTING: // Check whether the connection process completed if there is a channel running a VPN connection process if (se->IpcAsync != NULL) { if (se->IpcAsync->Done) { if (se->IpcAsync->Ipc != NULL) { char option_str[4096]; char l3_options[MAX_SIZE]; // Successful in VPN connection Debug("OpenVPN Channel %u Established (new key).\n", j); OvsLog(s, se, c, "LO_CHANNEL_ESTABLISHED"); // Return the PUSH_REPLY Format(option_str, sizeof(option_str), "PUSH_REPLY,ping %u,ping-restart %u", (OPENVPN_PING_SEND_INTERVAL / 1000), (OPENVPN_RECV_TIMEOUT / 1000)); if (se->Mode == OPENVPN_MODE_L3) { // Add such as the IP address that was acquired from the DHCP server // if the L3 mode to the option character string DHCP_OPTION_LIST *cao = &se->IpcAsync->L3ClientAddressOption; char ip_client[64]; char ip_tunnel_endpoint[64]; UINT ip_tunnel_endpoint_32; char ip_network[64]; char ip_subnet_mask[64]; char ip_dns1[64]; char ip_dns2[64]; char ip_wins1[64]; char ip_wins2[64]; char ip_defgw[64]; ClearStr(ip_dns1, sizeof(ip_dns1)); ClearStr(ip_dns2, sizeof(ip_dns2)); ClearStr(ip_wins1, sizeof(ip_wins1)); ClearStr(ip_wins2, sizeof(ip_wins2)); ClearStr(ip_defgw, sizeof(ip_defgw)); IPToStr32(ip_client, sizeof(ip_client), cao->ClientAddress); // Generate a virtual gateway address to be passed to the OpenVPN ip_tunnel_endpoint_32 = Endian32(cao->ClientAddress); ip_tunnel_endpoint_32++; ip_tunnel_endpoint_32 = Endian32(ip_tunnel_endpoint_32); IPToStr32(ip_tunnel_endpoint, sizeof(ip_tunnel_endpoint), ip_tunnel_endpoint_32); // Create a subnet information for the LAN IPToStr32(ip_network, sizeof(ip_network), GetNetworkAddress(cao->ClientAddress, cao->SubnetMask)); IPToStr32(ip_subnet_mask, sizeof(ip_subnet_mask), cao->SubnetMask); Format(l3_options, sizeof(l3_options), ",ifconfig %s %s", // ",ifconfig %s %s,route %s %s %s 1", ip_client, ip_tunnel_endpoint, ip_network, ip_subnet_mask, ip_tunnel_endpoint); StrCat(option_str, sizeof(option_str), l3_options); // Domain name if (IsEmptyStr(cao->DomainName) == false) { Format(l3_options, sizeof(l3_options), ",dhcp-option DOMAIN %s", cao->DomainName); StrCat(option_str, sizeof(option_str), l3_options); } // DNS server address 1 if (cao->DnsServer != 0) { char ip_str[64]; IPToStr32(ip_str, sizeof(ip_str), cao->DnsServer); Format(l3_options, sizeof(l3_options), ",dhcp-option DNS %s", ip_str); StrCat(option_str, sizeof(option_str), l3_options); StrCpy(ip_dns1, sizeof(ip_dns1), ip_str); } // DNS server address 2 if (cao->DnsServer2 != 0) { char ip_str[64]; IPToStr32(ip_str, sizeof(ip_str), cao->DnsServer2); Format(l3_options, sizeof(l3_options), ",dhcp-option DNS %s", ip_str); StrCat(option_str, sizeof(option_str), l3_options); StrCpy(ip_dns2, sizeof(ip_dns2), ip_str); } // WINS address 1 if (cao->WinsServer != 0) { char ip_str[64]; IPToStr32(ip_str, sizeof(ip_str), cao->WinsServer); Format(l3_options, sizeof(l3_options), ",dhcp-option WINS %s", ip_str); StrCat(option_str, sizeof(option_str), l3_options); StrCpy(ip_wins1, sizeof(ip_wins1), ip_str); } // WINS address 2 if (cao->WinsServer2 != 0) { char ip_str[64]; IPToStr32(ip_str, sizeof(ip_str), cao->WinsServer2); Format(l3_options, sizeof(l3_options), ",dhcp-option WINS %s", ip_str); StrCat(option_str, sizeof(option_str), l3_options); StrCpy(ip_wins2, sizeof(ip_wins2), ip_str); } // Default gateway if (cao->Gateway != 0) { Format(l3_options, sizeof(l3_options), ",route-gateway %s,redirect-gateway def1", ip_tunnel_endpoint); StrCat(option_str, sizeof(option_str), l3_options); IPToStr32(ip_defgw, sizeof(ip_defgw), cao->Gateway); } else { #if 0 // Currently disabled // If the default gateway is not specified, add the static routing table // entry for the local IP subnet IP local_network; IP client_ip; IP subnet_mask; UINTToIP(&client_ip, cao->ClientAddress); UINTToIP(&subnet_mask, cao->SubnetMask); Zero(&local_network, sizeof(IP)); IPAnd4(&local_network, &client_ip, &subnet_mask); Format(l3_options, sizeof(l3_options), ",route %r %r vpn_gateway", &local_network, &cao->SubnetMask); StrCat(option_str, sizeof(option_str), l3_options); #endif } // Classless routing table if (cao->ClasslessRoute.NumExistingRoutes >= 1) { UINT i; for (i = 0;i < MAX_DHCP_CLASSLESS_ROUTE_ENTRIES;i++) { DHCP_CLASSLESS_ROUTE *r = &cao->ClasslessRoute.Entries[i]; if (r->Exists) { Format(l3_options, sizeof(l3_options), ",route %r %r vpn_gateway", &r->Network, &r->SubnetMask); StrCat(option_str, sizeof(option_str), l3_options); } } } OvsLog(s, se, c, "LP_SET_IPV4_PARAM", ip_client, ip_subnet_mask, ip_defgw, ip_dns1, ip_dns2, ip_wins1, ip_wins2); } WriteFifo(c->SslPipe->SslInOut->SendFifo, option_str, StrSize(option_str)); Debug("Push Str: %s\n", option_str); OvsLog(s, se, c, "LO_PUSH_REPLY", option_str); StrCpy(se->PushReplyStr, sizeof(se->PushReplyStr), option_str); se->Ipc = se->IpcAsync->Ipc; se->IpcAsync->Ipc = NULL; s->SessionEstablishedCount++; // Set a Sock Event of IPC to Sock Event of the UDP Listener IPCSetSockEventWhenRecvL2Packet(se->Ipc, s->SockEvent); // State transition c->Status = OPENVPN_CHANNEL_STATUS_ESTABLISHED; c->EstablishedTick = s->Now; se->Established = true; se->LastCommTick = Tick64(); } else { char *str; if (se->IpcAsync->DhcpAllocFailed) { OvsLog(s, se, c, "LP_DHCP_REQUEST_NG"); } // Failed to connect VPN Debug("OpenVPN Channel %u Failed.\n", j); OvsLog(s, se, c, "LO_CHANNEL_FAILED"); // Return the AUTH_FAILED str = "AUTH_FAILED"; WriteFifo(c->SslPipe->SslInOut->SendFifo, str, StrSize(str)); s->SessionEstablishedCount++; // State transition c->Status = OPENVPN_CHANNEL_STATUS_DISCONNECTED; FreeIPCAsync(se->IpcAsync); se->IpcAsync = NULL; } } } break; case OPENVPN_CHANNEL_STATUS_ESTABLISHED: // Monitor the IPC whether not disconnected when there is a VPN connection completed channel if (IsIPCConnected(se->Ipc) == false) { // Send the RESTART since IPC is disconnected char *str = "RESTART"; Debug("OpenVPN Channel %u Disconnected by HUB.\n", j); OvsLog(s, se, c, "LO_CHANNEL_DISCONNECTED_BY_HUB"); WriteFifo(c->SslPipe->SslInOut->SendFifo, str, StrSize(str)); // State transition c->Status = OPENVPN_CHANNEL_STATUS_DISCONNECTED; // Set the session to disconnected state se->Established = false; se->LastCommTick = s->Now; } break; } } if (c != NULL) { // If there is a packet to be transmitted physically in SSL, send it if (c->SslPipe != NULL && SyncSslPipe(c->SslPipe)) { if (FifoSize(c->SslPipe->RawOut->RecvFifo) >= 1) { Debug("RawOut Fifo Size (c=%u): %u\n", c->KeyId, FifoSize(c->SslPipe->RawOut->RecvFifo)); OvsSendControlPacketWithAutoSplit(c, OPENVPN_P_CONTROL_V1, FifoPtr(c->SslPipe->RawOut->RecvFifo), FifoSize(c->SslPipe->RawOut->RecvFifo)); ReadFifo(c->SslPipe->RawOut->RecvFifo, NULL, FifoSize(c->SslPipe->RawOut->RecvFifo)); } } } if (c != NULL) { UINT num; UINT acks[OPENVPN_MAX_NUMACK]; UINT k; // Packet transmission for (k = 0;k < LIST_NUM(c->SendControlPacketList);k++) { OPENVPN_CONTROL_PACKET *cp = LIST_DATA(c->SendControlPacketList, k); if (cp->NextSendTime <= s->Now) { OPENVPN_PACKET *p; num = OvsGetAckReplyList(c, acks); p = OvsNewControlPacket(cp->OpCode, j, se->ServerSessionId, num, acks, se->ClientSessionId, cp->PacketId, cp->DataSize, cp->Data); OvsSendPacketNow(s, se, p); OvsFreePacket(p); cp->NextSendTime = s->Now + (UINT64)OPENVPN_CONTROL_PACKET_RESEND_INTERVAL; AddInterrupt(s->Interrupt, cp->NextSendTime); } } // If the response with an ACK-only packet is required, respond such that num = OvsGetAckReplyList(c, acks); if (num >= 1) { OPENVPN_PACKET *p = OvsNewControlPacket(OPENVPN_P_ACK_V1, j, se->ServerSessionId, num, acks, se->ClientSessionId, 0, 0, NULL); OvsSendPacketNow(s, se, p); OvsFreePacket(p); } } } if (se->Ipc != NULL) { if (se->Mode == OPENVPN_MODE_L3) { if (se->IpcAsync != NULL) { // Update DHCP address if (se->IpcAsync->L3NextDhcpRenewTick <= s->Now) { IP ip; se->IpcAsync->L3NextDhcpRenewTick = s->Now + se->IpcAsync->L3DhcpRenewInterval; UINTToIP(&ip, se->IpcAsync->L3ClientAddressOption.ServerAddress); IPCDhcpRenewIP(se->Ipc, &ip); } } IPCProcessL3Events(se->Ipc); } IPCProcessInterrupts(se->Ipc); } // Choose the latest channel in all established channels for (j = 0;j < OPENVPN_NUM_CHANNELS;j++) { OPENVPN_CHANNEL *c = se->Channels[j]; if (c != NULL) { if (c->Status == OPENVPN_CHANNEL_STATUS_ESTABLISHED) { if (max_tick <= c->EstablishedTick) { max_tick = c->EstablishedTick; latest_channel = c; } } } } if (se->Established == false) { latest_channel = NULL; } // Send the data using the latest channel (when there is no transmission channel, suck out the queue simply) if (se->Mode == OPENVPN_MODE_L2) { // Get an Ethernet frame from IPC while (true) { BLOCK *b = IPCRecvL2(se->Ipc); if (b == NULL) { break; } if (latest_channel != NULL && s->SupressSendPacket == false) { OvsSendDataPacket(latest_channel, latest_channel->KeyId, ++latest_channel->LastDataPacketId, b->Buf, b->Size); } FreeBlock(b); } } else { // Get an IPv4 packet from IPC while (true) { BLOCK *b = IPCRecvIPv4(se->Ipc); if (b == NULL) { break; } if (latest_channel != NULL && s->SupressSendPacket == false) { OvsSendDataPacket(latest_channel, latest_channel->KeyId, ++latest_channel->LastDataPacketId, b->Buf, b->Size); } FreeBlock(b); } } // Send a Ping if (latest_channel != NULL) { if ((se->NextPingSendTick == 0) || (se->NextPingSendTick <= s->Now)) { se->NextPingSendTick = s->Now + (UINT64)(OPENVPN_PING_SEND_INTERVAL); OvsSendDataPacket(latest_channel, latest_channel->KeyId, ++latest_channel->LastDataPacketId, ping_signature, sizeof(ping_signature)); //Debug("."); AddInterrupt(s->Interrupt, se->NextPingSendTick); } } if ((se->Established == false) && (s->Now >= (se->CreatedTick + (UINT64)OPENVPN_NEW_SESSION_DEADLINE_TIMEOUT))) { is_disconnected = true; } if (se->Established && (s->Now >= (se->LastCommTick + (UINT64)OPENVPN_RECV_TIMEOUT))) { is_disconnected = true; } if (is_disconnected) { if (delete_session_list == NULL) { delete_session_list = NewListFast(NULL); } Add(delete_session_list, se); } } if (delete_session_list != NULL) { UINT i; for (i = 0;i < LIST_NUM(delete_session_list);i++) { OPENVPN_SESSION *se = LIST_DATA(delete_session_list, i); Debug("Deleting Session %p\n", se); OvsLog(s, se, NULL, "LO_DELETE_SESSION"); OvsFreeSession(se); s->DisconnectCount++; Delete(s->SessionList, se); } ReleaseList(delete_session_list); } } // Send the packet now void OvsSendPacketNow(OPENVPN_SERVER *s, OPENVPN_SESSION *se, OPENVPN_PACKET *p) { BUF *b; UINT i; // Validate arguments if (s == NULL || se == NULL || p == NULL) { return; } Debug("Sending Opcode=%u ", p->OpCode); if (p->NumAck >= 1) { Debug("Sending ACK Packet IDs (c=%u): ", p->KeyId); for (i = 0;i < p->NumAck;i++) { Debug("%u ", p->AckPacketId[i]); } } Debug("\n"); b = OvsBuildPacket(p); OvsSendPacketRawNow(s, se, b->Buf, b->Size); Free(b); } void OvsSendPacketRawNow(OPENVPN_SERVER *s, OPENVPN_SESSION *se, void *data, UINT size) { UDPPACKET *u; // Validate arguments if (s == NULL || se == NULL || data == NULL || size == 0) { Free(data); return; } u = NewUdpPacket(&se->ServerIp, se->ServerPort, &se->ClientIp, se->ClientPort, data, size); Add(s->SendPacketList, u); } // Create a new OpenVPN control packet OPENVPN_PACKET *OvsNewControlPacket(UCHAR opcode, UCHAR key_id, UINT64 my_channel_id, UINT num_ack, UINT *ack_packet_ids, UINT64 your_channel_id, UINT packet_id, UINT data_size, UCHAR *data) { OPENVPN_PACKET *p = ZeroMalloc(sizeof(OPENVPN_PACKET)); UINT i; p->OpCode = opcode; p->KeyId = key_id; p->MySessionId = my_channel_id; p->NumAck = num_ack; for (i = 0;i < MIN(num_ack, OPENVPN_MAX_NUMACK);i++) { p->AckPacketId[i] = ack_packet_ids[i]; } p->YourSessionId = your_channel_id; p->PacketId = packet_id; if (data_size != 0 && data != NULL) { p->Data = Clone(data, data_size); p->DataSize = data_size; } return p; } // Comparison function of the entries in the session list int OvsCompareSessionList(void *p1, void *p2) { OPENVPN_SESSION *s1, *s2; int i; // Validate arguments if (p1 == NULL || p2 == NULL) { return 0; } s1 = *(OPENVPN_SESSION **)p1; s2 = *(OPENVPN_SESSION **)p2; if (s1 == NULL || s2 == NULL) { return 0; } i = CmpIpAddr(&s1->Protocol, &s2->Protocol); if (i != 0) { return i; } i = CmpIpAddr(&s1->ClientIp, &s2->ClientIp); if (i != 0) { return i; } i = COMPARE_RET(s1->ClientPort, s2->ClientPort); if (i != 0) { return i; } i = CmpIpAddr(&s1->ServerIp, &s2->ServerIp); if (i != 0) { return i; } i = COMPARE_RET(s1->ServerPort, s2->ServerPort); if (i != 0) { return i; } return 0; } // Identify whether the IP address is compatible to the tun device of OpenVPN bool OvsIsCompatibleL3IP(UINT ip) { IP p; UINTToIP(&p, ip); if ((p.addr[3] % 4) == 1) { return true; } return false; } // Get an IP address that is compatible to tun device of the OpenVPN after the specified IP address UINT OvsGetCompatibleL3IPNext(UINT ip) { ip = Endian32(ip); while (true) { if (OvsIsCompatibleL3IP(Endian32(ip))) { return Endian32(ip); } ip++; } } // Create a new OpenVPN server OPENVPN_SERVER *NewOpenVpnServer(CEDAR *cedar, INTERRUPT_MANAGER *interrupt, SOCK_EVENT *sock_event) { OPENVPN_SERVER *s; // Validate arguments if (cedar == NULL) { return NULL; } s = ZeroMalloc(sizeof(OPENVPN_SERVER)); s->Cedar = cedar; AddRef(s->Cedar->ref); s->Interrupt = interrupt; s->SessionList = NewList(OvsCompareSessionList); s->SendPacketList = NewListFast(NULL); s->Now = Tick64(); s->NextSessionId = 1; if (sock_event != NULL) { s->SockEvent = sock_event; AddRef(s->SockEvent->ref); } OvsLog(s, NULL, NULL, "LO_START"); s->Dh = DhNewGroup2(); return s; } // Release the OpenVPN server void FreeOpenVpnServer(OPENVPN_SERVER *s) { UINT i; // Validate arguments if (s == NULL) { return; } OvsLog(s, NULL, NULL, "LO_STOP"); // Release the session list for (i = 0;i < LIST_NUM(s->SessionList);i++) { OPENVPN_SESSION *se = LIST_DATA(s->SessionList, i); OvsFreeSession(se); } ReleaseList(s->SessionList); // Release the packet which is attempting to send for (i = 0;i < LIST_NUM(s->SendPacketList);i++) { UDPPACKET *p = LIST_DATA(s->SendPacketList, i); FreeUdpPacket(p); } ReleaseList(s->SendPacketList); ReleaseCedar(s->Cedar); if (s->SockEvent != NULL) { ReleaseSockEvent(s->SockEvent); } DhFree(s->Dh); Free(s); } // UDP reception procedure void OpenVpnServerUdpListenerProc(UDPLISTENER *u, LIST *packet_list) { OPENVPN_SERVER_UDP *us; UINT64 now = Tick64(); // Validate arguments if (u == NULL || packet_list == NULL) { return; } us = (OPENVPN_SERVER_UDP *)u->Param; if (OvsGetNoOpenVpnUdp()) { // OpenVPN over UDP is disabled return; } if (us->OpenVpnServer != NULL) { { u->PollMyIpAndPort = false; ClearStr(us->Cedar->OpenVPNPublicPorts, sizeof(us->Cedar->OpenVPNPublicPorts)); } OvsRecvPacket(us->OpenVpnServer, packet_list, OPENVPN_PROTOCOL_UDP); UdpListenerSendPackets(u, us->OpenVpnServer->SendPacketList); DeleteAll(us->OpenVpnServer->SendPacketList); } } // Create an OpenVPN server (UDP mode) OPENVPN_SERVER_UDP *NewOpenVpnServerUdp(CEDAR *cedar) { OPENVPN_SERVER_UDP *u; // Validate arguments if (cedar == NULL) { return NULL; } u = ZeroMalloc(sizeof(OPENVPN_SERVER_UDP)); u->Cedar = cedar; AddRef(u->Cedar->ref); // Create a UDP listener u->UdpListener = NewUdpListener(OpenVpnServerUdpListenerProc, u, &cedar->Server->ListenIP); // Create an OpenVPN server u->OpenVpnServer = NewOpenVpnServer(cedar, u->UdpListener->Interrupts, u->UdpListener->Event); return u; } // Apply the port list to the OpenVPN server void OvsApplyUdpPortList(OPENVPN_SERVER_UDP *u, char *port_list, IP *listen_ip) { LIST *o; UINT i; // Validate arguments if (u == NULL) { return; } DeleteAllPortFromUdpListener(u->UdpListener); if (u->UdpListener != NULL && listen_ip != NULL) { Copy(&u->UdpListener->ListenIP, listen_ip, sizeof(IP)); } o = StrToIntList(port_list, true); for (i = 0;i < LIST_NUM(o);i++) { UINT port = *((UINT *)LIST_DATA(o, i)); if (port >= 1 && port <= 65535) { AddPortToUdpListener(u->UdpListener, port); } } ReleaseIntList(o); } // Release the OpenVPN server (UDP mode) void FreeOpenVpnServerUdp(OPENVPN_SERVER_UDP *u) { // Validate arguments if (u == NULL) { return; } // Stop the UDP listener FreeUdpListener(u->UdpListener); // Release the OpenVPN server FreeOpenVpnServer(u->OpenVpnServer); ReleaseCedar(u->Cedar); Free(u); } // Check whether it's OpenSSL protocol by looking the first receive buffer of the TCP bool OvsCheckTcpRecvBufIfOpenVPNProtocol(UCHAR *buf, UINT size) { if (buf == NULL || size != 2) { return false; } if (buf[0] == 0x00 && buf[1] == 0x0E) { return true; } return false; } // Run the OpenVPN server in TCP mode bool OvsPerformTcpServer(CEDAR *cedar, SOCK *sock) { OPENVPN_SERVER *s; INTERRUPT_MANAGER *im; SOCK_EVENT *se; FIFO *tcp_recv_fifo; FIFO *tcp_send_fifo; UINT buf_size = (128 * 1024); UCHAR *buf; UINT64 giveup_time = Tick64() + (UINT64)OPENVPN_NEW_SESSION_DEADLINE_TIMEOUT; LIST *ovs_recv_packet; UINT i; bool ret = false; // Validate arguments if (cedar == NULL || sock == NULL) { return false; } // Initialize buf = Malloc(buf_size); im = NewInterruptManager(); se = NewSockEvent(); SetTimeout(sock, TIMEOUT_INFINITE); JoinSockToSockEvent(sock, se); tcp_recv_fifo = NewFifoFast(); tcp_send_fifo = NewFifoFast(); ovs_recv_packet = NewListFast(NULL); // Create an OpenVPN server s = NewOpenVpnServer(cedar, im, se); // Main loop Debug("Entering OpenVPN TCP Server Main Loop.\n"); while (true) { UINT next_interval; bool disconnected = false; UINT64 now = Tick64(); // Receive data from a TCP socket while (true) { UINT r = Recv(sock, buf, buf_size, false); if (r == SOCK_LATER) { // Can not read any more break; } else if (r == 0) { // Disconnected disconnected = true; break; } else { // Read WriteFifo(tcp_recv_fifo, buf, r); } } // Separate to a list of datagrams by interpreting the data received from the TCP socket while (true) { UINT r = FifoSize(tcp_recv_fifo); if (r >= sizeof(USHORT)) { void *ptr = FifoPtr(tcp_recv_fifo); USHORT packet_size = READ_USHORT(ptr); if (packet_size <= OPENVPN_TCP_MAX_PACKET_SIZE) { UINT total_len = (UINT)packet_size + sizeof(USHORT); if (r >= total_len) { if (ReadFifo(tcp_recv_fifo, buf, total_len) != total_len) { // Mismatch disconnected = true; break; } else { // Read one packet UINT payload_len = packet_size; UCHAR *payload_ptr = buf + sizeof(USHORT); // Pass the packet to the OpenVPN server Add(ovs_recv_packet, NewUdpPacket(&sock->RemoteIP, sock->RemotePort, &sock->LocalIP, sock->LocalPort, Clone(payload_ptr, payload_len), payload_len)); } } else { // Non-arrival break; } } else { // Invalid packet size disconnected = true; break; } } else { // Non-arrival break; } } // Pass a list of received datagrams to the OpenVPN server OvsRecvPacket(s, ovs_recv_packet, OPENVPN_PROTOCOL_TCP); // Release the received packet list for (i = 0;i < LIST_NUM(ovs_recv_packet);i++) { UDPPACKET *p = LIST_DATA(ovs_recv_packet, i); FreeUdpPacket(p); } DeleteAll(ovs_recv_packet); // Store in the queue by getting a list of the datagrams to be transmitted from the OpenVPN server for (i = 0;i < LIST_NUM(s->SendPacketList);i++) { UDPPACKET *p = LIST_DATA(s->SendPacketList, i); // Store the size to the TCP send queue first USHORT us = (USHORT)p->Size; //Debug(" *** TCP SEND %u\n", us); us = Endian16(us); WriteFifo(tcp_send_fifo, &us, sizeof(USHORT)); // Write the data body WriteFifo(tcp_send_fifo, p->Data, p->Size); // Packet release FreeUdpPacket(p); } DeleteAll(s->SendPacketList); // Send data to the TCP socket while (FifoSize(tcp_send_fifo) >= 1) { UINT r = Send(sock, FifoPtr(tcp_send_fifo), FifoSize(tcp_send_fifo), false); if (r == SOCK_LATER) { // Can not write any more break; } else if (r == 0) { // Disconnected disconnected = true; break; } else { // Wrote out ReadFifo(tcp_send_fifo, NULL, r); } } if (FifoSize(tcp_send_fifo) > MAX_BUFFERING_PACKET_SIZE) { s->SupressSendPacket = true; } else { s->SupressSendPacket = false; } if (s->DisconnectCount >= 1) { // Session disconnection has occurred on OpenVPN server-side disconnected = true; } if (giveup_time <= now) { UINT i; UINT num_established_sessions = 0; for (i = 0;i < LIST_NUM(s->SessionList);i++) { OPENVPN_SESSION *se = LIST_DATA(s->SessionList, i); if (se->Established) { num_established_sessions++; } } if (num_established_sessions == 0) { // If the number of sessions is 0 even if wait a certain period of time after the start of server, abort disconnected = true; } } if (disconnected) { // Error or disconnect occurs Debug("Breaking OpenVPN TCP Server Main Loop.\n"); break; } // Wait until the next event occurs next_interval = GetNextIntervalForInterrupt(im); next_interval = MIN(next_interval, UDPLISTENER_WAIT_INTERVAL); WaitSockEvent(se, next_interval); } if (s != NULL && s->SessionEstablishedCount != 0) { ret = true; } // Release the OpenVPN server FreeOpenVpnServer(s); // Release object FreeInterruptManager(im); ReleaseSockEvent(se); ReleaseFifo(tcp_recv_fifo); ReleaseFifo(tcp_send_fifo); Free(buf); // Release the received packet list for (i = 0;i < LIST_NUM(ovs_recv_packet);i++) { UDPPACKET *p = LIST_DATA(ovs_recv_packet, i); FreeUdpPacket(p); } ReleaseList(ovs_recv_packet); return ret; }
4402.c
/* * jcmaster.c * * Copyright (C) 1991-1994, Thomas G. Lane. * This file is part of the Independent JPEG Group's software. * For conditions of distribution and use, see the accompanying README file. * * This file contains master control logic for the JPEG compressor. * These routines are concerned with selecting the modules to be executed * and with determining the number of passes and the work to be done in each * pass. */ #define JPEG_INTERNALS #include "jinclude.h" #include "jpeglib.h" // sm: make type names globally unique #define my_master_ptr jcmaster_my_master_ptr /* Private state */ typedef struct my_comp_master { struct jpeg_comp_master pub; /* public fields */ int pass_number; /* eventually need more complex state... */ } my_comp_master; typedef my_comp_master * my_master_ptr; #pragma ccured_extends("Smy_comp_master", "Sjpeg_comp_master") /* * Support routines that do various essential calculations. */ LOCAL void initial_setup (j_compress_ptr cinfo) /* Do computations that are needed before master selection phase */ { int ci; jpeg_component_info *compptr; long samplesperrow; JDIMENSION jd_samplesperrow; /* Sanity check on image dimensions */ if (cinfo->image_height <= 0 || cinfo->image_width <= 0 || cinfo->num_components <= 0 || cinfo->input_components <= 0) ERREXIT(cinfo, JERR_EMPTY_IMAGE); /* Make sure image isn't bigger than I can handle */ if ((long) cinfo->image_height > (long) JPEG_MAX_DIMENSION || (long) cinfo->image_width > (long) JPEG_MAX_DIMENSION) ERREXIT1(cinfo, JERR_IMAGE_TOO_BIG, (unsigned int) JPEG_MAX_DIMENSION); /* Width of an input scanline must be representable as JDIMENSION. */ samplesperrow = (long) cinfo->image_width * (long) cinfo->input_components; jd_samplesperrow = (JDIMENSION) samplesperrow; if ((long) jd_samplesperrow != samplesperrow) ERREXIT(cinfo, JERR_WIDTH_OVERFLOW); /* For now, precision must match compiled-in value... */ if (cinfo->data_precision != BITS_IN_JSAMPLE) ERREXIT1(cinfo, JERR_BAD_PRECISION, cinfo->data_precision); /* Check that number of components won't exceed internal array sizes */ if (cinfo->num_components > MAX_COMPONENTS) ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components, MAX_COMPONENTS); /* Compute maximum sampling factors; check factor validity */ cinfo->max_h_samp_factor = 1; cinfo->max_v_samp_factor = 1; for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components; ci++, compptr++) { if (compptr->h_samp_factor<=0 || compptr->h_samp_factor>MAX_SAMP_FACTOR || compptr->v_samp_factor<=0 || compptr->v_samp_factor>MAX_SAMP_FACTOR) ERREXIT(cinfo, JERR_BAD_SAMPLING); cinfo->max_h_samp_factor = MAX(cinfo->max_h_samp_factor, compptr->h_samp_factor); cinfo->max_v_samp_factor = MAX(cinfo->max_v_samp_factor, compptr->v_samp_factor); } /* Compute dimensions of components */ for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components; ci++, compptr++) { /* For compression, we never do DCT scaling. */ compptr->DCT_scaled_size = DCTSIZE; /* Size in DCT blocks */ compptr->width_in_blocks = (JDIMENSION) jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor, (long) (cinfo->max_h_samp_factor * DCTSIZE)); compptr->height_in_blocks = (JDIMENSION) jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor, (long) (cinfo->max_v_samp_factor * DCTSIZE)); /* Size in samples */ compptr->downsampled_width = (JDIMENSION) jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor, (long) cinfo->max_h_samp_factor); compptr->downsampled_height = (JDIMENSION) jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor, (long) cinfo->max_v_samp_factor); /* Mark component needed (this flag isn't actually used for compression) */ compptr->component_needed = TRUE; } /* Compute number of fully interleaved MCU rows (number of times that * main controller will call coefficient controller). */ cinfo->total_iMCU_rows = (JDIMENSION) jdiv_round_up((long) cinfo->image_height, (long) (cinfo->max_v_samp_factor*DCTSIZE)); } LOCAL void per_scan_setup (j_compress_ptr cinfo) /* Do computations that are needed before processing a JPEG scan */ /* cinfo->comps_in_scan and cinfo->cur_comp_info[] are already set */ { int ci, mcublks, tmp; jpeg_component_info *compptr; if (cinfo->comps_in_scan == 1) { /* Noninterleaved (single-component) scan */ compptr = cinfo->cur_comp_info[0]; /* Overall image size in MCUs */ cinfo->MCUs_per_row = compptr->width_in_blocks; cinfo->MCU_rows_in_scan = compptr->height_in_blocks; /* For noninterleaved scan, always one block per MCU */ compptr->MCU_width = 1; compptr->MCU_height = 1; compptr->MCU_blocks = 1; compptr->MCU_sample_width = DCTSIZE; compptr->last_col_width = 1; compptr->last_row_height = 1; /* Prepare array describing MCU composition */ cinfo->blocks_in_MCU = 1; cinfo->MCU_membership[0] = 0; } else { /* Interleaved (multi-component) scan */ if (cinfo->comps_in_scan <= 0 || cinfo->comps_in_scan > MAX_COMPS_IN_SCAN) ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->comps_in_scan, MAX_COMPS_IN_SCAN); /* Overall image size in MCUs */ cinfo->MCUs_per_row = (JDIMENSION) jdiv_round_up((long) cinfo->image_width, (long) (cinfo->max_h_samp_factor*DCTSIZE)); cinfo->MCU_rows_in_scan = (JDIMENSION) jdiv_round_up((long) cinfo->image_height, (long) (cinfo->max_v_samp_factor*DCTSIZE)); cinfo->blocks_in_MCU = 0; for (ci = 0; ci < cinfo->comps_in_scan; ci++) { compptr = cinfo->cur_comp_info[ci]; /* Sampling factors give # of blocks of component in each MCU */ compptr->MCU_width = compptr->h_samp_factor; compptr->MCU_height = compptr->v_samp_factor; compptr->MCU_blocks = compptr->MCU_width * compptr->MCU_height; compptr->MCU_sample_width = compptr->MCU_width * DCTSIZE; /* Figure number of non-dummy blocks in last MCU column & row */ tmp = (int) (compptr->width_in_blocks % compptr->MCU_width); if (tmp == 0) tmp = compptr->MCU_width; compptr->last_col_width = tmp; tmp = (int) (compptr->height_in_blocks % compptr->MCU_height); if (tmp == 0) tmp = compptr->MCU_height; compptr->last_row_height = tmp; /* Prepare array describing MCU composition */ mcublks = compptr->MCU_blocks; if (cinfo->blocks_in_MCU + mcublks > MAX_BLOCKS_IN_MCU) ERREXIT(cinfo, JERR_BAD_MCU_SIZE); while (mcublks-- > 0) { cinfo->MCU_membership[cinfo->blocks_in_MCU++] = ci; } } } /* Convert restart specified in rows to actual MCU count. */ /* Note that count must fit in 16 bits, so we provide limiting. */ if (cinfo->restart_in_rows > 0) { long nominal = (long) cinfo->restart_in_rows * (long) cinfo->MCUs_per_row; cinfo->restart_interval = (unsigned int) MIN(nominal, 65535L); } } /* * Master selection of compression modules. * This is done once at the start of processing an image. We determine * which modules will be used and give them appropriate initialization calls. */ LOCAL void master_selection (j_compress_ptr cinfo) { my_master_ptr master = (my_master_ptr) cinfo->master; initial_setup(cinfo); master->pass_number = 0; /* There's not a lot of smarts here right now, but it'll get more * complicated when we have multiple implementations available... */ /* Preprocessing */ if (! cinfo->raw_data_in) { jinit_color_converter(cinfo); jinit_downsampler(cinfo); jinit_c_prep_controller(cinfo, FALSE /* never need full buffer here */); } /* Forward DCT */ jinit_forward_dct(cinfo); /* Entropy encoding: either Huffman or arithmetic coding. */ if (cinfo->arith_code) { #ifdef C_ARITH_CODING_SUPPORTED jinit_arith_encoder(cinfo); #else ERREXIT(cinfo, JERR_ARITH_NOTIMPL); #endif } else jinit_huff_encoder(cinfo); /* For now, a full buffer is needed only for Huffman optimization. */ jinit_c_coef_controller(cinfo, cinfo->optimize_coding); jinit_c_main_controller(cinfo, FALSE /* never need full buffer here */); jinit_marker_writer(cinfo); /* We can now tell the memory manager to allocate virtual arrays. */ (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo); /* Write the datastream header (SOI) immediately. * Frame and scan headers are postponed till later. * This lets application insert special markers after the SOI. */ (*cinfo->marker->write_file_header) (cinfo); } /* * Per-pass setup. * This is called at the beginning of each pass. We determine which modules * will be active during this pass and give them appropriate start_pass calls. * We also set is_last_pass to indicate whether any more passes will be * required. */ METHODDEF void prepare_for_pass (j_compress_ptr cinfo) { my_master_ptr master = (my_master_ptr) cinfo->master; int ci; int npasses; /* ???? JUST A QUICK CROCK FOR NOW ??? */ /* For now, handle only single interleaved output scan; */ /* we support two passes for Huffman optimization. */ /* Prepare for single scan containing all components */ if (cinfo->num_components > MAX_COMPS_IN_SCAN) ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components, MAX_COMPS_IN_SCAN); cinfo->comps_in_scan = cinfo->num_components; for (ci = 0; ci < cinfo->num_components; ci++) { cinfo->cur_comp_info[ci] = &cinfo->comp_info[ci]; } per_scan_setup(cinfo); if (! cinfo->optimize_coding) { /* Standard single-pass case */ npasses = 1; master->pub.call_pass_startup = TRUE; master->pub.is_last_pass = TRUE; if (! cinfo->raw_data_in) { (*cinfo->cconvert->start_pass) (cinfo); (*cinfo->downsample->start_pass) (cinfo); (*cinfo->prep->start_pass) (cinfo, JBUF_PASS_THRU); } (*cinfo->fdct->start_pass) (cinfo); (*cinfo->entropy->start_pass) (cinfo, FALSE); (*cinfo->coef->start_pass) (cinfo, JBUF_PASS_THRU); (*cinfo->main->start_pass) (cinfo, JBUF_PASS_THRU); } else { npasses = 2; switch (master->pass_number) { case 0: /* Huffman optimization: run all modules, gather statistics */ master->pub.call_pass_startup = FALSE; master->pub.is_last_pass = FALSE; if (! cinfo->raw_data_in) { (*cinfo->cconvert->start_pass) (cinfo); (*cinfo->downsample->start_pass) (cinfo); (*cinfo->prep->start_pass) (cinfo, JBUF_PASS_THRU); } (*cinfo->fdct->start_pass) (cinfo); (*cinfo->entropy->start_pass) (cinfo, TRUE); (*cinfo->coef->start_pass) (cinfo, JBUF_SAVE_AND_PASS); (*cinfo->main->start_pass) (cinfo, JBUF_PASS_THRU); break; case 1: /* Second pass: reread data from coefficient buffer */ master->pub.is_last_pass = TRUE; (*cinfo->entropy->start_pass) (cinfo, FALSE); (*cinfo->coef->start_pass) (cinfo, JBUF_CRANK_DEST); /* We emit frame/scan headers now */ (*cinfo->marker->write_frame_header) (cinfo); (*cinfo->marker->write_scan_header) (cinfo); break; } } /* Set up progress monitor's pass info if present */ if (cinfo->progress != NULL) { cinfo->progress->completed_passes = master->pass_number; cinfo->progress->total_passes = npasses; } master->pass_number++; } /* * Special start-of-pass hook. * This is called by jpeg_write_scanlines if call_pass_startup is TRUE. * In single-pass processing, we need this hook because we don't want to * write frame/scan headers during jpeg_start_compress; we want to let the * application write COM markers etc. between jpeg_start_compress and the * jpeg_write_scanlines loop. * In multi-pass processing, this routine is not used. */ METHODDEF void pass_startup (j_compress_ptr cinfo) { cinfo->master->call_pass_startup = FALSE; /* reset flag so call only once */ (*cinfo->marker->write_frame_header) (cinfo); (*cinfo->marker->write_scan_header) (cinfo); } /* * Finish up at end of pass. */ METHODDEF void finish_pass_master (j_compress_ptr cinfo) { /* More complex logic later ??? */ /* The entropy coder needs an end-of-pass call, either to analyze * statistics or to flush its output buffer. */ (*cinfo->entropy->finish_pass) (cinfo); } /* * Initialize master compression control. * This creates my own subrecord and also performs the master selection phase, * which causes other modules to create their subrecords. */ GLOBAL void jinit_master_compress (j_compress_ptr cinfo) { my_master_ptr master; master = (my_master_ptr)alloc_small_wrapper((j_common_ptr) cinfo, JPOOL_IMAGE, SIZEOF(my_comp_master)); cinfo->master = (struct jpeg_comp_master *) master; master->pub.prepare_for_pass = prepare_for_pass; master->pub.pass_startup = pass_startup; master->pub.finish_pass = finish_pass_master; master_selection(cinfo); }
333792.c
#define NULL ((void*)0) typedef unsigned long size_t; // Customize by platform. typedef long intptr_t; typedef unsigned long uintptr_t; typedef long scalar_t__; // Either arithmetic or pointer type. /* By default, we understand bool (as a convenience). */ typedef int bool; #define false 0 #define true 1 /* Forward declarations */ typedef struct TYPE_10__ TYPE_3__ ; typedef struct TYPE_9__ TYPE_2__ ; typedef struct TYPE_8__ TYPE_1__ ; /* Type definitions */ struct TYPE_8__ {scalar_t__ x; struct TYPE_8__* next; } ; typedef TYPE_1__ stbrp_node ; struct TYPE_9__ {int align; scalar_t__ width; scalar_t__ heuristic; int height; TYPE_1__* active_head; } ; typedef TYPE_2__ stbrp_context ; struct TYPE_10__ {int x; int y; TYPE_1__** prev_link; } ; typedef TYPE_3__ stbrp__findresult ; /* Variables and functions */ int /*<<< orphan*/ STBRP_ASSERT (int) ; scalar_t__ STBRP_HEURISTIC_Skyline_BF_sortHeight ; scalar_t__ STBRP_HEURISTIC_Skyline_BL_sortHeight ; int stbrp__skyline_find_min_y (TYPE_2__*,TYPE_1__*,int,int,int*) ; __attribute__((used)) static stbrp__findresult stbrp__skyline_find_best_pos(stbrp_context *c, int width, int height) { int best_waste = (1<<30), best_x, best_y = (1 << 30); stbrp__findresult fr; stbrp_node **prev, *node, *tail, **best = NULL; /* align to multiple of c->align */ width = (width + c->align - 1); width -= width % c->align; STBRP_ASSERT(width % c->align == 0); node = c->active_head; prev = &c->active_head; while (node->x + width <= c->width) { int waste; int y = stbrp__skyline_find_min_y(c, node, node->x, width, &waste); if (c->heuristic == STBRP_HEURISTIC_Skyline_BL_sortHeight) { /* actually just want to test BL bottom left */ if (y < best_y) { best_y = y; best = prev; } } else { /* best-fit */ if (y + height <= c->height) { /* can only use it if it first vertically */ if (y < best_y || (y == best_y && waste < best_waste)) { best_y = y; best_waste = waste; best = prev; } } } prev = &node->next; node = node->next; } best_x = (best == NULL) ? 0 : (*best)->x; /* if doing best-fit (BF), we also have to try aligning right edge to each node position * * e.g, if fitting * * ____________________ * |____________________| * * into * * | | * | ____________| * |____________| * * then right-aligned reduces waste, but bottom-left BL is always chooses left-aligned * * This makes BF take about 2x the time */ if (c->heuristic == STBRP_HEURISTIC_Skyline_BF_sortHeight) { tail = c->active_head; node = c->active_head; prev = &c->active_head; /* find first node that's admissible */ while (tail->x < width) tail = tail->next; while (tail) { int xpos = tail->x - width; int y,waste; STBRP_ASSERT(xpos >= 0); /* find the left position that matches this */ while (node->next->x <= xpos) { prev = &node->next; node = node->next; } STBRP_ASSERT(node->next->x > xpos && node->x <= xpos); y = stbrp__skyline_find_min_y(c, node, xpos, width, &waste); if (y + height < c->height) { if (y <= best_y) { if (y < best_y || waste < best_waste || (waste==best_waste && xpos < best_x)) { best_x = xpos; STBRP_ASSERT(y <= best_y); best_y = y; best_waste = waste; best = prev; } } } tail = tail->next; } } fr.prev_link = best; fr.x = best_x; fr.y = best_y; return fr; }
455953.c
/* $NetBSD: newfs_udf.c,v 1.22 2021/09/19 10:34:07 andvar Exp $ */ /* * Copyright (c) 2006, 2008, 2013 Reinoud Zandijk * 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. * */ /* * TODO * - implement metadata formatting for BD-R * - implement support for a read-only companion partition? */ #define _EXPOSE_MMC #if 0 # define DEBUG #endif #include <stdio.h> #include <stdlib.h> #include <dirent.h> #include <inttypes.h> #include <stdint.h> #include <string.h> #include <errno.h> #include <fcntl.h> #include <unistd.h> // #include <util.h> #include <time.h> #include <assert.h> #include <err.h> #include <sys/ioctl.h> #include <sys/stat.h> #include <sys/types.h> #include "cdio.h" // #include <sys/disklabel.h> // #include <sys/dkio.h> #include <sys/param.h> #include <sys/queue.h> #include "ecma167-udf.h" #include "udf_mount.h" // #include "mountprog.h" #include "udf_create.h" #include "udf_write.h" #include "newfs_udf.h" const char* getprogname(void); void setprogname(const char* __name); char * snprintb (char *buffer, size_t n, unsigned v, char *bits) { size_t len; int i, j; char c, *bp; snprintf (buffer, n, bits && *bits == 010 ? "0%o" : "0x%x", v); len = strlen(buffer); bp = buffer + len; n -= len; if (bits && *++bits) { j = 0; *bp++ = '<'; while ((i = *bits++) && n > 1) if (v & (1 << (i - 1))) { if (j++ && n > 1) { *bp++ = ','; n--; } for (; (c = *bits) > 32 && n > 1; bits++) { *bp++ = c; n--; } } else for (; *bits > 32; bits++) continue; if (n > 1) *bp++ = '>'; *bp = 0; } return buffer; } /* $NetBSD: dehumanize_number.c,v 1.2 2007/12/14 17:32:47 xtraeme Exp $ */ /* * Copyright (c) 2005, 2006 The NetBSD Foundation, Inc. * All rights reserved. * * This code is derived from software contributed to The NetBSD Foundation * by Julio M. Merino Vidal, developed as part of Google's Summer of Code * 2005 program. * * 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 NETBSD FOUNDATION, INC. AND CONTRIBUTORS * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include <sys/cdefs.h> #if defined(LIBC_SCCS) && !defined(lint) // __RCSID("$NetBSD: dehumanize_number.c,v 1.2 2007/12/14 17:32:47 xtraeme Exp $"); #endif /* LIBC_SCCS and not lint */ #include <inttypes.h> #include <ctype.h> #include <stdlib.h> #include <string.h> #include <errno.h> #include <limits.h> /* * Converts the number given in 'str', which may be given in a humanized * form (as described in humanize_number(3), but with some limitations), * to an int64_t without units. * In case of success, 0 is returned and *size holds the value. * Otherwise, -1 is returned and *size is untouched. * * TODO: Internationalization, SI units. */ int dehumanize_number(const char *str, int64_t *size) { char *ep, unit; const char *delimit; long multiplier; long long tmp, tmp2; size_t len; len = strlen(str); if (len == 0) { errno = EINVAL; return -1; } multiplier = 1; unit = str[len - 1]; if (isalpha((unsigned char)unit)) { switch (tolower((unsigned char)unit)) { case 'b': multiplier = 1; break; case 'k': multiplier = 1024; break; case 'm': multiplier = 1024 * 1024; break; case 'g': multiplier = 1024 * 1024 * 1024; break; default: errno = EINVAL; return -1; /* Invalid suffix. */ } delimit = &str[len - 1]; } else delimit = NULL; errno = 0; tmp = strtoll(str, &ep, 10); if (str[0] == '\0' || (ep != delimit && *ep != '\0')) return -1; /* Not a number. */ else if (errno == ERANGE && (tmp == LLONG_MAX || tmp == LLONG_MIN)) return -1; /* Out of range. */ tmp2 = tmp * multiplier; tmp2 = tmp2 / multiplier; if (tmp != tmp2) { errno = ERANGE; return -1; /* Out of range. */ } *size = tmp * multiplier; return 0; } int a_num(const char *s, const char *id_type) { int id; char *ep; id = strtol(s, &ep, 0); if (*ep || s == ep || id < 0) errx(1, "unknown %s id: %s", id_type, s); return id; } /* prototypes */ int newfs_udf(int argc, char **argv); static void usage(void) __attribute__((__noreturn__)); /* queue for temporary storage of sectors to be written out */ struct wrsect { uint64_t sectornr; uint8_t *sector_data; TAILQ_ENTRY(wrsect) next; }; /* write queue and track blocking skew */ TAILQ_HEAD(wrsect_list, wrsect) write_queue; /* global variables describing disc and format requests */ int fd; /* device: file descriptor */ char *dev; /* device: name */ struct mmc_discinfo mmc_discinfo; /* device: disc info */ char *format_str; /* format: string representation */ int format_flags; /* format: attribute flags */ int media_accesstype; /* derived from current mmc cap */ int check_surface; /* for rewritables */ int imagefile_secsize; /* for files */ int emul_packetsize; /* for discs and files */ int wrtrack_skew; int meta_perc = UDF_META_PERC; float meta_fract = (float) UDF_META_PERC / 100.0; /* --------------------------------------------------------------------- */ /* * write queue implementation */ int udf_write_sector(void *sector, uint64_t location) { struct wrsect *pos, *seekpos; /* search location */ TAILQ_FOREACH_REVERSE(seekpos, &write_queue, wrsect_list, next) { if (seekpos->sectornr <= location) break; } if ((seekpos == NULL) || (seekpos->sectornr != location)) { pos = calloc(1, sizeof(struct wrsect)); if (pos == NULL) return errno; /* allocate space for copy of sector data */ pos->sector_data = calloc(1, context.sector_size); if (pos->sector_data == NULL) { free(pos); return errno; } pos->sectornr = location; if (seekpos) { TAILQ_INSERT_AFTER(&write_queue, seekpos, pos, next); } else { TAILQ_INSERT_HEAD(&write_queue, pos, next); } } else { pos = seekpos; } memcpy(pos->sector_data, sector, context.sector_size); return 0; } /* * Now all write requests are queued in the TAILQ, write them out to the * disc/file image. Special care needs to be taken for devices that are only * strict overwritable i.e. only in packet size chunks * * XXX support for growing vnd? */ int writeout_write_queue(void) { struct wrsect *pos; uint64_t offset; uint64_t line_start, new_line_start; uint32_t line_len, line_offset, relpos; uint32_t blockingnr; uint8_t *linebuf, *adr; blockingnr = layout.blockingnr; line_len = blockingnr * context.sector_size; line_offset = wrtrack_skew * context.sector_size; linebuf = malloc(line_len); if (linebuf == NULL) return ENOMEM; pos = TAILQ_FIRST(&write_queue); bzero(linebuf, line_len); /* * Always writing out in whole lines now; this is slightly wastefull * on logical overwrite volumes but it reduces complexity and the loss * is near zero compared to disc size. */ line_start = (pos->sectornr - wrtrack_skew) / blockingnr; TAILQ_FOREACH(pos, &write_queue, next) { new_line_start = (pos->sectornr - wrtrack_skew) / blockingnr; if (new_line_start != line_start) { /* write out */ offset = (uint64_t) line_start * line_len + line_offset; #ifdef DEBUG printf("WRITEOUT %08"PRIu64" + %02d -- " "[%08"PRIu64"..%08"PRIu64"]\n", offset / context.sector_size, blockingnr, offset / context.sector_size, offset / context.sector_size + blockingnr-1); #endif if (pwrite(fd, linebuf, line_len, offset) < 0) { perror("Writing failed"); return errno; } line_start = new_line_start; bzero(linebuf, line_len); } relpos = (pos->sectornr - wrtrack_skew) % blockingnr; adr = linebuf + relpos * context.sector_size; memcpy(adr, pos->sector_data, context.sector_size); } /* writeout last chunk */ offset = (uint64_t) line_start * line_len + line_offset; #ifdef DEBUG printf("WRITEOUT %08"PRIu64" + %02d -- [%08"PRIu64"..%08"PRIu64"]\n", offset / context.sector_size, blockingnr, offset / context.sector_size, offset / context.sector_size + blockingnr-1); #endif if (pwrite(fd, linebuf, line_len, offset) < 0) { perror("Writing failed"); return errno; } /* success */ return 0; } /* --------------------------------------------------------------------- */ /* * mmc_discinfo and mmc_trackinfo readers modified from origional in udf main * code in sys/fs/udf/ */ #ifdef DEBUG static void udf_dump_discinfo(struct mmc_discinfo *di) { char bits[128]; printf("Device/media info :\n"); printf("\tMMC profile 0x%02x\n", di->mmc_profile); printf("\tderived class %d\n", di->mmc_class); printf("\tsector size %d\n", di->sector_size); printf("\tdisc state %d\n", di->disc_state); printf("\tlast ses state %d\n", di->last_session_state); printf("\tbg format state %d\n", di->bg_format_state); printf("\tfrst track %d\n", di->first_track); printf("\tfst on last ses %d\n", di->first_track_last_session); printf("\tlst on last ses %d\n", di->last_track_last_session); printf("\tlink block penalty %d\n", di->link_block_penalty); //snprintb(bits, sizeof(bits), MMC_DFLAGS_FLAGBITS, (uint64_t) di->disc_flags); printf("\tdisc flags %s\n", bits); printf("\tdisc id %x\n", di->disc_id); printf("\tdisc barcode %"PRIx64"\n", di->disc_barcode); printf("\tnum sessions %d\n", di->num_sessions); printf("\tnum tracks %d\n", di->num_tracks); //snprintb(bits, sizeof(bits), MMC_CAP_FLAGBITS, di->mmc_cur); printf("\tcapabilities cur %s\n", bits); //snprintb(bits, sizeof(bits), MMC_CAP_FLAGBITS, di->mmc_cap); printf("\tcapabilities cap %s\n", bits); printf("\n"); printf("\tlast_possible_lba %d\n", di->last_possible_lba); printf("\n"); } #else #define udf_dump_discinfo(a); #endif /* --------------------------------------------------------------------- */ static int udf_update_discinfo(struct mmc_discinfo *di) { struct stat st; //struct disklabel disklab; //struct partition *dp; off_t size, sectors, secsize; int partnr, error; memset(di, 0, sizeof(struct mmc_discinfo)); #if 0 /* check if we're on a MMC capable device, i.e. CD/DVD */ error = ioctl(fd, MMCGETDISCINFO, di); if (error == 0) return 0; #endif /* (re)fstat the file */ fstat(fd, &st); if (S_ISREG(st.st_mode)) { /* file support; we pick the minimum sector size allowed */ size = st.st_size; secsize = imagefile_secsize; sectors = size / secsize; } else { /* * disc partition support; note we can't use DIOCGPART in * userland so get disc label and use the stat info to get the * partition number. */ #if 0 if (ioctl(fd, DIOCGDINFO, &disklab) == -1) { /* failed to get disclabel! */ perror("disklabel"); return errno; } /* get disk partition it refers to */ fstat(fd, &st); partnr = DISKPART(st.st_rdev); dp = &disklab.d_partitions[partnr]; /* TODO problem with last_possible_lba on resizable VND */ if (dp->p_size == 0) { perror("faulty disklabel partition returned, " "check label\n"); return EIO; } #endif //sectors = dp->p_size; //secsize = disklab.d_secsize; sectors = 1000; secsize = 2048; // hardcoded! } /* set up a disc info profile for partitions */ di->mmc_profile = 0x01; /* disc type */ di->mmc_class = MMC_CLASS_DISC; di->disc_state = MMC_STATE_CLOSED; di->last_session_state = MMC_STATE_CLOSED; di->bg_format_state = MMC_BGFSTATE_COMPLETED; di->link_block_penalty = 0; di->mmc_cur = MMC_CAP_RECORDABLE | MMC_CAP_REWRITABLE | MMC_CAP_ZEROLINKBLK | MMC_CAP_HW_DEFECTFREE; di->mmc_cap = di->mmc_cur; di->disc_flags = MMC_DFLAGS_UNRESTRICTED; di->last_possible_lba = sectors - 1; di->sector_size = secsize; di->num_sessions = 1; di->num_tracks = 1; di->first_track = 1; di->first_track_last_session = di->last_track_last_session = 1; return 0; } int udf_update_trackinfo(struct mmc_discinfo *di, struct mmc_trackinfo *ti) { int error, class; class = di->mmc_class; if (class != MMC_CLASS_DISC) { /* tracknr specified in struct ti */ error = ioctl(fd, MMCGETTRACKINFO, ti); return error; } /* discs partition support */ if (ti->tracknr != 1) return EIO; /* create fake ti (TODO check for resized vnds) */ ti->sessionnr = 1; ti->track_mode = 0; /* XXX */ ti->data_mode = 0; /* XXX */ ti->flags = MMC_TRACKINFO_LRA_VALID | MMC_TRACKINFO_NWA_VALID; ti->track_start = 0; ti->packet_size = emul_packetsize; /* TODO support for resizable vnd */ ti->track_size = di->last_possible_lba; ti->next_writable = di->last_possible_lba; ti->last_recorded = ti->next_writable; ti->free_blocks = 0; return 0; } static int udf_setup_writeparams(struct mmc_discinfo *di) { struct mmc_writeparams mmc_writeparams; int error; if (di->mmc_class == MMC_CLASS_DISC) return 0; /* * only CD burning normally needs setting up, but other disc types * might need other settings to be made. The MMC framework will set up * the necessary recording parameters according to the disc * characteristics read in. Modifications can be made in the discinfo * structure passed to change the nature of the disc. */ memset(&mmc_writeparams, 0, sizeof(struct mmc_writeparams)); mmc_writeparams.mmc_class = di->mmc_class; mmc_writeparams.mmc_cur = di->mmc_cur; /* * UDF dictates first track to determine track mode for the whole * disc. [UDF 1.50/6.10.1.1, UDF 1.50/6.10.2.1] * To prevent problems with a `reserved' track in front we start with * the 2nd track and if that is not valid, go for the 1st. */ mmc_writeparams.tracknr = 2; mmc_writeparams.data_mode = MMC_DATAMODE_DEFAULT; /* XA disc */ mmc_writeparams.track_mode = MMC_TRACKMODE_DEFAULT; /* data */ error = ioctl(fd, MMCSETUPWRITEPARAMS, &mmc_writeparams); if (error) { mmc_writeparams.tracknr = 1; error = ioctl(fd, MMCSETUPWRITEPARAMS, &mmc_writeparams); } return error; } static void udf_synchronise_caches(void) { struct mmc_op mmc_op; bzero(&mmc_op, sizeof(struct mmc_op)); mmc_op.operation = MMC_OP_SYNCHRONISECACHE; /* this device might not know this ioct, so just be ignorant */ (void) ioctl(fd, MMCOP, &mmc_op); } /* --------------------------------------------------------------------- */ static int udf_prepare_disc(void) { struct mmc_trackinfo ti; struct mmc_op op; int tracknr, error; /* If the last track is damaged, repair it */ ti.tracknr = mmc_discinfo.last_track_last_session; error = udf_update_trackinfo(&mmc_discinfo, &ti); if (error) return error; if (ti.flags & MMC_TRACKINFO_DAMAGED) { /* * Need to repair last track before anything can be done. * this is an optional command, so ignore its error but report * warning. */ memset(&op, 0, sizeof(op)); op.operation = MMC_OP_REPAIRTRACK; op.mmc_profile = mmc_discinfo.mmc_profile; op.tracknr = ti.tracknr; error = ioctl(fd, MMCOP, &op); if (error) (void)printf("Drive can't explicitly repair last " "damaged track, but it might autorepair\n"); } /* last track (if any) might not be damaged now, operations are ok now */ /* setup write parameters from discinfo */ error = udf_setup_writeparams(&mmc_discinfo); if (error) return error; /* if the drive is not sequential, we're done */ if ((mmc_discinfo.mmc_cur & MMC_CAP_SEQUENTIAL) == 0) return 0; #ifdef notyet /* if last track is not the reserved but an empty track, unreserve it */ if (ti.flags & MMC_TRACKINFO_BLANK) { if (ti.flags & MMC_TRACKINFO_RESERVED == 0) { memset(&op, 0, sizeof(op)); op.operation = MMC_OP_UNRESERVETRACK; op.mmc_profile = mmc_discinfo.mmc_profile; op.tracknr = ti.tracknr; error = ioctl(fd, MMCOP, &op); if (error) return error; /* update discinfo since it changed by the operation */ error = udf_update_discinfo(&mmc_discinfo); if (error) return error; } } #endif /* close the last session if its still open */ if (mmc_discinfo.last_session_state == MMC_STATE_INCOMPLETE) { printf("Closing last open session if present\n"); /* close all associated tracks */ tracknr = mmc_discinfo.first_track_last_session; while (tracknr <= mmc_discinfo.last_track_last_session) { ti.tracknr = tracknr; error = udf_update_trackinfo(&mmc_discinfo, &ti); if (error) return error; printf("\tClosing open track %d\n", tracknr); memset(&op, 0, sizeof(op)); op.operation = MMC_OP_CLOSETRACK; op.mmc_profile = mmc_discinfo.mmc_profile; op.tracknr = tracknr; error = ioctl(fd, MMCOP, &op); if (error) return error; tracknr ++; } printf("Closing session\n"); memset(&op, 0, sizeof(op)); op.operation = MMC_OP_CLOSESESSION; op.mmc_profile = mmc_discinfo.mmc_profile; op.sessionnr = mmc_discinfo.num_sessions; error = ioctl(fd, MMCOP, &op); if (error) return error; /* update discinfo since it changed by the operations */ error = udf_update_discinfo(&mmc_discinfo); if (error) return error; } if (format_flags & FORMAT_TRACK512) { /* get last track again */ ti.tracknr = mmc_discinfo.last_track_last_session; error = udf_update_trackinfo(&mmc_discinfo, &ti); if (error) return error; /* Split up the space at 512 for iso cd9660 hooking */ memset(&op, 0, sizeof(op)); op.operation = MMC_OP_RESERVETRACK_NWA; /* UPTO nwa */ op.mmc_profile = mmc_discinfo.mmc_profile; op.extent = 512; /* size */ error = ioctl(fd, MMCOP, &op); if (error) return error; } return 0; } /* --------------------------------------------------------------------- */ int udf_surface_check(void) { uint32_t loc, block_bytes; uint32_t sector_size, blockingnr, bpos; uint8_t *buffer; int error, num_errors; sector_size = context.sector_size; blockingnr = layout.blockingnr; block_bytes = layout.blockingnr * sector_size; if ((buffer = malloc(block_bytes)) == NULL) return ENOMEM; /* set all one to not kill Flash memory? */ for (bpos = 0; bpos < block_bytes; bpos++) buffer[bpos] = 0x00; printf("\nChecking disc surface : phase 1 - writing\n"); num_errors = 0; loc = layout.first_lba; while (loc <= layout.last_lba) { /* write blockingnr sectors */ error = pwrite(fd, buffer, block_bytes, loc*sector_size); printf(" %08d + %d (%02d %%)\r", loc, blockingnr, (int)((100.0 * loc)/layout.last_lba)); fflush(stdout); if (error == -1) { /* block is bad */ printf("BAD block at %08d + %d \n", loc, layout.blockingnr); if ((error = udf_register_bad_block(loc))) { free(buffer); return error; } num_errors ++; } loc += layout.blockingnr; } printf("\nChecking disc surface : phase 2 - reading\n"); num_errors = 0; loc = layout.first_lba; while (loc <= layout.last_lba) { /* read blockingnr sectors */ error = pread(fd, buffer, block_bytes, loc*sector_size); printf(" %08d + %d (%02d %%)\r", loc, blockingnr, (int)((100.0 * loc)/layout.last_lba)); fflush(stdout); if (error == -1) { /* block is bad */ printf("BAD block at %08d + %d \n", loc, layout.blockingnr); if ((error = udf_register_bad_block(loc))) { free(buffer); return error; } num_errors ++; } loc += layout.blockingnr; } printf("Scan complete : %d bad blocks found\n", num_errors); free(buffer); return 0; } /* --------------------------------------------------------------------- */ static int udf_do_newfs(void) { int error; error = udf_do_newfs_prefix(); if (error) return error; error = udf_do_rootdir(); if (error) return error; error = udf_do_newfs_postfix(); return error; } /* --------------------------------------------------------------------- */ static void usage(void) { (void)fprintf(stderr, "Usage: %s [-cFM] [-L loglabel] " "[-P discid] [-S sectorsize] [-s size] [-p perc] " "[-t gmtoff] [-v min_udf] [-V max_udf] special\n", getprogname()); exit(EXIT_FAILURE); } int main(int argc, char **argv) { struct tm *tm; struct stat st; time_t now; off_t setsize; char scrap[255], *colon; int ch, req_enable, req_disable, force; int error; setprogname(argv[0]); /* initialise */ format_str = strdup(""); req_enable = req_disable = 0; format_flags = FORMAT_INVALID; force = 0; check_surface = 0; setsize = 0; imagefile_secsize = 512; /* minimum allowed sector size */ emul_packetsize = 32; /* reasonable default */ srandom((unsigned long) time(NULL)); udf_init_create_context(); context.app_name = "*NetBSD newfs"; context.app_version_main = APP_VERSION_MAIN; context.app_version_sub = APP_VERSION_SUB; context.impl_name = IMPL_NAME; /* minimum and maximum UDF versions we advise */ context.min_udf = 0x201; context.max_udf = 0x201; /* use user's time zone as default */ (void)time(&now); tm = localtime(&now); context.gmtoff = tm->tm_gmtoff; /* process options */ while ((ch = getopt(argc, argv, "cFL:Mp:P:s:S:B:t:v:V:")) != -1) { switch (ch) { case 'c' : check_surface = 1; break; case 'F' : force = 1; break; case 'L' : if (context.logvol_name) free(context.logvol_name); context.logvol_name = strdup(optarg); break; case 'M' : req_disable |= FORMAT_META; break; case 'p' : meta_perc = a_num(optarg, "meta_perc"); /* limit to `sensible` values */ meta_perc = MIN(meta_perc, 99); meta_perc = MAX(meta_perc, 1); meta_fract = (float) meta_perc/100.0; break; case 'v' : context.min_udf = a_udf_version(optarg, "min_udf"); if (context.min_udf > context.max_udf) context.max_udf = context.min_udf; break; case 'V' : context.max_udf = a_udf_version(optarg, "max_udf"); if (context.min_udf > context.max_udf) context.min_udf = context.max_udf; break; case 'P' : /* check if there is a ':' in the name */ if ((colon = strstr(optarg, ":"))) { if (context.volset_name) free(context.volset_name); *colon = 0; context.volset_name = strdup(optarg); optarg = colon+1; } if (context.primary_name) free(context.primary_name); if ((strstr(optarg, ":"))) { perror("primary name can't have ':' in its name"); return EXIT_FAILURE; } context.primary_name = strdup(optarg); break; case 's' : /* support for files, set file size */ /* XXX support for formatting recordables on vnd/file? */ if (dehumanize_number(optarg, &setsize) < 0) { perror("can't parse size argument"); return EXIT_FAILURE; } setsize = MAX(0, setsize); break; case 'S' : imagefile_secsize = a_num(optarg, "secsize"); imagefile_secsize = MAX(512, imagefile_secsize); break; case 'B' : emul_packetsize = a_num(optarg, "blockingnr, packetsize"); emul_packetsize = MAX(emul_packetsize, 1); emul_packetsize = MIN(emul_packetsize, 32); break; case 't' : /* time zone override */ context.gmtoff = a_num(optarg, "gmtoff"); break; default : usage(); /* NOTREACHED */ } } if (optind + 1 != argc) usage(); /* get device and directory specifier */ dev = argv[optind]; /* open device */ if ((fd = open(dev, O_RDWR, 0)) == -1) { /* check if we need to create a file */ fd = open(dev, O_RDONLY, 0); if (fd > 0) { perror("device is there but can't be opened for read/write"); return EXIT_FAILURE; } if (!force) { perror("can't open device"); return EXIT_FAILURE; } if (setsize == 0) { perror("need to create image file but no size specified"); return EXIT_FAILURE; } /* need to create a file */ fd = open(dev, O_RDWR | O_CREAT | O_TRUNC, 0777); if (fd == -1) { perror("can't create image file"); return EXIT_FAILURE; } } /* stat the device */ if (fstat(fd, &st) != 0) { perror("can't stat the device"); close(fd); return EXIT_FAILURE; } if (S_ISREG(st.st_mode)) { if (setsize == 0) setsize = st.st_size; /* sanitise arguments */ imagefile_secsize &= ~511; setsize &= ~(imagefile_secsize-1); if (ftruncate(fd, setsize)) { perror("can't resize file"); return EXIT_FAILURE; } } /* formatting can only be done on raw devices */ if (!S_ISREG(st.st_mode) && !S_ISCHR(st.st_mode)) { printf("%s is not a raw device\n", dev); close(fd); return EXIT_FAILURE; } /* just in case something went wrong, synchronise the drive's cache */ udf_synchronise_caches(); /* get 'disc' information */ error = udf_update_discinfo(&mmc_discinfo); if (error) { perror("can't retrieve discinfo"); close(fd); return EXIT_FAILURE; } /* derive disc identifiers when not specified and check given */ error = udf_proces_names(); if (error) { /* error message has been printed */ close(fd); return EXIT_FAILURE; } /* derive newfs disc format from disc profile */ error = udf_derive_format(req_enable, req_disable, force); if (error) { /* error message has been printed */ close(fd); return EXIT_FAILURE; } udf_dump_discinfo(&mmc_discinfo); printf("Formatting disc compatible with UDF version %x to %x\n\n", context.min_udf, context.max_udf); /* (void)snprintb(scrap, sizeof(scrap), FORMAT_FLAGBITS, (uint64_t) format_flags);*/ printf("UDF properties %s\n", scrap); printf("Volume set `%s'\n", context.volset_name); printf("Primary volume `%s`\n", context.primary_name); printf("Logical volume `%s`\n", context.logvol_name); if (format_flags & FORMAT_META) printf("Metadata percentage %d %%\n", meta_perc); printf("\n"); /* prepare disc if necessary (recordables mainly) */ error = udf_prepare_disc(); if (error) { perror("preparing disc failed"); close(fd); return EXIT_FAILURE; }; /* setup sector writeout queue's */ TAILQ_INIT(&write_queue); /* perform the newfs itself */ error = udf_do_newfs(); if (!error) { /* write out sectors */ error = writeout_write_queue(); } /* in any case, synchronise the drive's cache to prevent lockups */ udf_synchronise_caches(); close(fd); if (error) return EXIT_FAILURE; return EXIT_SUCCESS; } /* --------------------------------------------------------------------- */
154286.c
/* ** EPITECH PROJECT, 2021 ** my_put_nbr ** File description: ** displays the number given as a parameter. */ #include <unistd.h> void my_putchar(char c) { write(1, &c, 1); } int my_put_nbr(int nb) { unsigned int nbr; if (nb < 0) { write(1, "-", 1); nbr = -nb; } else { nbr = nb; } if (nbr >= 10) { my_put_nbr(nbr / 10); } my_putchar(nbr % 10 + '0'); return (0); }
84114.c
/*------------------------------------------------------------------------- * * ipci.c * POSTGRES inter-process communication initialization code. * * Portions Copyright (c) 1996-2019, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California * * * IDENTIFICATION * src/backend/storage/ipc/ipci.c * *------------------------------------------------------------------------- */ #include "postgres.h" #include "access/clog.h" #include "access/commit_ts.h" #include "access/heapam.h" #include "access/multixact.h" #include "access/nbtree.h" #include "access/subtrans.h" #include "access/twophase.h" #include "commands/async.h" #include "miscadmin.h" #include "pgstat.h" #include "postmaster/autovacuum.h" #include "postmaster/bgworker_internals.h" #include "postmaster/bgwriter.h" #include "postmaster/postmaster.h" #include "replication/logicallauncher.h" #include "replication/slot.h" #include "replication/walreceiver.h" #include "replication/walsender.h" #include "replication/origin.h" #include "storage/bufmgr.h" #include "storage/dsm.h" #include "storage/ipc.h" #include "storage/pg_shmem.h" #include "storage/pmsignal.h" #include "storage/predicate.h" #include "storage/proc.h" #include "storage/procarray.h" #include "storage/procsignal.h" #include "storage/sinvaladt.h" #include "storage/spin.h" #include "utils/snapmgr.h" /* GUCs */ int shared_memory_type = DEFAULT_SHARED_MEMORY_TYPE; shmem_startup_hook_type shmem_startup_hook = NULL; static Size total_addin_request = 0; static bool addin_request_allowed = true; /* * RequestAddinShmemSpace * Request that extra shmem space be allocated for use by * a loadable module. * * This is only useful if called from the _PG_init hook of a library that * is loaded into the postmaster via shared_preload_libraries. Once * shared memory has been allocated, calls will be ignored. (We could * raise an error, but it seems better to make it a no-op, so that * libraries containing such calls can be reloaded if needed.) */ void RequestAddinShmemSpace(Size size) { if (IsUnderPostmaster || !addin_request_allowed) return; /* too late */ total_addin_request = add_size(total_addin_request, size); } /* * CreateSharedMemoryAndSemaphores * Creates and initializes shared memory and semaphores. * * This is called by the postmaster or by a standalone backend. * It is also called by a backend forked from the postmaster in the * EXEC_BACKEND case. In the latter case, the shared memory segment * already exists and has been physically attached to, but we have to * initialize pointers in local memory that reference the shared structures, * because we didn't inherit the correct pointer values from the postmaster * as we do in the fork() scenario. The easiest way to do that is to run * through the same code as before. (Note that the called routines mostly * check IsUnderPostmaster, rather than EXEC_BACKEND, to detect this case. * This is a bit code-wasteful and could be cleaned up.) */ void CreateSharedMemoryAndSemaphores(int port) { PGShmemHeader *shim = NULL; if (!IsUnderPostmaster) { PGShmemHeader *seghdr; Size size; int numSemas; /* Compute number of semaphores we'll need */ numSemas = ProcGlobalSemas(); // numSemas=126 MaxBackends=122 NUM_AUXILIARY_PROCS=4 numSemas += SpinlockSemas(); // numSemas=126 /* * Size of the Postgres shared-memory block is estimated via * moderately-accurate estimates for the big hogs, plus 100K for the * stuff that's too small to bother with estimating. * * We take some care during this phase to ensure that the total size * request doesn't overflow size_t. If this gets through, we don't * need to be so careful during the actual allocation phase. */ size = 100000; size = add_size(size, PGSemaphoreShmemSize(numSemas)); size = add_size(size, SpinlockSemaSize()); size = add_size(size, hash_estimate_size(SHMEM_INDEX_SIZE, sizeof(ShmemIndexEnt))); size = add_size(size, BufferShmemSize()); size = add_size(size, LockShmemSize()); size = add_size(size, PredicateLockShmemSize()); size = add_size(size, ProcGlobalShmemSize()); size = add_size(size, XLOGShmemSize()); size = add_size(size, CLOGShmemSize()); size = add_size(size, CommitTsShmemSize()); size = add_size(size, SUBTRANSShmemSize()); size = add_size(size, TwoPhaseShmemSize()); size = add_size(size, BackgroundWorkerShmemSize()); size = add_size(size, MultiXactShmemSize()); size = add_size(size, LWLockShmemSize()); size = add_size(size, ProcArrayShmemSize()); size = add_size(size, BackendStatusShmemSize()); size = add_size(size, SInvalShmemSize()); size = add_size(size, PMSignalShmemSize()); size = add_size(size, ProcSignalShmemSize()); size = add_size(size, CheckpointerShmemSize()); size = add_size(size, AutoVacuumShmemSize()); size = add_size(size, ReplicationSlotsShmemSize()); size = add_size(size, ReplicationOriginShmemSize()); size = add_size(size, WalSndShmemSize()); size = add_size(size, WalRcvShmemSize()); size = add_size(size, ApplyLauncherShmemSize()); size = add_size(size, SnapMgrShmemSize()); size = add_size(size, BTreeShmemSize()); size = add_size(size, SyncScanShmemSize()); size = add_size(size, AsyncShmemSize()); #ifdef EXEC_BACKEND size = add_size(size, ShmemBackendArraySize()); #endif /* freeze the addin request size and include it */ addin_request_allowed = false; size = add_size(size, total_addin_request); /* might as well round it off to a multiple of a typical page size */ size = add_size(size, 8192 - (size % 8192)); elog(DEBUG3, "invoking IpcMemoryCreate(size=%zu)", size); /* * Create the shmem segment */ seghdr = PGSharedMemoryCreate(size, port, &shim); InitShmemAccess(seghdr); /* * Create semaphores,从共享内存中申请 126*128长度的空间; 每个信号量长度为128byte */ PGReserveSemaphores(numSemas, port); /* * If spinlocks are disabled, initialize emulation layer (which * depends on semaphores, so the order is important here). */ #ifndef HAVE_SPINLOCKS SpinlockSemaInit(); #endif } else { /* * We are reattaching to an existing shared memory segment. This * should only be reached in the EXEC_BACKEND case. */ #ifndef EXEC_BACKEND elog(PANIC, "should be attached to shared memory already"); #endif } /* * Set up shared memory allocation mechanism */ if (!IsUnderPostmaster) InitShmemAllocation(); /* * Now initialize LWLocks, which do shared memory allocation and are * needed for InitShmemIndex. */ CreateLWLocks(); /* * Set up shmem.c index hashtable */ InitShmemIndex(); /* * Set up xlog, clog, and buffers */ XLOGShmemInit(); CLOGShmemInit(); CommitTsShmemInit(); SUBTRANSShmemInit(); MultiXactShmemInit(); InitBufferPool(); /* * Set up lock manager */ InitLocks(); /* * Set up predicate lock manager */ InitPredicateLocks(); /* * Set up process table */ if (!IsUnderPostmaster) InitProcGlobal(); CreateSharedProcArray(); CreateSharedBackendStatus(); TwoPhaseShmemInit(); BackgroundWorkerShmemInit(); /* * Set up shared-inval messaging */ CreateSharedInvalidationState(); /* * Set up interprocess signaling mechanisms */ PMSignalShmemInit(); ProcSignalShmemInit(); CheckpointerShmemInit(); AutoVacuumShmemInit(); ReplicationSlotsShmemInit(); ReplicationOriginShmemInit(); WalSndShmemInit(); WalRcvShmemInit(); ApplyLauncherShmemInit(); /* * Set up other modules that need some shared memory space */ SnapMgrInit(); BTreeShmemInit(); SyncScanShmemInit(); AsyncShmemInit(); #ifdef EXEC_BACKEND /* * Alloc the win32 shared backend array */ if (!IsUnderPostmaster) ShmemBackendArrayAllocation(); #endif /* Initialize dynamic shared memory facilities. */ if (!IsUnderPostmaster) dsm_postmaster_startup(shim); /* * Now give loadable modules a chance to set up their shmem allocations */ if (shmem_startup_hook) shmem_startup_hook(); }
794470.c
/* slarfp.f -- translated by f2c (version 20061008). You must link the resulting object file with libf2c: on Microsoft Windows system, link with libf2c.lib; on Linux or Unix systems, link with .../path/to/libf2c.a -lm or, if you install libf2c.a in a standard place, with -lf2c -lm -- in that order, at the end of the command line, as in cc *.o -lf2c -lm Source for libf2c is in /netlib/f2c/libf2c.zip, e.g., http://www.netlib.org/f2c/libf2c.zip */ #include "clapack.h" /* Subroutine */ int slarfp_(integer *n, real *alpha, real *x, integer *incx, real *tau) { /* System generated locals */ integer i__1; real r__1; /* Builtin functions */ double r_sign(real *, real *); /* Local variables */ integer j, knt; real beta; extern doublereal snrm2_(integer *, real *, integer *); extern /* Subroutine */ int sscal_(integer *, real *, real *, integer *); real xnorm; extern doublereal slapy2_(real *, real *), slamch_(char *); real safmin, rsafmn; /* -- LAPACK auxiliary routine (version 3.2) -- */ /* Univ. of Tennessee, Univ. of California Berkeley and NAG Ltd.. */ /* November 2006 */ /* .. Scalar Arguments .. */ /* .. */ /* .. Array Arguments .. */ /* .. */ /* Purpose */ /* ======= */ /* SLARFP generates a real elementary reflector H of order n, such */ /* that */ /* H * ( alpha ) = ( beta ), H' * H = I. */ /* ( x ) ( 0 ) */ /* where alpha and beta are scalars, beta is non-negative, and x is */ /* an (n-1)-element real vector. H is represented in the form */ /* H = I - tau * ( 1 ) * ( 1 v' ) , */ /* ( v ) */ /* where tau is a real scalar and v is a real (n-1)-element */ /* vector. */ /* If the elements of x are all zero, then tau = 0 and H is taken to be */ /* the unit matrix. */ /* Otherwise 1 <= tau <= 2. */ /* Arguments */ /* ========= */ /* N (input) INTEGER */ /* The order of the elementary reflector. */ /* ALPHA (input/output) REAL */ /* On entry, the value alpha. */ /* On exit, it is overwritten with the value beta. */ /* X (input/output) REAL array, dimension */ /* (1+(N-2)*abs(INCX)) */ /* On entry, the vector x. */ /* On exit, it is overwritten with the vector v. */ /* INCX (input) INTEGER */ /* The increment between elements of X. INCX > 0. */ /* TAU (output) REAL */ /* The value tau. */ /* ===================================================================== */ /* .. Parameters .. */ /* .. */ /* .. Local Scalars .. */ /* .. */ /* .. External Functions .. */ /* .. */ /* .. Intrinsic Functions .. */ /* .. */ /* .. External Subroutines .. */ /* .. */ /* .. Executable Statements .. */ /* Parameter adjustments */ --x; /* Function Body */ if (*n <= 0) { *tau = 0.f; return 0; } i__1 = *n - 1; xnorm = snrm2_(&i__1, &x[1], incx); if (xnorm == 0.f) { /* H = [+/-1, 0; I], sign chosen so ALPHA >= 0. */ if (*alpha >= 0.f) { /* When TAU.eq.ZERO, the vector is special-cased to be */ /* all zeros in the application routines. We do not need */ /* to clear it. */ *tau = 0.f; } else { /* However, the application routines rely on explicit */ /* zero checks when TAU.ne.ZERO, and we must clear X. */ *tau = 2.f; i__1 = *n - 1; for (j = 1; j <= i__1; ++j) { x[(j - 1) * *incx + 1] = 0.f; } *alpha = -(*alpha); } } else { /* general case */ r__1 = slapy2_(alpha, &xnorm); beta = r_sign(&r__1, alpha); safmin = slamch_("S") / slamch_("E"); knt = 0; if (dabs(beta) < safmin) { /* XNORM, BETA may be inaccurate; scale X and recompute them */ rsafmn = 1.f / safmin; L10: ++knt; i__1 = *n - 1; sscal_(&i__1, &rsafmn, &x[1], incx); beta *= rsafmn; *alpha *= rsafmn; if (dabs(beta) < safmin) { goto L10; } /* New BETA is at most 1, at least SAFMIN */ i__1 = *n - 1; xnorm = snrm2_(&i__1, &x[1], incx); r__1 = slapy2_(alpha, &xnorm); beta = r_sign(&r__1, alpha); } *alpha += beta; if (beta < 0.f) { beta = -beta; *tau = -(*alpha) / beta; } else { *alpha = xnorm * (xnorm / *alpha); *tau = *alpha / beta; *alpha = -(*alpha); } i__1 = *n - 1; r__1 = 1.f / *alpha; sscal_(&i__1, &r__1, &x[1], incx); /* If BETA is subnormal, it may lose relative accuracy */ i__1 = knt; for (j = 1; j <= i__1; ++j) { beta *= safmin; /* L20: */ } *alpha = beta; } return 0; /* End of SLARFP */ } /* slarfp_ */
172648.c
// SPDX-License-Identifier: GPL-2.0-or-later /* * Universal Flash Storage Host controller PCI glue driver * * This code is based on drivers/scsi/ufs/ufshcd-pci.c * Copyright (C) 2011-2013 Samsung India Software Operations * * Authors: * Santosh Yaraganavi <[email protected]> * Vinayak Holikatti <[email protected]> */ #include "ufshcd.h" #include <linux/pci.h> #include <linux/pm_runtime.h> #include <linux/pm_qos.h> #include <linux/debugfs.h> struct intel_host { u32 active_ltr; u32 idle_ltr; struct dentry *debugfs_root; }; static int ufs_intel_disable_lcc(struct ufs_hba *hba) { u32 attr = UIC_ARG_MIB(PA_LOCAL_TX_LCC_ENABLE); u32 lcc_enable = 0; ufshcd_dme_get(hba, attr, &lcc_enable); if (lcc_enable) ufshcd_disable_host_tx_lcc(hba); return 0; } static int ufs_intel_link_startup_notify(struct ufs_hba *hba, enum ufs_notify_change_status status) { int err = 0; switch (status) { case PRE_CHANGE: err = ufs_intel_disable_lcc(hba); break; case POST_CHANGE: break; default: break; } return err; } #define INTEL_ACTIVELTR 0x804 #define INTEL_IDLELTR 0x808 #define INTEL_LTR_REQ BIT(15) #define INTEL_LTR_SCALE_MASK GENMASK(11, 10) #define INTEL_LTR_SCALE_1US (2 << 10) #define INTEL_LTR_SCALE_32US (3 << 10) #define INTEL_LTR_VALUE_MASK GENMASK(9, 0) static void intel_cache_ltr(struct ufs_hba *hba) { struct intel_host *host = ufshcd_get_variant(hba); host->active_ltr = readl(hba->mmio_base + INTEL_ACTIVELTR); host->idle_ltr = readl(hba->mmio_base + INTEL_IDLELTR); } static void intel_ltr_set(struct device *dev, s32 val) { struct ufs_hba *hba = dev_get_drvdata(dev); struct intel_host *host = ufshcd_get_variant(hba); u32 ltr; pm_runtime_get_sync(dev); /* * Program latency tolerance (LTR) accordingly what has been asked * by the PM QoS layer or disable it in case we were passed * negative value or PM_QOS_LATENCY_ANY. */ ltr = readl(hba->mmio_base + INTEL_ACTIVELTR); if (val == PM_QOS_LATENCY_ANY || val < 0) { ltr &= ~INTEL_LTR_REQ; } else { ltr |= INTEL_LTR_REQ; ltr &= ~INTEL_LTR_SCALE_MASK; ltr &= ~INTEL_LTR_VALUE_MASK; if (val > INTEL_LTR_VALUE_MASK) { val >>= 5; if (val > INTEL_LTR_VALUE_MASK) val = INTEL_LTR_VALUE_MASK; ltr |= INTEL_LTR_SCALE_32US | val; } else { ltr |= INTEL_LTR_SCALE_1US | val; } } if (ltr == host->active_ltr) goto out; writel(ltr, hba->mmio_base + INTEL_ACTIVELTR); writel(ltr, hba->mmio_base + INTEL_IDLELTR); /* Cache the values into intel_host structure */ intel_cache_ltr(hba); out: pm_runtime_put(dev); } static void intel_ltr_expose(struct device *dev) { dev->power.set_latency_tolerance = intel_ltr_set; dev_pm_qos_expose_latency_tolerance(dev); } static void intel_ltr_hide(struct device *dev) { dev_pm_qos_hide_latency_tolerance(dev); dev->power.set_latency_tolerance = NULL; } static void intel_add_debugfs(struct ufs_hba *hba) { struct dentry *dir = debugfs_create_dir(dev_name(hba->dev), NULL); struct intel_host *host = ufshcd_get_variant(hba); intel_cache_ltr(hba); host->debugfs_root = dir; debugfs_create_x32("active_ltr", 0444, dir, &host->active_ltr); debugfs_create_x32("idle_ltr", 0444, dir, &host->idle_ltr); } static void intel_remove_debugfs(struct ufs_hba *hba) { struct intel_host *host = ufshcd_get_variant(hba); debugfs_remove_recursive(host->debugfs_root); } static int ufs_intel_common_init(struct ufs_hba *hba) { struct intel_host *host; hba->caps |= UFSHCD_CAP_RPM_AUTOSUSPEND; host = devm_kzalloc(hba->dev, sizeof(*host), GFP_KERNEL); if (!host) return -ENOMEM; ufshcd_set_variant(hba, host); intel_ltr_expose(hba->dev); intel_add_debugfs(hba); return 0; } static void ufs_intel_common_exit(struct ufs_hba *hba) { intel_remove_debugfs(hba); intel_ltr_hide(hba->dev); } static int ufs_intel_resume(struct ufs_hba *hba, enum ufs_pm_op op) { /* * To support S4 (suspend-to-disk) with spm_lvl other than 5, the base * address registers must be restored because the restore kernel can * have used different addresses. */ ufshcd_writel(hba, lower_32_bits(hba->utrdl_dma_addr), REG_UTP_TRANSFER_REQ_LIST_BASE_L); ufshcd_writel(hba, upper_32_bits(hba->utrdl_dma_addr), REG_UTP_TRANSFER_REQ_LIST_BASE_H); ufshcd_writel(hba, lower_32_bits(hba->utmrdl_dma_addr), REG_UTP_TASK_REQ_LIST_BASE_L); ufshcd_writel(hba, upper_32_bits(hba->utmrdl_dma_addr), REG_UTP_TASK_REQ_LIST_BASE_H); if (ufshcd_is_link_hibern8(hba)) { int ret = ufshcd_uic_hibern8_exit(hba); if (!ret) { ufshcd_set_link_active(hba); } else { dev_err(hba->dev, "%s: hibern8 exit failed %d\n", __func__, ret); /* * Force reset and restore. Any other actions can lead * to an unrecoverable state. */ ufshcd_set_link_off(hba); } } return 0; } static int ufs_intel_ehl_init(struct ufs_hba *hba) { hba->quirks |= UFSHCD_QUIRK_BROKEN_AUTO_HIBERN8; return ufs_intel_common_init(hba); } static struct ufs_hba_variant_ops ufs_intel_cnl_hba_vops = { .name = "intel-pci", .init = ufs_intel_common_init, .exit = ufs_intel_common_exit, .link_startup_notify = ufs_intel_link_startup_notify, .resume = ufs_intel_resume, }; static struct ufs_hba_variant_ops ufs_intel_ehl_hba_vops = { .name = "intel-pci", .init = ufs_intel_ehl_init, .exit = ufs_intel_common_exit, .link_startup_notify = ufs_intel_link_startup_notify, .resume = ufs_intel_resume, }; #ifdef CONFIG_PM_SLEEP /** * ufshcd_pci_suspend - suspend power management function * @dev: pointer to PCI device handle * * Returns 0 if successful * Returns non-zero otherwise */ static int ufshcd_pci_suspend(struct device *dev) { return ufshcd_system_suspend(dev_get_drvdata(dev)); } /** * ufshcd_pci_resume - resume power management function * @dev: pointer to PCI device handle * * Returns 0 if successful * Returns non-zero otherwise */ static int ufshcd_pci_resume(struct device *dev) { return ufshcd_system_resume(dev_get_drvdata(dev)); } /** * ufshcd_pci_poweroff - suspend-to-disk poweroff function * @dev: pointer to PCI device handle * * Returns 0 if successful * Returns non-zero otherwise */ static int ufshcd_pci_poweroff(struct device *dev) { struct ufs_hba *hba = dev_get_drvdata(dev); int spm_lvl = hba->spm_lvl; int ret; /* * For poweroff we need to set the UFS device to PowerDown mode. * Force spm_lvl to ensure that. */ hba->spm_lvl = 5; ret = ufshcd_system_suspend(hba); hba->spm_lvl = spm_lvl; return ret; } #endif /* !CONFIG_PM_SLEEP */ #ifdef CONFIG_PM static int ufshcd_pci_runtime_suspend(struct device *dev) { return ufshcd_runtime_suspend(dev_get_drvdata(dev)); } static int ufshcd_pci_runtime_resume(struct device *dev) { return ufshcd_runtime_resume(dev_get_drvdata(dev)); } static int ufshcd_pci_runtime_idle(struct device *dev) { return ufshcd_runtime_idle(dev_get_drvdata(dev)); } #endif /* !CONFIG_PM */ /** * ufshcd_pci_shutdown - main function to put the controller in reset state * @pdev: pointer to PCI device handle */ static void ufshcd_pci_shutdown(struct pci_dev *pdev) { ufshcd_shutdown((struct ufs_hba *)pci_get_drvdata(pdev)); } /** * ufshcd_pci_remove - de-allocate PCI/SCSI host and host memory space * data structure memory * @pdev: pointer to PCI handle */ static void ufshcd_pci_remove(struct pci_dev *pdev) { struct ufs_hba *hba = pci_get_drvdata(pdev); pm_runtime_forbid(&pdev->dev); pm_runtime_get_noresume(&pdev->dev); ufshcd_remove(hba); ufshcd_dealloc_host(hba); } /** * ufshcd_pci_probe - probe routine of the driver * @pdev: pointer to PCI device handle * @id: PCI device id * * Returns 0 on success, non-zero value on failure */ static int ufshcd_pci_probe(struct pci_dev *pdev, const struct pci_device_id *id) { struct ufs_hba *hba; void __iomem *mmio_base; int err; err = pcim_enable_device(pdev); if (err) { dev_err(&pdev->dev, "pcim_enable_device failed\n"); return err; } pci_set_master(pdev); err = pcim_iomap_regions(pdev, 1 << 0, UFSHCD); if (err < 0) { dev_err(&pdev->dev, "request and iomap failed\n"); return err; } mmio_base = pcim_iomap_table(pdev)[0]; err = ufshcd_alloc_host(&pdev->dev, &hba); if (err) { dev_err(&pdev->dev, "Allocation failed\n"); return err; } pci_set_drvdata(pdev, hba); hba->vops = (struct ufs_hba_variant_ops *)id->driver_data; err = ufshcd_init(hba, mmio_base, pdev->irq); if (err) { dev_err(&pdev->dev, "Initialization failed\n"); ufshcd_dealloc_host(hba); return err; } pm_runtime_put_noidle(&pdev->dev); pm_runtime_allow(&pdev->dev); return 0; } static const struct dev_pm_ops ufshcd_pci_pm_ops = { #ifdef CONFIG_PM_SLEEP .suspend = ufshcd_pci_suspend, .resume = ufshcd_pci_resume, .freeze = ufshcd_pci_suspend, .thaw = ufshcd_pci_resume, .poweroff = ufshcd_pci_poweroff, .restore = ufshcd_pci_resume, #endif SET_RUNTIME_PM_OPS(ufshcd_pci_runtime_suspend, ufshcd_pci_runtime_resume, ufshcd_pci_runtime_idle) }; static const struct pci_device_id ufshcd_pci_tbl[] = { { PCI_VENDOR_ID_SAMSUNG, 0xC00C, PCI_ANY_ID, PCI_ANY_ID, 0, 0, 0 }, { PCI_VDEVICE(INTEL, 0x9DFA), (kernel_ulong_t)&ufs_intel_cnl_hba_vops }, { PCI_VDEVICE(INTEL, 0x4B41), (kernel_ulong_t)&ufs_intel_ehl_hba_vops }, { PCI_VDEVICE(INTEL, 0x4B43), (kernel_ulong_t)&ufs_intel_ehl_hba_vops }, { } /* terminate list */ }; MODULE_DEVICE_TABLE(pci, ufshcd_pci_tbl); static struct pci_driver ufshcd_pci_driver = { .name = UFSHCD, .id_table = ufshcd_pci_tbl, .probe = ufshcd_pci_probe, .remove = ufshcd_pci_remove, .shutdown = ufshcd_pci_shutdown, .driver = { .pm = &ufshcd_pci_pm_ops }, }; module_pci_driver(ufshcd_pci_driver); MODULE_AUTHOR("Santosh Yaragnavi <[email protected]>"); MODULE_AUTHOR("Vinayak Holikatti <[email protected]>"); MODULE_DESCRIPTION("UFS host controller PCI glue driver"); MODULE_LICENSE("GPL"); MODULE_VERSION(UFSHCD_DRIVER_VERSION);
614889.c
/* * Test for null proc handling with blocking routines */ #include <stdio.h> #include "mpi.h" #if defined(NEEDS_STDLIB_PROTOTYPES) #include "protofix.h" #endif int main( int argc, char *argv[] ) { int a[4]; int i, nproc; int rank, right, left; MPI_Status st[2], sts[2]; MPI_Request req[2]; int count, errcnt = 0; /* start up */ MPI_Init(&argc, &argv); MPI_Comm_size(MPI_COMM_WORLD, &nproc); MPI_Comm_rank(MPI_COMM_WORLD, &rank); /* set up processor chain (Apps should use Cart_create/shift) */ left = (rank == 0) ? MPI_PROC_NULL : rank - 1; right = (rank == nproc - 1) ? MPI_PROC_NULL : rank + 1; /* initialize local matrix */ /* globally: a[i] = i, i = 1 .. 2*nproc */ /* locally : a[i] = 2*rank+i, i=1,2 */ a[0] = -1; a[1] = 2*rank + 1; a[2] = 2*rank + 2; a[3] = -1; /* start all receives and sends */ MPI_Isend(&a[1], 1, MPI_INT, left, 0, MPI_COMM_WORLD, &req[0]); MPI_Isend(&a[2], 1, MPI_INT, right, 1, MPI_COMM_WORLD, &req[1]); st[0].MPI_SOURCE = nproc; st[0].MPI_TAG = -1; st[1].MPI_SOURCE = nproc; st[1].MPI_TAG = -1; MPI_Recv(&a[0], 1, MPI_INT, left, 1, MPI_COMM_WORLD, &st[0]); MPI_Recv(&a[3], 1, MPI_INT, right, 0, MPI_COMM_WORLD, &st[1]); MPI_Waitall( 2, req, sts ); /* Test the end points */ if (left == MPI_PROC_NULL) { if (st[0].MPI_TAG != MPI_ANY_TAG || st[0].MPI_SOURCE != MPI_PROC_NULL) { errcnt ++; fprintf( stderr, "Incorrect null status for left\n" ); if (st[0].MPI_SOURCE != MPI_PROC_NULL) { fprintf( stderr, "Source returned was %d but should be %d\n", st[0].MPI_SOURCE, MPI_PROC_NULL ); } } MPI_Get_count( &st[0], MPI_INT, &count ); if (count != 0) { errcnt ++; fprintf( stderr, "Incorrect null status for left (count)\n" ); fprintf( stderr, "Count was %d but should be 0\n", count ); } } else if (right == MPI_PROC_NULL) { if (st[1].MPI_TAG != MPI_ANY_TAG || st[1].MPI_SOURCE != MPI_PROC_NULL) { errcnt ++; fprintf( stderr, "Incorrect null status for right\n" ); if (st[1].MPI_SOURCE != MPI_PROC_NULL) { fprintf( stderr, "Source returned was %d but should be %d\n", st[1].MPI_SOURCE, MPI_PROC_NULL ); } } MPI_Get_count( &st[1], MPI_INT, &count ); if (count != 0) { errcnt ++; fprintf( stderr, "Incorrect null status for right (count)\n" ); fprintf( stderr, "Count was %d but should be 0\n", count ); } } /* Test results */ if (left == MPI_PROC_NULL) { if (a[0] != -1) { fprintf( stderr, "Expected -1, found %d in left partner\n", a[0] ); errcnt ++; } } else { if (a[0] != 2 * left + 2) { fprintf( stderr, "Expected %d, found %d in left partner\n", 2 * left + 2, a[0] ); errcnt ++; } } if (right == MPI_PROC_NULL) { if (a[3] != -1) { fprintf( stderr, "Expected -1, found %d in right partner\n", a[3] ); errcnt ++; } } else { if (a[3] != 2 * right + 1) { fprintf( stderr, "Expected %d, found %d in right partner\n", 2 * right + 1, a[3] ); errcnt ++; } } i = errcnt; MPI_Allreduce( &i, &errcnt, 1, MPI_INT, MPI_SUM, MPI_COMM_WORLD ); if (rank == 0) { if (errcnt > 0) { printf( "Found %d errors in the run \n", errcnt ); } else printf( "No errors in handling MPI_PROC_NULL\n" ); } /* clean up */ MPI_Finalize(); return 0; }
193086.c
// Copyright 2018-2019 Espressif Systems (Shanghai) PTE 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. #include "dsps_fft2r.h" #include "dsp_common.h" #include "dsp_types.h" #include <math.h> int16_t* dsps_fft_w_table_sc16; int dsps_fft_w_table_sc16_size; uint8_t dsps_fft2r_sc16_initialized = 0; uint8_t dsps_fft2r_sc16_mem_allocated = 0; static const int add_rount_mult = 0x7fff; static const int mult_shift_const = 0x7fff; // Used to shift data << 15 static inline int16_t xtfixed_bf_1(int16_t a0, int16_t a1, int16_t a2, int16_t a3, int16_t a4, int result_shift) { int result = a0*mult_shift_const; result -= (int32_t)a1*(int32_t)a2 + (int32_t)a3*(int32_t)a4; result += add_rount_mult; result = result >> result_shift; return (int16_t)result; } static inline int16_t xtfixed_bf_2(int16_t a0, int16_t a1, int16_t a2, int16_t a3, int16_t a4, int result_shift) { int result = a0 *mult_shift_const; result -= ((int32_t)a1*(int32_t)a2 - (int32_t)a3*(int32_t)a4); result += add_rount_mult; result = result >> result_shift; return (int16_t)result; } static inline int16_t xtfixed_bf_3(int16_t a0, int16_t a1, int16_t a2, int16_t a3, int16_t a4, int result_shift) { int result = a0 *mult_shift_const; result += (int32_t)a1*(int32_t)a2 + (int32_t)a3*(int32_t)a4; result += add_rount_mult; result = result >> result_shift; return (int16_t)result; } static inline int16_t xtfixed_bf_4(int16_t a0, int16_t a1, int16_t a2, int16_t a3, int16_t a4, int result_shift) { int result = a0 *mult_shift_const; result += (int32_t)a1*(int32_t)a2 - (int32_t)a3*(int32_t)a4; result += add_rount_mult; result = result >> result_shift; return (int16_t)result; } esp_err_t dsps_fft2r_init_sc16(int16_t* fft_table_buff, int table_size) { esp_err_t result = ESP_OK; if (dsps_fft2r_sc16_initialized != 0) { return result; } if (table_size > CONFIG_DSP_MAX_FFT_SIZE) { return ESP_ERR_DSP_PARAM_OUTOFRANGE; } if (table_size == 0){ return result; } if (fft_table_buff != NULL) { if (dsps_fft2r_sc16_mem_allocated) { return ESP_ERR_DSP_REINITIALIZED; } dsps_fft_w_table_sc16 = fft_table_buff; dsps_fft_w_table_sc16_size = table_size; } else { if (!dsps_fft2r_sc16_mem_allocated) { dsps_fft_w_table_sc16 = (int16_t*)malloc(CONFIG_DSP_MAX_FFT_SIZE*sizeof(int16_t)); } dsps_fft_w_table_size = CONFIG_DSP_MAX_FFT_SIZE; dsps_fft2r_sc16_mem_allocated = 1; } result = dsps_gen_w_r2_sc16(dsps_fft_w_table_sc16, CONFIG_DSP_MAX_FFT_SIZE); if (result != ESP_OK) { return result; } result = dsps_bit_rev_sc16_ansi(dsps_fft_w_table_sc16, CONFIG_DSP_MAX_FFT_SIZE >> 1); if (result != ESP_OK) { return result; } dsps_fft2r_sc16_initialized = 1; return ESP_OK; } void dsps_fft2r_deinit_sc16() { if (dsps_fft2r_sc16_mem_allocated) { free(dsps_fft_w_table_sc16); } dsps_fft2r_sc16_mem_allocated = 0; dsps_fft2r_sc16_initialized = 0; } esp_err_t dsps_fft2r_sc16_ansi(int16_t *data, int N) { if (!dsp_is_power_of_two(N)) { return ESP_ERR_DSP_INVALID_LENGTH; } if (!dsps_fft2r_sc16_initialized) { return ESP_ERR_DSP_UNINITIALIZED; } esp_err_t result = ESP_OK; uint32_t *w = (uint32_t*)dsps_fft_w_table_sc16; uint32_t *in_data = (uint32_t *)data; int ie, ia, m; sc16_t cs;// c - re, s - im sc16_t m_data; sc16_t a_data; ie = 1; for (int N2 = N / 2; N2 > 0; N2 >>= 1) { ia = 0; for (int j = 0; j < ie; j++) { cs.data = w[j]; //c = w[2 * j]; //s = w[2 * j + 1]; for (int i = 0; i < N2; i++) { m = ia + N2; m_data.data = in_data[m]; a_data.data = in_data[ia]; //data[2 * m] = data[2 * ia] - re_temp; //data[2 * m + 1] = data[2 * ia + 1] - im_temp; sc16_t m1; m1.re = xtfixed_bf_1(a_data.re, cs.re, m_data.re, cs.im, m_data.im, 16);//(a_data.re - temp.re + shift_const) >> 1; m1.im = xtfixed_bf_2(a_data.im, cs.re, m_data.im, cs.im, m_data.re, 16);//(a_data.im - temp.im + shift_const) >> 1; in_data[m] = m1.data; //data[2 * ia] = data[2 * ia] + re_temp; //data[2 * ia + 1] = data[2 * ia + 1] + im_temp; sc16_t m2; m2.re = xtfixed_bf_3(a_data.re, cs.re, m_data.re, cs.im, m_data.im, 16);//(a_data.re + temp.re + shift_const) >> 1; m2.im = xtfixed_bf_4(a_data.im, cs.re, m_data.im, cs.im, m_data.re, 16);//(a_data.im + temp.im + shift_const)>>1; in_data[ia] = m2.data; ia++; } ia += N2; } ie <<= 1; } return result; } static inline unsigned short reverse_sc16(unsigned short x, unsigned short N, int order) { unsigned short b = x; b = (b & 0xff00) >> 8 | (b & 0x00fF) << 8; b = (b & 0xf0F0) >> 4 | (b & 0x0f0F) << 4; b = (b & 0xCCCC) >> 2 | (b & 0x3333) << 2; b = (b & 0xAAAA) >> 1 | (b & 0x5555) << 1; return b >> (16 - order); } esp_err_t dsps_bit_rev_sc16_ansi(int16_t *data, int N) { if (!dsp_is_power_of_two(N)) { return ESP_ERR_DSP_INVALID_LENGTH; } esp_err_t result = ESP_OK; int j, k; uint32_t temp; uint32_t* in_data = (uint32_t*)data; j = 0; for (int i = 1; i < (N - 1); i++) { k = N >> 1; while (k <= j) { j -= k; k >>= 1; } j += k; if (i < j) { temp = in_data[j]; in_data[j] = in_data[i]; in_data[i] = temp; } } return result; } esp_err_t dsps_gen_w_r2_sc16(int16_t *w, int N) { if (!dsp_is_power_of_two(N)) { return ESP_ERR_DSP_INVALID_LENGTH; } esp_err_t result = ESP_OK; int i; float e = M_PI * 2.0 / N; for (i = 0; i < (N >> 1); i++) { w[2 * i] = (int16_t)(INT16_MAX * cosf(i * e)); w[2 * i + 1] = (int16_t)(INT16_MAX * sinf(i * e)); } return result; } esp_err_t dsps_cplx2reC_sc16(int16_t *data, int N) { if (!dsp_is_power_of_two(N)) { return ESP_ERR_DSP_INVALID_LENGTH; } esp_err_t result = ESP_OK; int i; int n2 = N << (1 + 1); // we will operate with int32 indexes uint32_t* in_data = (uint32_t*)data; sc16_t kl; sc16_t kh; sc16_t nl; sc16_t nh; for (i = 0; i < (N / 4); i++) { kl.data = in_data[i + 1]; nl.data = in_data[n2 - i - 1]; kh.data = in_data[i + 1 + N/2]; nh.data = data[n2 - i - 1 - N/2]; data[i * 2 + 0 + 2] = kl.re + nl.re; data[i * 2 + 1 + 2] = kl.im - nl.im; data[n2 - i * 2 - 1 - N] = kh.re + nh.re; data[n2 - i * 2 - 2 - N] = kh.im - nh.im; data[i * 2 + 0 + 2 + N] = kl.im + nl.im; data[i * 2 + 1 + 2 + N] = kl.re - nl.re; data[n2 - i * 2 - 1] = kh.im + nh.im; data[n2 - i * 2 - 2] = kh.re - nh.re; } data[N] = data[1]; data[1] = 0; data[N + 1] = 0; return result; }
64452.c
/* cpg - 5/20/02 - with parts borrowed from gm.c and tcpip.c */ /* i need to close connections properly, so the crserver can exit, etc. */ /* -- broker disconnects through the mothership? */ /* -- crTeacDoDisconnect is wrong, but it's not even getting called */ /* at the moment; the client application just quits */ /****************************************************** * Notes- * -Is CR_TEAC_BUFFER_PAD 16? ******************************************************/ #define CR_TEAC_COPY_MSGS_TO_MAIN_MEMORY 1 #define CR_TEAC_USE_RECV_THREAD 0 #include <unistd.h> #include <limits.h> #include <stdlib.h> #include <stdio.h> #include <errno.h> #include <sys/socket.h> #include <netinet/in.h> #include <netinet/tcp.h> #include <arpa/inet.h> #include <netdb.h> #include <string.h> #if CR_TEAC_USE_RECV_THREAD #include <pthread.h> #endif #include "teac.h" #include "cr_error.h" #include "cr_mem.h" #include "cr_string.h" #include "cr_net.h" #include "cr_endian.h" #include "net_internals.h" #if ( CR_TEAC_USE_RECV_THREAD && ! CHROMIUM_THREADSAFE ) #error "Teac configuration error: USE_RECV_THREAD requires CHROMIUM_THREADSAFE" #endif #if ( CR_TEAC_USE_RECV_THREAD && ! CR_TEAC_COPY_MSGS_TO_MAIN_MEMORY ) #error "Teac configuration error: USE_RECV_THREAD requires CR_TEAC_COPY_MSGS_TO_MAIN_MEMORY!" #endif #ifdef never #define CR_TEAC_SEND_CREDITS_THRESHOLD ( 1 << 18 ) #endif #define CR_TEAC_SEND_CREDITS_THRESHOLD ( 1 << 16 ) /* some random bits. Last must be 0 */ #define CR_TEAC_BUFFER_MAGIC 0x7b52e9e0 /* There must be 16 or fewer of these; they get packed into the * bottom 4 bits of a word containing CR_TEAC_BUFFER_MAGIC. */ typedef enum { CR_TEAC_KIND_SEND, CR_TEAC_KIND_FLOW_SEND, CR_TEAC_KIND_RECV, CR_TEAC_KIND_FLOW_RECV, CR_TEAC_KIND_RECV_LISTED } CRTeacBufferKind; typedef struct CRTeacConnection { CRConnection *conn; struct CRTeacConnection *credit_prev; struct CRTeacConnection *credit_next; struct CRTeacBuffer *incoming_head; struct CRTeacBuffer *incoming_tail; #ifdef CHROMIUM_THREADSAFE CRmutex msgListMutex; #endif } CRTeacConnection; /* The union in the following struct gets forced to length 8, to * make sure there are no size ambiguities when passing between * architectures with 32bit and 64bit pointers. */ typedef struct CRTeacBuffer { unsigned int magic; int len; /* used only with CR_TEAC_KIND_RECV_LISTED msgs */ union { SBuffer* sendBuffer; RBuffer* rcvBuffer; struct CRTeacBuffer* incoming_next; char filler[8]; /* force size of union to 8 */ } u; } CRTeacBuffer; #define CR_TEAC_BUFFER_PAD sizeof(CRTeacBuffer) static struct { int initialized; int num_conns; CRNetReceiveFuncList *recv_list; CRNetCloseFuncList *close_list; CRTeacConnection *credit_head; CRTeacConnection *credit_tail; unsigned int inside_recv; void *tcomm; char my_hostname[256]; int my_rank; int low_context; int high_context; char *low_node; char *high_node; unsigned char key[TEAC_KEY_SIZE]; #ifdef CHROMIUM_THREADSAFE CRmutex teacAPIMutex; pthread_t recvThread; #endif } cr_teac; /* Forward declarations */ void *crTeacAlloc( CRConnection * ); void crTeacFree( CRConnection *, void * ); int crTeacErrno( void ); char* crTeacErrorString( int err ); void crTeacInstantReclaim( CRConnection *conn, CRMessage *msg ); void crTeacSend( CRConnection *conn, void **bufp, const void *start, unsigned int len ); CRConnection *crTeacSelect( void ); void crTeacAccept( CRConnection *conn, const char *hostname, unsigned short port ); int crTeacDoConnect( CRConnection *conn ); void crTeacDoDisconnect( CRConnection *conn ); void crTeacHandleNewMessage( CRConnection *conn, CRMessage *msg, unsigned int len ); void crTeacSingleRecv( CRConnection *conn, void *buf, unsigned int len ); void crTeacSendExact( CRConnection *conn, const void *buf, unsigned int len ); int crTeacRecv( void ); static CRTeacConnection *crTeacConnectionLookup( int teac_id ); void* crTeacRecvThread( void* args ); int crTeacErrno( void ) { int err = errno; errno = 0; return err; } char * crTeacErrorString( int err ) { static char buf[512], *temp; temp = strerror( err ); if ( temp ) { crStrncpy( buf, temp, sizeof(buf)-1 ); } else { sprintf( buf, "err=%d", err ); } return buf; } static void crTeacCreditIncrease( CRTeacConnection *teac_conn ) { CRTeacConnection *parent; int my_credits; /* move this node up the doubly-linked, if it isn't already in the * right position */ parent = teac_conn->credit_prev; my_credits = teac_conn->conn->recv_credits; if ( parent && parent->conn->recv_credits < my_credits ) { /* we can't be at the head of the list, because our parent is * non-NULL */ /* are we the tail of the list? */ if ( cr_teac.credit_tail == teac_conn ) { /* yes, pull up the tail pointer, and fix our parent to be tail */ cr_teac.credit_tail = parent; parent->credit_next = NULL; } else { /* no, just link around us */ parent->credit_next = teac_conn->credit_next; teac_conn->credit_next->credit_prev = parent; } /* walk up the list until we find a guy with more credits than * us or we reach the head */ while ( parent && parent->conn->recv_credits < my_credits ) { parent = parent->credit_prev; } /* reinsert us -- we know there is somebody else in the list * (and thus we won't be the tail, because we moved up), * otherwise we would have been the head, and never bothered * trying to move ourself */ if ( parent ) { CRTeacConnection *child = parent->credit_next; teac_conn->credit_next = child; child->credit_prev = teac_conn; parent->credit_next = teac_conn; teac_conn->credit_prev = parent; } else { CRTeacConnection *child = cr_teac.credit_head; teac_conn->credit_next = child; child->credit_prev = teac_conn; cr_teac.credit_head = teac_conn; teac_conn->credit_prev = NULL; } } } static void crTeacCreditZero( CRTeacConnection *teac_conn ) { CRASSERT( cr_teac.credit_head == teac_conn ); /* if we aren't already at the tail of the list, */ if ( cr_teac.credit_tail != teac_conn ) { /* then pull us off the head, */ cr_teac.credit_head = teac_conn->credit_next; cr_teac.credit_head->credit_prev = NULL; /* and put us on the tail */ cr_teac.credit_tail->credit_next = teac_conn; teac_conn->credit_prev = cr_teac.credit_tail; teac_conn->credit_next = NULL; cr_teac.credit_tail = teac_conn; } } #if CR_TEAC_USE_RECV_THREAD void* crTeacRecvThread( void* args ) { crDebug("crTeacRecvThread: starting listener thread."); while (1) { CRConnection* conn = crTeacSelect( ); if ( conn ) { RBuffer* rbuf= NULL; CRTeacBuffer* teacMsg= NULL; CRTeacBuffer* cloneMsg= NULL; CRTeacConnection* teac_conn= crTeacConnectionLookup( conn->teac_id ); #ifdef never crDebug("crTeacRecvThread: beginning with allocation sizes %ld, %ld", ((Tcomm*)cr_teac.tcomm)->totalSendBufferBytesAllocated, ((Tcomm*)cr_teac.tcomm)->totalRecvBufferBytesAllocated); crDebug("crTeacRecvThread: entering teac_Recv on id %d", conn->teac_id); #endif #ifdef CHROMIUM_THREADSAFE crLockMutex(&cr_teac.teacAPIMutex); #endif rbuf = teac_Recv( cr_teac.tcomm, conn->teac_id ); #ifdef CHROMIUM_THREADSAFE crUnlockMutex(&cr_teac.teacAPIMutex); #endif #ifdef never crDebug("crTeacRecvThread: finished teac_Recv on id %d; got RBuffer at 0x%x", conn->teac_id,(int)rbuf); #endif if ( !rbuf ) { crError( "crTeacRecvThread: teac_Recv( teac_id=%d ) failed", conn->teac_id ); } teacMsg= (CRTeacBuffer*)(rbuf->buf); #ifdef never crDebug("crTeacRecvThread: new msg from teac_id %d is %ld bytes, at %lx", conn->teac_id, rbuf->totSize,(long)(teacMsg+1)); #endif teacMsg->magic= (CR_TEAC_BUFFER_MAGIC | (int)CR_TEAC_KIND_RECV); teacMsg->u.rcvBuffer= rbuf; cloneMsg= (CRTeacBuffer*)crAlloc(rbuf->validSize); crMemcpy( cloneMsg, teacMsg, rbuf->validSize ); cloneMsg->magic= (CR_TEAC_BUFFER_MAGIC | (int)CR_TEAC_KIND_RECV_LISTED); /* len field must be valid for LISTED messages */ cloneMsg->len= rbuf->validSize - CR_TEAC_BUFFER_PAD; cloneMsg->u.incoming_next= NULL; crLockMutex(&(teac_conn->msgListMutex)); if (teac_conn->incoming_tail) { teac_conn->incoming_tail->u.incoming_next= cloneMsg; teac_conn->incoming_tail= cloneMsg; } else { /* This is the first in the list */ teac_conn->incoming_head= teac_conn->incoming_tail= cloneMsg; } crUnlockMutex(&(teac_conn->msgListMutex)); crTeacFree(conn,(CRMessage*)(teacMsg+1)); /* frees original message */ #ifdef never crDebug("crTeacRecvThread: appended new msg to incoming at %lx, len %d", (long)(cloneMsg+1), cloneMsg->len); #endif } else { /* Let's try just spinning */ #ifdef never sched_yield(); #endif } } (void)args; return NULL; } #endif static void crTeacAddConnection( CRConnection *conn ) { CRTeacConnection *teac_conn = crAlloc( sizeof( CRTeacConnection ) ); CRASSERT( teac_conn ); teac_conn->conn = conn; teac_conn->credit_next = NULL; #ifdef CHROMIUM_THREADSAFE crInitMutex(&(teac_conn->msgListMutex)); #endif teac_conn->incoming_head= teac_conn->incoming_tail= NULL; if ( cr_teac.credit_head ) { teac_conn->credit_prev = cr_teac.credit_tail; cr_teac.credit_tail->credit_next = teac_conn; cr_teac.credit_tail = teac_conn; } else { teac_conn->credit_prev = NULL; cr_teac.credit_head = teac_conn; cr_teac.credit_tail = teac_conn; #if CR_TEAC_USE_RECV_THREAD /* First incoming teac connection, so start the receiver thread */ #ifdef never pthread_init(); #endif crDebug("crTeacAddConnection: about to start listener thread"); pthread_create(&cr_teac.recvThread, NULL, crTeacRecvThread, NULL); pthread_detach(cr_teac.recvThread); #endif } crTeacCreditIncrease( teac_conn ); } static void crTeacSendCredits( CRConnection *conn ) { CRTeacBuffer *buf = NULL; SBuffer *sbuf = NULL; CRMessageFlowControl *msg = NULL; CRASSERT( conn->recv_credits > 0 ); if (teac_sendBufferAvailable(cr_teac.tcomm)) { #ifdef never crDebug( "crTeacSendCredits: sending %d credits to %s:%d, id %d", conn->recv_credits, conn->hostname, conn->teac_rank, conn->teac_id); #endif #ifdef CHROMIUM_THREADSAFE crLockMutex(&cr_teac.teacAPIMutex); #endif sbuf= teac_getSendBuffer( cr_teac.tcomm, CR_TEAC_BUFFER_PAD + conn->mtu ); #ifdef CHROMIUM_THREADSAFE crUnlockMutex(&cr_teac.teacAPIMutex); #endif buf = (CRTeacBuffer*) sbuf->buf; buf->magic= (CR_TEAC_BUFFER_MAGIC | (int)CR_TEAC_KIND_FLOW_SEND); buf->len= 0; /* not used for this msg type */ buf->u.sendBuffer= sbuf; sbuf->validSize = CR_TEAC_BUFFER_PAD; *((SBuffer **) buf ) = sbuf; msg = (CRMessageFlowControl *)( buf+1 ); msg->header.type = CR_MESSAGE_FLOW_CONTROL; msg->header.conn_id = conn->id; msg->credits = conn->recv_credits; sbuf->validSize += sizeof( CRMessageFlowControl ); conn->send_credits -= sbuf->validSize; #ifdef CHROMIUM_THREADSAFE crLockMutex(&cr_teac.teacAPIMutex); #endif teac_Send( cr_teac.tcomm, &(conn->teac_id), 1, sbuf, buf ); #ifdef CHROMIUM_THREADSAFE crUnlockMutex(&cr_teac.teacAPIMutex); #endif conn->recv_credits = 0; #ifdef never crDebug( "crTeacSendCredits: sent credits to %s:%d", conn->hostname, conn->teac_rank ); #endif } else { #ifdef never crDebug( "crTeacSendCredits: no buffer; deferring sending to %s:%d, id %d", conn->hostname, conn->teac_rank, conn->teac_id); #endif } } static void crTeacMaybeSendCredits( void ) { if ( cr_teac.credit_head && cr_teac.credit_head->conn->recv_credits >= CR_TEAC_SEND_CREDITS_THRESHOLD ) { crTeacSendCredits( cr_teac.credit_head->conn ); crTeacCreditZero( cr_teac.credit_head ); } } static void crTeacWaitForSendCredits( CRConnection *conn ) { #ifdef never crDebug( "crTeacWaitForSendCredits: waiting for credits " "to talk to %s:%d (total=%d)", conn->hostname, conn->teac_rank, conn->send_credits ); #endif while ( conn->send_credits <= 0 ) { crTeacRecv( ); } #ifdef never crDebug( "crTeacWaitForSendCredits: found credits " "to talk to %s:%d (total=%d)", conn->hostname, conn->teac_rank, conn->send_credits ); #endif } static CRTeacConnection * crTeacConnectionLookup( int teac_id ) { CRTeacConnection *teac_conn = cr_teac.credit_head; CRConnection *conn = NULL; while ( teac_conn ) { conn = teac_conn->conn; if ( conn->teac_id == teac_id ) return teac_conn; teac_conn = teac_conn->credit_next; } return NULL; } void * crTeacAlloc( CRConnection *conn ) { SBuffer *sbuf = NULL; CRTeacBuffer *buf = NULL; CRMessage* msg= NULL; #ifdef CHROMIUM_THREADSAFE crLockMutex(&cr_teac.teacAPIMutex); #endif sbuf= teac_getUnreadySendBuffer( cr_teac.tcomm, CR_TEAC_BUFFER_PAD + conn->mtu ); #ifdef CHROMIUM_THREADSAFE crUnlockMutex(&cr_teac.teacAPIMutex); #endif buf = (CRTeacBuffer*) sbuf->buf; buf->magic= (CR_TEAC_BUFFER_MAGIC | CR_TEAC_KIND_SEND); buf->len= 0; /* not used for this msg type */ buf->u.sendBuffer= sbuf; sbuf->validSize = CR_TEAC_BUFFER_PAD; msg = (CRMessage *)( buf+1 ); msg->header.conn_id = conn->id; #ifdef never crDebug("crTeacAlloc: sizes %ld, %ld; alloc %d at %lx", ((Tcomm*)cr_teac.tcomm)->totalSendBufferBytesAllocated, ((Tcomm*)cr_teac.tcomm)->totalRecvBufferBytesAllocated, CR_TEAC_BUFFER_PAD + conn->mtu,(long)msg); #endif return (void *)msg; } void crTeacFree( CRConnection *conn, void *buf ) { CRMessage* msg= (CRMessage*)buf; CRTeacBuffer* teacBuf= ((CRTeacBuffer*)msg) - 1; CRTeacBufferKind kind= (CRTeacBufferKind)(teacBuf->magic & 0xF); switch (kind) { case CR_TEAC_KIND_RECV: { RBuffer* rbuf= teacBuf->u.rcvBuffer; conn->recv_credits += rbuf->validSize; #ifdef never crDebug("crTeacFree: sizes %ld, %ld; freeing %ld at %lx", ((Tcomm*)cr_teac.tcomm)->totalSendBufferBytesAllocated, ((Tcomm*)cr_teac.tcomm)->totalRecvBufferBytesAllocated, (rbuf->totSize),(long)msg); crDebug( "crTeacFree: freeing RBuffer at 0x%x from buffer 0x%x", (int)rbuf,(int)buf); #endif #ifdef CHROMIUM_THREADSAFE crLockMutex(&cr_teac.teacAPIMutex); #endif teac_Dispose( cr_teac.tcomm, rbuf ); #ifdef CHROMIUM_THREADSAFE crUnlockMutex(&cr_teac.teacAPIMutex); #endif crTeacCreditIncrease( crTeacConnectionLookup( conn->teac_id ) ); } break; case CR_TEAC_KIND_RECV_LISTED: { crFree(teacBuf); } break; case CR_TEAC_KIND_FLOW_RECV: { RBuffer* rbuf= teacBuf->u.rcvBuffer; conn->recv_credits += rbuf->validSize; crWarning("crTeacFree: misplaced CR_TEAC_KIND_FLOW_RECV message; freeing"); #ifdef CHROMIUM_THREADSAFE crLockMutex(&cr_teac.teacAPIMutex); #endif teac_Dispose( cr_teac.tcomm, rbuf ); #ifdef CHROMIUM_THREADSAFE crUnlockMutex(&cr_teac.teacAPIMutex); #endif } break; case CR_TEAC_KIND_SEND: { crWarning("crTeacFree: misplaced CR_TEAC_KIND_SEND message; losing it!"); } break; case CR_TEAC_KIND_FLOW_SEND: { crWarning("crTeacFree: misplaced CR_TEAC_KIND_FLOW_SEND message; losing it!"); } break; } } void crTeacInstantReclaim( CRConnection *conn, CRMessage *msg ) { /* Do nothing- message will be freed after dispatching in crTeacRecv() */ #ifdef never crDebug("crTeacInstantReclaim: got %d credits from %s:%d", ((CRMessageFlowControl*)msg)->credits, conn->hostname,conn->teac_rank); #endif } void crTeacSend( CRConnection *conn, void **bufp, const void *start, unsigned int len ) { CRMessage *buf = NULL; CRTeacBuffer* teacBuf= NULL; SBuffer *sbuf; CRTeacBufferKind kind; #ifdef never crDebug("crTeacSend: beginning with allocation sizes %ld, %ld", ((Tcomm*)cr_teac.tcomm)->totalSendBufferBytesAllocated, ((Tcomm*)cr_teac.tcomm)->totalRecvBufferBytesAllocated); #endif if ( cr_teac.inside_recv ) crError( "crTeacSend: cannot be called with crTeacRecv" ); while ( crTeacRecv( ) ) ; if ( conn->send_credits <= 0 ) crTeacWaitForSendCredits( conn ); if ( bufp == NULL ) { buf = (CRMessage*) crTeacAlloc( conn ); crMemcpy( (void*)buf, start, len ); } else { buf = (CRMessage *)( *bufp ); } teacBuf= ((CRTeacBuffer*)buf)-1; kind= (CRTeacBufferKind)(teacBuf->magic & 0xF); if (kind != CR_TEAC_KIND_SEND) crError("crTeacSend: someone passed me a buffer of type %d!",kind); sbuf = teacBuf->u.sendBuffer; sbuf->validSize += len; conn->send_credits -= sbuf->validSize; crDebug("crTeacSend: entering send block to %d, msg type %d", conn->teac_id,(((CRMessage*)start)->header.type-CR_MESSAGE_OPCODES)); #if CR_TEAC_USE_RECV_THREAD while (!teac_sendBufferAvailable(cr_teac.tcomm)) { /* Let's try just spinning */ #ifdef never sched_yield(); /* let recieve thread run while we wait */ #endif } #endif #ifdef never crDebug("crTeacSend: entering makeSendBufferReady to %d, msg type %d", conn->teac_id,(((CRMessage*)start)->header.type-CR_MESSAGE_OPCODES)); #endif #ifdef CHROMIUM_THREADSAFE crLockMutex(&cr_teac.teacAPIMutex); #endif sbuf= teac_makeSendBufferReady( cr_teac.tcomm, sbuf ); #ifdef never crDebug("crTeacSend: Sending to id %d",conn->teac_id ); #endif if (bufp==NULL) teac_Send( cr_teac.tcomm, &(conn->teac_id), 1, sbuf, teacBuf ); else teac_Send( cr_teac.tcomm, &(conn->teac_id), 1, sbuf, (void *)((char *) start - CR_TEAC_BUFFER_PAD ) ); #ifdef CHROMIUM_THREADSAFE crUnlockMutex(&cr_teac.teacAPIMutex); #endif #ifdef never crDebug("crTeacSend: finished Send of msg type %d to %d; loc %lx", (((CRMessage*)start)->header.type-CR_MESSAGE_OPCODES), conn->teac_id, (long)buf); #endif /* I have the sense that we're supposed to set *bufp to NULL here, * but doing so breaks things. */ } CRConnection * crTeacSelect( void ) { int count = 0; int *teac_ids = crAlloc( sizeof( int ) * cr_teac.num_conns ); int ready_id = -1; CRTeacConnection *teac_conn = NULL; /* Build a list of currently valid teac_ids */ teac_conn = cr_teac.credit_head; while ( teac_conn ) { teac_ids[count] = teac_conn->conn->teac_id; count++; teac_conn = teac_conn->credit_next; } /* Poll the connections */ #ifdef CHROMIUM_THREADSAFE crLockMutex(&cr_teac.teacAPIMutex); #endif ready_id = teac_Poll( cr_teac.tcomm, teac_ids, count ); #ifdef CHROMIUM_THREADSAFE crUnlockMutex(&cr_teac.teacAPIMutex); #endif crFree(teac_ids); if ( ready_id == -1 ) return NULL; /* Search for the connection with the proper teac_id */ teac_conn = crTeacConnectionLookup( ready_id ); if ( teac_conn ) { #ifdef never crDebug( "crTeacSelect: teac_id=%d has data available", teac_conn->conn->teac_id ); #endif return teac_conn->conn; } return NULL; } int crTeacRecv( void ) { CRConnection *conn = NULL; RBuffer *rbuf = NULL; CRMessage* msg= NULL; CRTeacConnection *teac_conn= NULL; CRTeacBuffer* teacMsg= NULL; CRTeacBuffer* cloneMsg= NULL; int len = 0; cr_teac.inside_recv++; crTeacMaybeSendCredits( ); #if CR_TEAC_USE_RECV_THREAD teac_conn= cr_teac.credit_head; teacMsg= NULL; while (teac_conn ) { if (teac_conn->incoming_head) { /* This connection has at least one incoming message */ crLockMutex(&(teac_conn->msgListMutex)); teacMsg= teac_conn->incoming_head; teac_conn->incoming_head= teacMsg->u.incoming_next; if (teac_conn->incoming_tail==teacMsg) teac_conn->incoming_tail= NULL; crUnlockMutex(&(teac_conn->msgListMutex)); msg= (CRMessage*)(teacMsg+1); len= teacMsg->len; conn= teac_conn->conn; crDebug("crTeacRecv: popped msg from incoming at %lx, length %d", (long)msg, len); break; } teac_conn= teac_conn->credit_next; } if (!teacMsg) { cr_teac.inside_recv--; return 0; } #else conn = crTeacSelect( ); if ( !conn ) { cr_teac.inside_recv--; return 0; } #ifdef never crDebug("crTeacRecv: beginning with allocation sizes %ld, %ld", ((Tcomm*)cr_teac.tcomm)->totalSendBufferBytesAllocated, ((Tcomm*)cr_teac.tcomm)->totalRecvBufferBytesAllocated); crDebug("crTeacRecv: entering teac_Recv on id %d", conn->teac_id); #endif #ifdef CHROMIUM_THREADSAFE crLockMutex(&cr_teac.teacAPIMutex); #endif rbuf = teac_Recv( cr_teac.tcomm, conn->teac_id ); #ifdef CHROMIUM_THREADSAFE crUnlockMutex(&cr_teac.teacAPIMutex); #endif #ifdef never crDebug("crTeacRecv: finished teac_Recv on id %d; got RBuffer at 0x%x", conn->teac_id,(int)rbuf); #endif if ( !rbuf ) { crError( "crTeacRecv: teac_Recv( teac_id=%d ) failed", conn->teac_id ); } teacMsg= (CRTeacBuffer*)(rbuf->buf); msg= (CRMessage*)(teacMsg+1); len = rbuf->validSize - CR_TEAC_BUFFER_PAD; #ifdef never crDebug("crTeacRecv: new msg from teac_id %d is %ld bytes, type %d, at %lx", conn->teac_id, rbuf->totSize, (int)(msg->header.type-CR_MESSAGE_OPCODES),(long)msg); #endif teacMsg->magic= (CR_TEAC_BUFFER_MAGIC | (int)CR_TEAC_KIND_RECV); teacMsg->u.rcvBuffer= rbuf; #if CR_TEAC_COPY_MSGS_TO_MAIN_MEMORY cloneMsg= (CRTeacBuffer*)crAlloc(rbuf->validSize); crMemcpy( cloneMsg, teacMsg, rbuf->validSize ); cloneMsg->magic= (CR_TEAC_BUFFER_MAGIC | (int)CR_TEAC_KIND_RECV_LISTED); cloneMsg->len= len; /* valid for LISTED messages */ cloneMsg->u.rcvBuffer= NULL; crTeacFree(conn,msg); /* frees original message */ msg= (CRMessage*)(cloneMsg+1); /* Leave the clone in its place */ #endif #endif crNetDispatchMessage( cr_teac.recv_list, conn, msg, len ); /* CR_MESSAGE_OPCODES is freed in * crserverlib/server_stream.c * * OOB messages are the programmer's problem. -- Humper 12/17/01 */ if (msg->header.type != CR_MESSAGE_OPCODES && msg->header.type != CR_MESSAGE_OOB) { crTeacFree( conn, msg ); } cr_teac.inside_recv--; return 1; } void crTeacInit( CRNetReceiveFuncList *rfl, CRNetCloseFuncList *cfl, unsigned int mtu ) { (void) mtu; cr_teac.recv_list = rfl; cr_teac.close_list = cfl; int i; long key_sum= 0; if ( cr_teac.initialized ) { return; } if ( crGetHostname( cr_teac.my_hostname, sizeof( cr_teac.my_hostname ) ) ) { crError( "crTeacInit: couldn't determine my own hostname!" ); } strtok( cr_teac.my_hostname, "." ); if ((cr_teac.low_node==NULL) || (cr_teac.high_node==NULL)) { crError( "crTeacInit: node range is not set!" ); } #ifdef CHROMIUM_THREADSAFE crInitMutex(&cr_teac.teacAPIMutex); cr_teac.recvThread= (pthread_t)0; #endif key_sum= 0; for (i=0; i<(int)sizeof(cr_teac.key); i++) key_sum += cr_teac.key[i]; if (key_sum==0) /* key not initialized */ crStrncpy((char*)&(cr_teac.key), "This is pretty random!", sizeof(cr_teac.key)); #ifdef CHROMIUM_THREADSAFE crLockMutex(&cr_teac.teacAPIMutex); #endif cr_teac.tcomm = teac_Init( cr_teac.low_node, cr_teac.high_node, cr_teac.low_context, cr_teac.high_context, cr_teac.my_rank, cr_teac.key ); #ifdef CHROMIUM_THREADSAFE crUnlockMutex(&cr_teac.teacAPIMutex); #endif if ( !cr_teac.tcomm ) crError( "crTeacInit: teac_Init( %d, %d, %d ) failed", cr_teac.low_context, cr_teac.high_context, cr_teac.my_rank ); cr_teac.num_conns = 0; cr_teac.credit_head = NULL; cr_teac.credit_tail = NULL; cr_teac.inside_recv = 0; cr_teac.initialized = 1; } void crTeacAccept( CRConnection *conn, const char *hostname, unsigned short port ) { CRConnection *mother; char response[8096]; char client_hostname[256]; int client_rank; int client_endianness; crDebug( "crTeacAccept is being called -- " "brokering the connection through the mothership!." ); mother = __copy_of_crMothershipConnect( ); /* Tell the mothership I'm willing to receive a client, and what my Teac info is */ if (!__copy_of_crMothershipSendString( mother, response, "acceptrequest quadrics %s %d %d", cr_teac.my_hostname, cr_teac.my_rank, conn->endianness ) ) { crError( "crTeacAccept: Mothership didn't like my accept request" ); } /* The response will contain the Teac information for the guy who accepted * this connection. The mothership will sit on the acceptrequest * until someone connects. */ sscanf( response, "%d %s %d %d", &(conn->id), client_hostname, &(client_rank), &(client_endianness) ); /* deal with endianness here */ conn->hostname = crStrdup(client_hostname); conn->teac_rank = client_rank; crDebug( "crTeacAccept: opening connection to %s:%d", conn->hostname, conn->teac_rank ); #ifdef CHROMIUM_THREADSAFE crLockMutex(&cr_teac.teacAPIMutex); #endif conn->teac_id = teac_getConnId( cr_teac.tcomm, conn->hostname, conn->teac_rank ); #ifdef CHROMIUM_THREADSAFE crUnlockMutex(&cr_teac.teacAPIMutex); #endif if ( conn->teac_id < 0 ) { crError( "crTeacAccept: couldn't establish an Teac connection with %s:%d", conn->hostname, conn->teac_rank ); } crDebug( "crTeacAccept: connection to %s:%d has teac_id=%d\n", conn->hostname, conn->teac_rank, conn->teac_id ); /* NOW, we can add the connection, since we have enough information * to uniquely determine the sender when we get a packet! */ crTeacAddConnection( conn ); __copy_of_crMothershipDisconnect( mother ); (void) port; } /* The function that actually connects. This should only be called by clients * Servers have another way to set up the connection. */ int crTeacDoConnect( CRConnection *conn ) { CRConnection *mother; char response[8096]; int server_endianness; crDebug( "crTeacDoConnect is being called -- " "brokering the connection through the mothership!" ); mother = __copy_of_crMothershipConnect( ); /* Tell the mothership who I want to connect to, and what my Teac info is */ if (!__copy_of_crMothershipSendString( mother, response, "connectrequest quadrics %s %d %s %d %d", conn->hostname, conn->teac_rank, cr_teac.my_hostname, cr_teac.my_rank, conn->endianness ) ) { crError( "crTeacDoConnect: Mothership didn't like my connect request" ); } /* The response will contain the Teac information for the guy who accepted * this connection. The mothership will sit on the connectrequest * until someone accepts. */ sscanf( response, "%d %d", &(conn->id), &(server_endianness) ); /* deal with endianness here */ crDebug( "crTeacDoConnect: opening connection to %s:%d", conn->hostname, conn->teac_rank ); #ifdef CHROMIUM_THREADSAFE crLockMutex(&cr_teac.teacAPIMutex); #endif conn->teac_id = teac_getConnId( cr_teac.tcomm, conn->hostname, conn->teac_rank ); #ifdef CHROMIUM_THREADSAFE crUnlockMutex(&cr_teac.teacAPIMutex); #endif if ( conn->teac_id < 0 ) { crError( "crTeacDoConnect: couldn't establish an Teac connection with %s:%d", conn->hostname, conn->teac_rank ); } crDebug( "crTeacDoConnect: connection to %s:%d has teac_id=%d\n", conn->hostname, conn->teac_rank, conn->teac_id ); /* NOW, we can add the connection, since we have enough information * to uniquely determine the sender when we get a packet! */ crTeacAddConnection( conn ); __copy_of_crMothershipDisconnect( mother ); return 1; } void crTeacDoDisconnect( CRConnection *conn ) { crDebug( "crTeacCloseConnection: shutting down Teac" ); #ifdef CHROMIUM_THREADSAFE crLockMutex(&cr_teac.teacAPIMutex); #endif teac_Close( cr_teac.tcomm ); #ifdef CHROMIUM_THREADSAFE crUnlockMutex(&cr_teac.teacAPIMutex); #endif crNetCallCloseCallbacks(conn); } void crTeacHandleNewMessage( CRConnection *conn, CRMessage *msg, unsigned int len ) { crError( "crTeacHandleNewMessage should not get called." ); (void) conn; (void) msg; (void) len; } void crTeacSingleRecv( CRConnection *conn, void *buf, unsigned int len ) { crError( "crTeacSingleRecv should not get called." ); (void) conn; (void) buf; (void) len; } void crTeacSendExact( CRConnection *conn, const void *buf, unsigned int len ) { crError( "crTeacSendExact should not get called." ); (void) conn; (void) buf; (void) len; } void crTeacConnection( CRConnection *conn ) { CRASSERT( cr_teac.initialized ); conn->type = CR_TEAC; conn->Alloc = crTeacAlloc; conn->Send = crTeacSend; conn->SendExact = crTeacSendExact; conn->Recv = crTeacSingleRecv; conn->Free = crTeacFree; conn->Accept = crTeacAccept; conn->Connect = crTeacDoConnect; conn->Disconnect = crTeacDoDisconnect; conn->InstantReclaim = crTeacInstantReclaim; conn->HandleNewMessage = crTeacHandleNewMessage; conn->index = cr_teac.num_conns; conn->sizeof_buffer_header = sizeof( CRTeacBuffer ); conn->actual_network = 1; cr_teac.num_conns++; } void crTeacSetRank( int rank ) { cr_teac.my_rank = rank; } void crTeacSetContextRange( int low_context, int high_context ) { cr_teac.low_context = low_context; cr_teac.high_context = high_context; crDebug( "crTeacSetContextRange: using contexts %d-%d", cr_teac.low_context, cr_teac.high_context ); } void crTeacSetNodeRange( const char *low_node, const char *high_node ) { char* low= crStrdup( low_node ); char* high= crStrdup( high_node ); cr_teac.low_node = strtok( low, "'" ); cr_teac.high_node = strtok( high, "'" ); crDebug( "crTeacSetNodeRange: low node=%s, high node=%s", cr_teac.low_node, cr_teac.high_node ); } void crTeacSetKey( const unsigned char* key, const int keyLength ) { int i; char msgbuf[3*TEAC_KEY_SIZE+1]; char* runner= msgbuf; int bytesToCopy= (keyLength<TEAC_KEY_SIZE)?keyLength:TEAC_KEY_SIZE; crMemcpy(&(cr_teac.key),key,bytesToCopy); for (i=0; i<TEAC_KEY_SIZE; i++) { sprintf(runner,"%02x,",cr_teac.key[i]); runner += 3; } *runner= '\0'; crDebug( "crTeacSetKey: Teac key is [%s]", msgbuf ); }
513422.c
/* * Copyright 2010-2017, Tarantool AUTHORS, please see AUTHORS file. * * 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 AUTHORS ``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 * AUTHORS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "vy_run.h" #include <zstd.h> #include "fiber.h" #include "fiber_cond.h" #include "fio.h" #include "cbus.h" #include "memory.h" #include "coio_file.h" #include "replication.h" #include "tuple_bloom.h" #include "xlog.h" #include "xrow.h" #include "vy_history.h" static const uint64_t vy_page_info_key_map = (1 << VY_PAGE_INFO_OFFSET) | (1 << VY_PAGE_INFO_SIZE) | (1 << VY_PAGE_INFO_UNPACKED_SIZE) | (1 << VY_PAGE_INFO_ROW_COUNT) | (1 << VY_PAGE_INFO_MIN_KEY) | (1 << VY_PAGE_INFO_ROW_INDEX_OFFSET); static const uint64_t vy_run_info_key_map = (1 << VY_RUN_INFO_MIN_KEY) | (1 << VY_RUN_INFO_MAX_KEY) | (1 << VY_RUN_INFO_MIN_LSN) | (1 << VY_RUN_INFO_MAX_LSN) | (1 << VY_RUN_INFO_PAGE_COUNT); /** xlog meta type for .run files */ #define XLOG_META_TYPE_RUN "RUN" /** xlog meta type for .index files */ #define XLOG_META_TYPE_INDEX "INDEX" const char *vy_file_suffix[] = { "index", /* VY_FILE_INDEX */ "index" inprogress_suffix, /* VY_FILE_INDEX_INPROGRESS */ "run", /* VY_FILE_RUN */ "run" inprogress_suffix, /* VY_FILE_RUN_INPROGRESS */ }; /* sync run and index files very 16 MB */ #define VY_RUN_SYNC_INTERVAL (1 << 24) /** * We read runs in background threads so as not to stall tx. * This structure represents such a thread. */ struct vy_run_reader { /** Thread that processes read requests. */ struct cord cord; /** Pipe from tx to the reader thread. */ struct cpipe reader_pipe; /** Pipe from the reader thread to tx. */ struct cpipe tx_pipe; }; /** Cbus task for vinyl page read. */ struct vy_page_read_task { /** parent */ struct cbus_call_msg base; /** vinyl page metadata */ struct vy_page_info *page_info; /** vy_run with fd - ref. counted */ struct vy_run *run; /** key to lookup within the page */ struct vy_entry key; /** iterator type (needed for for key lookup) */ enum iterator_type iterator_type; /** key definition (needed for key lookup) */ struct key_def *cmp_def; /** disk format (needed for key lookup) */ struct tuple_format *format; /** [out] position of the key in the page */ uint32_t pos_in_page; /** [out] true if key was found in the page */ bool equal_found; /** [out] resulting vinyl page */ struct vy_page *page; }; /** Destructor for env->zdctx_key thread-local variable */ static void vy_free_zdctx(void *arg) { assert(arg != NULL); ZSTD_freeDStream(arg); } /** Run reader thread function. */ static int vy_run_reader_f(va_list ap) { struct vy_run_reader *reader = va_arg(ap, struct vy_run_reader *); struct cbus_endpoint endpoint; cpipe_create(&reader->tx_pipe, "tx_prio"); cbus_endpoint_create(&endpoint, cord_name(cord()), fiber_schedule_cb, fiber()); cbus_loop(&endpoint); cbus_endpoint_destroy(&endpoint, cbus_process); cpipe_destroy(&reader->tx_pipe); return 0; } /** Start run reader threads. */ static void vy_run_env_start_readers(struct vy_run_env *env) { assert(env->reader_pool == NULL); assert(env->reader_pool_size > 0); env->reader_pool = calloc(env->reader_pool_size, sizeof(*env->reader_pool)); if (env->reader_pool == NULL) panic("failed to allocate vinyl reader thread pool"); for (int i = 0; i < env->reader_pool_size; i++) { struct vy_run_reader *reader = &env->reader_pool[i]; char name[FIBER_NAME_MAX]; snprintf(name, sizeof(name), "vinyl.reader.%d", i); if (cord_costart(&reader->cord, name, vy_run_reader_f, reader) != 0) panic("failed to start vinyl reader thread"); cpipe_create(&reader->reader_pipe, name); } env->next_reader = 0; } /** Join run reader threads. */ static void vy_run_env_stop_readers(struct vy_run_env *env) { for (int i = 0; i < env->reader_pool_size; i++) { struct vy_run_reader *reader = &env->reader_pool[i]; tt_pthread_cancel(reader->cord.id); tt_pthread_join(reader->cord.id, NULL); } free(env->reader_pool); } /** * Initialize vinyl run environment */ void vy_run_env_create(struct vy_run_env *env, int read_threads) { memset(env, 0, sizeof(*env)); env->reader_pool_size = read_threads; tt_pthread_key_create(&env->zdctx_key, vy_free_zdctx); mempool_create(&env->read_task_pool, cord_slab_cache(), sizeof(struct vy_page_read_task)); env->initial_join = false; } /** * Destroy vinyl run environment */ void vy_run_env_destroy(struct vy_run_env *env) { if (env->reader_pool != NULL) vy_run_env_stop_readers(env); mempool_destroy(&env->read_task_pool); tt_pthread_key_delete(env->zdctx_key); } /** * Enable coio reads for a vinyl run environment. */ void vy_run_env_enable_coio(struct vy_run_env *env) { if (env->reader_pool != NULL) return; /* already enabled */ vy_run_env_start_readers(env); } /** * Execute a task on behalf of a reader thread. */ static int vy_run_env_coio_call(struct vy_run_env *env, struct cbus_call_msg *msg, cbus_call_f func) { /* Optimization: use blocking I/O during WAL recovery. */ if (env->reader_pool == NULL) return func(msg); /* Pick a reader thread. */ struct vy_run_reader *reader; reader = &env->reader_pool[env->next_reader++]; env->next_reader %= env->reader_pool_size; /* Post the task to the reader thread. */ int rc = cbus_call(&reader->reader_pipe, &reader->tx_pipe, msg, func, NULL, TIMEOUT_INFINITY); if (rc != 0) return -1; if (fiber_is_cancelled()) { diag_set(FiberIsCancelled); return -1; } return 0; } /** * Initialize page info struct * * @retval 0 for Success * @retval -1 for error */ static int vy_page_info_create(struct vy_page_info *page_info, uint64_t offset, const char *min_key, struct key_def *cmp_def) { memset(page_info, 0, sizeof(*page_info)); page_info->offset = offset; page_info->unpacked_size = 0; page_info->min_key = vy_key_dup(min_key); if (page_info->min_key == NULL) return -1; uint32_t part_count = mp_decode_array(&min_key); page_info->min_key_hint = key_hint(min_key, part_count, cmp_def); return page_info->min_key == NULL ? -1 : 0; } /** * Destroy page info struct */ static void vy_page_info_destroy(struct vy_page_info *page_info) { if (page_info->min_key != NULL) free(page_info->min_key); } struct vy_run * vy_run_new(struct vy_run_env *env, int64_t id) { struct vy_run *run = calloc(1, sizeof(struct vy_run)); if (unlikely(run == NULL)) { diag_set(OutOfMemory, sizeof(struct vy_run), "malloc", "struct vy_run"); return NULL; } run->env = env; run->id = id; run->dump_lsn = -1; run->fd = -1; run->refs = 1; rlist_create(&run->in_lsm); rlist_create(&run->in_unused); return run; } static void vy_run_clear(struct vy_run *run) { if (run->page_info != NULL) { uint32_t page_no; for (page_no = 0; page_no < run->info.page_count; ++page_no) vy_page_info_destroy(run->page_info + page_no); free(run->page_info); } run->page_info = NULL; run->page_index_size = 0; run->info.page_count = 0; if (run->info.bloom != NULL) { tuple_bloom_delete(run->info.bloom); run->info.bloom = NULL; } free(run->info.min_key); run->info.min_key = NULL; free(run->info.max_key); run->info.max_key = NULL; } void vy_run_delete(struct vy_run *run) { assert(run->refs == 0); if (run->fd >= 0 && close(run->fd) < 0) say_syserror("close failed"); vy_run_clear(run); TRASH(run); free(run); } size_t vy_run_bloom_size(struct vy_run *run) { return run->info.bloom == NULL ? 0 : tuple_bloom_size(run->info.bloom); } /** * Find a page from which the iteration of a given key must be started. * LE and LT: the found page definitely contains the position * for iteration start. * GE, GT, EQ: Since page search uses only min_key of pages, * it may happen that the found page doesn't contain the position * for iteration start. In this case it is certain that the iteration * must be started from the beginning of the next page. * * @param run - run * @param key - key to find * @param key_def - key_def for comparison * @param itype - iterator type (see above) * @param equal_key: *equal_key is set to true if there is a page * with min_key equal to the given key. * @return offset of the page in page index OR run->info.page_count if * there no pages fulfilling the conditions. */ static uint32_t vy_page_index_find_page(struct vy_run *run, struct vy_entry key, struct key_def *cmp_def, enum iterator_type itype, bool *equal_key) { if (itype == ITER_EQ) itype = ITER_GE; /* One day it'll become obsolete */ assert(itype == ITER_GE || itype == ITER_GT || itype == ITER_LE || itype == ITER_LT); int dir = iterator_direction(itype); *equal_key = false; /** * Binary search in page index. Depends on given iterator_type: * ITER_GE: lowest page with min_key >= given key. * ITER_GT: lowest page with min_key > given key. * ITER_LE: highest page with min_key <= given key. * ITER_LT: highest page with min_key < given key. * * Example: we are searching for a value 2 in the run of 10 pages: * min_key: [1 1 2 2 2 2 2 3 3 3] * we want to find: [ LT GE LE GT ] * For LT and GE it's a classical lower_bound search. * Let's set up a range with left page's min_key < key and * right page's min >= key; binary cut the range until it * becomes of length 1 and then LT pos = left bound of the range * and GE pos = right bound of the range. * For LE and GT it's a classical upper_bound search. * Let's set up a range with left page's min_key <= key and * right page's min > key; binary cut the range until it * becomes of length 1 and then LE pos = left bound of the range * and GT pos = right bound of the range. */ bool is_lower_bound = itype == ITER_LT || itype == ITER_GE; assert(run->info.page_count > 0); /* Initially the range is set with virtual positions */ int32_t range[2] = { -1, run->info.page_count }; assert(run->info.page_count > 0); do { int32_t mid = range[0] + (range[1] - range[0]) / 2; struct vy_page_info *info = vy_run_page_info(run, mid); int cmp = vy_entry_compare_with_raw_key(key, info->min_key, info->min_key_hint, cmp_def); if (is_lower_bound) range[cmp <= 0] = mid; else range[cmp < 0] = mid; *equal_key = *equal_key || cmp == 0; } while (range[1] - range[0] > 1); if (range[0] < 0) range[0] = run->info.page_count; uint32_t page = range[dir > 0]; /** * Since page search uses only min_key of pages, * for GE, GT and EQ the previous page can contain * the point where iteration must be started. */ if (page > 0 && dir > 0) return page - 1; return page; } struct vy_slice * vy_slice_new(int64_t id, struct vy_run *run, struct vy_entry begin, struct vy_entry end, struct key_def *cmp_def) { struct vy_slice *slice = malloc(sizeof(*slice)); if (slice == NULL) { diag_set(OutOfMemory, sizeof(*slice), "malloc", "struct vy_slice"); return NULL; } memset(slice, 0, sizeof(*slice)); slice->id = id; slice->run = run; slice->seed = rand(); vy_run_ref(run); run->slice_count++; if (begin.stmt != NULL) tuple_ref(begin.stmt); slice->begin = begin; if (end.stmt != NULL) tuple_ref(end.stmt); slice->end = end; rlist_create(&slice->in_range); fiber_cond_create(&slice->pin_cond); if (run->info.page_count == 0) { /* The run is empty hence the slice is empty too. */ return slice; } /** Lookup the first and the last pages spanned by the slice. */ bool unused; if (slice->begin.stmt == NULL) { slice->first_page_no = 0; } else { slice->first_page_no = vy_page_index_find_page(run, slice->begin, cmp_def, ITER_GE, &unused); assert(slice->first_page_no < run->info.page_count); } if (slice->end.stmt == NULL) { slice->last_page_no = run->info.page_count - 1; } else { slice->last_page_no = vy_page_index_find_page(run, slice->end, cmp_def, ITER_LT, &unused); if (slice->last_page_no == run->info.page_count) { /* It's an empty slice */ slice->first_page_no = 0; slice->last_page_no = 0; return slice; } } assert(slice->last_page_no >= slice->first_page_no); /** Estimate the number of statements in the slice. */ uint32_t run_pages = run->info.page_count; uint32_t slice_pages = slice->last_page_no - slice->first_page_no + 1; slice->count.pages = slice_pages; slice->count.rows = DIV_ROUND_UP(run->count.rows * slice_pages, run_pages); slice->count.bytes = DIV_ROUND_UP(run->count.bytes * slice_pages, run_pages); slice->count.bytes_compressed = DIV_ROUND_UP( run->count.bytes_compressed * slice_pages, run_pages); return slice; } void vy_slice_delete(struct vy_slice *slice) { assert(slice->pin_count == 0); assert(slice->run->slice_count > 0); slice->run->slice_count--; vy_run_unref(slice->run); if (slice->begin.stmt != NULL) tuple_unref(slice->begin.stmt); if (slice->end.stmt != NULL) tuple_unref(slice->end.stmt); fiber_cond_destroy(&slice->pin_cond); TRASH(slice); free(slice); } int vy_slice_cut(struct vy_slice *slice, int64_t id, struct vy_entry begin, struct vy_entry end, struct key_def *cmp_def, struct vy_slice **result) { *result = NULL; if (begin.stmt != NULL && slice->end.stmt != NULL && vy_entry_compare(begin, slice->end, cmp_def) >= 0) return 0; /* no intersection: begin >= slice->end */ if (end.stmt != NULL && slice->begin.stmt != NULL && vy_entry_compare(end, slice->begin, cmp_def) <= 0) return 0; /* no intersection: end <= slice->end */ /* begin = MAX(begin, slice->begin) */ if (slice->begin.stmt != NULL && (begin.stmt == NULL || vy_entry_compare(begin, slice->begin, cmp_def) < 0)) begin = slice->begin; /* end = MIN(end, slice->end) */ if (slice->end.stmt != NULL && (end.stmt == NULL || vy_entry_compare(end, slice->end, cmp_def) > 0)) end = slice->end; *result = vy_slice_new(id, slice->run, begin, end, cmp_def); if (*result == NULL) return -1; /* OOM */ return 0; } /** * Decode page information from xrow. * * @param[out] page Page information. * @param xrow Xrow to decode. * @param cmp_def Definition of keys stored in the page. * @param filename Filename for error reporting. * * @retval 0 Success. * @retval -1 Error. */ static int vy_page_info_decode(struct vy_page_info *page, const struct xrow_header *xrow, struct key_def *cmp_def, const char *filename) { assert(xrow->type == VY_INDEX_PAGE_INFO); const char *pos = xrow->body->iov_base; memset(page, 0, sizeof(*page)); uint64_t key_map = vy_page_info_key_map; uint32_t map_size = mp_decode_map(&pos); uint32_t map_item; const char *key_beg; uint32_t part_count; for (map_item = 0; map_item < map_size; ++map_item) { uint32_t key = mp_decode_uint(&pos); key_map &= ~(1ULL << key); switch (key) { case VY_PAGE_INFO_OFFSET: page->offset = mp_decode_uint(&pos); break; case VY_PAGE_INFO_SIZE: page->size = mp_decode_uint(&pos); break; case VY_PAGE_INFO_ROW_COUNT: page->row_count = mp_decode_uint(&pos); break; case VY_PAGE_INFO_MIN_KEY: key_beg = pos; mp_next(&pos); page->min_key = vy_key_dup(key_beg); if (page->min_key == NULL) return -1; part_count = mp_decode_array(&key_beg); page->min_key_hint = key_hint(key_beg, part_count, cmp_def); break; case VY_PAGE_INFO_UNPACKED_SIZE: page->unpacked_size = mp_decode_uint(&pos); break; case VY_PAGE_INFO_ROW_INDEX_OFFSET: page->row_index_offset = mp_decode_uint(&pos); break; default: mp_next(&pos); /* unknown key, ignore */ break; } } if (key_map) { enum vy_page_info_key key = bit_ctz_u64(key_map); diag_set(ClientError, ER_INVALID_INDEX_FILE, filename, tt_sprintf("Can't decode page info: " "missing mandatory key %s", vy_page_info_key_name(key))); return -1; } return 0; } /** Decode statement statistics from @data and advance @data. */ static void vy_stmt_stat_decode(struct vy_stmt_stat *stat, const char **data) { uint32_t size = mp_decode_map(data); for (uint32_t i = 0; i < size; i++) { uint64_t key = mp_decode_uint(data); uint64_t value = mp_decode_uint(data); switch (key) { case IPROTO_INSERT: stat->inserts = value; break; case IPROTO_REPLACE: stat->replaces = value; break; case IPROTO_DELETE: stat->deletes = value; break; case IPROTO_UPSERT: stat->upserts = value; break; default: break; } } } /** * Decode the run metadata from xrow. * * @param xrow xrow to decode * @param[out] run_info the run information * @param filename File name for error reporting. * * @retval 0 success * @retval -1 error (check diag) */ int vy_run_info_decode(struct vy_run_info *run_info, const struct xrow_header *xrow, const char *filename) { assert(xrow->type == VY_INDEX_RUN_INFO); /* decode run */ const char *pos = xrow->body->iov_base; memset(run_info, 0, sizeof(*run_info)); uint64_t key_map = vy_run_info_key_map; uint32_t map_size = mp_decode_map(&pos); uint32_t map_item; const char *tmp; /* decode run values */ for (map_item = 0; map_item < map_size; ++map_item) { uint32_t key = mp_decode_uint(&pos); key_map &= ~(1ULL << key); switch (key) { case VY_RUN_INFO_MIN_KEY: tmp = pos; mp_next(&pos); run_info->min_key = vy_key_dup(tmp); if (run_info->min_key == NULL) return -1; break; case VY_RUN_INFO_MAX_KEY: tmp = pos; mp_next(&pos); run_info->max_key = vy_key_dup(tmp); if (run_info->max_key == NULL) return -1; break; case VY_RUN_INFO_MIN_LSN: run_info->min_lsn = mp_decode_uint(&pos); break; case VY_RUN_INFO_MAX_LSN: run_info->max_lsn = mp_decode_uint(&pos); break; case VY_RUN_INFO_PAGE_COUNT: run_info->page_count = mp_decode_uint(&pos); break; case VY_RUN_INFO_BLOOM_LEGACY: run_info->bloom = tuple_bloom_decode_legacy(&pos); if (run_info->bloom == NULL) return -1; break; case VY_RUN_INFO_BLOOM: run_info->bloom = tuple_bloom_decode(&pos); if (run_info->bloom == NULL) return -1; break; case VY_RUN_INFO_STMT_STAT: vy_stmt_stat_decode(&run_info->stmt_stat, &pos); break; default: mp_next(&pos); /* unknown key, ignore */ break; } } if (key_map) { enum vy_run_info_key key = bit_ctz_u64(key_map); diag_set(ClientError, ER_INVALID_INDEX_FILE, filename, tt_sprintf("Can't decode run info: " "missing mandatory key %s", vy_run_info_key_name(key))); return -1; } return 0; } static struct vy_page * vy_page_new(const struct vy_page_info *page_info) { struct vy_page *page = malloc(sizeof(*page)); if (page == NULL) { diag_set(OutOfMemory, sizeof(*page), "load_page", "page cache"); return NULL; } page->unpacked_size = page_info->unpacked_size; page->row_count = page_info->row_count; page->row_index = calloc(page_info->row_count, sizeof(uint32_t)); if (page->row_index == NULL) { diag_set(OutOfMemory, page_info->row_count * sizeof(uint32_t), "malloc", "page->row_index"); free(page); return NULL; } page->data = (char *)malloc(page_info->unpacked_size); if (page->data == NULL) { diag_set(OutOfMemory, page_info->unpacked_size, "malloc", "page->data"); free(page->row_index); free(page); return NULL; } return page; } static void vy_page_delete(struct vy_page *page) { uint32_t *row_index = page->row_index; char *data = page->data; #if !defined(NDEBUG) memset(row_index, '#', sizeof(uint32_t) * page->row_count); memset(data, '#', page->unpacked_size); memset(page, '#', sizeof(*page)); #endif /* !defined(NDEBUG) */ free(row_index); free(data); free(page); } static int vy_page_xrow(struct vy_page *page, uint32_t stmt_no, struct xrow_header *xrow) { assert(stmt_no < page->row_count); const char *data = page->data + page->row_index[stmt_no]; const char *data_end = stmt_no + 1 < page->row_count ? page->data + page->row_index[stmt_no + 1] : page->data + page->unpacked_size; return xrow_header_decode(xrow, &data, data_end, false); } /* {{{ vy_run_iterator vy_run_iterator support functions */ /** * Read raw stmt data from the page * @param page Page. * @param stmt_no Statement position in the page. * @param cmp_def Definition of keys stored in the page. * @param format Format for REPLACE/DELETE tuples. * * @retval not NULL Statement read from page. * @retval NULL Memory error. */ static struct vy_entry vy_page_stmt(struct vy_page *page, uint32_t stmt_no, struct key_def *cmp_def, struct tuple_format *format) { struct xrow_header xrow; if (vy_page_xrow(page, stmt_no, &xrow) != 0) return vy_entry_none(); struct vy_entry entry; entry.stmt = vy_stmt_decode(&xrow, format); if (entry.stmt == NULL) return vy_entry_none(); entry.hint = vy_stmt_hint(entry.stmt, cmp_def); return entry; } /** * Binary search in page * In terms of STL, makes lower_bound for EQ,GE,LT and upper_bound for GT,LE * Additionally *equal_key argument is set to true if the found value is * equal to given key (set to false otherwise). * @retval position in the page */ static uint32_t vy_page_find_key(struct vy_page *page, struct vy_entry key, struct key_def *cmp_def, struct tuple_format *format, enum iterator_type iterator_type, bool *equal_key) { uint32_t beg = 0; uint32_t end = page->row_count; *equal_key = false; /* for upper bound we change zero comparison result to -1 */ int zero_cmp = (iterator_type == ITER_GT || iterator_type == ITER_LE ? -1 : 0); while (beg != end) { uint32_t mid = beg + (end - beg) / 2; struct vy_entry fnd_key = vy_page_stmt(page, mid, cmp_def, format); if (fnd_key.stmt == NULL) return end; int cmp = vy_entry_compare(fnd_key, key, cmp_def); cmp = cmp ? cmp : zero_cmp; *equal_key = *equal_key || cmp == 0; if (cmp < 0) beg = mid + 1; else end = mid; tuple_unref(fnd_key.stmt); } return end; } /** * End iteration and free cached data. */ static void vy_run_iterator_stop(struct vy_run_iterator *itr) { if (itr->curr.stmt != NULL) { tuple_unref(itr->curr.stmt); itr->curr = vy_entry_none(); } if (itr->curr_page != NULL) { vy_page_delete(itr->curr_page); if (itr->prev_page != NULL) vy_page_delete(itr->prev_page); itr->curr_page = itr->prev_page = NULL; } } static int vy_row_index_decode(uint32_t *row_index, uint32_t row_count, struct xrow_header *xrow) { assert(xrow->type == VY_RUN_ROW_INDEX); const char *pos = xrow->body->iov_base; uint32_t map_size = mp_decode_map(&pos); uint32_t map_item; uint32_t size = 0; for (map_item = 0; map_item < map_size; ++map_item) { uint32_t key = mp_decode_uint(&pos); switch (key) { case VY_ROW_INDEX_DATA: size = mp_decode_binl(&pos); break; } } if (size != sizeof(uint32_t) * row_count) { diag_set(ClientError, ER_INVALID_RUN_FILE, tt_sprintf("Wrong row index size " "(expected %zu, got %u", sizeof(uint32_t) * row_count, (unsigned)size)); return -1; } for (uint32_t i = 0; i < row_count; ++i) { row_index[i] = mp_load_u32(&pos); } assert(pos == xrow->body->iov_base + xrow->body->iov_len); return 0; } /** Return the name of a run data file. */ static inline const char * vy_run_filename(struct vy_run *run) { char *buf = tt_static_buf(); vy_run_snprint_filename(buf, TT_STATIC_BUF_LEN, run->id, VY_FILE_RUN); return buf; } /** * Read a page requests from vinyl xlog data file. * * @retval 0 on success * @retval -1 on error, check diag */ static int vy_page_read(struct vy_page *page, const struct vy_page_info *page_info, struct vy_run *run, ZSTD_DStream *zdctx) { /* read xlog tx from xlog file */ size_t region_svp = region_used(&fiber()->gc); char *data = (char *)region_alloc(&fiber()->gc, page_info->size); if (data == NULL) { diag_set(OutOfMemory, page_info->size, "region gc", "page"); return -1; } ssize_t readen = fio_pread(run->fd, data, page_info->size, page_info->offset); ERROR_INJECT(ERRINJ_VYRUN_DATA_READ, { readen = -1; errno = EIO;}); if (readen < 0) { diag_set(SystemError, "failed to read from file"); goto error; } if (readen != (ssize_t)page_info->size) { diag_set(ClientError, ER_INVALID_RUN_FILE, "Unexpected end of file"); goto error; } struct errinj *inj = errinj(ERRINJ_VY_READ_PAGE_TIMEOUT, ERRINJ_DOUBLE); if (inj != NULL && inj->dparam > 0) thread_sleep(inj->dparam); ERROR_INJECT_SLEEP(ERRINJ_VY_READ_PAGE_DELAY); /* decode xlog tx */ const char *data_pos = data; const char *data_end = data + readen; char *rows = page->data; char *rows_end = rows + page_info->unpacked_size; if (xlog_tx_decode(data, data_end, rows, rows_end, zdctx) != 0) goto error; struct xrow_header xrow; data_pos = page->data + page_info->row_index_offset; data_end = page->data + page_info->unpacked_size; if (xrow_header_decode(&xrow, &data_pos, data_end, true) == -1) goto error; if (xrow.type != VY_RUN_ROW_INDEX) { diag_set(ClientError, ER_INVALID_RUN_FILE, tt_sprintf("Wrong row index type " "(expected %d, got %u)", VY_RUN_ROW_INDEX, (unsigned)xrow.type)); goto error; } if (vy_row_index_decode(page->row_index, page->row_count, &xrow) != 0) goto error; region_truncate(&fiber()->gc, region_svp); ERROR_INJECT(ERRINJ_VY_READ_PAGE, { diag_set(ClientError, ER_INJECTION, "vinyl page read"); return -1;}); return 0; error: region_truncate(&fiber()->gc, region_svp); diag_log(); say_error("error reading %s@%llu:%u", vy_run_filename(run), (unsigned long long)page_info->offset, (unsigned)page_info->size); return -1; } /** * Get thread local zstd decompression context */ static ZSTD_DStream * vy_env_get_zdctx(struct vy_run_env *env) { ZSTD_DStream *zdctx = tt_pthread_getspecific(env->zdctx_key); if (zdctx == NULL) { zdctx = ZSTD_createDStream(); if (zdctx == NULL) { diag_set(OutOfMemory, sizeof(zdctx), "malloc", "zstd context"); return NULL; } tt_pthread_setspecific(env->zdctx_key, zdctx); } return zdctx; } /** * vinyl read task callback */ static int vy_page_read_cb(struct cbus_call_msg *base) { struct vy_page_read_task *task = (struct vy_page_read_task *)base; ZSTD_DStream *zdctx = vy_env_get_zdctx(task->run->env); if (zdctx == NULL) return -1; if (vy_page_read(task->page, task->page_info, task->run, zdctx) != 0) return -1; if (task->key.stmt != NULL) { task->pos_in_page = vy_page_find_key(task->page, task->key, task->cmp_def, task->format, task->iterator_type, &task->equal_found); } return 0; } /** * Read a page from disk given its number. * The function caches two most recently read pages. * * @retval 0 success * @retval -1 critical error */ static NODISCARD int vy_run_iterator_load_page(struct vy_run_iterator *itr, uint32_t page_no, struct vy_entry key, enum iterator_type iterator_type, struct vy_page **result, uint32_t *pos_in_page, bool *equal_found) { struct vy_slice *slice = itr->slice; struct vy_run_env *env = slice->run->env; /* Check cache */ struct vy_page *page = NULL; if (itr->curr_page != NULL && itr->curr_page->page_no == page_no) { page = itr->curr_page; } else if (itr->prev_page != NULL && itr->prev_page->page_no == page_no) { SWAP(itr->prev_page, itr->curr_page); page = itr->curr_page; } if (page != NULL) { if (key.stmt != NULL) *pos_in_page = vy_page_find_key(page, key, itr->cmp_def, itr->format, iterator_type, equal_found); *result = page; return 0; } /* Allocate buffers */ struct vy_page_info *page_info = vy_run_page_info(slice->run, page_no); page = vy_page_new(page_info); if (page == NULL) return -1; /* Read page data from the disk */ struct vy_page_read_task *task = mempool_alloc(&env->read_task_pool); if (task == NULL) { diag_set(OutOfMemory, sizeof(*task), "mempool", "vy_page_read_task"); vy_page_delete(page); return -1; } task->run = slice->run; task->page_info = page_info; task->page = page; task->key = key; task->iterator_type = iterator_type; task->cmp_def = itr->cmp_def; task->format = itr->format; task->pos_in_page = 0; task->equal_found = false; int rc = vy_run_env_coio_call(env, &task->base, vy_page_read_cb); *pos_in_page = task->pos_in_page; *equal_found = task->equal_found; mempool_free(&env->read_task_pool, task); if (rc != 0) { vy_page_delete(page); return -1; } /* Update cache */ if (itr->prev_page != NULL) vy_page_delete(itr->prev_page); itr->prev_page = itr->curr_page; itr->curr_page = page; page->page_no = page_no; /* Update read statistics. */ itr->stat->read.rows += page_info->row_count; itr->stat->read.bytes += page_info->unpacked_size; itr->stat->read.bytes_compressed += page_info->size; itr->stat->read.pages++; *result = page; return 0; } /** * Read key and lsn by a given wide position. * For the first record in a page reads the result from the page * index instead of fetching it from disk. * * @retval 0 success * @retval -1 read error or out of memory. */ static NODISCARD int vy_run_iterator_read(struct vy_run_iterator *itr, struct vy_run_iterator_pos pos, struct vy_entry *ret) { struct vy_page *page; bool equal_found; uint32_t pos_in_page; int rc = vy_run_iterator_load_page(itr, pos.page_no, vy_entry_none(), ITER_GE, &page, &pos_in_page, &equal_found); if (rc != 0) return rc; *ret = vy_page_stmt(page, pos.pos_in_page, itr->cmp_def, itr->format); if (ret->stmt == NULL) return -1; return 0; } /** * Binary search in a run for the given key. * In terms of STL, makes lower_bound for EQ,GE,LT and upper_bound for GT,LE * Resulting wide position is stored it *pos argument * Additionally *equal_key argument is set to true if the found value is * equal to given key (untouched otherwise) * * @retval 0 success * @retval 1 EOF * @retval -1 read or memory error */ static NODISCARD int vy_run_iterator_search(struct vy_run_iterator *itr, enum iterator_type iterator_type, struct vy_entry key, struct vy_run_iterator_pos *pos, bool *equal_key) { pos->page_no = vy_page_index_find_page(itr->slice->run, key, itr->cmp_def, iterator_type, equal_key); if (pos->page_no == itr->slice->run->info.page_count) return 1; bool equal_in_page; struct vy_page *page; int rc = vy_run_iterator_load_page(itr, pos->page_no, key, iterator_type, &page, &pos->pos_in_page, &equal_in_page); if (rc != 0) return rc; if (pos->pos_in_page == page->row_count) { pos->page_no++; pos->pos_in_page = 0; } else { *equal_key = equal_in_page; } return 0; } /** * Increment (or decrement, depending on the order) the current * wide position. * @retval 0 success, set *pos to new value * @retval 1 EOF * Affects: curr_loaded_page */ static NODISCARD int vy_run_iterator_next_pos(struct vy_run_iterator *itr, enum iterator_type iterator_type, struct vy_run_iterator_pos *pos) { struct vy_run *run = itr->slice->run; *pos = itr->curr_pos; if (iterator_type == ITER_LE || iterator_type == ITER_LT) { assert(pos->page_no <= run->info.page_count); if (pos->pos_in_page > 0) { pos->pos_in_page--; } else { if (pos->page_no == 0) return 1; pos->page_no--; struct vy_page_info *page_info = vy_run_page_info(run, pos->page_no); assert(page_info->row_count > 0); pos->pos_in_page = page_info->row_count - 1; } } else { assert(iterator_type == ITER_GE || iterator_type == ITER_GT || iterator_type == ITER_EQ); assert(pos->page_no < run->info.page_count); struct vy_page_info *page_info = vy_run_page_info(run, pos->page_no); assert(page_info->row_count > 0); pos->pos_in_page++; if (pos->pos_in_page >= page_info->row_count) { pos->page_no++; pos->pos_in_page = 0; if (pos->page_no == run->info.page_count) return 1; } } return 0; } /** * Find the next record with lsn <= itr->lsn record. * The current position must be at the beginning of a series of * records with the same key it terms of direction of iterator * (i.e. left for GE, right for LE). * @retval 0 success or EOF (*ret == NULL) * @retval -1 read or memory error * Affects: curr_loaded_page, curr_pos */ static NODISCARD int vy_run_iterator_find_lsn(struct vy_run_iterator *itr, struct vy_entry *ret) { struct vy_slice *slice = itr->slice; struct key_def *cmp_def = itr->cmp_def; *ret = vy_entry_none(); assert(itr->search_started); assert(itr->curr.stmt != NULL); assert(itr->curr_pos.page_no < slice->run->info.page_count); while (vy_stmt_lsn(itr->curr.stmt) > (**itr->read_view).vlsn || vy_stmt_flags(itr->curr.stmt) & VY_STMT_SKIP_READ) { if (vy_run_iterator_next_pos(itr, itr->iterator_type, &itr->curr_pos) != 0) { vy_run_iterator_stop(itr); return 0; } tuple_unref(itr->curr.stmt); itr->curr = vy_entry_none(); if (vy_run_iterator_read(itr, itr->curr_pos, &itr->curr) != 0) return -1; if (itr->iterator_type == ITER_EQ && vy_entry_compare(itr->curr, itr->key, cmp_def) != 0) { vy_run_iterator_stop(itr); return 0; } } if (itr->iterator_type == ITER_LE || itr->iterator_type == ITER_LT) { struct vy_run_iterator_pos test_pos; while (vy_run_iterator_next_pos(itr, itr->iterator_type, &test_pos) == 0) { struct vy_entry test; if (vy_run_iterator_read(itr, test_pos, &test) != 0) return -1; if (vy_stmt_lsn(test.stmt) > (**itr->read_view).vlsn || vy_stmt_flags(test.stmt) & VY_STMT_SKIP_READ || vy_entry_compare(itr->curr, test, cmp_def) != 0) { tuple_unref(test.stmt); break; } tuple_unref(itr->curr.stmt); itr->curr = test; itr->curr_pos = test_pos; } } /* Check if the result is within the slice boundaries. */ if (itr->iterator_type == ITER_LE || itr->iterator_type == ITER_LT) { if (slice->begin.stmt != NULL && vy_entry_compare(itr->curr, slice->begin, cmp_def) < 0) { vy_run_iterator_stop(itr); return 0; } } else { assert(itr->iterator_type == ITER_GE || itr->iterator_type == ITER_GT || itr->iterator_type == ITER_EQ); if (slice->end.stmt != NULL && vy_entry_compare(itr->curr, slice->end, cmp_def) >= 0) { vy_run_iterator_stop(itr); return 0; } } vy_stmt_counter_acct_tuple(&itr->stat->get, itr->curr.stmt); *ret = itr->curr; return 0; } /** * Helper function for vy_run_iterator_seek(). * * Positions the iterator to the beginning (i.e. leftmost for GE, * rightmost for LE) of a series of statements matching the given * search criteria. * * Updates itr->curr_pos. Doesn't affect itr->curr. * * @retval 0 success * @retval 1 EOF * @retval -1 read or memory error */ static NODISCARD int vy_run_iterator_do_seek(struct vy_run_iterator *itr, enum iterator_type iterator_type, struct vy_entry key) { struct vy_run *run = itr->slice->run; struct vy_run_iterator_pos end_pos = {run->info.page_count, 0}; bool equal_found = false; if (!vy_stmt_is_empty_key(key.stmt)) { int rc = vy_run_iterator_search(itr, iterator_type, key, &itr->curr_pos, &equal_found); if (rc != 0) return rc; } else if (iterator_type == ITER_LE) { itr->curr_pos = end_pos; } else { assert(iterator_type == ITER_GE); itr->curr_pos.page_no = 0; itr->curr_pos.pos_in_page = 0; } if (iterator_type == ITER_EQ && !equal_found) return 1; if ((iterator_type == ITER_GE || iterator_type == ITER_GT) && itr->curr_pos.page_no == end_pos.page_no) return 1; if (iterator_type == ITER_LT || iterator_type == ITER_LE) { /** * 1) in case of ITER_LT we now positioned on the value >= than * given, so we need to make a step on previous key * 2) in case if ITER_LE we now positioned on the value > than * given (special branch of code in vy_run_iterator_search), * so we need to make a step on previous key */ return vy_run_iterator_next_pos(itr, iterator_type, &itr->curr_pos); } else { assert(iterator_type == ITER_GE || iterator_type == ITER_GT || iterator_type == ITER_EQ); /** * 1) in case of ITER_GT we now positioned on the value > than * given (special branch of code in vy_run_iterator_search), * so we need just to find proper lsn * 2) in case if ITER_GE or ITER_EQ we now positioned on the * value >= given, so we need just to find proper lsn */ return 0; } } /** * Position the iterator to the first statement satisfying * the iterator search criteria and following the given key * (pass NULL to start iteration). */ static NODISCARD int vy_run_iterator_seek(struct vy_run_iterator *itr, struct vy_entry last, struct vy_entry *ret) { struct key_def *cmp_def = itr->cmp_def; struct vy_slice *slice = itr->slice; struct tuple_bloom *bloom = slice->run->info.bloom; struct vy_entry key = itr->key; enum iterator_type iterator_type = itr->iterator_type; *ret = vy_entry_none(); assert(itr->search_started); /* Check the bloom filter on the first iteration. */ bool check_bloom = (itr->iterator_type == ITER_EQ && itr->curr.stmt == NULL && bloom != NULL); if (check_bloom && !vy_bloom_maybe_has(bloom, itr->key, itr->key_def)) { vy_run_iterator_stop(itr); itr->stat->bloom_hit++; return 0; } /* * vy_run_iterator_do_seek() implements its own EQ check. * We only need to check EQ here if iterator type and key * passed to it differ from the original. */ bool check_eq = false; /* * Modify iterator type and key so as to position it to * the first statement following the given key. */ if (last.stmt != NULL) { if (iterator_type == ITER_EQ) check_eq = true; iterator_type = iterator_direction(iterator_type) > 0 ? ITER_GT : ITER_LT; key = last; } /* Take slice boundaries into account. */ if (slice->begin.stmt != NULL && (iterator_type == ITER_GT || iterator_type == ITER_GE || iterator_type == ITER_EQ)) { /* * original | start * --------------+-------+-----+ * KEY | DIR | KEY | DIR | * --------+-----+-------+-----+ * > begin | * | key | * | * = begin | gt | key | gt | * | ge | begin | ge | * | eq | begin | ge | * < begin | gt | begin | ge | * | ge | begin | ge | * | eq | stop | */ int cmp = vy_entry_compare(key, slice->begin, cmp_def); if (cmp < 0 && iterator_type == ITER_EQ) { vy_run_iterator_stop(itr); return 0; } if (cmp < 0 || (cmp == 0 && iterator_type != ITER_GT)) { if (iterator_type == ITER_EQ) check_eq = true; iterator_type = ITER_GE; key = slice->begin; } } if (slice->end.stmt != NULL && (iterator_type == ITER_LT || iterator_type == ITER_LE)) { /* * original | start * --------------+-------+-----+ * KEY | DIR | KEY | DIR | * --------+-----+-------+-----+ * < end | * | key | * | * = end | lt | key | lt | * | le | end | lt | * > end | lt | end | lt | * | le | end | lt | */ int cmp = vy_entry_compare(key, slice->end, cmp_def); if (cmp > 0 || (cmp == 0 && iterator_type != ITER_LT)) { iterator_type = ITER_LT; key = slice->end; } } /* Perform a lookup in the run. */ itr->stat->lookup++; int rc = vy_run_iterator_do_seek(itr, iterator_type, key); if (rc < 0) return -1; if (rc > 0) goto not_found; /* Load the found statement. */ if (itr->curr.stmt != NULL) { tuple_unref(itr->curr.stmt); itr->curr = vy_entry_none(); } if (vy_run_iterator_read(itr, itr->curr_pos, &itr->curr) != 0) return -1; /* Check EQ constraint if necessary. */ if (check_eq && vy_entry_compare(itr->curr, itr->key, itr->cmp_def) != 0) goto not_found; /* Skip statements invisible from the iterator read view. */ return vy_run_iterator_find_lsn(itr, ret); not_found: if (check_bloom) itr->stat->bloom_miss++; vy_run_iterator_stop(itr); return 0; } /* }}} vy_run_iterator vy_run_iterator support functions */ /* {{{ vy_run_iterator API implementation */ void vy_run_iterator_open(struct vy_run_iterator *itr, struct vy_run_iterator_stat *stat, struct vy_slice *slice, enum iterator_type iterator_type, struct vy_entry key, const struct vy_read_view **rv, struct key_def *cmp_def, struct key_def *key_def, struct tuple_format *format) { itr->stat = stat; itr->cmp_def = cmp_def; itr->key_def = key_def; itr->format = format; itr->slice = slice; itr->iterator_type = iterator_type; itr->key = key; itr->read_view = rv; itr->curr = vy_entry_none(); itr->curr_pos.page_no = slice->run->info.page_count; itr->curr_page = NULL; itr->prev_page = NULL; itr->search_started = false; /* * Make sure the format we use to create tuples won't * go away if DDL is called while the iterator is used. * * XXX: Please remove this kludge when proper DDL locking * is implemented on transaction management level or multi * version data dictionary is in place. */ tuple_format_ref(format); } /** * Advance a run iterator to the newest statement for the next key. * The statement is returned in @ret (NULL if EOF). * Returns 0 on success, -1 on memory allocation or IO error. */ static NODISCARD int vy_run_iterator_next_key(struct vy_run_iterator *itr, struct vy_entry *ret) { *ret = vy_entry_none(); if (!itr->search_started) { itr->search_started = true; return vy_run_iterator_seek(itr, vy_entry_none(), ret); } if (itr->curr.stmt == NULL) return 0; assert(itr->curr_pos.page_no < itr->slice->run->info.page_count); struct vy_entry next = vy_entry_none(); do { if (next.stmt != NULL) tuple_unref(next.stmt); if (vy_run_iterator_next_pos(itr, itr->iterator_type, &itr->curr_pos) != 0) { vy_run_iterator_stop(itr); return 0; } if (vy_run_iterator_read(itr, itr->curr_pos, &next) != 0) return -1; } while (vy_entry_compare(itr->curr, next, itr->cmp_def) == 0); tuple_unref(itr->curr.stmt); itr->curr = next; if (itr->iterator_type == ITER_EQ && vy_entry_compare(next, itr->key, itr->cmp_def) != 0) { vy_run_iterator_stop(itr); return 0; } return vy_run_iterator_find_lsn(itr, ret); } /** * Advance a run iterator to the next (older) statement for the * current key. The statement is returned in @ret (NULL if EOF). * Returns 0 on success, -1 on memory allocation or IO error. */ static NODISCARD int vy_run_iterator_next_lsn(struct vy_run_iterator *itr, struct vy_entry *ret) { *ret = vy_entry_none(); assert(itr->search_started); assert(itr->curr.stmt != NULL); assert(itr->curr_pos.page_no < itr->slice->run->info.page_count); struct vy_run_iterator_pos next_pos; next: if (vy_run_iterator_next_pos(itr, ITER_GE, &next_pos) != 0) { vy_run_iterator_stop(itr); return 0; } struct vy_entry next; if (vy_run_iterator_read(itr, next_pos, &next) != 0) return -1; if (vy_entry_compare(itr->curr, next, itr->cmp_def) != 0) { tuple_unref(next.stmt); return 0; } tuple_unref(itr->curr.stmt); itr->curr = next; itr->curr_pos = next_pos; if (vy_stmt_flags(itr->curr.stmt) & VY_STMT_SKIP_READ) goto next; vy_stmt_counter_acct_tuple(&itr->stat->get, itr->curr.stmt); *ret = itr->curr; return 0; } NODISCARD int vy_run_iterator_next(struct vy_run_iterator *itr, struct vy_history *history) { vy_history_cleanup(history); struct vy_entry entry; if (vy_run_iterator_next_key(itr, &entry) != 0) return -1; while (entry.stmt != NULL) { if (vy_history_append_stmt(history, entry) != 0) return -1; if (vy_history_is_terminal(history)) break; if (vy_run_iterator_next_lsn(itr, &entry) != 0) return -1; } return 0; } NODISCARD int vy_run_iterator_skip(struct vy_run_iterator *itr, struct vy_entry last, struct vy_history *history) { /* * Check if the iterator is already positioned * at the statement following last. */ if (itr->search_started && (itr->curr.stmt == NULL || last.stmt == NULL || iterator_direction(itr->iterator_type) * vy_entry_compare(itr->curr, last, itr->cmp_def) > 0)) return 0; vy_history_cleanup(history); itr->search_started = true; struct vy_entry entry; if (vy_run_iterator_seek(itr, last, &entry) != 0) return -1; while (entry.stmt != NULL) { if (vy_history_append_stmt(history, entry) != 0) return -1; if (vy_history_is_terminal(history)) break; if (vy_run_iterator_next_lsn(itr, &entry) != 0) return -1; } return 0; } void vy_run_iterator_close(struct vy_run_iterator *itr) { vy_run_iterator_stop(itr); tuple_format_unref(itr->format); TRASH(itr); } /* }}} vy_run_iterator API implementation */ /** Account a page to run statistics. */ static void vy_run_acct_page(struct vy_run *run, struct vy_page_info *page) { const char *min_key_end = page->min_key; mp_next(&min_key_end); run->page_index_size += sizeof(struct vy_page_info); run->page_index_size += min_key_end - page->min_key; run->count.rows += page->row_count; run->count.bytes += page->unpacked_size; run->count.bytes_compressed += page->size; run->count.pages++; } int vy_run_recover(struct vy_run *run, const char *dir, uint32_t space_id, uint32_t iid, struct key_def *cmp_def) { char path[PATH_MAX]; vy_run_snprint_path(path, sizeof(path), dir, space_id, iid, run->id, VY_FILE_INDEX); struct xlog_cursor cursor; ERROR_INJECT_COUNTDOWN(ERRINJ_VY_RUN_OPEN, { diag_set(SystemError, "failed to open '%s' file", path); goto fail; }); if (xlog_cursor_open(&cursor, path)) goto fail; struct xlog_meta *meta = &cursor.meta; if (strcmp(meta->filetype, XLOG_META_TYPE_INDEX) != 0) { diag_set(ClientError, ER_INVALID_XLOG_TYPE, XLOG_META_TYPE_INDEX, meta->filetype); goto fail_close; } /* Read run header. */ struct xrow_header xrow; /* all rows should be in one tx */ int rc = xlog_cursor_next_tx(&cursor); if (rc != 0) { if (rc > 0) diag_set(ClientError, ER_INVALID_INDEX_FILE, path, "Unexpected end of file"); goto fail_close; } rc = xlog_cursor_next_row(&cursor, &xrow); if (rc != 0) { if (rc > 0) diag_set(ClientError, ER_INVALID_INDEX_FILE, path, "Unexpected end of file"); goto fail_close; } if (xrow.type != VY_INDEX_RUN_INFO) { diag_set(ClientError, ER_INVALID_INDEX_FILE, path, tt_sprintf("Wrong xrow type (expected %d, got %u)", VY_INDEX_RUN_INFO, (unsigned)xrow.type)); goto fail_close; } if (vy_run_info_decode(&run->info, &xrow, path) != 0) goto fail_close; /* Allocate buffer for page info. */ run->page_info = calloc(run->info.page_count, sizeof(struct vy_page_info)); if (run->page_info == NULL) { diag_set(OutOfMemory, run->info.page_count * sizeof(struct vy_page_info), "malloc", "struct vy_page_info"); goto fail_close; } for (uint32_t page_no = 0; page_no < run->info.page_count; page_no++) { int rc = xlog_cursor_next_row(&cursor, &xrow); if (rc != 0) { if (rc > 0) { /** To few pages in file */ diag_set(ClientError, ER_INVALID_INDEX_FILE, path, "Unexpected end of file"); } /* * Limit the count of pages to * successfully created pages. */ run->info.page_count = page_no; goto fail_close; } if (xrow.type != VY_INDEX_PAGE_INFO) { diag_set(ClientError, ER_INVALID_INDEX_FILE, tt_sprintf("Wrong xrow type " "(expected %d, got %u)", VY_INDEX_PAGE_INFO, (unsigned)xrow.type)); goto fail_close; } struct vy_page_info *page = run->page_info + page_no; if (vy_page_info_decode(page, &xrow, cmp_def, path) < 0) { /** * Limit the count of pages to successfully * created pages */ run->info.page_count = page_no; goto fail_close; } vy_run_acct_page(run, page); } /* We don't need to keep metadata file open any longer. */ xlog_cursor_close(&cursor, false); /* Prepare data file for reading. */ vy_run_snprint_path(path, sizeof(path), dir, space_id, iid, run->id, VY_FILE_RUN); if (xlog_cursor_open(&cursor, path)) goto fail; meta = &cursor.meta; if (strcmp(meta->filetype, XLOG_META_TYPE_RUN) != 0) { diag_set(ClientError, ER_INVALID_XLOG_TYPE, XLOG_META_TYPE_RUN, meta->filetype); goto fail_close; } run->fd = cursor.fd; xlog_cursor_close(&cursor, true); return 0; fail_close: xlog_cursor_close(&cursor, false); fail: vy_run_clear(run); diag_log(); say_error("failed to load `%s'", path); return -1; } /* dump statement to the run page buffers (stmt header and data) */ static int vy_run_dump_stmt(struct vy_entry entry, struct xlog *data_xlog, struct vy_page_info *info, struct key_def *key_def, bool is_primary) { struct xrow_header xrow; int rc = (is_primary ? vy_stmt_encode_primary(entry.stmt, key_def, 0, &xrow) : vy_stmt_encode_secondary(entry.stmt, key_def, vy_entry_multikey_idx(entry, key_def), &xrow)); if (rc != 0) return -1; ssize_t row_size; if ((row_size = xlog_write_row(data_xlog, &xrow)) < 0) return -1; info->unpacked_size += row_size; info->row_count++; return 0; } /** * Encode uint32_t array of row offsets (row index) as xrow * * @param row_index row index * @param row_count size of row index * @param[out] xrow xrow to fill. * @retval 0 for success * @retval -1 for error */ static int vy_row_index_encode(const uint32_t *row_index, uint32_t row_count, struct xrow_header *xrow) { memset(xrow, 0, sizeof(*xrow)); xrow->type = VY_RUN_ROW_INDEX; size_t size = mp_sizeof_map(1) + mp_sizeof_uint(VY_ROW_INDEX_DATA) + mp_sizeof_bin(sizeof(uint32_t) * row_count); char *pos = region_alloc(&fiber()->gc, size); if (pos == NULL) { diag_set(OutOfMemory, size, "region", "row index"); return -1; } xrow->body->iov_base = pos; pos = mp_encode_map(pos, 1); pos = mp_encode_uint(pos, VY_ROW_INDEX_DATA); pos = mp_encode_binl(pos, sizeof(uint32_t) * row_count); for (uint32_t i = 0; i < row_count; ++i) pos = mp_store_u32(pos, row_index[i]); xrow->body->iov_len = (void *)pos - xrow->body->iov_base; assert(xrow->body->iov_len == size); xrow->bodycnt = 1; return 0; } /** * Helper to extend run page info array */ static inline int vy_run_alloc_page_info(struct vy_run *run, uint32_t *page_info_capacity) { uint32_t cap = *page_info_capacity > 0 ? *page_info_capacity * 2 : 16; struct vy_page_info *page_info = realloc(run->page_info, cap * sizeof(*page_info)); if (page_info == NULL) { diag_set(OutOfMemory, cap * sizeof(*page_info), "realloc", "struct vy_page_info"); return -1; } run->page_info = page_info; *page_info_capacity = cap; return 0; } /** {{{ vy_page_info */ /** * Encode vy_page_info as xrow. * Allocates using region_alloc. * * @param page_info page information to encode * @param[out] xrow xrow to fill * * @retval 0 success * @retval -1 error, check diag */ static int vy_page_info_encode(const struct vy_page_info *page_info, struct xrow_header *xrow) { struct region *region = &fiber()->gc; uint32_t min_key_size; const char *tmp = page_info->min_key; assert(mp_typeof(*tmp) == MP_ARRAY); mp_next(&tmp); min_key_size = tmp - page_info->min_key; /* calc tuple size */ uint32_t size; /* 3 items: page offset, size, and map */ size = mp_sizeof_map(6) + mp_sizeof_uint(VY_PAGE_INFO_OFFSET) + mp_sizeof_uint(page_info->offset) + mp_sizeof_uint(VY_PAGE_INFO_SIZE) + mp_sizeof_uint(page_info->size) + mp_sizeof_uint(VY_PAGE_INFO_ROW_COUNT) + mp_sizeof_uint(page_info->row_count) + mp_sizeof_uint(VY_PAGE_INFO_MIN_KEY) + min_key_size + mp_sizeof_uint(VY_PAGE_INFO_UNPACKED_SIZE) + mp_sizeof_uint(page_info->unpacked_size) + mp_sizeof_uint(VY_PAGE_INFO_ROW_INDEX_OFFSET) + mp_sizeof_uint(page_info->row_index_offset); char *pos = region_alloc(region, size); if (pos == NULL) { diag_set(OutOfMemory, size, "region", "page encode"); return -1; } memset(xrow, 0, sizeof(*xrow)); /* encode page */ xrow->body->iov_base = pos; pos = mp_encode_map(pos, 6); pos = mp_encode_uint(pos, VY_PAGE_INFO_OFFSET); pos = mp_encode_uint(pos, page_info->offset); pos = mp_encode_uint(pos, VY_PAGE_INFO_SIZE); pos = mp_encode_uint(pos, page_info->size); pos = mp_encode_uint(pos, VY_PAGE_INFO_ROW_COUNT); pos = mp_encode_uint(pos, page_info->row_count); pos = mp_encode_uint(pos, VY_PAGE_INFO_MIN_KEY); memcpy(pos, page_info->min_key, min_key_size); pos += min_key_size; pos = mp_encode_uint(pos, VY_PAGE_INFO_UNPACKED_SIZE); pos = mp_encode_uint(pos, page_info->unpacked_size); pos = mp_encode_uint(pos, VY_PAGE_INFO_ROW_INDEX_OFFSET); pos = mp_encode_uint(pos, page_info->row_index_offset); xrow->body->iov_len = (void *)pos - xrow->body->iov_base; xrow->bodycnt = 1; xrow->type = VY_INDEX_PAGE_INFO; return 0; } /** vy_page_info }}} */ /** {{{ vy_run_info */ /** Return the size of encoded statement statistics. */ static size_t vy_stmt_stat_sizeof(const struct vy_stmt_stat *stat) { return mp_sizeof_map(4) + mp_sizeof_uint(IPROTO_INSERT) + mp_sizeof_uint(IPROTO_REPLACE) + mp_sizeof_uint(IPROTO_DELETE) + mp_sizeof_uint(IPROTO_UPSERT) + mp_sizeof_uint(stat->inserts) + mp_sizeof_uint(stat->replaces) + mp_sizeof_uint(stat->deletes) + mp_sizeof_uint(stat->upserts); } /** Encode statement statistics to @buf and return advanced @buf. */ static char * vy_stmt_stat_encode(const struct vy_stmt_stat *stat, char *buf) { buf = mp_encode_map(buf, 4); buf = mp_encode_uint(buf, IPROTO_INSERT); buf = mp_encode_uint(buf, stat->inserts); buf = mp_encode_uint(buf, IPROTO_REPLACE); buf = mp_encode_uint(buf, stat->replaces); buf = mp_encode_uint(buf, IPROTO_DELETE); buf = mp_encode_uint(buf, stat->deletes); buf = mp_encode_uint(buf, IPROTO_UPSERT); buf = mp_encode_uint(buf, stat->upserts); return buf; } /** * Encode vy_run_info as xrow * Allocates using region alloc * * @param run_info the run information * @param xrow xrow to fill. * * @retval 0 success * @retval -1 on error, check diag */ static int vy_run_info_encode(const struct vy_run_info *run_info, struct xrow_header *xrow) { const char *tmp; tmp = run_info->min_key; mp_next(&tmp); size_t min_key_size = tmp - run_info->min_key; tmp = run_info->max_key; mp_next(&tmp); size_t max_key_size = tmp - run_info->max_key; uint32_t key_count = 6; if (run_info->bloom != NULL) key_count++; size_t size = mp_sizeof_map(key_count); size += mp_sizeof_uint(VY_RUN_INFO_MIN_KEY) + min_key_size; size += mp_sizeof_uint(VY_RUN_INFO_MAX_KEY) + max_key_size; size += mp_sizeof_uint(VY_RUN_INFO_MIN_LSN) + mp_sizeof_uint(run_info->min_lsn); size += mp_sizeof_uint(VY_RUN_INFO_MAX_LSN) + mp_sizeof_uint(run_info->max_lsn); size += mp_sizeof_uint(VY_RUN_INFO_PAGE_COUNT) + mp_sizeof_uint(run_info->page_count); if (run_info->bloom != NULL) size += mp_sizeof_uint(VY_RUN_INFO_BLOOM) + tuple_bloom_size(run_info->bloom); size += mp_sizeof_uint(VY_RUN_INFO_STMT_STAT) + vy_stmt_stat_sizeof(&run_info->stmt_stat); char *pos = region_alloc(&fiber()->gc, size); if (pos == NULL) { diag_set(OutOfMemory, size, "region", "run encode"); return -1; } memset(xrow, 0, sizeof(*xrow)); xrow->body->iov_base = pos; /* encode values */ pos = mp_encode_map(pos, key_count); pos = mp_encode_uint(pos, VY_RUN_INFO_MIN_KEY); memcpy(pos, run_info->min_key, min_key_size); pos += min_key_size; pos = mp_encode_uint(pos, VY_RUN_INFO_MAX_KEY); memcpy(pos, run_info->max_key, max_key_size); pos += max_key_size; pos = mp_encode_uint(pos, VY_RUN_INFO_MIN_LSN); pos = mp_encode_uint(pos, run_info->min_lsn); pos = mp_encode_uint(pos, VY_RUN_INFO_MAX_LSN); pos = mp_encode_uint(pos, run_info->max_lsn); pos = mp_encode_uint(pos, VY_RUN_INFO_PAGE_COUNT); pos = mp_encode_uint(pos, run_info->page_count); if (run_info->bloom != NULL) { pos = mp_encode_uint(pos, VY_RUN_INFO_BLOOM); pos = tuple_bloom_encode(run_info->bloom, pos); } pos = mp_encode_uint(pos, VY_RUN_INFO_STMT_STAT); pos = vy_stmt_stat_encode(&run_info->stmt_stat, pos); xrow->body->iov_len = (void *)pos - xrow->body->iov_base; xrow->bodycnt = 1; xrow->type = VY_INDEX_RUN_INFO; return 0; } /* vy_run_info }}} */ /** * Write run index to file. */ static int vy_run_write_index(struct vy_run *run, const char *dirpath, uint32_t space_id, uint32_t iid) { char path[PATH_MAX]; vy_run_snprint_path(path, sizeof(path), dirpath, space_id, iid, run->id, VY_FILE_INDEX); say_info("writing `%s'", path); struct xlog index_xlog; struct xlog_meta meta; xlog_meta_create(&meta, XLOG_META_TYPE_INDEX, &INSTANCE_UUID, NULL, NULL); struct xlog_opts opts = xlog_opts_default; opts.rate_limit = run->env->snap_io_rate_limit; opts.sync_interval = VY_RUN_SYNC_INTERVAL; if (xlog_create(&index_xlog, path, 0, &meta, &opts) < 0) return -1; xlog_tx_begin(&index_xlog); struct region *region = &fiber()->gc; size_t mem_used = region_used(region); struct xrow_header xrow; if (vy_run_info_encode(&run->info, &xrow) != 0 || xlog_write_row(&index_xlog, &xrow) < 0) goto fail_rollback; for (uint32_t page_no = 0; page_no < run->info.page_count; ++page_no) { struct vy_page_info *page_info = vy_run_page_info(run, page_no); if (vy_page_info_encode(page_info, &xrow) < 0) { goto fail_rollback; } if (xlog_write_row(&index_xlog, &xrow) < 0) goto fail_rollback; } region_truncate(region, mem_used); if (xlog_tx_commit(&index_xlog) < 0) goto fail; ERROR_INJECT(ERRINJ_VY_INDEX_FILE_RENAME, { diag_set(ClientError, ER_INJECTION, "vinyl index file rename"); xlog_close(&index_xlog, false); return -1; }); if (xlog_flush(&index_xlog) < 0 || xlog_rename(&index_xlog) < 0) goto fail; xlog_close(&index_xlog, false); return 0; fail_rollback: region_truncate(region, mem_used); xlog_tx_rollback(&index_xlog); fail: xlog_close(&index_xlog, false); unlink(path); return -1; } int vy_run_writer_create(struct vy_run_writer *writer, struct vy_run *run, const char *dirpath, uint32_t space_id, uint32_t iid, struct key_def *cmp_def, struct key_def *key_def, uint64_t page_size, double bloom_fpr, bool no_compression) { memset(writer, 0, sizeof(*writer)); writer->run = run; writer->dirpath = dirpath; writer->space_id = space_id; writer->iid = iid; writer->cmp_def = cmp_def; writer->key_def = key_def; writer->page_size = page_size; writer->bloom_fpr = bloom_fpr; writer->no_compression = no_compression; if (bloom_fpr < 1) { writer->bloom = tuple_bloom_builder_new(key_def->part_count); if (writer->bloom == NULL) return -1; } xlog_clear(&writer->data_xlog); ibuf_create(&writer->row_index_buf, &cord()->slabc, 4096 * sizeof(uint32_t)); run->info.min_lsn = INT64_MAX; run->info.max_lsn = -1; assert(run->page_info == NULL); return 0; } /** * Create an xlog to write run. * @param writer Run writer. * @retval -1 Memory or IO error. * @retval 0 Success. */ static int vy_run_writer_create_xlog(struct vy_run_writer *writer) { assert(!xlog_is_open(&writer->data_xlog)); char path[PATH_MAX]; vy_run_snprint_path(path, sizeof(path), writer->dirpath, writer->space_id, writer->iid, writer->run->id, VY_FILE_RUN); say_info("writing `%s'", path); struct xlog_meta meta; xlog_meta_create(&meta, XLOG_META_TYPE_RUN, &INSTANCE_UUID, NULL, NULL); struct xlog_opts opts = xlog_opts_default; opts.rate_limit = writer->run->env->snap_io_rate_limit; opts.sync_interval = VY_RUN_SYNC_INTERVAL; opts.no_compression = writer->no_compression; if (xlog_create(&writer->data_xlog, path, 0, &meta, &opts) != 0) return -1; return 0; } /** * Start a new page with a min_key stored in @a first_entry. * @param writer Run writer. * @param first_entry First statement of a page. * * @retval -1 Memory error. * @retval 0 Success. */ static int vy_run_writer_start_page(struct vy_run_writer *writer, struct vy_entry first_entry) { struct vy_run *run = writer->run; if (run->info.page_count >= writer->page_info_capacity && vy_run_alloc_page_info(run, &writer->page_info_capacity) != 0) return -1; const char *key = vy_stmt_is_key(first_entry.stmt) ? tuple_data(first_entry.stmt) : tuple_extract_key(first_entry.stmt, writer->cmp_def, vy_entry_multikey_idx(first_entry, writer->cmp_def), NULL); if (key == NULL) return -1; if (run->info.page_count == 0) { assert(run->info.min_key == NULL); run->info.min_key = vy_key_dup(key); if (run->info.min_key == NULL) return -1; } struct vy_page_info *page = run->page_info + run->info.page_count; if (vy_page_info_create(page, writer->data_xlog.offset, key, writer->cmp_def) != 0) return -1; xlog_tx_begin(&writer->data_xlog); return 0; } /** * Write @a stmt into a current page. * @param writer Run writer. * @param entry Statement to write. * * @retval -1 Memory or IO error. * @retval 0 Success. */ static int vy_run_writer_write_to_page(struct vy_run_writer *writer, struct vy_entry entry) { if (writer->bloom != NULL && vy_bloom_builder_add(writer->bloom, entry, writer->key_def) != 0) return -1; if (writer->last.stmt != NULL) vy_stmt_unref_if_possible(writer->last.stmt); writer->last = entry; vy_stmt_ref_if_possible(entry.stmt); struct vy_run *run = writer->run; struct vy_page_info *page = run->page_info + run->info.page_count; uint32_t *offset = (uint32_t *)ibuf_alloc(&writer->row_index_buf, sizeof(uint32_t)); if (offset == NULL) { diag_set(OutOfMemory, sizeof(uint32_t), "ibuf", "row index"); return -1; } *offset = page->unpacked_size; if (vy_run_dump_stmt(entry, &writer->data_xlog, page, writer->cmp_def, writer->iid == 0) != 0) return -1; int64_t lsn = vy_stmt_lsn(entry.stmt); run->info.min_lsn = MIN(run->info.min_lsn, lsn); run->info.max_lsn = MAX(run->info.max_lsn, lsn); vy_stmt_stat_acct(&run->info.stmt_stat, vy_stmt_type(entry.stmt)); return 0; } /** * Finish a current page. * @param writer Run writer. * @retval -1 Memory or IO error. * @retval 0 Success. */ static int vy_run_writer_end_page(struct vy_run_writer *writer) { struct vy_run *run = writer->run; struct vy_page_info *page = run->page_info + run->info.page_count; assert(page->row_count > 0); assert(ibuf_used(&writer->row_index_buf) == sizeof(uint32_t) * page->row_count); struct xrow_header xrow; uint32_t *row_index = (uint32_t *)writer->row_index_buf.rpos; if (vy_row_index_encode(row_index, page->row_count, &xrow) < 0) return -1; ssize_t written = xlog_write_row(&writer->data_xlog, &xrow); if (written < 0) return -1; page->row_index_offset = page->unpacked_size; page->unpacked_size += written; written = xlog_tx_commit(&writer->data_xlog); if (written == 0) written = xlog_flush(&writer->data_xlog); if (written < 0) return -1; page->size = written; run->info.page_count++; vy_run_acct_page(run, page); ibuf_reset(&writer->row_index_buf); return 0; } int vy_run_writer_append_stmt(struct vy_run_writer *writer, struct vy_entry entry) { int rc = -1; size_t region_svp = region_used(&fiber()->gc); if (!xlog_is_open(&writer->data_xlog) && vy_run_writer_create_xlog(writer) != 0) goto out; if (ibuf_used(&writer->row_index_buf) == 0 && vy_run_writer_start_page(writer, entry) != 0) goto out; if (vy_run_writer_write_to_page(writer, entry) != 0) goto out; if (obuf_size(&writer->data_xlog.obuf) >= writer->page_size && vy_run_writer_end_page(writer) != 0) goto out; rc = 0; out: region_truncate(&fiber()->gc, region_svp); return rc; } /** * Destroy a run writer. * @param writer Writer to destroy. * @param reuse_fd True in a case of success run write. And else * false. */ static void vy_run_writer_destroy(struct vy_run_writer *writer, bool reuse_fd) { if (writer->last.stmt != NULL) vy_stmt_unref_if_possible(writer->last.stmt); if (xlog_is_open(&writer->data_xlog)) xlog_close(&writer->data_xlog, reuse_fd); if (writer->bloom != NULL) tuple_bloom_builder_delete(writer->bloom); ibuf_destroy(&writer->row_index_buf); } int vy_run_writer_commit(struct vy_run_writer *writer) { int rc = -1; size_t region_svp = region_used(&fiber()->gc); if (ibuf_used(&writer->row_index_buf) != 0 && vy_run_writer_end_page(writer) != 0) goto out; struct vy_run *run = writer->run; if (vy_run_is_empty(run)) { vy_run_writer_destroy(writer, false); rc = 0; goto out; } assert(writer->last.stmt != NULL); const char *key = vy_stmt_is_key(writer->last.stmt) ? tuple_data(writer->last.stmt) : tuple_extract_key(writer->last.stmt, writer->cmp_def, vy_entry_multikey_idx(writer->last, writer->cmp_def), NULL); if (key == NULL) goto out; assert(run->info.max_key == NULL); run->info.max_key = vy_key_dup(key); if (run->info.max_key == NULL) goto out; ERROR_INJECT(ERRINJ_VY_RUN_FILE_RENAME, { diag_set(ClientError, ER_INJECTION, "vinyl run file rename"); goto out; }); /* Sync data and link the file to the final name. */ if (xlog_sync(&writer->data_xlog) < 0 || xlog_rename(&writer->data_xlog) < 0) goto out; if (writer->bloom != NULL) { run->info.bloom = tuple_bloom_new(writer->bloom, writer->bloom_fpr); if (run->info.bloom == NULL) goto out; } if (vy_run_write_index(run, writer->dirpath, writer->space_id, writer->iid) != 0) goto out; run->fd = writer->data_xlog.fd; vy_run_writer_destroy(writer, true); rc = 0; out: region_truncate(&fiber()->gc, region_svp); return rc; } void vy_run_writer_abort(struct vy_run_writer *writer) { vy_run_writer_destroy(writer, false); } int vy_run_rebuild_index(struct vy_run *run, const char *dir, uint32_t space_id, uint32_t iid, struct key_def *cmp_def, struct key_def *key_def, struct tuple_format *format, const struct index_opts *opts) { assert(run->info.bloom == NULL); assert(run->page_info == NULL); struct region *region = &fiber()->gc; size_t mem_used = region_used(region); struct xlog_cursor cursor; char path[PATH_MAX]; vy_run_snprint_path(path, sizeof(path), dir, space_id, iid, run->id, VY_FILE_RUN); say_info("rebuilding index for `%s'", path); if (xlog_cursor_open(&cursor, path)) return -1; int rc = 0; uint32_t page_info_capacity = 0; const char *key = NULL; int64_t max_lsn = 0; int64_t min_lsn = INT64_MAX; struct tuple *prev_tuple = NULL; char *page_min_key = NULL; struct tuple_bloom_builder *bloom_builder = NULL; if (opts->bloom_fpr < 1) { bloom_builder = tuple_bloom_builder_new(key_def->part_count); if (bloom_builder == NULL) goto close_err; } off_t page_offset, next_page_offset = xlog_cursor_pos(&cursor); while ((rc = xlog_cursor_next_tx(&cursor)) == 0) { region_truncate(region, mem_used); page_offset = next_page_offset; next_page_offset = xlog_cursor_pos(&cursor); if (run->info.page_count == page_info_capacity && vy_run_alloc_page_info(run, &page_info_capacity) != 0) goto close_err; uint32_t page_row_count = 0; uint64_t page_row_index_offset = 0; uint64_t row_offset = xlog_cursor_tx_pos(&cursor); struct xrow_header xrow; while ((rc = xlog_cursor_next_row(&cursor, &xrow)) == 0) { if (xrow.type == VY_RUN_ROW_INDEX) { page_row_index_offset = row_offset; row_offset = xlog_cursor_tx_pos(&cursor); continue; } ++page_row_count; struct tuple *tuple = vy_stmt_decode(&xrow, format); if (tuple == NULL) goto close_err; if (bloom_builder != NULL) { struct vy_entry entry = {tuple, HINT_NONE}; if (vy_bloom_builder_add(bloom_builder, entry, key_def) != 0) { tuple_unref(tuple); goto close_err; } } key = vy_stmt_is_key(tuple) ? tuple_data(tuple) : tuple_extract_key(tuple, cmp_def, MULTIKEY_NONE, NULL); if (prev_tuple != NULL) tuple_unref(prev_tuple); prev_tuple = tuple; if (key == NULL) goto close_err; if (run->info.min_key == NULL) { run->info.min_key = vy_key_dup(key); if (run->info.min_key == NULL) goto close_err; } if (page_min_key == NULL) { page_min_key = vy_key_dup(key); if (page_min_key == NULL) goto close_err; } if (xrow.lsn > max_lsn) max_lsn = xrow.lsn; if (xrow.lsn < min_lsn) min_lsn = xrow.lsn; row_offset = xlog_cursor_tx_pos(&cursor); } struct vy_page_info *info; info = run->page_info + run->info.page_count; if (vy_page_info_create(info, page_offset, page_min_key, cmp_def) != 0) goto close_err; info->row_count = page_row_count; info->size = next_page_offset - page_offset; info->unpacked_size = xlog_cursor_tx_pos(&cursor); info->row_index_offset = page_row_index_offset; ++run->info.page_count; vy_run_acct_page(run, info); free(page_min_key); page_min_key = NULL; } if (key != NULL) { run->info.max_key = vy_key_dup(key); if (run->info.max_key == NULL) goto close_err; } run->info.max_lsn = max_lsn; run->info.min_lsn = min_lsn; if (prev_tuple != NULL) { tuple_unref(prev_tuple); prev_tuple = NULL; } region_truncate(region, mem_used); run->fd = cursor.fd; xlog_cursor_close(&cursor, true); if (bloom_builder != NULL) { run->info.bloom = tuple_bloom_new(bloom_builder, opts->bloom_fpr); if (run->info.bloom == NULL) goto close_err; tuple_bloom_builder_delete(bloom_builder); bloom_builder = NULL; } /* New run index is ready for write, unlink old file if exists */ vy_run_snprint_path(path, sizeof(path), dir, space_id, iid, run->id, VY_FILE_INDEX); if (unlink(path) < 0 && errno != ENOENT) { diag_set(SystemError, "failed to unlink file '%s'", path); goto close_err; } if (vy_run_write_index(run, dir, space_id, iid) != 0) goto close_err; return 0; close_err: vy_run_clear(run); region_truncate(region, mem_used); if (prev_tuple != NULL) tuple_unref(prev_tuple); if (page_min_key != NULL) free(page_min_key); if (bloom_builder != NULL) tuple_bloom_builder_delete(bloom_builder); if (xlog_cursor_is_open(&cursor)) xlog_cursor_close(&cursor, false); return -1; } int vy_run_remove_files(const char *dir, uint32_t space_id, uint32_t iid, int64_t run_id) { ERROR_INJECT(ERRINJ_VY_GC, {say_error("error injection: vinyl run %lld not deleted", (long long)run_id); return -1;}); int ret = 0; char path[PATH_MAX]; for (int type = 0; type < vy_file_MAX; type++) { vy_run_snprint_path(path, sizeof(path), dir, space_id, iid, run_id, type); if (coio_unlink(path) < 0) { if (errno != ENOENT) { say_syserror("error while removing %s", path); ret = -1; } } else say_info("removed %s", path); } return ret; } /** * Read a page with stream->page_no from the run and save it in stream->page. * Support function of slice stream. * @param stream - the stream. * @return 0 on success, -1 of memory or read error (diag is set). */ static NODISCARD int vy_slice_stream_read_page(struct vy_slice_stream *stream) { struct vy_run *run = stream->slice->run; assert(stream->page == NULL); ZSTD_DStream *zdctx = vy_env_get_zdctx(run->env); if (zdctx == NULL) return -1; struct vy_page_info *page_info = vy_run_page_info(run, stream->page_no); stream->page = vy_page_new(page_info); if (stream->page == NULL) return -1; if (vy_page_read(stream->page, page_info, run, zdctx) != 0) { vy_page_delete(stream->page); stream->page = NULL; return -1; } return 0; } /** * Binary search in a run for the given key. Find the first position with * a tuple greater or equal to slice * @retval 0 success * @retval -1 read or memory error */ static NODISCARD int vy_slice_stream_search(struct vy_stmt_stream *virt_stream) { assert(virt_stream->iface->start == vy_slice_stream_search); struct vy_slice_stream *stream = (struct vy_slice_stream *)virt_stream; assert(stream->page == NULL); if (stream->slice->begin.stmt == NULL) { /* Already at the beginning */ assert(stream->page_no == 0); assert(stream->pos_in_page == 0); return 0; } if (vy_slice_stream_read_page(stream) != 0) return -1; bool unused; stream->pos_in_page = vy_page_find_key(stream->page, stream->slice->begin, stream->cmp_def, stream->format, ITER_GE, &unused); if (stream->pos_in_page == stream->page->row_count) { /* The first tuple is in the beginning of the next page */ vy_page_delete(stream->page); stream->page = NULL; stream->page_no++; stream->pos_in_page = 0; } return 0; } /** * Get the value from the stream and move to the next position. * Set *ret to the value or NULL if EOF. * @param virt_stream - virtual stream. * @param ret - pointer to the result. * @return 0 on success, -1 on memory or read error. */ static NODISCARD int vy_slice_stream_next(struct vy_stmt_stream *virt_stream, struct vy_entry *ret) { assert(virt_stream->iface->next == vy_slice_stream_next); struct vy_slice_stream *stream = (struct vy_slice_stream *)virt_stream; *ret = vy_entry_none(); /* If the slice is ended, return EOF */ if (stream->page_no > stream->slice->last_page_no) return 0; /* If current page is not already read, read it */ if (stream->page == NULL && vy_slice_stream_read_page(stream) != 0) return -1; /* Read current tuple from the page */ struct vy_entry entry = vy_page_stmt(stream->page, stream->pos_in_page, stream->cmp_def, stream->format); if (entry.stmt == NULL) /* Read or memory error */ return -1; /* Check that the tuple is not out of slice bounds = */ if (stream->slice->end.stmt != NULL && stream->page_no >= stream->slice->last_page_no && vy_entry_compare(entry, stream->slice->end, stream->cmp_def) >= 0) { tuple_unref(entry.stmt); return 0; } /* We definitely has the next non-null tuple. Save it in stream */ if (stream->entry.stmt != NULL) tuple_unref(stream->entry.stmt); stream->entry = entry; *ret = entry; /* Increment position */ stream->pos_in_page++; /* Check whether the position is out of page */ struct vy_page_info *page_info = vy_run_page_info(stream->slice->run, stream->page_no); if (stream->pos_in_page >= page_info->row_count) { /** * Out of page. Free page, move the position to the next page * and * nullify page pointer to read it on the next iteration. */ vy_page_delete(stream->page); stream->page = NULL; stream->page_no++; stream->pos_in_page = 0; } return 0; } /** * Free resources. */ static void vy_slice_stream_stop(struct vy_stmt_stream *virt_stream) { assert(virt_stream->iface->stop == vy_slice_stream_stop); struct vy_slice_stream *stream = (struct vy_slice_stream *)virt_stream; if (stream->page != NULL) { vy_page_delete(stream->page); stream->page = NULL; } if (stream->entry.stmt != NULL) { tuple_unref(stream->entry.stmt); stream->entry = vy_entry_none(); } } static void vy_slice_stream_close(struct vy_stmt_stream *virt_stream) { assert(virt_stream->iface->close == vy_slice_stream_close); struct vy_slice_stream *stream = (struct vy_slice_stream *)virt_stream; tuple_format_unref(stream->format); } static const struct vy_stmt_stream_iface vy_slice_stream_iface = { .start = vy_slice_stream_search, .next = vy_slice_stream_next, .stop = vy_slice_stream_stop, .close = vy_slice_stream_close, }; void vy_slice_stream_open(struct vy_slice_stream *stream, struct vy_slice *slice, struct key_def *cmp_def, struct tuple_format *format) { stream->base.iface = &vy_slice_stream_iface; stream->page_no = slice->first_page_no; stream->pos_in_page = 0; /* We'll find it later */ stream->page = NULL; stream->entry = vy_entry_none(); stream->slice = slice; stream->cmp_def = cmp_def; stream->format = format; tuple_format_ref(format); }
829818.c
/* * Hacker Disassembler Engine 32 C * Copyright (c) 2008-2009, Vyacheslav Patkov. * All rights reserved. * */ #include <stdint.h> #include <string.h> #include "hde/hde32.h" #include "hde/table32.h" #ifdef _MSC_VER #pragma warning(disable:4701) #endif unsigned int hde32_disasm(const void *code, hde32s *hs) { uint8_t x, c, *p = (uint8_t*)code, cflags, opcode, pref = 0; uint8_t* ht = hde32_table, m_mod, m_reg, m_rm, disp_size = 0; memset(hs,0,sizeof(hde32s)); for (x = 16; x; x--) switch (c = *p++) { case 0xf3: hs->p_rep = c; pref |= PRE_F3; break; case 0xf2: hs->p_rep = c; pref |= PRE_F2; break; case 0xf0: hs->p_lock = c; pref |= PRE_LOCK; break; case 0x26: case 0x2e: case 0x36: case 0x3e: case 0x64: case 0x65: hs->p_seg = c; pref |= PRE_SEG; break; case 0x66: hs->p_66 = c; pref |= PRE_66; break; case 0x67: hs->p_67 = c; pref |= PRE_67; break; default: goto pref_done; } pref_done: hs->flags = (uint32_t)pref << 23; if (!pref) pref |= PRE_NONE; if ((hs->opcode = c) == 0x0f) { hs->opcode2 = c = *p++; ht += DELTA_OPCODES; } else if (c >= 0xa0 && c <= 0xa3) { if (pref & PRE_67) pref |= PRE_66; else pref &= ~PRE_66; } opcode = c; cflags = ht[ht[opcode / 4] + (opcode % 4)]; if (cflags == C_ERROR) { hs->flags |= F_ERROR | F_ERROR_OPCODE; cflags = 0; if ((opcode & -3) == 0x24) cflags++; } x = 0; if (cflags & C_GROUP) { uint16_t t; t = *(uint16_t*)(ht + (cflags & 0x7f)); cflags = (uint8_t)t; x = (uint8_t)(t >> 8); } if (hs->opcode2) { ht = hde32_table + DELTA_PREFIXES; if (ht[ht[opcode / 4] + (opcode % 4)] & pref) hs->flags |= F_ERROR | F_ERROR_OPCODE; } if (cflags & C_MODRM) { hs->flags |= F_MODRM; hs->modrm = c = *p++; hs->modrm_mod = m_mod = c >> 6; hs->modrm_rm = m_rm = c & 7; hs->modrm_reg = m_reg = (c & 0x3f) >> 3; if (x && ((x << m_reg) & 0x80)) hs->flags |= F_ERROR | F_ERROR_OPCODE; if (!hs->opcode2 && opcode >= 0xd9 && opcode <= 0xdf) { uint8_t t = opcode - 0xd9; if (m_mod == 3) { ht = hde32_table + DELTA_FPU_MODRM + t*8; t = ht[m_reg] << m_rm; } else { ht = hde32_table + DELTA_FPU_REG; t = ht[t] << m_reg; } if (t & 0x80) hs->flags |= F_ERROR | F_ERROR_OPCODE; } if (pref & PRE_LOCK) { if (m_mod == 3) { hs->flags |= F_ERROR | F_ERROR_LOCK; } else { uint8_t* table_end, op = opcode; if (hs->opcode2) { ht = hde32_table + DELTA_OP2_LOCK_OK; table_end = ht + DELTA_OP_ONLY_MEM - DELTA_OP2_LOCK_OK; } else { ht = hde32_table + DELTA_OP_LOCK_OK; table_end = ht + DELTA_OP2_LOCK_OK - DELTA_OP_LOCK_OK; op &= -2; } for (; ht != table_end; ht++) if (*ht++ == op) { if (!((*ht << m_reg) & 0x80)) goto no_lock_error; else break; } hs->flags |= F_ERROR | F_ERROR_LOCK; no_lock_error: ; } } if (hs->opcode2) { switch (opcode) { case 0x20: case 0x22: m_mod = 3; if (m_reg > 4 || m_reg == 1) goto error_operand; else goto no_error_operand; case 0x21: case 0x23: m_mod = 3; if (m_reg == 4 || m_reg == 5) goto error_operand; else goto no_error_operand; } } else { switch (opcode) { case 0x8c: if (m_reg > 5) goto error_operand; else goto no_error_operand; case 0x8e: if (m_reg == 1 || m_reg > 5) goto error_operand; else goto no_error_operand; } } if (m_mod == 3) { uint8_t* table_end; if (hs->opcode2) { ht = hde32_table + DELTA_OP2_ONLY_MEM; table_end = ht + sizeof(hde32_table) - DELTA_OP2_ONLY_MEM; } else { ht = hde32_table + DELTA_OP_ONLY_MEM; table_end = ht + DELTA_OP2_ONLY_MEM - DELTA_OP_ONLY_MEM; } for (; ht != table_end; ht += 2) if (*ht++ == opcode) { if ((*ht++ & pref) && !((*ht << m_reg) & 0x80)) goto error_operand; else break; } goto no_error_operand; } else if (hs->opcode2) { switch (opcode) { case 0x50: case 0xd7: case 0xf7: if (pref & (PRE_NONE | PRE_66)) goto error_operand; break; case 0xd6: if (pref & (PRE_F2 | PRE_F3)) goto error_operand; break; case 0xc5: goto error_operand; } goto no_error_operand; } else goto no_error_operand; error_operand: hs->flags |= F_ERROR | F_ERROR_OPERAND; no_error_operand: c = *p++; if (m_reg <= 1) { if (opcode == 0xf6) cflags |= C_IMM8; else if (opcode == 0xf7) cflags |= C_IMM_P66; } switch (m_mod) { case 0: if (pref & PRE_67) { if (m_rm == 6) disp_size = 2; } else if (m_rm == 5) disp_size = 4; break; case 1: disp_size = 1; break; case 2: disp_size = 2; if (!(pref & PRE_67)) disp_size <<= 1; break; } if (m_mod != 3 && m_rm == 4 && !(pref & PRE_67)) { hs->flags |= F_SIB; p++; hs->sib = c; hs->sib_scale = c >> 6; hs->sib_index = (c & 0x3f) >> 3; if ((hs->sib_base = c & 7) == 5 && !(m_mod & 1)) disp_size = 4; } p--; switch (disp_size) { case 1: hs->flags |= F_DISP8; hs->disp.disp8 = *p; break; case 2: hs->flags |= F_DISP16; hs->disp.disp16 = *(uint16_t*)p; break; case 4: hs->flags |= F_DISP32; hs->disp.disp32 = *(uint32_t*)p; break; } p += disp_size; } else if (pref & PRE_LOCK) hs->flags |= F_ERROR | F_ERROR_LOCK; if (cflags & C_IMM_P66) { if (cflags & C_REL32) { if (pref & PRE_66) { hs->flags |= F_IMM16 | F_RELATIVE; hs->imm.imm16 = *(uint16_t*)p; p += 2; goto disasm_done; } goto rel32_ok; } if (pref & PRE_66) { hs->flags |= F_IMM16; hs->imm.imm16 = *(uint16_t*)p; p += 2; } else { hs->flags |= F_IMM32; hs->imm.imm32 = *(uint32_t*)p; p += 4; } } if (cflags & C_IMM16) { if (hs->flags & F_IMM32) { hs->flags |= F_IMM16; hs->disp.disp16 = *(uint16_t*)p; } else if (hs->flags & F_IMM16) { hs->flags |= F_2IMM16; hs->disp.disp16 = *(uint16_t*)p; } else { hs->flags |= F_IMM16; hs->imm.imm16 = *(uint16_t*)p; } p += 2; } if (cflags & C_IMM8) { hs->flags |= F_IMM8; hs->imm.imm8 = *p++; } if (cflags & C_REL32) { rel32_ok: hs->flags |= F_IMM32 | F_RELATIVE; hs->imm.imm32 = *(uint32_t*)p; p += 4; } else if (cflags & C_REL8) { hs->flags |= F_IMM8 | F_RELATIVE; hs->imm.imm8 = *p++; } disasm_done: if ((hs->len = (uint8_t)(p-(uint8_t*)code)) > 15) { hs->flags |= F_ERROR | F_ERROR_LENGTH; hs->len = 15; } return (unsigned int)hs->len; }
534364.c
#define qw(a) (a - 10) #define qw( b) (b - 20) int main() { int x, y; x = 10; y = 20; qw(x); return 0; }
43314.c
/** * Exercitiul 1. * Determinarea numarului din intervalul [2, N] care are suma divizorilor nebanali maxima. */ #include <stdio.h> int main() { int N, i, j, s, s_max = -1, maxim; scanf("%d", &N); for (i = 2; i <= N; i++) { s = 0; // calculez suma divizorilor nebanali pentru i for (j = 2; j < i; j++) { if (i % j == 0) { // j e divizor pentru i s += j; } } if (s > s_max) { s_max = s; maxim = i; } } printf("%d %d\n", maxim, s_max); return 0; }
774136.c
/* ========================================================================== */ /* === Cholesky/cholmod_etree =============================================== */ /* ========================================================================== */ /* ----------------------------------------------------------------------------- * CHOLMOD/Cholesky Module. Copyright (C) 2005-2006, Timothy A. Davis * The CHOLMOD/Cholesky Module is licensed under Version 2.1 of the GNU * Lesser General Public License. See lesser.txt for a text of the license. * CHOLMOD is also available under other licenses; contact authors for details. * -------------------------------------------------------------------------- */ /* Compute the elimination tree of A or A'*A * * In the symmetric case, the upper triangular part of A is used. Entries not * in this part of the matrix are ignored. Computing the etree of a symmetric * matrix from just its lower triangular entries is not supported. * * In the unsymmetric case, all of A is used, and the etree of A'*A is computed. * * References: * * J. Liu, "A compact row storage scheme for Cholesky factors", ACM Trans. * Math. Software, vol 12, 1986, pp. 127-148. * * J. Liu, "The role of elimination trees in sparse factorization", SIAM J. * Matrix Analysis & Applic., vol 11, 1990, pp. 134-172. * * J. Gilbert, X. Li, E. Ng, B. Peyton, "Computing row and column counts for * sparse QR and LU factorization", BIT, vol 41, 2001, pp. 693-710. * * workspace: symmetric: Iwork (nrow), unsymmetric: Iwork (nrow+ncol) * * Supports any xtype (pattern, real, complex, or zomplex) */ #ifndef NCHOLESKY #include "cholmod_internal.h" #include "cholmod_cholesky.h" /* ========================================================================== */ /* === update_etree ========================================================= */ /* ========================================================================== */ static void update_etree ( /* inputs, not modified */ Int k, /* process the edge (k,i) in the input graph */ Int i, /* inputs, modified on output */ Int Parent [ ], /* Parent [t] = p if p is the parent of t */ Int Ancestor [ ] /* Ancestor [t] is the ancestor of node t in the partially-constructed etree */ ) { Int a ; for ( ; ; ) /* traverse the path from k to the root of the tree */ { a = Ancestor [k] ; if (a == i) { /* final ancestor reached; no change to tree */ return ; } /* perform path compression */ Ancestor [k] = i ; if (a == EMPTY) { /* final ancestor undefined; this is a new edge in the tree */ Parent [k] = i ; return ; } /* traverse up to the ancestor of k */ k = a ; } } /* ========================================================================== */ /* === cholmod_etree ======================================================== */ /* ========================================================================== */ /* Find the elimination tree of A or A'*A */ int CHOLMOD(etree) ( /* ---- input ---- */ cholmod_sparse *A, /* ---- output --- */ Int *Parent, /* size ncol. Parent [j] = p if p is the parent of j */ /* --------------- */ cholmod_common *Common ) { Int *Ap, *Ai, *Anz, *Ancestor, *Prev, *Iwork ; Int i, j, jprev, p, pend, nrow, ncol, packed, stype ; size_t s ; int ok = TRUE ; /* ---------------------------------------------------------------------- */ /* check inputs */ /* ---------------------------------------------------------------------- */ RETURN_IF_NULL_COMMON (FALSE) ; RETURN_IF_NULL (A, FALSE) ; RETURN_IF_NULL (Parent, FALSE) ; RETURN_IF_XTYPE_INVALID (A, CHOLMOD_PATTERN, CHOLMOD_ZOMPLEX, FALSE) ; Common->status = CHOLMOD_OK ; /* ---------------------------------------------------------------------- */ /* allocate workspace */ /* ---------------------------------------------------------------------- */ stype = A->stype ; /* s = A->nrow + (stype ? 0 : A->ncol) */ s = CHOLMOD(add_size_t) (A->nrow, (stype ? 0 : A->ncol), &ok) ; if (!ok) { ERROR (CHOLMOD_TOO_LARGE, "problem too large") ; return (FALSE) ; } CHOLMOD(allocate_work) (0, s, 0, Common) ; if (Common->status < CHOLMOD_OK) { return (FALSE) ; /* out of memory */ } ASSERT (CHOLMOD(dump_sparse) (A, "etree", Common) >= 0) ; Iwork = Common->Iwork ; /* ---------------------------------------------------------------------- */ /* get inputs */ /* ---------------------------------------------------------------------- */ ncol = A->ncol ; /* the number of columns of A */ nrow = A->nrow ; /* the number of rows of A */ Ap = A->p ; /* size ncol+1, column pointers for A */ Ai = A->i ; /* the row indices of A */ Anz = A->nz ; /* number of nonzeros in each column of A */ packed = A->packed ; Ancestor = Iwork ; /* size ncol (i/i/l) */ for (j = 0 ; j < ncol ; j++) { Parent [j] = EMPTY ; Ancestor [j] = EMPTY ; } /* ---------------------------------------------------------------------- */ /* compute the etree */ /* ---------------------------------------------------------------------- */ if (stype > 0) { /* ------------------------------------------------------------------ */ /* symmetric (upper) case: compute etree (A) */ /* ------------------------------------------------------------------ */ for (j = 0 ; j < ncol ; j++) { /* for each row i in column j of triu(A), excluding the diagonal */ p = Ap [j] ; pend = (packed) ? (Ap [j+1]) : (p + Anz [j]) ; for ( ; p < pend ; p++) { i = Ai [p] ; if (i < j) { update_etree (i, j, Parent, Ancestor) ; } } } } else if (stype == 0) { /* ------------------------------------------------------------------ */ /* unsymmetric case: compute etree (A'*A) */ /* ------------------------------------------------------------------ */ Prev = Iwork + ncol ; /* size nrow (i/i/l) */ for (i = 0 ; i < nrow ; i++) { Prev [i] = EMPTY ; } for (j = 0 ; j < ncol ; j++) { /* for each row i in column j of A */ p = Ap [j] ; pend = (packed) ? (Ap [j+1]) : (p + Anz [j]) ; for ( ; p < pend ; p++) { /* a graph is constructed dynamically with one path per row * of A. If the ith row of A contains column indices * (j1,j2,j3,j4) then the new graph has edges (j1,j2), (j2,j3), * and (j3,j4). When at node i of this path-graph, all edges * (jprev,j) are considered, where jprev<j */ i = Ai [p] ; jprev = Prev [i] ; if (jprev != EMPTY) { update_etree (jprev, j, Parent, Ancestor) ; } Prev [i] = j ; } } } else { /* ------------------------------------------------------------------ */ /* symmetric case with lower triangular part not supported */ /* ------------------------------------------------------------------ */ ERROR (CHOLMOD_INVALID, "symmetric lower not supported") ; return (FALSE) ; } ASSERT (CHOLMOD(dump_parent) (Parent, ncol, "Parent", Common)) ; return (TRUE) ; } #endif
753670.c
/* * Copyright (c) 2018 XLAB d.o.o. * * 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 <stdio.h> #include "cifer/test.h" #include "cifer/internal/common.h" int main(int argc, char *argv[]) { MunitSuite all_suites[] = { // keygen_suite, // matrix_suite, // prime_suite, // vector_suite, // dlog_suite, // big_suite, // string_suite, // ddh_suite, // ddh_multi_suite, // lwe_suite, // ring_lwe_suite, damgard_suite, // damgard_multi_suite, // lwe_fully_secure_suite, // paillier_suite, // dmcfe_suite, // damgard_dec_multi_suite, // fhipe_suite, // fh_multi_ipe_suite, // policy_suite, // gpsw_suite, // fame_suite, // dippe_suite, // uniform_suite, // normal_suite, // normal_cumulative_suite, // normal_negative_suite, // normal_double_suite, // normal_double_constant_suite, // normal_cdt_suite, // sgp_suite, // data_ser_suite, // fame_ser_suite, // gpsw_ser_suite, {NULL, NULL, NULL, 0, MUNIT_SUITE_OPTION_NONE} }; MunitSuite main_suite = { (char *) "", NULL, all_suites, 1, MUNIT_SUITE_OPTION_NONE }; if (cfe_init()) { perror("Insufficient entropy available for random generation\n"); return CFE_ERR_INIT; } return munit_suite_main(&main_suite, NULL, argc, argv); }
867694.c
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE114_Process_Control__w32_wchar_t_connect_socket_13.c Label Definition File: CWE114_Process_Control__w32.label.xml Template File: sources-sink-13.tmpl.c */ /* * @description * CWE: 114 Process Control * BadSource: connect_socket Read data using a connect socket (client side) * GoodSource: Hard code the full pathname to the library * Sink: * BadSink : Load a dynamic link library * Flow Variant: 13 Control flow: if(GLOBAL_CONST_FIVE==5) and if(GLOBAL_CONST_FIVE!=5) * * */ #include "std_testcase.h" #include <wchar.h> #ifdef _WIN32 #include <winsock2.h> #include <windows.h> #include <direct.h> #pragma comment(lib, "ws2_32") /* include ws2_32.lib when linking */ #define CLOSE_SOCKET closesocket #else /* NOT _WIN32 */ #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <unistd.h> #define INVALID_SOCKET -1 #define SOCKET_ERROR -1 #define CLOSE_SOCKET close #define SOCKET int #endif #define TCP_PORT 27015 #define IP_ADDRESS "127.0.0.1" #ifndef OMITBAD void CWE114_Process_Control__w32_wchar_t_connect_socket_13_bad() { wchar_t * data; wchar_t dataBuffer[100] = L""; data = dataBuffer; if(GLOBAL_CONST_FIVE==5) { { #ifdef _WIN32 WSADATA wsaData; int wsaDataInit = 0; #endif int recvResult; struct sockaddr_in service; wchar_t *replace; SOCKET connectSocket = INVALID_SOCKET; size_t dataLen = wcslen(data); do { #ifdef _WIN32 if (WSAStartup(MAKEWORD(2,2), &wsaData) != NO_ERROR) { break; } wsaDataInit = 1; #endif /* POTENTIAL FLAW: Read data using a connect socket */ connectSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if (connectSocket == INVALID_SOCKET) { break; } memset(&service, 0, sizeof(service)); service.sin_family = AF_INET; service.sin_addr.s_addr = inet_addr(IP_ADDRESS); service.sin_port = htons(TCP_PORT); if (connect(connectSocket, (struct sockaddr*)&service, sizeof(service)) == SOCKET_ERROR) { break; } /* Abort on error or the connection was closed, make sure to recv one * less char than is in the recv_buf in order to append a terminator */ /* Abort on error or the connection was closed */ recvResult = recv(connectSocket, (char *)(data + dataLen), sizeof(wchar_t) * (100 - dataLen - 1), 0); if (recvResult == SOCKET_ERROR || recvResult == 0) { break; } /* Append null terminator */ data[dataLen + recvResult / sizeof(wchar_t)] = L'\0'; /* Eliminate CRLF */ replace = wcschr(data, L'\r'); if (replace) { *replace = L'\0'; } replace = wcschr(data, L'\n'); if (replace) { *replace = L'\0'; } } while (0); if (connectSocket != INVALID_SOCKET) { CLOSE_SOCKET(connectSocket); } #ifdef _WIN32 if (wsaDataInit) { WSACleanup(); } #endif } } { HMODULE hModule; /* POTENTIAL FLAW: If the path to the library is not specified, an attacker may be able to * replace his own file with the intended library */ hModule = LoadLibraryW(data); if (hModule != NULL) { FreeLibrary(hModule); printLine("Library loaded and freed successfully"); } else { printLine("Unable to load library"); } } } #endif /* OMITBAD */ #ifndef OMITGOOD /* goodG2B1() - use goodsource and badsink by changing the GLOBAL_CONST_FIVE==5 to GLOBAL_CONST_FIVE!=5 */ static void goodG2B1() { wchar_t * data; wchar_t dataBuffer[100] = L""; data = dataBuffer; if(GLOBAL_CONST_FIVE!=5) { /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ printLine("Benign, fixed string"); } else { /* FIX: Specify the full pathname for the library */ wcscpy(data, L"C:\\Windows\\System32\\winsrv.dll"); } { HMODULE hModule; /* POTENTIAL FLAW: If the path to the library is not specified, an attacker may be able to * replace his own file with the intended library */ hModule = LoadLibraryW(data); if (hModule != NULL) { FreeLibrary(hModule); printLine("Library loaded and freed successfully"); } else { printLine("Unable to load library"); } } } /* goodG2B2() - use goodsource and badsink by reversing the blocks in the if statement */ static void goodG2B2() { wchar_t * data; wchar_t dataBuffer[100] = L""; data = dataBuffer; if(GLOBAL_CONST_FIVE==5) { /* FIX: Specify the full pathname for the library */ wcscpy(data, L"C:\\Windows\\System32\\winsrv.dll"); } { HMODULE hModule; /* POTENTIAL FLAW: If the path to the library is not specified, an attacker may be able to * replace his own file with the intended library */ hModule = LoadLibraryW(data); if (hModule != NULL) { FreeLibrary(hModule); printLine("Library loaded and freed successfully"); } else { printLine("Unable to load library"); } } } void CWE114_Process_Control__w32_wchar_t_connect_socket_13_good() { goodG2B1(); goodG2B2(); } #endif /* OMITGOOD */ /* Below is the main(). It is only used when building this testcase on * its own for testing or for building a binary to use in testing binary * analysis tools. It is not used when compiling all the testcases as one * application, which is how source code analysis tools are tested. */ #ifdef INCLUDEMAIN int main(int argc, char * argv[]) { /* seed randomness */ srand( (unsigned)time(NULL) ); #ifndef OMITGOOD printLine("Calling good()..."); CWE114_Process_Control__w32_wchar_t_connect_socket_13_good(); printLine("Finished good()"); #endif /* OMITGOOD */ #ifndef OMITBAD printLine("Calling bad()..."); CWE114_Process_Control__w32_wchar_t_connect_socket_13_bad(); printLine("Finished bad()"); #endif /* OMITBAD */ return 0; } #endif
432307.c
static char *sccsid = "@(#)gcos.c 4.4 (Berkeley) 87/12/04"; /* GCOS DEPENDENT PROCEDURES */ /* DEFAULT RULES FOR GCOS */ char *builtin[] { ".SUFFIXES : .d .c .y .lib", ".d.c:", "\t./dtgen $<", ".y.c:", "\t./yacc $<", "\tcopy y.tab.c; /$@", ".y.lib:", "\t./yacc $<", "\t./cc y.tab.c r=$@", ".c.lib:", "\t./cc $< r=$@", 0 }; # define MAXCSIZE 500 # define YZERO 60 int gtcalled 0; /* all kinds of static declarations that must be used.. */ static double day { 64*1000*60*60*24 }; /* length of day in clock ticks */ struct { int lhs:18, rhs:18; }; struct catb { int words[6], name1, name2, passw1, passw2, word10, word11, datcreat, datmod, datused, stuff[6], jjjj:18, tused:18; }; struct { int :3, slot:18; }; /* slot where time from cat. block fits */ struct catdesc { int cat1, cat2, cpass1, cpass2, file1, file2, filep1, filep2, endmark; }; extern int _q_reg, _a_reg; # define A10(x,y) 10*x + y /* interpret the mm/dd/yy format */ struct d9 { int :5, m1:4, :5, m2:4, :9, :5, d1:4, :5, d2:4, :9, :5, y1:4, :5, y2:4 ;}; struct d6 { int :2, m61:4, :2, m62:4, :2, d61:4, :2, d62:4, :2, y61:4, :2, y62:4; }; static day6( d6word ){ /* return the day number of a word in bci format */ int m, y, d; y = A10( d6word.y61, d6word.y62 ); m = A10( d6word.m61, d6word.m62 ); d = A10( d6word.d61, d6word.d62 ); return( d + 31*( m + 12*(y-YZERO) ) ); } static day9( p ) register int *p; { int m, y, d; y = A10( p->y1, p->y2 ); m = A10( p->m1, p->m2 ); d = A10( p->d1, p->d2 ); return( d + 31*( m + 12*(y-YZERO) ) ); } static int dfold( dayno, timeno ){ int kk; kk = ( day*dayno + timeno) / 32768.; } int prestime(){ int date[2]; drldrl( 021, date ); return( dfold( day9(date), _q_reg ) ); } # define DODRL ar[0] = status; ar[1] = &b.cat1; drldrl(30,sp1,sp2); p=ar[0]<<18; static struct { int fn1, fn2; int ftm; } fbb[MAXCSIZE]; static int catsiz; getcat() { register i, *p, j; int asname[4]; struct catdesc b; int sp1, sp2, temp; int ar[2], status[2]; int filbuf[380]; gtcalled = 1; sp1 = ar; sp1 >>= 18; sp2 = filbuf; sp2 >>= 18; sp2.lhs = 19; b.cat1 = b.cat2 = b.file1 = -1; b.cpass1 = b.cpass2 = 0202020202020; DODRL sp2.lhs++; for( i=0; p!=0 && i<MAXCSIZE; ++i ){ fbb[i].fn1 = b.file1 = p->name1; fbb[i].fn2 = b.file2 = p->name2; b.filep1 = p->passw1; b.filep2 = p->passw2; b.endmark = -1; temp = 0; temp.slot = p->tused; fbb[i].ftm = dfold( day6(p->datmod), temp ); DODRL } catsiz = i; } exists( p ) struct nameblock *p; { char *s, *cp, name[13]; int i, *p, bcd[2]; /* cheat about names with slashes -- try opening; if it is openable, it exists, and assume it was made at t=1 (long time ago); otherwise, assume it does not exist */ cp = p->namep; for(s=cp ; *s ; ++s) if(*s == '/') if(i = copen(cp,'r') < 0) return(0); else { cclose(i); return(1); } if(gtcalled == 0) getcat(); p = name; for( i=0; *cp; ++i ) name[i] = *cp++; while( i<12 ) name[i++] = ' '; f9to6( *p, bcd[0], 12 ); for ( i=0; i<catsiz; ++i ){ if( fbb[i].fn1 == bcd[0] && fbb[i].fn2 == bcd[1] ) return( fbb[i].ftm ); } return( 0 ); } #include "defs" static char n13[13]; static char *n13end &n13[12]; struct depblock *srchdir(pat, mkchain, nextdbl) char *pat; /* pattern to be matched in directory */ int mkchain; /* nonzero if results to be remembered */ struct depblock *nextdbl; /* final value for chain */ { int dirf; int i, nread; char *dirname, *dirpref, *endir, *filepat, *p, temp[BUFSIZ]; char fullname[BUFSIZ], *p1, *p2, *copys(); struct nameblock *q; struct depblock *thisdbl; struct pattern *patp; int *intp1, *intp2; if(gtcalled == 0) getcat(); thisdbl=0; if(mkchain == 0) for(patp=firstpat ; patp!=0 ; patp = patp->nxtpattern) if(! unequal(pat, patp->patval)) return(0); patp = ALLOC(pattern); patp->nxtpattern = firstpat; firstpat = patp; patp->patval = copys(pat); endir = 0; for(p=pat; *p!='\0'; ++p) if(*p=='/') endir = p; if(endir==0) { dirname = ""; dirpref = ""; filepat = pat; } else { fatal("File name has an embedded slash"); dirname = pat; *endir = '\0'; dirpref = concat(dirname, "/", temp); filepat = endir+1; } for(i=0;i<catsiz;++i) { intp1 = &fbb[i].fn1; intp2 = n13; f6to9(*intp1, *intp2, 12); for(p1=n13; p1<n13end && *p1!=' ' ; ++p1) if('A'<=*p1 && *p1<='Z') *p1 += ('a'-'A'); *p1 = '\0'; if( amatch(n13,filepat) ) { concat(dirpref,n13,fullname); if( (q=srchname(fullname)) ==0) q = makename(copys(fullname)); if(mkchain) { thisdbl = ALLOC(depblock); thisdbl->nextp = nextdbl; thisdbl->depname = q; nextdbl = thisdbl; } } } if(endir != 0) *endir = '/'; return(thisdbl); } /* stolen from glob through find */ amatch(s, p) char *s, *p; { register int cc, scc, k; int c, lc; scc = *s; lc = 077777; switch (c = *p) { case '[': k = 0; while (cc = *++p) { switch (cc) { case ']': if (k) return(amatch(++s, ++p)); else return(0); case '-': k |= lc <= scc & scc <= (cc=p[1]); } if (scc==(lc=cc)) k++; } return(0); case '?': caseq: if(scc) return(amatch(++s, ++p)); return(0); case '*': return(umatch(s, ++p)); case 0: return(!scc); } if (c==scc) goto caseq; return(0); } umatch(s, p) char *s, *p; { if(*p==0) return(1); while(*s) if (amatch(s++,p)) return(1); return(0); } dosys(comstring,nohalt) char *comstring; int nohalt; { char *p; for(p=comstring ; *p!='\0' ; ++p); if( p-comstring > 80) fatal("Command string longer than 80 characters"); system(comstring); return(0); } touch(s) char *s; { fprintf(stderr, "touch not yet implemented on GCOS\n"); cexit(2); }
415441.c
/* * Copyright (c) 2012-2014 Pavol Rusnak <[email protected]> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #include <stdio.h> #include <string.h> #include "qr_encode.h" /** * The same as test.c, only it reads from the first argument * and prints 0s and 1s instead of picture. * * It's used for compiling to JavaScript, because we can set up * argument and read 1/0s more easily */ int main(int argc, char **argv) { int side, i, j, a; uint8_t bitdata[QR_MAX_BITDATA]; if (argc<2){ printf("1"); return 1; } char *str=argv[1]; side = qr_encode(QR_LEVEL_M, 0, str, 0, bitdata); //for (i = 0; i < side + 2; i++) printf("1"); for (i = 0; i < side; i++) { // printf("1"); for (j = 0; j < side; j++) { a = i * side + j; printf((bitdata[a / 8] & (1 << (7 - a % 8))) ? "0" : "1"); } // printf("1"); } //for (i = 0; i < side + 2; i++) printf("1"); return 0; }
980039.c
/* inflate.c -- zlib decompression * Copyright (C) 1995-2016 Mark Adler * For conditions of distribution and use, see copyright notice in zlib.h */ /* * Change history: * * 1.2.beta0 24 Nov 2002 * - First version -- complete rewrite of inflate to simplify code, avoid * creation of window when not needed, minimize use of window when it is * needed, make inffast.c even faster, implement gzip decoding, and to * improve code readability and style over the previous zlib inflate code * * 1.2.beta1 25 Nov 2002 * - Use pointers for available input and output checking in inffast.c * - Remove input and output counters in inffast.c * - Change inffast.c entry and loop from avail_in >= 7 to >= 6 * - Remove unnecessary second byte pull from length extra in inffast.c * - Unroll direct copy to three copies per loop in inffast.c * * 1.2.beta2 4 Dec 2002 * - Change external routine names to reduce potential conflicts * - Correct filename to inffixed.h for fixed tables in inflate.c * - Make hbuf[] unsigned char to match parameter type in inflate.c * - Change strm->next_out[-state->offset] to *(strm->next_out - state->offset) * to avoid negation problem on Alphas (64 bit) in inflate.c * * 1.2.beta3 22 Dec 2002 * - Add comments on state->bits assertion in inffast.c * - Add comments on op field in inftrees.h * - Fix bug in reuse of allocated window after inflateReset() * - Remove bit fields--back to byte structure for speed * - Remove distance extra == 0 check in inflate_fast()--only helps for lengths * - Change post-increments to pre-increments in inflate_fast(), PPC biased? * - Add compile time option, POSTINC, to use post-increments instead (Intel?) * - Make MATCH copy in inflate() much faster for when inflate_fast() not used * - Use local copies of stream next and avail values, as well as local bit * buffer and bit count in inflate()--for speed when inflate_fast() not used * * 1.2.beta4 1 Jan 2003 * - Split ptr - 257 statements in inflate_table() to avoid compiler warnings * - Move a comment on output buffer sizes from inffast.c to inflate.c * - Add comments in inffast.c to introduce the inflate_fast() routine * - Rearrange window copies in inflate_fast() for speed and simplification * - Unroll last copy for window match in inflate_fast() * - Use local copies of window variables in inflate_fast() for speed * - Pull out common wnext == 0 case for speed in inflate_fast() * - Make op and len in inflate_fast() unsigned for consistency * - Add FAR to lcode and dcode declarations in inflate_fast() * - Simplified bad distance check in inflate_fast() * - Added inflateBackInit(), inflateBack(), and inflateBackEnd() in new * source file infback.c to provide a call-back interface to inflate for * programs like gzip and unzip -- uses window as output buffer to avoid * window copying * * 1.2.beta5 1 Jan 2003 * - Improved inflateBack() interface to allow the caller to provide initial * input in strm. * - Fixed stored blocks bug in inflateBack() * * 1.2.beta6 4 Jan 2003 * - Added comments in inffast.c on effectiveness of POSTINC * - Typecasting all around to reduce compiler warnings * - Changed loops from while (1) or do {} while (1) to for (;;), again to * make compilers happy * - Changed type of window in inflateBackInit() to unsigned char * * * 1.2.beta7 27 Jan 2003 * - Changed many types to unsigned or unsigned short to avoid warnings * - Added inflateCopy() function * * 1.2.0 9 Mar 2003 * - Changed inflateBack() interface to provide separate opaque descriptors * for the in() and out() functions * - Changed inflateBack() argument and in_func typedef to swap the length * and buffer address return values for the input function * - Check next_in and next_out for Z_NULL on entry to inflate() * * The history for versions after 1.2.0 are in ChangeLog in zlib distribution. */ #include "libdeflate/libdeflate.h" #include "zutil.h" #include "inftrees.h" #include "inflate.h" #include "inffast.h" #ifdef MAKEFIXED # ifndef BUILDFIXED # define BUILDFIXED # endif #endif /* function prototypes */ local int inflateStateCheck OF((z_streamp strm)); local void fixedtables OF((struct inflate_state FAR *state)); local int updatewindow OF((z_streamp strm, const unsigned char FAR *end, unsigned copy)); #ifdef BUILDFIXED void makefixed OF((void)); #endif local unsigned syncsearch OF((unsigned FAR *have, const unsigned char FAR *buf, unsigned len)); local int inflateStateCheck(strm) z_streamp strm; { struct inflate_state FAR *state; if (strm == Z_NULL || strm->zalloc == (alloc_func)0 || strm->zfree == (free_func)0) return 1; state = (struct inflate_state FAR *)strm->state; if (state == Z_NULL || state->strm != strm || state->mode < HEAD || state->mode > SYNC) return 1; return 0; } int ZEXPORT inflateResetKeep(strm) z_streamp strm; { struct inflate_state FAR *state; if (inflateStateCheck(strm)) return Z_STREAM_ERROR; state = (struct inflate_state FAR *)strm->state; strm->total_in = 0; // note: we don't reset total_ever_in (Divon Lan) strm->total_out = state->total = 0; strm->msg = Z_NULL; if (state->wrap) /* to support ill-conceived Java test suite */ strm->adler = state->wrap & 1; state->mode = HEAD; state->last = 0; state->havedict = 0; state->dmax = 32768U; state->head = Z_NULL; state->hold = 0; state->bits = 0; state->lencode = state->distcode = state->next = state->codes; state->sane = 1; state->back = -1; Tracev((stderr, "inflate: reset\n")); return Z_OK; } int ZEXPORT inflateReset(strm) z_streamp strm; { struct inflate_state FAR *state; if (inflateStateCheck(strm)) return Z_STREAM_ERROR; state = (struct inflate_state FAR *)strm->state; state->wsize = 0; state->whave = 0; state->wnext = 0; return inflateResetKeep(strm); } int ZEXPORT inflateReset2(strm, windowBits) z_streamp strm; int windowBits; { int wrap; struct inflate_state FAR *state; /* get the state */ if (inflateStateCheck(strm)) return Z_STREAM_ERROR; state = (struct inflate_state FAR *)strm->state; /* extract wrap request from windowBits parameter */ if (windowBits < 0) { wrap = 0; windowBits = -windowBits; } else { wrap = (windowBits >> 4) + 5; #ifdef GUNZIP if (windowBits < 48) windowBits &= 15; #endif } /* set number of window bits, free window if different */ if (windowBits && (windowBits < 8 || windowBits > 15)) return Z_STREAM_ERROR; if (state->window != Z_NULL && state->wbits != (unsigned)windowBits) { ZFREE(strm, state->window); state->window = Z_NULL; } /* update state and reset the rest of it */ state->wrap = wrap; state->wbits = (unsigned)windowBits; return inflateReset(strm); } int ZEXPORT inflateInit2_(strm, windowBits, version, stream_size) z_streamp strm; int windowBits; const char *version; int stream_size; { int ret; struct inflate_state FAR *state; if (version == Z_NULL || version[0] != ZLIB_VERSION[0] || stream_size != (int)(sizeof(z_stream))) return Z_VERSION_ERROR; if (strm == Z_NULL) return Z_STREAM_ERROR; strm->msg = Z_NULL; /* in case we return an error */ if (strm->zalloc == (alloc_func)0) { #ifdef Z_SOLO return Z_STREAM_ERROR; #else strm->zalloc = zcalloc; strm->opaque = (voidpf)0; #endif } if (strm->zfree == (free_func)0) #ifdef Z_SOLO return Z_STREAM_ERROR; #else strm->zfree = zcfree; #endif state = (struct inflate_state FAR *) ZALLOC(strm, 1, sizeof(struct inflate_state)); if (state == Z_NULL) return Z_MEM_ERROR; Tracev((stderr, "inflate: allocated\n")); strm->state = (struct internal_state FAR *)state; state->strm = strm; state->window = Z_NULL; state->mode = HEAD; /* to pass state test in inflateReset2() */ ret = inflateReset2(strm, windowBits); if (ret != Z_OK) { ZFREE(strm, state); strm->state = Z_NULL; } return ret; } int ZEXPORT inflateInit_(strm, version, stream_size) z_streamp strm; const char *version; int stream_size; { return inflateInit2_(strm, DEF_WBITS, version, stream_size); } int ZEXPORT inflatePrime(strm, bits, value) z_streamp strm; int bits; int value; { struct inflate_state FAR *state; if (inflateStateCheck(strm)) return Z_STREAM_ERROR; state = (struct inflate_state FAR *)strm->state; if (bits < 0) { state->hold = 0; state->bits = 0; return Z_OK; } if (bits > 16 || state->bits + (uInt)bits > 32) return Z_STREAM_ERROR; value &= (1L << bits) - 1; state->hold += (unsigned)value << state->bits; state->bits += (uInt)bits; return Z_OK; } /* Return state with length and distance decoding tables and index sizes set to fixed code decoding. Normally this returns fixed tables from inffixed.h. If BUILDFIXED is defined, then instead this routine builds the tables the first time it's called, and returns those tables the first time and thereafter. This reduces the size of the code by about 2K bytes, in exchange for a little execution time. However, BUILDFIXED should not be used for threaded applications, since the rewriting of the tables and virgin may not be thread-safe. */ local void fixedtables(state) struct inflate_state FAR *state; { #ifdef BUILDFIXED static int virgin = 1; static code *lenfix, *distfix; static code fixed[544]; /* build fixed huffman tables if first call (may not be thread safe) */ if (virgin) { unsigned sym, bits; static code *next; /* literal/length table */ sym = 0; while (sym < 144) state->lens[sym++] = 8; while (sym < 256) state->lens[sym++] = 9; while (sym < 280) state->lens[sym++] = 7; while (sym < 288) state->lens[sym++] = 8; next = fixed; lenfix = next; bits = 9; inflate_table(LENS, state->lens, 288, &(next), &(bits), state->work); /* distance table */ sym = 0; while (sym < 32) state->lens[sym++] = 5; distfix = next; bits = 5; inflate_table(DISTS, state->lens, 32, &(next), &(bits), state->work); /* do this just once */ virgin = 0; } #else /* !BUILDFIXED */ # include "inffixed.h" #endif /* BUILDFIXED */ state->lencode = lenfix; state->lenbits = 9; state->distcode = distfix; state->distbits = 5; } #ifdef MAKEFIXED #include <stdio.h> /* Write out the inffixed.h that is #include'd above. Defining MAKEFIXED also defines BUILDFIXED, so the tables are built on the fly. makefixed() writes those tables to stdout, which would be piped to inffixed.h. A small program can simply call makefixed to do this: void makefixed(void); int main(void) { makefixed(); return 0; } Then that can be linked with zlib built with MAKEFIXED defined and run: a.out > inffixed.h */ void makefixed() { unsigned low, size; struct inflate_state state; fixedtables(&state); puts(" /* inffixed.h -- table for decoding fixed codes"); puts(" * Generated automatically by makefixed()."); puts(" */"); puts(""); puts(" /* WARNING: this file should *not* be used by applications."); puts(" It is part of the implementation of this library and is"); puts(" subject to change. Applications should only use zlib.h."); puts(" */"); puts(""); size = 1U << 9; printf(" static const code lenfix[%u] = {", size); low = 0; for (;;) { if ((low % 7) == 0) printf("\n "); printf("{%u,%u,%d}", (low & 127) == 99 ? 64 : state.lencode[low].op, state.lencode[low].bits, state.lencode[low].val); if (++low == size) break; putchar(','); } puts("\n };"); size = 1U << 5; printf("\n static const code distfix[%u] = {", size); low = 0; for (;;) { if ((low % 6) == 0) printf("\n "); printf("{%u,%u,%d}", state.distcode[low].op, state.distcode[low].bits, state.distcode[low].val); if (++low == size) break; putchar(','); } puts("\n };"); } #endif /* MAKEFIXED */ /* Update the window with the last wsize (normally 32K) bytes written before returning. If window does not exist yet, create it. This is only called when a window is already in use, or when output has been written during this inflate call, but the end of the deflate stream has not been reached yet. It is also called to create a window for dictionary data when a dictionary is loaded. Providing output buffers larger than 32K to inflate() should provide a speed advantage, since only the last 32K of output is copied to the sliding window upon return from inflate(), and since all distances after the first 32K of output will fall in the output data, making match copies simpler and faster. The advantage may be dependent on the size of the processor's data caches. */ local int updatewindow(strm, end, copy) z_streamp strm; const Bytef *end; unsigned copy; { struct inflate_state FAR *state; unsigned dist; state = (struct inflate_state FAR *)strm->state; /* if it hasn't been done already, allocate space for the window */ if (state->window == Z_NULL) { state->window = (unsigned char FAR *) ZALLOC(strm, 1U << state->wbits, sizeof(unsigned char)); if (state->window == Z_NULL) return 1; } /* if window not in use yet, initialize */ if (state->wsize == 0) { state->wsize = 1U << state->wbits; state->wnext = 0; state->whave = 0; } /* copy state->wsize or less output bytes into the circular window */ if (copy >= state->wsize) { zmemcpy(state->window, end - state->wsize, state->wsize); state->wnext = 0; state->whave = state->wsize; } else { dist = state->wsize - state->wnext; if (dist > copy) dist = copy; zmemcpy(state->window + state->wnext, end - copy, dist); copy -= dist; if (copy) { zmemcpy(state->window, end - copy, copy); state->wnext = copy; state->whave = state->wsize; } else { state->wnext += dist; if (state->wnext == state->wsize) state->wnext = 0; if (state->whave < state->wsize) state->whave += dist; } } return 0; } /* Macros for inflate(): */ /* check function to use adler32() for zlib or crc32() for gzip */ #ifdef GUNZIP # define UPDATE(check, buf, len) \ (state->flags ? libdeflate_crc32(check, buf, len) : libdeflate_adler32(check, buf, len)) #else # define UPDATE(check, buf, len) libdeflate_adler32(check, buf, len) #endif /* check macros for header crc */ #ifdef GUNZIP # define CRC2(check, word) \ do { \ hbuf[0] = (unsigned char)(word); \ hbuf[1] = (unsigned char)((word) >> 8); \ check = libdeflate_crc32(check, hbuf, 2); \ } while (0) # define CRC4(check, word) \ do { \ hbuf[0] = (unsigned char)(word); \ hbuf[1] = (unsigned char)((word) >> 8); \ hbuf[2] = (unsigned char)((word) >> 16); \ hbuf[3] = (unsigned char)((word) >> 24); \ check = libdeflate_crc32(check, hbuf, 4); \ } while (0) #endif /* Load registers with state in inflate() for speed */ #define LOAD() \ do { \ put = strm->next_out; \ left = strm->avail_out; \ next = strm->next_in; \ have = strm->avail_in; \ hold = state->hold; \ bits = state->bits; \ } while (0) /* Restore state from registers in inflate() */ #define RESTORE() \ do { \ strm->next_out = put; \ strm->avail_out = left; \ strm->next_in = next; \ strm->avail_in = have; \ state->hold = hold; \ state->bits = bits; \ } while (0) /* Clear the input bit accumulator */ #define INITBITS() \ do { \ hold = 0; \ bits = 0; \ } while (0) /* Get a byte of input into the bit accumulator, or return from inflate() if there is no input available. */ #define PULLBYTE() \ do { \ if (have == 0) goto inf_leave; \ have--; \ hold += (unsigned long)(*next++) << bits; \ bits += 8; \ } while (0) /* Assure that there are at least n bits in the bit accumulator. If there is not enough available input to do that, then return from inflate(). */ #define NEEDBITS(n) \ do { \ while (bits < (unsigned)(n)) \ PULLBYTE(); \ } while (0) /* Return the low n bits of the bit accumulator (n < 16) */ #define BITS(n) \ ((unsigned)hold & ((1U << (n)) - 1)) /* Remove n bits from the bit accumulator */ #define DROPBITS(n) \ do { \ hold >>= (n); \ bits -= (unsigned)(n); \ } while (0) /* Remove zero to seven bits as needed to go to a byte boundary */ #define BYTEBITS() \ do { \ hold >>= bits & 7; \ bits -= bits & 7; \ } while (0) /* inflate() uses a state machine to process as much input data and generate as much output data as possible before returning. The state machine is structured roughly as follows: for (;;) switch (state) { ... case STATEn: if (not enough input data or output space to make progress) return; ... make progress ... state = STATEm; break; ... } so when inflate() is called again, the same case is attempted again, and if the appropriate resources are provided, the machine proceeds to the next state. The NEEDBITS() macro is usually the way the state evaluates whether it can proceed or should return. NEEDBITS() does the return if the requested bits are not available. The typical use of the BITS macros is: NEEDBITS(n); ... do something with BITS(n) ... DROPBITS(n); where NEEDBITS(n) either returns from inflate() if there isn't enough input left to load n bits into the accumulator, or it continues. BITS(n) gives the low n bits in the accumulator. When done, DROPBITS(n) drops the low n bits off the accumulator. INITBITS() clears the accumulator and sets the number of available bits to zero. BYTEBITS() discards just enough bits to put the accumulator on a byte boundary. After BYTEBITS() and a NEEDBITS(8), then BITS(8) would return the next byte in the stream. NEEDBITS(n) uses PULLBYTE() to get an available byte of input, or to return if there is no input available. The decoding of variable length codes uses PULLBYTE() directly in order to pull just enough bytes to decode the next code, and no more. Some states loop until they get enough input, making sure that enough state information is maintained to continue the loop where it left off if NEEDBITS() returns in the loop. For example, want, need, and keep would all have to actually be part of the saved state in case NEEDBITS() returns: case STATEw: while (want < need) { NEEDBITS(n); keep[want++] = BITS(n); DROPBITS(n); } state = STATEx; case STATEx: As shown above, if the next state is also the next case, then the break is omitted. A state may also return if there is not enough output space available to complete that state. Those states are copying stored data, writing a literal byte, and copying a matching string. When returning, a "goto inf_leave" is used to update the total counters, update the check value, and determine whether any progress has been made during that inflate() call in order to return the proper return code. Progress is defined as a change in either strm->avail_in or strm->avail_out. When there is a window, goto inf_leave will update the window with the last output written. If a goto inf_leave occurs in the middle of decompression and there is no window currently, goto inf_leave will create one and copy output to the window for the next call of inflate(). In this implementation, the flush parameter of inflate() only affects the return code (per zlib.h). inflate() always writes as much as possible to strm->next_out, given the space available and the provided input--the effect documented in zlib.h of Z_SYNC_FLUSH. Furthermore, inflate() always defers the allocation of and copying into a sliding window until necessary, which provides the effect documented in zlib.h for Z_FINISH when the entire input stream available. So the only thing the flush parameter actually does is: when flush is set to Z_FINISH, inflate() cannot return Z_OK. Instead it will return Z_BUF_ERROR if it has not reached the end of the stream. */ int ZEXPORT inflate(strm, flush) z_streamp strm; int flush; { struct inflate_state FAR *state; z_const unsigned char FAR *next; /* next input */ unsigned char FAR *put; /* next output */ unsigned have, left; /* available input and output */ unsigned long hold; /* bit buffer */ unsigned bits; /* bits in bit buffer */ unsigned in, out; /* save starting available input and output */ unsigned copy; /* number of stored or match bytes to copy */ unsigned char FAR *from; /* where to copy match bytes from */ code here; /* current decoding table entry */ code last; /* parent table entry */ unsigned len; /* length to copy for repeats, bits to drop */ int ret; /* return code */ #ifdef GUNZIP unsigned char hbuf[4]; /* buffer for gzip header crc calculation */ #endif static const unsigned short order[19] = /* permutation of code lengths */ {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15}; if (inflateStateCheck(strm) || strm->next_out == Z_NULL || (strm->next_in == Z_NULL && strm->avail_in != 0)) return Z_STREAM_ERROR; state = (struct inflate_state FAR *)strm->state; if (state->mode == TYPE) state->mode = TYPEDO; /* skip check */ LOAD(); in = have; out = left; ret = Z_OK; for (;;) switch (state->mode) { case HEAD: if (state->wrap == 0) { state->mode = TYPEDO; break; } NEEDBITS(16); #ifdef GUNZIP if ((state->wrap & 2) && hold == 0x8b1f) { /* gzip header */ if (state->wbits == 0) state->wbits = 15; state->check = libdeflate_crc32(0L, Z_NULL, 0); CRC2(state->check, hold); INITBITS(); state->mode = FLAGS; break; } state->flags = 0; /* expect zlib header */ if (state->head != Z_NULL) state->head->done = -1; if (!(state->wrap & 1) || /* check if zlib header allowed */ #else if ( #endif ((BITS(8) << 8) + (hold >> 8)) % 31) { strm->msg = (char *)"incorrect header check"; state->mode = BAD; break; } if (BITS(4) != Z_DEFLATED) { strm->msg = (char *)"unknown compression method"; state->mode = BAD; break; } DROPBITS(4); len = BITS(4) + 8; if (state->wbits == 0) state->wbits = len; if (len > 15 || len > state->wbits) { strm->msg = (char *)"invalid window size"; state->mode = BAD; break; } state->dmax = 1U << len; Tracev((stderr, "inflate: zlib header ok\n")); strm->adler = state->check = libdeflate_adler32(0L, Z_NULL, 0); state->mode = hold & 0x200 ? DICTID : TYPE; INITBITS(); break; #ifdef GUNZIP case FLAGS: NEEDBITS(16); state->flags = (int)(hold); if ((state->flags & 0xff) != Z_DEFLATED) { strm->msg = (char *)"unknown compression method"; state->mode = BAD; break; } if (state->flags & 0xe000) { strm->msg = (char *)"unknown header flags set"; state->mode = BAD; break; } if (state->head != Z_NULL) state->head->text = (int)((hold >> 8) & 1); if ((state->flags & 0x0200) && (state->wrap & 4)) CRC2(state->check, hold); INITBITS(); state->mode = TIME; case TIME: NEEDBITS(32); if (state->head != Z_NULL) state->head->time = hold; if ((state->flags & 0x0200) && (state->wrap & 4)) CRC4(state->check, hold); INITBITS(); state->mode = OS; case OS: NEEDBITS(16); if (state->head != Z_NULL) { state->head->xflags = (int)(hold & 0xff); state->head->os = (int)(hold >> 8); } if ((state->flags & 0x0200) && (state->wrap & 4)) CRC2(state->check, hold); INITBITS(); state->mode = EXLEN; case EXLEN: if (state->flags & 0x0400) { NEEDBITS(16); state->length = (unsigned)(hold); if (state->head != Z_NULL) state->head->extra_len = (unsigned)hold; if ((state->flags & 0x0200) && (state->wrap & 4)) CRC2(state->check, hold); INITBITS(); } else if (state->head != Z_NULL) state->head->extra = Z_NULL; state->mode = EXTRA; case EXTRA: if (state->flags & 0x0400) { copy = state->length; if (copy > have) copy = have; if (copy) { if (state->head != Z_NULL && state->head->extra != Z_NULL) { len = state->head->extra_len - state->length; zmemcpy(state->head->extra + len, next, len + copy > state->head->extra_max ? state->head->extra_max - len : copy); } if ((state->flags & 0x0200) && (state->wrap & 4)) state->check = libdeflate_crc32(state->check, next, copy); have -= copy; next += copy; state->length -= copy; } if (state->length) goto inf_leave; } state->length = 0; state->mode = NAME; case NAME: if (state->flags & 0x0800) { if (have == 0) goto inf_leave; copy = 0; do { len = (unsigned)(next[copy++]); if (state->head != Z_NULL && state->head->name != Z_NULL && state->length < state->head->name_max) state->head->name[state->length++] = (Bytef)len; } while (len && copy < have); if ((state->flags & 0x0200) && (state->wrap & 4)) state->check = libdeflate_crc32(state->check, next, copy); have -= copy; next += copy; if (len) goto inf_leave; } else if (state->head != Z_NULL) state->head->name = Z_NULL; state->length = 0; state->mode = COMMENT; case COMMENT: if (state->flags & 0x1000) { if (have == 0) goto inf_leave; copy = 0; do { len = (unsigned)(next[copy++]); if (state->head != Z_NULL && state->head->comment != Z_NULL && state->length < state->head->comm_max) state->head->comment[state->length++] = (Bytef)len; } while (len && copy < have); if ((state->flags & 0x0200) && (state->wrap & 4)) state->check = libdeflate_crc32(state->check, next, copy); have -= copy; next += copy; if (len) goto inf_leave; } else if (state->head != Z_NULL) state->head->comment = Z_NULL; state->mode = HCRC; case HCRC: if (state->flags & 0x0200) { NEEDBITS(16); if ((state->wrap & 4) && hold != (state->check & 0xffff)) { strm->msg = (char *)"header crc mismatch"; state->mode = BAD; break; } INITBITS(); } if (state->head != Z_NULL) { state->head->hcrc = (int)((state->flags >> 9) & 1); state->head->done = 1; } strm->adler = state->check = libdeflate_crc32(0L, Z_NULL, 0); state->mode = TYPE; break; #endif case DICTID: NEEDBITS(32); strm->adler = state->check = ZSWAP32(hold); INITBITS(); state->mode = DICT; case DICT: if (state->havedict == 0) { RESTORE(); return Z_NEED_DICT; } strm->adler = state->check = libdeflate_adler32(0L, Z_NULL, 0); state->mode = TYPE; case TYPE: if (flush == Z_BLOCK || flush == Z_TREES) goto inf_leave; case TYPEDO: if (state->last) { BYTEBITS(); state->mode = CHECK; break; } NEEDBITS(3); state->last = BITS(1); DROPBITS(1); switch (BITS(2)) { case 0: /* stored block */ Tracev((stderr, "inflate: stored block%s\n", state->last ? " (last)" : "")); state->mode = STORED; break; case 1: /* fixed block */ fixedtables(state); Tracev((stderr, "inflate: fixed codes block%s\n", state->last ? " (last)" : "")); state->mode = LEN_; /* decode codes */ if (flush == Z_TREES) { DROPBITS(2); goto inf_leave; } break; case 2: /* dynamic block */ Tracev((stderr, "inflate: dynamic codes block%s\n", state->last ? " (last)" : "")); state->mode = TABLE; break; case 3: strm->msg = (char *)"invalid block type"; state->mode = BAD; } DROPBITS(2); break; case STORED: BYTEBITS(); /* go to byte boundary */ NEEDBITS(32); if ((hold & 0xffff) != ((hold >> 16) ^ 0xffff)) { strm->msg = (char *)"invalid stored block lengths"; state->mode = BAD; break; } state->length = (unsigned)hold & 0xffff; Tracev((stderr, "inflate: stored length %u\n", state->length)); INITBITS(); state->mode = COPY_; if (flush == Z_TREES) goto inf_leave; case COPY_: state->mode = COPY; case COPY: copy = state->length; if (copy) { if (copy > have) copy = have; if (copy > left) copy = left; if (copy == 0) goto inf_leave; zmemcpy(put, next, copy); have -= copy; next += copy; left -= copy; put += copy; state->length -= copy; break; } Tracev((stderr, "inflate: stored end\n")); state->mode = TYPE; break; case TABLE: NEEDBITS(14); state->nlen = BITS(5) + 257; DROPBITS(5); state->ndist = BITS(5) + 1; DROPBITS(5); state->ncode = BITS(4) + 4; DROPBITS(4); #ifndef PKZIP_BUG_WORKAROUND if (state->nlen > 286 || state->ndist > 30) { strm->msg = (char *)"too many length or distance symbols"; state->mode = BAD; break; } #endif Tracev((stderr, "inflate: table sizes ok\n")); state->have = 0; state->mode = LENLENS; case LENLENS: while (state->have < state->ncode) { NEEDBITS(3); state->lens[order[state->have++]] = (unsigned short)BITS(3); DROPBITS(3); } while (state->have < 19) state->lens[order[state->have++]] = 0; state->next = state->codes; state->lencode = (const code FAR *)(state->next); state->lenbits = 7; ret = inflate_table(CODES, state->lens, 19, &(state->next), &(state->lenbits), state->work); if (ret) { strm->msg = (char *)"invalid code lengths set"; state->mode = BAD; break; } Tracev((stderr, "inflate: code lengths ok\n")); state->have = 0; state->mode = CODELENS; case CODELENS: while (state->have < state->nlen + state->ndist) { for (;;) { here = state->lencode[BITS(state->lenbits)]; if ((unsigned)(here.bits) <= bits) break; PULLBYTE(); } if (here.val < 16) { DROPBITS(here.bits); state->lens[state->have++] = here.val; } else { if (here.val == 16) { NEEDBITS(here.bits + 2); DROPBITS(here.bits); if (state->have == 0) { strm->msg = (char *)"invalid bit length repeat"; state->mode = BAD; break; } len = state->lens[state->have - 1]; copy = 3 + BITS(2); DROPBITS(2); } else if (here.val == 17) { NEEDBITS(here.bits + 3); DROPBITS(here.bits); len = 0; copy = 3 + BITS(3); DROPBITS(3); } else { NEEDBITS(here.bits + 7); DROPBITS(here.bits); len = 0; copy = 11 + BITS(7); DROPBITS(7); } if (state->have + copy > state->nlen + state->ndist) { strm->msg = (char *)"invalid bit length repeat"; state->mode = BAD; break; } while (copy--) state->lens[state->have++] = (unsigned short)len; } } /* handle error breaks in while */ if (state->mode == BAD) break; /* check for end-of-block code (better have one) */ if (state->lens[256] == 0) { strm->msg = (char *)"invalid code -- missing end-of-block"; state->mode = BAD; break; } /* build code tables -- note: do not change the lenbits or distbits values here (9 and 6) without reading the comments in inftrees.h concerning the ENOUGH constants, which depend on those values */ state->next = state->codes; state->lencode = (const code FAR *)(state->next); state->lenbits = 9; ret = inflate_table(LENS, state->lens, state->nlen, &(state->next), &(state->lenbits), state->work); if (ret) { strm->msg = (char *)"invalid literal/lengths set"; state->mode = BAD; break; } state->distcode = (const code FAR *)(state->next); state->distbits = 6; ret = inflate_table(DISTS, state->lens + state->nlen, state->ndist, &(state->next), &(state->distbits), state->work); if (ret) { strm->msg = (char *)"invalid distances set"; state->mode = BAD; break; } Tracev((stderr, "inflate: codes ok\n")); state->mode = LEN_; if (flush == Z_TREES) goto inf_leave; case LEN_: state->mode = LEN; case LEN: if (have >= 6 && left >= 258) { RESTORE(); inflate_fast(strm, out); LOAD(); if (state->mode == TYPE) state->back = -1; break; } state->back = 0; for (;;) { here = state->lencode[BITS(state->lenbits)]; if ((unsigned)(here.bits) <= bits) break; PULLBYTE(); } if (here.op && (here.op & 0xf0) == 0) { last = here; for (;;) { here = state->lencode[last.val + (BITS(last.bits + last.op) >> last.bits)]; if ((unsigned)(last.bits + here.bits) <= bits) break; PULLBYTE(); } DROPBITS(last.bits); state->back += last.bits; } DROPBITS(here.bits); state->back += here.bits; state->length = (unsigned)here.val; if ((int)(here.op) == 0) { Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ? "inflate: literal '%c'\n" : "inflate: literal 0x%02x\n", here.val)); state->mode = LIT; break; } if (here.op & 32) { Tracevv((stderr, "inflate: end of block\n")); state->back = -1; state->mode = TYPE; break; } if (here.op & 64) { strm->msg = (char *)"invalid literal/length code"; state->mode = BAD; break; } state->extra = (unsigned)(here.op) & 15; state->mode = LENEXT; case LENEXT: if (state->extra) { NEEDBITS(state->extra); state->length += BITS(state->extra); DROPBITS(state->extra); state->back += state->extra; } Tracevv((stderr, "inflate: length %u\n", state->length)); state->was = state->length; state->mode = DIST; case DIST: for (;;) { here = state->distcode[BITS(state->distbits)]; if ((unsigned)(here.bits) <= bits) break; PULLBYTE(); } if ((here.op & 0xf0) == 0) { last = here; for (;;) { here = state->distcode[last.val + (BITS(last.bits + last.op) >> last.bits)]; if ((unsigned)(last.bits + here.bits) <= bits) break; PULLBYTE(); } DROPBITS(last.bits); state->back += last.bits; } DROPBITS(here.bits); state->back += here.bits; if (here.op & 64) { strm->msg = (char *)"invalid distance code"; state->mode = BAD; break; } state->offset = (unsigned)here.val; state->extra = (unsigned)(here.op) & 15; state->mode = DISTEXT; case DISTEXT: if (state->extra) { NEEDBITS(state->extra); state->offset += BITS(state->extra); DROPBITS(state->extra); state->back += state->extra; } #ifdef INFLATE_STRICT if (state->offset > state->dmax) { strm->msg = (char *)"invalid distance too far back"; state->mode = BAD; break; } #endif Tracevv((stderr, "inflate: distance %u\n", state->offset)); state->mode = MATCH; case MATCH: if (left == 0) goto inf_leave; copy = out - left; if (state->offset > copy) { /* copy from window */ copy = state->offset - copy; if (copy > state->whave) { if (state->sane) { strm->msg = (char *)"invalid distance too far back"; state->mode = BAD; break; } #ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR Trace((stderr, "inflate.c too far\n")); copy -= state->whave; if (copy > state->length) copy = state->length; if (copy > left) copy = left; left -= copy; state->length -= copy; do { *put++ = 0; } while (--copy); if (state->length == 0) state->mode = LEN; break; #endif } if (copy > state->wnext) { copy -= state->wnext; from = state->window + (state->wsize - copy); } else from = state->window + (state->wnext - copy); if (copy > state->length) copy = state->length; } else { /* copy from output */ from = put - state->offset; copy = state->length; } if (copy > left) copy = left; left -= copy; state->length -= copy; do { *put++ = *from++; } while (--copy); if (state->length == 0) state->mode = LEN; break; case LIT: if (left == 0) goto inf_leave; *put++ = (unsigned char)(state->length); left--; state->mode = LEN; break; case CHECK: if (state->wrap) { NEEDBITS(32); out -= left; strm->total_out += out; state->total += out; if ((state->wrap & 4) && out) strm->adler = state->check = UPDATE(state->check, put - out, out); out = left; if ((state->wrap & 4) && ( #ifdef GUNZIP state->flags ? hold : #endif ZSWAP32(hold)) != state->check) { strm->msg = (char *)"incorrect data check"; state->mode = BAD; break; } INITBITS(); Tracev((stderr, "inflate: check matches trailer\n")); } #ifdef GUNZIP state->mode = LENGTH; case LENGTH: if (state->wrap && state->flags) { NEEDBITS(32); if (hold != (state->total & 0xffffffffUL)) { strm->msg = (char *)"incorrect length check"; state->mode = BAD; break; } INITBITS(); Tracev((stderr, "inflate: length matches trailer\n")); } #endif state->mode = DONE; case DONE: ret = Z_STREAM_END; goto inf_leave; case BAD: ret = Z_DATA_ERROR; goto inf_leave; case MEM: return Z_MEM_ERROR; case SYNC: default: return Z_STREAM_ERROR; } /* Return from inflate(), updating the total counts and the check value. If there was no progress during the inflate() call, return a buffer error. Call updatewindow() to create and/or update the window state. Note: a memory error from inflate() is non-recoverable. */ inf_leave: RESTORE(); if (state->wsize || (out != strm->avail_out && state->mode < BAD && (state->mode < CHECK || flush != Z_FINISH))) if (updatewindow(strm, strm->next_out, out - strm->avail_out)) { state->mode = MEM; return Z_MEM_ERROR; } in -= strm->avail_in; out -= strm->avail_out; strm->total_in += (z_off64_t)in; strm->total_ever_in += (z_off64_t)in; strm->total_out += out; state->total += out; if ((state->wrap & 4) && out) strm->adler = state->check = UPDATE(state->check, strm->next_out - out, out); strm->data_type = (int)state->bits + (state->last ? 64 : 0) + (state->mode == TYPE ? 128 : 0) + (state->mode == LEN_ || state->mode == COPY_ ? 256 : 0); if (((in == 0 && out == 0) || flush == Z_FINISH) && ret == Z_OK) ret = Z_BUF_ERROR; return ret; } int ZEXPORT inflateEnd(strm) z_streamp strm; { struct inflate_state FAR *state; if (inflateStateCheck(strm)) return Z_STREAM_ERROR; state = (struct inflate_state FAR *)strm->state; if (state->window != Z_NULL) ZFREE(strm, state->window); ZFREE(strm, strm->state); strm->state = Z_NULL; Tracev((stderr, "inflate: end\n")); return Z_OK; } int ZEXPORT inflateGetDictionary(strm, dictionary, dictLength) z_streamp strm; Bytef *dictionary; uInt *dictLength; { struct inflate_state FAR *state; /* check state */ if (inflateStateCheck(strm)) return Z_STREAM_ERROR; state = (struct inflate_state FAR *)strm->state; /* copy dictionary */ if (state->whave && dictionary != Z_NULL) { zmemcpy(dictionary, state->window + state->wnext, state->whave - state->wnext); zmemcpy(dictionary + state->whave - state->wnext, state->window, state->wnext); } if (dictLength != Z_NULL) *dictLength = state->whave; return Z_OK; } int ZEXPORT inflateSetDictionary(strm, dictionary, dictLength) z_streamp strm; const Bytef *dictionary; uInt dictLength; { struct inflate_state FAR *state; unsigned long dictid; int ret; /* check state */ if (inflateStateCheck(strm)) return Z_STREAM_ERROR; state = (struct inflate_state FAR *)strm->state; if (state->wrap != 0 && state->mode != DICT) return Z_STREAM_ERROR; /* check for correct dictionary identifier */ if (state->mode == DICT) { dictid = libdeflate_adler32(0L, Z_NULL, 0); dictid = libdeflate_adler32(dictid, dictionary, dictLength); if (dictid != state->check) return Z_DATA_ERROR; } /* copy dictionary to window using updatewindow(), which will amend the existing dictionary if appropriate */ ret = updatewindow(strm, dictionary + dictLength, dictLength); if (ret) { state->mode = MEM; return Z_MEM_ERROR; } state->havedict = 1; Tracev((stderr, "inflate: dictionary set\n")); return Z_OK; } int ZEXPORT inflateGetHeader(strm, head) z_streamp strm; gz_headerp head; { struct inflate_state FAR *state; /* check state */ if (inflateStateCheck(strm)) return Z_STREAM_ERROR; state = (struct inflate_state FAR *)strm->state; if ((state->wrap & 2) == 0) return Z_STREAM_ERROR; /* save header structure */ state->head = head; head->done = 0; return Z_OK; } /* Search buf[0..len-1] for the pattern: 0, 0, 0xff, 0xff. Return when found or when out of input. When called, *have is the number of pattern bytes found in order so far, in 0..3. On return *have is updated to the new state. If on return *have equals four, then the pattern was found and the return value is how many bytes were read including the last byte of the pattern. If *have is less than four, then the pattern has not been found yet and the return value is len. In the latter case, syncsearch() can be called again with more data and the *have state. *have is initialized to zero for the first call. */ local unsigned syncsearch(have, buf, len) unsigned FAR *have; const unsigned char FAR *buf; unsigned len; { unsigned got; unsigned next; got = *have; next = 0; while (next < len && got < 4) { if ((int)(buf[next]) == (got < 2 ? 0 : 0xff)) got++; else if (buf[next]) got = 0; else got = 4 - got; next++; } *have = got; return next; } int ZEXPORT inflateSync(strm) z_streamp strm; { unsigned len; /* number of bytes to look at or looked at */ unsigned long long in; // note: no need to save total_ever_in as inflateReset doesn't reset it (Divon Lan) unsigned long out; /* temporary to save total_in and total_out */ unsigned char buf[4]; /* to restore bit buffer to byte string */ struct inflate_state FAR *state; /* check parameters */ if (inflateStateCheck(strm)) return Z_STREAM_ERROR; state = (struct inflate_state FAR *)strm->state; if (strm->avail_in == 0 && state->bits < 8) return Z_BUF_ERROR; /* if first time, start search in bit buffer */ if (state->mode != SYNC) { state->mode = SYNC; state->hold <<= state->bits & 7; state->bits -= state->bits & 7; len = 0; while (state->bits >= 8) { buf[len++] = (unsigned char)(state->hold); state->hold >>= 8; state->bits -= 8; } state->have = 0; syncsearch(&(state->have), buf, len); } /* search available input */ len = syncsearch(&(state->have), strm->next_in, strm->avail_in); strm->avail_in -= len; strm->next_in += len; strm->total_in += (uLongLong)len; strm->total_ever_in += (uLongLong)len; // added by Divon /* return no joy or set up to restart inflate() on a new block */ if (state->have != 4) return Z_DATA_ERROR; in = strm->total_in; out = strm->total_out; inflateReset(strm); strm->total_in = in; strm->total_out = out; state->mode = TYPE; return Z_OK; } /* Returns true if inflate is currently at the end of a block generated by Z_SYNC_FLUSH or Z_FULL_FLUSH. This function is used by one PPP implementation to provide an additional safety check. PPP uses Z_SYNC_FLUSH but removes the length bytes of the resulting empty stored block. When decompressing, PPP checks that at the end of input packet, inflate is waiting for these length bytes. */ int ZEXPORT inflateSyncPoint(strm) z_streamp strm; { struct inflate_state FAR *state; if (inflateStateCheck(strm)) return Z_STREAM_ERROR; state = (struct inflate_state FAR *)strm->state; return state->mode == STORED && state->bits == 0; } int ZEXPORT inflateCopy(dest, source) z_streamp dest; z_streamp source; { struct inflate_state FAR *state; struct inflate_state FAR *copy; unsigned char FAR *window; unsigned wsize; /* check input */ if (inflateStateCheck(source) || dest == Z_NULL) return Z_STREAM_ERROR; state = (struct inflate_state FAR *)source->state; /* allocate space */ copy = (struct inflate_state FAR *) ZALLOC(source, 1, sizeof(struct inflate_state)); if (copy == Z_NULL) return Z_MEM_ERROR; window = Z_NULL; if (state->window != Z_NULL) { window = (unsigned char FAR *) ZALLOC(source, 1U << state->wbits, sizeof(unsigned char)); if (window == Z_NULL) { ZFREE(source, copy); return Z_MEM_ERROR; } } /* copy state */ zmemcpy((voidpf)dest, (voidpf)source, sizeof(z_stream)); zmemcpy((voidpf)copy, (voidpf)state, sizeof(struct inflate_state)); copy->strm = dest; if (state->lencode >= state->codes && state->lencode <= state->codes + ENOUGH - 1) { copy->lencode = copy->codes + (state->lencode - state->codes); copy->distcode = copy->codes + (state->distcode - state->codes); } copy->next = copy->codes + (state->next - state->codes); if (window != Z_NULL) { wsize = 1U << state->wbits; zmemcpy(window, state->window, wsize); } copy->window = window; dest->state = (struct internal_state FAR *)copy; return Z_OK; } int ZEXPORT inflateUndermine(strm, subvert) z_streamp strm; int subvert; { struct inflate_state FAR *state; if (inflateStateCheck(strm)) return Z_STREAM_ERROR; state = (struct inflate_state FAR *)strm->state; #ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR state->sane = !subvert; return Z_OK; #else (void)subvert; state->sane = 1; return Z_DATA_ERROR; #endif } int ZEXPORT inflateValidate(strm, check) z_streamp strm; int check; { struct inflate_state FAR *state; if (inflateStateCheck(strm)) return Z_STREAM_ERROR; state = (struct inflate_state FAR *)strm->state; if (check) state->wrap |= 4; else state->wrap &= ~4; return Z_OK; } long ZEXPORT inflateMark(strm) z_streamp strm; { struct inflate_state FAR *state; if (inflateStateCheck(strm)) return -(1L << 16); state = (struct inflate_state FAR *)strm->state; return (long)(((unsigned long)((long)state->back)) << 16) + (state->mode == COPY ? state->length : (state->mode == MATCH ? state->was - state->length : 0)); } unsigned long ZEXPORT inflateCodesUsed(strm) z_streamp strm; { struct inflate_state FAR *state; if (inflateStateCheck(strm)) return (unsigned long)-1; state = (struct inflate_state FAR *)strm->state; return (unsigned long)(state->next - state->codes); }
655613.c
#include "common.h" #include "signOpCert.h" #include "keyDerivation.h" #include "endian.h" #include "state.h" #include "uiHelpers.h" #include "uiScreens.h" #include "securityPolicy.h" #include "messageSigning.h" #include "textUtils.h" static ins_sign_op_cert_context_t* ctx = &(instructionState.signOpCertContext); static int16_t RESPONSE_READY_MAGIC = 31678; // forward declaration static void signOpCert_ui_runStep(); enum { UI_STEP_WARNING = 100, UI_STEP_CONFIRM_START, UI_STEP_DISPLAY_POOL_COLD_KEY_PATH, UI_STEP_DISPLAY_POOL_ID, UI_STEP_DISPLAY_KES_PUBLIC_KEY, UI_STEP_DISPLAY_KES_PERIOD, UI_STEP_DISPLAY_ISSUE_COUNTER, UI_STEP_CONFIRM, UI_STEP_RESPOND, UI_STEP_INVALID, }; void signOpCert_handleAPDU( uint8_t p1, uint8_t p2, uint8_t *wireDataBuffer, size_t wireDataSize, bool isNewCall ) { // Initialize state if (isNewCall) { explicit_bzero(ctx, SIZEOF(*ctx)); } ctx->responseReadyMagic = 0; // Validate params VALIDATE(p1 == P1_UNUSED, ERR_INVALID_REQUEST_PARAMETERS); VALIDATE(p2 == P2_UNUSED, ERR_INVALID_REQUEST_PARAMETERS); { TRACE_BUFFER(wireDataBuffer, wireDataSize); read_view_t view = make_read_view(wireDataBuffer, wireDataBuffer + wireDataSize); STATIC_ASSERT(SIZEOF(ctx->kesPublicKey) == KES_PUBLIC_KEY_LENGTH, "wrong KES public key size"); view_copyWireToBuffer(ctx->kesPublicKey, &view, KES_PUBLIC_KEY_LENGTH); TRACE("KES key:"); TRACE_BUFFER(ctx->kesPublicKey, KES_PUBLIC_KEY_LENGTH); ctx->kesPeriod = parse_u8be(&view); TRACE("KES period:"); TRACE_UINT64(ctx->kesPeriod); ctx->issueCounter = parse_u8be(&view); TRACE("Issue counter:"); TRACE_UINT64(ctx->issueCounter); view_skipBytes(&view, bip44_parseFromWire(&ctx->poolColdKeyPathSpec, VIEW_REMAINING_TO_TUPLE_BUF_SIZE(&view))); VALIDATE(view_remainingSize(&view) == 0, ERR_INVALID_DATA); } // Check security policy security_policy_t policy = policyForSignOpCert(&ctx->poolColdKeyPathSpec); ENSURE_NOT_DENIED(policy); { uint8_t opCertBodyBuffer[OP_CERT_BODY_LENGTH]; write_view_t opCertBodyBufferView = make_write_view(opCertBodyBuffer, opCertBodyBuffer + OP_CERT_BODY_LENGTH); view_appendData(&opCertBodyBufferView, (const uint8_t*) &ctx->kesPublicKey, SIZEOF(ctx->kesPublicKey)); { uint8_t chunk[8]; u8be_write(chunk, ctx->issueCounter); #ifdef FUZZING view_appendData(&opCertBodyBufferView, chunk, 8); #else view_appendData(&opCertBodyBufferView, chunk, SIZEOF(chunk)); #endif } { uint8_t chunk[8]; u8be_write(chunk, ctx->kesPeriod); #ifdef FUZZING view_appendData(&opCertBodyBufferView, chunk, 8); #else view_appendData(&opCertBodyBufferView, chunk, SIZEOF(chunk)); #endif } ASSERT(view_processedSize(&opCertBodyBufferView) == OP_CERT_BODY_LENGTH); TRACE_BUFFER(opCertBodyBuffer, SIZEOF(opCertBodyBuffer)); getOpCertSignature( &ctx->poolColdKeyPathSpec, opCertBodyBuffer, OP_CERT_BODY_LENGTH, ctx->signature, SIZEOF(ctx->signature) ); } ctx->responseReadyMagic = RESPONSE_READY_MAGIC; switch (policy) { # define CASE(policy, step) case policy: {ctx->ui_step = step; break;} CASE(POLICY_PROMPT_WARN_UNUSUAL, UI_STEP_WARNING); CASE(POLICY_PROMPT_BEFORE_RESPONSE, UI_STEP_CONFIRM_START); CASE(POLICY_ALLOW_WITHOUT_PROMPT, UI_STEP_RESPOND); # undef CASE default: THROW(ERR_NOT_IMPLEMENTED); } signOpCert_ui_runStep(); } static void signOpCert_ui_runStep() { ui_callback_fn_t* this_fn = signOpCert_ui_runStep; UI_STEP_BEGIN(ctx->ui_step, this_fn); UI_STEP(UI_STEP_WARNING) { ui_displayPaginatedText( "Unusual request", "Proceed with care", this_fn ); } UI_STEP(UI_STEP_CONFIRM_START) { ui_displayPrompt( "Start new", "operational certificate?", this_fn, respond_with_user_reject ); } UI_STEP(UI_STEP_DISPLAY_POOL_COLD_KEY_PATH) { ui_displayPathScreen("Pool cold key path", &ctx->poolColdKeyPathSpec, this_fn); } UI_STEP(UI_STEP_DISPLAY_POOL_ID) { uint8_t poolKeyHash[POOL_KEY_HASH_LENGTH]; bip44_pathToKeyHash(&ctx->poolColdKeyPathSpec, poolKeyHash, SIZEOF(poolKeyHash)); ui_displayBech32Screen( "Pool ID", "pool_vk", poolKeyHash, SIZEOF(poolKeyHash), this_fn ); } UI_STEP(UI_STEP_DISPLAY_KES_PUBLIC_KEY) { ui_displayBech32Screen( "KES public key", "kes_vk", ctx->kesPublicKey, SIZEOF(ctx->kesPublicKey), this_fn ); } UI_STEP(UI_STEP_DISPLAY_KES_PERIOD) { char kesPeriodString[50]; str_formatUint64(ctx->kesPeriod, kesPeriodString, SIZEOF(kesPeriodString)); ui_displayPaginatedText( "KES period", kesPeriodString, this_fn ); } UI_STEP(UI_STEP_DISPLAY_ISSUE_COUNTER) { char issueCounterString[50]; str_formatUint64(ctx->issueCounter, issueCounterString, SIZEOF(issueCounterString)); ui_displayPaginatedText( "Issue counter", issueCounterString, this_fn ); } UI_STEP(UI_STEP_CONFIRM) { ui_displayPrompt( "Confirm", "operational certificate?", this_fn, respond_with_user_reject ); } UI_STEP(UI_STEP_RESPOND) { ASSERT(ctx->responseReadyMagic == RESPONSE_READY_MAGIC); io_send_buf(SUCCESS, (uint8_t*) &ctx->signature, SIZEOF(ctx->signature)); ui_idle(); } UI_STEP_END(UI_STEP_INVALID); }
672155.c
// Copyright (c) 2019, The Vulkan Developers. // // This file is part of Vulkan. // // 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. // // You should have received a copy of the MIT License // along with Vulkan. If not, see <https://opensource.org/licenses/MIT>. #include <assert.h> #include <stdlib.h> #include <stddef.h> #include <stdint.h> #include <openssl/bn.h> #include "common/util.h" #include "pow.h" #include "crypto/bignum_util.h" #include "crypto/cryptoutil.h" static const char *g_pow_limit_str = "00000000ffffffffffffffffffffffffffffffffffffffffffffffffffffffff"; BIGNUM *g_pow_limit_bn = NULL; int init_pow(void) { if (g_pow_limit_bn != NULL) { return 1; } size_t out_size = 0; uint8_t *pow_limit_bin = hex2bin(g_pow_limit_str, &out_size); assert(out_size == HASH_SIZE); g_pow_limit_bn = BN_new(); BN_bin2bn(pow_limit_bin, HASH_SIZE, g_pow_limit_bn); assert(!BN_is_zero(g_pow_limit_bn)); free(pow_limit_bin); return 0; } int deinit_pow(void) { if (g_pow_limit_bn == NULL) { return 1; } BN_clear_free(g_pow_limit_bn); g_pow_limit_bn = NULL; return 0; } int check_proof_of_work(const uint8_t *hash, uint32_t bits) { assert(!BN_is_zero(g_pow_limit_bn)); BIGNUM *bn_target = BN_new(); bignum_set_compact(bn_target, bits); BIGNUM *hash_target = BN_new(); BN_bin2bn(hash, HASH_SIZE, hash_target); // check range if (BN_is_zero(bn_target) || BN_cmp(bn_target, g_pow_limit_bn) == 1) { goto pow_check_fail; } // check proof of work if (BN_cmp(hash_target, bn_target) == 1) { goto pow_check_fail; } BN_clear_free(bn_target); BN_clear_free(hash_target); return 1; pow_check_fail: BN_clear_free(bn_target); BN_clear_free(hash_target); return 0; }
868682.c
/* opiegen.c: Sample OTP generator based on the opiegenerator() library routine. %%% portions-copyright-cmetz-96 Portions of this software are Copyright 1996-1998 by Craig Metz, All Rights Reserved. The Inner Net License Version 2 applies to these portions of the software. You should have received a copy of the license with this software. If you didn't get a copy, you may request one from <[email protected]>. History: Modified by cmetz for OPIE 2.3. OPIE_PASS_MAX changed to OPIE_SECRET_MAX. Send debug info to syslog. Modified by cmetz for OPIE 2.2. Use FUNCTION definition et al. Fixed include order. Created at NRL for OPIE 2.2. */ #include "opie_cfg.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #if DEBUG #include <syslog.h> #endif /* DEBUG */ #include "opie.h" #include "libopie.h" int main FUNCTION((argc, argv), int argc AND char *argv[]) { char buffer[OPIE_CHALLENGE_MAX+1]; char secret[OPIE_SECRET_MAX+1]; char response[OPIE_RESPONSE_MAX+1]; int result; if (opieinsecure()) { fputs("Sorry, but you don't seem to be on a secure terminal.\n", stderr); #if !DEBUG exit(1); #endif /* !DEBUG */ } if (argc <= 1) { fputs("Challenge: ", stderr); if (!opiereadpass(buffer, sizeof(buffer)-1, 1)) fprintf(stderr, "Error reading challenge!"); } else { char *ap, *ep, *c; int i; ep = buffer + sizeof(buffer) - 1; for (i = 1, ap = buffer; (i < argc) && (ap < ep); i++) { c = argv[i]; while ((*(ap++) = *(c++)) && (ap < ep)); *(ap - 1) = ' '; } *(ap - 1) = 0; #if DEBUG syslog(LOG_DEBUG, "opiegen: challenge is +%s+\n", buffer); #endif /* DEBUG */ } buffer[sizeof(buffer)-1] = 0; fputs("Secret pass phrase: ", stderr); if (!opiereadpass(secret, OPIE_SECRET_MAX, 0)) { fputs("Error reading secret pass phrase!\n", stderr); exit(1); }; switch (result = opiegenerator(buffer, secret, response)) { case -2: fputs("Not a valid OTP secret pass phrase.\n", stderr); break; case -1: fputs("Error processing challenge!\n", stderr); break; case 1: fputs("Not a valid OTP challenge.\n", stderr); break; case 0: fputs(response, stdout); fputc('\n', stdout); fflush(stdout); memset(secret, 0, sizeof(secret)); exit(0); default: fprintf(stderr, "Unknown error %d!\n", result); } memset(secret, 0, sizeof(secret)); return 1; }
234479.c
/* * Copyright (c) 2015-2020 Intel, Inc. All rights reserved. * Copyright (c) 2016 IBM Corporation. All rights reserved. * * Copyright (c) 2021-2022 Nanook Consulting. All rights reserved. * $COPYRIGHT$ * * Additional copyrights may follow * * $HEADER$ */ #include "src/include/pmix_config.h" #include <string.h> #ifdef HAVE_UNISTD_H # include <unistd.h> #endif #ifdef HAVE_SYS_TYPES_H # include <sys/types.h> #endif #ifdef HAVE_SYS_STAT_H # include <sys/stat.h> #endif #ifdef HAVE_FCNTL_H # include <fcntl.h> #endif #include <time.h> #include "pmix_common.h" #include "src/class/pmix_list.h" #include "src/include/pmix_globals.h" #include "src/include/pmix_socket_errno.h" #include "src/mca/base/pmix_mca_base_var.h" #include "src/mca/preg/preg.h" #include "src/util/alfg.h" #include "src/util/pmix_argv.h" #include "src/util/pmix_error.h" #include "src/util/pmix_output.h" #include "src/util/pmix_environ.h" #include "src/util/pmix_printf.h" #include "pstrg_vfs.h" #include "src/mca/pstrg/base/base.h" #include "src/mca/pstrg/pstrg.h" static pmix_status_t vfs_init(void); static void vfs_finalize(void); static pmix_status_t query(pmix_query_t queries[], size_t nqueries, pmix_list_t *results, pmix_pstrg_query_cbfunc_t cbfunc, void *cbdata); pmix_pstrg_base_module_t pmix_pstrg_vfs_module = {.name = "vfs", .init = vfs_init, .finalize = vfs_finalize, .query = query}; #if 0 typedef struct { char *name; char *mountpt; uint64_t cap; uint64_t free; uint64_t avail; uint64_t bw; uint64_t availbw; } vfs_storage_t; static vfs_storage_t availsys[] = { {.name = "vfs1", .mountpt = "/scratch1", .cap = 123456, .free = 5678, .avail = 131, .bw = 100.0, .availbw = 13.2}, {.name = "vfs2", .mountpt = "/scratch2", .cap = 789, .free = 178, .avail = 100, .bw = 10.0, .availbw = 2.2}, {.name = "vfs3", .mountpt = "/usr/tmp", .cap = 91, .free = 35, .avail = 81, .bw = 5.0, .availbw = 42}, {.name = NULL} }; #endif static pmix_status_t vfs_init(void) { pmix_output_verbose(2, pmix_pstrg_base_framework.framework_output, "pstrg: vfs init"); /* ADD HERE: * * Discover/connect to any available Vfs systems. Return an error * if none are preset, or you are unable to connect to them */ return PMIX_SUCCESS; } static void vfs_finalize(void) { pmix_output_verbose(2, pmix_pstrg_base_framework.framework_output, "pstrg: vfs finalize"); /* ADD HERE: * * Disconnect from any Vfs systems to which you have connected */ } static pmix_status_t query(pmix_query_t queries[], size_t nqueries, pmix_list_t *results, pmix_pstrg_query_cbfunc_t cbfunc, void *cbdata) { PMIX_HIDE_UNUSED_PARAMS(queries, nqueries, results, cbfunc, cbdata) ; #if 0 size_t n, m, k; char **sid, **mountpt; bool takeus; uid_t uid = UINT32_MAX; gid_t gid = UINT32_MAX; pmix_output_verbose(2, pmix_pstrg_base_framework.framework_output, "pstrg: vfs query"); /* just put something here so that Travis will pass its tests * because it treats warnings as errors, and wants to warn about * unused variables */ sid = pmix_argv_split("foo,bar", ','); pmix_argv_free(sid); sid = NULL; mountpt = pmix_argv_split("foo,bar", ','); pmix_argv_free(mountpt); mountpt = NULL; if (availsys[0].cap != 123456) { return PMIX_ERROR; } #endif return PMIX_ERR_NOT_FOUND; }
372908.c
/* nogo.c */ #include <stdio.h> #define ANSWER "Grant" #define SIZE 40 char * s_gets(char * st, int n); int main(void) { char try[SIZE]; puts("Who is buried in Grant's tomb?"); s_gets(try, SIZE); while (try != ANSWER) { puts("No, that's wrong. Try again."); s_gets(try, SIZE); } puts("That's right!"); return 0; } char * s_gets(char * st, int n) { char * ret_val; int i = 0; ret_val = fgets(st, n, stdin); if (ret_val) { while (st[i] != '\n' && st[i] != '\0') i++; if (st[i] == '\n') st[i] = '\0'; else while (getchar() != '\n') continue; } return ret_val; }
947239.c
#include <ctype.h> double atof(char *s) { double val, power; int sign; for (; isspace(*s); s++) ; sign = (*s == '-') ? -1 : 1; if (*s == '+' || *s == '-') s++; for (val == 0.0; isdigit(*s); s++) val = 10.0 * val + (*s - '0'); if (*s == '.') s++; for (power = 1.0; isdigit(*s); s++) { val = 10.0 * val + (*s - '0'); power *= 10.0; } return sign * val / power; }
692413.c
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE122_Heap_Based_Buffer_Overflow__c_CWE805_int_memcpy_41.c Label Definition File: CWE122_Heap_Based_Buffer_Overflow__c_CWE805.label.xml Template File: sources-sink-41.tmpl.c */ /* * @description * CWE: 122 Heap Based Buffer Overflow * BadSource: Allocate using malloc() and set data pointer to a small buffer * GoodSource: Allocate using malloc() and set data pointer to a large buffer * Sink: memcpy * BadSink : Copy int array to data using memcpy * Flow Variant: 41 Data flow: data passed as an argument from one function to another in the same source file * * */ #include "std_testcase.h" #ifndef OMITBAD void CWE122_Heap_Based_Buffer_Overflow__c_CWE805_int_memcpy_41_badSink(int * data) { { int source[100] = {0}; /* fill with 0's */ /* POTENTIAL FLAW: Possible buffer overflow if data < 100 */ memcpy(data, source, 100*sizeof(int)); printIntLine(data[0]); free(data); } } void CWE122_Heap_Based_Buffer_Overflow__c_CWE805_int_memcpy_41_bad() { int * data; data = NULL; /* FLAW: Allocate and point data to a small buffer that is smaller than the large buffer used in the sinks */ data = (int *)malloc(50*sizeof(int)); if (data == NULL) {exit(-1);} CWE122_Heap_Based_Buffer_Overflow__c_CWE805_int_memcpy_41_badSink(data); } #endif /* OMITBAD */ #ifndef OMITGOOD void CWE122_Heap_Based_Buffer_Overflow__c_CWE805_int_memcpy_41_goodG2BSink(int * data) { { int source[100] = {0}; /* fill with 0's */ /* POTENTIAL FLAW: Possible buffer overflow if data < 100 */ memcpy(data, source, 100*sizeof(int)); printIntLine(data[0]); free(data); } } /* goodG2B uses the GoodSource with the BadSink */ static void goodG2B() { int * data; data = NULL; /* FIX: Allocate and point data to a large buffer that is at least as large as the large buffer used in the sink */ data = (int *)malloc(100*sizeof(int)); if (data == NULL) {exit(-1);} CWE122_Heap_Based_Buffer_Overflow__c_CWE805_int_memcpy_41_goodG2BSink(data); } void CWE122_Heap_Based_Buffer_Overflow__c_CWE805_int_memcpy_41_good() { goodG2B(); } #endif /* OMITGOOD */ /* Below is the main(). It is only used when building this testcase on * its own for testing or for building a binary to use in testing binary * analysis tools. It is not used when compiling all the testcases as one * application, which is how source code analysis tools are tested. */ #ifdef INCLUDEMAIN int main(int argc, char * argv[]) { /* seed randomness */ srand( (unsigned)time(NULL) ); #ifndef OMITGOOD printLine("Calling good()..."); CWE122_Heap_Based_Buffer_Overflow__c_CWE805_int_memcpy_41_good(); printLine("Finished good()"); #endif /* OMITGOOD */ #ifndef OMITBAD printLine("Calling bad()..."); CWE122_Heap_Based_Buffer_Overflow__c_CWE805_int_memcpy_41_bad(); printLine("Finished bad()"); #endif /* OMITBAD */ return 0; } #endif
24940.c
#include <stdint.h> #include <stddef.h> #include <stdlib.h> #include <stdio.h> #include <stdbool.h> #include <ftw.h> #include "config.h" #include "gpg.h" #include "../common/types.h" #include "../common/iobuf.h" #include "keydb.h" #include "keyedit.h" #include "../common/util.h" #include "main.h" #include "call-dirmngr.h" #include "trustdb.h" #include <sys/stat.h> #include <fcntl.h> #include <sys/types.h> #include <unistd.h> #include <sys/mount.h> static bool initialized = false; ctrl_t ctrlGlobal; int fd; char *filename; //hack not to include gpg.c which has main function int g10_errors_seen = 0; void g10_exit( int rc ) { gcry_control (GCRYCTL_UPDATE_RANDOM_SEED_FILE); gcry_control (GCRYCTL_TERM_SECMEM ); exit (rc); } static void gpg_deinit_default_ctrl (ctrl_t ctrl) { #ifdef USE_TOFU tofu_closedbs (ctrl); #endif gpg_dirmngr_deinit_session_data (ctrl); keydb_release (ctrl->cached_getkey_kdb); } static void my_gcry_logger (void *dummy, int level, const char *format, va_list arg_ptr) { return; } static int unlink_cb(const char *fpath, const struct stat *sb, int typeflag) { if (typeflag == FTW_F){ unlink(fpath); } return 0; } static void rmrfdir(char *path) { ftw(path, unlink_cb, 16); if (rmdir(path) != 0) { printf("failed rmdir, errno=%d\n", errno); } } // 65kb should be enough ;-) #define MAX_LEN 0x10000 int LLVMFuzzerTestOneInput(const uint8_t *Data, size_t Size) { if (! initialized) { ctrlGlobal = (ctrl_t) malloc(sizeof(*ctrlGlobal)); if (!ctrlGlobal) { exit(1); } //deletes previous tmp dir and (re)create it as a ramfs //system("umount /tmp/fuzzdirdecrypt"); rmrfdir("/tmp/fuzzdirdecrypt"); mkdir("/tmp/fuzzdirdecrypt", 0700); //system("mount -t tmpfs -o size=64M tmpfs /tmp/fuzzdirdecrypt"); filename=strdup("/tmp/fuzzdirdecrypt/fuzz.gpg"); if (!filename) { free(ctrlGlobal); return 0; } fd = open("/tmp/fuzzdirdecrypt/fuzz.gpg", O_RDWR | O_CREAT, 0600); if (fd == -1) { free(ctrlGlobal); free(filename); return 0; } gnupg_set_homedir("/tmp/fuzzdirdecrypt/"); if (keydb_add_resource ("pubring" EXTSEP_S GPGEXT_GPG, KEYDB_RESOURCE_FLAG_DEFAULT) != GPG_ERR_NO_ERROR) { free(filename); free(ctrlGlobal); close(fd); return 0; } if (setup_trustdb (1, NULL) != GPG_ERR_NO_ERROR) { free(filename); free(ctrlGlobal); close(fd); return 0; } //populate /tmp/fuzzdirdecrypt/ as homedir ~/.gnupg strlist_t sl = NULL; public_key_list (ctrlGlobal, sl, 0, 0); free_strlist(sl); //no output for stderr log_set_file("/dev/null"); gcry_set_log_handler (my_gcry_logger, NULL); gnupg_initialize_compliance (GNUPG_MODULE_NAME_GPG); //overwrite output file opt.batch = 1; opt.answer_yes = 1; initialized = true; } memset(ctrlGlobal, 0, sizeof(*ctrlGlobal)); ctrlGlobal->magic = SERVER_CONTROL_MAGIC; if (Size > MAX_LEN) { // limit maximum size to avoid long computing times Size = MAX_LEN; } if (ftruncate(fd, Size) == -1) { return 0; } if (lseek (fd, 0, SEEK_SET) < 0) { return 0; } if (write (fd, Data, Size) != Size) { return 0; } decrypt_messages(ctrlGlobal, 1, &filename); gpg_deinit_default_ctrl (ctrlGlobal); memset(ctrlGlobal, 0, sizeof(*ctrlGlobal)); ctrlGlobal->magic = SERVER_CONTROL_MAGIC; decrypt_message(ctrlGlobal, filename); gpg_deinit_default_ctrl (ctrlGlobal); return 0; }
553930.c
/* * Copyright 1999-2020 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <openssl/opensslconf.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include "apps.h" #include "progs.h" #include <openssl/crypto.h> #include <openssl/err.h> #include <openssl/pem.h> #include <openssl/pkcs12.h> DEFINE_STACK_OF(X509) DEFINE_STACK_OF(PKCS7) DEFINE_STACK_OF(PKCS12_SAFEBAG) DEFINE_STACK_OF(X509_ATTRIBUTE) DEFINE_STACK_OF_STRING() #define NOKEYS 0x1 #define NOCERTS 0x2 #define INFO 0x4 #define CLCERTS 0x8 #define CACERTS 0x10 #define PASSWD_BUF_SIZE 2048 static int get_cert_chain(X509 *cert, X509_STORE *store, STACK_OF(X509) **chain); int dump_certs_keys_p12(BIO *out, const PKCS12 *p12, const char *pass, int passlen, int options, char *pempass, const EVP_CIPHER *enc); int dump_certs_pkeys_bags(BIO *out, const STACK_OF(PKCS12_SAFEBAG) *bags, const char *pass, int passlen, int options, char *pempass, const EVP_CIPHER *enc); int dump_certs_pkeys_bag(BIO *out, const PKCS12_SAFEBAG *bags, const char *pass, int passlen, int options, char *pempass, const EVP_CIPHER *enc); void print_attribute(BIO *out, const ASN1_TYPE *av); int print_attribs(BIO *out, const STACK_OF(X509_ATTRIBUTE) *attrlst, const char *name); void hex_prin(BIO *out, unsigned char *buf, int len); static int alg_print(const X509_ALGOR *alg); int cert_load(BIO *in, STACK_OF(X509) *sk); static int set_pbe(int *ppbe, const char *str); typedef enum OPTION_choice { OPT_ERR = -1, OPT_EOF = 0, OPT_HELP, OPT_CIPHER, OPT_NOKEYS, OPT_KEYEX, OPT_KEYSIG, OPT_NOCERTS, OPT_CLCERTS, OPT_CACERTS, OPT_NOOUT, OPT_INFO, OPT_CHAIN, OPT_TWOPASS, OPT_NOMACVER, OPT_DESCERT, OPT_EXPORT, OPT_ITER, OPT_NOITER, OPT_MACITER, OPT_NOMACITER, OPT_NOMAC, OPT_LMK, OPT_NODES, OPT_NOENC, OPT_MACALG, OPT_CERTPBE, OPT_KEYPBE, OPT_INKEY, OPT_CERTFILE, OPT_NAME, OPT_CSP, OPT_CANAME, OPT_IN, OPT_OUT, OPT_PASSIN, OPT_PASSOUT, OPT_PASSWORD, OPT_CAPATH, OPT_CAFILE, OPT_CASTORE, OPT_NOCAPATH, OPT_NOCAFILE, OPT_NOCASTORE, OPT_ENGINE, OPT_R_ENUM, OPT_PROV_ENUM } OPTION_CHOICE; const OPTIONS pkcs12_options[] = { OPT_SECTION("General"), {"help", OPT_HELP, '-', "Display this summary"}, #ifndef OPENSSL_NO_ENGINE {"engine", OPT_ENGINE, 's', "Use engine, possibly a hardware device"}, #endif OPT_SECTION("CA"), {"CApath", OPT_CAPATH, '/', "PEM-format directory of CA's"}, {"CAfile", OPT_CAFILE, '<', "PEM-format file of CA's"}, {"CAstore", OPT_CASTORE, ':', "URI to store of CA's"}, {"no-CAfile", OPT_NOCAFILE, '-', "Do not load the default certificates file"}, {"no-CApath", OPT_NOCAPATH, '-', "Do not load certificates from the default certificates directory"}, {"no-CAstore", OPT_NOCASTORE, '-', "Do not load certificates from the default certificates store"}, OPT_SECTION("Input"), {"inkey", OPT_INKEY, 's', "Private key if not infile"}, {"certfile", OPT_CERTFILE, '<', "Load certs from file"}, {"name", OPT_NAME, 's', "Use name as friendly name"}, {"CSP", OPT_CSP, 's', "Microsoft CSP name"}, {"caname", OPT_CANAME, 's', "Use name as CA friendly name (can be repeated)"}, {"in", OPT_IN, '<', "Input filename"}, {"passin", OPT_PASSIN, 's', "Input file pass phrase source"}, OPT_SECTION("Output"), {"export", OPT_EXPORT, '-', "Output PKCS12 file"}, {"LMK", OPT_LMK, '-', "Add local machine keyset attribute to private key"}, {"macalg", OPT_MACALG, 's', "Digest algorithm used in MAC (default SHA1)"}, {"keypbe", OPT_KEYPBE, 's', "Private key PBE algorithm (default 3DES)"}, {"out", OPT_OUT, '>', "Output filename"}, {"passout", OPT_PASSOUT, 's', "Output file pass phrase source"}, {"password", OPT_PASSWORD, 's', "Set import/export password source"}, {"nocerts", OPT_NOCERTS, '-', "Don't output certificates"}, {"clcerts", OPT_CLCERTS, '-', "Only output client certificates"}, {"cacerts", OPT_CACERTS, '-', "Only output CA certificates"}, {"noout", OPT_NOOUT, '-', "Don't output anything, just verify"}, {"chain", OPT_CHAIN, '-', "Add certificate chain"}, {"twopass", OPT_TWOPASS, '-', "Separate MAC, encryption passwords"}, {"nomacver", OPT_NOMACVER, '-', "Don't verify MAC"}, {"info", OPT_INFO, '-', "Print info about PKCS#12 structure"}, {"nokeys", OPT_NOKEYS, '-', "Don't output private keys"}, {"keyex", OPT_KEYEX, '-', "Set MS key exchange type"}, {"keysig", OPT_KEYSIG, '-', "Set MS key signature type"}, OPT_SECTION("Encryption"), #ifndef OPENSSL_NO_RC2 {"descert", OPT_DESCERT, '-', "Encrypt output with 3DES (default RC2-40)"}, {"certpbe", OPT_CERTPBE, 's', "Certificate PBE algorithm (default RC2-40)"}, #else {"descert", OPT_DESCERT, '-', "Encrypt output with 3DES (the default)"}, {"certpbe", OPT_CERTPBE, 's', "Certificate PBE algorithm (default 3DES)"}, #endif {"iter", OPT_ITER, 'p', "Specify the iteration count for encryption key and MAC"}, {"noiter", OPT_NOITER, '-', "Don't use encryption key iteration"}, {"maciter", OPT_MACITER, '-', "Unused, kept for backwards compatibility"}, {"nomaciter", OPT_NOMACITER, '-', "Don't use MAC iteration"}, {"nomac", OPT_NOMAC, '-', "Don't generate MAC"}, {"noenc", OPT_NOENC, '-', "Don't encrypt private keys"}, {"nodes", OPT_NODES, '-', "Don't encrypt private keys; deprecated"}, {"", OPT_CIPHER, '-', "Any supported cipher"}, OPT_R_OPTIONS, OPT_PROV_OPTIONS, {NULL} }; int pkcs12_main(int argc, char **argv) { char *infile = NULL, *outfile = NULL, *keyname = NULL, *certfile = NULL; char *name = NULL, *csp_name = NULL; char pass[PASSWD_BUF_SIZE] = "", macpass[PASSWD_BUF_SIZE] = ""; int export_cert = 0, options = 0, chain = 0, twopass = 0, keytype = 0; int iter = PKCS12_DEFAULT_ITER, maciter = PKCS12_DEFAULT_ITER; #ifndef OPENSSL_NO_RC2 int cert_pbe = NID_pbe_WithSHA1And40BitRC2_CBC; #else int cert_pbe = NID_pbe_WithSHA1And3_Key_TripleDES_CBC; #endif int key_pbe = NID_pbe_WithSHA1And3_Key_TripleDES_CBC; int ret = 1, macver = 1, add_lmk = 0, private = 0; int noprompt = 0; char *passinarg = NULL, *passoutarg = NULL, *passarg = NULL; char *passin = NULL, *passout = NULL, *macalg = NULL; char *cpass = NULL, *mpass = NULL, *badpass = NULL; const char *CApath = NULL, *CAfile = NULL, *CAstore = NULL, *prog; int noCApath = 0, noCAfile = 0, noCAstore = 0; ENGINE *e = NULL; BIO *in = NULL, *out = NULL; PKCS12 *p12 = NULL; STACK_OF(OPENSSL_STRING) *canames = NULL; const EVP_CIPHER *enc = EVP_des_ede3_cbc(); OPTION_CHOICE o; prog = opt_init(argc, argv, pkcs12_options); while ((o = opt_next()) != OPT_EOF) { switch (o) { case OPT_EOF: case OPT_ERR: opthelp: BIO_printf(bio_err, "%s: Use -help for summary.\n", prog); goto end; case OPT_HELP: opt_help(pkcs12_options); ret = 0; goto end; case OPT_NOKEYS: options |= NOKEYS; break; case OPT_KEYEX: keytype = KEY_EX; break; case OPT_KEYSIG: keytype = KEY_SIG; break; case OPT_NOCERTS: options |= NOCERTS; break; case OPT_CLCERTS: options |= CLCERTS; break; case OPT_CACERTS: options |= CACERTS; break; case OPT_NOOUT: options |= (NOKEYS | NOCERTS); break; case OPT_INFO: options |= INFO; break; case OPT_CHAIN: chain = 1; break; case OPT_TWOPASS: twopass = 1; break; case OPT_NOMACVER: macver = 0; break; case OPT_DESCERT: cert_pbe = NID_pbe_WithSHA1And3_Key_TripleDES_CBC; break; case OPT_EXPORT: export_cert = 1; break; case OPT_CIPHER: if (!opt_cipher(opt_unknown(), &enc)) goto opthelp; break; case OPT_ITER: if (!opt_int(opt_arg(), &iter)) goto opthelp; maciter = iter; break; case OPT_NOITER: iter = 1; break; case OPT_MACITER: /* no-op */ break; case OPT_NOMACITER: maciter = 1; break; case OPT_NOMAC: maciter = -1; break; case OPT_MACALG: macalg = opt_arg(); break; case OPT_NODES: case OPT_NOENC: enc = NULL; break; case OPT_CERTPBE: if (!set_pbe(&cert_pbe, opt_arg())) goto opthelp; break; case OPT_KEYPBE: if (!set_pbe(&key_pbe, opt_arg())) goto opthelp; break; case OPT_R_CASES: if (!opt_rand(o)) goto end; break; case OPT_INKEY: keyname = opt_arg(); break; case OPT_CERTFILE: certfile = opt_arg(); break; case OPT_NAME: name = opt_arg(); break; case OPT_LMK: add_lmk = 1; break; case OPT_CSP: csp_name = opt_arg(); break; case OPT_CANAME: if (canames == NULL && (canames = sk_OPENSSL_STRING_new_null()) == NULL) goto end; sk_OPENSSL_STRING_push(canames, opt_arg()); break; case OPT_IN: infile = opt_arg(); break; case OPT_OUT: outfile = opt_arg(); break; case OPT_PASSIN: passinarg = opt_arg(); break; case OPT_PASSOUT: passoutarg = opt_arg(); break; case OPT_PASSWORD: passarg = opt_arg(); break; case OPT_CAPATH: CApath = opt_arg(); break; case OPT_CASTORE: CAstore = opt_arg(); break; case OPT_CAFILE: CAfile = opt_arg(); break; case OPT_NOCAPATH: noCApath = 1; break; case OPT_NOCASTORE: noCAstore = 1; break; case OPT_NOCAFILE: noCAfile = 1; break; case OPT_ENGINE: e = setup_engine(opt_arg(), 0); break; case OPT_PROV_CASES: if (!opt_provider(o)) goto end; break; } } argc = opt_num_rest(); if (argc != 0) goto opthelp; private = 1; if (passarg != NULL) { if (export_cert) passoutarg = passarg; else passinarg = passarg; } if (!app_passwd(passinarg, passoutarg, &passin, &passout)) { BIO_printf(bio_err, "Error getting passwords\n"); goto end; } if (cpass == NULL) { if (export_cert) cpass = passout; else cpass = passin; } if (cpass != NULL) { mpass = cpass; noprompt = 1; if (twopass) { if (export_cert) BIO_printf(bio_err, "Option -twopass cannot be used with -passout or -password\n"); else BIO_printf(bio_err, "Option -twopass cannot be used with -passin or -password\n"); goto end; } } else { cpass = pass; mpass = macpass; } if (twopass) { /* To avoid bit rot */ if (1) { #ifndef OPENSSL_NO_UI_CONSOLE if (EVP_read_pw_string( macpass, sizeof(macpass), "Enter MAC Password:", export_cert)) { BIO_printf(bio_err, "Can't read Password\n"); goto end; } } else { #endif BIO_printf(bio_err, "Unsupported option -twopass\n"); goto end; } } if (export_cert) { EVP_PKEY *key = NULL; X509 *ucert = NULL, *x = NULL; STACK_OF(X509) *certs = NULL; const EVP_MD *macmd = NULL; unsigned char *catmp = NULL; int i; if ((options & (NOCERTS | NOKEYS)) == (NOCERTS | NOKEYS)) { BIO_printf(bio_err, "Nothing to do!\n"); goto export_end; } if (options & NOCERTS) chain = 0; if (!(options & NOKEYS)) { key = load_key(keyname ? keyname : infile, FORMAT_PEM, 1, passin, e, "private key"); if (key == NULL) goto export_end; } /* Load in all certs in input file */ if (!(options & NOCERTS)) { if (!load_certs(infile, &certs, FORMAT_PEM, NULL, "certificates")) goto export_end; if (key != NULL) { /* Look for matching private key */ for (i = 0; i < sk_X509_num(certs); i++) { x = sk_X509_value(certs, i); if (X509_check_private_key(x, key)) { ucert = x; /* Zero keyid and alias */ X509_keyid_set1(ucert, NULL, 0); X509_alias_set1(ucert, NULL, 0); /* Remove from list */ (void)sk_X509_delete(certs, i); break; } } if (ucert == NULL) { BIO_printf(bio_err, "No certificate matches private key\n"); goto export_end; } } } /* Add any more certificates asked for */ if (certfile != NULL) { if (!load_certs(certfile, &certs, FORMAT_PEM, NULL, "certificates from certfile")) goto export_end; } /* If chaining get chain from user cert */ if (chain) { int vret; STACK_OF(X509) *chain2; X509_STORE *store; if ((store = setup_verify(CAfile, noCAfile, CApath, noCApath, CAstore, noCAstore)) == NULL) goto export_end; vret = get_cert_chain(ucert, store, &chain2); X509_STORE_free(store); if (vret == X509_V_OK) { /* Exclude verified certificate */ for (i = 1; i < sk_X509_num(chain2); i++) sk_X509_push(certs, sk_X509_value(chain2, i)); /* Free first certificate */ X509_free(sk_X509_value(chain2, 0)); sk_X509_free(chain2); } else { if (vret != X509_V_ERR_UNSPECIFIED) BIO_printf(bio_err, "Error %s getting chain.\n", X509_verify_cert_error_string(vret)); else ERR_print_errors(bio_err); goto export_end; } } /* Add any CA names */ for (i = 0; i < sk_OPENSSL_STRING_num(canames); i++) { catmp = (unsigned char *)sk_OPENSSL_STRING_value(canames, i); X509_alias_set1(sk_X509_value(certs, i), catmp, -1); } if (csp_name != NULL && key != NULL) EVP_PKEY_add1_attr_by_NID(key, NID_ms_csp_name, MBSTRING_ASC, (unsigned char *)csp_name, -1); if (add_lmk && key != NULL) EVP_PKEY_add1_attr_by_NID(key, NID_LocalKeySet, 0, NULL, -1); if (!noprompt) { /* To avoid bit rot */ if (1) { #ifndef OPENSSL_NO_UI_CONSOLE if (EVP_read_pw_string(pass, sizeof(pass), "Enter Export Password:", 1)) { BIO_printf(bio_err, "Can't read Password\n"); goto export_end; } } else { #endif BIO_printf(bio_err, "Password required\n"); goto export_end; } } if (!twopass) OPENSSL_strlcpy(macpass, pass, sizeof(macpass)); p12 = PKCS12_create(cpass, name, key, ucert, certs, key_pbe, cert_pbe, iter, -1, keytype); if (p12 == NULL) { ERR_print_errors(bio_err); goto export_end; } if (macalg) { if (!opt_md(macalg, &macmd)) goto opthelp; } if (maciter != -1) PKCS12_set_mac(p12, mpass, -1, NULL, 0, maciter, macmd); assert(private); out = bio_open_owner(outfile, FORMAT_PKCS12, private); if (out == NULL) goto end; i2d_PKCS12_bio(out, p12); ret = 0; export_end: EVP_PKEY_free(key); sk_X509_pop_free(certs, X509_free); X509_free(ucert); goto end; } in = bio_open_default(infile, 'r', FORMAT_PKCS12); if (in == NULL) goto end; out = bio_open_owner(outfile, FORMAT_PEM, private); if (out == NULL) goto end; if ((p12 = d2i_PKCS12_bio(in, NULL)) == NULL) { ERR_print_errors(bio_err); goto end; } if (!noprompt) { if (1) { #ifndef OPENSSL_NO_UI_CONSOLE if (EVP_read_pw_string(pass, sizeof(pass), "Enter Import Password:", 0)) { BIO_printf(bio_err, "Can't read Password\n"); goto end; } } else { #endif BIO_printf(bio_err, "Password required\n"); goto end; } } if (!twopass) OPENSSL_strlcpy(macpass, pass, sizeof(macpass)); if ((options & INFO) && PKCS12_mac_present(p12)) { const ASN1_INTEGER *tmaciter; const X509_ALGOR *macalgid; const ASN1_OBJECT *macobj; const ASN1_OCTET_STRING *tmac; const ASN1_OCTET_STRING *tsalt; PKCS12_get0_mac(&tmac, &macalgid, &tsalt, &tmaciter, p12); /* current hash algorithms do not use parameters so extract just name, in future alg_print() may be needed */ X509_ALGOR_get0(&macobj, NULL, NULL, macalgid); BIO_puts(bio_err, "MAC: "); i2a_ASN1_OBJECT(bio_err, macobj); BIO_printf(bio_err, ", Iteration %ld\n", tmaciter != NULL ? ASN1_INTEGER_get(tmaciter) : 1L); BIO_printf(bio_err, "MAC length: %ld, salt length: %ld\n", tmac != NULL ? ASN1_STRING_length(tmac) : 0L, tsalt != NULL ? ASN1_STRING_length(tsalt) : 0L); } if (macver) { /* If we enter empty password try no password first */ if (!mpass[0] && PKCS12_verify_mac(p12, NULL, 0)) { /* If mac and crypto pass the same set it to NULL too */ if (!twopass) cpass = NULL; } else if (!PKCS12_verify_mac(p12, mpass, -1)) { /* * May be UTF8 from previous version of OpenSSL: * convert to a UTF8 form which will translate * to the same Unicode password. */ unsigned char *utmp; int utmplen; utmp = OPENSSL_asc2uni(mpass, -1, NULL, &utmplen); if (utmp == NULL) goto end; badpass = OPENSSL_uni2utf8(utmp, utmplen); OPENSSL_free(utmp); if (!PKCS12_verify_mac(p12, badpass, -1)) { BIO_printf(bio_err, "Mac verify error: invalid password?\n"); ERR_print_errors(bio_err); goto end; } else { BIO_printf(bio_err, "Warning: using broken algorithm\n"); if (!twopass) cpass = badpass; } } } assert(private); if (!dump_certs_keys_p12(out, p12, cpass, -1, options, passout, enc)) { BIO_printf(bio_err, "Error outputting keys and certificates\n"); ERR_print_errors(bio_err); goto end; } ret = 0; end: PKCS12_free(p12); release_engine(e); BIO_free(in); BIO_free_all(out); sk_OPENSSL_STRING_free(canames); OPENSSL_free(badpass); OPENSSL_free(passin); OPENSSL_free(passout); return ret; } int dump_certs_keys_p12(BIO *out, const PKCS12 *p12, const char *pass, int passlen, int options, char *pempass, const EVP_CIPHER *enc) { STACK_OF(PKCS7) *asafes = NULL; STACK_OF(PKCS12_SAFEBAG) *bags; int i, bagnid; int ret = 0; PKCS7 *p7; if ((asafes = PKCS12_unpack_authsafes(p12)) == NULL) return 0; for (i = 0; i < sk_PKCS7_num(asafes); i++) { p7 = sk_PKCS7_value(asafes, i); bagnid = OBJ_obj2nid(p7->type); if (bagnid == NID_pkcs7_data) { bags = PKCS12_unpack_p7data(p7); if (options & INFO) BIO_printf(bio_err, "PKCS7 Data\n"); } else if (bagnid == NID_pkcs7_encrypted) { if (options & INFO) { BIO_printf(bio_err, "PKCS7 Encrypted data: "); alg_print(p7->d.encrypted->enc_data->algorithm); } bags = PKCS12_unpack_p7encdata(p7, pass, passlen); } else { continue; } if (!bags) goto err; if (!dump_certs_pkeys_bags(out, bags, pass, passlen, options, pempass, enc)) { sk_PKCS12_SAFEBAG_pop_free(bags, PKCS12_SAFEBAG_free); goto err; } sk_PKCS12_SAFEBAG_pop_free(bags, PKCS12_SAFEBAG_free); bags = NULL; } ret = 1; err: sk_PKCS7_pop_free(asafes, PKCS7_free); return ret; } int dump_certs_pkeys_bags(BIO *out, const STACK_OF(PKCS12_SAFEBAG) *bags, const char *pass, int passlen, int options, char *pempass, const EVP_CIPHER *enc) { int i; for (i = 0; i < sk_PKCS12_SAFEBAG_num(bags); i++) { if (!dump_certs_pkeys_bag(out, sk_PKCS12_SAFEBAG_value(bags, i), pass, passlen, options, pempass, enc)) return 0; } return 1; } int dump_certs_pkeys_bag(BIO *out, const PKCS12_SAFEBAG *bag, const char *pass, int passlen, int options, char *pempass, const EVP_CIPHER *enc) { EVP_PKEY *pkey; PKCS8_PRIV_KEY_INFO *p8; const PKCS8_PRIV_KEY_INFO *p8c; X509 *x509; const STACK_OF(X509_ATTRIBUTE) *attrs; int ret = 0; attrs = PKCS12_SAFEBAG_get0_attrs(bag); switch (PKCS12_SAFEBAG_get_nid(bag)) { case NID_keyBag: if (options & INFO) BIO_printf(bio_err, "Key bag\n"); if (options & NOKEYS) return 1; print_attribs(out, attrs, "Bag Attributes"); p8c = PKCS12_SAFEBAG_get0_p8inf(bag); if ((pkey = EVP_PKCS82PKEY(p8c)) == NULL) return 0; print_attribs(out, PKCS8_pkey_get0_attrs(p8c), "Key Attributes"); ret = PEM_write_bio_PrivateKey(out, pkey, enc, NULL, 0, NULL, pempass); EVP_PKEY_free(pkey); break; case NID_pkcs8ShroudedKeyBag: if (options & INFO) { const X509_SIG *tp8; const X509_ALGOR *tp8alg; BIO_printf(bio_err, "Shrouded Keybag: "); tp8 = PKCS12_SAFEBAG_get0_pkcs8(bag); X509_SIG_get0(tp8, &tp8alg, NULL); alg_print(tp8alg); } if (options & NOKEYS) return 1; print_attribs(out, attrs, "Bag Attributes"); if ((p8 = PKCS12_decrypt_skey(bag, pass, passlen)) == NULL) return 0; if ((pkey = EVP_PKCS82PKEY(p8)) == NULL) { PKCS8_PRIV_KEY_INFO_free(p8); return 0; } print_attribs(out, PKCS8_pkey_get0_attrs(p8), "Key Attributes"); PKCS8_PRIV_KEY_INFO_free(p8); ret = PEM_write_bio_PrivateKey(out, pkey, enc, NULL, 0, NULL, pempass); EVP_PKEY_free(pkey); break; case NID_certBag: if (options & INFO) BIO_printf(bio_err, "Certificate bag\n"); if (options & NOCERTS) return 1; if (PKCS12_SAFEBAG_get0_attr(bag, NID_localKeyID)) { if (options & CACERTS) return 1; } else if (options & CLCERTS) return 1; print_attribs(out, attrs, "Bag Attributes"); if (PKCS12_SAFEBAG_get_bag_nid(bag) != NID_x509Certificate) return 1; if ((x509 = PKCS12_SAFEBAG_get1_cert(bag)) == NULL) return 0; dump_cert_text(out, x509); ret = PEM_write_bio_X509(out, x509); X509_free(x509); break; case NID_safeContentsBag: if (options & INFO) BIO_printf(bio_err, "Safe Contents bag\n"); print_attribs(out, attrs, "Bag Attributes"); return dump_certs_pkeys_bags(out, PKCS12_SAFEBAG_get0_safes(bag), pass, passlen, options, pempass, enc); default: BIO_printf(bio_err, "Warning unsupported bag type: "); i2a_ASN1_OBJECT(bio_err, PKCS12_SAFEBAG_get0_type(bag)); BIO_printf(bio_err, "\n"); return 1; } return ret; } /* Given a single certificate return a verified chain or NULL if error */ static int get_cert_chain(X509 *cert, X509_STORE *store, STACK_OF(X509) **chain) { X509_STORE_CTX *store_ctx = NULL; STACK_OF(X509) *chn = NULL; int i = 0; store_ctx = X509_STORE_CTX_new(); if (store_ctx == NULL) { i = X509_V_ERR_UNSPECIFIED; goto end; } if (!X509_STORE_CTX_init(store_ctx, store, cert, NULL)) { i = X509_V_ERR_UNSPECIFIED; goto end; } if (X509_verify_cert(store_ctx) > 0) chn = X509_STORE_CTX_get1_chain(store_ctx); else if ((i = X509_STORE_CTX_get_error(store_ctx)) == 0) i = X509_V_ERR_UNSPECIFIED; end: X509_STORE_CTX_free(store_ctx); *chain = chn; return i; } static int alg_print(const X509_ALGOR *alg) { int pbenid, aparamtype; const ASN1_OBJECT *aoid; const void *aparam; PBEPARAM *pbe = NULL; X509_ALGOR_get0(&aoid, &aparamtype, &aparam, alg); pbenid = OBJ_obj2nid(aoid); BIO_printf(bio_err, "%s", OBJ_nid2ln(pbenid)); /* * If PBE algorithm is PBES2 decode algorithm parameters * for additional details. */ if (pbenid == NID_pbes2) { PBE2PARAM *pbe2 = NULL; int encnid; if (aparamtype == V_ASN1_SEQUENCE) pbe2 = ASN1_item_unpack(aparam, ASN1_ITEM_rptr(PBE2PARAM)); if (pbe2 == NULL) { BIO_puts(bio_err, ", <unsupported parameters>"); goto done; } X509_ALGOR_get0(&aoid, &aparamtype, &aparam, pbe2->keyfunc); pbenid = OBJ_obj2nid(aoid); X509_ALGOR_get0(&aoid, NULL, NULL, pbe2->encryption); encnid = OBJ_obj2nid(aoid); BIO_printf(bio_err, ", %s, %s", OBJ_nid2ln(pbenid), OBJ_nid2sn(encnid)); /* If KDF is PBKDF2 decode parameters */ if (pbenid == NID_id_pbkdf2) { PBKDF2PARAM *kdf = NULL; int prfnid; if (aparamtype == V_ASN1_SEQUENCE) kdf = ASN1_item_unpack(aparam, ASN1_ITEM_rptr(PBKDF2PARAM)); if (kdf == NULL) { BIO_puts(bio_err, ", <unsupported parameters>"); goto done; } if (kdf->prf == NULL) { prfnid = NID_hmacWithSHA1; } else { X509_ALGOR_get0(&aoid, NULL, NULL, kdf->prf); prfnid = OBJ_obj2nid(aoid); } BIO_printf(bio_err, ", Iteration %ld, PRF %s", ASN1_INTEGER_get(kdf->iter), OBJ_nid2sn(prfnid)); PBKDF2PARAM_free(kdf); #ifndef OPENSSL_NO_SCRYPT } else if (pbenid == NID_id_scrypt) { SCRYPT_PARAMS *kdf = NULL; if (aparamtype == V_ASN1_SEQUENCE) kdf = ASN1_item_unpack(aparam, ASN1_ITEM_rptr(SCRYPT_PARAMS)); if (kdf == NULL) { BIO_puts(bio_err, ", <unsupported parameters>"); goto done; } BIO_printf(bio_err, ", Salt length: %d, Cost(N): %ld, " "Block size(r): %ld, Parallelism(p): %ld", ASN1_STRING_length(kdf->salt), ASN1_INTEGER_get(kdf->costParameter), ASN1_INTEGER_get(kdf->blockSize), ASN1_INTEGER_get(kdf->parallelizationParameter)); SCRYPT_PARAMS_free(kdf); #endif } PBE2PARAM_free(pbe2); } else { if (aparamtype == V_ASN1_SEQUENCE) pbe = ASN1_item_unpack(aparam, ASN1_ITEM_rptr(PBEPARAM)); if (pbe == NULL) { BIO_puts(bio_err, ", <unsupported parameters>"); goto done; } BIO_printf(bio_err, ", Iteration %ld", ASN1_INTEGER_get(pbe->iter)); PBEPARAM_free(pbe); } done: BIO_puts(bio_err, "\n"); return 1; } /* Load all certificates from a given file */ int cert_load(BIO *in, STACK_OF(X509) *sk) { int ret = 0; X509 *cert; while ((cert = PEM_read_bio_X509(in, NULL, NULL, NULL))) { ret = 1; if (!sk_X509_push(sk, cert)) return 0; } if (ret) ERR_clear_error(); return ret; } /* Generalised x509 attribute value print */ void print_attribute(BIO *out, const ASN1_TYPE *av) { char *value; switch (av->type) { case V_ASN1_BMPSTRING: value = OPENSSL_uni2asc(av->value.bmpstring->data, av->value.bmpstring->length); BIO_printf(out, "%s\n", value); OPENSSL_free(value); break; case V_ASN1_OCTET_STRING: hex_prin(out, av->value.octet_string->data, av->value.octet_string->length); BIO_printf(out, "\n"); break; case V_ASN1_BIT_STRING: hex_prin(out, av->value.bit_string->data, av->value.bit_string->length); BIO_printf(out, "\n"); break; default: BIO_printf(out, "<Unsupported tag %d>\n", av->type); break; } } /* Generalised attribute print: handle PKCS#8 and bag attributes */ int print_attribs(BIO *out, const STACK_OF(X509_ATTRIBUTE) *attrlst, const char *name) { X509_ATTRIBUTE *attr; ASN1_TYPE *av; int i, j, attr_nid; if (!attrlst) { BIO_printf(out, "%s: <No Attributes>\n", name); return 1; } if (!sk_X509_ATTRIBUTE_num(attrlst)) { BIO_printf(out, "%s: <Empty Attributes>\n", name); return 1; } BIO_printf(out, "%s\n", name); for (i = 0; i < sk_X509_ATTRIBUTE_num(attrlst); i++) { ASN1_OBJECT *attr_obj; attr = sk_X509_ATTRIBUTE_value(attrlst, i); attr_obj = X509_ATTRIBUTE_get0_object(attr); attr_nid = OBJ_obj2nid(attr_obj); BIO_printf(out, " "); if (attr_nid == NID_undef) { i2a_ASN1_OBJECT(out, attr_obj); BIO_printf(out, ": "); } else { BIO_printf(out, "%s: ", OBJ_nid2ln(attr_nid)); } if (X509_ATTRIBUTE_count(attr)) { for (j = 0; j < X509_ATTRIBUTE_count(attr); j++) { av = X509_ATTRIBUTE_get0_type(attr, j); print_attribute(out, av); } } else { BIO_printf(out, "<No Values>\n"); } } return 1; } void hex_prin(BIO *out, unsigned char *buf, int len) { int i; for (i = 0; i < len; i++) BIO_printf(out, "%02X ", buf[i]); } static int set_pbe(int *ppbe, const char *str) { if (!str) return 0; if (strcmp(str, "NONE") == 0) { *ppbe = -1; return 1; } *ppbe = OBJ_txt2nid(str); if (*ppbe == NID_undef) { BIO_printf(bio_err, "Unknown PBE algorithm %s\n", str); return 0; } return 1; }
322540.c
#include "defs.h" #include DEF_MPERS_TYPE(struct_keyctl_kdf_params) #include "keyctl_kdf_params.h" typedef struct keyctl_kdf_params struct_keyctl_kdf_params; #include MPERS_DEFS MPERS_PRINTER_DECL(int, fetch_keyctl_kdf_params, struct tcb *const tcp, kernel_ulong_t addr, struct strace_keyctl_kdf_params *p) { struct_keyctl_kdf_params kdf; int ret; if ((ret = umove(tcp, addr, &kdf))) return ret; p->hashname = (kernel_ulong_t) #ifndef IN_MPERS (uintptr_t) #endif kdf.hashname; p->otherinfo = (kernel_ulong_t) #ifndef IN_MPERS (uintptr_t) #endif kdf.otherinfo; p->otherinfolen = kdf.otherinfolen; memcpy(p->__spare, kdf.__spare, sizeof(kdf.__spare)); return 0; }
305206.c
/* * ngtcp2 * * Copyright (c) 2017 ngtcp2 contributors * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "ngtcp2_acktr.h" #include <assert.h> #include "ngtcp2_macro.h" int ngtcp2_acktr_entry_new(ngtcp2_acktr_entry **ent, uint64_t pkt_num, ngtcp2_tstamp tstamp, ngtcp2_mem *mem) { *ent = ngtcp2_mem_malloc(mem, sizeof(ngtcp2_acktr_entry)); if (*ent == NULL) { return NGTCP2_ERR_NOMEM; } (*ent)->pkt_num = pkt_num; (*ent)->len = 1; (*ent)->tstamp = tstamp; return 0; } void ngtcp2_acktr_entry_del(ngtcp2_acktr_entry *ent, ngtcp2_mem *mem) { ngtcp2_mem_free(mem, ent); } static int greater(const ngtcp2_ksl_key *lhs, const ngtcp2_ksl_key *rhs) { return lhs->i > rhs->i; } int ngtcp2_acktr_init(ngtcp2_acktr *acktr, ngtcp2_log *log, ngtcp2_mem *mem) { int rv; ngtcp2_ksl_key inf_key = {-1}; rv = ngtcp2_ringbuf_init(&acktr->acks, 128, sizeof(ngtcp2_acktr_ack_entry), mem); if (rv != 0) { return rv; } rv = ngtcp2_ksl_init(&acktr->ents, greater, &inf_key, mem); if (rv != 0) { ngtcp2_ringbuf_free(&acktr->acks); return rv; } acktr->log = log; acktr->mem = mem; acktr->flags = NGTCP2_ACKTR_FLAG_NONE; acktr->first_unacked_ts = UINT64_MAX; acktr->rx_npkt = 0; return 0; } void ngtcp2_acktr_free(ngtcp2_acktr *acktr) { ngtcp2_ksl_it it; if (acktr == NULL) { return; } for (it = ngtcp2_ksl_begin(&acktr->ents); !ngtcp2_ksl_it_end(&it); ngtcp2_ksl_it_next(&it)) { ngtcp2_acktr_entry_del(ngtcp2_ksl_it_get(&it), acktr->mem); } ngtcp2_ksl_free(&acktr->ents); ngtcp2_ringbuf_free(&acktr->acks); } int ngtcp2_acktr_add(ngtcp2_acktr *acktr, uint64_t pkt_num, int active_ack, ngtcp2_tstamp ts) { ngtcp2_ksl_it it; ngtcp2_acktr_entry *ent, *prev_ent, *delent; int rv; int added = 0; if (ngtcp2_ksl_len(&acktr->ents)) { it = ngtcp2_ksl_lower_bound(&acktr->ents, (const ngtcp2_ksl_key *)&pkt_num); if (ngtcp2_ksl_it_end(&it)) { ngtcp2_ksl_it_prev(&it); ent = ngtcp2_ksl_it_get(&it); assert(ent->pkt_num >= pkt_num + ent->len); if (ent->pkt_num == pkt_num + ent->len) { ++ent->len; added = 1; } } else { ent = ngtcp2_ksl_it_get(&it); assert(ent->pkt_num != pkt_num); if (ngtcp2_ksl_it_begin(&it)) { if (ent->pkt_num + 1 == pkt_num) { ngtcp2_ksl_update_key(&acktr->ents, (const ngtcp2_ksl_key *)&ent->pkt_num, (const ngtcp2_ksl_key *)&pkt_num); ent->pkt_num = pkt_num; ent->tstamp = ts; ++ent->len; added = 1; } } else { ngtcp2_ksl_it_prev(&it); prev_ent = ngtcp2_ksl_it_get(&it); assert(prev_ent->pkt_num >= pkt_num + prev_ent->len); if (ent->pkt_num + 1 == pkt_num) { if (prev_ent->pkt_num == pkt_num + prev_ent->len) { prev_ent->len += ent->len + 1; rv = ngtcp2_ksl_remove(&acktr->ents, NULL, (const ngtcp2_ksl_key *)&ent->pkt_num); if (rv != 0) { return rv; } ngtcp2_acktr_entry_del(ent, acktr->mem); added = 1; } else { ngtcp2_ksl_update_key(&acktr->ents, (const ngtcp2_ksl_key *)&ent->pkt_num, (const ngtcp2_ksl_key *)&pkt_num); ent->pkt_num = pkt_num; ent->tstamp = ts; ++ent->len; added = 1; } } else if (prev_ent->pkt_num == pkt_num + prev_ent->len) { ++prev_ent->len; added = 1; } } } } if (!added) { rv = ngtcp2_acktr_entry_new(&ent, pkt_num, ts, acktr->mem); if (rv != 0) { return rv; } rv = ngtcp2_ksl_insert(&acktr->ents, NULL, (const ngtcp2_ksl_key *)&ent->pkt_num, ent); if (rv != 0) { ngtcp2_acktr_entry_del(ent, acktr->mem); return rv; } } if (active_ack) { acktr->flags |= NGTCP2_ACKTR_FLAG_ACTIVE_ACK; if (acktr->first_unacked_ts == UINT64_MAX) { acktr->first_unacked_ts = ts; } } if (ngtcp2_ksl_len(&acktr->ents) > NGTCP2_ACKTR_MAX_ENT) { it = ngtcp2_ksl_end(&acktr->ents); ngtcp2_ksl_it_prev(&it); delent = ngtcp2_ksl_it_get(&it); rv = ngtcp2_ksl_remove(&acktr->ents, NULL, (const ngtcp2_ksl_key *)&delent->pkt_num); if (rv != 0) { return rv; } ngtcp2_acktr_entry_del(delent, acktr->mem); } return 0; } int ngtcp2_acktr_forget(ngtcp2_acktr *acktr, ngtcp2_acktr_entry *ent) { ngtcp2_ksl_it it; int rv; it = ngtcp2_ksl_lower_bound(&acktr->ents, (const ngtcp2_ksl_key *)&ent->pkt_num); assert(ngtcp2_ksl_it_key(&it).i == (int64_t)ent->pkt_num); for (; !ngtcp2_ksl_it_end(&it);) { ent = ngtcp2_ksl_it_get(&it); rv = ngtcp2_ksl_remove(&acktr->ents, &it, (const ngtcp2_ksl_key *)&ent->pkt_num); if (rv != 0) { return rv; } ngtcp2_acktr_entry_del(ent, acktr->mem); } return 0; } ngtcp2_ksl_it ngtcp2_acktr_get(ngtcp2_acktr *acktr) { return ngtcp2_ksl_begin(&acktr->ents); } ngtcp2_acktr_ack_entry *ngtcp2_acktr_add_ack(ngtcp2_acktr *acktr, uint64_t pkt_num, uint64_t largest_ack) { ngtcp2_acktr_ack_entry *ent = ngtcp2_ringbuf_push_front(&acktr->acks); ent->largest_ack = largest_ack; ent->pkt_num = pkt_num; return ent; } /* * acktr_remove removes |ent| from |acktr|. The iterator which points * to the entry next to |ent| is assigned to |it|. * * This function returns 0 if it succeeds, or one of the following * negative error codes: * * NGTCP2_ERR_NOMEM * Out of memory. */ static int acktr_remove(ngtcp2_acktr *acktr, ngtcp2_ksl_it *it, ngtcp2_acktr_entry *ent) { int rv; rv = ngtcp2_ksl_remove(&acktr->ents, it, (const ngtcp2_ksl_key *)&ent->pkt_num); if (rv != 0) { return rv; } ngtcp2_acktr_entry_del(ent, acktr->mem); return 0; } static int acktr_on_ack(ngtcp2_acktr *acktr, ngtcp2_ringbuf *rb, size_t ack_ent_offset) { ngtcp2_acktr_ack_entry *ack_ent; ngtcp2_acktr_entry *ent; ngtcp2_ksl_it it; int rv; assert(ngtcp2_ringbuf_len(rb)); ack_ent = ngtcp2_ringbuf_get(rb, ack_ent_offset); /* Assume that ngtcp2_pkt_validate_ack(fr) returns 0 */ it = ngtcp2_ksl_lower_bound(&acktr->ents, (const ngtcp2_ksl_key *)&ack_ent->largest_ack); for (; !ngtcp2_ksl_it_end(&it);) { ent = ngtcp2_ksl_it_get(&it); rv = acktr_remove(acktr, &it, ent); if (rv != 0) { return rv; } } if (ngtcp2_ksl_len(&acktr->ents)) { assert(ngtcp2_ksl_it_end(&it)); ngtcp2_ksl_it_prev(&it); ent = ngtcp2_ksl_it_get(&it); if (ent->pkt_num > ack_ent->largest_ack && ack_ent->largest_ack >= ent->pkt_num - (ent->len - 1)) { ent->len = ent->pkt_num - ack_ent->largest_ack; } } ngtcp2_ringbuf_resize(rb, ack_ent_offset); return 0; } int ngtcp2_acktr_recv_ack(ngtcp2_acktr *acktr, const ngtcp2_ack *fr) { ngtcp2_acktr_ack_entry *ent; uint64_t largest_ack = fr->largest_ack, min_ack; size_t i, j; ngtcp2_ringbuf *rb = &acktr->acks; size_t nacks = ngtcp2_ringbuf_len(rb); int rv; /* Assume that ngtcp2_pkt_validate_ack(fr) returns 0 */ for (j = 0; j < nacks; ++j) { ent = ngtcp2_ringbuf_get(rb, j); if (largest_ack >= ent->pkt_num) { break; } } if (j == nacks) { return 0; } min_ack = largest_ack - fr->first_ack_blklen; if (min_ack <= ent->pkt_num && ent->pkt_num <= largest_ack) { rv = acktr_on_ack(acktr, rb, j); if (rv != 0) { return rv; } return 0; } for (i = 0; i < fr->num_blks && j < nacks; ++i) { largest_ack = min_ack - fr->blks[i].gap - 2; min_ack = largest_ack - fr->blks[i].blklen; for (;;) { if (ent->pkt_num > largest_ack) { ++j; if (j == nacks) { return 0; } ent = ngtcp2_ringbuf_get(rb, j); continue; } if (ent->pkt_num < min_ack) { break; } return acktr_on_ack(acktr, rb, j); } } return 0; } void ngtcp2_acktr_commit_ack(ngtcp2_acktr *acktr) { acktr->flags &= (uint16_t) ~(NGTCP2_ACKTR_FLAG_ACTIVE_ACK | NGTCP2_ACKTR_FLAG_IMMEDIATE_ACK); acktr->first_unacked_ts = UINT64_MAX; acktr->rx_npkt = 0; } int ngtcp2_acktr_require_active_ack(ngtcp2_acktr *acktr, uint64_t max_ack_delay, ngtcp2_tstamp ts) { return (acktr->flags & NGTCP2_ACKTR_FLAG_ACTIVE_ACK) && acktr->first_unacked_ts <= ts - max_ack_delay; } void ngtcp2_acktr_immediate_ack(ngtcp2_acktr *acktr) { acktr->flags |= NGTCP2_ACKTR_FLAG_IMMEDIATE_ACK; }