filename
stringlengths
3
9
code
stringlengths
4
1.05M
171095.c
#include <Python.h> #if PY_VERSION_HEX >= 0x03000000 #error #endif int main(void) { return 0; }
630912.c
/* xstat using old-style Unix stat system call. Copyright (C) 1991,95,96,97,98,2000 Free Software Foundation, Inc. This file is part of the GNU C Library. The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. */ /* Ho hum, if xstat == xstat64 we must get rid of the prototype or gcc will complain since they don't strictly match. */ #define __xstat64 __xstat64_disable #include <errno.h> #include <stddef.h> #include <sys/stat.h> #include <kernel_stat.h> #include <sysdep.h> #include <sys/syscall.h> #include <bp-checks.h> #include "kernel-features.h" #include <xstatconv.c> extern int __syscall_stat (const char *__unbounded, struct kernel_stat *__unbounded); #ifdef __NR_stat64 extern int __syscall_stat64 (const char *__unbounded, struct stat64 *__unbounded); # if __ASSUME_STAT64_SYSCALL == 0 /* The variable is shared between all wrappers around *stat64 calls. */ extern int __have_no_stat64; # endif #endif /* Get information about the file NAME in BUF. */ int __xstat (int vers, const char *name, struct stat *buf) { #if __ASSUME_STAT64_SYSCALL == 0 struct kernel_stat kbuf; #endif int result; if (vers == _STAT_VER_KERNEL) return INLINE_SYSCALL (stat, 2, CHECK_STRING (name), CHECK_1 ((struct kernel_stat *) buf)); #if __ASSUME_STAT64_SYSCALL > 0 { struct stat64 buf64; result = INLINE_SYSCALL (stat64, 2, CHECK_STRING (name), __ptrvalue (&buf64)); if (result == 0) result = xstat32_conv (vers, &buf64, buf); return result; } #else # if defined __NR_stat64 /* To support 32 bit UIDs, we have to use stat64. The normal stat call only returns 16 bit UIDs. */ if (! __have_no_stat64) { struct stat64 buf64; result = INLINE_SYSCALL (stat64, 2, CHECK_STRING (name), __ptrvalue (&buf64)); if (result == 0) result = xstat32_conv (vers, &buf64, buf); if (result != -1 || errno != ENOSYS) return result; __have_no_stat64 = 1; } # endif result = INLINE_SYSCALL (stat, 2, CHECK_STRING (name), __ptrvalue (&kbuf)); if (result == 0) result = xstat_conv (vers, &kbuf, buf); return result; #endif /* __ASSUME_STAT64_SYSCALL */ } weak_alias (__xstat, _xstat); #ifdef XSTAT_IS_XSTAT64 # undef __xstat64 strong_alias (__xstat, __xstat64); #endif
316581.c
/* SPU opcode list Copyright 2006 Free Software Foundation, Inc. This file is part of GDB, GAS, and the GNU binutils. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston, MA 02110-1301, USA. */ #include "opcode/spu.h" /* This file holds the Spu opcode table */ /* Example contents of spu-insn.h id_tag mode mode type opcode mnemonic asmtype dependency FPU L/S? branch? instruction QUAD WORD (0,RC,RB,RA,RT) latency APUOP(M_LQD, 1, 0, RI9, 0x1f8, "lqd", ASM_RI9IDX, 00012, FXU, 1, 0) Load Quadword d-form */ const struct spu_opcode spu_opcodes[] = { #define APUOP(TAG,MACFORMAT,OPCODE,MNEMONIC,ASMFORMAT,DEP,PIPE) \ { MACFORMAT, OPCODE, MNEMONIC, ASMFORMAT }, #define APUOPFB(TAG,MACFORMAT,OPCODE,FB,MNEMONIC,ASMFORMAT,DEP,PIPE) \ { MACFORMAT, OPCODE, MNEMONIC, ASMFORMAT }, #include "opcode/spu-insns.h" #undef APUOP #undef APUOPFB }; const int spu_num_opcodes = sizeof (spu_opcodes) / sizeof (spu_opcodes[0]);
776463.c
/* { dg-do compile { target { powerpc*-*-* } } } */ /* { dg-skip-if "do not override -mcpu" { powerpc*-*-* } { "-mcpu=*" } { "-mcpu=power9" } } */ /* { dg-require-effective-target powerpc_p9vector_ok } */ /* { dg-skip-if "" { powerpc*-*-aix* } } */ /* { dg-options "-mcpu=power9" } */ #include <altivec.h> int doTestBCDSignificance (_Decimal64 *p) { _Decimal64 source = *p; if (__builtin_dfp_dtstsfi_eq (63, source)) return 3; else return 5; } /* { dg-final { scan-assembler "dtstsfi" } } */
842487.c
/* getplay.c - Procedures for saving and retrieving a characters Last Modified: 09/16/86 UltraRogue Copyright (C) 1984, 1985, 1986 Herb Chong All rights reserved. Based on "Advanced Rogue" Copyright (C) 1983, 1984 Michael Morgan, Ken Dalka and AT&T All rights reserved. See the file LICENSE.TXT for full copyright and licensing information.*/ */ /* * Procedures for saving and retrieving a characters * starting attributes, armour, and weapon. * New addition to version 1.3 by S. A. Hester 11/8/83 */ #include <stdio.h> #include <ctype.h> #include "rogue.h" #define I_STR 0 #define I_INTEL 1 #define I_WISDOM 2 #define I_DEXT 3 #define I_CONST 4 #define I_CHARISMA 5 #define I_HPT 6 #define I_POWER 7 #define I_CTYPE 8 #define MAXPATT 9 /* Total Number of above defines. */ #define MAXPDEF 10 /* Maximum number of pre-defined chars */ static int def_array[MAXPDEF][MAXPATT]; /* Pre-def'd chars */ int geta_player() { int i; int fd; char pbuf[2 * LINELEN]; if ((fd = open("urogue.chr", 0)) < 0) return FALSE; encread((char *) def_array, sizeof(def_array), fd); close(fd); wclear(hw); touchwin(hw); print_stored(); mvwaddstr(hw, 0, 0, "Do you wish to select a character? "); wrefresh(hw); if ((getchar() & 0177) != 'y') return FALSE; do { wmove(hw, LINES - 1, 0); wclrtoeol(hw); mvwaddstr(hw, 0, 0, "Enter the number of a pre-defined character: "); wclrtoeol(hw); wrefresh(hw); get_str(pbuf, hw); i = atoi(pbuf) - 1; if (i < 0 || i > MAXPDEF - 1) { wstandout(hw); mvwaddstr(hw, 1, 0, "Please use the range 1 to"); wprintw(hw, " %d.", MAXPDEF); wstandend(hw); wclrtoeol(hw); wrefresh(hw); } else if (def_array[i][I_STR] == 0) { wstandout(hw); mvwaddstr(hw,1,0,"Please enter the number of a known character: "); wstandend(hw); wclrtoeol(hw); } else { mvwaddstr(hw, 1, 0, ""); wclrtoeol(hw); } } while (i < 0 || i > MAXPDEF - 1 || (def_array[i][I_STR] == 0)); pstats.s_str = def_array[i][I_STR]; pstats.s_intel = def_array[i][I_INTEL]; pstats.s_wisdom = def_array[i][I_WISDOM]; pstats.s_dext = def_array[i][I_DEXT]; pstats.s_const = def_array[i][I_CONST]; pstats.s_charisma = def_array[i][I_CHARISMA]; pstats.s_hpt = def_array[i][I_HPT]; pstats.s_power = def_array[i][I_POWER]; player.t_ctype = char_type = def_array[i][I_CTYPE]; max_stats = pstats; return(TRUE); } int puta_player() { int fd; char pbuf[2 * LINELEN]; short i; char *class = which_class(player.t_ctype); sprintf(pbuf, "You have a %s with the following attributes:", class); mvwaddstr(hw, 2, 0, pbuf); wclrtoeol(hw); sprintf(pbuf, "Int: %d Str: %d Wis: %d Dex: %d Con: %d Cha: %d Pow: %d Hpt: %d", pstats.s_intel, pstats.s_str, pstats.s_wisdom, pstats.s_dext, pstats.s_const, pstats.s_charisma, pstats.s_power, pstats.s_hpt ); mvwaddstr(hw, 3, 0, ""); wclrtoeol(hw); mvwaddstr(hw, 4, 0, pbuf); wclrtoeol(hw); mvwaddstr(hw, 5, 0, ""); wclrtoeol(hw); mvwaddstr(hw, 0, 0, "Would you like to save this character?"); wclrtoeol(hw); wrefresh(hw); if ((getchar() & 0177) != 'y') return(TRUE); do { mvwaddstr(hw, 0, 0, "Overwrite which number? "); wclrtoeol(hw); wrefresh(hw); get_str(pbuf, hw); i = atoi(pbuf) - 1; if (i < 0 || i > MAXPDEF - 1) { wstandout(hw); mvwaddstr(hw, 1, 0, "Use the range 1 to"); wprintw(hw, " %d!", MAXPDEF); wstandend(hw); wclrtoeol(hw); wrefresh(hw); } } while (i < 0 || i > MAXPDEF - 1); /* Set some global stuff */ def_array[i][I_STR] = pstats.s_str; def_array[i][I_INTEL] = pstats.s_intel; def_array[i][I_WISDOM] = pstats.s_wisdom; def_array[i][I_DEXT] = pstats.s_dext; def_array[i][I_CONST] = pstats.s_const; def_array[i][I_CHARISMA] = pstats.s_charisma; def_array[i][I_HPT] = pstats.s_hpt; def_array[i][I_POWER] = pstats.s_power; def_array[i][I_CTYPE] = player.t_ctype; /* OK. Now let's write this stuff out! */ if ((fd = creat("urogue.chr", 0644)) < 0) { sprintf(pbuf, "I can't seem to open/create urogue.chr."); mvwaddstr(hw, 5, 5, pbuf); mvwaddstr(hw, 6, 5, "However I'll let you play it anyway!"); mvwaddstr(hw, LINES - 1, 0, spacemsg); wrefresh(hw); wait_for(' '); return(TRUE); } encwrite((char *) def_array, sizeof(def_array), fd); close(fd); return(TRUE); } void do_getplayer() { if (char_type == C_NOTSET) do { /* See what type character will be */ mvwaddstr(hw, 3, 0, "[a] Fighter\t" "[b] Paladin\t" "[c] Ranger\n" "[d] Cleric\t" "[e] Druid\t" "[f] Magician\n" "[g] Illusionist\t" "[h] Thief\t" "[i] Assasin\t" "[j] Ninja"); mvwaddstr(hw, 0, 0, "What character class do you desire? "); wrefresh(hw); char_type = readchar() - 'a'; if (char_type < C_FIGHTER || char_type >= C_MONSTER) { wstandout(hw); mvwaddstr(hw, 1, 0, "Please enter a letter from a - j"); wstandend(hw); wclrtoeol(hw); wrefresh(hw); } else { mvwaddstr(hw, 1, 0, ""); wclrtoeol(hw); } } while (char_type < C_FIGHTER || char_type >= C_MONSTER); player.t_ctype = char_type; } void print_stored() { int i; char *class; char pbuf[2 * LINELEN]; wstandout(hw); mvwaddstr(hw, 9, 0, "YOUR CURRENT CHARACTERS:"); wstandend(hw); wclrtoeol(hw); for (i = 0; i < MAXPDEF; i++) { if (def_array[i][I_STR]) { class = which_class(def_array[i][I_CTYPE]); sprintf(pbuf, "%d. (%s): Int: %d Str: %d Wis: %d Dex: %d Con: %d Cha: %d" " Pow: %d Hpt: %d", i + 1, class, def_array[i][I_INTEL], def_array[i][I_STR], def_array[i][I_WISDOM], def_array[i][I_DEXT], def_array[i][I_CONST], def_array[i][I_CHARISMA], def_array[i][I_POWER], def_array[i][I_HPT]); mvwaddstr(hw, 11 + i, 0, pbuf); } else { sprintf(pbuf, "%d. ### NONE ###", i + 1); mvwaddstr(hw, 11 + i, 0, pbuf); } } } char * which_class(int c_class) { char *class; switch (c_class) { case C_FIGHTER: class = "fighter"; case C_MAGICIAN: class = "magician"; case C_CLERIC: class = "cleric"; case C_THIEF: class = "thief"; case C_PALADIN: class = "paladin"; case C_RANGER: class = "ranger"; case C_DRUID: class = "druid"; case C_ILLUSION: class = "illusionist"; case C_ASSASIN: class = "assasin"; case C_NINJA: class = "ninja"; default: class = "monster"; } return (class); }
751325.c
/* * (C) Copyright 2011 - 2012 Samsung Electronics * EXT4 filesystem implementation in Uboot by * Uma Shankar <uma.shankar@samsung.com> * Manjunatha C Achar <a.manjunatha@samsung.com> * * Ext4fs support * made from existing cmd_ext2.c file of Uboot * * (C) Copyright 2004 * esd gmbh <www.esd-electronics.com> * Reinhard Arlt <reinhard.arlt@esd-electronics.com> * * made from cmd_reiserfs by * * (C) Copyright 2003 - 2004 * Sysgo Real-Time Solutions, AG <www.elinos.com> * Pavel Bartusek <pba@sysgo.com> * * SPDX-License-Identifier: GPL-2.0+ */ /* * Changelog: * 0.1 - Newly created file for ext4fs support. Taken from cmd_ext2.c * file in uboot. Added ext4fs ls load and write support. */ #include <common.h> #include <part.h> #include <config.h> #include <command.h> #include <image.h> #include <linux/ctype.h> #include <asm/byteorder.h> #include <ext4fs.h> #include <linux/stat.h> #include <malloc.h> #include <fs.h> #if defined(CONFIG_CMD_USB) && defined(CONFIG_USB_STORAGE) #include <usb.h> #endif int do_ext4_load(cmd_tbl_t *cmdtp, int flag, int argc, char *const argv[]) { return do_load(cmdtp, flag, argc, argv, FS_TYPE_EXT); } int do_ext4_ls(cmd_tbl_t *cmdtp, int flag, int argc, char *const argv[]) { return do_ls(cmdtp, flag, argc, argv, FS_TYPE_EXT); } #if defined(CONFIG_CMD_EXT4_WRITE) int do_ext4_write(cmd_tbl_t *cmdtp, int flag, int argc, char *const argv[]) { const char *filename = "/"; int dev, part; unsigned long ram_address; unsigned long file_size; disk_partition_t info; block_dev_desc_t *dev_desc; if (argc < 6) return cmd_usage(cmdtp); part = get_device_and_partition(argv[1], argv[2], &dev_desc, &info, 1); if (part < 0) return 1; dev = dev_desc->dev; /* get the filename */ filename = argv[4]; /* get the address in hexadecimal format (string to int) */ ram_address = simple_strtoul(argv[3], NULL, 16); /* get the filesize in hexadecimal format */ file_size = simple_strtoul(argv[5], NULL, 16); /* set the device as block device */ ext4fs_set_blk_dev(dev_desc, &info); /* mount the filesystem */ if (!ext4fs_mount(info.size)) { printf("Bad ext4 partition %s %d:%d\n", argv[1], dev, part); goto fail; } /* start write */ if (ext4fs_write(filename, (unsigned char *)ram_address, file_size)) { printf("** Error ext4fs_write() **\n"); goto fail; } ext4fs_close(); return 0; fail: ext4fs_close(); return 1; } U_BOOT_CMD(ext4write, 6, 1, do_ext4_write, "create a file in the root directory", "<interface> <dev[:part]> <addr> <absolute filename path> [sizebytes]\n" " - create a file in / directory"); #endif U_BOOT_CMD(ext4ls, 4, 1, do_ext4_ls, "list files in a directory (default /)", "<interface> <dev[:part]> [directory]\n" " - list files from 'dev' on 'interface' in a 'directory'"); U_BOOT_CMD(ext4load, 6, 0, do_ext4_load, "load binary file from a Ext4 filesystem", "<interface> <dev[:part]> [addr] [filename] [bytes]\n" " - load binary file 'filename' from 'dev' on 'interface'\n" " to address 'addr' from ext4 filesystem");
511177.c
#include <stdio.h> #include <stdlib.h> #include <string.h> #include "../jsmn.h" /* * A small example of jsmn parsing when JSON structure is known and number of * tokens is predictable. */ char *readJSONFILE(char *file){ FILE *fp; char input[256]; int len = 0; strcat(file,".json"); fp = fopen(file , "rt"); if(fp==NULL){printf("%s 파일이 존재하지 않습니다\n",file); exit(1);} char *save = (char *)malloc(sizeof(char) * 256); while(1){ fgets(input , sizeof(input) , fp); if( feof(fp) ) { break ; } len += strlen(input); save= realloc(save, len + 1); strcat(save, input); //malloc, ralloc } //printf("%s\n", JSON_STRING); fclose(fp); return save; } static int jsoneq(const char *json, jsmntok_t *tok, const char *s) { if (tok->type == JSMN_STRING && (int) strlen(s) == tok->end - tok->start && strncmp(json + tok->start, s, tok->end - tok->start) == 0) { return 0; } return -1; } void jsonNameList(char *jsontr, jsmntok_t *t, int tokcount,int *nameTokIndex){ //printf("***** Name List ******\n"); int i; int j=0; for (i = 1; i < tokcount; i++) { if(t[i].type==JSMN_STRING){ if(t[i].size>0){ //if(t[i].parent!){ nameTokIndex[j]=i; ++j; // if(t[i].parent==0){ // // printf("[Name %d] %.*s\n",j,t[i].end-t[i].start,jsontr + t[i].start); } } } } void printNameList(char *jsontr, jsmntok_t *t, int *nameTokIndex,int *nt){ int i=0,j=1; int temp=0; if(t[t[t[t[nameTokIndex[1]].parent].parent].parent].type==JSMN_STRING){ temp=t[nameTokIndex[1]].parent; } else{ temp=t[nameTokIndex[0]].parent;} printf("***** Name List ******\n"); while(nameTokIndex[i]!=0){ if(t[t[nameTokIndex[i]].parent].parent==t[temp].parent){ nt[j-1]=nameTokIndex[i]; printf("[Name %d] %.*s\n",j,t[nameTokIndex[i]].end-t[nameTokIndex[i]].start,jsontr + t[nameTokIndex[i]].start); j++; } ++i; } } void selectNameList(char *jsontr, jsmntok_t *t, int *nameTokIndex){ int num; while(1){ printf("select Name's no (exit:0) >> "); scanf("%d",&num); if(num==0){return ;} if(nameTokIndex[num-1]==0) {printf("not correct name number retry!"); continue;} printf("[Name %d] %.*s\n",num,t[nameTokIndex[num-1]].end-t[nameTokIndex[num-1]].start,jsontr + t[nameTokIndex[num-1]].start); printf("%.*s\n",t[nameTokIndex[num-1]+1].end-t[nameTokIndex[num-1]+1].start,jsontr + t[nameTokIndex[num-1]+1].start); } } void ObjectNameList(char *jsontr, jsmntok_t *t, int *nameTokIndex, int *objectList){ printf("***** Object List ******\n"); int i=0; int j=1; int index=0; int temp=0; int *a; if(t[t[t[t[nameTokIndex[1]].parent].parent].parent].type==JSMN_STRING){ temp=t[t[nameTokIndex[1]].parent].parent; } else{ temp=t[t[nameTokIndex[0]].parent].parent;} while(nameTokIndex[i]!=0){ index=nameTokIndex[i]; if(t[index-1].parent==temp){ //printf("%d\n",temp); objectList[j-1]=index-1; objectList=(int *)realloc(objectList,sizeof(int)*(j+1)); printf("[Name %d] %.*s\n",j,t[index+1].end-t[index+1].start,jsontr + t[index+1].start); j++; } i++; } } // void check(jsmntok_t *t, int *objectList, int *nameTokIndex, int *nt, int **ntD){ // ntD=(int *)malloc(sizeof(int)*(sizeof(objectList)/sizeof(int))); // // for() // if(t[nt[i]].parent==objectList[]) // a++; // else if() // } // } void printSelectObjectNameList(char *jsontr,jsmntok_t *t, int *objectList,int *nameTokIndex, int *nt){ int num=0; int j=0; int k=0; //while(1){ printf("원하는 번호 입력 (Exit: 0) : "); scanf("%d",&num); int i=0; if(num==0){ return;} int o1=objectList[num-1]; while(nt[i]!=0){ if(t[nt[i]].parent==o1){ break; } i++; } printf("%.*s : %.*s\n",t[o1+1].end-t[o1+1].start,jsontr + t[o1+1].start,t[o1+2].end-t[o1+2].start,jsontr + t[o1+2].start); while(nt[i+1]!=0){ if(t[nt[i+1]].parent==o1){ printf("\t[%.*s]\t%.*s\n",t[nt[i+1]].end-t[nt[i+1]].start,jsontr + t[nt[i+1]].start,t[nt[i+1]+1].end-t[nt[i+1]+1].start,jsontr + t[nt[i+1]+1].start); } i++; } //} } //checking int main() { int i; int r; int *k; jsmn_parser p; char name[20]; jsmntok_t t[128]; /* We expect no more than 128 tokens */ int *objectList = (int *)malloc(sizeof(int)); int nameTokIndex[200]={0}; int nt[20]={0}; //while(1){ printf("원하는 파일명 입력: "); scanf("%s",name); char *JSON_STRING=readJSONFILE(name); jsmn_init(&p); r = jsmn_parse(&p, JSON_STRING, strlen(JSON_STRING), t, sizeof(t)/sizeof(t[0])); // printf("%d\n",t[t[2].parent].parent); // printf("%d\n",t[20].parent); jsonNameList(JSON_STRING,t,r,nameTokIndex); printNameList(JSON_STRING,t,nameTokIndex,nt); //selectNameList(JSON_STRING,t,nameTokIndex); ObjectNameList(JSON_STRING,t,nameTokIndex,objectList); printSelectObjectNameList(JSON_STRING,t,objectList,nameTokIndex,nt); //} //printf("%d",strlen(nameTokIndex)); // if (r < 0) { // printf("Failed to parse JSON: %d\n", r); // return 1; // } // // /* Assume the top-level element is an object */ // if (r < 1 || t[0].type != JSMN_OBJECT) { // printf("Object expected\n"); // return 1; // } // // /* Loop over all keys of the root object */ // for (i = 1; i < r; i++) { // if (jsoneq(JSON_STRING, &t[i], "name") == 0) { // /* We may use strndup() to fetch string value */ // printf("- name: %.*s\n", t[i+1].end-t[i+1].start, // JSON_STRING + t[i+1].start); // i++; // } else if (jsoneq(JSON_STRING, &t[i], "keywords") == 0) { // /* We may additionally check if the value is either "true" or "false" */ // printf("- keywords: %.*s\n", t[i+1].end-t[i+1].start, // JSON_STRING + t[i+1].start); // i++; // } else if (jsoneq(JSON_STRING, &t[i], "description") == 0) { // /* We may want to do strtol() here to get numeric value */ // printf("- UID: %.*s\n", t[i+1].end-t[i+1].start, // JSON_STRING + t[i+1].start); // i++; // } else if (jsoneq(JSON_STRING, &t[i], "examples") == 0) { // /* We may want to do strtol() here to get numeric value */ // printf("examples:\n"); // int j; // if (t[i+1].type != JSMN_ARRAY) { // continue; /* We expect groups to be an array of strings */ // } // for (j = 0; j < t[i+1].size; j++) { // jsmntok_t *g = &t[i+j+2]; // printf(" * %.*s\n", g->end - g->start, JSON_STRING + g->start); // } // i += t[i+1].size + 1; // // } // /*} else if (jsoneq(JSON_STRING, &t[i], "examples") == 0) { // int j; // printf("- Groups:\n"); // if (t[i+1].type != JSMN_ARRAY) { // continue; /* We expect groups to be an array of strings */ // /* } // for (j = 0; j < t[i+1].size; j++) { // jsmntok_t *g = &t[i+j+2]; // printf(" * %.*s\n", g->end - g->start, JSON_STRING + g->start); // } // i += t[i+1].size + 1; // } else { // printf("Unexpected key: %.*s\n", t[i].end-t[i].start, // JSON_STRING + t[i].start); // }*/ // } free(objectList); return EXIT_SUCCESS; }
66107.c
#include "py/mphal.h" void NUCLEO_H743ZI_board_early_init(void) { // Turn off the USB switch #define USB_PowerSwitchOn pin_G6 mp_hal_pin_output(USB_PowerSwitchOn); mp_hal_pin_low(USB_PowerSwitchOn); }
296978.c
/*KENDALLTAU Internal code for homogeneous region detection ** Please refer to file kendalltau.m ** License ** ------- ** This work is protected by the CeCILL-C Licence, see ** - Licence_CeCILL_V2.1-en.txt ** - Licence_CeCILL_V2.1-fr.txt ** ** Copyright 2015 Charles Deledalle */ /*#ifdef MATLAB_MEX_FILE*/ # include <mex.h> /*#endif*/ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include <time.h> #if defined(_WIN32) || defined(_WIN64) /* For Microsoft Windows SKD C++ compiler */ #define isnan mxIsNaN #define NAN (mxGetNaN()) //double roundf(double number) //{ // return (number >= 0) ? (int)(number + 0.5) : (int)(number - 0.5); //} #endif /* Lookup table for "1-2*abs(normcdf(linspace(0, 5, 4096), 0, 1) - 0.5)" */ const int normpvalues_2sided_size = 4096; const double normpvalues_2sided_max = 5; const double normpvalues_2sided[] = { 1.000000, 0.999026, 0.998052, 0.997077, 0.996103, 0.995129, 0.994155, 0.993181, 0.992206, 0.991232, 0.990258, 0.989284, 0.988310, 0.987336, 0.986362, 0.985388, 0.984414, 0.983439, 0.982465, 0.981492, 0.980518, 0.979544, 0.978570, 0.977596, 0.976622, 0.975648, 0.974675, 0.973701, 0.972727, 0.971754, 0.970780, 0.969806, 0.968833, 0.967860, 0.966886, 0.965913, 0.964939, 0.963966, 0.962993, 0.962020, 0.961047, 0.960074, 0.959101, 0.958128, 0.957155, 0.956182, 0.955210, 0.954237, 0.953264, 0.952292, 0.951319, 0.950347, 0.949375, 0.948402, 0.947430, 0.946458, 0.945486, 0.944514, 0.943543, 0.942571, 0.941599, 0.940628, 0.939656, 0.938685, 0.937713, 0.936742, 0.935771, 0.934800, 0.933829, 0.932858, 0.931888, 0.930917, 0.929947, 0.928976, 0.928006, 0.927036, 0.926066, 0.925096, 0.924126, 0.923156, 0.922186, 0.921217, 0.920247, 0.919278, 0.918309, 0.917340, 0.916371, 0.915402, 0.914433, 0.913465, 0.912497, 0.911528, 0.910560, 0.909592, 0.908624, 0.907656, 0.906689, 0.905721, 0.904754, 0.903787, 0.902820, 0.901853, 0.900886, 0.899919, 0.898953, 0.897987, 0.897020, 0.896054, 0.895089, 0.894123, 0.893157, 0.892192, 0.891227, 0.890262, 0.889297, 0.888332, 0.887367, 0.886403, 0.885439, 0.884475, 0.883511, 0.882547, 0.881584, 0.880620, 0.879657, 0.878694, 0.877731, 0.876768, 0.875806, 0.874844, 0.873881, 0.872920, 0.871958, 0.870996, 0.870035, 0.869074, 0.868113, 0.867152, 0.866191, 0.865231, 0.864271, 0.863311, 0.862351, 0.861391, 0.860432, 0.859473, 0.858514, 0.857555, 0.856597, 0.855638, 0.854680, 0.853722, 0.852765, 0.851807, 0.850850, 0.849893, 0.848936, 0.847979, 0.847023, 0.846067, 0.845111, 0.844155, 0.843200, 0.842245, 0.841290, 0.840335, 0.839380, 0.838426, 0.837472, 0.836518, 0.835565, 0.834611, 0.833658, 0.832705, 0.831753, 0.830800, 0.829848, 0.828896, 0.827945, 0.826993, 0.826042, 0.825091, 0.824141, 0.823191, 0.822240, 0.821291, 0.820341, 0.819392, 0.818443, 0.817494, 0.816546, 0.815597, 0.814649, 0.813702, 0.812754, 0.811807, 0.810860, 0.809914, 0.808967, 0.808021, 0.807076, 0.806130, 0.805185, 0.804240, 0.803296, 0.802351, 0.801407, 0.800464, 0.799520, 0.798577, 0.797634, 0.796692, 0.795749, 0.794807, 0.793866, 0.792924, 0.791983, 0.791042, 0.790102, 0.789162, 0.788222, 0.787282, 0.786343, 0.785404, 0.784466, 0.783527, 0.782589, 0.781652, 0.780714, 0.779777, 0.778841, 0.777904, 0.776968, 0.776032, 0.775097, 0.774162, 0.773227, 0.772293, 0.771359, 0.770425, 0.769491, 0.768558, 0.767625, 0.766693, 0.765761, 0.764829, 0.763898, 0.762967, 0.762036, 0.761106, 0.760176, 0.759246, 0.758316, 0.757387, 0.756459, 0.755531, 0.754603, 0.753675, 0.752748, 0.751821, 0.750894, 0.749968, 0.749042, 0.748117, 0.747192, 0.746267, 0.745343, 0.744419, 0.743495, 0.742572, 0.741649, 0.740727, 0.739804, 0.738883, 0.737961, 0.737040, 0.736120, 0.735199, 0.734280, 0.733360, 0.732441, 0.731522, 0.730604, 0.729686, 0.728768, 0.727851, 0.726934, 0.726018, 0.725102, 0.724186, 0.723271, 0.722356, 0.721442, 0.720528, 0.719614, 0.718701, 0.717788, 0.716876, 0.715964, 0.715052, 0.714141, 0.713230, 0.712320, 0.711410, 0.710500, 0.709591, 0.708682, 0.707774, 0.706866, 0.705959, 0.705051, 0.704145, 0.703239, 0.702333, 0.701427, 0.700522, 0.699618, 0.698714, 0.697810, 0.696907, 0.696004, 0.695102, 0.694200, 0.693298, 0.692397, 0.691496, 0.690596, 0.689696, 0.688797, 0.687898, 0.686999, 0.686101, 0.685204, 0.684307, 0.683410, 0.682514, 0.681618, 0.680723, 0.679828, 0.678933, 0.678039, 0.677146, 0.676252, 0.675360, 0.674468, 0.673576, 0.672685, 0.671794, 0.670903, 0.670014, 0.669124, 0.668235, 0.667347, 0.666459, 0.665571, 0.664684, 0.663797, 0.662911, 0.662025, 0.661140, 0.660255, 0.659371, 0.658487, 0.657604, 0.656721, 0.655839, 0.654957, 0.654076, 0.653195, 0.652314, 0.651434, 0.650555, 0.649676, 0.648797, 0.647919, 0.647042, 0.646165, 0.645288, 0.644412, 0.643537, 0.642662, 0.641787, 0.640913, 0.640040, 0.639167, 0.638294, 0.637422, 0.636550, 0.635679, 0.634809, 0.633939, 0.633069, 0.632200, 0.631332, 0.630464, 0.629596, 0.628729, 0.627863, 0.626997, 0.626131, 0.625266, 0.624402, 0.623538, 0.622674, 0.621812, 0.620949, 0.620087, 0.619226, 0.618365, 0.617505, 0.616645, 0.615786, 0.614927, 0.614069, 0.613212, 0.612354, 0.611498, 0.610642, 0.609786, 0.608931, 0.608077, 0.607223, 0.606370, 0.605517, 0.604664, 0.603813, 0.602961, 0.602111, 0.601261, 0.600411, 0.599562, 0.598713, 0.597865, 0.597018, 0.596171, 0.595325, 0.594479, 0.593634, 0.592789, 0.591945, 0.591101, 0.590258, 0.589416, 0.588574, 0.587733, 0.586892, 0.586052, 0.585212, 0.584373, 0.583534, 0.582696, 0.581859, 0.581022, 0.580186, 0.579350, 0.578515, 0.577680, 0.576846, 0.576013, 0.575180, 0.574347, 0.573516, 0.572684, 0.571854, 0.571024, 0.570194, 0.569365, 0.568537, 0.567709, 0.566882, 0.566055, 0.565229, 0.564404, 0.563579, 0.562755, 0.561931, 0.561108, 0.560285, 0.559463, 0.558642, 0.557821, 0.557001, 0.556182, 0.555363, 0.554544, 0.553726, 0.552909, 0.552092, 0.551276, 0.550461, 0.549646, 0.548832, 0.548018, 0.547205, 0.546393, 0.545581, 0.544769, 0.543959, 0.543149, 0.542339, 0.541530, 0.540722, 0.539914, 0.539107, 0.538301, 0.537495, 0.536690, 0.535885, 0.535081, 0.534278, 0.533475, 0.532672, 0.531871, 0.531070, 0.530270, 0.529470, 0.528671, 0.527872, 0.527074, 0.526277, 0.525480, 0.524684, 0.523889, 0.523094, 0.522300, 0.521506, 0.520713, 0.519921, 0.519129, 0.518338, 0.517547, 0.516758, 0.515968, 0.515180, 0.514392, 0.513604, 0.512818, 0.512032, 0.511246, 0.510461, 0.509677, 0.508893, 0.508111, 0.507328, 0.506547, 0.505765, 0.504985, 0.504205, 0.503426, 0.502648, 0.501870, 0.501093, 0.500316, 0.499540, 0.498765, 0.497990, 0.497216, 0.496443, 0.495670, 0.494898, 0.494126, 0.493355, 0.492585, 0.491816, 0.491047, 0.490279, 0.489511, 0.488744, 0.487978, 0.487212, 0.486447, 0.485683, 0.484919, 0.484156, 0.483394, 0.482632, 0.481871, 0.481110, 0.480351, 0.479592, 0.478833, 0.478075, 0.477318, 0.476562, 0.475806, 0.475051, 0.474296, 0.473542, 0.472789, 0.472036, 0.471284, 0.470533, 0.469783, 0.469033, 0.468284, 0.467535, 0.466787, 0.466040, 0.465293, 0.464547, 0.463802, 0.463057, 0.462313, 0.461570, 0.460828, 0.460086, 0.459344, 0.458604, 0.457864, 0.457125, 0.456386, 0.455648, 0.454911, 0.454174, 0.453439, 0.452703, 0.451969, 0.451235, 0.450502, 0.449769, 0.449037, 0.448306, 0.447576, 0.446846, 0.446117, 0.445388, 0.444661, 0.443934, 0.443207, 0.442481, 0.441756, 0.441032, 0.440308, 0.439585, 0.438863, 0.438141, 0.437420, 0.436700, 0.435980, 0.435262, 0.434543, 0.433826, 0.433109, 0.432393, 0.431677, 0.430962, 0.430248, 0.429535, 0.428822, 0.428110, 0.427399, 0.426688, 0.425978, 0.425269, 0.424560, 0.423852, 0.423145, 0.422439, 0.421733, 0.421028, 0.420323, 0.419619, 0.418916, 0.418214, 0.417512, 0.416811, 0.416111, 0.415411, 0.414712, 0.414014, 0.413317, 0.412620, 0.411924, 0.411228, 0.410534, 0.409840, 0.409146, 0.408454, 0.407762, 0.407071, 0.406380, 0.405690, 0.405001, 0.404313, 0.403625, 0.402938, 0.402252, 0.401566, 0.400881, 0.400197, 0.399513, 0.398830, 0.398148, 0.397467, 0.396786, 0.396106, 0.395427, 0.394748, 0.394070, 0.393393, 0.392717, 0.392041, 0.391366, 0.390692, 0.390018, 0.389345, 0.388673, 0.388001, 0.387330, 0.386660, 0.385991, 0.385322, 0.384654, 0.383987, 0.383320, 0.382654, 0.381989, 0.381325, 0.380661, 0.379998, 0.379336, 0.378674, 0.378013, 0.377353, 0.376694, 0.376035, 0.375377, 0.374719, 0.374063, 0.373407, 0.372752, 0.372097, 0.371443, 0.370790, 0.370138, 0.369486, 0.368835, 0.368185, 0.367536, 0.366887, 0.366239, 0.365592, 0.364945, 0.364299, 0.363654, 0.363009, 0.362366, 0.361722, 0.361080, 0.360438, 0.359798, 0.359157, 0.358518, 0.357879, 0.357241, 0.356604, 0.355967, 0.355331, 0.354696, 0.354062, 0.353428, 0.352795, 0.352163, 0.351531, 0.350900, 0.350270, 0.349640, 0.349012, 0.348384, 0.347756, 0.347130, 0.346504, 0.345879, 0.345255, 0.344631, 0.344008, 0.343386, 0.342764, 0.342143, 0.341523, 0.340904, 0.340285, 0.339667, 0.339050, 0.338434, 0.337818, 0.337203, 0.336588, 0.335975, 0.335362, 0.334750, 0.334138, 0.333528, 0.332918, 0.332308, 0.331700, 0.331092, 0.330485, 0.329878, 0.329273, 0.328668, 0.328063, 0.327460, 0.326857, 0.326255, 0.325654, 0.325053, 0.324453, 0.323854, 0.323256, 0.322658, 0.322061, 0.321464, 0.320869, 0.320274, 0.319680, 0.319086, 0.318494, 0.317902, 0.317311, 0.316720, 0.316130, 0.315541, 0.314953, 0.314365, 0.313778, 0.313192, 0.312606, 0.312022, 0.311438, 0.310854, 0.310272, 0.309690, 0.309109, 0.308528, 0.307949, 0.307370, 0.306791, 0.306214, 0.305637, 0.305061, 0.304485, 0.303911, 0.303337, 0.302764, 0.302191, 0.301619, 0.301048, 0.300478, 0.299908, 0.299339, 0.298771, 0.298204, 0.297637, 0.297071, 0.296506, 0.295941, 0.295377, 0.294814, 0.294252, 0.293690, 0.293129, 0.292569, 0.292009, 0.291450, 0.290892, 0.290335, 0.289778, 0.289222, 0.288667, 0.288113, 0.287559, 0.287006, 0.286453, 0.285902, 0.285351, 0.284801, 0.284251, 0.283702, 0.283154, 0.282607, 0.282061, 0.281515, 0.280969, 0.280425, 0.279881, 0.279338, 0.278796, 0.278254, 0.277714, 0.277173, 0.276634, 0.276095, 0.275557, 0.275020, 0.274483, 0.273947, 0.273412, 0.272878, 0.272344, 0.271811, 0.271279, 0.270747, 0.270217, 0.269686, 0.269157, 0.268628, 0.268100, 0.267573, 0.267046, 0.266521, 0.265995, 0.265471, 0.264947, 0.264424, 0.263902, 0.263380, 0.262859, 0.262339, 0.261820, 0.261301, 0.260783, 0.260266, 0.259749, 0.259233, 0.258718, 0.258204, 0.257690, 0.257177, 0.256664, 0.256153, 0.255642, 0.255132, 0.254622, 0.254113, 0.253605, 0.253098, 0.252591, 0.252085, 0.251580, 0.251075, 0.250572, 0.250068, 0.249566, 0.249064, 0.248563, 0.248063, 0.247563, 0.247064, 0.246566, 0.246069, 0.245572, 0.245076, 0.244580, 0.244086, 0.243592, 0.243098, 0.242606, 0.242114, 0.241623, 0.241132, 0.240643, 0.240154, 0.239665, 0.239177, 0.238691, 0.238204, 0.237719, 0.237234, 0.236750, 0.236266, 0.235783, 0.235301, 0.234820, 0.234339, 0.233859, 0.233380, 0.232901, 0.232424, 0.231946, 0.231470, 0.230994, 0.230519, 0.230045, 0.229571, 0.229098, 0.228625, 0.228154, 0.227683, 0.227213, 0.226743, 0.226274, 0.225806, 0.225339, 0.224872, 0.224406, 0.223940, 0.223476, 0.223012, 0.222548, 0.222086, 0.221624, 0.221162, 0.220702, 0.220242, 0.219783, 0.219324, 0.218866, 0.218409, 0.217953, 0.217497, 0.217042, 0.216587, 0.216134, 0.215681, 0.215228, 0.214777, 0.214326, 0.213875, 0.213426, 0.212977, 0.212529, 0.212081, 0.211634, 0.211188, 0.210743, 0.210298, 0.209854, 0.209410, 0.208967, 0.208525, 0.208084, 0.207643, 0.207203, 0.206763, 0.206325, 0.205887, 0.205449, 0.205013, 0.204577, 0.204141, 0.203706, 0.203272, 0.202839, 0.202406, 0.201975, 0.201543, 0.201113, 0.200683, 0.200253, 0.199825, 0.199397, 0.198969, 0.198543, 0.198117, 0.197692, 0.197267, 0.196843, 0.196420, 0.195997, 0.195575, 0.195154, 0.194733, 0.194313, 0.193894, 0.193475, 0.193058, 0.192640, 0.192224, 0.191808, 0.191392, 0.190978, 0.190564, 0.190150, 0.189738, 0.189326, 0.188914, 0.188504, 0.188094, 0.187684, 0.187276, 0.186868, 0.186460, 0.186054, 0.185647, 0.185242, 0.184837, 0.184433, 0.184030, 0.183627, 0.183225, 0.182823, 0.182422, 0.182022, 0.181623, 0.181224, 0.180826, 0.180428, 0.180031, 0.179635, 0.179239, 0.178844, 0.178450, 0.178056, 0.177663, 0.177271, 0.176879, 0.176488, 0.176097, 0.175708, 0.175318, 0.174930, 0.174542, 0.174155, 0.173768, 0.173382, 0.172997, 0.172612, 0.172228, 0.171845, 0.171462, 0.171080, 0.170698, 0.170317, 0.169937, 0.169558, 0.169179, 0.168800, 0.168423, 0.168046, 0.167669, 0.167294, 0.166918, 0.166544, 0.166170, 0.165797, 0.165424, 0.165052, 0.164681, 0.164310, 0.163940, 0.163571, 0.163202, 0.162834, 0.162466, 0.162099, 0.161733, 0.161367, 0.161002, 0.160638, 0.160274, 0.159911, 0.159548, 0.159186, 0.158825, 0.158464, 0.158104, 0.157744, 0.157386, 0.157027, 0.156670, 0.156313, 0.155956, 0.155601, 0.155245, 0.154891, 0.154537, 0.154184, 0.153831, 0.153479, 0.153127, 0.152777, 0.152426, 0.152077, 0.151728, 0.151379, 0.151032, 0.150684, 0.150338, 0.149992, 0.149646, 0.149302, 0.148958, 0.148614, 0.148271, 0.147929, 0.147587, 0.147246, 0.146905, 0.146565, 0.146226, 0.145887, 0.145549, 0.145212, 0.144875, 0.144539, 0.144203, 0.143868, 0.143533, 0.143199, 0.142866, 0.142533, 0.142201, 0.141870, 0.141539, 0.141208, 0.140878, 0.140549, 0.140221, 0.139893, 0.139565, 0.139239, 0.138912, 0.138587, 0.138262, 0.137937, 0.137613, 0.137290, 0.136967, 0.136645, 0.136324, 0.136003, 0.135683, 0.135363, 0.135044, 0.134725, 0.134407, 0.134089, 0.133773, 0.133456, 0.133141, 0.132826, 0.132511, 0.132197, 0.131884, 0.131571, 0.131259, 0.130947, 0.130636, 0.130325, 0.130015, 0.129706, 0.129397, 0.129089, 0.128781, 0.128474, 0.128168, 0.127862, 0.127556, 0.127251, 0.126947, 0.126644, 0.126340, 0.126038, 0.125736, 0.125434, 0.125134, 0.124833, 0.124534, 0.124234, 0.123936, 0.123638, 0.123340, 0.123043, 0.122747, 0.122451, 0.122156, 0.121861, 0.121567, 0.121273, 0.120980, 0.120688, 0.120396, 0.120105, 0.119814, 0.119524, 0.119234, 0.118945, 0.118656, 0.118368, 0.118080, 0.117793, 0.117507, 0.117221, 0.116936, 0.116651, 0.116367, 0.116083, 0.115800, 0.115517, 0.115235, 0.114954, 0.114673, 0.114392, 0.114112, 0.113833, 0.113554, 0.113276, 0.112998, 0.112721, 0.112444, 0.112168, 0.111893, 0.111618, 0.111343, 0.111069, 0.110796, 0.110523, 0.110250, 0.109978, 0.109707, 0.109436, 0.109166, 0.108896, 0.108627, 0.108358, 0.108090, 0.107822, 0.107555, 0.107289, 0.107023, 0.106757, 0.106492, 0.106227, 0.105963, 0.105700, 0.105437, 0.105175, 0.104913, 0.104651, 0.104390, 0.104130, 0.103870, 0.103611, 0.103352, 0.103094, 0.102836, 0.102579, 0.102322, 0.102066, 0.101810, 0.101555, 0.101300, 0.101046, 0.100792, 0.100539, 0.100286, 0.100034, 0.099782, 0.099531, 0.099281, 0.099030, 0.098781, 0.098532, 0.098283, 0.098035, 0.097787, 0.097540, 0.097293, 0.097047, 0.096802, 0.096556, 0.096312, 0.096068, 0.095824, 0.095581, 0.095338, 0.095096, 0.094854, 0.094613, 0.094372, 0.094132, 0.093892, 0.093653, 0.093414, 0.093176, 0.092938, 0.092701, 0.092464, 0.092228, 0.091992, 0.091757, 0.091522, 0.091288, 0.091054, 0.090820, 0.090587, 0.090355, 0.090123, 0.089891, 0.089660, 0.089430, 0.089200, 0.088970, 0.088741, 0.088513, 0.088284, 0.088057, 0.087830, 0.087603, 0.087377, 0.087151, 0.086925, 0.086701, 0.086476, 0.086252, 0.086029, 0.085806, 0.085583, 0.085361, 0.085140, 0.084919, 0.084698, 0.084478, 0.084258, 0.084039, 0.083820, 0.083602, 0.083384, 0.083167, 0.082950, 0.082733, 0.082517, 0.082302, 0.082087, 0.081872, 0.081658, 0.081444, 0.081231, 0.081018, 0.080805, 0.080594, 0.080382, 0.080171, 0.079960, 0.079750, 0.079541, 0.079331, 0.079123, 0.078914, 0.078706, 0.078499, 0.078292, 0.078085, 0.077879, 0.077674, 0.077468, 0.077264, 0.077059, 0.076855, 0.076652, 0.076449, 0.076246, 0.076044, 0.075842, 0.075641, 0.075440, 0.075240, 0.075040, 0.074840, 0.074641, 0.074443, 0.074244, 0.074047, 0.073849, 0.073652, 0.073456, 0.073260, 0.073064, 0.072869, 0.072674, 0.072480, 0.072286, 0.072092, 0.071899, 0.071707, 0.071514, 0.071322, 0.071131, 0.070940, 0.070750, 0.070559, 0.070370, 0.070180, 0.069991, 0.069803, 0.069615, 0.069427, 0.069240, 0.069053, 0.068867, 0.068681, 0.068495, 0.068310, 0.068125, 0.067941, 0.067757, 0.067574, 0.067391, 0.067208, 0.067026, 0.066844, 0.066662, 0.066481, 0.066301, 0.066120, 0.065941, 0.065761, 0.065582, 0.065403, 0.065225, 0.065047, 0.064870, 0.064693, 0.064516, 0.064340, 0.064164, 0.063989, 0.063814, 0.063639, 0.063465, 0.063291, 0.063117, 0.062944, 0.062772, 0.062599, 0.062427, 0.062256, 0.062085, 0.061914, 0.061744, 0.061574, 0.061404, 0.061235, 0.061066, 0.060898, 0.060730, 0.060562, 0.060395, 0.060228, 0.060061, 0.059895, 0.059730, 0.059564, 0.059399, 0.059235, 0.059071, 0.058907, 0.058743, 0.058580, 0.058417, 0.058255, 0.058093, 0.057932, 0.057770, 0.057610, 0.057449, 0.057289, 0.057129, 0.056970, 0.056811, 0.056652, 0.056494, 0.056336, 0.056179, 0.056022, 0.055865, 0.055709, 0.055552, 0.055397, 0.055241, 0.055087, 0.054932, 0.054778, 0.054624, 0.054470, 0.054317, 0.054164, 0.054012, 0.053860, 0.053708, 0.053557, 0.053406, 0.053255, 0.053105, 0.052955, 0.052806, 0.052656, 0.052507, 0.052359, 0.052211, 0.052063, 0.051915, 0.051768, 0.051622, 0.051475, 0.051329, 0.051183, 0.051038, 0.050893, 0.050748, 0.050604, 0.050460, 0.050316, 0.050173, 0.050030, 0.049887, 0.049745, 0.049603, 0.049462, 0.049320, 0.049179, 0.049039, 0.048899, 0.048759, 0.048619, 0.048480, 0.048341, 0.048202, 0.048064, 0.047926, 0.047789, 0.047651, 0.047515, 0.047378, 0.047242, 0.047106, 0.046970, 0.046835, 0.046700, 0.046565, 0.046431, 0.046297, 0.046164, 0.046030, 0.045897, 0.045765, 0.045632, 0.045500, 0.045369, 0.045237, 0.045106, 0.044975, 0.044845, 0.044715, 0.044585, 0.044456, 0.044327, 0.044198, 0.044069, 0.043941, 0.043813, 0.043686, 0.043558, 0.043432, 0.043305, 0.043179, 0.043053, 0.042927, 0.042802, 0.042677, 0.042552, 0.042427, 0.042303, 0.042179, 0.042056, 0.041933, 0.041810, 0.041687, 0.041565, 0.041443, 0.041321, 0.041200, 0.041079, 0.040958, 0.040837, 0.040717, 0.040597, 0.040478, 0.040358, 0.040239, 0.040121, 0.040002, 0.039884, 0.039767, 0.039649, 0.039532, 0.039415, 0.039298, 0.039182, 0.039066, 0.038950, 0.038835, 0.038720, 0.038605, 0.038490, 0.038376, 0.038262, 0.038148, 0.038035, 0.037922, 0.037809, 0.037696, 0.037584, 0.037472, 0.037360, 0.037249, 0.037138, 0.037027, 0.036916, 0.036806, 0.036696, 0.036586, 0.036477, 0.036367, 0.036258, 0.036150, 0.036041, 0.035933, 0.035826, 0.035718, 0.035611, 0.035504, 0.035397, 0.035291, 0.035185, 0.035079, 0.034973, 0.034868, 0.034763, 0.034658, 0.034553, 0.034449, 0.034345, 0.034242, 0.034138, 0.034035, 0.033932, 0.033829, 0.033727, 0.033625, 0.033523, 0.033421, 0.033320, 0.033219, 0.033118, 0.033018, 0.032917, 0.032817, 0.032718, 0.032618, 0.032519, 0.032420, 0.032321, 0.032223, 0.032125, 0.032027, 0.031929, 0.031832, 0.031734, 0.031637, 0.031541, 0.031444, 0.031348, 0.031252, 0.031157, 0.031061, 0.030966, 0.030871, 0.030776, 0.030682, 0.030588, 0.030494, 0.030400, 0.030307, 0.030214, 0.030121, 0.030028, 0.029936, 0.029844, 0.029752, 0.029660, 0.029568, 0.029477, 0.029386, 0.029295, 0.029205, 0.029115, 0.029025, 0.028935, 0.028845, 0.028756, 0.028667, 0.028578, 0.028490, 0.028401, 0.028313, 0.028225, 0.028138, 0.028050, 0.027963, 0.027876, 0.027790, 0.027703, 0.027617, 0.027531, 0.027445, 0.027360, 0.027274, 0.027189, 0.027104, 0.027020, 0.026935, 0.026851, 0.026767, 0.026683, 0.026600, 0.026517, 0.026434, 0.026351, 0.026268, 0.026186, 0.026104, 0.026022, 0.025940, 0.025859, 0.025777, 0.025696, 0.025616, 0.025535, 0.025455, 0.025374, 0.025295, 0.025215, 0.025135, 0.025056, 0.024977, 0.024898, 0.024820, 0.024741, 0.024663, 0.024585, 0.024507, 0.024430, 0.024352, 0.024275, 0.024198, 0.024121, 0.024045, 0.023969, 0.023893, 0.023817, 0.023741, 0.023666, 0.023590, 0.023515, 0.023440, 0.023366, 0.023291, 0.023217, 0.023143, 0.023069, 0.022996, 0.022922, 0.022849, 0.022776, 0.022703, 0.022631, 0.022558, 0.022486, 0.022414, 0.022343, 0.022271, 0.022200, 0.022128, 0.022057, 0.021987, 0.021916, 0.021846, 0.021775, 0.021705, 0.021636, 0.021566, 0.021497, 0.021427, 0.021358, 0.021290, 0.021221, 0.021153, 0.021084, 0.021016, 0.020948, 0.020881, 0.020813, 0.020746, 0.020679, 0.020612, 0.020545, 0.020479, 0.020412, 0.020346, 0.020280, 0.020214, 0.020149, 0.020083, 0.020018, 0.019953, 0.019888, 0.019824, 0.019759, 0.019695, 0.019631, 0.019567, 0.019503, 0.019439, 0.019376, 0.019313, 0.019250, 0.019187, 0.019124, 0.019062, 0.018999, 0.018937, 0.018875, 0.018813, 0.018752, 0.018690, 0.018629, 0.018568, 0.018507, 0.018446, 0.018386, 0.018326, 0.018265, 0.018205, 0.018145, 0.018086, 0.018026, 0.017967, 0.017908, 0.017849, 0.017790, 0.017731, 0.017673, 0.017614, 0.017556, 0.017498, 0.017440, 0.017383, 0.017325, 0.017268, 0.017211, 0.017154, 0.017097, 0.017040, 0.016984, 0.016928, 0.016871, 0.016815, 0.016760, 0.016704, 0.016648, 0.016593, 0.016538, 0.016483, 0.016428, 0.016373, 0.016319, 0.016264, 0.016210, 0.016156, 0.016102, 0.016048, 0.015995, 0.015941, 0.015888, 0.015835, 0.015782, 0.015729, 0.015676, 0.015624, 0.015572, 0.015519, 0.015467, 0.015416, 0.015364, 0.015312, 0.015261, 0.015210, 0.015158, 0.015107, 0.015057, 0.015006, 0.014955, 0.014905, 0.014855, 0.014805, 0.014755, 0.014705, 0.014656, 0.014606, 0.014557, 0.014508, 0.014459, 0.014410, 0.014361, 0.014312, 0.014264, 0.014216, 0.014167, 0.014119, 0.014071, 0.014024, 0.013976, 0.013929, 0.013881, 0.013834, 0.013787, 0.013740, 0.013694, 0.013647, 0.013601, 0.013554, 0.013508, 0.013462, 0.013416, 0.013370, 0.013325, 0.013279, 0.013234, 0.013189, 0.013144, 0.013099, 0.013054, 0.013009, 0.012965, 0.012920, 0.012876, 0.012832, 0.012788, 0.012744, 0.012700, 0.012657, 0.012613, 0.012570, 0.012527, 0.012484, 0.012441, 0.012398, 0.012355, 0.012313, 0.012270, 0.012228, 0.012186, 0.012144, 0.012102, 0.012060, 0.012019, 0.011977, 0.011936, 0.011894, 0.011853, 0.011812, 0.011771, 0.011731, 0.011690, 0.011649, 0.011609, 0.011569, 0.011529, 0.011489, 0.011449, 0.011409, 0.011369, 0.011330, 0.011290, 0.011251, 0.011212, 0.011173, 0.011134, 0.011095, 0.011057, 0.011018, 0.010980, 0.010941, 0.010903, 0.010865, 0.010827, 0.010789, 0.010752, 0.010714, 0.010676, 0.010639, 0.010602, 0.010565, 0.010528, 0.010491, 0.010454, 0.010417, 0.010381, 0.010344, 0.010308, 0.010272, 0.010236, 0.010200, 0.010164, 0.010128, 0.010092, 0.010057, 0.010021, 0.009986, 0.009951, 0.009916, 0.009881, 0.009846, 0.009811, 0.009776, 0.009742, 0.009707, 0.009673, 0.009639, 0.009605, 0.009571, 0.009537, 0.009503, 0.009469, 0.009436, 0.009402, 0.009369, 0.009336, 0.009302, 0.009269, 0.009236, 0.009204, 0.009171, 0.009138, 0.009106, 0.009073, 0.009041, 0.009009, 0.008977, 0.008945, 0.008913, 0.008881, 0.008849, 0.008818, 0.008786, 0.008755, 0.008723, 0.008692, 0.008661, 0.008630, 0.008599, 0.008568, 0.008538, 0.008507, 0.008476, 0.008446, 0.008416, 0.008385, 0.008355, 0.008325, 0.008295, 0.008266, 0.008236, 0.008206, 0.008177, 0.008147, 0.008118, 0.008089, 0.008059, 0.008030, 0.008001, 0.007972, 0.007944, 0.007915, 0.007886, 0.007858, 0.007829, 0.007801, 0.007773, 0.007745, 0.007717, 0.007689, 0.007661, 0.007633, 0.007605, 0.007578, 0.007550, 0.007523, 0.007495, 0.007468, 0.007441, 0.007414, 0.007387, 0.007360, 0.007333, 0.007307, 0.007280, 0.007253, 0.007227, 0.007201, 0.007174, 0.007148, 0.007122, 0.007096, 0.007070, 0.007044, 0.007018, 0.006993, 0.006967, 0.006942, 0.006916, 0.006891, 0.006866, 0.006840, 0.006815, 0.006790, 0.006765, 0.006740, 0.006716, 0.006691, 0.006666, 0.006642, 0.006617, 0.006593, 0.006569, 0.006545, 0.006520, 0.006496, 0.006472, 0.006449, 0.006425, 0.006401, 0.006377, 0.006354, 0.006330, 0.006307, 0.006284, 0.006260, 0.006237, 0.006214, 0.006191, 0.006168, 0.006145, 0.006122, 0.006100, 0.006077, 0.006055, 0.006032, 0.006010, 0.005987, 0.005965, 0.005943, 0.005921, 0.005899, 0.005877, 0.005855, 0.005833, 0.005811, 0.005790, 0.005768, 0.005747, 0.005725, 0.005704, 0.005682, 0.005661, 0.005640, 0.005619, 0.005598, 0.005577, 0.005556, 0.005535, 0.005514, 0.005494, 0.005473, 0.005453, 0.005432, 0.005412, 0.005391, 0.005371, 0.005351, 0.005331, 0.005311, 0.005291, 0.005271, 0.005251, 0.005231, 0.005212, 0.005192, 0.005172, 0.005153, 0.005134, 0.005114, 0.005095, 0.005076, 0.005056, 0.005037, 0.005018, 0.004999, 0.004980, 0.004961, 0.004943, 0.004924, 0.004905, 0.004887, 0.004868, 0.004850, 0.004831, 0.004813, 0.004795, 0.004776, 0.004758, 0.004740, 0.004722, 0.004704, 0.004686, 0.004668, 0.004651, 0.004633, 0.004615, 0.004598, 0.004580, 0.004563, 0.004545, 0.004528, 0.004511, 0.004493, 0.004476, 0.004459, 0.004442, 0.004425, 0.004408, 0.004391, 0.004374, 0.004358, 0.004341, 0.004324, 0.004308, 0.004291, 0.004275, 0.004258, 0.004242, 0.004226, 0.004209, 0.004193, 0.004177, 0.004161, 0.004145, 0.004129, 0.004113, 0.004097, 0.004081, 0.004066, 0.004050, 0.004034, 0.004019, 0.004003, 0.003988, 0.003972, 0.003957, 0.003942, 0.003927, 0.003911, 0.003896, 0.003881, 0.003866, 0.003851, 0.003836, 0.003821, 0.003806, 0.003792, 0.003777, 0.003762, 0.003748, 0.003733, 0.003719, 0.003704, 0.003690, 0.003675, 0.003661, 0.003647, 0.003633, 0.003618, 0.003604, 0.003590, 0.003576, 0.003562, 0.003548, 0.003534, 0.003521, 0.003507, 0.003493, 0.003480, 0.003466, 0.003452, 0.003439, 0.003425, 0.003412, 0.003399, 0.003385, 0.003372, 0.003359, 0.003346, 0.003332, 0.003319, 0.003306, 0.003293, 0.003280, 0.003267, 0.003255, 0.003242, 0.003229, 0.003216, 0.003204, 0.003191, 0.003178, 0.003166, 0.003153, 0.003141, 0.003128, 0.003116, 0.003104, 0.003092, 0.003079, 0.003067, 0.003055, 0.003043, 0.003031, 0.003019, 0.003007, 0.002995, 0.002983, 0.002971, 0.002959, 0.002948, 0.002936, 0.002924, 0.002913, 0.002901, 0.002890, 0.002878, 0.002867, 0.002855, 0.002844, 0.002833, 0.002821, 0.002810, 0.002799, 0.002788, 0.002777, 0.002765, 0.002754, 0.002743, 0.002732, 0.002722, 0.002711, 0.002700, 0.002689, 0.002678, 0.002668, 0.002657, 0.002646, 0.002636, 0.002625, 0.002614, 0.002604, 0.002594, 0.002583, 0.002573, 0.002562, 0.002552, 0.002542, 0.002532, 0.002521, 0.002511, 0.002501, 0.002491, 0.002481, 0.002471, 0.002461, 0.002451, 0.002441, 0.002431, 0.002422, 0.002412, 0.002402, 0.002392, 0.002383, 0.002373, 0.002363, 0.002354, 0.002344, 0.002335, 0.002325, 0.002316, 0.002307, 0.002297, 0.002288, 0.002279, 0.002269, 0.002260, 0.002251, 0.002242, 0.002233, 0.002224, 0.002215, 0.002206, 0.002197, 0.002188, 0.002179, 0.002170, 0.002161, 0.002152, 0.002143, 0.002135, 0.002126, 0.002117, 0.002109, 0.002100, 0.002091, 0.002083, 0.002074, 0.002066, 0.002057, 0.002049, 0.002041, 0.002032, 0.002024, 0.002016, 0.002007, 0.001999, 0.001991, 0.001983, 0.001975, 0.001967, 0.001958, 0.001950, 0.001942, 0.001934, 0.001926, 0.001919, 0.001911, 0.001903, 0.001895, 0.001887, 0.001879, 0.001872, 0.001864, 0.001856, 0.001848, 0.001841, 0.001833, 0.001826, 0.001818, 0.001811, 0.001803, 0.001796, 0.001788, 0.001781, 0.001773, 0.001766, 0.001759, 0.001751, 0.001744, 0.001737, 0.001730, 0.001723, 0.001715, 0.001708, 0.001701, 0.001694, 0.001687, 0.001680, 0.001673, 0.001666, 0.001659, 0.001652, 0.001645, 0.001639, 0.001632, 0.001625, 0.001618, 0.001611, 0.001605, 0.001598, 0.001591, 0.001585, 0.001578, 0.001571, 0.001565, 0.001558, 0.001552, 0.001545, 0.001539, 0.001532, 0.001526, 0.001519, 0.001513, 0.001507, 0.001500, 0.001494, 0.001488, 0.001482, 0.001475, 0.001469, 0.001463, 0.001457, 0.001451, 0.001445, 0.001438, 0.001432, 0.001426, 0.001420, 0.001414, 0.001408, 0.001402, 0.001397, 0.001391, 0.001385, 0.001379, 0.001373, 0.001367, 0.001362, 0.001356, 0.001350, 0.001344, 0.001339, 0.001333, 0.001327, 0.001322, 0.001316, 0.001310, 0.001305, 0.001299, 0.001294, 0.001288, 0.001283, 0.001277, 0.001272, 0.001267, 0.001261, 0.001256, 0.001250, 0.001245, 0.001240, 0.001235, 0.001229, 0.001224, 0.001219, 0.001214, 0.001208, 0.001203, 0.001198, 0.001193, 0.001188, 0.001183, 0.001178, 0.001173, 0.001168, 0.001163, 0.001158, 0.001153, 0.001148, 0.001143, 0.001138, 0.001133, 0.001128, 0.001123, 0.001119, 0.001114, 0.001109, 0.001104, 0.001100, 0.001095, 0.001090, 0.001085, 0.001081, 0.001076, 0.001071, 0.001067, 0.001062, 0.001058, 0.001053, 0.001049, 0.001044, 0.001040, 0.001035, 0.001031, 0.001026, 0.001022, 0.001017, 0.001013, 0.001008, 0.001004, 0.001000, 0.000995, 0.000991, 0.000987, 0.000983, 0.000978, 0.000974, 0.000970, 0.000966, 0.000961, 0.000957, 0.000953, 0.000949, 0.000945, 0.000941, 0.000937, 0.000933, 0.000928, 0.000924, 0.000920, 0.000916, 0.000912, 0.000908, 0.000904, 0.000900, 0.000897, 0.000893, 0.000889, 0.000885, 0.000881, 0.000877, 0.000873, 0.000869, 0.000866, 0.000862, 0.000858, 0.000854, 0.000851, 0.000847, 0.000843, 0.000839, 0.000836, 0.000832, 0.000828, 0.000825, 0.000821, 0.000818, 0.000814, 0.000810, 0.000807, 0.000803, 0.000800, 0.000796, 0.000793, 0.000789, 0.000786, 0.000782, 0.000779, 0.000775, 0.000772, 0.000769, 0.000765, 0.000762, 0.000758, 0.000755, 0.000752, 0.000748, 0.000745, 0.000742, 0.000739, 0.000735, 0.000732, 0.000729, 0.000726, 0.000722, 0.000719, 0.000716, 0.000713, 0.000710, 0.000706, 0.000703, 0.000700, 0.000697, 0.000694, 0.000691, 0.000688, 0.000685, 0.000682, 0.000679, 0.000676, 0.000673, 0.000670, 0.000667, 0.000664, 0.000661, 0.000658, 0.000655, 0.000652, 0.000649, 0.000646, 0.000643, 0.000640, 0.000637, 0.000635, 0.000632, 0.000629, 0.000626, 0.000623, 0.000621, 0.000618, 0.000615, 0.000612, 0.000610, 0.000607, 0.000604, 0.000601, 0.000599, 0.000596, 0.000593, 0.000591, 0.000588, 0.000585, 0.000583, 0.000580, 0.000577, 0.000575, 0.000572, 0.000570, 0.000567, 0.000565, 0.000562, 0.000559, 0.000557, 0.000554, 0.000552, 0.000549, 0.000547, 0.000544, 0.000542, 0.000540, 0.000537, 0.000535, 0.000532, 0.000530, 0.000527, 0.000525, 0.000523, 0.000520, 0.000518, 0.000516, 0.000513, 0.000511, 0.000509, 0.000506, 0.000504, 0.000502, 0.000499, 0.000497, 0.000495, 0.000493, 0.000490, 0.000488, 0.000486, 0.000484, 0.000482, 0.000479, 0.000477, 0.000475, 0.000473, 0.000471, 0.000468, 0.000466, 0.000464, 0.000462, 0.000460, 0.000458, 0.000456, 0.000454, 0.000452, 0.000450, 0.000447, 0.000445, 0.000443, 0.000441, 0.000439, 0.000437, 0.000435, 0.000433, 0.000431, 0.000429, 0.000427, 0.000425, 0.000423, 0.000421, 0.000420, 0.000418, 0.000416, 0.000414, 0.000412, 0.000410, 0.000408, 0.000406, 0.000404, 0.000402, 0.000401, 0.000399, 0.000397, 0.000395, 0.000393, 0.000391, 0.000390, 0.000388, 0.000386, 0.000384, 0.000382, 0.000381, 0.000379, 0.000377, 0.000375, 0.000374, 0.000372, 0.000370, 0.000369, 0.000367, 0.000365, 0.000363, 0.000362, 0.000360, 0.000358, 0.000357, 0.000355, 0.000353, 0.000352, 0.000350, 0.000348, 0.000347, 0.000345, 0.000344, 0.000342, 0.000340, 0.000339, 0.000337, 0.000336, 0.000334, 0.000333, 0.000331, 0.000329, 0.000328, 0.000326, 0.000325, 0.000323, 0.000322, 0.000320, 0.000319, 0.000317, 0.000316, 0.000314, 0.000313, 0.000311, 0.000310, 0.000308, 0.000307, 0.000306, 0.000304, 0.000303, 0.000301, 0.000300, 0.000298, 0.000297, 0.000296, 0.000294, 0.000293, 0.000292, 0.000290, 0.000289, 0.000287, 0.000286, 0.000285, 0.000283, 0.000282, 0.000281, 0.000279, 0.000278, 0.000277, 0.000275, 0.000274, 0.000273, 0.000272, 0.000270, 0.000269, 0.000268, 0.000266, 0.000265, 0.000264, 0.000263, 0.000261, 0.000260, 0.000259, 0.000258, 0.000257, 0.000255, 0.000254, 0.000253, 0.000252, 0.000250, 0.000249, 0.000248, 0.000247, 0.000246, 0.000245, 0.000243, 0.000242, 0.000241, 0.000240, 0.000239, 0.000238, 0.000237, 0.000235, 0.000234, 0.000233, 0.000232, 0.000231, 0.000230, 0.000229, 0.000228, 0.000227, 0.000225, 0.000224, 0.000223, 0.000222, 0.000221, 0.000220, 0.000219, 0.000218, 0.000217, 0.000216, 0.000215, 0.000214, 0.000213, 0.000212, 0.000211, 0.000210, 0.000209, 0.000208, 0.000207, 0.000206, 0.000205, 0.000204, 0.000203, 0.000202, 0.000201, 0.000200, 0.000199, 0.000198, 0.000197, 0.000196, 0.000195, 0.000194, 0.000193, 0.000192, 0.000191, 0.000190, 0.000190, 0.000189, 0.000188, 0.000187, 0.000186, 0.000185, 0.000184, 0.000183, 0.000182, 0.000181, 0.000181, 0.000180, 0.000179, 0.000178, 0.000177, 0.000176, 0.000175, 0.000174, 0.000174, 0.000173, 0.000172, 0.000171, 0.000170, 0.000169, 0.000169, 0.000168, 0.000167, 0.000166, 0.000165, 0.000165, 0.000164, 0.000163, 0.000162, 0.000161, 0.000161, 0.000160, 0.000159, 0.000158, 0.000157, 0.000157, 0.000156, 0.000155, 0.000154, 0.000154, 0.000153, 0.000152, 0.000151, 0.000151, 0.000150, 0.000149, 0.000148, 0.000148, 0.000147, 0.000146, 0.000146, 0.000145, 0.000144, 0.000143, 0.000143, 0.000142, 0.000141, 0.000141, 0.000140, 0.000139, 0.000139, 0.000138, 0.000137, 0.000137, 0.000136, 0.000135, 0.000134, 0.000134, 0.000133, 0.000133, 0.000132, 0.000131, 0.000131, 0.000130, 0.000129, 0.000129, 0.000128, 0.000127, 0.000127, 0.000126, 0.000125, 0.000125, 0.000124, 0.000124, 0.000123, 0.000122, 0.000122, 0.000121, 0.000121, 0.000120, 0.000119, 0.000119, 0.000118, 0.000118, 0.000117, 0.000116, 0.000116, 0.000115, 0.000115, 0.000114, 0.000114, 0.000113, 0.000112, 0.000112, 0.000111, 0.000111, 0.000110, 0.000110, 0.000109, 0.000109, 0.000108, 0.000107, 0.000107, 0.000106, 0.000106, 0.000105, 0.000105, 0.000104, 0.000104, 0.000103, 0.000103, 0.000102, 0.000102, 0.000101, 0.000101, 0.000100, 0.000100, 0.000099, 0.000099, 0.000098, 0.000098, 0.000097, 0.000097, 0.000096, 0.000096, 0.000095, 0.000095, 0.000094, 0.000094, 0.000093, 0.000093, 0.000092, 0.000092, 0.000092, 0.000091, 0.000091, 0.000090, 0.000090, 0.000089, 0.000089, 0.000088, 0.000088, 0.000087, 0.000087, 0.000087, 0.000086, 0.000086, 0.000085, 0.000085, 0.000084, 0.000084, 0.000084, 0.000083, 0.000083, 0.000082, 0.000082, 0.000081, 0.000081, 0.000081, 0.000080, 0.000080, 0.000079, 0.000079, 0.000079, 0.000078, 0.000078, 0.000077, 0.000077, 0.000077, 0.000076, 0.000076, 0.000075, 0.000075, 0.000075, 0.000074, 0.000074, 0.000074, 0.000073, 0.000073, 0.000072, 0.000072, 0.000072, 0.000071, 0.000071, 0.000071, 0.000070, 0.000070, 0.000069, 0.000069, 0.000069, 0.000068, 0.000068, 0.000068, 0.000067, 0.000067, 0.000067, 0.000066, 0.000066, 0.000066, 0.000065, 0.000065, 0.000065, 0.000064, 0.000064, 0.000064, 0.000063, 0.000063, 0.000063, 0.000062, 0.000062, 0.000062, 0.000061, 0.000061, 0.000061, 0.000060, 0.000060, 0.000060, 0.000060, 0.000059, 0.000059, 0.000059, 0.000058, 0.000058, 0.000058, 0.000057, 0.000057, 0.000057, 0.000057, 0.000056, 0.000056, 0.000056, 0.000055, 0.000055, 0.000055, 0.000055, 0.000054, 0.000054, 0.000054, 0.000053, 0.000053, 0.000053, 0.000053, 0.000052, 0.000052, 0.000052, 0.000051, 0.000051, 0.000051, 0.000051, 0.000050, 0.000050, 0.000050, 0.000050, 0.000049, 0.000049, 0.000049, 0.000049, 0.000048, 0.000048, 0.000048, 0.000048, 0.000047, 0.000047, 0.000047, 0.000047, 0.000046, 0.000046, 0.000046, 0.000046, 0.000045, 0.000045, 0.000045, 0.000045, 0.000044, 0.000044, 0.000044, 0.000044, 0.000044, 0.000043, 0.000043, 0.000043, 0.000043, 0.000042, 0.000042, 0.000042, 0.000042, 0.000042, 0.000041, 0.000041, 0.000041, 0.000041, 0.000040, 0.000040, 0.000040, 0.000040, 0.000040, 0.000039, 0.000039, 0.000039, 0.000039, 0.000039, 0.000038, 0.000038, 0.000038, 0.000038, 0.000038, 0.000037, 0.000037, 0.000037, 0.000037, 0.000037, 0.000036, 0.000036, 0.000036, 0.000036, 0.000036, 0.000035, 0.000035, 0.000035, 0.000035, 0.000035, 0.000034, 0.000034, 0.000034, 0.000034, 0.000034, 0.000034, 0.000033, 0.000033, 0.000033, 0.000033, 0.000033, 0.000033, 0.000032, 0.000032, 0.000032, 0.000032, 0.000032, 0.000031, 0.000031, 0.000031, 0.000031, 0.000031, 0.000031, 0.000030, 0.000030, 0.000030, 0.000030, 0.000030, 0.000030, 0.000030, 0.000029, 0.000029, 0.000029, 0.000029, 0.000029, 0.000029, 0.000028, 0.000028, 0.000028, 0.000028, 0.000028, 0.000028, 0.000028, 0.000027, 0.000027, 0.000027, 0.000027, 0.000027, 0.000027, 0.000027, 0.000026, 0.000026, 0.000026, 0.000026, 0.000026, 0.000026, 0.000026, 0.000025, 0.000025, 0.000025, 0.000025, 0.000025, 0.000025, 0.000025, 0.000024, 0.000024, 0.000024, 0.000024, 0.000024, 0.000024, 0.000024, 0.000024, 0.000023, 0.000023, 0.000023, 0.000023, 0.000023, 0.000023, 0.000023, 0.000023, 0.000022, 0.000022, 0.000022, 0.000022, 0.000022, 0.000022, 0.000022, 0.000022, 0.000021, 0.000021, 0.000021, 0.000021, 0.000021, 0.000021, 0.000021, 0.000021, 0.000021, 0.000020, 0.000020, 0.000020, 0.000020, 0.000020, 0.000020, 0.000020, 0.000020, 0.000020, 0.000019, 0.000019, 0.000019, 0.000019, 0.000019, 0.000019, 0.000019, 0.000019, 0.000019, 0.000019, 0.000018, 0.000018, 0.000018, 0.000018, 0.000018, 0.000018, 0.000018, 0.000018, 0.000018, 0.000018, 0.000017, 0.000017, 0.000017, 0.000017, 0.000017, 0.000017, 0.000017, 0.000017, 0.000017, 0.000017, 0.000016, 0.000016, 0.000016, 0.000016, 0.000016, 0.000016, 0.000016, 0.000016, 0.000016, 0.000016, 0.000016, 0.000016, 0.000015, 0.000015, 0.000015, 0.000015, 0.000015, 0.000015, 0.000015, 0.000015, 0.000015, 0.000015, 0.000015, 0.000015, 0.000014, 0.000014, 0.000014, 0.000014, 0.000014, 0.000014, 0.000014, 0.000014, 0.000014, 0.000014, 0.000014, 0.000014, 0.000014, 0.000013, 0.000013, 0.000013, 0.000013, 0.000013, 0.000013, 0.000013, 0.000013, 0.000013, 0.000013, 0.000013, 0.000013, 0.000013, 0.000012, 0.000012, 0.000012, 0.000012, 0.000012, 0.000012, 0.000012, 0.000012, 0.000012, 0.000012, 0.000012, 0.000012, 0.000012, 0.000012, 0.000012, 0.000011, 0.000011, 0.000011, 0.000011, 0.000011, 0.000011, 0.000011, 0.000011, 0.000011, 0.000011, 0.000011, 0.000011, 0.000011, 0.000011, 0.000011, 0.000011, 0.000011, 0.000010, 0.000010, 0.000010, 0.000010, 0.000010, 0.000010, 0.000010, 0.000010, 0.000010, 0.000010, 0.000010, 0.000010, 0.000010, 0.000010, 0.000010, 0.000010, 0.000010, 0.000009, 0.000009, 0.000009, 0.000009, 0.000009, 0.000009, 0.000009, 0.000009, 0.000009, 0.000009, 0.000009, 0.000009, 0.000009, 0.000009, 0.000009, 0.000009, 0.000009, 0.000009, 0.000009, 0.000009, 0.000008, 0.000008, 0.000008, 0.000008, 0.000008, 0.000008, 0.000008, 0.000008, 0.000008, 0.000008, 0.000008, 0.000008, 0.000008, 0.000008, 0.000008, 0.000008, 0.000008, 0.000008, 0.000008, 0.000008, 0.000008, 0.000008, 0.000007, 0.000007, 0.000007, 0.000007, 0.000007, 0.000007, 0.000007, 0.000007, 0.000007, 0.000007, 0.000007, 0.000007, 0.000007, 0.000007, 0.000007, 0.000007, 0.000007, 0.000007, 0.000007, 0.000007, 0.000007, 0.000007, 0.000007, 0.000007, 0.000007, 0.000006, 0.000006, 0.000006, 0.000006, 0.000006, 0.000006, 0.000006, 0.000006, 0.000006, 0.000006, 0.000006, 0.000006, 0.000006, 0.000006, 0.000006, 0.000006, 0.000006, 0.000006, 0.000006, 0.000006, 0.000006, 0.000006, 0.000006, 0.000006, 0.000006, 0.000006, 0.000006, 0.000006, 0.000006, 0.000005, 0.000005, 0.000005, 0.000005, 0.000005, 0.000005, 0.000005, 0.000005, 0.000005, 0.000005, 0.000005, 0.000005, 0.000005, 0.000005, 0.000005, 0.000005, 0.000005, 0.000005, 0.000005, 0.000005, 0.000005, 0.000005, 0.000005, 0.000005, 0.000005, 0.000005, 0.000005, 0.000005, 0.000005, 0.000005, 0.000005, 0.000005, 0.000005, 0.000005, 0.000004, 0.000004, 0.000004, 0.000004, 0.000004, 0.000004, 0.000004, 0.000004, 0.000004, 0.000004, 0.000004, 0.000004, 0.000004, 0.000004, 0.000004, 0.000004, 0.000004, 0.000004, 0.000004, 0.000004, 0.000004, 0.000004, 0.000004, 0.000004, 0.000004, 0.000004, 0.000004, 0.000004, 0.000004, 0.000004, 0.000004, 0.000004, 0.000004, 0.000004, 0.000004, 0.000004, 0.000004, 0.000004, 0.000004, 0.000004, 0.000004, 0.000004, 0.000004, 0.000003, 0.000003, 0.000003, 0.000003, 0.000003, 0.000003, 0.000003, 0.000003, 0.000003, 0.000003, 0.000003, 0.000003, 0.000003, 0.000003, 0.000003, 0.000003, 0.000003, 0.000003, 0.000003, 0.000003, 0.000003, 0.000003, 0.000003, 0.000003, 0.000003, 0.000003, 0.000003, 0.000003, 0.000003, 0.000003, 0.000003, 0.000003, 0.000003, 0.000003, 0.000003, 0.000003, 0.000003, 0.000003, 0.000003, 0.000003, 0.000003, 0.000003, 0.000003, 0.000003, 0.000003, 0.000003, 0.000003, 0.000003, 0.000003, 0.000003, 0.000003, 0.000003, 0.000003, 0.000003, 0.000003, 0.000003, 0.000002, 0.000002, 0.000002, 0.000002, 0.000002, 0.000002, 0.000002, 0.000002, 0.000002, 0.000002, 0.000002, 0.000002, 0.000002, 0.000002, 0.000002, 0.000002, 0.000002, 0.000002, 0.000002, 0.000002, 0.000002, 0.000002, 0.000002, 0.000002, 0.000002, 0.000002, 0.000002, 0.000002, 0.000002, 0.000002, 0.000002, 0.000002, 0.000002, 0.000002, 0.000002, 0.000002, 0.000002, 0.000002, 0.000002, 0.000002, 0.000002, 0.000002, 0.000002, 0.000002, 0.000002, 0.000002, 0.000002, 0.000002, 0.000002, 0.000002, 0.000002, 0.000002, 0.000002, 0.000002, 0.000002, 0.000002, 0.000002, 0.000002, 0.000002, 0.000002, 0.000002, 0.000002, 0.000002, 0.000002, 0.000002, 0.000002, 0.000002, 0.000002, 0.000002, 0.000002, 0.000002, 0.000002, 0.000002, 0.000002, 0.000002, 0.000002, 0.000002, 0.000002, 0.000002, 0.000002, 0.000002, 0.000002, 0.000002, 0.000002, 0.000002, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001 }; #define MOD(a, b) (((b) + (a) % (b)) % (b)) #define GET(buf, M, N, i, j) (buf[MOD(i, M) * N + MOD(j, N)]) #define SIGN(a) ((a) < 0 ? -1 : ((a) > 0 ? 1 : 0)) typedef struct { double data[2]; } double2; /* conquier phase of merge sort algorithm */ static int merge(double2* left, int nl, double2* right, int nr, int idx, double2* tmp) { int kl, kr, k; int i; /* number of inversions in bubble sort */ kl = 0; kr = 0; i = 0; for (k = 0; k < nl + nr; ++k) if (kr == nr || (kl < nl && (left[kl].data[idx] < right[kr].data[idx] || (left[kl].data[idx] == right[kr].data[idx] && left[kl].data[1-idx] <= right[kr].data[1-idx])))) { tmp[k].data[0] = left[kl].data[0]; tmp[k].data[1] = left[kl].data[1]; ++kl; } else { tmp[k].data[0] = right[kr].data[0]; tmp[k].data[1] = right[kr].data[1]; ++kr; i += nl - kl; } for (k = 0; k < nl + nr; ++k) { left[k].data[0] = tmp[k].data[0]; left[k].data[1] = tmp[k].data[1]; } return i; } /* merge sort algorithm (divide phase) return number of swaps that a bubble sort would have done */ static int merge_sort(double2* buf, int n, int idx, double2* tmp) { int m; int i, j; if (n <= 1) return 0; m = n / 2; i = merge_sort(buf, m, idx, tmp); j = merge_sort(buf + m, n - m, idx, tmp); return i + j + merge(buf, m, buf + m, n - m, idx, tmp); } /* Compute Kendall-tau coefficient in O(n log n) (not accounting for ties) */ static double2 kendalltau_noties(double2* buf, long n) { double2* buf1; double2* buf2; double2* tmp; double2 tau_z; long n0; double v; int disc; /* number of discordant pairs */ int conc; /* number of concordant pairs */ buf1 = malloc(n * sizeof(double2)); buf1 = memcpy(buf1, buf, n * sizeof(double2)); buf2 = malloc(n * sizeof(double2)); buf2 = memcpy(buf2, buf, n * sizeof(double2)); tmp = malloc(n * sizeof(double2)); merge_sort(buf1, n, 0, tmp); merge_sort(buf2, n, 1, tmp); n0 = n * (n - 1) / 2; /* number of pairs */ v = n * (n - 1) * (2 * n + 5) / 2; disc = merge_sort(buf1, n, 1, tmp); conc = n0 - disc; tau_z.data[0] = (conc - disc) / (double) n0; tau_z.data[1] = 3 * (conc - disc) / sqrt(v); free(buf1); free(buf2); free(tmp); return tau_z; } /* Compute Kendall-tau coefficient in O(n log n) (accounting for ties) */ static double2 kendalltau(double2* buf, long n) { double2* buf1; double2* buf2; double2* tmp; double2 tau_z; long n0, n1, n2, n3, t; long v0, v1, v2, v11, v22; double v; int disc; /* number of discordant pairs */ int conc; /* number of concordant pairs */ int k; buf1 = malloc(n * sizeof(double2)); buf1 = memcpy(buf1, buf, n * sizeof(double2)); buf2 = malloc(n * sizeof(double2)); buf2 = memcpy(buf2, buf, n * sizeof(double2)); tmp = malloc(n * sizeof(double2)); merge_sort(buf1, n, 0, tmp); merge_sort(buf2, n, 1, tmp); n0 = n * (n - 1) / 2; /* number of pairs */ v0 = n * (n - 1) * (2 * n + 5); n1 = 0; /* pair of ties wrt first list */ n2 = 0; /* pair of ties wrt second list */ n3 = 0; /* pair of ties wrt both list */ v1 = 0; v2 = 0; v11 = 0; v22 = 0; t = 1; for (k = 0; k < n - 1; ++k) if (buf1[k].data[0] == buf1[k+1].data[0]) ++t; else { n1 += t * (t - 1) / 2; v1 += t * (t - 1) * (2 * t + 5); v11 += t * (t - 1) * (t - 2); t = 1; } n1 += t * (t - 1) / 2; v1 += t * (t - 1) * (2 * t + 5); v11 += t * (t - 1) * (t - 2); t = 1; for (k = 0; k < n - 1; ++k) if (buf2[k].data[1] == buf2[k+1].data[1]) ++t; else { n2 += t * (t - 1) / 2; v2 += t * (t - 1) * (2 * t + 5); v22 += t * (t - 1) * (t - 2); t = 1; } n2 += t * (t - 1) / 2; v2 += t * (t - 1) * (2 * t + 5); v22 += t * (t - 1) * (t - 2); t = 1; for (k = 0; k < n - 1; ++k) { if (buf2[k].data[0] == buf2[k+1].data[0] && buf2[k].data[1] == buf2[k+1].data[1]) ++t; else { n3 += t * (t - 1) / 2; t = 1; } } n3 += t * (t - 1) / 2; v = (v0 - v1 - v2) / 18.0 + n1 * n2 / (double) n0 + v11 * v22 / (9.0 * n * (n - 1) * (n - 2)); disc = merge_sort(buf1, n, 1, tmp); conc = n0 - n1 - n2 + n3 - disc; tau_z.data[0] = (conc - disc) / sqrt((n0 - n1) * (n0 - n2)); tau_z.data[1] = (conc - disc) / sqrt(v); free(buf1); free(buf2); free(tmp); return tau_z; } /* Compute Kendall-tau coefficient in O(n^2) (not accounting for ties) */ static double2 kendalltau_naive_noties(double2* buf, long n) { int i, j; double2 tau_z; long n0; double v; n0 = n * (n - 1) / 2; v = n * (n - 1) * (2 * n + 5) / 2; tau_z.data[0] = 0; for (i = 1; i < n; ++i) for (j = 0; j < i; ++j) tau_z.data[0] += SIGN(buf[i].data[0] - buf[j].data[0]) * SIGN(buf[i].data[1] - buf[j].data[1]); tau_z.data[1] = 3 * tau_z.data[0] / sqrt(v); tau_z.data[0] /= n0; return tau_z; } /* Compute Kendall-tau coefficient in O(n^2) (accounting for ties) */ static double2 kendalltau_naive(double2* buf, long n) { int i, j, k; double2 tau_z; double2* buf1; double2* buf2; double2* tmp; long n0, n1, n2, t; long v0, v1, v2, v11, v22; double v; buf1 = malloc(n * sizeof(double2)); buf1 = memcpy(buf1, buf, n * sizeof(double2)); buf2 = malloc(n * sizeof(double2)); buf2 = memcpy(buf2, buf, n * sizeof(double2)); tmp = malloc(n * sizeof(double2)); merge_sort(buf1, n, 0, tmp); merge_sort(buf2, n, 1, tmp); n0 = n * (n - 1) / 2; /* number of pairs */ v0 = n * (n - 1) * (2 * n + 5); n1 = 0; /* pair of ties wrt first list */ n2 = 0; /* pair of ties wrt second list */ v1 = 0; v2 = 0; v11 = 0; v22 = 0; t = 1; for (k = 0; k < n - 1; ++k) if (buf1[k].data[0] == buf1[k+1].data[0]) ++t; else { n1 += t * (t - 1) / 2; v1 += t * (t - 1) * (2 * t + 5); v11 += t * (t - 1) * (t - 2); t = 1; } n1 += t * (t - 1) / 2; v1 += t * (t - 1) * (2 * t + 5); v11 += t * (t - 1) * (t - 2); t = 1; for (k = 0; k < n - 1; ++k) if (buf2[k].data[1] == buf2[k+1].data[1]) ++t; else { n2 += t * (t - 1) / 2; v2 += t * (t - 1) * (2 * t + 5); v22 += t * (t - 1) * (t - 2); t = 1; } n2 += t * (t - 1) / 2; v2 += t * (t - 1) * (2 * t + 5); v22 += t * (t - 1) * (t - 2); v = (v0 - v1 - v2) / 18.0 + n1 * n2 / (double) n0 + v11 * v22 / (9.0 * n * (n - 1) * (n - 2)); tau_z.data[0] = 0; for (i = 1; i < n; ++i) for (j = 0; j < i; ++j) tau_z.data[0] += SIGN(buf[i].data[0] - buf[j].data[0]) * SIGN(buf[i].data[1] - buf[j].data[1]); tau_z.data[1] = tau_z.data[0] / sqrt(v); tau_z.data[0] /= sqrt((n0 - n1) * (n0 - n2)); free(buf1); free(buf2); return tau_z; } /* Get p-value for 2sided test on z ~ N(0, 1) */ static double pvalue_2sided_from_z(double z) { if (isnan(z)) return NAN; z = fabs(z); if (z > normpvalues_2sided_max) return 0; else return normpvalues_2sided[(int) roundf((normpvalues_2sided_size-1) * z / normpvalues_2sided_max)]; } /* Compute tau on non-overlapping moving windows */ static int core(double* ima, double* ima_tau, double* ima_pvalue, int M, int N, int W, int dx, int dy, double2 (*kendalltau_func)(double2*, long)) { int* mask; double2* buf; double2 tau_z; double pvalue; int ij, i, j, k, l; long s; buf = malloc(W * W * sizeof(double2)); for (k = 0; k < M*N; ++k) ima_tau[k] = NAN; if (ima_pvalue) ima_pvalue = memcpy(ima_pvalue, ima_tau, M*N * sizeof(double)); mask = calloc(W * W, sizeof(int)); for (k = 0; k < W; ++k) for (l = 0; l < W; ++l) if (!GET(mask, W, W, k, l) && !GET(mask, W, W, k + dx, l + dy)) { GET(mask, W, W, k, l) = 1; GET(mask, W, W, k + dx, l + dy) = 2; } /*#pragma omp parallel default(shared) private(ij, i, j, k, l, s, tau_z, pvalue) */ { /*# pragma omp for schedule(dynamic) nowait*/ for (ij = 0; ij < (M / W) * (N / W); ++ij) { i = W * (ij / (N / W)); j = W * (ij % (N / W)); s = 0; for (k = 0; k < W; ++k) for (l = 0; l < W; ++l) if (GET(mask, W, W, k, l) == 1) { buf[s].data[0] = GET(ima, M, N, i + k, j + l); buf[s].data[1] = GET(ima, M, N, i + k + dx, j + l + dy); ++s; } tau_z = kendalltau_func(buf, s); for (k = 0; k < W; ++k) for (l = 0; l < W; ++l) GET(ima_tau, M, N, i + k, j + l) = tau_z.data[0]; if (ima_pvalue) { pvalue = pvalue_2sided_from_z(tau_z.data[1]); for (k = 0; k < W; ++k) for (l = 0; l < W; ++l) GET(ima_pvalue, M, N, i + k, j + l) = pvalue; } } } free(buf); free(mask); return 0; } #define isScalarValue(a) (mxIsNumeric(a) && !mxIsComplex(a) && mxGetM(a) == 1 && mxGetN(a) == 1) static void usage() { char str[1024]; sprintf(str, "usage: [tau, pvalue] = kendalltau(image, window_size, dx, dy,\n" \ " ['fast' | 'noties' | 'naive' | 'naive-noties'])\n"); mexErrMsgTxt(str); } void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) { double* ima; double* ima_tau; double* ima_pvalue; int W, dx, dy; int M, N; const size_t* sizes; double2 (*kendalltau_func)(double2*, long) = kendalltau; if (nrhs < 4 || nrhs > 5 || nlhs > 2) { usage(); return; } if (mxIsDouble(prhs[0]) != 1 || mxIsNumeric(prhs[0]) != 1 || mxGetNumberOfDimensions(prhs[0]) != 2 || !isScalarValue(prhs[1]) || !isScalarValue(prhs[2]) || !isScalarValue(prhs[3]) || (nrhs >= 5 && (!mxIsChar(prhs[4]) || mxGetM(prhs[4]) != 1))) { usage(); return; } if (nrhs >= 5) { int type_len = mxGetM(prhs[4]) * mxGetN(prhs[4]) + 1; char* type = mxCalloc(type_len, sizeof(char)); mxGetString(prhs[4], type, type_len); if (!strcmp(type, "fast")) kendalltau_func = kendalltau; else if (!strcmp(type, "noties")) kendalltau_func = kendalltau_noties; else if (!strcmp(type, "naive")) kendalltau_func = kendalltau_naive; else if (!strcmp(type, "naive-noties")) kendalltau_func = kendalltau_naive_noties; else { usage(); return; } }; sizes = mxGetDimensions(prhs[0]); M = sizes[1]; N = sizes[0]; ima = mxGetData(prhs[0]); W = (int) *mxGetPr(prhs[1]); dx = (int) *mxGetPr(prhs[2]); dy = (int) *mxGetPr(prhs[3]); plhs[0] = mxCreateNumericArray(2, sizes, mxDOUBLE_CLASS, mxREAL); ima_tau = mxGetData(plhs[0]); if (nlhs >= 2) { plhs[1] = mxCreateNumericArray(2, sizes, mxDOUBLE_CLASS, mxREAL); ima_pvalue = mxGetData(plhs[1]); } else ima_pvalue = NULL; switch (core(ima, ima_tau, ima_pvalue, M, N, W, dx, dy, kendalltau_func)) { case 0: break; ;; default: mexErrMsgTxt("Unexpected error"); ;; } }
41641.c
/** @file Implement image verification services for secure boot service Caution: This file requires additional review when modified. This library will have external input - PE/COFF image. This external input must be validated carefully to avoid security issue like buffer overflow, integer overflow. DxeImageVerificationLibImageRead() function will make sure the PE/COFF image content read is within the image buffer. DxeImageVerificationHandler(), HashPeImageByType(), HashPeImage() function will accept untrusted PE/COFF image and validate its data structure within this image buffer before use. Copyright (c) 2009 - 2018, Intel Corporation. All rights reserved.<BR> (C) Copyright 2016 Hewlett Packard Enterprise Development LP<BR> SPDX-License-Identifier: BSD-2-Clause-Patent **/ #include "DxeImageVerificationLib.h" // // Caution: This is used by a function which may receive untrusted input. // These global variables hold PE/COFF image data, and they should be validated before use. // EFI_IMAGE_OPTIONAL_HEADER_PTR_UNION mNtHeader; UINT32 mPeCoffHeaderOffset; EFI_GUID mCertType; // // Information on current PE/COFF image // UINTN mImageSize; UINT8 *mImageBase = NULL; UINT8 mImageDigest[MAX_DIGEST_SIZE]; UINTN mImageDigestSize; // // Notify string for authorization UI. // CHAR16 mNotifyString1[MAX_NOTIFY_STRING_LEN] = L"Image verification pass but not found in authorized database!"; CHAR16 mNotifyString2[MAX_NOTIFY_STRING_LEN] = L"Launch this image anyway? (Yes/Defer/No)"; // // Public Exponent of RSA Key. // CONST UINT8 mRsaE[] = { 0x01, 0x00, 0x01 }; // // OID ASN.1 Value for Hash Algorithms // UINT8 mHashOidValue[] = { 0x2B, 0x0E, 0x03, 0x02, 0x1A, // OBJ_sha1 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x04, // OBJ_sha224 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x01, // OBJ_sha256 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x02, // OBJ_sha384 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x03, // OBJ_sha512 }; HASH_TABLE mHash[] = { { L"SHA1", 20, &mHashOidValue[0], 5, Sha1GetContextSize, Sha1Init, Sha1Update, Sha1Final }, { L"SHA224", 28, &mHashOidValue[5], 9, NULL, NULL, NULL, NULL }, { L"SHA256", 32, &mHashOidValue[14], 9, Sha256GetContextSize, Sha256Init, Sha256Update, Sha256Final}, { L"SHA384", 48, &mHashOidValue[23], 9, Sha384GetContextSize, Sha384Init, Sha384Update, Sha384Final}, { L"SHA512", 64, &mHashOidValue[32], 9, Sha512GetContextSize, Sha512Init, Sha512Update, Sha512Final} }; EFI_STRING mHashTypeStr; /** SecureBoot Hook for processing image verification. @param[in] VariableName Name of Variable to be found. @param[in] VendorGuid Variable vendor GUID. @param[in] DataSize Size of Data found. If size is less than the data, this value contains the required size. @param[in] Data Data pointer. **/ VOID EFIAPI SecureBootHook ( IN CHAR16 *VariableName, IN EFI_GUID *VendorGuid, IN UINTN DataSize, IN VOID *Data ); /** Reads contents of a PE/COFF image in memory buffer. Caution: This function may receive untrusted input. PE/COFF image is external input, so this function will make sure the PE/COFF image content read is within the image buffer. @param FileHandle Pointer to the file handle to read the PE/COFF image. @param FileOffset Offset into the PE/COFF image to begin the read operation. @param ReadSize On input, the size in bytes of the requested read operation. On output, the number of bytes actually read. @param Buffer Output buffer that contains the data read from the PE/COFF image. @retval EFI_SUCCESS The specified portion of the PE/COFF image was read and the size **/ EFI_STATUS EFIAPI DxeImageVerificationLibImageRead ( IN VOID *FileHandle, IN UINTN FileOffset, IN OUT UINTN *ReadSize, OUT VOID *Buffer ) { UINTN EndPosition; if (FileHandle == NULL || ReadSize == NULL || Buffer == NULL) { return EFI_INVALID_PARAMETER; } if (MAX_ADDRESS - FileOffset < *ReadSize) { return EFI_INVALID_PARAMETER; } EndPosition = FileOffset + *ReadSize; if (EndPosition > mImageSize) { *ReadSize = (UINT32)(mImageSize - FileOffset); } if (FileOffset >= mImageSize) { *ReadSize = 0; } CopyMem (Buffer, (UINT8 *)((UINTN) FileHandle + FileOffset), *ReadSize); return EFI_SUCCESS; } /** Get the image type. @param[in] File This is a pointer to the device path of the file that is being dispatched. @return UINT32 Image Type **/ UINT32 GetImageType ( IN CONST EFI_DEVICE_PATH_PROTOCOL *File ) { EFI_STATUS Status; EFI_HANDLE DeviceHandle; EFI_DEVICE_PATH_PROTOCOL *TempDevicePath; EFI_BLOCK_IO_PROTOCOL *BlockIo; if (File == NULL) { return IMAGE_UNKNOWN; } // // First check to see if File is from a Firmware Volume // DeviceHandle = NULL; TempDevicePath = (EFI_DEVICE_PATH_PROTOCOL *) File; Status = gBS->LocateDevicePath ( &gEfiFirmwareVolume2ProtocolGuid, &TempDevicePath, &DeviceHandle ); if (!EFI_ERROR (Status)) { Status = gBS->OpenProtocol ( DeviceHandle, &gEfiFirmwareVolume2ProtocolGuid, NULL, NULL, NULL, EFI_OPEN_PROTOCOL_TEST_PROTOCOL ); if (!EFI_ERROR (Status)) { return IMAGE_FROM_FV; } } // // Next check to see if File is from a Block I/O device // DeviceHandle = NULL; TempDevicePath = (EFI_DEVICE_PATH_PROTOCOL *) File; Status = gBS->LocateDevicePath ( &gEfiBlockIoProtocolGuid, &TempDevicePath, &DeviceHandle ); if (!EFI_ERROR (Status)) { BlockIo = NULL; Status = gBS->OpenProtocol ( DeviceHandle, &gEfiBlockIoProtocolGuid, (VOID **) &BlockIo, NULL, NULL, EFI_OPEN_PROTOCOL_GET_PROTOCOL ); if (!EFI_ERROR (Status) && BlockIo != NULL) { if (BlockIo->Media != NULL) { if (BlockIo->Media->RemovableMedia) { // // Block I/O is present and specifies the media is removable // return IMAGE_FROM_REMOVABLE_MEDIA; } else { // // Block I/O is present and specifies the media is not removable // return IMAGE_FROM_FIXED_MEDIA; } } } } // // File is not in a Firmware Volume or on a Block I/O device, so check to see if // the device path supports the Simple File System Protocol. // DeviceHandle = NULL; TempDevicePath = (EFI_DEVICE_PATH_PROTOCOL *) File; Status = gBS->LocateDevicePath ( &gEfiSimpleFileSystemProtocolGuid, &TempDevicePath, &DeviceHandle ); if (!EFI_ERROR (Status)) { // // Simple File System is present without Block I/O, so assume media is fixed. // return IMAGE_FROM_FIXED_MEDIA; } // // File is not from an FV, Block I/O or Simple File System, so the only options // left are a PCI Option ROM and a Load File Protocol such as a PXE Boot from a NIC. // TempDevicePath = (EFI_DEVICE_PATH_PROTOCOL *) File; while (!IsDevicePathEndType (TempDevicePath)) { switch (DevicePathType (TempDevicePath)) { case MEDIA_DEVICE_PATH: if (DevicePathSubType (TempDevicePath) == MEDIA_RELATIVE_OFFSET_RANGE_DP) { return IMAGE_FROM_OPTION_ROM; } break; case MESSAGING_DEVICE_PATH: if (DevicePathSubType(TempDevicePath) == MSG_MAC_ADDR_DP) { return IMAGE_FROM_REMOVABLE_MEDIA; } break; default: break; } TempDevicePath = NextDevicePathNode (TempDevicePath); } return IMAGE_UNKNOWN; } /** Calculate hash of Pe/Coff image based on the authenticode image hashing in PE/COFF Specification 8.0 Appendix A Caution: This function may receive untrusted input. PE/COFF image is external input, so this function will validate its data structure within this image buffer before use. Notes: PE/COFF image has been checked by BasePeCoffLib PeCoffLoaderGetImageInfo() in its caller function DxeImageVerificationHandler(). @param[in] HashAlg Hash algorithm type. @retval TRUE Successfully hash image. @retval FALSE Fail in hash image. **/ BOOLEAN HashPeImage ( IN UINT32 HashAlg ) { BOOLEAN Status; EFI_IMAGE_SECTION_HEADER *Section; VOID *HashCtx; UINTN CtxSize; UINT8 *HashBase; UINTN HashSize; UINTN SumOfBytesHashed; EFI_IMAGE_SECTION_HEADER *SectionHeader; UINTN Index; UINTN Pos; UINT32 CertSize; UINT32 NumberOfRvaAndSizes; HashCtx = NULL; SectionHeader = NULL; Status = FALSE; if ((HashAlg >= HASHALG_MAX)) { return FALSE; } // // Initialize context of hash. // ZeroMem (mImageDigest, MAX_DIGEST_SIZE); switch (HashAlg) { case HASHALG_SHA1: mImageDigestSize = SHA1_DIGEST_SIZE; mCertType = gEfiCertSha1Guid; break; case HASHALG_SHA256: mImageDigestSize = SHA256_DIGEST_SIZE; mCertType = gEfiCertSha256Guid; break; case HASHALG_SHA384: mImageDigestSize = SHA384_DIGEST_SIZE; mCertType = gEfiCertSha384Guid; break; case HASHALG_SHA512: mImageDigestSize = SHA512_DIGEST_SIZE; mCertType = gEfiCertSha512Guid; break; default: return FALSE; } mHashTypeStr = mHash[HashAlg].Name; CtxSize = mHash[HashAlg].GetContextSize(); HashCtx = AllocatePool (CtxSize); if (HashCtx == NULL) { return FALSE; } // 1. Load the image header into memory. // 2. Initialize a SHA hash context. Status = mHash[HashAlg].HashInit(HashCtx); if (!Status) { goto Done; } // // Measuring PE/COFF Image Header; // But CheckSum field and SECURITY data directory (certificate) are excluded // // // 3. Calculate the distance from the base of the image header to the image checksum address. // 4. Hash the image header from its base to beginning of the image checksum. // HashBase = mImageBase; if (mNtHeader.Pe32->OptionalHeader.Magic == EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC) { // // Use PE32 offset. // HashSize = (UINTN) (&mNtHeader.Pe32->OptionalHeader.CheckSum) - (UINTN) HashBase; NumberOfRvaAndSizes = mNtHeader.Pe32->OptionalHeader.NumberOfRvaAndSizes; } else if (mNtHeader.Pe32->OptionalHeader.Magic == EFI_IMAGE_NT_OPTIONAL_HDR64_MAGIC) { // // Use PE32+ offset. // HashSize = (UINTN) (&mNtHeader.Pe32Plus->OptionalHeader.CheckSum) - (UINTN) HashBase; NumberOfRvaAndSizes = mNtHeader.Pe32Plus->OptionalHeader.NumberOfRvaAndSizes; } else { // // Invalid header magic number. // Status = FALSE; goto Done; } Status = mHash[HashAlg].HashUpdate(HashCtx, HashBase, HashSize); if (!Status) { goto Done; } // // 5. Skip over the image checksum (it occupies a single ULONG). // if (NumberOfRvaAndSizes <= EFI_IMAGE_DIRECTORY_ENTRY_SECURITY) { // // 6. Since there is no Cert Directory in optional header, hash everything // from the end of the checksum to the end of image header. // if (mNtHeader.Pe32->OptionalHeader.Magic == EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC) { // // Use PE32 offset. // HashBase = (UINT8 *) &mNtHeader.Pe32->OptionalHeader.CheckSum + sizeof (UINT32); HashSize = mNtHeader.Pe32->OptionalHeader.SizeOfHeaders - ((UINTN) HashBase - (UINTN) mImageBase); } else { // // Use PE32+ offset. // HashBase = (UINT8 *) &mNtHeader.Pe32Plus->OptionalHeader.CheckSum + sizeof (UINT32); HashSize = mNtHeader.Pe32Plus->OptionalHeader.SizeOfHeaders - ((UINTN) HashBase - (UINTN) mImageBase); } if (HashSize != 0) { Status = mHash[HashAlg].HashUpdate(HashCtx, HashBase, HashSize); if (!Status) { goto Done; } } } else { // // 7. Hash everything from the end of the checksum to the start of the Cert Directory. // if (mNtHeader.Pe32->OptionalHeader.Magic == EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC) { // // Use PE32 offset. // HashBase = (UINT8 *) &mNtHeader.Pe32->OptionalHeader.CheckSum + sizeof (UINT32); HashSize = (UINTN) (&mNtHeader.Pe32->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY]) - (UINTN) HashBase; } else { // // Use PE32+ offset. // HashBase = (UINT8 *) &mNtHeader.Pe32Plus->OptionalHeader.CheckSum + sizeof (UINT32); HashSize = (UINTN) (&mNtHeader.Pe32Plus->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY]) - (UINTN) HashBase; } if (HashSize != 0) { Status = mHash[HashAlg].HashUpdate(HashCtx, HashBase, HashSize); if (!Status) { goto Done; } } // // 8. Skip over the Cert Directory. (It is sizeof(IMAGE_DATA_DIRECTORY) bytes.) // 9. Hash everything from the end of the Cert Directory to the end of image header. // if (mNtHeader.Pe32->OptionalHeader.Magic == EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC) { // // Use PE32 offset // HashBase = (UINT8 *) &mNtHeader.Pe32->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY + 1]; HashSize = mNtHeader.Pe32->OptionalHeader.SizeOfHeaders - ((UINTN) HashBase - (UINTN) mImageBase); } else { // // Use PE32+ offset. // HashBase = (UINT8 *) &mNtHeader.Pe32Plus->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY + 1]; HashSize = mNtHeader.Pe32Plus->OptionalHeader.SizeOfHeaders - ((UINTN) HashBase - (UINTN) mImageBase); } if (HashSize != 0) { Status = mHash[HashAlg].HashUpdate(HashCtx, HashBase, HashSize); if (!Status) { goto Done; } } } // // 10. Set the SUM_OF_BYTES_HASHED to the size of the header. // if (mNtHeader.Pe32->OptionalHeader.Magic == EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC) { // // Use PE32 offset. // SumOfBytesHashed = mNtHeader.Pe32->OptionalHeader.SizeOfHeaders; } else { // // Use PE32+ offset // SumOfBytesHashed = mNtHeader.Pe32Plus->OptionalHeader.SizeOfHeaders; } Section = (EFI_IMAGE_SECTION_HEADER *) ( mImageBase + mPeCoffHeaderOffset + sizeof (UINT32) + sizeof (EFI_IMAGE_FILE_HEADER) + mNtHeader.Pe32->FileHeader.SizeOfOptionalHeader ); // // 11. Build a temporary table of pointers to all the IMAGE_SECTION_HEADER // structures in the image. The 'NumberOfSections' field of the image // header indicates how big the table should be. Do not include any // IMAGE_SECTION_HEADERs in the table whose 'SizeOfRawData' field is zero. // SectionHeader = (EFI_IMAGE_SECTION_HEADER *) AllocateZeroPool (sizeof (EFI_IMAGE_SECTION_HEADER) * mNtHeader.Pe32->FileHeader.NumberOfSections); if (SectionHeader == NULL) { Status = FALSE; goto Done; } // // 12. Using the 'PointerToRawData' in the referenced section headers as // a key, arrange the elements in the table in ascending order. In other // words, sort the section headers according to the disk-file offset of // the section. // for (Index = 0; Index < mNtHeader.Pe32->FileHeader.NumberOfSections; Index++) { Pos = Index; while ((Pos > 0) && (Section->PointerToRawData < SectionHeader[Pos - 1].PointerToRawData)) { CopyMem (&SectionHeader[Pos], &SectionHeader[Pos - 1], sizeof (EFI_IMAGE_SECTION_HEADER)); Pos--; } CopyMem (&SectionHeader[Pos], Section, sizeof (EFI_IMAGE_SECTION_HEADER)); Section += 1; } // // 13. Walk through the sorted table, bring the corresponding section // into memory, and hash the entire section (using the 'SizeOfRawData' // field in the section header to determine the amount of data to hash). // 14. Add the section's 'SizeOfRawData' to SUM_OF_BYTES_HASHED . // 15. Repeat steps 13 and 14 for all the sections in the sorted table. // for (Index = 0; Index < mNtHeader.Pe32->FileHeader.NumberOfSections; Index++) { Section = &SectionHeader[Index]; if (Section->SizeOfRawData == 0) { continue; } HashBase = mImageBase + Section->PointerToRawData; HashSize = (UINTN) Section->SizeOfRawData; Status = mHash[HashAlg].HashUpdate(HashCtx, HashBase, HashSize); if (!Status) { goto Done; } SumOfBytesHashed += HashSize; } // // 16. If the file size is greater than SUM_OF_BYTES_HASHED, there is extra // data in the file that needs to be added to the hash. This data begins // at file offset SUM_OF_BYTES_HASHED and its length is: // FileSize - (CertDirectory->Size) // if (mImageSize > SumOfBytesHashed) { HashBase = mImageBase + SumOfBytesHashed; if (NumberOfRvaAndSizes <= EFI_IMAGE_DIRECTORY_ENTRY_SECURITY) { CertSize = 0; } else { if (mNtHeader.Pe32->OptionalHeader.Magic == EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC) { // // Use PE32 offset. // CertSize = mNtHeader.Pe32->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY].Size; } else { // // Use PE32+ offset. // CertSize = mNtHeader.Pe32Plus->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY].Size; } } if (mImageSize > CertSize + SumOfBytesHashed) { HashSize = (UINTN) (mImageSize - CertSize - SumOfBytesHashed); Status = mHash[HashAlg].HashUpdate(HashCtx, HashBase, HashSize); if (!Status) { goto Done; } } else if (mImageSize < CertSize + SumOfBytesHashed) { Status = FALSE; goto Done; } } Status = mHash[HashAlg].HashFinal(HashCtx, mImageDigest); Done: if (HashCtx != NULL) { FreePool (HashCtx); } if (SectionHeader != NULL) { FreePool (SectionHeader); } return Status; } /** Recognize the Hash algorithm in PE/COFF Authenticode and calculate hash of Pe/Coff image based on the authenticode image hashing in PE/COFF Specification 8.0 Appendix A Caution: This function may receive untrusted input. PE/COFF image is external input, so this function will validate its data structure within this image buffer before use. @param[in] AuthData Pointer to the Authenticode Signature retrieved from signed image. @param[in] AuthDataSize Size of the Authenticode Signature in bytes. @retval EFI_UNSUPPORTED Hash algorithm is not supported. @retval EFI_SUCCESS Hash successfully. **/ EFI_STATUS HashPeImageByType ( IN UINT8 *AuthData, IN UINTN AuthDataSize ) { UINT8 Index; for (Index = 0; Index < HASHALG_MAX; Index++) { // // Check the Hash algorithm in PE/COFF Authenticode. // According to PKCS#7 Definition: // SignedData ::= SEQUENCE { // version Version, // digestAlgorithms DigestAlgorithmIdentifiers, // contentInfo ContentInfo, // .... } // The DigestAlgorithmIdentifiers can be used to determine the hash algorithm in PE/COFF hashing // This field has the fixed offset (+32) in final Authenticode ASN.1 data. // Fixed offset (+32) is calculated based on two bytes of length encoding. // if ((*(AuthData + 1) & TWO_BYTE_ENCODE) != TWO_BYTE_ENCODE) { // // Only support two bytes of Long Form of Length Encoding. // continue; } if (AuthDataSize < 32 + mHash[Index].OidLength) { return EFI_UNSUPPORTED; } if (CompareMem (AuthData + 32, mHash[Index].OidValue, mHash[Index].OidLength) == 0) { break; } } if (Index == HASHALG_MAX) { return EFI_UNSUPPORTED; } // // HASH PE Image based on Hash algorithm in PE/COFF Authenticode. // if (!HashPeImage(Index)) { return EFI_UNSUPPORTED; } return EFI_SUCCESS; } /** Returns the size of a given image execution info table in bytes. This function returns the size, in bytes, of the image execution info table specified by ImageExeInfoTable. If ImageExeInfoTable is NULL, then 0 is returned. @param ImageExeInfoTable A pointer to a image execution info table structure. @retval 0 If ImageExeInfoTable is NULL. @retval Others The size of a image execution info table in bytes. **/ UINTN GetImageExeInfoTableSize ( EFI_IMAGE_EXECUTION_INFO_TABLE *ImageExeInfoTable ) { UINTN Index; EFI_IMAGE_EXECUTION_INFO *ImageExeInfoItem; UINTN TotalSize; if (ImageExeInfoTable == NULL) { return 0; } ImageExeInfoItem = (EFI_IMAGE_EXECUTION_INFO *) ((UINT8 *) ImageExeInfoTable + sizeof (EFI_IMAGE_EXECUTION_INFO_TABLE)); TotalSize = sizeof (EFI_IMAGE_EXECUTION_INFO_TABLE); for (Index = 0; Index < ImageExeInfoTable->NumberOfImages; Index++) { TotalSize += ReadUnaligned32 ((UINT32 *) &ImageExeInfoItem->InfoSize); ImageExeInfoItem = (EFI_IMAGE_EXECUTION_INFO *) ((UINT8 *) ImageExeInfoItem + ReadUnaligned32 ((UINT32 *) &ImageExeInfoItem->InfoSize)); } return TotalSize; } /** Create an Image Execution Information Table entry and add it to system configuration table. @param[in] Action Describes the action taken by the firmware regarding this image. @param[in] Name Input a null-terminated, user-friendly name. @param[in] DevicePath Input device path pointer. @param[in] Signature Input signature info in EFI_SIGNATURE_LIST data structure. @param[in] SignatureSize Size of signature. **/ VOID AddImageExeInfo ( IN EFI_IMAGE_EXECUTION_ACTION Action, IN CHAR16 *Name OPTIONAL, IN CONST EFI_DEVICE_PATH_PROTOCOL *DevicePath, IN EFI_SIGNATURE_LIST *Signature OPTIONAL, IN UINTN SignatureSize ) { EFI_IMAGE_EXECUTION_INFO_TABLE *ImageExeInfoTable; EFI_IMAGE_EXECUTION_INFO_TABLE *NewImageExeInfoTable; EFI_IMAGE_EXECUTION_INFO *ImageExeInfoEntry; UINTN ImageExeInfoTableSize; UINTN NewImageExeInfoEntrySize; UINTN NameStringLen; UINTN DevicePathSize; CHAR16 *NameStr; ImageExeInfoTable = NULL; NewImageExeInfoTable = NULL; ImageExeInfoEntry = NULL; NameStringLen = 0; NameStr = NULL; if (DevicePath == NULL) { return ; } if (Name != NULL) { NameStringLen = StrSize (Name); } else { NameStringLen = sizeof (CHAR16); } EfiGetSystemConfigurationTable (&gEfiImageSecurityDatabaseGuid, (VOID **) &ImageExeInfoTable); if (ImageExeInfoTable != NULL) { // // The table has been found! // We must enlarge the table to accommodate the new exe info entry. // ImageExeInfoTableSize = GetImageExeInfoTableSize (ImageExeInfoTable); } else { // // Not Found! // We should create a new table to append to the configuration table. // ImageExeInfoTableSize = sizeof (EFI_IMAGE_EXECUTION_INFO_TABLE); } DevicePathSize = GetDevicePathSize (DevicePath); // // Signature size can be odd. Pad after signature to ensure next EXECUTION_INFO entry align // NewImageExeInfoEntrySize = sizeof (EFI_IMAGE_EXECUTION_INFO) + NameStringLen + DevicePathSize + SignatureSize; NewImageExeInfoTable = (EFI_IMAGE_EXECUTION_INFO_TABLE *) AllocateRuntimePool (ImageExeInfoTableSize + NewImageExeInfoEntrySize); if (NewImageExeInfoTable == NULL) { return ; } if (ImageExeInfoTable != NULL) { CopyMem (NewImageExeInfoTable, ImageExeInfoTable, ImageExeInfoTableSize); } else { NewImageExeInfoTable->NumberOfImages = 0; } NewImageExeInfoTable->NumberOfImages++; ImageExeInfoEntry = (EFI_IMAGE_EXECUTION_INFO *) ((UINT8 *) NewImageExeInfoTable + ImageExeInfoTableSize); // // Update new item's information. // WriteUnaligned32 ((UINT32 *) ImageExeInfoEntry, Action); WriteUnaligned32 ((UINT32 *) ((UINT8 *) ImageExeInfoEntry + sizeof (EFI_IMAGE_EXECUTION_ACTION)), (UINT32) NewImageExeInfoEntrySize); NameStr = (CHAR16 *)(ImageExeInfoEntry + 1); if (Name != NULL) { CopyMem ((UINT8 *) NameStr, Name, NameStringLen); } else { ZeroMem ((UINT8 *) NameStr, sizeof (CHAR16)); } CopyMem ( (UINT8 *) NameStr + NameStringLen, DevicePath, DevicePathSize ); if (Signature != NULL) { CopyMem ( (UINT8 *) NameStr + NameStringLen + DevicePathSize, Signature, SignatureSize ); } // // Update/replace the image execution table. // gBS->InstallConfigurationTable (&gEfiImageSecurityDatabaseGuid, (VOID *) NewImageExeInfoTable); // // Free Old table data! // if (ImageExeInfoTable != NULL) { FreePool (ImageExeInfoTable); } } /** Check whether the hash of an given X.509 certificate is in forbidden database (DBX). @param[in] Certificate Pointer to X.509 Certificate that is searched for. @param[in] CertSize Size of X.509 Certificate. @param[in] SignatureList Pointer to the Signature List in forbidden database. @param[in] SignatureListSize Size of Signature List. @param[out] RevocationTime Return the time that the certificate was revoked. @return TRUE The certificate hash is found in the forbidden database. @return FALSE The certificate hash is not found in the forbidden database. **/ BOOLEAN IsCertHashFoundInDatabase ( IN UINT8 *Certificate, IN UINTN CertSize, IN EFI_SIGNATURE_LIST *SignatureList, IN UINTN SignatureListSize, OUT EFI_TIME *RevocationTime ) { BOOLEAN IsFound; BOOLEAN Status; EFI_SIGNATURE_LIST *DbxList; UINTN DbxSize; EFI_SIGNATURE_DATA *CertHash; UINTN CertHashCount; UINTN Index; UINT32 HashAlg; VOID *HashCtx; UINT8 CertDigest[MAX_DIGEST_SIZE]; UINT8 *DbxCertHash; UINTN SiglistHeaderSize; UINT8 *TBSCert; UINTN TBSCertSize; IsFound = FALSE; DbxList = SignatureList; DbxSize = SignatureListSize; HashCtx = NULL; HashAlg = HASHALG_MAX; if ((RevocationTime == NULL) || (DbxList == NULL)) { return FALSE; } // // Retrieve the TBSCertificate from the X.509 Certificate. // if (!X509GetTBSCert (Certificate, CertSize, &TBSCert, &TBSCertSize)) { return FALSE; } while ((DbxSize > 0) && (SignatureListSize >= DbxList->SignatureListSize)) { // // Determine Hash Algorithm of Certificate in the forbidden database. // if (CompareGuid (&DbxList->SignatureType, &gEfiCertX509Sha256Guid)) { HashAlg = HASHALG_SHA256; } else if (CompareGuid (&DbxList->SignatureType, &gEfiCertX509Sha384Guid)) { HashAlg = HASHALG_SHA384; } else if (CompareGuid (&DbxList->SignatureType, &gEfiCertX509Sha512Guid)) { HashAlg = HASHALG_SHA512; } else { DbxSize -= DbxList->SignatureListSize; DbxList = (EFI_SIGNATURE_LIST *) ((UINT8 *) DbxList + DbxList->SignatureListSize); continue; } // // Calculate the hash value of current TBSCertificate for comparision. // if (mHash[HashAlg].GetContextSize == NULL) { goto Done; } ZeroMem (CertDigest, MAX_DIGEST_SIZE); HashCtx = AllocatePool (mHash[HashAlg].GetContextSize ()); if (HashCtx == NULL) { goto Done; } Status = mHash[HashAlg].HashInit (HashCtx); if (!Status) { goto Done; } Status = mHash[HashAlg].HashUpdate (HashCtx, TBSCert, TBSCertSize); if (!Status) { goto Done; } Status = mHash[HashAlg].HashFinal (HashCtx, CertDigest); if (!Status) { goto Done; } SiglistHeaderSize = sizeof (EFI_SIGNATURE_LIST) + DbxList->SignatureHeaderSize; CertHash = (EFI_SIGNATURE_DATA *) ((UINT8 *) DbxList + SiglistHeaderSize); CertHashCount = (DbxList->SignatureListSize - SiglistHeaderSize) / DbxList->SignatureSize; for (Index = 0; Index < CertHashCount; Index++) { // // Iterate each Signature Data Node within this CertList for verify. // DbxCertHash = CertHash->SignatureData; if (CompareMem (DbxCertHash, CertDigest, mHash[HashAlg].DigestLength) == 0) { // // Hash of Certificate is found in forbidden database. // IsFound = TRUE; // // Return the revocation time. // CopyMem (RevocationTime, (EFI_TIME *)(DbxCertHash + mHash[HashAlg].DigestLength), sizeof (EFI_TIME)); goto Done; } CertHash = (EFI_SIGNATURE_DATA *) ((UINT8 *) CertHash + DbxList->SignatureSize); } DbxSize -= DbxList->SignatureListSize; DbxList = (EFI_SIGNATURE_LIST *) ((UINT8 *) DbxList + DbxList->SignatureListSize); } Done: if (HashCtx != NULL) { FreePool (HashCtx); } return IsFound; } /** Check whether signature is in specified database. @param[in] VariableName Name of database variable that is searched in. @param[in] Signature Pointer to signature that is searched for. @param[in] CertType Pointer to hash algorithm. @param[in] SignatureSize Size of Signature. @return TRUE Found the signature in the variable database. @return FALSE Not found the signature in the variable database. **/ BOOLEAN IsSignatureFoundInDatabase ( IN CHAR16 *VariableName, IN UINT8 *Signature, IN EFI_GUID *CertType, IN UINTN SignatureSize ) { EFI_STATUS Status; EFI_SIGNATURE_LIST *CertList; EFI_SIGNATURE_DATA *Cert; UINTN DataSize; UINT8 *Data; UINTN Index; UINTN CertCount; BOOLEAN IsFound; // // Read signature database variable. // IsFound = FALSE; Data = NULL; DataSize = 0; Status = gRT->GetVariable (VariableName, &gEfiImageSecurityDatabaseGuid, NULL, &DataSize, NULL); if (Status != EFI_BUFFER_TOO_SMALL) { return FALSE; } Data = (UINT8 *) AllocateZeroPool (DataSize); if (Data == NULL) { return FALSE; } Status = gRT->GetVariable (VariableName, &gEfiImageSecurityDatabaseGuid, NULL, &DataSize, Data); if (EFI_ERROR (Status)) { goto Done; } // // Enumerate all signature data in SigDB to check if signature exists for executable. // CertList = (EFI_SIGNATURE_LIST *) Data; while ((DataSize > 0) && (DataSize >= CertList->SignatureListSize)) { CertCount = (CertList->SignatureListSize - sizeof (EFI_SIGNATURE_LIST) - CertList->SignatureHeaderSize) / CertList->SignatureSize; Cert = (EFI_SIGNATURE_DATA *) ((UINT8 *) CertList + sizeof (EFI_SIGNATURE_LIST) + CertList->SignatureHeaderSize); if ((CertList->SignatureSize == sizeof(EFI_SIGNATURE_DATA) - 1 + SignatureSize) && (CompareGuid(&CertList->SignatureType, CertType))) { for (Index = 0; Index < CertCount; Index++) { if (CompareMem (Cert->SignatureData, Signature, SignatureSize) == 0) { // // Find the signature in database. // IsFound = TRUE; // // Entries in UEFI_IMAGE_SECURITY_DATABASE that are used to validate image should be measured // if (StrCmp(VariableName, EFI_IMAGE_SECURITY_DATABASE) == 0) { SecureBootHook (VariableName, &gEfiImageSecurityDatabaseGuid, CertList->SignatureSize, Cert); } break; } Cert = (EFI_SIGNATURE_DATA *) ((UINT8 *) Cert + CertList->SignatureSize); } if (IsFound) { break; } } DataSize -= CertList->SignatureListSize; CertList = (EFI_SIGNATURE_LIST *) ((UINT8 *) CertList + CertList->SignatureListSize); } Done: if (Data != NULL) { FreePool (Data); } return IsFound; } /** Check whether the timestamp is valid by comparing the signing time and the revocation time. @param SigningTime A pointer to the signing time. @param RevocationTime A pointer to the revocation time. @retval TRUE The SigningTime is not later than the RevocationTime. @retval FALSE The SigningTime is later than the RevocationTime. **/ BOOLEAN IsValidSignatureByTimestamp ( IN EFI_TIME *SigningTime, IN EFI_TIME *RevocationTime ) { if (SigningTime->Year != RevocationTime->Year) { return (BOOLEAN) (SigningTime->Year < RevocationTime->Year); } else if (SigningTime->Month != RevocationTime->Month) { return (BOOLEAN) (SigningTime->Month < RevocationTime->Month); } else if (SigningTime->Day != RevocationTime->Day) { return (BOOLEAN) (SigningTime->Day < RevocationTime->Day); } else if (SigningTime->Hour != RevocationTime->Hour) { return (BOOLEAN) (SigningTime->Hour < RevocationTime->Hour); } else if (SigningTime->Minute != RevocationTime->Minute) { return (BOOLEAN) (SigningTime->Minute < RevocationTime->Minute); } return (BOOLEAN) (SigningTime->Second <= RevocationTime->Second); } /** Check if the given time value is zero. @param[in] Time Pointer of a time value. @retval TRUE The Time is Zero. @retval FALSE The Time is not Zero. **/ BOOLEAN IsTimeZero ( IN EFI_TIME *Time ) { if ((Time->Year == 0) && (Time->Month == 0) && (Time->Day == 0) && (Time->Hour == 0) && (Time->Minute == 0) && (Time->Second == 0)) { return TRUE; } return FALSE; } /** Check whether the timestamp signature is valid and the signing time is also earlier than the revocation time. @param[in] AuthData Pointer to the Authenticode signature retrieved from signed image. @param[in] AuthDataSize Size of the Authenticode signature in bytes. @param[in] RevocationTime The time that the certificate was revoked. @retval TRUE Timestamp signature is valid and signing time is no later than the revocation time. @retval FALSE Timestamp signature is not valid or the signing time is later than the revocation time. **/ BOOLEAN PassTimestampCheck ( IN UINT8 *AuthData, IN UINTN AuthDataSize, IN EFI_TIME *RevocationTime ) { EFI_STATUS Status; BOOLEAN VerifyStatus; EFI_SIGNATURE_LIST *CertList; EFI_SIGNATURE_DATA *Cert; UINT8 *DbtData; UINTN DbtDataSize; UINT8 *RootCert; UINTN RootCertSize; UINTN Index; UINTN CertCount; EFI_TIME SigningTime; // // Variable Initialization // VerifyStatus = FALSE; DbtData = NULL; CertList = NULL; Cert = NULL; RootCert = NULL; RootCertSize = 0; // // If RevocationTime is zero, the certificate shall be considered to always be revoked. // if (IsTimeZero (RevocationTime)) { return FALSE; } // // RevocationTime is non-zero, the certificate should be considered to be revoked from that time and onwards. // Using the dbt to get the trusted TSA certificates. // DbtDataSize = 0; Status = gRT->GetVariable (EFI_IMAGE_SECURITY_DATABASE2, &gEfiImageSecurityDatabaseGuid, NULL, &DbtDataSize, NULL); if (Status != EFI_BUFFER_TOO_SMALL) { goto Done; } DbtData = (UINT8 *) AllocateZeroPool (DbtDataSize); if (DbtData == NULL) { goto Done; } Status = gRT->GetVariable (EFI_IMAGE_SECURITY_DATABASE2, &gEfiImageSecurityDatabaseGuid, NULL, &DbtDataSize, (VOID *) DbtData); if (EFI_ERROR (Status)) { goto Done; } CertList = (EFI_SIGNATURE_LIST *) DbtData; while ((DbtDataSize > 0) && (DbtDataSize >= CertList->SignatureListSize)) { if (CompareGuid (&CertList->SignatureType, &gEfiCertX509Guid)) { Cert = (EFI_SIGNATURE_DATA *) ((UINT8 *) CertList + sizeof (EFI_SIGNATURE_LIST) + CertList->SignatureHeaderSize); CertCount = (CertList->SignatureListSize - sizeof (EFI_SIGNATURE_LIST) - CertList->SignatureHeaderSize) / CertList->SignatureSize; for (Index = 0; Index < CertCount; Index++) { // // Iterate each Signature Data Node within this CertList for verify. // RootCert = Cert->SignatureData; RootCertSize = CertList->SignatureSize - sizeof (EFI_GUID); // // Get the signing time if the timestamp signature is valid. // if (ImageTimestampVerify (AuthData, AuthDataSize, RootCert, RootCertSize, &SigningTime)) { // // The signer signature is valid only when the signing time is earlier than revocation time. // if (IsValidSignatureByTimestamp (&SigningTime, RevocationTime)) { VerifyStatus = TRUE; goto Done; } } Cert = (EFI_SIGNATURE_DATA *) ((UINT8 *) Cert + CertList->SignatureSize); } } DbtDataSize -= CertList->SignatureListSize; CertList = (EFI_SIGNATURE_LIST *) ((UINT8 *) CertList + CertList->SignatureListSize); } Done: if (DbtData != NULL) { FreePool (DbtData); } return VerifyStatus; } /** Check whether the image signature is forbidden by the forbidden database (dbx). The image is forbidden to load if any certificates for signing are revoked before signing time. @param[in] AuthData Pointer to the Authenticode signature retrieved from the signed image. @param[in] AuthDataSize Size of the Authenticode signature in bytes. @retval TRUE Image is forbidden by dbx. @retval FALSE Image is not forbidden by dbx. **/ BOOLEAN IsForbiddenByDbx ( IN UINT8 *AuthData, IN UINTN AuthDataSize ) { EFI_STATUS Status; BOOLEAN IsForbidden; UINT8 *Data; UINTN DataSize; EFI_SIGNATURE_LIST *CertList; UINTN CertListSize; EFI_SIGNATURE_DATA *CertData; UINT8 *RootCert; UINTN RootCertSize; UINTN CertCount; UINTN Index; UINT8 *CertBuffer; UINTN BufferLength; UINT8 *TrustedCert; UINTN TrustedCertLength; UINT8 CertNumber; UINT8 *CertPtr; UINT8 *Cert; UINTN CertSize; EFI_TIME RevocationTime; // // Variable Initialization // IsForbidden = FALSE; Data = NULL; CertList = NULL; CertData = NULL; RootCert = NULL; RootCertSize = 0; Cert = NULL; CertBuffer = NULL; BufferLength = 0; TrustedCert = NULL; TrustedCertLength = 0; // // The image will not be forbidden if dbx can't be got. // DataSize = 0; Status = gRT->GetVariable (EFI_IMAGE_SECURITY_DATABASE1, &gEfiImageSecurityDatabaseGuid, NULL, &DataSize, NULL); if (Status != EFI_BUFFER_TOO_SMALL) { return IsForbidden; } Data = (UINT8 *) AllocateZeroPool (DataSize); if (Data == NULL) { return IsForbidden; } Status = gRT->GetVariable (EFI_IMAGE_SECURITY_DATABASE1, &gEfiImageSecurityDatabaseGuid, NULL, &DataSize, (VOID *) Data); if (EFI_ERROR (Status)) { return IsForbidden; } // // Verify image signature with RAW X509 certificates in DBX database. // If passed, the image will be forbidden. // CertList = (EFI_SIGNATURE_LIST *) Data; CertListSize = DataSize; while ((CertListSize > 0) && (CertListSize >= CertList->SignatureListSize)) { if (CompareGuid (&CertList->SignatureType, &gEfiCertX509Guid)) { CertData = (EFI_SIGNATURE_DATA *) ((UINT8 *) CertList + sizeof (EFI_SIGNATURE_LIST) + CertList->SignatureHeaderSize); CertCount = (CertList->SignatureListSize - sizeof (EFI_SIGNATURE_LIST) - CertList->SignatureHeaderSize) / CertList->SignatureSize; for (Index = 0; Index < CertCount; Index++) { // // Iterate each Signature Data Node within this CertList for verify. // RootCert = CertData->SignatureData; RootCertSize = CertList->SignatureSize - sizeof (EFI_GUID); // // Call AuthenticodeVerify library to Verify Authenticode struct. // IsForbidden = AuthenticodeVerify ( AuthData, AuthDataSize, RootCert, RootCertSize, mImageDigest, mImageDigestSize ); if (IsForbidden) { DEBUG ((DEBUG_INFO, "DxeImageVerificationLib: Image is signed but signature is forbidden by DBX.\n")); goto Done; } CertData = (EFI_SIGNATURE_DATA *) ((UINT8 *) CertData + CertList->SignatureSize); } } CertListSize -= CertList->SignatureListSize; CertList = (EFI_SIGNATURE_LIST *) ((UINT8 *) CertList + CertList->SignatureListSize); } // // Check X.509 Certificate Hash & Possible Timestamp. // // // Retrieve the certificate stack from AuthData // The output CertStack format will be: // UINT8 CertNumber; // UINT32 Cert1Length; // UINT8 Cert1[]; // UINT32 Cert2Length; // UINT8 Cert2[]; // ... // UINT32 CertnLength; // UINT8 Certn[]; // Pkcs7GetSigners (AuthData, AuthDataSize, &CertBuffer, &BufferLength, &TrustedCert, &TrustedCertLength); if ((BufferLength == 0) || (CertBuffer == NULL)) { IsForbidden = TRUE; goto Done; } // // Check if any hash of certificates embedded in AuthData is in the forbidden database. // CertNumber = (UINT8) (*CertBuffer); CertPtr = CertBuffer + 1; for (Index = 0; Index < CertNumber; Index++) { CertSize = (UINTN) ReadUnaligned32 ((UINT32 *)CertPtr); Cert = (UINT8 *)CertPtr + sizeof (UINT32); // // Advance CertPtr to the next cert in image signer's cert list // CertPtr = CertPtr + sizeof (UINT32) + CertSize; if (IsCertHashFoundInDatabase (Cert, CertSize, (EFI_SIGNATURE_LIST *)Data, DataSize, &RevocationTime)) { // // Check the timestamp signature and signing time to determine if the image can be trusted. // IsForbidden = TRUE; if (PassTimestampCheck (AuthData, AuthDataSize, &RevocationTime)) { IsForbidden = FALSE; // // Pass DBT check. Continue to check other certs in image signer's cert list against DBX, DBT // continue; } DEBUG ((DEBUG_INFO, "DxeImageVerificationLib: Image is signed but signature failed the timestamp check.\n")); goto Done; } } Done: if (Data != NULL) { FreePool (Data); } Pkcs7FreeSigners (CertBuffer); Pkcs7FreeSigners (TrustedCert); return IsForbidden; } /** Check whether the image signature can be verified by the trusted certificates in DB database. @param[in] AuthData Pointer to the Authenticode signature retrieved from signed image. @param[in] AuthDataSize Size of the Authenticode signature in bytes. @retval TRUE Image passed verification using certificate in db. @retval FALSE Image didn't pass verification using certificate in db. **/ BOOLEAN IsAllowedByDb ( IN UINT8 *AuthData, IN UINTN AuthDataSize ) { EFI_STATUS Status; BOOLEAN VerifyStatus; EFI_SIGNATURE_LIST *CertList; EFI_SIGNATURE_DATA *CertData; UINTN DataSize; UINT8 *Data; UINT8 *RootCert; UINTN RootCertSize; UINTN Index; UINTN CertCount; UINTN DbxDataSize; UINT8 *DbxData; EFI_TIME RevocationTime; Data = NULL; CertList = NULL; CertData = NULL; RootCert = NULL; DbxData = NULL; RootCertSize = 0; VerifyStatus = FALSE; DataSize = 0; Status = gRT->GetVariable (EFI_IMAGE_SECURITY_DATABASE, &gEfiImageSecurityDatabaseGuid, NULL, &DataSize, NULL); if (Status == EFI_BUFFER_TOO_SMALL) { Data = (UINT8 *) AllocateZeroPool (DataSize); if (Data == NULL) { return VerifyStatus; } Status = gRT->GetVariable (EFI_IMAGE_SECURITY_DATABASE, &gEfiImageSecurityDatabaseGuid, NULL, &DataSize, (VOID *) Data); if (EFI_ERROR (Status)) { goto Done; } // // Find X509 certificate in Signature List to verify the signature in pkcs7 signed data. // CertList = (EFI_SIGNATURE_LIST *) Data; while ((DataSize > 0) && (DataSize >= CertList->SignatureListSize)) { if (CompareGuid (&CertList->SignatureType, &gEfiCertX509Guid)) { CertData = (EFI_SIGNATURE_DATA *) ((UINT8 *) CertList + sizeof (EFI_SIGNATURE_LIST) + CertList->SignatureHeaderSize); CertCount = (CertList->SignatureListSize - sizeof (EFI_SIGNATURE_LIST) - CertList->SignatureHeaderSize) / CertList->SignatureSize; for (Index = 0; Index < CertCount; Index++) { // // Iterate each Signature Data Node within this CertList for verify. // RootCert = CertData->SignatureData; RootCertSize = CertList->SignatureSize - sizeof (EFI_GUID); // // Call AuthenticodeVerify library to Verify Authenticode struct. // VerifyStatus = AuthenticodeVerify ( AuthData, AuthDataSize, RootCert, RootCertSize, mImageDigest, mImageDigestSize ); if (VerifyStatus) { // // Here We still need to check if this RootCert's Hash is revoked // Status = gRT->GetVariable (EFI_IMAGE_SECURITY_DATABASE1, &gEfiImageSecurityDatabaseGuid, NULL, &DbxDataSize, NULL); if (Status == EFI_BUFFER_TOO_SMALL) { goto Done; } DbxData = (UINT8 *) AllocateZeroPool (DbxDataSize); if (DbxData == NULL) { goto Done; } Status = gRT->GetVariable (EFI_IMAGE_SECURITY_DATABASE1, &gEfiImageSecurityDatabaseGuid, NULL, &DbxDataSize, (VOID *) DbxData); if (EFI_ERROR (Status)) { goto Done; } if (IsCertHashFoundInDatabase (RootCert, RootCertSize, (EFI_SIGNATURE_LIST *)DbxData, DbxDataSize, &RevocationTime)) { // // Check the timestamp signature and signing time to determine if the RootCert can be trusted. // VerifyStatus = PassTimestampCheck (AuthData, AuthDataSize, &RevocationTime); if (!VerifyStatus) { DEBUG ((DEBUG_INFO, "DxeImageVerificationLib: Image is signed and signature is accepted by DB, but its root cert failed the timestamp check.\n")); } } goto Done; } CertData = (EFI_SIGNATURE_DATA *) ((UINT8 *) CertData + CertList->SignatureSize); } } DataSize -= CertList->SignatureListSize; CertList = (EFI_SIGNATURE_LIST *) ((UINT8 *) CertList + CertList->SignatureListSize); } } Done: if (VerifyStatus) { SecureBootHook (EFI_IMAGE_SECURITY_DATABASE, &gEfiImageSecurityDatabaseGuid, CertList->SignatureSize, CertData); } if (Data != NULL) { FreePool (Data); } if (DbxData != NULL) { FreePool (DbxData); } return VerifyStatus; } /** Provide verification service for signed images, which include both signature validation and platform policy control. For signature types, both UEFI WIN_CERTIFICATE_UEFI_GUID and MSFT Authenticode type signatures are supported. In this implementation, only verify external executables when in USER MODE. Executables from FV is bypass, so pass in AuthenticationStatus is ignored. The image verification policy is: If the image is signed, At least one valid signature or at least one hash value of the image must match a record in the security database "db", and no valid signature nor any hash value of the image may be reflected in the security database "dbx". Otherwise, the image is not signed, The SHA256 hash value of the image must match a record in the security database "db", and not be reflected in the security data base "dbx". Caution: This function may receive untrusted input. PE/COFF image is external input, so this function will validate its data structure within this image buffer before use. @param[in] AuthenticationStatus This is the authentication status returned from the security measurement services for the input file. @param[in] File This is a pointer to the device path of the file that is being dispatched. This will optionally be used for logging. @param[in] FileBuffer File buffer matches the input file device path. @param[in] FileSize Size of File buffer matches the input file device path. @param[in] BootPolicy A boot policy that was used to call LoadImage() UEFI service. @retval EFI_SUCCESS The file specified by DevicePath and non-NULL FileBuffer did authenticate, and the platform policy dictates that the DXE Foundation may use the file. @retval EFI_SUCCESS The device path specified by NULL device path DevicePath and non-NULL FileBuffer did authenticate, and the platform policy dictates that the DXE Foundation may execute the image in FileBuffer. @retval EFI_OUT_RESOURCE Fail to allocate memory. @retval EFI_SECURITY_VIOLATION The file specified by File did not authenticate, and the platform policy dictates that File should be placed in the untrusted state. The image has been added to the file execution table. @retval EFI_ACCESS_DENIED The file specified by File and FileBuffer did not authenticate, and the platform policy dictates that the DXE Foundation many not use File. **/ EFI_STATUS EFIAPI DxeImageVerificationHandler ( IN UINT32 AuthenticationStatus, IN CONST EFI_DEVICE_PATH_PROTOCOL *File, IN VOID *FileBuffer, IN UINTN FileSize, IN BOOLEAN BootPolicy ) { EFI_STATUS Status; EFI_IMAGE_DOS_HEADER *DosHdr; EFI_STATUS VerifyStatus; EFI_SIGNATURE_LIST *SignatureList; UINTN SignatureListSize; EFI_SIGNATURE_DATA *Signature; EFI_IMAGE_EXECUTION_ACTION Action; WIN_CERTIFICATE *WinCertificate; UINT32 Policy; UINT8 *SecureBoot; PE_COFF_LOADER_IMAGE_CONTEXT ImageContext; UINT32 NumberOfRvaAndSizes; WIN_CERTIFICATE_EFI_PKCS *PkcsCertData; WIN_CERTIFICATE_UEFI_GUID *WinCertUefiGuid; UINT8 *AuthData; UINTN AuthDataSize; EFI_IMAGE_DATA_DIRECTORY *SecDataDir; UINT32 OffSet; CHAR16 *NameStr; SignatureList = NULL; SignatureListSize = 0; WinCertificate = NULL; SecDataDir = NULL; PkcsCertData = NULL; Action = EFI_IMAGE_EXECUTION_AUTH_UNTESTED; Status = EFI_ACCESS_DENIED; VerifyStatus = EFI_ACCESS_DENIED; // // Check the image type and get policy setting. // switch (GetImageType (File)) { case IMAGE_FROM_FV: Policy = ALWAYS_EXECUTE; break; case IMAGE_FROM_OPTION_ROM: Policy = PcdGet32 (PcdOptionRomImageVerificationPolicy); break; case IMAGE_FROM_REMOVABLE_MEDIA: Policy = PcdGet32 (PcdRemovableMediaImageVerificationPolicy); break; case IMAGE_FROM_FIXED_MEDIA: Policy = PcdGet32 (PcdFixedMediaImageVerificationPolicy); break; default: Policy = DENY_EXECUTE_ON_SECURITY_VIOLATION; break; } // // If policy is always/never execute, return directly. // if (Policy == ALWAYS_EXECUTE) { return EFI_SUCCESS; } else if (Policy == NEVER_EXECUTE) { return EFI_ACCESS_DENIED; } // // The policy QUERY_USER_ON_SECURITY_VIOLATION and ALLOW_EXECUTE_ON_SECURITY_VIOLATION // violates the UEFI spec and has been removed. // ASSERT (Policy != QUERY_USER_ON_SECURITY_VIOLATION && Policy != ALLOW_EXECUTE_ON_SECURITY_VIOLATION); if (Policy == QUERY_USER_ON_SECURITY_VIOLATION || Policy == ALLOW_EXECUTE_ON_SECURITY_VIOLATION) { CpuDeadLoop (); } GetEfiGlobalVariable2 (EFI_SECURE_BOOT_MODE_NAME, (VOID**)&SecureBoot, NULL); // // Skip verification if SecureBoot variable doesn't exist. // if (SecureBoot == NULL) { return EFI_SUCCESS; } // // Skip verification if SecureBoot is disabled but not AuditMode // if (*SecureBoot == SECURE_BOOT_MODE_DISABLE) { FreePool (SecureBoot); return EFI_SUCCESS; } FreePool (SecureBoot); // // Read the Dos header. // if (FileBuffer == NULL) { return EFI_INVALID_PARAMETER; } mImageBase = (UINT8 *) FileBuffer; mImageSize = FileSize; ZeroMem (&ImageContext, sizeof (ImageContext)); ImageContext.Handle = (VOID *) FileBuffer; ImageContext.ImageRead = (PE_COFF_LOADER_READ_FILE) DxeImageVerificationLibImageRead; // // Get information about the image being loaded // Status = PeCoffLoaderGetImageInfo (&ImageContext); if (EFI_ERROR (Status)) { // // The information can't be got from the invalid PeImage // DEBUG ((DEBUG_INFO, "DxeImageVerificationLib: PeImage invalid. Cannot retrieve image information.\n")); goto Done; } Status = EFI_ACCESS_DENIED; DosHdr = (EFI_IMAGE_DOS_HEADER *) mImageBase; if (DosHdr->e_magic == EFI_IMAGE_DOS_SIGNATURE) { // // DOS image header is present, // so read the PE header after the DOS image header. // mPeCoffHeaderOffset = DosHdr->e_lfanew; } else { mPeCoffHeaderOffset = 0; } // // Check PE/COFF image. // mNtHeader.Pe32 = (EFI_IMAGE_NT_HEADERS32 *) (mImageBase + mPeCoffHeaderOffset); if (mNtHeader.Pe32->Signature != EFI_IMAGE_NT_SIGNATURE) { // // It is not a valid Pe/Coff file. // DEBUG ((DEBUG_INFO, "DxeImageVerificationLib: Not a valid PE/COFF image.\n")); goto Done; } if (mNtHeader.Pe32->OptionalHeader.Magic == EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC) { // // Use PE32 offset. // NumberOfRvaAndSizes = mNtHeader.Pe32->OptionalHeader.NumberOfRvaAndSizes; if (NumberOfRvaAndSizes > EFI_IMAGE_DIRECTORY_ENTRY_SECURITY) { SecDataDir = (EFI_IMAGE_DATA_DIRECTORY *) &mNtHeader.Pe32->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY]; } } else { // // Use PE32+ offset. // NumberOfRvaAndSizes = mNtHeader.Pe32Plus->OptionalHeader.NumberOfRvaAndSizes; if (NumberOfRvaAndSizes > EFI_IMAGE_DIRECTORY_ENTRY_SECURITY) { SecDataDir = (EFI_IMAGE_DATA_DIRECTORY *) &mNtHeader.Pe32Plus->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY]; } } // // Start Image Validation. // if (SecDataDir == NULL || SecDataDir->Size == 0) { // // This image is not signed. The SHA256 hash value of the image must match a record in the security database "db", // and not be reflected in the security data base "dbx". // if (!HashPeImage (HASHALG_SHA256)) { DEBUG ((DEBUG_INFO, "DxeImageVerificationLib: Failed to hash this image using %s.\n", mHashTypeStr)); goto Done; } if (IsSignatureFoundInDatabase (EFI_IMAGE_SECURITY_DATABASE1, mImageDigest, &mCertType, mImageDigestSize)) { // // Image Hash is in forbidden database (DBX). // DEBUG ((DEBUG_INFO, "DxeImageVerificationLib: Image is not signed and %s hash of image is forbidden by DBX.\n", mHashTypeStr)); goto Done; } if (IsSignatureFoundInDatabase (EFI_IMAGE_SECURITY_DATABASE, mImageDigest, &mCertType, mImageDigestSize)) { // // Image Hash is in allowed database (DB). // return EFI_SUCCESS; } // // Image Hash is not found in both forbidden and allowed database. // DEBUG ((DEBUG_INFO, "DxeImageVerificationLib: Image is not signed and %s hash of image is not found in DB/DBX.\n", mHashTypeStr)); goto Done; } // // Verify the signature of the image, multiple signatures are allowed as per PE/COFF Section 4.7 // "Attribute Certificate Table". // The first certificate starts at offset (SecDataDir->VirtualAddress) from the start of the file. // for (OffSet = SecDataDir->VirtualAddress; OffSet < (SecDataDir->VirtualAddress + SecDataDir->Size); OffSet += (WinCertificate->dwLength + ALIGN_SIZE (WinCertificate->dwLength))) { WinCertificate = (WIN_CERTIFICATE *) (mImageBase + OffSet); if ((SecDataDir->VirtualAddress + SecDataDir->Size - OffSet) <= sizeof (WIN_CERTIFICATE) || (SecDataDir->VirtualAddress + SecDataDir->Size - OffSet) < WinCertificate->dwLength) { break; } // // Verify the image's Authenticode signature, only DER-encoded PKCS#7 signed data is supported. // if (WinCertificate->wCertificateType == WIN_CERT_TYPE_PKCS_SIGNED_DATA) { // // The certificate is formatted as WIN_CERTIFICATE_EFI_PKCS which is described in the // Authenticode specification. // PkcsCertData = (WIN_CERTIFICATE_EFI_PKCS *) WinCertificate; if (PkcsCertData->Hdr.dwLength <= sizeof (PkcsCertData->Hdr)) { break; } AuthData = PkcsCertData->CertData; AuthDataSize = PkcsCertData->Hdr.dwLength - sizeof(PkcsCertData->Hdr); } else if (WinCertificate->wCertificateType == WIN_CERT_TYPE_EFI_GUID) { // // The certificate is formatted as WIN_CERTIFICATE_UEFI_GUID which is described in UEFI Spec. // WinCertUefiGuid = (WIN_CERTIFICATE_UEFI_GUID *) WinCertificate; if (WinCertUefiGuid->Hdr.dwLength <= OFFSET_OF(WIN_CERTIFICATE_UEFI_GUID, CertData)) { break; } if (!CompareGuid (&WinCertUefiGuid->CertType, &gEfiCertPkcs7Guid)) { continue; } AuthData = WinCertUefiGuid->CertData; AuthDataSize = WinCertUefiGuid->Hdr.dwLength - OFFSET_OF(WIN_CERTIFICATE_UEFI_GUID, CertData); } else { if (WinCertificate->dwLength < sizeof (WIN_CERTIFICATE)) { break; } continue; } Status = HashPeImageByType (AuthData, AuthDataSize); if (EFI_ERROR (Status)) { continue; } // // Check the digital signature against the revoked certificate in forbidden database (dbx). // if (IsForbiddenByDbx (AuthData, AuthDataSize)) { Action = EFI_IMAGE_EXECUTION_AUTH_SIG_FAILED; VerifyStatus = EFI_ACCESS_DENIED; break; } // // Check the digital signature against the valid certificate in allowed database (db). // if (EFI_ERROR (VerifyStatus)) { if (IsAllowedByDb (AuthData, AuthDataSize)) { VerifyStatus = EFI_SUCCESS; } } // // Check the image's hash value. // if (IsSignatureFoundInDatabase (EFI_IMAGE_SECURITY_DATABASE1, mImageDigest, &mCertType, mImageDigestSize)) { Action = EFI_IMAGE_EXECUTION_AUTH_SIG_FOUND; DEBUG ((DEBUG_INFO, "DxeImageVerificationLib: Image is signed but %s hash of image is found in DBX.\n", mHashTypeStr)); VerifyStatus = EFI_ACCESS_DENIED; break; } else if (EFI_ERROR (VerifyStatus)) { if (IsSignatureFoundInDatabase (EFI_IMAGE_SECURITY_DATABASE, mImageDigest, &mCertType, mImageDigestSize)) { VerifyStatus = EFI_SUCCESS; } else { DEBUG ((DEBUG_INFO, "DxeImageVerificationLib: Image is signed but signature is not allowed by DB and %s hash of image is not found in DB/DBX.\n", mHashTypeStr)); } } } if (OffSet != (SecDataDir->VirtualAddress + SecDataDir->Size)) { // // The Size in Certificate Table or the attribute certificate table is corrupted. // VerifyStatus = EFI_ACCESS_DENIED; } if (!EFI_ERROR (VerifyStatus)) { return EFI_SUCCESS; } else { Status = EFI_ACCESS_DENIED; if (Action == EFI_IMAGE_EXECUTION_AUTH_SIG_FAILED || Action == EFI_IMAGE_EXECUTION_AUTH_SIG_FOUND) { // // Get image hash value as signature of executable. // SignatureListSize = sizeof (EFI_SIGNATURE_LIST) + sizeof (EFI_SIGNATURE_DATA) - 1 + mImageDigestSize; SignatureList = (EFI_SIGNATURE_LIST *) AllocateZeroPool (SignatureListSize); if (SignatureList == NULL) { Status = EFI_OUT_OF_RESOURCES; goto Done; } SignatureList->SignatureHeaderSize = 0; SignatureList->SignatureListSize = (UINT32) SignatureListSize; SignatureList->SignatureSize = (UINT32) (sizeof (EFI_SIGNATURE_DATA) - 1 + mImageDigestSize); CopyMem (&SignatureList->SignatureType, &mCertType, sizeof (EFI_GUID)); Signature = (EFI_SIGNATURE_DATA *) ((UINT8 *) SignatureList + sizeof (EFI_SIGNATURE_LIST)); CopyMem (Signature->SignatureData, mImageDigest, mImageDigestSize); } } Done: if (Status != EFI_SUCCESS) { // // Policy decides to defer or reject the image; add its information in image executable information table. // NameStr = ConvertDevicePathToText (File, FALSE, TRUE); AddImageExeInfo (Action, NameStr, File, SignatureList, SignatureListSize); if (NameStr != NULL) { DEBUG((EFI_D_INFO, "The image doesn't pass verification: %s\n", NameStr)); FreePool(NameStr); } Status = EFI_SECURITY_VIOLATION; } if (SignatureList != NULL) { FreePool (SignatureList); } return Status; } /** On Ready To Boot Services Event notification handler. Add the image execution information table if it is not in system configuration table. @param[in] Event Event whose notification function is being invoked @param[in] Context Pointer to the notification function's context **/ VOID EFIAPI OnReadyToBoot ( IN EFI_EVENT Event, IN VOID *Context ) { EFI_IMAGE_EXECUTION_INFO_TABLE *ImageExeInfoTable; UINTN ImageExeInfoTableSize; EfiGetSystemConfigurationTable (&gEfiImageSecurityDatabaseGuid, (VOID **) &ImageExeInfoTable); if (ImageExeInfoTable != NULL) { return; } ImageExeInfoTableSize = sizeof (EFI_IMAGE_EXECUTION_INFO_TABLE); ImageExeInfoTable = (EFI_IMAGE_EXECUTION_INFO_TABLE *) AllocateRuntimePool (ImageExeInfoTableSize); if (ImageExeInfoTable == NULL) { return ; } ImageExeInfoTable->NumberOfImages = 0; gBS->InstallConfigurationTable (&gEfiImageSecurityDatabaseGuid, (VOID *) ImageExeInfoTable); } /** Register security measurement handler. @param ImageHandle ImageHandle of the loaded driver. @param SystemTable Pointer to the EFI System Table. @retval EFI_SUCCESS The handlers were registered successfully. **/ EFI_STATUS EFIAPI DxeImageVerificationLibConstructor ( IN EFI_HANDLE ImageHandle, IN EFI_SYSTEM_TABLE *SystemTable ) { EFI_EVENT Event; // // Register the event to publish the image execution table. // EfiCreateEventReadyToBootEx ( TPL_CALLBACK, OnReadyToBoot, NULL, &Event ); return RegisterSecurity2Handler ( DxeImageVerificationHandler, EFI_AUTH_OPERATION_VERIFY_IMAGE | EFI_AUTH_OPERATION_IMAGE_REQUIRED ); }
536631.c
/* * mem usage plugin to fbpanel * * Licence: GPLv2 * * bercik-rrp@users.sf.net */ #include "../chart/chart.h" #include <stdlib.h> #include <string.h> //#define DEBUGPRN #include "dbg.h" #define CHECK_PERIOD 2 /* second */ typedef struct { chart_priv chart; int timer; gulong max; gchar *colors[2]; } mem2_priv; static chart_class *k; static void mem2_destructor(plugin_instance *p); typedef struct { char *name; gulong val; int valid; } mem_type_t; #if defined __linux__ #undef MT_ADD #define MT_ADD(x) MT_ ## x, enum { #include "../mem/mt.h" MT_NUM }; #undef MT_ADD #define MT_ADD(x) { #x, 0, 0 }, mem_type_t mt2[] = { #include "../mem/mt.h" }; static gboolean mt_match(char *buf, mem_type_t *m) { gulong val; int len; len = strlen(m->name); if (strncmp(buf, m->name, len)) return FALSE; if (sscanf(buf + len + 1, "%lu", &val) != 1) return FALSE; m->val = val; m->valid = 1; DBG("%s: %lu\n", m->name, val); return TRUE; } static int mem_usage(mem2_priv *c) { FILE *fp; char buf[160]; long unsigned int total[2]; float total_r[2]; int i; fp = fopen("/proc/meminfo", "r"); if (!fp) RET(FALSE);; for (i = 0; i < MT_NUM; i++) { mt2[i].valid = 0; mt2[i].val = 0; } while ((fgets(buf, sizeof(buf), fp)) != NULL) { for (i = 0; i < MT_NUM; i++) { if (!mt2[i].valid && mt_match(buf, mt2 + i)) break; } } fclose(fp); total[0] = (float)(mt2[MT_MemTotal].val -(mt2[MT_MemFree].val + mt2[MT_Buffers].val + mt2[MT_Cached].val + mt2[MT_Slab].val)); total[1] = (float)(mt2[MT_SwapTotal].val - mt2[MT_SwapFree].val); total_r[0] = (float)total[0] / mt2[MT_MemTotal].val; total_r[1] = (float)total[1] / mt2[MT_SwapTotal].val; g_snprintf(buf, sizeof(buf), "<b>Mem:</b> %d%%, %lu MB of %lu MB\n" "<b>Swap:</b> %d%%, %lu MB of %lu MB", (int)(total_r[0] * 100), total[0] >> 10, mt2[MT_MemTotal].val >> 10, (int)(total_r[1] * 100), total[1] >> 10, mt2[MT_SwapTotal].val >> 10); k->add_tick(&c->chart, total_r); gtk_widget_set_tooltip_markup(((plugin_instance *)c)->pwid, buf); RET(TRUE); } #else static int mem_usage() { } #endif static int mem2_constructor(plugin_instance *p) { mem2_priv *c; if (!(k = class_get("chart"))) RET(0); if (!PLUGIN_CLASS(k)->constructor(p)) RET(0); c = (mem2_priv *) p; c->colors[0] = "red"; c->colors[1] = NULL; XCG(p->xc, "MemColor", &c->colors[0], str); XCG(p->xc, "SwapColor", &c->colors[1], str); if (c->colors[1] == NULL) { k->set_rows(&c->chart, 1, c->colors); } else { k->set_rows(&c->chart, 2, c->colors); } gtk_widget_set_tooltip_markup(((plugin_instance *)c)->pwid, "<b>Memory</b>"); mem_usage(c); c->timer = g_timeout_add(CHECK_PERIOD * 1000, (GSourceFunc) mem_usage, (gpointer) c); RET(1); } static void mem2_destructor(plugin_instance *p) { mem2_priv *c = (mem2_priv *) p; ENTER; if (c->timer) g_source_remove(c->timer); PLUGIN_CLASS(k)->destructor(p); class_put("chart"); RET(); } static plugin_class class = { .fname = NULL, .count = 0, .type = "mem2", .name = "Chart Memory Monitor", .version = "1.0", .description = "Show memory usage as chart", .priv_size = sizeof(mem2_priv), .constructor = mem2_constructor, .destructor = mem2_destructor, }; static plugin_class *class_ptr = (plugin_class *) &class;
317609.c
//--------------------------------------------------------------------------------- // // Little Color Management System // Copyright (c) 1998-2011 Marti Maria Saguer // // 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 "lcms2_internal.h" //---------------------------------------------------------------------------------- // Optimization for 8 bits, Shaper-CLUT (3 inputs only) typedef struct { cmsContext ContextID; const cmsInterpParams* p; // Tetrahedrical interpolation parameters. This is a not-owned pointer. cmsUInt16Number rx[256], ry[256], rz[256]; cmsUInt32Number X0[256], Y0[256], Z0[256]; // Precomputed nodes and offsets for 8-bit input data } Prelin8Data; // Generic optimization for 16 bits Shaper-CLUT-Shaper (any inputs) typedef struct { cmsContext ContextID; // Number of channels int nInputs; int nOutputs; _cmsInterpFn16 EvalCurveIn16[MAX_INPUT_DIMENSIONS]; // The maximum number of input channels is known in advance cmsInterpParams* ParamsCurveIn16[MAX_INPUT_DIMENSIONS]; _cmsInterpFn16 EvalCLUT; // The evaluator for 3D grid const cmsInterpParams* CLUTparams; // (not-owned pointer) _cmsInterpFn16* EvalCurveOut16; // Points to an array of curve evaluators in 16 bits (not-owned pointer) cmsInterpParams** ParamsCurveOut16; // Points to an array of references to interpolation params (not-owned pointer) } Prelin16Data; // Optimization for matrix-shaper in 8 bits. Numbers are operated in n.14 signed, tables are stored in 1.14 fixed typedef cmsInt32Number cmsS1Fixed14Number; // Note that this may hold more than 16 bits! #define DOUBLE_TO_1FIXED14(x) ((cmsS1Fixed14Number) floor((x) * 16384.0 + 0.5)) typedef struct { cmsContext ContextID; cmsS1Fixed14Number Shaper1R[256]; // from 0..255 to 1.14 (0.0...1.0) cmsS1Fixed14Number Shaper1G[256]; cmsS1Fixed14Number Shaper1B[256]; cmsS1Fixed14Number Mat[3][3]; // n.14 to n.14 (needs a saturation after that) cmsS1Fixed14Number Off[3]; cmsUInt16Number Shaper2R[16385]; // 1.14 to 0..255 cmsUInt16Number Shaper2G[16385]; cmsUInt16Number Shaper2B[16385]; } MatShaper8Data; // Curves, optimization is shared between 8 and 16 bits typedef struct { cmsContext ContextID; int nCurves; // Number of curves int nElements; // Elements in curves cmsUInt16Number** Curves; // Points to a dynamically allocated array } Curves16Data; // Simple optimizations ---------------------------------------------------------------------------------------------------------- // Remove an element in linked chain static void _RemoveElement(cmsStage** head) { cmsStage* mpe = *head; cmsStage* next = mpe ->Next; *head = next; cmsStageFree(mpe); } // Remove all identities in chain. Note that pt actually is a double pointer to the element that holds the pointer. static cmsBool _Remove1Op(cmsPipeline* Lut, cmsStageSignature UnaryOp) { cmsStage** pt = &Lut ->Elements; cmsBool AnyOpt = FALSE; while (*pt != NULL) { if ((*pt) ->Implements == UnaryOp) { _RemoveElement(pt); AnyOpt = TRUE; } else pt = &((*pt) -> Next); } return AnyOpt; } // Same, but only if two adjacent elements are found static cmsBool _Remove2Op(cmsPipeline* Lut, cmsStageSignature Op1, cmsStageSignature Op2) { cmsStage** pt1; cmsStage** pt2; cmsBool AnyOpt = FALSE; pt1 = &Lut ->Elements; if (*pt1 == NULL) return AnyOpt; while (*pt1 != NULL) { pt2 = &((*pt1) -> Next); if (*pt2 == NULL) return AnyOpt; if ((*pt1) ->Implements == Op1 && (*pt2) ->Implements == Op2) { _RemoveElement(pt2); _RemoveElement(pt1); AnyOpt = TRUE; } else pt1 = &((*pt1) -> Next); } return AnyOpt; } // Preoptimize just gets rif of no-ops coming paired. Conversion from v2 to v4 followed // by a v4 to v2 and vice-versa. The elements are then discarded. static cmsBool PreOptimize(cmsPipeline* Lut) { cmsBool AnyOpt = FALSE, Opt; do { Opt = FALSE; // Remove all identities Opt |= _Remove1Op(Lut, cmsSigIdentityElemType); // Remove XYZ2Lab followed by Lab2XYZ Opt |= _Remove2Op(Lut, cmsSigXYZ2LabElemType, cmsSigLab2XYZElemType); // Remove Lab2XYZ followed by XYZ2Lab Opt |= _Remove2Op(Lut, cmsSigLab2XYZElemType, cmsSigXYZ2LabElemType); // Remove V4 to V2 followed by V2 to V4 Opt |= _Remove2Op(Lut, cmsSigLabV4toV2, cmsSigLabV2toV4); // Remove V2 to V4 followed by V4 to V2 Opt |= _Remove2Op(Lut, cmsSigLabV2toV4, cmsSigLabV4toV2); // Remove float pcs Lab conversions Opt |= _Remove2Op(Lut, cmsSigLab2FloatPCS, cmsSigFloatPCS2Lab); // Remove float pcs Lab conversions Opt |= _Remove2Op(Lut, cmsSigXYZ2FloatPCS, cmsSigFloatPCS2XYZ); if (Opt) AnyOpt = TRUE; } while (Opt); return AnyOpt; } static void Eval16nop1D(register const cmsUInt16Number Input[], register cmsUInt16Number Output[], register const struct _cms_interp_struc* p) { Output[0] = Input[0]; cmsUNUSED_PARAMETER(p); } static void PrelinEval16(register const cmsUInt16Number Input[], register cmsUInt16Number Output[], register const void* D) { Prelin16Data* p16 = (Prelin16Data*) D; cmsUInt16Number StageABC[MAX_INPUT_DIMENSIONS]; cmsUInt16Number StageDEF[cmsMAXCHANNELS]; int i; for (i=0; i < p16 ->nInputs; i++) { p16 ->EvalCurveIn16[i](&Input[i], &StageABC[i], p16 ->ParamsCurveIn16[i]); } p16 ->EvalCLUT(StageABC, StageDEF, p16 ->CLUTparams); for (i=0; i < p16 ->nOutputs; i++) { p16 ->EvalCurveOut16[i](&StageDEF[i], &Output[i], p16 ->ParamsCurveOut16[i]); } } static void PrelinOpt16free(cmsContext ContextID, void* ptr) { Prelin16Data* p16 = (Prelin16Data*) ptr; _cmsFree(ContextID, p16 ->EvalCurveOut16); _cmsFree(ContextID, p16 ->ParamsCurveOut16); _cmsFree(ContextID, p16); } static void* Prelin16dup(cmsContext ContextID, const void* ptr) { Prelin16Data* p16 = (Prelin16Data*) ptr; Prelin16Data* Duped = _cmsDupMem(ContextID, p16, sizeof(Prelin16Data)); if (Duped == NULL) return NULL; Duped ->EvalCurveOut16 = (_cmsInterpFn16*)_cmsDupMem(ContextID, p16 ->EvalCurveOut16, p16 ->nOutputs * sizeof(_cmsInterpFn16)); Duped ->ParamsCurveOut16 = (cmsInterpParams**)_cmsDupMem(ContextID, p16 ->ParamsCurveOut16, p16 ->nOutputs * sizeof(cmsInterpParams* )); return Duped; } static Prelin16Data* PrelinOpt16alloc(cmsContext ContextID, const cmsInterpParams* ColorMap, int nInputs, cmsToneCurve** In, int nOutputs, cmsToneCurve** Out ) { int i; Prelin16Data* p16 = _cmsMallocZero(ContextID, sizeof(Prelin16Data)); if (p16 == NULL) return NULL; p16 ->nInputs = nInputs; p16 -> nOutputs = nOutputs; for (i=0; i < nInputs; i++) { if (In == NULL) { p16 -> ParamsCurveIn16[i] = NULL; p16 -> EvalCurveIn16[i] = Eval16nop1D; } else { p16 -> ParamsCurveIn16[i] = In[i] ->InterpParams; p16 -> EvalCurveIn16[i] = p16 ->ParamsCurveIn16[i]->Interpolation.Lerp16; } } p16 ->CLUTparams = ColorMap; p16 ->EvalCLUT = ColorMap ->Interpolation.Lerp16; p16 -> EvalCurveOut16 = (_cmsInterpFn16*) _cmsCalloc(ContextID, nOutputs, sizeof(_cmsInterpFn16)); p16 -> ParamsCurveOut16 = (cmsInterpParams**) _cmsCalloc(ContextID, nOutputs, sizeof(cmsInterpParams* )); for (i=0; i < nOutputs; i++) { if (Out == NULL) { p16 ->ParamsCurveOut16[i] = NULL; p16 -> EvalCurveOut16[i] = Eval16nop1D; } else { p16 ->ParamsCurveOut16[i] = Out[i] ->InterpParams; p16 -> EvalCurveOut16[i] = p16 ->ParamsCurveOut16[i]->Interpolation.Lerp16; } } return p16; } // Resampling --------------------------------------------------------------------------------- #define PRELINEARIZATION_POINTS 4096 // Sampler implemented by another LUT. This is a clean way to precalculate the devicelink 3D CLUT for // almost any transform. We use floating point precision and then convert from floating point to 16 bits. static int XFormSampler16(register const cmsUInt16Number In[], register cmsUInt16Number Out[], register void* Cargo) { cmsPipeline* Lut = (cmsPipeline*) Cargo; cmsFloat32Number InFloat[cmsMAXCHANNELS], OutFloat[cmsMAXCHANNELS]; cmsUInt32Number i; _cmsAssert(Lut -> InputChannels < cmsMAXCHANNELS); _cmsAssert(Lut -> OutputChannels < cmsMAXCHANNELS); // From 16 bit to floating point for (i=0; i < Lut ->InputChannels; i++) InFloat[i] = (cmsFloat32Number) (In[i] / 65535.0); // Evaluate in floating point cmsPipelineEvalFloat(InFloat, OutFloat, Lut); // Back to 16 bits representation for (i=0; i < Lut ->OutputChannels; i++) Out[i] = _cmsQuickSaturateWord(OutFloat[i] * 65535.0); // Always succeed return TRUE; } // Try to see if the curves of a given MPE are linear static cmsBool AllCurvesAreLinear(cmsStage* mpe) { cmsToneCurve** Curves; cmsUInt32Number i, n; Curves = _cmsStageGetPtrToCurveSet(mpe); if (Curves == NULL) return FALSE; n = cmsStageOutputChannels(mpe); for (i=0; i < n; i++) { if (!cmsIsToneCurveLinear(Curves[i])) return FALSE; } return TRUE; } // This function replaces a specific node placed in "At" by the "Value" numbers. Its purpose // is to fix scum dot on broken profiles/transforms. Works on 1, 3 and 4 channels static cmsBool PatchLUT(cmsStage* CLUT, cmsUInt16Number At[], cmsUInt16Number Value[], int nChannelsOut, int nChannelsIn) { _cmsStageCLutData* Grid = (_cmsStageCLutData*) CLUT ->Data; cmsInterpParams* p16 = Grid ->Params; cmsFloat64Number px, py, pz, pw; int x0, y0, z0, w0; int i, index; if (CLUT -> Type != cmsSigCLutElemType) { cmsSignalError(CLUT->ContextID, cmsERROR_INTERNAL, "(internal) Attempt to PatchLUT on non-lut stage"); return FALSE; } if (nChannelsIn != 1 && nChannelsIn != 3 && nChannelsIn != 4) { cmsSignalError(CLUT->ContextID, cmsERROR_INTERNAL, "(internal) %d Channels are not supported on PatchLUT", nChannelsIn); return FALSE; } if (nChannelsIn == 4) { px = ((cmsFloat64Number) At[0] * (p16->Domain[0])) / 65535.0; py = ((cmsFloat64Number) At[1] * (p16->Domain[1])) / 65535.0; pz = ((cmsFloat64Number) At[2] * (p16->Domain[2])) / 65535.0; pw = ((cmsFloat64Number) At[3] * (p16->Domain[3])) / 65535.0; x0 = (int) floor(px); y0 = (int) floor(py); z0 = (int) floor(pz); w0 = (int) floor(pw); if (((px - x0) != 0) || ((py - y0) != 0) || ((pz - z0) != 0) || ((pw - w0) != 0)) return FALSE; // Not on exact node index = p16 -> opta[3] * x0 + p16 -> opta[2] * y0 + p16 -> opta[1] * z0 + p16 -> opta[0] * w0; } else if (nChannelsIn == 3) { px = ((cmsFloat64Number) At[0] * (p16->Domain[0])) / 65535.0; py = ((cmsFloat64Number) At[1] * (p16->Domain[1])) / 65535.0; pz = ((cmsFloat64Number) At[2] * (p16->Domain[2])) / 65535.0; x0 = (int) floor(px); y0 = (int) floor(py); z0 = (int) floor(pz); if (((px - x0) != 0) || ((py - y0) != 0) || ((pz - z0) != 0)) return FALSE; // Not on exact node index = p16 -> opta[2] * x0 + p16 -> opta[1] * y0 + p16 -> opta[0] * z0; } else if (nChannelsIn == 1) { px = ((cmsFloat64Number) At[0] * (p16->Domain[0])) / 65535.0; x0 = (int) floor(px); if (((px - x0) != 0)) return FALSE; // Not on exact node index = p16 -> opta[0] * x0; } else { cmsSignalError(CLUT->ContextID, cmsERROR_INTERNAL, "(internal) %d Channels are not supported on PatchLUT", nChannelsIn); return FALSE; } for (i=0; i < nChannelsOut; i++) Grid -> Tab.T[index + i] = Value[i]; return TRUE; } // Auxiliar, to see if two values are equal or very different static cmsBool WhitesAreEqual(int n, cmsUInt16Number White1[], cmsUInt16Number White2[] ) { int i; for (i=0; i < n; i++) { if (abs(White1[i] - White2[i]) > 0xf000) return TRUE; // Values are so extremly different that the fixup should be avoided if (White1[i] != White2[i]) return FALSE; } return TRUE; } // Locate the node for the white point and fix it to pure white in order to avoid scum dot. static cmsBool FixWhiteMisalignment(cmsPipeline* Lut, cmsColorSpaceSignature EntryColorSpace, cmsColorSpaceSignature ExitColorSpace) { cmsUInt16Number *WhitePointIn, *WhitePointOut; cmsUInt16Number WhiteIn[cmsMAXCHANNELS], WhiteOut[cmsMAXCHANNELS], ObtainedOut[cmsMAXCHANNELS]; cmsUInt32Number i, nOuts, nIns; cmsStage *PreLin = NULL, *CLUT = NULL, *PostLin = NULL; if (!_cmsEndPointsBySpace(EntryColorSpace, &WhitePointIn, NULL, &nIns)) return FALSE; if (!_cmsEndPointsBySpace(ExitColorSpace, &WhitePointOut, NULL, &nOuts)) return FALSE; // It needs to be fixed? if (Lut ->InputChannels != nIns) return FALSE; if (Lut ->OutputChannels != nOuts) return FALSE; cmsPipelineEval16(WhitePointIn, ObtainedOut, Lut); if (WhitesAreEqual(nOuts, WhitePointOut, ObtainedOut)) return TRUE; // whites already match // Check if the LUT comes as Prelin, CLUT or Postlin. We allow all combinations if (!cmsPipelineCheckAndRetreiveStages(Lut, 3, cmsSigCurveSetElemType, cmsSigCLutElemType, cmsSigCurveSetElemType, &PreLin, &CLUT, &PostLin)) if (!cmsPipelineCheckAndRetreiveStages(Lut, 2, cmsSigCurveSetElemType, cmsSigCLutElemType, &PreLin, &CLUT)) if (!cmsPipelineCheckAndRetreiveStages(Lut, 2, cmsSigCLutElemType, cmsSigCurveSetElemType, &CLUT, &PostLin)) if (!cmsPipelineCheckAndRetreiveStages(Lut, 1, cmsSigCLutElemType, &CLUT)) return FALSE; // We need to interpolate white points of both, pre and post curves if (PreLin) { cmsToneCurve** Curves = _cmsStageGetPtrToCurveSet(PreLin); for (i=0; i < nIns; i++) { WhiteIn[i] = cmsEvalToneCurve16(Curves[i], WhitePointIn[i]); } } else { for (i=0; i < nIns; i++) WhiteIn[i] = WhitePointIn[i]; } // If any post-linearization, we need to find how is represented white before the curve, do // a reverse interpolation in this case. if (PostLin) { cmsToneCurve** Curves = _cmsStageGetPtrToCurveSet(PostLin); for (i=0; i < nOuts; i++) { cmsToneCurve* InversePostLin = cmsReverseToneCurve(Curves[i]); if (InversePostLin == NULL) { WhiteOut[i] = WhitePointOut[i]; } else { WhiteOut[i] = cmsEvalToneCurve16(InversePostLin, WhitePointOut[i]); cmsFreeToneCurve(InversePostLin); } } } else { for (i=0; i < nOuts; i++) WhiteOut[i] = WhitePointOut[i]; } // Ok, proceed with patching. May fail and we don't care if it fails PatchLUT(CLUT, WhiteIn, WhiteOut, nOuts, nIns); return TRUE; } // ----------------------------------------------------------------------------------------------------------------------------------------------- // This function creates simple LUT from complex ones. The generated LUT has an optional set of // prelinearization curves, a CLUT of nGridPoints and optional postlinearization tables. // These curves have to exist in the original LUT in order to be used in the simplified output. // Caller may also use the flags to allow this feature. // LUTS with all curves will be simplified to a single curve. Parametric curves are lost. // This function should be used on 16-bits LUTS only, as floating point losses precision when simplified // ----------------------------------------------------------------------------------------------------------------------------------------------- static cmsBool OptimizeByResampling(cmsPipeline** Lut, cmsUInt32Number Intent, cmsUInt32Number* InputFormat, cmsUInt32Number* OutputFormat, cmsUInt32Number* dwFlags) { cmsPipeline* Src = NULL; cmsPipeline* Dest = NULL; cmsStage* mpe; cmsStage* CLUT; cmsStage *KeepPreLin = NULL, *KeepPostLin = NULL; int nGridPoints; cmsColorSpaceSignature ColorSpace, OutputColorSpace; cmsStage *NewPreLin = NULL; cmsStage *NewPostLin = NULL; _cmsStageCLutData* DataCLUT; cmsToneCurve** DataSetIn; cmsToneCurve** DataSetOut; Prelin16Data* p16; // This is a loosy optimization! does not apply in floating-point cases if (_cmsFormatterIsFloat(*InputFormat) || _cmsFormatterIsFloat(*OutputFormat)) return FALSE; ColorSpace = _cmsICCcolorSpace(T_COLORSPACE(*InputFormat)); OutputColorSpace = _cmsICCcolorSpace(T_COLORSPACE(*OutputFormat)); nGridPoints = _cmsReasonableGridpointsByColorspace(ColorSpace, *dwFlags); // For empty LUTs, 2 points are enough if (cmsPipelineStageCount(*Lut) == 0) nGridPoints = 2; Src = *Lut; // Named color pipelines cannot be optimized either for (mpe = cmsPipelineGetPtrToFirstStage(Src); mpe != NULL; mpe = cmsStageNext(mpe)) { if (cmsStageType(mpe) == cmsSigNamedColorElemType) return FALSE; } // Allocate an empty LUT Dest = cmsPipelineAlloc(Src ->ContextID, Src ->InputChannels, Src ->OutputChannels); if (!Dest) return FALSE; // Prelinearization tables are kept unless indicated by flags if (*dwFlags & cmsFLAGS_CLUT_PRE_LINEARIZATION) { // Get a pointer to the prelinearization element cmsStage* PreLin = cmsPipelineGetPtrToFirstStage(Src); // Check if suitable if (PreLin ->Type == cmsSigCurveSetElemType) { // Maybe this is a linear tram, so we can avoid the whole stuff if (!AllCurvesAreLinear(PreLin)) { // All seems ok, proceed. NewPreLin = cmsStageDup(PreLin); if(!cmsPipelineInsertStage(Dest, cmsAT_BEGIN, NewPreLin)) goto Error; // Remove prelinearization. Since we have duplicated the curve // in destination LUT, the sampling shoud be applied after this stage. cmsPipelineUnlinkStage(Src, cmsAT_BEGIN, &KeepPreLin); } } } // Allocate the CLUT CLUT = cmsStageAllocCLut16bit(Src ->ContextID, nGridPoints, Src ->InputChannels, Src->OutputChannels, NULL); if (CLUT == NULL) goto Error; // Add the CLUT to the destination LUT if (!cmsPipelineInsertStage(Dest, cmsAT_END, CLUT)) { goto Error; } // Postlinearization tables are kept unless indicated by flags if (*dwFlags & cmsFLAGS_CLUT_POST_LINEARIZATION) { // Get a pointer to the postlinearization if present cmsStage* PostLin = cmsPipelineGetPtrToLastStage(Src); // Check if suitable if (cmsStageType(PostLin) == cmsSigCurveSetElemType) { // Maybe this is a linear tram, so we can avoid the whole stuff if (!AllCurvesAreLinear(PostLin)) { // All seems ok, proceed. NewPostLin = cmsStageDup(PostLin); if (!cmsPipelineInsertStage(Dest, cmsAT_END, NewPostLin)) goto Error; // In destination LUT, the sampling shoud be applied after this stage. cmsPipelineUnlinkStage(Src, cmsAT_END, &KeepPostLin); } } } // Now its time to do the sampling. We have to ignore pre/post linearization // The source LUT whithout pre/post curves is passed as parameter. if (!cmsStageSampleCLut16bit(CLUT, XFormSampler16, (void*) Src, 0)) { Error: // Ops, something went wrong, Restore stages if (KeepPreLin != NULL) { if (!cmsPipelineInsertStage(Src, cmsAT_BEGIN, KeepPreLin)) { _cmsAssert(0); // This never happens } } if (KeepPostLin != NULL) { if (!cmsPipelineInsertStage(Src, cmsAT_END, KeepPostLin)) { _cmsAssert(0); // This never happens } } cmsPipelineFree(Dest); return FALSE; } // Done. if (KeepPreLin != NULL) cmsStageFree(KeepPreLin); if (KeepPostLin != NULL) cmsStageFree(KeepPostLin); cmsPipelineFree(Src); DataCLUT = (_cmsStageCLutData*) CLUT ->Data; if (NewPreLin == NULL) DataSetIn = NULL; else DataSetIn = ((_cmsStageToneCurvesData*) NewPreLin ->Data) ->TheCurves; if (NewPostLin == NULL) DataSetOut = NULL; else DataSetOut = ((_cmsStageToneCurvesData*) NewPostLin ->Data) ->TheCurves; if (DataSetIn == NULL && DataSetOut == NULL) { _cmsPipelineSetOptimizationParameters(Dest, (_cmsOPTeval16Fn) DataCLUT->Params->Interpolation.Lerp16, DataCLUT->Params, NULL, NULL); } else { p16 = PrelinOpt16alloc(Dest ->ContextID, DataCLUT ->Params, Dest ->InputChannels, DataSetIn, Dest ->OutputChannels, DataSetOut); _cmsPipelineSetOptimizationParameters(Dest, PrelinEval16, (void*) p16, PrelinOpt16free, Prelin16dup); } // Don't fix white on absolute colorimetric if (Intent == INTENT_ABSOLUTE_COLORIMETRIC) *dwFlags |= cmsFLAGS_NOWHITEONWHITEFIXUP; if (!(*dwFlags & cmsFLAGS_NOWHITEONWHITEFIXUP)) { FixWhiteMisalignment(Dest, ColorSpace, OutputColorSpace); } *Lut = Dest; return TRUE; cmsUNUSED_PARAMETER(Intent); } // ----------------------------------------------------------------------------------------------------------------------------------------------- // Fixes the gamma balancing of transform. This is described in my paper "Prelinearization Stages on // Color-Management Application-Specific Integrated Circuits (ASICs)" presented at NIP24. It only works // for RGB transforms. See the paper for more details // ----------------------------------------------------------------------------------------------------------------------------------------------- // Normalize endpoints by slope limiting max and min. This assures endpoints as well. // Descending curves are handled as well. static void SlopeLimiting(cmsToneCurve* g) { int BeginVal, EndVal; int AtBegin = (int) floor((cmsFloat64Number) g ->nEntries * 0.02 + 0.5); // Cutoff at 2% int AtEnd = g ->nEntries - AtBegin - 1; // And 98% cmsFloat64Number Val, Slope, beta; int i; if (cmsIsToneCurveDescending(g)) { BeginVal = 0xffff; EndVal = 0; } else { BeginVal = 0; EndVal = 0xffff; } // Compute slope and offset for begin of curve Val = g ->Table16[AtBegin]; Slope = (Val - BeginVal) / AtBegin; beta = Val - Slope * AtBegin; for (i=0; i < AtBegin; i++) g ->Table16[i] = _cmsQuickSaturateWord(i * Slope + beta); // Compute slope and offset for the end Val = g ->Table16[AtEnd]; Slope = (EndVal - Val) / AtBegin; // AtBegin holds the X interval, which is same in both cases beta = Val - Slope * AtEnd; for (i = AtEnd; i < (int) g ->nEntries; i++) g ->Table16[i] = _cmsQuickSaturateWord(i * Slope + beta); } // Precomputes tables for 8-bit on input devicelink. static Prelin8Data* PrelinOpt8alloc(cmsContext ContextID, const cmsInterpParams* p, cmsToneCurve* G[3]) { int i; cmsUInt16Number Input[3]; cmsS15Fixed16Number v1, v2, v3; Prelin8Data* p8; p8 = (Prelin8Data*)_cmsMallocZero(ContextID, sizeof(Prelin8Data)); if (p8 == NULL) return NULL; // Since this only works for 8 bit input, values comes always as x * 257, // we can safely take msb byte (x << 8 + x) for (i=0; i < 256; i++) { if (G != NULL) { // Get 16-bit representation Input[0] = cmsEvalToneCurve16(G[0], FROM_8_TO_16(i)); Input[1] = cmsEvalToneCurve16(G[1], FROM_8_TO_16(i)); Input[2] = cmsEvalToneCurve16(G[2], FROM_8_TO_16(i)); } else { Input[0] = FROM_8_TO_16(i); Input[1] = FROM_8_TO_16(i); Input[2] = FROM_8_TO_16(i); } // Move to 0..1.0 in fixed domain v1 = _cmsToFixedDomain(Input[0] * p -> Domain[0]); v2 = _cmsToFixedDomain(Input[1] * p -> Domain[1]); v3 = _cmsToFixedDomain(Input[2] * p -> Domain[2]); // Store the precalculated table of nodes p8 ->X0[i] = (p->opta[2] * FIXED_TO_INT(v1)); p8 ->Y0[i] = (p->opta[1] * FIXED_TO_INT(v2)); p8 ->Z0[i] = (p->opta[0] * FIXED_TO_INT(v3)); // Store the precalculated table of offsets p8 ->rx[i] = (cmsUInt16Number) FIXED_REST_TO_INT(v1); p8 ->ry[i] = (cmsUInt16Number) FIXED_REST_TO_INT(v2); p8 ->rz[i] = (cmsUInt16Number) FIXED_REST_TO_INT(v3); } p8 ->ContextID = ContextID; p8 ->p = p; return p8; } static void Prelin8free(cmsContext ContextID, void* ptr) { _cmsFree(ContextID, ptr); } static void* Prelin8dup(cmsContext ContextID, const void* ptr) { return _cmsDupMem(ContextID, ptr, sizeof(Prelin8Data)); } // A optimized interpolation for 8-bit input. #define DENS(i,j,k) (LutTable[(i)+(j)+(k)+OutChan]) static void PrelinEval8(register const cmsUInt16Number Input[], register cmsUInt16Number Output[], register const void* D) { cmsUInt8Number r, g, b; cmsS15Fixed16Number rx, ry, rz; cmsS15Fixed16Number c0, c1, c2, c3, Rest; int OutChan; register cmsS15Fixed16Number X0, X1, Y0, Y1, Z0, Z1; Prelin8Data* p8 = (Prelin8Data*) D; register const cmsInterpParams* p = p8 ->p; int TotalOut = p -> nOutputs; const cmsUInt16Number* LutTable = (const cmsUInt16Number*)p -> Table; r = Input[0] >> 8; g = Input[1] >> 8; b = Input[2] >> 8; X0 = X1 = p8->X0[r]; Y0 = Y1 = p8->Y0[g]; Z0 = Z1 = p8->Z0[b]; rx = p8 ->rx[r]; ry = p8 ->ry[g]; rz = p8 ->rz[b]; X1 = X0 + ((rx == 0) ? 0 : p ->opta[2]); Y1 = Y0 + ((ry == 0) ? 0 : p ->opta[1]); Z1 = Z0 + ((rz == 0) ? 0 : p ->opta[0]); // These are the 6 Tetrahedral for (OutChan=0; OutChan < TotalOut; OutChan++) { c0 = DENS(X0, Y0, Z0); if (rx >= ry && ry >= rz) { c1 = DENS(X1, Y0, Z0) - c0; c2 = DENS(X1, Y1, Z0) - DENS(X1, Y0, Z0); c3 = DENS(X1, Y1, Z1) - DENS(X1, Y1, Z0); } else if (rx >= rz && rz >= ry) { c1 = DENS(X1, Y0, Z0) - c0; c2 = DENS(X1, Y1, Z1) - DENS(X1, Y0, Z1); c3 = DENS(X1, Y0, Z1) - DENS(X1, Y0, Z0); } else if (rz >= rx && rx >= ry) { c1 = DENS(X1, Y0, Z1) - DENS(X0, Y0, Z1); c2 = DENS(X1, Y1, Z1) - DENS(X1, Y0, Z1); c3 = DENS(X0, Y0, Z1) - c0; } else if (ry >= rx && rx >= rz) { c1 = DENS(X1, Y1, Z0) - DENS(X0, Y1, Z0); c2 = DENS(X0, Y1, Z0) - c0; c3 = DENS(X1, Y1, Z1) - DENS(X1, Y1, Z0); } else if (ry >= rz && rz >= rx) { c1 = DENS(X1, Y1, Z1) - DENS(X0, Y1, Z1); c2 = DENS(X0, Y1, Z0) - c0; c3 = DENS(X0, Y1, Z1) - DENS(X0, Y1, Z0); } else if (rz >= ry && ry >= rx) { c1 = DENS(X1, Y1, Z1) - DENS(X0, Y1, Z1); c2 = DENS(X0, Y1, Z1) - DENS(X0, Y0, Z1); c3 = DENS(X0, Y0, Z1) - c0; } else { c1 = c2 = c3 = 0; } Rest = c1 * rx + c2 * ry + c3 * rz + 0x8001; Output[OutChan] = (cmsUInt16Number)c0 + ((Rest + (Rest>>16))>>16); } } #undef DENS // Curves that contain wide empty areas are not optimizeable static cmsBool IsDegenerated(const cmsToneCurve* g) { int i, Zeros = 0, Poles = 0; int nEntries = g ->nEntries; for (i=0; i < nEntries; i++) { if (g ->Table16[i] == 0x0000) Zeros++; if (g ->Table16[i] == 0xffff) Poles++; } if (Zeros == 1 && Poles == 1) return FALSE; // For linear tables if (Zeros > (nEntries / 4)) return TRUE; // Degenerated, mostly zeros if (Poles > (nEntries / 4)) return TRUE; // Degenerated, mostly poles return FALSE; } // -------------------------------------------------------------------------------------------------------------- // We need xput over here static cmsBool OptimizeByComputingLinearization(cmsPipeline** Lut, cmsUInt32Number Intent, cmsUInt32Number* InputFormat, cmsUInt32Number* OutputFormat, cmsUInt32Number* dwFlags) { cmsPipeline* OriginalLut; int nGridPoints; cmsToneCurve *Trans[cmsMAXCHANNELS], *TransReverse[cmsMAXCHANNELS]; cmsUInt32Number t, i; cmsFloat32Number v, In[cmsMAXCHANNELS], Out[cmsMAXCHANNELS]; cmsBool lIsSuitable, lIsLinear; cmsPipeline* OptimizedLUT = NULL, *LutPlusCurves = NULL; cmsStage* OptimizedCLUTmpe; cmsColorSpaceSignature ColorSpace, OutputColorSpace; cmsStage* OptimizedPrelinMpe; cmsStage* mpe; cmsToneCurve** OptimizedPrelinCurves; _cmsStageCLutData* OptimizedPrelinCLUT; // This is a loosy optimization! does not apply in floating-point cases if (_cmsFormatterIsFloat(*InputFormat) || _cmsFormatterIsFloat(*OutputFormat)) return FALSE; // Only on RGB if (T_COLORSPACE(*InputFormat) != PT_RGB) return FALSE; if (T_COLORSPACE(*OutputFormat) != PT_RGB) return FALSE; // On 16 bits, user has to specify the feature if (!_cmsFormatterIs8bit(*InputFormat)) { if (!(*dwFlags & cmsFLAGS_CLUT_PRE_LINEARIZATION)) return FALSE; } OriginalLut = *Lut; // Named color pipelines cannot be optimized either for (mpe = cmsPipelineGetPtrToFirstStage(OriginalLut); mpe != NULL; mpe = cmsStageNext(mpe)) { if (cmsStageType(mpe) == cmsSigNamedColorElemType) return FALSE; } ColorSpace = _cmsICCcolorSpace(T_COLORSPACE(*InputFormat)); OutputColorSpace = _cmsICCcolorSpace(T_COLORSPACE(*OutputFormat)); nGridPoints = _cmsReasonableGridpointsByColorspace(ColorSpace, *dwFlags); // Empty gamma containers memset(Trans, 0, sizeof(Trans)); memset(TransReverse, 0, sizeof(TransReverse)); for (t = 0; t < OriginalLut ->InputChannels; t++) { Trans[t] = cmsBuildTabulatedToneCurve16(OriginalLut ->ContextID, PRELINEARIZATION_POINTS, NULL); if (Trans[t] == NULL) goto Error; } // Populate the curves for (i=0; i < PRELINEARIZATION_POINTS; i++) { v = (cmsFloat32Number) ((cmsFloat64Number) i / (PRELINEARIZATION_POINTS - 1)); // Feed input with a gray ramp for (t=0; t < OriginalLut ->InputChannels; t++) In[t] = v; // Evaluate the gray value cmsPipelineEvalFloat(In, Out, OriginalLut); // Store result in curve for (t=0; t < OriginalLut ->InputChannels; t++) Trans[t] ->Table16[i] = _cmsQuickSaturateWord(Out[t] * 65535.0); } // Slope-limit the obtained curves for (t = 0; t < OriginalLut ->InputChannels; t++) SlopeLimiting(Trans[t]); // Check for validity lIsSuitable = TRUE; lIsLinear = TRUE; for (t=0; (lIsSuitable && (t < OriginalLut ->InputChannels)); t++) { // Exclude if already linear if (!cmsIsToneCurveLinear(Trans[t])) lIsLinear = FALSE; // Exclude if non-monotonic if (!cmsIsToneCurveMonotonic(Trans[t])) lIsSuitable = FALSE; if (IsDegenerated(Trans[t])) lIsSuitable = FALSE; } // If it is not suitable, just quit if (!lIsSuitable) goto Error; // Invert curves if possible for (t = 0; t < OriginalLut ->InputChannels; t++) { TransReverse[t] = cmsReverseToneCurveEx(PRELINEARIZATION_POINTS, Trans[t]); if (TransReverse[t] == NULL) goto Error; } // Now inset the reversed curves at the begin of transform LutPlusCurves = cmsPipelineDup(OriginalLut); if (LutPlusCurves == NULL) goto Error; if (!cmsPipelineInsertStage(LutPlusCurves, cmsAT_BEGIN, cmsStageAllocToneCurves(OriginalLut ->ContextID, OriginalLut ->InputChannels, TransReverse))) goto Error; // Create the result LUT OptimizedLUT = cmsPipelineAlloc(OriginalLut ->ContextID, OriginalLut ->InputChannels, OriginalLut ->OutputChannels); if (OptimizedLUT == NULL) goto Error; OptimizedPrelinMpe = cmsStageAllocToneCurves(OriginalLut ->ContextID, OriginalLut ->InputChannels, Trans); // Create and insert the curves at the beginning if (!cmsPipelineInsertStage(OptimizedLUT, cmsAT_BEGIN, OptimizedPrelinMpe)) goto Error; // Allocate the CLUT for result OptimizedCLUTmpe = cmsStageAllocCLut16bit(OriginalLut ->ContextID, nGridPoints, OriginalLut ->InputChannels, OriginalLut ->OutputChannels, NULL); // Add the CLUT to the destination LUT if (!cmsPipelineInsertStage(OptimizedLUT, cmsAT_END, OptimizedCLUTmpe)) goto Error; // Resample the LUT if (!cmsStageSampleCLut16bit(OptimizedCLUTmpe, XFormSampler16, (void*) LutPlusCurves, 0)) goto Error; // Free resources for (t = 0; t < OriginalLut ->InputChannels; t++) { if (Trans[t]) cmsFreeToneCurve(Trans[t]); if (TransReverse[t]) cmsFreeToneCurve(TransReverse[t]); } cmsPipelineFree(LutPlusCurves); OptimizedPrelinCurves = _cmsStageGetPtrToCurveSet(OptimizedPrelinMpe); OptimizedPrelinCLUT = (_cmsStageCLutData*) OptimizedCLUTmpe ->Data; // Set the evaluator if 8-bit if (_cmsFormatterIs8bit(*InputFormat)) { Prelin8Data* p8 = PrelinOpt8alloc(OptimizedLUT ->ContextID, OptimizedPrelinCLUT ->Params, OptimizedPrelinCurves); if (p8 == NULL) return FALSE; _cmsPipelineSetOptimizationParameters(OptimizedLUT, PrelinEval8, (void*) p8, Prelin8free, Prelin8dup); } else { Prelin16Data* p16 = PrelinOpt16alloc(OptimizedLUT ->ContextID, OptimizedPrelinCLUT ->Params, 3, OptimizedPrelinCurves, 3, NULL); if (p16 == NULL) return FALSE; _cmsPipelineSetOptimizationParameters(OptimizedLUT, PrelinEval16, (void*) p16, PrelinOpt16free, Prelin16dup); } // Don't fix white on absolute colorimetric if (Intent == INTENT_ABSOLUTE_COLORIMETRIC) *dwFlags |= cmsFLAGS_NOWHITEONWHITEFIXUP; if (!(*dwFlags & cmsFLAGS_NOWHITEONWHITEFIXUP)) { if (!FixWhiteMisalignment(OptimizedLUT, ColorSpace, OutputColorSpace)) { return FALSE; } } // And return the obtained LUT cmsPipelineFree(OriginalLut); *Lut = OptimizedLUT; return TRUE; Error: for (t = 0; t < OriginalLut ->InputChannels; t++) { if (Trans[t]) cmsFreeToneCurve(Trans[t]); if (TransReverse[t]) cmsFreeToneCurve(TransReverse[t]); } if (LutPlusCurves != NULL) cmsPipelineFree(LutPlusCurves); if (OptimizedLUT != NULL) cmsPipelineFree(OptimizedLUT); return FALSE; cmsUNUSED_PARAMETER(Intent); } // Curves optimizer ------------------------------------------------------------------------------------------------------------------ static void CurvesFree(cmsContext ContextID, void* ptr) { Curves16Data* Data = (Curves16Data*) ptr; int i; for (i=0; i < Data -> nCurves; i++) { _cmsFree(ContextID, Data ->Curves[i]); } _cmsFree(ContextID, Data ->Curves); _cmsFree(ContextID, ptr); } static void* CurvesDup(cmsContext ContextID, const void* ptr) { Curves16Data* Data = (Curves16Data*)_cmsDupMem(ContextID, ptr, sizeof(Curves16Data)); int i; if (Data == NULL) return NULL; Data ->Curves = (cmsUInt16Number**)_cmsDupMem(ContextID, Data ->Curves, Data ->nCurves * sizeof(cmsUInt16Number*)); for (i=0; i < Data -> nCurves; i++) { Data ->Curves[i] = (cmsUInt16Number*)_cmsDupMem(ContextID, Data ->Curves[i], Data -> nElements * sizeof(cmsUInt16Number)); } return (void*) Data; } // Precomputes tables for 8-bit on input devicelink. static Curves16Data* CurvesAlloc(cmsContext ContextID, int nCurves, int nElements, cmsToneCurve** G) { int i, j; Curves16Data* c16; c16 = (Curves16Data*)_cmsMallocZero(ContextID, sizeof(Curves16Data)); if (c16 == NULL) return NULL; c16 ->nCurves = nCurves; c16 ->nElements = nElements; c16 ->Curves = (cmsUInt16Number**)_cmsCalloc(ContextID, nCurves, sizeof(cmsUInt16Number*)); if (c16 ->Curves == NULL) return NULL; for (i=0; i < nCurves; i++) { c16->Curves[i] = (cmsUInt16Number*)_cmsCalloc(ContextID, nElements, sizeof(cmsUInt16Number)); if (c16->Curves[i] == NULL) { for (j=0; j < i; j++) { _cmsFree(ContextID, c16->Curves[j]); } _cmsFree(ContextID, c16->Curves); _cmsFree(ContextID, c16); return NULL; } if (nElements == 256) { for (j=0; j < nElements; j++) { c16 ->Curves[i][j] = cmsEvalToneCurve16(G[i], FROM_8_TO_16(j)); } } else { for (j=0; j < nElements; j++) { c16 ->Curves[i][j] = cmsEvalToneCurve16(G[i], (cmsUInt16Number) j); } } } return c16; } static void FastEvaluateCurves8(register const cmsUInt16Number In[], register cmsUInt16Number Out[], register const void* D) { Curves16Data* Data = (Curves16Data*) D; cmsUInt8Number x; int i; for (i=0; i < Data ->nCurves; i++) { x = (In[i] >> 8); Out[i] = Data -> Curves[i][x]; } } static void FastEvaluateCurves16(register const cmsUInt16Number In[], register cmsUInt16Number Out[], register const void* D) { Curves16Data* Data = (Curves16Data*) D; int i; for (i=0; i < Data ->nCurves; i++) { Out[i] = Data -> Curves[i][In[i]]; } } static void FastIdentity16(register const cmsUInt16Number In[], register cmsUInt16Number Out[], register const void* D) { cmsPipeline* Lut = (cmsPipeline*) D; cmsUInt32Number i; for (i=0; i < Lut ->InputChannels; i++) { Out[i] = In[i]; } } // If the target LUT holds only curves, the optimization procedure is to join all those // curves together. That only works on curves and does not work on matrices. static cmsBool OptimizeByJoiningCurves(cmsPipeline** Lut, cmsUInt32Number Intent, cmsUInt32Number* InputFormat, cmsUInt32Number* OutputFormat, cmsUInt32Number* dwFlags) { cmsToneCurve** GammaTables = NULL; cmsFloat32Number InFloat[cmsMAXCHANNELS], OutFloat[cmsMAXCHANNELS]; cmsUInt32Number i, j; cmsPipeline* Src = *Lut; cmsPipeline* Dest = NULL; cmsStage* mpe; cmsStage* ObtainedCurves = NULL; // This is a loosy optimization! does not apply in floating-point cases if (_cmsFormatterIsFloat(*InputFormat) || _cmsFormatterIsFloat(*OutputFormat)) return FALSE; // Only curves in this LUT? for (mpe = cmsPipelineGetPtrToFirstStage(Src); mpe != NULL; mpe = cmsStageNext(mpe)) { if (cmsStageType(mpe) != cmsSigCurveSetElemType) return FALSE; } // Allocate an empty LUT Dest = cmsPipelineAlloc(Src ->ContextID, Src ->InputChannels, Src ->OutputChannels); if (Dest == NULL) return FALSE; // Create target curves GammaTables = (cmsToneCurve**) _cmsCalloc(Src ->ContextID, Src ->InputChannels, sizeof(cmsToneCurve*)); if (GammaTables == NULL) goto Error; for (i=0; i < Src ->InputChannels; i++) { GammaTables[i] = cmsBuildTabulatedToneCurve16(Src ->ContextID, PRELINEARIZATION_POINTS, NULL); if (GammaTables[i] == NULL) goto Error; } // Compute 16 bit result by using floating point for (i=0; i < PRELINEARIZATION_POINTS; i++) { for (j=0; j < Src ->InputChannels; j++) InFloat[j] = (cmsFloat32Number) ((cmsFloat64Number) i / (PRELINEARIZATION_POINTS - 1)); cmsPipelineEvalFloat(InFloat, OutFloat, Src); for (j=0; j < Src ->InputChannels; j++) GammaTables[j] -> Table16[i] = _cmsQuickSaturateWord(OutFloat[j] * 65535.0); } ObtainedCurves = cmsStageAllocToneCurves(Src ->ContextID, Src ->InputChannels, GammaTables); if (ObtainedCurves == NULL) goto Error; for (i=0; i < Src ->InputChannels; i++) { cmsFreeToneCurve(GammaTables[i]); GammaTables[i] = NULL; } if (GammaTables != NULL) _cmsFree(Src ->ContextID, GammaTables); // Maybe the curves are linear at the end if (!AllCurvesAreLinear(ObtainedCurves)) { if (!cmsPipelineInsertStage(Dest, cmsAT_BEGIN, ObtainedCurves)) goto Error; // If the curves are to be applied in 8 bits, we can save memory if (_cmsFormatterIs8bit(*InputFormat)) { _cmsStageToneCurvesData* Data = (_cmsStageToneCurvesData*) ObtainedCurves ->Data; Curves16Data* c16 = CurvesAlloc(Dest ->ContextID, Data ->nCurves, 256, Data ->TheCurves); if (c16 == NULL) goto Error; *dwFlags |= cmsFLAGS_NOCACHE; _cmsPipelineSetOptimizationParameters(Dest, FastEvaluateCurves8, c16, CurvesFree, CurvesDup); } else { _cmsStageToneCurvesData* Data = (_cmsStageToneCurvesData*) cmsStageData(ObtainedCurves); Curves16Data* c16 = CurvesAlloc(Dest ->ContextID, Data ->nCurves, 65536, Data ->TheCurves); if (c16 == NULL) goto Error; *dwFlags |= cmsFLAGS_NOCACHE; _cmsPipelineSetOptimizationParameters(Dest, FastEvaluateCurves16, c16, CurvesFree, CurvesDup); } } else { // LUT optimizes to nothing. Set the identity LUT cmsStageFree(ObtainedCurves); if (!cmsPipelineInsertStage(Dest, cmsAT_BEGIN, cmsStageAllocIdentity(Dest ->ContextID, Src ->InputChannels))) goto Error; *dwFlags |= cmsFLAGS_NOCACHE; _cmsPipelineSetOptimizationParameters(Dest, FastIdentity16, (void*) Dest, NULL, NULL); } // We are done. cmsPipelineFree(Src); *Lut = Dest; return TRUE; Error: if (ObtainedCurves != NULL) cmsStageFree(ObtainedCurves); if (GammaTables != NULL) { for (i=0; i < Src ->InputChannels; i++) { if (GammaTables[i] != NULL) cmsFreeToneCurve(GammaTables[i]); } _cmsFree(Src ->ContextID, GammaTables); } if (Dest != NULL) cmsPipelineFree(Dest); return FALSE; cmsUNUSED_PARAMETER(Intent); cmsUNUSED_PARAMETER(InputFormat); cmsUNUSED_PARAMETER(OutputFormat); cmsUNUSED_PARAMETER(dwFlags); } // ------------------------------------------------------------------------------------------------------------------------------------- // LUT is Shaper - Matrix - Matrix - Shaper, which is very frequent when combining two matrix-shaper profiles static void FreeMatShaper(cmsContext ContextID, void* Data) { if (Data != NULL) _cmsFree(ContextID, Data); } static void* DupMatShaper(cmsContext ContextID, const void* Data) { return _cmsDupMem(ContextID, Data, sizeof(MatShaper8Data)); } // A fast matrix-shaper evaluator for 8 bits. This is a bit ticky since I'm using 1.14 signed fixed point // to accomplish some performance. Actually it takes 256x3 16 bits tables and 16385 x 3 tables of 8 bits, // in total about 50K, and the performance boost is huge! static void MatShaperEval16(register const cmsUInt16Number In[], register cmsUInt16Number Out[], register const void* D) { MatShaper8Data* p = (MatShaper8Data*) D; cmsS1Fixed14Number l1, l2, l3, r, g, b; cmsUInt32Number ri, gi, bi; // In this case (and only in this case!) we can use this simplification since // In[] is assured to come from a 8 bit number. (a << 8 | a) ri = In[0] & 0xFF; gi = In[1] & 0xFF; bi = In[2] & 0xFF; // Across first shaper, which also converts to 1.14 fixed point r = p->Shaper1R[ri]; g = p->Shaper1G[gi]; b = p->Shaper1B[bi]; // Evaluate the matrix in 1.14 fixed point l1 = (p->Mat[0][0] * r + p->Mat[0][1] * g + p->Mat[0][2] * b + p->Off[0] + 0x2000) >> 14; l2 = (p->Mat[1][0] * r + p->Mat[1][1] * g + p->Mat[1][2] * b + p->Off[1] + 0x2000) >> 14; l3 = (p->Mat[2][0] * r + p->Mat[2][1] * g + p->Mat[2][2] * b + p->Off[2] + 0x2000) >> 14; // Now we have to clip to 0..1.0 range ri = (l1 < 0) ? 0 : ((l1 > 16384) ? 16384 : l1); gi = (l2 < 0) ? 0 : ((l2 > 16384) ? 16384 : l2); bi = (l3 < 0) ? 0 : ((l3 > 16384) ? 16384 : l3); // And across second shaper, Out[0] = p->Shaper2R[ri]; Out[1] = p->Shaper2G[gi]; Out[2] = p->Shaper2B[bi]; } // This table converts from 8 bits to 1.14 after applying the curve static void FillFirstShaper(cmsS1Fixed14Number* Table, cmsToneCurve* Curve) { int i; cmsFloat32Number R, y; for (i=0; i < 256; i++) { R = (cmsFloat32Number) (i / 255.0); y = cmsEvalToneCurveFloat(Curve, R); Table[i] = DOUBLE_TO_1FIXED14(y); } } // This table converts form 1.14 (being 0x4000 the last entry) to 8 bits after applying the curve static void FillSecondShaper(cmsUInt16Number* Table, cmsToneCurve* Curve, cmsBool Is8BitsOutput) { int i; cmsFloat32Number R, Val; for (i=0; i < 16385; i++) { R = (cmsFloat32Number) (i / 16384.0); Val = cmsEvalToneCurveFloat(Curve, R); // Val comes 0..1.0 if (Is8BitsOutput) { // If 8 bits output, we can optimize further by computing the / 257 part. // first we compute the resulting byte and then we store the byte times // 257. This quantization allows to round very quick by doing a >> 8, but // since the low byte is always equal to msb, we can do a & 0xff and this works! cmsUInt16Number w = _cmsQuickSaturateWord(Val * 65535.0); cmsUInt8Number b = FROM_16_TO_8(w); Table[i] = FROM_8_TO_16(b); } else Table[i] = _cmsQuickSaturateWord(Val * 65535.0); } } // Compute the matrix-shaper structure static cmsBool SetMatShaper(cmsPipeline* Dest, cmsToneCurve* Curve1[3], cmsMAT3* Mat, cmsVEC3* Off, cmsToneCurve* Curve2[3], cmsUInt32Number* OutputFormat) { MatShaper8Data* p; int i, j; cmsBool Is8Bits = _cmsFormatterIs8bit(*OutputFormat); // Allocate a big chuck of memory to store precomputed tables p = (MatShaper8Data*) _cmsMalloc(Dest ->ContextID, sizeof(MatShaper8Data)); if (p == NULL) return FALSE; p -> ContextID = Dest -> ContextID; // Precompute tables FillFirstShaper(p ->Shaper1R, Curve1[0]); FillFirstShaper(p ->Shaper1G, Curve1[1]); FillFirstShaper(p ->Shaper1B, Curve1[2]); FillSecondShaper(p ->Shaper2R, Curve2[0], Is8Bits); FillSecondShaper(p ->Shaper2G, Curve2[1], Is8Bits); FillSecondShaper(p ->Shaper2B, Curve2[2], Is8Bits); // Convert matrix to nFixed14. Note that those values may take more than 16 bits as for (i=0; i < 3; i++) { for (j=0; j < 3; j++) { p ->Mat[i][j] = DOUBLE_TO_1FIXED14(Mat->v[i].n[j]); } } for (i=0; i < 3; i++) { if (Off == NULL) { p ->Off[i] = 0; } else { p ->Off[i] = DOUBLE_TO_1FIXED14(Off->n[i]); } } // Mark as optimized for faster formatter if (Is8Bits) *OutputFormat |= OPTIMIZED_SH(1); // Fill function pointers _cmsPipelineSetOptimizationParameters(Dest, MatShaperEval16, (void*) p, FreeMatShaper, DupMatShaper); return TRUE; } // 8 bits on input allows matrix-shaper boot up to 25 Mpixels per second on RGB. That's fast! // TODO: Allow a third matrix for abs. colorimetric static cmsBool OptimizeMatrixShaper(cmsPipeline** Lut, cmsUInt32Number Intent, cmsUInt32Number* InputFormat, cmsUInt32Number* OutputFormat, cmsUInt32Number* dwFlags) { cmsStage* Curve1, *Curve2; cmsStage* Matrix1, *Matrix2; _cmsStageMatrixData* Data1; _cmsStageMatrixData* Data2; cmsMAT3 res; cmsBool IdentityMat; cmsPipeline* Dest, *Src; // Only works on RGB to RGB if (T_CHANNELS(*InputFormat) != 3 || T_CHANNELS(*OutputFormat) != 3) return FALSE; // Only works on 8 bit input if (!_cmsFormatterIs8bit(*InputFormat)) return FALSE; // Seems suitable, proceed Src = *Lut; // Check for shaper-matrix-matrix-shaper structure, that is what this optimizer stands for if (!cmsPipelineCheckAndRetreiveStages(Src, 4, cmsSigCurveSetElemType, cmsSigMatrixElemType, cmsSigMatrixElemType, cmsSigCurveSetElemType, &Curve1, &Matrix1, &Matrix2, &Curve2)) return FALSE; // Get both matrices Data1 = (_cmsStageMatrixData*) cmsStageData(Matrix1); Data2 = (_cmsStageMatrixData*) cmsStageData(Matrix2); // Input offset should be zero if (Data1 ->Offset != NULL) return FALSE; // Multiply both matrices to get the result _cmsMAT3per(&res, (cmsMAT3*) Data2 ->Double, (cmsMAT3*) Data1 ->Double); // Now the result is in res + Data2 -> Offset. Maybe is a plain identity? IdentityMat = FALSE; if (_cmsMAT3isIdentity(&res) && Data2 ->Offset == NULL) { // We can get rid of full matrix IdentityMat = TRUE; } // Allocate an empty LUT Dest = cmsPipelineAlloc(Src ->ContextID, Src ->InputChannels, Src ->OutputChannels); if (!Dest) return FALSE; // Assamble the new LUT if (!cmsPipelineInsertStage(Dest, cmsAT_BEGIN, cmsStageDup(Curve1))) goto Error; if (!IdentityMat) if (!cmsPipelineInsertStage(Dest, cmsAT_END, cmsStageAllocMatrix(Dest ->ContextID, 3, 3, (const cmsFloat64Number*) &res, Data2 ->Offset))) goto Error; if (!cmsPipelineInsertStage(Dest, cmsAT_END, cmsStageDup(Curve2))) goto Error; // If identity on matrix, we can further optimize the curves, so call the join curves routine if (IdentityMat) { OptimizeByJoiningCurves(&Dest, Intent, InputFormat, OutputFormat, dwFlags); } else { _cmsStageToneCurvesData* mpeC1 = (_cmsStageToneCurvesData*) cmsStageData(Curve1); _cmsStageToneCurvesData* mpeC2 = (_cmsStageToneCurvesData*) cmsStageData(Curve2); // In this particular optimization, cach?does not help as it takes more time to deal with // the cach?that with the pixel handling *dwFlags |= cmsFLAGS_NOCACHE; // Setup the optimizarion routines SetMatShaper(Dest, mpeC1 ->TheCurves, &res, (cmsVEC3*) Data2 ->Offset, mpeC2->TheCurves, OutputFormat); } cmsPipelineFree(Src); *Lut = Dest; return TRUE; Error: // Leave Src unchanged cmsPipelineFree(Dest); return FALSE; } // ------------------------------------------------------------------------------------------------------------------------------------- // Optimization plug-ins // List of optimizations typedef struct _cmsOptimizationCollection_st { _cmsOPToptimizeFn OptimizePtr; struct _cmsOptimizationCollection_st *Next; } _cmsOptimizationCollection; // The built-in list. We currently implement 4 types of optimizations. Joining of curves, matrix-shaper, linearization and resampling static _cmsOptimizationCollection DefaultOptimization[] = { { OptimizeByJoiningCurves, &DefaultOptimization[1] }, { OptimizeMatrixShaper, &DefaultOptimization[2] }, { OptimizeByComputingLinearization, &DefaultOptimization[3] }, { OptimizeByResampling, NULL } }; // The linked list head _cmsOptimizationPluginChunkType _cmsOptimizationPluginChunk = { NULL }; // Duplicates the zone of memory used by the plug-in in the new context static void DupPluginOptimizationList(struct _cmsContext_struct* ctx, const struct _cmsContext_struct* src) { _cmsOptimizationPluginChunkType newHead = { NULL }; _cmsOptimizationCollection* entry; _cmsOptimizationCollection* Anterior = NULL; _cmsOptimizationPluginChunkType* head = (_cmsOptimizationPluginChunkType*) src->chunks[OptimizationPlugin]; _cmsAssert(ctx != NULL); _cmsAssert(head != NULL); // Walk the list copying all nodes for (entry = head->OptimizationCollection; entry != NULL; entry = entry ->Next) { _cmsOptimizationCollection *newEntry = ( _cmsOptimizationCollection *) _cmsSubAllocDup(ctx ->MemPool, entry, sizeof(_cmsOptimizationCollection)); if (newEntry == NULL) return; // We want to keep the linked list order, so this is a little bit tricky newEntry -> Next = NULL; if (Anterior) Anterior -> Next = newEntry; Anterior = newEntry; if (newHead.OptimizationCollection == NULL) newHead.OptimizationCollection = newEntry; } ctx ->chunks[OptimizationPlugin] = _cmsSubAllocDup(ctx->MemPool, &newHead, sizeof(_cmsOptimizationPluginChunkType)); } void _cmsAllocOptimizationPluginChunk(struct _cmsContext_struct* ctx, const struct _cmsContext_struct* src) { if (src != NULL) { // Copy all linked list DupPluginOptimizationList(ctx, src); } else { static _cmsOptimizationPluginChunkType OptimizationPluginChunkType = { NULL }; ctx ->chunks[OptimizationPlugin] = _cmsSubAllocDup(ctx ->MemPool, &OptimizationPluginChunkType, sizeof(_cmsOptimizationPluginChunkType)); } } // Register new ways to optimize cmsBool _cmsRegisterOptimizationPlugin(cmsContext ContextID, cmsPluginBase* Data) { cmsPluginOptimization* Plugin = (cmsPluginOptimization*) Data; _cmsOptimizationPluginChunkType* ctx = ( _cmsOptimizationPluginChunkType*) _cmsContextGetClientChunk(ContextID, OptimizationPlugin); _cmsOptimizationCollection* fl; if (Data == NULL) { ctx->OptimizationCollection = NULL; return TRUE; } // Optimizer callback is required if (Plugin ->OptimizePtr == NULL) return FALSE; fl = (_cmsOptimizationCollection*) _cmsPluginMalloc(ContextID, sizeof(_cmsOptimizationCollection)); if (fl == NULL) return FALSE; // Copy the parameters fl ->OptimizePtr = Plugin ->OptimizePtr; // Keep linked list fl ->Next = ctx->OptimizationCollection; // Set the head ctx ->OptimizationCollection = fl; // All is ok return TRUE; } // The entry point for LUT optimization cmsBool _cmsOptimizePipeline(cmsContext ContextID, cmsPipeline** PtrLut, int Intent, cmsUInt32Number* InputFormat, cmsUInt32Number* OutputFormat, cmsUInt32Number* dwFlags) { _cmsOptimizationPluginChunkType* ctx = ( _cmsOptimizationPluginChunkType*) _cmsContextGetClientChunk(ContextID, OptimizationPlugin); _cmsOptimizationCollection* Opts; cmsBool AnySuccess = FALSE; // A CLUT is being asked, so force this specific optimization if (*dwFlags & cmsFLAGS_FORCE_CLUT) { PreOptimize(*PtrLut); return OptimizeByResampling(PtrLut, Intent, InputFormat, OutputFormat, dwFlags); } // Anything to optimize? if ((*PtrLut) ->Elements == NULL) { _cmsPipelineSetOptimizationParameters(*PtrLut, FastIdentity16, (void*) *PtrLut, NULL, NULL); return TRUE; } // Try to get rid of identities and trivial conversions. AnySuccess = PreOptimize(*PtrLut); // After removal do we end with an identity? if ((*PtrLut) ->Elements == NULL) { _cmsPipelineSetOptimizationParameters(*PtrLut, FastIdentity16, (void*) *PtrLut, NULL, NULL); return TRUE; } // Do not optimize, keep all precision if (*dwFlags & cmsFLAGS_NOOPTIMIZE) return FALSE; // Try plug-in optimizations for (Opts = ctx->OptimizationCollection; Opts != NULL; Opts = Opts ->Next) { // If one schema succeeded, we are done if (Opts ->OptimizePtr(PtrLut, Intent, InputFormat, OutputFormat, dwFlags)) { return TRUE; // Optimized! } } // Try built-in optimizations for (Opts = DefaultOptimization; Opts != NULL; Opts = Opts ->Next) { if (Opts ->OptimizePtr(PtrLut, Intent, InputFormat, OutputFormat, dwFlags)) { return TRUE; } } // Only simple optimizations succeeded return AnySuccess; }
418102.c
/* * Copyright (C) 2015-2019 Alibaba Group Holding Limited */ #include <stdio.h> #include <string.h> #include "amp_defines.h" #include "amp_system.h" #include "amp_pm.h" #include "be_inl.h" #define MOD_STR "Battery" static duk_ret_t native_battery_conn_state_get(duk_context *ctx) { int ret = -1; int state; if (amp_battery_connect_state_get(&state)) { amp_error(MOD_STR, "get battery connect state fail"); goto out; } ret = state; out: duk_push_int(ctx, ret); return 1; } static duk_ret_t native_battery_voltage_get(duk_context *ctx) { int ret = -1; int voltage; if (amp_battery_voltage_get(&voltage)) { amp_error(MOD_STR, "get battery voltage fail"); goto out; } ret = voltage; out: duk_push_int(ctx, ret); return 1; } static duk_ret_t native_battery_level_get(duk_context *ctx) { int ret = -1; int level; if (amp_battery_level_get(&level)) { amp_error(MOD_STR, "get battery level fail"); goto out; } ret = level; out: duk_push_int(ctx, ret); return 1; } static duk_ret_t native_battery_temperature_get(duk_context *ctx) { int ret = -1; int temperature; if (amp_battery_temperature_get(&temperature)) { amp_error(MOD_STR, "get battery temperature fail"); goto out; } ret = temperature; out: duk_push_int(ctx, ret); return 1; } void module_battery_register(void) { duk_context *ctx = be_get_context(); duk_push_object(ctx); AMP_ADD_FUNCTION("getConnectState", native_battery_conn_state_get, 0); AMP_ADD_FUNCTION("getVoltage", native_battery_voltage_get, 0); AMP_ADD_FUNCTION("getLevel", native_battery_level_get, 0); AMP_ADD_FUNCTION("getTemperature", native_battery_temperature_get, 0); duk_put_prop_string(ctx, -2, "Battery"); }
359885.c
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <netdb.h> #include <error.h> #include <signal.h> #include <errno.h> #include <sys/wait.h> #include <sys/time.h> #include <time.h> #include "headers/utils.h" char *timestamp() { struct tm *local; time_t t = time(NULL); char *str; /* Get the localtime */ local = localtime(&t); str = asctime(local); int i = 0; int len = strlen(str) + 1; for (i = 0; i < len; i++) { if (str[i] == '\n') { /* Move all the char following the char "\n" by one to the left. */ strncpy(&str[i], &str[i + 1], len - i); } } return str; } /* sighandler */ void interrupt_handler(int s) { printf("[%s] SERVER: QUITING \n", timestamp()); close(server_fd); exit(EXIT_SUCCESS); } /* Get listener fd */ int establish_server( char *port, int backlog, char *server_IP) { int server_status, bind_status, listen_status, accept_status, addr_status; int n = 0, yes = 1; struct addrinfo server_addr, *results, *p; char addr[INET_ADDRSTRLEN]; memset(&server_addr, 0, sizeof(server_addr)); /* struct addrinfo { int ai_flags; int ai_family; int ai_socktype; int ai_protocol; socklen_t ai_addrlen; struct sockaddr *ai_addr; char *ai_canonname; struct addrinfo *ai_next; }; */ server_addr.ai_family = PF_INET; /* IPv4 */ server_addr.ai_socktype = SOCK_STREAM; /* tcp Stream */ server_addr.ai_flags = AI_PASSIVE; /* fill ip automatically */ /* get all the available address of this machine */ if ((addr_status = getaddrinfo(NULL, port, &server_addr, &results)) != 0) { printf("[%s] SERVER: ERROR getaddrinfo(): %s\n", timestamp(), gai_strerror(addr_status)); exit(EXIT_FAILURE); } /* bind a socket at the first available address */ for (p = results; p != NULL; p = p->ai_next) { inet_ntop(p->ai_family, p->ai_addr, addr, sizeof(addr)); printf("[%s] SERVER: Trying to build on: %s", timestamp(), addr); if ((server_fd = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) == -1) { perror("ERROR socket()"); continue; /* if socket can not be created on this address try another */ } if (setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int)) == -1) { perror("ERROR setsockopt()"); exit(EXIT_FAILURE); } if (((bind_status = bind(server_fd, p->ai_addr, p->ai_addrlen)) == -1)) { perror("ERROR bind()"); continue; } /** * control reaches here if all the above conditions satifie * we have succesfully bound a socket and can exit from this loop */ break; } freeaddrinfo(results); /** * if we get p== NULL that means we couldn't bind to any of the addresses * should return from the program */ if (p == NULL) { return -1; } if (listen_status = listen(server_fd, backlog) == -1) { // perror("ERROR listen()"); return -2; } strncpy(server_IP, addr, INET_ADDRSTRLEN); return 0; }
658350.c
/* * Licensed to the OpenAirInterface (OAI) Software Alliance under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The OpenAirInterface Software Alliance licenses this file to You under * the OAI 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.openairinterface.org/?page_id=698 * * 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. *------------------------------------------------------------------------------- * For more information about the OpenAirInterface (OAI) Software Alliance: * contact@openairinterface.org */ /*! \file m2ap_MCE_handler.c * \brief m2ap handler procedures for MCE * \author Javier Morgade <javier.morgade@ieee.org> * \date 2019 * \version 0.1 */ #include <stdint.h> #include "intertask_interface.h" #include "asn1_conversions.h" #include "m2ap_common.h" #include "m2ap_MCE_defs.h" #include "m2ap_MCE_handler.h" #include "m2ap_decoder.h" #include "m2ap_ids.h" //#include "m2ap_MCE_management_procedures.h" #include "m2ap_MCE_generate_messages.h" #include "m2ap_MCE_interface_management.h" //#include "m2ap_eNB_interface_management.h" #include "msc.h" #include "assertions.h" #include "conversions.h" /* Handlers matrix. Only eNB related procedure present here */ m2ap_message_decoded_callback m2ap_MCE_messages_callback[][3] = { { 0, MCE_handle_MBMS_SESSION_START_RESPONSE, 0 }, /* MBMSSessionStart */ { 0, MCE_handle_MBMS_SESSION_STOP_RESPONSE, 0 }, /* MBMSSessionStop */ { 0, MCE_handle_MBMS_SCHEDULING_INFORMATION_RESPONSE, 0 }, /* MBMSSchedulingInformation */ { 0, 0, 0 }, /* Error Indication */ { 0, 0, 0 }, /* Reset */ { MCE_handle_M2_SETUP_REQUEST, 0, 0 }, /* M2 Setup */ { 0, 0, 0 }, /* eNBConfigurationUpdate */ { 0, 0, 0 }, /* MCEConfigurationUpdate */ { 0, 0, 0 }, /* privateMessage */ { 0, 0, 0 }, /* MBMSSessionUpdate */ { 0, 0, 0 }, /* MBMSServiceCounting */ { 0, 0, 0 }, /* MBMSServiceCountingResultReport */ { 0, 0, 0 } /* MBMSOverloadNotification */ }; static char *m2ap_direction2String(int m2ap_dir) { static char *m2ap_direction_String[] = { "", /* Nothing */ "Originating message", /* originating message */ "Successfull outcome", /* successfull outcome */ "UnSuccessfull outcome", /* successfull outcome */ }; return(m2ap_direction_String[m2ap_dir]); } int m2ap_MCE_handle_message(instance_t instance, uint32_t assoc_id, int32_t stream, const uint8_t * const data, const uint32_t data_length) { M2AP_M2AP_PDU_t pdu; int ret; DevAssert(data != NULL); memset(&pdu, 0, sizeof(pdu)); if (m2ap_decode_pdu(&pdu, data, data_length) < 0) { LOG_E(M2AP, "Failed to decode PDU\n"); return -1; } /* Checking procedure Code and direction of message */ if (pdu.choice.initiatingMessage.procedureCode > sizeof(m2ap_MCE_messages_callback) / (3 * sizeof( m2ap_MCE_message_decoded_callback)) || (pdu.present > M2AP_M2AP_PDU_PR_unsuccessfulOutcome)) { LOG_E(M2AP, "[SCTP %d] Either procedureCode %ld or direction %d exceed expected\n", assoc_id, pdu.choice.initiatingMessage.procedureCode, pdu.present); ASN_STRUCT_FREE_CONTENTS_ONLY(asn_DEF_M2AP_M2AP_PDU, &pdu); return -1; } /* No handler present. * This can mean not implemented or no procedure for eNB (wrong direction). */ if (m2ap_MCE_messages_callback[pdu.choice.initiatingMessage.procedureCode][pdu.present - 1] == NULL) { LOG_E(M2AP, "[SCTP %d] No handler for procedureCode %ld in %s\n", assoc_id, pdu.choice.initiatingMessage.procedureCode, m2ap_direction2String(pdu.present - 1)); ASN_STRUCT_FREE_CONTENTS_ONLY(asn_DEF_M2AP_M2AP_PDU, &pdu); return -1; } /* Calling the right handler */ LOG_I(M2AP, "Calling handler with instance %d\n",instance); ret = (*m2ap_MCE_messages_callback[pdu.choice.initiatingMessage.procedureCode][pdu.present - 1]) (instance, assoc_id, stream, &pdu); ASN_STRUCT_FREE_CONTENTS_ONLY(asn_DEF_M2AP_M2AP_PDU, &pdu); return ret; }
789069.c
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE195_Signed_to_Unsigned_Conversion_Error__rand_memmove_63a.c Label Definition File: CWE195_Signed_to_Unsigned_Conversion_Error.label.xml Template File: sources-sink-63a.tmpl.c */ /* * @description * CWE: 195 Signed to Unsigned Conversion Error * BadSource: rand Set data to result of rand(), which may be zero * GoodSource: Positive integer * Sinks: memmove * BadSink : Copy strings using memmove() with the length of data * Flow Variant: 63 Data flow: pointer to data passed from one function to another in different source files * * */ #include "std_testcase.h" #ifndef OMITBAD /* bad function declaration */ void CWE195_Signed_to_Unsigned_Conversion_Error__rand_memmove_63b_badSink(int * dataPtr); void CWE195_Signed_to_Unsigned_Conversion_Error__rand_memmove_63_bad() { int data; /* Initialize data */ data = -1; /* POTENTIAL FLAW: Set data to a random value */ data = RAND32(); CWE195_Signed_to_Unsigned_Conversion_Error__rand_memmove_63b_badSink(&data); } #endif /* OMITBAD */ #ifndef OMITGOOD /* goodG2B uses the GoodSource with the BadSink */ void CWE195_Signed_to_Unsigned_Conversion_Error__rand_memmove_63b_goodG2BSink(int * data); static void goodG2B() { int data; /* Initialize data */ data = -1; /* FIX: Use a positive integer less than &InitialDataSize&*/ data = 100-1; CWE195_Signed_to_Unsigned_Conversion_Error__rand_memmove_63b_goodG2BSink(&data); } void CWE195_Signed_to_Unsigned_Conversion_Error__rand_memmove_63_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()..."); CWE195_Signed_to_Unsigned_Conversion_Error__rand_memmove_63_good(); printLine("Finished good()"); #endif /* OMITGOOD */ #ifndef OMITBAD printLine("Calling bad()..."); CWE195_Signed_to_Unsigned_Conversion_Error__rand_memmove_63_bad(); printLine("Finished bad()"); #endif /* OMITBAD */ return 0; } #endif
646194.c
/* * Falcon version 0.0.2 (master, Dec 02 2019) * fl-object.c: Falcon's object representation * See Falcon's license in the LICENSE file */ #include "fl-object.h" #include "../lib/fl-strlib.h" #include "fl-mem.h" #include <string.h> /** * Returns the name, as a string, of a given ObjType. */ const char *get_object_name(ObjType type) { const char *objectTypeNames[] = {"OBJ_STRING", "OBJ_FUNCTION", "OBJ_UPVALUE", "OBJ_CLOSURE", "OBJ_CLASS", "OBJ_INSTANCE", "OBJ_BMETHOD", "OBJ_LIST", "OBJ_MAP", "OBJ_NATIVE"}; return objectTypeNames[type]; } /** * Creates a new empty ObjString of a given length by claiming ownership of the new string. In this * case, the characters of the ObjString can be later freed when no longer needed. */ ObjString *make_string(FalconVM *vm, size_t length) { ObjString *str = (ObjString *) allocate_object(vm, sizeof(ObjString) + length + 1, OBJ_STRING); str->length = length; return str; } /** * Copies and allocates a given string, of a given length, to the heap. This way, the resulting * ObjString reliably owns its character array and can later free it. */ ObjString *new_ObjString(FalconVM *vm, const char *chars, size_t length) { uint32_t hash = hash_string((const unsigned char *) chars, length); ObjString *interned = find_string(&vm->strings, chars, length, hash); /* Checks if interned */ if (interned != NULL) return interned; /* Copies the characters to the ObjString */ ObjString *str = make_string(vm, length); memcpy(str->chars, chars, length); str->chars[length] = '\0'; str->hash = hash; DISABLE_GC(vm); /* Avoids GC from the "map_set" ahead */ map_set(vm, &vm->strings, str, NULL_VAL); /* Interns the string */ ENABLE_GC(vm); return str; } /** * Allocates a new empty ObjMap and initializes its fields. */ ObjMap *new_ObjMap(FalconVM *vm) { ObjMap *map = FALCON_ALLOCATE_OBJ(vm, ObjMap, OBJ_MAP); map->capacity = 0; map->count = 0; map->entries = NULL; return map; } /** * Allocates a new ObjFunction and initializes its fields. */ ObjFunction *new_ObjFunction(FalconVM *vm) { ObjFunction *function = FALCON_ALLOCATE_OBJ(vm, ObjFunction, OBJ_FUNCTION); function->arity = 0; function->upvalueCount = 0; function->name = NULL; init_bytecode(&function->bytecode); return function; } /** * Allocates a new ObjUpvalue and initializes its fields, setting the upvalue slot to a given * FalconValue. */ ObjUpvalue *new_ObjUpvalue(FalconVM *vm, FalconValue *slot) { ObjUpvalue *upvalue = FALCON_ALLOCATE_OBJ(vm, ObjUpvalue, OBJ_UPVALUE); upvalue->slot = slot; upvalue->next = NULL; upvalue->closed = NULL_VAL; return upvalue; } /** * Allocates a new ObjClosure and initializes its fields, also allocating a list of ObjUpvalues and * setting the closure function to a given ObjFunction. */ ObjClosure *new_ObjClosure(FalconVM *vm, ObjFunction *function) { ObjUpvalue **upvalues = FALCON_ALLOCATE(vm, ObjUpvalue *, function->upvalueCount); /* Sets upvalue list */ for (int i = 0; i < function->upvalueCount; i++) { upvalues[i] = NULL; /* Initialize current upvalue */ } ObjClosure *closure = FALCON_ALLOCATE_OBJ(vm, ObjClosure, OBJ_CLOSURE); closure->function = function; closure->upvalues = upvalues; closure->upvalueCount = function->upvalueCount; return closure; } /** * Allocates a new ObjClass and initializes its fields, setting its name to a given ObjString. */ ObjClass *new_ObjClass(FalconVM *vm, ObjString *name) { ObjClass *class_ = FALCON_ALLOCATE_OBJ(vm, ObjClass, OBJ_CLASS); DISABLE_GC(vm); /* Avoids GC from the "new_ObjMap" ahead */ class_->name = name; class_->methods = *new_ObjMap(vm); ENABLE_GC(vm); return class_; } /** * Allocates a new ObjInstance and initializes its fields, setting its class to a given ObjClass. */ ObjInstance *new_ObjInstance(FalconVM *vm, ObjClass *class_) { ObjInstance *instance = FALCON_ALLOCATE_OBJ(vm, ObjInstance, OBJ_INSTANCE); DISABLE_GC(vm); /* Avoids GC from the "new_ObjMap" ahead */ instance->class_ = class_; instance->fields = *new_ObjMap(vm); ENABLE_GC(vm); return instance; } /** * Allocates a new ObjBMethod and initializes its fields, setting its receiver to a given * FalconValue and its method to a given ObjClosure. */ ObjBMethod *new_ObjBMethod(FalconVM *vm, FalconValue receiver, ObjClosure *method) { ObjBMethod *bound = FALCON_ALLOCATE_OBJ(vm, ObjBMethod, OBJ_BMETHOD); bound->receiver = receiver; bound->method = method; return bound; } /** * Allocates a new ObjList and initializes its fields, also allocating a list of FalconValues of a * given size. */ ObjList *new_ObjList(FalconVM *vm, uint16_t size) { FalconValue *elements = FALCON_ALLOCATE(vm, FalconValue, size); ObjList *list = FALCON_ALLOCATE_OBJ(vm, ObjList, OBJ_LIST); list->elements.count = size; list->elements.capacity = size; list->elements.values = elements; return list; } /** * Allocates a new ObjNative and initializes its fields, setting its function to a given * FalconNativeFn and its name to a given string. */ ObjNative *new_ObjNative(FalconVM *vm, FalconNativeFn function, const char *name) { ObjNative *native = FALCON_ALLOCATE_OBJ(vm, ObjNative, OBJ_NATIVE); native->function = function; native->name = name; return native; }
972170.c
/* * "Optimize" a list of dependencies as spit out by gcc -MD * for the kernel build * =========================================================================== * * Author Kai Germaschewski * Copyright 2002 by Kai Germaschewski <kai.germaschewski@gmx.de> * * This software may be used and distributed according to the terms * of the GNU General Public License, incorporated herein by reference. * * * Introduction: * * gcc produces a very nice and correct list of dependencies which * tells make when to remake a file. * * To use this list as-is however has the drawback that virtually * every file in the kernel includes autoconf.h. * * If the user re-runs make *config, autoconf.h will be * regenerated. make notices that and will rebuild every file which * includes autoconf.h, i.e. basically all files. This is extremely * annoying if the user just changed CONFIG_HIS_DRIVER from n to m. * * So we play the same trick that "mkdep" played before. We replace * the dependency on autoconf.h by a dependency on every config * option which is mentioned in any of the listed prequisites. * * kconfig populates a tree in include/config/ with an empty file * for each config symbol and when the configuration is updated * the files representing changed config options are touched * which then let make pick up the changes and the files that use * the config symbols are rebuilt. * * So if the user changes his CONFIG_HIS_DRIVER option, only the objects * which depend on "include/linux/config/his/driver.h" will be rebuilt, * so most likely only his driver ;-) * * The idea above dates, by the way, back to Michael E Chastain, AFAIK. * * So to get dependencies right, there are two issues: * o if any of the files the compiler read changed, we need to rebuild * o if the command line given to the compile the file changed, we * better rebuild as well. * * The former is handled by using the -MD output, the later by saving * the command line used to compile the old object and comparing it * to the one we would now use. * * Again, also this idea is pretty old and has been discussed on * kbuild-devel a long time ago. I don't have a sensibly working * internet connection right now, so I rather don't mention names * without double checking. * * This code here has been based partially based on mkdep.c, which * says the following about its history: * * Copyright abandoned, Michael Chastain, <mailto:mec@shout.net>. * This is a C version of syncdep.pl by Werner Almesberger. * * * It is invoked as * * fixdep <depfile> <target> <cmdline> * * and will read the dependency file <depfile> * * The transformed dependency snipped is written to stdout. * * It first generates a line * * cmd_<target> = <cmdline> * * and then basically copies the .<target>.d file to stdout, in the * process filtering out the dependency on autoconf.h and adding * dependencies on include/config/my/option.h for every * CONFIG_MY_OPTION encountered in any of the prequisites. * * It will also filter out all the dependencies on *.ver. We need * to make sure that the generated version checksum are globally up * to date before even starting the recursive build, so it's too late * at this point anyway. * * The algorithm to grep for "CONFIG_..." is bit unusual, but should * be fast ;-) We don't even try to really parse the header files, but * merely grep, i.e. if CONFIG_FOO is mentioned in a comment, it will * be picked up as well. It's not a problem with respect to * correctness, since that can only give too many dependencies, thus * we cannot miss a rebuild. Since people tend to not mention totally * unrelated CONFIG_ options all over the place, it's not an * efficiency problem either. * * (Note: it'd be easy to port over the complete mkdep state machine, * but I don't think the added complexity is worth it) */ /* * Note 2: if somebody writes HELLO_CONFIG_BOOM in a file, it will depend onto * CONFIG_BOOM. This could seem a bug (not too hard to fix), but please do not * fix it! Some UserModeLinux files (look at arch/um/) call CONFIG_BOOM as * UML_CONFIG_BOOM, to avoid conflicts with /usr/include/linux/autoconf.h, * through arch/um/include/uml-config.h; this fixdep "bug" makes sure that * those files will have correct dependencies. */ #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #include <fcntl.h> #include <string.h> #include <stdlib.h> #include <stdio.h> #include <limits.h> #include <ctype.h> #ifdef __linux__ #define OS_LINUX #elif _WIN32 #define OS_WIN32 #else #error "Unsupported platforms" #endif #ifdef OS_LINUX #include <sys/mman.h> #include <arpa/inet.h> #else #include <winsock2.h> #include <windows.h> #pragma comment(lib,"ws2_32.a") #endif #ifdef OS_WIN32 void *mmap(char *filename, unsigned int filesize, HANDLE *phMap) { if ((filename == NULL) || (filesize == 0) || (phMap == NULL)) return NULL; HANDLE hMap = OpenFileMapping(FILE_MAP_READ, TRUE, filename); if (hMap == NULL) { OFSTRUCT buffer; HFILE hfile = OpenFile(filename, &buffer, OF_READ); if (hfile == NULL) return NULL; hMap = CreateFileMapping((HANDLE)hfile, NULL, PAGE_READONLY, 0, filesize, filename); CloseHandle(hfile); if (hMap == NULL) return NULL; } char *text = (CHAR *)MapViewOfFile(hMap, FILE_MAP_READ, 0, 0, filesize); if (text == NULL) { CloseHandle(hMap); return NULL; } *phMap = hMap; return text; } void munmap(char *text, HANDLE hMap) { if (text && hMap) { UnmapViewOfFile(text); CloseHandle(hMap); } } #endif #define INT_CONF ntohl(0x434f4e46) #define INT_ONFI ntohl(0x4f4e4649) #define INT_NFIG ntohl(0x4e464947) #define INT_FIG_ ntohl(0x4649475f) #define X_CONF_DIR "include/config/" char *target; char *depfile; char *cmdline; static void usage(void) { fprintf(stderr, "Usage: fixdep <depfile> <target> <cmdline>\n"); exit(1); } /* * Print out the commandline prefixed with cmd_<target filename> := */ static void print_cmdline(void) { printf("cmd_%s := %s\n\n", target, cmdline); } struct item { struct item *next; unsigned int len; unsigned int hash; char name[0]; }; #define HASHSZ 256 static struct item *hashtab[HASHSZ]; static unsigned int strhash(const char *str, unsigned int sz) { /* fnv32 hash */ unsigned int i, hash = 2166136261U; for (i = 0; i < sz; i++) hash = (hash ^ str[i]) * 0x01000193; return hash; } /* * Lookup a value in the configuration string. */ static int is_defined_config(const char *name, int len, unsigned int hash) { struct item *aux; for (aux = hashtab[hash % HASHSZ]; aux; aux = aux->next) { if (aux->hash == hash && aux->len == len && memcmp(aux->name, name, len) == 0) return 1; } return 0; } /* * Add a new value to the configuration string. */ static void define_config(const char *name, int len, unsigned int hash) { struct item *aux = malloc(sizeof(*aux) + len); if (!aux) { perror("fixdep:malloc"); exit(1); } memcpy(aux->name, name, len); aux->len = len; aux->hash = hash; aux->next = hashtab[hash % HASHSZ]; hashtab[hash % HASHSZ] = aux; } /* * Clear the set of configuration strings. */ static void clear_config(void) { struct item *aux, *next; unsigned int i; for (i = 0; i < HASHSZ; i++) { for (aux = hashtab[i]; aux; aux = next) { next = aux->next; free(aux); } hashtab[i] = NULL; } } /* * Record the use of a CONFIG_* word. */ static void use_config(const char *m, int slen) { unsigned int hash = strhash(m, slen); int c, i; if (is_defined_config(m, slen, hash)) return; define_config(m, slen, hash); printf(" $(wildcard "X_CONF_DIR); for (i = 0; i < slen; i++) putchar(tolower(m[i])); printf(".h) \\\n"); } static void parse_config_file(const char *map, size_t len) { const int *end = (const int *) (map + len); /* start at +1, so that p can never be < map */ const int *m = (const int *) map + 1; const char *p, *q; for (; m < end; m++) { if (*m == INT_CONF) { p = (char *) m ; goto conf; } if (*m == INT_ONFI) { p = (char *) m-1; goto conf; } if (*m == INT_NFIG) { p = (char *) m-2; goto conf; } if (*m == INT_FIG_) { p = (char *) m-3; goto conf; } continue; conf: if (p > map + len - 7) continue; if (memcmp(p, "CONFIG_", 7)) continue; for (q = p + 7; q < map + len; q++) { if (!(isalnum(*q) || *q == '_')) goto found; } continue; found: if (!memcmp(q - 7, "_MODULE", 7)) q -= 7; if( (q-p-7) < 0 ) continue; use_config(p+7, q-p-7); } } /* test is s ends in sub */ static int strrcmp(char *s, char *sub) { int slen = strlen(s); int sublen = strlen(sub); if (sublen > slen) return 1; return memcmp(s + slen - sublen, sub, sublen); } static void do_config_file(const char *filename) { struct stat st; int fd; void *map; fd = open(filename, O_RDONLY); if (fd < 0) { fprintf(stderr, "fixdep: error opening config file: "); perror(filename); exit(2); } fstat(fd, &st); if (st.st_size == 0) { close(fd); return; } #ifdef OS_LINUX map = mmap(NULL, st.st_size, PROT_READ, MAP_PRIVATE, fd, 0); if ((long) map == -1) { perror("fixdep: mmap"); close(fd); return; } #else HANDLE fMap; close(fd); map = mmap(filename, st.st_size, &fMap); if ((long) map == NULL) { perror("fixdep: mmap"); return; } #endif parse_config_file(map, st.st_size); #ifdef OS_LINUX munmap(map, st.st_size); close(fd); #else munmap(map, fMap); #endif } /* * Important: The below generated source_foo.o and deps_foo.o variable * assignments are parsed not only by make, but also by the rather simple * parser in scripts/mod/sumversion.c. */ static void parse_dep_file(void *map, size_t len) { char *m = map; char *end = m + len; char *p; char s[PATH_MAX]; int first; p = strchr(m, ':'); if (!p) { fprintf(stderr, "fixdep: parse error\n"); exit(1); } memcpy(s, m, p-m); s[p-m] = 0; m = p+1; clear_config(); first = 1; while (m < end) { while (m < end && (*m == ' ' || *m == '\\' || *m == '\n' || *m == '\r')) m++; p = m; while (p < end && *p != ' ') p++; if (p == end) { do p--; while (!isalnum(*p)); p++; if(p - m <= 0) break; } memcpy(s, m, p-m); s[p-m] = 0; #ifdef OS_WIN32 for (int i = 0;i < p-m; i++) if (s[i] == '\\') s[i] = '/'; #endif if (strrcmp(s, X_CONF_DIR"autoconf.h")) { /* * Do not list the source file as dependency, so that * kbuild is not confused if a .c file is rewritten * into .S or vice versa. Storing it in source_* is * needed for modpost to compute srcversions. */ if (first) { printf("source_%s := %s\n\n", target, s); printf("deps_%s := \\\n", target); } else printf(" %s \\\n", s); do_config_file(s); } first = 0; m = p + 1; } printf("\n%s: $(deps_%s)\n\n", target, target); printf("$(deps_%s):\n", target); } static void print_deps(void) { struct stat st; int fd; void *map; fd = open(depfile, O_RDONLY); if (fd < 0) { fprintf(stderr, "fixdep: error opening depfile: "); perror(depfile); exit(2); } if (fstat(fd, &st) < 0) { fprintf(stderr, "fixdep: error fstat'ing depfile: "); perror(depfile); exit(2); } if (st.st_size == 0) { fprintf(stderr,"fixdep: %s is empty\n",depfile); close(fd); return; } #ifdef OS_LINUX map = mmap(NULL, st.st_size, PROT_READ, MAP_PRIVATE, fd, 0); if ((long) map == -1) { perror("fixdep: mmap"); close(fd); return; } #else HANDLE fMap; close(fd); map = mmap(depfile, st.st_size, &fMap); if ((long) map == NULL) { perror("fixdep: mmap"); return; } #endif parse_dep_file(map, st.st_size); #ifdef OS_LINUX munmap(map, st.st_size); close(fd); #else munmap(map, fMap); #endif } static void traps(void) { static char test[] __attribute__((aligned(sizeof(int)))) = "CONF"; int *p = (int *)test; if (*p != INT_CONF) { fprintf(stderr, "fixdep: sizeof(int) != 4 or wrong endianess? %#x\n", *p); exit(2); } } int main(int argc, char *argv[]) { traps(); if (argc != 4) usage(); depfile = argv[1]; target = argv[2]; cmdline = argv[3]; print_cmdline(); print_deps(); return 0; }
955636.c
#include "common/include/data.h" #include "common/include/proc.h" #include "klibc/include/stdio.h" no_opt struct thread_control_block *get_tcb() { unsigned long tcb = 0; // __asm__ __volatile__ // ( // "mr %[reg], 13;" // : [reg]"=r"(tcb) // : // ); //kprintf("TCB @ %p\n", tcb); return (struct thread_control_block *)tcb; } no_opt int do_syscall(unsigned long num, unsigned long param1, unsigned long param2, unsigned long *out1, unsigned long *out2) { // register ulong __ppc32_reg_r3 __asm__("3") = num; // register ulong __ppc32_reg_r4 __asm__("4") = param1; // register ulong __ppc32_reg_r5 __asm__("5") = param2; // // __asm__ __volatile__ // ( // "sc;" // : "=r" (__ppc32_reg_r3), "=r" (__ppc32_reg_r4), "=r" (__ppc32_reg_r5) // : "r" (__ppc32_reg_r3), "r" (__ppc32_reg_r4), "r" (__ppc32_reg_r5) // ); // // if (out1) { // *out1 = __ppc32_reg_r4; // } // // if (out2) { // *out2 = __ppc32_reg_r5; // } return 1; //(int)__ppc32_reg_r3; }
421480.c
/* $OpenBSD: ca.c,v 1.38 2021/03/05 12:37:32 eric Exp $ */ /* * Copyright (c) 2014 Reyk Floeter <reyk@openbsd.org> * Copyright (c) 2012 Gilles Chehade <gilles@poolp.org> * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include "includes.h" #include <sys/types.h> #include <sys/queue.h> #include <sys/socket.h> #include <sys/tree.h> #include <grp.h> /* needed for setgroups */ #include <err.h> #include <imsg.h> #include <limits.h> #include <pwd.h> #include <signal.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <openssl/ssl.h> #include <openssl/pem.h> #include <openssl/evp.h> #include <openssl/ecdsa.h> #include <openssl/rsa.h> #include <openssl/engine.h> #include <openssl/err.h> #include "smtpd.h" #include "log.h" #include "ssl.h" static int ca_verify_cb(int, X509_STORE_CTX *); static int rsae_send_imsg(int, const unsigned char *, unsigned char *, RSA *, int, unsigned int); static int rsae_pub_enc(int, const unsigned char *, unsigned char *, RSA *, int); static int rsae_pub_dec(int,const unsigned char *, unsigned char *, RSA *, int); static int rsae_priv_enc(int, const unsigned char *, unsigned char *, RSA *, int); static int rsae_priv_dec(int, const unsigned char *, unsigned char *, RSA *, int); static int rsae_mod_exp(BIGNUM *, const BIGNUM *, RSA *, BN_CTX *); static int rsae_bn_mod_exp(BIGNUM *, const BIGNUM *, const BIGNUM *, const BIGNUM *, BN_CTX *, BN_MONT_CTX *); static int rsae_init(RSA *); static int rsae_finish(RSA *); static int rsae_keygen(RSA *, int, BIGNUM *, BN_GENCB *); static ECDSA_SIG *ecdsae_do_sign(const unsigned char *, int, const BIGNUM *, const BIGNUM *, EC_KEY *); static int ecdsae_sign_setup(EC_KEY *, BN_CTX *, BIGNUM **, BIGNUM **); static int ecdsae_do_verify(const unsigned char *, int, const ECDSA_SIG *, EC_KEY *); static struct dict pkeys; static uint64_t reqid = 0; static void ca_shutdown(void) { log_debug("debug: ca agent exiting"); _exit(0); } int ca(void) { struct passwd *pw; purge_config(PURGE_LISTENERS|PURGE_TABLES|PURGE_RULES|PURGE_DISPATCHERS); if ((pw = getpwnam(SMTPD_USER)) == NULL) fatalx("unknown user " SMTPD_USER); if (chroot(PATH_CHROOT) == -1) fatal("ca: chroot"); if (chdir("/") == -1) fatal("ca: chdir(\"/\")"); config_process(PROC_CA); if (setgroups(1, &pw->pw_gid) || setresgid(pw->pw_gid, pw->pw_gid, pw->pw_gid) || setresuid(pw->pw_uid, pw->pw_uid, pw->pw_uid)) fatal("ca: cannot drop privileges"); imsg_callback = ca_imsg; event_init(); signal(SIGINT, SIG_IGN); signal(SIGTERM, SIG_IGN); signal(SIGPIPE, SIG_IGN); signal(SIGHUP, SIG_IGN); config_peer(PROC_CONTROL); config_peer(PROC_PARENT); config_peer(PROC_DISPATCHER); /* Ignore them until we get our config */ mproc_disable(p_dispatcher); #if HAVE_PLEDGE if (pledge("stdio", NULL) == -1) err(1, "pledge"); #endif event_dispatch(); fatalx("exited event loop"); return (0); } void ca_init(void) { BIO *in = NULL; EVP_PKEY *pkey = NULL; struct pki *pki; const char *k; void *iter_dict; char *hash; log_debug("debug: init private ssl-tree"); dict_init(&pkeys); iter_dict = NULL; while (dict_iter(env->sc_pki_dict, &iter_dict, &k, (void **)&pki)) { if (pki->pki_key == NULL) continue; in = BIO_new_mem_buf(pki->pki_key, pki->pki_key_len); if (in == NULL) fatalx("ca_init: key"); pkey = PEM_read_bio_PrivateKey(in, NULL, NULL, NULL); if (pkey == NULL) fatalx("ca_init: PEM"); BIO_free(in); hash = ssl_pubkey_hash(pki->pki_cert, pki->pki_cert_len); if (dict_check(&pkeys, hash)) EVP_PKEY_free(pkey); else dict_xset(&pkeys, hash, pkey); free(hash); } } static int ca_verify_cb(int ok, X509_STORE_CTX *ctx) { switch (X509_STORE_CTX_get_error(ctx)) { case X509_V_OK: break; case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT: break; case X509_V_ERR_CERT_NOT_YET_VALID: case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD: break; case X509_V_ERR_CERT_HAS_EXPIRED: case X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD: break; case X509_V_ERR_NO_EXPLICIT_POLICY: break; } return ok; } int ca_X509_verify(void *certificate, void *chain, const char *CAfile, const char *CRLfile, const char **errstr) { X509_STORE *store = NULL; X509_STORE_CTX *xsc = NULL; int ret = 0; long error = 0; if ((store = X509_STORE_new()) == NULL) goto end; if (!X509_STORE_load_locations(store, CAfile, NULL)) { log_warn("warn: unable to load CA file %s", CAfile); goto end; } X509_STORE_set_default_paths(store); if ((xsc = X509_STORE_CTX_new()) == NULL) goto end; if (X509_STORE_CTX_init(xsc, store, certificate, chain) != 1) goto end; X509_STORE_CTX_set_verify_cb(xsc, ca_verify_cb); ret = X509_verify_cert(xsc); end: *errstr = NULL; if (ret != 1) { if (xsc) { error = X509_STORE_CTX_get_error(xsc); *errstr = X509_verify_cert_error_string(error); } else if (ERR_peek_last_error()) *errstr = ERR_error_string(ERR_peek_last_error(), NULL); } X509_STORE_CTX_free(xsc); X509_STORE_free(store); return ret > 0 ? 1 : 0; } void ca_imsg(struct mproc *p, struct imsg *imsg) { EVP_PKEY *pkey; RSA *rsa = NULL; EC_KEY *ecdsa = NULL; const void *from = NULL; unsigned char *to = NULL; struct msg m; const char *hash; size_t flen, tlen, padding; int buf_len; int ret = 0; uint64_t id; int v; if (imsg == NULL) ca_shutdown(); switch (imsg->hdr.type) { case IMSG_CONF_START: return; case IMSG_CONF_END: ca_init(); /* Start fulfilling requests */ mproc_enable(p_dispatcher); return; case IMSG_CTL_VERBOSE: m_msg(&m, imsg); m_get_int(&m, &v); m_end(&m); log_trace_verbose(v); return; case IMSG_CTL_PROFILE: m_msg(&m, imsg); m_get_int(&m, &v); m_end(&m); profiling = v; return; case IMSG_CA_RSA_PRIVENC: case IMSG_CA_RSA_PRIVDEC: m_msg(&m, imsg); m_get_id(&m, &id); m_get_string(&m, &hash); m_get_data(&m, &from, &flen); m_get_size(&m, &tlen); m_get_size(&m, &padding); m_end(&m); pkey = dict_get(&pkeys, hash); if (pkey == NULL || (rsa = EVP_PKEY_get1_RSA(pkey)) == NULL) fatalx("ca_imsg: invalid pkey hash"); if ((to = calloc(1, tlen)) == NULL) fatalx("ca_imsg: calloc"); switch (imsg->hdr.type) { case IMSG_CA_RSA_PRIVENC: ret = RSA_private_encrypt(flen, from, to, rsa, padding); break; case IMSG_CA_RSA_PRIVDEC: ret = RSA_private_decrypt(flen, from, to, rsa, padding); break; } m_create(p, imsg->hdr.type, 0, 0, -1); m_add_id(p, id); m_add_int(p, ret); if (ret > 0) m_add_data(p, to, (size_t)ret); m_close(p); free(to); RSA_free(rsa); return; case IMSG_CA_ECDSA_SIGN: m_msg(&m, imsg); m_get_id(&m, &id); m_get_string(&m, &hash); m_get_data(&m, &from, &flen); m_end(&m); pkey = dict_get(&pkeys, hash); if (pkey == NULL || (ecdsa = EVP_PKEY_get1_EC_KEY(pkey)) == NULL) fatalx("ca_imsg: invalid pkey hash"); buf_len = ECDSA_size(ecdsa); if ((to = calloc(1, buf_len)) == NULL) fatalx("ca_imsg: calloc"); ret = ECDSA_sign(0, from, flen, to, &buf_len, ecdsa); m_create(p, imsg->hdr.type, 0, 0, -1); m_add_id(p, id); m_add_int(p, ret); if (ret > 0) m_add_data(p, to, (size_t)buf_len); m_close(p); free(to); EC_KEY_free(ecdsa); return; } errx(1, "ca_imsg: unexpected %s imsg", imsg_to_str(imsg->hdr.type)); } /* * RSA privsep engine (called from unprivileged processes) */ const RSA_METHOD *rsa_default = NULL; static RSA_METHOD *rsae_method = NULL; static int rsae_send_imsg(int flen, const unsigned char *from, unsigned char *to, RSA *rsa, int padding, unsigned int cmd) { int ret = 0; struct imsgbuf *ibuf; struct imsg imsg; int n, done = 0; const void *toptr; char *hash; size_t tlen; struct msg m; uint64_t id; if ((hash = RSA_get_ex_data(rsa, 0)) == NULL) return (0); /* * Send a synchronous imsg because we cannot defer the RSA * operation in OpenSSL's engine layer. */ m_create(p_ca, cmd, 0, 0, -1); reqid++; m_add_id(p_ca, reqid); m_add_string(p_ca, hash); m_add_data(p_ca, (const void *)from, (size_t)flen); m_add_size(p_ca, (size_t)RSA_size(rsa)); m_add_size(p_ca, (size_t)padding); m_flush(p_ca); ibuf = &p_ca->imsgbuf; while (!done) { if ((n = imsg_read(ibuf)) == -1 && errno != EAGAIN) fatalx("imsg_read"); if (n == 0) fatalx("pipe closed"); while (!done) { if ((n = imsg_get(ibuf, &imsg)) == -1) fatalx("imsg_get error"); if (n == 0) break; log_imsg(PROC_DISPATCHER, PROC_CA, &imsg); switch (imsg.hdr.type) { case IMSG_CA_RSA_PRIVENC: case IMSG_CA_RSA_PRIVDEC: break; default: /* Another imsg is queued up in the buffer */ dispatcher_imsg(p_ca, &imsg); imsg_free(&imsg); continue; } m_msg(&m, &imsg); m_get_id(&m, &id); if (id != reqid) fatalx("invalid response id"); m_get_int(&m, &ret); if (ret > 0) m_get_data(&m, &toptr, &tlen); m_end(&m); if (ret > 0) memcpy(to, toptr, tlen); done = 1; imsg_free(&imsg); } } mproc_event_add(p_ca); return (ret); } static int rsae_pub_enc(int flen,const unsigned char *from, unsigned char *to, RSA *rsa, int padding) { log_debug("debug: %s: %s", proc_name(smtpd_process), __func__); return (RSA_meth_get_pub_enc(rsa_default)(flen, from, to, rsa, padding)); } static int rsae_pub_dec(int flen,const unsigned char *from, unsigned char *to, RSA *rsa, int padding) { log_debug("debug: %s: %s", proc_name(smtpd_process), __func__); return (RSA_meth_get_pub_dec(rsa_default)(flen, from, to, rsa, padding)); } static int rsae_priv_enc(int flen, const unsigned char *from, unsigned char *to, RSA *rsa, int padding) { log_debug("debug: %s: %s", proc_name(smtpd_process), __func__); if (RSA_get_ex_data(rsa, 0) != NULL) return (rsae_send_imsg(flen, from, to, rsa, padding, IMSG_CA_RSA_PRIVENC)); return (RSA_meth_get_priv_enc(rsa_default)(flen, from, to, rsa, padding)); } static int rsae_priv_dec(int flen, const unsigned char *from, unsigned char *to, RSA *rsa, int padding) { log_debug("debug: %s: %s", proc_name(smtpd_process), __func__); if (RSA_get_ex_data(rsa, 0) != NULL) return (rsae_send_imsg(flen, from, to, rsa, padding, IMSG_CA_RSA_PRIVDEC)); return (RSA_meth_get_priv_dec(rsa_default)(flen, from, to, rsa, padding)); } static int rsae_mod_exp(BIGNUM *r0, const BIGNUM *I, RSA *rsa, BN_CTX *ctx) { log_debug("debug: %s: %s", proc_name(smtpd_process), __func__); return (RSA_meth_get_mod_exp(rsa_default)(r0, I, rsa, ctx)); } static int rsae_bn_mod_exp(BIGNUM *r, const BIGNUM *a, const BIGNUM *p, const BIGNUM *m, BN_CTX *ctx, BN_MONT_CTX *m_ctx) { log_debug("debug: %s: %s", proc_name(smtpd_process), __func__); return (RSA_meth_get_bn_mod_exp(rsa_default)(r, a, p, m, ctx, m_ctx)); } static int rsae_init(RSA *rsa) { log_debug("debug: %s: %s", proc_name(smtpd_process), __func__); if (RSA_meth_get_init(rsa_default) == NULL) return (1); return (RSA_meth_get_init(rsa_default)(rsa)); } static int rsae_finish(RSA *rsa) { log_debug("debug: %s: %s", proc_name(smtpd_process), __func__); if (RSA_meth_get_finish(rsa_default) == NULL) return (1); return (RSA_meth_get_finish(rsa_default)(rsa)); } static int rsae_keygen(RSA *rsa, int bits, BIGNUM *e, BN_GENCB *cb) { log_debug("debug: %s: %s", proc_name(smtpd_process), __func__); return (RSA_meth_get_keygen(rsa_default)(rsa, bits, e, cb)); } /* * ECDSA privsep engine (called from unprivileged processes) */ #if defined(SUPPORT_ECDSA) const ECDSA_METHOD *ecdsa_default = NULL; static ECDSA_METHOD *ecdsae_method = NULL; ECDSA_METHOD * ECDSA_METHOD_new_temporary(const char *name, int); ECDSA_METHOD * ECDSA_METHOD_new_temporary(const char *name, int flags) { ECDSA_METHOD *ecdsa; if ((ecdsa = calloc(1, sizeof (*ecdsa))) == NULL) return NULL; if ((ecdsa->name = strdup(name)) == NULL) { free(ecdsa); return NULL; } ecdsa->flags = flags; return ecdsa; } #else const EC_KEY_METHOD *ecdsa_default = NULL; static EC_KEY_METHOD *ecdsae_method = NULL; #endif static ECDSA_SIG * ecdsae_send_enc_imsg(const unsigned char *dgst, int dgst_len, const BIGNUM *inv, const BIGNUM *rp, EC_KEY *eckey) { int ret = 0; struct imsgbuf *ibuf; struct imsg imsg; int n, done = 0; const void *toptr; char *hash; size_t tlen; struct msg m; uint64_t id; ECDSA_SIG *sig = NULL; #if defined(SUPPORT_ECDSA) if ((hash = ECDSA_get_ex_data(eckey, 0)) == NULL) return (0); #else if ((hash = EC_KEY_get_ex_data(eckey, 0)) == NULL) return (0); #endif /* * Send a synchronous imsg because we cannot defer the ECDSA * operation in OpenSSL's engine layer. */ m_create(p_ca, IMSG_CA_ECDSA_SIGN, 0, 0, -1); reqid++; m_add_id(p_ca, reqid); m_add_string(p_ca, hash); m_add_data(p_ca, (const void *)dgst, (size_t)dgst_len); m_flush(p_ca); ibuf = &p_ca->imsgbuf; while (!done) { if ((n = imsg_read(ibuf)) == -1 && errno != EAGAIN) fatalx("imsg_read"); if (n == 0) fatalx("pipe closed"); while (!done) { if ((n = imsg_get(ibuf, &imsg)) == -1) fatalx("imsg_get error"); if (n == 0) break; log_imsg(PROC_DISPATCHER, PROC_CA, &imsg); switch (imsg.hdr.type) { case IMSG_CA_ECDSA_SIGN: break; default: /* Another imsg is queued up in the buffer */ dispatcher_imsg(p_ca, &imsg); imsg_free(&imsg); continue; } m_msg(&m, &imsg); m_get_id(&m, &id); if (id != reqid) fatalx("invalid response id"); m_get_int(&m, &ret); if (ret > 0) m_get_data(&m, &toptr, &tlen); m_end(&m); done = 1; if (ret > 0) d2i_ECDSA_SIG(&sig, (const unsigned char **)&toptr, tlen); imsg_free(&imsg); } } mproc_event_add(p_ca); return (sig); } #if defined(SUPPORT_ECDSA) ECDSA_SIG * ecdsae_do_sign(const unsigned char *dgst, int dgst_len, const BIGNUM *inv, const BIGNUM *rp, EC_KEY *eckey) { log_debug("debug: %s: %s", proc_name(smtpd_process), __func__); if (ECDSA_get_ex_data(eckey, 0) != NULL) return (ecdsae_send_enc_imsg(dgst, dgst_len, inv, rp, eckey)); return (ecdsa_default->ecdsa_do_sign(dgst, dgst_len, inv, rp, eckey)); } int ecdsae_sign_setup(EC_KEY *eckey, BN_CTX *ctx, BIGNUM **kinv, BIGNUM **r) { log_debug("debug: %s: %s", proc_name(smtpd_process), __func__); return (ecdsa_default->ecdsa_sign_setup(eckey, ctx, kinv, r)); } int ecdsae_do_verify(const unsigned char *dgst, int dgst_len, const ECDSA_SIG *sig, EC_KEY *eckey) { log_debug("debug: %s: %s", proc_name(smtpd_process), __func__); return (ecdsa_default->ecdsa_do_verify(dgst, dgst_len, sig, eckey)); } #else int ecdsae_keygen(EC_KEY *eckey) { int (*keygen)(EC_KEY *key); EC_KEY_METHOD_get_keygen(ecdsa_default, &keygen); return keygen(eckey); } int ecdsae_compute_key(unsigned char **psec, size_t *pseclen, const EC_POINT *pub_key, const EC_KEY *ecdh) { int (*ckey)(unsigned char **psec, size_t *pseclen, const EC_POINT *pub_key, const EC_KEY *ecdh); EC_KEY_METHOD_get_compute_key(ecdsa_default, &ckey); return ckey(psec, pseclen, pub_key, ecdh); } int ecdsae_sign(int type, const unsigned char *dgst, int dlen, unsigned char *sig, unsigned int *siglen, const BIGNUM *kinv, const BIGNUM *r, EC_KEY *eckey) { int (*sign)(int type, const unsigned char *dgst, int dlen, unsigned char *sig, unsigned int *siglen, const BIGNUM *kinv, const BIGNUM *r, EC_KEY *eckey); log_debug("debug: %s: %s", proc_name(smtpd_process), __func__); EC_KEY_METHOD_get_sign(ecdsa_default, &sign, NULL, NULL); return (sign(type, dgst, dlen, sig, siglen, kinv, r, eckey)); } ECDSA_SIG * ecdsae_do_sign(const unsigned char *dgst, int dgst_len, const BIGNUM *inv, const BIGNUM *rp, EC_KEY *eckey) { ECDSA_SIG *(*psign_sig)(const unsigned char *dgst, int dgst_len, const BIGNUM *in_kinv, const BIGNUM *in_r, EC_KEY *eckey); log_debug("debug: %s: %s", proc_name(smtpd_process), __func__); if (EC_KEY_get_ex_data(eckey, 0) != NULL) return (ecdsae_send_enc_imsg(dgst, dgst_len, inv, rp, eckey)); EC_KEY_METHOD_get_sign(ecdsa_default, NULL, NULL, &psign_sig); return (psign_sig(dgst, dgst_len, inv, rp, eckey)); } int ecdsae_sign_setup(EC_KEY *eckey, BN_CTX *ctx, BIGNUM **kinv, BIGNUM **r) { int (*psign_setup)(EC_KEY *eckey, BN_CTX *ctx_in, BIGNUM **kinvp, BIGNUM **rp); log_debug("debug: %s: %s", proc_name(smtpd_process), __func__); EC_KEY_METHOD_get_sign(ecdsa_default, NULL, &psign_setup, NULL); return (psign_setup(eckey, ctx, kinv, r)); } int ecdsae_verify(int type, const unsigned char *dgst, int dgst_len, const unsigned char *sigbuf, int sig_len, EC_KEY *eckey) { int (*verify)(int type, const unsigned char *dgst, int dgst_len, const unsigned char *sigbuf, int sig_len, EC_KEY *eckey); log_debug("debug: %s: %s", proc_name(smtpd_process), __func__); EC_KEY_METHOD_get_verify(ecdsa_default, &verify, NULL); return (verify(type, dgst, dgst_len, sigbuf, sig_len, eckey)); } int ecdsae_do_verify(const unsigned char *dgst, int dgst_len, const ECDSA_SIG *sig, EC_KEY *eckey) { int (*pverify_sig)(const unsigned char *dgst, int dgst_len, const ECDSA_SIG *sig, EC_KEY *eckey); log_debug("debug: %s: %s", proc_name(smtpd_process), __func__); EC_KEY_METHOD_get_verify(ecdsa_default, NULL, &pverify_sig); return (pverify_sig(dgst, dgst_len, sig, eckey)); } #endif static void rsa_engine_init(void) { ENGINE *e; const char *errstr, *name; if ((rsae_method = RSA_meth_new("RSA privsep engine", 0)) == NULL) { errstr = "RSA_meth_new"; goto fail; } RSA_meth_set_pub_enc(rsae_method, rsae_pub_enc); RSA_meth_set_pub_dec(rsae_method, rsae_pub_dec); RSA_meth_set_priv_enc(rsae_method, rsae_priv_enc); RSA_meth_set_priv_dec(rsae_method, rsae_priv_dec); RSA_meth_set_mod_exp(rsae_method, rsae_mod_exp); RSA_meth_set_bn_mod_exp(rsae_method, rsae_bn_mod_exp); RSA_meth_set_init(rsae_method, rsae_init); RSA_meth_set_finish(rsae_method, rsae_finish); RSA_meth_set_keygen(rsae_method, rsae_keygen); if ((e = ENGINE_get_default_RSA()) == NULL) { if ((e = ENGINE_new()) == NULL) { errstr = "ENGINE_new"; goto fail; } if (!ENGINE_set_name(e, RSA_meth_get0_name(rsae_method))) { errstr = "ENGINE_set_name"; goto fail; } if ((rsa_default = RSA_get_default_method()) == NULL) { errstr = "RSA_get_default_method"; goto fail; } } else if ((rsa_default = ENGINE_get_RSA(e)) == NULL) { errstr = "ENGINE_get_RSA"; goto fail; } if ((name = ENGINE_get_name(e)) == NULL) name = "unknown RSA engine"; log_debug("debug: %s: using %s", __func__, name); if (RSA_meth_get_mod_exp(rsa_default) == NULL) RSA_meth_set_mod_exp(rsae_method, NULL); if (RSA_meth_get_bn_mod_exp(rsa_default) == NULL) RSA_meth_set_bn_mod_exp(rsae_method, NULL); if (RSA_meth_get_keygen(rsa_default) == NULL) RSA_meth_set_keygen(rsae_method, NULL); RSA_meth_set_flags(rsae_method, RSA_meth_get_flags(rsa_default) | RSA_METHOD_FLAG_NO_CHECK); RSA_meth_set0_app_data(rsae_method, RSA_meth_get0_app_data(rsa_default)); if (!ENGINE_set_RSA(e, rsae_method)) { errstr = "ENGINE_set_RSA"; goto fail; } if (!ENGINE_set_default_RSA(e)) { errstr = "ENGINE_set_default_RSA"; goto fail; } return; fail: ssl_error(errstr); fatalx("%s", errstr); } #if defined(SUPPORT_ECDSA) static void ecdsa_engine_init(void) { ENGINE *e; const char *errstr, *name; if ((ecdsae_method = ECDSA_METHOD_new_temporary("ECDSA privsep engine", 0)) == NULL) { errstr = "ECDSA_METHOD_new_temporary"; goto fail; } ecdsae_method->ecdsa_do_sign = ecdsae_do_sign; ecdsae_method->ecdsa_sign_setup = ecdsae_sign_setup; ecdsae_method->ecdsa_do_verify = ecdsae_do_verify; if ((e = ENGINE_get_default_ECDSA()) == NULL) { if ((e = ENGINE_new()) == NULL) { errstr = "ENGINE_new"; goto fail; } if (!ENGINE_set_name(e, ecdsae_method->name)) { errstr = "ENGINE_set_name"; goto fail; } if ((ecdsa_default = ECDSA_get_default_method()) == NULL) { errstr = "ECDSA_get_default_method"; goto fail; } } else if ((ecdsa_default = ENGINE_get_ECDSA(e)) == NULL) { errstr = "ENGINE_get_ECDSA"; goto fail; } if ((name = ENGINE_get_name(e)) == NULL) name = "unknown ECDSA engine"; log_debug("debug: %s: using %s", __func__, name); if (!ENGINE_set_ECDSA(e, ecdsae_method)) { errstr = "ENGINE_set_ECDSA"; goto fail; } if (!ENGINE_set_default_ECDSA(e)) { errstr = "ENGINE_set_default_ECDSA"; goto fail; } return; fail: ssl_error(errstr); fatalx("%s", errstr); } #else static void ecdsa_engine_init(void) { ENGINE *e; const char *errstr, *name; if ((ecdsae_method = EC_KEY_METHOD_new(NULL)) == NULL) { errstr = "EC_KEY_new"; goto fail; } EC_KEY_METHOD_set_keygen(ecdsae_method, ecdsae_keygen); EC_KEY_METHOD_set_compute_key(ecdsae_method, ecdsae_compute_key); EC_KEY_METHOD_set_sign(ecdsae_method, ecdsae_sign, ecdsae_sign_setup, ecdsae_do_sign); EC_KEY_METHOD_set_verify(ecdsae_method, ecdsae_verify, ecdsae_do_verify); if ((e = ENGINE_get_default_EC()) == NULL) { if ((e = ENGINE_new()) == NULL) { errstr = "ENGINE_new"; goto fail; } if (!ENGINE_set_name(e, "ECDSA privsep engine")) { errstr = "ENGINE_set_name"; goto fail; } if ((ecdsa_default = EC_KEY_get_default_method()) == NULL) { errstr = "EC_KEY_get_default_method"; goto fail; } } else if ((ecdsa_default = ENGINE_get_EC(e)) == NULL) { errstr = "ENGINE_get_EC"; goto fail; } if ((name = ENGINE_get_name(e)) == NULL) name = "unknown ECDSA engine"; log_debug("debug: %s: using %s", __func__, name); if (!ENGINE_set_EC(e, ecdsae_method)) { errstr = "ENGINE_set_EC"; goto fail; } if (!ENGINE_set_default_EC(e)) { errstr = "ENGINE_set_default_EC"; goto fail; } return; fail: ssl_error(errstr); fatalx("%s", errstr); } #endif void ca_engine_init(void) { rsa_engine_init(); ecdsa_engine_init(); }
107813.c
/* mcheck.ale */ #include "stddata.h" #include "mcheck.h" #include "display.h" #include "disc.h" #include "tags.h" static int recursive_macro_call; #define addMSG(x,y) add_new_string(x,MESSAGE);y=MESSAGE->aupb static void init_msg(void){ addMSG("rule %p: unbounded macro substitution",recursive_macro_call); } #undef addMSG static void skipSource(void){ int par[2]; if(Qcons(par)){;} else if((par[0]=Dlwb,Q(par))||(par[0]=Dupb,Q(par))|| (par[0]=Dvlwb,Q(par))||(par[0]=Dvupb,Q(par))||(par[0]=Dcalibre,Q(par))){ mustQtag(par);} else if((par[0]=Dsub,Q(par))){mustQtag(par);skipSource();par[0]=Dbus; mustQ(par);if(Qtag(par)){;}else{mustQcons(par);}} else if((par[0]=Dnoarg,Q(par))){;} else{mustQtag(par);} } static void skipAffixes(void){ int par[1];next:par[0]=Dplus;if(Q(par)){skipSource();goto next;} } static void classification(void),alternative(void), altSequence(void),member(void),checkMacroRule(int *a); static void ruleBody(void){ int par[1]; par[0]=Dlabel;if(Q(par)){mustQtag(par);} par[0]=Dlocal;if(Q(par)){par[0]=Dcolon;Qskip(par);} par[0]=Dbox;if(Q(par)){par[0]=Dbox;Qskip(par);classification();} else{altSequence();} } static void classification(void){ int par[1];nxt: par[0]=Darea;mustQ(par);par[0]=Darea;Qskip(par);par[0]=Dcomma;mustQ(par); alternative();par[0]=Dsemicolon;if(Q(par)){goto nxt;} } static void alternative(void){ int par[1];nxt: member();par[0]=Dcomma;if(Q(par)){goto nxt;} } static void altSequence(void){ int par[1];nxt: alternative();par[0]=Dsemicolon;if(Q(par)){goto nxt;} } static void member(void){ int par[2];int tag; par[0]=Dopen;if(Q(par)){ruleBody();par[0]=Dclose;mustQ(par);return;} par[0]=Dextension;if(Q(par)){par[0]=Dextension;Qskip(par);return;} par[0]=Djump;if(Q(par)){mustQtag(par);return;} par[0]=Dplus;if(Q(par)){return;} par[0]=Dminus;if(Q(par)){return;} mustQtag(par);tag=par[0];par[1]=rmacro;if(isTagFlag(par)){ par[0]=tag;checkMacroRule(par);}skipAffixes(); } static void checkMacroRule(int *a){ /* >tag */ int par[3];int dpos,dnum,mp,mn; par[0]=a[0];par[1]=rmchecked;if(isTagFlag(par)){return;} par[0]=a[0];par[1]=rmchecking;if(isTagFlag(par)){ par[0]=recursive_macro_call;par[1]=a[0];Error(2,par); par[0]=a[0];par[1]=rmchecking;clearTagFlag(par); par[0]=a[0];par[1]=rmchecked;setTagFlag(par); return;} par[0]=a[0];par[1]=rmchecking;setTagFlag(par);saveDiscPosition(par); dpos=par[0];dnum=par[1];par[0]=a[0];searchMacroRule(par); mp=par[1];mn=par[2];par[0]=mp;par[1]=mn;restoreDiscPosition(par); ruleBody();par[0]=a[0];par[1]=rmchecking;clearTagFlag(par); par[0]=a[0];par[1]=rmchecked;setTagFlag(par);par[0]=dpos;par[1]=dnum; restoreDiscPosition(par); } void mCheckMacroRules(void){ int par[3];int tag; tag=0;nxt:par[0]=tag;if(nextMacroRule(par)){tag=par[0]; checkMacroRule(par);goto nxt;} } /* --------------------------------------------- */ void initialize_mcheck(void){ init_msg(); } /* EOF */
6157.c
#include <getopt.h> #include <unistd.h> #include <stdlib.h> #include <stdio.h> #include <assert.h> #include <string.h> #include "banking.h" #include "labdefs.h" #include "util.h" int parent_work(IOHandle *handle) { bank_robbery(handle, handle->proc_num - 1); Message stop; stop.s_header.s_magic = MESSAGE_MAGIC; stop.s_header.s_type = STOP; stop.s_header.s_local_time = get_physical_time(); int rc = send_multicast(handle, &stop); if( rc != 0 ) return rc; return 0; } int parent_atexit(IOHandle *handle){ AllHistory all; all.s_history_len = handle->proc_num - 1; Message msg; for(local_id i = 1; i < handle->proc_num; i++){ int rc = receive(handle, i, &msg); if( rc != 0 ) return 1; memcpy(&all.s_history[i - 1], msg.s_payload, msg.s_header.s_payload_len); } print_history(&all); return 0; } void update_balance(BalanceHistory *history, TransferOrder *order){ timestamp_t current_time = get_physical_time(); balance_t prev; prev = history->s_history_len == 0 ? 0 : history->s_history[history->s_history_len - 1].s_balance; timestamp_t new_len = current_time + 1; if( new_len > 1 ) { for(timestamp_t t = history->s_history_len; t < new_len; t++){ history->s_history[t] = history->s_history[t - 1]; history->s_history[t].s_time++; } } history->s_history[current_time].s_time = current_time; history->s_history[current_time].s_balance_pending_in = 0; history->s_history[current_time].s_balance = order->s_src == history->s_id ? prev - order->s_amount : prev + order->s_amount; history->s_history_len = current_time + 1; } int child_work(IOHandle *handle, void *data) { assert(data != NULL); BalanceHistory *balances = (BalanceHistory*)data; BalanceHistory *history = &balances[handle->src_pid]; char buff[MAX_PAYLOAD_LEN]; // Receive transfer message Message msg; TransferOrder order; memset(&msg, 0, sizeof msg); memset(&order, 0, sizeof order); while( 1 ){ int rc = receive_any(handle, &msg); if( rc != 0 ) return 1; switch(msg.s_header.s_type){ case TRANSFER: memcpy(&order, msg.s_payload, msg.s_header.s_payload_len); if( order.s_src == handle->src_pid ) { snprintf(buff, MAX_PAYLOAD_LEN, log_transfer_out_fmt, get_physical_time(), handle->src_pid, order.s_amount, order.s_dst); log_event(buff); update_balance(history, &order); // Send transfer message to dest rc = send(handle, order.s_dst, &msg); if( rc != 0 ) return 1; }else{ // Send ACK message msg.s_header.s_type = ACK; msg.s_header.s_local_time = get_physical_time(); msg.s_header.s_payload_len = 0; snprintf(buff, MAX_PAYLOAD_LEN, log_transfer_in_fmt, get_physical_time(), handle->src_pid, order.s_amount, order.s_src); log_event(buff); rc = send(handle, 0, &msg); if( rc != 0 ) return 1; update_balance(history, &order); } break; case STOP: order.s_src = 0; order.s_dst = handle->src_pid; order.s_amount = 0; update_balance(history, &order); return 0; break; } } return 0; } int child_atexit(IOHandle *handle, void *data){ BalanceHistory *balances = (BalanceHistory*)data; BalanceHistory *history = &balances[handle->src_pid]; Message msg; msg.s_header.s_magic = MESSAGE_MAGIC; msg.s_header.s_type = BALANCE_HISTORY; msg.s_header.s_local_time = get_physical_time(); msg.s_header.s_payload_len = sizeof *history - (MAX_T + 1 - history->s_history_len) * sizeof *history->s_history; memcpy(msg.s_payload, history, msg.s_header.s_payload_len); int rc = send(handle, 0, &msg); return rc; } void transfer(void * parent_data, local_id src, local_id dst, balance_t amount) { Message msg; memset(&msg, 0, sizeof msg); msg.s_header.s_magic = MESSAGE_MAGIC; msg.s_header.s_type = TRANSFER; msg.s_header.s_local_time = get_physical_time(); TransferOrder order; order.s_src = src; order.s_dst = dst; order.s_amount = amount; msg.s_header.s_payload_len = sizeof order; memcpy(msg.s_payload, &order, msg.s_header.s_payload_len); int rc = send(parent_data, src, &msg); if( rc != 0 ) exit(1); rc = receive(parent_data, dst, &msg); if( rc != 0 ) exit(1); } int main(int argc, char * argv[]) { int rc = 0; int proc_num = get_proc_num_from_args(argc, argv); if( proc_num < 0 ) return 1; if( argc - optind < proc_num - 1 ) return 1; BalanceHistory *balances = calloc(1, proc_num * sizeof *balances); if( balances == NULL ) return 2; TransferOrder order; memset(&order, 0, sizeof order); for(int i = 1; i < proc_num; i++){ balances[i].s_id = i; order.s_dst = i; order.s_amount = atoi(argv[optind + i - 1]); balances[i].s_history_len = 0; update_balance(&balances[i], &order); } IOHandle handle; rc = create_handle(proc_num, &handle); if( rc != 0 ) return rc; rc = create_pipes(&handle); if( rc != 0 ) return rc; int is_parent = spawn_childs(&handle); if( is_parent < 0 ) return 2; if( is_parent ){ rc = parent(&handle); }else{ rc = child(&handle, balances); } free(handle.channel_table); free(balances); return rc; }
10981.c
#include<stdio.h> #include<stdlib.h> #include<sched.h> #include<unistd.h> #include<errno.h> #include<string.h> int err_chk(int call_value, const char* msg) { if(call_value<0) { perror(msg); exit(EXIT_FAILURE); } else { return call_value; } } int main() { printf("Enter PID:\n"); pid_t input_pid; scanf("%d", &input_pid); int policy = sched_getscheduler(input_pid); err_chk(policy, "Error getting policy!"); printf("Current Policy for pid %d: ", input_pid); switch (policy) { case SCHED_FIFO: printf("SCHED_FIFO"); break; case SCHED_OTHER: printf("SCHED_OTHER"); break; case SCHED_RR: printf("SCHED_RR"); break; // case SCHED_BATCH: // printf("SCHED_BATCH"); // break; // case SCHED_IDLE: // printf("SCHED_IDLE"); // break; // case SCHED_DEADLINE: // printf("SCHED_DEADLINE"); // break default: break; } struct sched_param prio; err_chk(sched_getparam(input_pid, &prio), "Error getting priority!"); printf("\n"); printf("Current priority: %d\n", prio.sched_priority); prio.sched_priority++; printf("Changing current priority to SCHED_FIFO...\n"); err_chk(sched_setscheduler(input_pid, SCHED_FIFO, &prio), "Error changing policy!"); }
98685.c
/** * @file lv_group.c * */ /********************* * INCLUDES *********************/ #include "lv_group.h" #if USE_LV_GROUP != 0 #include <stddef.h> //#include <stdio.h> /********************* * DEFINES *********************/ /********************** * TYPEDEFS **********************/ /********************** * STATIC PROTOTYPES **********************/ static void style_mod_def(lv_style_t * style); static void style_mod_def_new(lv_style_t * style); /********************** * STATIC VARIABLES **********************/ /********************** * MACROS **********************/ /********************** * GLOBAL FUNCTIONS **********************/ /** * Create a new object group * @return pointer to the new object group */ lv_group_t * lv_group_create(void) { lv_group_t * group = lv_mem_alloc(sizeof(lv_group_t)); lv_ll_init(&group->obj_ll, sizeof(lv_obj_t *)); group->style_mod = style_mod_def; group->obj_focus = NULL; group->frozen = 0; return group; } /** * Delete a group object * @param group pointer to a group */ void lv_group_del(lv_group_t * group) { lv_ll_clear(&(group->obj_ll)); lv_mem_free(group); } /** * Add an object to a group * @param group pointer to a group * @param obj pointer to an object to add */ void lv_group_add_obj(lv_group_t * group, lv_obj_t * obj) { obj->group_p = group; lv_obj_t ** next = lv_ll_ins_tail(&group->obj_ll); *next = obj; /* If the head and the tail is equal then there is only one object in the linked list. * In this case automatically activate it*/ if(lv_ll_get_head(&group->obj_ll) == next) { lv_group_focus_next(group); } } /** * Remove an object from its group * @param obj pointer to an object to remove */ void lv_group_remove_obj(lv_obj_t * obj) { lv_group_t * g = obj->group_p; if(g == NULL) return; /*Search the object and remove it from its group */ lv_obj_t ** i; LL_READ(g->obj_ll, i) { if(*i == obj) { lv_ll_rem(&g->obj_ll, i); lv_mem_free(i); obj->group_p = NULL; } } if(*g->obj_focus == obj) { g->obj_focus = NULL; lv_group_focus_next(g); } } /** * Focus on an object (defocus the current) * @param obj pointer to an object to focus on */ void lv_group_focus_obj(lv_obj_t * obj) { lv_group_t * g = obj->group_p; if(g == NULL) return; if(g->frozen != 0) return; lv_obj_t ** i; LL_READ(g->obj_ll, i) { if(*i == obj) { if(g->obj_focus != NULL) { (*g->obj_focus)->signal_func(*g->obj_focus, LV_SIGNAL_DEFOCUS, NULL); lv_obj_invalidate(*g->obj_focus); } g->obj_focus = i; if(g->obj_focus != NULL){ (*g->obj_focus)->signal_func(*g->obj_focus, LV_SIGNAL_FOCUS, NULL); lv_obj_invalidate(*g->obj_focus); } break; } } } /** * Focus the next object in a group (defocus the current) * @param group pointer to a group */ void lv_group_focus_next(lv_group_t * group) { if(group->frozen) return; if(group->obj_focus) { (*group->obj_focus)->signal_func(*group->obj_focus, LV_SIGNAL_DEFOCUS, NULL); lv_obj_invalidate(*group->obj_focus); } lv_obj_t ** obj_next; if(group->obj_focus == NULL) obj_next = lv_ll_get_head(&group->obj_ll); else obj_next = lv_ll_get_next(&group->obj_ll, group->obj_focus); if(obj_next == NULL) obj_next = lv_ll_get_head(&group->obj_ll); group->obj_focus = obj_next; if(group->obj_focus){ (*group->obj_focus)->signal_func(*group->obj_focus, LV_SIGNAL_FOCUS, NULL); lv_obj_invalidate(*group->obj_focus); if(group->focus_cb) group->focus_cb(group); } } /** * Focus the previous object in a group (defocus the current) * @param group pointer to a group */ void lv_group_focus_prev(lv_group_t * group) { if(group->frozen) return; if(group->obj_focus) { (*group->obj_focus)->signal_func(*group->obj_focus, LV_SIGNAL_DEFOCUS, NULL); lv_obj_invalidate(*group->obj_focus); } lv_obj_t ** obj_next; if(group->obj_focus == NULL) obj_next = lv_ll_get_tail(&group->obj_ll); else obj_next = lv_ll_get_prev(&group->obj_ll, group->obj_focus); if(obj_next == NULL) obj_next = lv_ll_get_tail(&group->obj_ll); group->obj_focus = obj_next; if(group->obj_focus != NULL){ (*group->obj_focus)->signal_func(*group->obj_focus, LV_SIGNAL_FOCUS, NULL); lv_obj_invalidate(*group->obj_focus); if(group->focus_cb) group->focus_cb(group); } } /** * Do not let to change the focus from the current object * @param group pointer to a group * @param en true: freeze, false: release freezing (normal mode) */ void lv_group_focus_freeze(lv_group_t * group, bool en) { if(en == false) group->frozen = 0; else group->frozen = 1; } /** * Send a control character to the focuses object of a group * @param group pointer to a group * @param c a character (use LV_GROUP_KEY_.. to navigate) */ void lv_group_send_data(lv_group_t * group, uint32_t c) { lv_obj_t * act = lv_group_get_focused(group); if(act == NULL) return; act->signal_func(act, LV_SIGNAL_CONTROLL, &c); } /** * Set a function for a group which will modify the object's style if it is in focus * @param group pointer to a group * @param style_mod_func the style modifier function pointer */ void lv_group_set_style_mod_cb(lv_group_t * group,lv_group_style_mod_func_t style_mod_func) { group->style_mod = style_mod_func; if(group->obj_focus != NULL) lv_obj_invalidate(*group->obj_focus); } /** * Set a function for a group which will be called when a new object is focused * @param group pointer to a group * @param focus_cb the call back function or NULL if unused */ void lv_group_set_focus_cb(lv_group_t * group, lv_group_focus_cb_t focus_cb) { group->focus_cb = focus_cb; } /** * Modify a style with the set 'style_mod' function. The input style remains unchanged. * @param group pointer to group * @param style pointer to a style to modify * @return a copy of the input style but modified with the 'style_mod' function */ lv_style_t * lv_group_mod_style(lv_group_t * group, const lv_style_t * style) { lv_style_copy(&group->style_tmp, style); if(group->style_mod != NULL) group->style_mod(&group->style_tmp); else style_mod_def(&group->style_tmp); return &group->style_tmp; } /** * Get the focused object or NULL if there isn't one * @param group pointer to a group * @return pointer to the focused object */ lv_obj_t * lv_group_get_focused(lv_group_t * group) { if(group == NULL) return NULL; if(group->obj_focus == NULL) return NULL; return *group->obj_focus; } /** * Get a the style modifier function of a group * @param group pointer to a group * @return pointer to the style modifier function */ lv_group_style_mod_func_t lv_group_get_style_mod_cb(lv_group_t * group) { return group->style_mod ; } /** * Get the focus callback function of a group * @param group pointer to a group * @return the call back function or NULL if not set */ lv_group_focus_cb_t lv_group_get_focus_cb(lv_group_t * group) { return group->focus_cb; } /********************** * STATIC FUNCTIONS **********************/ /** * Default style modifier function * @param style pointer to a style to modify. (Typically group.style_tmp) It will be OVERWRITTEN. */ static void style_mod_def(lv_style_t * style) { #if LV_COLOR_DEPTH != 1 /*Make the style to be a little bit orange*/ style->body.border.opa = LV_OPA_COVER; style->body.border.color = LV_COLOR_ORANGE; /*If not empty or has border then emphasis the border*/ if(style->body.empty == 0 || style->body.border.width != 0) style->body.border.width = LV_DPI / 20; style->body.main_color = lv_color_mix(style->body.main_color, LV_COLOR_ORANGE, LV_OPA_70); style->body.grad_color = lv_color_mix(style->body.grad_color, LV_COLOR_ORANGE, LV_OPA_70); style->body.shadow.color = lv_color_mix(style->body.shadow.color, LV_COLOR_ORANGE, LV_OPA_60); style->text.color = lv_color_mix(style->text.color, LV_COLOR_ORANGE, LV_OPA_70); #else style->body.border.opa = LV_OPA_COVER; style->body.border.color = LV_COLOR_BLACK; style->body.border.width = 3; #endif } static void style_mod_def_new(lv_style_t * style) { #if LV_COLOR_DEPTH != 1 /*Make the style to be a little bit orange*/ // style->body.border.opa = LV_OPA_COVER; // style->body.border.color = LV_COLOR_ORANGE; // // /*If not empty or has border then emphasis the border*/ // if(style->body.empty == 0 || style->body.border.width != 0) style->body.border.width = LV_DPI / 20; // // style->body.main_color = lv_color_mix(style->body.main_color, LV_COLOR_ORANGE, LV_OPA_70); // style->body.grad_color = lv_color_mix(style->body.grad_color, LV_COLOR_ORANGE, LV_OPA_70); // style->body.shadow.color = lv_color_mix(style->body.shadow.color, LV_COLOR_ORANGE, LV_OPA_60); // // style->text.color = lv_color_mix(style->text.color, LV_COLOR_ORANGE, LV_OPA_70); #else style->body.border.opa = LV_OPA_COVER; style->body.border.color = LV_COLOR_BLACK; style->body.border.width = 3; #endif } void lv_group_remove_all (lv_group_t* g1) { // lv_group_t* g1=NULL; lv_obj_t ** obj; LL_READ(g1->obj_ll, obj) { lv_obj_del(*obj); } } #endif /*USE_LV_GROUP != 0*/
201730.c
// Copyright 2012 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build darwin dragonfly freebsd linux nacl netbsd openbsd solaris windows #include "runtime.h" #include "array.h" #include "arch.h" #include "malloc.h" extern Slice envs; const byte* runtime_getenv(const char *s) { int32 i, j; intgo len; const byte *v, *bs; String* envv; int32 envc; bs = (const byte*)s; len = runtime_findnull(bs); envv = (String*)envs.__values; envc = envs.__count; for(i=0; i<envc; i++){ if(envv[i].len <= len) continue; v = (const byte*)envv[i].str; for(j=0; j<len; j++) if(bs[j] != v[j]) goto nomatch; if(v[len] != '=') goto nomatch; return v+len+1; nomatch:; } return nil; }
289834.c
/* * Copyright 2012-2017 Katherine Flavel * * See LICENCE for the full copyright terms. */ #include <assert.h> #include <limits.h> #include <stdlib.h> #include <string.h> #include <cl/tree.h> #include "internal.h" struct trie * trie_add(struct trie **trie, const char *s, const struct cl_command *command) { assert(trie != NULL); assert(s != NULL); assert(*s == '\0' || strcspn(s, "\t\v\f\r\n") != 0); assert(command != NULL); if (*trie == NULL) { size_t i; *trie = malloc(sizeof **trie); if (*trie == NULL) { return NULL; } (*trie)->command = NULL; /* TODO: assert(SIZE_MAX > UCHAR_MAX); */ for (i = 0; i < sizeof (*trie)->edge / sizeof *(*trie)->edge; i++) { (*trie)->edge[i] = NULL; } } if (*s == '\0') { /* * A command may be already populated within the trie in the case of * different usages given for the same path. If so, these are required * to have the same callback and fields, and modes which do not overlap * so that we may intersect our incoming command with what is present. */ if ((*trie)->command == NULL) { (*trie)->command = malloc(sizeof *(*trie)->command); if ((*trie)->command == NULL) { return NULL; } (*trie)->command->command = command->command; (*trie)->command->modes = 0; (*trie)->command->fields = command->fields; (*trie)->command->callback = command->callback; } assert(0 == strcmp((*trie)->command->command, command->command)); /* by definition */ assert(0 == ((*trie)->command->modes & command->modes)); assert((*trie)->command->callback == command->callback); assert((*trie)->command->fields == command->fields); (*trie)->command->modes |= command->modes; return *trie; } return trie_add(&(*trie)->edge[(unsigned char) *s], s + 1, command); } const struct trie * trie_walk(const struct trie *trie, const char *s, size_t len) { assert(trie != NULL); assert(s != NULL); assert(len > 0); do { trie = trie->edge[(unsigned char) *s]; if (trie == NULL) { return NULL; } s++; len--; } while (len > 0); return trie; } static const struct trie * trie_next(struct cl_peer *p, const struct trie *trie, int mode, char c, const struct trie **prev) { size_t i; assert(trie != NULL); assert(p->tree->visible != NULL); assert(prev != NULL); if (trie->command != NULL && p->tree->visible(p, mode, trie->command->modes)) { assert(trie->command->command != NULL); if (*prev == NULL) { return trie; } if (*prev == trie) { *prev = NULL; } } /* TODO: assert(SIZE_MAX > UCHAR_MAX); */ for (i = 0; i < sizeof trie->edge / sizeof *trie->edge; i++) { const struct trie *next; if (trie->edge[i] == NULL) { continue; } /* TODO: i don't like that this has knowledge of a specific char */ if (i == c) { assert(trie->edge[i] != NULL); return trie->edge[i]; } next = trie_next(p, trie->edge[i], mode, c, prev); if (next != NULL) { return next; } } return NULL; } const struct trie * trie_cycle(struct cl_peer *p, const struct trie *trie, int mode, char c, const struct trie *prev) { const struct trie *next; assert(p != NULL); assert(p->tree != NULL); assert(p->tree->visible != NULL); assert(trie != NULL); next = trie_next(p, trie, mode, c, &prev); if (next != NULL) { return next; } return trie_next(p, trie, mode, c, &next); } const struct trie * trie_run(struct cl_peer *p, const struct trie *trie, int mode, char c) { assert(p != NULL); assert(trie != NULL); (void) c; trie = trie_cycle(p, trie, mode, ' ', NULL); if (trie == NULL) { return NULL; } if (trie->command != NULL && trie != trie_cycle(p, trie, mode, ' ', trie)) { return NULL; } return trie; } void trie_help(struct cl_peer *p, const struct trie *trie, int mode) { size_t i; assert(p != NULL); assert(p->tree != NULL); assert(p->tree->commands != NULL); assert(trie != NULL); if (trie->command != NULL) { size_t i; for (i = 0; i < p->tree->command_count; i++) { assert(trie->command->command != NULL); assert(p->tree->commands[i].command != NULL); if (0 != strcmp(p->tree->commands[i].command, trie->command->command)) { continue; } if (!p->tree->visible(p, mode, p->tree->commands[i].modes)) { continue; } if (p->tree->commands[i].usage == NULL) { cl_printf(p, " %-18s\n", p->tree->commands[i].command); } else { cl_printf(p, " %-18s - %s\n", p->tree->commands[i].command, p->tree->commands[i].usage); } } } /* TODO: assert(SIZE_MAX > UCHAR_MAX); */ for (i = 0; i < sizeof trie->edge / sizeof *trie->edge; i++) { if (trie->edge[i] == NULL) { continue; } trie_help(p, trie->edge[i], mode); } }
226076.c
/* * Copyright © 2021 Google, Inc. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice (including the next * paragraph) shall be included in all copies or substantial portions of the * Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND 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 <assert.h> #include <ctype.h> #include <stdio.h> #include <stdlib.h> #include "emu.h" #include "util.h" /* * Emulator Registers: * * Handles access to GPR, GPU, control, and pipe registers. */ static bool is_draw_state_control_reg(unsigned n) { char *reg_name = afuc_control_reg_name(n); if (!reg_name) return false; bool ret = !!strstr(reg_name, "DRAW_STATE"); free(reg_name); return ret; } uint32_t emu_get_control_reg(struct emu *emu, unsigned n) { assert(n < ARRAY_SIZE(emu->control_regs.val)); if (is_draw_state_control_reg(n)) return emu_get_draw_state_reg(emu, n); return emu->control_regs.val[n]; } void emu_set_control_reg(struct emu *emu, unsigned n, uint32_t val) { EMU_CONTROL_REG(PACKET_TABLE_WRITE); EMU_CONTROL_REG(PACKET_TABLE_WRITE_ADDR); EMU_CONTROL_REG(REG_WRITE); EMU_CONTROL_REG(REG_WRITE_ADDR); assert(n < ARRAY_SIZE(emu->control_regs.val)); BITSET_SET(emu->control_regs.written, n); emu->control_regs.val[n] = val; /* Some control regs have special action on write: */ if (n == emu_reg_offset(&PACKET_TABLE_WRITE)) { unsigned write_addr = emu_get_reg32(emu, &PACKET_TABLE_WRITE_ADDR); assert(write_addr < ARRAY_SIZE(emu->jmptbl)); emu->jmptbl[write_addr] = val; emu_set_reg32(emu, &PACKET_TABLE_WRITE_ADDR, write_addr + 1); } else if (n == emu_reg_offset(&REG_WRITE)) { uint32_t write_addr = emu_get_reg32(emu, &REG_WRITE_ADDR); /* Upper bits seem like some flags, not part of the actual * register offset.. not sure what they mean yet: */ uint32_t flags = write_addr >> 16; write_addr &= 0xffff; emu_set_gpu_reg(emu, write_addr++, val); emu_set_reg32(emu, &REG_WRITE_ADDR, write_addr | (flags << 16)); } else if (is_draw_state_control_reg(n)) { emu_set_draw_state_reg(emu, n, val); } } static uint32_t emu_get_pipe_reg(struct emu *emu, unsigned n) { assert(n < ARRAY_SIZE(emu->pipe_regs.val)); return emu->pipe_regs.val[n]; } static void emu_set_pipe_reg(struct emu *emu, unsigned n, uint32_t val) { EMU_PIPE_REG(NRT_DATA); EMU_PIPE_REG(NRT_ADDR); assert(n < ARRAY_SIZE(emu->pipe_regs.val)); BITSET_SET(emu->pipe_regs.written, n); emu->pipe_regs.val[n] = val; /* Some pipe regs have special action on write: */ if (n == emu_reg_offset(&NRT_DATA)) { uintptr_t addr = emu_get_reg64(emu, &NRT_ADDR); emu_mem_write_dword(emu, addr, val); emu_set_reg64(emu, &NRT_ADDR, addr + 4); } } static uint32_t emu_get_gpu_reg(struct emu *emu, unsigned n) { if (n >= ARRAY_SIZE(emu->gpu_regs.val)) return 0; assert(n < ARRAY_SIZE(emu->gpu_regs.val)); return emu->gpu_regs.val[n]; } void emu_set_gpu_reg(struct emu *emu, unsigned n, uint32_t val) { if (n >= ARRAY_SIZE(emu->gpu_regs.val)) return; assert(n < ARRAY_SIZE(emu->gpu_regs.val)); BITSET_SET(emu->gpu_regs.written, n); emu->gpu_regs.val[n] = val; } static bool is_pipe_reg_addr(unsigned regoff) { return regoff > 0xffff; } static unsigned get_reg_addr(struct emu *emu) { switch (emu->data_mode) { case DATA_PIPE: case DATA_ADDR: return REG_ADDR; case DATA_USRADDR: return REG_USRADDR; default: unreachable("bad data_mode"); return 0; } } /* Handle reads for special streaming regs: */ static uint32_t emu_get_fifo_reg(struct emu *emu, unsigned n) { /* TODO the fifo regs are slurping out of a FIFO that the hw is filling * in parallel.. we can use `struct emu_queue` to emulate what is actually * happening more accurately */ if (n == REG_MEMDATA) { /* $memdata */ EMU_CONTROL_REG(MEM_READ_DWORDS); EMU_CONTROL_REG(MEM_READ_ADDR); unsigned read_dwords = emu_get_reg32(emu, &MEM_READ_DWORDS); uintptr_t read_addr = emu_get_reg64(emu, &MEM_READ_ADDR); if (read_dwords > 0) { emu_set_reg32(emu, &MEM_READ_DWORDS, read_dwords - 1); emu_set_reg64(emu, &MEM_READ_ADDR, read_addr + 4); } return emu_mem_read_dword(emu, read_addr); } else if (n == REG_REGDATA) { /* $regdata */ EMU_CONTROL_REG(REG_READ_DWORDS); EMU_CONTROL_REG(REG_READ_ADDR); unsigned read_dwords = emu_get_reg32(emu, &REG_READ_DWORDS); unsigned read_addr = emu_get_reg32(emu, &REG_READ_ADDR); /* I think if the fw doesn't write REG_READ_DWORDS before * REG_READ_ADDR, it just ends up with a single value written * into the FIFO that $regdata is consuming from: */ if (read_dwords > 0) { emu_set_reg32(emu, &REG_READ_DWORDS, read_dwords - 1); emu_set_reg32(emu, &REG_READ_ADDR, read_addr + 1); } return emu_get_gpu_reg(emu, read_addr); } else if (n == REG_DATA) { /* $data */ do { uint32_t rem = emu->gpr_regs.val[REG_REM]; assert(rem >= 0); uint32_t val; if (emu_queue_pop(&emu->roq, &val)) { emu_set_gpr_reg(emu, REG_REM, --rem); return val; } /* If FIFO is empty, prompt for more input: */ printf("FIFO empty, input a packet!\n"); emu->run_mode = false; emu_main_prompt(emu); } while (true); } else { unreachable("not a FIFO reg"); return 0; } } static void emu_set_fifo_reg(struct emu *emu, unsigned n, uint32_t val) { if ((n == REG_ADDR) || (n == REG_USRADDR)) { emu->data_mode = (n == REG_ADDR) ? DATA_ADDR : DATA_USRADDR; /* Treat these as normal register writes so we can see * updated values in the output as we step thru the * instructions: */ emu->gpr_regs.val[n] = val; BITSET_SET(emu->gpr_regs.written, n); if (is_pipe_reg_addr(val)) { /* "void" pipe regs don't have a value to write, so just * treat it as writing zero to the pipe reg: */ if (afuc_pipe_reg_is_void(val >> 24)) emu_set_pipe_reg(emu, val >> 24, 0); emu->data_mode = DATA_PIPE; } } else if (n == REG_DATA) { unsigned reg = get_reg_addr(emu); unsigned regoff = emu->gpr_regs.val[reg]; if (is_pipe_reg_addr(regoff)) { /* writes pipe registers: */ assert(!(regoff & 0xfbffff)); /* If b18 is set, don't auto-increment dest addr.. and if we * do auto-increment, we only increment the high 8b * * Note that we bypass emu_set_gpr_reg() in this case because * auto-incrementing isn't triggering a write to "void" pipe * regs. */ if (!(regoff & 0x40000)) { emu->gpr_regs.val[reg] = regoff + 0x01000000; BITSET_SET(emu->gpr_regs.written, reg); } emu_set_pipe_reg(emu, regoff >> 24, val); } else { /* writes to gpu registers: */ emu_set_gpr_reg(emu, reg, regoff+1); emu_set_gpu_reg(emu, regoff, val); } } } uint32_t emu_get_gpr_reg(struct emu *emu, unsigned n) { assert(n < ARRAY_SIZE(emu->gpr_regs.val)); /* Handle special regs: */ switch (n) { case 0x00: return 0; case REG_MEMDATA: case REG_REGDATA: case REG_DATA: return emu_get_fifo_reg(emu, n); default: return emu->gpr_regs.val[n]; } } void emu_set_gpr_reg(struct emu *emu, unsigned n, uint32_t val) { assert(n < ARRAY_SIZE(emu->gpr_regs.val)); switch (n) { case REG_ADDR: case REG_USRADDR: case REG_DATA: emu_set_fifo_reg(emu, n, val); break; default: emu->gpr_regs.val[n] = val; BITSET_SET(emu->gpr_regs.written, n); break; } } /* * Control/pipe register accessor helpers: */ struct emu_reg_accessor { unsigned (*get_offset)(const char *name); uint32_t (*get)(struct emu *emu, unsigned n); void (*set)(struct emu *emu, unsigned n, uint32_t val); }; const struct emu_reg_accessor emu_control_accessor = { .get_offset = afuc_control_reg, .get = emu_get_control_reg, .set = emu_set_control_reg, }; const struct emu_reg_accessor emu_pipe_accessor = { .get_offset = afuc_pipe_reg, .get = emu_get_pipe_reg, .set = emu_set_pipe_reg, }; const struct emu_reg_accessor emu_gpu_accessor = { .get_offset = afuc_gpu_reg, .get = emu_get_gpu_reg, .set = emu_set_gpu_reg, }; unsigned emu_reg_offset(struct emu_reg *reg) { if (reg->offset == ~0) reg->offset = reg->accessor->get_offset(reg->name); return reg->offset; } uint32_t emu_get_reg32(struct emu *emu, struct emu_reg *reg) { return reg->accessor->get(emu, emu_reg_offset(reg)); } uint64_t emu_get_reg64(struct emu *emu, struct emu_reg *reg) { uint64_t val = reg->accessor->get(emu, emu_reg_offset(reg) + 1); val <<= 32; val |= reg->accessor->get(emu, emu_reg_offset(reg)); return val; } void emu_set_reg32(struct emu *emu, struct emu_reg *reg, uint32_t val) { reg->accessor->set(emu, emu_reg_offset(reg), val); } void emu_set_reg64(struct emu *emu, struct emu_reg *reg, uint64_t val) { reg->accessor->set(emu, emu_reg_offset(reg), val); reg->accessor->set(emu, emu_reg_offset(reg) + 1, val >> 32); }
308745.c
/* See LICENSE file for copyright and license details. */ #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <libparser.h> static void free_input(struct libparser_unit *node) { struct libparser_unit *next; for (; node; next = node->next, free(node), node = next) free_input(node->in); } static intmax_t calculate(struct libparser_unit *node, const char *line) { struct libparser_unit *next; intmax_t value = 0; int op; if (!node->rule) { next = node->in->next; value = calculate(node->in, line); free_input(next); } else if (!strcmp(node->rule, "DIGIT")) { value = (intmax_t)(line[node->start] - '0'); } else if (!strcmp(node->rule, "sign")) { value = !strcmp(node->in->rule, "SUB") ? -1 : +1; free(node->in); } else if (!strcmp(node->rule, "unsigned")) { value = 0; next = node->in; free(node); for (node = next; node; node = next) { next = node->next; value *= 10; value += calculate(node, line); } } else if (!strcmp(node->rule, "number")) { next = node->in->next; value = calculate(node->in, line); free(node); for (node = next; node; node = next) { next = node->next; value *= calculate(node, line); } } else if (!strcmp(node->rule, "value")) { next = node->in->next; value = calculate(node->in, line); if (next) value *= calculate(next, line); } else if (!strcmp(node->rule, "hyper1")) { next = node->in->next; value = calculate(node->in, line); free(node); node = next; while (node) { next = node->next; op = !strcmp(node->rule, "SUB") ? -1 : +1; free(node); node = next; next = node->next; if (op < 0) value -= calculate(node, line); else value += calculate(node, line); node = next; } } else if (!strcmp(node->rule, "hyper2")) { next = node->in->next; value = calculate(node->in, line); free(node); node = next; while (node) { next = node->next; op = !strcmp(node->rule, "DIV") ? -1 : +1; free(node); node = next; next = node->next; if (op < 0) value /= calculate(node, line); else value *= calculate(node, line); node = next; } } else if (node->rule[0] != '@') { abort(); } else if (node->in) { next = node->in->next; value = calculate(node->in, line); if (next) free_input(next); } free(node); return value; } int main(int argc, char *argv[]) { struct libparser_unit *input; char *line = NULL; size_t size = 0; ssize_t len; intmax_t res; int r; if (argc == 2 ? strcmp(argv[1], "--") : argc > 2) { fprintf(stderr, "usage: %s\n", argv[0]); return 1; } while ((len = getline(&line, &size, stdin)) >= 0) { if (len && line[len - 1] == '\n') line[--len] = '\0'; r = libparser_parse_file(libparser_rule_table, line, (size_t)len, &input); if (r < 0) { perror("libparser_parse_file"); continue; } else if (!input) { fprintf(stderr, "didn't find anything to parse\n"); continue; } else if (input->end != (size_t)len) { fprintf(stderr, "line could not be parsed, stopped at column %zu\n", input->end); free_input(input); continue; } else if (!r) { fprintf(stderr, "premature end of line\n"); free_input(input); continue; } res = calculate(input, line); printf("%ji\n", res); } free(line); return 0; }
992436.c
/* * ircd-hybrid: an advanced Internet Relay Chat Daemon(ircd). * m_testmask.c: Counts the birdies err local and remote clients. * * Copyright (C) 2005 by Diane Bruce * Coypright (C) 2005 ircd-hybrid team * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * 1.Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2.Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3.The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * $Id: m_testmask.c 33 2005-10-02 20:50:00Z knight $ */ #include "stdinc.h" #include "handlers.h" #include "client.h" #include "common.h" #include "irc_string.h" #include "ircd_defs.h" #include "ircd.h" #include "restart.h" #include "s_conf.h" #include "send.h" #include "msg.h" #include "hostmask.h" #include "numeric.h" #include "parse.h" #include "modules.h" static void mo_testmask(struct Client *, struct Client *, int, char *[]); struct Message testmask_msgtab = { "TESTMASK", 0, 0, 0, 0, MFLG_SLOW, 0, {m_unregistered, m_not_oper, m_ignore, m_ignore, mo_testmask, m_ignore} }; #ifndef STATIC_MODULES void _modinit(void) { mod_add_cmd(&testmask_msgtab); } void _moddeinit(void) { mod_del_cmd(&testmask_msgtab); } const char *_version = "$Revision: 33 $"; #endif /* mo_testmask() * * inputs - pointer to physical connection request is coming from * - pointer to source connection request is coming from * - parc arg count * - parv actual arguments * output - NONE * side effects - count up clients matching mask * i.e. /quote testmask user@host */ static void mo_testmask(struct Client *client_p, struct Client *source_p, int parc, char *parv[]) { char *given_host; char *given_user = parv[1]; int local_count = 0, remote_count = 0; dlink_node *ptr, *next_ptr; struct Client *target_p; if (parc < 2 || ((given_host = strchr(given_user, '@')) == NULL)) { sendto_one(source_p, ":%s NOTICE %s :usage: user@host", me.name, source_p->name); return; } *given_host++ = '\0'; DLINK_FOREACH_SAFE(ptr, next_ptr, global_client_list.head) { target_p = ptr->data; if (IsDead(target_p) || !IsClient(target_p)) continue; if (match(given_user, target_p->username) && match(given_host, target_p->host)) { if (MyConnect(target_p)) local_count++; else remote_count++; } } sendto_one(source_p, form_str(RPL_TESTMASK), me.name, source_p->name, given_user, given_host, local_count, remote_count); }
380841.c
/* * rtc-ds1307.c - RTC driver for some mostly-compatible I2C chips. * * Copyright (C) 2005 James Chapman (ds1337 core) * Copyright (C) 2006 David Brownell * Copyright (C) 2009 Matthias Fuchs (rx8025 support) * Copyright (C) 2012 Bertrand Achard (nvram access fixes) * * 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/module.h> #include <linux/init.h> #include <linux/slab.h> #include <linux/i2c.h> #include <linux/string.h> #include <linux/rtc.h> #include <linux/bcd.h> #include <linux/rtc/ds1307.h> /* * We can't determine type by probing, but if we expect pre-Linux code * to have set the chip up as a clock (turning on the oscillator and * setting the date and time), Linux can ignore the non-clock features. * That's a natural job for a factory or repair bench. */ enum ds_type { ds_1307, ds_1337, ds_1338, ds_1339, ds_1340, ds_1388, ds_3231, m41t00, mcp7941x, rx_8025, last_ds_type /* always last */ /* rs5c372 too? different address... */ }; /* RTC registers don't differ much, except for the century flag */ #define DS1307_REG_SECS 0x00 /* 00-59 */ # define DS1307_BIT_CH 0x80 # define DS1340_BIT_nEOSC 0x80 # define MCP7941X_BIT_ST 0x80 #define DS1307_REG_MIN 0x01 /* 00-59 */ #define DS1307_REG_HOUR 0x02 /* 00-23, or 1-12{am,pm} */ # define DS1307_BIT_12HR 0x40 /* in REG_HOUR */ # define DS1307_BIT_PM 0x20 /* in REG_HOUR */ # define DS1340_BIT_CENTURY_EN 0x80 /* in REG_HOUR */ # define DS1340_BIT_CENTURY 0x40 /* in REG_HOUR */ #define DS1307_REG_WDAY 0x03 /* 01-07 */ # define MCP7941X_BIT_VBATEN 0x08 #define DS1307_REG_MDAY 0x04 /* 01-31 */ #define DS1307_REG_MONTH 0x05 /* 01-12 */ # define DS1337_BIT_CENTURY 0x80 /* in REG_MONTH */ #define DS1307_REG_YEAR 0x06 /* 00-99 */ /* * Other registers (control, status, alarms, trickle charge, NVRAM, etc) * start at 7, and they differ a LOT. Only control and status matter for * basic RTC date and time functionality; be careful using them. */ #define DS1307_REG_CONTROL 0x07 /* or ds1338 */ # define DS1307_BIT_OUT 0x80 # define DS1338_BIT_OSF 0x20 # define DS1307_BIT_SQWE 0x10 # define DS1307_BIT_RS1 0x02 # define DS1307_BIT_RS0 0x01 #define DS1337_REG_CONTROL 0x0e # define DS1337_BIT_nEOSC 0x80 # define DS1339_BIT_BBSQI 0x20 # define DS3231_BIT_BBSQW 0x40 /* same as BBSQI */ # define DS1337_BIT_RS2 0x10 # define DS1337_BIT_RS1 0x08 # define DS1337_BIT_INTCN 0x04 # define DS1337_BIT_A2IE 0x02 # define DS1337_BIT_A1IE 0x01 #define DS1340_REG_CONTROL 0x07 # define DS1340_BIT_OUT 0x80 # define DS1340_BIT_FT 0x40 # define DS1340_BIT_CALIB_SIGN 0x20 # define DS1340_M_CALIBRATION 0x1f #define DS1340_REG_FLAG 0x09 # define DS1340_BIT_OSF 0x80 #define DS1337_REG_STATUS 0x0f # define DS1337_BIT_OSF 0x80 # define DS1337_BIT_A2I 0x02 # define DS1337_BIT_A1I 0x01 #define DS1339_REG_ALARM1_SECS 0x07 #define DS13XX_TRICKLE_CHARGER_MAGIC 0xa0 #define RX8025_REG_CTRL1 0x0e # define RX8025_BIT_2412 0x20 #define RX8025_REG_CTRL2 0x0f # define RX8025_BIT_PON 0x10 # define RX8025_BIT_VDET 0x40 # define RX8025_BIT_XST 0x20 struct ds1307 { u8 offset; /* register's offset */ u8 regs[11]; u16 nvram_offset; struct bin_attribute *nvram; enum ds_type type; unsigned long flags; #define HAS_NVRAM 0 /* bit 0 == sysfs file active */ #define HAS_ALARM 1 /* bit 1 == irq claimed */ struct i2c_client *client; struct rtc_device *rtc; struct work_struct work; s32 (*read_block_data)(const struct i2c_client *client, u8 command, u8 length, u8 *values); s32 (*write_block_data)(const struct i2c_client *client, u8 command, u8 length, const u8 *values); }; struct chip_desc { unsigned alarm:1; u16 nvram_offset; u16 nvram_size; u16 trickle_charger_reg; u8 trickle_charger_setup; u8 (*do_trickle_setup)(struct i2c_client *, uint32_t, bool); }; static u8 do_trickle_setup_ds1339(struct i2c_client *, uint32_t ohms, bool diode); static struct chip_desc chips[last_ds_type] = { [ds_1307] = { .nvram_offset = 8, .nvram_size = 56, }, [ds_1337] = { .alarm = 1, }, [ds_1338] = { .nvram_offset = 8, .nvram_size = 56, }, [ds_1339] = { .alarm = 1, .trickle_charger_reg = 0x10, .do_trickle_setup = &do_trickle_setup_ds1339, }, [ds_1340] = { .trickle_charger_reg = 0x08, }, [ds_1388] = { .trickle_charger_reg = 0x0a, }, [ds_3231] = { .alarm = 1, }, [mcp7941x] = { .alarm = 1, /* this is battery backed SRAM */ .nvram_offset = 0x20, .nvram_size = 0x40, }, }; static const struct i2c_device_id ds1307_id[] = { { "ds1307", ds_1307 }, { "ds1337", ds_1337 }, { "ds1338", ds_1338 }, { "ds1339", ds_1339 }, { "ds1388", ds_1388 }, { "ds1340", ds_1340 }, { "ds3231", ds_3231 }, { "m41t00", m41t00 }, { "mcp7941x", mcp7941x }, { "pt7c4338", ds_1307 }, { "rx8025", rx_8025 }, { } }; MODULE_DEVICE_TABLE(i2c, ds1307_id); /*----------------------------------------------------------------------*/ #define BLOCK_DATA_MAX_TRIES 10 static s32 ds1307_read_block_data_once(const struct i2c_client *client, u8 command, u8 length, u8 *values) { s32 i, data; for (i = 0; i < length; i++) { data = i2c_smbus_read_byte_data(client, command + i); if (data < 0) return data; values[i] = data; } return i; } static s32 ds1307_read_block_data(const struct i2c_client *client, u8 command, u8 length, u8 *values) { u8 oldvalues[255]; s32 ret; int tries = 0; dev_dbg(&client->dev, "ds1307_read_block_data (length=%d)\n", length); ret = ds1307_read_block_data_once(client, command, length, values); if (ret < 0) return ret; do { if (++tries > BLOCK_DATA_MAX_TRIES) { dev_err(&client->dev, "ds1307_read_block_data failed\n"); return -EIO; } memcpy(oldvalues, values, length); ret = ds1307_read_block_data_once(client, command, length, values); if (ret < 0) return ret; } while (memcmp(oldvalues, values, length)); return length; } static s32 ds1307_write_block_data(const struct i2c_client *client, u8 command, u8 length, const u8 *values) { u8 currvalues[255]; int tries = 0; dev_dbg(&client->dev, "ds1307_write_block_data (length=%d)\n", length); do { s32 i, ret; if (++tries > BLOCK_DATA_MAX_TRIES) { dev_err(&client->dev, "ds1307_write_block_data failed\n"); return -EIO; } for (i = 0; i < length; i++) { ret = i2c_smbus_write_byte_data(client, command + i, values[i]); if (ret < 0) return ret; } ret = ds1307_read_block_data_once(client, command, length, currvalues); if (ret < 0) return ret; } while (memcmp(currvalues, values, length)); return length; } /*----------------------------------------------------------------------*/ /* These RTC devices are not designed to be connected to a SMbus adapter. SMbus limits block operations length to 32 bytes, whereas it's not limited on I2C buses. As a result, accesses may exceed 32 bytes; in that case, split them into smaller blocks */ static s32 ds1307_native_smbus_write_block_data(const struct i2c_client *client, u8 command, u8 length, const u8 *values) { u8 suboffset = 0; if (length <= I2C_SMBUS_BLOCK_MAX) return i2c_smbus_write_i2c_block_data(client, command, length, values); while (suboffset < length) { s32 retval = i2c_smbus_write_i2c_block_data(client, command + suboffset, min(I2C_SMBUS_BLOCK_MAX, length - suboffset), values + suboffset); if (retval < 0) return retval; suboffset += I2C_SMBUS_BLOCK_MAX; } return length; } static s32 ds1307_native_smbus_read_block_data(const struct i2c_client *client, u8 command, u8 length, u8 *values) { u8 suboffset = 0; if (length <= I2C_SMBUS_BLOCK_MAX) return i2c_smbus_read_i2c_block_data(client, command, length, values); while (suboffset < length) { s32 retval = i2c_smbus_read_i2c_block_data(client, command + suboffset, min(I2C_SMBUS_BLOCK_MAX, length - suboffset), values + suboffset); if (retval < 0) return retval; suboffset += I2C_SMBUS_BLOCK_MAX; } return length; } /*----------------------------------------------------------------------*/ /* * The IRQ logic includes a "real" handler running in IRQ context just * long enough to schedule this workqueue entry. We need a task context * to talk to the RTC, since I2C I/O calls require that; and disable the * IRQ until we clear its status on the chip, so that this handler can * work with any type of triggering (not just falling edge). * * The ds1337 and ds1339 both have two alarms, but we only use the first * one (with a "seconds" field). For ds1337 we expect nINTA is our alarm * signal; ds1339 chips have only one alarm signal. */ static void ds1307_work(struct work_struct *work) { struct ds1307 *ds1307; struct i2c_client *client; struct mutex *lock; int stat, control; ds1307 = container_of(work, struct ds1307, work); client = ds1307->client; lock = &ds1307->rtc->ops_lock; mutex_lock(lock); stat = i2c_smbus_read_byte_data(client, DS1337_REG_STATUS); if (stat < 0) goto out; if (stat & DS1337_BIT_A1I) { stat &= ~DS1337_BIT_A1I; i2c_smbus_write_byte_data(client, DS1337_REG_STATUS, stat); control = i2c_smbus_read_byte_data(client, DS1337_REG_CONTROL); if (control < 0) goto out; control &= ~DS1337_BIT_A1IE; i2c_smbus_write_byte_data(client, DS1337_REG_CONTROL, control); rtc_update_irq(ds1307->rtc, 1, RTC_AF | RTC_IRQF); } out: if (test_bit(HAS_ALARM, &ds1307->flags)) enable_irq(client->irq); mutex_unlock(lock); } static irqreturn_t ds1307_irq(int irq, void *dev_id) { struct i2c_client *client = dev_id; struct ds1307 *ds1307 = i2c_get_clientdata(client); disable_irq_nosync(irq); schedule_work(&ds1307->work); return IRQ_HANDLED; } /*----------------------------------------------------------------------*/ static int ds1307_get_time(struct device *dev, struct rtc_time *t) { struct ds1307 *ds1307 = dev_get_drvdata(dev); int tmp; /* read the RTC date and time registers all at once */ tmp = ds1307->read_block_data(ds1307->client, ds1307->offset, 7, ds1307->regs); if (tmp != 7) { dev_err(dev, "%s error %d\n", "read", tmp); return -EIO; } dev_dbg(dev, "%s: %7ph\n", "read", ds1307->regs); t->tm_sec = bcd2bin(ds1307->regs[DS1307_REG_SECS] & 0x7f); t->tm_min = bcd2bin(ds1307->regs[DS1307_REG_MIN] & 0x7f); tmp = ds1307->regs[DS1307_REG_HOUR] & 0x3f; t->tm_hour = bcd2bin(tmp); t->tm_wday = bcd2bin(ds1307->regs[DS1307_REG_WDAY] & 0x07) - 1; t->tm_mday = bcd2bin(ds1307->regs[DS1307_REG_MDAY] & 0x3f); tmp = ds1307->regs[DS1307_REG_MONTH] & 0x1f; t->tm_mon = bcd2bin(tmp) - 1; /* assume 20YY not 19YY, and ignore DS1337_BIT_CENTURY */ t->tm_year = bcd2bin(ds1307->regs[DS1307_REG_YEAR]) + 100; dev_dbg(dev, "%s secs=%d, mins=%d, " "hours=%d, mday=%d, mon=%d, year=%d, wday=%d\n", "read", t->tm_sec, t->tm_min, t->tm_hour, t->tm_mday, t->tm_mon, t->tm_year, t->tm_wday); /* initial clock setting can be undefined */ return rtc_valid_tm(t); } static int ds1307_set_time(struct device *dev, struct rtc_time *t) { struct ds1307 *ds1307 = dev_get_drvdata(dev); int result; int tmp; u8 *buf = ds1307->regs; dev_dbg(dev, "%s secs=%d, mins=%d, " "hours=%d, mday=%d, mon=%d, year=%d, wday=%d\n", "write", t->tm_sec, t->tm_min, t->tm_hour, t->tm_mday, t->tm_mon, t->tm_year, t->tm_wday); buf[DS1307_REG_SECS] = bin2bcd(t->tm_sec); buf[DS1307_REG_MIN] = bin2bcd(t->tm_min); buf[DS1307_REG_HOUR] = bin2bcd(t->tm_hour); buf[DS1307_REG_WDAY] = bin2bcd(t->tm_wday + 1); buf[DS1307_REG_MDAY] = bin2bcd(t->tm_mday); buf[DS1307_REG_MONTH] = bin2bcd(t->tm_mon + 1); /* assume 20YY not 19YY */ tmp = t->tm_year - 100; buf[DS1307_REG_YEAR] = bin2bcd(tmp); switch (ds1307->type) { case ds_1337: case ds_1339: case ds_3231: buf[DS1307_REG_MONTH] |= DS1337_BIT_CENTURY; break; case ds_1340: buf[DS1307_REG_HOUR] |= DS1340_BIT_CENTURY_EN | DS1340_BIT_CENTURY; break; case mcp7941x: /* * these bits were cleared when preparing the date/time * values and need to be set again before writing the * buffer out to the device. */ buf[DS1307_REG_SECS] |= MCP7941X_BIT_ST; buf[DS1307_REG_WDAY] |= MCP7941X_BIT_VBATEN; break; default: break; } dev_dbg(dev, "%s: %7ph\n", "write", buf); result = ds1307->write_block_data(ds1307->client, ds1307->offset, 7, buf); if (result < 0) { dev_err(dev, "%s error %d\n", "write", result); return result; } return 0; } static int ds1337_read_alarm(struct device *dev, struct rtc_wkalrm *t) { struct i2c_client *client = to_i2c_client(dev); struct ds1307 *ds1307 = i2c_get_clientdata(client); int ret; if (!test_bit(HAS_ALARM, &ds1307->flags)) return -EINVAL; /* read all ALARM1, ALARM2, and status registers at once */ ret = ds1307->read_block_data(client, DS1339_REG_ALARM1_SECS, 9, ds1307->regs); if (ret != 9) { dev_err(dev, "%s error %d\n", "alarm read", ret); return -EIO; } dev_dbg(dev, "%s: %02x %02x %02x %02x, %02x %02x %02x, %02x %02x\n", "alarm read", ds1307->regs[0], ds1307->regs[1], ds1307->regs[2], ds1307->regs[3], ds1307->regs[4], ds1307->regs[5], ds1307->regs[6], ds1307->regs[7], ds1307->regs[8]); /* * report alarm time (ALARM1); assume 24 hour and day-of-month modes, * and that all four fields are checked matches */ t->time.tm_sec = bcd2bin(ds1307->regs[0] & 0x7f); t->time.tm_min = bcd2bin(ds1307->regs[1] & 0x7f); t->time.tm_hour = bcd2bin(ds1307->regs[2] & 0x3f); t->time.tm_mday = bcd2bin(ds1307->regs[3] & 0x3f); t->time.tm_mon = -1; t->time.tm_year = -1; t->time.tm_wday = -1; t->time.tm_yday = -1; t->time.tm_isdst = -1; /* ... and status */ t->enabled = !!(ds1307->regs[7] & DS1337_BIT_A1IE); t->pending = !!(ds1307->regs[8] & DS1337_BIT_A1I); dev_dbg(dev, "%s secs=%d, mins=%d, " "hours=%d, mday=%d, enabled=%d, pending=%d\n", "alarm read", t->time.tm_sec, t->time.tm_min, t->time.tm_hour, t->time.tm_mday, t->enabled, t->pending); return 0; } static int ds1337_set_alarm(struct device *dev, struct rtc_wkalrm *t) { struct i2c_client *client = to_i2c_client(dev); struct ds1307 *ds1307 = i2c_get_clientdata(client); unsigned char *buf = ds1307->regs; u8 control, status; int ret; if (!test_bit(HAS_ALARM, &ds1307->flags)) return -EINVAL; dev_dbg(dev, "%s secs=%d, mins=%d, " "hours=%d, mday=%d, enabled=%d, pending=%d\n", "alarm set", t->time.tm_sec, t->time.tm_min, t->time.tm_hour, t->time.tm_mday, t->enabled, t->pending); /* read current status of both alarms and the chip */ ret = ds1307->read_block_data(client, DS1339_REG_ALARM1_SECS, 9, buf); if (ret != 9) { dev_err(dev, "%s error %d\n", "alarm write", ret); return -EIO; } control = ds1307->regs[7]; status = ds1307->regs[8]; dev_dbg(dev, "%s: %02x %02x %02x %02x, %02x %02x %02x, %02x %02x\n", "alarm set (old status)", ds1307->regs[0], ds1307->regs[1], ds1307->regs[2], ds1307->regs[3], ds1307->regs[4], ds1307->regs[5], ds1307->regs[6], control, status); /* set ALARM1, using 24 hour and day-of-month modes */ buf[0] = bin2bcd(t->time.tm_sec); buf[1] = bin2bcd(t->time.tm_min); buf[2] = bin2bcd(t->time.tm_hour); buf[3] = bin2bcd(t->time.tm_mday); /* set ALARM2 to non-garbage */ buf[4] = 0; buf[5] = 0; buf[6] = 0; /* optionally enable ALARM1 */ buf[7] = control & ~(DS1337_BIT_A1IE | DS1337_BIT_A2IE); if (t->enabled) { dev_dbg(dev, "alarm IRQ armed\n"); buf[7] |= DS1337_BIT_A1IE; /* only ALARM1 is used */ } buf[8] = status & ~(DS1337_BIT_A1I | DS1337_BIT_A2I); ret = ds1307->write_block_data(client, DS1339_REG_ALARM1_SECS, 9, buf); if (ret < 0) { dev_err(dev, "can't set alarm time\n"); return ret; } return 0; } static int ds1307_alarm_irq_enable(struct device *dev, unsigned int enabled) { struct i2c_client *client = to_i2c_client(dev); struct ds1307 *ds1307 = i2c_get_clientdata(client); int ret; if (!test_bit(HAS_ALARM, &ds1307->flags)) return -ENOTTY; ret = i2c_smbus_read_byte_data(client, DS1337_REG_CONTROL); if (ret < 0) return ret; if (enabled) ret |= DS1337_BIT_A1IE; else ret &= ~DS1337_BIT_A1IE; ret = i2c_smbus_write_byte_data(client, DS1337_REG_CONTROL, ret); if (ret < 0) return ret; return 0; } static const struct rtc_class_ops ds13xx_rtc_ops = { .read_time = ds1307_get_time, .set_time = ds1307_set_time, .read_alarm = ds1337_read_alarm, .set_alarm = ds1337_set_alarm, .alarm_irq_enable = ds1307_alarm_irq_enable, }; /*----------------------------------------------------------------------*/ /* * Alarm support for mcp7941x devices. */ #define MCP7941X_REG_CONTROL 0x07 # define MCP7941X_BIT_ALM0_EN 0x10 # define MCP7941X_BIT_ALM1_EN 0x20 #define MCP7941X_REG_ALARM0_BASE 0x0a #define MCP7941X_REG_ALARM0_CTRL 0x0d #define MCP7941X_REG_ALARM1_BASE 0x11 #define MCP7941X_REG_ALARM1_CTRL 0x14 # define MCP7941X_BIT_ALMX_IF (1 << 3) # define MCP7941X_BIT_ALMX_C0 (1 << 4) # define MCP7941X_BIT_ALMX_C1 (1 << 5) # define MCP7941X_BIT_ALMX_C2 (1 << 6) # define MCP7941X_BIT_ALMX_POL (1 << 7) # define MCP7941X_MSK_ALMX_MATCH (MCP7941X_BIT_ALMX_C0 | \ MCP7941X_BIT_ALMX_C1 | \ MCP7941X_BIT_ALMX_C2) static void mcp7941x_work(struct work_struct *work) { struct ds1307 *ds1307 = container_of(work, struct ds1307, work); struct i2c_client *client = ds1307->client; int reg, ret; mutex_lock(&ds1307->rtc->ops_lock); /* Check and clear alarm 0 interrupt flag. */ reg = i2c_smbus_read_byte_data(client, MCP7941X_REG_ALARM0_CTRL); if (reg < 0) goto out; if (!(reg & MCP7941X_BIT_ALMX_IF)) goto out; reg &= ~MCP7941X_BIT_ALMX_IF; ret = i2c_smbus_write_byte_data(client, MCP7941X_REG_ALARM0_CTRL, reg); if (ret < 0) goto out; /* Disable alarm 0. */ reg = i2c_smbus_read_byte_data(client, MCP7941X_REG_CONTROL); if (reg < 0) goto out; reg &= ~MCP7941X_BIT_ALM0_EN; ret = i2c_smbus_write_byte_data(client, MCP7941X_REG_CONTROL, reg); if (ret < 0) goto out; rtc_update_irq(ds1307->rtc, 1, RTC_AF | RTC_IRQF); out: if (test_bit(HAS_ALARM, &ds1307->flags)) enable_irq(client->irq); mutex_unlock(&ds1307->rtc->ops_lock); } static int mcp7941x_read_alarm(struct device *dev, struct rtc_wkalrm *t) { struct i2c_client *client = to_i2c_client(dev); struct ds1307 *ds1307 = i2c_get_clientdata(client); u8 *regs = ds1307->regs; int ret; if (!test_bit(HAS_ALARM, &ds1307->flags)) return -EINVAL; /* Read control and alarm 0 registers. */ ret = ds1307->read_block_data(client, MCP7941X_REG_CONTROL, 10, regs); if (ret < 0) return ret; t->enabled = !!(regs[0] & MCP7941X_BIT_ALM0_EN); /* Report alarm 0 time assuming 24-hour and day-of-month modes. */ t->time.tm_sec = bcd2bin(ds1307->regs[3] & 0x7f); t->time.tm_min = bcd2bin(ds1307->regs[4] & 0x7f); t->time.tm_hour = bcd2bin(ds1307->regs[5] & 0x3f); t->time.tm_wday = bcd2bin(ds1307->regs[6] & 0x7) - 1; t->time.tm_mday = bcd2bin(ds1307->regs[7] & 0x3f); t->time.tm_mon = bcd2bin(ds1307->regs[8] & 0x1f) - 1; t->time.tm_year = -1; t->time.tm_yday = -1; t->time.tm_isdst = -1; dev_dbg(dev, "%s, sec=%d min=%d hour=%d wday=%d mday=%d mon=%d " "enabled=%d polarity=%d irq=%d match=%d\n", __func__, t->time.tm_sec, t->time.tm_min, t->time.tm_hour, t->time.tm_wday, t->time.tm_mday, t->time.tm_mon, t->enabled, !!(ds1307->regs[6] & MCP7941X_BIT_ALMX_POL), !!(ds1307->regs[6] & MCP7941X_BIT_ALMX_IF), (ds1307->regs[6] & MCP7941X_MSK_ALMX_MATCH) >> 4); return 0; } static int mcp7941x_set_alarm(struct device *dev, struct rtc_wkalrm *t) { struct i2c_client *client = to_i2c_client(dev); struct ds1307 *ds1307 = i2c_get_clientdata(client); unsigned char *regs = ds1307->regs; int ret; if (!test_bit(HAS_ALARM, &ds1307->flags)) return -EINVAL; dev_dbg(dev, "%s, sec=%d min=%d hour=%d wday=%d mday=%d mon=%d " "enabled=%d pending=%d\n", __func__, t->time.tm_sec, t->time.tm_min, t->time.tm_hour, t->time.tm_wday, t->time.tm_mday, t->time.tm_mon, t->enabled, t->pending); /* Read control and alarm 0 registers. */ ret = ds1307->read_block_data(client, MCP7941X_REG_CONTROL, 10, regs); if (ret < 0) return ret; /* Set alarm 0, using 24-hour and day-of-month modes. */ regs[3] = bin2bcd(t->time.tm_sec); regs[4] = bin2bcd(t->time.tm_min); regs[5] = bin2bcd(t->time.tm_hour); regs[6] = bin2bcd(t->time.tm_wday) + 1; regs[7] = bin2bcd(t->time.tm_mday); regs[8] = bin2bcd(t->time.tm_mon) + 1; /* Clear the alarm 0 interrupt flag. */ regs[6] &= ~MCP7941X_BIT_ALMX_IF; /* Set alarm match: second, minute, hour, day, date, month. */ regs[6] |= MCP7941X_MSK_ALMX_MATCH; if (t->enabled) regs[0] |= MCP7941X_BIT_ALM0_EN; else regs[0] &= ~MCP7941X_BIT_ALM0_EN; ret = ds1307->write_block_data(client, MCP7941X_REG_CONTROL, 10, regs); if (ret < 0) return ret; return 0; } static int mcp7941x_alarm_irq_enable(struct device *dev, unsigned int enabled) { struct i2c_client *client = to_i2c_client(dev); struct ds1307 *ds1307 = i2c_get_clientdata(client); int reg; if (!test_bit(HAS_ALARM, &ds1307->flags)) return -EINVAL; reg = i2c_smbus_read_byte_data(client, MCP7941X_REG_CONTROL); if (reg < 0) return reg; if (enabled) reg |= MCP7941X_BIT_ALM0_EN; else reg &= ~MCP7941X_BIT_ALM0_EN; return i2c_smbus_write_byte_data(client, MCP7941X_REG_CONTROL, reg); } static const struct rtc_class_ops mcp7941x_rtc_ops = { .read_time = ds1307_get_time, .set_time = ds1307_set_time, .read_alarm = mcp7941x_read_alarm, .set_alarm = mcp7941x_set_alarm, .alarm_irq_enable = mcp7941x_alarm_irq_enable, }; /*----------------------------------------------------------------------*/ static ssize_t ds1307_nvram_read(struct file *filp, struct kobject *kobj, struct bin_attribute *attr, char *buf, loff_t off, size_t count) { struct i2c_client *client; struct ds1307 *ds1307; int result; client = kobj_to_i2c_client(kobj); ds1307 = i2c_get_clientdata(client); if (unlikely(off >= ds1307->nvram->size)) return 0; if ((off + count) > ds1307->nvram->size) count = ds1307->nvram->size - off; if (unlikely(!count)) return count; result = ds1307->read_block_data(client, ds1307->nvram_offset + off, count, buf); if (result < 0) dev_err(&client->dev, "%s error %d\n", "nvram read", result); return result; } static ssize_t ds1307_nvram_write(struct file *filp, struct kobject *kobj, struct bin_attribute *attr, char *buf, loff_t off, size_t count) { struct i2c_client *client; struct ds1307 *ds1307; int result; client = kobj_to_i2c_client(kobj); ds1307 = i2c_get_clientdata(client); if (unlikely(off >= ds1307->nvram->size)) return -EFBIG; if ((off + count) > ds1307->nvram->size) count = ds1307->nvram->size - off; if (unlikely(!count)) return count; result = ds1307->write_block_data(client, ds1307->nvram_offset + off, count, buf); if (result < 0) { dev_err(&client->dev, "%s error %d\n", "nvram write", result); return result; } return count; } /*----------------------------------------------------------------------*/ static u8 do_trickle_setup_ds1339(struct i2c_client *client, uint32_t ohms, bool diode) { u8 setup = (diode) ? DS1307_TRICKLE_CHARGER_DIODE : DS1307_TRICKLE_CHARGER_NO_DIODE; switch (ohms) { case 250: setup |= DS1307_TRICKLE_CHARGER_250_OHM; break; case 2000: setup |= DS1307_TRICKLE_CHARGER_2K_OHM; break; case 4000: setup |= DS1307_TRICKLE_CHARGER_4K_OHM; break; default: dev_warn(&client->dev, "Unsupported ohm value %u in dt\n", ohms); return 0; } return setup; } static void ds1307_trickle_of_init(struct i2c_client *client, struct chip_desc *chip) { uint32_t ohms = 0; bool diode = true; if (!chip->do_trickle_setup) goto out; if (of_property_read_u32(client->dev.of_node, "trickle-resistor-ohms" , &ohms)) goto out; if (of_property_read_bool(client->dev.of_node, "trickle-diode-disable")) diode = false; chip->trickle_charger_setup = chip->do_trickle_setup(client, ohms, diode); out: return; } static int ds1307_probe(struct i2c_client *client, const struct i2c_device_id *id) { struct ds1307 *ds1307; int err = -ENODEV; int tmp; struct chip_desc *chip = &chips[id->driver_data]; struct i2c_adapter *adapter = to_i2c_adapter(client->dev.parent); bool want_irq = false; unsigned char *buf; struct ds1307_platform_data *pdata = dev_get_platdata(&client->dev); static const int bbsqi_bitpos[] = { [ds_1337] = 0, [ds_1339] = DS1339_BIT_BBSQI, [ds_3231] = DS3231_BIT_BBSQW, }; const struct rtc_class_ops *rtc_ops = &ds13xx_rtc_ops; if (!i2c_check_functionality(adapter, I2C_FUNC_SMBUS_BYTE_DATA) && !i2c_check_functionality(adapter, I2C_FUNC_SMBUS_I2C_BLOCK)) return -EIO; ds1307 = devm_kzalloc(&client->dev, sizeof(struct ds1307), GFP_KERNEL); if (!ds1307) return -ENOMEM; i2c_set_clientdata(client, ds1307); ds1307->client = client; ds1307->type = id->driver_data; if (!pdata && client->dev.of_node) ds1307_trickle_of_init(client, chip); else if (pdata && pdata->trickle_charger_setup) chip->trickle_charger_setup = pdata->trickle_charger_setup; if (chip->trickle_charger_setup && chip->trickle_charger_reg) { dev_dbg(&client->dev, "writing trickle charger info 0x%x to 0x%x\n", DS13XX_TRICKLE_CHARGER_MAGIC | chip->trickle_charger_setup, chip->trickle_charger_reg); i2c_smbus_write_byte_data(client, chip->trickle_charger_reg, DS13XX_TRICKLE_CHARGER_MAGIC | chip->trickle_charger_setup); } buf = ds1307->regs; if (i2c_check_functionality(adapter, I2C_FUNC_SMBUS_I2C_BLOCK)) { ds1307->read_block_data = ds1307_native_smbus_read_block_data; ds1307->write_block_data = ds1307_native_smbus_write_block_data; } else { ds1307->read_block_data = ds1307_read_block_data; ds1307->write_block_data = ds1307_write_block_data; } switch (ds1307->type) { case ds_1337: case ds_1339: case ds_3231: /* get registers that the "rtc" read below won't read... */ tmp = ds1307->read_block_data(ds1307->client, DS1337_REG_CONTROL, 2, buf); if (tmp != 2) { dev_dbg(&client->dev, "read error %d\n", tmp); err = -EIO; goto exit; } /* oscillator off? turn it on, so clock can tick. */ if (ds1307->regs[0] & DS1337_BIT_nEOSC) ds1307->regs[0] &= ~DS1337_BIT_nEOSC; /* * Using IRQ? Disable the square wave and both alarms. * For some variants, be sure alarms can trigger when we're * running on Vbackup (BBSQI/BBSQW) */ if (ds1307->client->irq > 0 && chip->alarm) { INIT_WORK(&ds1307->work, ds1307_work); ds1307->regs[0] |= DS1337_BIT_INTCN | bbsqi_bitpos[ds1307->type]; ds1307->regs[0] &= ~(DS1337_BIT_A2IE | DS1337_BIT_A1IE); want_irq = true; } i2c_smbus_write_byte_data(client, DS1337_REG_CONTROL, ds1307->regs[0]); /* oscillator fault? clear flag, and warn */ if (ds1307->regs[1] & DS1337_BIT_OSF) { i2c_smbus_write_byte_data(client, DS1337_REG_STATUS, ds1307->regs[1] & ~DS1337_BIT_OSF); dev_warn(&client->dev, "SET TIME!\n"); } break; case rx_8025: tmp = i2c_smbus_read_i2c_block_data(ds1307->client, RX8025_REG_CTRL1 << 4 | 0x08, 2, buf); if (tmp != 2) { dev_dbg(&client->dev, "read error %d\n", tmp); err = -EIO; goto exit; } /* oscillator off? turn it on, so clock can tick. */ if (!(ds1307->regs[1] & RX8025_BIT_XST)) { ds1307->regs[1] |= RX8025_BIT_XST; i2c_smbus_write_byte_data(client, RX8025_REG_CTRL2 << 4 | 0x08, ds1307->regs[1]); dev_warn(&client->dev, "oscillator stop detected - SET TIME!\n"); } if (ds1307->regs[1] & RX8025_BIT_PON) { ds1307->regs[1] &= ~RX8025_BIT_PON; i2c_smbus_write_byte_data(client, RX8025_REG_CTRL2 << 4 | 0x08, ds1307->regs[1]); dev_warn(&client->dev, "power-on detected\n"); } if (ds1307->regs[1] & RX8025_BIT_VDET) { ds1307->regs[1] &= ~RX8025_BIT_VDET; i2c_smbus_write_byte_data(client, RX8025_REG_CTRL2 << 4 | 0x08, ds1307->regs[1]); dev_warn(&client->dev, "voltage drop detected\n"); } /* make sure we are running in 24hour mode */ if (!(ds1307->regs[0] & RX8025_BIT_2412)) { u8 hour; /* switch to 24 hour mode */ i2c_smbus_write_byte_data(client, RX8025_REG_CTRL1 << 4 | 0x08, ds1307->regs[0] | RX8025_BIT_2412); tmp = i2c_smbus_read_i2c_block_data(ds1307->client, RX8025_REG_CTRL1 << 4 | 0x08, 2, buf); if (tmp != 2) { dev_dbg(&client->dev, "read error %d\n", tmp); err = -EIO; goto exit; } /* correct hour */ hour = bcd2bin(ds1307->regs[DS1307_REG_HOUR]); if (hour == 12) hour = 0; if (ds1307->regs[DS1307_REG_HOUR] & DS1307_BIT_PM) hour += 12; i2c_smbus_write_byte_data(client, DS1307_REG_HOUR << 4 | 0x08, hour); } break; case ds_1388: ds1307->offset = 1; /* Seconds starts at 1 */ break; case mcp7941x: rtc_ops = &mcp7941x_rtc_ops; if (ds1307->client->irq > 0 && chip->alarm) { INIT_WORK(&ds1307->work, mcp7941x_work); want_irq = true; } break; default: break; } read_rtc: /* read RTC registers */ tmp = ds1307->read_block_data(ds1307->client, ds1307->offset, 8, buf); if (tmp != 8) { dev_dbg(&client->dev, "read error %d\n", tmp); err = -EIO; goto exit; } /* * minimal sanity checking; some chips (like DS1340) don't * specify the extra bits as must-be-zero, but there are * still a few values that are clearly out-of-range. */ tmp = ds1307->regs[DS1307_REG_SECS]; switch (ds1307->type) { case ds_1307: case m41t00: /* clock halted? turn it on, so clock can tick. */ if (tmp & DS1307_BIT_CH) { i2c_smbus_write_byte_data(client, DS1307_REG_SECS, 0); dev_warn(&client->dev, "SET TIME!\n"); goto read_rtc; } break; case ds_1338: /* clock halted? turn it on, so clock can tick. */ if (tmp & DS1307_BIT_CH) i2c_smbus_write_byte_data(client, DS1307_REG_SECS, 0); /* oscillator fault? clear flag, and warn */ if (ds1307->regs[DS1307_REG_CONTROL] & DS1338_BIT_OSF) { i2c_smbus_write_byte_data(client, DS1307_REG_CONTROL, ds1307->regs[DS1307_REG_CONTROL] & ~DS1338_BIT_OSF); dev_warn(&client->dev, "SET TIME!\n"); goto read_rtc; } break; case ds_1340: /* clock halted? turn it on, so clock can tick. */ if (tmp & DS1340_BIT_nEOSC) i2c_smbus_write_byte_data(client, DS1307_REG_SECS, 0); tmp = i2c_smbus_read_byte_data(client, DS1340_REG_FLAG); if (tmp < 0) { dev_dbg(&client->dev, "read error %d\n", tmp); err = -EIO; goto exit; } /* oscillator fault? clear flag, and warn */ if (tmp & DS1340_BIT_OSF) { i2c_smbus_write_byte_data(client, DS1340_REG_FLAG, 0); dev_warn(&client->dev, "SET TIME!\n"); } break; case mcp7941x: /* make sure that the backup battery is enabled */ if (!(ds1307->regs[DS1307_REG_WDAY] & MCP7941X_BIT_VBATEN)) { i2c_smbus_write_byte_data(client, DS1307_REG_WDAY, ds1307->regs[DS1307_REG_WDAY] | MCP7941X_BIT_VBATEN); } /* clock halted? turn it on, so clock can tick. */ if (!(tmp & MCP7941X_BIT_ST)) { i2c_smbus_write_byte_data(client, DS1307_REG_SECS, MCP7941X_BIT_ST); dev_warn(&client->dev, "SET TIME!\n"); goto read_rtc; } break; default: break; } tmp = ds1307->regs[DS1307_REG_HOUR]; switch (ds1307->type) { case ds_1340: case m41t00: /* * NOTE: ignores century bits; fix before deploying * systems that will run through year 2100. */ break; case rx_8025: break; default: if (!(tmp & DS1307_BIT_12HR)) break; /* * Be sure we're in 24 hour mode. Multi-master systems * take note... */ tmp = bcd2bin(tmp & 0x1f); if (tmp == 12) tmp = 0; if (ds1307->regs[DS1307_REG_HOUR] & DS1307_BIT_PM) tmp += 12; i2c_smbus_write_byte_data(client, ds1307->offset + DS1307_REG_HOUR, bin2bcd(tmp)); } device_set_wakeup_capable(&client->dev, want_irq); ds1307->rtc = devm_rtc_device_register(&client->dev, client->name, rtc_ops, THIS_MODULE); if (IS_ERR(ds1307->rtc)) { return PTR_ERR(ds1307->rtc); } if (want_irq) { err = request_irq(client->irq, ds1307_irq, IRQF_SHARED, ds1307->rtc->name, client); if (err) { client->irq = 0; dev_err(&client->dev, "unable to request IRQ!\n"); } else { set_bit(HAS_ALARM, &ds1307->flags); dev_dbg(&client->dev, "got IRQ %d\n", client->irq); } } if (chip->nvram_size) { ds1307->nvram = devm_kzalloc(&client->dev, sizeof(struct bin_attribute), GFP_KERNEL); if (!ds1307->nvram) { dev_err(&client->dev, "cannot allocate memory for nvram sysfs\n"); } else { ds1307->nvram->attr.name = "nvram"; ds1307->nvram->attr.mode = S_IRUGO | S_IWUSR; sysfs_bin_attr_init(ds1307->nvram); ds1307->nvram->read = ds1307_nvram_read; ds1307->nvram->write = ds1307_nvram_write; ds1307->nvram->size = chip->nvram_size; ds1307->nvram_offset = chip->nvram_offset; err = sysfs_create_bin_file(&client->dev.kobj, ds1307->nvram); if (err) { dev_err(&client->dev, "unable to create sysfs file: %s\n", ds1307->nvram->attr.name); } else { set_bit(HAS_NVRAM, &ds1307->flags); dev_info(&client->dev, "%zu bytes nvram\n", ds1307->nvram->size); } } } return 0; exit: return err; } static int ds1307_remove(struct i2c_client *client) { struct ds1307 *ds1307 = i2c_get_clientdata(client); if (test_and_clear_bit(HAS_ALARM, &ds1307->flags)) { free_irq(client->irq, client); cancel_work_sync(&ds1307->work); } if (test_and_clear_bit(HAS_NVRAM, &ds1307->flags)) sysfs_remove_bin_file(&client->dev.kobj, ds1307->nvram); return 0; } static struct i2c_driver ds1307_driver = { .driver = { .name = "rtc-ds1307", .owner = THIS_MODULE, }, .probe = ds1307_probe, .remove = ds1307_remove, .id_table = ds1307_id, }; module_i2c_driver(ds1307_driver); MODULE_DESCRIPTION("RTC driver for DS1307 and similar chips"); MODULE_LICENSE("GPL");
681394.c
/* * Copyright (c) 2016 Intel Corporation. * * SPDX-License-Identifier: Apache-2.0 */ #if defined(CONFIG_NET_DEBUG_L2_BLUETOOTH) #define SYS_LOG_DOMAIN "net/bt" #define NET_LOG_ENABLED 1 #endif #include <kernel.h> #include <toolchain.h> #include <linker/sections.h> #include <string.h> #include <errno.h> #include <board.h> #include <device.h> #include <init.h> #include <net/net_pkt.h> #include <net/net_core.h> #include <net/net_l2.h> #include <net/net_if.h> #include <net/bt.h> #include <6lo.h> #include <bluetooth/bluetooth.h> #include <bluetooth/hci.h> #include <bluetooth/conn.h> #include <bluetooth/uuid.h> #include <bluetooth/l2cap.h> #include "ipv6.h" #define L2CAP_IPSP_PSM 0x0023 #define L2CAP_IPSP_MTU 1280 #define CHAN_CTXT(_ch) CONTAINER_OF(_ch, struct bt_context, ipsp_chan.chan) #if defined(CONFIG_NET_L2_BLUETOOTH_MGMT) static struct bt_conn *default_conn; #endif struct bt_context { struct net_if *iface; struct bt_l2cap_le_chan ipsp_chan; bt_addr_t src; bt_addr_t dst; }; static enum net_verdict net_bt_recv(struct net_if *iface, struct net_pkt *pkt) { NET_DBG("iface %p pkt %p len %zu", iface, pkt, net_pkt_get_len(pkt)); if (!net_6lo_uncompress(pkt)) { NET_DBG("Packet decompression failed"); return NET_DROP; } return NET_CONTINUE; } static enum net_verdict net_bt_send(struct net_if *iface, struct net_pkt *pkt) { struct bt_context *ctxt = net_if_get_device(iface)->driver_data; NET_DBG("iface %p pkt %p len %zu", iface, pkt, net_pkt_get_len(pkt)); /* Only accept IPv6 packets */ if (net_pkt_family(pkt) != AF_INET6) { return NET_DROP; } if (!net_6lo_compress(pkt, true, NULL)) { NET_DBG("Packet compression failed"); return NET_DROP; } net_if_queue_tx(ctxt->iface, pkt); return NET_OK; } static inline u16_t net_bt_reserve(struct net_if *iface, void *unused) { ARG_UNUSED(iface); ARG_UNUSED(unused); return 0; } static int net_bt_enable(struct net_if *iface, bool state) { struct bt_context *ctxt = net_if_get_device(iface)->driver_data; NET_DBG("iface %p %s", iface, state ? "up" : "down"); if (state && ctxt->ipsp_chan.chan.state != BT_L2CAP_CONNECTED) { return -ENETDOWN; } return 0; } NET_L2_INIT(BLUETOOTH_L2, net_bt_recv, net_bt_send, net_bt_reserve, net_bt_enable); static void ipsp_connected(struct bt_l2cap_chan *chan) { struct bt_context *ctxt = CHAN_CTXT(chan); struct bt_conn_info info; struct net_linkaddr ll; struct in6_addr in6; #if defined(CONFIG_NET_DEBUG_L2_BLUETOOTH) char src[BT_ADDR_LE_STR_LEN]; char dst[BT_ADDR_LE_STR_LEN]; #endif bt_conn_get_info(chan->conn, &info); #if defined(CONFIG_NET_DEBUG_L2_BLUETOOTH) bt_addr_le_to_str(info.le.src, src, sizeof(src)); bt_addr_le_to_str(info.le.dst, dst, sizeof(dst)); NET_DBG("Channel %p Source %s connected to Destination %s", chan, src, dst); #endif /* Swap bytes since net APIs expect big endian address */ sys_memcpy_swap(ctxt->src.val, info.le.src->a.val, sizeof(ctxt->src)); sys_memcpy_swap(ctxt->dst.val, info.le.dst->a.val, sizeof(ctxt->dst)); net_if_set_link_addr(ctxt->iface, ctxt->src.val, sizeof(ctxt->src.val), NET_LINK_BLUETOOTH); ll.addr = ctxt->dst.val; ll.len = sizeof(ctxt->dst.val); ll.type = NET_LINK_BLUETOOTH; /* Add remote link-local address to the nbr cache to avoid sending ns: * https://tools.ietf.org/html/rfc7668#section-3.2.3 * A Bluetooth LE 6LN MUST NOT register its link-local address. */ net_ipv6_addr_create_iid(&in6, &ll); net_ipv6_nbr_add(ctxt->iface, &in6, &ll, false, NET_IPV6_NBR_STATE_REACHABLE); /* Set iface up */ net_if_up(ctxt->iface); } static void ipsp_disconnected(struct bt_l2cap_chan *chan) { struct bt_context *ctxt = CHAN_CTXT(chan); NET_DBG("Channel %p disconnected", chan); /* Set iface down */ net_if_down(ctxt->iface); #if defined(CONFIG_NET_L2_BLUETOOTH_MGMT) if (chan->conn != default_conn) { return; } bt_conn_unref(default_conn); default_conn = NULL; #endif } static void ipsp_recv(struct bt_l2cap_chan *chan, struct net_buf *buf) { struct bt_context *ctxt = CHAN_CTXT(chan); struct net_pkt *pkt; NET_DBG("Incoming data channel %p len %zu", chan, net_buf_frags_len(buf)); /* Get packet for bearer / protocol related data */ pkt = net_pkt_get_reserve_rx(0, K_FOREVER); /* Set destination address */ net_pkt_ll_dst(pkt)->addr = ctxt->src.val; net_pkt_ll_dst(pkt)->len = sizeof(ctxt->src); net_pkt_ll_dst(pkt)->type = NET_LINK_BLUETOOTH; /* Set source address */ net_pkt_ll_src(pkt)->addr = ctxt->dst.val; net_pkt_ll_src(pkt)->len = sizeof(ctxt->dst); net_pkt_ll_src(pkt)->type = NET_LINK_BLUETOOTH; /* Add data buffer as fragment of RX buffer, take a reference while * doing so since L2CAP will unref the buffer after return. */ net_pkt_frag_add(pkt, net_buf_ref(buf)); if (net_recv_data(ctxt->iface, pkt) < 0) { NET_DBG("Packet dropped by NET stack"); net_pkt_unref(pkt); } } static struct net_buf *ipsp_alloc_buf(struct bt_l2cap_chan *chan) { NET_DBG("Channel %p requires buffer", chan); return net_pkt_get_reserve_rx_data(0, K_FOREVER); } static struct bt_l2cap_chan_ops ipsp_ops = { .alloc_buf = ipsp_alloc_buf, .recv = ipsp_recv, .connected = ipsp_connected, .disconnected = ipsp_disconnected, }; static struct bt_context bt_context_data = { .iface = NULL, .ipsp_chan.chan.ops = &ipsp_ops, .ipsp_chan.rx.mtu = L2CAP_IPSP_MTU, }; static int bt_iface_send(struct net_if *iface, struct net_pkt *pkt) { struct bt_context *ctxt = net_if_get_device(iface)->driver_data; struct net_buf *frags; int ret; NET_DBG("iface %p pkt %p len %zu", iface, pkt, net_pkt_get_len(pkt)); /* Dettach data fragments for packet */ frags = pkt->frags; pkt->frags = NULL; net_pkt_unref(pkt); ret = bt_l2cap_chan_send(&ctxt->ipsp_chan.chan, frags); if (ret < 0) { return ret; } return ret; } static void bt_iface_init(struct net_if *iface) { struct bt_context *ctxt = net_if_get_device(iface)->driver_data; NET_DBG("iface %p", iface); ctxt->iface = iface; #if defined(CONFIG_NET_L2_BLUETOOTH_ZEP1656) /* Workaround Linux bug, see: * https://jira.zephyrproject.org/browse/ZEP-1656 */ atomic_set_bit(iface->flags, NET_IF_POINTOPOINT); #endif } static struct net_if_api bt_if_api = { .init = bt_iface_init, .send = bt_iface_send, }; static int ipsp_accept(struct bt_conn *conn, struct bt_l2cap_chan **chan) { NET_DBG("Incoming conn %p", conn); if (bt_context_data.ipsp_chan.chan.conn) { NET_ERR("No channels available"); return -ENOMEM; } *chan = &bt_context_data.ipsp_chan.chan; return 0; } static struct bt_l2cap_server server = { .psm = L2CAP_IPSP_PSM, .sec_level = CONFIG_NET_L2_BLUETOOTH_SEC_LEVEL, .accept = ipsp_accept, }; #if defined(CONFIG_NET_L2_BLUETOOTH_MGMT) static int bt_connect(u32_t mgmt_request, struct net_if *iface, void *data, size_t len) { struct bt_context *ctxt = net_if_get_device(iface)->driver_data; bt_addr_le_t *addr = data; if (len != sizeof(*addr)) { NET_ERR("Invalid address"); return -EINVAL; } if (ctxt->ipsp_chan.chan.conn) { NET_ERR("No channels available"); return -ENOMEM; } if (default_conn) { return bt_l2cap_chan_connect(default_conn, &ctxt->ipsp_chan.chan, L2CAP_IPSP_PSM); } default_conn = bt_conn_create_le(addr, BT_LE_CONN_PARAM_DEFAULT); return 0; } static bool eir_found(u8_t type, const u8_t *data, u8_t data_len, void *user_data) { int i; #if defined(CONFIG_NET_DEBUG_L2_BLUETOOTH) bt_addr_le_t *addr = user_data; char dev[BT_ADDR_LE_STR_LEN]; #endif if (type != BT_DATA_UUID16_SOME && type != BT_DATA_UUID16_ALL) { return false; } if (data_len % sizeof(u16_t) != 0) { NET_ERR("AD malformed\n"); return false; } for (i = 0; i < data_len; i += sizeof(u16_t)) { u16_t u16; memcpy(&u16, &data[i], sizeof(u16)); if (sys_le16_to_cpu(u16) != BT_UUID_IPSS_VAL) { continue; } #if defined(CONFIG_NET_DEBUG_L2_BLUETOOTH) bt_addr_le_to_str(addr, dev, sizeof(dev)); NET_DBG("[DEVICE]: %s", dev); #endif /* TODO: Notify device address found */ net_mgmt_event_notify(NET_EVENT_BT_SCAN_RESULT, bt_context_data.iface); return true; } return false; } static bool ad_parse(struct net_buf_simple *ad, bool (*func)(u8_t type, const u8_t *data, u8_t data_len, void *user_data), void *user_data) { while (ad->len > 1) { u8_t len = net_buf_simple_pull_u8(ad); u8_t type; /* Check for early termination */ if (len == 0) { return false; } if (len > ad->len || ad->len < 1) { NET_ERR("AD malformed\n"); return false; } type = net_buf_simple_pull_u8(ad); if (func(type, ad->data, len - 1, user_data)) { return true; } net_buf_simple_pull(ad, len - 1); } return false; } static void device_found(const bt_addr_le_t *addr, s8_t rssi, u8_t type, struct net_buf_simple *ad) { /* We're only interested in connectable events */ if (type == BT_LE_ADV_IND || type == BT_LE_ADV_DIRECT_IND) { ad_parse(ad, eir_found, (void *)addr); } } static void bt_active_scan(void) { int err; err = bt_le_scan_start(BT_LE_SCAN_ACTIVE, device_found); if (err) { NET_ERR("Bluetooth set active scan failed (err %d)\n", err); } } static void bt_passive_scan(void) { int err; err = bt_le_scan_start(BT_LE_SCAN_PASSIVE, device_found); if (err) { NET_ERR("Bluetooth set passive scan failed (err %d)\n", err); } } static void bt_scan_off(void) { int err; err = bt_le_scan_stop(); if (err) { NET_ERR("Stopping scanning failed (err %d)\n", err); } } static int bt_scan(u32_t mgmt_request, struct net_if *iface, void *data, size_t len) { if (!strcmp(data, "on") || !strcmp(data, "active")) { bt_active_scan(); } else if (!strcmp(data, "passive")) { bt_passive_scan(); } else if (!strcmp("off", data)) { bt_scan_off(); } else { return -EINVAL; } return 0; } static int bt_disconnect(u32_t mgmt_request, struct net_if *iface, void *data, size_t len) { struct bt_context *ctxt = net_if_get_device(iface)->driver_data; if (!ctxt->ipsp_chan.chan.conn) { NET_ERR("Not connected"); return -ENOTCONN; } /* Release connect reference in case of central/router role */ if (default_conn) { bt_conn_unref(default_conn); default_conn = NULL; } return bt_l2cap_chan_disconnect(&ctxt->ipsp_chan.chan); } static void connected(struct bt_conn *conn, u8_t err) { if (err) { #if defined(CONFIG_NET_DEBUG_L2_BLUETOOTH) char addr[BT_ADDR_LE_STR_LEN]; bt_addr_le_to_str(bt_conn_get_dst(conn), addr, sizeof(addr)); NET_ERR("Failed to connect to %s (%u)\n", addr, err); #endif return; } if (conn != default_conn) { return; } bt_l2cap_chan_connect(conn, &bt_context_data.ipsp_chan.chan, L2CAP_IPSP_PSM); } static void disconnected(struct bt_conn *conn, u8_t reason) { #if defined(CONFIG_NET_DEBUG_L2_BLUETOOTH) char addr[BT_ADDR_LE_STR_LEN]; #endif if (conn != default_conn) { return; } #if defined(CONFIG_NET_DEBUG_L2_BLUETOOTH) bt_addr_le_to_str(bt_conn_get_dst(conn), addr, sizeof(addr)); NET_DBG("Disconnected: %s (reason %u)\n", addr, reason); #endif bt_conn_unref(default_conn); default_conn = NULL; } static struct bt_conn_cb conn_callbacks = { .connected = connected, .disconnected = disconnected, }; #endif /* CONFIG_NET_L2_BLUETOOTH_MGMT */ static int net_bt_init(struct device *dev) { NET_DBG("dev %p driver_data %p", dev, dev->driver_data); #if defined(CONFIG_NET_L2_BLUETOOTH_MGMT) bt_conn_cb_register(&conn_callbacks); #endif bt_l2cap_server_register(&server); return 0; } #if defined(CONFIG_NET_L2_BLUETOOTH_MGMT) NET_MGMT_REGISTER_REQUEST_HANDLER(NET_REQUEST_BT_CONNECT, bt_connect); NET_MGMT_REGISTER_REQUEST_HANDLER(NET_REQUEST_BT_SCAN, bt_scan); NET_MGMT_REGISTER_REQUEST_HANDLER(NET_REQUEST_BT_DISCONNECT, bt_disconnect); #endif NET_DEVICE_INIT(net_bt, "net_bt", net_bt_init, &bt_context_data, NULL, CONFIG_KERNEL_INIT_PRIORITY_DEFAULT, &bt_if_api, BLUETOOTH_L2, NET_L2_GET_CTX_TYPE(BLUETOOTH_L2), L2CAP_IPSP_MTU);
420708.c
/* * Copyright (c) 2016 Intel Corporation * * SPDX-License-Identifier: Apache-2.0 */ #include <device.h> #include <drivers/i2c.h> #include <sys/util.h> #include <kernel.h> #include <drivers/sensor.h> #include <logging/log.h> #include "mpu6050.h" LOG_MODULE_DECLARE(MPU6050, CONFIG_SENSOR_LOG_LEVEL); int mpu6050_trigger_set(struct device *dev, const struct sensor_trigger *trig, sensor_trigger_handler_t handler) { struct mpu6050_data *drv_data = dev->driver_data; const struct mpu6050_config *cfg = dev->config->config_info; if (trig->type != SENSOR_TRIG_DATA_READY) { return -ENOTSUP; } gpio_pin_disable_callback(drv_data->gpio, cfg->int_pin); drv_data->data_ready_handler = handler; if (handler == NULL) { return 0; } drv_data->data_ready_trigger = *trig; gpio_pin_enable_callback(drv_data->gpio, cfg->int_pin); return 0; } static void mpu6050_gpio_callback(struct device *dev, struct gpio_callback *cb, u32_t pins) { struct mpu6050_data *drv_data = CONTAINER_OF(cb, struct mpu6050_data, gpio_cb); const struct mpu6050_config *cfg = drv_data->dev->config->config_info; ARG_UNUSED(pins); gpio_pin_disable_callback(dev, cfg->int_pin); #if defined(CONFIG_MPU6050_TRIGGER_OWN_THREAD) k_sem_give(&drv_data->gpio_sem); #elif defined(CONFIG_MPU6050_TRIGGER_GLOBAL_THREAD) k_work_submit(&drv_data->work); #endif } static void mpu6050_thread_cb(void *arg) { struct device *dev = arg; struct mpu6050_data *drv_data = dev->driver_data; const struct mpu6050_config *cfg = dev->config->config_info; if (drv_data->data_ready_handler != NULL) { drv_data->data_ready_handler(dev, &drv_data->data_ready_trigger); } gpio_pin_enable_callback(drv_data->gpio, cfg->int_pin); } #ifdef CONFIG_MPU6050_TRIGGER_OWN_THREAD static void mpu6050_thread(int dev_ptr, int unused) { struct device *dev = INT_TO_POINTER(dev_ptr); struct mpu6050_data *drv_data = dev->driver_data; ARG_UNUSED(unused); while (1) { k_sem_take(&drv_data->gpio_sem, K_FOREVER); mpu6050_thread_cb(dev); } } #endif #ifdef CONFIG_MPU6050_TRIGGER_GLOBAL_THREAD static void mpu6050_work_cb(struct k_work *work) { struct mpu6050_data *drv_data = CONTAINER_OF(work, struct mpu6050_data, work); mpu6050_thread_cb(drv_data->dev); } #endif int mpu6050_init_interrupt(struct device *dev) { struct mpu6050_data *drv_data = dev->driver_data; const struct mpu6050_config *cfg = dev->config->config_info; /* setup data ready gpio interrupt */ drv_data->gpio = device_get_binding(cfg->int_label); if (drv_data->gpio == NULL) { LOG_ERR("Failed to get pointer to %s device", cfg->int_label); return -EINVAL; } drv_data->dev = dev; gpio_pin_configure(drv_data->gpio, cfg->int_pin, GPIO_DIR_IN | GPIO_INT | GPIO_INT_EDGE | GPIO_INT_ACTIVE_HIGH | GPIO_INT_DEBOUNCE); gpio_init_callback(&drv_data->gpio_cb, mpu6050_gpio_callback, BIT(cfg->int_pin)); if (gpio_add_callback(drv_data->gpio, &drv_data->gpio_cb) < 0) { LOG_ERR("Failed to set gpio callback"); return -EIO; } /* enable data ready interrupt */ if (i2c_reg_write_byte(drv_data->i2c, cfg->i2c_addr, MPU6050_REG_INT_EN, MPU6050_DRDY_EN) < 0) { LOG_ERR("Failed to enable data ready interrupt."); return -EIO; } #if defined(CONFIG_MPU6050_TRIGGER_OWN_THREAD) k_sem_init(&drv_data->gpio_sem, 0, UINT_MAX); k_thread_create(&drv_data->thread, drv_data->thread_stack, CONFIG_MPU6050_THREAD_STACK_SIZE, (k_thread_entry_t)mpu6050_thread, dev, 0, NULL, K_PRIO_COOP(CONFIG_MPU6050_THREAD_PRIORITY), 0, K_NO_WAIT); #elif defined(CONFIG_MPU6050_TRIGGER_GLOBAL_THREAD) drv_data->work.handler = mpu6050_work_cb; #endif gpio_pin_enable_callback(drv_data->gpio, cfg->int_pin); return 0; }
148517.c
/* * Generated by asn1c-0.9.27 (http://lionet.info/asn1c) * From ASN.1 module "DSRC" * found in "../J2735_R41_Source_mod.ASN" * `asn1c -gen-PER -fcompound-names -fincludes-quoted` */ #include "Offset-B13.h" int Offset_B13_constraint(asn_TYPE_descriptor_t *td, const void *sptr, asn_app_constraint_failed_f *ctfailcb, void *app_key) { long value; if(!sptr) { _ASN_CTFAIL(app_key, td, sptr, "%s: value not given (%s:%d)", td->name, __FILE__, __LINE__); return -1; } value = *(const long *)sptr; if((value >= -4096 && value <= 4095)) { /* Constraint check succeeded */ return 0; } else { _ASN_CTFAIL(app_key, td, sptr, "%s: constraint failed (%s:%d)", td->name, __FILE__, __LINE__); return -1; } } /* * This type is implemented using NativeInteger, * so here we adjust the DEF accordingly. */ static void Offset_B13_1_inherit_TYPE_descriptor(asn_TYPE_descriptor_t *td) { td->free_struct = asn_DEF_NativeInteger.free_struct; td->print_struct = asn_DEF_NativeInteger.print_struct; td->check_constraints = asn_DEF_NativeInteger.check_constraints; td->ber_decoder = asn_DEF_NativeInteger.ber_decoder; td->der_encoder = asn_DEF_NativeInteger.der_encoder; td->xer_decoder = asn_DEF_NativeInteger.xer_decoder; td->xer_encoder = asn_DEF_NativeInteger.xer_encoder; td->uper_decoder = asn_DEF_NativeInteger.uper_decoder; td->uper_encoder = asn_DEF_NativeInteger.uper_encoder; if(!td->per_constraints) td->per_constraints = asn_DEF_NativeInteger.per_constraints; td->elements = asn_DEF_NativeInteger.elements; td->elements_count = asn_DEF_NativeInteger.elements_count; td->specifics = asn_DEF_NativeInteger.specifics; } void Offset_B13_free(asn_TYPE_descriptor_t *td, void *struct_ptr, int contents_only) { Offset_B13_1_inherit_TYPE_descriptor(td); td->free_struct(td, struct_ptr, contents_only); } int Offset_B13_print(asn_TYPE_descriptor_t *td, const void *struct_ptr, int ilevel, asn_app_consume_bytes_f *cb, void *app_key) { Offset_B13_1_inherit_TYPE_descriptor(td); return td->print_struct(td, struct_ptr, ilevel, cb, app_key); } asn_dec_rval_t Offset_B13_decode_ber(asn_codec_ctx_t *opt_codec_ctx, asn_TYPE_descriptor_t *td, void **structure, const void *bufptr, size_t size, int tag_mode) { Offset_B13_1_inherit_TYPE_descriptor(td); return td->ber_decoder(opt_codec_ctx, td, structure, bufptr, size, tag_mode); } asn_enc_rval_t Offset_B13_encode_der(asn_TYPE_descriptor_t *td, void *structure, int tag_mode, ber_tlv_tag_t tag, asn_app_consume_bytes_f *cb, void *app_key) { Offset_B13_1_inherit_TYPE_descriptor(td); return td->der_encoder(td, structure, tag_mode, tag, cb, app_key); } asn_dec_rval_t Offset_B13_decode_xer(asn_codec_ctx_t *opt_codec_ctx, asn_TYPE_descriptor_t *td, void **structure, const char *opt_mname, const void *bufptr, size_t size) { Offset_B13_1_inherit_TYPE_descriptor(td); return td->xer_decoder(opt_codec_ctx, td, structure, opt_mname, bufptr, size); } asn_enc_rval_t Offset_B13_encode_xer(asn_TYPE_descriptor_t *td, void *structure, int ilevel, enum xer_encoder_flags_e flags, asn_app_consume_bytes_f *cb, void *app_key) { Offset_B13_1_inherit_TYPE_descriptor(td); return td->xer_encoder(td, structure, ilevel, flags, cb, app_key); } asn_dec_rval_t Offset_B13_decode_uper(asn_codec_ctx_t *opt_codec_ctx, asn_TYPE_descriptor_t *td, asn_per_constraints_t *constraints, void **structure, asn_per_data_t *per_data) { Offset_B13_1_inherit_TYPE_descriptor(td); return td->uper_decoder(opt_codec_ctx, td, constraints, structure, per_data); } asn_enc_rval_t Offset_B13_encode_uper(asn_TYPE_descriptor_t *td, asn_per_constraints_t *constraints, void *structure, asn_per_outp_t *per_out) { Offset_B13_1_inherit_TYPE_descriptor(td); return td->uper_encoder(td, constraints, structure, per_out); } static asn_per_constraints_t asn_PER_type_Offset_B13_constr_1 GCC_NOTUSED = { { APC_CONSTRAINED, 13, 13, -4096, 4095 } /* (-4096..4095) */, { APC_UNCONSTRAINED, -1, -1, 0, 0 }, 0, 0 /* No PER value map */ }; static ber_tlv_tag_t asn_DEF_Offset_B13_tags_1[] = { (ASN_TAG_CLASS_UNIVERSAL | (2 << 2)) }; asn_TYPE_descriptor_t asn_DEF_Offset_B13 = { "Offset-B13", "Offset-B13", Offset_B13_free, Offset_B13_print, Offset_B13_constraint, Offset_B13_decode_ber, Offset_B13_encode_der, Offset_B13_decode_xer, Offset_B13_encode_xer, Offset_B13_decode_uper, Offset_B13_encode_uper, 0, /* Use generic outmost tag fetcher */ asn_DEF_Offset_B13_tags_1, sizeof(asn_DEF_Offset_B13_tags_1) /sizeof(asn_DEF_Offset_B13_tags_1[0]), /* 1 */ asn_DEF_Offset_B13_tags_1, /* Same as above */ sizeof(asn_DEF_Offset_B13_tags_1) /sizeof(asn_DEF_Offset_B13_tags_1[0]), /* 1 */ &asn_PER_type_Offset_B13_constr_1, 0, 0, /* No members */ 0 /* No specifics */ };
229060.c
/**************************************************************************** * arch/risc-v/src/nr5m100/nr5_irq_dispatch.c * * Copyright (C) 2016 Ken Pettit. All rights reserved. * Author: Ken Pettit <pettitkd@gmail.com> * * Modified for RISC-V: * * Copyright (C) 2016 Ken Pettit. All rights reserved. * Author: Ken Pettit <pettitkd@gmail.com> * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ /**************************************************************************** * Included Files ****************************************************************************/ #include <nuttx/config.h> #include <stdint.h> #include <assert.h> #include <nuttx/irq.h> #include <nuttx/arch.h> #include <nuttx/board.h> #include <arch/board/board.h> #include "riscv_arch.h" #include "riscv_internal.h" #include "group/group.h" /**************************************************************************** * Extern Functions ****************************************************************************/ int up_lsbenc(int); /**************************************************************************** * Public Data ****************************************************************************/ volatile uint32_t * g_current_regs; /**************************************************************************** * Public Functions ****************************************************************************/ /**************************************************************************** * irq_dispatch_all ****************************************************************************/ uint32_t * irq_dispatch_all(uint32_t *regs, uint32_t irqmask) { int next; int mask; mask = irqmask & 0xffff; board_autoled_on(LED_INIRQ); #ifdef CONFIG_SUPPRESS_INTERRUPTS PANIC(); #else /* Current regs non-zero indicates that we are processing an interrupt; * g_current_regs is also used to manage interrupt level context switches. * * Nested interrupts are not supported */ DEBUGASSERT(g_current_regs == NULL); g_current_regs = regs; /* Get ordinal index of interrupt number from mask */ next = up_lsbenc(mask); while (next != -1) { /* Deliver the IRQ */ irq_dispatch(next, regs); /* Clear the IRQ from the mask */ mask &= !(1 << next); next = up_lsbenc(mask); #if defined(CONFIG_ARCH_FPU) || defined(CONFIG_ARCH_ADDRENV) /* Check for a context switch. If a context switch occurred, then * g_current_regs will have a different value than it did on entry. * If an interrupt level context switch has occurred, then restore the * floating point state and the establish the correct address * environment before returning from the interrupt. */ if (regs != g_current_regs) { #ifdef CONFIG_ARCH_FPU /* Restore floating point registers */ up_restorefpu((uint32_t *)g_current_regs); #endif #ifdef CONFIG_ARCH_ADDRENV /* Make sure that the address environment for the previously * running task is closed down gracefully (data caches dump, * MMU flushed) and set up the address environment for the new * thread at the head of the ready-to-run list. */ group_addrenv(NULL); #endif } #endif } #endif /* If a context switch occurred while processing the interrupt then * g_current_regs may have change value. If we return any value different * from the input regs, then the lower level will know that a context * switch occurred during interrupt processing. */ regs = (uint32_t *) g_current_regs; g_current_regs = NULL; board_autoled_off(LED_INIRQ); /* Return the stack pointer */ return regs; }
286822.c
/** @file Implementation of EFI_HTTP_PROTOCOL protocol interfaces. Copyright (c) 2015 - 2017, Intel Corporation. All rights reserved.<BR> (C) Copyright 2015-2016 Hewlett Packard Enterprise Development LP<BR> This program and the accompanying materials are licensed and made available under the terms and conditions of the BSD License which accompanies this distribution. The full text of the license may be found at http://opensource.org/licenses/bsd-license.php. THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED. **/ #include "HttpDriver.h" EFI_HTTP_PROTOCOL mEfiHttpTemplate = { EfiHttpGetModeData, EfiHttpConfigure, EfiHttpRequest, EfiHttpCancel, EfiHttpResponse, EfiHttpPoll }; /** Returns the operational parameters for the current HTTP child instance. The GetModeData() function is used to read the current mode data (operational parameters) for this HTTP protocol instance. @param[in] This Pointer to EFI_HTTP_PROTOCOL instance. @param[out] HttpConfigData Point to buffer for operational parameters of this HTTP instance. @retval EFI_SUCCESS Operation succeeded. @retval EFI_INVALID_PARAMETER One or more of the following conditions is TRUE: This is NULL. HttpConfigData is NULL. HttpInstance->LocalAddressIsIPv6 is FALSE and HttpConfigData->IPv4Node is NULL. HttpInstance->LocalAddressIsIPv6 is TRUE and HttpConfigData->IPv6Node is NULL. @retval EFI_NOT_STARTED This EFI HTTP Protocol instance has not been started. **/ EFI_STATUS EFIAPI EfiHttpGetModeData ( IN EFI_HTTP_PROTOCOL *This, OUT EFI_HTTP_CONFIG_DATA *HttpConfigData ) { HTTP_PROTOCOL *HttpInstance; // // Check input parameters. // if ((This == NULL) || (HttpConfigData == NULL)) { return EFI_INVALID_PARAMETER; } HttpInstance = HTTP_INSTANCE_FROM_PROTOCOL (This); ASSERT (HttpInstance != NULL); if ((HttpInstance->LocalAddressIsIPv6 && HttpConfigData->AccessPoint.IPv6Node == NULL) || (!HttpInstance->LocalAddressIsIPv6 && HttpConfigData->AccessPoint.IPv4Node == NULL)) { return EFI_INVALID_PARAMETER; } if (HttpInstance->State < HTTP_STATE_HTTP_CONFIGED) { return EFI_NOT_STARTED; } HttpConfigData->HttpVersion = HttpInstance->HttpVersion; HttpConfigData->TimeOutMillisec = HttpInstance->TimeOutMillisec; HttpConfigData->LocalAddressIsIPv6 = HttpInstance->LocalAddressIsIPv6; if (HttpInstance->LocalAddressIsIPv6) { CopyMem ( HttpConfigData->AccessPoint.IPv6Node, &HttpInstance->Ipv6Node, sizeof (HttpInstance->Ipv6Node) ); } else { CopyMem ( HttpConfigData->AccessPoint.IPv4Node, &HttpInstance->IPv4Node, sizeof (HttpInstance->IPv4Node) ); } return EFI_SUCCESS; } /** Initialize or brutally reset the operational parameters for this EFI HTTP instance. The Configure() function does the following: When HttpConfigData is not NULL Initialize this EFI HTTP instance by configuring timeout, local address, port, etc. When HttpConfigData is NULL, reset this EFI HTTP instance by closing all active connections with remote hosts, canceling all asynchronous tokens, and flush request and response buffers without informing the appropriate hosts. No other EFI HTTP function can be executed by this instance until the Configure() function is executed and returns successfully. @param[in] This Pointer to EFI_HTTP_PROTOCOL instance. @param[in] HttpConfigData Pointer to the configure data to configure the instance. @retval EFI_SUCCESS Operation succeeded. @retval EFI_INVALID_PARAMETER One or more of the following conditions is TRUE: This is NULL. HttpConfigData->LocalAddressIsIPv6 is FALSE and HttpConfigData->IPv4Node is NULL. HttpConfigData->LocalAddressIsIPv6 is TRUE and HttpConfigData->IPv6Node is NULL. @retval EFI_ALREADY_STARTED Reinitialize this HTTP instance without calling Configure() with NULL to reset it. @retval EFI_DEVICE_ERROR An unexpected system or network error occurred. @retval EFI_OUT_OF_RESOURCES Could not allocate enough system resources when executing Configure(). @retval EFI_UNSUPPORTED One or more options in HttpConfigData are not supported in the implementation. **/ EFI_STATUS EFIAPI EfiHttpConfigure ( IN EFI_HTTP_PROTOCOL *This, IN EFI_HTTP_CONFIG_DATA *HttpConfigData ) { HTTP_PROTOCOL *HttpInstance; EFI_STATUS Status; // // Check input parameters. // if (This == NULL || (HttpConfigData != NULL && ((HttpConfigData->LocalAddressIsIPv6 && HttpConfigData->AccessPoint.IPv6Node == NULL) || (!HttpConfigData->LocalAddressIsIPv6 && HttpConfigData->AccessPoint.IPv4Node == NULL)))) { return EFI_INVALID_PARAMETER; } HttpInstance = HTTP_INSTANCE_FROM_PROTOCOL (This); ASSERT (HttpInstance != NULL && HttpInstance->Service != NULL); if (HttpConfigData != NULL) { // // Now configure this HTTP instance. // if (HttpInstance->State != HTTP_STATE_UNCONFIGED) { return EFI_ALREADY_STARTED; } HttpInstance->HttpVersion = HttpConfigData->HttpVersion; HttpInstance->TimeOutMillisec = HttpConfigData->TimeOutMillisec; HttpInstance->LocalAddressIsIPv6 = HttpConfigData->LocalAddressIsIPv6; if (HttpConfigData->LocalAddressIsIPv6) { CopyMem ( &HttpInstance->Ipv6Node, HttpConfigData->AccessPoint.IPv6Node, sizeof (HttpInstance->Ipv6Node) ); } else { CopyMem ( &HttpInstance->IPv4Node, HttpConfigData->AccessPoint.IPv4Node, sizeof (HttpInstance->IPv4Node) ); } // // Creat Tcp child // Status = HttpInitProtocol (HttpInstance, HttpInstance->LocalAddressIsIPv6); if (EFI_ERROR (Status)) { return Status; } HttpInstance->State = HTTP_STATE_HTTP_CONFIGED; return EFI_SUCCESS; } else { // // Reset all the resources related to HttpInsance. // HttpCleanProtocol (HttpInstance); HttpInstance->State = HTTP_STATE_UNCONFIGED; return EFI_SUCCESS; } } /** The Request() function queues an HTTP request to this HTTP instance. Similar to Transmit() function in the EFI TCP driver. When the HTTP request is sent successfully, or if there is an error, Status in token will be updated and Event will be signaled. @param[in] This Pointer to EFI_HTTP_PROTOCOL instance. @param[in] Token Pointer to storage containing HTTP request token. @retval EFI_SUCCESS Outgoing data was processed. @retval EFI_NOT_STARTED This EFI HTTP Protocol instance has not been started. @retval EFI_DEVICE_ERROR An unexpected system or network error occurred. @retval EFI_TIMEOUT Data was dropped out of the transmit or receive queue. @retval EFI_OUT_OF_RESOURCES Could not allocate enough system resources. @retval EFI_UNSUPPORTED The HTTP method is not supported in current implementation. @retval EFI_INVALID_PARAMETER One or more of the following conditions is TRUE: This is NULL. Token is NULL. Token->Message is NULL. Token->Message->Body is not NULL, Token->Message->BodyLength is non-zero, and Token->Message->Data is NULL, but a previous call to Request()has not been completed successfully. **/ EFI_STATUS EFIAPI EfiHttpRequest ( IN EFI_HTTP_PROTOCOL *This, IN EFI_HTTP_TOKEN *Token ) { EFI_HTTP_MESSAGE *HttpMsg; EFI_HTTP_REQUEST_DATA *Request; VOID *UrlParser; EFI_STATUS Status; CHAR8 *HostName; UINTN HostNameSize; UINT16 RemotePort; HTTP_PROTOCOL *HttpInstance; BOOLEAN Configure; BOOLEAN ReConfigure; BOOLEAN TlsConfigure; CHAR8 *RequestMsg; CHAR8 *Url; UINTN UrlLen; CHAR16 *HostNameStr; HTTP_TOKEN_WRAP *Wrap; CHAR8 *FileUrl; UINTN RequestMsgSize; EFI_HANDLE ImageHandle; // // Initializations // Url = NULL; UrlParser = NULL; RemotePort = 0; HostName = NULL; RequestMsg = NULL; HostNameStr = NULL; Wrap = NULL; FileUrl = NULL; TlsConfigure = FALSE; if ((This == NULL) || (Token == NULL)) { return EFI_INVALID_PARAMETER; } HttpMsg = Token->Message; if (HttpMsg == NULL) { return EFI_INVALID_PARAMETER; } Request = HttpMsg->Data.Request; // // Only support GET, HEAD, PUT and POST method in current implementation. // if ((Request != NULL) && (Request->Method != HttpMethodGet) && (Request->Method != HttpMethodHead) && (Request->Method != HttpMethodPut) && (Request->Method != HttpMethodPost)) { return EFI_UNSUPPORTED; } HttpInstance = HTTP_INSTANCE_FROM_PROTOCOL (This); ASSERT (HttpInstance != NULL); // // Capture the method into HttpInstance. // if (Request != NULL) { HttpInstance->Method = Request->Method; } if (HttpInstance->State < HTTP_STATE_HTTP_CONFIGED) { return EFI_NOT_STARTED; } if (Request == NULL) { // // Request would be NULL only for PUT/POST operation (in the current implementation) // if ((HttpInstance->Method != HttpMethodPut) && (HttpInstance->Method != HttpMethodPost)) { return EFI_INVALID_PARAMETER; } // // For PUT/POST, we need to have the TCP already configured. Bail out if it is not! // if (HttpInstance->State < HTTP_STATE_TCP_CONFIGED) { return EFI_INVALID_PARAMETER; } // // We need to have the Message Body for sending the HTTP message across in these cases. // if (HttpMsg->Body == NULL || HttpMsg->BodyLength == 0) { return EFI_INVALID_PARAMETER; } // // Use existing TCP instance to transmit the packet. // Configure = FALSE; ReConfigure = FALSE; } else { // // Check whether the token already existed. // if (EFI_ERROR (NetMapIterate (&HttpInstance->TxTokens, HttpTokenExist, Token))) { return EFI_ACCESS_DENIED; } // // Parse the URI of the remote host. // Url = HttpInstance->Url; UrlLen = StrLen (Request->Url) + 1; if (UrlLen > HTTP_URL_BUFFER_LEN) { Url = AllocateZeroPool (UrlLen); if (Url == NULL) { return EFI_OUT_OF_RESOURCES; } FreePool (HttpInstance->Url); HttpInstance->Url = Url; } UnicodeStrToAsciiStrS (Request->Url, Url, UrlLen); // // From the information in Url, the HTTP instance will // be able to determine whether to use http or https. // HttpInstance->UseHttps = IsHttpsUrl (Url); // // HTTP is disabled, return directly if the URI is not HTTPS. // if (!PcdGetBool (PcdAllowHttpConnections) && !(HttpInstance->UseHttps)) { DEBUG ((EFI_D_ERROR, "EfiHttpRequest: HTTP is disabled.\n")); return EFI_ACCESS_DENIED; } // // Check whether we need to create Tls child and open the TLS protocol. // if (HttpInstance->UseHttps && HttpInstance->TlsChildHandle == NULL) { // // Use TlsSb to create Tls child and open the TLS protocol. // if (HttpInstance->LocalAddressIsIPv6) { ImageHandle = HttpInstance->Service->Ip6DriverBindingHandle; } else { ImageHandle = HttpInstance->Service->Ip4DriverBindingHandle; } HttpInstance->TlsChildHandle = TlsCreateChild ( ImageHandle, &(HttpInstance->Tls), &(HttpInstance->TlsConfiguration) ); if (HttpInstance->TlsChildHandle == NULL) { return EFI_DEVICE_ERROR; } TlsConfigure = TRUE; } UrlParser = NULL; Status = HttpParseUrl (Url, (UINT32) AsciiStrLen (Url), FALSE, &UrlParser); if (EFI_ERROR (Status)) { goto Error1; } HostName = NULL; Status = HttpUrlGetHostName (Url, UrlParser, &HostName); if (EFI_ERROR (Status)) { goto Error1; } Status = HttpUrlGetPort (Url, UrlParser, &RemotePort); if (EFI_ERROR (Status)) { if (HttpInstance->UseHttps) { RemotePort = HTTPS_DEFAULT_PORT; } else { RemotePort = HTTP_DEFAULT_PORT; } } // // If Configure is TRUE, it indicates the first time to call Request(); // If ReConfigure is TRUE, it indicates the request URL is not same // with the previous call to Request(); // Configure = TRUE; ReConfigure = TRUE; if (HttpInstance->RemoteHost == NULL) { // // Request() is called the first time. // ReConfigure = FALSE; } else { if ((HttpInstance->RemotePort == RemotePort) && (AsciiStrCmp (HttpInstance->RemoteHost, HostName) == 0) && (!HttpInstance->UseHttps || (HttpInstance->UseHttps && !TlsConfigure && HttpInstance->TlsSessionState == EfiTlsSessionDataTransferring))) { // // Host Name and port number of the request URL are the same with previous call to Request(). // If Https protocol used, the corresponding SessionState is EfiTlsSessionDataTransferring. // Check whether previous TCP packet sent out. // if (EFI_ERROR (NetMapIterate (&HttpInstance->TxTokens, HttpTcpNotReady, NULL))) { // // Wrap the HTTP token in HTTP_TOKEN_WRAP // Wrap = AllocateZeroPool (sizeof (HTTP_TOKEN_WRAP)); if (Wrap == NULL) { Status = EFI_OUT_OF_RESOURCES; goto Error1; } Wrap->HttpToken = Token; Wrap->HttpInstance = HttpInstance; Status = HttpCreateTcpTxEvent (Wrap); if (EFI_ERROR (Status)) { goto Error1; } Status = NetMapInsertTail (&HttpInstance->TxTokens, Token, Wrap); if (EFI_ERROR (Status)) { goto Error1; } Wrap->TcpWrap.Method = Request->Method; FreePool (HostName); // // Queue the HTTP token and return. // return EFI_SUCCESS; } else { // // Use existing TCP instance to transmit the packet. // Configure = FALSE; ReConfigure = FALSE; } } else { // // Need close existing TCP instance and create a new TCP instance for data transmit. // if (HttpInstance->RemoteHost != NULL) { FreePool (HttpInstance->RemoteHost); HttpInstance->RemoteHost = NULL; HttpInstance->RemotePort = 0; } } } } if (Configure) { // // Parse Url for IPv4 or IPv6 address, if failed, perform DNS resolution. // if (!HttpInstance->LocalAddressIsIPv6) { Status = NetLibAsciiStrToIp4 (HostName, &HttpInstance->RemoteAddr); } else { Status = HttpUrlGetIp6 (Url, UrlParser, &HttpInstance->RemoteIpv6Addr); } if (EFI_ERROR (Status)) { HostNameSize = AsciiStrSize (HostName); HostNameStr = AllocateZeroPool (HostNameSize * sizeof (CHAR16)); if (HostNameStr == NULL) { Status = EFI_OUT_OF_RESOURCES; goto Error1; } AsciiStrToUnicodeStrS (HostName, HostNameStr, HostNameSize); if (!HttpInstance->LocalAddressIsIPv6) { Status = HttpDns4 (HttpInstance, HostNameStr, &HttpInstance->RemoteAddr); } else { Status = HttpDns6 (HttpInstance, HostNameStr, &HttpInstance->RemoteIpv6Addr); } FreePool (HostNameStr); if (EFI_ERROR (Status)) { goto Error1; } } // // Save the RemotePort and RemoteHost. // ASSERT (HttpInstance->RemoteHost == NULL); HttpInstance->RemotePort = RemotePort; HttpInstance->RemoteHost = HostName; HostName = NULL; } if (ReConfigure) { // // The request URL is different from previous calls to Request(), close existing TCP instance. // if (!HttpInstance->LocalAddressIsIPv6) { ASSERT (HttpInstance->Tcp4 != NULL); } else { ASSERT (HttpInstance->Tcp6 != NULL); } if (HttpInstance->UseHttps && !TlsConfigure) { Status = TlsCloseSession (HttpInstance); if (EFI_ERROR (Status)) { goto Error1; } TlsCloseTxRxEvent (HttpInstance); } HttpCloseConnection (HttpInstance); EfiHttpCancel (This, NULL); } // // Wrap the HTTP token in HTTP_TOKEN_WRAP // Wrap = AllocateZeroPool (sizeof (HTTP_TOKEN_WRAP)); if (Wrap == NULL) { Status = EFI_OUT_OF_RESOURCES; goto Error1; } Wrap->HttpToken = Token; Wrap->HttpInstance = HttpInstance; if (Request != NULL) { Wrap->TcpWrap.Method = Request->Method; } Status = HttpInitSession ( HttpInstance, Wrap, Configure || ReConfigure, TlsConfigure ); if (EFI_ERROR (Status)) { goto Error2; } if (!Configure && !ReConfigure && !TlsConfigure) { // // For the new HTTP token, create TX TCP token events. // Status = HttpCreateTcpTxEvent (Wrap); if (EFI_ERROR (Status)) { goto Error1; } } // // Create request message. // FileUrl = Url; if (Url != NULL && *FileUrl != '/') { // // Convert the absolute-URI to the absolute-path // while (*FileUrl != ':') { FileUrl++; } if ((*(FileUrl+1) == '/') && (*(FileUrl+2) == '/')) { FileUrl += 3; while (*FileUrl != '/') { FileUrl++; } } else { Status = EFI_INVALID_PARAMETER; goto Error3; } } Status = HttpGenRequestMessage (HttpMsg, FileUrl, &RequestMsg, &RequestMsgSize); if (EFI_ERROR (Status) || NULL == RequestMsg) { goto Error3; } ASSERT (RequestMsg != NULL); // // Every request we insert a TxToken and a response call would remove the TxToken. // In cases of PUT/POST, after an initial request-response pair, we would do a // continuous request without a response call. So, in such cases, where Request // structure is NULL, we would not insert a TxToken. // if (Request != NULL) { Status = NetMapInsertTail (&HttpInstance->TxTokens, Token, Wrap); if (EFI_ERROR (Status)) { goto Error4; } } // // Transmit the request message. // Status = HttpTransmitTcp ( HttpInstance, Wrap, (UINT8*) RequestMsg, RequestMsgSize ); if (EFI_ERROR (Status)) { goto Error5; } DispatchDpc (); if (HostName != NULL) { FreePool (HostName); } return EFI_SUCCESS; Error5: // // We would have inserted a TxToken only if Request structure is not NULL. // Hence check before we do a remove in this error case. // if (Request != NULL) { NetMapRemoveTail (&HttpInstance->TxTokens, NULL); } Error4: if (RequestMsg != NULL) { FreePool (RequestMsg); } Error3: if (HttpInstance->UseHttps) { TlsCloseSession (HttpInstance); TlsCloseTxRxEvent (HttpInstance); } Error2: HttpCloseConnection (HttpInstance); HttpCloseTcpConnCloseEvent (HttpInstance); if (NULL != Wrap->TcpWrap.Tx4Token.CompletionToken.Event) { gBS->CloseEvent (Wrap->TcpWrap.Tx4Token.CompletionToken.Event); Wrap->TcpWrap.Tx4Token.CompletionToken.Event = NULL; } if (NULL != Wrap->TcpWrap.Tx6Token.CompletionToken.Event) { gBS->CloseEvent (Wrap->TcpWrap.Tx6Token.CompletionToken.Event); Wrap->TcpWrap.Tx6Token.CompletionToken.Event = NULL; } Error1: if (HostName != NULL) { FreePool (HostName); } if (Wrap != NULL) { FreePool (Wrap); } if (UrlParser!= NULL) { HttpUrlFreeParser (UrlParser); } return Status; } /** Cancel a user's Token. @param[in] Map The HTTP instance's token queue. @param[in] Item Object container for one HTTP token and token's wrap. @param[in] Context The user's token to cancel. @retval EFI_SUCCESS Continue to check the next Item. @retval EFI_ABORTED The user's Token (Token != NULL) is cancelled. **/ EFI_STATUS EFIAPI HttpCancelTokens ( IN NET_MAP *Map, IN NET_MAP_ITEM *Item, IN VOID *Context ) { EFI_HTTP_TOKEN *Token; HTTP_TOKEN_WRAP *Wrap; HTTP_PROTOCOL *HttpInstance; Token = (EFI_HTTP_TOKEN *) Context; // // Return EFI_SUCCESS to check the next item in the map if // this one doesn't match. // if ((Token != NULL) && (Token != Item->Key)) { return EFI_SUCCESS; } Wrap = (HTTP_TOKEN_WRAP *) Item->Value; ASSERT (Wrap != NULL); HttpInstance = Wrap->HttpInstance; if (!HttpInstance->LocalAddressIsIPv6) { if (Wrap->TcpWrap.Rx4Token.CompletionToken.Event != NULL) { // // Cancle the Token before close its Event. // HttpInstance->Tcp4->Cancel (HttpInstance->Tcp4, &Wrap->TcpWrap.Rx4Token.CompletionToken); // // Dispatch the DPC queued by the NotifyFunction of the canceled token's events. // DispatchDpc (); } } else { if (Wrap->TcpWrap.Rx6Token.CompletionToken.Event != NULL) { // // Cancle the Token before close its Event. // HttpInstance->Tcp6->Cancel (HttpInstance->Tcp6, &Wrap->TcpWrap.Rx6Token.CompletionToken); // // Dispatch the DPC queued by the NotifyFunction of the canceled token's events. // DispatchDpc (); } } // // If only one item is to be cancel, return EFI_ABORTED to stop // iterating the map any more. // if (Token != NULL) { return EFI_ABORTED; } return EFI_SUCCESS; } /** Cancel the user's receive/transmit request. It is the worker function of EfiHttpCancel API. If a matching token is found, it will call HttpCancelTokens to cancel the token. @param[in] HttpInstance Pointer to HTTP_PROTOCOL structure. @param[in] Token The token to cancel. If NULL, all token will be cancelled. @retval EFI_SUCCESS The token is cancelled. @retval EFI_NOT_FOUND The asynchronous request or response token is not found. @retval Others Other error as indicated. **/ EFI_STATUS HttpCancel ( IN HTTP_PROTOCOL *HttpInstance, IN EFI_HTTP_TOKEN *Token ) { EFI_STATUS Status; // // First check the tokens queued by EfiHttpRequest(). // Status = NetMapIterate (&HttpInstance->TxTokens, HttpCancelTokens, Token); if (EFI_ERROR (Status)) { if (Token != NULL) { if (Status == EFI_ABORTED) { return EFI_SUCCESS; } } else { return Status; } } if (!HttpInstance->UseHttps) { // // Then check the tokens queued by EfiHttpResponse(), except for Https. // Status = NetMapIterate (&HttpInstance->RxTokens, HttpCancelTokens, Token); if (EFI_ERROR (Status)) { if (Token != NULL) { if (Status == EFI_ABORTED) { return EFI_SUCCESS; } else { return EFI_NOT_FOUND; } } else { return Status; } } } else { if (!HttpInstance->LocalAddressIsIPv6) { HttpInstance->Tcp4->Cancel (HttpInstance->Tcp4, &HttpInstance->Tcp4TlsRxToken.CompletionToken); } else { HttpInstance->Tcp6->Cancel (HttpInstance->Tcp6, &HttpInstance->Tcp6TlsRxToken.CompletionToken); } } return EFI_SUCCESS; } /** Abort an asynchronous HTTP request or response token. The Cancel() function aborts a pending HTTP request or response transaction. If Token is not NULL and the token is in transmit or receive queues when it is being cancelled, its Token->Status will be set to EFI_ABORTED and then Token->Event will be signaled. If the token is not in one of the queues, which usually means that the asynchronous operation has completed, EFI_NOT_FOUND is returned. If Token is NULL, all asynchronous tokens issued by Request() or Response() will be aborted. @param[in] This Pointer to EFI_HTTP_PROTOCOL instance. @param[in] Token Point to storage containing HTTP request or response token. @retval EFI_SUCCESS Request and Response queues are successfully flushed. @retval EFI_INVALID_PARAMETER This is NULL. @retval EFI_NOT_STARTED This instance hasn't been configured. @retval EFI_NOT_FOUND The asynchronous request or response token is not found. @retval EFI_UNSUPPORTED The implementation does not support this function. **/ EFI_STATUS EFIAPI EfiHttpCancel ( IN EFI_HTTP_PROTOCOL *This, IN EFI_HTTP_TOKEN *Token ) { HTTP_PROTOCOL *HttpInstance; if (This == NULL) { return EFI_INVALID_PARAMETER; } HttpInstance = HTTP_INSTANCE_FROM_PROTOCOL (This); ASSERT (HttpInstance != NULL); if (HttpInstance->State != HTTP_STATE_TCP_CONNECTED) { return EFI_NOT_STARTED; } return HttpCancel (HttpInstance, Token); } /** A callback function to intercept events during message parser. This function will be invoked during HttpParseMessageBody() with various events type. An error return status of the callback function will cause the HttpParseMessageBody() aborted. @param[in] EventType Event type of this callback call. @param[in] Data A pointer to data buffer. @param[in] Length Length in bytes of the Data. @param[in] Context Callback context set by HttpInitMsgParser(). @retval EFI_SUCCESS Continue to parser the message body. **/ EFI_STATUS EFIAPI HttpBodyParserCallback ( IN HTTP_BODY_PARSE_EVENT EventType, IN CHAR8 *Data, IN UINTN Length, IN VOID *Context ) { HTTP_TOKEN_WRAP *Wrap; UINTN BodyLength; CHAR8 *Body; if (EventType != BodyParseEventOnComplete) { return EFI_SUCCESS; } if (Data == NULL || Length != 0 || Context == NULL) { return EFI_SUCCESS; } Wrap = (HTTP_TOKEN_WRAP *) Context; Body = Wrap->HttpToken->Message->Body; BodyLength = Wrap->HttpToken->Message->BodyLength; if (Data < Body + BodyLength) { Wrap->HttpInstance->NextMsg = Data; } else { Wrap->HttpInstance->NextMsg = NULL; } // // Free Tx4Token or Tx6Token since already received corrsponding HTTP response. // FreePool (Wrap); return EFI_SUCCESS; } /** The work function of EfiHttpResponse(). @param[in] Wrap Pointer to HTTP token's wrap data. @retval EFI_SUCCESS Allocation succeeded. @retval EFI_OUT_OF_RESOURCES Failed to complete the opration due to lack of resources. @retval EFI_NOT_READY Can't find a corresponding Tx4Token/Tx6Token or the EFI_HTTP_UTILITIES_PROTOCOL is not available. **/ EFI_STATUS HttpResponseWorker ( IN HTTP_TOKEN_WRAP *Wrap ) { EFI_STATUS Status; EFI_HTTP_MESSAGE *HttpMsg; CHAR8 *EndofHeader; CHAR8 *HttpHeaders; UINTN SizeofHeaders; UINTN BufferSize; UINTN StatusCode; CHAR8 *Tmp; CHAR8 *HeaderTmp; CHAR8 *StatusCodeStr; UINTN BodyLen; HTTP_PROTOCOL *HttpInstance; EFI_HTTP_TOKEN *Token; NET_MAP_ITEM *Item; HTTP_TOKEN_WRAP *ValueInItem; UINTN HdrLen; NET_FRAGMENT Fragment; if (Wrap == NULL || Wrap->HttpInstance == NULL) { return EFI_INVALID_PARAMETER; } HttpInstance = Wrap->HttpInstance; Token = Wrap->HttpToken; HttpMsg = Token->Message; HttpInstance->EndofHeader = NULL; HttpInstance->HttpHeaders = NULL; HttpMsg->Headers = NULL; HttpHeaders = NULL; SizeofHeaders = 0; BufferSize = 0; EndofHeader = NULL; ValueInItem = NULL; Fragment.Len = 0; Fragment.Bulk = NULL; if (HttpMsg->Data.Response != NULL) { // // Check whether we have cached header from previous call. // if ((HttpInstance->CacheBody != NULL) && (HttpInstance->NextMsg != NULL)) { // // The data is stored at [NextMsg, CacheBody + CacheLen]. // HdrLen = HttpInstance->CacheBody + HttpInstance->CacheLen - HttpInstance->NextMsg; HttpHeaders = AllocateZeroPool (HdrLen); if (HttpHeaders == NULL) { Status = EFI_OUT_OF_RESOURCES; goto Error; } CopyMem (HttpHeaders, HttpInstance->NextMsg, HdrLen); FreePool (HttpInstance->CacheBody); HttpInstance->CacheBody = NULL; HttpInstance->NextMsg = NULL; HttpInstance->CacheOffset = 0; SizeofHeaders = HdrLen; BufferSize = HttpInstance->CacheLen; // // Check whether we cached the whole HTTP headers. // EndofHeader = AsciiStrStr (HttpHeaders, HTTP_END_OF_HDR_STR); } HttpInstance->EndofHeader = &EndofHeader; HttpInstance->HttpHeaders = &HttpHeaders; if (HttpInstance->TimeoutEvent == NULL) { // // Create TimeoutEvent for response // Status = gBS->CreateEvent ( EVT_TIMER, TPL_CALLBACK, NULL, NULL, &HttpInstance->TimeoutEvent ); if (EFI_ERROR (Status)) { goto Error; } } // // Start the timer, and wait Timeout seconds to receive the header packet. // Status = gBS->SetTimer (HttpInstance->TimeoutEvent, TimerRelative, HTTP_RESPONSE_TIMEOUT * TICKS_PER_SECOND); if (EFI_ERROR (Status)) { goto Error; } Status = HttpTcpReceiveHeader (HttpInstance, &SizeofHeaders, &BufferSize, HttpInstance->TimeoutEvent); gBS->SetTimer (HttpInstance->TimeoutEvent, TimerCancel, 0); if (EFI_ERROR (Status)) { goto Error; } ASSERT (HttpHeaders != NULL); // // Cache the part of body. // BodyLen = BufferSize - (EndofHeader - HttpHeaders); if (BodyLen > 0) { if (HttpInstance->CacheBody != NULL) { FreePool (HttpInstance->CacheBody); } HttpInstance->CacheBody = AllocateZeroPool (BodyLen); if (HttpInstance->CacheBody == NULL) { Status = EFI_OUT_OF_RESOURCES; goto Error; } CopyMem (HttpInstance->CacheBody, EndofHeader, BodyLen); HttpInstance->CacheLen = BodyLen; } // // Search for Status Code. // StatusCodeStr = HttpHeaders + AsciiStrLen (HTTP_VERSION_STR) + 1; if (StatusCodeStr == NULL) { Status = EFI_NOT_READY; goto Error; } StatusCode = AsciiStrDecimalToUintn (StatusCodeStr); // // Remove the first line of HTTP message, e.g. "HTTP/1.1 200 OK\r\n". // Tmp = AsciiStrStr (HttpHeaders, HTTP_CRLF_STR); if (Tmp == NULL) { Status = EFI_NOT_READY; goto Error; } // // We could have response with just a HTTP message and no headers. For Example, // "100 Continue". In such cases, we would not want to unnecessarily call a Parse // method. A "\r\n" following Tmp string again would indicate an end. Compare and // set SizeofHeaders to 0. // Tmp = Tmp + AsciiStrLen (HTTP_CRLF_STR); if (CompareMem (Tmp, HTTP_CRLF_STR, AsciiStrLen (HTTP_CRLF_STR)) == 0) { SizeofHeaders = 0; } else { SizeofHeaders = SizeofHeaders - (Tmp - HttpHeaders); } HttpMsg->Data.Response->StatusCode = HttpMappingToStatusCode (StatusCode); HttpInstance->StatusCode = StatusCode; Status = EFI_NOT_READY; ValueInItem = NULL; // // In cases of PUT/POST, after an initial request-response pair, we would do a // continuous request without a response call. So, we would not do an insert of // TxToken. After we have sent the complete file, we will call a response to get // a final response from server. In such a case, we would not have any TxTokens. // Hence, check that case before doing a NetMapRemoveHead. // if (!NetMapIsEmpty (&HttpInstance->TxTokens)) { NetMapRemoveHead (&HttpInstance->TxTokens, (VOID**) &ValueInItem); if (ValueInItem == NULL) { goto Error; } // // The first Tx Token not transmitted yet, insert back and return error. // if (!ValueInItem->TcpWrap.IsTxDone) { goto Error2; } } if (SizeofHeaders != 0) { HeaderTmp = AllocateZeroPool (SizeofHeaders); if (HeaderTmp == NULL) { Status = EFI_OUT_OF_RESOURCES; goto Error2; } CopyMem (HeaderTmp, Tmp, SizeofHeaders); FreePool (HttpHeaders); HttpHeaders = HeaderTmp; // // Check whether the EFI_HTTP_UTILITIES_PROTOCOL is available. // if (mHttpUtilities == NULL) { Status = EFI_NOT_READY; goto Error2; } // // Parse the HTTP header into array of key/value pairs. // Status = mHttpUtilities->Parse ( mHttpUtilities, HttpHeaders, SizeofHeaders, &HttpMsg->Headers, &HttpMsg->HeaderCount ); if (EFI_ERROR (Status)) { goto Error2; } FreePool (HttpHeaders); HttpHeaders = NULL; // // Init message-body parser by header information. // Status = HttpInitMsgParser ( HttpInstance->Method, HttpMsg->Data.Response->StatusCode, HttpMsg->HeaderCount, HttpMsg->Headers, HttpBodyParserCallback, (VOID *) ValueInItem, &HttpInstance->MsgParser ); if (EFI_ERROR (Status)) { goto Error2; } // // Check whether we received a complete HTTP message. // if (HttpInstance->CacheBody != NULL) { Status = HttpParseMessageBody (HttpInstance->MsgParser, HttpInstance->CacheLen, HttpInstance->CacheBody); if (EFI_ERROR (Status)) { goto Error2; } if (HttpIsMessageComplete (HttpInstance->MsgParser)) { // // Free the MsgParse since we already have a full HTTP message. // HttpFreeMsgParser (HttpInstance->MsgParser); HttpInstance->MsgParser = NULL; } } } if ((HttpMsg->Body == NULL) || (HttpMsg->BodyLength == 0)) { Status = EFI_SUCCESS; goto Exit; } } // // Receive the response body. // BodyLen = 0; // // First check whether we cached some data. // if (HttpInstance->CacheBody != NULL) { // // Calculate the length of the cached data. // if (HttpInstance->NextMsg != NULL) { // // We have a cached HTTP message which includes a part of HTTP header of next message. // BodyLen = HttpInstance->NextMsg - (HttpInstance->CacheBody + HttpInstance->CacheOffset); } else { BodyLen = HttpInstance->CacheLen - HttpInstance->CacheOffset; } if (BodyLen > 0) { // // We have some cached data. Just copy the data and return. // if (HttpMsg->BodyLength < BodyLen) { CopyMem (HttpMsg->Body, HttpInstance->CacheBody + HttpInstance->CacheOffset, HttpMsg->BodyLength); HttpInstance->CacheOffset = HttpInstance->CacheOffset + HttpMsg->BodyLength; } else { // // Copy all cached data out. // CopyMem (HttpMsg->Body, HttpInstance->CacheBody + HttpInstance->CacheOffset, BodyLen); HttpInstance->CacheOffset = BodyLen + HttpInstance->CacheOffset; HttpMsg->BodyLength = BodyLen; if (HttpInstance->NextMsg == NULL) { // // There is no HTTP header of next message. Just free the cache buffer. // FreePool (HttpInstance->CacheBody); HttpInstance->CacheBody = NULL; HttpInstance->NextMsg = NULL; HttpInstance->CacheOffset = 0; } } // // Return since we aready received required data. // Status = EFI_SUCCESS; goto Exit; } if (BodyLen == 0 && HttpInstance->MsgParser == NULL) { // // We received a complete HTTP message, and we don't have more data to return to caller. // HttpMsg->BodyLength = 0; Status = EFI_SUCCESS; goto Exit; } } ASSERT (HttpInstance->MsgParser != NULL); // // We still need receive more data when there is no cache data and MsgParser is not NULL; // if (!HttpInstance->UseHttps) { Status = HttpTcpReceiveBody (Wrap, HttpMsg); if (EFI_ERROR (Status)) { goto Error2; } } else { if (HttpInstance->TimeoutEvent == NULL) { // // Create TimeoutEvent for response // Status = gBS->CreateEvent ( EVT_TIMER, TPL_CALLBACK, NULL, NULL, &HttpInstance->TimeoutEvent ); if (EFI_ERROR (Status)) { goto Error2; } } // // Start the timer, and wait Timeout seconds to receive the body packet. // Status = gBS->SetTimer (HttpInstance->TimeoutEvent, TimerRelative, HTTP_RESPONSE_TIMEOUT * TICKS_PER_SECOND); if (EFI_ERROR (Status)) { goto Error2; } Status = HttpsReceive (HttpInstance, &Fragment, HttpInstance->TimeoutEvent); gBS->SetTimer (HttpInstance->TimeoutEvent, TimerCancel, 0); if (EFI_ERROR (Status)) { goto Error2; } // // Check whether we receive a complete HTTP message. // Status = HttpParseMessageBody ( HttpInstance->MsgParser, (UINTN) Fragment.Len, (CHAR8 *) Fragment.Bulk ); if (EFI_ERROR (Status)) { goto Error2; } if (HttpIsMessageComplete (HttpInstance->MsgParser)) { // // Free the MsgParse since we already have a full HTTP message. // HttpFreeMsgParser (HttpInstance->MsgParser); HttpInstance->MsgParser = NULL; } // // We receive part of header of next HTTP msg. // if (HttpInstance->NextMsg != NULL) { HttpMsg->BodyLength = MIN ((UINTN) HttpInstance->NextMsg - (UINTN) Fragment.Bulk, HttpMsg->BodyLength); CopyMem (HttpMsg->Body, Fragment.Bulk, HttpMsg->BodyLength); HttpInstance->CacheLen = Fragment.Len - HttpMsg->BodyLength; if (HttpInstance->CacheLen != 0) { if (HttpInstance->CacheBody != NULL) { FreePool (HttpInstance->CacheBody); } HttpInstance->CacheBody = AllocateZeroPool (HttpInstance->CacheLen); if (HttpInstance->CacheBody == NULL) { Status = EFI_OUT_OF_RESOURCES; goto Error2; } CopyMem (HttpInstance->CacheBody, Fragment.Bulk + HttpMsg->BodyLength, HttpInstance->CacheLen); HttpInstance->CacheOffset = 0; HttpInstance->NextMsg = HttpInstance->CacheBody + ((UINTN) HttpInstance->NextMsg - (UINTN) (Fragment.Bulk + HttpMsg->BodyLength)); } } else { HttpMsg->BodyLength = MIN (Fragment.Len, (UINT32) HttpMsg->BodyLength); CopyMem (HttpMsg->Body, Fragment.Bulk, HttpMsg->BodyLength); HttpInstance->CacheLen = Fragment.Len - HttpMsg->BodyLength; if (HttpInstance->CacheLen != 0) { if (HttpInstance->CacheBody != NULL) { FreePool (HttpInstance->CacheBody); } HttpInstance->CacheBody = AllocateZeroPool (HttpInstance->CacheLen); if (HttpInstance->CacheBody == NULL) { Status = EFI_OUT_OF_RESOURCES; goto Error2; } CopyMem (HttpInstance->CacheBody, Fragment.Bulk + HttpMsg->BodyLength, HttpInstance->CacheLen); HttpInstance->CacheOffset = 0; } } if (Fragment.Bulk != NULL) { FreePool (Fragment.Bulk); Fragment.Bulk = NULL; } goto Exit; } return Status; Exit: Item = NetMapFindKey (&Wrap->HttpInstance->RxTokens, Wrap->HttpToken); if (Item != NULL) { NetMapRemoveItem (&Wrap->HttpInstance->RxTokens, Item, NULL); } if (HttpInstance->StatusCode >= HTTP_ERROR_OR_NOT_SUPPORT_STATUS_CODE) { Token->Status = EFI_HTTP_ERROR; } else { Token->Status = Status; } gBS->SignalEvent (Token->Event); HttpCloseTcpRxEvent (Wrap); FreePool (Wrap); return Status; Error2: if (ValueInItem != NULL) { NetMapInsertHead (&HttpInstance->TxTokens, ValueInItem->HttpToken, ValueInItem); } Error: Item = NetMapFindKey (&Wrap->HttpInstance->RxTokens, Wrap->HttpToken); if (Item != NULL) { NetMapRemoveItem (&Wrap->HttpInstance->RxTokens, Item, NULL); } if (!HttpInstance->UseHttps) { HttpTcpTokenCleanup (Wrap); } else { FreePool (Wrap); } if (HttpHeaders != NULL) { FreePool (HttpHeaders); HttpHeaders = NULL; } if (Fragment.Bulk != NULL) { FreePool (Fragment.Bulk); Fragment.Bulk = NULL; } if (HttpMsg->Headers != NULL) { FreePool (HttpMsg->Headers); HttpMsg->Headers = NULL; } if (HttpInstance->CacheBody != NULL) { FreePool (HttpInstance->CacheBody); HttpInstance->CacheBody = NULL; } if (HttpInstance->StatusCode >= HTTP_ERROR_OR_NOT_SUPPORT_STATUS_CODE) { Token->Status = EFI_HTTP_ERROR; } else { Token->Status = Status; } gBS->SignalEvent (Token->Event); return Status; } /** The Response() function queues an HTTP response to this HTTP instance, similar to Receive() function in the EFI TCP driver. When the HTTP response is received successfully, or if there is an error, Status in token will be updated and Event will be signaled. The HTTP driver will queue a receive token to the underlying TCP instance. When data is received in the underlying TCP instance, the data will be parsed and Token will be populated with the response data. If the data received from the remote host contains an incomplete or invalid HTTP header, the HTTP driver will continue waiting (asynchronously) for more data to be sent from the remote host before signaling Event in Token. It is the responsibility of the caller to allocate a buffer for Body and specify the size in BodyLength. If the remote host provides a response that contains a content body, up to BodyLength bytes will be copied from the receive buffer into Body and BodyLength will be updated with the amount of bytes received and copied to Body. This allows the client to download a large file in chunks instead of into one contiguous block of memory. Similar to HTTP request, if Body is not NULL and BodyLength is non-zero and all other fields are NULL or 0, the HTTP driver will queue a receive token to underlying TCP instance. If data arrives in the receive buffer, up to BodyLength bytes of data will be copied to Body. The HTTP driver will then update BodyLength with the amount of bytes received and copied to Body. If the HTTP driver does not have an open underlying TCP connection with the host specified in the response URL, Request() will return EFI_ACCESS_DENIED. This is consistent with RFC 2616 recommendation that HTTP clients should attempt to maintain an open TCP connection between client and host. @param[in] This Pointer to EFI_HTTP_PROTOCOL instance. @param[in] Token Pointer to storage containing HTTP response token. @retval EFI_SUCCESS Allocation succeeded. @retval EFI_NOT_STARTED This EFI HTTP Protocol instance has not been initialized. @retval EFI_INVALID_PARAMETER One or more of the following conditions is TRUE: This is NULL. Token is NULL. Token->Message->Headers is NULL. Token->Message is NULL. Token->Message->Body is not NULL, Token->Message->BodyLength is non-zero, and Token->Message->Data is NULL, but a previous call to Response() has not been completed successfully. @retval EFI_OUT_OF_RESOURCES Could not allocate enough system resources. @retval EFI_ACCESS_DENIED An open TCP connection is not present with the host specified by response URL. **/ EFI_STATUS EFIAPI EfiHttpResponse ( IN EFI_HTTP_PROTOCOL *This, IN EFI_HTTP_TOKEN *Token ) { EFI_STATUS Status; EFI_HTTP_MESSAGE *HttpMsg; HTTP_PROTOCOL *HttpInstance; HTTP_TOKEN_WRAP *Wrap; if ((This == NULL) || (Token == NULL)) { return EFI_INVALID_PARAMETER; } HttpMsg = Token->Message; if (HttpMsg == NULL) { return EFI_INVALID_PARAMETER; } HttpInstance = HTTP_INSTANCE_FROM_PROTOCOL (This); ASSERT (HttpInstance != NULL); if (HttpInstance->State != HTTP_STATE_TCP_CONNECTED) { return EFI_NOT_STARTED; } // // Check whether the token already existed. // if (EFI_ERROR (NetMapIterate (&HttpInstance->RxTokens, HttpTokenExist, Token))) { return EFI_ACCESS_DENIED; } Wrap = AllocateZeroPool (sizeof (HTTP_TOKEN_WRAP)); if (Wrap == NULL) { return EFI_OUT_OF_RESOURCES; } Wrap->HttpInstance = HttpInstance; Wrap->HttpToken = Token; // // Notes: For Https, receive token wrapped in HTTP_TOKEN_WRAP is not used to // receive the https response. A special TlsRxToken is used for receiving TLS // related messages. It should be a blocking response. // if (!HttpInstance->UseHttps) { Status = HttpCreateTcpRxEvent (Wrap); if (EFI_ERROR (Status)) { goto Error; } } Status = NetMapInsertTail (&HttpInstance->RxTokens, Token, Wrap); if (EFI_ERROR (Status)) { goto Error; } // // If already have pending RxTokens, return directly. // if (NetMapGetCount (&HttpInstance->RxTokens) > 1) { return EFI_SUCCESS; } return HttpResponseWorker (Wrap); Error: if (Wrap != NULL) { if (Wrap->TcpWrap.Rx4Token.CompletionToken.Event != NULL) { gBS->CloseEvent (Wrap->TcpWrap.Rx4Token.CompletionToken.Event); } if (Wrap->TcpWrap.Rx6Token.CompletionToken.Event != NULL) { gBS->CloseEvent (Wrap->TcpWrap.Rx6Token.CompletionToken.Event); } FreePool (Wrap); } return Status; } /** The Poll() function can be used by network drivers and applications to increase the rate that data packets are moved between the communication devices and the transmit and receive queues. In some systems, the periodic timer event in the managed network driver may not poll the underlying communications device fast enough to transmit and/or receive all data packets without missing incoming packets or dropping outgoing packets. Drivers and applications that are experiencing packet loss should try calling the Poll() function more often. @param[in] This Pointer to EFI_HTTP_PROTOCOL instance. @retval EFI_SUCCESS Incoming or outgoing data was processed. @retval EFI_DEVICE_ERROR An unexpected system or network error occurred. @retval EFI_INVALID_PARAMETER This is NULL. @retval EFI_NOT_READY No incoming or outgoing data is processed. @retval EFI_NOT_STARTED This EFI HTTP Protocol instance has not been started. **/ EFI_STATUS EFIAPI EfiHttpPoll ( IN EFI_HTTP_PROTOCOL *This ) { EFI_STATUS Status; HTTP_PROTOCOL *HttpInstance; if (This == NULL) { return EFI_INVALID_PARAMETER; } HttpInstance = HTTP_INSTANCE_FROM_PROTOCOL (This); ASSERT (HttpInstance != NULL); if (HttpInstance->State != HTTP_STATE_TCP_CONNECTED) { return EFI_NOT_STARTED; } if (HttpInstance->LocalAddressIsIPv6) { if (HttpInstance->Tcp6 == NULL) { return EFI_NOT_STARTED; } Status = HttpInstance->Tcp6->Poll (HttpInstance->Tcp6); } else { if (HttpInstance->Tcp4 == NULL) { return EFI_NOT_STARTED; } Status = HttpInstance->Tcp4->Poll (HttpInstance->Tcp4); } DispatchDpc (); return Status; }
894455.c
/* thr_pth.c - wrappers around GNU Pth */ /* $OpenLDAP$ */ /* This work is part of OpenLDAP Software <http://www.openldap.org/>. * * Copyright 1998-2021 The OpenLDAP Foundation. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted only as authorized by the OpenLDAP * Public License. * * A copy of this license is available in file LICENSE in the * top-level directory of the distribution or, alternatively, at * <http://www.OpenLDAP.org/license.html>. */ #include "portable.h" #if defined( HAVE_GNU_PTH ) #include "ldap_pvt_thread.h" /* Get the thread interface */ #define LDAP_THREAD_IMPLEMENTATION #define LDAP_THREAD_RDWR_IMPLEMENTATION #include "ldap_thr_debug.h" /* May rename the symbols defined below */ #include <errno.h> /******************* * * * GNU Pth Threads * * * *******************/ static pth_attr_t detach_attr; static pth_attr_t joined_attr; int ldap_int_thread_initialize( void ) { if( !pth_init() ) { return -1; } detach_attr = pth_attr_new(); joined_attr = pth_attr_new(); #ifdef LDAP_PVT_THREAD_SET_STACK_SIZE pth_attr_set( joined_attr, PTH_ATTR_STACK_SIZE, LDAP_PVT_THREAD_STACK_SIZE ); pth_attr_set( detach_attr, PTH_ATTR_STACK_SIZE, LDAP_PVT_THREAD_STACK_SIZE ); #endif return pth_attr_set( detach_attr, PTH_ATTR_JOINABLE, FALSE ); } int ldap_int_thread_destroy( void ) { pth_attr_destroy(detach_attr); pth_kill(); return 0; } int ldap_pvt_thread_create( ldap_pvt_thread_t * thread, int detach, void *(*start_routine)( void *), void *arg) { *thread = pth_spawn( detach ? detach_attr : joined_attr, start_routine, arg ); return *thread == NULL ? errno : 0; } void ldap_pvt_thread_exit( void *retval ) { pth_exit( retval ); } int ldap_pvt_thread_join( ldap_pvt_thread_t thread, void **thread_return ) { return pth_join( thread, thread_return ) ? 0 : errno; } int ldap_pvt_thread_kill( ldap_pvt_thread_t thread, int signo ) { return pth_raise( thread, signo ) ? 0 : errno; } int ldap_pvt_thread_yield( void ) { return pth_yield(NULL) ? 0 : errno; } int ldap_pvt_thread_cond_init( ldap_pvt_thread_cond_t *cond ) { return( pth_cond_init( cond ) ? 0 : errno ); } int ldap_pvt_thread_cond_signal( ldap_pvt_thread_cond_t *cond ) { return( pth_cond_notify( cond, 0 ) ? 0 : errno ); } int ldap_pvt_thread_cond_broadcast( ldap_pvt_thread_cond_t *cond ) { return( pth_cond_notify( cond, 1 ) ? 0 : errno ); } int ldap_pvt_thread_cond_wait( ldap_pvt_thread_cond_t *cond, ldap_pvt_thread_mutex_t *mutex ) { return( pth_cond_await( cond, mutex, NULL ) ? 0 : errno ); } int ldap_pvt_thread_cond_destroy( ldap_pvt_thread_cond_t *cv ) { return 0; } int ldap_pvt_thread_mutex_init( ldap_pvt_thread_mutex_t *mutex ) { return( pth_mutex_init( mutex ) ? 0 : errno ); } int ldap_pvt_thread_mutex_recursive_init( ldap_pvt_thread_mutex_t *mutex ) { /* All pth mutexes are recursive */ return ldap_pvt_thread_mutex_init( mutex ); } int ldap_pvt_thread_mutex_destroy( ldap_pvt_thread_mutex_t *mutex ) { return 0; } int ldap_pvt_thread_mutex_lock( ldap_pvt_thread_mutex_t *mutex ) { return( pth_mutex_acquire( mutex, 0, NULL ) ? 0 : errno ); } int ldap_pvt_thread_mutex_unlock( ldap_pvt_thread_mutex_t *mutex ) { return( pth_mutex_release( mutex ) ? 0 : errno ); } int ldap_pvt_thread_mutex_trylock( ldap_pvt_thread_mutex_t *mutex ) { return( pth_mutex_acquire( mutex, 1, NULL ) ? 0 : errno ); } ldap_pvt_thread_t ldap_pvt_thread_self( void ) { return pth_self(); } int ldap_pvt_thread_key_create( ldap_pvt_thread_key_t *key ) { return pth_key_create( key, NULL ); } int ldap_pvt_thread_key_destroy( ldap_pvt_thread_key_t key ) { return pth_key_delete( key ); } int ldap_pvt_thread_key_setdata( ldap_pvt_thread_key_t key, void *data ) { return pth_key_setdata( key, data ); } int ldap_pvt_thread_key_getdata( ldap_pvt_thread_key_t key, void **data ) { *data = pth_key_getdata( key ); return 0; } #ifdef LDAP_THREAD_HAVE_RDWR int ldap_pvt_thread_rdwr_init( ldap_pvt_thread_rdwr_t *rw ) { return pth_rwlock_init( rw ) ? 0 : errno; } int ldap_pvt_thread_rdwr_destroy( ldap_pvt_thread_rdwr_t *rw ) { return 0; } int ldap_pvt_thread_rdwr_rlock( ldap_pvt_thread_rdwr_t *rw ) { return pth_rwlock_acquire( rw, PTH_RWLOCK_RD, 0, NULL ) ? 0 : errno; } int ldap_pvt_thread_rdwr_rtrylock( ldap_pvt_thread_rdwr_t *rw ) { return pth_rwlock_acquire( rw, PTH_RWLOCK_RD, 1, NULL ) ? 0 : errno; } int ldap_pvt_thread_rdwr_runlock( ldap_pvt_thread_rdwr_t *rw ) { return pth_rwlock_release( rw ) ? 0 : errno; } int ldap_pvt_thread_rdwr_wlock( ldap_pvt_thread_rdwr_t *rw ) { return pth_rwlock_acquire( rw, PTH_RWLOCK_RW, 0, NULL ) ? 0 : errno; } int ldap_pvt_thread_rdwr_wtrylock( ldap_pvt_thread_rdwr_t *rw ) { return pth_rwlock_acquire( rw, PTH_RWLOCK_RW, 1, NULL ) ? 0 : errno; } int ldap_pvt_thread_rdwr_wunlock( ldap_pvt_thread_rdwr_t *rw ) { return pth_rwlock_release( rw ) ? 0 : errno; } #endif /* LDAP_THREAD_HAVE_RDWR */ #endif /* HAVE_GNU_PTH */
97693.c
/* * sh7372 processor support * * Copyright (C) 2010 Magnus Damm * Copyright (C) 2008 Yoshihiro Shimoda * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; version 2 of the License. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include <linux/kernel.h> #include <linux/init.h> #include <linux/interrupt.h> #include <linux/irq.h> #include <linux/platform_device.h> #include <linux/of_platform.h> #include <linux/uio_driver.h> #include <linux/delay.h> #include <linux/input.h> #include <linux/io.h> #include <linux/serial_sci.h> #include <linux/sh_dma.h> #include <linux/sh_intc.h> #include <linux/sh_timer.h> #include <linux/pm_domain.h> #include <linux/dma-mapping.h> #include <linux/platform_data/sh_ipmmu.h> #include <mach/dma-register.h> #include <mach/hardware.h> #include <mach/irqs.h> #include <mach/sh7372.h> #include <mach/common.h> #include <asm/mach/map.h> #include <asm/mach-types.h> #include <asm/mach/arch.h> #include <asm/mach/time.h> static struct map_desc sh7372_io_desc[] __initdata = { /* create a 1:1 entity map for 0xe6xxxxxx * used by CPGA, INTC and PFC. */ { .virtual = 0xe6000000, .pfn = __phys_to_pfn(0xe6000000), .length = 256 << 20, .type = MT_DEVICE_NONSHARED }, }; void __init sh7372_map_io(void) { iotable_init(sh7372_io_desc, ARRAY_SIZE(sh7372_io_desc)); } /* PFC */ static struct resource sh7372_pfc_resources[] = { [0] = { .start = 0xe6050000, .end = 0xe6057fff, .flags = IORESOURCE_MEM, }, [1] = { .start = 0xe605800c, .end = 0xe6058027, .flags = IORESOURCE_MEM, } }; static struct platform_device sh7372_pfc_device = { .name = "pfc-sh7372", .id = -1, .resource = sh7372_pfc_resources, .num_resources = ARRAY_SIZE(sh7372_pfc_resources), }; void __init sh7372_pinmux_init(void) { platform_device_register(&sh7372_pfc_device); } /* SCIFA0 */ static struct plat_sci_port scif0_platform_data = { .mapbase = 0xe6c40000, .flags = UPF_BOOT_AUTOCONF, .scscr = SCSCR_RE | SCSCR_TE, .scbrr_algo_id = SCBRR_ALGO_4, .type = PORT_SCIFA, .irqs = { evt2irq(0x0c00), evt2irq(0x0c00), evt2irq(0x0c00), evt2irq(0x0c00) }, }; static struct platform_device scif0_device = { .name = "sh-sci", .id = 0, .dev = { .platform_data = &scif0_platform_data, }, }; /* SCIFA1 */ static struct plat_sci_port scif1_platform_data = { .mapbase = 0xe6c50000, .flags = UPF_BOOT_AUTOCONF, .scscr = SCSCR_RE | SCSCR_TE, .scbrr_algo_id = SCBRR_ALGO_4, .type = PORT_SCIFA, .irqs = { evt2irq(0x0c20), evt2irq(0x0c20), evt2irq(0x0c20), evt2irq(0x0c20) }, }; static struct platform_device scif1_device = { .name = "sh-sci", .id = 1, .dev = { .platform_data = &scif1_platform_data, }, }; /* SCIFA2 */ static struct plat_sci_port scif2_platform_data = { .mapbase = 0xe6c60000, .flags = UPF_BOOT_AUTOCONF, .scscr = SCSCR_RE | SCSCR_TE, .scbrr_algo_id = SCBRR_ALGO_4, .type = PORT_SCIFA, .irqs = { evt2irq(0x0c40), evt2irq(0x0c40), evt2irq(0x0c40), evt2irq(0x0c40) }, }; static struct platform_device scif2_device = { .name = "sh-sci", .id = 2, .dev = { .platform_data = &scif2_platform_data, }, }; /* SCIFA3 */ static struct plat_sci_port scif3_platform_data = { .mapbase = 0xe6c70000, .flags = UPF_BOOT_AUTOCONF, .scscr = SCSCR_RE | SCSCR_TE, .scbrr_algo_id = SCBRR_ALGO_4, .type = PORT_SCIFA, .irqs = { evt2irq(0x0c60), evt2irq(0x0c60), evt2irq(0x0c60), evt2irq(0x0c60) }, }; static struct platform_device scif3_device = { .name = "sh-sci", .id = 3, .dev = { .platform_data = &scif3_platform_data, }, }; /* SCIFA4 */ static struct plat_sci_port scif4_platform_data = { .mapbase = 0xe6c80000, .flags = UPF_BOOT_AUTOCONF, .scscr = SCSCR_RE | SCSCR_TE, .scbrr_algo_id = SCBRR_ALGO_4, .type = PORT_SCIFA, .irqs = { evt2irq(0x0d20), evt2irq(0x0d20), evt2irq(0x0d20), evt2irq(0x0d20) }, }; static struct platform_device scif4_device = { .name = "sh-sci", .id = 4, .dev = { .platform_data = &scif4_platform_data, }, }; /* SCIFA5 */ static struct plat_sci_port scif5_platform_data = { .mapbase = 0xe6cb0000, .flags = UPF_BOOT_AUTOCONF, .scscr = SCSCR_RE | SCSCR_TE, .scbrr_algo_id = SCBRR_ALGO_4, .type = PORT_SCIFA, .irqs = { evt2irq(0x0d40), evt2irq(0x0d40), evt2irq(0x0d40), evt2irq(0x0d40) }, }; static struct platform_device scif5_device = { .name = "sh-sci", .id = 5, .dev = { .platform_data = &scif5_platform_data, }, }; /* SCIFB */ static struct plat_sci_port scif6_platform_data = { .mapbase = 0xe6c30000, .flags = UPF_BOOT_AUTOCONF, .scscr = SCSCR_RE | SCSCR_TE, .scbrr_algo_id = SCBRR_ALGO_4, .type = PORT_SCIFB, .irqs = { evt2irq(0x0d60), evt2irq(0x0d60), evt2irq(0x0d60), evt2irq(0x0d60) }, }; static struct platform_device scif6_device = { .name = "sh-sci", .id = 6, .dev = { .platform_data = &scif6_platform_data, }, }; /* CMT */ static struct sh_timer_config cmt2_platform_data = { .name = "CMT2", .channel_offset = 0x40, .timer_bit = 5, .clockevent_rating = 125, .clocksource_rating = 125, }; static struct resource cmt2_resources[] = { [0] = { .name = "CMT2", .start = 0xe6130040, .end = 0xe613004b, .flags = IORESOURCE_MEM, }, [1] = { .start = evt2irq(0x0b80), /* CMT2 */ .flags = IORESOURCE_IRQ, }, }; static struct platform_device cmt2_device = { .name = "sh_cmt", .id = 2, .dev = { .platform_data = &cmt2_platform_data, }, .resource = cmt2_resources, .num_resources = ARRAY_SIZE(cmt2_resources), }; /* TMU */ static struct sh_timer_config tmu00_platform_data = { .name = "TMU00", .channel_offset = 0x4, .timer_bit = 0, .clockevent_rating = 200, }; static struct resource tmu00_resources[] = { [0] = { .name = "TMU00", .start = 0xfff60008, .end = 0xfff60013, .flags = IORESOURCE_MEM, }, [1] = { .start = intcs_evt2irq(0xe80), /* TMU_TUNI0 */ .flags = IORESOURCE_IRQ, }, }; static struct platform_device tmu00_device = { .name = "sh_tmu", .id = 0, .dev = { .platform_data = &tmu00_platform_data, }, .resource = tmu00_resources, .num_resources = ARRAY_SIZE(tmu00_resources), }; static struct sh_timer_config tmu01_platform_data = { .name = "TMU01", .channel_offset = 0x10, .timer_bit = 1, .clocksource_rating = 200, }; static struct resource tmu01_resources[] = { [0] = { .name = "TMU01", .start = 0xfff60014, .end = 0xfff6001f, .flags = IORESOURCE_MEM, }, [1] = { .start = intcs_evt2irq(0xea0), /* TMU_TUNI1 */ .flags = IORESOURCE_IRQ, }, }; static struct platform_device tmu01_device = { .name = "sh_tmu", .id = 1, .dev = { .platform_data = &tmu01_platform_data, }, .resource = tmu01_resources, .num_resources = ARRAY_SIZE(tmu01_resources), }; /* I2C */ static struct resource iic0_resources[] = { [0] = { .name = "IIC0", .start = 0xFFF20000, .end = 0xFFF20425 - 1, .flags = IORESOURCE_MEM, }, [1] = { .start = intcs_evt2irq(0xe00), /* IIC0_ALI0 */ .end = intcs_evt2irq(0xe60), /* IIC0_DTEI0 */ .flags = IORESOURCE_IRQ, }, }; static struct platform_device iic0_device = { .name = "i2c-sh_mobile", .id = 0, /* "i2c0" clock */ .num_resources = ARRAY_SIZE(iic0_resources), .resource = iic0_resources, }; static struct resource iic1_resources[] = { [0] = { .name = "IIC1", .start = 0xE6C20000, .end = 0xE6C20425 - 1, .flags = IORESOURCE_MEM, }, [1] = { .start = evt2irq(0x780), /* IIC1_ALI1 */ .end = evt2irq(0x7e0), /* IIC1_DTEI1 */ .flags = IORESOURCE_IRQ, }, }; static struct platform_device iic1_device = { .name = "i2c-sh_mobile", .id = 1, /* "i2c1" clock */ .num_resources = ARRAY_SIZE(iic1_resources), .resource = iic1_resources, }; /* DMA */ static const struct sh_dmae_slave_config sh7372_dmae_slaves[] = { { .slave_id = SHDMA_SLAVE_SCIF0_TX, .addr = 0xe6c40020, .chcr = CHCR_TX(XMIT_SZ_8BIT), .mid_rid = 0x21, }, { .slave_id = SHDMA_SLAVE_SCIF0_RX, .addr = 0xe6c40024, .chcr = CHCR_RX(XMIT_SZ_8BIT), .mid_rid = 0x22, }, { .slave_id = SHDMA_SLAVE_SCIF1_TX, .addr = 0xe6c50020, .chcr = CHCR_TX(XMIT_SZ_8BIT), .mid_rid = 0x25, }, { .slave_id = SHDMA_SLAVE_SCIF1_RX, .addr = 0xe6c50024, .chcr = CHCR_RX(XMIT_SZ_8BIT), .mid_rid = 0x26, }, { .slave_id = SHDMA_SLAVE_SCIF2_TX, .addr = 0xe6c60020, .chcr = CHCR_TX(XMIT_SZ_8BIT), .mid_rid = 0x29, }, { .slave_id = SHDMA_SLAVE_SCIF2_RX, .addr = 0xe6c60024, .chcr = CHCR_RX(XMIT_SZ_8BIT), .mid_rid = 0x2a, }, { .slave_id = SHDMA_SLAVE_SCIF3_TX, .addr = 0xe6c70020, .chcr = CHCR_TX(XMIT_SZ_8BIT), .mid_rid = 0x2d, }, { .slave_id = SHDMA_SLAVE_SCIF3_RX, .addr = 0xe6c70024, .chcr = CHCR_RX(XMIT_SZ_8BIT), .mid_rid = 0x2e, }, { .slave_id = SHDMA_SLAVE_SCIF4_TX, .addr = 0xe6c80020, .chcr = CHCR_TX(XMIT_SZ_8BIT), .mid_rid = 0x39, }, { .slave_id = SHDMA_SLAVE_SCIF4_RX, .addr = 0xe6c80024, .chcr = CHCR_RX(XMIT_SZ_8BIT), .mid_rid = 0x3a, }, { .slave_id = SHDMA_SLAVE_SCIF5_TX, .addr = 0xe6cb0020, .chcr = CHCR_TX(XMIT_SZ_8BIT), .mid_rid = 0x35, }, { .slave_id = SHDMA_SLAVE_SCIF5_RX, .addr = 0xe6cb0024, .chcr = CHCR_RX(XMIT_SZ_8BIT), .mid_rid = 0x36, }, { .slave_id = SHDMA_SLAVE_SCIF6_TX, .addr = 0xe6c30040, .chcr = CHCR_TX(XMIT_SZ_8BIT), .mid_rid = 0x3d, }, { .slave_id = SHDMA_SLAVE_SCIF6_RX, .addr = 0xe6c30060, .chcr = CHCR_RX(XMIT_SZ_8BIT), .mid_rid = 0x3e, }, { .slave_id = SHDMA_SLAVE_FLCTL0_TX, .addr = 0xe6a30050, .chcr = CHCR_TX(XMIT_SZ_32BIT), .mid_rid = 0x83, }, { .slave_id = SHDMA_SLAVE_FLCTL0_RX, .addr = 0xe6a30050, .chcr = CHCR_RX(XMIT_SZ_32BIT), .mid_rid = 0x83, }, { .slave_id = SHDMA_SLAVE_FLCTL1_TX, .addr = 0xe6a30060, .chcr = CHCR_TX(XMIT_SZ_32BIT), .mid_rid = 0x87, }, { .slave_id = SHDMA_SLAVE_FLCTL1_RX, .addr = 0xe6a30060, .chcr = CHCR_RX(XMIT_SZ_32BIT), .mid_rid = 0x87, }, { .slave_id = SHDMA_SLAVE_SDHI0_TX, .addr = 0xe6850030, .chcr = CHCR_TX(XMIT_SZ_16BIT), .mid_rid = 0xc1, }, { .slave_id = SHDMA_SLAVE_SDHI0_RX, .addr = 0xe6850030, .chcr = CHCR_RX(XMIT_SZ_16BIT), .mid_rid = 0xc2, }, { .slave_id = SHDMA_SLAVE_SDHI1_TX, .addr = 0xe6860030, .chcr = CHCR_TX(XMIT_SZ_16BIT), .mid_rid = 0xc9, }, { .slave_id = SHDMA_SLAVE_SDHI1_RX, .addr = 0xe6860030, .chcr = CHCR_RX(XMIT_SZ_16BIT), .mid_rid = 0xca, }, { .slave_id = SHDMA_SLAVE_SDHI2_TX, .addr = 0xe6870030, .chcr = CHCR_TX(XMIT_SZ_16BIT), .mid_rid = 0xcd, }, { .slave_id = SHDMA_SLAVE_SDHI2_RX, .addr = 0xe6870030, .chcr = CHCR_RX(XMIT_SZ_16BIT), .mid_rid = 0xce, }, { .slave_id = SHDMA_SLAVE_FSIA_TX, .addr = 0xfe1f0024, .chcr = CHCR_TX(XMIT_SZ_32BIT), .mid_rid = 0xb1, }, { .slave_id = SHDMA_SLAVE_FSIA_RX, .addr = 0xfe1f0020, .chcr = CHCR_RX(XMIT_SZ_32BIT), .mid_rid = 0xb2, }, { .slave_id = SHDMA_SLAVE_MMCIF_TX, .addr = 0xe6bd0034, .chcr = CHCR_TX(XMIT_SZ_32BIT), .mid_rid = 0xd1, }, { .slave_id = SHDMA_SLAVE_MMCIF_RX, .addr = 0xe6bd0034, .chcr = CHCR_RX(XMIT_SZ_32BIT), .mid_rid = 0xd2, }, }; #define SH7372_CHCLR (0x220 - 0x20) static const struct sh_dmae_channel sh7372_dmae_channels[] = { { .offset = 0, .dmars = 0, .dmars_bit = 0, .chclr_offset = SH7372_CHCLR + 0, }, { .offset = 0x10, .dmars = 0, .dmars_bit = 8, .chclr_offset = SH7372_CHCLR + 0x10, }, { .offset = 0x20, .dmars = 4, .dmars_bit = 0, .chclr_offset = SH7372_CHCLR + 0x20, }, { .offset = 0x30, .dmars = 4, .dmars_bit = 8, .chclr_offset = SH7372_CHCLR + 0x30, }, { .offset = 0x50, .dmars = 8, .dmars_bit = 0, .chclr_offset = SH7372_CHCLR + 0x50, }, { .offset = 0x60, .dmars = 8, .dmars_bit = 8, .chclr_offset = SH7372_CHCLR + 0x60, } }; static struct sh_dmae_pdata dma_platform_data = { .slave = sh7372_dmae_slaves, .slave_num = ARRAY_SIZE(sh7372_dmae_slaves), .channel = sh7372_dmae_channels, .channel_num = ARRAY_SIZE(sh7372_dmae_channels), .ts_low_shift = TS_LOW_SHIFT, .ts_low_mask = TS_LOW_BIT << TS_LOW_SHIFT, .ts_high_shift = TS_HI_SHIFT, .ts_high_mask = TS_HI_BIT << TS_HI_SHIFT, .ts_shift = dma_ts_shift, .ts_shift_num = ARRAY_SIZE(dma_ts_shift), .dmaor_init = DMAOR_DME, .chclr_present = 1, }; /* Resource order important! */ static struct resource sh7372_dmae0_resources[] = { { /* Channel registers and DMAOR */ .start = 0xfe008020, .end = 0xfe00828f, .flags = IORESOURCE_MEM, }, { /* DMARSx */ .start = 0xfe009000, .end = 0xfe00900b, .flags = IORESOURCE_MEM, }, { .name = "error_irq", .start = evt2irq(0x20c0), .end = evt2irq(0x20c0), .flags = IORESOURCE_IRQ, }, { /* IRQ for channels 0-5 */ .start = evt2irq(0x2000), .end = evt2irq(0x20a0), .flags = IORESOURCE_IRQ, }, }; /* Resource order important! */ static struct resource sh7372_dmae1_resources[] = { { /* Channel registers and DMAOR */ .start = 0xfe018020, .end = 0xfe01828f, .flags = IORESOURCE_MEM, }, { /* DMARSx */ .start = 0xfe019000, .end = 0xfe01900b, .flags = IORESOURCE_MEM, }, { .name = "error_irq", .start = evt2irq(0x21c0), .end = evt2irq(0x21c0), .flags = IORESOURCE_IRQ, }, { /* IRQ for channels 0-5 */ .start = evt2irq(0x2100), .end = evt2irq(0x21a0), .flags = IORESOURCE_IRQ, }, }; /* Resource order important! */ static struct resource sh7372_dmae2_resources[] = { { /* Channel registers and DMAOR */ .start = 0xfe028020, .end = 0xfe02828f, .flags = IORESOURCE_MEM, }, { /* DMARSx */ .start = 0xfe029000, .end = 0xfe02900b, .flags = IORESOURCE_MEM, }, { .name = "error_irq", .start = evt2irq(0x22c0), .end = evt2irq(0x22c0), .flags = IORESOURCE_IRQ, }, { /* IRQ for channels 0-5 */ .start = evt2irq(0x2200), .end = evt2irq(0x22a0), .flags = IORESOURCE_IRQ, }, }; static struct platform_device dma0_device = { .name = "sh-dma-engine", .id = 0, .resource = sh7372_dmae0_resources, .num_resources = ARRAY_SIZE(sh7372_dmae0_resources), .dev = { .platform_data = &dma_platform_data, }, }; static struct platform_device dma1_device = { .name = "sh-dma-engine", .id = 1, .resource = sh7372_dmae1_resources, .num_resources = ARRAY_SIZE(sh7372_dmae1_resources), .dev = { .platform_data = &dma_platform_data, }, }; static struct platform_device dma2_device = { .name = "sh-dma-engine", .id = 2, .resource = sh7372_dmae2_resources, .num_resources = ARRAY_SIZE(sh7372_dmae2_resources), .dev = { .platform_data = &dma_platform_data, }, }; /* * USB-DMAC */ static const struct sh_dmae_channel sh7372_usb_dmae_channels[] = { { .offset = 0, }, { .offset = 0x20, }, }; /* USB DMAC0 */ static const struct sh_dmae_slave_config sh7372_usb_dmae0_slaves[] = { { .slave_id = SHDMA_SLAVE_USB0_TX, .chcr = USBTS_INDEX2VAL(USBTS_XMIT_SZ_8BYTE), }, { .slave_id = SHDMA_SLAVE_USB0_RX, .chcr = USBTS_INDEX2VAL(USBTS_XMIT_SZ_8BYTE), }, }; static struct sh_dmae_pdata usb_dma0_platform_data = { .slave = sh7372_usb_dmae0_slaves, .slave_num = ARRAY_SIZE(sh7372_usb_dmae0_slaves), .channel = sh7372_usb_dmae_channels, .channel_num = ARRAY_SIZE(sh7372_usb_dmae_channels), .ts_low_shift = USBTS_LOW_SHIFT, .ts_low_mask = USBTS_LOW_BIT << USBTS_LOW_SHIFT, .ts_high_shift = USBTS_HI_SHIFT, .ts_high_mask = USBTS_HI_BIT << USBTS_HI_SHIFT, .ts_shift = dma_usbts_shift, .ts_shift_num = ARRAY_SIZE(dma_usbts_shift), .dmaor_init = DMAOR_DME, .chcr_offset = 0x14, .chcr_ie_bit = 1 << 5, .dmaor_is_32bit = 1, .needs_tend_set = 1, .no_dmars = 1, .slave_only = 1, }; static struct resource sh7372_usb_dmae0_resources[] = { { /* Channel registers and DMAOR */ .start = 0xe68a0020, .end = 0xe68a0064 - 1, .flags = IORESOURCE_MEM, }, { /* VCR/SWR/DMICR */ .start = 0xe68a0000, .end = 0xe68a0014 - 1, .flags = IORESOURCE_MEM, }, { /* IRQ for channels */ .start = evt2irq(0x0a00), .end = evt2irq(0x0a00), .flags = IORESOURCE_IRQ, }, }; static struct platform_device usb_dma0_device = { .name = "sh-dma-engine", .id = 3, .resource = sh7372_usb_dmae0_resources, .num_resources = ARRAY_SIZE(sh7372_usb_dmae0_resources), .dev = { .platform_data = &usb_dma0_platform_data, }, }; /* USB DMAC1 */ static const struct sh_dmae_slave_config sh7372_usb_dmae1_slaves[] = { { .slave_id = SHDMA_SLAVE_USB1_TX, .chcr = USBTS_INDEX2VAL(USBTS_XMIT_SZ_8BYTE), }, { .slave_id = SHDMA_SLAVE_USB1_RX, .chcr = USBTS_INDEX2VAL(USBTS_XMIT_SZ_8BYTE), }, }; static struct sh_dmae_pdata usb_dma1_platform_data = { .slave = sh7372_usb_dmae1_slaves, .slave_num = ARRAY_SIZE(sh7372_usb_dmae1_slaves), .channel = sh7372_usb_dmae_channels, .channel_num = ARRAY_SIZE(sh7372_usb_dmae_channels), .ts_low_shift = USBTS_LOW_SHIFT, .ts_low_mask = USBTS_LOW_BIT << USBTS_LOW_SHIFT, .ts_high_shift = USBTS_HI_SHIFT, .ts_high_mask = USBTS_HI_BIT << USBTS_HI_SHIFT, .ts_shift = dma_usbts_shift, .ts_shift_num = ARRAY_SIZE(dma_usbts_shift), .dmaor_init = DMAOR_DME, .chcr_offset = 0x14, .chcr_ie_bit = 1 << 5, .dmaor_is_32bit = 1, .needs_tend_set = 1, .no_dmars = 1, .slave_only = 1, }; static struct resource sh7372_usb_dmae1_resources[] = { { /* Channel registers and DMAOR */ .start = 0xe68c0020, .end = 0xe68c0064 - 1, .flags = IORESOURCE_MEM, }, { /* VCR/SWR/DMICR */ .start = 0xe68c0000, .end = 0xe68c0014 - 1, .flags = IORESOURCE_MEM, }, { /* IRQ for channels */ .start = evt2irq(0x1d00), .end = evt2irq(0x1d00), .flags = IORESOURCE_IRQ, }, }; static struct platform_device usb_dma1_device = { .name = "sh-dma-engine", .id = 4, .resource = sh7372_usb_dmae1_resources, .num_resources = ARRAY_SIZE(sh7372_usb_dmae1_resources), .dev = { .platform_data = &usb_dma1_platform_data, }, }; /* VPU */ static struct uio_info vpu_platform_data = { .name = "VPU5HG", .version = "0", .irq = intcs_evt2irq(0x980), }; static struct resource vpu_resources[] = { [0] = { .name = "VPU", .start = 0xfe900000, .end = 0xfe900157, .flags = IORESOURCE_MEM, }, }; static struct platform_device vpu_device = { .name = "uio_pdrv_genirq", .id = 0, .dev = { .platform_data = &vpu_platform_data, }, .resource = vpu_resources, .num_resources = ARRAY_SIZE(vpu_resources), }; /* VEU0 */ static struct uio_info veu0_platform_data = { .name = "VEU0", .version = "0", .irq = intcs_evt2irq(0x700), }; static struct resource veu0_resources[] = { [0] = { .name = "VEU0", .start = 0xfe920000, .end = 0xfe9200cb, .flags = IORESOURCE_MEM, }, }; static struct platform_device veu0_device = { .name = "uio_pdrv_genirq", .id = 1, .dev = { .platform_data = &veu0_platform_data, }, .resource = veu0_resources, .num_resources = ARRAY_SIZE(veu0_resources), }; /* VEU1 */ static struct uio_info veu1_platform_data = { .name = "VEU1", .version = "0", .irq = intcs_evt2irq(0x720), }; static struct resource veu1_resources[] = { [0] = { .name = "VEU1", .start = 0xfe924000, .end = 0xfe9240cb, .flags = IORESOURCE_MEM, }, }; static struct platform_device veu1_device = { .name = "uio_pdrv_genirq", .id = 2, .dev = { .platform_data = &veu1_platform_data, }, .resource = veu1_resources, .num_resources = ARRAY_SIZE(veu1_resources), }; /* VEU2 */ static struct uio_info veu2_platform_data = { .name = "VEU2", .version = "0", .irq = intcs_evt2irq(0x740), }; static struct resource veu2_resources[] = { [0] = { .name = "VEU2", .start = 0xfe928000, .end = 0xfe928307, .flags = IORESOURCE_MEM, }, }; static struct platform_device veu2_device = { .name = "uio_pdrv_genirq", .id = 3, .dev = { .platform_data = &veu2_platform_data, }, .resource = veu2_resources, .num_resources = ARRAY_SIZE(veu2_resources), }; /* VEU3 */ static struct uio_info veu3_platform_data = { .name = "VEU3", .version = "0", .irq = intcs_evt2irq(0x760), }; static struct resource veu3_resources[] = { [0] = { .name = "VEU3", .start = 0xfe92c000, .end = 0xfe92c307, .flags = IORESOURCE_MEM, }, }; static struct platform_device veu3_device = { .name = "uio_pdrv_genirq", .id = 4, .dev = { .platform_data = &veu3_platform_data, }, .resource = veu3_resources, .num_resources = ARRAY_SIZE(veu3_resources), }; /* JPU */ static struct uio_info jpu_platform_data = { .name = "JPU", .version = "0", .irq = intcs_evt2irq(0x560), }; static struct resource jpu_resources[] = { [0] = { .name = "JPU", .start = 0xfe980000, .end = 0xfe9902d3, .flags = IORESOURCE_MEM, }, }; static struct platform_device jpu_device = { .name = "uio_pdrv_genirq", .id = 5, .dev = { .platform_data = &jpu_platform_data, }, .resource = jpu_resources, .num_resources = ARRAY_SIZE(jpu_resources), }; /* SPU2DSP0 */ static struct uio_info spu0_platform_data = { .name = "SPU2DSP0", .version = "0", .irq = evt2irq(0x1800), }; static struct resource spu0_resources[] = { [0] = { .name = "SPU2DSP0", .start = 0xfe200000, .end = 0xfe2fffff, .flags = IORESOURCE_MEM, }, }; static struct platform_device spu0_device = { .name = "uio_pdrv_genirq", .id = 6, .dev = { .platform_data = &spu0_platform_data, }, .resource = spu0_resources, .num_resources = ARRAY_SIZE(spu0_resources), }; /* SPU2DSP1 */ static struct uio_info spu1_platform_data = { .name = "SPU2DSP1", .version = "0", .irq = evt2irq(0x1820), }; static struct resource spu1_resources[] = { [0] = { .name = "SPU2DSP1", .start = 0xfe300000, .end = 0xfe3fffff, .flags = IORESOURCE_MEM, }, }; static struct platform_device spu1_device = { .name = "uio_pdrv_genirq", .id = 7, .dev = { .platform_data = &spu1_platform_data, }, .resource = spu1_resources, .num_resources = ARRAY_SIZE(spu1_resources), }; /* IPMMUI (an IPMMU module for ICB/LMB) */ static struct resource ipmmu_resources[] = { [0] = { .name = "IPMMUI", .start = 0xfe951000, .end = 0xfe9510ff, .flags = IORESOURCE_MEM, }, }; static const char * const ipmmu_dev_names[] = { "sh_mobile_lcdc_fb.0", "sh_mobile_lcdc_fb.1", "sh_mobile_ceu.0", "uio_pdrv_genirq.0", "uio_pdrv_genirq.1", "uio_pdrv_genirq.2", "uio_pdrv_genirq.3", "uio_pdrv_genirq.4", "uio_pdrv_genirq.5", }; static struct shmobile_ipmmu_platform_data ipmmu_platform_data = { .dev_names = ipmmu_dev_names, .num_dev_names = ARRAY_SIZE(ipmmu_dev_names), }; static struct platform_device ipmmu_device = { .name = "ipmmu", .id = -1, .dev = { .platform_data = &ipmmu_platform_data, }, .resource = ipmmu_resources, .num_resources = ARRAY_SIZE(ipmmu_resources), }; static struct platform_device *sh7372_early_devices[] __initdata = { &scif0_device, &scif1_device, &scif2_device, &scif3_device, &scif4_device, &scif5_device, &scif6_device, &cmt2_device, &tmu00_device, &tmu01_device, &ipmmu_device, }; static struct platform_device *sh7372_late_devices[] __initdata = { &iic0_device, &iic1_device, &dma0_device, &dma1_device, &dma2_device, &usb_dma0_device, &usb_dma1_device, &vpu_device, &veu0_device, &veu1_device, &veu2_device, &veu3_device, &jpu_device, &spu0_device, &spu1_device, }; void __init sh7372_add_standard_devices(void) { struct pm_domain_device domain_devices[] = { { "A3RV", &vpu_device, }, { "A4MP", &spu0_device, }, { "A4MP", &spu1_device, }, { "A3SP", &scif0_device, }, { "A3SP", &scif1_device, }, { "A3SP", &scif2_device, }, { "A3SP", &scif3_device, }, { "A3SP", &scif4_device, }, { "A3SP", &scif5_device, }, { "A3SP", &scif6_device, }, { "A3SP", &iic1_device, }, { "A3SP", &dma0_device, }, { "A3SP", &dma1_device, }, { "A3SP", &dma2_device, }, { "A3SP", &usb_dma0_device, }, { "A3SP", &usb_dma1_device, }, { "A4R", &iic0_device, }, { "A4R", &veu0_device, }, { "A4R", &veu1_device, }, { "A4R", &veu2_device, }, { "A4R", &veu3_device, }, { "A4R", &jpu_device, }, { "A4R", &tmu00_device, }, { "A4R", &tmu01_device, }, }; sh7372_init_pm_domains(); platform_add_devices(sh7372_early_devices, ARRAY_SIZE(sh7372_early_devices)); platform_add_devices(sh7372_late_devices, ARRAY_SIZE(sh7372_late_devices)); rmobile_add_devices_to_domains(domain_devices, ARRAY_SIZE(domain_devices)); } void __init sh7372_earlytimer_init(void) { sh7372_clock_init(); shmobile_earlytimer_init(); } void __init sh7372_add_early_devices(void) { early_platform_add_devices(sh7372_early_devices, ARRAY_SIZE(sh7372_early_devices)); /* setup early console here as well */ shmobile_setup_console(); } #ifdef CONFIG_USE_OF void __init sh7372_add_early_devices_dt(void) { shmobile_setup_delay(800, 1, 3); /* Cortex-A8 @ 800MHz */ early_platform_add_devices(sh7372_early_devices, ARRAY_SIZE(sh7372_early_devices)); /* setup early console here as well */ shmobile_setup_console(); } static const struct of_dev_auxdata sh7372_auxdata_lookup[] __initconst = { { } }; void __init sh7372_add_standard_devices_dt(void) { /* clocks are setup late during boot in the case of DT */ sh7372_clock_init(); platform_add_devices(sh7372_early_devices, ARRAY_SIZE(sh7372_early_devices)); of_platform_populate(NULL, of_default_bus_match_table, sh7372_auxdata_lookup, NULL); } static const char *sh7372_boards_compat_dt[] __initdata = { "renesas,sh7372", NULL, }; DT_MACHINE_START(SH7372_DT, "Generic SH7372 (Flattened Device Tree)") .map_io = sh7372_map_io, .init_early = sh7372_add_early_devices_dt, .nr_irqs = NR_IRQS_LEGACY, .init_irq = sh7372_init_irq, .handle_irq = shmobile_handle_irq_intc, .init_machine = sh7372_add_standard_devices_dt, .dt_compat = sh7372_boards_compat_dt, MACHINE_END #endif /* CONFIG_USE_OF */
9141.c
#include <stdio.h> #include <stdlib.h> #include "quicksort.h" const int MAX = 1500 ; void quicksort(bool (*f)(int, int), int* t, int start, int end) { if (end-start < MAX) { insertion (f, t, start, end) ; } else { int pivot = choose_pivot (f, t, start, end) ; int pos_pivot = partition (f, t, pivot, start, end) ; quicksort (f, t, start, pos_pivot) ; quicksort (f, t, pos_pivot+1, end) ; } } int choose_pivot(bool (*f)(int, int), int* t, int start, int end) { int mid = (start+end-1)/2 ; int a = ( f(t[end-1], t[start]) ) ? start : (end-1) ; int b = start + end - a - 1 ; if (f(t[a], t[mid])) { return a ; } else { return (f(t[b], t[mid])) ? mid : b ; } } int partition(bool (*f)(int, int), int* t, int pivot, int start, int end) { int valpiv = t[pivot] ; int i = start+1 , ipivot = start ; swap (t, ipivot, pivot) ; for ( ; i < end ; i++) { if (f(t[i], valpiv)) { t[ipivot] = t[i] ; t[i] = t[ipivot+1] ; ipivot++ ; } } t[ipivot] = valpiv ; return ipivot ; } void swap (int* t, int a, int b) { int c = t[b]; t[b] = t[a] ; t[a] = c ; } void insertion (bool (*f)(int, int), int* t, int start, int end) { int i = start ; int current ; for ( ; i < end ; i++) { current = t[i] ; int j = i-1 ; for ( ; j >= start ; j--) { if (f(t[j], current)) { break ; } else { t[j+1] = t[j] ; } } t[j+1] = current ; } }
766539.c
#include "dlvsym.c"
147501.c
#include "testLibIncludeRequired1.h" #include "testLibIncludeRequired2.h" #include "testLibIncludeRequired4.h" #ifndef testLibRequired_IFACE_DEFINE #error Expected testLibRequired_IFACE_DEFINE #endif #ifndef BuildOnly_DEFINE #error Expected BuildOnly_DEFINE #endif #ifdef InstallOnly_DEFINE #error Unexpected InstallOnly_DEFINE #endif extern int testLibRequired(void); extern int testStaticLibRequiredPrivate(void); int testLibDepends(void) { return testLibRequired() + testStaticLibRequiredPrivate(); }
461992.c
/* * Copyright (C) Igor Sysoev */ #include <ngx_config.h> #include <ngx_core.h> #include <ngx_http.h> /* * the single part format: * * "HTTP/1.0 206 Partial Content" CRLF * ... header ... * "Content-Type: image/jpeg" CRLF * "Content-Length: SIZE" CRLF * "Content-Range: bytes START-END/SIZE" CRLF * CRLF * ... data ... * * * the mutlipart format: * * "HTTP/1.0 206 Partial Content" CRLF * ... header ... * "Content-Type: multipart/byteranges; boundary=0123456789" CRLF * CRLF * CRLF * "--0123456789" CRLF * "Content-Type: image/jpeg" CRLF * "Content-Range: bytes START0-END0/SIZE" CRLF * CRLF * ... data ... * CRLF * "--0123456789" CRLF * "Content-Type: image/jpeg" CRLF * "Content-Range: bytes START1-END1/SIZE" CRLF * CRLF * ... data ... * CRLF * "--0123456789--" CRLF */ typedef struct { off_t start; off_t end; ngx_str_t content_range; } ngx_http_range_t; typedef struct { off_t offset; ngx_str_t boundary_header; ngx_array_t ranges; } ngx_http_range_filter_ctx_t; ngx_int_t ngx_http_range_parse(ngx_http_request_t *r, ngx_http_range_filter_ctx_t *ctx); static ngx_int_t ngx_http_range_singlepart_header(ngx_http_request_t *r, ngx_http_range_filter_ctx_t *ctx); static ngx_int_t ngx_http_range_multipart_header(ngx_http_request_t *r, ngx_http_range_filter_ctx_t *ctx); static ngx_int_t ngx_http_range_not_satisfiable(ngx_http_request_t *r); static ngx_int_t ngx_http_range_test_overlapped(ngx_http_request_t *r, ngx_http_range_filter_ctx_t *ctx, ngx_chain_t *in); static ngx_int_t ngx_http_range_singlepart_body(ngx_http_request_t *r, ngx_http_range_filter_ctx_t *ctx, ngx_chain_t *in); static ngx_int_t ngx_http_range_multipart_body(ngx_http_request_t *r, ngx_http_range_filter_ctx_t *ctx, ngx_chain_t *in); static ngx_int_t ngx_http_range_header_filter_init(ngx_conf_t *cf); static ngx_int_t ngx_http_range_body_filter_init(ngx_conf_t *cf); static ngx_http_module_t ngx_http_range_header_filter_module_ctx = { NULL, /* preconfiguration */ ngx_http_range_header_filter_init, /* postconfiguration */ NULL, /* create main configuration */ NULL, /* init main configuration */ NULL, /* create server configuration */ NULL, /* merge server configuration */ NULL, /* create location configuration */ NULL, /* merge location configuration */ }; ngx_module_t ngx_http_range_header_filter_module = { NGX_MODULE_V1, &ngx_http_range_header_filter_module_ctx, /* module context */ NULL, /* module directives */ NGX_HTTP_MODULE, /* module type */ NULL, /* init master */ NULL, /* init module */ NULL, /* init process */ NULL, /* init thread */ NULL, /* exit thread */ NULL, /* exit process */ NULL, /* exit master */ NGX_MODULE_V1_PADDING }; static ngx_http_module_t ngx_http_range_body_filter_module_ctx = { NULL, /* preconfiguration */ ngx_http_range_body_filter_init, /* postconfiguration */ NULL, /* create main configuration */ NULL, /* init main configuration */ NULL, /* create server configuration */ NULL, /* merge server configuration */ NULL, /* create location configuration */ NULL, /* merge location configuration */ }; ngx_module_t ngx_http_range_body_filter_module = { NGX_MODULE_V1, &ngx_http_range_body_filter_module_ctx, /* module context */ NULL, /* module directives */ NGX_HTTP_MODULE, /* module type */ NULL, /* init master */ NULL, /* init module */ NULL, /* init process */ NULL, /* init thread */ NULL, /* exit thread */ NULL, /* exit process */ NULL, /* exit master */ NGX_MODULE_V1_PADDING }; static ngx_http_output_header_filter_pt ngx_http_next_header_filter; static ngx_http_output_body_filter_pt ngx_http_next_body_filter; static ngx_int_t ngx_http_range_header_filter(ngx_http_request_t *r) { time_t if_range; ngx_int_t rc; ngx_http_range_filter_ctx_t *ctx; if (r->http_version < NGX_HTTP_VERSION_10 || r->headers_out.status != NGX_HTTP_OK || r != r->main || r->headers_out.content_length_n == -1 || !r->allow_ranges) { return ngx_http_next_header_filter(r); } if (r->headers_in.range == NULL || r->headers_in.range->value.len < 7 || ngx_strncasecmp(r->headers_in.range->value.data, (u_char *) "bytes=", 6) != 0) { goto next_filter; } if (r->headers_in.if_range && r->headers_out.last_modified_time != -1) { if_range = ngx_http_parse_time(r->headers_in.if_range->value.data, r->headers_in.if_range->value.len); ngx_log_debug2(NGX_LOG_DEBUG_HTTP, r->connection->log, 0, "http ir:%d lm:%d", if_range, r->headers_out.last_modified_time); if (if_range != r->headers_out.last_modified_time) { goto next_filter; } } ctx = ngx_pcalloc(r->pool, sizeof(ngx_http_range_filter_ctx_t)); if (ctx == NULL) { return NGX_ERROR; } if (ngx_array_init(&ctx->ranges, r->pool, 1, sizeof(ngx_http_range_t)) != NGX_OK) { return NGX_ERROR; } rc = ngx_http_range_parse(r, ctx); if (rc == NGX_OK) { ngx_http_set_ctx(r, ctx, ngx_http_range_body_filter_module); r->headers_out.status = NGX_HTTP_PARTIAL_CONTENT; r->headers_out.status_line.len = 0; if (ctx->ranges.nelts == 1) { return ngx_http_range_singlepart_header(r, ctx); } return ngx_http_range_multipart_header(r, ctx); } if (rc == NGX_HTTP_RANGE_NOT_SATISFIABLE) { return ngx_http_range_not_satisfiable(r); } /* rc == NGX_ERROR */ return rc; next_filter: r->headers_out.accept_ranges = ngx_list_push(&r->headers_out.headers); if (r->headers_out.accept_ranges == NULL) { return NGX_ERROR; } r->headers_out.accept_ranges->hash = 1; ngx_str_set(&r->headers_out.accept_ranges->key, "Accept-Ranges"); ngx_str_set(&r->headers_out.accept_ranges->value, "bytes"); return ngx_http_next_header_filter(r); } ngx_int_t ngx_http_range_parse(ngx_http_request_t *r, ngx_http_range_filter_ctx_t *ctx) { u_char *p; off_t start, end; ngx_uint_t suffix; ngx_http_range_t *range; p = r->headers_in.range->value.data + 6; for ( ;; ) { start = 0; end = 0; suffix = 0; while (*p == ' ') { p++; } if (*p != '-') { if (*p < '0' || *p > '9') { return NGX_HTTP_RANGE_NOT_SATISFIABLE; } while (*p >= '0' && *p <= '9') { start = start * 10 + *p++ - '0'; } while (*p == ' ') { p++; } if (*p++ != '-') { return NGX_HTTP_RANGE_NOT_SATISFIABLE; } if (start >= r->headers_out.content_length_n) { return NGX_HTTP_RANGE_NOT_SATISFIABLE; } while (*p == ' ') { p++; } if (*p == ',' || *p == '\0') { range = ngx_array_push(&ctx->ranges); if (range == NULL) { return NGX_ERROR; } range->start = start; range->end = r->headers_out.content_length_n; if (*p++ != ',') { return NGX_OK; } continue; } } else { suffix = 1; p++; } if (*p < '0' || *p > '9') { return NGX_HTTP_RANGE_NOT_SATISFIABLE; } while (*p >= '0' && *p <= '9') { end = end * 10 + *p++ - '0'; } while (*p == ' ') { p++; } if (*p != ',' && *p != '\0') { return NGX_HTTP_RANGE_NOT_SATISFIABLE; } if (suffix) { start = r->headers_out.content_length_n - end; end = r->headers_out.content_length_n - 1; } if (start > end) { return NGX_HTTP_RANGE_NOT_SATISFIABLE; } range = ngx_array_push(&ctx->ranges); if (range == NULL) { return NGX_ERROR; } range->start = start; if (end >= r->headers_out.content_length_n) { /* * Download Accelerator sends the last byte position * that equals to the file length */ range->end = r->headers_out.content_length_n; } else { range->end = end + 1; } if (*p++ != ',') { return NGX_OK; } } } static ngx_int_t ngx_http_range_singlepart_header(ngx_http_request_t *r, ngx_http_range_filter_ctx_t *ctx) { ngx_table_elt_t *content_range; ngx_http_range_t *range; content_range = ngx_list_push(&r->headers_out.headers); if (content_range == NULL) { return NGX_ERROR; } r->headers_out.content_range = content_range; content_range->hash = 1; ngx_str_set(&content_range->key, "Content-Range"); content_range->value.data = ngx_pnalloc(r->pool, sizeof("bytes -/") - 1 + 3 * NGX_OFF_T_LEN); if (content_range->value.data == NULL) { return NGX_ERROR; } /* "Content-Range: bytes SSSS-EEEE/TTTT" header */ range = ctx->ranges.elts; content_range->value.len = ngx_sprintf(content_range->value.data, "bytes %O-%O/%O", range->start, range->end - 1, r->headers_out.content_length_n) - content_range->value.data; r->headers_out.content_length_n = range->end - range->start; if (r->headers_out.content_length) { r->headers_out.content_length->hash = 0; r->headers_out.content_length = NULL; } return ngx_http_next_header_filter(r); } static ngx_int_t ngx_http_range_multipart_header(ngx_http_request_t *r, ngx_http_range_filter_ctx_t *ctx) { size_t len; ngx_uint_t i; ngx_http_range_t *range; ngx_atomic_uint_t boundary; len = sizeof(CRLF "--") - 1 + NGX_ATOMIC_T_LEN + sizeof(CRLF "Content-Type: ") - 1 + r->headers_out.content_type.len + sizeof(CRLF "Content-Range: bytes ") - 1; if (r->headers_out.charset.len) { len += sizeof("; charset=") - 1 + r->headers_out.charset.len; } ctx->boundary_header.data = ngx_pnalloc(r->pool, len); if (ctx->boundary_header.data == NULL) { return NGX_ERROR; } boundary = ngx_next_temp_number(0); /* * The boundary header of the range: * CRLF * "--0123456789" CRLF * "Content-Type: image/jpeg" CRLF * "Content-Range: bytes " */ if (r->headers_out.charset.len) { ctx->boundary_header.len = ngx_sprintf(ctx->boundary_header.data, CRLF "--%0muA" CRLF "Content-Type: %V; charset=%V" CRLF "Content-Range: bytes ", boundary, &r->headers_out.content_type, &r->headers_out.charset) - ctx->boundary_header.data; r->headers_out.charset.len = 0; } else if (r->headers_out.content_type.len) { ctx->boundary_header.len = ngx_sprintf(ctx->boundary_header.data, CRLF "--%0muA" CRLF "Content-Type: %V" CRLF "Content-Range: bytes ", boundary, &r->headers_out.content_type) - ctx->boundary_header.data; } else { ctx->boundary_header.len = ngx_sprintf(ctx->boundary_header.data, CRLF "--%0muA" CRLF "Content-Range: bytes ", boundary) - ctx->boundary_header.data; } r->headers_out.content_type.data = ngx_pnalloc(r->pool, sizeof("Content-Type: multipart/byteranges; boundary=") - 1 + NGX_ATOMIC_T_LEN); if (r->headers_out.content_type.data == NULL) { return NGX_ERROR; } r->headers_out.content_type_lowcase = NULL; /* "Content-Type: multipart/byteranges; boundary=0123456789" */ r->headers_out.content_type.len = ngx_sprintf(r->headers_out.content_type.data, "multipart/byteranges; boundary=%0muA", boundary) - r->headers_out.content_type.data; r->headers_out.content_type_len = r->headers_out.content_type.len; /* the size of the last boundary CRLF "--0123456789--" CRLF */ len = sizeof(CRLF "--") - 1 + NGX_ATOMIC_T_LEN + sizeof("--" CRLF) - 1; range = ctx->ranges.elts; for (i = 0; i < ctx->ranges.nelts; i++) { /* the size of the range: "SSSS-EEEE/TTTT" CRLF CRLF */ range[i].content_range.data = ngx_pnalloc(r->pool, 3 * NGX_OFF_T_LEN + 2 + 4); if (range[i].content_range.data == NULL) { return NGX_ERROR; } range[i].content_range.len = ngx_sprintf(range[i].content_range.data, "%O-%O/%O" CRLF CRLF, range[i].start, range[i].end - 1, r->headers_out.content_length_n) - range[i].content_range.data; len += ctx->boundary_header.len + range[i].content_range.len + (size_t) (range[i].end - range[i].start); } r->headers_out.content_length_n = len; if (r->headers_out.content_length) { r->headers_out.content_length->hash = 0; r->headers_out.content_length = NULL; } return ngx_http_next_header_filter(r); } static ngx_int_t ngx_http_range_not_satisfiable(ngx_http_request_t *r) { ngx_table_elt_t *content_range; r->headers_out.status = NGX_HTTP_RANGE_NOT_SATISFIABLE; content_range = ngx_list_push(&r->headers_out.headers); if (content_range == NULL) { return NGX_ERROR; } r->headers_out.content_range = content_range; content_range->hash = 1; ngx_str_set(&content_range->key, "Content-Range"); content_range->value.data = ngx_pnalloc(r->pool, sizeof("bytes */") - 1 + NGX_OFF_T_LEN); if (content_range->value.data == NULL) { return NGX_ERROR; } content_range->value.len = ngx_sprintf(content_range->value.data, "bytes */%O", r->headers_out.content_length_n) - content_range->value.data; ngx_http_clear_content_length(r); return NGX_HTTP_RANGE_NOT_SATISFIABLE; } static ngx_int_t ngx_http_range_body_filter(ngx_http_request_t *r, ngx_chain_t *in) { ngx_http_range_filter_ctx_t *ctx; if (in == NULL) { return ngx_http_next_body_filter(r, in); } ctx = ngx_http_get_module_ctx(r, ngx_http_range_body_filter_module); if (ctx == NULL) { return ngx_http_next_body_filter(r, in); } if (ctx->ranges.nelts == 1) { return ngx_http_range_singlepart_body(r, ctx, in); } /* * multipart ranges are supported only if whole body is in a single buffer */ if (ngx_buf_special(in->buf)) { return ngx_http_next_body_filter(r, in); } if (ngx_http_range_test_overlapped(r, ctx, in) != NGX_OK) { return NGX_ERROR; } return ngx_http_range_multipart_body(r, ctx, in); } static ngx_int_t ngx_http_range_test_overlapped(ngx_http_request_t *r, ngx_http_range_filter_ctx_t *ctx, ngx_chain_t *in) { off_t start, last; ngx_buf_t *buf; ngx_uint_t i; ngx_http_range_t *range; if (ctx->offset) { goto overlapped; } buf = in->buf; if (!buf->last_buf) { if (buf->in_file) { start = buf->file_pos + ctx->offset; last = buf->file_last + ctx->offset; } else { start = buf->pos - buf->start + ctx->offset; last = buf->last - buf->start + ctx->offset; } range = ctx->ranges.elts; for (i = 0; i < ctx->ranges.nelts; i++) { if (start > range[i].start || last < range[i].end) { goto overlapped; } } } ctx->offset = ngx_buf_size(buf); return NGX_OK; overlapped: ngx_log_error(NGX_LOG_ALERT, r->connection->log, 0, "range in overlapped buffers"); return NGX_ERROR; } static ngx_int_t ngx_http_range_singlepart_body(ngx_http_request_t *r, ngx_http_range_filter_ctx_t *ctx, ngx_chain_t *in) { off_t start, last; ngx_buf_t *buf; ngx_chain_t *out, *cl, **ll; ngx_http_range_t *range; out = NULL; ll = &out; range = ctx->ranges.elts; for (cl = in; cl; cl = cl->next) { buf = cl->buf; start = ctx->offset; last = ctx->offset + ngx_buf_size(buf); ctx->offset = last; ngx_log_debug2(NGX_LOG_DEBUG_HTTP, r->connection->log, 0, "http range body buf: %O-%O", start, last); if (ngx_buf_special(buf)) { *ll = cl; ll = &cl->next; continue; } if (range->end <= start || range->start >= last) { ngx_log_debug0(NGX_LOG_DEBUG_HTTP, r->connection->log, 0, "http range body skip"); if (buf->in_file) { buf->file_pos = buf->file_last; } buf->pos = buf->last; buf->sync = 1; continue; } if (range->start > start) { if (buf->in_file) { buf->file_pos += range->start - start; } if (ngx_buf_in_memory(buf)) { buf->pos += (size_t) (range->start - start); } } if (range->end <= last) { if (buf->in_file) { buf->file_last -= last - range->end; } if (ngx_buf_in_memory(buf)) { buf->last -= (size_t) (last - range->end); } buf->last_buf = 1; *ll = cl; cl->next = NULL; break; } *ll = cl; ll = &cl->next; } if (out == NULL) { return NGX_OK; } return ngx_http_next_body_filter(r, out); } static ngx_int_t ngx_http_range_multipart_body(ngx_http_request_t *r, ngx_http_range_filter_ctx_t *ctx, ngx_chain_t *in) { off_t body_start; ngx_buf_t *b, *buf; ngx_uint_t i; ngx_chain_t *out, *hcl, *rcl, *dcl, **ll; ngx_http_range_t *range; ll = &out; buf = in->buf; range = ctx->ranges.elts; #if (NGX_HTTP_CACHE) body_start = r->cached ? r->cache->body_start : 0; #else body_start = 0; #endif for (i = 0; i < ctx->ranges.nelts; i++) { /* * The boundary header of the range: * CRLF * "--0123456789" CRLF * "Content-Type: image/jpeg" CRLF * "Content-Range: bytes " */ b = ngx_calloc_buf(r->pool); if (b == NULL) { return NGX_ERROR; } b->memory = 1; b->pos = ctx->boundary_header.data; b->last = ctx->boundary_header.data + ctx->boundary_header.len; hcl = ngx_alloc_chain_link(r->pool); if (hcl == NULL) { return NGX_ERROR; } hcl->buf = b; /* "SSSS-EEEE/TTTT" CRLF CRLF */ b = ngx_calloc_buf(r->pool); if (b == NULL) { return NGX_ERROR; } b->temporary = 1; b->pos = range[i].content_range.data; b->last = range[i].content_range.data + range[i].content_range.len; rcl = ngx_alloc_chain_link(r->pool); if (rcl == NULL) { return NGX_ERROR; } rcl->buf = b; /* the range data */ b = ngx_calloc_buf(r->pool); if (b == NULL) { return NGX_ERROR; } b->in_file = buf->in_file; b->temporary = buf->temporary; b->memory = buf->memory; b->mmap = buf->mmap; b->file = buf->file; if (buf->in_file) { b->file_pos = body_start + range[i].start; b->file_last = body_start + range[i].end; } if (ngx_buf_in_memory(buf)) { b->pos = buf->start + (size_t) range[i].start; b->last = buf->start + (size_t) range[i].end; } dcl = ngx_alloc_chain_link(r->pool); if (dcl == NULL) { return NGX_ERROR; } dcl->buf = b; *ll = hcl; hcl->next = rcl; rcl->next = dcl; ll = &dcl->next; } /* the last boundary CRLF "--0123456789--" CRLF */ b = ngx_calloc_buf(r->pool); if (b == NULL) { return NGX_ERROR; } b->temporary = 1; b->last_buf = 1; b->pos = ngx_pnalloc(r->pool, sizeof(CRLF "--") - 1 + NGX_ATOMIC_T_LEN + sizeof("--" CRLF) - 1); if (b->pos == NULL) { return NGX_ERROR; } b->last = ngx_cpymem(b->pos, ctx->boundary_header.data, sizeof(CRLF "--") - 1 + NGX_ATOMIC_T_LEN); *b->last++ = '-'; *b->last++ = '-'; *b->last++ = CR; *b->last++ = LF; hcl = ngx_alloc_chain_link(r->pool); if (hcl == NULL) { return NGX_ERROR; } hcl->buf = b; hcl->next = NULL; *ll = hcl; return ngx_http_next_body_filter(r, out); } static ngx_int_t ngx_http_range_header_filter_init(ngx_conf_t *cf) { ngx_http_next_header_filter = ngx_http_top_header_filter; ngx_http_top_header_filter = ngx_http_range_header_filter; return NGX_OK; } static ngx_int_t ngx_http_range_body_filter_init(ngx_conf_t *cf) { ngx_http_next_body_filter = ngx_http_top_body_filter; ngx_http_top_body_filter = ngx_http_range_body_filter; return NGX_OK; }
160247.c
#ifdef __cplusplus extern "C" { #endif #include <stdio.h> #include <string.h> #include <errno.h> #include <sys/types.h> #include <sys/socket.h> #include <sys/time.h> #include <unistd.h> #include <fcntl.h> #include <netinet/tcp.h> #include <netdb.h> #include <rtthread.h> #include "tc_iot_inc.h" //==============UDP API==================// void *tc_iot_hal_udp_create(char *host, unsigned short port) { #define NETWORK_ADDR_LEN (16) int rc = -1; long socket_id = -1; char port_ptr[6] = {0}; struct addrinfo hints; char addr[NETWORK_ADDR_LEN] = {0}; struct addrinfo *res, *ainfo; struct sockaddr_in *sa = NULL; if (NULL == host) { return (void *)(-1); } sprintf(port_ptr, "%d", port); memset((char *)&hints, 0x00, sizeof(hints)); hints.ai_socktype = SOCK_DGRAM; hints.ai_family = AF_INET; hints.ai_protocol = IPPROTO_UDP; rc = getaddrinfo(host, port_ptr, &hints, &res); if (0 != rc) { TC_IOT_LOG_ERROR("getaddrinfo error"); return (void *)(-1); } for (ainfo = res; ainfo != NULL; ainfo = ainfo->ai_next) { if ((AF_INET == ainfo->ai_family) || (AF_AT == ainfo->ai_family)) { sa = (struct sockaddr_in *)ainfo->ai_addr; strncpy(addr, inet_ntoa(sa->sin_addr), NETWORK_ADDR_LEN); TC_IOT_LOG_TRACE("The host IP %s, port is %d\r\n", addr, ntohs(sa->sin_port)); socket_id = socket(ainfo->ai_family, ainfo->ai_socktype, ainfo->ai_protocol); if (socket_id < 0) { TC_IOT_LOG_ERROR("create socket error"); continue; } if (0 == connect(socket_id, ainfo->ai_addr, ainfo->ai_addrlen)) { break; } close(socket_id); } else { TC_IOT_LOG_ERROR("ai_family %d", ainfo->ai_family); } } freeaddrinfo(res); return (void *)socket_id; #undef NETWORK_ADDR_LEN } void tc_iot_hal_udp_close(void *p_socket) { long socket_id = -1; socket_id = (long)p_socket; close(socket_id); } int tc_iot_hal_udp_write(void *p_socket, const unsigned char *p_data, unsigned int datalen) { int rc = -1; long socket_id = -1; socket_id = (long)p_socket; rc = send(socket_id, (char *)p_data, (int)datalen, 0); if (-1 == rc) { return -1; } return rc; } int tc_iot_hal_udp_read(void *p_socket, unsigned char *p_data, unsigned int datalen) { long socket_id = -1; int count = -1; if (NULL == p_data || NULL == p_socket) { return -1; } socket_id = (long)p_socket; count = (int)read(socket_id, p_data, datalen); return count; } int tc_iot_hal_udp_readTimeout(void *p_socket, unsigned char *p_data, unsigned int datalen, unsigned int timeout) { int ret; struct timeval tv; fd_set read_fds; long socket_id = -1; if (NULL == p_socket || NULL == p_data) { return -1; } socket_id = (long)p_socket; if (socket_id < 0) { return -1; } FD_ZERO(&read_fds); FD_SET(socket_id, &read_fds); tv.tv_sec = timeout / 1000; tv.tv_usec = (timeout % 1000) * 1000; ret = select(socket_id + 1, &read_fds, NULL, NULL, timeout == 0 ? NULL : &tv); /* Zero fds ready means we timed out */ if (ret == 0) { return -2; /* receive timeout */ } if (ret < 0) { if (errno == EINTR) { return -3; /* want read */ } return -4; /* receive failed */ } /* This call will not block */ return tc_iot_hal_udp_read(p_socket, p_data, datalen); } //===================================// #ifdef __cplusplus } #endif
181489.c
/* * Copyright (c) 2015-2019, Texas Instruments Incorporated * 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 Texas Instruments Incorporated 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. */ /* * ======== uartecho.c ======== */ #include <stdint.h> #include <stddef.h> #include <math.h> /* Driver Header files */ #include <ti/drivers/GPIO.h> #include <ti/drivers/UART.h> /* Driver configuration */ #include "ti_drivers_config.h" /* * ======== mainThread ======== */ void *mainThread(void *arg0) { char input; char buffer[40] = {0}; const char resetMsg[] = "Custom SAS simulator:\r\n"; const char detectMsg[] = "Detected!\r\n"; const char echoPrompt[] = "Echoing characters:\r\n"; UART_Handle uart; UART_Params uartParams; /* Call driver init functions */ GPIO_init(); UART_init(); /* Configure the LED pin */ GPIO_setConfig(CONFIG_GPIO_LED_0, GPIO_CFG_OUT_STD | GPIO_CFG_OUT_LOW); /* Turn on user LED */ GPIO_write(CONFIG_GPIO_LED_0, CONFIG_GPIO_LED_ON); /* Create a UART with data processing off. */ UART_Params_init(&uartParams); uartParams.writeDataMode = UART_DATA_BINARY; uartParams.readDataMode = UART_DATA_BINARY; uartParams.readReturnMode = UART_RETURN_FULL; uartParams.readEcho = UART_ECHO_OFF; uartParams.baudRate = 115200; uart = UART_open(CONFIG_UART_0, &uartParams); if (uart == NULL) { /* UART_open() failed */ while (1); } UART_write(uart, resetMsg, sizeof(resetMsg)); uint16_t voc = 0; uint16_t vmp = 0; uint16_t imp = 0; uint16_t isc = 0; uint32_t n = 0; uint16_t index = 0; float Voc; float Vmp; float Imp; float Isc; float N; float Rs = 0; float log2 = 0.69314718; float table[1024] = {0}; uint16_t j = 0; float vout = 0; uint8_t SOO = 0xFE; uint8_t EOO = 0xFD; float i; float x; float series; float v; /* Loop forever echoing */ while (1) { UART_read(uart, &input, sizeof(input)); if (input == 0xFD) { UART_read(uart, &voc, sizeof(voc)); UART_read(uart, &vmp, sizeof(vmp)); UART_read(uart, &imp, sizeof(imp)); UART_read(uart, &isc, sizeof(isc)); UART_read(uart, &n, sizeof(n)); UART_read(uart, &input, sizeof(input)); if (input == 0xFE) { UART_write(uart, &voc, sizeof(voc)); UART_write(uart, &vmp, sizeof(vmp)); UART_write(uart, &imp, sizeof(imp)); UART_write(uart, &isc, sizeof(isc)); UART_write(uart, &n, sizeof(n)); Voc = (float) voc / 10.0; Vmp = (float) vmp / 10.0; Imp = (float) imp / 10.0; Isc = (float) isc / 10.0; N = ((float) n) / 1000.0; Rs = (Voc - Vmp) / Imp; for (j = 0; j < 1024; j++) { i = ((float)j * Isc) / 1023.0; x = pow((i/Isc),N); series = log2; series -= (x / 2); series -= (pow(x,2)/8); series -= (pow(x,3)/24); series -= (pow(x,4)/64); v = (Voc * series) / log2; v -= Rs * ( i - Isc ); v /= (1 + ( ( Rs * Isc ) / Voc ) ); table[j] = v; } } UART_write(uart, &EOO, sizeof(EOO)); } if (input == 0xFB) { // UART_read(uart, &index, sizeof(index)); // UART_write(uart, &index, sizeof(index)); // vout = table[index]; UART_read(uart, &input, sizeof(input)); if (input == 0xFC) { UART_write(uart, &SOO, sizeof(SOO)); for (j = 0; j < 1024; j++) { vout = table[j]; UART_write(uart, &vout, sizeof(vout)); } //UART_write(uart, &vout, sizeof(vout)); //UART_write(uart, &EOO, sizeof(EOO)); } UART_write(uart, &EOO, sizeof(EOO)); } } }
320015.c
/* Copyright 2017, 2018 Bloomberg Finance L.P. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include <alloca.h> #include <pthread.h> #include <stdlib.h> #include "comdb2_plugin.h" #include "pb_alloc.h" #include "sp.h" #include "sql.h" #include "comdb2_appsock.h" #include "comdb2_atomic.h" #include <str0.h> #include <sqlquery.pb-c.h> #include <sqlresponse.pb-c.h> struct thr_handle; struct sbuf2; extern char gbl_dbname[MAX_DBNAME_LENGTH]; extern int gbl_sqlwrtimeoutms; extern int active_appsock_conns; #if WITH_SSL extern ssl_mode gbl_client_ssl_mode; extern SSL_CTX *gbl_ssl_ctx; extern int gbl_nid_dbname; void ssl_set_clnt_user(struct sqlclntstate *clnt); #endif int disable_server_sql_timeouts(void); int tdef_to_tranlevel(int tdef); int check_active_appsock_connections(struct sqlclntstate *clnt); int osql_clean_sqlclntstate(struct sqlclntstate *clnt); int watcher_warning_function(void *arg, int timeout, int gap); void handle_sql_intrans_unrecoverable_error(struct sqlclntstate *clnt); int fdb_access_control_create(struct sqlclntstate *clnt, char *str); int handle_failed_dispatch(struct sqlclntstate *clnt, char *errstr); int sbuf_is_local(SBUF2 *sb); static int newsql_clr_snapshot(struct sqlclntstate *); static int newsql_has_high_availability(struct sqlclntstate *); static int newsql_has_parallel_sql(struct sqlclntstate *); struct newsqlheader { int type; /* newsql request/response type */ int compression; /* Some sort of compression done? */ int state; /* query state - whether it's progressing, etc. */ int length; /* length of response */ }; struct newsql_postponed_data { size_t len; struct newsqlheader hdr; uint8_t *row; }; /* (SERVER) */ /* Default --> (val: 1) */ /* | */ /* +--> Client has SKIP feature? */ /* | | */ /* NO | | YES */ /* | | */ /* SET INTRANSRESULTS OFF ------)--->+--> (val: 0) --+ */ /* | | */ /* | +-----------------+ */ /* | | */ /* | +---> Send server SKIP feature; */ /* | Don't send intrans results */ /* | */ /* SET INTRANSRESULTS ON +-------> (val: 1) --+ */ /* | | */ /* | (val: -1) +-----------------+ */ /* | | */ /* +---------------------+--> Don't send server SKIP feature; */ /* Send intrans results */ /* */ /* (CLIENT) */ /* CDB2_READ_INTRANS_RESULTS is ON? */ /* /\ */ /* NO (default) / \ YES */ /* / \ */ /* Send Client \ */ /* SKIP feature \ */ /* / \ */ /* Server has \ */ /* SKIP feature? \ */ /* / \ \ */ /* Y / \ N \ */ /* / \ \ */ /* Don't read Read intrans results */ /* intrans results for writes */ /* for writes */ /* */ /* -- */ /* Rivers */ struct newsql_appdata { int8_t send_intrans_response; CDB2QUERY *query; CDB2SQLQUERY *sqlquery; struct newsql_postponed_data *postponed; /* row buf */ size_t packed_capacity; void *packed_buf; /* columns */ int count; int capacity; int type[0]; /* must be last */ }; static int fill_snapinfo(struct sqlclntstate *clnt, int *file, int *offset) { struct newsql_appdata *appdata = clnt->appdata; CDB2SQLQUERY *sql_query = appdata->sqlquery; int rcode = 0; if (sql_query && sql_query->snapshot_info && sql_query->snapshot_info->file > 0) { *file = sql_query->snapshot_info->file; *offset = sql_query->snapshot_info->offset; sql_debug_logf( clnt, __func__, __LINE__, "fill-snapinfo " "sql_query->snapinfo is [%d][%d], clnt->snapinfo is [%d][%d]: " "use client snapinfo!\n", sql_query->snapshot_info->file, sql_query->snapshot_info->offset, clnt->snapshot_file, clnt->snapshot_offset); return 0; } if (*file == 0 && sql_query && (in_client_trans(clnt) || clnt->is_hasql_retry) && clnt->snapshot_file) { sql_debug_logf( clnt, __func__, __LINE__, "fill-snapinfo " "sql_query->snapinfo is [%d][%d] clnt->snapinfo is [%d][%d]\n", (sql_query && sql_query->snapshot_info) ? sql_query->snapshot_info->file : -1, (sql_query && sql_query->snapshot_info) ? sql_query->snapshot_info->offset : -1, clnt->snapshot_file, clnt->snapshot_offset); *file = clnt->snapshot_file; *offset = clnt->snapshot_offset; logmsg(LOGMSG_USER, "%s line %d setting newsql snapinfo retry info is [%d][%d]\n", __func__, __LINE__, *file, *offset); return 0; } if (*file == 0 && sql_query && clnt->ctrl_sqlengine == SQLENG_STRT_STATE) { int rc; uint32_t snapinfo_file, snapinfo_offset; if (bdb_attr_get(thedb->bdb_attr, BDB_ATTR_DURABLE_LSNS)) { uint32_t durable_gen; rc = request_durable_lsn_from_master( thedb->bdb_env, &snapinfo_file, &snapinfo_offset, &durable_gen); if (rc == 0) { sql_debug_logf( clnt, __func__, __LINE__, "master returned " "durable-lsn [%d][%d], clnt->is_hasql_retry=%d\n", *file, *offset, clnt->is_hasql_retry); } else { sql_debug_logf(clnt, __func__, __LINE__, "durable-lsn request " "returns %d snapshot_file=%d snapshot_offset=%d " "is_hasql_retry=%d\n", rc, clnt->snapshot_file, clnt->snapshot_offset, clnt->is_hasql_retry); rcode = -1; } } else { (void)bdb_get_current_lsn(thedb->bdb_env, &snapinfo_file, &snapinfo_offset); rc = 0; sql_debug_logf(clnt, __func__, __LINE__, "durable-lsn is disabled. Use my LSN [%d][%d], " "clnt->is_hasql_retry=%d\n", *file, *offset, clnt->is_hasql_retry); } if (rc == 0) { *file = snapinfo_file; *offset = snapinfo_offset; } else { rcode = -1; } return rcode; } if (*file == 0) { bdb_tran_get_start_file_offset(thedb->bdb_env, clnt->dbtran.shadow_tran, file, offset); sql_debug_logf(clnt, __func__, __LINE__, "start_file_offset snapinfo " "is [%d][%d], sqlengine-state is %d\n", *file, *offset, clnt->ctrl_sqlengine); } return rcode; } #define _has_effects(clnt, sql_response) \ CDB2EFFECTS effects = CDB2__EFFECTS__INIT; \ \ clnt->effects.num_affected = clnt->effects.num_updated + \ clnt->effects.num_deleted + \ clnt->effects.num_inserted; \ effects.num_affected = clnt->effects.num_affected; \ effects.num_selected = clnt->effects.num_selected; \ effects.num_updated = clnt->effects.num_updated; \ effects.num_deleted = clnt->effects.num_deleted; \ effects.num_inserted = clnt->effects.num_inserted; \ \ sql_response.effects = &effects; #define _has_features(clnt, sql_response) \ CDB2ServerFeatures features[10]; \ int n_features = 0; \ struct newsql_appdata *appdata = clnt->appdata; \ if (appdata->send_intrans_response == 0) { \ features[n_features] = CDB2_SERVER_FEATURES__SKIP_INTRANS_RESULTS; \ n_features++; \ } \ \ if (n_features) { \ sql_response.n_features = n_features; \ sql_response.features = features; \ } #define _has_snapshot(clnt, sql_response) \ CDB2SQLRESPONSE__Snapshotinfo snapshotinfo = \ CDB2__SQLRESPONSE__SNAPSHOTINFO__INIT; \ \ if (newsql_has_high_availability(clnt)) { \ int file = 0, offset = 0; \ if (fill_snapinfo(clnt, &file, &offset)) { \ sql_response.error_code = (char)CDB2ERR_CHANGENODE; \ } \ if (file) { \ snapshotinfo.file = file; \ snapshotinfo.offset = offset; \ sql_response.snapshot_info = &snapshotinfo; \ } \ } /* Skip spaces and tabs, requires at least one space */ static inline char *skipws(char *str) { if (str) { while (*str && isspace(*str)) str++; } return str; } int gbl_abort_on_unset_ha_flag = 0; static int is_snap_uid_retry(struct sqlclntstate *clnt) { // Retries happen with a 'begin'. This can't be a retry if we are already // in a transaction if (clnt->ctrl_sqlengine != SQLENG_NORMAL_PROCESS) { return 0; } // Need to clear snapshot info here: we are not in a transaction. This code // makes sure that snapshot_file is cleared. newsql_clr_snapshot(clnt); struct newsql_appdata *appdata = clnt->appdata; CDB2SQLQUERY *sqlquery = appdata->sqlquery; if (sqlquery->retry == 0) { // Returning 0 because the retry flag is not lit return 0; } if (newsql_has_high_availability(clnt) == 0) { if (gbl_abort_on_unset_ha_flag) { // We shouldn't be here - try to understand why fflush(stdout); fflush(stderr); abort(); } } /** * If this is a retry, then: * * 1) this should be a BEGIN * 2) the retry flag should be set (we only set retry flag on a begin) * 3) we *could* have a valid snapshot_file and snapshot_offset * * 3 is the most difficult, as it looks like we don't actually know the * durable lsn until the first statement sent after the begin. This is * okay, but to make this work we just need to be extremely careful and * only send back the snapshot_file and snapshot_offset at the correct * time **/ /* Retry case has flag lit on "begin" */ if (sqlquery->snapshot_info && sqlquery->snapshot_info->file && strncasecmp(clnt->sql, "begin", 5) == 0) { clnt->snapshot_file = sqlquery->snapshot_info->file; clnt->snapshot_offset = sqlquery->snapshot_info->offset; clnt->is_hasql_retry = 1; } // XXX short circuiting the last-row optimization until i have a chance // to verify it. return 0; } static inline int newsql_to_client_type(int newsql_type) { switch (newsql_type) { case CDB2_INTEGER: return CLIENT_INT; case CDB2_REAL: return CLIENT_REAL; case CDB2_CSTRING: return CLIENT_CSTR; case CDB2_BLOB: return CLIENT_BLOB; case CDB2_DATETIME: return CLIENT_DATETIME; case CDB2_DATETIMEUS: return CLIENT_DATETIMEUS; case CDB2_INTERVALYM: return CLIENT_INTVYM; case CDB2_INTERVALDS: return CLIENT_INTVDS; case CDB2_INTERVALDSUS: return CLIENT_INTVDSUS; default: return -1; } } static int newsql_send_hdr(struct sqlclntstate *clnt, int h, int state) { struct newsqlheader hdr = {0}; hdr.type = ntohl(h); hdr.state = ntohl(state); int rc; lock_client_write_lock(clnt); if ((rc = sbuf2write((char *)&hdr, sizeof(hdr), clnt->sb)) != sizeof(hdr)) goto done; if ((rc = sbuf2flush(clnt->sb)) < 0) goto done; rc = 0; done: unlock_client_write_lock(clnt); return rc; } #define NEWSQL_MAX_RESPONSE_ON_STACK (16 * 1024) static int newsql_response_int(struct sqlclntstate *clnt, const CDB2SQLRESPONSE *r, int h, int flush) { size_t len = cdb2__sqlresponse__get_packed_size(r); uint8_t *buf; if (len < NEWSQL_MAX_RESPONSE_ON_STACK) { buf = alloca(len); } else { struct newsql_appdata *appdata = clnt->appdata; if (appdata->packed_capacity < len) { appdata->packed_capacity = len + 1024; appdata->packed_buf = malloc_resize(appdata->packed_buf, appdata->packed_capacity); } buf = appdata->packed_buf; } cdb2__sqlresponse__pack(r, buf); struct newsqlheader hdr = {0}; hdr.type = ntohl(h); hdr.length = ntohl(len); int rc; lock_client_write_lock(clnt); if ((rc = sbuf2write((char *)&hdr, sizeof(hdr), clnt->sb)) != sizeof(hdr)) goto done; if ((rc = sbuf2write((char *)buf, len, clnt->sb)) != len) goto done; if (flush && (rc = sbuf2flush(clnt->sb)) < 0) goto done; rc = 0; done: unlock_client_write_lock(clnt); return rc; } static int newsql_response(struct sqlclntstate *c, const CDB2SQLRESPONSE *r, int flush) { return newsql_response_int(c, r, RESPONSE_HEADER__SQL_RESPONSE, flush); } static int get_col_type(struct sqlclntstate *clnt, sqlite3_stmt *stmt, int col) { struct newsql_appdata *appdata = clnt->appdata; CDB2SQLQUERY *sql_query = appdata->sqlquery; int type = -1; if (sql_query->n_types) { type = sql_query->types[col]; } else if (stmt) { if (sqlite3_can_get_column_type_and_data(clnt, stmt)) { type = column_type(clnt, stmt, col); if (type == SQLITE_NULL) { type = typestr_to_type(sqlite3_column_decltype(stmt, col)); } } else { type = SQLITE_NULL; } } if (type == SQLITE_DECIMAL) { type = SQLITE_TEXT; } return type; } static struct newsql_appdata *get_newsql_appdata(struct sqlclntstate *clnt, int ncols) { struct newsql_appdata *appdata = clnt->appdata; size_t alloc_sz; if (appdata == NULL) { alloc_sz = sizeof(struct newsql_appdata) + ncols * sizeof(appdata->type[0]); appdata = calloc(1, alloc_sz); clnt->appdata = appdata; if (!appdata) goto oom; appdata->capacity = ncols; appdata->send_intrans_response = 1; } else if (appdata->capacity < ncols) { size_t n = ncols + 32; alloc_sz = sizeof(struct newsql_appdata) + n * sizeof(appdata->type[0]); appdata = realloc(appdata, alloc_sz); clnt->appdata = appdata; if (!appdata) goto oom; appdata->capacity = n; } appdata->count = ncols; return appdata; oom: logmsg(LOGMSG_ERROR, "%s:%d failed to (re)alloc %lu bytes (errno: %d, reason: %s)\n", __func__, __LINE__, alloc_sz, errno, strerror(errno)); return NULL; } static void free_newsql_appdata(struct sqlclntstate *clnt) { struct newsql_appdata *appdata = clnt->appdata; if (appdata == NULL) { return; } if (appdata->postponed) { free(appdata->postponed->row); free(appdata->postponed); appdata->postponed = NULL; } free(appdata->packed_buf); free(appdata); clnt->appdata = NULL; } extern int gbl_return_long_column_names; #define MAX_COL_NAME_LEN 31 #define ADJUST_LONG_COL_NAME(n, l) \ do { \ if (!gbl_return_long_column_names && l > MAX_COL_NAME_LEN) { \ l = MAX_COL_NAME_LEN + 1; \ char *namebuf = alloca(l); \ n = strncpy0(namebuf, n, l); \ } \ } while (0) static int newsql_columns(struct sqlclntstate *clnt, sqlite3_stmt *stmt) { int ncols = column_count(clnt, stmt); struct newsql_appdata *appdata = get_newsql_appdata(clnt, ncols); CDB2SQLRESPONSE__Column cols[ncols]; CDB2SQLRESPONSE__Column *value[ncols]; for (int i = 0; i < ncols; ++i) { value[i] = &cols[i]; cdb2__sqlresponse__column__init(&cols[i]); const char *name = sqlite3_column_name(stmt, i); size_t len = strlen(name) + 1; ADJUST_LONG_COL_NAME(name, len); cols[i].value.data = (uint8_t *)name; cols[i].value.len = len; cols[i].has_type = 1; cols[i].type = appdata->type[i] = get_col_type(clnt, stmt, i); } CDB2SQLRESPONSE resp = CDB2__SQLRESPONSE__INIT; resp.response_type = RESPONSE_TYPE__COLUMN_NAMES; resp.n_value = ncols; resp.value = value; return newsql_response(clnt, &resp, 0); } /* ** Derive types from cdb2_run_statement_typed, or defined in sp, or ** from sql statement. */ static int newsql_columns_lua(struct sqlclntstate *clnt, struct response_data *arg) { int ncols = arg->ncols; sqlite3_stmt *stmt = arg->stmt; if (stmt && column_count(clnt, stmt) != ncols) { return -1; } struct newsql_appdata *appdata = get_newsql_appdata(clnt, ncols); size_t n_types = appdata->sqlquery->n_types; if (n_types && n_types != ncols) { return -2; } CDB2SQLRESPONSE__Column cols[ncols]; CDB2SQLRESPONSE__Column *value[ncols]; for (int i = 0; i < ncols; ++i) { value[i] = &cols[i]; cdb2__sqlresponse__column__init(&cols[i]); const char *name = sp_column_name(arg, i); size_t len = strlen(name) + 1; ADJUST_LONG_COL_NAME(name, len); cols[i].value.data = (uint8_t *)name; cols[i].value.len = len; cols[i].has_type = 1; cols[i].type = appdata->type[i] = sp_column_type(arg, i, n_types, get_col_type(clnt, stmt, i)); } clnt->osql.sent_column_data = 1; CDB2SQLRESPONSE resp = CDB2__SQLRESPONSE__INIT; resp.response_type = RESPONSE_TYPE__COLUMN_NAMES; resp.n_value = ncols; resp.value = value; return newsql_response(clnt, &resp, 0); } static int newsql_columns_str(struct sqlclntstate *clnt, char **names, int ncols) { struct newsql_appdata *appdata = get_newsql_appdata(clnt, ncols); CDB2SQLRESPONSE__Column cols[ncols]; CDB2SQLRESPONSE__Column *value[ncols]; for (int i = 0; i < ncols; ++i) { value[i] = &cols[i]; cdb2__sqlresponse__column__init(&cols[i]); const char *name = names[i]; cols[i].value.data = (uint8_t *)name; cols[i].value.len = strlen(name) + 1; cols[i].has_type = 1; cols[i].type = appdata->type[i] = SQLITE_TEXT; } clnt->osql.sent_column_data = 1; CDB2SQLRESPONSE resp = CDB2__SQLRESPONSE__INIT; resp.response_type = RESPONSE_TYPE__COLUMN_NAMES; resp.n_value = ncols; resp.value = value; return newsql_response(clnt, &resp, 0); } static int newsql_debug(struct sqlclntstate *c, char *info) { CDB2SQLRESPONSE r = CDB2__SQLRESPONSE__INIT; r.response_type = RESPONSE_TYPE__SP_DEBUG; r.info_string = info; return newsql_response_int(c, &r, RESPONSE_HEADER__SQL_RESPONSE_TRACE, 1); } static int newsql_error(struct sqlclntstate *c, char *r, int e) { CDB2SQLRESPONSE resp = CDB2__SQLRESPONSE__INIT; resp.error_code = e; resp.error_string = r; resp.response_type = c->osql.sent_column_data ? RESPONSE_TYPE__COLUMN_VALUES : RESPONSE_TYPE__COLUMN_NAMES; return newsql_response(c, &resp, 1); } static int newsql_flush(struct sqlclntstate *clnt) { lock_client_write_lock(clnt); int rc = sbuf2flush(clnt->sb); unlock_client_write_lock(clnt); return rc < 0; } static int newsql_heartbeat(struct sqlclntstate *clnt) { int state; if (!clnt->heartbeat) return 0; if (!clnt->ready_for_heartbeats) return 0; state = (clnt->sqltick > clnt->sqltick_last_seen); clnt->sqltick_last_seen = clnt->sqltick; return newsql_send_hdr(clnt, RESPONSE_HEADER__SQL_RESPONSE_HEARTBEAT, state); } static int newsql_save_postponed_row(struct sqlclntstate *clnt, CDB2SQLRESPONSE *resp) { size_t len = cdb2__sqlresponse__get_packed_size(resp); struct newsql_appdata *appdata = clnt->appdata; if (appdata->postponed == NULL) { appdata->postponed = calloc(1, sizeof(struct newsql_postponed_data)); appdata->postponed->hdr.type = ntohl(RESPONSE_HEADER__SQL_RESPONSE); } appdata->postponed->len = len; appdata->postponed->hdr.length = htonl(len); appdata->postponed->row = realloc(appdata->postponed->row, len); cdb2__sqlresponse__pack(resp, appdata->postponed->row); return 0; } static int newsql_send_postponed_row(struct sqlclntstate *clnt) { struct newsql_appdata *appdata = clnt->appdata; char *hdr = (char *)&appdata->postponed->hdr; size_t hdrsz = sizeof(struct newsqlheader); char *row = (char *)appdata->postponed->row; size_t len = appdata->postponed->len; int rc; lock_client_write_lock(clnt); if ((rc = sbuf2write(hdr, hdrsz, clnt->sb)) != hdrsz) goto done; if ((rc = sbuf2write(row, len, clnt->sb)) != len) goto done; rc = 0; done: unlock_client_write_lock(clnt); return rc; } #define newsql_null(cols, i) \ do { \ cols[i].has_isnull = 1; \ cols[i].isnull = 1; \ } while (0) #define newsql_integer(cols, i, val, flip) \ do { \ int64_t *pi64 = alloca(sizeof(int64_t)); \ *pi64 = flip ? flibc_llflip(val) : val; \ cols[i].value.len = sizeof(int64_t); \ cols[i].value.data = (uint8_t *)pi64; \ } while (0) #define newsql_double(cols, i, val, flip) \ do { \ double *pd = alloca(sizeof(double)); \ *pd = flip ? flibc_dblflip(val) : val; \ cols[i].value.len = sizeof(double); \ cols[i].value.data = (uint8_t *)pd; \ } while (0) #define newsql_ym(cols, i, val, flip) \ do { \ cdb2_client_intv_ym_t *c = alloca(sizeof(cdb2_client_intv_ym_t)); \ if (flip) { \ c->sign = flibc_intflip(val->sign); \ c->years = flibc_intflip(val->u.ym.years); \ c->months = flibc_intflip(val->u.ym.months); \ } else { \ c->sign = val->sign; \ c->years = val->u.ym.years; \ c->months = val->u.ym.months; \ } \ cols[i].value.len = sizeof(*c); \ cols[i].value.data = (uint8_t *)c; \ } while (0) #define newsql_ds(cols, i, val, flip) \ do { \ int frac = val->u.ds.frac; \ if (type == SQLITE_INTERVAL_DS && val->u.ds.prec == 6) { \ frac /= 1000; \ } else if (type == SQLITE_INTERVAL_DSUS && val->u.ds.prec == 3) { \ frac *= 1000; \ } \ cdb2_client_intv_ds_t *c = alloca(sizeof(cdb2_client_intv_ds_t)); \ if (flip) { \ c->sign = flibc_intflip(val->sign); \ c->days = flibc_intflip(val->u.ds.days); \ c->hours = flibc_intflip(val->u.ds.hours); \ c->mins = flibc_intflip(val->u.ds.mins); \ c->sec = flibc_intflip(val->u.ds.sec); \ c->msec = flibc_intflip(frac); \ } else { \ c->sign = val->sign; \ c->days = val->u.ds.days; \ c->hours = val->u.ds.hours; \ c->mins = val->u.ds.mins; \ c->sec = val->u.ds.sec; \ c->msec = frac; \ } \ cols[i].value.len = sizeof(*c); \ cols[i].value.data = (uint8_t *)c; \ } while (0) #ifdef _SUN_SOURCE #include <arpa/nameser_compat.h> #endif #ifndef BYTE_ORDER #error "Missing BYTE_ORDER" #endif static int newsql_row(struct sqlclntstate *clnt, struct response_data *arg, int postpone) { sqlite3_stmt *stmt = arg->stmt; if (stmt == NULL) { return newsql_send_postponed_row(clnt); } int ncols = column_count(clnt, stmt); struct newsql_appdata *appdata = get_newsql_appdata(clnt, ncols); assert(ncols == appdata->count); int flip = 0; #if BYTE_ORDER == BIG_ENDIAN if (appdata->sqlquery->little_endian) #elif BYTE_ORDER == LITTLE_ENDIAN if (!appdata->sqlquery->little_endian) #endif flip = 1; CDB2SQLRESPONSE__Column cols[ncols]; CDB2SQLRESPONSE__Column *value[ncols]; for (int i = 0; i < ncols; ++i) { value[i] = &cols[i]; cdb2__sqlresponse__column__init(&cols[i]); if (!sqlite3_can_get_column_type_and_data(clnt, stmt) || column_type(clnt, stmt, i) == SQLITE_NULL) { newsql_null(cols, i); continue; } int type = appdata->type[i]; switch (type) { case SQLITE_INTEGER: { int64_t i64 = column_int64(clnt, stmt, i); newsql_integer(cols, i, i64, flip); break; } case SQLITE_FLOAT: { double d = column_double(clnt, stmt, i); newsql_double(cols, i, d, flip); break; } case SQLITE_TEXT: { cols[i].value.len = column_bytes(clnt, stmt, i) + 1; cols[i].value.data = (uint8_t *)column_text(clnt, stmt, i); break; } case SQLITE_BLOB: { cols[i].value.len = column_bytes(clnt, stmt, i); cols[i].value.data = (uint8_t *)column_blob(clnt, stmt, i); break; } case SQLITE_DATETIME: case SQLITE_DATETIMEUS: { const dttz_t *d = column_datetime(clnt, stmt, i); cdb2_client_datetime_t *c = alloca(sizeof(*c)); if (convDttz2ClientDatetime(d, stmt_tzname(stmt), c, type) != 0) { char *e = "failed to convert sqlite to client datetime for field"; errstat_set_rcstrf(arg->err, ERR_CONVERSION_DT, "%s \"%s\"", e, sqlite3_column_name(stmt, i)); return -1; } if (flip) { c->msec = flibc_intflip(c->msec); c->tm.tm_sec = flibc_intflip(c->tm.tm_sec); c->tm.tm_min = flibc_intflip(c->tm.tm_min); c->tm.tm_hour = flibc_intflip(c->tm.tm_hour); c->tm.tm_mday = flibc_intflip(c->tm.tm_mday); c->tm.tm_mon = flibc_intflip(c->tm.tm_mon); c->tm.tm_year = flibc_intflip(c->tm.tm_year); c->tm.tm_wday = flibc_intflip(c->tm.tm_wday); c->tm.tm_yday = flibc_intflip(c->tm.tm_yday); c->tm.tm_isdst = flibc_intflip(c->tm.tm_isdst); } cols[i].value.len = sizeof(*c); cols[i].value.data = (uint8_t *)c; break; } case SQLITE_INTERVAL_YM: { const intv_t *val = column_interval(clnt, stmt, i, SQLITE_AFF_INTV_MO); newsql_ym(cols, i, val, flip); break; } case SQLITE_INTERVAL_DS: case SQLITE_INTERVAL_DSUS: { const intv_t *val = column_interval(clnt, stmt, i, SQLITE_AFF_INTV_SE); newsql_ds(cols, i, val, flip); break; } case SQLITE_DECIMAL: default: return -1; } } CDB2SQLRESPONSE r = CDB2__SQLRESPONSE__INIT; r.response_type = RESPONSE_TYPE__COLUMN_VALUES; r.n_value = ncols; r.value = value; if (clnt->num_retry) { r.has_row_id = 1; r.row_id = arg->row_id; } if (postpone) { return newsql_save_postponed_row(clnt, &r); } else if (arg->pingpong) { return newsql_response_int(clnt, &r, RESPONSE_HEADER__SQL_RESPONSE_PING, 1); } return newsql_response(clnt, &r, 0); } static int newsql_row_last(struct sqlclntstate *clnt) { CDB2SQLRESPONSE resp = CDB2__SQLRESPONSE__INIT; resp.response_type = RESPONSE_TYPE__LAST_ROW; _has_effects(clnt, resp); _has_snapshot(clnt, resp); _has_features(clnt, resp); return newsql_response(clnt, &resp, 1); } static int newsql_row_last_dummy(struct sqlclntstate *clnt) { int rc; CDB2SQLRESPONSE resp = CDB2__SQLRESPONSE__INIT; resp.response_type = RESPONSE_TYPE__COLUMN_NAMES; if ((rc = newsql_response(clnt, &resp, 0)) != 0) { return rc; } return newsql_row_last(clnt); } static int newsql_row_lua(struct sqlclntstate *clnt, struct response_data *arg) { struct newsql_appdata *appdata = clnt->appdata; int ncols = arg->ncols; assert(ncols == appdata->count); int flip = 0; #if BYTE_ORDER == BIG_ENDIAN if (appdata->sqlquery->little_endian) #elif BYTE_ORDER == LITTLE_ENDIAN if (!appdata->sqlquery->little_endian) #endif flip = 1; CDB2SQLRESPONSE__Column cols[ncols]; CDB2SQLRESPONSE__Column *value[ncols]; for (int i = 0; i < ncols; ++i) { value[i] = &cols[i]; cdb2__sqlresponse__column__init(&cols[i]); if (sp_column_nil(arg, i)) { newsql_null(cols, i); continue; } int type = appdata->type[i]; switch (type) { case SQLITE_INTEGER: { int64_t i64; sp_column_val(arg, i, type, &i64); newsql_integer(cols, i, i64, flip); break; } case SQLITE_FLOAT: { double d; sp_column_val(arg, i, type, &d); newsql_double(cols, i, d, flip); break; } case SQLITE_TEXT: { size_t l; cols[i].value.data = sp_column_ptr(arg, i, type, &l); cols[i].value.len = l + 1; break; } case SQLITE_BLOB: { size_t l; cols[i].value.data = sp_column_ptr(arg, i, type, &l); cols[i].value.len = l; break; } case SQLITE_DATETIME: case SQLITE_DATETIMEUS: { datetime_t d; sp_column_val(arg, i, type, &d); if (d.prec == DTTZ_PREC_MSEC && type == SQLITE_DATETIMEUS) d.frac *= 1000; else if (d.prec == DTTZ_PREC_USEC && type == SQLITE_DATETIME) d.frac /= 1000; cdb2_client_datetime_t *c = alloca(sizeof(*c)); strcpy(c->tzname, d.tzname); if (flip) { c->msec = flibc_intflip(d.frac); c->tm.tm_sec = flibc_intflip(d.tm.tm_sec); c->tm.tm_min = flibc_intflip(d.tm.tm_min); c->tm.tm_hour = flibc_intflip(d.tm.tm_hour); c->tm.tm_mday = flibc_intflip(d.tm.tm_mday); c->tm.tm_mon = flibc_intflip(d.tm.tm_mon); c->tm.tm_year = flibc_intflip(d.tm.tm_year); c->tm.tm_wday = flibc_intflip(d.tm.tm_wday); c->tm.tm_yday = flibc_intflip(d.tm.tm_yday); c->tm.tm_isdst = flibc_intflip(d.tm.tm_isdst); } else { c->msec = d.frac; c->tm.tm_sec = d.tm.tm_sec; c->tm.tm_min = d.tm.tm_min; c->tm.tm_hour = d.tm.tm_hour; c->tm.tm_mday = d.tm.tm_mday; c->tm.tm_mon = d.tm.tm_mon; c->tm.tm_year = d.tm.tm_year; c->tm.tm_wday = d.tm.tm_wday; c->tm.tm_yday = d.tm.tm_yday; c->tm.tm_isdst = d.tm.tm_isdst; } cols[i].value.len = sizeof(*c); cols[i].value.data = (uint8_t *)c; break; } case SQLITE_INTERVAL_YM: { intv_t in, *val = &in; sp_column_val(arg, i, type, val); cdb2_client_intv_ym_t *c = alloca(sizeof(*c)); newsql_ym(cols, i, val, flip); break; } case SQLITE_INTERVAL_DS: case SQLITE_INTERVAL_DSUS: { intv_t in, *val = &in; sp_column_val(arg, i, type, &in); newsql_ds(cols, i, val, flip); break; } default: return -1; } } CDB2SQLRESPONSE r = CDB2__SQLRESPONSE__INIT; r.response_type = RESPONSE_TYPE__COLUMN_VALUES; r.n_value = ncols; r.value = value; if (arg->pingpong) { return newsql_response_int(clnt, &r, RESPONSE_HEADER__SQL_RESPONSE_PING, 1); } return newsql_response(clnt, &r, 0); } static int newsql_row_str(struct sqlclntstate *clnt, char **data, int ncols) { struct newsql_appdata *appdata = clnt->appdata; UNUSED_PARAMETER(appdata); /* prod build without assert */ assert(ncols == appdata->count); CDB2SQLRESPONSE__Column cols[ncols]; CDB2SQLRESPONSE__Column *value[ncols]; for (int i = 0; i < ncols; ++i) { value[i] = &cols[i]; cdb2__sqlresponse__column__init(&cols[i]); if (data[i] == NULL) { cols[i].has_isnull = 1; cols[i].isnull = 1; continue; } cols[i].value.data = (uint8_t *)data[i]; cols[i].value.len = strlen(data[i]) + 1; } CDB2SQLRESPONSE resp = CDB2__SQLRESPONSE__INIT; resp.response_type = RESPONSE_TYPE__COLUMN_VALUES; resp.n_value = ncols; resp.value = value; return newsql_response(clnt, &resp, 0); } static int newsql_trace(struct sqlclntstate *clnt, char *info) { CDB2SQLRESPONSE r = CDB2__SQLRESPONSE__INIT; r.response_type = RESPONSE_TYPE__SP_TRACE; r.info_string = info; return newsql_response_int(clnt, &r, RESPONSE_HEADER__SQL_RESPONSE_TRACE, 1); } static int newsql_cost(struct sqlclntstate *clnt) { dump_client_query_stats(clnt->dbglog, clnt->query_stats); return 0; } static int newsql_write_response(struct sqlclntstate *c, int t, void *a, int i) { switch (t) { case RESPONSE_COLUMNS: return newsql_columns(c, a); case RESPONSE_COLUMNS_LUA: return newsql_columns_lua(c, a); case RESPONSE_COLUMNS_STR: return newsql_columns_str(c, a, i); case RESPONSE_DEBUG: return newsql_debug(c, a); case RESPONSE_ERROR: return newsql_error(c, a, i); case RESPONSE_ERROR_ACCESS: return newsql_error(c, a, CDB2ERR_ACCESS); case RESPONSE_ERROR_BAD_STATE: return newsql_error(c, a, CDB2ERR_BADSTATE); case RESPONSE_ERROR_PREPARE: return newsql_error(c, a, CDB2ERR_PREPARE_ERROR); case RESPONSE_ERROR_REJECT: return newsql_error(c, a, CDB2ERR_REJECTED); case RESPONSE_FLUSH: return newsql_flush(c); case RESPONSE_HEARTBEAT: return newsql_heartbeat(c); case RESPONSE_ROW: return newsql_row(c, a, i); case RESPONSE_ROW_LAST: return newsql_row_last(c); case RESPONSE_ROW_LAST_DUMMY: return newsql_row_last_dummy(c); case RESPONSE_ROW_LUA: return newsql_row_lua(c, a); case RESPONSE_ROW_STR: return newsql_row_str(c, a, i); case RESPONSE_TRACE: return newsql_trace(c, a); case RESPONSE_COST: return newsql_cost(c); /* fastsql only messages */ case RESPONSE_EFFECTS: case RESPONSE_ERROR_PREPARE_RETRY: return 0; default: abort(); } } static int newsql_ping_pong(struct sqlclntstate *clnt) { struct newsqlheader hdr = {0}; int rc, r, w, timeout = 0; sbuf2gettimeout(clnt->sb, &r, &w); sbuf2settimeout(clnt->sb, 1000, w); rc = sbuf2fread_timeout((void *)&hdr, sizeof(hdr), 1, clnt->sb, &timeout); sbuf2settimeout(clnt->sb, r, w); if (timeout) return -1; if (rc != 1) return -2; if (ntohl(hdr.type) != RESPONSE_HEADER__SQL_RESPONSE_PONG) return -3; return 0; } static int newsql_sp_cmd(struct sqlclntstate *clnt, void *cmd, size_t sz) { struct newsqlheader hdr = {0}; if (sbuf2fread((void *)&hdr, sizeof(hdr), 1, clnt->sb) != 1) { return -1; } if (ntohl(hdr.type) != CDB2_REQUEST_TYPE__CDB2QUERY) { return -2; } int len = ntohl(hdr.length); if (len > sz) { return -3; } uint8_t buf[len]; if (sbuf2fread((char *)buf, len, 1, clnt->sb) != 1) { return -4; } CDB2QUERY *query = cdb2__query__unpack(NULL, len, buf); if (!query) { return -5; } strncpy0(cmd, query->spcmd, sz); cdb2__query__free_unpacked(query, NULL); return 0; } static int newsql_read_response(struct sqlclntstate *c, int t, void *r, int e) { switch (t) { case RESPONSE_PING_PONG: return newsql_ping_pong(c); case RESPONSE_SP_CMD: return newsql_sp_cmd(c, r, e); default: abort(); } } struct newsql_stmt { CDB2QUERY *query; char tzname[CDB2_MAX_TZNAME]; }; static void *newsql_save_stmt(struct sqlclntstate *clnt, void *arg) { struct newsql_appdata *appdata = clnt->appdata; struct newsql_stmt *stmt = malloc(sizeof(struct newsql_stmt)); stmt->query = appdata->query; strncpy0(stmt->tzname, clnt->tzname, sizeof(stmt->tzname)); return stmt; } static void *newsql_restore_stmt(struct sqlclntstate *clnt, void *arg) { struct newsql_stmt *stmt = arg; struct newsql_appdata *appdata = clnt->appdata; CDB2QUERY *query = appdata->query = stmt->query; appdata->sqlquery = query->sqlquery; strncpy0(clnt->tzname, stmt->tzname, sizeof(clnt->tzname)); clnt->sql = query->sqlquery->sql_query; return NULL; } static void *newsql_destroy_stmt(struct sqlclntstate *clnt, void *arg) { struct newsql_stmt *stmt = arg; struct newsql_appdata *appdata = clnt->appdata; if (appdata->query == stmt->query) { appdata->query = NULL; } cdb2__query__free_unpacked(stmt->query, &pb_alloc); free(stmt); return NULL; } static void *newsql_print_stmt(struct sqlclntstate *clnt, void *arg) { struct newsql_stmt *stmt = arg; return stmt->query->sqlquery->sql_query; } static int newsql_param_count(struct sqlclntstate *clnt) { struct newsql_appdata *appdata = clnt->appdata; return appdata->sqlquery->n_bindvars; } static int newsql_param_index(struct sqlclntstate *clnt, const char *name, int64_t *index) { /* ** Currently implemented like sqlite3_bind_parameter_index() ** Can be done better with qsort + bsearch */ struct newsql_appdata *appdata = clnt->appdata; CDB2SQLQUERY *sqlquery = appdata->sqlquery; size_t n = sqlquery->n_bindvars; for (size_t i = 0; i < n; ++i) { if (strcmp(sqlquery->bindvars[i]->varname, name) == 0) { *index = i; return 0; } } return -1; } static int newsql_param_value(struct sqlclntstate *clnt, struct param_data *param, int n) { struct newsql_appdata *appdata = clnt->appdata; CDB2SQLQUERY *sqlquery = appdata->sqlquery; if (n >= sqlquery->n_bindvars) { return -1; } CDB2SQLQUERY__Bindvalue *val = sqlquery->bindvars[n]; param->name = val->varname; param->pos = val->has_index ? val->index : 0; param->type = newsql_to_client_type(val->type); void *p = val->value.data; if (val->has_isnull && val->isnull) { param->null = 1; return 0; } if (val->value.data == NULL) { if (param->type != CLIENT_BLOB) { param->null = 1; return 0; } p = (void *)""; } int len = val->value.len; int little = appdata->sqlquery->little_endian; return get_type(param, p, len, param->type, clnt->tzname, little); } static int newsql_override_count(struct sqlclntstate *clnt) { struct newsql_appdata *appdata = clnt->appdata; return appdata->sqlquery->n_types; } static int newsql_override_type(struct sqlclntstate *clnt, int i) { struct newsql_appdata *appdata = clnt->appdata; int n = appdata->sqlquery->n_types; if (n && i >= 0 && i < n) { return appdata->sqlquery->types[i]; } return 0; } static int newsql_clr_cnonce(struct sqlclntstate *clnt) { struct newsql_appdata *appdata = clnt->appdata; CDB2SQLQUERY *sqlquery = appdata->sqlquery; sqlquery->has_cnonce = 0; return 0; } static int newsql_has_cnonce(struct sqlclntstate *clnt) { struct newsql_appdata *appdata = clnt->appdata; CDB2SQLQUERY *sqlquery = appdata->sqlquery; return sqlquery->has_cnonce; } static int newsql_set_cnonce(struct sqlclntstate *clnt) { struct newsql_appdata *appdata = clnt->appdata; CDB2SQLQUERY *sqlquery = appdata->sqlquery; sqlquery->has_cnonce = 1; return 0; } static int newsql_get_cnonce(struct sqlclntstate *clnt, snap_uid_t *snap) { struct newsql_appdata *appdata = clnt->appdata; CDB2SQLQUERY *sqlquery = appdata->sqlquery; if (!sqlquery->has_cnonce || sqlquery->cnonce.len > MAX_SNAP_KEY_LEN) { return -1; } snap->keylen = sqlquery->cnonce.len; memcpy(snap->key, sqlquery->cnonce.data, sqlquery->cnonce.len); return 0; } static int newsql_clr_snapshot(struct sqlclntstate *clnt) { clnt->snapshot_file = 0; clnt->snapshot_offset = 0; clnt->is_hasql_retry = 0; return 0; } static int newsql_get_snapshot(struct sqlclntstate *clnt, int *file, int *offset) { struct newsql_appdata *appdata = clnt->appdata; CDB2SQLQUERY *sqlquery = appdata->sqlquery; if (sqlquery->snapshot_info) { *file = sqlquery->snapshot_info->file; *offset = sqlquery->snapshot_info->offset; } return 0; } static int newsql_upd_snapshot(struct sqlclntstate *clnt) { struct newsql_appdata *appdata = clnt->appdata; CDB2SQLQUERY *sqlquery = appdata->sqlquery; extern int gbl_disable_skip_rows; /* We need to restore send_intrans_response on clnt even if the snapshot info has been populated. However, dont't attempt to restore if client overrides send_intrans_response by setting INTRANSRESULTS to ON. */ if (appdata->send_intrans_response != -1 && sqlquery->n_features > 0 && gbl_disable_skip_rows == 0) { for (int ii = 0; ii < sqlquery->n_features; ii++) { if (CDB2_CLIENT_FEATURES__SKIP_INTRANS_RESULTS != sqlquery->features[ii]) continue; appdata->send_intrans_response = 0; } } if (clnt->is_hasql_retry) { return 0; } // If this is a retry, we should already have the snapshot file and offset newsql_clr_snapshot(clnt); if (sqlquery->snapshot_info) { clnt->snapshot_file = sqlquery->snapshot_info->file; clnt->snapshot_offset = sqlquery->snapshot_info->offset; } return 0; } static int newsql_has_high_availability(struct sqlclntstate *clnt) { return clnt->high_availability_flag; } static int newsql_set_high_availability(struct sqlclntstate *clnt) { clnt->high_availability_flag = 1; return 0; } static int newsql_clr_high_availability(struct sqlclntstate *clnt) { clnt->high_availability_flag = 0; return 0; } static int newsql_get_high_availability(struct sqlclntstate *clnt) { struct newsql_appdata *appdata = clnt->appdata; CDB2SQLQUERY *sqlquery = appdata->sqlquery; /* MOHIT -- Check here that we are in high availablity, its cdb2api, and * is its a retry. */ if (clnt->ctrl_sqlengine == SQLENG_NORMAL_PROCESS) { if (sqlquery->retry) { clnt->num_retry = sqlquery->retry; if (sqlquery->snapshot_info) { clnt->snapshot_file = sqlquery->snapshot_info->file; clnt->snapshot_offset = sqlquery->snapshot_info->offset; } else { clnt->snapshot_file = 0; clnt->snapshot_offset = 0; } } else { clnt->num_retry = 0; clnt->snapshot_file = 0; clnt->snapshot_offset = 0; } } return is_snap_uid_retry(clnt); } static int newsql_has_parallel_sql(struct sqlclntstate *clnt) { return !gbl_dohsql_disable; } static void newsql_add_steps(struct sqlclntstate *clnt, double steps) { gbl_nnewsql_steps += steps; } static void newsql_setup_client_info(struct sqlclntstate *clnt, struct sqlthdstate *thd, char *replay) { struct newsql_appdata *appdata = clnt->appdata; CDB2SQLQUERY *sqlquery = appdata->sqlquery; CDB2SQLQUERY__Cinfo *cinfo = sqlquery->client_info; if (cinfo == NULL) return; thrman_wheref(thd->thr_self, "%s pid: %d host_id: %d argv0: %s open-stack: %s sql: %s", replay, cinfo->pid, cinfo->host_id, cinfo->argv0 ? cinfo->argv0 : "(unset)", cinfo->stack ? cinfo->stack : "(no-stack)", clnt->sql); } static int newsql_skip_row(struct sqlclntstate *clnt, uint64_t rowid) { struct newsql_appdata *appdata = clnt->appdata; CDB2SQLQUERY *sqlquery = appdata->sqlquery; if (clnt->num_retry == sqlquery->retry && (clnt->num_retry == 0 || sqlquery->has_skip_rows == 0 || sqlquery->skip_rows < rowid)) { return 0; } return 1; } static int newsql_log_context(struct sqlclntstate *clnt, struct reqlogger *logger) { struct newsql_appdata *appdata = clnt->appdata; CDB2SQLQUERY *sqlquery = appdata->sqlquery; if (sqlquery->n_context > 0) { for (int i = 0; i < sqlquery->n_context; ++i) { reqlog_logf(logger, REQL_INFO, "(%d) %s", i, sqlquery->context[i]); } } /* If request context is set, the client is changing the context. */ if (sqlquery->context) { /* Latch the context - client only re-sends context if it changes. TODO: this seems needlessly expensive. */ for (int i = 0, len = clnt->ncontext; i != len; ++i) free(clnt->context[i]); free(clnt->context); clnt->ncontext = sqlquery->n_context; clnt->context = malloc(sizeof(char *) * sqlquery->n_context); for (int i = 0; i < sqlquery->n_context; i++) clnt->context[i] = strdup(sqlquery->context[i]); } /* Whether latched from previous run, or just set, pass this to logger. */ reqlog_set_context(logger, clnt->ncontext, clnt->context); return 0; } static uint64_t newsql_get_client_starttime(struct sqlclntstate *clnt) { struct newsql_appdata *appdata = clnt->appdata; CDB2SQLQUERY *sqlquery = appdata->sqlquery; if (sqlquery->req_info) { return sqlquery->req_info->timestampus; } return 0; } static int newsql_get_client_retries(struct sqlclntstate *clnt) { struct newsql_appdata *appdata = clnt->appdata; CDB2SQLQUERY *sqlquery = appdata->sqlquery; if (sqlquery->req_info) { return sqlquery->req_info->num_retries; } return 0; } static int newsql_send_intrans_response(struct sqlclntstate *clnt) { struct newsql_appdata *appdata = clnt->appdata; return appdata->send_intrans_response; } int handle_set_querylimits(char *sqlstr, struct sqlclntstate *clnt) { int iswarn = 0; double cost; char *endp; sqlstr += 11; sqlstr = skipws(sqlstr); if (strncasecmp(sqlstr, "warn", 4) == 0) { sqlstr += 4; sqlstr = skipws(sqlstr); iswarn = 1; } if (strncasecmp(sqlstr, "maxcost", 7) == 0) { sqlstr += 7; sqlstr = skipws(sqlstr); cost = strtod(sqlstr, &endp); if (*endp != 0) return 1; if (iswarn) { clnt->limits.maxcost_warn = cost; } else { clnt->limits.maxcost = cost; } return 0; } else if (strncasecmp(sqlstr, "tablescans", 10) == 0) { int onoff = 1; sqlstr += 10; sqlstr = skipws(sqlstr); if (strncasecmp(sqlstr, "on", 2) == 0) { onoff = 1; } else if (strncasecmp(sqlstr, "off", 3) == 0) { onoff = 0; } else return 0; if (iswarn) { clnt->limits.tablescans_warn = onoff; } else { clnt->limits.tablescans_ok = htonl(onoff); } return 0; } else if (strncasecmp(sqlstr, "temptables", 10) == 0) { int onoff = 1; sqlstr += 10; sqlstr = skipws(sqlstr); if (strncasecmp(sqlstr, "on", 2) == 0) { onoff = 0; } else if (strncasecmp(sqlstr, "off", 3) == 0) { onoff = 1; } else return 0; if (iswarn) { clnt->limits.temptables_warn = htonl(onoff); } else { clnt->limits.temptables_ok = htonl(onoff); } return 0; } else return 1; } /* Process sql query if it is a set command. */ static int process_set_commands(struct dbenv *dbenv, struct sqlclntstate *clnt, CDB2SQLQUERY *sql_query) { struct newsql_appdata *appdata = clnt->appdata; int num_commands = 0; char *sqlstr = NULL; char *endp; int rc = 0; num_commands = sql_query->n_set_flags; for (int ii = 0; ii < num_commands && rc == 0; ii++) { sqlstr = sql_query->set_flags[ii]; sqlstr = skipws(sqlstr); if (strncasecmp(sqlstr, "set", 3) == 0) { char err[256]; err[0] = '\0'; sql_debug_logf(clnt, __func__, __LINE__, "processing set command '%s'\n", sqlstr); sqlstr += 3; sqlstr = skipws(sqlstr); if (strncasecmp(sqlstr, "transaction", 11) == 0) { sqlstr += 11; sqlstr = skipws(sqlstr); if (strncasecmp(sqlstr, "chunk", 5) == 0) { int tmp; sqlstr += 5; sqlstr = skipws(sqlstr); if (!sqlstr || ((tmp = atoi(sqlstr)) <= 0)) { snprintf(err, sizeof(err), "set transaction chunk N: missing chunk size " "N \"%s\"", sqlstr); rc = ii + 1; } else { clnt->dbtran.maxchunksize = tmp; /* in chunked mode, we disable verify retries */ clnt->verifyretry_off = 1; } } else { clnt->dbtran.mode = TRANLEVEL_INVALID; newsql_clr_high_availability(clnt); if (strncasecmp(sqlstr, "read", 4) == 0) { sqlstr += 4; sqlstr = skipws(sqlstr); if (strncasecmp(sqlstr, "committed", 9) == 0) { clnt->dbtran.mode = TRANLEVEL_RECOM; } } else if (strncasecmp(sqlstr, "serial", 6) == 0) { clnt->dbtran.mode = TRANLEVEL_SERIAL; if (clnt->hasql_on == 1) { newsql_set_high_availability(clnt); } } else if (strncasecmp(sqlstr, "blocksql", 7) == 0) { clnt->dbtran.mode = TRANLEVEL_SOSQL; } else if (strncasecmp(sqlstr, "snap", 4) == 0) { sqlstr += 4; clnt->dbtran.mode = TRANLEVEL_SNAPISOL; clnt->verify_retries = 0; if (clnt->hasql_on == 1) { newsql_set_high_availability(clnt); logmsg(LOGMSG_ERROR, "Enabling snapshot isolation " "high availability\n"); } } if (clnt->dbtran.mode == TRANLEVEL_INVALID) rc = ii + 1; } } else if (strncasecmp(sqlstr, "timeout", 7) == 0) { sqlstr += 7; sqlstr = skipws(sqlstr); int timeout = strtol(sqlstr, &endp, 10); int notimeout = disable_server_sql_timeouts(); sbuf2settimeout( clnt->sb, bdb_attr_get(thedb->bdb_attr, BDB_ATTR_MAX_SQL_IDLE_TIME) * 1000, notimeout ? 0 : timeout); if (timeout == 0) net_add_watch(clnt->sb, 0, 0); else net_add_watch_warning( clnt->sb, bdb_attr_get(dbenv->bdb_attr, BDB_ATTR_MAX_SQL_IDLE_TIME), notimeout ? 0 : (timeout / 1000), clnt, watcher_warning_function); } else if (strncasecmp(sqlstr, "maxquerytime", 12) == 0) { sqlstr += 12; sqlstr = skipws(sqlstr); int timeout = strtol(sqlstr, &endp, 10); if (timeout >= 0) clnt->query_timeout = timeout; } else if (strncasecmp(sqlstr, "timezone", 8) == 0) { sqlstr += 8; sqlstr = skipws(sqlstr); strncpy0(clnt->tzname, sqlstr, sizeof(clnt->tzname)); } else if (strncasecmp(sqlstr, "datetime", 8) == 0) { sqlstr += 8; sqlstr = skipws(sqlstr); if (strncasecmp(sqlstr, "precision", 9) == 0) { sqlstr += 9; sqlstr = skipws(sqlstr); DTTZ_TEXT_TO_PREC(sqlstr, clnt->dtprec, 0, return -1); } else { rc = ii + 1; } } else if (strncasecmp(sqlstr, "user", 4) == 0) { sqlstr += 4; sqlstr = skipws(sqlstr); if (!sqlite3IsCorrectlyQuoted(sqlstr)) { snprintf(err, sizeof(err), "set user: '%s' is an incorrectly quoted string", sqlstr); rc = ii + 1; } else { sqlite3Dequote(sqlstr); if (strlen(sqlstr) >= sizeof(clnt->user)) { snprintf(err, sizeof(err), "set user: '%s' exceeds %zu characters", sqlstr, sizeof(clnt->user) - 1); rc = ii + 1; } else { clnt->have_user = 1; /* Re-authenticate the new user. */ if (clnt->authgen && strcmp(clnt->user, sqlstr) != 0) clnt->authgen = 0; clnt->is_x509_user = 0; strcpy(clnt->user, sqlstr); } } } else if (strncasecmp(sqlstr, "password", 8) == 0) { sqlstr += 8; sqlstr = skipws(sqlstr); if (!sqlite3IsCorrectlyQuoted(sqlstr)) { snprintf(err, sizeof(err), "set user: '%s' is an incorrectly quoted string", sqlstr); rc = ii + 1; } else { sqlite3Dequote(sqlstr); if (strlen(sqlstr) >= sizeof(clnt->password)) { snprintf(err, sizeof(err), "set password: '%s' exceeds %zu characters", sqlstr, sizeof(clnt->password) - 1); rc = ii + 1; } else { clnt->have_password = 1; /* Re-authenticate the new password. */ if (clnt->authgen && strcmp(clnt->password, sqlstr) != 0) clnt->authgen = 0; strcpy(clnt->password, sqlstr); } } } else if (strncasecmp(sqlstr, "spversion", 9) == 0) { clnt->spversion.version_num = 0; free(clnt->spversion.version_str); clnt->spversion.version_str = NULL; sqlstr += 9; sqlstr = skipws(sqlstr); char *spname = sqlstr; while (!isspace(*sqlstr)) { ++sqlstr; } *sqlstr = 0; if ((sqlstr - spname) < MAX_SPNAME) { strncpy0(clnt->spname, spname, MAX_SPNAME); } else { rc = ii + 1; } ++sqlstr; sqlstr = skipws(sqlstr); int ver = strtol(sqlstr, &endp, 10); if (*sqlstr == '\'' || *sqlstr == '"') { // looks like a str if (strlen(sqlstr) < MAX_SPVERSION_LEN) { clnt->spversion.version_str = strdup(sqlstr); sqlite3Dequote(clnt->spversion.version_str); } else { rc = ii + 1; } } else if (*endp == 0) { // parsed entire number successfully clnt->spversion.version_num = ver; } else { rc = ii + 1; } } else if (strncasecmp(sqlstr, "prepare_only", 12) == 0) { sqlstr += 12; sqlstr = skipws(sqlstr); if (strncasecmp(sqlstr, "off", 3) == 0) { clnt->prepare_only = 0; } else { clnt->prepare_only = 1; } } else if (strncasecmp(sqlstr, "readonly", 8) == 0) { sqlstr += 8; sqlstr = skipws(sqlstr); if (strncasecmp(sqlstr, "off", 3) == 0) { clnt->is_readonly = 0; } else { clnt->is_readonly = 1; } } else if (strncasecmp(sqlstr, "expert", 6) == 0) { sqlstr += 6; sqlstr = skipws(sqlstr); if (strncasecmp(sqlstr, "off", 3) == 0) { clnt->is_expert = 0; } else { clnt->is_expert = 1; } } else if (strncasecmp(sqlstr, "sptrace", 7) == 0) { sqlstr += 7; sqlstr = skipws(sqlstr); if (strncasecmp(sqlstr, "off", 3) == 0) { clnt->want_stored_procedure_trace = 0; } else { clnt->want_stored_procedure_trace = 1; } } else if (strncasecmp(sqlstr, "cursordebug", 11) == 0) { sqlstr += 11; sqlstr = skipws(sqlstr); bdb_osql_trak(sqlstr, &clnt->bdb_osql_trak); } else if (strncasecmp(sqlstr, "spdebug", 7) == 0) { sqlstr += 7; sqlstr = skipws(sqlstr); if (strncasecmp(sqlstr, "off", 3) == 0) { clnt->want_stored_procedure_debug = 0; } else { clnt->want_stored_procedure_debug = 1; } } else if (strncasecmp(sqlstr, "HASQL", 5) == 0) { sqlstr += 5; sqlstr = skipws(sqlstr); if (strncasecmp(sqlstr, "on", 2) == 0) { clnt->hasql_on = 1; if (clnt->dbtran.mode == TRANLEVEL_SERIAL || clnt->dbtran.mode == TRANLEVEL_SNAPISOL) { newsql_set_high_availability(clnt); sql_debug_logf(clnt, __func__, __LINE__, "setting " "high_availability\n"); } } else { clnt->hasql_on = 0; newsql_clr_high_availability(clnt); sql_debug_logf(clnt, __func__, __LINE__, "clearing " "high_availability\n"); } } else if (strncasecmp(sqlstr, "verifyretry", 11) == 0) { sqlstr += 11; sqlstr = skipws(sqlstr); if (strncasecmp(sqlstr, "on", 2) == 0) { clnt->verifyretry_off = 0; } else { clnt->verifyretry_off = 1; } } else if (strncasecmp(sqlstr, "queryeffects", 12) == 0) { sqlstr += 12; sqlstr = skipws(sqlstr); if (strncasecmp(sqlstr, "statement", 9) == 0) { clnt->statement_query_effects = 1; } if (strncasecmp(sqlstr, "transaction", 11) == 0) { clnt->statement_query_effects = 0; } } else if (strncasecmp(sqlstr, "remote", 6) == 0) { sqlstr += 6; sqlstr = skipws(sqlstr); int fdbrc = fdb_access_control_create(clnt, sqlstr); if (fdbrc) { logmsg( LOGMSG_ERROR, "%s: failed to process remote access settings \"%s\"\n", __func__, sqlstr); rc = ii + 1; } } else if (strncasecmp(sqlstr, "getcost", 7) == 0) { sqlstr += 7; sqlstr = skipws(sqlstr); if (strncasecmp(sqlstr, "on", 2) == 0) { clnt->get_cost = 1; } else { clnt->get_cost = 0; } } else if (strncasecmp(sqlstr, "explain", 7) == 0) { sqlstr += 7; sqlstr = skipws(sqlstr); if (strncasecmp(sqlstr, "on", 2) == 0) { clnt->is_explain = 1; } else if (strncasecmp(sqlstr, "verbose", 7) == 0) { clnt->is_explain = 2; } else { clnt->is_explain = 0; } } else if (strncasecmp(sqlstr, "maxtransize", 11) == 0) { sqlstr += 11; int maxtransz = strtol(sqlstr, &endp, 10); if (endp != sqlstr && maxtransz >= 0) clnt->osql_max_trans = maxtransz; else logmsg(LOGMSG_ERROR, "Error: bad value for maxtransize %s\n", sqlstr); #ifdef DEBUG printf("setting clnt->osql_max_trans to %d\n", clnt->osql_max_trans); #endif } else if (strncasecmp(sqlstr, "groupconcatmemlimit", sizeof("groupconcatmemlimit") - 1) == 0) { sqlstr += sizeof("groupconcatmemlimit"); int sz = strtol(sqlstr, &endp, 10); if (endp != sqlstr && sz >= 0) clnt->group_concat_mem_limit = sz; else logmsg(LOGMSG_ERROR, "Error: bad value for groupconcatmemlimit %s\n", sqlstr); #ifdef DEBUG printf("setting clnt->group_concat_mem_limit to %d\n", clnt->group_concat_mem_limit); #endif } else if (strncasecmp(sqlstr, "plannereffort", 13) == 0) { sqlstr += 13; int effort = strtol(sqlstr, &endp, 10); if (0 < effort && effort <= 10) clnt->planner_effort = effort; #ifdef DEBUG printf("setting clnt->planner_effort to %d\n", clnt->planner_effort); #endif } else if (strncasecmp(sqlstr, "intransresults", 14) == 0) { sqlstr += 14; sqlstr = skipws(sqlstr); if (strncasecmp(sqlstr, "off", 3) == 0) { appdata->send_intrans_response = 0; } else { appdata->send_intrans_response = -1; } } else if (strncasecmp(sqlstr, "admin", 5) == 0) { sqlstr += 7; sqlstr = skipws(sqlstr); if (strncasecmp(sqlstr, "off", 3) == 0) { clnt->admin = 0; } else { clnt->admin = 1; } } else if (strncasecmp(sqlstr, "querylimit", 10) == 0) { rc = handle_set_querylimits(sqlstr, clnt); } else { rc = ii + 1; } if (rc) { if (err[0] == '\0') snprintf(err, sizeof(err) - 1, "Invalid set command '%s'", sqlstr); newsql_write_response(clnt, RESPONSE_ERROR_PREPARE, err, 0); } } } return rc; } static void send_dbinforesponse(struct dbenv *dbenv, SBUF2 *sb) { CDB2DBINFORESPONSE *dbinfo_response = malloc(sizeof(CDB2DBINFORESPONSE)); cdb2__dbinforesponse__init(dbinfo_response); fill_dbinfo(dbinfo_response, dbenv->bdb_env); int len = cdb2__dbinforesponse__get_packed_size(dbinfo_response); uint8_t *buf, *malloc_buf = NULL; if (len > NEWSQL_MAX_RESPONSE_ON_STACK) { buf = malloc_buf = malloc(len); } else { buf = alloca(len); } cdb2__dbinforesponse__pack(dbinfo_response, buf); struct newsqlheader hdr = {0}; hdr.type = htonl(RESPONSE_HEADER__DBINFO_RESPONSE); hdr.length = htonl(len); sbuf2write((char *)&hdr, sizeof(hdr), sb); sbuf2write((char *)buf, len, sb); sbuf2flush(sb); free(malloc_buf); cdb2__dbinforesponse__free_unpacked(dbinfo_response, &pb_alloc); } static int do_query_on_master_check(struct dbenv *dbenv, struct sqlclntstate *clnt, CDB2SQLQUERY *sql_query) { int allow_master_exec = 0; int allow_master_dbinfo = 0; for (int ii = 0; ii < sql_query->n_features; ii++) { if (CDB2_CLIENT_FEATURES__ALLOW_MASTER_EXEC == sql_query->features[ii]) { allow_master_exec = 1; } else if (CDB2_CLIENT_FEATURES__ALLOW_MASTER_DBINFO == sql_query->features[ii]) { allow_master_dbinfo = 1; } else if (CDB2_CLIENT_FEATURES__ALLOW_QUEUING == sql_query->features[ii]) { clnt->queue_me = 1; } } int do_master_check; if (dbenv->rep_sync == REP_SYNC_NONE || sbuf_is_local(clnt->sb)) do_master_check = 0; else do_master_check = 1; if (do_master_check && bdb_master_should_reject(dbenv->bdb_env) && allow_master_exec == 0) { ATOMIC_ADD32(gbl_masterrejects, 1); /* Send sql response with dbinfo. */ if (allow_master_dbinfo) send_dbinforesponse(dbenv, clnt->sb); logmsg(LOGMSG_DEBUG, "Query on master, will be rejected\n"); return 1; } return 0; } int gbl_send_failed_dispatch_message = 0; static CDB2QUERY *read_newsql_query(struct dbenv *dbenv, struct sqlclntstate *clnt, SBUF2 *sb) { struct newsqlheader hdr = {0}; CDB2QUERY *query = NULL; int rc; int pre_enabled = 0; int was_timeout = 0; retry_read: rc = sbuf2fread_timeout((char *)&hdr, sizeof(hdr), 1, sb, &was_timeout); if (rc != 1) { if (was_timeout && gbl_send_failed_dispatch_message) { handle_failed_dispatch(clnt, "Socket read timeout."); } return NULL; } hdr.type = ntohl(hdr.type); hdr.compression = ntohl(hdr.compression); hdr.length = ntohl(hdr.length); if (hdr.type == CDB2_REQUEST_TYPE__SSLCONN) { #if WITH_SSL /* If client requires SSL and we haven't done that, do SSL_accept() now. handle_newsql_request() will close the sb if SSL_accept() fails. */ /* Can't SSL_accept twice - probably a client API logic error. Let it disconnect. */ if (sslio_has_ssl(sb)) { logmsg(LOGMSG_WARN, "The connection is already SSL encrypted.\n"); return NULL; } /* Flush the SSL ability byte. We need to do this because: 1) The `require_ssl` field in dbinfo may not reflect the actual status of this node; 2) Doing SSL_accept() immediately would cause too many unnecessary EAGAIN/EWOULDBLOCK's for non-blocking BIO. */ char ssl_able = (gbl_client_ssl_mode >= SSL_ALLOW) ? 'Y' : 'N'; if ((rc = sbuf2putc(sb, ssl_able)) < 0 || (rc = sbuf2flush(sb)) < 0) return NULL; /* Don't close the connection if SSL verify fails so that we can send back an error to the client. */ if (ssl_able == 'Y' && sslio_accept(sb, gbl_ssl_ctx, gbl_client_ssl_mode, gbl_dbname, gbl_nid_dbname, NULL, 0, 0) != 1) { newsql_error(clnt, "Client certificate authentication failed.", CDB2ERR_CONNECT_ERROR); return NULL; } /* Extract the user from the certificate. */ ssl_set_clnt_user(clnt); #else /* Not compiled with SSL. Send back `N' to client and retry read. */ if ((rc = sbuf2putc(sb, 'N')) < 0 || (rc = sbuf2flush(sb)) < 0) return NULL; #endif goto retry_read; } else if (hdr.type == CDB2_REQUEST_TYPE__RESET) { /* Reset from sockpool.*/ if (clnt->ctrl_sqlengine == SQLENG_INTRANS_STATE) { /* Discard the pending transaction when receiving RESET from the sockpool. We reach here if 1) the handle is in a open transaction, and 2) the last statement is a SELECT, and 3) the client closes the handle and donates the connection to the sockpool, and then, 4) the client creates a new handle and reuses the connection from the sockpool. */ handle_sql_intrans_unrecoverable_error(clnt); } reset_clnt(clnt, sb, 0); clnt->tzname[0] = '\0'; clnt->osql.count_changes = 1; clnt->heartbeat = 1; clnt->dbtran.mode = tdef_to_tranlevel(gbl_sql_tranlevel_default); goto retry_read; } if (hdr.type > 2) { logmsg(LOGMSG_ERROR, "%s: Invalid message %d\n", __func__, hdr.type); return NULL; } int bytes = hdr.length; if (bytes <= 0) { logmsg(LOGMSG_ERROR, "%s: Junk message %d\n", __func__, bytes); return NULL; } char *p; if (bytes <= gbl_blob_sz_thresh_bytes) p = malloc(bytes); else while (1) { // big buffer. most certainly it is a huge blob. errno = 0; /* precondition: well-defined before call that may set */ p = comdb2_timedmalloc(blobmem, bytes, 1000); if (p != NULL || errno != ETIMEDOUT) break; Pthread_mutex_lock(&clnt->wait_mutex); clnt->heartbeat = 1; if (clnt->ready_for_heartbeats == 0) { pre_enabled = 1; clnt->ready_for_heartbeats = 1; } newsql_heartbeat(clnt); fdb_heartbeats(clnt); Pthread_mutex_unlock(&clnt->wait_mutex); } if (pre_enabled) { Pthread_mutex_lock(&clnt->wait_mutex); clnt->ready_for_heartbeats = 0; Pthread_mutex_unlock(&clnt->wait_mutex); pre_enabled = 0; } if (!p) { logmsg(LOGMSG_ERROR, "%s: out of memory malloc %d\n", __func__, bytes); return NULL; } rc = sbuf2fread(p, bytes, 1, sb); if (rc != 1) { free(p); logmsg(LOGMSG_DEBUG, "Error in sbuf2fread rc=%d\n", rc); return NULL; } while (1) { errno = 0; /* precondition: well-defined before call that may set */ query = cdb2__query__unpack(&pb_alloc, bytes, (uint8_t *)p); // errno can be set by cdb2__query__unpack // we retry malloc on out of memory condition if (query || errno != ETIMEDOUT) break; Pthread_mutex_lock(&clnt->wait_mutex); if (clnt->heartbeat == 0) clnt->heartbeat = 1; if (clnt->ready_for_heartbeats == 0) { pre_enabled = 1; clnt->ready_for_heartbeats = 1; } newsql_heartbeat(clnt); fdb_heartbeats(clnt); Pthread_mutex_unlock(&clnt->wait_mutex); } free(p); if (pre_enabled) { Pthread_mutex_lock(&clnt->wait_mutex); clnt->ready_for_heartbeats = 0; Pthread_mutex_unlock(&clnt->wait_mutex); } if (!query) return NULL; if (errno != 0) { cdb2__query__free_unpacked(query, &pb_alloc); return NULL; } // one of dbinfo or sqlquery must be non-NULL if (unlikely(!query->dbinfo && !query->sqlquery)) { cdb2__query__free_unpacked(query, &pb_alloc); query = NULL; goto retry_read; } if (query->dbinfo) { if (query->dbinfo->has_want_effects && query->dbinfo->want_effects == 1) { CDB2SQLRESPONSE sql_response = CDB2__SQLRESPONSE__INIT; CDB2EFFECTS effects = CDB2__EFFECTS__INIT; sql_response.response_type = RESPONSE_TYPE__COMDB2_INFO; /* Last Row. */ sql_response.n_value = 0; if (clnt->verifyretry_off == 1 || clnt->dbtran.mode == TRANLEVEL_SNAPISOL || clnt->dbtran.mode == TRANLEVEL_SERIAL) { clnt->effects.num_affected = clnt->effects.num_updated + clnt->effects.num_deleted + clnt->effects.num_inserted; effects.num_affected = clnt->effects.num_affected; effects.num_selected = clnt->effects.num_selected; effects.num_updated = clnt->effects.num_updated; effects.num_deleted = clnt->effects.num_deleted; effects.num_inserted = clnt->effects.num_inserted; set_sent_data_to_client(clnt, 1, __func__, __LINE__); sql_response.effects = &effects; sql_response.error_code = 0; } else { sql_response.error_code = -1; sql_response.error_string = "Get effects not supported in " "transaction with verifyretry on"; } newsql_response_int(clnt, &sql_response, RESPONSE_HEADER__SQL_EFFECTS, 1); } else { send_dbinforesponse(dbenv, sb); } cdb2__query__free_unpacked(query, &pb_alloc); query = NULL; goto retry_read; } #if WITH_SSL /* Do security check before we return. We do it only after the query has been unpacked so that we know whether it is a new client (new clients have SSL feature). The check must be done for every query, otherwise attackers could bypass it by using pooled connections from sockpool. The overhead of the check is negligible. */ if (gbl_client_ssl_mode >= SSL_REQUIRE && !sslio_has_ssl(sb)) { /* The code block does 2 things: 1. Return an error to outdated clients; 2. Send dbinfo to new clients to trigger SSL. It may happen when require_ssl is first time enabled across the cluster. */ int client_supports_ssl = 0; for (int ii = 0; ii < query->sqlquery->n_features; ++ii) { if (CDB2_CLIENT_FEATURES__SSL == query->sqlquery->features[ii]) { client_supports_ssl = 1; break; } } if (client_supports_ssl) { newsql_send_hdr(clnt, RESPONSE_HEADER__SQL_RESPONSE_SSL, 0); cdb2__query__free_unpacked(query, &pb_alloc); query = NULL; goto retry_read; } else { newsql_error(clnt, "The database requires SSL connections.", CDB2ERR_CONNECT_ERROR); } cdb2__query__free_unpacked(query, &pb_alloc); return NULL; } #endif return query; } extern int gbl_allow_incoherent_sql; static inline int incoh_reject(int admin, bdb_state_type *bdb_state) { /* If this isn't from an admin session and the node isn't coherent and we disallow running queries on an incoherent node, reject */ return (!admin && !bdb_am_i_coherent(bdb_state) && !gbl_allow_incoherent_sql); } int64_t gbl_denied_appsock_connection_count = 0; #define APPDATA ((struct newsql_appdata *)(clnt.appdata)) static int handle_newsql_request(comdb2_appsock_arg_t *arg) { CDB2QUERY *query = NULL; int rc = 0; struct sqlclntstate clnt; struct thr_handle *thr_self; struct sbuf2 *sb; struct dbenv *dbenv; struct dbtable *tab; extern size_t gbl_cached_output_buffer_max_bytes; thr_self = arg->thr_self; dbenv = arg->dbenv; tab = arg->tab; sb = arg->sb; if (tab->dbtype != DBTYPE_TAGGED_TABLE) { /* Don't change this message. The sql api recognises the first four characters (Erro) and can respond gracefully. */ sbuf2printf(sb, "Error: newsql is only supported for tagged DBs\n"); logmsg(LOGMSG_ERROR, "Error: newsql is only supported for tagged DBs\n"); sbuf2flush(sb); return APPSOCK_RETURN_ERR; } if (incoh_reject(arg->admin, dbenv->bdb_env)) { logmsg(LOGMSG_DEBUG, "%s:%d td %u new query on incoherent node, dropping socket\n", __func__, __LINE__, (uint32_t)pthread_self()); return APPSOCK_RETURN_OK; } /* There are points when we can't accept any more connections. */ if (dbenv->no_more_sql_connections) { return APPSOCK_RETURN_OK; } /* If we are NOT the master, and the db is set up for async replication, we should return an error at this point rather than proceed with potentially incoherent data. */ if (!arg->admin && dbenv->rep_sync == REP_SYNC_NONE && dbenv->master != gbl_mynode) { logmsg(LOGMSG_DEBUG, "%s:%d td %u new query on replicant with sync none, dropping\n", __func__, __LINE__, (uint32_t)pthread_self()); return APPSOCK_RETURN_OK; } /* This flag cannot be set to non-zero until after all the early returns in this function; otherwise, we may "leak" appsock connections. */ if (arg->keepsocket) *arg->keepsocket = 1; /* New way. Do the basic socket I/O in line in this thread (which has a very small stack); the handle_fastsql_requests function will dispatch to a pooled sql engine for performing queries. */ thrman_change_type(thr_self, THRTYPE_APPSOCK_SQL); reset_clnt(&clnt, sb, 1); clnt_register(&clnt); get_newsql_appdata(&clnt, 32); plugin_set_callbacks(&clnt, newsql); clnt.tzname[0] = '\0'; clnt.admin = arg->admin; if (incoh_reject(clnt.admin, thedb->bdb_env)) { logmsg(LOGMSG_ERROR, "%s:%d td %u new query on incoherent node, dropping socket\n", __func__, __LINE__, (uint32_t)pthread_self()); goto done; } query = read_newsql_query(dbenv, &clnt, sb); if (query == NULL) { logmsg(LOGMSG_DEBUG, "Query is NULL.\n"); goto done; } if (!clnt.admin && check_active_appsock_connections(&clnt)) { static time_t pr = 0; time_t now; gbl_denied_appsock_connection_count++; if ((now = time(NULL)) - pr) { logmsg(LOGMSG_WARN, "%s: Exhausted appsock connections, total %d connections " "denied-connection count=%"PRId64"\n", __func__, active_appsock_conns, gbl_denied_appsock_connection_count); pr = now; } newsql_error(&clnt, "Exhausted appsock connections.", CDB2__ERROR_CODE__APPSOCK_LIMIT); goto done; } #if 0 else logmsg(LOGMSG_DEBUG, "New Query: %s\n", query->sqlquery->sql_query); #endif if (query->sqlquery == NULL) { logmsg(LOGMSG_DEBUG, "Malformed SQL request.\n"); goto done; } CDB2SQLQUERY *sql_query = query->sqlquery; if (!clnt.admin && do_query_on_master_check(dbenv, &clnt, sql_query)) goto done; if (sql_query->client_info) { clnt.conninfo.pid = sql_query->client_info->pid; clnt.last_pid = sql_query->client_info->pid; } else { clnt.conninfo.pid = 0; clnt.last_pid = 0; } clnt.osql.count_changes = 1; clnt.dbtran.mode = tdef_to_tranlevel(gbl_sql_tranlevel_default); newsql_clr_high_availability(&clnt); int notimeout = disable_server_sql_timeouts(); sbuf2settimeout( sb, bdb_attr_get(thedb->bdb_attr, BDB_ATTR_MAX_SQL_IDLE_TIME) * 1000, notimeout ? 0 : gbl_sqlwrtimeoutms); sbuf2flush(sb); net_set_writefn(sb, sql_writer); int wrtimeoutsec; if (gbl_sqlwrtimeoutms == 0 || notimeout) wrtimeoutsec = 0; else wrtimeoutsec = gbl_sqlwrtimeoutms / 1000; net_add_watch_warning( sb, bdb_attr_get(thedb->bdb_attr, BDB_ATTR_MAX_SQL_IDLE_TIME), wrtimeoutsec, &clnt, watcher_warning_function); /* appsock threads aren't sql threads so for appsock pool threads * sqlthd will be NULL */ struct sql_thread *sqlthd = pthread_getspecific(query_info_key); if (sqlthd) { bzero(&sqlthd->clnt->conn, sizeof(struct conninfo)); sqlthd->clnt->origin[0] = 0; } sbuf2setclnt(sb, &clnt); while (query) { sql_query = query->sqlquery; #ifdef EXTENDED_DEBUG #define MAXTOPRINT 200 int num = logmsg(LOGMSG_DEBUG, "Query is '%.*s", MAXTOPRINT, sql_query->sql_query); if (num >= MAXTOPRINT) logmsg(LOGMSG_DEBUG, "...'\n"); else logmsg(LOGMSG_DEBUG, "'\n"); #endif APPDATA->query = query; APPDATA->sqlquery = sql_query; clnt.sql = sql_query->sql_query; clnt.added_to_hist = 0; if (!in_client_trans(&clnt)) { bzero(&clnt.effects, sizeof(clnt.effects)); bzero(&clnt.log_effects, sizeof(clnt.log_effects)); clnt.had_errors = 0; clnt.ctrl_sqlengine = SQLENG_NORMAL_PROCESS; } if (clnt.dbtran.mode < TRANLEVEL_SOSQL) { clnt.dbtran.mode = TRANLEVEL_SOSQL; } clnt.osql.sent_column_data = 0; clnt.stop_this_statement = 0; if ((clnt.tzname[0] == '\0') && sql_query->tzname) strncpy0(clnt.tzname, sql_query->tzname, sizeof(clnt.tzname)); if (sql_query->dbname && dbenv->envname && strcasecmp(sql_query->dbname, dbenv->envname)) { char errstr[64 + (2 * MAX_DBNAME_LENGTH)]; snprintf(errstr, sizeof(errstr), "DB name mismatch query:%s actual:%s", sql_query->dbname, dbenv->envname); logmsg(LOGMSG_ERROR, "%s\n", errstr); newsql_error(&clnt, errstr, CDB2__ERROR_CODE__WRONG_DB); goto done; } if (sql_query->client_info) { if (clnt.rawnodestats) { release_node_stats(clnt.argv0, clnt.stack, clnt.origin); clnt.rawnodestats = NULL; } if (clnt.conninfo.pid && clnt.conninfo.pid != sql_query->client_info->pid) { /* Different pid is coming without reset. */ logmsg(LOGMSG_WARN, "Multiple processes using same socket PID 1 %d " "PID 2 %d Host %.8x\n", clnt.conninfo.pid, sql_query->client_info->pid, sql_query->client_info->host_id); } clnt.conninfo.pid = sql_query->client_info->pid; clnt.conninfo.node = sql_query->client_info->host_id; if (clnt.argv0) { free(clnt.argv0); clnt.argv0 = NULL; } if (clnt.stack) { free(clnt.stack); clnt.stack = NULL; } if (sql_query->client_info->argv0) { clnt.argv0 = strdup(sql_query->client_info->argv0); } if (sql_query->client_info->stack) { clnt.stack = strdup(sql_query->client_info->stack); } } if (clnt.rawnodestats == NULL) { clnt.rawnodestats = get_raw_node_stats( clnt.argv0, clnt.stack, clnt.origin, sbuf2fileno(clnt.sb)); } if (process_set_commands(dbenv, &clnt, sql_query)) goto done; if (gbl_rowlocks && clnt.dbtran.mode != TRANLEVEL_SERIAL) clnt.dbtran.mode = TRANLEVEL_SNAPISOL; /* avoid new accepting new queries/transaction on opened connections if we are incoherent (and not in a transaction). */ if (incoh_reject(clnt.admin, thedb->bdb_env) && (clnt.ctrl_sqlengine == SQLENG_NORMAL_PROCESS)) { logmsg(LOGMSG_ERROR, "%s line %d td %u new query on incoherent node, " "dropping socket\n", __func__, __LINE__, (uint32_t)pthread_self()); goto done; } clnt.heartbeat = 1; ATOMIC_ADD32(gbl_nnewsql, 1); bool isCommitRollback = (strncasecmp(clnt.sql, "commit", 6) == 0 || strncasecmp(clnt.sql, "rollback", 8) == 0) ? true : false; if (!clnt.had_errors || isCommitRollback) { /* tell blobmem that I want my priority back when the sql thread is done */ comdb2bma_pass_priority_back(blobmem); rc = dispatch_sql_query(&clnt, PRIORITY_T_DEFAULT); if (clnt.had_errors && isCommitRollback) { rc = -1; } } clnt_change_state(&clnt, CONNECTION_IDLE); if (clnt.osql.replay == OSQL_RETRY_DO) { if (clnt.dbtran.trans_has_sp) { osql_set_replay(__FILE__, __LINE__, &clnt, OSQL_RETRY_NONE); srs_tran_destroy(&clnt); } else { rc = srs_tran_replay(&clnt, arg->thr_self); } if (clnt.osql.history == NULL) { query = APPDATA->query = NULL; } } else { /* if this transaction is done (marked by SQLENG_NORMAL_PROCESS), clean transaction sql history */ if (clnt.osql.history && clnt.ctrl_sqlengine == SQLENG_NORMAL_PROCESS) { srs_tran_destroy(&clnt); query = APPDATA->query = NULL; } } if (rc && !in_client_trans(&clnt)) goto done; if (clnt.added_to_hist) { clnt.added_to_hist = 0; } else if (APPDATA->query) { cdb2__query__free_unpacked(APPDATA->query, &pb_alloc); APPDATA->query = NULL; } /* Keep a reasonable amount of memory in the clnt. */ if (APPDATA->packed_capacity > gbl_cached_output_buffer_max_bytes) { APPDATA->packed_capacity = 0; free(APPDATA->packed_buf); APPDATA->packed_buf = NULL; } query = read_newsql_query(dbenv, &clnt, sb); } done: sbuf2setclnt(sb, NULL); clnt_unregister(&clnt); if (clnt.ctrl_sqlengine == SQLENG_INTRANS_STATE) { handle_sql_intrans_unrecoverable_error(&clnt); } if (clnt.rawnodestats) { release_node_stats(clnt.argv0, clnt.stack, clnt.origin); clnt.rawnodestats = NULL; } if (clnt.argv0) { free(clnt.argv0); clnt.argv0 = NULL; } if (clnt.stack) { free(clnt.stack); clnt.stack = NULL; } close_sp(&clnt); osql_clean_sqlclntstate(&clnt); if (clnt.dbglog) { sbuf2close(clnt.dbglog); clnt.dbglog = NULL; } if (query) { cdb2__query__free_unpacked(query, &pb_alloc); } free_newsql_appdata(&clnt); /* XXX free logical tran? */ close_appsock(sb); arg->sb = NULL; cleanup_clnt(&clnt); return APPSOCK_RETURN_OK; } comdb2_appsock_t newsql_plugin = { "newsql", /* Name */ "", /* Usage info */ 0, /* Execution count */ APPSOCK_FLAG_IS_SQL, /* Flags */ handle_newsql_request /* Handler function */ }; #include "plugin.h"
408058.c
/* * Copyright 1989, 1998 The Open Group Permission to use, copy, modify, distribute, and sell this software and its documentation for any purpose is hereby granted without fee, provided that the above copyright notice appear in all copies and that both that copyright notice and this permission notice appear in supporting documentation. The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE OPEN GROUP BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. Except as contained in this notice, the name of The Open Group shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Software without prior written authorization from The Open Group. * * Author: Chris D. Peterson, MIT X Consortium */ /* $XFree86: xc/programs/editres/geometry.c,v 1.6 2006/01/09 15:00:41 dawes Exp $ */ #include <X11/Intrinsic.h> #include <X11/StringDefs.h> #include <X11/Shell.h> #include <stdio.h> #include <X11/Xaw/Cardinals.h> #include "editresP.h" /* * Local function definitions */ static void AddToFlashList ( TreeInfo * tree_info, GetGeomInfo * geom_info, char ** errors ); static void _AddToFlashList ( TreeInfo * tree_info, char ** errors, WNode * node, int x, int y, unsigned int width, unsigned int height ); static void CreateFlashWidget ( TreeInfo * tree_info, int x, int y, unsigned int width, unsigned int height ); static void FlashWidgets ( TreeInfo * tree_info ); static void FlashWidgetsOn ( XtPointer info_ptr, XtIntervalId * id ); static void FlashWidgetsOff ( XtPointer info_ptr, XtIntervalId * id ); static void FlashWidgetsCleanup ( XtPointer info_ptr, XtIntervalId * id ); /* Function Name: _FindWidget * Description: Finds a widget in the tree and shows it to the user. * Arguments: w - any widget in the application. * Returns: none. */ void _FindWidget(w) Widget w; { char msg[BUFSIZ]; WNode * node; Window win; int x, y; /* location of event in root coordinates. */ sprintf(msg, res_labels[14]); SetMessage(global_screen_data.info_label, msg); if ( (win = GetClientWindow(w, &x, &y)) != None) { node = FindWidgetFromWindow(global_tree_info, win); if (node != NULL) { ProtocolStream * stream = &(global_client.stream); _XEditResResetStream(stream); InsertWidgetFromNode(stream, node); _XEditResPut16(stream, (short) x); _XEditResPut16(stream, (short) y); SetCommand(w, LocalFindChild, NULL); return; } } SetMessage(global_screen_data.info_label, res_labels[15]); } /* Function Name: DisplayChild * Description: Displays the child node returned by the client * Arguments: event - the event from the client. * Returns: none. */ void DisplayChild(event) Event * event; { FindChildEvent * find_event = (FindChildEvent *) event; WNode * node; char msg[BUFSIZ]; node = FindNode(global_tree_info->top_node, find_event->widgets.ids, find_event->widgets.num_widgets); if (node == NULL) { sprintf(msg, res_labels[13]); SetMessage(global_screen_data.info_label, msg); return; } SetAndCenterTreeNode(node); node = node->tree_info->top_node; sprintf(msg, res_labels[12], node->name, node->class); SetMessage(global_screen_data.info_label, msg); _FlashActiveWidgets(global_tree_info); } /* Function Name: _FlashActiveWidgets * Description: Highlights all active widgets in the tree. * Arguments: tree_info - information about the current tree. * Returns: none. */ void _FlashActiveWidgets(tree_info) TreeInfo * tree_info; { int i; ProtocolStream * stream = &(global_client.stream); if (tree_info == NULL) { SetMessage(global_screen_data.info_label, res_labels[17]); return; } if (tree_info->num_nodes == 0) { SetMessage(global_screen_data.info_label,res_labels[18]); return; } _XEditResResetStream(stream); /* * Insert the number of widgets. */ _XEditResPut16(stream, (unsigned short) tree_info->num_nodes); for (i = 0; i < tree_info->num_nodes; i++) InsertWidgetFromNode(stream, global_tree_info->active_nodes[i]); SetCommand(tree_info->tree_widget, LocalFlashWidget, NULL); } /* Function Name: HandleFlashWidget * Description: Is called when client has returned geometry of all widget * to flash. * Arguments: event - the event containing the client info. * Returns: none. */ char * HandleFlashWidget(event) Event * event; { GetGeomEvent * geom_event = (GetGeomEvent *) event; char * errors = NULL; int i; for (i = 0; i < (int)geom_event->num_entries; i++) AddToFlashList(global_tree_info, geom_event->info + i, &errors); FlashWidgets(global_tree_info); return(errors); } /* Function Name: AddWidgetToFlashList * Description: Adds a widget to the list of widget to flash. * Arguments: tree_info - info about this tree. * geom_info - the info from the client about this widget. * errors - a string containing the errors. * Returns: none */ static void AddToFlashList(tree_info, geom_info, errors) TreeInfo * tree_info; GetGeomInfo * geom_info; char ** errors; { WNode * node; char buf[BUFSIZ]; node = FindNode(tree_info->top_node, geom_info->widgets.ids, geom_info->widgets.num_widgets); if (node == NULL) { sprintf(buf, "Editres Internal Error: Unable to FindNode.\n"); AddString(errors, buf); return; } if (geom_info->error) { AddString(errors, geom_info->message); return; } if (!geom_info->visable) { sprintf(buf, "%s(0x%lx) - This widget is not mapped\n", node->name, node->id); AddString(errors, buf); return; } _AddToFlashList(tree_info, errors, node, geom_info->x, geom_info->y, geom_info->width + geom_info->border_width, geom_info->height + geom_info->border_width); } /* Function Name: _AddToFlashList * Description: adds the window to the current client's flash list. * Arguments: errors - a string to stuff any errors encountered. * node - the node associated with this object. * x, y - location of the flash widget in root coords. * width, height - size of the flash widget. * Returns: none. */ static void _AddToFlashList(tree_info, errors, node, x, y, width, height) TreeInfo * tree_info; char ** errors; WNode * node; int x, y; unsigned int width, height; { Display * dpy = XtDisplay(tree_info->tree_widget); Window window = (Window) node->window; XWindowAttributes attrs; if (window == EDITRES_IS_OBJECT) window = node->parent->window; if (window == EDITRES_IS_UNREALIZED) { char buf[BUFSIZ]; if (node->window == EDITRES_IS_OBJECT) sprintf(buf, "%s(0x%lx) - This object's parent is unrealized\n", node->name, node->id); else sprintf(buf, "%s(0x%lx) - This widget is unrealized\n", node->name, node->id); AddString(errors, buf); return; } global_error_code = NO_ERROR; /* Reset Error code. */ global_old_error_handler = XSetErrorHandler(HandleXErrors); global_serial_num = NextRequest(dpy); XGetWindowAttributes(dpy, window, &attrs); XSync(dpy, FALSE); XSetErrorHandler(global_old_error_handler); if (global_error_code == NO_WINDOW) { char buf[BUFSIZ]; sprintf(buf, "%s(0x%lx) - This widget's window no longer exists.\n", node->name, node->id); AddString(errors, buf); return; } if (attrs.map_state != IsViewable) { char buf[BUFSIZ]; sprintf(buf, "%s(0x%lx) - This widget is not mapped.\n", node->name, node->id); AddString(errors, buf); return; } CreateFlashWidget(tree_info, x, y, width, height); } /* Function Name: CreateFlashWidget * Description: Creates a widget of the size specified that * will flash on the display, and adds it to the list * of widgets to flash. * Arguments: tree_info - the tree information structure. * x,y,width, height - size and location of the flash widget. * Returns: none. */ #define MORE_FLASH_WIDGETS 5 static void CreateFlashWidget(tree_info, x, y, width, height) TreeInfo * tree_info; int x, y; unsigned int width, height; { Widget shell; Arg args[3]; Cardinal num = 0; Dimension bw; XtSetArg(args[num], XtNx, x); num++; XtSetArg(args[num], XtNy, y); num++; XtSetArg(args[num], XtNbackground, global_resources.flash_color); num++; shell = XtCreatePopupShell("flash", overrideShellWidgetClass, tree_info->tree_widget, args, num); num = 0; XtSetArg(args[num], XtNborderWidth, &bw); num++; XtGetValues(shell, args, num); bw *= 2; num = 0; XtSetArg(args[num], XtNwidth, (width - bw)); num++; XtSetArg(args[num], XtNheight, (height - bw)); num++; XtSetValues(shell, args, num); if (tree_info->num_flash_widgets + 1 > tree_info->alloc_flash_widgets) { tree_info->alloc_flash_widgets += MORE_FLASH_WIDGETS; tree_info->flash_widgets = (Widget *) XtRealloc((char *)tree_info->flash_widgets, sizeof(Widget) * tree_info->alloc_flash_widgets); } tree_info->flash_widgets[tree_info->num_flash_widgets] = shell; tree_info->num_flash_widgets++; } /* Function Name: FlashWidgets * Description: Starts the widgets flashing. * Arguments: tree_info - the info about the tree (contains flash list) * Returns: none */ static void FlashWidgets(tree_info) TreeInfo * tree_info; { int i; unsigned long wait, half_flash; XtAppContext ac = XtWidgetToApplicationContext(tree_info->tree_widget); if (tree_info->flash_widgets == NULL) /* no widgets to flash. */ return; wait = half_flash = global_resources.flash_time/2; for (i = 1; i < global_resources.num_flashes; i++) { XtAppAddTimeOut(ac, wait, FlashWidgetsOff,(XtPointer)tree_info); wait += half_flash; XtAppAddTimeOut(ac, wait, FlashWidgetsOn,(XtPointer)tree_info); wait += half_flash; } wait += half_flash; XtAppAddTimeOut(ac, wait, FlashWidgetsCleanup, (XtPointer)tree_info); FlashWidgetsOn((XtPointer) tree_info, (XtIntervalId *) NULL); } /* Function Name: FlashWidgetsOn * Description: Turns on all the Flash Widgets. * Arguments: info_ptr - pointer to the tree info. * id - *** UNUSED ***. * Returns: none */ /* ARGSUSED */ static void FlashWidgetsOn(info_ptr, id) XtPointer info_ptr; XtIntervalId * id; { int i; TreeInfo * tree_info = (TreeInfo *) info_ptr; for (i = 0; i < tree_info->num_flash_widgets; i++) { XtRealizeWidget(tree_info->flash_widgets[i]); XMapRaised(XtDisplay(tree_info->flash_widgets[i]), XtWindow(tree_info->flash_widgets[i])); } } /* Function Name: FlashWidgetsOff * Description: Turns off all the Flash Widgets. * Arguments: info_ptr - pointer to the tree info. * id - *** UNUSED ***. * Returns: none */ /* ARGSUSED */ static void FlashWidgetsOff(info_ptr, id) XtPointer info_ptr; XtIntervalId * id; { int i; TreeInfo * tree_info = (TreeInfo *) info_ptr; for (i = 0; i < tree_info->num_flash_widgets; i++) XtUnmapWidget(tree_info->flash_widgets[i]); } /* Function Name: FlashWidgetsCleanup * Description: Destroys all the Flash Widgets. * Arguments: info_ptr - pointer to the tree info. * id - *** UNUSED ***. * Returns: none */ /* ARGSUSED */ static void FlashWidgetsCleanup(info_ptr, id) XtPointer info_ptr; XtIntervalId * id; { int i; TreeInfo * tree_info = (TreeInfo *) info_ptr; /* * Unmap 'em first for consistency. */ for (i = 0; i < tree_info->num_flash_widgets; i++) XtUnmapWidget(tree_info->flash_widgets[i]); XFlush(XtDisplay(tree_info->tree_widget)); for (i = 0; i < tree_info->num_flash_widgets; i++) XtDestroyWidget(tree_info->flash_widgets[i]); XtFree((char *)tree_info->flash_widgets); tree_info->flash_widgets = NULL; tree_info->num_flash_widgets = tree_info->alloc_flash_widgets = 0; }
307753.c
#include <stdio.h> #define SACK_IMPLEMENTATION #include "sack.h" int main(int argc, char ** argv) { int i; sack sack; sack_init(&sack, 1000); puts("passing 1 arg makes it free all pointers but leak the table"); puts("passing 2 args makes it free everything"); for(i = 0; i < 123; ++i) printf("%p\n", sack_memdupmore(&sack, sack_alloc(&sack, 123), 123, 512)); if(argc > 1) sack_freepointers(&sack); if(argc > 2) sack_deinit(&sack); return 0; }
853655.c
int x = 10; int* a; float* b; int main(void) { a = &x; b = (float*)a; *b; }
874113.c
/* Call a function from a linked list of pointers that has a free'd element. */ #include <stdio.h> #include <stdlib.h> typedef int (*pfptr)(const char *, ...); typedef struct _link { struct _link *next; pfptr function; } link; int main() { link *start, *next, *current; int i; current = start = malloc(sizeof(link)); for (i = 0; i < 10; i++) { current->next = malloc(sizeof(link)); current->function = printf; next = current->next; if (i == 4) free(current); current = next; } current->next = NULL; start->next->next->next->next->next->next->function("hello world\n"); return 0; }
50493.c
/***************************************************************************** Copyright (c) 2014, Intel Corp. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * 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 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. 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. ***************************************************************************** * Contents: Native middle-level C interface to LAPACK function shgeqz * Author: Intel Corporation *****************************************************************************/ #include "lapacke_utils.h" lapack_int LAPACKE_shgeqz_work( int matrix_layout, char job, char compq, char compz, lapack_int n, lapack_int ilo, lapack_int ihi, float* h, lapack_int ldh, float* t, lapack_int ldt, float* alphar, float* alphai, float* beta, float* q, lapack_int ldq, float* z, lapack_int ldz, float* work, lapack_int lwork ) { lapack_int info = 0; if( matrix_layout == LAPACK_COL_MAJOR ) { /* Call LAPACK function and adjust info */ LAPACK_shgeqz( &job, &compq, &compz, &n, &ilo, &ihi, h, &ldh, t, &ldt, alphar, alphai, beta, q, &ldq, z, &ldz, work, &lwork, &info ); if( info < 0 ) { info = info - 1; } } else if( matrix_layout == LAPACK_ROW_MAJOR ) { lapack_int ldh_t = MAX(1,n); lapack_int ldq_t = MAX(1,n); lapack_int ldt_t = MAX(1,n); lapack_int ldz_t = MAX(1,n); float* h_t = NULL; float* t_t = NULL; float* q_t = NULL; float* z_t = NULL; /* Check leading dimension(s) */ if( ldh < n ) { info = -9; LAPACKE_xerbla( "LAPACKE_shgeqz_work", info ); return info; } if( ldq < n ) { info = -16; LAPACKE_xerbla( "LAPACKE_shgeqz_work", info ); return info; } if( ldt < n ) { info = -11; LAPACKE_xerbla( "LAPACKE_shgeqz_work", info ); return info; } if( ldz < n ) { info = -18; LAPACKE_xerbla( "LAPACKE_shgeqz_work", info ); return info; } /* Query optimal working array(s) size if requested */ if( lwork == -1 ) { LAPACK_shgeqz( &job, &compq, &compz, &n, &ilo, &ihi, h, &ldh_t, t, &ldt_t, alphar, alphai, beta, q, &ldq_t, z, &ldz_t, work, &lwork, &info ); return (info < 0) ? (info - 1) : info; } /* Allocate memory for temporary array(s) */ h_t = (float*)LAPACKE_malloc( sizeof(float) * ldh_t * MAX(1,n) ); if( h_t == NULL ) { info = LAPACK_TRANSPOSE_MEMORY_ERROR; goto exit_level_0; } t_t = (float*)LAPACKE_malloc( sizeof(float) * ldt_t * MAX(1,n) ); if( t_t == NULL ) { info = LAPACK_TRANSPOSE_MEMORY_ERROR; goto exit_level_1; } if( LAPACKE_lsame( compq, 'i' ) || LAPACKE_lsame( compq, 'v' ) ) { q_t = (float*)LAPACKE_malloc( sizeof(float) * ldq_t * MAX(1,n) ); if( q_t == NULL ) { info = LAPACK_TRANSPOSE_MEMORY_ERROR; goto exit_level_2; } } if( LAPACKE_lsame( compz, 'i' ) || LAPACKE_lsame( compz, 'v' ) ) { z_t = (float*)LAPACKE_malloc( sizeof(float) * ldz_t * MAX(1,n) ); if( z_t == NULL ) { info = LAPACK_TRANSPOSE_MEMORY_ERROR; goto exit_level_3; } } /* Transpose input matrices */ LAPACKE_sge_trans( matrix_layout, n, n, h, ldh, h_t, ldh_t ); LAPACKE_sge_trans( matrix_layout, n, n, t, ldt, t_t, ldt_t ); if( LAPACKE_lsame( compq, 'v' ) ) { LAPACKE_sge_trans( matrix_layout, n, n, q, ldq, q_t, ldq_t ); } if( LAPACKE_lsame( compz, 'v' ) ) { LAPACKE_sge_trans( matrix_layout, n, n, z, ldz, z_t, ldz_t ); } /* Call LAPACK function and adjust info */ LAPACK_shgeqz( &job, &compq, &compz, &n, &ilo, &ihi, h_t, &ldh_t, t_t, &ldt_t, alphar, alphai, beta, q_t, &ldq_t, z_t, &ldz_t, work, &lwork, &info ); if( info < 0 ) { info = info - 1; } /* Transpose output matrices */ LAPACKE_sge_trans( LAPACK_COL_MAJOR, n, n, h_t, ldh_t, h, ldh ); LAPACKE_sge_trans( LAPACK_COL_MAJOR, n, n, t_t, ldt_t, t, ldt ); if( LAPACKE_lsame( compq, 'i' ) || LAPACKE_lsame( compq, 'v' ) ) { LAPACKE_sge_trans( LAPACK_COL_MAJOR, n, n, q_t, ldq_t, q, ldq ); } if( LAPACKE_lsame( compz, 'i' ) || LAPACKE_lsame( compz, 'v' ) ) { LAPACKE_sge_trans( LAPACK_COL_MAJOR, n, n, z_t, ldz_t, z, ldz ); } /* Release memory and exit */ if( LAPACKE_lsame( compz, 'i' ) || LAPACKE_lsame( compz, 'v' ) ) { LAPACKE_free( z_t ); } exit_level_3: if( LAPACKE_lsame( compq, 'i' ) || LAPACKE_lsame( compq, 'v' ) ) { LAPACKE_free( q_t ); } exit_level_2: LAPACKE_free( t_t ); exit_level_1: LAPACKE_free( h_t ); exit_level_0: if( info == LAPACK_TRANSPOSE_MEMORY_ERROR ) { LAPACKE_xerbla( "LAPACKE_shgeqz_work", info ); } } else { info = -1; LAPACKE_xerbla( "LAPACKE_shgeqz_work", info ); } return info; }
108805.c
/* ---------------------------------------------------------------------- * Copyright (C) 2010-2014 ARM Limited. All rights reserved. * * $Date: 19. March 2015 * $Revision: V.1.4.5 * * Project: CMSIS DSP Library * Title: riscv_dct4_f32.c * * Description: Processing function of DCT4 & IDCT4 F32. * * Target Processor: Cortex-M4/Cortex-M3/Cortex-M0 * * 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 ARM LIMITED 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. Modifications 2017 Mostafa Saleh (Ported to RISC-V PULPino) * -------------------------------------------------------------------- */ #include <riscv_dsp/riscv_math.h> /** * @ingroup groupTransforms */ /** * @defgroup DCT4_IDCT4 DCT Type IV Functions * Representation of signals by minimum number of values is important for storage and transmission. * The possibility of large discontinuity between the beginning and end of a period of a signal * in DFT can be avoided by extending the signal so that it is even-symmetric. * Discrete Cosine Transform (DCT) is constructed such that its energy is heavily concentrated in the lower part of the * spectrum and is very widely used in signal and image coding applications. * The family of DCTs (DCT type- 1,2,3,4) is the outcome of different combinations of homogeneous boundary conditions. * DCT has an excellent energy-packing capability, hence has many applications and in data compression in particular. * * DCT is essentially the Discrete Fourier Transform(DFT) of an even-extended real signal. * Reordering of the input data makes the computation of DCT just a problem of * computing the DFT of a real signal with a few additional operations. * This approach provides regular, simple, and very efficient DCT algorithms for practical hardware and software implementations. * * DCT type-II can be implemented using Fast fourier transform (FFT) internally, as the transform is applied on real values, Real FFT can be used. * DCT4 is implemented using DCT2 as their implementations are similar except with some added pre-processing and post-processing. * DCT2 implementation can be described in the following steps: * - Re-ordering input * - Calculating Real FFT * - Multiplication of weights and Real FFT output and getting real part from the product. * * This process is explained by the block diagram below: * \image html DCT4.gif "Discrete Cosine Transform - type-IV" * * \par Algorithm: * The N-point type-IV DCT is defined as a real, linear transformation by the formula: * \image html DCT4Equation.gif * where <code>k = 0,1,2,.....N-1</code> *\par * Its inverse is defined as follows: * \image html IDCT4Equation.gif * where <code>n = 0,1,2,.....N-1</code> *\par * The DCT4 matrices become involutory (i.e. they are self-inverse) by multiplying with an overall scale factor of sqrt(2/N). * The symmetry of the transform matrix indicates that the fast algorithms for the forward * and inverse transform computation are identical. * Note that the implementation of Inverse DCT4 and DCT4 is same, hence same process function can be used for both. * * \par Lengths supported by the transform: * As DCT4 internally uses Real FFT, it supports all the lengths supported by riscv_rfft_f32(). * The library provides separate functions for Q15, Q31, and floating-point data types. * \par Instance Structure * The instances for Real FFT and FFT, cosine values table and twiddle factor table are stored in an instance data structure. * A separate instance structure must be defined for each transform. * There are separate instance structure declarations for each of the 3 supported data types. * * \par Initialization Functions * There is also an associated initialization function for each data type. * The initialization function performs the following operations: * - Sets the values of the internal structure fields. * - Initializes Real FFT as its process function is used internally in DCT4, by calling riscv_rfft_init_f32(). * \par * Use of the initialization function is optional. * However, if the initialization function is used, then the instance structure cannot be placed into a const data section. * To place an instance structure into a const data section, the instance structure must be manually initialized. * Manually initialize the instance structure as follows: * <pre> *riscv_dct4_instance_f32 S = {N, Nby2, normalize, pTwiddle, pCosFactor, pRfft, pCfft}; *riscv_dct4_instance_q31 S = {N, Nby2, normalize, pTwiddle, pCosFactor, pRfft, pCfft}; *riscv_dct4_instance_q15 S = {N, Nby2, normalize, pTwiddle, pCosFactor, pRfft, pCfft}; * </pre> * where \c N is the length of the DCT4; \c Nby2 is half of the length of the DCT4; * \c normalize is normalizing factor used and is equal to <code>sqrt(2/N)</code>; * \c pTwiddle points to the twiddle factor table; * \c pCosFactor points to the cosFactor table; * \c pRfft points to the real FFT instance; * \c pCfft points to the complex FFT instance; * The CFFT and RFFT structures also needs to be initialized, refer to riscv_cfft_radix4_f32() * and riscv_rfft_f32() respectively for details regarding static initialization. * * \par Fixed-Point Behavior * Care must be taken when using the fixed-point versions of the DCT4 transform functions. * In particular, the overflow and saturation behavior of the accumulator used in each function must be considered. * Refer to the function specific documentation below for usage guidelines. */ /** * @addtogroup DCT4_IDCT4 * @{ */ /** * @brief Processing function for the floating-point DCT4/IDCT4. * @param[in] *S points to an instance of the floating-point DCT4/IDCT4 structure. * @param[in] *pState points to state buffer. * @param[in,out] *pInlineBuffer points to the in-place input and output buffer. * @return none. */ void riscv_dct4_f32( const riscv_dct4_instance_f32 * S, float32_t * pState, float32_t * pInlineBuffer) { uint32_t i; /* Loop counter */ float32_t *weights = S->pTwiddle; /* Pointer to the Weights table */ float32_t *cosFact = S->pCosFactor; /* Pointer to the cos factors table */ float32_t *pS1, *pS2, *pbuff; /* Temporary pointers for input buffer and pState buffer */ float32_t in; /* Temporary variable */ /* DCT4 computation involves DCT2 (which is calculated using RFFT) * along with some pre-processing and post-processing. * Computational procedure is explained as follows: * (a) Pre-processing involves multiplying input with cos factor, * r(n) = 2 * u(n) * cos(pi*(2*n+1)/(4*n)) * where, * r(n) -- output of preprocessing * u(n) -- input to preprocessing(actual Source buffer) * (b) Calculation of DCT2 using FFT is divided into three steps: * Step1: Re-ordering of even and odd elements of input. * Step2: Calculating FFT of the re-ordered input. * Step3: Taking the real part of the product of FFT output and weights. * (c) Post-processing - DCT4 can be obtained from DCT2 output using the following equation: * Y4(k) = Y2(k) - Y4(k-1) and Y4(-1) = Y4(0) * where, * Y4 -- DCT4 output, Y2 -- DCT2 output * (d) Multiplying the output with the normalizing factor sqrt(2/N). */ /*-------- Pre-processing ------------*/ /* Multiplying input with cos factor i.e. r(n) = 2 * x(n) * cos(pi*(2*n+1)/(4*n)) */ riscv_scale_f32(pInlineBuffer, 2.0f, pInlineBuffer, S->N); riscv_mult_f32(pInlineBuffer, cosFact, pInlineBuffer, S->N); /* ---------------------------------------------------------------- * Step1: Re-ordering of even and odd elements as, * pState[i] = pInlineBuffer[2*i] and * pState[N-i-1] = pInlineBuffer[2*i+1] where i = 0 to N/2 ---------------------------------------------------------------------*/ /* pS1 initialized to pState */ pS1 = pState; /* pS2 initialized to pState+N-1, so that it points to the end of the state buffer */ pS2 = pState + (S->N - 1u); /* pbuff initialized to input buffer */ pbuff = pInlineBuffer; /* Initializing the loop counter to N/2 */ i = (uint32_t) S->Nby2; do { /* Re-ordering of even and odd elements */ /* pState[i] = pInlineBuffer[2*i] */ *pS1++ = *pbuff++; /* pState[N-i-1] = pInlineBuffer[2*i+1] */ *pS2-- = *pbuff++; /* Decrement the loop counter */ i--; } while(i > 0u); /* pbuff initialized to input buffer */ pbuff = pInlineBuffer; /* pS1 initialized to pState */ pS1 = pState; /* Initializing the loop counter */ i = (uint32_t) S->N; do { /* Writing the re-ordered output back to inplace input buffer */ *pbuff++ = *pS1++; /* Decrement the loop counter */ i--; } while(i > 0u); /* --------------------------------------------------------- * Step2: Calculate RFFT for N-point input * ---------------------------------------------------------- */ /* pInlineBuffer is real input of length N , pState is the complex output of length 2N */ riscv_rfft_f32(S->pRfft, pInlineBuffer, pState); /*---------------------------------------------------------------------- * Step3: Multiply the FFT output with the weights. *----------------------------------------------------------------------*/ riscv_cmplx_mult_cmplx_f32(pState, weights, pState, S->N); /* ----------- Post-processing ---------- */ /* DCT-IV can be obtained from DCT-II by the equation, * Y4(k) = Y2(k) - Y4(k-1) and Y4(-1) = Y4(0) * Hence, Y4(0) = Y2(0)/2 */ /* Getting only real part from the output and Converting to DCT-IV */ /* pbuff initialized to input buffer. */ pbuff = pInlineBuffer; /* pS1 initialized to pState */ pS1 = pState; /* Calculating Y4(0) from Y2(0) using Y4(0) = Y2(0)/2 */ in = *pS1++ * (float32_t) 0.5; /* input buffer acts as inplace, so output values are stored in the input itself. */ *pbuff++ = in; /* pState pointer is incremented twice as the real values are located alternatively in the array */ pS1++; /* Initializing the loop counter */ i = ((uint32_t) S->N - 1u); do { /* Calculating Y4(1) to Y4(N-1) from Y2 using equation Y4(k) = Y2(k) - Y4(k-1) */ /* pState pointer (pS1) is incremented twice as the real values are located alternatively in the array */ in = *pS1++ - in; *pbuff++ = in; /* points to the next real value */ pS1++; /* Decrement the loop counter */ i--; } while(i > 0u); /*------------ Normalizing the output by multiplying with the normalizing factor ----------*/ /* Initializing the loop counter */ i = (uint32_t) S->N; /* pbuff initialized to the pInlineBuffer(now contains the output values) */ pbuff = pInlineBuffer; do { /* Multiplying pInlineBuffer with the normalizing factor sqrt(2/N) */ in = *pbuff; *pbuff++ = in * S->normalize; /* Decrement the loop counter */ i--; } while(i > 0u); } /** * @} end of DCT4_IDCT4 group */
620848.c
// SPDX-License-Identifier: GPL-2.0-or-later /* * Copyright 2011 Freescale Semiconductor, Inc. */ #include <linux/module.h> #include <linux/init.h> #include <linux/of.h> #include <linux/of_device.h> #include <linux/platform_device.h> #include <linux/slab.h> #include <linux/dma-mapping.h> #include <linux/clk.h> #include <linux/clk-provider.h> #include <linux/delay.h> #include <linux/io.h> #include <linux/time.h> #include <sound/core.h> #include <sound/pcm.h> #include <sound/pcm_params.h> #include <sound/soc.h> #include "mxs-saif.h" #define MXS_SET_ADDR 0x4 #define MXS_CLR_ADDR 0x8 static struct mxs_saif *mxs_saif[2]; /* * SAIF is a little different with other normal SOC DAIs on clock using. * * For MXS, two SAIF modules are instantiated on-chip. * Each SAIF has a set of clock pins and can be operating in master * mode simultaneously if they are connected to different off-chip codecs. * Also, one of the two SAIFs can master or drive the clock pins while the * other SAIF, in slave mode, receives clocking from the master SAIF. * This also means that both SAIFs must operate at the same sample rate. * * We abstract this as each saif has a master, the master could be * itself or other saifs. In the generic saif driver, saif does not need * to know the different clkmux. Saif only needs to know who is its master * and operating its master to generate the proper clock rate for it. * The master id is provided in mach-specific layer according to different * clkmux setting. */ static int mxs_saif_set_dai_sysclk(struct snd_soc_dai *cpu_dai, int clk_id, unsigned int freq, int dir) { struct mxs_saif *saif = snd_soc_dai_get_drvdata(cpu_dai); switch (clk_id) { case MXS_SAIF_MCLK: saif->mclk = freq; break; default: return -EINVAL; } return 0; } /* * Since SAIF may work on EXTMASTER mode, IOW, it's working BITCLK&LRCLK * is provided by other SAIF, we provide a interface here to get its master * from its master_id. * Note that the master could be itself. */ static inline struct mxs_saif *mxs_saif_get_master(struct mxs_saif * saif) { return mxs_saif[saif->master_id]; } /* * Set SAIF clock and MCLK */ static int mxs_saif_set_clk(struct mxs_saif *saif, unsigned int mclk, unsigned int rate) { u32 scr; int ret; struct mxs_saif *master_saif; dev_dbg(saif->dev, "mclk %d rate %d\n", mclk, rate); /* Set master saif to generate proper clock */ master_saif = mxs_saif_get_master(saif); if (!master_saif) return -EINVAL; dev_dbg(saif->dev, "master saif%d\n", master_saif->id); /* Checking if can playback and capture simutaneously */ if (master_saif->ongoing && rate != master_saif->cur_rate) { dev_err(saif->dev, "can not change clock, master saif%d(rate %d) is ongoing\n", master_saif->id, master_saif->cur_rate); return -EINVAL; } scr = __raw_readl(master_saif->base + SAIF_CTRL); scr &= ~BM_SAIF_CTRL_BITCLK_MULT_RATE; scr &= ~BM_SAIF_CTRL_BITCLK_BASE_RATE; /* * Set SAIF clock * * The SAIF clock should be either 384*fs or 512*fs. * If MCLK is used, the SAIF clk ratio needs to match mclk ratio. * For 256x, 128x, 64x, and 32x sub-rates, set saif clk as 512*fs. * For 192x, 96x, and 48x sub-rates, set saif clk as 384*fs. * * If MCLK is not used, we just set saif clk to 512*fs. */ ret = clk_prepare_enable(master_saif->clk); if (ret) return ret; if (master_saif->mclk_in_use) { switch (mclk / rate) { case 32: case 64: case 128: case 256: case 512: scr &= ~BM_SAIF_CTRL_BITCLK_BASE_RATE; ret = clk_set_rate(master_saif->clk, 512 * rate); break; case 48: case 96: case 192: case 384: scr |= BM_SAIF_CTRL_BITCLK_BASE_RATE; ret = clk_set_rate(master_saif->clk, 384 * rate); break; default: /* SAIF MCLK should be a sub-rate of 512x or 384x */ clk_disable_unprepare(master_saif->clk); return -EINVAL; } } else { ret = clk_set_rate(master_saif->clk, 512 * rate); scr &= ~BM_SAIF_CTRL_BITCLK_BASE_RATE; } clk_disable_unprepare(master_saif->clk); if (ret) return ret; master_saif->cur_rate = rate; if (!master_saif->mclk_in_use) { __raw_writel(scr, master_saif->base + SAIF_CTRL); return 0; } /* * Program the over-sample rate for MCLK output * * The available MCLK range is 32x, 48x... 512x. The rate * could be from 8kHz to 192kH. */ switch (mclk / rate) { case 32: scr |= BF_SAIF_CTRL_BITCLK_MULT_RATE(4); break; case 64: scr |= BF_SAIF_CTRL_BITCLK_MULT_RATE(3); break; case 128: scr |= BF_SAIF_CTRL_BITCLK_MULT_RATE(2); break; case 256: scr |= BF_SAIF_CTRL_BITCLK_MULT_RATE(1); break; case 512: scr |= BF_SAIF_CTRL_BITCLK_MULT_RATE(0); break; case 48: scr |= BF_SAIF_CTRL_BITCLK_MULT_RATE(3); break; case 96: scr |= BF_SAIF_CTRL_BITCLK_MULT_RATE(2); break; case 192: scr |= BF_SAIF_CTRL_BITCLK_MULT_RATE(1); break; case 384: scr |= BF_SAIF_CTRL_BITCLK_MULT_RATE(0); break; default: return -EINVAL; } __raw_writel(scr, master_saif->base + SAIF_CTRL); return 0; } /* * Put and disable MCLK. */ int mxs_saif_put_mclk(unsigned int saif_id) { struct mxs_saif *saif = mxs_saif[saif_id]; u32 stat; if (!saif) return -EINVAL; stat = __raw_readl(saif->base + SAIF_STAT); if (stat & BM_SAIF_STAT_BUSY) { dev_err(saif->dev, "error: busy\n"); return -EBUSY; } clk_disable_unprepare(saif->clk); /* disable MCLK output */ __raw_writel(BM_SAIF_CTRL_CLKGATE, saif->base + SAIF_CTRL + MXS_SET_ADDR); __raw_writel(BM_SAIF_CTRL_RUN, saif->base + SAIF_CTRL + MXS_CLR_ADDR); saif->mclk_in_use = 0; return 0; } EXPORT_SYMBOL_GPL(mxs_saif_put_mclk); /* * Get MCLK and set clock rate, then enable it * * This interface is used for codecs who are using MCLK provided * by saif. */ int mxs_saif_get_mclk(unsigned int saif_id, unsigned int mclk, unsigned int rate) { struct mxs_saif *saif = mxs_saif[saif_id]; u32 stat; int ret; struct mxs_saif *master_saif; if (!saif) return -EINVAL; /* Clear Reset */ __raw_writel(BM_SAIF_CTRL_SFTRST, saif->base + SAIF_CTRL + MXS_CLR_ADDR); /* FIXME: need clear clk gate for register r/w */ __raw_writel(BM_SAIF_CTRL_CLKGATE, saif->base + SAIF_CTRL + MXS_CLR_ADDR); master_saif = mxs_saif_get_master(saif); if (saif != master_saif) { dev_err(saif->dev, "can not get mclk from a non-master saif\n"); return -EINVAL; } stat = __raw_readl(saif->base + SAIF_STAT); if (stat & BM_SAIF_STAT_BUSY) { dev_err(saif->dev, "error: busy\n"); return -EBUSY; } saif->mclk_in_use = 1; ret = mxs_saif_set_clk(saif, mclk, rate); if (ret) return ret; ret = clk_prepare_enable(saif->clk); if (ret) return ret; /* enable MCLK output */ __raw_writel(BM_SAIF_CTRL_RUN, saif->base + SAIF_CTRL + MXS_SET_ADDR); return 0; } EXPORT_SYMBOL_GPL(mxs_saif_get_mclk); /* * SAIF DAI format configuration. * Should only be called when port is inactive. */ static int mxs_saif_set_dai_fmt(struct snd_soc_dai *cpu_dai, unsigned int fmt) { u32 scr, stat; u32 scr0; struct mxs_saif *saif = snd_soc_dai_get_drvdata(cpu_dai); stat = __raw_readl(saif->base + SAIF_STAT); if (stat & BM_SAIF_STAT_BUSY) { dev_err(cpu_dai->dev, "error: busy\n"); return -EBUSY; } /* If SAIF1 is configured as slave, the clk gate needs to be cleared * before the register can be written. */ if (saif->id != saif->master_id) { __raw_writel(BM_SAIF_CTRL_SFTRST, saif->base + SAIF_CTRL + MXS_CLR_ADDR); __raw_writel(BM_SAIF_CTRL_CLKGATE, saif->base + SAIF_CTRL + MXS_CLR_ADDR); } scr0 = __raw_readl(saif->base + SAIF_CTRL); scr0 = scr0 & ~BM_SAIF_CTRL_BITCLK_EDGE & ~BM_SAIF_CTRL_LRCLK_POLARITY \ & ~BM_SAIF_CTRL_JUSTIFY & ~BM_SAIF_CTRL_DELAY; scr = 0; /* DAI mode */ switch (fmt & SND_SOC_DAIFMT_FORMAT_MASK) { case SND_SOC_DAIFMT_I2S: /* data frame low 1clk before data */ scr |= BM_SAIF_CTRL_DELAY; scr &= ~BM_SAIF_CTRL_LRCLK_POLARITY; break; case SND_SOC_DAIFMT_LEFT_J: /* data frame high with data */ scr &= ~BM_SAIF_CTRL_DELAY; scr &= ~BM_SAIF_CTRL_LRCLK_POLARITY; scr &= ~BM_SAIF_CTRL_JUSTIFY; break; default: return -EINVAL; } /* DAI clock inversion */ switch (fmt & SND_SOC_DAIFMT_INV_MASK) { case SND_SOC_DAIFMT_IB_IF: scr |= BM_SAIF_CTRL_BITCLK_EDGE; scr |= BM_SAIF_CTRL_LRCLK_POLARITY; break; case SND_SOC_DAIFMT_IB_NF: scr |= BM_SAIF_CTRL_BITCLK_EDGE; scr &= ~BM_SAIF_CTRL_LRCLK_POLARITY; break; case SND_SOC_DAIFMT_NB_IF: scr &= ~BM_SAIF_CTRL_BITCLK_EDGE; scr |= BM_SAIF_CTRL_LRCLK_POLARITY; break; case SND_SOC_DAIFMT_NB_NF: scr &= ~BM_SAIF_CTRL_BITCLK_EDGE; scr &= ~BM_SAIF_CTRL_LRCLK_POLARITY; break; } /* * Note: We simply just support master mode since SAIF TX can only * work as master. * Here the master is relative to codec side. * Saif internally could be slave when working on EXTMASTER mode. * We just hide this to machine driver. */ switch (fmt & SND_SOC_DAIFMT_MASTER_MASK) { case SND_SOC_DAIFMT_CBS_CFS: if (saif->id == saif->master_id) scr &= ~BM_SAIF_CTRL_SLAVE_MODE; else scr |= BM_SAIF_CTRL_SLAVE_MODE; __raw_writel(scr | scr0, saif->base + SAIF_CTRL); break; default: return -EINVAL; } return 0; } static int mxs_saif_startup(struct snd_pcm_substream *substream, struct snd_soc_dai *cpu_dai) { struct mxs_saif *saif = snd_soc_dai_get_drvdata(cpu_dai); int ret; /* clear error status to 0 for each re-open */ saif->fifo_underrun = 0; saif->fifo_overrun = 0; /* Clear Reset for normal operations */ __raw_writel(BM_SAIF_CTRL_SFTRST, saif->base + SAIF_CTRL + MXS_CLR_ADDR); /* clear clock gate */ __raw_writel(BM_SAIF_CTRL_CLKGATE, saif->base + SAIF_CTRL + MXS_CLR_ADDR); ret = clk_prepare(saif->clk); if (ret) return ret; return 0; } static void mxs_saif_shutdown(struct snd_pcm_substream *substream, struct snd_soc_dai *cpu_dai) { struct mxs_saif *saif = snd_soc_dai_get_drvdata(cpu_dai); clk_unprepare(saif->clk); } /* * Should only be called when port is inactive. * although can be called multiple times by upper layers. */ static int mxs_saif_hw_params(struct snd_pcm_substream *substream, struct snd_pcm_hw_params *params, struct snd_soc_dai *cpu_dai) { struct mxs_saif *saif = snd_soc_dai_get_drvdata(cpu_dai); struct mxs_saif *master_saif; u32 scr, stat; int ret; master_saif = mxs_saif_get_master(saif); if (!master_saif) return -EINVAL; /* mclk should already be set */ if (!saif->mclk && saif->mclk_in_use) { dev_err(cpu_dai->dev, "set mclk first\n"); return -EINVAL; } stat = __raw_readl(saif->base + SAIF_STAT); if (!saif->mclk_in_use && (stat & BM_SAIF_STAT_BUSY)) { dev_err(cpu_dai->dev, "error: busy\n"); return -EBUSY; } /* * Set saif clk based on sample rate. * If mclk is used, we also set mclk, if not, saif->mclk is * default 0, means not used. */ ret = mxs_saif_set_clk(saif, saif->mclk, params_rate(params)); if (ret) { dev_err(cpu_dai->dev, "unable to get proper clk\n"); return ret; } if (saif != master_saif) { /* * Set an initial clock rate for the saif internal logic to work * properly. This is important when working in EXTMASTER mode * that uses the other saif's BITCLK&LRCLK but it still needs a * basic clock which should be fast enough for the internal * logic. */ clk_enable(saif->clk); ret = clk_set_rate(saif->clk, 24000000); clk_disable(saif->clk); if (ret) return ret; ret = clk_prepare(master_saif->clk); if (ret) return ret; } scr = __raw_readl(saif->base + SAIF_CTRL); scr &= ~BM_SAIF_CTRL_WORD_LENGTH; scr &= ~BM_SAIF_CTRL_BITCLK_48XFS_ENABLE; switch (params_format(params)) { case SNDRV_PCM_FORMAT_S16_LE: scr |= BF_SAIF_CTRL_WORD_LENGTH(0); break; case SNDRV_PCM_FORMAT_S20_3LE: scr |= BF_SAIF_CTRL_WORD_LENGTH(4); scr |= BM_SAIF_CTRL_BITCLK_48XFS_ENABLE; break; case SNDRV_PCM_FORMAT_S24_LE: scr |= BF_SAIF_CTRL_WORD_LENGTH(8); scr |= BM_SAIF_CTRL_BITCLK_48XFS_ENABLE; break; default: return -EINVAL; } /* Tx/Rx config */ if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK) { /* enable TX mode */ scr &= ~BM_SAIF_CTRL_READ_MODE; } else { /* enable RX mode */ scr |= BM_SAIF_CTRL_READ_MODE; } __raw_writel(scr, saif->base + SAIF_CTRL); return 0; } static int mxs_saif_prepare(struct snd_pcm_substream *substream, struct snd_soc_dai *cpu_dai) { struct mxs_saif *saif = snd_soc_dai_get_drvdata(cpu_dai); /* enable FIFO error irqs */ __raw_writel(BM_SAIF_CTRL_FIFO_ERROR_IRQ_EN, saif->base + SAIF_CTRL + MXS_SET_ADDR); return 0; } static int mxs_saif_trigger(struct snd_pcm_substream *substream, int cmd, struct snd_soc_dai *cpu_dai) { struct mxs_saif *saif = snd_soc_dai_get_drvdata(cpu_dai); struct mxs_saif *master_saif; u32 delay; int ret; master_saif = mxs_saif_get_master(saif); if (!master_saif) return -EINVAL; switch (cmd) { case SNDRV_PCM_TRIGGER_START: case SNDRV_PCM_TRIGGER_RESUME: case SNDRV_PCM_TRIGGER_PAUSE_RELEASE: if (saif->state == MXS_SAIF_STATE_RUNNING) return 0; dev_dbg(cpu_dai->dev, "start\n"); ret = clk_enable(master_saif->clk); if (ret) { dev_err(saif->dev, "Failed to enable master clock\n"); return ret; } /* * If the saif's master is not itself, we also need to enable * itself clk for its internal basic logic to work. */ if (saif != master_saif) { ret = clk_enable(saif->clk); if (ret) { dev_err(saif->dev, "Failed to enable master clock\n"); clk_disable(master_saif->clk); return ret; } __raw_writel(BM_SAIF_CTRL_RUN, saif->base + SAIF_CTRL + MXS_SET_ADDR); } if (!master_saif->mclk_in_use) __raw_writel(BM_SAIF_CTRL_RUN, master_saif->base + SAIF_CTRL + MXS_SET_ADDR); if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK) { /* * write data to saif data register to trigger * the transfer. * For 24-bit format the 32-bit FIFO register stores * only one channel, so we need to write twice. * This is also safe for the other non 24-bit formats. */ __raw_writel(0, saif->base + SAIF_DATA); __raw_writel(0, saif->base + SAIF_DATA); } else { /* * read data from saif data register to trigger * the receive. * For 24-bit format the 32-bit FIFO register stores * only one channel, so we need to read twice. * This is also safe for the other non 24-bit formats. */ __raw_readl(saif->base + SAIF_DATA); __raw_readl(saif->base + SAIF_DATA); } master_saif->ongoing = 1; saif->state = MXS_SAIF_STATE_RUNNING; dev_dbg(saif->dev, "CTRL 0x%x STAT 0x%x\n", __raw_readl(saif->base + SAIF_CTRL), __raw_readl(saif->base + SAIF_STAT)); dev_dbg(master_saif->dev, "CTRL 0x%x STAT 0x%x\n", __raw_readl(master_saif->base + SAIF_CTRL), __raw_readl(master_saif->base + SAIF_STAT)); break; case SNDRV_PCM_TRIGGER_SUSPEND: case SNDRV_PCM_TRIGGER_STOP: case SNDRV_PCM_TRIGGER_PAUSE_PUSH: if (saif->state == MXS_SAIF_STATE_STOPPED) return 0; dev_dbg(cpu_dai->dev, "stop\n"); /* wait a while for the current sample to complete */ delay = USEC_PER_SEC / master_saif->cur_rate; if (!master_saif->mclk_in_use) { __raw_writel(BM_SAIF_CTRL_RUN, master_saif->base + SAIF_CTRL + MXS_CLR_ADDR); udelay(delay); } clk_disable(master_saif->clk); if (saif != master_saif) { __raw_writel(BM_SAIF_CTRL_RUN, saif->base + SAIF_CTRL + MXS_CLR_ADDR); udelay(delay); clk_disable(saif->clk); } master_saif->ongoing = 0; saif->state = MXS_SAIF_STATE_STOPPED; break; default: return -EINVAL; } return 0; } #define MXS_SAIF_RATES SNDRV_PCM_RATE_8000_192000 #define MXS_SAIF_FORMATS \ (SNDRV_PCM_FMTBIT_S16_LE | SNDRV_PCM_FMTBIT_S20_3LE | \ SNDRV_PCM_FMTBIT_S24_LE) static const struct snd_soc_dai_ops mxs_saif_dai_ops = { .startup = mxs_saif_startup, .shutdown = mxs_saif_shutdown, .trigger = mxs_saif_trigger, .prepare = mxs_saif_prepare, .hw_params = mxs_saif_hw_params, .set_sysclk = mxs_saif_set_dai_sysclk, .set_fmt = mxs_saif_set_dai_fmt, }; static int mxs_saif_dai_probe(struct snd_soc_dai *dai) { struct mxs_saif *saif = dev_get_drvdata(dai->dev); snd_soc_dai_set_drvdata(dai, saif); return 0; } static struct snd_soc_dai_driver mxs_saif_dai = { .name = "mxs-saif", .probe = mxs_saif_dai_probe, .playback = { .channels_min = 2, .channels_max = 2, .rates = MXS_SAIF_RATES, .formats = MXS_SAIF_FORMATS, }, .capture = { .channels_min = 2, .channels_max = 2, .rates = MXS_SAIF_RATES, .formats = MXS_SAIF_FORMATS, }, .ops = &mxs_saif_dai_ops, }; static const struct snd_soc_component_driver mxs_saif_component = { .name = "mxs-saif", }; static irqreturn_t mxs_saif_irq(int irq, void *dev_id) { struct mxs_saif *saif = dev_id; unsigned int stat; stat = __raw_readl(saif->base + SAIF_STAT); if (!(stat & (BM_SAIF_STAT_FIFO_UNDERFLOW_IRQ | BM_SAIF_STAT_FIFO_OVERFLOW_IRQ))) return IRQ_NONE; if (stat & BM_SAIF_STAT_FIFO_UNDERFLOW_IRQ) { dev_dbg(saif->dev, "underrun!!! %d\n", ++saif->fifo_underrun); __raw_writel(BM_SAIF_STAT_FIFO_UNDERFLOW_IRQ, saif->base + SAIF_STAT + MXS_CLR_ADDR); } if (stat & BM_SAIF_STAT_FIFO_OVERFLOW_IRQ) { dev_dbg(saif->dev, "overrun!!! %d\n", ++saif->fifo_overrun); __raw_writel(BM_SAIF_STAT_FIFO_OVERFLOW_IRQ, saif->base + SAIF_STAT + MXS_CLR_ADDR); } dev_dbg(saif->dev, "SAIF_CTRL %x SAIF_STAT %x\n", __raw_readl(saif->base + SAIF_CTRL), __raw_readl(saif->base + SAIF_STAT)); return IRQ_HANDLED; } static int mxs_saif_mclk_init(struct platform_device *pdev) { struct mxs_saif *saif = platform_get_drvdata(pdev); struct device_node *np = pdev->dev.of_node; struct clk *clk; int ret; clk = clk_register_divider(&pdev->dev, "mxs_saif_mclk", __clk_get_name(saif->clk), 0, saif->base + SAIF_CTRL, BP_SAIF_CTRL_BITCLK_MULT_RATE, 3, 0, NULL); if (IS_ERR(clk)) { ret = PTR_ERR(clk); if (ret == -EEXIST) return 0; dev_err(&pdev->dev, "failed to register mclk: %d\n", ret); return PTR_ERR(clk); } ret = of_clk_add_provider(np, of_clk_src_simple_get, clk); if (ret) return ret; return 0; } static int mxs_saif_probe(struct platform_device *pdev) { struct device_node *np = pdev->dev.of_node; struct mxs_saif *saif; int irq, ret = 0; struct device_node *master; if (!np) return -EINVAL; saif = devm_kzalloc(&pdev->dev, sizeof(*saif), GFP_KERNEL); if (!saif) return -ENOMEM; ret = of_alias_get_id(np, "saif"); if (ret < 0) return ret; else saif->id = ret; if (saif->id >= ARRAY_SIZE(mxs_saif)) { dev_err(&pdev->dev, "get wrong saif id\n"); return -EINVAL; } /* * If there is no "fsl,saif-master" phandle, it's a saif * master. Otherwise, it's a slave and its phandle points * to the master. */ master = of_parse_phandle(np, "fsl,saif-master", 0); if (!master) { saif->master_id = saif->id; } else { ret = of_alias_get_id(master, "saif"); if (ret < 0) return ret; else saif->master_id = ret; if (saif->master_id >= ARRAY_SIZE(mxs_saif)) { dev_err(&pdev->dev, "get wrong master id\n"); return -EINVAL; } } mxs_saif[saif->id] = saif; saif->clk = devm_clk_get(&pdev->dev, NULL); if (IS_ERR(saif->clk)) { ret = PTR_ERR(saif->clk); dev_err(&pdev->dev, "Cannot get the clock: %d\n", ret); return ret; } saif->base = devm_platform_ioremap_resource(pdev, 0); if (IS_ERR(saif->base)) return PTR_ERR(saif->base); irq = platform_get_irq(pdev, 0); if (irq < 0) return irq; saif->dev = &pdev->dev; ret = devm_request_irq(&pdev->dev, irq, mxs_saif_irq, 0, dev_name(&pdev->dev), saif); if (ret) { dev_err(&pdev->dev, "failed to request irq\n"); return ret; } platform_set_drvdata(pdev, saif); /* We only support saif0 being tx and clock master */ if (saif->id == 0) { ret = mxs_saif_mclk_init(pdev); if (ret) dev_warn(&pdev->dev, "failed to init clocks\n"); } ret = devm_snd_soc_register_component(&pdev->dev, &mxs_saif_component, &mxs_saif_dai, 1); if (ret) { dev_err(&pdev->dev, "register DAI failed\n"); return ret; } ret = mxs_pcm_platform_register(&pdev->dev); if (ret) { dev_err(&pdev->dev, "register PCM failed: %d\n", ret); return ret; } return 0; } static const struct of_device_id mxs_saif_dt_ids[] = { { .compatible = "fsl,imx28-saif", }, { /* sentinel */ } }; MODULE_DEVICE_TABLE(of, mxs_saif_dt_ids); static struct platform_driver mxs_saif_driver = { .probe = mxs_saif_probe, .driver = { .name = "mxs-saif", .of_match_table = mxs_saif_dt_ids, }, }; module_platform_driver(mxs_saif_driver); MODULE_AUTHOR("Freescale Semiconductor, Inc."); MODULE_DESCRIPTION("MXS ASoC SAIF driver"); MODULE_LICENSE("GPL"); MODULE_ALIAS("platform:mxs-saif");
180701.c
/* bigBed - interface to binary file with bed-style values (that is a bunch of * possibly overlapping regions. */ /* Copyright (C) 2013 The Regents of the University of California * See kent/LICENSE or http://genome.ucsc.edu/license/ for licensing information. */ #include "common.h" #include "hash.h" #include "linefile.h" #include "obscure.h" #include "dystring.h" #include "rangeTree.h" #include "cirTree.h" #include "bPlusTree.h" #include "basicBed.h" #include "asParse.h" #include "zlibFace.h" #include "sig.h" #include "udc.h" #include "bbiFile.h" #include "bigBed.h" struct bbiFile *bigBedFileOpenAlias(char *fileName, struct hash *aliasHash) /* Open up big bed file with chrom alias hash. */ { return bbiFileOpenAlias(fileName, bigBedSig, "big bed", aliasHash); } struct bbiFile *bigBedFileOpen(char *fileName) /* Open up big bed file. */ { return bigBedFileOpenAlias(fileName, NULL); } boolean bigBedFileCheckSigs(char *fileName) /* check file signatures at beginning and end of file */ { return bbiFileCheckSigs(fileName, bigBedSig, "big bed"); } struct bigBedInterval *bigBedIntervalQuery(struct bbiFile *bbi, char *chrom, bits32 start, bits32 end, int maxItems, struct lm *lm) /* Get data for interval. Return list allocated out of lm. Set maxItems to maximum * number of items to return, or to 0 for all items. */ { struct bigBedInterval *el, *list = NULL; int itemCount = 0; bbiAttachUnzoomedCir(bbi); // Find blocks with padded start and end to make sure we include zero-length insertions: bits32 paddedStart = (start > 0) ? start-1 : start; bits32 paddedEnd = end+1; bits32 chromId; struct fileOffsetSize *blockList = bbiOverlappingBlocks(bbi, bbi->unzoomedCir, chrom, paddedStart, paddedEnd, &chromId); struct fileOffsetSize *block, *beforeGap, *afterGap; struct udcFile *udc = bbi->udc; boolean isSwapped = bbi->isSwapped; /* Set up for uncompression optionally. */ char *uncompressBuf = NULL; if (bbi->uncompressBufSize > 0) uncompressBuf = needLargeMem(bbi->uncompressBufSize); char *mergedBuf = NULL; for (block = blockList; block != NULL; ) { /* Find contigious blocks and read them into mergedBuf. */ fileOffsetSizeFindGap(block, &beforeGap, &afterGap); bits64 mergedOffset = block->offset; bits64 mergedSize = beforeGap->offset + beforeGap->size - mergedOffset; udcSeek(udc, mergedOffset); mergedBuf = needLargeMem(mergedSize); udcMustRead(udc, mergedBuf, mergedSize); char *blockBuf = mergedBuf; /* Loop through individual blocks within merged section. */ for (;block != afterGap; block = block->next) { /* Uncompress if necessary. */ char *blockPt, *blockEnd; if (uncompressBuf) { blockPt = uncompressBuf; int uncSize = zUncompress(blockBuf, block->size, uncompressBuf, bbi->uncompressBufSize); blockEnd = blockPt + uncSize; } else { blockPt = blockBuf; blockEnd = blockPt + block->size; } while (blockPt < blockEnd) { /* Read next record into local variables. */ bits32 chr = memReadBits32(&blockPt, isSwapped); bits32 s = memReadBits32(&blockPt, isSwapped); bits32 e = memReadBits32(&blockPt, isSwapped); /* calculate length of rest of bed fields */ int restLen = strlen(blockPt); /* If we're actually in range then copy it into a new element and add to list. */ if (chr == chromId && ((s < end && e > start) // Make sure to include zero-length insertion elements at start or end: || (s == e && (s == end || e == start)))) { ++itemCount; if (maxItems > 0 && itemCount > maxItems) break; lmAllocVar(lm, el); el->start = s; el->end = e; if (restLen > 0) el->rest = lmCloneStringZ(lm, blockPt, restLen); el->chromId = chromId; slAddHead(&list, el); } // move blockPt pointer to end of previous bed blockPt += restLen + 1; } if (maxItems > 0 && itemCount > maxItems) break; blockBuf += block->size; } if (maxItems > 0 && itemCount > maxItems) break; freez(&mergedBuf); } freez(&mergedBuf); freeMem(uncompressBuf); slFreeList(&blockList); slReverse(&list); return list; } int bigBedIntervalToRow(struct bigBedInterval *interval, char *chrom, char *startBuf, char *endBuf, char **row, int rowSize) /* Convert bigBedInterval into an array of chars equivalent to what you'd get by * parsing the bed file. The startBuf and endBuf are used to hold the ascii representation of * start and end. Note that the interval->rest string will have zeroes inserted as a side effect. */ { int fieldCount = 3; sprintf(startBuf, "%u", interval->start); sprintf(endBuf, "%u", interval->end); row[0] = chrom; row[1] = startBuf; row[2] = endBuf; if (!isEmpty(interval->rest)) { int wordCount = chopByChar(cloneString(interval->rest), '\t', row+3, rowSize-3); fieldCount += wordCount; } return fieldCount; } static struct bbiInterval *bigBedCoverageIntervals(struct bbiFile *bbi, char *chrom, bits32 start, bits32 end, struct lm *lm) /* Return intervals where the val is the depth of coverage. */ { /* Get list of overlapping intervals */ struct bigBedInterval *bi, *biList = bigBedIntervalQuery(bbi, chrom, start, end, 0, lm); if (biList == NULL) return NULL; /* Make a range tree that collects coverage. */ struct rbTree *rangeTree = rangeTreeNew(); for (bi = biList; bi != NULL; bi = bi->next) rangeTreeAddToCoverageDepth(rangeTree, bi->start, bi->end); struct range *range, *rangeList = rangeTreeList(rangeTree); /* Convert rangeList to bbiInterval list. */ struct bbiInterval *bwi, *bwiList = NULL; for (range = rangeList; range != NULL; range = range->next) { lmAllocVar(lm, bwi); bwi->start = range->start; if (bwi->start < start) bwi->start = start; bwi->end = range->end; if (bwi->end > end) bwi->end = end; bwi->val = ptToInt(range->val); slAddHead(&bwiList, bwi); } slReverse(&bwiList); /* Clean up and go home. */ rangeTreeFree(&rangeTree); return bwiList; } boolean bigBedSummaryArrayExtended(struct bbiFile *bbi, char *chrom, bits32 start, bits32 end, int summarySize, struct bbiSummaryElement *summary) /* Get extended summary information for summarySize evenly spaced elements into * the summary array. */ { return bbiSummaryArrayExtended(bbi, chrom, start, end, bigBedCoverageIntervals, summarySize, summary); } boolean bigBedSummaryArray(struct bbiFile *bbi, char *chrom, bits32 start, bits32 end, enum bbiSummaryType summaryType, int summarySize, double *summaryValues) /* Fill in summaryValues with data from indicated chromosome range in bigBed file. * Be sure to initialize summaryValues to a default value, which will not be touched * for regions without data in file. (Generally you want the default value to either * be 0.0 or nan("") depending on the application.) Returns FALSE if no data * at that position. */ { return bbiSummaryArray(bbi, chrom, start, end, bigBedCoverageIntervals, summaryType, summarySize, summaryValues); } struct offsetSize /* Simple file offset and file size. */ { bits64 offset; bits64 size; }; static int cmpOffsetSizeRef(const void *va, const void *vb) /* Compare to sort slRef pointing to offsetSize. Sort is kind of hokey, * but guarantees all items that are the same will be next to each other * at least, which is all we care about. */ { const struct slRef *a = *((struct slRef **)va); const struct slRef *b = *((struct slRef **)vb); return memcmp(a->val, b->val, sizeof(struct offsetSize)); } static struct fileOffsetSize *fosFromRedundantBlockList(struct slRef **pBlockList, boolean isSwapped) /* Convert from list of references to offsetSize format to list of fileOffsetSize * format, while removing redundancy. Sorts *pBlockList as a side effect. */ { /* Sort input so it it easy to uniquify. */ slSort(pBlockList, cmpOffsetSizeRef); struct slRef *blockList = *pBlockList; /* Make new fileOffsetSize for each unique offsetSize. */ struct fileOffsetSize *fosList = NULL, *fos; struct offsetSize lastOffsetSize = {0,0}; struct slRef *blockRef; for (blockRef = blockList; blockRef != NULL; blockRef = blockRef->next) { if (memcmp(&lastOffsetSize, blockRef->val, sizeof(lastOffsetSize)) != 0) { memcpy(&lastOffsetSize, blockRef->val, sizeof(lastOffsetSize)); AllocVar(fos); if (isSwapped) { fos->offset = byteSwap64(lastOffsetSize.offset); fos->size = byteSwap64(lastOffsetSize.size); } else { fos->offset = lastOffsetSize.offset; fos->size = lastOffsetSize.size; } slAddHead(&fosList, fos); } } slReverse(&fosList); return fosList; } static struct fileOffsetSize *bigBedChunksMatchingName(struct bbiFile *bbi, struct bptFile *index, char *name) /* Get list of file chunks that match name. Can slFreeList this when done. */ { struct slRef *blockList = bptFileFindMultiple(index, name, strlen(name), sizeof(struct offsetSize)); struct fileOffsetSize *fosList = fosFromRedundantBlockList(&blockList, bbi->isSwapped); slRefFreeListAndVals(&blockList); return fosList; } static struct fileOffsetSize *bigBedChunksMatchingNames(struct bbiFile *bbi, struct bptFile *index, char **names, int nameCount) /* Get list of file chunks that match any of the names. Can slFreeList this when done. */ { /* Go through all names and make a blockList that includes all blocks with any hit to any name. * Many of these blocks will occur multiple times. */ struct slRef *blockList = NULL; int nameIx; for (nameIx = 0; nameIx < nameCount; ++nameIx) { char *name = names[nameIx]; struct slRef *oneList = bptFileFindMultiple(index, name, strlen(name), sizeof(struct offsetSize)); blockList = slCat(oneList, blockList); } /* Create nonredundant list of blocks. */ struct fileOffsetSize *fosList = fosFromRedundantBlockList(&blockList, bbi->isSwapped); /* Clean up and resturn result. */ slRefFreeListAndVals(&blockList); return fosList; } typedef boolean (*BbFirstWordMatch)(char *line, int fieldIx, void *target); /* A function that returns TRUE if first word in tab-separated line matches target. */ static void extractField(char *line, int fieldIx, char **retField, int *retFieldSize) /* Go through tab separated line and figure out start and size of given field. */ { int i; fieldIx -= 3; /* Skip over chrom/start/end, which are not in line. */ for (i=0; i<fieldIx; ++i) { line = strchr(line, '\t'); if (line == NULL) { warn("Not enough fields in extractField of %s", line); internalErr(); } line += 1; } char *end = strchr(line, '\t'); if (end == NULL) end = line + strlen(line); *retField = line; *retFieldSize = end - line; } static boolean bbWordMatchesName(char *line, int fieldIx, void *target) /* Return true if first word of line is same as target, which is just a string. */ { char *name = target; int fieldSize; char *field; extractField(line, fieldIx, &field, &fieldSize); return strlen(name) == fieldSize && memcmp(name, field, fieldSize) == 0; } static boolean bbWordIsInHash(char *line, int fieldIx, void *target) /* Return true if first word of line is same as target, which is just a string. */ { int fieldSize; char *field; extractField(line, fieldIx, &field, &fieldSize); char fieldString[fieldSize+1]; memcpy(fieldString, field, fieldSize); fieldString[fieldSize] = 0; /* Return boolean value that reflects whether we found it in hash */ struct hash *hash = target; return hashLookup(hash, fieldString) != NULL; } static struct bigBedInterval *bigBedIntervalsMatchingName(struct bbiFile *bbi, struct fileOffsetSize *fosList, BbFirstWordMatch matcher, int fieldIx, void *target, struct lm *lm) /* Return list of intervals inside of sectors of bbiFile defined by fosList where the name * matches target somehow. */ { struct bigBedInterval *interval, *intervalList = NULL; struct fileOffsetSize *fos; boolean isSwapped = bbi->isSwapped; for (fos = fosList; fos != NULL; fos = fos->next) { /* Read in raw data */ udcSeek(bbi->udc, fos->offset); char *rawData = needLargeMem(fos->size); udcRead(bbi->udc, rawData, fos->size); /* Optionally uncompress data, and set data pointer to uncompressed version. */ char *uncompressedData = NULL; char *data = NULL; int dataSize = 0; if (bbi->uncompressBufSize > 0) { data = uncompressedData = needLargeMem(bbi->uncompressBufSize); dataSize = zUncompress(rawData, fos->size, uncompressedData, bbi->uncompressBufSize); } else { data = rawData; dataSize = fos->size; } /* Set up for "memRead" routines to more or less treat memory block like file */ char *blockPt = data, *blockEnd = data + dataSize; struct dyString *dy = dyStringNew(32); // Keep bits outside of chrom/start/end here /* Read next record into local variables. */ while (blockPt < blockEnd) { bits32 chromIx = memReadBits32(&blockPt, isSwapped); bits32 s = memReadBits32(&blockPt, isSwapped); bits32 e = memReadBits32(&blockPt, isSwapped); int c; dyStringClear(dy); // TODO - can simplify this probably just to for (;;) {if ((c = *blockPt++) == 0) ... while ((c = *blockPt++) >= 0) { if (c == 0) break; dyStringAppendC(dy, c); } if ((*matcher)(dy->string, fieldIx, target)) { lmAllocVar(lm, interval); interval->start = s; interval->end = e; interval->rest = cloneString(dy->string); interval->chromId = chromIx; slAddHead(&intervalList, interval); } } /* Clean up temporary buffers. */ dyStringFree(&dy); freez(&uncompressedData); freez(&rawData); } slReverse(&intervalList); return intervalList; } struct bigBedInterval *bigBedNameQuery(struct bbiFile *bbi, struct bptFile *index, int fieldIx, char *name, struct lm *lm) /* Return list of intervals matching file. These intervals will be allocated out of lm. */ { struct fileOffsetSize *fosList = bigBedChunksMatchingName(bbi, index, name); struct bigBedInterval *intervalList = bigBedIntervalsMatchingName(bbi, fosList, bbWordMatchesName, fieldIx, name, lm); slFreeList(&fosList); return intervalList; } struct bigBedInterval *bigBedMultiNameQuery(struct bbiFile *bbi, struct bptFile *index, int fieldIx, char **names, int nameCount, struct lm *lm) /* Fetch all records matching any of the names. Using given index on given field. * Return list is allocated out of lm. */ { /* Set up name index and get list of chunks that match any of our names. */ struct fileOffsetSize *fosList = bigBedChunksMatchingNames(bbi, index, names, nameCount); /* Create hash of all names. */ struct hash *hash = newHash(0); int nameIx; for (nameIx=0; nameIx < nameCount; ++nameIx) hashAdd(hash, names[nameIx], NULL); /* Get intervals where name matches hash target. */ struct bigBedInterval *intervalList = bigBedIntervalsMatchingName(bbi, fosList, bbWordIsInHash, fieldIx, hash, lm); /* Clean up and return results. */ slFreeList(&fosList); hashFree(&hash); return intervalList; } void bigBedIntervalListToBedFile(struct bbiFile *bbi, struct bigBedInterval *intervalList, FILE *f) /* Write out big bed interval list to bed file, looking up chromosome. */ { char chromName[bbi->chromBpt->keySize+1]; int lastChromId = -1; struct bigBedInterval *interval; for (interval = intervalList; interval != NULL; interval = interval->next) { bbiCachedChromLookup(bbi, interval->chromId, lastChromId, chromName, sizeof(chromName)); lastChromId = interval->chromId; fprintf(f, "%s\t%u\t%u\t%s\n", chromName, interval->start, interval->end, interval->rest); } } int bigBedIntervalToRowLookupChrom(struct bigBedInterval *interval, struct bigBedInterval *prevInterval, struct bbiFile *bbi, char *chromBuf, int chromBufSize, char *startBuf, char *endBuf, char **row, int rowSize) /* Convert bigBedInterval to array of chars equivalend to what you'd get by parsing the * bed file. If you already know what chromosome the interval is on use the simpler * bigBedIntervalToRow. This one will look up the chromosome based on the chromId field * of the interval, which is relatively time consuming. To avoid doing this unnecessarily * pass in a non-NULL prevInterval, and if the chromId is the same on prevInterval as this, * it will avoid the lookup. The chromBufSize should be at greater or equal to * bbi->chromBpt->keySize+1. The startBuf and endBuf are used to hold the ascii representation of * start and end, and should be 16 bytes. Note that the interval->rest string will have zeroes * inserted as a side effect. Returns number of fields in row. */ { int lastChromId = (prevInterval == NULL ? -1 : prevInterval->chromId); bbiCachedChromLookup(bbi, interval->chromId, lastChromId, chromBuf, chromBufSize); return bigBedIntervalToRow(interval, chromBuf, startBuf, endBuf, row, rowSize); } char *bigBedAutoSqlText(struct bbiFile *bbi) /* Get autoSql text if any associated with file. Do a freeMem of this when done. */ { if (bbi->asOffset == 0) return NULL; struct udcFile *f = bbi->udc; udcSeek(f, bbi->asOffset); return udcReadStringAndZero(f); } struct asObject *bigBedAs(struct bbiFile *bbi) /* Get autoSql object definition if any associated with file. */ { if (bbi->asOffset == 0) return NULL; char *asText = bigBedAutoSqlText(bbi); struct asObject *as = asParseText(asText); freeMem(asText); return as; } struct asObject *bigBedAsOrDefault(struct bbiFile *bbi) // Get asObject associated with bigBed - if none exists in file make it up from field counts. { struct asObject *as = bigBedAs(bbi); if (as == NULL) as = asParseText(bedAsDef(bbi->definedFieldCount, bbi->fieldCount)); return as; } struct asObject *bigBedFileAsObjOrDefault(char *fileName) // Get asObject associated with bigBed file, or the default. { struct bbiFile *bbi = bigBedFileOpen(fileName); if (bbi) { struct asObject *as = bigBedAsOrDefault(bbi); bbiFileClose(&bbi); return as; } return NULL; } struct slName *bbFieldNames(struct bbiFile *bbi) /* Get list of fields in bigBed */ { if (!bbi) return NULL; struct asObject *as = bigBedAs(bbi); if (!as) return NULL; struct asColumn *col; struct slName *colNames = NULL; for (col = as->columnList; col; col = col->next) slNameAddHead(&colNames, col->name); asObjectFree(&as); slReverse(&colNames); return colNames; } int bbFieldIndex(struct bbiFile *bbi, char* fieldName) /* return the index of a given field */ { if (fieldName==NULL) return -1; struct asObject *as = bigBedAsOrDefault(bbi); if (as == NULL) return -1; // search for field name, return index if found struct asColumn *col = as->columnList; int ix = 0; for (;col != NULL;col=col->next, ix+=1) if (sameString(col->name, fieldName)) return ix; return -1; } int bbExtraFieldIndex(struct bbiFile *bbi, char* fieldName) /* return the index of a given extra field */ { if (fieldName==NULL) return 0; struct asObject *as = bigBedAsOrDefault(bbi); if (as == NULL) return 0; // search for field name, return index if found struct asColumn *col = as->columnList; int ix = 0; for (;col != NULL;col=col->next, ix+=1) if (sameString(col->name, fieldName)) return max(ix-3, 0); // never return a negative value return 0; } bits64 bigBedItemCount(struct bbiFile *bbi) /* Return total items in file. */ { udcSeek(bbi->udc, bbi->unzoomedDataOffset); return udcReadBits64(bbi->udc, bbi->isSwapped); } struct slName *bigBedListExtraIndexes(struct bbiFile *bbi) /* Return list of names of extra indexes beyond primary chrom:start-end one" */ { struct udcFile *udc = bbi->udc; boolean isSwapped = bbi->isSwapped; /* See if we have any extra indexes, and if so seek to there. */ bits64 offset = bbi->extraIndexListOffset; if (offset == 0) return NULL; udcSeek(udc, offset); /* Construct list of field that are being indexed. List is list of * field numbers within asObj. */ int i; struct slInt *intList = NULL, *intEl; for (i=0; i<bbi->extraIndexCount; ++i) { bits16 fieldCount; udcReadBits16(udc, isSwapped); // type fieldCount = udcReadBits16(udc, isSwapped); udcSeekCur(udc, sizeof(bits64)); // skip over fileOffset udcSeekCur(udc, 4); // skip over reserved bits if (fieldCount == 1) { bits16 fieldId = udcReadBits16(udc, isSwapped); udcSeekCur(udc, 2); // skip over reserved bits intEl = slIntNew(fieldId); slAddHead(&intList, intEl); } else { warn("Not yet understanding indexes on multiple fields at once."); internalErr(); } } /* Now have to make an asObject to find out name that corresponds to this field. */ struct asObject *as = bigBedAsOrDefault(bbi); /* Make list of field names out of list of field numbers */ struct slName *nameList = NULL; for (intEl = intList; intEl != NULL; intEl = intEl->next) { struct asColumn *col = slElementFromIx(as->columnList, intEl->val); if (col == NULL) { warn("Inconsistent bigBed file %s", bbi->fileName); internalErr(); } slNameAddHead(&nameList, col->name); } asObjectFree(&as); return nameList; } struct bptFile *bigBedOpenExtraIndex(struct bbiFile *bbi, char *fieldName, int *retFieldIx) /* Return index associated with fieldName. Aborts if no such index. Optionally return * index in a row of this field. */ { struct udcFile *udc = bbi->udc; boolean isSwapped = bbi->isSwapped; struct asObject *as = bigBedAsOrDefault(bbi); struct asColumn *col = asColumnFind(as, fieldName); if (col == NULL) errAbort("No field %s in %s", fieldName, bbi->fileName); int colIx = slIxFromElement(as->columnList, col); if (retFieldIx != NULL) *retFieldIx = colIx; asObjectFree(&as); /* See if we have any extra indexes, and if so seek to there. */ bits64 offset = bbi->extraIndexListOffset; if (offset == 0) errAbort("%s has no indexes", bbi->fileName); udcSeek(udc, offset); /* Go through each extra index and see if it's a match */ int i; for (i=0; i<bbi->extraIndexCount; ++i) { bits16 type = udcReadBits16(udc, isSwapped); bits16 fieldCount = udcReadBits16(udc, isSwapped); bits64 fileOffset = udcReadBits64(udc, isSwapped); udcSeekCur(udc, 4); // skip over reserved bits if (type != 0) { warn("Don't understand type %d", type); internalErr(); } if (fieldCount == 1) { bits16 fieldId = udcReadBits16(udc, isSwapped); udcSeekCur(udc, 2); // skip over reserved bits if (fieldId == colIx) { udcSeek(udc, fileOffset); struct bptFile *bpt = bptFileAttach(bbi->fileName, udc); return bpt; } } else { warn("Not yet understanding indexes on multiple fields at once."); internalErr(); } } errAbort("%s is not indexed in %s", fieldName, bbi->fileName); return NULL; }
146689.c
/* * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * * Copyright (c) 2014 Damien P. George * Copyright (c) 2015-2017 Paul Sokolovsky * * 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 "py/mpconfig.h" #if MICROPY_PY_USELECT_POSIX #if MICROPY_PY_USELECT #error "Can't have both MICROPY_PY_USELECT and MICROPY_PY_USELECT_POSIX." #endif #include <stdio.h> #include <errno.h> #include <poll.h> #include "py/runtime.h" #include "py/stream.h" #include "py/obj.h" #include "py/objlist.h" #include "py/objtuple.h" #include "py/mphal.h" #include "py/mpthread.h" #define DEBUG 0 #if MICROPY_PY_SOCKET extern const mp_obj_type_t mp_type_socket; #endif // Flags for poll() #define FLAG_ONESHOT (1) /// \class Poll - poll class typedef struct _mp_obj_poll_t { mp_obj_base_t base; unsigned short alloc; unsigned short len; struct pollfd *entries; mp_obj_t *obj_map; short iter_cnt; short iter_idx; int flags; // callee-owned tuple mp_obj_t ret_tuple; } mp_obj_poll_t; STATIC int get_fd(mp_obj_t fdlike) { if (mp_obj_is_obj(fdlike)) { const mp_stream_p_t *stream_p = mp_get_stream_raise(fdlike, MP_STREAM_OP_IOCTL); int err; mp_uint_t res = stream_p->ioctl(fdlike, MP_STREAM_GET_FILENO, 0, &err); if (res != MP_STREAM_ERROR) { return res; } } return mp_obj_get_int(fdlike); } /// \method register(obj[, eventmask]) STATIC mp_obj_t poll_register(size_t n_args, const mp_obj_t *args) { mp_obj_poll_t *self = MP_OBJ_TO_PTR(args[0]); bool is_fd = mp_obj_is_int(args[1]); int fd = get_fd(args[1]); mp_uint_t flags; if (n_args == 3) { flags = mp_obj_get_int(args[2]); } else { flags = POLLIN | POLLOUT; } struct pollfd *free_slot = NULL; struct pollfd *entry = self->entries; for (int i = 0; i < self->len; i++, entry++) { int entry_fd = entry->fd; if (entry_fd == fd) { entry->events = flags; return mp_const_false; } if (entry_fd == -1) { free_slot = entry; } } if (free_slot == NULL) { if (self->len >= self->alloc) { self->entries = m_renew(struct pollfd, self->entries, self->alloc, self->alloc + 4); if (self->obj_map) { self->obj_map = m_renew(mp_obj_t, self->obj_map, self->alloc, self->alloc + 4); } self->alloc += 4; } free_slot = &self->entries[self->len++]; } if (!is_fd) { if (self->obj_map == NULL) { self->obj_map = m_new0(mp_obj_t, self->alloc); } self->obj_map[free_slot - self->entries] = args[1]; } free_slot->fd = fd; free_slot->events = flags; free_slot->revents = 0; return mp_const_true; } MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(poll_register_obj, 2, 3, poll_register); /// \method unregister(obj) STATIC mp_obj_t poll_unregister(mp_obj_t self_in, mp_obj_t obj_in) { mp_obj_poll_t *self = MP_OBJ_TO_PTR(self_in); struct pollfd *entries = self->entries; int fd = get_fd(obj_in); for (int i = self->len - 1; i >= 0; i--) { if (entries->fd == fd) { entries->fd = -1; if (self->obj_map) { self->obj_map[entries - self->entries] = MP_OBJ_NULL; } break; } entries++; } // TODO raise KeyError if obj didn't exist in map return mp_const_none; } MP_DEFINE_CONST_FUN_OBJ_2(poll_unregister_obj, poll_unregister); /// \method modify(obj, eventmask) STATIC mp_obj_t poll_modify(mp_obj_t self_in, mp_obj_t obj_in, mp_obj_t eventmask_in) { mp_obj_poll_t *self = MP_OBJ_TO_PTR(self_in); struct pollfd *entries = self->entries; int fd = get_fd(obj_in); for (int i = self->len - 1; i >= 0; i--) { if (entries->fd == fd) { entries->events = mp_obj_get_int(eventmask_in); return mp_const_none; } entries++; } // obj doesn't exist in poller mp_raise_OSError(MP_ENOENT); } MP_DEFINE_CONST_FUN_OBJ_3(poll_modify_obj, poll_modify); STATIC int poll_poll_internal(size_t n_args, const mp_obj_t *args) { mp_obj_poll_t *self = MP_OBJ_TO_PTR(args[0]); // work out timeout (it's given already in ms) int timeout = -1; int flags = 0; if (n_args >= 2) { if (args[1] != mp_const_none) { mp_int_t timeout_i = mp_obj_get_int(args[1]); if (timeout_i >= 0) { timeout = timeout_i; } } if (n_args >= 3) { flags = mp_obj_get_int(args[2]); } } self->flags = flags; int n_ready; MP_HAL_RETRY_SYSCALL(n_ready, poll(self->entries, self->len, timeout), mp_raise_OSError(err)); return n_ready; } /// \method poll([timeout]) /// Timeout is in milliseconds. STATIC mp_obj_t poll_poll(size_t n_args, const mp_obj_t *args) { int n_ready = poll_poll_internal(n_args, args); if (n_ready == 0) { return mp_const_empty_tuple; } mp_obj_poll_t *self = MP_OBJ_TO_PTR(args[0]); mp_obj_list_t *ret_list = MP_OBJ_TO_PTR(mp_obj_new_list(n_ready, NULL)); int ret_i = 0; struct pollfd *entries = self->entries; for (int i = 0; i < self->len; i++, entries++) { if (entries->revents != 0) { mp_obj_tuple_t *t = MP_OBJ_TO_PTR(mp_obj_new_tuple(2, NULL)); // If there's an object stored, return it, otherwise raw fd if (self->obj_map && self->obj_map[i] != MP_OBJ_NULL) { t->items[0] = self->obj_map[i]; } else { t->items[0] = MP_OBJ_NEW_SMALL_INT(entries->fd); } t->items[1] = MP_OBJ_NEW_SMALL_INT(entries->revents); ret_list->items[ret_i++] = MP_OBJ_FROM_PTR(t); if (self->flags & FLAG_ONESHOT) { entries->events = 0; } } } return MP_OBJ_FROM_PTR(ret_list); } MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(poll_poll_obj, 1, 3, poll_poll); STATIC mp_obj_t poll_ipoll(size_t n_args, const mp_obj_t *args) { mp_obj_poll_t *self = MP_OBJ_TO_PTR(args[0]); if (self->ret_tuple == MP_OBJ_NULL) { self->ret_tuple = mp_obj_new_tuple(2, NULL); } int n_ready = poll_poll_internal(n_args, args); self->iter_cnt = n_ready; self->iter_idx = 0; return args[0]; } MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(poll_ipoll_obj, 1, 3, poll_ipoll); STATIC mp_obj_t poll_iternext(mp_obj_t self_in) { mp_obj_poll_t *self = MP_OBJ_TO_PTR(self_in); if (self->iter_cnt == 0) { return MP_OBJ_STOP_ITERATION; } self->iter_cnt--; struct pollfd *entries = self->entries + self->iter_idx; for (int i = self->iter_idx; i < self->len; i++, entries++) { self->iter_idx++; if (entries->revents != 0) { mp_obj_tuple_t *t = MP_OBJ_TO_PTR(self->ret_tuple); // If there's an object stored, return it, otherwise raw fd if (self->obj_map && self->obj_map[i] != MP_OBJ_NULL) { t->items[0] = self->obj_map[i]; } else { t->items[0] = MP_OBJ_NEW_SMALL_INT(entries->fd); } t->items[1] = MP_OBJ_NEW_SMALL_INT(entries->revents); if (self->flags & FLAG_ONESHOT) { entries->events = 0; } return MP_OBJ_FROM_PTR(t); } } assert(!"inconsistent number of poll active entries"); self->iter_cnt = 0; return MP_OBJ_STOP_ITERATION; } #if DEBUG STATIC mp_obj_t poll_dump(mp_obj_t self_in) { mp_obj_poll_t *self = MP_OBJ_TO_PTR(self_in); struct pollfd *entries = self->entries; for (int i = self->len - 1; i >= 0; i--) { printf("fd: %d ev: %x rev: %x", entries->fd, entries->events, entries->revents); if (self->obj_map) { printf(" obj: %p", self->obj_map[entries - self->entries]); } printf("\n"); entries++; } return mp_const_none; } MP_DEFINE_CONST_FUN_OBJ_1(poll_dump_obj, poll_dump); #endif STATIC const mp_rom_map_elem_t poll_locals_dict_table[] = { { MP_ROM_QSTR(MP_QSTR_register), MP_ROM_PTR(&poll_register_obj) }, { MP_ROM_QSTR(MP_QSTR_unregister), MP_ROM_PTR(&poll_unregister_obj) }, { MP_ROM_QSTR(MP_QSTR_modify), MP_ROM_PTR(&poll_modify_obj) }, { MP_ROM_QSTR(MP_QSTR_poll), MP_ROM_PTR(&poll_poll_obj) }, { MP_ROM_QSTR(MP_QSTR_ipoll), MP_ROM_PTR(&poll_ipoll_obj) }, #if DEBUG { MP_ROM_QSTR(MP_QSTR_dump), MP_ROM_PTR(&poll_dump_obj) }, #endif }; STATIC MP_DEFINE_CONST_DICT(poll_locals_dict, poll_locals_dict_table); STATIC const mp_obj_type_t mp_type_poll = { { &mp_type_type }, .name = MP_QSTR_poll, .getiter = mp_identity_getiter, .iternext = poll_iternext, .locals_dict = (void *)&poll_locals_dict, }; STATIC mp_obj_t select_poll(size_t n_args, const mp_obj_t *args) { int alloc = 4; if (n_args > 0) { alloc = mp_obj_get_int(args[0]); } mp_obj_poll_t *poll = mp_obj_malloc(mp_obj_poll_t, &mp_type_poll); poll->entries = m_new(struct pollfd, alloc); poll->alloc = alloc; poll->len = 0; poll->obj_map = NULL; poll->iter_cnt = 0; poll->ret_tuple = MP_OBJ_NULL; return MP_OBJ_FROM_PTR(poll); } MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(mp_select_poll_obj, 0, 1, select_poll); STATIC const mp_rom_map_elem_t mp_module_select_globals_table[] = { { MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_uselect) }, { MP_ROM_QSTR(MP_QSTR_poll), MP_ROM_PTR(&mp_select_poll_obj) }, { MP_ROM_QSTR(MP_QSTR_POLLIN), MP_ROM_INT(POLLIN) }, { MP_ROM_QSTR(MP_QSTR_POLLOUT), MP_ROM_INT(POLLOUT) }, { MP_ROM_QSTR(MP_QSTR_POLLERR), MP_ROM_INT(POLLERR) }, { MP_ROM_QSTR(MP_QSTR_POLLHUP), MP_ROM_INT(POLLHUP) }, }; STATIC MP_DEFINE_CONST_DICT(mp_module_select_globals, mp_module_select_globals_table); const mp_obj_module_t mp_module_uselect = { .base = { &mp_type_module }, .globals = (mp_obj_dict_t *)&mp_module_select_globals, }; #endif // MICROPY_PY_USELECT_POSIX
649182.c
/* PF: Compiler and helper functions. The code in this file is partitioned in two classes: px_ non-linear expression primitives _px_ misc functions (not respecting px_ nor pf_ API) Note that the px_ functions are *NOT LINEAR*. They respect the API of the EX language: a mostly functional dynamically typed expression language using the C-stack. The linear stack operations carry the pf_ prefix and are defined separately in the pf.c file. The compiler is written in terms of nonlinear functions because: - The code graph it produces is nonlinear (loops + procedure reuse) - C's lexical scope meshes better with an expression language than a stack language. - It will make the interface with SC simpler, which is also written in EX. - I find writing a compiler (a tree/graph processor) in a combinator language needs too much cleverness. Due to reliance on random access, data structure translation begs for lexical scope, and is facilitated by pattern matching. */ #include <stdlib.h> #include <sys/types.h> #include <unistd.h> #include <signal.h> #include <pf/pf.h> #include <px/px.h> #include <leaf_posix/channel.h> /* Leaf object wrappers. */ //DEF_RC_TYPE(port) //DEF_RC_TYPE(bytes) //DEF_RC_TYPE(inexact) //DEF_RC_TYPE(channel) //DEF_RC_TYPE(ck) /* TOOLS+DATA */ _ px_abort(pf *pf, _ tag, _ arg) { return RAISE_ERROR(tag, arg); } _ _px_top(pf *pf) { if (unlikely (NIL == pf->p)) px_error_underflow(pf); return _CAR(pf->p); } _ _px_second(pf *pf) { if (unlikely (NIL == pf->p)) px_error_underflow(pf); _ more = _CDR(pf->p); if (unlikely (NIL == more)) px_error_underflow(pf); return _CAR(more); } _ px_error_underflow(pf *pf) { return px_abort(pf, pf->s_underflow, VOID); } _ _px_leaf_to_object(pf *pf, leaf_object *l) { return const_to_object(l); } leaf_object* _px_object_to_leaf(pf *pf, object ob) { void *x = object_to_const(NULL, ob); if (!const_struct(x)) return NULL; // all other constants are pointers to leaf objects. return x; } void* _px_ref_struct(pf *pf, object ob, void *type) { // FIXME: should this unpack LIN? return _px_object_to_leaf(pf, ob); } _ _px_make_port(pf *pf, FILE *f, const char *name) { return _px_leaf_to_object(pf, (leaf_object*)port_file_new(stdout, name)); } _ _px_make_string(pf *pf, const char *name) { return _px_leaf_to_object(pf, (leaf_object*)bytes_from_cstring(name)); } _ _px_make_qstring(pf *pf, const char *name) { return _px_leaf_to_object(pf, (leaf_object*)bytes_from_qcstring(name)); } _ _px_make_symbol(pf *pf, const char *str){ return const_to_object(symbol_from_cstring(str)); } _ px_display(pf *pf, _ ob) { bytes *b = CAST(bytes, ob); port_write(_px_port(pf), b->bytes, strlen(b->bytes)); return VOID; } /* MEMORY MANAGEMENT The stack machine's inner data model consists of constants (permanent data), refcount managed abstact leaf objects and a linear tree of cons cells. The outer memory is a classic GC managed graph. RC-managed data traversing the linear->graph boundary needs to be properly wrapped to synchronize the two memory managers. Graph data can be treated as constants in the linear memory, as the linear memory tree is part of the GC roots. Implementation: Linear lists are tagged differently from ordinary cons cells. However, the *unsafe* macros _CAR _CDR ... can still access them, since their layout is the same. They should always be constructed through LINEAR_CONS, not LCONS. The former uses the freelist, while the latter allocates a cell from GC memory. */ /* Allocate/reuse cell. */ _ px_linear_cons(pf *pf, _ car, _ cdr) { _px_need_free(pf); _ rv = pf->freelist; pf->freelist = _CDR(pf->freelist); _CAR(rv) = car; _CDR(rv) = cdr; return rv; } _ px_linear_next(pf *pf, _ car, _ cdr) { _ ob = px_linear_cons(pf, car, cdr); vector *v = object_to_vector(EX, ob); vector_reset_flags(v, TAG_LNEXT); return ob; } _ px_linear_data(pf *pf, _ car, _ cdr) { _ ob = px_linear_cons(pf, car, cdr); vector *v = object_to_vector(EX, ob); vector_reset_flags(v, TAG_LDATA); return ob; } /* Unlink will RC manage objects, and move pairs to the freelist. */ static _ _px_unlink_pop(pf *pf, _ lst) { _ ob = MOVE(_CAR(lst), VOID); _px_unlink(pf, ob); _px_to_free(pf, &lst); return lst; } void _px_unlink(pf* pf, _ ob) { next: /* Lists: recurse. */ if (object_to_lpair(EX, ob) || object_to_ldata(EX, ob) || object_to_lnext(EX, ob)) { ob = _px_unlink_pop(pf, ob); goto next; } else { leaf_object *l; if ((l = _px_object_to_leaf(pf, ob))) leaf_free(l); } } /* Link will RC++ objects and recursively copy pair structures, using pairs from the freelist.. */ _ _px_link(pf *pf, _ ob) { leaf_object *l; if ((l = _px_object_to_leaf(pf, ob))) { leaf_dup(l); return ob; } pair *p; if ((p = object_to_lpair(EX, ob))) { return LINEAR_CONS(_px_link(pf, p->car), _px_link(pf, p->cdr)); } else if ((p = object_to_lnext(EX, ob))) { return LINEAR_NEXT(_px_link(pf, p->car), _px_link(pf, p->cdr)); } else if ((p = object_to_ldata(EX, ob))) { return LINEAR_DATA(_px_link(pf, p->car), _px_link(pf, p->cdr)); } else { return ob; } } /* Whenever data is exported to the GC-managed side (graph memory or outer memory), CONS cells are copied and ref counts are incremented on leaf objects. Additionally, leaf objects need to be wrapped in a UNIQ object to ensure that each RC++ in copy to graph corresponds to one RC-- per wrapper on GC */ static void _gc_unlink(_ ob, pf *pf) { _px_unlink(pf, ob); } static void *unlink_fin = _gc_unlink; _ px_box(pf *pf, _ ob) { return gc_make_tagged(GC, TAG_BOX, 2, fin_to_object((void*)(&unlink_fin)), ob); } _ px_uniq(pf *pf, _ ob) { return gc_make_tagged(GC, TAG_UNIQ, 2, fin_to_object((void*)(&unlink_fin)), ob); } _ px_copy_to_graph(pf *pf, _ ob) { pair *p; leaf_object *l; if ((l = _px_object_to_leaf(pf, ob))) { /* Don't wrap these non-managed constants. Compiler expects them to not be wrapped. */ if ((l->__type == prim_type()) || (l->__type == symbol_type())) { return ob; } else { _px_link(pf, ob); return UNIQ(ob); } } /* Recursively copy the tree. */ else if ((p = object_to_lpair(EX, ob))) { return CONS(COPY_TO_GRAPH(p->car), COPY_TO_GRAPH(p->cdr)); } /* FIXME: Seq code contination frames are currently not representable outside the VM. */ else if ((p = object_to_lnext(EX, ob)) || (p = object_to_ldata(EX, ob))) { _ex_printf(EX, "WARNING: lnext/ldata -> nonlinear pair conversion.\n"); return CONS(COPY_TO_GRAPH(p->car), COPY_TO_GRAPH(p->cdr)); } else return ob; } _ px_unpack_uniq(pf *pf, _ ob) { uniq *l; if ((l = object_to_uniq(EX, ob))) { return l->object; } else { return ob; } } _ px_copy_from_graph(pf *pf, _ ob) { pair *p; /* Unwrap UNIQ objects. */ ob = px_unpack_uniq(pf, ob); /* Leaf object */ if (_px_object_to_leaf(pf, ob)) { return _px_link(pf, px_unpack_uniq(pf, ob)); } /* CONS cells: recursive copy into linear cells. */ else if ((p = object_to_pair(EX, ob))) { return LINEAR_CONS(COPY_FROM_GRAPH(p->car), COPY_FROM_GRAPH(p->cdr)); } /* Anything else is treated as constant. */ else return ob; } /* EXPRESSIONS It's simpler to factor out primitives as N -> 1 expressions, and then couple them (automatically?) to the parameter stack. This uses the same naming convention as sc_ and ex_, namely px_ : N x object -> object _px_ : any other operation on *pf */ port *_px_port(pf *pf) { return object_to_port(EX, pf->output); } /* Code _printing_. tries to guess what form of quotation the object came from. The code is largely trial and error, trying to handle all the corner cases. See also the quote, seq and prim cases in px_write() */ /* Print as part of code sequence. */ _ px_write_name_or_quotation(pf *pf, _ ob) { quote *q; uniq *l; /* Try to resolve the name. */ _ sym = UNFIND(pf->dict, ob); /* Print name if it has one. */ if (FALSE != sym) return px_write(pf, sym); /* If the object was a data quotation that's not registered as code in the dictionary, print it as an inline quotation.*/ if ((q = object_to_quote(EX, ob))) { if ((object_to_seq(EX, q->object)) || (object_to_quote(EX, q->object)) || (object_to_prim(EX, q->object))) { return px_write(pf, q->object); } else { _ex_printf(EX, "'"); /* Don't print the UNIQ wrapper. */ if ((l = object_to_uniq(EX, q->object))) { return px_write(pf, l->object); } else { return px_write(pf, q->object); } } } /* Otherwise indicate that there the object has no name. */ return _ex_printf(EX, "_"); } const char *CL = "["; const char *CR = "]"; _ px_write(pf *pf, _ ob) { void *x; if ((x = object_to_box(EX, ob))) { return _ex_write_vector(EX, "box", object_to_vector(EX, ob)); } else if ((x = object_to_uniq(EX, ob))) { return _ex_write_vector(EX, "uniq", object_to_vector(EX, ob)); } /* SEQ and QUOTE are decompiled. Use square brackets to distinguish from lists. */ else if ((x = object_to_seq(EX, ob))) { long max = 10; _ex_printf(EX, CL); for(;;) { seq *s = (seq*)x; px_write_name_or_quotation(pf, s->now); _ex_printf(EX, " "); ob = s->next; if (!(x = object_to_seq(EX, ob))) { px_write_name_or_quotation(pf, s->next); _ex_printf(EX, CR); return VOID; } /* If the tail has a name, print that instead. */ _ sym = UNFIND(pf->dict, ob); if (FALSE != sym) { px_write(pf, sym); return _ex_printf(EX, CR); } /* Prevent loops from generating too much output. */ if (!(--max)) { _ex_printf(EX, "..."); return _ex_printf(EX, CR); } } } /* Primitive or quoted datum. */ else if ((x = object_to_quote(EX, ob)) || (x = object_to_prim(EX, ob))) { // quote *q = (quote*)x; /* Print it as a singleton. */ _ex_printf(EX, CL); px_write_name_or_quotation(pf, ob); return _ex_printf(EX, CR); } else if (HALT == ob) { return _ex_printf(EX, "#halt"); } else if (pf->ip_prompt_tag == ob) { return _ex_printf(EX, "#prompt"); } return _ex_write(EX, ob); } /* COMPILER */ /* Compilation is factored into several steps. The main distinction is again to perform the global side effects (update of the toplevel environement) _after_ all allocation has finished. These are the passes: 1. Create skeleton environment. 2. Translate s-expr -> SEQ | PRIM | QUOTE 3. Resolve (remaining) undefined references. 4. Patch toplevel environment. */ /* Convert definition list of (name . src) symbolic code pairs to a compiled dictionary of (name . code) pairs, using E_top for undefined references. */ _ px_skeleton_entry(pf *pf, _ code) { return CONS(CAR(code), VOID); } _ px_compile_defs(pf *pf, _ E_top, _ defs) { /* Create skeleton dictionary. */ _ E_local = _ex_map1_prim(EX, (ex_1)px_skeleton_entry, defs); _ penv = E_local; _ pdefs = defs; /* Translate to code graph. */ while (NIL != penv) { _ entry = CAR(penv); _ src = CDAR(pdefs); _CDR(entry) = px_compile_program_env(pf, E_top, E_local, src); penv = CDR(penv); pdefs = CDR(pdefs); } /* Resolve all references. */ px_bang_resolve(pf, E_top, E_local); // FIXME: /* Check degenerate loops */ /* Snap pointers. */ return E_local; } /* Compile anonymous symbolic code to code graph. */ _ px_quote(pf *pf, _ data) { return STRUCT(TAG_QUOTE, 1, data); } _ px_seq(pf *pf, _ sub, _ next) { return STRUCT(TAG_SEQ, 2, sub, next); } /* This one is insidious.. The input code is always nonlinear, but what if it already contains wrapped linear data? This needs a properly specified quote/unquote semantics. Essentially, this can only receive atoms that can appear in *source code*, so we only translate nonlinear lists to linear ones. */ _ px_quote_source_datum(pf *pf, _ datum) { if ((object_to_pair(EX, datum))) { return QUOTE(COPY_FROM_GRAPH(datum)); } else { return QUOTE(datum); } } _ px_compile_program_env(pf *pf, _ E_top, _ E_local, _ src) { _ rv; _ *cursor = &rv; if (NIL == src) return pf->ip_nop; /* Compile with proper tail calls. */ for(;;) { _ compiled, datum = CAR(src); /* Quoted empty program. */ if (NIL == datum) { compiled = QUOTE(pf->ip_nop); } else if (TRUE == IS_LIST(datum)) { /* Special Form. */ _ tag = _CAR(datum); if (tag == pf->s_quote) { compiled = QUOTE_SOURCE_DATUM(_CADR(datum)); } else if (tag == pf->s_var) { _ val = (NIL == _CDR(datum) ? VOID : _CADR(datum)); compiled = QUOTE(BOX(COPY_FROM_GRAPH(val))); } /* Quoted subprogram. */ else { compiled = QUOTE // Doesn't need wrapping. (COMPILE_PROGRAM_ENV(E_top, E_local, datum)); } } /* If possible, dereference. In case we're compiling non-recursive code, this first pass will produce fully linked code. */ else if (TRUE == IS_SYMBOL(datum)) { _ val = FIND2(E_local, E_top, datum); if (FALSE == val) ERROR("undefined", datum); if (VOID != val) compiled = val; else compiled = datum; } /* Quote literal data. */ else { compiled = QUOTE_SOURCE_DATUM(datum); } /* Return if this was the last one. */ if (NIL == CDR(src)) { *cursor = compiled; return rv; } /* Allocate sequence if there's more to come. */ else { _ seq = SEQ(compiled, VOID); *cursor = seq; cursor = &(object_to_seq(EX, seq)->next); src = CDR(src); } } } _ px_compile_program(pf *pf, _ src) { return px_compile_program_env(pf, NIL, pf->dict, src); } _ px_make_loop(pf *pf, _ code) { _ ob = SEQ(code, VOID); object_to_seq(EX, ob)->next = ob; return ob; } /* Walk the code, eliminating symbolic references where possible. Note: this only traverses the part of the code graph that's the result of a compilation. */ _ _px_resolve_sub(pf *pf, _ E_top, _ E_local, _ *cursor); _ _px_resolve_non_seq(pf *pf, _ E_top, _ E_local, _ *cursor) { _ sub = *cursor; quote *q; if ((q = object_to_quote(EX, sub))) { return _px_resolve_sub(pf, E_top, E_local, &(q->object)); } if (IS_SYMBOL(sub)) { _ val = FIND2(E_local, E_top, sub); if (FALSE != val) { *cursor = val; return ONE; } } return ZERO; } /* Resolve a flat subroutine without recursing into the call graph. */ _ _px_resolve_sub(pf *pf, _ E_top, _ E_local, _ *cursor) { _ derefs = ZERO; for(;;) { seq* s; _ sub = *cursor; /* Sequence, resolve NOW, then continue. */ if ((s = object_to_seq(EX, sub))) { _ dr = _px_resolve_non_seq(pf, E_top, E_local, &s->now); derefs = ADD(derefs, dr); cursor = &s->next; } /* Other: resolve and return. */ else { _ dr = _px_resolve_non_seq(pf, E_top, E_local, cursor); return ADD(derefs, dr); } } } _ px_bang_resolve(pf *pf, _ E_top, _ E_local) { _ todo = E_local; _ derefs = ZERO; while (NIL != todo) { _ *cursor = &_CDAR(todo); derefs = ADD(derefs, _px_resolve_sub(pf, E_top, E_local, cursor)); todo = CDR(todo); } return derefs; } _ px_define(pf *pf, _ defs) { /* Create an isolated environment. */ _ E = px_compile_defs(pf, pf->dict, defs); /* Patch it into the global one. */ while (NIL != E) { _ var = _CAAR(E); _ val = _CDAR(E); //POST_TAG("define",var); pf->dict = ENV_DEF(pf->dict, var, val); E = _CDR(E); } // _PRINT_DICT(); return VOID; } /* Linear code serves as a substrate for any form of code constructed linearly at run-time. This includes continuations, partial applications and code compositions / concatenations. Currently linear code is represented by 2 tags: NEXT and DATA */ _ px_bang_linear_compose(pf *pf, _ partial, _ full) { _ *x = &partial; /* Wind to end. */ while (object_to_ldata(EX, *x) || object_to_lnext(EX, *x)) { x = &(_CDR(*x)); } *x = full; return partial; } _ px_error_undefined(pf *pf, _ var) { return ERROR("undefined", var); } /* Converting data that is passed through the exception handlers to linear form needs some care. The following constraints are necessary: - All _linear_ data needs to be reachable from the machine state _at all times_. C stack can only contain access pointers into this data structure. - Therefore, all _linear_ data that is referenced through the exception mechanism needs to be _linked_ because it is already residing somehwere else. - Nonlinear data that passes through the exception mechanism can safely be treated as a constant. */ _ px_linearize_exception(pf *pf, _ ob) { return _px_link(pf, ob); }
539627.c
/* +----------------------------------------------------------------------+ | 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: | | http://www.php.net/license/3_01.txt | | If you did not receive a copy of the PHP license and are unable to | | obtain it through the world-wide-web, please send a note to | | license@php.net so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Author: Jim Winstead <jimw@php.net> | +----------------------------------------------------------------------+ */ #include "php.h" #include "fopen_wrappers.h" #include "php_globals.h" #include <stdlib.h> #include <sys/stat.h> #include <string.h> #include <errno.h> #include <ctype.h> #include <time.h> #if HAVE_UNISTD_H # include <unistd.h> #endif #if HAVE_SYS_PARAM_H # include <sys/param.h> #endif #if HAVE_SYS_VFS_H # include <sys/vfs.h> #endif #ifdef OS2 # define INCL_DOS # include <os2.h> #endif #if defined(HAVE_SYS_STATVFS_H) && defined(HAVE_STATVFS) # include <sys/statvfs.h> #elif defined(HAVE_SYS_STATFS_H) && defined(HAVE_STATFS) # include <sys/statfs.h> #elif defined(HAVE_SYS_MOUNT_H) && defined(HAVE_STATFS) # include <sys/mount.h> #endif #if HAVE_PWD_H # ifdef PHP_WIN32 # include "win32/pwd.h" # else # include <pwd.h> # endif #endif #if HAVE_GRP_H # ifdef PHP_WIN32 # include "win32/grp.h" # else # include <grp.h> # endif #endif #if HAVE_UTIME # ifdef PHP_WIN32 # include <sys/utime.h> # else # include <utime.h> # endif #endif #ifdef PHP_WIN32 #include "win32/winutil.h" #endif #include "basic_functions.h" #include "php_filestat.h" PHP_RINIT_FUNCTION(filestat) /* {{{ */ { BG(CurrentStatFile)=NULL; BG(CurrentLStatFile)=NULL; return SUCCESS; } /* }}} */ PHP_RSHUTDOWN_FUNCTION(filestat) /* {{{ */ { if (BG(CurrentStatFile)) { efree (BG(CurrentStatFile)); BG(CurrentStatFile) = NULL; } if (BG(CurrentLStatFile)) { efree (BG(CurrentLStatFile)); BG(CurrentLStatFile) = NULL; } return SUCCESS; } /* }}} */ static int php_disk_total_space(char *path, double *space) /* {{{ */ #if defined(WINDOWS) /* {{{ */ { ULARGE_INTEGER FreeBytesAvailableToCaller; ULARGE_INTEGER TotalNumberOfBytes; ULARGE_INTEGER TotalNumberOfFreeBytes; PHP_WIN32_IOUTIL_INIT_W(path) if (GetDiskFreeSpaceExW(pathw, &FreeBytesAvailableToCaller, &TotalNumberOfBytes, &TotalNumberOfFreeBytes) == 0) { char *err = php_win_err(); php_error_docref(NULL, E_WARNING, "%s", err); php_win_err_free(err); PHP_WIN32_IOUTIL_CLEANUP_W() return FAILURE; } /* i know - this is ugly, but i works <thies@thieso.net> */ *space = TotalNumberOfBytes.HighPart * (double) (((zend_ulong)1) << 31) * 2.0 + TotalNumberOfBytes.LowPart; PHP_WIN32_IOUTIL_CLEANUP_W() return SUCCESS; } /* }}} */ #elif defined(OS2) /* {{{ */ { double bytestotal = 0; FSALLOCATE fsinfo; char drive = path[0] & 95; if (DosQueryFSInfo( drive ? drive - 64 : 0, FSIL_ALLOC, &fsinfo, sizeof( fsinfo ) ) == 0) { bytestotal = (double)fsinfo.cbSector * fsinfo.cSectorUnit * fsinfo.cUnit; *space = bytestotal; return SUCCESS; } return FAILURE; } /* }}} */ #else /* {{{ if !defined(OS2) && !defined(WINDOWS) */ { double bytestotal = 0; #if defined(HAVE_SYS_STATVFS_H) && defined(HAVE_STATVFS) struct statvfs buf; #elif (defined(HAVE_SYS_STATFS_H) || defined(HAVE_SYS_MOUNT_H)) && defined(HAVE_STATFS) struct statfs buf; #endif #if defined(HAVE_SYS_STATVFS_H) && defined(HAVE_STATVFS) if (statvfs(path, &buf)) { php_error_docref(NULL, E_WARNING, "%s", strerror(errno)); return FAILURE; } if (buf.f_frsize) { bytestotal = (((double)buf.f_blocks) * ((double)buf.f_frsize)); } else { bytestotal = (((double)buf.f_blocks) * ((double)buf.f_bsize)); } #elif (defined(HAVE_SYS_STATFS_H) || defined(HAVE_SYS_MOUNT_H)) && defined(HAVE_STATFS) if (statfs(path, &buf)) { php_error_docref(NULL, E_WARNING, "%s", strerror(errno)); return FAILURE; } bytestotal = (((double)buf.f_bsize) * ((double)buf.f_blocks)); #endif *space = bytestotal; return SUCCESS; } #endif /* }}} */ /* }}} */ /* {{{ proto float|false disk_total_space(string path) Get total disk space for filesystem that path is on */ PHP_FUNCTION(disk_total_space) { double bytestotal; char *path; size_t path_len; ZEND_PARSE_PARAMETERS_START(1, 1) Z_PARAM_PATH(path, path_len) ZEND_PARSE_PARAMETERS_END(); if (php_check_open_basedir(path)) { RETURN_FALSE; } if (php_disk_total_space(path, &bytestotal) == SUCCESS) { RETURN_DOUBLE(bytestotal); } RETURN_FALSE; } /* }}} */ static int php_disk_free_space(char *path, double *space) /* {{{ */ #if defined(WINDOWS) /* {{{ */ { ULARGE_INTEGER FreeBytesAvailableToCaller; ULARGE_INTEGER TotalNumberOfBytes; ULARGE_INTEGER TotalNumberOfFreeBytes; PHP_WIN32_IOUTIL_INIT_W(path) if (GetDiskFreeSpaceExW(pathw, &FreeBytesAvailableToCaller, &TotalNumberOfBytes, &TotalNumberOfFreeBytes) == 0) { char *err = php_win_err(); php_error_docref(NULL, E_WARNING, "%s", err); php_win_err_free(err); PHP_WIN32_IOUTIL_CLEANUP_W() return FAILURE; } *space = FreeBytesAvailableToCaller.HighPart * (double) (1ULL << 32) + FreeBytesAvailableToCaller.LowPart; PHP_WIN32_IOUTIL_CLEANUP_W() return SUCCESS; } /* }}} */ #elif defined(OS2) /* {{{ */ { double bytesfree = 0; FSALLOCATE fsinfo; char drive = path[0] & 95; if (DosQueryFSInfo( drive ? drive - 64 : 0, FSIL_ALLOC, &fsinfo, sizeof( fsinfo ) ) == 0) { bytesfree = (double)fsinfo.cbSector * fsinfo.cSectorUnit * fsinfo.cUnitAvail; *space = bytesfree; return SUCCESS; } return FAILURE; } /* }}} */ #else /* {{{ if !defined(OS2) && !defined(WINDOWS) */ { double bytesfree = 0; #if defined(HAVE_SYS_STATVFS_H) && defined(HAVE_STATVFS) struct statvfs buf; #elif (defined(HAVE_SYS_STATFS_H) || defined(HAVE_SYS_MOUNT_H)) && defined(HAVE_STATFS) struct statfs buf; #endif #if defined(HAVE_SYS_STATVFS_H) && defined(HAVE_STATVFS) if (statvfs(path, &buf)) { php_error_docref(NULL, E_WARNING, "%s", strerror(errno)); return FAILURE; } if (buf.f_frsize) { bytesfree = (((double)buf.f_bavail) * ((double)buf.f_frsize)); } else { bytesfree = (((double)buf.f_bavail) * ((double)buf.f_bsize)); } #elif (defined(HAVE_SYS_STATFS_H) || defined(HAVE_SYS_MOUNT_H)) && defined(HAVE_STATFS) if (statfs(path, &buf)) { php_error_docref(NULL, E_WARNING, "%s", strerror(errno)); return FAILURE; } bytesfree = (((double)buf.f_bsize) * ((double)buf.f_bavail)); #endif *space = bytesfree; return SUCCESS; } #endif /* }}} */ /* }}} */ /* {{{ proto float|false disk_free_space(string path) Get free disk space for filesystem that path is on */ PHP_FUNCTION(disk_free_space) { double bytesfree; char *path; size_t path_len; ZEND_PARSE_PARAMETERS_START(1, 1) Z_PARAM_PATH(path, path_len) ZEND_PARSE_PARAMETERS_END(); if (php_check_open_basedir(path)) { RETURN_FALSE; } if (php_disk_free_space(path, &bytesfree) == SUCCESS) { RETURN_DOUBLE(bytesfree); } RETURN_FALSE; } /* }}} */ #ifndef PHP_WIN32 PHPAPI int php_get_gid_by_name(const char *name, gid_t *gid) { #if defined(ZTS) && defined(HAVE_GETGRNAM_R) && defined(_SC_GETGR_R_SIZE_MAX) struct group gr; struct group *retgrptr; long grbuflen = sysconf(_SC_GETGR_R_SIZE_MAX); char *grbuf; if (grbuflen < 1) { return FAILURE; } grbuf = emalloc(grbuflen); if (getgrnam_r(name, &gr, grbuf, grbuflen, &retgrptr) != 0 || retgrptr == NULL) { efree(grbuf); return FAILURE; } efree(grbuf); *gid = gr.gr_gid; #else struct group *gr = getgrnam(name); if (!gr) { return FAILURE; } *gid = gr->gr_gid; #endif return SUCCESS; } #endif static void php_do_chgrp(INTERNAL_FUNCTION_PARAMETERS, int do_lchgrp) /* {{{ */ { char *filename; size_t filename_len; zval *group; #if !defined(WINDOWS) gid_t gid; int ret; #endif php_stream_wrapper *wrapper; ZEND_PARSE_PARAMETERS_START(2, 2) Z_PARAM_PATH(filename, filename_len) Z_PARAM_ZVAL(group) ZEND_PARSE_PARAMETERS_END(); wrapper = php_stream_locate_url_wrapper(filename, NULL, 0); if(wrapper != &php_plain_files_wrapper || strncasecmp("file://", filename, 7) == 0) { if(wrapper && wrapper->wops->stream_metadata) { int option; void *value; if (Z_TYPE_P(group) == IS_LONG) { option = PHP_STREAM_META_GROUP; value = &Z_LVAL_P(group); } else if (Z_TYPE_P(group) == IS_STRING) { option = PHP_STREAM_META_GROUP_NAME; value = Z_STRVAL_P(group); } else { zend_type_error("Parameter 2 should be string or int, %s given", zend_zval_type_name(group)); return; } if(wrapper->wops->stream_metadata(wrapper, filename, option, value, NULL)) { RETURN_TRUE; } else { RETURN_FALSE; } } else { #if !defined(WINDOWS) /* On Windows, we expect regular chgrp to fail silently by default */ php_error_docref(NULL, E_WARNING, "Can not call chgrp() for a non-standard stream"); #endif RETURN_FALSE; } } #if defined(WINDOWS) /* We have no native chgrp on Windows, nothing left to do if stream doesn't have own implementation */ RETURN_FALSE; #else if (Z_TYPE_P(group) == IS_LONG) { gid = (gid_t)Z_LVAL_P(group); } else if (Z_TYPE_P(group) == IS_STRING) { if(php_get_gid_by_name(Z_STRVAL_P(group), &gid) != SUCCESS) { php_error_docref(NULL, E_WARNING, "Unable to find gid for %s", Z_STRVAL_P(group)); RETURN_FALSE; } } else { zend_type_error("Parameter 2 should be string or int, %s given", zend_zval_type_name(group)); return; } /* Check the basedir */ if (php_check_open_basedir(filename)) { RETURN_FALSE; } if (do_lchgrp) { #if HAVE_LCHOWN ret = VCWD_LCHOWN(filename, -1, gid); #endif } else { ret = VCWD_CHOWN(filename, -1, gid); } if (ret == -1) { php_error_docref(NULL, E_WARNING, "%s", strerror(errno)); RETURN_FALSE; } RETURN_TRUE; #endif } /* }}} */ /* {{{ proto bool chgrp(string filename, mixed group) Change file group */ PHP_FUNCTION(chgrp) { php_do_chgrp(INTERNAL_FUNCTION_PARAM_PASSTHRU, 0); } /* }}} */ /* {{{ proto bool lchgrp(string filename, mixed group) Change symlink group */ #if HAVE_LCHOWN PHP_FUNCTION(lchgrp) { # if !defined(WINDOWS) php_do_chgrp(INTERNAL_FUNCTION_PARAM_PASSTHRU, 1); # else RETURN_FALSE; # endif } #endif /* }}} */ #ifndef PHP_WIN32 PHPAPI uid_t php_get_uid_by_name(const char *name, uid_t *uid) { #if defined(ZTS) && defined(_SC_GETPW_R_SIZE_MAX) && defined(HAVE_GETPWNAM_R) struct passwd pw; struct passwd *retpwptr = NULL; long pwbuflen = sysconf(_SC_GETPW_R_SIZE_MAX); char *pwbuf; if (pwbuflen < 1) { return FAILURE; } pwbuf = emalloc(pwbuflen); if (getpwnam_r(name, &pw, pwbuf, pwbuflen, &retpwptr) != 0 || retpwptr == NULL) { efree(pwbuf); return FAILURE; } efree(pwbuf); *uid = pw.pw_uid; #else struct passwd *pw = getpwnam(name); if (!pw) { return FAILURE; } *uid = pw->pw_uid; #endif return SUCCESS; } #endif static void php_do_chown(INTERNAL_FUNCTION_PARAMETERS, int do_lchown) /* {{{ */ { char *filename; size_t filename_len; zval *user; #if !defined(WINDOWS) uid_t uid; int ret; #endif php_stream_wrapper *wrapper; ZEND_PARSE_PARAMETERS_START(2, 2) Z_PARAM_PATH(filename, filename_len) Z_PARAM_ZVAL(user) ZEND_PARSE_PARAMETERS_END(); wrapper = php_stream_locate_url_wrapper(filename, NULL, 0); if(wrapper != &php_plain_files_wrapper || strncasecmp("file://", filename, 7) == 0) { if(wrapper && wrapper->wops->stream_metadata) { int option; void *value; if (Z_TYPE_P(user) == IS_LONG) { option = PHP_STREAM_META_OWNER; value = &Z_LVAL_P(user); } else if (Z_TYPE_P(user) == IS_STRING) { option = PHP_STREAM_META_OWNER_NAME; value = Z_STRVAL_P(user); } else { php_error_docref(NULL, E_WARNING, "parameter 2 should be string or int, %s given", zend_zval_type_name(user)); RETURN_FALSE; } if(wrapper->wops->stream_metadata(wrapper, filename, option, value, NULL)) { RETURN_TRUE; } else { RETURN_FALSE; } } else { #if !defined(WINDOWS) /* On Windows, we expect regular chown to fail silently by default */ php_error_docref(NULL, E_WARNING, "Can not call chown() for a non-standard stream"); #endif RETURN_FALSE; } } #if defined(WINDOWS) /* We have no native chown on Windows, nothing left to do if stream doesn't have own implementation */ RETURN_FALSE; #else if (Z_TYPE_P(user) == IS_LONG) { uid = (uid_t)Z_LVAL_P(user); } else if (Z_TYPE_P(user) == IS_STRING) { if(php_get_uid_by_name(Z_STRVAL_P(user), &uid) != SUCCESS) { php_error_docref(NULL, E_WARNING, "Unable to find uid for %s", Z_STRVAL_P(user)); RETURN_FALSE; } } else { php_error_docref(NULL, E_WARNING, "parameter 2 should be string or int, %s given", zend_zval_type_name(user)); RETURN_FALSE; } /* Check the basedir */ if (php_check_open_basedir(filename)) { RETURN_FALSE; } if (do_lchown) { #if HAVE_LCHOWN ret = VCWD_LCHOWN(filename, uid, -1); #endif } else { ret = VCWD_CHOWN(filename, uid, -1); } if (ret == -1) { php_error_docref(NULL, E_WARNING, "%s", strerror(errno)); RETURN_FALSE; } RETURN_TRUE; #endif } /* }}} */ /* {{{ proto bool chown(string filename, mixed user) Change file owner */ PHP_FUNCTION(chown) { php_do_chown(INTERNAL_FUNCTION_PARAM_PASSTHRU, 0); } /* }}} */ /* {{{ proto bool chown(string filename, mixed user) Change file owner */ #if HAVE_LCHOWN PHP_FUNCTION(lchown) { # if !defined(WINDOWS) RETVAL_TRUE; php_do_chown(INTERNAL_FUNCTION_PARAM_PASSTHRU, 1); # else RETURN_FALSE; # endif } #endif /* }}} */ /* {{{ proto bool chmod(string filename, int mode) Change file mode */ PHP_FUNCTION(chmod) { char *filename; size_t filename_len; zend_long mode; int ret; mode_t imode; php_stream_wrapper *wrapper; ZEND_PARSE_PARAMETERS_START(2, 2) Z_PARAM_PATH(filename, filename_len) Z_PARAM_LONG(mode) ZEND_PARSE_PARAMETERS_END(); wrapper = php_stream_locate_url_wrapper(filename, NULL, 0); if(wrapper != &php_plain_files_wrapper || strncasecmp("file://", filename, 7) == 0) { if(wrapper && wrapper->wops->stream_metadata) { if(wrapper->wops->stream_metadata(wrapper, filename, PHP_STREAM_META_ACCESS, &mode, NULL)) { RETURN_TRUE; } else { RETURN_FALSE; } } else { php_error_docref(NULL, E_WARNING, "Can not call chmod() for a non-standard stream"); RETURN_FALSE; } } /* Check the basedir */ if (php_check_open_basedir(filename)) { RETURN_FALSE; } imode = (mode_t) mode; ret = VCWD_CHMOD(filename, imode); if (ret == -1) { php_error_docref(NULL, E_WARNING, "%s", strerror(errno)); RETURN_FALSE; } RETURN_TRUE; } /* }}} */ #if HAVE_UTIME /* {{{ proto bool touch(string filename [, int time [, int atime]]) Set modification time of file */ PHP_FUNCTION(touch) { char *filename; size_t filename_len; zend_long filetime = 0, fileatime = 0; int ret, argc = ZEND_NUM_ARGS(); FILE *file; struct utimbuf newtimebuf; struct utimbuf *newtime = &newtimebuf; php_stream_wrapper *wrapper; ZEND_PARSE_PARAMETERS_START(1, 3) Z_PARAM_PATH(filename, filename_len) Z_PARAM_OPTIONAL Z_PARAM_LONG(filetime) Z_PARAM_LONG(fileatime) ZEND_PARSE_PARAMETERS_END(); if (!filename_len) { RETURN_FALSE; } switch (argc) { case 1: newtime = NULL; break; case 2: newtime->modtime = newtime->actime = filetime; break; case 3: newtime->modtime = filetime; newtime->actime = fileatime; break; default: /* Never reached */ WRONG_PARAM_COUNT; } wrapper = php_stream_locate_url_wrapper(filename, NULL, 0); if(wrapper != &php_plain_files_wrapper || strncasecmp("file://", filename, 7) == 0) { if(wrapper && wrapper->wops->stream_metadata) { if(wrapper->wops->stream_metadata(wrapper, filename, PHP_STREAM_META_TOUCH, newtime, NULL)) { RETURN_TRUE; } else { RETURN_FALSE; } } else { php_stream *stream; if(argc > 1) { php_error_docref(NULL, E_WARNING, "Can not call touch() for a non-standard stream"); RETURN_FALSE; } stream = php_stream_open_wrapper_ex(filename, "c", REPORT_ERRORS, NULL, NULL); if(stream != NULL) { php_stream_close(stream); RETURN_TRUE; } else { RETURN_FALSE; } } } /* Check the basedir */ if (php_check_open_basedir(filename)) { RETURN_FALSE; } /* create the file if it doesn't exist already */ if (VCWD_ACCESS(filename, F_OK) != 0) { file = VCWD_FOPEN(filename, "w"); if (file == NULL) { php_error_docref(NULL, E_WARNING, "Unable to create file %s because %s", filename, strerror(errno)); RETURN_FALSE; } fclose(file); } ret = VCWD_UTIME(filename, newtime); if (ret == -1) { php_error_docref(NULL, E_WARNING, "Utime failed: %s", strerror(errno)); RETURN_FALSE; } RETURN_TRUE; } /* }}} */ #endif /* {{{ php_clear_stat_cache() */ PHPAPI void php_clear_stat_cache(zend_bool clear_realpath_cache, const char *filename, size_t filename_len) { /* always clear CurrentStatFile and CurrentLStatFile even if filename is not NULL * as it may contain outdated data (e.g. "nlink" for a directory when deleting a file * in this directory, as shown by lstat_stat_variation9.phpt) */ if (BG(CurrentStatFile)) { efree(BG(CurrentStatFile)); BG(CurrentStatFile) = NULL; } if (BG(CurrentLStatFile)) { efree(BG(CurrentLStatFile)); BG(CurrentLStatFile) = NULL; } if (clear_realpath_cache) { if (filename != NULL) { realpath_cache_del(filename, filename_len); } else { realpath_cache_clean(); } } } /* }}} */ /* {{{ proto void clearstatcache([bool clear_realpath_cache[, string filename]]) Clear file stat cache */ PHP_FUNCTION(clearstatcache) { zend_bool clear_realpath_cache = 0; char *filename = NULL; size_t filename_len = 0; ZEND_PARSE_PARAMETERS_START(0, 2) Z_PARAM_OPTIONAL Z_PARAM_BOOL(clear_realpath_cache) Z_PARAM_PATH(filename, filename_len) ZEND_PARSE_PARAMETERS_END(); php_clear_stat_cache(clear_realpath_cache, filename, filename_len); } /* }}} */ #define IS_LINK_OPERATION(__t) ((__t) == FS_TYPE || (__t) == FS_IS_LINK || (__t) == FS_LSTAT) #define IS_EXISTS_CHECK(__t) ((__t) == FS_EXISTS || (__t) == FS_IS_W || (__t) == FS_IS_R || (__t) == FS_IS_X || (__t) == FS_IS_FILE || (__t) == FS_IS_DIR || (__t) == FS_IS_LINK) #define IS_ABLE_CHECK(__t) ((__t) == FS_IS_R || (__t) == FS_IS_W || (__t) == FS_IS_X) #define IS_ACCESS_CHECK(__t) (IS_ABLE_CHECK(type) || (__t) == FS_EXISTS) /* {{{ php_stat */ PHPAPI void php_stat(const char *filename, size_t filename_length, int type, zval *return_value) { zval stat_dev, stat_ino, stat_mode, stat_nlink, stat_uid, stat_gid, stat_rdev, stat_size, stat_atime, stat_mtime, stat_ctime, stat_blksize, stat_blocks; zend_stat_t *stat_sb; php_stream_statbuf ssb; int flags = 0, rmask=S_IROTH, wmask=S_IWOTH, xmask=S_IXOTH; /* access rights defaults to other */ char *stat_sb_names[13] = { "dev", "ino", "mode", "nlink", "uid", "gid", "rdev", "size", "atime", "mtime", "ctime", "blksize", "blocks" }; const char *local; php_stream_wrapper *wrapper; if (!filename_length) { RETURN_FALSE; } if ((wrapper = php_stream_locate_url_wrapper(filename, &local, 0)) == &php_plain_files_wrapper && php_check_open_basedir(local)) { RETURN_FALSE; } if (IS_ACCESS_CHECK(type)) { if (wrapper == &php_plain_files_wrapper) { switch (type) { #ifdef F_OK case FS_EXISTS: RETURN_BOOL(VCWD_ACCESS(local, F_OK) == 0); break; #endif #ifdef W_OK case FS_IS_W: RETURN_BOOL(VCWD_ACCESS(local, W_OK) == 0); break; #endif #ifdef R_OK case FS_IS_R: RETURN_BOOL(VCWD_ACCESS(local, R_OK) == 0); break; #endif #ifdef X_OK case FS_IS_X: RETURN_BOOL(VCWD_ACCESS(local, X_OK) == 0); break; #endif } } } if (IS_LINK_OPERATION(type)) { flags |= PHP_STREAM_URL_STAT_LINK; } if (IS_EXISTS_CHECK(type)) { flags |= PHP_STREAM_URL_STAT_QUIET; } if (php_stream_stat_path_ex((char *)filename, flags, &ssb, NULL)) { /* Error Occurred */ if (!IS_EXISTS_CHECK(type)) { php_error_docref(NULL, E_WARNING, "%sstat failed for %s", IS_LINK_OPERATION(type) ? "L" : "", filename); } RETURN_FALSE; } stat_sb = &ssb.sb; if (type >= FS_IS_W && type <= FS_IS_X) { if(ssb.sb.st_uid==getuid()) { rmask=S_IRUSR; wmask=S_IWUSR; xmask=S_IXUSR; } else if(ssb.sb.st_gid==getgid()) { rmask=S_IRGRP; wmask=S_IWGRP; xmask=S_IXGRP; } else { int groups, n, i; gid_t *gids; groups = getgroups(0, NULL); if(groups > 0) { gids=(gid_t *)safe_emalloc(groups, sizeof(gid_t), 0); n=getgroups(groups, gids); for(i=0;i<n;i++){ if(ssb.sb.st_gid==gids[i]) { rmask=S_IRGRP; wmask=S_IWGRP; xmask=S_IXGRP; break; } } efree(gids); } } } if (IS_ABLE_CHECK(type) && getuid() == 0) { /* root has special perms on plain_wrapper */ if (wrapper == &php_plain_files_wrapper) { if (type == FS_IS_X) { xmask = S_IXROOT; } else { RETURN_TRUE; } } } switch (type) { case FS_PERMS: RETURN_LONG((zend_long)ssb.sb.st_mode); case FS_INODE: RETURN_LONG((zend_long)ssb.sb.st_ino); case FS_SIZE: RETURN_LONG((zend_long)ssb.sb.st_size); case FS_OWNER: RETURN_LONG((zend_long)ssb.sb.st_uid); case FS_GROUP: RETURN_LONG((zend_long)ssb.sb.st_gid); case FS_ATIME: RETURN_LONG((zend_long)ssb.sb.st_atime); case FS_MTIME: RETURN_LONG((zend_long)ssb.sb.st_mtime); case FS_CTIME: RETURN_LONG((zend_long)ssb.sb.st_ctime); case FS_TYPE: if (S_ISLNK(ssb.sb.st_mode)) { RETURN_STRING("link"); } switch(ssb.sb.st_mode & S_IFMT) { case S_IFIFO: RETURN_STRING("fifo"); case S_IFCHR: RETURN_STRING("char"); case S_IFDIR: RETURN_STRING("dir"); case S_IFBLK: RETURN_STRING("block"); case S_IFREG: RETURN_STRING("file"); #if defined(S_IFSOCK) && !defined(PHP_WIN32) case S_IFSOCK: RETURN_STRING("socket"); #endif } php_error_docref(NULL, E_NOTICE, "Unknown file type (%d)", ssb.sb.st_mode&S_IFMT); RETURN_STRING("unknown"); case FS_IS_W: RETURN_BOOL((ssb.sb.st_mode & wmask) != 0); case FS_IS_R: RETURN_BOOL((ssb.sb.st_mode&rmask)!=0); case FS_IS_X: RETURN_BOOL((ssb.sb.st_mode&xmask)!=0); case FS_IS_FILE: RETURN_BOOL(S_ISREG(ssb.sb.st_mode)); case FS_IS_DIR: RETURN_BOOL(S_ISDIR(ssb.sb.st_mode)); case FS_IS_LINK: RETURN_BOOL(S_ISLNK(ssb.sb.st_mode)); case FS_EXISTS: RETURN_TRUE; /* the false case was done earlier */ case FS_LSTAT: /* FALLTHROUGH */ case FS_STAT: array_init(return_value); ZVAL_LONG(&stat_dev, stat_sb->st_dev); ZVAL_LONG(&stat_ino, stat_sb->st_ino); ZVAL_LONG(&stat_mode, stat_sb->st_mode); ZVAL_LONG(&stat_nlink, stat_sb->st_nlink); ZVAL_LONG(&stat_uid, stat_sb->st_uid); ZVAL_LONG(&stat_gid, stat_sb->st_gid); #ifdef HAVE_STRUCT_STAT_ST_RDEV ZVAL_LONG(&stat_rdev, stat_sb->st_rdev); #else ZVAL_LONG(&stat_rdev, -1); #endif ZVAL_LONG(&stat_size, stat_sb->st_size); ZVAL_LONG(&stat_atime, stat_sb->st_atime); ZVAL_LONG(&stat_mtime, stat_sb->st_mtime); ZVAL_LONG(&stat_ctime, stat_sb->st_ctime); #ifdef HAVE_STRUCT_STAT_ST_BLKSIZE ZVAL_LONG(&stat_blksize, stat_sb->st_blksize); #else ZVAL_LONG(&stat_blksize,-1); #endif #ifdef HAVE_STRUCT_STAT_ST_BLOCKS ZVAL_LONG(&stat_blocks, stat_sb->st_blocks); #else ZVAL_LONG(&stat_blocks,-1); #endif /* Store numeric indexes in proper order */ zend_hash_next_index_insert(Z_ARRVAL_P(return_value), &stat_dev); zend_hash_next_index_insert(Z_ARRVAL_P(return_value), &stat_ino); zend_hash_next_index_insert(Z_ARRVAL_P(return_value), &stat_mode); zend_hash_next_index_insert(Z_ARRVAL_P(return_value), &stat_nlink); zend_hash_next_index_insert(Z_ARRVAL_P(return_value), &stat_uid); zend_hash_next_index_insert(Z_ARRVAL_P(return_value), &stat_gid); zend_hash_next_index_insert(Z_ARRVAL_P(return_value), &stat_rdev); zend_hash_next_index_insert(Z_ARRVAL_P(return_value), &stat_size); zend_hash_next_index_insert(Z_ARRVAL_P(return_value), &stat_atime); zend_hash_next_index_insert(Z_ARRVAL_P(return_value), &stat_mtime); zend_hash_next_index_insert(Z_ARRVAL_P(return_value), &stat_ctime); zend_hash_next_index_insert(Z_ARRVAL_P(return_value), &stat_blksize); zend_hash_next_index_insert(Z_ARRVAL_P(return_value), &stat_blocks); /* Store string indexes referencing the same zval*/ zend_hash_str_add_new(Z_ARRVAL_P(return_value), stat_sb_names[0], strlen(stat_sb_names[0]), &stat_dev); zend_hash_str_add_new(Z_ARRVAL_P(return_value), stat_sb_names[1], strlen(stat_sb_names[1]), &stat_ino); zend_hash_str_add_new(Z_ARRVAL_P(return_value), stat_sb_names[2], strlen(stat_sb_names[2]), &stat_mode); zend_hash_str_add_new(Z_ARRVAL_P(return_value), stat_sb_names[3], strlen(stat_sb_names[3]), &stat_nlink); zend_hash_str_add_new(Z_ARRVAL_P(return_value), stat_sb_names[4], strlen(stat_sb_names[4]), &stat_uid); zend_hash_str_add_new(Z_ARRVAL_P(return_value), stat_sb_names[5], strlen(stat_sb_names[5]), &stat_gid); zend_hash_str_add_new(Z_ARRVAL_P(return_value), stat_sb_names[6], strlen(stat_sb_names[6]), &stat_rdev); zend_hash_str_add_new(Z_ARRVAL_P(return_value), stat_sb_names[7], strlen(stat_sb_names[7]), &stat_size); zend_hash_str_add_new(Z_ARRVAL_P(return_value), stat_sb_names[8], strlen(stat_sb_names[8]), &stat_atime); zend_hash_str_add_new(Z_ARRVAL_P(return_value), stat_sb_names[9], strlen(stat_sb_names[9]), &stat_mtime); zend_hash_str_add_new(Z_ARRVAL_P(return_value), stat_sb_names[10], strlen(stat_sb_names[10]), &stat_ctime); zend_hash_str_add_new(Z_ARRVAL_P(return_value), stat_sb_names[11], strlen(stat_sb_names[11]), &stat_blksize); zend_hash_str_add_new(Z_ARRVAL_P(return_value), stat_sb_names[12], strlen(stat_sb_names[12]), &stat_blocks); return; } php_error_docref(NULL, E_WARNING, "Didn't understand stat call"); RETURN_FALSE; } /* }}} */ /* another quickie macro to make defining similar functions easier */ /* {{{ FileFunction(name, funcnum) */ #define FileFunction(name, funcnum) \ ZEND_NAMED_FUNCTION(name) { \ char *filename; \ size_t filename_len; \ \ ZEND_PARSE_PARAMETERS_START(1, 1) \ Z_PARAM_PATH(filename, filename_len) \ ZEND_PARSE_PARAMETERS_END(); \ \ php_stat(filename, filename_len, funcnum, return_value); \ } /* }}} */ /* {{{ proto int fileperms(string filename) Get file permissions */ FileFunction(PHP_FN(fileperms), FS_PERMS) /* }}} */ /* {{{ proto int fileinode(string filename) Get file inode */ FileFunction(PHP_FN(fileinode), FS_INODE) /* }}} */ /* {{{ proto int filesize(string filename) Get file size */ FileFunction(PHP_FN(filesize), FS_SIZE) /* }}} */ /* {{{ proto int fileowner(string filename) Get file owner */ FileFunction(PHP_FN(fileowner), FS_OWNER) /* }}} */ /* {{{ proto int filegroup(string filename) Get file group */ FileFunction(PHP_FN(filegroup), FS_GROUP) /* }}} */ /* {{{ proto int fileatime(string filename) Get last access time of file */ FileFunction(PHP_FN(fileatime), FS_ATIME) /* }}} */ /* {{{ proto int filemtime(string filename) Get last modification time of file */ FileFunction(PHP_FN(filemtime), FS_MTIME) /* }}} */ /* {{{ proto int filectime(string filename) Get inode modification time of file */ FileFunction(PHP_FN(filectime), FS_CTIME) /* }}} */ /* {{{ proto string filetype(string filename) Get file type */ FileFunction(PHP_FN(filetype), FS_TYPE) /* }}} */ /* {{{ proto bool is_writable(string filename) Returns true if file can be written */ FileFunction(PHP_FN(is_writable), FS_IS_W) /* }}} */ /* {{{ proto bool is_readable(string filename) Returns true if file can be read */ FileFunction(PHP_FN(is_readable), FS_IS_R) /* }}} */ /* {{{ proto bool is_executable(string filename) Returns true if file is executable */ FileFunction(PHP_FN(is_executable), FS_IS_X) /* }}} */ /* {{{ proto bool is_file(string filename) Returns true if file is a regular file */ FileFunction(PHP_FN(is_file), FS_IS_FILE) /* }}} */ /* {{{ proto bool is_dir(string filename) Returns true if file is directory */ FileFunction(PHP_FN(is_dir), FS_IS_DIR) /* }}} */ /* {{{ proto bool is_link(string filename) Returns true if file is symbolic link */ FileFunction(PHP_FN(is_link), FS_IS_LINK) /* }}} */ /* {{{ proto bool file_exists(string filename) Returns true if filename exists */ FileFunction(PHP_FN(file_exists), FS_EXISTS) /* }}} */ /* {{{ proto array lstat(string filename) Give information about a file or symbolic link */ FileFunction(php_if_lstat, FS_LSTAT) /* }}} */ /* {{{ proto array stat(string filename) Give information about a file */ FileFunction(php_if_stat, FS_STAT) /* }}} */ /* {{{ proto bool realpath_cache_size() Get current size of realpath cache */ PHP_FUNCTION(realpath_cache_size) { ZEND_PARSE_PARAMETERS_NONE(); RETURN_LONG(realpath_cache_size()); } /* {{{ proto bool realpath_cache_get() Get current size of realpath cache */ PHP_FUNCTION(realpath_cache_get) { realpath_cache_bucket **buckets = realpath_cache_get_buckets(), **end = buckets + realpath_cache_max_buckets(); ZEND_PARSE_PARAMETERS_NONE(); array_init(return_value); while(buckets < end) { realpath_cache_bucket *bucket = *buckets; while(bucket) { zval entry; array_init(&entry); /* bucket->key is unsigned long */ if (ZEND_LONG_MAX >= bucket->key) { add_assoc_long_ex(&entry, "key", sizeof("key") - 1, bucket->key); } else { add_assoc_double_ex(&entry, "key", sizeof("key") - 1, (double)bucket->key); } add_assoc_bool_ex(&entry, "is_dir", sizeof("is_dir") - 1, bucket->is_dir); add_assoc_stringl_ex(&entry, "realpath", sizeof("realpath") - 1, bucket->realpath, bucket->realpath_len); add_assoc_long_ex(&entry, "expires", sizeof("expires") - 1, bucket->expires); #ifdef PHP_WIN32 add_assoc_bool_ex(&entry, "is_rvalid", sizeof("is_rvalid") - 1, bucket->is_rvalid); add_assoc_bool_ex(&entry, "is_wvalid", sizeof("is_wvalid") - 1, bucket->is_wvalid); add_assoc_bool_ex(&entry, "is_readable", sizeof("is_readable") - 1, bucket->is_readable); add_assoc_bool_ex(&entry, "is_writable", sizeof("is_writable") - 1, bucket->is_writable); #endif zend_hash_str_update(Z_ARRVAL_P(return_value), bucket->path, bucket->path_len, &entry); bucket = bucket->next; } buckets++; } }
69111.c
// A minimal client for splitcounter.c, only intended to show that the specs are minimally usable. #include <assert.h> #include "splitcounter.h" struct gvar { //@ int x; }; int main() //@ : main //@ requires true; //@ ensures true; { struct gvar g; //@ g.x = 0; { /*@ predicate inv(; int x) = [1/2]g.x |-> x; @*/ //@ close inv(0); //@ close exists<predicate(int)>(inv); struct counter *c = create_counter(); { /*@ predicate pre(;) = [1/2]g.x |-> 0; predicate post(;) = [1/2]g.x |-> 1; @*/ //@ produce_lemma_function_pointer_chunk incr_ghop(inv, pre, post)() { open inv(_); open pre(); g.x++; close post(); close inv(1); }; //@ close pre(); incr_left(c); //@ open post(); //@ leak is_incr_ghop(_, _, _, _); } { /*@ predicate pre(;) = [1/2]g.x |-> 1; predicate post(;) = [1/2]g.x |-> 2; @*/ //@ produce_lemma_function_pointer_chunk incr_ghop(inv, pre, post)() { open inv(_); open pre(); g.x++; close post(); close inv(2); }; //@ close pre(); incr_right(c); //@ open post(); //@ leak is_incr_ghop(_, _, _, _); } long long v; { /*@ predicate pre(;) = [1/2]g.x |-> 2; predicate post(; int value) = [1/2]g.x |-> 2 &*& value == 2; @*/ //@ produce_lemma_function_pointer_chunk read_ghop(inv, pre, post)() { open inv(_); open pre(); close post(2); close inv(2); }; //@ close pre(); v = read(c); //@ open post(v); } assert(v == 2); dispose_counter(c); //@ open inv(_); return 0; } }
779475.c
/*----------------------------------------------------------------------------- * Copyright (C) 2010-2014 ARM Limited. All rights reserved. * * $Date: 19. March 2015 * $Revision: V.1.4.5 * * Project: CMSIS DSP Library * Title: arm_fir_interpolate_init_q31.c * * Description: Q31 FIR interpolator initialization function * * Target Processor: Cortex-M4/Cortex-M3/Cortex-M0 * * 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 ARM LIMITED 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. Modifications 2017 Mostafa Saleh (Ported to RISC-V PULPino) * ---------------------------------------------------------------------------*/ #include "riscv_math.h" /** * @ingroup groupFilters */ /** * @addtogroup FIR_Interpolate * @{ */ /** * @brief Initialization function for the Q31 FIR interpolator. * @param[in,out] *S points to an instance of the Q31 FIR interpolator structure. * @param[in] L upsample factor. * @param[in] numTaps number of filter coefficients in the filter. * @param[in] *pCoeffs points to the filter coefficient buffer. * @param[in] *pState points to the state buffer. * @param[in] blockSize number of input samples to process per call. * @return The function returns RISCV_MATH_SUCCESS if initialization was successful or RISCV_MATH_LENGTH_ERROR if * the filter length <code>numTaps</code> is not a multiple of the interpolation factor <code>L</code>. * * <b>Description:</b> * \par * <code>pCoeffs</code> points to the array of filter coefficients stored in time reversed order: * <pre> * {b[numTaps-1], b[numTaps-2], b[numTaps-2], ..., b[1], b[0]} * </pre> * The length of the filter <code>numTaps</code> must be a multiple of the interpolation factor <code>L</code>. * \par * <code>pState</code> points to the array of state variables. * <code>pState</code> is of length <code>(numTaps/L)+blockSize-1</code> words * where <code>blockSize</code> is the number of input samples processed by each call to <code>riscv_fir_interpolate_q31()</code>. */ riscv_status riscv_fir_interpolate_init_q31( riscv_fir_interpolate_instance_q31 * S, uint8_t L, uint16_t numTaps, q31_t * pCoeffs, q31_t * pState, uint32_t blockSize) { riscv_status status; /* The filter length must be a multiple of the interpolation factor */ if((numTaps % L) != 0u) { /* Set status as RISCV_MATH_LENGTH_ERROR */ status = RISCV_MATH_LENGTH_ERROR; } else { /* Assign coefficient pointer */ S->pCoeffs = pCoeffs; /* Assign Interpolation factor */ S->L = L; /* Assign polyPhaseLength */ S->phaseLength = numTaps / L; /* Clear state buffer and size of buffer is always phaseLength + blockSize - 1 */ memset(pState, 0, (blockSize + ((uint32_t) S->phaseLength - 1u)) * sizeof(q31_t)); /* Assign state pointer */ S->pState = pState; status = RISCV_MATH_SUCCESS; } return (status); } /** * @} end of FIR_Interpolate group */
657346.c
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ #include <sys/param.h> #include <stdint.h> #include <stdlib.h> #include "crypto/s2n_hmac.h" #include "tls/s2n_record.h" #include "tls/s2n_prf.h" #include "tls/s2n_connection.h" #include <smack.h> #include <smack-contracts.h> #include "ct-verif.h" #include "sidetrail.h" #include "utils/s2n_safety.h" #include "tls/s2n_cipher_suites.h" #include "utils/s2n_blob.h" #include "crypto/s2n_cipher.h" int s2n_record_parse_aead( const struct s2n_cipher_suite *cipher_suite, struct s2n_connection *conn, uint8_t content_type, uint16_t encrypted_length, uint8_t * implicit_iv, struct s2n_hmac_state *mac, uint8_t * sequence_number, struct s2n_session_key *session_key); #define DECRYPT_COST 10 #define IV_SIZE 16 #define MAX_SIZE 1024 #define TAG_SIZE 16 int decrypt_aead(struct s2n_session_key *session_key, struct s2n_blob* iv, struct s2n_blob* aad, struct s2n_blob* in, struct s2n_blob* out) { int size = in->size; __VERIFIER_ASSUME_LEAKAGE(size * DECRYPT_COST); out->data = malloc(size); return 0; } int s2n_increment_sequence_number(uint8_t * sequence_number){ __VERIFIER_ASSUME_LEAKAGE(0); return 0; } int s2n_record_parse_wrapper(int *xor_pad, int *digest_pad, int padding_length, int encrypted_length, uint8_t content_type, int flags ) { __VERIFIER_ASSERT_MAX_LEAKAGE(10); __VERIFIER_assume(encrypted_length > 0); public_in(__SMACK_value(padding_length)); public_in(__SMACK_value(encrypted_length)); public_in(__SMACK_value(flags)); struct s2n_hmac_state hmac = { .alg = S2N_HMAC_SHA1, .hash_block_size = BLOCK_SIZE, .currently_in_hash_block = 0, .digest_size = SHA_DIGEST_LENGTH, .xor_pad_size = BLOCK_SIZE, .inner.alg = S2N_HASH_SHA1, .inner.currently_in_hash_block = 0, .inner_just_key.alg = S2N_HASH_SHA1, .inner_just_key.currently_in_hash_block = 0, .outer.alg = S2N_HASH_SHA1, .outer.currently_in_hash_block = 0, .outer_just_key.alg = S2N_HASH_SHA1, .outer_just_key.currently_in_hash_block = 0, .xor_pad = *xor_pad, .digest_pad = *digest_pad }; struct s2n_cipher aead_cipher = { .type = S2N_AEAD, .io.aead.decrypt = decrypt_aead, .io.aead.record_iv_size = IV_SIZE, .io.aead.fixed_iv_size = IV_SIZE, .io.aead.tag_size = TAG_SIZE, }; struct s2n_record_algorithm record_algorithm = { .cipher = &aead_cipher, .flags = flags }; struct s2n_cipher_suite cipher_suite = { .record_alg = &record_algorithm, }; /* cppcheck-suppress unassignedVariable */ uint8_t data1[MAX_SIZE]; /* cppcheck-suppress unassignedVariable */ uint8_t data2[MAX_SIZE]; struct s2n_connection conn = { .actual_protocol_version = S2N_TLS10, .in = { .read_cursor = 0, .write_cursor = MAX_SIZE, .blob = { .data = data1, .size = MAX_SIZE, }, }, .header_in = { .read_cursor = 0, .write_cursor = S2N_TLS_RECORD_HEADER_LENGTH, .blob = { .data = data2, .size = MAX_SIZE, }, }, }; uint8_t sequence_number[S2N_TLS_SEQUENCE_NUM_LEN]; struct s2n_session_key session_key; uint8_t implicit_iv[S2N_TLS_MAX_IV_LEN]; return s2n_record_parse_aead(&cipher_suite, &conn, content_type, encrypted_length, implicit_iv, &hmac, sequence_number, &session_key); }
356893.c
// SPDX-License-Identifier: GPL-2.0+ /* * Tests for the driver model ADC API * * Copyright (c) 2015 Samsung Electronics * Przemyslaw Marczak <p.marczak@samsung.com> */ #include <common.h> #include <adc.h> #include <dm.h> #include <dm/root.h> #include <dm/util.h> #include <dm/test.h> #include <errno.h> #include <fdtdec.h> #include <power/regulator.h> #include <power/sandbox_pmic.h> #include <sandbox-adc.h> #include <test/ut.h> static int dm_test_adc_bind(struct unit_test_state *uts) { struct udevice *dev; unsigned int channel_mask; ut_assertok(uclass_get_device_by_name(UCLASS_ADC, "adc@0", &dev)); ut_asserteq_str(SANDBOX_ADC_DEVNAME, dev->name); ut_assertok(adc_channel_mask(dev, &channel_mask)); ut_asserteq((1 << SANDBOX_ADC_CHANNELS) - 1, channel_mask); return 0; } DM_TEST(dm_test_adc_bind, DM_TESTF_SCAN_FDT); static int dm_test_adc_wrong_channel_selection(struct unit_test_state *uts) { struct udevice *dev; ut_assertok(uclass_get_device_by_name(UCLASS_ADC, "adc@0", &dev)); ut_asserteq(-EINVAL, adc_start_channel(dev, SANDBOX_ADC_CHANNELS)); return 0; } DM_TEST(dm_test_adc_wrong_channel_selection, DM_TESTF_SCAN_FDT); static int dm_test_adc_supply(struct unit_test_state *uts) { struct udevice *supply; struct udevice *dev; int uV; ut_assertok(uclass_get_device_by_name(UCLASS_ADC, "adc@0", &dev)); /* Test Vss value - predefined 0 uV */ ut_assertok(adc_vss_value(dev, &uV)); ut_asserteq(SANDBOX_ADC_VSS_VALUE, uV); /* Test Vdd initial value - buck2 */ ut_assertok(adc_vdd_value(dev, &uV)); ut_asserteq(SANDBOX_BUCK2_INITIAL_EXPECTED_UV, uV); /* Change Vdd value - buck2 manual preset */ ut_assertok(regulator_get_by_devname(SANDBOX_BUCK2_DEVNAME, &supply)); ut_assertok(regulator_set_value(supply, SANDBOX_BUCK2_SET_UV)); ut_asserteq(SANDBOX_BUCK2_SET_UV, regulator_get_value(supply)); /* Update ADC platdata and get new Vdd value */ ut_assertok(adc_vdd_value(dev, &uV)); ut_asserteq(SANDBOX_BUCK2_SET_UV, uV); /* Disable buck2 and test ADC supply enable function */ ut_assertok(regulator_set_enable(supply, false)); ut_asserteq(false, regulator_get_enable(supply)); /* adc_start_channel() should enable the supply regulator */ ut_assertok(adc_start_channel(dev, 0)); ut_asserteq(true, regulator_get_enable(supply)); return 0; } DM_TEST(dm_test_adc_supply, DM_TESTF_SCAN_FDT); struct adc_channel adc_channel_test_data[] = { { 0, SANDBOX_ADC_CHANNEL0_DATA }, { 1, SANDBOX_ADC_CHANNEL1_DATA }, { 2, SANDBOX_ADC_CHANNEL2_DATA }, { 3, SANDBOX_ADC_CHANNEL3_DATA }, }; static int dm_test_adc_single_channel_conversion(struct unit_test_state *uts) { struct adc_channel *tdata = adc_channel_test_data; unsigned int i, data; struct udevice *dev; ut_assertok(uclass_get_device_by_name(UCLASS_ADC, "adc@0", &dev)); /* Test each ADC channel's value */ for (i = 0; i < SANDBOX_ADC_CHANNELS; i++, tdata++) { ut_assertok(adc_start_channel(dev, tdata->id)); ut_assertok(adc_channel_data(dev, tdata->id, &data)); ut_asserteq(tdata->data, data); } return 0; } DM_TEST(dm_test_adc_single_channel_conversion, DM_TESTF_SCAN_FDT); static int dm_test_adc_multi_channel_conversion(struct unit_test_state *uts) { struct adc_channel channels[SANDBOX_ADC_CHANNELS]; struct udevice *dev; struct adc_channel *tdata = adc_channel_test_data; unsigned int i, channel_mask; channel_mask = ADC_CHANNEL(0) | ADC_CHANNEL(1) | ADC_CHANNEL(2) | ADC_CHANNEL(3); /* Start multi channel conversion */ ut_assertok(uclass_get_device_by_name(UCLASS_ADC, "adc@0", &dev)); ut_assertok(adc_start_channels(dev, channel_mask)); ut_assertok(adc_channels_data(dev, channel_mask, channels)); /* Compare the expected and returned conversion data. */ for (i = 0; i < SANDBOX_ADC_CHANNELS; i++, tdata++) ut_asserteq(tdata->data, channels[i].data); return 0; } DM_TEST(dm_test_adc_multi_channel_conversion, DM_TESTF_SCAN_FDT); static int dm_test_adc_single_channel_shot(struct unit_test_state *uts) { struct adc_channel *tdata = adc_channel_test_data; unsigned int i, data; for (i = 0; i < SANDBOX_ADC_CHANNELS; i++, tdata++) { /* Start single channel conversion */ ut_assertok(adc_channel_single_shot("adc@0", tdata->id, &data)); /* Compare the expected and returned conversion data. */ ut_asserteq(tdata->data, data); } return 0; } DM_TEST(dm_test_adc_single_channel_shot, DM_TESTF_SCAN_FDT); static int dm_test_adc_multi_channel_shot(struct unit_test_state *uts) { struct adc_channel channels[SANDBOX_ADC_CHANNELS]; struct adc_channel *tdata = adc_channel_test_data; unsigned int i, channel_mask; channel_mask = ADC_CHANNEL(0) | ADC_CHANNEL(1) | ADC_CHANNEL(2) | ADC_CHANNEL(3); /* Start single call and multi channel conversion */ ut_assertok(adc_channels_single_shot("adc@0", channel_mask, channels)); /* Compare the expected and returned conversion data. */ for (i = 0; i < SANDBOX_ADC_CHANNELS; i++, tdata++) ut_asserteq(tdata->data, channels[i].data); return 0; } DM_TEST(dm_test_adc_multi_channel_shot, DM_TESTF_SCAN_FDT); static const int dm_test_adc_uV_data[SANDBOX_ADC_CHANNELS] = { ((u64)SANDBOX_ADC_CHANNEL0_DATA * SANDBOX_BUCK2_INITIAL_EXPECTED_UV) / SANDBOX_ADC_DATA_MASK, ((u64)SANDBOX_ADC_CHANNEL1_DATA * SANDBOX_BUCK2_INITIAL_EXPECTED_UV) / SANDBOX_ADC_DATA_MASK, ((u64)SANDBOX_ADC_CHANNEL2_DATA * SANDBOX_BUCK2_INITIAL_EXPECTED_UV) / SANDBOX_ADC_DATA_MASK, ((u64)SANDBOX_ADC_CHANNEL3_DATA * SANDBOX_BUCK2_INITIAL_EXPECTED_UV) / SANDBOX_ADC_DATA_MASK, }; static int dm_test_adc_raw_to_uV(struct unit_test_state *uts) { struct adc_channel *tdata = adc_channel_test_data; unsigned int i, data; struct udevice *dev; int uV; ut_assertok(uclass_get_device_by_name(UCLASS_ADC, "adc@0", &dev)); /* Test each ADC channel's value in microvolts */ for (i = 0; i < SANDBOX_ADC_CHANNELS; i++, tdata++) { ut_assertok(adc_start_channel(dev, tdata->id)); ut_assertok(adc_channel_data(dev, tdata->id, &data)); ut_assertok(adc_raw_to_uV(dev, data, &uV)); ut_asserteq(dm_test_adc_uV_data[i], uV); } return 0; } DM_TEST(dm_test_adc_raw_to_uV, DM_TESTF_SCAN_FDT);
670400.c
#include <assert.h> unsigned int square1 (unsigned int x) { return x * x; } unsigned int square2 (unsigned int x) { x = x; return x * x; } unsigned int nondet_ui(); int main (void) { unsigned int x = nontdet_ui(); unsigned int y = square1(x); unsigned int z = square2(x); assert((y & 0x2) == 0x0); assert((z & 0x2) == 0x0); //expected to fail return 1; }
430652.c
/* * Copyright (c) 2004-2010 The Trustees of Indiana University and Indiana * University Research and Technology * Corporation. All rights reserved. * Copyright (c) 2004-2011 The University of Tennessee and The University * of Tennessee Research Foundation. All rights * reserved. * Copyright (c) 2004-2005 High Performance Computing Center Stuttgart, * University of Stuttgart. All rights reserved. * Copyright (c) 2004-2005 The Regents of the University of California. * All rights reserved. * Copyright (c) 2006-2013 Los Alamos National Security, LLC. * All rights reserved. * Copyright (c) 2009-2012 Cisco Systems, Inc. All rights reserved. * Copyright (c) 2011 Oak Ridge National Labs. All rights reserved. * Copyright (c) 2013-2020 Intel, Inc. All rights reserved. * Copyright (c) 2015 Mellanox Technologies, Inc. All rights reserved. * $COPYRIGHT$ * * Additional copyrights may follow * * $HEADER$ * */ #include "src/include/pmix_config.h" #include "include/pmix.h" #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <time.h> #include "src/class/pmix_object.h" #include "src/util/output.h" #include "src/util/printf.h" static pmix_proc_t myproc; int main(int argc, char **argv) { pmix_status_t rc; pmix_value_t value; pmix_value_t *val = &value; uint64_t seckey[2]; pmix_proc_t proc; pmix_info_t *info; size_t n, ninfo; /* init us */ if (PMIX_SUCCESS != (rc = PMIx_Init(&myproc, NULL, 0))) { pmix_output(0, "Client ns %s rank %d: PMIx_Init failed: %s", myproc.nspace, myproc.rank, PMIx_Error_string(rc)); exit(rc); } pmix_output(0, "GWClient ns %s rank %d: Running", myproc.nspace, myproc.rank); /* look for network data */ memset(&proc, 0, sizeof(pmix_proc_t)); (void)strncpy(proc.nspace, myproc.nspace, PMIX_MAX_NSLEN); proc.rank = PMIX_RANK_WILDCARD; if (PMIX_SUCCESS != (rc = PMIx_Get(&proc, "my.net.key", NULL, 0, &val)) || PMIX_DATA_ARRAY != val->type || NULL == val->data.darray || NULL == val->data.darray->array) { pmix_output(0, "Client ns %s rank %d: PMIx_Get my.net.key failed: %s", myproc.nspace, myproc.rank, PMIx_Error_string(rc)); exit(rc); } /* the returned value has all the network allocation info in a * pmix_data_array_t */ info = (pmix_info_t*)val->data.darray->array; ninfo = val->data.darray->size; pmix_output(0, "Client ns %s rank %d: got network assignment:", myproc.nspace, myproc.rank); for (n=0; n < ninfo; n++) { if (PMIX_STRING == info[n].value.type) { pmix_output(0, "\tKey: %s Value: %s", info[n].key, info[n].value.data.string); } else if (PMIX_BYTE_OBJECT == info[n].value.type) { memcpy(seckey, info[n].value.data.bo.bytes, info[n].value.data.bo.size); pmix_output(0, "\tKey: %s sec key: %ld.%ld", info[n].key, (long int)seckey[0], (long int)seckey[1]); } } PMIX_VALUE_RELEASE(val); /* finalize us */ pmix_output(0, "Client ns %s rank %d: Finalizing", myproc.nspace, myproc.rank); if (PMIX_SUCCESS != (rc = PMIx_Finalize(NULL, 0))) { fprintf(stderr, "Client ns %s rank %d:PMIx_Finalize failed: %s\n", myproc.nspace, myproc.rank, PMIx_Error_string(rc)); } else { fprintf(stderr, "Client ns %s rank %d:PMIx_Finalize successfully completed\n", myproc.nspace, myproc.rank); } fflush(stderr); return(rc); }
417114.c
/* Copyright (c) 2013 Anton Titov. * Copyright (c) 2013 pCloud Ltd. * 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 pCloud Ltd 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 pCloud Ltd 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 "pupload.h" #include "pstatus.h" #include "ptimer.h" #include "plibs.h" #include "ptasks.h" #include "pssl.h" #include "psettings.h" #include "pnetlibs.h" #include "papi.h" #include "pfolder.h" #include "pcallbacks.h" #include "pdiff.h" #include "plist.h" typedef struct { psync_list list; psync_fileid_t localfileid; uint64_t filesize; uint64_t uploaded; uint64_t taskid; psync_syncid_t syncid; int stop; unsigned char hash[PSYNC_HASH_DIGEST_HEXLEN]; } upload_list_t; typedef struct { upload_list_t upllist; char filename[]; } upload_task_t; static pthread_mutex_t upload_mutex=PTHREAD_MUTEX_INITIALIZER; static pthread_cond_t upload_cond=PTHREAD_COND_INITIALIZER; static uint32_t upload_wakes=0; static psync_uint_t current_uploads_waiters=0; static pthread_mutex_t current_uploads_mutex=PTHREAD_MUTEX_INITIALIZER; static pthread_cond_t current_uploads_cond=PTHREAD_COND_INITIALIZER; static psync_list uploads=PSYNC_LIST_STATIC_INIT(uploads); static const uint32_t requiredstatuses[]={ PSTATUS_COMBINE(PSTATUS_TYPE_RUN, PSTATUS_RUN_RUN), PSTATUS_COMBINE(PSTATUS_TYPE_ONLINE, PSTATUS_ONLINE_ONLINE), PSTATUS_COMBINE(PSTATUS_TYPE_ACCFULL, PSTATUS_ACCFULL_QUOTAOK) }; void psync_upload_inc_uploads(){ pthread_mutex_lock(&upload_mutex); psync_status.filesuploading++; pthread_mutex_unlock(&upload_mutex); psync_send_status_update(); } void psync_upload_dec_uploads(){ pthread_mutex_lock(&upload_mutex); psync_status.filesuploading--; if (psync_status.filesuploading==0 && current_uploads_waiters) pthread_cond_broadcast(&current_uploads_cond); pthread_mutex_unlock(&upload_mutex); psync_send_status_update(); } void psync_upload_dec_uploads_cnt(uint32_t cnt){ pthread_mutex_lock(&upload_mutex); psync_status.filesuploading-=cnt; if (psync_status.filesuploading==0 && current_uploads_waiters) pthread_cond_broadcast(&current_uploads_cond); pthread_mutex_unlock(&upload_mutex); psync_send_status_update(); } void psync_upload_add_bytes_uploaded(uint64_t bytes){ pthread_mutex_lock(&upload_mutex); psync_status.bytesuploaded+=bytes; pthread_mutex_unlock(&upload_mutex); psync_send_status_update(); } void psync_upload_sub_bytes_uploaded(uint64_t bytes){ pthread_mutex_lock(&upload_mutex); psync_status.bytesuploaded-=bytes; pthread_mutex_unlock(&upload_mutex); psync_send_status_update(); } static void task_wait_no_uploads(){ pthread_mutex_lock(&current_uploads_mutex); while (psync_status.filesuploading){ current_uploads_waiters++; pthread_cond_wait(&current_uploads_cond, &current_uploads_mutex); current_uploads_waiters--; } pthread_mutex_unlock(&current_uploads_mutex); } static int64_t do_run_command_res(const char *cmd, size_t cmdlen, const binparam *params, size_t paramscnt){ psync_socket *api; binresult *res; uint64_t result; api=psync_apipool_get(); if (unlikely(!api)) return -1; res=do_send_command(api, cmd, cmdlen, params, paramscnt, -1, 1); if (likely(res)) psync_apipool_release(api); else{ psync_apipool_release_bad(api); return -1; } result=psync_find_result(res, "result", PARAM_NUM)->num; psync_free(res); if (unlikely(result)){ psync_process_api_error(result); debug(D_WARNING, "command %s returned code %u", cmd, (unsigned)result); } return result; } static int do_run_command(const char *cmd, size_t cmdlen, const binparam *params, size_t paramscnt){ uint64_t result; result=do_run_command_res(cmd, cmdlen, params, paramscnt); if (unlikely(result)){ psync_process_api_error(result); debug(D_WARNING, "command %s returned code %u", cmd, (unsigned)result); return psync_handle_api_result(result)==PSYNC_NET_TEMPFAIL?-1:0; } else return 0; } #define run_command(cmd, params) do_run_command(cmd, strlen(cmd), params, sizeof(params)/sizeof(binparam)) #define run_command_res(cmd, params) do_run_command_res(cmd, strlen(cmd), params, sizeof(params)/sizeof(binparam)) static int task_createfolder(psync_syncid_t syncid, psync_folderid_t localfolderid, const char *name){ psync_sql_res *res; psync_uint_row row; psync_folderid_t parentfolderid, folderid; psync_socket *api; binresult *bres; char *nname; uint64_t result; int ret; res=psync_sql_query_rdlock("SELECT s.folderid FROM localfolder l, syncedfolder s WHERE l.id=? AND l.syncid=? AND l.localparentfolderid=s.localfolderid AND s.syncid=?"); psync_sql_bind_uint(res, 1, localfolderid); psync_sql_bind_uint(res, 2, syncid); psync_sql_bind_uint(res, 3, syncid); if (likely_log(row=psync_sql_fetch_rowint(res))) parentfolderid=row[0]; else parentfolderid=PSYNC_INVALID_FOLDERID; psync_sql_free_result(res); nname=psync_strnormalize_filename(name); if (unlikely(parentfolderid==PSYNC_INVALID_FOLDERID)){ psync_free(nname); return 0; } else{ binparam params[]={P_STR("auth", psync_my_auth), P_NUM("folderid", parentfolderid), P_STR("name", nname)}; api=psync_apipool_get(); if (unlikely(!api)){ psync_free(nname); return -1; } psync_diff_lock(); bres=send_command(api, "createfolderifnotexists", params); psync_free(nname); if (likely(bres)) psync_apipool_release(api); else{ psync_diff_unlock(); psync_apipool_release_bad(api); return -1; } result=psync_find_result(bres, "result", PARAM_NUM)->num; if (unlikely(result)){ psync_diff_unlock(); debug(D_WARNING, "command createfolderifnotexists returned code %u", (unsigned)result); psync_process_api_error(result); if (psync_handle_api_result(result)==PSYNC_NET_TEMPFAIL) return -1; else return 0; } folderid=psync_find_result(psync_find_result(bres, "metadata", PARAM_HASH), "folderid", PARAM_NUM)->num; psync_free(bres); debug(D_NOTICE, "remote folder %lu %lu/%s created", (long unsigned)folderid, (long unsigned)parentfolderid, name); psync_sql_start_transaction(); res=psync_sql_prep_statement("UPDATE localfolder SET folderid=? WHERE id=? AND syncid=?"); psync_sql_bind_uint(res, 1, folderid); psync_sql_bind_uint(res, 2, localfolderid); psync_sql_bind_uint(res, 3, syncid); psync_sql_run_free(res); res=psync_sql_prep_statement("UPDATE syncedfolder SET folderid=? WHERE localfolderid=? AND syncid=?"); psync_sql_bind_uint(res, 1, folderid); psync_sql_bind_uint(res, 2, localfolderid); psync_sql_bind_uint(res, 3, syncid); psync_sql_run_free(res); ret=psync_sql_commit_transaction(); psync_diff_unlock(); return ret; } } static int task_renameremotefile(psync_fileid_t fileid, psync_folderid_t newparentfolderid, const char *newname){ binparam params[]={P_STR("auth", psync_my_auth), P_NUM("fileid", fileid), P_NUM("tofolderid", newparentfolderid), P_STR("toname", newname)}; int ret; ret=run_command("renamefile", params); if (likely(!ret)) debug(D_NOTICE, "remote fileid %lu moved/renamed to (%lu)/%s", (long unsigned)fileid, (long unsigned)newparentfolderid, newname); return ret; } static int task_renamefile(psync_syncid_t syncid, psync_fileid_t localfileid, psync_folderid_t newlocalparentfolderid, const char *newname){ psync_sql_res *res; psync_uint_row row; psync_fileid_t fileid; psync_folderid_t folderid; char *nname; int ret; task_wait_no_uploads(); res=psync_sql_query_rdlock("SELECT fileid FROM localfile WHERE id=?"); psync_sql_bind_uint(res, 1, localfileid); if ((row=psync_sql_fetch_rowint(res))) fileid=row[0]; else fileid=0; psync_sql_free_result(res); res=psync_sql_query_rdlock("SELECT folderid FROM syncedfolder WHERE syncid=? AND localfolderid=?"); psync_sql_bind_uint(res, 1, syncid); psync_sql_bind_uint(res, 2, newlocalparentfolderid); if ((row=psync_sql_fetch_rowint(res))) folderid=row[0]; else folderid=0; psync_sql_free_result(res); if (unlikely_log(!fileid) || unlikely_log(!folderid)) return 0; else{ nname=psync_strnormalize_filename(newname); ret=task_renameremotefile(fileid, folderid, nname); psync_free(nname); return ret; } } static int task_renameremotefolder(psync_folderid_t folderid, psync_folderid_t newparentfolderid, const char *newname){ binparam params[]={P_STR("auth", psync_my_auth), P_NUM("folderid", folderid), P_NUM("tofolderid", newparentfolderid), P_STR("toname", newname)}; int ret; ret=run_command("renamefolder", params); if (likely(!ret)) debug(D_NOTICE, "remote folderid %lu moved/renamed to (%lu)/%s", (long unsigned)folderid, (long unsigned)newparentfolderid, newname); return ret; } static int task_renamefolder(psync_syncid_t syncid, psync_fileid_t localfolderid, psync_folderid_t newlocalparentfolderid, const char *newname){ psync_sql_res *res; psync_uint_row row; psync_folderid_t folderid, parentfolderid; char *nname; int ret; task_wait_no_uploads(); res=psync_sql_query_rdlock("SELECT folderid FROM syncedfolder WHERE syncid=? AND localfolderid=?"); psync_sql_bind_uint(res, 1, syncid); psync_sql_bind_uint(res, 2, localfolderid); if ((row=psync_sql_fetch_rowint(res))) folderid=row[0]; else folderid=0; psync_sql_free_result(res); res=psync_sql_query_rdlock("SELECT folderid FROM syncedfolder WHERE syncid=? AND localfolderid=?"); psync_sql_bind_uint(res, 1, syncid); psync_sql_bind_uint(res, 2, newlocalparentfolderid); if ((row=psync_sql_fetch_rowint(res))) parentfolderid=row[0]; else parentfolderid=0; psync_sql_free_result(res); if (unlikely_log(!folderid) || unlikely_log(!parentfolderid)) return 0; else{ nname=psync_strnormalize_filename(newname); ret=task_renameremotefolder(folderid, parentfolderid, nname); psync_free(nname); return ret; } } static void set_local_file_remote_id(psync_fileid_t localfileid, psync_fileid_t fileid, uint64_t hash){ psync_sql_res *res; res=psync_sql_prep_statement("UPDATE localfile SET fileid=?, hash=? WHERE id=?"); psync_sql_bind_uint(res, 1, fileid); psync_sql_bind_uint(res, 2, hash); psync_sql_bind_uint(res, 3, localfileid); psync_sql_run_free(res); } static void set_local_file_conflicted(psync_fileid_t localfileid, psync_fileid_t fileid, uint64_t hash, const char *localpath, const char *newname, uint64_t taskid){ psync_sql_res *res; char *newpath; debug(D_NOTICE, "conflict found, renaming %s to %s", localpath, newname); psync_sql_start_transaction(); res=psync_sql_prep_statement("UPDATE localfile SET fileid=?, hash=?, name=? WHERE id=?"); psync_sql_bind_uint(res, 1, fileid); psync_sql_bind_uint(res, 2, hash); psync_sql_bind_string(res, 3, newname); psync_sql_bind_uint(res, 4, localfileid); psync_sql_run_free(res); res=psync_sql_prep_statement("UPDATE task SET name=? WHERE id=?"); psync_sql_bind_string(res, 1, newname); psync_sql_bind_uint(res, 2, taskid); psync_sql_run_free(res); newpath=psync_local_path_for_local_file(localfileid, NULL); if (unlikely_log(psync_file_rename_overwrite(localpath, newpath))) psync_sql_rollback_transaction(); else psync_sql_commit_transaction(); psync_free(newpath); } static int copy_file(psync_fileid_t fileid, uint64_t hash, psync_folderid_t folderid, const char *name, psync_fileid_t localfileid){ binparam params[]={P_STR("auth", psync_my_auth), P_NUM("fileid", fileid), P_NUM("hash", hash), P_NUM("tofolderid", folderid), P_STR("toname", name)}; psync_socket *api; binresult *res; const binresult *meta; uint64_t result; api=psync_apipool_get(); if (unlikely(!api)) return -1; psync_diff_lock(); res=send_command(api, "copyfile", params); if (likely(res)) psync_apipool_release(api); else{ psync_diff_unlock(); psync_apipool_release_bad(api); return -1; } result=psync_find_result(res, "result", PARAM_NUM)->num; if (unlikely(result)){ psync_diff_unlock(); psync_free(res); debug(D_WARNING, "command copyfile returned code %u", (unsigned)result); psync_process_api_error(result); return 0; } meta=psync_find_result(res, "metadata", PARAM_HASH); set_local_file_remote_id(localfileid, psync_find_result(meta, "fileid", PARAM_NUM)->num, psync_find_result(meta, "hash", PARAM_NUM)->num); psync_diff_unlock(); psync_free(res); return 1; } static int check_file_if_exists(const unsigned char *hashhex, uint64_t fsize, psync_folderid_t folderid, const char *name, psync_fileid_t localfileid){ psync_sql_res *res; psync_uint_row row; psync_fileid_t fileid; uint64_t filesize, hash; unsigned char shashhex[PSYNC_HASH_DIGEST_HEXLEN]; int ret; res=psync_sql_query_rdlock("SELECT id, size FROM file WHERE parentfolderid=? AND name=?"); psync_sql_bind_uint(res, 1, folderid); psync_sql_bind_string(res, 2, name); row=psync_sql_fetch_rowint(res); if (row && row[1]==fsize){ fileid=row[0]; psync_sql_free_result(res); ret=psync_get_remote_file_checksum(fileid, shashhex, &filesize, &hash); if (ret==PSYNC_NET_OK){ if (filesize==fsize && !memcmp(hashhex, shashhex, PSYNC_HASH_DIGEST_HEXLEN)){ debug(D_NOTICE, "file %lu/%s already exists and matches local checksum, not doing anything", (unsigned long)folderid, name); set_local_file_remote_id(localfileid, fileid, hash); return 1; } else return 0; } else if (ret==PSYNC_NET_TEMPFAIL) return -1; else if (ret==PSYNC_NET_PERMFAIL) return 0; } psync_sql_free_result(res); return 0; } static int copy_file_if_exists(const unsigned char *hashhex, uint64_t fsize, psync_folderid_t folderid, const char *name, psync_fileid_t localfileid){ binparam params[]={P_STR("auth", psync_my_auth), P_NUM("size", fsize), P_LSTR(PSYNC_CHECKSUM, hashhex, PSYNC_HASH_DIGEST_HEXLEN)}; psync_socket *api; binresult *res; const binresult *metas, *meta; uint64_t result; int ret; api=psync_apipool_get(); if (unlikely(!api)) return -1; res=send_command(api, "getfilesbychecksum", params); if (likely(res)) psync_apipool_release(api); else{ psync_apipool_release_bad(api); return -1; } result=psync_find_result(res, "result", PARAM_NUM)->num; if (unlikely(result)){ psync_free(res); debug(D_WARNING, "command getfilesbychecksum returned code %u", (unsigned)result); psync_process_api_error(result); return 0; } metas=psync_find_result(res, "metadata", PARAM_ARRAY); if (!metas->length){ psync_free(res); return 0; } meta=metas->array[0]; ret=copy_file(psync_find_result(meta, "fileid", PARAM_NUM)->num, psync_find_result(meta, "hash", PARAM_NUM)->num, folderid, name, localfileid); if (ret==1) debug(D_NOTICE, "file %lu/%s copied to %lu/%s instead of uploading due to matching checksum", (long unsigned)psync_find_result(meta, "parentfolderid", PARAM_NUM)->num, psync_find_result(meta, "name", PARAM_STR)->str, (long unsigned)folderid, name); psync_free(res); return ret; } static void wake_upload_when_ready(){ if (current_uploads_waiters && psync_status.filesuploading<PSYNC_MAX_PARALLEL_UPLOADS && psync_status.bytestouploadcurrent-psync_status.bytesuploaded<=PSYNC_START_NEW_UPLOADS_TRESHOLD) pthread_cond_signal(&current_uploads_cond); } static void add_bytes_uploaded(uint64_t bytes){ pthread_mutex_lock(&current_uploads_mutex); psync_status.bytesuploaded+=bytes; wake_upload_when_ready(); pthread_mutex_unlock(&current_uploads_mutex); psync_send_status_update(); } static int upload_file(const char *localpath, const unsigned char *hashhex, uint64_t fsize, psync_folderid_t folderid, const char *name, psync_fileid_t localfileid, psync_syncid_t syncid, upload_list_t *upload, binparam pr){ binparam params[]={P_STR("auth", psync_my_auth), P_NUM("folderid", folderid), P_STR("filename", name), P_BOOL("nopartial", 1), {pr.paramtype, pr.paramnamelen, pr.opts, pr.paramname, {pr.num}} /* specially for Visual Studio compiler */}; psync_socket *api; void *buff; binresult *res; const binresult *meta; const char *hashhexsrv; psync_sql_res *sres; uint64_t bw, result, fileid, rsize, hash; size_t rd; ssize_t rrd; psync_file_t fd; fd=psync_file_open(localpath, P_O_RDONLY, 0); if (fd==INVALID_HANDLE_VALUE){ debug(D_WARNING, "could not open local file %s", localpath); return -1; } api=psync_apipool_get(); if (unlikely(!api)) goto err0; if (unlikely_log(!do_send_command(api, "uploadfile", strlen("uploadfile"), params, ARRAY_SIZE(params), fsize, 0))) goto err1; bw=0; buff=psync_malloc(PSYNC_COPY_BUFFER_SIZE); while (bw<fsize){ if (unlikely(upload->stop)){ debug(D_NOTICE, "upload of %s stopped", localpath); goto err2; } psync_wait_statuses_array(requiredstatuses, ARRAY_SIZE(requiredstatuses)); if (fsize-bw>PSYNC_COPY_BUFFER_SIZE) rd=PSYNC_COPY_BUFFER_SIZE; else rd=fsize-bw; rrd=psync_file_read(fd, buff, rd); if (unlikely_log(rrd<=0)) goto err2; if (unlikely_log(psync_socket_writeall_upload(api, buff, rrd)!=rrd)) goto err2; bw+=rrd; if (bw==fsize && psync_file_read(fd, buff, 1)!=0){ debug(D_WARNING, "file %s has grown while uploading, retrying", localpath); goto err2; } upload->uploaded+=rrd; add_bytes_uploaded(rrd); } psync_free(buff); psync_file_close(fd); psync_set_default_sendbuf(api); psync_diff_lock(); res=get_result(api); if (likely(res)) psync_apipool_release(api); else{ psync_apipool_release_bad(api); goto err00; } result=psync_find_result(res, "result", PARAM_NUM)->num; if (unlikely(result)){ psync_free(res); debug(D_WARNING, "command uploadfile returned code %u", (unsigned)result); psync_process_api_error(result); if (psync_handle_api_result(result)==PSYNC_NET_TEMPFAIL) goto err00; else{ psync_diff_unlock(); return 0; } } meta=psync_find_result(res, "metadata", PARAM_ARRAY)->array[0]; fileid=psync_find_result(meta, "fileid", PARAM_NUM)->num; hash=psync_find_result(meta, "hash", PARAM_NUM)->num; rsize=psync_find_result(meta, "size", PARAM_NUM)->num; hashhexsrv=psync_find_result(psync_find_result(res, "checksums", PARAM_ARRAY)->array[0], PSYNC_CHECKSUM, PARAM_STR)->str; psync_sql_start_transaction(); sres=psync_sql_prep_statement("REPLACE INTO hashchecksum (hash, size, checksum) VALUES (?, ?, ?)"); psync_sql_bind_uint(sres, 1, hash); psync_sql_bind_uint(sres, 2, rsize); psync_sql_bind_lstring(sres, 3, hashhexsrv, PSYNC_HASH_DIGEST_HEXLEN); psync_sql_run_free(sres); if (psync_check_result(meta, "conflicted", PARAM_BOOL)){ psync_sql_commit_transaction(); set_local_file_conflicted(localfileid, fileid, hash, localpath, psync_find_result(meta, "name", PARAM_STR)->str, upload->taskid); } else{ set_local_file_remote_id(localfileid, fileid, hash); psync_sql_commit_transaction(); } psync_diff_unlock(); psync_free(res); if (unlikely_log(rsize!=fsize) || unlikely_log(memcmp(hashhexsrv, hashhex, PSYNC_HASH_DIGEST_HEXLEN))) return -1; debug(D_NOTICE, "file %s uploaded to %lu/%s", localpath, (long unsigned)folderid, name); return 0; err2: psync_free(buff); err1: psync_apipool_release_bad(api); err0: psync_file_close(fd); err00: psync_diff_unlock(); return -1; } static int upload_range(psync_socket *api, psync_upload_range_list_t *r, upload_list_t *upload, psync_uploadid_t uploadid, psync_file_t fd){ binparam params[]={P_STR("auth", psync_my_auth), P_NUM("uploadoffset", r->uploadoffset), P_NUM("id", r->id), P_NUM("uploadid", uploadid)}; void *buff; uint64_t bw; size_t rd; ssize_t rrd; if (unlikely_log(psync_file_seek(fd, r->off, P_SEEK_SET)==-1) || unlikely_log(!do_send_command(api, "upload_write", strlen("upload_write"), params, ARRAY_SIZE(params), r->len, 0))) return PSYNC_NET_TEMPFAIL; bw=0; buff=psync_malloc(PSYNC_COPY_BUFFER_SIZE); while (bw<r->len){ if (unlikely(upload->stop)){ debug(D_NOTICE, "upload stopped"); goto err0; } psync_wait_statuses_array(requiredstatuses, ARRAY_SIZE(requiredstatuses)); if (r->len-bw>PSYNC_COPY_BUFFER_SIZE) rd=PSYNC_COPY_BUFFER_SIZE; else rd=r->len-bw; rrd=psync_file_read(fd, buff, rd); if (unlikely_log(rrd<=0)) goto err0; bw+=rrd; if (unlikely_log(psync_socket_writeall_upload(api, buff, rrd)!=rrd)) goto err0; upload->uploaded+=rrd; add_bytes_uploaded(rrd); } psync_free(buff); return PSYNC_NET_OK; err0: psync_free(buff); return PSYNC_NET_TEMPFAIL; } static int upload_from_file(psync_socket *api, psync_upload_range_list_t *r, psync_uploadid_t uploadid, upload_list_t *upload){ binparam params[]={P_STR("auth", psync_my_auth), P_NUM("uploadoffset", r->uploadoffset), P_NUM("id", r->id), P_NUM("uploadid", uploadid), P_NUM("fileid", r->file.fileid), P_NUM("hash", r->file.hash), P_NUM("offset", r->off), P_NUM("count", r->len)}; if (unlikely_log(!send_command_no_res(api, "upload_writefromfile", params))) return PSYNC_NET_TEMPFAIL; else{ upload->uploaded+=r->len; add_bytes_uploaded(r->len); return PSYNC_NET_OK; } } static int upload_from_upload(psync_socket *api, psync_upload_range_list_t *r, psync_uploadid_t uploadid, upload_list_t *upload){ binparam params[]={P_STR("auth", psync_my_auth), P_NUM("uploadoffset", r->uploadoffset), P_NUM("id", r->id), P_NUM("uploadid", uploadid), P_NUM("readuploadid", r->uploadid), P_NUM("offset", r->off), P_NUM("count", r->len)}; if (unlikely_log(!send_command_no_res(api, "upload_writefromupload", params))) return PSYNC_NET_TEMPFAIL; else{ upload->uploaded+=r->len; add_bytes_uploaded(r->len); return PSYNC_NET_OK; } } static int upload_get_checksum(psync_socket *api, psync_uploadid_t uploadid, uint32_t id){ binparam params[]={P_STR("auth", psync_my_auth), P_NUM("uploadid", uploadid), P_NUM("id", id)}; if (unlikely_log(!send_command_no_res(api, "upload_info", params))) return PSYNC_NET_TEMPFAIL; else return PSYNC_NET_OK; } static int upload_save(psync_socket *api, psync_fileid_t localfileid, const char *localpath, const unsigned char *hashhex, uint64_t size, psync_uploadid_t uploadid, psync_folderid_t folderid, const char *name, uint64_t taskid, binparam pr){ binparam params[]={P_STR("auth", psync_my_auth), P_NUM("folderid", folderid), P_STR("name", name), P_NUM("uploadid", uploadid), {pr.paramtype, pr.paramnamelen, pr.opts, pr.paramname, {pr.num}} /* specially for Visual Studio compiler */}; psync_sql_res *sres; binresult *res; const binresult *meta; psync_fileid_t fileid; uint64_t result, hash; int ret; psync_diff_lock(); res=send_command(api, "upload_save", params); if (res){ result=psync_find_result(res, "result", PARAM_NUM)->num; if (unlikely(result)){ debug(D_WARNING, "command upload_save returned code %u", (unsigned)result); psync_process_api_error(result); ret=psync_handle_api_result(result); } else{ meta=psync_find_result(res, "metadata", PARAM_HASH); fileid=psync_find_result(meta, "fileid", PARAM_NUM)->num; hash=psync_find_result(meta, "hash", PARAM_NUM)->num; psync_sql_start_transaction(); sres=psync_sql_prep_statement("REPLACE INTO hashchecksum (hash, size, checksum) VALUES (?, ?, ?)"); psync_sql_bind_uint(sres, 1, hash); psync_sql_bind_uint(sres, 2, size); psync_sql_bind_lstring(sres, 3, (const char *)hashhex, PSYNC_HASH_DIGEST_HEXLEN); psync_sql_run_free(sres); if (psync_check_result(meta, "conflicted", PARAM_BOOL)) set_local_file_conflicted(localfileid, fileid, hash, localpath, psync_find_result(meta, "name", PARAM_STR)->str, taskid); else set_local_file_remote_id(localfileid, fileid, hash); psync_sql_commit_transaction(); ret=PSYNC_NET_OK; } psync_free(res); } else ret=PSYNC_NET_TEMPFAIL; psync_diff_unlock(); return ret; } static int upload_big_file(const char *localpath, const unsigned char *hashhex, uint64_t fsize, psync_folderid_t folderid, const char *name, psync_fileid_t localfileid, psync_syncid_t syncid, upload_list_t *upload, psync_uploadid_t uploadid, uint64_t uploadoffset, binparam pr){ psync_socket *api; binresult *res; psync_sql_res *sql; psync_uint_row row; psync_full_result_int *fr; psync_upload_range_list_t *le, *le2; psync_list rlist; uint64_t result; uint32_t rid, respwait, id; psync_file_t fd; int ret; debug(D_NOTICE, "uploading file %s with repeating block inspection", localpath); if (uploadoffset){ debug(D_NOTICE, "resuming from position %lu", (unsigned long)uploadoffset); upload->uploaded+=uploadoffset; add_bytes_uploaded(uploadoffset); } api=psync_apipool_get(); if (unlikely(!api)) return -1; if (!uploadid){ binparam params[]={P_STR("auth", psync_my_auth), P_NUM("filesize", fsize)}; res=send_command(api, "upload_create", params); if (!res) goto err0; result=psync_find_result(res, "result", PARAM_NUM)->num; if (unlikely(result)){ psync_free(res); psync_apipool_release(api); psync_process_api_error(result); debug(D_WARNING, "upload_create returned %lu", (unsigned long)result); if (psync_handle_api_result(result)==PSYNC_NET_TEMPFAIL) return -1; else return 0; } uploadid=psync_find_result(res, "uploadid", PARAM_NUM)->num; psync_free(res); sql=psync_sql_prep_statement("INSERT INTO localfileupload (localfileid, uploadid) VALUES (?, ?)"); psync_sql_bind_uint(sql, 1, localfileid); psync_sql_bind_uint(sql, 2, uploadid); psync_sql_run_free(sql); } psync_list_init(&rlist); if (likely(uploadoffset<fsize)){ le=psync_new(psync_upload_range_list_t); le->uploadoffset=uploadoffset; le->off=uploadoffset; le->len=fsize-uploadoffset; le->type=PSYNC_URANGE_UPLOAD; psync_list_add_tail(&rlist, &le->list); } fd=psync_file_open(localpath, P_O_RDONLY, 0); if (unlikely(fd==INVALID_HANDLE_VALUE)){ debug(D_WARNING, "could not open local file %s", localpath); psync_apipool_release(api); psync_list_for_each_element_call(&rlist, psync_upload_range_list_t, list, psync_free); return -1; } if (likely(uploadoffset<fsize)){ sql=psync_sql_query_rdlock("SELECT fileid, hash FROM localfile WHERE id=?"); psync_sql_bind_uint(sql, 1, localfileid); if ((row=psync_sql_fetch_rowint(sql))){ uint64_t fileid, hash; fileid=row[0]; hash=row[1]; psync_sql_free_result(sql); if (fileid && psync_net_scan_file_for_blocks(api, &rlist, fileid, hash, fd)==PSYNC_NET_TEMPFAIL) goto err1; } else psync_sql_free_result(sql); sql=psync_sql_query_rdlock("SELECT uploadid FROM localfileupload WHERE localfileid=? ORDER BY uploadid DESC LIMIT 5"); psync_sql_bind_uint(sql, 1, localfileid); fr=psync_sql_fetchall_int(sql); for (id=0; id<fr->rows; id++) if (psync_get_result_cell(fr, id, 0)!=uploadid && psync_net_scan_upload_for_blocks(api, &rlist, psync_get_result_cell(fr, id, 0), fd)==PSYNC_NET_TEMPFAIL){ psync_free(fr); goto err1; } psync_free(fr); } rid=0; respwait=0; le=psync_new(psync_upload_range_list_t); le->type=PSYNC_URANGE_LAST; psync_list_add_tail(&rlist, &le->list); psync_list_for_each_element(le, &rlist, psync_upload_range_list_t, list){ if (upload->stop) goto err1; le->uploadoffset=uploadoffset; le->id=++rid; if (le->type==PSYNC_URANGE_LAST){ if (upload_get_checksum(api, uploadid, le->id)) goto err1; else respwait++; } while (respwait && (le->type==PSYNC_URANGE_LAST || psync_socket_pendingdata(api) || psync_select_in(&api->sock, 1, 0)!=SOCKET_ERROR)){ res=get_result(api); if (unlikely_log(!res)) goto err1; respwait--; result=psync_find_result(res, "result", PARAM_NUM)->num; if (unlikely(result)){ id=psync_find_result(res, "id", PARAM_NUM)->num; psync_free(res); psync_process_api_error(result); if (unlikely_log(!id)) goto err1; while (respwait){ res=get_result(api); if (unlikely_log(!res)) goto err1; respwait--; psync_free(res); } psync_list_for_each_element(le2, &rlist, psync_upload_range_list_t, list) if (le2->id==id){ if (le2->type==PSYNC_URANGE_LAST || le2->type==PSYNC_URANGE_UPLOAD){ debug(D_ERROR, "range of type %u failed with error %lu", (unsigned)le2->type, (unsigned long)result); goto err1; } else{ debug(D_WARNING, "range of type %u failed with error %lu, restarting as upload range", (unsigned)le2->type, (unsigned long)result); le2->type=PSYNC_URANGE_UPLOAD; uploadoffset=le2->uploadoffset; le2->off=le2->uploadoffset; le=le2; goto restart; } } debug(D_BUG, "could not find id %u", (unsigned)id); goto err1; } else if (le->type==PSYNC_URANGE_LAST && le->id==psync_find_result(res, "id", PARAM_NUM)->num){ if (unlikely(psync_find_result(res, "size", PARAM_NUM)->num!=fsize)){ debug(D_WARNING, "file size mismatch after upload, expected: %lu, got: %lu", (unsigned long)fsize, (unsigned long)psync_find_result(res, "size", PARAM_NUM)->num); psync_free(res); goto err1; } else if (unlikely(memcmp(psync_find_result(res, PSYNC_CHECKSUM, PARAM_STR)->str, hashhex, PSYNC_HASH_DIGEST_HEXLEN))){ debug(D_WARNING, "hash mismatch after upload, expected: %."NTO_STR(PSYNC_HASH_DIGEST_HEXLEN) "s, got: %."NTO_STR(PSYNC_HASH_DIGEST_HEXLEN)"s", hashhex, psync_find_result(res, PSYNC_CHECKSUM, PARAM_STR)->str); psync_free(res); goto err1; } else assert(respwait==0); } psync_free(res); } restart: if (le->type==PSYNC_URANGE_UPLOAD){ debug(D_NOTICE, "uploading %lu bytes", (unsigned long)le->len); ret=upload_range(api, le, upload, uploadid, fd); } else if (le->type==PSYNC_URANGE_COPY_FILE){ debug(D_NOTICE, "copying %lu bytes from fileid %lu hash %lu offset %lu", (unsigned long)le->len, (unsigned long)le->file.fileid, (unsigned long)le->file.hash, (unsigned long)le->off); ret=upload_from_file(api, le, uploadid, upload); } else if (le->type==PSYNC_URANGE_COPY_UPLOAD){ debug(D_NOTICE, "copying %lu bytes from uploadid %lu offset %lu", (unsigned long)le->len, (unsigned long)le->uploadid, (unsigned long)le->off); ret=upload_from_upload(api, le, uploadid, upload); } else if (le->type==PSYNC_URANGE_LAST) break; else { debug(D_BUG, "Invalid range type %u", (unsigned)le->type); goto err1; } if (unlikely_log(ret!=PSYNC_NET_OK)){ if (ret==PSYNC_NET_TEMPFAIL) goto err1; else goto errp; } respwait++; uploadoffset+=le->len; } psync_list_for_each_element_call(&rlist, psync_upload_range_list_t, list, psync_free); if (psync_file_size(fd)!=fsize){ debug(D_NOTICE, "file %s changed filesize while uploading, restarting task", localpath); ret=PSYNC_NET_TEMPFAIL; } else ret=PSYNC_NET_OK; psync_file_close(fd); if (ret==PSYNC_NET_OK) ret=upload_save(api, localfileid, localpath, hashhex, fsize, uploadid, folderid, name, upload->taskid, pr); if (ret==PSYNC_NET_TEMPFAIL){ psync_apipool_release_bad(api); return -1; } else{ psync_apipool_release(api); return 0; } err1: psync_file_close(fd); psync_list_for_each_element_call(&rlist, psync_upload_range_list_t, list, psync_free); err0: psync_apipool_release_bad(api); return -1; errp: psync_file_close(fd); psync_list_for_each_element_call(&rlist, psync_upload_range_list_t, list, psync_free); psync_apipool_release_bad(api); return 0; } static void delete_uploadid(psync_uploadid_t uploadid){ binparam params[]={P_STR("auth", psync_my_auth), P_NUM("uploadid", uploadid)}; psync_socket *api; binresult *res; api=psync_apipool_get(); if (unlikely(!api)) return; res=send_command(api, "upload_delete", params); if (res) psync_apipool_release(api); else psync_apipool_release_bad(api); psync_free(res); } static void delete_uploadids(psync_fileid_t localfileid){ psync_sql_res *res; psync_full_result_int *rows; uint32_t i; res=psync_sql_query_rdlock("SELECT uploadid FROM localfileupload WHERE localfileid=?"); psync_sql_bind_uint(res, 1, localfileid); rows=psync_sql_fetchall_int(res); if (rows->rows){ for (i=0; i<rows->rows; i++) delete_uploadid(psync_get_result_cell(rows, i, 0)); res=psync_sql_prep_statement("DELETE FROM localfileupload WHERE localfileid=?"); psync_sql_bind_uint(res, 1, localfileid); psync_sql_run_free(res); } psync_free(rows); } static int task_uploadfile(psync_syncid_t syncid, psync_folderid_t localfileid, const char *name, upload_list_t *upload){ psync_sql_res *res; psync_uint_row row; char *localpath, *nname; psync_file_lock_t *lock; psync_folderid_t folderid; psync_uploadid_t uploadid; uint64_t fsize, ufsize; psync_stat_t st; unsigned char hashhex[PSYNC_HASH_DIGEST_HEXLEN], uhashhex[PSYNC_HASH_DIGEST_HEXLEN], phashhex[PSYNC_HASH_DIGEST_HEXLEN]; binparam pr; int ret; psync_wait_statuses_array(requiredstatuses, ARRAY_SIZE(requiredstatuses)); if (upload->stop) return -1; localpath=psync_local_path_for_local_file(localfileid, NULL); if (unlikely(!localpath)){ debug(D_WARNING, "could not find local file %s (id %lu)", name, (unsigned long)localfileid); return 0; } if (!psync_stat(localpath, &st) && psync_stat_mtime(&st)>=psync_timer_time()-PSYNC_UPLOAD_OLDER_THAN_SEC){ time_t ctime; debug(D_NOTICE, "file %s is too new, waiting for upload", localpath); ctime=psync_timer_time(); psync_apipool_prepare(); if (ctime<psync_stat_mtime(&st)-2) debug(D_NOTICE, "file %s has a modification time in the future, skipping waits", localpath); else{ ret=0; do { psync_milisleep((psync_stat_mtime(&st)+PSYNC_UPLOAD_OLDER_THAN_SEC-ctime)*1000+500); ctime=psync_timer_time(); if (psync_stat(localpath, &st)){ debug(D_NOTICE, "can not stat %s anymore, failing for now", localpath); psync_free(localpath); return -1; } } while (psync_stat_mtime(&st)>=psync_timer_time()-PSYNC_UPLOAD_OLDER_THAN_SEC && ++ret<=10); if (ret==10){ debug(D_NOTICE, "file %s kept changing %d times, skipping for now", localpath, ret); psync_free(localpath); return -1; } debug(D_NOTICE, "file %s got old enough", localpath); } } lock=psync_lock_file(localpath); if (!lock){ debug(D_NOTICE, "file %s is currently locked, skipping for now", localpath); psync_free(localpath); psync_milisleep(PSYNC_SLEEP_ON_LOCKED_FILE); return -1; } res=psync_sql_query_rdlock("SELECT uploadid FROM localfileupload WHERE localfileid=? ORDER BY uploadid DESC LIMIT 1"); psync_sql_bind_uint(res, 1, localfileid); if ((row=psync_sql_fetch_rowint(res))) uploadid=row[0]; else uploadid=0; psync_sql_free_result(res); ufsize=0; if (uploadid){ ret=psync_get_upload_checksum(uploadid, uhashhex, &ufsize); if (ret==PSYNC_NET_TEMPFAIL){ psync_unlock_file(lock); psync_free(localpath); return -1; } else if (ret==PSYNC_NET_PERMFAIL) uploadid=0; } nname=psync_strnormalize_filename(name); if (uploadid) ret=psync_get_local_file_checksum_part(localpath, hashhex, &fsize, phashhex, ufsize); else ret=psync_get_local_file_checksum(localpath, hashhex, &fsize); if (ret){ debug(D_WARNING, "could not open local file %s, deleting it from localfile", localpath); res=psync_sql_prep_statement("DELETE FROM localfile WHERE id=?"); psync_sql_bind_uint(res, 1, localfileid); psync_sql_run_free(res); psync_unlock_file(lock); psync_free(nname); psync_free(localpath); return 0; } if (fsize!=upload->filesize){ pthread_mutex_lock(&current_uploads_mutex); psync_status.bytestouploadcurrent-=upload->filesize; psync_status.bytestouploadcurrent+=fsize; pthread_mutex_unlock(&current_uploads_mutex); upload->filesize=fsize; } res=psync_sql_prep_statement("UPDATE localfile SET size=?, checksum=? WHERE id=?"); psync_sql_bind_uint(res, 1, fsize); psync_sql_bind_lstring(res, 2, (char *)hashhex, PSYNC_HASH_DIGEST_HEXLEN); psync_sql_bind_uint(res, 3, localfileid); psync_sql_run_free(res); res=psync_sql_query_rdlock("SELECT s.folderid FROM localfile f, syncedfolder s WHERE f.id=? AND f.localparentfolderid=s.localfolderid AND s.syncid=?"); psync_sql_bind_uint(res, 1, localfileid); psync_sql_bind_uint(res, 2, syncid); if (likely_log(row=psync_sql_fetch_rowint(res))) folderid=row[0]; else{ debug(D_WARNING, "could not get remote folderid for local file %lu", (unsigned long)localfileid); psync_sql_free_result(res); psync_unlock_file(lock); psync_free(nname); psync_free(localpath); return 0; } psync_sql_free_result(res); ret=check_file_if_exists(hashhex, fsize, folderid, nname, localfileid); /* PSYNC_MIN_SIZE_FOR_EXISTS_CHECK should be low enough not to waste bandwidth and high enough * not to waste a roundtrip to the server. Few kilos should be fine */ if (ret==0 && fsize>=PSYNC_MIN_SIZE_FOR_EXISTS_CHECK) ret=copy_file_if_exists(hashhex, fsize, folderid, nname, localfileid); if (ret==1 || ret==-1){ psync_unlock_file(lock); psync_free(nname); psync_free(localpath); return ret==1?0:-1; } memcpy(upload->hash, hashhex, PSYNC_HASH_DIGEST_HEXLEN); res=psync_sql_query_rdlock("SELECT hash FROM localfile WHERE hash IS NOT NULL AND id=?"); psync_sql_bind_uint(res, 1, localfileid); if ((row=psync_sql_fetch_rowint(res))){ pr.paramtype=PARAM_NUM; pr.paramnamelen=6; pr.paramname="ifhash"; pr.num=row[0]; } else{ pr.paramtype=PARAM_STR; pr.paramnamelen=6; pr.paramname="ifhash"; pr.opts=3; pr.str="new"; } psync_sql_free_result(res); debug(D_NOTICE, "uploading file %s", localpath); if (fsize<=PSYNC_MIN_SIZE_FOR_CHECKSUMS) ret=upload_file(localpath, hashhex, fsize, folderid, nname, localfileid, syncid, upload, pr); else{ if (uploadid && !memcmp(phashhex, uhashhex, PSYNC_HASH_DIGEST_HEXLEN)) ret=upload_big_file(localpath, hashhex, fsize, folderid, nname, localfileid, syncid, upload, uploadid, ufsize, pr); else{ if (uploadid && memcmp(phashhex, uhashhex, PSYNC_HASH_DIGEST_HEXLEN)) debug(D_WARNING, "restarting upload due to checksum mismatch up to offset %lu, expected: %."NTO_STR(PSYNC_HASH_DIGEST_HEXLEN) "s, got: %."NTO_STR(PSYNC_HASH_DIGEST_HEXLEN)"s", (unsigned long)ufsize, phashhex, uhashhex); ret=upload_big_file(localpath, hashhex, fsize, folderid, nname, localfileid, syncid, upload, 0, 0, pr); } } psync_unlock_file(lock); psync_free(nname); psync_free(localpath); if (!ret) delete_uploadids(localfileid); return ret; } static void task_run_upload_file_thread(void *ptr){ upload_task_t *ut; psync_sql_res *res; ut=(upload_task_t *)ptr; if (task_uploadfile(ut->upllist.syncid, ut->upllist.localfileid, ut->filename, &ut->upllist)){ psync_milisleep(PSYNC_SLEEP_ON_FAILED_DOWNLOAD); res=psync_sql_prep_statement("UPDATE task SET inprogress=0 WHERE id=?"); psync_sql_bind_uint(res, 1, ut->upllist.taskid); psync_sql_run_free(res); psync_wake_upload(); } else{ res=psync_sql_prep_statement("DELETE FROM task WHERE id=?"); psync_sql_bind_uint(res, 1, ut->upllist.taskid); psync_sql_run_free(res); } pthread_mutex_lock(&current_uploads_mutex); psync_status.bytestouploadcurrent-=ut->upllist.filesize; psync_status.bytesuploaded-=ut->upllist.uploaded; psync_status.filesuploading--; if (!psync_status.filesuploading){ psync_status.bytesuploaded=0; psync_status.bytestouploadcurrent=0; } psync_list_del(&ut->upllist.list); wake_upload_when_ready(); pthread_mutex_unlock(&current_uploads_mutex); psync_status_recalc_to_upload_async(); psync_free(ut); } static int task_run_uploadfile(uint64_t taskid, psync_syncid_t syncid, psync_folderid_t localfileid, const char *filename){ psync_sql_res *res; upload_task_t *ut; psync_uint_row row; uint64_t filesize; size_t len; int stop; res=psync_sql_query_rdlock("SELECT size FROM localfile WHERE id=?"); psync_sql_bind_uint(res, 1, localfileid); row=psync_sql_fetch_rowint(res); if (likely(row)){ filesize=row[0]; psync_sql_free_result(res); } else{ psync_sql_free_result(res); debug(D_WARNING, "could not get size for local file %s (localfileid %lu)", filename, (unsigned long)localfileid); return 0; } res=psync_sql_prep_statement("UPDATE task SET inprogress=1 WHERE id=?"); psync_sql_bind_uint(res, 1, taskid); psync_sql_run_free(res); len=strlen(filename); ut=(upload_task_t *)psync_malloc(offsetof(upload_task_t, filename)+len+1); ut->upllist.taskid=taskid; ut->upllist.localfileid=localfileid; ut->upllist.filesize=filesize; ut->upllist.uploaded=0; ut->upllist.syncid=syncid; ut->upllist.stop=0; ut->upllist.hash[0]=0; memcpy(ut->filename, filename, len+1); stop=0; pthread_mutex_lock(&current_uploads_mutex); psync_list_add_tail(&uploads, &ut->upllist.list); while (!ut->upllist.stop && (psync_status.filesuploading>=PSYNC_MAX_PARALLEL_UPLOADS || psync_status.bytestouploadcurrent-psync_status.bytesuploaded>PSYNC_START_NEW_UPLOADS_TRESHOLD)){ current_uploads_waiters++; pthread_cond_wait(&current_uploads_cond, &current_uploads_mutex); current_uploads_waiters--; } if (unlikely(ut->upllist.stop)){ psync_list_del(&ut->upllist.list); stop=1; } else{ psync_status.bytestouploadcurrent+=filesize; psync_status.filesuploading++; } pthread_mutex_unlock(&current_uploads_mutex); if (stop){ psync_free(ut); res=psync_sql_prep_statement("UPDATE task SET inprogress=0 WHERE id=?"); psync_sql_bind_uint(res, 1, taskid); psync_sql_run_free(res); } else{ psync_status_send_update(); psync_run_thread1("upload file", task_run_upload_file_thread, ut); } return -1; } static int task_deletefile(psync_fileid_t fileid){ binparam params[]={P_STR("auth", psync_my_auth), P_NUM("fileid", fileid)}; int ret; task_wait_no_uploads(); ret=run_command("deletefile", params); if (likely(!ret)) debug(D_NOTICE, "remote fileid %lu deleted", (long unsigned)fileid); return ret; } static int task_deletefolderrec(psync_folderid_t folderid){ binparam params[]={P_STR("auth", psync_my_auth), P_NUM("folderid", folderid)}; int ret; task_wait_no_uploads(); ret=run_command("deletefolderrecursive", params); if (likely(!ret)) debug(D_NOTICE, "remote folder %lu deleted", (long unsigned)folderid); return ret; } static int upload_task(uint64_t taskid, uint32_t type, psync_syncid_t syncid, uint64_t itemid, uint64_t localitemid, uint64_t newitemid, const char *name, psync_syncid_t newsyncid){ int res; switch (type){ case PSYNC_CREATE_REMOTE_FOLDER: res=task_createfolder(syncid, localitemid, name); break; case PSYNC_RENAME_REMOTE_FILE: res=task_renamefile(newsyncid, localitemid, newitemid, name); break; case PSYNC_RENAME_REMOTE_FOLDER: res=task_renamefolder(newsyncid, localitemid, newitemid, name); break; case PSYNC_UPLOAD_FILE: res=task_run_uploadfile(taskid, syncid, localitemid, name); break; case PSYNC_DELETE_REMOTE_FILE: res=task_deletefile(itemid); break; case PSYNC_DELREC_REMOTE_FOLDER: res=task_deletefolderrec(itemid); break; default: debug(D_BUG, "invalid task type %u", (unsigned)type); res=0; break; } if (res && type!=PSYNC_UPLOAD_FILE) debug(D_WARNING, "task of type %u, syncid %u, id %lu localid %lu failed", (unsigned)type, (unsigned)syncid, (unsigned long)itemid, (unsigned long)localitemid); return res; } static void upload_thread(){ psync_sql_res *res; psync_variant *row; uint64_t taskid; uint32_t type; while (psync_do_run){ psync_wait_statuses_array(requiredstatuses, ARRAY_SIZE(requiredstatuses)); row=psync_sql_row("SELECT id, type, syncid, itemid, localitemid, newitemid, name, newsyncid FROM task WHERE type&" NTO_STR(PSYNC_TASK_DWLUPL_MASK)"="NTO_STR(PSYNC_TASK_UPLOAD)" AND inprogress=0 ORDER BY id LIMIT 1"); if (row){ taskid=psync_get_number(row[0]); type=psync_get_number(row[1]); if (!upload_task(taskid, type, psync_get_number(row[2]), psync_get_number(row[3]), psync_get_number(row[4]), psync_get_number_or_null(row[5]), psync_get_string_or_null(row[6]), psync_get_number_or_null(row[7]))){ res=psync_sql_prep_statement("DELETE FROM task WHERE id=?"); psync_sql_bind_uint(res, 1, taskid); psync_sql_run_free(res); } else if (type!=PSYNC_UPLOAD_FILE) psync_milisleep(PSYNC_SLEEP_ON_FAILED_UPLOAD); psync_free(row); continue; } pthread_mutex_lock(&upload_mutex); if (!upload_wakes) pthread_cond_wait(&upload_cond, &upload_mutex); upload_wakes=0; pthread_mutex_unlock(&upload_mutex); } } void psync_wake_upload(){ pthread_mutex_lock(&upload_mutex); if (!upload_wakes++) pthread_cond_signal(&upload_cond); pthread_mutex_unlock(&upload_mutex); } void psync_upload_init(){ psync_timer_exception_handler(psync_wake_upload); psync_run_thread("upload main", upload_thread); } void psync_delete_upload_tasks_for_file(psync_fileid_t localfileid){ psync_sql_res *res; upload_list_t *upl; res=psync_sql_prep_statement("DELETE FROM task WHERE type=? AND localitemid=?"); psync_sql_bind_uint(res, 1, PSYNC_UPLOAD_FILE); psync_sql_bind_uint(res, 2, localfileid); psync_sql_run(res); if (psync_sql_affected_rows()) psync_status_recalc_to_upload_async(); psync_sql_free_result(res); pthread_mutex_lock(&current_uploads_mutex); psync_list_for_each_element(upl, &uploads, upload_list_t, list) if (upl->localfileid==localfileid) upl->stop=1; pthread_mutex_unlock(&current_uploads_mutex); } void psync_stop_sync_upload(psync_syncid_t syncid){ upload_list_t *upl; psync_sql_res *res; res=psync_sql_prep_statement("DELETE FROM task WHERE syncid=? AND type&"NTO_STR(PSYNC_TASK_DWLUPL_MASK)"="NTO_STR(PSYNC_TASK_UPLOAD)); psync_sql_bind_uint(res, 1, syncid); psync_sql_run_free(res); pthread_mutex_lock(&current_uploads_mutex); psync_list_for_each_element(upl, &uploads, upload_list_t, list) if (upl->syncid==syncid) upl->stop=1; pthread_mutex_unlock(&current_uploads_mutex); psync_status_recalc_to_upload_async(); } void psync_stop_all_upload(){ upload_list_t *upl; pthread_mutex_lock(&current_uploads_mutex); psync_list_for_each_element(upl, &uploads, upload_list_t, list) upl->stop=1; pthread_mutex_unlock(&current_uploads_mutex); }
89457.c
/* Copyright (c) 2015-2018, Linaro Limited * Copyright (c) 2019, Nokia * All rights reserved. * * SPDX-License-Identifier: BSD-3-Clause */ #include <odp_debug_internal.h> #include <odp_packet_io_internal.h> #include <odp_errno_define.h> #include <odp/api/system_info.h> #include <odp_shm_internal.h> #include <odp_ring_ptr_internal.h> #include <odp_global_data.h> #include <errno.h> #include <fcntl.h> #include <sys/mman.h> #include <sys/stat.h> #include <unistd.h> #define IPC_ODP_DEBUG_PRINT 0 #define IPC_ODP_DBG(fmt, ...) \ do { \ if (IPC_ODP_DEBUG_PRINT == 1) \ ODP_DBG(fmt, ##__VA_ARGS__);\ } while (0) /* Burst size for IPC free operations */ #define IPC_BURST_SIZE 32 /* that struct is exported to shared memory, so that processes can find * each other. */ struct pktio_info { struct { /* Pool base address */ void *base_addr; /* number of buffer*/ char pool_name[ODP_POOL_NAME_LEN]; /* 1 if master finished creation of all shared objects */ int init_done; /* IPC ring size */ uint32_t ring_size; /* IPC ring mask */ uint32_t ring_mask; } master; struct { /* Pool base address */ void *base_addr; char pool_name[ODP_POOL_NAME_LEN]; /* pid of the slave process written to shm and * used by master to look up memory created by * slave */ int pid; int init_done; } slave; } ODP_PACKED; typedef struct { /* TX */ struct { /* ODP ring for IPC msg packets indexes transmitted to shared * memory */ ring_ptr_t *send; /* ODP ring for IPC msg packets indexes already processed by * remote process */ ring_ptr_t *free; } tx; /* RX */ struct { /* ODP ring for IPC msg packets indexes received from shared * memory (from remote process) */ ring_ptr_t *recv; /* odp ring for ipc msg packets indexes already processed by * current process */ ring_ptr_t *free; /* local cache to keep packet order right */ ring_ptr_t *cache; } rx; /* slave */ /* Remote pool mdata base addr */ void *pool_mdata_base; /* Remote pool base address for offset calculation */ void *remote_base_addr; odp_pool_t pool; /**< Pool of main process */ enum { PKTIO_TYPE_IPC_MASTER = 0, /**< Master is the process which creates shm */ PKTIO_TYPE_IPC_SLAVE /**< Slave is the process which connects to shm */ } type; /**< define if it's master or slave process */ odp_atomic_u32_t ready; /**< 1 - pktio is ready and can recv/send packet, 0 - not yet ready */ /* Local copy of IPC ring size */ uint32_t ring_size; /* Local copy IPC ring mask */ uint32_t ring_mask; struct pktio_info *pinfo; odp_shm_t pinfo_shm; odp_shm_t remote_pool_shm; /**< shm of remote pool get with _ipc_map_remote_pool() */ } pkt_ipc_t; ODP_STATIC_ASSERT(PKTIO_PRIVATE_SIZE >= sizeof(pkt_ipc_t), "PKTIO_PRIVATE_SIZE too small"); static inline pkt_ipc_t *pkt_priv(pktio_entry_t *pktio_entry) { return (pkt_ipc_t *)(uintptr_t)(pktio_entry->s.pkt_priv); } /* MAC address for the "ipc" interface */ static const char pktio_ipc_mac[] = {0x12, 0x12, 0x12, 0x12, 0x12, 0x12}; static odp_shm_t _ipc_map_remote_pool(const char *name, int pid); /* create the ring */ static ring_ptr_t *_ring_create(const char *name, uint32_t count, uint32_t shm_flags) { ring_ptr_t *r; size_t ring_size; odp_shm_t shm; if (odp_global_ro.shm_single_va) shm_flags |= ODP_SHM_SINGLE_VA; /* count must be a power of 2 */ if (!CHECK_IS_POWER2(count)) { ODP_ERR("Requested size is invalid, must be a power of 2\n"); __odp_errno = EINVAL; return NULL; } ring_size = sizeof(ring_ptr_t) + count * sizeof(void *); /* reserve a memory zone for this ring.*/ shm = odp_shm_reserve(name, ring_size, ODP_CACHE_LINE_SIZE, shm_flags); r = odp_shm_addr(shm); if (r != NULL) { /* init the ring structure */ ring_ptr_init(r); } else { __odp_errno = ENOMEM; ODP_ERR("Cannot reserve memory\n"); } return r; } static int _ring_destroy(const char *name) { odp_shm_t shm = odp_shm_lookup(name); if (shm != ODP_SHM_INVALID) return odp_shm_free(shm); return 0; } /** * Return the number of entries in a ring. */ static uint32_t _ring_count(ring_ptr_t *r, uint32_t mask) { uint32_t prod_tail = odp_atomic_load_u32(&r->r.w_tail); uint32_t cons_tail = odp_atomic_load_u32(&r->r.r_tail); return (prod_tail - cons_tail) & mask; } /** * Return the number of free entries in a ring. */ static uint32_t _ring_free_count(ring_ptr_t *r, uint32_t mask) { uint32_t prod_tail = odp_atomic_load_u32(&r->r.w_tail); uint32_t cons_tail = odp_atomic_load_u32(&r->r.r_tail); return (cons_tail - prod_tail - 1) & mask; } static const char *_ipc_odp_buffer_pool_shm_name(odp_pool_t pool_hdl) { pool_t *pool; odp_shm_t shm; odp_shm_info_t info; pool = pool_entry_from_hdl(pool_hdl); shm = pool->shm; odp_shm_info(shm, &info); return info.name; } static int _ipc_master_start(pktio_entry_t *pktio_entry) { pkt_ipc_t *pktio_ipc = pkt_priv(pktio_entry); struct pktio_info *pinfo = pktio_ipc->pinfo; odp_shm_t shm; if (pinfo->slave.init_done == 0) return -1; shm = _ipc_map_remote_pool(pinfo->slave.pool_name, pinfo->slave.pid); if (shm == ODP_SHM_INVALID) { ODP_DBG("no pool file %s for pid %d\n", pinfo->slave.pool_name, pinfo->slave.pid); return -1; } pktio_ipc->remote_pool_shm = shm; pktio_ipc->remote_base_addr = pinfo->slave.base_addr; pktio_ipc->pool_mdata_base = (char *)odp_shm_addr(shm); odp_atomic_store_u32(&pktio_ipc->ready, 1); IPC_ODP_DBG("%s started.\n", pktio_entry->s.name); return 0; } static int _ipc_init_master(pktio_entry_t *pktio_entry, const char *dev, odp_pool_t pool_hdl) { pkt_ipc_t *pktio_ipc = pkt_priv(pktio_entry); char ipc_shm_name[ODP_POOL_NAME_LEN + sizeof("_m_prod")]; struct pktio_info *pinfo; const char *pool_name; pool_t *pool = pool_entry_from_hdl(pool_hdl); uint32_t ring_size; uint32_t ring_mask; if ((uint64_t)ROUNDUP_POWER2_U32(pool->num + 1) > UINT32_MAX) { ODP_ERR("Too large packet pool\n"); return -1; } /* Ring must be able to store all packets in the pool */ ring_size = ROUNDUP_POWER2_U32(pool->num + 1); /* Ring size has to larger than burst size */ if (ring_size <= IPC_BURST_SIZE) ring_size = ROUNDUP_POWER2_U32(IPC_BURST_SIZE + 1); ring_mask = ring_size - 1; pktio_ipc->ring_size = ring_size; pktio_ipc->ring_mask = ring_mask; if (strlen(dev) > (ODP_POOL_NAME_LEN - sizeof("_m_prod"))) { ODP_ERR("too big ipc name\n"); return -1; } pktio_ipc->rx.cache = _ring_create("ipc_rx_cache", ring_size, 0); if (!pktio_ipc->rx.cache) { ODP_ERR("pid %d unable to create ipc rx cache\n", getpid()); return -1; } /* generate name in shm like ipc_pktio_r for * to be processed packets ring. */ snprintf(ipc_shm_name, sizeof(ipc_shm_name), "%s_m_prod", dev); pktio_ipc->tx.send = _ring_create(ipc_shm_name, ring_size, ODP_SHM_PROC | ODP_SHM_EXPORT); if (!pktio_ipc->tx.send) { ODP_ERR("pid %d unable to create ipc ring %s name\n", getpid(), ipc_shm_name); return -1; } ODP_DBG("Created IPC ring: %s, count %d, free %d\n", ipc_shm_name, _ring_count(pktio_ipc->tx.send, ring_mask), _ring_free_count(pktio_ipc->tx.send, ring_mask)); /* generate name in shm like ipc_pktio_p for * already processed packets */ snprintf(ipc_shm_name, sizeof(ipc_shm_name), "%s_m_cons", dev); pktio_ipc->tx.free = _ring_create(ipc_shm_name, ring_size, ODP_SHM_PROC | ODP_SHM_EXPORT); if (!pktio_ipc->tx.free) { ODP_ERR("pid %d unable to create ipc ring %s name\n", getpid(), ipc_shm_name); goto free_m_prod; } ODP_DBG("Created IPC ring: %s, count %d, free %d\n", ipc_shm_name, _ring_count(pktio_ipc->tx.free, ring_mask), _ring_free_count(pktio_ipc->tx.free, ring_mask)); snprintf(ipc_shm_name, sizeof(ipc_shm_name), "%s_s_prod", dev); pktio_ipc->rx.recv = _ring_create(ipc_shm_name, ring_size, ODP_SHM_PROC | ODP_SHM_EXPORT); if (!pktio_ipc->rx.recv) { ODP_ERR("pid %d unable to create ipc ring %s name\n", getpid(), ipc_shm_name); goto free_m_cons; } ODP_DBG("Created IPC ring: %s, count %d, free %d\n", ipc_shm_name, _ring_count(pktio_ipc->rx.recv, ring_mask), _ring_free_count(pktio_ipc->rx.recv, ring_mask)); snprintf(ipc_shm_name, sizeof(ipc_shm_name), "%s_s_cons", dev); pktio_ipc->rx.free = _ring_create(ipc_shm_name, ring_size, ODP_SHM_PROC | ODP_SHM_EXPORT); if (!pktio_ipc->rx.free) { ODP_ERR("pid %d unable to create ipc ring %s name\n", getpid(), ipc_shm_name); goto free_s_prod; } ODP_DBG("Created IPC ring: %s, count %d, free %d\n", ipc_shm_name, _ring_count(pktio_ipc->rx.free, ring_mask), _ring_free_count(pktio_ipc->rx.free, ring_mask)); /* Set up pool name for remote info */ pinfo = pktio_ipc->pinfo; pool_name = _ipc_odp_buffer_pool_shm_name(pool_hdl); if (strlen(pool_name) > ODP_POOL_NAME_LEN) { ODP_ERR("pid %d ipc pool name %s is too big %d\n", getpid(), pool_name, strlen(pool_name)); goto free_s_prod; } memcpy(pinfo->master.pool_name, pool_name, strlen(pool_name)); /* Export ring info for the slave process to use */ pinfo->master.ring_size = ring_size; pinfo->master.ring_mask = ring_mask; pinfo->master.base_addr = odp_shm_addr(pool->shm); pinfo->slave.base_addr = 0; pinfo->slave.pid = 0; pinfo->slave.init_done = 0; pktio_ipc->pool = pool_hdl; ODP_DBG("Pre init... DONE.\n"); pinfo->master.init_done = 1; _ipc_master_start(pktio_entry); return 0; free_s_prod: snprintf(ipc_shm_name, sizeof(ipc_shm_name), "%s_s_prod", dev); _ring_destroy(ipc_shm_name); free_m_cons: snprintf(ipc_shm_name, sizeof(ipc_shm_name), "%s_m_cons", dev); _ring_destroy(ipc_shm_name); free_m_prod: snprintf(ipc_shm_name, sizeof(ipc_shm_name), "%s_m_prod", dev); _ring_destroy(ipc_shm_name); return -1; } static void _ipc_export_pool(struct pktio_info *pinfo, odp_pool_t pool_hdl) { pool_t *pool = pool_entry_from_hdl(pool_hdl); snprintf(pinfo->slave.pool_name, ODP_POOL_NAME_LEN, "%s", _ipc_odp_buffer_pool_shm_name(pool_hdl)); pinfo->slave.pid = odp_global_ro.main_pid; pinfo->slave.base_addr = odp_shm_addr(pool->shm); } static odp_shm_t _ipc_map_remote_pool(const char *name, int pid) { odp_shm_t shm; char rname[ODP_SHM_NAME_LEN]; snprintf(rname, ODP_SHM_NAME_LEN, "remote-%s", name); shm = odp_shm_import(name, pid, rname); if (shm == ODP_SHM_INVALID) { ODP_ERR("unable map %s\n", name); return ODP_SHM_INVALID; } IPC_ODP_DBG("Mapped remote pool %s to local %s\n", name, rname); return shm; } static void *_ipc_shm_map(char *name, int pid) { odp_shm_t shm; shm = odp_shm_import(name, pid, name); if (ODP_SHM_INVALID == shm) { ODP_ERR("unable to map: %s\n", name); return NULL; } return odp_shm_addr(shm); } static int _ipc_init_slave(const char *dev, pktio_entry_t *pktio_entry, odp_pool_t pool_hdl) { pkt_ipc_t *pktio_ipc = pkt_priv(pktio_entry); pool_t *pool = pool_entry_from_hdl(pool_hdl); uint32_t ring_size = pktio_ipc->pinfo->master.ring_size; if (strlen(dev) > (ODP_POOL_NAME_LEN - sizeof("_slave_r"))) { ODP_ERR("Too big ipc name\n"); return -1; } /* Check that IPC rings are able to store all packets */ if (pool->num >= ring_size) { ODP_ERR("Slave process packet pool too large. Master process " "packet pool has to be larger than slave pool.\n"); return -1; } pktio_ipc->rx.cache = _ring_create("ipc_rx_cache", ring_size, 0); if (!pktio_ipc->rx.cache) { ODP_ERR("Pid %d unable to create ipc rx cache\n", getpid()); return -1; } pktio_ipc->ring_size = ring_size; pktio_ipc->ring_mask = pktio_ipc->pinfo->master.ring_mask; pktio_ipc->pool = pool_hdl; return 0; } static int _ipc_slave_start(pktio_entry_t *pktio_entry) { pkt_ipc_t *pktio_ipc = pkt_priv(pktio_entry); char ipc_shm_name[ODP_POOL_NAME_LEN + sizeof("_slave_r")]; struct pktio_info *pinfo; odp_shm_t shm; char tail[ODP_POOL_NAME_LEN]; char dev[ODP_POOL_NAME_LEN]; int pid; uint32_t ring_mask = pktio_ipc->ring_mask; if (sscanf(pktio_entry->s.name, "ipc:%d:%s", &pid, tail) != 2) { ODP_ERR("wrong pktio name\n"); return -1; } sprintf(dev, "ipc:%s", tail); snprintf(ipc_shm_name, sizeof(ipc_shm_name), "%s_m_prod", dev); pktio_ipc->rx.recv = _ipc_shm_map(ipc_shm_name, pid); if (!pktio_ipc->rx.recv) { ODP_DBG("pid %d unable to find ipc ring %s name\n", getpid(), dev); sleep(1); return -1; } ODP_DBG("Connected IPC ring: %s, count %d, free %d\n", ipc_shm_name, _ring_count(pktio_ipc->rx.recv, ring_mask), _ring_free_count(pktio_ipc->rx.recv, ring_mask)); snprintf(ipc_shm_name, sizeof(ipc_shm_name), "%s_m_cons", dev); pktio_ipc->rx.free = _ipc_shm_map(ipc_shm_name, pid); if (!pktio_ipc->rx.free) { ODP_ERR("pid %d unable to find ipc ring %s name\n", getpid(), dev); goto free_m_prod; } ODP_DBG("Connected IPC ring: %s, count %d, free %d\n", ipc_shm_name, _ring_count(pktio_ipc->rx.free, ring_mask), _ring_free_count(pktio_ipc->rx.free, ring_mask)); snprintf(ipc_shm_name, sizeof(ipc_shm_name), "%s_s_prod", dev); pktio_ipc->tx.send = _ipc_shm_map(ipc_shm_name, pid); if (!pktio_ipc->tx.send) { ODP_ERR("pid %d unable to find ipc ring %s name\n", getpid(), dev); goto free_m_cons; } ODP_DBG("Connected IPC ring: %s, count %d, free %d\n", ipc_shm_name, _ring_count(pktio_ipc->tx.send, ring_mask), _ring_free_count(pktio_ipc->tx.send, ring_mask)); snprintf(ipc_shm_name, sizeof(ipc_shm_name), "%s_s_cons", dev); pktio_ipc->tx.free = _ipc_shm_map(ipc_shm_name, pid); if (!pktio_ipc->tx.free) { ODP_ERR("pid %d unable to find ipc ring %s name\n", getpid(), dev); goto free_s_prod; } ODP_DBG("Connected IPC ring: %s, count %d, free %d\n", ipc_shm_name, _ring_count(pktio_ipc->tx.free, ring_mask), _ring_free_count(pktio_ipc->tx.free, ring_mask)); /* Get info about remote pool */ pinfo = pktio_ipc->pinfo; shm = _ipc_map_remote_pool(pinfo->master.pool_name, pid); pktio_ipc->remote_pool_shm = shm; pktio_ipc->pool_mdata_base = (char *)odp_shm_addr(shm); pktio_ipc->remote_base_addr = pinfo->master.base_addr; _ipc_export_pool(pinfo, pktio_ipc->pool); odp_atomic_store_u32(&pktio_ipc->ready, 1); pinfo->slave.init_done = 1; ODP_DBG("%s started.\n", pktio_entry->s.name); return 0; free_s_prod: snprintf(ipc_shm_name, sizeof(ipc_shm_name), "%s_s_prod", dev); shm = odp_shm_lookup(ipc_shm_name); odp_shm_free(shm); free_m_cons: snprintf(ipc_shm_name, sizeof(ipc_shm_name), "%s_m_cons", dev); shm = odp_shm_lookup(ipc_shm_name); odp_shm_free(shm); free_m_prod: snprintf(ipc_shm_name, sizeof(ipc_shm_name), "%s_m_prod", dev); shm = odp_shm_lookup(ipc_shm_name); odp_shm_free(shm); return -1; } static int ipc_pktio_open(odp_pktio_t id ODP_UNUSED, pktio_entry_t *pktio_entry, const char *dev, odp_pool_t pool) { pkt_ipc_t *pktio_ipc = pkt_priv(pktio_entry); int ret = 0; int pid; struct pktio_info *pinfo; char name[ODP_POOL_NAME_LEN + sizeof("_info")]; char tail[ODP_POOL_NAME_LEN]; odp_shm_t shm; if (strncmp(dev, "ipc", 3)) return -1; odp_atomic_init_u32(&pktio_ipc->ready, 0); /* Shared info about remote pktio */ if (sscanf(dev, "ipc:%d:%s", &pid, tail) == 2) { pktio_ipc->type = PKTIO_TYPE_IPC_SLAVE; snprintf(name, sizeof(name), "ipc:%s_info", tail); IPC_ODP_DBG("lookup for name %s for pid %d\n", name, pid); shm = odp_shm_import(name, pid, name); if (ODP_SHM_INVALID == shm) return -1; pinfo = odp_shm_addr(shm); if (!pinfo->master.init_done) { odp_shm_free(shm); return -1; } pktio_ipc->pinfo = pinfo; pktio_ipc->pinfo_shm = shm; ODP_DBG("process %d is slave\n", getpid()); ret = _ipc_init_slave(name, pktio_entry, pool); } else { pktio_ipc->type = PKTIO_TYPE_IPC_MASTER; snprintf(name, sizeof(name), "%s_info", dev); shm = odp_shm_reserve(name, sizeof(struct pktio_info), ODP_CACHE_LINE_SIZE, ODP_SHM_EXPORT | ODP_SHM_SINGLE_VA); if (ODP_SHM_INVALID == shm) { ODP_ERR("can not create shm %s\n", name); return -1; } pinfo = odp_shm_addr(shm); pinfo->master.init_done = 0; pinfo->master.pool_name[0] = 0; pktio_ipc->pinfo = pinfo; pktio_ipc->pinfo_shm = shm; ODP_DBG("process %d is master\n", getpid()); ret = _ipc_init_master(pktio_entry, dev, pool); } if (ret) odp_shm_free(shm); return ret; } static void _ipc_free_ring_packets(pktio_entry_t *pktio_entry, ring_ptr_t *r, uint32_t r_mask) { pkt_ipc_t *pktio_ipc = pkt_priv(pktio_entry); uintptr_t offsets[IPC_BURST_SIZE]; int ret; void **rbuf_p; int i; void *addr; pool_t *pool; if (!r) return; pool = pool_entry_from_hdl(pktio_ipc->pool); addr = odp_shm_addr(pool->shm); rbuf_p = (void *)&offsets; while (1) { ret = ring_ptr_deq_multi(r, r_mask, rbuf_p, IPC_BURST_SIZE); if (ret <= 0) break; for (i = 0; i < ret; i++) { odp_packet_hdr_t *phdr; odp_packet_t pkt; phdr = (void *)((uint8_t *)addr + offsets[i]); pkt = packet_handle(phdr); odp_packet_free(pkt); } } } static int ipc_pktio_recv_lockless(pktio_entry_t *pktio_entry, odp_packet_t pkt_table[], int len) { pkt_ipc_t *pktio_ipc = pkt_priv(pktio_entry); uint32_t ring_mask = pktio_ipc->ring_mask; int pkts = 0; int i; ring_ptr_t *r; ring_ptr_t *r_p; uintptr_t offsets[len]; void **ipcbufs_p = (void *)&offsets[0]; uint32_t ready; ready = odp_atomic_load_u32(&pktio_ipc->ready); if (odp_unlikely(!ready)) { IPC_ODP_DBG("start pktio is missing before usage?\n"); return 0; } _ipc_free_ring_packets(pktio_entry, pktio_ipc->tx.free, ring_mask); /* rx from cache */ r = pktio_ipc->rx.cache; pkts = ring_ptr_deq_multi(r, ring_mask, ipcbufs_p, len); if (odp_unlikely(pkts < 0)) ODP_ABORT("internal error dequeue\n"); /* rx from other app */ if (pkts == 0) { ipcbufs_p = (void *)&offsets[0]; r = pktio_ipc->rx.recv; pkts = ring_ptr_deq_multi(r, ring_mask, ipcbufs_p, len); if (odp_unlikely(pkts < 0)) ODP_ABORT("internal error dequeue\n"); } /* fast path */ if (odp_likely(0 == pkts)) return 0; for (i = 0; i < pkts; i++) { odp_pool_t pool; odp_packet_t pkt; odp_packet_hdr_t *phdr; void *pkt_data; uint64_t data_pool_off; void *rmt_data_ptr; phdr = (void *)((uint8_t *)pktio_ipc->pool_mdata_base + offsets[i]); pool = pktio_ipc->pool; if (odp_unlikely(pool == ODP_POOL_INVALID)) ODP_ABORT("invalid pool"); data_pool_off = (uint8_t *)phdr->seg_data - (uint8_t *)pktio_ipc->remote_base_addr; pkt = odp_packet_alloc(pool, phdr->frame_len); if (odp_unlikely(pkt == ODP_PACKET_INVALID)) { /* Original pool might be smaller then * ring size. If packet can not be * allocated from pool at this time, * simple get in on next recv() call. To keep * packet ordering store such packets in local * cache. */ IPC_ODP_DBG("unable to allocate packet %d/%d\n", i, pkts); break; } /* Copy packet data. */ pkt_data = odp_packet_data(pkt); if (odp_unlikely(!pkt_data)) ODP_ABORT("unable to map pkt_data ipc_slave %d\n", (PKTIO_TYPE_IPC_SLAVE == pktio_ipc->type)); /* Copy packet data from shared pool to local pool. */ rmt_data_ptr = (uint8_t *)pktio_ipc->pool_mdata_base + data_pool_off; memcpy(pkt_data, rmt_data_ptr, phdr->frame_len); /* Copy packets L2, L3 parsed offsets and size */ copy_packet_cls_metadata(phdr, packet_hdr(pkt)); packet_hdr(pkt)->frame_len = phdr->frame_len; packet_hdr(pkt)->headroom = phdr->headroom; packet_hdr(pkt)->tailroom = phdr->tailroom; /* Take classification fields */ packet_hdr(pkt)->p = phdr->p; pkt_table[i] = pkt; } /* put back to rx ring dequed but not processed packets*/ if (pkts != i) { ipcbufs_p = (void *)&offsets[i]; r_p = pktio_ipc->rx.cache; ring_ptr_enq_multi(r_p, ring_mask, ipcbufs_p, pkts - i); if (i == 0) return 0; } /*num of actually received packets*/ pkts = i; /* Now tell other process that we no longer need that buffers.*/ r_p = pktio_ipc->rx.free; ipcbufs_p = (void *)&offsets[0]; ring_ptr_enq_multi(r_p, ring_mask, ipcbufs_p, pkts); for (i = 0; i < pkts; i++) { IPC_ODP_DBG("%d/%d send to be free packet offset %x\n", i, pkts, offsets[i]); } return pkts; } static int ipc_pktio_recv(pktio_entry_t *pktio_entry, int index ODP_UNUSED, odp_packet_t pkt_table[], int num) { int ret; odp_ticketlock_lock(&pktio_entry->s.rxl); ret = ipc_pktio_recv_lockless(pktio_entry, pkt_table, num); odp_ticketlock_unlock(&pktio_entry->s.rxl); return ret; } static int ipc_pktio_send_lockless(pktio_entry_t *pktio_entry, const odp_packet_t pkt_table[], int num) { pkt_ipc_t *pktio_ipc = pkt_priv(pktio_entry); uint32_t ring_mask = pktio_ipc->ring_mask; ring_ptr_t *r; void **rbuf_p; int i; uint32_t ready = odp_atomic_load_u32(&pktio_ipc->ready); pool_t *ipc_pool = pool_entry_from_hdl(pktio_ipc->pool); odp_packet_t pkt_table_mapped[num]; /**< Ready to send packet has to be * in memory mapped pool. */ uintptr_t offsets[num]; if (odp_unlikely(!ready)) return 0; _ipc_free_ring_packets(pktio_entry, pktio_ipc->tx.free, ring_mask); /* Copy packets to shm shared pool if they are in different * pool, or if they are references (we can't share across IPC). */ for (i = 0; i < num; i++) { odp_packet_t pkt = pkt_table[i]; odp_packet_hdr_t *pkt_hdr; pool_t *pool; pkt_hdr = packet_hdr(pkt); pool = pkt_hdr->buf_hdr.pool_ptr; if (pool->pool_idx != ipc_pool->pool_idx || odp_packet_has_ref(pkt)) { odp_packet_t newpkt; newpkt = odp_packet_copy(pkt, pktio_ipc->pool); if (newpkt == ODP_PACKET_INVALID) ODP_ABORT("Unable to copy packet\n"); odp_packet_free(pkt); pkt_table_mapped[i] = newpkt; } else { pkt_table_mapped[i] = pkt; } } /* Set offset to phdr for outgoing packets */ for (i = 0; i < num; i++) { odp_packet_t pkt = pkt_table_mapped[i]; odp_packet_hdr_t *pkt_hdr = packet_hdr(pkt); odp_pool_t pool_hdl = odp_packet_pool(pkt); pool_t *pool = pool_entry_from_hdl(pool_hdl); offsets[i] = (uint8_t *)pkt_hdr - (uint8_t *)odp_shm_addr(pool->shm); /* compile all function code even if ipc disabled with config */ IPC_ODP_DBG("%d/%d send packet %" PRIu64 ", pool %" PRIu64 "," "phdr = %p, offset %x, sendoff %x, addr %p iaddr " "%p\n", i, num, odp_packet_to_u64(pkt), odp_pool_to_u64(pool_hdl), pkt_hdr, (uint8_t *)pkt_hdr->seg_data - (uint8_t *)odp_shm_addr(pool->shm), offsets[i], odp_shm_addr(pool->shm), odp_shm_addr(ipc_pool->shm)); } /* Put packets to ring to be processed by other process. */ rbuf_p = (void *)&offsets[0]; r = pktio_ipc->tx.send; ring_ptr_enq_multi(r, ring_mask, rbuf_p, num); return num; } static int ipc_pktio_send(pktio_entry_t *pktio_entry, int index ODP_UNUSED, const odp_packet_t pkt_table[], int num) { int ret; odp_ticketlock_lock(&pktio_entry->s.txl); ret = ipc_pktio_send_lockless(pktio_entry, pkt_table, num); odp_ticketlock_unlock(&pktio_entry->s.txl); return ret; } static uint32_t ipc_mtu_get(pktio_entry_t *pktio_entry ODP_UNUSED) { /* mtu not limited, pool settings are used. */ return (9 * 1024); } static int ipc_mac_addr_get(pktio_entry_t *pktio_entry ODP_UNUSED, void *mac_addr) { memcpy(mac_addr, pktio_ipc_mac, ETH_ALEN); return ETH_ALEN; } static int ipc_start(pktio_entry_t *pktio_entry) { pkt_ipc_t *pktio_ipc = pkt_priv(pktio_entry); uint32_t ready = odp_atomic_load_u32(&pktio_ipc->ready); if (ready) { ODP_ABORT("%s Already started\n", pktio_entry->s.name); return -1; } if (pktio_ipc->type == PKTIO_TYPE_IPC_MASTER) return _ipc_master_start(pktio_entry); else return _ipc_slave_start(pktio_entry); } static int ipc_stop(pktio_entry_t *pktio_entry) { pkt_ipc_t *pktio_ipc = pkt_priv(pktio_entry); uint32_t ring_mask = pktio_ipc->ring_mask; odp_atomic_store_u32(&pktio_ipc->ready, 0); if (pktio_ipc->tx.send) _ipc_free_ring_packets(pktio_entry, pktio_ipc->tx.send, ring_mask); /* other process can transfer packets from one ring to * other, use delay here to free that packets. */ sleep(1); if (pktio_ipc->tx.free) _ipc_free_ring_packets(pktio_entry, pktio_ipc->tx.free, ring_mask); return 0; } static int ipc_link_status(pktio_entry_t *pktio_entry) { pkt_ipc_t *pktio_ipc = pkt_priv(pktio_entry); if (odp_atomic_load_u32(&pktio_ipc->ready)) return ODP_PKTIO_LINK_STATUS_UP; return ODP_PKTIO_LINK_STATUS_DOWN; } static int ipc_link_info(pktio_entry_t *pktio_entry, odp_pktio_link_info_t *info) { pkt_ipc_t *pktio_ipc = pkt_priv(pktio_entry); memset(info, 0, sizeof(odp_pktio_link_info_t)); info->autoneg = ODP_PKTIO_LINK_AUTONEG_OFF; info->duplex = ODP_PKTIO_LINK_DUPLEX_FULL; info->media = "virtual"; info->pause_rx = ODP_PKTIO_LINK_PAUSE_OFF; info->pause_tx = ODP_PKTIO_LINK_PAUSE_OFF; info->speed = ODP_PKTIO_LINK_SPEED_UNKNOWN; if (odp_atomic_load_u32(&pktio_ipc->ready)) info->status = ODP_PKTIO_LINK_STATUS_UP; else info->status = ODP_PKTIO_LINK_STATUS_DOWN; return 0; } static int ipc_close(pktio_entry_t *pktio_entry) { pkt_ipc_t *pktio_ipc = pkt_priv(pktio_entry); char ipc_shm_name[ODP_POOL_NAME_LEN + sizeof("_m_prod")]; char *dev = pktio_entry->s.name; char name[ODP_POOL_NAME_LEN]; char tail[ODP_POOL_NAME_LEN]; int pid = 0; ipc_stop(pktio_entry); odp_shm_free(pktio_ipc->remote_pool_shm); if (sscanf(dev, "ipc:%d:%s", &pid, tail) == 2) snprintf(name, sizeof(name), "ipc:%s", tail); else snprintf(name, sizeof(name), "%s", dev); /* unlink this pktio info for both master and slave */ odp_shm_free(pktio_ipc->pinfo_shm); /* destroy rings */ snprintf(ipc_shm_name, sizeof(ipc_shm_name), "%s_s_cons", name); _ring_destroy(ipc_shm_name); snprintf(ipc_shm_name, sizeof(ipc_shm_name), "%s_s_prod", name); _ring_destroy(ipc_shm_name); snprintf(ipc_shm_name, sizeof(ipc_shm_name), "%s_m_cons", name); _ring_destroy(ipc_shm_name); snprintf(ipc_shm_name, sizeof(ipc_shm_name), "%s_m_prod", name); _ring_destroy(ipc_shm_name); _ring_destroy("ipc_rx_cache"); return 0; } const pktio_if_ops_t ipc_pktio_ops = { .name = "ipc", .print = NULL, .init_global = NULL, .init_local = NULL, .term = NULL, .open = ipc_pktio_open, .close = ipc_close, .recv = ipc_pktio_recv, .send = ipc_pktio_send, .start = ipc_start, .stop = ipc_stop, .link_status = ipc_link_status, .link_info = ipc_link_info, .mtu_get = ipc_mtu_get, .promisc_mode_set = NULL, .promisc_mode_get = NULL, .mac_get = ipc_mac_addr_get, .mac_set = NULL, .pktin_ts_res = NULL, .pktin_ts_from_ns = NULL, .config = NULL };
68299.c
// SPDX-License-Identifier: GPL-2.0-only /* * POWER Data Stream Control Register (DSCR) fork test * * This testcase modifies the DSCR using mtspr, forks and then * verifies that the child process has the correct changed DSCR * value using mfspr. * * When using the privilege state SPR, the instructions such as * mfspr or mtspr are priviledged and the kernel emulates them * for us. Instructions using problem state SPR can be exuecuted * directly without any emulation if the HW supports them. Else * they also get emulated by the kernel. * * Copyright 2012, Anton Blanchard, IBM Corporation. * Copyright 2015, Anshuman Khandual, IBM Corporation. */ #include "dscr.h" int dscr_inherit(void) { unsigned long i, dscr = 0; pid_t pid; srand(getpid()); set_dscr(dscr); for (i = 0; i < COUNT; i++) { unsigned long cur_dscr, cur_dscr_usr; dscr++; if (dscr > DSCR_MAX) dscr = 0; if (i % 2 == 0) set_dscr_usr(dscr); else set_dscr(dscr); pid = fork(); if (pid == -1) { perror("fork() failed"); exit(1); } else if (pid) { int status; if (waitpid(pid, &status, 0) == -1) { perror("waitpid() failed"); exit(1); } if (!WIFEXITED(status)) { fprintf(stderr, "Child didn't exit cleanly\n"); exit(1); } if (WEXITSTATUS(status) != 0) { fprintf(stderr, "Child didn't exit cleanly\n"); return 1; } } else { cur_dscr = get_dscr(); if (cur_dscr != dscr) { fprintf(stderr, "Kernel DSCR should be %ld " "but is %ld\n", dscr, cur_dscr); exit(1); } cur_dscr_usr = get_dscr_usr(); if (cur_dscr_usr != dscr) { fprintf(stderr, "User DSCR should be %ld " "but is %ld\n", dscr, cur_dscr_usr); exit(1); } exit(0); } } return 0; } int main(int argc, char *argv[]) { return test_harness(dscr_inherit, "dscr_inherit_test"); }
736971.c
/*! @file : leds.c * @author Ernesto Andres Rincon Cruz * @version 1.0.0 * @date 1/09/2021 * @brief Driver para * @details * */ /******************************************************************************* * Includes ******************************************************************************/ #include "leds.h" #include "fsl_gpio.h" /******************************************************************************* * Definitions ******************************************************************************/ /******************************************************************************* * Private Prototypes ******************************************************************************/ /******************************************************************************* * External vars ******************************************************************************/ /******************************************************************************* * Local vars ******************************************************************************/ /******************************************************************************* * Private Source Code ******************************************************************************/ /******************************************************************************* * Public Source Code ******************************************************************************/ void encender_led_verde(){ GPIO_PinWrite(GPIOD,5,0); } void apagar_led_verde(){ GPIO_PinWrite(GPIOD,5,1); } void encender_led_rojo(){ //encender led rojo GPIO_PinWrite(GPIOE,31,0); } void apagar_led_rojo(){ //apagar led rojo GPIO_PinWrite(GPIOE,31,1); }
799133.c
#include<stdio.h> #include<stdlib.h> #include<math.h> int main() { float a; printf("Enter radius: "); scanf(" %f",&a); printf("diameter: %.2f\n",a*2); printf("circumference: %.2f\n",(a*2*22/7)); printf("area: %.2f\n",pow(a,2)*22/7); return 0; }
802995.c
// Copyright (c) 2018 Cláudio Patrício // // 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 "../../ac2.c" volatile int value2display = 0; void _int_(_ADC_VECTOR) isr_adc(void) { //uint *ADC1BUF = (uint *) &ADC1BUF0; IFS1bits.AD1IF = 0; } void _int_(_TIMER_1_VECTOR) isr_T1(void) { //AD1CON1bits.ASAM = 1; // Start converting IFS0bits.T1IF = 0; } void _int_(_TIMER_3_VECTOR) isr_T3(void) { //int2led(value2display, false, 10); IFS0bits.T3IF = 0; } int main() { volatile char teste, teste2; int addr = 0; //debug = true; spi2_init(); spi2_setClock(EEPROM_CLOCK); while(1) { teste = getChar(); if(teste == 'R' || teste == 'r') { printStr("Indique o endereço a ler: "); addr = readInt(16); teste2 = eeprom_readData(addr); printStr("\nValor na memória: "); printInt(teste2, 16); putChar('\n'); } else if(teste == 'W' || teste == 'w') { printStr("Indique o endereço a escrever: "); addr = readInt(16); printStr("\nIndique o valor a gravar: "); eeprom_writeStatusCommand(SPI2_WREN); eeprom_writeData(addr, readInt(16)); putChar('\n'); } } return 0; }
319597.c
// SPDX-License-Identifier: GPL-2.0-only /* * Sparse bit array * * Copyright (C) 2018, Google LLC. * Copyright (C) 2018, Red Hat, Inc. (code style cleanup and fuzzing driver) * * This library provides functions to support a memory efficient bit array, * with an index size of 2^64. A sparsebit array is allocated through * the use sparsebit_alloc() and free'd via sparsebit_free(), * such as in the following: * * struct sparsebit *s; * s = sparsebit_alloc(); * sparsebit_free(&s); * * The struct sparsebit type resolves down to a struct sparsebit. * Note that, sparsebit_free() takes a pointer to the sparsebit * structure. This is so that sparsebit_free() is able to poison * the pointer (e.g. set it to NULL) to the struct sparsebit before * returning to the caller. * * Between the return of sparsebit_alloc() and the call of * sparsebit_free(), there are multiple query and modifying operations * that can be performed on the allocated sparsebit array. All of * these operations take as a parameter the value returned from * sparsebit_alloc() and most also take a bit index. Frequently * used routines include: * * ---- Query Operations * sparsebit_is_set(s, idx) * sparsebit_is_clear(s, idx) * sparsebit_any_set(s) * sparsebit_first_set(s) * sparsebit_next_set(s, prev_idx) * * ---- Modifying Operations * sparsebit_set(s, idx) * sparsebit_clear(s, idx) * sparsebit_set_num(s, idx, num); * sparsebit_clear_num(s, idx, num); * * A common operation, is to itterate over all the bits set in a test * sparsebit array. This can be done via code with the following structure: * * sparsebit_idx_t idx; * if (sparsebit_any_set(s)) { * idx = sparsebit_first_set(s); * do { * ... * idx = sparsebit_next_set(s, idx); * } while (idx != 0); * } * * The index of the first bit set needs to be obtained via * sparsebit_first_set(), because sparsebit_next_set(), needs * the index of the previously set. The sparsebit_idx_t type is * unsigned, so there is no previous index before 0 that is available. * Also, the call to sparsebit_first_set() is not made unless there * is at least 1 bit in the array set. This is because sparsebit_first_set() * aborts if sparsebit_first_set() is called with no bits set. * It is the callers responsibility to assure that the * sparsebit array has at least a single bit set before calling * sparsebit_first_set(). * * ==== Implementation Overview ==== * For the most part the internal implementation of sparsebit is * opaque to the caller. One important implementation detail that the * caller may need to be aware of is the spatial complexity of the * implementation. This implementation of a sparsebit array is not * only sparse, in that it uses memory proportional to the number of bits * set. It is also efficient in memory usage when most of the bits are * set. * * At a high-level the state of the bit settings are maintained through * the use of a binary-search tree, where each node contains at least * the following members: * * typedef uint64_t sparsebit_idx_t; * typedef uint64_t sparsebit_num_t; * * sparsebit_idx_t idx; * uint32_t mask; * sparsebit_num_t num_after; * * The idx member contains the bit index of the first bit described by this * node, while the mask member stores the setting of the first 32-bits. * The setting of the bit at idx + n, where 0 <= n < 32, is located in the * mask member at 1 << n. * * Nodes are sorted by idx and the bits described by two nodes will never * overlap. The idx member is always aligned to the mask size, i.e. a * multiple of 32. * * Beyond a typical implementation, the nodes in this implementation also * contains a member named num_after. The num_after member holds the * number of bits immediately after the mask bits that are contiguously set. * The use of the num_after member allows this implementation to efficiently * represent cases where most bits are set. For example, the case of all * but the last two bits set, is represented by the following two nodes: * * node 0 - idx: 0x0 mask: 0xffffffff num_after: 0xffffffffffffffc0 * node 1 - idx: 0xffffffffffffffe0 mask: 0x3fffffff num_after: 0 * * ==== Invariants ==== * This implementation usses the following invariants: * * + Node are only used to represent bits that are set. * Nodes with a mask of 0 and num_after of 0 are not allowed. * * + Sum of bits set in all the nodes is equal to the value of * the struct sparsebit_pvt num_set member. * * + The setting of at least one bit is always described in a nodes * mask (mask >= 1). * * + A node with all mask bits set only occurs when the last bit * described by the previous node is not equal to this nodes * starting index - 1. All such occurences of this condition are * avoided by moving the setting of the nodes mask bits into * the previous nodes num_after setting. * * + Node starting index is evenly divisible by the number of bits * within a nodes mask member. * * + Nodes never represent a range of bits that wrap around the * highest supported index. * * (idx + MASK_BITS + num_after - 1) <= ((sparsebit_idx_t) 0) - 1) * * As a consequence of the above, the num_after member of a node * will always be <=: * * maximum_index - nodes_starting_index - number_of_mask_bits * * + Nodes within the binary search tree are sorted based on each * nodes starting index. * * + The range of bits described by any two nodes do not overlap. The * range of bits described by a single node is: * * start: node->idx * end (inclusive): node->idx + MASK_BITS + node->num_after - 1; * * Note, at times these invariants are temporarily violated for a * specific portion of the code. For example, when setting a mask * bit, there is a small delay between when the mask bit is set and the * value in the struct sparsebit_pvt num_set member is updated. Other * temporary violations occur when node_split() is called with a specified * index and assures that a node where its mask represents the bit * at the specified index exists. At times to do this node_split() * must split an existing node into two nodes or create a node that * has no bits set. Such temporary violations must be corrected before * returning to the caller. These corrections are typically performed * by the local function node_reduce(). */ #include "test_util.h" #include "sparsebit.h" #include <limits.h> #include <assert.h> #define DUMP_LINE_MAX 100 /* Does not include indent amount */ typedef uint32_t mask_t; #define MASK_BITS (sizeof(mask_t) * CHAR_BIT) struct node { struct node *parent; struct node *left; struct node *right; sparsebit_idx_t idx; /* index of least-significant bit in mask */ sparsebit_num_t num_after; /* num contiguously set after mask */ mask_t mask; }; struct sparsebit { /* * Points to root node of the binary search * tree. Equal to NULL when no bits are set in * the entire sparsebit array. */ struct node *root; /* * A redundant count of the total number of bits set. Used for * diagnostic purposes and to change the time complexity of * sparsebit_num_set() from O(n) to O(1). * Note: Due to overflow, a value of 0 means none or all set. */ sparsebit_num_t num_set; }; /* Returns the number of set bits described by the settings * of the node pointed to by nodep. */ static sparsebit_num_t node_num_set(struct node *nodep) { return nodep->num_after + __builtin_popcount(nodep->mask); } /* Returns a pointer to the node that describes the * lowest bit index. */ static struct node *node_first(struct sparsebit *s) { struct node *nodep; for (nodep = s->root; nodep && nodep->left; nodep = nodep->left) ; return nodep; } /* Returns a pointer to the node that describes the * lowest bit index > the index of the node pointed to by np. * Returns NULL if no node with a higher index exists. */ static struct node *node_next(struct sparsebit *s, struct node *np) { struct node *nodep = np; /* * If current node has a right child, next node is the left-most * of the right child. */ if (nodep->right) { for (nodep = nodep->right; nodep->left; nodep = nodep->left) ; return nodep; } /* * No right child. Go up until node is left child of a parent. * That parent is then the next node. */ while (nodep->parent && nodep == nodep->parent->right) nodep = nodep->parent; return nodep->parent; } /* Searches for and returns a pointer to the node that describes the * highest index < the index of the node pointed to by np. * Returns NULL if no node with a lower index exists. */ static struct node *node_prev(struct sparsebit *s, struct node *np) { struct node *nodep = np; /* * If current node has a left child, next node is the right-most * of the left child. */ if (nodep->left) { for (nodep = nodep->left; nodep->right; nodep = nodep->right) ; return (struct node *) nodep; } /* * No left child. Go up until node is right child of a parent. * That parent is then the next node. */ while (nodep->parent && nodep == nodep->parent->left) nodep = nodep->parent; return (struct node *) nodep->parent; } /* Allocates space to hold a copy of the node sub-tree pointed to by * subtree and duplicates the bit settings to the newly allocated nodes. * Returns the newly allocated copy of subtree. */ static struct node *node_copy_subtree(struct node *subtree) { struct node *root; /* Duplicate the node at the root of the subtree */ root = calloc(1, sizeof(*root)); if (!root) { perror("calloc"); abort(); } root->idx = subtree->idx; root->mask = subtree->mask; root->num_after = subtree->num_after; /* As needed, recursively duplicate the left and right subtrees */ if (subtree->left) { root->left = node_copy_subtree(subtree->left); root->left->parent = root; } if (subtree->right) { root->right = node_copy_subtree(subtree->right); root->right->parent = root; } return root; } /* Searches for and returns a pointer to the node that describes the setting * of the bit given by idx. A node describes the setting of a bit if its * index is within the bits described by the mask bits or the number of * contiguous bits set after the mask. Returns NULL if there is no such node. */ static struct node *node_find(struct sparsebit *s, sparsebit_idx_t idx) { struct node *nodep; /* Find the node that describes the setting of the bit at idx */ for (nodep = s->root; nodep; nodep = nodep->idx > idx ? nodep->left : nodep->right) { if (idx >= nodep->idx && idx <= nodep->idx + MASK_BITS + nodep->num_after - 1) break; } return nodep; } /* Entry Requirements: * + A node that describes the setting of idx is not already present. * * Adds a new node to describe the setting of the bit at the index given * by idx. Returns a pointer to the newly added node. * * TODO(lhuemill): Degenerate cases causes the tree to get unbalanced. */ static struct node *node_add(struct sparsebit *s, sparsebit_idx_t idx) { struct node *nodep, *parentp, *prev; /* Allocate and initialize the new node. */ nodep = calloc(1, sizeof(*nodep)); if (!nodep) { perror("calloc"); abort(); } nodep->idx = idx & -MASK_BITS; /* If no nodes, set it up as the root node. */ if (!s->root) { s->root = nodep; return nodep; } /* * Find the parent where the new node should be attached * and add the node there. */ parentp = s->root; while (true) { if (idx < parentp->idx) { if (!parentp->left) { parentp->left = nodep; nodep->parent = parentp; break; } parentp = parentp->left; } else { assert(idx > parentp->idx + MASK_BITS + parentp->num_after - 1); if (!parentp->right) { parentp->right = nodep; nodep->parent = parentp; break; } parentp = parentp->right; } } /* * Does num_after bits of previous node overlap with the mask * of the new node? If so set the bits in the new nodes mask * and reduce the previous nodes num_after. */ prev = node_prev(s, nodep); while (prev && prev->idx + MASK_BITS + prev->num_after - 1 >= nodep->idx) { unsigned int n1 = (prev->idx + MASK_BITS + prev->num_after - 1) - nodep->idx; assert(prev->num_after > 0); assert(n1 < MASK_BITS); assert(!(nodep->mask & (1 << n1))); nodep->mask |= (1 << n1); prev->num_after--; } return nodep; } /* Returns whether all the bits in the sparsebit array are set. */ bool sparsebit_all_set(struct sparsebit *s) { /* * If any nodes there must be at least one bit set. Only case * where a bit is set and total num set is 0, is when all bits * are set. */ return s->root && s->num_set == 0; } /* Clears all bits described by the node pointed to by nodep, then * removes the node. */ static void node_rm(struct sparsebit *s, struct node *nodep) { struct node *tmp; sparsebit_num_t num_set; num_set = node_num_set(nodep); assert(s->num_set >= num_set || sparsebit_all_set(s)); s->num_set -= node_num_set(nodep); /* Have both left and right child */ if (nodep->left && nodep->right) { /* * Move left children to the leftmost leaf node * of the right child. */ for (tmp = nodep->right; tmp->left; tmp = tmp->left) ; tmp->left = nodep->left; nodep->left = NULL; tmp->left->parent = tmp; } /* Left only child */ if (nodep->left) { if (!nodep->parent) { s->root = nodep->left; nodep->left->parent = NULL; } else { nodep->left->parent = nodep->parent; if (nodep == nodep->parent->left) nodep->parent->left = nodep->left; else { assert(nodep == nodep->parent->right); nodep->parent->right = nodep->left; } } nodep->parent = nodep->left = nodep->right = NULL; free(nodep); return; } /* Right only child */ if (nodep->right) { if (!nodep->parent) { s->root = nodep->right; nodep->right->parent = NULL; } else { nodep->right->parent = nodep->parent; if (nodep == nodep->parent->left) nodep->parent->left = nodep->right; else { assert(nodep == nodep->parent->right); nodep->parent->right = nodep->right; } } nodep->parent = nodep->left = nodep->right = NULL; free(nodep); return; } /* Leaf Node */ if (!nodep->parent) { s->root = NULL; } else { if (nodep->parent->left == nodep) nodep->parent->left = NULL; else { assert(nodep == nodep->parent->right); nodep->parent->right = NULL; } } nodep->parent = nodep->left = nodep->right = NULL; free(nodep); return; } /* Splits the node containing the bit at idx so that there is a node * that starts at the specified index. If no such node exists, a new * node at the specified index is created. Returns the new node. * * idx must start of a mask boundary. */ static struct node *node_split(struct sparsebit *s, sparsebit_idx_t idx) { struct node *nodep1, *nodep2; sparsebit_idx_t offset; sparsebit_num_t orig_num_after; assert(!(idx % MASK_BITS)); /* * Is there a node that describes the setting of idx? * If not, add it. */ nodep1 = node_find(s, idx); if (!nodep1) return node_add(s, idx); /* * All done if the starting index of the node is where the * split should occur. */ if (nodep1->idx == idx) return nodep1; /* * Split point not at start of mask, so it must be part of * bits described by num_after. */ /* * Calculate offset within num_after for where the split is * to occur. */ offset = idx - (nodep1->idx + MASK_BITS); orig_num_after = nodep1->num_after; /* * Add a new node to describe the bits starting at * the split point. */ nodep1->num_after = offset; nodep2 = node_add(s, idx); /* Move bits after the split point into the new node */ nodep2->num_after = orig_num_after - offset; if (nodep2->num_after >= MASK_BITS) { nodep2->mask = ~(mask_t) 0; nodep2->num_after -= MASK_BITS; } else { nodep2->mask = (1 << nodep2->num_after) - 1; nodep2->num_after = 0; } return nodep2; } /* Iteratively reduces the node pointed to by nodep and its adjacent * nodes into a more compact form. For example, a node with a mask with * all bits set adjacent to a previous node, will get combined into a * single node with an increased num_after setting. * * After each reduction, a further check is made to see if additional * reductions are possible with the new previous and next nodes. Note, * a search for a reduction is only done across the nodes nearest nodep * and those that became part of a reduction. Reductions beyond nodep * and the adjacent nodes that are reduced are not discovered. It is the * responsibility of the caller to pass a nodep that is within one node * of each possible reduction. * * This function does not fix the temporary violation of all invariants. * For example it does not fix the case where the bit settings described * by two or more nodes overlap. Such a violation introduces the potential * complication of a bit setting for a specific index having different settings * in different nodes. This would then introduce the further complication * of which node has the correct setting of the bit and thus such conditions * are not allowed. * * This function is designed to fix invariant violations that are introduced * by node_split() and by changes to the nodes mask or num_after members. * For example, when setting a bit within a nodes mask, the function that * sets the bit doesn't have to worry about whether the setting of that * bit caused the mask to have leading only or trailing only bits set. * Instead, the function can call node_reduce(), with nodep equal to the * node address that it set a mask bit in, and node_reduce() will notice * the cases of leading or trailing only bits and that there is an * adjacent node that the bit settings could be merged into. * * This implementation specifically detects and corrects violation of the * following invariants: * * + Node are only used to represent bits that are set. * Nodes with a mask of 0 and num_after of 0 are not allowed. * * + The setting of at least one bit is always described in a nodes * mask (mask >= 1). * * + A node with all mask bits set only occurs when the last bit * described by the previous node is not equal to this nodes * starting index - 1. All such occurences of this condition are * avoided by moving the setting of the nodes mask bits into * the previous nodes num_after setting. */ static void node_reduce(struct sparsebit *s, struct node *nodep) { bool reduction_performed; do { reduction_performed = false; struct node *prev, *next, *tmp; /* 1) Potential reductions within the current node. */ /* Nodes with all bits cleared may be removed. */ if (nodep->mask == 0 && nodep->num_after == 0) { /* * About to remove the node pointed to by * nodep, which normally would cause a problem * for the next pass through the reduction loop, * because the node at the starting point no longer * exists. This potential problem is handled * by first remembering the location of the next * or previous nodes. Doesn't matter which, because * once the node at nodep is removed, there will be * no other nodes between prev and next. * * Note, the checks performed on nodep against both * both prev and next both check for an adjacent * node that can be reduced into a single node. As * such, after removing the node at nodep, doesn't * matter whether the nodep for the next pass * through the loop is equal to the previous pass * prev or next node. Either way, on the next pass * the one not selected will become either the * prev or next node. */ tmp = node_next(s, nodep); if (!tmp) tmp = node_prev(s, nodep); node_rm(s, nodep); nodep = NULL; nodep = tmp; reduction_performed = true; continue; } /* * When the mask is 0, can reduce the amount of num_after * bits by moving the initial num_after bits into the mask. */ if (nodep->mask == 0) { assert(nodep->num_after != 0); assert(nodep->idx + MASK_BITS > nodep->idx); nodep->idx += MASK_BITS; if (nodep->num_after >= MASK_BITS) { nodep->mask = ~0; nodep->num_after -= MASK_BITS; } else { nodep->mask = (1u << nodep->num_after) - 1; nodep->num_after = 0; } reduction_performed = true; continue; } /* * 2) Potential reductions between the current and * previous nodes. */ prev = node_prev(s, nodep); if (prev) { sparsebit_idx_t prev_highest_bit; /* Nodes with no bits set can be removed. */ if (prev->mask == 0 && prev->num_after == 0) { node_rm(s, prev); reduction_performed = true; continue; } /* * All mask bits set and previous node has * adjacent index. */ if (nodep->mask + 1 == 0 && prev->idx + MASK_BITS == nodep->idx) { prev->num_after += MASK_BITS + nodep->num_after; nodep->mask = 0; nodep->num_after = 0; reduction_performed = true; continue; } /* * Is node adjacent to previous node and the node * contains a single contiguous range of bits * starting from the beginning of the mask? */ prev_highest_bit = prev->idx + MASK_BITS - 1 + prev->num_after; if (prev_highest_bit + 1 == nodep->idx && (nodep->mask | (nodep->mask >> 1)) == nodep->mask) { /* * How many contiguous bits are there? * Is equal to the total number of set * bits, due to an earlier check that * there is a single contiguous range of * set bits. */ unsigned int num_contiguous = __builtin_popcount(nodep->mask); assert((num_contiguous > 0) && ((1ULL << num_contiguous) - 1) == nodep->mask); prev->num_after += num_contiguous; nodep->mask = 0; /* * For predictable performance, handle special * case where all mask bits are set and there * is a non-zero num_after setting. This code * is functionally correct without the following * conditionalized statements, but without them * the value of num_after is only reduced by * the number of mask bits per pass. There are * cases where num_after can be close to 2^64. * Without this code it could take nearly * (2^64) / 32 passes to perform the full * reduction. */ if (num_contiguous == MASK_BITS) { prev->num_after += nodep->num_after; nodep->num_after = 0; } reduction_performed = true; continue; } } /* * 3) Potential reductions between the current and * next nodes. */ next = node_next(s, nodep); if (next) { /* Nodes with no bits set can be removed. */ if (next->mask == 0 && next->num_after == 0) { node_rm(s, next); reduction_performed = true; continue; } /* * Is next node index adjacent to current node * and has a mask with all bits set? */ if (next->idx == nodep->idx + MASK_BITS + nodep->num_after && next->mask == ~(mask_t) 0) { nodep->num_after += MASK_BITS; next->mask = 0; nodep->num_after += next->num_after; next->num_after = 0; node_rm(s, next); next = NULL; reduction_performed = true; continue; } } } while (nodep && reduction_performed); } /* Returns whether the bit at the index given by idx, within the * sparsebit array is set or not. */ bool sparsebit_is_set(struct sparsebit *s, sparsebit_idx_t idx) { struct node *nodep; /* Find the node that describes the setting of the bit at idx */ for (nodep = s->root; nodep; nodep = nodep->idx > idx ? nodep->left : nodep->right) if (idx >= nodep->idx && idx <= nodep->idx + MASK_BITS + nodep->num_after - 1) goto have_node; return false; have_node: /* Bit is set if it is any of the bits described by num_after */ if (nodep->num_after && idx >= nodep->idx + MASK_BITS) return true; /* Is the corresponding mask bit set */ assert(idx >= nodep->idx && idx - nodep->idx < MASK_BITS); return !!(nodep->mask & (1 << (idx - nodep->idx))); } /* Within the sparsebit array pointed to by s, sets the bit * at the index given by idx. */ static void bit_set(struct sparsebit *s, sparsebit_idx_t idx) { struct node *nodep; /* Skip bits that are already set */ if (sparsebit_is_set(s, idx)) return; /* * Get a node where the bit at idx is described by the mask. * The node_split will also create a node, if there isn't * already a node that describes the setting of bit. */ nodep = node_split(s, idx & -MASK_BITS); /* Set the bit within the nodes mask */ assert(idx >= nodep->idx && idx <= nodep->idx + MASK_BITS - 1); assert(!(nodep->mask & (1 << (idx - nodep->idx)))); nodep->mask |= 1 << (idx - nodep->idx); s->num_set++; node_reduce(s, nodep); } /* Within the sparsebit array pointed to by s, clears the bit * at the index given by idx. */ static void bit_clear(struct sparsebit *s, sparsebit_idx_t idx) { struct node *nodep; /* Skip bits that are already cleared */ if (!sparsebit_is_set(s, idx)) return; /* Is there a node that describes the setting of this bit? */ nodep = node_find(s, idx); if (!nodep) return; /* * If a num_after bit, split the node, so that the bit is * part of a node mask. */ if (idx >= nodep->idx + MASK_BITS) nodep = node_split(s, idx & -MASK_BITS); /* * After node_split above, bit at idx should be within the mask. * Clear that bit. */ assert(idx >= nodep->idx && idx <= nodep->idx + MASK_BITS - 1); assert(nodep->mask & (1 << (idx - nodep->idx))); nodep->mask &= ~(1 << (idx - nodep->idx)); assert(s->num_set > 0 || sparsebit_all_set(s)); s->num_set--; node_reduce(s, nodep); } /* Recursively dumps to the FILE stream given by stream the contents * of the sub-tree of nodes pointed to by nodep. Each line of output * is prefixed by the number of spaces given by indent. On each * recursion, the indent amount is increased by 2. This causes nodes * at each level deeper into the binary search tree to be displayed * with a greater indent. */ static void dump_nodes(FILE *stream, struct node *nodep, unsigned int indent) { char *node_type; /* Dump contents of node */ if (!nodep->parent) node_type = "root"; else if (nodep == nodep->parent->left) node_type = "left"; else { assert(nodep == nodep->parent->right); node_type = "right"; } fprintf(stream, "%*s---- %s nodep: %p\n", indent, "", node_type, nodep); fprintf(stream, "%*s parent: %p left: %p right: %p\n", indent, "", nodep->parent, nodep->left, nodep->right); fprintf(stream, "%*s idx: 0x%lx mask: 0x%x num_after: 0x%lx\n", indent, "", nodep->idx, nodep->mask, nodep->num_after); /* If present, dump contents of left child nodes */ if (nodep->left) dump_nodes(stream, nodep->left, indent + 2); /* If present, dump contents of right child nodes */ if (nodep->right) dump_nodes(stream, nodep->right, indent + 2); } static inline sparsebit_idx_t node_first_set(struct node *nodep, int start) { mask_t leading = (mask_t)1 << start; int n1 = __builtin_ctz(nodep->mask & -leading); return nodep->idx + n1; } static inline sparsebit_idx_t node_first_clear(struct node *nodep, int start) { mask_t leading = (mask_t)1 << start; int n1 = __builtin_ctz(~nodep->mask & -leading); return nodep->idx + n1; } /* Dumps to the FILE stream specified by stream, the implementation dependent * internal state of s. Each line of output is prefixed with the number * of spaces given by indent. The output is completely implementation * dependent and subject to change. Output from this function should only * be used for diagnostic purposes. For example, this function can be * used by test cases after they detect an unexpected condition, as a means * to capture diagnostic information. */ static void sparsebit_dump_internal(FILE *stream, struct sparsebit *s, unsigned int indent) { /* Dump the contents of s */ fprintf(stream, "%*sroot: %p\n", indent, "", s->root); fprintf(stream, "%*snum_set: 0x%lx\n", indent, "", s->num_set); if (s->root) dump_nodes(stream, s->root, indent); } /* Allocates and returns a new sparsebit array. The initial state * of the newly allocated sparsebit array has all bits cleared. */ struct sparsebit *sparsebit_alloc(void) { struct sparsebit *s; /* Allocate top level structure. */ s = calloc(1, sizeof(*s)); if (!s) { perror("calloc"); abort(); } return s; } /* Frees the implementation dependent data for the sparsebit array * pointed to by s and poisons the pointer to that data. */ void sparsebit_free(struct sparsebit **sbitp) { struct sparsebit *s = *sbitp; if (!s) return; sparsebit_clear_all(s); free(s); *sbitp = NULL; } /* Makes a copy of the sparsebit array given by s, to the sparsebit * array given by d. Note, d must have already been allocated via * sparsebit_alloc(). It can though already have bits set, which * if different from src will be cleared. */ void sparsebit_copy(struct sparsebit *d, struct sparsebit *s) { /* First clear any bits already set in the destination */ sparsebit_clear_all(d); if (s->root) { d->root = node_copy_subtree(s->root); d->num_set = s->num_set; } } /* Returns whether num consecutive bits starting at idx are all set. */ bool sparsebit_is_set_num(struct sparsebit *s, sparsebit_idx_t idx, sparsebit_num_t num) { sparsebit_idx_t next_cleared; assert(num > 0); assert(idx + num - 1 >= idx); /* With num > 0, the first bit must be set. */ if (!sparsebit_is_set(s, idx)) return false; /* Find the next cleared bit */ next_cleared = sparsebit_next_clear(s, idx); /* * If no cleared bits beyond idx, then there are at least num * set bits. idx + num doesn't wrap. Otherwise check if * there are enough set bits between idx and the next cleared bit. */ return next_cleared == 0 || next_cleared - idx >= num; } /* Returns whether the bit at the index given by idx. */ bool sparsebit_is_clear(struct sparsebit *s, sparsebit_idx_t idx) { return !sparsebit_is_set(s, idx); } /* Returns whether num consecutive bits starting at idx are all cleared. */ bool sparsebit_is_clear_num(struct sparsebit *s, sparsebit_idx_t idx, sparsebit_num_t num) { sparsebit_idx_t next_set; assert(num > 0); assert(idx + num - 1 >= idx); /* With num > 0, the first bit must be cleared. */ if (!sparsebit_is_clear(s, idx)) return false; /* Find the next set bit */ next_set = sparsebit_next_set(s, idx); /* * If no set bits beyond idx, then there are at least num * cleared bits. idx + num doesn't wrap. Otherwise check if * there are enough cleared bits between idx and the next set bit. */ return next_set == 0 || next_set - idx >= num; } /* Returns the total number of bits set. Note: 0 is also returned for * the case of all bits set. This is because with all bits set, there * is 1 additional bit set beyond what can be represented in the return * value. Use sparsebit_any_set(), instead of sparsebit_num_set() > 0, * to determine if the sparsebit array has any bits set. */ sparsebit_num_t sparsebit_num_set(struct sparsebit *s) { return s->num_set; } /* Returns whether any bit is set in the sparsebit array. */ bool sparsebit_any_set(struct sparsebit *s) { /* * Nodes only describe set bits. If any nodes then there * is at least 1 bit set. */ if (!s->root) return false; /* * Every node should have a non-zero mask. For now will * just assure that the root node has a non-zero mask, * which is a quick check that at least 1 bit is set. */ assert(s->root->mask != 0); assert(s->num_set > 0 || (s->root->num_after == ((sparsebit_num_t) 0) - MASK_BITS && s->root->mask == ~(mask_t) 0)); return true; } /* Returns whether all the bits in the sparsebit array are cleared. */ bool sparsebit_all_clear(struct sparsebit *s) { return !sparsebit_any_set(s); } /* Returns whether all the bits in the sparsebit array are set. */ bool sparsebit_any_clear(struct sparsebit *s) { return !sparsebit_all_set(s); } /* Returns the index of the first set bit. Abort if no bits are set. */ sparsebit_idx_t sparsebit_first_set(struct sparsebit *s) { struct node *nodep; /* Validate at least 1 bit is set */ assert(sparsebit_any_set(s)); nodep = node_first(s); return node_first_set(nodep, 0); } /* Returns the index of the first cleared bit. Abort if * no bits are cleared. */ sparsebit_idx_t sparsebit_first_clear(struct sparsebit *s) { struct node *nodep1, *nodep2; /* Validate at least 1 bit is cleared. */ assert(sparsebit_any_clear(s)); /* If no nodes or first node index > 0 then lowest cleared is 0 */ nodep1 = node_first(s); if (!nodep1 || nodep1->idx > 0) return 0; /* Does the mask in the first node contain any cleared bits. */ if (nodep1->mask != ~(mask_t) 0) return node_first_clear(nodep1, 0); /* * All mask bits set in first node. If there isn't a second node * then the first cleared bit is the first bit after the bits * described by the first node. */ nodep2 = node_next(s, nodep1); if (!nodep2) { /* * No second node. First cleared bit is first bit beyond * bits described by first node. */ assert(nodep1->mask == ~(mask_t) 0); assert(nodep1->idx + MASK_BITS + nodep1->num_after != (sparsebit_idx_t) 0); return nodep1->idx + MASK_BITS + nodep1->num_after; } /* * There is a second node. * If it is not adjacent to the first node, then there is a gap * of cleared bits between the nodes, and the first cleared bit * is the first bit within the gap. */ if (nodep1->idx + MASK_BITS + nodep1->num_after != nodep2->idx) return nodep1->idx + MASK_BITS + nodep1->num_after; /* * Second node is adjacent to the first node. * Because it is adjacent, its mask should be non-zero. If all * its mask bits are set, then with it being adjacent, it should * have had the mask bits moved into the num_after setting of the * previous node. */ return node_first_clear(nodep2, 0); } /* Returns index of next bit set within s after the index given by prev. * Returns 0 if there are no bits after prev that are set. */ sparsebit_idx_t sparsebit_next_set(struct sparsebit *s, sparsebit_idx_t prev) { sparsebit_idx_t lowest_possible = prev + 1; sparsebit_idx_t start; struct node *nodep; /* A bit after the highest index can't be set. */ if (lowest_possible == 0) return 0; /* * Find the leftmost 'candidate' overlapping or to the right * of lowest_possible. */ struct node *candidate = NULL; /* True iff lowest_possible is within candidate */ bool contains = false; /* * Find node that describes setting of bit at lowest_possible. * If such a node doesn't exist, find the node with the lowest * starting index that is > lowest_possible. */ for (nodep = s->root; nodep;) { if ((nodep->idx + MASK_BITS + nodep->num_after - 1) >= lowest_possible) { candidate = nodep; if (candidate->idx <= lowest_possible) { contains = true; break; } nodep = nodep->left; } else { nodep = nodep->right; } } if (!candidate) return 0; assert(candidate->mask != 0); /* Does the candidate node describe the setting of lowest_possible? */ if (!contains) { /* * Candidate doesn't describe setting of bit at lowest_possible. * Candidate points to the first node with a starting index * > lowest_possible. */ assert(candidate->idx > lowest_possible); return node_first_set(candidate, 0); } /* * Candidate describes setting of bit at lowest_possible. * Note: although the node describes the setting of the bit * at lowest_possible, its possible that its setting and the * setting of all latter bits described by this node are 0. * For now, just handle the cases where this node describes * a bit at or after an index of lowest_possible that is set. */ start = lowest_possible - candidate->idx; if (start < MASK_BITS && candidate->mask >= (1 << start)) return node_first_set(candidate, start); if (candidate->num_after) { sparsebit_idx_t first_num_after_idx = candidate->idx + MASK_BITS; return lowest_possible < first_num_after_idx ? first_num_after_idx : lowest_possible; } /* * Although candidate node describes setting of bit at * the index of lowest_possible, all bits at that index and * latter that are described by candidate are cleared. With * this, the next bit is the first bit in the next node, if * such a node exists. If a next node doesn't exist, then * there is no next set bit. */ candidate = node_next(s, candidate); if (!candidate) return 0; return node_first_set(candidate, 0); } /* Returns index of next bit cleared within s after the index given by prev. * Returns 0 if there are no bits after prev that are cleared. */ sparsebit_idx_t sparsebit_next_clear(struct sparsebit *s, sparsebit_idx_t prev) { sparsebit_idx_t lowest_possible = prev + 1; sparsebit_idx_t idx; struct node *nodep1, *nodep2; /* A bit after the highest index can't be set. */ if (lowest_possible == 0) return 0; /* * Does a node describing the setting of lowest_possible exist? * If not, the bit at lowest_possible is cleared. */ nodep1 = node_find(s, lowest_possible); if (!nodep1) return lowest_possible; /* Does a mask bit in node 1 describe the next cleared bit. */ for (idx = lowest_possible - nodep1->idx; idx < MASK_BITS; idx++) if (!(nodep1->mask & (1 << idx))) return nodep1->idx + idx; /* * Next cleared bit is not described by node 1. If there * isn't a next node, then next cleared bit is described * by bit after the bits described by the first node. */ nodep2 = node_next(s, nodep1); if (!nodep2) return nodep1->idx + MASK_BITS + nodep1->num_after; /* * There is a second node. * If it is not adjacent to the first node, then there is a gap * of cleared bits between the nodes, and the next cleared bit * is the first bit within the gap. */ if (nodep1->idx + MASK_BITS + nodep1->num_after != nodep2->idx) return nodep1->idx + MASK_BITS + nodep1->num_after; /* * Second node is adjacent to the first node. * Because it is adjacent, its mask should be non-zero. If all * its mask bits are set, then with it being adjacent, it should * have had the mask bits moved into the num_after setting of the * previous node. */ return node_first_clear(nodep2, 0); } /* Starting with the index 1 greater than the index given by start, finds * and returns the index of the first sequence of num consecutively set * bits. Returns a value of 0 of no such sequence exists. */ sparsebit_idx_t sparsebit_next_set_num(struct sparsebit *s, sparsebit_idx_t start, sparsebit_num_t num) { sparsebit_idx_t idx; assert(num >= 1); for (idx = sparsebit_next_set(s, start); idx != 0 && idx + num - 1 >= idx; idx = sparsebit_next_set(s, idx)) { assert(sparsebit_is_set(s, idx)); /* * Does the sequence of bits starting at idx consist of * num set bits? */ if (sparsebit_is_set_num(s, idx, num)) return idx; /* * Sequence of set bits at idx isn't large enough. * Skip this entire sequence of set bits. */ idx = sparsebit_next_clear(s, idx); if (idx == 0) return 0; } return 0; } /* Starting with the index 1 greater than the index given by start, finds * and returns the index of the first sequence of num consecutively cleared * bits. Returns a value of 0 of no such sequence exists. */ sparsebit_idx_t sparsebit_next_clear_num(struct sparsebit *s, sparsebit_idx_t start, sparsebit_num_t num) { sparsebit_idx_t idx; assert(num >= 1); for (idx = sparsebit_next_clear(s, start); idx != 0 && idx + num - 1 >= idx; idx = sparsebit_next_clear(s, idx)) { assert(sparsebit_is_clear(s, idx)); /* * Does the sequence of bits starting at idx consist of * num cleared bits? */ if (sparsebit_is_clear_num(s, idx, num)) return idx; /* * Sequence of cleared bits at idx isn't large enough. * Skip this entire sequence of cleared bits. */ idx = sparsebit_next_set(s, idx); if (idx == 0) return 0; } return 0; } /* Sets the bits * in the inclusive range idx through idx + num - 1. */ void sparsebit_set_num(struct sparsebit *s, sparsebit_idx_t start, sparsebit_num_t num) { struct node *nodep, *next; unsigned int n1; sparsebit_idx_t idx; sparsebit_num_t n; sparsebit_idx_t middle_start, middle_end; assert(num > 0); assert(start + num - 1 >= start); /* * Leading - bits before first mask boundary. * * TODO(lhuemill): With some effort it may be possible to * replace the following loop with a sequential sequence * of statements. High level sequence would be: * * 1. Use node_split() to force node that describes setting * of idx to be within the mask portion of a node. * 2. Form mask of bits to be set. * 3. Determine number of mask bits already set in the node * and store in a local variable named num_already_set. * 4. Set the appropriate mask bits within the node. * 5. Increment struct sparsebit_pvt num_set member * by the number of bits that were actually set. * Exclude from the counts bits that were already set. * 6. Before returning to the caller, use node_reduce() to * handle the multiple corner cases that this method * introduces. */ for (idx = start, n = num; n > 0 && idx % MASK_BITS != 0; idx++, n--) bit_set(s, idx); /* Middle - bits spanning one or more entire mask */ middle_start = idx; middle_end = middle_start + (n & -MASK_BITS) - 1; if (n >= MASK_BITS) { nodep = node_split(s, middle_start); /* * As needed, split just after end of middle bits. * No split needed if end of middle bits is at highest * supported bit index. */ if (middle_end + 1 > middle_end) (void) node_split(s, middle_end + 1); /* Delete nodes that only describe bits within the middle. */ for (next = node_next(s, nodep); next && (next->idx < middle_end); next = node_next(s, nodep)) { assert(next->idx + MASK_BITS + next->num_after - 1 <= middle_end); node_rm(s, next); next = NULL; } /* As needed set each of the mask bits */ for (n1 = 0; n1 < MASK_BITS; n1++) { if (!(nodep->mask & (1 << n1))) { nodep->mask |= 1 << n1; s->num_set++; } } s->num_set -= nodep->num_after; nodep->num_after = middle_end - middle_start + 1 - MASK_BITS; s->num_set += nodep->num_after; node_reduce(s, nodep); } idx = middle_end + 1; n -= middle_end - middle_start + 1; /* Trailing - bits at and beyond last mask boundary */ assert(n < MASK_BITS); for (; n > 0; idx++, n--) bit_set(s, idx); } /* Clears the bits * in the inclusive range idx through idx + num - 1. */ void sparsebit_clear_num(struct sparsebit *s, sparsebit_idx_t start, sparsebit_num_t num) { struct node *nodep, *next; unsigned int n1; sparsebit_idx_t idx; sparsebit_num_t n; sparsebit_idx_t middle_start, middle_end; assert(num > 0); assert(start + num - 1 >= start); /* Leading - bits before first mask boundary */ for (idx = start, n = num; n > 0 && idx % MASK_BITS != 0; idx++, n--) bit_clear(s, idx); /* Middle - bits spanning one or more entire mask */ middle_start = idx; middle_end = middle_start + (n & -MASK_BITS) - 1; if (n >= MASK_BITS) { nodep = node_split(s, middle_start); /* * As needed, split just after end of middle bits. * No split needed if end of middle bits is at highest * supported bit index. */ if (middle_end + 1 > middle_end) (void) node_split(s, middle_end + 1); /* Delete nodes that only describe bits within the middle. */ for (next = node_next(s, nodep); next && (next->idx < middle_end); next = node_next(s, nodep)) { assert(next->idx + MASK_BITS + next->num_after - 1 <= middle_end); node_rm(s, next); next = NULL; } /* As needed clear each of the mask bits */ for (n1 = 0; n1 < MASK_BITS; n1++) { if (nodep->mask & (1 << n1)) { nodep->mask &= ~(1 << n1); s->num_set--; } } /* Clear any bits described by num_after */ s->num_set -= nodep->num_after; nodep->num_after = 0; /* * Delete the node that describes the beginning of * the middle bits and perform any allowed reductions * with the nodes prev or next of nodep. */ node_reduce(s, nodep); nodep = NULL; } idx = middle_end + 1; n -= middle_end - middle_start + 1; /* Trailing - bits at and beyond last mask boundary */ assert(n < MASK_BITS); for (; n > 0; idx++, n--) bit_clear(s, idx); } /* Sets the bit at the index given by idx. */ void sparsebit_set(struct sparsebit *s, sparsebit_idx_t idx) { sparsebit_set_num(s, idx, 1); } /* Clears the bit at the index given by idx. */ void sparsebit_clear(struct sparsebit *s, sparsebit_idx_t idx) { sparsebit_clear_num(s, idx, 1); } /* Sets the bits in the entire addressable range of the sparsebit array. */ void sparsebit_set_all(struct sparsebit *s) { sparsebit_set(s, 0); sparsebit_set_num(s, 1, ~(sparsebit_idx_t) 0); assert(sparsebit_all_set(s)); } /* Clears the bits in the entire addressable range of the sparsebit array. */ void sparsebit_clear_all(struct sparsebit *s) { sparsebit_clear(s, 0); sparsebit_clear_num(s, 1, ~(sparsebit_idx_t) 0); assert(!sparsebit_any_set(s)); } static size_t display_range(FILE *stream, sparsebit_idx_t low, sparsebit_idx_t high, bool prepend_comma_space) { char *fmt_str; size_t sz; /* Determine the printf format string */ if (low == high) fmt_str = prepend_comma_space ? ", 0x%lx" : "0x%lx"; else fmt_str = prepend_comma_space ? ", 0x%lx:0x%lx" : "0x%lx:0x%lx"; /* * When stream is NULL, just determine the size of what would * have been printed, else print the range. */ if (!stream) sz = snprintf(NULL, 0, fmt_str, low, high); else sz = fprintf(stream, fmt_str, low, high); return sz; } /* Dumps to the FILE stream given by stream, the bit settings * of s. Each line of output is prefixed with the number of * spaces given by indent. The length of each line is implementation * dependent and does not depend on the indent amount. The following * is an example output of a sparsebit array that has bits: * * 0x5, 0x8, 0xa:0xe, 0x12 * * This corresponds to a sparsebit whose bits 5, 8, 10, 11, 12, 13, 14, 18 * are set. Note that a ':', instead of a '-' is used to specify a range of * contiguous bits. This is done because '-' is used to specify command-line * options, and sometimes ranges are specified as command-line arguments. */ void sparsebit_dump(FILE *stream, struct sparsebit *s, unsigned int indent) { size_t current_line_len = 0; size_t sz; struct node *nodep; if (!sparsebit_any_set(s)) return; /* Display initial indent */ fprintf(stream, "%*s", indent, ""); /* For each node */ for (nodep = node_first(s); nodep; nodep = node_next(s, nodep)) { unsigned int n1; sparsebit_idx_t low, high; /* For each group of bits in the mask */ for (n1 = 0; n1 < MASK_BITS; n1++) { if (nodep->mask & (1 << n1)) { low = high = nodep->idx + n1; for (; n1 < MASK_BITS; n1++) { if (nodep->mask & (1 << n1)) high = nodep->idx + n1; else break; } if ((n1 == MASK_BITS) && nodep->num_after) high += nodep->num_after; /* * How much room will it take to display * this range. */ sz = display_range(NULL, low, high, current_line_len != 0); /* * If there is not enough room, display * a newline plus the indent of the next * line. */ if (current_line_len + sz > DUMP_LINE_MAX) { fputs("\n", stream); fprintf(stream, "%*s", indent, ""); current_line_len = 0; } /* Display the range */ sz = display_range(stream, low, high, current_line_len != 0); current_line_len += sz; } } /* * If num_after and most significant-bit of mask is not * set, then still need to display a range for the bits * described by num_after. */ if (!(nodep->mask & (1 << (MASK_BITS - 1))) && nodep->num_after) { low = nodep->idx + MASK_BITS; high = nodep->idx + MASK_BITS + nodep->num_after - 1; /* * How much room will it take to display * this range. */ sz = display_range(NULL, low, high, current_line_len != 0); /* * If there is not enough room, display * a newline plus the indent of the next * line. */ if (current_line_len + sz > DUMP_LINE_MAX) { fputs("\n", stream); fprintf(stream, "%*s", indent, ""); current_line_len = 0; } /* Display the range */ sz = display_range(stream, low, high, current_line_len != 0); current_line_len += sz; } } fputs("\n", stream); } /* Validates the internal state of the sparsebit array given by * s. On error, diagnostic information is printed to stderr and * abort is called. */ void sparsebit_validate_internal(struct sparsebit *s) { bool error_detected = false; struct node *nodep, *prev = NULL; sparsebit_num_t total_bits_set = 0; unsigned int n1; /* For each node */ for (nodep = node_first(s); nodep; prev = nodep, nodep = node_next(s, nodep)) { /* * Increase total bits set by the number of bits set * in this node. */ for (n1 = 0; n1 < MASK_BITS; n1++) if (nodep->mask & (1 << n1)) total_bits_set++; total_bits_set += nodep->num_after; /* * Arbitrary choice as to whether a mask of 0 is allowed * or not. For diagnostic purposes it is beneficial to * have only one valid means to represent a set of bits. * To support this an arbitrary choice has been made * to not allow a mask of zero. */ if (nodep->mask == 0) { fprintf(stderr, "Node mask of zero, " "nodep: %p nodep->mask: 0x%x", nodep, nodep->mask); error_detected = true; break; } /* * Validate num_after is not greater than the max index * - the number of mask bits. The num_after member * uses 0-based indexing and thus has no value that * represents all bits set. This limitation is handled * by requiring a non-zero mask. With a non-zero mask, * MASK_BITS worth of bits are described by the mask, * which makes the largest needed num_after equal to: * * (~(sparsebit_num_t) 0) - MASK_BITS + 1 */ if (nodep->num_after > (~(sparsebit_num_t) 0) - MASK_BITS + 1) { fprintf(stderr, "num_after too large, " "nodep: %p nodep->num_after: 0x%lx", nodep, nodep->num_after); error_detected = true; break; } /* Validate node index is divisible by the mask size */ if (nodep->idx % MASK_BITS) { fprintf(stderr, "Node index not divisible by " "mask size,\n" " nodep: %p nodep->idx: 0x%lx " "MASK_BITS: %lu\n", nodep, nodep->idx, MASK_BITS); error_detected = true; break; } /* * Validate bits described by node don't wrap beyond the * highest supported index. */ if ((nodep->idx + MASK_BITS + nodep->num_after - 1) < nodep->idx) { fprintf(stderr, "Bits described by node wrap " "beyond highest supported index,\n" " nodep: %p nodep->idx: 0x%lx\n" " MASK_BITS: %lu nodep->num_after: 0x%lx", nodep, nodep->idx, MASK_BITS, nodep->num_after); error_detected = true; break; } /* Check parent pointers. */ if (nodep->left) { if (nodep->left->parent != nodep) { fprintf(stderr, "Left child parent pointer " "doesn't point to this node,\n" " nodep: %p nodep->left: %p " "nodep->left->parent: %p", nodep, nodep->left, nodep->left->parent); error_detected = true; break; } } if (nodep->right) { if (nodep->right->parent != nodep) { fprintf(stderr, "Right child parent pointer " "doesn't point to this node,\n" " nodep: %p nodep->right: %p " "nodep->right->parent: %p", nodep, nodep->right, nodep->right->parent); error_detected = true; break; } } if (!nodep->parent) { if (s->root != nodep) { fprintf(stderr, "Unexpected root node, " "s->root: %p nodep: %p", s->root, nodep); error_detected = true; break; } } if (prev) { /* * Is index of previous node before index of * current node? */ if (prev->idx >= nodep->idx) { fprintf(stderr, "Previous node index " ">= current node index,\n" " prev: %p prev->idx: 0x%lx\n" " nodep: %p nodep->idx: 0x%lx", prev, prev->idx, nodep, nodep->idx); error_detected = true; break; } /* * Nodes occur in asscending order, based on each * nodes starting index. */ if ((prev->idx + MASK_BITS + prev->num_after - 1) >= nodep->idx) { fprintf(stderr, "Previous node bit range " "overlap with current node bit range,\n" " prev: %p prev->idx: 0x%lx " "prev->num_after: 0x%lx\n" " nodep: %p nodep->idx: 0x%lx " "nodep->num_after: 0x%lx\n" " MASK_BITS: %lu", prev, prev->idx, prev->num_after, nodep, nodep->idx, nodep->num_after, MASK_BITS); error_detected = true; break; } /* * When the node has all mask bits set, it shouldn't * be adjacent to the last bit described by the * previous node. */ if (nodep->mask == ~(mask_t) 0 && prev->idx + MASK_BITS + prev->num_after == nodep->idx) { fprintf(stderr, "Current node has mask with " "all bits set and is adjacent to the " "previous node,\n" " prev: %p prev->idx: 0x%lx " "prev->num_after: 0x%lx\n" " nodep: %p nodep->idx: 0x%lx " "nodep->num_after: 0x%lx\n" " MASK_BITS: %lu", prev, prev->idx, prev->num_after, nodep, nodep->idx, nodep->num_after, MASK_BITS); error_detected = true; break; } } } if (!error_detected) { /* * Is sum of bits set in each node equal to the count * of total bits set. */ if (s->num_set != total_bits_set) { fprintf(stderr, "Number of bits set mismatch,\n" " s->num_set: 0x%lx total_bits_set: 0x%lx", s->num_set, total_bits_set); error_detected = true; } } if (error_detected) { fputs(" dump_internal:\n", stderr); sparsebit_dump_internal(stderr, s, 4); abort(); } } #ifdef FUZZ /* A simple but effective fuzzing driver. Look for bugs with the help * of some invariants and of a trivial representation of sparsebit. * Just use 512 bytes of /dev/zero and /dev/urandom as inputs, and let * afl-fuzz do the magic. :) */ #include <stdlib.h> struct range { sparsebit_idx_t first, last; bool set; }; struct sparsebit *s; struct range ranges[1000]; int num_ranges; static bool get_value(sparsebit_idx_t idx) { int i; for (i = num_ranges; --i >= 0; ) if (ranges[i].first <= idx && idx <= ranges[i].last) return ranges[i].set; return false; } static void operate(int code, sparsebit_idx_t first, sparsebit_idx_t last) { sparsebit_num_t num; sparsebit_idx_t next; if (first < last) { num = last - first + 1; } else { num = first - last + 1; first = last; last = first + num - 1; } switch (code) { case 0: sparsebit_set(s, first); assert(sparsebit_is_set(s, first)); assert(!sparsebit_is_clear(s, first)); assert(sparsebit_any_set(s)); assert(!sparsebit_all_clear(s)); if (get_value(first)) return; if (num_ranges == 1000) exit(0); ranges[num_ranges++] = (struct range) { .first = first, .last = first, .set = true }; break; case 1: sparsebit_clear(s, first); assert(!sparsebit_is_set(s, first)); assert(sparsebit_is_clear(s, first)); assert(sparsebit_any_clear(s)); assert(!sparsebit_all_set(s)); if (!get_value(first)) return; if (num_ranges == 1000) exit(0); ranges[num_ranges++] = (struct range) { .first = first, .last = first, .set = false }; break; case 2: assert(sparsebit_is_set(s, first) == get_value(first)); assert(sparsebit_is_clear(s, first) == !get_value(first)); break; case 3: if (sparsebit_any_set(s)) assert(get_value(sparsebit_first_set(s))); if (sparsebit_any_clear(s)) assert(!get_value(sparsebit_first_clear(s))); sparsebit_set_all(s); assert(!sparsebit_any_clear(s)); assert(sparsebit_all_set(s)); num_ranges = 0; ranges[num_ranges++] = (struct range) { .first = 0, .last = ~(sparsebit_idx_t)0, .set = true }; break; case 4: if (sparsebit_any_set(s)) assert(get_value(sparsebit_first_set(s))); if (sparsebit_any_clear(s)) assert(!get_value(sparsebit_first_clear(s))); sparsebit_clear_all(s); assert(!sparsebit_any_set(s)); assert(sparsebit_all_clear(s)); num_ranges = 0; break; case 5: next = sparsebit_next_set(s, first); assert(next == 0 || next > first); assert(next == 0 || get_value(next)); break; case 6: next = sparsebit_next_clear(s, first); assert(next == 0 || next > first); assert(next == 0 || !get_value(next)); break; case 7: next = sparsebit_next_clear(s, first); if (sparsebit_is_set_num(s, first, num)) { assert(next == 0 || next > last); if (first) next = sparsebit_next_set(s, first - 1); else if (sparsebit_any_set(s)) next = sparsebit_first_set(s); else return; assert(next == first); } else { assert(sparsebit_is_clear(s, first) || next <= last); } break; case 8: next = sparsebit_next_set(s, first); if (sparsebit_is_clear_num(s, first, num)) { assert(next == 0 || next > last); if (first) next = sparsebit_next_clear(s, first - 1); else if (sparsebit_any_clear(s)) next = sparsebit_first_clear(s); else return; assert(next == first); } else { assert(sparsebit_is_set(s, first) || next <= last); } break; case 9: sparsebit_set_num(s, first, num); assert(sparsebit_is_set_num(s, first, num)); assert(!sparsebit_is_clear_num(s, first, num)); assert(sparsebit_any_set(s)); assert(!sparsebit_all_clear(s)); if (num_ranges == 1000) exit(0); ranges[num_ranges++] = (struct range) { .first = first, .last = last, .set = true }; break; case 10: sparsebit_clear_num(s, first, num); assert(!sparsebit_is_set_num(s, first, num)); assert(sparsebit_is_clear_num(s, first, num)); assert(sparsebit_any_clear(s)); assert(!sparsebit_all_set(s)); if (num_ranges == 1000) exit(0); ranges[num_ranges++] = (struct range) { .first = first, .last = last, .set = false }; break; case 11: sparsebit_validate_internal(s); break; default: break; } } unsigned char get8(void) { int ch; ch = getchar(); if (ch == EOF) exit(0); return ch; } uint64_t get64(void) { uint64_t x; x = get8(); x = (x << 8) | get8(); x = (x << 8) | get8(); x = (x << 8) | get8(); x = (x << 8) | get8(); x = (x << 8) | get8(); x = (x << 8) | get8(); return (x << 8) | get8(); } int main(void) { s = sparsebit_alloc(); for (;;) { uint8_t op = get8() & 0xf; uint64_t first = get64(); uint64_t last = get64(); operate(op, first, last); } } #endif
117949.c
/* $OpenBSD: vasprintf.c,v 1.5 1998/08/14 21:39:41 deraadt Exp $ */ /* * Copyright (c) 1997 Todd C. Miller <Todd.Miller@courtesan.com> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED ``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. */ #if defined(LIBC_SCCS) && !defined(lint) static char rcsid[] = "$OpenBSD: vasprintf.c,v 1.5 1998/08/14 21:39:41 deraadt Exp $"; #endif /* LIBC_SCCS and not lint */ #include <stdio.h> #include <stdlib.h> #include <errno.h> int vasprintf(str, fmt, ap) char **str; const char *fmt; _BSD_VA_LIST_ ap; { int ret; FILE f; unsigned char *_base; f._file = -1; f._flags = __SWR | __SSTR | __SALC; f._bf._base = f._p = (unsigned char *)malloc(128); if (f._bf._base == NULL) { *str = NULL; errno = ENOMEM; return (-1); } f._bf._size = f._w = 127; /* Leave room for the NULL */ ret = vfprintf(&f, fmt, ap); *f._p = '\0'; _base = realloc(f._bf._base, f._bf._size + 1); if (_base == NULL) { if (f._bf._base) free(f._bf._base); f._bf._base = NULL; errno = ENOMEM; ret = -1; } f._bf._base = _base; *str = (char *)f._bf._base; return (ret); }
690146.c
/* * Copyright (c) 2019 Peter Bigot Consulting, LLC * * SPDX-License-Identifier: Apache-2.0 */ #include <drivers/adc.h> int adc_gain_invert(enum adc_gain gain, s32_t *value) { struct gain_desc { u8_t mul; u8_t div; }; static const struct gain_desc gains[] = { [ADC_GAIN_1_6] = {.mul = 6, .div = 1}, [ADC_GAIN_1_5] = {.mul = 5, .div = 1}, [ADC_GAIN_1_4] = {.mul = 4, .div = 1}, [ADC_GAIN_1_3] = {.mul = 3, .div = 1}, [ADC_GAIN_1_2] = {.mul = 2, .div = 1}, [ADC_GAIN_2_3] = {.mul = 3, .div = 2}, [ADC_GAIN_1] = {.mul = 1, .div = 1}, [ADC_GAIN_2] = {.mul = 1, .div = 2}, [ADC_GAIN_3] = {.mul = 1, .div = 3}, [ADC_GAIN_4] = {.mul = 1, .div = 4}, [ADC_GAIN_8] = {.mul = 1, .div = 8}, [ADC_GAIN_16] = {.mul = 1, .div = 16}, [ADC_GAIN_32] = {.mul = 1, .div = 32}, [ADC_GAIN_64] = {.mul = 1, .div = 64}, }; int rv = -EINVAL; if ((u8_t)gain < ARRAY_SIZE(gains)) { const struct gain_desc *gdp = &gains[gain]; if ((gdp->mul != 0) && (gdp->div != 0)) { *value = (gdp->mul * *value) / gdp->div; rv = 0; } } return rv; }
671788.c
/******************************************************************************* * Copyright (c) 2013-2017, Andrés Martinelli <andmarti@gmail.com * * All rights reserved. * * * * This file is a part of SC-IM * * * * SC-IM is a spreadsheet program that is based on SC. The original authors * * of SC are James Gosling and Mark Weiser, and mods were later added by * * Chuck Martin. * * * * Redistribution and use in source and binary forms, with or without * * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright * * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * * notice, this list of conditions and the following disclaimer in the * * documentation and/or other materials provided with the distribution. * * 3. All advertising materials mentioning features or use of this software * * must display the following acknowledgement: * * This product includes software developed by Andrés Martinelli * * <andmarti@gmail.com>. * * 4. Neither the name of the Andrés Martinelli 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 ANDRES MARTINELLI ''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 ANDRES MARTINELLI 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 * * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * *******************************************************************************/ /** * \file string.c * \author Andrés Martinelli <andmarti@gmail.com> * \date 2017-07-18 * \brief TODO Write a brief file description. */ #include <stdlib.h> #include <string.h> #include <ctype.h> // for isdigit #include <wctype.h> // for iswprint #include <wchar.h> #include <stdio.h> #include "string.h" #include <curses.h> #include "../sc.h" #include "../macros.h" /** * \brief Remove POSICION character of a cell (zero based) * * \param[in] str * \param[in] posicion * * \return 0 on success * \return -1 otherwise */ int del_char(char * str, int posicion) { int i, slen = strlen(str); if ( posicion >= slen || posicion < 0 ) return -1; for (i = posicion; i < slen - 1; i++) { str[i] = str[i + 1]; } str[--slen] = '\0'; return 0; } /** * \brief Remove POSICION character of a cell (zero based) (Wide char version) * * \param[in] srt * \param[in] posicion * * \return 0 on success * \return -1 otherwise */ int del_wchar(wchar_t * str, int posicion) { int i, slen = wcslen(str); if ( posicion >= slen || posicion < 0 ) return -1; for (i = posicion; i < slen - 1; i++) { str[i] = str[i + 1]; } str[--slen] = '\0'; return 0; } /** * \brief Remove D to H characters range of a cell * * \param[in] str * \param[in] d * \param[in] h * * \return 0 on success * \return -1 otherwise */ int del_range_chars(char * str, int d, int h) { int i = 0, j = 0, slen = strlen(str); if ( h >= slen || h < d ) return -1; for (j = 0; j <= (h-d); j++) for (i = d; i < slen - 1; i++) { str[i] = str[i+1]; } str[slen - (h - d) - 1] = '\0'; return 0; } /** * \brief Remove D to H characters range of a cell. Wide char version. * * \param[in] str * \param[in] d * \param[in] h * * \return 0 on success * \return -1 otherwise */ int del_range_wchars(wchar_t * str, int d, int h) { int i = 0, j = 0, slen = wcslen(str); if ( h >= slen || h < d ) return -1; for (j = 0; j <= (h-d); j++) for (i = d; i < slen - 1; i++) { str[i] = str[i+1]; } str[slen - (h - d) - 1] = L'\0'; return 0; } /** * \brief Add a C character to a cell in POSICION. * * \details Wide char version. STR should be * previously allocated with enough memory. * * \param[in] str * \param[in] c * \param[in] posicion * * \return 0 on success * \return -1 otherwise */ int add_char(char * str, char c, int posicion) { int slen = strlen(str); int len = slen - posicion; if (posicion > slen) return -1; while (len) { str[posicion + len] = str[posicion + len -1]; len--; } str[++slen] = '\0'; str[posicion] = c; return 0; } /** * \brief Add a C character to a cell in POSICION. Wade char version. * * \details STR should be previously allocated with enough memory. * * \param[in] str * \param[in] c * \param[in] posicion * * \return 0 on success * \return -1 otherwise */ int add_wchar(wchar_t * str, wchar_t c, int posicion) { int slen = wcslen(str); int len = slen - posicion; if (posicion > slen) return -1; while (len) { str[posicion + len] = str[posicion + len -1]; len--; } str[++slen] = L'\0'; str[posicion] = c; return 0; } /** * \brief Replace all matches FROM character TO character * * \param[in] s * \param[in] from * \param[in] to * * \return none */ void subst(char * s, char from, char to) { while (*s == from) *s++ = to; return; } /** * \brief Rind string B inside string S * * \param[in] * \param[in[ b * * \return S position in B * \return -1 otherwise */ int str_in_str(char * s, char * b) { int slen = strlen(s); int blen = strlen(b); if (! slen || ! blen) return -1; int e = 0; int i; while ( e <= slen-blen ) { for (i=0; i<blen; i++) { if (s[e+i] != b[i]) { break; } } if (i >= blen) return e; else e++; } return -1; } /** * \brief Find string B inside string S. Wide char version. * * \param[in] s * \param[in] b * * \return S position in B * \return -1 otherwise */ int wstr_in_wstr(wchar_t * s, wchar_t * b) { int slen = wcslen(s); int blen = wcslen(b); if (! slen || ! blen) return -1; int e = 0; int i; while ( e <= slen-blen ) { for (i=0; i<blen; i++) { if (s[e+i] != b[i]) { break; } } if (i >= blen) return e; else e++; } return -1; } /** * \brief Returns 1 if special control character is found * * \param[in] d * * \return 1 if special control character is found */ int is_idchar (int d) { switch (d) { case OKEY_LEFT: case OKEY_RIGHT: case OKEY_DOWN: case OKEY_UP: case OKEY_TAB: case OKEY_BS: case OKEY_HOME: case OKEY_END: case OKEY_PGUP: case OKEY_PGDOWN: case OKEY_DEL: //case OKEY_ENTER: case OKEY_ESC: return 1; } return 0; } /** * \brief TODO Document this function * * \param[in] string * \param[in] junk * * \return string */ char * rtrim(char * string, char junk) { char * original = string + strlen(string); while(*--original == junk); *(original + 1) = '\0'; return string; } /** * \brief TODO Document this function * * \param[in] string * \param[in] junk * * \return TODO returns */ char * ltrim(char * string, char junk) { char * original = string; char * p = original; int trimmed = 0; do { if (*original != junk || trimmed) { trimmed = 1; *p++ = *original; } } while (*original++ != '\0'); return string; } /** * \brief Tells if a string represents a numeric value * * \param[in] string * * \return 1 if string represents a numeric value * \return 0 otherwise */ int isnumeric(char * string) { int i, len = strlen(string); int res = true; bool has_dot = false; bool has_dash = false; bool has_digit = false; for (i=0; i<len; i++) { if ( string[i] == '.' && ! has_dot ) { has_dot = true; continue; } if ( string[i] == '-' ) { if (has_digit) { res = false; break; } if (! has_dash) { has_dash = true; } else { res = false; break; } continue; } if ( isdigit(string[i]) ) { has_digit = true; continue; } res = false; break; } return res; } /** * \brief Clean \r and \n from a string * * \param[in] string * * \return 1 of changes were made * \return 0 otherwise */ int clean_carrier(char * string) { int i, changes = 0, len = strlen(string); for (i=0; i<len; i++) { if ( string[i] == '\r' || string[i] == '\n' ) { del_char(string, i); len--; changes = 1; } } return changes; } /** * \brief strtok version that handles null fields * * \param[in] line * \param[in] delims * * \return TODO returns */ char * xstrtok(char * line, char * delims) { static char * saveline = NULL; char * p; int n; if (line != NULL) saveline = line; // see if we have reached the end of the line if (saveline == NULL || *saveline == '\0') return(NULL); // return the number of characters that aren't delims n = strcspn(saveline, delims); p = saveline; // save start of this token saveline += n; // bump past the delim if (*saveline != '\0') // trash the delim if necessary *saveline++ = '\0'; return p; } /** * \brief Change the number of occurences of a word in s. Not used. * * \param[in] s * \param[in] word * \param[in] overlap * * \return c */ int count_word_occurrences(char * s, char * word, int overlap) { int c = 0, l = strlen(word); while (*s != '\0') { if (strncmp(s++, word, l)) continue; if (!overlap) s += l - 1; c++; } return c; } /** * \brief Search substr word inside string and replace all its occurances with replacement * * \param[in] string * \param[in] substr * \param[in] replacement * * \return resulting string */ char * str_replace ( const char * string, const char * substr, const char * replacement){ char * tok = NULL; char * newstr = NULL; char * oldstr = NULL; char * head = NULL; /* if either substr or replacement is NULL, duplicate string a let caller handle it */ if ( substr == NULL || replacement == NULL ) return strdup (string); newstr = strdup (string); head = newstr; while ( (tok = strstr ( head, substr ))) { oldstr = newstr; newstr = malloc ( strlen ( oldstr ) - strlen ( substr ) + strlen ( replacement ) + 1 ); /* failed to alloc mem, free old string and return NULL */ if ( newstr == NULL ){ free (oldstr); return NULL; } memcpy ( newstr, oldstr, tok - oldstr ); memcpy ( newstr + (tok - oldstr), replacement, strlen ( replacement ) ); memcpy ( newstr + (tok - oldstr) + strlen( replacement ), tok + strlen ( substr ), strlen ( oldstr ) - strlen ( substr ) - ( tok - oldstr ) ); memset ( newstr + strlen ( oldstr ) - strlen ( substr ) + strlen ( replacement ) , 0, 1 ); /* move back head right after the last replacement */ head = newstr + (tok - oldstr) + strlen( replacement ); free (oldstr); } return newstr; } /** * \brief TODO Document uppercase() * * \param[in] sPtr * * \return none */ void uppercase(char * sPtr) { for(; *sPtr != '\0'; ++sPtr) *sPtr = toupper(*sPtr); } /** * \brief TODO Document sc+isprint() * * \param[in] d * * \return TODO returns */ int sc_isprint(int d) { if ( ((d > 31) && (d < 127)) || ((d > 127) && (d < 255)) || iswprint(d) ) return 1; return 0; } /** * \brief Return the number of wide chars of wchar_t * s string. Needed to * fill p column positions. * * \param[in] s * \param[in] p * * \return TODO returns */ int count_width_widestring(const wchar_t * s, int p) { int n; int c_width = 0; for (n=0; n<wcslen(s); n++) { c_width += wcwidth( s[n] ); if (c_width > p) break; } return n; }
392448.c
// http://stackoverflow.com/questions/5083465/fast-efficient-least-squares-fit-algorithm-in-c // "AFAIK the code is public domain." // -Mark Lakata /* linreg(int n, REAL x[], REAL y[], REAL* b, REAL* m, REAL* r) n = number of data points x,y = arrays of data *b = output intercept *m = output slope *r = output correlation coefficient (can be NULL if you don't want it) */ //#define REAL float #define REAL double inline static REAL sqr(REAL x) { return x*x; } int linreg(int n, const REAL x[], const REAL y[], REAL* m, REAL* b, REAL* r) { REAL sumx = 0.0; /* sum of x */ REAL sumx2 = 0.0; /* sum of x**2 */ REAL sumxy = 0.0; /* sum of x * y */ REAL sumy = 0.0; /* sum of y */ REAL sumy2 = 0.0; /* sum of y**2 */ for (int i=0;i<n;i++) { sumx += x[i]; sumx2 += sqr(x[i]); sumxy += x[i] * y[i]; sumy += y[i]; sumy2 += sqr(y[i]); } REAL denom = (n * sumx2 - sqr(sumx)); if (denom == 0) { // singular matrix. can't solve the problem. *m = 0; *b = 0; if (r) *r = 0; return 0; } *m = (n * sumxy - sumx * sumy) / denom; *b = (sumy * sumx2 - sumx * sumxy) / denom; if (r!=NULL) { *r = (sumxy - sumx * sumy / n) / /* compute correlation coeff */ sqrt((sumx2 - sqr(sumx)/n) * (sumy2 - sqr(sumy)/n)); } return 1; }
114792.c
/* Terratec ActiveRadio ISA Standalone card driver for Linux radio support * (c) 1999 R. Offermanns (rolf@offermanns.de) * based on the aimslab radio driver from M. Kirkwood * many thanks to Michael Becker and Friedhelm Birth (from TerraTec) * * * History: * 1999-05-21 First preview release * * Notes on the hardware: * There are two "main" chips on the card: * - Philips OM5610 (http://www-us.semiconductors.philips.com/acrobat/datasheets/OM5610_2.pdf) * - Philips SAA6588 (http://www-us.semiconductors.philips.com/acrobat/datasheets/SAA6588_1.pdf) * (you can get the datasheet at the above links) * * Frequency control is done digitally -- ie out(port,encodefreq(95.8)); * Volume Control is done digitally * * there is a I2C controlled RDS decoder (SAA6588) onboard, which i would like to support someday * (as soon i have understand how to get started :) * If you can help me out with that, please contact me!! * * * Converted to V4L2 API by Mauro Carvalho Chehab <mchehab@infradead.org> */ #include <linux/module.h> /* Modules */ #include <linux/init.h> /* Initdata */ #include <linux/ioport.h> /* request_region */ #include <linux/videodev2.h> /* kernel radio structs */ #include <linux/mutex.h> #include <linux/version.h> /* for KERNEL_VERSION MACRO */ #include <linux/io.h> /* outb, outb_p */ #include <media/v4l2-device.h> #include <media/v4l2-ioctl.h> MODULE_AUTHOR("R.OFFERMANNS & others"); MODULE_DESCRIPTION("A driver for the TerraTec ActiveRadio Standalone radio card."); MODULE_LICENSE("GPL"); #ifndef CONFIG_RADIO_TERRATEC_PORT #define CONFIG_RADIO_TERRATEC_PORT 0x590 #endif static int io = CONFIG_RADIO_TERRATEC_PORT; static int radio_nr = -1; module_param(io, int, 0); MODULE_PARM_DESC(io, "I/O address of the TerraTec ActiveRadio card (0x590 or 0x591)"); module_param(radio_nr, int, 0); #define RADIO_VERSION KERNEL_VERSION(0, 0, 2) static struct v4l2_queryctrl radio_qctrl[] = { { .id = V4L2_CID_AUDIO_MUTE, .name = "Mute", .minimum = 0, .maximum = 1, .default_value = 1, .type = V4L2_CTRL_TYPE_BOOLEAN, },{ .id = V4L2_CID_AUDIO_VOLUME, .name = "Volume", .minimum = 0, .maximum = 0xff, .step = 1, .default_value = 0xff, .type = V4L2_CTRL_TYPE_INTEGER, } }; #define WRT_DIS 0x00 #define CLK_OFF 0x00 #define IIC_DATA 0x01 #define IIC_CLK 0x02 #define DATA 0x04 #define CLK_ON 0x08 #define WRT_EN 0x10 struct terratec { struct v4l2_device v4l2_dev; struct video_device vdev; int io; int curvol; unsigned long curfreq; int muted; struct mutex lock; }; static struct terratec terratec_card; /* local things */ static void tt_write_vol(struct terratec *tt, int volume) { int i; volume = volume + (volume * 32); /* change both channels */ mutex_lock(&tt->lock); for (i = 0; i < 8; i++) { if (volume & (0x80 >> i)) outb(0x80, tt->io + 1); else outb(0x00, tt->io + 1); } mutex_unlock(&tt->lock); } static void tt_mute(struct terratec *tt) { tt->muted = 1; tt_write_vol(tt, 0); } static int tt_setvol(struct terratec *tt, int vol) { if (vol == tt->curvol) { /* requested volume = current */ if (tt->muted) { /* user is unmuting the card */ tt->muted = 0; tt_write_vol(tt, vol); /* enable card */ } return 0; } if (vol == 0) { /* volume = 0 means mute the card */ tt_write_vol(tt, 0); /* "turn off card" by setting vol to 0 */ tt->curvol = vol; /* track the volume state! */ return 0; } tt->muted = 0; tt_write_vol(tt, vol); tt->curvol = vol; return 0; } /* this is the worst part in this driver */ /* many more or less strange things are going on here, but hey, it works :) */ static int tt_setfreq(struct terratec *tt, unsigned long freq1) { int freq; int i; int p; int temp; long rest; unsigned char buffer[25]; /* we have to bit shift 25 registers */ mutex_lock(&tt->lock); tt->curfreq = freq1; freq = freq1 / 160; /* convert the freq. to a nice to handle value */ memset(buffer, 0, sizeof(buffer)); rest = freq * 10 + 10700; /* I once had understood what is going on here */ /* maybe some wise guy (friedhelm?) can comment this stuff */ i = 13; p = 10; temp = 102400; while (rest != 0) { if (rest % temp == rest) buffer[i] = 0; else { buffer[i] = 1; rest = rest - temp; } i--; p--; temp = temp / 2; } for (i = 24; i > -1; i--) { /* bit shift the values to the radiocard */ if (buffer[i] == 1) { outb(WRT_EN | DATA, tt->io); outb(WRT_EN | DATA | CLK_ON, tt->io); outb(WRT_EN | DATA, tt->io); } else { outb(WRT_EN | 0x00, tt->io); outb(WRT_EN | 0x00 | CLK_ON, tt->io); } } outb(0x00, tt->io); mutex_unlock(&tt->lock); return 0; } static int tt_getsigstr(struct terratec *tt) { if (inb(tt->io) & 2) /* bit set = no signal present */ return 0; return 1; /* signal present */ } static int vidioc_querycap(struct file *file, void *priv, struct v4l2_capability *v) { strlcpy(v->driver, "radio-terratec", sizeof(v->driver)); strlcpy(v->card, "ActiveRadio", sizeof(v->card)); strlcpy(v->bus_info, "ISA", sizeof(v->bus_info)); v->version = RADIO_VERSION; v->capabilities = V4L2_CAP_TUNER | V4L2_CAP_RADIO; return 0; } static int vidioc_g_tuner(struct file *file, void *priv, struct v4l2_tuner *v) { struct terratec *tt = video_drvdata(file); if (v->index > 0) return -EINVAL; strlcpy(v->name, "FM", sizeof(v->name)); v->type = V4L2_TUNER_RADIO; v->rangelow = 87 * 16000; v->rangehigh = 108 * 16000; v->rxsubchans = V4L2_TUNER_SUB_MONO; v->capability = V4L2_TUNER_CAP_LOW; v->audmode = V4L2_TUNER_MODE_MONO; v->signal = 0xFFFF * tt_getsigstr(tt); return 0; } static int vidioc_s_tuner(struct file *file, void *priv, struct v4l2_tuner *v) { return v->index ? -EINVAL : 0; } static int vidioc_s_frequency(struct file *file, void *priv, struct v4l2_frequency *f) { struct terratec *tt = video_drvdata(file); if (f->tuner != 0 || f->type != V4L2_TUNER_RADIO) return -EINVAL; tt_setfreq(tt, f->frequency); return 0; } static int vidioc_g_frequency(struct file *file, void *priv, struct v4l2_frequency *f) { struct terratec *tt = video_drvdata(file); if (f->tuner != 0) return -EINVAL; f->type = V4L2_TUNER_RADIO; f->frequency = tt->curfreq; return 0; } static int vidioc_queryctrl(struct file *file, void *priv, struct v4l2_queryctrl *qc) { int i; for (i = 0; i < ARRAY_SIZE(radio_qctrl); i++) { if (qc->id && qc->id == radio_qctrl[i].id) { memcpy(qc, &(radio_qctrl[i]), sizeof(*qc)); return 0; } } return -EINVAL; } static int vidioc_g_ctrl(struct file *file, void *priv, struct v4l2_control *ctrl) { struct terratec *tt = video_drvdata(file); switch (ctrl->id) { case V4L2_CID_AUDIO_MUTE: if (tt->muted) ctrl->value = 1; else ctrl->value = 0; return 0; case V4L2_CID_AUDIO_VOLUME: ctrl->value = tt->curvol * 6554; return 0; } return -EINVAL; } static int vidioc_s_ctrl(struct file *file, void *priv, struct v4l2_control *ctrl) { struct terratec *tt = video_drvdata(file); switch (ctrl->id) { case V4L2_CID_AUDIO_MUTE: if (ctrl->value) tt_mute(tt); else tt_setvol(tt,tt->curvol); return 0; case V4L2_CID_AUDIO_VOLUME: tt_setvol(tt,ctrl->value); return 0; } return -EINVAL; } static int vidioc_g_input(struct file *filp, void *priv, unsigned int *i) { *i = 0; return 0; } static int vidioc_s_input(struct file *filp, void *priv, unsigned int i) { return i ? -EINVAL : 0; } static int vidioc_g_audio(struct file *file, void *priv, struct v4l2_audio *a) { a->index = 0; strlcpy(a->name, "Radio", sizeof(a->name)); a->capability = V4L2_AUDCAP_STEREO; return 0; } static int vidioc_s_audio(struct file *file, void *priv, struct v4l2_audio *a) { return a->index ? -EINVAL : 0; } static const struct v4l2_file_operations terratec_fops = { .owner = THIS_MODULE, .ioctl = video_ioctl2, }; static const struct v4l2_ioctl_ops terratec_ioctl_ops = { .vidioc_querycap = vidioc_querycap, .vidioc_g_tuner = vidioc_g_tuner, .vidioc_s_tuner = vidioc_s_tuner, .vidioc_g_frequency = vidioc_g_frequency, .vidioc_s_frequency = vidioc_s_frequency, .vidioc_queryctrl = vidioc_queryctrl, .vidioc_g_ctrl = vidioc_g_ctrl, .vidioc_s_ctrl = vidioc_s_ctrl, .vidioc_g_audio = vidioc_g_audio, .vidioc_s_audio = vidioc_s_audio, .vidioc_g_input = vidioc_g_input, .vidioc_s_input = vidioc_s_input, }; static int __init terratec_init(void) { struct terratec *tt = &terratec_card; struct v4l2_device *v4l2_dev = &tt->v4l2_dev; int res; strlcpy(v4l2_dev->name, "terratec", sizeof(v4l2_dev->name)); tt->io = io; if (tt->io == -1) { v4l2_err(v4l2_dev, "you must set an I/O address with io=0x590 or 0x591\n"); return -EINVAL; } if (!request_region(tt->io, 2, "terratec")) { v4l2_err(v4l2_dev, "port 0x%x already in use\n", io); return -EBUSY; } res = v4l2_device_register(NULL, v4l2_dev); if (res < 0) { release_region(tt->io, 2); v4l2_err(v4l2_dev, "Could not register v4l2_device\n"); return res; } strlcpy(tt->vdev.name, v4l2_dev->name, sizeof(tt->vdev.name)); tt->vdev.v4l2_dev = v4l2_dev; tt->vdev.fops = &terratec_fops; tt->vdev.ioctl_ops = &terratec_ioctl_ops; tt->vdev.release = video_device_release_empty; video_set_drvdata(&tt->vdev, tt); mutex_init(&tt->lock); if (video_register_device(&tt->vdev, VFL_TYPE_RADIO, radio_nr) < 0) { v4l2_device_unregister(&tt->v4l2_dev); release_region(tt->io, 2); return -EINVAL; } v4l2_info(v4l2_dev, "TERRATEC ActivRadio Standalone card driver.\n"); /* mute card - prevents noisy bootups */ tt_write_vol(tt, 0); return 0; } static void __exit terratec_exit(void) { struct terratec *tt = &terratec_card; struct v4l2_device *v4l2_dev = &tt->v4l2_dev; video_unregister_device(&tt->vdev); v4l2_device_unregister(&tt->v4l2_dev); release_region(tt->io, 2); v4l2_info(v4l2_dev, "TERRATEC ActivRadio Standalone card driver unloaded.\n"); } module_init(terratec_init); module_exit(terratec_exit);
373286.c
/* * Copyright 2015-present MongoDB, Inc. * * 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 <mongoc/mongoc.h> #include "mongoc/mongoc-collection-private.h" #include "mongoc/mongoc-util-private.h" #include "mongoc/mongoc-uri-private.h" #include "json-test.h" #include "json-test-operations.h" #include "json-test-monitoring.h" #include "TestSuite.h" #include "test-libmongoc.h" #ifdef _MSC_VER #include <io.h> #else #include <dirent.h> #endif #ifdef BSON_HAVE_STRINGS_H #include <strings.h> #endif mongoc_topology_description_type_t topology_type_from_test (const char *type) { if (strcmp (type, "ReplicaSetWithPrimary") == 0) { return MONGOC_TOPOLOGY_RS_WITH_PRIMARY; } else if (strcmp (type, "ReplicaSetNoPrimary") == 0) { return MONGOC_TOPOLOGY_RS_NO_PRIMARY; } else if (strcmp (type, "Unknown") == 0) { return MONGOC_TOPOLOGY_UNKNOWN; } else if (strcmp (type, "Single") == 0) { return MONGOC_TOPOLOGY_SINGLE; } else if (strcmp (type, "Sharded") == 0) { return MONGOC_TOPOLOGY_SHARDED; } fprintf (stderr, "can't parse this: %s", type); BSON_ASSERT (0); return 0; } mongoc_server_description_type_t server_type_from_test (const char *type) { if (strcmp (type, "RSPrimary") == 0) { return MONGOC_SERVER_RS_PRIMARY; } else if (strcmp (type, "RSSecondary") == 0) { return MONGOC_SERVER_RS_SECONDARY; } else if (strcmp (type, "Standalone") == 0) { return MONGOC_SERVER_STANDALONE; } else if (strcmp (type, "Mongos") == 0) { return MONGOC_SERVER_MONGOS; } else if (strcmp (type, "PossiblePrimary") == 0) { return MONGOC_SERVER_POSSIBLE_PRIMARY; } else if (strcmp (type, "RSArbiter") == 0) { return MONGOC_SERVER_RS_ARBITER; } else if (strcmp (type, "RSOther") == 0) { return MONGOC_SERVER_RS_OTHER; } else if (strcmp (type, "RSGhost") == 0) { return MONGOC_SERVER_RS_GHOST; } else if (strcmp (type, "Unknown") == 0) { return MONGOC_SERVER_UNKNOWN; } fprintf (stderr, "ERROR: Unknown server type %s\n", type); BSON_ASSERT (0); return 0; } static mongoc_read_mode_t read_mode_from_test (const char *mode) { if (bson_strcasecmp (mode, "Primary") == 0) { return MONGOC_READ_PRIMARY; } else if (bson_strcasecmp (mode, "PrimaryPreferred") == 0) { return MONGOC_READ_PRIMARY_PREFERRED; } else if (bson_strcasecmp (mode, "Secondary") == 0) { return MONGOC_READ_SECONDARY; } else if (bson_strcasecmp (mode, "SecondaryPreferred") == 0) { return MONGOC_READ_SECONDARY_PREFERRED; } else if (bson_strcasecmp (mode, "Nearest") == 0) { return MONGOC_READ_NEAREST; } else { test_error ("Unknown read preference mode \"%s\"", mode); } return MONGOC_READ_PRIMARY; } static mongoc_ss_optype_t optype_from_test (const char *op) { if (strcmp (op, "read") == 0) { return MONGOC_SS_READ; } else if (strcmp (op, "write") == 0) { return MONGOC_SS_WRITE; } return MONGOC_SS_READ; } /* *----------------------------------------------------------------------- * * server_description_by_hostname -- * * Return a reference to a mongoc_server_description_t or NULL. * *----------------------------------------------------------------------- */ mongoc_server_description_t * server_description_by_hostname (mongoc_topology_description_t *topology, const char *address) { mongoc_set_t *set = topology->servers; mongoc_server_description_t *server_iter; int i; for (i = 0; i < set->items_len; i++) { server_iter = (mongoc_server_description_t *) mongoc_set_get_item ( topology->servers, i); if (strcasecmp (address, server_iter->connection_address) == 0) { return server_iter; } } return NULL; } /* *----------------------------------------------------------------------- * * process_sdam_test_ismaster_responses -- * * Update a topology description with the ismaster responses in a "phase" * from an SDAM or SDAM Monitoring test, like: * * [ * [ * "a:27017", * { * "ok": 1, * "ismaster": false * } * ] * ] * * See: * https://github.com/mongodb/specifications/tree/master/source/server-discovery-and-monitoring/tests * *----------------------------------------------------------------------- */ void process_sdam_test_ismaster_responses (bson_t *phase, mongoc_topology_description_t *td) { mongoc_server_description_t *sd; bson_t ismasters; bson_t ismaster; bson_t response; bson_iter_t phase_field_iter; bson_iter_t ismaster_iter; bson_iter_t ismaster_field_iter; const char *hostname; /* grab ismaster responses out and feed them to topology */ BSON_ASSERT (bson_iter_init_find (&phase_field_iter, phase, "responses")); bson_iter_bson (&phase_field_iter, &ismasters); bson_iter_init (&ismaster_iter, &ismasters); while (bson_iter_next (&ismaster_iter)) { bson_iter_bson (&ismaster_iter, &ismaster); bson_iter_init_find (&ismaster_field_iter, &ismaster, "0"); hostname = bson_iter_utf8 (&ismaster_field_iter, NULL); sd = server_description_by_hostname (td, hostname); /* if server has been removed from topology, skip */ if (!sd) { continue; } bson_iter_init_find (&ismaster_field_iter, &ismaster, "1"); bson_iter_bson (&ismaster_field_iter, &response); /* send ismaster through the topology description's handler */ capture_logs (true); mongoc_topology_description_handle_ismaster ( td, sd->id, &response, 1, NULL); if (td->servers->items_len == 0) { ASSERT_CAPTURED_LOG ("topology", MONGOC_LOG_LEVEL_WARNING, "Last server removed from topology"); } capture_logs (false); } } /* *----------------------------------------------------------------------- * * test_server_selection_logic_cb -- * * Runs the JSON tests for server selection logic that are * included with the Server Selection spec. * *----------------------------------------------------------------------- */ void test_server_selection_logic_cb (bson_t *test) { bool expected_error; bson_error_t error; int32_t heartbeat_msec; mongoc_topology_description_t topology; mongoc_server_description_t *sd; mongoc_read_prefs_t *read_prefs; mongoc_read_mode_t read_mode; mongoc_ss_optype_t op; bson_iter_t iter; bson_iter_t topology_iter; bson_iter_t server_iter; bson_iter_t sd_iter; bson_iter_t read_pref_iter; bson_iter_t tag_sets_iter; bson_iter_t last_write_iter; bson_iter_t expected_servers_iter; bson_t first_tag_set; bson_t test_topology; bson_t test_servers; bson_t server; bson_t test_read_pref; bson_t test_tag_sets; uint32_t i = 0; bool matched_servers[50]; mongoc_array_t selected_servers; _mongoc_array_init (&selected_servers, sizeof (mongoc_server_description_t *)); BSON_ASSERT (test); expected_error = bson_iter_init_find (&iter, test, "error") && bson_iter_as_bool (&iter); heartbeat_msec = MONGOC_TOPOLOGY_HEARTBEAT_FREQUENCY_MS_SINGLE_THREADED; if (bson_iter_init_find (&iter, test, "heartbeatFrequencyMS")) { heartbeat_msec = bson_iter_int32 (&iter); } /* pull out topology description field */ BSON_ASSERT (bson_iter_init_find (&iter, test, "topology_description")); bson_iter_bson (&iter, &test_topology); /* set topology state from test */ BSON_ASSERT (bson_iter_init_find (&topology_iter, &test_topology, "type")); mongoc_topology_description_init (&topology, heartbeat_msec); topology.type = topology_type_from_test (bson_iter_utf8 (&topology_iter, NULL)); /* for each server description in test, add server to our topology */ BSON_ASSERT ( bson_iter_init_find (&topology_iter, &test_topology, "servers")); bson_iter_bson (&topology_iter, &test_servers); bson_iter_init (&server_iter, &test_servers); while (bson_iter_next (&server_iter)) { bson_iter_bson (&server_iter, &server); /* initialize new server description with given address */ sd = (mongoc_server_description_t *) bson_malloc0 (sizeof *sd); BSON_ASSERT (bson_iter_init_find (&sd_iter, &server, "address")); mongoc_server_description_init (sd, bson_iter_utf8 (&sd_iter, NULL), i++); BSON_ASSERT (bson_iter_init_find (&sd_iter, &server, "type")); sd->type = server_type_from_test (bson_iter_utf8 (&sd_iter, NULL)); if (bson_iter_init_find (&sd_iter, &server, "avg_rtt_ms")) { sd->round_trip_time_msec = bson_iter_int32 (&sd_iter); } else if (sd->type != MONGOC_SERVER_UNKNOWN) { test_error ("%s has no avg_rtt_ms", sd->host.host_and_port); abort (); } if (bson_iter_init_find (&sd_iter, &server, "maxWireVersion")) { sd->max_wire_version = (int32_t) bson_iter_as_int64 (&sd_iter); } if (bson_iter_init_find (&sd_iter, &server, "lastUpdateTime")) { sd->last_update_time_usec = bson_iter_as_int64 (&sd_iter) * 1000; } if (bson_iter_init_find (&sd_iter, &server, "lastWrite")) { BSON_ASSERT (BSON_ITER_HOLDS_DOCUMENT (&sd_iter) && bson_iter_recurse (&sd_iter, &last_write_iter) && bson_iter_find (&last_write_iter, "lastWriteDate") && BSON_ITER_HOLDS_INT (&last_write_iter)); sd->last_write_date_ms = bson_iter_as_int64 (&last_write_iter); } if (bson_iter_init_find (&sd_iter, &server, "tags")) { bson_destroy (&sd->tags); bson_iter_bson (&sd_iter, &sd->tags); } /* add new server to our topology description */ mongoc_set_add (topology.servers, sd->id, sd); } /* create read preference document from test */ BSON_ASSERT (bson_iter_init_find (&iter, test, "read_preference")); bson_iter_bson (&iter, &test_read_pref); if (bson_iter_init_find (&read_pref_iter, &test_read_pref, "mode")) { read_mode = read_mode_from_test (bson_iter_utf8 (&read_pref_iter, NULL)); ASSERT_CMPINT (read_mode, !=, 0); } else { read_mode = MONGOC_READ_PRIMARY; } read_prefs = mongoc_read_prefs_new (read_mode); if (bson_iter_init_find (&read_pref_iter, &test_read_pref, "tag_sets")) { /* ignore "tag_sets: [{}]" */ if (bson_iter_recurse (&read_pref_iter, &tag_sets_iter) && bson_iter_next (&tag_sets_iter) && BSON_ITER_HOLDS_DOCUMENT (&tag_sets_iter)) { bson_iter_bson (&tag_sets_iter, &first_tag_set); if (!bson_empty (&first_tag_set)) { /* not empty */ bson_iter_bson (&read_pref_iter, &test_tag_sets); mongoc_read_prefs_set_tags (read_prefs, &test_tag_sets); } } } if (bson_iter_init_find ( &read_pref_iter, &test_read_pref, "maxStalenessSeconds")) { mongoc_read_prefs_set_max_staleness_seconds ( read_prefs, bson_iter_as_int64 (&read_pref_iter)); } /* get operation type */ op = MONGOC_SS_READ; if (bson_iter_init_find (&iter, test, "operation")) { op = optype_from_test (bson_iter_utf8 (&iter, NULL)); } if (expected_error) { BSON_ASSERT (!mongoc_read_prefs_is_valid (read_prefs) || !mongoc_topology_compatible (&topology, read_prefs, &error)); goto DONE; } /* no expected error */ BSON_ASSERT (mongoc_read_prefs_is_valid (read_prefs)); BSON_ASSERT (mongoc_topology_compatible (&topology, read_prefs, &error)); /* read in latency window servers */ BSON_ASSERT (bson_iter_init_find (&iter, test, "in_latency_window")); /* TODO: use topology_select instead? */ mongoc_topology_description_suitable_servers ( &selected_servers, op, &topology, read_prefs, MONGOC_TOPOLOGY_LOCAL_THRESHOLD_MS); /* check each server in expected_servers is in selected_servers */ memset (matched_servers, 0, sizeof (matched_servers)); bson_iter_recurse (&iter, &expected_servers_iter); while (bson_iter_next (&expected_servers_iter)) { bool found = false; bson_iter_t host; BSON_ASSERT (bson_iter_recurse (&expected_servers_iter, &host)); BSON_ASSERT (bson_iter_find (&host, "address")); for (i = 0; i < selected_servers.len; i++) { sd = _mongoc_array_index ( &selected_servers, mongoc_server_description_t *, i); if (strcmp (sd->host.host_and_port, bson_iter_utf8 (&host, NULL)) == 0) { found = true; break; } } if (!found) { test_error ("Should have been selected but wasn't: %s", bson_iter_utf8 (&host, NULL)); abort (); } matched_servers[i] = true; } /* check each server in selected_servers is in expected_servers */ for (i = 0; i < selected_servers.len; i++) { if (!matched_servers[i]) { sd = _mongoc_array_index ( &selected_servers, mongoc_server_description_t *, i); test_error ("Shouldn't have been selected but was: %s", sd->host.host_and_port); abort (); } } DONE: mongoc_read_prefs_destroy (read_prefs); mongoc_topology_description_destroy (&topology); _mongoc_array_destroy (&selected_servers); } /* *----------------------------------------------------------------------- * * assemble_path -- * * Given a parent directory and filename, compile a full path to * the child file. * * "dst" receives the joined path, delimited by "/" even on Windows. * *----------------------------------------------------------------------- */ void assemble_path (const char *parent_path, const char *child_name, char *dst /* OUT */) { char *p; int path_len = (int) strlen (parent_path); int name_len = (int) strlen (child_name); BSON_ASSERT (path_len + name_len + 1 < MAX_TEST_NAME_LENGTH); memset (dst, '\0', MAX_TEST_NAME_LENGTH * sizeof (char)); strncat (dst, parent_path, path_len); strncat (dst, "/", 1); strncat (dst, child_name, name_len); for (p = dst; *p; ++p) { if (*p == '\\') { *p = '/'; } } } /* *----------------------------------------------------------------------- * * collect_tests_from_dir -- * * Recursively search the directory at @dir_path for files with * '.json' in their filenames. Append all found file paths to * @paths, and return the number of files found. * *----------------------------------------------------------------------- */ int collect_tests_from_dir (char (*paths)[MAX_TEST_NAME_LENGTH] /* OUT */, const char *dir_path, int paths_index, int max_paths) { #ifdef _MSC_VER char *dir_path_plus_star; intptr_t handle; struct _finddata_t info; char child_path[MAX_TEST_NAME_LENGTH]; dir_path_plus_star = bson_strdup_printf ("%s/*", dir_path); handle = _findfirst (dir_path_plus_star, &info); if (handle == -1) { bson_free (dir_path_plus_star); return 0; } while (1) { BSON_ASSERT (paths_index < max_paths); if (info.attrib & _A_SUBDIR) { /* recursively call on child directories */ if (strcmp (info.name, "..") != 0 && strcmp (info.name, ".") != 0) { assemble_path (dir_path, info.name, child_path); paths_index = collect_tests_from_dir ( paths, child_path, paths_index, max_paths); } } else if (strstr (info.name, ".json")) { /* if this is a JSON test, collect its path */ assemble_path (dir_path, info.name, paths[paths_index++]); } if (_findnext (handle, &info) == -1) { break; } } bson_free (dir_path_plus_star); _findclose (handle); return paths_index; #else struct dirent *entry; struct stat dir_stat; char child_path[MAX_TEST_NAME_LENGTH]; DIR *dir; dir = opendir (dir_path); if (!dir) { MONGOC_ERROR ("Cannot open \"%s\"", dir_path); MONGOC_ERROR ("Run test-libmongoc in repository root directory.\n"); abort (); } while ((entry = readdir (dir))) { BSON_ASSERT (paths_index < max_paths); if (strcmp (entry->d_name, "..") == 0 || strcmp (entry->d_name, ".") == 0) { continue; } assemble_path (dir_path, entry->d_name, child_path); if (0 == stat (child_path, &dir_stat) && S_ISDIR (dir_stat.st_mode)) { /* recursively call on child directories */ paths_index = collect_tests_from_dir (paths, child_path, paths_index, max_paths); } else if (strstr (entry->d_name, ".json")) { /* if this is a JSON test, collect its path */ assemble_path (dir_path, entry->d_name, paths[paths_index++]); } } closedir (dir); return paths_index; #endif } /* *----------------------------------------------------------------------- * * get_bson_from_json_file -- * * Open the file at @filename and store its contents in a * bson_t. This function assumes that @filename contains a * single JSON object. * * NOTE: caller owns returned bson_t and must free it. * *----------------------------------------------------------------------- */ bson_t * get_bson_from_json_file (char *filename) { FILE *file; long length; bson_t *data; bson_error_t error; const char *buffer; file = fopen (filename, "rb"); if (!file) { return NULL; } /* get file length */ fseek (file, 0, SEEK_END); length = ftell (file); fseek (file, 0, SEEK_SET); if (length < 1) { return NULL; } /* read entire file into buffer */ buffer = (const char *) bson_malloc0 (length); if (fread ((void *) buffer, 1, length, file) != length) { abort (); } fclose (file); if (!buffer) { return NULL; } /* convert to bson */ data = bson_new_from_json ((const uint8_t *) buffer, length, &error); if (!data) { fprintf (stderr, "Cannot parse %s: %s\n", filename, error.message); abort (); } bson_free ((void *) buffer); return data; } static bool check_version_info (const bson_t *scenario, bool print_reason) { const char *s; char *padded; server_version_t test_version, server_version; if (bson_has_field (scenario, "maxServerVersion")) { s = bson_lookup_utf8 (scenario, "maxServerVersion"); /* s is like "3.0", don't skip if server is 3.0.x but skip 3.1+ */ padded = bson_strdup_printf ("%s.99", s); test_version = test_framework_str_to_version (padded); bson_free (padded); server_version = test_framework_get_server_version (); if (server_version > test_version) { if (print_reason && test_suite_debug_output ()) { printf (" SKIP, maxServerVersion=\"%s\"\n", s); fflush (stdout); } return false; } } if (bson_has_field (scenario, "minServerVersion")) { s = bson_lookup_utf8 (scenario, "minServerVersion"); test_version = test_framework_str_to_version (s); server_version = test_framework_get_server_version (); if (server_version < test_version) { if (print_reason && test_suite_debug_output ()) { printf (" SKIP, minServerVersion=\"%s\"\n", s); fflush (stdout); } return false; } } if (bson_has_field (scenario, "topology")) { bson_iter_t iter; bson_t topology; char *current_topology; BSON_ASSERT (bson_iter_init_find (&iter, scenario, "topology")); BSON_ASSERT (BSON_ITER_HOLDS_ARRAY (&iter)); bson_iter_bson (&iter, &topology); /* Determine cluster type */ if (test_framework_is_mongos ()) { current_topology = "sharded"; } else if (test_framework_is_replset ()) { current_topology = "replicaset"; } else { current_topology = "single"; } bson_iter_init (&iter, &topology); while (bson_iter_next (&iter)) { const char *test_topology; BSON_ASSERT (BSON_ITER_HOLDS_UTF8 (&iter)); test_topology = bson_iter_utf8 (&iter, NULL); if (strcmp (test_topology, current_topology) == 0) { return true; } } /* If we didn't match any of the listed topologies, skip */ if (print_reason && test_suite_debug_output ()) { printf (" SKIP, test topologies do not match current %s setup\n", current_topology); fflush (stdout); } return false; } return true; } static bool check_scenario_version (const bson_t *scenario) { /* version info can be nested inside "runOn" array */ if (bson_has_field (scenario, "runOn")) { bson_iter_t iter; bson_t run_on; bson_t version_info; bson_lookup_doc (scenario, "runOn", &run_on); BSON_ASSERT (bson_iter_init (&iter, &run_on)); while (bson_iter_next (&iter)) { bson_iter_bson (&iter, &version_info); if (check_version_info (&version_info, false)) { return true; } } if (test_suite_debug_output ()) { printf (" SKIP, no matching topologies in runOn\n"); fflush (stdout); } return false; } return check_version_info (scenario, true); } static int check_test_version (const bson_t *test) { const char *s; char *padded; server_version_t test_version, server_version; if (bson_has_field (test, "minServerVersion")) { s = bson_lookup_utf8 (test, "minServerVersion"); test_version = test_framework_str_to_version (s); server_version = test_framework_get_server_version (); if (server_version < test_version) { if (test_suite_debug_output ()) { printf (" SKIP, minServerVersion %s\n", s); fflush (stdout); } return false; } } if (bson_has_field (test, "ignore_if_server_version_greater_than")) { s = bson_lookup_utf8 (test, "ignore_if_server_version_greater_than"); /* s is like "3.0", don't skip if server is 3.0.x but skip 3.1+ */ padded = bson_strdup_printf ("%s.99", s); test_version = test_framework_str_to_version (padded); bson_free (padded); server_version = test_framework_get_server_version (); if (server_version > test_version) { if (test_suite_debug_output ()) { printf (" SKIP, ignore_if_server_version_greater_than %s\n", s); fflush (stdout); } return false; } } if (bson_has_field (test, "ignore_if_server_version_less_than")) { s = bson_lookup_utf8 (test, "ignore_if_server_version_less_than"); test_version = test_framework_str_to_version (s); server_version = test_framework_get_server_version (); if (server_version < test_version) { if (test_suite_debug_output ()) { printf (" SKIP, ignore_if_server_version_less_than %s\n", s); fflush (stdout); } return false; } } /* server version is ok, don't skip the test */ return true; } /* is this test allowed to run against the current test topology? */ static bool check_topology_type (const bson_t *test) { bson_iter_t iter; bson_iter_t child; const char *s; bool compatible; bool is_mongos; bool is_replset; bool is_single; bool match; bool can_proceed; /* "topology" is an array of compatible topologies. * "ignore_if_topology_type" is an array of incompatible types. * So far, the only valid values are "single", "sharded", and "replicaset" */ if (bson_iter_init_find (&iter, test, "topology")) { compatible = true; } else if (bson_iter_init_find (&iter, test, "ignore_if_topology_type")) { compatible = false; } else { return true; } ASSERT (BSON_ITER_HOLDS_ARRAY (&iter)); ASSERT (bson_iter_recurse (&iter, &child)); is_mongos = test_framework_is_mongos (); is_replset = test_framework_is_replset (); is_single = !is_mongos && !is_replset; match = false; while (bson_iter_next (&child)) { if (BSON_ITER_HOLDS_UTF8 (&child)) { s = bson_iter_utf8 (&child, NULL); if (!strcmp (s, "sharded") && is_mongos) { match = true; } else if (!strcmp (s, "replicaset") && is_replset) { match = true; } else if (!strcmp (s, "single") && is_single) { match = true; } } } can_proceed = (compatible == match); if (!can_proceed && test_suite_debug_output ()) { printf (" SKIP, incompatible topology type\n"); fflush (stdout); } return can_proceed; } static void _insert_data (mongoc_collection_t *collection, bson_t *documents) { bson_iter_t iter; mongoc_bulk_operation_t *bulk; bson_t *majority = tmp_bson ("{'writeConcern': {'w': 'majority'}}"); bool r; uint32_t server_id; bson_error_t error; mongoc_collection_delete_many ( collection, tmp_bson ("{}"), majority, NULL, NULL); if (!bson_count_keys (documents)) { return; } bson_iter_init (&iter, documents); bulk = mongoc_collection_create_bulk_operation_with_opts (collection, majority); while (bson_iter_next (&iter)) { bson_t document; bson_t opts = BSON_INITIALIZER; bson_iter_bson (&iter, &document); r = mongoc_bulk_operation_insert_with_opts ( bulk, &document, &opts, &error); ASSERT_OR_PRINT (r, error); bson_destroy (&opts); } server_id = mongoc_bulk_operation_execute (bulk, NULL, &error); ASSERT_OR_PRINT (server_id, error); mongoc_bulk_operation_destroy (bulk); } /* insert the documents in a spec test scenario's "data" array */ static void insert_data (const char *db_name, const char *collection_name, const bson_t *scenario) { mongoc_client_t *client; mongoc_database_t *db; mongoc_collection_t *collection; mongoc_collection_t *tmp_collection; bson_error_t error; bson_t documents; bson_iter_t iter; bson_t *majority = tmp_bson ("{'writeConcern': {'w': 'majority'}}"); /* use a fresh client to prepare the collection */ client = test_framework_client_new (); db = mongoc_client_get_database (client, db_name); collection = mongoc_database_get_collection (db, collection_name); mongoc_collection_delete_many ( collection, tmp_bson ("{}"), majority, NULL, NULL); /* ignore failure if it already exists */ tmp_collection = mongoc_database_create_collection (db, collection_name, majority, &error); if (tmp_collection) { mongoc_collection_destroy (tmp_collection); } if (!bson_has_field (scenario, "data")) { goto DONE; } bson_iter_init_find (&iter, scenario, "data"); if (BSON_ITER_HOLDS_ARRAY (&iter)) { bson_lookup_doc (scenario, "data", &documents); _insert_data (collection, &documents); } else { /* go through collection: [] */ bson_iter_recurse (&iter, &iter); while (bson_iter_next (&iter)) { bson_t collection_documents; mongoc_collection_destroy (collection); collection = mongoc_database_get_collection (db, bson_iter_key (&iter)); bson_iter_bson (&iter, &collection_documents); _insert_data (collection, &collection_documents); } } DONE: mongoc_database_destroy (db); mongoc_collection_destroy (collection); mongoc_client_destroy (client); } static void check_outcome_collection (mongoc_collection_t *collection, bson_t *test) { bson_t data; bson_iter_t iter; mongoc_read_concern_t *rc; mongoc_cursor_t *cursor; bson_t query = BSON_INITIALIZER; mongoc_read_prefs_t *prefs = mongoc_read_prefs_new (MONGOC_READ_PRIMARY); bson_lookup_doc (test, "outcome.collection.data", &data); ASSERT (bson_iter_init (&iter, &data)); rc = mongoc_read_concern_new (); /* If the collection has had its read_concern set by a test, make sure it's set to LOCAL for this check. */ if (mongoc_read_concern_get_level (collection->read_concern)) { mongoc_read_concern_set_level (rc, MONGOC_READ_CONCERN_LEVEL_LOCAL); mongoc_collection_set_read_concern (collection, rc); } cursor = mongoc_collection_find_with_opts (collection, &query, NULL, prefs); while (bson_iter_next (&iter)) { bson_t expected_doc; const bson_t *actual_doc; bson_iter_bson (&iter, &expected_doc); ASSERT_CURSOR_NEXT (cursor, &actual_doc); ASSERT (match_bson (actual_doc, &expected_doc, false)); } ASSERT_CURSOR_DONE (cursor); bson_destroy (&data); mongoc_read_prefs_destroy (prefs); bson_destroy (&query); mongoc_read_concern_destroy (rc); mongoc_cursor_destroy (cursor); } static void execute_test (const json_test_config_t *config, mongoc_client_t *client, mongoc_database_t *db, mongoc_collection_t *collection, bson_t *test) { json_test_ctx_t ctx; uint32_t server_id; bson_error_t error; mongoc_collection_t *other_collection; if (test_suite_debug_output ()) { const char *description = bson_lookup_utf8 (test, "description"); printf (" - %s\n", description); fflush (stdout); } if (!check_test_version (test) || !check_topology_type (test)) { return; } /* Select a primary for testing */ server_id = mongoc_topology_select_server_id ( collection->client->topology, MONGOC_SS_WRITE, NULL, &error); ASSERT_OR_PRINT (server_id, error); json_test_ctx_init (&ctx, test, client, db, collection, config); if (config->before_test_cb) { config->before_test_cb (&ctx, test); } if (bson_has_field (test, "failPoint")) { activate_fail_point (client, server_id, test, "failPoint"); } set_apm_callbacks (&ctx, collection->client); json_test_operations (&ctx, test); if (config->after_test_cb) { config->after_test_cb (&ctx, test); } json_test_ctx_end_sessions (&ctx); if (bson_has_field (test, "expectations")) { bson_t expectations; bson_lookup_doc (test, "expectations", &expectations); check_json_apm_events (&ctx, &expectations); if (config->events_check_cb) { config->events_check_cb (&ctx.events); } } if (bson_has_field (test, "outcome.collection")) { if (bson_has_field (test, "outcome.collection.name")) { other_collection = mongoc_database_get_collection ( db, bson_lookup_utf8 (test, "outcome.collection.name")); check_outcome_collection (other_collection, test); mongoc_collection_destroy (other_collection); } else { check_outcome_collection (collection, test); } } mongoc_client_set_apm_callbacks (collection->client, NULL, NULL); json_test_ctx_cleanup (&ctx); deactivate_fail_points (collection->client, server_id); } void activate_fail_point (mongoc_client_t *client, const uint32_t server_id, const bson_t *test, const char *key) { bson_t command; bson_error_t error; bool r; BSON_ASSERT (client); BSON_ASSERT (server_id); bson_lookup_doc (test, key, &command); ASSERT_CMPSTR (_mongoc_get_command_name (&command), "configureFailPoint"); r = mongoc_client_command_simple_with_server_id ( client, "admin", &command, NULL, server_id, NULL, &error); ASSERT_OR_PRINT (r, error); } /* *----------------------------------------------------------------------- * * deactivate_fail_points -- * * Deactivate the onPrimaryTransactionalWrite fail point, and all * future fail points used in JSON tests. * *----------------------------------------------------------------------- */ void deactivate_fail_points (mongoc_client_t *client, uint32_t server_id) { mongoc_server_description_t *sd; bson_t *command; bool r; bson_error_t error; sd = mongoc_client_get_server_description (client, server_id); BSON_ASSERT (sd); if (sd->type == MONGOC_SERVER_RS_PRIMARY && sd->max_wire_version >= WIRE_VERSION_RETRY_WRITES) { command = tmp_bson ("{'configureFailPoint': 'onPrimaryTransactionalWrite'," " 'mode': 'off'}"); r = mongoc_client_command_simple_with_server_id ( client, "admin", command, NULL, server_id, NULL, &error); ASSERT_OR_PRINT (r, error); command = tmp_bson ("{'configureFailPoint': 'failCommand'," " 'mode': 'off'}"); r = mongoc_client_command_simple_with_server_id ( client, "admin", command, NULL, server_id, NULL, &error); /* ignore error from servers that predate "failCommand" fail point */ if (!r && !strstr (error.message, "failCommand not found")) { ASSERT_OR_PRINT (r, error); } } mongoc_server_description_destroy (sd); } static void set_uri_opts_from_bson (mongoc_uri_t *uri, const bson_t *opts) { bson_iter_t iter; BSON_ASSERT (bson_iter_init (&iter, opts)); while (bson_iter_next (&iter)) { /* can't use bson_lookup_write_concern etc. with clientOptions format */ if (!strcmp (bson_iter_key (&iter), "w")) { mongoc_write_concern_t *wc = mongoc_write_concern_new (); if (BSON_ITER_HOLDS_UTF8 (&iter)) { mongoc_write_concern_set_wtag (wc, bson_iter_utf8 (&iter, NULL)); } else if (BSON_ITER_HOLDS_INT (&iter)) { mongoc_write_concern_set_w (wc, (int32_t) bson_iter_as_int64 (&iter)); } else { test_error ("Unrecognized type for 'w': %d", bson_iter_type (&iter)); } mongoc_uri_set_write_concern (uri, wc); mongoc_write_concern_destroy (wc); } else if (!strcmp (bson_iter_key (&iter), "readConcernLevel")) { mongoc_read_concern_t *rc = mongoc_read_concern_new (); mongoc_read_concern_set_level (rc, bson_iter_utf8 (&iter, NULL)); mongoc_uri_set_read_concern (uri, rc); mongoc_read_concern_destroy (rc); } else if (!strcmp (bson_iter_key (&iter), "readPreference")) { mongoc_read_prefs_t *read_prefs = mongoc_read_prefs_new ( read_mode_from_test (bson_iter_utf8 (&iter, NULL))); mongoc_uri_set_read_prefs_t (uri, read_prefs); mongoc_read_prefs_destroy (read_prefs); } else if (!strcmp (bson_iter_key (&iter), "retryWrites")) { mongoc_uri_set_option_as_bool ( uri, "retryWrites", bson_iter_bool (&iter)); } else if (!strcmp (bson_iter_key (&iter), "heartbeatFrequencyMS")) { mongoc_uri_set_option_as_int32 ( uri, "heartbeatFrequencyMS", bson_iter_int32 (&iter)); } else if (!strcmp (bson_iter_key (&iter), "retryReads")) { mongoc_uri_set_option_as_bool ( uri, "retryReads", bson_iter_bool (&iter)); } else { MONGOC_ERROR ("Unsupported clientOptions field \"%s\" in %s", bson_iter_key (&iter), bson_as_json (opts, NULL)); abort (); } } } static bool _should_skip_due_to_server_39704 (const bson_t *test) { const char *desc = bson_lookup_utf8 (test, "description"); const char *bad_tests[] = { "only first countDocuments includes readConcern", "only first find includes readConcern", "only first aggregate includes readConcern", "only first distinct includes readConcern", "only first runCommand includes readConcern", "transaction options inherited from defaultTransactionOptions", "startTransaction options override defaults", "defaultTransactionOptions override client options", "readConcern snapshot in startTransaction options", "withTransaction inherits transaction options from " "defaultTransactionOptions", "withTransaction explicit transaction options", "withTransaction explicit transaction options override " "defaultTransactionOptions", "withTransaction explicit transaction options override client options"}; int i; /* Only an issue for sharded clusters. */ if (!test_framework_is_mongos ()) { return false; } for (i = 0; i < sizeof (bad_tests) / sizeof (char *); i++) { if (0 == strcmp (desc, bad_tests[i])) { return true; } } return false; } /* *----------------------------------------------------------------------- * * run_json_general_test -- * * Run a JSON test scenario from the CRUD, Command Monitoring, * Retryable Writes, Change Stream, or Transactions Spec. * * Call json_test_config_cleanup on @config after the last call * to run_json_general_test. * *----------------------------------------------------------------------- */ void run_json_general_test (const json_test_config_t *config) { const bson_t *scenario = config->scenario; bson_iter_t scenario_iter; bson_iter_t tests_iter; const char *db_name; const char *collection_name; ASSERT (scenario); if (!check_scenario_version (scenario)) { return; } db_name = bson_has_field (scenario, "database_name") ? bson_lookup_utf8 (scenario, "database_name") : "test"; collection_name = bson_has_field (scenario, "collection_name") ? bson_lookup_utf8 (scenario, "collection_name") : "test"; ASSERT (bson_iter_init_find (&scenario_iter, scenario, "tests")); ASSERT (BSON_ITER_HOLDS_ARRAY (&scenario_iter)); ASSERT (bson_iter_recurse (&scenario_iter, &tests_iter)); while (bson_iter_next (&tests_iter)) { bson_t test; char *selected_test; const char *description; bson_iter_t client_opts_iter; mongoc_uri_t *uri; mongoc_client_t *client; mongoc_database_t *db; mongoc_collection_t *collection; uint32_t server_id; bson_error_t error; bool r; bson_iter_t uri_iter; ASSERT (BSON_ITER_HOLDS_DOCUMENT (&tests_iter)); bson_iter_bson (&tests_iter, &test); selected_test = test_framework_getenv ("MONGOC_JSON_SUBTEST"); description = bson_lookup_utf8 (&test, "description"); if (selected_test && strcmp (selected_test, description) != 0) { fprintf ( stderr, " - %s SKIPPED by MONGOC_JSON_SUBTEST\n", description); bson_free (selected_test); continue; } if (bson_has_field (&test, "skipReason")) { fprintf (stderr, " - %s SKIPPED, reason: %s\n", description, bson_lookup_utf8 (&test, "skipReason")); continue; } if (_should_skip_due_to_server_39704 (&test)) { fprintf (stderr, " - %s SKIPPED, reason: SERVER-39704 causes sharded tests to " "fail when using readConcern: snapshot\n", description); continue; } bson_free (selected_test); uri = test_framework_get_uri (); /* If we are using multiple mongos, hardcode them in, for now, but keep * the other URI components (CDRIVER-3285) */ if (bson_iter_init_find (&uri_iter, &test, "useMultipleMongoses") && bson_iter_as_bool (&uri_iter)) { ASSERT_OR_PRINT ( mongoc_uri_upsert_host_and_port (uri, "localhost:27017", &error), error); ASSERT_OR_PRINT ( mongoc_uri_upsert_host_and_port (uri, "localhost:27018", &error), error); } if (bson_iter_init_find (&client_opts_iter, &test, "clientOptions")) { bson_t client_opts; ASSERT (BSON_ITER_HOLDS_DOCUMENT (&tests_iter)); bson_iter_bson (&client_opts_iter, &client_opts); set_uri_opts_from_bson (uri, &client_opts); } client = mongoc_client_new_from_uri (uri); mongoc_client_set_error_api (client, 2); test_framework_set_ssl_opts (client); /* reconnect right away, if a fail point causes a disconnect */ client->topology->min_heartbeat_frequency_msec = 0; mongoc_uri_destroy (uri); /* clean up in case a previous test aborted */ server_id = mongoc_topology_select_server_id ( client->topology, MONGOC_SS_WRITE, NULL, &error); ASSERT_OR_PRINT (server_id, error); deactivate_fail_points (client, server_id); r = mongoc_client_command_with_opts (client, "admin", tmp_bson ("{'killAllSessions': []}"), NULL, NULL, NULL, &error); /* expect "operation was interrupted", ignore "command not found" */ if (!r && (error.domain != MONGOC_ERROR_SERVER || (error.code != 11601 && error.code != 59))) { MONGOC_WARNING ("Error in killAllSessions: %s", error.message); } insert_data (db_name, collection_name, scenario); db = mongoc_client_get_database (client, db_name); collection = mongoc_database_get_collection (db, collection_name); execute_test (config, client, db, collection, &test); mongoc_collection_destroy (collection); mongoc_database_destroy (db); mongoc_client_destroy (client); } } /* *----------------------------------------------------------------------- * * json_test_config_cleanup -- * * Free memory after run_json_general_test. * *----------------------------------------------------------------------- */ void json_test_config_cleanup (json_test_config_t *config) { /* no-op */ } /* Tests on unsupported operations are automatically skipped with a message * indicating why. */ static bson_t * _skip_if_unsupported (const char *test_name, bson_t *original) { int i; bool skip = false; const char *unsupported_tests[] = { "/retryable_reads/gridfs-downloadByName", "/retryable_reads/gridfs-downloadByName-serverErrors", "/retryable_reads/listCollectionObjects", "/retryable_reads/listCollectionObjects-serverErrors", "/retryable_reads/listDatabaseObjects", "/retryable_reads/listDatabaseObjects-serverErrors", "/retryable_reads/listIndexNames", "/retryable_reads/listIndexNames-serverErrors", "/retryable_reads/mapReduce"}; for (i = 0; i < sizeof (unsupported_tests) / sizeof (unsupported_tests[0]); i++) { if (0 == strcmp (test_name, unsupported_tests[i])) { skip = true; break; } } if (skip) { /* Modify the test file to give all entries in "tests" a skipReason */ bson_t *modified = bson_new (); bson_t modified_tests; bson_iter_t iter; bson_copy_to_excluding_noinit (original, modified, "tests", NULL); BSON_APPEND_ARRAY_BEGIN (modified, "tests", &modified_tests); BSON_ASSERT (bson_iter_init_find (&iter, original, "tests")); for (bson_iter_recurse (&iter, &iter); bson_iter_next (&iter);) { bson_t original_test; bson_t modified_test; bson_iter_bson (&iter, &original_test); BSON_APPEND_DOCUMENT_BEGIN ( &modified_tests, bson_iter_key (&iter), &modified_test); bson_concat (&modified_test, &original_test); BSON_APPEND_UTF8 (&modified_test, "skipReason", "libmongoc does not support required operation."); bson_append_document_end (&modified_tests, &modified_test); } bson_append_array_end (modified, &modified_tests); bson_destroy (original); return modified; } return original; } /* *----------------------------------------------------------------------- * * install_json_test_suite -- * * Given a path to a directory containing JSON tests, import each * test into a BSON blob and call the provided callback for * evaluation. * * It is expected that the callback will BSON_ASSERT on failure, so if * callback returns quietly the test is considered to have passed. * *----------------------------------------------------------------------- */ void _install_json_test_suite_with_check (TestSuite *suite, const char *dir_path, test_hook callback, ...) { char test_paths[MAX_NUM_TESTS][MAX_TEST_NAME_LENGTH]; int num_tests; int i; bson_t *test; char *skip_json; char *ext; va_list ap; num_tests = collect_tests_from_dir (&test_paths[0], dir_path, 0, MAX_NUM_TESTS); for (i = 0; i < num_tests; i++) { test = get_bson_from_json_file (test_paths[i]); skip_json = COALESCE (strstr (test_paths[i], "/json"), strstr (test_paths[i], "\\json")); BSON_ASSERT (skip_json); skip_json += strlen ("/json"); ext = strstr (skip_json, ".json"); BSON_ASSERT (ext); ext[0] = '\0'; test = _skip_if_unsupported (skip_json, test); /* list of "check" functions that decide whether to skip the test */ va_start (ap, callback); _V_TestSuite_AddFull (suite, skip_json, (void (*) (void *)) callback, (void (*) (void *)) bson_destroy, test, ap); va_end (ap); } } /* *----------------------------------------------------------------------- * * install_json_test_suite -- * * Given a path to a directory containing JSON tests, import each * test into a BSON blob and call the provided callback for * evaluation. * * It is expected that the callback will BSON_ASSERT on failure, so if * callback returns quietly the test is considered to have passed. * *----------------------------------------------------------------------- */ void install_json_test_suite (TestSuite *suite, const char *dir_path, test_hook callback) { install_json_test_suite_with_check ( suite, dir_path, callback, TestSuite_CheckLive); }
672953.c
/* Table for builtin transformation mapping. Copyright (C) 1997, 1998, 1999, 2000, 2001 Free Software Foundation, Inc. This file is part of the GNU C Library. Contributed by Ulrich Drepper <drepper@cygnus.com>, 1997. The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. */ #include <endian.h> #include <limits.h> #include <string.h> #include <gconv_int.h> #include <assert.h> static struct builtin_map { const char *name; __gconv_fct fct; int min_needed_from; int max_needed_from; int min_needed_to; int max_needed_to; } map[] = { #define BUILTIN_TRANSFORMATION(From, To, Cost, Name, Fct, MinF, MaxF, \ MinT, MaxT) \ { \ .name = Name, \ .fct = Fct, \ \ .min_needed_from = MinF, \ .max_needed_from = MaxF, \ .min_needed_to = MinT, \ .max_needed_to = MaxT \ }, #define BUILTIN_ALIAS(From, To) #include <gconv_builtin.h> }; void internal_function __gconv_get_builtin_trans (const char *name, struct __gconv_step *step) { size_t cnt; for (cnt = 0; cnt < sizeof (map) / sizeof (map[0]); ++cnt) if (strcmp (name, map[cnt].name) == 0) break; assert (cnt < sizeof (map) / sizeof (map[0])); step->__fct = map[cnt].fct; step->__init_fct = NULL; step->__end_fct = NULL; step->__shlib_handle = NULL; step->__modname = NULL; step->__min_needed_from = map[cnt].min_needed_from; step->__max_needed_from = map[cnt].max_needed_from; step->__min_needed_to = map[cnt].min_needed_to; step->__max_needed_to = map[cnt].max_needed_to; /* None of the builtin converters handles stateful encoding. */ step->__stateful = 0; }
594336.c
/* RAxML-VI-HPC (version 2.2) a program for sequential and parallel estimation of phylogenetic trees * Copyright August 2006 by Alexandros Stamatakis * * Partially derived from * fastDNAml, a program for estimation of phylogenetic trees from sequences by Gary J. Olsen * * and * * Programs of the PHYLIP package by Joe Felsenstein. * * This program is free software; you may redistribute it and/or modify its * 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. * * * For any other enquiries send an Email to Alexandros Stamatakis * Alexandros.Stamatakis@epfl.ch * * When publishing work that is based on the results from RAxML-VI-HPC please cite: * * Alexandros Stamatakis:"RAxML-VI-HPC: maximum likelihood-based phylogenetic analyses with * thousands of taxa and mixed models". * Bioinformatics 2006; doi: 10.1093/bioinformatics/btl446 */ #ifndef WIN32 #include <sys/times.h> #include <sys/types.h> #include <sys/time.h> #include <unistd.h> #endif #include <limits.h> #include <math.h> #include <time.h> #include <stdlib.h> #include <stdio.h> #include <ctype.h> #include <string.h> #include <stdint.h> #ifdef __AVX #ifdef __SIM_SSE3 #define _SSE3_WAS_DEFINED #undef __SIM_SSE3 #endif #endif #ifdef __SIM_SSE3 #include <xmmintrin.h> #include <pmmintrin.h> #endif #ifdef __AVX #include <xmmintrin.h> #include <immintrin.h> #endif #include "axml.h" extern const unsigned int mask32[32]; /* vector-specific stuff */ extern char **globalArgv; extern int globalArgc; #ifdef __SIM_SSE3 #define INTS_PER_VECTOR 4 #define INT_TYPE __m128i #define CAST __m128i* #define SET_ALL_BITS_ONE _mm_set_epi32(0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF) #define SET_ALL_BITS_ZERO _mm_set_epi32(0x00000000, 0x00000000, 0x00000000, 0x00000000) #define VECTOR_LOAD _mm_load_si128 #define VECTOR_BIT_AND _mm_and_si128 #define VECTOR_BIT_OR _mm_or_si128 #define VECTOR_STORE _mm_store_si128 #define VECTOR_AND_NOT _mm_andnot_si128 #endif #ifdef __AVX #define INTS_PER_VECTOR 8 #define INT_TYPE __m256d #define CAST double* #define SET_ALL_BITS_ONE (__m256d)_mm256_set_epi32(0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF) #define SET_ALL_BITS_ZERO (__m256d)_mm256_set_epi32(0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000) #define VECTOR_LOAD _mm256_load_pd #define VECTOR_BIT_AND _mm256_and_pd #define VECTOR_BIT_OR _mm256_or_pd #define VECTOR_STORE _mm256_store_pd #define VECTOR_AND_NOT _mm256_andnot_pd #endif extern double masterTime; extern char workdir[1024]; extern char run_id[128]; /********************************DNA FUNCTIONS *****************************************************************/ static void checkSeed(analdef *adef) { static boolean seedChecked = FALSE; if(!seedChecked) { /*printf("Checking seed\n");*/ if(adef->parsimonySeed <= 0) { printf("Error: you need to specify a random number seed with \"-p\" for the randomized stepwise addition\n"); printf("parsimony algorithm or random tree building algorithm such that runs can be reproduced and debugged ... exiting\n"); } assert(adef->parsimonySeed > 0); seedChecked = TRUE; } } static void getxnodeLocal (nodeptr p) { nodeptr s; if((s = p->next)->x || (s = s->next)->x) { p->x = s->x; s->x = 0; } } static void computeTraversalInfoParsimony(nodeptr p, int *ti, int *counter, int maxTips, boolean full) { nodeptr q = p->next->back, r = p->next->next->back; if(! p->x) getxnodeLocal(p); if(full) { if(q->number > maxTips) computeTraversalInfoParsimony(q, ti, counter, maxTips, full); if(r->number > maxTips) computeTraversalInfoParsimony(r, ti, counter, maxTips, full); } else { if(q->number > maxTips && !q->x) computeTraversalInfoParsimony(q, ti, counter, maxTips, full); if(r->number > maxTips && !r->x) computeTraversalInfoParsimony(r, ti, counter, maxTips, full); } ti[*counter] = p->number; ti[*counter + 1] = q->number; ti[*counter + 2] = r->number; *counter = *counter + 4; } #if (defined(__SIM_SSE3) || defined(__AVX)) static inline unsigned int populationCount(INT_TYPE v_N) { unsigned int res[INTS_PER_VECTOR] __attribute__ ((aligned (BYTE_ALIGNMENT))); unsigned int i, a = 0; VECTOR_STORE((CAST)res, v_N); for(i = 0; i < INTS_PER_VECTOR; i++) a += BIT_COUNT(res[i]); return a; } #else static inline unsigned int populationCount(unsigned int n) { return BIT_COUNT(n); } #endif #if (defined(__SIM_SSE3) || defined(__AVX)) void newviewParsimonyIterativeFast(tree *tr) { INT_TYPE allOne = SET_ALL_BITS_ONE; int model, *ti = tr->ti, count = ti[0], index; for(index = 4; index < count; index += 4) { unsigned int totalScore = 0; size_t pNumber = (size_t)ti[index], qNumber = (size_t)ti[index + 1], rNumber = (size_t)ti[index + 2]; for(model = 0; model < tr->NumberOfModels; model++) { size_t k, states = tr->partitionData[model].states, width = tr->partitionData[model].parsimonyLength; unsigned int i; switch(states) { case 2: { parsimonyNumber *left[2], *right[2], *this[2]; for(k = 0; k < 2; k++) { left[k] = &(tr->partitionData[model].parsVect[(width * 2 * qNumber) + width * k]); right[k] = &(tr->partitionData[model].parsVect[(width * 2 * rNumber) + width * k]); this[k] = &(tr->partitionData[model].parsVect[(width * 2 * pNumber) + width * k]); } for(i = 0; i < width; i += INTS_PER_VECTOR) { INT_TYPE s_r, s_l, v_N, l_A, l_C, v_A, v_C; s_l = VECTOR_LOAD((CAST)(&left[0][i])); s_r = VECTOR_LOAD((CAST)(&right[0][i])); l_A = VECTOR_BIT_AND(s_l, s_r); v_A = VECTOR_BIT_OR(s_l, s_r); s_l = VECTOR_LOAD((CAST)(&left[1][i])); s_r = VECTOR_LOAD((CAST)(&right[1][i])); l_C = VECTOR_BIT_AND(s_l, s_r); v_C = VECTOR_BIT_OR(s_l, s_r); v_N = VECTOR_BIT_OR(l_A, l_C); VECTOR_STORE((CAST)(&this[0][i]), VECTOR_BIT_OR(l_A, VECTOR_AND_NOT(v_N, v_A))); VECTOR_STORE((CAST)(&this[1][i]), VECTOR_BIT_OR(l_C, VECTOR_AND_NOT(v_N, v_C))); v_N = VECTOR_AND_NOT(v_N, allOne); totalScore += populationCount(v_N); } } break; case 4: { parsimonyNumber *left[4], *right[4], *this[4]; for(k = 0; k < 4; k++) { left[k] = &(tr->partitionData[model].parsVect[(width * 4 * qNumber) + width * k]); right[k] = &(tr->partitionData[model].parsVect[(width * 4 * rNumber) + width * k]); this[k] = &(tr->partitionData[model].parsVect[(width * 4 * pNumber) + width * k]); } for(i = 0; i < width; i += INTS_PER_VECTOR) { INT_TYPE s_r, s_l, v_N, l_A, l_C, l_G, l_T, v_A, v_C, v_G, v_T; s_l = VECTOR_LOAD((CAST)(&left[0][i])); s_r = VECTOR_LOAD((CAST)(&right[0][i])); l_A = VECTOR_BIT_AND(s_l, s_r); v_A = VECTOR_BIT_OR(s_l, s_r); s_l = VECTOR_LOAD((CAST)(&left[1][i])); s_r = VECTOR_LOAD((CAST)(&right[1][i])); l_C = VECTOR_BIT_AND(s_l, s_r); v_C = VECTOR_BIT_OR(s_l, s_r); s_l = VECTOR_LOAD((CAST)(&left[2][i])); s_r = VECTOR_LOAD((CAST)(&right[2][i])); l_G = VECTOR_BIT_AND(s_l, s_r); v_G = VECTOR_BIT_OR(s_l, s_r); s_l = VECTOR_LOAD((CAST)(&left[3][i])); s_r = VECTOR_LOAD((CAST)(&right[3][i])); l_T = VECTOR_BIT_AND(s_l, s_r); v_T = VECTOR_BIT_OR(s_l, s_r); v_N = VECTOR_BIT_OR(VECTOR_BIT_OR(l_A, l_C), VECTOR_BIT_OR(l_G, l_T)); VECTOR_STORE((CAST)(&this[0][i]), VECTOR_BIT_OR(l_A, VECTOR_AND_NOT(v_N, v_A))); VECTOR_STORE((CAST)(&this[1][i]), VECTOR_BIT_OR(l_C, VECTOR_AND_NOT(v_N, v_C))); VECTOR_STORE((CAST)(&this[2][i]), VECTOR_BIT_OR(l_G, VECTOR_AND_NOT(v_N, v_G))); VECTOR_STORE((CAST)(&this[3][i]), VECTOR_BIT_OR(l_T, VECTOR_AND_NOT(v_N, v_T))); v_N = VECTOR_AND_NOT(v_N, allOne); totalScore += populationCount(v_N); } } break; case 20: { parsimonyNumber *left[20], *right[20], *this[20]; for(k = 0; k < 20; k++) { left[k] = &(tr->partitionData[model].parsVect[(width * 20 * qNumber) + width * k]); right[k] = &(tr->partitionData[model].parsVect[(width * 20 * rNumber) + width * k]); this[k] = &(tr->partitionData[model].parsVect[(width * 20 * pNumber) + width * k]); } for(i = 0; i < width; i += INTS_PER_VECTOR) { size_t j; INT_TYPE s_r, s_l, v_N = SET_ALL_BITS_ZERO, l_A[20], v_A[20]; for(j = 0; j < 20; j++) { s_l = VECTOR_LOAD((CAST)(&left[j][i])); s_r = VECTOR_LOAD((CAST)(&right[j][i])); l_A[j] = VECTOR_BIT_AND(s_l, s_r); v_A[j] = VECTOR_BIT_OR(s_l, s_r); v_N = VECTOR_BIT_OR(v_N, l_A[j]); } for(j = 0; j < 20; j++) VECTOR_STORE((CAST)(&this[j][i]), VECTOR_BIT_OR(l_A[j], VECTOR_AND_NOT(v_N, v_A[j]))); v_N = VECTOR_AND_NOT(v_N, allOne); totalScore += populationCount(v_N); } } break; default: { parsimonyNumber *left[32], *right[32], *this[32]; assert(states <= 32); for(k = 0; k < states; k++) { left[k] = &(tr->partitionData[model].parsVect[(width * states * qNumber) + width * k]); right[k] = &(tr->partitionData[model].parsVect[(width * states * rNumber) + width * k]); this[k] = &(tr->partitionData[model].parsVect[(width * states * pNumber) + width * k]); } for(i = 0; i < width; i += INTS_PER_VECTOR) { size_t j; INT_TYPE s_r, s_l, v_N = SET_ALL_BITS_ZERO, l_A[32], v_A[32]; for(j = 0; j < states; j++) { s_l = VECTOR_LOAD((CAST)(&left[j][i])); s_r = VECTOR_LOAD((CAST)(&right[j][i])); l_A[j] = VECTOR_BIT_AND(s_l, s_r); v_A[j] = VECTOR_BIT_OR(s_l, s_r); v_N = VECTOR_BIT_OR(v_N, l_A[j]); } for(j = 0; j < states; j++) VECTOR_STORE((CAST)(&this[j][i]), VECTOR_BIT_OR(l_A[j], VECTOR_AND_NOT(v_N, v_A[j]))); v_N = VECTOR_AND_NOT(v_N, allOne); totalScore += populationCount(v_N); } } } } tr->parsimonyScore[pNumber] = totalScore + tr->parsimonyScore[rNumber] + tr->parsimonyScore[qNumber]; } } unsigned int evaluateParsimonyIterativeFast(tree *tr) { INT_TYPE allOne = SET_ALL_BITS_ONE; size_t pNumber = (size_t)tr->ti[1], qNumber = (size_t)tr->ti[2]; int model; unsigned int bestScore = tr->bestParsimony, sum; if(tr->ti[0] > 4) newviewParsimonyIterativeFast(tr); sum = tr->parsimonyScore[pNumber] + tr->parsimonyScore[qNumber]; for(model = 0; model < tr->NumberOfModels; model++) { size_t k, states = tr->partitionData[model].states, width = tr->partitionData[model].parsimonyLength, i; switch(states) { case 2: { parsimonyNumber *left[2], *right[2]; for(k = 0; k < 2; k++) { left[k] = &(tr->partitionData[model].parsVect[(width * 2 * qNumber) + width * k]); right[k] = &(tr->partitionData[model].parsVect[(width * 2 * pNumber) + width * k]); } for(i = 0; i < width; i += INTS_PER_VECTOR) { INT_TYPE l_A = VECTOR_BIT_AND(VECTOR_LOAD((CAST)(&left[0][i])), VECTOR_LOAD((CAST)(&right[0][i]))), l_C = VECTOR_BIT_AND(VECTOR_LOAD((CAST)(&left[1][i])), VECTOR_LOAD((CAST)(&right[1][i]))), v_N = VECTOR_BIT_OR(l_A, l_C); v_N = VECTOR_AND_NOT(v_N, allOne); sum += populationCount(v_N); if(sum >= bestScore) return sum; } } break; case 4: { parsimonyNumber *left[4], *right[4]; for(k = 0; k < 4; k++) { left[k] = &(tr->partitionData[model].parsVect[(width * 4 * qNumber) + width * k]); right[k] = &(tr->partitionData[model].parsVect[(width * 4 * pNumber) + width * k]); } for(i = 0; i < width; i += INTS_PER_VECTOR) { INT_TYPE l_A = VECTOR_BIT_AND(VECTOR_LOAD((CAST)(&left[0][i])), VECTOR_LOAD((CAST)(&right[0][i]))), l_C = VECTOR_BIT_AND(VECTOR_LOAD((CAST)(&left[1][i])), VECTOR_LOAD((CAST)(&right[1][i]))), l_G = VECTOR_BIT_AND(VECTOR_LOAD((CAST)(&left[2][i])), VECTOR_LOAD((CAST)(&right[2][i]))), l_T = VECTOR_BIT_AND(VECTOR_LOAD((CAST)(&left[3][i])), VECTOR_LOAD((CAST)(&right[3][i]))), v_N = VECTOR_BIT_OR(VECTOR_BIT_OR(l_A, l_C), VECTOR_BIT_OR(l_G, l_T)); v_N = VECTOR_AND_NOT(v_N, allOne); sum += populationCount(v_N); if(sum >= bestScore) return sum; } } break; case 20: { parsimonyNumber *left[20], *right[20]; for(k = 0; k < 20; k++) { left[k] = &(tr->partitionData[model].parsVect[(width * 20 * qNumber) + width * k]); right[k] = &(tr->partitionData[model].parsVect[(width * 20 * pNumber) + width * k]); } for(i = 0; i < width; i += INTS_PER_VECTOR) { int j; INT_TYPE l_A, v_N = SET_ALL_BITS_ZERO; for(j = 0; j < 20; j++) { l_A = VECTOR_BIT_AND(VECTOR_LOAD((CAST)(&left[j][i])), VECTOR_LOAD((CAST)(&right[j][i]))); v_N = VECTOR_BIT_OR(l_A, v_N); } v_N = VECTOR_AND_NOT(v_N, allOne); sum += populationCount(v_N); if(sum >= bestScore) return sum; } } break; default: { parsimonyNumber *left[32], *right[32]; assert(states <= 32); for(k = 0; k < states; k++) { left[k] = &(tr->partitionData[model].parsVect[(width * states * qNumber) + width * k]); right[k] = &(tr->partitionData[model].parsVect[(width * states * pNumber) + width * k]); } for(i = 0; i < width; i += INTS_PER_VECTOR) { size_t j; INT_TYPE l_A, v_N = SET_ALL_BITS_ZERO; for(j = 0; j < states; j++) { l_A = VECTOR_BIT_AND(VECTOR_LOAD((CAST)(&left[j][i])), VECTOR_LOAD((CAST)(&right[j][i]))); v_N = VECTOR_BIT_OR(l_A, v_N); } v_N = VECTOR_AND_NOT(v_N, allOne); sum += populationCount(v_N); if(sum >= bestScore) return sum; } } } } return sum; } #else void newviewParsimonyIterativeFast(tree *tr) { int model, *ti = tr->ti, count = ti[0], index; for(index = 4; index < count; index += 4) { unsigned int totalScore = 0; size_t pNumber = (size_t)ti[index], qNumber = (size_t)ti[index + 1], rNumber = (size_t)ti[index + 2]; for(model = 0; model < tr->NumberOfModels; model++) { size_t k, states = tr->partitionData[model].states, width = tr->partitionData[model].parsimonyLength; unsigned int i; switch(states) { case 2: { parsimonyNumber *left[2], *right[2], *this[2]; parsimonyNumber o_A, o_C, t_A, t_C, t_N; for(k = 0; k < 2; k++) { left[k] = &(tr->partitionData[model].parsVect[(width * 2 * qNumber) + width * k]); right[k] = &(tr->partitionData[model].parsVect[(width * 2 * rNumber) + width * k]); this[k] = &(tr->partitionData[model].parsVect[(width * 2 * pNumber) + width * k]); } for(i = 0; i < width; i++) { t_A = left[0][i] & right[0][i]; t_C = left[1][i] & right[1][i]; o_A = left[0][i] | right[0][i]; o_C = left[1][i] | right[1][i]; t_N = ~(t_A | t_C); this[0][i] = t_A | (t_N & o_A); this[1][i] = t_C | (t_N & o_C); totalScore += populationCount(t_N); } } break; case 4: { parsimonyNumber *left[4], *right[4], *this[4]; for(k = 0; k < 4; k++) { left[k] = &(tr->partitionData[model].parsVect[(width * 4 * qNumber) + width * k]); right[k] = &(tr->partitionData[model].parsVect[(width * 4 * rNumber) + width * k]); this[k] = &(tr->partitionData[model].parsVect[(width * 4 * pNumber) + width * k]); } parsimonyNumber o_A, o_C, o_G, o_T, t_A, t_C, t_G, t_T, t_N; for(i = 0; i < width; i++) { t_A = left[0][i] & right[0][i]; t_C = left[1][i] & right[1][i]; t_G = left[2][i] & right[2][i]; t_T = left[3][i] & right[3][i]; o_A = left[0][i] | right[0][i]; o_C = left[1][i] | right[1][i]; o_G = left[2][i] | right[2][i]; o_T = left[3][i] | right[3][i]; t_N = ~(t_A | t_C | t_G | t_T); this[0][i] = t_A | (t_N & o_A); this[1][i] = t_C | (t_N & o_C); this[2][i] = t_G | (t_N & o_G); this[3][i] = t_T | (t_N & o_T); totalScore += populationCount(t_N); } } break; case 20: { parsimonyNumber *left[20], *right[20], *this[20]; parsimonyNumber o_A[20], t_A[20], t_N; for(k = 0; k < 20; k++) { left[k] = &(tr->partitionData[model].parsVect[(width * 20 * qNumber) + width * k]); right[k] = &(tr->partitionData[model].parsVect[(width * 20 * rNumber) + width * k]); this[k] = &(tr->partitionData[model].parsVect[(width * 20 * pNumber) + width * k]); } for(i = 0; i < width; i++) { size_t k; t_N = 0; for(k = 0; k < 20; k++) { t_A[k] = left[k][i] & right[k][i]; o_A[k] = left[k][i] | right[k][i]; t_N = t_N | t_A[k]; } t_N = ~t_N; for(k = 0; k < 20; k++) this[k][i] = t_A[k] | (t_N & o_A[k]); totalScore += populationCount(t_N); } } break; default: { parsimonyNumber *left[32], *right[32], *this[32]; parsimonyNumber o_A[32], t_A[32], t_N; assert(states <= 32); for(k = 0; k < states; k++) { left[k] = &(tr->partitionData[model].parsVect[(width * states * qNumber) + width * k]); right[k] = &(tr->partitionData[model].parsVect[(width * states * rNumber) + width * k]); this[k] = &(tr->partitionData[model].parsVect[(width * states * pNumber) + width * k]); } for(i = 0; i < width; i++) { t_N = 0; for(k = 0; k < states; k++) { t_A[k] = left[k][i] & right[k][i]; o_A[k] = left[k][i] | right[k][i]; t_N = t_N | t_A[k]; } t_N = ~t_N; for(k = 0; k < states; k++) this[k][i] = t_A[k] | (t_N & o_A[k]); totalScore += populationCount(t_N); } } } } tr->parsimonyScore[pNumber] = totalScore + tr->parsimonyScore[rNumber] + tr->parsimonyScore[qNumber]; } } unsigned int evaluateParsimonyIterativeFast(tree *tr) { size_t pNumber = (size_t)tr->ti[1], qNumber = (size_t)tr->ti[2]; int model; unsigned int bestScore = tr->bestParsimony, sum; if(tr->ti[0] > 4) newviewParsimonyIterativeFast(tr); sum = tr->parsimonyScore[pNumber] + tr->parsimonyScore[qNumber]; for(model = 0; model < tr->NumberOfModels; model++) { size_t k, states = tr->partitionData[model].states, width = tr->partitionData[model].parsimonyLength, i; switch(states) { case 2: { parsimonyNumber t_A, t_C, t_N, *left[2], *right[2]; for(k = 0; k < 2; k++) { left[k] = &(tr->partitionData[model].parsVect[(width * 2 * qNumber) + width * k]); right[k] = &(tr->partitionData[model].parsVect[(width * 2 * pNumber) + width * k]); } for(i = 0; i < width; i++) { t_A = left[0][i] & right[0][i]; t_C = left[1][i] & right[1][i]; t_N = ~(t_A | t_C); sum += populationCount(t_N); if(sum >= bestScore) return sum; } } break; case 4: { parsimonyNumber t_A, t_C, t_G, t_T, t_N, *left[4], *right[4]; for(k = 0; k < 4; k++) { left[k] = &(tr->partitionData[model].parsVect[(width * 4 * qNumber) + width * k]); right[k] = &(tr->partitionData[model].parsVect[(width * 4 * pNumber) + width * k]); } for(i = 0; i < width; i++) { t_A = left[0][i] & right[0][i]; t_C = left[1][i] & right[1][i]; t_G = left[2][i] & right[2][i]; t_T = left[3][i] & right[3][i]; t_N = ~(t_A | t_C | t_G | t_T); sum += populationCount(t_N); if(sum >= bestScore) return sum; } } break; case 20: { parsimonyNumber t_A, t_N, *left[20], *right[20]; for(k = 0; k < 20; k++) { left[k] = &(tr->partitionData[model].parsVect[(width * 20 * qNumber) + width * k]); right[k] = &(tr->partitionData[model].parsVect[(width * 20 * pNumber) + width * k]); } for(i = 0; i < width; i++) { t_N = 0; for(k = 0; k < 20; k++) { t_A = left[k][i] & right[k][i]; t_N = t_N | t_A; } t_N = ~t_N; sum += populationCount(t_N); if(sum >= bestScore) return sum; } } break; default: { parsimonyNumber t_A, t_N, *left[32], *right[32]; assert(states <= 32); for(k = 0; k < states; k++) { left[k] = &(tr->partitionData[model].parsVect[(width * states * qNumber) + width * k]); right[k] = &(tr->partitionData[model].parsVect[(width * states * pNumber) + width * k]); } for(i = 0; i < width; i++) { t_N = 0; for(k = 0; k < states; k++) { t_A = left[k][i] & right[k][i]; t_N = t_N | t_A; } t_N = ~t_N; sum += populationCount(t_N); if(sum >= bestScore) return sum; } } } } return sum; } #endif static unsigned int evaluateParsimony(tree *tr, nodeptr p, boolean full) { volatile unsigned int result; nodeptr q = p->back; int *ti = tr->ti, counter = 4; ti[1] = p->number; ti[2] = q->number; if(full) { if(p->number > tr->mxtips) computeTraversalInfoParsimony(p, ti, &counter, tr->mxtips, full); if(q->number > tr->mxtips) computeTraversalInfoParsimony(q, ti, &counter, tr->mxtips, full); } else { if(p->number > tr->mxtips && !p->x) computeTraversalInfoParsimony(p, ti, &counter, tr->mxtips, full); if(q->number > tr->mxtips && !q->x) computeTraversalInfoParsimony(q, ti, &counter, tr->mxtips, full); } ti[0] = counter; result = evaluateParsimonyIterativeFast(tr); return result; } static void newviewParsimony(tree *tr, nodeptr p) { if(p->number <= tr->mxtips) return; { int counter = 4; computeTraversalInfoParsimony(p, tr->ti, &counter, tr->mxtips, FALSE); tr->ti[0] = counter; newviewParsimonyIterativeFast(tr); } } /****************************************************************************************************************************************/ static void insertParsimony (tree *tr, nodeptr p, nodeptr q) { nodeptr r; r = q->back; hookupDefault(p->next, q, tr->numBranches); hookupDefault(p->next->next, r, tr->numBranches); newviewParsimony(tr, p); } /* static nodeptr buildNewTip (tree *tr, nodeptr p) { nodeptr q; q = tr->nodep[(tr->nextnode)++]; hookupDefault(p, q, tr->numBranches); q->next->back = (nodeptr)NULL; q->next->next->back = (nodeptr)NULL; assert(q == q->next->next->next); assert(q->x || q->next->x || q->next->next->x); return q; } */ static nodeptr buildNewTip (tree *tr, nodeptr p) { nodeptr q; q = tr->nodep[(tr->nextnode)++]; hookupDefault(p, q, tr->numBranches); q->next->back = (nodeptr)NULL; q->next->next->back = (nodeptr)NULL; return q; } static void buildSimpleTree (tree *tr, int ip, int iq, int ir) { nodeptr p, s; int i; i = MIN(ip, iq); if (ir < i) i = ir; tr->start = tr->nodep[i]; tr->ntips = 3; p = tr->nodep[ip]; hookupDefault(p, tr->nodep[iq], tr->numBranches); s = buildNewTip(tr, tr->nodep[ir]); insertParsimony(tr, s, p); } static void testInsertParsimony (tree *tr, nodeptr p, nodeptr q) { unsigned int mp; nodeptr r = q->back; boolean doIt = TRUE; if(tr->grouped) { int rNumber = tr->constraintVector[r->number], qNumber = tr->constraintVector[q->number], pNumber = tr->constraintVector[p->number]; doIt = FALSE; if(pNumber == -9) pNumber = checker(tr, p->back); if(pNumber == -9) doIt = TRUE; else { if(qNumber == -9) qNumber = checker(tr, q); if(rNumber == -9) rNumber = checker(tr, r); if(pNumber == rNumber || pNumber == qNumber) doIt = TRUE; } } if(doIt) { insertParsimony(tr, p, q); mp = evaluateParsimony(tr, p->next->next, FALSE); if(mp < tr->bestParsimony) { tr->bestParsimony = mp; tr->insertNode = q; tr->removeNode = p; } hookupDefault(q, r, tr->numBranches); p->next->next->back = p->next->back = (nodeptr) NULL; } return; } static void restoreTreeParsimony(tree *tr, nodeptr p, nodeptr q) { nodeptr r = q->back; int counter = 4; hookupDefault(p->next, q, tr->numBranches); hookupDefault(p->next->next, r, tr->numBranches); computeTraversalInfoParsimony(p, tr->ti, &counter, tr->mxtips, FALSE); tr->ti[0] = counter; newviewParsimonyIterativeFast(tr); } static void addTraverseParsimony (tree *tr, nodeptr p, nodeptr q, int mintrav, int maxtrav, boolean doAll) { if (doAll || (--mintrav <= 0)) testInsertParsimony(tr, p, q); if (((q->number > tr->mxtips)) && ((--maxtrav > 0) || doAll)) { addTraverseParsimony(tr, p, q->next->back, mintrav, maxtrav, doAll); addTraverseParsimony(tr, p, q->next->next->back, mintrav, maxtrav, doAll); } } static nodeptr findAnyTipFast(nodeptr p, int numsp) { return (p->number <= numsp)? p : findAnyTipFast(p->next->back, numsp); } static nodeptr removeNodeParsimony (nodeptr p, tree *tr) { nodeptr q, r; q = p->next->back; r = p->next->next->back; hookupDefault(q, r, tr->numBranches); p->next->next->back = p->next->back = (node *) NULL; return q; } static int rearrangeParsimony(tree *tr, nodeptr p, int mintrav, int maxtrav, boolean doAll) { nodeptr p1, p2, q, q1, q2; int mintrav2; boolean doP = TRUE, doQ = TRUE; if (maxtrav > tr->ntips - 3) maxtrav = tr->ntips - 3; assert(mintrav == 1); if(maxtrav < mintrav) return 0; q = p->back; if(tr->constrained) { if(! tipHomogeneityChecker(tr, p->back, 0)) doP = FALSE; if(! tipHomogeneityChecker(tr, q->back, 0)) doQ = FALSE; if(doQ == FALSE && doP == FALSE) return 0; } if((p->number > tr->mxtips) && doP) { p1 = p->next->back; p2 = p->next->next->back; if ((p1->number > tr->mxtips) || (p2->number > tr->mxtips)) { removeNodeParsimony(p, tr); if ((p1->number > tr->mxtips)) { addTraverseParsimony(tr, p, p1->next->back, mintrav, maxtrav, doAll); addTraverseParsimony(tr, p, p1->next->next->back, mintrav, maxtrav, doAll); } if ((p2->number > tr->mxtips)) { addTraverseParsimony(tr, p, p2->next->back, mintrav, maxtrav, doAll); addTraverseParsimony(tr, p, p2->next->next->back, mintrav, maxtrav, doAll); } hookupDefault(p->next, p1, tr->numBranches); hookupDefault(p->next->next, p2, tr->numBranches); newviewParsimony(tr, p); } } if ((q->number > tr->mxtips) && (maxtrav > 0) && doQ) { q1 = q->next->back; q2 = q->next->next->back; if ( ( (q1->number > tr->mxtips) && ((q1->next->back->number > tr->mxtips) || (q1->next->next->back->number > tr->mxtips)) ) || ( (q2->number > tr->mxtips) && ((q2->next->back->number > tr->mxtips) || (q2->next->next->back->number > tr->mxtips)) ) ) { removeNodeParsimony(q, tr); mintrav2 = mintrav > 2 ? mintrav : 2; if ((q1->number > tr->mxtips)) { addTraverseParsimony(tr, q, q1->next->back, mintrav2 , maxtrav, doAll); addTraverseParsimony(tr, q, q1->next->next->back, mintrav2 , maxtrav, doAll); } if ((q2->number > tr->mxtips)) { addTraverseParsimony(tr, q, q2->next->back, mintrav2 , maxtrav, doAll); addTraverseParsimony(tr, q, q2->next->next->back, mintrav2 , maxtrav, doAll); } hookupDefault(q->next, q1, tr->numBranches); hookupDefault(q->next->next, q2, tr->numBranches); newviewParsimony(tr, q); } } return 1; } static void restoreTreeRearrangeParsimony(tree *tr) { removeNodeParsimony(tr->removeNode, tr); restoreTreeParsimony(tr, tr->removeNode, tr->insertNode); } /* static boolean isInformative2(tree *tr, int site) { int informativeCounter = 0, check[256], j, undetermined = 15; unsigned char nucleotide, target = 0; for(j = 0; j < 256; j++) check[j] = 0; for(j = 1; j <= tr->mxtips; j++) { nucleotide = tr->yVector[j][site]; check[nucleotide] = check[nucleotide] + 1; } if(check[1] > 1) { informativeCounter++; target = target | 1; } if(check[2] > 1) { informativeCounter++; target = target | 2; } if(check[4] > 1) { informativeCounter++; target = target | 4; } if(check[8] > 1) { informativeCounter++; target = target | 8; } if(informativeCounter >= 2) return TRUE; else { for(j = 0; j < undetermined; j++) { if(j == 3 || j == 5 || j == 6 || j == 7 || j == 9 || j == 10 || j == 11 || j == 12 || j == 13 || j == 14) { if(check[j] > 1) { if(!(target & j)) return TRUE; } } } } return FALSE; } */ static boolean isInformative(tree *tr, int dataType, int site) { int informativeCounter = 0, check[256], j, undetermined = getUndetermined(dataType); const unsigned int *bitVector = getBitVector(dataType); unsigned char nucleotide; for(j = 0; j < 256; j++) check[j] = 0; for(j = 1; j <= tr->mxtips; j++) { nucleotide = tr->yVector[j][site]; check[nucleotide] = check[nucleotide] + 1; assert(bitVector[nucleotide] > 0); } for(j = 0; j < undetermined; j++) { if(check[j] > 0) informativeCounter++; } if(informativeCounter <= 1) return FALSE; else { for(j = 0; j < undetermined; j++) { if(check[j] > 1) return TRUE; } } return FALSE; } static void determineUninformativeSites(tree *tr, int *informative) { int i, number = 0; /* Not all characters are useful in constructing a parsimony tree. Invariant characters, those that have the same state in all taxa, are obviously useless and are ignored by the method. Characters in which a state occurs in only one taxon are also ignored. All these characters are called parsimony uninformative. Alternative definition: informative columns contain at least two types of nucleotides, and each nucleotide must appear at least twice in each column. Kind of a pain if we intend to check for this when using, e.g., amibiguous DNA encoding. */ for(i = 0; i < tr->cdta->endsite; i++) { if(isInformative(tr, tr->dataVector[i], i)) informative[i] = 1; else { informative[i] = 0; number++; } } /* printf("Uninformative Patterns: %d\n", number); */ } static void reorderNodes(tree *tr, nodeptr *np, nodeptr p, int *count) { int i, found = 0; if((p->number <= tr->mxtips)) return; else { for(i = tr->mxtips + 1; (i <= (tr->mxtips + tr->mxtips - 1)) && (found == 0); i++) { if (p == np[i] || p == np[i]->next || p == np[i]->next->next) { if(p == np[i]) tr->nodep[*count + tr->mxtips + 1] = np[i]; else { if(p == np[i]->next) tr->nodep[*count + tr->mxtips + 1] = np[i]->next; else tr->nodep[*count + tr->mxtips + 1] = np[i]->next->next; } found = 1; *count = *count + 1; } } assert(found != 0); reorderNodes(tr, np, p->next->back, count); reorderNodes(tr, np, p->next->next->back, count); } } static void compressDNA(tree *tr, int *informative, boolean saveMemory) { size_t totalNodes, i, model; if(saveMemory) totalNodes = (size_t)tr->innerNodes + 1 + (size_t)tr->mxtips; else totalNodes = 2 * (size_t)tr->mxtips; for(model = 0; model < (size_t) tr->NumberOfModels; model++) { size_t k, states = (size_t)tr->partitionData[model].states, compressedEntries, compressedEntriesPadded, entries = 0, lower = tr->partitionData[model].lower, upper = tr->partitionData[model].upper; parsimonyNumber **compressedTips = (parsimonyNumber **)rax_malloc(states * sizeof(parsimonyNumber*)), *compressedValues = (parsimonyNumber *)rax_malloc(states * sizeof(parsimonyNumber)); for(i = lower; i < upper; i++) if(informative[i]) entries += (size_t)tr->cdta->aliaswgt[i]; compressedEntries = entries / PCF; if(entries % PCF != 0) compressedEntries++; #if (defined(__SIM_SSE3) || defined(__AVX)) if(compressedEntries % INTS_PER_VECTOR != 0) compressedEntriesPadded = compressedEntries + (INTS_PER_VECTOR - (compressedEntries % INTS_PER_VECTOR)); else compressedEntriesPadded = compressedEntries; #else compressedEntriesPadded = compressedEntries; #endif tr->partitionData[model].parsVect = (parsimonyNumber *)rax_malloc((size_t)compressedEntriesPadded * states * totalNodes * sizeof(parsimonyNumber)); for(i = 0; i < compressedEntriesPadded * states * totalNodes; i++) tr->partitionData[model].parsVect[i] = 0; for(i = 0; i < (size_t)tr->mxtips; i++) { size_t w = 0, compressedIndex = 0, compressedCounter = 0, index = 0; for(k = 0; k < states; k++) { compressedTips[k] = &(tr->partitionData[model].parsVect[(compressedEntriesPadded * states * (i + 1)) + (compressedEntriesPadded * k)]); compressedValues[k] = 0; } for(index = lower; index < (size_t)upper; index++) { if(informative[index]) { const unsigned int *bitValue = getBitVector(tr->partitionData[model].dataType); parsimonyNumber value = bitValue[tr->yVector[i + 1][index]]; for(w = 0; w < (size_t)tr->cdta->aliaswgt[index]; w++) { for(k = 0; k < states; k++) { if(value & mask32[k]) compressedValues[k] |= mask32[compressedCounter]; } compressedCounter++; if(compressedCounter == PCF) { for(k = 0; k < states; k++) { compressedTips[k][compressedIndex] = compressedValues[k]; compressedValues[k] = 0; } compressedCounter = 0; compressedIndex++; } } } } for(;compressedIndex < compressedEntriesPadded; compressedIndex++) { for(;compressedCounter < PCF; compressedCounter++) for(k = 0; k < states; k++) compressedValues[k] |= mask32[compressedCounter]; for(k = 0; k < states; k++) { compressedTips[k][compressedIndex] = compressedValues[k]; compressedValues[k] = 0; } compressedCounter = 0; } } tr->partitionData[model].parsimonyLength = compressedEntriesPadded; rax_free(compressedTips); rax_free(compressedValues); } tr->parsimonyScore = (unsigned int*)rax_malloc(sizeof(unsigned int) * totalNodes); for(i = 0; i < totalNodes; i++) tr->parsimonyScore[i] = 0; } static void stepwiseAddition(tree *tr, nodeptr p, nodeptr q) { nodeptr r = q->back; unsigned int mp; int counter = 4; p->next->back = q; q->back = p->next; p->next->next->back = r; r->back = p->next->next; computeTraversalInfoParsimony(p, tr->ti, &counter, tr->mxtips, FALSE); tr->ti[0] = counter; tr->ti[1] = p->number; tr->ti[2] = p->back->number; mp = evaluateParsimonyIterativeFast(tr); if(mp < tr->bestParsimony) { tr->bestParsimony = mp; tr->insertNode = q; } q->back = r; r->back = q; if(q->number > tr->mxtips && tr->parsimonyScore[q->number] > 0) { stepwiseAddition(tr, p, q->next->back); stepwiseAddition(tr, p, q->next->next->back); } } static void markNodesInTree(nodeptr p, tree *tr, unsigned char *nodesInTree) { if(isTip(p->number, tr->mxtips)) nodesInTree[p->number] = 1; else { markNodesInTree(p->next->back, tr, nodesInTree); markNodesInTree(p->next->next->back, tr, nodesInTree); } } void makeParsimonyTreeFast(tree *tr, analdef *adef, boolean full) { nodeptr p, f; size_t model; int i, nextsp, *perm = (int *)rax_malloc((size_t)(tr->mxtips + 1) * sizeof(int)), *informative = (int *)rax_malloc(sizeof(int) * (size_t)tr->cdta->endsite); unsigned int randomMP, startMP; /* double t; */ determineUninformativeSites(tr, informative); compressDNA(tr, informative, FALSE); rax_free(informative); tr->ti = (int*)rax_malloc(sizeof(int) * 4 * (size_t)tr->mxtips); /*t = gettime();*/ if(!full) { int j = 0; unsigned char *nodesInTree = (unsigned char*)rax_calloc((size_t)(tr->mxtips + 1), sizeof(unsigned char)); tr->start = findAnyTipFast(tr->start, tr->rdta->numsp); tr->bestParsimony = INT_MAX; evaluateParsimony(tr, tr->start->back, TRUE); assert(tr->start); checkSeed(adef); markNodesInTree(tr->start, tr, nodesInTree); markNodesInTree(tr->start->back, tr, nodesInTree); j = tr->ntips + 1; if(tr->grouped) { for(i = 1; i <= tr->mxtips; i++) { if(tr->constraintVector[i] == -1) { perm[j++] = i; tr->constraintVector[i] = -9; } } } else { if(tr->constrained) { for(i = 1; i <= tr->mxtips; i++) tr->constraintVector[i] = 0; for(i = 1; i <= tr->mxtips; i++) { if(nodesInTree[i] == 0) perm[j++] = i; else tr->constraintVector[i] = 1; } } else { for(i = 1; i <= tr->mxtips; i++) if(nodesInTree[i] == 0) perm[j++] = i; } } for(i = tr->ntips + 1; i <= tr->mxtips; i++) { int k, j; k = (int)((double)(tr->mxtips + 1 - i) * randum(&adef->parsimonySeed)); assert(i + k <= tr->mxtips); j = perm[i]; perm[i] = perm[i + k]; perm[i + k] = j; } f = tr->start; rax_free(nodesInTree); } else { assert(!tr->constrained); makePermutation(perm, 1, tr->mxtips, adef); tr->ntips = 0; tr->nextnode = tr->mxtips + 1; buildSimpleTree(tr, perm[1], perm[2], perm[3]); f = tr->start; } while(tr->ntips < tr->mxtips) { nodeptr q; tr->bestParsimony = INT_MAX; nextsp = ++(tr->ntips); p = tr->nodep[perm[nextsp]]; q = tr->nodep[(tr->nextnode)++]; p->back = q; q->back = p; if(tr->grouped && !full) { int number = p->back->number; tr->constraintVector[number] = -9; } stepwiseAddition(tr, q, f->back); { nodeptr r = tr->insertNode->back; int counter = 4; hookupDefault(q->next, tr->insertNode, tr->numBranches); hookupDefault(q->next->next, r, tr->numBranches); computeTraversalInfoParsimony(q, tr->ti, &counter, tr->mxtips, FALSE); tr->ti[0] = counter; newviewParsimonyIterativeFast(tr); } } //printf("ADD: %d\n", tr->bestParsimony); nodeRectifier(tr); if(adef->stepwiseAdditionOnly == FALSE) { randomMP = tr->bestParsimony; do { startMP = randomMP; nodeRectifier(tr); for(i = 1; i <= tr->mxtips + tr->mxtips - 2; i++) { rearrangeParsimony(tr, tr->nodep[i], 1, 20, FALSE); if(tr->bestParsimony < randomMP) { restoreTreeRearrangeParsimony(tr); randomMP = tr->bestParsimony; } } } while(randomMP < startMP); } //printf("OPT: %d\n", tr->bestParsimony); rax_free(perm); rax_free(tr->parsimonyScore); for(model = 0; model < (size_t) tr->NumberOfModels; model++) rax_free(tr->partitionData[model].parsVect); rax_free(tr->ti); } static void insertRandom (nodeptr p, nodeptr q, int numBranches) { nodeptr r; r = q->back; hookupDefault(p->next, q, numBranches); hookupDefault(p->next->next, r, numBranches); } static void buildSimpleTreeRandom (tree *tr, int ip, int iq, int ir) { nodeptr p, s; int i; i = MIN(ip, iq); if (ir < i) i = ir; tr->start = tr->nodep[i]; tr->ntips = 3; p = tr->nodep[ip]; hookupDefault(p, tr->nodep[iq], tr->numBranches); s = buildNewTip(tr, tr->nodep[ir]); insertRandom(s, p, tr->numBranches); } int checker(tree *tr, nodeptr p) { int group = tr->constraintVector[p->number]; if(isTip(p->number, tr->mxtips)) { group = tr->constraintVector[p->number]; return group; } else { if(group != -9) return group; group = checker(tr, p->next->back); if(group != -9) return group; group = checker(tr, p->next->next->back); if(group != -9) return group; return -9; } } static int markBranches(nodeptr *branches, nodeptr p, int *counter, int numsp) { if(isTip(p->number, numsp)) return 0; else { branches[*counter] = p->next; branches[*counter + 1] = p->next->next; *counter = *counter + 2; return ((2 + markBranches(branches, p->next->back, counter, numsp) + markBranches(branches, p->next->next->back, counter, numsp))); } } nodeptr findAnyTip(nodeptr p, int numsp) { return isTip(p->number, numsp) ? p : findAnyTip(p->next->back, numsp); } int randomInt(int n, analdef *adef) { return ((int)(randum(&adef->parsimonySeed) * (double)n)); // return rand() %n; } void makePermutation(int *perm, int lower, int n, analdef *adef) { int i, j, k; checkSeed(adef); for (i = lower; i <= n; i++) perm[i] = i; for (i = lower; i <= n; i++) { k = (int)((double)(n + 1 - i) * randum(&adef->parsimonySeed)); assert(i + k <= n); j = perm[i]; perm[i] = perm[i + k]; perm[i + k] = j; } } boolean tipHomogeneityChecker(tree *tr, nodeptr p, int grouping) { if(isTip(p->number, tr->mxtips)) { if(tr->constraintVector[p->number] != grouping) return FALSE; else return TRUE; } else { return (tipHomogeneityChecker(tr, p->next->back, grouping) && tipHomogeneityChecker(tr, p->next->next->back,grouping)); } } void makeRandomTree(tree *tr, analdef *adef) { nodeptr p, f, randomBranch; int nextsp; int *perm, branchCounter; nodeptr *branches; branches = (nodeptr *)rax_malloc(sizeof(nodeptr) * (2 * tr->mxtips)); perm = (int *)rax_malloc((tr->mxtips + 1) * sizeof(int)); makePermutation(perm, 1, tr->mxtips, adef); tr->ntips = 0; tr->nextnode = tr->mxtips + 1; buildSimpleTreeRandom(tr, perm[1], perm[2], perm[3]); while (tr->ntips < tr->mxtips) { tr->bestParsimony = INT_MAX; nextsp = ++(tr->ntips); p = tr->nodep[perm[nextsp]]; /*printf("ADDING SPECIES %d\n", nextsp);*/ buildNewTip(tr, p); f = findAnyTip(tr->start, tr->mxtips); f = f->back; branchCounter = 1; branches[0] = f; markBranches(branches, f, &branchCounter, tr->mxtips); assert(branchCounter == ((2 * (tr->ntips - 1)) - 3)); randomBranch = branches[randomInt(branchCounter, adef)]; insertRandom(p->back, randomBranch, tr->numBranches); } rax_free(perm); rax_free(branches); } void nodeRectifier(tree *tr) { nodeptr *np = (nodeptr *)rax_malloc(2 * tr->mxtips * sizeof(nodeptr)); int i; int count = 0; tr->start = tr->nodep[1]; tr->rooted = FALSE; /* TODO why is tr->rooted set to FALSE here ?*/ for(i = tr->mxtips + 1; i <= (tr->mxtips + tr->mxtips - 1); i++) np[i] = tr->nodep[i]; reorderNodes(tr, np, tr->start->back, &count); rax_free(np); } void makeParsimonyTree(tree *tr, analdef *adef) { makeParsimonyTreeFast(tr, adef, TRUE); } void makeParsimonyTreeIncomplete(tree *tr, analdef *adef) { makeParsimonyTreeFast(tr, adef, FALSE); } static void setupBranchMetaInfo(tree *tr, nodeptr p, int nTips, branchInfo *bInf) { int countBranches = tr->branchCounter; if(isTip(p->number, tr->mxtips)) { p->bInf = &bInf[countBranches]; p->back->bInf = &bInf[countBranches]; bInf[countBranches].oP = p; bInf[countBranches].oQ = p->back; bInf[countBranches].epa->leftNodeNumber = p->number; bInf[countBranches].epa->rightNodeNumber = p->back->number; bInf[countBranches].epa->branchNumber = countBranches; bInf[countBranches].epa->originalBranchLength = p->z[0]; tr->branchCounter = tr->branchCounter + 1; return; } else { nodeptr q; assert(p == p->next->next->next); p->bInf = &bInf[countBranches]; p->back->bInf = &bInf[countBranches]; bInf[countBranches].oP = p; bInf[countBranches].oQ = p->back; bInf[countBranches].epa->leftNodeNumber = p->number; bInf[countBranches].epa->rightNodeNumber = p->back->number; bInf[countBranches].epa->branchNumber = countBranches; bInf[countBranches].epa->originalBranchLength = p->z[0]; tr->branchCounter = tr->branchCounter + 1; q = p->next; while(q != p) { setupBranchMetaInfo(tr, q->back, nTips, bInf); q = q->next; } return; } } static void setupJointFormat(tree *tr, nodeptr p, int ntips, branchInfo *bInf, int *count) { if(isTip(p->number, tr->mxtips)) { p->bInf->epa->jointLabel = *count; *count = *count + 1; return; } else { setupJointFormat(tr, p->next->back, ntips, bInf, count); setupJointFormat(tr, p->next->next->back, ntips, bInf, count); p->bInf->epa->jointLabel = *count; *count = *count + 1; return; } } static void setupBranchInfo(tree *tr, nodeptr q) { nodeptr originalNode = tr->nodep[tr->mxtips + 1]; int count = 0; tr->branchCounter = 0; setupBranchMetaInfo(tr, q, tr->ntips, tr->bInf); assert(tr->branchCounter == tr->numberOfBranches); if(tr->wasRooted) { assert(tr->leftRootNode->back == tr->rightRootNode); assert(tr->leftRootNode == tr->rightRootNode->back); if(!isTip(tr->leftRootNode->number, tr->mxtips)) { setupJointFormat(tr, tr->leftRootNode->next->back, tr->ntips, tr->bInf, &count); setupJointFormat(tr, tr->leftRootNode->next->next->back, tr->ntips, tr->bInf, &count); } tr->leftRootNode->bInf->epa->jointLabel = count; tr->rootLabel = count; count = count + 1; if(!isTip(tr->rightRootNode->number, tr->mxtips)) { setupJointFormat(tr, tr->rightRootNode->next->back, tr->ntips, tr->bInf, &count); setupJointFormat(tr, tr->rightRootNode->next->next->back, tr->ntips, tr->bInf, &count); } } else { setupJointFormat(tr, originalNode->back, tr->ntips, tr->bInf, &count); setupJointFormat(tr, originalNode->next->back, tr->ntips, tr->bInf, &count); setupJointFormat(tr, originalNode->next->next->back, tr->ntips, tr->bInf, &count); } assert(count == tr->numberOfBranches); } static void testInsertFast(tree *tr, nodeptr r, nodeptr q) { unsigned int result; nodeptr x = q->back; int i, *inserts = tr->inserts; assert(!tr->grouped); hookupDefault(r->next, q, tr->numBranches); hookupDefault(r->next->next, x, tr->numBranches); newviewParsimony(tr, r); for(i = 0; i < tr->numberOfTipsForInsertion; i++) { hookupDefault(r, tr->nodep[inserts[i]], tr->numBranches); tr->bestParsimony = INT_MAX; result = evaluateParsimony(tr, r, FALSE); r->back = (nodeptr) NULL; tr->nodep[inserts[i]]->back = (nodeptr) NULL; tr->bInf[q->bInf->epa->branchNumber].epa->parsimonyScore[i] = result; } hookupDefault(q, x, tr->numBranches); r->next->next->back = r->next->back = (nodeptr) NULL; } static void traverseTree(tree *tr, nodeptr r, nodeptr q) { testInsertFast(tr, r, q); if(!isTip(q->number, tr->rdta->numsp)) { nodeptr a = q->next; while(a != q) { traverseTree(tr, r, a->back); a = a->next; } } } typedef struct { unsigned int parsimonyScore; int number; } infoMP; static int infoCompare(const void *p1, const void *p2) { infoMP *rc1 = (infoMP *)p1; infoMP *rc2 = (infoMP *)p2; unsigned int i = rc1->parsimonyScore; unsigned int j = rc2->parsimonyScore; if (i > j) return (1); if (i < j) return (-1); return (0); } void classifyMP(tree *tr, analdef *adef) { int *informative = (int *)rax_malloc(sizeof(int) * (size_t)tr->cdta->endsite), i, j, *perm; infoMP *inf; nodeptr r, q; char jointFormatTreeFileName[1024], originalLabelledTreeFileName[1024], labelledTreeFileName[1024], likelihoodWeightsFileName[1024]; FILE *likelihoodWeightsFile, *treeFile; unsigned int score; assert(adef->restart); determineUninformativeSites(tr, informative); compressDNA(tr, informative, TRUE); rax_free(informative); tr->ti = (int*)rax_malloc(sizeof(int) * 4 * (size_t)tr->mxtips); tr->numberOfBranches = 2 * tr->ntips - 3; printBothOpen("\nRAxML Evolutionary Placement Algorithm using parsimony\n"); tr->bestParsimony = INT_MAX; score = evaluateParsimony(tr, tr->start->back, TRUE); printBothOpen("\nparsimony score of reference tree: %u\n\n", score); perm = (int *)rax_calloc(((size_t)tr->mxtips) + 1, sizeof(int)); tr->inserts = (int *)rax_calloc((size_t)tr->mxtips, sizeof(int)); markTips(tr->start, perm, tr->mxtips); markTips(tr->start->back, perm ,tr->mxtips); tr->numberOfTipsForInsertion = 0; for(i = 1; i <= tr->mxtips; i++) { if(perm[i] == 0) { tr->inserts[tr->numberOfTipsForInsertion] = i; tr->numberOfTipsForInsertion = tr->numberOfTipsForInsertion + 1; } } rax_free(perm); printBothOpen("RAxML will place %d Query Sequences into the %d branches of the reference tree with %d taxa\n\n", tr->numberOfTipsForInsertion, (2 * tr->ntips - 3), tr->ntips); assert(tr->numberOfTipsForInsertion == (tr->mxtips - tr->ntips)); tr->bInf = (branchInfo*)rax_malloc(tr->numberOfBranches * sizeof(branchInfo)); for(i = 0; i < tr->numberOfBranches; i++) { tr->bInf[i].epa = (epaBranchData*)rax_malloc(sizeof(epaBranchData)); tr->bInf[i].epa->parsimonyScore = (unsigned int*)rax_malloc(tr->numberOfTipsForInsertion * sizeof(unsigned int)); for(j = 0; j < tr->numberOfTipsForInsertion; j++) tr->bInf[i].epa->parsimonyScore[j] = INT_MAX; tr->bInf[i].epa->branchNumber = i; tr->bInf[i].epa->countThem = (int*)rax_calloc(tr->numberOfTipsForInsertion, sizeof(int)); sprintf(tr->bInf[i].epa->branchLabel, "I%d", i); } r = tr->nodep[(tr->nextnode)++]; q = findAnyTip(tr->start, tr->rdta->numsp); assert(isTip(q->number, tr->rdta->numsp)); assert(!isTip(q->back->number, tr->rdta->numsp)); q = q->back; setupBranchInfo(tr, q); traverseTree(tr, r, q); printBothOpen("Overall Classification time: %f\n\n", gettime() - masterTime); strcpy(jointFormatTreeFileName, workdir); strcpy(originalLabelledTreeFileName, workdir); strcpy(labelledTreeFileName, workdir); strcpy(likelihoodWeightsFileName, workdir); strcat(jointFormatTreeFileName, "RAxML_portableTree."); strcat(originalLabelledTreeFileName, "RAxML_originalLabelledTree."); strcat(labelledTreeFileName, "RAxML_labelledTree."); strcat(likelihoodWeightsFileName, "RAxML_equallyParsimoniousPlacements."); strcat(jointFormatTreeFileName, run_id); strcat(originalLabelledTreeFileName, run_id); strcat(labelledTreeFileName, run_id); strcat(likelihoodWeightsFileName, run_id); strcat(jointFormatTreeFileName, ".jplace"); rax_free(tr->tree_string); tr->treeStringLength *= 16; tr->tree_string = (char*)rax_calloc(tr->treeStringLength, sizeof(char)); treeFile = myfopen(originalLabelledTreeFileName, "wb"); Tree2StringClassify(tr->tree_string, tr, tr->inserts, TRUE, FALSE, FALSE, tr->mxtips + 1, FALSE); fprintf(treeFile, "%s\n", tr->tree_string); fclose(treeFile); treeFile = myfopen(jointFormatTreeFileName, "wb"); Tree2StringClassify(tr->tree_string, tr, tr->inserts, TRUE, TRUE, FALSE, tr->mxtips + 1, FALSE); fprintf(treeFile, "{\n"); fprintf(treeFile, "\t\"tree\": \"%s\", \n", tr->tree_string); fprintf(treeFile, "\t\"placements\": [\n"); inf = (infoMP*)rax_malloc(sizeof(infoMP) * tr->numberOfBranches); /* joint format */ for(i = 0; i < tr->numberOfTipsForInsertion; i++) { unsigned int lmax; int validEntries = tr->numberOfBranches; for(j = 0; j < tr->numberOfBranches; j++) { inf[j].parsimonyScore = tr->bInf[j].epa->parsimonyScore[i]; inf[j].number = tr->bInf[j].epa->jointLabel; } qsort(inf, tr->numberOfBranches, sizeof(infoMP), infoCompare); j = 0; lmax = inf[0].parsimonyScore; fprintf(treeFile, "\t{\"p\":["); while(j < validEntries && inf[j].parsimonyScore == lmax) { if(j > 0) { if(tr->wasRooted && inf[j].number == tr->rootLabel) assert(0); else fprintf(treeFile, ",[%d, %u]", inf[j].number, inf[j].parsimonyScore); } else { if(tr->wasRooted && inf[j].number == tr->rootLabel) assert(0); else fprintf(treeFile, "[%d, %u]", inf[j].number, inf[j].parsimonyScore); } j++; } if(i == tr->numberOfTipsForInsertion - 1) fprintf(treeFile, "], \"n\":[\"%s\"]}\n", tr->nameList[tr->inserts[i]]); else fprintf(treeFile, "], \"n\":[\"%s\"]},\n", tr->nameList[tr->inserts[i]]); } fprintf(treeFile, "\t ],\n"); /* fprintf(treeFile, "\t\"metadata\": {\"invocation\": \"RAxML EPA parsimony\"},\n");*/ fprintf(treeFile, "\t\"metadata\": {\"invocation\": "); fprintf(treeFile, "\""); { int i; for(i = 0; i < globalArgc; i++) fprintf(treeFile,"%s ", globalArgv[i]); } fprintf(treeFile, "\", \"raxml_version\": \"%s\"", programVersion); fprintf(treeFile,"},\n"); fprintf(treeFile, "\t\"version\": 2,\n"); fprintf(treeFile, "\t\"fields\": [\n"); fprintf(treeFile, "\t\"edge_num\", \"parsimony\"\n"); fprintf(treeFile, "\t]\n"); fprintf(treeFile, "}\n"); fclose(treeFile); /* JSON format end */ likelihoodWeightsFile = myfopen(likelihoodWeightsFileName, "wb"); for(i = 0; i < tr->numberOfTipsForInsertion; i++) { unsigned int lmax; int validEntries = tr->numberOfBranches; for(j = 0; j < tr->numberOfBranches; j++) { inf[j].parsimonyScore = tr->bInf[j].epa->parsimonyScore[i]; inf[j].number = j; } qsort(inf, tr->numberOfBranches, sizeof(infoMP), infoCompare); j = 0; lmax = inf[0].parsimonyScore; while(j < validEntries && inf[j].parsimonyScore == lmax) { fprintf(likelihoodWeightsFile, "%s I%d %u\n", tr->nameList[tr->inserts[i]], inf[j].number, inf[j].parsimonyScore); tr->bInf[inf[j].number].epa->countThem[i] = 1; j++; } } rax_free(inf); fclose(likelihoodWeightsFile); Tree2StringClassify(tr->tree_string, tr, tr->inserts, FALSE, FALSE, FALSE, tr->mxtips + 1, FALSE); treeFile = fopen(labelledTreeFileName, "wb"); fprintf(treeFile, "%s\n", tr->tree_string); fclose(treeFile); printBothOpen("Equally parsimonious read placements written to file: %s\n\n", likelihoodWeightsFileName); printBothOpen("Labelled reference tree with branch labels (without query sequences) written to file: %s\n\n", originalLabelledTreeFileName); printBothOpen("Labelled reference tree with branch labels in portable pplacer/EPA format (without query sequences) written to file: %s\n\n", jointFormatTreeFileName); printBothOpen("Labelled reference tree including branch labels and query sequences written to file: %s\n\n", labelledTreeFileName); exit(0); } #ifdef __AVX #ifdef _SSE3_WAS_DEFINED #define __SIM_SSE3 #undef _SSE3_WAS_DEFINED #endif #endif
826008.c
//------------------------------------------------------------------------------ // GB_Asaxpy3B_noM: hard-coded saxpy3 method for a semiring //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // If this file is in the Generated/ folder, do not edit it (auto-generated). #include "GB_AxB_defs__eq_eq_uint8.h" #ifndef GBCOMPACT //------------------------------------------------------------------------------ // C=A*B, C<M>=A*B, C<!M>=A*B: saxpy method (Gustavson + Hash) //------------------------------------------------------------------------------ #if ( !GB_DISABLE ) #include "GB_AxB_saxpy3_template.h" GrB_Info GB (_Asaxpy3B_noM__eq_eq_uint8) ( GrB_Matrix C, // C=A*B, C sparse or hypersparse const GrB_Matrix A, bool A_is_pattern, const GrB_Matrix B, bool B_is_pattern, GB_saxpy3task_struct *restrict SaxpyTasks, const int ntasks, const int nfine, const int nthreads, const int do_sort, GB_Context Context ) { if (GB_IS_SPARSE (A) && GB_IS_SPARSE (B)) { // both A and B are sparse #define GB_META16 #define GB_NO_MASK 1 #define GB_MASK_COMP 0 #define GB_A_IS_SPARSE 1 #define GB_A_IS_HYPER 0 #define GB_A_IS_BITMAP 0 #define GB_A_IS_FULL 0 #define GB_B_IS_SPARSE 1 #define GB_B_IS_HYPER 0 #define GB_B_IS_BITMAP 0 #define GB_B_IS_FULL 0 #include "GB_meta16_definitions.h" #include "GB_AxB_saxpy3_template.c" } else { // general case #undef GB_META16 #define GB_NO_MASK 1 #define GB_MASK_COMP 0 #include "GB_meta16_definitions.h" #include "GB_AxB_saxpy3_template.c" } return (GrB_SUCCESS) ; } #endif #endif
355648.c
/* statistical difference * * Copyright: 1990, N. Dessipris. * * Author: Nicos Dessipris * Written on: 02/05/1990 * Modified on : * 6/8/93 JC * - now works for odd window sizes * - ANSIfication * 25/5/95 JC * - new IM_ARRAY() macro * 25/1/96 JC * - im_lhisteq() adapted to make new im_stdif() * - now partial, plus rolling window * - 5x faster, amazingly * - works * 7/4/04 * - now uses im_embed() with edge stretching on the input, not * the output * 25/3/10 * - gtkdoc * - small cleanups * 10/8/13 * - wrapped as a class using hist_local.c * - many bands */ /* This file is part of VIPS. VIPS is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser 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 */ /* These files are distributed with VIPS - http://www.vips.ecs.soton.ac.uk */ #ifdef HAVE_CONFIG_H #include <config.h> #endif /*HAVE_CONFIG_H*/ #include <vips/intl.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include <vips/vips.h> #include <vips/internal.h> typedef struct _VipsStdif { VipsOperation parent_instance; VipsImage *in; VipsImage *out; int width; int height; double a; double m0; double b; double s0; } VipsStdif; typedef VipsOperationClass VipsStdifClass; G_DEFINE_TYPE( VipsStdif, vips_stdif, VIPS_TYPE_OPERATION ); /* How ugly and stupid. */ #define MAX_BANDS (100) static int vips_stdif_generate( VipsRegion *or, void *vseq, void *a, void *b, gboolean *stop ) { VipsRect *r = &or->valid; VipsRegion *ir = (VipsRegion *) vseq; VipsImage *in = (VipsImage *) a; VipsStdif *stdif = (VipsStdif *) b; int bands = in->Bands; int npel = stdif->width * stdif->width; VipsRect irect; int y; int lsk; int centre; /* Offset to move to centre of window */ /* What part of ir do we need? */ irect.left = or->valid.left; irect.top = or->valid.top; irect.width = or->valid.width + stdif->width; irect.height = or->valid.height + stdif->height; if( vips_region_prepare( ir, &irect ) ) return( -1 ); lsk = VIPS_REGION_LSKIP( ir ); centre = lsk * (stdif->height / 2) + stdif->width / 2; for( y = 0; y < r->height; y++ ) { /* Get input and output pointers for this line. */ VipsPel *p = VIPS_REGION_ADDR( ir, r->left, r->top + y ); VipsPel *q = VIPS_REGION_ADDR( or, r->left, r->top + y ); double f1 = stdif->a * stdif->m0; double f2 = 1.0 - stdif->a; double f3 = stdif->b * stdif->s0; VipsPel *p1; int x, i, j, b; /* We will get int overflow for windows larger than about 256 * x 256, sadly. */ unsigned int sum[MAX_BANDS]; unsigned int sum2[MAX_BANDS]; /* Find sum, sum of squares for the start of this line. */ for( b = 0; b < bands; b++ ) { memset( sum, 0, bands * sizeof( unsigned int ) ); memset( sum2, 0, bands * sizeof( unsigned int ) ); } p1 = p; for( j = 0; j < stdif->height; j++ ) { i = 0; for( x = 0; x < stdif->width; x++ ) { for( b = 0; b < bands; b++ ) { int t = p1[i++]; sum[b] += t; sum2[b] += t * t; } } p1 += lsk; } /* Loop for output pels. */ for( x = 0; x < r->width; x++ ) { for( b = 0; b < bands; b++ ) { /* Find stats. */ double mean = (double) sum[b] / npel; double var = (double) sum2[b] / npel - (mean * mean); double sig = sqrt( var ); /* Transform. */ double res = f1 + f2 * mean + ((double) p[centre] - mean) * (f3 / (stdif->s0 + stdif->b * sig)); /* And write. */ if( res < 0.0 ) *q++ = 0; else if( res >= 256.0 ) *q++ = 255; else *q++ = res + 0.5; /* Adapt sums - remove the pels from the left * hand column, add in pels for a new * right-hand column. */ p1 = p; for( j = 0; j < stdif->height; j++ ) { int t1 = p1[0]; int t2 = p1[bands * stdif->width]; sum[b] -= t1; sum2[b] -= t1 * t1; sum[b] += t2; sum2[b] += t2 * t2; p1 += lsk; } p += 1; } } } return( 0 ); } static int vips_stdif_build( VipsObject *object ) { VipsObjectClass *class = VIPS_OBJECT_GET_CLASS( object ); VipsStdif *stdif = (VipsStdif *) object; VipsImage **t = (VipsImage **) vips_object_local_array( object, 3 ); VipsImage *in; if( VIPS_OBJECT_CLASS( vips_stdif_parent_class )->build( object ) ) return( -1 ); in = stdif->in; if( vips_image_decode( in, &t[0] ) ) return( -1 ); in = t[0]; if( vips_check_format( class->nickname, in, VIPS_FORMAT_UCHAR ) ) return( -1 ); if( stdif->width > in->Xsize || stdif->height > in->Ysize ) { vips_error( class->nickname, "%s", _( "window too large" ) ); return( -1 ); } if( in->Bands > MAX_BANDS ) { vips_error( class->nickname, "%s", _( "too many bands" ) ); return( -1 ); } /* Expand the input. */ if( vips_embed( in, &t[1], stdif->width / 2, stdif->height / 2, in->Xsize + stdif->width - 1, in->Ysize + stdif->height - 1, "extend", VIPS_EXTEND_COPY, NULL ) ) return( -1 ); in = t[1]; g_object_set( object, "out", vips_image_new(), NULL ); /* Set demand hints. FATSTRIP is good for us, as THINSTRIP will cause * too many recalculations on overlaps. */ if( vips_image_pipelinev( stdif->out, VIPS_DEMAND_STYLE_FATSTRIP, in, NULL ) ) return( -1 ); stdif->out->Xsize -= stdif->width - 1; stdif->out->Ysize -= stdif->height - 1; if( vips_image_generate( stdif->out, vips_start_one, vips_stdif_generate, vips_stop_one, in, stdif ) ) return( -1 ); stdif->out->Xoffset = 0; stdif->out->Yoffset = 0; return( 0 ); } static void vips_stdif_class_init( VipsStdifClass *class ) { GObjectClass *gobject_class = G_OBJECT_CLASS( class ); VipsObjectClass *object_class = (VipsObjectClass *) class; gobject_class->set_property = vips_object_set_property; gobject_class->get_property = vips_object_get_property; object_class->nickname = "stdif"; object_class->description = _( "statistical difference" ); object_class->build = vips_stdif_build; VIPS_ARG_IMAGE( class, "in", 1, _( "Input" ), _( "Input image" ), VIPS_ARGUMENT_REQUIRED_INPUT, G_STRUCT_OFFSET( VipsStdif, in ) ); VIPS_ARG_IMAGE( class, "out", 2, _( "Output" ), _( "Output image" ), VIPS_ARGUMENT_REQUIRED_OUTPUT, G_STRUCT_OFFSET( VipsStdif, out ) ); /* Windows larger than 256x256 will overflow sum2, see above. */ VIPS_ARG_INT( class, "width", 4, _( "Width" ), _( "Window width in pixels" ), VIPS_ARGUMENT_REQUIRED_INPUT, G_STRUCT_OFFSET( VipsStdif, width ), 1, 256, 11 ); VIPS_ARG_INT( class, "height", 5, _( "Height" ), _( "Window height in pixels" ), VIPS_ARGUMENT_REQUIRED_INPUT, G_STRUCT_OFFSET( VipsStdif, height ), 1, 256, 11 ); VIPS_ARG_DOUBLE( class, "a", 2, _( "Mean weight" ), _( "Weight of new mean" ), VIPS_ARGUMENT_OPTIONAL_INPUT, G_STRUCT_OFFSET( VipsStdif, a ), 0.0, 1.0, 0.5 ); VIPS_ARG_DOUBLE( class, "m0", 2, _( "Mean" ), _( "New mean" ), VIPS_ARGUMENT_OPTIONAL_INPUT, G_STRUCT_OFFSET( VipsStdif, m0 ), -INFINITY, INFINITY, 128 ); VIPS_ARG_DOUBLE( class, "b", 2, _( "Deviation weight" ), _( "Weight of new deviation" ), VIPS_ARGUMENT_OPTIONAL_INPUT, G_STRUCT_OFFSET( VipsStdif, b ), 0.0, 2.0, 0.5 ); VIPS_ARG_DOUBLE( class, "s0", 2, _( "Deviation" ), _( "New deviation" ), VIPS_ARGUMENT_OPTIONAL_INPUT, G_STRUCT_OFFSET( VipsStdif, s0 ), -INFINITY, INFINITY, 50 ); } static void vips_stdif_init( VipsStdif *stdif ) { stdif->width = 11; stdif->height = 11; stdif->a = 0.5; stdif->m0 = 128.0; stdif->b = 0.5; stdif->s0 = 50.0; } /** * vips_stdif: * @in: input image * @out: output image * @width: width of region * @height: height of region * @...: %NULL-terminated list of optional named arguments * * Optional arguments: * * * @a: weight of new mean * * @m0: target mean * * @b: weight of new deviation * * @s0: target deviation * * vips_stdif() preforms statistical differencing according to the formula * given in page 45 of the book "An Introduction to Digital Image * Processing" by Wayne Niblack. This transformation emphasises the way in * which a pel differs statistically from its neighbours. It is useful for * enhancing low-contrast images with lots of detail, such as X-ray plates. * * At point (i,j) the output is given by the equation: * * |[ * vout(i,j) = @a * @m0 + (1 - @a) * meanv + * (vin(i,j) - meanv) * (@b * @s0) / (@s0 + @b * stdv) * ]| * * Values @a, @m0, @b and @s0 are entered, while meanv and stdv are the values * calculated over a moving window of size @width, @height centred on pixel * (i,j). @m0 is the new mean, @a is the weight given to it. @s0 is the new * standard deviation, @b is the weight given to it. * * Try: * * |[ * vips stdif $VIPSHOME/pics/huysum.v fred.v 0.5 128 0.5 50 11 11 * ]| * * The operation works on one-band uchar images only, and writes a one-band * uchar image as its result. The output image has the same size as the * input. * * See also: vips_hist_local(). * * Returns: 0 on success, -1 on error */ int vips_stdif( VipsImage *in, VipsImage **out, int width, int height, ... ) { va_list ap; int result; va_start( ap, height ); result = vips_call_split( "stdif", ap, in, out, width, height ); va_end( ap ); return( result ); }
433889.c
#ifdef HAVE_CONFIG_H #include "../ext_config.h" #endif #include <php.h> #include "../php_ext.h" #include "../ext.h" #include <Zend/zend_operators.h> #include <Zend/zend_exceptions.h> #include <Zend/zend_interfaces.h> #include "kernel/main.h" /** * 沙盒 auth * * @author Xiangmin Liu <635750556@qq.com> * * @since 2017.12.23 * * @version 1.0 */ ZEPHIR_INIT_CLASS(Leevel_Auth) { ZEPHIR_REGISTER_CLASS_EX(Leevel, Auth, leevel, auth, leevel_support_facade_ce, leevel_auth_method_entry, 0); return SUCCESS; } /** * 返回门面名字 * * @return string */ PHP_METHOD(Leevel_Auth, name) { zval *this_ptr = getThis(); RETURN_STRING("auths"); }
827380.c
/* * Copyright (c) 2012 Georg Lippitsch <georg.lippitsch@gmx.at> * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file * libiec61883 interface */ #include <sys/poll.h> #include <libraw1394/raw1394.h> #include <libavc1394/avc1394.h> #include <libavc1394/rom1394.h> #include <libiec61883/iec61883.h> #include "libavformat/dv.h" #include "libavformat/mpegts.h" #include "libavutil/opt.h" #include "avdevice.h" #define THREADS HAVE_PTHREADS #if THREADS #include <pthread.h> #endif #define MOTDCT_SPEC_ID 0x00005068 #define IEC61883_AUTO 0 #define IEC61883_DV 1 #define IEC61883_HDV 2 /** * For DV, one packet corresponds exactly to one frame. * For HDV, these are MPEG2 transport stream packets. * The queue is implemented as linked list. */ typedef struct DVPacket { uint8_t *buf; ///< actual buffer data int len; ///< size of buffer allocated struct DVPacket *next; ///< next DVPacket } DVPacket; struct iec61883_data { AVClass *class; raw1394handle_t raw1394; ///< handle for libraw1394 iec61883_dv_fb_t iec61883_dv; ///< handle for libiec61883 when used with DV iec61883_mpeg2_t iec61883_mpeg2; ///< handle for libiec61883 when used with HDV DVDemuxContext *dv_demux; ///< generic DV muxing/demuxing context MpegTSContext *mpeg_demux; ///< generic HDV muxing/demuxing context DVPacket *queue_first; ///< first element of packet queue DVPacket *queue_last; ///< last element of packet queue char *device_guid; ///< to select one of multiple DV devices int packets; ///< Number of packets queued int max_packets; ///< Max. number of packets in queue int bandwidth; ///< returned by libiec61883 int channel; ///< returned by libiec61883 int input_port; ///< returned by libiec61883 int type; ///< Stream type, to distinguish DV/HDV int node; ///< returned by libiec61883 int output_port; ///< returned by libiec61883 int thread_loop; ///< Condition for thread while-loop int receiving; ///< True as soon data from device available int receive_error; ///< Set in receive task in case of error int eof; ///< True as soon as no more data available struct pollfd raw1394_poll; ///< to poll for new data from libraw1394 /** Parse function for DV/HDV differs, so this is set before packets arrive */ int (*parse_queue)(struct iec61883_data *dv, AVPacket *pkt); #if THREADS pthread_t receive_task_thread; pthread_mutex_t mutex; pthread_cond_t cond; #endif }; static int iec61883_callback(unsigned char *data, int length, int complete, void *callback_data) { struct iec61883_data *dv = callback_data; DVPacket *packet; int ret; #if THREADS pthread_mutex_lock(&dv->mutex); #endif if (dv->packets >= dv->max_packets) { av_log(NULL, AV_LOG_ERROR, "DV packet queue overrun, dropping.\n"); ret = 0; goto exit; } packet = av_mallocz(sizeof(*packet)); if (!packet) { ret = -1; goto exit; } packet->buf = av_malloc(length); if (!packet->buf) { ret = -1; goto exit; } packet->len = length; memcpy(packet->buf, data, length); if (dv->queue_first) { dv->queue_last->next = packet; dv->queue_last = packet; } else { dv->queue_first = packet; dv->queue_last = packet; } dv->packets++; ret = 0; exit: #if THREADS pthread_cond_broadcast(&dv->cond); pthread_mutex_unlock(&dv->mutex); #endif return ret; } static void *iec61883_receive_task(void *opaque) { struct iec61883_data *dv = (struct iec61883_data *)opaque; int result; #if THREADS while (dv->thread_loop) #endif { while ((result = poll(&dv->raw1394_poll, 1, 200)) < 0) { if (!(errno == EAGAIN || errno == EINTR)) { av_log(NULL, AV_LOG_ERROR, "Raw1394 poll error occurred.\n"); dv->receive_error = AVERROR(EIO); return NULL; } } if (result > 0 && ((dv->raw1394_poll.revents & POLLIN) || (dv->raw1394_poll.revents & POLLPRI))) { dv->receiving = 1; raw1394_loop_iterate(dv->raw1394); } else if (dv->receiving) { av_log(NULL, AV_LOG_ERROR, "No more input data available\n"); #if THREADS pthread_mutex_lock(&dv->mutex); dv->eof = 1; pthread_cond_broadcast(&dv->cond); pthread_mutex_unlock(&dv->mutex); #else dv->eof = 1; #endif return NULL; } } return NULL; } static int iec61883_parse_queue_dv(struct iec61883_data *dv, AVPacket *pkt) { DVPacket *packet; int size; size = avpriv_dv_get_packet(dv->dv_demux, pkt); if (size > 0) return size; packet = dv->queue_first; if (!packet) return -1; size = avpriv_dv_produce_packet(dv->dv_demux, pkt, packet->buf, packet->len, -1); dv->queue_first = packet->next; av_free(packet); dv->packets--; if (size > 0) return size; return -1; } static int iec61883_parse_queue_hdv(struct iec61883_data *dv, AVPacket *pkt) { DVPacket *packet; int size; while (dv->queue_first) { packet = dv->queue_first; size = avpriv_mpegts_parse_packet(dv->mpeg_demux, pkt, packet->buf, packet->len); dv->queue_first = packet->next; av_freep(&packet->buf); av_freep(&packet); dv->packets--; if (size > 0) return size; } return -1; } static int iec61883_read_header(AVFormatContext *context) { struct iec61883_data *dv = context->priv_data; struct raw1394_portinfo pinf[16]; rom1394_directory rom_dir; char *endptr; int inport; int nb_ports; int port = -1; int response; int i, j = 0; uint64_t guid = 0; dv->input_port = -1; dv->output_port = -1; dv->channel = -1; dv->raw1394 = raw1394_new_handle(); if (!dv->raw1394) { av_log(context, AV_LOG_ERROR, "Failed to open IEEE1394 interface.\n"); return AVERROR(EIO); } if ((nb_ports = raw1394_get_port_info(dv->raw1394, pinf, 16)) < 0) { av_log(context, AV_LOG_ERROR, "Failed to get number of IEEE1394 ports.\n"); goto fail; } inport = strtol(context->filename, &endptr, 10); if (endptr != context->filename && *endptr == '\0') { av_log(context, AV_LOG_INFO, "Selecting IEEE1394 port: %d\n", inport); j = inport; nb_ports = inport + 1; } else if (strcmp(context->filename, "auto")) { av_log(context, AV_LOG_ERROR, "Invalid input \"%s\", you should specify " "\"auto\" for auto-detection, or the port number.\n", context->filename); goto fail; } if (dv->device_guid) { if (sscanf(dv->device_guid, "%"SCNu64, &guid) != 1) { av_log(context, AV_LOG_INFO, "Invalid dvguid parameter: %s\n", dv->device_guid); goto fail; } } for (; j < nb_ports && port==-1; ++j) { raw1394_destroy_handle(dv->raw1394); if (!(dv->raw1394 = raw1394_new_handle_on_port(j))) { av_log(context, AV_LOG_ERROR, "Failed setting IEEE1394 port.\n"); goto fail; } for (i=0; i<raw1394_get_nodecount(dv->raw1394); ++i) { /* Select device explicitly by GUID */ if (guid > 1) { if (guid == rom1394_get_guid(dv->raw1394, i)) { dv->node = i; port = j; break; } } else { /* Select first AV/C tape recorder player node */ if (rom1394_get_directory(dv->raw1394, i, &rom_dir) < 0) continue; if (((rom1394_get_node_type(&rom_dir) == ROM1394_NODE_TYPE_AVC) && avc1394_check_subunit_type(dv->raw1394, i, AVC1394_SUBUNIT_TYPE_VCR)) || (rom_dir.unit_spec_id == MOTDCT_SPEC_ID)) { rom1394_free_directory(&rom_dir); dv->node = i; port = j; break; } rom1394_free_directory(&rom_dir); } } } if (port == -1) { av_log(context, AV_LOG_ERROR, "No AV/C devices found.\n"); goto fail; } /* Provide bus sanity for multiple connections */ iec61883_cmp_normalize_output(dv->raw1394, 0xffc0 | dv->node); /* Find out if device is DV or HDV */ if (dv->type == IEC61883_AUTO) { response = avc1394_transaction(dv->raw1394, dv->node, AVC1394_CTYPE_STATUS | AVC1394_SUBUNIT_TYPE_TAPE_RECORDER | AVC1394_SUBUNIT_ID_0 | AVC1394_VCR_COMMAND_OUTPUT_SIGNAL_MODE | 0xFF, 2); response = AVC1394_GET_OPERAND0(response); dv->type = (response == 0x10 || response == 0x90 || response == 0x1A || response == 0x9A) ? IEC61883_HDV : IEC61883_DV; } /* Connect to device, and do initialization */ dv->channel = iec61883_cmp_connect(dv->raw1394, dv->node, &dv->output_port, raw1394_get_local_id(dv->raw1394), &dv->input_port, &dv->bandwidth); if (dv->channel < 0) dv->channel = 63; if (!dv->max_packets) dv->max_packets = 100; if (CONFIG_MPEGTS_DEMUXER && dv->type == IEC61883_HDV) { /* Init HDV receive */ avformat_new_stream(context, NULL); dv->mpeg_demux = avpriv_mpegts_parse_open(context); if (!dv->mpeg_demux) goto fail; dv->parse_queue = iec61883_parse_queue_hdv; dv->iec61883_mpeg2 = iec61883_mpeg2_recv_init(dv->raw1394, (iec61883_mpeg2_recv_t)iec61883_callback, dv); dv->max_packets *= 766; } else { /* Init DV receive */ dv->dv_demux = avpriv_dv_init_demux(context); if (!dv->dv_demux) goto fail; dv->parse_queue = iec61883_parse_queue_dv; dv->iec61883_dv = iec61883_dv_fb_init(dv->raw1394, iec61883_callback, dv); } dv->raw1394_poll.fd = raw1394_get_fd(dv->raw1394); dv->raw1394_poll.events = POLLIN | POLLERR | POLLHUP | POLLPRI; /* Actually start receiving */ if (dv->type == IEC61883_HDV) iec61883_mpeg2_recv_start(dv->iec61883_mpeg2, dv->channel); else iec61883_dv_fb_start(dv->iec61883_dv, dv->channel); #if THREADS dv->thread_loop = 1; if (pthread_mutex_init(&dv->mutex, NULL)) goto fail; if (pthread_cond_init(&dv->cond, NULL)) goto fail; if (pthread_create(&dv->receive_task_thread, NULL, iec61883_receive_task, dv)) goto fail; #endif return 0; fail: raw1394_destroy_handle(dv->raw1394); return AVERROR(EIO); } static int iec61883_read_packet(AVFormatContext *context, AVPacket *pkt) { struct iec61883_data *dv = context->priv_data; int size; /** * Try to parse frames from queue */ #if THREADS pthread_mutex_lock(&dv->mutex); while ((size = dv->parse_queue(dv, pkt)) == -1) if (!dv->eof) pthread_cond_wait(&dv->cond, &dv->mutex); else break; pthread_mutex_unlock(&dv->mutex); #else int result; while ((size = dv->parse_queue(dv, pkt)) == -1) { iec61883_receive_task((void *)dv); if (dv->receive_error) return dv->receive_error; } #endif return size; } static int iec61883_close(AVFormatContext *context) { struct iec61883_data *dv = context->priv_data; #if THREADS dv->thread_loop = 0; pthread_join(dv->receive_task_thread, NULL); pthread_cond_destroy(&dv->cond); pthread_mutex_destroy(&dv->mutex); #endif if (CONFIG_MPEGTS_DEMUXER && dv->type == IEC61883_HDV) { iec61883_mpeg2_recv_stop(dv->iec61883_mpeg2); iec61883_mpeg2_close(dv->iec61883_mpeg2); avpriv_mpegts_parse_close(dv->mpeg_demux); } else { iec61883_dv_fb_stop(dv->iec61883_dv); iec61883_dv_fb_close(dv->iec61883_dv); } while (dv->queue_first) { DVPacket *packet = dv->queue_first; dv->queue_first = packet->next; av_freep(&packet->buf); av_freep(&packet); } iec61883_cmp_disconnect(dv->raw1394, dv->node, dv->output_port, raw1394_get_local_id(dv->raw1394), dv->input_port, dv->channel, dv->bandwidth); raw1394_destroy_handle(dv->raw1394); return 0; } static const AVOption options[] = { { "dvtype", "override autodetection of DV/HDV", offsetof(struct iec61883_data, type), AV_OPT_TYPE_INT, {.i64 = IEC61883_AUTO}, IEC61883_AUTO, IEC61883_HDV, AV_OPT_FLAG_DECODING_PARAM, "dvtype" }, { "auto", "auto detect DV/HDV", 0, AV_OPT_TYPE_CONST, {.i64 = IEC61883_AUTO}, 0, 0, AV_OPT_FLAG_DECODING_PARAM, "dvtype" }, { "dv", "force device being treated as DV device", 0, AV_OPT_TYPE_CONST, {.i64 = IEC61883_DV}, 0, 0, AV_OPT_FLAG_DECODING_PARAM, "dvtype" }, { "hdv" , "force device being treated as HDV device", 0, AV_OPT_TYPE_CONST, {.i64 = IEC61883_HDV}, 0, 0, AV_OPT_FLAG_DECODING_PARAM, "dvtype" }, { "dvbuffer", "set queue buffer size (in packets)", offsetof(struct iec61883_data, max_packets), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, AV_OPT_FLAG_DECODING_PARAM }, { "dvguid", "select one of multiple DV devices by its GUID", offsetof(struct iec61883_data, device_guid), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, AV_OPT_FLAG_DECODING_PARAM }, { NULL }, }; static const AVClass iec61883_class = { .class_name = "iec61883 indev", .item_name = av_default_item_name, .option = options, .version = LIBAVUTIL_VERSION_INT, .category = AV_CLASS_CATEGORY_DEVICE_VIDEO_INPUT, }; AVInputFormat ff_iec61883_demuxer = { .name = "iec61883", .long_name = NULL_IF_CONFIG_SMALL("libiec61883 (new DV1394) A/V input device"), .priv_data_size = sizeof(struct iec61883_data), .read_header = iec61883_read_header, .read_packet = iec61883_read_packet, .read_close = iec61883_close, .flags = AVFMT_NOFILE, .priv_class = &iec61883_class, };
713364.c
#include <stdio.h> #include <string.h> #include <stdlib.h> #include <errno.h> #include <unistd.h> #include <pthread.h> #define error_en(en, msg) \ do { \ errno = en; \ perror(msg); \ exit(EXIT_FAILURE); \ } while (0) static void *thread_t1(void *arg) { printf("%s\n", (char *)arg); return (void *)strlen(arg); } int main(int argc, char *argv[]) { int ret = 0; void *result = NULL; pthread_t t1; ret = pthread_create(&t1, NULL, thread_t1, "Thread t1"); if (ret) error_en(ret, "Thread create failed"); ret = pthread_join(t1, &result); if (ret) error_en(ret, "Thread join failed"); printf("Thread return: %zu\n", (size_t)result); exit(EXIT_SUCCESS); }
734422.c
// Copyright 2011 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. #include "runtime.h" #include "defs_GOOS_GOARCH.h" #include "os_GOOS.h" void runtime·dumpregs(Context *r) { runtime·printf("rax %X\n", r->Rax); runtime·printf("rbx %X\n", r->Rbx); runtime·printf("rcx %X\n", r->Rcx); runtime·printf("rdx %X\n", r->Rdx); runtime·printf("rdi %X\n", r->Rdi); runtime·printf("rsi %X\n", r->Rsi); runtime·printf("rbp %X\n", r->Rbp); runtime·printf("rsp %X\n", r->Rsp); runtime·printf("r8 %X\n", r->R8 ); runtime·printf("r9 %X\n", r->R9 ); runtime·printf("r10 %X\n", r->R10); runtime·printf("r11 %X\n", r->R11); runtime·printf("r12 %X\n", r->R12); runtime·printf("r13 %X\n", r->R13); runtime·printf("r14 %X\n", r->R14); runtime·printf("r15 %X\n", r->R15); runtime·printf("rip %X\n", r->Rip); runtime·printf("rflags %X\n", r->EFlags); runtime·printf("cs %X\n", (uint64)r->SegCs); runtime·printf("fs %X\n", (uint64)r->SegFs); runtime·printf("gs %X\n", (uint64)r->SegGs); } uint32 runtime·sighandler(ExceptionRecord *info, Context *r, G *gp) { bool crash; uintptr *sp; switch(info->ExceptionCode) { case EXCEPTION_BREAKPOINT: return 1; } if(gp != nil && runtime·issigpanic(info->ExceptionCode)) { // Make it look like a call to the signal func. // Have to pass arguments out of band since // augmenting the stack frame would break // the unwinding code. gp->sig = info->ExceptionCode; gp->sigcode0 = info->ExceptionInformation[0]; gp->sigcode1 = info->ExceptionInformation[1]; gp->sigpc = r->Rip; // Only push runtime·sigpanic if r->rip != 0. // If r->rip == 0, probably panicked because of a // call to a nil func. Not pushing that onto sp will // make the trace look like a call to runtime·sigpanic instead. // (Otherwise the trace will end at runtime·sigpanic and we // won't get to see who faulted.) if(r->Rip != 0) { sp = (uintptr*)r->Rsp; *--sp = r->Rip; r->Rsp = (uintptr)sp; } r->Rip = (uintptr)runtime·sigpanic; return 0; } if(runtime·panicking) // traceback already printed runtime·exit(2); runtime·panicking = 1; runtime·printf("Exception %x %p %p\n", info->ExceptionCode, info->ExceptionInformation[0], info->ExceptionInformation[1]); runtime·printf("PC=%X\n", r->Rip); if(m->lockedg != nil && m->ncgo > 0 && gp == m->g0) { runtime·printf("signal arrived during cgo execution\n"); gp = m->lockedg; } runtime·printf("\n"); if(runtime·gotraceback(&crash)){ runtime·traceback(r->Rip, r->Rsp, 0, gp); runtime·tracebackothers(gp); runtime·dumpregs(r); } if(crash) runtime·crash(); runtime·exit(2); return 0; } void runtime·sigenable(uint32 sig) { USED(sig); } void runtime·sigdisable(uint32 sig) { USED(sig); } void runtime·dosigprof(Context *r, G *gp) { runtime·sigprof((uint8*)r->Rip, (uint8*)r->Rsp, nil, gp); }
574670.c
#include <stdint.h> #include "address.h" #include "params.h" #include "utils.h" void PQCLEAN_SPHINCSSHA256128SSIMPLE_CLEAN_addr_to_bytes( unsigned char *bytes, const uint32_t addr[8]) { int i; for (i = 0; i < 8; i++) { PQCLEAN_SPHINCSSHA256128SSIMPLE_CLEAN_ull_to_bytes( bytes + i * 4, 4, addr[i]); } } void PQCLEAN_SPHINCSSHA256128SSIMPLE_CLEAN_set_layer_addr( uint32_t addr[8], uint32_t layer) { addr[0] = layer; } void PQCLEAN_SPHINCSSHA256128SSIMPLE_CLEAN_set_tree_addr( uint32_t addr[8], uint64_t tree) { addr[1] = 0; addr[2] = (uint32_t) (tree >> 32); addr[3] = (uint32_t) tree; } void PQCLEAN_SPHINCSSHA256128SSIMPLE_CLEAN_set_type( uint32_t addr[8], uint32_t type) { addr[4] = type; } void PQCLEAN_SPHINCSSHA256128SSIMPLE_CLEAN_copy_subtree_addr( uint32_t out[8], const uint32_t in[8]) { out[0] = in[0]; out[1] = in[1]; out[2] = in[2]; out[3] = in[3]; } /* These functions are used for OTS addresses. */ void PQCLEAN_SPHINCSSHA256128SSIMPLE_CLEAN_set_keypair_addr( uint32_t addr[8], uint32_t keypair) { addr[5] = keypair; } void PQCLEAN_SPHINCSSHA256128SSIMPLE_CLEAN_copy_keypair_addr( uint32_t out[8], const uint32_t in[8]) { out[0] = in[0]; out[1] = in[1]; out[2] = in[2]; out[3] = in[3]; out[5] = in[5]; } void PQCLEAN_SPHINCSSHA256128SSIMPLE_CLEAN_set_chain_addr( uint32_t addr[8], uint32_t chain) { addr[6] = chain; } void PQCLEAN_SPHINCSSHA256128SSIMPLE_CLEAN_set_hash_addr( uint32_t addr[8], uint32_t hash) { addr[7] = hash; } /* These functions are used for all hash tree addresses (including FORS). */ void PQCLEAN_SPHINCSSHA256128SSIMPLE_CLEAN_set_tree_height( uint32_t addr[8], uint32_t tree_height) { addr[6] = tree_height; } void PQCLEAN_SPHINCSSHA256128SSIMPLE_CLEAN_set_tree_index( uint32_t addr[8], uint32_t tree_index) { addr[7] = tree_index; }
553136.c
/* l2cap.c - L2CAP handling */ /* * Copyright (c) 2015-2016 Intel Corporation * * SPDX-License-Identifier: Apache-2.0 */ #include <zephyr.h> #include <string.h> #include <errno.h> #include <sys/atomic.h> #include <sys/byteorder.h> #include <sys/util.h> #include <bluetooth/hci.h> #include <bluetooth/bluetooth.h> #include <bluetooth/conn.h> #include <drivers/bluetooth/hci_driver.h> #define BT_DBG_ENABLED IS_ENABLED(CONFIG_BT_DEBUG_L2CAP) #define LOG_MODULE_NAME bt_l2cap #include "common/log.h" #include "hci_core.h" #include "conn_internal.h" #include "l2cap_internal.h" #define LE_CHAN_RTX(_w) CONTAINER_OF(_w, struct bt_l2cap_le_chan, chan.rtx_work) #define CHAN_RX(_w) CONTAINER_OF(_w, struct bt_l2cap_le_chan, rx_work) #define L2CAP_LE_MIN_MTU 23 #define L2CAP_ECRED_MIN_MTU 64 #if defined(CONFIG_BT_HCI_ACL_FLOW_CONTROL) #define L2CAP_LE_MAX_CREDITS (CONFIG_BT_ACL_RX_COUNT - 1) #else #define L2CAP_LE_MAX_CREDITS (CONFIG_BT_RX_BUF_COUNT - 1) #endif #define L2CAP_LE_CID_DYN_START 0x0040 #define L2CAP_LE_CID_DYN_END 0x007f #define L2CAP_LE_CID_IS_DYN(_cid) \ (_cid >= L2CAP_LE_CID_DYN_START && _cid <= L2CAP_LE_CID_DYN_END) #define L2CAP_LE_PSM_FIXED_START 0x0001 #define L2CAP_LE_PSM_FIXED_END 0x007f #define L2CAP_LE_PSM_DYN_START 0x0080 #define L2CAP_LE_PSM_DYN_END 0x00ff #define L2CAP_LE_PSM_IS_DYN(_psm) \ (_psm >= L2CAP_LE_PSM_DYN_START && _psm <= L2CAP_LE_PSM_DYN_END) #define L2CAP_CONN_TIMEOUT K_SECONDS(40) #define L2CAP_DISC_TIMEOUT K_SECONDS(2) #define L2CAP_RTX_TIMEOUT K_SECONDS(2) /* Dedicated pool for disconnect buffers so they are guaranteed to be send * even in case of data congestion due to flooding. */ NET_BUF_POOL_FIXED_DEFINE(disc_pool, 1, BT_L2CAP_BUF_SIZE(CONFIG_BT_L2CAP_TX_MTU), NULL); #if defined(CONFIG_BT_L2CAP_DYNAMIC_CHANNEL) /* Size of MTU is based on the maximum amount of data the buffer can hold * excluding ACL and driver headers. */ #define L2CAP_MAX_LE_MPS BT_L2CAP_RX_MTU /* For now use MPS - SDU length to disable segmentation */ #define L2CAP_MAX_LE_MTU (L2CAP_MAX_LE_MPS - 2) #define L2CAP_ECRED_CHAN_MAX 5 #define l2cap_lookup_ident(conn, ident) __l2cap_lookup_ident(conn, ident, false) #define l2cap_remove_ident(conn, ident) __l2cap_lookup_ident(conn, ident, true) struct data_sent { uint16_t len; }; #define data_sent(buf) ((struct data_sent *)net_buf_user_data(buf)) static sys_slist_t servers; #endif /* CONFIG_BT_L2CAP_DYNAMIC_CHANNEL */ /* L2CAP signalling channel specific context */ struct bt_l2cap { /* The channel this context is associated with */ struct bt_l2cap_le_chan chan; }; static struct bt_l2cap bt_l2cap_pool[CONFIG_BT_MAX_CONN]; static uint8_t get_ident(void) { static uint8_t ident; ident++; /* handle integer overflow (0 is not valid) */ if (!ident) { ident++; } return ident; } #if defined(CONFIG_BT_L2CAP_DYNAMIC_CHANNEL) static struct bt_l2cap_le_chan *l2cap_chan_alloc_cid(struct bt_conn *conn, struct bt_l2cap_chan *chan) { struct bt_l2cap_le_chan *ch = BT_L2CAP_LE_CHAN(chan); uint16_t cid; /* * No action needed if there's already a CID allocated, e.g. in * the case of a fixed channel. */ if (ch->rx.cid > 0) { return ch; } for (cid = L2CAP_LE_CID_DYN_START; cid <= L2CAP_LE_CID_DYN_END; cid++) { if (!bt_l2cap_le_lookup_rx_cid(conn, cid)) { ch->rx.cid = cid; return ch; } } return NULL; } static struct bt_l2cap_le_chan * __l2cap_lookup_ident(struct bt_conn *conn, uint16_t ident, bool remove) { struct bt_l2cap_chan *chan; sys_snode_t *prev = NULL; SYS_SLIST_FOR_EACH_CONTAINER(&conn->channels, chan, node) { if (chan->ident == ident) { if (remove) { sys_slist_remove(&conn->channels, prev, &chan->node); } return BT_L2CAP_LE_CHAN(chan); } prev = &chan->node; } return NULL; } #endif /* CONFIG_BT_L2CAP_DYNAMIC_CHANNEL */ void bt_l2cap_chan_remove(struct bt_conn *conn, struct bt_l2cap_chan *ch) { struct bt_l2cap_chan *chan; sys_snode_t *prev = NULL; SYS_SLIST_FOR_EACH_CONTAINER(&conn->channels, chan, node) { if (chan == ch) { sys_slist_remove(&conn->channels, prev, &chan->node); return; } prev = &chan->node; } } const char *bt_l2cap_chan_state_str(bt_l2cap_chan_state_t state) { switch (state) { case BT_L2CAP_DISCONNECTED: return "disconnected"; case BT_L2CAP_CONNECT: return "connect"; case BT_L2CAP_CONFIG: return "config"; case BT_L2CAP_CONNECTED: return "connected"; case BT_L2CAP_DISCONNECT: return "disconnect"; default: return "unknown"; } } #if defined(CONFIG_BT_L2CAP_DYNAMIC_CHANNEL) #if defined(CONFIG_BT_DEBUG_L2CAP) void bt_l2cap_chan_set_state_debug(struct bt_l2cap_chan *chan, bt_l2cap_chan_state_t state, const char *func, int line) { BT_DBG("chan %p psm 0x%04x %s -> %s", chan, chan->psm, bt_l2cap_chan_state_str(chan->state), bt_l2cap_chan_state_str(state)); /* check transitions validness */ switch (state) { case BT_L2CAP_DISCONNECTED: /* regardless of old state always allows this state */ break; case BT_L2CAP_CONNECT: if (chan->state != BT_L2CAP_DISCONNECTED) { BT_WARN("%s()%d: invalid transition", func, line); } break; case BT_L2CAP_CONFIG: if (chan->state != BT_L2CAP_CONNECT) { BT_WARN("%s()%d: invalid transition", func, line); } break; case BT_L2CAP_CONNECTED: if (chan->state != BT_L2CAP_CONFIG && chan->state != BT_L2CAP_CONNECT) { BT_WARN("%s()%d: invalid transition", func, line); } break; case BT_L2CAP_DISCONNECT: if (chan->state != BT_L2CAP_CONFIG && chan->state != BT_L2CAP_CONNECTED) { BT_WARN("%s()%d: invalid transition", func, line); } break; default: BT_ERR("%s()%d: unknown (%u) state was set", func, line, state); return; } chan->state = state; } #else void bt_l2cap_chan_set_state(struct bt_l2cap_chan *chan, bt_l2cap_chan_state_t state) { chan->state = state; } #endif /* CONFIG_BT_DEBUG_L2CAP */ #endif /* CONFIG_BT_L2CAP_DYNAMIC_CHANNEL */ void bt_l2cap_chan_del(struct bt_l2cap_chan *chan) { const struct bt_l2cap_chan_ops *ops = chan->ops; BT_DBG("conn %p chan %p", chan->conn, chan); if (!chan->conn) { goto destroy; } if (ops->disconnected) { ops->disconnected(chan); } chan->conn = NULL; destroy: #if defined(CONFIG_BT_L2CAP_DYNAMIC_CHANNEL) /* Reset internal members of common channel */ bt_l2cap_chan_set_state(chan, BT_L2CAP_DISCONNECTED); chan->psm = 0U; #endif if (chan->destroy) { chan->destroy(chan); } if (ops->released) { ops->released(chan); } } static void l2cap_rtx_timeout(struct k_work *work) { struct bt_l2cap_le_chan *chan = LE_CHAN_RTX(work); struct bt_conn *conn = chan->chan.conn; BT_ERR("chan %p timeout", chan); bt_l2cap_chan_remove(conn, &chan->chan); bt_l2cap_chan_del(&chan->chan); #if defined(CONFIG_BT_L2CAP_DYNAMIC_CHANNEL) /* Remove other channels if pending on the same ident */ while ((chan = l2cap_remove_ident(conn, chan->chan.ident))) { bt_l2cap_chan_del(&chan->chan); } #endif /* CONFIG_BT_L2CAP_DYNAMIC_CHANNEL */ } #if defined(CONFIG_BT_L2CAP_DYNAMIC_CHANNEL) static void l2cap_chan_le_recv(struct bt_l2cap_le_chan *chan, struct net_buf *buf); static void l2cap_rx_process(struct k_work *work) { struct bt_l2cap_le_chan *ch = CHAN_RX(work); struct net_buf *buf; while ((buf = net_buf_get(&ch->rx_queue, K_NO_WAIT))) { BT_DBG("ch %p buf %p", ch, buf); l2cap_chan_le_recv(ch, buf); net_buf_unref(buf); } } #endif /* CONFIG_BT_L2CAP_DYNAMIC_CHANNEL */ void bt_l2cap_chan_add(struct bt_conn *conn, struct bt_l2cap_chan *chan, bt_l2cap_chan_destroy_t destroy) { /* Attach channel to the connection */ sys_slist_append(&conn->channels, &chan->node); chan->conn = conn; chan->destroy = destroy; BT_DBG("conn %p chan %p", conn, chan); } static bool l2cap_chan_add(struct bt_conn *conn, struct bt_l2cap_chan *chan, bt_l2cap_chan_destroy_t destroy) { struct bt_l2cap_le_chan *ch; #if defined(CONFIG_BT_L2CAP_DYNAMIC_CHANNEL) ch = l2cap_chan_alloc_cid(conn, chan); #else ch = BT_L2CAP_LE_CHAN(chan); #endif if (!ch) { BT_ERR("Unable to allocate L2CAP CID"); return false; } k_delayed_work_init(&chan->rtx_work, l2cap_rtx_timeout); atomic_clear(chan->status); bt_l2cap_chan_add(conn, chan, destroy); #if defined(CONFIG_BT_L2CAP_DYNAMIC_CHANNEL) if (L2CAP_LE_CID_IS_DYN(ch->rx.cid)) { k_work_init(&ch->rx_work, l2cap_rx_process); k_fifo_init(&ch->rx_queue); bt_l2cap_chan_set_state(chan, BT_L2CAP_CONNECT); } #endif /* CONFIG_BT_L2CAP_DYNAMIC_CHANNEL */ return true; } void bt_l2cap_connected(struct bt_conn *conn) { struct bt_l2cap_chan *chan; if (IS_ENABLED(CONFIG_BT_BREDR) && conn->type == BT_CONN_TYPE_BR) { bt_l2cap_br_connected(conn); return; } Z_STRUCT_SECTION_FOREACH(bt_l2cap_fixed_chan, fchan) { struct bt_l2cap_le_chan *ch; if (fchan->accept(conn, &chan) < 0) { continue; } ch = BT_L2CAP_LE_CHAN(chan); /* Fill up remaining fixed channel context attached in * fchan->accept() */ ch->rx.cid = fchan->cid; ch->tx.cid = fchan->cid; if (!l2cap_chan_add(conn, chan, fchan->destroy)) { return; } if (chan->ops->connected) { chan->ops->connected(chan); } /* Always set output status to fixed channels */ atomic_set_bit(chan->status, BT_L2CAP_STATUS_OUT); if (chan->ops->status) { chan->ops->status(chan, chan->status); } } } void bt_l2cap_disconnected(struct bt_conn *conn) { struct bt_l2cap_chan *chan, *next; SYS_SLIST_FOR_EACH_CONTAINER_SAFE(&conn->channels, chan, next, node) { bt_l2cap_chan_del(chan); } } static struct net_buf *l2cap_create_le_sig_pdu(struct net_buf *buf, uint8_t code, uint8_t ident, uint16_t len) { struct bt_l2cap_sig_hdr *hdr; struct net_buf_pool *pool = NULL; if (code == BT_L2CAP_DISCONN_REQ) { pool = &disc_pool; } /* Don't wait more than the minimum RTX timeout of 2 seconds */ buf = bt_l2cap_create_pdu_timeout(pool, 0, L2CAP_RTX_TIMEOUT); if (!buf) { /* If it was not possible to allocate a buffer within the * timeout return NULL. */ BT_ERR("Unable to allocate buffer for op 0x%02x", code); return NULL; } hdr = net_buf_add(buf, sizeof(*hdr)); hdr->code = code; hdr->ident = ident; hdr->len = sys_cpu_to_le16(len); return buf; } #if defined(CONFIG_BT_L2CAP_DYNAMIC_CHANNEL) static void l2cap_chan_send_req(struct bt_l2cap_chan *chan, struct net_buf *buf, k_timeout_t timeout) { /* BLUETOOTH SPECIFICATION Version 4.2 [Vol 3, Part A] page 126: * * The value of this timer is implementation-dependent but the minimum * initial value is 1 second and the maximum initial value is 60 * seconds. One RTX timer shall exist for each outstanding signaling * request, including each Echo Request. The timer disappears on the * final expiration, when the response is received, or the physical * link is lost. */ k_delayed_work_submit(&chan->rtx_work, timeout); bt_l2cap_send(chan->conn, BT_L2CAP_CID_LE_SIG, buf); } static int l2cap_le_conn_req(struct bt_l2cap_le_chan *ch) { struct net_buf *buf; struct bt_l2cap_le_conn_req *req; ch->chan.ident = get_ident(); buf = l2cap_create_le_sig_pdu(NULL, BT_L2CAP_LE_CONN_REQ, ch->chan.ident, sizeof(*req)); if (!buf) { return -ENOMEM; } req = net_buf_add(buf, sizeof(*req)); req->psm = sys_cpu_to_le16(ch->chan.psm); req->scid = sys_cpu_to_le16(ch->rx.cid); req->mtu = sys_cpu_to_le16(ch->rx.mtu); req->mps = sys_cpu_to_le16(ch->rx.mps); req->credits = sys_cpu_to_le16(ch->rx.init_credits); l2cap_chan_send_req(&ch->chan, buf, L2CAP_CONN_TIMEOUT); return 0; } static int l2cap_ecred_conn_req(struct bt_l2cap_chan **chan, int channels) { struct net_buf *buf; struct bt_l2cap_ecred_conn_req *req; struct bt_l2cap_le_chan *ch; int i; uint8_t ident; if (!chan || !channels) { return -EINVAL; } ident = get_ident(); buf = l2cap_create_le_sig_pdu(NULL, BT_L2CAP_ECRED_CONN_REQ, ident, sizeof(*req) + (channels * sizeof(uint16_t))); req = net_buf_add(buf, sizeof(*req)); ch = BT_L2CAP_LE_CHAN(chan[0]); /* Init common parameters */ req->psm = sys_cpu_to_le16(ch->chan.psm); req->mtu = sys_cpu_to_le16(ch->rx.mtu); req->mps = sys_cpu_to_le16(ch->rx.mps); req->credits = sys_cpu_to_le16(ch->rx.init_credits); for (i = 0; i < channels; i++) { ch = BT_L2CAP_LE_CHAN(chan[i]); ch->chan.ident = ident; net_buf_add_le16(buf, ch->rx.cid); } l2cap_chan_send_req(*chan, buf, L2CAP_CONN_TIMEOUT); return 0; } static void l2cap_le_encrypt_change(struct bt_l2cap_chan *chan, uint8_t status) { /* Skip channels that are not pending waiting for encryption */ if (!atomic_test_and_clear_bit(chan->status, BT_L2CAP_STATUS_ENCRYPT_PENDING)) { return; } if (status) { bt_l2cap_chan_remove(chan->conn, chan); bt_l2cap_chan_del(chan); return; } if (chan->ident) { struct bt_l2cap_chan *echan[L2CAP_ECRED_CHAN_MAX]; struct bt_l2cap_le_chan *ch; int i = 0; while ((ch = l2cap_remove_ident(chan->conn, chan->ident))) { echan[i++] = &ch->chan; } /* Retry ecred connect */ l2cap_ecred_conn_req(echan, i); return; } /* Retry to connect */ l2cap_le_conn_req(BT_L2CAP_LE_CHAN(chan)); } #endif /* CONFIG_BT_L2CAP_DYNAMIC_CHANNEL */ void bt_l2cap_encrypt_change(struct bt_conn *conn, uint8_t hci_status) { struct bt_l2cap_chan *chan; if (IS_ENABLED(CONFIG_BT_BREDR) && conn->type == BT_CONN_TYPE_BR) { l2cap_br_encrypt_change(conn, hci_status); return; } SYS_SLIST_FOR_EACH_CONTAINER(&conn->channels, chan, node) { #if defined(CONFIG_BT_L2CAP_DYNAMIC_CHANNEL) l2cap_le_encrypt_change(chan, hci_status); #endif if (chan->ops->encrypt_change) { chan->ops->encrypt_change(chan, hci_status); } } } struct net_buf *bt_l2cap_create_pdu_timeout(struct net_buf_pool *pool, size_t reserve, k_timeout_t timeout) { return bt_conn_create_pdu_timeout(pool, sizeof(struct bt_l2cap_hdr) + reserve, timeout); } int bt_l2cap_send_cb(struct bt_conn *conn, uint16_t cid, struct net_buf *buf, bt_conn_tx_cb_t cb, void *user_data) { struct bt_l2cap_hdr *hdr; BT_DBG("conn %p cid %u len %zu", conn, cid, net_buf_frags_len(buf)); hdr = net_buf_push(buf, sizeof(*hdr)); hdr->len = sys_cpu_to_le16(buf->len - sizeof(*hdr)); hdr->cid = sys_cpu_to_le16(cid); return bt_conn_send_cb(conn, buf, cb, user_data); } static void l2cap_send_reject(struct bt_conn *conn, uint8_t ident, uint16_t reason, void *data, uint8_t data_len) { struct bt_l2cap_cmd_reject *rej; struct net_buf *buf; buf = l2cap_create_le_sig_pdu(NULL, BT_L2CAP_CMD_REJECT, ident, sizeof(*rej) + data_len); if (!buf) { return; } rej = net_buf_add(buf, sizeof(*rej)); rej->reason = sys_cpu_to_le16(reason); if (data) { net_buf_add_mem(buf, data, data_len); } bt_l2cap_send(conn, BT_L2CAP_CID_LE_SIG, buf); } static void le_conn_param_rsp(struct bt_l2cap *l2cap, struct net_buf *buf) { struct bt_l2cap_conn_param_rsp *rsp = (void *)buf->data; if (buf->len < sizeof(*rsp)) { BT_ERR("Too small LE conn param rsp"); return; } BT_DBG("LE conn param rsp result %u", sys_le16_to_cpu(rsp->result)); } static void le_conn_param_update_req(struct bt_l2cap *l2cap, uint8_t ident, struct net_buf *buf) { struct bt_conn *conn = l2cap->chan.chan.conn; struct bt_le_conn_param param; struct bt_l2cap_conn_param_rsp *rsp; struct bt_l2cap_conn_param_req *req = (void *)buf->data; bool accepted; if (buf->len < sizeof(*req)) { BT_ERR("Too small LE conn update param req"); return; } if (conn->role != BT_HCI_ROLE_MASTER) { l2cap_send_reject(conn, ident, BT_L2CAP_REJ_NOT_UNDERSTOOD, NULL, 0); return; } param.interval_min = sys_le16_to_cpu(req->min_interval); param.interval_max = sys_le16_to_cpu(req->max_interval); param.latency = sys_le16_to_cpu(req->latency); param.timeout = sys_le16_to_cpu(req->timeout); BT_DBG("min 0x%04x max 0x%04x latency: 0x%04x timeout: 0x%04x", param.interval_min, param.interval_max, param.latency, param.timeout); buf = l2cap_create_le_sig_pdu(buf, BT_L2CAP_CONN_PARAM_RSP, ident, sizeof(*rsp)); if (!buf) { return; } accepted = le_param_req(conn, &param); rsp = net_buf_add(buf, sizeof(*rsp)); if (accepted) { rsp->result = sys_cpu_to_le16(BT_L2CAP_CONN_PARAM_ACCEPTED); } else { rsp->result = sys_cpu_to_le16(BT_L2CAP_CONN_PARAM_REJECTED); } bt_l2cap_send(conn, BT_L2CAP_CID_LE_SIG, buf); if (accepted) { bt_conn_le_conn_update(conn, &param); } } struct bt_l2cap_chan *bt_l2cap_le_lookup_tx_cid(struct bt_conn *conn, uint16_t cid) { struct bt_l2cap_chan *chan; SYS_SLIST_FOR_EACH_CONTAINER(&conn->channels, chan, node) { if (BT_L2CAP_LE_CHAN(chan)->tx.cid == cid) { return chan; } } return NULL; } struct bt_l2cap_chan *bt_l2cap_le_lookup_rx_cid(struct bt_conn *conn, uint16_t cid) { struct bt_l2cap_chan *chan; SYS_SLIST_FOR_EACH_CONTAINER(&conn->channels, chan, node) { if (BT_L2CAP_LE_CHAN(chan)->rx.cid == cid) { return chan; } } return NULL; } #if defined(CONFIG_BT_L2CAP_DYNAMIC_CHANNEL) static struct bt_l2cap_server *l2cap_server_lookup_psm(uint16_t psm) { struct bt_l2cap_server *server; SYS_SLIST_FOR_EACH_CONTAINER(&servers, server, node) { if (server->psm == psm) { return server; } } return NULL; } int bt_l2cap_server_register(struct bt_l2cap_server *server) { if (!server->accept) { return -EINVAL; } if (server->psm) { if (server->psm < L2CAP_LE_PSM_FIXED_START || server->psm > L2CAP_LE_PSM_DYN_END) { return -EINVAL; } /* Check if given PSM is already in use */ if (l2cap_server_lookup_psm(server->psm)) { BT_DBG("PSM already registered"); return -EADDRINUSE; } } else { uint16_t psm; for (psm = L2CAP_LE_PSM_DYN_START; psm <= L2CAP_LE_PSM_DYN_END; psm++) { if (!l2cap_server_lookup_psm(psm)) { break; } } if (psm > L2CAP_LE_PSM_DYN_END) { BT_WARN("No free dynamic PSMs available"); return -EADDRNOTAVAIL; } BT_DBG("Allocated PSM 0x%04x for new server", psm); server->psm = psm; } if (server->sec_level > BT_SECURITY_L4) { return -EINVAL; } else if (server->sec_level < BT_SECURITY_L1) { /* Level 0 is only applicable for BR/EDR */ server->sec_level = BT_SECURITY_L1; } BT_DBG("PSM 0x%04x", server->psm); sys_slist_append(&servers, &server->node); return 0; } static void l2cap_chan_rx_init(struct bt_l2cap_le_chan *chan) { BT_DBG("chan %p", chan); /* Use existing MTU if defined */ if (!chan->rx.mtu) { chan->rx.mtu = L2CAP_MAX_LE_MTU; } /* Use existing credits if defined */ if (!chan->rx.init_credits) { if (chan->chan.ops->alloc_buf) { /* Auto tune credits to receive a full packet */ chan->rx.init_credits = (chan->rx.mtu + (L2CAP_MAX_LE_MPS - 1)) / L2CAP_MAX_LE_MPS; } else { chan->rx.init_credits = L2CAP_LE_MAX_CREDITS; } } /* MPS shall not be bigger than MTU + 2 as the remaining bytes cannot * be used. */ chan->rx.mps = MIN(chan->rx.mtu + 2, L2CAP_MAX_LE_MPS); atomic_set(&chan->rx.credits, 0); if (BT_DBG_ENABLED && chan->rx.init_credits * chan->rx.mps < chan->rx.mtu + 2) { BT_WARN("Not enough credits for a full packet"); } } static struct net_buf *l2cap_chan_le_get_tx_buf(struct bt_l2cap_le_chan *ch) { struct net_buf *buf; /* Return current buffer */ if (ch->tx_buf) { buf = ch->tx_buf; ch->tx_buf = NULL; return buf; } return net_buf_get(&ch->tx_queue, K_NO_WAIT); } static int l2cap_chan_le_send_sdu(struct bt_l2cap_le_chan *ch, struct net_buf **buf, uint16_t sent); static void l2cap_chan_tx_process(struct k_work *work) { struct bt_l2cap_le_chan *ch; struct net_buf *buf; ch = CONTAINER_OF(work, struct bt_l2cap_le_chan, tx_work); /* Resume tx in case there are buffers in the queue */ while ((buf = l2cap_chan_le_get_tx_buf(ch))) { int sent = data_sent(buf)->len; BT_DBG("buf %p sent %u", buf, sent); sent = l2cap_chan_le_send_sdu(ch, &buf, sent); if (sent < 0) { if (sent == -EAGAIN) { ch->tx_buf = buf; } break; } } } static void l2cap_chan_tx_init(struct bt_l2cap_le_chan *chan) { BT_DBG("chan %p", chan); (void)memset(&chan->tx, 0, sizeof(chan->tx)); atomic_set(&chan->tx.credits, 0); k_fifo_init(&chan->tx_queue); k_work_init(&chan->tx_work, l2cap_chan_tx_process); } static void l2cap_chan_tx_give_credits(struct bt_l2cap_le_chan *chan, uint16_t credits) { BT_DBG("chan %p credits %u", chan, credits); atomic_add(&chan->tx.credits, credits); if (!atomic_test_and_set_bit(chan->chan.status, BT_L2CAP_STATUS_OUT) && chan->chan.ops->status) { chan->chan.ops->status(&chan->chan, chan->chan.status); } } static void l2cap_chan_rx_give_credits(struct bt_l2cap_le_chan *chan, uint16_t credits) { BT_DBG("chan %p credits %u", chan, credits); atomic_add(&chan->rx.credits, credits); } static void l2cap_chan_destroy(struct bt_l2cap_chan *chan) { struct bt_l2cap_le_chan *ch = BT_L2CAP_LE_CHAN(chan); struct net_buf *buf; BT_DBG("chan %p cid 0x%04x", ch, ch->rx.cid); /* Cancel ongoing work */ k_delayed_work_cancel(&chan->rtx_work); if (ch->tx_buf) { net_buf_unref(ch->tx_buf); ch->tx_buf = NULL; } /* Remove buffers on the TX queue */ while ((buf = net_buf_get(&ch->tx_queue, K_NO_WAIT))) { net_buf_unref(buf); } /* Remove buffers on the RX queue */ while ((buf = net_buf_get(&ch->rx_queue, K_NO_WAIT))) { net_buf_unref(buf); } /* Destroy segmented SDU if it exists */ if (ch->_sdu) { net_buf_unref(ch->_sdu); ch->_sdu = NULL; ch->_sdu_len = 0U; } } static uint16_t le_err_to_result(int err) { switch (err) { case -ENOMEM: return BT_L2CAP_LE_ERR_NO_RESOURCES; case -EACCES: return BT_L2CAP_LE_ERR_AUTHORIZATION; case -EPERM: return BT_L2CAP_LE_ERR_KEY_SIZE; case -ENOTSUP: /* This handle the cases where a fixed channel is registered but * for some reason (e.g. controller not suporting a feature) * cannot be used. */ return BT_L2CAP_LE_ERR_PSM_NOT_SUPP; default: return BT_L2CAP_LE_ERR_UNACCEPT_PARAMS; } } static uint16_t l2cap_chan_accept(struct bt_conn *conn, struct bt_l2cap_server *server, uint16_t scid, uint16_t mtu, uint16_t mps, uint16_t credits, struct bt_l2cap_chan **chan) { struct bt_l2cap_le_chan *ch; int err; BT_DBG("conn %p scid 0x%04x chan %p", conn, scid, chan); if (!L2CAP_LE_CID_IS_DYN(scid)) { return BT_L2CAP_LE_ERR_INVALID_SCID; } *chan = bt_l2cap_le_lookup_tx_cid(conn, scid); if (*chan) { return BT_L2CAP_LE_ERR_SCID_IN_USE; } /* Request server to accept the new connection and allocate the * channel. */ err = server->accept(conn, chan); if (err < 0) { return le_err_to_result(err); } (*chan)->required_sec_level = server->sec_level; if (!l2cap_chan_add(conn, *chan, l2cap_chan_destroy)) { return BT_L2CAP_LE_ERR_NO_RESOURCES; } ch = BT_L2CAP_LE_CHAN(*chan); /* Init TX parameters */ l2cap_chan_tx_init(ch); ch->tx.cid = scid; ch->tx.mps = mps; ch->tx.mtu = mtu; ch->tx.init_credits = credits; l2cap_chan_tx_give_credits(ch, credits); /* Init RX parameters */ l2cap_chan_rx_init(ch); l2cap_chan_rx_give_credits(ch, ch->rx.init_credits); /* Set channel PSM */ (*chan)->psm = server->psm; /* Update state */ bt_l2cap_chan_set_state(*chan, BT_L2CAP_CONNECTED); if ((*chan)->ops->connected) { (*chan)->ops->connected(*chan); } return BT_L2CAP_LE_SUCCESS; } static void le_conn_req(struct bt_l2cap *l2cap, uint8_t ident, struct net_buf *buf) { struct bt_conn *conn = l2cap->chan.chan.conn; struct bt_l2cap_chan *chan; struct bt_l2cap_le_chan *ch; struct bt_l2cap_server *server; struct bt_l2cap_le_conn_req *req = (void *)buf->data; struct bt_l2cap_le_conn_rsp *rsp; uint16_t psm, scid, mtu, mps, credits; uint16_t result; if (buf->len < sizeof(*req)) { BT_ERR("Too small LE conn req packet size"); return; } psm = sys_le16_to_cpu(req->psm); scid = sys_le16_to_cpu(req->scid); mtu = sys_le16_to_cpu(req->mtu); mps = sys_le16_to_cpu(req->mps); credits = sys_le16_to_cpu(req->credits); BT_DBG("psm 0x%02x scid 0x%04x mtu %u mps %u credits %u", psm, scid, mtu, mps, credits); if (mtu < L2CAP_LE_MIN_MTU || mps < L2CAP_LE_MIN_MTU) { BT_ERR("Invalid LE-Conn Req params"); return; } buf = l2cap_create_le_sig_pdu(buf, BT_L2CAP_LE_CONN_RSP, ident, sizeof(*rsp)); if (!buf) { return; } rsp = net_buf_add(buf, sizeof(*rsp)); (void)memset(rsp, 0, sizeof(*rsp)); /* Check if there is a server registered */ server = l2cap_server_lookup_psm(psm); if (!server) { rsp->result = sys_cpu_to_le16(BT_L2CAP_LE_ERR_PSM_NOT_SUPP); goto rsp; } /* Check if connection has minimum required security level */ if (conn->sec_level < server->sec_level) { rsp->result = sys_cpu_to_le16(BT_L2CAP_LE_ERR_AUTHENTICATION); goto rsp; } result = l2cap_chan_accept(conn, server, scid, mtu, mps, credits, &chan); if (result != BT_L2CAP_LE_SUCCESS) { rsp->result = sys_cpu_to_le16(result); goto rsp; } ch = BT_L2CAP_LE_CHAN(chan); /* Prepare response protocol data */ rsp->dcid = sys_cpu_to_le16(ch->rx.cid); rsp->mps = sys_cpu_to_le16(ch->rx.mps); rsp->mtu = sys_cpu_to_le16(ch->rx.mtu); rsp->credits = sys_cpu_to_le16(ch->rx.init_credits); rsp->result = BT_L2CAP_LE_SUCCESS; rsp: bt_l2cap_send(conn, BT_L2CAP_CID_LE_SIG, buf); } static void le_ecred_conn_req(struct bt_l2cap *l2cap, uint8_t ident, struct net_buf *buf) { struct bt_conn *conn = l2cap->chan.chan.conn; struct bt_l2cap_chan *chan[L2CAP_ECRED_CHAN_MAX]; struct bt_l2cap_le_chan *ch = NULL; struct bt_l2cap_server *server; struct bt_l2cap_ecred_conn_req *req; struct bt_l2cap_ecred_conn_rsp *rsp; uint16_t psm, mtu, mps, credits, result = BT_L2CAP_LE_ERR_INVALID_SCID; uint16_t scid, dcid[L2CAP_ECRED_CHAN_MAX]; int i = 0; if (buf->len < sizeof(*req)) { BT_ERR("Too small LE conn req packet size"); result = BT_L2CAP_LE_ERR_INVALID_PARAMS; goto response; } req = net_buf_pull_mem(buf, sizeof(*req)); psm = sys_le16_to_cpu(req->psm); mtu = sys_le16_to_cpu(req->mtu); mps = sys_le16_to_cpu(req->mps); credits = sys_le16_to_cpu(req->credits); BT_DBG("psm 0x%02x mtu %u mps %u credits %u", psm, mtu, mps, credits); if (mtu < L2CAP_ECRED_MIN_MTU || mps < L2CAP_ECRED_MIN_MTU) { BT_ERR("Invalid ecred conn req params"); result = BT_L2CAP_LE_ERR_UNACCEPT_PARAMS; goto response; } /* Check if there is a server registered */ server = l2cap_server_lookup_psm(psm); if (!server) { result = BT_L2CAP_LE_ERR_PSM_NOT_SUPP; goto response; } /* Check if connection has minimum required security level */ if (conn->sec_level < server->sec_level) { result = BT_L2CAP_LE_ERR_AUTHENTICATION; goto response; } while (buf->len >= sizeof(scid)) { scid = net_buf_pull_le16(buf); result = l2cap_chan_accept(conn, server, scid, mtu, mps, credits, &chan[i]); switch (result) { case BT_L2CAP_LE_SUCCESS: ch = BT_L2CAP_LE_CHAN(chan[i]); dcid[i++] = sys_cpu_to_le16(ch->rx.cid); continue; /* Some connections refused – invalid Source CID */ case BT_L2CAP_LE_ERR_INVALID_SCID: /* Some connections refused – Source CID already allocated */ case BT_L2CAP_LE_ERR_SCID_IN_USE: /* If a Destination CID is 0x0000, the channel was not * established. */ dcid[i++] = 0x0000; continue; /* Some connections refused – not enough resources * available. */ case BT_L2CAP_LE_ERR_NO_RESOURCES: default: goto response; } } response: if (!i) { i = buf->len / sizeof(scid); } buf = l2cap_create_le_sig_pdu(buf, BT_L2CAP_ECRED_CONN_RSP, ident, sizeof(*rsp) + (sizeof(scid) * i)); rsp = net_buf_add(buf, sizeof(*rsp)); (void)memset(rsp, 0, sizeof(*rsp)); if (result == BT_L2CAP_LE_ERR_UNACCEPT_PARAMS || result == BT_L2CAP_LE_ERR_PSM_NOT_SUPP || result == BT_L2CAP_LE_ERR_AUTHENTICATION) { memset(dcid, 0, sizeof(scid) * i); } else if (ch) { rsp->mps = sys_cpu_to_le16(ch->rx.mps); rsp->mtu = sys_cpu_to_le16(ch->rx.mtu); rsp->credits = sys_cpu_to_le16(ch->rx.init_credits); } net_buf_add_mem(buf, dcid, sizeof(scid) * i); rsp->result = sys_cpu_to_le16(result); bt_l2cap_send(conn, BT_L2CAP_CID_LE_SIG, buf); } static void le_ecred_reconf_req(struct bt_l2cap *l2cap, uint8_t ident, struct net_buf *buf) { struct bt_conn *conn = l2cap->chan.chan.conn; struct bt_l2cap_ecred_reconf_req *req; struct bt_l2cap_ecred_reconf_rsp *rsp; uint16_t mtu, mps; uint16_t scid, result; if (buf->len < sizeof(*req)) { BT_ERR("Too small ecred reconf req packet size"); return; } req = net_buf_pull_mem(buf, sizeof(*req)); mtu = sys_le16_to_cpu(req->mtu); mps = sys_le16_to_cpu(req->mps); if (mtu < L2CAP_ECRED_MIN_MTU) { result = BT_L2CAP_RECONF_INVALID_MTU; goto response; } if (mps < L2CAP_ECRED_MIN_MTU) { result = BT_L2CAP_RECONF_INVALID_MTU; goto response; } while (buf->len >= sizeof(scid)) { struct bt_l2cap_chan *chan; scid = net_buf_pull_le16(buf); BT_DBG("scid 0x%04x", scid); if (!scid) { continue; } chan = bt_l2cap_le_lookup_tx_cid(conn, scid); if (!chan) { continue; } /* If the MTU value is decreased for any of the included * channels, then the receiver shall disconnect all * included channels. */ if (BT_L2CAP_LE_CHAN(chan)->tx.mtu > mtu) { BT_ERR("chan %p decreased MTU %u -> %u", chan, BT_L2CAP_LE_CHAN(chan)->tx.mtu, mtu); result = BT_L2CAP_RECONF_INVALID_MTU; bt_l2cap_chan_disconnect(chan); goto response; } BT_L2CAP_LE_CHAN(chan)->tx.mtu = mtu; BT_L2CAP_LE_CHAN(chan)->tx.mps = mps; } BT_DBG("mtu %u mps %u", mtu, mps); result = BT_L2CAP_RECONF_SUCCESS; response: buf = l2cap_create_le_sig_pdu(buf, BT_L2CAP_ECRED_RECONF_RSP, ident, sizeof(*rsp)); rsp = net_buf_add(buf, sizeof(*rsp)); rsp->result = sys_cpu_to_le16(result); bt_l2cap_send(conn, BT_L2CAP_CID_LE_SIG, buf); } static struct bt_l2cap_le_chan *l2cap_remove_rx_cid(struct bt_conn *conn, uint16_t cid) { struct bt_l2cap_chan *chan; sys_snode_t *prev = NULL; /* Protect fixed channels against accidental removal */ if (!L2CAP_LE_CID_IS_DYN(cid)) { return NULL; } SYS_SLIST_FOR_EACH_CONTAINER(&conn->channels, chan, node) { if (BT_L2CAP_LE_CHAN(chan)->rx.cid == cid) { sys_slist_remove(&conn->channels, prev, &chan->node); return BT_L2CAP_LE_CHAN(chan); } prev = &chan->node; } return NULL; } static void le_disconn_req(struct bt_l2cap *l2cap, uint8_t ident, struct net_buf *buf) { struct bt_conn *conn = l2cap->chan.chan.conn; struct bt_l2cap_le_chan *chan; struct bt_l2cap_disconn_req *req = (void *)buf->data; struct bt_l2cap_disconn_rsp *rsp; uint16_t dcid; if (buf->len < sizeof(*req)) { BT_ERR("Too small LE conn req packet size"); return; } dcid = sys_le16_to_cpu(req->dcid); BT_DBG("dcid 0x%04x scid 0x%04x", dcid, sys_le16_to_cpu(req->scid)); chan = l2cap_remove_rx_cid(conn, dcid); if (!chan) { struct bt_l2cap_cmd_reject_cid_data data; data.scid = req->scid; data.dcid = req->dcid; l2cap_send_reject(conn, ident, BT_L2CAP_REJ_INVALID_CID, &data, sizeof(data)); return; } buf = l2cap_create_le_sig_pdu(buf, BT_L2CAP_DISCONN_RSP, ident, sizeof(*rsp)); if (!buf) { return; } rsp = net_buf_add(buf, sizeof(*rsp)); rsp->dcid = sys_cpu_to_le16(chan->rx.cid); rsp->scid = sys_cpu_to_le16(chan->tx.cid); bt_l2cap_chan_del(&chan->chan); bt_l2cap_send(conn, BT_L2CAP_CID_LE_SIG, buf); } static int l2cap_change_security(struct bt_l2cap_le_chan *chan, uint16_t err) { int ret; if (atomic_test_bit(chan->chan.status, BT_L2CAP_STATUS_ENCRYPT_PENDING)) { return -EINPROGRESS; } switch (err) { case BT_L2CAP_LE_ERR_ENCRYPTION: if (chan->chan.required_sec_level >= BT_SECURITY_L2) { return -EALREADY; } chan->chan.required_sec_level = BT_SECURITY_L2; break; case BT_L2CAP_LE_ERR_AUTHENTICATION: if (chan->chan.required_sec_level < BT_SECURITY_L2) { chan->chan.required_sec_level = BT_SECURITY_L2; } else if (chan->chan.required_sec_level < BT_SECURITY_L3) { chan->chan.required_sec_level = BT_SECURITY_L3; } else if (chan->chan.required_sec_level < BT_SECURITY_L4) { chan->chan.required_sec_level = BT_SECURITY_L4; } else { return -EALREADY; } break; default: return -EINVAL; } ret = bt_conn_set_security(chan->chan.conn, chan->chan.required_sec_level); if (ret < 0) { return ret; } atomic_set_bit(chan->chan.status, BT_L2CAP_STATUS_ENCRYPT_PENDING); return 0; } static void le_ecred_conn_rsp(struct bt_l2cap *l2cap, uint8_t ident, struct net_buf *buf) { struct bt_conn *conn = l2cap->chan.chan.conn; struct bt_l2cap_le_chan *chan; struct bt_l2cap_ecred_conn_rsp *rsp; uint16_t dcid, mtu, mps, credits, result; if (buf->len < sizeof(*rsp)) { BT_ERR("Too small ecred conn rsp packet size"); return; } rsp = net_buf_pull_mem(buf, sizeof(*rsp)); mtu = sys_le16_to_cpu(rsp->mtu); mps = sys_le16_to_cpu(rsp->mps); credits = sys_le16_to_cpu(rsp->credits); result = sys_le16_to_cpu(rsp->result); BT_DBG("mtu 0x%04x mps 0x%04x credits 0x%04x result %u", mtu, mps, credits, result); switch (result) { case BT_L2CAP_LE_ERR_AUTHENTICATION: case BT_L2CAP_LE_ERR_ENCRYPTION: while ((chan = l2cap_lookup_ident(conn, ident))) { /* Cancel RTX work */ k_delayed_work_cancel(&chan->chan.rtx_work); /* If security needs changing wait it to be completed */ if (!l2cap_change_security(chan, result)) { return; } bt_l2cap_chan_remove(conn, &chan->chan); bt_l2cap_chan_del(&chan->chan); } break; case BT_L2CAP_LE_SUCCESS: /* Some connections refused – invalid Source CID */ case BT_L2CAP_LE_ERR_INVALID_SCID: /* Some connections refused – Source CID already allocated */ case BT_L2CAP_LE_ERR_SCID_IN_USE: /* Some connections refused – not enough resources available */ case BT_L2CAP_LE_ERR_NO_RESOURCES: while ((chan = l2cap_lookup_ident(conn, ident))) { struct bt_l2cap_chan *c; /* Cancel RTX work */ k_delayed_work_cancel(&chan->chan.rtx_work); dcid = net_buf_pull_le16(buf); BT_DBG("dcid 0x%04x", dcid); /* If a Destination CID is 0x0000, the channel was not * established. */ if (!dcid) { bt_l2cap_chan_remove(conn, &chan->chan); bt_l2cap_chan_del(&chan->chan); continue; } c = bt_l2cap_le_lookup_tx_cid(conn, dcid); if (c) { /* If a device receives a * L2CAP_CREDIT_BASED_CONNECTION_RSP packet * with an already assigned Destination CID, * then both the original channel and the new * channel shall be immediately discarded and * not used. */ bt_l2cap_chan_remove(conn, &chan->chan); bt_l2cap_chan_del(&chan->chan); bt_l2cap_chan_disconnect(c); continue; } chan->tx.cid = dcid; chan->chan.ident = 0U; chan->tx.mtu = mtu; chan->tx.mps = mps; /* Update state */ bt_l2cap_chan_set_state(&chan->chan, BT_L2CAP_CONNECTED); if (chan->chan.ops->connected) { chan->chan.ops->connected(&chan->chan); } /* Give credits */ l2cap_chan_tx_give_credits(chan, credits); l2cap_chan_rx_give_credits(chan, chan->rx.init_credits); } break; case BT_L2CAP_LE_ERR_PSM_NOT_SUPP: default: while ((chan = l2cap_remove_ident(conn, ident))) { bt_l2cap_chan_del(&chan->chan); } break; } } static void le_conn_rsp(struct bt_l2cap *l2cap, uint8_t ident, struct net_buf *buf) { struct bt_conn *conn = l2cap->chan.chan.conn; struct bt_l2cap_le_chan *chan; struct bt_l2cap_le_conn_rsp *rsp = (void *)buf->data; uint16_t dcid, mtu, mps, credits, result; if (buf->len < sizeof(*rsp)) { BT_ERR("Too small LE conn rsp packet size"); return; } dcid = sys_le16_to_cpu(rsp->dcid); mtu = sys_le16_to_cpu(rsp->mtu); mps = sys_le16_to_cpu(rsp->mps); credits = sys_le16_to_cpu(rsp->credits); result = sys_le16_to_cpu(rsp->result); BT_DBG("dcid 0x%04x mtu %u mps %u credits %u result 0x%04x", dcid, mtu, mps, credits, result); /* Keep the channel in case of security errors */ if (result == BT_L2CAP_LE_SUCCESS || result == BT_L2CAP_LE_ERR_AUTHENTICATION || result == BT_L2CAP_LE_ERR_ENCRYPTION) { chan = l2cap_lookup_ident(conn, ident); } else { chan = l2cap_remove_ident(conn, ident); } if (!chan) { BT_ERR("Cannot find channel for ident %u", ident); return; } /* Cancel RTX work */ k_delayed_work_cancel(&chan->chan.rtx_work); /* Reset ident since it got a response */ chan->chan.ident = 0U; switch (result) { case BT_L2CAP_LE_SUCCESS: chan->tx.cid = dcid; chan->tx.mtu = mtu; chan->tx.mps = mps; /* Update state */ bt_l2cap_chan_set_state(&chan->chan, BT_L2CAP_CONNECTED); if (chan->chan.ops->connected) { chan->chan.ops->connected(&chan->chan); } /* Give credits */ l2cap_chan_tx_give_credits(chan, credits); l2cap_chan_rx_give_credits(chan, chan->rx.init_credits); break; case BT_L2CAP_LE_ERR_AUTHENTICATION: case BT_L2CAP_LE_ERR_ENCRYPTION: /* If security needs changing wait it to be completed */ if (l2cap_change_security(chan, result) == 0) { return; } bt_l2cap_chan_remove(conn, &chan->chan); default: bt_l2cap_chan_del(&chan->chan); } } static void le_disconn_rsp(struct bt_l2cap *l2cap, uint8_t ident, struct net_buf *buf) { struct bt_conn *conn = l2cap->chan.chan.conn; struct bt_l2cap_le_chan *chan; struct bt_l2cap_disconn_rsp *rsp = (void *)buf->data; uint16_t scid; if (buf->len < sizeof(*rsp)) { BT_ERR("Too small LE disconn rsp packet size"); return; } scid = sys_le16_to_cpu(rsp->scid); BT_DBG("dcid 0x%04x scid 0x%04x", sys_le16_to_cpu(rsp->dcid), scid); chan = l2cap_remove_rx_cid(conn, scid); if (!chan) { return; } bt_l2cap_chan_del(&chan->chan); } static inline struct net_buf *l2cap_alloc_seg(struct net_buf *buf) { struct net_buf_pool *pool = net_buf_pool_get(buf->pool_id); struct net_buf *seg; /* Try to use original pool if possible */ seg = net_buf_alloc(pool, K_NO_WAIT); if (seg) { net_buf_reserve(seg, BT_L2CAP_CHAN_SEND_RESERVE); return seg; } /* Fallback to using global connection tx pool */ return bt_l2cap_create_pdu_timeout(NULL, 0, K_NO_WAIT); } static struct net_buf *l2cap_chan_create_seg(struct bt_l2cap_le_chan *ch, struct net_buf *buf, size_t sdu_hdr_len) { struct net_buf *seg; uint16_t headroom; uint16_t len; /* Segment if data (+ data headroom) is bigger than MPS */ if (buf->len + sdu_hdr_len > ch->tx.mps) { goto segment; } headroom = BT_L2CAP_CHAN_SEND_RESERVE + sdu_hdr_len; /* Check if original buffer has enough headroom and don't have any * fragments. */ if (net_buf_headroom(buf) >= headroom && !buf->frags) { if (sdu_hdr_len) { /* Push SDU length if set */ net_buf_push_le16(buf, net_buf_frags_len(buf)); } return net_buf_ref(buf); } segment: seg = l2cap_alloc_seg(buf); if (!seg) { return NULL; } if (sdu_hdr_len) { net_buf_add_le16(seg, net_buf_frags_len(buf)); } /* Don't send more that TX MPS including SDU length */ len = MIN(net_buf_tailroom(seg), ch->tx.mps - sdu_hdr_len); /* Limit if original buffer is smaller than the segment */ len = MIN(buf->len, len); net_buf_add_mem(seg, buf->data, len); net_buf_pull(buf, len); BT_DBG("ch %p seg %p len %u", ch, seg, seg->len); return seg; } static void l2cap_chan_tx_resume(struct bt_l2cap_le_chan *ch) { if (!atomic_get(&ch->tx.credits) || (k_fifo_is_empty(&ch->tx_queue) && !ch->tx_buf)) { return; } k_work_submit(&ch->tx_work); } static void l2cap_chan_sdu_sent(struct bt_conn *conn, void *user_data) { struct bt_l2cap_chan *chan = user_data; BT_DBG("conn %p chan %p", conn, chan); if (chan->ops->sent) { chan->ops->sent(chan); } l2cap_chan_tx_resume(BT_L2CAP_LE_CHAN(chan)); } static void l2cap_chan_seg_sent(struct bt_conn *conn, void *user_data) { struct bt_l2cap_chan *chan = user_data; BT_DBG("conn %p chan %p", conn, chan); l2cap_chan_tx_resume(BT_L2CAP_LE_CHAN(chan)); } static bool test_and_dec(atomic_t *target) { atomic_t old_value, new_value; do { old_value = atomic_get(target); if (!old_value) { return false; } new_value = old_value - 1; } while (atomic_cas(target, old_value, new_value) == 0); return true; } /* This returns -EAGAIN whenever a segment cannot be send immediately which can * happen under the following circuntances: * * 1. There are no credits * 2. There are no buffers * 3. There are no TX contexts * * In all cases the original buffer is unaffected so it can be pushed back to * be sent later. */ static int l2cap_chan_le_send(struct bt_l2cap_le_chan *ch, struct net_buf *buf, uint16_t sdu_hdr_len) { struct net_buf *seg; struct net_buf_simple_state state; int len, err; if (!test_and_dec(&ch->tx.credits)) { BT_WARN("No credits to transmit packet"); return -EAGAIN; } /* Save state so it can be restored if we failed to send */ net_buf_simple_save(&buf->b, &state); seg = l2cap_chan_create_seg(ch, buf, sdu_hdr_len); if (!seg) { atomic_inc(&ch->tx.credits); return -EAGAIN; } BT_DBG("ch %p cid 0x%04x len %u credits %u", ch, ch->tx.cid, seg->len, atomic_get(&ch->tx.credits)); len = seg->len - sdu_hdr_len; /* Set a callback if there is no data left in the buffer and sent * callback has been set. */ if ((buf == seg || !buf->len) && ch->chan.ops->sent) { err = bt_l2cap_send_cb(ch->chan.conn, ch->tx.cid, seg, l2cap_chan_sdu_sent, &ch->chan); } else { err = bt_l2cap_send_cb(ch->chan.conn, ch->tx.cid, seg, l2cap_chan_seg_sent, &ch->chan); } if (err) { BT_WARN("Unable to send seg %d", err); atomic_inc(&ch->tx.credits); if (err == -ENOBUFS) { /* Restore state since segment could not be sent */ net_buf_simple_restore(&buf->b, &state); return -EAGAIN; } return err; } /* Check if there is no credits left clear output status and notify its * change. */ if (!atomic_get(&ch->tx.credits)) { atomic_clear_bit(ch->chan.status, BT_L2CAP_STATUS_OUT); if (ch->chan.ops->status) { ch->chan.ops->status(&ch->chan, ch->chan.status); } } return len; } static int l2cap_chan_le_send_sdu(struct bt_l2cap_le_chan *ch, struct net_buf **buf, uint16_t sent) { int ret, total_len; struct net_buf *frag; total_len = net_buf_frags_len(*buf) + sent; if (total_len > ch->tx.mtu) { return -EMSGSIZE; } frag = *buf; if (!frag->len && frag->frags) { frag = frag->frags; } if (!sent) { /* Add SDU length for the first segment */ ret = l2cap_chan_le_send(ch, frag, BT_L2CAP_SDU_HDR_LEN); if (ret < 0) { if (ret == -EAGAIN) { /* Store sent data into user_data */ data_sent(frag)->len = sent; } *buf = frag; return ret; } sent = ret; } /* Send remaining segments */ for (ret = 0; sent < total_len; sent += ret) { /* Proceed to next fragment */ if (!frag->len) { frag = net_buf_frag_del(NULL, frag); } ret = l2cap_chan_le_send(ch, frag, 0); if (ret < 0) { if (ret == -EAGAIN) { /* Store sent data into user_data */ data_sent(frag)->len = sent; } *buf = frag; return ret; } } BT_DBG("ch %p cid 0x%04x sent %u total_len %u", ch, ch->tx.cid, sent, total_len); net_buf_unref(frag); return ret; } static void le_credits(struct bt_l2cap *l2cap, uint8_t ident, struct net_buf *buf) { struct bt_conn *conn = l2cap->chan.chan.conn; struct bt_l2cap_chan *chan; struct bt_l2cap_le_credits *ev = (void *)buf->data; struct bt_l2cap_le_chan *ch; uint16_t credits, cid; if (buf->len < sizeof(*ev)) { BT_ERR("Too small LE Credits packet size"); return; } cid = sys_le16_to_cpu(ev->cid); credits = sys_le16_to_cpu(ev->credits); BT_DBG("cid 0x%04x credits %u", cid, credits); chan = bt_l2cap_le_lookup_tx_cid(conn, cid); if (!chan) { BT_ERR("Unable to find channel of LE Credits packet"); return; } ch = BT_L2CAP_LE_CHAN(chan); if (atomic_get(&ch->tx.credits) + credits > UINT16_MAX) { BT_ERR("Credits overflow"); bt_l2cap_chan_disconnect(chan); return; } l2cap_chan_tx_give_credits(ch, credits); BT_DBG("chan %p total credits %u", ch, atomic_get(&ch->tx.credits)); l2cap_chan_tx_resume(ch); } static void reject_cmd(struct bt_l2cap *l2cap, uint8_t ident, struct net_buf *buf) { struct bt_conn *conn = l2cap->chan.chan.conn; struct bt_l2cap_le_chan *chan; /* Check if there is a outstanding channel */ chan = l2cap_remove_ident(conn, ident); if (!chan) { return; } bt_l2cap_chan_del(&chan->chan); } #endif /* CONFIG_BT_L2CAP_DYNAMIC_CHANNEL */ static int l2cap_recv(struct bt_l2cap_chan *chan, struct net_buf *buf) { struct bt_l2cap *l2cap = CONTAINER_OF(chan, struct bt_l2cap, chan); struct bt_l2cap_sig_hdr *hdr; uint16_t len; if (buf->len < sizeof(*hdr)) { BT_ERR("Too small L2CAP signaling PDU"); return 0; } hdr = net_buf_pull_mem(buf, sizeof(*hdr)); len = sys_le16_to_cpu(hdr->len); BT_DBG("Signaling code 0x%02x ident %u len %u", hdr->code, hdr->ident, len); if (buf->len != len) { BT_ERR("L2CAP length mismatch (%u != %u)", buf->len, len); return 0; } if (!hdr->ident) { BT_ERR("Invalid ident value in L2CAP PDU"); return 0; } switch (hdr->code) { case BT_L2CAP_CONN_PARAM_RSP: le_conn_param_rsp(l2cap, buf); break; #if defined(CONFIG_BT_L2CAP_DYNAMIC_CHANNEL) case BT_L2CAP_LE_CONN_REQ: le_conn_req(l2cap, hdr->ident, buf); break; case BT_L2CAP_LE_CONN_RSP: le_conn_rsp(l2cap, hdr->ident, buf); break; case BT_L2CAP_DISCONN_REQ: le_disconn_req(l2cap, hdr->ident, buf); break; case BT_L2CAP_DISCONN_RSP: le_disconn_rsp(l2cap, hdr->ident, buf); break; case BT_L2CAP_LE_CREDITS: le_credits(l2cap, hdr->ident, buf); break; case BT_L2CAP_CMD_REJECT: reject_cmd(l2cap, hdr->ident, buf); break; case BT_L2CAP_ECRED_CONN_REQ: le_ecred_conn_req(l2cap, hdr->ident, buf); break; case BT_L2CAP_ECRED_CONN_RSP: le_ecred_conn_rsp(l2cap, hdr->ident, buf); break; case BT_L2CAP_ECRED_RECONF_REQ: le_ecred_reconf_req(l2cap, hdr->ident, buf); break; #else case BT_L2CAP_CMD_REJECT: /* Ignored */ break; #endif /* CONFIG_BT_L2CAP_DYNAMIC_CHANNEL */ case BT_L2CAP_CONN_PARAM_REQ: if (IS_ENABLED(CONFIG_BT_CENTRAL)) { le_conn_param_update_req(l2cap, hdr->ident, buf); break; } /* Fall-through */ default: BT_WARN("Unknown L2CAP PDU code 0x%02x", hdr->code); l2cap_send_reject(chan->conn, hdr->ident, BT_L2CAP_REJ_NOT_UNDERSTOOD, NULL, 0); break; } return 0; } #if defined(CONFIG_BT_L2CAP_DYNAMIC_CHANNEL) static void l2cap_chan_shutdown(struct bt_l2cap_chan *chan) { struct bt_l2cap_le_chan *ch = BT_L2CAP_LE_CHAN(chan); struct net_buf *buf; BT_DBG("chan %p", chan); atomic_set_bit(chan->status, BT_L2CAP_STATUS_SHUTDOWN); /* Destroy segmented SDU if it exists */ if (ch->_sdu) { net_buf_unref(ch->_sdu); ch->_sdu = NULL; ch->_sdu_len = 0U; } /* Cleanup outstanding request */ if (ch->tx_buf) { net_buf_unref(ch->tx_buf); ch->tx_buf = NULL; } /* Remove buffers on the TX queue */ while ((buf = net_buf_get(&ch->tx_queue, K_NO_WAIT))) { net_buf_unref(buf); } /* Remove buffers on the RX queue */ while ((buf = net_buf_get(&ch->rx_queue, K_NO_WAIT))) { net_buf_unref(buf); } /* Update status */ if (chan->ops->status) { chan->ops->status(chan, chan->status); } } static void l2cap_chan_send_credits(struct bt_l2cap_le_chan *chan, struct net_buf *buf, uint16_t credits) { struct bt_l2cap_le_credits *ev; /* Cap the number of credits given */ if (credits > chan->rx.init_credits) { credits = chan->rx.init_credits; } buf = l2cap_create_le_sig_pdu(buf, BT_L2CAP_LE_CREDITS, get_ident(), sizeof(*ev)); if (!buf) { BT_ERR("Unable to send credits update"); /* Disconnect would probably not work either so the only * option left is to shutdown the channel. */ l2cap_chan_shutdown(&chan->chan); return; } l2cap_chan_rx_give_credits(chan, credits); ev = net_buf_add(buf, sizeof(*ev)); ev->cid = sys_cpu_to_le16(chan->rx.cid); ev->credits = sys_cpu_to_le16(credits); bt_l2cap_send(chan->chan.conn, BT_L2CAP_CID_LE_SIG, buf); BT_DBG("chan %p credits %u", chan, atomic_get(&chan->rx.credits)); } static void l2cap_chan_update_credits(struct bt_l2cap_le_chan *chan, struct net_buf *buf) { uint16_t credits; atomic_val_t old_credits = atomic_get(&chan->rx.credits); /* Restore enough credits to complete the sdu */ credits = ((chan->_sdu_len - net_buf_frags_len(buf)) + (chan->rx.mps - 1)) / chan->rx.mps; if (credits < old_credits) { return; } credits -= old_credits; l2cap_chan_send_credits(chan, buf, credits); } int bt_l2cap_chan_recv_complete(struct bt_l2cap_chan *chan, struct net_buf *buf) { struct bt_l2cap_le_chan *ch = BT_L2CAP_LE_CHAN(chan); struct bt_conn *conn = chan->conn; uint16_t credits; __ASSERT_NO_MSG(chan); __ASSERT_NO_MSG(buf); if (!conn) { return -ENOTCONN; } if (conn->type != BT_CONN_TYPE_LE) { return -ENOTSUP; } BT_DBG("chan %p buf %p", chan, buf); /* Restore credits used by packet */ memcpy(&credits, net_buf_user_data(buf), sizeof(credits)); l2cap_chan_send_credits(ch, buf, credits); net_buf_unref(buf); return 0; } static struct net_buf *l2cap_alloc_frag(k_timeout_t timeout, void *user_data) { struct bt_l2cap_le_chan *chan = user_data; struct net_buf *frag = NULL; frag = chan->chan.ops->alloc_buf(&chan->chan); if (!frag) { return NULL; } BT_DBG("frag %p tailroom %zu", frag, net_buf_tailroom(frag)); return frag; } static void l2cap_chan_le_recv_sdu(struct bt_l2cap_le_chan *chan, struct net_buf *buf, uint16_t seg) { int err; BT_DBG("chan %p len %zu", chan, net_buf_frags_len(buf)); /* Receiving complete SDU, notify channel and reset SDU buf */ err = chan->chan.ops->recv(&chan->chan, buf); if (err < 0) { if (err != -EINPROGRESS) { BT_ERR("err %d", err); bt_l2cap_chan_disconnect(&chan->chan); net_buf_unref(buf); } return; } l2cap_chan_send_credits(chan, buf, seg); net_buf_unref(buf); } static void l2cap_chan_le_recv_seg(struct bt_l2cap_le_chan *chan, struct net_buf *buf) { uint16_t len; uint16_t seg = 0U; len = net_buf_frags_len(chan->_sdu); if (len) { memcpy(&seg, net_buf_user_data(chan->_sdu), sizeof(seg)); } if (len + buf->len > chan->_sdu_len) { BT_ERR("SDU length mismatch"); bt_l2cap_chan_disconnect(&chan->chan); return; } seg++; /* Store received segments in user_data */ memcpy(net_buf_user_data(chan->_sdu), &seg, sizeof(seg)); BT_DBG("chan %p seg %d len %zu", chan, seg, net_buf_frags_len(buf)); /* Append received segment to SDU */ len = net_buf_append_bytes(chan->_sdu, buf->len, buf->data, K_NO_WAIT, l2cap_alloc_frag, chan); if (len != buf->len) { BT_ERR("Unable to store SDU"); bt_l2cap_chan_disconnect(&chan->chan); return; } if (net_buf_frags_len(chan->_sdu) < chan->_sdu_len) { /* Give more credits if remote has run out of them, this * should only happen if the remote cannot fully utilize the * MPS for some reason. */ if (!atomic_get(&chan->rx.credits) && seg == chan->rx.init_credits) { l2cap_chan_update_credits(chan, buf); } return; } buf = chan->_sdu; chan->_sdu = NULL; chan->_sdu_len = 0U; l2cap_chan_le_recv_sdu(chan, buf, seg); } static void l2cap_chan_le_recv(struct bt_l2cap_le_chan *chan, struct net_buf *buf) { uint16_t sdu_len; int err; if (!test_and_dec(&chan->rx.credits)) { BT_ERR("No credits to receive packet"); bt_l2cap_chan_disconnect(&chan->chan); return; } /* Check if segments already exist */ if (chan->_sdu) { l2cap_chan_le_recv_seg(chan, buf); return; } sdu_len = net_buf_pull_le16(buf); BT_DBG("chan %p len %u sdu_len %u", chan, buf->len, sdu_len); if (sdu_len > chan->rx.mtu) { BT_ERR("Invalid SDU length"); bt_l2cap_chan_disconnect(&chan->chan); return; } /* Always allocate buffer from the channel if supported. */ if (chan->chan.ops->alloc_buf) { chan->_sdu = chan->chan.ops->alloc_buf(&chan->chan); if (!chan->_sdu) { BT_ERR("Unable to allocate buffer for SDU"); bt_l2cap_chan_disconnect(&chan->chan); return; } chan->_sdu_len = sdu_len; l2cap_chan_le_recv_seg(chan, buf); return; } err = chan->chan.ops->recv(&chan->chan, buf); if (err) { if (err != -EINPROGRESS) { BT_ERR("err %d", err); bt_l2cap_chan_disconnect(&chan->chan); } return; } l2cap_chan_send_credits(chan, buf, 1); } static void l2cap_chan_recv_queue(struct bt_l2cap_le_chan *chan, struct net_buf *buf) { if (chan->chan.state == BT_L2CAP_DISCONNECT) { BT_WARN("Ignoring data received while disconnecting"); net_buf_unref(buf); return; } if (atomic_test_bit(chan->chan.status, BT_L2CAP_STATUS_SHUTDOWN)) { BT_WARN("Ignoring data received while channel has shutdown"); net_buf_unref(buf); return; } if (!L2CAP_LE_PSM_IS_DYN(chan->chan.psm)) { l2cap_chan_le_recv(chan, buf); net_buf_unref(buf); return; } net_buf_put(&chan->rx_queue, buf); k_work_submit(&chan->rx_work); } #endif /* CONFIG_BT_L2CAP_DYNAMIC_CHANNEL */ static void l2cap_chan_recv(struct bt_l2cap_chan *chan, struct net_buf *buf) { #if defined(CONFIG_BT_L2CAP_DYNAMIC_CHANNEL) struct bt_l2cap_le_chan *ch = BT_L2CAP_LE_CHAN(chan); if (L2CAP_LE_CID_IS_DYN(ch->rx.cid)) { l2cap_chan_recv_queue(ch, buf); return; } #endif /* CONFIG_BT_L2CAP_DYNAMIC_CHANNEL */ BT_DBG("chan %p len %u", chan, buf->len); chan->ops->recv(chan, buf); net_buf_unref(buf); } void bt_l2cap_recv(struct bt_conn *conn, struct net_buf *buf) { struct bt_l2cap_hdr *hdr; struct bt_l2cap_chan *chan; uint16_t cid; if (IS_ENABLED(CONFIG_BT_BREDR) && conn->type == BT_CONN_TYPE_BR) { bt_l2cap_br_recv(conn, buf); return; } if (buf->len < sizeof(*hdr)) { BT_ERR("Too small L2CAP PDU received"); net_buf_unref(buf); return; } hdr = net_buf_pull_mem(buf, sizeof(*hdr)); cid = sys_le16_to_cpu(hdr->cid); BT_DBG("Packet for CID %u len %u", cid, buf->len); chan = bt_l2cap_le_lookup_rx_cid(conn, cid); if (!chan) { BT_WARN("Ignoring data for unknown CID 0x%04x", cid); net_buf_unref(buf); return; } l2cap_chan_recv(chan, buf); } int bt_l2cap_update_conn_param(struct bt_conn *conn, const struct bt_le_conn_param *param) { struct bt_l2cap_conn_param_req *req; struct net_buf *buf; buf = l2cap_create_le_sig_pdu(NULL, BT_L2CAP_CONN_PARAM_REQ, get_ident(), sizeof(*req)); if (!buf) { return -ENOMEM; } req = net_buf_add(buf, sizeof(*req)); req->min_interval = sys_cpu_to_le16(param->interval_min); req->max_interval = sys_cpu_to_le16(param->interval_max); req->latency = sys_cpu_to_le16(param->latency); req->timeout = sys_cpu_to_le16(param->timeout); bt_l2cap_send(conn, BT_L2CAP_CID_LE_SIG, buf); return 0; } static void l2cap_connected(struct bt_l2cap_chan *chan) { BT_DBG("ch %p cid 0x%04x", BT_L2CAP_LE_CHAN(chan), BT_L2CAP_LE_CHAN(chan)->rx.cid); } static void l2cap_disconnected(struct bt_l2cap_chan *chan) { BT_DBG("ch %p cid 0x%04x", BT_L2CAP_LE_CHAN(chan), BT_L2CAP_LE_CHAN(chan)->rx.cid); } static int l2cap_accept(struct bt_conn *conn, struct bt_l2cap_chan **chan) { int i; static const struct bt_l2cap_chan_ops ops = { .connected = l2cap_connected, .disconnected = l2cap_disconnected, .recv = l2cap_recv, }; BT_DBG("conn %p handle %u", conn, conn->handle); for (i = 0; i < ARRAY_SIZE(bt_l2cap_pool); i++) { struct bt_l2cap *l2cap = &bt_l2cap_pool[i]; if (l2cap->chan.chan.conn) { continue; } l2cap->chan.chan.ops = &ops; *chan = &l2cap->chan.chan; return 0; } BT_ERR("No available L2CAP context for conn %p", conn); return -ENOMEM; } BT_L2CAP_CHANNEL_DEFINE(le_fixed_chan, BT_L2CAP_CID_LE_SIG, l2cap_accept, NULL); void bt_l2cap_init(void) { if (IS_ENABLED(CONFIG_BT_BREDR)) { bt_l2cap_br_init(); } } #if defined(CONFIG_BT_L2CAP_DYNAMIC_CHANNEL) static int l2cap_le_connect(struct bt_conn *conn, struct bt_l2cap_le_chan *ch, uint16_t psm) { if (psm < L2CAP_LE_PSM_FIXED_START || psm > L2CAP_LE_PSM_DYN_END) { return -EINVAL; } l2cap_chan_tx_init(ch); l2cap_chan_rx_init(ch); if (!l2cap_chan_add(conn, &ch->chan, l2cap_chan_destroy)) { return -ENOMEM; } ch->chan.psm = psm; return l2cap_le_conn_req(ch); } static int l2cap_ecred_init(struct bt_conn *conn, struct bt_l2cap_le_chan *ch, uint16_t psm) { if (psm < L2CAP_LE_PSM_FIXED_START || psm > L2CAP_LE_PSM_DYN_END) { return -EINVAL; } l2cap_chan_tx_init(ch); l2cap_chan_rx_init(ch); if (!l2cap_chan_add(conn, &ch->chan, l2cap_chan_destroy)) { return -ENOMEM; } ch->chan.psm = psm; BT_DBG("ch %p psm 0x%02x mtu %u mps %u credits %u", ch, ch->chan.psm, ch->rx.mtu, ch->rx.mps, ch->rx.init_credits); return 0; } int bt_l2cap_ecred_chan_connect(struct bt_conn *conn, struct bt_l2cap_chan **chan, uint16_t psm) { int i, err; BT_DBG("conn %p chan %p psm 0x%04x", conn, chan, psm); if (!conn || !chan) { return -EINVAL; } /* Init non-null channels */ for (i = 0; i < L2CAP_ECRED_CHAN_MAX; i++) { if (!chan[i]) { break; } err = l2cap_ecred_init(conn, BT_L2CAP_LE_CHAN(chan[i]), psm); if (err < 0) { i--; goto fail; } } return l2cap_ecred_conn_req(chan, i); fail: /* Remove channels added */ for (; i >= 0; i--) { if (!chan[i]) { continue; } bt_l2cap_chan_remove(conn, chan[i]); } return err; } int bt_l2cap_chan_connect(struct bt_conn *conn, struct bt_l2cap_chan *chan, uint16_t psm) { BT_DBG("conn %p chan %p psm 0x%04x", conn, chan, psm); if (!conn || conn->state != BT_CONN_CONNECTED) { return -ENOTCONN; } if (!chan) { return -EINVAL; } if (IS_ENABLED(CONFIG_BT_BREDR) && conn->type == BT_CONN_TYPE_BR) { return bt_l2cap_br_chan_connect(conn, chan, psm); } if (chan->required_sec_level > BT_SECURITY_L4) { return -EINVAL; } else if (chan->required_sec_level == BT_SECURITY_L0) { chan->required_sec_level = BT_SECURITY_L1; } return l2cap_le_connect(conn, BT_L2CAP_LE_CHAN(chan), psm); } int bt_l2cap_chan_disconnect(struct bt_l2cap_chan *chan) { struct bt_conn *conn = chan->conn; struct net_buf *buf; struct bt_l2cap_disconn_req *req; struct bt_l2cap_le_chan *ch; if (!conn) { return -ENOTCONN; } if (IS_ENABLED(CONFIG_BT_BREDR) && conn->type == BT_CONN_TYPE_BR) { return bt_l2cap_br_chan_disconnect(chan); } ch = BT_L2CAP_LE_CHAN(chan); BT_DBG("chan %p scid 0x%04x dcid 0x%04x", chan, ch->rx.cid, ch->tx.cid); ch->chan.ident = get_ident(); buf = l2cap_create_le_sig_pdu(NULL, BT_L2CAP_DISCONN_REQ, ch->chan.ident, sizeof(*req)); if (!buf) { return -ENOMEM; } req = net_buf_add(buf, sizeof(*req)); req->dcid = sys_cpu_to_le16(ch->rx.cid); req->scid = sys_cpu_to_le16(ch->tx.cid); l2cap_chan_send_req(chan, buf, L2CAP_DISC_TIMEOUT); bt_l2cap_chan_set_state(chan, BT_L2CAP_DISCONNECT); return 0; } int bt_l2cap_chan_send(struct bt_l2cap_chan *chan, struct net_buf *buf) { struct bt_l2cap_le_chan *ch = BT_L2CAP_LE_CHAN(chan); int err; if (!buf) { return -EINVAL; } BT_DBG("chan %p buf %p len %zu", chan, buf, net_buf_frags_len(buf)); if (!chan->conn || chan->conn->state != BT_CONN_CONNECTED) { return -ENOTCONN; } if (atomic_test_bit(chan->status, BT_L2CAP_STATUS_SHUTDOWN)) { return -ESHUTDOWN; } if (IS_ENABLED(CONFIG_BT_BREDR) && chan->conn->type == BT_CONN_TYPE_BR) { return bt_l2cap_br_chan_send(chan, buf); } /* Queue if there are pending segments left from previous packet or * there are no credits available. */ if (ch->tx_buf || !k_fifo_is_empty(&ch->tx_queue) || !atomic_get(&ch->tx.credits)) { data_sent(buf)->len = 0; net_buf_put(&ch->tx_queue, buf); k_work_submit(&ch->tx_work); return 0; } err = l2cap_chan_le_send_sdu(ch, &buf, 0); if (err < 0) { if (err == -EAGAIN && data_sent(buf)->len) { /* Queue buffer if at least one segment could be sent */ net_buf_put(&ch->tx_queue, buf); return data_sent(buf)->len; } BT_ERR("failed to send message %d", err); } return err; } #endif /* CONFIG_BT_L2CAP_DYNAMIC_CHANNEL */
24146.c
/* deflate.c -- compress data using the deflation algorithm * Copyright (C) 1995-2013 Jean-loup Gailly and Mark Adler * For conditions of distribution and use, see copyright notice in zlib.h */ /* * ALGORITHM * * The "deflation" process depends on being able to identify portions * of the input text which are identical to earlier input (within a * sliding window trailing behind the input currently being processed). * * The most straightforward technique turns out to be the fastest for * most input files: try all possible matches and select the longest. * The key feature of this algorithm is that insertions into the string * dictionary are very simple and thus fast, and deletions are avoided * completely. Insertions are performed at each input character, whereas * string matches are performed only when the previous match ends. So it * is preferable to spend more time in matches to allow very fast string * insertions and avoid deletions. The matching algorithm for small * strings is inspired from that of Rabin & Karp. A brute force approach * is used to find longer strings when a small match has been found. * A similar algorithm is used in comic (by Jan-Mark Wams) and freeze * (by Leonid Broukhis). * A previous version of this file used a more sophisticated algorithm * (by Fiala and Greene) which is guaranteed to run in linear amortized * time, but has a larger average cost, uses more memory and is patented. * However the F&G algorithm may be faster for some highly redundant * files if the parameter max_chain_length (described below) is too large. * * ACKNOWLEDGEMENTS * * The idea of lazy evaluation of matches is due to Jan-Mark Wams, and * I found it in 'freeze' written by Leonid Broukhis. * Thanks to many people for bug reports and testing. * * REFERENCES * * Deutsch, L.P.,"DEFLATE Compressed Data Format Specification". * Available in http://tools.ietf.org/html/rfc1951 * * A description of the Rabin and Karp algorithm is given in the book * "Algorithms" by R. Sedgewick, Addison-Wesley, p252. * * Fiala,E.R., and Greene,D.H. * Data Compression with Finite Windows, Comm.ACM, 32,4 (1989) 490-595 * */ /* @(#) $Id$ */ #include "deflate.h" const char deflate_copyright[] = " deflate 1.2.8 Copyright 1995-2013 Jean-loup Gailly and Mark Adler "; /* If you use the zlib library in a product, an acknowledgment is welcome in the documentation of your product. If for some reason you cannot include such an acknowledgment, I would appreciate that you keep this copyright string in the executable of your product. */ /* =========================================================================== * Function prototypes. */ typedef enum { need_more, /* block not completed, need more input or more output */ block_done, /* block flush performed */ finish_started, /* finish started, need only more output at next deflate */ finish_done /* finish done, accept no more input or output */ } block_state; typedef block_state (*compress_func) OF((deflate_state *s, int flush)); /* Compression function. Returns the block state after the call. */ local void fill_window OF((deflate_state *s)); local block_state deflate_stored OF((deflate_state *s, int flush)); local block_state deflate_fast OF((deflate_state *s, int flush)); #ifndef FASTEST local block_state deflate_slow OF((deflate_state *s, int flush)); #endif local block_state deflate_rle OF((deflate_state *s, int flush)); local block_state deflate_huff OF((deflate_state *s, int flush)); local void lm_init OF((deflate_state *s)); local void putShortMSB OF((deflate_state *s, uInt b)); local void flush_pending OF((z_streamp strm)); local int read_buf OF((z_streamp strm, Bytef *buf, unsigned size)); #ifdef ASMV void match_init OF((void)); /* asm code initialization */ uInt longest_match OF((deflate_state *s, IPos cur_match)); #else local uInt longest_match OF((deflate_state *s, IPos cur_match)); #endif #ifdef DEBUG local void check_match OF((deflate_state *s, IPos start, IPos match, int length)); #endif /* =========================================================================== * Local data */ #define NIL 0 /* Tail of hash chains */ #ifndef TOO_FAR # define TOO_FAR 4096 #endif /* Matches of length 3 are discarded if their distance exceeds TOO_FAR */ /* Values for max_lazy_match, good_match and max_chain_length, depending on * the desired pack level (0..9). The values given below have been tuned to * exclude worst case performance for pathological files. Better values may be * found for specific files. */ typedef struct config_s { ush good_length; /* reduce lazy search above this match length */ ush max_lazy; /* do not perform lazy search above this match length */ ush nice_length; /* quit search above this match length */ ush max_chain; compress_func func; } config; #ifdef FASTEST local const config configuration_table[2] = { /* good lazy nice chain */ /* 0 */ {0, 0, 0, 0, deflate_stored}, /* store only */ /* 1 */ {4, 4, 8, 4, deflate_fast}}; /* max speed, no lazy matches */ #else local const config configuration_table[10] = { /* good lazy nice chain */ /* 0 */ {0, 0, 0, 0, deflate_stored}, /* store only */ /* 1 */ {4, 4, 8, 4, deflate_fast}, /* max speed, no lazy matches */ /* 2 */ {4, 5, 16, 8, deflate_fast}, /* 3 */ {4, 6, 32, 32, deflate_fast}, /* 4 */ {4, 4, 16, 16, deflate_slow}, /* lazy matches */ /* 5 */ {8, 16, 32, 32, deflate_slow}, /* 6 */ {8, 16, 128, 128, deflate_slow}, /* 7 */ {8, 32, 128, 256, deflate_slow}, /* 8 */ {32, 128, 258, 1024, deflate_slow}, /* 9 */ {32, 258, 258, 4096, deflate_slow}}; /* max compression */ #endif /* Note: the deflate() code requires max_lazy >= MIN_MATCH and max_chain >= 4 * For deflate_fast() (levels <= 3) good is ignored and lazy has a different * meaning. */ #define EQUAL 0 /* result of memcmp for equal strings */ #ifndef NO_DUMMY_DECL struct static_tree_desc_s {int dummy;}; /* for buggy compilers */ #endif /* rank Z_BLOCK between Z_NO_FLUSH and Z_PARTIAL_FLUSH */ #define RANK(f) (((f) << 1) - ((f) > 4 ? 9 : 0)) /* =========================================================================== * Update a hash value with the given input byte * IN assertion: all calls to to UPDATE_HASH are made with consecutive * input characters, so that a running hash key can be computed from the * previous key instead of complete recalculation each time. */ #define UPDATE_HASH(s,h,c) (h = (((h)<<s->hash_shift) ^ (c)) & s->hash_mask) /* =========================================================================== * Insert string str in the dictionary and set match_head to the previous head * of the hash chain (the most recent string with same hash key). Return * the previous length of the hash chain. * If this file is compiled with -DFASTEST, the compression level is forced * to 1, and no hash chains are maintained. * IN assertion: all calls to to INSERT_STRING are made with consecutive * input characters and the first MIN_MATCH bytes of str are valid * (except for the last MIN_MATCH-1 bytes of the input file). */ #ifdef FASTEST #define INSERT_STRING(s, str, match_head) \ (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \ match_head = s->head[s->ins_h], \ s->head[s->ins_h] = (Pos)(str)) #else #define INSERT_STRING(s, str, match_head) \ (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \ match_head = s->prev[(str) & s->w_mask] = s->head[s->ins_h], \ s->head[s->ins_h] = (Pos)(str)) #endif /* =========================================================================== * Initialize the hash table (avoiding 64K overflow for 16 bit systems). * prev[] will be initialized on the fly. */ #define CLEAR_HASH(s) \ s->head[s->hash_size-1] = NIL; \ zmemzero((Bytef *)s->head, (unsigned)(s->hash_size-1)*sizeof(*s->head)); /* ========================================================================= */ int ZEXPORT deflateInit_(strm, level, version, stream_size) z_streamp strm; int level; const char *version; int stream_size; { return deflateInit2_(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY, version, stream_size); /* To do: ignore strm->next_in if we use it as window */ } /* ========================================================================= */ int ZEXPORT deflateInit2_(strm, level, method, windowBits, memLevel, strategy, version, stream_size) z_streamp strm; int level; int method; int windowBits; int memLevel; int strategy; const char *version; int stream_size; { deflate_state *s; int wrap = 1; static const char my_version[] = ZLIB_VERSION; ushf *overlay; /* We overlay pending_buf and d_buf+l_buf. This works since the average * output size for (length,distance) codes is <= 24 bits. */ if (version == Z_NULL || version[0] != my_version[0] || stream_size != sizeof(z_stream)) { return Z_VERSION_ERROR; } if (strm == Z_NULL) return Z_STREAM_ERROR; strm->msg = Z_NULL; 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 #ifdef FASTEST if (level != 0) level = 1; #else if (level == Z_DEFAULT_COMPRESSION) level = 6; #endif if (windowBits < 0) { /* suppress zlib wrapper */ wrap = 0; windowBits = -windowBits; } #ifdef GZIP else if (windowBits > 15) { wrap = 2; /* write gzip wrapper instead */ windowBits -= 16; } #endif if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method != Z_DEFLATED || windowBits < 8 || windowBits > 15 || level < 0 || level > 9 || strategy < 0 || strategy > Z_FIXED) { return Z_STREAM_ERROR; } if (windowBits == 8) windowBits = 9; /* until 256-byte window bug fixed */ s = (deflate_state *) ZALLOC(strm, 1, sizeof(deflate_state)); if (s == Z_NULL) return Z_MEM_ERROR; strm->state = (struct internal_state FAR *)s; s->strm = strm; s->wrap = wrap; s->gzhead = Z_NULL; s->w_bits = windowBits; s->w_size = 1 << s->w_bits; s->w_mask = s->w_size - 1; s->hash_bits = memLevel + 7; s->hash_size = 1 << s->hash_bits; s->hash_mask = s->hash_size - 1; s->hash_shift = ((s->hash_bits+MIN_MATCH-1)/MIN_MATCH); s->window = (Bytef *) ZALLOC(strm, s->w_size, 2*sizeof(Byte)); s->prev = (Posf *) ZALLOC(strm, s->w_size, sizeof(Pos)); s->head = (Posf *) ZALLOC(strm, s->hash_size, sizeof(Pos)); s->high_water = 0; /* nothing written to s->window yet */ s->lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */ overlay = (ushf *) ZALLOC(strm, s->lit_bufsize, sizeof(ush)+2); s->pending_buf = (uchf *) overlay; s->pending_buf_size = (ulg)s->lit_bufsize * (sizeof(ush)+2L); if (s->window == Z_NULL || s->prev == Z_NULL || s->head == Z_NULL || s->pending_buf == Z_NULL) { s->status = FINISH_STATE; strm->msg = ERR_MSG(Z_MEM_ERROR); deflateEnd (strm); return Z_MEM_ERROR; } s->d_buf = overlay + s->lit_bufsize/sizeof(ush); s->l_buf = s->pending_buf + (1+sizeof(ush))*s->lit_bufsize; s->level = level; s->strategy = strategy; s->method = (Byte)method; return deflateReset(strm); } /* ========================================================================= */ int ZEXPORT deflateSetDictionary (strm, dictionary, dictLength) z_streamp strm; const Bytef *dictionary; uInt dictLength; { deflate_state *s; uInt str, n; int wrap; unsigned avail; z_const unsigned char *next; if (strm == Z_NULL || strm->state == Z_NULL || dictionary == Z_NULL) return Z_STREAM_ERROR; s = strm->state; wrap = s->wrap; if (wrap == 2 || (wrap == 1 && s->status != INIT_STATE) || s->lookahead) return Z_STREAM_ERROR; /* when using zlib wrappers, compute Adler-32 for provided dictionary */ if (wrap == 1) strm->adler = adler32(strm->adler, dictionary, dictLength); s->wrap = 0; /* avoid computing Adler-32 in read_buf */ /* if dictionary would fill window, just replace the history */ if (dictLength >= s->w_size) { if (wrap == 0) { /* already empty otherwise */ CLEAR_HASH(s); s->strstart = 0; s->block_start = 0L; s->insert = 0; } dictionary += dictLength - s->w_size; /* use the tail */ dictLength = s->w_size; } /* insert dictionary into window and hash */ avail = strm->avail_in; next = strm->next_in; strm->avail_in = dictLength; strm->next_in = (z_const Bytef *)dictionary; fill_window(s); while (s->lookahead >= MIN_MATCH) { str = s->strstart; n = s->lookahead - (MIN_MATCH-1); do { UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); #ifndef FASTEST s->prev[str & s->w_mask] = s->head[s->ins_h]; #endif s->head[s->ins_h] = (Pos)str; str++; } while (--n); s->strstart = str; s->lookahead = MIN_MATCH-1; fill_window(s); } s->strstart += s->lookahead; s->block_start = (long)s->strstart; s->insert = s->lookahead; s->lookahead = 0; s->match_length = s->prev_length = MIN_MATCH-1; s->match_available = 0; strm->next_in = next; strm->avail_in = avail; s->wrap = wrap; return Z_OK; } /* ========================================================================= */ int ZEXPORT deflateResetKeep (strm) z_streamp strm; { deflate_state *s; if (strm == Z_NULL || strm->state == Z_NULL || strm->zalloc == (alloc_func)0 || strm->zfree == (free_func)0) { return Z_STREAM_ERROR; } strm->total_in = strm->total_out = 0; strm->msg = Z_NULL; /* use zfree if we ever allocate msg dynamically */ strm->data_type = Z_UNKNOWN; s = (deflate_state *)strm->state; s->pending = 0; s->pending_out = s->pending_buf; if (s->wrap < 0) { s->wrap = -s->wrap; /* was made negative by deflate(..., Z_FINISH); */ } s->status = s->wrap ? INIT_STATE : BUSY_STATE; strm->adler = #ifdef GZIP s->wrap == 2 ? crc32(0L, Z_NULL, 0) : #endif adler32(0L, Z_NULL, 0); s->last_flush = Z_NO_FLUSH; _tr_init(s); return Z_OK; } /* ========================================================================= */ int ZEXPORT deflateReset (strm) z_streamp strm; { int ret; ret = deflateResetKeep(strm); if (ret == Z_OK) lm_init(strm->state); return ret; } /* ========================================================================= */ int ZEXPORT deflateSetHeader (strm, head) z_streamp strm; gz_headerp head; { if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR; if (strm->state->wrap != 2) return Z_STREAM_ERROR; strm->state->gzhead = head; return Z_OK; } /* ========================================================================= */ int ZEXPORT deflatePending (strm, pending, bits) unsigned *pending; int *bits; z_streamp strm; { if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR; if (pending != Z_NULL) *pending = strm->state->pending; if (bits != Z_NULL) *bits = strm->state->bi_valid; return Z_OK; } /* ========================================================================= */ int ZEXPORT deflatePrime (strm, bits, value) z_streamp strm; int bits; int value; { deflate_state *s; int put; if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR; s = strm->state; if ((Bytef *)(s->d_buf) < s->pending_out + ((Buf_size + 7) >> 3)) return Z_BUF_ERROR; do { put = Buf_size - s->bi_valid; if (put > bits) put = bits; s->bi_buf |= (ush)((value & ((1 << put) - 1)) << s->bi_valid); s->bi_valid += put; _tr_flush_bits(s); value >>= put; bits -= put; } while (bits); return Z_OK; } /* ========================================================================= */ int ZEXPORT deflateParams(strm, level, strategy) z_streamp strm; int level; int strategy; { deflate_state *s; compress_func func; int err = Z_OK; if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR; s = strm->state; #ifdef FASTEST if (level != 0) level = 1; #else if (level == Z_DEFAULT_COMPRESSION) level = 6; #endif if (level < 0 || level > 9 || strategy < 0 || strategy > Z_FIXED) { return Z_STREAM_ERROR; } func = configuration_table[s->level].func; if ((strategy != s->strategy || func != configuration_table[level].func) && strm->total_in != 0) { /* Flush the last buffer: */ err = deflate(strm, Z_BLOCK); if (err == Z_BUF_ERROR && s->pending == 0) err = Z_OK; } if (s->level != level) { s->level = level; s->max_lazy_match = configuration_table[level].max_lazy; s->good_match = configuration_table[level].good_length; s->nice_match = configuration_table[level].nice_length; s->max_chain_length = configuration_table[level].max_chain; } s->strategy = strategy; return err; } /* ========================================================================= */ int ZEXPORT deflateTune(strm, good_length, max_lazy, nice_length, max_chain) z_streamp strm; int good_length; int max_lazy; int nice_length; int max_chain; { deflate_state *s; if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR; s = strm->state; s->good_match = good_length; s->max_lazy_match = max_lazy; s->nice_match = nice_length; s->max_chain_length = max_chain; return Z_OK; } /* ========================================================================= * For the default windowBits of 15 and memLevel of 8, this function returns * a close to exact, as well as small, upper bound on the compressed size. * They are coded as constants here for a reason--if the #define's are * changed, then this function needs to be changed as well. The return * value for 15 and 8 only works for those exact settings. * * For any setting other than those defaults for windowBits and memLevel, * the value returned is a conservative worst case for the maximum expansion * resulting from using fixed blocks instead of stored blocks, which deflate * can emit on compressed data for some combinations of the parameters. * * This function could be more sophisticated to provide closer upper bounds for * every combination of windowBits and memLevel. But even the conservative * upper bound of about 14% expansion does not seem onerous for output buffer * allocation. */ uLong ZEXPORT deflateBound(strm, sourceLen) z_streamp strm; uLong sourceLen; { deflate_state *s; uLong complen, wraplen; Bytef *str; /* conservative upper bound for compressed data */ complen = sourceLen + ((sourceLen + 7) >> 3) + ((sourceLen + 63) >> 6) + 5; /* if can't get parameters, return conservative bound plus zlib wrapper */ if (strm == Z_NULL || strm->state == Z_NULL) return complen + 6; /* compute wrapper length */ s = strm->state; switch (s->wrap) { case 0: /* raw deflate */ wraplen = 0; break; case 1: /* zlib wrapper */ wraplen = 6 + (s->strstart ? 4 : 0); break; case 2: /* gzip wrapper */ wraplen = 18; if (s->gzhead != Z_NULL) { /* user-supplied gzip header */ if (s->gzhead->extra != Z_NULL) wraplen += 2 + s->gzhead->extra_len; str = s->gzhead->name; if (str != Z_NULL) do { wraplen++; } while (*str++); str = s->gzhead->comment; if (str != Z_NULL) do { wraplen++; } while (*str++); if (s->gzhead->hcrc) wraplen += 2; } break; default: /* for compiler happiness */ wraplen = 6; } /* if not default parameters, return conservative bound */ if (s->w_bits != 15 || s->hash_bits != 8 + 7) return complen + wraplen; /* default settings: return tight bound for that case */ return sourceLen + (sourceLen >> 12) + (sourceLen >> 14) + (sourceLen >> 25) + 13 - 6 + wraplen; } /* ========================================================================= * Put a short in the pending buffer. The 16-bit value is put in MSB order. * IN assertion: the stream state is correct and there is enough room in * pending_buf. */ local void putShortMSB (s, b) deflate_state *s; uInt b; { put_byte(s, (Byte)(b >> 8)); put_byte(s, (Byte)(b & 0xff)); } /* ========================================================================= * Flush as much pending output as possible. All deflate() output goes * through this function so some applications may wish to modify it * to avoid allocating a large strm->next_out buffer and copying into it. * (See also read_buf()). */ local void flush_pending(strm) z_streamp strm; { unsigned len; deflate_state *s = strm->state; _tr_flush_bits(s); len = s->pending; if (len > strm->avail_out) len = strm->avail_out; if (len == 0) return; zmemcpy(strm->next_out, s->pending_out, len); strm->next_out += len; s->pending_out += len; strm->total_out += len; strm->avail_out -= len; s->pending -= len; if (s->pending == 0) { s->pending_out = s->pending_buf; } } /* ========================================================================= */ int ZEXPORT deflate (strm, flush) z_streamp strm; int flush; { int old_flush; /* value of flush param for previous deflate call */ deflate_state *s; if (strm == Z_NULL || strm->state == Z_NULL || flush > Z_BLOCK || flush < 0) { return Z_STREAM_ERROR; } s = strm->state; if (strm->next_out == Z_NULL || (strm->next_in == Z_NULL && strm->avail_in != 0) || (s->status == FINISH_STATE && flush != Z_FINISH)) { ERR_RETURN(strm, Z_STREAM_ERROR); } if (strm->avail_out == 0) ERR_RETURN(strm, Z_BUF_ERROR); s->strm = strm; /* just in case */ old_flush = s->last_flush; s->last_flush = flush; /* Write the header */ if (s->status == INIT_STATE) { #ifdef GZIP if (s->wrap == 2) { strm->adler = crc32(0L, Z_NULL, 0); put_byte(s, 31); put_byte(s, 139); put_byte(s, 8); if (s->gzhead == Z_NULL) { put_byte(s, 0); put_byte(s, 0); put_byte(s, 0); put_byte(s, 0); put_byte(s, 0); put_byte(s, s->level == 9 ? 2 : (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ? 4 : 0)); put_byte(s, OS_CODE); s->status = BUSY_STATE; } else { put_byte(s, (s->gzhead->text ? 1 : 0) + (s->gzhead->hcrc ? 2 : 0) + (s->gzhead->extra == Z_NULL ? 0 : 4) + (s->gzhead->name == Z_NULL ? 0 : 8) + (s->gzhead->comment == Z_NULL ? 0 : 16) ); put_byte(s, (Byte)(s->gzhead->time & 0xff)); put_byte(s, (Byte)((s->gzhead->time >> 8) & 0xff)); put_byte(s, (Byte)((s->gzhead->time >> 16) & 0xff)); put_byte(s, (Byte)((s->gzhead->time >> 24) & 0xff)); put_byte(s, s->level == 9 ? 2 : (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ? 4 : 0)); put_byte(s, s->gzhead->os & 0xff); if (s->gzhead->extra != Z_NULL) { put_byte(s, s->gzhead->extra_len & 0xff); put_byte(s, (s->gzhead->extra_len >> 8) & 0xff); } if (s->gzhead->hcrc) strm->adler = crc32(strm->adler, s->pending_buf, s->pending); s->gzindex = 0; s->status = EXTRA_STATE; } } else #endif { uInt header = (Z_DEFLATED + ((s->w_bits-8)<<4)) << 8; uInt level_flags; if (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2) level_flags = 0; else if (s->level < 6) level_flags = 1; else if (s->level == 6) level_flags = 2; else level_flags = 3; header |= (level_flags << 6); if (s->strstart != 0) header |= PRESET_DICT; header += 31 - (header % 31); s->status = BUSY_STATE; putShortMSB(s, header); /* Save the adler32 of the preset dictionary: */ if (s->strstart != 0) { putShortMSB(s, (uInt)(strm->adler >> 16)); putShortMSB(s, (uInt)(strm->adler & 0xffff)); } strm->adler = adler32(0L, Z_NULL, 0); } } #ifdef GZIP if (s->status == EXTRA_STATE) { if (s->gzhead->extra != Z_NULL) { uInt beg = s->pending; /* start of bytes to update crc */ while (s->gzindex < (s->gzhead->extra_len & 0xffff)) { if (s->pending == s->pending_buf_size) { if (s->gzhead->hcrc && s->pending > beg) strm->adler = crc32(strm->adler, s->pending_buf + beg, s->pending - beg); flush_pending(strm); beg = s->pending; if (s->pending == s->pending_buf_size) break; } put_byte(s, s->gzhead->extra[s->gzindex]); s->gzindex++; } if (s->gzhead->hcrc && s->pending > beg) strm->adler = crc32(strm->adler, s->pending_buf + beg, s->pending - beg); if (s->gzindex == s->gzhead->extra_len) { s->gzindex = 0; s->status = NAME_STATE; } } else s->status = NAME_STATE; } if (s->status == NAME_STATE) { if (s->gzhead->name != Z_NULL) { uInt beg = s->pending; /* start of bytes to update crc */ int val; do { if (s->pending == s->pending_buf_size) { if (s->gzhead->hcrc && s->pending > beg) strm->adler = crc32(strm->adler, s->pending_buf + beg, s->pending - beg); flush_pending(strm); beg = s->pending; if (s->pending == s->pending_buf_size) { val = 1; break; } } val = s->gzhead->name[s->gzindex++]; put_byte(s, val); } while (val != 0); if (s->gzhead->hcrc && s->pending > beg) strm->adler = crc32(strm->adler, s->pending_buf + beg, s->pending - beg); if (val == 0) { s->gzindex = 0; s->status = COMMENT_STATE; } } else s->status = COMMENT_STATE; } if (s->status == COMMENT_STATE) { if (s->gzhead->comment != Z_NULL) { uInt beg = s->pending; /* start of bytes to update crc */ int val; do { if (s->pending == s->pending_buf_size) { if (s->gzhead->hcrc && s->pending > beg) strm->adler = crc32(strm->adler, s->pending_buf + beg, s->pending - beg); flush_pending(strm); beg = s->pending; if (s->pending == s->pending_buf_size) { val = 1; break; } } val = s->gzhead->comment[s->gzindex++]; put_byte(s, val); } while (val != 0); if (s->gzhead->hcrc && s->pending > beg) strm->adler = crc32(strm->adler, s->pending_buf + beg, s->pending - beg); if (val == 0) s->status = HCRC_STATE; } else s->status = HCRC_STATE; } if (s->status == HCRC_STATE) { if (s->gzhead->hcrc) { if (s->pending + 2 > s->pending_buf_size) flush_pending(strm); if (s->pending + 2 <= s->pending_buf_size) { put_byte(s, (Byte)(strm->adler & 0xff)); put_byte(s, (Byte)((strm->adler >> 8) & 0xff)); strm->adler = crc32(0L, Z_NULL, 0); s->status = BUSY_STATE; } } else s->status = BUSY_STATE; } #endif /* Flush as much pending output as possible */ if (s->pending != 0) { flush_pending(strm); if (strm->avail_out == 0) { /* Since avail_out is 0, deflate will be called again with * more output space, but possibly with both pending and * avail_in equal to zero. There won't be anything to do, * but this is not an error situation so make sure we * return OK instead of BUF_ERROR at next call of deflate: */ s->last_flush = -1; return Z_OK; } /* Make sure there is something to do and avoid duplicate consecutive * flushes. For repeated and useless calls with Z_FINISH, we keep * returning Z_STREAM_END instead of Z_BUF_ERROR. */ } else if (strm->avail_in == 0 && RANK(flush) <= RANK(old_flush) && flush != Z_FINISH) { ERR_RETURN(strm, Z_BUF_ERROR); } /* User must not provide more input after the first FINISH: */ if (s->status == FINISH_STATE && strm->avail_in != 0) { ERR_RETURN(strm, Z_BUF_ERROR); } /* Start a new block or continue the current one. */ if (strm->avail_in != 0 || s->lookahead != 0 || (flush != Z_NO_FLUSH && s->status != FINISH_STATE)) { block_state bstate; bstate = s->strategy == Z_HUFFMAN_ONLY ? deflate_huff(s, flush) : (s->strategy == Z_RLE ? deflate_rle(s, flush) : (*(configuration_table[s->level].func))(s, flush)); if (bstate == finish_started || bstate == finish_done) { s->status = FINISH_STATE; } if (bstate == need_more || bstate == finish_started) { if (strm->avail_out == 0) { s->last_flush = -1; /* avoid BUF_ERROR next call, see above */ } return Z_OK; /* If flush != Z_NO_FLUSH && avail_out == 0, the next call * of deflate should use the same flush parameter to make sure * that the flush is complete. So we don't have to output an * empty block here, this will be done at next call. This also * ensures that for a very small output buffer, we emit at most * one empty block. */ } if (bstate == block_done) { if (flush == Z_PARTIAL_FLUSH) { _tr_align(s); } else if (flush != Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */ _tr_stored_block(s, (char*)0, 0L, 0); /* For a full flush, this empty block will be recognized * as a special marker by inflate_sync(). */ if (flush == Z_FULL_FLUSH) { CLEAR_HASH(s); /* forget history */ if (s->lookahead == 0) { s->strstart = 0; s->block_start = 0L; s->insert = 0; } } } flush_pending(strm); if (strm->avail_out == 0) { s->last_flush = -1; /* avoid BUF_ERROR at next call, see above */ return Z_OK; } } } Assert(strm->avail_out > 0, "bug2"); if (flush != Z_FINISH) return Z_OK; if (s->wrap <= 0) return Z_STREAM_END; /* Write the trailer */ #ifdef GZIP if (s->wrap == 2) { put_byte(s, (Byte)(strm->adler & 0xff)); put_byte(s, (Byte)((strm->adler >> 8) & 0xff)); put_byte(s, (Byte)((strm->adler >> 16) & 0xff)); put_byte(s, (Byte)((strm->adler >> 24) & 0xff)); put_byte(s, (Byte)(strm->total_in & 0xff)); put_byte(s, (Byte)((strm->total_in >> 8) & 0xff)); put_byte(s, (Byte)((strm->total_in >> 16) & 0xff)); put_byte(s, (Byte)((strm->total_in >> 24) & 0xff)); } else #endif { putShortMSB(s, (uInt)(strm->adler >> 16)); putShortMSB(s, (uInt)(strm->adler & 0xffff)); } flush_pending(strm); /* If avail_out is zero, the application will call deflate again * to flush the rest. */ if (s->wrap > 0) s->wrap = -s->wrap; /* write the trailer only once! */ return s->pending != 0 ? Z_OK : Z_STREAM_END; } /* ========================================================================= */ int ZEXPORT deflateEnd (strm) z_streamp strm; { int status; if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR; status = strm->state->status; if (status != INIT_STATE && status != EXTRA_STATE && status != NAME_STATE && status != COMMENT_STATE && status != HCRC_STATE && status != BUSY_STATE && status != FINISH_STATE) { return Z_STREAM_ERROR; } /* Deallocate in reverse order of allocations: */ TRY_FREE(strm, strm->state->pending_buf); TRY_FREE(strm, strm->state->head); TRY_FREE(strm, strm->state->prev); TRY_FREE(strm, strm->state->window); ZFREE(strm, strm->state); strm->state = Z_NULL; return status == BUSY_STATE ? Z_DATA_ERROR : Z_OK; } /* ========================================================================= * Copy the source state to the destination state. * To simplify the source, this is not supported for 16-bit MSDOS (which * doesn't have enough memory anyway to duplicate compression states). */ int ZEXPORT deflateCopy (dest, source) z_streamp dest; z_streamp source; { #ifdef MAXSEG_64K return Z_STREAM_ERROR; #else deflate_state *ds; deflate_state *ss; ushf *overlay; if (source == Z_NULL || dest == Z_NULL || source->state == Z_NULL) { return Z_STREAM_ERROR; } ss = source->state; zmemcpy((voidpf)dest, (voidpf)source, sizeof(z_stream)); ds = (deflate_state *) ZALLOC(dest, 1, sizeof(deflate_state)); if (ds == Z_NULL) return Z_MEM_ERROR; dest->state = (struct internal_state FAR *) ds; zmemcpy((voidpf)ds, (voidpf)ss, sizeof(deflate_state)); ds->strm = dest; ds->window = (Bytef *) ZALLOC(dest, ds->w_size, 2*sizeof(Byte)); ds->prev = (Posf *) ZALLOC(dest, ds->w_size, sizeof(Pos)); ds->head = (Posf *) ZALLOC(dest, ds->hash_size, sizeof(Pos)); overlay = (ushf *) ZALLOC(dest, ds->lit_bufsize, sizeof(ush)+2); ds->pending_buf = (uchf *) overlay; if (ds->window == Z_NULL || ds->prev == Z_NULL || ds->head == Z_NULL || ds->pending_buf == Z_NULL) { deflateEnd (dest); return Z_MEM_ERROR; } /* following zmemcpy do not work for 16-bit MSDOS */ zmemcpy(ds->window, ss->window, ds->w_size * 2 * sizeof(Byte)); zmemcpy((voidpf)ds->prev, (voidpf)ss->prev, ds->w_size * sizeof(Pos)); zmemcpy((voidpf)ds->head, (voidpf)ss->head, ds->hash_size * sizeof(Pos)); zmemcpy(ds->pending_buf, ss->pending_buf, (uInt)ds->pending_buf_size); ds->pending_out = ds->pending_buf + (ss->pending_out - ss->pending_buf); ds->d_buf = overlay + ds->lit_bufsize/sizeof(ush); ds->l_buf = ds->pending_buf + (1+sizeof(ush))*ds->lit_bufsize; ds->l_desc.dyn_tree = ds->dyn_ltree; ds->d_desc.dyn_tree = ds->dyn_dtree; ds->bl_desc.dyn_tree = ds->bl_tree; return Z_OK; #endif /* MAXSEG_64K */ } /* =========================================================================== * Read a new buffer from the current input stream, update the adler32 * and total number of bytes read. All deflate() input goes through * this function so some applications may wish to modify it to avoid * allocating a large strm->next_in buffer and copying from it. * (See also flush_pending()). */ local int read_buf(strm, buf, size) z_streamp strm; Bytef *buf; unsigned size; { unsigned len = strm->avail_in; if (len > size) len = size; if (len == 0) return 0; strm->avail_in -= len; zmemcpy(buf, strm->next_in, len); if (strm->state->wrap == 1) { strm->adler = adler32(strm->adler, buf, len); } #ifdef GZIP else if (strm->state->wrap == 2) { strm->adler = crc32(strm->adler, buf, len); } #endif strm->next_in += len; strm->total_in += len; return (int)len; } /* =========================================================================== * Initialize the "longest match" routines for a new zlib stream */ local void lm_init (s) deflate_state *s; { s->window_size = (ulg)2L*s->w_size; CLEAR_HASH(s); /* Set the default configuration parameters: */ s->max_lazy_match = configuration_table[s->level].max_lazy; s->good_match = configuration_table[s->level].good_length; s->nice_match = configuration_table[s->level].nice_length; s->max_chain_length = configuration_table[s->level].max_chain; s->strstart = 0; s->block_start = 0L; s->lookahead = 0; s->insert = 0; s->match_length = s->prev_length = MIN_MATCH-1; s->match_available = 0; s->ins_h = 0; #ifndef FASTEST #ifdef ASMV match_init(); /* initialize the asm code */ #endif #endif } #ifndef FASTEST /* =========================================================================== * Set match_start to the longest match starting at the given string and * return its length. Matches shorter or equal to prev_length are discarded, * in which case the result is equal to prev_length and match_start is * garbage. * IN assertions: cur_match is the head of the hash chain for the current * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1 * OUT assertion: the match length is not greater than s->lookahead. */ #ifndef ASMV /* For 80x86 and 680x0, an optimized version will be provided in match.asm or * match.S. The code will be functionally equivalent. */ local uInt longest_match(s, cur_match) deflate_state *s; IPos cur_match; /* current match */ { unsigned chain_length = s->max_chain_length;/* max hash chain length */ register Bytef *scan = s->window + s->strstart; /* current string */ register Bytef *match; /* matched string */ register int len; /* length of current match */ int best_len = s->prev_length; /* best match length so far */ int nice_match = s->nice_match; /* stop if match long enough */ IPos limit = s->strstart > (IPos)MAX_DIST(s) ? s->strstart - (IPos)MAX_DIST(s) : NIL; /* Stop when cur_match becomes <= limit. To simplify the code, * we prevent matches with the string of window index 0. */ Posf *prev = s->prev; uInt wmask = s->w_mask; #ifdef UNALIGNED_OK /* Compare two bytes at a time. Note: this is not always beneficial. * Try with and without -DUNALIGNED_OK to check. */ register Bytef *strend = s->window + s->strstart + MAX_MATCH - 1; register ush scan_start = *(ushf*)scan; register ush scan_end = *(ushf*)(scan+best_len-1); #else register Bytef *strend = s->window + s->strstart + MAX_MATCH; register Byte scan_end1 = scan[best_len-1]; register Byte scan_end = scan[best_len]; #endif /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16. * It is easy to get rid of this optimization if necessary. */ Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever"); /* Do not waste too much time if we already have a good match: */ if (s->prev_length >= s->good_match) { chain_length >>= 2; } /* Do not look for matches beyond the end of the input. This is necessary * to make deflate deterministic. */ if ((uInt)nice_match > s->lookahead) nice_match = s->lookahead; Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead"); do { Assert(cur_match < s->strstart, "no future"); match = s->window + cur_match; /* Skip to next match if the match length cannot increase * or if the match length is less than 2. Note that the checks below * for insufficient lookahead only occur occasionally for performance * reasons. Therefore uninitialized memory will be accessed, and * conditional jumps will be made that depend on those values. * However the length of the match is limited to the lookahead, so * the output of deflate is not affected by the uninitialized values. */ #if (defined(UNALIGNED_OK) && MAX_MATCH == 258) /* This code assumes sizeof(unsigned short) == 2. Do not use * UNALIGNED_OK if your compiler uses a different size. */ if (*(ushf*)(match+best_len-1) != scan_end || *(ushf*)match != scan_start) continue; /* It is not necessary to compare scan[2] and match[2] since they are * always equal when the other bytes match, given that the hash keys * are equal and that HASH_BITS >= 8. Compare 2 bytes at a time at * strstart+3, +5, ... up to strstart+257. We check for insufficient * lookahead only every 4th comparison; the 128th check will be made * at strstart+257. If MAX_MATCH-2 is not a multiple of 8, it is * necessary to put more guard bytes at the end of the window, or * to check more often for insufficient lookahead. */ Assert(scan[2] == match[2], "scan[2]?"); scan++, match++; do { } while (*(ushf*)(scan+=2) == *(ushf*)(match+=2) && *(ushf*)(scan+=2) == *(ushf*)(match+=2) && *(ushf*)(scan+=2) == *(ushf*)(match+=2) && *(ushf*)(scan+=2) == *(ushf*)(match+=2) && scan < strend); /* The funny "do {}" generates better code on most compilers */ /* Here, scan <= window+strstart+257 */ Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan"); if (*scan == *match) scan++; len = (MAX_MATCH - 1) - (int)(strend-scan); scan = strend - (MAX_MATCH-1); #else /* UNALIGNED_OK */ if (match[best_len] != scan_end || match[best_len-1] != scan_end1 || *match != *scan || *++match != scan[1]) continue; /* The check at best_len-1 can be removed because it will be made * again later. (This heuristic is not always a win.) * It is not necessary to compare scan[2] and match[2] since they * are always equal when the other bytes match, given that * the hash keys are equal and that HASH_BITS >= 8. */ (void)(scan += 2), match++; Assert(*scan == *match, "match[2]?"); /* We check for insufficient lookahead only every 8th comparison; * the 256th check will be made at strstart+258. */ do { } while (*++scan == *++match && *++scan == *++match && *++scan == *++match && *++scan == *++match && *++scan == *++match && *++scan == *++match && *++scan == *++match && *++scan == *++match && scan < strend); Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan"); len = MAX_MATCH - (int)(strend - scan); scan = strend - MAX_MATCH; #endif /* UNALIGNED_OK */ if (len > best_len) { s->match_start = cur_match; best_len = len; if (len >= nice_match) break; #ifdef UNALIGNED_OK scan_end = *(ushf*)(scan+best_len-1); #else scan_end1 = scan[best_len-1]; scan_end = scan[best_len]; #endif } } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length != 0); if ((uInt)best_len <= s->lookahead) return (uInt)best_len; return s->lookahead; } #endif /* ASMV */ #else /* FASTEST */ /* --------------------------------------------------------------------------- * Optimized version for FASTEST only */ local uInt longest_match(s, cur_match) deflate_state *s; IPos cur_match; /* current match */ { register Bytef *scan = s->window + s->strstart; /* current string */ register Bytef *match; /* matched string */ register int len; /* length of current match */ register Bytef *strend = s->window + s->strstart + MAX_MATCH; /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16. * It is easy to get rid of this optimization if necessary. */ Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever"); Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead"); Assert(cur_match < s->strstart, "no future"); match = s->window + cur_match; /* Return failure if the match length is less than 2: */ if (match[0] != scan[0] || match[1] != scan[1]) return MIN_MATCH-1; /* The check at best_len-1 can be removed because it will be made * again later. (This heuristic is not always a win.) * It is not necessary to compare scan[2] and match[2] since they * are always equal when the other bytes match, given that * the hash keys are equal and that HASH_BITS >= 8. */ scan += 2, match += 2; Assert(*scan == *match, "match[2]?"); /* We check for insufficient lookahead only every 8th comparison; * the 256th check will be made at strstart+258. */ do { } while (*++scan == *++match && *++scan == *++match && *++scan == *++match && *++scan == *++match && *++scan == *++match && *++scan == *++match && *++scan == *++match && *++scan == *++match && scan < strend); Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan"); len = MAX_MATCH - (int)(strend - scan); if (len < MIN_MATCH) return MIN_MATCH - 1; s->match_start = cur_match; return (uInt)len <= s->lookahead ? (uInt)len : s->lookahead; } #endif /* FASTEST */ #ifdef DEBUG /* =========================================================================== * Check that the match at match_start is indeed a match. */ local void check_match(s, start, match, length) deflate_state *s; IPos start, match; int length; { /* check that the match is indeed a match */ if (zmemcmp(s->window + match, s->window + start, length) != EQUAL) { fprintf(stderr, " start %u, match %u, length %d\n", start, match, length); do { fprintf(stderr, "%c%c", s->window[match++], s->window[start++]); } while (--length != 0); z_error("invalid match"); } if (z_verbose > 1) { fprintf(stderr,"\\[%d,%d]", start-match, length); do { putc(s->window[start++], stderr); } while (--length != 0); } } #else # define check_match(s, start, match, length) #endif /* DEBUG */ /* =========================================================================== * Fill the window when the lookahead becomes insufficient. * Updates strstart and lookahead. * * IN assertion: lookahead < MIN_LOOKAHEAD * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD * At least one byte has been read, or avail_in == 0; reads are * performed for at least two bytes (required for the zip translate_eol * option -- not supported here). */ local void fill_window(s) deflate_state *s; { register unsigned n, m; register Posf *p; unsigned more; /* Amount of free space at the end of the window. */ uInt wsize = s->w_size; Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead"); do { more = (unsigned)(s->window_size -(ulg)s->lookahead -(ulg)s->strstart); /* Deal with !@#$% 64K limit: */ if (sizeof(int) <= 2) { if (more == 0 && s->strstart == 0 && s->lookahead == 0) { more = wsize; } else if (more == (unsigned)(-1)) { /* Very unlikely, but possible on 16 bit machine if * strstart == 0 && lookahead == 1 (input done a byte at time) */ more--; } } /* If the window is almost full and there is insufficient lookahead, * move the upper half to the lower one to make room in the upper half. */ if (s->strstart >= wsize+MAX_DIST(s)) { zmemcpy(s->window, s->window+wsize, (unsigned)wsize); s->match_start -= wsize; s->strstart -= wsize; /* we now have strstart >= MAX_DIST */ s->block_start -= (long) wsize; /* Slide the hash table (could be avoided with 32 bit values at the expense of memory usage). We slide even when level == 0 to keep the hash table consistent if we switch back to level > 0 later. (Using level 0 permanently is not an optimal usage of zlib, so we don't care about this pathological case.) */ n = s->hash_size; p = &s->head[n]; do { m = *--p; *p = (Pos)(m >= wsize ? m-wsize : NIL); } while (--n); n = wsize; #ifndef FASTEST p = &s->prev[n]; do { m = *--p; *p = (Pos)(m >= wsize ? m-wsize : NIL); /* If n is not on any hash chain, prev[n] is garbage but * its value will never be used. */ } while (--n); #endif more += wsize; } if (s->strm->avail_in == 0) break; /* If there was no sliding: * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 && * more == window_size - lookahead - strstart * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1) * => more >= window_size - 2*WSIZE + 2 * In the BIG_MEM or MMAP case (not yet supported), * window_size == input_size + MIN_LOOKAHEAD && * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD. * Otherwise, window_size == 2*WSIZE so more >= 2. * If there was sliding, more >= WSIZE. So in all cases, more >= 2. */ Assert(more >= 2, "more < 2"); n = read_buf(s->strm, s->window + s->strstart + s->lookahead, more); s->lookahead += n; /* Initialize the hash value now that we have some input: */ if (s->lookahead + s->insert >= MIN_MATCH) { uInt str = s->strstart - s->insert; s->ins_h = s->window[str]; UPDATE_HASH(s, s->ins_h, s->window[str + 1]); #if MIN_MATCH != 3 Call UPDATE_HASH() MIN_MATCH-3 more times #endif while (s->insert) { UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); #ifndef FASTEST s->prev[str & s->w_mask] = s->head[s->ins_h]; #endif s->head[s->ins_h] = (Pos)str; str++; s->insert--; if (s->lookahead + s->insert < MIN_MATCH) break; } } /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage, * but this is not important since only literal bytes will be emitted. */ } while (s->lookahead < MIN_LOOKAHEAD && s->strm->avail_in != 0); /* If the WIN_INIT bytes after the end of the current data have never been * written, then zero those bytes in order to avoid memory check reports of * the use of uninitialized (or uninitialised as Julian writes) bytes by * the longest match routines. Update the high water mark for the next * time through here. WIN_INIT is set to MAX_MATCH since the longest match * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead. */ if (s->high_water < s->window_size) { ulg curr = s->strstart + (ulg)(s->lookahead); ulg init; if (s->high_water < curr) { /* Previous high water mark below current data -- zero WIN_INIT * bytes or up to end of window, whichever is less. */ init = s->window_size - curr; if (init > WIN_INIT) init = WIN_INIT; zmemzero(s->window + curr, (unsigned)init); s->high_water = curr + init; } else if (s->high_water < (ulg)curr + WIN_INIT) { /* High water mark at or above current data, but below current data * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up * to end of window, whichever is less. */ init = (ulg)curr + WIN_INIT - s->high_water; if (init > s->window_size - s->high_water) init = s->window_size - s->high_water; zmemzero(s->window + s->high_water, (unsigned)init); s->high_water += init; } } Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD, "not enough room for search"); } /* =========================================================================== * Flush the current block, with given end-of-file flag. * IN assertion: strstart is set to the end of the current match. */ #define FLUSH_BLOCK_ONLY(s, last) { \ _tr_flush_block(s, (s->block_start >= 0L ? \ (charf *)&s->window[(unsigned)s->block_start] : \ (charf *)Z_NULL), \ (ulg)((long)s->strstart - s->block_start), \ (last)); \ s->block_start = s->strstart; \ flush_pending(s->strm); \ Tracev((stderr,"[FLUSH]")); \ } /* Same but force premature exit if necessary. */ #define FLUSH_BLOCK(s, last) { \ FLUSH_BLOCK_ONLY(s, last); \ if (s->strm->avail_out == 0) return (last) ? finish_started : need_more; \ } /* =========================================================================== * Copy without compression as much as possible from the input stream, return * the current block state. * This function does not insert new strings in the dictionary since * uncompressible data is probably not useful. This function is used * only for the level=0 compression option. * NOTE: this function should be optimized to avoid extra copying from * window to pending_buf. */ local block_state deflate_stored(s, flush) deflate_state *s; int flush; { /* Stored blocks are limited to 0xffff bytes, pending_buf is limited * to pending_buf_size, and each stored block has a 5 byte header: */ ulg max_block_size = 0xffff; ulg max_start; if (max_block_size > s->pending_buf_size - 5) { max_block_size = s->pending_buf_size - 5; } /* Copy as much as possible from input to output: */ for (;;) { /* Fill the window as much as possible: */ if (s->lookahead <= 1) { Assert(s->strstart < s->w_size+MAX_DIST(s) || s->block_start >= (long)s->w_size, "slide too late"); fill_window(s); if (s->lookahead == 0 && flush == Z_NO_FLUSH) return need_more; if (s->lookahead == 0) break; /* flush the current block */ } Assert(s->block_start >= 0L, "block gone"); s->strstart += s->lookahead; s->lookahead = 0; /* Emit a stored block if pending_buf will be full: */ max_start = s->block_start + max_block_size; if (s->strstart == 0 || (ulg)s->strstart >= max_start) { /* strstart == 0 is possible when wraparound on 16-bit machine */ s->lookahead = (uInt)(s->strstart - max_start); s->strstart = (uInt)max_start; FLUSH_BLOCK(s, 0); } /* Flush if we may have to slide, otherwise block_start may become * negative and the data will be gone: */ if (s->strstart - (uInt)s->block_start >= MAX_DIST(s)) { FLUSH_BLOCK(s, 0); } } s->insert = 0; if (flush == Z_FINISH) { FLUSH_BLOCK(s, 1); return finish_done; } if ((long)s->strstart > s->block_start) FLUSH_BLOCK(s, 0); return block_done; } /* =========================================================================== * Compress as much as possible from the input stream, return the current * block state. * This function does not perform lazy evaluation of matches and inserts * new strings in the dictionary only for unmatched strings or for short * matches. It is used only for the fast compression options. */ local block_state deflate_fast(s, flush) deflate_state *s; int flush; { IPos hash_head; /* head of the hash chain */ int bflush; /* set if current block must be flushed */ for (;;) { /* Make sure that we always have enough lookahead, except * at the end of the input file. We need MAX_MATCH bytes * for the next match, plus MIN_MATCH bytes to insert the * string following the next match. */ if (s->lookahead < MIN_LOOKAHEAD) { fill_window(s); if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) { return need_more; } if (s->lookahead == 0) break; /* flush the current block */ } /* Insert the string window[strstart .. strstart+2] in the * dictionary, and set hash_head to the head of the hash chain: */ hash_head = NIL; if (s->lookahead >= MIN_MATCH) { INSERT_STRING(s, s->strstart, hash_head); } /* Find the longest match, discarding those <= prev_length. * At this point we have always match_length < MIN_MATCH */ if (hash_head != NIL && s->strstart - hash_head <= MAX_DIST(s)) { /* To simplify the code, we prevent matches with the string * of window index 0 (in particular we have to avoid a match * of the string with itself at the start of the input file). */ s->match_length = longest_match (s, hash_head); /* longest_match() sets match_start */ } if (s->match_length >= MIN_MATCH) { check_match(s, s->strstart, s->match_start, s->match_length); _tr_tally_dist(s, s->strstart - s->match_start, s->match_length - MIN_MATCH, bflush); s->lookahead -= s->match_length; /* Insert new strings in the hash table only if the match length * is not too large. This saves time but degrades compression. */ #ifndef FASTEST if (s->match_length <= s->max_insert_length && s->lookahead >= MIN_MATCH) { s->match_length--; /* string at strstart already in table */ do { s->strstart++; INSERT_STRING(s, s->strstart, hash_head); /* strstart never exceeds WSIZE-MAX_MATCH, so there are * always MIN_MATCH bytes ahead. */ } while (--s->match_length != 0); s->strstart++; } else #endif { s->strstart += s->match_length; s->match_length = 0; s->ins_h = s->window[s->strstart]; UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]); #if MIN_MATCH != 3 Call UPDATE_HASH() MIN_MATCH-3 more times #endif /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not * matter since it will be recomputed at next deflate call. */ } } else { /* No match, output a literal byte */ Tracevv((stderr,"%c", s->window[s->strstart])); _tr_tally_lit (s, s->window[s->strstart], bflush); s->lookahead--; s->strstart++; } if (bflush) FLUSH_BLOCK(s, 0); } s->insert = s->strstart < MIN_MATCH-1 ? s->strstart : MIN_MATCH-1; if (flush == Z_FINISH) { FLUSH_BLOCK(s, 1); return finish_done; } if (s->last_lit) FLUSH_BLOCK(s, 0); return block_done; } #ifndef FASTEST /* =========================================================================== * Same as above, but achieves better compression. We use a lazy * evaluation for matches: a match is finally adopted only if there is * no better match at the next window position. */ local block_state deflate_slow(s, flush) deflate_state *s; int flush; { IPos hash_head; /* head of hash chain */ int bflush; /* set if current block must be flushed */ /* Process the input block. */ for (;;) { /* Make sure that we always have enough lookahead, except * at the end of the input file. We need MAX_MATCH bytes * for the next match, plus MIN_MATCH bytes to insert the * string following the next match. */ if (s->lookahead < MIN_LOOKAHEAD) { fill_window(s); if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) { return need_more; } if (s->lookahead == 0) break; /* flush the current block */ } /* Insert the string window[strstart .. strstart+2] in the * dictionary, and set hash_head to the head of the hash chain: */ hash_head = NIL; if (s->lookahead >= MIN_MATCH) { INSERT_STRING(s, s->strstart, hash_head); } /* Find the longest match, discarding those <= prev_length. */ (void)(s->prev_length = s->match_length), s->prev_match = s->match_start; s->match_length = MIN_MATCH-1; if (hash_head != NIL && s->prev_length < s->max_lazy_match && s->strstart - hash_head <= MAX_DIST(s)) { /* To simplify the code, we prevent matches with the string * of window index 0 (in particular we have to avoid a match * of the string with itself at the start of the input file). */ s->match_length = longest_match (s, hash_head); /* longest_match() sets match_start */ if (s->match_length <= 5 && (s->strategy == Z_FILTERED #if TOO_FAR <= 32767 || (s->match_length == MIN_MATCH && s->strstart - s->match_start > TOO_FAR) #endif )) { /* If prev_match is also MIN_MATCH, match_start is garbage * but we will ignore the current match anyway. */ s->match_length = MIN_MATCH-1; } } /* If there was a match at the previous step and the current * match is not better, output the previous match: */ if (s->prev_length >= MIN_MATCH && s->match_length <= s->prev_length) { uInt max_insert = s->strstart + s->lookahead - MIN_MATCH; /* Do not insert strings in hash table beyond this. */ check_match(s, s->strstart-1, s->prev_match, s->prev_length); _tr_tally_dist(s, s->strstart -1 - s->prev_match, s->prev_length - MIN_MATCH, bflush); /* Insert in hash table all strings up to the end of the match. * strstart-1 and strstart are already inserted. If there is not * enough lookahead, the last two strings are not inserted in * the hash table. */ s->lookahead -= s->prev_length-1; s->prev_length -= 2; do { if (++s->strstart <= max_insert) { INSERT_STRING(s, s->strstart, hash_head); } } while (--s->prev_length != 0); s->match_available = 0; s->match_length = MIN_MATCH-1; s->strstart++; if (bflush) FLUSH_BLOCK(s, 0); } else if (s->match_available) { /* If there was no match at the previous position, output a * single literal. If there was a match but the current match * is longer, truncate the previous match to a single literal. */ Tracevv((stderr,"%c", s->window[s->strstart-1])); _tr_tally_lit(s, s->window[s->strstart-1], bflush); if (bflush) { FLUSH_BLOCK_ONLY(s, 0); } s->strstart++; s->lookahead--; if (s->strm->avail_out == 0) return need_more; } else { /* There is no previous match to compare with, wait for * the next step to decide. */ s->match_available = 1; s->strstart++; s->lookahead--; } } Assert (flush != Z_NO_FLUSH, "no flush?"); if (s->match_available) { Tracevv((stderr,"%c", s->window[s->strstart-1])); _tr_tally_lit(s, s->window[s->strstart-1], bflush); s->match_available = 0; } s->insert = s->strstart < MIN_MATCH-1 ? s->strstart : MIN_MATCH-1; if (flush == Z_FINISH) { FLUSH_BLOCK(s, 1); return finish_done; } if (s->last_lit) FLUSH_BLOCK(s, 0); return block_done; } #endif /* FASTEST */ /* =========================================================================== * For Z_RLE, simply look for runs of bytes, generate matches only of distance * one. Do not maintain a hash table. (It will be regenerated if this run of * deflate switches away from Z_RLE.) */ local block_state deflate_rle(s, flush) deflate_state *s; int flush; { int bflush; /* set if current block must be flushed */ uInt prev; /* byte at distance one to match */ Bytef *scan, *strend; /* scan goes up to strend for length of run */ for (;;) { /* Make sure that we always have enough lookahead, except * at the end of the input file. We need MAX_MATCH bytes * for the longest run, plus one for the unrolled loop. */ if (s->lookahead <= MAX_MATCH) { fill_window(s); if (s->lookahead <= MAX_MATCH && flush == Z_NO_FLUSH) { return need_more; } if (s->lookahead == 0) break; /* flush the current block */ } /* See how many times the previous byte repeats */ s->match_length = 0; if (s->lookahead >= MIN_MATCH && s->strstart > 0) { scan = s->window + s->strstart - 1; prev = *scan; if (prev == *++scan && prev == *++scan && prev == *++scan) { strend = s->window + s->strstart + MAX_MATCH; do { } while (prev == *++scan && prev == *++scan && prev == *++scan && prev == *++scan && prev == *++scan && prev == *++scan && prev == *++scan && prev == *++scan && scan < strend); s->match_length = MAX_MATCH - (int)(strend - scan); if (s->match_length > s->lookahead) s->match_length = s->lookahead; } Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan"); } /* Emit match if have run of MIN_MATCH or longer, else emit literal */ if (s->match_length >= MIN_MATCH) { check_match(s, s->strstart, s->strstart - 1, s->match_length); _tr_tally_dist(s, 1, s->match_length - MIN_MATCH, bflush); s->lookahead -= s->match_length; s->strstart += s->match_length; s->match_length = 0; } else { /* No match, output a literal byte */ Tracevv((stderr,"%c", s->window[s->strstart])); _tr_tally_lit (s, s->window[s->strstart], bflush); s->lookahead--; s->strstart++; } if (bflush) FLUSH_BLOCK(s, 0); } s->insert = 0; if (flush == Z_FINISH) { FLUSH_BLOCK(s, 1); return finish_done; } if (s->last_lit) FLUSH_BLOCK(s, 0); return block_done; } /* =========================================================================== * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table. * (It will be regenerated if this run of deflate switches away from Huffman.) */ local block_state deflate_huff(s, flush) deflate_state *s; int flush; { int bflush; /* set if current block must be flushed */ for (;;) { /* Make sure that we have a literal to write. */ if (s->lookahead == 0) { fill_window(s); if (s->lookahead == 0) { if (flush == Z_NO_FLUSH) return need_more; break; /* flush the current block */ } } /* Output a literal byte */ s->match_length = 0; Tracevv((stderr,"%c", s->window[s->strstart])); _tr_tally_lit (s, s->window[s->strstart], bflush); s->lookahead--; s->strstart++; if (bflush) FLUSH_BLOCK(s, 0); } s->insert = 0; if (flush == Z_FINISH) { FLUSH_BLOCK(s, 1); return finish_done; } if (s->last_lit) FLUSH_BLOCK(s, 0); return block_done; }
917677.c
/*----------------------------------------------------------------------------*/ /* Hobbit RRD handler module. */ /* */ /* Copyright (C) 2004-2009 Henrik Storner <henrik@hswn.dk> */ /* */ /* This program is released under the GNU General Public License (GPL), */ /* version 2. See the file "COPYING" for details. */ /* */ /*----------------------------------------------------------------------------*/ static char bbnet_rcsid[] = "$Id$"; int do_net_rrd(char *hostname, char *testname, char *classname, char *pagepaths, char *msg, time_t tstamp) { static char *bbnet_params[] = { "DS:sec:GAUGE:600:0:U", NULL }; static void *bbnet_tpl = NULL; char *p; float seconds = 0.0; if (bbnet_tpl == NULL) bbnet_tpl = setup_template(bbnet_params); if (strcmp(testname, "http") == 0) { char *line1, *url = NULL, *eoln; line1 = msg; while ((line1 = strchr(line1, '\n')) != NULL) { line1++; /* Skip the newline */ eoln = strchr(line1, '\n'); if (eoln) *eoln = '\0'; if ( (strncmp(line1, "&green", 6) == 0) || (strncmp(line1, "&yellow", 7) == 0) || (strncmp(line1, "&red", 4) == 0) ) { p = strstr(line1, "http"); if (p) { url = xstrdup(p); p = strchr(url, ' '); if (p) *p = '\0'; } } else if (url && ((p = strstr(line1, "Seconds:")) != NULL) && (sscanf(p, "Seconds: %f", &seconds) == 1)) { char *urlfn = url; if (strncmp(urlfn, "http://", 7) == 0) urlfn += 7; p = urlfn; while ((p = strchr(p, '/')) != NULL) *p = ','; setupfn3("%s.%s.%s.rrd", "tcp", "http", urlfn); sprintf(rrdvalues, "%d:%.2f", (int)tstamp, seconds); create_and_update_rrd(hostname, testname, classname, pagepaths, bbnet_params, bbnet_tpl); xfree(url); url = NULL; } if (eoln) *eoln = '\n'; } if (url) xfree(url); } else if (strcmp(testname, xgetenv("PINGCOLUMN")) == 0) { /* * Ping-tests, possibly using fping. */ char *tmod = "ms"; if ((p = strstr(msg, "time=")) != NULL) { /* Standard ping, reports ".... time=0.2 ms" */ seconds = atof(p+5); tmod = p + 5; tmod += strspn(tmod, "0123456789. "); } else if ((p = strstr(msg, "alive")) != NULL) { /* fping, reports ".... alive (0.43 ms)" */ seconds = atof(p+7); tmod = p + 7; tmod += strspn(tmod, "0123456789. "); } if (strncmp(tmod, "ms", 2) == 0) seconds = seconds / 1000.0; else if (strncmp(tmod, "usec", 4) == 0) seconds = seconds / 1000000.0; setupfn2("%s.%s.rrd", "tcp", testname); sprintf(rrdvalues, "%d:%.6f", (int)tstamp, seconds); return create_and_update_rrd(hostname, testname, classname, pagepaths, bbnet_params, bbnet_tpl); } else { /* * Normal network tests - pick up the "Seconds:" value */ p = strstr(msg, "\nSeconds:"); if (p && (sscanf(p+1, "Seconds: %f", &seconds) == 1)) { setupfn2("%s.%s.rrd", "tcp", testname); sprintf(rrdvalues, "%d:%.2f", (int)tstamp, seconds); return create_and_update_rrd(hostname, testname, classname, pagepaths, bbnet_params, bbnet_tpl); } } return 0; }
623693.c
/* * Driver for IBM Power 842 compression accelerator * * 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, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * * Copyright (C) IBM Corporation, 2012 * * Authors: Robert Jennings <rcj@linux.vnet.ibm.com> * Seth Jennings <sjenning@linux.vnet.ibm.com> */ #include <linux/kernel.h> #include <linux/module.h> #include <linux/nx842.h> #include <linux/of.h> #include <linux/slab.h> #include <asm/page.h> #include <asm/vio.h> #include "nx_csbcpb.h" /* struct nx_csbcpb */ #define MODULE_NAME "nx-compress" MODULE_LICENSE("GPL"); MODULE_AUTHOR("Robert Jennings <rcj@linux.vnet.ibm.com>"); MODULE_DESCRIPTION("842 H/W Compression driver for IBM Power processors"); #define SHIFT_4K 12 #define SHIFT_64K 16 #define SIZE_4K (1UL << SHIFT_4K) #define SIZE_64K (1UL << SHIFT_64K) /* IO buffer must be 128 byte aligned */ #define IO_BUFFER_ALIGN 128 struct nx842_header { int blocks_nr; /* number of compressed blocks */ int offset; /* offset of the first block (from beginning of header) */ int sizes[0]; /* size of compressed blocks */ }; static inline int nx842_header_size(const struct nx842_header *hdr) { return sizeof(struct nx842_header) + hdr->blocks_nr * sizeof(hdr->sizes[0]); } /* Macros for fields within nx_csbcpb */ /* Check the valid bit within the csbcpb valid field */ #define NX842_CSBCBP_VALID_CHK(x) (x & BIT_MASK(7)) /* CE macros operate on the completion_extension field bits in the csbcpb. * CE0 0=full completion, 1=partial completion * CE1 0=CE0 indicates completion, 1=termination (output may be modified) * CE2 0=processed_bytes is source bytes, 1=processed_bytes is target bytes */ #define NX842_CSBCPB_CE0(x) (x & BIT_MASK(7)) #define NX842_CSBCPB_CE1(x) (x & BIT_MASK(6)) #define NX842_CSBCPB_CE2(x) (x & BIT_MASK(5)) /* The NX unit accepts data only on 4K page boundaries */ #define NX842_HW_PAGE_SHIFT SHIFT_4K #define NX842_HW_PAGE_SIZE (ASM_CONST(1) << NX842_HW_PAGE_SHIFT) #define NX842_HW_PAGE_MASK (~(NX842_HW_PAGE_SIZE-1)) enum nx842_status { UNAVAILABLE, AVAILABLE }; struct ibm_nx842_counters { atomic64_t comp_complete; atomic64_t comp_failed; atomic64_t decomp_complete; atomic64_t decomp_failed; atomic64_t swdecomp; atomic64_t comp_times[32]; atomic64_t decomp_times[32]; }; static struct nx842_devdata { struct vio_dev *vdev; struct device *dev; struct ibm_nx842_counters *counters; unsigned int max_sg_len; unsigned int max_sync_size; unsigned int max_sync_sg; enum nx842_status status; } __rcu *devdata; static DEFINE_SPINLOCK(devdata_mutex); #define NX842_COUNTER_INC(_x) \ static inline void nx842_inc_##_x( \ const struct nx842_devdata *dev) { \ if (dev) \ atomic64_inc(&dev->counters->_x); \ } NX842_COUNTER_INC(comp_complete); NX842_COUNTER_INC(comp_failed); NX842_COUNTER_INC(decomp_complete); NX842_COUNTER_INC(decomp_failed); NX842_COUNTER_INC(swdecomp); #define NX842_HIST_SLOTS 16 static void ibm_nx842_incr_hist(atomic64_t *times, unsigned int time) { int bucket = fls(time); if (bucket) bucket = min((NX842_HIST_SLOTS - 1), bucket - 1); atomic64_inc(&times[bucket]); } /* NX unit operation flags */ #define NX842_OP_COMPRESS 0x0 #define NX842_OP_CRC 0x1 #define NX842_OP_DECOMPRESS 0x2 #define NX842_OP_COMPRESS_CRC (NX842_OP_COMPRESS | NX842_OP_CRC) #define NX842_OP_DECOMPRESS_CRC (NX842_OP_DECOMPRESS | NX842_OP_CRC) #define NX842_OP_ASYNC (1<<23) #define NX842_OP_NOTIFY (1<<22) #define NX842_OP_NOTIFY_INT(x) ((x & 0xff)<<8) static unsigned long nx842_get_desired_dma(struct vio_dev *viodev) { /* No use of DMA mappings within the driver. */ return 0; } struct nx842_slentry { unsigned long ptr; /* Real address (use __pa()) */ unsigned long len; }; /* pHyp scatterlist entry */ struct nx842_scatterlist { int entry_nr; /* number of slentries */ struct nx842_slentry *entries; /* ptr to array of slentries */ }; /* Does not include sizeof(entry_nr) in the size */ static inline unsigned long nx842_get_scatterlist_size( struct nx842_scatterlist *sl) { return sl->entry_nr * sizeof(struct nx842_slentry); } static inline unsigned long nx842_get_pa(void *addr) { if (is_vmalloc_addr(addr)) return page_to_phys(vmalloc_to_page(addr)) + offset_in_page(addr); else return __pa(addr); } static int nx842_build_scatterlist(unsigned long buf, int len, struct nx842_scatterlist *sl) { unsigned long nextpage; struct nx842_slentry *entry; sl->entry_nr = 0; entry = sl->entries; while (len) { entry->ptr = nx842_get_pa((void *)buf); nextpage = ALIGN(buf + 1, NX842_HW_PAGE_SIZE); if (nextpage < buf + len) { /* we aren't at the end yet */ if (IS_ALIGNED(buf, NX842_HW_PAGE_SIZE)) /* we are in the middle (or beginning) */ entry->len = NX842_HW_PAGE_SIZE; else /* we are at the beginning */ entry->len = nextpage - buf; } else { /* at the end */ entry->len = len; } len -= entry->len; buf += entry->len; sl->entry_nr++; entry++; } return 0; } /* * Working memory for software decompression */ struct sw842_fifo { union { char f8[256][8]; char f4[512][4]; }; char f2[256][2]; unsigned char f84_full; unsigned char f2_full; unsigned char f8_count; unsigned char f2_count; unsigned int f4_count; }; /* * Working memory for crypto API */ struct nx842_workmem { char bounce[PAGE_SIZE]; /* bounce buffer for decompression input */ union { /* hardware working memory */ struct { /* scatterlist */ char slin[SIZE_4K]; char slout[SIZE_4K]; /* coprocessor status/parameter block */ struct nx_csbcpb csbcpb; }; /* software working memory */ struct sw842_fifo swfifo; /* software decompression fifo */ }; }; int nx842_get_workmem_size(void) { return sizeof(struct nx842_workmem) + NX842_HW_PAGE_SIZE; } EXPORT_SYMBOL_GPL(nx842_get_workmem_size); int nx842_get_workmem_size_aligned(void) { return sizeof(struct nx842_workmem); } EXPORT_SYMBOL_GPL(nx842_get_workmem_size_aligned); static int nx842_validate_result(struct device *dev, struct cop_status_block *csb) { /* The csb must be valid after returning from vio_h_cop_sync */ if (!NX842_CSBCBP_VALID_CHK(csb->valid)) { dev_err(dev, "%s: cspcbp not valid upon completion.\n", __func__); dev_dbg(dev, "valid:0x%02x cs:0x%02x cc:0x%02x ce:0x%02x\n", csb->valid, csb->crb_seq_number, csb->completion_code, csb->completion_extension); dev_dbg(dev, "processed_bytes:%d address:0x%016lx\n", csb->processed_byte_count, (unsigned long)csb->address); return -EIO; } /* Check return values from the hardware in the CSB */ switch (csb->completion_code) { case 0: /* Completed without error */ break; case 64: /* Target bytes > Source bytes during compression */ case 13: /* Output buffer too small */ dev_dbg(dev, "%s: Compression output larger than input\n", __func__); return -ENOSPC; case 66: /* Input data contains an illegal template field */ case 67: /* Template indicates data past the end of the input stream */ dev_dbg(dev, "%s: Bad data for decompression (code:%d)\n", __func__, csb->completion_code); return -EINVAL; default: dev_dbg(dev, "%s: Unspecified error (code:%d)\n", __func__, csb->completion_code); return -EIO; } /* Hardware sanity check */ if (!NX842_CSBCPB_CE2(csb->completion_extension)) { dev_err(dev, "%s: No error returned by hardware, but " "data returned is unusable, contact support.\n" "(Additional info: csbcbp->processed bytes " "does not specify processed bytes for the " "target buffer.)\n", __func__); return -EIO; } return 0; } /** * nx842_compress - Compress data using the 842 algorithm * * Compression provide by the NX842 coprocessor on IBM Power systems. * The input buffer is compressed and the result is stored in the * provided output buffer. * * Upon return from this function @outlen contains the length of the * compressed data. If there is an error then @outlen will be 0 and an * error will be specified by the return code from this function. * * @in: Pointer to input buffer, must be page aligned * @inlen: Length of input buffer, must be PAGE_SIZE * @out: Pointer to output buffer * @outlen: Length of output buffer * @wrkmem: ptr to buffer for working memory, size determined by * nx842_get_workmem_size() * * Returns: * 0 Success, output of length @outlen stored in the buffer at @out * -ENOMEM Unable to allocate internal buffers * -ENOSPC Output buffer is to small * -EMSGSIZE XXX Difficult to describe this limitation * -EIO Internal error * -ENODEV Hardware unavailable */ int nx842_compress(const unsigned char *in, unsigned int inlen, unsigned char *out, unsigned int *outlen, void *wmem) { struct nx842_header *hdr; struct nx842_devdata *local_devdata; struct device *dev = NULL; struct nx842_workmem *workmem; struct nx842_scatterlist slin, slout; struct nx_csbcpb *csbcpb; int ret = 0, max_sync_size, i, bytesleft, size, hdrsize; unsigned long inbuf, outbuf, padding; struct vio_pfo_op op = { .done = NULL, .handle = 0, .timeout = 0, }; unsigned long start_time = get_tb(); /* * Make sure input buffer is 64k page aligned. This is assumed since * this driver is designed for page compression only (for now). This * is very nice since we can now use direct DDE(s) for the input and * the alignment is guaranteed. */ inbuf = (unsigned long)in; if (!IS_ALIGNED(inbuf, PAGE_SIZE) || inlen != PAGE_SIZE) return -EINVAL; rcu_read_lock(); local_devdata = rcu_dereference(devdata); if (!local_devdata || !local_devdata->dev) { rcu_read_unlock(); return -ENODEV; } max_sync_size = local_devdata->max_sync_size; dev = local_devdata->dev; /* Create the header */ hdr = (struct nx842_header *)out; hdr->blocks_nr = PAGE_SIZE / max_sync_size; hdrsize = nx842_header_size(hdr); outbuf = (unsigned long)out + hdrsize; bytesleft = *outlen - hdrsize; /* Init scatterlist */ workmem = (struct nx842_workmem *)ALIGN((unsigned long)wmem, NX842_HW_PAGE_SIZE); slin.entries = (struct nx842_slentry *)workmem->slin; slout.entries = (struct nx842_slentry *)workmem->slout; /* Init operation */ op.flags = NX842_OP_COMPRESS; csbcpb = &workmem->csbcpb; memset(csbcpb, 0, sizeof(*csbcpb)); op.csbcpb = nx842_get_pa(csbcpb); op.out = nx842_get_pa(slout.entries); for (i = 0; i < hdr->blocks_nr; i++) { /* * Aligning the output blocks to 128 bytes does waste space, * but it prevents the need for bounce buffers and memory * copies. It also simplifies the code a lot. In the worst * case (64k page, 4k max_sync_size), you lose up to * (128*16)/64k = ~3% the compression factor. For 64k * max_sync_size, the loss would be at most 128/64k = ~0.2%. */ padding = ALIGN(outbuf, IO_BUFFER_ALIGN) - outbuf; outbuf += padding; bytesleft -= padding; if (i == 0) /* save offset into first block in header */ hdr->offset = padding + hdrsize; if (bytesleft <= 0) { ret = -ENOSPC; goto unlock; } /* * NOTE: If the default max_sync_size is changed from 4k * to 64k, remove the "likely" case below, since a * scatterlist will always be needed. */ if (likely(max_sync_size == NX842_HW_PAGE_SIZE)) { /* Create direct DDE */ op.in = nx842_get_pa((void *)inbuf); op.inlen = max_sync_size; } else { /* Create indirect DDE (scatterlist) */ nx842_build_scatterlist(inbuf, max_sync_size, &slin); op.in = nx842_get_pa(slin.entries); op.inlen = -nx842_get_scatterlist_size(&slin); } /* * If max_sync_size != NX842_HW_PAGE_SIZE, an indirect * DDE is required for the outbuf. * If max_sync_size == NX842_HW_PAGE_SIZE, outbuf must * also be page aligned (1 in 128/4k=32 chance) in order * to use a direct DDE. * This is unlikely, just use an indirect DDE always. */ nx842_build_scatterlist(outbuf, min(bytesleft, max_sync_size), &slout); /* op.out set before loop */ op.outlen = -nx842_get_scatterlist_size(&slout); /* Send request to pHyp */ ret = vio_h_cop_sync(local_devdata->vdev, &op); /* Check for pHyp error */ if (ret) { dev_dbg(dev, "%s: vio_h_cop_sync error (ret=%d, hret=%ld)\n", __func__, ret, op.hcall_err); ret = -EIO; goto unlock; } /* Check for hardware error */ ret = nx842_validate_result(dev, &csbcpb->csb); if (ret && ret != -ENOSPC) goto unlock; /* Handle incompressible data */ if (unlikely(ret == -ENOSPC)) { if (bytesleft < max_sync_size) { /* * Not enough space left in the output buffer * to store uncompressed block */ goto unlock; } else { /* Store incompressible block */ memcpy((void *)outbuf, (void *)inbuf, max_sync_size); hdr->sizes[i] = -max_sync_size; outbuf += max_sync_size; bytesleft -= max_sync_size; /* Reset ret, incompressible data handled */ ret = 0; } } else { /* Normal case, compression was successful */ size = csbcpb->csb.processed_byte_count; dev_dbg(dev, "%s: processed_bytes=%d\n", __func__, size); hdr->sizes[i] = size; outbuf += size; bytesleft -= size; } inbuf += max_sync_size; } *outlen = (unsigned int)(outbuf - (unsigned long)out); unlock: if (ret) nx842_inc_comp_failed(local_devdata); else { nx842_inc_comp_complete(local_devdata); ibm_nx842_incr_hist(local_devdata->counters->comp_times, (get_tb() - start_time) / tb_ticks_per_usec); } rcu_read_unlock(); return ret; } EXPORT_SYMBOL_GPL(nx842_compress); static int sw842_decompress(const unsigned char *, int, unsigned char *, int *, const void *); /** * nx842_decompress - Decompress data using the 842 algorithm * * Decompression provide by the NX842 coprocessor on IBM Power systems. * The input buffer is decompressed and the result is stored in the * provided output buffer. The size allocated to the output buffer is * provided by the caller of this function in @outlen. Upon return from * this function @outlen contains the length of the decompressed data. * If there is an error then @outlen will be 0 and an error will be * specified by the return code from this function. * * @in: Pointer to input buffer, will use bounce buffer if not 128 byte * aligned * @inlen: Length of input buffer * @out: Pointer to output buffer, must be page aligned * @outlen: Length of output buffer, must be PAGE_SIZE * @wrkmem: ptr to buffer for working memory, size determined by * nx842_get_workmem_size() * * Returns: * 0 Success, output of length @outlen stored in the buffer at @out * -ENODEV Hardware decompression device is unavailable * -ENOMEM Unable to allocate internal buffers * -ENOSPC Output buffer is to small * -EINVAL Bad input data encountered when attempting decompress * -EIO Internal error */ int nx842_decompress(const unsigned char *in, unsigned int inlen, unsigned char *out, unsigned int *outlen, void *wmem) { struct nx842_header *hdr; struct nx842_devdata *local_devdata; struct device *dev = NULL; struct nx842_workmem *workmem; struct nx842_scatterlist slin, slout; struct nx_csbcpb *csbcpb; int ret = 0, i, size, max_sync_size; unsigned long inbuf, outbuf; struct vio_pfo_op op = { .done = NULL, .handle = 0, .timeout = 0, }; unsigned long start_time = get_tb(); /* Ensure page alignment and size */ outbuf = (unsigned long)out; if (!IS_ALIGNED(outbuf, PAGE_SIZE) || *outlen != PAGE_SIZE) return -EINVAL; rcu_read_lock(); local_devdata = rcu_dereference(devdata); if (local_devdata) dev = local_devdata->dev; /* Get header */ hdr = (struct nx842_header *)in; workmem = (struct nx842_workmem *)ALIGN((unsigned long)wmem, NX842_HW_PAGE_SIZE); inbuf = (unsigned long)in + hdr->offset; if (likely(!IS_ALIGNED(inbuf, IO_BUFFER_ALIGN))) { /* Copy block(s) into bounce buffer for alignment */ memcpy(workmem->bounce, in + hdr->offset, inlen - hdr->offset); inbuf = (unsigned long)workmem->bounce; } /* Init scatterlist */ slin.entries = (struct nx842_slentry *)workmem->slin; slout.entries = (struct nx842_slentry *)workmem->slout; /* Init operation */ op.flags = NX842_OP_DECOMPRESS; csbcpb = &workmem->csbcpb; memset(csbcpb, 0, sizeof(*csbcpb)); op.csbcpb = nx842_get_pa(csbcpb); /* * max_sync_size may have changed since compression, * so we can't read it from the device info. We need * to derive it from hdr->blocks_nr. */ max_sync_size = PAGE_SIZE / hdr->blocks_nr; for (i = 0; i < hdr->blocks_nr; i++) { /* Skip padding */ inbuf = ALIGN(inbuf, IO_BUFFER_ALIGN); if (hdr->sizes[i] < 0) { /* Negative sizes indicate uncompressed data blocks */ size = abs(hdr->sizes[i]); memcpy((void *)outbuf, (void *)inbuf, size); outbuf += size; inbuf += size; continue; } if (!dev) goto sw; /* * The better the compression, the more likely the "likely" * case becomes. */ if (likely((inbuf & NX842_HW_PAGE_MASK) == ((inbuf + hdr->sizes[i] - 1) & NX842_HW_PAGE_MASK))) { /* Create direct DDE */ op.in = nx842_get_pa((void *)inbuf); op.inlen = hdr->sizes[i]; } else { /* Create indirect DDE (scatterlist) */ nx842_build_scatterlist(inbuf, hdr->sizes[i] , &slin); op.in = nx842_get_pa(slin.entries); op.inlen = -nx842_get_scatterlist_size(&slin); } /* * NOTE: If the default max_sync_size is changed from 4k * to 64k, remove the "likely" case below, since a * scatterlist will always be needed. */ if (likely(max_sync_size == NX842_HW_PAGE_SIZE)) { /* Create direct DDE */ op.out = nx842_get_pa((void *)outbuf); op.outlen = max_sync_size; } else { /* Create indirect DDE (scatterlist) */ nx842_build_scatterlist(outbuf, max_sync_size, &slout); op.out = nx842_get_pa(slout.entries); op.outlen = -nx842_get_scatterlist_size(&slout); } /* Send request to pHyp */ ret = vio_h_cop_sync(local_devdata->vdev, &op); /* Check for pHyp error */ if (ret) { dev_dbg(dev, "%s: vio_h_cop_sync error (ret=%d, hret=%ld)\n", __func__, ret, op.hcall_err); dev = NULL; goto sw; } /* Check for hardware error */ ret = nx842_validate_result(dev, &csbcpb->csb); if (ret) { dev = NULL; goto sw; } /* HW decompression success */ inbuf += hdr->sizes[i]; outbuf += csbcpb->csb.processed_byte_count; continue; sw: /* software decompression */ size = max_sync_size; ret = sw842_decompress( (unsigned char *)inbuf, hdr->sizes[i], (unsigned char *)outbuf, &size, wmem); if (ret) pr_debug("%s: sw842_decompress failed with %d\n", __func__, ret); if (ret) { if (ret != -ENOSPC && ret != -EINVAL && ret != -EMSGSIZE) ret = -EIO; goto unlock; } /* SW decompression success */ inbuf += hdr->sizes[i]; outbuf += size; } *outlen = (unsigned int)(outbuf - (unsigned long)out); unlock: if (ret) /* decompress fail */ nx842_inc_decomp_failed(local_devdata); else { if (!dev) /* software decompress */ nx842_inc_swdecomp(local_devdata); nx842_inc_decomp_complete(local_devdata); ibm_nx842_incr_hist(local_devdata->counters->decomp_times, (get_tb() - start_time) / tb_ticks_per_usec); } rcu_read_unlock(); return ret; } EXPORT_SYMBOL_GPL(nx842_decompress); /** * nx842_OF_set_defaults -- Set default (disabled) values for devdata * * @devdata - struct nx842_devdata to update * * Returns: * 0 on success * -ENOENT if @devdata ptr is NULL */ static int nx842_OF_set_defaults(struct nx842_devdata *devdata) { if (devdata) { devdata->max_sync_size = 0; devdata->max_sync_sg = 0; devdata->max_sg_len = 0; devdata->status = UNAVAILABLE; return 0; } else return -ENOENT; } /** * nx842_OF_upd_status -- Update the device info from OF status prop * * The status property indicates if the accelerator is enabled. If the * device is in the OF tree it indicates that the hardware is present. * The status field indicates if the device is enabled when the status * is 'okay'. Otherwise the device driver will be disabled. * * @devdata - struct nx842_devdata to update * @prop - struct property point containing the maxsyncop for the update * * Returns: * 0 - Device is available * -EINVAL - Device is not available */ static int nx842_OF_upd_status(struct nx842_devdata *devdata, struct property *prop) { int ret = 0; const char *status = (const char *)prop->value; if (!strncmp(status, "okay", (size_t)prop->length)) { devdata->status = AVAILABLE; } else { dev_info(devdata->dev, "%s: status '%s' is not 'okay'\n", __func__, status); devdata->status = UNAVAILABLE; } return ret; } /** * nx842_OF_upd_maxsglen -- Update the device info from OF maxsglen prop * * Definition of the 'ibm,max-sg-len' OF property: * This field indicates the maximum byte length of a scatter list * for the platform facility. It is a single cell encoded as with encode-int. * * Example: * # od -x ibm,max-sg-len * 0000000 0000 0ff0 * * In this example, the maximum byte length of a scatter list is * 0x0ff0 (4,080). * * @devdata - struct nx842_devdata to update * @prop - struct property point containing the maxsyncop for the update * * Returns: * 0 on success * -EINVAL on failure */ static int nx842_OF_upd_maxsglen(struct nx842_devdata *devdata, struct property *prop) { int ret = 0; const int *maxsglen = prop->value; if (prop->length != sizeof(*maxsglen)) { dev_err(devdata->dev, "%s: unexpected format for ibm,max-sg-len property\n", __func__); dev_dbg(devdata->dev, "%s: ibm,max-sg-len is %d bytes long, expected %lu bytes\n", __func__, prop->length, sizeof(*maxsglen)); ret = -EINVAL; } else { devdata->max_sg_len = (unsigned int)min(*maxsglen, (int)NX842_HW_PAGE_SIZE); } return ret; } /** * nx842_OF_upd_maxsyncop -- Update the device info from OF maxsyncop prop * * Definition of the 'ibm,max-sync-cop' OF property: * Two series of cells. The first series of cells represents the maximums * that can be synchronously compressed. The second series of cells * represents the maximums that can be synchronously decompressed. * 1. The first cell in each series contains the count of the number of * data length, scatter list elements pairs that follow – each being * of the form * a. One cell data byte length * b. One cell total number of scatter list elements * * Example: * # od -x ibm,max-sync-cop * 0000000 0000 0001 0000 1000 0000 01fe 0000 0001 * 0000020 0000 1000 0000 01fe * * In this example, compression supports 0x1000 (4,096) data byte length * and 0x1fe (510) total scatter list elements. Decompression supports * 0x1000 (4,096) data byte length and 0x1f3 (510) total scatter list * elements. * * @devdata - struct nx842_devdata to update * @prop - struct property point containing the maxsyncop for the update * * Returns: * 0 on success * -EINVAL on failure */ static int nx842_OF_upd_maxsyncop(struct nx842_devdata *devdata, struct property *prop) { int ret = 0; const struct maxsynccop_t { int comp_elements; int comp_data_limit; int comp_sg_limit; int decomp_elements; int decomp_data_limit; int decomp_sg_limit; } *maxsynccop; if (prop->length != sizeof(*maxsynccop)) { dev_err(devdata->dev, "%s: unexpected format for ibm,max-sync-cop property\n", __func__); dev_dbg(devdata->dev, "%s: ibm,max-sync-cop is %d bytes long, expected %lu bytes\n", __func__, prop->length, sizeof(*maxsynccop)); ret = -EINVAL; goto out; } maxsynccop = (const struct maxsynccop_t *)prop->value; /* Use one limit rather than separate limits for compression and * decompression. Set a maximum for this so as not to exceed the * size that the header can support and round the value down to * the hardware page size (4K) */ devdata->max_sync_size = (unsigned int)min(maxsynccop->comp_data_limit, maxsynccop->decomp_data_limit); devdata->max_sync_size = min_t(unsigned int, devdata->max_sync_size, SIZE_64K); if (devdata->max_sync_size < SIZE_4K) { dev_err(devdata->dev, "%s: hardware max data size (%u) is " "less than the driver minimum, unable to use " "the hardware device\n", __func__, devdata->max_sync_size); ret = -EINVAL; goto out; } devdata->max_sync_sg = (unsigned int)min(maxsynccop->comp_sg_limit, maxsynccop->decomp_sg_limit); if (devdata->max_sync_sg < 1) { dev_err(devdata->dev, "%s: hardware max sg size (%u) is " "less than the driver minimum, unable to use " "the hardware device\n", __func__, devdata->max_sync_sg); ret = -EINVAL; goto out; } out: return ret; } /** * * nx842_OF_upd -- Handle OF properties updates for the device. * * Set all properties from the OF tree. Optionally, a new property * can be provided by the @new_prop pointer to overwrite an existing value. * The device will remain disabled until all values are valid, this function * will return an error for updates unless all values are valid. * * @new_prop: If not NULL, this property is being updated. If NULL, update * all properties from the current values in the OF tree. * * Returns: * 0 - Success * -ENOMEM - Could not allocate memory for new devdata structure * -EINVAL - property value not found, new_prop is not a recognized * property for the device or property value is not valid. * -ENODEV - Device is not available */ static int nx842_OF_upd(struct property *new_prop) { struct nx842_devdata *old_devdata = NULL; struct nx842_devdata *new_devdata = NULL; struct device_node *of_node = NULL; struct property *status = NULL; struct property *maxsglen = NULL; struct property *maxsyncop = NULL; int ret = 0; unsigned long flags; spin_lock_irqsave(&devdata_mutex, flags); old_devdata = rcu_dereference_check(devdata, lockdep_is_held(&devdata_mutex)); if (old_devdata) of_node = old_devdata->dev->of_node; if (!old_devdata || !of_node) { pr_err("%s: device is not available\n", __func__); spin_unlock_irqrestore(&devdata_mutex, flags); return -ENODEV; } new_devdata = kzalloc(sizeof(*new_devdata), GFP_NOFS); if (!new_devdata) { dev_err(old_devdata->dev, "%s: Could not allocate memory for device data\n", __func__); ret = -ENOMEM; goto error_out; } memcpy(new_devdata, old_devdata, sizeof(*old_devdata)); new_devdata->counters = old_devdata->counters; /* Set ptrs for existing properties */ status = of_find_property(of_node, "status", NULL); maxsglen = of_find_property(of_node, "ibm,max-sg-len", NULL); maxsyncop = of_find_property(of_node, "ibm,max-sync-cop", NULL); if (!status || !maxsglen || !maxsyncop) { dev_err(old_devdata->dev, "%s: Could not locate device properties\n", __func__); ret = -EINVAL; goto error_out; } /* Set ptr to new property if provided */ if (new_prop) { /* Single property */ if (!strncmp(new_prop->name, "status", new_prop->length)) { status = new_prop; } else if (!strncmp(new_prop->name, "ibm,max-sg-len", new_prop->length)) { maxsglen = new_prop; } else if (!strncmp(new_prop->name, "ibm,max-sync-cop", new_prop->length)) { maxsyncop = new_prop; } else { /* * Skip the update, the property being updated * has no impact. */ goto out; } } /* Perform property updates */ ret = nx842_OF_upd_status(new_devdata, status); if (ret) goto error_out; ret = nx842_OF_upd_maxsglen(new_devdata, maxsglen); if (ret) goto error_out; ret = nx842_OF_upd_maxsyncop(new_devdata, maxsyncop); if (ret) goto error_out; out: dev_info(old_devdata->dev, "%s: max_sync_size new:%u old:%u\n", __func__, new_devdata->max_sync_size, old_devdata->max_sync_size); dev_info(old_devdata->dev, "%s: max_sync_sg new:%u old:%u\n", __func__, new_devdata->max_sync_sg, old_devdata->max_sync_sg); dev_info(old_devdata->dev, "%s: max_sg_len new:%u old:%u\n", __func__, new_devdata->max_sg_len, old_devdata->max_sg_len); rcu_assign_pointer(devdata, new_devdata); spin_unlock_irqrestore(&devdata_mutex, flags); synchronize_rcu(); dev_set_drvdata(new_devdata->dev, new_devdata); kfree(old_devdata); return 0; error_out: if (new_devdata) { dev_info(old_devdata->dev, "%s: device disabled\n", __func__); nx842_OF_set_defaults(new_devdata); rcu_assign_pointer(devdata, new_devdata); spin_unlock_irqrestore(&devdata_mutex, flags); synchronize_rcu(); dev_set_drvdata(new_devdata->dev, new_devdata); kfree(old_devdata); } else { dev_err(old_devdata->dev, "%s: could not update driver from hardware\n", __func__); spin_unlock_irqrestore(&devdata_mutex, flags); } if (!ret) ret = -EINVAL; return ret; } /** * nx842_OF_notifier - Process updates to OF properties for the device * * @np: notifier block * @action: notifier action * @update: struct pSeries_reconfig_prop_update pointer if action is * PSERIES_UPDATE_PROPERTY * * Returns: * NOTIFY_OK on success * NOTIFY_BAD encoded with error number on failure, use * notifier_to_errno() to decode this value */ static int nx842_OF_notifier(struct notifier_block *np, unsigned long action, void *update) { struct of_prop_reconfig *upd = update; struct nx842_devdata *local_devdata; struct device_node *node = NULL; rcu_read_lock(); local_devdata = rcu_dereference(devdata); if (local_devdata) node = local_devdata->dev->of_node; if (local_devdata && action == OF_RECONFIG_UPDATE_PROPERTY && !strcmp(upd->dn->name, node->name)) { rcu_read_unlock(); nx842_OF_upd(upd->prop); } else rcu_read_unlock(); return NOTIFY_OK; } static struct notifier_block nx842_of_nb = { .notifier_call = nx842_OF_notifier, }; #define nx842_counter_read(_name) \ static ssize_t nx842_##_name##_show(struct device *dev, \ struct device_attribute *attr, \ char *buf) { \ struct nx842_devdata *local_devdata; \ int p = 0; \ rcu_read_lock(); \ local_devdata = rcu_dereference(devdata); \ if (local_devdata) \ p = snprintf(buf, PAGE_SIZE, "%ld\n", \ atomic64_read(&local_devdata->counters->_name)); \ rcu_read_unlock(); \ return p; \ } #define NX842DEV_COUNTER_ATTR_RO(_name) \ nx842_counter_read(_name); \ static struct device_attribute dev_attr_##_name = __ATTR(_name, \ 0444, \ nx842_##_name##_show,\ NULL); NX842DEV_COUNTER_ATTR_RO(comp_complete); NX842DEV_COUNTER_ATTR_RO(comp_failed); NX842DEV_COUNTER_ATTR_RO(decomp_complete); NX842DEV_COUNTER_ATTR_RO(decomp_failed); NX842DEV_COUNTER_ATTR_RO(swdecomp); static ssize_t nx842_timehist_show(struct device *, struct device_attribute *, char *); static struct device_attribute dev_attr_comp_times = __ATTR(comp_times, 0444, nx842_timehist_show, NULL); static struct device_attribute dev_attr_decomp_times = __ATTR(decomp_times, 0444, nx842_timehist_show, NULL); static ssize_t nx842_timehist_show(struct device *dev, struct device_attribute *attr, char *buf) { char *p = buf; struct nx842_devdata *local_devdata; atomic64_t *times; int bytes_remain = PAGE_SIZE; int bytes; int i; rcu_read_lock(); local_devdata = rcu_dereference(devdata); if (!local_devdata) { rcu_read_unlock(); return 0; } if (attr == &dev_attr_comp_times) times = local_devdata->counters->comp_times; else if (attr == &dev_attr_decomp_times) times = local_devdata->counters->decomp_times; else { rcu_read_unlock(); return 0; } for (i = 0; i < (NX842_HIST_SLOTS - 2); i++) { bytes = snprintf(p, bytes_remain, "%u-%uus:\t%ld\n", i ? (2<<(i-1)) : 0, (2<<i)-1, atomic64_read(&times[i])); bytes_remain -= bytes; p += bytes; } /* The last bucket holds everything over * 2<<(NX842_HIST_SLOTS - 2) us */ bytes = snprintf(p, bytes_remain, "%uus - :\t%ld\n", 2<<(NX842_HIST_SLOTS - 2), atomic64_read(&times[(NX842_HIST_SLOTS - 1)])); p += bytes; rcu_read_unlock(); return p - buf; } static struct attribute *nx842_sysfs_entries[] = { &dev_attr_comp_complete.attr, &dev_attr_comp_failed.attr, &dev_attr_decomp_complete.attr, &dev_attr_decomp_failed.attr, &dev_attr_swdecomp.attr, &dev_attr_comp_times.attr, &dev_attr_decomp_times.attr, NULL, }; static struct attribute_group nx842_attribute_group = { .name = NULL, /* put in device directory */ .attrs = nx842_sysfs_entries, }; static int __init nx842_probe(struct vio_dev *viodev, const struct vio_device_id *id) { struct nx842_devdata *old_devdata, *new_devdata = NULL; unsigned long flags; int ret = 0; spin_lock_irqsave(&devdata_mutex, flags); old_devdata = rcu_dereference_check(devdata, lockdep_is_held(&devdata_mutex)); if (old_devdata && old_devdata->vdev != NULL) { dev_err(&viodev->dev, "%s: Attempt to register more than one instance of the hardware\n", __func__); ret = -1; goto error_unlock; } dev_set_drvdata(&viodev->dev, NULL); new_devdata = kzalloc(sizeof(*new_devdata), GFP_NOFS); if (!new_devdata) { dev_err(&viodev->dev, "%s: Could not allocate memory for device data\n", __func__); ret = -ENOMEM; goto error_unlock; } new_devdata->counters = kzalloc(sizeof(*new_devdata->counters), GFP_NOFS); if (!new_devdata->counters) { dev_err(&viodev->dev, "%s: Could not allocate memory for performance counters\n", __func__); ret = -ENOMEM; goto error_unlock; } new_devdata->vdev = viodev; new_devdata->dev = &viodev->dev; nx842_OF_set_defaults(new_devdata); rcu_assign_pointer(devdata, new_devdata); spin_unlock_irqrestore(&devdata_mutex, flags); synchronize_rcu(); kfree(old_devdata); of_reconfig_notifier_register(&nx842_of_nb); ret = nx842_OF_upd(NULL); if (ret && ret != -ENODEV) { dev_err(&viodev->dev, "could not parse device tree. %d\n", ret); ret = -1; goto error; } rcu_read_lock(); if (dev_set_drvdata(&viodev->dev, rcu_dereference(devdata))) { rcu_read_unlock(); dev_err(&viodev->dev, "failed to set driver data for device\n"); ret = -1; goto error; } rcu_read_unlock(); if (sysfs_create_group(&viodev->dev.kobj, &nx842_attribute_group)) { dev_err(&viodev->dev, "could not create sysfs device attributes\n"); ret = -1; goto error; } return 0; error_unlock: spin_unlock_irqrestore(&devdata_mutex, flags); if (new_devdata) kfree(new_devdata->counters); kfree(new_devdata); error: return ret; } static int __exit nx842_remove(struct vio_dev *viodev) { struct nx842_devdata *old_devdata; unsigned long flags; pr_info("Removing IBM Power 842 compression device\n"); sysfs_remove_group(&viodev->dev.kobj, &nx842_attribute_group); spin_lock_irqsave(&devdata_mutex, flags); old_devdata = rcu_dereference_check(devdata, lockdep_is_held(&devdata_mutex)); of_reconfig_notifier_unregister(&nx842_of_nb); rcu_assign_pointer(devdata, NULL); spin_unlock_irqrestore(&devdata_mutex, flags); synchronize_rcu(); dev_set_drvdata(&viodev->dev, NULL); if (old_devdata) kfree(old_devdata->counters); kfree(old_devdata); return 0; } static struct vio_device_id nx842_driver_ids[] = { {"ibm,compression-v1", "ibm,compression"}, {"", ""}, }; static struct vio_driver nx842_driver = { .name = MODULE_NAME, .probe = nx842_probe, .remove = nx842_remove, .get_desired_dma = nx842_get_desired_dma, .id_table = nx842_driver_ids, }; static int __init nx842_init(void) { struct nx842_devdata *new_devdata; pr_info("Registering IBM Power 842 compression driver\n"); RCU_INIT_POINTER(devdata, NULL); new_devdata = kzalloc(sizeof(*new_devdata), GFP_KERNEL); if (!new_devdata) { pr_err("Could not allocate memory for device data\n"); return -ENOMEM; } new_devdata->status = UNAVAILABLE; RCU_INIT_POINTER(devdata, new_devdata); return vio_register_driver(&nx842_driver); } module_init(nx842_init); static void __exit nx842_exit(void) { struct nx842_devdata *old_devdata; unsigned long flags; pr_info("Exiting IBM Power 842 compression driver\n"); spin_lock_irqsave(&devdata_mutex, flags); old_devdata = rcu_dereference_check(devdata, lockdep_is_held(&devdata_mutex)); rcu_assign_pointer(devdata, NULL); spin_unlock_irqrestore(&devdata_mutex, flags); synchronize_rcu(); if (old_devdata) dev_set_drvdata(old_devdata->dev, NULL); kfree(old_devdata); vio_unregister_driver(&nx842_driver); } module_exit(nx842_exit); /********************************* * 842 software decompressor *********************************/ typedef int (*sw842_template_op)(const char **, int *, unsigned char **, struct sw842_fifo *); static int sw842_data8(const char **, int *, unsigned char **, struct sw842_fifo *); static int sw842_data4(const char **, int *, unsigned char **, struct sw842_fifo *); static int sw842_data2(const char **, int *, unsigned char **, struct sw842_fifo *); static int sw842_ptr8(const char **, int *, unsigned char **, struct sw842_fifo *); static int sw842_ptr4(const char **, int *, unsigned char **, struct sw842_fifo *); static int sw842_ptr2(const char **, int *, unsigned char **, struct sw842_fifo *); /* special templates */ #define SW842_TMPL_REPEAT 0x1B #define SW842_TMPL_ZEROS 0x1C #define SW842_TMPL_EOF 0x1E static sw842_template_op sw842_tmpl_ops[26][4] = { { sw842_data8, NULL}, /* 0 (00000) */ { sw842_data4, sw842_data2, sw842_ptr2, NULL}, { sw842_data4, sw842_ptr2, sw842_data2, NULL}, { sw842_data4, sw842_ptr2, sw842_ptr2, NULL}, { sw842_data4, sw842_ptr4, NULL}, { sw842_data2, sw842_ptr2, sw842_data4, NULL}, { sw842_data2, sw842_ptr2, sw842_data2, sw842_ptr2}, { sw842_data2, sw842_ptr2, sw842_ptr2, sw842_data2}, { sw842_data2, sw842_ptr2, sw842_ptr2, sw842_ptr2,}, { sw842_data2, sw842_ptr2, sw842_ptr4, NULL}, { sw842_ptr2, sw842_data2, sw842_data4, NULL}, /* 10 (01010) */ { sw842_ptr2, sw842_data4, sw842_ptr2, NULL}, { sw842_ptr2, sw842_data2, sw842_ptr2, sw842_data2}, { sw842_ptr2, sw842_data2, sw842_ptr2, sw842_ptr2}, { sw842_ptr2, sw842_data2, sw842_ptr4, NULL}, { sw842_ptr2, sw842_ptr2, sw842_data4, NULL}, { sw842_ptr2, sw842_ptr2, sw842_data2, sw842_ptr2}, { sw842_ptr2, sw842_ptr2, sw842_ptr2, sw842_data2}, { sw842_ptr2, sw842_ptr2, sw842_ptr2, sw842_ptr2}, { sw842_ptr2, sw842_ptr2, sw842_ptr4, NULL}, { sw842_ptr4, sw842_data4, NULL}, /* 20 (10100) */ { sw842_ptr4, sw842_data2, sw842_ptr2, NULL}, { sw842_ptr4, sw842_ptr2, sw842_data2, NULL}, { sw842_ptr4, sw842_ptr2, sw842_ptr2, NULL}, { sw842_ptr4, sw842_ptr4, NULL}, { sw842_ptr8, NULL} }; /* Software decompress helpers */ static uint8_t sw842_get_byte(const char *buf, int bit) { uint8_t tmpl; uint16_t tmp; tmp = htons(*(uint16_t *)(buf)); tmp = (uint16_t)(tmp << bit); tmp = ntohs(tmp); memcpy(&tmpl, &tmp, 1); return tmpl; } static uint8_t sw842_get_template(const char **buf, int *bit) { uint8_t byte; byte = sw842_get_byte(*buf, *bit); byte = byte >> 3; byte &= 0x1F; *buf += (*bit + 5) / 8; *bit = (*bit + 5) % 8; return byte; } /* repeat_count happens to be 5-bit too (like the template) */ static uint8_t sw842_get_repeat_count(const char **buf, int *bit) { uint8_t byte; byte = sw842_get_byte(*buf, *bit); byte = byte >> 2; byte &= 0x3F; *buf += (*bit + 6) / 8; *bit = (*bit + 6) % 8; return byte; } static uint8_t sw842_get_ptr2(const char **buf, int *bit) { uint8_t ptr; ptr = sw842_get_byte(*buf, *bit); (*buf)++; return ptr; } static uint16_t sw842_get_ptr4(const char **buf, int *bit, struct sw842_fifo *fifo) { uint16_t ptr; ptr = htons(*(uint16_t *)(*buf)); ptr = (uint16_t)(ptr << *bit); ptr = ptr >> 7; ptr &= 0x01FF; *buf += (*bit + 9) / 8; *bit = (*bit + 9) % 8; return ptr; } static uint8_t sw842_get_ptr8(const char **buf, int *bit, struct sw842_fifo *fifo) { return sw842_get_ptr2(buf, bit); } /* Software decompress template ops */ static int sw842_data8(const char **inbuf, int *inbit, unsigned char **outbuf, struct sw842_fifo *fifo) { int ret; ret = sw842_data4(inbuf, inbit, outbuf, fifo); if (ret) return ret; ret = sw842_data4(inbuf, inbit, outbuf, fifo); return ret; } static int sw842_data4(const char **inbuf, int *inbit, unsigned char **outbuf, struct sw842_fifo *fifo) { int ret; ret = sw842_data2(inbuf, inbit, outbuf, fifo); if (ret) return ret; ret = sw842_data2(inbuf, inbit, outbuf, fifo); return ret; } static int sw842_data2(const char **inbuf, int *inbit, unsigned char **outbuf, struct sw842_fifo *fifo) { **outbuf = sw842_get_byte(*inbuf, *inbit); (*inbuf)++; (*outbuf)++; **outbuf = sw842_get_byte(*inbuf, *inbit); (*inbuf)++; (*outbuf)++; return 0; } static int sw842_ptr8(const char **inbuf, int *inbit, unsigned char **outbuf, struct sw842_fifo *fifo) { uint8_t ptr; ptr = sw842_get_ptr8(inbuf, inbit, fifo); if (!fifo->f84_full && (ptr >= fifo->f8_count)) return 1; memcpy(*outbuf, fifo->f8[ptr], 8); *outbuf += 8; return 0; } static int sw842_ptr4(const char **inbuf, int *inbit, unsigned char **outbuf, struct sw842_fifo *fifo) { uint16_t ptr; ptr = sw842_get_ptr4(inbuf, inbit, fifo); if (!fifo->f84_full && (ptr >= fifo->f4_count)) return 1; memcpy(*outbuf, fifo->f4[ptr], 4); *outbuf += 4; return 0; } static int sw842_ptr2(const char **inbuf, int *inbit, unsigned char **outbuf, struct sw842_fifo *fifo) { uint8_t ptr; ptr = sw842_get_ptr2(inbuf, inbit); if (!fifo->f2_full && (ptr >= fifo->f2_count)) return 1; memcpy(*outbuf, fifo->f2[ptr], 2); *outbuf += 2; return 0; } static void sw842_copy_to_fifo(const char *buf, struct sw842_fifo *fifo) { unsigned char initial_f2count = fifo->f2_count; memcpy(fifo->f8[fifo->f8_count], buf, 8); fifo->f4_count += 2; fifo->f8_count += 1; if (!fifo->f84_full && fifo->f4_count >= 512) { fifo->f84_full = 1; fifo->f4_count /= 512; } memcpy(fifo->f2[fifo->f2_count++], buf, 2); memcpy(fifo->f2[fifo->f2_count++], buf + 2, 2); memcpy(fifo->f2[fifo->f2_count++], buf + 4, 2); memcpy(fifo->f2[fifo->f2_count++], buf + 6, 2); if (fifo->f2_count < initial_f2count) fifo->f2_full = 1; } static int sw842_decompress(const unsigned char *src, int srclen, unsigned char *dst, int *destlen, const void *wrkmem) { uint8_t tmpl; const char *inbuf; int inbit = 0; unsigned char *outbuf, *outbuf_end, *origbuf, *prevbuf; const char *inbuf_end; sw842_template_op op; int opindex; int i, repeat_count; struct sw842_fifo *fifo; int ret = 0; fifo = &((struct nx842_workmem *)(wrkmem))->swfifo; memset(fifo, 0, sizeof(*fifo)); origbuf = NULL; inbuf = src; inbuf_end = src + srclen; outbuf = dst; outbuf_end = dst + *destlen; while ((tmpl = sw842_get_template(&inbuf, &inbit)) != SW842_TMPL_EOF) { if (inbuf >= inbuf_end) { ret = -EINVAL; goto out; } opindex = 0; prevbuf = origbuf; origbuf = outbuf; switch (tmpl) { case SW842_TMPL_REPEAT: if (prevbuf == NULL) { ret = -EINVAL; goto out; } repeat_count = sw842_get_repeat_count(&inbuf, &inbit) + 1; /* Did the repeat count advance past the end of input */ if (inbuf > inbuf_end) { ret = -EINVAL; goto out; } for (i = 0; i < repeat_count; i++) { /* Would this overflow the output buffer */ if ((outbuf + 8) > outbuf_end) { ret = -ENOSPC; goto out; } memcpy(outbuf, prevbuf, 8); sw842_copy_to_fifo(outbuf, fifo); outbuf += 8; } break; case SW842_TMPL_ZEROS: /* Would this overflow the output buffer */ if ((outbuf + 8) > outbuf_end) { ret = -ENOSPC; goto out; } memset(outbuf, 0, 8); sw842_copy_to_fifo(outbuf, fifo); outbuf += 8; break; default: if (tmpl > 25) { ret = -EINVAL; goto out; } /* Does this go past the end of the input buffer */ if ((inbuf + 2) > inbuf_end) { ret = -EINVAL; goto out; } /* Would this overflow the output buffer */ if ((outbuf + 8) > outbuf_end) { ret = -ENOSPC; goto out; } while (opindex < 4 && (op = sw842_tmpl_ops[tmpl][opindex++]) != NULL) { ret = (*op)(&inbuf, &inbit, &outbuf, fifo); if (ret) { ret = -EINVAL; goto out; } sw842_copy_to_fifo(origbuf, fifo); } } } out: if (!ret) *destlen = (unsigned int)(outbuf - dst); else *destlen = 0; return ret; }
930131.c
/* $OpenBSD$ */ /* * Copyright (c) 2015 Nicholas Marriott <nicholas.marriott@gmail.com> * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF MIND, 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 <sys/types.h> #include <event.h> #include <stdlib.h> #include "tmux.h" static int alerts_fired; static void alerts_timer(int, short, void *); static int alerts_enabled(struct window *, int); static void alerts_callback(int, short, void *); static void alerts_reset(struct window *); static int alerts_action_applies(struct winlink *, const char *); static int alerts_check_all(struct window *); static int alerts_check_bell(struct window *); static int alerts_check_activity(struct window *); static int alerts_check_silence(struct window *); static void alerts_set_message(struct winlink *, const char *, const char *); static TAILQ_HEAD(, window) alerts_list = TAILQ_HEAD_INITIALIZER(alerts_list); static void alerts_timer(__unused int fd, __unused short events, void *arg) { struct window *w = arg; log_debug("@%u alerts timer expired", w->id); alerts_queue(w, WINDOW_SILENCE); } static void alerts_callback(__unused int fd, __unused short events, __unused void *arg) { struct window *w, *w1; int alerts; TAILQ_FOREACH_SAFE(w, &alerts_list, alerts_entry, w1) { alerts = alerts_check_all(w); log_debug("@%u alerts check, alerts %#x", w->id, alerts); w->alerts_queued = 0; TAILQ_REMOVE(&alerts_list, w, alerts_entry); w->flags &= ~WINDOW_ALERTFLAGS; window_remove_ref(w, __func__); } alerts_fired = 0; } static int alerts_action_applies(struct winlink *wl, const char *name) { int action; /* * {bell,activity,silence}-action determines when to alert: none means * nothing happens, current means only do something for the current * window and other means only for windows other than the current. */ action = options_get_number(wl->session->options, name); if (action == ALERT_ANY) return (1); if (action == ALERT_CURRENT) return (wl == wl->session->curw); if (action == ALERT_OTHER) return (wl != wl->session->curw); return (0); } static int alerts_check_all(struct window *w) { int alerts; alerts = alerts_check_bell(w); alerts |= alerts_check_activity(w); alerts |= alerts_check_silence(w); return (alerts); } void alerts_check_session(struct session *s) { struct winlink *wl; RB_FOREACH(wl, winlinks, &s->windows) alerts_check_all(wl->window); } static int alerts_enabled(struct window *w, int flags) { if (flags & WINDOW_BELL) { if (options_get_number(w->options, "monitor-bell")) return (1); } if (flags & WINDOW_ACTIVITY) { if (options_get_number(w->options, "monitor-activity")) return (1); } if (flags & WINDOW_SILENCE) { if (options_get_number(w->options, "monitor-silence") != 0) return (1); } return (0); } void alerts_reset_all(void) { struct window *w; RB_FOREACH(w, windows, &windows) alerts_reset(w); } static void alerts_reset(struct window *w) { struct timeval tv; w->flags &= ~WINDOW_SILENCE; if (event_initialized(&w->alerts_timer)) event_del(&w->alerts_timer); timerclear(&tv); tv.tv_sec = options_get_number(w->options, "monitor-silence"); log_debug("@%u alerts timer reset %u", w->id, (u_int)tv.tv_sec); if (tv.tv_sec != 0) event_add(&w->alerts_timer, &tv); } void alerts_queue(struct window *w, int flags) { alerts_reset(w); if (!event_initialized(&w->alerts_timer)) evtimer_set(&w->alerts_timer, alerts_timer, w); if ((w->flags & flags) != flags) { w->flags |= flags; log_debug("@%u alerts flags added %#x", w->id, flags); } if (alerts_enabled(w, flags)) { if (!w->alerts_queued) { w->alerts_queued = 1; TAILQ_INSERT_TAIL(&alerts_list, w, alerts_entry); window_add_ref(w, __func__); } if (!alerts_fired) { log_debug("alerts check queued (by @%u)", w->id); event_once(-1, EV_TIMEOUT, alerts_callback, NULL, NULL); alerts_fired = 1; } } } static int alerts_check_bell(struct window *w) { struct winlink *wl; struct session *s; if (~w->flags & WINDOW_BELL) return (0); if (!options_get_number(w->options, "monitor-bell")) return (0); TAILQ_FOREACH(wl, &w->winlinks, wentry) wl->session->flags &= ~SESSION_ALERTED; TAILQ_FOREACH(wl, &w->winlinks, wentry) { /* * Bells are allowed even if there is an existing bell (so do * not check WINLINK_BELL). */ s = wl->session; if (s->curw != wl) wl->flags |= WINLINK_BELL; if (!alerts_action_applies(wl, "bell-action")) continue; notify_winlink("alert-bell", wl); if (s->flags & SESSION_ALERTED) continue; s->flags |= SESSION_ALERTED; alerts_set_message(wl, "Bell", "visual-bell"); } return (WINDOW_BELL); } static int alerts_check_activity(struct window *w) { struct winlink *wl; struct session *s; if (~w->flags & WINDOW_ACTIVITY) return (0); if (!options_get_number(w->options, "monitor-activity")) return (0); TAILQ_FOREACH(wl, &w->winlinks, wentry) wl->session->flags &= ~SESSION_ALERTED; TAILQ_FOREACH(wl, &w->winlinks, wentry) { if (wl->flags & WINLINK_ACTIVITY) continue; s = wl->session; if (s->curw != wl) wl->flags |= WINLINK_ACTIVITY; if (!alerts_action_applies(wl, "activity-action")) continue; notify_winlink("alert-activity", wl); if (s->flags & SESSION_ALERTED) continue; s->flags |= SESSION_ALERTED; alerts_set_message(wl, "Activity", "visual-activity"); } return (WINDOW_ACTIVITY); } static int alerts_check_silence(struct window *w) { struct winlink *wl; struct session *s; if (~w->flags & WINDOW_SILENCE) return (0); if (options_get_number(w->options, "monitor-silence") == 0) return (0); TAILQ_FOREACH(wl, &w->winlinks, wentry) wl->session->flags &= ~SESSION_ALERTED; TAILQ_FOREACH(wl, &w->winlinks, wentry) { if (wl->flags & WINLINK_SILENCE) continue; s = wl->session; if (s->curw != wl) wl->flags |= WINLINK_SILENCE; if (!alerts_action_applies(wl, "silence-action")) continue; notify_winlink("alert-silence", wl); if (s->flags & SESSION_ALERTED) continue; s->flags |= SESSION_ALERTED; alerts_set_message(wl, "Silence", "visual-silence"); } return (WINDOW_SILENCE); } static void alerts_set_message(struct winlink *wl, const char *type, const char *option) { struct client *c; int visual; /* * We have found an alert (bell, activity or silence), so we need to * pass it on to the user. For each client attached to this session, * decide whether a bell, message or both is needed. * * If visual-{bell,activity,silence} is on, then a message is * substituted for a bell; if it is off, a bell is sent as normal; both * mean both a bell and message is sent. */ visual = options_get_number(wl->session->options, option); TAILQ_FOREACH(c, &clients, entry) { if (c->session != wl->session || c->flags & CLIENT_CONTROL) continue; if (visual == VISUAL_OFF || visual == VISUAL_BOTH) tty_putcode(&c->tty, TTYC_BEL); if (visual == VISUAL_OFF) continue; if (c->session->curw == wl) status_message_set(c, "%s in current window", type); else status_message_set(c, "%s in window %d", type, wl->idx); } }
145852.c
/* Generated by Nim Compiler v0.15.0 */ /* (c) 2016 Andreas Rumpf */ /* The generated code is subject to the original license. */ #define NIM_INTBITS 64 #include "nimbase.h" #include <stdio.h> typedef struct Tnode292802 Tnode292802; typedef struct NimStringDesc NimStringDesc; typedef struct TGenericSeq TGenericSeq; typedef struct Ttype292840 Ttype292840; typedef struct Tlineinfo191336 Tlineinfo191336; typedef struct Tsym292834 Tsym292834; typedef struct Tident199010 Tident199010; typedef struct Tnodeseq292796 Tnodeseq292796; typedef struct Tllstream282204 Tllstream282204; typedef struct Tidobj199004 Tidobj199004; typedef struct TNimObject TNimObject; typedef struct TNimType TNimType; typedef struct TNimNode TNimNode; typedef struct Ttypeseq292836 Ttypeseq292836; typedef struct TY292960 TY292960; typedef struct Tloc292816 Tloc292816; typedef struct Ropeobj178006 Ropeobj178006; typedef struct TY292929 TY292929; typedef struct Tstrtable292806 Tstrtable292806; typedef struct Tsymseq292804 Tsymseq292804; typedef struct Tlib292820 Tlib292820; typedef struct TY292961 TY292961; typedef struct Tinstantiation292824 Tinstantiation292824; typedef struct Tlistentry147007 Tlistentry147007; struct TGenericSeq { NI len; NI reserved; }; struct NimStringDesc { TGenericSeq Sup; NIM_CHAR data[SEQ_DECL_SIZE]; }; struct Tlineinfo191336 { NI16 line; NI16 col; NI32 fileindex; }; typedef NU16 Tnodeflag292427Set; typedef NU8 Tnodekind292020; struct Tnode292802 { Ttype292840* typ; Tlineinfo191336 info; Tnodeflag292427Set flags; Tnodekind292020 kind; union{ struct {NI64 intval; } S1; struct {NF floatval; } S2; struct {NimStringDesc* strval; } S3; struct {Tsym292834* sym; } S4; struct {Tident199010* ident; } S5; struct {Tnodeseq292796* sons; } S6; } kindU; NimStringDesc* comment; }; typedef NU16 Tmsgkind191002; typedef NU8 Trenderflag311004Set; typedef NU8 char136Set[32]; typedef NU8 Tnimkind3403; typedef NU8 Tnimtypeflag3409Set; typedef N_NIMCALL_PTR(void, TY3489) (void* p0, NI op0); typedef N_NIMCALL_PTR(void*, TY3494) (void* p0); struct TNimType { NI size; Tnimkind3403 kind; Tnimtypeflag3409Set flags; TNimType* base; TNimNode* node; void* finalizer; TY3489 marker; TY3494 deepcopy; }; struct TNimObject { TNimType* m_type; }; struct Tidobj199004 { TNimObject Sup; NI id; }; typedef NU8 Ttypekind292244; typedef NU8 Tcallingconvention292002; typedef NU32 Ttypeflag292431Set; typedef NU8 Tlockind292808; typedef NU8 Tstorageloc292812; typedef NU16 Tlocflag292810Set; struct Tloc292816 { Tlockind292808 k; Tstorageloc292812 s; Tlocflag292810Set flags; Ttype292840* t; Ropeobj178006* r; }; struct Ttype292840 { Tidobj199004 Sup; Ttypekind292244 kind; Tcallingconvention292002 callconv; Ttypeflag292431Set flags; Ttypeseq292836* sons; Tnode292802* n; Tsym292834* owner; Tsym292834* sym; Tsym292834* destructor; Tsym292834* deepcopy; Tsym292834* assignment; TY292960* methods; NI64 size; NI16 align; NI16 locklevel; Tloc292816 loc; }; typedef NU8 Tsymkind292435; struct Tstrtable292806 { NI counter; Tsymseq292804* data; }; typedef NU16 Tmagic292524; typedef NU32 Tsymflag292184Set; typedef NU32 Toption169009Set; struct Tsym292834 { Tidobj199004 Sup; Tsymkind292435 kind; union{ struct {Ttypeseq292836* typeinstcache; } S1; struct {TY292929* procinstcache; Tsym292834* gcunsafetyreason; } S2; struct {TY292929* usedgenerics; Tstrtable292806 tab; } S3; struct {Tsym292834* guard; NI bitsize; } S4; } kindU; Tmagic292524 magic; Ttype292840* typ; Tident199010* name; Tlineinfo191336 info; Tsym292834* owner; Tsymflag292184Set flags; Tnode292802* ast; Toption169009Set options; NI position; NI offset; Tloc292816 loc; Tlib292820* annex; Tnode292802* constraint; }; struct Tident199010 { Tidobj199004 Sup; NimStringDesc* s; Tident199010* next; NI h; }; typedef NU8 Tllstreamkind282202; struct Tllstream282204 { TNimObject Sup; Tllstreamkind282202 kind; FILE* f; NimStringDesc* s; NI rd; NI wr; NI lineoffset; }; typedef NU8 Tnimnodekind3405; struct TNimNode { Tnimnodekind3405 kind; NI offset; TNimType* typ; NCSTRING name; NI len; TNimNode** sons; }; struct TY292961 { NI Field0; Tsym292834* Field1; }; struct Ropeobj178006 { TNimObject Sup; Ropeobj178006* left; Ropeobj178006* right; NI length; NimStringDesc* data; }; struct Tlistentry147007 { TNimObject Sup; Tlistentry147007* prev; Tlistentry147007* next; }; typedef NU8 Tlibkind292818; struct Tlib292820 { Tlistentry147007 Sup; Tlibkind292818 kind; NIM_BOOL generated; NIM_BOOL isoverriden; Ropeobj178006* name; Tnode292802* path; }; struct Tinstantiation292824 { Tsym292834* sym; Ttypeseq292836* concretetypes; NI compilesid; }; struct Tnodeseq292796 { TGenericSeq Sup; Tnode292802* data[SEQ_DECL_SIZE]; }; struct Ttypeseq292836 { TGenericSeq Sup; Ttype292840* data[SEQ_DECL_SIZE]; }; struct TY292960 { TGenericSeq Sup; TY292961 data[SEQ_DECL_SIZE]; }; struct TY292929 { TGenericSeq Sup; Tinstantiation292824* data[SEQ_DECL_SIZE]; }; struct Tsymseq292804 { TGenericSeq Sup; Tsym292834* data[SEQ_DECL_SIZE]; }; N_NIMCALL(Tnode292802*, getarg_315033_1413030668)(Tnode292802* n0, NimStringDesc* name0, NI pos0); N_NIMCALL(NI, sonslen_295351_850551059)(Tnode292802* n0); N_NIMCALL(void, invalidpragma_315029_1413030668)(Tnode292802* n0); N_NIMCALL(void, localerror_196080_155036129)(Tlineinfo191336 info0, Tmsgkind191002 msg0, NimStringDesc* arg0); N_NIMCALL(NimStringDesc*, rendertree_311044_382274130)(Tnode292802* n0, Trenderflag311004Set renderflags0); N_NIMCALL(NIM_BOOL, identeq_199450_791273810)(Tident199010* id0, NimStringDesc* name0); N_NIMCALL(NimStringDesc*, copyString)(NimStringDesc* src0); N_NIMCALL(NimStringDesc*, strarg_315017_1413030668)(Tnode292802* n0, NimStringDesc* name0, NI pos0, NimStringDesc* default_315022_1413030668); N_NIMCALL(NIM_BOOL, boolarg_315023_1413030668)(Tnode292802* n0, NimStringDesc* name0, NI pos0, NIM_BOOL default_315028_1413030668); N_NIMCALL(Tllstream282204*, llstreamopen_282218_597494479)(NimStringDesc* data0); N_NIMCALL(NimStringDesc*, rawNewString)(NI space0); N_NIMCALL(NimStringDesc*, rawNewString)(NI cap0); N_NIMCALL(NIM_BOOL, llstreamreadline_282550_597494479)(Tllstream282204* s0, NimStringDesc** line0); N_NIMCALL(NimStringDesc*, nsuStrip)(NimStringDesc* s0, NIM_BOOL leading0, NIM_BOOL trailing0, char136Set chars0); N_NIMCALL(NIM_BOOL, nsuStartsWith)(NimStringDesc* s0, NimStringDesc* prefix0); N_NIMCALL(void, llstreamwriteln_282608_597494479)(Tllstream282204* s0, NimStringDesc* data0); N_NIMCALL(void, llstreamclose_282278_597494479)(Tllstream282204* s0); N_NIMCALL(NimStringDesc*, nsuReplaceStr)(NimStringDesc* s0, NimStringDesc* sub0, NimStringDesc* by0); STRING_LITERAL(T1413030668_2, "startswith", 10); STRING_LITERAL(T1413030668_3, "", 0); STRING_LITERAL(T1413030668_4, "true", 4); STRING_LITERAL(T1413030668_5, "false", 5); STRING_LITERAL(T1413030668_6, "leading", 7); STRING_LITERAL(T1413030668_7, "trailing", 8); static NIM_CONST char136Set T1413030668_8 = { 0x00, 0x3E, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00} ; STRING_LITERAL(T1413030668_9, "sub", 3); STRING_LITERAL(T1413030668_10, "by", 2); N_NIMCALL(void, invalidpragma_315029_1413030668)(Tnode292802* n0) { NimStringDesc* LOC1; LOC1 = (NimStringDesc*)0; LOC1 = rendertree_311044_382274130(n0, 4); localerror_196080_155036129((*n0).info, ((Tmsgkind191002) 167), LOC1); } N_NIMCALL(Tnode292802*, getarg_315033_1413030668)(Tnode292802* n0, NimStringDesc* name0, NI pos0) { Tnode292802* result0; { result0 = (Tnode292802*)0; result0 = NIM_NIL; { if (!((*n0).kind >= ((Tnodekind292020) 1) && (*n0).kind <= ((Tnodekind292020) 23))) goto LA3; goto BeforeRet; } LA3: ; { NI i_315061_1413030668; NI HEX3Atmp_315090_1413030668; NI LOC6; NI res_315093_1413030668; i_315061_1413030668 = (NI)0; HEX3Atmp_315090_1413030668 = (NI)0; LOC6 = (NI)0; LOC6 = sonslen_295351_850551059(n0); HEX3Atmp_315090_1413030668 = (NI)(LOC6 - ((NI) 1)); res_315093_1413030668 = ((NI) 1); { while (1) { if (!(res_315093_1413030668 <= HEX3Atmp_315090_1413030668)) goto LA8; i_315061_1413030668 = res_315093_1413030668; { if (!((*(*n0).kindU.S6.sons->data[i_315061_1413030668]).kind == ((Tnodekind292020) 33))) goto LA11; { if (!!(((*(*(*n0).kindU.S6.sons->data[i_315061_1413030668]).kindU.S6.sons->data[((NI) 0)]).kind == ((Tnodekind292020) 2)))) goto LA15; invalidpragma_315029_1413030668(n0); } LA15: ; { NIM_BOOL LOC19; LOC19 = (NIM_BOOL)0; LOC19 = identeq_199450_791273810((*(*(*n0).kindU.S6.sons->data[i_315061_1413030668]).kindU.S6.sons->data[((NI) 0)]).kindU.S5.ident, name0); if (!LOC19) goto LA20; result0 = (*(*n0).kindU.S6.sons->data[i_315061_1413030668]).kindU.S6.sons->data[((NI) 1)]; goto BeforeRet; } LA20: ; } goto LA9; LA11: ; { if (!(i_315061_1413030668 == pos0)) goto LA23; result0 = (*n0).kindU.S6.sons->data[i_315061_1413030668]; goto BeforeRet; } goto LA9; LA23: ; LA9: ; res_315093_1413030668 += ((NI) 1); } LA8: ; } } }BeforeRet: ; return result0; } N_NIMCALL(NIM_CHAR, chararg_315011_1413030668)(Tnode292802* n0, NimStringDesc* name0, NI pos0, NIM_CHAR default_315016_1413030668) { NIM_CHAR result0; Tnode292802* x0; result0 = (NIM_CHAR)0; x0 = getarg_315033_1413030668(n0, name0, pos0); { if (!(x0 == NIM_NIL)) goto LA3; result0 = default_315016_1413030668; } goto LA1; LA3: ; { if (!((*x0).kind == ((Tnodekind292020) 5))) goto LA6; result0 = ((NIM_CHAR) (((NI) (((NI) ((*x0).kindU.S1.intval)))))); } goto LA1; LA6: ; { invalidpragma_315029_1413030668(n0); } LA1: ; return result0; } N_NIMCALL(NimStringDesc*, strarg_315017_1413030668)(Tnode292802* n0, NimStringDesc* name0, NI pos0, NimStringDesc* default_315022_1413030668) { NimStringDesc* result0; Tnode292802* x0; result0 = (NimStringDesc*)0; x0 = getarg_315033_1413030668(n0, name0, pos0); { if (!(x0 == NIM_NIL)) goto LA3; result0 = copyString(default_315022_1413030668); } goto LA1; LA3: ; { if (!((*x0).kind >= ((Tnodekind292020) 20) && (*x0).kind <= ((Tnodekind292020) 22))) goto LA6; result0 = copyString((*x0).kindU.S3.strval); } goto LA1; LA6: ; { invalidpragma_315029_1413030668(n0); } LA1: ; return result0; } N_NIMCALL(NIM_BOOL, boolarg_315023_1413030668)(Tnode292802* n0, NimStringDesc* name0, NI pos0, NIM_BOOL default_315028_1413030668) { NIM_BOOL result0; Tnode292802* x0; result0 = (NIM_BOOL)0; x0 = getarg_315033_1413030668(n0, name0, pos0); { if (!(x0 == NIM_NIL)) goto LA3; result0 = default_315028_1413030668; } goto LA1; LA3: ; { NIM_BOOL LOC6; LOC6 = (NIM_BOOL)0; LOC6 = ((*x0).kind == ((Tnodekind292020) 2)); if (!(LOC6)) goto LA7; LOC6 = identeq_199450_791273810((*x0).kindU.S5.ident, ((NimStringDesc*) &T1413030668_4)); LA7: ; if (!LOC6) goto LA8; result0 = NIM_TRUE; } goto LA1; LA8: ; { NIM_BOOL LOC11; LOC11 = (NIM_BOOL)0; LOC11 = ((*x0).kind == ((Tnodekind292020) 2)); if (!(LOC11)) goto LA12; LOC11 = identeq_199450_791273810((*x0).kindU.S5.ident, ((NimStringDesc*) &T1413030668_5)); LA12: ; if (!LOC11) goto LA13; result0 = NIM_FALSE; } goto LA1; LA13: ; { invalidpragma_315029_1413030668(n0); } LA1: ; return result0; } N_NIMCALL(Tllstream282204*, filterstrip_315006_1413030668)(Tllstream282204* stdin_315008_1413030668, NimStringDesc* filename0, Tnode292802* call0) { Tllstream282204* result0; NimStringDesc* pattern0; NIM_BOOL leading0; NIM_BOOL trailing0; NimStringDesc* line0; result0 = (Tllstream282204*)0; pattern0 = strarg_315017_1413030668(call0, ((NimStringDesc*) &T1413030668_2), ((NI) 1), ((NimStringDesc*) &T1413030668_3)); leading0 = boolarg_315023_1413030668(call0, ((NimStringDesc*) &T1413030668_6), ((NI) 2), NIM_TRUE); trailing0 = boolarg_315023_1413030668(call0, ((NimStringDesc*) &T1413030668_7), ((NI) 3), NIM_TRUE); result0 = llstreamopen_282218_597494479(((NimStringDesc*) &T1413030668_3)); line0 = rawNewString(((NI) 80)); { while (1) { NIM_BOOL LOC3; NimStringDesc* stripped0; LOC3 = (NIM_BOOL)0; LOC3 = llstreamreadline_282550_597494479(stdin_315008_1413030668, (&line0)); if (!LOC3) goto LA2; stripped0 = nsuStrip(line0, leading0, trailing0, T1413030668_8); { NIM_BOOL LOC6; LOC6 = (NIM_BOOL)0; LOC6 = ((pattern0 ? pattern0->Sup.len : 0) == ((NI) 0)); if (LOC6) goto LA7; LOC6 = nsuStartsWith(stripped0, pattern0); LA7: ; if (!LOC6) goto LA8; llstreamwriteln_282608_597494479(result0, stripped0); } goto LA4; LA8: ; { llstreamwriteln_282608_597494479(result0, line0); } LA4: ; } LA2: ; } llstreamclose_282278_597494479(stdin_315008_1413030668); return result0; } N_NIMCALL(Tllstream282204*, filterreplace_315001_1413030668)(Tllstream282204* stdin_315003_1413030668, NimStringDesc* filename0, Tnode292802* call0) { Tllstream282204* result0; NimStringDesc* sub0; NimStringDesc* by0; NimStringDesc* line0; result0 = (Tllstream282204*)0; sub0 = strarg_315017_1413030668(call0, ((NimStringDesc*) &T1413030668_9), ((NI) 1), ((NimStringDesc*) &T1413030668_3)); { if (!((sub0 ? sub0->Sup.len : 0) == ((NI) 0))) goto LA3; invalidpragma_315029_1413030668(call0); } LA3: ; by0 = strarg_315017_1413030668(call0, ((NimStringDesc*) &T1413030668_10), ((NI) 2), ((NimStringDesc*) &T1413030668_3)); result0 = llstreamopen_282218_597494479(((NimStringDesc*) &T1413030668_3)); line0 = rawNewString(((NI) 80)); { while (1) { NIM_BOOL LOC7; NimStringDesc* LOC8; LOC7 = (NIM_BOOL)0; LOC7 = llstreamreadline_282550_597494479(stdin_315003_1413030668, (&line0)); if (!LOC7) goto LA6; LOC8 = (NimStringDesc*)0; LOC8 = nsuReplaceStr(line0, sub0, by0); llstreamwriteln_282608_597494479(result0, LOC8); } LA6: ; } llstreamclose_282278_597494479(stdin_315003_1413030668); return result0; } NIM_EXTERNC N_NOINLINE(void, compiler_filtersInit000)(void) { } NIM_EXTERNC N_NOINLINE(void, compiler_filtersDatInit000)(void) { }
444387.c
#include <sys/socket.h> #include <sys/types.h> #include <netinet/in.h> #include <netdb.h> #include <stdio.h> #include <string.h> #include <stdlib.h> #include <unistd.h> #include <errno.h> #include <arpa/inet.h> int main(int argc, char *argv[]) { int sockfd = 0, n = 0; char recvBuff[1024]; struct sockaddr_in serv_addr; if(argc != 2) { printf("\n Usage: %s <ip of server> \n",argv[0]); return 1; } memset(recvBuff, '0',sizeof(recvBuff)); if((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) { printf("\n Error : Could not create socket \n"); return 1; } memset(&serv_addr, '0', sizeof(serv_addr)); serv_addr.sin_family = AF_INET; serv_addr.sin_port = htons(5000); if(inet_pton(AF_INET, argv[1], &serv_addr.sin_addr)<=0) { printf("\n inet_pton error occured\n"); return 1; } if( connect(sockfd, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0) { printf("\n Error : Connect Failed \n"); return 1; } while ( (n = read(sockfd, recvBuff, sizeof(recvBuff)-1)) > 0) { recvBuff[n] = 0; if(fputs(recvBuff, stdout) == EOF) { printf("\n Error : Fputs error\n"); } } if(n < 0) { printf("\n Read error \n"); } return 0; }
284571.c
/* +----------------------------------------------------------------------+ | PHP Version 5 | +----------------------------------------------------------------------+ | Copyright (c) 1997-2012 The PHP Group | +----------------------------------------------------------------------+ | This source file is subject to version 3.01 of the PHP license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.php.net/license/3_01.txt | | If you did not receive a copy of the PHP license and are unable to | | obtain it through the world-wide-web, please send a note to | | license@php.net so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Author: | +----------------------------------------------------------------------+ */ /* $Id$ */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <stdio.h> #include <string.h> #include "php.h" #include "php_ini.h" #include "main/SAPI.h" #include "ext/standard/php_string.h" #include "php_load_config.h" ZEND_DECLARE_MODULE_GLOBALS(config) /* True global resources - no need for thread safety here */ static int le_config; /* {{{ config_functions[] * * Every user visible function must have an entry in config_functions[]. */ const zend_function_entry config_functions[] = { PHP_FE(config, NULL) /* For testing, remove later. */ { NULL, NULL, NULL, 0, 0 } /* Must be the last line in config_functions[] */ }; /* }}} */ /* {{{ config_module_entry */ zend_module_entry config_module_entry = { #if ZEND_MODULE_API_NO >= 20010901 STANDARD_MODULE_HEADER, #endif "config", config_functions, PHP_MINIT(config), PHP_MSHUTDOWN(config), PHP_RINIT(config), /* Replace with NULL if there's nothing to do at request start */ PHP_RSHUTDOWN(config), /* Replace with NULL if there's nothing to do at request end */ PHP_MINFO(config), #if ZEND_MODULE_API_NO >= 20010901 "0.1", /* Replace with version number for your extension */ #endif STANDARD_MODULE_PROPERTIES }; /* }}} */ #ifdef COMPILE_DL_CONFIG ZEND_GET_MODULE(config) #endif /* {{{ PHP_INI */ PHP_INI_BEGIN() STD_PHP_INI_ENTRY("config.path", "", PHP_INI_SYSTEM, OnUpdateString, path, zend_config_globals, config_globals) PHP_INI_END() /* }}} */ static void php_config_init_globals(zend_config_globals *config_globals) { config_globals->path = NULL; config_globals->slist = NULL; } static ulong time33(const char *arKey, uint nKeyLength) { register ulong hash = 5381; /* variant with the hash unrolled eight times */ for (; nKeyLength >= 8; nKeyLength -= 8) { hash = ((hash << 5) + hash) + *arKey++; hash = ((hash << 5) + hash) + *arKey++; hash = ((hash << 5) + hash) + *arKey++; hash = ((hash << 5) + hash) + *arKey++; hash = ((hash << 5) + hash) + *arKey++; hash = ((hash << 5) + hash) + *arKey++; hash = ((hash << 5) + hash) + *arKey++; hash = ((hash << 5) + hash) + *arKey++; } switch (nKeyLength) { case 7: hash = ((hash << 5) + hash) + *arKey++; /* fallthrough... */ case 6: hash = ((hash << 5) + hash) + *arKey++; /* fallthrough... */ case 5: hash = ((hash << 5) + hash) + *arKey++; /* fallthrough... */ case 4: hash = ((hash << 5) + hash) + *arKey++; /* fallthrough... */ case 3: hash = ((hash << 5) + hash) + *arKey++; /* fallthrough... */ case 2: hash = ((hash << 5) + hash) + *arKey++; /* fallthrough... */ case 1: hash = ((hash << 5) + hash) + *arKey++; break; case 0: break; EMPTY_SWITCH_DEFAULT_CASE() } return hash; } /** * 检测key是否已经存在 * @param slist 单项列表 * @param key 键名 * @param key_len 键名长度 * @return int 大于0表示已经存在,否则返回0 */ static int slist_key_exists(SLIST *slist, char *key, int key_len){ node *cur; if(slist->length == 0) return 0; cur = slist->first; while(cur != NULL){ if(cur->hashcode == key_len && strcmp(cur->key, key) == 0){ return 1; } cur = cur->next; } return 0; } static int slist_add_item(SLIST *slist, char *key, int key_len, char *val, int val_len){ node *cur, *last; if(slist_key_exists(slist, key, key_len)){ return 0; } cur = (node *)pemalloc(sizeof(node), 1); cur->next = NULL; cur->key = pestrdup(key, 1); cur->hashcode = time33(key, key_len); cur->data = pestrdup(val, 1); if(slist->length == 0){ slist->first = cur; slist->last = cur; }else{ last = slist->last; while(1){ if(last->next == NULL){ last->next = cur; break; }else{ last = last->next; } } } slist->length++; return 1; } static int slist_find_item(SLIST *slist, char *key, int key_len, char **data){ node *cur; if(slist->length == 0) return 0; cur = slist->first; while(cur != NULL){ if(cur->hashcode == time33(key, key_len) && strcmp(cur->key, key) == 0){ *data = cur->data; return SUCCESS; } cur = cur->next; } return FAILURE; } static int php_config_initlize(zval *file_path, int module_number){ char content[1024] = {0}; FILE *fp; int file_exists; SLIST *slist; struct stat file_stat; int action = CONFIG_TYPE_UNKONW; //0:定义define, 1:定义array, -1:不操作 slist = CONFIG_G(slist); file_exists = VCWD_STAT(Z_STRVAL_P(file_path), &file_stat); if(file_exists != 0){ zend_error(E_WARNING, "file:%s not exists!", Z_STRVAL_P(file_path)); return 1; } fp = VCWD_FOPEN(Z_STRVAL_P(file_path), "r"); while(fgets(content, 1024, fp)){ char *trim_content, *temp_content; char *p; temp_content = estrndup(content, strlen(content)+1); trim_content = php_trim(temp_content, strlen(temp_content), NULL, 0, NULL, 3 TSRMLS_CC); if(strlen(trim_content) == 0 || trim_content[0] == ';') { efree(temp_content); continue; } p = strstr(trim_content, "="); if(!p && strcmp(trim_content, "[define]") == 0){ action = CONFIG_TYPE_DEFINE; }else if(!p && strcmp(trim_content, "[config]") == 0){ action = CONFIG_TYPE_CONFIG; }else if(p){ char *key; char *trim_key, *trim_val; int trim_val_len, trim_key_len; zend_constant c; key = estrndup(trim_content, strlen(trim_content) - strlen(p)); trim_val = p+1; trim_val_len= strlen(trim_val); trim_key = php_trim(key, strlen(key), NULL, 0, NULL, 3 TSRMLS_CC); trim_val = php_trim(trim_val, trim_val_len, NULL, 0, NULL, 3 TSRMLS_CC); trim_val_len = strlen(trim_val); trim_key_len = strlen(trim_key); switch(action){ //未定义操作 case CONFIG_TYPE_UNKONW: break; case CONFIG_TYPE_DEFINE: c.value.type = IS_STRING; c.value.value.str.val = pestrdup(trim_val, trim_val_len+1); c.value.value.str.len = trim_val_len; c.flags = CONST_PERSISTENT | CONST_CS; c.name = pestrdup(trim_key, trim_key_len+1); c.name_len = trim_key_len+1; c.module_number = module_number; zend_register_constant(&c TSRMLS_CC); break; case CONFIG_TYPE_CONFIG: slist_add_item(slist, trim_key, trim_key_len, trim_val, trim_val_len); break; } efree(key); efree(trim_val); efree(trim_key); } // free(p); efree(trim_content); efree(temp_content); } } /* {{{ PHP_MINIT_FUNCTION */ PHP_MINIT_FUNCTION(config) { zval *delim, *explode_arr, *explode_strs; HashTable *files; php_config_init_globals(&config_globals); REGISTER_INI_ENTRIES(); config_globals.slist = (SLIST *)pemalloc(sizeof(SLIST), 1); config_globals.slist->last = NULL; config_globals.slist->first = NULL; config_globals.slist->length= 0; MAKE_STD_ZVAL(delim); MAKE_STD_ZVAL(explode_strs); MAKE_STD_ZVAL(explode_arr); array_init(explode_arr); ZVAL_STRING(delim, ",", 1); ZVAL_STRING(explode_strs, CONFIG_G(path), 1); php_explode(delim, explode_strs, explode_arr, LONG_MAX); files = Z_ARRVAL_P(explode_arr); for ( zend_hash_internal_pointer_reset(files); zend_hash_has_more_elements(files) == SUCCESS; zend_hash_move_forward(files) ){ zval **file_path; if(zend_hash_get_current_data(files, (void**)&file_path) == FAILURE){ continue; } if(Z_STRLEN_PP(file_path) > 0){ php_config_initlize(*file_path, module_number); } } zend_hash_destroy(Z_ARRVAL_P(explode_arr)); efree(Z_STRVAL_P(explode_strs)); efree(Z_STRVAL_P(delim)); efree(delim); efree(explode_strs); efree(explode_arr); return SUCCESS; } /* }}} */ /* {{{ PHP_MSHUTDOWN_FUNCTION */ PHP_MSHUTDOWN_FUNCTION(config) { /* uncomment this line if you have INI entries*/ UNREGISTER_INI_ENTRIES(); return SUCCESS; } /* }}} */ /* Remove if there's nothing to do at request start */ /* {{{ PHP_RINIT_FUNCTION */ PHP_RINIT_FUNCTION(config) { return SUCCESS; } /* }}} */ /* Remove if there's nothing to do at request end */ /* {{{ PHP_RSHUTDOWN_FUNCTION */ PHP_RSHUTDOWN_FUNCTION(config) { return SUCCESS; } /* }}} */ /* {{{ PHP_MINFO_FUNCTION */ PHP_MINFO_FUNCTION(config) { php_info_print_table_start(); php_info_print_table_header(2, "config support", "enabled"); php_info_print_table_end(); /* Remove comments if you have entries in php.ini */ DISPLAY_INI_ENTRIES(); } /* }}} */ /** * 读取或设置配置 * @param string $key 配置键名 * function config(string $key); */ PHP_FUNCTION(config) { char *key = NULL; int key_len; SLIST *slist; char *data; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &key, &key_len) == FAILURE) { return; } slist = CONFIG_G(slist); if(slist_find_item(slist, key, key_len, &data) == SUCCESS){ RETURN_STRING(data, 1); } RETURN_NULL(); } /* }}} */ /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: noet sw=4 ts=4 fdm=marker * vim<600: noet sw=4 ts=4 */
896906.c
/* * Copyright (c) 1997 Erez Zadok * Copyright (c) 1990 Jan-Simon Pendry * Copyright (c) 1990 Imperial College of Science, Technology & Medicine * Copyright (c) 1990 The Regents of the University of California. * All rights reserved. * * This code is derived from software contributed to Berkeley by * Jan-Simon Pendry at Imperial College, London. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. All advertising materials mentioning features or use of this software * must display the following acknowledgement: * This product includes software developed by the University of * California, Berkeley and its contributors. * 4. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * %W% (Berkeley) %G% * * $Id: info_file.c,v 1.1.1.2 1997/12/22 22:28:23 cgd Exp $ * */ /* * Get info from file */ #ifdef HAVE_CONFIG_H # include <config.h> #endif /* HAVE_CONFIG_H */ #include <am_defs.h> #include <amd.h> #define MAX_LINE_LEN 2048 /* forward declarations */ int file_init(mnt_map *m, char *map, time_t *tp); int file_reload(mnt_map *m, char *map, void (*fn) (mnt_map *, char *, char *)); int file_search(mnt_map *m, char *map, char *key, char **pval, time_t *tp); int file_mtime(mnt_map *m, char *map, time_t *tp); static int read_line(char *buf, int size, FILE * fp) { int done = 0; do { while (fgets(buf, size, fp)) { int len = strlen(buf); done += len; if (len > 1 && buf[len - 2] == '\\' && buf[len - 1] == '\n') { int ch; buf += len - 2; size -= len - 2; *buf = '\n'; buf[1] = '\0'; /* * Skip leading white space on next line */ while ((ch = getc(fp)) != EOF && isascii(ch) && isspace(ch)) ; (void) ungetc(ch, fp); } else { return done; } } } while (size > 0 && !feof(fp)); return done; } /* * Try to locate a key in a file */ static int search_or_reload_file(FILE * fp, char *map, char *key, char **val, mnt_map *m, void (*fn) (mnt_map *m, char *, char *)) { char key_val[MAX_LINE_LEN]; int chuck = 0; int line_no = 0; while (read_line(key_val, sizeof(key_val), fp)) { char *kp; char *cp; char *hash; int len = strlen(key_val); line_no++; /* * Make sure we got the whole line */ if (key_val[len - 1] != '\n') { plog(XLOG_WARNING, "line %d in \"%s\" is too long", line_no, map); chuck = 1; } else { key_val[len - 1] = '\0'; } /* * Strip comments */ hash = strchr(key_val, '#'); if (hash) *hash = '\0'; /* * Find start of key */ for (kp = key_val; *kp && isascii(*kp) && isspace(*kp); kp++) ; /* * Ignore blank lines */ if (!*kp) goto again; /* * Find end of key */ for (cp = kp; *cp && (!isascii(*cp) || !isspace(*cp)); cp++) ; /* * Check whether key matches */ if (*cp) *cp++ = '\0'; if (fn || (*key == *kp && STREQ(key, kp))) { while (*cp && isascii(*cp) && isspace(*cp)) cp++; if (*cp) { /* * Return a copy of the data */ char *dc = strdup(cp); if (fn) { (*fn) (m, strdup(kp), dc); } else { *val = dc; #ifdef DEBUG dlog("%s returns %s", key, dc); #endif /* DEBUG */ } if (!fn) return 0; } else { plog(XLOG_USER, "%s: line %d has no value field", map, line_no); } } again: /* * If the last read didn't get a whole line then * throw away the remainder before continuing... */ if (chuck) { while (fgets(key_val, sizeof(key_val), fp) && !strchr(key_val, '\n')) ; chuck = 0; } } return fn ? 0 : ENOENT; } static FILE * file_open(char *map, time_t *tp) { FILE *mapf = fopen(map, "r"); if (mapf && tp) { struct stat stb; if (fstat(fileno(mapf), &stb) < 0) *tp = clocktime(); else *tp = stb.st_mtime; } return mapf; } int file_init(mnt_map *m, char *map, time_t *tp) { FILE *mapf = file_open(map, tp); if (mapf) { fclose(mapf); return 0; } return errno; } int file_reload(mnt_map *m, char *map, void (*fn) (mnt_map *, char *, char *)) { FILE *mapf = file_open(map, (time_t *) 0); if (mapf) { int error = search_or_reload_file(mapf, map, 0, 0, m, fn); (void) fclose(mapf); return error; } return errno; } int file_search(mnt_map *m, char *map, char *key, char **pval, time_t *tp) { time_t t; FILE *mapf = file_open(map, &t); if (mapf) { int error; if (*tp < t) { *tp = t; error = -1; } else { error = search_or_reload_file(mapf, map, key, pval, 0, 0); } (void) fclose(mapf); return error; } return errno; } int file_mtime(mnt_map *m, char *map, time_t *tp) { FILE *mapf = file_open(map, tp); if (mapf) { (void) fclose(mapf); return 0; } return errno; }
839144.c
#include "dump_gl_screen.h" #include "write_bmp.h" #include <stdlib.h> void dump_gl_screen(const char *filename, GLsizei width, GLsizei height) { void *data; if(width==0 || height==0) return; data = malloc(width * height * 4); if(!data) return; glReadPixels(0, 0, width, height, GL_RGBA, GL_UNSIGNED_BYTE, data); bmp_dump32((char*)data, width, height, false, filename); free(data); }
462749.c
/* * Licensed to the OpenAirInterface (OAI) Software Alliance under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The OpenAirInterface Software Alliance licenses this file to You under * the terms found in the LICENSE file in the root of this source tree. * * 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. *------------------------------------------------------------------------------- * For more information about the OpenAirInterface (OAI) Software Alliance: * contact@openairinterface.org */ #include <stdbool.h> #include <stdlib.h> #include "lte/gateway/c/core/oai/common/common_defs.h" #include "lte/gateway/c/core/oai/common/common_types.h" #include "lte/gateway/c/core/oai/common/dynamic_memory_check.h" #include "lte/gateway/c/core/oai/common/log.h" #include "lte/gateway/c/core/oai/include/mme_app_ue_context.h" #include "lte/gateway/c/core/oai/lib/3gpp/3gpp_24.007.h" #include "lte/gateway/c/core/oai/lib/bstr/bstrlib.h" #include "lte/gateway/c/core/oai/tasks/mme_app/mme_app_timer.h" #include "lte/gateway/c/core/oai/tasks/nas/api/mme/mme_api.h" #include "lte/gateway/c/core/oai/tasks/nas/emm/emm_data.h" #include "lte/gateway/c/core/oai/tasks/nas/esm/esm_ebr.h" #include "lte/gateway/c/core/oai/tasks/nas/esm/esm_ebr_context.h" /****************************************************************************/ /**************** E X T E R N A L D E F I N I T I O N S ****************/ /****************************************************************************/ #define ESM_EBR_NB_UE_MAX (MME_API_NB_UE_MAX + 1) /****************************************************************************/ /******************* L O C A L D E F I N I T I O N S *******************/ /****************************************************************************/ /* String representation of EPS bearer context status */ static const char* esm_ebr_state_str[ESM_EBR_STATE_MAX] = { "BEARER CONTEXT INACTIVE", "BEARER CONTEXT ACTIVE", "BEARER CONTEXT INACTIVE PENDING", "BEARER CONTEXT MODIFY PENDING", "BEARER CONTEXT ACTIVE PENDING"}; /* ---------------------- User notification data ---------------------- */ /* Returns the index of the next available entry in the list of EPS bearer context data */ static int esm_ebr_get_available_entry(emm_context_t* emm_context); /****************************************************************************/ /****************** E X P O R T E D F U N C T I O N S ******************/ /****************************************************************************/ //------------------------------------------------------------------------------ const char* esm_ebr_state2string(esm_ebr_state esm_ebr_state) { switch (esm_ebr_state) { case ESM_EBR_INACTIVE: return "ESM_EBR_INACTIVE"; case ESM_EBR_ACTIVE: return "ESM_EBR_ACTIVE"; case ESM_EBR_INACTIVE_PENDING: return "ESM_EBR_INACTIVE_PENDING"; case ESM_EBR_MODIFY_PENDING: return "ESM_EBR_MODIFY_PENDING"; case ESM_EBR_ACTIVE_PENDING: return "ESM_EBR_ACTIVE_PENDING"; default: return "UNKNOWN"; } } /**************************************************************************** ** ** ** Name: esm_ebr_initialize() ** ** ** ** Description: Initialize EPS bearer context data ** ** ** ** Inputs: cb: User notification callback ** ** Others: None ** ** ** ** Outputs: None ** ** Return: None ** ** Others: _esm_ebr_data ** ** ** ***************************************************************************/ void esm_ebr_initialize(void) { OAILOG_FUNC_IN(LOG_NAS_ESM); OAILOG_FUNC_OUT(LOG_NAS_ESM); } /**************************************************************************** ** ** ** Name: esm_ebr_assign() ** ** ** ** Description: Assigns a new EPS bearer context ** ** ** ** Inputs: emm_context: context where new EBI is created ** ** ** ** Outputs: None ** ** Return: The identity of the new EPS bearer context ** ** if successfully assigned; ** ** the not assigned EBI (0) otherwise. ** ** Others: _esm_ebr_data ** ** ** ***************************************************************************/ status_code_e esm_ebr_assign(emm_context_t* emm_context) { OAILOG_FUNC_IN(LOG_NAS_ESM); ue_mm_context_t* ue_context_p = PARENT_STRUCT(emm_context, struct ue_mm_context_s, emm_context); int i = esm_ebr_get_available_entry(emm_context); if (i < 0) { OAILOG_FUNC_RETURN(LOG_NAS_ESM, ESM_EBI_UNASSIGNED); } OAILOG_DEBUG_UE(LOG_NAS_ESM, emm_context->_imsi64, "ESM-FSM - EPS bearer identity = %u assigned for " "ue_id:" MME_UE_S1AP_ID_FMT "\n", INDEX_TO_EBI(i), ue_context_p->mme_ue_s1ap_id); OAILOG_FUNC_RETURN(LOG_NAS_ESM, INDEX_TO_EBI(i)); } /**************************************************************************** ** ** ** Name: esm_ebr_release() ** ** ** ** Description: Release the given EPS bearer identity ** ** ** ** Inputs: ue_id: Lower layers UE identifier ** ** ebi: The identity of the EPS bearer context to ** ** be released ** ** Others: None ** ** ** ** Outputs: None ** ** Return: RETURNok if the EPS bearer context has ** ** been successfully released; ** ** RETURNerror otherwise. ** ** Others: _esm_ebr_data ** ** ** ***************************************************************************/ status_code_e esm_ebr_release(emm_context_t* emm_context, ebi_t ebi) { OAILOG_FUNC_IN(LOG_NAS_ESM); esm_ebr_context_t* ebr_ctx = NULL; bearer_context_t* bearer_context = NULL; if ((ebi < ESM_EBI_MIN) || (ebi > ESM_EBI_MAX)) { OAILOG_FUNC_RETURN(LOG_NAS_ESM, RETURNerror); } ue_mm_context_t* ue_mm_context = PARENT_STRUCT(emm_context, struct ue_mm_context_s, emm_context); /* * Get EPS bearer context data */ bearer_context = ue_mm_context->bearer_contexts[EBI_TO_INDEX(ebi)]; if ((bearer_context == NULL) || (bearer_context->ebi != ebi)) { /* * EPS bearer context not assigned */ OAILOG_FUNC_RETURN(LOG_NAS_ESM, RETURNerror); } ebr_ctx = &bearer_context->esm_ebr_context; /* * Do not release active EPS bearer context */ if (ebr_ctx->status != ESM_EBR_INACTIVE) { OAILOG_ERROR_UE(LOG_NAS_ESM, ue_mm_context->emm_context._imsi64, "ESM-FSM - EPS bearer context is not INACTIVE for ue " "id " MME_UE_S1AP_ID_FMT "\n", ue_mm_context->mme_ue_s1ap_id); OAILOG_FUNC_RETURN(LOG_NAS_ESM, RETURNerror); } /* * Stop the retransmission timer if still running */ if (ebr_ctx->timer.id != NAS_TIMER_INACTIVE_ID || ebr_ctx->args) { OAILOG_INFO_UE(LOG_NAS_ESM, ue_mm_context->emm_context._imsi64, "ESM-FSM - Stop retransmission timer %ld for ue " "id " MME_UE_S1AP_ID_FMT "\n", ebr_ctx->timer.id, ue_mm_context->mme_ue_s1ap_id); esm_ebr_timer_data_t* esm_ebr_timer_data = ebr_ctx->args; // stop the timer if it's running if (ebr_ctx->timer.id != NAS_TIMER_INACTIVE_ID) { nas_timer_stop(&(ebr_ctx->timer)); } /* * Release the retransmisison timer parameters */ if (esm_ebr_timer_data) { if (esm_ebr_timer_data->msg) { bdestroy_wrapper(&esm_ebr_timer_data->msg); } free_wrapper((void**)&esm_ebr_timer_data); } ebr_ctx->args = NULL; } /* * Release EPS bearer context data */ // struct attribute of another struct, no free OAILOG_INFO_UE( LOG_NAS_ESM, ue_mm_context->emm_context._imsi64, "ESM-FSM - EPS bearer context %d released for ue id " MME_UE_S1AP_ID_FMT "\n", ebi, ue_mm_context->mme_ue_s1ap_id); OAILOG_FUNC_RETURN(LOG_NAS_ESM, RETURNok); } /**************************************************************************** ** ** ** Name: esm_ebr_start_timer() ** ** ** ** Description: Start the timer of the specified EPS bearer context to ** ** expire after a given time interval. Timer expiration will ** ** schedule execution of the callback function where stored ** ** ESM message should be re-transmit. ** ** ** ** Inputs: ue_id: Lower layers UE identifier ** ** ebi: The identity of the EPS bearer ** ** msg: The encoded ESM message to be stored ** ** sec: The value of the time interval in seconds ** ** cb: Function executed upon timer expiration ** ** Others: None ** ** ** ** Outputs: None ** ** Return: RETURNok, RETURNerror ** ** Others: _esm_ebr_data ** ** ** ***************************************************************************/ status_code_e esm_ebr_start_timer(emm_context_t* emm_context, ebi_t ebi, CLONE_REF const_bstring msg, uint32_t msec, time_out_t cb) { OAILOG_FUNC_IN(LOG_NAS_ESM); esm_ebr_context_t* ebr_ctx = NULL; bearer_context_t* bearer_context = NULL; if ((ebi < ESM_EBI_MIN) || (ebi > ESM_EBI_MAX)) { OAILOG_ERROR(LOG_NAS_ESM, "ESM-FSM - Retransmission timer bad ebi %d\n", ebi); OAILOG_FUNC_RETURN(LOG_NAS_ESM, RETURNerror); } ue_mm_context_t* ue_mm_context = PARENT_STRUCT(emm_context, struct ue_mm_context_s, emm_context); if (ue_mm_context == NULL) { OAILOG_ERROR(LOG_NAS_ESM, "ESM-FSM - ue mme context null..\n"); OAILOG_FUNC_RETURN(LOG_NAS_ESM, RETURNerror); } /* * Get EPS bearer context data */ bearer_context = ue_mm_context->bearer_contexts[EBI_TO_INDEX(ebi)]; if ((bearer_context == NULL) || (bearer_context->ebi != ebi)) { /* * EPS bearer context not assigned */ OAILOG_ERROR_UE(LOG_NAS_ESM, ue_mm_context->emm_context._imsi64, "ESM-FSM - EPS bearer context not assigned for ebi %u \n", ebi); OAILOG_FUNC_RETURN(LOG_NAS_ESM, RETURNerror); } ebr_ctx = &bearer_context->esm_ebr_context; esm_ebr_timer_data_t* esm_ebr_timer_data = NULL; ebr_ctx->timer.msec = msec; timer_arg_t timer_args; timer_args.ue_id = ue_mm_context->mme_ue_s1ap_id; timer_args.ebi = ebi; if (ebr_ctx->timer.id != NAS_TIMER_INACTIVE_ID) { // Re-start the retransmission timer nas_timer_stop(&(ebr_ctx->timer)); nas_timer_start(&(ebr_ctx->timer), cb, &timer_args); esm_ebr_timer_data = ebr_ctx->args; } else { /* * If timer-id is set to NAS_TIMER_INACTIVE_ID and has non-null * timer argument, indicates that timer details are read from Redis DB */ if (ebr_ctx->args) { nas_timer_start(&(ebr_ctx->timer), cb, &timer_args); esm_ebr_timer_data = ebr_ctx->args; } else { esm_ebr_timer_data = (esm_ebr_timer_data_t*)calloc(1, sizeof(esm_ebr_timer_data_t)); if (esm_ebr_timer_data) { // Set the UE identifier esm_ebr_timer_data->ue_id = ue_mm_context->mme_ue_s1ap_id; esm_ebr_timer_data->ctx = emm_context; // Set the EPS bearer identity esm_ebr_timer_data->ebi = ebi; // Reset the retransmission counter esm_ebr_timer_data->count = 0; // Set the ESM message to be re-transmited esm_ebr_timer_data->msg = bstrcpy(msg); // Setup the retransmission timer to expire at the given // time interval nas_timer_start(&(ebr_ctx->timer), cb, &timer_args); ebr_ctx->args = esm_ebr_timer_data; } } } if ((esm_ebr_timer_data) && (ebr_ctx->timer.id != NAS_TIMER_INACTIVE_ID)) { OAILOG_INFO_UE(LOG_NAS_ESM, emm_context->_imsi64, "ESM-FSM - Retransmission timer %ld expires in " "%d milliseconds for ue id " MME_UE_S1AP_ID_FMT "\n", ebr_ctx->timer.id, ebr_ctx->timer.msec, esm_ebr_timer_data->ue_id); OAILOG_FUNC_RETURN(LOG_NAS_ESM, RETURNok); } else { OAILOG_ERROR( LOG_NAS_ESM, "ESM-FSM - esm_ebr_timer_data == NULL(%p) or ebr_ctx->timer.id == " "NAS_TIMER_INACTIVE_ID == -1 (%ld)\n", esm_ebr_timer_data, ebr_ctx->timer.id); } OAILOG_FUNC_RETURN(LOG_NAS_ESM, RETURNerror); } /**************************************************************************** ** ** ** Name: esm_ebr_stop_timer() ** ** ** ** Description: Stop the timer previously started for the given EPS bea- ** ** rer context ** ** ** ** Inputs: ue_id: Lower layers UE identifier ** ** ebi: The identity of the EPS bearer ** ** Others: None ** ** ** ** Outputs: None ** ** Return: RETURNok, RETURNerror ** ** Others: _esm_ebr_data ** ** ** ***************************************************************************/ status_code_e esm_ebr_stop_timer(emm_context_t* emm_context, ebi_t ebi) { esm_ebr_context_t* ebr_ctx = NULL; bearer_context_t* bearer_context = NULL; OAILOG_FUNC_IN(LOG_NAS_ESM); if ((ebi < ESM_EBI_MIN) || (ebi > ESM_EBI_MAX)) { OAILOG_FUNC_RETURN(LOG_NAS_ESM, RETURNerror); } ue_mm_context_t* ue_mm_context = PARENT_STRUCT(emm_context, struct ue_mm_context_s, emm_context); /* * Get EPS bearer context data */ bearer_context = ue_mm_context->bearer_contexts[EBI_TO_INDEX(ebi)]; if ((bearer_context == NULL) || (bearer_context->ebi != ebi)) { /* * EPS bearer context not assigned */ OAILOG_FUNC_RETURN(LOG_NAS_ESM, RETURNerror); } ebr_ctx = &bearer_context->esm_ebr_context; /* * Stop the retransmission timer if still running */ if (ebr_ctx->timer.id != NAS_TIMER_INACTIVE_ID || ebr_ctx->args) { OAILOG_INFO_UE( LOG_NAS_ESM, emm_context->_imsi64, "ESM-FSM - Stop retransmission timer %ld " MME_UE_S1AP_ID_FMT "\n", ebr_ctx->timer.id, ue_mm_context->mme_ue_s1ap_id); esm_ebr_timer_data_t* esm_ebr_timer_data = ebr_ctx->args; nas_timer_stop(&(ebr_ctx->timer)); /* * Release the retransmisison timer parameters */ if (esm_ebr_timer_data) { if (esm_ebr_timer_data->msg) { bdestroy_wrapper(&esm_ebr_timer_data->msg); } free_wrapper((void**)&esm_ebr_timer_data); } ebr_ctx->args = NULL; } OAILOG_FUNC_RETURN(LOG_NAS_ESM, RETURNok); } /**************************************************************************** ** ** ** Name: esm_ebr_get_pending_ebi() ** ** ** ** Description: Returns the EPS bearer identity assigned to the first EPS ** ** bearer context entry which is pending in the given state ** ** ** ** Inputs: ue_id: Lower layers UE identifier ** ** status: The EPS bearer context status ** ** Others: _esm_ebr_data ** ** ** ** Outputs: None ** ** Return: The EPS bearer identity of the EPS bearer ** ** context entry if it exists; ** ** the not assigned EBI (0) otherwise. ** ** Others: None ** ** ** ***************************************************************************/ ebi_t esm_ebr_get_pending_ebi(emm_context_t* emm_context, esm_ebr_state status) { int i; OAILOG_FUNC_IN(LOG_NAS_ESM); ue_mm_context_t* ue_mm_context = PARENT_STRUCT(emm_context, struct ue_mm_context_s, emm_context); for (i = 0; i < BEARERS_PER_UE; i++) { if (ue_mm_context->bearer_contexts[i] == NULL) { continue; } if (ue_mm_context->bearer_contexts[i]->esm_ebr_context.status != status) { continue; } /* * EPS bearer context entry found */ break; } if (i < BEARERS_PER_UE) { OAILOG_FUNC_RETURN(LOG_NAS_ESM, ue_mm_context->bearer_contexts[i]->ebi); } /* * EPS bearer context entry not found */ OAILOG_FUNC_RETURN(LOG_NAS_ESM, ESM_EBI_UNASSIGNED); } /**************************************************************************** ** ** ** Name: esm_ebr_set_status() ** ** ** ** Description: Set the status of the specified EPS bearer context to the ** ** given state ** ** ** ** Inputs: ue_id: Lower layers UE identifier ** ** ebi: The identity of the EPS bearer ** ** status: The new EPS bearer context status ** ** ue_requested: true/false if the modification of the EPS ** ** bearer context status was requested by the ** ** UE/network ** ** Others: None ** ** ** ** Outputs: None ** ** Return: RETURNok, RETURNerror ** ** Others: _esm_ebr_data ** ** ** ***************************************************************************/ status_code_e esm_ebr_set_status(emm_context_t* emm_context, ebi_t ebi, esm_ebr_state status, bool ue_requested) { bearer_context_t* bearer_context = NULL; esm_ebr_context_t* ebr_ctx = 0; esm_ebr_state old_status = ESM_EBR_INACTIVE; OAILOG_FUNC_IN(LOG_NAS_ESM); if (emm_context == NULL) { OAILOG_ERROR(LOG_NAS_ESM, "ESM-FSM - emm context null... \n"); OAILOG_FUNC_RETURN(LOG_NAS_ESM, RETURNerror); } if ((ebi < ESM_EBI_MIN) || (ebi > ESM_EBI_MAX)) { OAILOG_ERROR_UE( LOG_NAS_ESM, emm_context->_imsi64, "ESM-FSM - Invalid EPS bearer identity range ebi= (%d) \n", ebi); OAILOG_FUNC_RETURN(LOG_NAS_ESM, RETURNerror); } ue_mm_context_t* ue_mm_context = PARENT_STRUCT(emm_context, struct ue_mm_context_s, emm_context); if (ue_mm_context == NULL) { OAILOG_ERROR(LOG_NAS_ESM, "ESM-FSM - ue mme context null... \n"); } /* * Get EPS bearer context data */ bearer_context = ue_mm_context->bearer_contexts[EBI_TO_INDEX(ebi)]; if ((bearer_context == NULL) || (bearer_context->ebi != ebi)) { /* * EPS bearer context not assigned */ OAILOG_ERROR(LOG_NAS_ESM, "ESM-FSM - EPS bearer context not assigned \n" "(ebi=%d)", ebi); OAILOG_FUNC_RETURN(LOG_NAS_ESM, RETURNerror); } ebr_ctx = &bearer_context->esm_ebr_context; old_status = ebr_ctx->status; if (status < ESM_EBR_STATE_MAX) { if (status != old_status) { OAILOG_INFO_UE(LOG_NAS_ESM, emm_context->_imsi64, "ESM-FSM - Status of EPS bearer context %d changed:" " %s ===> %s for ue id " MME_UE_S1AP_ID_FMT "\n", ebi, esm_ebr_state_str[old_status], esm_ebr_state_str[status], ue_mm_context->mme_ue_s1ap_id); ebr_ctx->status = status; OAILOG_FUNC_RETURN(LOG_NAS_ESM, RETURNok); } else { OAILOG_INFO_UE(LOG_NAS_ESM, emm_context->_imsi64, "ESM-FSM - Status of EPS bearer context %d unchanged:" " %s \n", ebi, esm_ebr_state_str[status]); } } OAILOG_FUNC_RETURN(LOG_NAS_ESM, RETURNerror); } /**************************************************************************** ** ** ** Name: esm_ebr_get_status() ** ** ** ** Description: Get the current status value of the specified EPS bearer ** ** context ** ** ** ** Inputs: ue_id: Lower layers UE identifier ** ** ebi: The identity of the EPS bearer ** ** Others: _esm_ebr_data ** ** ** ** Outputs: None ** ** Return: The current value of the EPS bearer con- ** ** text status ** ** Others: None ** ** ** ***************************************************************************/ esm_ebr_state esm_ebr_get_status(emm_context_t* emm_context, ebi_t ebi) { if ((ebi < ESM_EBI_MIN) || (ebi > ESM_EBI_MAX)) { return (ESM_EBR_INACTIVE); } ue_mm_context_t* ue_mm_context = PARENT_STRUCT(emm_context, struct ue_mm_context_s, emm_context); bearer_context_t* bearer_context = NULL; bearer_context = ue_mm_context->bearer_contexts[EBI_TO_INDEX(ebi)]; if (bearer_context == NULL) { /* * EPS bearer context not allocated */ return (ESM_EBR_INACTIVE); } if (bearer_context->ebi != ebi) { /* * EPS bearer context not assigned */ return (ESM_EBR_INACTIVE); } return (bearer_context->esm_ebr_context.status); } /**************************************************************************** ** ** ** Name: esm_ebr_is_reserved() ** ** ** ** Description: Check whether the given EPS bearer identity is a reserved ** ** value ** ** ** ** Inputs: ebi: The identity of the EPS bearer ** ** Others: None ** ** ** ** Outputs: None ** ** Return: true, false ** ** Others: None ** ** ** ***************************************************************************/ bool esm_ebr_is_reserved(ebi_t ebi) { return ((ebi != ESM_EBI_UNASSIGNED) && (ebi < ESM_EBI_MIN)); } /**************************************************************************** ** ** ** Name: esm_ebr_is_not_in_use() ** ** ** ** Description: Check whether the given EPS bearer identity does not ** ** match an assigned EBI value currently in use ** ** ** ** Inputs: ue_id: Lower layers UE identifier ** ** ebi: The identity of the EPS bearer ** ** Others: _esm_ebr_data ** ** ** ** Outputs: None ** ** Return: true, false ** ** Others: None ** ** ** ***************************************************************************/ bool esm_ebr_is_not_in_use(emm_context_t* emm_context, ebi_t ebi) { ue_mm_context_t* ue_mm_context = PARENT_STRUCT(emm_context, struct ue_mm_context_s, emm_context); return ((ebi == ESM_EBI_UNASSIGNED) || (ue_mm_context->bearer_contexts[EBI_TO_INDEX(ebi)] == NULL) || (ue_mm_context->bearer_contexts[EBI_TO_INDEX(ebi)]->ebi) != ebi); } /****************************************************************************/ /********************* L O C A L F U N C T I O N S *********************/ /****************************************************************************/ /**************************************************************************** ** ** ** Name: _esm_ebr_get_available_entry() ** ** ** ** Description: Returns the index of the next available entry in the list ** ** of EPS bearer context data ** ** ** ** Inputs: ue_id: Lower layers UE identifier ** ** Others: _esm_ebr_data ** ** ** ** Outputs: None ** ** Return: The index of the next available EPS bearer ** ** context data entry; -1 if no any entry is ** ** available. ** ** Others: None ** ** ** ***************************************************************************/ static int esm_ebr_get_available_entry(emm_context_t* emm_context) { ue_mm_context_t* ue_mm_context = PARENT_STRUCT(emm_context, struct ue_mm_context_s, emm_context); int i; for (i = 0; i < BEARERS_PER_UE; i++) { if (ue_mm_context->bearer_contexts[i] == NULL) { return i; } } return -1; }
304988.c
//***************************************************************************** // // i2s.c - Driver for the I2S controller. // // Copyright (c) 2008-2012 Texas Instruments Incorporated. All rights reserved. // Software License Agreement // // 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 Texas Instruments Incorporated 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. // // This is part of revision 9453 of the Stellaris Peripheral Driver Library. // //***************************************************************************** //***************************************************************************** // //! \addtogroup i2s_api //! @{ // //***************************************************************************** #include "inc/hw_i2s.h" #include "inc/hw_ints.h" #include "inc/hw_memmap.h" #include "inc/hw_types.h" #include "driverlib/debug.h" #include "driverlib/i2s.h" #include "driverlib/interrupt.h" //***************************************************************************** // //! Enables the I2S transmit module for operation. //! //! \param ulBase is the I2S module base address. //! //! This function enables the transmit module for operation. The module //! should be enabled after configuration. When the module is disabled, //! no data or clocks are generated on the I2S signals. //! //! \return None. // //***************************************************************************** void I2STxEnable(unsigned long ulBase) { // // Check the arguments. // ASSERT(ulBase == I2S0_BASE); // // Enable the tx FIFO service request. // HWREG(ulBase + I2S_O_TXISM) = I2S_TXISM_FFM; // // Read-modify-write the enable bit. // HWREG(ulBase + I2S_O_CFG) |= I2S_CFG_TXEN; } //***************************************************************************** // //! Disables the I2S transmit module for operation. //! //! \param ulBase is the I2S module base address. //! //! This function disables the transmit module for operation. The module //! should be disabled before configuration. When the module is disabled, //! no data or clocks are generated on the I2S signals. //! //! \return None. // //***************************************************************************** void I2STxDisable(unsigned long ulBase) { // // Check the arguments. // ASSERT(ulBase == I2S0_BASE); // // Read-modify-write the enable bit. // HWREG(ulBase + I2S_O_CFG) &= ~I2S_CFG_TXEN; } //***************************************************************************** // //! Writes data samples to the I2S transmit FIFO with blocking. //! //! \param ulBase is the I2S module base address. //! \param ulData is the single- or dual-channel I2S data. //! //! This function writes a single-channel sample or combined left-right //! samples to the I2S transmit FIFO. The format of the sample is determined //! by the configuration that was used with the function I2STxConfigSet(). //! If the transmit mode is \b I2S_MODE_DUAL_STEREO then the \e ulData //! parameter contains either the left or right sample. The left and right //! sample alternate with each write to the FIFO, left sample first. If the //! transmit mode is \b I2S_MODE_COMPACT_STEREO_16 or //! \b I2S_MODE_COMPACT_STEREO_8, then the \e ulData parameter contains both //! the left and right samples. If the transmit mode is //! \b I2S_MODE_SINGLE_MONO then the \e ulData parameter contains the single //! channel sample. //! //! For the compact modes, both the left and right samples are written at //! the same time. If 16-bit compact mode is used, then the least significant //! 16 bits contain the left sample, and the most significant 16 bits contain //! the right sample. If 8-bit compact mode is used, then the lower 8 bits //! contain the left sample, and the next 8 bits contain the right sample, //! with the upper 16 bits unused. //! //! If there is no room in the transmit FIFO, then this function waits //! in a polling loop until the data can be written. //! //! \return None. // //***************************************************************************** void I2STxDataPut(unsigned long ulBase, unsigned long ulData) { // // Check the arguments. // ASSERT(ulBase == I2S0_BASE); // // Wait until there is space. // while(HWREG(ulBase + I2S_O_TXLEV) >= 16) { } // // Write the data to the I2S. // HWREG(ulBase + I2S_O_TXFIFO) = ulData; } //***************************************************************************** // //! Writes data samples to the I2S transmit FIFO without blocking. //! //! \param ulBase is the I2S module base address. //! \param ulData is the single- or dual-channel I2S data. //! //! This function writes a single-channel sample or combined left-right //! samples to the I2S transmit FIFO. The format of the sample is determined //! by the configuration that was used with the function I2STxConfigSet(). //! If the transmit mode is \b I2S_MODE_DUAL_STEREO then the \e ulData //! parameter contains either the left or right sample. The left and right //! sample alternate with each write to the FIFO, left sample first. If the //! transmit mode is \b I2S_MODE_COMPACT_STEREO_16 or //! \b I2S_MODE_COMPACT_STEREO_8, then the \e ulData parameter contains both //! the left and right samples. If the transmit mode is //! \b I2S_MODE_SINGLE_MONO then the \e ulData parameter contains the single- //! channel sample. //! //! For the compact modes, both the left and right samples are written at //! the same time. If 16-bit compact mode is used, then the least significant //! 16 bits contain the left sample, and the most significant 16 bits contain //! the right sample. If 8-bit compact mode is used, then the lower 8 bits //! contain the left sample, and the next 8 bits contain the right sample, //! with the upper 16 bits unused. //! //! If there is no room in the transmit FIFO, then this function returns //! immediately without writing any data to the FIFO. //! //! \return The number of elements written to the I2S transmit FIFO (1 or 0). // //***************************************************************************** long I2STxDataPutNonBlocking(unsigned long ulBase, unsigned long ulData) { // // Check the arguments. // ASSERT(ulBase == I2S0_BASE); // // Check for space to write. // if(HWREG(ulBase + I2S_O_TXLEV) < 16) { HWREG(ulBase + I2S_O_TXFIFO) = ulData; return(1); } else { return(0); } } //***************************************************************************** // //! Configures the I2S transmit module. //! //! \param ulBase is the I2S module base address. //! \param ulConfig is the logical OR of the configuration options. //! //! This function is used to configure the options for the I2S transmit //! channel. The parameter \e ulConfig is the logical OR of the following //! options: //! //! - \b I2S_CONFIG_FORMAT_I2S for standard I2S format, //! \b I2S_CONFIG_FORMAT_LEFT_JUST for left justified format, or //! \b I2S_CONFIG_FORMAT_RIGHT_JUST for right justified format. //! - \b I2S_CONFIG_SCLK_INVERT to invert the polarity of the serial bit clock. //! - \b I2S_CONFIG_MODE_DUAL for dual channel stereo, //! \b I2S_CONFIG_MODE_COMPACT_16 for 16-bit compact stereo mode, //! \b I2S_CONFIG_MODE_COMPACT_8 for 8-bit compact stereo mode, or //! \b I2S_CONFIG_MODE_MONO for single channel mono format. //! - \b I2S_CONFIG_CLK_MASTER or \b I2S_CONFIG_CLK_SLAVE to select whether //! the I2S transmitter is the clock master or slave. //! - \b I2S_CONFIG_SAMPLE_SIZE_32, \b _24, \b _20, \b _16, or \b _8 //! to select the number of bits per sample. //! - \b I2S_CONFIG_WIRE_SIZE_32, \b _24, \b _20, \b _16, or \b _8 //! to select the number of bits per word that are transferred on the data //! line. //! - \b I2S_CONFIG_EMPTY_ZERO or \b I2S_CONFIG_EMPTY_REPEAT to select whether //! the module transmits zeroes or repeats the last sample when the FIFO is //! empty. //! //! \return None. // //***************************************************************************** void I2STxConfigSet(unsigned long ulBase, unsigned long ulConfig) { // // Check the arguments. // ASSERT(ulBase == I2S0_BASE); ASSERT((ulConfig & (I2S_CONFIG_FORMAT_MASK | I2S_CONFIG_MODE_MASK | I2S_CONFIG_EMPTY_MASK | I2S_CONFIG_CLK_MASK | I2S_CONFIG_SAMPLE_SIZE_MASK | I2S_CONFIG_WIRE_SIZE_MASK)) == ulConfig); // // Check to see if a compact mode is used. // if((ulConfig & I2S_CONFIG_MODE_MASK) == I2S_CONFIG_MODE_COMPACT_8) { // // If compact 8 mode is used, then need to adjust some bits // before writing the config register. Also set the FIFO // config register for 8-bit compact samples. // ulConfig &= ~I2S_CONFIG_MODE_MONO; HWREG(ulBase + I2S_O_TXFIFOCFG) = I2S_TXFIFOCFG_CSS; } else { // // If compact 8 mode is not used, then set the FIFO config // register for 16 bit. This setting is okay if a compact // mode is not used. // HWREG(ulBase + I2S_O_TXFIFOCFG) = 0; } // // Write the configuration register. Because all the fields are // specified by the configuration parameter, it is not necessary // to do a read-modify-write. // HWREG(ulBase + I2S_O_TXCFG) = ulConfig; } //***************************************************************************** // //! Sets the FIFO level at which a service request is generated. //! //! \param ulBase is the I2S module base address. //! \param ulLevel is the FIFO service request limit. //! //! This function is used to set the transmit FIFO fullness level at which a //! service request occurs. The service request is used to generate an //! interrupt or a DMA transfer request. The transmit FIFO generates a //! service request when the number of items in the FIFO is less than the level //! specified in the \e ulLevel parameter. For example, if \e ulLevel is 8, //! then a service request is generated when there are less than 8 samples //! remaining in the transmit FIFO. //! //! For the purposes of counting the FIFO level, a left-right sample pair //! counts as 2, whether the mode is dual or compact stereo. When mono mode is //! used, internally the mono sample is still treated as a sample pair, so a //! single mono sample counts as 2. Because the FIFO always deals with sample //! pairs, the level must be an even number from 0 to 16. The maximum value is //! 16, which causes a service request when there is any room in the FIFO. //! The minimum value is 0, which disables the service request. //! //! \return None. // //***************************************************************************** void I2STxFIFOLimitSet(unsigned long ulBase, unsigned long ulLevel) { // // Check the arguments. // ASSERT(ulBase == I2S0_BASE); ASSERT(ulLevel <= 16); // // Write the FIFO limit // HWREG(ulBase + I2S_O_TXLIMIT) = ulLevel; } //***************************************************************************** // //! Gets the current setting of the FIFO service request level. //! //! \param ulBase is the I2S module base address. //! //! This function is used to get the value of the transmit FIFO service //! request level. This value is set using the I2STxFIFOLimitSet() //! function. //! //! \return Returns the current value of the FIFO service request limit. // //***************************************************************************** unsigned long I2STxFIFOLimitGet(unsigned long ulBase) { // // Check the arguments. // ASSERT(ulBase == I2S0_BASE); // // Read and return the FIFO limit // return(HWREG(ulBase + I2S_O_TXLIMIT)); } //***************************************************************************** // //! Gets the number of samples in the transmit FIFO. //! //! \param ulBase is the I2S module base address. //! //! This function is used to get the number of samples in the transmit FIFO. //! For the purposes of measuring the FIFO level, a left-right sample pair //! counts as 2, whether the mode is dual or compact stereo. When mono mode is //! used, internally the mono sample is still treated as a sample pair, so a //! single mono sample counts as 2. Because the FIFO always deals with sample //! pairs, normally the level is an even number from 0 to 16. If dual stereo //! mode is used and only the left sample has been written without the matching //! right sample, then the FIFO level is an odd value. If the FIFO level is //! odd, it indicates a left-right sample mismatch. //! //! \return Returns the number of samples in the transmit FIFO, which is //! normally an even number. // //***************************************************************************** unsigned long I2STxFIFOLevelGet(unsigned long ulBase) { // // Check the arguments. // ASSERT(ulBase == I2S0_BASE); // // Read and return the transmit FIFO level. // return(HWREG(ulBase + I2S_O_TXLEV)); } //***************************************************************************** // //! Enables the I2S receive module for operation. //! //! \param ulBase is the I2S module base address. //! //! This function enables the receive module for operation. The module should //! be enabled after configuration. When the module is disabled, no data is //! clocked in regardless of the signals on the I2S interface. //! //! \return None. // //***************************************************************************** void I2SRxEnable(unsigned long ulBase) { // // Check the arguments. // ASSERT(ulBase == I2S0_BASE); // // Enable the tx FIFO service request. // HWREG(ulBase + I2S_O_RXISM) = I2S_RXISM_FFM; // // Read-modify-write the enable bit. // HWREG(ulBase + I2S_O_CFG) |= I2S_CFG_RXEN; } //***************************************************************************** // //! Disables the I2S receive module for operation. //! //! \param ulBase is the I2S module base address. //! //! This function disables the receive module for operation. The module should //! be disabled before configuration. When the module is disabled, no data is //! clocked in regardless of the signals on the I2S interface. //! //! \return None. // //***************************************************************************** void I2SRxDisable(unsigned long ulBase) { // // Check the arguments. // ASSERT(ulBase == I2S0_BASE); // // Read-modify-write the enable bit. // HWREG(ulBase + I2S_O_CFG) &= ~I2S_CFG_RXEN; } //***************************************************************************** // //! Reads data samples from the I2S receive FIFO with blocking. //! //! \param ulBase is the I2S module base address. //! \param pulData points to storage for the returned I2S sample data. //! //! This function reads a single channel sample or combined left-right //! samples from the I2S receive FIFO. The format of the sample is determined //! by the configuration that was used with the function I2SRxConfigSet(). //! If the receive mode is \b I2S_MODE_DUAL_STEREO then the returned value //! contains either the left or right sample. The left and right sample //! alternate with each read from the FIFO, left sample first. If the receive //! mode is \b I2S_MODE_COMPACT_STEREO_16 or \b I2S_MODE_COMPACT_STEREO_8, then //! the returned data contains both the left and right samples. If the //! receive mode is \b I2S_MODE_SINGLE_MONO then the returned data //! contains the single channel sample. //! //! For the compact modes, both the left and right samples are read at //! the same time. If 16-bit compact mode is used, then the least significant //! 16 bits contain the left sample, and the most significant 16 bits contain //! the right sample. If 8-bit compact mode is used, then the lower 8 bits //! contain the left sample, and the next 8 bits contain the right sample, //! with the upper 16 bits unused. //! //! If there is no data in the receive FIFO, then this function waits //! in a polling loop until data is available. //! //! \return None. // //***************************************************************************** void I2SRxDataGet(unsigned long ulBase, unsigned long *pulData) { // // Check the arguments. // ASSERT(ulBase == I2S0_BASE); // // Wait until there is data available. // while(HWREG(ulBase + I2S_O_RXLEV) == 0) { } // // Read data from the I2S receive FIFO. // *pulData = HWREG(ulBase + I2S_O_RXFIFO); } //***************************************************************************** // //! Reads data samples from the I2S receive FIFO without blocking. //! //! \param ulBase is the I2S module base address. //! \param pulData points to storage for the returned I2S sample data. //! //! This function reads a single channel sample or combined left-right //! samples from the I2S receive FIFO. The format of the sample is determined //! by the configuration that was used with the function I2SRxConfigSet(). //! If the receive mode is \b I2S_MODE_DUAL_STEREO then the received data //! contains either the left or right sample. The left and right sample //! alternate with each read from the FIFO, left sample first. If the receive //! mode is \b I2S_MODE_COMPACT_STEREO_16 or \b I2S_MODE_COMPACT_STEREO_8, then //! the received data contains both the left and right samples. If the //! receive mode is \b I2S_MODE_SINGLE_MONO then the received data //! contains the single channel sample. //! //! For the compact modes, both the left and right samples are read at //! the same time. If 16-bit compact mode is used, then the least significant //! 16 bits contain the left sample, and the most significant 16 bits contain //! the right sample. If 8-bit compact mode is used, then the lower 8 bits //! contain the left sample, and the next 8 bits contain the right sample, //! with the upper 16 bits unused. //! //! If there is no data in the receive FIFO, then this function returns //! immediately without reading any data from the FIFO. //! //! \return The number of elements read from the I2S receive FIFO (1 or 0). // //***************************************************************************** long I2SRxDataGetNonBlocking(unsigned long ulBase, unsigned long *pulData) { // // Check the arguments. // ASSERT(ulBase == I2S0_BASE); // // Check for available samples. // if(HWREG(ulBase + I2S_O_RXLEV) != 0) { *pulData = HWREG(ulBase + I2S_O_RXFIFO); return(1); } else { return(0); } } //***************************************************************************** // //! Configures the I2S receive module. //! //! \param ulBase is the I2S module base address. //! \param ulConfig is the logical OR of the configuration options. //! //! This function is used to configure the options for the I2S receive //! channel. The parameter \e ulConfig is the logical OR of the following //! options: //! //! - \b I2S_CONFIG_FORMAT_I2S for standard I2S format, //! \b I2S_CONFIG_FORMAT_LEFT_JUST for left justified format, or //! \b I2S_CONFIG_FORMAT_RIGHT_JUST for right justified format. //! - \b I2S_CONFIG_SCLK_INVERT to invert the polarity of the serial bit clock. //! - \b I2S_CONFIG_MODE_DUAL for dual channel stereo, //! \b I2S_CONFIG_MODE_COMPACT_16 for 16-bit compact stereo mode, //! \b I2S_CONFIG_MODE_COMPACT_8 for 8-bit compact stereo mode, or //! \b I2S_CONFIG_MODE_MONO for single channel mono format. //! - \b I2S_CONFIG_CLK_MASTER or \b I2S_CONFIG_CLK_SLAVE to select whether //! the I2S receiver is the clock master or slave. //! - \b I2S_CONFIG_SAMPLE_SIZE_32, \b _24, \b _20, \b _16, or \b _8 //! to select the number of bits per sample. //! - \b I2S_CONFIG_WIRE_SIZE_32, \b _24, \b _20, \b _16, or \b _8 //! to select the number of bits per word that are transferred on the data //! line. //! //! \return None. // //***************************************************************************** void I2SRxConfigSet(unsigned long ulBase, unsigned long ulConfig) { // // Check the arguments. // ASSERT(ulBase == I2S0_BASE); ASSERT((ulConfig & (I2S_CONFIG_FORMAT_MASK | I2S_CONFIG_MODE_MASK | I2S_CONFIG_CLK_MASK | I2S_CONFIG_SAMPLE_SIZE_MASK | I2S_CONFIG_WIRE_SIZE_MASK)) == ulConfig); // // Clear out any prior config of the RX FIFO config register. // HWREG(ulBase + I2S_O_RXFIFOCFG) = 0; // // If mono mode is used, then the FMM bit needs to be set. // if((ulConfig & I2S_CONFIG_MODE_MASK) == I2S_CONFIG_MODE_MONO) { HWREG(ulBase + I2S_O_RXFIFOCFG) |= I2S_RXFIFOCFG_FMM; } // // If a compact mode is used, then the CSS bit needs to be set. // else if((ulConfig & I2S_CONFIG_MODE_MASK) == I2S_CONFIG_MODE_COMPACT_8) { HWREG(ulBase + I2S_O_RXFIFOCFG) |= I2S_RXFIFOCFG_CSS; } // // The "mono" bits must be removed from the configuration word // prior to writing to hardware, because the RX configuration register // does not actually use these bits. // ulConfig &= ~I2S_CONFIG_MODE_MONO; // // Write the configuration register. Because all the fields are // specified by the configuration parameter, it is not necessary // to do a read-modify-write. // HWREG(ulBase + I2S_O_RXCFG) = ulConfig; } //***************************************************************************** // //! Sets the FIFO level at which a service request is generated. //! //! \param ulBase is the I2S module base address. //! \param ulLevel is the FIFO service request limit. //! //! This function is used to set the receive FIFO fullness level at which a //! service request occurs. The service request is used to generate an //! interrupt or a DMA transfer request. The receive FIFO generates a //! service request when the number of items in the FIFO is greater than the //! level specified in the \e ulLevel parameter. For example, if \e ulLevel is //! 4, then a service request is generated when there are more than 4 samples //! available in the receive FIFO. //! //! For the purposes of counting the FIFO level, a left-right sample pair //! counts as 2, whether the mode is dual or compact stereo. When mono mode is //! used, internally the mono sample is still treated as a sample pair, so a //! single mono sample counts as 2. Because the FIFO always deals with sample //! pairs, the level must be an even number from 0 to 16. The minimum value is //! 0, which causes a service request when there is any data available in //! the FIFO. The maximum value is 16, which disables the service request //! (because there cannot be more than 16 items in the FIFO). //! //! \return None. // //***************************************************************************** void I2SRxFIFOLimitSet(unsigned long ulBase, unsigned long ulLevel) { // // Check the arguments. // ASSERT(ulBase == I2S0_BASE); ASSERT(ulLevel <= 16); // // Write the FIFO limit // HWREG(ulBase + I2S_O_RXLIMIT) = ulLevel; } //***************************************************************************** // //! Gets the current setting of the FIFO service request level. //! //! \param ulBase is the I2S module base address. //! //! This function is used to get the value of the receive FIFO service //! request level. This value is set using the I2SRxFIFOLimitSet() //! function. //! //! \return Returns the current value of the FIFO service request limit. // //***************************************************************************** unsigned long I2SRxFIFOLimitGet(unsigned long ulBase) { // // Check the arguments. // ASSERT(ulBase == I2S0_BASE); // // Read and return the FIFO limit. The lower bit is masked // because it always reads as 1 and has no meaning. // return(HWREG(ulBase + I2S_O_RXLIMIT) & 0xFFFE); } //***************************************************************************** // //! Gets the number of samples in the receive FIFO. //! //! \param ulBase is the I2S module base address. //! //! This function is used to get the number of samples in the receive FIFO. //! For the purposes of measuring the FIFO level, a left-right sample pair //! counts as 2, whether the mode is dual or compact stereo. When mono mode is //! used, internally the mono sample is still treated as a sample pair, so a //! single mono sample counts as 2. Because the FIFO always deals with sample //! pairs, normally the level is an even number from 0 to 16. If dual stereo //! mode is used and only the left sample has been read without reading the //! matching right sample, then the FIFO level is an odd value. If the FIFO //! level is odd, it indicates a left-right sample mismatch. //! //! \return Returns the number of samples in the transmit FIFO, which is //! normally an even number. // //***************************************************************************** unsigned long I2SRxFIFOLevelGet(unsigned long ulBase) { // // Check the arguments. // ASSERT(ulBase == I2S0_BASE); // // Read and return the receive FIFO level. // return(HWREG(ulBase + I2S_O_RXLEV)); } //***************************************************************************** // //! Enables the I2S transmit and receive modules for operation. //! //! \param ulBase is the I2S module base address. //! //! This function simultaneously enables the transmit and receive modules for //! operation, providing a synchronized SCLK and LRCLK. The module should be //! enabled after configuration. When the module is disabled, no data or //! clocks are generated on the I2S signals. //! //! \return None. // //***************************************************************************** void I2STxRxEnable(unsigned long ulBase) { // // Check the arguments. // ASSERT(ulBase == I2S0_BASE); // // Enable the Tx FIFO service request. // HWREG(ulBase + I2S_O_TXISM) = I2S_TXISM_FFM; // // Enable the Rx FIFO service request. // HWREG(ulBase + I2S_O_RXISM) = I2S_RXISM_FFM; // // Enable the transmit and receive modules. // HWREG(ulBase + I2S_O_CFG) |= I2S_CFG_TXEN | I2S_CFG_RXEN; } //***************************************************************************** // //! Disables the I2S transmit and receive modules. //! //! \param ulBase is the I2S module base address. //! //! This function simultaneously disables the transmit and receive modules. //! When the module is disabled, no data or clocks are generated on the I2S //! signals. //! //! \return None. // //***************************************************************************** void I2STxRxDisable(unsigned long ulBase) { // // Check the arguments. // ASSERT(ulBase == I2S0_BASE); // // Disable the transmit and receive modules. // HWREG(ulBase + I2S_O_CFG) &= ~(I2S_CFG_TXEN | I2S_CFG_RXEN); } //***************************************************************************** // //! Configures the I2S transmit and receive modules. //! //! \param ulBase is the I2S module base address. //! \param ulConfig is the logical OR of the configuration options. //! //! This function is used to configure the options for the I2S transmit and //! receive channels with identical parameters. The parameter \e ulConfig is //! the logical OR of the following options: //! //! - \b I2S_CONFIG_FORMAT_I2S for standard I2S format, //! \b I2S_CONFIG_FORMAT_LEFT_JUST for left justified format, or //! \b I2S_CONFIG_FORMAT_RIGHT_JUST for right justified format. //! - \b I2S_CONFIG_SCLK_INVERT to invert the polarity of the serial bit clock. //! - \b I2S_CONFIG_MODE_DUAL for dual-channel stereo, //! \b I2S_CONFIG_MODE_COMPACT_16 for 16-bit compact stereo mode, //! \b I2S_CONFIG_MODE_COMPACT_8 for 8-bit compact stereo mode, or //! \b I2S_CONFIG_MODE_MONO for single-channel mono format. //! - \b I2S_CONFIG_CLK_MASTER or \b I2S_CONFIG_CLK_SLAVE to select whether //! the I2S transmitter is the clock master or slave. //! - \b I2S_CONFIG_SAMPLE_SIZE_32, \b _24, \b _20, \b _16, or \b _8 //! to select the number of bits per sample. //! - \b I2S_CONFIG_WIRE_SIZE_32, \b _24, \b _20, \b _16, or \b _8 //! to select the number of bits per word that are transferred on the data //! line. //! - \b I2S_CONFIG_EMPTY_ZERO or \b I2S_CONFIG_EMPTY_REPEAT to select whether //! the module transmits zeroes or repeats the last sample when the FIFO is //! empty. //! //! \return None. // //***************************************************************************** void I2STxRxConfigSet(unsigned long ulBase, unsigned long ulConfig) { // // Check the arguments. // ASSERT(ulBase == I2S0_BASE); ASSERT((ulConfig & (I2S_CONFIG_FORMAT_MASK | I2S_CONFIG_MODE_MASK | I2S_CONFIG_EMPTY_MASK | I2S_CONFIG_CLK_MASK | I2S_CONFIG_SAMPLE_SIZE_MASK | I2S_CONFIG_WIRE_SIZE_MASK)) == ulConfig); // // Clear out any prior configuration of the FIFO config registers. // HWREG(ulBase + I2S_O_TXFIFOCFG) = 0; HWREG(ulBase + I2S_O_RXFIFOCFG) = 0; // // If mono mode is used, then the FMM bit needs to be set. // if((ulConfig & I2S_CONFIG_MODE_MASK) == I2S_CONFIG_MODE_MONO) { HWREG(ulBase + I2S_O_RXFIFOCFG) |= I2S_RXFIFOCFG_FMM; ulConfig &= ~(I2S_CONFIG_MODE_MONO); } // // If a compact mode is used, then the CSS bit needs to be set. // if((ulConfig & I2S_CONFIG_MODE_MASK) == I2S_CONFIG_MODE_COMPACT_8) { HWREG(ulBase + I2S_O_TXFIFOCFG) |= I2S_TXFIFOCFG_CSS; HWREG(ulBase + I2S_O_RXFIFOCFG) |= I2S_RXFIFOCFG_CSS; } // // Write the configuration register. Because all the fields are specified // by the configuration parameter, it is not necessary to do a // read-modify-write. // HWREG(ulBase + I2S_O_TXCFG) = ulConfig; HWREG(ulBase + I2S_O_RXCFG) = ulConfig; } //***************************************************************************** // //! Selects the source of the master clock, internal or external. //! //! \param ulBase is the I2S module base address. //! \param ulMClock is the logical OR of the master clock configuration //! choices. //! //! This function selects whether the master clock is sourced from the device //! internal PLL or comes from an external pin. The I2S serial bit clock //! (SCLK) and left-right word clock (LRCLK) are derived from the I2S master //! clock. The transmit and receive modules can be configured independently. //! The \e ulMClock parameter is chosen from the following: //! //! - one of \b I2S_TX_MCLK_EXT or \b I2S_TX_MCLK_INT //! - one of \b I2S_RX_MCLK_EXT or \b I2S_RX_MCLK_INT //! //! \return None. // //***************************************************************************** void I2SMasterClockSelect(unsigned long ulBase, unsigned long ulMClock) { unsigned long ulConfig; // // Check the arguments. // ASSERT(ulBase == I2S0_BASE); ASSERT((ulMClock & (I2S_TX_MCLK_EXT | I2S_RX_MCLK_EXT)) == ulMClock); // // Set the clock selection bits in the configuation word. // ulConfig = HWREG(ulBase + I2S_O_CFG) & ~(I2S_TX_MCLK_EXT | I2S_RX_MCLK_EXT); HWREG(ulBase + I2S_O_CFG) = ulConfig | ulMClock; } //***************************************************************************** // //! Enables I2S interrupt sources. //! //! \param ulBase is the I2S module base address. //! \param ulIntFlags is a bit mask of the interrupt sources to be enabled. //! //! This function enables the specified I2S sources to generate interrupts. //! The \e ulIntFlags parameter can be the logical OR of any of the following //! values: //! //! - \b I2S_INT_RXERR for receive errors //! - \b I2S_INT_RXREQ for receive FIFO service requests //! - \b I2S_INT_TXERR for transmit errors //! - \b I2S_INT_TXREQ for transmit FIFO service requests //! //! \return None. // //***************************************************************************** void I2SIntEnable(unsigned long ulBase, unsigned long ulIntFlags) { // // Check the arguments. // ASSERT(ulBase == I2S0_BASE); ASSERT((ulIntFlags & (I2S_INT_RXERR | I2S_INT_RXREQ | I2S_INT_TXERR | I2S_INT_TXREQ)) == ulIntFlags); // // Enable the specified interrupts. // HWREG(ulBase + I2S_O_IM) |= ulIntFlags; } //***************************************************************************** // //! Disables I2S interrupt sources. //! //! \param ulBase is the I2S module base address. //! \param ulIntFlags is a bit mask of the interrupt sources to be disabled. //! //! This function disables the specified I2S sources for interrupt //! generation. The \e ulIntFlags parameter can be the logical OR //! of any of the following values: \b I2S_INT_RXERR, \b I2S_INT_RXREQ, //! \b I2S_INT_TXERR, or \b I2S_INT_TXREQ. //! //! \return None. // //***************************************************************************** void I2SIntDisable(unsigned long ulBase, unsigned long ulIntFlags) { // // Check the arguments. // ASSERT(ulBase == I2S0_BASE); ASSERT((ulIntFlags & (I2S_INT_RXERR | I2S_INT_RXREQ | I2S_INT_TXERR | I2S_INT_TXREQ)) == ulIntFlags); // // Enable the specified interrupts. // HWREG(ulBase + I2S_O_IM) &= ~ulIntFlags; } //***************************************************************************** // //! Gets the I2S interrupt status. //! //! \param ulBase is the I2S module base address. //! \param bMasked is set \b true to get the masked interrupt status, or //! \b false to get the raw interrupt status. //! //! This function returns the I2S interrupt status. It can return either //! the raw or masked interrupt status. //! //! \return Returns the masked or raw I2S interrupt status, as a bit field //! of any of the following values: \b I2S_INT_RXERR, \b I2S_INT_RXREQ, //! \b I2S_INT_TXERR, or \b I2S_INT_TXREQ // //***************************************************************************** unsigned long I2SIntStatus(unsigned long ulBase, tBoolean bMasked) { // // Check the arguments. // ASSERT(ulBase == I2S0_BASE); // // Return either the interrupt status or the raw interrupt status as // requested. // if(bMasked) { return(HWREG(ulBase + I2S_O_MIS)); } else { return(HWREG(ulBase + I2S_O_RIS)); } } //***************************************************************************** // //! Clears pending I2S interrupt sources. //! //! \param ulBase is the I2S module base address. //! \param ulIntFlags is a bit mask of the interrupt sources to be cleared. //! //! This function clears the specified pending I2S interrupts. This function //! must be called in the interrupt handler to keep the interrupt from being //! triggered again immediately upon exit. The \e ulIntFlags parameter can be //! the logical OR of any of the following values: \b I2S_INT_RXERR, //! \b I2S_INT_RXREQ, \b I2S_INT_TXERR, or \b I2S_INT_TXREQ. //! //! \note Because there is a write buffer in the Cortex-M processor, it may //! take several clock cycles before the interrupt source is actually cleared. //! Therefore, it is recommended that the interrupt source be cleared early in //! the interrupt handler (as opposed to the very last action) to avoid //! returning from the interrupt handler before the interrupt source is //! actually cleared. Failure to do so may result in the interrupt handler //! being immediately reentered (because the interrupt controller still sees //! the interrupt source asserted). //! //! \return None. // //***************************************************************************** void I2SIntClear(unsigned long ulBase, unsigned long ulIntFlags) { // // Check the arguments. // ASSERT(ulBase == I2S0_BASE); ASSERT((ulIntFlags & (I2S_INT_RXERR | I2S_INT_RXREQ | I2S_INT_TXERR | I2S_INT_TXREQ)) == ulIntFlags); // // Clear the requested interrupt sources. // HWREG(ulBase + I2S_O_IC) = ulIntFlags; } //***************************************************************************** // //! Registers an interrupt handler for the I2S controller. //! //! \param ulBase is the I2S module base address. //! \param pfnHandler is a pointer to the function to be called when the //! interrupt is activated. //! //! This function sets and enables the handler to be called when the I2S //! controller generates an interrupt. Specific I2S interrupts must still be //! enabled with the I2SIntEnable() function. It is the responsibility of the //! interrupt handler to clear any pending interrupts with I2SIntClear(). //! //! \sa IntRegister() for important information about registering interrupt //! handlers. //! //! \return None. // //***************************************************************************** void I2SIntRegister(unsigned long ulBase, void (*pfnHandler)(void)) { // // Check the arguments. // ASSERT(ulBase == I2S0_BASE); ASSERT(pfnHandler); // // Register the interrupt handler. // IntRegister(INT_I2S0, pfnHandler); // // Enable the I2S interface interrupt. // IntEnable(INT_I2S0); } //***************************************************************************** // //! Unregisters an interrupt handler for the I2S controller. //! //! \param ulBase is the I2S module base address. //! //! This function disables and clears the handler to be called when the //! I2S interrupt occurs. //! //! \sa IntRegister() for important information about registering interrupt //! handlers. //! //! \return None. // //***************************************************************************** void I2SIntUnregister(unsigned long ulBase) { // // Check the arguments. // ASSERT(ulBase == I2S0_BASE); // // Disable the I2S interface interrupt. // IntDisable(INT_I2S0); // // Unregister the interrupt handler. // IntUnregister(INT_I2S0); } //***************************************************************************** // // Close the Doxygen group. //! @} // //*****************************************************************************
483187.c
/* * Copyright(c) 2019 Intel Corporation * SPDX - License - Identifier: BSD - 2 - Clause - Patent */ //#include "EbUtility.h" #include "EbDefinitions.h" static void diffwtd_mask_d16(uint8_t *mask, int which_inverse, int mask_base, const CONV_BUF_TYPE *src0, int src0_stride, const CONV_BUF_TYPE *src1, int src1_stride, int h, int w, ConvolveParams *conv_params, int bd) { int round = 2 * FILTER_BITS - conv_params->round_0 - conv_params->round_1 + (bd - 8); int i, j, m, diff; for (i = 0; i < h; ++i) { for (j = 0; j < w; ++j) { diff = abs(src0[i * src0_stride + j] - src1[i * src1_stride + j]); diff = ROUND_POWER_OF_TWO(diff, round); m = clamp(mask_base + (diff / DIFF_FACTOR), 0, AOM_BLEND_A64_MAX_ALPHA); mask[i * w + j] = which_inverse ? AOM_BLEND_A64_MAX_ALPHA - m : m; } } } void av1_build_compound_diffwtd_mask_d16_c(uint8_t *mask, DIFFWTD_MASK_TYPE mask_type, const CONV_BUF_TYPE *src0, int src0_stride, const CONV_BUF_TYPE *src1, int src1_stride, int h, int w, ConvolveParams *conv_params, int bd) { switch (mask_type) { case DIFFWTD_38: diffwtd_mask_d16(mask, 0, 38, src0, src0_stride, src1, src1_stride, h, w, conv_params, bd); break; case DIFFWTD_38_INV: diffwtd_mask_d16(mask, 1, 38, src0, src0_stride, src1, src1_stride, h, w, conv_params, bd); break; default: assert(0); } }
264037.c
#include <stdio.h> #include <string.h> int main(){ int n,a; printf("Enter the total number of subjects "); scanf("%d",&n); char subject[n-1][20],sub; float marks[n-1],mar; char grade[n-1][3]; float gpa[n-1], avgGpa,gpaSum; char finalGrade[3]; for(a=0;a<n;a++){ printf("Enter Subject and marks out of 100 (Seperated by space) "); scanf("%s %f",subject[a],&marks[a]); } for(a=0;a<n;a++){ if(marks[a]>90){ strcpy(grade[a],"A+"); gpa[a] = 4; } else if(marks[a]<90 && marks[a]>80){ strcpy(grade[a], "A"); gpa[a]= 3.6; } else if(marks[a] < 80 && marks[a] > 70) { strcpy(grade[a], "B+"); gpa[a] = 3.2; } else if (marks[a] < 70 && marks[a] > 60) { strcpy(grade[a], "B"); gpa[a] = 2.8; } else if (marks[a] < 60 && marks[a] > 50) { strcpy(grade[a], "C+"); gpa[a] = 2.4; } else if (marks[a] < 50 && marks[a] > 40) { strcpy(grade[a], "C"); gpa[a] = 2.0; } else if (marks[a] < 20 && marks[a] > 40) { strcpy(grade[a], "D"); gpa[a] = 1.6; } else if (marks[a] < 1 && marks[a] > 20) { strcpy(grade[a], "E"); gpa[a] = 0.8; }else{ strcpy(grade[a], "NA"); gpa[a] = 0; } } gpaSum = 0; printf("\n\nSubject\t Marks\t Grade\t GPA\n"); for (a = 0; a < n; a++) { gpaSum=gpaSum+gpa[a]; printf("%s\t %.2f\t %s\t %.1f\n", subject[a], marks[a], grade[a],gpa[a]); } avgGpa = gpaSum/n; for (a = 0; a < n; a++) { if (avgGpa > 3.6) { strcpy(finalGrade, "A+"); } else if (avgGpa < 3.6 && avgGpa > 3.2) { strcpy(finalGrade, "A"); } else if (avgGpa < 3.2 && avgGpa > 2.8) { strcpy(finalGrade, "B+"); } else if (avgGpa < 2.8 && avgGpa > 2.4) { strcpy(finalGrade, "B"); } else if (avgGpa < 2.0 && avgGpa > 1.6) { strcpy(finalGrade, "C+"); } else if (avgGpa < 1.6 && avgGpa > 0.8) { strcpy(finalGrade, "C"); } else if (avgGpa < 0.8 && avgGpa > 0) { strcpy(finalGrade, "D"); } else { strcpy(finalGrade, "NA"); } } printf("\nYour Avergae Grade Point GPA) is %.2f", avgGpa); printf("\nYour Final Grade is %s", finalGrade); return 0; }
243771.c
// // 1px-libsixel.c - libsixel version // // reference: // libsixel // https://github.com/saitoha/libsixel // // github : // https ://github.com/yoggy/1px // // license : // Copyright(c) 2015 yoggy <yoggy0@gmail.com> // Released under the MIT license // http://opensource.org/licenses/mit-license.php; // #include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <string.h> #include <sixel/sixel.h> #include <termios.h> #include <sys/select.h> #include <sys/ioctl.h> #include <unistd.h> #include <time.h> #include <sys/time.h> void update_pixbuf(uint8_t *pixbuf, int w, int h) { int x = 100, y = 100; int pixbuf_size = w * h * 3; memset(pixbuf, 0, pixbuf_size); struct timeval t; gettimeofday(&t, NULL); int c = t.tv_usec / 1000 / 250; uint8_t r, g, b; switch(c) { case 0: r = 255; g = 0; b = 0; break; case 1: r = 0; g = 255; b = 0; break; case 2: r = 0; g = 0; b = 255; break; case 3: r = 0; g = 0; b = 0; break; } pixbuf[x * 3 + y * w * 3 + 0] = r; pixbuf[x * 3 + y * w * 3 + 1] = g; pixbuf[x * 3 + y * w * 3 + 2] = b; } static int sixel_write(char *data, int size, void *priv) { return fwrite(data, 1, size, (FILE *)priv); } int main(int argc, char *argv[]) { SIXELSTATUS status; sixel_output_t *context = NULL; sixel_dither_t *dither = NULL; uint8_t *pixbuf = NULL; int w = 200, h = 200; int pixbuf_size = w * h * 3; pixbuf = (uint8_t*)malloc(pixbuf_size); update_pixbuf(pixbuf, w, h); status = sixel_output_new(&context, sixel_write, stdout, NULL); if (SIXEL_FAILED(status)) { printf("ERROR: sixel_output_new() failed...\n"); exit(1); } while(1) { update_pixbuf(pixbuf, w, h); // create dither data (pallet) status = sixel_dither_new(&dither, 256, NULL); status = sixel_dither_initialize( dither, pixbuf, w, h, SIXEL_PIXELFORMAT_RGB888, SIXEL_LARGE_AUTO, SIXEL_REP_AUTO, SIXEL_QUALITY_AUTO); // move cursor to top-left printf("\033[H\0337"); // output sixel data to stdout status = sixel_encode(pixbuf, w, h, SIXEL_PIXELFORMAT_RGB888, dither, context); if (SIXEL_FAILED(status)) { printf("ERROR: sixel_encode() failed...\n"); exit(1); } // free dither data sixel_dither_unref(dither); } sixel_output_unref(context); return 0; } /* vim : set ai si expandtab ts=4 sw=4 */
94848.c
/****************************************************************************** * $Id$ * * Project: MapServer * Purpose: Legend generation. * Author: Steve Lime and the MapServer team. * ****************************************************************************** * Copyright (c) 1996-2005 Regents of the University of Minnesota. * * 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 of this Software or works derived from this 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 "mapserver.h" #define PSF .8 #define VMARGIN 5 /* margin at top and bottom of legend graphic */ #define HMARGIN 5 /* margin at left and right of legend graphic */ /* * generic function for drawing a legend icon. (added for bug #2348) * renderer specific drawing functions shouldn't be called directly, but through * this function */ int msDrawLegendIcon(mapObj *map, layerObj *lp, classObj *theclass, int width, int height, imageObj *image, int dstX, int dstY, int scale_independant, class_hittest *hittest) { int i, type, hasmarkersymbol, ret=MS_SUCCESS; double offset; double polygon_contraction = 0.5; /* used to account for the width of a polygon's outline */ shapeObj box, zigzag; lineObj box_line,zigzag_line; pointObj box_point[5], zigzag_point[4]; pointObj marker; char szPath[MS_MAXPATHLEN]; styleObj outline_style; imageObj *image_draw = image; int originalopacity = lp->opacity; rendererVTableObj *renderer; outputFormatObj *transFormat = NULL, *altFormat=NULL; const char *alternativeFormatString = NULL; if(!MS_RENDERER_PLUGIN(image->format)) { msSetError(MS_MISCERR,"unsupported image format","msDrawLegendIcon()"); return MS_FAILURE; } alternativeFormatString = msLayerGetProcessingKey(lp, "RENDERER"); if (MS_RENDERER_PLUGIN(image_draw->format) && alternativeFormatString!=NULL && (altFormat= msSelectOutputFormat(map, alternativeFormatString))) { msInitializeRendererVTable(altFormat); image_draw = msImageCreate(image->width, image->height, altFormat, image->imagepath, image->imageurl, map->resolution, map->defresolution, &map->imagecolor); image_draw->map = map; renderer = MS_IMAGE_RENDERER(image_draw); } else { renderer = MS_IMAGE_RENDERER(image_draw); if (lp->opacity > 0 && lp->opacity < 100) { if (!renderer->supports_transparent_layers) { image_draw = msImageCreate(image->width, image->height, image->format, image->imagepath, image->imageurl, map->resolution, map->defresolution, NULL); if (!image_draw) { msSetError(MS_MISCERR, "Unable to initialize temporary transparent image.", "msDrawLegendIcon()"); return (MS_FAILURE); } image_draw->map = map; /* set opacity to full, as the renderer should be rendering a fully opaque image */ lp->opacity=100; } } } if(renderer->supports_clipping && MS_VALID_COLOR(map->legend.outlinecolor)) { /* keep GD specific code here for now as it supports clipping */ rectObj clip; clip.maxx = dstX + width - 1; clip.maxy = dstY + height -1; clip.minx = dstX; clip.miny = dstY; renderer->setClip(image_draw,clip); } /* if the class has a keyimage, treat it as a point layer * (the keyimage will be treated there) */ if(theclass->keyimage != NULL) { type = MS_LAYER_POINT; } else { /* some polygon layers may be better drawn using zigzag if there is no fill */ type = lp->type; if(type == MS_LAYER_POLYGON) { type = MS_LAYER_LINE; for(i=0; i<theclass->numstyles; i++) { if(MS_VALID_COLOR(theclass->styles[i]->color)) { /* there is a fill */ type = MS_LAYER_POLYGON; } if(MS_VALID_COLOR(theclass->styles[i]->outlinecolor)) { /* there is an outline */ polygon_contraction = MS_MAX(polygon_contraction, theclass->styles[i]->width / 2.0); } } } } /* initialize the box used for polygons and for outlines */ msInitShape(&box); box.line = &box_line; box.numlines = 1; box.line[0].point = box_point; box.line[0].numpoints = 5; box.line[0].point[0].x = dstX + polygon_contraction; box.line[0].point[0].y = dstY + polygon_contraction; box.line[0].point[1].x = dstX + width - polygon_contraction; box.line[0].point[1].y = dstY + polygon_contraction; box.line[0].point[2].x = dstX + width - polygon_contraction; box.line[0].point[2].y = dstY + height - polygon_contraction; box.line[0].point[3].x = dstX + polygon_contraction; box.line[0].point[3].y = dstY + height - polygon_contraction; box.line[0].point[4].x = box.line[0].point[0].x; box.line[0].point[4].y = box.line[0].point[0].y; /* ** now draw the appropriate color/symbol/size combination */ switch(type) { case MS_LAYER_POINT: marker.x = dstX + MS_NINT(width / 2.0); marker.y = dstY + MS_NINT(height / 2.0); if(theclass->keyimage != NULL) { int symbolNum; styleObj imgStyle; symbolObj *symbol=NULL; symbolNum = msAddImageSymbol(&(map->symbolset), msBuildPath(szPath, map->mappath, theclass->keyimage)); if(symbolNum == -1) { msSetError(MS_IMGERR, "Failed to open legend key image", "msCreateLegendIcon()"); return(MS_FAILURE); } symbol = map->symbolset.symbol[symbolNum]; initStyle(&imgStyle); /*set size so that symbol will be scaled properly #3296*/ if (width/symbol->sizex < height/symbol->sizey) imgStyle.size = symbol->sizey*(width/symbol->sizex); else imgStyle.size = symbol->sizey*(height/symbol->sizey); if (imgStyle.size > imgStyle.maxsize) imgStyle.maxsize = imgStyle.size; imgStyle.symbol = symbolNum; ret = msDrawMarkerSymbol(map ,image_draw,&marker,&imgStyle, 1.0); if(UNLIKELY(ret == MS_FAILURE)) goto legend_icon_cleanup; /* TO DO: we may want to handle this differently depending on the relative size of the keyimage */ } else { for(i=0; i<theclass->numstyles; i++) { if(!scale_independant && map->scaledenom > 0) { styleObj *lp = theclass->styles[i]; if((lp->maxscaledenom > 0) && (map->scaledenom > lp->maxscaledenom)) continue; if((lp->minscaledenom > 0) && (map->scaledenom <= lp->minscaledenom)) continue; } if(hittest && hittest->stylehits[i].status == 0) continue; ret = msDrawMarkerSymbol(map, image_draw, &marker, theclass->styles[i], lp->scalefactor * image->resolutionfactor); if(UNLIKELY(ret == MS_FAILURE)) goto legend_icon_cleanup; } } break; case MS_LAYER_LINE: offset = 1; /* To set the offset, we only check the size/width parameter of the first style */ if (theclass->numstyles > 0) { if (theclass->styles[0]->symbol > 0 && theclass->styles[0]->symbol < map->symbolset.numsymbols && map->symbolset.symbol[theclass->styles[0]->symbol]->type != MS_SYMBOL_SIMPLE) offset = theclass->styles[0]->size/2; else offset = theclass->styles[0]->width/2; } msInitShape(&zigzag); zigzag.line = &zigzag_line; zigzag.numlines = 1; zigzag.line[0].point = zigzag_point; zigzag.line[0].numpoints = 4; zigzag.line[0].point[0].x = dstX + offset; zigzag.line[0].point[0].y = dstY + height - offset; zigzag.line[0].point[1].x = dstX + MS_NINT(width / 3.0) - 1; zigzag.line[0].point[1].y = dstY + offset; zigzag.line[0].point[2].x = dstX + MS_NINT(2.0 * width / 3.0) - 1; zigzag.line[0].point[2].y = dstY + height - offset; zigzag.line[0].point[3].x = dstX + width - offset; zigzag.line[0].point[3].y = dstY + offset; for(i=0; i<theclass->numstyles; i++) { if(!scale_independant && map->scaledenom > 0) { styleObj *lp = theclass->styles[i]; if((lp->maxscaledenom > 0) && (map->scaledenom > lp->maxscaledenom)) continue; if((lp->minscaledenom > 0) && (map->scaledenom <= lp->minscaledenom)) continue; } if(hittest && hittest->stylehits[i].status == 0) continue; if (theclass->styles[i]->_geomtransform.type == MS_GEOMTRANSFORM_NONE || theclass->styles[i]->_geomtransform.type == MS_GEOMTRANSFORM_LABELPOINT || theclass->styles[i]->_geomtransform.type == MS_GEOMTRANSFORM_LABELPOLY) { ret = msDrawLineSymbol(map, image_draw, &zigzag, theclass->styles[i], lp->scalefactor * image_draw->resolutionfactor); if(UNLIKELY(ret == MS_FAILURE)) goto legend_icon_cleanup; } else { ret = msDrawTransformedShape(map, image_draw, &zigzag, theclass->styles[i], lp->scalefactor * image_draw->resolutionfactor); if(UNLIKELY(ret == MS_FAILURE)) goto legend_icon_cleanup; } } break; case MS_LAYER_CIRCLE: case MS_LAYER_RASTER: case MS_LAYER_CHART: case MS_LAYER_POLYGON: for(i=0; i<theclass->numstyles; i++) { if(!scale_independant && map->scaledenom > 0) { styleObj *lp = theclass->styles[i]; if((lp->maxscaledenom > 0) && (map->scaledenom > lp->maxscaledenom)) continue; if((lp->minscaledenom > 0) && (map->scaledenom <= lp->minscaledenom)) continue; } if(hittest && hittest->stylehits[i].status == 0) continue; if (theclass->styles[i]->_geomtransform.type == MS_GEOMTRANSFORM_NONE || theclass->styles[i]->_geomtransform.type == MS_GEOMTRANSFORM_LABELPOINT || theclass->styles[i]->_geomtransform.type == MS_GEOMTRANSFORM_LABELPOLY) { ret = msDrawShadeSymbol(map, image_draw, &box, theclass->styles[i], lp->scalefactor * image_draw->resolutionfactor); if(UNLIKELY(ret == MS_FAILURE)) goto legend_icon_cleanup; } else { ret = msDrawTransformedShape(map, image_draw, &box, theclass->styles[i], lp->scalefactor); if(UNLIKELY(ret == MS_FAILURE)) goto legend_icon_cleanup; } } break; default: return MS_FAILURE; break; } /* end symbol drawing */ /* handle label styles */ for(i=0; i<theclass->numlabels; i++) { labelObj *l = theclass->labels[i]; if(!scale_independant && map->scaledenom > 0) { if(msScaleInBounds(map->scaledenom, l->minscaledenom, l->maxscaledenom)) { int j; for(j=0; j<l->numstyles; j++) { styleObj *s = l->styles[j]; marker.x = dstX + MS_NINT(width / 2.0); marker.y = dstY + MS_NINT(height / 2.0); if(s->_geomtransform.type == MS_GEOMTRANSFORM_LABELPOINT) { ret = msDrawMarkerSymbol(map, image_draw, &marker, s, lp->scalefactor); if(UNLIKELY(ret == MS_FAILURE)) goto legend_icon_cleanup; } } } } } /* handle "pure" text layers, i.e. layers with no symbology */ hasmarkersymbol = 0; if(theclass->numstyles == 0) { for(i=0; i<theclass->numlabels; i++) { labelObj *l = theclass->labels[i]; if(!scale_independant && map->scaledenom > 0) { if(msScaleInBounds(map->scaledenom, l->minscaledenom, l->maxscaledenom)) { int j; for(j=0; j<l->numstyles; j++) { styleObj *s = l->styles[j]; if(s->_geomtransform.type == MS_GEOMTRANSFORM_LABELPOINT) { hasmarkersymbol = 1; } } } } } } else { hasmarkersymbol = 1; } if(!hasmarkersymbol && theclass->numlabels>0) { textSymbolObj ts; pointObj textstartpt; marker.x = dstX + MS_NINT(width / 2.0); marker.y = dstY + MS_NINT(height / 2.0); initTextSymbol(&ts); msPopulateTextSymbolForLabelAndString(&ts,theclass->labels[0],msStrdup("Az"),lp->scalefactor*image_draw->resolutionfactor,image_draw->resolutionfactor, duplicate_always); ts.label->size = height - 1; ret = msComputeTextPath(map,&ts); if(UNLIKELY(ret == MS_FAILURE)) goto legend_icon_cleanup; textstartpt = get_metrics(&marker,MS_CC,ts.textpath,0,0,0,0,NULL); ret = msDrawTextSymbol(map,image_draw, textstartpt, &ts); freeTextSymbol(&ts); if(UNLIKELY(ret == MS_FAILURE)) goto legend_icon_cleanup; } /* handle an outline if necessary */ if(MS_VALID_COLOR(map->legend.outlinecolor)) { initStyle(&outline_style); outline_style.color = map->legend.outlinecolor; ret = msDrawLineSymbol(map, image_draw, &box, &outline_style, image_draw->resolutionfactor); if(UNLIKELY(ret == MS_FAILURE)) goto legend_icon_cleanup; /* reset clipping rectangle */ if(renderer->supports_clipping) renderer->resetClip(image_draw); } if (altFormat) { rendererVTableObj *renderer = MS_IMAGE_RENDERER(image); rendererVTableObj *altrenderer = MS_IMAGE_RENDERER(image_draw); rasterBufferObj rb; memset(&rb,0,sizeof(rasterBufferObj)); ret = altrenderer->getRasterBufferHandle(image_draw,&rb); if(UNLIKELY(ret == MS_FAILURE)) goto legend_icon_cleanup; ret = renderer->mergeRasterBuffer(image,&rb,lp->opacity*0.01,0,0,0,0,rb.width,rb.height); if(UNLIKELY(ret == MS_FAILURE)) goto legend_icon_cleanup; /* * hack to work around bug #3834: if we have use an alternate renderer, the symbolset may contain * symbols that reference it. We want to remove those references before the altFormat is destroyed * to avoid a segfault and/or a leak, and so the the main renderer doesn't pick the cache up thinking * it's for him. */ for(i=0; i<map->symbolset.numsymbols; i++) { if (map->symbolset.symbol[i]!=NULL) { symbolObj *s = map->symbolset.symbol[i]; if(s->renderer == altrenderer) { altrenderer->freeSymbol(s); s->renderer = NULL; } } } } else if(image != image_draw) { rendererVTableObj *renderer = MS_IMAGE_RENDERER(image_draw); rasterBufferObj rb; memset(&rb,0,sizeof(rasterBufferObj)); lp->opacity = originalopacity; ret = renderer->getRasterBufferHandle(image_draw,&rb); if(UNLIKELY(ret == MS_FAILURE)) goto legend_icon_cleanup; ret = renderer->mergeRasterBuffer(image,&rb,lp->opacity*0.01,0,0,0,0,rb.width,rb.height); if(UNLIKELY(ret == MS_FAILURE)) goto legend_icon_cleanup; /* deref and possibly free temporary transparent output format. */ msApplyOutputFormat( &transFormat, NULL, MS_NOOVERRIDE, MS_NOOVERRIDE, MS_NOOVERRIDE ); } legend_icon_cleanup: if(image != image_draw) { msFreeImage(image_draw); } return ret; } imageObj *msCreateLegendIcon(mapObj* map, layerObj* lp, classObj* class, int width, int height, int scale_independant) { imageObj *image; outputFormatObj *format = NULL; int i = 0; rendererVTableObj *renderer = MS_MAP_RENDERER(map); if( !renderer ) { msSetError(MS_MISCERR, "invalid map outputformat", "msCreateLegendIcon()"); return(NULL); } /* ensure we have an image format representing the options for the legend */ msApplyOutputFormat(&format, map->outputformat, map->legend.transparent, map->legend.interlace, MS_NOOVERRIDE); image = msImageCreate(width,height,format,map->web.imagepath, map->web.imageurl, map->resolution, map->defresolution, &(map->legend.imagecolor)); /* drop this reference to output format */ msApplyOutputFormat( &format, NULL, MS_NOOVERRIDE, MS_NOOVERRIDE, MS_NOOVERRIDE ); if(image == NULL) { msSetError(MS_IMGERR, "Unable to initialize image.","msCreateLegendIcon()"); return(NULL); } image->map = map; /* Call drawLegendIcon with destination (0, 0) */ /* Return an empty image if lp==NULL || class=NULL */ /* (If class is NULL draw the legend for all classes. Modifications done */ /* Fev 2004 by AY) */ if (lp) { if (class) { if(UNLIKELY(MS_FAILURE == msDrawLegendIcon(map, lp, class, width, height, image, 0, 0, scale_independant, NULL))) { msFreeImage(image); return NULL; } } else { for (i=0; i<lp->numclasses; i++) { if(UNLIKELY(MS_FAILURE == msDrawLegendIcon(map, lp, lp->class[i], width, height, image, 0, 0, scale_independant, NULL))) { msFreeImage(image); return NULL; } } } } return image; } /* * Calculates the optimal size for the legend. If the optional layerObj * argument is given, the legend size will be calculated for only that * layer. Otherwise, the legend size is calculated for all layers that * are not MS_OFF or of MS_LAYER_QUERY type. * * Returns one of: * MS_SUCCESS * MS_FAILURE */ int msLegendCalcSize(mapObj *map, int scale_independent, int *size_x, int *size_y, int *layer_index, int num_layers, map_hittest *hittest, double resolutionfactor) { int i, j; int status, maxwidth=0, nLegendItems=0; char *text; layerObj *lp; rectObj rect; int current_layers=0; /* reset sizes */ *size_x = 0; *size_y = 0; /* enable scale-dependent calculations */ if(!scale_independent) { map->cellsize = msAdjustExtent(&(map->extent), map->width, map->height); status = msCalculateScale(map->extent, map->units, map->width, map->height, map->resolution, &map->scaledenom); if(status != MS_SUCCESS) return MS_FAILURE; } /* * step through all map classes, and for each one that will be displayed * calculate the label size */ if (layer_index != NULL && num_layers >0) current_layers = num_layers; else current_layers = map->numlayers; for(i=0; i< current_layers; i++) { int layerindex; if (layer_index != NULL && num_layers > 0) layerindex = layer_index[i]; else layerindex = map->layerorder[i]; lp = (GET_LAYER(map, layerindex)); if((lp->status == MS_OFF && (layer_index == NULL || num_layers <= 0)) || (lp->type == MS_LAYER_QUERY)) /* skip it */ continue; if(hittest && hittest->layerhits[layerindex].status == 0) continue; if(!scale_independent && map->scaledenom > 0) { if((lp->maxscaledenom > 0) && (map->scaledenom > lp->maxscaledenom)) continue; if((lp->minscaledenom > 0) && (map->scaledenom <= lp->minscaledenom)) continue; } for(j=lp->numclasses-1; j>=0; j--) { textSymbolObj ts; text = lp->class[j]->title?lp->class[j]->title:lp->class[j]->name; /* point to the right legend text, title takes precedence */ if(!text) continue; /* skip it */ /* skip the class if the classgroup is defined */ if(lp->classgroup && (lp->class[j]->group == NULL || strcasecmp(lp->class[j]->group, lp->classgroup) != 0)) continue; /* verify class scale */ if(!scale_independent && map->scaledenom > 0) { if((lp->class[j]->maxscaledenom > 0) && (map->scaledenom > lp->class[j]->maxscaledenom)) continue; if((lp->class[j]->minscaledenom > 0) && (map->scaledenom <= lp->class[j]->minscaledenom)) continue; } if(hittest && hittest->layerhits[layerindex].classhits[j].status == 0) continue; if(*text) { initTextSymbol(&ts); msPopulateTextSymbolForLabelAndString(&ts,&map->legend.label,msStrdup(text),lp->scalefactor*resolutionfactor,resolutionfactor, 0); if(UNLIKELY(MS_FAILURE == msGetTextSymbolSize(map,&ts,&rect))) { freeTextSymbol(&ts); return MS_FAILURE; } freeTextSymbol(&ts); maxwidth = MS_MAX(maxwidth, MS_NINT(rect.maxx - rect.minx)); *size_y += MS_MAX(MS_NINT(rect.maxy - rect.miny), map->legend.keysizey); } else { *size_y += map->legend.keysizey; } nLegendItems++; } } /* Calculate the size of the legend: */ /* - account for the Y keyspacing */ *size_y += (2*VMARGIN) + ((nLegendItems-1) * map->legend.keyspacingy); /* - determine the legend width */ *size_x = (2*HMARGIN) + maxwidth + map->legend.keyspacingx + map->legend.keysizex; if(*size_y <=0 || *size_x <=0) return MS_FAILURE; return MS_SUCCESS; } /* ** Creates a GD image of a legend for a specific map. msDrawLegend() ** respects the current scale, and classes without a name are not ** added to the legend. ** ** scale_independent is used for WMS GetLegendGraphic. It should be set to ** MS_FALSE in most cases. If it is set to MS_TRUE then the layers' minscale ** and maxscale are ignored and layers that are currently out of scale still ** show up in the legend. */ imageObj *msDrawLegend(mapObj *map, int scale_independent, map_hittest *hittest) { int i,j,ret=MS_SUCCESS; /* loop counters */ pointObj pnt; int size_x, size_y=0; layerObj *lp; rectObj rect; imageObj *image = NULL; outputFormatObj *format = NULL; char *text; struct legend_struct { int height; textSymbolObj ts; int layerindex, classindex; struct legend_struct* pred; }; typedef struct legend_struct legendlabel; legendlabel *head=NULL,*cur=NULL; if(!MS_RENDERER_PLUGIN(map->outputformat)) { msSetError(MS_MISCERR,"unsupported output format","msDrawLegend()"); return NULL; } if(msValidateContexts(map) != MS_SUCCESS) return NULL; /* make sure there are no recursive REQUIRES or LABELREQUIRES expressions */ if(msLegendCalcSize(map, scale_independent, &size_x, &size_y, NULL, 0, hittest, map->resolution/map->defresolution) != MS_SUCCESS) return NULL; /* * step through all map classes, and for each one that will be displayed * keep a reference to its label size and text */ for(i=0; i<map->numlayers; i++) { lp = (GET_LAYER(map, map->layerorder[i])); if((lp->status == MS_OFF) || (lp->type == MS_LAYER_QUERY)) /* skip it */ continue; if(hittest && hittest->layerhits[map->layerorder[i]].status == 0) continue; if(!scale_independent && map->scaledenom > 0) { if((lp->maxscaledenom > 0) && (map->scaledenom > lp->maxscaledenom)) continue; if((lp->minscaledenom > 0) && (map->scaledenom <= lp->minscaledenom)) continue; } if(!scale_independent && lp->maxscaledenom <=0 && lp->minscaledenom <=0) { if((lp->maxgeowidth > 0) && ((map->extent.maxx - map->extent.minx) > lp->maxgeowidth)) continue; if((lp->mingeowidth > 0) && ((map->extent.maxx - map->extent.minx) < lp->mingeowidth)) continue; } /* set the scale factor so that scale dependant symbols are drawn in the legend with their default size */ if(lp->sizeunits != MS_PIXELS) { map->cellsize = msAdjustExtent(&(map->extent), map->width, map->height); lp->scalefactor = (msInchesPerUnit(lp->sizeunits,0)/msInchesPerUnit(map->units,0)) / map->cellsize; } for(j=lp->numclasses-1; j>=0; j--) { text = lp->class[j]->title?lp->class[j]->title:lp->class[j]->name; /* point to the right legend text, title takes precedence */ if(!text) continue; /* skip it */ /* skip the class if the classgroup is defined */ if(lp->classgroup && (lp->class[j]->group == NULL || strcasecmp(lp->class[j]->group, lp->classgroup) != 0)) continue; if(!scale_independent && map->scaledenom > 0) { /* verify class scale here */ if((lp->class[j]->maxscaledenom > 0) && (map->scaledenom > lp->class[j]->maxscaledenom)) continue; if((lp->class[j]->minscaledenom > 0) && (map->scaledenom <= lp->class[j]->minscaledenom)) continue; } if(hittest && hittest->layerhits[map->layerorder[i]].classhits[j].status == 0) { continue; } cur = (legendlabel*) msSmallMalloc(sizeof(legendlabel)); initTextSymbol(&cur->ts); if(*text) { msPopulateTextSymbolForLabelAndString(&cur->ts,&map->legend.label,msStrdup(text),lp->scalefactor*map->resolution/map->defresolution,map->resolution/map->defresolution, 0); if(UNLIKELY(MS_FAILURE == msComputeTextPath(map,&cur->ts))) { ret = MS_FAILURE; goto cleanup; } if(UNLIKELY(MS_FAILURE == msGetTextSymbolSize(map,&cur->ts,&rect))) { ret = MS_FAILURE; goto cleanup; } cur->height = MS_MAX(MS_NINT(rect.maxy - rect.miny), map->legend.keysizey); } else { cur->height = map->legend.keysizey; } cur->classindex = j; cur->layerindex = i; cur->pred = head; head = cur; } } /* ensure we have an image format representing the options for the legend. */ msApplyOutputFormat(&format, map->outputformat, map->legend.transparent, map->legend.interlace, MS_NOOVERRIDE); /* initialize the legend image */ image = msImageCreate(size_x, size_y, format, map->web.imagepath, map->web.imageurl, map->resolution, map->defresolution, &map->legend.imagecolor); if(!image) { msSetError(MS_MISCERR, "Unable to initialize image.", "msDrawLegend()"); return NULL; } image->map = map; /* image = renderer->createImage(size_x,size_y,format,&(map->legend.imagecolor)); */ /* drop this reference to output format */ msApplyOutputFormat(&format, NULL, MS_NOOVERRIDE, MS_NOOVERRIDE, MS_NOOVERRIDE); pnt.y = VMARGIN; pnt.x = HMARGIN + map->legend.keysizex + map->legend.keyspacingx; while(cur) { /* cur initially points on the last legend item, i.e. the one that should be at the top */ class_hittest *ch = NULL; /* set the scale factor so that scale dependant symbols are drawn in the legend with their default size */ if(map->layers[cur->layerindex]->sizeunits != MS_PIXELS) { map->cellsize = msAdjustExtent(&(map->extent), map->width, map->height); map->layers[cur->layerindex]->scalefactor = (msInchesPerUnit(map->layers[cur->layerindex]->sizeunits,0)/msInchesPerUnit(map->units,0)) / map->cellsize; } if(hittest) { ch = &hittest->layerhits[cur->layerindex].classhits[cur->classindex]; } ret = msDrawLegendIcon(map, map->layers[cur->layerindex], map->layers[cur->layerindex]->class[cur->classindex], map->legend.keysizex, map->legend.keysizey, image, HMARGIN, (int) pnt.y, scale_independent, ch); if(UNLIKELY(ret != MS_SUCCESS)) goto cleanup; pnt.y += cur->height; if(cur->ts.annotext) { pnt.y -= cur->ts.textpath->bounds.bbox.maxy; ret = msDrawTextSymbol(map,image,pnt,&cur->ts); if(UNLIKELY(ret == MS_FAILURE)) goto cleanup; pnt.y += cur->ts.textpath->bounds.bbox.maxy; freeTextSymbol(&cur->ts); } pnt.y += map->legend.keyspacingy; /* bump y for next label */ /* clean up */ head = cur; cur = cur->pred; free(head); } /* next legend */ cleanup: while(cur) { freeTextSymbol(&cur->ts); head = cur; cur = cur->pred; free(head); } if(UNLIKELY(ret != MS_SUCCESS)) { if(image) msFreeImage(image); return NULL; } return(image); } /* TODO */ int msEmbedLegend(mapObj *map, imageObj *img) { int s,l; pointObj point; imageObj *image = NULL; symbolObj *legendSymbol; char* imageType = NULL; rendererVTableObj *renderer; s = msGetSymbolIndex(&(map->symbolset), "legend", MS_FALSE); if(s != -1) msRemoveSymbol(&(map->symbolset), s); /* solves some caching issues in AGG with long-running processes */ if(msGrowSymbolSet(&map->symbolset) == NULL) return -1; s = map->symbolset.numsymbols; legendSymbol = map->symbolset.symbol[s]; map->symbolset.numsymbols++; initSymbol(legendSymbol); if(!MS_RENDERER_PLUGIN(map->outputformat) || !MS_MAP_RENDERER(map)->supports_pixel_buffer) { imageType = msStrdup(map->imagetype); /* save format */ if MS_DRIVER_CAIRO(map->outputformat) map->outputformat = msSelectOutputFormat( map, "cairopng" ); else map->outputformat = msSelectOutputFormat( map, "png" ); msInitializeRendererVTable(map->outputformat); } renderer = MS_MAP_RENDERER(map); /* render the legend. */ image = msDrawLegend(map, MS_FALSE, NULL); if( image == NULL ) { msFree(imageType); return MS_FAILURE; } if (imageType) { map->outputformat = msSelectOutputFormat( map, imageType ); /* restore format */ msFree(imageType); } /* copy renderered legend image into symbol */ legendSymbol->pixmap_buffer = calloc(1,sizeof(rasterBufferObj)); MS_CHECK_ALLOC(legendSymbol->pixmap_buffer, sizeof(rasterBufferObj), MS_FAILURE); if(MS_SUCCESS != renderer->getRasterBufferCopy(image,legendSymbol->pixmap_buffer)) return MS_FAILURE; legendSymbol->renderer = renderer; msFreeImage( image ); if(!legendSymbol->pixmap_buffer) return(MS_FAILURE); /* something went wrong creating scalebar */ legendSymbol->type = MS_SYMBOL_PIXMAP; /* intialize a few things */ legendSymbol->name = msStrdup("legend"); legendSymbol->sizex = legendSymbol->pixmap_buffer->width; legendSymbol->sizey = legendSymbol->pixmap_buffer->height; /* I'm not too sure this test is sufficient ... NFW. */ /* if(map->legend.transparent == MS_ON) */ /* gdImageColorTransparent(legendSymbol->img_deprecated, 0); */ switch(map->legend.position) { case(MS_LL): point.x = MS_NINT(legendSymbol->sizex/2.0); point.y = map->height - MS_NINT(legendSymbol->sizey/2.0); break; case(MS_LR): point.x = map->width - MS_NINT(legendSymbol->sizex/2.0); point.y = map->height - MS_NINT(legendSymbol->sizey/2.0); break; case(MS_LC): point.x = MS_NINT(map->width/2.0); point.y = map->height - MS_NINT(legendSymbol->sizey/2.0); break; case(MS_UR): point.x = map->width - MS_NINT(legendSymbol->sizex/2.0); point.y = MS_NINT(legendSymbol->sizey/2.0); break; case(MS_UL): point.x = MS_NINT(legendSymbol->sizex/2.0); point.y = MS_NINT(legendSymbol->sizey/2.0); break; case(MS_UC): point.x = MS_NINT(map->width/2.0); point.y = MS_NINT(legendSymbol->sizey/2.0); break; } l = msGetLayerIndex(map, "__embed__legend"); if(l == -1) { if(msGrowMapLayers(map) == NULL) return(-1); l = map->numlayers; map->numlayers++; if(initLayer((GET_LAYER(map, l)), map) == -1) return(-1); GET_LAYER(map, l)->name = msStrdup("__embed__legend"); GET_LAYER(map, l)->type = MS_LAYER_POINT; if(msGrowLayerClasses( GET_LAYER(map, l) ) == NULL) return(-1); if(initClass(GET_LAYER(map, l)->class[0]) == -1) return(-1); GET_LAYER(map, l)->numclasses = 1; /* so we make sure to free it */ /* update the layer order list with the layer's index. */ map->layerorder[l] = l; } GET_LAYER(map, l)->status = MS_ON; if(map->legend.postlabelcache) { /* add it directly to the image */ if(UNLIKELY(msMaybeAllocateClassStyle(GET_LAYER(map, l)->class[0], 0)==MS_FAILURE)) return MS_FAILURE; GET_LAYER(map, l)->class[0]->styles[0]->symbol = s; if(UNLIKELY(MS_FAILURE == msDrawMarkerSymbol(map, img, &point, GET_LAYER(map, l)->class[0]->styles[0], 1.0))) return MS_FAILURE; } else { if(!GET_LAYER(map, l)->class[0]->labels) { if(msGrowClassLabels(GET_LAYER(map, l)->class[0]) == NULL) return MS_FAILURE; initLabel(GET_LAYER(map, l)->class[0]->labels[0]); GET_LAYER(map, l)->class[0]->numlabels = 1; GET_LAYER(map, l)->class[0]->labels[0]->force = MS_TRUE; GET_LAYER(map, l)->class[0]->labels[0]->size = MS_MEDIUM; /* must set a size to have a valid label definition */ GET_LAYER(map, l)->class[0]->labels[0]->priority = MS_MAX_LABEL_PRIORITY; } if(GET_LAYER(map, l)->class[0]->labels[0]->numstyles == 0) { if(msGrowLabelStyles(GET_LAYER(map,l)->class[0]->labels[0]) == NULL) return(MS_FAILURE); GET_LAYER(map,l)->class[0]->labels[0]->numstyles = 1; initStyle(GET_LAYER(map,l)->class[0]->labels[0]->styles[0]); GET_LAYER(map,l)->class[0]->labels[0]->styles[0]->_geomtransform.type = MS_GEOMTRANSFORM_LABELPOINT; } GET_LAYER(map,l)->class[0]->labels[0]->styles[0]->symbol = s; if(UNLIKELY(MS_FAILURE == msAddLabel(map, img, GET_LAYER(map, l)->class[0]->labels[0], l, 0, NULL, &point, -1, NULL))) return MS_FAILURE; } /* Mark layer as deleted so that it doesn't interfere with html legends or with saving maps */ GET_LAYER(map, l)->status = MS_DELETE; return MS_SUCCESS; }
924482.c
/** @file Copyright (c) 2018 Loongson Technology Corporation Limited (www.loongson.cn). All intellectual property rights(Copyright, Patent and Trademark) reserved. Any violations of copyright or other intellectual property rights of the Loongson Technology Corporation Limited will be held accountable in accordance with the law, if you (or any of your subsidiaries, corporate affiliates or agents) initiate directly or indirectly any Intellectual Property Assertion or Intellectual Property Litigation: (i) against Loongson Technology Corporation Limited or any of its subsidiaries or corporate affiliates, (ii) against any party if such Intellectual Property Assertion or Intellectual Property Litigation arises in whole or in part from any software, technology, product or service of Loongson Technology Corporation Limited or any of its subsidiaries or corporate affiliates, or (iii) against any party relating to the Software. 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). **/ #include "UefiCapsuleCommandsLib.h" CONST CHAR16 gUefiCapsuleFileName[] = L"ShellCommand"; EFI_HANDLE gUefiCapsuleHiiHandle = NULL; /** return the file name of the help text file if not using HII. @return The string pointer to the file name. **/ CONST CHAR16* EFIAPI ShellCommandGetManFileNameCapsule ( VOID ) { return (gUefiCapsuleFileName); } SHELL_STATUS EFIAPI ShellCommandRunCapsule ( IN EFI_HANDLE ImageHandle, IN EFI_SYSTEM_TABLE *SystemTable ) { EFI_STATUS Status; Status = CapsuleApp(ImageHandle,SystemTable); if (EFI_ERROR(Status)) { Print (L"CapsuleApp API: failed status - %r\n", Status); return SHELL_LOAD_ERROR; } return SHELL_SUCCESS; } /** Constructor for the Shell Capsule Command library. Install the handlers for Capsule UEFI Shell command. @param ImageHandle The image handle of the process. @param SysTable The EFI System Table pointer. @retval EFI_SUCCESS The shell command handlers were installed sucessfully. @retval EFI_UNSUPPORTED The shell level required was not found. **/ EFI_STATUS EFIAPI CapsuleCommandLibConstructor ( IN EFI_HANDLE ImageHandle, IN EFI_SYSTEM_TABLE *SysTable ) { gUefiCapsuleHiiHandle = NULL; // // check our bit of the profiles mask // if ((PcdGet8(PcdShellProfileMask) & BIT4) == 0) { return (EFI_SUCCESS); } gUefiCapsuleHiiHandle = HiiAddPackages (&gUefiCapsuleHiiGuid, ImageHandle,UefiCapsuleCommandsLibStrings, NULL); if (gUefiCapsuleHiiHandle == NULL) { return (EFI_DEVICE_ERROR); } // // install our shell command handlers // ShellCommandRegisterCommandName(L"capsule", ShellCommandRunCapsule, ShellCommandGetManFileNameCapsule, 0, L"capsule", TRUE , gUefiCapsuleHiiHandle, STRING_TOKEN(STR_GET_HELP_CAPSULE)); return (EFI_SUCCESS); } /** Destructor for the library. free any resources. @param ImageHandle The image handle of the process. @param SysTable The EFI System Table pointer. **/ EFI_STATUS EFIAPI CapsuleCommandLibDestructor ( IN EFI_HANDLE ImageHandle, IN EFI_SYSTEM_TABLE *SysTable ) { if (gUefiCapsuleHiiHandle != NULL) { HiiRemovePackages(gUefiCapsuleHiiHandle); } return (EFI_SUCCESS); }