filename
stringlengths
3
9
code
stringlengths
4
1.87M
610466.c
/* * Copyright (c) 2017, ARM Limited and Contributors. All rights reserved. * * SPDX-License-Identifier: BSD-3-Clause */ #include <arch_helpers.h> #include <assert.h> #include <io/io_block.h> #include <mmio.h> #include <platform_def.h> #include <sys/types.h> #include <utils_def.h> #include "uniphier.h" #define MMC_CMD_SWITCH 6 #define MMC_CMD_SELECT_CARD 7 #define MMC_CMD_SEND_CSD 9 #define MMC_CMD_READ_MULTIPLE_BLOCK 18 #define EXT_CSD_PART_CONF 179 /* R/W */ #define MMC_RSP_PRESENT BIT(0) #define MMC_RSP_136 BIT(1) /* 136 bit response */ #define MMC_RSP_CRC BIT(2) /* expect valid crc */ #define MMC_RSP_BUSY BIT(3) /* card may send busy */ #define MMC_RSP_OPCODE BIT(4) /* response contains opcode */ #define MMC_RSP_NONE (0) #define MMC_RSP_R1 (MMC_RSP_PRESENT | MMC_RSP_CRC | MMC_RSP_OPCODE) #define MMC_RSP_R1b (MMC_RSP_PRESENT | MMC_RSP_CRC | MMC_RSP_OPCODE | \ MMC_RSP_BUSY) #define MMC_RSP_R2 (MMC_RSP_PRESENT | MMC_RSP_136 | MMC_RSP_CRC) #define MMC_RSP_R3 (MMC_RSP_PRESENT) #define MMC_RSP_R4 (MMC_RSP_PRESENT) #define MMC_RSP_R5 (MMC_RSP_PRESENT | MMC_RSP_CRC | MMC_RSP_OPCODE) #define MMC_RSP_R6 (MMC_RSP_PRESENT | MMC_RSP_CRC | MMC_RSP_OPCODE) #define MMC_RSP_R7 (MMC_RSP_PRESENT | MMC_RSP_CRC | MMC_RSP_OPCODE) #define SDHCI_DMA_ADDRESS 0x00 #define SDHCI_BLOCK_SIZE 0x04 #define SDHCI_MAKE_BLKSZ(dma, blksz) ((((dma) & 0x7) << 12) | ((blksz) & 0xFFF)) #define SDHCI_BLOCK_COUNT 0x06 #define SDHCI_ARGUMENT 0x08 #define SDHCI_TRANSFER_MODE 0x0C #define SDHCI_TRNS_DMA BIT(0) #define SDHCI_TRNS_BLK_CNT_EN BIT(1) #define SDHCI_TRNS_ACMD12 BIT(2) #define SDHCI_TRNS_READ BIT(4) #define SDHCI_TRNS_MULTI BIT(5) #define SDHCI_COMMAND 0x0E #define SDHCI_CMD_RESP_MASK 0x03 #define SDHCI_CMD_CRC 0x08 #define SDHCI_CMD_INDEX 0x10 #define SDHCI_CMD_DATA 0x20 #define SDHCI_CMD_ABORTCMD 0xC0 #define SDHCI_CMD_RESP_NONE 0x00 #define SDHCI_CMD_RESP_LONG 0x01 #define SDHCI_CMD_RESP_SHORT 0x02 #define SDHCI_CMD_RESP_SHORT_BUSY 0x03 #define SDHCI_MAKE_CMD(c, f) ((((c) & 0xff) << 8) | ((f) & 0xff)) #define SDHCI_RESPONSE 0x10 #define SDHCI_HOST_CONTROL 0x28 #define SDHCI_CTRL_DMA_MASK 0x18 #define SDHCI_CTRL_SDMA 0x00 #define SDHCI_BLOCK_GAP_CONTROL 0x2A #define SDHCI_SOFTWARE_RESET 0x2F #define SDHCI_RESET_CMD 0x02 #define SDHCI_RESET_DATA 0x04 #define SDHCI_INT_STATUS 0x30 #define SDHCI_INT_RESPONSE BIT(0) #define SDHCI_INT_DATA_END BIT(1) #define SDHCI_INT_DMA_END BIT(3) #define SDHCI_INT_ERROR BIT(15) #define SDHCI_SIGNAL_ENABLE 0x38 /* RCA assigned by Boot ROM */ #define UNIPHIER_EMMC_RCA 0x1000 struct uniphier_mmc_cmd { unsigned int cmdidx; unsigned int resp_type; unsigned int cmdarg; unsigned int is_data; }; static int uniphier_emmc_block_addressing; static int uniphier_emmc_send_cmd(uintptr_t host_base, struct uniphier_mmc_cmd *cmd) { uint32_t mode = 0; uint32_t end_bit; uint32_t stat, flags, dma_addr; mmio_write_32(host_base + SDHCI_INT_STATUS, -1); mmio_write_32(host_base + SDHCI_SIGNAL_ENABLE, 0); mmio_write_32(host_base + SDHCI_ARGUMENT, cmd->cmdarg); if (cmd->is_data) mode = SDHCI_TRNS_DMA | SDHCI_TRNS_BLK_CNT_EN | SDHCI_TRNS_ACMD12 | SDHCI_TRNS_READ | SDHCI_TRNS_MULTI; mmio_write_16(host_base + SDHCI_TRANSFER_MODE, mode); if (!(cmd->resp_type & MMC_RSP_PRESENT)) flags = SDHCI_CMD_RESP_NONE; else if (cmd->resp_type & MMC_RSP_136) flags = SDHCI_CMD_RESP_LONG; else if (cmd->resp_type & MMC_RSP_BUSY) flags = SDHCI_CMD_RESP_SHORT_BUSY; else flags = SDHCI_CMD_RESP_SHORT; if (cmd->resp_type & MMC_RSP_CRC) flags |= SDHCI_CMD_CRC; if (cmd->resp_type & MMC_RSP_OPCODE) flags |= SDHCI_CMD_INDEX; if (cmd->is_data) flags |= SDHCI_CMD_DATA; if (cmd->resp_type & MMC_RSP_BUSY || cmd->is_data) end_bit = SDHCI_INT_DATA_END; else end_bit = SDHCI_INT_RESPONSE; mmio_write_16(host_base + SDHCI_COMMAND, SDHCI_MAKE_CMD(cmd->cmdidx, flags)); do { stat = mmio_read_32(host_base + SDHCI_INT_STATUS); if (stat & SDHCI_INT_ERROR) return -EIO; if (stat & SDHCI_INT_DMA_END) { mmio_write_32(host_base + SDHCI_INT_STATUS, stat); dma_addr = mmio_read_32(host_base + SDHCI_DMA_ADDRESS); mmio_write_32(host_base + SDHCI_DMA_ADDRESS, dma_addr); } } while (!(stat & end_bit)); return 0; } static int uniphier_emmc_switch_part(uintptr_t host_base, int part_num) { struct uniphier_mmc_cmd cmd = {0}; cmd.cmdidx = MMC_CMD_SWITCH; cmd.resp_type = MMC_RSP_R1b; cmd.cmdarg = (EXT_CSD_PART_CONF << 16) | (part_num << 8) | (3 << 24); return uniphier_emmc_send_cmd(host_base, &cmd); } static int uniphier_emmc_is_over_2gb(uintptr_t host_base) { struct uniphier_mmc_cmd cmd = {0}; uint32_t csd40, csd72; /* CSD[71:40], CSD[103:72] */ int ret; cmd.cmdidx = MMC_CMD_SEND_CSD; cmd.resp_type = MMC_RSP_R2; cmd.cmdarg = UNIPHIER_EMMC_RCA << 16; ret = uniphier_emmc_send_cmd(host_base, &cmd); if (ret) return ret; csd40 = mmio_read_32(host_base + SDHCI_RESPONSE + 4); csd72 = mmio_read_32(host_base + SDHCI_RESPONSE + 8); return !(~csd40 & 0xffc00380) && !(~csd72 & 0x3); } static int uniphier_emmc_load_image(uintptr_t host_base, uint32_t dev_addr, unsigned long load_addr, uint32_t block_cnt) { struct uniphier_mmc_cmd cmd = {0}; uint8_t tmp; assert((load_addr >> 32) == 0); mmio_write_32(host_base + SDHCI_DMA_ADDRESS, load_addr); mmio_write_16(host_base + SDHCI_BLOCK_SIZE, SDHCI_MAKE_BLKSZ(7, 512)); mmio_write_16(host_base + SDHCI_BLOCK_COUNT, block_cnt); tmp = mmio_read_8(host_base + SDHCI_HOST_CONTROL); tmp &= ~SDHCI_CTRL_DMA_MASK; tmp |= SDHCI_CTRL_SDMA; mmio_write_8(host_base + SDHCI_HOST_CONTROL, tmp); tmp = mmio_read_8(host_base + SDHCI_BLOCK_GAP_CONTROL); tmp &= ~1; /* clear Stop At Block Gap Request */ mmio_write_8(host_base + SDHCI_BLOCK_GAP_CONTROL, tmp); cmd.cmdidx = MMC_CMD_READ_MULTIPLE_BLOCK; cmd.resp_type = MMC_RSP_R1; cmd.cmdarg = dev_addr; cmd.is_data = 1; return uniphier_emmc_send_cmd(host_base, &cmd); } static size_t uniphier_emmc_read(int lba, uintptr_t buf, size_t size) { uintptr_t host_base = 0x5a000200; int ret; inv_dcache_range(buf, size); if (!uniphier_emmc_block_addressing) lba *= 512; ret = uniphier_emmc_load_image(host_base, lba, buf, size / 512); inv_dcache_range(buf, size); return ret ? 0 : size; } static const struct io_block_dev_spec uniphier_emmc_dev_spec = { .buffer = { .offset = UNIPHIER_BLOCK_BUF_BASE, .length = UNIPHIER_BLOCK_BUF_SIZE, }, .ops = { .read = uniphier_emmc_read, }, .block_size = 512, }; static int uniphier_emmc_hw_init(void) { uintptr_t host_base = 0x5a000200; struct uniphier_mmc_cmd cmd = {0}; int ret; /* * deselect card before SEND_CSD command. * Do not check the return code. It fails, but it is OK. */ cmd.cmdidx = MMC_CMD_SELECT_CARD; cmd.resp_type = MMC_RSP_R1; uniphier_emmc_send_cmd(host_base, &cmd); /* CMD7 (arg=0) */ /* reset CMD Line */ mmio_write_8(host_base + SDHCI_SOFTWARE_RESET, SDHCI_RESET_CMD | SDHCI_RESET_DATA); while (mmio_read_8(host_base + SDHCI_SOFTWARE_RESET)) ; ret = uniphier_emmc_is_over_2gb(host_base); if (ret < 0) return ret; uniphier_emmc_block_addressing = ret; cmd.cmdarg = UNIPHIER_EMMC_RCA << 16; /* select card again */ ret = uniphier_emmc_send_cmd(host_base, &cmd); if (ret) return ret; /* switch to Boot Partition 1 */ ret = uniphier_emmc_switch_part(host_base, 1); if (ret) return ret; return 0; } int uniphier_emmc_init(uintptr_t *block_dev_spec) { int ret; ret = uniphier_emmc_hw_init(); if (ret) return ret; *block_dev_spec = (uintptr_t)&uniphier_emmc_dev_spec; return 0; }
637320.c
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE134_Uncontrolled_Format_String__wchar_t_connect_socket_vprintf_42.c Label Definition File: CWE134_Uncontrolled_Format_String.vasinks.label.xml Template File: sources-vasinks-42.tmpl.c */ /* * @description * CWE: 134 Uncontrolled Format String * BadSource: connect_socket Read data using a connect socket (client side) * GoodSource: Copy a fixed string into data * Sinks: vprintf * GoodSink: vwprintf with a format string * BadSink : vwprintf without a format string * Flow Variant: 42 Data flow: data returned from one function to another in the same source file * * */ #include <stdarg.h> #include "std_testcase.h" #ifdef _WIN32 # include <winsock2.h> # include <windows.h> # include <direct.h> # pragma comment(lib, "ws2_32") /* include ws2_32.lib when linking */ # define CLOSE_SOCKET closesocket # define PATH_SZ 100 #else /* NOT _WIN32 */ # define INVALID_SOCKET -1 # define SOCKET_ERROR -1 # define CLOSE_SOCKET close # define SOCKET int # define PATH_SZ PATH_MAX #endif #define TCP_PORT 27015 #ifndef OMITBAD static wchar_t * bad_source(wchar_t * data) { { #ifdef _WIN32 WSADATA wsa_data; int wsa_data_init = 0; #endif int recv_rv; struct sockaddr_in s_in; wchar_t *replace; SOCKET connect_socket = INVALID_SOCKET; size_t data_len = wcslen(data); do { #ifdef _WIN32 if (WSAStartup(MAKEWORD(2,2), &wsa_data) != NO_ERROR) break; wsa_data_init = 1; #endif connect_socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if (connect_socket == INVALID_SOCKET) break; memset(&s_in, 0, sizeof(s_in)); s_in.sin_family = AF_INET; s_in.sin_addr.s_addr = inet_addr("127.0.0.1"); s_in.sin_port = htons(TCP_PORT); if (connect(connect_socket, (struct sockaddr*)&s_in, sizeof(s_in)) == SOCKET_ERROR) break; /* Abort on error or the connection was closed, make sure to recv one * less char than is in the recv_buf in order to append a terminator */ recv_rv = recv(connect_socket, (char *)data+data_len, (int)(100-data_len-1), 0); if (recv_rv == SOCKET_ERROR || recv_rv == 0) break; /* Append null terminator */ data[recv_rv] = L'\0'; /* Eliminate CRLF */ replace = wcschr(data, L'\r'); if (replace) *replace = L'\0'; replace = wcschr(data, L'\n'); if (replace) *replace = L'\0'; } while (0); if (connect_socket != INVALID_SOCKET) CLOSE_SOCKET(connect_socket); #ifdef _WIN32 if (wsa_data_init) WSACleanup(); #endif } return data; } static void bad_vasink(wchar_t * data, ...) { { va_list args; va_start(args, data); /* POTENTIAL FLAW: Do not specify the format allowing a possible format string vulnerability */ vwprintf(data, args); va_end(args); } } void CWE134_Uncontrolled_Format_String__wchar_t_connect_socket_vprintf_42_bad() { wchar_t * data; wchar_t data_buf[100] = L""; data = data_buf; data = bad_source(data); bad_vasink(data, data); } #endif /* OMITBAD */ #ifndef OMITGOOD /* goodG2B uses the GoodSource with the BadSink */ static wchar_t * goodG2B_source(wchar_t * data) { /* FIX: Use a fixed string that does not contain a format specifier */ wcscpy(data, L"fixedstringtest"); return data; } static void goodG2B_vasink(wchar_t * data, ...) { { va_list args; va_start(args, data); /* POTENTIAL FLAW: Do not specify the format allowing a possible format string vulnerability */ vwprintf(data, args); va_end(args); } } static void goodG2B() { wchar_t * data; wchar_t data_buf[100] = L""; data = data_buf; data = goodG2B_source(data); goodG2B_vasink(data, data); } /* goodB2G uses the BadSource with the GoodSink */ static wchar_t * goodB2G_source(wchar_t * data) { { #ifdef _WIN32 WSADATA wsa_data; int wsa_data_init = 0; #endif int recv_rv; struct sockaddr_in s_in; wchar_t *replace; SOCKET connect_socket = INVALID_SOCKET; size_t data_len = wcslen(data); do { #ifdef _WIN32 if (WSAStartup(MAKEWORD(2,2), &wsa_data) != NO_ERROR) break; wsa_data_init = 1; #endif connect_socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if (connect_socket == INVALID_SOCKET) break; memset(&s_in, 0, sizeof(s_in)); s_in.sin_family = AF_INET; s_in.sin_addr.s_addr = inet_addr("127.0.0.1"); s_in.sin_port = htons(TCP_PORT); if (connect(connect_socket, (struct sockaddr*)&s_in, sizeof(s_in)) == SOCKET_ERROR) break; /* Abort on error or the connection was closed, make sure to recv one * less char than is in the recv_buf in order to append a terminator */ recv_rv = recv(connect_socket, (char *)data+data_len, (int)(100-data_len-1), 0); if (recv_rv == SOCKET_ERROR || recv_rv == 0) break; /* Append null terminator */ data[recv_rv] = L'\0'; /* Eliminate CRLF */ replace = wcschr(data, L'\r'); if (replace) *replace = L'\0'; replace = wcschr(data, L'\n'); if (replace) *replace = L'\0'; } while (0); if (connect_socket != INVALID_SOCKET) CLOSE_SOCKET(connect_socket); #ifdef _WIN32 if (wsa_data_init) WSACleanup(); #endif } return data; } static void goodB2G_vasink(wchar_t * data, ...) { { va_list args; va_start(args, data); /* FIX: Specify the format disallowing a format string vulnerability */ vwprintf(L"%s", args); va_end(args); } } static void goodB2G() { wchar_t * data; wchar_t data_buf[100] = L""; data = data_buf; data = goodB2G_source(data); goodB2G_vasink(data, data); } void CWE134_Uncontrolled_Format_String__wchar_t_connect_socket_vprintf_42_good() { goodG2B(); goodB2G(); } #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()..."); CWE134_Uncontrolled_Format_String__wchar_t_connect_socket_vprintf_42_good(); printLine("Finished good()"); #endif /* OMITGOOD */ #ifndef OMITBAD printLine("Calling bad()..."); CWE134_Uncontrolled_Format_String__wchar_t_connect_socket_vprintf_42_bad(); printLine("Finished bad()"); #endif /* OMITBAD */ return 0; } #endif
378679.c
#include <stdlib.h> #include <stdio.h> #include <math.h> int main(){ double a,b,c,x,y; printf("\nCalculadora de funcao de segundo grau"); printf("\n(Considere a equacao como ax2 + bx + c = y)"); printf("\nDigite o (a) da equacao: "); scanf("%lf", &a); printf("\nDigite o (b) da equacao: "); scanf("%lf", &b); printf("\nDigite o (c) da equacao: "); scanf("%lf", &c); printf("\nDigite o (x) da equacao: "); scanf("%lf", &x); y = a*pow(x,2) + b*x + c; printf("\nPara essa equacao o Y e %f\n", y); return 0; }
477172.c
/* * Copyright 2012 Cisco Systems, Inc. All rights reserved. * * This program is free software; you may 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. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #include <linux/module.h> #include <linux/errno.h> #include <linux/debugfs.h> #include "fnic.h" static struct dentry *fnic_trace_debugfs_root; static struct dentry *fnic_trace_debugfs_file; static struct dentry *fnic_trace_enable; static struct dentry *fnic_stats_debugfs_root; static struct dentry *fnic_fc_trace_debugfs_file; static struct dentry *fnic_fc_rdata_trace_debugfs_file; static struct dentry *fnic_fc_trace_enable; static struct dentry *fnic_fc_trace_clear; struct fc_trace_flag_type { u8 fc_row_file; u8 fc_normal_file; u8 fnic_trace; u8 fc_trace; u8 fc_clear; }; static struct fc_trace_flag_type *fc_trc_flag; /* * fnic_debugfs_init - Initialize debugfs for fnic debug logging * * Description: * When Debugfs is configured this routine sets up the fnic debugfs * file system. If not already created, this routine will create the * fnic directory and statistics directory for trace buffer and * stats logging. */ int fnic_debugfs_init(void) { int rc = -1; fnic_trace_debugfs_root = debugfs_create_dir("fnic", NULL); if (!fnic_trace_debugfs_root) { printk(KERN_DEBUG "Cannot create debugfs root\n"); return rc; } if (!fnic_trace_debugfs_root) { printk(KERN_DEBUG "fnic root directory doesn't exist in debugfs\n"); return rc; } fnic_stats_debugfs_root = debugfs_create_dir("statistics", fnic_trace_debugfs_root); if (!fnic_stats_debugfs_root) { printk(KERN_DEBUG "Cannot create Statistics directory\n"); return rc; } /* Allocate memory to structure */ fc_trc_flag = (struct fc_trace_flag_type *) vmalloc(sizeof(struct fc_trace_flag_type)); if (fc_trc_flag) { fc_trc_flag->fc_row_file = 0; fc_trc_flag->fc_normal_file = 1; fc_trc_flag->fnic_trace = 2; fc_trc_flag->fc_trace = 3; fc_trc_flag->fc_clear = 4; } rc = 0; return rc; } /* * fnic_debugfs_terminate - Tear down debugfs infrastructure * * Description: * When Debugfs is configured this routine removes debugfs file system * elements that are specific to fnic. */ void fnic_debugfs_terminate(void) { debugfs_remove(fnic_stats_debugfs_root); fnic_stats_debugfs_root = NULL; debugfs_remove(fnic_trace_debugfs_root); fnic_trace_debugfs_root = NULL; if (fc_trc_flag) vfree(fc_trc_flag); } /* * fnic_trace_ctrl_open - Open the trace_enable file for fnic_trace * Or Open fc_trace_enable file for fc_trace * @inode: The inode pointer. * @file: The file pointer to attach the trace enable/disable flag. * * Description: * This routine opens a debugsfs file trace_enable or fc_trace_enable. * * Returns: * This function returns zero if successful. */ static int fnic_trace_ctrl_open(struct inode *inode, struct file *filp) { filp->private_data = inode->i_private; return 0; } /* * fnic_trace_ctrl_read - * Read trace_enable ,fc_trace_enable * or fc_trace_clear debugfs file * @filp: The file pointer to read from. * @ubuf: The buffer to copy the data to. * @cnt: The number of bytes to read. * @ppos: The position in the file to start reading from. * * Description: * This routine reads value of variable fnic_tracing_enabled or * fnic_fc_tracing_enabled or fnic_fc_trace_cleared * and stores into local @buf. * It will start reading file at @ppos and * copy up to @cnt of data to @ubuf from @buf. * * Returns: * This function returns the amount of data that was read. */ static ssize_t fnic_trace_ctrl_read(struct file *filp, char __user *ubuf, size_t cnt, loff_t *ppos) { char buf[64]; int len; u8 *trace_type; len = 0; trace_type = (u8 *)filp->private_data; if (*trace_type == fc_trc_flag->fnic_trace) len = sprintf(buf, "%u\n", fnic_tracing_enabled); else if (*trace_type == fc_trc_flag->fc_trace) len = sprintf(buf, "%u\n", fnic_fc_tracing_enabled); else if (*trace_type == fc_trc_flag->fc_clear) len = sprintf(buf, "%u\n", fnic_fc_trace_cleared); else pr_err("fnic: Cannot read to any debugfs file\n"); return simple_read_from_buffer(ubuf, cnt, ppos, buf, len); } /* * fnic_trace_ctrl_write - * Write to trace_enable, fc_trace_enable or * fc_trace_clear debugfs file * @filp: The file pointer to write from. * @ubuf: The buffer to copy the data from. * @cnt: The number of bytes to write. * @ppos: The position in the file to start writing to. * * Description: * This routine writes data from user buffer @ubuf to buffer @buf and * sets fc_trace_enable ,tracing_enable or fnic_fc_trace_cleared * value as per user input. * * Returns: * This function returns the amount of data that was written. */ static ssize_t fnic_trace_ctrl_write(struct file *filp, const char __user *ubuf, size_t cnt, loff_t *ppos) { char buf[64]; unsigned long val; int ret; u8 *trace_type; trace_type = (u8 *)filp->private_data; if (cnt >= sizeof(buf)) return -EINVAL; if (copy_from_user(&buf, ubuf, cnt)) return -EFAULT; buf[cnt] = 0; ret = kstrtoul(buf, 10, &val); if (ret < 0) return ret; if (*trace_type == fc_trc_flag->fnic_trace) fnic_tracing_enabled = val; else if (*trace_type == fc_trc_flag->fc_trace) fnic_fc_tracing_enabled = val; else if (*trace_type == fc_trc_flag->fc_clear) fnic_fc_trace_cleared = val; else pr_err("fnic: cannot write to any debufs file\n"); (*ppos)++; return cnt; } static const struct file_operations fnic_trace_ctrl_fops = { .owner = THIS_MODULE, .open = fnic_trace_ctrl_open, .read = fnic_trace_ctrl_read, .write = fnic_trace_ctrl_write, }; /* * fnic_trace_debugfs_open - Open the fnic trace log * @inode: The inode pointer * @file: The file pointer to attach the log output * * Description: * This routine is the entry point for the debugfs open file operation. * It allocates the necessary buffer for the log, fills the buffer from * the in-memory log and then returns a pointer to that log in * the private_data field in @file. * * Returns: * This function returns zero if successful. On error it will return * a negative error value. */ static int fnic_trace_debugfs_open(struct inode *inode, struct file *file) { fnic_dbgfs_t *fnic_dbg_prt; u8 *rdata_ptr; rdata_ptr = (u8 *)inode->i_private; fnic_dbg_prt = kzalloc(sizeof(fnic_dbgfs_t), GFP_KERNEL); if (!fnic_dbg_prt) return -ENOMEM; if (*rdata_ptr == fc_trc_flag->fnic_trace) { fnic_dbg_prt->buffer = vmalloc(3 * (trace_max_pages * PAGE_SIZE)); if (!fnic_dbg_prt->buffer) { kfree(fnic_dbg_prt); return -ENOMEM; } memset((void *)fnic_dbg_prt->buffer, 0, 3 * (trace_max_pages * PAGE_SIZE)); fnic_dbg_prt->buffer_len = fnic_get_trace_data(fnic_dbg_prt); } else { fnic_dbg_prt->buffer = vmalloc(3 * (fnic_fc_trace_max_pages * PAGE_SIZE)); if (!fnic_dbg_prt->buffer) { kfree(fnic_dbg_prt); return -ENOMEM; } memset((void *)fnic_dbg_prt->buffer, 0, 3 * (fnic_fc_trace_max_pages * PAGE_SIZE)); fnic_dbg_prt->buffer_len = fnic_fc_trace_get_data(fnic_dbg_prt, *rdata_ptr); } file->private_data = fnic_dbg_prt; return 0; } /* * fnic_trace_debugfs_lseek - Seek through a debugfs file * @file: The file pointer to seek through. * @offset: The offset to seek to or the amount to seek by. * @howto: Indicates how to seek. * * Description: * This routine is the entry point for the debugfs lseek file operation. * The @howto parameter indicates whether @offset is the offset to directly * seek to, or if it is a value to seek forward or reverse by. This function * figures out what the new offset of the debugfs file will be and assigns * that value to the f_pos field of @file. * * Returns: * This function returns the new offset if successful and returns a negative * error if unable to process the seek. */ static loff_t fnic_trace_debugfs_lseek(struct file *file, loff_t offset, int howto) { fnic_dbgfs_t *fnic_dbg_prt = file->private_data; return fixed_size_llseek(file, offset, howto, fnic_dbg_prt->buffer_len); } /* * fnic_trace_debugfs_read - Read a debugfs file * @file: The file pointer to read from. * @ubuf: The buffer to copy the data to. * @nbytes: The number of bytes to read. * @pos: The position in the file to start reading from. * * Description: * This routine reads data from the buffer indicated in the private_data * field of @file. It will start reading at @pos and copy up to @nbytes of * data to @ubuf. * * Returns: * This function returns the amount of data that was read (this could be * less than @nbytes if the end of the file was reached). */ static ssize_t fnic_trace_debugfs_read(struct file *file, char __user *ubuf, size_t nbytes, loff_t *pos) { fnic_dbgfs_t *fnic_dbg_prt = file->private_data; int rc = 0; rc = simple_read_from_buffer(ubuf, nbytes, pos, fnic_dbg_prt->buffer, fnic_dbg_prt->buffer_len); return rc; } /* * fnic_trace_debugfs_release - Release the buffer used to store * debugfs file data * @inode: The inode pointer * @file: The file pointer that contains the buffer to release * * Description: * This routine frees the buffer that was allocated when the debugfs * file was opened. * * Returns: * This function returns zero. */ static int fnic_trace_debugfs_release(struct inode *inode, struct file *file) { fnic_dbgfs_t *fnic_dbg_prt = file->private_data; vfree(fnic_dbg_prt->buffer); kfree(fnic_dbg_prt); return 0; } static const struct file_operations fnic_trace_debugfs_fops = { .owner = THIS_MODULE, .open = fnic_trace_debugfs_open, .llseek = fnic_trace_debugfs_lseek, .read = fnic_trace_debugfs_read, .release = fnic_trace_debugfs_release, }; /* * fnic_trace_debugfs_init - Initialize debugfs for fnic trace logging * * Description: * When Debugfs is configured this routine sets up the fnic debugfs * file system. If not already created, this routine will create the * create file trace to log fnic trace buffer output into debugfs and * it will also create file trace_enable to control enable/disable of * trace logging into trace buffer. */ int fnic_trace_debugfs_init(void) { int rc = -1; if (!fnic_trace_debugfs_root) { printk(KERN_DEBUG "FNIC Debugfs root directory doesn't exist\n"); return rc; } fnic_trace_enable = debugfs_create_file("tracing_enable", S_IFREG|S_IRUGO|S_IWUSR, fnic_trace_debugfs_root, &(fc_trc_flag->fnic_trace), &fnic_trace_ctrl_fops); if (!fnic_trace_enable) { printk(KERN_DEBUG "Cannot create trace_enable file under debugfs\n"); return rc; } fnic_trace_debugfs_file = debugfs_create_file("trace", S_IFREG|S_IRUGO|S_IWUSR, fnic_trace_debugfs_root, &(fc_trc_flag->fnic_trace), &fnic_trace_debugfs_fops); if (!fnic_trace_debugfs_file) { printk(KERN_DEBUG "Cannot create trace file under debugfs\n"); return rc; } rc = 0; return rc; } /* * fnic_trace_debugfs_terminate - Tear down debugfs infrastructure * * Description: * When Debugfs is configured this routine removes debugfs file system * elements that are specific to fnic trace logging. */ void fnic_trace_debugfs_terminate(void) { debugfs_remove(fnic_trace_debugfs_file); fnic_trace_debugfs_file = NULL; debugfs_remove(fnic_trace_enable); fnic_trace_enable = NULL; } /* * fnic_fc_trace_debugfs_init - * Initialize debugfs for fnic control frame trace logging * * Description: * When Debugfs is configured this routine sets up the fnic_fc debugfs * file system. If not already created, this routine will create the * create file trace to log fnic fc trace buffer output into debugfs and * it will also create file fc_trace_enable to control enable/disable of * trace logging into trace buffer. */ int fnic_fc_trace_debugfs_init(void) { int rc = -1; if (!fnic_trace_debugfs_root) { pr_err("fnic:Debugfs root directory doesn't exist\n"); return rc; } fnic_fc_trace_enable = debugfs_create_file("fc_trace_enable", S_IFREG|S_IRUGO|S_IWUSR, fnic_trace_debugfs_root, &(fc_trc_flag->fc_trace), &fnic_trace_ctrl_fops); if (!fnic_fc_trace_enable) { pr_err("fnic: Failed create fc_trace_enable file\n"); return rc; } fnic_fc_trace_clear = debugfs_create_file("fc_trace_clear", S_IFREG|S_IRUGO|S_IWUSR, fnic_trace_debugfs_root, &(fc_trc_flag->fc_clear), &fnic_trace_ctrl_fops); if (!fnic_fc_trace_clear) { pr_err("fnic: Failed to create fc_trace_enable file\n"); return rc; } fnic_fc_rdata_trace_debugfs_file = debugfs_create_file("fc_trace_rdata", S_IFREG|S_IRUGO|S_IWUSR, fnic_trace_debugfs_root, &(fc_trc_flag->fc_normal_file), &fnic_trace_debugfs_fops); if (!fnic_fc_rdata_trace_debugfs_file) { pr_err("fnic: Failed create fc_rdata_trace file\n"); return rc; } fnic_fc_trace_debugfs_file = debugfs_create_file("fc_trace", S_IFREG|S_IRUGO|S_IWUSR, fnic_trace_debugfs_root, &(fc_trc_flag->fc_row_file), &fnic_trace_debugfs_fops); if (!fnic_fc_trace_debugfs_file) { pr_err("fnic: Failed to create fc_trace file\n"); return rc; } rc = 0; return rc; } /* * fnic_fc_trace_debugfs_terminate - Tear down debugfs infrastructure * * Description: * When Debugfs is configured this routine removes debugfs file system * elements that are specific to fnic_fc trace logging. */ void fnic_fc_trace_debugfs_terminate(void) { debugfs_remove(fnic_fc_trace_debugfs_file); fnic_fc_trace_debugfs_file = NULL; debugfs_remove(fnic_fc_rdata_trace_debugfs_file); fnic_fc_rdata_trace_debugfs_file = NULL; debugfs_remove(fnic_fc_trace_enable); fnic_fc_trace_enable = NULL; debugfs_remove(fnic_fc_trace_clear); fnic_fc_trace_clear = NULL; } /* * fnic_reset_stats_open - Open the reset_stats file * @inode: The inode pointer. * @file: The file pointer to attach the stats reset flag. * * Description: * This routine opens a debugsfs file reset_stats and stores i_private data * to debug structure to retrieve later for while performing other * file oprations. * * Returns: * This function returns zero if successful. */ static int fnic_reset_stats_open(struct inode *inode, struct file *file) { struct stats_debug_info *debug; debug = kzalloc(sizeof(struct stats_debug_info), GFP_KERNEL); if (!debug) return -ENOMEM; debug->i_private = inode->i_private; file->private_data = debug; return 0; } /* * fnic_reset_stats_read - Read a reset_stats debugfs file * @filp: The file pointer to read from. * @ubuf: The buffer to copy the data to. * @cnt: The number of bytes to read. * @ppos: The position in the file to start reading from. * * Description: * This routine reads value of variable reset_stats * and stores into local @buf. It will start reading file at @ppos and * copy up to @cnt of data to @ubuf from @buf. * * Returns: * This function returns the amount of data that was read. */ static ssize_t fnic_reset_stats_read(struct file *file, char __user *ubuf, size_t cnt, loff_t *ppos) { struct stats_debug_info *debug = file->private_data; struct fnic *fnic = (struct fnic *)debug->i_private; char buf[64]; int len; len = sprintf(buf, "%u\n", fnic->reset_stats); return simple_read_from_buffer(ubuf, cnt, ppos, buf, len); } /* * fnic_reset_stats_write - Write to reset_stats debugfs file * @filp: The file pointer to write from. * @ubuf: The buffer to copy the data from. * @cnt: The number of bytes to write. * @ppos: The position in the file to start writing to. * * Description: * This routine writes data from user buffer @ubuf to buffer @buf and * resets cumulative stats of fnic. * * Returns: * This function returns the amount of data that was written. */ static ssize_t fnic_reset_stats_write(struct file *file, const char __user *ubuf, size_t cnt, loff_t *ppos) { struct stats_debug_info *debug = file->private_data; struct fnic *fnic = (struct fnic *)debug->i_private; struct fnic_stats *stats = &fnic->fnic_stats; u64 *io_stats_p = (u64 *)&stats->io_stats; u64 *fw_stats_p = (u64 *)&stats->fw_stats; char buf[64]; unsigned long val; int ret; if (cnt >= sizeof(buf)) return -EINVAL; if (copy_from_user(&buf, ubuf, cnt)) return -EFAULT; buf[cnt] = 0; ret = kstrtoul(buf, 10, &val); if (ret < 0) return ret; fnic->reset_stats = val; if (fnic->reset_stats) { /* Skip variable is used to avoid descrepancies to Num IOs * and IO Completions stats. Skip incrementing No IO Compls * for pending active IOs after reset stats */ atomic64_set(&fnic->io_cmpl_skip, atomic64_read(&stats->io_stats.active_ios)); memset(&stats->abts_stats, 0, sizeof(struct abort_stats)); memset(&stats->term_stats, 0, sizeof(struct terminate_stats)); memset(&stats->reset_stats, 0, sizeof(struct reset_stats)); memset(&stats->misc_stats, 0, sizeof(struct misc_stats)); memset(&stats->vlan_stats, 0, sizeof(struct vlan_stats)); memset(io_stats_p+1, 0, sizeof(struct io_path_stats) - sizeof(u64)); memset(fw_stats_p+1, 0, sizeof(struct fw_stats) - sizeof(u64)); } (*ppos)++; return cnt; } /* * fnic_reset_stats_release - Release the buffer used to store * debugfs file data * @inode: The inode pointer * @file: The file pointer that contains the buffer to release * * Description: * This routine frees the buffer that was allocated when the debugfs * file was opened. * * Returns: * This function returns zero. */ static int fnic_reset_stats_release(struct inode *inode, struct file *file) { struct stats_debug_info *debug = file->private_data; kfree(debug); return 0; } /* * fnic_stats_debugfs_open - Open the stats file for specific host * and get fnic stats. * @inode: The inode pointer. * @file: The file pointer to attach the specific host statistics. * * Description: * This routine opens a debugsfs file stats of specific host and print * fnic stats. * * Returns: * This function returns zero if successful. */ static int fnic_stats_debugfs_open(struct inode *inode, struct file *file) { struct fnic *fnic = inode->i_private; struct fnic_stats *fnic_stats = &fnic->fnic_stats; struct stats_debug_info *debug; int buf_size = 2 * PAGE_SIZE; debug = kzalloc(sizeof(struct stats_debug_info), GFP_KERNEL); if (!debug) return -ENOMEM; debug->debug_buffer = vmalloc(buf_size); if (!debug->debug_buffer) { kfree(debug); return -ENOMEM; } debug->buf_size = buf_size; memset((void *)debug->debug_buffer, 0, buf_size); debug->buffer_len = fnic_get_stats_data(debug, fnic_stats); file->private_data = debug; return 0; } /* * fnic_stats_debugfs_read - Read a debugfs file * @file: The file pointer to read from. * @ubuf: The buffer to copy the data to. * @nbytes: The number of bytes to read. * @pos: The position in the file to start reading from. * * Description: * This routine reads data from the buffer indicated in the private_data * field of @file. It will start reading at @pos and copy up to @nbytes of * data to @ubuf. * * Returns: * This function returns the amount of data that was read (this could be * less than @nbytes if the end of the file was reached). */ static ssize_t fnic_stats_debugfs_read(struct file *file, char __user *ubuf, size_t nbytes, loff_t *pos) { struct stats_debug_info *debug = file->private_data; int rc = 0; rc = simple_read_from_buffer(ubuf, nbytes, pos, debug->debug_buffer, debug->buffer_len); return rc; } /* * fnic_stats_stats_release - Release the buffer used to store * debugfs file data * @inode: The inode pointer * @file: The file pointer that contains the buffer to release * * Description: * This routine frees the buffer that was allocated when the debugfs * file was opened. * * Returns: * This function returns zero. */ static int fnic_stats_debugfs_release(struct inode *inode, struct file *file) { struct stats_debug_info *debug = file->private_data; vfree(debug->debug_buffer); kfree(debug); return 0; } static const struct file_operations fnic_stats_debugfs_fops = { .owner = THIS_MODULE, .open = fnic_stats_debugfs_open, .read = fnic_stats_debugfs_read, .release = fnic_stats_debugfs_release, }; static const struct file_operations fnic_reset_debugfs_fops = { .owner = THIS_MODULE, .open = fnic_reset_stats_open, .read = fnic_reset_stats_read, .write = fnic_reset_stats_write, .release = fnic_reset_stats_release, }; /* * fnic_stats_init - Initialize stats struct and create stats file per fnic * * Description: * When Debugfs is configured this routine sets up the stats file per fnic * It will create file stats and reset_stats under statistics/host# directory * to log per fnic stats. */ int fnic_stats_debugfs_init(struct fnic *fnic) { int rc = -1; char name[16]; snprintf(name, sizeof(name), "host%d", fnic->lport->host->host_no); if (!fnic_stats_debugfs_root) { printk(KERN_DEBUG "fnic_stats root doesn't exist\n"); return rc; } fnic->fnic_stats_debugfs_host = debugfs_create_dir(name, fnic_stats_debugfs_root); if (!fnic->fnic_stats_debugfs_host) { printk(KERN_DEBUG "Cannot create host directory\n"); return rc; } fnic->fnic_stats_debugfs_file = debugfs_create_file("stats", S_IFREG|S_IRUGO|S_IWUSR, fnic->fnic_stats_debugfs_host, fnic, &fnic_stats_debugfs_fops); if (!fnic->fnic_stats_debugfs_file) { printk(KERN_DEBUG "Cannot create host stats file\n"); return rc; } fnic->fnic_reset_debugfs_file = debugfs_create_file("reset_stats", S_IFREG|S_IRUGO|S_IWUSR, fnic->fnic_stats_debugfs_host, fnic, &fnic_reset_debugfs_fops); if (!fnic->fnic_reset_debugfs_file) { printk(KERN_DEBUG "Cannot create host stats file\n"); return rc; } rc = 0; return rc; } /* * fnic_stats_debugfs_remove - Tear down debugfs infrastructure of stats * * Description: * When Debugfs is configured this routine removes debugfs file system * elements that are specific to fnic stats. */ void fnic_stats_debugfs_remove(struct fnic *fnic) { if (!fnic) return; debugfs_remove(fnic->fnic_stats_debugfs_file); fnic->fnic_stats_debugfs_file = NULL; debugfs_remove(fnic->fnic_reset_debugfs_file); fnic->fnic_reset_debugfs_file = NULL; debugfs_remove(fnic->fnic_stats_debugfs_host); fnic->fnic_stats_debugfs_host = NULL; }
450634.c
// SPDX-License-Identifier: GPL-2.0-or-later /* mpihelp-add_2.c - MPI helper functions * Copyright (C) 1994, 1996, 1997, 1998, 2001 Free Software Foundation, Inc. * * This file is part of GnuPG. * * Note: This code is heavily based on the GNU MP Library. * Actually it's the same code with only minor changes in the * way the data is stored; this is to support the abstraction * of an optional secure memory allocation which may be used * to avoid revealing of sensitive data due to paging etc. * The GNU MP Library itself is published under the LGPL; * however I decided to publish this code under the plain GPL. */ #include "mpi-internal.h" #include "longlong.h" mpi_limb_t mpihelp_sub_n(mpi_ptr_t res_ptr, mpi_ptr_t s1_ptr, mpi_ptr_t s2_ptr, mpi_size_t size) { mpi_limb_t x, y, cy; mpi_size_t j; /* The loop counter and index J goes from -SIZE to -1. This way the loop becomes faster. */ j = -size; /* Offset the base pointers to compensate for the negative indices. */ s1_ptr -= j; s2_ptr -= j; res_ptr -= j; cy = 0; do { y = s2_ptr[j]; x = s1_ptr[j]; y += cy; /* add previous carry to subtrahend */ cy = y < cy; /* get out carry from that addition */ y = x - y; /* main subtract */ cy += y > x; /* get out carry from the subtract, combine */ res_ptr[j] = y; } while (++j); return cy; }
559641.c
/* * QEMU NE2000 emulation -- isa bus windup * * Copyright (c) 2003-2004 Fabrice Bellard * * 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 "hw.h" #include "pc.h" #include "isa.h" #include "qdev.h" #include "net.h" #include "ne2000.h" #include "exec-memory.h" typedef struct ISANE2000State { ISADevice dev; uint32_t iobase; uint32_t isairq; NE2000State ne2000; } ISANE2000State; static void isa_ne2000_cleanup(VLANClientState *nc) { NE2000State *s = DO_UPCAST(NICState, nc, nc)->opaque; s->nic = NULL; } static NetClientInfo net_ne2000_isa_info = { .type = NET_CLIENT_TYPE_NIC, .size = sizeof(NICState), .can_receive = ne2000_can_receive, .receive = ne2000_receive, .cleanup = isa_ne2000_cleanup, }; static const VMStateDescription vmstate_isa_ne2000 = { .name = "ne2000", .version_id = 2, .minimum_version_id = 0, .minimum_version_id_old = 0, .fields = (VMStateField []) { VMSTATE_STRUCT(ne2000, ISANE2000State, 0, vmstate_ne2000, NE2000State), VMSTATE_END_OF_LIST() } }; static int isa_ne2000_initfn(ISADevice *dev) { ISANE2000State *isa = DO_UPCAST(ISANE2000State, dev, dev); NE2000State *s = &isa->ne2000; ne2000_setup_io(s, 0x20); isa_register_ioport(dev, &s->io, isa->iobase); isa_init_irq(dev, &s->irq, isa->isairq); qemu_macaddr_default_if_unset(&s->c.macaddr); ne2000_reset(s); s->nic = qemu_new_nic(&net_ne2000_isa_info, &s->c, dev->qdev.info->name, dev->qdev.id, s); qemu_format_nic_info_str(&s->nic->nc, s->c.macaddr.a); return 0; } static ISADeviceInfo ne2000_isa_info = { .qdev.name = "ne2k_isa", .qdev.size = sizeof(ISANE2000State), .init = isa_ne2000_initfn, .qdev.props = (Property[]) { DEFINE_PROP_HEX32("iobase", ISANE2000State, iobase, 0x300), DEFINE_PROP_UINT32("irq", ISANE2000State, isairq, 9), DEFINE_NIC_PROPERTIES(ISANE2000State, ne2000.c), DEFINE_PROP_END_OF_LIST(), }, }; static void ne2000_isa_register_devices(void) { isa_qdev_register(&ne2000_isa_info); } device_init(ne2000_isa_register_devices)
719413.c
#include "Segment.h" #include "LKH.h" #include "Sequence.h" /* * The BestKOptMove function makes edge exchanges. If possible, it makes a * r-opt move (r >= 2) that improves the tour. Otherwise, it makes the most * promising sequential K-opt move that fulfils the positive gain criterion. * To prevent an infinity chain of moves the last edge in a K-opt move must * not previously have been included in the chain. * * The edge (t[1],t[2]) is the first edge to be exchanged. G0 is a pointer to * the accumulated gain. * * In case a K-opt move is found that improves the tour, the improvement of * the cost is made available to the caller through the parameter Gain. * If *Gain > 0, an improvement of the current tour has been found. In this * case the function returns 0. * * Otherwise, the best K-opt move is made, and a pointer to the node that was * connected to t[1] (in order to close the tour) is returned. The new * accumulated gain is made available to the caller through the parameter G0. * * The function is called from the LinKernighan function. */ static GainType BestG2; static GainType BestKOptMoveRec(int k, GainType G0); Node *BestKOptMove(Node * t1, Node * t2, GainType * G0, GainType * Gain) { K = Swaps == 0 ? MoveType : SubsequentMoveType; *Gain = 0; t[1] = t1; t[2] = t2; T[2 * K] = 0; BestG2 = MINUS_INFINITY; /* * Determine (T[3],T[4], ..., T[2K]) = (t[3],t[4], ..., t[2K]) * such that * * G[2 * K] = *G0 - C(t[2],T[3]) + C(T[3],T[4]) * - C(T[4],T[5]) + C(T[5],T[6]) * ... * - C(T[2K-3],T[2K-2]) + C(T[2K-1],T[2K]) * * is maximum, and (T[2K-1],T[2K]) has not previously been included. * If during this process a legal move with *Gain > 0 is found, then * make the move and exit BestKOptMove immediately. */ MarkDeleted(t1, t2); *Gain = BestKOptMoveRec(2, *G0); UnmarkDeleted(t1, t2); if (*Gain <= 0 && T[2 * K]) { int i; memcpy(t + 1, T + 1, 2 * K * sizeof(Node *)); for (i = 2; i < 2 * K; i += 2) incl[incl[i] = i + 1] = i; incl[incl[1] = 2 * K] = 1; MakeKOptMove(K); for (i = 1; i < 2 * K; i += 2) Exclude(T[i], T[i + 1]); *G0 = BestG2; return T[2 * K]; } return 0; } static GainType BestKOptMoveRec(int k, GainType G0) { Candidate *Nt2; Node *t1, *t2, *t3, *t4; GainType G1, G2, G3, Gain; int X4, i; int Breadth2 = 0; t1 = t[1]; t2 = t[i = 2 * k - 2]; incl[incl[i] = i + 1] = i; incl[incl[1] = i + 2] = 1; /* Choose (t2,t3) as a candidate edge emanating from t2 */ for (Nt2 = t2->CandidateSet; (t3 = Nt2->To); Nt2++) { if (t3 == t2->Pred || t3 == t2->Suc || ((G1 = G0 - Nt2->Cost) <= 0 && GainCriterionUsed && ProblemType != HCP && ProblemType != HPP) || Added(t2, t3)) continue; if (++Breadth2 > MaxBreadth) break; MarkAdded(t2, t3); t[2 * k - 1] = t3; G[2 * k - 2] = G1 + t3->Pi; /* Choose t4 as one of t3's two neighbors on the tour */ for (X4 = 1; X4 <= 2; X4++) { t4 = X4 == 1 ? PRED(t3) : SUC(t3); if (FixedOrCommon(t3, t4) || Deleted(t3, t4)) continue; t[2 * k] = t4; G2 = G1 + C(t3, t4); G3 = MINUS_INFINITY; if (t4 != t1 && !Forbidden(t4, t1) && !Added(t4, t1) && (!c || G2 - c(t4, t1) > 0) && (G3 = G2 - C(t4, t1)) > 0 && FeasibleKOptMove(k)) { UnmarkAdded(t2, t3); MakeKOptMove(k); return G3; } if (Backtracking && !Excludable(t3, t4)) continue; MarkDeleted(t3, t4); G[2 * k - 1] = G2 - t4->Pi; if (k < K) { if ((Gain = BestKOptMoveRec(k + 1, G2)) > 0) { UnmarkAdded(t2, t3); UnmarkDeleted(t3, t4); return Gain; } incl[incl[1] = 2 * k] = 1; } if (t4 != t1 && !Forbidden(t4, t1) && k + 1 < NonsequentialMoveType && PatchingC >= 2 && PatchingA >= 1 && (Swaps == 0 || SubsequentPatching)) { if (G3 == MINUS_INFINITY) G3 = G2 - C(t4, t1); if ((PatchingCRestricted ? G3 > 0 && IsCandidate(t4, t1) : PatchingCExtended ? G3 > 0 || IsCandidate(t4, t1) : G3 > 0) && (Gain = PatchCycles(k, G3)) > 0) { UnmarkAdded(t2, t3); UnmarkDeleted(t3, t4); return Gain; } } UnmarkDeleted(t3, t4); if (k == K && t4 != t1 && t3 != t1 && G3 <= 0 && !Added(t4, t1) && (!GainCriterionUsed || G2 - Precision >= t4->Cost)) { if (!Backtracking || Swaps > 0) { if ((G2 > BestG2 || (G2 == BestG2 && !Near(t3, t4) && Near(T[2 * K - 1], T[2 * K]))) && Swaps < MaxSwaps && Excludable(t3, t4) && !InInputTour(t3, t4)) { if (RestrictedSearch && K > 2 && ProblemType != HCP && ProblemType != HPP) { /* Ignore the move if the gain does not vary */ G[0] = G[2 * K - 2]; G[1] = G[2 * K - 1]; for (i = 2 * K - 3; i >= 2; i--) if (G[i] != G[i % 2]) break; if (i < 2) continue; } if (FeasibleKOptMove(K)) { BestG2 = G2; memcpy(T + 1, t + 1, 2 * K * sizeof(Node *)); } } } else if (MaxSwaps > 0 && FeasibleKOptMove(K)) { Node *SUCt1 = SUC(t1); MakeKOptMove(K); for (i = 1; i < 2 * k; i += 2) { Exclude(t[i], t[i + 1]); UnmarkDeleted(t[i], t[i + 1]); } for (i = 2; i < 2 * k; i += 2) UnmarkAdded(t[i], t[i + 1]); memcpy(tSaved + 1, t + 1, 2 * k * sizeof(Node *)); while ((t4 = BestSubsequentMove(t1, t4, &G2, &Gain))); if (Gain > 0) { UnmarkAdded(t2, t3); return Gain; } RestoreTour(); K = k; memcpy(t + 1, tSaved + 1, 2 * K * sizeof(Node *)); for (i = 1; i < 2 * K - 2; i += 2) MarkDeleted(t[i], t[i + 1]); for (i = 2; i < 2 * K; i += 2) MarkAdded(t[i], t[i + 1]); for (i = 2; i < 2 * K; i += 2) incl[incl[i] = i + 1] = i; incl[incl[1] = 2 * K] = 1; if (SUCt1 != SUC(t1)) Reversed ^= 1; T[2 * K] = 0; } } } UnmarkAdded(t2, t3); if (t3 == t1) continue; /* Try to delete an added edge, (_,t3) or (t3,_) */ for (i = 2 * k - 4; i >= 2; i--) { if (t3 == t[i]) { t4 = t[i ^ 1]; if (t4 == t1 || Forbidden(t4, t1) || FixedOrCommon(t3, t4) || Added(t4, t1)) continue; G2 = G1 + C(t3, t4); if ((!c || G2 - c(t4, t1) > 0) && (Gain = G2 - C(t4, t1)) > 0) { incl[incl[i ^ 1] = 1] = i ^ 1; incl[incl[i] = 2 * k - 2] = i; if (FeasibleKOptMove(k - 1)) { MakeKOptMove(k - 1); return Gain; } incl[incl[i ^ 1] = i] = i ^ 1; } } } incl[1] = 2 * k; incl[2 * k - 2] = 2 * k - 1; } return 0; }
497434.c
/****************************************************** Copyright (c) 2011-2013 Percona LLC and/or its affiliates. The xbstream utility: serialize/deserialize files in the XBSTREAM format. 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 Street, Fifth Floor, Boston, MA 02110-1301, USA *******************************************************/ #include <mysql_version.h> #include <my_base.h> #include <my_getopt.h> #include <hash.h> #include <my_pthread.h> #include "common.h" #include "xbstream.h" #include "datasink.h" #include "crc_glue.h" #define XBSTREAM_VERSION "1.0" #define XBSTREAM_BUFFER_SIZE (10 * 1024 * 1024UL) #define START_FILE_HASH_SIZE 16 typedef enum { RUN_MODE_NONE, RUN_MODE_CREATE, RUN_MODE_EXTRACT } run_mode_t; /* Need the following definitions to avoid linking with ds_*.o and their link dependencies */ datasink_t datasink_archive; datasink_t datasink_xbstream; datasink_t datasink_compress; datasink_t datasink_tmpfile; datasink_t datasink_buffer; static run_mode_t opt_mode; static char * opt_directory = NULL; static my_bool opt_verbose = 0; static int opt_parallel = 1; static struct my_option my_long_options[] = { {"help", '?', "Display this help and exit.", 0, 0, 0, GET_NO_ARG, NO_ARG, 0, 0, 0, 0, 0, 0}, {"create", 'c', "Stream the specified files to the standard output.", 0, 0, 0, GET_NO_ARG, NO_ARG, 0, 0, 0, 0, 0, 0}, {"extract", 'x', "Extract to disk files from the stream on the " "standard input.", 0, 0, 0, GET_NO_ARG, NO_ARG, 0, 0, 0, 0, 0, 0}, {"directory", 'C', "Change the current directory to the specified one " "before streaming or extracting.", &opt_directory, &opt_directory, 0, GET_STR_ALLOC, REQUIRED_ARG, 0, 0, 0, 0, 0, 0}, {"verbose", 'v', "Print verbose output.", &opt_verbose, &opt_verbose, 0, GET_BOOL, NO_ARG, 0, 0, 0, 0, 0, 0}, {"parallel", 'p', "Number of worker threads for reading / writing.", &opt_parallel, &opt_parallel, 0, GET_INT, REQUIRED_ARG, 1, 1, INT_MAX, 0, 0, 0}, {0, 0, 0, 0, 0, 0, GET_NO_ARG, NO_ARG, 0, 0, 0, 0, 0, 0} }; typedef struct { HASH *filehash; xb_rstream_t *stream; ds_ctxt_t *ds_ctxt; pthread_mutex_t *mutex; } extract_ctxt_t; typedef struct { char *path; uint pathlen; my_off_t offset; ds_file_t *file; pthread_mutex_t mutex; } file_entry_t; static int get_options(int *argc, char ***argv); static int mode_create(int argc, char **argv); static int mode_extract(int n_threads, int argc, char **argv); static my_bool get_one_option(int optid, const struct my_option *opt, char *argument); int main(int argc, char **argv) { MY_INIT(argv[0]); crc_init(); if (get_options(&argc, &argv)) { goto err; } if (opt_mode == RUN_MODE_NONE) { msg("%s: either -c or -x must be specified.\n", my_progname); goto err; } /* Change the current directory if -C is specified */ if (opt_directory && my_setwd(opt_directory, MYF(MY_WME))) { goto err; } if (opt_mode == RUN_MODE_CREATE && mode_create(argc, argv)) { goto err; } else if (opt_mode == RUN_MODE_EXTRACT && mode_extract(opt_parallel, argc, argv)) { goto err; } my_cleanup_options(my_long_options); my_end(0); return EXIT_SUCCESS; err: my_cleanup_options(my_long_options); my_end(0); exit(EXIT_FAILURE); } static int get_options(int *argc, char ***argv) { int ho_error; if ((ho_error= handle_options(argc, argv, my_long_options, get_one_option))) { exit(EXIT_FAILURE); } return 0; } static void print_version(void) { printf("%s Ver %s for %s (%s)\n", my_progname, XBSTREAM_VERSION, SYSTEM_TYPE, MACHINE_TYPE); } static void usage(void) { print_version(); puts("Copyright (C) 2011-2013 Percona LLC and/or its affiliates."); puts("This software comes with ABSOLUTELY NO WARRANTY. " "This is free software,\nand you are welcome to modify and " "redistribute it under the GPL license.\n"); puts("Serialize/deserialize files in the XBSTREAM format.\n"); puts("Usage: "); printf(" %s -c [OPTIONS...] FILES... # stream specified files to " "standard output.\n", my_progname); printf(" %s -x [OPTIONS...] # extract files from the stream" "on the standard input.\n", my_progname); puts("\nOptions:"); my_print_help(my_long_options); } static int set_run_mode(run_mode_t mode) { if (opt_mode != RUN_MODE_NONE) { msg("%s: can't set specify both -c and -x.\n", my_progname); return 1; } opt_mode = mode; return 0; } static my_bool get_one_option(int optid, const struct my_option *opt __attribute__((unused)), char *argument __attribute__((unused))) { switch (optid) { case 'c': if (set_run_mode(RUN_MODE_CREATE)) { return TRUE; } break; case 'x': if (set_run_mode(RUN_MODE_EXTRACT)) { return TRUE; } break; case '?': usage(); exit(0); } return FALSE; } static int stream_one_file(File file, xb_wstream_file_t *xbfile) { uchar *buf; ssize_t bytes; my_off_t offset; posix_fadvise(file, 0, 0, POSIX_FADV_SEQUENTIAL); offset = my_tell(file, MYF(MY_WME)); buf = (uchar*)(my_malloc(XBSTREAM_BUFFER_SIZE, MYF(MY_FAE))); while ((bytes = (ssize_t)my_read(file, buf, XBSTREAM_BUFFER_SIZE, MYF(MY_WME))) > 0) { if (xb_stream_write_data(xbfile, buf, bytes)) { msg("%s: xb_stream_write_data() failed.\n", my_progname); my_free(buf); return 1; } posix_fadvise(file, offset, XBSTREAM_BUFFER_SIZE, POSIX_FADV_DONTNEED); offset += XBSTREAM_BUFFER_SIZE; } my_free(buf); if (bytes < 0) { return 1; } return 0; } static int mode_create(int argc, char **argv) { int i; MY_STAT mystat; xb_wstream_t *stream; if (argc < 1) { msg("%s: no files are specified.\n", my_progname); return 1; } stream = xb_stream_write_new(); if (stream == NULL) { msg("%s: xb_stream_write_new() failed.\n", my_progname); return 1; } for (i = 0; i < argc; i++) { char *filepath = argv[i]; File src_file; xb_wstream_file_t *file; if (my_stat(filepath, &mystat, MYF(MY_WME)) == NULL) { goto err; } if (!MY_S_ISREG(mystat.st_mode)) { msg("%s: %s is not a regular file, exiting.\n", my_progname, filepath); goto err; } if ((src_file = my_open(filepath, O_RDONLY, MYF(MY_WME))) < 0) { msg("%s: failed to open %s.\n", my_progname, filepath); goto err; } file = xb_stream_write_open(stream, filepath, &mystat, NULL, NULL); if (file == NULL) { goto err; } if (opt_verbose) { msg("%s\n", filepath); } if (stream_one_file(src_file, file) || xb_stream_write_close(file) || my_close(src_file, MYF(MY_WME))) { goto err; } } xb_stream_write_done(stream); return 0; err: xb_stream_write_done(stream); return 1; } static file_entry_t * file_entry_new(extract_ctxt_t *ctxt, const char *path, uint pathlen) { file_entry_t *entry; ds_file_t *file; entry = (file_entry_t *) my_malloc(sizeof(file_entry_t), MYF(MY_WME | MY_ZEROFILL)); if (entry == NULL) { return NULL; } entry->path = my_strndup(path, pathlen, MYF(MY_WME)); if (entry->path == NULL) { goto err; } entry->pathlen = pathlen; file = ds_open(ctxt->ds_ctxt, path, NULL); if (file == NULL) { msg("%s: failed to create file.\n", my_progname); goto err; } if (opt_verbose) { msg("%s\n", entry->path); } entry->file = file; pthread_mutex_init(&entry->mutex, NULL); return entry; err: if (entry->path != NULL) { my_free(entry->path); } my_free(entry); return NULL; } static uchar * get_file_entry_key(file_entry_t *entry, size_t *length, my_bool not_used __attribute__((unused))) { *length = entry->pathlen; return (uchar *) entry->path; } static void file_entry_free(file_entry_t *entry) { pthread_mutex_destroy(&entry->mutex); ds_close(entry->file); my_free(entry->path); my_free(entry); } static void * extract_worker_thread_func(void *arg) { xb_rstream_chunk_t chunk; file_entry_t *entry; xb_rstream_result_t res; extract_ctxt_t *ctxt = (extract_ctxt_t *) arg; my_thread_init(); memset(&chunk, 0, sizeof(chunk)); while (1) { pthread_mutex_lock(ctxt->mutex); res = xb_stream_read_chunk(ctxt->stream, &chunk); if (res != XB_STREAM_READ_CHUNK) { pthread_mutex_unlock(ctxt->mutex); break; } /* If unknown type and ignorable flag is set, skip this chunk */ if (chunk.type == XB_CHUNK_TYPE_UNKNOWN && \ !(chunk.flags & XB_STREAM_FLAG_IGNORABLE)) { pthread_mutex_unlock(ctxt->mutex); continue; } /* See if we already have this file open */ entry = (file_entry_t *) my_hash_search(ctxt->filehash, (uchar *) chunk.path, chunk.pathlen); if (entry == NULL) { entry = file_entry_new(ctxt, chunk.path, chunk.pathlen); if (entry == NULL) { pthread_mutex_unlock(ctxt->mutex); break; } if (my_hash_insert(ctxt->filehash, (uchar *) entry)) { msg("%s: my_hash_insert() failed.\n", my_progname); pthread_mutex_unlock(ctxt->mutex); break; } } pthread_mutex_lock(&entry->mutex); pthread_mutex_unlock(ctxt->mutex); res = xb_stream_validate_checksum(&chunk); if (res != XB_STREAM_READ_CHUNK) { pthread_mutex_unlock(&entry->mutex); break; } if (chunk.type == XB_CHUNK_TYPE_EOF) { pthread_mutex_lock(ctxt->mutex); pthread_mutex_unlock(&entry->mutex); my_hash_delete(ctxt->filehash, (uchar *) entry); pthread_mutex_unlock(ctxt->mutex); continue; } if (entry->offset != chunk.offset) { msg("%s: out-of-order chunk: real offset = 0x%llx, " "expected offset = 0x%llx\n", my_progname, chunk.offset, entry->offset); pthread_mutex_unlock(&entry->mutex); res = XB_STREAM_READ_ERROR; break; } if (ds_write(entry->file, chunk.data, chunk.length)) { msg("%s: my_write() failed.\n", my_progname); pthread_mutex_unlock(&entry->mutex); res = XB_STREAM_READ_ERROR; break; } entry->offset += chunk.length; pthread_mutex_unlock(&entry->mutex); } if (chunk.data) my_free(chunk.data); my_thread_end(); return (void *)(res); } static int mode_extract(int n_threads, int argc __attribute__((unused)), char **argv __attribute__((unused))) { xb_rstream_t *stream = NULL; HASH filehash; ds_ctxt_t *ds_ctxt = NULL; extract_ctxt_t ctxt; int i; pthread_t *tids = NULL; void **retvals = NULL; pthread_mutex_t mutex; int ret = 0; if (my_hash_init(&filehash, &my_charset_bin, START_FILE_HASH_SIZE, 0, 0, (my_hash_get_key) get_file_entry_key, (my_hash_free_key) file_entry_free, MYF(0))) { msg("%s: failed to initialize file hash.\n", my_progname); return 1; } if (pthread_mutex_init(&mutex, NULL)) { msg("%s: failed to initialize mutex.\n", my_progname); my_hash_free(&filehash); return 1; } /* If --directory is specified, it is already set as CWD by now. */ ds_ctxt = ds_create(".", DS_TYPE_LOCAL); if (ds_ctxt == NULL) { ret = 1; goto exit; } stream = xb_stream_read_new(); if (stream == NULL) { msg("%s: xb_stream_read_new() failed.\n", my_progname); pthread_mutex_destroy(&mutex); ret = 1; goto exit; } ctxt.stream = stream; ctxt.filehash = &filehash; ctxt.ds_ctxt = ds_ctxt; ctxt.mutex = &mutex; tids = calloc(n_threads, sizeof(pthread_t)); retvals = calloc(n_threads, sizeof(void*)); for (i = 0; i < n_threads; i++) pthread_create(tids + i, NULL, extract_worker_thread_func, &ctxt); for (i = 0; i < n_threads; i++) pthread_join(tids[i], retvals + i); for (i = 0; i < n_threads; i++) { if ((size_t)retvals[i] == XB_STREAM_READ_ERROR) { ret = 1; goto exit; } } exit: pthread_mutex_destroy(&mutex); free(tids); free(retvals); my_hash_free(&filehash); if (ds_ctxt != NULL) { ds_destroy(ds_ctxt); } xb_stream_read_done(stream); return ret; }
756917.c
/* * Copyright (c) 2011-2020 Seagate Technology LLC and/or its Affiliates * * 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. * * For any questions about this software or licensing, * please email [email protected] or [email protected]. * */ #include <stdlib.h> /* system */ #include <stdio.h> /* fopen, fgetc, ... */ #include <unistd.h> /* unlink */ #include <sys/stat.h> /* mkdir */ #include <sys/types.h> /* mkdir */ #include "lib/misc.h" /* M0_SET0 */ #include "lib/memory.h" /* m0_alloc_align */ #include "lib/errno.h" #include "lib/finject.h" /* M0_FI_ENABLED */ #include "lib/ub.h" #include "ut/stob.h" #include "ut/ut.h" #include "lib/assert.h" #include "lib/arith.h" #include "stob/domain.h" #include "stob/io.h" #include "stob/stob.h" #include "fol/fol.h" #include "balloc/balloc.h" /* M0_BALLOC_NON_SPARE_ZONE */ /** @addtogroup stob @{ */ enum { NR = 3, NR_SORT = 256, MIN_BUF_SIZE = 4096, MIN_BUF_SIZE_IN_BLOCKS = 4, }; enum { M0_STOB_UT_DOMAIN_KEY = 0x01, M0_STOB_UT_STOB_KEY = 0x02, }; /** @todo move vars to a context */ static const char linux_location[] = "linuxstob:./__s"; static const char perf_location[] = "perfstob:./__s"; static struct m0_stob_domain *dom; static struct m0_stob *obj; static const char linux_path[] = "./__s/o/100000000000000:2"; static const char perf_path[] = "./__s/backstore/o/100000000000000:2"; static struct m0_stob_io io; static m0_bcount_t user_vec[NR]; static char *user_buf[NR]; static char *read_buf[NR]; static char *user_bufs[NR]; static char *read_bufs[NR]; static m0_bindex_t stob_vec[NR]; static struct m0_clink clink; static FILE *f; static uint32_t block_shift; static uint32_t buf_size; static int test_adieu_init(const char *location, const char *dom_cfg, const char *stob_cfg) { int i; int rc; struct m0_stob_id stob_id; rc = m0_stob_domain_create(location, NULL, M0_STOB_UT_DOMAIN_KEY, dom_cfg, &dom); M0_ASSERT(rc == 0); M0_ASSERT(dom != NULL); m0_stob_id_make(0, M0_STOB_UT_STOB_KEY, &dom->sd_id, &stob_id); rc = m0_stob_find(&stob_id, &obj); M0_ASSERT(rc == 0); rc = m0_stob_locate(obj); M0_ASSERT(rc == 0); rc = m0_ut_stob_create(obj, stob_cfg, NULL); M0_ASSERT(rc == 0); block_shift = m0_stob_block_shift(obj); /* buf_size is chosen so it would be at least MIN_BUF_SIZE in bytes * or it would consist of at least MIN_BUF_SIZE_IN_BLOCKS blocks */ buf_size = max_check(MIN_BUF_SIZE, (1 << block_shift) * MIN_BUF_SIZE_IN_BLOCKS); for (i = 0; i < ARRAY_SIZE(user_buf); ++i) { user_buf[i] = m0_alloc_aligned(buf_size, block_shift); M0_ASSERT(user_buf[i] != NULL); } for (i = 0; i < ARRAY_SIZE(read_buf); ++i) { read_buf[i] = m0_alloc_aligned(buf_size, block_shift); M0_ASSERT(read_buf[i] != NULL); } for (i = 0; i < NR; ++i) { user_bufs[i] = m0_stob_addr_pack(user_buf[i], block_shift); read_bufs[i] = m0_stob_addr_pack(read_buf[i], block_shift); user_vec[i] = buf_size >> block_shift; stob_vec[i] = (buf_size * (2 * i + 1)) >> block_shift; memset(user_buf[i], ('a' + i)|1, buf_size); } return rc; } static void test_adieu_fini(void) { int i; int rc; rc = m0_stob_destroy(obj, NULL); M0_ASSERT(rc == 0); rc = m0_stob_domain_destroy(dom); M0_ASSERT(rc == 0); for (i = 0; i < ARRAY_SIZE(user_buf); ++i) m0_free(user_buf[i]); for (i = 0; i < ARRAY_SIZE(read_buf); ++i) m0_free(read_buf[i]); } static void test_write(int i) { int rc; struct m0_fol_frag *fol_frag; M0_ALLOC_PTR(fol_frag); M0_UB_ASSERT(fol_frag != NULL); m0_stob_io_init(&io); io.si_opcode = SIO_WRITE; io.si_flags = 0; io.si_fol_frag = fol_frag; io.si_user.ov_vec.v_nr = i; io.si_user.ov_vec.v_count = user_vec; io.si_user.ov_buf = (void **)user_bufs; io.si_stob.iv_vec.v_nr = i; io.si_stob.iv_vec.v_count = user_vec; io.si_stob.iv_index = stob_vec; m0_clink_init(&clink, NULL); m0_clink_add_lock(&io.si_wait, &clink); rc = m0_stob_io_prepare_and_launch(&io, obj, NULL, NULL); M0_ASSERT(rc == 0); m0_chan_wait(&clink); M0_ASSERT(io.si_rc == 0); M0_ASSERT(io.si_count == (buf_size * i) >> block_shift); m0_clink_del_lock(&clink); m0_clink_fini(&clink); m0_stob_io_fini(&io); } static void test_read(int i) { int rc; m0_stob_io_init(&io); io.si_opcode = SIO_READ; io.si_flags = 0; io.si_user.ov_vec.v_nr = i; io.si_user.ov_vec.v_count = user_vec; io.si_user.ov_buf = (void **)read_bufs; io.si_stob.iv_vec.v_nr = i; io.si_stob.iv_vec.v_count = user_vec; io.si_stob.iv_index = stob_vec; m0_clink_init(&clink, NULL); m0_clink_add_lock(&io.si_wait, &clink); rc = m0_stob_io_prepare_and_launch(&io, obj, NULL, NULL); M0_ASSERT(rc == 0); m0_chan_wait(&clink); M0_ASSERT(io.si_rc == 0); M0_ASSERT(io.si_count == (buf_size * i) >> block_shift); m0_clink_del_lock(&clink); m0_clink_fini(&clink); m0_stob_io_fini(&io); } /** Adieu unit-test. */ static void test_adieu(const char *path) { int ch; int i; int j; for (i = 1; i < NR; ++i) { test_write(i); /* this works only for linuxstob */ f = fopen(path, "r"); for (j = 0; j < i; ++j) { int k; for (k = 0; k < buf_size; ++k) { ch = fgetc(f); M0_ASSERT(ch == '\0'); M0_ASSERT(!feof(f)); } for (k = 0; k < buf_size; ++k) { ch = fgetc(f); M0_ASSERT(ch != '\0'); M0_ASSERT(!feof(f)); } } ch = fgetc(f); M0_ASSERT(ch == EOF); fclose(f); } for (i = 1; i < NR; ++i) { test_read(i); M0_ASSERT(memcmp(user_buf[i - 1], read_buf[i - 1], buf_size) == 0); } } void m0_stob_ut_adieu_linux(void) { int rc; rc = test_adieu_init(linux_location, NULL, NULL); M0_ASSERT(rc == 0); test_adieu(linux_path); test_adieu_fini(); } void m0_stob_ut_adieu_perf(void) { int rc; rc = test_adieu_init(perf_location, NULL, NULL); M0_ASSERT(rc == 0); test_adieu(perf_path); test_adieu_fini(); } /* Adieu unit-benchmark */ static void ub_write(int i) { test_write(NR - 1); } static void ub_read(int i) { test_read(NR - 1); } static m0_bcount_t user_vec1[NR_SORT]; static char *user_bufs1[NR_SORT]; static m0_bindex_t stob_vec1[NR_SORT]; static void ub_iovec_init() { int i; for (i = 0; i < NR_SORT ; i++) stob_vec1[i] = MIN_BUF_SIZE * i; m0_stob_io_init(&io); io.si_opcode = SIO_WRITE; io.si_flags = 0; io.si_user.ov_vec.v_nr = NR_SORT; io.si_user.ov_vec.v_count = user_vec1; io.si_user.ov_buf = (void **)user_bufs1; io.si_stob.iv_vec.v_nr = NR_SORT; io.si_stob.iv_vec.v_count = user_vec1; io.si_stob.iv_index = stob_vec1; } static void ub_iovec_invert() { int i; bool swapped; /* Reverse sort index vecs. */ do { swapped = false; for (i = 0; i < NR_SORT - 1; i++) { if (stob_vec1[i] < stob_vec1[i + 1]) { m0_bindex_t tmp = stob_vec1[i]; stob_vec1[i] = stob_vec1[i + 1]; stob_vec1[i + 1] = tmp; swapped = true; } } } while(swapped); } static void ub_iovec_sort() { m0_stob_iovec_sort(&io); } static void ub_iovec_sort_invert() { ub_iovec_invert(); m0_stob_iovec_sort(&io); } static int ub_init(const char *opts M0_UNUSED) { return test_adieu_init(linux_location, NULL, NULL); } static void ub_fini(void) { test_adieu_fini(); } enum { UB_ITER = 100, UB_ITER_SORT = 100000 }; struct m0_ub_set m0_adieu_ub = { .us_name = "adieu-ub", .us_init = ub_init, .us_fini = ub_fini, .us_run = { { .ub_name = "write-prime", .ub_iter = 1, .ub_round = ub_write, .ub_block_size = MIN_BUF_SIZE, .ub_blocks_per_op = MIN_BUF_SIZE_IN_BLOCKS }, { .ub_name = "write", .ub_iter = UB_ITER, .ub_block_size = MIN_BUF_SIZE, .ub_blocks_per_op = MIN_BUF_SIZE_IN_BLOCKS, .ub_round = ub_write }, { .ub_name = "read", .ub_iter = UB_ITER, .ub_block_size = MIN_BUF_SIZE, .ub_blocks_per_op = MIN_BUF_SIZE_IN_BLOCKS, .ub_round = ub_read }, { .ub_name = "iovec-sort", .ub_iter = UB_ITER_SORT, .ub_init = ub_iovec_init, .ub_block_size = MIN_BUF_SIZE, .ub_blocks_per_op = MIN_BUF_SIZE_IN_BLOCKS, .ub_round = ub_iovec_sort }, { .ub_name = "iovec-sort-invert", .ub_iter = UB_ITER_SORT, .ub_init = ub_iovec_init, .ub_block_size = MIN_BUF_SIZE, .ub_blocks_per_op = MIN_BUF_SIZE_IN_BLOCKS, .ub_round = ub_iovec_sort_invert }, { .ub_name = NULL } } }; /** @} end group stob */ /* * Local variables: * c-indentation-style: "K&R" * c-basic-offset: 8 * tab-width: 8 * fill-column: 80 * scroll-step: 1 * End: */
270584.c
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE244_Failure_to_Clear_Heap_Before_Release__w32_wchar_t_15.c Label Definition File: CWE244_Failure_to_Clear_Heap_Before_Release__w32.label.xml Template File: point-flaw-15.tmpl.c */ /* * @description * CWE: 244 Failure to Clear Heap Before Release * Sinks: * GoodSink: Clear the password buffer before releasing the memory from the heap * BadSink : Release password from the heap without first clearing the buffer * Flow Variant: 15 Control flow: switch(6) * * */ #include "std_testcase.h" #include <wchar.h> #ifdef _WIN32 # include <windows.h> #pragma comment(lib, "advapi32.lib") #endif #ifndef OMITBAD void CWE244_Failure_to_Clear_Heap_Before_Release__w32_wchar_t_15_bad() { switch(6) { case 6: { wchar_t * password = (wchar_t *)malloc(100*sizeof(wchar_t)); size_t password_len = 0; HANDLE pHandle; wchar_t * username = L"User"; wchar_t * domain = L"Domain"; /* Initialize password */ password[0] = L'\0'; fgetws(password, 100, stdin); /* Remove the carriage return from the string that is inserted by fgetws() */ password_len = wcslen(password); if (password_len > 0) { password[password_len-1] = L'\0'; } /* Use the password in LogonUser() to establish that it is "sensitive" */ if (LogonUserW( username, domain, password, LOGON32_LOGON_NETWORK, LOGON32_PROVIDER_DEFAULT, &pHandle) != 0) { printLine("User logged in successfully."); CloseHandle(pHandle); } else { printLine("Unable to login."); } /* FLAW: free() password without clearing the password buffer */ free(password); } break; default: /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ { wchar_t * password = (wchar_t *)malloc(100*sizeof(wchar_t)); size_t password_len = 0; HANDLE pHandle; wchar_t * username = L"User"; wchar_t * domain = L"Domain"; /* Initialize password */ password[0] = L'\0'; fgetws(password, 100, stdin); /* Remove the carriage return from the string that is inserted by fgetws() */ password_len = wcslen(password); if (password_len > 0) { password[password_len-1] = L'\0'; } /* Use the password in LogonUser() to establish that it is "sensitive" */ if (LogonUserW( username, domain, password, LOGON32_LOGON_NETWORK, LOGON32_PROVIDER_DEFAULT, &pHandle) != 0) { printLine("User logged in successfully."); CloseHandle(pHandle); } else { printLine("Unable to login."); } password_len = wcslen(password); /* FIX: Clear password prior to freeing */ SecureZeroMemory(password, password_len * sizeof(wchar_t)); } } } #endif /* OMITBAD */ #ifndef OMITGOOD /* good1() changes the switch to switch(5) */ static void good1() { switch(5) { case 6: /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ { wchar_t * password = (wchar_t *)malloc(100*sizeof(wchar_t)); size_t password_len = 0; HANDLE pHandle; wchar_t * username = L"User"; wchar_t * domain = L"Domain"; /* Initialize password */ password[0] = L'\0'; fgetws(password, 100, stdin); /* Remove the carriage return from the string that is inserted by fgetws() */ password_len = wcslen(password); if (password_len > 0) { password[password_len-1] = L'\0'; } /* Use the password in LogonUser() to establish that it is "sensitive" */ if (LogonUserW( username, domain, password, LOGON32_LOGON_NETWORK, LOGON32_PROVIDER_DEFAULT, &pHandle) != 0) { printLine("User logged in successfully."); CloseHandle(pHandle); } else { printLine("Unable to login."); } /* FLAW: free() password without clearing the password buffer */ free(password); } break; default: { wchar_t * password = (wchar_t *)malloc(100*sizeof(wchar_t)); size_t password_len = 0; HANDLE pHandle; wchar_t * username = L"User"; wchar_t * domain = L"Domain"; /* Initialize password */ password[0] = L'\0'; fgetws(password, 100, stdin); /* Remove the carriage return from the string that is inserted by fgetws() */ password_len = wcslen(password); if (password_len > 0) { password[password_len-1] = L'\0'; } /* Use the password in LogonUser() to establish that it is "sensitive" */ if (LogonUserW( username, domain, password, LOGON32_LOGON_NETWORK, LOGON32_PROVIDER_DEFAULT, &pHandle) != 0) { printLine("User logged in successfully."); CloseHandle(pHandle); } else { printLine("Unable to login."); } password_len = wcslen(password); /* FIX: Clear password prior to freeing */ SecureZeroMemory(password, password_len * sizeof(wchar_t)); } } } /* good2() reverses the blocks in the switch */ static void good2() { switch(6) { case 6: { wchar_t * password = (wchar_t *)malloc(100*sizeof(wchar_t)); size_t password_len = 0; HANDLE pHandle; wchar_t * username = L"User"; wchar_t * domain = L"Domain"; /* Initialize password */ password[0] = L'\0'; fgetws(password, 100, stdin); /* Remove the carriage return from the string that is inserted by fgetws() */ password_len = wcslen(password); if (password_len > 0) { password[password_len-1] = L'\0'; } /* Use the password in LogonUser() to establish that it is "sensitive" */ if (LogonUserW( username, domain, password, LOGON32_LOGON_NETWORK, LOGON32_PROVIDER_DEFAULT, &pHandle) != 0) { printLine("User logged in successfully."); CloseHandle(pHandle); } else { printLine("Unable to login."); } password_len = wcslen(password); /* FIX: Clear password prior to freeing */ SecureZeroMemory(password, password_len * sizeof(wchar_t)); } break; default: /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ { wchar_t * password = (wchar_t *)malloc(100*sizeof(wchar_t)); size_t password_len = 0; HANDLE pHandle; wchar_t * username = L"User"; wchar_t * domain = L"Domain"; /* Initialize password */ password[0] = L'\0'; fgetws(password, 100, stdin); /* Remove the carriage return from the string that is inserted by fgetws() */ password_len = wcslen(password); if (password_len > 0) { password[password_len-1] = L'\0'; } /* Use the password in LogonUser() to establish that it is "sensitive" */ if (LogonUserW( username, domain, password, LOGON32_LOGON_NETWORK, LOGON32_PROVIDER_DEFAULT, &pHandle) != 0) { printLine("User logged in successfully."); CloseHandle(pHandle); } else { printLine("Unable to login."); } /* FLAW: free() password without clearing the password buffer */ free(password); } } } void CWE244_Failure_to_Clear_Heap_Before_Release__w32_wchar_t_15_good() { good1(); good2(); } #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()..."); CWE244_Failure_to_Clear_Heap_Before_Release__w32_wchar_t_15_good(); printLine("Finished good()"); #endif /* OMITGOOD */ #ifndef OMITBAD printLine("Calling bad()..."); CWE244_Failure_to_Clear_Heap_Before_Release__w32_wchar_t_15_bad(); printLine("Finished bad()"); #endif /* OMITBAD */ return 0; } #endif
1005176.c
/**************************************************************************************** * The Sentential Decision Diagram Package * sdd version 1.1.1, January 31, 2014 * http://reasoning.cs.ucla.edu/sdd ****************************************************************************************/ #include "sddapi.h" #include "compiler.h" #include "parameters.h" /**************************************************************************************** * this file contains the fnf-to-sdd compiler, with AUTO gc and sdd-minimize * * NOTE: this file is currently set to use the vtree search algorithm distributed * with the SDD package. this is meant to allow users to modify this search algorithm, * with the hope that they will improve on it. * * by commenting in/out TWO lines of code below, this can be changed to use the vtree * search algorithm built into the SDD library (look for SWITCH-TO-LIBRARY-SEARCH). * * the two algorithms are identical though, so the results should match. ****************************************************************************************/ // local declarations static SddNode* apply_vtree_auto(Vtree* vtree, BoolOp op, SddManager* manager); SddNode* apply_litset_auto(LitSet* litset, SddManager* manager); /**************************************************************************************** * compiles a cnf or dnf into an sdd ****************************************************************************************/ //fnf is either a cnf or a dnf SddNode* fnf_to_sdd_auto(Fnf* fnf, SddManager* manager) { sdd_manager_auto_gc_and_minimize_on(manager); //to SWITCH-TO-LIBRARY-SEARCH, comment in the next line, comment out the one after sdd_manager_set_minimize_function(vtree_search,manager); //user-defined search algorithm // sdd_manager_set_minimize_function(sdd_vtree_minimize,manager); //library's search algorithm distribute_fnf_over_vtree(fnf,manager); SddNode* node = apply_vtree_auto(sdd_manager_vtree(manager),fnf->op,manager); free_vtree_data(sdd_manager_vtree(manager)); //root may have changed return node; } //each vtree node is associated with a set of litsets (clauses or terms) //the totality of these litsets represent an fnf (cnf or dnf) //returns an sdd which is equivalent to the cnf/dnf associated with vtree SddNode* apply_vtree_auto(Vtree* vtree, BoolOp op, SddManager* manager) { //get litsets associated with vtree node //do this first as vtree root may be changed by dynamic vtree search LitSet** litsets = DATA(vtree,litsets); SddSize litset_count = DATA(vtree,litset_count); sort_litsets_by_lca(litsets,litset_count,manager); SddNode* node; if(sdd_vtree_is_leaf(vtree)) node = ONE(manager,op); else { SddNode* l_node = apply_vtree_auto(sdd_vtree_left(vtree),op,manager); sdd_ref(l_node,manager); SddNode* r_node = apply_vtree_auto(sdd_vtree_right(vtree),op,manager); sdd_deref(l_node,manager); node = sdd_apply(l_node,r_node,op,manager); } while(litset_count--) { //compile and integrate litset sdd_ref(node,manager); SddNode* litset = apply_litset_auto(*litsets++,manager); //may gc node sdd_deref(node,manager); node = sdd_apply(litset,node,op,manager); //recompute lcas of remaining clauses and sort again sort_litsets_by_lca(litsets,litset_count,manager); } return node; } //converts a clause/term into an equivalent sdd SddNode* apply_litset_auto(LitSet* litset, SddManager* manager) { BoolOp op = litset->op; //conjoin (term) or disjoin (clause) SddLiteral* literals = litset->literals; SddNode* node = ONE(manager,op); //will not be gc'd for(SddLiteral i=0; i<litset->literal_count; i++) { SddNode* literal = sdd_manager_literal(literals[i],manager); node = sdd_apply(node,literal,op,manager); } return node; } /**************************************************************************************** * end ****************************************************************************************/
100221.c
/* Copyright 2019 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "ringbuf.h" #include <stdbool.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <assert.h> #define RB_TAG "RINGBUF" ringbuf_t* rb_init(const char* name, uint32_t size) { ringbuf_t* r; unsigned char* buf; if (size < 2 || !name) { return NULL; } r = malloc(sizeof(ringbuf_t)); assert(r); #if (CONFIG_SPIRAM_SUPPORT && \ (CONFIG_SPIRAM_USE_CAPS_ALLOC || CONFIG_SPIRAM_USE_MALLOC)) buf = heap_caps_calloc(1, size, MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT); #else buf = calloc(1, size); #endif assert(buf); r->name = (char*)name; r->base = r->readptr = r->writeptr = buf; r->fill_cnt = 0; r->size = size; //vSemaphoreCreateBinary(r->can_read); aos_sem_new(&r->can_read, 0); assert(r->can_read); // vSemaphoreCreateBinary(r->can_write); aos_sem_new(&r->can_write, 0); assert(r->can_write); // r->lock = xSemaphoreCreateMutex(); aos_mutex_new(&r->lock); assert(r->lock); r->abort_read = 0; r->abort_write = 0; r->writer_finished = 0; r->reader_unblock = 0; return r; } void rb_cleanup(ringbuf_t* rb) { free(rb->base); rb->base = NULL; // vSemaphoreDelete(rb->can_read); aos_sem_free(&rb->can_read); rb->can_read = NULL; // vSemaphoreDelete(rb->can_write); aos_sem_free(&rb->can_write); rb->can_write = NULL; // vSemaphoreDelete(rb->lock); aos_mutex_free(&rb->lock); rb->lock = NULL; free(rb); } /* * @brief: get the number of filled bytes in the buffer */ ssize_t rb_filled(ringbuf_t* rb) { return rb->fill_cnt; } /* * @brief: get the number of empty bytes available in the buffer */ ssize_t rb_available(ringbuf_t* rb) { LOGD(RB_TAG, "rb leftover %d bytes", rb->size - rb->fill_cnt); return (rb->size - rb->fill_cnt); } int rb_read(ringbuf_t* rb, uint8_t* buf, int buf_len, uint32_t ticks_to_wait) { int read_size; int total_read_size = 0; /** * In case where we are able to read buf_len in one go, * we are not able to check for abort and keep returning buf_len as bytes * read. Check for argument validity check and abort case before entering * memcpy loop. */ if (rb == NULL || rb->abort_read == 1) { return RB_FAIL; } //xSemaphoreTake(rb->lock, portMAX_DELAY); aos_mutex_lock(&rb->lock, AOS_WAIT_FOREVER); while (buf_len) { if (rb->fill_cnt < buf_len) { read_size = rb->fill_cnt; } else { read_size = buf_len; } if ((rb->readptr + read_size) > (rb->base + rb->size)) { int rlen1 = rb->base + rb->size - rb->readptr; int rlen2 = read_size - rlen1; if (buf) { memcpy(buf, rb->readptr, rlen1); memcpy(buf + rlen1, rb->base, rlen2); } rb->readptr = rb->base + rlen2; } else { if (buf) { memcpy(buf, rb->readptr, read_size); } rb->readptr = rb->readptr + read_size; } buf_len -= read_size; rb->fill_cnt -= read_size; total_read_size += read_size; if (buf) { buf += read_size; } // xSemaphoreGive(rb->can_write); aos_sem_signal(&rb->can_write); if (buf_len == 0) { break; } // xSemaphoreGive(rb->lock); aos_mutex_unlock(&rb->lock); if (!rb->writer_finished && !rb->abort_read && !rb->reader_unblock) { // if (xSemaphoreTake(rb->can_read, ticks_to_wait) != pdTRUE) { if (aos_sem_wait(&rb->can_read, ticks_to_wait) != pdTRUE) { goto out; } } if (rb->abort_read == 1) { total_read_size = RB_ABORT; goto out; } if (rb->writer_finished == 1) { goto out; } if (rb->reader_unblock == 1) { if (total_read_size == 0) { total_read_size = RB_READER_UNBLOCK; } goto out; } aos_mutex_lock(&rb->lock, AOS_WAIT_FOREVER); //xSemaphoreTake(rb->lock, portMAX_DELAY); } // xSemaphoreGive(rb->lock); aos_mutex_unlock(&rb->lock); out: if (rb->writer_finished == 1 && total_read_size == 0) { total_read_size = RB_WRITER_FINISHED; } rb->reader_unblock = 0; /* We are anyway unblocking reader */ return total_read_size; } int rb_write(ringbuf_t* rb, const uint8_t* buf, int buf_len, uint32_t ticks_to_wait) { int write_size; int total_write_size = 0; /** * In case where we are able to write buf_len in one go, * we are not able to check for abort and keep returning buf_len as bytes * written. Check for arguments' validity and abort case before entering * memcpy loop. */ if (rb == NULL || buf == NULL || rb->abort_write == 1) { return RB_FAIL; } //xSemaphoreTake(rb->lock, portMAX_DELAY); aos_mutex_lock(&rb->lock, AOS_WAIT_FOREVER); while (buf_len) { if ((rb->size - rb->fill_cnt) < buf_len) { write_size = rb->size - rb->fill_cnt; } else { write_size = buf_len; } if ((rb->writeptr + write_size) > (rb->base + rb->size)) { int wlen1 = rb->base + rb->size - rb->writeptr; int wlen2 = write_size - wlen1; memcpy(rb->writeptr, buf, wlen1); memcpy(rb->base, buf + wlen1, wlen2); rb->writeptr = rb->base + wlen2; } else { memcpy(rb->writeptr, buf, write_size); rb->writeptr = rb->writeptr + write_size; } buf_len -= write_size; rb->fill_cnt += write_size; total_write_size += write_size; buf += write_size; // xSemaphoreGive(rb->can_read); aos_sem_signal(&rb->can_read); if (buf_len == 0) { break; } // xSemaphoreGive(rb->lock); aos_mutex_unlock(&rb->lock); if (rb->writer_finished) { return write_size > 0 ? write_size : RB_WRITER_FINISHED; } // if (xSemaphoreTake(rb->can_write, ticks_to_wait) != pdTRUE) { if (aos_sem_wait(&rb->can_write, ticks_to_wait) != pdTRUE) { goto out; } if (rb->abort_write == 1) { goto out; } // xSemaphoreTake(rb->lock, portMAX_DELAY); aos_mutex_lock(&rb->lock, AOS_WAIT_FOREVER); } // xSemaphoreGive(rb->lock); aos_mutex_unlock(&rb->lock); out: return total_write_size; } /** * abort and set abort_read and abort_write to asked values. */ static void _rb_reset(ringbuf_t* rb, int abort_read, int abort_write) { if (rb == NULL) { return; } // xSemaphoreTake(rb->lock, portMAX_DELAY); aos_mutex_lock(&rb->lock, AOS_WAIT_FOREVER); rb->readptr = rb->writeptr = rb->base; rb->fill_cnt = 0; rb->writer_finished = 0; rb->reader_unblock = 0; rb->abort_read = abort_read; rb->abort_write = abort_write; // xSemaphoreGive(rb->lock); aos_mutex_unlock(&rb->lock); } void rb_reset(ringbuf_t* rb) { _rb_reset(rb, 0, 0); } void rb_abort_read(ringbuf_t* rb) { if (rb == NULL) { return; } rb->abort_read = 1; // xSemaphoreGive(rb->can_read); // xSemaphoreGive(rb->lock); aos_sem_signal(&rb->can_read); aos_mutex_unlock(&rb->lock); } void rb_abort_write(ringbuf_t* rb) { if (rb == NULL) { return; } rb->abort_write = 1; // xSemaphoreGive(rb->can_write); // xSemaphoreGive(rb->lock); aos_sem_signal(&rb->can_write); aos_mutex_unlock(&rb->lock); } void rb_abort(ringbuf_t* rb) { if (rb == NULL) { return; } rb->abort_read = 1; rb->abort_write = 1; // xSemaphoreGive(rb->can_read); // xSemaphoreGive(rb->can_write); // xSemaphoreGive(rb->lock); aos_sem_signal(&rb->can_read); aos_sem_signal(&rb->can_write); aos_mutex_unlock(&rb->lock); } /** * Reset the ringbuffer and keep rb_write aborted. * Note that we are taking lock before even toggling `abort_write` variable. * This serves a special purpose to not allow this abort to be mixed with * rb_write. */ void rb_reset_and_abort_write(ringbuf_t* rb) { _rb_reset(rb, 0, 1); // xSemaphoreGive(rb->can_write); aos_sem_signal(&rb->can_write); } void rb_signal_writer_finished(ringbuf_t* rb) { if (rb == NULL) { return; } rb->writer_finished = 1; // xSemaphoreGive(rb->can_read); aos_sem_signal(&rb->can_read); } int rb_is_writer_finished(ringbuf_t* rb) { if (rb == NULL) { return RB_FAIL; } return (rb->writer_finished); } void rb_wakeup_reader(ringbuf_t* rb) { if (rb == NULL) { return; } rb->reader_unblock = 1; // xSemaphoreGive(rb->can_read); aos_sem_signal(&rb->can_read); } void rb_stat(ringbuf_t* rb) { aos_mutex_lock(&rb->lock, AOS_WAIT_FOREVER); //xSemaphoreTake(rb->lock, portMAX_DELAY); LOGI(RB_TAG, "filled: %d, base: %p, read_ptr: %p, write_ptr: %p, size: %d\n", rb->fill_cnt, rb->base, rb->readptr, rb->writeptr, rb->size); // xSemaphoreGive(rb->lock); aos_mutex_unlock(&rb->lock); }
README.md exists but content is empty.
Downloads last month
43

Collection including ahmedheakl/the_stack_data_1M_2