filename
stringlengths 3
9
| code
stringlengths 4
1.05M
|
---|---|
1001037.c | /*
* BSD 3-Clause License
*
* Copyright (c) 2019, zhanglw ([email protected])
* 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. Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "qc_error.h"
int qc_seterr(QcErr *err, int errcode, const char *fmt, ...){
if(NULL == err)
return -1;
memset(err, 0, sizeof(QcErr));
err->code = errcode;
char vs[QC_MAXSIZE_ERRDESC];
va_list vl;
va_start(vl, fmt);
vsnprintf(vs, sizeof(vs), fmt, vl);
strncpy(err->desc, vs, sizeof(vs));
va_end(vl);
return 0;
}
|
493575.c | /*-------------------------------------------------------------------------
*
* nodeAppend.c
* routines to handle append nodes.
*
* Portions Copyright (c) 1996-2015, PostgreSQL Global Development Group
* Portions Copyright (c) 1994, Regents of the University of California
*
*
* IDENTIFICATION
* src/backend/executor/nodeAppend.c
*
*-------------------------------------------------------------------------
*/
/* INTERFACE ROUTINES
* ExecInitAppend - initialize the append node
* ExecAppend - retrieve the next tuple from the node
* ExecEndAppend - shut down the append node
* ExecReScanAppend - rescan the append node
*
* NOTES
* Each append node contains a list of one or more subplans which
* must be iteratively processed (forwards or backwards).
* Tuples are retrieved by executing the 'whichplan'th subplan
* until the subplan stops returning tuples, at which point that
* plan is shut down and the next started up.
*
* Append nodes don't make use of their left and right
* subtrees, rather they maintain a list of subplans so
* a typical append node looks like this in the plan tree:
*
* ...
* /
* Append -------+------+------+--- nil
* / \ | | |
* nil nil ... ... ...
* subplans
*
* Append nodes are currently used for unions, and to support
* inheritance queries, where several relations need to be scanned.
* For example, in our standard person/student/employee/student-emp
* example, where student and employee inherit from person
* and student-emp inherits from student and employee, the
* query:
*
* select name from person
*
* generates the plan:
*
* |
* Append -------+-------+--------+--------+
* / \ | | | |
* nil nil Scan Scan Scan Scan
* | | | |
* person employee student student-emp
*/
#include "postgres.h"
#include "executor/execdebug.h"
#include "executor/nodeAppend.h"
static bool exec_append_initialize_next(AppendState *appendstate);
/* ----------------------------------------------------------------
* exec_append_initialize_next
*
* Sets up the append state node for the "next" scan.
*
* Returns t iff there is a "next" scan to process.
* ----------------------------------------------------------------
*/
static bool
exec_append_initialize_next(AppendState *appendstate)
{
int whichplan;
/*
* get information from the append node
*/
whichplan = appendstate->as_whichplan;
if (whichplan < 0)
{
/*
* if scanning in reverse, we start at the last scan in the list and
* then proceed back to the first.. in any case we inform ExecAppend
* that we are at the end of the line by returning FALSE
*/
appendstate->as_whichplan = 0;
return FALSE;
}
else if (whichplan >= appendstate->as_nplans)
{
/*
* as above, end the scan if we go beyond the last scan in our list..
*/
appendstate->as_whichplan = appendstate->as_nplans - 1;
return FALSE;
}
else
{
return TRUE;
}
}
/* ----------------------------------------------------------------
* ExecInitAppend
*
* Begin all of the subscans of the append node.
*
* (This is potentially wasteful, since the entire result of the
* append node may not be scanned, but this way all of the
* structures get allocated in the executor's top level memory
* block instead of that of the call to ExecAppend.)
* ----------------------------------------------------------------
*/
AppendState *
ExecInitAppend(Append *node, EState *estate, int eflags)
{
AppendState *appendstate = makeNode(AppendState);
PlanState **appendplanstates;
int nplans;
int i;
ListCell *lc;
/* check for unsupported flags */
Assert(!(eflags & EXEC_FLAG_MARK));
/*
* Set up empty vector of subplan states
*/
nplans = list_length(node->appendplans);
appendplanstates = (PlanState **) palloc0(nplans * sizeof(PlanState *));
/*
* create new AppendState for our append node
*/
appendstate->ps.plan = (Plan *) node;
appendstate->ps.state = estate;
appendstate->appendplans = appendplanstates;
appendstate->as_nplans = nplans;
/*
* Miscellaneous initialization
*
* Append plans don't have expression contexts because they never call
* ExecQual or ExecProject.
*/
/*
* append nodes still have Result slots, which hold pointers to tuples, so
* we have to initialize them.
*/
ExecInitResultTupleSlot(estate, &appendstate->ps);
/*
* call ExecInitNode on each of the plans to be executed and save the
* results into the array "appendplans".
*/
i = 0;
foreach(lc, node->appendplans)
{
Plan *initNode = (Plan *) lfirst(lc);
appendplanstates[i] = ExecInitNode(initNode, estate, eflags);
i++;
}
/*
* initialize output tuple type
*/
ExecAssignResultTypeFromTL(&appendstate->ps);
appendstate->ps.ps_ProjInfo = NULL;
/*
* initialize to scan first subplan
*/
appendstate->as_whichplan = 0;
exec_append_initialize_next(appendstate);
return appendstate;
}
/* ----------------------------------------------------------------
* ExecAppend
*
* Handles iteration over multiple subplans.
* ----------------------------------------------------------------
*/
TupleTableSlot *
ExecAppend(AppendState *node)
{
for (;;)
{
PlanState *subnode;
TupleTableSlot *result;
/*
* figure out which subplan we are currently processing
*/
subnode = node->appendplans[node->as_whichplan];
/*
* get a tuple from the subplan
*/
result = ExecProcNode(subnode);
if (!TupIsNull(result))
{
/*
* If the subplan gave us something then return it as-is. We do
* NOT make use of the result slot that was set up in
* ExecInitAppend; there's no need for it.
*/
return result;
}
/*
* Go on to the "next" subplan in the appropriate direction. If no
* more subplans, return the empty slot set up for us by
* ExecInitAppend.
*/
if (ScanDirectionIsForward(node->ps.state->es_direction))
node->as_whichplan++;
else
node->as_whichplan--;
if (!exec_append_initialize_next(node))
return ExecClearTuple(node->ps.ps_ResultTupleSlot);
/* Else loop back and try to get a tuple from the new subplan */
}
}
/* ----------------------------------------------------------------
* ExecEndAppend
*
* Shuts down the subscans of the append node.
*
* Returns nothing of interest.
* ----------------------------------------------------------------
*/
void
ExecEndAppend(AppendState *node)
{
PlanState **appendplans;
int nplans;
int i;
/*
* get information from the node
*/
appendplans = node->appendplans;
nplans = node->as_nplans;
/*
* shut down each of the subscans
*/
for (i = 0; i < nplans; i++)
ExecEndNode(appendplans[i]);
}
void
ExecReScanAppend(AppendState *node)
{
int i;
for (i = 0; i < node->as_nplans; i++)
{
PlanState *subnode = node->appendplans[i];
/*
* ExecReScan doesn't know about my subplans, so I have to do
* changed-parameter signaling myself.
*/
if (node->ps.chgParam != NULL)
UpdateChangedParamSet(subnode, node->ps.chgParam);
/*
* If chgParam of subnode is not null then plan will be re-scanned by
* first ExecProcNode.
*/
if (subnode->chgParam == NULL)
ExecReScan(subnode);
}
node->as_whichplan = 0;
exec_append_initialize_next(node);
}
|
777308.c | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <CL/cl.h>
unsigned char *read_buffer(char *file_name, size_t *size_ptr)
{
FILE *f;
unsigned char *buf;
size_t size;
/* Open file */
f = fopen(file_name, "rb");
if (!f)
return NULL;
/* Obtain file size */
fseek(f, 0, SEEK_END);
size = ftell(f);
fseek(f, 0, SEEK_SET);
/* Allocate and read buffer */
buf = malloc(size + 1);
fread(buf, 1, size, f);
buf[size] = '\0';
/* Return size of buffer */
if (size_ptr)
*size_ptr = size;
/* Return buffer */
return buf;
}
void write_buffer(char *file_name, const char *buffer, size_t buffer_size)
{
FILE *f;
/* Open file */
f = fopen(file_name, "w+");
/* Write buffer */
if(buffer)
fwrite(buffer, 1, buffer_size, f);
/* Close file */
fclose(f);
}
int main(int argc, char const *argv[])
{
/* Get platform */
cl_platform_id platform;
cl_uint num_platforms;
cl_int ret = clGetPlatformIDs(1, &platform, &num_platforms);
if (ret != CL_SUCCESS)
{
printf("error: call to 'clGetPlatformIDs' failed\n");
exit(1);
}
printf("Number of platforms: %d\n", num_platforms);
printf("platform=%p\n", platform);
/* Get platform name */
char platform_name[100];
ret = clGetPlatformInfo(platform, CL_PLATFORM_NAME, sizeof(platform_name), platform_name, NULL);
if (ret != CL_SUCCESS)
{
printf("error: call to 'clGetPlatformInfo' failed\n");
exit(1);
}
printf("platform.name='%s'\n\n", platform_name);
/* Get device */
cl_device_id device;
cl_uint num_devices;
ret = clGetDeviceIDs(platform, CL_DEVICE_TYPE_GPU, 1, &device, &num_devices);
if (ret != CL_SUCCESS)
{
printf("error: call to 'clGetDeviceIDs' failed\n");
exit(1);
}
printf("Number of devices: %d\n", num_devices);
printf("device=%p\n", device);
/* Get device name */
char device_name[100];
ret = clGetDeviceInfo(device, CL_DEVICE_NAME, sizeof(device_name),
device_name, NULL);
if (ret != CL_SUCCESS)
{
printf("error: call to 'clGetDeviceInfo' failed\n");
exit(1);
}
printf("device.name='%s'\n", device_name);
printf("\n");
/* Create a Context Object */
cl_context context;
context = clCreateContext(NULL, 1, &device, NULL, NULL, &ret);
if (ret != CL_SUCCESS)
{
printf("error: call to 'clCreateContext' failed\n");
exit(1);
}
printf("context=%p\n", context);
/* Create a Command Queue Object*/
cl_command_queue command_queue;
command_queue = clCreateCommandQueue(context, device, 0, &ret);
if (ret != CL_SUCCESS)
{
printf("error: call to 'clCreateCommandQueue' failed\n");
exit(1);
}
printf("command_queue=%p\n", command_queue);
printf("\n");
/* Program source */
unsigned char *source_code;
size_t source_length;
/* Read program from 'mix_float4float4float4.cl' */
source_code = read_buffer("mix_float4float4float4.cl", &source_length);
/* Create a program */
cl_program program;
program = clCreateProgramWithSource(context, 1, (const char **)&source_code, &source_length, &ret);
if (ret != CL_SUCCESS)
{
printf("error: call to 'clCreateProgramWithSource' failed\n");
exit(1);
}
printf("program=%p\n", program);
/* Build program */
ret = clBuildProgram(program, 1, &device, NULL, NULL, NULL);
if (ret != CL_SUCCESS )
{
size_t size;
char *log;
/* Get log size */
clGetProgramBuildInfo(program, device, CL_PROGRAM_BUILD_LOG,0, NULL, &size);
/* Allocate log and print */
log = malloc(size);
clGetProgramBuildInfo(program, device, CL_PROGRAM_BUILD_LOG,size, log, NULL);
printf("error: call to 'clBuildProgram' failed:\n%s\n", log);
/* Free log and exit */
free(log);
exit(1);
}
printf("program built\n");
printf("\n");
/* Create a Kernel Object */
cl_kernel kernel;
kernel = clCreateKernel(program, "mix_float4float4float4", &ret);
if (ret != CL_SUCCESS)
{
printf("error: call to 'clCreateKernel' failed\n");
exit(1);
}
/* Create and allocate host buffers */
size_t num_elem = 10;
/* Create and init host side src buffer 0 */
cl_float4 *src_0_host_buffer;
src_0_host_buffer = malloc(num_elem * sizeof(cl_float4));
for (int i = 0; i < num_elem; i++)
src_0_host_buffer[i] = (cl_float4){{2.0, 2.0, 2.0, 2.0}};
/* Create and init device side src buffer 0 */
cl_mem src_0_device_buffer;
src_0_device_buffer = clCreateBuffer(context, CL_MEM_READ_ONLY, num_elem * sizeof(cl_float4), NULL, &ret);
if (ret != CL_SUCCESS)
{
printf("error: could not create source buffer\n");
exit(1);
}
ret = clEnqueueWriteBuffer(command_queue, src_0_device_buffer, CL_TRUE, 0, num_elem * sizeof(cl_float4), src_0_host_buffer, 0, NULL, NULL);
if (ret != CL_SUCCESS)
{
printf("error: call to 'clEnqueueWriteBuffer' failed\n");
exit(1);
}
/* Create and init host side src buffer 1 */
cl_float4 *src_1_host_buffer;
src_1_host_buffer = malloc(num_elem * sizeof(cl_float4));
for (int i = 0; i < num_elem; i++)
src_1_host_buffer[i] = (cl_float4){{2.0, 2.0, 2.0, 2.0}};
/* Create and init device side src buffer 1 */
cl_mem src_1_device_buffer;
src_1_device_buffer = clCreateBuffer(context, CL_MEM_READ_ONLY, num_elem * sizeof(cl_float4), NULL, &ret);
if (ret != CL_SUCCESS)
{
printf("error: could not create source buffer\n");
exit(1);
}
ret = clEnqueueWriteBuffer(command_queue, src_1_device_buffer, CL_TRUE, 0, num_elem * sizeof(cl_float4), src_1_host_buffer, 0, NULL, NULL);
if (ret != CL_SUCCESS)
{
printf("error: call to 'clEnqueueWriteBuffer' failed\n");
exit(1);
}
/* Create and init host side src buffer 2 */
cl_float4 *src_2_host_buffer;
src_2_host_buffer = malloc(num_elem * sizeof(cl_float4));
for (int i = 0; i < num_elem; i++)
src_2_host_buffer[i] = (cl_float4){{2.0, 2.0, 2.0, 2.0}};
/* Create and init device side src buffer 2 */
cl_mem src_2_device_buffer;
src_2_device_buffer = clCreateBuffer(context, CL_MEM_READ_ONLY, num_elem * sizeof(cl_float4), NULL, &ret);
if (ret != CL_SUCCESS)
{
printf("error: could not create source buffer\n");
exit(1);
}
ret = clEnqueueWriteBuffer(command_queue, src_2_device_buffer, CL_TRUE, 0, num_elem * sizeof(cl_float4), src_2_host_buffer, 0, NULL, NULL);
if (ret != CL_SUCCESS)
{
printf("error: call to 'clEnqueueWriteBuffer' failed\n");
exit(1);
}
/* Create host dst buffer */
cl_float4 *dst_host_buffer;
dst_host_buffer = malloc(num_elem * sizeof(cl_float4));
memset((void *)dst_host_buffer, 1, num_elem * sizeof(cl_float4));
/* Create device dst buffer */
cl_mem dst_device_buffer;
dst_device_buffer = clCreateBuffer(context, CL_MEM_WRITE_ONLY, num_elem *sizeof(cl_float4), NULL, &ret);
if (ret != CL_SUCCESS)
{
printf("error: could not create dst buffer\n");
exit(1);
}
/* Set kernel arguments */
ret = CL_SUCCESS;
ret |= clSetKernelArg(kernel, 0, sizeof(cl_mem), &src_0_device_buffer);
ret |= clSetKernelArg(kernel, 1, sizeof(cl_mem), &src_1_device_buffer);
ret |= clSetKernelArg(kernel, 2, sizeof(cl_mem), &src_2_device_buffer);
ret |= clSetKernelArg(kernel, 3, sizeof(cl_mem), &dst_device_buffer);
if (ret != CL_SUCCESS)
{
printf("error: call to 'clSetKernelArg' failed\n");
exit(1);
}
/* Launch the kernel */
size_t global_work_size = num_elem;
size_t local_work_size = num_elem;
ret = clEnqueueNDRangeKernel(command_queue, kernel, 1, NULL, &global_work_size, &local_work_size, 0, NULL, NULL);
if (ret != CL_SUCCESS)
{
printf("error: call to 'clEnqueueNDRangeKernel' failed\n");
exit(1);
}
/* Wait for it to finish */
clFinish(command_queue);
/* Read results from GPU */
ret = clEnqueueReadBuffer(command_queue, dst_device_buffer, CL_TRUE,0, num_elem * sizeof(cl_float4), dst_host_buffer, 0, NULL, NULL);
if (ret != CL_SUCCESS)
{
printf("error: call to 'clEnqueueReadBuffer' failed\n");
exit(1);
}
/* Dump dst buffer to file */
char dump_file[100];
sprintf((char *)&dump_file, "%s.result", argv[0]);
write_buffer(dump_file, (const char *)dst_host_buffer, num_elem * sizeof(cl_float4));
printf("Result dumped to %s\n", dump_file);
/* Free host dst buffer */
free(dst_host_buffer);
/* Free device dst buffer */
ret = clReleaseMemObject(dst_device_buffer);
if (ret != CL_SUCCESS)
{
printf("error: call to 'clReleaseMemObject' failed\n");
exit(1);
}
/* Free host side src buffer 0 */
free(src_0_host_buffer);
/* Free device side src buffer 0 */
ret = clReleaseMemObject(src_0_device_buffer);
if (ret != CL_SUCCESS)
{
printf("error: call to 'clReleaseMemObject' failed\n");
exit(1);
}
/* Free host side src buffer 1 */
free(src_1_host_buffer);
/* Free device side src buffer 1 */
ret = clReleaseMemObject(src_1_device_buffer);
if (ret != CL_SUCCESS)
{
printf("error: call to 'clReleaseMemObject' failed\n");
exit(1);
}
/* Free host side src buffer 2 */
free(src_2_host_buffer);
/* Free device side src buffer 2 */
ret = clReleaseMemObject(src_2_device_buffer);
if (ret != CL_SUCCESS)
{
printf("error: call to 'clReleaseMemObject' failed\n");
exit(1);
}
/* Release kernel */
ret = clReleaseKernel(kernel);
if (ret != CL_SUCCESS)
{
printf("error: call to 'clReleaseKernel' failed\n");
exit(1);
}
/* Release program */
ret = clReleaseProgram(program);
if (ret != CL_SUCCESS)
{
printf("error: call to 'clReleaseProgram' failed\n");
exit(1);
}
/* Release command queue */
ret = clReleaseCommandQueue(command_queue);
if (ret != CL_SUCCESS)
{
printf("error: call to 'clReleaseCommandQueue' failed\n");
exit(1);
}
/* Release context */
ret = clReleaseContext(context);
if (ret != CL_SUCCESS)
{
printf("error: call to 'clReleaseContext' failed\n");
exit(1);
}
return 0;
} |
885264.c | /*
* Atmel Touch Screen Driver
*
* Copyright (c) 2008 ATMEL
* Copyright (c) 2008 Dan Liang
* Copyright (c) 2008 TimeSys Corporation
* Copyright (c) 2008 Justin Waters
*
* Based on touchscreen code from Atmel Corporation.
*
* 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/init.h>
#include <linux/err.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/input.h>
#include <linux/slab.h>
#include <linux/interrupt.h>
#include <linux/clk.h>
#include <linux/platform_device.h>
#include <linux/io.h>
#include <mach/board.h>
#include <mach/cpu.h>
/* Register definitions based on AT91SAM9RL64 preliminary draft datasheet */
#define ATMEL_TSADCC_CR 0x00 /* Control register */
#define ATMEL_TSADCC_SWRST (1 << 0) /* Software Reset*/
#define ATMEL_TSADCC_START (1 << 1) /* Start conversion */
#define ATMEL_TSADCC_MR 0x04 /* Mode register */
#define ATMEL_TSADCC_TSAMOD (3 << 0) /* ADC mode */
#define ATMEL_TSADCC_TSAMOD_ADC_ONLY_MODE (0x0) /* ADC Mode */
#define ATMEL_TSADCC_TSAMOD_TS_ONLY_MODE (0x1) /* Touch Screen Only Mode */
#define ATMEL_TSADCC_LOWRES (1 << 4) /* Resolution selection */
#define ATMEL_TSADCC_SLEEP (1 << 5) /* Sleep mode */
#define ATMEL_TSADCC_PENDET (1 << 6) /* Pen Detect selection */
#define ATMEL_TSADCC_PRES (1 << 7) /* Pressure Measurement Selection */
#define ATMEL_TSADCC_PRESCAL (0x3f << 8) /* Prescalar Rate Selection */
#define ATMEL_TSADCC_EPRESCAL (0xff << 8) /* Prescalar Rate Selection (Extended) */
#define ATMEL_TSADCC_STARTUP (0x7f << 16) /* Start Up time */
#define ATMEL_TSADCC_SHTIM (0xf << 24) /* Sample & Hold time */
#define ATMEL_TSADCC_PENDBC (0xf << 28) /* Pen Detect debouncing time */
#define ATMEL_TSADCC_TRGR 0x08 /* Trigger register */
#define ATMEL_TSADCC_TRGMOD (7 << 0) /* Trigger mode */
#define ATMEL_TSADCC_TRGMOD_NONE (0 << 0)
#define ATMEL_TSADCC_TRGMOD_EXT_RISING (1 << 0)
#define ATMEL_TSADCC_TRGMOD_EXT_FALLING (2 << 0)
#define ATMEL_TSADCC_TRGMOD_EXT_ANY (3 << 0)
#define ATMEL_TSADCC_TRGMOD_PENDET (4 << 0)
#define ATMEL_TSADCC_TRGMOD_PERIOD (5 << 0)
#define ATMEL_TSADCC_TRGMOD_CONTINUOUS (6 << 0)
#define ATMEL_TSADCC_TRGPER (0xffff << 16) /* Trigger period */
#define ATMEL_TSADCC_TSR 0x0C /* Touch Screen register */
#define ATMEL_TSADCC_TSFREQ (0xf << 0) /* TS Frequency in Interleaved mode */
#define ATMEL_TSADCC_TSSHTIM (0xf << 24) /* Sample & Hold time */
#define ATMEL_TSADCC_CHER 0x10 /* Channel Enable register */
#define ATMEL_TSADCC_CHDR 0x14 /* Channel Disable register */
#define ATMEL_TSADCC_CHSR 0x18 /* Channel Status register */
#define ATMEL_TSADCC_CH(n) (1 << (n)) /* Channel number */
#define ATMEL_TSADCC_SR 0x1C /* Status register */
#define ATMEL_TSADCC_EOC(n) (1 << ((n)+0)) /* End of conversion for channel N */
#define ATMEL_TSADCC_OVRE(n) (1 << ((n)+8)) /* Overrun error for channel N */
#define ATMEL_TSADCC_DRDY (1 << 16) /* Data Ready */
#define ATMEL_TSADCC_GOVRE (1 << 17) /* General Overrun Error */
#define ATMEL_TSADCC_ENDRX (1 << 18) /* End of RX Buffer */
#define ATMEL_TSADCC_RXBUFF (1 << 19) /* TX Buffer full */
#define ATMEL_TSADCC_PENCNT (1 << 20) /* Pen contact */
#define ATMEL_TSADCC_NOCNT (1 << 21) /* No contact */
#define ATMEL_TSADCC_LCDR 0x20 /* Last Converted Data register */
#define ATMEL_TSADCC_DATA (0x3ff << 0) /* Channel data */
#define ATMEL_TSADCC_IER 0x24 /* Interrupt Enable register */
#define ATMEL_TSADCC_IDR 0x28 /* Interrupt Disable register */
#define ATMEL_TSADCC_IMR 0x2C /* Interrupt Mask register */
#define ATMEL_TSADCC_CDR0 0x30 /* Channel Data 0 */
#define ATMEL_TSADCC_CDR1 0x34 /* Channel Data 1 */
#define ATMEL_TSADCC_CDR2 0x38 /* Channel Data 2 */
#define ATMEL_TSADCC_CDR3 0x3C /* Channel Data 3 */
#define ATMEL_TSADCC_CDR4 0x40 /* Channel Data 4 */
#define ATMEL_TSADCC_CDR5 0x44 /* Channel Data 5 */
#define ATMEL_TSADCC_XPOS 0x50
#define ATMEL_TSADCC_Z1DAT 0x54
#define ATMEL_TSADCC_Z2DAT 0x58
#define PRESCALER_VAL(x) ((x) >> 8)
#define ADC_DEFAULT_CLOCK 100000
struct atmel_tsadcc {
struct input_dev *input;
char phys[32];
struct clk *clk;
int irq;
unsigned int prev_absx;
unsigned int prev_absy;
unsigned char bufferedmeasure;
};
static void __iomem *tsc_base;
#define atmel_tsadcc_read(reg) __raw_readl(tsc_base + (reg))
#define atmel_tsadcc_write(reg, val) __raw_writel((val), tsc_base + (reg))
static irqreturn_t atmel_tsadcc_interrupt(int irq, void *dev)
{
struct atmel_tsadcc *ts_dev = (struct atmel_tsadcc *)dev;
struct input_dev *input_dev = ts_dev->input;
unsigned int status;
unsigned int reg;
status = atmel_tsadcc_read(ATMEL_TSADCC_SR);
status &= atmel_tsadcc_read(ATMEL_TSADCC_IMR);
if (status & ATMEL_TSADCC_NOCNT) {
/* Contact lost */
reg = atmel_tsadcc_read(ATMEL_TSADCC_MR) | ATMEL_TSADCC_PENDBC;
atmel_tsadcc_write(ATMEL_TSADCC_MR, reg);
atmel_tsadcc_write(ATMEL_TSADCC_TRGR, ATMEL_TSADCC_TRGMOD_NONE);
atmel_tsadcc_write(ATMEL_TSADCC_IDR,
ATMEL_TSADCC_EOC(3) | ATMEL_TSADCC_NOCNT);
atmel_tsadcc_write(ATMEL_TSADCC_IER, ATMEL_TSADCC_PENCNT);
input_report_key(input_dev, BTN_TOUCH, 0);
ts_dev->bufferedmeasure = 0;
input_sync(input_dev);
} else if (status & ATMEL_TSADCC_PENCNT) {
/* Pen detected */
reg = atmel_tsadcc_read(ATMEL_TSADCC_MR);
reg &= ~ATMEL_TSADCC_PENDBC;
atmel_tsadcc_write(ATMEL_TSADCC_IDR, ATMEL_TSADCC_PENCNT);
atmel_tsadcc_write(ATMEL_TSADCC_MR, reg);
atmel_tsadcc_write(ATMEL_TSADCC_IER,
ATMEL_TSADCC_EOC(3) | ATMEL_TSADCC_NOCNT);
atmel_tsadcc_write(ATMEL_TSADCC_TRGR,
ATMEL_TSADCC_TRGMOD_PERIOD | (0x0FFF << 16));
} else if (status & ATMEL_TSADCC_EOC(3)) {
/* Conversion finished */
if (ts_dev->bufferedmeasure) {
/* Last measurement is always discarded, since it can
* be erroneous.
* Always report previous measurement */
input_report_abs(input_dev, ABS_X, ts_dev->prev_absx);
input_report_abs(input_dev, ABS_Y, ts_dev->prev_absy);
input_report_key(input_dev, BTN_TOUCH, 1);
input_sync(input_dev);
} else
ts_dev->bufferedmeasure = 1;
/* Now make new measurement */
ts_dev->prev_absx = atmel_tsadcc_read(ATMEL_TSADCC_CDR3) << 10;
ts_dev->prev_absx /= atmel_tsadcc_read(ATMEL_TSADCC_CDR2);
ts_dev->prev_absy = atmel_tsadcc_read(ATMEL_TSADCC_CDR1) << 10;
ts_dev->prev_absy /= atmel_tsadcc_read(ATMEL_TSADCC_CDR0);
}
return IRQ_HANDLED;
}
/*
* The functions for inserting/removing us as a module.
*/
static int __devinit atmel_tsadcc_probe(struct platform_device *pdev)
{
struct atmel_tsadcc *ts_dev;
struct input_dev *input_dev;
struct resource *res;
struct at91_tsadcc_data *pdata = pdev->dev.platform_data;
int err = 0;
unsigned int prsc;
unsigned int reg;
res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
if (!res) {
dev_err(&pdev->dev, "no mmio resource defined.\n");
return -ENXIO;
}
/* Allocate memory for device */
ts_dev = kzalloc(sizeof(struct atmel_tsadcc), GFP_KERNEL);
if (!ts_dev) {
dev_err(&pdev->dev, "failed to allocate memory.\n");
return -ENOMEM;
}
platform_set_drvdata(pdev, ts_dev);
input_dev = input_allocate_device();
if (!input_dev) {
dev_err(&pdev->dev, "failed to allocate input device.\n");
err = -EBUSY;
goto err_free_mem;
}
ts_dev->irq = platform_get_irq(pdev, 0);
if (ts_dev->irq < 0) {
dev_err(&pdev->dev, "no irq ID is designated.\n");
err = -ENODEV;
goto err_free_dev;
}
if (!request_mem_region(res->start, resource_size(res),
"atmel tsadcc regs")) {
dev_err(&pdev->dev, "resources is unavailable.\n");
err = -EBUSY;
goto err_free_dev;
}
tsc_base = ioremap(res->start, resource_size(res));
if (!tsc_base) {
dev_err(&pdev->dev, "failed to map registers.\n");
err = -ENOMEM;
goto err_release_mem;
}
err = request_irq(ts_dev->irq, atmel_tsadcc_interrupt, 0,
pdev->dev.driver->name, ts_dev);
if (err) {
dev_err(&pdev->dev, "failed to allocate irq.\n");
goto err_unmap_regs;
}
ts_dev->clk = clk_get(&pdev->dev, "tsc_clk");
if (IS_ERR(ts_dev->clk)) {
dev_err(&pdev->dev, "failed to get ts_clk\n");
err = PTR_ERR(ts_dev->clk);
goto err_free_irq;
}
ts_dev->input = input_dev;
ts_dev->bufferedmeasure = 0;
snprintf(ts_dev->phys, sizeof(ts_dev->phys),
"%s/input0", dev_name(&pdev->dev));
input_dev->name = "atmel touch screen controller";
input_dev->phys = ts_dev->phys;
input_dev->dev.parent = &pdev->dev;
__set_bit(EV_ABS, input_dev->evbit);
input_set_abs_params(input_dev, ABS_X, 0, 0x3FF, 0, 0);
input_set_abs_params(input_dev, ABS_Y, 0, 0x3FF, 0, 0);
input_set_capability(input_dev, EV_KEY, BTN_TOUCH);
/* clk_enable() always returns 0, no need to check it */
clk_enable(ts_dev->clk);
prsc = clk_get_rate(ts_dev->clk);
dev_info(&pdev->dev, "Master clock is set at: %d Hz\n", prsc);
if (!pdata)
goto err_fail;
if (!pdata->adc_clock)
pdata->adc_clock = ADC_DEFAULT_CLOCK;
prsc = (prsc / (2 * pdata->adc_clock)) - 1;
/* saturate if this value is too high */
if (cpu_is_at91sam9rl()) {
if (prsc > PRESCALER_VAL(ATMEL_TSADCC_PRESCAL))
prsc = PRESCALER_VAL(ATMEL_TSADCC_PRESCAL);
} else {
if (prsc > PRESCALER_VAL(ATMEL_TSADCC_EPRESCAL))
prsc = PRESCALER_VAL(ATMEL_TSADCC_EPRESCAL);
}
dev_info(&pdev->dev, "Prescaler is set at: %d\n", prsc);
reg = ATMEL_TSADCC_TSAMOD_TS_ONLY_MODE |
((0x00 << 5) & ATMEL_TSADCC_SLEEP) | /* Normal Mode */
((0x01 << 6) & ATMEL_TSADCC_PENDET) | /* Enable Pen Detect */
(prsc << 8) |
((0x26 << 16) & ATMEL_TSADCC_STARTUP) |
((pdata->pendet_debounce << 28) & ATMEL_TSADCC_PENDBC);
atmel_tsadcc_write(ATMEL_TSADCC_CR, ATMEL_TSADCC_SWRST);
atmel_tsadcc_write(ATMEL_TSADCC_MR, reg);
atmel_tsadcc_write(ATMEL_TSADCC_TRGR, ATMEL_TSADCC_TRGMOD_NONE);
atmel_tsadcc_write(ATMEL_TSADCC_TSR,
(pdata->ts_sample_hold_time << 24) & ATMEL_TSADCC_TSSHTIM);
atmel_tsadcc_read(ATMEL_TSADCC_SR);
atmel_tsadcc_write(ATMEL_TSADCC_IER, ATMEL_TSADCC_PENCNT);
/* All went ok, so register to the input system */
err = input_register_device(input_dev);
if (err)
goto err_fail;
return 0;
err_fail:
clk_disable(ts_dev->clk);
clk_put(ts_dev->clk);
err_free_irq:
free_irq(ts_dev->irq, ts_dev);
err_unmap_regs:
iounmap(tsc_base);
err_release_mem:
release_mem_region(res->start, resource_size(res));
err_free_dev:
input_free_device(input_dev);
err_free_mem:
kfree(ts_dev);
return err;
}
static int __devexit atmel_tsadcc_remove(struct platform_device *pdev)
{
struct atmel_tsadcc *ts_dev = dev_get_drvdata(&pdev->dev);
struct resource *res;
free_irq(ts_dev->irq, ts_dev);
input_unregister_device(ts_dev->input);
res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
iounmap(tsc_base);
release_mem_region(res->start, resource_size(res));
clk_disable(ts_dev->clk);
clk_put(ts_dev->clk);
kfree(ts_dev);
return 0;
}
static struct platform_driver atmel_tsadcc_driver = {
.probe = atmel_tsadcc_probe,
.remove = __devexit_p(atmel_tsadcc_remove),
.driver = {
.name = "atmel_tsadcc",
},
};
module_platform_driver(atmel_tsadcc_driver);
MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("Atmel TouchScreen Driver");
MODULE_AUTHOR("Dan Liang <[email protected]>");
|
598918.c | /*
* Copyright (C) 2008-2009 Texas Instruments Inc
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Driver name : VPFE Capture driver
* VPFE Capture driver allows applications to capture and stream video
* frames on DaVinci SoCs (DM6446, DM355 etc) from a YUV source such as
* TVP5146 or Raw Bayer RGB image data from an image sensor
* such as Microns' MT9T001, MT9T031 etc.
*
* These SoCs have, in common, a Video Processing Subsystem (VPSS) that
* consists of a Video Processing Front End (VPFE) for capturing
* video/raw image data and Video Processing Back End (VPBE) for displaying
* YUV data through an in-built analog encoder or Digital LCD port. This
* driver is for capture through VPFE. A typical EVM using these SoCs have
* following high level configuration.
*
*
* decoder(TVP5146/ YUV/
* MT9T001) --> Raw Bayer RGB ---> MUX -> VPFE (CCDC/ISIF)
* data input | |
* V |
* SDRAM |
* V
* Image Processor
* |
* V
* SDRAM
* The data flow happens from a decoder connected to the VPFE over a
* YUV embedded (BT.656/BT.1120) or separate sync or raw bayer rgb interface
* and to the input of VPFE through an optional MUX (if more inputs are
* to be interfaced on the EVM). The input data is first passed through
* CCDC (CCD Controller, a.k.a Image Sensor Interface, ISIF). The CCDC
* does very little or no processing on YUV data and does pre-process Raw
* Bayer RGB data through modules such as Defect Pixel Correction (DFC)
* Color Space Conversion (CSC), data gain/offset etc. After this, data
* can be written to SDRAM or can be connected to the image processing
* block such as IPIPE (on DM355 only).
*
* Features supported
* - MMAP IO
* - Capture using TVP5146 over BT.656
* - support for interfacing decoders using sub device model
* - Work with DM355 or DM6446 CCDC to do Raw Bayer RGB/YUV
* data capture to SDRAM.
* TODO list
* - Support multiple REQBUF after open
* - Support for de-allocating buffers through REQBUF
* - Support for Raw Bayer RGB capture
* - Support for chaining Image Processor
* - Support for static allocation of buffers
* - Support for USERPTR IO
* - Support for STREAMON before QBUF
* - Support for control ioctls
*/
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/init.h>
#include <linux/platform_device.h>
#include <linux/interrupt.h>
#include <media/v4l2-common.h>
#include <linux/io.h>
#include <media/davinci/vpfe_capture.h>
#include "ccdc_hw_device.h"
static int debug;
static u32 numbuffers = 3;
static u32 bufsize = (720 * 576 * 2);
module_param(numbuffers, uint, S_IRUGO);
module_param(bufsize, uint, S_IRUGO);
module_param(debug, int, 0644);
MODULE_PARM_DESC(numbuffers, "buffer count (default:3)");
MODULE_PARM_DESC(bufsize, "buffer size in bytes (default:720 x 576 x 2)");
MODULE_PARM_DESC(debug, "Debug level 0-1");
MODULE_DESCRIPTION("VPFE Video for Linux Capture Driver");
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Texas Instruments");
/* standard information */
struct vpfe_standard {
v4l2_std_id std_id;
unsigned int width;
unsigned int height;
struct v4l2_fract pixelaspect;
/* 0 - progressive, 1 - interlaced */
int frame_format;
};
/* ccdc configuration */
struct ccdc_config {
/* This make sure vpfe is probed and ready to go */
int vpfe_probed;
/* name of ccdc device */
char name[32];
};
/* data structures */
static struct vpfe_config_params config_params = {
.min_numbuffers = 3,
.numbuffers = 3,
.min_bufsize = 720 * 480 * 2,
.device_bufsize = 720 * 576 * 2,
};
/* ccdc device registered */
static struct ccdc_hw_device *ccdc_dev;
/* lock for accessing ccdc information */
static DEFINE_MUTEX(ccdc_lock);
/* ccdc configuration */
static struct ccdc_config *ccdc_cfg;
const struct vpfe_standard vpfe_standards[] = {
{V4L2_STD_525_60, 720, 480, {11, 10}, 1},
{V4L2_STD_625_50, 720, 576, {54, 59}, 1},
};
/* Used when raw Bayer image from ccdc is directly captured to SDRAM */
static const struct vpfe_pixel_format vpfe_pix_fmts[] = {
{
.fmtdesc = {
.index = 0,
.type = V4L2_BUF_TYPE_VIDEO_CAPTURE,
.description = "Bayer GrRBGb 8bit A-Law compr.",
.pixelformat = V4L2_PIX_FMT_SBGGR8,
},
.bpp = 1,
},
{
.fmtdesc = {
.index = 1,
.type = V4L2_BUF_TYPE_VIDEO_CAPTURE,
.description = "Bayer GrRBGb - 16bit",
.pixelformat = V4L2_PIX_FMT_SBGGR16,
},
.bpp = 2,
},
{
.fmtdesc = {
.index = 2,
.type = V4L2_BUF_TYPE_VIDEO_CAPTURE,
.description = "Bayer GrRBGb 8bit DPCM compr.",
.pixelformat = V4L2_PIX_FMT_SGRBG10DPCM8,
},
.bpp = 1,
},
{
.fmtdesc = {
.index = 3,
.type = V4L2_BUF_TYPE_VIDEO_CAPTURE,
.description = "YCbCr 4:2:2 Interleaved UYVY",
.pixelformat = V4L2_PIX_FMT_UYVY,
},
.bpp = 2,
},
{
.fmtdesc = {
.index = 4,
.type = V4L2_BUF_TYPE_VIDEO_CAPTURE,
.description = "YCbCr 4:2:2 Interleaved YUYV",
.pixelformat = V4L2_PIX_FMT_YUYV,
},
.bpp = 2,
},
{
.fmtdesc = {
.index = 5,
.type = V4L2_BUF_TYPE_VIDEO_CAPTURE,
.description = "Y/CbCr 4:2:0 - Semi planar",
.pixelformat = V4L2_PIX_FMT_NV12,
},
.bpp = 1,
},
};
/*
* vpfe_lookup_pix_format()
* lookup an entry in the vpfe pix format table based on pix_format
*/
static const struct vpfe_pixel_format *vpfe_lookup_pix_format(u32 pix_format)
{
int i;
for (i = 0; i < ARRAY_SIZE(vpfe_pix_fmts); i++) {
if (pix_format == vpfe_pix_fmts[i].fmtdesc.pixelformat)
return &vpfe_pix_fmts[i];
}
return NULL;
}
/*
* vpfe_register_ccdc_device. CCDC module calls this to
* register with vpfe capture
*/
int vpfe_register_ccdc_device(struct ccdc_hw_device *dev)
{
int ret = 0;
printk(KERN_NOTICE "vpfe_register_ccdc_device: %s\n", dev->name);
BUG_ON(!dev->hw_ops.open);
BUG_ON(!dev->hw_ops.enable);
BUG_ON(!dev->hw_ops.set_hw_if_params);
BUG_ON(!dev->hw_ops.configure);
BUG_ON(!dev->hw_ops.set_buftype);
BUG_ON(!dev->hw_ops.get_buftype);
BUG_ON(!dev->hw_ops.enum_pix);
BUG_ON(!dev->hw_ops.set_frame_format);
BUG_ON(!dev->hw_ops.get_frame_format);
BUG_ON(!dev->hw_ops.get_pixel_format);
BUG_ON(!dev->hw_ops.set_pixel_format);
BUG_ON(!dev->hw_ops.set_image_window);
BUG_ON(!dev->hw_ops.get_image_window);
BUG_ON(!dev->hw_ops.get_line_length);
BUG_ON(!dev->hw_ops.getfid);
mutex_lock(&ccdc_lock);
if (NULL == ccdc_cfg) {
/*
* TODO. Will this ever happen? if so, we need to fix it.
* Proabably we need to add the request to a linked list and
* walk through it during vpfe probe
*/
printk(KERN_ERR "vpfe capture not initialized\n");
ret = -EFAULT;
goto unlock;
}
if (strcmp(dev->name, ccdc_cfg->name)) {
/* ignore this ccdc */
ret = -EINVAL;
goto unlock;
}
if (ccdc_dev) {
printk(KERN_ERR "ccdc already registered\n");
ret = -EINVAL;
goto unlock;
}
ccdc_dev = dev;
unlock:
mutex_unlock(&ccdc_lock);
return ret;
}
EXPORT_SYMBOL(vpfe_register_ccdc_device);
/*
* vpfe_unregister_ccdc_device. CCDC module calls this to
* unregister with vpfe capture
*/
void vpfe_unregister_ccdc_device(struct ccdc_hw_device *dev)
{
if (NULL == dev) {
printk(KERN_ERR "invalid ccdc device ptr\n");
return;
}
printk(KERN_NOTICE "vpfe_unregister_ccdc_device, dev->name = %s\n",
dev->name);
if (strcmp(dev->name, ccdc_cfg->name)) {
/* ignore this ccdc */
return;
}
mutex_lock(&ccdc_lock);
ccdc_dev = NULL;
mutex_unlock(&ccdc_lock);
return;
}
EXPORT_SYMBOL(vpfe_unregister_ccdc_device);
/*
* vpfe_get_ccdc_image_format - Get image parameters based on CCDC settings
*/
static int vpfe_get_ccdc_image_format(struct vpfe_device *vpfe_dev,
struct v4l2_format *f)
{
struct v4l2_rect image_win;
enum ccdc_buftype buf_type;
enum ccdc_frmfmt frm_fmt;
memset(f, 0, sizeof(*f));
f->type = V4L2_BUF_TYPE_VIDEO_OUTPUT;
ccdc_dev->hw_ops.get_image_window(&image_win);
f->fmt.pix.width = image_win.width;
f->fmt.pix.height = image_win.height;
f->fmt.pix.bytesperline = ccdc_dev->hw_ops.get_line_length();
f->fmt.pix.sizeimage = f->fmt.pix.bytesperline *
f->fmt.pix.height;
buf_type = ccdc_dev->hw_ops.get_buftype();
f->fmt.pix.pixelformat = ccdc_dev->hw_ops.get_pixel_format();
frm_fmt = ccdc_dev->hw_ops.get_frame_format();
if (frm_fmt == CCDC_FRMFMT_PROGRESSIVE)
f->fmt.pix.field = V4L2_FIELD_NONE;
else if (frm_fmt == CCDC_FRMFMT_INTERLACED) {
if (buf_type == CCDC_BUFTYPE_FLD_INTERLEAVED)
f->fmt.pix.field = V4L2_FIELD_INTERLACED;
else if (buf_type == CCDC_BUFTYPE_FLD_SEPARATED)
f->fmt.pix.field = V4L2_FIELD_SEQ_TB;
else {
v4l2_err(&vpfe_dev->v4l2_dev, "Invalid buf_type\n");
return -EINVAL;
}
} else {
v4l2_err(&vpfe_dev->v4l2_dev, "Invalid frm_fmt\n");
return -EINVAL;
}
return 0;
}
/*
* vpfe_config_ccdc_image_format()
* For a pix format, configure ccdc to setup the capture
*/
static int vpfe_config_ccdc_image_format(struct vpfe_device *vpfe_dev)
{
enum ccdc_frmfmt frm_fmt = CCDC_FRMFMT_INTERLACED;
int ret = 0;
if (ccdc_dev->hw_ops.set_pixel_format(
vpfe_dev->fmt.fmt.pix.pixelformat) < 0) {
v4l2_err(&vpfe_dev->v4l2_dev,
"couldn't set pix format in ccdc\n");
return -EINVAL;
}
/* configure the image window */
ccdc_dev->hw_ops.set_image_window(&vpfe_dev->crop);
switch (vpfe_dev->fmt.fmt.pix.field) {
case V4L2_FIELD_INTERLACED:
/* do nothing, since it is default */
ret = ccdc_dev->hw_ops.set_buftype(
CCDC_BUFTYPE_FLD_INTERLEAVED);
break;
case V4L2_FIELD_NONE:
frm_fmt = CCDC_FRMFMT_PROGRESSIVE;
/* buffer type only applicable for interlaced scan */
break;
case V4L2_FIELD_SEQ_TB:
ret = ccdc_dev->hw_ops.set_buftype(
CCDC_BUFTYPE_FLD_SEPARATED);
break;
default:
return -EINVAL;
}
/* set the frame format */
if (!ret)
ret = ccdc_dev->hw_ops.set_frame_format(frm_fmt);
return ret;
}
/*
* vpfe_config_image_format()
* For a given standard, this functions sets up the default
* pix format & crop values in the vpfe device and ccdc. It first
* starts with defaults based values from the standard table.
* It then checks if sub device support g_mbus_fmt and then override the
* values based on that.Sets crop values to match with scan resolution
* starting at 0,0. It calls vpfe_config_ccdc_image_format() set the
* values in ccdc
*/
static int vpfe_config_image_format(struct vpfe_device *vpfe_dev,
v4l2_std_id std_id)
{
struct vpfe_subdev_info *sdinfo = vpfe_dev->current_subdev;
struct v4l2_mbus_framefmt mbus_fmt;
struct v4l2_pix_format *pix = &vpfe_dev->fmt.fmt.pix;
int i, ret = 0;
for (i = 0; i < ARRAY_SIZE(vpfe_standards); i++) {
if (vpfe_standards[i].std_id & std_id) {
vpfe_dev->std_info.active_pixels =
vpfe_standards[i].width;
vpfe_dev->std_info.active_lines =
vpfe_standards[i].height;
vpfe_dev->std_info.frame_format =
vpfe_standards[i].frame_format;
vpfe_dev->std_index = i;
break;
}
}
if (i == ARRAY_SIZE(vpfe_standards)) {
v4l2_err(&vpfe_dev->v4l2_dev, "standard not supported\n");
return -EINVAL;
}
vpfe_dev->crop.top = 0;
vpfe_dev->crop.left = 0;
vpfe_dev->crop.width = vpfe_dev->std_info.active_pixels;
vpfe_dev->crop.height = vpfe_dev->std_info.active_lines;
pix->width = vpfe_dev->crop.width;
pix->height = vpfe_dev->crop.height;
/* first field and frame format based on standard frame format */
if (vpfe_dev->std_info.frame_format) {
pix->field = V4L2_FIELD_INTERLACED;
/* assume V4L2_PIX_FMT_UYVY as default */
pix->pixelformat = V4L2_PIX_FMT_UYVY;
v4l2_fill_mbus_format(&mbus_fmt, pix,
V4L2_MBUS_FMT_YUYV10_2X10);
} else {
pix->field = V4L2_FIELD_NONE;
/* assume V4L2_PIX_FMT_SBGGR8 */
pix->pixelformat = V4L2_PIX_FMT_SBGGR8;
v4l2_fill_mbus_format(&mbus_fmt, pix,
V4L2_MBUS_FMT_SBGGR8_1X8);
}
/* if sub device supports g_mbus_fmt, override the defaults */
ret = v4l2_device_call_until_err(&vpfe_dev->v4l2_dev,
sdinfo->grp_id, video, g_mbus_fmt, &mbus_fmt);
if (ret && ret != -ENOIOCTLCMD) {
v4l2_err(&vpfe_dev->v4l2_dev,
"error in getting g_mbus_fmt from sub device\n");
return ret;
}
v4l2_fill_pix_format(pix, &mbus_fmt);
pix->bytesperline = pix->width * 2;
pix->sizeimage = pix->bytesperline * pix->height;
/* Sets the values in CCDC */
ret = vpfe_config_ccdc_image_format(vpfe_dev);
if (ret)
return ret;
/* Update the values of sizeimage and bytesperline */
if (!ret) {
pix->bytesperline = ccdc_dev->hw_ops.get_line_length();
pix->sizeimage = pix->bytesperline * pix->height;
}
return ret;
}
static int vpfe_initialize_device(struct vpfe_device *vpfe_dev)
{
int ret = 0;
/* set first input of current subdevice as the current input */
vpfe_dev->current_input = 0;
/* set default standard */
vpfe_dev->std_index = 0;
/* Configure the default format information */
ret = vpfe_config_image_format(vpfe_dev,
vpfe_standards[vpfe_dev->std_index].std_id);
if (ret)
return ret;
/* now open the ccdc device to initialize it */
mutex_lock(&ccdc_lock);
if (NULL == ccdc_dev) {
v4l2_err(&vpfe_dev->v4l2_dev, "ccdc device not registered\n");
ret = -ENODEV;
goto unlock;
}
if (!try_module_get(ccdc_dev->owner)) {
v4l2_err(&vpfe_dev->v4l2_dev, "Couldn't lock ccdc module\n");
ret = -ENODEV;
goto unlock;
}
ret = ccdc_dev->hw_ops.open(vpfe_dev->pdev);
if (!ret)
vpfe_dev->initialized = 1;
/* Clear all VPFE/CCDC interrupts */
if (vpfe_dev->cfg->clr_intr)
vpfe_dev->cfg->clr_intr(-1);
unlock:
mutex_unlock(&ccdc_lock);
return ret;
}
/*
* vpfe_open : It creates object of file handle structure and
* stores it in private_data member of filepointer
*/
static int vpfe_open(struct file *file)
{
struct vpfe_device *vpfe_dev = video_drvdata(file);
struct vpfe_fh *fh;
v4l2_dbg(1, debug, &vpfe_dev->v4l2_dev, "vpfe_open\n");
if (!vpfe_dev->cfg->num_subdevs) {
v4l2_err(&vpfe_dev->v4l2_dev, "No decoder registered\n");
return -ENODEV;
}
/* Allocate memory for the file handle object */
fh = kmalloc(sizeof(struct vpfe_fh), GFP_KERNEL);
if (NULL == fh) {
v4l2_err(&vpfe_dev->v4l2_dev,
"unable to allocate memory for file handle object\n");
return -ENOMEM;
}
/* store pointer to fh in private_data member of file */
file->private_data = fh;
fh->vpfe_dev = vpfe_dev;
mutex_lock(&vpfe_dev->lock);
/* If decoder is not initialized. initialize it */
if (!vpfe_dev->initialized) {
if (vpfe_initialize_device(vpfe_dev)) {
mutex_unlock(&vpfe_dev->lock);
return -ENODEV;
}
}
/* Increment device usrs counter */
vpfe_dev->usrs++;
/* Set io_allowed member to false */
fh->io_allowed = 0;
/* Initialize priority of this instance to default priority */
fh->prio = V4L2_PRIORITY_UNSET;
v4l2_prio_open(&vpfe_dev->prio, &fh->prio);
mutex_unlock(&vpfe_dev->lock);
return 0;
}
static void vpfe_schedule_next_buffer(struct vpfe_device *vpfe_dev)
{
unsigned long addr;
vpfe_dev->next_frm = list_entry(vpfe_dev->dma_queue.next,
struct videobuf_buffer, queue);
list_del(&vpfe_dev->next_frm->queue);
vpfe_dev->next_frm->state = VIDEOBUF_ACTIVE;
addr = videobuf_to_dma_contig(vpfe_dev->next_frm);
ccdc_dev->hw_ops.setfbaddr(addr);
}
static void vpfe_schedule_bottom_field(struct vpfe_device *vpfe_dev)
{
unsigned long addr;
addr = videobuf_to_dma_contig(vpfe_dev->cur_frm);
addr += vpfe_dev->field_off;
ccdc_dev->hw_ops.setfbaddr(addr);
}
static void vpfe_process_buffer_complete(struct vpfe_device *vpfe_dev)
{
v4l2_get_timestamp(&vpfe_dev->cur_frm->ts);
vpfe_dev->cur_frm->state = VIDEOBUF_DONE;
vpfe_dev->cur_frm->size = vpfe_dev->fmt.fmt.pix.sizeimage;
wake_up_interruptible(&vpfe_dev->cur_frm->done);
vpfe_dev->cur_frm = vpfe_dev->next_frm;
}
/* ISR for VINT0*/
static irqreturn_t vpfe_isr(int irq, void *dev_id)
{
struct vpfe_device *vpfe_dev = dev_id;
enum v4l2_field field;
int fid;
v4l2_dbg(1, debug, &vpfe_dev->v4l2_dev, "\nStarting vpfe_isr...\n");
field = vpfe_dev->fmt.fmt.pix.field;
/* if streaming not started, don't do anything */
if (!vpfe_dev->started)
goto clear_intr;
/* only for 6446 this will be applicable */
if (NULL != ccdc_dev->hw_ops.reset)
ccdc_dev->hw_ops.reset();
if (field == V4L2_FIELD_NONE) {
/* handle progressive frame capture */
v4l2_dbg(1, debug, &vpfe_dev->v4l2_dev,
"frame format is progressive...\n");
if (vpfe_dev->cur_frm != vpfe_dev->next_frm)
vpfe_process_buffer_complete(vpfe_dev);
goto clear_intr;
}
/* interlaced or TB capture check which field we are in hardware */
fid = ccdc_dev->hw_ops.getfid();
/* switch the software maintained field id */
vpfe_dev->field_id ^= 1;
v4l2_dbg(1, debug, &vpfe_dev->v4l2_dev, "field id = %x:%x.\n",
fid, vpfe_dev->field_id);
if (fid == vpfe_dev->field_id) {
/* we are in-sync here,continue */
if (fid == 0) {
/*
* One frame is just being captured. If the next frame
* is available, release the current frame and move on
*/
if (vpfe_dev->cur_frm != vpfe_dev->next_frm)
vpfe_process_buffer_complete(vpfe_dev);
/*
* based on whether the two fields are stored
* interleavely or separately in memory, reconfigure
* the CCDC memory address
*/
if (field == V4L2_FIELD_SEQ_TB) {
vpfe_schedule_bottom_field(vpfe_dev);
}
goto clear_intr;
}
/*
* if one field is just being captured configure
* the next frame get the next frame from the empty
* queue if no frame is available hold on to the
* current buffer
*/
spin_lock(&vpfe_dev->dma_queue_lock);
if (!list_empty(&vpfe_dev->dma_queue) &&
vpfe_dev->cur_frm == vpfe_dev->next_frm)
vpfe_schedule_next_buffer(vpfe_dev);
spin_unlock(&vpfe_dev->dma_queue_lock);
} else if (fid == 0) {
/*
* out of sync. Recover from any hardware out-of-sync.
* May loose one frame
*/
vpfe_dev->field_id = fid;
}
clear_intr:
if (vpfe_dev->cfg->clr_intr)
vpfe_dev->cfg->clr_intr(irq);
return IRQ_HANDLED;
}
/* vdint1_isr - isr handler for VINT1 interrupt */
static irqreturn_t vdint1_isr(int irq, void *dev_id)
{
struct vpfe_device *vpfe_dev = dev_id;
v4l2_dbg(1, debug, &vpfe_dev->v4l2_dev, "\nInside vdint1_isr...\n");
/* if streaming not started, don't do anything */
if (!vpfe_dev->started) {
if (vpfe_dev->cfg->clr_intr)
vpfe_dev->cfg->clr_intr(irq);
return IRQ_HANDLED;
}
spin_lock(&vpfe_dev->dma_queue_lock);
if ((vpfe_dev->fmt.fmt.pix.field == V4L2_FIELD_NONE) &&
!list_empty(&vpfe_dev->dma_queue) &&
vpfe_dev->cur_frm == vpfe_dev->next_frm)
vpfe_schedule_next_buffer(vpfe_dev);
spin_unlock(&vpfe_dev->dma_queue_lock);
if (vpfe_dev->cfg->clr_intr)
vpfe_dev->cfg->clr_intr(irq);
return IRQ_HANDLED;
}
static void vpfe_detach_irq(struct vpfe_device *vpfe_dev)
{
enum ccdc_frmfmt frame_format;
frame_format = ccdc_dev->hw_ops.get_frame_format();
if (frame_format == CCDC_FRMFMT_PROGRESSIVE)
free_irq(vpfe_dev->ccdc_irq1, vpfe_dev);
}
static int vpfe_attach_irq(struct vpfe_device *vpfe_dev)
{
enum ccdc_frmfmt frame_format;
frame_format = ccdc_dev->hw_ops.get_frame_format();
if (frame_format == CCDC_FRMFMT_PROGRESSIVE) {
return request_irq(vpfe_dev->ccdc_irq1, vdint1_isr,
IRQF_DISABLED, "vpfe_capture1",
vpfe_dev);
}
return 0;
}
/* vpfe_stop_ccdc_capture: stop streaming in ccdc/isif */
static void vpfe_stop_ccdc_capture(struct vpfe_device *vpfe_dev)
{
vpfe_dev->started = 0;
ccdc_dev->hw_ops.enable(0);
if (ccdc_dev->hw_ops.enable_out_to_sdram)
ccdc_dev->hw_ops.enable_out_to_sdram(0);
}
/*
* vpfe_release : This function deletes buffer queue, frees the
* buffers and the vpfe file handle
*/
static int vpfe_release(struct file *file)
{
struct vpfe_device *vpfe_dev = video_drvdata(file);
struct vpfe_fh *fh = file->private_data;
struct vpfe_subdev_info *sdinfo;
int ret;
v4l2_dbg(1, debug, &vpfe_dev->v4l2_dev, "vpfe_release\n");
/* Get the device lock */
mutex_lock(&vpfe_dev->lock);
/* if this instance is doing IO */
if (fh->io_allowed) {
if (vpfe_dev->started) {
sdinfo = vpfe_dev->current_subdev;
ret = v4l2_device_call_until_err(&vpfe_dev->v4l2_dev,
sdinfo->grp_id,
video, s_stream, 0);
if (ret && (ret != -ENOIOCTLCMD))
v4l2_err(&vpfe_dev->v4l2_dev,
"stream off failed in subdev\n");
vpfe_stop_ccdc_capture(vpfe_dev);
vpfe_detach_irq(vpfe_dev);
videobuf_streamoff(&vpfe_dev->buffer_queue);
}
vpfe_dev->io_usrs = 0;
vpfe_dev->numbuffers = config_params.numbuffers;
}
/* Decrement device usrs counter */
vpfe_dev->usrs--;
/* Close the priority */
v4l2_prio_close(&vpfe_dev->prio, fh->prio);
/* If this is the last file handle */
if (!vpfe_dev->usrs) {
vpfe_dev->initialized = 0;
if (ccdc_dev->hw_ops.close)
ccdc_dev->hw_ops.close(vpfe_dev->pdev);
module_put(ccdc_dev->owner);
}
mutex_unlock(&vpfe_dev->lock);
file->private_data = NULL;
/* Free memory allocated to file handle object */
kfree(fh);
return 0;
}
/*
* vpfe_mmap : It is used to map kernel space buffers
* into user spaces
*/
static int vpfe_mmap(struct file *file, struct vm_area_struct *vma)
{
/* Get the device object and file handle object */
struct vpfe_device *vpfe_dev = video_drvdata(file);
v4l2_dbg(1, debug, &vpfe_dev->v4l2_dev, "vpfe_mmap\n");
return videobuf_mmap_mapper(&vpfe_dev->buffer_queue, vma);
}
/*
* vpfe_poll: It is used for select/poll system call
*/
static unsigned int vpfe_poll(struct file *file, poll_table *wait)
{
struct vpfe_device *vpfe_dev = video_drvdata(file);
v4l2_dbg(1, debug, &vpfe_dev->v4l2_dev, "vpfe_poll\n");
if (vpfe_dev->started)
return videobuf_poll_stream(file,
&vpfe_dev->buffer_queue, wait);
return 0;
}
/* vpfe capture driver file operations */
static const struct v4l2_file_operations vpfe_fops = {
.owner = THIS_MODULE,
.open = vpfe_open,
.release = vpfe_release,
.unlocked_ioctl = video_ioctl2,
.mmap = vpfe_mmap,
.poll = vpfe_poll
};
/*
* vpfe_check_format()
* This function adjust the input pixel format as per hardware
* capabilities and update the same in pixfmt.
* Following algorithm used :-
*
* If given pixformat is not in the vpfe list of pix formats or not
* supported by the hardware, current value of pixformat in the device
* is used
* If given field is not supported, then current field is used. If field
* is different from current, then it is matched with that from sub device.
* Minimum height is 2 lines for interlaced or tb field and 1 line for
* progressive. Maximum height is clamped to active active lines of scan
* Minimum width is 32 bytes in memory and width is clamped to active
* pixels of scan.
* bytesperline is a multiple of 32.
*/
static const struct vpfe_pixel_format *
vpfe_check_format(struct vpfe_device *vpfe_dev,
struct v4l2_pix_format *pixfmt)
{
u32 min_height = 1, min_width = 32, max_width, max_height;
const struct vpfe_pixel_format *vpfe_pix_fmt;
u32 pix;
int temp, found;
vpfe_pix_fmt = vpfe_lookup_pix_format(pixfmt->pixelformat);
if (NULL == vpfe_pix_fmt) {
/*
* use current pixel format in the vpfe device. We
* will find this pix format in the table
*/
pixfmt->pixelformat = vpfe_dev->fmt.fmt.pix.pixelformat;
vpfe_pix_fmt = vpfe_lookup_pix_format(pixfmt->pixelformat);
}
/* check if hw supports it */
temp = 0;
found = 0;
while (ccdc_dev->hw_ops.enum_pix(&pix, temp) >= 0) {
if (vpfe_pix_fmt->fmtdesc.pixelformat == pix) {
found = 1;
break;
}
temp++;
}
if (!found) {
/* use current pixel format */
pixfmt->pixelformat = vpfe_dev->fmt.fmt.pix.pixelformat;
/*
* Since this is currently used in the vpfe device, we
* will find this pix format in the table
*/
vpfe_pix_fmt = vpfe_lookup_pix_format(pixfmt->pixelformat);
}
/* check what field format is supported */
if (pixfmt->field == V4L2_FIELD_ANY) {
/* if field is any, use current value as default */
pixfmt->field = vpfe_dev->fmt.fmt.pix.field;
}
/*
* if field is not same as current field in the vpfe device
* try matching the field with the sub device field
*/
if (vpfe_dev->fmt.fmt.pix.field != pixfmt->field) {
/*
* If field value is not in the supported fields, use current
* field used in the device as default
*/
switch (pixfmt->field) {
case V4L2_FIELD_INTERLACED:
case V4L2_FIELD_SEQ_TB:
/* if sub device is supporting progressive, use that */
if (!vpfe_dev->std_info.frame_format)
pixfmt->field = V4L2_FIELD_NONE;
break;
case V4L2_FIELD_NONE:
if (vpfe_dev->std_info.frame_format)
pixfmt->field = V4L2_FIELD_INTERLACED;
break;
default:
/* use current field as default */
pixfmt->field = vpfe_dev->fmt.fmt.pix.field;
break;
}
}
/* Now adjust image resolutions supported */
if (pixfmt->field == V4L2_FIELD_INTERLACED ||
pixfmt->field == V4L2_FIELD_SEQ_TB)
min_height = 2;
max_width = vpfe_dev->std_info.active_pixels;
max_height = vpfe_dev->std_info.active_lines;
min_width /= vpfe_pix_fmt->bpp;
v4l2_info(&vpfe_dev->v4l2_dev, "width = %d, height = %d, bpp = %d\n",
pixfmt->width, pixfmt->height, vpfe_pix_fmt->bpp);
pixfmt->width = clamp((pixfmt->width), min_width, max_width);
pixfmt->height = clamp((pixfmt->height), min_height, max_height);
/* If interlaced, adjust height to be a multiple of 2 */
if (pixfmt->field == V4L2_FIELD_INTERLACED)
pixfmt->height &= (~1);
/*
* recalculate bytesperline and sizeimage since width
* and height might have changed
*/
pixfmt->bytesperline = (((pixfmt->width * vpfe_pix_fmt->bpp) + 31)
& ~31);
if (pixfmt->pixelformat == V4L2_PIX_FMT_NV12)
pixfmt->sizeimage =
pixfmt->bytesperline * pixfmt->height +
((pixfmt->bytesperline * pixfmt->height) >> 1);
else
pixfmt->sizeimage = pixfmt->bytesperline * pixfmt->height;
v4l2_info(&vpfe_dev->v4l2_dev, "adjusted width = %d, height ="
" %d, bpp = %d, bytesperline = %d, sizeimage = %d\n",
pixfmt->width, pixfmt->height, vpfe_pix_fmt->bpp,
pixfmt->bytesperline, pixfmt->sizeimage);
return vpfe_pix_fmt;
}
static int vpfe_querycap(struct file *file, void *priv,
struct v4l2_capability *cap)
{
struct vpfe_device *vpfe_dev = video_drvdata(file);
v4l2_dbg(1, debug, &vpfe_dev->v4l2_dev, "vpfe_querycap\n");
cap->version = VPFE_CAPTURE_VERSION_CODE;
cap->capabilities = V4L2_CAP_VIDEO_CAPTURE | V4L2_CAP_STREAMING;
strlcpy(cap->driver, CAPTURE_DRV_NAME, sizeof(cap->driver));
strlcpy(cap->bus_info, "VPFE", sizeof(cap->bus_info));
strlcpy(cap->card, vpfe_dev->cfg->card_name, sizeof(cap->card));
return 0;
}
static int vpfe_g_fmt_vid_cap(struct file *file, void *priv,
struct v4l2_format *fmt)
{
struct vpfe_device *vpfe_dev = video_drvdata(file);
int ret = 0;
v4l2_dbg(1, debug, &vpfe_dev->v4l2_dev, "vpfe_g_fmt_vid_cap\n");
/* Fill in the information about format */
*fmt = vpfe_dev->fmt;
return ret;
}
static int vpfe_enum_fmt_vid_cap(struct file *file, void *priv,
struct v4l2_fmtdesc *fmt)
{
struct vpfe_device *vpfe_dev = video_drvdata(file);
const struct vpfe_pixel_format *pix_fmt;
int temp_index;
u32 pix;
v4l2_dbg(1, debug, &vpfe_dev->v4l2_dev, "vpfe_enum_fmt_vid_cap\n");
if (ccdc_dev->hw_ops.enum_pix(&pix, fmt->index) < 0)
return -EINVAL;
/* Fill in the information about format */
pix_fmt = vpfe_lookup_pix_format(pix);
if (NULL != pix_fmt) {
temp_index = fmt->index;
*fmt = pix_fmt->fmtdesc;
fmt->index = temp_index;
return 0;
}
return -EINVAL;
}
static int vpfe_s_fmt_vid_cap(struct file *file, void *priv,
struct v4l2_format *fmt)
{
struct vpfe_device *vpfe_dev = video_drvdata(file);
const struct vpfe_pixel_format *pix_fmts;
int ret = 0;
v4l2_dbg(1, debug, &vpfe_dev->v4l2_dev, "vpfe_s_fmt_vid_cap\n");
/* If streaming is started, return error */
if (vpfe_dev->started) {
v4l2_err(&vpfe_dev->v4l2_dev, "Streaming is started\n");
return -EBUSY;
}
/* Check for valid frame format */
pix_fmts = vpfe_check_format(vpfe_dev, &fmt->fmt.pix);
if (NULL == pix_fmts)
return -EINVAL;
/* store the pixel format in the device object */
ret = mutex_lock_interruptible(&vpfe_dev->lock);
if (ret)
return ret;
/* First detach any IRQ if currently attached */
vpfe_detach_irq(vpfe_dev);
vpfe_dev->fmt = *fmt;
/* set image capture parameters in the ccdc */
ret = vpfe_config_ccdc_image_format(vpfe_dev);
mutex_unlock(&vpfe_dev->lock);
return ret;
}
static int vpfe_try_fmt_vid_cap(struct file *file, void *priv,
struct v4l2_format *f)
{
struct vpfe_device *vpfe_dev = video_drvdata(file);
const struct vpfe_pixel_format *pix_fmts;
v4l2_dbg(1, debug, &vpfe_dev->v4l2_dev, "vpfe_try_fmt_vid_cap\n");
pix_fmts = vpfe_check_format(vpfe_dev, &f->fmt.pix);
if (NULL == pix_fmts)
return -EINVAL;
return 0;
}
/*
* vpfe_get_subdev_input_index - Get subdev index and subdev input index for a
* given app input index
*/
static int vpfe_get_subdev_input_index(struct vpfe_device *vpfe_dev,
int *subdev_index,
int *subdev_input_index,
int app_input_index)
{
struct vpfe_config *cfg = vpfe_dev->cfg;
struct vpfe_subdev_info *sdinfo;
int i, j = 0;
for (i = 0; i < cfg->num_subdevs; i++) {
sdinfo = &cfg->sub_devs[i];
if (app_input_index < (j + sdinfo->num_inputs)) {
*subdev_index = i;
*subdev_input_index = app_input_index - j;
return 0;
}
j += sdinfo->num_inputs;
}
return -EINVAL;
}
/*
* vpfe_get_app_input - Get app input index for a given subdev input index
* driver stores the input index of the current sub device and translate it
* when application request the current input
*/
static int vpfe_get_app_input_index(struct vpfe_device *vpfe_dev,
int *app_input_index)
{
struct vpfe_config *cfg = vpfe_dev->cfg;
struct vpfe_subdev_info *sdinfo;
int i, j = 0;
for (i = 0; i < cfg->num_subdevs; i++) {
sdinfo = &cfg->sub_devs[i];
if (!strcmp(sdinfo->name, vpfe_dev->current_subdev->name)) {
if (vpfe_dev->current_input >= sdinfo->num_inputs)
return -1;
*app_input_index = j + vpfe_dev->current_input;
return 0;
}
j += sdinfo->num_inputs;
}
return -EINVAL;
}
static int vpfe_enum_input(struct file *file, void *priv,
struct v4l2_input *inp)
{
struct vpfe_device *vpfe_dev = video_drvdata(file);
struct vpfe_subdev_info *sdinfo;
int subdev, index ;
v4l2_dbg(1, debug, &vpfe_dev->v4l2_dev, "vpfe_enum_input\n");
if (vpfe_get_subdev_input_index(vpfe_dev,
&subdev,
&index,
inp->index) < 0) {
v4l2_err(&vpfe_dev->v4l2_dev, "input information not found"
" for the subdev\n");
return -EINVAL;
}
sdinfo = &vpfe_dev->cfg->sub_devs[subdev];
memcpy(inp, &sdinfo->inputs[index], sizeof(struct v4l2_input));
return 0;
}
static int vpfe_g_input(struct file *file, void *priv, unsigned int *index)
{
struct vpfe_device *vpfe_dev = video_drvdata(file);
v4l2_dbg(1, debug, &vpfe_dev->v4l2_dev, "vpfe_g_input\n");
return vpfe_get_app_input_index(vpfe_dev, index);
}
static int vpfe_s_input(struct file *file, void *priv, unsigned int index)
{
struct vpfe_device *vpfe_dev = video_drvdata(file);
struct v4l2_subdev *sd;
struct vpfe_subdev_info *sdinfo;
int subdev_index, inp_index;
struct vpfe_route *route;
u32 input = 0, output = 0;
int ret = -EINVAL;
v4l2_dbg(1, debug, &vpfe_dev->v4l2_dev, "vpfe_s_input\n");
ret = mutex_lock_interruptible(&vpfe_dev->lock);
if (ret)
return ret;
/*
* If streaming is started return device busy
* error
*/
if (vpfe_dev->started) {
v4l2_err(&vpfe_dev->v4l2_dev, "Streaming is on\n");
ret = -EBUSY;
goto unlock_out;
}
ret = vpfe_get_subdev_input_index(vpfe_dev,
&subdev_index,
&inp_index,
index);
if (ret < 0) {
v4l2_err(&vpfe_dev->v4l2_dev, "invalid input index\n");
goto unlock_out;
}
sdinfo = &vpfe_dev->cfg->sub_devs[subdev_index];
sd = vpfe_dev->sd[subdev_index];
route = &sdinfo->routes[inp_index];
if (route && sdinfo->can_route) {
input = route->input;
output = route->output;
}
if (sd)
ret = v4l2_subdev_call(sd, video, s_routing, input, output, 0);
if (ret) {
v4l2_err(&vpfe_dev->v4l2_dev,
"vpfe_doioctl:error in setting input in decoder\n");
ret = -EINVAL;
goto unlock_out;
}
vpfe_dev->current_subdev = sdinfo;
if (sd)
vpfe_dev->v4l2_dev.ctrl_handler = sd->ctrl_handler;
vpfe_dev->current_input = index;
vpfe_dev->std_index = 0;
/* set the bus/interface parameter for the sub device in ccdc */
ret = ccdc_dev->hw_ops.set_hw_if_params(&sdinfo->ccdc_if_params);
if (ret)
goto unlock_out;
/* set the default image parameters in the device */
ret = vpfe_config_image_format(vpfe_dev,
vpfe_standards[vpfe_dev->std_index].std_id);
unlock_out:
mutex_unlock(&vpfe_dev->lock);
return ret;
}
static int vpfe_querystd(struct file *file, void *priv, v4l2_std_id *std_id)
{
struct vpfe_device *vpfe_dev = video_drvdata(file);
struct vpfe_subdev_info *sdinfo;
int ret = 0;
v4l2_dbg(1, debug, &vpfe_dev->v4l2_dev, "vpfe_querystd\n");
ret = mutex_lock_interruptible(&vpfe_dev->lock);
sdinfo = vpfe_dev->current_subdev;
if (ret)
return ret;
/* Call querystd function of decoder device */
ret = v4l2_device_call_until_err(&vpfe_dev->v4l2_dev, sdinfo->grp_id,
video, querystd, std_id);
mutex_unlock(&vpfe_dev->lock);
return ret;
}
static int vpfe_s_std(struct file *file, void *priv, v4l2_std_id std_id)
{
struct vpfe_device *vpfe_dev = video_drvdata(file);
struct vpfe_subdev_info *sdinfo;
int ret = 0;
v4l2_dbg(1, debug, &vpfe_dev->v4l2_dev, "vpfe_s_std\n");
/* Call decoder driver function to set the standard */
ret = mutex_lock_interruptible(&vpfe_dev->lock);
if (ret)
return ret;
sdinfo = vpfe_dev->current_subdev;
/* If streaming is started, return device busy error */
if (vpfe_dev->started) {
v4l2_err(&vpfe_dev->v4l2_dev, "streaming is started\n");
ret = -EBUSY;
goto unlock_out;
}
ret = v4l2_device_call_until_err(&vpfe_dev->v4l2_dev, sdinfo->grp_id,
core, s_std, std_id);
if (ret < 0) {
v4l2_err(&vpfe_dev->v4l2_dev, "Failed to set standard\n");
goto unlock_out;
}
ret = vpfe_config_image_format(vpfe_dev, std_id);
unlock_out:
mutex_unlock(&vpfe_dev->lock);
return ret;
}
static int vpfe_g_std(struct file *file, void *priv, v4l2_std_id *std_id)
{
struct vpfe_device *vpfe_dev = video_drvdata(file);
v4l2_dbg(1, debug, &vpfe_dev->v4l2_dev, "vpfe_g_std\n");
*std_id = vpfe_standards[vpfe_dev->std_index].std_id;
return 0;
}
/*
* Videobuf operations
*/
static int vpfe_videobuf_setup(struct videobuf_queue *vq,
unsigned int *count,
unsigned int *size)
{
struct vpfe_fh *fh = vq->priv_data;
struct vpfe_device *vpfe_dev = fh->vpfe_dev;
v4l2_dbg(1, debug, &vpfe_dev->v4l2_dev, "vpfe_buffer_setup\n");
*size = vpfe_dev->fmt.fmt.pix.sizeimage;
if (vpfe_dev->memory == V4L2_MEMORY_MMAP &&
vpfe_dev->fmt.fmt.pix.sizeimage > config_params.device_bufsize)
*size = config_params.device_bufsize;
if (*count < config_params.min_numbuffers)
*count = config_params.min_numbuffers;
v4l2_dbg(1, debug, &vpfe_dev->v4l2_dev,
"count=%d, size=%d\n", *count, *size);
return 0;
}
static int vpfe_videobuf_prepare(struct videobuf_queue *vq,
struct videobuf_buffer *vb,
enum v4l2_field field)
{
struct vpfe_fh *fh = vq->priv_data;
struct vpfe_device *vpfe_dev = fh->vpfe_dev;
unsigned long addr;
int ret;
v4l2_dbg(1, debug, &vpfe_dev->v4l2_dev, "vpfe_buffer_prepare\n");
/* If buffer is not initialized, initialize it */
if (VIDEOBUF_NEEDS_INIT == vb->state) {
vb->width = vpfe_dev->fmt.fmt.pix.width;
vb->height = vpfe_dev->fmt.fmt.pix.height;
vb->size = vpfe_dev->fmt.fmt.pix.sizeimage;
vb->field = field;
ret = videobuf_iolock(vq, vb, NULL);
if (ret < 0)
return ret;
addr = videobuf_to_dma_contig(vb);
/* Make sure user addresses are aligned to 32 bytes */
if (!ALIGN(addr, 32))
return -EINVAL;
vb->state = VIDEOBUF_PREPARED;
}
return 0;
}
static void vpfe_videobuf_queue(struct videobuf_queue *vq,
struct videobuf_buffer *vb)
{
/* Get the file handle object and device object */
struct vpfe_fh *fh = vq->priv_data;
struct vpfe_device *vpfe_dev = fh->vpfe_dev;
unsigned long flags;
v4l2_dbg(1, debug, &vpfe_dev->v4l2_dev, "vpfe_buffer_queue\n");
/* add the buffer to the DMA queue */
spin_lock_irqsave(&vpfe_dev->dma_queue_lock, flags);
list_add_tail(&vb->queue, &vpfe_dev->dma_queue);
spin_unlock_irqrestore(&vpfe_dev->dma_queue_lock, flags);
/* Change state of the buffer */
vb->state = VIDEOBUF_QUEUED;
}
static void vpfe_videobuf_release(struct videobuf_queue *vq,
struct videobuf_buffer *vb)
{
struct vpfe_fh *fh = vq->priv_data;
struct vpfe_device *vpfe_dev = fh->vpfe_dev;
unsigned long flags;
v4l2_dbg(1, debug, &vpfe_dev->v4l2_dev, "vpfe_videobuf_release\n");
/*
* We need to flush the buffer from the dma queue since
* they are de-allocated
*/
spin_lock_irqsave(&vpfe_dev->dma_queue_lock, flags);
INIT_LIST_HEAD(&vpfe_dev->dma_queue);
spin_unlock_irqrestore(&vpfe_dev->dma_queue_lock, flags);
videobuf_dma_contig_free(vq, vb);
vb->state = VIDEOBUF_NEEDS_INIT;
}
static struct videobuf_queue_ops vpfe_videobuf_qops = {
.buf_setup = vpfe_videobuf_setup,
.buf_prepare = vpfe_videobuf_prepare,
.buf_queue = vpfe_videobuf_queue,
.buf_release = vpfe_videobuf_release,
};
/*
* vpfe_reqbufs. currently support REQBUF only once opening
* the device.
*/
static int vpfe_reqbufs(struct file *file, void *priv,
struct v4l2_requestbuffers *req_buf)
{
struct vpfe_device *vpfe_dev = video_drvdata(file);
struct vpfe_fh *fh = file->private_data;
int ret = 0;
v4l2_dbg(1, debug, &vpfe_dev->v4l2_dev, "vpfe_reqbufs\n");
if (V4L2_BUF_TYPE_VIDEO_CAPTURE != req_buf->type) {
v4l2_err(&vpfe_dev->v4l2_dev, "Invalid buffer type\n");
return -EINVAL;
}
ret = mutex_lock_interruptible(&vpfe_dev->lock);
if (ret)
return ret;
if (vpfe_dev->io_usrs != 0) {
v4l2_err(&vpfe_dev->v4l2_dev, "Only one IO user allowed\n");
ret = -EBUSY;
goto unlock_out;
}
vpfe_dev->memory = req_buf->memory;
videobuf_queue_dma_contig_init(&vpfe_dev->buffer_queue,
&vpfe_videobuf_qops,
vpfe_dev->pdev,
&vpfe_dev->irqlock,
req_buf->type,
vpfe_dev->fmt.fmt.pix.field,
sizeof(struct videobuf_buffer),
fh, NULL);
fh->io_allowed = 1;
vpfe_dev->io_usrs = 1;
INIT_LIST_HEAD(&vpfe_dev->dma_queue);
ret = videobuf_reqbufs(&vpfe_dev->buffer_queue, req_buf);
unlock_out:
mutex_unlock(&vpfe_dev->lock);
return ret;
}
static int vpfe_querybuf(struct file *file, void *priv,
struct v4l2_buffer *buf)
{
struct vpfe_device *vpfe_dev = video_drvdata(file);
v4l2_dbg(1, debug, &vpfe_dev->v4l2_dev, "vpfe_querybuf\n");
if (V4L2_BUF_TYPE_VIDEO_CAPTURE != buf->type) {
v4l2_err(&vpfe_dev->v4l2_dev, "Invalid buf type\n");
return -EINVAL;
}
if (vpfe_dev->memory != V4L2_MEMORY_MMAP) {
v4l2_err(&vpfe_dev->v4l2_dev, "Invalid memory\n");
return -EINVAL;
}
/* Call videobuf_querybuf to get information */
return videobuf_querybuf(&vpfe_dev->buffer_queue, buf);
}
static int vpfe_qbuf(struct file *file, void *priv,
struct v4l2_buffer *p)
{
struct vpfe_device *vpfe_dev = video_drvdata(file);
struct vpfe_fh *fh = file->private_data;
v4l2_dbg(1, debug, &vpfe_dev->v4l2_dev, "vpfe_qbuf\n");
if (V4L2_BUF_TYPE_VIDEO_CAPTURE != p->type) {
v4l2_err(&vpfe_dev->v4l2_dev, "Invalid buf type\n");
return -EINVAL;
}
/*
* If this file handle is not allowed to do IO,
* return error
*/
if (!fh->io_allowed) {
v4l2_err(&vpfe_dev->v4l2_dev, "fh->io_allowed\n");
return -EACCES;
}
return videobuf_qbuf(&vpfe_dev->buffer_queue, p);
}
static int vpfe_dqbuf(struct file *file, void *priv,
struct v4l2_buffer *buf)
{
struct vpfe_device *vpfe_dev = video_drvdata(file);
v4l2_dbg(1, debug, &vpfe_dev->v4l2_dev, "vpfe_dqbuf\n");
if (V4L2_BUF_TYPE_VIDEO_CAPTURE != buf->type) {
v4l2_err(&vpfe_dev->v4l2_dev, "Invalid buf type\n");
return -EINVAL;
}
return videobuf_dqbuf(&vpfe_dev->buffer_queue,
buf, file->f_flags & O_NONBLOCK);
}
/*
* vpfe_calculate_offsets : This function calculates buffers offset
* for top and bottom field
*/
static void vpfe_calculate_offsets(struct vpfe_device *vpfe_dev)
{
struct v4l2_rect image_win;
v4l2_dbg(1, debug, &vpfe_dev->v4l2_dev, "vpfe_calculate_offsets\n");
ccdc_dev->hw_ops.get_image_window(&image_win);
vpfe_dev->field_off = image_win.height * image_win.width;
}
/* vpfe_start_ccdc_capture: start streaming in ccdc/isif */
static void vpfe_start_ccdc_capture(struct vpfe_device *vpfe_dev)
{
ccdc_dev->hw_ops.enable(1);
if (ccdc_dev->hw_ops.enable_out_to_sdram)
ccdc_dev->hw_ops.enable_out_to_sdram(1);
vpfe_dev->started = 1;
}
/*
* vpfe_streamon. Assume the DMA queue is not empty.
* application is expected to call QBUF before calling
* this ioctl. If not, driver returns error
*/
static int vpfe_streamon(struct file *file, void *priv,
enum v4l2_buf_type buf_type)
{
struct vpfe_device *vpfe_dev = video_drvdata(file);
struct vpfe_fh *fh = file->private_data;
struct vpfe_subdev_info *sdinfo;
unsigned long addr;
int ret = 0;
v4l2_dbg(1, debug, &vpfe_dev->v4l2_dev, "vpfe_streamon\n");
if (V4L2_BUF_TYPE_VIDEO_CAPTURE != buf_type) {
v4l2_err(&vpfe_dev->v4l2_dev, "Invalid buf type\n");
return -EINVAL;
}
/* If file handle is not allowed IO, return error */
if (!fh->io_allowed) {
v4l2_err(&vpfe_dev->v4l2_dev, "fh->io_allowed\n");
return -EACCES;
}
sdinfo = vpfe_dev->current_subdev;
ret = v4l2_device_call_until_err(&vpfe_dev->v4l2_dev, sdinfo->grp_id,
video, s_stream, 1);
if (ret && (ret != -ENOIOCTLCMD)) {
v4l2_err(&vpfe_dev->v4l2_dev, "stream on failed in subdev\n");
return -EINVAL;
}
/* If buffer queue is empty, return error */
if (list_empty(&vpfe_dev->buffer_queue.stream)) {
v4l2_err(&vpfe_dev->v4l2_dev, "buffer queue is empty\n");
return -EIO;
}
/* Call videobuf_streamon to start streaming * in videobuf */
ret = videobuf_streamon(&vpfe_dev->buffer_queue);
if (ret)
return ret;
ret = mutex_lock_interruptible(&vpfe_dev->lock);
if (ret)
goto streamoff;
/* Get the next frame from the buffer queue */
vpfe_dev->next_frm = list_entry(vpfe_dev->dma_queue.next,
struct videobuf_buffer, queue);
vpfe_dev->cur_frm = vpfe_dev->next_frm;
/* Remove buffer from the buffer queue */
list_del(&vpfe_dev->cur_frm->queue);
/* Mark state of the current frame to active */
vpfe_dev->cur_frm->state = VIDEOBUF_ACTIVE;
/* Initialize field_id and started member */
vpfe_dev->field_id = 0;
addr = videobuf_to_dma_contig(vpfe_dev->cur_frm);
/* Calculate field offset */
vpfe_calculate_offsets(vpfe_dev);
if (vpfe_attach_irq(vpfe_dev) < 0) {
v4l2_err(&vpfe_dev->v4l2_dev,
"Error in attaching interrupt handle\n");
ret = -EFAULT;
goto unlock_out;
}
if (ccdc_dev->hw_ops.configure() < 0) {
v4l2_err(&vpfe_dev->v4l2_dev,
"Error in configuring ccdc\n");
ret = -EINVAL;
goto unlock_out;
}
ccdc_dev->hw_ops.setfbaddr((unsigned long)(addr));
vpfe_start_ccdc_capture(vpfe_dev);
mutex_unlock(&vpfe_dev->lock);
return ret;
unlock_out:
mutex_unlock(&vpfe_dev->lock);
streamoff:
ret = videobuf_streamoff(&vpfe_dev->buffer_queue);
return ret;
}
static int vpfe_streamoff(struct file *file, void *priv,
enum v4l2_buf_type buf_type)
{
struct vpfe_device *vpfe_dev = video_drvdata(file);
struct vpfe_fh *fh = file->private_data;
struct vpfe_subdev_info *sdinfo;
int ret = 0;
v4l2_dbg(1, debug, &vpfe_dev->v4l2_dev, "vpfe_streamoff\n");
if (V4L2_BUF_TYPE_VIDEO_CAPTURE != buf_type) {
v4l2_err(&vpfe_dev->v4l2_dev, "Invalid buf type\n");
return -EINVAL;
}
/* If io is allowed for this file handle, return error */
if (!fh->io_allowed) {
v4l2_err(&vpfe_dev->v4l2_dev, "fh->io_allowed\n");
return -EACCES;
}
/* If streaming is not started, return error */
if (!vpfe_dev->started) {
v4l2_err(&vpfe_dev->v4l2_dev, "device started\n");
return -EINVAL;
}
ret = mutex_lock_interruptible(&vpfe_dev->lock);
if (ret)
return ret;
vpfe_stop_ccdc_capture(vpfe_dev);
vpfe_detach_irq(vpfe_dev);
sdinfo = vpfe_dev->current_subdev;
ret = v4l2_device_call_until_err(&vpfe_dev->v4l2_dev, sdinfo->grp_id,
video, s_stream, 0);
if (ret && (ret != -ENOIOCTLCMD))
v4l2_err(&vpfe_dev->v4l2_dev, "stream off failed in subdev\n");
ret = videobuf_streamoff(&vpfe_dev->buffer_queue);
mutex_unlock(&vpfe_dev->lock);
return ret;
}
static int vpfe_cropcap(struct file *file, void *priv,
struct v4l2_cropcap *crop)
{
struct vpfe_device *vpfe_dev = video_drvdata(file);
v4l2_dbg(1, debug, &vpfe_dev->v4l2_dev, "vpfe_cropcap\n");
if (vpfe_dev->std_index >= ARRAY_SIZE(vpfe_standards))
return -EINVAL;
memset(crop, 0, sizeof(struct v4l2_cropcap));
crop->type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
crop->bounds.width = crop->defrect.width =
vpfe_standards[vpfe_dev->std_index].width;
crop->bounds.height = crop->defrect.height =
vpfe_standards[vpfe_dev->std_index].height;
crop->pixelaspect = vpfe_standards[vpfe_dev->std_index].pixelaspect;
return 0;
}
static int vpfe_g_crop(struct file *file, void *priv,
struct v4l2_crop *crop)
{
struct vpfe_device *vpfe_dev = video_drvdata(file);
v4l2_dbg(1, debug, &vpfe_dev->v4l2_dev, "vpfe_g_crop\n");
crop->c = vpfe_dev->crop;
return 0;
}
static int vpfe_s_crop(struct file *file, void *priv,
const struct v4l2_crop *crop)
{
struct vpfe_device *vpfe_dev = video_drvdata(file);
struct v4l2_rect rect = crop->c;
int ret = 0;
v4l2_dbg(1, debug, &vpfe_dev->v4l2_dev, "vpfe_s_crop\n");
if (vpfe_dev->started) {
/* make sure streaming is not started */
v4l2_err(&vpfe_dev->v4l2_dev,
"Cannot change crop when streaming is ON\n");
return -EBUSY;
}
ret = mutex_lock_interruptible(&vpfe_dev->lock);
if (ret)
return ret;
if (rect.top < 0 || rect.left < 0) {
v4l2_err(&vpfe_dev->v4l2_dev,
"doesn't support negative values for top & left\n");
ret = -EINVAL;
goto unlock_out;
}
/* adjust the width to 16 pixel boundary */
rect.width = ((rect.width + 15) & ~0xf);
/* make sure parameters are valid */
if ((rect.left + rect.width >
vpfe_dev->std_info.active_pixels) ||
(rect.top + rect.height >
vpfe_dev->std_info.active_lines)) {
v4l2_err(&vpfe_dev->v4l2_dev, "Error in S_CROP params\n");
ret = -EINVAL;
goto unlock_out;
}
ccdc_dev->hw_ops.set_image_window(&rect);
vpfe_dev->fmt.fmt.pix.width = rect.width;
vpfe_dev->fmt.fmt.pix.height = rect.height;
vpfe_dev->fmt.fmt.pix.bytesperline =
ccdc_dev->hw_ops.get_line_length();
vpfe_dev->fmt.fmt.pix.sizeimage =
vpfe_dev->fmt.fmt.pix.bytesperline *
vpfe_dev->fmt.fmt.pix.height;
vpfe_dev->crop = rect;
unlock_out:
mutex_unlock(&vpfe_dev->lock);
return ret;
}
static long vpfe_param_handler(struct file *file, void *priv,
bool valid_prio, unsigned int cmd, void *param)
{
struct vpfe_device *vpfe_dev = video_drvdata(file);
int ret = 0;
v4l2_dbg(2, debug, &vpfe_dev->v4l2_dev, "vpfe_param_handler\n");
if (vpfe_dev->started) {
/* only allowed if streaming is not started */
v4l2_dbg(1, debug, &vpfe_dev->v4l2_dev,
"device already started\n");
return -EBUSY;
}
ret = mutex_lock_interruptible(&vpfe_dev->lock);
if (ret)
return ret;
switch (cmd) {
case VPFE_CMD_S_CCDC_RAW_PARAMS:
ret = -EINVAL;
v4l2_warn(&vpfe_dev->v4l2_dev,
"VPFE_CMD_S_CCDC_RAW_PARAMS not supported\n");
break;
default:
ret = -ENOTTY;
}
unlock_out:
mutex_unlock(&vpfe_dev->lock);
return ret;
}
/* vpfe capture ioctl operations */
static const struct v4l2_ioctl_ops vpfe_ioctl_ops = {
.vidioc_querycap = vpfe_querycap,
.vidioc_g_fmt_vid_cap = vpfe_g_fmt_vid_cap,
.vidioc_enum_fmt_vid_cap = vpfe_enum_fmt_vid_cap,
.vidioc_s_fmt_vid_cap = vpfe_s_fmt_vid_cap,
.vidioc_try_fmt_vid_cap = vpfe_try_fmt_vid_cap,
.vidioc_enum_input = vpfe_enum_input,
.vidioc_g_input = vpfe_g_input,
.vidioc_s_input = vpfe_s_input,
.vidioc_querystd = vpfe_querystd,
.vidioc_s_std = vpfe_s_std,
.vidioc_g_std = vpfe_g_std,
.vidioc_reqbufs = vpfe_reqbufs,
.vidioc_querybuf = vpfe_querybuf,
.vidioc_qbuf = vpfe_qbuf,
.vidioc_dqbuf = vpfe_dqbuf,
.vidioc_streamon = vpfe_streamon,
.vidioc_streamoff = vpfe_streamoff,
.vidioc_cropcap = vpfe_cropcap,
.vidioc_g_crop = vpfe_g_crop,
.vidioc_s_crop = vpfe_s_crop,
.vidioc_default = vpfe_param_handler,
};
static struct vpfe_device *vpfe_initialize(void)
{
struct vpfe_device *vpfe_dev;
/* Default number of buffers should be 3 */
if ((numbuffers > 0) &&
(numbuffers < config_params.min_numbuffers))
numbuffers = config_params.min_numbuffers;
/*
* Set buffer size to min buffers size if invalid buffer size is
* given
*/
if (bufsize < config_params.min_bufsize)
bufsize = config_params.min_bufsize;
config_params.numbuffers = numbuffers;
if (numbuffers)
config_params.device_bufsize = bufsize;
/* Allocate memory for device objects */
vpfe_dev = kzalloc(sizeof(*vpfe_dev), GFP_KERNEL);
return vpfe_dev;
}
/*
* vpfe_probe : This function creates device entries by register
* itself to the V4L2 driver and initializes fields of each
* device objects
*/
static int vpfe_probe(struct platform_device *pdev)
{
struct vpfe_subdev_info *sdinfo;
struct vpfe_config *vpfe_cfg;
struct resource *res1;
struct vpfe_device *vpfe_dev;
struct i2c_adapter *i2c_adap;
struct video_device *vfd;
int ret = -ENOMEM, i, j;
int num_subdevs = 0;
/* Get the pointer to the device object */
vpfe_dev = vpfe_initialize();
if (!vpfe_dev) {
v4l2_err(pdev->dev.driver,
"Failed to allocate memory for vpfe_dev\n");
return ret;
}
vpfe_dev->pdev = &pdev->dev;
if (NULL == pdev->dev.platform_data) {
v4l2_err(pdev->dev.driver, "Unable to get vpfe config\n");
ret = -ENODEV;
goto probe_free_dev_mem;
}
vpfe_cfg = pdev->dev.platform_data;
vpfe_dev->cfg = vpfe_cfg;
if (NULL == vpfe_cfg->ccdc ||
NULL == vpfe_cfg->card_name ||
NULL == vpfe_cfg->sub_devs) {
v4l2_err(pdev->dev.driver, "null ptr in vpfe_cfg\n");
ret = -ENOENT;
goto probe_free_dev_mem;
}
/* Allocate memory for ccdc configuration */
ccdc_cfg = kmalloc(sizeof(struct ccdc_config), GFP_KERNEL);
if (NULL == ccdc_cfg) {
v4l2_err(pdev->dev.driver,
"Memory allocation failed for ccdc_cfg\n");
goto probe_free_dev_mem;
}
mutex_lock(&ccdc_lock);
strncpy(ccdc_cfg->name, vpfe_cfg->ccdc, 32);
/* Get VINT0 irq resource */
res1 = platform_get_resource(pdev, IORESOURCE_IRQ, 0);
if (!res1) {
v4l2_err(pdev->dev.driver,
"Unable to get interrupt for VINT0\n");
ret = -ENODEV;
goto probe_free_ccdc_cfg_mem;
}
vpfe_dev->ccdc_irq0 = res1->start;
/* Get VINT1 irq resource */
res1 = platform_get_resource(pdev, IORESOURCE_IRQ, 1);
if (!res1) {
v4l2_err(pdev->dev.driver,
"Unable to get interrupt for VINT1\n");
ret = -ENODEV;
goto probe_free_ccdc_cfg_mem;
}
vpfe_dev->ccdc_irq1 = res1->start;
ret = request_irq(vpfe_dev->ccdc_irq0, vpfe_isr, IRQF_DISABLED,
"vpfe_capture0", vpfe_dev);
if (0 != ret) {
v4l2_err(pdev->dev.driver, "Unable to request interrupt\n");
goto probe_free_ccdc_cfg_mem;
}
/* Allocate memory for video device */
vfd = video_device_alloc();
if (NULL == vfd) {
ret = -ENOMEM;
v4l2_err(pdev->dev.driver, "Unable to alloc video device\n");
goto probe_out_release_irq;
}
/* Initialize field of video device */
vfd->release = video_device_release;
vfd->fops = &vpfe_fops;
vfd->ioctl_ops = &vpfe_ioctl_ops;
vfd->tvnorms = 0;
vfd->v4l2_dev = &vpfe_dev->v4l2_dev;
snprintf(vfd->name, sizeof(vfd->name),
"%s_V%d.%d.%d",
CAPTURE_DRV_NAME,
(VPFE_CAPTURE_VERSION_CODE >> 16) & 0xff,
(VPFE_CAPTURE_VERSION_CODE >> 8) & 0xff,
(VPFE_CAPTURE_VERSION_CODE) & 0xff);
/* Set video_dev to the video device */
vpfe_dev->video_dev = vfd;
ret = v4l2_device_register(&pdev->dev, &vpfe_dev->v4l2_dev);
if (ret) {
v4l2_err(pdev->dev.driver,
"Unable to register v4l2 device.\n");
goto probe_out_video_release;
}
v4l2_info(&vpfe_dev->v4l2_dev, "v4l2 device registered\n");
spin_lock_init(&vpfe_dev->irqlock);
spin_lock_init(&vpfe_dev->dma_queue_lock);
mutex_init(&vpfe_dev->lock);
/* Initialize field of the device objects */
vpfe_dev->numbuffers = config_params.numbuffers;
/* Initialize prio member of device object */
v4l2_prio_init(&vpfe_dev->prio);
/* register video device */
v4l2_dbg(1, debug, &vpfe_dev->v4l2_dev,
"trying to register vpfe device.\n");
v4l2_dbg(1, debug, &vpfe_dev->v4l2_dev,
"video_dev=%x\n", (int)&vpfe_dev->video_dev);
vpfe_dev->fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
ret = video_register_device(vpfe_dev->video_dev,
VFL_TYPE_GRABBER, -1);
if (ret) {
v4l2_err(pdev->dev.driver,
"Unable to register video device.\n");
goto probe_out_v4l2_unregister;
}
v4l2_info(&vpfe_dev->v4l2_dev, "video device registered\n");
/* set the driver data in platform device */
platform_set_drvdata(pdev, vpfe_dev);
/* set driver private data */
video_set_drvdata(vpfe_dev->video_dev, vpfe_dev);
i2c_adap = i2c_get_adapter(vpfe_cfg->i2c_adapter_id);
num_subdevs = vpfe_cfg->num_subdevs;
vpfe_dev->sd = kmalloc(sizeof(struct v4l2_subdev *) * num_subdevs,
GFP_KERNEL);
if (NULL == vpfe_dev->sd) {
v4l2_err(&vpfe_dev->v4l2_dev,
"unable to allocate memory for subdevice pointers\n");
ret = -ENOMEM;
goto probe_out_video_unregister;
}
for (i = 0; i < num_subdevs; i++) {
struct v4l2_input *inps;
sdinfo = &vpfe_cfg->sub_devs[i];
/* Load up the subdevice */
vpfe_dev->sd[i] =
v4l2_i2c_new_subdev_board(&vpfe_dev->v4l2_dev,
i2c_adap,
&sdinfo->board_info,
NULL);
if (vpfe_dev->sd[i]) {
v4l2_info(&vpfe_dev->v4l2_dev,
"v4l2 sub device %s registered\n",
sdinfo->name);
vpfe_dev->sd[i]->grp_id = sdinfo->grp_id;
/* update tvnorms from the sub devices */
for (j = 0; j < sdinfo->num_inputs; j++) {
inps = &sdinfo->inputs[j];
vfd->tvnorms |= inps->std;
}
} else {
v4l2_info(&vpfe_dev->v4l2_dev,
"v4l2 sub device %s register fails\n",
sdinfo->name);
goto probe_sd_out;
}
}
/* set first sub device as current one */
vpfe_dev->current_subdev = &vpfe_cfg->sub_devs[0];
vpfe_dev->v4l2_dev.ctrl_handler = vpfe_dev->sd[0]->ctrl_handler;
/* We have at least one sub device to work with */
mutex_unlock(&ccdc_lock);
return 0;
probe_sd_out:
kfree(vpfe_dev->sd);
probe_out_video_unregister:
video_unregister_device(vpfe_dev->video_dev);
probe_out_v4l2_unregister:
v4l2_device_unregister(&vpfe_dev->v4l2_dev);
probe_out_video_release:
if (!video_is_registered(vpfe_dev->video_dev))
video_device_release(vpfe_dev->video_dev);
probe_out_release_irq:
free_irq(vpfe_dev->ccdc_irq0, vpfe_dev);
probe_free_ccdc_cfg_mem:
kfree(ccdc_cfg);
mutex_unlock(&ccdc_lock);
probe_free_dev_mem:
kfree(vpfe_dev);
return ret;
}
/*
* vpfe_remove : It un-register device from V4L2 driver
*/
static int vpfe_remove(struct platform_device *pdev)
{
struct vpfe_device *vpfe_dev = platform_get_drvdata(pdev);
v4l2_info(pdev->dev.driver, "vpfe_remove\n");
free_irq(vpfe_dev->ccdc_irq0, vpfe_dev);
kfree(vpfe_dev->sd);
v4l2_device_unregister(&vpfe_dev->v4l2_dev);
video_unregister_device(vpfe_dev->video_dev);
kfree(vpfe_dev);
kfree(ccdc_cfg);
return 0;
}
static int vpfe_suspend(struct device *dev)
{
return 0;
}
static int vpfe_resume(struct device *dev)
{
return 0;
}
static const struct dev_pm_ops vpfe_dev_pm_ops = {
.suspend = vpfe_suspend,
.resume = vpfe_resume,
};
static struct platform_driver vpfe_driver = {
.driver = {
.name = CAPTURE_DRV_NAME,
.owner = THIS_MODULE,
.pm = &vpfe_dev_pm_ops,
},
.probe = vpfe_probe,
.remove = vpfe_remove,
};
module_platform_driver(vpfe_driver);
|
238651.c | #include "parser.h"
#include <assert.h>
#include <ctype.h>
#include <setjmp.h>
#include <stdio.h>
#include <string.h>
#include "ast.h"
#include "except.h"
#include "lexer.h"
#include "node.h"
#include "pool.h"
typedef struct {
node_t base;
char value[MAXTOK + 1];
} symbol_t;
static symbol_t g_pool[N_ELEMS];
pool_t g_symbol_pool = INIT_POOL(g_pool, N_ELEMS, symbol_t);
static ast_t * ParseExpr(lexer_t * const, const symbol_t *);
static ast_t * ParseVar(const char * const, const symbol_t * const);
static ast_t * ParseNum(const char *);
static ast_t * ParseSum(lexer_t * const, const symbol_t *);
static ast_t * ParseApp(lexer_t * const, const symbol_t *);
static ast_t * ParseAbs(lexer_t * const, const symbol_t *, int *);
static void
PushNewSymbol(const symbol_t ** scope, const char * const token)
{
symbol_t * symbol;
assert(scope);
assert(token);
symbol = Pool_Alloc(&g_symbol_pool);
strcpy(symbol->value, token);
Push(scope, symbol);
}
static void
Consume(lexer_t * const lexer)
{
int cnt;
switch (cnt = Lexer_NextToken(lexer)) {
case 0:
fprintf(stderr, "Unexpected end of input.\n");
/* fall-through */
case -1:
THROW;
default:
return;
}
}
static void
Match(lexer_t * const lexer, const tokenType_t type)
{
if (type != lexer->type) {
fprintf(stderr, "Unexpected token: %s.\n", lexer->token);
THROW;
}
}
static inline void
Expect(lexer_t * const lexer, const tokenType_t type)
{
Consume(lexer);
Match(lexer, type);
}
ast_t *
Parse(lexer_t * const lexer)
{
Consume(lexer);
return ParseExpr(lexer, NULL);
}
static ast_t *
ParseExpr(lexer_t * const lexer, const symbol_t *scope)
{
assert(lexer->type != LEX_NONE);
switch (lexer->type) {
case LEX_VAR:
return ParseVar(lexer->token, scope);
case LEX_NUM:
return ParseNum(lexer->token);
case LEX_LBRACK:
Consume(lexer);
if (lexer->type == LEX_PLUS) {
return ParseSum(lexer, scope);
}
return ParseApp(lexer, scope);
default:
fprintf(stderr, "Unexpected token: %s.\n", lexer->token);
THROW;
}
}
static ast_t *
ParseVar(const char * const token, const symbol_t * const scope)
{
ast_t * ap;
symbol_t * it;
assert(token);
if (IsEmpty(scope)) {
goto error;
}
ap = Ast_Node(AST_COMP);
Ast_AddChild(ap, Ast_Snd());
it = Link(scope);
do {
if (strcmp(token, it->value) == 0) {
return ap;
} else {
Ast_AddChild(ap, Ast_Fst());
}
} while ((it = Link(it)) != Link(scope));
error:
fprintf(stderr, "Unbound variable: %s.\n", token);
THROW;
}
static ast_t *
ParseNum(const char *cp)
{
int total = 0;
assert(isdigit(*cp));
do {
assert(isdigit(*cp));
total = (10 * total) + (*cp - '0');
} while (*++cp != '\0');
return Ast_Quote(total);
}
static ast_t *
ParseSum(lexer_t * const lexer, const symbol_t *scope)
{
ast_t * root;
assert(lexer);
assert(lexer->type == LEX_PLUS);
Consume(lexer);
root = ParseExpr(lexer, scope);
Consume(lexer);
do {
root = Ast_Pair(root, ParseExpr(lexer, scope));
root = Ast_Pair(Ast_Plus(), root);
root = Ast_Comp(2, root, Ast_App());
Consume(lexer);
} while (lexer->type != LEX_RBRACK);
return root;
}
static ast_t *
ParseApp(lexer_t * const lexer, const symbol_t *scope)
{
ast_t * root;
int cnt;
assert(lexer);
root = ParseAbs(lexer, scope, &cnt);
while (cnt-- > 0) {
Consume(lexer);
root = Ast_Pair(root, ParseExpr(lexer, scope));
root = Ast_Comp(2, root, Ast_App());
}
Expect(lexer, LEX_RBRACK);
return root;
}
static ast_t *
ParseAbs(lexer_t * const lexer, const symbol_t *scope, int *cnt)
{
ast_t * ap;
int i;
assert(lexer);
Match(lexer, LEX_LBRACK);
Expect(lexer, LEX_LAMBDA);
Expect(lexer, LEX_LBRACK);
Expect(lexer, LEX_VAR);
PushNewSymbol(&scope, lexer->token);
Consume(lexer);
for (*cnt = 1; lexer->type != LEX_RBRACK; ++*cnt) {
Match(lexer, LEX_VAR);
PushNewSymbol(&scope, lexer->token);
Consume(lexer);
}
Consume(lexer);
ap = ParseExpr(lexer, scope);
Expect(lexer, LEX_RBRACK);
for (i = *cnt; i > 0; --i) {
ap = Ast_Cur(ap);
Pool_Free(&g_symbol_pool, Pop(&scope));
}
return ap;
}
|
419669.c | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* rush_utils.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: jde-oliv <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2018/04/01 21:04:16 by jde-oliv #+# #+# */
/* Updated: 2018/04/01 22:45:25 by acalkins ### ########.fr */
/* */
/* ************************************************************************** */
#include "rush_2.h"
int ft_strlen(char *str)
{
int i;
i = 0;
while (str[i])
{
i++;
}
return (i);
}
int ft_find_rows(char *str)
{
int i;
int row;
i = 0;
row = 0;
while (str[i] != '\0')
{
if (str[i] == '\n')
row++;
i++;
}
return (row);
}
int ft_find_cols(int len, int row)
{
return ((len - row) / row);
}
void find_type(char *str, int col, int row)
{
int match;
match = 0;
if (ft_strcmp(str, ft_rush00(col, row)) == 0)
display(col, row, 0, ++match);
if (ft_strcmp(str, ft_rush01(col, row)) == 0)
display(col, row, 1, ++match);
if (ft_strcmp(str, ft_rush02(col, row)) == 0)
display(col, row, 2, ++match);
if (ft_strcmp(str, ft_rush03(col, row)) == 0)
display(col, row, 3, ++match);
if (ft_strcmp(str, ft_rush04(col, row)) == 0)
display(col, row, 4, ++match);
if (match == 0)
ft_putstr("aucune");
}
void display(int col, int row, int id, int match)
{
if (match > 1)
ft_putstr(" || ");
ft_putstr("[rush-0");
ft_putnbr(id);
ft_putstr("] [");
ft_putnbr(col);
ft_putstr("] [");
ft_putnbr(row);
ft_putstr("]");
}
|
316162.c | #include "EsUnitTest.h"
#include "EsProperties.h"
/*****************/
/* T E S T S */
/*****************/
/**
* @brief Test New/Free.
* @note This also tests that a NULL EsWorkTaskFreeDataFunc is ok
* @return TRUE if tests passes, FALSE otherwise
*/
static pboolean test_newFree() {
EsProperties *props;
props = EsProperties_new();
ES_ASSERT(props != NULL);
EsProperties_free(props);
return TRUE;
}
static pboolean test_properties() {
EsProperties *props;
EsPropertyPair pair;
char *val;
/* Test against null props */
props = NULL;
ES_ASSERT(EsProperties_getSize(props) == 0);
ES_ASSERT(EsProperties_includesKey(props, NULL) == FALSE);
ES_ASSERT(EsProperties_at(props, NULL) == NULL);
EsProperties_atPut(props, NULL, NULL);
ES_ASSERT(EsProperties_valueEquals(props, NULL, NULL) == FALSE);
ES_ASSERT(EsProperties_removeKey(props, NULL) == NULL);
EsProperties_atIndex(props, 0, &pair);
ES_ASSERT(pair.key == NULL);
ES_ASSERT(pair.value == NULL);
props = EsProperties_new();
/* Test against null args */
ES_ASSERT(EsProperties_getSize(props) == 0);
ES_ASSERT(EsProperties_includesKey(props, NULL) == FALSE);
ES_ASSERT(EsProperties_at(props, NULL) == NULL);
EsProperties_atPut(props, NULL, NULL);
ES_ASSERT(EsProperties_valueEquals(props, NULL, NULL) == FALSE);
ES_ASSERT(EsProperties_removeKey(props, NULL) == NULL);
EsProperties_atIndex(props, 0, NULL);
/* Test empty prop props / valid keys */
ES_ASSERT(EsProperties_getSize(props) == 0);
ES_ASSERT(EsProperties_includesKey(props, "Key") == FALSE);
ES_ASSERT(EsProperties_at(props, "Key") == NULL);
ES_ASSERT(EsProperties_valueEquals(props, "Key", "Value") == FALSE);
/* Add key */
EsProperties_atPut(props, "Key", "Value");
ES_ASSERT(EsProperties_getSize(props) == 1);
ES_ASSERT(EsProperties_includesKey(props, "Key") == TRUE);
ES_ASSERT(EsProperties_at(props, "Key") != NULL);
ES_ASSERT(EsProperties_valueEquals(props, "Key", "Value"));
EsProperties_atIndex(props, 0, &pair);
ES_ASSERT(strcmp(pair.key, "Key") == 0);
ES_ASSERT(strcmp(pair.value, "Value") == 0)
EsProperties_atIndex(props, 1, &pair);
ES_ASSERT(pair.key == NULL);
ES_ASSERT(pair.value == NULL);
/* Add second key */
EsProperties_atPut(props, "Key2", "Value2");
ES_ASSERT(EsProperties_getSize(props) == 2);
ES_ASSERT(EsProperties_includesKey(props, "Key") == TRUE);
ES_ASSERT(EsProperties_at(props, "Key") != NULL);
ES_ASSERT(EsProperties_valueEquals(props, "Key", "Value"));
ES_ASSERT(EsProperties_includesKey(props, "Key2") == TRUE);
ES_ASSERT(EsProperties_at(props, "Key2") != NULL);
ES_ASSERT(EsProperties_valueEquals(props, "Key2", "Value2"));
/* Add third key */
EsProperties_atPut(props, "Key3", "Value3");
ES_ASSERT(EsProperties_getSize(props) == 3);
ES_ASSERT(EsProperties_includesKey(props, "Key") == TRUE);
ES_ASSERT(EsProperties_at(props, "Key") != NULL);
ES_ASSERT(EsProperties_valueEquals(props, "Key", "Value"));
ES_ASSERT(EsProperties_includesKey(props, "Key2") == TRUE);
ES_ASSERT(EsProperties_at(props, "Key2") != NULL);
ES_ASSERT(EsProperties_valueEquals(props, "Key2", "Value2"));
ES_ASSERT(EsProperties_includesKey(props, "Key3") == TRUE);
ES_ASSERT(EsProperties_at(props, "Key3") != NULL);
ES_ASSERT(EsProperties_valueEquals(props, "Key3", "Value3"));
EsProperties_atIndex(props, 2, &pair);
ES_ASSERT(strcmp(pair.key, "Key3") == 0);
ES_ASSERT(strcmp(pair.value, "Value3") == 0)
EsProperties_atIndex(props, 3, &pair);
ES_ASSERT(pair.key == NULL);
ES_ASSERT(pair.value == NULL);
/* Remove head */
val = EsProperties_removeKey(props, "Key");
ES_ASSERT(EsProperties_getSize(props) == 2);
ES_ASSERT(EsProperties_includesKey(props, "Key") == FALSE);
ES_ASSERT(EsProperties_includesKey(props, "Key2") == TRUE);
ES_ASSERT(EsProperties_includesKey(props, "Key3") == TRUE);
ES_ASSERT(val != NULL);
ES_ASSERT(strncmp(val, "Value", strlen("Value")) == 0);
ES_ASSERT(EsProperties_at(props, "Key") == NULL);
ES_ASSERT(EsProperties_valueEquals(props, "Key", "Value") == FALSE);
/* Remove tail */
val = EsProperties_removeKey(props, "Key3");
ES_ASSERT(EsProperties_getSize(props) == 1);
ES_ASSERT(EsProperties_includesKey(props, "Key") == FALSE);
ES_ASSERT(EsProperties_includesKey(props, "Key2") == TRUE);
ES_ASSERT(EsProperties_includesKey(props, "Key3") == FALSE);
ES_ASSERT(val != NULL);
ES_ASSERT(strncmp(val, "Value3", strlen("Value3")) == 0);
ES_ASSERT(EsProperties_at(props, "Key3") == NULL);
ES_ASSERT(EsProperties_valueEquals(props, "Key3", "Value3") == FALSE);
/* Remove last*/
val = EsProperties_removeKey(props, "Key2");
ES_ASSERT(EsProperties_getSize(props) == 0);
ES_ASSERT(EsProperties_includesKey(props, "Key") == FALSE);
ES_ASSERT(EsProperties_includesKey(props, "Key2") == FALSE);
ES_ASSERT(EsProperties_includesKey(props, "Key3") == FALSE);
ES_ASSERT(val != NULL);
ES_ASSERT(strncmp(val, "Value2", strlen("Value2")) == 0);
ES_ASSERT(EsProperties_at(props, "Key2") == NULL);
ES_ASSERT(EsProperties_valueEquals(props, "Key2", "Value2") == FALSE);
EsProperties_free(props);
return TRUE;
}
static pboolean test_sequenceable() {
EsProperties *p = NULL;
EsPropertyPair pair;
U_32 totalNum = 0;
U_32 i = 0;
p = EsProperties_new();
EsProperties_atPut(p, "key1", "value");
EsProperties_atPut(p, "key2", "value");
EsProperties_atPut(p, "key3", "value");
EsProperties_atPut(p, "key4", "value");
totalNum = EsProperties_getSize(p);
for(i = 0; i < totalNum; i++) {
EsProperties_atIndex(p, i, &pair);
}
ES_ASSERT(i == 4);
EsProperties_free(p);
return TRUE;
}
/**************************/
/* T E S T S U I T E */
/**************************/
/**
* Run all Tests
* @return 0 on Pass, -1 on Fail
*/
int main() {
ES_RUN_TEST(test_newFree);
ES_RUN_TEST(test_properties);
ES_RUN_TEST(test_sequenceable);
ES_RETURN_TEST_RESULTS();
} |
331624.c | // SPDX-License-Identifier: GPL-2.0-only
/*
* Cryptographic API.
*
* Support for OMAP SHA1/MD5 HW acceleration.
*
* Copyright (c) 2010 Nokia Corporation
* Author: Dmitry Kasatkin <[email protected]>
* Copyright (c) 2011 Texas Instruments Incorporated
*
* Some ideas are from old omap-sha1-md5.c driver.
*/
#define pr_fmt(fmt) "%s: " fmt, __func__
#include <linux/err.h>
#include <linux/device.h>
#include <linux/module.h>
#include <linux/init.h>
#include <linux/errno.h>
#include <linux/interrupt.h>
#include <linux/kernel.h>
#include <linux/irq.h>
#include <linux/io.h>
#include <linux/platform_device.h>
#include <linux/scatterlist.h>
#include <linux/dma-mapping.h>
#include <linux/dmaengine.h>
#include <linux/pm_runtime.h>
#include <linux/of.h>
#include <linux/of_device.h>
#include <linux/of_address.h>
#include <linux/of_irq.h>
#include <linux/delay.h>
#include <linux/crypto.h>
#include <crypto/scatterwalk.h>
#include <crypto/algapi.h>
#include <crypto/sha1.h>
#include <crypto/sha2.h>
#include <crypto/hash.h>
#include <crypto/hmac.h>
#include <crypto/internal/hash.h>
#include <crypto/engine.h>
#define MD5_DIGEST_SIZE 16
#define SHA_REG_IDIGEST(dd, x) ((dd)->pdata->idigest_ofs + ((x)*0x04))
#define SHA_REG_DIN(dd, x) ((dd)->pdata->din_ofs + ((x) * 0x04))
#define SHA_REG_DIGCNT(dd) ((dd)->pdata->digcnt_ofs)
#define SHA_REG_ODIGEST(dd, x) ((dd)->pdata->odigest_ofs + (x * 0x04))
#define SHA_REG_CTRL 0x18
#define SHA_REG_CTRL_LENGTH (0xFFFFFFFF << 5)
#define SHA_REG_CTRL_CLOSE_HASH (1 << 4)
#define SHA_REG_CTRL_ALGO_CONST (1 << 3)
#define SHA_REG_CTRL_ALGO (1 << 2)
#define SHA_REG_CTRL_INPUT_READY (1 << 1)
#define SHA_REG_CTRL_OUTPUT_READY (1 << 0)
#define SHA_REG_REV(dd) ((dd)->pdata->rev_ofs)
#define SHA_REG_MASK(dd) ((dd)->pdata->mask_ofs)
#define SHA_REG_MASK_DMA_EN (1 << 3)
#define SHA_REG_MASK_IT_EN (1 << 2)
#define SHA_REG_MASK_SOFTRESET (1 << 1)
#define SHA_REG_AUTOIDLE (1 << 0)
#define SHA_REG_SYSSTATUS(dd) ((dd)->pdata->sysstatus_ofs)
#define SHA_REG_SYSSTATUS_RESETDONE (1 << 0)
#define SHA_REG_MODE(dd) ((dd)->pdata->mode_ofs)
#define SHA_REG_MODE_HMAC_OUTER_HASH (1 << 7)
#define SHA_REG_MODE_HMAC_KEY_PROC (1 << 5)
#define SHA_REG_MODE_CLOSE_HASH (1 << 4)
#define SHA_REG_MODE_ALGO_CONSTANT (1 << 3)
#define SHA_REG_MODE_ALGO_MASK (7 << 0)
#define SHA_REG_MODE_ALGO_MD5_128 (0 << 1)
#define SHA_REG_MODE_ALGO_SHA1_160 (1 << 1)
#define SHA_REG_MODE_ALGO_SHA2_224 (2 << 1)
#define SHA_REG_MODE_ALGO_SHA2_256 (3 << 1)
#define SHA_REG_MODE_ALGO_SHA2_384 (1 << 0)
#define SHA_REG_MODE_ALGO_SHA2_512 (3 << 0)
#define SHA_REG_LENGTH(dd) ((dd)->pdata->length_ofs)
#define SHA_REG_IRQSTATUS 0x118
#define SHA_REG_IRQSTATUS_CTX_RDY (1 << 3)
#define SHA_REG_IRQSTATUS_PARTHASH_RDY (1 << 2)
#define SHA_REG_IRQSTATUS_INPUT_RDY (1 << 1)
#define SHA_REG_IRQSTATUS_OUTPUT_RDY (1 << 0)
#define SHA_REG_IRQENA 0x11C
#define SHA_REG_IRQENA_CTX_RDY (1 << 3)
#define SHA_REG_IRQENA_PARTHASH_RDY (1 << 2)
#define SHA_REG_IRQENA_INPUT_RDY (1 << 1)
#define SHA_REG_IRQENA_OUTPUT_RDY (1 << 0)
#define DEFAULT_TIMEOUT_INTERVAL HZ
#define DEFAULT_AUTOSUSPEND_DELAY 1000
/* mostly device flags */
#define FLAGS_FINAL 1
#define FLAGS_DMA_ACTIVE 2
#define FLAGS_OUTPUT_READY 3
#define FLAGS_INIT 4
#define FLAGS_CPU 5
#define FLAGS_DMA_READY 6
#define FLAGS_AUTO_XOR 7
#define FLAGS_BE32_SHA1 8
#define FLAGS_SGS_COPIED 9
#define FLAGS_SGS_ALLOCED 10
#define FLAGS_HUGE 11
/* context flags */
#define FLAGS_FINUP 16
#define FLAGS_MODE_SHIFT 18
#define FLAGS_MODE_MASK (SHA_REG_MODE_ALGO_MASK << FLAGS_MODE_SHIFT)
#define FLAGS_MODE_MD5 (SHA_REG_MODE_ALGO_MD5_128 << FLAGS_MODE_SHIFT)
#define FLAGS_MODE_SHA1 (SHA_REG_MODE_ALGO_SHA1_160 << FLAGS_MODE_SHIFT)
#define FLAGS_MODE_SHA224 (SHA_REG_MODE_ALGO_SHA2_224 << FLAGS_MODE_SHIFT)
#define FLAGS_MODE_SHA256 (SHA_REG_MODE_ALGO_SHA2_256 << FLAGS_MODE_SHIFT)
#define FLAGS_MODE_SHA384 (SHA_REG_MODE_ALGO_SHA2_384 << FLAGS_MODE_SHIFT)
#define FLAGS_MODE_SHA512 (SHA_REG_MODE_ALGO_SHA2_512 << FLAGS_MODE_SHIFT)
#define FLAGS_HMAC 21
#define FLAGS_ERROR 22
#define OP_UPDATE 1
#define OP_FINAL 2
#define OMAP_ALIGN_MASK (sizeof(u32)-1)
#define OMAP_ALIGNED __attribute__((aligned(sizeof(u32))))
#define BUFLEN SHA512_BLOCK_SIZE
#define OMAP_SHA_DMA_THRESHOLD 256
#define OMAP_SHA_MAX_DMA_LEN (1024 * 2048)
struct omap_sham_dev;
struct omap_sham_reqctx {
struct omap_sham_dev *dd;
unsigned long flags;
u8 op;
u8 digest[SHA512_DIGEST_SIZE] OMAP_ALIGNED;
size_t digcnt;
size_t bufcnt;
size_t buflen;
/* walk state */
struct scatterlist *sg;
struct scatterlist sgl[2];
int offset; /* offset in current sg */
int sg_len;
unsigned int total; /* total request */
u8 buffer[] OMAP_ALIGNED;
};
struct omap_sham_hmac_ctx {
struct crypto_shash *shash;
u8 ipad[SHA512_BLOCK_SIZE] OMAP_ALIGNED;
u8 opad[SHA512_BLOCK_SIZE] OMAP_ALIGNED;
};
struct omap_sham_ctx {
struct crypto_engine_ctx enginectx;
unsigned long flags;
/* fallback stuff */
struct crypto_shash *fallback;
struct omap_sham_hmac_ctx base[];
};
#define OMAP_SHAM_QUEUE_LENGTH 10
struct omap_sham_algs_info {
struct ahash_alg *algs_list;
unsigned int size;
unsigned int registered;
};
struct omap_sham_pdata {
struct omap_sham_algs_info *algs_info;
unsigned int algs_info_size;
unsigned long flags;
int digest_size;
void (*copy_hash)(struct ahash_request *req, int out);
void (*write_ctrl)(struct omap_sham_dev *dd, size_t length,
int final, int dma);
void (*trigger)(struct omap_sham_dev *dd, size_t length);
int (*poll_irq)(struct omap_sham_dev *dd);
irqreturn_t (*intr_hdlr)(int irq, void *dev_id);
u32 odigest_ofs;
u32 idigest_ofs;
u32 din_ofs;
u32 digcnt_ofs;
u32 rev_ofs;
u32 mask_ofs;
u32 sysstatus_ofs;
u32 mode_ofs;
u32 length_ofs;
u32 major_mask;
u32 major_shift;
u32 minor_mask;
u32 minor_shift;
};
struct omap_sham_dev {
struct list_head list;
unsigned long phys_base;
struct device *dev;
void __iomem *io_base;
int irq;
int err;
struct dma_chan *dma_lch;
struct tasklet_struct done_task;
u8 polling_mode;
u8 xmit_buf[BUFLEN] OMAP_ALIGNED;
unsigned long flags;
int fallback_sz;
struct crypto_queue queue;
struct ahash_request *req;
struct crypto_engine *engine;
const struct omap_sham_pdata *pdata;
};
struct omap_sham_drv {
struct list_head dev_list;
spinlock_t lock;
unsigned long flags;
};
static struct omap_sham_drv sham = {
.dev_list = LIST_HEAD_INIT(sham.dev_list),
.lock = __SPIN_LOCK_UNLOCKED(sham.lock),
};
static int omap_sham_enqueue(struct ahash_request *req, unsigned int op);
static void omap_sham_finish_req(struct ahash_request *req, int err);
static inline u32 omap_sham_read(struct omap_sham_dev *dd, u32 offset)
{
return __raw_readl(dd->io_base + offset);
}
static inline void omap_sham_write(struct omap_sham_dev *dd,
u32 offset, u32 value)
{
__raw_writel(value, dd->io_base + offset);
}
static inline void omap_sham_write_mask(struct omap_sham_dev *dd, u32 address,
u32 value, u32 mask)
{
u32 val;
val = omap_sham_read(dd, address);
val &= ~mask;
val |= value;
omap_sham_write(dd, address, val);
}
static inline int omap_sham_wait(struct omap_sham_dev *dd, u32 offset, u32 bit)
{
unsigned long timeout = jiffies + DEFAULT_TIMEOUT_INTERVAL;
while (!(omap_sham_read(dd, offset) & bit)) {
if (time_is_before_jiffies(timeout))
return -ETIMEDOUT;
}
return 0;
}
static void omap_sham_copy_hash_omap2(struct ahash_request *req, int out)
{
struct omap_sham_reqctx *ctx = ahash_request_ctx(req);
struct omap_sham_dev *dd = ctx->dd;
u32 *hash = (u32 *)ctx->digest;
int i;
for (i = 0; i < dd->pdata->digest_size / sizeof(u32); i++) {
if (out)
hash[i] = omap_sham_read(dd, SHA_REG_IDIGEST(dd, i));
else
omap_sham_write(dd, SHA_REG_IDIGEST(dd, i), hash[i]);
}
}
static void omap_sham_copy_hash_omap4(struct ahash_request *req, int out)
{
struct omap_sham_reqctx *ctx = ahash_request_ctx(req);
struct omap_sham_dev *dd = ctx->dd;
int i;
if (ctx->flags & BIT(FLAGS_HMAC)) {
struct crypto_ahash *tfm = crypto_ahash_reqtfm(dd->req);
struct omap_sham_ctx *tctx = crypto_ahash_ctx(tfm);
struct omap_sham_hmac_ctx *bctx = tctx->base;
u32 *opad = (u32 *)bctx->opad;
for (i = 0; i < dd->pdata->digest_size / sizeof(u32); i++) {
if (out)
opad[i] = omap_sham_read(dd,
SHA_REG_ODIGEST(dd, i));
else
omap_sham_write(dd, SHA_REG_ODIGEST(dd, i),
opad[i]);
}
}
omap_sham_copy_hash_omap2(req, out);
}
static void omap_sham_copy_ready_hash(struct ahash_request *req)
{
struct omap_sham_reqctx *ctx = ahash_request_ctx(req);
u32 *in = (u32 *)ctx->digest;
u32 *hash = (u32 *)req->result;
int i, d, big_endian = 0;
if (!hash)
return;
switch (ctx->flags & FLAGS_MODE_MASK) {
case FLAGS_MODE_MD5:
d = MD5_DIGEST_SIZE / sizeof(u32);
break;
case FLAGS_MODE_SHA1:
/* OMAP2 SHA1 is big endian */
if (test_bit(FLAGS_BE32_SHA1, &ctx->dd->flags))
big_endian = 1;
d = SHA1_DIGEST_SIZE / sizeof(u32);
break;
case FLAGS_MODE_SHA224:
d = SHA224_DIGEST_SIZE / sizeof(u32);
break;
case FLAGS_MODE_SHA256:
d = SHA256_DIGEST_SIZE / sizeof(u32);
break;
case FLAGS_MODE_SHA384:
d = SHA384_DIGEST_SIZE / sizeof(u32);
break;
case FLAGS_MODE_SHA512:
d = SHA512_DIGEST_SIZE / sizeof(u32);
break;
default:
d = 0;
}
if (big_endian)
for (i = 0; i < d; i++)
hash[i] = be32_to_cpup((__be32 *)in + i);
else
for (i = 0; i < d; i++)
hash[i] = le32_to_cpup((__le32 *)in + i);
}
static int omap_sham_hw_init(struct omap_sham_dev *dd)
{
int err;
err = pm_runtime_resume_and_get(dd->dev);
if (err < 0) {
dev_err(dd->dev, "failed to get sync: %d\n", err);
return err;
}
if (!test_bit(FLAGS_INIT, &dd->flags)) {
set_bit(FLAGS_INIT, &dd->flags);
dd->err = 0;
}
return 0;
}
static void omap_sham_write_ctrl_omap2(struct omap_sham_dev *dd, size_t length,
int final, int dma)
{
struct omap_sham_reqctx *ctx = ahash_request_ctx(dd->req);
u32 val = length << 5, mask;
if (likely(ctx->digcnt))
omap_sham_write(dd, SHA_REG_DIGCNT(dd), ctx->digcnt);
omap_sham_write_mask(dd, SHA_REG_MASK(dd),
SHA_REG_MASK_IT_EN | (dma ? SHA_REG_MASK_DMA_EN : 0),
SHA_REG_MASK_IT_EN | SHA_REG_MASK_DMA_EN);
/*
* Setting ALGO_CONST only for the first iteration
* and CLOSE_HASH only for the last one.
*/
if ((ctx->flags & FLAGS_MODE_MASK) == FLAGS_MODE_SHA1)
val |= SHA_REG_CTRL_ALGO;
if (!ctx->digcnt)
val |= SHA_REG_CTRL_ALGO_CONST;
if (final)
val |= SHA_REG_CTRL_CLOSE_HASH;
mask = SHA_REG_CTRL_ALGO_CONST | SHA_REG_CTRL_CLOSE_HASH |
SHA_REG_CTRL_ALGO | SHA_REG_CTRL_LENGTH;
omap_sham_write_mask(dd, SHA_REG_CTRL, val, mask);
}
static void omap_sham_trigger_omap2(struct omap_sham_dev *dd, size_t length)
{
}
static int omap_sham_poll_irq_omap2(struct omap_sham_dev *dd)
{
return omap_sham_wait(dd, SHA_REG_CTRL, SHA_REG_CTRL_INPUT_READY);
}
static int get_block_size(struct omap_sham_reqctx *ctx)
{
int d;
switch (ctx->flags & FLAGS_MODE_MASK) {
case FLAGS_MODE_MD5:
case FLAGS_MODE_SHA1:
d = SHA1_BLOCK_SIZE;
break;
case FLAGS_MODE_SHA224:
case FLAGS_MODE_SHA256:
d = SHA256_BLOCK_SIZE;
break;
case FLAGS_MODE_SHA384:
case FLAGS_MODE_SHA512:
d = SHA512_BLOCK_SIZE;
break;
default:
d = 0;
}
return d;
}
static void omap_sham_write_n(struct omap_sham_dev *dd, u32 offset,
u32 *value, int count)
{
for (; count--; value++, offset += 4)
omap_sham_write(dd, offset, *value);
}
static void omap_sham_write_ctrl_omap4(struct omap_sham_dev *dd, size_t length,
int final, int dma)
{
struct omap_sham_reqctx *ctx = ahash_request_ctx(dd->req);
u32 val, mask;
if (likely(ctx->digcnt))
omap_sham_write(dd, SHA_REG_DIGCNT(dd), ctx->digcnt);
/*
* Setting ALGO_CONST only for the first iteration and
* CLOSE_HASH only for the last one. Note that flags mode bits
* correspond to algorithm encoding in mode register.
*/
val = (ctx->flags & FLAGS_MODE_MASK) >> (FLAGS_MODE_SHIFT);
if (!ctx->digcnt) {
struct crypto_ahash *tfm = crypto_ahash_reqtfm(dd->req);
struct omap_sham_ctx *tctx = crypto_ahash_ctx(tfm);
struct omap_sham_hmac_ctx *bctx = tctx->base;
int bs, nr_dr;
val |= SHA_REG_MODE_ALGO_CONSTANT;
if (ctx->flags & BIT(FLAGS_HMAC)) {
bs = get_block_size(ctx);
nr_dr = bs / (2 * sizeof(u32));
val |= SHA_REG_MODE_HMAC_KEY_PROC;
omap_sham_write_n(dd, SHA_REG_ODIGEST(dd, 0),
(u32 *)bctx->ipad, nr_dr);
omap_sham_write_n(dd, SHA_REG_IDIGEST(dd, 0),
(u32 *)bctx->ipad + nr_dr, nr_dr);
ctx->digcnt += bs;
}
}
if (final) {
val |= SHA_REG_MODE_CLOSE_HASH;
if (ctx->flags & BIT(FLAGS_HMAC))
val |= SHA_REG_MODE_HMAC_OUTER_HASH;
}
mask = SHA_REG_MODE_ALGO_CONSTANT | SHA_REG_MODE_CLOSE_HASH |
SHA_REG_MODE_ALGO_MASK | SHA_REG_MODE_HMAC_OUTER_HASH |
SHA_REG_MODE_HMAC_KEY_PROC;
dev_dbg(dd->dev, "ctrl: %08x, flags: %08lx\n", val, ctx->flags);
omap_sham_write_mask(dd, SHA_REG_MODE(dd), val, mask);
omap_sham_write(dd, SHA_REG_IRQENA, SHA_REG_IRQENA_OUTPUT_RDY);
omap_sham_write_mask(dd, SHA_REG_MASK(dd),
SHA_REG_MASK_IT_EN |
(dma ? SHA_REG_MASK_DMA_EN : 0),
SHA_REG_MASK_IT_EN | SHA_REG_MASK_DMA_EN);
}
static void omap_sham_trigger_omap4(struct omap_sham_dev *dd, size_t length)
{
omap_sham_write(dd, SHA_REG_LENGTH(dd), length);
}
static int omap_sham_poll_irq_omap4(struct omap_sham_dev *dd)
{
return omap_sham_wait(dd, SHA_REG_IRQSTATUS,
SHA_REG_IRQSTATUS_INPUT_RDY);
}
static int omap_sham_xmit_cpu(struct omap_sham_dev *dd, size_t length,
int final)
{
struct omap_sham_reqctx *ctx = ahash_request_ctx(dd->req);
int count, len32, bs32, offset = 0;
const u32 *buffer;
int mlen;
struct sg_mapping_iter mi;
dev_dbg(dd->dev, "xmit_cpu: digcnt: %zd, length: %zd, final: %d\n",
ctx->digcnt, length, final);
dd->pdata->write_ctrl(dd, length, final, 0);
dd->pdata->trigger(dd, length);
/* should be non-zero before next lines to disable clocks later */
ctx->digcnt += length;
ctx->total -= length;
if (final)
set_bit(FLAGS_FINAL, &dd->flags); /* catch last interrupt */
set_bit(FLAGS_CPU, &dd->flags);
len32 = DIV_ROUND_UP(length, sizeof(u32));
bs32 = get_block_size(ctx) / sizeof(u32);
sg_miter_start(&mi, ctx->sg, ctx->sg_len,
SG_MITER_FROM_SG | SG_MITER_ATOMIC);
mlen = 0;
while (len32) {
if (dd->pdata->poll_irq(dd))
return -ETIMEDOUT;
for (count = 0; count < min(len32, bs32); count++, offset++) {
if (!mlen) {
sg_miter_next(&mi);
mlen = mi.length;
if (!mlen) {
pr_err("sg miter failure.\n");
return -EINVAL;
}
offset = 0;
buffer = mi.addr;
}
omap_sham_write(dd, SHA_REG_DIN(dd, count),
buffer[offset]);
mlen -= 4;
}
len32 -= min(len32, bs32);
}
sg_miter_stop(&mi);
return -EINPROGRESS;
}
static void omap_sham_dma_callback(void *param)
{
struct omap_sham_dev *dd = param;
set_bit(FLAGS_DMA_READY, &dd->flags);
tasklet_schedule(&dd->done_task);
}
static int omap_sham_xmit_dma(struct omap_sham_dev *dd, size_t length,
int final)
{
struct omap_sham_reqctx *ctx = ahash_request_ctx(dd->req);
struct dma_async_tx_descriptor *tx;
struct dma_slave_config cfg;
int ret;
dev_dbg(dd->dev, "xmit_dma: digcnt: %zd, length: %zd, final: %d\n",
ctx->digcnt, length, final);
if (!dma_map_sg(dd->dev, ctx->sg, ctx->sg_len, DMA_TO_DEVICE)) {
dev_err(dd->dev, "dma_map_sg error\n");
return -EINVAL;
}
memset(&cfg, 0, sizeof(cfg));
cfg.dst_addr = dd->phys_base + SHA_REG_DIN(dd, 0);
cfg.dst_addr_width = DMA_SLAVE_BUSWIDTH_4_BYTES;
cfg.dst_maxburst = get_block_size(ctx) / DMA_SLAVE_BUSWIDTH_4_BYTES;
ret = dmaengine_slave_config(dd->dma_lch, &cfg);
if (ret) {
pr_err("omap-sham: can't configure dmaengine slave: %d\n", ret);
return ret;
}
tx = dmaengine_prep_slave_sg(dd->dma_lch, ctx->sg, ctx->sg_len,
DMA_MEM_TO_DEV,
DMA_PREP_INTERRUPT | DMA_CTRL_ACK);
if (!tx) {
dev_err(dd->dev, "prep_slave_sg failed\n");
return -EINVAL;
}
tx->callback = omap_sham_dma_callback;
tx->callback_param = dd;
dd->pdata->write_ctrl(dd, length, final, 1);
ctx->digcnt += length;
ctx->total -= length;
if (final)
set_bit(FLAGS_FINAL, &dd->flags); /* catch last interrupt */
set_bit(FLAGS_DMA_ACTIVE, &dd->flags);
dmaengine_submit(tx);
dma_async_issue_pending(dd->dma_lch);
dd->pdata->trigger(dd, length);
return -EINPROGRESS;
}
static int omap_sham_copy_sg_lists(struct omap_sham_reqctx *ctx,
struct scatterlist *sg, int bs, int new_len)
{
int n = sg_nents(sg);
struct scatterlist *tmp;
int offset = ctx->offset;
ctx->total = new_len;
if (ctx->bufcnt)
n++;
ctx->sg = kmalloc_array(n, sizeof(*sg), GFP_KERNEL);
if (!ctx->sg)
return -ENOMEM;
sg_init_table(ctx->sg, n);
tmp = ctx->sg;
ctx->sg_len = 0;
if (ctx->bufcnt) {
sg_set_buf(tmp, ctx->dd->xmit_buf, ctx->bufcnt);
tmp = sg_next(tmp);
ctx->sg_len++;
new_len -= ctx->bufcnt;
}
while (sg && new_len) {
int len = sg->length - offset;
if (len <= 0) {
offset -= sg->length;
sg = sg_next(sg);
continue;
}
if (new_len < len)
len = new_len;
if (len > 0) {
new_len -= len;
sg_set_page(tmp, sg_page(sg), len, sg->offset + offset);
offset = 0;
ctx->offset = 0;
ctx->sg_len++;
if (new_len <= 0)
break;
tmp = sg_next(tmp);
}
sg = sg_next(sg);
}
if (tmp)
sg_mark_end(tmp);
set_bit(FLAGS_SGS_ALLOCED, &ctx->dd->flags);
ctx->offset += new_len - ctx->bufcnt;
ctx->bufcnt = 0;
return 0;
}
static int omap_sham_copy_sgs(struct omap_sham_reqctx *ctx,
struct scatterlist *sg, int bs,
unsigned int new_len)
{
int pages;
void *buf;
pages = get_order(new_len);
buf = (void *)__get_free_pages(GFP_ATOMIC, pages);
if (!buf) {
pr_err("Couldn't allocate pages for unaligned cases.\n");
return -ENOMEM;
}
if (ctx->bufcnt)
memcpy(buf, ctx->dd->xmit_buf, ctx->bufcnt);
scatterwalk_map_and_copy(buf + ctx->bufcnt, sg, ctx->offset,
min(new_len, ctx->total) - ctx->bufcnt, 0);
sg_init_table(ctx->sgl, 1);
sg_set_buf(ctx->sgl, buf, new_len);
ctx->sg = ctx->sgl;
set_bit(FLAGS_SGS_COPIED, &ctx->dd->flags);
ctx->sg_len = 1;
ctx->offset += new_len - ctx->bufcnt;
ctx->bufcnt = 0;
ctx->total = new_len;
return 0;
}
static int omap_sham_align_sgs(struct scatterlist *sg,
int nbytes, int bs, bool final,
struct omap_sham_reqctx *rctx)
{
int n = 0;
bool aligned = true;
bool list_ok = true;
struct scatterlist *sg_tmp = sg;
int new_len;
int offset = rctx->offset;
int bufcnt = rctx->bufcnt;
if (!sg || !sg->length || !nbytes) {
if (bufcnt) {
bufcnt = DIV_ROUND_UP(bufcnt, bs) * bs;
sg_init_table(rctx->sgl, 1);
sg_set_buf(rctx->sgl, rctx->dd->xmit_buf, bufcnt);
rctx->sg = rctx->sgl;
rctx->sg_len = 1;
}
return 0;
}
new_len = nbytes;
if (offset)
list_ok = false;
if (final)
new_len = DIV_ROUND_UP(new_len, bs) * bs;
else
new_len = (new_len - 1) / bs * bs;
if (!new_len)
return 0;
if (nbytes != new_len)
list_ok = false;
while (nbytes > 0 && sg_tmp) {
n++;
if (bufcnt) {
if (!IS_ALIGNED(bufcnt, bs)) {
aligned = false;
break;
}
nbytes -= bufcnt;
bufcnt = 0;
if (!nbytes)
list_ok = false;
continue;
}
#ifdef CONFIG_ZONE_DMA
if (page_zonenum(sg_page(sg_tmp)) != ZONE_DMA) {
aligned = false;
break;
}
#endif
if (offset < sg_tmp->length) {
if (!IS_ALIGNED(offset + sg_tmp->offset, 4)) {
aligned = false;
break;
}
if (!IS_ALIGNED(sg_tmp->length - offset, bs)) {
aligned = false;
break;
}
}
if (offset) {
offset -= sg_tmp->length;
if (offset < 0) {
nbytes += offset;
offset = 0;
}
} else {
nbytes -= sg_tmp->length;
}
sg_tmp = sg_next(sg_tmp);
if (nbytes < 0) {
list_ok = false;
break;
}
}
if (new_len > OMAP_SHA_MAX_DMA_LEN) {
new_len = OMAP_SHA_MAX_DMA_LEN;
aligned = false;
}
if (!aligned)
return omap_sham_copy_sgs(rctx, sg, bs, new_len);
else if (!list_ok)
return omap_sham_copy_sg_lists(rctx, sg, bs, new_len);
rctx->total = new_len;
rctx->offset += new_len;
rctx->sg_len = n;
if (rctx->bufcnt) {
sg_init_table(rctx->sgl, 2);
sg_set_buf(rctx->sgl, rctx->dd->xmit_buf, rctx->bufcnt);
sg_chain(rctx->sgl, 2, sg);
rctx->sg = rctx->sgl;
} else {
rctx->sg = sg;
}
return 0;
}
static int omap_sham_prepare_request(struct crypto_engine *engine, void *areq)
{
struct ahash_request *req = container_of(areq, struct ahash_request,
base);
struct omap_sham_reqctx *rctx = ahash_request_ctx(req);
int bs;
int ret;
unsigned int nbytes;
bool final = rctx->flags & BIT(FLAGS_FINUP);
bool update = rctx->op == OP_UPDATE;
int hash_later;
bs = get_block_size(rctx);
nbytes = rctx->bufcnt;
if (update)
nbytes += req->nbytes - rctx->offset;
dev_dbg(rctx->dd->dev,
"%s: nbytes=%d, bs=%d, total=%d, offset=%d, bufcnt=%zd\n",
__func__, nbytes, bs, rctx->total, rctx->offset,
rctx->bufcnt);
if (!nbytes)
return 0;
rctx->total = nbytes;
if (update && req->nbytes && (!IS_ALIGNED(rctx->bufcnt, bs))) {
int len = bs - rctx->bufcnt % bs;
if (len > req->nbytes)
len = req->nbytes;
scatterwalk_map_and_copy(rctx->buffer + rctx->bufcnt, req->src,
0, len, 0);
rctx->bufcnt += len;
rctx->offset = len;
}
if (rctx->bufcnt)
memcpy(rctx->dd->xmit_buf, rctx->buffer, rctx->bufcnt);
ret = omap_sham_align_sgs(req->src, nbytes, bs, final, rctx);
if (ret)
return ret;
hash_later = nbytes - rctx->total;
if (hash_later < 0)
hash_later = 0;
if (hash_later && hash_later <= rctx->buflen) {
scatterwalk_map_and_copy(rctx->buffer,
req->src,
req->nbytes - hash_later,
hash_later, 0);
rctx->bufcnt = hash_later;
} else {
rctx->bufcnt = 0;
}
if (hash_later > rctx->buflen)
set_bit(FLAGS_HUGE, &rctx->dd->flags);
rctx->total = min(nbytes, rctx->total);
return 0;
}
static int omap_sham_update_dma_stop(struct omap_sham_dev *dd)
{
struct omap_sham_reqctx *ctx = ahash_request_ctx(dd->req);
dma_unmap_sg(dd->dev, ctx->sg, ctx->sg_len, DMA_TO_DEVICE);
clear_bit(FLAGS_DMA_ACTIVE, &dd->flags);
return 0;
}
static struct omap_sham_dev *omap_sham_find_dev(struct omap_sham_reqctx *ctx)
{
struct omap_sham_dev *dd;
if (ctx->dd)
return ctx->dd;
spin_lock_bh(&sham.lock);
dd = list_first_entry(&sham.dev_list, struct omap_sham_dev, list);
list_move_tail(&dd->list, &sham.dev_list);
ctx->dd = dd;
spin_unlock_bh(&sham.lock);
return dd;
}
static int omap_sham_init(struct ahash_request *req)
{
struct crypto_ahash *tfm = crypto_ahash_reqtfm(req);
struct omap_sham_ctx *tctx = crypto_ahash_ctx(tfm);
struct omap_sham_reqctx *ctx = ahash_request_ctx(req);
struct omap_sham_dev *dd;
int bs = 0;
ctx->dd = NULL;
dd = omap_sham_find_dev(ctx);
if (!dd)
return -ENODEV;
ctx->flags = 0;
dev_dbg(dd->dev, "init: digest size: %d\n",
crypto_ahash_digestsize(tfm));
switch (crypto_ahash_digestsize(tfm)) {
case MD5_DIGEST_SIZE:
ctx->flags |= FLAGS_MODE_MD5;
bs = SHA1_BLOCK_SIZE;
break;
case SHA1_DIGEST_SIZE:
ctx->flags |= FLAGS_MODE_SHA1;
bs = SHA1_BLOCK_SIZE;
break;
case SHA224_DIGEST_SIZE:
ctx->flags |= FLAGS_MODE_SHA224;
bs = SHA224_BLOCK_SIZE;
break;
case SHA256_DIGEST_SIZE:
ctx->flags |= FLAGS_MODE_SHA256;
bs = SHA256_BLOCK_SIZE;
break;
case SHA384_DIGEST_SIZE:
ctx->flags |= FLAGS_MODE_SHA384;
bs = SHA384_BLOCK_SIZE;
break;
case SHA512_DIGEST_SIZE:
ctx->flags |= FLAGS_MODE_SHA512;
bs = SHA512_BLOCK_SIZE;
break;
}
ctx->bufcnt = 0;
ctx->digcnt = 0;
ctx->total = 0;
ctx->offset = 0;
ctx->buflen = BUFLEN;
if (tctx->flags & BIT(FLAGS_HMAC)) {
if (!test_bit(FLAGS_AUTO_XOR, &dd->flags)) {
struct omap_sham_hmac_ctx *bctx = tctx->base;
memcpy(ctx->buffer, bctx->ipad, bs);
ctx->bufcnt = bs;
}
ctx->flags |= BIT(FLAGS_HMAC);
}
return 0;
}
static int omap_sham_update_req(struct omap_sham_dev *dd)
{
struct ahash_request *req = dd->req;
struct omap_sham_reqctx *ctx = ahash_request_ctx(req);
int err;
bool final = (ctx->flags & BIT(FLAGS_FINUP)) &&
!(dd->flags & BIT(FLAGS_HUGE));
dev_dbg(dd->dev, "update_req: total: %u, digcnt: %zd, final: %d",
ctx->total, ctx->digcnt, final);
if (ctx->total < get_block_size(ctx) ||
ctx->total < dd->fallback_sz)
ctx->flags |= BIT(FLAGS_CPU);
if (ctx->flags & BIT(FLAGS_CPU))
err = omap_sham_xmit_cpu(dd, ctx->total, final);
else
err = omap_sham_xmit_dma(dd, ctx->total, final);
/* wait for dma completion before can take more data */
dev_dbg(dd->dev, "update: err: %d, digcnt: %zd\n", err, ctx->digcnt);
return err;
}
static int omap_sham_final_req(struct omap_sham_dev *dd)
{
struct ahash_request *req = dd->req;
struct omap_sham_reqctx *ctx = ahash_request_ctx(req);
int err = 0, use_dma = 1;
if (dd->flags & BIT(FLAGS_HUGE))
return 0;
if ((ctx->total <= get_block_size(ctx)) || dd->polling_mode)
/*
* faster to handle last block with cpu or
* use cpu when dma is not present.
*/
use_dma = 0;
if (use_dma)
err = omap_sham_xmit_dma(dd, ctx->total, 1);
else
err = omap_sham_xmit_cpu(dd, ctx->total, 1);
ctx->bufcnt = 0;
dev_dbg(dd->dev, "final_req: err: %d\n", err);
return err;
}
static int omap_sham_hash_one_req(struct crypto_engine *engine, void *areq)
{
struct ahash_request *req = container_of(areq, struct ahash_request,
base);
struct omap_sham_reqctx *ctx = ahash_request_ctx(req);
struct omap_sham_dev *dd = ctx->dd;
int err;
bool final = (ctx->flags & BIT(FLAGS_FINUP)) &&
!(dd->flags & BIT(FLAGS_HUGE));
dev_dbg(dd->dev, "hash-one: op: %u, total: %u, digcnt: %zd, final: %d",
ctx->op, ctx->total, ctx->digcnt, final);
dd->req = req;
err = omap_sham_hw_init(dd);
if (err)
return err;
if (ctx->digcnt)
dd->pdata->copy_hash(req, 0);
if (ctx->op == OP_UPDATE)
err = omap_sham_update_req(dd);
else if (ctx->op == OP_FINAL)
err = omap_sham_final_req(dd);
if (err != -EINPROGRESS)
omap_sham_finish_req(req, err);
return 0;
}
static int omap_sham_finish_hmac(struct ahash_request *req)
{
struct omap_sham_ctx *tctx = crypto_tfm_ctx(req->base.tfm);
struct omap_sham_hmac_ctx *bctx = tctx->base;
int bs = crypto_shash_blocksize(bctx->shash);
int ds = crypto_shash_digestsize(bctx->shash);
SHASH_DESC_ON_STACK(shash, bctx->shash);
shash->tfm = bctx->shash;
return crypto_shash_init(shash) ?:
crypto_shash_update(shash, bctx->opad, bs) ?:
crypto_shash_finup(shash, req->result, ds, req->result);
}
static int omap_sham_finish(struct ahash_request *req)
{
struct omap_sham_reqctx *ctx = ahash_request_ctx(req);
struct omap_sham_dev *dd = ctx->dd;
int err = 0;
if (ctx->digcnt) {
omap_sham_copy_ready_hash(req);
if ((ctx->flags & BIT(FLAGS_HMAC)) &&
!test_bit(FLAGS_AUTO_XOR, &dd->flags))
err = omap_sham_finish_hmac(req);
}
dev_dbg(dd->dev, "digcnt: %zd, bufcnt: %zd\n", ctx->digcnt, ctx->bufcnt);
return err;
}
static void omap_sham_finish_req(struct ahash_request *req, int err)
{
struct omap_sham_reqctx *ctx = ahash_request_ctx(req);
struct omap_sham_dev *dd = ctx->dd;
if (test_bit(FLAGS_SGS_COPIED, &dd->flags))
free_pages((unsigned long)sg_virt(ctx->sg),
get_order(ctx->sg->length));
if (test_bit(FLAGS_SGS_ALLOCED, &dd->flags))
kfree(ctx->sg);
ctx->sg = NULL;
dd->flags &= ~(BIT(FLAGS_SGS_ALLOCED) | BIT(FLAGS_SGS_COPIED) |
BIT(FLAGS_CPU) | BIT(FLAGS_DMA_READY) |
BIT(FLAGS_OUTPUT_READY));
if (!err)
dd->pdata->copy_hash(req, 1);
if (dd->flags & BIT(FLAGS_HUGE)) {
/* Re-enqueue the request */
omap_sham_enqueue(req, ctx->op);
return;
}
if (!err) {
if (test_bit(FLAGS_FINAL, &dd->flags))
err = omap_sham_finish(req);
} else {
ctx->flags |= BIT(FLAGS_ERROR);
}
/* atomic operation is not needed here */
dd->flags &= ~(BIT(FLAGS_FINAL) | BIT(FLAGS_CPU) |
BIT(FLAGS_DMA_READY) | BIT(FLAGS_OUTPUT_READY));
pm_runtime_mark_last_busy(dd->dev);
pm_runtime_put_autosuspend(dd->dev);
ctx->offset = 0;
crypto_finalize_hash_request(dd->engine, req, err);
}
static int omap_sham_handle_queue(struct omap_sham_dev *dd,
struct ahash_request *req)
{
return crypto_transfer_hash_request_to_engine(dd->engine, req);
}
static int omap_sham_enqueue(struct ahash_request *req, unsigned int op)
{
struct omap_sham_reqctx *ctx = ahash_request_ctx(req);
struct omap_sham_dev *dd = ctx->dd;
ctx->op = op;
return omap_sham_handle_queue(dd, req);
}
static int omap_sham_update(struct ahash_request *req)
{
struct omap_sham_reqctx *ctx = ahash_request_ctx(req);
struct omap_sham_dev *dd = omap_sham_find_dev(ctx);
if (!req->nbytes)
return 0;
if (ctx->bufcnt + req->nbytes <= ctx->buflen) {
scatterwalk_map_and_copy(ctx->buffer + ctx->bufcnt, req->src,
0, req->nbytes, 0);
ctx->bufcnt += req->nbytes;
return 0;
}
if (dd->polling_mode)
ctx->flags |= BIT(FLAGS_CPU);
return omap_sham_enqueue(req, OP_UPDATE);
}
static int omap_sham_final_shash(struct ahash_request *req)
{
struct omap_sham_ctx *tctx = crypto_tfm_ctx(req->base.tfm);
struct omap_sham_reqctx *ctx = ahash_request_ctx(req);
int offset = 0;
/*
* If we are running HMAC on limited hardware support, skip
* the ipad in the beginning of the buffer if we are going for
* software fallback algorithm.
*/
if (test_bit(FLAGS_HMAC, &ctx->flags) &&
!test_bit(FLAGS_AUTO_XOR, &ctx->dd->flags))
offset = get_block_size(ctx);
return crypto_shash_tfm_digest(tctx->fallback, ctx->buffer + offset,
ctx->bufcnt - offset, req->result);
}
static int omap_sham_final(struct ahash_request *req)
{
struct omap_sham_reqctx *ctx = ahash_request_ctx(req);
ctx->flags |= BIT(FLAGS_FINUP);
if (ctx->flags & BIT(FLAGS_ERROR))
return 0; /* uncompleted hash is not needed */
/*
* OMAP HW accel works only with buffers >= 9.
* HMAC is always >= 9 because ipad == block size.
* If buffersize is less than fallback_sz, we use fallback
* SW encoding, as using DMA + HW in this case doesn't provide
* any benefit.
*/
if (!ctx->digcnt && ctx->bufcnt < ctx->dd->fallback_sz)
return omap_sham_final_shash(req);
else if (ctx->bufcnt)
return omap_sham_enqueue(req, OP_FINAL);
/* copy ready hash (+ finalize hmac) */
return omap_sham_finish(req);
}
static int omap_sham_finup(struct ahash_request *req)
{
struct omap_sham_reqctx *ctx = ahash_request_ctx(req);
int err1, err2;
ctx->flags |= BIT(FLAGS_FINUP);
err1 = omap_sham_update(req);
if (err1 == -EINPROGRESS || err1 == -EBUSY)
return err1;
/*
* final() has to be always called to cleanup resources
* even if udpate() failed, except EINPROGRESS
*/
err2 = omap_sham_final(req);
return err1 ?: err2;
}
static int omap_sham_digest(struct ahash_request *req)
{
return omap_sham_init(req) ?: omap_sham_finup(req);
}
static int omap_sham_setkey(struct crypto_ahash *tfm, const u8 *key,
unsigned int keylen)
{
struct omap_sham_ctx *tctx = crypto_ahash_ctx(tfm);
struct omap_sham_hmac_ctx *bctx = tctx->base;
int bs = crypto_shash_blocksize(bctx->shash);
int ds = crypto_shash_digestsize(bctx->shash);
int err, i;
err = crypto_shash_setkey(tctx->fallback, key, keylen);
if (err)
return err;
if (keylen > bs) {
err = crypto_shash_tfm_digest(bctx->shash, key, keylen,
bctx->ipad);
if (err)
return err;
keylen = ds;
} else {
memcpy(bctx->ipad, key, keylen);
}
memset(bctx->ipad + keylen, 0, bs - keylen);
if (!test_bit(FLAGS_AUTO_XOR, &sham.flags)) {
memcpy(bctx->opad, bctx->ipad, bs);
for (i = 0; i < bs; i++) {
bctx->ipad[i] ^= HMAC_IPAD_VALUE;
bctx->opad[i] ^= HMAC_OPAD_VALUE;
}
}
return err;
}
static int omap_sham_cra_init_alg(struct crypto_tfm *tfm, const char *alg_base)
{
struct omap_sham_ctx *tctx = crypto_tfm_ctx(tfm);
const char *alg_name = crypto_tfm_alg_name(tfm);
/* Allocate a fallback and abort if it failed. */
tctx->fallback = crypto_alloc_shash(alg_name, 0,
CRYPTO_ALG_NEED_FALLBACK);
if (IS_ERR(tctx->fallback)) {
pr_err("omap-sham: fallback driver '%s' "
"could not be loaded.\n", alg_name);
return PTR_ERR(tctx->fallback);
}
crypto_ahash_set_reqsize(__crypto_ahash_cast(tfm),
sizeof(struct omap_sham_reqctx) + BUFLEN);
if (alg_base) {
struct omap_sham_hmac_ctx *bctx = tctx->base;
tctx->flags |= BIT(FLAGS_HMAC);
bctx->shash = crypto_alloc_shash(alg_base, 0,
CRYPTO_ALG_NEED_FALLBACK);
if (IS_ERR(bctx->shash)) {
pr_err("omap-sham: base driver '%s' "
"could not be loaded.\n", alg_base);
crypto_free_shash(tctx->fallback);
return PTR_ERR(bctx->shash);
}
}
tctx->enginectx.op.do_one_request = omap_sham_hash_one_req;
tctx->enginectx.op.prepare_request = omap_sham_prepare_request;
tctx->enginectx.op.unprepare_request = NULL;
return 0;
}
static int omap_sham_cra_init(struct crypto_tfm *tfm)
{
return omap_sham_cra_init_alg(tfm, NULL);
}
static int omap_sham_cra_sha1_init(struct crypto_tfm *tfm)
{
return omap_sham_cra_init_alg(tfm, "sha1");
}
static int omap_sham_cra_sha224_init(struct crypto_tfm *tfm)
{
return omap_sham_cra_init_alg(tfm, "sha224");
}
static int omap_sham_cra_sha256_init(struct crypto_tfm *tfm)
{
return omap_sham_cra_init_alg(tfm, "sha256");
}
static int omap_sham_cra_md5_init(struct crypto_tfm *tfm)
{
return omap_sham_cra_init_alg(tfm, "md5");
}
static int omap_sham_cra_sha384_init(struct crypto_tfm *tfm)
{
return omap_sham_cra_init_alg(tfm, "sha384");
}
static int omap_sham_cra_sha512_init(struct crypto_tfm *tfm)
{
return omap_sham_cra_init_alg(tfm, "sha512");
}
static void omap_sham_cra_exit(struct crypto_tfm *tfm)
{
struct omap_sham_ctx *tctx = crypto_tfm_ctx(tfm);
crypto_free_shash(tctx->fallback);
tctx->fallback = NULL;
if (tctx->flags & BIT(FLAGS_HMAC)) {
struct omap_sham_hmac_ctx *bctx = tctx->base;
crypto_free_shash(bctx->shash);
}
}
static int omap_sham_export(struct ahash_request *req, void *out)
{
struct omap_sham_reqctx *rctx = ahash_request_ctx(req);
memcpy(out, rctx, sizeof(*rctx) + rctx->bufcnt);
return 0;
}
static int omap_sham_import(struct ahash_request *req, const void *in)
{
struct omap_sham_reqctx *rctx = ahash_request_ctx(req);
const struct omap_sham_reqctx *ctx_in = in;
memcpy(rctx, in, sizeof(*rctx) + ctx_in->bufcnt);
return 0;
}
static struct ahash_alg algs_sha1_md5[] = {
{
.init = omap_sham_init,
.update = omap_sham_update,
.final = omap_sham_final,
.finup = omap_sham_finup,
.digest = omap_sham_digest,
.halg.digestsize = SHA1_DIGEST_SIZE,
.halg.base = {
.cra_name = "sha1",
.cra_driver_name = "omap-sha1",
.cra_priority = 400,
.cra_flags = CRYPTO_ALG_KERN_DRIVER_ONLY |
CRYPTO_ALG_ASYNC |
CRYPTO_ALG_NEED_FALLBACK,
.cra_blocksize = SHA1_BLOCK_SIZE,
.cra_ctxsize = sizeof(struct omap_sham_ctx),
.cra_alignmask = OMAP_ALIGN_MASK,
.cra_module = THIS_MODULE,
.cra_init = omap_sham_cra_init,
.cra_exit = omap_sham_cra_exit,
}
},
{
.init = omap_sham_init,
.update = omap_sham_update,
.final = omap_sham_final,
.finup = omap_sham_finup,
.digest = omap_sham_digest,
.halg.digestsize = MD5_DIGEST_SIZE,
.halg.base = {
.cra_name = "md5",
.cra_driver_name = "omap-md5",
.cra_priority = 400,
.cra_flags = CRYPTO_ALG_KERN_DRIVER_ONLY |
CRYPTO_ALG_ASYNC |
CRYPTO_ALG_NEED_FALLBACK,
.cra_blocksize = SHA1_BLOCK_SIZE,
.cra_ctxsize = sizeof(struct omap_sham_ctx),
.cra_alignmask = OMAP_ALIGN_MASK,
.cra_module = THIS_MODULE,
.cra_init = omap_sham_cra_init,
.cra_exit = omap_sham_cra_exit,
}
},
{
.init = omap_sham_init,
.update = omap_sham_update,
.final = omap_sham_final,
.finup = omap_sham_finup,
.digest = omap_sham_digest,
.setkey = omap_sham_setkey,
.halg.digestsize = SHA1_DIGEST_SIZE,
.halg.base = {
.cra_name = "hmac(sha1)",
.cra_driver_name = "omap-hmac-sha1",
.cra_priority = 400,
.cra_flags = CRYPTO_ALG_KERN_DRIVER_ONLY |
CRYPTO_ALG_ASYNC |
CRYPTO_ALG_NEED_FALLBACK,
.cra_blocksize = SHA1_BLOCK_SIZE,
.cra_ctxsize = sizeof(struct omap_sham_ctx) +
sizeof(struct omap_sham_hmac_ctx),
.cra_alignmask = OMAP_ALIGN_MASK,
.cra_module = THIS_MODULE,
.cra_init = omap_sham_cra_sha1_init,
.cra_exit = omap_sham_cra_exit,
}
},
{
.init = omap_sham_init,
.update = omap_sham_update,
.final = omap_sham_final,
.finup = omap_sham_finup,
.digest = omap_sham_digest,
.setkey = omap_sham_setkey,
.halg.digestsize = MD5_DIGEST_SIZE,
.halg.base = {
.cra_name = "hmac(md5)",
.cra_driver_name = "omap-hmac-md5",
.cra_priority = 400,
.cra_flags = CRYPTO_ALG_KERN_DRIVER_ONLY |
CRYPTO_ALG_ASYNC |
CRYPTO_ALG_NEED_FALLBACK,
.cra_blocksize = SHA1_BLOCK_SIZE,
.cra_ctxsize = sizeof(struct omap_sham_ctx) +
sizeof(struct omap_sham_hmac_ctx),
.cra_alignmask = OMAP_ALIGN_MASK,
.cra_module = THIS_MODULE,
.cra_init = omap_sham_cra_md5_init,
.cra_exit = omap_sham_cra_exit,
}
}
};
/* OMAP4 has some algs in addition to what OMAP2 has */
static struct ahash_alg algs_sha224_sha256[] = {
{
.init = omap_sham_init,
.update = omap_sham_update,
.final = omap_sham_final,
.finup = omap_sham_finup,
.digest = omap_sham_digest,
.halg.digestsize = SHA224_DIGEST_SIZE,
.halg.base = {
.cra_name = "sha224",
.cra_driver_name = "omap-sha224",
.cra_priority = 400,
.cra_flags = CRYPTO_ALG_KERN_DRIVER_ONLY |
CRYPTO_ALG_ASYNC |
CRYPTO_ALG_NEED_FALLBACK,
.cra_blocksize = SHA224_BLOCK_SIZE,
.cra_ctxsize = sizeof(struct omap_sham_ctx),
.cra_alignmask = OMAP_ALIGN_MASK,
.cra_module = THIS_MODULE,
.cra_init = omap_sham_cra_init,
.cra_exit = omap_sham_cra_exit,
}
},
{
.init = omap_sham_init,
.update = omap_sham_update,
.final = omap_sham_final,
.finup = omap_sham_finup,
.digest = omap_sham_digest,
.halg.digestsize = SHA256_DIGEST_SIZE,
.halg.base = {
.cra_name = "sha256",
.cra_driver_name = "omap-sha256",
.cra_priority = 400,
.cra_flags = CRYPTO_ALG_KERN_DRIVER_ONLY |
CRYPTO_ALG_ASYNC |
CRYPTO_ALG_NEED_FALLBACK,
.cra_blocksize = SHA256_BLOCK_SIZE,
.cra_ctxsize = sizeof(struct omap_sham_ctx),
.cra_alignmask = OMAP_ALIGN_MASK,
.cra_module = THIS_MODULE,
.cra_init = omap_sham_cra_init,
.cra_exit = omap_sham_cra_exit,
}
},
{
.init = omap_sham_init,
.update = omap_sham_update,
.final = omap_sham_final,
.finup = omap_sham_finup,
.digest = omap_sham_digest,
.setkey = omap_sham_setkey,
.halg.digestsize = SHA224_DIGEST_SIZE,
.halg.base = {
.cra_name = "hmac(sha224)",
.cra_driver_name = "omap-hmac-sha224",
.cra_priority = 400,
.cra_flags = CRYPTO_ALG_KERN_DRIVER_ONLY |
CRYPTO_ALG_ASYNC |
CRYPTO_ALG_NEED_FALLBACK,
.cra_blocksize = SHA224_BLOCK_SIZE,
.cra_ctxsize = sizeof(struct omap_sham_ctx) +
sizeof(struct omap_sham_hmac_ctx),
.cra_alignmask = OMAP_ALIGN_MASK,
.cra_module = THIS_MODULE,
.cra_init = omap_sham_cra_sha224_init,
.cra_exit = omap_sham_cra_exit,
}
},
{
.init = omap_sham_init,
.update = omap_sham_update,
.final = omap_sham_final,
.finup = omap_sham_finup,
.digest = omap_sham_digest,
.setkey = omap_sham_setkey,
.halg.digestsize = SHA256_DIGEST_SIZE,
.halg.base = {
.cra_name = "hmac(sha256)",
.cra_driver_name = "omap-hmac-sha256",
.cra_priority = 400,
.cra_flags = CRYPTO_ALG_KERN_DRIVER_ONLY |
CRYPTO_ALG_ASYNC |
CRYPTO_ALG_NEED_FALLBACK,
.cra_blocksize = SHA256_BLOCK_SIZE,
.cra_ctxsize = sizeof(struct omap_sham_ctx) +
sizeof(struct omap_sham_hmac_ctx),
.cra_alignmask = OMAP_ALIGN_MASK,
.cra_module = THIS_MODULE,
.cra_init = omap_sham_cra_sha256_init,
.cra_exit = omap_sham_cra_exit,
}
},
};
static struct ahash_alg algs_sha384_sha512[] = {
{
.init = omap_sham_init,
.update = omap_sham_update,
.final = omap_sham_final,
.finup = omap_sham_finup,
.digest = omap_sham_digest,
.halg.digestsize = SHA384_DIGEST_SIZE,
.halg.base = {
.cra_name = "sha384",
.cra_driver_name = "omap-sha384",
.cra_priority = 400,
.cra_flags = CRYPTO_ALG_KERN_DRIVER_ONLY |
CRYPTO_ALG_ASYNC |
CRYPTO_ALG_NEED_FALLBACK,
.cra_blocksize = SHA384_BLOCK_SIZE,
.cra_ctxsize = sizeof(struct omap_sham_ctx),
.cra_alignmask = OMAP_ALIGN_MASK,
.cra_module = THIS_MODULE,
.cra_init = omap_sham_cra_init,
.cra_exit = omap_sham_cra_exit,
}
},
{
.init = omap_sham_init,
.update = omap_sham_update,
.final = omap_sham_final,
.finup = omap_sham_finup,
.digest = omap_sham_digest,
.halg.digestsize = SHA512_DIGEST_SIZE,
.halg.base = {
.cra_name = "sha512",
.cra_driver_name = "omap-sha512",
.cra_priority = 400,
.cra_flags = CRYPTO_ALG_KERN_DRIVER_ONLY |
CRYPTO_ALG_ASYNC |
CRYPTO_ALG_NEED_FALLBACK,
.cra_blocksize = SHA512_BLOCK_SIZE,
.cra_ctxsize = sizeof(struct omap_sham_ctx),
.cra_alignmask = OMAP_ALIGN_MASK,
.cra_module = THIS_MODULE,
.cra_init = omap_sham_cra_init,
.cra_exit = omap_sham_cra_exit,
}
},
{
.init = omap_sham_init,
.update = omap_sham_update,
.final = omap_sham_final,
.finup = omap_sham_finup,
.digest = omap_sham_digest,
.setkey = omap_sham_setkey,
.halg.digestsize = SHA384_DIGEST_SIZE,
.halg.base = {
.cra_name = "hmac(sha384)",
.cra_driver_name = "omap-hmac-sha384",
.cra_priority = 400,
.cra_flags = CRYPTO_ALG_KERN_DRIVER_ONLY |
CRYPTO_ALG_ASYNC |
CRYPTO_ALG_NEED_FALLBACK,
.cra_blocksize = SHA384_BLOCK_SIZE,
.cra_ctxsize = sizeof(struct omap_sham_ctx) +
sizeof(struct omap_sham_hmac_ctx),
.cra_alignmask = OMAP_ALIGN_MASK,
.cra_module = THIS_MODULE,
.cra_init = omap_sham_cra_sha384_init,
.cra_exit = omap_sham_cra_exit,
}
},
{
.init = omap_sham_init,
.update = omap_sham_update,
.final = omap_sham_final,
.finup = omap_sham_finup,
.digest = omap_sham_digest,
.setkey = omap_sham_setkey,
.halg.digestsize = SHA512_DIGEST_SIZE,
.halg.base = {
.cra_name = "hmac(sha512)",
.cra_driver_name = "omap-hmac-sha512",
.cra_priority = 400,
.cra_flags = CRYPTO_ALG_KERN_DRIVER_ONLY |
CRYPTO_ALG_ASYNC |
CRYPTO_ALG_NEED_FALLBACK,
.cra_blocksize = SHA512_BLOCK_SIZE,
.cra_ctxsize = sizeof(struct omap_sham_ctx) +
sizeof(struct omap_sham_hmac_ctx),
.cra_alignmask = OMAP_ALIGN_MASK,
.cra_module = THIS_MODULE,
.cra_init = omap_sham_cra_sha512_init,
.cra_exit = omap_sham_cra_exit,
}
},
};
static void omap_sham_done_task(unsigned long data)
{
struct omap_sham_dev *dd = (struct omap_sham_dev *)data;
int err = 0;
dev_dbg(dd->dev, "%s: flags=%lx\n", __func__, dd->flags);
if (test_bit(FLAGS_CPU, &dd->flags)) {
if (test_and_clear_bit(FLAGS_OUTPUT_READY, &dd->flags))
goto finish;
} else if (test_bit(FLAGS_DMA_READY, &dd->flags)) {
if (test_and_clear_bit(FLAGS_DMA_ACTIVE, &dd->flags)) {
omap_sham_update_dma_stop(dd);
if (dd->err) {
err = dd->err;
goto finish;
}
}
if (test_and_clear_bit(FLAGS_OUTPUT_READY, &dd->flags)) {
/* hash or semi-hash ready */
clear_bit(FLAGS_DMA_READY, &dd->flags);
goto finish;
}
}
return;
finish:
dev_dbg(dd->dev, "update done: err: %d\n", err);
/* finish curent request */
omap_sham_finish_req(dd->req, err);
}
static irqreturn_t omap_sham_irq_common(struct omap_sham_dev *dd)
{
set_bit(FLAGS_OUTPUT_READY, &dd->flags);
tasklet_schedule(&dd->done_task);
return IRQ_HANDLED;
}
static irqreturn_t omap_sham_irq_omap2(int irq, void *dev_id)
{
struct omap_sham_dev *dd = dev_id;
if (unlikely(test_bit(FLAGS_FINAL, &dd->flags)))
/* final -> allow device to go to power-saving mode */
omap_sham_write_mask(dd, SHA_REG_CTRL, 0, SHA_REG_CTRL_LENGTH);
omap_sham_write_mask(dd, SHA_REG_CTRL, SHA_REG_CTRL_OUTPUT_READY,
SHA_REG_CTRL_OUTPUT_READY);
omap_sham_read(dd, SHA_REG_CTRL);
return omap_sham_irq_common(dd);
}
static irqreturn_t omap_sham_irq_omap4(int irq, void *dev_id)
{
struct omap_sham_dev *dd = dev_id;
omap_sham_write_mask(dd, SHA_REG_MASK(dd), 0, SHA_REG_MASK_IT_EN);
return omap_sham_irq_common(dd);
}
static struct omap_sham_algs_info omap_sham_algs_info_omap2[] = {
{
.algs_list = algs_sha1_md5,
.size = ARRAY_SIZE(algs_sha1_md5),
},
};
static const struct omap_sham_pdata omap_sham_pdata_omap2 = {
.algs_info = omap_sham_algs_info_omap2,
.algs_info_size = ARRAY_SIZE(omap_sham_algs_info_omap2),
.flags = BIT(FLAGS_BE32_SHA1),
.digest_size = SHA1_DIGEST_SIZE,
.copy_hash = omap_sham_copy_hash_omap2,
.write_ctrl = omap_sham_write_ctrl_omap2,
.trigger = omap_sham_trigger_omap2,
.poll_irq = omap_sham_poll_irq_omap2,
.intr_hdlr = omap_sham_irq_omap2,
.idigest_ofs = 0x00,
.din_ofs = 0x1c,
.digcnt_ofs = 0x14,
.rev_ofs = 0x5c,
.mask_ofs = 0x60,
.sysstatus_ofs = 0x64,
.major_mask = 0xf0,
.major_shift = 4,
.minor_mask = 0x0f,
.minor_shift = 0,
};
#ifdef CONFIG_OF
static struct omap_sham_algs_info omap_sham_algs_info_omap4[] = {
{
.algs_list = algs_sha1_md5,
.size = ARRAY_SIZE(algs_sha1_md5),
},
{
.algs_list = algs_sha224_sha256,
.size = ARRAY_SIZE(algs_sha224_sha256),
},
};
static const struct omap_sham_pdata omap_sham_pdata_omap4 = {
.algs_info = omap_sham_algs_info_omap4,
.algs_info_size = ARRAY_SIZE(omap_sham_algs_info_omap4),
.flags = BIT(FLAGS_AUTO_XOR),
.digest_size = SHA256_DIGEST_SIZE,
.copy_hash = omap_sham_copy_hash_omap4,
.write_ctrl = omap_sham_write_ctrl_omap4,
.trigger = omap_sham_trigger_omap4,
.poll_irq = omap_sham_poll_irq_omap4,
.intr_hdlr = omap_sham_irq_omap4,
.idigest_ofs = 0x020,
.odigest_ofs = 0x0,
.din_ofs = 0x080,
.digcnt_ofs = 0x040,
.rev_ofs = 0x100,
.mask_ofs = 0x110,
.sysstatus_ofs = 0x114,
.mode_ofs = 0x44,
.length_ofs = 0x48,
.major_mask = 0x0700,
.major_shift = 8,
.minor_mask = 0x003f,
.minor_shift = 0,
};
static struct omap_sham_algs_info omap_sham_algs_info_omap5[] = {
{
.algs_list = algs_sha1_md5,
.size = ARRAY_SIZE(algs_sha1_md5),
},
{
.algs_list = algs_sha224_sha256,
.size = ARRAY_SIZE(algs_sha224_sha256),
},
{
.algs_list = algs_sha384_sha512,
.size = ARRAY_SIZE(algs_sha384_sha512),
},
};
static const struct omap_sham_pdata omap_sham_pdata_omap5 = {
.algs_info = omap_sham_algs_info_omap5,
.algs_info_size = ARRAY_SIZE(omap_sham_algs_info_omap5),
.flags = BIT(FLAGS_AUTO_XOR),
.digest_size = SHA512_DIGEST_SIZE,
.copy_hash = omap_sham_copy_hash_omap4,
.write_ctrl = omap_sham_write_ctrl_omap4,
.trigger = omap_sham_trigger_omap4,
.poll_irq = omap_sham_poll_irq_omap4,
.intr_hdlr = omap_sham_irq_omap4,
.idigest_ofs = 0x240,
.odigest_ofs = 0x200,
.din_ofs = 0x080,
.digcnt_ofs = 0x280,
.rev_ofs = 0x100,
.mask_ofs = 0x110,
.sysstatus_ofs = 0x114,
.mode_ofs = 0x284,
.length_ofs = 0x288,
.major_mask = 0x0700,
.major_shift = 8,
.minor_mask = 0x003f,
.minor_shift = 0,
};
static const struct of_device_id omap_sham_of_match[] = {
{
.compatible = "ti,omap2-sham",
.data = &omap_sham_pdata_omap2,
},
{
.compatible = "ti,omap3-sham",
.data = &omap_sham_pdata_omap2,
},
{
.compatible = "ti,omap4-sham",
.data = &omap_sham_pdata_omap4,
},
{
.compatible = "ti,omap5-sham",
.data = &omap_sham_pdata_omap5,
},
{},
};
MODULE_DEVICE_TABLE(of, omap_sham_of_match);
static int omap_sham_get_res_of(struct omap_sham_dev *dd,
struct device *dev, struct resource *res)
{
struct device_node *node = dev->of_node;
int err = 0;
dd->pdata = of_device_get_match_data(dev);
if (!dd->pdata) {
dev_err(dev, "no compatible OF match\n");
err = -EINVAL;
goto err;
}
err = of_address_to_resource(node, 0, res);
if (err < 0) {
dev_err(dev, "can't translate OF node address\n");
err = -EINVAL;
goto err;
}
dd->irq = irq_of_parse_and_map(node, 0);
if (!dd->irq) {
dev_err(dev, "can't translate OF irq value\n");
err = -EINVAL;
goto err;
}
err:
return err;
}
#else
static const struct of_device_id omap_sham_of_match[] = {
{},
};
static int omap_sham_get_res_of(struct omap_sham_dev *dd,
struct device *dev, struct resource *res)
{
return -EINVAL;
}
#endif
static int omap_sham_get_res_pdev(struct omap_sham_dev *dd,
struct platform_device *pdev, struct resource *res)
{
struct device *dev = &pdev->dev;
struct resource *r;
int err = 0;
/* Get the base address */
r = platform_get_resource(pdev, IORESOURCE_MEM, 0);
if (!r) {
dev_err(dev, "no MEM resource info\n");
err = -ENODEV;
goto err;
}
memcpy(res, r, sizeof(*res));
/* Get the IRQ */
dd->irq = platform_get_irq(pdev, 0);
if (dd->irq < 0) {
err = dd->irq;
goto err;
}
/* Only OMAP2/3 can be non-DT */
dd->pdata = &omap_sham_pdata_omap2;
err:
return err;
}
static ssize_t fallback_show(struct device *dev, struct device_attribute *attr,
char *buf)
{
struct omap_sham_dev *dd = dev_get_drvdata(dev);
return sprintf(buf, "%d\n", dd->fallback_sz);
}
static ssize_t fallback_store(struct device *dev, struct device_attribute *attr,
const char *buf, size_t size)
{
struct omap_sham_dev *dd = dev_get_drvdata(dev);
ssize_t status;
long value;
status = kstrtol(buf, 0, &value);
if (status)
return status;
/* HW accelerator only works with buffers > 9 */
if (value < 9) {
dev_err(dev, "minimum fallback size 9\n");
return -EINVAL;
}
dd->fallback_sz = value;
return size;
}
static ssize_t queue_len_show(struct device *dev, struct device_attribute *attr,
char *buf)
{
struct omap_sham_dev *dd = dev_get_drvdata(dev);
return sprintf(buf, "%d\n", dd->queue.max_qlen);
}
static ssize_t queue_len_store(struct device *dev,
struct device_attribute *attr, const char *buf,
size_t size)
{
struct omap_sham_dev *dd = dev_get_drvdata(dev);
ssize_t status;
long value;
status = kstrtol(buf, 0, &value);
if (status)
return status;
if (value < 1)
return -EINVAL;
/*
* Changing the queue size in fly is safe, if size becomes smaller
* than current size, it will just not accept new entries until
* it has shrank enough.
*/
dd->queue.max_qlen = value;
return size;
}
static DEVICE_ATTR_RW(queue_len);
static DEVICE_ATTR_RW(fallback);
static struct attribute *omap_sham_attrs[] = {
&dev_attr_queue_len.attr,
&dev_attr_fallback.attr,
NULL,
};
static struct attribute_group omap_sham_attr_group = {
.attrs = omap_sham_attrs,
};
static int omap_sham_probe(struct platform_device *pdev)
{
struct omap_sham_dev *dd;
struct device *dev = &pdev->dev;
struct resource res;
dma_cap_mask_t mask;
int err, i, j;
u32 rev;
dd = devm_kzalloc(dev, sizeof(struct omap_sham_dev), GFP_KERNEL);
if (dd == NULL) {
dev_err(dev, "unable to alloc data struct.\n");
err = -ENOMEM;
goto data_err;
}
dd->dev = dev;
platform_set_drvdata(pdev, dd);
INIT_LIST_HEAD(&dd->list);
tasklet_init(&dd->done_task, omap_sham_done_task, (unsigned long)dd);
crypto_init_queue(&dd->queue, OMAP_SHAM_QUEUE_LENGTH);
err = (dev->of_node) ? omap_sham_get_res_of(dd, dev, &res) :
omap_sham_get_res_pdev(dd, pdev, &res);
if (err)
goto data_err;
dd->io_base = devm_ioremap_resource(dev, &res);
if (IS_ERR(dd->io_base)) {
err = PTR_ERR(dd->io_base);
goto data_err;
}
dd->phys_base = res.start;
err = devm_request_irq(dev, dd->irq, dd->pdata->intr_hdlr,
IRQF_TRIGGER_NONE, dev_name(dev), dd);
if (err) {
dev_err(dev, "unable to request irq %d, err = %d\n",
dd->irq, err);
goto data_err;
}
dma_cap_zero(mask);
dma_cap_set(DMA_SLAVE, mask);
dd->dma_lch = dma_request_chan(dev, "rx");
if (IS_ERR(dd->dma_lch)) {
err = PTR_ERR(dd->dma_lch);
if (err == -EPROBE_DEFER)
goto data_err;
dd->polling_mode = 1;
dev_dbg(dev, "using polling mode instead of dma\n");
}
dd->flags |= dd->pdata->flags;
sham.flags |= dd->pdata->flags;
pm_runtime_use_autosuspend(dev);
pm_runtime_set_autosuspend_delay(dev, DEFAULT_AUTOSUSPEND_DELAY);
dd->fallback_sz = OMAP_SHA_DMA_THRESHOLD;
pm_runtime_enable(dev);
pm_runtime_irq_safe(dev);
err = pm_runtime_get_sync(dev);
if (err < 0) {
dev_err(dev, "failed to get sync: %d\n", err);
goto err_pm;
}
rev = omap_sham_read(dd, SHA_REG_REV(dd));
pm_runtime_put_sync(&pdev->dev);
dev_info(dev, "hw accel on OMAP rev %u.%u\n",
(rev & dd->pdata->major_mask) >> dd->pdata->major_shift,
(rev & dd->pdata->minor_mask) >> dd->pdata->minor_shift);
spin_lock(&sham.lock);
list_add_tail(&dd->list, &sham.dev_list);
spin_unlock(&sham.lock);
dd->engine = crypto_engine_alloc_init(dev, 1);
if (!dd->engine) {
err = -ENOMEM;
goto err_engine;
}
err = crypto_engine_start(dd->engine);
if (err)
goto err_engine_start;
for (i = 0; i < dd->pdata->algs_info_size; i++) {
if (dd->pdata->algs_info[i].registered)
break;
for (j = 0; j < dd->pdata->algs_info[i].size; j++) {
struct ahash_alg *alg;
alg = &dd->pdata->algs_info[i].algs_list[j];
alg->export = omap_sham_export;
alg->import = omap_sham_import;
alg->halg.statesize = sizeof(struct omap_sham_reqctx) +
BUFLEN;
err = crypto_register_ahash(alg);
if (err)
goto err_algs;
dd->pdata->algs_info[i].registered++;
}
}
err = sysfs_create_group(&dev->kobj, &omap_sham_attr_group);
if (err) {
dev_err(dev, "could not create sysfs device attrs\n");
goto err_algs;
}
return 0;
err_algs:
for (i = dd->pdata->algs_info_size - 1; i >= 0; i--)
for (j = dd->pdata->algs_info[i].registered - 1; j >= 0; j--)
crypto_unregister_ahash(
&dd->pdata->algs_info[i].algs_list[j]);
err_engine_start:
crypto_engine_exit(dd->engine);
err_engine:
spin_lock(&sham.lock);
list_del(&dd->list);
spin_unlock(&sham.lock);
err_pm:
pm_runtime_disable(dev);
if (!dd->polling_mode)
dma_release_channel(dd->dma_lch);
data_err:
dev_err(dev, "initialization failed.\n");
return err;
}
static int omap_sham_remove(struct platform_device *pdev)
{
struct omap_sham_dev *dd;
int i, j;
dd = platform_get_drvdata(pdev);
if (!dd)
return -ENODEV;
spin_lock(&sham.lock);
list_del(&dd->list);
spin_unlock(&sham.lock);
for (i = dd->pdata->algs_info_size - 1; i >= 0; i--)
for (j = dd->pdata->algs_info[i].registered - 1; j >= 0; j--) {
crypto_unregister_ahash(
&dd->pdata->algs_info[i].algs_list[j]);
dd->pdata->algs_info[i].registered--;
}
tasklet_kill(&dd->done_task);
pm_runtime_disable(&pdev->dev);
if (!dd->polling_mode)
dma_release_channel(dd->dma_lch);
sysfs_remove_group(&dd->dev->kobj, &omap_sham_attr_group);
return 0;
}
#ifdef CONFIG_PM_SLEEP
static int omap_sham_suspend(struct device *dev)
{
pm_runtime_put_sync(dev);
return 0;
}
static int omap_sham_resume(struct device *dev)
{
int err = pm_runtime_resume_and_get(dev);
if (err < 0) {
dev_err(dev, "failed to get sync: %d\n", err);
return err;
}
return 0;
}
#endif
static SIMPLE_DEV_PM_OPS(omap_sham_pm_ops, omap_sham_suspend, omap_sham_resume);
static struct platform_driver omap_sham_driver = {
.probe = omap_sham_probe,
.remove = omap_sham_remove,
.driver = {
.name = "omap-sham",
.pm = &omap_sham_pm_ops,
.of_match_table = omap_sham_of_match,
},
};
module_platform_driver(omap_sham_driver);
MODULE_DESCRIPTION("OMAP SHA1/MD5 hw acceleration support.");
MODULE_LICENSE("GPL v2");
MODULE_AUTHOR("Dmitry Kasatkin");
MODULE_ALIAS("platform:omap-sham");
|
171476.c | #include <math.h>
#include <stdio.h>
#define TRUE 1
#define FALSE 0
// Precondition
// (and (<= 4 x1 159/25) (<= 4 x2 159/25) (<= 4 x3 159/25) (<= 4 x4 159/25) (<= 4 x5 159/25) (<= 4 x6 159/25))
double ex0(double x1, double x2, double x3, double x4, double x5, double x6) {
return (((((x2 * x5) + (x3 * x6)) - (x2 * x3)) - (x5 * x6)) + (x1 * (((((-x1 + x2) + x3) - x4) + x5) + x6)));
}
int main() {
FILE *fp;
fp = fopen("kepler0_posit.txt", "w+");
double x1, x2, x3, x4, x5, x6;
for (x1 = 4.; x1 <= 159./25.; x1 += 0.3)
for (x2 = 4.; x2 <= 159./25.; x2 += 0.3)
for (x3 = 4.; x3 <= 159./25.; x3 += 0.3)
for (x4 = 4.; x4 <= 159./25.; x4 += 0.3)
for (x5 = 4.; x5 <= 159./25.; x5 += 0.3)
for (x6 = 4.; x6 <= 159./25.; x6 += 0.3)
fprintf(fp, "%.20g\n", ex0(x1, x2, x3, x4, x5, x6));
fclose(fp);
} |
156330.c | /*************************************************************************
* *
* YAP Prolog *
* *
* Yap Prolog was developed at NCCUP - Universidade do Porto *
* *
* Copyright L.Damas, V.S.Costa and Universidade do Porto 1985-1997 *
* *
**************************************************************************
* *
* File: heapgc.c *
* Last rev: *
* mods: *
* comments: Global Stack garbage collector *
* *
*************************************************************************/
#ifdef SCCS
static char SccsId[] = "%W% %G%";
#endif /* SCCS */
#include "absmi.h"
#include "yapio.h"
#include "alloc.h"
#include "attvar.h"
#if !defined(TABLING)
//#define EASY_SHUNTING 1
#endif /* !TABLING */
#define HYBRID_SCHEME 1
#define DEBUG_printf0(A,B)
#define DEBUG_printf1(A,B,C)
#define DEBUG_printf20(A,B)
#define DEBUG_printf21(A,B,C)
/* global variables for garbage collection */
STATIC_PROTO(Int p_inform_gc, ( CACHE_TYPE1 ));
STATIC_PROTO(Int p_gc, ( CACHE_TYPE1 ));
STATIC_PROTO(void marking_phase, (tr_fr_ptr, CELL *, yamop * CACHE_TYPE));
STATIC_PROTO(void compaction_phase, (tr_fr_ptr, CELL *, yamop * CACHE_TYPE));
STATIC_PROTO(void init_dbtable, (tr_fr_ptr CACHE_TYPE));
STATIC_PROTO(void mark_external_reference, (CELL * CACHE_TYPE));
STATIC_PROTO(void mark_db_fixed, (CELL * CACHE_TYPE));
STATIC_PROTO(void mark_regs, (tr_fr_ptr CACHE_TYPE));
STATIC_PROTO(void mark_trail, (tr_fr_ptr, tr_fr_ptr, CELL *, choiceptr CACHE_TYPE));
STATIC_PROTO(void mark_environments, (CELL *, OPREG, CELL * CACHE_TYPE));
STATIC_PROTO(void mark_choicepoints, (choiceptr, tr_fr_ptr, int CACHE_TYPE));
STATIC_PROTO(void into_relocation_chain, (CELL *, CELL * CACHE_TYPE));
STATIC_PROTO(void sweep_trail, (choiceptr, tr_fr_ptr CACHE_TYPE));
STATIC_PROTO(void sweep_environments, (CELL *, OPREG, CELL * CACHE_TYPE));
STATIC_PROTO(void sweep_choicepoints, (choiceptr CACHE_TYPE));
STATIC_PROTO(void compact_heap, ( CACHE_TYPE1 ));
STATIC_PROTO(void update_relocation_chain, (CELL *, CELL * CACHE_TYPE));
STATIC_PROTO(int is_gc_verbose, (void));
STATIC_PROTO(int is_gc_very_verbose, (void));
STATIC_PROTO(void LeaveGCMode, ( CACHE_TYPE1 ));
#ifdef EASY_SHUNTING
STATIC_PROTO(void set_conditionals, (tr_fr_ptr CACHE_TYPE));
#endif /* EASY_SHUNTING */
#include "heapgc.h"
typedef struct gc_mark_continuation {
CELL *v;
int nof;
} cont;
/* straightforward binary tree scheme that, given a key, finds a
matching dbref */
typedef enum {
db_entry,
cl_entry,
lcl_entry,
li_entry,
dcl_entry
} db_entry_type;
typedef struct db_entry {
CODEADDR val;
db_entry_type db_type;
int in_use;
struct db_entry *left;
CODEADDR lim;
struct db_entry *right;
} *dbentry;
typedef struct RB_red_blk_node {
CODEADDR key;
CODEADDR lim;
db_entry_type db_type;
int in_use;
int red; /* if red=0 then the node is black */
struct RB_red_blk_node* left;
struct RB_red_blk_node* right;
struct RB_red_blk_node* parent;
} rb_red_blk_node;
#ifdef EASY_SHUNTING
#undef LOCAL_cont_top0
#define LOCAL_cont_top0 (cont *)LOCAL_sTR
#endif
/* support for hybrid garbage collection scheme */
static void
gc_growtrail(int committed, tr_fr_ptr begsTR, cont *old_cont_top0 USES_REGS)
{
UInt sz = LOCAL_TrailTop-(ADDR)LOCAL_OldTR;
/* ask for double the size */
sz = 2*sz;
if (!Yap_growtrail(sz, TRUE)) {
#ifdef EASY_SHUNTING
if (begsTR) {
LOCAL_sTR = (tr_fr_ptr)old_cont_top0;
while (begsTR != NULL) {
tr_fr_ptr newsTR = (tr_fr_ptr)TrailTerm(begsTR);
TrailTerm(LOCAL_sTR) = TrailTerm(begsTR+1);
TrailTerm(LOCAL_sTR+1) = TrailTerm(begsTR+2);
begsTR = newsTR;
LOCAL_sTR += 2;
}
}
set_conditionals(LOCAL_sTR PASS_REGS);
#endif
/* could not find more trail */
save_machine_regs();
siglongjmp(LOCAL_gc_restore, 2);
}
}
inline static void
PUSH_CONTINUATION(CELL *v, int nof USES_REGS) {
cont *x;
x = LOCAL_cont_top;
x++;
if ((ADDR)x > LOCAL_TrailTop-1024) {
gc_growtrail(TRUE, NULL, NULL PASS_REGS);
}
x->v = v;
x->nof = nof;
LOCAL_cont_top = x;
}
#define POP_CONTINUATION() { \
if (LOCAL_cont_top == LOCAL_cont_top0) \
return; \
else { \
int nof = LOCAL_cont_top->nof; \
cont *x = LOCAL_cont_top; \
\
current = x->v; \
if (nof == 1) \
LOCAL_cont_top = --x; \
else { \
x->nof = nof-1; \
x->v = current+1; \
} \
} \
goto begin; }
#ifdef HYBRID_SCHEME
inline static void
PUSH_POINTER(CELL *v USES_REGS) {
if (LOCAL_iptop >= (CELL_PTR *)ASP) return;
*LOCAL_iptop++ = v;
}
inline static void
POP_POINTER( USES_REGS1 ) {
if (LOCAL_iptop >= (CELL_PTR *)ASP) return;
--LOCAL_iptop;
}
inline static void
POPSWAP_POINTER(CELL_PTR *vp, CELL_PTR v USES_REGS) {
if (LOCAL_iptop >= (CELL_PTR *)ASP || LOCAL_iptop == vp) return;
if (*vp != v)
return;
--LOCAL_iptop;
if (vp != LOCAL_iptop)
*vp = *LOCAL_iptop;
}
/*
original code from In Hyuk Choi,
found at http://userpages.umbc.edu/~ichoi1/project/cs441.htm
*/
static inline void
exchange(CELL_PTR * b, Int i, Int j)
{
CELL *t = b[j];
b[j] = b[i];
b[i] = t;
}
static UInt
partition(CELL *a[], Int p, Int r)
{
CELL *x;
UInt i, j;
x = a[p];
i = p+1;
j = r;
while (a[j] > x && i < j) {
j--;
}
while (a[i] < x && i < j) {
i++;
}
while(i < j) {
exchange(a, i, j);
i++;
j--;
while (a[j] > x && i < j) {
j--;
}
while (a[i] < x && i < j) {
i++;
}
}
if (a[i] > x)
i--;
exchange(a, p, i);
return(i);
}
static void
insort(CELL *a[], Int p, Int q)
{
Int j;
for (j = p+1; j <= q; j ++) {
CELL *key;
Int i;
key = a[j];
i = j;
while (i > p && a[i-1] > key) {
a[i] = a[i-1];
i --;
}
a[i] = key;
}
}
static void
quicksort(CELL *a[], Int p, Int r)
{
Int q;
if (p < r) {
if (r - p < 100) {
insort(a, p, r);
return;
}
exchange(a, p, (p+r)/2);
q = partition (a, p, r);
quicksort(a, p, q-1);
quicksort(a, q + 1, r);
}
}
#else
#define PUSH_POINTER(P PASS_REGS)
#define POP_POINTER( PASS_REGS1 )
#define POPSWAP_POINTER(P)
#endif /* HYBRID_SCHEME */
#ifdef MULTI_ASSIGNMENT_VARIABLES
/*
Based in opt.mavar.h. This is a set of routines to find out if a
ma trail entry has appeared before in the same trail segment. All ma
entries for the same cell are then linked. At the end of mark_trail() only
one will remain.
*/
static inline unsigned int
GC_MAVAR_HASH(CELL *addr) {
#if SIZEOF_INT_P==8
return((((unsigned int)((CELL)(addr)))>>3)%GC_MAVARS_HASH_SIZE);
#else
return((((unsigned int)((CELL)(addr)))>>2)%GC_MAVARS_HASH_SIZE);
#endif
}
static inline gc_ma_hash_entry *
GC_ALLOC_NEW_MASPACE( USES_REGS1 )
{
gc_ma_hash_entry *new = LOCAL_gc_ma_h_top;
if ((char *)LOCAL_gc_ma_h_top > LOCAL_TrailTop-1024)
gc_growtrail(FALSE, NULL, NULL PASS_REGS);
LOCAL_gc_ma_h_top++;
LOCAL_cont_top = (cont *)LOCAL_gc_ma_h_top;
#ifdef EASY_SHUNTING
LOCAL_sTR = LOCAL_sTR0 = (tr_fr_ptr)LOCAL_cont_top;
#else
LOCAL_cont_top0 = LOCAL_cont_top;
#endif
return new;
}
static inline gc_ma_hash_entry*
gc_lookup_ma_var(CELL *addr, tr_fr_ptr trp USES_REGS) {
unsigned int i = GC_MAVAR_HASH(addr);
gc_ma_hash_entry *nptr, *optr = NULL;
if (LOCAL_gc_ma_hash_table[i].timestmp != LOCAL_gc_timestamp) {
LOCAL_gc_ma_hash_table[i].timestmp = LOCAL_gc_timestamp;
LOCAL_gc_ma_hash_table[i].addr = addr;
#if TABLING
LOCAL_gc_ma_hash_table[i].loc = trp;
LOCAL_gc_ma_hash_table[i].more = LOCAL_gc_ma_h_list;
LOCAL_gc_ma_h_list = LOCAL_gc_ma_hash_table+i;
#endif /* TABLING */
LOCAL_gc_ma_hash_table[i].next = NULL;
return NULL;
}
nptr = LOCAL_gc_ma_hash_table+i;
while (nptr) {
optr = nptr;
if (nptr->addr == addr) {
#if TABLING
/*
we're moving from oldest to more recent, so only a new entry
has the correct new value
*/
TrailVal(nptr->loc+1) = TrailVal(trp+1);
#endif /* TABLING */
return nptr;
}
nptr = nptr->next;
}
nptr = GC_ALLOC_NEW_MASPACE( PASS_REGS1 );
optr->next = nptr;
nptr->addr = addr;
#if TABLING
nptr->loc = trp;
nptr->more = LOCAL_gc_ma_h_list;
#endif /* TABLING */
nptr->next = NULL;
LOCAL_gc_ma_h_list = nptr;
return NULL;
}
static inline void
GC_NEW_MAHASH(gc_ma_hash_entry *top USES_REGS) {
UInt time = ++LOCAL_gc_timestamp;
LOCAL_gc_ma_h_list = NULL;
if (time == 0) {
unsigned int i;
/* damn, we overflowed */
for (i = 0; i < GC_MAVARS_HASH_SIZE; i++)
LOCAL_gc_ma_hash_table[i].timestmp = 0L;
time = ++LOCAL_gc_timestamp;
}
LOCAL_gc_ma_h_top = top;
LOCAL_cont_top = (cont *)LOCAL_gc_ma_h_top;
#ifdef EASY_SHUNTING
LOCAL_sTR = (tr_fr_ptr)LOCAL_cont_top;
#else
LOCAL_cont_top0 = LOCAL_cont_top;
#endif
}
#endif
/* find all accessible objects on the heap and squeeze out all the rest */
static void
check_pr_trail(tr_fr_ptr trp USES_REGS)
{
if ((tr_fr_ptr)LOCAL_TrailTop-TR < 1024) {
if (!Yap_growtrail(0, TRUE) || TRUE) {
/* could not find more trail */
save_machine_regs();
siglongjmp(LOCAL_gc_restore, 2);
}
}
}
/* push the active registers onto the trail for inclusion during gc */
static void
push_registers(Int num_regs, yamop *nextop USES_REGS)
{
int i;
StaticArrayEntry *sal = LOCAL_StaticArrays;
/* push array entries first */
ArrayEntry *al = LOCAL_DynamicArrays;
GlobalEntry *gl = LOCAL_GlobalVariables;
TrailTerm(TR++) = LOCAL_GlobalArena;
while (al) {
check_pr_trail(TR PASS_REGS);
TrailTerm(TR++) = al->ValueOfVE;
al = al->NextAE;
}
while (gl) {
check_pr_trail(TR PASS_REGS);
TrailTerm(TR++) = gl->global;
gl = gl->NextGE;
}
while (sal) {
if (sal->ArrayType == array_of_nb_terms) {
UInt arity = -sal->ArrayEArity, i;
for (i=0; i < arity; i++) {
Term tlive = sal->ValueOfVE.lterms[i].tlive;
if (!IsVarTerm(tlive) || !IsUnboundVar(&sal->ValueOfVE.lterms[i].tlive)) {
check_pr_trail(TR PASS_REGS);
TrailTerm(TR++) = tlive;
}
}
}
sal = sal->NextAE;
}
check_pr_trail(TR PASS_REGS);
TrailTerm(TR) = LOCAL_GcGeneration;
TR++;
TrailTerm(TR) = LOCAL_GcPhase;
TR++;
#ifdef COROUTINING
TrailTerm(TR) = LOCAL_WokenGoals;
TrailTerm(TR+1) = LOCAL_AttsMutableList;
TR += 2;
#endif
for (i = 1; i <= num_regs; i++) {
check_pr_trail(TR PASS_REGS);
TrailTerm(TR++) = (CELL) XREGS[i];
}
/* push any live registers we might have hanging around */
if (nextop->opc == Yap_opcode(_move_back) ||
nextop->opc == Yap_opcode(_skip)) {
CELL *lab = (CELL *)(nextop->u.l.l);
CELL max = lab[0];
Int curr = lab[1];
lab += 2;
if (max) {
CELL i;
for (i=0L; i <= max; i++) {
if (i == 8*CellSize) {
curr = lab[0];
lab++;
}
if (curr & 1) {
check_pr_trail(TR PASS_REGS);
TrailTerm(TR++) = XREGS[i];
}
curr >>= 1;
}
}
}
}
/* pop the corrected register values from the trail and update the registers */
static void
pop_registers(Int num_regs, yamop *nextop USES_REGS)
{
int i;
tr_fr_ptr ptr = TR;
StaticArrayEntry *sal = LOCAL_StaticArrays;
/* pop info on opaque variables */
while (LOCAL_extra_gc_cells > LOCAL_extra_gc_cells_base) {
Opaque_CallOnGCRelocate f;
CELL *ptr = LOCAL_extra_gc_cells-1;
size_t n = ptr[0], t = ptr[-1];
LOCAL_extra_gc_cells -= (n+1);
if ( (f = Yap_blob_gc_relocate_handler(t)) ) {
int out = (f)(Yap_BlobTag(t), Yap_BlobInfo(t), LOCAL_extra_gc_cells, n);
if (out < 0) {
/* error: we don't have enough room */
/* could not find more trail */
save_machine_regs();
siglongjmp(LOCAL_gc_restore, 4);
}
}
}
/* pop array entries first */
ArrayEntry *al = LOCAL_DynamicArrays;
GlobalEntry *gl = LOCAL_GlobalVariables;
LOCAL_GlobalArena = TrailTerm(ptr++);
while (al) {
al->ValueOfVE = TrailTerm(ptr++);
al = al->NextAE;
}
while (gl) {
gl->global = TrailTerm(ptr++);
gl = gl->NextGE;
}
sal = LOCAL_StaticArrays;
while (sal) {
if (sal->ArrayType == array_of_nb_terms) {
UInt arity = -sal->ArrayEArity;
for (i=0; i < arity; i++) {
Term tlive = sal->ValueOfVE.lterms[i].tlive;
if (!IsVarTerm(tlive) || !IsUnboundVar(&sal->ValueOfVE.lterms[i].tlive)) {
sal->ValueOfVE.lterms[i].tlive = TrailTerm(ptr++);
}
}
}
sal = sal->NextAE;
}
LOCAL_GcGeneration = TrailTerm(ptr++);
LOCAL_GcPhase = TrailTerm(ptr++);
#ifdef COROUTINING
#ifdef MULTI_ASSIGNMENT_VARIABLES
LOCAL_WokenGoals = TrailTerm(ptr++);
LOCAL_AttsMutableList = TrailTerm(ptr++);
#endif
#endif
for (i = 1; i <= num_regs; i++)
XREGS[i] = TrailTerm(ptr++);
/* pop any live registers we might have hanging around */
if (nextop->opc == Yap_opcode(_move_back) ||
nextop->opc == Yap_opcode(_skip)) {
CELL *lab = (CELL *)(nextop->u.l.l);
CELL max = lab[0];
Int curr = lab[1];
lab += 2;
if (max) {
CELL i;
for (i=0L; i <= max; i++) {
if (i == 8*CellSize) {
curr = lab[0];
lab++;
}
if (curr & 1) {
XREGS[i] = TrailTerm(ptr++);
}
curr >>= 1;
}
}
}
}
#if DEBUG && COUNT_CELLS_MARKED
static int
count_cells_marked(void)
{
CELL *current;
int found_marked = 0;
for (current = H - 1; current >= H0; current--) {
if (MARKED_PTR(current)) {
found_marked++;
}
}
return(found_marked);
}
#endif
static rb_red_blk_node *
RBMalloc(UInt size USES_REGS)
{
ADDR new = LOCAL_db_vec;
LOCAL_db_vec += size;
if ((ADDR)LOCAL_db_vec > LOCAL_TrailTop-1024) {
gc_growtrail(FALSE, NULL, NULL PASS_REGS);
}
return (rb_red_blk_node *)new;
}
static rb_red_blk_node *
RBTreeCreate(void) {
CACHE_REGS
rb_red_blk_node* temp;
/* see the comment in the rb_red_blk_tree structure in red_black_tree.h */
/* for information on nil and root */
temp=LOCAL_db_nil= RBMalloc(sizeof(rb_red_blk_node) PASS_REGS);
temp->parent=temp->left=temp->right=temp;
temp->red=0;
temp->key=NULL;
temp = RBMalloc(sizeof(rb_red_blk_node) PASS_REGS);
temp->parent=temp->left=temp->right=LOCAL_db_nil;
temp->key=NULL;
temp->red=0;
return temp;
}
/* This is code originally written by Emin Martinian */
/***********************************************************************/
/* FUNCTION: LeftRotate */
/**/
/* INPUTS: This takes a tree so that it can access the appropriate */
/* root and nil pointers, and the node to rotate on. */
/**/
/* OUTPUT: None */
/**/
/* Modifies Input: tree, x */
/**/
/* EFFECTS: Rotates as described in _Introduction_To_Algorithms by */
/* Cormen, Leiserson, Rivest (Chapter 14). Basically this */
/* makes the parent of x be to the left of x, x the parent of */
/* its parent before the rotation and fixes other pointers */
/* accordingly. */
/***********************************************************************/
static void
LeftRotate(rb_red_blk_node* x USES_REGS) {
rb_red_blk_node* y;
rb_red_blk_node* nil=LOCAL_db_nil;
/* I originally wrote this function to use the sentinel for */
/* nil to avoid checking for nil. However this introduces a */
/* very subtle bug because sometimes this function modifies */
/* the parent pointer of nil. This can be a problem if a */
/* function which calls LeftRotate also uses the nil sentinel */
/* and expects the nil sentinel's parent pointer to be unchanged */
/* after calling this function. For example, when RBDeleteFixUP */
/* calls LeftRotate it expects the parent pointer of nil to be */
/* unchanged. */
y=x->right;
x->right=y->left;
if (y->left != nil) y->left->parent=x; /* used to use sentinel here */
/* and do an unconditional assignment instead of testing for nil */
y->parent=x->parent;
/* instead of checking if x->parent is the root as in the book, we */
/* count on the root sentinel to implicitly take care of this case */
if( x == x->parent->left) {
x->parent->left=y;
} else {
x->parent->right=y;
}
y->left=x;
x->parent=y;
#ifdef DEBUG_ASSERT
Assert(!LOCAL_db_nil->red,"nil not red in LeftRotate");
#endif
}
/***********************************************************************/
/* FUNCTION: RighttRotate */
/**/
/* INPUTS: This takes a tree so that it can access the appropriate */
/* root and nil pointers, and the node to rotate on. */
/**/
/* OUTPUT: None */
/**/
/* Modifies Input?: tree, y */
/**/
/* EFFECTS: Rotates as described in _Introduction_To_Algorithms by */
/* Cormen, Leiserson, Rivest (Chapter 14). Basically this */
/* makes the parent of x be to the left of x, x the parent of */
/* its parent before the rotation and fixes other pointers */
/* accordingly. */
/***********************************************************************/
static void
RightRotate(rb_red_blk_node* y USES_REGS) {
rb_red_blk_node* x;
rb_red_blk_node* nil=LOCAL_db_nil;
/* I originally wrote this function to use the sentinel for */
/* nil to avoid checking for nil. However this introduces a */
/* very subtle bug because sometimes this function modifies */
/* the parent pointer of nil. This can be a problem if a */
/* function which calls LeftRotate also uses the nil sentinel */
/* and expects the nil sentinel's parent pointer to be unchanged */
/* after calling this function. For example, when RBDeleteFixUP */
/* calls LeftRotate it expects the parent pointer of nil to be */
/* unchanged. */
x=y->left;
y->left=x->right;
if (nil != x->right) x->right->parent=y; /*used to use sentinel here */
/* and do an unconditional assignment instead of testing for nil */
/* instead of checking if x->parent is the root as in the book, we */
/* count on the root sentinel to implicitly take care of this case */
x->parent=y->parent;
if( y == y->parent->left) {
y->parent->left=x;
} else {
y->parent->right=x;
}
x->right=y;
y->parent=x;
#ifdef DEBUG_ASSERT
Assert(!LOCAL_db_nil->red,"nil not red in RightRotate");
#endif
}
/***********************************************************************/
/* FUNCTION: TreeInsertHelp */
/**/
/* INPUTS: tree is the tree to insert into and z is the node to insert */
/**/
/* OUTPUT: none */
/**/
/* Modifies Input: tree, z */
/**/
/* EFFECTS: Inserts z into the tree as if it were a regular binary tree */
/* using the algorithm described in _Introduction_To_Algorithms_ */
/* by Cormen et al. This funciton is only intended to be called */
/* by the RBTreeInsert function and not by the user */
/***********************************************************************/
static void
TreeInsertHelp(rb_red_blk_node* z USES_REGS) {
/* This function should only be called by InsertRBTree (see above) */
rb_red_blk_node* x;
rb_red_blk_node* y;
rb_red_blk_node* nil=LOCAL_db_nil;
z->left=z->right=nil;
y=LOCAL_db_root;
x=LOCAL_db_root->left;
while( x != nil) {
y=x;
if (x->key < z->key) { /* x.key > z.key */
x=x->left;
} else { /* x,key <= z.key */
x=x->right;
}
}
z->parent=y;
if ( (y == LOCAL_db_root) ||
(y->key < z->key)) { /* y.key > z.key */
y->left=z;
} else {
y->right=z;
}
#ifdef DEBUG_ASSERT
Assert(!LOCAL_db_nil->red,"nil not red in TreeInsertHelp");
#endif
}
/* Before calling Insert RBTree the node x should have its key set */
/***********************************************************************/
/* FUNCTION: RBTreeInsert */
/**/
/* INPUTS: tree is the red-black tree to insert a node which has a key */
/* pointed to by key and info pointed to by info. */
/**/
/* OUTPUT: This function returns a pointer to the newly inserted node */
/* which is guarunteed to be valid until this node is deleted. */
/* What this means is if another data structure stores this */
/* pointer then the tree does not need to be searched when this */
/* is to be deleted. */
/**/
/* Modifies Input: tree */
/**/
/* EFFECTS: Creates a node node which contains the appropriate key and */
/* info pointers and inserts it into the tree. */
/***********************************************************************/
static rb_red_blk_node *
RBTreeInsert(CODEADDR key, CODEADDR end, db_entry_type db_type USES_REGS) {
rb_red_blk_node * y;
rb_red_blk_node * x;
rb_red_blk_node * newNode;
x=(rb_red_blk_node*) RBMalloc(sizeof(rb_red_blk_node) PASS_REGS);
x->key=key;
x->lim=end;
x->db_type=db_type;
x->in_use = FALSE;
TreeInsertHelp(x PASS_REGS);
newNode=x;
x->red=1;
while(x->parent->red) { /* use sentinel instead of checking for root */
if (x->parent == x->parent->parent->left) {
y=x->parent->parent->right;
if (y->red) {
x->parent->red=0;
y->red=0;
x->parent->parent->red=1;
x=x->parent->parent;
} else {
if (x == x->parent->right) {
x=x->parent;
LeftRotate(x PASS_REGS);
}
x->parent->red=0;
x->parent->parent->red=1;
RightRotate(x->parent->parent PASS_REGS);
}
} else { /* case for x->parent == x->parent->parent->right */
y=x->parent->parent->left;
if (y->red) {
x->parent->red=0;
y->red=0;
x->parent->parent->red=1;
x=x->parent->parent;
} else {
if (x == x->parent->left) {
x=x->parent;
RightRotate(x PASS_REGS);
}
x->parent->red=0;
x->parent->parent->red=1;
LeftRotate(x->parent->parent PASS_REGS);
}
}
}
LOCAL_db_root->left->red=0;
return newNode;
#ifdef DEBUG_ASSERT
Assert(!LOCAL_db_nil->red,"nil not red in RBTreeInsert");
Assert(!LOCAL_db_root->red,"root not red in RBTreeInsert");
#endif
}
/* init the table */
static void
store_in_dbtable(CODEADDR entry, CODEADDR end, db_entry_type db_type USES_REGS)
{
RBTreeInsert(entry, end, db_type PASS_REGS);
}
/* find an element in the dbentries table */
static rb_red_blk_node *
find_ref_in_dbtable(CODEADDR entry USES_REGS)
{
rb_red_blk_node *current = LOCAL_db_root->left;
while (current != LOCAL_db_nil) {
if (current->key <= entry && current->lim > entry) {
return current;
}
if (entry < current->key)
current = current->right;
else
current = current->left;
}
return current;
}
/* find an element in the dbentries table */
static void
mark_ref_in_use(DBRef ref USES_REGS)
{
rb_red_blk_node *el = find_ref_in_dbtable((CODEADDR)ref PASS_REGS);
el->in_use = TRUE;
}
static int
ref_in_use(DBRef ref USES_REGS)
{
rb_red_blk_node *el = find_ref_in_dbtable((CODEADDR)ref PASS_REGS);
return el->in_use;
}
static void
mark_db_fixed(CELL *ptr USES_REGS) {
rb_red_blk_node *el;
el = find_ref_in_dbtable((CODEADDR)ptr PASS_REGS);
if (el != LOCAL_db_nil) {
el->in_use = TRUE;
}
}
static void
init_dbtable(tr_fr_ptr trail_ptr USES_REGS) {
StaticClause *sc = DeadStaticClauses;
MegaClause *mc = DeadMegaClauses;
StaticIndex *si = DeadStaticIndices;
LOCAL_extra_gc_cells =
LOCAL_extra_gc_cells_base = (CELL *)TR;
LOCAL_extra_gc_cells_top = LOCAL_extra_gc_cells_base+
LOCAL_extra_gc_cells_size;
if ((char *)LOCAL_extra_gc_cells_top > LOCAL_TrailTop-1024)
gc_growtrail(FALSE, NULL, NULL PASS_REGS);
LOCAL_db_vec0 = LOCAL_db_vec = (ADDR)LOCAL_extra_gc_cells_top;
LOCAL_db_root = RBTreeCreate();
while (trail_ptr > (tr_fr_ptr)LOCAL_TrailBase) {
register CELL trail_cell;
trail_ptr--;
trail_cell = TrailTerm(trail_ptr);
if (!IsVarTerm(trail_cell) && IsPairTerm(trail_cell)) {
CELL *pt0 = RepPair(trail_cell);
/* DB pointer */
CELL flags;
#ifdef FROZEN_STACKS /* TRAIL */
/* avoid frozen segments */
if (
#ifdef YAPOR_SBA
(ADDR) pt0 >= HeapTop
#else
(ADDR) pt0 >= LOCAL_TrailBase && (ADDR) pt0 < LOCAL_TrailTop
#endif
) {
continue;
}
#endif /* FROZEN_STACKS */
flags = *pt0;
/* for the moment, if all references to the term in the stacks
are only pointers, reset the flag */
if (FlagOn(DBClMask, flags)) {
DBRef dbr = DBStructFlagsToDBStruct(pt0);
store_in_dbtable((CODEADDR)dbr,
(CODEADDR)dbr+sizeof(DBStruct)+sizeof(CELL)*dbr->DBT.NOfCells,
db_entry PASS_REGS);
} else if (flags & LogUpdMask) {
if (flags & IndexMask) {
LogUpdIndex *li = ClauseFlagsToLogUpdIndex(pt0);
store_in_dbtable((CODEADDR)li, (CODEADDR)li+li->ClSize, li_entry PASS_REGS);
} else {
LogUpdClause *cli = ClauseFlagsToLogUpdClause(pt0);
store_in_dbtable((CODEADDR)cli, (CODEADDR)cli+cli->ClSize, lcl_entry PASS_REGS);
}
} else {
DynamicClause *dcl = ClauseFlagsToDynamicClause(pt0);
store_in_dbtable((CODEADDR)dcl, (CODEADDR)dcl+dcl->ClSize, dcl_entry PASS_REGS);
}
}
}
while (sc) {
store_in_dbtable((CODEADDR)sc, (CODEADDR)sc+sc->ClSize, dcl_entry PASS_REGS);
sc = sc->ClNext;
}
while (si) {
store_in_dbtable((CODEADDR)si, (CODEADDR)si+si->ClSize, dcl_entry PASS_REGS);
si = si->SiblingIndex;
}
while (mc) {
store_in_dbtable((CODEADDR)mc, (CODEADDR)mc+mc->ClSize, dcl_entry PASS_REGS);
mc = mc->ClNext;
}
if (LOCAL_db_vec == LOCAL_db_vec0) {
/* could not find any entries: probably using LOG UPD semantics */
LOCAL_db_vec0 = NULL;
}
}
#ifdef DEBUG
/* #define INSTRUMENT_GC 1 */
#ifdef INSTRUMENT_GC
typedef enum {
gc_var,
gc_ref,
gc_atom,
gc_int,
gc_num,
gc_list,
gc_appl,
gc_func,
gc_susp
} gc_types;
unsigned long chain[16];
unsigned long env_vars;
unsigned long vars[gc_susp+1];
unsigned long num_bs;
unsigned long old_vars, new_vars;
static CELL *TrueHB;
static void
inc_vars_of_type(CELL *curr,gc_types val) {
if (curr >= H0 && curr < TrueHB) {
old_vars++;
} else if (curr >= TrueHB && curr < H) {
new_vars++;
} else {
return;
}
vars[val]++;
}
static void
put_type_info(unsigned long total)
{
fprintf(GLOBAL_stderr,"%% type info for %lu cells\n", total);
fprintf(GLOBAL_stderr,"%% %lu vars\n", vars[gc_var]);
fprintf(GLOBAL_stderr,"%% %lu refs\n", vars[gc_ref]);
fprintf(GLOBAL_stderr,"%% %lu references from env\n", env_vars);
fprintf(GLOBAL_stderr,"%% %lu atoms\n", vars[gc_atom]);
fprintf(GLOBAL_stderr,"%% %lu small ints\n", vars[gc_int]);
fprintf(GLOBAL_stderr,"%% %lu other numbers\n", vars[gc_num]);
fprintf(GLOBAL_stderr,"%% %lu lists\n", vars[gc_list]);
fprintf(GLOBAL_stderr,"%% %lu compound terms\n", vars[gc_appl]);
fprintf(GLOBAL_stderr,"%% %lu functors\n", vars[gc_func]);
fprintf(GLOBAL_stderr,"%% %lu suspensions\n", vars[gc_susp]);
}
static void
inc_var(CELL *current, CELL *next)
{
int len = 1;
CELL *mynext=next;
if (ONHEAP(current)) {
if (next == current) {
inc_vars_of_type(current,gc_var);
chain[0]++;
} else {
inc_vars_of_type(current,gc_ref);
while(ONHEAP(mynext) && IsVarTerm(*mynext)) {
CELL *prox = GET_NEXT(*mynext);
if (prox == mynext) {
chain[0]++;
break;
}
len++;
mynext = prox;
}
if (len>=15)
(chain[15])++;
else
(chain[len])++;
}
}
}
#endif /* INSTRUMENT_GC */
int STD_PROTO(vsc_stop,(void));
int
vsc_stop(void) {
return(1);
}
#endif
#ifdef CHECK_GLOBAL
static void
check_global(void) {
CELL *current;
#ifdef INSTRUMENT_GC
vars[gc_var] = 0;
vars[gc_ref] = 0;
vars[gc_atom] = 0;
vars[gc_int] = 0;
vars[gc_num] = 0;
vars[gc_list] = 0;
vars[gc_appl] = 0;
vars[gc_func] = 0;
vars[gc_susp] = 0;
#endif
for (current = H - 1; current >= H0; current--) {
CELL ccurr = *current;
if (MARKED_PTR(current)) {
CELL ccell = UNMARK_CELL(ccurr);
if (ccell == EndSpecials) {
/* oops, we found a blob */
CELL *ptr = current-1;
UInt nofcells;
while (!MARKED_PTR(ptr)) ptr--;
nofcells = current-ptr;
current = ptr;
ccurr = *current;
/* process the functor next */
}
}
#if INSTRUMENT_GC
if (IsVarTerm(ccurr)) {
if (IsBlobFunctor((Functor)ccurr)) vars[gc_num]++;
else if (ccurr != 0 && (ccurr < (CELL)LOCAL_GlobalBase || ccurr > (CELL)LOCAL_TrailTop)) {
/* printf("%p: %s/%d\n", current,
RepAtom(NameOfFunctor((Functor)ccurr))->StrOfAE,
ArityOfFunctor((Functor)ccurr));*/
vars[gc_func]++;
}
else if (IsUnboundVar(current)) vars[gc_var]++;
else vars[gc_ref]++;
} else if (IsApplTerm(ccurr)) {
/* printf("%p: f->%p\n",current,RepAppl(ccurr)); */
vars[gc_appl]++;
} else if (IsPairTerm(ccurr)) {
/* printf("%p: l->%p\n",current,RepPair(ccurr)); */
vars[gc_list]++;
} else if (IsAtomTerm(ccurr)) {
/* printf("%p: %s\n",current,RepAtom(AtomOfTerm(ccurr))->StrOfAE); */
vars[gc_atom]++;
} else if (IsIntTerm(ccurr)) {
/* printf("%p: %d\n",current,IntOfTerm(ccurr)); */
vars[gc_int]++;
}
#endif
}
#if INSTRUMENT_GC
put_type_info(H-H0);
vars[gc_var] = 0;
vars[gc_ref] = 0;
vars[gc_atom] = 0;
vars[gc_int] = 0;
vars[gc_num] = 0;
vars[gc_list] = 0;
vars[gc_appl] = 0;
vars[gc_func] = 0;
vars[gc_susp] = 0;
#endif
}
#else
#define check_global()
#endif /* CHECK_GLOBAL */
/* mark a heap object and all heap objects accessible from it */
static void
mark_variable(CELL_PTR current USES_REGS)
{
CELL_PTR next;
register CELL ccur;
unsigned int arity;
char *local_bp = LOCAL_bp;
begin:
if (UNMARKED_MARK(current,local_bp)) {
POP_CONTINUATION();
}
if (current >= H0 && current < H) {
LOCAL_total_marked++;
if (current < LOCAL_HGEN) {
LOCAL_total_oldies++;
} else {
DEBUG_printf0("%p 1\n", current);
}
}
PUSH_POINTER(current PASS_REGS);
ccur = *current;
next = GET_NEXT(ccur);
if (IsVarTerm(ccur)) {
if (IN_BETWEEN(LOCAL_GlobalBase,current,H) && GlobalIsAttVar(current) && current==next) {
if (next < H0) POP_CONTINUATION();
if (!UNMARKED_MARK(next-1,local_bp)) {
LOCAL_total_marked++;
if (next-1 < LOCAL_HGEN) {
LOCAL_total_oldies++;
} else {
DEBUG_printf0("%p 1\n", next-1);
}
PUSH_POINTER(next-1 PASS_REGS);
}
PUSH_CONTINUATION(next+1,2 PASS_REGS);
current = next;
goto begin;
} else if (ONHEAP(next)) {
#ifdef EASY_SHUNTING
CELL cnext;
/* do variable shunting between variables in the global */
cnext = *next;
if (!MARKED_PTR(next)) {
if (IsVarTerm(cnext) && (CELL)next == cnext) {
/* new global variable to new global variable */
if (next > current && current < LOCAL_prev_HB && current >= HB && next >= HB && next < LOCAL_prev_HB) {
#ifdef INSTRUMENT_GC
inc_var(current, current);
#endif
*next = (CELL)current;
UNMARK(next);
MARK(current);
*current = (CELL)current;
POP_CONTINUATION();
} else {
/* can't help here */
#ifdef INSTRUMENT_GC
inc_var(current, next);
#endif
current = next;
}
} else {
/* binding to a determinate reference */
if (next >= HB && current < LCL0 && cnext != TermFoundVar) {
UNMARK(current);
*current = cnext;
if (current >= H0 && current < H) {
LOCAL_total_marked--;
if (current < LOCAL_HGEN) {
LOCAL_total_oldies--;
} else {
DEBUG_printf0("%p-1\n", next-1);
}
}
POP_POINTER( PASS_REGS1 );
} else {
#ifdef INSTRUMENT_GC
inc_var(current, next);
#endif
current = next;
}
}
/* try to shorten chains if they go through the current CP */
} else if (next > HB &&
IsVarTerm(cnext) &&
UNMARK_CELL(cnext) != (CELL)next &&
current < LCL0) {
/* This step is possible because we clean up the trail */
*current = UNMARK_CELL(cnext);
UNMARK(current);
if (current >= H0 && current < H ) {
LOCAL_total_marked--;
if (current < LOCAL_HGEN) {
LOCAL_total_oldies--;
} else {
DEBUG_printf0("%p-1\n", next-1);
}
}
POP_POINTER( PASS_REGS1 );
} else
#endif
/* what I'd do without variable shunting */
{
#ifdef INSTRUMENT_GC
inc_var(current, next);
#endif
current = next;
}
goto begin;
#ifdef DEBUG
} else if (next < (CELL *)LOCAL_GlobalBase || next > (CELL *)LOCAL_TrailTop) {
fprintf(GLOBAL_stderr, "OOPS in GC: marking, current=%p, *current=" UInt_FORMAT " next=%p\n", current, ccur, next);
#endif
} else {
#ifdef COROUTING
LOCAL_total_smarked++;
#endif
#ifdef INSTRUMENT_GC
inc_var(current, next);
#endif
}
POP_CONTINUATION();
} else if (IsAtomOrIntTerm(ccur)) {
#ifdef INSTRUMENT_GC
if (IsAtomTerm(ccur))
inc_vars_of_type(current,gc_atom);
else
inc_vars_of_type(current, gc_int);
#endif
POP_CONTINUATION();
} else if (IsPairTerm(ccur)) {
#ifdef INSTRUMENT_GC
inc_vars_of_type(current,gc_list);
#endif
if (ONHEAP(next)) {
/* speedup for strings */
if (IsAtomOrIntTerm(*next)) {
if (!UNMARKED_MARK(next,local_bp)) {
LOCAL_total_marked++;
if (next < LOCAL_HGEN) {
LOCAL_total_oldies++;
} else {
DEBUG_printf0("%p 1\n", next);
}
PUSH_POINTER(next PASS_REGS);
}
current = next+1;
goto begin;
} else {
PUSH_CONTINUATION(next+1,1 PASS_REGS);
current = next;
goto begin;
}
} else if (ONCODE(next)) {
mark_db_fixed(RepPair(ccur) PASS_REGS);
}
POP_CONTINUATION();
} else if (IsApplTerm(ccur)) {
register CELL cnext = *next;
#ifdef INSTRUMENT_GC
if (!IsExtensionFunctor((Functor)cnext))
inc_vars_of_type(current,gc_appl);
else
inc_vars_of_type(current,gc_num);
#endif
if (ONCODE(next)) {
if ((Functor)cnext == FunctorDBRef) {
DBRef tref = DBRefOfTerm(ccur);
/* make sure the reference is marked as in use */
if ((tref->Flags & (ErasedMask|LogUpdMask)) == (ErasedMask|LogUpdMask)) {
*current = MkDBRefTerm((DBRef)LogDBErasedMarker);
MARK(current);
} else {
mark_ref_in_use(tref PASS_REGS);
}
} else {
mark_db_fixed(next PASS_REGS);
}
POP_CONTINUATION();
}
if ( MARKED_PTR(next) || !ONHEAP(next) )
POP_CONTINUATION();
if (next < H0) POP_CONTINUATION();
if (IsExtensionFunctor((Functor)cnext)) {
switch (cnext) {
case (CELL)FunctorLongInt:
MARK(next);
MARK(next+2);
if (next < LOCAL_HGEN) {
LOCAL_total_oldies+=3;
} else {
DEBUG_printf0("%p 1\n", next);
DEBUG_printf0("%p 3\n", next);
}
LOCAL_total_marked += 3;
PUSH_POINTER(next PASS_REGS);
PUSH_POINTER(next+2 PASS_REGS);
POP_CONTINUATION();
case (CELL)FunctorDouble:
MARK(next);
PUSH_POINTER(next PASS_REGS);
{
UInt sz = 1+SIZEOF_DOUBLE/SIZEOF_LONG_INT;
if (next < LOCAL_HGEN) {
LOCAL_total_oldies+= 1+sz;
} else {
DEBUG_printf0("%p 1\n", next);
DEBUG_printf1("%p %ld\n", next, (long int)(sz+1));
}
LOCAL_total_marked += 1+sz;
PUSH_POINTER(next+sz PASS_REGS);
MARK(next+sz);
}
POP_CONTINUATION();
case (CELL)FunctorBigInt:
{
Opaque_CallOnGCMark f;
Term t = AbsAppl(next);
UInt sz = (sizeof(MP_INT)+CellSize+
((MP_INT *)(next+2))->_mp_alloc*sizeof(mp_limb_t))/CellSize;
MARK(next);
if ( (f = Yap_blob_gc_mark_handler(t)) ) {
Int n = (f)(Yap_BlobTag(t), Yap_BlobInfo(t), LOCAL_extra_gc_cells, LOCAL_extra_gc_cells_top - (LOCAL_extra_gc_cells+2));
if (n < 0) {
/* error: we don't have enough room */
/* could not find more trail */
save_machine_regs();
siglongjmp(LOCAL_gc_restore, 3);
} else if (n > 0) {
CELL *ptr = LOCAL_extra_gc_cells;
LOCAL_extra_gc_cells += n+2;
PUSH_CONTINUATION(ptr, n+1 PASS_REGS);
ptr += n;
ptr[0] = t;
ptr[1] = n+1;
}
}
/* size is given by functor + friends */
if (next < LOCAL_HGEN) {
LOCAL_total_oldies += 2+sz;
} else {
DEBUG_printf0("%p 1\n", next);
DEBUG_printf1("%p %ld\n", next, (long int)(sz+2));
}
LOCAL_total_marked += 2+sz;
PUSH_POINTER(next PASS_REGS);
sz++;
#if DEBUG
if (next[sz] != EndSpecials) {
fprintf(stderr,"[ Error: could not find EndSpecials at blob %p type " UInt_FORMAT " ]\n", next, next[1]);
}
#endif
MARK(next+sz);
PUSH_POINTER(next+sz PASS_REGS);
}
default:
POP_CONTINUATION();
}
}
if (next < H0) POP_CONTINUATION();
#ifdef INSTRUMENT_GC
inc_vars_of_type(next,gc_func);
#endif
arity = ArityOfFunctor((Functor)(cnext));
MARK(next);
++LOCAL_total_marked;
if (next < LOCAL_HGEN) {
++LOCAL_total_oldies;
} else {
DEBUG_printf0("%p 1\n", next);
}
PUSH_POINTER(next PASS_REGS);
next++;
/* speedup for leaves */
while (arity && IsAtomOrIntTerm(*next)) {
if (!UNMARKED_MARK(next,local_bp)) {
LOCAL_total_marked++;
if (next < LOCAL_HGEN) {
LOCAL_total_oldies++;
} else {
DEBUG_printf0("%p 1\n", next);
}
PUSH_POINTER(next PASS_REGS);
}
next++;
arity--;
}
if (!arity) POP_CONTINUATION();
current = next;
if (arity == 1) goto begin;
PUSH_CONTINUATION(current+1,arity-1 PASS_REGS);
goto begin;
}
}
void
Yap_mark_variable(CELL_PTR current)
{
CACHE_REGS
mark_variable(current PASS_REGS);
}
static void
mark_code(CELL_PTR ptr, CELL *next USES_REGS)
{
if (ONCODE(next)) {
CELL reg = *ptr;
if (IsApplTerm(reg) && (Functor)(*next) == FunctorDBRef) {
DBRef tref = DBRefOfTerm(reg);
/* make sure the reference is marked as in use */
if ((tref->Flags & (LogUpdMask|ErasedMask)) == (LogUpdMask|ErasedMask)) {
*ptr = MkDBRefTerm((DBRef)LogDBErasedMarker);
} else {
mark_ref_in_use(tref PASS_REGS);
}
} else {
mark_db_fixed(next PASS_REGS);
}
}
}
static void
mark_external_reference(CELL *ptr USES_REGS) {
CELL *next = GET_NEXT(*ptr);
if (ONHEAP(next)) {
#ifdef HYBRID_SCHEME
CELL_PTR *old = LOCAL_iptop;
#endif
mark_variable(ptr PASS_REGS);
POPSWAP_POINTER(old, ptr PASS_REGS);
} else {
MARK(ptr);
mark_code(ptr, next PASS_REGS);
}
}
static void inline
mark_external_reference2(CELL *ptr USES_REGS) {
CELL *next = GET_NEXT(*ptr);
if (ONHEAP(next)) {
#ifdef HYBRID_SCHEME
CELL_PTR *old = LOCAL_iptop;
#endif
mark_variable(ptr PASS_REGS);
POPSWAP_POINTER(old, ptr PASS_REGS);
} else {
mark_code(ptr,next PASS_REGS);
}
}
/*
* mark all heap objects accessible from the trail (which includes the active
* general purpose registers)
*/
void
Yap_mark_external_reference(CELL *ptr) {
CACHE_REGS
mark_external_reference(ptr PASS_REGS);
}
static void
mark_regs(tr_fr_ptr old_TR USES_REGS)
{
tr_fr_ptr trail_ptr;
/* first, whatever we dumped on the trail. Easier just to do
the registers separately? */
for (trail_ptr = old_TR; trail_ptr < TR; trail_ptr++) {
mark_external_reference(&TrailTerm(trail_ptr) PASS_REGS);
}
}
/* mark all heap objects accessible from a chain of environments */
static void
mark_environments(CELL_PTR gc_ENV, OPREG size, CELL *pvbmap USES_REGS)
{
CELL_PTR saved_var;
while (gc_ENV != NULL) { /* no more environments */
Int bmap = 0;
int currv = 0;
#ifdef DEBUG
if (size < 0 || size > 512)
fprintf(GLOBAL_stderr,"OOPS in GC: env size for %p is " UInt_FORMAT "\n", gc_ENV, (CELL)size);
#endif
mark_db_fixed((CELL *)gc_ENV[E_CP] PASS_REGS);
/* for each saved variable */
if (size > EnvSizeInCells) {
int tsize = size - EnvSizeInCells;
currv = sizeof(CELL)*8-tsize%(sizeof(CELL)*8);
if (pvbmap != NULL) {
pvbmap += tsize/(sizeof(CELL)*8);
bmap = *pvbmap;
} else {
bmap = ((CELL)-1);
}
bmap = (Int)(((CELL)bmap) << currv);
}
for (saved_var = gc_ENV - size; saved_var < gc_ENV - EnvSizeInCells; saved_var++) {
if (currv == sizeof(CELL)*8) {
if (pvbmap) {
pvbmap--;
bmap = *pvbmap;
} else {
bmap = ((CELL)-1);
}
currv = 0;
}
/* we may have already been here */
if (bmap < 0 && !MARKED_PTR(saved_var)) {
#ifdef INSTRUMENT_GC
Term ccur = *saved_var;
if (IsVarTerm(ccur)) {
int len = 1;
CELL *mynext= GET_NEXT(ccur);
if (ONHEAP(mynext)) {
env_vars++;
while(ONHEAP(mynext) && IsVarTerm(*mynext)) {
CELL *prox = GET_NEXT(*mynext);
if (prox == mynext) {
chain[0]++;
break;
}
len++;
mynext = prox;
}
if (len>=15) {
(chain[15])++;
} else {
(chain[len])++;
}
}
}
#endif
mark_external_reference(saved_var PASS_REGS);
}
bmap <<= 1;
currv++;
}
/* have we met this environment before?? */
/* we use the B field in the environment to tell whether we have
been here before or not.
We do it at the end because we don't want to lose any variables
that would have been trimmed at the first environment visit.
*/
if (MARKED_PTR(gc_ENV+E_CB))
return;
MARK(gc_ENV+E_CB);
size = EnvSize((yamop *) (gc_ENV[E_CP])); /* size = EnvSize(CP) */
pvbmap = EnvBMap((yamop *) (gc_ENV[E_CP]));
#if 0
if (size < 0) {
PredEntry *pe = EnvPreg(gc_ENV[E_CP]);
op_numbers op = Yap_op_from_opcode(ENV_ToOp(gc_ENV[E_CP]));
#if defined(ANALYST) || defined(DEBUG)
fprintf(GLOBAL_stderr,"ENV %p-%p(%d) %s\n", gc_ENV, pvbmap, size-EnvSizeInCells, Yap_op_names[op]);
#else
fprintf(GLOBAL_stderr,"ENV %p-%p(%d) %d\n", gc_ENV, pvbmap, size-EnvSizeInCells, (int)op);
#endif
if (pe->ArityOfPE)
fprintf(GLOBAL_stderr," %s/%d\n", RepAtom(NameOfFunctor(pe->FunctorOfPred))->StrOfAE, pe->ArityOfPE);
else
fprintf(GLOBAL_stderr," %s\n", RepAtom((Atom)(pe->FunctorOfPred))->StrOfAE);
}
#endif
gc_ENV = (CELL_PTR) gc_ENV[E_E]; /* link to prev
* environment */
}
}
/*
Cleaning the trail should be quick and simple, right? Well, not
really :-(. The problem is that the trail includes a dumping ground
of the WAM registers and of extra choice-point fields, which need
to be cleaned from somewhere.
And cleaning the trail itself is not easy. The problem is that we
may not have cleaned the trail after cuts. If we naively followed
these pointers, we could have direct references to the global
stack! A solution is to verify whether we are poiting at a
legitimate trail entry. Unfortunately this requires some extra work
following choice-points.
*/
static void
mark_trail(tr_fr_ptr trail_ptr, tr_fr_ptr trail_base, CELL *gc_H, choiceptr gc_B USES_REGS)
{
#ifdef EASY_SHUNTING
tr_fr_ptr begsTR = NULL, endsTR = NULL;
tr_fr_ptr OldsTR0 = LOCAL_sTR0;
#endif
#ifdef COROUTINING
CELL *detatt = NULL;
#endif
cont *old_cont_top0 = LOCAL_cont_top0;
GC_NEW_MAHASH((gc_ma_hash_entry *)LOCAL_cont_top0 PASS_REGS);
while (trail_base < trail_ptr) {
register CELL trail_cell;
trail_cell = TrailTerm(trail_base);
if (IsVarTerm(trail_cell)) {
CELL *hp = (CELL *)trail_cell;
/* if a variable older than the current CP has not been marked yet,
than its new binding is not accessible and we can reset it. Note
we must use gc_H to avoid trouble with dangling variables
in the heap */
if (((hp < gc_H && hp >= H0) || (hp > (CELL *)gc_B && hp < LCL0) ) && !MARKED_PTR(hp)) {
/* perform early reset */
/* reset term to be a variable */
RESET_VARIABLE(hp);
LOCAL_discard_trail_entries++;
RESET_VARIABLE(&TrailTerm(trail_base));
#ifdef FROZEN_STACKS
RESET_VARIABLE(&TrailVal(trail_base));
#endif
} else if (hp < (CELL *)LOCAL_GlobalBase || hp > (CELL *)LOCAL_TrailTop) {
/* pointers from the Heap back into the trail are process in mark_regs. */
/* do nothing !!! */
} else if ((hp < (CELL *)gc_B && hp >= gc_H) || hp > (CELL *)LOCAL_TrailBase) {
/* clean the trail, avoid dangling pointers! */
RESET_VARIABLE(&TrailTerm(trail_base));
#ifdef FROZEN_STACKS
RESET_VARIABLE(&TrailVal(trail_base));
#endif
LOCAL_discard_trail_entries++;
} else {
if (trail_cell == (CELL)trail_base)
LOCAL_discard_trail_entries++;
else {
/* This is a bit of a mess: when I find an attributed variable that was bound
nondeterministically, I know that after backtracking it will be back to be an unbound variable.
The ideal solution would be to unbind all variables. The current solution is to
remark it as an attributed variable */
if (IN_BETWEEN(LOCAL_GlobalBase,hp,H) && GlobalIsAttVar(hp) && !UNMARKED_MARK(hp-1,LOCAL_bp)) {
LOCAL_total_marked++;
PUSH_POINTER(hp-1 PASS_REGS);
if (hp-1 < LOCAL_HGEN) {
LOCAL_total_oldies++;
} else {
DEBUG_printf0("%p 1\n", hp-1);
}
mark_variable(hp+1 PASS_REGS);
mark_variable(hp+2 PASS_REGS);
}
#ifdef FROZEN_STACKS
mark_external_reference(&TrailVal(trail_base) PASS_REGS);
#endif
}
#ifdef EASY_SHUNTING
if (hp < gc_H && hp >= H0 && !MARKED_PTR(hp)) {
tr_fr_ptr nsTR = (tr_fr_ptr)LOCAL_cont_top0;
CELL *cptr = (CELL *)trail_cell;
if ((ADDR)nsTR > LOCAL_TrailTop-1024) {
gc_growtrail(TRUE, begsTR, old_cont_top0 PASS_REGS);
}
TrailTerm(nsTR) = (CELL)NULL;
TrailTerm(nsTR+1) = *hp;
TrailTerm(nsTR+2) = trail_cell;
if (begsTR == NULL)
begsTR = nsTR;
else
TrailTerm(endsTR) = (CELL)nsTR;
endsTR = nsTR;
LOCAL_cont_top = (cont *)(nsTR+3);
LOCAL_sTR = (tr_fr_ptr)LOCAL_cont_top;
LOCAL_gc_ma_h_top = (gc_ma_hash_entry *)(nsTR+3);
RESET_VARIABLE(cptr);
MARK(cptr);
}
#endif
}
} else if (IsPairTerm(trail_cell)) {
/* cannot safely ignore this */
CELL *cptr = RepPair(trail_cell);
if (IN_BETWEEN(LOCAL_GlobalBase,cptr,H)) {
if (GlobalIsAttVar(cptr)) {
TrailTerm(trail_base) = (CELL)cptr;
mark_external_reference(&TrailTerm(trail_base) PASS_REGS);
TrailTerm(trail_base) = trail_cell;
} else if (*cptr == (CELL)FunctorBigInt) {
TrailTerm(trail_base) = AbsAppl(cptr);
mark_external_reference(&TrailTerm(trail_base) PASS_REGS);
TrailTerm(trail_base) = trail_cell;
}
#ifdef DEBUG
else
fprintf(GLOBAL_stderr,"OOPS in GC: weird trail entry at %p:" UInt_FORMAT "\n", &TrailTerm(trail_base), (CELL)cptr);
#endif
}
}
#if MULTI_ASSIGNMENT_VARIABLES
else {
CELL *cptr = RepAppl(trail_cell);
/* This is a bit complex. The idea is that we may have several
trailings for the same mavar in the same trail segment. Essentially,
the problem arises because of !. What we want is to ignore all but
the last entry, or in this case, all but the first entry with the last
value.
*/
if (cptr < (CELL *)gc_B && cptr >= gc_H) {
goto remove_trash_entry;
} else if (IsAttVar(cptr)) {
/* MABINDING that should be recovered */
if (detatt && cptr < detatt) {
goto remove_trash_entry;
} else {
/* This attributed variable is still in play */
mark_variable(cptr PASS_REGS);
}
}
if (!gc_lookup_ma_var(cptr, trail_base PASS_REGS)) {
/* check whether this is the first time we see it*/
Term t0 = TrailTerm(trail_base+1);
if (!IsAtomicTerm(t0)) {
CELL *next = GET_NEXT(t0);
/* check if we have a garbage entry, where we are setting a
pointer to ourselves. */
if (next < (CELL *)gc_B && next >= gc_H) {
goto remove_trash_entry;
}
}
if (HEAP_PTR(trail_cell)) {
/* fool the gc into thinking this is a variable */
TrailTerm(trail_base) = (CELL)cptr;
mark_external_reference(&(TrailTerm(trail_base)) PASS_REGS);
/* reset the gc to believe the original tag */
TrailTerm(trail_base) = AbsAppl((CELL *)TrailTerm(trail_base));
}
#ifdef FROZEN_STACKS
mark_external_reference(&(TrailVal(trail_base)) PASS_REGS);
trail_base++;
if (HEAP_PTR(trail_cell)) {
TrailTerm(trail_base) = (CELL)cptr;
mark_external_reference(&(TrailTerm(trail_base)) PASS_REGS);
/* reset the gc to believe the original tag */
TrailTerm(trail_base) = AbsAppl((CELL *)TrailTerm(trail_base));
}
/* don't need to mark the next TrailVal, this is done at the end
of segment */
#else
trail_base++;
mark_external_reference(&(TrailTerm(trail_base)) PASS_REGS);
trail_base ++;
if (HEAP_PTR(trail_cell)) {
/* fool the gc into thinking this is a variable */
TrailTerm(trail_base) = (CELL)cptr;
mark_external_reference(&(TrailTerm(trail_base)) PASS_REGS);
/* reset the gc to believe the original tag */
TrailTerm(trail_base) = AbsAppl((CELL *)TrailTerm(trail_base));
}
#endif /* TABLING */
} else {
remove_trash_entry:
/* we can safely ignore this little monster */
#ifdef FROZEN_STACKS
LOCAL_discard_trail_entries += 2;
RESET_VARIABLE(&TrailTerm(trail_base));
RESET_VARIABLE(&TrailVal(trail_base));
#else
LOCAL_discard_trail_entries += 3;
RESET_VARIABLE(&TrailTerm(trail_base));
trail_base++;
RESET_VARIABLE(&TrailTerm(trail_base));
#endif
trail_base++;
RESET_VARIABLE(&TrailTerm(trail_base));
#ifdef FROZEN_STACKS
RESET_VARIABLE(&TrailVal(trail_base));
#endif
}
}
#endif
trail_base++;
}
#if TABLING
/*
Ugly, but needed: we're not really sure about what were the new
values until the very end
*/
{
gc_ma_hash_entry *gl = LOCAL_gc_ma_h_list;
while (gl) {
mark_external_reference(&(TrailVal(gl->loc+1)) PASS_REGS);
gl = gl->more;
}
}
#endif /* TABLING */
#ifdef EASY_SHUNTING
/* set back old variables */
LOCAL_sTR = (tr_fr_ptr)old_cont_top0;
while (begsTR != NULL) {
tr_fr_ptr newsTR = (tr_fr_ptr)TrailTerm(begsTR);
TrailTerm(LOCAL_sTR) = TrailTerm(begsTR+1);
TrailTerm(LOCAL_sTR+1) = TrailTerm(begsTR+2);
begsTR = newsTR;
LOCAL_sTR += 2;
}
LOCAL_sTR0 = OldsTR0;
#else
LOCAL_cont_top0 = old_cont_top0;
#endif
LOCAL_cont_top = LOCAL_cont_top0;
}
/*
* mark all heap objects accessible from each choicepoint & its chain of
* environments
*/
#ifdef TABLING
#define init_substitution_pointer(GCB, SUBS_PTR, DEP_FR) \
if (DepFr_leader_cp(DEP_FR) == GCB) { \
/* GCB is a generator-consumer node */ \
/* never here if batched scheduling */ \
SUBS_PTR = (CELL *) (GEN_CP(GCB) + 1); \
SUBS_PTR += SgFr_arity(GEN_CP(GCB)->cp_sg_fr); \
} else { \
SUBS_PTR = (CELL *) (CONS_CP(GCB) + 1); \
}
#endif /* TABLING */
static void
mark_slots( USES_REGS1 )
{
Int curslot = CurSlot;
while (curslot) {
CELL *ptr = LCL0-curslot;
Int ns = IntegerOfTerm(*ptr);
ptr++;
while (ns > 0) {
// Yap_DebugPlWrite(ptr);
//fprintf(stderr,"\n");
mark_external_reference(ptr PASS_REGS);
ptr++;
ns--;
}
curslot = IntegerOfTerm(*ptr);
}
}
#ifdef TABLING
static choiceptr
youngest_cp(choiceptr gc_B, dep_fr_ptr *depfrp)
{
dep_fr_ptr depfr = *depfrp;
choiceptr min = gc_B;
if (!gc_B) {
return gc_B;
}
if (depfr && min > DepFr_cons_cp(depfr)) {
min = DepFr_cons_cp(depfr);
}
if (depfr && min == DepFr_cons_cp(depfr)) {
*depfrp = DepFr_next(depfr);
}
return min;
}
#endif /* TABLING */
static void
mark_choicepoints(register choiceptr gc_B, tr_fr_ptr saved_TR, int very_verbose USES_REGS)
{
OPCODE
trust_lu = Yap_opcode(_trust_logical),
count_trust_lu = Yap_opcode(_count_trust_logical),
profiled_trust_lu = Yap_opcode(_profiled_trust_logical);
yamop *lu_cl0 = NEXTOP(PredLogUpdClause0->CodeOfPred,Otapl),
*lu_cl = NEXTOP(PredLogUpdClause->CodeOfPred,Otapl),
*lu_cle = NEXTOP(PredLogUpdClauseErase->CodeOfPred,Otapl),
*su_cl = NEXTOP(PredStaticClause->CodeOfPred,Otapl);
#ifdef TABLING
dep_fr_ptr depfr = LOCAL_top_dep_fr;
sg_fr_ptr aux_sg_fr = LOCAL_top_sg_fr;
#endif /* TABLING */
#ifdef TABLING
gc_B = youngest_cp(gc_B, &depfr);
#endif /* TABLING */
while (gc_B != NULL) {
op_numbers opnum;
register OPCODE op;
yamop *rtp = gc_B->cp_ap;
mark_db_fixed((CELL *)rtp PASS_REGS);
#ifdef DETERMINISTIC_TABLING
if (!IS_DET_GEN_CP(gc_B))
#endif /* DETERMINISTIC_TABLING */
mark_db_fixed((CELL *)(gc_B->cp_cp) PASS_REGS);
#ifdef EASY_SHUNTING
LOCAL_current_B = gc_B;
LOCAL_prev_HB = HB;
#endif
HB = gc_B->cp_h;
#ifdef INSTRUMENT_GC
num_bs++;
#endif
#ifdef TABLING
if (rtp == NULL) {
if (aux_sg_fr && gc_B == SgFr_gen_cp(aux_sg_fr)) {
/* found generator */
opnum = _table_completion;
} else {
/* found sld node is done */
opnum = _trust_fail;
}
} else {
#endif /* TABLING */
op = rtp->opc;
opnum = Yap_op_from_opcode(op);
#ifdef TABLING
}
if (aux_sg_fr && gc_B == SgFr_gen_cp(aux_sg_fr)) {
aux_sg_fr = SgFr_next(aux_sg_fr);
}
#endif /* TABLING */
if (very_verbose) {
PredEntry *pe = Yap_PredForChoicePt(gc_B);
#if defined(ANALYST) || defined(DEBUG)
if (pe == NULL) {
fprintf(GLOBAL_stderr,"%% marked " UInt_FORMAT " (%s)\n", LOCAL_total_marked, Yap_op_names[opnum]);
} else if (pe->ArityOfPE) {
fprintf(GLOBAL_stderr,"%% %s/" UInt_FORMAT " marked " UInt_FORMAT " (%s)\n", RepAtom(NameOfFunctor(pe->FunctorOfPred))->StrOfAE, pe->ArityOfPE, LOCAL_total_marked, Yap_op_names[opnum]);
} else {
fprintf(GLOBAL_stderr,"%% %s marked " UInt_FORMAT " (%s)\n", RepAtom((Atom)(pe->FunctorOfPred))->StrOfAE, LOCAL_total_marked, Yap_op_names[opnum]);
}
#else
if (pe == NULL) {
fprintf(GLOBAL_stderr,"%% marked " Int_FORMAT " (%u)\n", LOCAL_total_marked, (unsigned int)opnum);
} else if (pe->ArityOfPE) {
fprintf(GLOBAL_stderr,"%% %s/%d marked " Int_FORMAT " (%u)\n", RepAtom(NameOfFunctor(pe->FunctorOfPred))->StrOfAE, pe->ArityOfPE, LOCAL_total_marked, (unsigned int)opnum);
} else {
fprintf(GLOBAL_stderr,"%% %s marked " Int_FORMAT " (%u)\n", RepAtom((Atom)(pe->FunctorOfPred))->StrOfAE, LOCAL_total_marked, (unsigned int)opnum);
}
#endif
}
{
/* find out how many cells are still alive in the trail */
mark_trail(saved_TR, gc_B->cp_tr, gc_B->cp_h, gc_B PASS_REGS);
saved_TR = gc_B->cp_tr;
}
if (opnum == _or_else || opnum == _or_last) {
/* ; choice point */
mark_environments((CELL_PTR) (gc_B->cp_a1),
-gc_B->cp_cp->u.Osblp.s / ((OPREG)sizeof(CELL)),
gc_B->cp_cp->u.Osblp.bmap
PASS_REGS);
} else {
/* choicepoint with arguments */
register CELL_PTR saved_reg;
OPREG nargs;
if (opnum == _Nstop)
mark_environments((CELL_PTR) gc_B->cp_env,
EnvSizeInCells,
NULL PASS_REGS);
else if (opnum != _trust_fail)
#ifdef DETERMINISTIC_TABLING
if (!IS_DET_GEN_CP(gc_B))
#endif /* DETERMINISTIC_TABLING */
mark_environments((CELL_PTR) gc_B->cp_env,
EnvSize((yamop *) (gc_B->cp_cp)),
EnvBMap((yamop *) (gc_B->cp_cp)) PASS_REGS);
/* extended choice point */
restart_cp:
switch (opnum) {
case _Nstop:
if (gc_B->cp_b != NULL) {
nargs = 0;
break;
} else {
/* this is the last choice point, the work is done ;-) */
return;
}
case _retry_c:
case _retry_userc:
if (gc_B->cp_ap == RETRY_C_RECORDED_K_CODE
|| gc_B->cp_ap == RETRY_C_RECORDEDP_CODE) {
/* we have a reference from the choice-point stack to a term */
choiceptr old_b = B;
DBRef ref;
B = gc_B;
ref = (DBRef)EXTRA_CBACK_ARG(3,1);
if (IsVarTerm((CELL)ref)) {
mark_ref_in_use(ref PASS_REGS);
} else {
if (ONCODE((CELL)ref)) {
mark_db_fixed(RepAppl((CELL)ref) PASS_REGS);
}
}
B = old_b;
}
nargs = rtp->u.OtapFs.s+rtp->u.OtapFs.extra;
break;
case _jump:
rtp = rtp->u.l.l;
op = rtp->opc;
opnum = Yap_op_from_opcode(op);
goto restart_cp;
case _retry_profiled:
case _count_retry:
rtp = NEXTOP(rtp,l);
op = rtp->opc;
opnum = Yap_op_from_opcode(op);
goto restart_cp;
case _trust_fail:
nargs = 0;
break;
#ifdef TABLING
case _table_load_answer:
{
CELL *vars_ptr, vars;
vars_ptr = (CELL *) (LOAD_CP(gc_B) + 1);
vars = *vars_ptr++;
while (vars--) {
mark_external_reference(vars_ptr PASS_REGS);
vars_ptr++;
}
}
nargs = 0;
break;
case _table_try_answer:
case _table_retry_me:
case _table_trust_me:
case _table_retry:
case _table_trust:
{
CELL *vars_ptr, vars;
vars_ptr = (CELL *)(GEN_CP(gc_B) + 1);
nargs = rtp->u.Otapl.s;
while (nargs--) {
mark_external_reference(vars_ptr PASS_REGS);
vars_ptr++;
}
vars = *vars_ptr++;
while (vars--) {
mark_external_reference(vars_ptr PASS_REGS);
vars_ptr++;
}
}
nargs = 0;
break;
case _table_completion:
#ifdef THREADS_CONSUMER_SHARING
case _table_answer_resolution_completion:
#endif /* THREADS_CONSUMER_SHARING */
{
CELL *vars_ptr, vars;
#ifdef DETERMINISTIC_TABLING
if (IS_DET_GEN_CP(gc_B))
vars_ptr = (CELL *)(DET_GEN_CP(gc_B) + 1);
else
#endif /* DETERMINISTIC_TABLING */
{
vars_ptr = (CELL *)(GEN_CP(gc_B) + 1);
nargs = SgFr_arity(GEN_CP(gc_B)->cp_sg_fr);
while (nargs--) {
mark_external_reference(vars_ptr PASS_REGS);
vars_ptr++;
}
}
vars = *vars_ptr++;
while (vars--) {
mark_external_reference(vars_ptr PASS_REGS);
vars_ptr++;
}
}
nargs = 0;
break;
case _table_answer_resolution:
{
CELL *vars_ptr, vars;
init_substitution_pointer(gc_B, vars_ptr, CONS_CP(gc_B)->cp_dep_fr);
vars = *vars_ptr++;
while (vars--) {
mark_external_reference(vars_ptr PASS_REGS);
vars_ptr++;
}
}
nargs = 0;
break;
case _trie_trust_var:
case _trie_retry_var:
case _trie_trust_var_in_pair:
case _trie_retry_var_in_pair:
case _trie_trust_val:
case _trie_retry_val:
case _trie_trust_val_in_pair:
case _trie_retry_val_in_pair:
case _trie_trust_atom:
case _trie_retry_atom:
case _trie_trust_atom_in_pair:
case _trie_retry_atom_in_pair:
case _trie_trust_null:
case _trie_retry_null:
case _trie_trust_null_in_pair:
case _trie_retry_null_in_pair:
case _trie_trust_pair:
case _trie_retry_pair:
case _trie_trust_appl:
case _trie_retry_appl:
case _trie_trust_appl_in_pair:
case _trie_retry_appl_in_pair:
case _trie_trust_extension:
case _trie_retry_extension:
case _trie_trust_double:
case _trie_retry_double:
case _trie_trust_longint:
case _trie_retry_longint:
case _trie_trust_gterm:
case _trie_retry_gterm:
{
CELL *vars_ptr;
int heap_arity, vars_arity, subs_arity;
vars_ptr = (CELL *)(gc_B + 1);
heap_arity = vars_ptr[0];
vars_arity = vars_ptr[1 + heap_arity];
subs_arity = vars_ptr[2 + heap_arity + vars_arity];
vars_ptr += 2 + heap_arity + subs_arity + vars_arity;
if (subs_arity) {
while (subs_arity--) {
mark_external_reference(vars_ptr PASS_REGS);
vars_ptr--;
}
}
vars_ptr--; /* skip subs_arity entry */
if (vars_arity) {
while (vars_arity--) {
mark_external_reference(vars_ptr PASS_REGS);
vars_ptr--;
}
}
vars_ptr--; /* skip vars_arity entry */
if (heap_arity) {
while (heap_arity--) {
if (*vars_ptr == 0) /* double/longint extension mark */
break;
mark_external_reference(vars_ptr PASS_REGS);
vars_ptr--;
}
}
}
nargs = 0;
break;
#endif /* TABLING */
case _profiled_retry_and_mark:
case _count_retry_and_mark:
case _retry_and_mark:
mark_ref_in_use((DBRef)ClauseCodeToDynamicClause(gc_B->cp_ap) PASS_REGS);
case _retry2:
nargs = 2;
break;
case _retry3:
nargs = 3;
break;
case _retry4:
nargs = 4;
break;
case _try_logical:
case _retry_logical:
{
/* find out who owns this sequence of try-retry-trust */
/* I don't like this code, it's a bad idea to do a linear scan,
on the other hand it's the only way we can be sure we can reclaim
space
*/
yamop *end = rtp->u.OtaLl.n;
while (end->opc != trust_lu &&
end->opc != count_trust_lu &&
end->opc != profiled_trust_lu )
end = end->u.OtaLl.n;
mark_ref_in_use((DBRef)end->u.OtILl.block PASS_REGS);
}
/* mark timestamp */
nargs = rtp->u.OtaLl.s+1;
break;
case _count_retry_logical:
{
/* find out who owns this sequence of try-retry-trust */
/* I don't like this code, it's a bad idea to do a linear scan,
on the other hand it's the only way we can be sure we can reclaim
space
*/
yamop *end = rtp->u.OtaLl.n;
while (Yap_op_from_opcode(end->opc) != _count_trust_logical)
end = end->u.OtaLl.n;
mark_ref_in_use((DBRef)end->u.OtILl.block PASS_REGS);
}
/* mark timestamp */
nargs = rtp->u.OtaLl.s+1;
break;
case _profiled_retry_logical:
{
/* find out who owns this sequence of try-retry-trust */
/* I don't like this code, it's a bad idea to do a linear scan,
on the other hand it's the only way we can be sure we can reclaim
space
*/
yamop *end = rtp->u.OtaLl.n;
while (Yap_op_from_opcode(end->opc) != _profiled_trust_logical)
end = end->u.OtaLl.n;
mark_ref_in_use((DBRef)end->u.OtILl.block PASS_REGS);
}
/* mark timestamp */
nargs = rtp->u.OtaLl.s+1;
break;
case _trust_logical:
case _count_trust_logical:
case _profiled_trust_logical:
/* mark timestamp */
mark_ref_in_use((DBRef)rtp->u.OtILl.block PASS_REGS);
nargs = rtp->u.OtILl.d->ClPred->ArityOfPE+1;
break;
#ifdef DEBUG
case _retry_me:
case _trust_me:
case _profiled_retry_me:
case _profiled_trust_me:
case _count_retry_me:
case _count_trust_me:
case _retry:
case _trust:
if (IN_BETWEEN(H0,(CELL *)(gc_B->cp_ap),H)) {
fprintf(stderr,"OOPS in GC: gc not supported in this case!!!\n");
exit(1);
}
nargs = rtp->u.Otapl.s;
break;
default:
fprintf(GLOBAL_stderr, "OOPS in GC: Unexpected opcode: %d\n", opnum);
nargs = 0;
#else
default:
nargs = rtp->u.Otapl.s;
#endif
}
if (gc_B->cp_ap == lu_cl0 ||
gc_B->cp_ap == lu_cl ||
gc_B->cp_ap == lu_cle ||
gc_B->cp_ap == su_cl) {
yamop *pt = (yamop *)IntegerOfTerm(gc_B->cp_args[1]);
if (gc_B->cp_ap == su_cl) {
mark_db_fixed((CELL *)pt PASS_REGS);
} else {
while (pt->opc != trust_lu &&
pt->opc != count_trust_lu &&
pt->opc != profiled_trust_lu
)
pt = pt->u.OtaLl.n;
mark_ref_in_use((DBRef)pt->u.OtILl.block PASS_REGS);
}
}
/* for each saved register */
for (saved_reg = &gc_B->cp_a1;
/* assumes we can count registers in CP this
way */
saved_reg < &gc_B->cp_a1 + nargs;
saved_reg++) {
mark_external_reference(saved_reg PASS_REGS);
}
}
#if TABLING
gc_B = youngest_cp(gc_B->cp_b, &depfr);
#else
gc_B = gc_B->cp_b;
#endif /* TABLING */
}
}
/*
* insert a cell which points to a heap object into relocation chain of that
* object
*/
static inline void
into_relocation_chain(CELL_PTR current, CELL_PTR next USES_REGS)
{
CELL current_tag;
current_tag = TAG(*current);
if (RMARKED(next))
RMARK(current);
else {
UNRMARK(current);
RMARK(next);
}
*current = *next;
*next = (CELL) current | current_tag;
}
static void
CleanDeadClauses( USES_REGS1 )
{
{
StaticClause **cptr;
StaticClause *cl;
cptr = &(DeadStaticClauses);
cl = DeadStaticClauses;
while (cl) {
if (!ref_in_use((DBRef)cl PASS_REGS)) {
char *ocl = (char *)cl;
Yap_ClauseSpace -= cl->ClSize;
cl = cl->ClNext;
*cptr = cl;
Yap_FreeCodeSpace(ocl);
} else {
cptr = &(cl->ClNext);
cl = cl->ClNext;
}
}
}
{
StaticIndex **cptr;
StaticIndex *cl;
cptr = &(DeadStaticIndices);
cl = DeadStaticIndices;
while (cl) {
if (!ref_in_use((DBRef)cl PASS_REGS)) {
char *ocl = (char *)cl;
if (cl->ClFlags & SwitchTableMask)
Yap_IndexSpace_SW -= cl->ClSize;
else
Yap_IndexSpace_Tree -= cl->ClSize;
cl = cl->SiblingIndex;
*cptr = cl;
Yap_FreeCodeSpace(ocl);
} else {
cptr = &(cl->SiblingIndex);
cl = cl->SiblingIndex;
}
}
}
{
MegaClause **cptr;
MegaClause *cl;
cptr = &(DeadMegaClauses);
cl = DeadMegaClauses;
while (cl) {
if (!ref_in_use((DBRef)cl PASS_REGS)) {
char *ocl = (char *)cl;
Yap_ClauseSpace -= cl->ClSize;
cl = cl->ClNext;
*cptr = cl;
Yap_FreeCodeSpace(ocl);
} else {
cptr = &(cl->ClNext);
cl = cl->ClNext;
}
}
}
}
/* insert trail cells which point to heap objects into relocation chains */
static void
sweep_trail(choiceptr gc_B, tr_fr_ptr old_TR USES_REGS)
{
tr_fr_ptr trail_ptr, dest;
Int OldHeapUsed = HeapUsed;
#ifdef DEBUG
Int hp_entrs = 0, hp_erased = 0, hp_not_in_use = 0,
hp_in_use_erased = 0, code_entries = 0;
#endif
CELL *ptr = LOCAL_extra_gc_cells;
while (ptr > LOCAL_extra_gc_cells_base) {
Int k = ptr[-1], i;
ptr = ptr-1;
for (i = 0; i < k; i++) {
ptr--;
if (IN_BETWEEN(LOCAL_GlobalBase,ptr[0],LOCAL_TrailTop) &&
MARKED_PTR(ptr)) {
UNMARK(ptr);
if (HEAP_PTR(ptr[0])) {
into_relocation_chain(ptr, GET_NEXT(ptr[0]) PASS_REGS);
}
}
}
}
#ifndef FROZEN_STACKS
{
choiceptr current = gc_B;
choiceptr next = gc_B->cp_b;
tr_fr_ptr source, dest;
/* invert cp ptrs */
current->cp_b = NULL;
while (next) {
choiceptr n = next;
next = n->cp_b;
n->cp_b = current;
current = n;
}
next = current;
current = NULL;
/* next, clean trail */
source = dest = (tr_fr_ptr)LOCAL_TrailBase;
while (source < old_TR) {
CELL trail_cell;
while (next && source == next->cp_tr) {
choiceptr b = next;
b->cp_tr = dest;
next = b->cp_b;
b->cp_b = current;
current = b;
}
trail_cell = TrailTerm(source);
if (trail_cell != (CELL)source) {
dest++;
}
source++;
}
while (next) {
choiceptr b = next;
b->cp_tr = dest;
next = b->cp_b;
b->cp_b = current;
current = b;
}
}
#endif /* FROZEN_STACKS */
/* first, whatever we dumped on the trail. Easier just to do
the registers separately? */
for (trail_ptr = old_TR; trail_ptr < TR; trail_ptr++) {
if (IN_BETWEEN(LOCAL_GlobalBase,TrailTerm(trail_ptr),LOCAL_TrailTop) &&
MARKED_PTR(&TrailTerm(trail_ptr))) {
UNMARK(&TrailTerm(trail_ptr));
if (HEAP_PTR(TrailTerm(trail_ptr))) {
into_relocation_chain(&TrailTerm(trail_ptr), GET_NEXT(TrailTerm(trail_ptr)) PASS_REGS);
}
}
}
/* next, follows the real trail entries */
trail_ptr = (tr_fr_ptr)LOCAL_TrailBase;
dest = trail_ptr;
while (trail_ptr < old_TR) {
register CELL trail_cell;
trail_cell = TrailTerm(trail_ptr);
#ifndef FROZEN_STACKS
/* recover a trail cell */
if (trail_cell == (CELL)trail_ptr) {
TrailTerm(dest) = trail_cell;
trail_ptr++;
/* just skip cell */
} else
#endif
{
TrailTerm(dest) = trail_cell;
if (IsVarTerm(trail_cell)) {
/* we need to check whether this is a honest to god trail entry */
/* make sure it is a heap cell before we test whether it has been marked */
if ((CELL *)trail_cell < H && (CELL *)trail_cell >= H0 && MARKED_PTR((CELL *)trail_cell)) {
if (HEAP_PTR(trail_cell)) {
into_relocation_chain(&TrailTerm(dest), GET_NEXT(trail_cell) PASS_REGS);
}
}
#ifdef FROZEN_STACKS
/* it is complex to recover cells with frozen segments */
TrailVal(dest) = TrailVal(trail_ptr);
if (MARKED_PTR(&TrailVal(dest))) {
if (HEAP_PTR(TrailVal(dest))) {
into_relocation_chain(&TrailVal(dest), GET_NEXT(TrailVal(dest)) PASS_REGS);
}
}
#endif
} else if (IsPairTerm(trail_cell)) {
CELL *pt0 = RepPair(trail_cell);
CELL flags;
if (IN_BETWEEN(LOCAL_GlobalBase, pt0, H)) {
if (GlobalIsAttVar(pt0)) {
TrailTerm(dest) = trail_cell;
/* be careful with partial gc */
if (HEAP_PTR(TrailTerm(dest))) {
into_relocation_chain(&TrailTerm(dest), GET_NEXT(trail_cell) PASS_REGS);
}
} else if (*pt0 == (CELL)FunctorBigInt) {
TrailTerm(dest) = trail_cell;
/* be careful with partial gc */
if (HEAP_PTR(TrailTerm(dest))) {
into_relocation_chain(&TrailTerm(dest), GET_NEXT(trail_cell) PASS_REGS);
}
}
dest++;
trail_ptr++;
continue;
}
#ifdef FROZEN_STACKS /* TRAIL */
/* process all segments */
if (
#ifdef YAPOR_SBA
(ADDR) pt0 >= LOCAL_GlobalBase
#else
(ADDR) pt0 >= LOCAL_TrailBase
#endif
) {
trail_ptr++;
dest++;
continue;
}
#endif /* FROZEN_STACKS */
flags = *pt0;
#ifdef DEBUG
hp_entrs++;
if (!ref_in_use((DBRef)pt0 PASS_REGS)) {
hp_not_in_use++;
if (!FlagOn(DBClMask, flags)) {
code_entries++;
}
if (FlagOn(ErasedMask, flags)) {
hp_erased++;
}
} else {
if (FlagOn(ErasedMask, flags)) {
hp_in_use_erased++;
}
}
#endif
if (!ref_in_use((DBRef)pt0 PASS_REGS)) {
if (FlagOn(DBClMask, flags)) {
DBRef dbr = (DBRef) ((CELL)pt0 - (CELL) &(((DBRef) NIL)->Flags));
dbr->Flags &= ~InUseMask;
DEC_DBREF_COUNT(dbr);
if (dbr->Flags & ErasedMask) {
Yap_ErDBE(dbr);
}
} else {
if (flags & LogUpdMask) {
if (flags & IndexMask) {
LogUpdIndex *indx = ClauseFlagsToLogUpdIndex(pt0);
int erase;
#if defined(YAPOR) || defined(THREADS)
/*
gc may be called when executing a dynamic goal,
check PP to avoid deadlock
*/
PredEntry *ap = indx->ClPred;
if (ap != PP)
PELOCK(85,ap);
#endif
DEC_CLREF_COUNT(indx);
indx->ClFlags &= ~InUseMask;
erase = (indx->ClFlags & ErasedMask
&& !indx->ClRefCount);
if (erase) {
/* at this point,
no one is accessing the clause */
Yap_ErLogUpdIndex(indx);
}
#if defined(YAPOR) || defined(THREADS)
if (ap != PP)
UNLOCK(ap->PELock);
#endif
} else {
LogUpdClause *cl = ClauseFlagsToLogUpdClause(pt0);
#if defined(YAPOR) || defined(THREADS)
PredEntry *ap = cl->ClPred;
#endif
int erase;
#if defined(YAPOR) || defined(THREADS)
if (ap != PP)
PELOCK(86,ap);
#endif
DEC_CLREF_COUNT(cl);
cl->ClFlags &= ~InUseMask;
erase = ((cl->ClFlags & ErasedMask) && !cl->ClRefCount);
if (erase) {
/* at this point,
no one is accessing the clause */
Yap_ErLogUpdCl(cl);
}
#if defined(YAPOR) || defined(THREADS)
if (ap != PP)
UNLOCK(ap->PELock);
#endif
}
} else {
DynamicClause *cl = ClauseFlagsToDynamicClause(pt0);
int erase;
DEC_CLREF_COUNT(cl);
cl->ClFlags &= ~InUseMask;
erase = (cl->ClFlags & ErasedMask)
#if defined(YAPOR) || defined(THREADS)
&& (cl->ClRefCount == 0)
#endif
;
if (erase) {
/* at this point,
no one is accessing the clause */
Yap_ErCl(cl);
}
}
}
RESET_VARIABLE(&TrailTerm(dest));
#ifdef FROZEN_STACKS
RESET_VARIABLE(&TrailVal(dest));
#endif
LOCAL_discard_trail_entries++;
}
#if MULTI_ASSIGNMENT_VARIABLES
} else {
#ifdef FROZEN_STACKS
CELL trail_cell = TrailTerm(trail_ptr+1);
CELL old = TrailVal(trail_ptr);
CELL old1 = TrailVal(trail_ptr+1);
Int marked_ptr = MARKED_PTR(&TrailTerm(trail_ptr+1));
Int marked_val_old = MARKED_PTR(&TrailVal(trail_ptr));
Int marked_val_ptr = MARKED_PTR(&TrailVal(trail_ptr+1));
TrailTerm(dest+1) = TrailTerm(dest) = trail_cell;
TrailVal(dest) = old;
TrailVal(dest+1) = old1;
if (marked_ptr) {
UNMARK(&TrailTerm(dest));
UNMARK(&TrailTerm(dest+1));
if (HEAP_PTR(trail_cell)) {
into_relocation_chain(&TrailTerm(dest), GET_NEXT(trail_cell) PASS_REGS);
into_relocation_chain(&TrailTerm(dest+1), GET_NEXT(trail_cell) PASS_REGS);
}
}
if (marked_val_old) {
UNMARK(&TrailVal(dest));
if (HEAP_PTR(old)) {
into_relocation_chain(&TrailVal(dest), GET_NEXT(old) PASS_REGS);
}
}
if (marked_val_ptr) {
UNMARK(&TrailVal(dest+1));
if (HEAP_PTR(old1)) {
into_relocation_chain(&TrailVal(dest+1), GET_NEXT(old1) PASS_REGS);
}
}
trail_ptr ++;
dest ++;
#else
CELL trail_cell = TrailTerm(trail_ptr+2);
CELL old = TrailTerm(trail_ptr+1);
Int marked_ptr = MARKED_PTR(&TrailTerm(trail_ptr+2));
Int marked_old = MARKED_PTR(&TrailTerm(trail_ptr+1));
CELL *ptr;
/* be sure we don't overwrite before we read */
if (marked_ptr)
ptr = RepAppl(UNMARK_CELL(trail_cell));
else
ptr = RepAppl(trail_cell);
TrailTerm(dest+1) = old;
if (marked_old) {
UNMARK(&TrailTerm(dest+1));
if (HEAP_PTR(old)) {
into_relocation_chain(&TrailTerm(dest+1), GET_NEXT(old) PASS_REGS);
}
}
TrailTerm(dest+2) = TrailTerm(dest) = trail_cell;
if (marked_ptr) {
UNMARK(&TrailTerm(dest));
UNMARK(&TrailTerm(dest+2));
if (HEAP_PTR(trail_cell)) {
into_relocation_chain(&TrailTerm(dest), GET_NEXT(trail_cell) PASS_REGS);
into_relocation_chain(&TrailTerm(dest+2), GET_NEXT(trail_cell) PASS_REGS);
}
}
trail_ptr += 2;
dest += 2;
#endif
#endif
}
trail_ptr++;
dest++;
}
}
LOCAL_new_TR = dest;
if (is_gc_verbose()) {
if (old_TR != (tr_fr_ptr)LOCAL_TrailBase)
fprintf(GLOBAL_stderr,
"%% Trail: discarded %d (%ld%%) cells out of %ld\n",
LOCAL_discard_trail_entries,
(unsigned long int)(LOCAL_discard_trail_entries*100/(old_TR-(tr_fr_ptr)LOCAL_TrailBase)),
(unsigned long int)(old_TR-(tr_fr_ptr)LOCAL_TrailBase));
#ifdef DEBUG
if (hp_entrs > 0)
fprintf(GLOBAL_stderr,
"%% Trail: unmarked %ld dbentries (%ld%%) out of %ld\n",
(long int)hp_not_in_use,
(long int)(hp_not_in_use*100/hp_entrs),
(long int)hp_entrs);
if (hp_in_use_erased > 0 && hp_erased > 0)
fprintf(GLOBAL_stderr,
"%% Trail: deleted %ld dbentries (%ld%%) out of %ld\n",
(long int)hp_erased,
(long int)(hp_erased*100/(hp_erased+hp_in_use_erased)),
(long int)(hp_erased+hp_in_use_erased));
#endif
if (OldHeapUsed) {
fprintf(GLOBAL_stderr,
"%% Heap: recovered %ld bytes (%ld%%) out of %ld\n",
(unsigned long int)(OldHeapUsed-HeapUsed),
(unsigned long int)((OldHeapUsed-HeapUsed)/(OldHeapUsed/100)),
(unsigned long int)OldHeapUsed);
}
}
CleanDeadClauses( PASS_REGS1 );
}
/*
* insert cells of a chain of environments which point to heap objects into
* relocation chains
*/
static void
sweep_environments(CELL_PTR gc_ENV, OPREG size, CELL *pvbmap USES_REGS)
{
CELL_PTR saved_var;
while (gc_ENV != NULL) { /* no more environments */
Int bmap = 0;
int currv = 0;
/* for each saved variable */
if (size > EnvSizeInCells) {
int tsize = size - EnvSizeInCells;
currv = sizeof(CELL)*8-tsize%(sizeof(CELL)*8);
if (pvbmap != NULL) {
pvbmap += tsize/(sizeof(CELL)*8);
bmap = *pvbmap;
} else {
bmap = ((CELL)-1);
}
bmap = (Int)(((CELL)bmap) << currv);
}
for (saved_var = gc_ENV - size; saved_var < gc_ENV - EnvSizeInCells; saved_var++) {
if (currv == sizeof(CELL)*8) {
if (pvbmap != NULL) {
pvbmap--;
bmap = *pvbmap;
} else {
bmap = ((CELL)-1);
}
currv = 0;
}
if (bmap < 0) {
CELL env_cell = *saved_var;
if (MARKED_PTR(saved_var)) {
UNMARK(saved_var);
if (HEAP_PTR(env_cell)) {
into_relocation_chain(saved_var, GET_NEXT(env_cell) PASS_REGS);
}
}
}
bmap <<= 1;
currv++;
}
/* have we met this environment before?? */
/* we use the B field in the environment to tell whether we have
been here before or not
*/
if (!MARKED_PTR(gc_ENV+E_CB))
return;
UNMARK(gc_ENV+E_CB);
size = EnvSize((yamop *) (gc_ENV[E_CP])); /* size = EnvSize(CP) */
pvbmap = EnvBMap((yamop *) (gc_ENV[E_CP]));
gc_ENV = (CELL_PTR) gc_ENV[E_E]; /* link to prev
* environment */
}
}
static void
sweep_slots( USES_REGS1 )
{
Int curslot = CurSlot;
while (curslot) {
CELL *ptr = LCL0-curslot;
Int ns = IntOfTerm(*ptr);
ptr++;
while (ns > 0) {
CELL cp_cell = *ptr;
if (MARKED_PTR(ptr)) {
UNMARK(ptr);
if (HEAP_PTR(cp_cell)) {
into_relocation_chain(ptr, GET_NEXT(cp_cell) PASS_REGS);
}
}
ptr++;
ns--;
}
curslot = IntegerOfTerm(*ptr);
}
}
static void
sweep_b(choiceptr gc_B, UInt arity USES_REGS)
{
register CELL_PTR saved_reg;
sweep_environments(gc_B->cp_env,
EnvSize((yamop *) (gc_B->cp_cp)),
EnvBMap((yamop *) (gc_B->cp_cp)) PASS_REGS);
/* for each saved register */
for (saved_reg = &gc_B->cp_a1;
saved_reg < &gc_B->cp_a1 + arity;
saved_reg++) {
CELL cp_cell = *saved_reg;
if (MARKED_PTR(saved_reg)) {
UNMARK(saved_reg);
if (HEAP_PTR(cp_cell)) {
into_relocation_chain(saved_reg, GET_NEXT(cp_cell) PASS_REGS);
}
}
}
}
/*
* insert cells of each choicepoint & its chain of environments which point
* to heap objects into relocation chains
*/
static void
sweep_choicepoints(choiceptr gc_B USES_REGS)
{
#ifdef TABLING
dep_fr_ptr depfr = LOCAL_top_dep_fr;
sg_fr_ptr aux_sg_fr = LOCAL_top_sg_fr;
#endif /* TABLING */
#ifdef TABLING
gc_B = youngest_cp(gc_B, &depfr);
#endif /* TABLING */
while (gc_B != NULL) {
yamop *rtp = gc_B->cp_ap;
register OPCODE op;
op_numbers opnum;
#ifdef TABLING
if (rtp == NULL) {
if (aux_sg_fr && gc_B == SgFr_gen_cp(aux_sg_fr)) {
/* found generator */
opnum = _table_completion;
} else {
/* found sld node is done */
opnum = _trust_fail;
}
} else {
#endif /* TABLING */
op = rtp->opc;
opnum = Yap_op_from_opcode(op);
#ifdef TABLING
}
if (aux_sg_fr && gc_B == SgFr_gen_cp(aux_sg_fr)) {
aux_sg_fr = SgFr_next(aux_sg_fr);
}
#endif /* TABLING */
restart_cp:
/*
* fprintf(GLOBAL_stderr,"sweeping cps: %x, %x, %x\n",
* *gc_B,CP_Extra(gc_B),CP_Nargs(gc_B));
*/
/* any choice point */
switch (opnum) {
case _Nstop:
/* end of the road, say bye bye! */
sweep_environments(gc_B->cp_env,
EnvSizeInCells,
NULL PASS_REGS);
if (gc_B->cp_b != NULL) {
break;
} else
return;
case _trust_fail:
break;
case _or_else:
case _or_last:
sweep_environments((CELL_PTR)(gc_B->cp_a1),
-gc_B->cp_cp->u.Osblp.s / ((OPREG)sizeof(CELL)),
gc_B->cp_cp->u.Osblp.bmap
PASS_REGS);
break;
case _retry_profiled:
case _count_retry:
rtp = NEXTOP(rtp,l);
op = rtp->opc;
opnum = Yap_op_from_opcode(op);
goto restart_cp;
case _jump:
rtp = rtp->u.l.l;
op = rtp->opc;
opnum = Yap_op_from_opcode(op);
goto restart_cp;
#ifdef TABLING
case _table_load_answer:
{
CELL *vars_ptr, vars;
sweep_environments(gc_B->cp_env, EnvSize(gc_B->cp_cp), EnvBMap(gc_B->cp_cp) PASS_REGS);
vars_ptr = (CELL *) (LOAD_CP(gc_B) + 1);
vars = *vars_ptr++;
while (vars--) {
CELL cp_cell = *vars_ptr;
if (MARKED_PTR(vars_ptr)) {
UNMARK(vars_ptr);
if (HEAP_PTR(cp_cell)) {
into_relocation_chain(vars_ptr, GET_NEXT(cp_cell) PASS_REGS);
}
}
vars_ptr++;
}
}
break;
case _table_try_answer:
case _table_retry_me:
case _table_trust_me:
case _table_retry:
case _table_trust:
{
int nargs;
CELL *vars_ptr, vars;
sweep_environments(gc_B->cp_env, EnvSize(gc_B->cp_cp), EnvBMap(gc_B->cp_cp) PASS_REGS);
vars_ptr = (CELL *)(GEN_CP(gc_B) + 1);
nargs = rtp->u.Otapl.s;
while(nargs--) {
CELL cp_cell = *vars_ptr;
if (MARKED_PTR(vars_ptr)) {
UNMARK(vars_ptr);
if (HEAP_PTR(cp_cell)) {
into_relocation_chain(vars_ptr, GET_NEXT(cp_cell) PASS_REGS);
}
}
vars_ptr++;
}
vars = *vars_ptr++;
while (vars--) {
CELL cp_cell = *vars_ptr;
if (MARKED_PTR(vars_ptr)) {
UNMARK(vars_ptr);
if (HEAP_PTR(cp_cell)) {
into_relocation_chain(vars_ptr, GET_NEXT(cp_cell) PASS_REGS);
}
}
vars_ptr++;
}
}
break;
case _table_completion:
#ifdef THREADS_CONSUMER_SHARING
case _table_answer_resolution_completion:
#endif /* THREADS_CONSUMER_SHARING */
{
int nargs;
CELL *vars_ptr, vars;
#ifdef DETERMINISTIC_TABLING
if (IS_DET_GEN_CP(gc_B))
vars_ptr = (CELL *)(DET_GEN_CP(gc_B) + 1);
else
#endif /* DETERMINISTIC_TABLING */
{
sweep_environments(gc_B->cp_env, EnvSize(gc_B->cp_cp), EnvBMap(gc_B->cp_cp) PASS_REGS);
vars_ptr = (CELL *)(GEN_CP(gc_B) + 1);
nargs = SgFr_arity(GEN_CP(gc_B)->cp_sg_fr);
while(nargs--) {
CELL cp_cell = *vars_ptr;
if (MARKED_PTR(vars_ptr)) {
UNMARK(vars_ptr);
if (HEAP_PTR(cp_cell)) {
into_relocation_chain(vars_ptr, GET_NEXT(cp_cell) PASS_REGS);
}
}
vars_ptr++;
}
}
vars = *vars_ptr++;
while (vars--) {
CELL cp_cell = *vars_ptr;
if (MARKED_PTR(vars_ptr)) {
UNMARK(vars_ptr);
if (HEAP_PTR(cp_cell)) {
into_relocation_chain(vars_ptr, GET_NEXT(cp_cell) PASS_REGS);
}
}
vars_ptr++;
}
}
break;
case _table_answer_resolution:
{
CELL *vars_ptr, vars;
sweep_environments(gc_B->cp_env, EnvSize(gc_B->cp_cp), EnvBMap(gc_B->cp_cp) PASS_REGS);
init_substitution_pointer(gc_B, vars_ptr, CONS_CP(gc_B)->cp_dep_fr);
vars = *vars_ptr++;
while (vars--) {
CELL cp_cell = *vars_ptr;
if (MARKED_PTR(vars_ptr)) {
UNMARK(vars_ptr);
if (HEAP_PTR(cp_cell)) {
into_relocation_chain(vars_ptr, GET_NEXT(cp_cell) PASS_REGS);
}
}
vars_ptr++;
}
}
break;
case _trie_trust_var:
case _trie_retry_var:
case _trie_trust_var_in_pair:
case _trie_retry_var_in_pair:
case _trie_trust_val:
case _trie_retry_val:
case _trie_trust_val_in_pair:
case _trie_retry_val_in_pair:
case _trie_trust_atom:
case _trie_retry_atom:
case _trie_trust_atom_in_pair:
case _trie_retry_atom_in_pair:
case _trie_trust_null:
case _trie_retry_null:
case _trie_trust_null_in_pair:
case _trie_retry_null_in_pair:
case _trie_trust_pair:
case _trie_retry_pair:
case _trie_trust_appl:
case _trie_retry_appl:
case _trie_trust_appl_in_pair:
case _trie_retry_appl_in_pair:
case _trie_trust_extension:
case _trie_retry_extension:
case _trie_trust_double:
case _trie_retry_double:
case _trie_trust_longint:
case _trie_retry_longint:
case _trie_trust_gterm:
case _trie_retry_gterm:
{
CELL *vars_ptr;
int heap_arity, vars_arity, subs_arity;
sweep_environments(gc_B->cp_env, EnvSize(gc_B->cp_cp), EnvBMap(gc_B->cp_cp) PASS_REGS);
vars_ptr = (CELL *)(gc_B + 1);
heap_arity = vars_ptr[0];
vars_arity = vars_ptr[1 + heap_arity];
subs_arity = vars_ptr[2 + heap_arity + vars_arity];
vars_ptr += 2 + heap_arity + subs_arity + vars_arity;
if (subs_arity) {
while (subs_arity--) {
CELL cp_cell = *vars_ptr;
if (MARKED_PTR(vars_ptr)) {
UNMARK(vars_ptr);
if (HEAP_PTR(cp_cell)) {
into_relocation_chain(vars_ptr, GET_NEXT(cp_cell) PASS_REGS);
}
}
vars_ptr--;
}
}
vars_ptr--; /* skip subs_arity entry */
if (vars_arity) {
while (vars_arity--) {
CELL cp_cell = *vars_ptr;
if (MARKED_PTR(vars_ptr)) {
UNMARK(vars_ptr);
if (HEAP_PTR(cp_cell)) {
into_relocation_chain(vars_ptr, GET_NEXT(cp_cell) PASS_REGS);
}
}
vars_ptr--;
}
}
vars_ptr--; /* skip vars_arity entry */
if (heap_arity) {
while (heap_arity--) {
CELL cp_cell = *vars_ptr;
if (*vars_ptr == 0) /* double/longint extension mark */
break;
if (MARKED_PTR(vars_ptr)) {
UNMARK(vars_ptr);
if (HEAP_PTR(cp_cell)) {
into_relocation_chain(vars_ptr, GET_NEXT(cp_cell) PASS_REGS);
}
}
vars_ptr--;
}
}
}
break;
#endif /* TABLING */
case _try_logical:
case _retry_logical:
case _count_retry_logical:
case _profiled_retry_logical:
/* sweep timestamp */
sweep_b(gc_B, rtp->u.OtaLl.s+1 PASS_REGS);
break;
case _trust_logical:
case _count_trust_logical:
case _profiled_trust_logical:
sweep_b(gc_B, rtp->u.OtILl.d->ClPred->ArityOfPE+1 PASS_REGS);
break;
case _retry2:
sweep_b(gc_B, 2 PASS_REGS);
break;
case _retry3:
sweep_b(gc_B, 3 PASS_REGS);
break;
case _retry4:
sweep_b(gc_B, 4 PASS_REGS);
break;
case _retry_c:
case _retry_userc:
{
register CELL_PTR saved_reg;
/* for each extra saved register */
for (saved_reg = &(gc_B->cp_a1)+rtp->u.OtapFs.s;
saved_reg < &(gc_B->cp_a1)+rtp->u.OtapFs.s+rtp->u.OtapFs.extra;
saved_reg++) {
CELL cp_cell = *saved_reg;
if (MARKED_PTR(saved_reg)) {
UNMARK(saved_reg);
if (HEAP_PTR(cp_cell)) {
into_relocation_chain(saved_reg, GET_NEXT(cp_cell) PASS_REGS);
}
}
}
}
/* continue to clean environments and arguments */
default:
sweep_b(gc_B,rtp->u.Otapl.s PASS_REGS);
}
/* link to prev choicepoint */
#if TABLING
gc_B = youngest_cp(gc_B->cp_b, &depfr);
#else
gc_B = gc_B->cp_b;
#endif /* TABLING */
}
}
/* update a relocation chain to point all its cells to new location of object */
static void
update_relocation_chain(CELL_PTR current, CELL_PTR dest USES_REGS)
{
CELL_PTR next;
CELL ccur = *current;
int rmarked = RMARKED(current);
UNRMARK(current);
while (rmarked) {
CELL current_tag;
next = GET_NEXT(ccur);
current_tag = TAG(ccur);
ccur = *next;
rmarked = RMARKED(next);
UNRMARK(next);
*next = (CELL) dest | current_tag;
}
*current = ccur;
}
static inline choiceptr
update_B_H( choiceptr gc_B, CELL *current, CELL *dest, CELL *odest
#ifdef TABLING
, dep_fr_ptr *depfrp
#endif /* TABLING */
) {
/* also make the value of H in a choicepoint
coherent with the new global
*/
#ifdef TABLING
dep_fr_ptr depfr = *depfrp;
#endif /* TABLING */
while (gc_B && current <= gc_B->cp_h) {
if (gc_B->cp_h == current) {
gc_B->cp_h = dest;
} else {
gc_B->cp_h = odest;
}
gc_B = gc_B->cp_b;
#ifdef TABLING
/* make sure we include consumers */
if (depfr && gc_B >= DepFr_cons_cp(depfr)) {
gc_B = DepFr_cons_cp(depfr);
*depfrp = depfr = DepFr_next(depfr);
}
#endif /* TABLING */
}
return gc_B;
}
static inline CELL *
set_next_hb(choiceptr gc_B USES_REGS)
{
if (gc_B) {
return gc_B->cp_h;
} else {
return H0;
}
}
/*
* move marked objects on the heap upwards over unmarked objects, and reset
* all pointers to point to new locations
*/
static void
compact_heap( USES_REGS1 )
{
CELL_PTR dest, current, next;
#ifdef DEBUG
Int found_marked = 0;
#endif /* DEBUG */
choiceptr gc_B = B;
int in_garbage = 0;
CELL *next_hb;
CELL *start_from = H0;
#ifdef TABLING
dep_fr_ptr depfr = LOCAL_top_dep_fr;
#endif /* TABLING */
/*
* upward phase - scan heap from high to low, setting marked upward
* ptrs to point to what will be the new locations of the
* objects pointed to
*/
#ifdef TABLING
if (depfr && gc_B >= DepFr_cons_cp(depfr)) {
gc_B = DepFr_cons_cp(depfr);
depfr = DepFr_next(depfr);
}
#endif /* TABLING */
next_hb = set_next_hb(gc_B PASS_REGS);
dest = H0 + LOCAL_total_marked - 1;
gc_B = update_B_H(gc_B, H, dest+1, dest+2
#ifdef TABLING
, &depfr
#endif /* TABLING */
);
for (current = H - 1; current >= start_from; current--) {
if (MARKED_PTR(current)) {
CELL ccell = UNMARK_CELL(*current);
if (in_garbage > 0) {
current[1] = in_garbage;
in_garbage = 0;
}
if (current <= next_hb) {
gc_B = update_B_H(gc_B, current, dest, dest+1
#ifdef TABLING
, &depfr
#endif /* TABLING */
);
next_hb = set_next_hb(gc_B PASS_REGS);
}
if (ccell == EndSpecials) {
/* oops, we found a blob */
CELL *ptr = current-1;
UInt nofcells;
while (!MARKED_PTR(ptr)) {
ptr--;
}
nofcells = current-ptr;
ptr++;
MARK(ptr);
#ifdef DEBUG
found_marked+=nofcells;
#endif
/* first swap the tag so that it will be seen by the next step */
current[0] = ptr[0];
ptr[0] = EndSpecials;
dest -= nofcells;
current = ptr;
/* process the functor on a separate cycle */
DEBUG_printf21("%p %ld\n", current-1, (long int)(nofcells+1));
continue;
} else {
DEBUG_printf20("%p 1\n", current);
}
#ifdef DEBUG
found_marked++;
#endif /* DEBUG */
update_relocation_chain(current, dest PASS_REGS);
if (HEAP_PTR(*current)) {
next = GET_NEXT(*current);
if (next < current) /* push into reloc.
* chain */
into_relocation_chain(current, next PASS_REGS);
else if (current == next) { /* cell pointing to
* itself */
UNRMARK(current);
*current = (CELL) dest; /* no tag */
}
}
dest--;
} else {
in_garbage++;
}
}
if (in_garbage)
start_from[0] = in_garbage;
#ifdef DEBUG
if (dest != start_from-1)
fprintf(GLOBAL_stderr,"%% Bad Dest (%lu): %p should be %p\n",
(unsigned long int)LOCAL_GcCalls,
dest,
start_from-1);
if (LOCAL_total_marked != found_marked)
fprintf(GLOBAL_stderr,"%% Upward (%lu): %lu total against %lu found\n",
(unsigned long int)LOCAL_GcCalls,
(unsigned long int)LOCAL_total_marked,
(unsigned long int)found_marked);
found_marked = start_from-H0;
#endif
/*
* downward phase - scan heap from low to high, moving marked objects
* to their new locations & setting downward pointers to pt to new
* locations
*/
dest = (CELL_PTR) start_from;
for (current = start_from; current < H; current++) {
CELL ccur = *current;
if (MARKED_PTR(current)) {
CELL uccur = UNMARK_CELL(ccur);
if (uccur == EndSpecials) {
CELL *old_dest = dest;
dest++;
current++;
while (!MARKED_PTR(current)) {
*dest++ = *current++;
}
*old_dest = *current;
/* if we have are calling from the C-interface,
we may have an open array when we start the gc */
if (LOCAL_OpenArray) {
CELL *start = current + (dest-old_dest);
if (LOCAL_OpenArray < current &&
LOCAL_OpenArray > start) {
UInt off = LOCAL_OpenArray-start;
LOCAL_OpenArray = old_dest+off;
}
}
*dest++ = EndSpecials;
#ifdef DEBUG
found_marked += (dest-old_dest);
#endif
continue;
}
#ifdef DEBUG
found_marked++;
#endif
update_relocation_chain(current, dest PASS_REGS);
ccur = *current;
next = GET_NEXT(ccur);
if (HEAP_PTR(ccur) &&
(next = GET_NEXT(ccur)) < H && /* move current cell &
* push */
next > current) { /* into relocation chain */
*dest = ccur;
into_relocation_chain(dest, next PASS_REGS);
UNMARK(dest);
} else {
/* just move current cell */
*dest = ccur = UNMARK_CELL(ccur);
}
/* next cell, please */
dest++;
} else {
current += (ccur-1);
}
}
#ifdef DEBUG
if (LOCAL_total_marked != found_marked)
fprintf(GLOBAL_stderr,"%% Downward (%lu): %lu total against %lu found\n",
(unsigned long int)LOCAL_GcCalls,
(unsigned long int)LOCAL_total_marked,
(unsigned long int)found_marked);
#endif
H = dest; /* reset H */
HB = B->cp_h;
#ifdef TABLING
if (B_FZ == (choiceptr)LCL0)
H_FZ = H0;
else
H_FZ = B_FZ->cp_h;
#endif /* TABLING */
}
#ifdef HYBRID_SCHEME
/*
* move marked objects on the heap upwards over unmarked objects, and reset
* all pointers to point to new locations
*/
static void
icompact_heap( USES_REGS1 )
{
CELL_PTR *iptr, *ibase = (CELL_PTR *)H;
CELL_PTR dest;
CELL *next_hb;
#ifdef DEBUG
Int found_marked = 0;
#endif /* DEBUG */
#ifdef TABLING
dep_fr_ptr depfr = LOCAL_top_dep_fr;
#endif /* TABLING */
choiceptr gc_B = B;
/*
* upward phase - scan heap from high to low, setting marked upward
* ptrs to point to what will be the new locations of the
* objects pointed to
*/
#ifdef TABLING
if (depfr && gc_B >= DepFr_cons_cp(depfr)) {
gc_B = DepFr_cons_cp(depfr);
depfr = DepFr_next(depfr);
}
#endif /* TABLING */
next_hb = set_next_hb(gc_B PASS_REGS);
dest = (CELL_PTR) H0 + LOCAL_total_marked - 1;
gc_B = update_B_H(gc_B, H, dest+1, dest+2
#ifdef TABLING
, &depfr
#endif /* TABLING */
);
for (iptr = LOCAL_iptop - 1; iptr >= ibase; iptr--) {
CELL ccell;
CELL_PTR current;
current = *iptr;
ccell = UNMARK_CELL(*current);
if (current <= next_hb) {
gc_B = update_B_H(gc_B, current, dest, dest+1
#ifdef TABLING
, &depfr
#endif /* TABLING */
);
next_hb = set_next_hb(gc_B PASS_REGS);
}
if (ccell == EndSpecials) {
/* oops, we found a blob */
CELL_PTR ptr;
UInt nofcells;
/* use the first cell after the functor for all our dirty tricks */
ptr = iptr[-1]+1;
nofcells = current-ptr;
#ifdef DEBUG
found_marked+=(nofcells+1);
#endif /* DEBUG */
dest -= nofcells+1;
/* this one's being used */
/* make the second step see the EndSpecial tag */
current[0] = ptr[0];
ptr[0] = EndSpecials;
iptr[0] = ptr;
continue;
}
#ifdef DEBUG
found_marked++;
#endif /* DEBUG */
update_relocation_chain(current, dest PASS_REGS);
if (HEAP_PTR(*current)) {
CELL_PTR next;
next = GET_NEXT(*current);
if (next < current) /* push into reloc.
* chain */
into_relocation_chain(current, next PASS_REGS);
else if (current == next) { /* cell pointing to
* itself */
UNRMARK(current);
*current = (CELL) dest; /* no tag */
}
}
dest--;
}
#ifdef DEBUG
if (dest != H0-1)
fprintf(GLOBAL_stderr,"%% Bad Dest (%lu): %p should be %p\n",
(unsigned long int)LOCAL_GcCalls,
dest,
H0-1);
if (LOCAL_total_marked != found_marked)
fprintf(GLOBAL_stderr,"%% Upward (%lu): %lu total against %lu found\n",
(unsigned long int)LOCAL_GcCalls,
(unsigned long int)LOCAL_total_marked,
(unsigned long int)found_marked);
found_marked = 0;
#endif
/*
* downward phase - scan heap from low to high, moving marked objects
* to their new locations & setting downward pointers to pt to new
* locations
*/
dest = H0;
for (iptr = ibase; iptr < LOCAL_iptop; iptr++) {
CELL_PTR next;
CELL *current = *iptr;
CELL ccur = *current;
CELL uccur = UNMARK_CELL(ccur);
if (uccur == EndSpecials) {
CELL *old_dest = dest;
/* leave a hole */
dest++;
current++;
while (!MARKED_PTR(current)) {
*dest++ = *current++;
}
/* fill in hole */
*old_dest = *current;
*dest++ = EndSpecials;
#ifdef DEBUG
found_marked += dest-old_dest;
#endif
continue;
}
#ifdef DEBUG
found_marked++;
#endif
update_relocation_chain(current, dest PASS_REGS);
ccur = *current;
next = GET_NEXT(ccur);
if (HEAP_PTR(ccur) && /* move current cell &
* push */
next > current) { /* into relocation chain */
*dest = ccur;
into_relocation_chain(dest, next PASS_REGS);
UNMARK(dest);
dest++;
} else {
/* just move current cell */
*dest++ = ccur = UNMARK_CELL(ccur);
}
}
#ifdef DEBUG
if (H0+LOCAL_total_marked != dest)
fprintf(GLOBAL_stderr,"%% Downward (%lu): %p total against %p found\n",
(unsigned long int)LOCAL_GcCalls,
H0+LOCAL_total_marked,
dest);
if (LOCAL_total_marked != found_marked)
fprintf(GLOBAL_stderr,"%% Downward (%lu): %lu total against %lu found\n",
(unsigned long int)LOCAL_GcCalls,
(unsigned long int)LOCAL_total_marked,
(unsigned long int)found_marked);
#endif
H = dest; /* reset H */
HB = B->cp_h;
#ifdef TABLING
if (B_FZ == (choiceptr)LCL0)
H_FZ = H0;
else
H_FZ = B_FZ->cp_h;
#endif /* TABLING */
}
#endif /* HYBRID_SCHEME */
#ifdef EASY_SHUNTING
static void
set_conditionals(tr_fr_ptr str USES_REGS) {
while (str != LOCAL_sTR0) {
CELL *cptr;
str -= 2;
cptr = (CELL *)TrailTerm(str+1);
*cptr = TrailTerm(str);
}
LOCAL_sTR = LOCAL_sTR0 = NULL;
}
#endif
/*
* mark all objects on the heap that are accessible from active registers,
* the trail, environments, and choicepoints
*/
static void
marking_phase(tr_fr_ptr old_TR, CELL *current_env, yamop *curp USES_REGS)
{
#ifdef EASY_SHUNTING
LOCAL_current_B = B;
LOCAL_prev_HB = H;
#endif
init_dbtable(old_TR PASS_REGS);
#ifdef EASY_SHUNTING
LOCAL_sTR0 = (tr_fr_ptr)LOCAL_db_vec;
LOCAL_sTR = (tr_fr_ptr)LOCAL_db_vec;
/* make sure we set HB before we do any variable shunting!!! */
#else
LOCAL_cont_top0 = (cont *)LOCAL_db_vec;
#endif
LOCAL_cont_top = (cont *)LOCAL_db_vec;
/* These two must be marked first so that our trail optimisation won't lose
values */
mark_slots( PASS_REGS1 );
mark_regs(old_TR PASS_REGS); /* active registers & trail */
/* active environments */
mark_environments(current_env, EnvSize(curp), EnvBMap(curp) PASS_REGS);
mark_choicepoints(B, old_TR, is_gc_very_verbose() PASS_REGS); /* choicepoints, and environs */
#ifdef EASY_SHUNTING
set_conditionals(LOCAL_sTR PASS_REGS);
#endif
}
static void
sweep_oldgen(CELL *max, CELL *base USES_REGS)
{
CELL *ptr = base;
char *bpb = LOCAL_bp+(base-(CELL*)LOCAL_GlobalBase);
while (ptr < max) {
if (*bpb) {
if (HEAP_PTR(*ptr)) {
into_relocation_chain(ptr, GET_NEXT(*ptr) PASS_REGS);
}
}
ptr++;
bpb++;
}
}
/*
* move marked heap objects upwards over unmarked objects, and reset all
* pointers to point to new locations
*/
static void
compaction_phase(tr_fr_ptr old_TR, CELL *current_env, yamop *curp USES_REGS)
{
CELL *CurrentH0 = NULL;
int icompact = (LOCAL_iptop < (CELL_PTR *)ASP && 10*LOCAL_total_marked < H-H0);
if (icompact) {
/* we are going to reuse the total space */
if (LOCAL_HGEN != H0) {
/* undo optimisation */
LOCAL_total_marked += LOCAL_total_oldies;
}
} else {
if (LOCAL_HGEN != H0) {
CurrentH0 = H0;
H0 = LOCAL_HGEN;
sweep_oldgen(LOCAL_HGEN, CurrentH0 PASS_REGS);
}
}
sweep_slots( PASS_REGS1 );
sweep_environments(current_env, EnvSize(curp), EnvBMap(curp) PASS_REGS);
sweep_choicepoints(B PASS_REGS);
sweep_trail(B, old_TR PASS_REGS);
#ifdef HYBRID_SCHEME
if (icompact) {
#ifdef DEBUG
/*
if (LOCAL_total_marked
#ifdef COROUTINING
-LOCAL_total_smarked
#endif
!= LOCAL_iptop-(CELL_PTR *)H && LOCAL_iptop < (CELL_PTR *)ASP -1024)
fprintf(GLOBAL_stderr,"%% Oops on LOCAL_iptop-H (%ld) vs %ld\n", (unsigned long int)(LOCAL_iptop-(CELL_PTR *)H), LOCAL_total_marked);
*/
#endif
#if DEBUGX
int effectiveness = (((H-H0)-LOCAL_total_marked)*100)/(H-H0);
fprintf(GLOBAL_stderr,"%% using pointers (%d)\n", effectiveness);
#endif
if (CurrentH0) {
H0 = CurrentH0;
LOCAL_HGEN = H0;
LOCAL_total_marked += LOCAL_total_oldies;
CurrentH0 = NULL;
}
quicksort((CELL_PTR *)H, 0, (LOCAL_iptop-(CELL_PTR *)H)-1);
icompact_heap( PASS_REGS1 );
} else
#endif /* HYBRID_SCHEME */
{
#ifdef DEBUG
/*
#ifdef HYBRID_SCHEME
int effectiveness = (((H-H0)-LOCAL_total_marked)*100)/(H-H0);
fprintf(stderr,"%% not using pointers (%d) ASP: %p, ip %p (expected %p) \n", effectiveness, ASP, LOCAL_iptop, H+LOCAL_total_marked);
#endif
*/
#endif
compact_heap( PASS_REGS1 );
}
if (CurrentH0) {
H0 = CurrentH0;
#ifdef TABLING
/* make sure that we have the correct H_FZ if we're not tabling */
if (B_FZ == (choiceptr)LCL0)
H_FZ = H0;
#endif /* TABLING */
}
}
static int
do_gc(Int predarity, CELL *current_env, yamop *nextop USES_REGS)
{
Int heap_cells;
int gc_verbose;
volatile tr_fr_ptr old_TR = NULL;
UInt m_time, c_time, time_start, gc_time;
Int effectiveness, tot;
int gc_trace;
UInt gc_phase;
UInt alloc_sz;
int jmp_res;
heap_cells = H-H0;
gc_verbose = is_gc_verbose();
effectiveness = 0;
gc_trace = FALSE;
LOCAL_GcCalls++;
#ifdef INSTRUMENT_GC
{
int i;
for (i=0; i<16; i++)
chain[i]=0;
vars[gc_var] = 0;
vars[gc_ref] = 0;
vars[gc_atom] = 0;
vars[gc_int] = 0;
vars[gc_num] = 0;
vars[gc_list] = 0;
vars[gc_appl] = 0;
vars[gc_func] = 0;
vars[gc_susp] = 0;
env_vars = 0;
old_vars = new_vars = 0;
TrueHB = HB;
num_bs = 0;
}
#endif
#ifdef DEBUG
check_global();
#endif
if (Yap_GetValue(AtomGcTrace) != TermNil)
gc_trace = 1;
if (gc_trace) {
fprintf(GLOBAL_stderr, "%% gc\n");
} else if (gc_verbose) {
#if defined(YAPOR) || defined(THREADS)
fprintf(GLOBAL_stderr, "%% Worker Id %d:\n", worker_id);
#endif
fprintf(GLOBAL_stderr, "%% Start of garbage collection %lu:\n", (unsigned long int)LOCAL_GcCalls);
fprintf(GLOBAL_stderr, "%% Global: %8ld cells (%p-%p)\n", (long int)heap_cells,H0,H);
fprintf(GLOBAL_stderr, "%% Local:%8ld cells (%p-%p)\n", (unsigned long int)(LCL0-ASP),LCL0,ASP);
fprintf(GLOBAL_stderr, "%% Trail:%8ld cells (%p-%p)\n",
(unsigned long int)(TR-(tr_fr_ptr)LOCAL_TrailBase),LOCAL_TrailBase,TR);
}
#if !USE_SYSTEM_MALLOC
if (HeapTop >= LOCAL_GlobalBase - MinHeapGap) {
*--ASP = (CELL)current_env;
if (!Yap_growheap(FALSE, MinHeapGap, NULL)) {
Yap_Error(OUT_OF_HEAP_ERROR, TermNil, LOCAL_ErrorMessage);
return -1;
}
current_env = (CELL *)*ASP;
ASP++;
}
#endif
time_start = Yap_cputime();
jmp_res = sigsetjmp(LOCAL_gc_restore, 0);
if (jmp_res == 2) {
UInt sz;
/* we cannot recover, fail system */
restore_machine_regs();
sz = LOCAL_TrailTop-(ADDR)LOCAL_OldTR;
/* ask for double the size */
sz = 2*sz;
TR = LOCAL_OldTR;
*--ASP = (CELL)current_env;
if (
!Yap_growtrail(sz, FALSE)
) {
Yap_Error(OUT_OF_TRAIL_ERROR,TermNil,"out of %lB during gc", sz);
return -1;
} else {
LOCAL_total_marked = 0;
LOCAL_total_oldies = 0;
#ifdef COROUTING
LOCAL_total_smarked = 0;
#endif
LOCAL_discard_trail_entries = 0;
current_env = (CELL *)*ASP;
ASP++;
}
} else if (jmp_res == 3) {
/* we cannot recover, fail system */
restore_machine_regs();
TR = LOCAL_OldTR;
LOCAL_total_marked = 0;
LOCAL_total_oldies = 0;
#ifdef COROUTING
LOCAL_total_smarked = 0;
#endif
LOCAL_discard_trail_entries = 0;
if (LOCAL_extra_gc_cells_size < 1024 *104) {
LOCAL_extra_gc_cells_size <<= 1;
} else {
LOCAL_extra_gc_cells_size += 1024*1024;
}
} else if (jmp_res == 4) {
/* we cannot recover, fail completely */
Yap_exit(1);
}
#if EASY_SHUNTING
LOCAL_sTR0 = LOCAL_sTR = NULL;
#endif
LOCAL_total_marked = 0;
LOCAL_total_oldies = 0;
#ifdef COROUTING
LOCAL_total_smarked = 0;
#endif
LOCAL_discard_trail_entries = 0;
alloc_sz = (CELL *)LOCAL_TrailTop-(CELL*)LOCAL_GlobalBase;
LOCAL_bp = Yap_PreAllocCodeSpace();
while (IN_BETWEEN(LOCAL_bp, AuxSp, LOCAL_bp+alloc_sz)) {
/* not enough space */
*--ASP = (CELL)current_env;
LOCAL_bp = (char *)Yap_ExpandPreAllocCodeSpace(alloc_sz, NULL, TRUE);
if (!LOCAL_bp)
return -1;
current_env = (CELL *)*ASP;
ASP++;
}
memset((void *)LOCAL_bp, 0, alloc_sz);
#ifdef HYBRID_SCHEME
LOCAL_iptop = (CELL_PTR *)H;
#endif
/* get the number of active registers */
LOCAL_HGEN = VarOfTerm(Yap_ReadTimedVar(LOCAL_GcGeneration));
gc_phase = (UInt)IntegerOfTerm(Yap_ReadTimedVar(LOCAL_GcPhase));
/* old LOCAL_HGEN are not very reliable, but still may have data to recover */
if (gc_phase != LOCAL_GcCurrentPhase) {
LOCAL_HGEN = H0;
}
/* fprintf(stderr,"LOCAL_HGEN is %ld, %p, %p/%p\n", IntegerOfTerm(Yap_ReadTimedVar(LOCAL_GcGeneration)), LOCAL_HGEN, H,H0);*/
LOCAL_OldTR = (tr_fr_ptr)(old_TR = TR);
push_registers(predarity, nextop PASS_REGS);
/* make sure we clean bits after a reset */
marking_phase(old_TR, current_env, nextop PASS_REGS);
if (LOCAL_total_oldies > ((LOCAL_HGEN-H0)*8)/10) {
LOCAL_total_marked -= LOCAL_total_oldies;
tot = LOCAL_total_marked+(LOCAL_HGEN-H0);
} else {
if (LOCAL_HGEN != H0) {
LOCAL_HGEN = H0;
LOCAL_GcCurrentPhase++;
}
tot = LOCAL_total_marked;
}
m_time = Yap_cputime();
gc_time = m_time-time_start;
if (heap_cells) {
if (heap_cells > 1000000)
effectiveness = (heap_cells-tot)/(heap_cells/100);
else
effectiveness = 100*(heap_cells-tot)/heap_cells;
} else
effectiveness = 0;
if (gc_verbose) {
fprintf(GLOBAL_stderr, "%% Mark: Marked %ld cells of %ld (efficiency: %ld%%) in %g sec\n",
(long int)tot, (long int)heap_cells, (long int)effectiveness, (double)(m_time-time_start)/1000);
if (LOCAL_HGEN-H0)
fprintf(GLOBAL_stderr,"%% previous generation has size " UInt_FORMAT ", with " UInt_FORMAT " (" UInt_FORMAT "%%) unmarked\n", (UInt)(LOCAL_HGEN-H0), (UInt)((LOCAL_HGEN-H0)-LOCAL_total_oldies), (UInt)(100*((LOCAL_HGEN-H0)-LOCAL_total_oldies)/(LOCAL_HGEN-H0)));
#ifdef INSTRUMENT_GC
{
int i;
for (i=0; i<16; i++) {
if (chain[i]) {
fprintf(GLOBAL_stderr, "%% chain[%d]=%lu\n", i, chain[i]);
}
}
put_type_info((unsigned long int)tot);
fprintf(GLOBAL_stderr,"%% %lu/%ld before and %lu/%ld after\n", old_vars, (unsigned long int)(B->cp_h-H0), new_vars, (unsigned long int)(H-B->cp_h));
fprintf(GLOBAL_stderr,"%% %ld choicepoints\n", num_bs);
}
#endif
}
time_start = m_time;
compaction_phase(old_TR, current_env, nextop PASS_REGS);
TR = old_TR;
pop_registers(predarity, nextop PASS_REGS);
TR = LOCAL_new_TR;
/* fprintf(GLOBAL_stderr,"NEW LOCAL_HGEN %ld (%ld)\n", H-H0, LOCAL_HGEN-H0);*/
{
Term t = MkVarTerm();
Yap_UpdateTimedVar(LOCAL_GcGeneration, t);
}
Yap_UpdateTimedVar(LOCAL_GcPhase, MkIntegerTerm(LOCAL_GcCurrentPhase));
c_time = Yap_cputime();
if (gc_verbose) {
fprintf(GLOBAL_stderr, "%% Compress: took %g sec\n", (double)(c_time-time_start)/1000);
}
gc_time += (c_time-time_start);
LOCAL_TotGcTime += gc_time;
LOCAL_TotGcRecovered += heap_cells-tot;
if (gc_verbose) {
fprintf(GLOBAL_stderr, "%% GC %lu took %g sec, total of %g sec doing GC so far.\n", (unsigned long int)LOCAL_GcCalls, (double)gc_time/1000, (double)LOCAL_TotGcTime/1000);
fprintf(GLOBAL_stderr, "%% Left %ld cells free in stacks.\n",
(unsigned long int)(ASP-H));
}
check_global();
return effectiveness;
}
static int
is_gc_verbose(void)
{
CACHE_REGS
if (LOCAL_PrologMode == BootMode)
return FALSE;
#ifdef INSTRUMENT_GC
/* always give info when we are debugging gc */
return(TRUE);
#else
return(Yap_GetValue(AtomGcVerbose) != TermNil ||
Yap_GetValue(AtomGcVeryVerbose) != TermNil);
#endif
}
int
Yap_is_gc_verbose(void)
{
return is_gc_verbose();
}
static int
is_gc_very_verbose(void)
{
CACHE_REGS
if (LOCAL_PrologMode == BootMode)
return FALSE;
return Yap_GetValue(AtomGcVeryVerbose) != TermNil;
}
Int
Yap_total_gc_time(void)
{
CACHE_REGS
return(LOCAL_TotGcTime);
}
static Int
p_inform_gc( USES_REGS1 )
{
Term tn = MkIntegerTerm(LOCAL_TotGcTime);
Term tt = MkIntegerTerm(LOCAL_GcCalls);
Term ts = Yap_Mk64IntegerTerm((LOCAL_TotGcRecovered*sizeof(CELL)));
return(Yap_unify(tn, ARG2) && Yap_unify(tt, ARG1) && Yap_unify(ts, ARG3));
}
static int
call_gc(UInt gc_lim, Int predarity, CELL *current_env, yamop *nextop USES_REGS)
{
UInt gc_margin = MinStackGap;
Term Tgc_margin;
Int effectiveness = 0;
int gc_on = FALSE, gc_t = FALSE;
if (Yap_GetValue(AtomGc) != TermNil)
gc_on = TRUE;
if (IsIntegerTerm(Tgc_margin = Yap_GetValue(AtomGcMargin)) &&
gc_margin > 0) {
gc_margin = (UInt)IntegerOfTerm(Tgc_margin);
gc_t = TRUE;
} else {
/* only go exponential for the first 6 calls, that would ask about 2MB minimum */
if (LOCAL_GcCalls < 8)
gc_margin <<= LOCAL_GcCalls;
else {
/* next grow linearly */
gc_margin <<= 8;
/* don't do this: it forces the system to ask for ever more stack!!
gc_margin *= LOCAL_GcCalls;
*/
}
}
if (gc_margin < gc_lim)
gc_margin = gc_lim;
LOCAL_HGEN = VarOfTerm(Yap_ReadTimedVar(LOCAL_GcGeneration));
if (gc_on && !(LOCAL_PrologMode & InErrorMode) &&
/* make sure there is a point in collecting the heap */
(ASP-H0)*sizeof(CELL) > gc_lim &&
H-LOCAL_HGEN > (LCL0-ASP)/2) {
effectiveness = do_gc(predarity, current_env, nextop PASS_REGS);
if (effectiveness < 0)
return FALSE;
if (effectiveness > 90 && !gc_t) {
while (gc_margin < (H-H0)/sizeof(CELL))
gc_margin <<= 1;
}
} else {
effectiveness = 0;
}
/* expand the stack if effectiveness is less than 20 % */
if (ASP - H < gc_margin/sizeof(CELL) ||
effectiveness < 20) {
LeaveGCMode( PASS_REGS1 );
#ifndef YAPOR
if (gc_margin < 2*CalculateStackGap())
gc_margin = 2*CalculateStackGap();
return Yap_growstack(gc_margin);
#endif
}
/*
* debug for(save_total=1; save_total<=N; ++save_total)
* plwrite(XREGS[save_total],NULL,30,0,0);
*/
return TRUE;
}
static void
LeaveGCMode( USES_REGS1 )
{
if (LOCAL_PrologMode & GCMode)
LOCAL_PrologMode &= ~GCMode;
if (LOCAL_PrologMode & AbortMode) {
LOCAL_PrologMode &= ~AbortMode;
/* in case someone mangles the P register */
Yap_Error(PURE_ABORT, TermNil, "abort from console");
Yap_RestartYap( 1 );
}
}
int
Yap_gc(Int predarity, CELL *current_env, yamop *nextop)
{
CACHE_REGS
int res;
LOCAL_PrologMode |= GCMode;
res=call_gc(4096, predarity, current_env, nextop PASS_REGS);
LeaveGCMode( PASS_REGS1 );
if (LOCAL_PrologMode & GCMode)
LOCAL_PrologMode &= ~GCMode;
return res;
}
int
Yap_gcl(UInt gc_lim, Int predarity, CELL *current_env, yamop *nextop)
{
CACHE_REGS
int res;
UInt min = CalculateStackGap()*sizeof(CELL);
LOCAL_PrologMode |= GCMode;
if (gc_lim < min)
gc_lim = min;
res = call_gc(gc_lim, predarity, current_env, nextop PASS_REGS);
LeaveGCMode( PASS_REGS1 );
return res;
}
static Int
p_gc( USES_REGS1 )
{
int res;
LOCAL_PrologMode |= GCMode;
if (P->opc == Yap_opcode(_execute_cpred))
res = do_gc(0, ENV, CP PASS_REGS) >= 0;
else
res = do_gc(0, ENV, P PASS_REGS) >= 0;
LeaveGCMode( PASS_REGS1 );
return res;
}
void
Yap_init_gc(void)
{
Yap_InitCPred("$gc", 0, p_gc, HiddenPredFlag);
Yap_InitCPred("$inform_gc", 3, p_inform_gc, HiddenPredFlag);
}
void
Yap_inc_mark_variable()
{
CACHE_REGS
LOCAL_total_marked++;
}
|
511594.c | //------------------------------------------------------------------------------
// cube-sapp.c
//------------------------------------------------------------------------------
#define HANDMADE_MATH_IMPLEMENTATION
#define HANDMADE_MATH_NO_SSE
#include "HandmadeMath.h"
#include "sokol_gfx.h"
#include "sokol_app.h"
#include "sokol_glue.h"
#include "dbgui/dbgui.h"
#include "cube-sapp.glsl.h"
static struct {
float rx, ry;
sg_pipeline pip;
sg_bindings bind;
} state;
void init(void) {
sg_setup(&(sg_desc){
.context = sapp_sgcontext()
});
__dbgui_setup(sapp_sample_count());
/* cube vertex buffer */
float vertices[] = {
-1.0, -1.0, -1.0, 1.0, 0.0, 0.0, 1.0,
1.0, -1.0, -1.0, 1.0, 0.0, 0.0, 1.0,
1.0, 1.0, -1.0, 1.0, 0.0, 0.0, 1.0,
-1.0, 1.0, -1.0, 1.0, 0.0, 0.0, 1.0,
-1.0, -1.0, 1.0, 0.0, 1.0, 0.0, 1.0,
1.0, -1.0, 1.0, 0.0, 1.0, 0.0, 1.0,
1.0, 1.0, 1.0, 0.0, 1.0, 0.0, 1.0,
-1.0, 1.0, 1.0, 0.0, 1.0, 0.0, 1.0,
-1.0, -1.0, -1.0, 0.0, 0.0, 1.0, 1.0,
-1.0, 1.0, -1.0, 0.0, 0.0, 1.0, 1.0,
-1.0, 1.0, 1.0, 0.0, 0.0, 1.0, 1.0,
-1.0, -1.0, 1.0, 0.0, 0.0, 1.0, 1.0,
1.0, -1.0, -1.0, 1.0, 0.5, 0.0, 1.0,
1.0, 1.0, -1.0, 1.0, 0.5, 0.0, 1.0,
1.0, 1.0, 1.0, 1.0, 0.5, 0.0, 1.0,
1.0, -1.0, 1.0, 1.0, 0.5, 0.0, 1.0,
-1.0, -1.0, -1.0, 0.0, 0.5, 1.0, 1.0,
-1.0, -1.0, 1.0, 0.0, 0.5, 1.0, 1.0,
1.0, -1.0, 1.0, 0.0, 0.5, 1.0, 1.0,
1.0, -1.0, -1.0, 0.0, 0.5, 1.0, 1.0,
-1.0, 1.0, -1.0, 1.0, 0.0, 0.5, 1.0,
-1.0, 1.0, 1.0, 1.0, 0.0, 0.5, 1.0,
1.0, 1.0, 1.0, 1.0, 0.0, 0.5, 1.0,
1.0, 1.0, -1.0, 1.0, 0.0, 0.5, 1.0
};
sg_buffer vbuf = sg_make_buffer(&(sg_buffer_desc){
.size = sizeof(vertices),
.content = vertices,
.label = "cube-vertices"
});
/* create an index buffer for the cube */
uint16_t indices[] = {
0, 1, 2, 0, 2, 3,
6, 5, 4, 7, 6, 4,
8, 9, 10, 8, 10, 11,
14, 13, 12, 15, 14, 12,
16, 17, 18, 16, 18, 19,
22, 21, 20, 23, 22, 20
};
sg_buffer ibuf = sg_make_buffer(&(sg_buffer_desc){
.type = SG_BUFFERTYPE_INDEXBUFFER,
.size = sizeof(indices),
.content = indices,
.label = "cube-indices"
});
/* create shader */
sg_shader shd = sg_make_shader(cube_shader_desc());
/* create pipeline object */
state.pip = sg_make_pipeline(&(sg_pipeline_desc){
.layout = {
/* test to provide buffer stride, but no attr offsets */
.buffers[0].stride = 28,
.attrs = {
[ATTR_vs_position].format = SG_VERTEXFORMAT_FLOAT3,
[ATTR_vs_color0].format = SG_VERTEXFORMAT_FLOAT4
}
},
.shader = shd,
.index_type = SG_INDEXTYPE_UINT16,
.depth_stencil = {
.depth_compare_func = SG_COMPAREFUNC_LESS_EQUAL,
.depth_write_enabled = true,
},
.rasterizer.cull_mode = SG_CULLMODE_BACK,
.label = "cube-pipeline"
});
/* setup resource bindings */
state.bind = (sg_bindings) {
.vertex_buffers[0] = vbuf,
.index_buffer = ibuf
};
}
void frame(void) {
/* NOTE: the vs_params_t struct has been code-generated by the shader-code-gen */
vs_params_t vs_params;
const float w = (float) sapp_width();
const float h = (float) sapp_height();
hmm_mat4 proj = HMM_Perspective(60.0f, w/h, 0.01f, 10.0f);
hmm_mat4 view = HMM_LookAt(HMM_Vec3(0.0f, 1.5f, 6.0f), HMM_Vec3(0.0f, 0.0f, 0.0f), HMM_Vec3(0.0f, 1.0f, 0.0f));
hmm_mat4 view_proj = HMM_MultiplyMat4(proj, view);
state.rx += 1.0f; state.ry += 2.0f;
hmm_mat4 rxm = HMM_Rotate(state.rx, HMM_Vec3(1.0f, 0.0f, 0.0f));
hmm_mat4 rym = HMM_Rotate(state.ry, HMM_Vec3(0.0f, 1.0f, 0.0f));
hmm_mat4 model = HMM_MultiplyMat4(rxm, rym);
vs_params.mvp = HMM_MultiplyMat4(view_proj, model);
sg_pass_action pass_action = {
.colors[0] = { .action = SG_ACTION_CLEAR, .val = { 0.25f, 0.5f, 0.75f, 1.0f } }
};
sg_begin_default_pass(&pass_action, (int)w, (int)h);
sg_apply_pipeline(state.pip);
sg_apply_bindings(&state.bind);
sg_apply_uniforms(SG_SHADERSTAGE_VS, SLOT_vs_params, &vs_params, sizeof(vs_params));
sg_draw(0, 36, 1);
__dbgui_draw();
sg_end_pass();
sg_commit();
}
void cleanup(void) {
__dbgui_shutdown();
sg_shutdown();
}
sapp_desc sokol_main(int argc, char* argv[]) {
(void)argc;
(void)argv;
return (sapp_desc){
.init_cb = init,
.frame_cb = frame,
.cleanup_cb = cleanup,
.event_cb = __dbgui_event,
.width = 800,
.height = 600,
.sample_count = 4,
.gl_force_gles2 = true,
.window_title = "Cube (sokol-app)",
};
}
|
865722.c | /* -*- Mode: c; c-basic-offset: 2 -*-
*
* raptor_utf8.c - Raptor Unicode Normal Form C (NFC) support
*
* Copyright (C) 2004-2006, David Beckett http://purl.org/net/dajobe/
* Copyright (C) 2004-2004, University of Bristol, UK http://www.bristol.ac.uk/
*
* This package is Free Software and part of Redland http://librdf.org/
*
* It is licensed under the following three licenses as alternatives:
* 1. GNU Lesser General Public License (LGPL) V2.1 or any newer version
* 2. GNU General Public License (GPL) V2 or any newer version
* 3. Apache License, V2.0 or any newer version
*
* You may not use this file except in compliance with at least one of
* the above three licenses.
*
* See LICENSE.html or LICENSE.txt at the top of this package for the
* complete terms and further detail along with the license texts for
* the licenses in COPYING.LIB, COPYING and LICENSE-2.0.txt respectively.
*
*
* See Unicode Normalization http://unicode.org/unicode/reports/tr15/
* for the definition of Unicode Normal Form C (NFC)
*
*/
#ifdef HAVE_CONFIG_H
#include <raptor_config.h>
#endif
#ifdef WIN32
#include <win32_raptor_config.h>
#endif
#ifdef HAVE_STDLIB_H
#include <stdlib.h>
#endif
#include <stdio.h>
#include <stdarg.h>
#ifdef HAVE_STDLIB_H
#include <stdlib.h>
#endif
/* Raptor includes */
#include "raptor.h"
#include "raptor_internal.h"
#include "raptor_nfc.h"
#undef RAPTOR_DEBUG_NFC_CHECK
/*
* raptor_nfc_check_combiners - Check for allowed combining characters
* @base: first character (U+0...U+FFFF)
* @follow: second character (U+0...U+FFFF)
*
* Return value: non-0 if combination is allowed
*/
static int
raptor_nfc_check_combiners(u16 base, u16 follow)
{
int low=0;
int high=RAPTOR_NFC_RECOMBINERS_COUNT;
while(low < high) {
int middle=(low+high)/2;
u16 middle_base=raptor_nfc_recombiners[middle].base;
if(base == middle_base) {
/* found base */
u16 middle_follow=raptor_nfc_recombiners[middle].follow;
if(middle_follow == follow)
/* success */
return 1;
/* otherwise need to binary search for further 'follow'
* values for this base
*/
if(follow < middle_follow)
high=middle;
else
low=middle+1;
} else if(base < middle_base)
high=middle;
else
low=middle+1;
}
return raptor_nfc_recombiners[low].base == base &&
raptor_nfc_recombiners[low].follow == follow;
}
static int
raptor_nfc_get_class(unsigned long key)
{
int low=0;
int high=RAPTOR_NFC_CLASSES_COUNT;
while (low < high) {
int middle=(low+high)/2;
unsigned int middle_key=raptor_nfc_classes[middle].key;
/* found class */
if(key == middle_key)
return raptor_nfc_classes[middle].combining_class;
/* otherwise need to binary search further */
if(key < middle_key)
high=middle;
else
low=middle+1;
}
return raptor_nfc_classes[low].combining_class;
}
static RAPTOR_INLINE raptor_nfc_code_flag
raptor_nfc_get_code_flag (unsigned long c)
{
if(c < 0x10900) {
/* U+0 to U+108FF - from flags table (first 0x10900 entries) */
if(c & 1)
return (raptor_nfc_code_flag)(raptor_nfc_flags[c>>1] & 0xF);
else
return (raptor_nfc_code_flag)(raptor_nfc_flags[c>>1] >>4);
} else if(c < 0x1D000)
/* U+10900 to U+1CFFF - codes do not exist */
return NoNo;
else if(c < 0x1D800) {
/* U+1D000 to U+1D7FF - from flags table (after first 0x10900) */
c -= (0x1D000-0x10900);
if(c & 1)
return (raptor_nfc_code_flag)(raptor_nfc_flags[c>>1] & 0xF);
else
return (raptor_nfc_code_flag)(raptor_nfc_flags[c>>1] >>4);
} else if(c < 0x20000)
/* U+1D800 to U+1FFFF - codes do not exist */
return NoNo;
else if(c < 0x2A6D7)
/* U+20000 to U+2A6D6 - CJK Ideograph Extension B - simple */
return simp;
else if(c < 0x2F800)
/* U+2A6D8 to U+2F7FF - codes do not exist */
return NoNo;
else if(c < 0x2FA1E)
/* U+2F800 to U+2FA1D - CJK Compatibility Ideographs Supplement - forbidden/excluded in NFC */
/* FIXME Unicode 4 says to 2FA1F */
return NOFC;
else if(c == 0xE0001)
/* U+E0001 - "Language Tag" - simple */
return simp;
else if(c < 0xE0020)
/* U+E0002 to U+E001F - codes do not exist */
return NoNo;
else if(c < 0xE0080)
/* U+E0020 to U+E007F - Tag components - simple */
return simp;
else if(c < 0xE0100)
/* U+E0080 to U+E00FF - codes do not exist */
return NoNo;
else if(c < 0xE01F0)
/* U+E0100 to U+E01EF - Variation Selectors Supplement - simple */
return simp;
else
/* otherwise does not exist/forbidden */
return NoNo;
}
#ifdef RAPTOR_DEBUG_NFC_CHECK
#define RAPTOR_NFC_CHECK_FAIL(char, reason) do { fprintf(stderr, "%s:%d:%s: NFC check failed on U+%04lX: " reason "\n", __FILE__, __LINE__, __func__, char); } while(0)
#else
#define RAPTOR_NFC_CHECK_FAIL(char, reason)
#endif
/**
* raptor_nfc_check:
* @input: UTF-8 string
* @length: length of string
* @errorp: pointer to store offset of character in error (or NULL)
*
* Unicode Normal Form C (NFC) check function.
*
* If errorp is not NULL, it is set to the offset of the character
* in error in the buffer, or <0 if there is no error.
*
* Return value: Non 0 if the string is NFC
**/
int
raptor_nfc_check (const unsigned char* string, size_t len, int *error)
{
const unsigned char* start;
int is_start;
size_t offset;
raptor_nfc_code_flag prev_char_flag=(raptor_nfc_code_flag)0;
unsigned long prev_char=0L;
int prev_class;
start=string;
is_start=1;
offset=0;
prev_class=0;
while(offset < len) {
raptor_unichar unichar;
int unichar_len;
int combining_class=0;
raptor_nfc_code_flag flag;
unichar_len=raptor_utf8_to_unicode_char(&unichar, string, len);
if(unichar_len < 0 || unichar_len > (int)len) {
/* UTF-8 encoding had an error or ended in the middle of a string */
if(error)
*error=offset;
RAPTOR_NFC_CHECK_FAIL(unichar, "UTF-8 decoding error");
return 0;
}
string += unichar_len;
offset += unichar_len;
len -= unichar_len;
flag = raptor_nfc_get_code_flag(unichar);
switch (flag) {
case HIGH:
case loww:
case NOFC:
/* Forbidden combinations:
* HIGH: high surrogate
*
* loww: low surrogate
*
* NOFC: Either singleton or excluded. Exclusions are given in:
* http://www.unicode.org/unicode/reports/tr15/#Primary_Exclusion_List_Table
* http://www.unicode.org/Public/UNIDATA/CompositionExclusions.txt
*/
if(error)
*error=offset;
RAPTOR_NFC_CHECK_FAIL(unichar, "forbidden combinations - HIGH, loww, NOFC");
return 0;
case NoNo:
/* character does not exist */
if(error)
*error=offset;
RAPTOR_NFC_CHECK_FAIL(unichar, "NoNo - character does not exist");
return 0;
case ReCo:
/* class > 0 and recombining */
/* class > 0 are forbidden at start */
if(is_start) {
if(error)
*error=offset;
RAPTOR_NFC_CHECK_FAIL(unichar, "ReCo at start");
return 0;
}
combining_class=raptor_nfc_get_class(unichar);
/* check 1 - previous class later than current, always an error */
if(prev_class > combining_class) {
if(error)
*error=offset;
RAPTOR_NFC_CHECK_FAIL(unichar, "ReCo and prev class > current");
return 0;
}
/* check 2 - previous class same as current - always OK */
/* check 3 - previous class earlier than current class.
* Only perform combining check when both are in range
*/
if(prev_class < combining_class &&
prev_char < 0x10000 && unichar < 0x10000 &&
raptor_nfc_check_combiners(prev_char, unichar)) {
if(error)
*error=offset;
RAPTOR_NFC_CHECK_FAIL(unichar, "ReCo and combiners check failed");
return 0;
}
break;
case NoRe:
/* class >0, not recombining */
/* class > 0 are forbidden at start */
if(is_start) {
if(error)
*error=offset;
RAPTOR_NFC_CHECK_FAIL(unichar, "NoRe at start");
return 0;
}
combining_class=raptor_nfc_get_class(unichar);
if(prev_class > combining_class) {
if(error)
*error=offset;
RAPTOR_NFC_CHECK_FAIL(unichar, "NoRe and prev class > current");
return 0;
}
break;
case COM0:
/* class is 0 and composing */
/* Composing characters forbidden at start */
if(is_start) {
if(error)
*error=offset;
RAPTOR_NFC_CHECK_FAIL(unichar, "COMB at start");
return 0;
}
/* Only perform combining check when both are in range */
if(prev_char < 0x10000 && unichar < 0x10000 &&
raptor_nfc_check_combiners(prev_char, unichar)) {
if(error)
*error=offset;
RAPTOR_NFC_CHECK_FAIL(unichar, "COMB and combiners check failed");
return 0;
}
combining_class=0;
break;
case Hang:
/* hangul Jamo (Korean) initial consonants */
combining_class=0;
break;
case hAng:
/* Hangul Jamo (Korean) medial vowels
* Must not be at the start and must not follow
* a Hangul initial consonant
*/
if(is_start || prev_char_flag == Hang) {
if(error)
*error=offset;
RAPTOR_NFC_CHECK_FAIL(unichar, "hAng at start");
return 0;
}
combining_class=0;
break;
case haNG:
/* hangul trailing consonants
* Must not be at the start and must not follow a
* hangul initial/medial syllable
*/
if(is_start || prev_char_flag == HAng) {
if(error)
*error=offset;
RAPTOR_NFC_CHECK_FAIL(unichar, "haNG at start");
return 0;
}
combining_class=0;
break;
case HAng:
/* Hangul Jamo (Korean) initial/medial syllables */
combining_class=0;
break;
case Base:
/* base that combines */
case simp:
/* simple characters */
combining_class=0;
break;
}
prev_char=unichar;
prev_char_flag=flag;
prev_class=combining_class;
is_start=0;
}
return 1;
}
|
842064.c | /* Created RJudd December 28, 1997 */
/* SPAWARSYSCEN D881 */
/**********************************************************************
// For TASP VSIPL Documentation and Code neither the United States /
// Government, the United States Navy, nor any of their employees, /
// makes any warranty, express or implied, including the warranties /
// of merchantability and fitness for a particular purpose, or /
// assumes any legal liability or responsibility for the accuracy, /
// completeness, or usefulness of any information, apparatus, /
// product, or process disclosed, or represents that its use would /
// not infringe privately owned rights /
**********************************************************************/
/* $Id: vsip_cvdiv_d.c,v 2.0 2003/02/22 15:18:50 judd Exp $ */
/* Modified RJudd June 28, 1998 */
/* to add complex block support */
/* Removed Tisdale error checking Sept 00 */
#include<vsip.h>
#include<vsip_cvviewattributes_d.h>
void (vsip_cvdiv_d)(
const vsip_cvview_d *a,
const vsip_cvview_d *b,
const vsip_cvview_d *r) {
{
/* register */ vsip_length n = r->length;
vsip_stride cast = a->block->cstride,
cbst = b->block->cstride,
crst = r->block->cstride;
vsip_scalar_d *apr = (vsip_scalar_d *)((a->block->R->array) + cast * a->offset),
*bpr = (vsip_scalar_d *)((b->block->R->array) + cbst * b->offset),
*rpr = (vsip_scalar_d *)((r->block->R->array) + crst * r->offset);
vsip_scalar_d *api = (vsip_scalar_d *)((a->block->I->array) + cast * a->offset),
*bpi = (vsip_scalar_d *)((b->block->I->array) + cbst * b->offset),
*rpi = (vsip_scalar_d *)((r->block->I->array) + crst * r->offset);
vsip_scalar_d temp,magbsq;
/* register */ vsip_stride ast = (cast * a->stride),
bst = (cbst * b->stride),
rst = (crst * r->stride);
/*end define*/
while(n-- > 0){
magbsq = (*bpr * *bpr + *bpi * *bpi);
temp = (*apr * *bpr + *api * *bpi) / magbsq;
*rpi = (*api * *bpr - *apr * *bpi) / magbsq;
*rpr = temp;
apr += ast; api += ast;
bpr += bst; bpi += bst;
rpr += rst; rpi += rst;
}
}
}
|
776080.c | /**
******************************************************************************
* @file MDR1986VE3_IT.c
* @author Milandr Application Team
* @version V1.2.0
* @date 03/04/2013
* @brief Main Interrupt Service Routines.
*
******************************************************************************
* <br><br>
*
* THE PRESENT FIRMWARE WHICH IS FOR GUIDANCE ONLY AIMS AT PROVIDING CUSTOMERS
* WITH CODING INFORMATION REGARDING THEIR PRODUCTS IN ORDER FOR THEM TO SAVE
* TIME. AS A RESULT, MILANDR SHALL NOT BE HELD LIABLE FOR ANY DIRECT, INDIRECT
* OR CONSEQUENTIAL DAMAGES WITH RESPECT TO ANY CLAIMS ARISING
* FROM THE CONTENT OF SUCH FIRMWARE AND/OR THE USE MADE BY CUSTOMERS OF THE
* CODING INFORMATION CONTAINED HEREIN IN CONNECTION WITH THEIR PRODUCTS.
*
* <h2><center>© COPYRIGHT 2013 Milandr</center></h2>
*/
/* Includes ------------------------------------------------------------------*/
#include "stdio.h"
#include "MDR32F9Qx_config.h"
#include "MDR32F9Qx_eth.h"
#include "MDR1986VE3.h"
#include "MDR1986VE3_IT.h"
#include "MDR32F9Qx_port.h"
#include "tcpip.h"
extern uint32_t InputFrame[1514/4];
/* Private typedef -----------------------------------------------------------*/
/* Private define ------------------------------------------------------------*/
/* Private macro -------------------------------------------------------------*/
#if defined (_USE_DEBUG_UART_)
#define DEBUG_PRINTF(...) printf(__VA_ARGS__)
#else
#define DEBUG_PRINTF(...)
#endif /* #if defined _USE_DEBUG_UART_ */
/* Private variables ---------------------------------------------------------*/
/* Private function prototypes -----------------------------------------------*/
void Hard_fault_handler_c(unsigned int* hardfault_args);
/* Private functions ---------------------------------------------------------*/
/*******************************************************************************
* Function Name : NMI_Handler
* Description : This function handles NMI exception.
* Input : None
* Output : None
* Return : None
*******************************************************************************/
void NMI_Handler(void)
{
}
/*******************************************************************************
* Function Name : HardFault_Handler
* Description : This function handles Hard Fault exception.
* Input : None
* Output : None
* Return : None
*******************************************************************************/
void HardFault_Handler(void)
{
unsigned int contr_reg;
contr_reg = __get_CONTROL();
if(contr_reg&2)
{
__ASM("MRS R0, PSP");
}
else{
__ASM("MRS R0, MSP");
}
//top of stack is in R0. It is passed to C-function.
__ASM("BL (Hard_fault_handler_c)");
/* Go to infinite loop when Hard Fault exception occurs */
while (1);
}
/*******************************************************************************
* Function Name : SVC_Handler
* Description : This function handles SVCall exception.
* Input : None
* Output : None
* Return : None
*******************************************************************************/
void SVC_Handler(void)
{
}
/*******************************************************************************
* Function Name : PendSV_Handler
* Description : This function handles Debug PendSV exception.
* Input : None
* Output : None
* Return : None
*******************************************************************************/
void PendSV_Handler(void)
{
}
/*******************************************************************************
* Function Name : SysTick_Handler
* Description : This function handles SysTick Handler.
* Input : None
* Output : None
* Return : None
*******************************************************************************/
void SysTick_Handler(void)
{
}
/*******************************************************************************
* Function Name : MIL_STD_1553B2_IRQHandler
* Description : This function handles MIL_STD_1553B2 global interrupt request.
* Input : None
* Output : None
* Return : None
*******************************************************************************/
void MIL_STD_1553B2_IRQHandler(void)
{
}
/*******************************************************************************
* Function Name : MIL_STD_1553B1_IRQHandler
* Description : This function handles MIL_STD_1553B1 global interrupt request.
* Input : None
* Output : None
* Return : None
*******************************************************************************/
void MIL_STD_1553B1_IRQHandler(void)
{
}
/*******************************************************************************
* Function Name : USB_IRQHandler
* Description : This function handles USB global interrupt request.
* Input : None
* Output : None
* Return : None
*******************************************************************************/
/*
void USB_IRQHandler(void)
{
}
*/
/*******************************************************************************
* Function Name : CAN1_IRQHandler
* Description : This function handles CAN1 global interrupt request.
* Input : None
* Output : None
* Return : None
*******************************************************************************/
void CAN1_IRQHandler(void)
{
}
/*******************************************************************************
* Function Name : CAN2_IRQHandler
* Description : This function handles CAN2 global interrupt request.
* Input : None
* Output : None
* Return : None
*******************************************************************************/
void CAN2_IRQHandler(void)
{
}
/*******************************************************************************
* Function Name : DMA_IRQHandler
* Description : This function handles DMA global interrupt request.
* Input : None
* Output : None
* Return : None
*******************************************************************************/
void DMA_IRQHandler(void)
{
}
/*******************************************************************************
* Function Name : UART1_IRQHandler
* Description : This function handles UART1 global interrupt request.
* Input : None
* Output : None
* Return : None
*******************************************************************************/
void UART1_IRQHandler(void)
{
}
/*******************************************************************************
* Function Name : UART2_IRQHandler
* Description : This function handles UART2 global interrupt request.
* Input : None
* Output : None
* Return : None
*******************************************************************************/
void UART2_IRQHandler(void)
{
}
/*******************************************************************************
* Function Name : SSP1_IRQHandler
* Description : This function handles SSP1 global interrupt request.
* Input : None
* Output : None
* Return : None
*******************************************************************************/
void SSP1_IRQHandler(void)
{
}
/*******************************************************************************
* Function Name : BUSY_IRQHandler
* Description : This function handles BUSY global interrupt request.
* Input : None
* Output : None
* Return : None
*******************************************************************************/
void BUSY_IRQHandler(void)
{
}
/*******************************************************************************
* Function Name : ARINC429R_IRQHandler
* Description : This function handles ARINC429R global interrupt request.
* Input : None
* Output : None
* Return : None
*******************************************************************************/
void ARINC429R_IRQHandler(void)
{
}
/*******************************************************************************
* Function Name : POWER_IRQHandler
* Description : This function handles POWER global interrupt request.
* Input : None
* Output : None
* Return : None
*******************************************************************************/
void POWER_IRQHandler(void)
{
}
/*******************************************************************************
* Function Name : WWDG_IRQHandler
* Description : This function handles WWDG global interrupt request.
* Input : None
* Output : None
* Return : None
*******************************************************************************/
void WWDG_IRQHandler(void)
{
}
/*******************************************************************************
* Function Name : TIMER4_IRQHandler
* Description : This function handles TIMER4 global interrupt request.
* Input : None
* Output : None
* Return : None
*******************************************************************************/
void TIMER4_IRQHandler(void)
{
}
/*******************************************************************************
* Function Name : Timer1_IRQHandler
* Description : This function handles Timer1 global interrupt request.
* Input : None
* Output : None
* Return : None
*******************************************************************************/
void Timer1_IRQHandler(void)
{
}
/*******************************************************************************
* Function Name : Timer2_IRQHandler
* Description : This function handles Timer2 global interrupt request.
* Input : None
* Output : None
* Return : None
*******************************************************************************/
void Timer2_IRQHandler(void)
{
}
/*******************************************************************************
* Function Name : Timer3_IRQHandler
* Description : This function handles Timer3 global interrupt request.
* Input : None
* Output : None
* Return : None
*******************************************************************************/
void Timer3_IRQHandler(void)
{
}
/*******************************************************************************
* Function Name : ADC_IRQHandler
* Description : This function handles ADC global interrupt request.
* Input : None
* Output : None
* Return : None
*******************************************************************************/
void ADC_IRQHandler(void)
{
}
/*******************************************************************************
* Function Name : ETHERNET_IRQHandler
* Description : This function handles ETHERNET global interrupt request.
* Input : None
* Output : None
* Return : None
*******************************************************************************/
void ETHERNET_IRQHandler(void)
{
}
/*******************************************************************************
* Function Name : SSP3_IRQHandler
* Description : This function handles SSP3 global interrupt request.
* Input : None
* Output : None
* Return : None
*******************************************************************************/
void SSP3_IRQHandler(void)
{
}
/*******************************************************************************
* Function Name : SSP2_IRQHandler
* Description : This function handles SSP2 global interrupt request.
* Input : None
* Output : None
* Return : None
*******************************************************************************/
void SSP2_IRQHandler(void)
{
}
/*******************************************************************************
* Function Name : ARINC429T1_IRQHandler
* Description : This function handles ARINC429T1 global interrupt request.
* Input : None
* Output : None
* Return : None
*******************************************************************************/
void ARINC429T1_IRQHandler(void)
{
}
/*******************************************************************************
* Function Name : ARINC429T2_IRQHandler
* Description : This function handles ARINC429T2 global interrupt request.
* Input : None
* Output : None
* Return : None
*******************************************************************************/
void ARINC429T2_IRQHandler(void)
{
}
/*******************************************************************************
* Function Name : ARINC429T3_IRQHandler
* Description : This function handles ARINC429T3 global interrupt request.
* Input : None
* Output : None
* Return : None
*******************************************************************************/
void ARINC429T3_IRQHandler(void)
{
}
/*******************************************************************************
* Function Name : ARINC429T3_IRQHandler
* Description : This function handles ARINC429T3 global interrupt request.
* Input : None
* Output : None
* Return : None
*******************************************************************************/
void ARINC429T4_IRQHandler(void)
{
}
/*******************************************************************************
* Function Name : BKP_IRQHandler
* Description : This function handles BKP global interrupt request.
* Input : None
* Output : None
* Return : None
*******************************************************************************/
void BKP_IRQHandler(void)
{
}
/*******************************************************************************
* Function Name : EXT_INT1_IRQHandler
* Description : This function handles EXT_INT1 interrupt request.
* Input : None
* Output : None
* Return : None
*******************************************************************************/
void EXT_INT1_IRQHandler(void)
{
}
/*******************************************************************************
* Function Name : EXT_INT2_IRQHandler
* Description : This function handles EXT_INT2 interrupt request.
* Input : None
* Output : None
* Return : None
*******************************************************************************/
void EXT_INT2_IRQHandler(void)
{
}
/*******************************************************************************
* Function Name : EXT_INT3_IRQHandler
* Description : This function handles EXT_INT3 global interrupt request.
* requests.
* Input : None
* Output : None
* Return : None
*******************************************************************************/
void EXT_INT3_IRQHandler(void)
{
}
/*******************************************************************************
* Function Name : EXT_INT4_IRQHandler
* Description : This function handles EXT_INT4 interrupt request.
* Input : None
* Output : None
* Return : None
*******************************************************************************/
void EXT_INT4_IRQHandler(void)
{
}
/**
* @brief
* @param
* @retval
*/
void Hard_fault_handler_c(unsigned int* hardfault_args)
{
unsigned int stacked_r0;
unsigned int stacked_r1;
unsigned int stacked_r2;
unsigned int stacked_r3;
unsigned int stacked_r12;
unsigned int stacked_lr;
unsigned int stacked_pc;
unsigned int stacked_psr;
stacked_r0 = ((unsigned long) hardfault_args[0]);
stacked_r1 = ((unsigned long) hardfault_args[1]);
stacked_r2 = ((unsigned long) hardfault_args[2]);
stacked_r3 = ((unsigned long) hardfault_args[3]);
stacked_r12 = ((unsigned long) hardfault_args[4]);
stacked_lr = ((unsigned long) hardfault_args[5]);
stacked_pc = ((unsigned long) hardfault_args[6]);
stacked_psr = ((unsigned long) hardfault_args[7]);
DEBUG_PRINTF("[Hard fault handler]\r\n");
DEBUG_PRINTF("R0 = 0x%x\r\n", stacked_r0);
DEBUG_PRINTF("R1 = 0x%x\r\n", stacked_r1);
DEBUG_PRINTF("R2 = 0x%x\r\n", stacked_r2);
DEBUG_PRINTF("R3 = 0x%x\r\n", stacked_r3);
DEBUG_PRINTF("R12 = 0x%x\r\n", stacked_r12);
DEBUG_PRINTF("LR = 0x%x\r\n", stacked_lr);
DEBUG_PRINTF("PC = 0x%x\r\n", stacked_pc);
DEBUG_PRINTF("PSR = 0x%x\r\n", stacked_psr);
/* Go to infinite loop when Hard Fault exception occurs */
while (1);
}
/******************* (C) COPYRIGHT 2013 Milandr *********/
/* END OF FILE MDR1986VE3_IT.c */
|
191130.c | /* $NetBSD: c_nec_eisa.c,v 1.2 2001/08/13 18:45:49 soda Exp $ */
/*-
* Copyright (C) 2000 Shuichiro URATA. 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 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.
*/
/*
* for NEC EISA generation machines.
*/
#include <sys/param.h>
#include <sys/systm.h>
#include <sys/device.h>
#include <uvm/uvm_extern.h>
#include <machine/autoconf.h>
#include <machine/pio.h>
#include <machine/platform.h>
#include <mips/pte.h>
#include <dev/isa/isavar.h>
#include <arc/arc/wired_map.h>
#include <arc/jazz/pica.h>
#include <arc/jazz/rd94.h>
#include <arc/jazz/jazziovar.h>
#include <arc/isa/isabrvar.h>
/*
* chipset-dependent isa bus configuration
*/
int isabr_nec_eisa_intr_status __P((void));
struct isabr_config isabr_nec_eisa_conf = {
isabr_nec_eisa_intr_status,
};
int
isabr_nec_eisa_intr_status()
{
return (in32(RD94_SYS_INTSTAT2) & (ICU_LEN - 1));
}
/*
* chipset-dependent jazzio bus configuration
*/
void jazzio_nec_eisa_set_iointr_mask __P((int));
struct jazzio_config jazzio_nec_eisa_conf = {
RD94_SYS_INTSTAT1,
jazzio_nec_eisa_set_iointr_mask,
RD94_SYS_TL_BASE,
RD94_SYS_DMA0_REGS,
};
void
jazzio_nec_eisa_set_iointr_mask(mask)
int mask;
{
out16(RD94_SYS_LB_IE2, mask);
}
/*
* critial i/o space, interrupt, and other chipset related initialization.
*/
void
c_nec_eisa_init()
{
/*
* Initialize I/O address offset
*/
arc_bus_space_init(&jazzio_bus, "jazzio",
RD94_P_LOCAL_IO_BASE, RD94_V_LOCAL_IO_BASE,
RD94_V_LOCAL_IO_BASE, RD94_S_LOCAL_IO_BASE);
/* XXX - not really confirmed */
arc_bus_space_init(&arc_bus_io, "r94eisaio",
RD94_P_PCI_IO, RD94_V_PCI_IO, 0, RD94_S_PCI_IO);
arc_bus_space_init(&arc_bus_mem, "r94eisamem",
RD94_P_PCI_MEM, RD94_V_PCI_MEM, 0, RD94_S_PCI_MEM);
/*
* Initialize wired TLB for I/O space which is used on early stage
*/
arc_enter_wired(RD94_V_LOCAL_IO_BASE, RD94_P_LOCAL_IO_BASE, 0,
MIPS3_PG_SIZE_256K);
arc_enter_wired(RD94_V_PCI_IO, RD94_P_PCI_IO, RD94_P_PCI_MEM,
MIPS3_PG_SIZE_16M);
/*
* Initialize interrupt priority
*/
splvec.splnet = MIPS_INT_MASK_SPL2;
splvec.splbio = MIPS_INT_MASK_SPL2;
splvec.splvm = MIPS_INT_MASK_SPL2;
splvec.spltty = MIPS_INT_MASK_SPL2;
splvec.splclock = MIPS_INT_MASK_SPL5;
splvec.splstatclock = MIPS_INT_MASK_SPL5;
/*
* Disable all interrupts. New masks will be set up
* during system configuration
*/
out16(RD94_SYS_LB_IE1, 0);
out16(RD94_SYS_LB_IE2, 0);
out32(RD94_SYS_EXT_IMASK, 0);
/*
* common configuration between NEC EISA and PCI platforms
*/
c_nec_jazz_init();
/* common configuration for Magnum derived and NEC EISA machines */
c_jazz_eisa_init();
/* chipset-dependent isa bus configuration */
isabr_conf = &isabr_nec_eisa_conf;
/* chipset-dependent jazzio bus configuration */
jazzio_conf = &jazzio_nec_eisa_conf;
}
|
768244.c | //inherit for an "identifier" mob that will id or detect magic
//important code for this mob - you will need to set_id_uses();
//and set_detect_uses();, which will set the number of identify
//and detect magic spells the mob has, respectively
//You may also set_price() if you wish. Price is altered based
//on the player's level and charisma. Identify prices are set
//up to be 5 times the price of detect, but you can change this
//by doing set_highmod() on your particular mob if you want.
//The base code as it is will make characters level 10 and under
//pay 70 gold for detect and 350 gold for identify. Higher
//level characters will be charged much, much more. With the
//current numbers in place, a level 20 would be charged 2800 for
//a detect magic and 8400 for an identify.
//coded by ~Circe~ 6/12/05
//Adding the ability for identifiers to also use study to reveal lore
//For now, the study price is the same as the detect price
//~Circe~ 7/25/13
#include <std.h>
inherit NPC;
#define LOG "identifier_usage"
object current;
object *failedStuff;
//failedStuff defined here and initiated in create because
//local variables don't exist after the function is done
int id_uses, detect_uses;
int price = 35;
int newprice,truePrice;
int oldSpeed;
string myenchant;
int highmod = 12;
void create(){
::create();
set_property("no steal",1);
set_property("no animate",1);
failedStuff = ({});
}
void init(){
::init();
add_action("ask_em","ask");
}
set_price(int p){
price = p;
}
void set_speed(int s){
::set_speed(s);
oldSpeed = s;
}
string query_long(string str){
string longD = ::query_long(str);
longD += "\n"+QCN+" will identify magical auras on items if you are "+
"willing to pay. Simply say for "+QO+" to <detect this [item]> or "+
"<identify this [item]> you carry. Alternatively, you could ask "+QS+" "
"to <study this [item]> to learn the lore on the particular object. "
"%^BOLD%^You need to make sure the item in "+
"question is the first such item in your inventory and use the "+
"syntax listed above, even if it comes out 'identify this boots'"+
".\n%^BOLD%^%^RED%^You may also "+
"type <ask detect>, <ask identify>, or <ask study> to see what prices "+QS+" "+
"would charge you.";
return longD;
}
void catch_say(string str){
if(strsrch(lower_case(str),"identify") != -1 || strsrch(lower_case(str),"detect") != -1 || strsrch(lower_case(str),"study") != -1) {
call_out("do_interact",1,str,TP);
}
}
int augmentPrice(object player){
int cha;
cha = player->query_stats("charisma");
switch (cha) {
case 0..3: return newprice*2;
case 4..6: return (newprice*17)/10;
case 7..10: return (newprice*15)/10;
case 11..13: return (newprice*12)/10;
case 14..16: return newprice;
case 17..19: return (newprice*4)/5;
case 20..25: return newprice/2;
default: return newprice;
}
}
int get_detect_price(object player){
int mylevel = player->query_highest_level();
if(mylevel < 11){
mylevel = 2;
newprice = (mylevel*price);
}else{
newprice = (mylevel*price*highmod)/3;
}
truePrice = augmentPrice(player);
return truePrice;
}
int get_id_price(object player){
int mylevel = player->query_highest_level();
if(mylevel < 11){
mylevel = 2;
newprice = (mylevel*price*5);
}
newprice = (mylevel*price*highmod);
truePrice = augmentPrice(player);
return truePrice;
}
void determine_enchant(object thing){
int num = thing->query_property("enchantment");
switch(num){
case -1: case 1: myenchant = "a faint blue glow";
break;
case -2: case 2: myenchant = "a blue glow";
break;
case -3: case 3: myenchant = "a bright blue glow";
break;
case -4: case -5: case -6: case -7: case -8: case -9: case -10:
case 4: case 5: case 6: case 7: case 8: case 9: case 10:
myenchant = "a very bright blue glow";
break;
default: myenchant = "no magical aura";
break;
}
return myenchant;
}
void failure(string stuff){
force_me("emote frowns and blinks a few times.");
force_me("say There is something wrong with the aura around "+
"that "+stuff+". I cannot tell you more about it.");
current = 0;
set_speed(oldSpeed);
return;
}
int query_detect_uses(){
return detect_uses;
}
void set_detect_uses(int x){
detect_uses = x;
return;
}
int query_id_uses(){
return id_uses;
}
void set_id_uses(int x){
id_uses = x;
return;
}
int query_highmod(){
return highmod;
}
void set_highmod(int x){
highmod = x;
return;
}
void do_interact(string str, object player){
object thing;
int mylevel, i;
string junk,which,stuff,morejunk;
object *ppl;
if (objectp(current) && player != current) {
force_me("emote waves you away as "+QS+" concentrates on something else.");
return;
}
if (!objectp(current)) {
if (player->query_invis()) {
force_me("emote gazes off into nowhere, looking for the source of the voice.");
return;
}
if (sscanf(str, "%s identify this %s", junk,stuff) != 2) {
if (sscanf(str, "%s detect this %s", junk,stuff) != 2) {
if (sscanf(str, "%s study this %s", junk,stuff) != 2) {
force_me("say Please say something like 'identify this "+
"dagger', 'detect this cloak', or 'study this shield'. If you are having "+
"difficulties, you may wish to not use color or "+
"punctuation in your speech.");
return;
}
}
}
if(strsrch(str,"identify") != -1){
which = "identify";
}
if(strsrch(str,"detect") != -1){
which = "detect";
}
if(strsrch(str,"study") != -1){
which = "study";
}
sscanf(stuff,"%s %s",stuff,morejunk);
if(which == "detect" && !detect_uses){
force_me("say I'm sorry, but I cannot perform "+
"another detect magic spell at the moment.");
return;
}
if(which == "identify" && !id_uses){
force_me("say I'm sorry, but I cannot perform "+
"another identify spell at the moment.");
return;
}
force_me("emote considers for a moment.");
if(which == "detect"){
truePrice = get_detect_price(player);
}
if(which == "study"){
truePrice = get_detect_price(player);
}
if(which == "identify"){
truePrice = get_id_price(player);
}
if (!player->query_funds("gold",truePrice)) {
force_me("say You don't have enough to pay me. It will cost you "+
""+truePrice+" gold.");
return;
}else{
if(!thing = present(stuff,player)){
force_me("say You don't seem to have any "+stuff+".");
return;
}
if(member_array(thing,failedStuff) != -1){
if(which == "identify"){
force_me("say I have tried to identify that "+stuff+" "+
"recently and cannot tell you any more about it.");
return;
}
}
tell_room(ETO, QCN+" collects some gold from "+player->QCN+".",player);
tell_object(player, QCN+" collects "+truePrice+" gold from you.");
player->use_funds("gold",truePrice);
current = player;
::set_speed(0);
switch(which){
case "detect": force_me("say Well, then, you wish to know "+
"if that "+stuff+" you carry is magical.");
tell_room(ETO,"%^CYAN%^"+QCN+" concentrates "+
"carefully.");
if(!present(current,ETO)) return;
if(!present(thing,current)){
force_me("say You seem to have lost "+
"the "+stuff+".");
return;
}
myenchant = determine_enchant(thing);
force_me("emote studies the object carefully.");
force_me("say I detect "+myenchant+" on "+
"that "+stuff+".");
detect_uses--;
log_file(LOG,""+(string)player->QCN+" had "+
""+(string)thing->query_short()+" %^BOLD%^%^CYAN%^detected for magic %^RESET%^"+
"by "+TO->QCN+" at "+ctime(time())+".\n");
call_out("endstuff",1);
break;
case "identify": force_me("say Ahh, you wish to know what "+
"sort of enchantment is on that "+stuff+".");
tell_room(ETO,"%^CYAN%^Blinking several "+
"times, "+QCN+" chants a short phrase.");
tell_room(ETO,"%^BOLD%^%^CYAN%^"+QCN+" "+
"touches the "+stuff+" and reveals its "+
"magical nature to all.");
// removing this - these NPCs are rare as is. Failing a L1 spell seems overkill. N, 8/12.
/* if(!random(7)){
failedStuff += ({thing});
id_uses--;
log_file(LOG,""+TO->QCN+" %^BOLD%^%^RED%^failed to identify %^RESET%^"+
""+(string)thing->query_short()+" for "+
""+(string)player->QCN+" at "+ctime(time())+".\n");
failure(stuff);
return;
}*/
if((int)thing->query_property("enchantment") < 0){
failedStuff += ({thing});
id_uses--;
log_file(LOG,""+TO->QCN+" %^BOLD%^%^RED%^failed to identify %^RESET%^"+
""+(string)thing->query_short()+" for "+
""+(string)player->QCN+" at "+ctime(time())+" "+
"(%^BOLD%^%^RED%^CURSE%^RESET%^).\n");
failure(stuff);
return;
}
ppl = all_inventory(ETO);
if(!present(current,ETO)) return;
if(!present(thing,current)){
force_me("say You seem to have lost "+
"the "+stuff+".");
return;
}
for(i=0;i<sizeof(ppl);i++){
if(interactive(ppl[i])){
thing->add_identified(ppl[i]->query_name());
}
}
log_file(LOG,""+(string)player->QCN+" had a "+
""+(string)thing->query_short()+" %^BOLD%^%^MAGENTA%^identified %^RESET%^by "+
""+TO->QCN+" at "+ctime(time())+".\n");
id_uses--;
call_out("endstuff",1);
break;
case "study": force_me("say I see. You wish to know "+
"the lore behind that "+stuff+" you carry.");
tell_room(ETO,"%^CYAN%^"+QCN+" concentrates "+
"carefully.");
if(!present(current,ETO)) return;
if(!present(thing,current)){
force_me("say You seem to have lost "+
"the "+stuff+".");
return;
}
force_me("emote studies the object carefully.");
force_me("say The story behind that "+stuff+" is: "+(string)thing->query_lore()+".");
log_file(LOG,""+(string)player->QCN+" had "+
""+(string)thing->query_short()+" %^BOLD%^%^YELLOW%^studied for lore %^RESET%^"+
"by "+TO->QCN+" at "+ctime(time())+".\n");
call_out("endstuff",1);
break;
default: tell_room(ETO,"Something seems to be wrong. Please "+
"ask for a wiz or bug report it.");
break;
}
return;
}
force_me("emote waves you away as "+QS+" concentrates on something else.");
return;
}
}
void endstuff(){
force_me("say Your patronage is appreciated. I trust you'll "+
"remember my services in the future.");
set_speed(oldSpeed);
current = 0;
}
void reset(){
::reset();
if(!detect_uses){
detect_uses += 2;
}
if(!id_uses){
id_uses += 2;
}
}
int ask_em(string str){
int mylevel;
if(!str){
tell_object(TP,"You need to <ask detect>, <ask identify>, or <ask study>.");
return 1;
}
if (objectp(current) && TP != current) {
force_me("emote waves you away as "+QS+" concentrates on something else.");
return 1;
}
if(str == "detect"){
get_detect_price(TP);
tell_object(TP,"It would cost "+truePrice+" gold for me to detect "+
"magic for you.");
log_file(LOG,""+(string)TPQCN+" asked "+TO->QCN+" "+
"for a %^CYAN%^detect magic %^RESET%^price at "+ctime(time())+".\n");
}
if(str == "study"){
get_detect_price(TP);
tell_object(TP,"It would cost "+truePrice+" gold for me to study an object for you.");
log_file(LOG,""+(string)TPQCN+" asked "+TO->QCN+" "+
"for a %^YELLOW%^study lore %^RESET%^price at "+ctime(time())+".\n");
}
if(str == "identify"){
get_id_price(TP);
tell_object(TP,"It would cost "+truePrice+" gold for me to identify "+
"an item for you.");
log_file(LOG,""+(string)TPQCN+" asked "+TO->QCN+" "+
"for an %^BOLD%^%^BLUE%^identify %^RESET%^price at "+ctime(time())+".\n");
}
tell_room(ETO,""+TPQCN+" seems to be discussing something with the mage.",TP);
return 1;
} |
269991.c | // Auto-generated file. Do not edit!
// Template: src/qs8-dwconv/unipass-avx512skx-mul32.c.in
// Generator: tools/xngen
//
// Copyright 2020 Google LLC
//
// This source code is licensed under the BSD-style license found in the
// LICENSE file in the root directory of this source tree.
#include <assert.h>
#include <immintrin.h>
#include <xnnpack/dwconv.h>
#include <xnnpack/intrinsics-polyfill.h>
void xnn_qs8_dwconv_minmax_ukernel_up32x25__avx512skx_mul32(
size_t channels,
size_t output_width,
const int8_t** input,
const void* weights,
int8_t* output,
size_t input_stride,
size_t output_increment,
size_t input_offset,
const int8_t* zero,
const union xnn_qs8_gemm_params params[restrict XNN_MIN_ELEMENTS(1)]) XNN_DISABLE_TSAN
{
assert(channels != 0);
assert(output_width != 0);
const __mmask16 vblend_mask = _cvtu32_mask16(0xAAAA);
const __m512i vmultiplier = _mm512_broadcast_i32x4(_mm_load_si128((const __m128i*) params->sse2.multiplier));
const __m512i vrounding = _mm512_broadcast_i32x4(_mm_load_si128((const __m128i*) params->sse2.rounding));
const __m512i vremainder_mask = _mm512_broadcast_i32x4(_mm_load_si128((const __m128i*) params->sse2.remainder_mask));
const __m512i vremainder_threshold = _mm512_broadcast_i32x4(_mm_load_si128((const __m128i*) params->sse2.remainder_threshold));
const __m128i vshift = _mm_load_si128((const __m128i*) params->sse2.shift);
const __m512i voutput_zero_point = _mm512_broadcast_i32x4(_mm_load_si128((const __m128i*) params->sse2.output_zero_point));
const __m512i voutput_min = _mm512_broadcast_i32x4(_mm_load_si128((const __m128i*) params->sse2.output_min));
const __m512i voutput_max = _mm512_broadcast_i32x4(_mm_load_si128((const __m128i*) params->sse2.output_max));
const __m256i vpermute_mask = _mm256_set_epi32(7, 3, 5, 1, 6, 2, 4, 0);
do {
const int8_t* i0 = input[0];
assert(i0 != NULL);
if XNN_UNPREDICTABLE(i0 != zero) {
i0 = (const int8_t*) ((uintptr_t) i0 + input_offset);
}
const int8_t* i1 = input[1];
assert(i1 != NULL);
if XNN_UNPREDICTABLE(i1 != zero) {
i1 = (const int8_t*) ((uintptr_t) i1 + input_offset);
}
const int8_t* i2 = input[2];
assert(i2 != NULL);
if XNN_UNPREDICTABLE(i2 != zero) {
i2 = (const int8_t*) ((uintptr_t) i2 + input_offset);
}
const int8_t* i3 = input[3];
assert(i3 != NULL);
if XNN_UNPREDICTABLE(i3 != zero) {
i3 = (const int8_t*) ((uintptr_t) i3 + input_offset);
}
const int8_t* i4 = input[4];
assert(i4 != NULL);
if XNN_UNPREDICTABLE(i4 != zero) {
i4 = (const int8_t*) ((uintptr_t) i4 + input_offset);
}
const int8_t* i5 = input[5];
assert(i5 != NULL);
if XNN_UNPREDICTABLE(i5 != zero) {
i5 = (const int8_t*) ((uintptr_t) i5 + input_offset);
}
const int8_t* i6 = input[6];
assert(i6 != NULL);
if XNN_UNPREDICTABLE(i6 != zero) {
i6 = (const int8_t*) ((uintptr_t) i6 + input_offset);
}
const int8_t* i7 = input[7];
assert(i7 != NULL);
if XNN_UNPREDICTABLE(i7 != zero) {
i7 = (const int8_t*) ((uintptr_t) i7 + input_offset);
}
const int8_t* i8 = input[8];
assert(i8 != NULL);
if XNN_UNPREDICTABLE(i8 != zero) {
i8 = (const int8_t*) ((uintptr_t) i8 + input_offset);
}
const int8_t* i9 = input[9];
assert(i9 != NULL);
if XNN_UNPREDICTABLE(i9 != zero) {
i9 = (const int8_t*) ((uintptr_t) i9 + input_offset);
}
const int8_t* i10 = input[10];
assert(i10 != NULL);
if XNN_UNPREDICTABLE(i10 != zero) {
i10 = (const int8_t*) ((uintptr_t) i10 + input_offset);
}
const int8_t* i11 = input[11];
assert(i11 != NULL);
if XNN_UNPREDICTABLE(i11 != zero) {
i11 = (const int8_t*) ((uintptr_t) i11 + input_offset);
}
const int8_t* i12 = input[12];
assert(i12 != NULL);
if XNN_UNPREDICTABLE(i12 != zero) {
i12 = (const int8_t*) ((uintptr_t) i12 + input_offset);
}
const int8_t* i13 = input[13];
assert(i13 != NULL);
if XNN_UNPREDICTABLE(i13 != zero) {
i13 = (const int8_t*) ((uintptr_t) i13 + input_offset);
}
const int8_t* i14 = input[14];
assert(i14 != NULL);
if XNN_UNPREDICTABLE(i14 != zero) {
i14 = (const int8_t*) ((uintptr_t) i14 + input_offset);
}
const int8_t* i15 = input[15];
assert(i15 != NULL);
if XNN_UNPREDICTABLE(i15 != zero) {
i15 = (const int8_t*) ((uintptr_t) i15 + input_offset);
}
const int8_t* i16 = input[16];
assert(i16 != NULL);
if XNN_UNPREDICTABLE(i16 != zero) {
i16 = (const int8_t*) ((uintptr_t) i16 + input_offset);
}
const int8_t* i17 = input[17];
assert(i17 != NULL);
if XNN_UNPREDICTABLE(i17 != zero) {
i17 = (const int8_t*) ((uintptr_t) i17 + input_offset);
}
const int8_t* i18 = input[18];
assert(i18 != NULL);
if XNN_UNPREDICTABLE(i18 != zero) {
i18 = (const int8_t*) ((uintptr_t) i18 + input_offset);
}
const int8_t* i19 = input[19];
assert(i19 != NULL);
if XNN_UNPREDICTABLE(i19 != zero) {
i19 = (const int8_t*) ((uintptr_t) i19 + input_offset);
}
const int8_t* i20 = input[20];
assert(i20 != NULL);
if XNN_UNPREDICTABLE(i20 != zero) {
i20 = (const int8_t*) ((uintptr_t) i20 + input_offset);
}
const int8_t* i21 = input[21];
assert(i21 != NULL);
if XNN_UNPREDICTABLE(i21 != zero) {
i21 = (const int8_t*) ((uintptr_t) i21 + input_offset);
}
const int8_t* i22 = input[22];
assert(i22 != NULL);
if XNN_UNPREDICTABLE(i22 != zero) {
i22 = (const int8_t*) ((uintptr_t) i22 + input_offset);
}
const int8_t* i23 = input[23];
assert(i23 != NULL);
if XNN_UNPREDICTABLE(i23 != zero) {
i23 = (const int8_t*) ((uintptr_t) i23 + input_offset);
}
const int8_t* i24 = input[24];
assert(i24 != NULL);
if XNN_UNPREDICTABLE(i24 != zero) {
i24 = (const int8_t*) ((uintptr_t) i24 + input_offset);
}
input = (const int8_t**) ((uintptr_t) input + input_stride);
size_t c = channels;
const void* w = weights;
for (; c >= 32; c -= 32) {
__m512i vacc0123456789ABCDEF = _mm512_loadu_si512(w);
__m512i vaccGHIJKLMNOPQRSTUV = _mm512_loadu_si512((const void*) ((uintptr_t) w + 16 * sizeof(int32_t)));
const __m512i vi0x0123456789ABCDEF = _mm512_cvtepi8_epi32(_mm_loadu_si128((const __m128i*) i0));
const __m512i vk0x0123456789ABCDEF = _mm512_cvtepi8_epi32(_mm_load_si128((const __m128i*) ((uintptr_t) w + 32 * sizeof(int32_t) + 0 * sizeof(int8_t))));
const __m512i vi0xGHIJKLMNOPQRSTUV = _mm512_cvtepi8_epi32(_mm_loadu_si128((const __m128i*) (i0 + 16)));
const __m512i vk0xGHIJKLMNOPQRSTUV = _mm512_cvtepi8_epi32(_mm_load_si128((const __m128i*) ((uintptr_t) w + 32 * sizeof(int32_t) + 16 * sizeof(int8_t))));
i0 += 32;
vacc0123456789ABCDEF = _mm512_add_epi32(vacc0123456789ABCDEF, _mm512_mullo_epi32(vi0x0123456789ABCDEF, vk0x0123456789ABCDEF));
vaccGHIJKLMNOPQRSTUV = _mm512_add_epi32(vaccGHIJKLMNOPQRSTUV, _mm512_mullo_epi32(vi0xGHIJKLMNOPQRSTUV, vk0xGHIJKLMNOPQRSTUV));
const __m512i vi1x0123456789ABCDEF = _mm512_cvtepi8_epi32(_mm_loadu_si128((const __m128i*) i1));
const __m512i vk1x0123456789ABCDEF = _mm512_cvtepi8_epi32(_mm_load_si128((const __m128i*) ((uintptr_t) w + 32 * sizeof(int32_t) + 32 * sizeof(int8_t))));
const __m512i vi1xGHIJKLMNOPQRSTUV = _mm512_cvtepi8_epi32(_mm_loadu_si128((const __m128i*) (i1 + 16)));
const __m512i vk1xGHIJKLMNOPQRSTUV = _mm512_cvtepi8_epi32(_mm_load_si128((const __m128i*) ((uintptr_t) w + 32 * sizeof(int32_t) + 48 * sizeof(int8_t))));
i1 += 32;
vacc0123456789ABCDEF = _mm512_add_epi32(vacc0123456789ABCDEF, _mm512_mullo_epi32(vi1x0123456789ABCDEF, vk1x0123456789ABCDEF));
vaccGHIJKLMNOPQRSTUV = _mm512_add_epi32(vaccGHIJKLMNOPQRSTUV, _mm512_mullo_epi32(vi1xGHIJKLMNOPQRSTUV, vk1xGHIJKLMNOPQRSTUV));
const __m512i vi2x0123456789ABCDEF = _mm512_cvtepi8_epi32(_mm_loadu_si128((const __m128i*) i2));
const __m512i vk2x0123456789ABCDEF = _mm512_cvtepi8_epi32(_mm_load_si128((const __m128i*) ((uintptr_t) w + 32 * sizeof(int32_t) + 64 * sizeof(int8_t))));
const __m512i vi2xGHIJKLMNOPQRSTUV = _mm512_cvtepi8_epi32(_mm_loadu_si128((const __m128i*) (i2 + 16)));
const __m512i vk2xGHIJKLMNOPQRSTUV = _mm512_cvtepi8_epi32(_mm_load_si128((const __m128i*) ((uintptr_t) w + 32 * sizeof(int32_t) + 80 * sizeof(int8_t))));
i2 += 32;
vacc0123456789ABCDEF = _mm512_add_epi32(vacc0123456789ABCDEF, _mm512_mullo_epi32(vi2x0123456789ABCDEF, vk2x0123456789ABCDEF));
vaccGHIJKLMNOPQRSTUV = _mm512_add_epi32(vaccGHIJKLMNOPQRSTUV, _mm512_mullo_epi32(vi2xGHIJKLMNOPQRSTUV, vk2xGHIJKLMNOPQRSTUV));
const __m512i vi3x0123456789ABCDEF = _mm512_cvtepi8_epi32(_mm_loadu_si128((const __m128i*) i3));
const __m512i vk3x0123456789ABCDEF = _mm512_cvtepi8_epi32(_mm_load_si128((const __m128i*) ((uintptr_t) w + 32 * sizeof(int32_t) + 96 * sizeof(int8_t))));
const __m512i vi3xGHIJKLMNOPQRSTUV = _mm512_cvtepi8_epi32(_mm_loadu_si128((const __m128i*) (i3 + 16)));
const __m512i vk3xGHIJKLMNOPQRSTUV = _mm512_cvtepi8_epi32(_mm_load_si128((const __m128i*) ((uintptr_t) w + 32 * sizeof(int32_t) + 112 * sizeof(int8_t))));
i3 += 32;
vacc0123456789ABCDEF = _mm512_add_epi32(vacc0123456789ABCDEF, _mm512_mullo_epi32(vi3x0123456789ABCDEF, vk3x0123456789ABCDEF));
vaccGHIJKLMNOPQRSTUV = _mm512_add_epi32(vaccGHIJKLMNOPQRSTUV, _mm512_mullo_epi32(vi3xGHIJKLMNOPQRSTUV, vk3xGHIJKLMNOPQRSTUV));
const __m512i vi4x0123456789ABCDEF = _mm512_cvtepi8_epi32(_mm_loadu_si128((const __m128i*) i4));
const __m512i vk4x0123456789ABCDEF = _mm512_cvtepi8_epi32(_mm_load_si128((const __m128i*) ((uintptr_t) w + 32 * sizeof(int32_t) + 128 * sizeof(int8_t))));
const __m512i vi4xGHIJKLMNOPQRSTUV = _mm512_cvtepi8_epi32(_mm_loadu_si128((const __m128i*) (i4 + 16)));
const __m512i vk4xGHIJKLMNOPQRSTUV = _mm512_cvtepi8_epi32(_mm_load_si128((const __m128i*) ((uintptr_t) w + 32 * sizeof(int32_t) + 144 * sizeof(int8_t))));
i4 += 32;
vacc0123456789ABCDEF = _mm512_add_epi32(vacc0123456789ABCDEF, _mm512_mullo_epi32(vi4x0123456789ABCDEF, vk4x0123456789ABCDEF));
vaccGHIJKLMNOPQRSTUV = _mm512_add_epi32(vaccGHIJKLMNOPQRSTUV, _mm512_mullo_epi32(vi4xGHIJKLMNOPQRSTUV, vk4xGHIJKLMNOPQRSTUV));
const __m512i vi5x0123456789ABCDEF = _mm512_cvtepi8_epi32(_mm_loadu_si128((const __m128i*) i5));
const __m512i vk5x0123456789ABCDEF = _mm512_cvtepi8_epi32(_mm_load_si128((const __m128i*) ((uintptr_t) w + 32 * sizeof(int32_t) + 160 * sizeof(int8_t))));
const __m512i vi5xGHIJKLMNOPQRSTUV = _mm512_cvtepi8_epi32(_mm_loadu_si128((const __m128i*) (i5 + 16)));
const __m512i vk5xGHIJKLMNOPQRSTUV = _mm512_cvtepi8_epi32(_mm_load_si128((const __m128i*) ((uintptr_t) w + 32 * sizeof(int32_t) + 176 * sizeof(int8_t))));
i5 += 32;
vacc0123456789ABCDEF = _mm512_add_epi32(vacc0123456789ABCDEF, _mm512_mullo_epi32(vi5x0123456789ABCDEF, vk5x0123456789ABCDEF));
vaccGHIJKLMNOPQRSTUV = _mm512_add_epi32(vaccGHIJKLMNOPQRSTUV, _mm512_mullo_epi32(vi5xGHIJKLMNOPQRSTUV, vk5xGHIJKLMNOPQRSTUV));
const __m512i vi6x0123456789ABCDEF = _mm512_cvtepi8_epi32(_mm_loadu_si128((const __m128i*) i6));
const __m512i vk6x0123456789ABCDEF = _mm512_cvtepi8_epi32(_mm_load_si128((const __m128i*) ((uintptr_t) w + 32 * sizeof(int32_t) + 192 * sizeof(int8_t))));
const __m512i vi6xGHIJKLMNOPQRSTUV = _mm512_cvtepi8_epi32(_mm_loadu_si128((const __m128i*) (i6 + 16)));
const __m512i vk6xGHIJKLMNOPQRSTUV = _mm512_cvtepi8_epi32(_mm_load_si128((const __m128i*) ((uintptr_t) w + 32 * sizeof(int32_t) + 208 * sizeof(int8_t))));
i6 += 32;
vacc0123456789ABCDEF = _mm512_add_epi32(vacc0123456789ABCDEF, _mm512_mullo_epi32(vi6x0123456789ABCDEF, vk6x0123456789ABCDEF));
vaccGHIJKLMNOPQRSTUV = _mm512_add_epi32(vaccGHIJKLMNOPQRSTUV, _mm512_mullo_epi32(vi6xGHIJKLMNOPQRSTUV, vk6xGHIJKLMNOPQRSTUV));
const __m512i vi7x0123456789ABCDEF = _mm512_cvtepi8_epi32(_mm_loadu_si128((const __m128i*) i7));
const __m512i vk7x0123456789ABCDEF = _mm512_cvtepi8_epi32(_mm_load_si128((const __m128i*) ((uintptr_t) w + 32 * sizeof(int32_t) + 224 * sizeof(int8_t))));
const __m512i vi7xGHIJKLMNOPQRSTUV = _mm512_cvtepi8_epi32(_mm_loadu_si128((const __m128i*) (i7 + 16)));
const __m512i vk7xGHIJKLMNOPQRSTUV = _mm512_cvtepi8_epi32(_mm_load_si128((const __m128i*) ((uintptr_t) w + 32 * sizeof(int32_t) + 240 * sizeof(int8_t))));
i7 += 32;
vacc0123456789ABCDEF = _mm512_add_epi32(vacc0123456789ABCDEF, _mm512_mullo_epi32(vi7x0123456789ABCDEF, vk7x0123456789ABCDEF));
vaccGHIJKLMNOPQRSTUV = _mm512_add_epi32(vaccGHIJKLMNOPQRSTUV, _mm512_mullo_epi32(vi7xGHIJKLMNOPQRSTUV, vk7xGHIJKLMNOPQRSTUV));
const __m512i vi8x0123456789ABCDEF = _mm512_cvtepi8_epi32(_mm_loadu_si128((const __m128i*) i8));
const __m512i vk8x0123456789ABCDEF = _mm512_cvtepi8_epi32(_mm_load_si128((const __m128i*) ((uintptr_t) w + 32 * sizeof(int32_t) + 256 * sizeof(int8_t))));
const __m512i vi8xGHIJKLMNOPQRSTUV = _mm512_cvtepi8_epi32(_mm_loadu_si128((const __m128i*) (i8 + 16)));
const __m512i vk8xGHIJKLMNOPQRSTUV = _mm512_cvtepi8_epi32(_mm_load_si128((const __m128i*) ((uintptr_t) w + 32 * sizeof(int32_t) + 272 * sizeof(int8_t))));
i8 += 32;
vacc0123456789ABCDEF = _mm512_add_epi32(vacc0123456789ABCDEF, _mm512_mullo_epi32(vi8x0123456789ABCDEF, vk8x0123456789ABCDEF));
vaccGHIJKLMNOPQRSTUV = _mm512_add_epi32(vaccGHIJKLMNOPQRSTUV, _mm512_mullo_epi32(vi8xGHIJKLMNOPQRSTUV, vk8xGHIJKLMNOPQRSTUV));
const __m512i vi9x0123456789ABCDEF = _mm512_cvtepi8_epi32(_mm_loadu_si128((const __m128i*) i9));
const __m512i vk9x0123456789ABCDEF = _mm512_cvtepi8_epi32(_mm_load_si128((const __m128i*) ((uintptr_t) w + 32 * sizeof(int32_t) + 288 * sizeof(int8_t))));
const __m512i vi9xGHIJKLMNOPQRSTUV = _mm512_cvtepi8_epi32(_mm_loadu_si128((const __m128i*) (i9 + 16)));
const __m512i vk9xGHIJKLMNOPQRSTUV = _mm512_cvtepi8_epi32(_mm_load_si128((const __m128i*) ((uintptr_t) w + 32 * sizeof(int32_t) + 304 * sizeof(int8_t))));
i9 += 32;
vacc0123456789ABCDEF = _mm512_add_epi32(vacc0123456789ABCDEF, _mm512_mullo_epi32(vi9x0123456789ABCDEF, vk9x0123456789ABCDEF));
vaccGHIJKLMNOPQRSTUV = _mm512_add_epi32(vaccGHIJKLMNOPQRSTUV, _mm512_mullo_epi32(vi9xGHIJKLMNOPQRSTUV, vk9xGHIJKLMNOPQRSTUV));
const __m512i vi10x0123456789ABCDEF = _mm512_cvtepi8_epi32(_mm_loadu_si128((const __m128i*) i10));
const __m512i vk10x0123456789ABCDEF = _mm512_cvtepi8_epi32(_mm_load_si128((const __m128i*) ((uintptr_t) w + 32 * sizeof(int32_t) + 320 * sizeof(int8_t))));
const __m512i vi10xGHIJKLMNOPQRSTUV = _mm512_cvtepi8_epi32(_mm_loadu_si128((const __m128i*) (i10 + 16)));
const __m512i vk10xGHIJKLMNOPQRSTUV = _mm512_cvtepi8_epi32(_mm_load_si128((const __m128i*) ((uintptr_t) w + 32 * sizeof(int32_t) + 336 * sizeof(int8_t))));
i10 += 32;
vacc0123456789ABCDEF = _mm512_add_epi32(vacc0123456789ABCDEF, _mm512_mullo_epi32(vi10x0123456789ABCDEF, vk10x0123456789ABCDEF));
vaccGHIJKLMNOPQRSTUV = _mm512_add_epi32(vaccGHIJKLMNOPQRSTUV, _mm512_mullo_epi32(vi10xGHIJKLMNOPQRSTUV, vk10xGHIJKLMNOPQRSTUV));
const __m512i vi11x0123456789ABCDEF = _mm512_cvtepi8_epi32(_mm_loadu_si128((const __m128i*) i11));
const __m512i vk11x0123456789ABCDEF = _mm512_cvtepi8_epi32(_mm_load_si128((const __m128i*) ((uintptr_t) w + 32 * sizeof(int32_t) + 352 * sizeof(int8_t))));
const __m512i vi11xGHIJKLMNOPQRSTUV = _mm512_cvtepi8_epi32(_mm_loadu_si128((const __m128i*) (i11 + 16)));
const __m512i vk11xGHIJKLMNOPQRSTUV = _mm512_cvtepi8_epi32(_mm_load_si128((const __m128i*) ((uintptr_t) w + 32 * sizeof(int32_t) + 368 * sizeof(int8_t))));
i11 += 32;
vacc0123456789ABCDEF = _mm512_add_epi32(vacc0123456789ABCDEF, _mm512_mullo_epi32(vi11x0123456789ABCDEF, vk11x0123456789ABCDEF));
vaccGHIJKLMNOPQRSTUV = _mm512_add_epi32(vaccGHIJKLMNOPQRSTUV, _mm512_mullo_epi32(vi11xGHIJKLMNOPQRSTUV, vk11xGHIJKLMNOPQRSTUV));
const __m512i vi12x0123456789ABCDEF = _mm512_cvtepi8_epi32(_mm_loadu_si128((const __m128i*) i12));
const __m512i vk12x0123456789ABCDEF = _mm512_cvtepi8_epi32(_mm_load_si128((const __m128i*) ((uintptr_t) w + 32 * sizeof(int32_t) + 384 * sizeof(int8_t))));
const __m512i vi12xGHIJKLMNOPQRSTUV = _mm512_cvtepi8_epi32(_mm_loadu_si128((const __m128i*) (i12 + 16)));
const __m512i vk12xGHIJKLMNOPQRSTUV = _mm512_cvtepi8_epi32(_mm_load_si128((const __m128i*) ((uintptr_t) w + 32 * sizeof(int32_t) + 400 * sizeof(int8_t))));
i12 += 32;
vacc0123456789ABCDEF = _mm512_add_epi32(vacc0123456789ABCDEF, _mm512_mullo_epi32(vi12x0123456789ABCDEF, vk12x0123456789ABCDEF));
vaccGHIJKLMNOPQRSTUV = _mm512_add_epi32(vaccGHIJKLMNOPQRSTUV, _mm512_mullo_epi32(vi12xGHIJKLMNOPQRSTUV, vk12xGHIJKLMNOPQRSTUV));
const __m512i vi13x0123456789ABCDEF = _mm512_cvtepi8_epi32(_mm_loadu_si128((const __m128i*) i13));
const __m512i vk13x0123456789ABCDEF = _mm512_cvtepi8_epi32(_mm_load_si128((const __m128i*) ((uintptr_t) w + 32 * sizeof(int32_t) + 416 * sizeof(int8_t))));
const __m512i vi13xGHIJKLMNOPQRSTUV = _mm512_cvtepi8_epi32(_mm_loadu_si128((const __m128i*) (i13 + 16)));
const __m512i vk13xGHIJKLMNOPQRSTUV = _mm512_cvtepi8_epi32(_mm_load_si128((const __m128i*) ((uintptr_t) w + 32 * sizeof(int32_t) + 432 * sizeof(int8_t))));
i13 += 32;
vacc0123456789ABCDEF = _mm512_add_epi32(vacc0123456789ABCDEF, _mm512_mullo_epi32(vi13x0123456789ABCDEF, vk13x0123456789ABCDEF));
vaccGHIJKLMNOPQRSTUV = _mm512_add_epi32(vaccGHIJKLMNOPQRSTUV, _mm512_mullo_epi32(vi13xGHIJKLMNOPQRSTUV, vk13xGHIJKLMNOPQRSTUV));
const __m512i vi14x0123456789ABCDEF = _mm512_cvtepi8_epi32(_mm_loadu_si128((const __m128i*) i14));
const __m512i vk14x0123456789ABCDEF = _mm512_cvtepi8_epi32(_mm_load_si128((const __m128i*) ((uintptr_t) w + 32 * sizeof(int32_t) + 448 * sizeof(int8_t))));
const __m512i vi14xGHIJKLMNOPQRSTUV = _mm512_cvtepi8_epi32(_mm_loadu_si128((const __m128i*) (i14 + 16)));
const __m512i vk14xGHIJKLMNOPQRSTUV = _mm512_cvtepi8_epi32(_mm_load_si128((const __m128i*) ((uintptr_t) w + 32 * sizeof(int32_t) + 464 * sizeof(int8_t))));
i14 += 32;
vacc0123456789ABCDEF = _mm512_add_epi32(vacc0123456789ABCDEF, _mm512_mullo_epi32(vi14x0123456789ABCDEF, vk14x0123456789ABCDEF));
vaccGHIJKLMNOPQRSTUV = _mm512_add_epi32(vaccGHIJKLMNOPQRSTUV, _mm512_mullo_epi32(vi14xGHIJKLMNOPQRSTUV, vk14xGHIJKLMNOPQRSTUV));
const __m512i vi15x0123456789ABCDEF = _mm512_cvtepi8_epi32(_mm_loadu_si128((const __m128i*) i15));
const __m512i vk15x0123456789ABCDEF = _mm512_cvtepi8_epi32(_mm_load_si128((const __m128i*) ((uintptr_t) w + 32 * sizeof(int32_t) + 480 * sizeof(int8_t))));
const __m512i vi15xGHIJKLMNOPQRSTUV = _mm512_cvtepi8_epi32(_mm_loadu_si128((const __m128i*) (i15 + 16)));
const __m512i vk15xGHIJKLMNOPQRSTUV = _mm512_cvtepi8_epi32(_mm_load_si128((const __m128i*) ((uintptr_t) w + 32 * sizeof(int32_t) + 496 * sizeof(int8_t))));
i15 += 32;
vacc0123456789ABCDEF = _mm512_add_epi32(vacc0123456789ABCDEF, _mm512_mullo_epi32(vi15x0123456789ABCDEF, vk15x0123456789ABCDEF));
vaccGHIJKLMNOPQRSTUV = _mm512_add_epi32(vaccGHIJKLMNOPQRSTUV, _mm512_mullo_epi32(vi15xGHIJKLMNOPQRSTUV, vk15xGHIJKLMNOPQRSTUV));
const __m512i vi16x0123456789ABCDEF = _mm512_cvtepi8_epi32(_mm_loadu_si128((const __m128i*) i16));
const __m512i vk16x0123456789ABCDEF = _mm512_cvtepi8_epi32(_mm_load_si128((const __m128i*) ((uintptr_t) w + 32 * sizeof(int32_t) + 512 * sizeof(int8_t))));
const __m512i vi16xGHIJKLMNOPQRSTUV = _mm512_cvtepi8_epi32(_mm_loadu_si128((const __m128i*) (i16 + 16)));
const __m512i vk16xGHIJKLMNOPQRSTUV = _mm512_cvtepi8_epi32(_mm_load_si128((const __m128i*) ((uintptr_t) w + 32 * sizeof(int32_t) + 528 * sizeof(int8_t))));
i16 += 32;
vacc0123456789ABCDEF = _mm512_add_epi32(vacc0123456789ABCDEF, _mm512_mullo_epi32(vi16x0123456789ABCDEF, vk16x0123456789ABCDEF));
vaccGHIJKLMNOPQRSTUV = _mm512_add_epi32(vaccGHIJKLMNOPQRSTUV, _mm512_mullo_epi32(vi16xGHIJKLMNOPQRSTUV, vk16xGHIJKLMNOPQRSTUV));
const __m512i vi17x0123456789ABCDEF = _mm512_cvtepi8_epi32(_mm_loadu_si128((const __m128i*) i17));
const __m512i vk17x0123456789ABCDEF = _mm512_cvtepi8_epi32(_mm_load_si128((const __m128i*) ((uintptr_t) w + 32 * sizeof(int32_t) + 544 * sizeof(int8_t))));
const __m512i vi17xGHIJKLMNOPQRSTUV = _mm512_cvtepi8_epi32(_mm_loadu_si128((const __m128i*) (i17 + 16)));
const __m512i vk17xGHIJKLMNOPQRSTUV = _mm512_cvtepi8_epi32(_mm_load_si128((const __m128i*) ((uintptr_t) w + 32 * sizeof(int32_t) + 560 * sizeof(int8_t))));
i17 += 32;
vacc0123456789ABCDEF = _mm512_add_epi32(vacc0123456789ABCDEF, _mm512_mullo_epi32(vi17x0123456789ABCDEF, vk17x0123456789ABCDEF));
vaccGHIJKLMNOPQRSTUV = _mm512_add_epi32(vaccGHIJKLMNOPQRSTUV, _mm512_mullo_epi32(vi17xGHIJKLMNOPQRSTUV, vk17xGHIJKLMNOPQRSTUV));
const __m512i vi18x0123456789ABCDEF = _mm512_cvtepi8_epi32(_mm_loadu_si128((const __m128i*) i18));
const __m512i vk18x0123456789ABCDEF = _mm512_cvtepi8_epi32(_mm_load_si128((const __m128i*) ((uintptr_t) w + 32 * sizeof(int32_t) + 576 * sizeof(int8_t))));
const __m512i vi18xGHIJKLMNOPQRSTUV = _mm512_cvtepi8_epi32(_mm_loadu_si128((const __m128i*) (i18 + 16)));
const __m512i vk18xGHIJKLMNOPQRSTUV = _mm512_cvtepi8_epi32(_mm_load_si128((const __m128i*) ((uintptr_t) w + 32 * sizeof(int32_t) + 592 * sizeof(int8_t))));
i18 += 32;
vacc0123456789ABCDEF = _mm512_add_epi32(vacc0123456789ABCDEF, _mm512_mullo_epi32(vi18x0123456789ABCDEF, vk18x0123456789ABCDEF));
vaccGHIJKLMNOPQRSTUV = _mm512_add_epi32(vaccGHIJKLMNOPQRSTUV, _mm512_mullo_epi32(vi18xGHIJKLMNOPQRSTUV, vk18xGHIJKLMNOPQRSTUV));
const __m512i vi19x0123456789ABCDEF = _mm512_cvtepi8_epi32(_mm_loadu_si128((const __m128i*) i19));
const __m512i vk19x0123456789ABCDEF = _mm512_cvtepi8_epi32(_mm_load_si128((const __m128i*) ((uintptr_t) w + 32 * sizeof(int32_t) + 608 * sizeof(int8_t))));
const __m512i vi19xGHIJKLMNOPQRSTUV = _mm512_cvtepi8_epi32(_mm_loadu_si128((const __m128i*) (i19 + 16)));
const __m512i vk19xGHIJKLMNOPQRSTUV = _mm512_cvtepi8_epi32(_mm_load_si128((const __m128i*) ((uintptr_t) w + 32 * sizeof(int32_t) + 624 * sizeof(int8_t))));
i19 += 32;
vacc0123456789ABCDEF = _mm512_add_epi32(vacc0123456789ABCDEF, _mm512_mullo_epi32(vi19x0123456789ABCDEF, vk19x0123456789ABCDEF));
vaccGHIJKLMNOPQRSTUV = _mm512_add_epi32(vaccGHIJKLMNOPQRSTUV, _mm512_mullo_epi32(vi19xGHIJKLMNOPQRSTUV, vk19xGHIJKLMNOPQRSTUV));
const __m512i vi20x0123456789ABCDEF = _mm512_cvtepi8_epi32(_mm_loadu_si128((const __m128i*) i20));
const __m512i vk20x0123456789ABCDEF = _mm512_cvtepi8_epi32(_mm_load_si128((const __m128i*) ((uintptr_t) w + 32 * sizeof(int32_t) + 640 * sizeof(int8_t))));
const __m512i vi20xGHIJKLMNOPQRSTUV = _mm512_cvtepi8_epi32(_mm_loadu_si128((const __m128i*) (i20 + 16)));
const __m512i vk20xGHIJKLMNOPQRSTUV = _mm512_cvtepi8_epi32(_mm_load_si128((const __m128i*) ((uintptr_t) w + 32 * sizeof(int32_t) + 656 * sizeof(int8_t))));
i20 += 32;
vacc0123456789ABCDEF = _mm512_add_epi32(vacc0123456789ABCDEF, _mm512_mullo_epi32(vi20x0123456789ABCDEF, vk20x0123456789ABCDEF));
vaccGHIJKLMNOPQRSTUV = _mm512_add_epi32(vaccGHIJKLMNOPQRSTUV, _mm512_mullo_epi32(vi20xGHIJKLMNOPQRSTUV, vk20xGHIJKLMNOPQRSTUV));
const __m512i vi21x0123456789ABCDEF = _mm512_cvtepi8_epi32(_mm_loadu_si128((const __m128i*) i21));
const __m512i vk21x0123456789ABCDEF = _mm512_cvtepi8_epi32(_mm_load_si128((const __m128i*) ((uintptr_t) w + 32 * sizeof(int32_t) + 672 * sizeof(int8_t))));
const __m512i vi21xGHIJKLMNOPQRSTUV = _mm512_cvtepi8_epi32(_mm_loadu_si128((const __m128i*) (i21 + 16)));
const __m512i vk21xGHIJKLMNOPQRSTUV = _mm512_cvtepi8_epi32(_mm_load_si128((const __m128i*) ((uintptr_t) w + 32 * sizeof(int32_t) + 688 * sizeof(int8_t))));
i21 += 32;
vacc0123456789ABCDEF = _mm512_add_epi32(vacc0123456789ABCDEF, _mm512_mullo_epi32(vi21x0123456789ABCDEF, vk21x0123456789ABCDEF));
vaccGHIJKLMNOPQRSTUV = _mm512_add_epi32(vaccGHIJKLMNOPQRSTUV, _mm512_mullo_epi32(vi21xGHIJKLMNOPQRSTUV, vk21xGHIJKLMNOPQRSTUV));
const __m512i vi22x0123456789ABCDEF = _mm512_cvtepi8_epi32(_mm_loadu_si128((const __m128i*) i22));
const __m512i vk22x0123456789ABCDEF = _mm512_cvtepi8_epi32(_mm_load_si128((const __m128i*) ((uintptr_t) w + 32 * sizeof(int32_t) + 704 * sizeof(int8_t))));
const __m512i vi22xGHIJKLMNOPQRSTUV = _mm512_cvtepi8_epi32(_mm_loadu_si128((const __m128i*) (i22 + 16)));
const __m512i vk22xGHIJKLMNOPQRSTUV = _mm512_cvtepi8_epi32(_mm_load_si128((const __m128i*) ((uintptr_t) w + 32 * sizeof(int32_t) + 720 * sizeof(int8_t))));
i22 += 32;
vacc0123456789ABCDEF = _mm512_add_epi32(vacc0123456789ABCDEF, _mm512_mullo_epi32(vi22x0123456789ABCDEF, vk22x0123456789ABCDEF));
vaccGHIJKLMNOPQRSTUV = _mm512_add_epi32(vaccGHIJKLMNOPQRSTUV, _mm512_mullo_epi32(vi22xGHIJKLMNOPQRSTUV, vk22xGHIJKLMNOPQRSTUV));
const __m512i vi23x0123456789ABCDEF = _mm512_cvtepi8_epi32(_mm_loadu_si128((const __m128i*) i23));
const __m512i vk23x0123456789ABCDEF = _mm512_cvtepi8_epi32(_mm_load_si128((const __m128i*) ((uintptr_t) w + 32 * sizeof(int32_t) + 736 * sizeof(int8_t))));
const __m512i vi23xGHIJKLMNOPQRSTUV = _mm512_cvtepi8_epi32(_mm_loadu_si128((const __m128i*) (i23 + 16)));
const __m512i vk23xGHIJKLMNOPQRSTUV = _mm512_cvtepi8_epi32(_mm_load_si128((const __m128i*) ((uintptr_t) w + 32 * sizeof(int32_t) + 752 * sizeof(int8_t))));
i23 += 32;
vacc0123456789ABCDEF = _mm512_add_epi32(vacc0123456789ABCDEF, _mm512_mullo_epi32(vi23x0123456789ABCDEF, vk23x0123456789ABCDEF));
vaccGHIJKLMNOPQRSTUV = _mm512_add_epi32(vaccGHIJKLMNOPQRSTUV, _mm512_mullo_epi32(vi23xGHIJKLMNOPQRSTUV, vk23xGHIJKLMNOPQRSTUV));
const __m512i vi24x0123456789ABCDEF = _mm512_cvtepi8_epi32(_mm_loadu_si128((const __m128i*) i24));
const __m512i vk24x0123456789ABCDEF = _mm512_cvtepi8_epi32(_mm_load_si128((const __m128i*) ((uintptr_t) w + 32 * sizeof(int32_t) + 768 * sizeof(int8_t))));
const __m512i vi24xGHIJKLMNOPQRSTUV = _mm512_cvtepi8_epi32(_mm_loadu_si128((const __m128i*) (i24 + 16)));
const __m512i vk24xGHIJKLMNOPQRSTUV = _mm512_cvtepi8_epi32(_mm_load_si128((const __m128i*) ((uintptr_t) w + 32 * sizeof(int32_t) + 784 * sizeof(int8_t))));
i24 += 32;
vacc0123456789ABCDEF = _mm512_add_epi32(vacc0123456789ABCDEF, _mm512_mullo_epi32(vi24x0123456789ABCDEF, vk24x0123456789ABCDEF));
vaccGHIJKLMNOPQRSTUV = _mm512_add_epi32(vaccGHIJKLMNOPQRSTUV, _mm512_mullo_epi32(vi24xGHIJKLMNOPQRSTUV, vk24xGHIJKLMNOPQRSTUV));
w = (const void*) ((uintptr_t) w + 32 * sizeof(int32_t) + 800 * sizeof(int8_t));
const __m512i vacc13579BDF = _mm512_shuffle_epi32(vacc0123456789ABCDEF, _MM_SHUFFLE(3, 3, 1, 1));
const __m512i vaccHJLNPRTV = _mm512_shuffle_epi32(vaccGHIJKLMNOPQRSTUV, _MM_SHUFFLE(3, 3, 1, 1));
const __m512i vprod02468ACE = _mm512_add_epi64(_mm512_mul_epi32(vacc0123456789ABCDEF, vmultiplier), vrounding);
const __m512i vprod13579BDF = _mm512_add_epi64(_mm512_mul_epi32(vacc13579BDF, vmultiplier), vrounding);
const __m512i vprodGIKMOQSU = _mm512_add_epi64(_mm512_mul_epi32(vaccGHIJKLMNOPQRSTUV, vmultiplier), vrounding);
const __m512i vprodHJLNPRTV = _mm512_add_epi64(_mm512_mul_epi32(vaccHJLNPRTV, vmultiplier), vrounding);
const __m512i vq31prod02468ACE = _mm512_srli_epi64(vprod02468ACE, 31);
const __m512i vq31prod13579BDF = _mm512_add_epi64(vprod13579BDF, vprod13579BDF);
const __m512i vq31prodGIKMOQSU = _mm512_srli_epi64(vprodGIKMOQSU, 31);
const __m512i vq31prodHJLNPRTV = _mm512_add_epi64(vprodHJLNPRTV, vprodHJLNPRTV);
const __m512i vq31prod0123456789ABCDEF = _mm512_mask_blend_epi32(vblend_mask, vq31prod02468ACE, vq31prod13579BDF);
const __m512i vq31prodGHIJKLMNOPQRSTUV = _mm512_mask_blend_epi32(vblend_mask, vq31prodGIKMOQSU, vq31prodHJLNPRTV);
const __m512i vrem0123456789ABCDEF =
_mm512_add_epi32(_mm512_and_epi32(vq31prod0123456789ABCDEF, vremainder_mask), _mm512_srai_epi32(vq31prod0123456789ABCDEF, 31));
const __m512i vremGHIJKLMNOPQRSTUV =
_mm512_add_epi32(_mm512_and_epi32(vq31prodGHIJKLMNOPQRSTUV, vremainder_mask), _mm512_srai_epi32(vq31prodGHIJKLMNOPQRSTUV, 31));
vacc0123456789ABCDEF = _mm512_sra_epi32(vq31prod0123456789ABCDEF, vshift);
vaccGHIJKLMNOPQRSTUV = _mm512_sra_epi32(vq31prodGHIJKLMNOPQRSTUV, vshift);
const __m512i vminus_one = _mm512_set1_epi32(-1);
vacc0123456789ABCDEF = _mm512_mask_sub_epi32(vacc0123456789ABCDEF, _mm512_cmpgt_epi32_mask(vrem0123456789ABCDEF, vremainder_threshold), vacc0123456789ABCDEF, vminus_one);
vaccGHIJKLMNOPQRSTUV = _mm512_mask_sub_epi32(vaccGHIJKLMNOPQRSTUV, _mm512_cmpgt_epi32_mask(vremGHIJKLMNOPQRSTUV, vremainder_threshold), vaccGHIJKLMNOPQRSTUV, vminus_one);
__m512i vout0123GHIJ4567KLMN89ABOPQRCDEFSTUV = _mm512_adds_epi16(_mm512_packs_epi32(vacc0123456789ABCDEF, vaccGHIJKLMNOPQRSTUV), voutput_zero_point);
__m256i voutGHIJOPQRKLMNSTUV = _mm256_adds_epi16(_mm256_packs_epi32(_mm512_castsi512_si256(vaccGHIJKLMNOPQRSTUV), _mm512_extracti32x8_epi32(vaccGHIJKLMNOPQRSTUV, 1)), _mm512_castsi512_si256(voutput_zero_point));
vout0123GHIJ4567KLMN89ABOPQRCDEFSTUV = _mm512_min_epi16(_mm512_max_epi16(vout0123GHIJ4567KLMN89ABOPQRCDEFSTUV, voutput_min), voutput_max);
voutGHIJOPQRKLMNSTUV = _mm256_min_epi16(_mm256_max_epi16(voutGHIJOPQRKLMNSTUV, _mm512_castsi512_si256(voutput_min)), _mm512_castsi512_si256(voutput_max));
const __m256i vout0123GHIJ4567KLMN = _mm512_castsi512_si256(vout0123GHIJ4567KLMN89ABOPQRCDEFSTUV);
const __m256i vout89ABOPQRCDEFSTUV = _mm512_extracti32x8_epi32(vout0123GHIJ4567KLMN89ABOPQRCDEFSTUV, 1);
const __m256i vout0123GHIJ89ABOPQR4567KLMNCDEFSTUV = _mm256_packs_epi16(vout0123GHIJ4567KLMN, vout89ABOPQRCDEFSTUV);
__m256i vout0123456789ABCDEFGHIJKLMNOPQRSTUV = _mm256_permutevar8x32_epi32(vout0123GHIJ89ABOPQR4567KLMNCDEFSTUV, vpermute_mask);
const __m128i voutGHIJOPQR = _mm256_castsi256_si128(voutGHIJOPQRKLMNSTUV);
const __m128i voutKLMNSTUV = _mm256_extracti128_si256(voutGHIJOPQRKLMNSTUV, 1);
__m128i voutGHIJKLMNOPQRSTUV = _mm_shuffle_epi32(_mm_packs_epi16(voutGHIJOPQR, voutKLMNSTUV), _MM_SHUFFLE(3, 1, 2, 0));
_mm256_storeu_si256((__m256i*) output, vout0123456789ABCDEFGHIJKLMNOPQRSTUV);
_mm_storeu_si128((__m128i*) (output + 16), voutGHIJKLMNOPQRSTUV);
output += 32;
}
if XNN_UNLIKELY(c != 0) {
// Prepare mask for valid 8-bit elements (depends on nc).
const __mmask16 vmask = _cvtu32_mask16((uint32_t) ((UINT32_C(1) << (c & 15)) - UINT32_C(1)));
const int8_t* k = (const int8_t*) ((uintptr_t) w + 32 * sizeof(int32_t));
do {
__m512i vacc0123456789ABCDEF = _mm512_loadu_si512(w);
const __m512i vi0x0123456789ABCDEF = _mm512_cvtepi8_epi32(_mm_loadu_si128((const __m128i*) i0));
const __m512i vk0x0123456789ABCDEF = _mm512_cvtepi8_epi32(_mm_loadu_si128((const __m128i*) k));
i0 += 16;
vacc0123456789ABCDEF = _mm512_add_epi32(vacc0123456789ABCDEF, _mm512_mullo_epi32(vi0x0123456789ABCDEF, vk0x0123456789ABCDEF));
const __m512i vi1x0123456789ABCDEF = _mm512_cvtepi8_epi32(_mm_loadu_si128((const __m128i*) i1));
const __m512i vk1x0123456789ABCDEF = _mm512_cvtepi8_epi32(_mm_loadu_si128((const __m128i*) (k + 32)));
i1 += 16;
vacc0123456789ABCDEF = _mm512_add_epi32(vacc0123456789ABCDEF, _mm512_mullo_epi32(vi1x0123456789ABCDEF, vk1x0123456789ABCDEF));
const __m512i vi2x0123456789ABCDEF = _mm512_cvtepi8_epi32(_mm_loadu_si128((const __m128i*) i2));
const __m512i vk2x0123456789ABCDEF = _mm512_cvtepi8_epi32(_mm_loadu_si128((const __m128i*) (k + 64)));
i2 += 16;
vacc0123456789ABCDEF = _mm512_add_epi32(vacc0123456789ABCDEF, _mm512_mullo_epi32(vi2x0123456789ABCDEF, vk2x0123456789ABCDEF));
const __m512i vi3x0123456789ABCDEF = _mm512_cvtepi8_epi32(_mm_loadu_si128((const __m128i*) i3));
const __m512i vk3x0123456789ABCDEF = _mm512_cvtepi8_epi32(_mm_loadu_si128((const __m128i*) (k + 96)));
i3 += 16;
vacc0123456789ABCDEF = _mm512_add_epi32(vacc0123456789ABCDEF, _mm512_mullo_epi32(vi3x0123456789ABCDEF, vk3x0123456789ABCDEF));
const __m512i vi4x0123456789ABCDEF = _mm512_cvtepi8_epi32(_mm_loadu_si128((const __m128i*) i4));
const __m512i vk4x0123456789ABCDEF = _mm512_cvtepi8_epi32(_mm_loadu_si128((const __m128i*) (k + 128)));
i4 += 16;
vacc0123456789ABCDEF = _mm512_add_epi32(vacc0123456789ABCDEF, _mm512_mullo_epi32(vi4x0123456789ABCDEF, vk4x0123456789ABCDEF));
const __m512i vi5x0123456789ABCDEF = _mm512_cvtepi8_epi32(_mm_loadu_si128((const __m128i*) i5));
const __m512i vk5x0123456789ABCDEF = _mm512_cvtepi8_epi32(_mm_loadu_si128((const __m128i*) (k + 160)));
i5 += 16;
vacc0123456789ABCDEF = _mm512_add_epi32(vacc0123456789ABCDEF, _mm512_mullo_epi32(vi5x0123456789ABCDEF, vk5x0123456789ABCDEF));
const __m512i vi6x0123456789ABCDEF = _mm512_cvtepi8_epi32(_mm_loadu_si128((const __m128i*) i6));
const __m512i vk6x0123456789ABCDEF = _mm512_cvtepi8_epi32(_mm_loadu_si128((const __m128i*) (k + 192)));
i6 += 16;
vacc0123456789ABCDEF = _mm512_add_epi32(vacc0123456789ABCDEF, _mm512_mullo_epi32(vi6x0123456789ABCDEF, vk6x0123456789ABCDEF));
const __m512i vi7x0123456789ABCDEF = _mm512_cvtepi8_epi32(_mm_loadu_si128((const __m128i*) i7));
const __m512i vk7x0123456789ABCDEF = _mm512_cvtepi8_epi32(_mm_loadu_si128((const __m128i*) (k + 224)));
i7 += 16;
vacc0123456789ABCDEF = _mm512_add_epi32(vacc0123456789ABCDEF, _mm512_mullo_epi32(vi7x0123456789ABCDEF, vk7x0123456789ABCDEF));
const __m512i vi8x0123456789ABCDEF = _mm512_cvtepi8_epi32(_mm_loadu_si128((const __m128i*) i8));
const __m512i vk8x0123456789ABCDEF = _mm512_cvtepi8_epi32(_mm_loadu_si128((const __m128i*) (k + 256)));
i8 += 16;
vacc0123456789ABCDEF = _mm512_add_epi32(vacc0123456789ABCDEF, _mm512_mullo_epi32(vi8x0123456789ABCDEF, vk8x0123456789ABCDEF));
const __m512i vi9x0123456789ABCDEF = _mm512_cvtepi8_epi32(_mm_loadu_si128((const __m128i*) i9));
const __m512i vk9x0123456789ABCDEF = _mm512_cvtepi8_epi32(_mm_loadu_si128((const __m128i*) (k + 288)));
i9 += 16;
vacc0123456789ABCDEF = _mm512_add_epi32(vacc0123456789ABCDEF, _mm512_mullo_epi32(vi9x0123456789ABCDEF, vk9x0123456789ABCDEF));
const __m512i vi10x0123456789ABCDEF = _mm512_cvtepi8_epi32(_mm_loadu_si128((const __m128i*) i10));
const __m512i vk10x0123456789ABCDEF = _mm512_cvtepi8_epi32(_mm_loadu_si128((const __m128i*) (k + 320)));
i10 += 16;
vacc0123456789ABCDEF = _mm512_add_epi32(vacc0123456789ABCDEF, _mm512_mullo_epi32(vi10x0123456789ABCDEF, vk10x0123456789ABCDEF));
const __m512i vi11x0123456789ABCDEF = _mm512_cvtepi8_epi32(_mm_loadu_si128((const __m128i*) i11));
const __m512i vk11x0123456789ABCDEF = _mm512_cvtepi8_epi32(_mm_loadu_si128((const __m128i*) (k + 352)));
i11 += 16;
vacc0123456789ABCDEF = _mm512_add_epi32(vacc0123456789ABCDEF, _mm512_mullo_epi32(vi11x0123456789ABCDEF, vk11x0123456789ABCDEF));
const __m512i vi12x0123456789ABCDEF = _mm512_cvtepi8_epi32(_mm_loadu_si128((const __m128i*) i12));
const __m512i vk12x0123456789ABCDEF = _mm512_cvtepi8_epi32(_mm_loadu_si128((const __m128i*) (k + 384)));
i12 += 16;
vacc0123456789ABCDEF = _mm512_add_epi32(vacc0123456789ABCDEF, _mm512_mullo_epi32(vi12x0123456789ABCDEF, vk12x0123456789ABCDEF));
const __m512i vi13x0123456789ABCDEF = _mm512_cvtepi8_epi32(_mm_loadu_si128((const __m128i*) i13));
const __m512i vk13x0123456789ABCDEF = _mm512_cvtepi8_epi32(_mm_loadu_si128((const __m128i*) (k + 416)));
i13 += 16;
vacc0123456789ABCDEF = _mm512_add_epi32(vacc0123456789ABCDEF, _mm512_mullo_epi32(vi13x0123456789ABCDEF, vk13x0123456789ABCDEF));
const __m512i vi14x0123456789ABCDEF = _mm512_cvtepi8_epi32(_mm_loadu_si128((const __m128i*) i14));
const __m512i vk14x0123456789ABCDEF = _mm512_cvtepi8_epi32(_mm_loadu_si128((const __m128i*) (k + 448)));
i14 += 16;
vacc0123456789ABCDEF = _mm512_add_epi32(vacc0123456789ABCDEF, _mm512_mullo_epi32(vi14x0123456789ABCDEF, vk14x0123456789ABCDEF));
const __m512i vi15x0123456789ABCDEF = _mm512_cvtepi8_epi32(_mm_loadu_si128((const __m128i*) i15));
const __m512i vk15x0123456789ABCDEF = _mm512_cvtepi8_epi32(_mm_loadu_si128((const __m128i*) (k + 480)));
i15 += 16;
vacc0123456789ABCDEF = _mm512_add_epi32(vacc0123456789ABCDEF, _mm512_mullo_epi32(vi15x0123456789ABCDEF, vk15x0123456789ABCDEF));
const __m512i vi16x0123456789ABCDEF = _mm512_cvtepi8_epi32(_mm_loadu_si128((const __m128i*) i16));
const __m512i vk16x0123456789ABCDEF = _mm512_cvtepi8_epi32(_mm_loadu_si128((const __m128i*) (k + 512)));
i16 += 16;
vacc0123456789ABCDEF = _mm512_add_epi32(vacc0123456789ABCDEF, _mm512_mullo_epi32(vi16x0123456789ABCDEF, vk16x0123456789ABCDEF));
const __m512i vi17x0123456789ABCDEF = _mm512_cvtepi8_epi32(_mm_loadu_si128((const __m128i*) i17));
const __m512i vk17x0123456789ABCDEF = _mm512_cvtepi8_epi32(_mm_loadu_si128((const __m128i*) (k + 544)));
i17 += 16;
vacc0123456789ABCDEF = _mm512_add_epi32(vacc0123456789ABCDEF, _mm512_mullo_epi32(vi17x0123456789ABCDEF, vk17x0123456789ABCDEF));
const __m512i vi18x0123456789ABCDEF = _mm512_cvtepi8_epi32(_mm_loadu_si128((const __m128i*) i18));
const __m512i vk18x0123456789ABCDEF = _mm512_cvtepi8_epi32(_mm_loadu_si128((const __m128i*) (k + 576)));
i18 += 16;
vacc0123456789ABCDEF = _mm512_add_epi32(vacc0123456789ABCDEF, _mm512_mullo_epi32(vi18x0123456789ABCDEF, vk18x0123456789ABCDEF));
const __m512i vi19x0123456789ABCDEF = _mm512_cvtepi8_epi32(_mm_loadu_si128((const __m128i*) i19));
const __m512i vk19x0123456789ABCDEF = _mm512_cvtepi8_epi32(_mm_loadu_si128((const __m128i*) (k + 608)));
i19 += 16;
vacc0123456789ABCDEF = _mm512_add_epi32(vacc0123456789ABCDEF, _mm512_mullo_epi32(vi19x0123456789ABCDEF, vk19x0123456789ABCDEF));
const __m512i vi20x0123456789ABCDEF = _mm512_cvtepi8_epi32(_mm_loadu_si128((const __m128i*) i20));
const __m512i vk20x0123456789ABCDEF = _mm512_cvtepi8_epi32(_mm_loadu_si128((const __m128i*) (k + 640)));
i20 += 16;
vacc0123456789ABCDEF = _mm512_add_epi32(vacc0123456789ABCDEF, _mm512_mullo_epi32(vi20x0123456789ABCDEF, vk20x0123456789ABCDEF));
const __m512i vi21x0123456789ABCDEF = _mm512_cvtepi8_epi32(_mm_loadu_si128((const __m128i*) i21));
const __m512i vk21x0123456789ABCDEF = _mm512_cvtepi8_epi32(_mm_loadu_si128((const __m128i*) (k + 672)));
i21 += 16;
vacc0123456789ABCDEF = _mm512_add_epi32(vacc0123456789ABCDEF, _mm512_mullo_epi32(vi21x0123456789ABCDEF, vk21x0123456789ABCDEF));
const __m512i vi22x0123456789ABCDEF = _mm512_cvtepi8_epi32(_mm_loadu_si128((const __m128i*) i22));
const __m512i vk22x0123456789ABCDEF = _mm512_cvtepi8_epi32(_mm_loadu_si128((const __m128i*) (k + 704)));
i22 += 16;
vacc0123456789ABCDEF = _mm512_add_epi32(vacc0123456789ABCDEF, _mm512_mullo_epi32(vi22x0123456789ABCDEF, vk22x0123456789ABCDEF));
const __m512i vi23x0123456789ABCDEF = _mm512_cvtepi8_epi32(_mm_loadu_si128((const __m128i*) i23));
const __m512i vk23x0123456789ABCDEF = _mm512_cvtepi8_epi32(_mm_loadu_si128((const __m128i*) (k + 736)));
i23 += 16;
vacc0123456789ABCDEF = _mm512_add_epi32(vacc0123456789ABCDEF, _mm512_mullo_epi32(vi23x0123456789ABCDEF, vk23x0123456789ABCDEF));
const __m512i vi24x0123456789ABCDEF = _mm512_cvtepi8_epi32(_mm_loadu_si128((const __m128i*) i24));
const __m512i vk24x0123456789ABCDEF = _mm512_cvtepi8_epi32(_mm_loadu_si128((const __m128i*) (k + 768)));
i24 += 16;
vacc0123456789ABCDEF = _mm512_add_epi32(vacc0123456789ABCDEF, _mm512_mullo_epi32(vi24x0123456789ABCDEF, vk24x0123456789ABCDEF));
w = (const void*) ((uintptr_t) w + 16 * sizeof(int32_t));
k += 16;
const __m512i vacc13579BDF = _mm512_shuffle_epi32(vacc0123456789ABCDEF, _MM_SHUFFLE(3, 3, 1, 1));
const __m512i vprod02468ACE = _mm512_add_epi64(_mm512_mul_epi32(vacc0123456789ABCDEF, vmultiplier), vrounding);
const __m512i vprod13579BDF = _mm512_add_epi64(_mm512_mul_epi32(vacc13579BDF, vmultiplier), vrounding);
const __m512i vq31prod02468ACE = _mm512_srli_epi64(vprod02468ACE, 31);
const __m512i vq31prod13579BDF = _mm512_add_epi64(vprod13579BDF, vprod13579BDF);
const __m512i vq31prod0123456789ABCDEF = _mm512_mask_blend_epi32(vblend_mask, vq31prod02468ACE, vq31prod13579BDF);
const __m512i vrem0123456789ABCDEF = _mm512_add_epi32(_mm512_and_epi32(vq31prod0123456789ABCDEF, vremainder_mask), _mm512_srai_epi32(vq31prod0123456789ABCDEF, 31));
vacc0123456789ABCDEF = _mm512_sra_epi32(vq31prod0123456789ABCDEF, vshift);
vacc0123456789ABCDEF = _mm512_mask_sub_epi32(vacc0123456789ABCDEF, _mm512_cmpgt_epi32_mask(vrem0123456789ABCDEF, vremainder_threshold), vacc0123456789ABCDEF, _mm512_set1_epi32(-1));
__m256i vout012389AB4567CDEF = _mm256_adds_epi16(_mm256_packs_epi32(_mm512_castsi512_si256(vacc0123456789ABCDEF), _mm512_extracti32x8_epi32(vacc0123456789ABCDEF, 1)), _mm512_castsi512_si256(voutput_zero_point));
vout012389AB4567CDEF = _mm256_min_epi16(_mm256_max_epi16(vout012389AB4567CDEF, _mm512_castsi512_si256(voutput_min)), _mm512_castsi512_si256(voutput_max));
const __m128i vout012389AB = _mm256_castsi256_si128(vout012389AB4567CDEF);
const __m128i vout4567CDEF = _mm256_extracti128_si256(vout012389AB4567CDEF, 1);
__m128i vout0123456789ABCDEF = _mm_shuffle_epi32(_mm_packs_epi16(vout012389AB, vout4567CDEF), _MM_SHUFFLE(3, 1, 2, 0));
if XNN_LIKELY(c >= 16) {
_mm_storeu_si128((__m128i*) output, vout0123456789ABCDEF);
output += 16;
c -= 16;
} else {
_mm_mask_storeu_epi8(output, vmask, vout0123456789ABCDEF);
output = (int8_t*) ((uintptr_t) output + c);
c = 0;
}
} while (c != 0);
}
output = (int8_t*) ((uintptr_t) output + output_increment);
} while (--output_width != 0);
}
|
78720.c | static int array[8] = {0x01, 0x02, 0x03, 0x04};
int addr(void)
{
return (array[0] + array[1]);
}
|
587854.c | /*-
* Written by Atsushi Murai <[email protected]>
* Copyright (c) 1998, System Planning and Engineering Co.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* $OpenBSD: alias_nbt.c,v 1.9 2004/05/31 02:21:17 brad Exp $
*
* TODO:
* oClean up.
* oConsidering for word alignment for other platform.
*/
/*
alias_nbt.c performs special processing for NetBios over TCP/IP
sessions by UDP.
Initial version: May, 1998 (Atsushi Murai <[email protected]>)
See HISTORY file for record of revisions.
*/
/* Includes */
#include <ctype.h>
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <netinet/in_systm.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netinet/ip.h>
#include <netinet/udp.h>
#include <netinet/tcp.h>
#include "alias_local.h"
typedef struct {
struct in_addr oldaddr;
u_short oldport;
struct in_addr newaddr;
u_short newport;
u_short *uh_sum;
} NBTArguments;
typedef struct {
unsigned char type;
unsigned char flags;
u_short id;
struct in_addr source_ip;
u_short source_port;
u_short len;
u_short offset;
} NbtDataHeader;
#define OpQuery 0
#define OpUnknown 4
#define OpRegist 5
#define OpRelease 6
#define OpWACK 7
#define OpRefresh 8
typedef struct {
u_short nametrid;
u_short dir:1, opcode:4, nmflags:7, rcode:4;
u_short qdcount;
u_short ancount;
u_short nscount;
u_short arcount;
} NbtNSHeader;
#define FMT_ERR 0x1
#define SRV_ERR 0x2
#define IMP_ERR 0x4
#define RFS_ERR 0x5
#define ACT_ERR 0x6
#define CFT_ERR 0x7
#ifdef DEBUG
static void PrintRcode( u_char rcode ) {
switch (rcode) {
case FMT_ERR:
printf("\nFormat Error.");
case SRV_ERR:
printf("\nSever failure.");
case IMP_ERR:
printf("\nUnsupported request error.\n");
case RFS_ERR:
printf("\nRefused error.\n");
case ACT_ERR:
printf("\nActive error.\n");
case CFT_ERR:
printf("\nName in conflict error.\n");
default:
printf("\n?%c?=%0x\n", '?', rcode);
}
}
#endif
/* Handling Name field */
static u_char *AliasHandleName ( u_char *p, char *pmax ) {
u_char *s;
u_char c;
int compress;
/* Following length field */
if (p == NULL || (char *)p >= pmax)
return(NULL);
if (*p & 0xc0 ) {
p = p + 2;
if ((char *)p > pmax)
return(NULL);
return ((u_char *)p);
}
while ( ( *p & 0x3f) != 0x00 ) {
s = p + 1;
if ( *p == 0x20 )
compress = 1;
else
compress = 0;
/* Get next length field */
p = (u_char *)(p + (*p & 0x3f) + 1);
if ((char *)p > pmax) {
p = NULL;
break;
}
#ifdef DEBUG
printf(":");
#endif
while (s < p) {
if ( compress == 1 ) {
c = (u_char )(((((*s & 0x0f) << 4) | (*(s+1) & 0x0f)) - 0x11));
#ifdef DEBUG
if (isprint( c ) )
printf("%c", c );
else
printf("<0x%02x>", c );
#endif
s +=2;
} else {
#ifdef DEBUG
printf("%c", *s);
#endif
s++;
}
}
#ifdef DEBUG
printf(":");
#endif
fflush(stdout);
}
/* Set up to out of Name field */
if (p == NULL || (char *)p >= pmax)
p = NULL;
else
p++;
return ((u_char *)p);
}
/*
* NetBios Datagram Handler (IP/UDP)
*/
#define DGM_DIRECT_UNIQ 0x10
#define DGM_DIRECT_GROUP 0x11
#define DGM_BROADCAST 0x12
#define DGM_ERROR 0x13
#define DGM_QUERY 0x14
#define DGM_POSITIVE_RES 0x15
#define DGM_NEGATIVE_RES 0x16
int AliasHandleUdpNbt(
struct ip *pip, /* IP packet to examine/patch */
struct alias_link *link,
struct in_addr *alias_address,
u_short alias_port
) {
struct udphdr * uh;
NbtDataHeader *ndh;
u_char *p = NULL;
char *pmax;
/* Calculate data length of UDP packet */
uh = (struct udphdr *) ((char *) pip + (pip->ip_hl << 2));
pmax = (char *)uh + ntohs( uh->uh_ulen );
ndh = (NbtDataHeader *)((char *)uh + (sizeof (struct udphdr)));
if ((char *)(ndh + 1) > pmax)
return(-1);
#ifdef DEBUG
printf("\nType=%02x,", ndh->type );
#endif
switch ( ndh->type ) {
case DGM_DIRECT_UNIQ:
case DGM_DIRECT_GROUP:
case DGM_BROADCAST:
p = (u_char *)ndh + 14;
p = AliasHandleName ( p, pmax ); /* Source Name */
p = AliasHandleName ( p, pmax ); /* Destination Name */
break;
case DGM_ERROR:
p = (u_char *)ndh + 11;
break;
case DGM_QUERY:
case DGM_POSITIVE_RES:
case DGM_NEGATIVE_RES:
p = (u_char *)ndh + 10;
p = AliasHandleName ( p, pmax ); /* Destination Name */
break;
}
if (p == NULL || (char *)p > pmax)
p = NULL;
#ifdef DEBUG
printf("%s:%d-->", inet_ntoa(ndh->source_ip), ntohs(ndh->source_port) );
#endif
/* Doing a IP address and Port number Translation */
if ( uh->uh_sum != 0 ) {
int acc;
u_short *sptr;
acc = ndh->source_port;
acc -= alias_port;
sptr = (u_short *) &(ndh->source_ip);
acc += *sptr++;
acc += *sptr;
sptr = (u_short *) alias_address;
acc -= *sptr++;
acc -= *sptr;
ADJUST_CHECKSUM(acc, uh->uh_sum);
}
ndh->source_ip = *alias_address;
ndh->source_port = alias_port;
#ifdef DEBUG
printf("%s:%d\n", inet_ntoa(ndh->source_ip), ntohs(ndh->source_port) );
fflush(stdout);
#endif
return((p == NULL) ? -1 : 0);
}
/* Question Section */
#define QS_TYPE_NB 0x0020
#define QS_TYPE_NBSTAT 0x0021
#define QS_CLAS_IN 0x0001
typedef struct {
u_short type; /* The type of Request */
u_short class; /* The class of Request */
} NBTNsQuestion;
static u_char *
AliasHandleQuestion(
u_short count,
NBTNsQuestion *q,
char *pmax,
NBTArguments *nbtarg)
{
while ( count != 0 ) {
/* Name Filed */
q = (NBTNsQuestion *)AliasHandleName((u_char *)q, pmax);
if (q == NULL || (char *)(q + 1) > pmax) {
q = NULL;
break;
}
/* Type and Class filed */
switch ( ntohs(q->type) ) {
case QS_TYPE_NB:
case QS_TYPE_NBSTAT:
q= q+1;
break;
default:
#ifdef DEBUG
printf("\nUnknown Type on Question %0x\n", ntohs(q->type) );
#endif
break;
}
count--;
}
/* Set up to out of Question Section */
return ((u_char *)q);
}
/* Resource Record */
#define RR_TYPE_A 0x0001
#define RR_TYPE_NS 0x0002
#define RR_TYPE_NULL 0x000a
#define RR_TYPE_NB 0x0020
#define RR_TYPE_NBSTAT 0x0021
#define RR_CLAS_IN 0x0001
#define SizeOfNsResource 8
typedef struct {
u_short type;
u_short class;
unsigned int ttl;
u_short rdlen;
} NBTNsResource;
#define SizeOfNsRNB 6
typedef struct {
u_short g:1, ont:2, resv:13;
struct in_addr addr;
} NBTNsRNB;
static u_char *
AliasHandleResourceNB(
NBTNsResource *q,
char *pmax,
NBTArguments *nbtarg)
{
NBTNsRNB *nb;
u_short bcount;
if (q == NULL || (char *)(q + 1) > pmax)
return(NULL);
/* Check out a length */
bcount = ntohs(q->rdlen);
/* Forward to Resource NB position */
nb = (NBTNsRNB *)((u_char *)q + SizeOfNsResource);
/* Processing all in_addr array */
#ifdef DEBUG
printf("NB rec[%s", inet_ntoa(nbtarg->oldaddr));
printf("->%s, %dbytes] ",inet_ntoa(nbtarg->newaddr ), bcount);
#endif
while ( nb != NULL && bcount != 0 ) {
if ((char *)(nb + 1) > pmax) {
nb = NULL;
break;
}
#ifdef DEBUG
printf("<%s>", inet_ntoa(nb->addr) );
#endif
if (!bcmp(&nbtarg->oldaddr,&nb->addr, sizeof(struct in_addr) ) ) {
if ( *nbtarg->uh_sum != 0 ) {
int acc;
u_short *sptr;
sptr = (u_short *) &(nb->addr);
acc = *sptr++;
acc += *sptr;
sptr = (u_short *) &(nbtarg->newaddr);
acc -= *sptr++;
acc -= *sptr;
ADJUST_CHECKSUM(acc, *nbtarg->uh_sum);
}
nb->addr = nbtarg->newaddr;
#ifdef DEBUG
printf("O");
#endif
}
#ifdef DEBUG
else {
printf(".");
}
#endif
nb=(NBTNsRNB *)((u_char *)nb + SizeOfNsRNB);
bcount -= SizeOfNsRNB;
}
if (nb == NULL || (char *)(nb + 1) > pmax) {
nb = NULL;
}
return ((u_char *)nb);
}
#define SizeOfResourceA 6
typedef struct {
struct in_addr addr;
} NBTNsResourceA;
static u_char *
AliasHandleResourceA(
NBTNsResource *q,
char *pmax,
NBTArguments *nbtarg)
{
NBTNsResourceA *a;
u_short bcount;
if (q == NULL || (char *)(q + 1) > pmax)
return(NULL);
/* Forward to Resource A position */
a = (NBTNsResourceA *)( (u_char *)q + sizeof(NBTNsResource) );
/* Check out of length */
bcount = ntohs(q->rdlen);
/* Processing all in_addr array */
#ifdef DEBUG
printf("Arec [%s", inet_ntoa(nbtarg->oldaddr));
printf("->%s]",inet_ntoa(nbtarg->newaddr ));
#endif
while ( bcount != 0 ) {
if (a == NULL || (char *)(a + 1) > pmax)
return(NULL);
#ifdef DEBUG
printf("..%s", inet_ntoa(a->addr) );
#endif
if ( !bcmp(&nbtarg->oldaddr, &a->addr, sizeof(struct in_addr) ) ) {
if ( *nbtarg->uh_sum != 0 ) {
int acc;
u_short *sptr;
sptr = (u_short *) &(a->addr); /* Old */
acc = *sptr++;
acc += *sptr;
sptr = (u_short *) &nbtarg->newaddr; /* New */
acc -= *sptr++;
acc -= *sptr;
ADJUST_CHECKSUM(acc, *nbtarg->uh_sum);
}
a->addr = nbtarg->newaddr;
}
a++; /*XXXX*/
bcount -= SizeOfResourceA;
}
if (a == NULL || (char *)(a + 1) > pmax)
a = NULL;
return ((u_char *)a);
}
typedef struct {
u_short opcode:4, flags:8, resv:4;
} NBTNsResourceNULL;
static u_char *
AliasHandleResourceNULL(
NBTNsResource *q,
char *pmax,
NBTArguments *nbtarg)
{
NBTNsResourceNULL *n;
u_short bcount;
if (q == NULL || (char *)(q + 1) > pmax)
return(NULL);
/* Forward to Resource NULL position */
n = (NBTNsResourceNULL *)( (u_char *)q + sizeof(NBTNsResource) );
/* Check out of length */
bcount = ntohs(q->rdlen);
/* Processing all in_addr array */
while ( bcount != 0 ) {
if ((char *)(n + 1) > pmax) {
n = NULL;
break;
}
n++;
bcount -= sizeof(NBTNsResourceNULL);
}
if ((char *)(n + 1) > pmax)
n = NULL;
return ((u_char *)n);
}
static u_char *
AliasHandleResourceNS(
NBTNsResource *q,
char *pmax,
NBTArguments *nbtarg)
{
NBTNsResourceNULL *n;
u_short bcount;
if (q == NULL || (char *)(q + 1) > pmax)
return(NULL);
/* Forward to Resource NULL position */
n = (NBTNsResourceNULL *)( (u_char *)q + sizeof(NBTNsResource) );
/* Check out of length */
bcount = ntohs(q->rdlen);
/* Resource Record Name Filed */
q = (NBTNsResource *)AliasHandleName( (u_char *)n, pmax ); /* XXX */
if (q == NULL || (char *)((u_char *)n + bcount) > pmax)
return(NULL);
else
return ((u_char *)n + bcount);
}
typedef struct {
u_short numnames;
} NBTNsResourceNBSTAT;
static u_char *
AliasHandleResourceNBSTAT(
NBTNsResource *q,
char *pmax,
NBTArguments *nbtarg)
{
NBTNsResourceNBSTAT *n;
u_short bcount;
if (q == NULL || (char *)(q + 1) > pmax)
return(NULL);
/* Forward to Resource NBSTAT position */
n = (NBTNsResourceNBSTAT *)( (u_char *)q + sizeof(NBTNsResource) );
/* Check out of length */
bcount = ntohs(q->rdlen);
if (q == NULL || (char *)((u_char *)n + bcount) > pmax)
return(NULL);
else
return ((u_char *)n + bcount);
}
static u_char *
AliasHandleResource(
u_short count,
NBTNsResource *q,
char *pmax,
NBTArguments
*nbtarg)
{
while ( count != 0 ) {
/* Resource Record Name Filed */
q = (NBTNsResource *)AliasHandleName( (u_char *)q, pmax );
if (q == NULL || (char *)(q + 1) > pmax)
break;
#ifdef DEBUG
printf("type=%02x, count=%d\n", ntohs(q->type), count );
#endif
/* Type and Class filed */
switch ( ntohs(q->type) ) {
case RR_TYPE_NB:
q = (NBTNsResource *)AliasHandleResourceNB(
q,
pmax,
nbtarg
);
break;
case RR_TYPE_A:
q = (NBTNsResource *)AliasHandleResourceA(
q,
pmax,
nbtarg
);
break;
case RR_TYPE_NS:
q = (NBTNsResource *)AliasHandleResourceNS(
q,
pmax,
nbtarg
);
break;
case RR_TYPE_NULL:
q = (NBTNsResource *)AliasHandleResourceNULL(
q,
pmax,
nbtarg
);
break;
case RR_TYPE_NBSTAT:
q = (NBTNsResource *)AliasHandleResourceNBSTAT(
q,
pmax,
nbtarg
);
break;
default:
#ifdef DEBUG
printf(
"\nUnknown Type of Resource %0x\n",
ntohs(q->type)
);
#endif
break;
}
count--;
}
fflush(stdout);
return ((u_char *)q);
}
int AliasHandleUdpNbtNS(
struct ip *pip, /* IP packet to examine/patch */
struct alias_link *link,
struct in_addr *alias_address,
u_short *alias_port,
struct in_addr *original_address,
u_short *original_port )
{
struct udphdr * uh;
NbtNSHeader * nsh;
u_char * p;
char *pmax;
NBTArguments nbtarg;
/* Set up Common Parameter */
nbtarg.oldaddr = *alias_address;
nbtarg.oldport = *alias_port;
nbtarg.newaddr = *original_address;
nbtarg.newport = *original_port;
/* Calculate data length of UDP packet */
uh = (struct udphdr *) ((char *) pip + (pip->ip_hl << 2));
nbtarg.uh_sum = &(uh->uh_sum);
nsh = (NbtNSHeader *)((char *)uh + (sizeof(struct udphdr)));
p = (u_char *)(nsh + 1);
pmax = (char *)uh + ntohs( uh->uh_ulen );
if ((char *)(nsh + 1) > pmax)
return(-1);
#ifdef DEBUG
printf(" [%s] ID=%02x, op=%01x, flag=%02x, rcode=%01x, qd=%04x"
", an=%04x, ns=%04x, ar=%04x, [%d]-->",
nsh->dir ? "Response": "Request",
nsh->nametrid,
nsh->opcode,
nsh->nmflags,
nsh->rcode,
ntohs(nsh->qdcount),
ntohs(nsh->ancount),
ntohs(nsh->nscount),
ntohs(nsh->arcount),
(u_char *)p -(u_char *)nsh
);
#endif
/* Question Entries */
if (ntohs(nsh->qdcount) !=0 ) {
p = AliasHandleQuestion(
ntohs(nsh->qdcount),
(NBTNsQuestion *)p,
pmax,
&nbtarg
);
}
/* Answer Resource Records */
if (ntohs(nsh->ancount) !=0 ) {
p = AliasHandleResource(
ntohs(nsh->ancount),
(NBTNsResource *)p,
pmax,
&nbtarg
);
}
/* Authority Resource Recodrs */
if (ntohs(nsh->nscount) !=0 ) {
p = AliasHandleResource(
ntohs(nsh->nscount),
(NBTNsResource *)p,
pmax,
&nbtarg
);
}
/* Additional Resource Recodrs */
if (ntohs(nsh->arcount) !=0 ) {
p = AliasHandleResource(
ntohs(nsh->arcount),
(NBTNsResource *)p,
pmax,
&nbtarg
);
}
#ifdef DEBUG
PrintRcode(nsh->rcode);
#endif
return ((p == NULL) ? -1 : 0);
}
|
528016.c | // SPDX-License-Identifier: GPL-2.0
/*
* Copyright (C) 2019 SiFive
*/
#include <linux/bitops.h>
#include <linux/device.h>
#include <linux/errno.h>
#include <linux/of_irq.h>
#include <linux/gpio/driver.h>
#include <linux/init.h>
#include <linux/platform_device.h>
#include <linux/slab.h>
#include <linux/spinlock.h>
#include <linux/regmap.h>
#define SIFIVE_GPIO_INPUT_VAL 0x00
#define SIFIVE_GPIO_INPUT_EN 0x04
#define SIFIVE_GPIO_OUTPUT_EN 0x08
#define SIFIVE_GPIO_OUTPUT_VAL 0x0C
#define SIFIVE_GPIO_RISE_IE 0x18
#define SIFIVE_GPIO_RISE_IP 0x1C
#define SIFIVE_GPIO_FALL_IE 0x20
#define SIFIVE_GPIO_FALL_IP 0x24
#define SIFIVE_GPIO_HIGH_IE 0x28
#define SIFIVE_GPIO_HIGH_IP 0x2C
#define SIFIVE_GPIO_LOW_IE 0x30
#define SIFIVE_GPIO_LOW_IP 0x34
#define SIFIVE_GPIO_OUTPUT_XOR 0x40
#define SIFIVE_GPIO_MAX 32
#define SIFIVE_GPIO_IRQ_OFFSET 7
struct sifive_gpio {
void __iomem *base;
struct gpio_chip gc;
struct regmap *regs;
unsigned long irq_state;
unsigned int trigger[SIFIVE_GPIO_MAX];
unsigned int irq_parent[SIFIVE_GPIO_MAX];
};
static void sifive_gpio_set_ie(struct sifive_gpio *chip, unsigned int offset)
{
unsigned long flags;
unsigned int trigger;
spin_lock_irqsave(&chip->gc.bgpio_lock, flags);
trigger = (chip->irq_state & BIT(offset)) ? chip->trigger[offset] : 0;
regmap_update_bits(chip->regs, SIFIVE_GPIO_RISE_IE, BIT(offset),
(trigger & IRQ_TYPE_EDGE_RISING) ? BIT(offset) : 0);
regmap_update_bits(chip->regs, SIFIVE_GPIO_FALL_IE, BIT(offset),
(trigger & IRQ_TYPE_EDGE_FALLING) ? BIT(offset) : 0);
regmap_update_bits(chip->regs, SIFIVE_GPIO_HIGH_IE, BIT(offset),
(trigger & IRQ_TYPE_LEVEL_HIGH) ? BIT(offset) : 0);
regmap_update_bits(chip->regs, SIFIVE_GPIO_LOW_IE, BIT(offset),
(trigger & IRQ_TYPE_LEVEL_LOW) ? BIT(offset) : 0);
spin_unlock_irqrestore(&chip->gc.bgpio_lock, flags);
}
static int sifive_gpio_irq_set_type(struct irq_data *d, unsigned int trigger)
{
struct gpio_chip *gc = irq_data_get_irq_chip_data(d);
struct sifive_gpio *chip = gpiochip_get_data(gc);
int offset = irqd_to_hwirq(d);
if (offset < 0 || offset >= gc->ngpio)
return -EINVAL;
chip->trigger[offset] = trigger;
sifive_gpio_set_ie(chip, offset);
return 0;
}
static void sifive_gpio_irq_enable(struct irq_data *d)
{
struct gpio_chip *gc = irq_data_get_irq_chip_data(d);
struct sifive_gpio *chip = gpiochip_get_data(gc);
int offset = irqd_to_hwirq(d) % SIFIVE_GPIO_MAX;
u32 bit = BIT(offset);
unsigned long flags;
irq_chip_enable_parent(d);
/* Switch to input */
gc->direction_input(gc, offset);
spin_lock_irqsave(&gc->bgpio_lock, flags);
/* Clear any sticky pending interrupts */
regmap_write(chip->regs, SIFIVE_GPIO_RISE_IP, bit);
regmap_write(chip->regs, SIFIVE_GPIO_FALL_IP, bit);
regmap_write(chip->regs, SIFIVE_GPIO_HIGH_IP, bit);
regmap_write(chip->regs, SIFIVE_GPIO_LOW_IP, bit);
spin_unlock_irqrestore(&gc->bgpio_lock, flags);
/* Enable interrupts */
assign_bit(offset, &chip->irq_state, 1);
sifive_gpio_set_ie(chip, offset);
}
static void sifive_gpio_irq_disable(struct irq_data *d)
{
struct gpio_chip *gc = irq_data_get_irq_chip_data(d);
struct sifive_gpio *chip = gpiochip_get_data(gc);
int offset = irqd_to_hwirq(d) % SIFIVE_GPIO_MAX;
assign_bit(offset, &chip->irq_state, 0);
sifive_gpio_set_ie(chip, offset);
irq_chip_disable_parent(d);
}
static void sifive_gpio_irq_eoi(struct irq_data *d)
{
struct gpio_chip *gc = irq_data_get_irq_chip_data(d);
struct sifive_gpio *chip = gpiochip_get_data(gc);
int offset = irqd_to_hwirq(d) % SIFIVE_GPIO_MAX;
u32 bit = BIT(offset);
unsigned long flags;
spin_lock_irqsave(&gc->bgpio_lock, flags);
/* Clear all pending interrupts */
regmap_write(chip->regs, SIFIVE_GPIO_RISE_IP, bit);
regmap_write(chip->regs, SIFIVE_GPIO_FALL_IP, bit);
regmap_write(chip->regs, SIFIVE_GPIO_HIGH_IP, bit);
regmap_write(chip->regs, SIFIVE_GPIO_LOW_IP, bit);
spin_unlock_irqrestore(&gc->bgpio_lock, flags);
irq_chip_eoi_parent(d);
}
static struct irq_chip sifive_gpio_irqchip = {
.name = "sifive-gpio",
.irq_set_type = sifive_gpio_irq_set_type,
.irq_mask = irq_chip_mask_parent,
.irq_unmask = irq_chip_unmask_parent,
.irq_enable = sifive_gpio_irq_enable,
.irq_disable = sifive_gpio_irq_disable,
.irq_eoi = sifive_gpio_irq_eoi,
};
static int sifive_gpio_child_to_parent_hwirq(struct gpio_chip *gc,
unsigned int child,
unsigned int child_type,
unsigned int *parent,
unsigned int *parent_type)
{
*parent_type = IRQ_TYPE_NONE;
*parent = child + SIFIVE_GPIO_IRQ_OFFSET;
return 0;
}
static const struct regmap_config sifive_gpio_regmap_config = {
.reg_bits = 32,
.reg_stride = 4,
.val_bits = 32,
.fast_io = true,
.disable_locking = true,
};
static int sifive_gpio_probe(struct platform_device *pdev)
{
struct device *dev = &pdev->dev;
struct device_node *node = pdev->dev.of_node;
struct device_node *irq_parent;
struct irq_domain *parent;
struct gpio_irq_chip *girq;
struct sifive_gpio *chip;
int ret, ngpio;
chip = devm_kzalloc(dev, sizeof(*chip), GFP_KERNEL);
if (!chip)
return -ENOMEM;
chip->base = devm_platform_ioremap_resource(pdev, 0);
if (IS_ERR(chip->base)) {
dev_err(dev, "failed to allocate device memory\n");
return PTR_ERR(chip->base);
}
chip->regs = devm_regmap_init_mmio(dev, chip->base,
&sifive_gpio_regmap_config);
if (IS_ERR(chip->regs))
return PTR_ERR(chip->regs);
ngpio = of_irq_count(node);
if (ngpio > SIFIVE_GPIO_MAX) {
dev_err(dev, "Too many GPIO interrupts (max=%d)\n",
SIFIVE_GPIO_MAX);
return -ENXIO;
}
irq_parent = of_irq_find_parent(node);
if (!irq_parent) {
dev_err(dev, "no IRQ parent node\n");
return -ENODEV;
}
parent = irq_find_host(irq_parent);
if (!parent) {
dev_err(dev, "no IRQ parent domain\n");
return -ENODEV;
}
ret = bgpio_init(&chip->gc, dev, 4,
chip->base + SIFIVE_GPIO_INPUT_VAL,
chip->base + SIFIVE_GPIO_OUTPUT_VAL,
NULL,
chip->base + SIFIVE_GPIO_OUTPUT_EN,
chip->base + SIFIVE_GPIO_INPUT_EN,
0);
if (ret) {
dev_err(dev, "unable to init generic GPIO\n");
return ret;
}
/* Disable all GPIO interrupts before enabling parent interrupts */
regmap_write(chip->regs, SIFIVE_GPIO_RISE_IE, 0);
regmap_write(chip->regs, SIFIVE_GPIO_FALL_IE, 0);
regmap_write(chip->regs, SIFIVE_GPIO_HIGH_IE, 0);
regmap_write(chip->regs, SIFIVE_GPIO_LOW_IE, 0);
chip->irq_state = 0;
chip->gc.base = -1;
chip->gc.ngpio = ngpio;
chip->gc.label = dev_name(dev);
chip->gc.parent = dev;
chip->gc.owner = THIS_MODULE;
girq = &chip->gc.irq;
girq->chip = &sifive_gpio_irqchip;
girq->fwnode = of_node_to_fwnode(node);
girq->parent_domain = parent;
girq->child_to_parent_hwirq = sifive_gpio_child_to_parent_hwirq;
girq->handler = handle_bad_irq;
girq->default_type = IRQ_TYPE_NONE;
platform_set_drvdata(pdev, chip);
return gpiochip_add_data(&chip->gc, chip);
}
static const struct of_device_id sifive_gpio_match[] = {
{ .compatible = "sifive,gpio0" },
{ .compatible = "sifive,fu540-c000-gpio" },
{ },
};
static struct platform_driver sifive_gpio_driver = {
.probe = sifive_gpio_probe,
.driver = {
.name = "sifive_gpio",
.of_match_table = of_match_ptr(sifive_gpio_match),
},
};
builtin_platform_driver(sifive_gpio_driver)
|
406725.c | /* esp-azure example
This example code is in the Public Domain (or CC0 licensed, at your option.)
Unless required by applicable law or agreed to in writing, this
software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
CONDITIONS OF ANY KIND, either express or implied.
*/
#include <stdio.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "freertos/event_groups.h"
#include "esp_system.h"
#include "esp_system.h"
#include "esp_wifi.h"
#include "esp_event_loop.h"
#include "esp_log.h"
#include "nvs_flash.h"
#include "iothub_client_sample_mqtt.h"
#define EXAMPLE_WIFI_SSID CONFIG_WIFI_SSID
#define EXAMPLE_WIFI_PASS CONFIG_WIFI_PASSWORD
EventGroupHandle_t wifi_event_group;
#ifndef BIT0
#define BIT0 (0x1 << 0)
#endif
/* The event group allows multiple bits for each event,
but we only care about one event - are we connected
to the AP with an IP? */
const int CONNECTED_BIT = BIT0;
static const char *TAG = "azure";
static esp_err_t event_handler(void *ctx, system_event_t *event)
{
switch(event->event_id) {
case SYSTEM_EVENT_STA_START:
esp_wifi_connect();
break;
case SYSTEM_EVENT_STA_GOT_IP:
xEventGroupSetBits(wifi_event_group, CONNECTED_BIT);
break;
case SYSTEM_EVENT_STA_DISCONNECTED:
/* This is a workaround as ESP platform WiFi libs don't currently
auto-reassociate. */
esp_wifi_connect();
xEventGroupClearBits(wifi_event_group, CONNECTED_BIT);
break;
default:
break;
}
return ESP_OK;
}
static void initialise_wifi(void)
{
tcpip_adapter_init();
wifi_event_group = xEventGroupCreate();
ESP_ERROR_CHECK( esp_event_loop_init(event_handler, NULL) );
wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT();
ESP_ERROR_CHECK( esp_wifi_init(&cfg) );
ESP_ERROR_CHECK( esp_wifi_set_storage(WIFI_STORAGE_RAM) );
wifi_config_t wifi_config = {
.sta = {
.ssid = EXAMPLE_WIFI_SSID,
.password = EXAMPLE_WIFI_PASS,
},
};
ESP_LOGI(TAG, "Setting WiFi configuration SSID %s...", wifi_config.sta.ssid);
ESP_ERROR_CHECK( esp_wifi_set_mode(WIFI_MODE_STA) );
ESP_ERROR_CHECK( esp_wifi_set_config(ESP_IF_WIFI_STA, &wifi_config) );
ESP_ERROR_CHECK( esp_wifi_start() );
}
extern void optiga_trust_init(void);
void azure_task(void *pvParameter)
{
xEventGroupWaitBits(wifi_event_group, CONNECTED_BIT,
false, true, portMAX_DELAY);
ESP_LOGI(TAG, "Connected to AP success!");
optiga_trust_init();
iothub_client_sample_mqtt_run();
vTaskDelete(NULL);
}
void app_main()
{
// Initialize NVS
esp_err_t ret = nvs_flash_init();
if (ret == ESP_ERR_NVS_NO_FREE_PAGES) {
ESP_ERROR_CHECK(nvs_flash_erase());
ret = nvs_flash_init();
}
ESP_ERROR_CHECK( ret );
initialise_wifi();
if ( xTaskCreate(&azure_task, "azure_task", 1024 * 5, NULL, 5, NULL) != pdPASS ) {
printf("create azure task failed\r\n");
}
}
|
421063.c | /*-------------------------------------------------------------------------
*
* remote_print.c
* remote print routines
*
*
* Copyright (c) 2019-2021 ZettaDB inc. All rights reserved.
*
* This source code is licensed under Apache 2.0 License,
* combined with Common Clause Condition 1.0, as detailed in the NOTICE file.
*
* IDENTIFICATION
* src/backend/nodes/remote_print.c
*
*-------------------------------------------------------------------------
*/
#include "postgres.h"
#include "pgtime.h"
#include "miscadmin.h"
#include "access/printtup.h"
#include "catalog/heap.h"
#include "catalog/pg_type.h"
#include "executor/spi.h"
#include "lib/stringinfo.h"
#include "nodes/print.h"
#include "nodes/nodeFuncs.h"
#include "optimizer/clauses.h"
#include "parser/parsetree.h"
#include "utils/lsyscache.h"
#include "utils/builtins.h"
#include "access/remotetup.h"
#include "commands/sequence.h"
static bool mysql_has_func(const char *fn);
static int SQLValueFuncValue(SQLValueFunction *svfo, StringInfo str);
static int append_expr_list(StringInfo str, List *l, RemotePrintExprContext *rpec);
static int eval_nextval_expr(StringInfo str, NextValueExpr *nve);
#undef APPEND_CHAR
#undef APPEND_EXPR
#undef APPEND_STR
#undef APPEND_STR_FMT
#define APPEND_CHAR(c) do { \
appendStringInfoChar(str, c);\
nw++; \
} while (0)
#define APPEND_EXPR(expr) do { \
nw1 = snprint_expr(str, ((Expr*)(expr)), rpec);\
if (nw1 < 0) \
return nw1; \
nw += nw1; \
} while (0)
#define APPEND_STR(str0) do { \
nw1 = appendStringInfoString(str, (str0)); \
nw += nw1; \
} while (0)
#define APPEND_STR_FMT(fmt, str0) do { \
nw1 = appendStringInfo(str, fmt, str0); \
nw += nw1; \
} while (0)
#define APPEND_FUNC2(funcname, arg1, arg2) do {\
nw1 = appendStringInfoString(str, funcname); \
appendStringInfoChar(str, '('); \
nw += nw1+3; \
nw1 = snprint_expr(str, ((Expr*)(arg1)), rpec);\
if (nw1 < 0) return nw1; \
nw += nw1; \
appendStringInfoChar(str, ','); \
nw1 = snprint_expr(str, ((Expr*)(arg2)), rpec);\
if (nw1 < 0) return nw1; \
nw += nw1; \
appendStringInfoChar(str, ')'); \
}while (0)
#define APPEND_FUNC1(funcname, arg1) do {\
nw1 = appendStringInfoString(str, funcname); \
appendStringInfoChar(str, '('); \
nw += nw1+2; \
nw1 = snprint_expr(str, ((Expr*)(arg1)), rpec);\
if (nw1 < 0) return nw1; \
nw += nw1; \
appendStringInfoChar(str, ')'); \
}while (0)
// the 3rd argument is a string.
#define APPEND_FUNC3_3s(funcname, arg1, arg2, arg3) do {\
nw1 = appendStringInfoString(str, funcname); \
appendStringInfoChar(str, '('); \
nw += nw1+4; \
nw1 = snprint_expr(str, ((Expr*)(arg1)), rpec);\
if (nw1 < 0) return nw1; \
nw += nw1; \
appendStringInfoChar(str, ','); \
nw1 = snprint_expr(str, ((Expr*)(arg2)), rpec);\
if (nw1 < 0) return nw1; \
nw += nw1; \
appendStringInfoChar(str, ','); \
nw1 = appendStringInfoString(str, arg3); \
nw += nw1; \
appendStringInfoChar(str, ')'); \
}while (0)
/**
* Sorted list of mysql functions, as of mysql-8.0.15.
*/
static const char *mysql_funcs[] = {
"ABS",
"ACOS",
"ADDTIME",
"AES_DECRYPT",
"AES_ENCRYPT",
"ANY_VALUE",
"ASIN",
"ATAN",
"ATAN2",
"BENCHMARK",
"BIN",
"BIN_TO_UUID",
"BIT_COUNT",
"BIT_LENGTH",
"CEIL",
"CEILING",
"CHARACTER_LENGTH",
"CHAR_LENGTH",
"COERCIBILITY",
"COMPRESS",
"CONCAT",
"CONCAT_WS",
"CONNECTION_ID",
"CONV",
"CONVERT_TZ",
"COS",
"COT",
"CRC32",
"CURRENT_ROLE",
"DATEDIFF",
"DATE_FORMAT",
"DAYNAME",
"DAYOFMONTH",
"DAYOFWEEK",
"DAYOFYEAR",
"DEGREES",
"ELT",
"EXP",
"EXPORT_SET",
"EXTRACTVALUE",
"FIELD",
"FIND_IN_SET",
"FLOOR",
"FOUND_ROWS",
"FROM_BASE64",
"FROM_DAYS",
"FROM_UNIXTIME",
"GET_LOCK",
"GREATEST",
"GTID_SUBSET",
"GTID_SUBTRACT",
"HEX",
"IFNULL",
"INET6_ATON",
"INET6_NTOA",
"INET_ATON",
"INET_NTOA",
"INSTR",
"IS_FREE_LOCK",
"IS_IPV4",
"IS_IPV4_COMPAT",
"IS_IPV4_MAPPED",
"IS_IPV6",
"ISNULL",
"IS_USED_LOCK",
"IS_UUID",
"JSON_ARRAY",
"JSON_ARRAY_APPEND",
"JSON_ARRAY_INSERT",
"JSON_CONTAINS",
"JSON_CONTAINS_PATH",
"JSON_DEPTH",
"JSON_EXTRACT",
"JSON_INSERT",
"JSON_KEYS",
"JSON_LENGTH",
"JSON_MERGE",
"JSON_MERGE_PATCH",
"JSON_MERGE_PRESERVE",
"JSON_OBJECT",
"JSON_PRETTY",
"JSON_QUOTE",
"JSON_REMOVE",
"JSON_REPLACE",
"JSON_SEARCH",
"JSON_SET",
"JSON_STORAGE_FREE",
"JSON_STORAGE_SIZE",
"JSON_TYPE",
"JSON_UNQUOTE",
"JSON_VALID",
"LAST_DAY",
"LAST_INSERT_ID",
"LCASE",
"LEAST",
"LENGTH",
"LN",
"LOAD_FILE",
"LOCATE",
"LOG",
"LOG10",
"LOG2",
"LOWER",
"LPAD",
"LTRIM",
"MAKEDATE",
"MAKE_SET",
"MAKETIME",
"MASTER_POS_WAIT",
"MBRCONTAINS",
"MBRCOVEREDBY",
"MBRCOVERS",
"MBRDISJOINT",
"MBREQUALS",
"MBRINTERSECTS",
"MBROVERLAPS",
"MBRTOUCHES",
"MBRWITHIN",
"MD5",
"MONTHNAME",
"NAME_CONST",
"NULLIF",
"OCT",
"OCTET_LENGTH",
"ORD",
"PERIOD_ADD",
"PERIOD_DIFF",
"PI",
"POW",
"POWER",
"QUOTE",
"RADIANS",
"RAND",
"RANDOM_BYTES",
"REGEXP_INSTR",
"REGEXP_LIKE",
"REGEXP_REPLACE",
"REGEXP_SUBSTR",
"RELEASE_ALL_LOCKS",
"RELEASE_LOCK",
"REVERSE",
"ROLES_GRAPHML",
"ROTATE_SYSTEM_KEY",
"ROUND",
"RPAD",
"RTRIM",
"SEC_TO_TIME",
"SHA",
"SHA1",
"SHA2",
"SIGN",
"SIN",
"SLEEP",
"SOUNDEX",
"SPACE",
"SQRT",
"ST_AREA",
"ST_ASBINARY",
"ST_ASGEOJSON",
"ST_ASTEXT",
"ST_ASWKB",
"ST_ASWKT",
"STATEMENT_DIGEST",
"STATEMENT_DIGEST_TEXT",
"ST_BUFFER",
"ST_BUFFER_STRATEGY",
"ST_CENTROID",
"ST_CONTAINS",
"ST_CONVEXHULL",
"ST_CROSSES",
"ST_DIFFERENCE",
"ST_DIMENSION",
"ST_DISJOINT",
"ST_DISTANCE",
"ST_DISTANCE_SPHERE",
"ST_ENDPOINT",
"ST_ENVELOPE",
"ST_EQUALS",
"ST_EXTERIORRING",
"ST_GEOHASH",
"ST_GEOMCOLLFROMTEXT",
"ST_GEOMCOLLFROMTXT",
"ST_GEOMCOLLFROMWKB",
"ST_GEOMETRYCOLLECTIONFROMTEXT",
"ST_GEOMETRYCOLLECTIONFROMWKB",
"ST_GEOMETRYFROMTEXT",
"ST_GEOMETRYFROMWKB",
"ST_GEOMETRYN",
"ST_GEOMETRYTYPE",
"ST_GEOMFROMGEOJSON",
"ST_GEOMFROMTEXT",
"ST_GEOMFROMWKB",
"ST_INTERIORRINGN",
"ST_INTERSECTION",
"ST_INTERSECTS",
"ST_ISCLOSED",
"ST_ISEMPTY",
"ST_ISSIMPLE",
"ST_ISVALID",
"ST_LATFROMGEOHASH",
"ST_LATITUDE",
"ST_LENGTH",
"ST_LINEFROMTEXT",
"ST_LINEFROMWKB",
"ST_LINESTRINGFROMTEXT",
"ST_LINESTRINGFROMWKB",
"ST_LONGFROMGEOHASH",
"ST_LONGITUDE",
"ST_MAKEENVELOPE",
"ST_MLINEFROMTEXT",
"ST_MLINEFROMWKB",
"ST_MPOINTFROMTEXT",
"ST_MPOINTFROMWKB",
"ST_MPOLYFROMTEXT",
"ST_MPOLYFROMWKB",
"ST_MULTILINESTRINGFROMTEXT",
"ST_MULTILINESTRINGFROMWKB",
"ST_MULTIPOINTFROMTEXT",
"ST_MULTIPOINTFROMWKB",
"ST_MULTIPOLYGONFROMTEXT",
"ST_MULTIPOLYGONFROMWKB",
"ST_NUMGEOMETRIES",
"ST_NUMINTERIORRING",
"ST_NUMINTERIORRINGS",
"ST_NUMPOINTS",
"ST_OVERLAPS",
"ST_POINTFROMGEOHASH",
"ST_POINTFROMTEXT",
"ST_POINTFROMWKB",
"ST_POINTN",
"ST_POLYFROMTEXT",
"ST_POLYFROMWKB",
"ST_POLYGONFROMTEXT",
"ST_POLYGONFROMWKB",
"STRCMP",
"STR_TO_DATE",
"ST_SIMPLIFY",
"ST_SRID",
"ST_STARTPOINT",
"ST_SWAPXY",
"ST_SYMDIFFERENCE",
"ST_TOUCHES",
"ST_TRANSFORM",
"ST_UNION",
"ST_VALIDATE",
"ST_WITHIN",
"ST_X",
"ST_Y",
"SUBSTRING_INDEX",
"SUBTIME",
"TAN",
"TIMEDIFF",
"TIME_FORMAT",
"TIME_TO_SEC",
"TO_BASE64",
"TO_DAYS",
"TO_SECONDS",
"UCASE",
"UNCOMPRESS",
"UNCOMPRESSED_LENGTH",
"UNHEX",
"UNIX_TIMESTAMP",
"UPDATEXML",
"UPPER",
"UUID",
"UUID_SHORT",
"UUID_TO_BIN",
"VALIDATE_PASSWORD_STRENGTH",
"VERSION",
"WAIT_FOR_EXECUTED_GTID_SET",
"WAIT_UNTIL_SQL_THREAD_AFTER_GTIDS",
"WEEKDAY",
"WEEKOFYEAR",
"YEARWEEK"
};
inline static int func_name_cmp(const void *n1, const void*n2)
{
char *s1 = (char *)n1;
char **ps2 = (char **)n2;
if (s1 == NULL || *ps2 == NULL)
return s1 > *ps2 ? 1 : (s1 == *ps2 ? 0 : -1);
return strcasecmp(s1, *ps2);
}
static inline bool mysql_has_func(const char *fn)
{
void *pos = bsearch(fn, mysql_funcs, sizeof(mysql_funcs)/sizeof(void*),
sizeof(void*), func_name_cmp);
return pos != NULL;
}
inline static bool type_is_array_category(Oid typid)
{
char typcat;
bool preferred;
get_type_category_preferred(typid, &typcat, &preferred);
return typcat == TYPCATEGORY_ARRAY;
}
/*
* See if a type is one of the string types.
* */
inline static bool is_str_type(Oid typid)
{
const static Oid strtypids[] = //{18, 25, 1002, 1009, 1014, 1015, 1042, 1043, 1263, 2275};
{CHAROID, TEXTOID, CHARARRAYOID, NAMEARRAYOID, TEXTARRAYOID, BPCHARARRAYOID,
VARCHARARRAYOID, CSTRINGARRAYOID, BPCHAROID, VARCHAROID, CSTRINGOID};
// BPCHAROID, VARCHAROID, CSTRINGOID, CHAROID, TEXTOID
for (int i = 0; i < sizeof(strtypids)/sizeof(Oid); i++)
if (typid == strtypids[i])
return true;
return false;
}
inline static bool is_expr_integer(Node *expr)
{
int typeid = exprType(expr);
return typeid == INT2OID || typeid == INT4OID || typeid == INT8OID;
}
/*
@retval NO. of bytes appended to 'str'. return -2 if the const type
is not supported in mysql.
*/
static int output_const_type_value(StringInfo str, bool isnull, Oid type,
Datum value)
{
int nw = 0, nw1 = 0;
if (isnull)
{
APPEND_STR("NULL");
return nw1;
}
Oid typoutput;
bool typIsVarlena;
char *outputstr = NULL;
getTypeOutputInfo(type, &typoutput, &typIsVarlena);
/*
* Always produce date/time/timestamp/internval/timetz/timestamptz values
* using ISO, YMD date style/order, ISO interval style, in UTC+0 timezone.
* Temporarily modify the 3 session vars to do so and restore
* them after done.
* */
pg_tz *gmt_tz = pg_tzset("GMT"), *origtz = NULL;
int orig_datestyle = -1, orig_dateorder = -1, orig_intvstyle = -1;
{
orig_datestyle = DateStyle;
orig_dateorder = DateOrder;
origtz = session_timezone;
orig_intvstyle = IntervalStyle;
DateStyle = USE_ISO_DATES;
DateOrder = DATEORDER_YMD;
IntervalStyle = INTSTYLE_ISO_8601;
session_timezone = gmt_tz;
}
outputstr = OidOutputFunctionCall(typoutput, value);
if (format_type_remote(type) == NULL)
{
if (type_is_array_category(type))
{
/*
pg uses an array to store the const value list used in exprs like IN.
Only allow 1-D array, replace the {} with () because mysql
only accept 1-D () list.
For now such an array constant is always used only for a
'col IN(exprlist)' expression. But in future we may do more, as
detailed in the handler for ScalarArrayOpExpr in snprint_expr.
*/
char *p = outputstr, *q = NULL;
if ((p = strchr(p, '{')))
{
q = p;
if ((p = strchr(p + 1, '{')))
ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("Only 1-D array constant is supported in Kunlun-db.")));
p = q;
if ((p = strchr(p + 1, '}')) == NULL)
ereport(ERROR, (errcode(ERRCODE_DATA_EXCEPTION),
errmsg("Invalid array constant: %s, unmatchcing brackets.", outputstr)));
*p = ')';
*q = '(';
}
else
ereport(ERROR, (errcode(ERRCODE_DATA_EXCEPTION),
errmsg("Invalid array constant: %s, brackets not found.", outputstr)));
}
}
{
DateStyle = orig_datestyle;
DateOrder = orig_dateorder;
IntervalStyle = orig_intvstyle;
session_timezone = origtz;
}
outputstr = pg_to_mysql_const(type, outputstr);
const int ics = const_output_needs_quote(type);
/*
* In pg str const always wrapped in single quotes('), if there were '
* in the string they must have been escaped otherwise lexer already
* errored out.
* */
if (ics == 1)
APPEND_CHAR('\'');
APPEND_STR(outputstr);
if (ics == 1)
APPEND_CHAR('\'');
pfree(outputstr);
return nw1 + ics ? 2 : 0;
}
const char *get_var_attname(const Var *var, const List *rtable)
{
const char *relname, *attname;
switch (var->varno)
{
case INNER_VAR:
relname = "INNER";
attname = "?";
break;
case OUTER_VAR:
relname = "OUTER";
attname = "?";
break;
case INDEX_VAR:
relname = "INDEX";
attname = "?";
break;
default:
{
RangeTblEntry *rte;
Assert(var->varno > 0 &&
(int) var->varno <= list_length(rtable));
rte = rt_fetch(var->varno, rtable);
relname = rte->eref->aliasname;
if (var->varattno < 0)
{
Form_pg_attribute sysatt = SystemAttributeDefinition(var->varattno, true);
ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("Kunlun-db: Can't access system attribute(%s) from remote tables.",
sysatt ? sysatt->attname.data : "<unknown>")));
}
attname = get_rte_attribute_name(rte, var->varattno);
}
break;
}
return attname;
}
/*
* print expr into str.
* Returns NO. of bytes appended to str; now never returns -1; return -2
* if the expr of one of its components can/should not be serialized, and in this
* case 'str' is half written, so caller should note down its old length for
* truncation on error;
* See/use get_rule_expr() to handle more types of exprs.
*
* This function must recognize non-standard functions and operators, i.e. which
* are not supported by MySQL, and return -2 in this case. The pg_operator and
* pg_functions should have had a boolean column 'standard' to indicate whether
* the operator/function is in SQL standard.
* */
int
snprint_expr(StringInfo str, const Expr *expr, RemotePrintExprContext *rpec)
{
int nw = 0, nw1 = 0;
const List *rtable = rpec->rtable;
if (expr == NULL || str->maxlen == 0 || !str->data)
{
return 0;
}
/*
Normally an expr will be serialized into one expr here, except a few
like RowExpr as shown below.
*/
rpec->num_vals = 1;
if (IsA(expr, Var))
{
const Var *var = (const Var *) expr;
/*
* Here we don't print the relation name, because it can be a
* partition table name. We know for sure that the column name is
* qualified and valid in both computing node and storage node.
* */
APPEND_STR(get_var_attname(var, rtable));
}
else if (IsA(expr, Const))
{
const Const *c = (const Const *) expr;
if ((nw1 = output_const_type_value(str, c->constisnull, c->consttype,
c->constvalue)) < 0)
return nw1;
nw += nw1;
}
else if (IsA(expr, OpExpr))
{
const OpExpr *e = (const OpExpr *) expr;
char *opname;
#define OPC_EQ(i, c) (opname[(i)] == (c))
APPEND_CHAR('(');
opname = get_opname(e->opno);
if (opname[0] == '+' || opname[0] == '=' || opname[0] == '-' || opname[0] == '*'|| opname[0] == '%')
goto commons;
if (OPC_EQ(0, '~') && OPC_EQ(1, '~') && OPC_EQ(2, '\0')) //strcmp(opname, "~~") == 0)
opname = "LIKE";
if (OPC_EQ(0, '!') && OPC_EQ(1, '~') && OPC_EQ(2, '~') && OPC_EQ(3, '\0')) //strcmp(opname, "!~~") == 0)
opname = "NOT LIKE";
else if (OPC_EQ(0, '|') && OPC_EQ(1, '|') && OPC_EQ(2, '\0')) //strcmp(opname, "||") == 0)
{
opname = "concat";
APPEND_FUNC2(opname, get_leftop((const Expr *) e), get_rightop((const Expr *) e));
goto op_expr_done;
}
else if (OPC_EQ(0, '^') && OPC_EQ(1, '\0'))//strcmp(opname, "^") == 0)
{
opname = "power";
APPEND_FUNC2(opname, get_leftop((const Expr *) e), get_rightop((const Expr *) e));
goto op_expr_done;
}
else if (OPC_EQ(0, '|') && OPC_EQ(1, '/') && OPC_EQ(2, '\0'))//strcmp(opname, "|/") == 0)
{
opname = "sqrt";
APPEND_FUNC1(opname, get_leftop((const Expr *) e));
goto op_expr_done;
}
else if (OPC_EQ(0, '|') && OPC_EQ(1, '|') && OPC_EQ(2, '/') && OPC_EQ(3, '\0'))//strcmp(opname, "||/") == 0)
{
return -2;
}
else if (OPC_EQ(0, '@') && OPC_EQ(1, '\0'))//strcmp(opname, "@") == 0)
{
opname = "abs";
APPEND_FUNC1(opname, get_leftop((const Expr *) e));
goto op_expr_done;
}
else if (OPC_EQ(0, '#') && OPC_EQ(1, '\0'))//strcmp(opname, "#") == 0)
opname = "^";
else if (strcasecmp(opname, "SIMILAR TO") == 0)
{
opname = "regexp_like";
APPEND_FUNC2(opname, get_leftop((const Expr *) e), get_rightop((const Expr *) e));
goto op_expr_done;
}
else if (OPC_EQ(0, '~') && OPC_EQ(1, '\0'))//strcmp(opname, "~") == 0)
{
if (list_length(e->args) == 1)
{
Node *arg1 = get_leftop((const Expr *) e);
Oid arg1typ = exprType(arg1);
if (arg1typ == MACADDROID || arg1typ == MACADDR8OID || arg1typ == INETOID)
return -2;
APPEND_FUNC1(opname, arg1);
goto op_expr_done;
}
opname = "regexp_like";
APPEND_FUNC3_3s(opname, get_leftop((const Expr *) e), get_rightop((const Expr *) e), "'c'");
goto op_expr_done;
}
else if (OPC_EQ(0, '~') && OPC_EQ(1, '*') && OPC_EQ(2, '\0'))//strcmp(opname, "~*") == 0)
{
opname = "regexp_like";
APPEND_FUNC3_3s(opname, get_leftop((const Expr *) e), get_rightop((const Expr *) e), "'i'");
goto op_expr_done;
}
else if (OPC_EQ(0, '!') && OPC_EQ(1, '~') && OPC_EQ(2, '\0'))//strcmp(opname, "!~") == 0)
{
opname = "NOT REGEXP_LIKE";
APPEND_FUNC3_3s(opname, get_leftop((const Expr *) e), get_rightop((const Expr *) e), "'c'");
goto op_expr_done;
}
else if (OPC_EQ(0, '!') && OPC_EQ(1, '~') && OPC_EQ(2, '*') && OPC_EQ(3, '\0'))//strcmp(opname, "!~*") == 0)
{
opname = "NOT REGEXP_LIKE";
APPEND_FUNC3_3s(opname, get_leftop((const Expr *) e), get_rightop((const Expr *) e), "'i'");
goto op_expr_done;
}
else if (OPC_EQ(0, '/') && OPC_EQ(1, '\0') && //strcmp(opname, "/") == 0 &&
is_expr_integer(get_leftop((const Expr *) e)) &&
is_expr_integer(get_rightop((const Expr *) e)))
{
opname = "DIV";
}
if ((opname[0] == '<' || opname[0] == '>') && !((opname[0] == '<' && opname[1] == '>')))
{
/*
* enum values in mysql can only do = or != comparison, anything
* else should be rejected. but such checks are too expensive, so
* instead we do this:
* Given <,<=, >, >= operators, if one argument is enum, then we
* can't serialize it because mysql does enum lt/gt comparison as
* strings not as enum sort values.
* */
Oid ltypid = exprType(get_leftop((const Expr *) e));
Oid rtypid = exprType(get_rightop((const Expr *) e));
if (type_is_enum_lite(ltypid) || type_is_enum_lite(rtypid) ||
ltypid == INETOID || rtypid == INETOID)
return -2;
}
/*
* MySQL doesn't support inet operands for oprs <<, <<=, <, <=, >>, >>=, >, >=, &&,+,- and unary ~
* or macaddr/macaddr8 operands for oprs &, |, unary ~
* */
if (opname[0] == '&' && opname[1] == '&' && opname[2] == '\0')
{
Oid ltypid = exprType(get_leftop((const Expr *) e));
Oid rtypid = exprType(get_rightop((const Expr *) e));
if (ltypid == INETOID || rtypid == INETOID)
return -2;
}
if ((opname[0] == '&' || opname[0] == '|') && opname[1] == '\0')
{
Oid ltypid = exprType(get_leftop((const Expr *) e));
Oid rtypid = exprType(get_rightop((const Expr *) e));
if (ltypid == MACADDROID || rtypid == MACADDROID ||
ltypid == MACADDR8OID || rtypid == MACADDR8OID)
return -2;
}
commons:
if ((opname[0] == '+' || opname[0] == '-') && opname[1] == '\0')
{
Oid ltypid = exprType(get_leftop((const Expr *) e));
Oid rtypid = exprType(get_rightop((const Expr *) e));
if (ltypid == INETOID || rtypid == INETOID)
return -2;
}
/*
* MySQL can't do substract to produce interval values, have to do it
* in computing node.
* */
if (opname[0] == '-' && opname[1] == '\0' &&
(is_interval_opr_type(exprType(get_leftop((const Expr *) e))) ||
is_interval_opr_type(exprType(get_rightop((const Expr *) e)))))
return -2;
#if 0
else if (strcasecmp(opname, "") == 0)
opname = "";
#endif
if (list_length(e->args) > 1)
{
APPEND_EXPR(get_leftop((const Expr *) e));
APPEND_STR_FMT(" %s ", ((opname != NULL) ? opname : "(invalid operator)"));
APPEND_EXPR(get_rightop((const Expr *) e));
}
else
{
/* we print prefix and postfix ops the same... */
APPEND_STR_FMT(" %s ", (opname != NULL) ? opname : "(invalid operator)");
APPEND_EXPR(get_leftop((const Expr *) e));
}
op_expr_done:
APPEND_CHAR(')');
}
else if (IsA(expr, FuncExpr))
{
const FuncExpr *e = (const FuncExpr *) expr;
char *funcname;
funcname = get_func_name(e->funcid);
if (!mysql_has_func(funcname))
{
/*
no need for such functions, let mysql do local type conversion
if needed.
*/
if (is_type_conversion_func(e->funcid))
{
APPEND_EXPR(linitial(e->args));
goto end;
}
else
goto unsupported;
}
APPEND_STR_FMT(" %s(", (funcname != NULL) ? funcname : "(invalid function)");
if ((nw1 = append_expr_list(str, e->args, rpec)) < 0)
return nw1;
nw += nw1;
APPEND_CHAR(')');
}
else if (IsA(expr, BoolExpr))
{
BoolExpr *boolexpr = (BoolExpr *) expr;
int nargs = list_length(boolexpr->args);
int off;
ListCell *lc;
off = 0;
APPEND_CHAR('(');
foreach(lc, boolexpr->args)
{
Expr *arg = (Expr *) lfirst(lc);
/* Perform the appropriate step type */
switch (boolexpr->boolop)
{
case AND_EXPR:
Assert(nargs >= 2);
APPEND_EXPR(arg);
if (lnext(lc))
APPEND_STR(" AND ");
break;
case OR_EXPR:
Assert(nargs >= 2);
APPEND_EXPR(arg);
if (lnext(lc))
APPEND_STR(" OR ");
break;
case NOT_EXPR:
Assert(nargs == 1);
APPEND_STR("NOT ");
APPEND_EXPR(arg);
break;
default:
goto unsupported;
break;
}
off++;
}
APPEND_CHAR(')');
}
else if (IsA(expr, BooleanTest))
{
BooleanTest *btest = (BooleanTest *) expr;
const char *pbteststr = 0;
switch (btest->booltesttype)
{
case IS_TRUE:
pbteststr = " IS TRUE";
break;
case IS_NOT_TRUE:
pbteststr = " IS NOT TRUE";
break;
case IS_FALSE:
pbteststr = " IS FALSE";
break;
case IS_NOT_FALSE:
pbteststr = " IS NOT FALSE";
break;
case IS_UNKNOWN:
pbteststr = " IS NULL";
break;
case IS_NOT_UNKNOWN:
pbteststr = " IS NOT NULL";
break;
default:
elog(ERROR, "unrecognized booltesttype: %d",
(int) btest->booltesttype);
}
APPEND_CHAR('(');
APPEND_EXPR(btest->arg);
APPEND_STR(pbteststr);
APPEND_CHAR(')');
}
else if (IsA(expr, NullTest))
{
const char *pnteststr = 0;
NullTest *ntest = (NullTest *) expr;
if (ntest->nulltesttype == IS_NULL)
{
pnteststr = " IS NULL";
}
else if (ntest->nulltesttype == IS_NOT_NULL)
{
pnteststr = " IS NOT NULL";
}
else
{
elog(ERROR, "unrecognized nulltesttype: %d",
(int) ntest->nulltesttype);
}
APPEND_CHAR('(');
APPEND_EXPR(ntest->arg);
APPEND_STR(pnteststr);
APPEND_CHAR(')');
}
else if (IsA(expr, Param) && !rpec->ignore_param_quals)
{
Param *param = (Param *)expr;
ParamExecData *ped = rpec->rpec_param_exec_vals + param->paramid;
if ((nw1 = output_const_type_value(str, ped->isnull, param->paramtype,
ped->value)) < 0)
return nw1;
nw += nw1;
}
else if (IsA(expr, RelabelType))
{
RelabelType *rt = (RelabelType*)expr;
APPEND_EXPR(rt->arg);
}
else if (IsA(expr, CoerceViaIO))
{
CoerceViaIO*cvi = (CoerceViaIO*)expr;
APPEND_EXPR(cvi->arg);
}
else if (IsA(expr, SQLValueFunction))
{
SQLValueFunction *svf = (SQLValueFunction *)expr;
if ((nw1 = SQLValueFuncValue(svf, str)) < 0)
return nw1;
nw += nw1;
}
else if (IsA(expr, MinMaxExpr))
{
MinMaxExpr*mme = (MinMaxExpr*)expr;
if (mme->op == IS_GREATEST)
APPEND_STR(" GREATEST(");
else if (mme->op == IS_LEAST)
APPEND_STR(" LEAST(");
else
return -2;
if ((nw1 = append_expr_list(str, mme->args, rpec)) < 0)
return nw1;
nw += nw1;
APPEND_CHAR(')');
}
else if (IsA(expr, CoalesceExpr))
{
CoalesceExpr *ce = (CoalesceExpr *)expr;
APPEND_STR(" Coalesce(");
if ((nw1 = append_expr_list(str, ce->args, rpec)) < 0)
return nw1;
nw += nw1;
APPEND_CHAR(')');
}
else if (IsA(expr, CaseExpr))
{
CaseExpr *ce = (CaseExpr *)expr;
APPEND_STR(" CASE ");
bool eqs = false;
ListCell *lc = NULL;
if (ce->arg)
{
APPEND_EXPR(ce->arg);
eqs = (ce->casetype != InvalidOid);
}
foreach(lc, ce->args)
{
CaseWhen *cw = (CaseWhen *)lfirst(lc);
APPEND_STR(" WHEN ");
if (!eqs)
APPEND_EXPR(cw->expr);
else if (IsA(cw->expr, OpExpr))
{
/*
According to comments in CaseExpr definition, cw->expr must
be a CaseTestExpr = compexpr expression in this case.
However, there are
situations where pg doesn't handle correctly, e.g. when ce->arg
is a NullTest node, and we'd have to error out.
*/
OpExpr *eqexpr = (OpExpr*)cw->expr;
/*Assert(IsA(linitial(eqexpr->args), CaseTestExpr));
The CaseTestExpr node maybe wrapped into a RelabelType node,
or other nodes.
*/
APPEND_EXPR(lsecond(eqexpr->args));
}
else
return -2;
APPEND_STR(" THEN ");
APPEND_EXPR(cw->result);
}
if (ce->defresult)
{
APPEND_STR(" ELSE ");
APPEND_EXPR(ce->defresult);
}
APPEND_STR(" END ");
}
else if (IsA(expr, ScalarArrayOpExpr))
{
ScalarArrayOpExpr *scoe = (ScalarArrayOpExpr *)expr;
const char *opname = get_opname(scoe->opno);
APPEND_EXPR(linitial(scoe->args));
/*
APPEND_STR(opname);
if (scoe->useOr)
APPEND_STR(" ANY");
else
APPEND_STR(" ALL");
*/
/*
'col IN (expr1, expr2, ..., exprN)' is valid SQL expr, but
'col comp-opr ANY(expr1, expr2, ..., exprN)'
isn't, for both mysql and pg.
For mysql-8.0.19 and newer, we can convert it to
'col comp-opr ANY(VALUES ROW(expr1), ROW(expr2),..., ROW(exprN))',
especially the 'exprN' here can be a list, such as '1,2,3', to
do a 'row subquery' as in mysql's terms, so we can accept 1-D or 2D
array here when we upgrade to newer mysql.
but for current kunlun-storage(based on mysql-8.0.18), we have to
reject such exprs so we only send 'col IN(expr list)' grammar.
pg supports 'col comp-opr ANY(array-constructor)' grammar so
that ' a > ANY(ARRAY[1,2,3])' is valid for pg but this is not
standard SQL and this is how we would recv such an unsupported expr
here because if the subquery is an select, pg will do semijoin.
*/
if (!(scoe->useOr && strcmp(opname, "=") == 0))
return -2;
APPEND_STR(" IN");
rpec->skip_n = 1;
if ((nw1 = append_expr_list(str, scoe->args, rpec)) < 0)
{
rpec->skip_n = 0;
return nw1;
}
rpec->skip_n = 0;
nw += nw1;
}
else if (IsA(expr, NextValueExpr))
{
NextValueExpr *nve = (NextValueExpr *)expr;
nw += eval_nextval_expr(str, nve);
}
else if (IsA(expr, RowExpr))
{
RowExpr *rowexpr = (RowExpr *)expr;
if ((nw1 = append_expr_list(str, rowexpr->args, rpec)) < 0)
return nw1;
nw += nw1;
rpec->num_vals = list_length(rowexpr->args);
}
else
{
unsupported:
return -2;
}
end:
return nw;
}
#define CONST_STR_LEN(conststr) conststr,(sizeof(conststr)-1)
static int SQLValueFuncValue(SQLValueFunction *svfo, StringInfo str_res)
{
int nw = -1;
static char sql_func[64];
bool is_datetime = false;
switch (svfo->op)
{
case SVFOP_CURRENT_DATE:
nw = snprintf(sql_func, sizeof(sql_func), "SELECT CURRENT_DATE ");
is_datetime = true;
break;
case SVFOP_CURRENT_TIME:
nw = snprintf(sql_func, sizeof(sql_func), "SELECT CURRENT_TIME ");
is_datetime = true;
break;
case SVFOP_CURRENT_TIME_N:
nw = snprintf(sql_func, sizeof(sql_func), "SELECT CURRENT_TIME(%d) ",
svfo->typmod);
is_datetime = true;
break;
case SVFOP_CURRENT_TIMESTAMP:
nw = snprintf(sql_func, sizeof(sql_func), "SELECT CURRENT_TIMESTAMP ");
is_datetime = true;
break;
case SVFOP_CURRENT_TIMESTAMP_N:
nw = snprintf(sql_func, sizeof(sql_func), "SELECT CURRENT_TIMESTAMP(%d) ",
svfo->typmod);
is_datetime = true;
break;
case SVFOP_LOCALTIME:
nw = snprintf(sql_func, sizeof(sql_func), "SELECT LOCALTIME ");
is_datetime = true;
break;
case SVFOP_LOCALTIME_N:
nw = snprintf(sql_func, sizeof(sql_func), "SELECT LOCALTIME(%d) ",
svfo->typmod);
is_datetime = true;
break;
case SVFOP_LOCALTIMESTAMP:
nw = snprintf(sql_func, sizeof(sql_func), "SELECT LOCALTIMESTAMP ");
is_datetime = true;
break;
case SVFOP_LOCALTIMESTAMP_N:
nw = snprintf(sql_func, sizeof(sql_func), "SELECT LOCALTIMESTAMP(%d) ",
svfo->typmod);
is_datetime = true;
break;
case SVFOP_CURRENT_ROLE:
nw = snprintf(sql_func, sizeof(sql_func), "SELECT CURRENT_ROLE ");
break;
case SVFOP_CURRENT_USER:
nw = snprintf(sql_func, sizeof(sql_func), "SELECT CURRENT_USER ");
break;
case SVFOP_USER:
nw = snprintf(sql_func, sizeof(sql_func), "SELECT USER ");
break;
case SVFOP_SESSION_USER:
nw = snprintf(sql_func, sizeof(sql_func), "SELECT SESSION_USER ");
break;
case SVFOP_CURRENT_CATALOG:
nw = snprintf(sql_func, sizeof(sql_func), "SELECT CURRENT_CATALOG ");
break;
case SVFOP_CURRENT_SCHEMA:
nw = snprintf(sql_func, sizeof(sql_func), "SELECT CURRENT_SCHEMA ");
break;
default:
nw = -2;
break;
}
if (nw >= sizeof(sql_func))
{
nw = -2;
goto end;
}
// execute the sql function and return the value.
SPI_connect();
// always use standard date/time/ts values in UTC+0.
pg_tz *gmt_tz = pg_tzset("GMT"), *origtz = NULL;
int orig_datestyle = -1, orig_dateorder = -1, orig_intvstyle = -1;
if (is_datetime)
{
orig_datestyle = DateStyle;
orig_dateorder = DateOrder;
origtz = session_timezone;
orig_intvstyle = IntervalStyle;
DateStyle = USE_ISO_DATES;
DateOrder = DATEORDER_YMD;
IntervalStyle = INTSTYLE_ISO_8601;
session_timezone = gmt_tz;
}
int ret = SPI_execute(sql_func, true, 0);
if (ret != SPI_OK_SELECT)
{
SPI_finish();
elog(ERROR, "SPI_execute failed for function %s: error code %d", sql_func, ret);
}
if (SPI_processed != 1)
{
SPI_finish();
elog(ERROR, "SPI_execute returned %lu rows executing function %s, but 1 row is expected.",
SPI_processed, sql_func);
}
char *val = SPI_getvalue(SPI_tuptable->vals[0], SPI_tuptable->tupdesc, 1);
nw = appendStringInfo(str_res, "'%s'", val);
if (orig_datestyle != -1)
{
DateStyle = orig_datestyle;
DateOrder = orig_dateorder;
IntervalStyle = orig_intvstyle;
session_timezone = origtz;
}
SPI_finish();
end:
return nw;
}
static int append_expr_list(StringInfo str, List *l, RemotePrintExprContext *rpec)
{
int nw = 0, nw1 = 0, cnt = 0;
ListCell *lc;
foreach(lc, l)
{
if (cnt++ < rpec->skip_n) continue;
APPEND_EXPR(lfirst(lc));
if (lnext(lc))
{
APPEND_CHAR(',');
}
}
return nw;
}
static int eval_nextval_expr(StringInfo str, NextValueExpr *nve)
{
int64 newval = nextval_internal(nve->seqid, false);
int nw = 0, nw1 = 0;
switch (nve->typeId)
{
case INT2OID:
APPEND_STR_FMT("%d", (int16) newval);
break;
case INT4OID:
APPEND_STR_FMT("%d", (int32) newval);
break;
case INT8OID:
APPEND_STR_FMT("%ld", (int64) newval);
break;
default:
elog(ERROR, "unsupported sequence type %u", nve->typeId);
}
return nw;
}
|
661231.c | /*
* This file is part of the Micro Python project, http://micropython.org/
*
* The MIT License (MIT)
*
* Copyright (c) 2013, 2014 Damien P. George
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include <stdio.h>
#include <string.h>
#include <stdarg.h>
#include <errno.h>
#include "py/nlr.h"
#include "py/runtime.h"
#include "py/stream.h"
#include "uart.h"
#include "pybioctl.h"
#include MICROPY_HAL_H
//TODO: Add UART7/8 support for MCU_SERIES_F7
/// \moduleref pyb
/// \class UART - duplex serial communication bus
///
/// UART implements the standard UART/USART duplex serial communications protocol. At
/// the physical level it consists of 2 lines: RX and TX. The unit of communication
/// is a character (not to be confused with a string character) which can be 8 or 9
/// bits wide.
///
/// UART objects can be created and initialised using:
///
/// from pyb import UART
///
/// uart = UART(1, 9600) # init with given baudrate
/// uart.init(9600, bits=8, parity=None, stop=1) # init with given parameters
///
/// Bits can be 8 or 9. Parity can be None, 0 (even) or 1 (odd). Stop can be 1 or 2.
///
/// A UART object acts like a stream object and reading and writing is done
/// using the standard stream methods:
///
/// uart.read(10) # read 10 characters, returns a bytes object
/// uart.readall() # read all available characters
/// uart.readline() # read a line
/// uart.readinto(buf) # read and store into the given buffer
/// uart.write('abc') # write the 3 characters
///
/// Individual characters can be read/written using:
///
/// uart.readchar() # read 1 character and returns it as an integer
/// uart.writechar(42) # write 1 character
///
/// To check if there is anything to be read, use:
///
/// uart.any() # returns True if any characters waiting
#define CHAR_WIDTH_8BIT (0)
#define CHAR_WIDTH_9BIT (1)
struct _pyb_uart_obj_t {
mp_obj_base_t base;
UART_HandleTypeDef uart; // this is 17 words big
IRQn_Type irqn;
pyb_uart_t uart_id : 8;
bool is_enabled : 1;
byte char_width; // 0 for 7,8 bit chars, 1 for 9 bit chars
uint16_t char_mask; // 0x7f for 7 bit, 0xff for 8 bit, 0x1ff for 9 bit
uint16_t timeout; // timeout waiting for first char
uint16_t timeout_char; // timeout waiting between chars
uint16_t read_buf_len; // len in chars; buf can hold len-1 chars
volatile uint16_t read_buf_head; // indexes first empty slot
uint16_t read_buf_tail; // indexes first full slot (not full if equals head)
byte *read_buf; // byte or uint16_t, depending on char size
};
STATIC mp_obj_t pyb_uart_deinit(mp_obj_t self_in);
void uart_init0(void) {
for (int i = 0; i < MP_ARRAY_SIZE(MP_STATE_PORT(pyb_uart_obj_all)); i++) {
MP_STATE_PORT(pyb_uart_obj_all)[i] = NULL;
}
}
// unregister all interrupt sources
void uart_deinit(void) {
for (int i = 0; i < MP_ARRAY_SIZE(MP_STATE_PORT(pyb_uart_obj_all)); i++) {
pyb_uart_obj_t *uart_obj = MP_STATE_PORT(pyb_uart_obj_all)[i];
if (uart_obj != NULL) {
pyb_uart_deinit(uart_obj);
}
}
}
// assumes Init parameters have been set up correctly
STATIC bool uart_init2(pyb_uart_obj_t *uart_obj) {
USART_TypeDef *UARTx;
IRQn_Type irqn;
uint32_t GPIO_Pin, GPIO_Pin2;
uint8_t GPIO_AF_UARTx = 0;
GPIO_TypeDef* GPIO_Port = NULL;
GPIO_TypeDef* GPIO_Port2 = NULL;
switch (uart_obj->uart_id) {
#if defined(MICROPY_HW_UART1_PORT) && defined(MICROPY_HW_UART1_PINS)
// USART1 is on PA9/PA10 (CK on PA8), PB6/PB7
case PYB_UART_1:
UARTx = USART1;
irqn = USART1_IRQn;
GPIO_AF_UARTx = GPIO_AF7_USART1;
GPIO_Port = MICROPY_HW_UART1_PORT;
GPIO_Pin = MICROPY_HW_UART1_PINS;
__USART1_CLK_ENABLE();
break;
#endif
#if defined(MICROPY_HW_UART1_TX_PORT) && \
defined(MICROPY_HW_UART1_TX_PIN) && \
defined(MICROPY_HW_UART1_RX_PORT) && \
defined(MICROPY_HW_UART1_RX_PIN)
case PYB_UART_1:
UARTx = USART1;
irqn = USART1_IRQn;
GPIO_AF_UARTx = GPIO_AF7_USART1;
GPIO_Port = MICROPY_HW_UART1_TX_PORT;
GPIO_Pin = MICROPY_HW_UART1_TX_PIN;
GPIO_Port2 = MICROPY_HW_UART1_RX_PORT;
GPIO_Pin2 = MICROPY_HW_UART1_RX_PIN;
__USART1_CLK_ENABLE();
break;
#endif
#if defined(MICROPY_HW_UART2_PORT) && defined(MICROPY_HW_UART2_PINS)
// USART2 is on PA2/PA3 (CTS,RTS,CK on PA0,PA1,PA4), PD5/PD6 (CK on PD7)
case PYB_UART_2:
UARTx = USART2;
irqn = USART2_IRQn;
GPIO_AF_UARTx = GPIO_AF7_USART2;
GPIO_Port = MICROPY_HW_UART2_PORT;
GPIO_Pin = MICROPY_HW_UART2_PINS;
#if defined(MICROPY_HW_UART2_RTS)
if (uart_obj->uart.Init.HwFlowCtl & UART_HWCONTROL_RTS) {
GPIO_Pin |= MICROPY_HW_UART2_RTS;
}
#endif
#if defined(MICROPY_HW_UART2_CTS)
if (uart_obj->uart.Init.HwFlowCtl & UART_HWCONTROL_CTS) {
GPIO_Pin |= MICROPY_HW_UART2_CTS;
}
#endif
__USART2_CLK_ENABLE();
break;
#endif
#if defined(USART3) && defined(MICROPY_HW_UART3_PORT) && defined(MICROPY_HW_UART3_PINS)
// USART3 is on PB10/PB11 (CK,CTS,RTS on PB12,PB13,PB14), PC10/PC11 (CK on PC12), PD8/PD9 (CK on PD10)
case PYB_UART_3:
UARTx = USART3;
irqn = USART3_IRQn;
GPIO_AF_UARTx = GPIO_AF7_USART3;
GPIO_Port = MICROPY_HW_UART3_PORT;
GPIO_Pin = MICROPY_HW_UART3_PINS;
#if defined(MICROPY_HW_UART3_RTS)
if (uart_obj->uart.Init.HwFlowCtl & UART_HWCONTROL_RTS) {
GPIO_Pin |= MICROPY_HW_UART3_RTS;
}
#endif
#if defined(MICROPY_HW_UART3_CTS)
if (uart_obj->uart.Init.HwFlowCtl & UART_HWCONTROL_CTS) {
GPIO_Pin |= MICROPY_HW_UART3_CTS;
}
#endif
__USART3_CLK_ENABLE();
break;
#endif
#if defined(UART4) && defined(MICROPY_HW_UART4_PORT) && defined(MICROPY_HW_UART4_PINS)
// UART4 is on PA0/PA1, PC10/PC11
case PYB_UART_4:
UARTx = UART4;
irqn = UART4_IRQn;
GPIO_AF_UARTx = GPIO_AF8_UART4;
GPIO_Port = MICROPY_HW_UART4_PORT;
GPIO_Pin = MICROPY_HW_UART4_PINS;
__UART4_CLK_ENABLE();
break;
#endif
#if defined(UART5) && \
defined(MICROPY_HW_UART5_TX_PORT) && \
defined(MICROPY_HW_UART5_TX_PIN) && \
defined(MICROPY_HW_UART5_RX_PORT) && \
defined(MICROPY_HW_UART5_RX_PIN)
case PYB_UART_5:
UARTx = UART5;
irqn = UART5_IRQn;
GPIO_AF_UARTx = GPIO_AF8_UART5;
GPIO_Port = MICROPY_HW_UART5_TX_PORT;
GPIO_Port2 = MICROPY_HW_UART5_RX_PORT;
GPIO_Pin = MICROPY_HW_UART5_TX_PIN;
GPIO_Pin2 = MICROPY_HW_UART5_RX_PIN;
__UART5_CLK_ENABLE();
break;
#endif
#if defined(MICROPY_HW_UART6_PORT) && defined(MICROPY_HW_UART6_PINS)
// USART6 is on PC6/PC7 (CK on PC8)
case PYB_UART_6:
UARTx = USART6;
irqn = USART6_IRQn;
GPIO_AF_UARTx = GPIO_AF8_USART6;
GPIO_Port = MICROPY_HW_UART6_PORT;
GPIO_Pin = MICROPY_HW_UART6_PINS;
__USART6_CLK_ENABLE();
break;
#endif
default:
// UART does not exist or is not configured for this board
return false;
}
uart_obj->irqn = irqn;
uart_obj->uart.Instance = UARTx;
// init GPIO
mp_hal_gpio_clock_enable(GPIO_Port);
GPIO_InitTypeDef GPIO_InitStructure;
GPIO_InitStructure.Pin = GPIO_Pin;
GPIO_InitStructure.Speed = GPIO_SPEED_HIGH;
GPIO_InitStructure.Mode = GPIO_MODE_AF_PP;
GPIO_InitStructure.Pull = GPIO_PULLUP;
GPIO_InitStructure.Alternate = GPIO_AF_UARTx;
HAL_GPIO_Init(GPIO_Port, &GPIO_InitStructure);
// init GPIO for second pin if needed
if (GPIO_Port2 != NULL) {
mp_hal_gpio_clock_enable(GPIO_Port2);
GPIO_InitStructure.Pin = GPIO_Pin2;
HAL_GPIO_Init(GPIO_Port2, &GPIO_InitStructure);
}
// init UARTx
HAL_UART_Init(&uart_obj->uart);
uart_obj->is_enabled = true;
return true;
}
/* obsolete and unused
bool uart_init(pyb_uart_obj_t *uart_obj, uint32_t baudrate) {
UART_HandleTypeDef *uh = &uart_obj->uart;
memset(uh, 0, sizeof(*uh));
uh->Init.BaudRate = baudrate;
uh->Init.WordLength = UART_WORDLENGTH_8B;
uh->Init.StopBits = UART_STOPBITS_1;
uh->Init.Parity = UART_PARITY_NONE;
uh->Init.Mode = UART_MODE_TX_RX;
uh->Init.HwFlowCtl = UART_HWCONTROL_NONE;
uh->Init.OverSampling = UART_OVERSAMPLING_16;
return uart_init2(uart_obj);
}
*/
bool uart_rx_any(pyb_uart_obj_t *self) {
return self->read_buf_tail != self->read_buf_head
|| __HAL_UART_GET_FLAG(&self->uart, UART_FLAG_RXNE) != RESET;
}
// Waits at most timeout milliseconds for at least 1 char to become ready for
// reading (from buf or for direct reading).
// Returns true if something available, false if not.
STATIC bool uart_rx_wait(pyb_uart_obj_t *self, uint32_t timeout) {
uint32_t start = HAL_GetTick();
for (;;) {
if (self->read_buf_tail != self->read_buf_head || __HAL_UART_GET_FLAG(&self->uart, UART_FLAG_RXNE) != RESET) {
return true; // have at least 1 char ready for reading
}
if (HAL_GetTick() - start >= timeout) {
return false; // timeout
}
__WFI();
}
}
// assumes there is a character available
int uart_rx_char(pyb_uart_obj_t *self) {
if (self->read_buf_tail != self->read_buf_head) {
// buffering via IRQ
int data;
if (self->char_width == CHAR_WIDTH_9BIT) {
data = ((uint16_t*)self->read_buf)[self->read_buf_tail];
} else {
data = self->read_buf[self->read_buf_tail];
}
self->read_buf_tail = (self->read_buf_tail + 1) % self->read_buf_len;
return data;
} else {
// no buffering
#if defined(MCU_SERIES_F7)
return self->uart.Instance->RDR & self->char_mask;
#else
return self->uart.Instance->DR & self->char_mask;
#endif
}
}
STATIC void uart_tx_char(pyb_uart_obj_t *uart_obj, int c) {
uint8_t ch = c;
HAL_UART_Transmit(&uart_obj->uart, &ch, 1, uart_obj->timeout);
}
void uart_tx_strn(pyb_uart_obj_t *uart_obj, const char *str, uint len) {
HAL_UART_Transmit(&uart_obj->uart, (uint8_t*)str, len, uart_obj->timeout);
}
void uart_tx_strn_cooked(pyb_uart_obj_t *uart_obj, const char *str, uint len) {
for (const char *top = str + len; str < top; str++) {
if (*str == '\n') {
uart_tx_char(uart_obj, '\r');
}
uart_tx_char(uart_obj, *str);
}
}
// this IRQ handler is set up to handle RXNE interrupts only
void uart_irq_handler(mp_uint_t uart_id) {
// get the uart object
pyb_uart_obj_t *self = MP_STATE_PORT(pyb_uart_obj_all)[uart_id - 1];
if (self == NULL) {
// UART object has not been set, so we can't do anything, not
// even disable the IRQ. This should never happen.
return;
}
if (__HAL_UART_GET_FLAG(&self->uart, UART_FLAG_RXNE) != RESET) {
#if defined(MCU_SERIES_F7)
int data = self->uart.Instance->RDR; // clears UART_FLAG_RXNE
#else
int data = self->uart.Instance->DR; // clears UART_FLAG_RXNE
#endif
data &= self->char_mask;
if (self->read_buf_len != 0) {
uint16_t next_head = (self->read_buf_head + 1) % self->read_buf_len;
if (next_head != self->read_buf_tail) {
// only store data if room in buf
if (self->char_width == CHAR_WIDTH_9BIT) {
((uint16_t*)self->read_buf)[self->read_buf_head] = data;
} else {
self->read_buf[self->read_buf_head] = data;
}
self->read_buf_head = next_head;
}
} else {
// TODO set flag for buffer overflow
}
}
}
/******************************************************************************/
/* Micro Python bindings */
STATIC void pyb_uart_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t kind) {
pyb_uart_obj_t *self = self_in;
if (!self->is_enabled) {
mp_printf(print, "UART(%u)", self->uart_id);
} else {
mp_int_t bits = (self->uart.Init.WordLength == UART_WORDLENGTH_8B ? 8 : 9);
if (self->uart.Init.Parity != UART_PARITY_NONE) {
bits -= 1;
}
mp_printf(print, "UART(%u, baudrate=%u, bits=%u, parity=",
self->uart_id, self->uart.Init.BaudRate, bits);
if (self->uart.Init.Parity == UART_PARITY_NONE) {
mp_print_str(print, "None");
} else {
mp_printf(print, "%u", self->uart.Init.Parity == UART_PARITY_EVEN ? 0 : 1);
}
mp_printf(print, ", stop=%u, timeout=%u, timeout_char=%u, read_buf_len=%u)",
self->uart.Init.StopBits == UART_STOPBITS_1 ? 1 : 2,
self->timeout, self->timeout_char, self->read_buf_len);
}
}
/// \method init(baudrate, bits=8, parity=None, stop=1, *, timeout=1000, timeout_char=0, read_buf_len=64)
///
/// Initialise the UART bus with the given parameters:
///
/// - `baudrate` is the clock rate.
/// - `bits` is the number of bits per byte, 7, 8 or 9.
/// - `parity` is the parity, `None`, 0 (even) or 1 (odd).
/// - `stop` is the number of stop bits, 1 or 2.
/// - `timeout` is the timeout in milliseconds to wait for the first character.
/// - `timeout_char` is the timeout in milliseconds to wait between characters.
/// - `read_buf_len` is the character length of the read buffer (0 to disable).
STATIC mp_obj_t pyb_uart_init_helper(pyb_uart_obj_t *self, mp_uint_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) {
static const mp_arg_t allowed_args[] = {
{ MP_QSTR_baudrate, MP_ARG_REQUIRED | MP_ARG_INT, {.u_int = 9600} },
{ MP_QSTR_bits, MP_ARG_INT, {.u_int = 8} },
{ MP_QSTR_parity, MP_ARG_OBJ, {.u_obj = mp_const_none} },
{ MP_QSTR_stop, MP_ARG_INT, {.u_int = 1} },
{ MP_QSTR_flow, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = UART_HWCONTROL_NONE} },
{ MP_QSTR_timeout, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 1000} },
{ MP_QSTR_timeout_char, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 0} },
{ MP_QSTR_read_buf_len, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 64} },
};
// parse args
mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)];
mp_arg_parse_all(n_args, pos_args, kw_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args);
// set the UART configuration values
memset(&self->uart, 0, sizeof(self->uart));
UART_InitTypeDef *init = &self->uart.Init;
// baudrate
init->BaudRate = args[0].u_int;
// parity
mp_int_t bits = args[1].u_int;
if (args[2].u_obj == mp_const_none) {
init->Parity = UART_PARITY_NONE;
} else {
mp_int_t parity = mp_obj_get_int(args[2].u_obj);
init->Parity = (parity & 1) ? UART_PARITY_ODD : UART_PARITY_EVEN;
bits += 1; // STs convention has bits including parity
}
// number of bits
if (bits == 8) {
init->WordLength = UART_WORDLENGTH_8B;
} else if (bits == 9) {
init->WordLength = UART_WORDLENGTH_9B;
} else {
nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "unsupported combination of bits and parity"));
}
// stop bits
switch (args[3].u_int) {
case 1: init->StopBits = UART_STOPBITS_1; break;
default: init->StopBits = UART_STOPBITS_2; break;
}
// flow control
init->HwFlowCtl = args[4].u_int;
// extra config (not yet configurable)
init->Mode = UART_MODE_TX_RX;
init->OverSampling = UART_OVERSAMPLING_16;
// init UART (if it fails, it's because the port doesn't exist)
if (!uart_init2(self)) {
nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "UART(%d) does not exist", self->uart_id));
}
// set timeouts
self->timeout = args[5].u_int;
self->timeout_char = args[6].u_int;
// setup the read buffer
m_del(byte, self->read_buf, self->read_buf_len << self->char_width);
if (init->WordLength == UART_WORDLENGTH_9B && init->Parity == UART_PARITY_NONE) {
self->char_mask = 0x1ff;
self->char_width = CHAR_WIDTH_9BIT;
} else {
if (init->WordLength == UART_WORDLENGTH_9B || init->Parity == UART_PARITY_NONE) {
self->char_mask = 0xff;
} else {
self->char_mask = 0x7f;
}
self->char_width = CHAR_WIDTH_8BIT;
}
self->read_buf_head = 0;
self->read_buf_tail = 0;
if (args[7].u_int <= 0) {
// no read buffer
self->read_buf_len = 0;
self->read_buf = NULL;
HAL_NVIC_DisableIRQ(self->irqn);
__HAL_UART_DISABLE_IT(&self->uart, UART_IT_RXNE);
} else {
// read buffer using interrupts
self->read_buf_len = args[7].u_int;
self->read_buf = m_new(byte, args[7].u_int << self->char_width);
__HAL_UART_ENABLE_IT(&self->uart, UART_IT_RXNE);
HAL_NVIC_SetPriority(self->irqn, 0xd, 0xd); // next-to-next-to lowest priority
HAL_NVIC_EnableIRQ(self->irqn);
}
// compute actual baudrate that was configured
// (this formula assumes UART_OVERSAMPLING_16)
uint32_t actual_baudrate;
if (self->uart.Instance == USART1 || self->uart.Instance == USART6) {
actual_baudrate = HAL_RCC_GetPCLK2Freq();
} else {
actual_baudrate = HAL_RCC_GetPCLK1Freq();
}
actual_baudrate /= self->uart.Instance->BRR;
// check we could set the baudrate within 5%
uint32_t baudrate_diff;
if (actual_baudrate > init->BaudRate) {
baudrate_diff = actual_baudrate - init->BaudRate;
} else {
baudrate_diff = init->BaudRate - actual_baudrate;
}
init->BaudRate = actual_baudrate; // remember actual baudrate for printing
if (20 * baudrate_diff > init->BaudRate) {
nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "set baudrate %d is not within 5%% of desired value", actual_baudrate));
}
return mp_const_none;
}
/// \classmethod \constructor(bus, ...)
///
/// Construct a UART object on the given bus. `bus` can be 1-6, or 'XA', 'XB', 'YA', or 'YB'.
/// With no additional parameters, the UART object is created but not
/// initialised (it has the settings from the last initialisation of
/// the bus, if any). If extra arguments are given, the bus is initialised.
/// See `init` for parameters of initialisation.
///
/// The physical pins of the UART busses are:
///
/// - `UART(4)` is on `XA`: `(TX, RX) = (X1, X2) = (PA0, PA1)`
/// - `UART(1)` is on `XB`: `(TX, RX) = (X9, X10) = (PB6, PB7)`
/// - `UART(6)` is on `YA`: `(TX, RX) = (Y1, Y2) = (PC6, PC7)`
/// - `UART(3)` is on `YB`: `(TX, RX) = (Y9, Y10) = (PB10, PB11)`
/// - `UART(2)` is on: `(TX, RX) = (X3, X4) = (PA2, PA3)`
STATIC mp_obj_t pyb_uart_make_new(mp_obj_t type_in, mp_uint_t n_args, mp_uint_t n_kw, const mp_obj_t *args) {
// check arguments
mp_arg_check_num(n_args, n_kw, 1, MP_OBJ_FUN_ARGS_MAX, true);
// work out port
int uart_id = 0;
if (MP_OBJ_IS_STR(args[0])) {
const char *port = mp_obj_str_get_str(args[0]);
if (0) {
#ifdef MICROPY_HW_UART1_NAME
} else if (strcmp(port, MICROPY_HW_UART1_NAME) == 0) {
uart_id = PYB_UART_1;
#endif
#ifdef MICROPY_HW_UART2_NAME
} else if (strcmp(port, MICROPY_HW_UART2_NAME) == 0) {
uart_id = PYB_UART_2;
#endif
#ifdef MICROPY_HW_UART3_NAME
} else if (strcmp(port, MICROPY_HW_UART3_NAME) == 0) {
uart_id = PYB_UART_3;
#endif
#ifdef MICROPY_HW_UART4_NAME
} else if (strcmp(port, MICROPY_HW_UART4_NAME) == 0) {
uart_id = PYB_UART_4;
#endif
#ifdef MICROPY_HW_UART5_NAME
} else if (strcmp(port, MICROPY_HW_UART5_NAME) == 0) {
uart_id = PYB_UART_5;
#endif
#ifdef MICROPY_HW_UART6_NAME
} else if (strcmp(port, MICROPY_HW_UART6_NAME) == 0) {
uart_id = PYB_UART_6;
#endif
} else {
nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "UART(%s) does not exist", port));
}
} else {
uart_id = mp_obj_get_int(args[0]);
if (uart_id < 1 || uart_id > MP_ARRAY_SIZE(MP_STATE_PORT(pyb_uart_obj_all))) {
nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "UART(%d) does not exist", uart_id));
}
}
pyb_uart_obj_t *self;
if (MP_STATE_PORT(pyb_uart_obj_all)[uart_id - 1] == NULL) {
// create new UART object
self = m_new0(pyb_uart_obj_t, 1);
self->base.type = &pyb_uart_type;
self->uart_id = uart_id;
MP_STATE_PORT(pyb_uart_obj_all)[uart_id - 1] = self;
} else {
// reference existing UART object
self = MP_STATE_PORT(pyb_uart_obj_all)[uart_id - 1];
}
if (n_args > 1 || n_kw > 0) {
// start the peripheral
mp_map_t kw_args;
mp_map_init_fixed_table(&kw_args, n_kw, args + n_args);
pyb_uart_init_helper(self, n_args - 1, args + 1, &kw_args);
}
return self;
}
STATIC mp_obj_t pyb_uart_init(mp_uint_t n_args, const mp_obj_t *args, mp_map_t *kw_args) {
return pyb_uart_init_helper(args[0], n_args - 1, args + 1, kw_args);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_KW(pyb_uart_init_obj, 1, pyb_uart_init);
/// \method deinit()
/// Turn off the UART bus.
STATIC mp_obj_t pyb_uart_deinit(mp_obj_t self_in) {
pyb_uart_obj_t *self = self_in;
self->is_enabled = false;
UART_HandleTypeDef *uart = &self->uart;
HAL_UART_DeInit(uart);
if (uart->Instance == USART1) {
HAL_NVIC_DisableIRQ(USART1_IRQn);
__USART1_FORCE_RESET();
__USART1_RELEASE_RESET();
__USART1_CLK_DISABLE();
} else if (uart->Instance == USART2) {
HAL_NVIC_DisableIRQ(USART2_IRQn);
__USART2_FORCE_RESET();
__USART2_RELEASE_RESET();
__USART2_CLK_DISABLE();
#if defined(USART3)
} else if (uart->Instance == USART3) {
HAL_NVIC_DisableIRQ(USART3_IRQn);
__USART3_FORCE_RESET();
__USART3_RELEASE_RESET();
__USART3_CLK_DISABLE();
#endif
#if defined(UART4)
} else if (uart->Instance == UART4) {
HAL_NVIC_DisableIRQ(UART4_IRQn);
__UART4_FORCE_RESET();
__UART4_RELEASE_RESET();
__UART4_CLK_DISABLE();
#endif
#if defined(UART5)
} else if (uart->Instance == UART5) {
HAL_NVIC_DisableIRQ(UART5_IRQn);
__UART5_FORCE_RESET();
__UART5_RELEASE_RESET();
__UART5_CLK_DISABLE();
#endif
} else if (uart->Instance == USART6) {
HAL_NVIC_DisableIRQ(USART6_IRQn);
__USART6_FORCE_RESET();
__USART6_RELEASE_RESET();
__USART6_CLK_DISABLE();
}
return mp_const_none;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_1(pyb_uart_deinit_obj, pyb_uart_deinit);
/// \method any()
/// Return `True` if any characters waiting, else `False`.
STATIC mp_obj_t pyb_uart_any(mp_obj_t self_in) {
pyb_uart_obj_t *self = self_in;
if (uart_rx_any(self)) {
return mp_const_true;
} else {
return mp_const_false;
}
}
STATIC MP_DEFINE_CONST_FUN_OBJ_1(pyb_uart_any_obj, pyb_uart_any);
/// \method writechar(char)
/// Write a single character on the bus. `char` is an integer to write.
/// Return value: `None`.
STATIC mp_obj_t pyb_uart_writechar(mp_obj_t self_in, mp_obj_t char_in) {
pyb_uart_obj_t *self = self_in;
// get the character to write (might be 9 bits)
uint16_t data = mp_obj_get_int(char_in);
// write the data
HAL_StatusTypeDef status = HAL_UART_Transmit(&self->uart, (uint8_t*)&data, 1, self->timeout);
if (status != HAL_OK) {
mp_hal_raise(status);
}
return mp_const_none;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_2(pyb_uart_writechar_obj, pyb_uart_writechar);
/// \method readchar()
/// Receive a single character on the bus.
/// Return value: The character read, as an integer. Returns -1 on timeout.
STATIC mp_obj_t pyb_uart_readchar(mp_obj_t self_in) {
pyb_uart_obj_t *self = self_in;
if (uart_rx_wait(self, self->timeout)) {
return MP_OBJ_NEW_SMALL_INT(uart_rx_char(self));
} else {
// return -1 on timeout
return MP_OBJ_NEW_SMALL_INT(-1);
}
}
STATIC MP_DEFINE_CONST_FUN_OBJ_1(pyb_uart_readchar_obj, pyb_uart_readchar);
// uart.sendbreak()
STATIC mp_obj_t pyb_uart_sendbreak(mp_obj_t self_in) {
pyb_uart_obj_t *self = self_in;
#if defined(MCU_SERIES_F7)
self->uart.Instance->RQR = USART_RQR_SBKRQ; // write-only register
#else
self->uart.Instance->CR1 |= USART_CR1_SBK;
#endif
return mp_const_none;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_1(pyb_uart_sendbreak_obj, pyb_uart_sendbreak);
STATIC const mp_map_elem_t pyb_uart_locals_dict_table[] = {
// instance methods
{ MP_OBJ_NEW_QSTR(MP_QSTR_init), (mp_obj_t)&pyb_uart_init_obj },
{ MP_OBJ_NEW_QSTR(MP_QSTR_deinit), (mp_obj_t)&pyb_uart_deinit_obj },
{ MP_OBJ_NEW_QSTR(MP_QSTR_any), (mp_obj_t)&pyb_uart_any_obj },
/// \method read([nbytes])
{ MP_OBJ_NEW_QSTR(MP_QSTR_read), (mp_obj_t)&mp_stream_read_obj },
/// \method readall()
{ MP_OBJ_NEW_QSTR(MP_QSTR_readall), (mp_obj_t)&mp_stream_readall_obj },
/// \method readline()
{ MP_OBJ_NEW_QSTR(MP_QSTR_readline), (mp_obj_t)&mp_stream_unbuffered_readline_obj},
/// \method readinto(buf[, nbytes])
{ MP_OBJ_NEW_QSTR(MP_QSTR_readinto), (mp_obj_t)&mp_stream_readinto_obj },
/// \method write(buf)
{ MP_OBJ_NEW_QSTR(MP_QSTR_write), (mp_obj_t)&mp_stream_write_obj },
{ MP_OBJ_NEW_QSTR(MP_QSTR_writechar), (mp_obj_t)&pyb_uart_writechar_obj },
{ MP_OBJ_NEW_QSTR(MP_QSTR_readchar), (mp_obj_t)&pyb_uart_readchar_obj },
{ MP_OBJ_NEW_QSTR(MP_QSTR_sendbreak), (mp_obj_t)&pyb_uart_sendbreak_obj },
// class constants
{ MP_OBJ_NEW_QSTR(MP_QSTR_RTS), MP_OBJ_NEW_SMALL_INT(UART_HWCONTROL_RTS) },
{ MP_OBJ_NEW_QSTR(MP_QSTR_CTS), MP_OBJ_NEW_SMALL_INT(UART_HWCONTROL_CTS) },
};
STATIC MP_DEFINE_CONST_DICT(pyb_uart_locals_dict, pyb_uart_locals_dict_table);
STATIC mp_uint_t pyb_uart_read(mp_obj_t self_in, void *buf_in, mp_uint_t size, int *errcode) {
pyb_uart_obj_t *self = self_in;
byte *buf = buf_in;
// check that size is a multiple of character width
if (size & self->char_width) {
*errcode = EIO;
return MP_STREAM_ERROR;
}
// convert byte size to char size
size >>= self->char_width;
// make sure we want at least 1 char
if (size == 0) {
return 0;
}
// wait for first char to become available
if (!uart_rx_wait(self, self->timeout)) {
// we can either return 0 to indicate EOF (then read() method returns b'')
// or return EAGAIN error to indicate non-blocking (then read() method returns None)
return 0;
}
// read the data
byte *orig_buf = buf;
for (;;) {
int data = uart_rx_char(self);
if (self->char_width == CHAR_WIDTH_9BIT) {
*(uint16_t*)buf = data;
buf += 2;
} else {
*buf++ = data;
}
if (--size == 0 || !uart_rx_wait(self, self->timeout_char)) {
// return number of bytes read
return buf - orig_buf;
}
}
}
STATIC mp_uint_t pyb_uart_write(mp_obj_t self_in, const void *buf_in, mp_uint_t size, int *errcode) {
pyb_uart_obj_t *self = self_in;
const byte *buf = buf_in;
// check that size is a multiple of character width
if (size & self->char_width) {
*errcode = EIO;
return MP_STREAM_ERROR;
}
// write the data
HAL_StatusTypeDef status = HAL_UART_Transmit(&self->uart, (uint8_t*)buf, size >> self->char_width, self->timeout);
if (status == HAL_OK) {
// return number of bytes written
return size;
} else {
*errcode = mp_hal_status_to_errno_table[status];
return MP_STREAM_ERROR;
}
}
STATIC mp_uint_t pyb_uart_ioctl(mp_obj_t self_in, mp_uint_t request, mp_uint_t arg, int *errcode) {
pyb_uart_obj_t *self = self_in;
mp_uint_t ret;
if (request == MP_IOCTL_POLL) {
mp_uint_t flags = arg;
ret = 0;
if ((flags & MP_IOCTL_POLL_RD) && uart_rx_any(self)) {
ret |= MP_IOCTL_POLL_RD;
}
if ((flags & MP_IOCTL_POLL_WR) && __HAL_UART_GET_FLAG(&self->uart, UART_FLAG_TXE)) {
ret |= MP_IOCTL_POLL_WR;
}
} else {
*errcode = EINVAL;
ret = MP_STREAM_ERROR;
}
return ret;
}
STATIC const mp_stream_p_t uart_stream_p = {
.read = pyb_uart_read,
.write = pyb_uart_write,
.ioctl = pyb_uart_ioctl,
.is_text = false,
};
const mp_obj_type_t pyb_uart_type = {
{ &mp_type_type },
.name = MP_QSTR_UART,
.print = pyb_uart_print,
.make_new = pyb_uart_make_new,
.getiter = mp_identity,
.iternext = mp_stream_unbuffered_iter,
.stream_p = &uart_stream_p,
.locals_dict = (mp_obj_t)&pyb_uart_locals_dict,
};
|
972593.c | /* $NetBSD: debug.c,v 1.3 2017/01/14 00:50:56 christos Exp $ */
/*-
* Copyright (c) 1993 The NetBSD Foundation, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include <sys/types.h>
#include <ctype.h>
#include <limits.h>
#include <regex.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <wchar.h>
#include <wctype.h>
/* Don't sort these! */
#include "utils.h"
#include "regex2.h"
#include "test_regex.h"
#ifdef __NetBSD__
static void s_print(struct re_guts *, FILE *);
static char *regchar(int);
/*
* regprint - print a regexp for debugging
*/
void
regprint(regex_t *r, FILE *d)
{
struct re_guts *g = r->re_g;
int c;
int last;
int nincat[NC];
fprintf(d, "%ld states, %zu categories", (long)g->nstates,
g->ncategories);
fprintf(d, ", first %ld last %ld", (long)g->firststate,
(long)g->laststate);
if (g->iflags&USEBOL)
fprintf(d, ", USEBOL");
if (g->iflags&USEEOL)
fprintf(d, ", USEEOL");
if (g->iflags&BAD)
fprintf(d, ", BAD");
if (g->nsub > 0)
fprintf(d, ", nsub=%ld", (long)g->nsub);
if (g->must != NULL)
fprintf(d, ", must(%ld) `%*s'", (long)g->mlen, (int)g->mlen,
g->must);
if (g->backrefs)
fprintf(d, ", backrefs");
if (g->nplus > 0)
fprintf(d, ", nplus %ld", (long)g->nplus);
fprintf(d, "\n");
s_print(g, d);
for (size_t i = 0; i < g->ncategories; i++) {
nincat[i] = 0;
for (c = CHAR_MIN; c <= CHAR_MAX; c++)
if (g->categories[c] == i)
nincat[i]++;
}
fprintf(d, "cc0#%d", nincat[0]);
for (size_t i = 1; i < g->ncategories; i++)
if (nincat[i] == 1) {
for (c = CHAR_MIN; c <= CHAR_MAX; c++)
if (g->categories[c] == i)
break;
fprintf(d, ", %zu=%s", i, regchar(c));
}
fprintf(d, "\n");
for (size_t i = 1; i < g->ncategories; i++)
if (nincat[i] != 1) {
fprintf(d, "cc%zu\t", i);
last = -1;
for (c = CHAR_MIN; c <= CHAR_MAX+1; c++) /* +1 does flush */
if (c <= CHAR_MAX && g->categories[c] == i) {
if (last < 0) {
fprintf(d, "%s", regchar(c));
last = c;
}
} else {
if (last >= 0) {
if (last != c-1)
fprintf(d, "-%s",
regchar(c-1));
last = -1;
}
}
fprintf(d, "\n");
}
}
/*
* s_print - print the strip for debugging
*/
static void
s_print(struct re_guts *g, FILE *d)
{
sop *s;
cset *cs;
int done = 0;
sop opnd;
int col = 0;
ssize_t last;
sopno offset = 2;
# define GAP() { if (offset % 5 == 0) { \
if (col > 40) { \
fprintf(d, "\n\t"); \
col = 0; \
} else { \
fprintf(d, " "); \
col++; \
} \
} else \
col++; \
offset++; \
}
if (OP(g->strip[0]) != OEND)
fprintf(d, "missing initial OEND!\n");
for (s = &g->strip[1]; !done; s++) {
opnd = OPND(*s);
switch (OP(*s)) {
case OEND:
fprintf(d, "\n");
done = 1;
break;
case OCHAR:
if (strchr("\\|()^$.[+*?{}!<> ", (char)opnd) != NULL)
fprintf(d, "\\%c", (char)opnd);
else
fprintf(d, "%s", regchar((char)opnd));
break;
case OBOL:
fprintf(d, "^");
break;
case OEOL:
fprintf(d, "$");
break;
case OBOW:
fprintf(d, "\\{");
break;
case OEOW:
fprintf(d, "\\}");
break;
case OANY:
fprintf(d, ".");
break;
case OANYOF:
fprintf(d, "[(%ld)", (long)opnd);
cs = &g->sets[opnd];
last = -1;
for (size_t i = 0; i < g->csetsize+1; i++) /* +1 flushes */
if (CHIN(cs, i) && i < g->csetsize) {
if (last < 0) {
fprintf(d, "%s", regchar(i));
last = i;
}
} else {
if (last >= 0) {
if (last != (ssize_t)i - 1)
fprintf(d, "-%s",
regchar(i - 1));
last = -1;
}
}
fprintf(d, "]");
break;
case OBACK_:
fprintf(d, "(\\<%ld>", (long)opnd);
break;
case O_BACK:
fprintf(d, "<%ld>\\)", (long)opnd);
break;
case OPLUS_:
fprintf(d, "(+");
if (OP(*(s+opnd)) != O_PLUS)
fprintf(d, "<%ld>", (long)opnd);
break;
case O_PLUS:
if (OP(*(s-opnd)) != OPLUS_)
fprintf(d, "<%ld>", (long)opnd);
fprintf(d, "+)");
break;
case OQUEST_:
fprintf(d, "(?");
if (OP(*(s+opnd)) != O_QUEST)
fprintf(d, "<%ld>", (long)opnd);
break;
case O_QUEST:
if (OP(*(s-opnd)) != OQUEST_)
fprintf(d, "<%ld>", (long)opnd);
fprintf(d, "?)");
break;
case OLPAREN:
fprintf(d, "((<%ld>", (long)opnd);
break;
case ORPAREN:
fprintf(d, "<%ld>))", (long)opnd);
break;
case OCH_:
fprintf(d, "<");
if (OP(*(s+opnd)) != OOR2)
fprintf(d, "<%ld>", (long)opnd);
break;
case OOR1:
if (OP(*(s-opnd)) != OOR1 && OP(*(s-opnd)) != OCH_)
fprintf(d, "<%ld>", (long)opnd);
fprintf(d, "|");
break;
case OOR2:
fprintf(d, "|");
if (OP(*(s+opnd)) != OOR2 && OP(*(s+opnd)) != O_CH)
fprintf(d, "<%ld>", (long)opnd);
break;
case O_CH:
if (OP(*(s-opnd)) != OOR1)
fprintf(d, "<%ld>", (long)opnd);
fprintf(d, ">");
break;
default:
fprintf(d, "!%d(%d)!", OP(*s), opnd);
break;
}
if (!done)
GAP();
}
}
/*
* regchar - make a character printable
*/
static char * /* -> representation */
regchar(int ch)
{
static char buf[10];
if (isprint(ch) || ch == ' ')
sprintf(buf, "%c", ch);
else
sprintf(buf, "\\%o", ch);
return(buf);
}
#else
void
regprint(regex_t *r, FILE *d)
{
}
#endif
|
646577.c | /*-------------------------------------------------------------------------
*
* tstoreReceiver.c
* An implementation of DestReceiver that stores the result tuples in
* a Tuplestore.
*
* Optionally, we can force detoasting (but not decompression) of out-of-line
* toasted values. This is to support cursors WITH HOLD, which must retain
* data even if the underlying table is dropped.
*
*
* Portions Copyright (c) 1996-2016, PostgreSQL Global Development Group
* Portions Copyright (c) 1994, Regents of the University of California
*
* IDENTIFICATION
* src/backend/executor/tstoreReceiver.c
*
*-------------------------------------------------------------------------
*/
#include "postgres.h"
#include "access/heapam.h"
#include "access/tuptoaster.h"
#include "executor/tstoreReceiver.h"
typedef struct
{
DestReceiver pub;
/* parameters: */
Tuplestorestate *tstore; /* where to put the data */
MemoryContext cxt; /* context containing tstore */
bool detoast; /* were we told to detoast? */
/* workspace: */
Datum *outvalues; /* values array for result tuple */
Datum *tofree; /* temp values to be pfree'd */
} TStoreState;
static bool tstoreReceiveSlot_notoast(TupleTableSlot *slot, DestReceiver *self);
static bool tstoreReceiveSlot_detoast(TupleTableSlot *slot, DestReceiver *self);
/*
* Prepare to receive tuples from executor.
*/
static void
tstoreStartupReceiver(DestReceiver *self, int operation, TupleDesc typeinfo)
{
TStoreState *myState = (TStoreState *) self;
bool needtoast = false;
Form_pg_attribute *attrs = typeinfo->attrs;
int natts = typeinfo->natts;
int i;
/* Check if any columns require detoast work */
if (myState->detoast)
{
for (i = 0; i < natts; i++)
{
if (attrs[i]->attisdropped)
continue;
if (attrs[i]->attlen == -1)
{
needtoast = true;
break;
}
}
}
/* Set up appropriate callback */
if (needtoast)
{
myState->pub.receiveSlot = tstoreReceiveSlot_detoast;
/* Create workspace */
myState->outvalues = (Datum *)
MemoryContextAlloc(myState->cxt, natts * sizeof(Datum));
myState->tofree = (Datum *)
MemoryContextAlloc(myState->cxt, natts * sizeof(Datum));
}
else
{
myState->pub.receiveSlot = tstoreReceiveSlot_notoast;
myState->outvalues = NULL;
myState->tofree = NULL;
}
}
/*
* Receive a tuple from the executor and store it in the tuplestore.
* This is for the easy case where we don't have to detoast.
*/
static bool
tstoreReceiveSlot_notoast(TupleTableSlot *slot, DestReceiver *self)
{
TStoreState *myState = (TStoreState *) self;
tuplestore_puttupleslot(myState->tstore, slot);
return true;
}
/*
* Receive a tuple from the executor and store it in the tuplestore.
* This is for the case where we have to detoast any toasted values.
*/
static bool
tstoreReceiveSlot_detoast(TupleTableSlot *slot, DestReceiver *self)
{
TStoreState *myState = (TStoreState *) self;
TupleDesc typeinfo = slot->tts_tupleDescriptor;
Form_pg_attribute *attrs = typeinfo->attrs;
int natts = typeinfo->natts;
int nfree;
int i;
MemoryContext oldcxt;
/* Make sure the tuple is fully deconstructed */
slot_getallattrs(slot);
/*
* Fetch back any out-of-line datums. We build the new datums array in
* myState->outvalues[] (but we can re-use the slot's isnull array). Also,
* remember the fetched values to free afterwards.
*/
nfree = 0;
for (i = 0; i < natts; i++)
{
Datum val = slot_get_values(slot)[i];
if (!attrs[i]->attisdropped &&
attrs[i]->attlen == -1 &&
!slot_get_isnull(slot)[i])
{
if (VARATT_IS_EXTERNAL(DatumGetPointer(val)))
{
val = PointerGetDatum(heap_tuple_fetch_attr((struct varlena *)
DatumGetPointer(val)));
myState->tofree[nfree++] = val;
}
}
myState->outvalues[i] = val;
}
/*
* Push the modified tuple into the tuplestore.
*/
oldcxt = MemoryContextSwitchTo(myState->cxt);
tuplestore_putvalues(myState->tstore, typeinfo,
myState->outvalues, slot_get_isnull(slot));
MemoryContextSwitchTo(oldcxt);
/* And release any temporary detoasted values */
for (i = 0; i < nfree; i++)
pfree(DatumGetPointer(myState->tofree[i]));
return true;
}
/*
* Clean up at end of an executor run
*/
static void
tstoreShutdownReceiver(DestReceiver *self)
{
TStoreState *myState = (TStoreState *) self;
/* Release workspace if any */
if (myState->outvalues)
pfree(myState->outvalues);
myState->outvalues = NULL;
if (myState->tofree)
pfree(myState->tofree);
myState->tofree = NULL;
}
/*
* Destroy receiver when done with it
*/
static void
tstoreDestroyReceiver(DestReceiver *self)
{
pfree(self);
}
/*
* Initially create a DestReceiver object.
*/
DestReceiver *
CreateTuplestoreDestReceiver(void)
{
TStoreState *self = (TStoreState *) palloc0(sizeof(TStoreState));
self->pub.receiveSlot = tstoreReceiveSlot_notoast; /* might change */
self->pub.rStartup = tstoreStartupReceiver;
self->pub.rShutdown = tstoreShutdownReceiver;
self->pub.rDestroy = tstoreDestroyReceiver;
self->pub.mydest = DestTuplestore;
/* private fields will be set by SetTuplestoreDestReceiverParams */
return (DestReceiver *) self;
}
/*
* Set parameters for a TuplestoreDestReceiver
*/
void
SetTuplestoreDestReceiverParams(DestReceiver *self,
Tuplestorestate *tStore,
MemoryContext tContext,
bool detoast)
{
TStoreState *myState = (TStoreState *) self;
Assert(myState->pub.mydest == DestTuplestore);
myState->tstore = tStore;
myState->cxt = tContext;
myState->detoast = detoast;
}
|
788702.c | // SPDX-License-Identifier: GPL-2.0 OR Linux-OpenIB
// Copyright (c) 2020 Mellanox Technologies.
#include <linux/mlx5/driver.h>
#include <linux/mlx5/mlx5_ifc.h>
#include <linux/mlx5/fs.h>
#include "lib/fs_chains.h"
#include "fs_ft_pool.h"
#include "en/mapping.h"
#include "fs_core.h"
#include "en_tc.h"
#define chains_lock(chains) ((chains)->lock)
#define chains_ht(chains) ((chains)->chains_ht)
#define prios_ht(chains) ((chains)->prios_ht)
#define tc_default_ft(chains) ((chains)->tc_default_ft)
#define tc_end_ft(chains) ((chains)->tc_end_ft)
#define ns_to_chains_fs_prio(ns) ((ns) == MLX5_FLOW_NAMESPACE_FDB ? \
FDB_TC_OFFLOAD : MLX5E_TC_PRIO)
#define FT_TBL_SZ (64 * 1024)
struct mlx5_fs_chains {
struct mlx5_core_dev *dev;
struct rhashtable chains_ht;
struct rhashtable prios_ht;
/* Protects above chains_ht and prios_ht */
struct mutex lock;
struct mlx5_flow_table *tc_default_ft;
struct mlx5_flow_table *tc_end_ft;
struct mapping_ctx *chains_mapping;
enum mlx5_flow_namespace_type ns;
u32 group_num;
u32 flags;
};
struct fs_chain {
struct rhash_head node;
u32 chain;
int ref;
int id;
struct mlx5_fs_chains *chains;
struct list_head prios_list;
struct mlx5_flow_handle *restore_rule;
struct mlx5_modify_hdr *miss_modify_hdr;
};
struct prio_key {
u32 chain;
u32 prio;
u32 level;
};
struct prio {
struct rhash_head node;
struct list_head list;
struct prio_key key;
int ref;
struct fs_chain *chain;
struct mlx5_flow_table *ft;
struct mlx5_flow_table *next_ft;
struct mlx5_flow_group *miss_group;
struct mlx5_flow_handle *miss_rule;
};
static const struct rhashtable_params chain_params = {
.head_offset = offsetof(struct fs_chain, node),
.key_offset = offsetof(struct fs_chain, chain),
.key_len = sizeof_field(struct fs_chain, chain),
.automatic_shrinking = true,
};
static const struct rhashtable_params prio_params = {
.head_offset = offsetof(struct prio, node),
.key_offset = offsetof(struct prio, key),
.key_len = sizeof_field(struct prio, key),
.automatic_shrinking = true,
};
bool mlx5_chains_prios_supported(struct mlx5_fs_chains *chains)
{
return chains->flags & MLX5_CHAINS_AND_PRIOS_SUPPORTED;
}
bool mlx5_chains_ignore_flow_level_supported(struct mlx5_fs_chains *chains)
{
return chains->flags & MLX5_CHAINS_IGNORE_FLOW_LEVEL_SUPPORTED;
}
bool mlx5_chains_backwards_supported(struct mlx5_fs_chains *chains)
{
return mlx5_chains_prios_supported(chains) &&
mlx5_chains_ignore_flow_level_supported(chains);
}
u32 mlx5_chains_get_chain_range(struct mlx5_fs_chains *chains)
{
if (!mlx5_chains_prios_supported(chains))
return 1;
if (mlx5_chains_ignore_flow_level_supported(chains))
return UINT_MAX - 1;
/* We should get here only for eswitch case */
return FDB_TC_MAX_CHAIN;
}
u32 mlx5_chains_get_nf_ft_chain(struct mlx5_fs_chains *chains)
{
return mlx5_chains_get_chain_range(chains) + 1;
}
u32 mlx5_chains_get_prio_range(struct mlx5_fs_chains *chains)
{
if (mlx5_chains_ignore_flow_level_supported(chains))
return UINT_MAX;
if (!chains->dev->priv.eswitch ||
chains->dev->priv.eswitch->mode != MLX5_ESWITCH_OFFLOADS)
return 1;
/* We should get here only for eswitch case */
return FDB_TC_MAX_PRIO;
}
static unsigned int mlx5_chains_get_level_range(struct mlx5_fs_chains *chains)
{
if (mlx5_chains_ignore_flow_level_supported(chains))
return UINT_MAX;
/* Same value for FDB and NIC RX tables */
return FDB_TC_LEVELS_PER_PRIO;
}
void
mlx5_chains_set_end_ft(struct mlx5_fs_chains *chains,
struct mlx5_flow_table *ft)
{
tc_end_ft(chains) = ft;
}
static struct mlx5_flow_table *
mlx5_chains_create_table(struct mlx5_fs_chains *chains,
u32 chain, u32 prio, u32 level)
{
struct mlx5_flow_table_attr ft_attr = {};
struct mlx5_flow_namespace *ns;
struct mlx5_flow_table *ft;
int sz;
if (chains->flags & MLX5_CHAINS_FT_TUNNEL_SUPPORTED)
ft_attr.flags |= (MLX5_FLOW_TABLE_TUNNEL_EN_REFORMAT |
MLX5_FLOW_TABLE_TUNNEL_EN_DECAP);
sz = (chain == mlx5_chains_get_nf_ft_chain(chains)) ? FT_TBL_SZ : POOL_NEXT_SIZE;
ft_attr.max_fte = sz;
/* We use tc_default_ft(chains) as the table's next_ft till
* ignore_flow_level is allowed on FT creation and not just for FTEs.
* Instead caller should add an explicit miss rule if needed.
*/
ft_attr.next_ft = tc_default_ft(chains);
/* The root table(chain 0, prio 1, level 0) is required to be
* connected to the previous fs_core managed prio.
* We always create it, as a managed table, in order to align with
* fs_core logic.
*/
if (!mlx5_chains_ignore_flow_level_supported(chains) ||
(chain == 0 && prio == 1 && level == 0)) {
ft_attr.level = level;
ft_attr.prio = prio - 1;
ns = (chains->ns == MLX5_FLOW_NAMESPACE_FDB) ?
mlx5_get_fdb_sub_ns(chains->dev, chain) :
mlx5_get_flow_namespace(chains->dev, chains->ns);
} else {
ft_attr.flags |= MLX5_FLOW_TABLE_UNMANAGED;
ft_attr.prio = ns_to_chains_fs_prio(chains->ns);
/* Firmware doesn't allow us to create another level 0 table,
* so we create all unmanaged tables as level 1.
*
* To connect them, we use explicit miss rules with
* ignore_flow_level. Caller is responsible to create
* these rules (if needed).
*/
ft_attr.level = 1;
ns = mlx5_get_flow_namespace(chains->dev, chains->ns);
}
ft_attr.autogroup.num_reserved_entries = 2;
ft_attr.autogroup.max_num_groups = chains->group_num;
ft = mlx5_create_auto_grouped_flow_table(ns, &ft_attr);
if (IS_ERR(ft)) {
mlx5_core_warn(chains->dev, "Failed to create chains table err %d (chain: %d, prio: %d, level: %d, size: %d)\n",
(int)PTR_ERR(ft), chain, prio, level, sz);
return ft;
}
return ft;
}
static int
create_chain_restore(struct fs_chain *chain)
{
struct mlx5_eswitch *esw = chain->chains->dev->priv.eswitch;
u8 modact[MLX5_UN_SZ_BYTES(set_add_copy_action_in_auto)] = {};
struct mlx5_fs_chains *chains = chain->chains;
enum mlx5e_tc_attr_to_reg chain_to_reg;
struct mlx5_modify_hdr *mod_hdr;
u32 index;
int err;
if (chain->chain == mlx5_chains_get_nf_ft_chain(chains) ||
!mlx5_chains_prios_supported(chains))
return 0;
err = mlx5_chains_get_chain_mapping(chains, chain->chain, &index);
if (err)
return err;
if (index == MLX5_FS_DEFAULT_FLOW_TAG) {
/* we got the special default flow tag id, so we won't know
* if we actually marked the packet with the restore rule
* we create.
*
* This case isn't possible with MLX5_FS_DEFAULT_FLOW_TAG = 0.
*/
err = mlx5_chains_get_chain_mapping(chains, chain->chain, &index);
mapping_remove(chains->chains_mapping, MLX5_FS_DEFAULT_FLOW_TAG);
if (err)
return err;
}
chain->id = index;
if (chains->ns == MLX5_FLOW_NAMESPACE_FDB) {
chain_to_reg = CHAIN_TO_REG;
chain->restore_rule = esw_add_restore_rule(esw, chain->id);
if (IS_ERR(chain->restore_rule)) {
err = PTR_ERR(chain->restore_rule);
goto err_rule;
}
} else if (chains->ns == MLX5_FLOW_NAMESPACE_KERNEL) {
/* For NIC RX we don't need a restore rule
* since we write the metadata to reg_b
* that is passed to SW directly.
*/
chain_to_reg = NIC_CHAIN_TO_REG;
} else {
err = -EINVAL;
goto err_rule;
}
MLX5_SET(set_action_in, modact, action_type, MLX5_ACTION_TYPE_SET);
MLX5_SET(set_action_in, modact, field,
mlx5e_tc_attr_to_reg_mappings[chain_to_reg].mfield);
MLX5_SET(set_action_in, modact, offset,
mlx5e_tc_attr_to_reg_mappings[chain_to_reg].moffset);
MLX5_SET(set_action_in, modact, length,
mlx5e_tc_attr_to_reg_mappings[chain_to_reg].mlen == 32 ?
0 : mlx5e_tc_attr_to_reg_mappings[chain_to_reg].mlen);
MLX5_SET(set_action_in, modact, data, chain->id);
mod_hdr = mlx5_modify_header_alloc(chains->dev, chains->ns,
1, modact);
if (IS_ERR(mod_hdr)) {
err = PTR_ERR(mod_hdr);
goto err_mod_hdr;
}
chain->miss_modify_hdr = mod_hdr;
return 0;
err_mod_hdr:
if (!IS_ERR_OR_NULL(chain->restore_rule))
mlx5_del_flow_rules(chain->restore_rule);
err_rule:
/* Datapath can't find this mapping, so we can safely remove it */
mapping_remove(chains->chains_mapping, chain->id);
return err;
}
static void destroy_chain_restore(struct fs_chain *chain)
{
struct mlx5_fs_chains *chains = chain->chains;
if (!chain->miss_modify_hdr)
return;
if (chain->restore_rule)
mlx5_del_flow_rules(chain->restore_rule);
mlx5_modify_header_dealloc(chains->dev, chain->miss_modify_hdr);
mapping_remove(chains->chains_mapping, chain->id);
}
static struct fs_chain *
mlx5_chains_create_chain(struct mlx5_fs_chains *chains, u32 chain)
{
struct fs_chain *chain_s = NULL;
int err;
chain_s = kvzalloc(sizeof(*chain_s), GFP_KERNEL);
if (!chain_s)
return ERR_PTR(-ENOMEM);
chain_s->chains = chains;
chain_s->chain = chain;
INIT_LIST_HEAD(&chain_s->prios_list);
err = create_chain_restore(chain_s);
if (err)
goto err_restore;
err = rhashtable_insert_fast(&chains_ht(chains), &chain_s->node,
chain_params);
if (err)
goto err_insert;
return chain_s;
err_insert:
destroy_chain_restore(chain_s);
err_restore:
kvfree(chain_s);
return ERR_PTR(err);
}
static void
mlx5_chains_destroy_chain(struct fs_chain *chain)
{
struct mlx5_fs_chains *chains = chain->chains;
rhashtable_remove_fast(&chains_ht(chains), &chain->node,
chain_params);
destroy_chain_restore(chain);
kvfree(chain);
}
static struct fs_chain *
mlx5_chains_get_chain(struct mlx5_fs_chains *chains, u32 chain)
{
struct fs_chain *chain_s;
chain_s = rhashtable_lookup_fast(&chains_ht(chains), &chain,
chain_params);
if (!chain_s) {
chain_s = mlx5_chains_create_chain(chains, chain);
if (IS_ERR(chain_s))
return chain_s;
}
chain_s->ref++;
return chain_s;
}
static struct mlx5_flow_handle *
mlx5_chains_add_miss_rule(struct fs_chain *chain,
struct mlx5_flow_table *ft,
struct mlx5_flow_table *next_ft)
{
struct mlx5_fs_chains *chains = chain->chains;
struct mlx5_flow_destination dest = {};
struct mlx5_flow_act act = {};
act.flags = FLOW_ACT_NO_APPEND;
if (mlx5_chains_ignore_flow_level_supported(chain->chains))
act.flags |= FLOW_ACT_IGNORE_FLOW_LEVEL;
act.action = MLX5_FLOW_CONTEXT_ACTION_FWD_DEST;
dest.type = MLX5_FLOW_DESTINATION_TYPE_FLOW_TABLE;
dest.ft = next_ft;
if (next_ft == tc_end_ft(chains) &&
chain->chain != mlx5_chains_get_nf_ft_chain(chains) &&
mlx5_chains_prios_supported(chains)) {
act.modify_hdr = chain->miss_modify_hdr;
act.action |= MLX5_FLOW_CONTEXT_ACTION_MOD_HDR;
}
return mlx5_add_flow_rules(ft, NULL, &act, &dest, 1);
}
static int
mlx5_chains_update_prio_prevs(struct prio *prio,
struct mlx5_flow_table *next_ft)
{
struct mlx5_flow_handle *miss_rules[FDB_TC_LEVELS_PER_PRIO + 1] = {};
struct fs_chain *chain = prio->chain;
struct prio *pos;
int n = 0, err;
if (prio->key.level)
return 0;
/* Iterate in reverse order until reaching the level 0 rule of
* the previous priority, adding all the miss rules first, so we can
* revert them if any of them fails.
*/
pos = prio;
list_for_each_entry_continue_reverse(pos,
&chain->prios_list,
list) {
miss_rules[n] = mlx5_chains_add_miss_rule(chain,
pos->ft,
next_ft);
if (IS_ERR(miss_rules[n])) {
err = PTR_ERR(miss_rules[n]);
goto err_prev_rule;
}
n++;
if (!pos->key.level)
break;
}
/* Success, delete old miss rules, and update the pointers. */
n = 0;
pos = prio;
list_for_each_entry_continue_reverse(pos,
&chain->prios_list,
list) {
mlx5_del_flow_rules(pos->miss_rule);
pos->miss_rule = miss_rules[n];
pos->next_ft = next_ft;
n++;
if (!pos->key.level)
break;
}
return 0;
err_prev_rule:
while (--n >= 0)
mlx5_del_flow_rules(miss_rules[n]);
return err;
}
static void
mlx5_chains_put_chain(struct fs_chain *chain)
{
if (--chain->ref == 0)
mlx5_chains_destroy_chain(chain);
}
static struct prio *
mlx5_chains_create_prio(struct mlx5_fs_chains *chains,
u32 chain, u32 prio, u32 level)
{
int inlen = MLX5_ST_SZ_BYTES(create_flow_group_in);
struct mlx5_flow_handle *miss_rule;
struct mlx5_flow_group *miss_group;
struct mlx5_flow_table *next_ft;
struct mlx5_flow_table *ft;
struct fs_chain *chain_s;
struct list_head *pos;
struct prio *prio_s;
u32 *flow_group_in;
int err;
chain_s = mlx5_chains_get_chain(chains, chain);
if (IS_ERR(chain_s))
return ERR_CAST(chain_s);
prio_s = kvzalloc(sizeof(*prio_s), GFP_KERNEL);
flow_group_in = kvzalloc(inlen, GFP_KERNEL);
if (!prio_s || !flow_group_in) {
err = -ENOMEM;
goto err_alloc;
}
/* Chain's prio list is sorted by prio and level.
* And all levels of some prio point to the next prio's level 0.
* Example list (prio, level):
* (3,0)->(3,1)->(5,0)->(5,1)->(6,1)->(7,0)
* In hardware, we will we have the following pointers:
* (3,0) -> (5,0) -> (7,0) -> Slow path
* (3,1) -> (5,0)
* (5,1) -> (7,0)
* (6,1) -> (7,0)
*/
/* Default miss for each chain: */
next_ft = (chain == mlx5_chains_get_nf_ft_chain(chains)) ?
tc_default_ft(chains) :
tc_end_ft(chains);
list_for_each(pos, &chain_s->prios_list) {
struct prio *p = list_entry(pos, struct prio, list);
/* exit on first pos that is larger */
if (prio < p->key.prio || (prio == p->key.prio &&
level < p->key.level)) {
/* Get next level 0 table */
next_ft = p->key.level == 0 ? p->ft : p->next_ft;
break;
}
}
ft = mlx5_chains_create_table(chains, chain, prio, level);
if (IS_ERR(ft)) {
err = PTR_ERR(ft);
goto err_create;
}
MLX5_SET(create_flow_group_in, flow_group_in, start_flow_index,
ft->max_fte - 2);
MLX5_SET(create_flow_group_in, flow_group_in, end_flow_index,
ft->max_fte - 1);
miss_group = mlx5_create_flow_group(ft, flow_group_in);
if (IS_ERR(miss_group)) {
err = PTR_ERR(miss_group);
goto err_group;
}
/* Add miss rule to next_ft */
miss_rule = mlx5_chains_add_miss_rule(chain_s, ft, next_ft);
if (IS_ERR(miss_rule)) {
err = PTR_ERR(miss_rule);
goto err_miss_rule;
}
prio_s->miss_group = miss_group;
prio_s->miss_rule = miss_rule;
prio_s->next_ft = next_ft;
prio_s->chain = chain_s;
prio_s->key.chain = chain;
prio_s->key.prio = prio;
prio_s->key.level = level;
prio_s->ft = ft;
err = rhashtable_insert_fast(&prios_ht(chains), &prio_s->node,
prio_params);
if (err)
goto err_insert;
list_add(&prio_s->list, pos->prev);
/* Table is ready, connect it */
err = mlx5_chains_update_prio_prevs(prio_s, ft);
if (err)
goto err_update;
kvfree(flow_group_in);
return prio_s;
err_update:
list_del(&prio_s->list);
rhashtable_remove_fast(&prios_ht(chains), &prio_s->node,
prio_params);
err_insert:
mlx5_del_flow_rules(miss_rule);
err_miss_rule:
mlx5_destroy_flow_group(miss_group);
err_group:
mlx5_destroy_flow_table(ft);
err_create:
err_alloc:
kvfree(prio_s);
kvfree(flow_group_in);
mlx5_chains_put_chain(chain_s);
return ERR_PTR(err);
}
static void
mlx5_chains_destroy_prio(struct mlx5_fs_chains *chains,
struct prio *prio)
{
struct fs_chain *chain = prio->chain;
WARN_ON(mlx5_chains_update_prio_prevs(prio,
prio->next_ft));
list_del(&prio->list);
rhashtable_remove_fast(&prios_ht(chains), &prio->node,
prio_params);
mlx5_del_flow_rules(prio->miss_rule);
mlx5_destroy_flow_group(prio->miss_group);
mlx5_destroy_flow_table(prio->ft);
mlx5_chains_put_chain(chain);
kvfree(prio);
}
struct mlx5_flow_table *
mlx5_chains_get_table(struct mlx5_fs_chains *chains, u32 chain, u32 prio,
u32 level)
{
struct mlx5_flow_table *prev_fts;
struct prio *prio_s;
struct prio_key key;
int l = 0;
if ((chain > mlx5_chains_get_chain_range(chains) &&
chain != mlx5_chains_get_nf_ft_chain(chains)) ||
prio > mlx5_chains_get_prio_range(chains) ||
level > mlx5_chains_get_level_range(chains))
return ERR_PTR(-EOPNOTSUPP);
/* create earlier levels for correct fs_core lookup when
* connecting tables.
*/
for (l = 0; l < level; l++) {
prev_fts = mlx5_chains_get_table(chains, chain, prio, l);
if (IS_ERR(prev_fts)) {
prio_s = ERR_CAST(prev_fts);
goto err_get_prevs;
}
}
key.chain = chain;
key.prio = prio;
key.level = level;
mutex_lock(&chains_lock(chains));
prio_s = rhashtable_lookup_fast(&prios_ht(chains), &key,
prio_params);
if (!prio_s) {
prio_s = mlx5_chains_create_prio(chains, chain,
prio, level);
if (IS_ERR(prio_s))
goto err_create_prio;
}
++prio_s->ref;
mutex_unlock(&chains_lock(chains));
return prio_s->ft;
err_create_prio:
mutex_unlock(&chains_lock(chains));
err_get_prevs:
while (--l >= 0)
mlx5_chains_put_table(chains, chain, prio, l);
return ERR_CAST(prio_s);
}
void
mlx5_chains_put_table(struct mlx5_fs_chains *chains, u32 chain, u32 prio,
u32 level)
{
struct prio *prio_s;
struct prio_key key;
key.chain = chain;
key.prio = prio;
key.level = level;
mutex_lock(&chains_lock(chains));
prio_s = rhashtable_lookup_fast(&prios_ht(chains), &key,
prio_params);
if (!prio_s)
goto err_get_prio;
if (--prio_s->ref == 0)
mlx5_chains_destroy_prio(chains, prio_s);
mutex_unlock(&chains_lock(chains));
while (level-- > 0)
mlx5_chains_put_table(chains, chain, prio, level);
return;
err_get_prio:
mutex_unlock(&chains_lock(chains));
WARN_ONCE(1,
"Couldn't find table: (chain: %d prio: %d level: %d)",
chain, prio, level);
}
struct mlx5_flow_table *
mlx5_chains_get_tc_end_ft(struct mlx5_fs_chains *chains)
{
return tc_end_ft(chains);
}
struct mlx5_flow_table *
mlx5_chains_create_global_table(struct mlx5_fs_chains *chains)
{
u32 chain, prio, level;
int err;
if (!mlx5_chains_ignore_flow_level_supported(chains)) {
err = -EOPNOTSUPP;
mlx5_core_warn(chains->dev,
"Couldn't create global flow table, ignore_flow_level not supported.");
goto err_ignore;
}
chain = mlx5_chains_get_chain_range(chains),
prio = mlx5_chains_get_prio_range(chains);
level = mlx5_chains_get_level_range(chains);
return mlx5_chains_create_table(chains, chain, prio, level);
err_ignore:
return ERR_PTR(err);
}
void
mlx5_chains_destroy_global_table(struct mlx5_fs_chains *chains,
struct mlx5_flow_table *ft)
{
mlx5_destroy_flow_table(ft);
}
static struct mlx5_fs_chains *
mlx5_chains_init(struct mlx5_core_dev *dev, struct mlx5_chains_attr *attr)
{
struct mlx5_fs_chains *chains_priv;
u32 max_flow_counter;
int err;
chains_priv = kzalloc(sizeof(*chains_priv), GFP_KERNEL);
if (!chains_priv)
return ERR_PTR(-ENOMEM);
max_flow_counter = (MLX5_CAP_GEN(dev, max_flow_counter_31_16) << 16) |
MLX5_CAP_GEN(dev, max_flow_counter_15_0);
mlx5_core_dbg(dev,
"Init flow table chains, max counters(%d), groups(%d), max flow table size(%d)\n",
max_flow_counter, attr->max_grp_num, attr->max_ft_sz);
chains_priv->dev = dev;
chains_priv->flags = attr->flags;
chains_priv->ns = attr->ns;
chains_priv->group_num = attr->max_grp_num;
chains_priv->chains_mapping = attr->mapping;
tc_default_ft(chains_priv) = tc_end_ft(chains_priv) = attr->default_ft;
mlx5_core_info(dev, "Supported tc offload range - chains: %u, prios: %u\n",
mlx5_chains_get_chain_range(chains_priv),
mlx5_chains_get_prio_range(chains_priv));
err = rhashtable_init(&chains_ht(chains_priv), &chain_params);
if (err)
goto init_chains_ht_err;
err = rhashtable_init(&prios_ht(chains_priv), &prio_params);
if (err)
goto init_prios_ht_err;
mutex_init(&chains_lock(chains_priv));
return chains_priv;
init_prios_ht_err:
rhashtable_destroy(&chains_ht(chains_priv));
init_chains_ht_err:
kfree(chains_priv);
return ERR_PTR(err);
}
static void
mlx5_chains_cleanup(struct mlx5_fs_chains *chains)
{
mutex_destroy(&chains_lock(chains));
rhashtable_destroy(&prios_ht(chains));
rhashtable_destroy(&chains_ht(chains));
kfree(chains);
}
struct mlx5_fs_chains *
mlx5_chains_create(struct mlx5_core_dev *dev, struct mlx5_chains_attr *attr)
{
struct mlx5_fs_chains *chains;
chains = mlx5_chains_init(dev, attr);
return chains;
}
void
mlx5_chains_destroy(struct mlx5_fs_chains *chains)
{
mlx5_chains_cleanup(chains);
}
int
mlx5_chains_get_chain_mapping(struct mlx5_fs_chains *chains, u32 chain,
u32 *chain_mapping)
{
struct mapping_ctx *ctx = chains->chains_mapping;
struct mlx5_mapped_obj mapped_obj = {};
mapped_obj.type = MLX5_MAPPED_OBJ_CHAIN;
mapped_obj.chain = chain;
return mapping_add(ctx, &mapped_obj, chain_mapping);
}
int
mlx5_chains_put_chain_mapping(struct mlx5_fs_chains *chains, u32 chain_mapping)
{
struct mapping_ctx *ctx = chains->chains_mapping;
return mapping_remove(ctx, chain_mapping);
}
|
226495.c | #include <ccan/ccan/opt/opt.h>
#include <ccan/tal/str/str.h>
#include <common/json_command.h>
#include <common/json_helpers.h>
#include <common/jsonrpc_errors.h>
#include <common/wallet_tx.h>
#include <inttypes.h>
#include <wallet/wallet.h>
void wtx_init(struct command *cmd, struct wallet_tx *wtx, struct amount_sat max)
{
wtx->cmd = cmd;
wtx->amount = max;
}
struct command_result *param_wtx(struct command *cmd,
const char *name,
const char *buffer,
const jsmntok_t *tok,
struct wallet_tx *wtx)
{
struct amount_sat max = wtx->amount;
if (json_tok_streq(buffer, tok, "all")) {
wtx->all_funds = true;
return NULL;
}
wtx->all_funds = false;
if (!parse_amount_sat(&wtx->amount,
buffer + tok->start, tok->end - tok->start))
return command_fail(cmd, JSONRPC2_INVALID_PARAMS,
"'%s' should be an amount in satoshis or all, not '%.*s'",
name,
tok->end - tok->start,
buffer + tok->start);
if (amount_sat_greater(wtx->amount, max))
return command_fail(wtx->cmd, FUND_MAX_EXCEEDED,
"Amount exceeded %s",
type_to_string(tmpctx, struct amount_sat,
&max));
return NULL;
}
struct command_result *param_utxos(struct command *cmd,
const char *name,
const char *buffer,
const jsmntok_t *tok,
const struct utxo ***utxos)
{
size_t i;
const jsmntok_t *curr;
struct zcore_txid **txids = tal_arr(cmd, struct zcore_txid*, 0);
unsigned int **outnums = tal_arr(cmd, unsigned int*, 0);
json_for_each_arr(i, curr, tok) {
jsmntok_t txid_tok, outnum_tok;
if (!split_tok(buffer, curr, ':', &txid_tok, &outnum_tok))
return command_fail(cmd, JSONRPC2_INVALID_PARAMS,
"Could not decode the outpoint from \"%s\""
" The utxos should be specified as"
" 'txid:output_index'.",
json_strdup(tmpctx, buffer, curr));
struct zcore_txid *txid = tal(txids, struct zcore_txid);
unsigned int *outnum = tal(txids, unsigned int);
if (!json_to_txid(buffer, (const jsmntok_t*)&txid_tok, txid)) {
return command_fail(cmd, JSONRPC2_INVALID_PARAMS,
"Could not get a txid out of \"%s\"",
json_strdup(tmpctx, buffer, &txid_tok));
}
if(!json_to_number(buffer, (const jsmntok_t*)&outnum_tok, outnum))
return command_fail(cmd, JSONRPC2_INVALID_PARAMS,
"Could not get a vout out of \"%s\"",
json_strdup(tmpctx, buffer, &outnum_tok));
tal_arr_expand(&txids, txid);
tal_arr_expand(&outnums, outnum);
}
if (!tal_count(txids) || !tal_count(outnums))
return command_fail(cmd, JSONRPC2_INVALID_PARAMS,
"Please specify an array of 'txid:output_index',"
" not \"%.*s\"",
tok->end - tok->start,
buffer + tok->start);
*utxos = wallet_select_specific(cmd, cmd->ld->wallet, txids, outnums);
tal_free(txids);
tal_free(outnums);
if (!*utxos)
return command_fail(cmd, JSONRPC2_INVALID_PARAMS,
"Could not decode all of the outpoints. The utxos"
" should be specified as an array of "
" 'txid:output_index'.");
if (tal_count(*utxos) == 0)
return command_fail(cmd, JSONRPC2_INVALID_PARAMS,
"No matching utxo was found from the wallet. "
"You can get a list of the wallet utxos with"
" the `listfunds` RPC call.");
return NULL;
}
static struct command_result *check_amount(const struct wallet_tx *wtx,
struct amount_sat amount)
{
if (tal_count(wtx->utxos) == 0) {
/* Since it's possible the lack of utxos is because we haven't finished
* syncing yet, report a sync timing error first */
if (!topology_synced(wtx->cmd->ld->topology))
return command_fail(wtx->cmd, FUNDING_STILL_SYNCING_ZCORE,
"Still syncing with zcore network");
return command_fail(wtx->cmd, FUND_CANNOT_AFFORD,
"Cannot afford transaction");
}
if (amount_sat_less(amount, get_chainparams(wtx->cmd->ld)->dust_limit)) {
return command_fail(wtx->cmd, FUND_OUTPUT_IS_DUST,
"Output %s would be dust",
type_to_string(tmpctx, struct amount_sat,
&amount));
}
return NULL;
}
struct command_result *wtx_select_utxos(struct wallet_tx *tx,
u32 fee_rate_per_kw,
size_t out_len,
u32 maxheight)
{
struct command_result *res;
struct amount_sat fee_estimate;
if (tx->all_funds) {
struct amount_sat amount;
tx->utxos = wallet_select_all(tx, tx->cmd->ld->wallet,
fee_rate_per_kw, out_len,
maxheight,
&amount,
&fee_estimate);
res = check_amount(tx, amount);
if (res)
return res;
/* tx->amount is max permissible */
if (amount_sat_less_eq(amount, tx->amount)) {
tx->change = AMOUNT_SAT(0);
tx->change_key_index = 0;
tx->amount = amount;
return NULL;
}
/* Too much? Try again, but ask for limit instead. */
tx->all_funds = false;
tx->utxos = tal_free(tx->utxos);
}
tx->utxos = wallet_select_coins(tx, tx->cmd->ld->wallet,
true, tx->amount,
fee_rate_per_kw, out_len,
maxheight,
&fee_estimate, &tx->change);
if (!tx->utxos) {
/* Try again, without change this time */
tx->utxos = wallet_select_coins(tx, tx->cmd->ld->wallet,
false, tx->amount,
fee_rate_per_kw, out_len,
maxheight,
&fee_estimate, &tx->change);
}
res = check_amount(tx, tx->amount);
if (res)
return res;
if (amount_sat_less(tx->change, get_chainparams(tx->cmd->ld)->dust_limit)) {
tx->change = AMOUNT_SAT(0);
tx->change_key_index = 0;
} else {
tx->change_key_index = wallet_get_newindex(tx->cmd->ld);
}
return NULL;
}
struct command_result *wtx_from_utxos(struct wallet_tx *tx,
u32 fee_rate_per_kw,
size_t out_len,
u32 maxheight,
const struct utxo **utxos)
{
size_t weight;
struct amount_sat total_amount, fee_estimate;
tx->change = AMOUNT_SAT(0);
tx->change_key_index = 0;
total_amount = AMOUNT_SAT(0);
/* The transaction has `tal_count(tx.utxos)` inputs and one output */
/* (version + in count + out count + locktime) (index + value + script length) */
/* + segwit marker + flag */
weight = 4 * (4 + 1 + 1 + 4) + 4 * (8 + 1 + out_len) + 1 + 1;
for (size_t i = 0; i < tal_count(utxos); i++) {
if (!*utxos[i]->blockheight || *utxos[i]->blockheight > maxheight) {
tal_arr_remove(&utxos, i);
continue;
}
/* txid + index + sequence + script_len */
weight += (32 + 4 + 4 + 1) * 4;
/* P2SH variants include push of <0 <20-byte-key-hash>> */
if (utxos[i]->is_p2sh)
weight += 23 * 4;
/* Account for witness (1 byte count + sig + key) */
weight += 1 + (1 + 73 + 1 + 33);
if (!amount_sat_add(&total_amount, total_amount, utxos[i]->amount))
fatal("Overflow when computing input amount");
}
tx->utxos = tal_steal(tx, utxos);
if (!tx->all_funds && amount_sat_less(tx->amount, total_amount)
&& !amount_sat_sub(&tx->change, total_amount, tx->amount))
fatal("Overflow when computing change");
if (amount_sat_greater_eq(tx->change, get_chainparams(tx->cmd->ld)->dust_limit)) {
/* Add the change output's weight */
weight += (8 + 1 + out_len) * 4;
}
fee_estimate = amount_tx_fee(fee_rate_per_kw, weight);
if (tx->all_funds || amount_sat_eq(tx->change, AMOUNT_SAT(0))) {
tx->amount = total_amount;
if (!amount_sat_sub(&tx->amount, tx->amount, fee_estimate))
return command_fail(tx->cmd, FUND_CANNOT_AFFORD,
"Cannot afford transaction with %s sats of fees",
type_to_string(tmpctx, struct amount_sat,
&fee_estimate));
} else {
if (!amount_sat_sub(&tx->change, tx->change, fee_estimate)) {
/* Try again without a change output */
weight -= (8 + 1 + out_len) * 4;
fee_estimate = amount_tx_fee(fee_rate_per_kw, weight);
if (!amount_sat_sub(&tx->change, tx->change, fee_estimate))
return command_fail(tx->cmd, FUND_CANNOT_AFFORD,
"Cannot afford transaction with %s sats of fees",
type_to_string(tmpctx, struct amount_sat,
&fee_estimate));
tx->change = AMOUNT_SAT(0);
} else {
tx->change_key_index = wallet_get_newindex(tx->cmd->ld);
}
}
return check_amount(tx, tx->amount);
}
|
700806.c | /*
* Rockchip USB2.0 PHY with Innosilicon IP block driver
*
* Copyright (C) 2016 Fuzhou Rockchip Electronics Co., Ltd
*
* 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.
*/
#include <linux/clk.h>
#include <linux/clk-provider.h>
#include <linux/delay.h>
#include <linux/extcon-provider.h>
#include <linux/interrupt.h>
#include <linux/io.h>
#include <linux/gpio/consumer.h>
#include <linux/jiffies.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/mutex.h>
#include <linux/of.h>
#include <linux/of_address.h>
#include <linux/of_irq.h>
#include <linux/of_platform.h>
#include <linux/phy/phy.h>
#include <linux/platform_device.h>
#include <linux/power_supply.h>
#include <linux/regmap.h>
#include <linux/mfd/syscon.h>
#include <linux/usb/of.h>
#include <linux/usb/otg.h>
#define BIT_WRITEABLE_SHIFT 16
#define SCHEDULE_DELAY (60 * HZ)
#define OTG_SCHEDULE_DELAY (2 * HZ)
enum rockchip_usb2phy_port_id {
USB2PHY_PORT_OTG,
USB2PHY_PORT_HOST,
USB2PHY_NUM_PORTS,
};
enum rockchip_usb2phy_host_state {
PHY_STATE_HS_ONLINE = 0,
PHY_STATE_DISCONNECT = 1,
PHY_STATE_CONNECT = 2,
PHY_STATE_FS_LS_ONLINE = 4,
};
/**
* Different states involved in USB charger detection.
* USB_CHG_STATE_UNDEFINED USB charger is not connected or detection
* process is not yet started.
* USB_CHG_STATE_WAIT_FOR_DCD Waiting for Data pins contact.
* USB_CHG_STATE_DCD_DONE Data pin contact is detected.
* USB_CHG_STATE_PRIMARY_DONE Primary detection is completed (Detects
* between SDP and DCP/CDP).
* USB_CHG_STATE_SECONDARY_DONE Secondary detection is completed (Detects
* between DCP and CDP).
* USB_CHG_STATE_DETECTED USB charger type is determined.
*/
enum usb_chg_state {
USB_CHG_STATE_UNDEFINED = 0,
USB_CHG_STATE_WAIT_FOR_DCD,
USB_CHG_STATE_DCD_DONE,
USB_CHG_STATE_PRIMARY_DONE,
USB_CHG_STATE_SECONDARY_DONE,
USB_CHG_STATE_DETECTED,
};
static const unsigned int rockchip_usb2phy_extcon_cable[] = {
EXTCON_USB,
EXTCON_USB_HOST,
EXTCON_CHG_USB_SDP,
EXTCON_CHG_USB_CDP,
EXTCON_CHG_USB_DCP,
EXTCON_CHG_USB_SLOW,
EXTCON_NONE,
};
struct usb2phy_reg {
unsigned int offset;
unsigned int bitend;
unsigned int bitstart;
unsigned int disable;
unsigned int enable;
};
/**
* struct rockchip_chg_det_reg: usb charger detect registers
* @cp_det: charging port detected successfully.
* @dcp_det: dedicated charging port detected successfully.
* @dp_det: assert data pin connect successfully.
* @idm_sink_en: open dm sink curren.
* @idp_sink_en: open dp sink current.
* @idp_src_en: open dm source current.
* @rdm_pdwn_en: open dm pull down resistor.
* @vdm_src_en: open dm voltage source.
* @vdp_src_en: open dp voltage source.
* @opmode: utmi operational mode.
*/
struct rockchip_chg_det_reg {
struct usb2phy_reg cp_det;
struct usb2phy_reg dcp_det;
struct usb2phy_reg dp_det;
struct usb2phy_reg idm_sink_en;
struct usb2phy_reg idp_sink_en;
struct usb2phy_reg idp_src_en;
struct usb2phy_reg rdm_pdwn_en;
struct usb2phy_reg vdm_src_en;
struct usb2phy_reg vdp_src_en;
struct usb2phy_reg opmode;
};
/**
* struct rockchip_usb2phy_port_cfg: usb-phy port configuration.
* @phy_sus: phy suspend register.
* @bvalid_det_en: vbus valid rise detection enable register.
* @bvalid_det_st: vbus valid rise detection status register.
* @bvalid_det_clr: vbus valid rise detection clear register.
* @ls_det_en: linestate detection enable register.
* @ls_det_st: linestate detection state register.
* @ls_det_clr: linestate detection clear register.
* @utmi_avalid: utmi vbus avalid status register.
* @utmi_bvalid: utmi vbus bvalid status register.
* @utmi_ls: utmi linestate state register.
* @utmi_hstdet: utmi host disconnect register.
*/
struct rockchip_usb2phy_port_cfg {
struct usb2phy_reg phy_sus;
struct usb2phy_reg bvalid_det_en;
struct usb2phy_reg bvalid_det_st;
struct usb2phy_reg bvalid_det_clr;
struct usb2phy_reg ls_det_en;
struct usb2phy_reg ls_det_st;
struct usb2phy_reg ls_det_clr;
struct usb2phy_reg utmi_avalid;
struct usb2phy_reg utmi_bvalid;
struct usb2phy_reg utmi_ls;
struct usb2phy_reg utmi_hstdet;
};
/**
* struct rockchip_usb2phy_cfg: usb-phy configuration.
* @reg: the address offset of grf for usb-phy config.
* @num_ports: specify how many ports that the phy has.
* @clkout_ctl: keep on/turn off output clk of phy.
* @chg_det: charger detection registers.
*/
struct rockchip_usb2phy_cfg {
unsigned int reg;
unsigned int num_ports;
struct usb2phy_reg clkout_ctl;
const struct rockchip_usb2phy_port_cfg port_cfgs[USB2PHY_NUM_PORTS];
const struct rockchip_chg_det_reg chg_det;
};
/**
* struct rockchip_usb2phy_port: usb-phy port data.
* @port_id: flag for otg port or host port.
* @suspended: phy suspended flag.
* @utmi_avalid: utmi avalid status usage flag.
* true - use avalid to get vbus status
* flase - use bvalid to get vbus status
* @vbus_attached: otg device vbus status.
* @bvalid_irq: IRQ number assigned for vbus valid rise detection.
* @ls_irq: IRQ number assigned for linestate detection.
* @otg_mux_irq: IRQ number which multiplex otg-id/otg-bvalid/linestate
* irqs to one irq in otg-port.
* @mutex: for register updating in sm_work.
* @chg_work: charge detect work.
* @otg_sm_work: OTG state machine work.
* @sm_work: HOST state machine work.
* @phy_cfg: port register configuration, assigned by driver data.
* @event_nb: hold event notification callback.
* @state: define OTG enumeration states before device reset.
* @mode: the dr_mode of the controller.
*/
struct rockchip_usb2phy_port {
struct phy *phy;
unsigned int port_id;
bool suspended;
bool utmi_avalid;
bool vbus_attached;
int bvalid_irq;
int ls_irq;
int otg_mux_irq;
struct mutex mutex;
struct delayed_work chg_work;
struct delayed_work otg_sm_work;
struct delayed_work sm_work;
const struct rockchip_usb2phy_port_cfg *port_cfg;
struct notifier_block event_nb;
enum usb_otg_state state;
enum usb_dr_mode mode;
};
/**
* struct rockchip_usb2phy: usb2.0 phy driver data.
* @grf: General Register Files regmap.
* @usbgrf: USB General Register Files regmap.
* @clk: clock struct of phy input clk.
* @clk480m: clock struct of phy output clk.
* @clk_hw: clock struct of phy output clk management.
* @chg_state: states involved in USB charger detection.
* @chg_type: USB charger types.
* @dcd_retries: The retry count used to track Data contact
* detection process.
* @edev: extcon device for notification registration
* @phy_cfg: phy register configuration, assigned by driver data.
* @ports: phy port instance.
*/
struct rockchip_usb2phy {
struct device *dev;
struct regmap *grf;
struct regmap *usbgrf;
struct clk *clk;
struct clk *clk480m;
struct clk_hw clk480m_hw;
enum usb_chg_state chg_state;
enum power_supply_type chg_type;
u8 dcd_retries;
struct extcon_dev *edev;
const struct rockchip_usb2phy_cfg *phy_cfg;
struct rockchip_usb2phy_port ports[USB2PHY_NUM_PORTS];
};
static inline struct regmap *get_reg_base(struct rockchip_usb2phy *rphy)
{
return rphy->usbgrf == NULL ? rphy->grf : rphy->usbgrf;
}
static inline int property_enable(struct regmap *base,
const struct usb2phy_reg *reg, bool en)
{
unsigned int val, mask, tmp;
tmp = en ? reg->enable : reg->disable;
mask = GENMASK(reg->bitend, reg->bitstart);
val = (tmp << reg->bitstart) | (mask << BIT_WRITEABLE_SHIFT);
return regmap_write(base, reg->offset, val);
}
static inline bool property_enabled(struct regmap *base,
const struct usb2phy_reg *reg)
{
int ret;
unsigned int tmp, orig;
unsigned int mask = GENMASK(reg->bitend, reg->bitstart);
ret = regmap_read(base, reg->offset, &orig);
if (ret)
return false;
tmp = (orig & mask) >> reg->bitstart;
return tmp == reg->enable;
}
static int rockchip_usb2phy_clk480m_prepare(struct clk_hw *hw)
{
struct rockchip_usb2phy *rphy =
container_of(hw, struct rockchip_usb2phy, clk480m_hw);
struct regmap *base = get_reg_base(rphy);
int ret;
/* turn on 480m clk output if it is off */
if (!property_enabled(base, &rphy->phy_cfg->clkout_ctl)) {
ret = property_enable(base, &rphy->phy_cfg->clkout_ctl, true);
if (ret)
return ret;
/* waiting for the clk become stable */
usleep_range(1200, 1300);
}
return 0;
}
static void rockchip_usb2phy_clk480m_unprepare(struct clk_hw *hw)
{
struct rockchip_usb2phy *rphy =
container_of(hw, struct rockchip_usb2phy, clk480m_hw);
struct regmap *base = get_reg_base(rphy);
/* turn off 480m clk output */
property_enable(base, &rphy->phy_cfg->clkout_ctl, false);
}
static int rockchip_usb2phy_clk480m_prepared(struct clk_hw *hw)
{
struct rockchip_usb2phy *rphy =
container_of(hw, struct rockchip_usb2phy, clk480m_hw);
struct regmap *base = get_reg_base(rphy);
return property_enabled(base, &rphy->phy_cfg->clkout_ctl);
}
static unsigned long
rockchip_usb2phy_clk480m_recalc_rate(struct clk_hw *hw,
unsigned long parent_rate)
{
return 480000000;
}
static const struct clk_ops rockchip_usb2phy_clkout_ops = {
.prepare = rockchip_usb2phy_clk480m_prepare,
.unprepare = rockchip_usb2phy_clk480m_unprepare,
.is_prepared = rockchip_usb2phy_clk480m_prepared,
.recalc_rate = rockchip_usb2phy_clk480m_recalc_rate,
};
static void rockchip_usb2phy_clk480m_unregister(void *data)
{
struct rockchip_usb2phy *rphy = data;
of_clk_del_provider(rphy->dev->of_node);
clk_unregister(rphy->clk480m);
}
static int
rockchip_usb2phy_clk480m_register(struct rockchip_usb2phy *rphy)
{
struct device_node *node = rphy->dev->of_node;
struct clk_init_data init;
const char *clk_name;
int ret;
init.flags = 0;
init.name = "clk_usbphy_480m";
init.ops = &rockchip_usb2phy_clkout_ops;
/* optional override of the clockname */
of_property_read_string(node, "clock-output-names", &init.name);
if (rphy->clk) {
clk_name = __clk_get_name(rphy->clk);
init.parent_names = &clk_name;
init.num_parents = 1;
} else {
init.parent_names = NULL;
init.num_parents = 0;
}
rphy->clk480m_hw.init = &init;
/* register the clock */
rphy->clk480m = clk_register(rphy->dev, &rphy->clk480m_hw);
if (IS_ERR(rphy->clk480m)) {
ret = PTR_ERR(rphy->clk480m);
goto err_ret;
}
ret = of_clk_add_provider(node, of_clk_src_simple_get, rphy->clk480m);
if (ret < 0)
goto err_clk_provider;
ret = devm_add_action(rphy->dev, rockchip_usb2phy_clk480m_unregister,
rphy);
if (ret < 0)
goto err_unreg_action;
return 0;
err_unreg_action:
of_clk_del_provider(node);
err_clk_provider:
clk_unregister(rphy->clk480m);
err_ret:
return ret;
}
static int rockchip_usb2phy_extcon_register(struct rockchip_usb2phy *rphy)
{
int ret;
struct device_node *node = rphy->dev->of_node;
struct extcon_dev *edev;
if (of_property_read_bool(node, "extcon")) {
edev = extcon_get_edev_by_phandle(rphy->dev, 0);
if (IS_ERR(edev)) {
if (PTR_ERR(edev) != -EPROBE_DEFER)
dev_err(rphy->dev, "Invalid or missing extcon\n");
return PTR_ERR(edev);
}
} else {
/* Initialize extcon device */
edev = devm_extcon_dev_allocate(rphy->dev,
rockchip_usb2phy_extcon_cable);
if (IS_ERR(edev))
return -ENOMEM;
ret = devm_extcon_dev_register(rphy->dev, edev);
if (ret) {
dev_err(rphy->dev, "failed to register extcon device\n");
return ret;
}
}
rphy->edev = edev;
return 0;
}
static int rockchip_usb2phy_init(struct phy *phy)
{
struct rockchip_usb2phy_port *rport = phy_get_drvdata(phy);
struct rockchip_usb2phy *rphy = dev_get_drvdata(phy->dev.parent);
int ret = 0;
mutex_lock(&rport->mutex);
if (rport->port_id == USB2PHY_PORT_OTG) {
if (rport->mode != USB_DR_MODE_HOST &&
rport->mode != USB_DR_MODE_UNKNOWN) {
/* clear bvalid status and enable bvalid detect irq */
ret = property_enable(rphy->grf,
&rport->port_cfg->bvalid_det_clr,
true);
if (ret)
goto out;
ret = property_enable(rphy->grf,
&rport->port_cfg->bvalid_det_en,
true);
if (ret)
goto out;
schedule_delayed_work(&rport->otg_sm_work,
OTG_SCHEDULE_DELAY * 3);
} else {
/* If OTG works in host only mode, do nothing. */
dev_dbg(&rport->phy->dev, "mode %d\n", rport->mode);
}
} else if (rport->port_id == USB2PHY_PORT_HOST) {
/* clear linestate and enable linestate detect irq */
ret = property_enable(rphy->grf,
&rport->port_cfg->ls_det_clr, true);
if (ret)
goto out;
ret = property_enable(rphy->grf,
&rport->port_cfg->ls_det_en, true);
if (ret)
goto out;
schedule_delayed_work(&rport->sm_work, SCHEDULE_DELAY);
}
out:
mutex_unlock(&rport->mutex);
return ret;
}
static int rockchip_usb2phy_power_on(struct phy *phy)
{
struct rockchip_usb2phy_port *rport = phy_get_drvdata(phy);
struct rockchip_usb2phy *rphy = dev_get_drvdata(phy->dev.parent);
struct regmap *base = get_reg_base(rphy);
int ret;
dev_dbg(&rport->phy->dev, "port power on\n");
if (!rport->suspended)
return 0;
ret = clk_prepare_enable(rphy->clk480m);
if (ret)
return ret;
ret = property_enable(base, &rport->port_cfg->phy_sus, false);
if (ret)
return ret;
/* waiting for the utmi_clk to become stable */
usleep_range(1500, 2000);
rport->suspended = false;
return 0;
}
static int rockchip_usb2phy_power_off(struct phy *phy)
{
struct rockchip_usb2phy_port *rport = phy_get_drvdata(phy);
struct rockchip_usb2phy *rphy = dev_get_drvdata(phy->dev.parent);
struct regmap *base = get_reg_base(rphy);
int ret;
dev_dbg(&rport->phy->dev, "port power off\n");
if (rport->suspended)
return 0;
ret = property_enable(base, &rport->port_cfg->phy_sus, true);
if (ret)
return ret;
rport->suspended = true;
clk_disable_unprepare(rphy->clk480m);
return 0;
}
static int rockchip_usb2phy_exit(struct phy *phy)
{
struct rockchip_usb2phy_port *rport = phy_get_drvdata(phy);
if (rport->port_id == USB2PHY_PORT_OTG &&
rport->mode != USB_DR_MODE_HOST &&
rport->mode != USB_DR_MODE_UNKNOWN) {
cancel_delayed_work_sync(&rport->otg_sm_work);
cancel_delayed_work_sync(&rport->chg_work);
} else if (rport->port_id == USB2PHY_PORT_HOST)
cancel_delayed_work_sync(&rport->sm_work);
return 0;
}
static const struct phy_ops rockchip_usb2phy_ops = {
.init = rockchip_usb2phy_init,
.exit = rockchip_usb2phy_exit,
.power_on = rockchip_usb2phy_power_on,
.power_off = rockchip_usb2phy_power_off,
.owner = THIS_MODULE,
};
static void rockchip_usb2phy_otg_sm_work(struct work_struct *work)
{
struct rockchip_usb2phy_port *rport =
container_of(work, struct rockchip_usb2phy_port,
otg_sm_work.work);
struct rockchip_usb2phy *rphy = dev_get_drvdata(rport->phy->dev.parent);
static unsigned int cable;
unsigned long delay;
bool vbus_attach, sch_work, notify_charger;
if (rport->utmi_avalid)
vbus_attach = property_enabled(rphy->grf,
&rport->port_cfg->utmi_avalid);
else
vbus_attach = property_enabled(rphy->grf,
&rport->port_cfg->utmi_bvalid);
sch_work = false;
notify_charger = false;
delay = OTG_SCHEDULE_DELAY;
dev_dbg(&rport->phy->dev, "%s otg sm work\n",
usb_otg_state_string(rport->state));
switch (rport->state) {
case OTG_STATE_UNDEFINED:
rport->state = OTG_STATE_B_IDLE;
if (!vbus_attach)
rockchip_usb2phy_power_off(rport->phy);
/* fall through */
case OTG_STATE_B_IDLE:
if (extcon_get_state(rphy->edev, EXTCON_USB_HOST) > 0) {
dev_dbg(&rport->phy->dev, "usb otg host connect\n");
rport->state = OTG_STATE_A_HOST;
rockchip_usb2phy_power_on(rport->phy);
return;
} else if (vbus_attach) {
dev_dbg(&rport->phy->dev, "vbus_attach\n");
switch (rphy->chg_state) {
case USB_CHG_STATE_UNDEFINED:
schedule_delayed_work(&rport->chg_work, 0);
return;
case USB_CHG_STATE_DETECTED:
switch (rphy->chg_type) {
case POWER_SUPPLY_TYPE_USB:
dev_dbg(&rport->phy->dev, "sdp cable is connected\n");
rockchip_usb2phy_power_on(rport->phy);
rport->state = OTG_STATE_B_PERIPHERAL;
notify_charger = true;
sch_work = true;
cable = EXTCON_CHG_USB_SDP;
break;
case POWER_SUPPLY_TYPE_USB_DCP:
dev_dbg(&rport->phy->dev, "dcp cable is connected\n");
rockchip_usb2phy_power_off(rport->phy);
notify_charger = true;
sch_work = true;
cable = EXTCON_CHG_USB_DCP;
break;
case POWER_SUPPLY_TYPE_USB_CDP:
dev_dbg(&rport->phy->dev, "cdp cable is connected\n");
rockchip_usb2phy_power_on(rport->phy);
rport->state = OTG_STATE_B_PERIPHERAL;
notify_charger = true;
sch_work = true;
cable = EXTCON_CHG_USB_CDP;
break;
default:
break;
}
break;
default:
break;
}
} else {
notify_charger = true;
rphy->chg_state = USB_CHG_STATE_UNDEFINED;
rphy->chg_type = POWER_SUPPLY_TYPE_UNKNOWN;
}
if (rport->vbus_attached != vbus_attach) {
rport->vbus_attached = vbus_attach;
if (notify_charger && rphy->edev) {
extcon_set_state_sync(rphy->edev,
cable, vbus_attach);
if (cable == EXTCON_CHG_USB_SDP)
extcon_set_state_sync(rphy->edev,
EXTCON_USB,
vbus_attach);
}
}
break;
case OTG_STATE_B_PERIPHERAL:
if (!vbus_attach) {
dev_dbg(&rport->phy->dev, "usb disconnect\n");
rphy->chg_state = USB_CHG_STATE_UNDEFINED;
rphy->chg_type = POWER_SUPPLY_TYPE_UNKNOWN;
rport->state = OTG_STATE_B_IDLE;
delay = 0;
rockchip_usb2phy_power_off(rport->phy);
}
sch_work = true;
break;
case OTG_STATE_A_HOST:
if (extcon_get_state(rphy->edev, EXTCON_USB_HOST) == 0) {
dev_dbg(&rport->phy->dev, "usb otg host disconnect\n");
rport->state = OTG_STATE_B_IDLE;
rockchip_usb2phy_power_off(rport->phy);
}
break;
default:
break;
}
if (sch_work)
schedule_delayed_work(&rport->otg_sm_work, delay);
}
static const char *chg_to_string(enum power_supply_type chg_type)
{
switch (chg_type) {
case POWER_SUPPLY_TYPE_USB:
return "USB_SDP_CHARGER";
case POWER_SUPPLY_TYPE_USB_DCP:
return "USB_DCP_CHARGER";
case POWER_SUPPLY_TYPE_USB_CDP:
return "USB_CDP_CHARGER";
default:
return "INVALID_CHARGER";
}
}
static void rockchip_chg_enable_dcd(struct rockchip_usb2phy *rphy,
bool en)
{
struct regmap *base = get_reg_base(rphy);
property_enable(base, &rphy->phy_cfg->chg_det.rdm_pdwn_en, en);
property_enable(base, &rphy->phy_cfg->chg_det.idp_src_en, en);
}
static void rockchip_chg_enable_primary_det(struct rockchip_usb2phy *rphy,
bool en)
{
struct regmap *base = get_reg_base(rphy);
property_enable(base, &rphy->phy_cfg->chg_det.vdp_src_en, en);
property_enable(base, &rphy->phy_cfg->chg_det.idm_sink_en, en);
}
static void rockchip_chg_enable_secondary_det(struct rockchip_usb2phy *rphy,
bool en)
{
struct regmap *base = get_reg_base(rphy);
property_enable(base, &rphy->phy_cfg->chg_det.vdm_src_en, en);
property_enable(base, &rphy->phy_cfg->chg_det.idp_sink_en, en);
}
#define CHG_DCD_POLL_TIME (100 * HZ / 1000)
#define CHG_DCD_MAX_RETRIES 6
#define CHG_PRIMARY_DET_TIME (40 * HZ / 1000)
#define CHG_SECONDARY_DET_TIME (40 * HZ / 1000)
static void rockchip_chg_detect_work(struct work_struct *work)
{
struct rockchip_usb2phy_port *rport =
container_of(work, struct rockchip_usb2phy_port, chg_work.work);
struct rockchip_usb2phy *rphy = dev_get_drvdata(rport->phy->dev.parent);
struct regmap *base = get_reg_base(rphy);
bool is_dcd, tmout, vout;
unsigned long delay;
dev_dbg(&rport->phy->dev, "chg detection work state = %d\n",
rphy->chg_state);
switch (rphy->chg_state) {
case USB_CHG_STATE_UNDEFINED:
if (!rport->suspended)
rockchip_usb2phy_power_off(rport->phy);
/* put the controller in non-driving mode */
property_enable(base, &rphy->phy_cfg->chg_det.opmode, false);
/* Start DCD processing stage 1 */
rockchip_chg_enable_dcd(rphy, true);
rphy->chg_state = USB_CHG_STATE_WAIT_FOR_DCD;
rphy->dcd_retries = 0;
delay = CHG_DCD_POLL_TIME;
break;
case USB_CHG_STATE_WAIT_FOR_DCD:
/* get data contact detection status */
is_dcd = property_enabled(rphy->grf,
&rphy->phy_cfg->chg_det.dp_det);
tmout = ++rphy->dcd_retries == CHG_DCD_MAX_RETRIES;
/* stage 2 */
if (is_dcd || tmout) {
/* stage 4 */
/* Turn off DCD circuitry */
rockchip_chg_enable_dcd(rphy, false);
/* Voltage Source on DP, Probe on DM */
rockchip_chg_enable_primary_det(rphy, true);
delay = CHG_PRIMARY_DET_TIME;
rphy->chg_state = USB_CHG_STATE_DCD_DONE;
} else {
/* stage 3 */
delay = CHG_DCD_POLL_TIME;
}
break;
case USB_CHG_STATE_DCD_DONE:
vout = property_enabled(rphy->grf,
&rphy->phy_cfg->chg_det.cp_det);
rockchip_chg_enable_primary_det(rphy, false);
if (vout) {
/* Voltage Source on DM, Probe on DP */
rockchip_chg_enable_secondary_det(rphy, true);
delay = CHG_SECONDARY_DET_TIME;
rphy->chg_state = USB_CHG_STATE_PRIMARY_DONE;
} else {
if (rphy->dcd_retries == CHG_DCD_MAX_RETRIES) {
/* floating charger found */
rphy->chg_type = POWER_SUPPLY_TYPE_USB_DCP;
rphy->chg_state = USB_CHG_STATE_DETECTED;
delay = 0;
} else {
rphy->chg_type = POWER_SUPPLY_TYPE_USB;
rphy->chg_state = USB_CHG_STATE_DETECTED;
delay = 0;
}
}
break;
case USB_CHG_STATE_PRIMARY_DONE:
vout = property_enabled(rphy->grf,
&rphy->phy_cfg->chg_det.dcp_det);
/* Turn off voltage source */
rockchip_chg_enable_secondary_det(rphy, false);
if (vout)
rphy->chg_type = POWER_SUPPLY_TYPE_USB_DCP;
else
rphy->chg_type = POWER_SUPPLY_TYPE_USB_CDP;
/* fall through */
case USB_CHG_STATE_SECONDARY_DONE:
rphy->chg_state = USB_CHG_STATE_DETECTED;
delay = 0;
/* fall through */
case USB_CHG_STATE_DETECTED:
/* put the controller in normal mode */
property_enable(base, &rphy->phy_cfg->chg_det.opmode, true);
rockchip_usb2phy_otg_sm_work(&rport->otg_sm_work.work);
dev_info(&rport->phy->dev, "charger = %s\n",
chg_to_string(rphy->chg_type));
return;
default:
return;
}
schedule_delayed_work(&rport->chg_work, delay);
}
/*
* The function manage host-phy port state and suspend/resume phy port
* to save power.
*
* we rely on utmi_linestate and utmi_hostdisconnect to identify whether
* devices is disconnect or not. Besides, we do not need care it is FS/LS
* disconnected or HS disconnected, actually, we just only need get the
* device is disconnected at last through rearm the delayed work,
* to suspend the phy port in _PHY_STATE_DISCONNECT_ case.
*
* NOTE: It may invoke *phy_powr_off or *phy_power_on which will invoke
* some clk related APIs, so do not invoke it from interrupt context directly.
*/
static void rockchip_usb2phy_sm_work(struct work_struct *work)
{
struct rockchip_usb2phy_port *rport =
container_of(work, struct rockchip_usb2phy_port, sm_work.work);
struct rockchip_usb2phy *rphy = dev_get_drvdata(rport->phy->dev.parent);
unsigned int sh = rport->port_cfg->utmi_hstdet.bitend -
rport->port_cfg->utmi_hstdet.bitstart + 1;
unsigned int ul, uhd, state;
unsigned int ul_mask, uhd_mask;
int ret;
mutex_lock(&rport->mutex);
ret = regmap_read(rphy->grf, rport->port_cfg->utmi_ls.offset, &ul);
if (ret < 0)
goto next_schedule;
ret = regmap_read(rphy->grf, rport->port_cfg->utmi_hstdet.offset, &uhd);
if (ret < 0)
goto next_schedule;
uhd_mask = GENMASK(rport->port_cfg->utmi_hstdet.bitend,
rport->port_cfg->utmi_hstdet.bitstart);
ul_mask = GENMASK(rport->port_cfg->utmi_ls.bitend,
rport->port_cfg->utmi_ls.bitstart);
/* stitch on utmi_ls and utmi_hstdet as phy state */
state = ((uhd & uhd_mask) >> rport->port_cfg->utmi_hstdet.bitstart) |
(((ul & ul_mask) >> rport->port_cfg->utmi_ls.bitstart) << sh);
switch (state) {
case PHY_STATE_HS_ONLINE:
dev_dbg(&rport->phy->dev, "HS online\n");
break;
case PHY_STATE_FS_LS_ONLINE:
/*
* For FS/LS device, the online state share with connect state
* from utmi_ls and utmi_hstdet register, so we distinguish
* them via suspended flag.
*
* Plus, there are two cases, one is D- Line pull-up, and D+
* line pull-down, the state is 4; another is D+ line pull-up,
* and D- line pull-down, the state is 2.
*/
if (!rport->suspended) {
/* D- line pull-up, D+ line pull-down */
dev_dbg(&rport->phy->dev, "FS/LS online\n");
break;
}
/* fall through */
case PHY_STATE_CONNECT:
if (rport->suspended) {
dev_dbg(&rport->phy->dev, "Connected\n");
rockchip_usb2phy_power_on(rport->phy);
rport->suspended = false;
} else {
/* D+ line pull-up, D- line pull-down */
dev_dbg(&rport->phy->dev, "FS/LS online\n");
}
break;
case PHY_STATE_DISCONNECT:
if (!rport->suspended) {
dev_dbg(&rport->phy->dev, "Disconnected\n");
rockchip_usb2phy_power_off(rport->phy);
rport->suspended = true;
}
/*
* activate the linestate detection to get the next device
* plug-in irq.
*/
property_enable(rphy->grf, &rport->port_cfg->ls_det_clr, true);
property_enable(rphy->grf, &rport->port_cfg->ls_det_en, true);
/*
* we don't need to rearm the delayed work when the phy port
* is suspended.
*/
mutex_unlock(&rport->mutex);
return;
default:
dev_dbg(&rport->phy->dev, "unknown phy state\n");
break;
}
next_schedule:
mutex_unlock(&rport->mutex);
schedule_delayed_work(&rport->sm_work, SCHEDULE_DELAY);
}
static irqreturn_t rockchip_usb2phy_linestate_irq(int irq, void *data)
{
struct rockchip_usb2phy_port *rport = data;
struct rockchip_usb2phy *rphy = dev_get_drvdata(rport->phy->dev.parent);
if (!property_enabled(rphy->grf, &rport->port_cfg->ls_det_st))
return IRQ_NONE;
mutex_lock(&rport->mutex);
/* disable linestate detect irq and clear its status */
property_enable(rphy->grf, &rport->port_cfg->ls_det_en, false);
property_enable(rphy->grf, &rport->port_cfg->ls_det_clr, true);
mutex_unlock(&rport->mutex);
/*
* In this case for host phy port, a new device is plugged in,
* meanwhile, if the phy port is suspended, we need rearm the work to
* resume it and mange its states; otherwise, we do nothing about that.
*/
if (rport->suspended && rport->port_id == USB2PHY_PORT_HOST)
rockchip_usb2phy_sm_work(&rport->sm_work.work);
return IRQ_HANDLED;
}
static irqreturn_t rockchip_usb2phy_bvalid_irq(int irq, void *data)
{
struct rockchip_usb2phy_port *rport = data;
struct rockchip_usb2phy *rphy = dev_get_drvdata(rport->phy->dev.parent);
if (!property_enabled(rphy->grf, &rport->port_cfg->bvalid_det_st))
return IRQ_NONE;
mutex_lock(&rport->mutex);
/* clear bvalid detect irq pending status */
property_enable(rphy->grf, &rport->port_cfg->bvalid_det_clr, true);
mutex_unlock(&rport->mutex);
rockchip_usb2phy_otg_sm_work(&rport->otg_sm_work.work);
return IRQ_HANDLED;
}
static irqreturn_t rockchip_usb2phy_otg_mux_irq(int irq, void *data)
{
struct rockchip_usb2phy_port *rport = data;
struct rockchip_usb2phy *rphy = dev_get_drvdata(rport->phy->dev.parent);
if (property_enabled(rphy->grf, &rport->port_cfg->bvalid_det_st))
return rockchip_usb2phy_bvalid_irq(irq, data);
else
return IRQ_NONE;
}
static int rockchip_usb2phy_host_port_init(struct rockchip_usb2phy *rphy,
struct rockchip_usb2phy_port *rport,
struct device_node *child_np)
{
int ret;
rport->port_id = USB2PHY_PORT_HOST;
rport->port_cfg = &rphy->phy_cfg->port_cfgs[USB2PHY_PORT_HOST];
rport->suspended = true;
mutex_init(&rport->mutex);
INIT_DELAYED_WORK(&rport->sm_work, rockchip_usb2phy_sm_work);
rport->ls_irq = of_irq_get_byname(child_np, "linestate");
if (rport->ls_irq < 0) {
dev_err(rphy->dev, "no linestate irq provided\n");
return rport->ls_irq;
}
ret = devm_request_threaded_irq(rphy->dev, rport->ls_irq, NULL,
rockchip_usb2phy_linestate_irq,
IRQF_ONESHOT,
"rockchip_usb2phy", rport);
if (ret) {
dev_err(rphy->dev, "failed to request linestate irq handle\n");
return ret;
}
return 0;
}
static int rockchip_otg_event(struct notifier_block *nb,
unsigned long event, void *ptr)
{
struct rockchip_usb2phy_port *rport =
container_of(nb, struct rockchip_usb2phy_port, event_nb);
schedule_delayed_work(&rport->otg_sm_work, OTG_SCHEDULE_DELAY);
return NOTIFY_DONE;
}
static int rockchip_usb2phy_otg_port_init(struct rockchip_usb2phy *rphy,
struct rockchip_usb2phy_port *rport,
struct device_node *child_np)
{
int ret;
rport->port_id = USB2PHY_PORT_OTG;
rport->port_cfg = &rphy->phy_cfg->port_cfgs[USB2PHY_PORT_OTG];
rport->state = OTG_STATE_UNDEFINED;
/*
* set suspended flag to true, but actually don't
* put phy in suspend mode, it aims to enable usb
* phy and clock in power_on() called by usb controller
* driver during probe.
*/
rport->suspended = true;
rport->vbus_attached = false;
mutex_init(&rport->mutex);
rport->mode = of_usb_get_dr_mode_by_phy(child_np, -1);
if (rport->mode == USB_DR_MODE_HOST ||
rport->mode == USB_DR_MODE_UNKNOWN) {
ret = 0;
goto out;
}
INIT_DELAYED_WORK(&rport->chg_work, rockchip_chg_detect_work);
INIT_DELAYED_WORK(&rport->otg_sm_work, rockchip_usb2phy_otg_sm_work);
rport->utmi_avalid =
of_property_read_bool(child_np, "rockchip,utmi-avalid");
/*
* Some SoCs use one interrupt with otg-id/otg-bvalid/linestate
* interrupts muxed together, so probe the otg-mux interrupt first,
* if not found, then look for the regular interrupts one by one.
*/
rport->otg_mux_irq = of_irq_get_byname(child_np, "otg-mux");
if (rport->otg_mux_irq > 0) {
ret = devm_request_threaded_irq(rphy->dev, rport->otg_mux_irq,
NULL,
rockchip_usb2phy_otg_mux_irq,
IRQF_ONESHOT,
"rockchip_usb2phy_otg",
rport);
if (ret) {
dev_err(rphy->dev,
"failed to request otg-mux irq handle\n");
goto out;
}
} else {
rport->bvalid_irq = of_irq_get_byname(child_np, "otg-bvalid");
if (rport->bvalid_irq < 0) {
dev_err(rphy->dev, "no vbus valid irq provided\n");
ret = rport->bvalid_irq;
goto out;
}
ret = devm_request_threaded_irq(rphy->dev, rport->bvalid_irq,
NULL,
rockchip_usb2phy_bvalid_irq,
IRQF_ONESHOT,
"rockchip_usb2phy_bvalid",
rport);
if (ret) {
dev_err(rphy->dev,
"failed to request otg-bvalid irq handle\n");
goto out;
}
}
if (!IS_ERR(rphy->edev)) {
rport->event_nb.notifier_call = rockchip_otg_event;
ret = devm_extcon_register_notifier(rphy->dev, rphy->edev,
EXTCON_USB_HOST, &rport->event_nb);
if (ret)
dev_err(rphy->dev, "register USB HOST notifier failed\n");
}
out:
return ret;
}
static int rockchip_usb2phy_probe(struct platform_device *pdev)
{
struct device *dev = &pdev->dev;
struct device_node *np = dev->of_node;
struct device_node *child_np;
struct phy_provider *provider;
struct rockchip_usb2phy *rphy;
const struct rockchip_usb2phy_cfg *phy_cfgs;
const struct of_device_id *match;
unsigned int reg;
int index, ret;
rphy = devm_kzalloc(dev, sizeof(*rphy), GFP_KERNEL);
if (!rphy)
return -ENOMEM;
match = of_match_device(dev->driver->of_match_table, dev);
if (!match || !match->data) {
dev_err(dev, "phy configs are not assigned!\n");
return -EINVAL;
}
if (!dev->parent || !dev->parent->of_node)
return -EINVAL;
rphy->grf = syscon_node_to_regmap(dev->parent->of_node);
if (IS_ERR(rphy->grf))
return PTR_ERR(rphy->grf);
if (of_device_is_compatible(np, "rockchip,rv1108-usb2phy")) {
rphy->usbgrf =
syscon_regmap_lookup_by_phandle(dev->of_node,
"rockchip,usbgrf");
if (IS_ERR(rphy->usbgrf))
return PTR_ERR(rphy->usbgrf);
} else {
rphy->usbgrf = NULL;
}
if (of_property_read_u32(np, "reg", ®)) {
dev_err(dev, "the reg property is not assigned in %s node\n",
np->name);
return -EINVAL;
}
rphy->dev = dev;
phy_cfgs = match->data;
rphy->chg_state = USB_CHG_STATE_UNDEFINED;
rphy->chg_type = POWER_SUPPLY_TYPE_UNKNOWN;
platform_set_drvdata(pdev, rphy);
ret = rockchip_usb2phy_extcon_register(rphy);
if (ret)
return ret;
/* find out a proper config which can be matched with dt. */
index = 0;
while (phy_cfgs[index].reg) {
if (phy_cfgs[index].reg == reg) {
rphy->phy_cfg = &phy_cfgs[index];
break;
}
++index;
}
if (!rphy->phy_cfg) {
dev_err(dev, "no phy-config can be matched with %s node\n",
np->name);
return -EINVAL;
}
rphy->clk = of_clk_get_by_name(np, "phyclk");
if (!IS_ERR(rphy->clk)) {
clk_prepare_enable(rphy->clk);
} else {
dev_info(&pdev->dev, "no phyclk specified\n");
rphy->clk = NULL;
}
ret = rockchip_usb2phy_clk480m_register(rphy);
if (ret) {
dev_err(dev, "failed to register 480m output clock\n");
goto disable_clks;
}
index = 0;
for_each_available_child_of_node(np, child_np) {
struct rockchip_usb2phy_port *rport = &rphy->ports[index];
struct phy *phy;
/* This driver aims to support both otg-port and host-port */
if (of_node_cmp(child_np->name, "host-port") &&
of_node_cmp(child_np->name, "otg-port"))
goto next_child;
phy = devm_phy_create(dev, child_np, &rockchip_usb2phy_ops);
if (IS_ERR(phy)) {
dev_err(dev, "failed to create phy\n");
ret = PTR_ERR(phy);
goto put_child;
}
rport->phy = phy;
phy_set_drvdata(rport->phy, rport);
/* initialize otg/host port separately */
if (!of_node_cmp(child_np->name, "host-port")) {
ret = rockchip_usb2phy_host_port_init(rphy, rport,
child_np);
if (ret)
goto put_child;
} else {
ret = rockchip_usb2phy_otg_port_init(rphy, rport,
child_np);
if (ret)
goto put_child;
}
next_child:
/* to prevent out of boundary */
if (++index >= rphy->phy_cfg->num_ports)
break;
}
provider = devm_of_phy_provider_register(dev, of_phy_simple_xlate);
return PTR_ERR_OR_ZERO(provider);
put_child:
of_node_put(child_np);
disable_clks:
if (rphy->clk) {
clk_disable_unprepare(rphy->clk);
clk_put(rphy->clk);
}
return ret;
}
static const struct rockchip_usb2phy_cfg rk3228_phy_cfgs[] = {
{
.reg = 0x760,
.num_ports = 2,
.clkout_ctl = { 0x0768, 4, 4, 1, 0 },
.port_cfgs = {
[USB2PHY_PORT_OTG] = {
.phy_sus = { 0x0760, 15, 0, 0, 0x1d1 },
.bvalid_det_en = { 0x0680, 3, 3, 0, 1 },
.bvalid_det_st = { 0x0690, 3, 3, 0, 1 },
.bvalid_det_clr = { 0x06a0, 3, 3, 0, 1 },
.ls_det_en = { 0x0680, 2, 2, 0, 1 },
.ls_det_st = { 0x0690, 2, 2, 0, 1 },
.ls_det_clr = { 0x06a0, 2, 2, 0, 1 },
.utmi_bvalid = { 0x0480, 4, 4, 0, 1 },
.utmi_ls = { 0x0480, 3, 2, 0, 1 },
},
[USB2PHY_PORT_HOST] = {
.phy_sus = { 0x0764, 15, 0, 0, 0x1d1 },
.ls_det_en = { 0x0680, 4, 4, 0, 1 },
.ls_det_st = { 0x0690, 4, 4, 0, 1 },
.ls_det_clr = { 0x06a0, 4, 4, 0, 1 }
}
},
.chg_det = {
.opmode = { 0x0760, 3, 0, 5, 1 },
.cp_det = { 0x0884, 4, 4, 0, 1 },
.dcp_det = { 0x0884, 3, 3, 0, 1 },
.dp_det = { 0x0884, 5, 5, 0, 1 },
.idm_sink_en = { 0x0768, 8, 8, 0, 1 },
.idp_sink_en = { 0x0768, 7, 7, 0, 1 },
.idp_src_en = { 0x0768, 9, 9, 0, 1 },
.rdm_pdwn_en = { 0x0768, 10, 10, 0, 1 },
.vdm_src_en = { 0x0768, 12, 12, 0, 1 },
.vdp_src_en = { 0x0768, 11, 11, 0, 1 },
},
},
{
.reg = 0x800,
.num_ports = 2,
.clkout_ctl = { 0x0808, 4, 4, 1, 0 },
.port_cfgs = {
[USB2PHY_PORT_OTG] = {
.phy_sus = { 0x800, 15, 0, 0, 0x1d1 },
.ls_det_en = { 0x0684, 0, 0, 0, 1 },
.ls_det_st = { 0x0694, 0, 0, 0, 1 },
.ls_det_clr = { 0x06a4, 0, 0, 0, 1 }
},
[USB2PHY_PORT_HOST] = {
.phy_sus = { 0x804, 15, 0, 0, 0x1d1 },
.ls_det_en = { 0x0684, 1, 1, 0, 1 },
.ls_det_st = { 0x0694, 1, 1, 0, 1 },
.ls_det_clr = { 0x06a4, 1, 1, 0, 1 }
}
},
},
{ /* sentinel */ }
};
static const struct rockchip_usb2phy_cfg rk3328_phy_cfgs[] = {
{
.reg = 0x100,
.num_ports = 2,
.clkout_ctl = { 0x108, 4, 4, 1, 0 },
.port_cfgs = {
[USB2PHY_PORT_OTG] = {
.phy_sus = { 0x0100, 15, 0, 0, 0x1d1 },
.bvalid_det_en = { 0x0110, 2, 2, 0, 1 },
.bvalid_det_st = { 0x0114, 2, 2, 0, 1 },
.bvalid_det_clr = { 0x0118, 2, 2, 0, 1 },
.ls_det_en = { 0x0110, 0, 0, 0, 1 },
.ls_det_st = { 0x0114, 0, 0, 0, 1 },
.ls_det_clr = { 0x0118, 0, 0, 0, 1 },
.utmi_avalid = { 0x0120, 10, 10, 0, 1 },
.utmi_bvalid = { 0x0120, 9, 9, 0, 1 },
.utmi_ls = { 0x0120, 5, 4, 0, 1 },
},
[USB2PHY_PORT_HOST] = {
.phy_sus = { 0x104, 15, 0, 0, 0x1d1 },
.ls_det_en = { 0x110, 1, 1, 0, 1 },
.ls_det_st = { 0x114, 1, 1, 0, 1 },
.ls_det_clr = { 0x118, 1, 1, 0, 1 },
.utmi_ls = { 0x120, 17, 16, 0, 1 },
.utmi_hstdet = { 0x120, 19, 19, 0, 1 }
}
},
.chg_det = {
.opmode = { 0x0100, 3, 0, 5, 1 },
.cp_det = { 0x0120, 24, 24, 0, 1 },
.dcp_det = { 0x0120, 23, 23, 0, 1 },
.dp_det = { 0x0120, 25, 25, 0, 1 },
.idm_sink_en = { 0x0108, 8, 8, 0, 1 },
.idp_sink_en = { 0x0108, 7, 7, 0, 1 },
.idp_src_en = { 0x0108, 9, 9, 0, 1 },
.rdm_pdwn_en = { 0x0108, 10, 10, 0, 1 },
.vdm_src_en = { 0x0108, 12, 12, 0, 1 },
.vdp_src_en = { 0x0108, 11, 11, 0, 1 },
},
},
{ /* sentinel */ }
};
static const struct rockchip_usb2phy_cfg rk3366_phy_cfgs[] = {
{
.reg = 0x700,
.num_ports = 2,
.clkout_ctl = { 0x0724, 15, 15, 1, 0 },
.port_cfgs = {
[USB2PHY_PORT_HOST] = {
.phy_sus = { 0x0728, 15, 0, 0, 0x1d1 },
.ls_det_en = { 0x0680, 4, 4, 0, 1 },
.ls_det_st = { 0x0690, 4, 4, 0, 1 },
.ls_det_clr = { 0x06a0, 4, 4, 0, 1 },
.utmi_ls = { 0x049c, 14, 13, 0, 1 },
.utmi_hstdet = { 0x049c, 12, 12, 0, 1 }
}
},
},
{ /* sentinel */ }
};
static const struct rockchip_usb2phy_cfg rk3399_phy_cfgs[] = {
{
.reg = 0xe450,
.num_ports = 2,
.clkout_ctl = { 0xe450, 4, 4, 1, 0 },
.port_cfgs = {
[USB2PHY_PORT_OTG] = {
.phy_sus = { 0xe454, 1, 0, 2, 1 },
.bvalid_det_en = { 0xe3c0, 3, 3, 0, 1 },
.bvalid_det_st = { 0xe3e0, 3, 3, 0, 1 },
.bvalid_det_clr = { 0xe3d0, 3, 3, 0, 1 },
.utmi_avalid = { 0xe2ac, 7, 7, 0, 1 },
.utmi_bvalid = { 0xe2ac, 12, 12, 0, 1 },
},
[USB2PHY_PORT_HOST] = {
.phy_sus = { 0xe458, 1, 0, 0x2, 0x1 },
.ls_det_en = { 0xe3c0, 6, 6, 0, 1 },
.ls_det_st = { 0xe3e0, 6, 6, 0, 1 },
.ls_det_clr = { 0xe3d0, 6, 6, 0, 1 },
.utmi_ls = { 0xe2ac, 22, 21, 0, 1 },
.utmi_hstdet = { 0xe2ac, 23, 23, 0, 1 }
}
},
.chg_det = {
.opmode = { 0xe454, 3, 0, 5, 1 },
.cp_det = { 0xe2ac, 2, 2, 0, 1 },
.dcp_det = { 0xe2ac, 1, 1, 0, 1 },
.dp_det = { 0xe2ac, 0, 0, 0, 1 },
.idm_sink_en = { 0xe450, 8, 8, 0, 1 },
.idp_sink_en = { 0xe450, 7, 7, 0, 1 },
.idp_src_en = { 0xe450, 9, 9, 0, 1 },
.rdm_pdwn_en = { 0xe450, 10, 10, 0, 1 },
.vdm_src_en = { 0xe450, 12, 12, 0, 1 },
.vdp_src_en = { 0xe450, 11, 11, 0, 1 },
},
},
{
.reg = 0xe460,
.num_ports = 2,
.clkout_ctl = { 0xe460, 4, 4, 1, 0 },
.port_cfgs = {
[USB2PHY_PORT_OTG] = {
.phy_sus = { 0xe464, 1, 0, 2, 1 },
.bvalid_det_en = { 0xe3c0, 8, 8, 0, 1 },
.bvalid_det_st = { 0xe3e0, 8, 8, 0, 1 },
.bvalid_det_clr = { 0xe3d0, 8, 8, 0, 1 },
.utmi_avalid = { 0xe2ac, 10, 10, 0, 1 },
.utmi_bvalid = { 0xe2ac, 16, 16, 0, 1 },
},
[USB2PHY_PORT_HOST] = {
.phy_sus = { 0xe468, 1, 0, 0x2, 0x1 },
.ls_det_en = { 0xe3c0, 11, 11, 0, 1 },
.ls_det_st = { 0xe3e0, 11, 11, 0, 1 },
.ls_det_clr = { 0xe3d0, 11, 11, 0, 1 },
.utmi_ls = { 0xe2ac, 26, 25, 0, 1 },
.utmi_hstdet = { 0xe2ac, 27, 27, 0, 1 }
}
},
},
{ /* sentinel */ }
};
static const struct rockchip_usb2phy_cfg rv1108_phy_cfgs[] = {
{
.reg = 0x100,
.num_ports = 2,
.clkout_ctl = { 0x108, 4, 4, 1, 0 },
.port_cfgs = {
[USB2PHY_PORT_OTG] = {
.phy_sus = { 0x0100, 15, 0, 0, 0x1d1 },
.bvalid_det_en = { 0x0680, 3, 3, 0, 1 },
.bvalid_det_st = { 0x0690, 3, 3, 0, 1 },
.bvalid_det_clr = { 0x06a0, 3, 3, 0, 1 },
.ls_det_en = { 0x0680, 2, 2, 0, 1 },
.ls_det_st = { 0x0690, 2, 2, 0, 1 },
.ls_det_clr = { 0x06a0, 2, 2, 0, 1 },
.utmi_bvalid = { 0x0804, 10, 10, 0, 1 },
.utmi_ls = { 0x0804, 13, 12, 0, 1 },
},
[USB2PHY_PORT_HOST] = {
.phy_sus = { 0x0104, 15, 0, 0, 0x1d1 },
.ls_det_en = { 0x0680, 4, 4, 0, 1 },
.ls_det_st = { 0x0690, 4, 4, 0, 1 },
.ls_det_clr = { 0x06a0, 4, 4, 0, 1 },
.utmi_ls = { 0x0804, 9, 8, 0, 1 },
.utmi_hstdet = { 0x0804, 7, 7, 0, 1 }
}
},
.chg_det = {
.opmode = { 0x0100, 3, 0, 5, 1 },
.cp_det = { 0x0804, 1, 1, 0, 1 },
.dcp_det = { 0x0804, 0, 0, 0, 1 },
.dp_det = { 0x0804, 2, 2, 0, 1 },
.idm_sink_en = { 0x0108, 8, 8, 0, 1 },
.idp_sink_en = { 0x0108, 7, 7, 0, 1 },
.idp_src_en = { 0x0108, 9, 9, 0, 1 },
.rdm_pdwn_en = { 0x0108, 10, 10, 0, 1 },
.vdm_src_en = { 0x0108, 12, 12, 0, 1 },
.vdp_src_en = { 0x0108, 11, 11, 0, 1 },
},
},
{ /* sentinel */ }
};
static const struct of_device_id rockchip_usb2phy_dt_match[] = {
{ .compatible = "rockchip,rk3228-usb2phy", .data = &rk3228_phy_cfgs },
{ .compatible = "rockchip,rk3328-usb2phy", .data = &rk3328_phy_cfgs },
{ .compatible = "rockchip,rk3366-usb2phy", .data = &rk3366_phy_cfgs },
{ .compatible = "rockchip,rk3399-usb2phy", .data = &rk3399_phy_cfgs },
{ .compatible = "rockchip,rv1108-usb2phy", .data = &rv1108_phy_cfgs },
{}
};
MODULE_DEVICE_TABLE(of, rockchip_usb2phy_dt_match);
static struct platform_driver rockchip_usb2phy_driver = {
.probe = rockchip_usb2phy_probe,
.driver = {
.name = "rockchip-usb2phy",
.of_match_table = rockchip_usb2phy_dt_match,
},
};
module_platform_driver(rockchip_usb2phy_driver);
MODULE_AUTHOR("Frank Wang <[email protected]>");
MODULE_DESCRIPTION("Rockchip USB2.0 PHY driver");
MODULE_LICENSE("GPL v2");
|
98266.c | /******************************************************************************
*
* This file is provided under a dual BSD/GPLv2 license. When using or
* redistributing this file, you may do so under either license.
*
* GPL LICENSE SUMMARY
*
* Copyright(c) 2012 - 2013 Intel Corporation. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of version 2 of the GNU General Public License as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110,
* USA
*
* The full GNU General Public License is included in this distribution
* in the file called COPYING.
*
* Contact Information:
* Intel Linux Wireless <[email protected]>
* Intel Corporation, 5200 N.E. Elam Young Parkway, Hillsboro, OR 97124-6497
*
* BSD LICENSE
*
* Copyright(c) 2012 - 2013 Intel Corporation. All rights reserved.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* * Neither the name 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.
*
*****************************************************************************/
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/init.h>
#include <net/mac80211.h>
#include "iwl-debug.h"
#include "mvm.h"
#include "iwl-modparams.h"
#include "fw-api-power.h"
#define POWER_KEEP_ALIVE_PERIOD_SEC 25
int iwl_mvm_beacon_filter_send_cmd(struct iwl_mvm *mvm,
struct iwl_beacon_filter_cmd *cmd)
{
int ret;
ret = iwl_mvm_send_cmd_pdu(mvm, REPLY_BEACON_FILTERING_CMD, CMD_SYNC,
sizeof(struct iwl_beacon_filter_cmd), cmd);
if (!ret) {
IWL_DEBUG_POWER(mvm, "ba_enable_beacon_abort is: %d\n",
le32_to_cpu(cmd->ba_enable_beacon_abort));
IWL_DEBUG_POWER(mvm, "ba_escape_timer is: %d\n",
le32_to_cpu(cmd->ba_escape_timer));
IWL_DEBUG_POWER(mvm, "bf_debug_flag is: %d\n",
le32_to_cpu(cmd->bf_debug_flag));
IWL_DEBUG_POWER(mvm, "bf_enable_beacon_filter is: %d\n",
le32_to_cpu(cmd->bf_enable_beacon_filter));
IWL_DEBUG_POWER(mvm, "bf_energy_delta is: %d\n",
le32_to_cpu(cmd->bf_energy_delta));
IWL_DEBUG_POWER(mvm, "bf_escape_timer is: %d\n",
le32_to_cpu(cmd->bf_escape_timer));
IWL_DEBUG_POWER(mvm, "bf_roaming_energy_delta is: %d\n",
le32_to_cpu(cmd->bf_roaming_energy_delta));
IWL_DEBUG_POWER(mvm, "bf_roaming_state is: %d\n",
le32_to_cpu(cmd->bf_roaming_state));
IWL_DEBUG_POWER(mvm, "bf_temp_threshold is: %d\n",
le32_to_cpu(cmd->bf_temp_threshold));
IWL_DEBUG_POWER(mvm, "bf_temp_fast_filter is: %d\n",
le32_to_cpu(cmd->bf_temp_fast_filter));
IWL_DEBUG_POWER(mvm, "bf_temp_slow_filter is: %d\n",
le32_to_cpu(cmd->bf_temp_slow_filter));
}
return ret;
}
static
void iwl_mvm_beacon_filter_set_cqm_params(struct iwl_mvm *mvm,
struct ieee80211_vif *vif,
struct iwl_beacon_filter_cmd *cmd)
{
struct iwl_mvm_vif *mvmvif = iwl_mvm_vif_from_mac80211(vif);
if (vif->bss_conf.cqm_rssi_thold) {
cmd->bf_energy_delta =
cpu_to_le32(vif->bss_conf.cqm_rssi_hyst);
/* fw uses an absolute value for this */
cmd->bf_roaming_state =
cpu_to_le32(-vif->bss_conf.cqm_rssi_thold);
}
cmd->ba_enable_beacon_abort = cpu_to_le32(mvmvif->bf_data.ba_enabled);
}
int iwl_mvm_update_beacon_abort(struct iwl_mvm *mvm,
struct ieee80211_vif *vif, bool enable)
{
struct iwl_mvm_vif *mvmvif = iwl_mvm_vif_from_mac80211(vif);
struct iwl_beacon_filter_cmd cmd = {
IWL_BF_CMD_CONFIG_DEFAULTS,
.bf_enable_beacon_filter = cpu_to_le32(1),
.ba_enable_beacon_abort = cpu_to_le32(enable),
};
if (!mvmvif->bf_data.bf_enabled)
return 0;
if (mvm->cur_ucode == IWL_UCODE_WOWLAN)
cmd.ba_escape_timer = cpu_to_le32(IWL_BA_ESCAPE_TIMER_D3);
mvmvif->bf_data.ba_enabled = enable;
iwl_mvm_beacon_filter_set_cqm_params(mvm, vif, &cmd);
iwl_mvm_beacon_filter_debugfs_parameters(vif, &cmd);
return iwl_mvm_beacon_filter_send_cmd(mvm, &cmd);
}
static void iwl_mvm_power_log(struct iwl_mvm *mvm,
struct iwl_mac_power_cmd *cmd)
{
IWL_DEBUG_POWER(mvm,
"Sending power table command on mac id 0x%X for power level %d, flags = 0x%X\n",
cmd->id_and_color, iwlmvm_mod_params.power_scheme,
le16_to_cpu(cmd->flags));
IWL_DEBUG_POWER(mvm, "Keep alive = %u sec\n",
le16_to_cpu(cmd->keep_alive_seconds));
if (!(cmd->flags & cpu_to_le16(POWER_FLAGS_POWER_MANAGEMENT_ENA_MSK))) {
IWL_DEBUG_POWER(mvm, "Disable power management\n");
return;
}
IWL_DEBUG_POWER(mvm, "Rx timeout = %u usec\n",
le32_to_cpu(cmd->rx_data_timeout));
IWL_DEBUG_POWER(mvm, "Tx timeout = %u usec\n",
le32_to_cpu(cmd->tx_data_timeout));
if (cmd->flags & cpu_to_le16(POWER_FLAGS_SKIP_OVER_DTIM_MSK))
IWL_DEBUG_POWER(mvm, "DTIM periods to skip = %u\n",
cmd->skip_dtim_periods);
if (cmd->flags & cpu_to_le16(POWER_FLAGS_LPRX_ENA_MSK))
IWL_DEBUG_POWER(mvm, "LP RX RSSI threshold = %u\n",
cmd->lprx_rssi_threshold);
if (cmd->flags & cpu_to_le16(POWER_FLAGS_ADVANCE_PM_ENA_MSK)) {
IWL_DEBUG_POWER(mvm, "uAPSD enabled\n");
IWL_DEBUG_POWER(mvm, "Rx timeout (uAPSD) = %u usec\n",
le32_to_cpu(cmd->rx_data_timeout_uapsd));
IWL_DEBUG_POWER(mvm, "Tx timeout (uAPSD) = %u usec\n",
le32_to_cpu(cmd->tx_data_timeout_uapsd));
IWL_DEBUG_POWER(mvm, "QNDP TID = %d\n", cmd->qndp_tid);
IWL_DEBUG_POWER(mvm, "ACs flags = 0x%x\n", cmd->uapsd_ac_flags);
IWL_DEBUG_POWER(mvm, "Max SP = %d\n", cmd->uapsd_max_sp);
}
}
static void iwl_mvm_power_build_cmd(struct iwl_mvm *mvm,
struct ieee80211_vif *vif,
struct iwl_mac_power_cmd *cmd)
{
struct ieee80211_hw *hw = mvm->hw;
struct ieee80211_chanctx_conf *chanctx_conf;
struct ieee80211_channel *chan;
int dtimper, dtimper_msec;
int keep_alive;
bool radar_detect = false;
struct iwl_mvm_vif *mvmvif __maybe_unused =
iwl_mvm_vif_from_mac80211(vif);
enum ieee80211_ac_numbers ac;
bool tid_found = false;
cmd->id_and_color = cpu_to_le32(FW_CMD_ID_AND_COLOR(mvmvif->id,
mvmvif->color));
dtimper = hw->conf.ps_dtim_period ?: 1;
/*
* Regardless of power management state the driver must set
* keep alive period. FW will use it for sending keep alive NDPs
* immediately after association. Check that keep alive period
* is at least 3 * DTIM
*/
dtimper_msec = dtimper * vif->bss_conf.beacon_int;
keep_alive = max_t(int, 3 * dtimper_msec,
MSEC_PER_SEC * POWER_KEEP_ALIVE_PERIOD_SEC);
keep_alive = DIV_ROUND_UP(keep_alive, MSEC_PER_SEC);
cmd->keep_alive_seconds = cpu_to_le16(keep_alive);
if (iwlmvm_mod_params.power_scheme == IWL_POWER_SCHEME_CAM)
return;
cmd->flags |= cpu_to_le16(POWER_FLAGS_POWER_SAVE_ENA_MSK);
#ifdef CONFIG_IWLWIFI_DEBUGFS
if (mvmvif->dbgfs_pm.mask & MVM_DEBUGFS_PM_DISABLE_POWER_OFF &&
mvmvif->dbgfs_pm.disable_power_off)
cmd->flags &= cpu_to_le16(~POWER_FLAGS_POWER_SAVE_ENA_MSK);
#endif
if (!vif->bss_conf.ps)
return;
cmd->flags |= cpu_to_le16(POWER_FLAGS_POWER_MANAGEMENT_ENA_MSK);
if (vif->bss_conf.beacon_rate &&
(vif->bss_conf.beacon_rate->bitrate == 10 ||
vif->bss_conf.beacon_rate->bitrate == 60)) {
cmd->flags |= cpu_to_le16(POWER_FLAGS_LPRX_ENA_MSK);
cmd->lprx_rssi_threshold = POWER_LPRX_RSSI_THRESHOLD;
}
/* Check if radar detection is required on current channel */
rcu_read_lock();
chanctx_conf = rcu_dereference(vif->chanctx_conf);
WARN_ON(!chanctx_conf);
if (chanctx_conf) {
chan = chanctx_conf->def.chan;
radar_detect = chan->flags & IEEE80211_CHAN_RADAR;
}
rcu_read_unlock();
/* Check skip over DTIM conditions */
if (!radar_detect && (dtimper <= 10) &&
(iwlmvm_mod_params.power_scheme == IWL_POWER_SCHEME_LP ||
mvm->cur_ucode == IWL_UCODE_WOWLAN)) {
cmd->flags |= cpu_to_le16(POWER_FLAGS_SKIP_OVER_DTIM_MSK);
cmd->skip_dtim_periods = 3;
}
if (mvm->cur_ucode != IWL_UCODE_WOWLAN) {
cmd->rx_data_timeout =
cpu_to_le32(IWL_MVM_DEFAULT_PS_RX_DATA_TIMEOUT);
cmd->tx_data_timeout =
cpu_to_le32(IWL_MVM_DEFAULT_PS_TX_DATA_TIMEOUT);
} else {
cmd->rx_data_timeout =
cpu_to_le32(IWL_MVM_WOWLAN_PS_RX_DATA_TIMEOUT);
cmd->tx_data_timeout =
cpu_to_le32(IWL_MVM_WOWLAN_PS_TX_DATA_TIMEOUT);
}
for (ac = IEEE80211_AC_VO; ac <= IEEE80211_AC_BK; ac++) {
if (!mvmvif->queue_params[ac].uapsd)
continue;
if (mvm->cur_ucode != IWL_UCODE_WOWLAN)
cmd->flags |=
cpu_to_le16(POWER_FLAGS_ADVANCE_PM_ENA_MSK);
cmd->uapsd_ac_flags |= BIT(ac);
/* QNDP TID - the highest TID with no admission control */
if (!tid_found && !mvmvif->queue_params[ac].acm) {
tid_found = true;
switch (ac) {
case IEEE80211_AC_VO:
cmd->qndp_tid = 6;
break;
case IEEE80211_AC_VI:
cmd->qndp_tid = 5;
break;
case IEEE80211_AC_BE:
cmd->qndp_tid = 0;
break;
case IEEE80211_AC_BK:
cmd->qndp_tid = 1;
break;
}
}
}
if (cmd->flags & cpu_to_le16(POWER_FLAGS_ADVANCE_PM_ENA_MSK)) {
if (cmd->uapsd_ac_flags == (BIT(IEEE80211_AC_VO) |
BIT(IEEE80211_AC_VI) |
BIT(IEEE80211_AC_BE) |
BIT(IEEE80211_AC_BK))) {
cmd->flags |= cpu_to_le16(POWER_FLAGS_SNOOZE_ENA_MSK);
cmd->snooze_interval =
cpu_to_le16(IWL_MVM_PS_SNOOZE_INTERVAL);
cmd->snooze_window =
(mvm->cur_ucode == IWL_UCODE_WOWLAN) ?
cpu_to_le16(IWL_MVM_WOWLAN_PS_SNOOZE_WINDOW) :
cpu_to_le16(IWL_MVM_PS_SNOOZE_WINDOW);
}
cmd->uapsd_max_sp = IWL_UAPSD_MAX_SP;
if (mvm->cur_ucode == IWL_UCODE_WOWLAN || cmd->flags &
cpu_to_le16(POWER_FLAGS_SNOOZE_ENA_MSK)) {
cmd->rx_data_timeout_uapsd =
cpu_to_le32(IWL_MVM_WOWLAN_PS_RX_DATA_TIMEOUT);
cmd->tx_data_timeout_uapsd =
cpu_to_le32(IWL_MVM_WOWLAN_PS_TX_DATA_TIMEOUT);
} else {
cmd->rx_data_timeout_uapsd =
cpu_to_le32(IWL_MVM_UAPSD_RX_DATA_TIMEOUT);
cmd->tx_data_timeout_uapsd =
cpu_to_le32(IWL_MVM_UAPSD_TX_DATA_TIMEOUT);
}
if (cmd->flags & cpu_to_le16(POWER_FLAGS_SNOOZE_ENA_MSK)) {
cmd->heavy_tx_thld_packets =
IWL_MVM_PS_SNOOZE_HEAVY_TX_THLD_PACKETS;
cmd->heavy_rx_thld_packets =
IWL_MVM_PS_SNOOZE_HEAVY_RX_THLD_PACKETS;
} else {
cmd->heavy_tx_thld_packets =
IWL_MVM_PS_HEAVY_TX_THLD_PACKETS;
cmd->heavy_rx_thld_packets =
IWL_MVM_PS_HEAVY_RX_THLD_PACKETS;
}
cmd->heavy_tx_thld_percentage =
IWL_MVM_PS_HEAVY_TX_THLD_PERCENT;
cmd->heavy_rx_thld_percentage =
IWL_MVM_PS_HEAVY_RX_THLD_PERCENT;
}
#ifdef CONFIG_IWLWIFI_DEBUGFS
if (mvmvif->dbgfs_pm.mask & MVM_DEBUGFS_PM_KEEP_ALIVE)
cmd->keep_alive_seconds =
cpu_to_le16(mvmvif->dbgfs_pm.keep_alive_seconds);
if (mvmvif->dbgfs_pm.mask & MVM_DEBUGFS_PM_SKIP_OVER_DTIM) {
if (mvmvif->dbgfs_pm.skip_over_dtim)
cmd->flags |=
cpu_to_le16(POWER_FLAGS_SKIP_OVER_DTIM_MSK);
else
cmd->flags &=
cpu_to_le16(~POWER_FLAGS_SKIP_OVER_DTIM_MSK);
}
if (mvmvif->dbgfs_pm.mask & MVM_DEBUGFS_PM_RX_DATA_TIMEOUT)
cmd->rx_data_timeout =
cpu_to_le32(mvmvif->dbgfs_pm.rx_data_timeout);
if (mvmvif->dbgfs_pm.mask & MVM_DEBUGFS_PM_TX_DATA_TIMEOUT)
cmd->tx_data_timeout =
cpu_to_le32(mvmvif->dbgfs_pm.tx_data_timeout);
if (mvmvif->dbgfs_pm.mask & MVM_DEBUGFS_PM_SKIP_DTIM_PERIODS)
cmd->skip_dtim_periods = mvmvif->dbgfs_pm.skip_dtim_periods;
if (mvmvif->dbgfs_pm.mask & MVM_DEBUGFS_PM_LPRX_ENA) {
if (mvmvif->dbgfs_pm.lprx_ena)
cmd->flags |= cpu_to_le16(POWER_FLAGS_LPRX_ENA_MSK);
else
cmd->flags &= cpu_to_le16(~POWER_FLAGS_LPRX_ENA_MSK);
}
if (mvmvif->dbgfs_pm.mask & MVM_DEBUGFS_PM_LPRX_RSSI_THRESHOLD)
cmd->lprx_rssi_threshold = mvmvif->dbgfs_pm.lprx_rssi_threshold;
if (mvmvif->dbgfs_pm.mask & MVM_DEBUGFS_PM_SNOOZE_ENABLE) {
if (mvmvif->dbgfs_pm.snooze_ena)
cmd->flags |=
cpu_to_le16(POWER_FLAGS_SNOOZE_ENA_MSK);
else
cmd->flags &=
cpu_to_le16(~POWER_FLAGS_SNOOZE_ENA_MSK);
}
#endif /* CONFIG_IWLWIFI_DEBUGFS */
}
static int iwl_mvm_power_mac_update_mode(struct iwl_mvm *mvm,
struct ieee80211_vif *vif)
{
int ret;
bool ba_enable;
struct iwl_mac_power_cmd cmd = {};
if (vif->type != NL80211_IFTYPE_STATION || vif->p2p)
return 0;
/*
* TODO: The following vif_count verification is temporary condition.
* Avoid power mode update if more than one interface is currently
* active. Remove this condition when FW will support power management
* on multiple MACs.
*/
IWL_DEBUG_POWER(mvm, "Currently %d interfaces active\n",
mvm->vif_count);
if (mvm->vif_count > 1)
return 0;
iwl_mvm_power_build_cmd(mvm, vif, &cmd);
iwl_mvm_power_log(mvm, &cmd);
ret = iwl_mvm_send_cmd_pdu(mvm, MAC_PM_POWER_TABLE, CMD_SYNC,
sizeof(cmd), &cmd);
if (ret)
return ret;
ba_enable = !!(cmd.flags &
cpu_to_le16(POWER_FLAGS_POWER_MANAGEMENT_ENA_MSK));
return iwl_mvm_update_beacon_abort(mvm, vif, ba_enable);
}
static int iwl_mvm_power_mac_disable(struct iwl_mvm *mvm,
struct ieee80211_vif *vif)
{
struct iwl_mac_power_cmd cmd = {};
struct iwl_mvm_vif *mvmvif __maybe_unused =
iwl_mvm_vif_from_mac80211(vif);
if (vif->type != NL80211_IFTYPE_STATION || vif->p2p)
return 0;
cmd.id_and_color = cpu_to_le32(FW_CMD_ID_AND_COLOR(mvmvif->id,
mvmvif->color));
if (iwlmvm_mod_params.power_scheme != IWL_POWER_SCHEME_CAM)
cmd.flags |= cpu_to_le16(POWER_FLAGS_POWER_SAVE_ENA_MSK);
#ifdef CONFIG_IWLWIFI_DEBUGFS
if (mvmvif->dbgfs_pm.mask & MVM_DEBUGFS_PM_DISABLE_POWER_OFF &&
mvmvif->dbgfs_pm.disable_power_off)
cmd.flags &= cpu_to_le16(~POWER_FLAGS_POWER_SAVE_ENA_MSK);
#endif
iwl_mvm_power_log(mvm, &cmd);
return iwl_mvm_send_cmd_pdu(mvm, MAC_PM_POWER_TABLE, CMD_ASYNC,
sizeof(cmd), &cmd);
}
static int iwl_mvm_power_update_device(struct iwl_mvm *mvm)
{
struct iwl_device_power_cmd cmd = {
.flags = cpu_to_le16(DEVICE_POWER_FLAGS_POWER_SAVE_ENA_MSK),
};
if (!(mvm->fw->ucode_capa.flags & IWL_UCODE_TLV_FLAGS_DEVICE_PS_CMD))
return 0;
if (iwlmvm_mod_params.power_scheme == IWL_POWER_SCHEME_CAM)
cmd.flags |= cpu_to_le16(DEVICE_POWER_FLAGS_CAM_MSK);
#ifdef CONFIG_IWLWIFI_DEBUGFS
if ((mvm->cur_ucode == IWL_UCODE_WOWLAN) ? mvm->disable_power_off_d3 :
mvm->disable_power_off)
cmd.flags &=
cpu_to_le16(~DEVICE_POWER_FLAGS_POWER_SAVE_ENA_MSK);
#endif
IWL_DEBUG_POWER(mvm,
"Sending device power command with flags = 0x%X\n",
cmd.flags);
return iwl_mvm_send_cmd_pdu(mvm, POWER_TABLE_CMD, CMD_SYNC, sizeof(cmd),
&cmd);
}
#ifdef CONFIG_IWLWIFI_DEBUGFS
static int iwl_mvm_power_mac_dbgfs_read(struct iwl_mvm *mvm,
struct ieee80211_vif *vif, char *buf,
int bufsz)
{
struct iwl_mac_power_cmd cmd = {};
int pos = 0;
iwl_mvm_power_build_cmd(mvm, vif, &cmd);
if (!(mvm->fw->ucode_capa.flags & IWL_UCODE_TLV_FLAGS_DEVICE_PS_CMD))
pos += scnprintf(buf+pos, bufsz-pos, "disable_power_off = %d\n",
(cmd.flags &
cpu_to_le16(POWER_FLAGS_POWER_SAVE_ENA_MSK)) ?
0 : 1);
pos += scnprintf(buf+pos, bufsz-pos, "power_scheme = %d\n",
iwlmvm_mod_params.power_scheme);
pos += scnprintf(buf+pos, bufsz-pos, "flags = 0x%x\n",
le16_to_cpu(cmd.flags));
pos += scnprintf(buf+pos, bufsz-pos, "keep_alive = %d\n",
le16_to_cpu(cmd.keep_alive_seconds));
if (cmd.flags & cpu_to_le16(POWER_FLAGS_POWER_MANAGEMENT_ENA_MSK)) {
pos += scnprintf(buf+pos, bufsz-pos, "skip_over_dtim = %d\n",
(cmd.flags &
cpu_to_le16(POWER_FLAGS_SKIP_OVER_DTIM_MSK)) ?
1 : 0);
pos += scnprintf(buf+pos, bufsz-pos, "skip_dtim_periods = %d\n",
cmd.skip_dtim_periods);
if (!(cmd.flags &
cpu_to_le16(POWER_FLAGS_ADVANCE_PM_ENA_MSK))) {
pos += scnprintf(buf+pos, bufsz-pos,
"rx_data_timeout = %d\n",
le32_to_cpu(cmd.rx_data_timeout));
pos += scnprintf(buf+pos, bufsz-pos,
"tx_data_timeout = %d\n",
le32_to_cpu(cmd.tx_data_timeout));
}
if (cmd.flags & cpu_to_le16(POWER_FLAGS_LPRX_ENA_MSK))
pos += scnprintf(buf+pos, bufsz-pos,
"lprx_rssi_threshold = %d\n",
cmd.lprx_rssi_threshold);
if (cmd.flags & cpu_to_le16(POWER_FLAGS_ADVANCE_PM_ENA_MSK)) {
pos +=
scnprintf(buf+pos, bufsz-pos,
"rx_data_timeout_uapsd = %d\n",
le32_to_cpu(cmd.rx_data_timeout_uapsd));
pos +=
scnprintf(buf+pos, bufsz-pos,
"tx_data_timeout_uapsd = %d\n",
le32_to_cpu(cmd.tx_data_timeout_uapsd));
pos += scnprintf(buf+pos, bufsz-pos, "qndp_tid = %d\n",
cmd.qndp_tid);
pos += scnprintf(buf+pos, bufsz-pos,
"uapsd_ac_flags = 0x%x\n",
cmd.uapsd_ac_flags);
pos += scnprintf(buf+pos, bufsz-pos,
"uapsd_max_sp = %d\n",
cmd.uapsd_max_sp);
pos += scnprintf(buf+pos, bufsz-pos,
"heavy_tx_thld_packets = %d\n",
cmd.heavy_tx_thld_packets);
pos += scnprintf(buf+pos, bufsz-pos,
"heavy_rx_thld_packets = %d\n",
cmd.heavy_rx_thld_packets);
pos += scnprintf(buf+pos, bufsz-pos,
"heavy_tx_thld_percentage = %d\n",
cmd.heavy_tx_thld_percentage);
pos += scnprintf(buf+pos, bufsz-pos,
"heavy_rx_thld_percentage = %d\n",
cmd.heavy_rx_thld_percentage);
pos +=
scnprintf(buf+pos, bufsz-pos, "snooze_enable = %d\n",
(cmd.flags &
cpu_to_le16(POWER_FLAGS_SNOOZE_ENA_MSK)) ?
1 : 0);
}
if (cmd.flags & cpu_to_le16(POWER_FLAGS_SNOOZE_ENA_MSK)) {
pos += scnprintf(buf+pos, bufsz-pos,
"snooze_interval = %d\n",
cmd.snooze_interval);
pos += scnprintf(buf+pos, bufsz-pos,
"snooze_window = %d\n",
cmd.snooze_window);
}
}
return pos;
}
void
iwl_mvm_beacon_filter_debugfs_parameters(struct ieee80211_vif *vif,
struct iwl_beacon_filter_cmd *cmd)
{
struct iwl_mvm_vif *mvmvif = iwl_mvm_vif_from_mac80211(vif);
struct iwl_dbgfs_bf *dbgfs_bf = &mvmvif->dbgfs_bf;
if (dbgfs_bf->mask & MVM_DEBUGFS_BF_ENERGY_DELTA)
cmd->bf_energy_delta = cpu_to_le32(dbgfs_bf->bf_energy_delta);
if (dbgfs_bf->mask & MVM_DEBUGFS_BF_ROAMING_ENERGY_DELTA)
cmd->bf_roaming_energy_delta =
cpu_to_le32(dbgfs_bf->bf_roaming_energy_delta);
if (dbgfs_bf->mask & MVM_DEBUGFS_BF_ROAMING_STATE)
cmd->bf_roaming_state = cpu_to_le32(dbgfs_bf->bf_roaming_state);
if (dbgfs_bf->mask & MVM_DEBUGFS_BF_TEMP_THRESHOLD)
cmd->bf_temp_threshold =
cpu_to_le32(dbgfs_bf->bf_temp_threshold);
if (dbgfs_bf->mask & MVM_DEBUGFS_BF_TEMP_FAST_FILTER)
cmd->bf_temp_fast_filter =
cpu_to_le32(dbgfs_bf->bf_temp_fast_filter);
if (dbgfs_bf->mask & MVM_DEBUGFS_BF_TEMP_SLOW_FILTER)
cmd->bf_temp_slow_filter =
cpu_to_le32(dbgfs_bf->bf_temp_slow_filter);
if (dbgfs_bf->mask & MVM_DEBUGFS_BF_DEBUG_FLAG)
cmd->bf_debug_flag = cpu_to_le32(dbgfs_bf->bf_debug_flag);
if (dbgfs_bf->mask & MVM_DEBUGFS_BF_ESCAPE_TIMER)
cmd->bf_escape_timer = cpu_to_le32(dbgfs_bf->bf_escape_timer);
if (dbgfs_bf->mask & MVM_DEBUGFS_BA_ESCAPE_TIMER)
cmd->ba_escape_timer = cpu_to_le32(dbgfs_bf->ba_escape_timer);
if (dbgfs_bf->mask & MVM_DEBUGFS_BA_ENABLE_BEACON_ABORT)
cmd->ba_enable_beacon_abort =
cpu_to_le32(dbgfs_bf->ba_enable_beacon_abort);
}
#endif
int iwl_mvm_enable_beacon_filter(struct iwl_mvm *mvm,
struct ieee80211_vif *vif)
{
struct iwl_mvm_vif *mvmvif = iwl_mvm_vif_from_mac80211(vif);
struct iwl_beacon_filter_cmd cmd = {
IWL_BF_CMD_CONFIG_DEFAULTS,
.bf_enable_beacon_filter = cpu_to_le32(1),
};
int ret;
if (mvmvif != mvm->bf_allowed_vif ||
vif->type != NL80211_IFTYPE_STATION || vif->p2p)
return 0;
iwl_mvm_beacon_filter_set_cqm_params(mvm, vif, &cmd);
iwl_mvm_beacon_filter_debugfs_parameters(vif, &cmd);
ret = iwl_mvm_beacon_filter_send_cmd(mvm, &cmd);
if (!ret)
mvmvif->bf_data.bf_enabled = true;
return ret;
}
int iwl_mvm_disable_beacon_filter(struct iwl_mvm *mvm,
struct ieee80211_vif *vif)
{
struct iwl_beacon_filter_cmd cmd = {};
struct iwl_mvm_vif *mvmvif = iwl_mvm_vif_from_mac80211(vif);
int ret;
if (!(mvm->fw->ucode_capa.flags & IWL_UCODE_TLV_FLAGS_BF_UPDATED) ||
vif->type != NL80211_IFTYPE_STATION || vif->p2p)
return 0;
ret = iwl_mvm_beacon_filter_send_cmd(mvm, &cmd);
if (!ret)
mvmvif->bf_data.bf_enabled = false;
return ret;
}
int iwl_mvm_update_beacon_filter(struct iwl_mvm *mvm,
struct ieee80211_vif *vif)
{
struct iwl_mvm_vif *mvmvif = iwl_mvm_vif_from_mac80211(vif);
if (!mvmvif->bf_data.bf_enabled)
return 0;
return iwl_mvm_enable_beacon_filter(mvm, vif);
}
const struct iwl_mvm_power_ops pm_mac_ops = {
.power_update_mode = iwl_mvm_power_mac_update_mode,
.power_update_device_mode = iwl_mvm_power_update_device,
.power_disable = iwl_mvm_power_mac_disable,
#ifdef CONFIG_IWLWIFI_DEBUGFS
.power_dbgfs_read = iwl_mvm_power_mac_dbgfs_read,
#endif
};
|
681777.c | #ifndef lint
static const char SCCSID[]="@(#)geod_for.c 4.6 95/09/23 GIE REL";
#endif
# include "projects.h"
# include "geodesic.h"
# define MERI_TOL 1e-9
static double
th1,costh1,sinth1,sina12,cosa12,M,N,c1,c2,D,P,s1;
static int
merid, signS;
void
geod_pre(void) {
al12 = adjlon(al12); /* reduce to +- 0-PI */
signS = fabs(al12) > HALFPI ? 1 : 0;
th1 = ellipse ? atan(onef * tan(phi1)) : phi1;
costh1 = cos(th1);
sinth1 = sin(th1);
if ((merid = fabs(sina12 = sin(al12)) < MERI_TOL)) {
sina12 = 0.;
cosa12 = fabs(al12) < HALFPI ? 1. : -1.;
M = 0.;
} else {
cosa12 = cos(al12);
M = costh1 * sina12;
}
N = costh1 * cosa12;
if (ellipse) {
if (merid) {
c1 = 0.;
c2 = f4;
D = 1. - c2;
D *= D;
P = c2 / D;
} else {
c1 = f * M;
c2 = f4 * (1. - M * M);
D = (1. - c2)*(1. - c2 - c1 * M);
P = (1. + .5 * c1 * M) * c2 / D;
}
}
if (merid) s1 = HALFPI - th1;
else {
s1 = (fabs(M) >= 1.) ? 0. : acos(M);
s1 = sinth1 / sin(s1);
s1 = (fabs(s1) >= 1.) ? 0. : acos(s1);
}
}
void
geod_for(void) {
double d,sind,u,V,X,ds,cosds,sinds,ss,de;
if (ellipse) {
d = S / (D * a);
if (signS) d = -d;
u = 2. * (s1 - d);
V = cos(u + d);
X = c2 * c2 * (sind = sin(d)) * cos(d) * (2. * V * V - 1.);
ds = d + X - 2. * P * V * (1. - 2. * P * cos(u)) * sind;
ss = s1 + s1 - ds;
} else {
ds = S / a;
if (signS) ds = - ds;
}
cosds = cos(ds);
sinds = sin(ds);
if (signS) sinds = - sinds;
al21 = N * cosds - sinth1 * sinds;
if (merid) {
phi2 = atan( tan(HALFPI + s1 - ds) / onef);
if (al21 > 0.) {
al21 = PI;
if (signS)
de = PI;
else {
phi2 = - phi2;
de = 0.;
}
} else {
al21 = 0.;
if (signS) {
phi2 = - phi2;
de = 0;
} else
de = PI;
}
} else {
al21 = atan(M / al21);
if (al21 > 0)
al21 += PI;
if (al12 < 0.)
al21 -= PI;
al21 = adjlon(al21);
phi2 = atan(-(sinth1 * cosds + N * sinds) * sin(al21) /
(ellipse ? onef * M : M));
de = atan2(sinds * sina12 ,
(costh1 * cosds - sinth1 * sinds * cosa12));
if (ellipse)
if (signS)
de += c1 * ((1. - c2) * ds +
c2 * sinds * cos(ss));
else
de -= c1 * ((1. - c2) * ds -
c2 * sinds * cos(ss));
}
lam2 = adjlon( lam1 + de );
}
|
609873.c | /**
******************************************************************************
* @file USB_Device/MSC_Standalone/Src/usbd_storage.c
* @author MCD Application Team
* @version V1.0.3
* @date 22-April-2016
* @brief Memory management layer
******************************************************************************
* @attention
*
* <h2><center>© Copyright (c) 2016 STMicroelectronics International N.V.
* All rights reserved.</center></h2>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted, provided that the following conditions are met:
*
* 1. Redistribution of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. Neither the name of STMicroelectronics nor the names of other
* contributors to this software may be used to endorse or promote products
* derived from this software without specific written permission.
* 4. This software, including modifications and/or derivative works of this
* software, must execute solely and exclusively on microcontroller or
* microprocessor devices manufactured by or for STMicroelectronics.
* 5. Redistribution and use of this software other than as permitted under
* this license is void and will automatically terminate your rights under
* this license.
*
* THIS SOFTWARE IS PROVIDED BY STMICROELECTRONICS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS, IMPLIED OR STATUTORY WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
* PARTICULAR PURPOSE AND NON-INFRINGEMENT OF THIRD PARTY INTELLECTUAL PROPERTY
* RIGHTS ARE DISCLAIMED TO THE FULLEST EXTENT PERMITTED BY LAW. IN NO EVENT
* SHALL STMICROELECTRONICS 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.
*
******************************************************************************
*/
/* Includes ------------------------------------------------------------------*/
#include "usbd_storage.h"
#include "stm32746g_discovery_sd.h"
/* Private typedef -----------------------------------------------------------*/
/* Private define ------------------------------------------------------------*/
#define STORAGE_LUN_NBR 1
#define STORAGE_BLK_NBR 0x10000
#define STORAGE_BLK_SIZ 0x200
/* Private macro -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
/* USB Mass storage Standard Inquiry Data */
int8_t STORAGE_Inquirydata[] = { /* 36 */
/* LUN 0 */
0x00,
0x80,
0x02,
0x02,
(STANDARD_INQUIRY_DATA_LEN - 5),
0x00,
0x00,
0x00,
'S', 'T', 'M', ' ', ' ', ' ', ' ', ' ', /* Manufacturer: 8 bytes */
'P', 'r', 'o', 'd', 'u', 'c', 't', ' ', /* Product : 16 Bytes */
' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
'0', '.', '0','1', /* Version : 4 Bytes */
};
/* Private function prototypes -----------------------------------------------*/
int8_t STORAGE_Init(uint8_t lun);
int8_t STORAGE_GetCapacity(uint8_t lun, uint32_t *block_num, uint16_t *block_size);
int8_t STORAGE_IsReady(uint8_t lun);
int8_t STORAGE_IsWriteProtected(uint8_t lun);
int8_t STORAGE_Read(uint8_t lun, uint8_t *buf, uint32_t blk_addr, uint16_t blk_len);
int8_t STORAGE_Write(uint8_t lun, uint8_t *buf, uint32_t blk_addr, uint16_t blk_len);
int8_t STORAGE_GetMaxLun(void);
USBD_StorageTypeDef USBD_DISK_fops = {
STORAGE_Init,
STORAGE_GetCapacity,
STORAGE_IsReady,
STORAGE_IsWriteProtected,
STORAGE_Read,
STORAGE_Write,
STORAGE_GetMaxLun,
STORAGE_Inquirydata,
};
/* Private functions ---------------------------------------------------------*/
/**
* @brief Initializes the storage unit (medium)
* @param lun: Logical unit number
* @retval Status (0 : OK / -1 : Error)
*/
int8_t STORAGE_Init(uint8_t lun)
{
BSP_SD_Init();
return 0;
}
/**
* @brief Returns the medium capacity.
* @param lun: Logical unit number
* @param block_num: Number of total block number
* @param block_size: Block size
* @retval Status (0: OK / -1: Error)
*/
int8_t STORAGE_GetCapacity(uint8_t lun, uint32_t *block_num, uint16_t *block_size)
{
HAL_SD_CardInfoTypedef info;
int8_t ret = -1;
if(BSP_SD_IsDetected() != SD_NOT_PRESENT)
{
BSP_SD_GetCardInfo(&info);
*block_num = (info.CardCapacity)/STORAGE_BLK_SIZ - 1;
*block_size = STORAGE_BLK_SIZ;
ret = 0;
}
return ret;
}
/**
* @brief Checks whether the medium is ready.
* @param lun: Logical unit number
* @retval Status (0: OK / -1: Error)
*/
int8_t STORAGE_IsReady(uint8_t lun)
{
static int8_t prev_status = 0;
int8_t ret = -1;
if(BSP_SD_IsDetected() != SD_NOT_PRESENT)
{
if(prev_status < 0)
{
BSP_SD_Init();
prev_status = 0;
}
if(BSP_SD_GetStatus() == SD_TRANSFER_OK)
{
ret = 0;
}
}
else if(prev_status == 0)
{
prev_status = -1;
}
return ret;
}
/**
* @brief Checks whether the medium is write protected.
* @param lun: Logical unit number
* @retval Status (0: write enabled / -1: otherwise)
*/
int8_t STORAGE_IsWriteProtected(uint8_t lun)
{
return 0;
}
/**
* @brief Reads data from the medium.
* @param lun: Logical unit number
* @param blk_addr: Logical block address
* @param blk_len: Blocks number
* @retval Status (0: OK / -1: Error)
*/
int8_t STORAGE_Read(uint8_t lun, uint8_t *buf, uint32_t blk_addr, uint16_t blk_len)
{
int8_t ret = -1;
if(BSP_SD_IsDetected() != SD_NOT_PRESENT)
{
BSP_SD_ReadBlocks_DMA((uint32_t *)buf, blk_addr * STORAGE_BLK_SIZ, STORAGE_BLK_SIZ, blk_len);
ret = 0;
SCB_InvalidateDCache_by_Addr((uint32_t*)buf, (int32_t)(STORAGE_BLK_SIZ * blk_len));
}
return ret;
}
/**
* @brief Writes data into the medium.
* @param lun: Logical unit number
* @param blk_addr: Logical block address
* @param blk_len: Blocks number
* @retval Status (0 : OK / -1 : Error)
*/
int8_t STORAGE_Write(uint8_t lun, uint8_t *buf, uint32_t blk_addr, uint16_t blk_len)
{
int8_t ret = -1;
if(BSP_SD_IsDetected() != SD_NOT_PRESENT)
{
SCB_CleanDCache_by_Addr((uint32_t*)buf, (int32_t)(STORAGE_BLK_SIZ * blk_len));
BSP_SD_WriteBlocks_DMA((uint32_t *)buf, blk_addr * STORAGE_BLK_SIZ, STORAGE_BLK_SIZ, blk_len);
ret = 0;
}
return ret;
}
/**
* @brief Returns the Max Supported LUNs.
* @param None
* @retval Lun(s) number
*/
int8_t STORAGE_GetMaxLun(void)
{
return(STORAGE_LUN_NBR - 1);
}
/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
|
644824.c | /**
* Copyright (c) 2014 - 2017, Nordic Semiconductor ASA
*
* 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, except as embedded into a Nordic
* Semiconductor ASA integrated circuit in a product or a software update for
* such product, must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other
* materials provided with the distribution.
*
* 3. Neither the name of Nordic Semiconductor ASA nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* 4. This software, with or without modification, must only be used with a
* Nordic Semiconductor ASA integrated circuit.
*
* 5. Any software provided in binary form under this license must not be reverse
* engineered, decompiled, modified and/or disassembled.
*
* THIS SOFTWARE IS PROVIDED BY NORDIC SEMICONDUCTOR ASA "AS IS" AND ANY EXPRESS
* OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY, NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL NORDIC SEMICONDUCTOR ASA 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.
*
*/
/**
* @brief BLE LED Button Service central and client application main file.
*
* This file contains the source code for a sample client application using the LED Button service.
*/
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include "nordic_common.h"
#include "softdevice_handler.h"
#include "app_timer.h"
#include "boards.h"
#include "bsp.h"
#include "bsp_btn_ble.h"
#include "ble.h"
#include "ble_hci.h"
#include "ble_advdata.h"
#include "ble_advertising.h"
#include "ble_conn_params.h"
#include "ble_db_discovery.h"
#include "ble_lbs_c.h"
#define NRF_LOG_MODULE_NAME "APP"
#include "nrf_log.h"
#include "nrf_log_ctrl.h"
#define CENTRAL_LINK_COUNT 1 /**< Number of central links used by the application. When changing this number remember to adjust the RAM settings*/
#define PERIPHERAL_LINK_COUNT 0 /**< Number of peripheral links used by the application. When changing this number remember to adjust the RAM settings*/
#if (NRF_SD_BLE_API_VERSION == 3)
#define NRF_BLE_MAX_MTU_SIZE GATT_MTU_SIZE_DEFAULT /**< MTU size used in the softdevice enabling and to reply to a BLE_GATTS_EVT_EXCHANGE_MTU_REQUEST event. */
#endif
#define CENTRAL_SCANNING_LED BSP_BOARD_LED_0 /**< Scanning LED will be on when the device is scanning. */
#define CENTRAL_CONNECTED_LED BSP_BOARD_LED_1 /**< Connected LED will be on when the device is connected. */
#define APP_TIMER_PRESCALER 0 /**< Value of the RTC1 PRESCALER register. */
#define APP_TIMER_OP_QUEUE_SIZE 2 /**< Size of timer operation queues. */
#define SEC_PARAM_BOND 1 /**< Perform bonding. */
#define SEC_PARAM_MITM 0 /**< Man In The Middle protection not required. */
#define SEC_PARAM_IO_CAPABILITIES BLE_GAP_IO_CAPS_NONE /**< No I/O capabilities. */
#define SEC_PARAM_OOB 0 /**< Out Of Band data not available. */
#define SEC_PARAM_MIN_KEY_SIZE 7 /**< Minimum encryption key size in octets. */
#define SEC_PARAM_MAX_KEY_SIZE 16 /**< Maximum encryption key size in octets. */
#define SCAN_INTERVAL 0x00A0 /**< Determines scan interval in units of 0.625 millisecond. */
#define SCAN_WINDOW 0x0050 /**< Determines scan window in units of 0.625 millisecond. */
#define SCAN_TIMEOUT 0x0000 /**< Timout when scanning. 0x0000 disables timeout. */
#define MIN_CONNECTION_INTERVAL MSEC_TO_UNITS(7.5, UNIT_1_25_MS) /**< Determines minimum connection interval in milliseconds. */
#define MAX_CONNECTION_INTERVAL MSEC_TO_UNITS(30, UNIT_1_25_MS) /**< Determines maximum connection interval in milliseconds. */
#define SLAVE_LATENCY 0 /**< Determines slave latency in terms of connection events. */
#define SUPERVISION_TIMEOUT MSEC_TO_UNITS(4000, UNIT_10_MS) /**< Determines supervision time-out in units of 10 milliseconds. */
#define UUID16_SIZE 2 /**< Size of a UUID, in bytes. */
#define LEDBUTTON_LED BSP_BOARD_LED_2 /**< LED to indicate a change of state of the the Button characteristic on the peer. */
#define LEDBUTTON_BUTTON_PIN BSP_BUTTON_0 /**< Button that will write to the LED characteristic of the peer */
#define BUTTON_DETECTION_DELAY APP_TIMER_TICKS(50, APP_TIMER_PRESCALER) /**< Delay from a GPIOTE event until a button is reported as pushed (in number of timer ticks). */
static const char m_target_periph_name[] = "Nordic_Blinky"; /**< Name of the device we try to connect to. This name is searched in the scan report data*/
/**@brief Variable length data encapsulation in terms of length and pointer to data. */
typedef struct
{
uint8_t * p_data; /**< Pointer to data. */
uint16_t data_len; /**< Length of data. */
} data_t;
/**
* @brief Parameters used when scanning.
*/
static const ble_gap_scan_params_t m_scan_params =
{
.active = 1,
.interval = SCAN_INTERVAL,
.window = SCAN_WINDOW,
.timeout = SCAN_TIMEOUT,
#if (NRF_SD_BLE_API_VERSION == 2)
.selective = 0,
.p_whitelist = NULL,
#endif
#if (NRF_SD_BLE_API_VERSION == 3)
.use_whitelist = 0,
#endif
};
/**@brief Connection parameters requested for connection. */
static const ble_gap_conn_params_t m_connection_param =
{
(uint16_t)MIN_CONNECTION_INTERVAL,
(uint16_t)MAX_CONNECTION_INTERVAL,
(uint16_t)SLAVE_LATENCY,
(uint16_t)SUPERVISION_TIMEOUT
};
static ble_lbs_c_t m_ble_lbs_c; /**< Main structure used by the LBS client module. */
static ble_db_discovery_t m_ble_db_discovery; /**< DB structure used by the database discovery module. */
/**@brief Function to handle asserts in the SoftDevice.
*
* @details This function will be called in case of an assert in the SoftDevice.
*
* @warning This handler is an example only and does not fit a final product. You need to analyze
* how your product is supposed to react in case of Assert.
* @warning On assert from the SoftDevice, the system can only recover on reset.
*
* @param[in] line_num Line number of the failing ASSERT call.
* @param[in] p_file_name File name of the failing ASSERT call.
*/
void assert_nrf_callback(uint16_t line_num, const uint8_t * p_file_name)
{
app_error_handler(0xDEADBEEF, line_num, p_file_name);
}
/**@brief Function for the LEDs initialization.
*
* @details Initializes all LEDs used by the application.
*/
static void leds_init(void)
{
bsp_board_leds_init();
}
/**
* @brief Parses advertisement data, providing length and location of the field in case
* matching data is found.
*
* @param[in] type Type of data to be looked for in advertisement data.
* @param[in] p_advdata Advertisement report length and pointer to report.
* @param[out] p_typedata If data type requested is found in the data report, type data length and
* pointer to data will be populated here.
*
* @retval NRF_SUCCESS if the data type is found in the report.
* @retval NRF_ERROR_NOT_FOUND if the data type could not be found.
*/
static uint32_t adv_report_parse(uint8_t type, data_t * p_advdata, data_t * p_typedata)
{
uint32_t index = 0;
uint8_t * p_data;
p_data = p_advdata->p_data;
while (index < p_advdata->data_len)
{
uint8_t field_length = p_data[index];
uint8_t field_type = p_data[index + 1];
if (field_type == type)
{
p_typedata->p_data = &p_data[index + 2];
p_typedata->data_len = field_length - 1;
return NRF_SUCCESS;
}
index += field_length + 1;
}
return NRF_ERROR_NOT_FOUND;
}
/**@brief Function to start scanning.
*/
static void scan_start(void)
{
ret_code_t err_code;
(void) sd_ble_gap_scan_stop();
err_code = sd_ble_gap_scan_start(&m_scan_params);
APP_ERROR_CHECK(err_code);
bsp_board_led_off(CENTRAL_CONNECTED_LED);
bsp_board_led_on(CENTRAL_SCANNING_LED);
}
/**@brief Handles events coming from the LED Button central module.
*/
static void lbs_c_evt_handler(ble_lbs_c_t * p_lbs_c, ble_lbs_c_evt_t * p_lbs_c_evt)
{
switch (p_lbs_c_evt->evt_type)
{
case BLE_LBS_C_EVT_DISCOVERY_COMPLETE:
{
ret_code_t err_code;
err_code = ble_lbs_c_handles_assign(&m_ble_lbs_c,
p_lbs_c_evt->conn_handle,
&p_lbs_c_evt->params.peer_db);
NRF_LOG_INFO("LED Button service discovered on conn_handle 0x%x.\r\n", p_lbs_c_evt->conn_handle);
err_code = app_button_enable();
APP_ERROR_CHECK(err_code);
// LED Button service discovered. Enable notification of Button.
err_code = ble_lbs_c_button_notif_enable(p_lbs_c);
APP_ERROR_CHECK(err_code);
} break; // BLE_LBS_C_EVT_DISCOVERY_COMPLETE
case BLE_LBS_C_EVT_BUTTON_NOTIFICATION:
{
NRF_LOG_INFO("Button state changed on peer to 0x%x.\r\n", p_lbs_c_evt->params.button.button_state);
if (p_lbs_c_evt->params.button.button_state)
{
bsp_board_led_on(LEDBUTTON_LED);
}
else
{
bsp_board_led_off(LEDBUTTON_LED);
}
} break; // BLE_LBS_C_EVT_BUTTON_NOTIFICATION
default:
// No implementation needed.
break;
}
}
/**@brief Function for handling the advertising report BLE event.
*
* @param[in] p_ble_evt Bluetooth stack event.
*/
static void on_adv_report(const ble_evt_t * const p_ble_evt)
{
uint32_t err_code;
data_t adv_data;
bool do_connect = false;
data_t dev_name;
// For readibility.
const ble_gap_evt_t * const p_gap_evt = &p_ble_evt->evt.gap_evt;
const ble_gap_addr_t * const peer_addr = &p_gap_evt->params.adv_report.peer_addr;
{
// Initialize advertisement report for parsing
adv_data.p_data = (uint8_t *)p_gap_evt->params.adv_report.data;
adv_data.data_len = p_gap_evt->params.adv_report.dlen;
//search for advertising names
bool found_name = false;
err_code = adv_report_parse(BLE_GAP_AD_TYPE_COMPLETE_LOCAL_NAME,
&adv_data,
&dev_name);
if (err_code != NRF_SUCCESS)
{
// Look for the short local name if it was not found as complete
err_code = adv_report_parse(BLE_GAP_AD_TYPE_SHORT_LOCAL_NAME,
&adv_data,
&dev_name);
if (err_code != NRF_SUCCESS)
{
// If we can't parse the data, then exit
return;
}
else
{
found_name = true;
}
}
else
{
found_name = true;
}
if (found_name)
{
if (strlen(m_target_periph_name) != 0)
{
if (memcmp(m_target_periph_name, dev_name.p_data, dev_name.data_len )== 0)
{
do_connect = true;
}
}
}
}
if (do_connect)
{
// Initiate connection.
err_code = sd_ble_gap_connect(peer_addr, &m_scan_params, &m_connection_param);
APP_ERROR_CHECK(err_code);
}
}
/**@brief Function for handling BLE Stack events concerning central applications.
*
* @details This function keeps the connection handles of central applications up-to-date. It
* parses scanning reports, initiating a connection attempt to peripherals when a target UUID
* is found, and manages connection parameter update requests. Additionally, it updates the status
* of LEDs used to report central applications activity.
*
* @note Since this function updates connection handles, @ref BLE_GAP_EVT_DISCONNECTED events
* should be dispatched to the target application before invoking this function.
*
* @param[in] p_ble_evt Bluetooth stack event.
*/
static void on_ble_evt(const ble_evt_t * const p_ble_evt)
{
ret_code_t err_code;
// For readability.
const ble_gap_evt_t * const p_gap_evt = &p_ble_evt->evt.gap_evt;
switch (p_ble_evt->header.evt_id)
{
// Upon connection, check which peripheral has connected (HR or RSC), initiate DB
// discovery, update LEDs status and resume scanning if necessary. */
case BLE_GAP_EVT_CONNECTED:
{
NRF_LOG_INFO("Connected.\r\n");
err_code = ble_lbs_c_handles_assign(&m_ble_lbs_c, p_gap_evt->conn_handle, NULL);
APP_ERROR_CHECK(err_code);
err_code = ble_db_discovery_start(&m_ble_db_discovery, p_gap_evt->conn_handle);
APP_ERROR_CHECK(err_code);
// Update LEDs status, and check if we should be looking for more
// peripherals to connect to.
bsp_board_led_on(CENTRAL_CONNECTED_LED);
bsp_board_led_off(CENTRAL_SCANNING_LED);
} break;
// Upon disconnection, reset the connection handle of the peer which disconnected, update
// the LEDs status and start scanning again.
case BLE_GAP_EVT_DISCONNECTED:
{
NRF_LOG_INFO("Disconnected.\r\n");
scan_start();
} break;
case BLE_GAP_EVT_ADV_REPORT:
{
on_adv_report(p_ble_evt);
} break;
case BLE_GAP_EVT_TIMEOUT:
{
// We have not specified a timeout for scanning, so only connection attemps can timeout.
if (p_gap_evt->params.timeout.src == BLE_GAP_TIMEOUT_SRC_CONN)
{
NRF_LOG_DEBUG("Connection request timed out.\r\n");
}
} break;
case BLE_GAP_EVT_CONN_PARAM_UPDATE_REQUEST:
{
// Accept parameters requested by peer.
err_code = sd_ble_gap_conn_param_update(p_gap_evt->conn_handle,
&p_gap_evt->params.conn_param_update_request.conn_params);
APP_ERROR_CHECK(err_code);
} break;
case BLE_GATTC_EVT_TIMEOUT:
{
// Disconnect on GATT Client timeout event.
NRF_LOG_DEBUG("GATT Client Timeout.\r\n");
err_code = sd_ble_gap_disconnect(p_ble_evt->evt.gattc_evt.conn_handle,
BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
APP_ERROR_CHECK(err_code);
} break;
case BLE_GATTS_EVT_TIMEOUT:
{
// Disconnect on GATT Server timeout event.
NRF_LOG_DEBUG("GATT Server Timeout.\r\n");
err_code = sd_ble_gap_disconnect(p_ble_evt->evt.gatts_evt.conn_handle,
BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
APP_ERROR_CHECK(err_code);
} break;
#if (NRF_SD_BLE_API_VERSION == 3)
case BLE_GATTS_EVT_EXCHANGE_MTU_REQUEST:
{
err_code = sd_ble_gatts_exchange_mtu_reply(p_ble_evt->evt.gatts_evt.conn_handle,
NRF_BLE_MAX_MTU_SIZE);
APP_ERROR_CHECK(err_code);
} break;
#endif
default:
// No implementation needed.
break;
}
}
/**@brief Function for dispatching a BLE stack event to all modules with a BLE stack event handler.
*
* @details This function is called from the scheduler in the main loop after a BLE stack event has
* been received.
*
* @param[in] p_ble_evt Bluetooth stack event.
*/
static void ble_evt_dispatch(ble_evt_t * p_ble_evt)
{
on_ble_evt(p_ble_evt);
ble_db_discovery_on_ble_evt(&m_ble_db_discovery, p_ble_evt);
ble_lbs_c_on_ble_evt(&m_ble_lbs_c, p_ble_evt);
}
/**@brief LED Button client initialization.
*/
static void lbs_c_init(void)
{
uint32_t err_code;
ble_lbs_c_init_t lbs_c_init_obj;
lbs_c_init_obj.evt_handler = lbs_c_evt_handler;
err_code = ble_lbs_c_init(&m_ble_lbs_c, &lbs_c_init_obj);
APP_ERROR_CHECK(err_code);
}
/**@brief Function for initializing the BLE stack.
*
* @details Initializes the SoftDevice and the BLE event interrupts.
*/
static void ble_stack_init(void)
{
ret_code_t err_code;
nrf_clock_lf_cfg_t clock_lf_cfg = NRF_CLOCK_LFCLKSRC;
// Initialize the SoftDevice handler module.
SOFTDEVICE_HANDLER_INIT(&clock_lf_cfg, NULL);
ble_enable_params_t ble_enable_params;
err_code = softdevice_enable_get_default_config(CENTRAL_LINK_COUNT,
PERIPHERAL_LINK_COUNT,
&ble_enable_params);
APP_ERROR_CHECK(err_code);
//Check the ram settings against the used number of links
CHECK_RAM_START_ADDR(CENTRAL_LINK_COUNT,PERIPHERAL_LINK_COUNT);
// Enable BLE stack.
#if (NRF_SD_BLE_API_VERSION == 3)
ble_enable_params.gatt_enable_params.att_mtu = NRF_BLE_MAX_MTU_SIZE;
#endif
err_code = softdevice_enable(&ble_enable_params);
APP_ERROR_CHECK(err_code);
// Register with the SoftDevice handler module for BLE events.
err_code = softdevice_ble_evt_handler_set(ble_evt_dispatch);
APP_ERROR_CHECK(err_code);
}
/**@brief Function for handling events from the button handler module.
*
* @param[in] pin_no The pin that the event applies to.
* @param[in] button_action The button action (press/release).
*/
static void button_event_handler(uint8_t pin_no, uint8_t button_action)
{
uint32_t err_code;
switch (pin_no)
{
case LEDBUTTON_BUTTON_PIN:
err_code = ble_lbs_led_status_send(&m_ble_lbs_c, button_action);
if (err_code != NRF_SUCCESS &&
err_code != BLE_ERROR_INVALID_CONN_HANDLE &&
err_code != NRF_ERROR_INVALID_STATE)
{
APP_ERROR_CHECK(err_code);
}
if (err_code == NRF_SUCCESS)
{
NRF_LOG_INFO("LBS write LED state %d\r\n", button_action);
}
break;
default:
APP_ERROR_HANDLER(pin_no);
break;
}
}
/**@brief Function for initializing the button handler module.
*/
static void buttons_init(void)
{
uint32_t err_code;
//The array must be static because a pointer to it will be saved in the button handler module.
static app_button_cfg_t buttons[] =
{
{LEDBUTTON_BUTTON_PIN, false, BUTTON_PULL, button_event_handler}
};
err_code = app_button_init(buttons, sizeof(buttons) / sizeof(buttons[0]),
BUTTON_DETECTION_DELAY);
APP_ERROR_CHECK(err_code);
}
/**@brief Function for handling database discovery events.
*
* @details This function is callback function to handle events from the database discovery module.
* Depending on the UUIDs that are discovered, this function should forward the events
* to their respective services.
*
* @param[in] p_event Pointer to the database discovery event.
*/
static void db_disc_handler(ble_db_discovery_evt_t * p_evt)
{
ble_lbs_on_db_disc_evt(&m_ble_lbs_c, p_evt);
}
/**
* @brief Database discovery initialization.
*/
static void db_discovery_init(void)
{
ret_code_t err_code = ble_db_discovery_init(db_disc_handler);
APP_ERROR_CHECK(err_code);
}
/** @brief Function to sleep until a BLE event is received by the application.
*/
static void power_manage(void)
{
ret_code_t err_code = sd_app_evt_wait();
APP_ERROR_CHECK(err_code);
}
int main(void)
{
ret_code_t err_code;
err_code = NRF_LOG_INIT(NULL);
APP_ERROR_CHECK(err_code);
leds_init();
APP_TIMER_INIT(APP_TIMER_PRESCALER, APP_TIMER_OP_QUEUE_SIZE, NULL);
buttons_init();
ble_stack_init();
db_discovery_init();
lbs_c_init();
// Start scanning for peripherals and initiate connection to devices which
// advertise.
scan_start();
NRF_LOG_INFO("\r\nBlinky Start!\r\n");
// Turn on the LED to signal scanning.
bsp_board_led_on(CENTRAL_SCANNING_LED);
for (;;)
{
if (NRF_LOG_PROCESS() == false)
{
// Wait for BLE events.
power_manage();
}
}
}
|
383279.c | //------------------------------------------------------------------------------
// GB_AxB: hard-coded functions for semiring: C<M>=A*B or A'*B
//------------------------------------------------------------------------------
// 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.h"
#ifndef GBCOMPACT
#include "GB_control.h"
#include "GB_ek_slice.h"
#include "GB_bracket.h"
#include "GB_sort.h"
#include "GB_atomics.h"
#include "GB_AxB_saxpy3.h"
#include "GB_AxB__include.h"
#include "GB_unused.h"
#include "GB_bitmap_assign_methods.h"
// The C=A*B semiring is defined by the following types and operators:
// A'*B function (dot2): GB_Adot2B__plus_isne_fp32
// A'*B function (dot3): GB_Adot3B__plus_isne_fp32
// C+=A'*B function (dot4): GB_Adot4B__plus_isne_fp32
// A*B function (saxpy3): GB_Asaxpy3B__plus_isne_fp32
// C type: float
// A type: float
// B type: float
// Multiply: z = (aik != bkj)
// Add: cij += z
// 'any' monoid? 0
// atomic? 1
// OpenMP atomic? 1
// MultAdd: cij += (aik != bkj)
// Identity: 0
// Terminal: ;
#define GB_ATYPE \
float
#define GB_BTYPE \
float
#define GB_CTYPE \
float
#define GB_ASIZE (sizeof (GB_BTYPE))
#define GB_BSIZE (sizeof (GB_BTYPE))
#define GB_CSIZE (sizeof (GB_CTYPE))
// true for int64, uint64, float, double, float complex, and double complex
#define GB_CTYPE_IGNORE_OVERFLOW \
1
// aik = Ax [pA]
#define GB_GETA(aik,Ax,pA) \
float aik = Ax [pA]
// bkj = Bx [pB]
#define GB_GETB(bkj,Bx,pB) \
float bkj = Bx [pB]
// Gx [pG] = Ax [pA]
#define GB_LOADA(Gx,pG,Ax,pA) \
Gx [pG] = Ax [pA]
// Gx [pG] = Bx [pB]
#define GB_LOADB(Gx,pG,Bx,pB) \
Gx [pG] = Bx [pB]
#define GB_CX(p) Cx [p]
// multiply operator
#define GB_MULT(z, x, y, i, k, j) \
z = (x != y)
// cast from a real scalar (or 2, if C is complex) to the type of C
#define GB_CTYPE_CAST(x,y) \
((float) x)
// cast from a real scalar (or 2, if A is complex) to the type of A
#define GB_ATYPE_CAST(x,y) \
((float) x)
// multiply-add
#define GB_MULTADD(z, x, y, i, k, j) \
z += (x != y)
// monoid identity value
#define GB_IDENTITY \
0
// 1 if the identity value can be assigned via memset, with all bytes the same
#define GB_HAS_IDENTITY_BYTE \
1
// identity byte, for memset
#define GB_IDENTITY_BYTE \
0
// break if cij reaches the terminal value (dot product only)
#define GB_DOT_TERMINAL(cij) \
;
// simd pragma for dot-product loop vectorization
#define GB_PRAGMA_SIMD_DOT(cij) \
GB_PRAGMA_SIMD_REDUCTION (+,cij)
// simd pragma for other loop vectorization
#define GB_PRAGMA_SIMD_VECTORIZE GB_PRAGMA_SIMD
// 1 for the PLUS_PAIR_(real) semirings, not for the complex case
#define GB_IS_PLUS_PAIR_REAL_SEMIRING \
0
// 1 for performance-critical semirings, which get extra optimization
#define GB_IS_PERFORMANCE_CRITICAL_SEMIRING \
0
// declare the cij scalar
#if GB_IS_PLUS_PAIR_REAL_SEMIRING
// also initialize cij to zero
#define GB_CIJ_DECLARE(cij) \
float cij = 0
#else
// all other semirings: just declare cij, do not initialize it
#define GB_CIJ_DECLARE(cij) \
float cij
#endif
// cij = Cx [pC]
#define GB_GETC(cij,p) cij = Cx [p]
// Cx [pC] = cij
#define GB_PUTC(cij,p) Cx [p] = cij
// Cx [p] = t
#define GB_CIJ_WRITE(p,t) Cx [p] = t
// C(i,j) += t
#define GB_CIJ_UPDATE(p,t) \
Cx [p] += t
// x + y
#define GB_ADD_FUNCTION(x,y) \
x + y
// bit pattern for bool, 8-bit, 16-bit, and 32-bit integers
#define GB_CTYPE_BITS \
0
// 1 if monoid update can skipped entirely (the ANY monoid)
#define GB_IS_ANY_MONOID \
0
// 1 if monoid update is EQ
#define GB_IS_EQ_MONOID \
0
// 1 if monoid update can be done atomically, 0 otherwise
#define GB_HAS_ATOMIC \
1
// 1 if monoid update can be done with an OpenMP atomic update, 0 otherwise
#if GB_MICROSOFT
#define GB_HAS_OMP_ATOMIC \
1
#else
#define GB_HAS_OMP_ATOMIC \
1
#endif
// 1 for the ANY_PAIR semirings
#define GB_IS_ANY_PAIR_SEMIRING \
0
// 1 if PAIR is the multiply operator
#define GB_IS_PAIR_MULTIPLIER \
0
// 1 if monoid is PLUS_FC32
#define GB_IS_PLUS_FC32_MONOID \
0
// 1 if monoid is PLUS_FC64
#define GB_IS_PLUS_FC64_MONOID \
0
// 1 if monoid is ANY_FC32
#define GB_IS_ANY_FC32_MONOID \
0
// 1 if monoid is ANY_FC64
#define GB_IS_ANY_FC64_MONOID \
0
// 1 if monoid is MIN for signed or unsigned integers
#define GB_IS_IMIN_MONOID \
0
// 1 if monoid is MAX for signed or unsigned integers
#define GB_IS_IMAX_MONOID \
0
// 1 if monoid is MIN for float or double
#define GB_IS_FMIN_MONOID \
0
// 1 if monoid is MAX for float or double
#define GB_IS_FMAX_MONOID \
0
// 1 for the FIRSTI or FIRSTI1 multiply operator
#define GB_IS_FIRSTI_MULTIPLIER \
0
// 1 for the FIRSTJ or FIRSTJ1 multiply operator
#define GB_IS_FIRSTJ_MULTIPLIER \
0
// 1 for the SECONDJ or SECONDJ1 multiply operator
#define GB_IS_SECONDJ_MULTIPLIER \
0
// atomic compare-exchange
#define GB_ATOMIC_COMPARE_EXCHANGE(target, expected, desired) \
GB_ATOMIC_COMPARE_EXCHANGE_32 (target, expected, desired)
#if GB_IS_ANY_PAIR_SEMIRING
// result is purely symbolic; no numeric work to do. Hx is not used.
#define GB_HX_WRITE(i,t)
#define GB_CIJ_GATHER(p,i)
#define GB_CIJ_GATHER_UPDATE(p,i)
#define GB_HX_UPDATE(i,t)
#define GB_CIJ_MEMCPY(p,i,len)
#else
// Hx [i] = t
#define GB_HX_WRITE(i,t) Hx [i] = t
// Cx [p] = Hx [i]
#define GB_CIJ_GATHER(p,i) Cx [p] = Hx [i]
// Cx [p] += Hx [i]
#define GB_CIJ_GATHER_UPDATE(p,i) \
Cx [p] += Hx [i]
// Hx [i] += t
#define GB_HX_UPDATE(i,t) \
Hx [i] += t
// memcpy (&(Cx [p]), &(Hx [i]), len)
#define GB_CIJ_MEMCPY(p,i,len) \
memcpy (Cx +(p), Hx +(i), (len) * sizeof(float))
#endif
// 1 if the semiring has a concise bitmap multiply-add
#define GB_HAS_BITMAP_MULTADD \
1
// concise statement(s) for the bitmap case:
// if (exists)
// if (cb == 0)
// cx = ax * bx
// cb = 1
// else
// cx += ax * bx
#define GB_BITMAP_MULTADD(cb,cx,exists,ax,bx) \
cx += ((ax != bx)) * X [exists] ; cb |= exists
// define X for bitmap multiply-add
#define GB_XINIT \
float X [2] = {0,1}
// load X [1] = bkj for bitmap multiply-add
#define GB_XLOAD(bkj) \
;
// disable this semiring and use the generic case if these conditions hold
#define GB_DISABLE \
(GxB_NO_PLUS || GxB_NO_ISNE || GxB_NO_FP32 || GxB_NO_PLUS_FP32 || GxB_NO_ISNE_FP32 || GxB_NO_PLUS_ISNE_FP32)
//------------------------------------------------------------------------------
// C=A'*B, C<M>=A'*B, or C<!M>=A'*B: dot product method where C is bitmap
//------------------------------------------------------------------------------
GrB_Info GB_Adot2B__plus_isne_fp32
(
GrB_Matrix C,
const GrB_Matrix M, const bool Mask_comp, const bool Mask_struct,
const GrB_Matrix A, bool A_is_pattern, int64_t *GB_RESTRICT A_slice,
const GrB_Matrix B, bool B_is_pattern, int64_t *GB_RESTRICT B_slice,
int nthreads, int naslice, int nbslice
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_AxB_dot2_meta.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C<M>=A'*B: masked dot product method (phase 2) where C is sparse or hyper
//------------------------------------------------------------------------------
GrB_Info GB_Adot3B__plus_isne_fp32
(
GrB_Matrix C,
const GrB_Matrix M, const bool Mask_struct,
const GrB_Matrix A, bool A_is_pattern,
const GrB_Matrix B, bool B_is_pattern,
const GB_task_struct *GB_RESTRICT TaskList,
const int ntasks,
const int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_AxB_dot3_meta.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C+=A'*B: dense dot product
//------------------------------------------------------------------------------
GrB_Info GB_Adot4B__plus_isne_fp32
(
GrB_Matrix C,
const GrB_Matrix A, bool A_is_pattern,
int64_t *GB_RESTRICT A_slice, int naslice,
const GrB_Matrix B, bool B_is_pattern,
int64_t *GB_RESTRICT B_slice, int nbslice,
const int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_AxB_dot4_meta.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C=A*B, C<M>=A*B, C<!M>=A*B: saxpy3 method (Gustavson + Hash)
//------------------------------------------------------------------------------
#include "GB_AxB_saxpy3_template.h"
GrB_Info GB_Asaxpy3B__plus_isne_fp32
(
GrB_Matrix C,
const GrB_Matrix M, const bool Mask_comp, const bool Mask_struct,
const bool M_dense_in_place,
const GrB_Matrix A, bool A_is_pattern,
const GrB_Matrix B, bool B_is_pattern,
GB_saxpy3task_struct *GB_RESTRICT TaskList,
int ntasks,
int nfine,
int nthreads,
const int do_sort,
GB_Context Context
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_AxB_saxpy_template.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
|
837639.c | /*
* Copyright 1998 Massachusetts Institute of Technology
*
* Permission to use, copy, modify, and distribute this software and
* its documentation for any purpose and without fee is hereby
* granted, provided that both the above copyright notice and this
* permission notice appear in all copies, that both the above
* copyright notice and this permission notice appear in all
* supporting documentation, and that the name of M.I.T. not be used
* in advertising or publicity pertaining to distribution of the
* software without specific, written prior permission. M.I.T. makes
* no representations about the suitability of this software for any
* purpose. It is provided "as is" without express or implied
* warranty.
*
* THIS SOFTWARE IS PROVIDED BY M.I.T. ``AS IS''. M.I.T. DISCLAIMS
* ALL EXPRESS OR IMPLIED WARRANTIES WITH REGARD TO THIS SOFTWARE,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT
* SHALL M.I.T. BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* $FreeBSD: src/sys/kern/subr_rman.c,v 1.10.2.1 2001/06/05 08:06:08 imp Exp $
*/
/*
* The kernel resource manager. This code is responsible for keeping track
* of hardware resources which are apportioned out to various drivers.
* It does not actually assign those resources, and it is not expected
* that end-device drivers will call into this code directly. Rather,
* the code which implements the buses that those devices are attached to,
* and the code which manages CPU resources, will call this code, and the
* end-device drivers will make upcalls to that code to actually perform
* the allocation.
*
* There are two sorts of resources managed by this code. The first is
* the more familiar array (RMAN_ARRAY) type; resources in this class
* consist of a sequence of individually-allocatable objects which have
* been numbered in some well-defined order. Most of the resources
* are of this type, as it is the most familiar. The second type is
* called a gauge (RMAN_GAUGE), and models fungible resources (i.e.,
* resources in which each instance is indistinguishable from every
* other instance). The principal anticipated application of gauges
* is in the context of power consumption, where a bus may have a specific
* power budget which all attached devices share. RMAN_GAUGE is not
* implemented yet.
*
* For array resources, we make one simplifying assumption: two clients
* sharing the same resource must use the same range of indices. That
* is to say, sharing of overlapping-but-not-identical regions is not
* permitted.
*/
#include <sys/param.h>
#include <sys/systm.h>
#include <sys/kernel.h>
#include <sys/lock.h>
#include <sys/malloc.h>
#include <sys/bus.h> /* XXX debugging */
#include <sys/rman.h>
#include <sys/sysctl.h>
int rman_debug = 0;
TUNABLE_INT("debug.rman_debug", &rman_debug);
SYSCTL_INT(_debug, OID_AUTO, rman_debug, CTLFLAG_RW,
&rman_debug, 0, "rman debug");
#define DPRINTF(params) if (rman_debug) kprintf params
static MALLOC_DEFINE(M_RMAN, "rman", "Resource manager");
struct rman_head rman_head;
static struct lwkt_token rman_tok; /* mutex to protect rman_head */
static int int_rman_activate_resource(struct rman *rm, struct resource *r,
struct resource **whohas);
static int int_rman_deactivate_resource(struct resource *r);
static int int_rman_release_resource(struct rman *rm, struct resource *r);
int
rman_init(struct rman *rm, int cpuid)
{
static int once;
if (once == 0) {
once = 1;
TAILQ_INIT(&rman_head);
lwkt_token_init(&rman_tok, "rman");
}
if (rm->rm_type == RMAN_UNINIT)
panic("rman_init");
if (rm->rm_type == RMAN_GAUGE)
panic("implement RMAN_GAUGE");
TAILQ_INIT(&rm->rm_list);
rm->rm_slock = kmalloc(sizeof *rm->rm_slock, M_RMAN, M_NOWAIT);
if (rm->rm_slock == NULL)
return ENOMEM;
lwkt_token_init(rm->rm_slock, "rmanslock");
rm->rm_cpuid = cpuid;
lwkt_gettoken(&rman_tok);
TAILQ_INSERT_TAIL(&rman_head, rm, rm_link);
lwkt_reltoken(&rman_tok);
return 0;
}
/*
* NB: this interface is not robust against programming errors which
* add multiple copies of the same region.
*/
int
rman_manage_region(struct rman *rm, u_long start, u_long end)
{
struct resource *r, *s;
DPRINTF(("rman_manage_region: <%s> request: start %#lx, end %#lx\n",
rm->rm_descr, start, end));
r = kmalloc(sizeof *r, M_RMAN, M_NOWAIT | M_ZERO);
if (r == NULL)
return ENOMEM;
r->r_sharehead = 0;
r->r_start = start;
r->r_end = end;
r->r_flags = 0;
r->r_dev = 0;
r->r_rm = rm;
lwkt_gettoken(rm->rm_slock);
for (s = TAILQ_FIRST(&rm->rm_list);
s && s->r_end < r->r_start;
s = TAILQ_NEXT(s, r_link))
;
if (s == NULL)
TAILQ_INSERT_TAIL(&rm->rm_list, r, r_link);
else
TAILQ_INSERT_BEFORE(s, r, r_link);
lwkt_reltoken(rm->rm_slock);
return 0;
}
int
rman_fini(struct rman *rm)
{
struct resource *r;
lwkt_gettoken(rm->rm_slock);
TAILQ_FOREACH(r, &rm->rm_list, r_link) {
if (r->r_flags & RF_ALLOCATED) {
lwkt_reltoken(rm->rm_slock);
return EBUSY;
}
}
/*
* There really should only be one of these if we are in this
* state and the code is working properly, but it can't hurt.
*/
while (!TAILQ_EMPTY(&rm->rm_list)) {
r = TAILQ_FIRST(&rm->rm_list);
TAILQ_REMOVE(&rm->rm_list, r, r_link);
kfree(r, M_RMAN);
}
lwkt_reltoken(rm->rm_slock);
/* XXX what's the point of this if we are going to free the struct? */
lwkt_gettoken(&rman_tok);
TAILQ_REMOVE(&rman_head, rm, rm_link);
lwkt_reltoken(&rman_tok);
kfree(rm->rm_slock, M_RMAN);
return 0;
}
struct resource *
rman_reserve_resource(struct rman *rm, u_long start, u_long end, u_long count,
u_int flags, device_t dev)
{
u_int want_activate;
struct resource *r, *s, *rv;
u_long rstart, rend;
rv = NULL;
DPRINTF(("rman_reserve_resource: <%s> request: [%#lx, %#lx], length "
"%#lx, flags %u, device %s\n", rm->rm_descr, start, end,
count, flags,
dev == NULL ? "<null>" : device_get_nameunit(dev)));
want_activate = (flags & RF_ACTIVE);
flags &= ~RF_ACTIVE;
lwkt_gettoken(rm->rm_slock);
for (r = TAILQ_FIRST(&rm->rm_list);
r && r->r_end < start + count - 1;
r = TAILQ_NEXT(r, r_link))
;
if (r == NULL) {
DPRINTF(("could not find a region\n"));
goto out;
}
/*
* First try to find an acceptable totally-unshared region.
*/
for (s = r; s; s = TAILQ_NEXT(s, r_link)) {
DPRINTF(("considering [%#lx, %#lx]\n", s->r_start, s->r_end));
if (s->r_start > end - (count - 1)) {
DPRINTF(("s->r_start (%#lx) > end (%#lx)\n",
s->r_start, end));
break;
}
if (s->r_flags & RF_ALLOCATED) {
DPRINTF(("region is allocated\n"));
continue;
}
rstart = ulmax(s->r_start, start);
rstart = rounddown2(rstart + (1ul << RF_ALIGNMENT(flags)) - 1,
1ul << RF_ALIGNMENT(flags));
rend = ulmin(s->r_end, ulmax(start + count - 1, end));
DPRINTF(("truncated region: [%#lx, %#lx]; size %#lx (requested %#lx)\n",
rstart, rend, (rend - rstart + 1), count));
if ((rend - rstart + 1) >= count) {
DPRINTF(("candidate region: [%#lx, %#lx], size %#lx\n",
rstart, rend, (rend - rstart + 1)));
if ((s->r_end - s->r_start + 1) == count) {
DPRINTF(("candidate region is entire chunk\n"));
rv = s;
rv->r_flags |= RF_ALLOCATED | flags;
rv->r_dev = dev;
goto out;
}
/*
* If s->r_start < rstart and
* s->r_end > rstart + count - 1, then
* we need to split the region into three pieces
* (the middle one will get returned to the user).
* Otherwise, we are allocating at either the
* beginning or the end of s, so we only need to
* split it in two. The first case requires
* two new allocations; the second requires but one.
*/
rv = kmalloc(sizeof *rv, M_RMAN, M_NOWAIT | M_ZERO);
if (rv == NULL)
goto out;
rv->r_start = rstart;
rv->r_end = rstart + count - 1;
rv->r_flags = flags | RF_ALLOCATED;
rv->r_dev = dev;
rv->r_sharehead = 0;
rv->r_rm = rm;
if (s->r_start < rv->r_start && s->r_end > rv->r_end) {
DPRINTF(("splitting region in three parts: "
"[%#lx, %#lx]; [%#lx, %#lx]; [%#lx, %#lx]\n",
s->r_start, rv->r_start - 1,
rv->r_start, rv->r_end,
rv->r_end + 1, s->r_end));
/*
* We are allocating in the middle.
*/
r = kmalloc(sizeof *r, M_RMAN,
M_NOWAIT | M_ZERO);
if (r == NULL) {
kfree(rv, M_RMAN);
rv = NULL;
goto out;
}
r->r_start = rv->r_end + 1;
r->r_end = s->r_end;
r->r_flags = s->r_flags;
r->r_dev = 0;
r->r_sharehead = 0;
r->r_rm = rm;
s->r_end = rv->r_start - 1;
TAILQ_INSERT_AFTER(&rm->rm_list, s, rv,
r_link);
TAILQ_INSERT_AFTER(&rm->rm_list, rv, r,
r_link);
} else if (s->r_start == rv->r_start) {
DPRINTF(("allocating from the beginning\n"));
/*
* We are allocating at the beginning.
*/
s->r_start = rv->r_end + 1;
TAILQ_INSERT_BEFORE(s, rv, r_link);
} else {
DPRINTF(("allocating at the end\n"));
/*
* We are allocating at the end.
*/
s->r_end = rv->r_start - 1;
TAILQ_INSERT_AFTER(&rm->rm_list, s, rv,
r_link);
}
goto out;
}
}
/*
* Now find an acceptable shared region, if the client's requirements
* allow sharing. By our implementation restriction, a candidate
* region must match exactly by both size and sharing type in order
* to be considered compatible with the client's request. (The
* former restriction could probably be lifted without too much
* additional work, but this does not seem warranted.)
*/
DPRINTF(("no unshared regions found\n"));
if ((flags & (RF_SHAREABLE | RF_TIMESHARE)) == 0)
goto out;
for (s = r; s; s = TAILQ_NEXT(s, r_link)) {
if (s->r_start > end)
break;
if ((s->r_flags & flags) != flags)
continue;
rstart = ulmax(s->r_start, start);
rend = ulmin(s->r_end, ulmax(start + count, end));
if (s->r_start >= start && s->r_end <= end
&& (s->r_end - s->r_start + 1) == count) {
rv = kmalloc(sizeof *rv, M_RMAN, M_NOWAIT | M_ZERO);
if (rv == NULL)
goto out;
rv->r_start = s->r_start;
rv->r_end = s->r_end;
rv->r_flags = s->r_flags &
(RF_ALLOCATED | RF_SHAREABLE | RF_TIMESHARE);
rv->r_dev = dev;
rv->r_rm = rm;
if (s->r_sharehead == 0) {
s->r_sharehead = kmalloc(sizeof *s->r_sharehead,
M_RMAN,
M_NOWAIT | M_ZERO);
if (s->r_sharehead == 0) {
kfree(rv, M_RMAN);
rv = NULL;
goto out;
}
LIST_INIT(s->r_sharehead);
LIST_INSERT_HEAD(s->r_sharehead, s,
r_sharelink);
s->r_flags |= RF_FIRSTSHARE;
}
rv->r_sharehead = s->r_sharehead;
LIST_INSERT_HEAD(s->r_sharehead, rv, r_sharelink);
goto out;
}
}
/*
* We couldn't find anything.
*/
DPRINTF(("no region found\n"));
out:
/*
* If the user specified RF_ACTIVE in the initial flags,
* which is reflected in `want_activate', we attempt to atomically
* activate the resource. If this fails, we release the resource
* and indicate overall failure. (This behavior probably doesn't
* make sense for RF_TIMESHARE-type resources.)
*/
if (rv && want_activate) {
struct resource *whohas;
DPRINTF(("activating region\n"));
if (int_rman_activate_resource(rm, rv, &whohas)) {
int_rman_release_resource(rm, rv);
rv = NULL;
}
}
lwkt_reltoken(rm->rm_slock);
return (rv);
}
static int
int_rman_activate_resource(struct rman *rm, struct resource *r,
struct resource **whohas)
{
struct resource *s;
int ok;
/*
* If we are not timesharing, then there is nothing much to do.
* If we already have the resource, then there is nothing at all to do.
* If we are not on a sharing list with anybody else, then there is
* little to do.
*/
if ((r->r_flags & RF_TIMESHARE) == 0
|| (r->r_flags & RF_ACTIVE) != 0
|| r->r_sharehead == 0) {
r->r_flags |= RF_ACTIVE;
return 0;
}
ok = 1;
for (s = LIST_FIRST(r->r_sharehead); s && ok;
s = LIST_NEXT(s, r_sharelink)) {
if ((s->r_flags & RF_ACTIVE) != 0) {
ok = 0;
*whohas = s;
}
}
if (ok) {
r->r_flags |= RF_ACTIVE;
return 0;
}
return EBUSY;
}
int
rman_activate_resource(struct resource *r)
{
int rv;
struct resource *whohas;
struct rman *rm;
rm = r->r_rm;
lwkt_gettoken(rm->rm_slock);
rv = int_rman_activate_resource(rm, r, &whohas);
lwkt_reltoken(rm->rm_slock);
return rv;
}
#if 0
/* XXX */
int
rman_await_resource(struct resource *r, int slpflags, int timo)
{
int rv;
struct resource *whohas;
struct rman *rm;
rm = r->r_rm;
for (;;) {
lwkt_gettoken(rm->rm_slock);
rv = int_rman_activate_resource(rm, r, &whohas);
if (rv != EBUSY)
return (rv); /* returns with ilock held */
if (r->r_sharehead == 0)
panic("rman_await_resource");
/*
* A critical section will hopefully will prevent a race
* between lwkt_reltoken and tsleep where a process
* could conceivably get in and release the resource
* before we have a chance to sleep on it. YYY
*/
crit_enter();
whohas->r_flags |= RF_WANTED;
rv = tsleep(r->r_sharehead, slpflags, "rmwait", timo);
if (rv) {
lwkt_reltoken(rm->rm_slock);
crit_exit();
return rv;
}
crit_exit();
}
}
#endif
static int
int_rman_deactivate_resource(struct resource *r)
{
r->r_flags &= ~RF_ACTIVE;
if (r->r_flags & RF_WANTED) {
r->r_flags &= ~RF_WANTED;
wakeup(r->r_sharehead);
}
return 0;
}
int
rman_deactivate_resource(struct resource *r)
{
struct rman *rm;
rm = r->r_rm;
lwkt_gettoken(rm->rm_slock);
int_rman_deactivate_resource(r);
lwkt_reltoken(rm->rm_slock);
return 0;
}
static int
int_rman_release_resource(struct rman *rm, struct resource *r)
{
struct resource *s, *t;
if (r->r_flags & RF_ACTIVE)
int_rman_deactivate_resource(r);
/*
* Check for a sharing list first. If there is one, then we don't
* have to think as hard.
*/
if (r->r_sharehead) {
/*
* If a sharing list exists, then we know there are at
* least two sharers.
*
* If we are in the main circleq, appoint someone else.
*/
LIST_REMOVE(r, r_sharelink);
s = LIST_FIRST(r->r_sharehead);
if (r->r_flags & RF_FIRSTSHARE) {
s->r_flags |= RF_FIRSTSHARE;
TAILQ_INSERT_BEFORE(r, s, r_link);
TAILQ_REMOVE(&rm->rm_list, r, r_link);
}
/*
* Make sure that the sharing list goes away completely
* if the resource is no longer being shared at all.
*/
if (LIST_NEXT(s, r_sharelink) == 0) {
kfree(s->r_sharehead, M_RMAN);
s->r_sharehead = 0;
s->r_flags &= ~RF_FIRSTSHARE;
}
goto out;
}
/*
* Look at the adjacent resources in the list and see if our
* segment can be merged with any of them.
*/
s = TAILQ_PREV(r, resource_head, r_link);
t = TAILQ_NEXT(r, r_link);
if (s != NULL && (s->r_flags & RF_ALLOCATED) == 0
&& t != NULL && (t->r_flags & RF_ALLOCATED) == 0) {
/*
* Merge all three segments.
*/
s->r_end = t->r_end;
TAILQ_REMOVE(&rm->rm_list, r, r_link);
TAILQ_REMOVE(&rm->rm_list, t, r_link);
kfree(t, M_RMAN);
} else if (s != NULL && (s->r_flags & RF_ALLOCATED) == 0) {
/*
* Merge previous segment with ours.
*/
s->r_end = r->r_end;
TAILQ_REMOVE(&rm->rm_list, r, r_link);
} else if (t != NULL && (t->r_flags & RF_ALLOCATED) == 0) {
/*
* Merge next segment with ours.
*/
t->r_start = r->r_start;
TAILQ_REMOVE(&rm->rm_list, r, r_link);
} else {
/*
* At this point, we know there is nothing we
* can potentially merge with, because on each
* side, there is either nothing there or what is
* there is still allocated. In that case, we don't
* want to remove r from the list; we simply want to
* change it to an unallocated region and return
* without freeing anything.
*/
r->r_flags &= ~RF_ALLOCATED;
return 0;
}
out:
kfree(r, M_RMAN);
return 0;
}
int
rman_release_resource(struct resource *r)
{
struct rman *rm = r->r_rm;
int rv;
lwkt_gettoken(rm->rm_slock);
rv = int_rman_release_resource(rm, r);
lwkt_reltoken(rm->rm_slock);
return (rv);
}
/*
* Find the hightest bit set, and add one if more than one bit
* set. We're effectively computing the ceil(log2(size)) here.
*
* This function cannot compute alignments above (1LU<<63)+1
* as this would require returning '64' which will not fit in
* the flags field and doesn't work well for calculations either.
*/
uint32_t
rman_make_alignment_flags(size_t size)
{
int i;
for (i = 63; i; --i) {
if ((1LU << i) & size)
break;
}
if (~(1LU << i) & size)
++i;
if (i == 64)
i = 63;
return(RF_ALIGNMENT_LOG2(i));
}
/*
* Sysctl interface for scanning the resource lists.
*
* We take two input parameters; the index into the list of resource
* managers, and the resource offset into the list.
*/
static int
sysctl_rman(SYSCTL_HANDLER_ARGS)
{
int *name = (int *)arg1;
u_int namelen = arg2;
int rman_idx, res_idx;
struct rman *rm;
struct resource *res;
struct u_rman urm;
struct u_resource ures;
int error;
if (namelen != 3)
return (EINVAL);
if (bus_data_generation_check(name[0]))
return (EINVAL);
rman_idx = name[1];
res_idx = name[2];
/*
* Find the indexed resource manager
*/
TAILQ_FOREACH(rm, &rman_head, rm_link) {
if (rman_idx-- == 0)
break;
}
if (rm == NULL)
return (ENOENT);
/*
* If the resource index is -1, we want details on the
* resource manager.
*/
if (res_idx == -1) {
urm.rm_handle = (uintptr_t)rm;
strlcpy(urm.rm_descr, rm->rm_descr, RM_TEXTLEN);
urm.rm_start = rm->rm_start;
urm.rm_size = rm->rm_end - rm->rm_start + 1;
urm.rm_type = rm->rm_type;
error = SYSCTL_OUT(req, &urm, sizeof(urm));
return (error);
}
/*
* Find the indexed resource and return it.
*/
TAILQ_FOREACH(res, &rm->rm_list, r_link) {
if (res_idx-- == 0) {
ures.r_handle = (uintptr_t)res;
ures.r_parent = (uintptr_t)res->r_rm;
ures.r_device = (uintptr_t)res->r_dev;
if (res->r_dev != NULL) {
if (device_get_name(res->r_dev) != NULL) {
ksnprintf(ures.r_devname, RM_TEXTLEN,
"%s%d",
device_get_name(res->r_dev),
device_get_unit(res->r_dev));
} else {
strlcpy(ures.r_devname, "nomatch",
RM_TEXTLEN);
}
} else {
ures.r_devname[0] = '\0';
}
ures.r_start = res->r_start;
ures.r_size = res->r_end - res->r_start + 1;
ures.r_flags = res->r_flags;
error = SYSCTL_OUT(req, &ures, sizeof(ures));
return (error);
}
}
return (ENOENT);
}
SYSCTL_NODE(_hw_bus, OID_AUTO, rman, CTLFLAG_RD, sysctl_rman,
"kernel resource manager");
|
585507.c | //fpath3
#include <std.h>;
#include "../bforest.h"
inherit IHRMS+"fpath.c";
void create(){
::create();
set_exits(([
"north":INRMS+"fpath2",
"southeast":INRMS+"fpath4",
"northwest":INRMS+"fpath59",
"west":INRMS+"fpath58",
"east":INRMS+"bce2",
]));
} |
918282.c | /*
* Copyright © 2017 VMware, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the ?~@~\License?~@~]); you may not
* use this file except in compliance with the License. You may obtain a copy
* of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* 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 "includes.h"
VMDIR_REPLICATION_METRICS_CACHE gVdirReplMetricsCache =
{
// NOTE: order of fields MUST stay in sync with struct definition...
VMDIR_SF_INIT(.pHashMap, NULL),
VMDIR_SF_INIT(.pLock, NULL)
};
|
344079.c | /* Copyright ©2006-2014 Kris Maglione <maglione.k at Gmail>
* See LICENSE file for license details.
*/
#include "dat.h"
#include <math.h>
#include "fns.h"
uint
frame_idx(Frame *f) {
Frame *fp;
uint i;
fp = f->area->frame;
for(i = 1; fp != f; fp = fp->anext)
i++;
return i;
}
Frame*
frame_create(Client *c, View *v) {
static ushort id = 1;
Frame *f;
f = emallocz(sizeof *f);
f->id = id++;
f->client = c;
f->view = v;
if(c->sel) {
f->floatr = c->sel->floatr;
f->r = c->sel->r;
}else if(c->sel) {
f->floatr = c->frame->floatr;
f->r = c->frame->r;
}else {
f->r = client_grav(c, c->r);
f->floatr = f->r;
c->sel = f;
}
f->collapsed = false;
f->screen = -1;
f->oldarea = -1;
f->oldscreen = -1;
return f;
}
void
frame_remove(Frame *f) {
Area *a;
a = f->area;
if(f->aprev)
f->aprev->anext = f->anext;
if(f->anext)
f->anext->aprev = f->aprev;
if(f == a->frame)
a->frame = f->anext;
if(a->floating) {
if(f->sprev)
f->sprev->snext = f->snext;
if(f->snext)
f->snext->sprev = f->sprev;
if(f == a->stack)
a->stack = f->snext;
}
f->anext = f->aprev = f->snext = f->sprev = nil;
}
void
frame_insert(Frame *f, Frame *pos) {
Area *a;
a = f->area;
if(pos) {
assert(pos != f);
f->aprev = pos;
f->anext = pos->anext;
}else {
assert(f->area->frame != f);
f->anext = f->area->frame;
f->area->frame = f;
}
if(f->aprev)
f->aprev->anext = f;
if(f->anext)
f->anext->aprev = f;
if(a->floating) {
assert(f->sprev == nil);
frame_restack(f, nil);
}
}
bool
frame_restack(Frame *f, Frame *above) {
Area *a;
a = f->area;
if(!a->floating)
return false;
if(f == above)
return false;
if(f->sprev || f == a->stack)
if(f->sprev == above)
return false;
if(f->sprev)
f->sprev->snext = f->snext;
else if(f->snext)
a->stack = f->snext;
if(f->snext)
f->snext->sprev = f->sprev;
f->sprev = above;
if(above == nil) {
f->snext = a->stack;
a->stack = f;
}
else {
f->snext = above->snext;
above->snext = f;
}
if(f->snext)
f->snext->sprev = f;
assert(f->snext != f && f->sprev != f);
return true;
}
/* Handlers */
static bool
bup_event(Window *w, void *aux, XButtonEvent *e) {
if((e->state & def.mod) != def.mod)
XAllowEvents(display, ReplayPointer, e->time);
else
XUngrabPointer(display, e->time);
if(!e->subwindow)
event("ClientClick %#C %d\n", aux, e->button);
return false;
}
static bool
bdown_event(Window *w, void *aux, XButtonEvent *e) {
Frame *f;
Client *c;
c = aux;
f = c->sel;
if((e->state & def.mod) == def.mod) {
switch(e->button) {
case Button1:
focus(c, false);
mouse_resize(c, Center, true);
break;
case Button2:
frame_restack(f, nil);
view_restack(f->view);
focus(c, false);
grabpointer(c->framewin, nil, cursor[CurNone], ButtonReleaseMask);
break;
case Button3:
focus(c, false);
mouse_resize(c, quadrant(f->r, Pt(e->x_root, e->y_root)), true);
break;
default:
XAllowEvents(display, ReplayPointer, e->time);
break;
}
}else {
if(e->button == Button1) {
if(!e->subwindow) {
frame_restack(f, nil);
view_restack(f->view);
mouse_checkresize(f, Pt(e->x, e->y), true);
}
if(f->client != selclient())
focus(c, false);
}
if(e->subwindow)
XAllowEvents(display, ReplayPointer, e->time);
else {
/* Ungrab so a menu can receive events before the button is released */
XUngrabPointer(display, e->time);
sync();
event("ClientMouseDown %#C %d\n", f->client, e->button);
}
}
return false;
}
static bool
enter_event(Window *w, void *aux, XCrossingEvent *e) {
Client *c;
Frame *f;
c = aux;
f = c->sel;
if(disp.focus != c || selclient() != c) {
Dprint(DFocus, "%E\n", e);
Dprint(DFocus, "enter_notify(f) => [%#C]%s%s\n",
f->client, f->client->name,
e->serial <= event_lastconfigure ? " (ignored)" : "");
if(e->detail != NotifyInferior)
if(e->serial > event_lastconfigure && !f->collapsed)
focus(f->client, false);
}
mouse_checkresize(f, Pt(e->x, e->y), false);
return false;
}
static bool
expose_event(Window *w, void *aux, XExposeEvent *e) {
Client *c;
USED(e);
c = aux;
if(c->sel)
frame_draw(c->sel);
return false;
}
static bool
motion_event(Window *w, void *aux, XMotionEvent *e) {
Client *c;
c = aux;
mouse_checkresize(c->sel, Pt(e->x, e->y), false);
return false;
}
Handlers framehandler = {
.bup = bup_event,
.bdown = bdown_event,
.enter = enter_event,
.expose = expose_event,
.motion = motion_event,
};
WinHints
frame_gethints(Frame *f) {
WinHints h;
Client *c;
Rectangle r;
Point d;
int minh;
minh = labelh(def.font);
c = f->client;
h = *c->w.hints;
r = frame_client2rect(c, ZR, f->area->floating);
d = subpt(r.max, r.min);
if(!f->area->floating && def.incmode == IIgnore)
h.inc = Pt(1, 1);
if(h.min.x < 2*minh)
h.min.x = minh + (2*minh) % h.inc.x;
if(h.min.y < minh)
h.min.y = minh + minh % h.inc.y;
h.min.x += d.x;
h.min.y += d.y;
/* Guard against overflow. */
h.max.x = max(h.max.x + d.x, h.max.x);
h.max.y = max(h.max.y + d.y, h.max.y);
h.base.x += d.x;
h.base.y += d.y;
h.baspect.x += d.x;
h.baspect.y += d.y;
h.group = 0;
h.grav = ZP;
h.gravstatic = 0;
h.position = 0;
return h;
}
#define ADJ(PE, ME) \
if(c->fullscreen >= 0) \
return r; \
\
if(!floating) { \
r.min.x PE 1; \
r.min.y PE labelh(def.font); \
r.max.x ME 1; \
r.max.y ME 1; \
}else { \
if(!c->borderless) { \
r.min.x PE def.border; \
r.max.x ME def.border; \
r.max.y ME def.border; \
} \
if(!c->titleless) \
r.min.y PE labelh(def.font); \
} \
Rectangle
frame_rect2client(Client *c, Rectangle r, bool floating) {
ADJ(+=, -=)
/* Force clients to be at least 1x1 */
r.max.x = max(r.max.x, r.min.x+1);
r.max.y = max(r.max.y, r.min.y+1);
return r;
}
Rectangle
frame_client2rect(Client *c, Rectangle r, bool floating) {
ADJ(-=, +=)
return r;
}
#undef ADJ
void
frame_resize(Frame *f, Rectangle r) {
Client *c;
Rectangle fr, cr;
int collapsed, dx;
if(btassert("8 full", Dx(r) <= 0 || Dy(r) < 0
|| Dy(r) == 0 && (!f->area->max || resizing)
&& !f->collapsed)) {
fprint(2, "Frame rect: %R\n", r);
r.max.x = max(r.min.x+1, r.max.x);
r.max.y = max(r.min.y+1, r.max.y);
}
c = f->client;
if(c->fullscreen >= 0) {
f->r = screens[c->fullscreen]->r;
f->crect = rectsetorigin(f->r, ZP);
return;
}
/*
if(f->area->floating)
f->collapsed = false;
*/
fr = frame_hints(f, r, get_sticky(f->r, r));
if(f->area->floating && !c->strut)
fr = constrain(fr, -1);
/* Collapse managed frames which are too small */
/* XXX. */
collapsed = f->collapsed;
if(!f->area->floating && f->area->mode == Coldefault) {
f->collapsed = false;
if(Dy(r) < 2 * labelh(def.font))
f->collapsed = true;
}
if(collapsed != f->collapsed)
ewmh_updatestate(c);
fr.max.x = max(fr.max.x, fr.min.x + 2*labelh(def.font));
if(f->collapsed && f->area->floating)
fr.max.y = fr.min.y + labelh(def.font);
cr = frame_rect2client(c, fr, f->area->floating);
if(f->area->floating)
f->r = fr;
else {
f->r = r;
dx = Dx(r) - Dx(cr);
dx -= 2 * (cr.min.x - fr.min.x);
cr.min.x += dx / 2;
cr.max.x += dx / 2;
}
f->crect = rectsubpt(cr, f->r.min);
if(f->area->floating && !f->collapsed)
f->floatr = f->r;
}
static void
pushlabel(Image *img, Rectangle *rp, char *s, CTuple *col) {
Rectangle r;
int w;
w = textwidth(def.font, s) + def.font->height;
w = min(w, Dx(*rp) - 30); /* Magic number. */
if(w > 0) {
r = *rp;
r.min.x = r.max.x - w;
rp->max.x -= w;
if(0)
drawline(img, Pt(rp->max.x, r.min.y+2),
Pt(rp->max.x, r.max.y-2),
CapButt, 1, &col->border);
drawstring(img, def.font, r, East,
s, &col->fg);
}
free(s);
}
void
frame_draw(Frame *f) {
Rectangle r, fr;
Client *c;
CTuple *col;
Image *img;
char *s;
int n, m;
if(f == nil || f->view != selview || f->area == nil)
return;
c = f->client;
img = c->framewin->depth == 32 ? disp.ibuf32 : disp.ibuf;
fr = rectsetorigin(c->framewin->r, ZP);
/* Pick colors. */
if((c == selclient() || c == disp.focus) && disp.sel)
col = &def.focuscolor;
else
col = &def.normcolor;
/* Background/border */
r = fr;
fill(img, r, &col->bg);
border(img, r, 1, &col->border);
/* Title border */
r.max.y = r.min.y + labelh(def.font);
border(img, r, 1, &col->border);
f->titlebar = insetrect(r, 3);
f->titlebar.max.y += 3;
f->grabbox = insetrect(r, 2);
f->grabbox.max.x = f->grabbox.min.x + Dy(f->grabbox);
/* Odd focus. Unselected, with keyboard focus. */
/* Draw a border just inside the titlebar. */
if(c != selclient() && c == disp.focus) {
border(img, insetrect(r, 1), 1, &def.normcolor.bg);
border(img, insetrect(r, 2), 1, &def.focuscolor.border);
}
if(c->urgent)
fill(img, f->grabbox, &col->fg);
border(img, f->grabbox, 1, &col->border);
/* Odd focus. Selected, without keyboard focus. */
/* Draw a border around the grabbox. */
if(c != disp.focus && col == &def.focuscolor)
border(img, insetrect(r, -1), 1, &def.normcolor.bg);
/* Draw a border on borderless+titleless selected apps. */
if(c->borderless && c->titleless && f->area->floating && !c->fullscreen && c == selclient())
setborder(c->framewin, def.border, &def.focuscolor.border);
else
setborder(c->framewin, 0, &def.focuscolor.border);
/* Label */
r = Rect(f->grabbox.max.x, 0, fr.max.x, labelh(def.font));
/* Draw count on frames in 'max' columns. */
if(f->area->max && !resizing) {
n = stack_count(f, &m);
pushlabel(img, &r, smprint("%d/%d", m, n), col);
}
/* Label clients with extra tags. */
if((s = client_extratags(c)))
pushlabel(img, &r, s, col);
if(f->area->floating) /* Make sure floating clients have room for their indicators. */
r.max.x -= f->grabbox.max.x;
if(!ewmh_responsive_p(c))
r.min.x += drawstring(img, def.font, r, West, "(wedged) ", &col->fg);
r.min.x += drawstring(img, def.font, r, West, c->name, &col->fg);
/* Draw inner border on floating clients. */
if(f->area->floating) {
r.min.x += 10;
r.max.x += Dx(f->grabbox);
r.min.y = f->grabbox.min.y;
r.max.y = f->grabbox.max.y;
border(img, r, 1, &col->border);
}
/* Border increment gaps... */
r.min.y = f->crect.min.y;
r.min.x = max(1, f->crect.min.x - 1);
r.max.x = min(fr.max.x - 1, f->crect.max.x + 1);
r.max.y = min(fr.max.y - 1, f->crect.max.y + 1);
border(img, r, 1, &col->border);
/* Why? Because some non-ICCCM-compliant apps feel the need to
* change the background properties of all of their ancestor windows
* in order to implement pseudo-transparency.
* What's more, the designers of X11 felt that it would be unfair to
* implementers to make it possible to detect, or forbid, such changes.
*/
XSetWindowBackgroundPixmap(display, c->framewin->xid, None);
copyimage(c->framewin, fr, img, ZP);
}
void
frame_draw_all(void) {
Client *c;
for(c=client; c; c=c->next)
if(c->sel && c->sel->view == selview)
frame_draw(c->sel);
}
void
frame_swap(Frame *fa, Frame *fb) {
Frame **fp;
Client *c;
if(fa == fb) return;
for(fp = &fa->client->frame; *fp; fp = &fp[0]->cnext)
if(*fp == fa) break;
fp[0] = fp[0]->cnext;
for(fp = &fb->client->frame; *fp; fp = &fp[0]->cnext)
if(*fp == fb) break;
fp[0] = fp[0]->cnext;
c = fa->client;
fa->client = fb->client;
fb->client = c;
fb->cnext = c->frame;
c->frame = fb;
c = fa->client;
fa->cnext = c->frame;
c->frame = fa;
if(c->sel)
view_update(c->sel->view);
}
void
move_focus(Frame *old_f, Frame *f) {
int noinput;
noinput = (old_f && old_f->client->noinput) ||
(f && f->client->noinput) ||
disp.hasgrab != &c_root;
if(noinput || true) {
if(old_f)
frame_draw(old_f);
if(f)
frame_draw(f);
}
}
void
frame_focus(Frame *f) {
Frame *old_f, *ff;
View *v;
Area *a, *old_a;
v = f->view;
a = f->area;
old_a = v->sel;
if(0 && f->collapsed) {
for(ff=f; ff->collapsed && ff->anext; ff=ff->anext)
;
for(; ff->collapsed && ff->aprev; ff=ff->aprev)
;
/* XXX */
f->colr.max.y = f->colr.min.y + Dy(ff->colr);
ff->colr.max.y = ff->colr.min.y + labelh(def.font);
}
else if(f->area->mode == Coldefault) {
/* XXX */
for(; f->collapsed && f->anext; f=f->anext)
;
for(; f->collapsed && f->aprev; f=f->aprev)
;
}
old_f = old_a->sel;
a->sel = f;
if(a != old_a)
area_focus(f->area);
if(old_a != v->oldsel && f != old_f)
v->oldsel = nil;
if(f->area->floating)
f->collapsed = false;
if(v == selview && a == v->sel && !resizing) {
move_focus(old_f, f);
if(a->floating)
float_arrange(a);
// if(!a->floating && ((a->mode == Colstack) || (a->mode == Colmax)))
if(true)
column_arrange(a, false);
client_focus(f->client);
}
}
int
frame_delta_h(void) {
return def.border + labelh(def.font);
}
Rectangle
constrain(Rectangle r, int inset) {
WMScreen **sp;
WMScreen *s, *sbest;
Rectangle isect;
Point p;
int best, n;
if(inset < 0)
inset = Dy(screen->brect);
/*
* FIXME: This will cause problems for windows with
* D(r) < 2 * inset
*/
SET(best);
sbest = nil;
for(sp=screens; (s = *sp); sp++) {
if(!screen->showing)
continue;
isect = rect_intersection(r, insetrect(s->r, inset));
if(Dx(isect) >= 0 && Dy(isect) >= 0)
return r;
if(Dx(isect) <= 0 && Dy(isect) <= 0)
n = max(Dx(isect), Dy(isect));
else
n = min(Dx(isect), Dy(isect));
if(!sbest || n > best) {
sbest = s;
best = n;
}
}
if (!sbest)
return r;
isect = insetrect(sbest->r, inset);
p = ZP;
p.x -= min(r.max.x - isect.min.x, 0);
p.x -= max(r.min.x - isect.max.x, 0);
p.y -= min(r.max.y - isect.min.y, 0);
p.y -= max(r.min.y - isect.max.y, 0);
return rectaddpt(r, p);
}
|
35777.c | /****************************************************************************
* arch/z80/src/z80/z80_initialstate.c
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership. The
* ASF licenses this file to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*
****************************************************************************/
/****************************************************************************
* Included Files
****************************************************************************/
#include <nuttx/config.h>
#include <string.h>
#include <nuttx/arch.h>
#include "chip.h"
#include "z80_internal.h"
#include "z80_arch.h"
/****************************************************************************
* Public Functions
****************************************************************************/
/****************************************************************************
* Name: up_initial_state
*
* Description:
* A new thread is being started and a new TCB
* has been created. This function is called to initialize
* the processor specific portions of the new TCB.
*
* This function must setup the initial architecture registers
* and/or stack so that execution will begin at tcb->start
* on the next context switch.
*
****************************************************************************/
void up_initial_state(struct tcb_s *tcb)
{
struct xcptcontext *xcp = &tcb->xcp;
/* Initialize the idle thread stack */
if (tcb->pid == 0)
{
up_use_stack(tcb,
(void *)CONFIG_STACK_BASE, CONFIG_IDLETHREAD_STACKSIZE);
}
/* Initialize the initial exception register context structure */
memset(xcp, 0, sizeof(struct xcptcontext));
#ifndef CONFIG_SUPPRESS_INTERRUPTS
xcp->regs[XCPT_I] = Z80_PV_FLAG; /* Parity flag will enable interrupts */
#endif
xcp->regs[XCPT_SP] = (chipreg_t)tcb->adj_stack_ptr;
xcp->regs[XCPT_PC] = (chipreg_t)tcb->start;
}
|
542707.c | /* -*- mode: c; c-basic-offset: 8; -*-
* vim: noexpandtab sw=8 ts=8 sts=0:
*
* super.c
*
* load/unload driver, mount/dismount volumes
*
* Copyright (C) 2002, 2004 Oracle. All rights reserved.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 021110-1307, USA.
*/
#include <linux/module.h>
#include <linux/fs.h>
#include <linux/types.h>
#include <linux/slab.h>
#include <linux/highmem.h>
#include <linux/init.h>
#include <linux/random.h>
#include <linux/statfs.h>
#include <linux/moduleparam.h>
#include <linux/blkdev.h>
#include <linux/socket.h>
#include <linux/inet.h>
#include <linux/parser.h>
#include <linux/crc32.h>
#include <linux/debugfs.h>
#include <linux/mount.h>
#include <linux/seq_file.h>
#include <linux/quotaops.h>
#include <linux/cleancache.h>
#include <linux/signal.h>
#define CREATE_TRACE_POINTS
#include "ocfs2_trace.h"
#include <cluster/masklog.h>
#include "ocfs2.h"
/* this should be the only file to include a version 1 header */
#include "ocfs1_fs_compat.h"
#include "alloc.h"
#include "aops.h"
#include "blockcheck.h"
#include "dlmglue.h"
#include "export.h"
#include "extent_map.h"
#include "heartbeat.h"
#include "inode.h"
#include "journal.h"
#include "localalloc.h"
#include "namei.h"
#include "slot_map.h"
#include "super.h"
#include "sysfile.h"
#include "uptodate.h"
#include "xattr.h"
#include "quota.h"
#include "refcounttree.h"
#include "suballoc.h"
#include "buffer_head_io.h"
#include "filecheck.h"
static struct kmem_cache *ocfs2_inode_cachep;
struct kmem_cache *ocfs2_dquot_cachep;
struct kmem_cache *ocfs2_qf_chunk_cachep;
static struct dentry *ocfs2_debugfs_root;
MODULE_AUTHOR("Oracle");
MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("OCFS2 cluster file system");
struct mount_options
{
unsigned long commit_interval;
unsigned long mount_opt;
unsigned int atime_quantum;
signed short slot;
int localalloc_opt;
unsigned int resv_level;
int dir_resv_level;
char cluster_stack[OCFS2_STACK_LABEL_LEN + 1];
};
static int ocfs2_parse_options(struct super_block *sb, char *options,
struct mount_options *mopt,
int is_remount);
static int ocfs2_check_set_options(struct super_block *sb,
struct mount_options *options);
static int ocfs2_show_options(struct seq_file *s, struct dentry *root);
static void ocfs2_put_super(struct super_block *sb);
static int ocfs2_mount_volume(struct super_block *sb);
static int ocfs2_remount(struct super_block *sb, int *flags, char *data);
static void ocfs2_dismount_volume(struct super_block *sb, int mnt_err);
static int ocfs2_initialize_mem_caches(void);
static void ocfs2_free_mem_caches(void);
static void ocfs2_delete_osb(struct ocfs2_super *osb);
static int ocfs2_statfs(struct dentry *dentry, struct kstatfs *buf);
static int ocfs2_sync_fs(struct super_block *sb, int wait);
static int ocfs2_init_global_system_inodes(struct ocfs2_super *osb);
static int ocfs2_init_local_system_inodes(struct ocfs2_super *osb);
static void ocfs2_release_system_inodes(struct ocfs2_super *osb);
static int ocfs2_check_volume(struct ocfs2_super *osb);
static int ocfs2_verify_volume(struct ocfs2_dinode *di,
struct buffer_head *bh,
u32 sectsize,
struct ocfs2_blockcheck_stats *stats);
static int ocfs2_initialize_super(struct super_block *sb,
struct buffer_head *bh,
int sector_size,
struct ocfs2_blockcheck_stats *stats);
static int ocfs2_get_sector(struct super_block *sb,
struct buffer_head **bh,
int block,
int sect_size);
static struct inode *ocfs2_alloc_inode(struct super_block *sb);
static void ocfs2_destroy_inode(struct inode *inode);
static int ocfs2_susp_quotas(struct ocfs2_super *osb, int unsuspend);
static int ocfs2_enable_quotas(struct ocfs2_super *osb);
static void ocfs2_disable_quotas(struct ocfs2_super *osb);
static struct dquot **ocfs2_get_dquots(struct inode *inode)
{
return OCFS2_I(inode)->i_dquot;
}
static const struct super_operations ocfs2_sops = {
.statfs = ocfs2_statfs,
.alloc_inode = ocfs2_alloc_inode,
.destroy_inode = ocfs2_destroy_inode,
.drop_inode = ocfs2_drop_inode,
.evict_inode = ocfs2_evict_inode,
.sync_fs = ocfs2_sync_fs,
.put_super = ocfs2_put_super,
.remount_fs = ocfs2_remount,
.show_options = ocfs2_show_options,
.quota_read = ocfs2_quota_read,
.quota_write = ocfs2_quota_write,
.get_dquots = ocfs2_get_dquots,
};
enum {
Opt_barrier,
Opt_err_panic,
Opt_err_ro,
Opt_intr,
Opt_nointr,
Opt_hb_none,
Opt_hb_local,
Opt_hb_global,
Opt_data_ordered,
Opt_data_writeback,
Opt_atime_quantum,
Opt_slot,
Opt_commit,
Opt_localalloc,
Opt_localflocks,
Opt_stack,
Opt_user_xattr,
Opt_nouser_xattr,
Opt_inode64,
Opt_acl,
Opt_noacl,
Opt_usrquota,
Opt_grpquota,
Opt_coherency_buffered,
Opt_coherency_full,
Opt_resv_level,
Opt_dir_resv_level,
Opt_journal_async_commit,
Opt_err_cont,
Opt_err,
};
static const match_table_t tokens = {
{Opt_barrier, "barrier=%u"},
{Opt_err_panic, "errors=panic"},
{Opt_err_ro, "errors=remount-ro"},
{Opt_intr, "intr"},
{Opt_nointr, "nointr"},
{Opt_hb_none, OCFS2_HB_NONE},
{Opt_hb_local, OCFS2_HB_LOCAL},
{Opt_hb_global, OCFS2_HB_GLOBAL},
{Opt_data_ordered, "data=ordered"},
{Opt_data_writeback, "data=writeback"},
{Opt_atime_quantum, "atime_quantum=%u"},
{Opt_slot, "preferred_slot=%u"},
{Opt_commit, "commit=%u"},
{Opt_localalloc, "localalloc=%d"},
{Opt_localflocks, "localflocks"},
{Opt_stack, "cluster_stack=%s"},
{Opt_user_xattr, "user_xattr"},
{Opt_nouser_xattr, "nouser_xattr"},
{Opt_inode64, "inode64"},
{Opt_acl, "acl"},
{Opt_noacl, "noacl"},
{Opt_usrquota, "usrquota"},
{Opt_grpquota, "grpquota"},
{Opt_coherency_buffered, "coherency=buffered"},
{Opt_coherency_full, "coherency=full"},
{Opt_resv_level, "resv_level=%u"},
{Opt_dir_resv_level, "dir_resv_level=%u"},
{Opt_journal_async_commit, "journal_async_commit"},
{Opt_err_cont, "errors=continue"},
{Opt_err, NULL}
};
#ifdef CONFIG_DEBUG_FS
static int ocfs2_osb_dump(struct ocfs2_super *osb, char *buf, int len)
{
struct ocfs2_cluster_connection *cconn = osb->cconn;
struct ocfs2_recovery_map *rm = osb->recovery_map;
struct ocfs2_orphan_scan *os = &osb->osb_orphan_scan;
int i, out = 0;
unsigned long flags;
out += snprintf(buf + out, len - out,
"%10s => Id: %-s Uuid: %-s Gen: 0x%X Label: %-s\n",
"Device", osb->dev_str, osb->uuid_str,
osb->fs_generation, osb->vol_label);
out += snprintf(buf + out, len - out,
"%10s => State: %d Flags: 0x%lX\n", "Volume",
atomic_read(&osb->vol_state), osb->osb_flags);
out += snprintf(buf + out, len - out,
"%10s => Block: %lu Cluster: %d\n", "Sizes",
osb->sb->s_blocksize, osb->s_clustersize);
out += snprintf(buf + out, len - out,
"%10s => Compat: 0x%X Incompat: 0x%X "
"ROcompat: 0x%X\n",
"Features", osb->s_feature_compat,
osb->s_feature_incompat, osb->s_feature_ro_compat);
out += snprintf(buf + out, len - out,
"%10s => Opts: 0x%lX AtimeQuanta: %u\n", "Mount",
osb->s_mount_opt, osb->s_atime_quantum);
if (cconn) {
out += snprintf(buf + out, len - out,
"%10s => Stack: %s Name: %*s "
"Version: %d.%d\n", "Cluster",
(*osb->osb_cluster_stack == '\0' ?
"o2cb" : osb->osb_cluster_stack),
cconn->cc_namelen, cconn->cc_name,
cconn->cc_version.pv_major,
cconn->cc_version.pv_minor);
}
spin_lock_irqsave(&osb->dc_task_lock, flags);
out += snprintf(buf + out, len - out,
"%10s => Pid: %d Count: %lu WakeSeq: %lu "
"WorkSeq: %lu\n", "DownCnvt",
(osb->dc_task ? task_pid_nr(osb->dc_task) : -1),
osb->blocked_lock_count, osb->dc_wake_sequence,
osb->dc_work_sequence);
spin_unlock_irqrestore(&osb->dc_task_lock, flags);
spin_lock(&osb->osb_lock);
out += snprintf(buf + out, len - out, "%10s => Pid: %d Nodes:",
"Recovery",
(osb->recovery_thread_task ?
task_pid_nr(osb->recovery_thread_task) : -1));
if (rm->rm_used == 0)
out += snprintf(buf + out, len - out, " None\n");
else {
for (i = 0; i < rm->rm_used; i++)
out += snprintf(buf + out, len - out, " %d",
rm->rm_entries[i]);
out += snprintf(buf + out, len - out, "\n");
}
spin_unlock(&osb->osb_lock);
out += snprintf(buf + out, len - out,
"%10s => Pid: %d Interval: %lu\n", "Commit",
(osb->commit_task ? task_pid_nr(osb->commit_task) : -1),
osb->osb_commit_interval);
out += snprintf(buf + out, len - out,
"%10s => State: %d TxnId: %lu NumTxns: %d\n",
"Journal", osb->journal->j_state,
osb->journal->j_trans_id,
atomic_read(&osb->journal->j_num_trans));
out += snprintf(buf + out, len - out,
"%10s => GlobalAllocs: %d LocalAllocs: %d "
"SubAllocs: %d LAWinMoves: %d SAExtends: %d\n",
"Stats",
atomic_read(&osb->alloc_stats.bitmap_data),
atomic_read(&osb->alloc_stats.local_data),
atomic_read(&osb->alloc_stats.bg_allocs),
atomic_read(&osb->alloc_stats.moves),
atomic_read(&osb->alloc_stats.bg_extends));
out += snprintf(buf + out, len - out,
"%10s => State: %u Descriptor: %llu Size: %u bits "
"Default: %u bits\n",
"LocalAlloc", osb->local_alloc_state,
(unsigned long long)osb->la_last_gd,
osb->local_alloc_bits, osb->local_alloc_default_bits);
spin_lock(&osb->osb_lock);
out += snprintf(buf + out, len - out,
"%10s => InodeSlot: %d StolenInodes: %d, "
"MetaSlot: %d StolenMeta: %d\n", "Steal",
osb->s_inode_steal_slot,
atomic_read(&osb->s_num_inodes_stolen),
osb->s_meta_steal_slot,
atomic_read(&osb->s_num_meta_stolen));
spin_unlock(&osb->osb_lock);
out += snprintf(buf + out, len - out, "OrphanScan => ");
out += snprintf(buf + out, len - out, "Local: %u Global: %u ",
os->os_count, os->os_seqno);
out += snprintf(buf + out, len - out, " Last Scan: ");
if (atomic_read(&os->os_state) == ORPHAN_SCAN_INACTIVE)
out += snprintf(buf + out, len - out, "Disabled\n");
else
out += snprintf(buf + out, len - out, "%lu seconds ago\n",
(unsigned long)(ktime_get_seconds() - os->os_scantime));
out += snprintf(buf + out, len - out, "%10s => %3s %10s\n",
"Slots", "Num", "RecoGen");
for (i = 0; i < osb->max_slots; ++i) {
out += snprintf(buf + out, len - out,
"%10s %c %3d %10d\n",
" ",
(i == osb->slot_num ? '*' : ' '),
i, osb->slot_recovery_generations[i]);
}
return out;
}
static int ocfs2_osb_debug_open(struct inode *inode, struct file *file)
{
struct ocfs2_super *osb = inode->i_private;
char *buf = NULL;
buf = kmalloc(PAGE_SIZE, GFP_KERNEL);
if (!buf)
goto bail;
i_size_write(inode, ocfs2_osb_dump(osb, buf, PAGE_SIZE));
file->private_data = buf;
return 0;
bail:
return -ENOMEM;
}
static int ocfs2_debug_release(struct inode *inode, struct file *file)
{
kfree(file->private_data);
return 0;
}
static ssize_t ocfs2_debug_read(struct file *file, char __user *buf,
size_t nbytes, loff_t *ppos)
{
return simple_read_from_buffer(buf, nbytes, ppos, file->private_data,
i_size_read(file->f_mapping->host));
}
#else
static int ocfs2_osb_debug_open(struct inode *inode, struct file *file)
{
return 0;
}
static int ocfs2_debug_release(struct inode *inode, struct file *file)
{
return 0;
}
static ssize_t ocfs2_debug_read(struct file *file, char __user *buf,
size_t nbytes, loff_t *ppos)
{
return 0;
}
#endif /* CONFIG_DEBUG_FS */
static const struct file_operations ocfs2_osb_debug_fops = {
.open = ocfs2_osb_debug_open,
.release = ocfs2_debug_release,
.read = ocfs2_debug_read,
.llseek = generic_file_llseek,
};
static int ocfs2_sync_fs(struct super_block *sb, int wait)
{
int status;
tid_t target;
struct ocfs2_super *osb = OCFS2_SB(sb);
if (ocfs2_is_hard_readonly(osb))
return -EROFS;
if (wait) {
status = ocfs2_flush_truncate_log(osb);
if (status < 0)
mlog_errno(status);
} else {
ocfs2_schedule_truncate_log_flush(osb, 0);
}
if (jbd2_journal_start_commit(OCFS2_SB(sb)->journal->j_journal,
&target)) {
if (wait)
jbd2_log_wait_commit(OCFS2_SB(sb)->journal->j_journal,
target);
}
return 0;
}
static int ocfs2_need_system_inode(struct ocfs2_super *osb, int ino)
{
if (!OCFS2_HAS_RO_COMPAT_FEATURE(osb->sb, OCFS2_FEATURE_RO_COMPAT_USRQUOTA)
&& (ino == USER_QUOTA_SYSTEM_INODE
|| ino == LOCAL_USER_QUOTA_SYSTEM_INODE))
return 0;
if (!OCFS2_HAS_RO_COMPAT_FEATURE(osb->sb, OCFS2_FEATURE_RO_COMPAT_GRPQUOTA)
&& (ino == GROUP_QUOTA_SYSTEM_INODE
|| ino == LOCAL_GROUP_QUOTA_SYSTEM_INODE))
return 0;
return 1;
}
static int ocfs2_init_global_system_inodes(struct ocfs2_super *osb)
{
struct inode *new = NULL;
int status = 0;
int i;
new = ocfs2_iget(osb, osb->root_blkno, OCFS2_FI_FLAG_SYSFILE, 0);
if (IS_ERR(new)) {
status = PTR_ERR(new);
mlog_errno(status);
goto bail;
}
osb->root_inode = new;
new = ocfs2_iget(osb, osb->system_dir_blkno, OCFS2_FI_FLAG_SYSFILE, 0);
if (IS_ERR(new)) {
status = PTR_ERR(new);
mlog_errno(status);
goto bail;
}
osb->sys_root_inode = new;
for (i = OCFS2_FIRST_ONLINE_SYSTEM_INODE;
i <= OCFS2_LAST_GLOBAL_SYSTEM_INODE; i++) {
if (!ocfs2_need_system_inode(osb, i))
continue;
new = ocfs2_get_system_file_inode(osb, i, osb->slot_num);
if (!new) {
ocfs2_release_system_inodes(osb);
status = -EINVAL;
mlog_errno(status);
/* FIXME: Should ERROR_RO_FS */
mlog(ML_ERROR, "Unable to load system inode %d, "
"possibly corrupt fs?", i);
goto bail;
}
// the array now has one ref, so drop this one
iput(new);
}
bail:
if (status)
mlog_errno(status);
return status;
}
static int ocfs2_init_local_system_inodes(struct ocfs2_super *osb)
{
struct inode *new = NULL;
int status = 0;
int i;
for (i = OCFS2_LAST_GLOBAL_SYSTEM_INODE + 1;
i < NUM_SYSTEM_INODES;
i++) {
if (!ocfs2_need_system_inode(osb, i))
continue;
new = ocfs2_get_system_file_inode(osb, i, osb->slot_num);
if (!new) {
ocfs2_release_system_inodes(osb);
status = -EINVAL;
mlog(ML_ERROR, "status=%d, sysfile=%d, slot=%d\n",
status, i, osb->slot_num);
goto bail;
}
/* the array now has one ref, so drop this one */
iput(new);
}
bail:
if (status)
mlog_errno(status);
return status;
}
static void ocfs2_release_system_inodes(struct ocfs2_super *osb)
{
int i;
struct inode *inode;
for (i = 0; i < NUM_GLOBAL_SYSTEM_INODES; i++) {
inode = osb->global_system_inodes[i];
if (inode) {
iput(inode);
osb->global_system_inodes[i] = NULL;
}
}
inode = osb->sys_root_inode;
if (inode) {
iput(inode);
osb->sys_root_inode = NULL;
}
inode = osb->root_inode;
if (inode) {
iput(inode);
osb->root_inode = NULL;
}
if (!osb->local_system_inodes)
return;
for (i = 0; i < NUM_LOCAL_SYSTEM_INODES * osb->max_slots; i++) {
if (osb->local_system_inodes[i]) {
iput(osb->local_system_inodes[i]);
osb->local_system_inodes[i] = NULL;
}
}
kfree(osb->local_system_inodes);
osb->local_system_inodes = NULL;
}
/* We're allocating fs objects, use GFP_NOFS */
static struct inode *ocfs2_alloc_inode(struct super_block *sb)
{
struct ocfs2_inode_info *oi;
oi = kmem_cache_alloc(ocfs2_inode_cachep, GFP_NOFS);
if (!oi)
return NULL;
oi->i_sync_tid = 0;
oi->i_datasync_tid = 0;
memset(&oi->i_dquot, 0, sizeof(oi->i_dquot));
jbd2_journal_init_jbd_inode(&oi->ip_jinode, &oi->vfs_inode);
return &oi->vfs_inode;
}
static void ocfs2_i_callback(struct rcu_head *head)
{
struct inode *inode = container_of(head, struct inode, i_rcu);
kmem_cache_free(ocfs2_inode_cachep, OCFS2_I(inode));
}
static void ocfs2_destroy_inode(struct inode *inode)
{
call_rcu(&inode->i_rcu, ocfs2_i_callback);
}
static unsigned long long ocfs2_max_file_offset(unsigned int bbits,
unsigned int cbits)
{
unsigned int bytes = 1 << cbits;
unsigned int trim = bytes;
unsigned int bitshift = 32;
/*
* i_size and all block offsets in ocfs2 are always 64 bits
* wide. i_clusters is 32 bits, in cluster-sized units. So on
* 64 bit platforms, cluster size will be the limiting factor.
*/
#if BITS_PER_LONG == 32
# if defined(CONFIG_LBDAF)
BUILD_BUG_ON(sizeof(sector_t) != 8);
/*
* We might be limited by page cache size.
*/
if (bytes > PAGE_SIZE) {
bytes = PAGE_SIZE;
trim = 1;
/*
* Shift by 31 here so that we don't get larger than
* MAX_LFS_FILESIZE
*/
bitshift = 31;
}
# else
/*
* We are limited by the size of sector_t. Use block size, as
* that's what we expose to the VFS.
*/
bytes = 1 << bbits;
trim = 1;
bitshift = 31;
# endif
#endif
/*
* Trim by a whole cluster when we can actually approach the
* on-disk limits. Otherwise we can overflow i_clusters when
* an extent start is at the max offset.
*/
return (((unsigned long long)bytes) << bitshift) - trim;
}
static int ocfs2_remount(struct super_block *sb, int *flags, char *data)
{
int incompat_features;
int ret = 0;
struct mount_options parsed_options;
struct ocfs2_super *osb = OCFS2_SB(sb);
u32 tmp;
sync_filesystem(sb);
if (!ocfs2_parse_options(sb, data, &parsed_options, 1) ||
!ocfs2_check_set_options(sb, &parsed_options)) {
ret = -EINVAL;
goto out;
}
tmp = OCFS2_MOUNT_HB_LOCAL | OCFS2_MOUNT_HB_GLOBAL |
OCFS2_MOUNT_HB_NONE;
if ((osb->s_mount_opt & tmp) != (parsed_options.mount_opt & tmp)) {
ret = -EINVAL;
mlog(ML_ERROR, "Cannot change heartbeat mode on remount\n");
goto out;
}
if ((osb->s_mount_opt & OCFS2_MOUNT_DATA_WRITEBACK) !=
(parsed_options.mount_opt & OCFS2_MOUNT_DATA_WRITEBACK)) {
ret = -EINVAL;
mlog(ML_ERROR, "Cannot change data mode on remount\n");
goto out;
}
/* Probably don't want this on remount; it might
* mess with other nodes */
if (!(osb->s_mount_opt & OCFS2_MOUNT_INODE64) &&
(parsed_options.mount_opt & OCFS2_MOUNT_INODE64)) {
ret = -EINVAL;
mlog(ML_ERROR, "Cannot enable inode64 on remount\n");
goto out;
}
/* We're going to/from readonly mode. */
if ((*flags & MS_RDONLY) != (sb->s_flags & MS_RDONLY)) {
/* Disable quota accounting before remounting RO */
if (*flags & MS_RDONLY) {
ret = ocfs2_susp_quotas(osb, 0);
if (ret < 0)
goto out;
}
/* Lock here so the check of HARD_RO and the potential
* setting of SOFT_RO is atomic. */
spin_lock(&osb->osb_lock);
if (osb->osb_flags & OCFS2_OSB_HARD_RO) {
mlog(ML_ERROR, "Remount on readonly device is forbidden.\n");
ret = -EROFS;
goto unlock_osb;
}
if (*flags & MS_RDONLY) {
sb->s_flags |= MS_RDONLY;
osb->osb_flags |= OCFS2_OSB_SOFT_RO;
} else {
if (osb->osb_flags & OCFS2_OSB_ERROR_FS) {
mlog(ML_ERROR, "Cannot remount RDWR "
"filesystem due to previous errors.\n");
ret = -EROFS;
goto unlock_osb;
}
incompat_features = OCFS2_HAS_RO_COMPAT_FEATURE(sb, ~OCFS2_FEATURE_RO_COMPAT_SUPP);
if (incompat_features) {
mlog(ML_ERROR, "Cannot remount RDWR because "
"of unsupported optional features "
"(%x).\n", incompat_features);
ret = -EINVAL;
goto unlock_osb;
}
sb->s_flags &= ~MS_RDONLY;
osb->osb_flags &= ~OCFS2_OSB_SOFT_RO;
}
trace_ocfs2_remount(sb->s_flags, osb->osb_flags, *flags);
unlock_osb:
spin_unlock(&osb->osb_lock);
/* Enable quota accounting after remounting RW */
if (!ret && !(*flags & MS_RDONLY)) {
if (sb_any_quota_suspended(sb))
ret = ocfs2_susp_quotas(osb, 1);
else
ret = ocfs2_enable_quotas(osb);
if (ret < 0) {
/* Return back changes... */
spin_lock(&osb->osb_lock);
sb->s_flags |= MS_RDONLY;
osb->osb_flags |= OCFS2_OSB_SOFT_RO;
spin_unlock(&osb->osb_lock);
goto out;
}
}
}
if (!ret) {
/* Only save off the new mount options in case of a successful
* remount. */
osb->s_mount_opt = parsed_options.mount_opt;
osb->s_atime_quantum = parsed_options.atime_quantum;
osb->preferred_slot = parsed_options.slot;
if (parsed_options.commit_interval)
osb->osb_commit_interval = parsed_options.commit_interval;
if (!ocfs2_is_hard_readonly(osb))
ocfs2_set_journal_params(osb);
sb->s_flags = (sb->s_flags & ~MS_POSIXACL) |
((osb->s_mount_opt & OCFS2_MOUNT_POSIX_ACL) ?
MS_POSIXACL : 0);
}
out:
return ret;
}
static int ocfs2_sb_probe(struct super_block *sb,
struct buffer_head **bh,
int *sector_size,
struct ocfs2_blockcheck_stats *stats)
{
int status, tmpstat;
struct ocfs1_vol_disk_hdr *hdr;
struct ocfs2_dinode *di;
int blksize;
*bh = NULL;
/* may be > 512 */
*sector_size = bdev_logical_block_size(sb->s_bdev);
if (*sector_size > OCFS2_MAX_BLOCKSIZE) {
mlog(ML_ERROR, "Hardware sector size too large: %d (max=%d)\n",
*sector_size, OCFS2_MAX_BLOCKSIZE);
status = -EINVAL;
goto bail;
}
/* Can this really happen? */
if (*sector_size < OCFS2_MIN_BLOCKSIZE)
*sector_size = OCFS2_MIN_BLOCKSIZE;
/* check block zero for old format */
status = ocfs2_get_sector(sb, bh, 0, *sector_size);
if (status < 0) {
mlog_errno(status);
goto bail;
}
hdr = (struct ocfs1_vol_disk_hdr *) (*bh)->b_data;
if (hdr->major_version == OCFS1_MAJOR_VERSION) {
mlog(ML_ERROR, "incompatible version: %u.%u\n",
hdr->major_version, hdr->minor_version);
status = -EINVAL;
}
if (memcmp(hdr->signature, OCFS1_VOLUME_SIGNATURE,
strlen(OCFS1_VOLUME_SIGNATURE)) == 0) {
mlog(ML_ERROR, "incompatible volume signature: %8s\n",
hdr->signature);
status = -EINVAL;
}
brelse(*bh);
*bh = NULL;
if (status < 0) {
mlog(ML_ERROR, "This is an ocfs v1 filesystem which must be "
"upgraded before mounting with ocfs v2\n");
goto bail;
}
/*
* Now check at magic offset for 512, 1024, 2048, 4096
* blocksizes. 4096 is the maximum blocksize because it is
* the minimum clustersize.
*/
status = -EINVAL;
for (blksize = *sector_size;
blksize <= OCFS2_MAX_BLOCKSIZE;
blksize <<= 1) {
tmpstat = ocfs2_get_sector(sb, bh,
OCFS2_SUPER_BLOCK_BLKNO,
blksize);
if (tmpstat < 0) {
status = tmpstat;
mlog_errno(status);
break;
}
di = (struct ocfs2_dinode *) (*bh)->b_data;
memset(stats, 0, sizeof(struct ocfs2_blockcheck_stats));
spin_lock_init(&stats->b_lock);
tmpstat = ocfs2_verify_volume(di, *bh, blksize, stats);
if (tmpstat < 0) {
brelse(*bh);
*bh = NULL;
}
if (tmpstat != -EAGAIN) {
status = tmpstat;
break;
}
}
bail:
return status;
}
static int ocfs2_verify_heartbeat(struct ocfs2_super *osb)
{
u32 hb_enabled = OCFS2_MOUNT_HB_LOCAL | OCFS2_MOUNT_HB_GLOBAL;
if (osb->s_mount_opt & hb_enabled) {
if (ocfs2_mount_local(osb)) {
mlog(ML_ERROR, "Cannot heartbeat on a locally "
"mounted device.\n");
return -EINVAL;
}
if (ocfs2_userspace_stack(osb)) {
mlog(ML_ERROR, "Userspace stack expected, but "
"o2cb heartbeat arguments passed to mount\n");
return -EINVAL;
}
if (((osb->s_mount_opt & OCFS2_MOUNT_HB_GLOBAL) &&
!ocfs2_cluster_o2cb_global_heartbeat(osb)) ||
((osb->s_mount_opt & OCFS2_MOUNT_HB_LOCAL) &&
ocfs2_cluster_o2cb_global_heartbeat(osb))) {
mlog(ML_ERROR, "Mismatching o2cb heartbeat modes\n");
return -EINVAL;
}
}
if (!(osb->s_mount_opt & hb_enabled)) {
if (!ocfs2_mount_local(osb) && !ocfs2_is_hard_readonly(osb) &&
!ocfs2_userspace_stack(osb)) {
mlog(ML_ERROR, "Heartbeat has to be started to mount "
"a read-write clustered device.\n");
return -EINVAL;
}
}
return 0;
}
/*
* If we're using a userspace stack, mount should have passed
* a name that matches the disk. If not, mount should not
* have passed a stack.
*/
static int ocfs2_verify_userspace_stack(struct ocfs2_super *osb,
struct mount_options *mopt)
{
if (!ocfs2_userspace_stack(osb) && mopt->cluster_stack[0]) {
mlog(ML_ERROR,
"cluster stack passed to mount, but this filesystem "
"does not support it\n");
return -EINVAL;
}
if (ocfs2_userspace_stack(osb) &&
strncmp(osb->osb_cluster_stack, mopt->cluster_stack,
OCFS2_STACK_LABEL_LEN)) {
mlog(ML_ERROR,
"cluster stack passed to mount (\"%s\") does not "
"match the filesystem (\"%s\")\n",
mopt->cluster_stack,
osb->osb_cluster_stack);
return -EINVAL;
}
return 0;
}
static int ocfs2_susp_quotas(struct ocfs2_super *osb, int unsuspend)
{
int type;
struct super_block *sb = osb->sb;
unsigned int feature[OCFS2_MAXQUOTAS] = {
OCFS2_FEATURE_RO_COMPAT_USRQUOTA,
OCFS2_FEATURE_RO_COMPAT_GRPQUOTA};
int status = 0;
for (type = 0; type < OCFS2_MAXQUOTAS; type++) {
if (!OCFS2_HAS_RO_COMPAT_FEATURE(sb, feature[type]))
continue;
if (unsuspend)
status = dquot_resume(sb, type);
else {
struct ocfs2_mem_dqinfo *oinfo;
/* Cancel periodic syncing before suspending */
oinfo = sb_dqinfo(sb, type)->dqi_priv;
cancel_delayed_work_sync(&oinfo->dqi_sync_work);
status = dquot_suspend(sb, type);
}
if (status < 0)
break;
}
if (status < 0)
mlog(ML_ERROR, "Failed to suspend/unsuspend quotas on "
"remount (error = %d).\n", status);
return status;
}
static int ocfs2_enable_quotas(struct ocfs2_super *osb)
{
struct inode *inode[OCFS2_MAXQUOTAS] = { NULL, NULL };
struct super_block *sb = osb->sb;
unsigned int feature[OCFS2_MAXQUOTAS] = {
OCFS2_FEATURE_RO_COMPAT_USRQUOTA,
OCFS2_FEATURE_RO_COMPAT_GRPQUOTA};
unsigned int ino[OCFS2_MAXQUOTAS] = {
LOCAL_USER_QUOTA_SYSTEM_INODE,
LOCAL_GROUP_QUOTA_SYSTEM_INODE };
int status;
int type;
sb_dqopt(sb)->flags |= DQUOT_QUOTA_SYS_FILE | DQUOT_NEGATIVE_USAGE;
for (type = 0; type < OCFS2_MAXQUOTAS; type++) {
if (!OCFS2_HAS_RO_COMPAT_FEATURE(sb, feature[type]))
continue;
inode[type] = ocfs2_get_system_file_inode(osb, ino[type],
osb->slot_num);
if (!inode[type]) {
status = -ENOENT;
goto out_quota_off;
}
status = dquot_enable(inode[type], type, QFMT_OCFS2,
DQUOT_USAGE_ENABLED);
if (status < 0)
goto out_quota_off;
}
for (type = 0; type < OCFS2_MAXQUOTAS; type++)
iput(inode[type]);
return 0;
out_quota_off:
ocfs2_disable_quotas(osb);
for (type = 0; type < OCFS2_MAXQUOTAS; type++)
iput(inode[type]);
mlog_errno(status);
return status;
}
static void ocfs2_disable_quotas(struct ocfs2_super *osb)
{
int type;
struct inode *inode;
struct super_block *sb = osb->sb;
struct ocfs2_mem_dqinfo *oinfo;
/* We mostly ignore errors in this function because there's not much
* we can do when we see them */
for (type = 0; type < OCFS2_MAXQUOTAS; type++) {
if (!sb_has_quota_loaded(sb, type))
continue;
oinfo = sb_dqinfo(sb, type)->dqi_priv;
cancel_delayed_work_sync(&oinfo->dqi_sync_work);
inode = igrab(sb->s_dquot.files[type]);
/* Turn off quotas. This will remove all dquot structures from
* memory and so they will be automatically synced to global
* quota files */
dquot_disable(sb, type, DQUOT_USAGE_ENABLED |
DQUOT_LIMITS_ENABLED);
if (!inode)
continue;
iput(inode);
}
}
static int ocfs2_fill_super(struct super_block *sb, void *data, int silent)
{
struct dentry *root;
int status, sector_size;
struct mount_options parsed_options;
struct inode *inode = NULL;
struct ocfs2_super *osb = NULL;
struct buffer_head *bh = NULL;
char nodestr[12];
struct ocfs2_blockcheck_stats stats;
trace_ocfs2_fill_super(sb, data, silent);
if (!ocfs2_parse_options(sb, data, &parsed_options, 0)) {
status = -EINVAL;
goto read_super_error;
}
/* probe for superblock */
status = ocfs2_sb_probe(sb, &bh, §or_size, &stats);
if (status < 0) {
mlog(ML_ERROR, "superblock probe failed!\n");
goto read_super_error;
}
status = ocfs2_initialize_super(sb, bh, sector_size, &stats);
osb = OCFS2_SB(sb);
if (status < 0) {
mlog_errno(status);
goto read_super_error;
}
brelse(bh);
bh = NULL;
if (!ocfs2_check_set_options(sb, &parsed_options)) {
status = -EINVAL;
goto read_super_error;
}
osb->s_mount_opt = parsed_options.mount_opt;
osb->s_atime_quantum = parsed_options.atime_quantum;
osb->preferred_slot = parsed_options.slot;
osb->osb_commit_interval = parsed_options.commit_interval;
ocfs2_la_set_sizes(osb, parsed_options.localalloc_opt);
osb->osb_resv_level = parsed_options.resv_level;
osb->osb_dir_resv_level = parsed_options.resv_level;
if (parsed_options.dir_resv_level == -1)
osb->osb_dir_resv_level = parsed_options.resv_level;
else
osb->osb_dir_resv_level = parsed_options.dir_resv_level;
status = ocfs2_verify_userspace_stack(osb, &parsed_options);
if (status)
goto read_super_error;
sb->s_magic = OCFS2_SUPER_MAGIC;
sb->s_flags = (sb->s_flags & ~(MS_POSIXACL | MS_NOSEC)) |
((osb->s_mount_opt & OCFS2_MOUNT_POSIX_ACL) ? MS_POSIXACL : 0);
/* Hard readonly mode only if: bdev_read_only, MS_RDONLY,
* heartbeat=none */
if (bdev_read_only(sb->s_bdev)) {
if (!(sb->s_flags & MS_RDONLY)) {
status = -EACCES;
mlog(ML_ERROR, "Readonly device detected but readonly "
"mount was not specified.\n");
goto read_super_error;
}
/* You should not be able to start a local heartbeat
* on a readonly device. */
if (osb->s_mount_opt & OCFS2_MOUNT_HB_LOCAL) {
status = -EROFS;
mlog(ML_ERROR, "Local heartbeat specified on readonly "
"device.\n");
goto read_super_error;
}
status = ocfs2_check_journals_nolocks(osb);
if (status < 0) {
if (status == -EROFS)
mlog(ML_ERROR, "Recovery required on readonly "
"file system, but write access is "
"unavailable.\n");
else
mlog_errno(status);
goto read_super_error;
}
ocfs2_set_ro_flag(osb, 1);
printk(KERN_NOTICE "ocfs2: Readonly device (%s) detected. "
"Cluster services will not be used for this mount. "
"Recovery will be skipped.\n", osb->dev_str);
}
if (!ocfs2_is_hard_readonly(osb)) {
if (sb->s_flags & MS_RDONLY)
ocfs2_set_ro_flag(osb, 0);
}
status = ocfs2_verify_heartbeat(osb);
if (status < 0) {
mlog_errno(status);
goto read_super_error;
}
osb->osb_debug_root = debugfs_create_dir(osb->uuid_str,
ocfs2_debugfs_root);
if (!osb->osb_debug_root) {
status = -EINVAL;
mlog(ML_ERROR, "Unable to create per-mount debugfs root.\n");
goto read_super_error;
}
osb->osb_ctxt = debugfs_create_file("fs_state", S_IFREG|S_IRUSR,
osb->osb_debug_root,
osb,
&ocfs2_osb_debug_fops);
if (!osb->osb_ctxt) {
status = -EINVAL;
mlog_errno(status);
goto read_super_error;
}
if (ocfs2_meta_ecc(osb)) {
status = ocfs2_blockcheck_stats_debugfs_install(
&osb->osb_ecc_stats,
osb->osb_debug_root);
if (status) {
mlog(ML_ERROR,
"Unable to create blockcheck statistics "
"files\n");
goto read_super_error;
}
}
status = ocfs2_mount_volume(sb);
if (status < 0)
goto read_super_error;
if (osb->root_inode)
inode = igrab(osb->root_inode);
if (!inode) {
status = -EIO;
mlog_errno(status);
goto read_super_error;
}
root = d_make_root(inode);
if (!root) {
status = -ENOMEM;
mlog_errno(status);
goto read_super_error;
}
sb->s_root = root;
ocfs2_complete_mount_recovery(osb);
if (ocfs2_mount_local(osb))
snprintf(nodestr, sizeof(nodestr), "local");
else
snprintf(nodestr, sizeof(nodestr), "%u", osb->node_num);
printk(KERN_INFO "ocfs2: Mounting device (%s) on (node %s, slot %d) "
"with %s data mode.\n",
osb->dev_str, nodestr, osb->slot_num,
osb->s_mount_opt & OCFS2_MOUNT_DATA_WRITEBACK ? "writeback" :
"ordered");
atomic_set(&osb->vol_state, VOLUME_MOUNTED);
wake_up(&osb->osb_mount_event);
/* Now we can initialize quotas because we can afford to wait
* for cluster locks recovery now. That also means that truncation
* log recovery can happen but that waits for proper quota setup */
if (!(sb->s_flags & MS_RDONLY)) {
status = ocfs2_enable_quotas(osb);
if (status < 0) {
/* We have to err-out specially here because
* s_root is already set */
mlog_errno(status);
atomic_set(&osb->vol_state, VOLUME_DISABLED);
wake_up(&osb->osb_mount_event);
return status;
}
}
ocfs2_complete_quota_recovery(osb);
/* Now we wake up again for processes waiting for quotas */
atomic_set(&osb->vol_state, VOLUME_MOUNTED_QUOTAS);
wake_up(&osb->osb_mount_event);
/* Start this when the mount is almost sure of being successful */
ocfs2_orphan_scan_start(osb);
/* Create filecheck sysfile /sys/fs/ocfs2/<devname>/filecheck */
ocfs2_filecheck_create_sysfs(sb);
return status;
read_super_error:
brelse(bh);
if (osb) {
atomic_set(&osb->vol_state, VOLUME_DISABLED);
wake_up(&osb->osb_mount_event);
ocfs2_dismount_volume(sb, 1);
}
if (status)
mlog_errno(status);
return status;
}
static struct dentry *ocfs2_mount(struct file_system_type *fs_type,
int flags,
const char *dev_name,
void *data)
{
return mount_bdev(fs_type, flags, dev_name, data, ocfs2_fill_super);
}
static struct file_system_type ocfs2_fs_type = {
.owner = THIS_MODULE,
.name = "ocfs2",
.mount = ocfs2_mount,
.kill_sb = kill_block_super,
.fs_flags = FS_REQUIRES_DEV|FS_RENAME_DOES_D_MOVE,
.next = NULL
};
MODULE_ALIAS_FS("ocfs2");
static int ocfs2_check_set_options(struct super_block *sb,
struct mount_options *options)
{
if (options->mount_opt & OCFS2_MOUNT_USRQUOTA &&
!OCFS2_HAS_RO_COMPAT_FEATURE(sb,
OCFS2_FEATURE_RO_COMPAT_USRQUOTA)) {
mlog(ML_ERROR, "User quotas were requested, but this "
"filesystem does not have the feature enabled.\n");
return 0;
}
if (options->mount_opt & OCFS2_MOUNT_GRPQUOTA &&
!OCFS2_HAS_RO_COMPAT_FEATURE(sb,
OCFS2_FEATURE_RO_COMPAT_GRPQUOTA)) {
mlog(ML_ERROR, "Group quotas were requested, but this "
"filesystem does not have the feature enabled.\n");
return 0;
}
if (options->mount_opt & OCFS2_MOUNT_POSIX_ACL &&
!OCFS2_HAS_INCOMPAT_FEATURE(sb, OCFS2_FEATURE_INCOMPAT_XATTR)) {
mlog(ML_ERROR, "ACL support requested but extended attributes "
"feature is not enabled\n");
return 0;
}
/* No ACL setting specified? Use XATTR feature... */
if (!(options->mount_opt & (OCFS2_MOUNT_POSIX_ACL |
OCFS2_MOUNT_NO_POSIX_ACL))) {
if (OCFS2_HAS_INCOMPAT_FEATURE(sb, OCFS2_FEATURE_INCOMPAT_XATTR))
options->mount_opt |= OCFS2_MOUNT_POSIX_ACL;
else
options->mount_opt |= OCFS2_MOUNT_NO_POSIX_ACL;
}
return 1;
}
static int ocfs2_parse_options(struct super_block *sb,
char *options,
struct mount_options *mopt,
int is_remount)
{
int status, user_stack = 0;
char *p;
u32 tmp;
int token, option;
substring_t args[MAX_OPT_ARGS];
trace_ocfs2_parse_options(is_remount, options ? options : "(none)");
mopt->commit_interval = 0;
mopt->mount_opt = OCFS2_MOUNT_NOINTR;
mopt->atime_quantum = OCFS2_DEFAULT_ATIME_QUANTUM;
mopt->slot = OCFS2_INVALID_SLOT;
mopt->localalloc_opt = -1;
mopt->cluster_stack[0] = '\0';
mopt->resv_level = OCFS2_DEFAULT_RESV_LEVEL;
mopt->dir_resv_level = -1;
if (!options) {
status = 1;
goto bail;
}
while ((p = strsep(&options, ",")) != NULL) {
if (!*p)
continue;
token = match_token(p, tokens, args);
switch (token) {
case Opt_hb_local:
mopt->mount_opt |= OCFS2_MOUNT_HB_LOCAL;
break;
case Opt_hb_none:
mopt->mount_opt |= OCFS2_MOUNT_HB_NONE;
break;
case Opt_hb_global:
mopt->mount_opt |= OCFS2_MOUNT_HB_GLOBAL;
break;
case Opt_barrier:
if (match_int(&args[0], &option)) {
status = 0;
goto bail;
}
if (option)
mopt->mount_opt |= OCFS2_MOUNT_BARRIER;
else
mopt->mount_opt &= ~OCFS2_MOUNT_BARRIER;
break;
case Opt_intr:
mopt->mount_opt &= ~OCFS2_MOUNT_NOINTR;
break;
case Opt_nointr:
mopt->mount_opt |= OCFS2_MOUNT_NOINTR;
break;
case Opt_err_panic:
mopt->mount_opt &= ~OCFS2_MOUNT_ERRORS_CONT;
mopt->mount_opt &= ~OCFS2_MOUNT_ERRORS_ROFS;
mopt->mount_opt |= OCFS2_MOUNT_ERRORS_PANIC;
break;
case Opt_err_ro:
mopt->mount_opt &= ~OCFS2_MOUNT_ERRORS_CONT;
mopt->mount_opt &= ~OCFS2_MOUNT_ERRORS_PANIC;
mopt->mount_opt |= OCFS2_MOUNT_ERRORS_ROFS;
break;
case Opt_err_cont:
mopt->mount_opt &= ~OCFS2_MOUNT_ERRORS_ROFS;
mopt->mount_opt &= ~OCFS2_MOUNT_ERRORS_PANIC;
mopt->mount_opt |= OCFS2_MOUNT_ERRORS_CONT;
break;
case Opt_data_ordered:
mopt->mount_opt &= ~OCFS2_MOUNT_DATA_WRITEBACK;
break;
case Opt_data_writeback:
mopt->mount_opt |= OCFS2_MOUNT_DATA_WRITEBACK;
break;
case Opt_user_xattr:
mopt->mount_opt &= ~OCFS2_MOUNT_NOUSERXATTR;
break;
case Opt_nouser_xattr:
mopt->mount_opt |= OCFS2_MOUNT_NOUSERXATTR;
break;
case Opt_atime_quantum:
if (match_int(&args[0], &option)) {
status = 0;
goto bail;
}
if (option >= 0)
mopt->atime_quantum = option;
break;
case Opt_slot:
if (match_int(&args[0], &option)) {
status = 0;
goto bail;
}
if (option)
mopt->slot = (s16)option;
break;
case Opt_commit:
if (match_int(&args[0], &option)) {
status = 0;
goto bail;
}
if (option < 0)
return 0;
if (option == 0)
option = JBD2_DEFAULT_MAX_COMMIT_AGE;
mopt->commit_interval = HZ * option;
break;
case Opt_localalloc:
if (match_int(&args[0], &option)) {
status = 0;
goto bail;
}
if (option >= 0)
mopt->localalloc_opt = option;
break;
case Opt_localflocks:
/*
* Changing this during remount could race
* flock() requests, or "unbalance" existing
* ones (e.g., a lock is taken in one mode but
* dropped in the other). If users care enough
* to flip locking modes during remount, we
* could add a "local" flag to individual
* flock structures for proper tracking of
* state.
*/
if (!is_remount)
mopt->mount_opt |= OCFS2_MOUNT_LOCALFLOCKS;
break;
case Opt_stack:
/* Check both that the option we were passed
* is of the right length and that it is a proper
* string of the right length.
*/
if (((args[0].to - args[0].from) !=
OCFS2_STACK_LABEL_LEN) ||
(strnlen(args[0].from,
OCFS2_STACK_LABEL_LEN) !=
OCFS2_STACK_LABEL_LEN)) {
mlog(ML_ERROR,
"Invalid cluster_stack option\n");
status = 0;
goto bail;
}
memcpy(mopt->cluster_stack, args[0].from,
OCFS2_STACK_LABEL_LEN);
mopt->cluster_stack[OCFS2_STACK_LABEL_LEN] = '\0';
/*
* Open code the memcmp here as we don't have
* an osb to pass to
* ocfs2_userspace_stack().
*/
if (memcmp(mopt->cluster_stack,
OCFS2_CLASSIC_CLUSTER_STACK,
OCFS2_STACK_LABEL_LEN))
user_stack = 1;
break;
case Opt_inode64:
mopt->mount_opt |= OCFS2_MOUNT_INODE64;
break;
case Opt_usrquota:
mopt->mount_opt |= OCFS2_MOUNT_USRQUOTA;
break;
case Opt_grpquota:
mopt->mount_opt |= OCFS2_MOUNT_GRPQUOTA;
break;
case Opt_coherency_buffered:
mopt->mount_opt |= OCFS2_MOUNT_COHERENCY_BUFFERED;
break;
case Opt_coherency_full:
mopt->mount_opt &= ~OCFS2_MOUNT_COHERENCY_BUFFERED;
break;
case Opt_acl:
mopt->mount_opt |= OCFS2_MOUNT_POSIX_ACL;
mopt->mount_opt &= ~OCFS2_MOUNT_NO_POSIX_ACL;
break;
case Opt_noacl:
mopt->mount_opt |= OCFS2_MOUNT_NO_POSIX_ACL;
mopt->mount_opt &= ~OCFS2_MOUNT_POSIX_ACL;
break;
case Opt_resv_level:
if (is_remount)
break;
if (match_int(&args[0], &option)) {
status = 0;
goto bail;
}
if (option >= OCFS2_MIN_RESV_LEVEL &&
option < OCFS2_MAX_RESV_LEVEL)
mopt->resv_level = option;
break;
case Opt_dir_resv_level:
if (is_remount)
break;
if (match_int(&args[0], &option)) {
status = 0;
goto bail;
}
if (option >= OCFS2_MIN_RESV_LEVEL &&
option < OCFS2_MAX_RESV_LEVEL)
mopt->dir_resv_level = option;
break;
case Opt_journal_async_commit:
mopt->mount_opt |= OCFS2_MOUNT_JOURNAL_ASYNC_COMMIT;
break;
default:
mlog(ML_ERROR,
"Unrecognized mount option \"%s\" "
"or missing value\n", p);
status = 0;
goto bail;
}
}
if (user_stack == 0) {
/* Ensure only one heartbeat mode */
tmp = mopt->mount_opt & (OCFS2_MOUNT_HB_LOCAL |
OCFS2_MOUNT_HB_GLOBAL |
OCFS2_MOUNT_HB_NONE);
if (hweight32(tmp) != 1) {
mlog(ML_ERROR, "Invalid heartbeat mount options\n");
status = 0;
goto bail;
}
}
status = 1;
bail:
return status;
}
static int ocfs2_show_options(struct seq_file *s, struct dentry *root)
{
struct ocfs2_super *osb = OCFS2_SB(root->d_sb);
unsigned long opts = osb->s_mount_opt;
unsigned int local_alloc_megs;
if (opts & (OCFS2_MOUNT_HB_LOCAL | OCFS2_MOUNT_HB_GLOBAL)) {
seq_printf(s, ",_netdev");
if (opts & OCFS2_MOUNT_HB_LOCAL)
seq_printf(s, ",%s", OCFS2_HB_LOCAL);
else
seq_printf(s, ",%s", OCFS2_HB_GLOBAL);
} else
seq_printf(s, ",%s", OCFS2_HB_NONE);
if (opts & OCFS2_MOUNT_NOINTR)
seq_printf(s, ",nointr");
if (opts & OCFS2_MOUNT_DATA_WRITEBACK)
seq_printf(s, ",data=writeback");
else
seq_printf(s, ",data=ordered");
if (opts & OCFS2_MOUNT_BARRIER)
seq_printf(s, ",barrier=1");
if (opts & OCFS2_MOUNT_ERRORS_PANIC)
seq_printf(s, ",errors=panic");
else if (opts & OCFS2_MOUNT_ERRORS_CONT)
seq_printf(s, ",errors=continue");
else
seq_printf(s, ",errors=remount-ro");
if (osb->preferred_slot != OCFS2_INVALID_SLOT)
seq_printf(s, ",preferred_slot=%d", osb->preferred_slot);
seq_printf(s, ",atime_quantum=%u", osb->s_atime_quantum);
if (osb->osb_commit_interval)
seq_printf(s, ",commit=%u",
(unsigned) (osb->osb_commit_interval / HZ));
local_alloc_megs = osb->local_alloc_bits >> (20 - osb->s_clustersize_bits);
if (local_alloc_megs != ocfs2_la_default_mb(osb))
seq_printf(s, ",localalloc=%d", local_alloc_megs);
if (opts & OCFS2_MOUNT_LOCALFLOCKS)
seq_printf(s, ",localflocks,");
if (osb->osb_cluster_stack[0])
seq_show_option_n(s, "cluster_stack", osb->osb_cluster_stack,
OCFS2_STACK_LABEL_LEN);
if (opts & OCFS2_MOUNT_USRQUOTA)
seq_printf(s, ",usrquota");
if (opts & OCFS2_MOUNT_GRPQUOTA)
seq_printf(s, ",grpquota");
if (opts & OCFS2_MOUNT_COHERENCY_BUFFERED)
seq_printf(s, ",coherency=buffered");
else
seq_printf(s, ",coherency=full");
if (opts & OCFS2_MOUNT_NOUSERXATTR)
seq_printf(s, ",nouser_xattr");
else
seq_printf(s, ",user_xattr");
if (opts & OCFS2_MOUNT_INODE64)
seq_printf(s, ",inode64");
if (opts & OCFS2_MOUNT_POSIX_ACL)
seq_printf(s, ",acl");
else
seq_printf(s, ",noacl");
if (osb->osb_resv_level != OCFS2_DEFAULT_RESV_LEVEL)
seq_printf(s, ",resv_level=%d", osb->osb_resv_level);
if (osb->osb_dir_resv_level != osb->osb_resv_level)
seq_printf(s, ",dir_resv_level=%d", osb->osb_resv_level);
if (opts & OCFS2_MOUNT_JOURNAL_ASYNC_COMMIT)
seq_printf(s, ",journal_async_commit");
return 0;
}
static int __init ocfs2_init(void)
{
int status;
status = init_ocfs2_uptodate_cache();
if (status < 0)
goto out1;
status = ocfs2_initialize_mem_caches();
if (status < 0)
goto out2;
ocfs2_debugfs_root = debugfs_create_dir("ocfs2", NULL);
if (!ocfs2_debugfs_root) {
status = -ENOMEM;
mlog(ML_ERROR, "Unable to create ocfs2 debugfs root.\n");
goto out3;
}
ocfs2_set_locking_protocol();
status = register_quota_format(&ocfs2_quota_format);
if (status < 0)
goto out3;
status = register_filesystem(&ocfs2_fs_type);
if (!status)
return 0;
unregister_quota_format(&ocfs2_quota_format);
out3:
debugfs_remove(ocfs2_debugfs_root);
ocfs2_free_mem_caches();
out2:
exit_ocfs2_uptodate_cache();
out1:
mlog_errno(status);
return status;
}
static void __exit ocfs2_exit(void)
{
unregister_quota_format(&ocfs2_quota_format);
debugfs_remove(ocfs2_debugfs_root);
ocfs2_free_mem_caches();
unregister_filesystem(&ocfs2_fs_type);
exit_ocfs2_uptodate_cache();
}
static void ocfs2_put_super(struct super_block *sb)
{
trace_ocfs2_put_super(sb);
ocfs2_sync_blockdev(sb);
ocfs2_dismount_volume(sb, 0);
ocfs2_filecheck_remove_sysfs(sb);
}
static int ocfs2_statfs(struct dentry *dentry, struct kstatfs *buf)
{
struct ocfs2_super *osb;
u32 numbits, freebits;
int status;
struct ocfs2_dinode *bm_lock;
struct buffer_head *bh = NULL;
struct inode *inode = NULL;
trace_ocfs2_statfs(dentry->d_sb, buf);
osb = OCFS2_SB(dentry->d_sb);
inode = ocfs2_get_system_file_inode(osb,
GLOBAL_BITMAP_SYSTEM_INODE,
OCFS2_INVALID_SLOT);
if (!inode) {
mlog(ML_ERROR, "failed to get bitmap inode\n");
status = -EIO;
goto bail;
}
status = ocfs2_inode_lock(inode, &bh, 0);
if (status < 0) {
mlog_errno(status);
goto bail;
}
bm_lock = (struct ocfs2_dinode *) bh->b_data;
numbits = le32_to_cpu(bm_lock->id1.bitmap1.i_total);
freebits = numbits - le32_to_cpu(bm_lock->id1.bitmap1.i_used);
buf->f_type = OCFS2_SUPER_MAGIC;
buf->f_bsize = dentry->d_sb->s_blocksize;
buf->f_namelen = OCFS2_MAX_FILENAME_LEN;
buf->f_blocks = ((sector_t) numbits) *
(osb->s_clustersize >> osb->sb->s_blocksize_bits);
buf->f_bfree = ((sector_t) freebits) *
(osb->s_clustersize >> osb->sb->s_blocksize_bits);
buf->f_bavail = buf->f_bfree;
buf->f_files = numbits;
buf->f_ffree = freebits;
buf->f_fsid.val[0] = crc32_le(0, osb->uuid_str, OCFS2_VOL_UUID_LEN)
& 0xFFFFFFFFUL;
buf->f_fsid.val[1] = crc32_le(0, osb->uuid_str + OCFS2_VOL_UUID_LEN,
OCFS2_VOL_UUID_LEN) & 0xFFFFFFFFUL;
brelse(bh);
ocfs2_inode_unlock(inode, 0);
status = 0;
bail:
iput(inode);
if (status)
mlog_errno(status);
return status;
}
static void ocfs2_inode_init_once(void *data)
{
struct ocfs2_inode_info *oi = data;
oi->ip_flags = 0;
oi->ip_open_count = 0;
spin_lock_init(&oi->ip_lock);
ocfs2_extent_map_init(&oi->vfs_inode);
INIT_LIST_HEAD(&oi->ip_io_markers);
INIT_LIST_HEAD(&oi->ip_unwritten_list);
oi->ip_dir_start_lookup = 0;
init_rwsem(&oi->ip_alloc_sem);
init_rwsem(&oi->ip_xattr_sem);
mutex_init(&oi->ip_io_mutex);
oi->ip_blkno = 0ULL;
oi->ip_clusters = 0;
ocfs2_resv_init_once(&oi->ip_la_data_resv);
ocfs2_lock_res_init_once(&oi->ip_rw_lockres);
ocfs2_lock_res_init_once(&oi->ip_inode_lockres);
ocfs2_lock_res_init_once(&oi->ip_open_lockres);
ocfs2_metadata_cache_init(INODE_CACHE(&oi->vfs_inode),
&ocfs2_inode_caching_ops);
inode_init_once(&oi->vfs_inode);
}
static int ocfs2_initialize_mem_caches(void)
{
ocfs2_inode_cachep = kmem_cache_create("ocfs2_inode_cache",
sizeof(struct ocfs2_inode_info),
0,
(SLAB_HWCACHE_ALIGN|SLAB_RECLAIM_ACCOUNT|
SLAB_MEM_SPREAD|SLAB_ACCOUNT),
ocfs2_inode_init_once);
ocfs2_dquot_cachep = kmem_cache_create("ocfs2_dquot_cache",
sizeof(struct ocfs2_dquot),
0,
(SLAB_HWCACHE_ALIGN|SLAB_RECLAIM_ACCOUNT|
SLAB_MEM_SPREAD),
NULL);
ocfs2_qf_chunk_cachep = kmem_cache_create("ocfs2_qf_chunk_cache",
sizeof(struct ocfs2_quota_chunk),
0,
(SLAB_RECLAIM_ACCOUNT|SLAB_MEM_SPREAD),
NULL);
if (!ocfs2_inode_cachep || !ocfs2_dquot_cachep ||
!ocfs2_qf_chunk_cachep) {
if (ocfs2_inode_cachep)
kmem_cache_destroy(ocfs2_inode_cachep);
if (ocfs2_dquot_cachep)
kmem_cache_destroy(ocfs2_dquot_cachep);
if (ocfs2_qf_chunk_cachep)
kmem_cache_destroy(ocfs2_qf_chunk_cachep);
return -ENOMEM;
}
return 0;
}
static void ocfs2_free_mem_caches(void)
{
/*
* Make sure all delayed rcu free inodes are flushed before we
* destroy cache.
*/
rcu_barrier();
if (ocfs2_inode_cachep)
kmem_cache_destroy(ocfs2_inode_cachep);
ocfs2_inode_cachep = NULL;
if (ocfs2_dquot_cachep)
kmem_cache_destroy(ocfs2_dquot_cachep);
ocfs2_dquot_cachep = NULL;
if (ocfs2_qf_chunk_cachep)
kmem_cache_destroy(ocfs2_qf_chunk_cachep);
ocfs2_qf_chunk_cachep = NULL;
}
static int ocfs2_get_sector(struct super_block *sb,
struct buffer_head **bh,
int block,
int sect_size)
{
if (!sb_set_blocksize(sb, sect_size)) {
mlog(ML_ERROR, "unable to set blocksize\n");
return -EIO;
}
*bh = sb_getblk(sb, block);
if (!*bh) {
mlog_errno(-ENOMEM);
return -ENOMEM;
}
lock_buffer(*bh);
if (!buffer_dirty(*bh))
clear_buffer_uptodate(*bh);
unlock_buffer(*bh);
ll_rw_block(REQ_OP_READ, 0, 1, bh);
wait_on_buffer(*bh);
if (!buffer_uptodate(*bh)) {
mlog_errno(-EIO);
brelse(*bh);
*bh = NULL;
return -EIO;
}
return 0;
}
static int ocfs2_mount_volume(struct super_block *sb)
{
int status = 0;
int unlock_super = 0;
struct ocfs2_super *osb = OCFS2_SB(sb);
if (ocfs2_is_hard_readonly(osb))
goto leave;
status = ocfs2_dlm_init(osb);
if (status < 0) {
mlog_errno(status);
goto leave;
}
status = ocfs2_super_lock(osb, 1);
if (status < 0) {
mlog_errno(status);
goto leave;
}
unlock_super = 1;
/* This will load up the node map and add ourselves to it. */
status = ocfs2_find_slot(osb);
if (status < 0) {
mlog_errno(status);
goto leave;
}
/* load all node-local system inodes */
status = ocfs2_init_local_system_inodes(osb);
if (status < 0) {
mlog_errno(status);
goto leave;
}
status = ocfs2_check_volume(osb);
if (status < 0) {
mlog_errno(status);
goto leave;
}
status = ocfs2_truncate_log_init(osb);
if (status < 0)
mlog_errno(status);
leave:
if (unlock_super)
ocfs2_super_unlock(osb, 1);
return status;
}
static void ocfs2_dismount_volume(struct super_block *sb, int mnt_err)
{
int tmp, hangup_needed = 0;
struct ocfs2_super *osb = NULL;
char nodestr[12];
trace_ocfs2_dismount_volume(sb);
BUG_ON(!sb);
osb = OCFS2_SB(sb);
BUG_ON(!osb);
debugfs_remove(osb->osb_ctxt);
/* Orphan scan should be stopped as early as possible */
ocfs2_orphan_scan_stop(osb);
ocfs2_disable_quotas(osb);
/* All dquots should be freed by now */
WARN_ON(!llist_empty(&osb->dquot_drop_list));
/* Wait for worker to be done with the work structure in osb */
cancel_work_sync(&osb->dquot_drop_work);
ocfs2_shutdown_local_alloc(osb);
ocfs2_truncate_log_shutdown(osb);
/* This will disable recovery and flush any recovery work. */
ocfs2_recovery_exit(osb);
ocfs2_journal_shutdown(osb);
ocfs2_sync_blockdev(sb);
ocfs2_purge_refcount_trees(osb);
/* No cluster connection means we've failed during mount, so skip
* all the steps which depended on that to complete. */
if (osb->cconn) {
tmp = ocfs2_super_lock(osb, 1);
if (tmp < 0) {
mlog_errno(tmp);
return;
}
}
if (osb->slot_num != OCFS2_INVALID_SLOT)
ocfs2_put_slot(osb);
if (osb->cconn)
ocfs2_super_unlock(osb, 1);
ocfs2_release_system_inodes(osb);
/*
* If we're dismounting due to mount error, mount.ocfs2 will clean
* up heartbeat. If we're a local mount, there is no heartbeat.
* If we failed before we got a uuid_str yet, we can't stop
* heartbeat. Otherwise, do it.
*/
if (!mnt_err && !ocfs2_mount_local(osb) && osb->uuid_str &&
!ocfs2_is_hard_readonly(osb))
hangup_needed = 1;
if (osb->cconn)
ocfs2_dlm_shutdown(osb, hangup_needed);
ocfs2_blockcheck_stats_debugfs_remove(&osb->osb_ecc_stats);
debugfs_remove(osb->osb_debug_root);
if (hangup_needed)
ocfs2_cluster_hangup(osb->uuid_str, strlen(osb->uuid_str));
atomic_set(&osb->vol_state, VOLUME_DISMOUNTED);
if (ocfs2_mount_local(osb))
snprintf(nodestr, sizeof(nodestr), "local");
else
snprintf(nodestr, sizeof(nodestr), "%u", osb->node_num);
printk(KERN_INFO "ocfs2: Unmounting device (%s) on (node %s)\n",
osb->dev_str, nodestr);
ocfs2_delete_osb(osb);
kfree(osb);
sb->s_dev = 0;
sb->s_fs_info = NULL;
}
static int ocfs2_setup_osb_uuid(struct ocfs2_super *osb, const unsigned char *uuid,
unsigned uuid_bytes)
{
int i, ret;
char *ptr;
BUG_ON(uuid_bytes != OCFS2_VOL_UUID_LEN);
osb->uuid_str = kzalloc(OCFS2_VOL_UUID_LEN * 2 + 1, GFP_KERNEL);
if (osb->uuid_str == NULL)
return -ENOMEM;
for (i = 0, ptr = osb->uuid_str; i < OCFS2_VOL_UUID_LEN; i++) {
/* print with null */
ret = snprintf(ptr, 3, "%02X", uuid[i]);
if (ret != 2) /* drop super cleans up */
return -EINVAL;
/* then only advance past the last char */
ptr += 2;
}
return 0;
}
/* Make sure entire volume is addressable by our journal. Requires
osb_clusters_at_boot to be valid and for the journal to have been
initialized by ocfs2_journal_init(). */
static int ocfs2_journal_addressable(struct ocfs2_super *osb)
{
int status = 0;
u64 max_block =
ocfs2_clusters_to_blocks(osb->sb,
osb->osb_clusters_at_boot) - 1;
/* 32-bit block number is always OK. */
if (max_block <= (u32)~0ULL)
goto out;
/* Volume is "huge", so see if our journal is new enough to
support it. */
if (!(OCFS2_HAS_COMPAT_FEATURE(osb->sb,
OCFS2_FEATURE_COMPAT_JBD2_SB) &&
jbd2_journal_check_used_features(osb->journal->j_journal, 0, 0,
JBD2_FEATURE_INCOMPAT_64BIT))) {
mlog(ML_ERROR, "The journal cannot address the entire volume. "
"Enable the 'block64' journal option with tunefs.ocfs2");
status = -EFBIG;
goto out;
}
out:
return status;
}
static int ocfs2_initialize_super(struct super_block *sb,
struct buffer_head *bh,
int sector_size,
struct ocfs2_blockcheck_stats *stats)
{
int status;
int i, cbits, bbits;
struct ocfs2_dinode *di = (struct ocfs2_dinode *)bh->b_data;
struct inode *inode = NULL;
struct ocfs2_journal *journal;
struct ocfs2_super *osb;
u64 total_blocks;
osb = kzalloc(sizeof(struct ocfs2_super), GFP_KERNEL);
if (!osb) {
status = -ENOMEM;
mlog_errno(status);
goto bail;
}
sb->s_fs_info = osb;
sb->s_op = &ocfs2_sops;
sb->s_d_op = &ocfs2_dentry_ops;
sb->s_export_op = &ocfs2_export_ops;
sb->s_qcop = &dquot_quotactl_sysfile_ops;
sb->dq_op = &ocfs2_quota_operations;
sb->s_quota_types = QTYPE_MASK_USR | QTYPE_MASK_GRP;
sb->s_xattr = ocfs2_xattr_handlers;
sb->s_time_gran = 1;
sb->s_flags |= MS_NOATIME;
/* this is needed to support O_LARGEFILE */
cbits = le32_to_cpu(di->id2.i_super.s_clustersize_bits);
bbits = le32_to_cpu(di->id2.i_super.s_blocksize_bits);
sb->s_maxbytes = ocfs2_max_file_offset(bbits, cbits);
memcpy(sb->s_uuid, di->id2.i_super.s_uuid,
sizeof(di->id2.i_super.s_uuid));
osb->osb_dx_mask = (1 << (cbits - bbits)) - 1;
for (i = 0; i < 3; i++)
osb->osb_dx_seed[i] = le32_to_cpu(di->id2.i_super.s_dx_seed[i]);
osb->osb_dx_seed[3] = le32_to_cpu(di->id2.i_super.s_uuid_hash);
osb->sb = sb;
osb->s_sectsize_bits = blksize_bits(sector_size);
BUG_ON(!osb->s_sectsize_bits);
spin_lock_init(&osb->dc_task_lock);
init_waitqueue_head(&osb->dc_event);
osb->dc_work_sequence = 0;
osb->dc_wake_sequence = 0;
INIT_LIST_HEAD(&osb->blocked_lock_list);
osb->blocked_lock_count = 0;
spin_lock_init(&osb->osb_lock);
spin_lock_init(&osb->osb_xattr_lock);
ocfs2_init_steal_slots(osb);
mutex_init(&osb->system_file_mutex);
atomic_set(&osb->alloc_stats.moves, 0);
atomic_set(&osb->alloc_stats.local_data, 0);
atomic_set(&osb->alloc_stats.bitmap_data, 0);
atomic_set(&osb->alloc_stats.bg_allocs, 0);
atomic_set(&osb->alloc_stats.bg_extends, 0);
/* Copy the blockcheck stats from the superblock probe */
osb->osb_ecc_stats = *stats;
ocfs2_init_node_maps(osb);
snprintf(osb->dev_str, sizeof(osb->dev_str), "%u,%u",
MAJOR(osb->sb->s_dev), MINOR(osb->sb->s_dev));
osb->max_slots = le16_to_cpu(di->id2.i_super.s_max_slots);
if (osb->max_slots > OCFS2_MAX_SLOTS || osb->max_slots == 0) {
mlog(ML_ERROR, "Invalid number of node slots (%u)\n",
osb->max_slots);
status = -EINVAL;
goto bail;
}
ocfs2_orphan_scan_init(osb);
status = ocfs2_recovery_init(osb);
if (status) {
mlog(ML_ERROR, "Unable to initialize recovery state\n");
mlog_errno(status);
goto bail;
}
init_waitqueue_head(&osb->checkpoint_event);
osb->s_atime_quantum = OCFS2_DEFAULT_ATIME_QUANTUM;
osb->slot_num = OCFS2_INVALID_SLOT;
osb->s_xattr_inline_size = le16_to_cpu(
di->id2.i_super.s_xattr_inline_size);
osb->local_alloc_state = OCFS2_LA_UNUSED;
osb->local_alloc_bh = NULL;
INIT_DELAYED_WORK(&osb->la_enable_wq, ocfs2_la_enable_worker);
init_waitqueue_head(&osb->osb_mount_event);
status = ocfs2_resmap_init(osb, &osb->osb_la_resmap);
if (status) {
mlog_errno(status);
goto bail;
}
osb->vol_label = kmalloc(OCFS2_MAX_VOL_LABEL_LEN, GFP_KERNEL);
if (!osb->vol_label) {
mlog(ML_ERROR, "unable to alloc vol label\n");
status = -ENOMEM;
goto bail;
}
osb->slot_recovery_generations =
kcalloc(osb->max_slots, sizeof(*osb->slot_recovery_generations),
GFP_KERNEL);
if (!osb->slot_recovery_generations) {
status = -ENOMEM;
mlog_errno(status);
goto bail;
}
init_waitqueue_head(&osb->osb_wipe_event);
osb->osb_orphan_wipes = kcalloc(osb->max_slots,
sizeof(*osb->osb_orphan_wipes),
GFP_KERNEL);
if (!osb->osb_orphan_wipes) {
status = -ENOMEM;
mlog_errno(status);
goto bail;
}
osb->osb_rf_lock_tree = RB_ROOT;
osb->s_feature_compat =
le32_to_cpu(OCFS2_RAW_SB(di)->s_feature_compat);
osb->s_feature_ro_compat =
le32_to_cpu(OCFS2_RAW_SB(di)->s_feature_ro_compat);
osb->s_feature_incompat =
le32_to_cpu(OCFS2_RAW_SB(di)->s_feature_incompat);
if ((i = OCFS2_HAS_INCOMPAT_FEATURE(osb->sb, ~OCFS2_FEATURE_INCOMPAT_SUPP))) {
mlog(ML_ERROR, "couldn't mount because of unsupported "
"optional features (%x).\n", i);
status = -EINVAL;
goto bail;
}
if (!(osb->sb->s_flags & MS_RDONLY) &&
(i = OCFS2_HAS_RO_COMPAT_FEATURE(osb->sb, ~OCFS2_FEATURE_RO_COMPAT_SUPP))) {
mlog(ML_ERROR, "couldn't mount RDWR because of "
"unsupported optional features (%x).\n", i);
status = -EINVAL;
goto bail;
}
if (ocfs2_clusterinfo_valid(osb)) {
osb->osb_stackflags =
OCFS2_RAW_SB(di)->s_cluster_info.ci_stackflags;
strlcpy(osb->osb_cluster_stack,
OCFS2_RAW_SB(di)->s_cluster_info.ci_stack,
OCFS2_STACK_LABEL_LEN + 1);
if (strlen(osb->osb_cluster_stack) != OCFS2_STACK_LABEL_LEN) {
mlog(ML_ERROR,
"couldn't mount because of an invalid "
"cluster stack label (%s) \n",
osb->osb_cluster_stack);
status = -EINVAL;
goto bail;
}
strlcpy(osb->osb_cluster_name,
OCFS2_RAW_SB(di)->s_cluster_info.ci_cluster,
OCFS2_CLUSTER_NAME_LEN + 1);
} else {
/* The empty string is identical with classic tools that
* don't know about s_cluster_info. */
osb->osb_cluster_stack[0] = '\0';
}
get_random_bytes(&osb->s_next_generation, sizeof(u32));
/* FIXME
* This should be done in ocfs2_journal_init(), but unknown
* ordering issues will cause the filesystem to crash.
* If anyone wants to figure out what part of the code
* refers to osb->journal before ocfs2_journal_init() is run,
* be my guest.
*/
/* initialize our journal structure */
journal = kzalloc(sizeof(struct ocfs2_journal), GFP_KERNEL);
if (!journal) {
mlog(ML_ERROR, "unable to alloc journal\n");
status = -ENOMEM;
goto bail;
}
osb->journal = journal;
journal->j_osb = osb;
atomic_set(&journal->j_num_trans, 0);
init_rwsem(&journal->j_trans_barrier);
init_waitqueue_head(&journal->j_checkpointed);
spin_lock_init(&journal->j_lock);
journal->j_trans_id = (unsigned long) 1;
INIT_LIST_HEAD(&journal->j_la_cleanups);
INIT_WORK(&journal->j_recovery_work, ocfs2_complete_recovery);
journal->j_state = OCFS2_JOURNAL_FREE;
INIT_WORK(&osb->dquot_drop_work, ocfs2_drop_dquot_refs);
init_llist_head(&osb->dquot_drop_list);
/* get some pseudo constants for clustersize bits */
osb->s_clustersize_bits =
le32_to_cpu(di->id2.i_super.s_clustersize_bits);
osb->s_clustersize = 1 << osb->s_clustersize_bits;
if (osb->s_clustersize < OCFS2_MIN_CLUSTERSIZE ||
osb->s_clustersize > OCFS2_MAX_CLUSTERSIZE) {
mlog(ML_ERROR, "Volume has invalid cluster size (%d)\n",
osb->s_clustersize);
status = -EINVAL;
goto bail;
}
total_blocks = ocfs2_clusters_to_blocks(osb->sb,
le32_to_cpu(di->i_clusters));
status = generic_check_addressable(osb->sb->s_blocksize_bits,
total_blocks);
if (status) {
mlog(ML_ERROR, "Volume too large "
"to mount safely on this system");
status = -EFBIG;
goto bail;
}
if (ocfs2_setup_osb_uuid(osb, di->id2.i_super.s_uuid,
sizeof(di->id2.i_super.s_uuid))) {
mlog(ML_ERROR, "Out of memory trying to setup our uuid.\n");
status = -ENOMEM;
goto bail;
}
strlcpy(osb->vol_label, di->id2.i_super.s_label,
OCFS2_MAX_VOL_LABEL_LEN);
osb->root_blkno = le64_to_cpu(di->id2.i_super.s_root_blkno);
osb->system_dir_blkno = le64_to_cpu(di->id2.i_super.s_system_dir_blkno);
osb->first_cluster_group_blkno =
le64_to_cpu(di->id2.i_super.s_first_cluster_group);
osb->fs_generation = le32_to_cpu(di->i_fs_generation);
osb->uuid_hash = le32_to_cpu(di->id2.i_super.s_uuid_hash);
trace_ocfs2_initialize_super(osb->vol_label, osb->uuid_str,
(unsigned long long)osb->root_blkno,
(unsigned long long)osb->system_dir_blkno,
osb->s_clustersize_bits);
osb->osb_dlm_debug = ocfs2_new_dlm_debug();
if (!osb->osb_dlm_debug) {
status = -ENOMEM;
mlog_errno(status);
goto bail;
}
atomic_set(&osb->vol_state, VOLUME_INIT);
/* load root, system_dir, and all global system inodes */
status = ocfs2_init_global_system_inodes(osb);
if (status < 0) {
mlog_errno(status);
goto bail;
}
/*
* global bitmap
*/
inode = ocfs2_get_system_file_inode(osb, GLOBAL_BITMAP_SYSTEM_INODE,
OCFS2_INVALID_SLOT);
if (!inode) {
status = -EINVAL;
mlog_errno(status);
goto bail;
}
osb->bitmap_blkno = OCFS2_I(inode)->ip_blkno;
osb->osb_clusters_at_boot = OCFS2_I(inode)->ip_clusters;
iput(inode);
osb->bitmap_cpg = ocfs2_group_bitmap_size(sb, 0,
osb->s_feature_incompat) * 8;
status = ocfs2_init_slot_info(osb);
if (status < 0) {
mlog_errno(status);
goto bail;
}
cleancache_init_shared_fs(sb);
osb->ocfs2_wq = alloc_ordered_workqueue("ocfs2_wq", WQ_MEM_RECLAIM);
if (!osb->ocfs2_wq) {
status = -ENOMEM;
mlog_errno(status);
}
bail:
return status;
}
/*
* will return: -EAGAIN if it is ok to keep searching for superblocks
* -EINVAL if there is a bad superblock
* 0 on success
*/
static int ocfs2_verify_volume(struct ocfs2_dinode *di,
struct buffer_head *bh,
u32 blksz,
struct ocfs2_blockcheck_stats *stats)
{
int status = -EAGAIN;
if (memcmp(di->i_signature, OCFS2_SUPER_BLOCK_SIGNATURE,
strlen(OCFS2_SUPER_BLOCK_SIGNATURE)) == 0) {
/* We have to do a raw check of the feature here */
if (le32_to_cpu(di->id2.i_super.s_feature_incompat) &
OCFS2_FEATURE_INCOMPAT_META_ECC) {
status = ocfs2_block_check_validate(bh->b_data,
bh->b_size,
&di->i_check,
stats);
if (status)
goto out;
}
status = -EINVAL;
if ((1 << le32_to_cpu(di->id2.i_super.s_blocksize_bits)) != blksz) {
mlog(ML_ERROR, "found superblock with incorrect block "
"size: found %u, should be %u\n",
1 << le32_to_cpu(di->id2.i_super.s_blocksize_bits),
blksz);
} else if (le16_to_cpu(di->id2.i_super.s_major_rev_level) !=
OCFS2_MAJOR_REV_LEVEL ||
le16_to_cpu(di->id2.i_super.s_minor_rev_level) !=
OCFS2_MINOR_REV_LEVEL) {
mlog(ML_ERROR, "found superblock with bad version: "
"found %u.%u, should be %u.%u\n",
le16_to_cpu(di->id2.i_super.s_major_rev_level),
le16_to_cpu(di->id2.i_super.s_minor_rev_level),
OCFS2_MAJOR_REV_LEVEL,
OCFS2_MINOR_REV_LEVEL);
} else if (bh->b_blocknr != le64_to_cpu(di->i_blkno)) {
mlog(ML_ERROR, "bad block number on superblock: "
"found %llu, should be %llu\n",
(unsigned long long)le64_to_cpu(di->i_blkno),
(unsigned long long)bh->b_blocknr);
} else if (le32_to_cpu(di->id2.i_super.s_clustersize_bits) < 12 ||
le32_to_cpu(di->id2.i_super.s_clustersize_bits) > 20) {
mlog(ML_ERROR, "bad cluster size found: %u\n",
1 << le32_to_cpu(di->id2.i_super.s_clustersize_bits));
} else if (!le64_to_cpu(di->id2.i_super.s_root_blkno)) {
mlog(ML_ERROR, "bad root_blkno: 0\n");
} else if (!le64_to_cpu(di->id2.i_super.s_system_dir_blkno)) {
mlog(ML_ERROR, "bad system_dir_blkno: 0\n");
} else if (le16_to_cpu(di->id2.i_super.s_max_slots) > OCFS2_MAX_SLOTS) {
mlog(ML_ERROR,
"Superblock slots found greater than file system "
"maximum: found %u, max %u\n",
le16_to_cpu(di->id2.i_super.s_max_slots),
OCFS2_MAX_SLOTS);
} else {
/* found it! */
status = 0;
}
}
out:
if (status && status != -EAGAIN)
mlog_errno(status);
return status;
}
static int ocfs2_check_volume(struct ocfs2_super *osb)
{
int status;
int dirty;
int local;
struct ocfs2_dinode *local_alloc = NULL; /* only used if we
* recover
* ourselves. */
/* Init our journal object. */
status = ocfs2_journal_init(osb->journal, &dirty);
if (status < 0) {
mlog(ML_ERROR, "Could not initialize journal!\n");
goto finally;
}
/* Now that journal has been initialized, check to make sure
entire volume is addressable. */
status = ocfs2_journal_addressable(osb);
if (status)
goto finally;
/* If the journal was unmounted cleanly then we don't want to
* recover anything. Otherwise, journal_load will do that
* dirty work for us :) */
if (!dirty) {
status = ocfs2_journal_wipe(osb->journal, 0);
if (status < 0) {
mlog_errno(status);
goto finally;
}
} else {
printk(KERN_NOTICE "ocfs2: File system on device (%s) was not "
"unmounted cleanly, recovering it.\n", osb->dev_str);
}
local = ocfs2_mount_local(osb);
/* will play back anything left in the journal. */
status = ocfs2_journal_load(osb->journal, local, dirty);
if (status < 0) {
mlog(ML_ERROR, "ocfs2 journal load failed! %d\n", status);
goto finally;
}
if (osb->s_mount_opt & OCFS2_MOUNT_JOURNAL_ASYNC_COMMIT)
jbd2_journal_set_features(osb->journal->j_journal,
JBD2_FEATURE_COMPAT_CHECKSUM, 0,
JBD2_FEATURE_INCOMPAT_ASYNC_COMMIT);
else
jbd2_journal_clear_features(osb->journal->j_journal,
JBD2_FEATURE_COMPAT_CHECKSUM, 0,
JBD2_FEATURE_INCOMPAT_ASYNC_COMMIT);
if (dirty) {
/* recover my local alloc if we didn't unmount cleanly. */
status = ocfs2_begin_local_alloc_recovery(osb,
osb->slot_num,
&local_alloc);
if (status < 0) {
mlog_errno(status);
goto finally;
}
/* we complete the recovery process after we've marked
* ourselves as mounted. */
}
status = ocfs2_load_local_alloc(osb);
if (status < 0) {
mlog_errno(status);
goto finally;
}
if (dirty) {
/* Recovery will be completed after we've mounted the
* rest of the volume. */
osb->dirty = 1;
osb->local_alloc_copy = local_alloc;
local_alloc = NULL;
}
/* go through each journal, trylock it and if you get the
* lock, and it's marked as dirty, set the bit in the recover
* map and launch a recovery thread for it. */
status = ocfs2_mark_dead_nodes(osb);
if (status < 0) {
mlog_errno(status);
goto finally;
}
status = ocfs2_compute_replay_slots(osb);
if (status < 0)
mlog_errno(status);
finally:
kfree(local_alloc);
if (status)
mlog_errno(status);
return status;
}
/*
* The routine gets called from dismount or close whenever a dismount on
* volume is requested and the osb open count becomes 1.
* It will remove the osb from the global list and also free up all the
* initialized resources and fileobject.
*/
static void ocfs2_delete_osb(struct ocfs2_super *osb)
{
/* This function assumes that the caller has the main osb resource */
/* ocfs2_initializer_super have already created this workqueue */
if (osb->ocfs2_wq) {
flush_workqueue(osb->ocfs2_wq);
destroy_workqueue(osb->ocfs2_wq);
}
ocfs2_free_slot_info(osb);
kfree(osb->osb_orphan_wipes);
kfree(osb->slot_recovery_generations);
/* FIXME
* This belongs in journal shutdown, but because we have to
* allocate osb->journal at the start of ocfs2_initialize_osb(),
* we free it here.
*/
kfree(osb->journal);
kfree(osb->local_alloc_copy);
kfree(osb->uuid_str);
kfree(osb->vol_label);
ocfs2_put_dlm_debug(osb->osb_dlm_debug);
memset(osb, 0, sizeof(struct ocfs2_super));
}
/* Depending on the mount option passed, perform one of the following:
* Put OCFS2 into a readonly state (default)
* Return EIO so that only the process errs
* Fix the error as if fsck.ocfs2 -y
* panic
*/
static int ocfs2_handle_error(struct super_block *sb)
{
struct ocfs2_super *osb = OCFS2_SB(sb);
int rv = 0;
ocfs2_set_osb_flag(osb, OCFS2_OSB_ERROR_FS);
pr_crit("On-disk corruption discovered. "
"Please run fsck.ocfs2 once the filesystem is unmounted.\n");
if (osb->s_mount_opt & OCFS2_MOUNT_ERRORS_PANIC) {
panic("OCFS2: (device %s): panic forced after error\n",
sb->s_id);
} else if (osb->s_mount_opt & OCFS2_MOUNT_ERRORS_CONT) {
pr_crit("OCFS2: Returning error to the calling process.\n");
rv = -EIO;
} else { /* default option */
rv = -EROFS;
if (sb->s_flags & MS_RDONLY &&
(ocfs2_is_soft_readonly(osb) ||
ocfs2_is_hard_readonly(osb)))
return rv;
pr_crit("OCFS2: File system is now read-only.\n");
sb->s_flags |= MS_RDONLY;
ocfs2_set_ro_flag(osb, 0);
}
return rv;
}
int __ocfs2_error(struct super_block *sb, const char *function,
const char *fmt, ...)
{
struct va_format vaf;
va_list args;
va_start(args, fmt);
vaf.fmt = fmt;
vaf.va = &args;
/* Not using mlog here because we want to show the actual
* function the error came from. */
printk(KERN_CRIT "OCFS2: ERROR (device %s): %s: %pV",
sb->s_id, function, &vaf);
va_end(args);
return ocfs2_handle_error(sb);
}
/* Handle critical errors. This is intentionally more drastic than
* ocfs2_handle_error, so we only use for things like journal errors,
* etc. */
void __ocfs2_abort(struct super_block *sb, const char *function,
const char *fmt, ...)
{
struct va_format vaf;
va_list args;
va_start(args, fmt);
vaf.fmt = fmt;
vaf.va = &args;
printk(KERN_CRIT "OCFS2: abort (device %s): %s: %pV",
sb->s_id, function, &vaf);
va_end(args);
/* We don't have the cluster support yet to go straight to
* hard readonly in here. Until then, we want to keep
* ocfs2_abort() so that we can at least mark critical
* errors.
*
* TODO: This should abort the journal and alert other nodes
* that our slot needs recovery. */
/* Force a panic(). This stinks, but it's better than letting
* things continue without having a proper hard readonly
* here. */
if (!ocfs2_mount_local(OCFS2_SB(sb)))
OCFS2_SB(sb)->s_mount_opt |= OCFS2_MOUNT_ERRORS_PANIC;
ocfs2_handle_error(sb);
}
/*
* Void signal blockers, because in-kernel sigprocmask() only fails
* when SIG_* is wrong.
*/
void ocfs2_block_signals(sigset_t *oldset)
{
int rc;
sigset_t blocked;
sigfillset(&blocked);
rc = sigprocmask(SIG_BLOCK, &blocked, oldset);
BUG_ON(rc);
}
void ocfs2_unblock_signals(sigset_t *oldset)
{
int rc = sigprocmask(SIG_SETMASK, oldset, NULL);
BUG_ON(rc);
}
module_init(ocfs2_init);
module_exit(ocfs2_exit);
|
565041.c | #ifdef COMPILE_FOR_TEST
#include <assert.h>
#define assume(cond) assert(cond)
#endif
void main(int argc, char* argv[]) {
int x_0_0;//sh_buf.outcnt
int x_0_1;//sh_buf.outcnt
int x_0_2;//sh_buf.outcnt
int x_0_3;//sh_buf.outcnt
int x_0_4;//sh_buf.outcnt
int x_0_5;//sh_buf.outcnt
int x_1_0;//sh_buf.outbuf[0]
int x_1_1;//sh_buf.outbuf[0]
int x_2_0;//sh_buf.outbuf[1]
int x_2_1;//sh_buf.outbuf[1]
int x_3_0;//sh_buf.outbuf[2]
int x_3_1;//sh_buf.outbuf[2]
int x_4_0;//sh_buf.outbuf[3]
int x_4_1;//sh_buf.outbuf[3]
int x_5_0;//sh_buf.outbuf[4]
int x_5_1;//sh_buf.outbuf[4]
int x_6_0;//sh_buf.outbuf[5]
int x_7_0;//sh_buf.outbuf[6]
int x_8_0;//sh_buf.outbuf[7]
int x_9_0;//sh_buf.outbuf[8]
int x_10_0;//sh_buf.outbuf[9]
int x_11_0;//LOG_BUFSIZE
int x_11_1;//LOG_BUFSIZE
int x_12_0;//CREST_scheduler::lock_0
int x_13_0;//t3 T0
int x_14_0;//t2 T0
int x_15_0;//arg T0
int x_16_0;//functioncall::param T0
int x_16_1;//functioncall::param T0
int x_17_0;//buffered T0
int x_18_0;//functioncall::param T0
int x_18_1;//functioncall::param T0
int x_19_0;//functioncall::param T0
int x_19_1;//functioncall::param T0
int x_20_0;//functioncall::param T0
int x_20_1;//functioncall::param T0
int x_21_0;//functioncall::param T0
int x_21_1;//functioncall::param T0
int x_22_0;//direction T0
int x_23_0;//functioncall::param T0
int x_23_1;//functioncall::param T0
int x_24_0;//functioncall::param T0
int x_24_1;//functioncall::param T0
int x_25_0;//functioncall::param T0
int x_25_1;//functioncall::param T0
int x_26_0;//functioncall::param T0
int x_26_1;//functioncall::param T0
int x_27_0;//functioncall::param T0
int x_27_1;//functioncall::param T0
int x_28_0;//functioncall::param T0
int x_28_1;//functioncall::param T0
int x_29_0;//functioncall::param T0
int x_29_1;//functioncall::param T0
int x_30_0;//functioncall::param T0
int x_30_1;//functioncall::param T0
int x_31_0;//functioncall::param T0
int x_31_1;//functioncall::param T0
int x_32_0;//functioncall::param T0
int x_32_1;//functioncall::param T0
int x_33_0;//functioncall::param T0
int x_33_1;//functioncall::param T0
int x_34_0;//functioncall::param T0
int x_34_1;//functioncall::param T0
int x_35_0;//functioncall::param T1
int x_35_1;//functioncall::param T1
int x_36_0;//functioncall::param T1
int x_36_1;//functioncall::param T1
int x_37_0;//i T1
int x_37_1;//i T1
int x_37_2;//i T1
int x_38_0;//rv T1
int x_39_0;//functioncall::param T1
int x_39_1;//functioncall::param T1
int x_40_0;//functioncall::param T1
int x_40_1;//functioncall::param T1
int x_41_0;//functioncall::param T1
int x_41_1;//functioncall::param T1
int x_42_0;//functioncall::param T1
int x_42_1;//functioncall::param T1
int x_43_0;//functioncall::param T1
int x_43_1;//functioncall::param T1
int x_44_0;//functioncall::param T1
int x_44_1;//functioncall::param T1
int x_45_0;//functioncall::param T2
int x_45_1;//functioncall::param T2
int x_46_0;//functioncall::param T2
int x_46_1;//functioncall::param T2
int x_47_0;//i T2
int x_47_1;//i T2
int x_47_2;//i T2
int x_47_3;//i T2
int x_48_0;//rv T2
int x_49_0;//rv T2
int x_49_1;//rv T2
int x_50_0;//functioncall::param T2
int x_50_1;//functioncall::param T2
int x_51_0;//functioncall::param T2
int x_51_1;//functioncall::param T2
int x_52_0;//functioncall::param T2
int x_52_1;//functioncall::param T2
int x_53_0;//functioncall::param T2
int x_53_1;//functioncall::param T2
int x_54_0;//functioncall::param T2
int x_54_1;//functioncall::param T2
int x_55_0;//functioncall::param T2
int x_55_1;//functioncall::param T2
int x_55_2;//functioncall::param T2
int x_56_0;//functioncall::param T2
int x_56_1;//functioncall::param T2
T_0_0_0: x_0_0 = 0;
T_0_1_0: x_1_0 = 0;
T_0_2_0: x_2_0 = 0;
T_0_3_0: x_3_0 = 0;
T_0_4_0: x_4_0 = 0;
T_0_5_0: x_5_0 = 0;
T_0_6_0: x_6_0 = 0;
T_0_7_0: x_7_0 = 0;
T_0_8_0: x_8_0 = 0;
T_0_9_0: x_9_0 = 0;
T_0_10_0: x_10_0 = 0;
T_0_11_0: x_11_0 = 0;
T_0_12_0: x_13_0 = 3452944;
T_0_13_0: x_14_0 = 961876576;
T_0_14_0: x_15_0 = 0;
T_0_15_0: x_16_0 = 972752847;
T_0_16_0: x_16_1 = -1;
T_0_17_0: x_17_0 = 0;
T_0_18_0: x_18_0 = 1852646349;
T_0_19_0: x_18_1 = x_17_0;
T_0_20_0: x_19_0 = 1747015517;
T_0_21_0: x_19_1 = 97;
T_0_22_0: x_20_0 = 438110551;
T_0_23_0: x_20_1 = 0;
T_0_24_0: x_21_0 = 510323217;
T_0_25_0: x_21_1 = 0;
T_0_26_0: x_22_0 = 961871936;
T_0_27_0: x_23_0 = 309994871;
T_0_28_0: x_23_1 = x_22_0;
T_0_29_0: x_24_0 = 1200091615;
T_0_30_0: x_24_1 = 0;
T_0_31_0: x_12_0 = -1;
T_0_32_0: x_0_1 = 5;
T_0_33_0: x_1_1 = 72;
T_0_34_0: x_2_1 = 69;
T_0_35_0: x_3_1 = 76;
T_0_36_0: x_4_1 = 76;
T_0_37_0: x_5_1 = 79;
T_0_38_0: x_25_0 = 805113411;
T_0_39_0: x_25_1 = 83;
T_0_40_0: x_26_0 = 725319399;
T_0_41_0: x_26_1 = 1;
T_0_42_0: x_27_0 = 1303274725;
T_0_43_0: x_27_1 = 1;
T_0_44_0: x_28_0 = 1510840866;
T_0_45_0: x_28_1 = 1;
T_0_46_0: x_29_0 = 581359637;
T_0_47_0: x_29_1 = 82;
T_0_48_0: x_30_0 = 1381196683;
T_0_49_0: x_30_1 = 90;
T_0_50_0: x_31_0 = 1214423904;
T_0_51_0: x_31_1 = 1;
T_0_52_0: x_32_0 = 1133300161;
T_0_53_0: x_32_1 = 1;
T_0_54_0: x_33_0 = 259649672;
T_0_55_0: x_33_1 = 2;
T_0_56_0: x_34_0 = 2005545452;
T_0_57_0: x_34_1 = 2;
T_0_58_0: x_11_1 = 6;
T_2_59_2: x_45_0 = 1903936732;
T_2_60_2: x_45_1 = x_33_1;
T_2_61_2: x_46_0 = 192634151;
T_2_62_2: x_46_1 = x_34_1;
T_2_63_2: x_47_0 = 0;
T_2_64_2: x_48_0 = -1012534783;
T_1_65_1: x_35_0 = 2077578412;
T_1_66_1: x_35_1 = x_27_1;
T_1_67_1: x_36_0 = 1509899317;
T_1_68_1: x_36_1 = x_28_1;
T_1_69_1: x_37_0 = 0;
T_1_70_1: x_38_0 = -1010433535;
T_2_71_2: if (x_0_1 + x_46_1 > x_11_1 && x_0_1 != 0) x_49_0 = 968939440;
T_2_72_2: if (x_0_1 + x_46_1 > x_11_1 && x_0_1 != 0 && x_18_1 == 0 && x_18_1 == 0) x_50_0 = 1326381734;
T_2_73_2: if (x_0_1 + x_46_1 > x_11_1 && x_0_1 != 0 && x_18_1 == 0 && x_18_1 == 0) x_50_1 = -1;
T_2_74_2: if (x_0_1 + x_46_1 > x_11_1 && x_0_1 != 0 && x_18_1 == 0 && x_18_1 == 0) x_49_1 = x_50_1;
T_2_75_2: if (x_0_1 + x_46_1 > x_11_1 && x_0_1 != 0 && x_18_1 == 0 && x_49_1 + 1 == 0) x_0_2 = 0;
T_2_76_2: if (x_0_1 + x_46_1 > x_11_1 && x_0_1 != 0) x_51_0 = 132356914;
T_2_77_2: if (x_0_1 + x_46_1 > x_11_1 && x_0_1 != 0) x_51_1 = 9;
T_2_78_2: if (x_0_1 + x_46_1 > x_11_1 && x_0_1 != 0) x_52_0 = 867584313;
T_2_79_2: if (x_0_1 + x_46_1 > x_11_1 && x_0_1 != 0) x_52_1 = x_51_1;
T_2_80_2: if (x_0_1 + x_46_1 > x_11_1 && x_0_1 != 0) x_0_3 = 0;
T_2_81_2: if (x_46_1 < x_11_1) x_53_0 = 593560989;
T_2_82_2: if (x_46_1 < x_11_1) x_53_1 = 47511940765440;
T_1_83_1: if (x_36_1 < x_11_1) x_39_0 = 1804834009;
T_1_84_1: if (x_36_1 < x_11_1) x_39_1 = 47511938664192;
T_1_85_1: if (x_46_1 < x_11_1) x_54_0 = 1115647937;
T_1_86_1: if (x_46_1 < x_11_1) x_54_1 = x_0_3 + x_46_1;
T_2_87_2: if (x_46_1 < x_11_1) x_47_1 = 0;
T_2_88_2: if (x_46_1 < x_11_1 && x_47_1 < x_45_1) x_55_0 = 647268924;
T_2_89_2: if (x_46_1 < x_11_1 && x_47_1 < x_45_1) x_55_1 = 47511940765440;
T_2_90_2: if (x_46_1 < x_11_1) x_47_2 = 1 + x_47_1;
T_2_91_2: if (x_46_1 < x_11_1 && x_47_2 < x_45_1) x_55_2 = 47511940765440;
T_2_92_2: if (x_46_1 < x_11_1) x_47_3 = 1 + x_47_2;
T_2_93_2: if (x_46_1 < x_11_1) x_56_0 = 1815606619;
T_2_94_2: if (x_46_1 < x_11_1) x_56_1 = 47511940765440;
T_2_95_2: if (x_36_1 < x_11_1) x_40_0 = 1284831424;
T_2_96_2: if (x_36_1 < x_11_1) x_40_1 = x_0_3 + x_36_1;
T_1_97_1: if (x_36_1 < x_11_1) x_37_1 = 0;
T_1_98_1: if (x_36_1 < x_11_1 && x_37_1 < x_35_1) x_41_0 = 975853959;
T_1_99_1: if (x_36_1 < x_11_1 && x_37_1 < x_35_1) x_41_1 = 47511938664192;
T_1_100_1: if (x_36_1 < x_11_1) x_37_2 = 1 + x_37_1;
T_1_101_1: if (x_36_1 < x_11_1) x_42_0 = 640875818;
T_1_102_1: if (x_36_1 < x_11_1) x_42_1 = 47511938664192;
T_1_103_1: if (x_36_1 < x_11_1) x_0_4 = x_0_3 + x_36_1;
T_1_104_1: if (x_36_1 < x_11_1) x_43_0 = 989994126;
T_1_105_1: if (x_36_1 < x_11_1) x_43_1 = 47511938664192;
T_1_106_1: if (x_46_1 < x_11_1) x_0_5 = x_0_3 + x_46_1;
T_1_107_1: if (x_36_1 < x_11_1) x_44_0 = 575385829;
T_2_108_2: if (x_36_1 < x_11_1) x_44_1 = 47511938664192;
T_1_109_1: if (x_36_1 < x_11_1) assert(x_0_5 == x_40_1);
}
|
12031.c | /*
+----------------------------------------------------------------------+
| PHP Version 5 |
+----------------------------------------------------------------------+
| Copyright (c) 2006-2013 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 |
| [email protected] so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Authors: Georg Richter <[email protected]> |
| Andrey Hristov <[email protected]> |
| Ulf Wendel <[email protected]> |
+----------------------------------------------------------------------+
*/
/* $Id$ */
#include "php.h"
#include "mysqlnd.h"
#include "mysqlnd_wireprotocol.h"
#include "mysqlnd_priv.h"
#include "mysqlnd_debug.h"
#define MYSQLND_SILENT
enum mysqlnd_timestamp_type
{
MYSQLND_TIMESTAMP_NONE= -2,
MYSQLND_TIMESTAMP_ERROR= -1,
MYSQLND_TIMESTAMP_DATE= 0,
MYSQLND_TIMESTAMP_DATETIME= 1,
MYSQLND_TIMESTAMP_TIME= 2
};
struct st_mysqlnd_time
{
unsigned int year, month, day, hour, minute, second;
unsigned long second_part;
zend_bool neg;
enum mysqlnd_timestamp_type time_type;
};
struct st_mysqlnd_perm_bind mysqlnd_ps_fetch_functions[MYSQL_TYPE_LAST + 1];
#define MYSQLND_PS_SKIP_RESULT_W_LEN -1
#define MYSQLND_PS_SKIP_RESULT_STR -2
/* {{{ ps_fetch_from_1_to_8_bytes */
void ps_fetch_from_1_to_8_bytes(zval *zv, const MYSQLND_FIELD * const field,
unsigned int pack_len, zend_uchar **row, zend_bool as_unicode,
unsigned int byte_count TSRMLS_DC)
{
char tmp[22];
size_t tmp_len = 0;
zend_bool is_bit = field->type == MYSQL_TYPE_BIT;
DBG_ENTER("ps_fetch_from_1_to_8_bytes");
DBG_INF_FMT("zv=%p byte_count=%u", zv, byte_count);
if (field->flags & UNSIGNED_FLAG) {
uint64_t uval = 0;
switch (byte_count) {
case 8:uval = is_bit? (uint64_t) bit_uint8korr(*row):(uint64_t) uint8korr(*row);break;
case 7:uval = bit_uint7korr(*row);break;
case 6:uval = bit_uint6korr(*row);break;
case 5:uval = bit_uint5korr(*row);break;
case 4:uval = is_bit? (uint64_t) bit_uint4korr(*row):(uint64_t) uint4korr(*row);break;
case 3:uval = is_bit? (uint64_t) bit_uint3korr(*row):(uint64_t) uint3korr(*row);break;
case 2:uval = is_bit? (uint64_t) bit_uint2korr(*row):(uint64_t) uint2korr(*row);break;
case 1:uval = (uint64_t) uint1korr(*row);break;
}
#if SIZEOF_LONG==4
if (uval > INT_MAX) {
DBG_INF("stringify");
tmp_len = sprintf((char *)&tmp, MYSQLND_LLU_SPEC, uval);
} else
#endif /* #if SIZEOF_LONG==4 */
{
if (byte_count < 8 || uval <= L64(9223372036854775807)) {
ZVAL_LONG(zv, (long) uval); /* the cast is safe, we are in the range */
} else {
DBG_INF("stringify");
tmp_len = sprintf((char *)&tmp, MYSQLND_LLU_SPEC, uval);
}
}
} else {
/* SIGNED */
int64_t lval = 0;
switch (byte_count) {
case 8:lval = (int64_t) sint8korr(*row);break;
/*
7, 6 and 5 are not possible.
BIT is only unsigned, thus only uint5|6|7 macroses exist
*/
case 4:lval = (int64_t) sint4korr(*row);break;
case 3:lval = (int64_t) sint3korr(*row);break;
case 2:lval = (int64_t) sint2korr(*row);break;
case 1:lval = (int64_t) *(int8_t*)*row;break;
}
#if SIZEOF_LONG==4
if ((L64(2147483647) < (int64_t) lval) || (L64(-2147483648) > (int64_t) lval)) {
DBG_INF("stringify");
tmp_len = sprintf((char *)&tmp, MYSQLND_LL_SPEC, lval);
} else
#endif /* SIZEOF */
{
ZVAL_LONG(zv, (long) lval); /* the cast is safe, we are in the range */
}
}
if (tmp_len) {
#if MYSQLND_UNICODE
if (as_unicode) {
DBG_INF("stringify");
ZVAL_UTF8_STRINGL(zv, tmp, tmp_len, ZSTR_DUPLICATE);
} else
#endif
{
DBG_INF("stringify");
ZVAL_STRINGL(zv, tmp, tmp_len, 1);
}
}
(*row)+= byte_count;
DBG_VOID_RETURN;
}
/* }}} */
/* {{{ ps_fetch_null */
static
void ps_fetch_null(zval *zv, const MYSQLND_FIELD * const field,
unsigned int pack_len, zend_uchar **row,
zend_bool as_unicode TSRMLS_DC)
{
ZVAL_NULL(zv);
}
/* }}} */
/* {{{ ps_fetch_int8 */
static
void ps_fetch_int8(zval *zv, const MYSQLND_FIELD * const field,
unsigned int pack_len, zend_uchar **row,
zend_bool as_unicode TSRMLS_DC)
{
ps_fetch_from_1_to_8_bytes(zv, field, pack_len, row, as_unicode, 1 TSRMLS_CC);
}
/* }}} */
/* {{{ ps_fetch_int16 */
static
void ps_fetch_int16(zval *zv, const MYSQLND_FIELD * const field,
unsigned int pack_len, zend_uchar **row,
zend_bool as_unicode TSRMLS_DC)
{
ps_fetch_from_1_to_8_bytes(zv, field, pack_len, row, as_unicode, 2 TSRMLS_CC);
}
/* }}} */
/* {{{ ps_fetch_int32 */
static
void ps_fetch_int32(zval *zv, const MYSQLND_FIELD * const field,
unsigned int pack_len, zend_uchar **row,
zend_bool as_unicode TSRMLS_DC)
{
ps_fetch_from_1_to_8_bytes(zv, field, pack_len, row, as_unicode, 4 TSRMLS_CC);
}
/* }}} */
/* {{{ ps_fetch_int64 */
static
void ps_fetch_int64(zval *zv, const MYSQLND_FIELD * const field,
unsigned int pack_len, zend_uchar **row,
zend_bool as_unicode TSRMLS_DC)
{
ps_fetch_from_1_to_8_bytes(zv, field, pack_len, row, as_unicode, 8 TSRMLS_CC);
}
/* }}} */
/* {{{ ps_fetch_float */
static
void ps_fetch_float(zval *zv, const MYSQLND_FIELD * const field,
unsigned int pack_len, zend_uchar **row,
zend_bool as_unicode TSRMLS_DC)
{
float value;
DBG_ENTER("ps_fetch_float");
float4get(value, *row);
ZVAL_DOUBLE(zv, value);
(*row)+= 4;
DBG_INF_FMT("value=%f", value);
DBG_VOID_RETURN;
}
/* }}} */
/* {{{ ps_fetch_double */
static
void ps_fetch_double(zval *zv, const MYSQLND_FIELD * const field,
unsigned int pack_len, zend_uchar **row,
zend_bool as_unicode TSRMLS_DC)
{
double value;
DBG_ENTER("ps_fetch_double");
float8get(value, *row);
ZVAL_DOUBLE(zv, value);
(*row)+= 8;
DBG_INF_FMT("value=%f", value);
DBG_VOID_RETURN;
}
/* }}} */
/* {{{ ps_fetch_time */
static
void ps_fetch_time(zval *zv, const MYSQLND_FIELD * const field,
unsigned int pack_len, zend_uchar **row,
zend_bool as_unicode TSRMLS_DC)
{
struct st_mysqlnd_time t;
unsigned int length; /* First byte encodes the length*/
char * value;
DBG_ENTER("ps_fetch_time");
if ((length = php_mysqlnd_net_field_length(row))) {
zend_uchar *to= *row;
t.time_type = MYSQLND_TIMESTAMP_TIME;
t.neg = (zend_bool) to[0];
t.day = (unsigned long) sint4korr(to+1);
t.hour = (unsigned int) to[5];
t.minute = (unsigned int) to[6];
t.second = (unsigned int) to[7];
t.second_part = (length > 8) ? (unsigned long) sint4korr(to+8) : 0;
t.year = t.month= 0;
if (t.day) {
/* Convert days to hours at once */
t.hour += t.day*24;
t.day = 0;
}
(*row) += length;
} else {
memset(&t, 0, sizeof(t));
t.time_type = MYSQLND_TIMESTAMP_TIME;
}
/*
QQ : How to make this unicode without copying two times the buffer -
Unicode equivalent of spprintf?
*/
length = spprintf(&value, 0, "%s%02u:%02u:%02u", (t.neg ? "-" : ""), t.hour, t.minute, t.second);
DBG_INF_FMT("%s", value);
#if MYSQLND_UNICODE
if (!as_unicode) {
#endif
ZVAL_STRINGL(zv, value, length, 1);
efree(value); /* allocated by spprintf */
#if MYSQLND_UNICODE
} else {
ZVAL_UTF8_STRINGL(zv, value, length, ZSTR_AUTOFREE);
}
#endif
DBG_VOID_RETURN;
}
/* }}} */
/* {{{ ps_fetch_date */
static
void ps_fetch_date(zval *zv, const MYSQLND_FIELD * const field,
unsigned int pack_len, zend_uchar **row,
zend_bool as_unicode TSRMLS_DC)
{
struct st_mysqlnd_time t = {0};
unsigned int length; /* First byte encodes the length*/
char * value;
DBG_ENTER("ps_fetch_date");
if ((length = php_mysqlnd_net_field_length(row))) {
zend_uchar *to= *row;
t.time_type= MYSQLND_TIMESTAMP_DATE;
t.neg= 0;
t.second_part = t.hour = t.minute = t.second = 0;
t.year = (unsigned int) sint2korr(to);
t.month = (unsigned int) to[2];
t.day = (unsigned int) to[3];
(*row)+= length;
} else {
memset(&t, 0, sizeof(t));
t.time_type = MYSQLND_TIMESTAMP_DATE;
}
/*
QQ : How to make this unicode without copying two times the buffer -
Unicode equivalent of spprintf?
*/
length = spprintf(&value, 0, "%04u-%02u-%02u", t.year, t.month, t.day);
DBG_INF_FMT("%s", value);
#if MYSQLND_UNICODE
if (!as_unicode) {
#endif
ZVAL_STRINGL(zv, value, length, 1);
efree(value); /* allocated by spprintf */
#if MYSQLND_UNICODE
} else {
ZVAL_UTF8_STRINGL(zv, value, length, ZSTR_AUTOFREE);
}
#endif
DBG_VOID_RETURN;
}
/* }}} */
/* {{{ ps_fetch_datetime */
static
void ps_fetch_datetime(zval *zv, const MYSQLND_FIELD * const field,
unsigned int pack_len, zend_uchar **row,
zend_bool as_unicode TSRMLS_DC)
{
struct st_mysqlnd_time t;
unsigned int length; /* First byte encodes the length*/
char * value;
DBG_ENTER("ps_fetch_datetime");
if ((length = php_mysqlnd_net_field_length(row))) {
zend_uchar *to= *row;
t.time_type = MYSQLND_TIMESTAMP_DATETIME;
t.neg = 0;
t.year = (unsigned int) sint2korr(to);
t.month = (unsigned int) to[2];
t.day = (unsigned int) to[3];
if (length > 4) {
t.hour = (unsigned int) to[4];
t.minute = (unsigned int) to[5];
t.second = (unsigned int) to[6];
} else {
t.hour = t.minute = t.second= 0;
}
t.second_part = (length > 7) ? (unsigned long) sint4korr(to+7) : 0;
(*row)+= length;
} else {
memset(&t, 0, sizeof(t));
t.time_type = MYSQLND_TIMESTAMP_DATETIME;
}
/*
QQ : How to make this unicode without copying two times the buffer -
Unicode equivalent of spprintf?
*/
length = spprintf(&value, 0, "%04u-%02u-%02u %02u:%02u:%02u",
t.year, t.month, t.day, t.hour, t.minute, t.second);
DBG_INF_FMT("%s", value);
#if MYSQLND_UNICODE
if (!as_unicode) {
#endif
ZVAL_STRINGL(zv, value, length, 1);
efree(value); /* allocated by spprintf */
#if MYSQLND_UNICODE
} else {
ZVAL_UTF8_STRINGL(zv, to, length, ZSTR_AUTOFREE);
}
#endif
DBG_VOID_RETURN;
}
/* }}} */
/* {{{ ps_fetch_string */
static
void ps_fetch_string(zval *zv, const MYSQLND_FIELD * const field,
unsigned int pack_len, zend_uchar **row,
zend_bool as_unicode TSRMLS_DC)
{
/*
For now just copy, before we make it possible
to write \0 to the row buffer
*/
unsigned long length = php_mysqlnd_net_field_length(row);
DBG_ENTER("ps_fetch_string");
DBG_INF_FMT("len = %lu", length);
#if MYSQLND_UNICODE
if (field->charsetnr == MYSQLND_BINARY_CHARSET_NR) {
DBG_INF("Binary charset");
ZVAL_STRINGL(zv, (char *)*row, length, 1);
} else {
DBG_INF_FMT("copying from the row buffer");
ZVAL_UTF8_STRINGL(zv, (char*)*row, length, ZSTR_DUPLICATE);
}
#else
DBG_INF("copying from the row buffer");
ZVAL_STRINGL(zv, (char *)*row, length, 1);
#endif
(*row) += length;
DBG_VOID_RETURN;
}
/* }}} */
/* {{{ ps_fetch_bit */
static
void ps_fetch_bit(zval *zv, const MYSQLND_FIELD * const field,
unsigned int pack_len, zend_uchar **row,
zend_bool as_unicode TSRMLS_DC)
{
unsigned long length= php_mysqlnd_net_field_length(row);
ps_fetch_from_1_to_8_bytes(zv, field, pack_len, row, as_unicode, length TSRMLS_CC);
}
/* }}} */
/* {{{ _mysqlnd_init_ps_fetch_subsystem */
void _mysqlnd_init_ps_fetch_subsystem()
{
memset(mysqlnd_ps_fetch_functions, 0, sizeof(mysqlnd_ps_fetch_functions));
mysqlnd_ps_fetch_functions[MYSQL_TYPE_NULL].func = ps_fetch_null;
mysqlnd_ps_fetch_functions[MYSQL_TYPE_NULL].pack_len = 0;
mysqlnd_ps_fetch_functions[MYSQL_TYPE_NULL].php_type = IS_NULL;
mysqlnd_ps_fetch_functions[MYSQL_TYPE_NULL].can_ret_as_str_in_uni = TRUE;
mysqlnd_ps_fetch_functions[MYSQL_TYPE_TINY].func = ps_fetch_int8;
mysqlnd_ps_fetch_functions[MYSQL_TYPE_TINY].pack_len = 1;
mysqlnd_ps_fetch_functions[MYSQL_TYPE_TINY].php_type = IS_LONG;
mysqlnd_ps_fetch_functions[MYSQL_TYPE_TINY].can_ret_as_str_in_uni = TRUE;
mysqlnd_ps_fetch_functions[MYSQL_TYPE_SHORT].func = ps_fetch_int16;
mysqlnd_ps_fetch_functions[MYSQL_TYPE_SHORT].pack_len = 2;
mysqlnd_ps_fetch_functions[MYSQL_TYPE_SHORT].php_type = IS_LONG;
mysqlnd_ps_fetch_functions[MYSQL_TYPE_SHORT].can_ret_as_str_in_uni = TRUE;
mysqlnd_ps_fetch_functions[MYSQL_TYPE_YEAR].func = ps_fetch_int16;
mysqlnd_ps_fetch_functions[MYSQL_TYPE_YEAR].pack_len = 2;
mysqlnd_ps_fetch_functions[MYSQL_TYPE_YEAR].php_type = IS_LONG;
mysqlnd_ps_fetch_functions[MYSQL_TYPE_YEAR].can_ret_as_str_in_uni = TRUE;
mysqlnd_ps_fetch_functions[MYSQL_TYPE_INT24].func = ps_fetch_int32;
mysqlnd_ps_fetch_functions[MYSQL_TYPE_INT24].pack_len = 4;
mysqlnd_ps_fetch_functions[MYSQL_TYPE_INT24].php_type = IS_LONG;
mysqlnd_ps_fetch_functions[MYSQL_TYPE_INT24].can_ret_as_str_in_uni = TRUE;
mysqlnd_ps_fetch_functions[MYSQL_TYPE_LONG].func = ps_fetch_int32;
mysqlnd_ps_fetch_functions[MYSQL_TYPE_LONG].pack_len = 4;
mysqlnd_ps_fetch_functions[MYSQL_TYPE_LONG].php_type = IS_LONG;
mysqlnd_ps_fetch_functions[MYSQL_TYPE_LONG].can_ret_as_str_in_uni = TRUE;
mysqlnd_ps_fetch_functions[MYSQL_TYPE_LONGLONG].func = ps_fetch_int64;
mysqlnd_ps_fetch_functions[MYSQL_TYPE_LONGLONG].pack_len= 8;
mysqlnd_ps_fetch_functions[MYSQL_TYPE_LONGLONG].php_type= IS_LONG;
mysqlnd_ps_fetch_functions[MYSQL_TYPE_LONGLONG].can_ret_as_str_in_uni = TRUE;
mysqlnd_ps_fetch_functions[MYSQL_TYPE_FLOAT].func = ps_fetch_float;
mysqlnd_ps_fetch_functions[MYSQL_TYPE_FLOAT].pack_len = 4;
mysqlnd_ps_fetch_functions[MYSQL_TYPE_FLOAT].php_type = IS_DOUBLE;
mysqlnd_ps_fetch_functions[MYSQL_TYPE_FLOAT].can_ret_as_str_in_uni = TRUE;
mysqlnd_ps_fetch_functions[MYSQL_TYPE_DOUBLE].func = ps_fetch_double;
mysqlnd_ps_fetch_functions[MYSQL_TYPE_DOUBLE].pack_len = 8;
mysqlnd_ps_fetch_functions[MYSQL_TYPE_DOUBLE].php_type = IS_DOUBLE;
mysqlnd_ps_fetch_functions[MYSQL_TYPE_DOUBLE].can_ret_as_str_in_uni = TRUE;
mysqlnd_ps_fetch_functions[MYSQL_TYPE_TIME].func = ps_fetch_time;
mysqlnd_ps_fetch_functions[MYSQL_TYPE_TIME].pack_len = MYSQLND_PS_SKIP_RESULT_W_LEN;
mysqlnd_ps_fetch_functions[MYSQL_TYPE_TIME].php_type = IS_STRING;
mysqlnd_ps_fetch_functions[MYSQL_TYPE_TIME].can_ret_as_str_in_uni = TRUE;
mysqlnd_ps_fetch_functions[MYSQL_TYPE_DATE].func = ps_fetch_date;
mysqlnd_ps_fetch_functions[MYSQL_TYPE_DATE].pack_len = MYSQLND_PS_SKIP_RESULT_W_LEN;
mysqlnd_ps_fetch_functions[MYSQL_TYPE_DATE].php_type = IS_STRING;
mysqlnd_ps_fetch_functions[MYSQL_TYPE_DATE].can_ret_as_str_in_uni = TRUE;
mysqlnd_ps_fetch_functions[MYSQL_TYPE_NEWDATE].func = ps_fetch_string;
mysqlnd_ps_fetch_functions[MYSQL_TYPE_NEWDATE].pack_len = MYSQLND_PS_SKIP_RESULT_W_LEN;
mysqlnd_ps_fetch_functions[MYSQL_TYPE_NEWDATE].php_type = IS_STRING;
mysqlnd_ps_fetch_functions[MYSQL_TYPE_NEWDATE].can_ret_as_str_in_uni = TRUE;
mysqlnd_ps_fetch_functions[MYSQL_TYPE_DATETIME].func = ps_fetch_datetime;
mysqlnd_ps_fetch_functions[MYSQL_TYPE_DATETIME].pack_len= MYSQLND_PS_SKIP_RESULT_W_LEN;
mysqlnd_ps_fetch_functions[MYSQL_TYPE_DATETIME].php_type= IS_STRING;
mysqlnd_ps_fetch_functions[MYSQL_TYPE_DATETIME].can_ret_as_str_in_uni = TRUE;
mysqlnd_ps_fetch_functions[MYSQL_TYPE_TIMESTAMP].func = ps_fetch_datetime;
mysqlnd_ps_fetch_functions[MYSQL_TYPE_TIMESTAMP].pack_len= MYSQLND_PS_SKIP_RESULT_W_LEN;
mysqlnd_ps_fetch_functions[MYSQL_TYPE_TIMESTAMP].php_type= IS_STRING;
mysqlnd_ps_fetch_functions[MYSQL_TYPE_TIMESTAMP].can_ret_as_str_in_uni = TRUE;
mysqlnd_ps_fetch_functions[MYSQL_TYPE_TINY_BLOB].func = ps_fetch_string;
mysqlnd_ps_fetch_functions[MYSQL_TYPE_TINY_BLOB].pack_len= MYSQLND_PS_SKIP_RESULT_STR;
mysqlnd_ps_fetch_functions[MYSQL_TYPE_TINY_BLOB].php_type = IS_STRING;
mysqlnd_ps_fetch_functions[MYSQL_TYPE_TINY_BLOB].is_possibly_blob = TRUE;
mysqlnd_ps_fetch_functions[MYSQL_TYPE_TINY_BLOB].can_ret_as_str_in_uni = TRUE;
mysqlnd_ps_fetch_functions[MYSQL_TYPE_BLOB].func = ps_fetch_string;
mysqlnd_ps_fetch_functions[MYSQL_TYPE_BLOB].pack_len = MYSQLND_PS_SKIP_RESULT_STR;
mysqlnd_ps_fetch_functions[MYSQL_TYPE_BLOB].php_type = IS_STRING;
mysqlnd_ps_fetch_functions[MYSQL_TYPE_BLOB].is_possibly_blob = TRUE;
mysqlnd_ps_fetch_functions[MYSQL_TYPE_BLOB].can_ret_as_str_in_uni = TRUE;
mysqlnd_ps_fetch_functions[MYSQL_TYPE_MEDIUM_BLOB].func = ps_fetch_string;
mysqlnd_ps_fetch_functions[MYSQL_TYPE_MEDIUM_BLOB].pack_len = MYSQLND_PS_SKIP_RESULT_STR;
mysqlnd_ps_fetch_functions[MYSQL_TYPE_MEDIUM_BLOB].php_type = IS_STRING;
mysqlnd_ps_fetch_functions[MYSQL_TYPE_MEDIUM_BLOB].is_possibly_blob = TRUE;
mysqlnd_ps_fetch_functions[MYSQL_TYPE_MEDIUM_BLOB].can_ret_as_str_in_uni = TRUE;
mysqlnd_ps_fetch_functions[MYSQL_TYPE_LONG_BLOB].func = ps_fetch_string;
mysqlnd_ps_fetch_functions[MYSQL_TYPE_LONG_BLOB].pack_len = MYSQLND_PS_SKIP_RESULT_STR;
mysqlnd_ps_fetch_functions[MYSQL_TYPE_LONG_BLOB].php_type = IS_STRING;
mysqlnd_ps_fetch_functions[MYSQL_TYPE_LONG_BLOB].is_possibly_blob = TRUE;
mysqlnd_ps_fetch_functions[MYSQL_TYPE_LONG_BLOB].can_ret_as_str_in_uni = TRUE;
mysqlnd_ps_fetch_functions[MYSQL_TYPE_BIT].func = ps_fetch_bit;
mysqlnd_ps_fetch_functions[MYSQL_TYPE_BIT].pack_len = 8;
mysqlnd_ps_fetch_functions[MYSQL_TYPE_BIT].php_type = IS_LONG;
mysqlnd_ps_fetch_functions[MYSQL_TYPE_BIT].can_ret_as_str_in_uni = TRUE;
mysqlnd_ps_fetch_functions[MYSQL_TYPE_VAR_STRING].func = ps_fetch_string;
mysqlnd_ps_fetch_functions[MYSQL_TYPE_VAR_STRING].pack_len = MYSQLND_PS_SKIP_RESULT_STR;
mysqlnd_ps_fetch_functions[MYSQL_TYPE_VAR_STRING].php_type = IS_STRING;
mysqlnd_ps_fetch_functions[MYSQL_TYPE_VAR_STRING].is_possibly_blob = TRUE;
mysqlnd_ps_fetch_functions[MYSQL_TYPE_VARCHAR].func = ps_fetch_string;
mysqlnd_ps_fetch_functions[MYSQL_TYPE_VARCHAR].pack_len = MYSQLND_PS_SKIP_RESULT_STR;
mysqlnd_ps_fetch_functions[MYSQL_TYPE_VARCHAR].php_type = IS_STRING;
mysqlnd_ps_fetch_functions[MYSQL_TYPE_VARCHAR].is_possibly_blob = TRUE;
mysqlnd_ps_fetch_functions[MYSQL_TYPE_STRING].func = ps_fetch_string;
mysqlnd_ps_fetch_functions[MYSQL_TYPE_STRING].pack_len = MYSQLND_PS_SKIP_RESULT_STR;
mysqlnd_ps_fetch_functions[MYSQL_TYPE_STRING].php_type = IS_STRING;
mysqlnd_ps_fetch_functions[MYSQL_TYPE_STRING].is_possibly_blob = TRUE;
mysqlnd_ps_fetch_functions[MYSQL_TYPE_DECIMAL].func = ps_fetch_string;
mysqlnd_ps_fetch_functions[MYSQL_TYPE_DECIMAL].pack_len = MYSQLND_PS_SKIP_RESULT_STR;
mysqlnd_ps_fetch_functions[MYSQL_TYPE_DECIMAL].php_type = IS_STRING;
mysqlnd_ps_fetch_functions[MYSQL_TYPE_DECIMAL].can_ret_as_str_in_uni = TRUE;
mysqlnd_ps_fetch_functions[MYSQL_TYPE_NEWDECIMAL].func = ps_fetch_string;
mysqlnd_ps_fetch_functions[MYSQL_TYPE_NEWDECIMAL].pack_len = MYSQLND_PS_SKIP_RESULT_STR;
mysqlnd_ps_fetch_functions[MYSQL_TYPE_NEWDECIMAL].php_type = IS_STRING;
mysqlnd_ps_fetch_functions[MYSQL_TYPE_NEWDECIMAL].can_ret_as_str_in_uni = TRUE;
mysqlnd_ps_fetch_functions[MYSQL_TYPE_ENUM].func = ps_fetch_string;
mysqlnd_ps_fetch_functions[MYSQL_TYPE_ENUM].pack_len = MYSQLND_PS_SKIP_RESULT_STR;
mysqlnd_ps_fetch_functions[MYSQL_TYPE_ENUM].php_type = IS_STRING;
mysqlnd_ps_fetch_functions[MYSQL_TYPE_SET].func = ps_fetch_string;
mysqlnd_ps_fetch_functions[MYSQL_TYPE_SET].pack_len = MYSQLND_PS_SKIP_RESULT_STR;
mysqlnd_ps_fetch_functions[MYSQL_TYPE_SET].php_type = IS_STRING;
mysqlnd_ps_fetch_functions[MYSQL_TYPE_GEOMETRY].func = ps_fetch_string;
mysqlnd_ps_fetch_functions[MYSQL_TYPE_GEOMETRY].pack_len= MYSQLND_PS_SKIP_RESULT_STR;
mysqlnd_ps_fetch_functions[MYSQL_TYPE_GEOMETRY].php_type= IS_STRING;
}
/* }}} */
/* {{{ mysqlnd_stmt_copy_it */
static enum_func_status
mysqlnd_stmt_copy_it(zval *** copies, zval *original, unsigned int param_count, unsigned int current TSRMLS_DC)
{
if (!*copies) {
*copies = mnd_ecalloc(param_count, sizeof(zval *));
}
if (*copies) {
MAKE_STD_ZVAL((*copies)[current]);
*(*copies)[current] = *original;
Z_SET_REFCOUNT_P((*copies)[current], 1);
zval_copy_ctor((*copies)[current]);
return PASS;
}
return FAIL;
}
/* }}} */
/* {{{ mysqlnd_stmt_execute_store_params */
static enum_func_status
mysqlnd_stmt_execute_store_params(MYSQLND_STMT * s, zend_uchar **buf, zend_uchar **p, size_t *buf_len TSRMLS_DC)
{
MYSQLND_STMT_DATA * stmt = s->data;
unsigned int i = 0;
zend_uchar * provided_buffer = *buf;
size_t left = (*buf_len - (*p - *buf));
size_t data_size = 0;
zval **copies = NULL;/* if there are different types */
enum_func_status ret = FAIL;
int resend_types_next_time = 0;
size_t null_byte_offset;
DBG_ENTER("mysqlnd_stmt_execute_store_params");
{
unsigned int null_count = (stmt->param_count + 7) / 8;
/* give it some reserved space - 20 bytes */
if (left < (null_count + 20)) {
unsigned int offset = *p - *buf;
zend_uchar *tmp_buf;
*buf_len = offset + null_count + 20;
tmp_buf = mnd_emalloc(*buf_len);
if (!tmp_buf) {
SET_OOM_ERROR(stmt->error_info);
goto end;
}
memcpy(tmp_buf, *buf, offset);
if (*buf != provided_buffer) {
mnd_efree(*buf);
}
*buf = tmp_buf;
/* Update our pos pointer */
*p = *buf + offset;
}
/* put `null` bytes */
null_byte_offset = *p - *buf;
memset(*p, 0, null_count);
*p += null_count;
}
/* 1. Store type information */
/*
check if need to send the types even if stmt->send_types_to_server is 0. This is because
if we send "i" (42) then the type will be int and the server will expect int. However, if next
time we try to send > LONG_MAX, the conversion to string will send a string and the server
won't expect it and interpret the value as 0. Thus we need to resend the types, if any such values
occur, and force resend for the next execution.
*/
for (i = 0; i < stmt->param_count; i++) {
if (Z_TYPE_P(stmt->param_bind[i].zv) != IS_NULL &&
(stmt->param_bind[i].type == MYSQL_TYPE_LONG || stmt->param_bind[i].type == MYSQL_TYPE_LONGLONG))
{
/* always copy the var, because we do many conversions */
if (Z_TYPE_P(stmt->param_bind[i].zv) != IS_LONG &&
PASS != mysqlnd_stmt_copy_it(&copies, stmt->param_bind[i].zv, stmt->param_count, i TSRMLS_CC))
{
SET_OOM_ERROR(stmt->error_info);
goto end;
}
/*
if it doesn't fit in a long send it as a string.
Check bug #52891 : Wrong data inserted with mysqli/mysqlnd when using bind_param, value > LONG_MAX
*/
if (Z_TYPE_P(stmt->param_bind[i].zv) != IS_LONG) {
zval *tmp_data = (copies && copies[i])? copies[i]: stmt->param_bind[i].zv;
convert_to_double_ex(&tmp_data);
if (Z_DVAL_P(tmp_data) > LONG_MAX || Z_DVAL_P(tmp_data) < LONG_MIN) {
stmt->send_types_to_server = resend_types_next_time = 1;
}
}
}
}
int1store(*p, stmt->send_types_to_server);
(*p)++;
if (stmt->send_types_to_server) {
/* 2 bytes per type, and leave 20 bytes for future use */
if (left < ((stmt->param_count * 2) + 20)) {
unsigned int offset = *p - *buf;
zend_uchar *tmp_buf;
*buf_len = offset + stmt->param_count * 2 + 20;
tmp_buf = mnd_emalloc(*buf_len);
if (!tmp_buf) {
SET_OOM_ERROR(stmt->error_info);
goto end;
}
memcpy(tmp_buf, *buf, offset);
if (*buf != provided_buffer) {
mnd_efree(*buf);
}
*buf = tmp_buf;
/* Update our pos pointer */
*p = *buf + offset;
}
for (i = 0; i < stmt->param_count; i++) {
short current_type = stmt->param_bind[i].type;
/* our types are not unsigned */
#if SIZEOF_LONG==8
if (current_type == MYSQL_TYPE_LONG) {
current_type = MYSQL_TYPE_LONGLONG;
}
#endif
if (Z_TYPE_P(stmt->param_bind[i].zv) != IS_NULL && (current_type == MYSQL_TYPE_LONG || current_type == MYSQL_TYPE_LONGLONG)) {
/*
if it doesn't fit in a long send it as a string.
Check bug #52891 : Wrong data inserted with mysqli/mysqlnd when using bind_param, value > LONG_MAX
*/
if (Z_TYPE_P(stmt->param_bind[i].zv) != IS_LONG) {
zval *tmp_data = (copies && copies[i])? copies[i]: stmt->param_bind[i].zv;
convert_to_double_ex(&tmp_data);
if (Z_DVAL_P(tmp_data) > LONG_MAX || Z_DVAL_P(tmp_data) < LONG_MIN) {
convert_to_string_ex(&tmp_data);
current_type = MYSQL_TYPE_VAR_STRING;
/*
don't change stmt->param_bind[i].type to MYSQL_TYPE_VAR_STRING
we force convert_to_long_ex in all cases, thus the type will be right in the next switch.
if the type is however not long, then we will do a goto in the next switch.
We want to preserve the original bind type given by the user. Thus, we do these hacks.
*/
} else {
convert_to_long_ex(&tmp_data);
}
}
}
int2store(*p, current_type);
*p+= 2;
}
}
stmt->send_types_to_server = resend_types_next_time;
/* 2. Store data */
/* 2.1 Calculate how much space we need */
for (i = 0; i < stmt->param_count; i++) {
unsigned int j;
zval *the_var = stmt->param_bind[i].zv;
if (!the_var || (stmt->param_bind[i].type != MYSQL_TYPE_LONG_BLOB && Z_TYPE_P(the_var) == IS_NULL)) {
continue;
}
for (j = i + 1; j < stmt->param_count; j++) {
if (stmt->param_bind[j].zv == the_var) {
/* Double binding of the same zval, make a copy */
if (!copies || !copies[i]) {
if (PASS != mysqlnd_stmt_copy_it(&copies, the_var, stmt->param_count, i TSRMLS_CC)) {
SET_OOM_ERROR(stmt->error_info);
goto end;
}
}
break;
}
}
switch (stmt->param_bind[i].type) {
case MYSQL_TYPE_DOUBLE:
data_size += 8;
if (Z_TYPE_P(the_var) != IS_DOUBLE) {
if (!copies || !copies[i]) {
if (PASS != mysqlnd_stmt_copy_it(&copies, the_var, stmt->param_count, i TSRMLS_CC)) {
SET_OOM_ERROR(stmt->error_info);
goto end;
}
}
}
break;
case MYSQL_TYPE_LONGLONG:
{
zval *tmp_data = (copies && copies[i])? copies[i]: stmt->param_bind[i].zv;
if (Z_TYPE_P(tmp_data) == IS_STRING) {
goto use_string;
}
convert_to_long_ex(&tmp_data);
}
data_size += 8;
break;
case MYSQL_TYPE_LONG:
{
zval *tmp_data = (copies && copies[i])? copies[i]: stmt->param_bind[i].zv;
if (Z_TYPE_P(tmp_data) == IS_STRING) {
goto use_string;
}
convert_to_long_ex(&tmp_data);
}
data_size += 4;
break;
case MYSQL_TYPE_LONG_BLOB:
if (!(stmt->param_bind[i].flags & MYSQLND_PARAM_BIND_BLOB_USED)) {
/*
User hasn't sent anything, we will send empty string.
Empty string has length of 0, encoded in 1 byte. No real
data will follows after it.
*/
data_size++;
}
break;
case MYSQL_TYPE_VAR_STRING:
use_string:
data_size += 8; /* max 8 bytes for size */
#if MYSQLND_UNICODE
if (Z_TYPE_P(the_var) != IS_STRING || Z_TYPE_P(the_var) == IS_UNICODE)
#else
if (Z_TYPE_P(the_var) != IS_STRING)
#endif
{
if (!copies || !copies[i]) {
if (PASS != mysqlnd_stmt_copy_it(&copies, the_var, stmt->param_count, i TSRMLS_CC)) {
SET_OOM_ERROR(stmt->error_info);
goto end;
}
}
the_var = copies[i];
#if MYSQLND_UNICODE
if (Z_TYPE_P(the_var) == IS_UNICODE) {
zval_unicode_to_string_ex(the_var, UG(utf8_conv) TSRMLS_CC);
}
#endif
}
convert_to_string_ex(&the_var);
data_size += Z_STRLEN_P(the_var);
break;
}
}
/* 2.2 Enlarge the buffer, if needed */
left = (*buf_len - (*p - *buf));
if (left < data_size) {
unsigned int offset = *p - *buf;
zend_uchar *tmp_buf;
*buf_len = offset + data_size + 10; /* Allocate + 10 for safety */
tmp_buf = mnd_emalloc(*buf_len);
if (!tmp_buf) {
SET_OOM_ERROR(stmt->error_info);
goto end;
}
memcpy(tmp_buf, *buf, offset);
/*
When too many columns the buffer provided to the function might not be sufficient.
In this case new buffer has been allocated above. When we allocate a buffer and then
allocate a bigger one here, we should free the first one.
*/
if (*buf != provided_buffer) {
mnd_efree(*buf);
}
*buf = tmp_buf;
/* Update our pos pointer */
*p = *buf + offset;
}
/* 2.3 Store the actual data */
for (i = 0; i < stmt->param_count; i++) {
zval *data = (copies && copies[i])? copies[i]: stmt->param_bind[i].zv;
/* Handle long data */
if (stmt->param_bind[i].zv && Z_TYPE_P(data) == IS_NULL) {
(*buf + null_byte_offset)[i/8] |= (zend_uchar) (1 << (i & 7));
} else {
switch (stmt->param_bind[i].type) {
case MYSQL_TYPE_DOUBLE:
convert_to_double_ex(&data);
float8store(*p, Z_DVAL_P(data));
(*p) += 8;
break;
case MYSQL_TYPE_LONGLONG:
if (Z_TYPE_P(data) == IS_STRING) {
goto send_string;
}
/* data has alreade been converted to long */
int8store(*p, Z_LVAL_P(data));
(*p) += 8;
break;
case MYSQL_TYPE_LONG:
if (Z_TYPE_P(data) == IS_STRING) {
goto send_string;
}
/* data has alreade been converted to long */
int4store(*p, Z_LVAL_P(data));
(*p) += 4;
break;
case MYSQL_TYPE_LONG_BLOB:
if (stmt->param_bind[i].flags & MYSQLND_PARAM_BIND_BLOB_USED) {
stmt->param_bind[i].flags &= ~MYSQLND_PARAM_BIND_BLOB_USED;
} else {
/* send_long_data() not called, send empty string */
*p = php_mysqlnd_net_store_length(*p, 0);
}
break;
case MYSQL_TYPE_VAR_STRING:
send_string:
{
unsigned int len = Z_STRLEN_P(data);
/* to is after p. The latter hasn't been moved */
*p = php_mysqlnd_net_store_length(*p, len);
memcpy(*p, Z_STRVAL_P(data), len);
(*p) += len;
}
break;
default:
/* Won't happen, but set to NULL */
(*buf + null_byte_offset)[i/8] |= (zend_uchar) (1 << (i & 7));
break;
}
}
}
ret = PASS;
end:
if (copies) {
for (i = 0; i < stmt->param_count; i++) {
if (copies[i]) {
zval_ptr_dtor(&copies[i]);
}
}
mnd_efree(copies);
}
DBG_INF_FMT("ret=%s", ret == PASS? "PASS":"FAIL");
DBG_RETURN(ret);
}
/* }}} */
/* {{{ mysqlnd_stmt_execute_generate_request */
enum_func_status
mysqlnd_stmt_execute_generate_request(MYSQLND_STMT * const s, zend_uchar ** request, size_t *request_len, zend_bool * free_buffer TSRMLS_DC)
{
MYSQLND_STMT_DATA * stmt = s->data;
zend_uchar *p = stmt->execute_cmd_buffer.buffer,
*cmd_buffer = stmt->execute_cmd_buffer.buffer;
size_t cmd_buffer_length = stmt->execute_cmd_buffer.length;
enum_func_status ret;
DBG_ENTER("mysqlnd_stmt_execute_generate_request");
int4store(p, stmt->stmt_id);
p += 4;
/* flags is 4 bytes, we store just 1 */
int1store(p, (zend_uchar) stmt->flags);
p++;
/* Make it all zero */
int4store(p, 0);
int1store(p, 1); /* and send 1 for iteration count */
p+= 4;
ret = mysqlnd_stmt_execute_store_params(s, &cmd_buffer, &p, &cmd_buffer_length TSRMLS_CC);
*free_buffer = (cmd_buffer != stmt->execute_cmd_buffer.buffer);
*request_len = (p - cmd_buffer);
*request = cmd_buffer;
DBG_INF_FMT("ret=%s", ret == PASS? "PASS":"FAIL");
DBG_RETURN(ret);
}
/* }}} */
/*
* 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
*/
|
725213.c | /*
* File: packet.c
* Author: Erik Gresak
* Email: [email protected]
* Created on August 23, 2017, 7:26 AM
*/
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#include <math.h>
#include "packet.h"
// Sector Constant
// decoding MType description & direction
#define MTYPE_JOIN_REQUEST 0
#define MTYPE_JOIN_ACCEPT 1
#define MTYPE_UNCONFIRMED_DATA_UP 2
#define MTYPE_UNCONFIRMED_DATA_DOWN 3
#define MTYPE_CONFIRMED_DATA_UP 4
#define MTYPE_CONFIRMED_DATA_DOWN 5
// endSector
char *slice(char *arr, size_t start, size_t size) {
if (arr == NULL)
return NULL;
char *_arr = (char*) malloc(size + 1);
for (int i = start; i < size + start; i++) {
_arr[i - start] = arr[i];
}
_arr[size] = '\0';
return _arr;
}
char *reversArray(char *arr) {
if (arr == NULL)
return NULL;
int end = strlen(arr);
int len = strlen(arr);
char *_array = (char*) malloc(len + 1);
for (int i = 0; i < len; i++) {
--end;
if ((i % 2) == 0) {
_array[i] = arr[end - 1];
} else {
_array[i] = arr[end + 1];
}
}
_array[len] = '\0';
return _array;
}
int getInt(char *arr) {
char hexDigits[16] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
char *_i = (char*) malloc(strlen(arr));
int len = strlen(arr);
int j, decimal = 0;
for (int i = 0; i < len; i++) {
_i[i] = arr[i];
}
for (int i = 0; i < len; i++) {
for (j = 0; j < 16; j++) {
if (_i[i] == hexDigits[j]) {
decimal += j * (int) pow(16, (len-1) - i);
}
}
}
free(_i);
_i = NULL;
return decimal;
}
int getMessageType() {
return (getInt(MHDR) & 0xff) >> 5; //5
}
bool isDataMessage() {
switch (getMessageType()) {
case MTYPE_UNCONFIRMED_DATA_UP:
case MTYPE_UNCONFIRMED_DATA_DOWN:
case MTYPE_CONFIRMED_DATA_UP:
case MTYPE_CONFIRMED_DATA_DOWN:
return true;
default:
return false;
}
}
bool isJoinRequestMessage() {
return (getMessageType() == MTYPE_JOIN_REQUEST);
}
bool isJoinAcceptMessage() {
return (getMessageType() == MTYPE_JOIN_ACCEPT);
}
void freeMem() {
free(MHDR);
free(FCtrl);
free(FCnt);
free(FRMPayload);
free(FPort);
free(AppEUI);
free(DevEUI);
free(DevNonce);
free(MIC);
free(AppNonce);
free(NetID);
free(CFList);
free(MACPayload);
free(FOpts);
free(FHDR);
MHDR = NULL;
FCtrl = NULL;
FCnt = NULL;
FRMPayload = NULL;
FPort = NULL;
AppEUI = NULL;
DevEUI = NULL;
DevNonce = NULL;
MIC = NULL;
AppNonce = NULL;
NetID = NULL;
CFList = NULL;
MACPayload = NULL;
FOpts = NULL;
FHDR = NULL;
}
// Sector initialization
void initialization(char* packet) {
size_t _strl = strlen(packet);
char *_packet = packet;
// initialization
MHDR = (char*) malloc(2);
MIC = (char*) malloc(8);
FCtrl = (char*) malloc(2);
DevAddr = (char*) malloc(8);
FCnt = (char*) malloc(4);
FRMPayload = (char*) malloc(0);
FPort = (char*) malloc(0);
AppEUI = (char*) malloc(16);
DevEUI = (char*) malloc(16);
DevNonce = (char*) malloc(4);
MIC = (char*) malloc(8);
AppNonce = (char*) malloc(6);
NetID = (char*) malloc(6);
DevAddr = (char*) malloc(8);
CFList = (char*) malloc(0);
PHYPayload = packet;
MHDR = slice(_packet, 0, 2);
if (isJoinRequestMessage()) {
AppEUI = reversArray(slice(_packet, 2, 16));
DevEUI = reversArray(slice(_packet, 18, 16));
DevNonce = reversArray(slice(_packet, 34, 4));
MIC = slice(_packet, _strl - 8, 8);
} else if (isJoinAcceptMessage()) {
AppNonce = reversArray(slice(_packet, 2, 6));
NetID = reversArray(slice(_packet, 8, 6));
DevAddr = reversArray(slice(_packet, 14, 8));
DLSettings = getInt(_packet);
RxDelay = getInt(_packet);
if (_strl == 66) {
CFList = (char*) malloc(32);
CFList = slice(_packet, 26, 32);
}
MIC = slice(_packet, _strl - 8, 8);
} else if (isDataMessage() && (_strl > 10)) {
MACPayload = (char*) malloc(_strl - 10);
MACPayload = slice(_packet, 2, (_strl - 10));
MIC = slice(_packet, (_strl - 8), 8);
FCtrl = slice(MACPayload, 8, 2);
int _FCtrl = getInt(FCtrl);
int FOptsLen = (_FCtrl & 0x0f) *2;
if (FOptsLen != 0) {
FOpts = (char*) malloc(FOptsLen);
FOpts = slice(MACPayload, 14, FOptsLen);
}
int FHDR_length = 14 + FOptsLen;
FHDR = (char*) malloc(FHDR_length);
FHDR = slice(MACPayload, 0, 0 + FHDR_length);
DevAddr = reversArray(slice(FHDR, 0, 8));
FCnt = slice(FHDR, 10, 4);
FCnt = reversArray(FCnt);
if (FHDR_length != strlen(MACPayload)) {
FPort = (char*) malloc(2);
FPort = slice(MACPayload, FHDR_length, 2);
if (FHDR_length < strlen(MACPayload)) {
FRMPayload = (char*) malloc(strlen(MACPayload)-(FHDR_length + 2));
FRMPayload = slice(MACPayload, FHDR_length + 2, strlen(MACPayload) - (FHDR_length + 2));
}
}
}
}
// endSector
|
702555.c | /**CFile****************************************************************
FileName [disjunctiveMonotone.c]
SystemName [ABC: Logic synthesis and verification system.]
PackageName [Liveness property checking.]
Synopsis [Constraint analysis module for the k-Liveness algorithm
invented by Koen Classen, Niklas Sorensson.]
Author [Sayak Ray]
Affiliation [UC Berkeley]
Date [Ver. 1.0. Started - October 31, 2012.]
***********************************************************************/
#include <stdio.h>
#include "base/main/main.h"
#include "aig/aig/aig.h"
#include "aig/saig/saig.h"
#include <string.h>
#include "base/main/mainInt.h"
#include "proof/pdr/pdr.h"
#include <time.h>
ABC_NAMESPACE_IMPL_START
struct aigPoIndices
{
int attrPendingSignalIndex;
int attrHintSingalBeginningMarker;
int attrHintSingalEndMarker;
int attrSafetyInvarIndex;
};
extern struct aigPoIndices *allocAigPoIndices();
extern void deallocAigPoIndices(struct aigPoIndices *toBeDeletedAigPoIndices);
extern int collectSafetyInvariantPOIndex(Abc_Ntk_t *pNtk);
struct antecedentConsequentVectorsStruct
{
Vec_Int_t *attrAntecedents;
Vec_Int_t *attrConsequentCandidates;
};
struct antecedentConsequentVectorsStruct *allocAntecedentConsequentVectorsStruct()
{
struct antecedentConsequentVectorsStruct *newStructure;
newStructure = (struct antecedentConsequentVectorsStruct *)malloc(sizeof (struct antecedentConsequentVectorsStruct));
newStructure->attrAntecedents = NULL;
newStructure->attrConsequentCandidates = NULL;
assert( newStructure != NULL );
return newStructure;
}
void deallocAntecedentConsequentVectorsStruct(struct antecedentConsequentVectorsStruct *toBeDeleted)
{
assert( toBeDeleted != NULL );
if(toBeDeleted->attrAntecedents)
Vec_IntFree( toBeDeleted->attrAntecedents );
if(toBeDeleted->attrConsequentCandidates)
Vec_IntFree( toBeDeleted->attrConsequentCandidates );
free( toBeDeleted );
}
Aig_Man_t *createDisjunctiveMonotoneTester(Aig_Man_t *pAig, struct aigPoIndices *aigPoIndicesArg,
struct antecedentConsequentVectorsStruct *anteConseVectors, int *startMonotonePropPo)
{
Aig_Man_t *pNewAig;
int iElem, i, nRegCount;
int piCopied = 0, liCopied = 0, liCreated = 0, loCopied = 0, loCreated = 0;
int poCopied = 0, poCreated = 0;
Aig_Obj_t *pObj, *pObjPo, *pObjDriver, *pObjDriverNew, *pObjPendingDriverNew, *pObjPendingAndNextPending;
Aig_Obj_t *pPendingFlop, *pObjConseCandFlop, *pObjSafetyInvariantPoDriver;
//Vec_Ptr_t *vHintMonotoneLocalDriverNew;
Vec_Ptr_t *vConseCandFlopOutput;
//Vec_Ptr_t *vHintMonotoneLocalProp;
Aig_Obj_t *pObjAnteDisjunction, *pObjConsecDriver, *pObjConsecDriverNew, *pObjCandMonotone, *pObjPrevCandMonotone, *pObjMonotonePropDriver;
Vec_Ptr_t *vCandMonotoneProp;
Vec_Ptr_t *vCandMonotoneFlopInput;
int pendingSignalIndexLocal = aigPoIndicesArg->attrPendingSignalIndex;
Vec_Int_t *vAntecedentsLocal = anteConseVectors->attrAntecedents;
Vec_Int_t *vConsequentCandidatesLocal = anteConseVectors->attrConsequentCandidates;
if( vConsequentCandidatesLocal == NULL )
return NULL; //no candidates for consequent is provided, hence no need to generate a new AIG
//****************************************************************
// Step1: create the new manager
// Note: The new manager is created with "2 * Aig_ManObjNumMax(p)"
// nodes, but this selection is arbitrary - need to be justified
//****************************************************************
pNewAig = Aig_ManStart( Aig_ManObjNumMax(pAig) );
pNewAig->pName = (char *)malloc( strlen( pAig->pName ) + strlen("_monotone") + 2 );
sprintf(pNewAig->pName, "%s_%s", pAig->pName, "monotone");
pNewAig->pSpec = NULL;
//****************************************************************
// Step 2: map constant nodes
//****************************************************************
pObj = Aig_ManConst1( pAig );
pObj->pData = Aig_ManConst1( pNewAig );
//****************************************************************
// Step 3: create true PIs
//****************************************************************
Saig_ManForEachPi( pAig, pObj, i )
{
piCopied++;
pObj->pData = Aig_ObjCreateCi(pNewAig);
}
//****************************************************************
// Step 5: create register outputs
//****************************************************************
Saig_ManForEachLo( pAig, pObj, i )
{
loCopied++;
pObj->pData = Aig_ObjCreateCi(pNewAig);
}
//****************************************************************
// Step 6: create "D" register output for PENDING flop
//****************************************************************
loCreated++;
pPendingFlop = Aig_ObjCreateCi( pNewAig );
//****************************************************************
// Step 6.a: create "D" register output for HINT_MONOTONE flop
//****************************************************************
vConseCandFlopOutput = Vec_PtrAlloc(Vec_IntSize(vConsequentCandidatesLocal));
Vec_IntForEachEntry( vConsequentCandidatesLocal, iElem, i )
{
loCreated++;
pObjConseCandFlop = Aig_ObjCreateCi( pNewAig );
Vec_PtrPush( vConseCandFlopOutput, pObjConseCandFlop );
}
nRegCount = loCreated + loCopied;
//********************************************************************
// Step 7: create internal nodes
//********************************************************************
Aig_ManForEachNode( pAig, pObj, i )
{
pObj->pData = Aig_And( pNewAig, Aig_ObjChild0Copy(pObj), Aig_ObjChild1Copy(pObj) );
}
//********************************************************************
// Step 8: mapping appropriate new flop drivers
//********************************************************************
if( aigPoIndicesArg->attrSafetyInvarIndex != -1 )
{
pObjPo = Aig_ManCo( pAig, aigPoIndicesArg->attrSafetyInvarIndex );
pObjDriver = Aig_NotCond((Aig_Obj_t *)Aig_ObjFanin0(pObjPo), Aig_ObjFaninC0(pObjPo));
pObjDriverNew = !Aig_IsComplement(pObjDriver)?
(Aig_Obj_t *)(Aig_Regular(pObjDriver)->pData) :
Aig_Not((Aig_Obj_t *)(Aig_Regular(pObjDriver)->pData));
pObjSafetyInvariantPoDriver = pObjDriverNew;
}
else
pObjSafetyInvariantPoDriver = Aig_ManConst1(pNewAig);
pObjPo = Aig_ManCo( pAig, pendingSignalIndexLocal );
pObjDriver = Aig_NotCond((Aig_Obj_t *)Aig_ObjFanin0(pObjPo), Aig_ObjFaninC0(pObjPo));
pObjPendingDriverNew = !Aig_IsComplement(pObjDriver)?
(Aig_Obj_t *)(Aig_Regular(pObjDriver)->pData) :
Aig_Not((Aig_Obj_t *)(Aig_Regular(pObjDriver)->pData));
pObjPendingAndNextPending = Aig_And( pNewAig, pObjPendingDriverNew, pPendingFlop );
pObjAnteDisjunction = Aig_Not(Aig_ManConst1( pNewAig ));
if( vAntecedentsLocal )
{
Vec_IntForEachEntry( vAntecedentsLocal, iElem, i )
{
pObjPo = Aig_ManCo( pAig, iElem );
pObjDriver = Aig_NotCond((Aig_Obj_t *)Aig_ObjFanin0(pObjPo), Aig_ObjFaninC0(pObjPo));
pObjDriverNew = !Aig_IsComplement(pObjDriver)?
(Aig_Obj_t *)(Aig_Regular(pObjDriver)->pData) :
Aig_Not((Aig_Obj_t *)(Aig_Regular(pObjDriver)->pData));
pObjAnteDisjunction = Aig_Or( pNewAig, pObjDriverNew, pObjAnteDisjunction );
}
}
vCandMonotoneProp = Vec_PtrAlloc( Vec_IntSize(vConsequentCandidatesLocal) );
vCandMonotoneFlopInput = Vec_PtrAlloc( Vec_IntSize(vConsequentCandidatesLocal) );
Vec_IntForEachEntry( vConsequentCandidatesLocal, iElem, i )
{
pObjPo = Aig_ManCo( pAig, iElem );
pObjConsecDriver = Aig_NotCond((Aig_Obj_t *)Aig_ObjFanin0(pObjPo), Aig_ObjFaninC0(pObjPo));
pObjConsecDriverNew = !Aig_IsComplement(pObjConsecDriver)?
(Aig_Obj_t *)(Aig_Regular(pObjConsecDriver)->pData) :
Aig_Not((Aig_Obj_t *)(Aig_Regular(pObjConsecDriver)->pData));
pObjCandMonotone = Aig_Or( pNewAig, pObjConsecDriverNew, pObjAnteDisjunction );
pObjPrevCandMonotone = (Aig_Obj_t *)(Vec_PtrEntry( vConseCandFlopOutput, i ));
pObjMonotonePropDriver = Aig_Or( pNewAig, Aig_Not( Aig_And( pNewAig, pObjPendingAndNextPending, pObjPrevCandMonotone ) ),
pObjCandMonotone );
//Conjunting safety invar
pObjMonotonePropDriver = Aig_And( pNewAig, pObjMonotonePropDriver, pObjSafetyInvariantPoDriver );
Vec_PtrPush( vCandMonotoneFlopInput, pObjCandMonotone );
Vec_PtrPush( vCandMonotoneProp, pObjMonotonePropDriver );
}
//********************************************************************
// Step 9: create primary outputs
//********************************************************************
Saig_ManForEachPo( pAig, pObj, i )
{
poCopied++;
pObj->pData = Aig_ObjCreateCo( pNewAig, Aig_ObjChild0Copy(pObj) );
}
*startMonotonePropPo = i;
Vec_PtrForEachEntry( Aig_Obj_t *, vCandMonotoneProp, pObj, i )
{
poCreated++;
pObjPo = Aig_ObjCreateCo( pNewAig, pObj );
}
//********************************************************************
// Step 9: create latch inputs
//********************************************************************
Saig_ManForEachLi( pAig, pObj, i )
{
liCopied++;
Aig_ObjCreateCo( pNewAig, Aig_ObjChild0Copy(pObj) );
}
//********************************************************************
// Step 9.a: create latch input for PENDING_FLOP
//********************************************************************
liCreated++;
Aig_ObjCreateCo( pNewAig, pObjPendingDriverNew );
//********************************************************************
// Step 9.b: create latch input for MONOTONE_FLOP
//********************************************************************
Vec_PtrForEachEntry( Aig_Obj_t *, vCandMonotoneFlopInput, pObj, i )
{
liCreated++;
Aig_ObjCreateCo( pNewAig, pObj );
}
Aig_ManSetRegNum( pNewAig, nRegCount );
Aig_ManCleanup( pNewAig );
assert( Aig_ManCheck( pNewAig ) );
assert( loCopied + loCreated == liCopied + liCreated );
Vec_PtrFree(vConseCandFlopOutput);
Vec_PtrFree(vCandMonotoneProp);
Vec_PtrFree(vCandMonotoneFlopInput);
return pNewAig;
}
Vec_Int_t *findNewDisjunctiveMonotone( Aig_Man_t *pAig, struct aigPoIndices *aigPoIndicesArg, struct antecedentConsequentVectorsStruct *anteConseVectors )
{
Aig_Man_t *pAigNew;
Aig_Obj_t *pObjTargetPo;
int poMarker;
//int i, RetValue, poSerialNum;
int i, poSerialNum;
Pdr_Par_t Pars, * pPars = &Pars;
//Abc_Cex_t * pCex = NULL;
Vec_Int_t *vMonotoneIndex;
//char fileName[20];
Abc_Cex_t * cexElem;
int pendingSignalIndexLocal = aigPoIndicesArg->attrPendingSignalIndex;
pAigNew = createDisjunctiveMonotoneTester(pAig, aigPoIndicesArg, anteConseVectors, &poMarker );
//printf("enter an integer : ");
//waitForInteger = getchar();
//putchar(waitForInteger);
vMonotoneIndex = Vec_IntAlloc(0);
for( i=0; i<Saig_ManPoNum(pAigNew); i++ )
{
pObjTargetPo = Aig_ManCo( pAigNew, i );
Aig_ObjChild0Flip( pObjTargetPo );
}
Pdr_ManSetDefaultParams( pPars );
pPars->fVerbose = 0;
pPars->fNotVerbose = 1;
pPars->fSolveAll = 1;
pAigNew->vSeqModelVec = NULL;
Pdr_ManSolve( pAigNew, pPars );
if( pAigNew->vSeqModelVec )
{
Vec_PtrForEachEntry( Abc_Cex_t *, pAigNew->vSeqModelVec, cexElem, i )
{
if( cexElem == NULL && i >= pendingSignalIndexLocal + 1)
{
poSerialNum = i - (pendingSignalIndexLocal + 1);
Vec_IntPush( vMonotoneIndex, Vec_IntEntry( anteConseVectors->attrConsequentCandidates, poSerialNum ));
}
}
}
for( i=0; i<Saig_ManPoNum(pAigNew); i++ )
{
pObjTargetPo = Aig_ManCo( pAigNew, i );
Aig_ObjChild0Flip( pObjTargetPo );
}
//if(pAigNew->vSeqModelVec)
// Vec_PtrFree(pAigNew->vSeqModelVec);
Aig_ManStop(pAigNew);
if( Vec_IntSize( vMonotoneIndex ) > 0 )
{
return vMonotoneIndex;
}
else
{
Vec_IntFree(vMonotoneIndex);
return NULL;
}
}
Vec_Int_t *updateAnteConseVectors(struct antecedentConsequentVectorsStruct *anteConse )
{
Vec_Int_t *vCandMonotone;
int iElem, i;
//if( vKnownMonotone == NULL || Vec_IntSize(vKnownMonotone) <= 0 )
// return vHintMonotone;
if( anteConse->attrAntecedents == NULL || Vec_IntSize(anteConse->attrAntecedents) <= 0 )
return anteConse->attrConsequentCandidates;
vCandMonotone = Vec_IntAlloc(0);
Vec_IntForEachEntry( anteConse->attrConsequentCandidates, iElem, i )
{
if( Vec_IntFind( anteConse->attrAntecedents, iElem ) == -1 )
Vec_IntPush( vCandMonotone, iElem );
}
return vCandMonotone;
}
Vec_Int_t *vectorDifference(Vec_Int_t *A, Vec_Int_t *B)
{
Vec_Int_t *C;
int iElem, i;
C = Vec_IntAlloc(0);
Vec_IntForEachEntry( A, iElem, i )
{
if( Vec_IntFind( B, iElem ) == -1 )
{
Vec_IntPush( C, iElem );
}
}
return C;
}
Vec_Int_t *createSingletonIntVector( int iElem )
{
Vec_Int_t *myVec = Vec_IntAlloc(1);
Vec_IntPush(myVec, iElem);
return myVec;
}
#if 0
Vec_Ptr_t *generateDisjuntiveMonotone_rec()
{
nextLevelSignals = ;
if level is not exhausted
for all x \in nextLevelSignals
{
append x in currAntecendent
recond it as a monotone predicate
resurse with level - 1
}
}
#endif
#if 0
Vec_Ptr_t *generateDisjuntiveMonotoneLevels(Aig_Man_t *pAig,
struct aigPoIndices *aigPoIndicesInstance,
struct antecedentConsequentVectorsStruct *anteConsecInstanceOrig,
int level )
{
Vec_Int_t *firstLevelMonotone;
Vec_Int_t *currVecInt;
Vec_Ptr_t *hierarchyList;
int iElem, i;
assert( level >= 1 );
firstLevelMonotone = findNewDisjunctiveMonotone( pAig, aigPoIndicesInstance, anteConsecInstance );
if( firstLevelMonotone == NULL || Vec_IntSize(firstLevelMonotone) <= 0 )
return NULL;
hierarchyList = Vec_PtrAlloc(Vec_IntSize(firstLevelMonotone));
Vec_IntForEachEntry( firstLevelMonotone, iElem, i )
{
currVecInt = createSingletonIntVector( iElem );
Vec_PtrPush( hierarchyList, currVecInt );
}
if( level > 1 )
{
Vec_IntForEachEntry( firstLevelMonotone, iElem, i )
{
currVecInt = (Vec_Int_t *)Vec_PtrEntry( hierarchyList, i );
}
}
return hierarchyList;
}
#endif
int Vec_IntPushUniqueLocal( Vec_Int_t * p, int Entry )
{
int i;
for ( i = 0; i < p->nSize; i++ )
if ( p->pArray[i] == Entry )
return 1;
Vec_IntPush( p, Entry );
return 0;
}
Vec_Ptr_t *findNextLevelDisjunctiveMonotone(
Aig_Man_t *pAig,
struct aigPoIndices *aigPoIndicesInstance,
struct antecedentConsequentVectorsStruct *anteConsecInstance,
Vec_Ptr_t *previousMonotoneVectors )
{
Vec_Ptr_t *newLevelPtrVec;
Vec_Int_t *vElem, *vNewDisjunctVector, *newDisjunction;
int i, j, iElem;
struct antecedentConsequentVectorsStruct *anteConsecInstanceLocal;
Vec_Int_t *vUnionPrevMonotoneVector, *vDiffVector;
newLevelPtrVec = Vec_PtrAlloc(0);
vUnionPrevMonotoneVector = Vec_IntAlloc(0);
Vec_PtrForEachEntry(Vec_Int_t *, previousMonotoneVectors, vElem, i)
Vec_IntForEachEntry( vElem, iElem, j )
Vec_IntPushUniqueLocal( vUnionPrevMonotoneVector, iElem );
Vec_PtrForEachEntry(Vec_Int_t *, previousMonotoneVectors, vElem, i)
{
anteConsecInstanceLocal = allocAntecedentConsequentVectorsStruct();
anteConsecInstanceLocal->attrAntecedents = Vec_IntDup(vElem);
vDiffVector = vectorDifference( anteConsecInstance->attrConsequentCandidates, vUnionPrevMonotoneVector);
anteConsecInstanceLocal->attrConsequentCandidates = vDiffVector;
assert( vDiffVector );
//printf("Calling target function %d\n", i);
vNewDisjunctVector = findNewDisjunctiveMonotone( pAig, aigPoIndicesInstance, anteConsecInstanceLocal );
if( vNewDisjunctVector )
{
Vec_IntForEachEntry(vNewDisjunctVector, iElem, j)
{
newDisjunction = Vec_IntDup(vElem);
Vec_IntPush( newDisjunction, iElem );
Vec_PtrPush( newLevelPtrVec, newDisjunction );
}
Vec_IntFree(vNewDisjunctVector);
}
deallocAntecedentConsequentVectorsStruct( anteConsecInstanceLocal );
}
Vec_IntFree(vUnionPrevMonotoneVector);
return newLevelPtrVec;
}
void printAllIntVectors(Vec_Ptr_t *vDisjunctions, Abc_Ntk_t *pNtk, char *fileName)
{
Vec_Int_t *vElem;
int i, j, iElem;
char *name, *hintSubStr;
FILE *fp;
fp = fopen( fileName, "a" );
Vec_PtrForEachEntry(Vec_Int_t *, vDisjunctions, vElem, i)
{
fprintf(fp, "( ");
Vec_IntForEachEntry( vElem, iElem, j )
{
name = Abc_ObjName( Abc_NtkPo(pNtk, iElem));
hintSubStr = strstr( name, "hint");
assert( hintSubStr );
fprintf(fp, "%s", hintSubStr);
if( j < Vec_IntSize(vElem) - 1 )
{
fprintf(fp, " || ");
}
else
{
fprintf(fp, " )\n");
}
}
}
fclose(fp);
}
void printAllIntVectorsStabil(Vec_Ptr_t *vDisjunctions, Abc_Ntk_t *pNtk, char *fileName)
{
Vec_Int_t *vElem;
int i, j, iElem;
char *name, *hintSubStr;
FILE *fp;
fp = fopen( fileName, "a" );
Vec_PtrForEachEntry(Vec_Int_t *, vDisjunctions, vElem, i)
{
printf("INT[%d] : ( ", i);
fprintf(fp, "( ");
Vec_IntForEachEntry( vElem, iElem, j )
{
name = Abc_ObjName( Abc_NtkPo(pNtk, iElem));
hintSubStr = strstr( name, "csLevel1Stabil");
assert( hintSubStr );
printf("%s", hintSubStr);
fprintf(fp, "%s", hintSubStr);
if( j < Vec_IntSize(vElem) - 1 )
{
printf(" || ");
fprintf(fp, " || ");
}
else
{
printf(" )\n");
fprintf(fp, " )\n");
}
}
//printf(")\n");
}
fclose(fp);
}
void appendVecToMasterVecInt(Vec_Ptr_t *masterVec, Vec_Ptr_t *candVec )
{
int i;
Vec_Int_t *vCand;
Vec_Int_t *vNewIntVec;
assert(masterVec != NULL);
assert(candVec != NULL);
Vec_PtrForEachEntry( Vec_Int_t *, candVec, vCand, i )
{
vNewIntVec = Vec_IntDup(vCand);
Vec_PtrPush(masterVec, vNewIntVec);
}
}
void deallocateVecOfIntVec( Vec_Ptr_t *vecOfIntVec )
{
Vec_Int_t *vInt;
int i;
if( vecOfIntVec )
{
Vec_PtrForEachEntry( Vec_Int_t *, vecOfIntVec, vInt, i )
{
Vec_IntFree( vInt );
}
Vec_PtrFree(vecOfIntVec);
}
}
Vec_Ptr_t *findDisjunctiveMonotoneSignals( Abc_Ntk_t *pNtk )
{
Aig_Man_t *pAig;
Vec_Int_t *vCandidateMonotoneSignals;
Vec_Int_t *vKnownMonotoneSignals;
//Vec_Int_t *vKnownMonotoneSignalsRoundTwo;
//Vec_Int_t *vOldConsequentVector;
//Vec_Int_t *vRemainingConsecVector;
int i;
int iElem;
int pendingSignalIndex;
Abc_Ntk_t *pNtkTemp;
int hintSingalBeginningMarker;
int hintSingalEndMarker;
struct aigPoIndices *aigPoIndicesInstance;
//struct monotoneVectorsStruct *monotoneVectorsInstance;
struct antecedentConsequentVectorsStruct *anteConsecInstance;
//Aig_Obj_t *safetyDriverNew;
Vec_Int_t *newIntVec;
Vec_Ptr_t *levelOneMonotne, *levelTwoMonotne;
//Vec_Ptr_t *levelThreeMonotne;
Vec_Ptr_t *vMasterDisjunctions;
extern int findPendingSignal(Abc_Ntk_t *pNtk);
extern Vec_Int_t *findHintOutputs(Abc_Ntk_t *pNtk);
extern Aig_Man_t * Abc_NtkToDar( Abc_Ntk_t * pNtk, int fExors, int fRegisters );
//system("rm monotone.dat");
/*******************************************/
//Finding the PO index of the pending signal
/*******************************************/
pendingSignalIndex = findPendingSignal(pNtk);
if( pendingSignalIndex == -1 )
{
printf("\nNo Pending Signal Found\n");
return NULL;
}
//else
//printf("Po[%d] = %s\n", pendingSignalIndex, Abc_ObjName( Abc_NtkPo(pNtk, pendingSignalIndex) ) );
/*******************************************/
//Finding the PO indices of all hint signals
/*******************************************/
vCandidateMonotoneSignals = findHintOutputs(pNtk);
if( vCandidateMonotoneSignals == NULL )
return NULL;
else
{
//Vec_IntForEachEntry( vCandidateMonotoneSignals, iElem, i )
// printf("Po[%d] = %s\n", iElem, Abc_ObjName( Abc_NtkPo(pNtk, iElem) ) );
hintSingalBeginningMarker = Vec_IntEntry( vCandidateMonotoneSignals, 0 );
hintSingalEndMarker = Vec_IntEntry( vCandidateMonotoneSignals, Vec_IntSize(vCandidateMonotoneSignals) - 1 );
}
/**********************************************/
//Allocating "struct" with necessary parameters
/**********************************************/
aigPoIndicesInstance = allocAigPoIndices();
aigPoIndicesInstance->attrPendingSignalIndex = pendingSignalIndex;
aigPoIndicesInstance->attrHintSingalBeginningMarker = hintSingalBeginningMarker;
aigPoIndicesInstance->attrHintSingalEndMarker = hintSingalEndMarker;
aigPoIndicesInstance->attrSafetyInvarIndex = collectSafetyInvariantPOIndex(pNtk);
/****************************************************/
//Allocating "struct" with necessary monotone vectors
/****************************************************/
anteConsecInstance = allocAntecedentConsequentVectorsStruct();
anteConsecInstance->attrAntecedents = NULL;
anteConsecInstance->attrConsequentCandidates = vCandidateMonotoneSignals;
/*******************************************/
//Generate AIG from Ntk
/*******************************************/
if( !Abc_NtkIsStrash( pNtk ) )
{
pNtkTemp = Abc_NtkStrash( pNtk, 0, 0, 0 );
pAig = Abc_NtkToDar( pNtkTemp, 0, 1 );
}
else
{
pAig = Abc_NtkToDar( pNtk, 0, 1 );
pNtkTemp = pNtk;
}
/*******************************************/
//finding LEVEL 1 monotone signals
/*******************************************/
//printf("Calling target function outside loop\n");
vKnownMonotoneSignals = findNewDisjunctiveMonotone( pAig, aigPoIndicesInstance, anteConsecInstance );
levelOneMonotne = Vec_PtrAlloc(0);
Vec_IntForEachEntry( vKnownMonotoneSignals, iElem, i )
{
newIntVec = createSingletonIntVector( iElem );
Vec_PtrPush( levelOneMonotne, newIntVec );
//printf("Monotone Po[%d] = %s\n", iElem, Abc_ObjName( Abc_NtkPo(pNtk, iElem) ) );
}
//printAllIntVectors( levelOneMonotne, pNtk, "monotone.dat" );
vMasterDisjunctions = Vec_PtrAlloc( Vec_PtrSize( levelOneMonotne ));
appendVecToMasterVecInt(vMasterDisjunctions, levelOneMonotne );
/*******************************************/
//finding LEVEL >1 monotone signals
/*******************************************/
#if 0
if( vKnownMonotoneSignals )
{
Vec_IntForEachEntry( vKnownMonotoneSignals, iElem, i )
{
printf("\n**************************************************************\n");
printf("Exploring Second Layer : Reference Po[%d] = %s", iElem, Abc_ObjName( Abc_NtkPo(pNtk, iElem) ));
printf("\n**************************************************************\n");
anteConsecInstance->attrAntecedents = createSingletonIntVector( iElem );
vOldConsequentVector = anteConsecInstance->attrConsequentCandidates;
vRemainingConsecVector = updateAnteConseVectors(anteConsecInstance);
if( anteConsecInstance->attrConsequentCandidates != vRemainingConsecVector )
{
anteConsecInstance->attrConsequentCandidates = vRemainingConsecVector;
}
vKnownMonotoneSignalsRoundTwo = findNewDisjunctiveMonotone( pAig, aigPoIndicesInstance, anteConsecInstance );
Vec_IntForEachEntry( vKnownMonotoneSignalsRoundTwo, iElemTwo, iTwo )
{
printf("Monotone Po[%d] = %s, (%d, %d)\n", iElemTwo, Abc_ObjName( Abc_NtkPo(pNtk, iElemTwo) ), iElem, iElemTwo );
}
Vec_IntFree(vKnownMonotoneSignalsRoundTwo);
Vec_IntFree(anteConsecInstance->attrAntecedents);
if(anteConsecInstance->attrConsequentCandidates != vOldConsequentVector)
{
Vec_IntFree(anteConsecInstance->attrConsequentCandidates);
anteConsecInstance->attrConsequentCandidates = vOldConsequentVector;
}
}
}
#endif
#if 1
levelTwoMonotne = findNextLevelDisjunctiveMonotone( pAig, aigPoIndicesInstance, anteConsecInstance, levelOneMonotne );
//printAllIntVectors( levelTwoMonotne, pNtk, "monotone.dat" );
appendVecToMasterVecInt(vMasterDisjunctions, levelTwoMonotne );
#endif
//levelThreeMonotne = findNextLevelDisjunctiveMonotone( pAig, aigPoIndicesInstance, anteConsecInstance, levelTwoMonotne );
//printAllIntVectors( levelThreeMonotne );
//printAllIntVectors( levelTwoMonotne, pNtk, "monotone.dat" );
//appendVecToMasterVecInt(vMasterDisjunctions, levelThreeMonotne );
deallocAigPoIndices(aigPoIndicesInstance);
deallocAntecedentConsequentVectorsStruct(anteConsecInstance);
//deallocPointersToMonotoneVectors(monotoneVectorsInstance);
deallocateVecOfIntVec( levelOneMonotne );
deallocateVecOfIntVec( levelTwoMonotne );
Aig_ManStop(pAig);
Vec_IntFree(vKnownMonotoneSignals);
return vMasterDisjunctions;
}
ABC_NAMESPACE_IMPL_END
|
173925.c | /*
C140.c
Simulator based on AMUSE sources.
The C140 sound chip is used by Namco System 2 and System 21
The 219 ASIC (which incorporates a modified C140) is used by Namco NA-1 and NA-2
This chip controls 24 channels (C140) or 16 (219) of PCM.
16 bytes are associated with each channel.
Channels can be 8 bit signed PCM, or 12 bit signed PCM.
Timer behavior is not yet handled.
Unmapped registers:
0x1f8:timer interval? (Nx0.1 ms)
0x1fa:irq ack? timer restart?
0x1fe:timer switch?(0:off 1:on)
--------------
ASIC "219" notes
On the 219 ASIC used on NA-1 and NA-2, the high registers have the following
meaning instead:
0x1f7: bank for voices 0-3
0x1f1: bank for voices 4-7
0x1f3: bank for voices 8-11
0x1f5: bank for voices 12-15
Some games (bkrtmaq, xday2) write to 0x1fd for voices 12-15 instead. Probably the bank registers
mirror at 1f8, in which case 1ff is also 0-3, 1f9 is also 4-7, 1fb is also 8-11, and 1fd is also 12-15.
Each bank is 0x20000 (128k), and the voice addresses on the 219 are all multiplied by 2.
Additionally, the 219's base pitch is the same as the C352's (42667). But these changes
are IMO not sufficient to make this a separate file - all the other registers are
fully compatible.
Finally, the 219 only has 16 voices.
*/
/*
2000.06.26 CAB fixed compressed pcm playback
2002.07.20 R.Belmont added support for multiple banking types
2006.01.08 R.Belmont added support for NA-1/2 "219" derivative
*/
#include "emu.h"
#include "streams.h"
#include "c140.h"
#define MAX_VOICE 24
struct voice_registers
{
UINT8 volume_right;
UINT8 volume_left;
UINT8 frequency_msb;
UINT8 frequency_lsb;
UINT8 bank;
UINT8 mode;
UINT8 start_msb;
UINT8 start_lsb;
UINT8 end_msb;
UINT8 end_lsb;
UINT8 loop_msb;
UINT8 loop_lsb;
UINT8 reserved[4];
};
typedef struct
{
long ptoffset;
long pos;
long key;
//--work
long lastdt;
long prevdt;
long dltdt;
//--reg
long rvol;
long lvol;
long frequency;
long bank;
long mode;
long sample_start;
long sample_end;
long sample_loop;
} VOICE;
typedef struct _c140_state c140_state;
struct _c140_state
{
int sample_rate;
sound_stream *stream;
int banking_type;
/* internal buffers */
INT16 *mixer_buffer_left;
INT16 *mixer_buffer_right;
int baserate;
void *pRom;
UINT8 REG[0x200];
INT16 pcmtbl[8]; //2000.06.26 CAB
VOICE voi[MAX_VOICE];
};
INLINE c140_state *get_safe_token(running_device *device)
{
assert(device != NULL);
assert(device->type() == SOUND_C140);
return (c140_state *)downcast<legacy_device_base *>(device)->token();
}
static void init_voice( VOICE *v )
{
v->key=0;
v->ptoffset=0;
v->rvol=0;
v->lvol=0;
v->frequency=0;
v->bank=0;
v->mode=0;
v->sample_start=0;
v->sample_end=0;
v->sample_loop=0;
}
READ8_DEVICE_HANDLER( c140_r )
{
c140_state *info = get_safe_token(device);
offset&=0x1ff;
return info->REG[offset];
}
/*
find_sample: compute the actual address of a sample given it's
address and banking registers, as well as the board type.
I suspect in "real life" this works like the Sega MultiPCM where the banking
is done by a small PAL or GAL external to the sound chip, which can be switched
per-game or at least per-PCB revision as addressing range needs grow.
*/
static long find_sample(c140_state *info, long adrs, long bank, int voice)
{
long newadr = 0;
static const INT16 asic219banks[4] = { 0x1f7, 0x1f1, 0x1f3, 0x1f5 };
adrs=(bank<<16)+adrs;
switch (info->banking_type)
{
case C140_TYPE_SYSTEM2:
// System 2 banking
newadr = ((adrs&0x200000)>>2)|(adrs&0x7ffff);
break;
case C140_TYPE_SYSTEM21_A:
// System 21 type A (simple) banking.
// similar to System 2's.
newadr = ((adrs&0x300000)>>1)+(adrs&0x7ffff);
break;
case C140_TYPE_SYSTEM21_B:
// System 21 type B (chip select) banking
// get base address of sample inside the bank
newadr = ((adrs&0x100000)>>2) + (adrs&0x3ffff);
// now add the starting bank offsets based on the 2
// chip select bits.
// 0x40000 picks individual 512k ROMs
if (adrs & 0x40000)
{
newadr += 0x80000;
}
// and 0x200000 which group of chips...
if (adrs & 0x200000)
{
newadr += 0x100000;
}
break;
case C140_TYPE_ASIC219:
// ASIC219's banking is fairly simple
newadr = ((info->REG[asic219banks[voice/4]]&0x3) * 0x20000) + adrs;
break;
}
return (newadr);
}
WRITE8_DEVICE_HANDLER( c140_w )
{
c140_state *info = get_safe_token(device);
stream_update(info->stream);
offset&=0x1ff;
// mirror the bank registers on the 219, fixes bkrtmaq (and probably xday2 based on notes in the HLE)
if ((offset >= 0x1f8) && (info->banking_type == C140_TYPE_ASIC219))
{
offset -= 8;
}
info->REG[offset]=data;
if( offset<0x180 )
{
VOICE *v = &info->voi[offset>>4];
if( (offset&0xf)==0x5 )
{
if( data&0x80 )
{
const struct voice_registers *vreg = (struct voice_registers *) &info->REG[offset&0x1f0];
v->key=1;
v->ptoffset=0;
v->pos=0;
v->lastdt=0;
v->prevdt=0;
v->dltdt=0;
v->bank = vreg->bank;
v->mode = data;
// on the 219 asic, addresses are in words
if (info->banking_type == C140_TYPE_ASIC219)
{
v->sample_loop = (vreg->loop_msb*256 + vreg->loop_lsb)*2;
v->sample_start = (vreg->start_msb*256 + vreg->start_lsb)*2;
v->sample_end = (vreg->end_msb*256 + vreg->end_lsb)*2;
#if 0
logerror("219: play v %d mode %02x start %x loop %x end %x\n",
offset>>4, v->mode,
find_sample(info, v->sample_start, v->bank, offset>>4),
find_sample(info, v->sample_loop, v->bank, offset>>4),
find_sample(info, v->sample_end, v->bank, offset>>4));
#endif
}
else
{
v->sample_loop = vreg->loop_msb*256 + vreg->loop_lsb;
v->sample_start = vreg->start_msb*256 + vreg->start_lsb;
v->sample_end = vreg->end_msb*256 + vreg->end_lsb;
}
}
else
{
v->key=0;
}
}
}
}
void c140_set_base(running_device *device, void *base)
{
c140_state *info = get_safe_token(device);
info->pRom = base;
}
INLINE int limit(INT32 in)
{
if(in>0x7fff) return 0x7fff;
else if(in<-0x8000) return -0x8000;
return in;
}
static STREAM_UPDATE( update_stereo )
{
c140_state *info = (c140_state *)param;
int i,j;
INT32 rvol,lvol;
INT32 dt;
INT32 sdt;
INT32 st,ed,sz;
INT8 *pSampleData;
INT32 frequency,delta,offset,pos;
INT32 cnt, voicecnt;
INT32 lastdt,prevdt,dltdt;
float pbase=(float)info->baserate*2.0 / (float)info->sample_rate;
INT16 *lmix, *rmix;
if(samples>info->sample_rate) samples=info->sample_rate;
/* zap the contents of the mixer buffer */
memset(info->mixer_buffer_left, 0, samples * sizeof(INT16));
memset(info->mixer_buffer_right, 0, samples * sizeof(INT16));
/* get the number of voices to update */
voicecnt = (info->banking_type == C140_TYPE_ASIC219) ? 16 : 24;
//--- audio update
for( i=0;i<voicecnt;i++ )
{
VOICE *v = &info->voi[i];
const struct voice_registers *vreg = (struct voice_registers *)&info->REG[i*16];
if( v->key )
{
frequency= vreg->frequency_msb*256 + vreg->frequency_lsb;
/* Abort voice if no frequency value set */
if(frequency==0) continue;
/* Delta = frequency * ((8MHz/374)*2 / sample rate) */
delta=(long)((float)frequency * pbase);
/* Calculate left/right channel volumes */
lvol=(vreg->volume_left*32)/MAX_VOICE; //32ch -> 24ch
rvol=(vreg->volume_right*32)/MAX_VOICE;
/* Set mixer outputs base pointers */
lmix = info->mixer_buffer_left;
rmix = info->mixer_buffer_right;
/* Retrieve sample start/end and calculate size */
st=v->sample_start;
ed=v->sample_end;
sz=ed-st;
/* Retrieve base pointer to the sample data */
pSampleData=(signed char*)((FPTR)info->pRom + find_sample(info, st, v->bank, i));
/* Fetch back previous data pointers */
offset=v->ptoffset;
pos=v->pos;
lastdt=v->lastdt;
prevdt=v->prevdt;
dltdt=v->dltdt;
/* Switch on data type - compressed PCM is only for C140 */
if ((v->mode&8) && (info->banking_type != C140_TYPE_ASIC219))
{
//compressed PCM (maybe correct...)
/* Loop for enough to fill sample buffer as requested */
for(j=0;j<samples;j++)
{
offset += delta;
cnt = (offset>>16)&0x7fff;
offset &= 0xffff;
pos+=cnt;
//for(;cnt>0;cnt--)
{
/* Check for the end of the sample */
if(pos >= sz)
{
/* Check if its a looping sample, either stop or loop */
if(v->mode&0x10)
{
pos = (v->sample_loop - st);
}
else
{
v->key=0;
break;
}
}
/* Read the chosen sample byte */
dt=pSampleData[pos];
/* decompress to 13bit range */ //2000.06.26 CAB
sdt=dt>>3; //signed
if(sdt<0) sdt = (sdt<<(dt&7)) - info->pcmtbl[dt&7];
else sdt = (sdt<<(dt&7)) + info->pcmtbl[dt&7];
prevdt=lastdt;
lastdt=sdt;
dltdt=(lastdt - prevdt);
}
/* Caclulate the sample value */
dt=((dltdt*offset)>>16)+prevdt;
/* Write the data to the sample buffers */
*lmix++ +=(dt*lvol)>>(5+5);
*rmix++ +=(dt*rvol)>>(5+5);
}
}
else
{
/* linear 8bit signed PCM */
for(j=0;j<samples;j++)
{
offset += delta;
cnt = (offset>>16)&0x7fff;
offset &= 0xffff;
pos += cnt;
/* Check for the end of the sample */
if(pos >= sz)
{
/* Check if its a looping sample, either stop or loop */
if( v->mode&0x10 )
{
pos = (v->sample_loop - st);
}
else
{
v->key=0;
break;
}
}
if( cnt )
{
prevdt=lastdt;
if (info->banking_type == C140_TYPE_ASIC219)
{
lastdt = pSampleData[BYTE_XOR_BE(pos)];
// Sign + magnitude format
if ((v->mode & 0x01) && (lastdt & 0x80))
lastdt = -(lastdt & 0x7f);
// Sign flip
if (v->mode & 0x40)
lastdt = -lastdt;
}
else
{
lastdt=pSampleData[pos];
}
dltdt = (lastdt - prevdt);
}
/* Caclulate the sample value */
dt=((dltdt*offset)>>16)+prevdt;
/* Write the data to the sample buffers */
*lmix++ +=(dt*lvol)>>5;
*rmix++ +=(dt*rvol)>>5;
}
}
/* Save positional data for next callback */
v->ptoffset=offset;
v->pos=pos;
v->lastdt=lastdt;
v->prevdt=prevdt;
v->dltdt=dltdt;
}
}
/* render to MAME's stream buffer */
lmix = info->mixer_buffer_left;
rmix = info->mixer_buffer_right;
{
stream_sample_t *dest1 = outputs[0];
stream_sample_t *dest2 = outputs[1];
for (i = 0; i < samples; i++)
{
*dest1++ = limit(8*(*lmix++));
*dest2++ = limit(8*(*rmix++));
}
}
}
static DEVICE_START( c140 )
{
const c140_interface *intf = (const c140_interface *)device->baseconfig().static_config();
c140_state *info = get_safe_token(device);
info->sample_rate=info->baserate=device->clock();
info->banking_type = intf->banking_type;
info->stream = stream_create(device,0,2,info->sample_rate,info,update_stereo);
info->pRom=*device->region();
/* make decompress pcm table */ //2000.06.26 CAB
{
int i;
INT32 segbase=0;
for(i=0;i<8;i++)
{
info->pcmtbl[i]=segbase; //segment base value
segbase += 16<<i;
}
}
memset(info->REG,0,sizeof(info->REG));
{
int i;
for(i=0;i<MAX_VOICE;i++) init_voice( &info->voi[i] );
}
/* allocate a pair of buffers to mix into - 1 second's worth should be more than enough */
info->mixer_buffer_left = auto_alloc_array(device->machine, INT16, 2 * info->sample_rate);
info->mixer_buffer_right = info->mixer_buffer_left + info->sample_rate;
}
/**************************************************************************
* Generic get_info
**************************************************************************/
DEVICE_GET_INFO( c140 )
{
switch (state)
{
/* --- the following bits of info are returned as 64-bit signed integers --- */
case DEVINFO_INT_TOKEN_BYTES: info->i = sizeof(c140_state); break;
/* --- the following bits of info are returned as pointers to data or functions --- */
case DEVINFO_FCT_START: info->start = DEVICE_START_NAME( c140 ); break;
case DEVINFO_FCT_STOP: /* nothing */ break;
case DEVINFO_FCT_RESET: /* nothing */ break;
/* --- the following bits of info are returned as NULL-terminated strings --- */
case DEVINFO_STR_NAME: strcpy(info->s, "C140"); break;
case DEVINFO_STR_FAMILY: strcpy(info->s, "Namco PCM"); break;
case DEVINFO_STR_VERSION: strcpy(info->s, "1.0"); break;
case DEVINFO_STR_SOURCE_FILE: strcpy(info->s, __FILE__); break;
case DEVINFO_STR_CREDITS: strcpy(info->s, "Copyright Nicola Salmoria and the MAME Team"); break;
}
}
DEFINE_LEGACY_SOUND_DEVICE(C140, c140);
|
921700.c | #include "system_includes.h"
#include "mobcal_pgpaqmr.h"
void mobcal_pgpaqmr(int n, double *p, double *q, double *r) {
/*
p <- p .+ (q .* r)
This routine should get a fused multipliy add if available.
*/
int i;
int padi;
for (i=0;i<8;i++) {
p[i] = p[i] + (q[i] * r[i]);
}
}
|
906046.c | /*
* Copyright 2000 by Hans Reiser, licensing governed by reiserfs/README
*/
#include <linux/time.h>
#include <linux/fs.h>
#include <linux/reiserfs_fs.h>
#include <linux/reiserfs_acl.h>
#include <linux/reiserfs_xattr.h>
#include <linux/exportfs.h>
#include <linux/pagemap.h>
#include <linux/highmem.h>
#include <linux/slab.h>
#include <asm/uaccess.h>
#include <asm/unaligned.h>
#include <linux/buffer_head.h>
#include <linux/mpage.h>
#include <linux/writeback.h>
#include <linux/quotaops.h>
#include <linux/swap.h>
int reiserfs_commit_write(struct file *f, struct page *page,
unsigned from, unsigned to);
void reiserfs_evict_inode(struct inode *inode)
{
/* We need blocks for transaction + (user+group) quota update (possibly delete) */
int jbegin_count =
JOURNAL_PER_BALANCE_CNT * 2 +
2 * REISERFS_QUOTA_INIT_BLOCKS(inode->i_sb);
struct reiserfs_transaction_handle th;
int depth;
int err;
if (!inode->i_nlink && !is_bad_inode(inode))
dquot_initialize(inode);
truncate_inode_pages(&inode->i_data, 0);
if (inode->i_nlink)
goto no_delete;
depth = reiserfs_write_lock_once(inode->i_sb);
/* The = 0 happens when we abort creating a new inode for some reason like lack of space.. */
if (!(inode->i_state & I_NEW) && INODE_PKEY(inode)->k_objectid != 0) { /* also handles bad_inode case */
reiserfs_delete_xattrs(inode);
if (journal_begin(&th, inode->i_sb, jbegin_count))
goto out;
reiserfs_update_inode_transaction(inode);
reiserfs_discard_prealloc(&th, inode);
err = reiserfs_delete_object(&th, inode);
/* Do quota update inside a transaction for journaled quotas. We must do that
* after delete_object so that quota updates go into the same transaction as
* stat data deletion */
if (!err)
dquot_free_inode(inode);
if (journal_end(&th, inode->i_sb, jbegin_count))
goto out;
/* check return value from reiserfs_delete_object after
* ending the transaction
*/
if (err)
goto out;
/* all items of file are deleted, so we can remove "save" link */
remove_save_link(inode, 0 /* not truncate */ ); /* we can't do anything
* about an error here */
} else {
/* no object items are in the tree */
;
}
out:
end_writeback(inode); /* note this must go after the journal_end to prevent deadlock */
dquot_drop(inode);
inode->i_blocks = 0;
reiserfs_write_unlock_once(inode->i_sb, depth);
return;
no_delete:
end_writeback(inode);
dquot_drop(inode);
}
static void _make_cpu_key(struct cpu_key *key, int version, __u32 dirid,
__u32 objectid, loff_t offset, int type, int length)
{
key->version = version;
key->on_disk_key.k_dir_id = dirid;
key->on_disk_key.k_objectid = objectid;
set_cpu_key_k_offset(key, offset);
set_cpu_key_k_type(key, type);
key->key_length = length;
}
/* take base of inode_key (it comes from inode always) (dirid, objectid) and version from an inode, set
offset and type of key */
void make_cpu_key(struct cpu_key *key, struct inode *inode, loff_t offset,
int type, int length)
{
_make_cpu_key(key, get_inode_item_key_version(inode),
le32_to_cpu(INODE_PKEY(inode)->k_dir_id),
le32_to_cpu(INODE_PKEY(inode)->k_objectid), offset, type,
length);
}
//
// when key is 0, do not set version and short key
//
inline void make_le_item_head(struct item_head *ih, const struct cpu_key *key,
int version,
loff_t offset, int type, int length,
int entry_count /*or ih_free_space */ )
{
if (key) {
ih->ih_key.k_dir_id = cpu_to_le32(key->on_disk_key.k_dir_id);
ih->ih_key.k_objectid =
cpu_to_le32(key->on_disk_key.k_objectid);
}
put_ih_version(ih, version);
set_le_ih_k_offset(ih, offset);
set_le_ih_k_type(ih, type);
put_ih_item_len(ih, length);
/* set_ih_free_space (ih, 0); */
// for directory items it is entry count, for directs and stat
// datas - 0xffff, for indirects - 0
put_ih_entry_count(ih, entry_count);
}
//
// FIXME: we might cache recently accessed indirect item
// Ugh. Not too eager for that....
// I cut the code until such time as I see a convincing argument (benchmark).
// I don't want a bloated inode struct..., and I don't like code complexity....
/* cutting the code is fine, since it really isn't in use yet and is easy
** to add back in. But, Vladimir has a really good idea here. Think
** about what happens for reading a file. For each page,
** The VFS layer calls reiserfs_readpage, who searches the tree to find
** an indirect item. This indirect item has X number of pointers, where
** X is a big number if we've done the block allocation right. But,
** we only use one or two of these pointers during each call to readpage,
** needlessly researching again later on.
**
** The size of the cache could be dynamic based on the size of the file.
**
** I'd also like to see us cache the location the stat data item, since
** we are needlessly researching for that frequently.
**
** --chris
*/
/* If this page has a file tail in it, and
** it was read in by get_block_create_0, the page data is valid,
** but tail is still sitting in a direct item, and we can't write to
** it. So, look through this page, and check all the mapped buffers
** to make sure they have valid block numbers. Any that don't need
** to be unmapped, so that __block_write_begin will correctly call
** reiserfs_get_block to convert the tail into an unformatted node
*/
static inline void fix_tail_page_for_writing(struct page *page)
{
struct buffer_head *head, *next, *bh;
if (page && page_has_buffers(page)) {
head = page_buffers(page);
bh = head;
do {
next = bh->b_this_page;
if (buffer_mapped(bh) && bh->b_blocknr == 0) {
reiserfs_unmap_buffer(bh);
}
bh = next;
} while (bh != head);
}
}
/* reiserfs_get_block does not need to allocate a block only if it has been
done already or non-hole position has been found in the indirect item */
static inline int allocation_needed(int retval, b_blocknr_t allocated,
struct item_head *ih,
__le32 * item, int pos_in_item)
{
if (allocated)
return 0;
if (retval == POSITION_FOUND && is_indirect_le_ih(ih) &&
get_block_num(item, pos_in_item))
return 0;
return 1;
}
static inline int indirect_item_found(int retval, struct item_head *ih)
{
return (retval == POSITION_FOUND) && is_indirect_le_ih(ih);
}
static inline void set_block_dev_mapped(struct buffer_head *bh,
b_blocknr_t block, struct inode *inode)
{
map_bh(bh, inode->i_sb, block);
}
//
// files which were created in the earlier version can not be longer,
// than 2 gb
//
static int file_capable(struct inode *inode, sector_t block)
{
if (get_inode_item_key_version(inode) != KEY_FORMAT_3_5 || // it is new file.
block < (1 << (31 - inode->i_sb->s_blocksize_bits))) // old file, but 'block' is inside of 2gb
return 1;
return 0;
}
static int restart_transaction(struct reiserfs_transaction_handle *th,
struct inode *inode, struct treepath *path)
{
struct super_block *s = th->t_super;
int len = th->t_blocks_allocated;
int err;
BUG_ON(!th->t_trans_id);
BUG_ON(!th->t_refcount);
pathrelse(path);
/* we cannot restart while nested */
if (th->t_refcount > 1) {
return 0;
}
reiserfs_update_sd(th, inode);
err = journal_end(th, s, len);
if (!err) {
err = journal_begin(th, s, JOURNAL_PER_BALANCE_CNT * 6);
if (!err)
reiserfs_update_inode_transaction(inode);
}
return err;
}
// it is called by get_block when create == 0. Returns block number
// for 'block'-th logical block of file. When it hits direct item it
// returns 0 (being called from bmap) or read direct item into piece
// of page (bh_result)
// Please improve the english/clarity in the comment above, as it is
// hard to understand.
static int _get_block_create_0(struct inode *inode, sector_t block,
struct buffer_head *bh_result, int args)
{
INITIALIZE_PATH(path);
struct cpu_key key;
struct buffer_head *bh;
struct item_head *ih, tmp_ih;
b_blocknr_t blocknr;
char *p = NULL;
int chars;
int ret;
int result;
int done = 0;
unsigned long offset;
// prepare the key to look for the 'block'-th block of file
make_cpu_key(&key, inode,
(loff_t) block * inode->i_sb->s_blocksize + 1, TYPE_ANY,
3);
result = search_for_position_by_key(inode->i_sb, &key, &path);
if (result != POSITION_FOUND) {
pathrelse(&path);
if (p)
kunmap(bh_result->b_page);
if (result == IO_ERROR)
return -EIO;
// We do not return -ENOENT if there is a hole but page is uptodate, because it means
// That there is some MMAPED data associated with it that is yet to be written to disk.
if ((args & GET_BLOCK_NO_HOLE)
&& !PageUptodate(bh_result->b_page)) {
return -ENOENT;
}
return 0;
}
//
bh = get_last_bh(&path);
ih = get_ih(&path);
if (is_indirect_le_ih(ih)) {
__le32 *ind_item = (__le32 *) B_I_PITEM(bh, ih);
/* FIXME: here we could cache indirect item or part of it in
the inode to avoid search_by_key in case of subsequent
access to file */
blocknr = get_block_num(ind_item, path.pos_in_item);
ret = 0;
if (blocknr) {
map_bh(bh_result, inode->i_sb, blocknr);
if (path.pos_in_item ==
((ih_item_len(ih) / UNFM_P_SIZE) - 1)) {
set_buffer_boundary(bh_result);
}
} else
// We do not return -ENOENT if there is a hole but page is uptodate, because it means
// That there is some MMAPED data associated with it that is yet to be written to disk.
if ((args & GET_BLOCK_NO_HOLE)
&& !PageUptodate(bh_result->b_page)) {
ret = -ENOENT;
}
pathrelse(&path);
if (p)
kunmap(bh_result->b_page);
return ret;
}
// requested data are in direct item(s)
if (!(args & GET_BLOCK_READ_DIRECT)) {
// we are called by bmap. FIXME: we can not map block of file
// when it is stored in direct item(s)
pathrelse(&path);
if (p)
kunmap(bh_result->b_page);
return -ENOENT;
}
/* if we've got a direct item, and the buffer or page was uptodate,
** we don't want to pull data off disk again. skip to the
** end, where we map the buffer and return
*/
if (buffer_uptodate(bh_result)) {
goto finished;
} else
/*
** grab_tail_page can trigger calls to reiserfs_get_block on up to date
** pages without any buffers. If the page is up to date, we don't want
** read old data off disk. Set the up to date bit on the buffer instead
** and jump to the end
*/
if (!bh_result->b_page || PageUptodate(bh_result->b_page)) {
set_buffer_uptodate(bh_result);
goto finished;
}
// read file tail into part of page
offset = (cpu_key_k_offset(&key) - 1) & (PAGE_CACHE_SIZE - 1);
copy_item_head(&tmp_ih, ih);
/* we only want to kmap if we are reading the tail into the page.
** this is not the common case, so we don't kmap until we are
** sure we need to. But, this means the item might move if
** kmap schedules
*/
if (!p)
p = (char *)kmap(bh_result->b_page);
p += offset;
memset(p, 0, inode->i_sb->s_blocksize);
do {
if (!is_direct_le_ih(ih)) {
BUG();
}
/* make sure we don't read more bytes than actually exist in
** the file. This can happen in odd cases where i_size isn't
** correct, and when direct item padding results in a few
** extra bytes at the end of the direct item
*/
if ((le_ih_k_offset(ih) + path.pos_in_item) > inode->i_size)
break;
if ((le_ih_k_offset(ih) - 1 + ih_item_len(ih)) > inode->i_size) {
chars =
inode->i_size - (le_ih_k_offset(ih) - 1) -
path.pos_in_item;
done = 1;
} else {
chars = ih_item_len(ih) - path.pos_in_item;
}
memcpy(p, B_I_PITEM(bh, ih) + path.pos_in_item, chars);
if (done)
break;
p += chars;
if (PATH_LAST_POSITION(&path) != (B_NR_ITEMS(bh) - 1))
// we done, if read direct item is not the last item of
// node FIXME: we could try to check right delimiting key
// to see whether direct item continues in the right
// neighbor or rely on i_size
break;
// update key to look for the next piece
set_cpu_key_k_offset(&key, cpu_key_k_offset(&key) + chars);
result = search_for_position_by_key(inode->i_sb, &key, &path);
if (result != POSITION_FOUND)
// i/o error most likely
break;
bh = get_last_bh(&path);
ih = get_ih(&path);
} while (1);
flush_dcache_page(bh_result->b_page);
kunmap(bh_result->b_page);
finished:
pathrelse(&path);
if (result == IO_ERROR)
return -EIO;
/* this buffer has valid data, but isn't valid for io. mapping it to
* block #0 tells the rest of reiserfs it just has a tail in it
*/
map_bh(bh_result, inode->i_sb, 0);
set_buffer_uptodate(bh_result);
return 0;
}
// this is called to create file map. So, _get_block_create_0 will not
// read direct item
static int reiserfs_bmap(struct inode *inode, sector_t block,
struct buffer_head *bh_result, int create)
{
if (!file_capable(inode, block))
return -EFBIG;
reiserfs_write_lock(inode->i_sb);
/* do not read the direct item */
_get_block_create_0(inode, block, bh_result, 0);
reiserfs_write_unlock(inode->i_sb);
return 0;
}
/* special version of get_block that is only used by grab_tail_page right
** now. It is sent to __block_write_begin, and when you try to get a
** block past the end of the file (or a block from a hole) it returns
** -ENOENT instead of a valid buffer. __block_write_begin expects to
** be able to do i/o on the buffers returned, unless an error value
** is also returned.
**
** So, this allows __block_write_begin to be used for reading a single block
** in a page. Where it does not produce a valid page for holes, or past the
** end of the file. This turns out to be exactly what we need for reading
** tails for conversion.
**
** The point of the wrapper is forcing a certain value for create, even
** though the VFS layer is calling this function with create==1. If you
** don't want to send create == GET_BLOCK_NO_HOLE to reiserfs_get_block,
** don't use this function.
*/
static int reiserfs_get_block_create_0(struct inode *inode, sector_t block,
struct buffer_head *bh_result,
int create)
{
return reiserfs_get_block(inode, block, bh_result, GET_BLOCK_NO_HOLE);
}
/* This is special helper for reiserfs_get_block in case we are executing
direct_IO request. */
static int reiserfs_get_blocks_direct_io(struct inode *inode,
sector_t iblock,
struct buffer_head *bh_result,
int create)
{
int ret;
bh_result->b_page = NULL;
/* We set the b_size before reiserfs_get_block call since it is
referenced in convert_tail_for_hole() that may be called from
reiserfs_get_block() */
bh_result->b_size = (1 << inode->i_blkbits);
ret = reiserfs_get_block(inode, iblock, bh_result,
create | GET_BLOCK_NO_DANGLE);
if (ret)
goto out;
/* don't allow direct io onto tail pages */
if (buffer_mapped(bh_result) && bh_result->b_blocknr == 0) {
/* make sure future calls to the direct io funcs for this offset
** in the file fail by unmapping the buffer
*/
clear_buffer_mapped(bh_result);
ret = -EINVAL;
}
/* Possible unpacked tail. Flush the data before pages have
disappeared */
if (REISERFS_I(inode)->i_flags & i_pack_on_close_mask) {
int err;
reiserfs_write_lock(inode->i_sb);
err = reiserfs_commit_for_inode(inode);
REISERFS_I(inode)->i_flags &= ~i_pack_on_close_mask;
reiserfs_write_unlock(inode->i_sb);
if (err < 0)
ret = err;
}
out:
return ret;
}
/*
** helper function for when reiserfs_get_block is called for a hole
** but the file tail is still in a direct item
** bh_result is the buffer head for the hole
** tail_offset is the offset of the start of the tail in the file
**
** This calls prepare_write, which will start a new transaction
** you should not be in a transaction, or have any paths held when you
** call this.
*/
static int convert_tail_for_hole(struct inode *inode,
struct buffer_head *bh_result,
loff_t tail_offset)
{
unsigned long index;
unsigned long tail_end;
unsigned long tail_start;
struct page *tail_page;
struct page *hole_page = bh_result->b_page;
int retval = 0;
if ((tail_offset & (bh_result->b_size - 1)) != 1)
return -EIO;
/* always try to read until the end of the block */
tail_start = tail_offset & (PAGE_CACHE_SIZE - 1);
tail_end = (tail_start | (bh_result->b_size - 1)) + 1;
index = tail_offset >> PAGE_CACHE_SHIFT;
/* hole_page can be zero in case of direct_io, we are sure
that we cannot get here if we write with O_DIRECT into
tail page */
if (!hole_page || index != hole_page->index) {
tail_page = grab_cache_page(inode->i_mapping, index);
retval = -ENOMEM;
if (!tail_page) {
goto out;
}
} else {
tail_page = hole_page;
}
/* we don't have to make sure the conversion did not happen while
** we were locking the page because anyone that could convert
** must first take i_mutex.
**
** We must fix the tail page for writing because it might have buffers
** that are mapped, but have a block number of 0. This indicates tail
** data that has been read directly into the page, and
** __block_write_begin won't trigger a get_block in this case.
*/
fix_tail_page_for_writing(tail_page);
retval = __reiserfs_write_begin(tail_page, tail_start,
tail_end - tail_start);
if (retval)
goto unlock;
/* tail conversion might change the data in the page */
flush_dcache_page(tail_page);
retval = reiserfs_commit_write(NULL, tail_page, tail_start, tail_end);
unlock:
if (tail_page != hole_page) {
unlock_page(tail_page);
page_cache_release(tail_page);
}
out:
return retval;
}
static inline int _allocate_block(struct reiserfs_transaction_handle *th,
sector_t block,
struct inode *inode,
b_blocknr_t * allocated_block_nr,
struct treepath *path, int flags)
{
BUG_ON(!th->t_trans_id);
#ifdef REISERFS_PREALLOCATE
if (!(flags & GET_BLOCK_NO_IMUX)) {
return reiserfs_new_unf_blocknrs2(th, inode, allocated_block_nr,
path, block);
}
#endif
return reiserfs_new_unf_blocknrs(th, inode, allocated_block_nr, path,
block);
}
int reiserfs_get_block(struct inode *inode, sector_t block,
struct buffer_head *bh_result, int create)
{
int repeat, retval = 0;
b_blocknr_t allocated_block_nr = 0; // b_blocknr_t is (unsigned) 32 bit int
INITIALIZE_PATH(path);
int pos_in_item;
struct cpu_key key;
struct buffer_head *bh, *unbh = NULL;
struct item_head *ih, tmp_ih;
__le32 *item;
int done;
int fs_gen;
int lock_depth;
struct reiserfs_transaction_handle *th = NULL;
/* space reserved in transaction batch:
. 3 balancings in direct->indirect conversion
. 1 block involved into reiserfs_update_sd()
XXX in practically impossible worst case direct2indirect()
can incur (much) more than 3 balancings.
quota update for user, group */
int jbegin_count =
JOURNAL_PER_BALANCE_CNT * 3 + 1 +
2 * REISERFS_QUOTA_TRANS_BLOCKS(inode->i_sb);
int version;
int dangle = 1;
loff_t new_offset =
(((loff_t) block) << inode->i_sb->s_blocksize_bits) + 1;
lock_depth = reiserfs_write_lock_once(inode->i_sb);
version = get_inode_item_key_version(inode);
if (!file_capable(inode, block)) {
reiserfs_write_unlock_once(inode->i_sb, lock_depth);
return -EFBIG;
}
/* if !create, we aren't changing the FS, so we don't need to
** log anything, so we don't need to start a transaction
*/
if (!(create & GET_BLOCK_CREATE)) {
int ret;
/* find number of block-th logical block of the file */
ret = _get_block_create_0(inode, block, bh_result,
create | GET_BLOCK_READ_DIRECT);
reiserfs_write_unlock_once(inode->i_sb, lock_depth);
return ret;
}
/*
* if we're already in a transaction, make sure to close
* any new transactions we start in this func
*/
if ((create & GET_BLOCK_NO_DANGLE) ||
reiserfs_transaction_running(inode->i_sb))
dangle = 0;
/* If file is of such a size, that it might have a tail and tails are enabled
** we should mark it as possibly needing tail packing on close
*/
if ((have_large_tails(inode->i_sb)
&& inode->i_size < i_block_size(inode) * 4)
|| (have_small_tails(inode->i_sb)
&& inode->i_size < i_block_size(inode)))
REISERFS_I(inode)->i_flags |= i_pack_on_close_mask;
/* set the key of the first byte in the 'block'-th block of file */
make_cpu_key(&key, inode, new_offset, TYPE_ANY, 3 /*key length */ );
if ((new_offset + inode->i_sb->s_blocksize - 1) > inode->i_size) {
start_trans:
th = reiserfs_persistent_transaction(inode->i_sb, jbegin_count);
if (!th) {
retval = -ENOMEM;
goto failure;
}
reiserfs_update_inode_transaction(inode);
}
research:
retval = search_for_position_by_key(inode->i_sb, &key, &path);
if (retval == IO_ERROR) {
retval = -EIO;
goto failure;
}
bh = get_last_bh(&path);
ih = get_ih(&path);
item = get_item(&path);
pos_in_item = path.pos_in_item;
fs_gen = get_generation(inode->i_sb);
copy_item_head(&tmp_ih, ih);
if (allocation_needed
(retval, allocated_block_nr, ih, item, pos_in_item)) {
/* we have to allocate block for the unformatted node */
if (!th) {
pathrelse(&path);
goto start_trans;
}
repeat =
_allocate_block(th, block, inode, &allocated_block_nr,
&path, create);
if (repeat == NO_DISK_SPACE || repeat == QUOTA_EXCEEDED) {
/* restart the transaction to give the journal a chance to free
** some blocks. releases the path, so we have to go back to
** research if we succeed on the second try
*/
SB_JOURNAL(inode->i_sb)->j_next_async_flush = 1;
retval = restart_transaction(th, inode, &path);
if (retval)
goto failure;
repeat =
_allocate_block(th, block, inode,
&allocated_block_nr, NULL, create);
if (repeat != NO_DISK_SPACE && repeat != QUOTA_EXCEEDED) {
goto research;
}
if (repeat == QUOTA_EXCEEDED)
retval = -EDQUOT;
else
retval = -ENOSPC;
goto failure;
}
if (fs_changed(fs_gen, inode->i_sb)
&& item_moved(&tmp_ih, &path)) {
goto research;
}
}
if (indirect_item_found(retval, ih)) {
b_blocknr_t unfm_ptr;
/* 'block'-th block is in the file already (there is
corresponding cell in some indirect item). But it may be
zero unformatted node pointer (hole) */
unfm_ptr = get_block_num(item, pos_in_item);
if (unfm_ptr == 0) {
/* use allocated block to plug the hole */
reiserfs_prepare_for_journal(inode->i_sb, bh, 1);
if (fs_changed(fs_gen, inode->i_sb)
&& item_moved(&tmp_ih, &path)) {
reiserfs_restore_prepared_buffer(inode->i_sb,
bh);
goto research;
}
set_buffer_new(bh_result);
if (buffer_dirty(bh_result)
&& reiserfs_data_ordered(inode->i_sb))
reiserfs_add_ordered_list(inode, bh_result);
put_block_num(item, pos_in_item, allocated_block_nr);
unfm_ptr = allocated_block_nr;
journal_mark_dirty(th, inode->i_sb, bh);
reiserfs_update_sd(th, inode);
}
set_block_dev_mapped(bh_result, unfm_ptr, inode);
pathrelse(&path);
retval = 0;
if (!dangle && th)
retval = reiserfs_end_persistent_transaction(th);
reiserfs_write_unlock_once(inode->i_sb, lock_depth);
/* the item was found, so new blocks were not added to the file
** there is no need to make sure the inode is updated with this
** transaction
*/
return retval;
}
if (!th) {
pathrelse(&path);
goto start_trans;
}
/* desired position is not found or is in the direct item. We have
to append file with holes up to 'block'-th block converting
direct items to indirect one if necessary */
done = 0;
do {
if (is_statdata_le_ih(ih)) {
__le32 unp = 0;
struct cpu_key tmp_key;
/* indirect item has to be inserted */
make_le_item_head(&tmp_ih, &key, version, 1,
TYPE_INDIRECT, UNFM_P_SIZE,
0 /* free_space */ );
if (cpu_key_k_offset(&key) == 1) {
/* we are going to add 'block'-th block to the file. Use
allocated block for that */
unp = cpu_to_le32(allocated_block_nr);
set_block_dev_mapped(bh_result,
allocated_block_nr, inode);
set_buffer_new(bh_result);
done = 1;
}
tmp_key = key; // ;)
set_cpu_key_k_offset(&tmp_key, 1);
PATH_LAST_POSITION(&path)++;
retval =
reiserfs_insert_item(th, &path, &tmp_key, &tmp_ih,
inode, (char *)&unp);
if (retval) {
reiserfs_free_block(th, inode,
allocated_block_nr, 1);
goto failure; // retval == -ENOSPC, -EDQUOT or -EIO or -EEXIST
}
//mark_tail_converted (inode);
} else if (is_direct_le_ih(ih)) {
/* direct item has to be converted */
loff_t tail_offset;
tail_offset =
((le_ih_k_offset(ih) -
1) & ~(inode->i_sb->s_blocksize - 1)) + 1;
if (tail_offset == cpu_key_k_offset(&key)) {
/* direct item we just found fits into block we have
to map. Convert it into unformatted node: use
bh_result for the conversion */
set_block_dev_mapped(bh_result,
allocated_block_nr, inode);
unbh = bh_result;
done = 1;
} else {
/* we have to padd file tail stored in direct item(s)
up to block size and convert it to unformatted
node. FIXME: this should also get into page cache */
pathrelse(&path);
/*
* ugly, but we can only end the transaction if
* we aren't nested
*/
BUG_ON(!th->t_refcount);
if (th->t_refcount == 1) {
retval =
reiserfs_end_persistent_transaction
(th);
th = NULL;
if (retval)
goto failure;
}
retval =
convert_tail_for_hole(inode, bh_result,
tail_offset);
if (retval) {
if (retval != -ENOSPC)
reiserfs_error(inode->i_sb,
"clm-6004",
"convert tail failed "
"inode %lu, error %d",
inode->i_ino,
retval);
if (allocated_block_nr) {
/* the bitmap, the super, and the stat data == 3 */
if (!th)
th = reiserfs_persistent_transaction(inode->i_sb, 3);
if (th)
reiserfs_free_block(th,
inode,
allocated_block_nr,
1);
}
goto failure;
}
goto research;
}
retval =
direct2indirect(th, inode, &path, unbh,
tail_offset);
if (retval) {
reiserfs_unmap_buffer(unbh);
reiserfs_free_block(th, inode,
allocated_block_nr, 1);
goto failure;
}
/* it is important the set_buffer_uptodate is done after
** the direct2indirect. The buffer might contain valid
** data newer than the data on disk (read by readpage, changed,
** and then sent here by writepage). direct2indirect needs
** to know if unbh was already up to date, so it can decide
** if the data in unbh needs to be replaced with data from
** the disk
*/
set_buffer_uptodate(unbh);
/* unbh->b_page == NULL in case of DIRECT_IO request, this means
buffer will disappear shortly, so it should not be added to
*/
if (unbh->b_page) {
/* we've converted the tail, so we must
** flush unbh before the transaction commits
*/
reiserfs_add_tail_list(inode, unbh);
/* mark it dirty now to prevent commit_write from adding
** this buffer to the inode's dirty buffer list
*/
/*
* AKPM: changed __mark_buffer_dirty to mark_buffer_dirty().
* It's still atomic, but it sets the page dirty too,
* which makes it eligible for writeback at any time by the
* VM (which was also the case with __mark_buffer_dirty())
*/
mark_buffer_dirty(unbh);
}
} else {
/* append indirect item with holes if needed, when appending
pointer to 'block'-th block use block, which is already
allocated */
struct cpu_key tmp_key;
unp_t unf_single = 0; // We use this in case we need to allocate only
// one block which is a fastpath
unp_t *un;
__u64 max_to_insert =
MAX_ITEM_LEN(inode->i_sb->s_blocksize) /
UNFM_P_SIZE;
__u64 blocks_needed;
RFALSE(pos_in_item != ih_item_len(ih) / UNFM_P_SIZE,
"vs-804: invalid position for append");
/* indirect item has to be appended, set up key of that position */
make_cpu_key(&tmp_key, inode,
le_key_k_offset(version,
&(ih->ih_key)) +
op_bytes_number(ih,
inode->i_sb->s_blocksize),
//pos_in_item * inode->i_sb->s_blocksize,
TYPE_INDIRECT, 3); // key type is unimportant
RFALSE(cpu_key_k_offset(&tmp_key) > cpu_key_k_offset(&key),
"green-805: invalid offset");
blocks_needed =
1 +
((cpu_key_k_offset(&key) -
cpu_key_k_offset(&tmp_key)) >> inode->i_sb->
s_blocksize_bits);
if (blocks_needed == 1) {
un = &unf_single;
} else {
un = kzalloc(min(blocks_needed, max_to_insert) * UNFM_P_SIZE, GFP_NOFS);
if (!un) {
un = &unf_single;
blocks_needed = 1;
max_to_insert = 0;
}
}
if (blocks_needed <= max_to_insert) {
/* we are going to add target block to the file. Use allocated
block for that */
un[blocks_needed - 1] =
cpu_to_le32(allocated_block_nr);
set_block_dev_mapped(bh_result,
allocated_block_nr, inode);
set_buffer_new(bh_result);
done = 1;
} else {
/* paste hole to the indirect item */
/* If kmalloc failed, max_to_insert becomes zero and it means we
only have space for one block */
blocks_needed =
max_to_insert ? max_to_insert : 1;
}
retval =
reiserfs_paste_into_item(th, &path, &tmp_key, inode,
(char *)un,
UNFM_P_SIZE *
blocks_needed);
if (blocks_needed != 1)
kfree(un);
if (retval) {
reiserfs_free_block(th, inode,
allocated_block_nr, 1);
goto failure;
}
if (!done) {
/* We need to mark new file size in case this function will be
interrupted/aborted later on. And we may do this only for
holes. */
inode->i_size +=
inode->i_sb->s_blocksize * blocks_needed;
}
}
if (done == 1)
break;
/* this loop could log more blocks than we had originally asked
** for. So, we have to allow the transaction to end if it is
** too big or too full. Update the inode so things are
** consistent if we crash before the function returns
**
** release the path so that anybody waiting on the path before
** ending their transaction will be able to continue.
*/
if (journal_transaction_should_end(th, th->t_blocks_allocated)) {
retval = restart_transaction(th, inode, &path);
if (retval)
goto failure;
}
/*
* inserting indirect pointers for a hole can take a
* long time. reschedule if needed and also release the write
* lock for others.
*/
if (need_resched()) {
reiserfs_write_unlock_once(inode->i_sb, lock_depth);
schedule();
lock_depth = reiserfs_write_lock_once(inode->i_sb);
}
retval = search_for_position_by_key(inode->i_sb, &key, &path);
if (retval == IO_ERROR) {
retval = -EIO;
goto failure;
}
if (retval == POSITION_FOUND) {
reiserfs_warning(inode->i_sb, "vs-825",
"%K should not be found", &key);
retval = -EEXIST;
if (allocated_block_nr)
reiserfs_free_block(th, inode,
allocated_block_nr, 1);
pathrelse(&path);
goto failure;
}
bh = get_last_bh(&path);
ih = get_ih(&path);
item = get_item(&path);
pos_in_item = path.pos_in_item;
} while (1);
retval = 0;
failure:
if (th && (!dangle || (retval && !th->t_trans_id))) {
int err;
if (th->t_trans_id)
reiserfs_update_sd(th, inode);
err = reiserfs_end_persistent_transaction(th);
if (err)
retval = err;
}
reiserfs_write_unlock_once(inode->i_sb, lock_depth);
reiserfs_check_path(&path);
return retval;
}
static int
reiserfs_readpages(struct file *file, struct address_space *mapping,
struct list_head *pages, unsigned nr_pages)
{
return mpage_readpages(mapping, pages, nr_pages, reiserfs_get_block);
}
/* Compute real number of used bytes by file
* Following three functions can go away when we'll have enough space in stat item
*/
static int real_space_diff(struct inode *inode, int sd_size)
{
int bytes;
loff_t blocksize = inode->i_sb->s_blocksize;
if (S_ISLNK(inode->i_mode) || S_ISDIR(inode->i_mode))
return sd_size;
/* End of file is also in full block with indirect reference, so round
** up to the next block.
**
** there is just no way to know if the tail is actually packed
** on the file, so we have to assume it isn't. When we pack the
** tail, we add 4 bytes to pretend there really is an unformatted
** node pointer
*/
bytes =
((inode->i_size +
(blocksize - 1)) >> inode->i_sb->s_blocksize_bits) * UNFM_P_SIZE +
sd_size;
return bytes;
}
static inline loff_t to_real_used_space(struct inode *inode, ulong blocks,
int sd_size)
{
if (S_ISLNK(inode->i_mode) || S_ISDIR(inode->i_mode)) {
return inode->i_size +
(loff_t) (real_space_diff(inode, sd_size));
}
return ((loff_t) real_space_diff(inode, sd_size)) +
(((loff_t) blocks) << 9);
}
/* Compute number of blocks used by file in ReiserFS counting */
static inline ulong to_fake_used_blocks(struct inode *inode, int sd_size)
{
loff_t bytes = inode_get_bytes(inode);
loff_t real_space = real_space_diff(inode, sd_size);
/* keeps fsck and non-quota versions of reiserfs happy */
if (S_ISLNK(inode->i_mode) || S_ISDIR(inode->i_mode)) {
bytes += (loff_t) 511;
}
/* files from before the quota patch might i_blocks such that
** bytes < real_space. Deal with that here to prevent it from
** going negative.
*/
if (bytes < real_space)
return 0;
return (bytes - real_space) >> 9;
}
//
// BAD: new directories have stat data of new type and all other items
// of old type. Version stored in the inode says about body items, so
// in update_stat_data we can not rely on inode, but have to check
// item version directly
//
// called by read_locked_inode
static void init_inode(struct inode *inode, struct treepath *path)
{
struct buffer_head *bh;
struct item_head *ih;
__u32 rdev;
//int version = ITEM_VERSION_1;
bh = PATH_PLAST_BUFFER(path);
ih = PATH_PITEM_HEAD(path);
copy_key(INODE_PKEY(inode), &(ih->ih_key));
INIT_LIST_HEAD(&(REISERFS_I(inode)->i_prealloc_list));
REISERFS_I(inode)->i_flags = 0;
REISERFS_I(inode)->i_prealloc_block = 0;
REISERFS_I(inode)->i_prealloc_count = 0;
REISERFS_I(inode)->i_trans_id = 0;
REISERFS_I(inode)->i_jl = NULL;
reiserfs_init_xattr_rwsem(inode);
if (stat_data_v1(ih)) {
struct stat_data_v1 *sd =
(struct stat_data_v1 *)B_I_PITEM(bh, ih);
unsigned long blocks;
set_inode_item_key_version(inode, KEY_FORMAT_3_5);
set_inode_sd_version(inode, STAT_DATA_V1);
inode->i_mode = sd_v1_mode(sd);
inode->i_nlink = sd_v1_nlink(sd);
inode->i_uid = sd_v1_uid(sd);
inode->i_gid = sd_v1_gid(sd);
inode->i_size = sd_v1_size(sd);
inode->i_atime.tv_sec = sd_v1_atime(sd);
inode->i_mtime.tv_sec = sd_v1_mtime(sd);
inode->i_ctime.tv_sec = sd_v1_ctime(sd);
inode->i_atime.tv_nsec = 0;
inode->i_ctime.tv_nsec = 0;
inode->i_mtime.tv_nsec = 0;
inode->i_blocks = sd_v1_blocks(sd);
inode->i_generation = le32_to_cpu(INODE_PKEY(inode)->k_dir_id);
blocks = (inode->i_size + 511) >> 9;
blocks = _ROUND_UP(blocks, inode->i_sb->s_blocksize >> 9);
if (inode->i_blocks > blocks) {
// there was a bug in <=3.5.23 when i_blocks could take negative
// values. Starting from 3.5.17 this value could even be stored in
// stat data. For such files we set i_blocks based on file
// size. Just 2 notes: this can be wrong for sparce files. On-disk value will be
// only updated if file's inode will ever change
inode->i_blocks = blocks;
}
rdev = sd_v1_rdev(sd);
REISERFS_I(inode)->i_first_direct_byte =
sd_v1_first_direct_byte(sd);
/* an early bug in the quota code can give us an odd number for the
** block count. This is incorrect, fix it here.
*/
if (inode->i_blocks & 1) {
inode->i_blocks++;
}
inode_set_bytes(inode,
to_real_used_space(inode, inode->i_blocks,
SD_V1_SIZE));
/* nopack is initially zero for v1 objects. For v2 objects,
nopack is initialised from sd_attrs */
REISERFS_I(inode)->i_flags &= ~i_nopack_mask;
} else {
// new stat data found, but object may have old items
// (directories and symlinks)
struct stat_data *sd = (struct stat_data *)B_I_PITEM(bh, ih);
inode->i_mode = sd_v2_mode(sd);
inode->i_nlink = sd_v2_nlink(sd);
inode->i_uid = sd_v2_uid(sd);
inode->i_size = sd_v2_size(sd);
inode->i_gid = sd_v2_gid(sd);
inode->i_mtime.tv_sec = sd_v2_mtime(sd);
inode->i_atime.tv_sec = sd_v2_atime(sd);
inode->i_ctime.tv_sec = sd_v2_ctime(sd);
inode->i_ctime.tv_nsec = 0;
inode->i_mtime.tv_nsec = 0;
inode->i_atime.tv_nsec = 0;
inode->i_blocks = sd_v2_blocks(sd);
rdev = sd_v2_rdev(sd);
if (S_ISCHR(inode->i_mode) || S_ISBLK(inode->i_mode))
inode->i_generation =
le32_to_cpu(INODE_PKEY(inode)->k_dir_id);
else
inode->i_generation = sd_v2_generation(sd);
if (S_ISDIR(inode->i_mode) || S_ISLNK(inode->i_mode))
set_inode_item_key_version(inode, KEY_FORMAT_3_5);
else
set_inode_item_key_version(inode, KEY_FORMAT_3_6);
REISERFS_I(inode)->i_first_direct_byte = 0;
set_inode_sd_version(inode, STAT_DATA_V2);
inode_set_bytes(inode,
to_real_used_space(inode, inode->i_blocks,
SD_V2_SIZE));
/* read persistent inode attributes from sd and initialise
generic inode flags from them */
REISERFS_I(inode)->i_attrs = sd_v2_attrs(sd);
sd_attrs_to_i_attrs(sd_v2_attrs(sd), inode);
}
pathrelse(path);
if (S_ISREG(inode->i_mode)) {
inode->i_op = &reiserfs_file_inode_operations;
inode->i_fop = &reiserfs_file_operations;
inode->i_mapping->a_ops = &reiserfs_address_space_operations;
} else if (S_ISDIR(inode->i_mode)) {
inode->i_op = &reiserfs_dir_inode_operations;
inode->i_fop = &reiserfs_dir_operations;
} else if (S_ISLNK(inode->i_mode)) {
inode->i_op = &reiserfs_symlink_inode_operations;
inode->i_mapping->a_ops = &reiserfs_address_space_operations;
} else {
inode->i_blocks = 0;
inode->i_op = &reiserfs_special_inode_operations;
init_special_inode(inode, inode->i_mode, new_decode_dev(rdev));
}
}
// update new stat data with inode fields
static void inode2sd(void *sd, struct inode *inode, loff_t size)
{
struct stat_data *sd_v2 = (struct stat_data *)sd;
__u16 flags;
set_sd_v2_mode(sd_v2, inode->i_mode);
set_sd_v2_nlink(sd_v2, inode->i_nlink);
set_sd_v2_uid(sd_v2, inode->i_uid);
set_sd_v2_size(sd_v2, size);
set_sd_v2_gid(sd_v2, inode->i_gid);
set_sd_v2_mtime(sd_v2, inode->i_mtime.tv_sec);
set_sd_v2_atime(sd_v2, inode->i_atime.tv_sec);
set_sd_v2_ctime(sd_v2, inode->i_ctime.tv_sec);
set_sd_v2_blocks(sd_v2, to_fake_used_blocks(inode, SD_V2_SIZE));
if (S_ISCHR(inode->i_mode) || S_ISBLK(inode->i_mode))
set_sd_v2_rdev(sd_v2, new_encode_dev(inode->i_rdev));
else
set_sd_v2_generation(sd_v2, inode->i_generation);
flags = REISERFS_I(inode)->i_attrs;
i_attrs_to_sd_attrs(inode, &flags);
set_sd_v2_attrs(sd_v2, flags);
}
// used to copy inode's fields to old stat data
static void inode2sd_v1(void *sd, struct inode *inode, loff_t size)
{
struct stat_data_v1 *sd_v1 = (struct stat_data_v1 *)sd;
set_sd_v1_mode(sd_v1, inode->i_mode);
set_sd_v1_uid(sd_v1, inode->i_uid);
set_sd_v1_gid(sd_v1, inode->i_gid);
set_sd_v1_nlink(sd_v1, inode->i_nlink);
set_sd_v1_size(sd_v1, size);
set_sd_v1_atime(sd_v1, inode->i_atime.tv_sec);
set_sd_v1_ctime(sd_v1, inode->i_ctime.tv_sec);
set_sd_v1_mtime(sd_v1, inode->i_mtime.tv_sec);
if (S_ISCHR(inode->i_mode) || S_ISBLK(inode->i_mode))
set_sd_v1_rdev(sd_v1, new_encode_dev(inode->i_rdev));
else
set_sd_v1_blocks(sd_v1, to_fake_used_blocks(inode, SD_V1_SIZE));
// Sigh. i_first_direct_byte is back
set_sd_v1_first_direct_byte(sd_v1,
REISERFS_I(inode)->i_first_direct_byte);
}
/* NOTE, you must prepare the buffer head before sending it here,
** and then log it after the call
*/
static void update_stat_data(struct treepath *path, struct inode *inode,
loff_t size)
{
struct buffer_head *bh;
struct item_head *ih;
bh = PATH_PLAST_BUFFER(path);
ih = PATH_PITEM_HEAD(path);
if (!is_statdata_le_ih(ih))
reiserfs_panic(inode->i_sb, "vs-13065", "key %k, found item %h",
INODE_PKEY(inode), ih);
if (stat_data_v1(ih)) {
// path points to old stat data
inode2sd_v1(B_I_PITEM(bh, ih), inode, size);
} else {
inode2sd(B_I_PITEM(bh, ih), inode, size);
}
return;
}
void reiserfs_update_sd_size(struct reiserfs_transaction_handle *th,
struct inode *inode, loff_t size)
{
struct cpu_key key;
INITIALIZE_PATH(path);
struct buffer_head *bh;
int fs_gen;
struct item_head *ih, tmp_ih;
int retval;
BUG_ON(!th->t_trans_id);
make_cpu_key(&key, inode, SD_OFFSET, TYPE_STAT_DATA, 3); //key type is unimportant
for (;;) {
int pos;
/* look for the object's stat data */
retval = search_item(inode->i_sb, &key, &path);
if (retval == IO_ERROR) {
reiserfs_error(inode->i_sb, "vs-13050",
"i/o failure occurred trying to "
"update %K stat data", &key);
return;
}
if (retval == ITEM_NOT_FOUND) {
pos = PATH_LAST_POSITION(&path);
pathrelse(&path);
if (inode->i_nlink == 0) {
/*reiserfs_warning (inode->i_sb, "vs-13050: reiserfs_update_sd: i_nlink == 0, stat data not found"); */
return;
}
reiserfs_warning(inode->i_sb, "vs-13060",
"stat data of object %k (nlink == %d) "
"not found (pos %d)",
INODE_PKEY(inode), inode->i_nlink,
pos);
reiserfs_check_path(&path);
return;
}
/* sigh, prepare_for_journal might schedule. When it schedules the
** FS might change. We have to detect that, and loop back to the
** search if the stat data item has moved
*/
bh = get_last_bh(&path);
ih = get_ih(&path);
copy_item_head(&tmp_ih, ih);
fs_gen = get_generation(inode->i_sb);
reiserfs_prepare_for_journal(inode->i_sb, bh, 1);
if (fs_changed(fs_gen, inode->i_sb)
&& item_moved(&tmp_ih, &path)) {
reiserfs_restore_prepared_buffer(inode->i_sb, bh);
continue; /* Stat_data item has been moved after scheduling. */
}
break;
}
update_stat_data(&path, inode, size);
journal_mark_dirty(th, th->t_super, bh);
pathrelse(&path);
return;
}
/* reiserfs_read_locked_inode is called to read the inode off disk, and it
** does a make_bad_inode when things go wrong. But, we need to make sure
** and clear the key in the private portion of the inode, otherwise a
** corresponding iput might try to delete whatever object the inode last
** represented.
*/
static void reiserfs_make_bad_inode(struct inode *inode)
{
memset(INODE_PKEY(inode), 0, KEY_SIZE);
make_bad_inode(inode);
}
//
// initially this function was derived from minix or ext2's analog and
// evolved as the prototype did
//
int reiserfs_init_locked_inode(struct inode *inode, void *p)
{
struct reiserfs_iget_args *args = (struct reiserfs_iget_args *)p;
inode->i_ino = args->objectid;
INODE_PKEY(inode)->k_dir_id = cpu_to_le32(args->dirid);
return 0;
}
/* looks for stat data in the tree, and fills up the fields of in-core
inode stat data fields */
void reiserfs_read_locked_inode(struct inode *inode,
struct reiserfs_iget_args *args)
{
INITIALIZE_PATH(path_to_sd);
struct cpu_key key;
unsigned long dirino;
int retval;
dirino = args->dirid;
/* set version 1, version 2 could be used too, because stat data
key is the same in both versions */
key.version = KEY_FORMAT_3_5;
key.on_disk_key.k_dir_id = dirino;
key.on_disk_key.k_objectid = inode->i_ino;
key.on_disk_key.k_offset = 0;
key.on_disk_key.k_type = 0;
/* look for the object's stat data */
retval = search_item(inode->i_sb, &key, &path_to_sd);
if (retval == IO_ERROR) {
reiserfs_error(inode->i_sb, "vs-13070",
"i/o failure occurred trying to find "
"stat data of %K", &key);
reiserfs_make_bad_inode(inode);
return;
}
if (retval != ITEM_FOUND) {
/* a stale NFS handle can trigger this without it being an error */
pathrelse(&path_to_sd);
reiserfs_make_bad_inode(inode);
inode->i_nlink = 0;
return;
}
init_inode(inode, &path_to_sd);
/* It is possible that knfsd is trying to access inode of a file
that is being removed from the disk by some other thread. As we
update sd on unlink all that is required is to check for nlink
here. This bug was first found by Sizif when debugging
SquidNG/Butterfly, forgotten, and found again after Philippe
Gramoulle <[email protected]> reproduced it.
More logical fix would require changes in fs/inode.c:iput() to
remove inode from hash-table _after_ fs cleaned disk stuff up and
in iget() to return NULL if I_FREEING inode is found in
hash-table. */
/* Currently there is one place where it's ok to meet inode with
nlink==0: processing of open-unlinked and half-truncated files
during mount (fs/reiserfs/super.c:finish_unfinished()). */
if ((inode->i_nlink == 0) &&
!REISERFS_SB(inode->i_sb)->s_is_unlinked_ok) {
reiserfs_warning(inode->i_sb, "vs-13075",
"dead inode read from disk %K. "
"This is likely to be race with knfsd. Ignore",
&key);
reiserfs_make_bad_inode(inode);
}
reiserfs_check_path(&path_to_sd); /* init inode should be relsing */
}
/**
* reiserfs_find_actor() - "find actor" reiserfs supplies to iget5_locked().
*
* @inode: inode from hash table to check
* @opaque: "cookie" passed to iget5_locked(). This is &reiserfs_iget_args.
*
* This function is called by iget5_locked() to distinguish reiserfs inodes
* having the same inode numbers. Such inodes can only exist due to some
* error condition. One of them should be bad. Inodes with identical
* inode numbers (objectids) are distinguished by parent directory ids.
*
*/
int reiserfs_find_actor(struct inode *inode, void *opaque)
{
struct reiserfs_iget_args *args;
args = opaque;
/* args is already in CPU order */
return (inode->i_ino == args->objectid) &&
(le32_to_cpu(INODE_PKEY(inode)->k_dir_id) == args->dirid);
}
struct inode *reiserfs_iget(struct super_block *s, const struct cpu_key *key)
{
struct inode *inode;
struct reiserfs_iget_args args;
args.objectid = key->on_disk_key.k_objectid;
args.dirid = key->on_disk_key.k_dir_id;
reiserfs_write_unlock(s);
inode = iget5_locked(s, key->on_disk_key.k_objectid,
reiserfs_find_actor, reiserfs_init_locked_inode,
(void *)(&args));
reiserfs_write_lock(s);
if (!inode)
return ERR_PTR(-ENOMEM);
if (inode->i_state & I_NEW) {
reiserfs_read_locked_inode(inode, &args);
unlock_new_inode(inode);
}
if (comp_short_keys(INODE_PKEY(inode), key) || is_bad_inode(inode)) {
/* either due to i/o error or a stale NFS handle */
iput(inode);
inode = NULL;
}
return inode;
}
static struct dentry *reiserfs_get_dentry(struct super_block *sb,
u32 objectid, u32 dir_id, u32 generation)
{
struct cpu_key key;
struct inode *inode;
key.on_disk_key.k_objectid = objectid;
key.on_disk_key.k_dir_id = dir_id;
reiserfs_write_lock(sb);
inode = reiserfs_iget(sb, &key);
if (inode && !IS_ERR(inode) && generation != 0 &&
generation != inode->i_generation) {
iput(inode);
inode = NULL;
}
reiserfs_write_unlock(sb);
return d_obtain_alias(inode);
}
struct dentry *reiserfs_fh_to_dentry(struct super_block *sb, struct fid *fid,
int fh_len, int fh_type)
{
/* fhtype happens to reflect the number of u32s encoded.
* due to a bug in earlier code, fhtype might indicate there
* are more u32s then actually fitted.
* so if fhtype seems to be more than len, reduce fhtype.
* Valid types are:
* 2 - objectid + dir_id - legacy support
* 3 - objectid + dir_id + generation
* 4 - objectid + dir_id + objectid and dirid of parent - legacy
* 5 - objectid + dir_id + generation + objectid and dirid of parent
* 6 - as above plus generation of directory
* 6 does not fit in NFSv2 handles
*/
if (fh_type > fh_len) {
if (fh_type != 6 || fh_len != 5)
reiserfs_warning(sb, "reiserfs-13077",
"nfsd/reiserfs, fhtype=%d, len=%d - odd",
fh_type, fh_len);
fh_type = fh_len;
}
if (fh_len < 2)
return NULL;
return reiserfs_get_dentry(sb, fid->raw[0], fid->raw[1],
(fh_type == 3 || fh_type >= 5) ? fid->raw[2] : 0);
}
struct dentry *reiserfs_fh_to_parent(struct super_block *sb, struct fid *fid,
int fh_len, int fh_type)
{
if (fh_type > fh_len)
fh_type = fh_len;
if (fh_type < 4)
return NULL;
return reiserfs_get_dentry(sb,
(fh_type >= 5) ? fid->raw[3] : fid->raw[2],
(fh_type >= 5) ? fid->raw[4] : fid->raw[3],
(fh_type == 6) ? fid->raw[5] : 0);
}
int reiserfs_encode_fh(struct dentry *dentry, __u32 * data, int *lenp,
int need_parent)
{
struct inode *inode = dentry->d_inode;
int maxlen = *lenp;
if (need_parent && (maxlen < 5)) {
*lenp = 5;
return 255;
} else if (maxlen < 3) {
*lenp = 3;
return 255;
}
data[0] = inode->i_ino;
data[1] = le32_to_cpu(INODE_PKEY(inode)->k_dir_id);
data[2] = inode->i_generation;
*lenp = 3;
/* no room for directory info? return what we've stored so far */
if (maxlen < 5 || !need_parent)
return 3;
spin_lock(&dentry->d_lock);
inode = dentry->d_parent->d_inode;
data[3] = inode->i_ino;
data[4] = le32_to_cpu(INODE_PKEY(inode)->k_dir_id);
*lenp = 5;
if (maxlen >= 6) {
data[5] = inode->i_generation;
*lenp = 6;
}
spin_unlock(&dentry->d_lock);
return *lenp;
}
/* looks for stat data, then copies fields to it, marks the buffer
containing stat data as dirty */
/* reiserfs inodes are never really dirty, since the dirty inode call
** always logs them. This call allows the VFS inode marking routines
** to properly mark inodes for datasync and such, but only actually
** does something when called for a synchronous update.
*/
int reiserfs_write_inode(struct inode *inode, struct writeback_control *wbc)
{
struct reiserfs_transaction_handle th;
int jbegin_count = 1;
if (inode->i_sb->s_flags & MS_RDONLY)
return -EROFS;
/* memory pressure can sometimes initiate write_inode calls with sync == 1,
** these cases are just when the system needs ram, not when the
** inode needs to reach disk for safety, and they can safely be
** ignored because the altered inode has already been logged.
*/
if (wbc->sync_mode == WB_SYNC_ALL && !(current->flags & PF_MEMALLOC)) {
reiserfs_write_lock(inode->i_sb);
if (!journal_begin(&th, inode->i_sb, jbegin_count)) {
reiserfs_update_sd(&th, inode);
journal_end_sync(&th, inode->i_sb, jbegin_count);
}
reiserfs_write_unlock(inode->i_sb);
}
return 0;
}
/* stat data of new object is inserted already, this inserts the item
containing "." and ".." entries */
static int reiserfs_new_directory(struct reiserfs_transaction_handle *th,
struct inode *inode,
struct item_head *ih, struct treepath *path,
struct inode *dir)
{
struct super_block *sb = th->t_super;
char empty_dir[EMPTY_DIR_SIZE];
char *body = empty_dir;
struct cpu_key key;
int retval;
BUG_ON(!th->t_trans_id);
_make_cpu_key(&key, KEY_FORMAT_3_5, le32_to_cpu(ih->ih_key.k_dir_id),
le32_to_cpu(ih->ih_key.k_objectid), DOT_OFFSET,
TYPE_DIRENTRY, 3 /*key length */ );
/* compose item head for new item. Directories consist of items of
old type (ITEM_VERSION_1). Do not set key (second arg is 0), it
is done by reiserfs_new_inode */
if (old_format_only(sb)) {
make_le_item_head(ih, NULL, KEY_FORMAT_3_5, DOT_OFFSET,
TYPE_DIRENTRY, EMPTY_DIR_SIZE_V1, 2);
make_empty_dir_item_v1(body, ih->ih_key.k_dir_id,
ih->ih_key.k_objectid,
INODE_PKEY(dir)->k_dir_id,
INODE_PKEY(dir)->k_objectid);
} else {
make_le_item_head(ih, NULL, KEY_FORMAT_3_5, DOT_OFFSET,
TYPE_DIRENTRY, EMPTY_DIR_SIZE, 2);
make_empty_dir_item(body, ih->ih_key.k_dir_id,
ih->ih_key.k_objectid,
INODE_PKEY(dir)->k_dir_id,
INODE_PKEY(dir)->k_objectid);
}
/* look for place in the tree for new item */
retval = search_item(sb, &key, path);
if (retval == IO_ERROR) {
reiserfs_error(sb, "vs-13080",
"i/o failure occurred creating new directory");
return -EIO;
}
if (retval == ITEM_FOUND) {
pathrelse(path);
reiserfs_warning(sb, "vs-13070",
"object with this key exists (%k)",
&(ih->ih_key));
return -EEXIST;
}
/* insert item, that is empty directory item */
return reiserfs_insert_item(th, path, &key, ih, inode, body);
}
/* stat data of object has been inserted, this inserts the item
containing the body of symlink */
static int reiserfs_new_symlink(struct reiserfs_transaction_handle *th, struct inode *inode, /* Inode of symlink */
struct item_head *ih,
struct treepath *path, const char *symname,
int item_len)
{
struct super_block *sb = th->t_super;
struct cpu_key key;
int retval;
BUG_ON(!th->t_trans_id);
_make_cpu_key(&key, KEY_FORMAT_3_5,
le32_to_cpu(ih->ih_key.k_dir_id),
le32_to_cpu(ih->ih_key.k_objectid),
1, TYPE_DIRECT, 3 /*key length */ );
make_le_item_head(ih, NULL, KEY_FORMAT_3_5, 1, TYPE_DIRECT, item_len,
0 /*free_space */ );
/* look for place in the tree for new item */
retval = search_item(sb, &key, path);
if (retval == IO_ERROR) {
reiserfs_error(sb, "vs-13080",
"i/o failure occurred creating new symlink");
return -EIO;
}
if (retval == ITEM_FOUND) {
pathrelse(path);
reiserfs_warning(sb, "vs-13080",
"object with this key exists (%k)",
&(ih->ih_key));
return -EEXIST;
}
/* insert item, that is body of symlink */
return reiserfs_insert_item(th, path, &key, ih, inode, symname);
}
/* inserts the stat data into the tree, and then calls
reiserfs_new_directory (to insert ".", ".." item if new object is
directory) or reiserfs_new_symlink (to insert symlink body if new
object is symlink) or nothing (if new object is regular file)
NOTE! uid and gid must already be set in the inode. If we return
non-zero due to an error, we have to drop the quota previously allocated
for the fresh inode. This can only be done outside a transaction, so
if we return non-zero, we also end the transaction. */
int reiserfs_new_inode(struct reiserfs_transaction_handle *th,
struct inode *dir, int mode, const char *symname,
/* 0 for regular, EMTRY_DIR_SIZE for dirs,
strlen (symname) for symlinks) */
loff_t i_size, struct dentry *dentry,
struct inode *inode,
struct reiserfs_security_handle *security)
{
struct super_block *sb;
struct reiserfs_iget_args args;
INITIALIZE_PATH(path_to_key);
struct cpu_key key;
struct item_head ih;
struct stat_data sd;
int retval;
int err;
BUG_ON(!th->t_trans_id);
reiserfs_write_unlock(inode->i_sb);
err = dquot_alloc_inode(inode);
reiserfs_write_lock(inode->i_sb);
if (err)
goto out_end_trans;
if (!dir->i_nlink) {
err = -EPERM;
goto out_bad_inode;
}
sb = dir->i_sb;
/* item head of new item */
ih.ih_key.k_dir_id = reiserfs_choose_packing(dir);
ih.ih_key.k_objectid = cpu_to_le32(reiserfs_get_unused_objectid(th));
if (!ih.ih_key.k_objectid) {
err = -ENOMEM;
goto out_bad_inode;
}
args.objectid = inode->i_ino = le32_to_cpu(ih.ih_key.k_objectid);
if (old_format_only(sb))
make_le_item_head(&ih, NULL, KEY_FORMAT_3_5, SD_OFFSET,
TYPE_STAT_DATA, SD_V1_SIZE, MAX_US_INT);
else
make_le_item_head(&ih, NULL, KEY_FORMAT_3_6, SD_OFFSET,
TYPE_STAT_DATA, SD_SIZE, MAX_US_INT);
memcpy(INODE_PKEY(inode), &(ih.ih_key), KEY_SIZE);
args.dirid = le32_to_cpu(ih.ih_key.k_dir_id);
if (insert_inode_locked4(inode, args.objectid,
reiserfs_find_actor, &args) < 0) {
err = -EINVAL;
goto out_bad_inode;
}
if (old_format_only(sb))
/* not a perfect generation count, as object ids can be reused, but
** this is as good as reiserfs can do right now.
** note that the private part of inode isn't filled in yet, we have
** to use the directory.
*/
inode->i_generation = le32_to_cpu(INODE_PKEY(dir)->k_objectid);
else
#if defined( USE_INODE_GENERATION_COUNTER )
inode->i_generation =
le32_to_cpu(REISERFS_SB(sb)->s_rs->s_inode_generation);
#else
inode->i_generation = ++event;
#endif
/* fill stat data */
inode->i_nlink = (S_ISDIR(mode) ? 2 : 1);
/* uid and gid must already be set by the caller for quota init */
/* symlink cannot be immutable or append only, right? */
if (S_ISLNK(inode->i_mode))
inode->i_flags &= ~(S_IMMUTABLE | S_APPEND);
inode->i_mtime = inode->i_atime = inode->i_ctime = CURRENT_TIME_SEC;
inode->i_size = i_size;
inode->i_blocks = 0;
inode->i_bytes = 0;
REISERFS_I(inode)->i_first_direct_byte = S_ISLNK(mode) ? 1 :
U32_MAX /*NO_BYTES_IN_DIRECT_ITEM */ ;
INIT_LIST_HEAD(&(REISERFS_I(inode)->i_prealloc_list));
REISERFS_I(inode)->i_flags = 0;
REISERFS_I(inode)->i_prealloc_block = 0;
REISERFS_I(inode)->i_prealloc_count = 0;
REISERFS_I(inode)->i_trans_id = 0;
REISERFS_I(inode)->i_jl = NULL;
REISERFS_I(inode)->i_attrs =
REISERFS_I(dir)->i_attrs & REISERFS_INHERIT_MASK;
sd_attrs_to_i_attrs(REISERFS_I(inode)->i_attrs, inode);
reiserfs_init_xattr_rwsem(inode);
/* key to search for correct place for new stat data */
_make_cpu_key(&key, KEY_FORMAT_3_6, le32_to_cpu(ih.ih_key.k_dir_id),
le32_to_cpu(ih.ih_key.k_objectid), SD_OFFSET,
TYPE_STAT_DATA, 3 /*key length */ );
/* find proper place for inserting of stat data */
retval = search_item(sb, &key, &path_to_key);
if (retval == IO_ERROR) {
err = -EIO;
goto out_bad_inode;
}
if (retval == ITEM_FOUND) {
pathrelse(&path_to_key);
err = -EEXIST;
goto out_bad_inode;
}
if (old_format_only(sb)) {
if (inode->i_uid & ~0xffff || inode->i_gid & ~0xffff) {
pathrelse(&path_to_key);
/* i_uid or i_gid is too big to be stored in stat data v3.5 */
err = -EINVAL;
goto out_bad_inode;
}
inode2sd_v1(&sd, inode, inode->i_size);
} else {
inode2sd(&sd, inode, inode->i_size);
}
// store in in-core inode the key of stat data and version all
// object items will have (directory items will have old offset
// format, other new objects will consist of new items)
if (old_format_only(sb) || S_ISDIR(mode) || S_ISLNK(mode))
set_inode_item_key_version(inode, KEY_FORMAT_3_5);
else
set_inode_item_key_version(inode, KEY_FORMAT_3_6);
if (old_format_only(sb))
set_inode_sd_version(inode, STAT_DATA_V1);
else
set_inode_sd_version(inode, STAT_DATA_V2);
/* insert the stat data into the tree */
#ifdef DISPLACE_NEW_PACKING_LOCALITIES
if (REISERFS_I(dir)->new_packing_locality)
th->displace_new_blocks = 1;
#endif
retval =
reiserfs_insert_item(th, &path_to_key, &key, &ih, inode,
(char *)(&sd));
if (retval) {
err = retval;
reiserfs_check_path(&path_to_key);
goto out_bad_inode;
}
#ifdef DISPLACE_NEW_PACKING_LOCALITIES
if (!th->displace_new_blocks)
REISERFS_I(dir)->new_packing_locality = 0;
#endif
if (S_ISDIR(mode)) {
/* insert item with "." and ".." */
retval =
reiserfs_new_directory(th, inode, &ih, &path_to_key, dir);
}
if (S_ISLNK(mode)) {
/* insert body of symlink */
if (!old_format_only(sb))
i_size = ROUND_UP(i_size);
retval =
reiserfs_new_symlink(th, inode, &ih, &path_to_key, symname,
i_size);
}
if (retval) {
err = retval;
reiserfs_check_path(&path_to_key);
journal_end(th, th->t_super, th->t_blocks_allocated);
goto out_inserted_sd;
}
if (reiserfs_posixacl(inode->i_sb)) {
retval = reiserfs_inherit_default_acl(th, dir, dentry, inode);
if (retval) {
err = retval;
reiserfs_check_path(&path_to_key);
journal_end(th, th->t_super, th->t_blocks_allocated);
goto out_inserted_sd;
}
} else if (inode->i_sb->s_flags & MS_POSIXACL) {
reiserfs_warning(inode->i_sb, "jdm-13090",
"ACLs aren't enabled in the fs, "
"but vfs thinks they are!");
} else if (IS_PRIVATE(dir))
inode->i_flags |= S_PRIVATE;
if (security->name) {
retval = reiserfs_security_write(th, inode, security);
if (retval) {
err = retval;
reiserfs_check_path(&path_to_key);
retval = journal_end(th, th->t_super,
th->t_blocks_allocated);
if (retval)
err = retval;
goto out_inserted_sd;
}
}
reiserfs_update_sd(th, inode);
reiserfs_check_path(&path_to_key);
return 0;
/* it looks like you can easily compress these two goto targets into
* one. Keeping it like this doesn't actually hurt anything, and they
* are place holders for what the quota code actually needs.
*/
out_bad_inode:
/* Invalidate the object, nothing was inserted yet */
INODE_PKEY(inode)->k_objectid = 0;
/* Quota change must be inside a transaction for journaling */
dquot_free_inode(inode);
out_end_trans:
journal_end(th, th->t_super, th->t_blocks_allocated);
reiserfs_write_unlock(inode->i_sb);
/* Drop can be outside and it needs more credits so it's better to have it outside */
dquot_drop(inode);
reiserfs_write_lock(inode->i_sb);
inode->i_flags |= S_NOQUOTA;
make_bad_inode(inode);
out_inserted_sd:
inode->i_nlink = 0;
th->t_trans_id = 0; /* so the caller can't use this handle later */
unlock_new_inode(inode); /* OK to do even if we hadn't locked it */
iput(inode);
return err;
}
/*
** finds the tail page in the page cache,
** reads the last block in.
**
** On success, page_result is set to a locked, pinned page, and bh_result
** is set to an up to date buffer for the last block in the file. returns 0.
**
** tail conversion is not done, so bh_result might not be valid for writing
** check buffer_mapped(bh_result) and bh_result->b_blocknr != 0 before
** trying to write the block.
**
** on failure, nonzero is returned, page_result and bh_result are untouched.
*/
static int grab_tail_page(struct inode *inode,
struct page **page_result,
struct buffer_head **bh_result)
{
/* we want the page with the last byte in the file,
** not the page that will hold the next byte for appending
*/
unsigned long index = (inode->i_size - 1) >> PAGE_CACHE_SHIFT;
unsigned long pos = 0;
unsigned long start = 0;
unsigned long blocksize = inode->i_sb->s_blocksize;
unsigned long offset = (inode->i_size) & (PAGE_CACHE_SIZE - 1);
struct buffer_head *bh;
struct buffer_head *head;
struct page *page;
int error;
/* we know that we are only called with inode->i_size > 0.
** we also know that a file tail can never be as big as a block
** If i_size % blocksize == 0, our file is currently block aligned
** and it won't need converting or zeroing after a truncate.
*/
if ((offset & (blocksize - 1)) == 0) {
return -ENOENT;
}
page = grab_cache_page(inode->i_mapping, index);
error = -ENOMEM;
if (!page) {
goto out;
}
/* start within the page of the last block in the file */
start = (offset / blocksize) * blocksize;
error = __block_write_begin(page, start, offset - start,
reiserfs_get_block_create_0);
if (error)
goto unlock;
head = page_buffers(page);
bh = head;
do {
if (pos >= start) {
break;
}
bh = bh->b_this_page;
pos += blocksize;
} while (bh != head);
if (!buffer_uptodate(bh)) {
/* note, this should never happen, prepare_write should
** be taking care of this for us. If the buffer isn't up to date,
** I've screwed up the code to find the buffer, or the code to
** call prepare_write
*/
reiserfs_error(inode->i_sb, "clm-6000",
"error reading block %lu", bh->b_blocknr);
error = -EIO;
goto unlock;
}
*bh_result = bh;
*page_result = page;
out:
return error;
unlock:
unlock_page(page);
page_cache_release(page);
return error;
}
/*
** vfs version of truncate file. Must NOT be called with
** a transaction already started.
**
** some code taken from block_truncate_page
*/
int reiserfs_truncate_file(struct inode *inode, int update_timestamps)
{
struct reiserfs_transaction_handle th;
/* we want the offset for the first byte after the end of the file */
unsigned long offset = inode->i_size & (PAGE_CACHE_SIZE - 1);
unsigned blocksize = inode->i_sb->s_blocksize;
unsigned length;
struct page *page = NULL;
int error;
struct buffer_head *bh = NULL;
int err2;
int lock_depth;
lock_depth = reiserfs_write_lock_once(inode->i_sb);
if (inode->i_size > 0) {
error = grab_tail_page(inode, &page, &bh);
if (error) {
// -ENOENT means we truncated past the end of the file,
// and get_block_create_0 could not find a block to read in,
// which is ok.
if (error != -ENOENT)
reiserfs_error(inode->i_sb, "clm-6001",
"grab_tail_page failed %d",
error);
page = NULL;
bh = NULL;
}
}
/* so, if page != NULL, we have a buffer head for the offset at
** the end of the file. if the bh is mapped, and bh->b_blocknr != 0,
** then we have an unformatted node. Otherwise, we have a direct item,
** and no zeroing is required on disk. We zero after the truncate,
** because the truncate might pack the item anyway
** (it will unmap bh if it packs).
*/
/* it is enough to reserve space in transaction for 2 balancings:
one for "save" link adding and another for the first
cut_from_item. 1 is for update_sd */
error = journal_begin(&th, inode->i_sb,
JOURNAL_PER_BALANCE_CNT * 2 + 1);
if (error)
goto out;
reiserfs_update_inode_transaction(inode);
if (update_timestamps)
/* we are doing real truncate: if the system crashes before the last
transaction of truncating gets committed - on reboot the file
either appears truncated properly or not truncated at all */
add_save_link(&th, inode, 1);
err2 = reiserfs_do_truncate(&th, inode, page, update_timestamps);
error =
journal_end(&th, inode->i_sb, JOURNAL_PER_BALANCE_CNT * 2 + 1);
if (error)
goto out;
/* check reiserfs_do_truncate after ending the transaction */
if (err2) {
error = err2;
goto out;
}
if (update_timestamps) {
error = remove_save_link(inode, 1 /* truncate */);
if (error)
goto out;
}
if (page) {
length = offset & (blocksize - 1);
/* if we are not on a block boundary */
if (length) {
length = blocksize - length;
zero_user(page, offset, length);
if (buffer_mapped(bh) && bh->b_blocknr != 0) {
mark_buffer_dirty(bh);
}
}
unlock_page(page);
page_cache_release(page);
}
reiserfs_write_unlock_once(inode->i_sb, lock_depth);
return 0;
out:
if (page) {
unlock_page(page);
page_cache_release(page);
}
reiserfs_write_unlock_once(inode->i_sb, lock_depth);
return error;
}
static int map_block_for_writepage(struct inode *inode,
struct buffer_head *bh_result,
unsigned long block)
{
struct reiserfs_transaction_handle th;
int fs_gen;
struct item_head tmp_ih;
struct item_head *ih;
struct buffer_head *bh;
__le32 *item;
struct cpu_key key;
INITIALIZE_PATH(path);
int pos_in_item;
int jbegin_count = JOURNAL_PER_BALANCE_CNT;
loff_t byte_offset = ((loff_t)block << inode->i_sb->s_blocksize_bits)+1;
int retval;
int use_get_block = 0;
int bytes_copied = 0;
int copy_size;
int trans_running = 0;
/* catch places below that try to log something without starting a trans */
th.t_trans_id = 0;
if (!buffer_uptodate(bh_result)) {
return -EIO;
}
kmap(bh_result->b_page);
start_over:
reiserfs_write_lock(inode->i_sb);
make_cpu_key(&key, inode, byte_offset, TYPE_ANY, 3);
research:
retval = search_for_position_by_key(inode->i_sb, &key, &path);
if (retval != POSITION_FOUND) {
use_get_block = 1;
goto out;
}
bh = get_last_bh(&path);
ih = get_ih(&path);
item = get_item(&path);
pos_in_item = path.pos_in_item;
/* we've found an unformatted node */
if (indirect_item_found(retval, ih)) {
if (bytes_copied > 0) {
reiserfs_warning(inode->i_sb, "clm-6002",
"bytes_copied %d", bytes_copied);
}
if (!get_block_num(item, pos_in_item)) {
/* crap, we are writing to a hole */
use_get_block = 1;
goto out;
}
set_block_dev_mapped(bh_result,
get_block_num(item, pos_in_item), inode);
} else if (is_direct_le_ih(ih)) {
char *p;
p = page_address(bh_result->b_page);
p += (byte_offset - 1) & (PAGE_CACHE_SIZE - 1);
copy_size = ih_item_len(ih) - pos_in_item;
fs_gen = get_generation(inode->i_sb);
copy_item_head(&tmp_ih, ih);
if (!trans_running) {
/* vs-3050 is gone, no need to drop the path */
retval = journal_begin(&th, inode->i_sb, jbegin_count);
if (retval)
goto out;
reiserfs_update_inode_transaction(inode);
trans_running = 1;
if (fs_changed(fs_gen, inode->i_sb)
&& item_moved(&tmp_ih, &path)) {
reiserfs_restore_prepared_buffer(inode->i_sb,
bh);
goto research;
}
}
reiserfs_prepare_for_journal(inode->i_sb, bh, 1);
if (fs_changed(fs_gen, inode->i_sb)
&& item_moved(&tmp_ih, &path)) {
reiserfs_restore_prepared_buffer(inode->i_sb, bh);
goto research;
}
memcpy(B_I_PITEM(bh, ih) + pos_in_item, p + bytes_copied,
copy_size);
journal_mark_dirty(&th, inode->i_sb, bh);
bytes_copied += copy_size;
set_block_dev_mapped(bh_result, 0, inode);
/* are there still bytes left? */
if (bytes_copied < bh_result->b_size &&
(byte_offset + bytes_copied) < inode->i_size) {
set_cpu_key_k_offset(&key,
cpu_key_k_offset(&key) +
copy_size);
goto research;
}
} else {
reiserfs_warning(inode->i_sb, "clm-6003",
"bad item inode %lu", inode->i_ino);
retval = -EIO;
goto out;
}
retval = 0;
out:
pathrelse(&path);
if (trans_running) {
int err = journal_end(&th, inode->i_sb, jbegin_count);
if (err)
retval = err;
trans_running = 0;
}
reiserfs_write_unlock(inode->i_sb);
/* this is where we fill in holes in the file. */
if (use_get_block) {
retval = reiserfs_get_block(inode, block, bh_result,
GET_BLOCK_CREATE | GET_BLOCK_NO_IMUX
| GET_BLOCK_NO_DANGLE);
if (!retval) {
if (!buffer_mapped(bh_result)
|| bh_result->b_blocknr == 0) {
/* get_block failed to find a mapped unformatted node. */
use_get_block = 0;
goto start_over;
}
}
}
kunmap(bh_result->b_page);
if (!retval && buffer_mapped(bh_result) && bh_result->b_blocknr == 0) {
/* we've copied data from the page into the direct item, so the
* buffer in the page is now clean, mark it to reflect that.
*/
lock_buffer(bh_result);
clear_buffer_dirty(bh_result);
unlock_buffer(bh_result);
}
return retval;
}
/*
* [email protected]: updated in 2.5.54 to follow the same general io
* start/recovery path as __block_write_full_page, along with special
* code to handle reiserfs tails.
*/
static int reiserfs_write_full_page(struct page *page,
struct writeback_control *wbc)
{
struct inode *inode = page->mapping->host;
unsigned long end_index = inode->i_size >> PAGE_CACHE_SHIFT;
int error = 0;
unsigned long block;
sector_t last_block;
struct buffer_head *head, *bh;
int partial = 0;
int nr = 0;
int checked = PageChecked(page);
struct reiserfs_transaction_handle th;
struct super_block *s = inode->i_sb;
int bh_per_page = PAGE_CACHE_SIZE / s->s_blocksize;
th.t_trans_id = 0;
/* no logging allowed when nonblocking or from PF_MEMALLOC */
if (checked && (current->flags & PF_MEMALLOC)) {
redirty_page_for_writepage(wbc, page);
unlock_page(page);
return 0;
}
/* The page dirty bit is cleared before writepage is called, which
* means we have to tell create_empty_buffers to make dirty buffers
* The page really should be up to date at this point, so tossing
* in the BH_Uptodate is just a sanity check.
*/
if (!page_has_buffers(page)) {
create_empty_buffers(page, s->s_blocksize,
(1 << BH_Dirty) | (1 << BH_Uptodate));
}
head = page_buffers(page);
/* last page in the file, zero out any contents past the
** last byte in the file
*/
if (page->index >= end_index) {
unsigned last_offset;
last_offset = inode->i_size & (PAGE_CACHE_SIZE - 1);
/* no file contents in this page */
if (page->index >= end_index + 1 || !last_offset) {
unlock_page(page);
return 0;
}
zero_user_segment(page, last_offset, PAGE_CACHE_SIZE);
}
bh = head;
block = page->index << (PAGE_CACHE_SHIFT - s->s_blocksize_bits);
last_block = (i_size_read(inode) - 1) >> inode->i_blkbits;
/* first map all the buffers, logging any direct items we find */
do {
if (block > last_block) {
/*
* This can happen when the block size is less than
* the page size. The corresponding bytes in the page
* were zero filled above
*/
clear_buffer_dirty(bh);
set_buffer_uptodate(bh);
} else if ((checked || buffer_dirty(bh)) &&
(!buffer_mapped(bh) || (buffer_mapped(bh)
&& bh->b_blocknr ==
0))) {
/* not mapped yet, or it points to a direct item, search
* the btree for the mapping info, and log any direct
* items found
*/
if ((error = map_block_for_writepage(inode, bh, block))) {
goto fail;
}
}
bh = bh->b_this_page;
block++;
} while (bh != head);
/*
* we start the transaction after map_block_for_writepage,
* because it can create holes in the file (an unbounded operation).
* starting it here, we can make a reliable estimate for how many
* blocks we're going to log
*/
if (checked) {
ClearPageChecked(page);
reiserfs_write_lock(s);
error = journal_begin(&th, s, bh_per_page + 1);
if (error) {
reiserfs_write_unlock(s);
goto fail;
}
reiserfs_update_inode_transaction(inode);
}
/* now go through and lock any dirty buffers on the page */
do {
get_bh(bh);
if (!buffer_mapped(bh))
continue;
if (buffer_mapped(bh) && bh->b_blocknr == 0)
continue;
if (checked) {
reiserfs_prepare_for_journal(s, bh, 1);
journal_mark_dirty(&th, s, bh);
continue;
}
/* from this point on, we know the buffer is mapped to a
* real block and not a direct item
*/
if (wbc->sync_mode != WB_SYNC_NONE) {
lock_buffer(bh);
} else {
if (!trylock_buffer(bh)) {
redirty_page_for_writepage(wbc, page);
continue;
}
}
if (test_clear_buffer_dirty(bh)) {
mark_buffer_async_write(bh);
} else {
unlock_buffer(bh);
}
} while ((bh = bh->b_this_page) != head);
if (checked) {
error = journal_end(&th, s, bh_per_page + 1);
reiserfs_write_unlock(s);
if (error)
goto fail;
}
BUG_ON(PageWriteback(page));
set_page_writeback(page);
unlock_page(page);
/*
* since any buffer might be the only dirty buffer on the page,
* the first submit_bh can bring the page out of writeback.
* be careful with the buffers.
*/
do {
struct buffer_head *next = bh->b_this_page;
if (buffer_async_write(bh)) {
submit_bh(WRITE, bh);
nr++;
}
put_bh(bh);
bh = next;
} while (bh != head);
error = 0;
done:
if (nr == 0) {
/*
* if this page only had a direct item, it is very possible for
* no io to be required without there being an error. Or,
* someone else could have locked them and sent them down the
* pipe without locking the page
*/
bh = head;
do {
if (!buffer_uptodate(bh)) {
partial = 1;
break;
}
bh = bh->b_this_page;
} while (bh != head);
if (!partial)
SetPageUptodate(page);
end_page_writeback(page);
}
return error;
fail:
/* catches various errors, we need to make sure any valid dirty blocks
* get to the media. The page is currently locked and not marked for
* writeback
*/
ClearPageUptodate(page);
bh = head;
do {
get_bh(bh);
if (buffer_mapped(bh) && buffer_dirty(bh) && bh->b_blocknr) {
lock_buffer(bh);
mark_buffer_async_write(bh);
} else {
/*
* clear any dirty bits that might have come from getting
* attached to a dirty page
*/
clear_buffer_dirty(bh);
}
bh = bh->b_this_page;
} while (bh != head);
SetPageError(page);
BUG_ON(PageWriteback(page));
set_page_writeback(page);
unlock_page(page);
do {
struct buffer_head *next = bh->b_this_page;
if (buffer_async_write(bh)) {
clear_buffer_dirty(bh);
submit_bh(WRITE, bh);
nr++;
}
put_bh(bh);
bh = next;
} while (bh != head);
goto done;
}
static int reiserfs_readpage(struct file *f, struct page *page)
{
return block_read_full_page(page, reiserfs_get_block);
}
static int reiserfs_writepage(struct page *page, struct writeback_control *wbc)
{
struct inode *inode = page->mapping->host;
reiserfs_wait_on_write_block(inode->i_sb);
return reiserfs_write_full_page(page, wbc);
}
static void reiserfs_truncate_failed_write(struct inode *inode)
{
truncate_inode_pages(inode->i_mapping, inode->i_size);
reiserfs_truncate_file(inode, 0);
}
static int reiserfs_write_begin(struct file *file,
struct address_space *mapping,
loff_t pos, unsigned len, unsigned flags,
struct page **pagep, void **fsdata)
{
struct inode *inode;
struct page *page;
pgoff_t index;
int ret;
int old_ref = 0;
inode = mapping->host;
*fsdata = 0;
if (flags & AOP_FLAG_CONT_EXPAND &&
(pos & (inode->i_sb->s_blocksize - 1)) == 0) {
pos ++;
*fsdata = (void *)(unsigned long)flags;
}
index = pos >> PAGE_CACHE_SHIFT;
page = grab_cache_page_write_begin(mapping, index, flags);
if (!page)
return -ENOMEM;
*pagep = page;
reiserfs_wait_on_write_block(inode->i_sb);
fix_tail_page_for_writing(page);
if (reiserfs_transaction_running(inode->i_sb)) {
struct reiserfs_transaction_handle *th;
th = (struct reiserfs_transaction_handle *)current->
journal_info;
BUG_ON(!th->t_refcount);
BUG_ON(!th->t_trans_id);
old_ref = th->t_refcount;
th->t_refcount++;
}
ret = __block_write_begin(page, pos, len, reiserfs_get_block);
if (ret && reiserfs_transaction_running(inode->i_sb)) {
struct reiserfs_transaction_handle *th = current->journal_info;
/* this gets a little ugly. If reiserfs_get_block returned an
* error and left a transacstion running, we've got to close it,
* and we've got to free handle if it was a persistent transaction.
*
* But, if we had nested into an existing transaction, we need
* to just drop the ref count on the handle.
*
* If old_ref == 0, the transaction is from reiserfs_get_block,
* and it was a persistent trans. Otherwise, it was nested above.
*/
if (th->t_refcount > old_ref) {
if (old_ref)
th->t_refcount--;
else {
int err;
reiserfs_write_lock(inode->i_sb);
err = reiserfs_end_persistent_transaction(th);
reiserfs_write_unlock(inode->i_sb);
if (err)
ret = err;
}
}
}
if (ret) {
unlock_page(page);
page_cache_release(page);
/* Truncate allocated blocks */
reiserfs_truncate_failed_write(inode);
}
return ret;
}
int __reiserfs_write_begin(struct page *page, unsigned from, unsigned len)
{
struct inode *inode = page->mapping->host;
int ret;
int old_ref = 0;
reiserfs_write_unlock(inode->i_sb);
reiserfs_wait_on_write_block(inode->i_sb);
reiserfs_write_lock(inode->i_sb);
fix_tail_page_for_writing(page);
if (reiserfs_transaction_running(inode->i_sb)) {
struct reiserfs_transaction_handle *th;
th = (struct reiserfs_transaction_handle *)current->
journal_info;
BUG_ON(!th->t_refcount);
BUG_ON(!th->t_trans_id);
old_ref = th->t_refcount;
th->t_refcount++;
}
ret = __block_write_begin(page, from, len, reiserfs_get_block);
if (ret && reiserfs_transaction_running(inode->i_sb)) {
struct reiserfs_transaction_handle *th = current->journal_info;
/* this gets a little ugly. If reiserfs_get_block returned an
* error and left a transacstion running, we've got to close it,
* and we've got to free handle if it was a persistent transaction.
*
* But, if we had nested into an existing transaction, we need
* to just drop the ref count on the handle.
*
* If old_ref == 0, the transaction is from reiserfs_get_block,
* and it was a persistent trans. Otherwise, it was nested above.
*/
if (th->t_refcount > old_ref) {
if (old_ref)
th->t_refcount--;
else {
int err;
reiserfs_write_lock(inode->i_sb);
err = reiserfs_end_persistent_transaction(th);
reiserfs_write_unlock(inode->i_sb);
if (err)
ret = err;
}
}
}
return ret;
}
static sector_t reiserfs_aop_bmap(struct address_space *as, sector_t block)
{
return generic_block_bmap(as, block, reiserfs_bmap);
}
static int reiserfs_write_end(struct file *file, struct address_space *mapping,
loff_t pos, unsigned len, unsigned copied,
struct page *page, void *fsdata)
{
struct inode *inode = page->mapping->host;
int ret = 0;
int update_sd = 0;
struct reiserfs_transaction_handle *th;
unsigned start;
int lock_depth = 0;
bool locked = false;
if ((unsigned long)fsdata & AOP_FLAG_CONT_EXPAND)
pos ++;
reiserfs_wait_on_write_block(inode->i_sb);
if (reiserfs_transaction_running(inode->i_sb))
th = current->journal_info;
else
th = NULL;
start = pos & (PAGE_CACHE_SIZE - 1);
if (unlikely(copied < len)) {
if (!PageUptodate(page))
copied = 0;
page_zero_new_buffers(page, start + copied, start + len);
}
flush_dcache_page(page);
reiserfs_commit_page(inode, page, start, start + copied);
/* generic_commit_write does this for us, but does not update the
** transaction tracking stuff when the size changes. So, we have
** to do the i_size updates here.
*/
if (pos + copied > inode->i_size) {
struct reiserfs_transaction_handle myth;
lock_depth = reiserfs_write_lock_once(inode->i_sb);
locked = true;
/* If the file have grown beyond the border where it
can have a tail, unmark it as needing a tail
packing */
if ((have_large_tails(inode->i_sb)
&& inode->i_size > i_block_size(inode) * 4)
|| (have_small_tails(inode->i_sb)
&& inode->i_size > i_block_size(inode)))
REISERFS_I(inode)->i_flags &= ~i_pack_on_close_mask;
ret = journal_begin(&myth, inode->i_sb, 1);
if (ret)
goto journal_error;
reiserfs_update_inode_transaction(inode);
inode->i_size = pos + copied;
/*
* this will just nest into our transaction. It's important
* to use mark_inode_dirty so the inode gets pushed around on the
* dirty lists, and so that O_SYNC works as expected
*/
mark_inode_dirty(inode);
reiserfs_update_sd(&myth, inode);
update_sd = 1;
ret = journal_end(&myth, inode->i_sb, 1);
if (ret)
goto journal_error;
}
if (th) {
if (!locked) {
lock_depth = reiserfs_write_lock_once(inode->i_sb);
locked = true;
}
if (!update_sd)
mark_inode_dirty(inode);
ret = reiserfs_end_persistent_transaction(th);
if (ret)
goto out;
}
out:
if (locked)
reiserfs_write_unlock_once(inode->i_sb, lock_depth);
unlock_page(page);
page_cache_release(page);
if (pos + len > inode->i_size)
reiserfs_truncate_failed_write(inode);
return ret == 0 ? copied : ret;
journal_error:
reiserfs_write_unlock_once(inode->i_sb, lock_depth);
locked = false;
if (th) {
if (!update_sd)
reiserfs_update_sd(th, inode);
ret = reiserfs_end_persistent_transaction(th);
}
goto out;
}
int reiserfs_commit_write(struct file *f, struct page *page,
unsigned from, unsigned to)
{
struct inode *inode = page->mapping->host;
loff_t pos = ((loff_t) page->index << PAGE_CACHE_SHIFT) + to;
int ret = 0;
int update_sd = 0;
struct reiserfs_transaction_handle *th = NULL;
reiserfs_write_unlock(inode->i_sb);
reiserfs_wait_on_write_block(inode->i_sb);
reiserfs_write_lock(inode->i_sb);
if (reiserfs_transaction_running(inode->i_sb)) {
th = current->journal_info;
}
reiserfs_commit_page(inode, page, from, to);
/* generic_commit_write does this for us, but does not update the
** transaction tracking stuff when the size changes. So, we have
** to do the i_size updates here.
*/
if (pos > inode->i_size) {
struct reiserfs_transaction_handle myth;
/* If the file have grown beyond the border where it
can have a tail, unmark it as needing a tail
packing */
if ((have_large_tails(inode->i_sb)
&& inode->i_size > i_block_size(inode) * 4)
|| (have_small_tails(inode->i_sb)
&& inode->i_size > i_block_size(inode)))
REISERFS_I(inode)->i_flags &= ~i_pack_on_close_mask;
ret = journal_begin(&myth, inode->i_sb, 1);
if (ret)
goto journal_error;
reiserfs_update_inode_transaction(inode);
inode->i_size = pos;
/*
* this will just nest into our transaction. It's important
* to use mark_inode_dirty so the inode gets pushed around on the
* dirty lists, and so that O_SYNC works as expected
*/
mark_inode_dirty(inode);
reiserfs_update_sd(&myth, inode);
update_sd = 1;
ret = journal_end(&myth, inode->i_sb, 1);
if (ret)
goto journal_error;
}
if (th) {
if (!update_sd)
mark_inode_dirty(inode);
ret = reiserfs_end_persistent_transaction(th);
if (ret)
goto out;
}
out:
return ret;
journal_error:
if (th) {
if (!update_sd)
reiserfs_update_sd(th, inode);
ret = reiserfs_end_persistent_transaction(th);
}
return ret;
}
void sd_attrs_to_i_attrs(__u16 sd_attrs, struct inode *inode)
{
if (reiserfs_attrs(inode->i_sb)) {
if (sd_attrs & REISERFS_SYNC_FL)
inode->i_flags |= S_SYNC;
else
inode->i_flags &= ~S_SYNC;
if (sd_attrs & REISERFS_IMMUTABLE_FL)
inode->i_flags |= S_IMMUTABLE;
else
inode->i_flags &= ~S_IMMUTABLE;
if (sd_attrs & REISERFS_APPEND_FL)
inode->i_flags |= S_APPEND;
else
inode->i_flags &= ~S_APPEND;
if (sd_attrs & REISERFS_NOATIME_FL)
inode->i_flags |= S_NOATIME;
else
inode->i_flags &= ~S_NOATIME;
if (sd_attrs & REISERFS_NOTAIL_FL)
REISERFS_I(inode)->i_flags |= i_nopack_mask;
else
REISERFS_I(inode)->i_flags &= ~i_nopack_mask;
}
}
void i_attrs_to_sd_attrs(struct inode *inode, __u16 * sd_attrs)
{
if (reiserfs_attrs(inode->i_sb)) {
if (inode->i_flags & S_IMMUTABLE)
*sd_attrs |= REISERFS_IMMUTABLE_FL;
else
*sd_attrs &= ~REISERFS_IMMUTABLE_FL;
if (inode->i_flags & S_SYNC)
*sd_attrs |= REISERFS_SYNC_FL;
else
*sd_attrs &= ~REISERFS_SYNC_FL;
if (inode->i_flags & S_NOATIME)
*sd_attrs |= REISERFS_NOATIME_FL;
else
*sd_attrs &= ~REISERFS_NOATIME_FL;
if (REISERFS_I(inode)->i_flags & i_nopack_mask)
*sd_attrs |= REISERFS_NOTAIL_FL;
else
*sd_attrs &= ~REISERFS_NOTAIL_FL;
}
}
/* decide if this buffer needs to stay around for data logging or ordered
** write purposes
*/
static int invalidatepage_can_drop(struct inode *inode, struct buffer_head *bh)
{
int ret = 1;
struct reiserfs_journal *j = SB_JOURNAL(inode->i_sb);
lock_buffer(bh);
spin_lock(&j->j_dirty_buffers_lock);
if (!buffer_mapped(bh)) {
goto free_jh;
}
/* the page is locked, and the only places that log a data buffer
* also lock the page.
*/
if (reiserfs_file_data_log(inode)) {
/*
* very conservative, leave the buffer pinned if
* anyone might need it.
*/
if (buffer_journaled(bh) || buffer_journal_dirty(bh)) {
ret = 0;
}
} else if (buffer_dirty(bh)) {
struct reiserfs_journal_list *jl;
struct reiserfs_jh *jh = bh->b_private;
/* why is this safe?
* reiserfs_setattr updates i_size in the on disk
* stat data before allowing vmtruncate to be called.
*
* If buffer was put onto the ordered list for this
* transaction, we know for sure either this transaction
* or an older one already has updated i_size on disk,
* and this ordered data won't be referenced in the file
* if we crash.
*
* if the buffer was put onto the ordered list for an older
* transaction, we need to leave it around
*/
if (jh && (jl = jh->jl)
&& jl != SB_JOURNAL(inode->i_sb)->j_current_jl)
ret = 0;
}
free_jh:
if (ret && bh->b_private) {
reiserfs_free_jh(bh);
}
spin_unlock(&j->j_dirty_buffers_lock);
unlock_buffer(bh);
return ret;
}
/* clm -- taken from fs/buffer.c:block_invalidate_page */
static void reiserfs_invalidatepage(struct page *page, unsigned long offset)
{
struct buffer_head *head, *bh, *next;
struct inode *inode = page->mapping->host;
unsigned int curr_off = 0;
int ret = 1;
BUG_ON(!PageLocked(page));
if (offset == 0)
ClearPageChecked(page);
if (!page_has_buffers(page))
goto out;
head = page_buffers(page);
bh = head;
do {
unsigned int next_off = curr_off + bh->b_size;
next = bh->b_this_page;
/*
* is this block fully invalidated?
*/
if (offset <= curr_off) {
if (invalidatepage_can_drop(inode, bh))
reiserfs_unmap_buffer(bh);
else
ret = 0;
}
curr_off = next_off;
bh = next;
} while (bh != head);
/*
* We release buffers only if the entire page is being invalidated.
* The get_block cached value has been unconditionally invalidated,
* so real IO is not possible anymore.
*/
if (!offset && ret) {
ret = try_to_release_page(page, 0);
/* maybe should BUG_ON(!ret); - neilb */
}
out:
return;
}
static int reiserfs_set_page_dirty(struct page *page)
{
struct inode *inode = page->mapping->host;
if (reiserfs_file_data_log(inode)) {
SetPageChecked(page);
return __set_page_dirty_nobuffers(page);
}
return __set_page_dirty_buffers(page);
}
/*
* Returns 1 if the page's buffers were dropped. The page is locked.
*
* Takes j_dirty_buffers_lock to protect the b_assoc_buffers list_heads
* in the buffers at page_buffers(page).
*
* even in -o notail mode, we can't be sure an old mount without -o notail
* didn't create files with tails.
*/
static int reiserfs_releasepage(struct page *page, gfp_t unused_gfp_flags)
{
struct inode *inode = page->mapping->host;
struct reiserfs_journal *j = SB_JOURNAL(inode->i_sb);
struct buffer_head *head;
struct buffer_head *bh;
int ret = 1;
WARN_ON(PageChecked(page));
spin_lock(&j->j_dirty_buffers_lock);
head = page_buffers(page);
bh = head;
do {
if (bh->b_private) {
if (!buffer_dirty(bh) && !buffer_locked(bh)) {
reiserfs_free_jh(bh);
} else {
ret = 0;
break;
}
}
bh = bh->b_this_page;
} while (bh != head);
if (ret)
ret = try_to_free_buffers(page);
spin_unlock(&j->j_dirty_buffers_lock);
return ret;
}
/* We thank Mingming Cao for helping us understand in great detail what
to do in this section of the code. */
static ssize_t reiserfs_direct_IO(int rw, struct kiocb *iocb,
const struct iovec *iov, loff_t offset,
unsigned long nr_segs)
{
struct file *file = iocb->ki_filp;
struct inode *inode = file->f_mapping->host;
ssize_t ret;
ret = blockdev_direct_IO(rw, iocb, inode, inode->i_sb->s_bdev, iov,
offset, nr_segs,
reiserfs_get_blocks_direct_io, NULL);
/*
* In case of error extending write may have instantiated a few
* blocks outside i_size. Trim these off again.
*/
if (unlikely((rw & WRITE) && ret < 0)) {
loff_t isize = i_size_read(inode);
loff_t end = offset + iov_length(iov, nr_segs);
if (end > isize)
vmtruncate(inode, isize);
}
return ret;
}
int reiserfs_setattr(struct dentry *dentry, struct iattr *attr)
{
struct inode *inode = dentry->d_inode;
unsigned int ia_valid;
int depth;
int error;
error = inode_change_ok(inode, attr);
if (error)
return error;
/* must be turned off for recursive notify_change calls */
ia_valid = attr->ia_valid &= ~(ATTR_KILL_SUID|ATTR_KILL_SGID);
if (is_quota_modification(inode, attr))
dquot_initialize(inode);
depth = reiserfs_write_lock_once(inode->i_sb);
if (attr->ia_valid & ATTR_SIZE) {
/* version 2 items will be caught by the s_maxbytes check
** done for us in vmtruncate
*/
if (get_inode_item_key_version(inode) == KEY_FORMAT_3_5 &&
attr->ia_size > MAX_NON_LFS) {
error = -EFBIG;
goto out;
}
/* fill in hole pointers in the expanding truncate case. */
if (attr->ia_size > inode->i_size) {
error = generic_cont_expand_simple(inode, attr->ia_size);
if (REISERFS_I(inode)->i_prealloc_count > 0) {
int err;
struct reiserfs_transaction_handle th;
/* we're changing at most 2 bitmaps, inode + super */
err = journal_begin(&th, inode->i_sb, 4);
if (!err) {
reiserfs_discard_prealloc(&th, inode);
err = journal_end(&th, inode->i_sb, 4);
}
if (err)
error = err;
}
if (error)
goto out;
/*
* file size is changed, ctime and mtime are
* to be updated
*/
attr->ia_valid |= (ATTR_MTIME | ATTR_CTIME);
}
}
if ((((attr->ia_valid & ATTR_UID) && (attr->ia_uid & ~0xffff)) ||
((attr->ia_valid & ATTR_GID) && (attr->ia_gid & ~0xffff))) &&
(get_inode_sd_version(inode) == STAT_DATA_V1)) {
/* stat data of format v3.5 has 16 bit uid and gid */
error = -EINVAL;
goto out;
}
if ((ia_valid & ATTR_UID && attr->ia_uid != inode->i_uid) ||
(ia_valid & ATTR_GID && attr->ia_gid != inode->i_gid)) {
struct reiserfs_transaction_handle th;
int jbegin_count =
2 *
(REISERFS_QUOTA_INIT_BLOCKS(inode->i_sb) +
REISERFS_QUOTA_DEL_BLOCKS(inode->i_sb)) +
2;
error = reiserfs_chown_xattrs(inode, attr);
if (error)
return error;
/* (user+group)*(old+new) structure - we count quota info and , inode write (sb, inode) */
error = journal_begin(&th, inode->i_sb, jbegin_count);
if (error)
goto out;
reiserfs_write_unlock_once(inode->i_sb, depth);
error = dquot_transfer(inode, attr);
depth = reiserfs_write_lock_once(inode->i_sb);
if (error) {
journal_end(&th, inode->i_sb, jbegin_count);
goto out;
}
/* Update corresponding info in inode so that everything is in
* one transaction */
if (attr->ia_valid & ATTR_UID)
inode->i_uid = attr->ia_uid;
if (attr->ia_valid & ATTR_GID)
inode->i_gid = attr->ia_gid;
mark_inode_dirty(inode);
error = journal_end(&th, inode->i_sb, jbegin_count);
if (error)
goto out;
}
/*
* Relax the lock here, as it might truncate the
* inode pages and wait for inode pages locks.
* To release such page lock, the owner needs the
* reiserfs lock
*/
reiserfs_write_unlock_once(inode->i_sb, depth);
if ((attr->ia_valid & ATTR_SIZE) &&
attr->ia_size != i_size_read(inode))
error = vmtruncate(inode, attr->ia_size);
if (!error) {
setattr_copy(inode, attr);
mark_inode_dirty(inode);
}
depth = reiserfs_write_lock_once(inode->i_sb);
if (!error && reiserfs_posixacl(inode->i_sb)) {
if (attr->ia_valid & ATTR_MODE)
error = reiserfs_acl_chmod(inode);
}
out:
reiserfs_write_unlock_once(inode->i_sb, depth);
return error;
}
const struct address_space_operations reiserfs_address_space_operations = {
.writepage = reiserfs_writepage,
.readpage = reiserfs_readpage,
.readpages = reiserfs_readpages,
.releasepage = reiserfs_releasepage,
.invalidatepage = reiserfs_invalidatepage,
.write_begin = reiserfs_write_begin,
.write_end = reiserfs_write_end,
.bmap = reiserfs_aop_bmap,
.direct_IO = reiserfs_direct_IO,
.set_page_dirty = reiserfs_set_page_dirty,
};
|
828775.c | /*
This file shows the basics of using binn objects. It does not show lists and maps.
For more examples check https://github.com/liteserver/binn/blob/master/usage.md
*/
#include <binn.h>
/*
** option 1: use the raw buffer pointer
*/
void read_example_1(void *buf) {
int id;
char *name;
double price;
id = binn_object_int32(buf, "id");
name = binn_object_str(buf, "name");
price = binn_object_double(buf, "price");
}
/*
** option 2: load the raw buffer to a binn pointer
*/
void read_example_2(void *buf) {
int id;
char *name;
double price;
binn *obj;
obj = binn_open(buf);
if (obj == 0) return;
id = binn_object_int32(obj, "id");
name = binn_object_str(obj, "name");
price = binn_object_double(obj, "price");
binn_free(obj); /* releases the binn pointer but NOT the received buf */
}
/*
** option 3: use the current created object
**
** this is used when both the writer and the reader are in the same app
*/
void read_example_3a(binn *obj) {
int id;
char *name;
double price;
id = binn_object_int32(obj, "id");
name = binn_object_str(obj, "name");
price = binn_object_double(obj, "price");
}
/* almost the same but in this case the binn pointer is returned from another function */
void read_example_3b() {
int id;
char *name;
double price;
binn *obj;
obj = some_function(); /* this function should return a binn pointer */
id = binn_object_int32(obj, "id");
name = binn_object_str(obj, "name");
price = binn_object_double(obj, "price");
binn_free(obj);
}
|
295340.c | /*
* (C) Copyright 2014 Kurento (http://kurento.org/)
*
* 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.
*
*/
#ifdef HAVE_CONFIG_H
# include <config.h>
#endif
#include "kmsparsetreebin.h"
#include <kmsutils.h>
#define GST_DEFAULT_NAME "parsetreebin"
#define GST_CAT_DEFAULT kms_parse_tree_bin_debug
GST_DEBUG_CATEGORY_STATIC (GST_CAT_DEFAULT);
#define kms_parse_tree_bin_parent_class parent_class
G_DEFINE_TYPE (KmsParseTreeBin, kms_parse_tree_bin, KMS_TYPE_TREE_BIN);
#define KMS_PARSE_TREE_BIN_GET_PRIVATE(obj) ( \
G_TYPE_INSTANCE_GET_PRIVATE ( \
(obj), \
KMS_TYPE_PARSE_TREE_BIN, \
KmsParseTreeBinPrivate \
) \
)
#define BITRATE_THRESHOLD 0.07
struct _KmsParseTreeBinPrivate
{
GstElement *parser;
/* Bitrate calculation */
GstClockTime last_buffer_pts;
GstClockTime last_buffer_dts;
guint bitrate_mean;
guint last_pushed_bitrate;
};
static GstElement *
create_parser_for_caps (const GstCaps * caps)
{
GList *parser_list, *filtered_list, *l;
GstElementFactory *parser_factory = NULL;
GstElement *parser = NULL;
parser_list =
gst_element_factory_list_get_elements (GST_ELEMENT_FACTORY_TYPE_PARSER,
GST_RANK_NONE);
filtered_list =
gst_element_factory_list_filter (parser_list, caps, GST_PAD_SINK, FALSE);
for (l = filtered_list; l != NULL && parser_factory == NULL; l = l->next) {
parser_factory = GST_ELEMENT_FACTORY (l->data);
if (gst_element_factory_get_num_pad_templates (parser_factory) != 2)
parser_factory = NULL;
}
if (parser_factory != NULL) {
parser = gst_element_factory_create (parser_factory, NULL);
} else {
parser = gst_element_factory_make ("capsfilter", NULL);
}
gst_plugin_feature_list_free (filtered_list);
gst_plugin_feature_list_free (parser_list);
return parser;
}
static gboolean
difference_over_threshold (guint a, guint b, float th)
{
return (a > b ? (a - b) > (a * th) : (b - a) > (b * th));
}
static GstPadProbeReturn
bitrate_calculation_probe (GstPad * pad, GstPadProbeInfo * info, gpointer data)
{
KmsParseTreeBin *self = data;
if (GST_PAD_PROBE_INFO_TYPE (info) | GST_PAD_PROBE_TYPE_BUFFER) {
GstBuffer *buffer = gst_pad_probe_info_get_buffer (info);
GstClockTime timediff = GST_CLOCK_TIME_NONE;
guint bitrate;
if (GST_CLOCK_TIME_IS_VALID (buffer->dts)
&& GST_CLOCK_TIME_IS_VALID (self->priv->last_buffer_dts)) {
timediff = buffer->dts - self->priv->last_buffer_dts;
} else if (GST_CLOCK_TIME_IS_VALID (buffer->pts)
&& GST_CLOCK_TIME_IS_VALID (self->priv->last_buffer_pts)) {
timediff = buffer->pts - self->priv->last_buffer_pts;
}
if (timediff > 0) {
bitrate = (gst_buffer_get_size (buffer) * GST_SECOND * 8) / timediff;
self->priv->bitrate_mean = (self->priv->bitrate_mean * 7 + bitrate) / 8;
if (self->priv->last_pushed_bitrate == 0
|| difference_over_threshold (self->priv->bitrate_mean,
self->priv->last_pushed_bitrate, BITRATE_THRESHOLD)) {
GstTagList *taglist = NULL;
GstEvent *previous_tag_event;
GST_TRACE_OBJECT (self, "Bitrate: %u", bitrate);
GST_TRACE_OBJECT (self, "Bitrate_mean:\t\t%u",
self->priv->bitrate_mean);
previous_tag_event = gst_pad_get_sticky_event (pad, GST_EVENT_TAG, 0);
if (previous_tag_event) {
GST_TRACE_OBJECT (self, "Previous tag event: %" GST_PTR_FORMAT,
previous_tag_event);
gst_event_parse_tag (previous_tag_event, &taglist);
taglist = gst_tag_list_copy (taglist);
gst_tag_list_add (taglist, GST_TAG_MERGE_REPLACE, "bitrate",
self->priv->bitrate_mean, NULL);
gst_event_unref (previous_tag_event);
}
if (!taglist) {
taglist =
gst_tag_list_new ("bitrate", self->priv->bitrate_mean, NULL);
}
gst_pad_send_event (pad, gst_event_new_tag (taglist));
self->priv->last_pushed_bitrate = self->priv->bitrate_mean;
}
}
self->priv->last_buffer_pts = buffer->pts;
self->priv->last_buffer_dts = buffer->dts;
} else if (GST_PAD_PROBE_INFO_TYPE (info) | GST_PAD_PROBE_TYPE_BUFFER_LIST) {
GST_WARNING_OBJECT (self,
"Bufferlist is not supported yet for bitrate calculation");
}
return GST_PAD_PROBE_OK;
}
static void
kms_parse_tree_bin_configure (KmsParseTreeBin * self, const GstCaps * caps)
{
KmsTreeBin *tree_bin = KMS_TREE_BIN (self);
GstElement *output_tee;
self->priv->parser = create_parser_for_caps (caps);
gst_bin_add (GST_BIN (self), self->priv->parser);
gst_element_sync_state_with_parent (self->priv->parser);
kms_tree_bin_set_input_element (tree_bin, self->priv->parser);
output_tee = kms_tree_bin_get_output_tee (tree_bin);
if (!kms_utils_caps_are_raw (caps) && kms_utils_caps_are_video (caps)) {
GstPad *sink = gst_element_get_static_pad (output_tee, "sink");
gst_pad_add_probe (sink,
GST_PAD_PROBE_TYPE_BUFFER | GST_PAD_PROBE_TYPE_BUFFER_LIST,
bitrate_calculation_probe, self, NULL);
g_object_unref (sink);
}
gst_element_link_many (self->priv->parser, output_tee, NULL);
}
KmsParseTreeBin *
kms_parse_tree_bin_new (const GstCaps * caps)
{
GObject *parse;
parse = g_object_new (KMS_TYPE_PARSE_TREE_BIN, NULL);
kms_parse_tree_bin_configure (KMS_PARSE_TREE_BIN (parse), caps);
return KMS_PARSE_TREE_BIN (parse);
}
GstElement *
kms_parse_tree_bin_get_parser (KmsParseTreeBin * self)
{
return self->priv->parser;
}
static void
kms_parse_tree_bin_init (KmsParseTreeBin * self)
{
self->priv = KMS_PARSE_TREE_BIN_GET_PRIVATE (self);
self->priv->last_buffer_dts = GST_CLOCK_TIME_NONE;
self->priv->last_buffer_pts = GST_CLOCK_TIME_NONE;
}
static void
kms_parse_tree_bin_class_init (KmsParseTreeBinClass * klass)
{
GstElementClass *gstelement_class = GST_ELEMENT_CLASS (klass);
gst_element_class_set_details_simple (gstelement_class,
"ParseTreeBin",
"Generic",
"Bin to parse and distribute media.",
"Miguel París Díaz <[email protected]>");
GST_DEBUG_CATEGORY_INIT (GST_CAT_DEFAULT, GST_DEFAULT_NAME, 0,
GST_DEFAULT_NAME);
g_type_class_add_private (klass, sizeof (KmsParseTreeBinPrivate));
}
|
794895.c | /*------------------------------------------------------------------------------
Copyright (c) 2008 The Khronos Group Inc.
All Rights Reserved. This code is protected by copyright laws and contains
material proprietary to the Khronos Group, Inc. This is UNPUBLISHED
PROPRIETARY SOURCE CODE that may not be disclosed in whole or in part to third
parties, and may not be reproduced, republished, distributed, transmitted,
displayed, broadcast or otherwise exploited in any manner without the express
prior written permission of Khronos Group.
The receipt or possession of this code does not convey any rights to reproduce,
disclose, or distribute its contents, or to manufacture, use, or sell anything
that it may describe, in whole or in part other than under the terms of the
Khronos Adopters Agreement or Khronos Conformance Test Source License Agreement
as executed between Khronos and the recipient.
For the avoidance of doubt, this code when provided: a) under the Khronos
Conformance Test Source License Agreement is for the sole purpose of creating
conformance tests for delivery to Khronos and does not provide for formally
testing products or use of Khronos trademarks on conformant products; b) under
the Khronos Adopters Agreement is for the sole purpose of formally
administering tests to products pursuant to the Khronos Conformance Process
Document.
Khronos, OpenKODE, OpenVG, OpenWF, glFX, OpenMAX and OpenSL ES are trademarks
of the Khronos Group Inc. COLLADA is a trademark of Sony Computer
Entertainment Inc. used by permission by Khronos. OpenGL and OpenML are
registered trademarks and the OpenGL ES logo is a trademark of Silicon Graphics
Inc. used by permission by Khronos.
Use, duplication or disclosure by the Government is subject to restrictions as
set forth in subdivision (c)(1)(ii) of the Rights in Technical Data and
Computer Software clause at DFARS 252.227-7013, and/or in similar or successor
clauses in the FAR, DOD or NASA FAR Supplement. Unpublished rights reserved
under the Copyright Laws of the United States and other countries.
------------------------------------------------------------------------------*/
#include "../main.h"
#include "../util/util.h"
int G20608_PathOperation_by_HUONE (CT_File AnsFile, CT_File RefFile)
{
return (int)PyramidDiff_by_HYBRID(AnsFile.tga, RefFile.tga);
}
|
920488.c | /*******************************************************************************************
*
* raylib [audio] example - Music playing (streaming)
*
* NOTE: This example requires OpenAL Soft library installed
*
* This example has been created using raylib 1.3 (www.raylib.com)
* raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details)
*
* Copyright (c) 2015 Ramon Santamaria (@raysan5)
*
********************************************************************************************/
#include "raylib.h"
#include "list.h"
#define DARKRED CLITERAL{ 117, 14, 14, 255 }
#define LIGHTGRAY2 CLITERAL{ 168, 168, 168, 255 }
int main()
{
// Initialization
//-------------------------------------------------------------------------------------------------------------------
int screenWidth = 450;
int screenHeight = 180;
InitWindow(screenWidth, screenHeight, "Linked List Music Player");
InitAudioDevice(); // Initialize audio device
Camera3D camera;
camera.position = (Vector3){ 0.01f, 10.0f, 25.0f }; // Camera position
camera.target = (Vector3){ 0.01f, -8.0f, 0.0f }; // Camera looking at point
camera.up = (Vector3){ 0.0f, -1.0f, 0.0f }; // Camera up vector (rotation towards target)
camera.fovy = 45.0f; // Camera field-of-view Y
camera.type = CAMERA_PERSPECTIVE; // Camera mode type
Music music[8] = {
LoadMusicStream("xystus.ogg"),
LoadMusicStream("seventh_wonder.ogg"),
LoadMusicStream("serpentine.ogg"),
LoadMusicStream("martyrs_soen.ogg"),
LoadMusicStream("labyrinth.ogg"),
LoadMusicStream("dream_theater.ogg"),
LoadMusicStream("darkwater.ogg"),
LoadMusicStream("circus_maximus.ogg")
};
char titles[8][64] = {
"Circus Maximus - Isolate",
"Darkwater - The Play II",
"Dream Theater - Yste Jam",
"Libyrinth - L.Y.A.F.H.",
"Soen - Martyrs",
"Serpentine - Whatever Heartache",
"Seventh Wonder - Tears for a Father",
"Xystus - End of the Line"
};
List *list = new_list( &UnloadMusicStream );
for (int i = 0; i < 8; i++) {
list_insert_next(list, NULL, music[i]);
}
Node *curr_node = list_head(list);
Music current = (Music)list_data(curr_node);
int count = 0;
PlayMusicStream(current);
float timePlayed = 0.0f;
bool pause = false;
Image images[4] = { // Initialize button images/textures
LoadImage("play.png"),
LoadImage("pause.png"),
LoadImage("back.png"),
LoadImage("forward.png")
};
for (int i = 0; i < 4; i++) {
ImageResize(&images[i], 100, 100);
}
Texture textures[4] = {
LoadTextureFromImage(images[0]),
LoadTextureFromImage(images[1]),
LoadTextureFromImage(images[2]),
LoadTextureFromImage(images[3])
};
for (int i = 0; i < 4; i++) {
UnloadImage(images[i]);
}
int buttonXOff = 25; // Button position offset
int buttonYOff = 10;
// Collision rectangle for the forward button
Rectangle forward_rect;
forward_rect.x = 250 + buttonXOff + (float) buttonXOff;
forward_rect.y = buttonYOff + (float) buttonXOff;
forward_rect.width = 50.f;
forward_rect.height = 50.f;
// Collision circle for play/pause button
Vector2 play_pause_vec;
play_pause_vec.x = 175 + buttonXOff + (float) buttonXOff;
play_pause_vec.y = 25 + buttonYOff + (float) buttonXOff;
// Collision rectangle for restart button
Rectangle back_rect;
back_rect.x = 50 + buttonXOff + (float) buttonXOff;
back_rect.y = buttonYOff + (float) buttonXOff;
back_rect.width = 50.f;
back_rect.height = 50.f;
// 3D Vector for song timeline
Vector3 cube_center = {0, 0, 0};
SetTargetFPS(60); // Set our game to run at 60 frames-per-second
// Main game loop
//-------------------------------------------------------------------------------------------------------------------
while (!WindowShouldClose()) // Detect window close button or ESC key
{
// Update
//---------------------------------------------------------------------------------------------------------------
UpdateMusicStream(current); // Update music buffer with new stream data
// Restart music playing (stop and play)
if (IsKeyPressed(KEY_SPACE) || (CheckCollisionPointCircle(GetMousePosition(), play_pause_vec, 50) && IsMouseButtonPressed(0)))
{
pause = !pause;
if (pause) PauseMusicStream(current);
else ResumeMusicStream(current);
}
SetWindowTitle(titles[count]);
// Get timePlayed scaled to bar dimensions (400 pixels)
timePlayed = GetMusicTimePlayed(current)/GetMusicTimeLength(current)*400;
// check the forward button to skip
if ((CheckCollisionPointRec(GetMousePosition(), forward_rect) && IsMouseButtonPressed(0))
|| (GetMusicTimeLength(current) <= (GetMusicTimePlayed(current) + 1))) {
if (curr_node->next == NULL) {
curr_node = list_head(list);
count = 0;
} else {
curr_node = list_next(curr_node);
count++;
}
current = (Music)list_data(curr_node);
StopMusicStream(current);
PlayMusicStream(current);
}
// Check the back button to restart the song
if (CheckCollisionPointRec(GetMousePosition(), back_rect) && IsMouseButtonPressed(0)) {
StopMusicStream(current);
PlayMusicStream(current);
}
//---------------------------------------------------------------------------------------------------------------
// Draw
//---------------------------------------------------------------------------------------------------------------
BeginDrawing();
ClearBackground(LIGHTGRAY2);
BeginMode3D(camera);
DrawCube(cube_center, 1, 2, 2, DARKRED);
//DrawCubeWires(cube_center, 1.05f, 2.05f, 2.05f, RED);
DrawCube(cube_center, (float)timePlayed / 8.f, 1, 1, DARKGRAY);
DrawCubeWires(cube_center, (float)timePlayed / 8.f + 0.5, 1.5f, 1.5f, DARKRED);
EndMode3D();
if (pause)
DrawTexture(textures[0], 150 + buttonXOff, buttonYOff, GRAY);
else
DrawTexture(textures[1], 150 + buttonXOff, buttonYOff, WHITE);
DrawTexture(textures[2], 50 + buttonXOff, buttonYOff, WHITE);
DrawTexture(textures[3], 250 + buttonXOff, buttonYOff, WHITE);
EndDrawing();
//---------------------------------------------------------------------------------------------------------------
}
// De-Initialization
//-------------------------------------------------------------------------------------------------------------------
destroy_list(list);
for (int i = 0; i < 4; i++) {
UnloadTexture(textures[i]);
}
CloseAudioDevice(); // Close audio device (music streaming is automatically stopped)
CloseWindow(); // Close window and OpenGL context
//-------------------------------------------------------------------------------------------------------------------
return 0;
}
|
473178.c | /*
(c) Copyright 2001-2009 The world wide DirectFB Open Source Community (directfb.org)
(c) Copyright 2000-2004 Convergence (integrated media) GmbH
All rights reserved.
Written by Denis Oliver Kropp <[email protected]>,
Andreas Hundt <[email protected]>,
Sven Neumann <[email protected]>,
Ville Syrjälä <[email protected]> and
Claudio Ciccani <[email protected]>.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the
Free Software Foundation, Inc., 59 Temple Place - Suite 330,
Boston, MA 02111-1307, USA.
*/
#include <config.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <directfb.h>
#include <direct/interface.h>
#include <direct/mem.h>
#include <direct/memcpy.h>
#include <direct/messages.h>
#include <direct/util.h>
#include <voodoo/conf.h>
#include <voodoo/interface.h>
#include <voodoo/manager.h>
#include <voodoo/message.h>
#include <idirectfbsurface_requestor.h>
#include "idirectfbsurface_dispatcher.h"
static DFBResult Probe( void );
static DFBResult Construct( IDirectFBSurface *thiz,
IDirectFBSurface *real,
VoodooManager *manager,
VoodooInstanceID super,
void *arg,
VoodooInstanceID *ret_instance );
#include <direct/interface_implementation.h>
DIRECT_INTERFACE_IMPLEMENTATION( IDirectFBSurface, Dispatcher )
/**************************************************************************************************/
/*
* private data struct of IDirectFBSurface_Dispatcher
*/
typedef struct {
int ref; /* reference counter */
IDirectFBSurface *real;
VoodooInstanceID super;
VoodooInstanceID self;
VoodooManager *manager;
VoodooInstanceID remote;
} IDirectFBSurface_Dispatcher_data;
/**************************************************************************************************/
static void
IDirectFBSurface_Dispatcher_Destruct( IDirectFBSurface *thiz )
{
IDirectFBSurface_Dispatcher_data *data;
D_DEBUG( "%s (%p)\n", __FUNCTION__, thiz );
data = thiz->priv;
data->real->Release( data->real );
DIRECT_DEALLOCATE_INTERFACE( thiz );
}
/**************************************************************************************************/
static DirectResult
IDirectFBSurface_Dispatcher_AddRef( IDirectFBSurface *thiz )
{
DIRECT_INTERFACE_GET_DATA(IDirectFBSurface_Dispatcher)
data->ref++;
return DFB_OK;
}
static DirectResult
IDirectFBSurface_Dispatcher_Release( IDirectFBSurface *thiz )
{
DIRECT_INTERFACE_GET_DATA(IDirectFBSurface_Dispatcher)
if (--data->ref == 0)
IDirectFBSurface_Dispatcher_Destruct( thiz );
return DFB_OK;
}
static DFBResult
IDirectFBSurface_Dispatcher_GetCapabilities( IDirectFBSurface *thiz,
DFBSurfaceCapabilities *caps )
{
DIRECT_INTERFACE_GET_DATA(IDirectFBSurface_Dispatcher)
if (!caps)
return DFB_INVARG;
return DFB_UNIMPLEMENTED;
}
static DFBResult
IDirectFBSurface_Dispatcher_GetPosition( IDirectFBSurface *thiz,
int *x,
int *y )
{
DIRECT_INTERFACE_GET_DATA(IDirectFBSurface_Dispatcher)
if (!x && !y)
return DFB_INVARG;
return DFB_UNIMPLEMENTED;
}
static DFBResult
IDirectFBSurface_Dispatcher_GetSize( IDirectFBSurface *thiz,
int *width,
int *height )
{
DIRECT_INTERFACE_GET_DATA(IDirectFBSurface_Dispatcher)
if (!width && !height)
return DFB_INVARG;
return DFB_UNIMPLEMENTED;
}
static DFBResult
IDirectFBSurface_Dispatcher_GetVisibleRectangle( IDirectFBSurface *thiz,
DFBRectangle *rect )
{
DIRECT_INTERFACE_GET_DATA(IDirectFBSurface_Dispatcher)
if (!rect)
return DFB_INVARG;
return DFB_UNIMPLEMENTED;
}
static DFBResult
IDirectFBSurface_Dispatcher_GetPixelFormat( IDirectFBSurface *thiz,
DFBSurfacePixelFormat *format )
{
DIRECT_INTERFACE_GET_DATA(IDirectFBSurface_Dispatcher)
if (!format)
return DFB_INVARG;
return DFB_UNIMPLEMENTED;
}
static DFBResult
IDirectFBSurface_Dispatcher_GetAccelerationMask( IDirectFBSurface *thiz,
IDirectFBSurface *source,
DFBAccelerationMask *mask )
{
DIRECT_INTERFACE_GET_DATA(IDirectFBSurface_Dispatcher)
if (!mask)
return DFB_INVARG;
return DFB_UNIMPLEMENTED;
}
static DFBResult
IDirectFBSurface_Dispatcher_GetPalette( IDirectFBSurface *thiz,
IDirectFBPalette **interface_ptr )
{
DIRECT_INTERFACE_GET_DATA(IDirectFBSurface_Dispatcher)
if (!interface_ptr)
return DFB_INVARG;
return DFB_UNIMPLEMENTED;
}
static DFBResult
IDirectFBSurface_Dispatcher_SetPalette( IDirectFBSurface *thiz,
IDirectFBPalette *palette )
{
DIRECT_INTERFACE_GET_DATA(IDirectFBSurface_Dispatcher)
if (!palette)
return DFB_INVARG;
return DFB_UNIMPLEMENTED;
}
static DFBResult
IDirectFBSurface_Dispatcher_SetAlphaRamp( IDirectFBSurface *thiz,
u8 a0, u8 a1, u8 a2, u8 a3 )
{
DIRECT_INTERFACE_GET_DATA(IDirectFBSurface_Dispatcher)
return DFB_UNIMPLEMENTED;
}
static DFBResult
IDirectFBSurface_Dispatcher_Lock( IDirectFBSurface *thiz,
DFBSurfaceLockFlags flags,
void **ret_ptr, int *ret_pitch )
{
DIRECT_INTERFACE_GET_DATA(IDirectFBSurface_Dispatcher)
if (!flags || !ret_ptr || !ret_pitch)
return DFB_INVARG;
return DFB_UNIMPLEMENTED;
}
static DFBResult
IDirectFBSurface_Dispatcher_GetFramebufferOffset( IDirectFBSurface *thiz,
int *offset )
{
DIRECT_INTERFACE_GET_DATA(IDirectFBSurface_Dispatcher)
if (!offset)
return DFB_INVARG;
return DFB_UNIMPLEMENTED;
}
static DFBResult
IDirectFBSurface_Dispatcher_GetPhysicalAddress( IDirectFBSurface *thiz,
unsigned long *addr )
{
DIRECT_INTERFACE_GET_DATA(IDirectFBSurface_Dispatcher)
if (!addr)
return DFB_INVARG;
return DFB_UNIMPLEMENTED;
}
static DFBResult
IDirectFBSurface_Dispatcher_Unlock( IDirectFBSurface *thiz )
{
DIRECT_INTERFACE_GET_DATA(IDirectFBSurface_Dispatcher)
return DFB_UNIMPLEMENTED;
}
static DFBResult
IDirectFBSurface_Dispatcher_Flip( IDirectFBSurface *thiz,
const DFBRegion *region,
DFBSurfaceFlipFlags flags )
{
DIRECT_INTERFACE_GET_DATA(IDirectFBSurface_Dispatcher)
return DFB_UNIMPLEMENTED;
}
static DFBResult
IDirectFBSurface_Dispatcher_SetField( IDirectFBSurface *thiz,
int field )
{
DIRECT_INTERFACE_GET_DATA(IDirectFBSurface_Dispatcher)
if (field < 0 || field > 1)
return DFB_INVARG;
return DFB_UNIMPLEMENTED;
}
static DFBResult
IDirectFBSurface_Dispatcher_Clear( IDirectFBSurface *thiz,
u8 r, u8 g, u8 b, u8 a )
{
DIRECT_INTERFACE_GET_DATA(IDirectFBSurface_Dispatcher)
return DFB_UNIMPLEMENTED;
}
static DFBResult
IDirectFBSurface_Dispatcher_SetClip( IDirectFBSurface *thiz,
const DFBRegion *clip )
{
DIRECT_INTERFACE_GET_DATA(IDirectFBSurface_Dispatcher)
return DFB_UNIMPLEMENTED;
}
static DFBResult
IDirectFBSurface_Dispatcher_GetClip( IDirectFBSurface *thiz,
DFBRegion *clip )
{
DIRECT_INTERFACE_GET_DATA(IDirectFBSurface_Dispatcher)
if (!clip)
return DFB_INVARG;
return DFB_UNIMPLEMENTED;
}
static DFBResult
IDirectFBSurface_Dispatcher_SetColor( IDirectFBSurface *thiz,
u8 r, u8 g, u8 b, u8 a )
{
DIRECT_INTERFACE_GET_DATA(IDirectFBSurface_Dispatcher)
return DFB_UNIMPLEMENTED;
}
static DFBResult
IDirectFBSurface_Dispatcher_SetColorIndex( IDirectFBSurface *thiz,
unsigned int index )
{
DIRECT_INTERFACE_GET_DATA(IDirectFBSurface_Dispatcher)
return DFB_UNIMPLEMENTED;
}
static DFBResult
IDirectFBSurface_Dispatcher_SetSrcBlendFunction( IDirectFBSurface *thiz,
DFBSurfaceBlendFunction src )
{
DIRECT_INTERFACE_GET_DATA(IDirectFBSurface_Dispatcher)
return DFB_UNIMPLEMENTED;
}
static DFBResult
IDirectFBSurface_Dispatcher_SetDstBlendFunction( IDirectFBSurface *thiz,
DFBSurfaceBlendFunction dst )
{
DIRECT_INTERFACE_GET_DATA(IDirectFBSurface_Dispatcher)
return DFB_UNIMPLEMENTED;
}
static DFBResult
IDirectFBSurface_Dispatcher_SetPorterDuff( IDirectFBSurface *thiz,
DFBSurfacePorterDuffRule rule )
{
DIRECT_INTERFACE_GET_DATA(IDirectFBSurface_Dispatcher)
return DFB_UNIMPLEMENTED;
}
static DFBResult
IDirectFBSurface_Dispatcher_SetSrcColorKey( IDirectFBSurface *thiz,
u8 r,
u8 g,
u8 b )
{
DIRECT_INTERFACE_GET_DATA(IDirectFBSurface_Dispatcher)
return DFB_UNIMPLEMENTED;
}
static DFBResult
IDirectFBSurface_Dispatcher_SetSrcColorKeyIndex( IDirectFBSurface *thiz,
unsigned int index )
{
DIRECT_INTERFACE_GET_DATA(IDirectFBSurface_Dispatcher)
return DFB_UNIMPLEMENTED;
}
static DFBResult
IDirectFBSurface_Dispatcher_SetDstColorKey( IDirectFBSurface *thiz,
u8 r,
u8 g,
u8 b )
{
DIRECT_INTERFACE_GET_DATA(IDirectFBSurface_Dispatcher)
return DFB_UNIMPLEMENTED;
}
static DFBResult
IDirectFBSurface_Dispatcher_SetDstColorKeyIndex( IDirectFBSurface *thiz,
unsigned int index )
{
DIRECT_INTERFACE_GET_DATA(IDirectFBSurface_Dispatcher)
return DFB_UNIMPLEMENTED;
}
static DFBResult
IDirectFBSurface_Dispatcher_SetFont( IDirectFBSurface *thiz,
IDirectFBFont *font )
{
DIRECT_INTERFACE_GET_DATA(IDirectFBSurface_Dispatcher)
return DFB_UNIMPLEMENTED;
}
static DFBResult
IDirectFBSurface_Dispatcher_GetFont( IDirectFBSurface *thiz,
IDirectFBFont **font )
{
DIRECT_INTERFACE_GET_DATA(IDirectFBSurface_Dispatcher)
return DFB_UNIMPLEMENTED;
}
static DFBResult
IDirectFBSurface_Dispatcher_SetDrawingFlags( IDirectFBSurface *thiz,
DFBSurfaceDrawingFlags flags )
{
DIRECT_INTERFACE_GET_DATA(IDirectFBSurface_Dispatcher)
return DFB_UNIMPLEMENTED;
}
static DFBResult
IDirectFBSurface_Dispatcher_FillRectangle( IDirectFBSurface *thiz,
int x, int y, int w, int h )
{
DIRECT_INTERFACE_GET_DATA(IDirectFBSurface_Dispatcher)
return DFB_UNIMPLEMENTED;
}
static DFBResult
IDirectFBSurface_Dispatcher_FillRectangles( IDirectFBSurface *thiz,
const DFBRectangle *rects,
unsigned int num_rects )
{
DIRECT_INTERFACE_GET_DATA(IDirectFBSurface_Dispatcher)
return DFB_UNIMPLEMENTED;
}
static DFBResult
IDirectFBSurface_Dispatcher_FillTrapezoids( IDirectFBSurface *thiz,
const DFBTrapezoid *traps,
unsigned int num_traps )
{
DIRECT_INTERFACE_GET_DATA(IDirectFBSurface_Dispatcher)
return DFB_UNIMPLEMENTED;
}
static DFBResult
IDirectFBSurface_Dispatcher_FillSpans( IDirectFBSurface *thiz,
int y,
const DFBSpan *spans,
unsigned int num_spans )
{
DIRECT_INTERFACE_GET_DATA(IDirectFBSurface_Dispatcher)
return DFB_UNIMPLEMENTED;
}
static DFBResult
IDirectFBSurface_Dispatcher_DrawLine( IDirectFBSurface *thiz,
int x1, int y1, int x2, int y2 )
{
DIRECT_INTERFACE_GET_DATA(IDirectFBSurface_Dispatcher)
return DFB_UNIMPLEMENTED;
}
static DFBResult
IDirectFBSurface_Dispatcher_DrawLines( IDirectFBSurface *thiz,
const DFBRegion *lines,
unsigned int num_lines )
{
DIRECT_INTERFACE_GET_DATA(IDirectFBSurface_Dispatcher)
if (!lines || !num_lines)
return DFB_INVARG;
return DFB_UNIMPLEMENTED;
}
static DFBResult
IDirectFBSurface_Dispatcher_DrawRectangle( IDirectFBSurface *thiz,
int x, int y, int w, int h )
{
DIRECT_INTERFACE_GET_DATA(IDirectFBSurface_Dispatcher)
if (w<=0 || h<=0)
return DFB_INVARG;
return DFB_UNIMPLEMENTED;
}
static DFBResult
IDirectFBSurface_Dispatcher_FillTriangle( IDirectFBSurface *thiz,
int x1, int y1,
int x2, int y2,
int x3, int y3 )
{
DIRECT_INTERFACE_GET_DATA(IDirectFBSurface_Dispatcher)
return DFB_UNIMPLEMENTED;
}
static DFBResult
IDirectFBSurface_Dispatcher_SetBlittingFlags( IDirectFBSurface *thiz,
DFBSurfaceBlittingFlags flags )
{
DIRECT_INTERFACE_GET_DATA(IDirectFBSurface_Dispatcher)
return DFB_UNIMPLEMENTED;
}
static DFBResult
IDirectFBSurface_Dispatcher_Blit( IDirectFBSurface *thiz,
IDirectFBSurface *source,
const DFBRectangle *rect,
int x,
int y )
{
DIRECT_INTERFACE_GET_DATA(IDirectFBSurface_Dispatcher)
if (!source)
return DFB_INVARG;
return DFB_UNIMPLEMENTED;
}
static DFBResult
IDirectFBSurface_Dispatcher_TileBlit( IDirectFBSurface *thiz,
IDirectFBSurface *source,
const DFBRectangle *rect,
int x,
int y )
{
DIRECT_INTERFACE_GET_DATA(IDirectFBSurface_Dispatcher)
if (!source)
return DFB_INVARG;
return DFB_UNIMPLEMENTED;
}
static DFBResult
IDirectFBSurface_Dispatcher_BatchBlit( IDirectFBSurface *thiz,
IDirectFBSurface *source,
const DFBRectangle *source_rects,
const DFBPoint *dest_points,
int num )
{
DIRECT_INTERFACE_GET_DATA(IDirectFBSurface_Dispatcher)
if (!source || !source_rects || !dest_points || num < 1)
return DFB_INVARG;
return DFB_UNIMPLEMENTED;
}
static DFBResult
IDirectFBSurface_Dispatcher_StretchBlit( IDirectFBSurface *thiz,
IDirectFBSurface *source,
const DFBRectangle *source_rect,
const DFBRectangle *destination_rect )
{
DIRECT_INTERFACE_GET_DATA(IDirectFBSurface_Dispatcher)
if (!source)
return DFB_INVARG;
return DFB_UNIMPLEMENTED;
}
static DFBResult
IDirectFBSurface_Dispatcher_TextureTriangles( IDirectFBSurface *thiz,
IDirectFBSurface *source,
const DFBVertex *vertices,
const int *indices,
int num,
DFBTriangleFormation formation )
{
DIRECT_INTERFACE_GET_DATA(IDirectFBSurface_Dispatcher)
if (!source || !vertices || num < 3)
return DFB_INVARG;
return DFB_UNIMPLEMENTED;
}
static DFBResult
IDirectFBSurface_Dispatcher_DrawString( IDirectFBSurface *thiz,
const char *text, int bytes,
int x, int y,
DFBSurfaceTextFlags flags )
{
DIRECT_INTERFACE_GET_DATA(IDirectFBSurface_Dispatcher)
if (!text)
return DFB_INVARG;
return DFB_UNIMPLEMENTED;
}
static DFBResult
IDirectFBSurface_Dispatcher_DrawGlyph( IDirectFBSurface *thiz,
unsigned int index, int x, int y,
DFBSurfaceTextFlags flags )
{
DIRECT_INTERFACE_GET_DATA(IDirectFBSurface_Dispatcher)
if (!index)
return DFB_INVARG;
return DFB_UNIMPLEMENTED;
}
static DFBResult
IDirectFBSurface_Dispatcher_SetEncoding( IDirectFBSurface *thiz,
DFBTextEncodingID encoding )
{
DIRECT_INTERFACE_GET_DATA(IDirectFBSurface_Dispatcher)
return DFB_UNIMPLEMENTED;
}
static DFBResult
IDirectFBSurface_Dispatcher_GetSubSurface( IDirectFBSurface *thiz,
const DFBRectangle *rect,
IDirectFBSurface **surface )
{
DIRECT_INTERFACE_GET_DATA(IDirectFBSurface_Dispatcher)
if (!surface)
return DFB_INVARG;
return DFB_UNIMPLEMENTED;
}
static DFBResult
IDirectFBSurface_Dispatcher_GetGL( IDirectFBSurface *thiz,
IDirectFBGL **interface_ptr )
{
DIRECT_INTERFACE_GET_DATA(IDirectFBSurface_Dispatcher)
if (!interface_ptr)
return DFB_INVARG;
return DFB_UNIMPLEMENTED;
}
static DFBResult
IDirectFBSurface_Dispatcher_Dump( IDirectFBSurface *thiz,
const char *directory,
const char *prefix )
{
DIRECT_INTERFACE_GET_DATA(IDirectFBSurface_Dispatcher)
if (!directory || !prefix)
return DFB_INVARG;
return DFB_UNIMPLEMENTED;
}
static DFBResult
IDirectFBSurface_Dispatcher_DisableAcceleration( IDirectFBSurface *thiz,
DFBAccelerationMask mask )
{
DIRECT_INTERFACE_GET_DATA(IDirectFBSurface_Dispatcher)
return DFB_UNIMPLEMENTED;
}
static DFBResult
IDirectFBSurface_Dispatcher_ReleaseSource( IDirectFBSurface *thiz )
{
DIRECT_INTERFACE_GET_DATA(IDirectFBSurface_Dispatcher)
return DFB_UNIMPLEMENTED;
}
static DFBResult
IDirectFBSurface_Dispatcher_SetIndexTranslation( IDirectFBSurface *thiz,
const int *indices,
int num_indices )
{
DIRECT_INTERFACE_GET_DATA(IDirectFBSurface_Dispatcher)
return DFB_UNIMPLEMENTED;
}
/**************************************************************************************************/
static DirectResult
Dispatch_Release( IDirectFBSurface *thiz, IDirectFBSurface *real,
VoodooManager *manager, VoodooRequestMessage *msg )
{
DIRECT_INTERFACE_GET_DATA(IDirectFBSurface_Dispatcher)
return voodoo_manager_unregister_local( manager, data->self );
}
static DirectResult
Dispatch_GetPosition( IDirectFBSurface *thiz, IDirectFBSurface *real,
VoodooManager *manager, VoodooRequestMessage *msg )
{
DFBResult ret;
DFBPoint position;
DIRECT_INTERFACE_GET_DATA(IDirectFBSurface_Dispatcher)
ret = real->GetPosition( real, &position.x, &position.y );
if (ret)
return ret;
return voodoo_manager_respond( manager, true, msg->header.serial,
DFB_OK, VOODOO_INSTANCE_NONE,
VMBT_DATA, sizeof(DFBPoint), &position,
VMBT_NONE );
}
static DirectResult
Dispatch_GetSize( IDirectFBSurface *thiz, IDirectFBSurface *real,
VoodooManager *manager, VoodooRequestMessage *msg )
{
DFBResult ret;
DFBDimension dimension;
DIRECT_INTERFACE_GET_DATA(IDirectFBSurface_Dispatcher)
ret = real->GetSize( real, &dimension.w, &dimension.h );
if (ret)
return ret;
return voodoo_manager_respond( manager, true, msg->header.serial,
DFB_OK, VOODOO_INSTANCE_NONE,
VMBT_DATA, sizeof(DFBDimension), &dimension,
VMBT_NONE );
}
static DirectResult
Dispatch_GetVisibleRectangle( IDirectFBSurface *thiz, IDirectFBSurface *real,
VoodooManager *manager, VoodooRequestMessage *msg )
{
DFBResult ret;
DFBRectangle rect;
DIRECT_INTERFACE_GET_DATA(IDirectFBSurface_Dispatcher)
ret = real->GetVisibleRectangle( real, &rect );
if (ret)
return ret;
return voodoo_manager_respond( manager, true, msg->header.serial,
DFB_OK, VOODOO_INSTANCE_NONE,
VMBT_DATA, sizeof(DFBRectangle), &rect,
VMBT_NONE );
}
static DirectResult
Dispatch_GetPixelFormat( IDirectFBSurface *thiz, IDirectFBSurface *real,
VoodooManager *manager, VoodooRequestMessage *msg )
{
DFBResult ret;
DFBSurfacePixelFormat format;
DIRECT_INTERFACE_GET_DATA(IDirectFBSurface_Dispatcher)
ret = real->GetPixelFormat( real, &format );
if (ret)
return ret;
return voodoo_manager_respond( manager, true, msg->header.serial,
DFB_OK, VOODOO_INSTANCE_NONE,
VMBT_INT, format,
VMBT_NONE );
}
static DirectResult
Dispatch_GetAccelerationMask( IDirectFBSurface *thiz, IDirectFBSurface *real,
VoodooManager *manager, VoodooRequestMessage *msg )
{
DirectResult ret;
VoodooMessageParser parser;
VoodooInstanceID instance;
void *surface = NULL;
DFBAccelerationMask mask;
DIRECT_INTERFACE_GET_DATA(IDirectFBSurface_Dispatcher)
VOODOO_PARSER_BEGIN( parser, msg );
VOODOO_PARSER_GET_ID( parser, instance );
VOODOO_PARSER_END( parser );
if (instance != VOODOO_INSTANCE_NONE) {
ret = voodoo_manager_lookup_local( manager, instance, NULL, &surface );
if (ret)
return ret;
}
ret = real->GetAccelerationMask( real, surface, &mask );
if (ret)
return ret;
return voodoo_manager_respond( manager, true, msg->header.serial,
DFB_OK, VOODOO_INSTANCE_NONE,
VMBT_INT, mask,
VMBT_NONE );
}
static DirectResult
Dispatch_GetPalette( IDirectFBSurface *thiz, IDirectFBSurface *real,
VoodooManager *manager, VoodooRequestMessage *msg )
{
DirectResult ret;
IDirectFBPalette *palette;
VoodooInstanceID instance;
DIRECT_INTERFACE_GET_DATA(IDirectFBSurface_Dispatcher)
ret = real->GetPalette( real, &palette );
if (ret)
return ret;
ret = voodoo_construct_dispatcher( manager, "IDirectFBPalette", palette,
data->super, NULL, &instance, NULL );
if (ret) {
palette->Release( palette );
return ret;
}
return voodoo_manager_respond( manager, true, msg->header.serial,
DFB_OK, instance,
VMBT_NONE );
}
static DirectResult
Dispatch_SetPalette( IDirectFBSurface *thiz, IDirectFBSurface *real,
VoodooManager *manager, VoodooRequestMessage *msg )
{
DirectResult ret;
VoodooMessageParser parser;
VoodooInstanceID instance;
void *palette;
DIRECT_INTERFACE_GET_DATA(IDirectFBSurface_Dispatcher)
VOODOO_PARSER_BEGIN( parser, msg );
VOODOO_PARSER_GET_ID( parser, instance );
VOODOO_PARSER_END( parser );
ret = voodoo_manager_lookup_local( manager, instance, NULL, &palette );
if (ret)
return ret;
real->SetPalette( real, palette );
return DFB_OK;
}
static DirectResult
Dispatch_Flip( IDirectFBSurface *thiz, IDirectFBSurface *real,
VoodooManager *manager, VoodooRequestMessage *msg )
{
DirectResult ret;
VoodooMessageParser parser;
const DFBRegion *region;
DFBSurfaceFlipFlags flags;
unsigned int millis;
DIRECT_INTERFACE_GET_DATA(IDirectFBSurface_Dispatcher)
VOODOO_PARSER_BEGIN( parser, msg );
VOODOO_PARSER_GET_ODATA( parser, region );
VOODOO_PARSER_GET_INT( parser, flags );
if (data->remote)
VOODOO_PARSER_GET_UINT( parser, millis );
VOODOO_PARSER_END( parser );
ret = real->Flip( real, region, flags );
if (data->remote)
voodoo_manager_request( manager, data->remote,
IDIRECTFBSURFACE_REQUESTOR_METHOD_ID_FlipNotify, VREQ_NONE, NULL,
VMBT_UINT, millis,
VMBT_NONE );
if (flags & DSFLIP_WAIT)
return voodoo_manager_respond( manager, true, msg->header.serial,
ret, VOODOO_INSTANCE_NONE,
VMBT_NONE );
return DFB_OK;
}
static DirectResult
Dispatch_Clear( IDirectFBSurface *thiz, IDirectFBSurface *real,
VoodooManager *manager, VoodooRequestMessage *msg )
{
VoodooMessageParser parser;
const DFBColor *color;
DIRECT_INTERFACE_GET_DATA(IDirectFBSurface_Dispatcher)
VOODOO_PARSER_BEGIN( parser, msg );
VOODOO_PARSER_GET_DATA( parser, color );
VOODOO_PARSER_END( parser );
real->Clear( real, color->r, color->g, color->b, color->a );
return DFB_OK;
}
static DirectResult
Dispatch_SetClip( IDirectFBSurface *thiz, IDirectFBSurface *real,
VoodooManager *manager, VoodooRequestMessage *msg )
{
VoodooMessageParser parser;
const DFBRegion *clip;
DIRECT_INTERFACE_GET_DATA(IDirectFBSurface_Dispatcher)
VOODOO_PARSER_BEGIN( parser, msg );
VOODOO_PARSER_GET_ODATA( parser, clip );
VOODOO_PARSER_END( parser );
real->SetClip( real, clip );
return DFB_OK;
}
static DirectResult
Dispatch_SetColor( IDirectFBSurface *thiz, IDirectFBSurface *real,
VoodooManager *manager, VoodooRequestMessage *msg )
{
VoodooMessageParser parser;
const DFBColor *color;
DIRECT_INTERFACE_GET_DATA(IDirectFBSurface_Dispatcher)
VOODOO_PARSER_BEGIN( parser, msg );
VOODOO_PARSER_GET_DATA( parser, color );
VOODOO_PARSER_END( parser );
real->SetColor( real, color->r, color->g, color->b, color->a );
return DFB_OK;
}
static DirectResult
Dispatch_SetSrcColorKey( IDirectFBSurface *thiz, IDirectFBSurface *real,
VoodooManager *manager, VoodooRequestMessage *msg )
{
VoodooMessageParser parser;
const DFBColor *color;
DIRECT_INTERFACE_GET_DATA(IDirectFBSurface_Dispatcher)
VOODOO_PARSER_BEGIN( parser, msg );
VOODOO_PARSER_GET_DATA( parser, color );
VOODOO_PARSER_END( parser );
real->SetSrcColorKey( real, color->r, color->g, color->b );
return DFB_OK;
}
static DirectResult
Dispatch_SetSrcColorKeyIndex( IDirectFBSurface *thiz, IDirectFBSurface *real,
VoodooManager *manager, VoodooRequestMessage *msg )
{
VoodooMessageParser parser;
unsigned int index;
DIRECT_INTERFACE_GET_DATA(IDirectFBSurface_Dispatcher)
VOODOO_PARSER_BEGIN( parser, msg );
VOODOO_PARSER_GET_UINT( parser, index );
VOODOO_PARSER_END( parser );
real->SetSrcColorKeyIndex( real, index );
return DFB_OK;
}
static DirectResult
Dispatch_SetDstColorKey( IDirectFBSurface *thiz, IDirectFBSurface *real,
VoodooManager *manager, VoodooRequestMessage *msg )
{
VoodooMessageParser parser;
const DFBColor *color;
DIRECT_INTERFACE_GET_DATA(IDirectFBSurface_Dispatcher)
VOODOO_PARSER_BEGIN( parser, msg );
VOODOO_PARSER_GET_DATA( parser, color );
VOODOO_PARSER_END( parser );
real->SetDstColorKey( real, color->r, color->g, color->b );
return DFB_OK;
}
static DirectResult
Dispatch_SetDstColorKeyIndex( IDirectFBSurface *thiz, IDirectFBSurface *real,
VoodooManager *manager, VoodooRequestMessage *msg )
{
VoodooMessageParser parser;
unsigned int index;
DIRECT_INTERFACE_GET_DATA(IDirectFBSurface_Dispatcher)
VOODOO_PARSER_BEGIN( parser, msg );
VOODOO_PARSER_GET_UINT( parser, index );
VOODOO_PARSER_END( parser );
real->SetDstColorKeyIndex( real, index );
return DFB_OK;
}
static DirectResult
Dispatch_SetBlittingFlags( IDirectFBSurface *thiz, IDirectFBSurface *real,
VoodooManager *manager, VoodooRequestMessage *msg )
{
VoodooMessageParser parser;
DFBSurfaceBlittingFlags flags;
DIRECT_INTERFACE_GET_DATA(IDirectFBSurface_Dispatcher)
VOODOO_PARSER_BEGIN( parser, msg );
VOODOO_PARSER_GET_INT( parser, flags );
VOODOO_PARSER_END( parser );
real->SetBlittingFlags( real, flags );
return DFB_OK;
}
static DirectResult
Dispatch_Blit( IDirectFBSurface *thiz, IDirectFBSurface *real,
VoodooManager *manager, VoodooRequestMessage *msg )
{
DirectResult ret;
VoodooMessageParser parser;
VoodooInstanceID instance;
const DFBRectangle *rect;
const DFBPoint *point;
void *surface;
DIRECT_INTERFACE_GET_DATA(IDirectFBSurface_Dispatcher)
VOODOO_PARSER_BEGIN( parser, msg );
VOODOO_PARSER_GET_ID( parser, instance );
VOODOO_PARSER_GET_ODATA( parser, rect );
VOODOO_PARSER_GET_DATA( parser, point );
VOODOO_PARSER_END( parser );
ret = voodoo_manager_lookup_local( manager, instance, NULL, &surface );
if (ret)
return ret;
real->Blit( real, surface, rect, point->x, point->y );
return DFB_OK;
}
static DirectResult
Dispatch_TileBlit( IDirectFBSurface *thiz, IDirectFBSurface *real,
VoodooManager *manager, VoodooRequestMessage *msg )
{
DirectResult ret;
VoodooMessageParser parser;
VoodooInstanceID instance;
const DFBRectangle *rect;
const DFBPoint *point;
void *surface;
DIRECT_INTERFACE_GET_DATA(IDirectFBSurface_Dispatcher)
VOODOO_PARSER_BEGIN( parser, msg );
VOODOO_PARSER_GET_ID( parser, instance );
VOODOO_PARSER_GET_ODATA( parser, rect );
VOODOO_PARSER_GET_DATA( parser, point );
VOODOO_PARSER_END( parser );
ret = voodoo_manager_lookup_local( manager, instance, NULL, &surface );
if (ret)
return ret;
real->TileBlit( real, surface, rect, point->x, point->y );
return DFB_OK;
}
static DirectResult
Dispatch_BatchBlit( IDirectFBSurface *thiz, IDirectFBSurface *real,
VoodooManager *manager, VoodooRequestMessage *msg )
{
DirectResult ret;
VoodooMessageParser parser;
VoodooInstanceID instance;
unsigned int num;
const DFBRectangle *source_rects;
const DFBPoint *dest_points;
void *surface;
DIRECT_INTERFACE_GET_DATA(IDirectFBSurface_Dispatcher)
VOODOO_PARSER_BEGIN( parser, msg );
VOODOO_PARSER_GET_ID( parser, instance );
VOODOO_PARSER_GET_UINT( parser, num );
VOODOO_PARSER_GET_DATA( parser, source_rects );
VOODOO_PARSER_GET_DATA( parser, dest_points );
VOODOO_PARSER_END( parser );
ret = voodoo_manager_lookup_local( manager, instance, NULL, &surface );
if (ret)
return ret;
real->BatchBlit( real, surface, source_rects, dest_points, num );
return DFB_OK;
}
static DirectResult
Dispatch_StretchBlit( IDirectFBSurface *thiz, IDirectFBSurface *real,
VoodooManager *manager, VoodooRequestMessage *msg )
{
DirectResult ret;
VoodooMessageParser parser;
VoodooInstanceID instance;
const DFBRectangle *srect;
const DFBRectangle *drect;
void *surface;
DIRECT_INTERFACE_GET_DATA(IDirectFBSurface_Dispatcher)
VOODOO_PARSER_BEGIN( parser, msg );
VOODOO_PARSER_GET_ID( parser, instance );
VOODOO_PARSER_GET_ODATA( parser, srect );
VOODOO_PARSER_GET_ODATA( parser, drect );
VOODOO_PARSER_END( parser );
ret = voodoo_manager_lookup_local( manager, instance, NULL, &surface );
if (ret)
return ret;
real->StretchBlit( real, surface, srect, drect );
return DFB_OK;
}
static DirectResult
Dispatch_TextureTriangles( IDirectFBSurface *thiz, IDirectFBSurface *real,
VoodooManager *manager, VoodooRequestMessage *msg )
{
DirectResult ret;
VoodooMessageParser parser;
VoodooInstanceID instance;
const DFBVertex *vertices;
const int *indices;
int num;
DFBTriangleFormation formation;
void *surface;
DIRECT_INTERFACE_GET_DATA(IDirectFBSurface_Dispatcher)
VOODOO_PARSER_BEGIN( parser, msg );
VOODOO_PARSER_GET_ID( parser, instance );
VOODOO_PARSER_GET_DATA( parser, vertices );
VOODOO_PARSER_GET_ODATA( parser, indices );
VOODOO_PARSER_GET_INT( parser, num );
VOODOO_PARSER_GET_INT( parser, formation );
VOODOO_PARSER_END( parser );
ret = voodoo_manager_lookup_local( manager, instance, NULL, &surface );
if (ret)
return ret;
real->TextureTriangles( real, surface, vertices, indices, num, formation );
return DFB_OK;
}
static DirectResult
Dispatch_SetDrawingFlags( IDirectFBSurface *thiz, IDirectFBSurface *real,
VoodooManager *manager, VoodooRequestMessage *msg )
{
VoodooMessageParser parser;
DFBSurfaceDrawingFlags flags;
DIRECT_INTERFACE_GET_DATA(IDirectFBSurface_Dispatcher)
VOODOO_PARSER_BEGIN( parser, msg );
VOODOO_PARSER_GET_INT( parser, flags );
VOODOO_PARSER_END( parser );
real->SetDrawingFlags( real, flags );
return DFB_OK;
}
static DirectResult
Dispatch_FillRectangle( IDirectFBSurface *thiz, IDirectFBSurface *real,
VoodooManager *manager, VoodooRequestMessage *msg )
{
VoodooMessageParser parser;
const DFBRectangle *rect;
DIRECT_INTERFACE_GET_DATA(IDirectFBSurface_Dispatcher)
VOODOO_PARSER_BEGIN( parser, msg );
VOODOO_PARSER_GET_DATA( parser, rect );
VOODOO_PARSER_END( parser );
real->FillRectangle( real, rect->x, rect->y, rect->w, rect->h );
return DFB_OK;
}
static DirectResult
Dispatch_FillRectangles( IDirectFBSurface *thiz, IDirectFBSurface *real,
VoodooManager *manager, VoodooRequestMessage *msg )
{
VoodooMessageParser parser;
unsigned int num_rects;
const DFBRectangle *rects;
DIRECT_INTERFACE_GET_DATA(IDirectFBSurface_Dispatcher)
VOODOO_PARSER_BEGIN( parser, msg );
VOODOO_PARSER_GET_UINT( parser, num_rects );
VOODOO_PARSER_GET_DATA( parser, rects );
VOODOO_PARSER_END( parser );
real->FillRectangles( real, rects, num_rects );
return DFB_OK;
}
static DirectResult
Dispatch_FillTrapezoids( IDirectFBSurface *thiz, IDirectFBSurface *real,
VoodooManager *manager, VoodooRequestMessage *msg )
{
VoodooMessageParser parser;
unsigned int num_traps;
const DFBTrapezoid *traps;
DIRECT_INTERFACE_GET_DATA(IDirectFBSurface_Dispatcher)
VOODOO_PARSER_BEGIN( parser, msg );
VOODOO_PARSER_GET_UINT( parser, num_traps );
VOODOO_PARSER_GET_DATA( parser, traps );
VOODOO_PARSER_END( parser );
real->FillTrapezoids( real, traps, num_traps );
return DFB_OK;
}
static DirectResult
Dispatch_FillSpans( IDirectFBSurface *thiz, IDirectFBSurface *real,
VoodooManager *manager, VoodooRequestMessage *msg )
{
VoodooMessageParser parser;
int y;
unsigned int num_spans;
const DFBSpan *spans;
DIRECT_INTERFACE_GET_DATA(IDirectFBSurface_Dispatcher)
VOODOO_PARSER_BEGIN( parser, msg );
VOODOO_PARSER_GET_INT( parser, y );
VOODOO_PARSER_GET_UINT( parser, num_spans );
VOODOO_PARSER_GET_DATA( parser, spans );
VOODOO_PARSER_END( parser );
real->FillSpans( real, y, spans, num_spans );
return DFB_OK;
}
static DirectResult
Dispatch_DrawLine( IDirectFBSurface *thiz, IDirectFBSurface *real,
VoodooManager *manager, VoodooRequestMessage *msg )
{
VoodooMessageParser parser;
const DFBRegion *line;
DIRECT_INTERFACE_GET_DATA(IDirectFBSurface_Dispatcher)
VOODOO_PARSER_BEGIN( parser, msg );
VOODOO_PARSER_GET_DATA( parser, line );
VOODOO_PARSER_END( parser );
real->DrawLine( real, line->x1, line->y1, line->x2, line->y2 );
return DFB_OK;
}
static DirectResult
Dispatch_DrawLines( IDirectFBSurface *thiz, IDirectFBSurface *real,
VoodooManager *manager, VoodooRequestMessage *msg )
{
VoodooMessageParser parser;
unsigned int num_lines;
const DFBRegion *lines;
DIRECT_INTERFACE_GET_DATA(IDirectFBSurface_Dispatcher)
VOODOO_PARSER_BEGIN( parser, msg );
VOODOO_PARSER_GET_UINT( parser, num_lines );
VOODOO_PARSER_GET_DATA( parser, lines );
VOODOO_PARSER_END( parser );
real->DrawLines( real, lines, num_lines );
return DFB_OK;
}
static DirectResult
Dispatch_DrawRectangle( IDirectFBSurface *thiz, IDirectFBSurface *real,
VoodooManager *manager, VoodooRequestMessage *msg )
{
VoodooMessageParser parser;
const DFBRectangle *rect;
DIRECT_INTERFACE_GET_DATA(IDirectFBSurface_Dispatcher)
VOODOO_PARSER_BEGIN( parser, msg );
VOODOO_PARSER_GET_DATA( parser, rect );
VOODOO_PARSER_END( parser );
real->DrawRectangle( real, rect->x, rect->y, rect->w, rect->h );
return DFB_OK;
}
static DirectResult
Dispatch_FillTriangle( IDirectFBSurface *thiz, IDirectFBSurface *real,
VoodooManager *manager, VoodooRequestMessage *msg )
{
VoodooMessageParser parser;
const DFBTriangle *tri;
DIRECT_INTERFACE_GET_DATA(IDirectFBSurface_Dispatcher)
VOODOO_PARSER_BEGIN( parser, msg );
VOODOO_PARSER_GET_DATA( parser, tri );
VOODOO_PARSER_END( parser );
real->FillTriangle( real, tri->x1, tri->y1, tri->x2, tri->y2, tri->x3, tri->y3 );
return DFB_OK;
}
static DirectResult
Dispatch_SetFont( IDirectFBSurface *thiz, IDirectFBSurface *real,
VoodooManager *manager, VoodooRequestMessage *msg )
{
DirectResult ret;
VoodooMessageParser parser;
VoodooInstanceID instance;
void *font;
DIRECT_INTERFACE_GET_DATA(IDirectFBSurface_Dispatcher)
VOODOO_PARSER_BEGIN( parser, msg );
VOODOO_PARSER_GET_ID( parser, instance );
VOODOO_PARSER_END( parser );
if (instance == VOODOO_INSTANCE_NONE) {
real->SetFont( real, NULL );
return DFB_OK;
}
ret = voodoo_manager_lookup_local( manager, instance, NULL, &font );
if (ret)
return ret;
real->SetFont( real, font );
return DFB_OK;
}
static DirectResult
Dispatch_DrawString( IDirectFBSurface *thiz, IDirectFBSurface *real,
VoodooManager *manager, VoodooRequestMessage *msg )
{
VoodooMessageParser parser;
const char *text;
int bytes;
const DFBPoint *point;
DFBSurfaceTextFlags flags;
DIRECT_INTERFACE_GET_DATA(IDirectFBSurface_Dispatcher)
VOODOO_PARSER_BEGIN( parser, msg );
VOODOO_PARSER_GET_DATA( parser, text );
VOODOO_PARSER_GET_INT( parser, bytes );
VOODOO_PARSER_GET_DATA( parser, point );
VOODOO_PARSER_GET_INT( parser, flags );
VOODOO_PARSER_END( parser );
real->DrawString( real, text, bytes, point->x, point->y, flags );
return DFB_OK;
}
static DirectResult
Dispatch_DrawGlyph( IDirectFBSurface *thiz, IDirectFBSurface *real,
VoodooManager *manager, VoodooRequestMessage *msg )
{
VoodooMessageParser parser;
unsigned int index;
const DFBPoint *point;
DFBSurfaceTextFlags flags;
DIRECT_INTERFACE_GET_DATA(IDirectFBSurface_Dispatcher)
VOODOO_PARSER_BEGIN( parser, msg );
VOODOO_PARSER_GET_UINT( parser, index );
VOODOO_PARSER_GET_DATA( parser, point );
VOODOO_PARSER_GET_INT( parser, flags );
VOODOO_PARSER_END( parser );
real->DrawGlyph( real, index, point->x, point->y, flags );
return DFB_OK;
}
static DirectResult
Dispatch_SetEncoding( IDirectFBSurface *thiz, IDirectFBSurface *real,
VoodooManager *manager, VoodooRequestMessage *msg )
{
VoodooMessageParser parser;
DFBTextEncodingID encoding;
DIRECT_INTERFACE_GET_DATA(IDirectFBSurface_Dispatcher)
VOODOO_PARSER_BEGIN( parser, msg );
VOODOO_PARSER_GET_UINT( parser, encoding );
VOODOO_PARSER_END( parser );
real->SetEncoding( real, encoding );
return DFB_OK;
}
static DirectResult
Dispatch_GetSubSurface( IDirectFBSurface *thiz, IDirectFBSurface *real,
VoodooManager *manager, VoodooRequestMessage *msg )
{
DirectResult ret;
VoodooMessageParser parser;
const DFBRectangle *rect;
IDirectFBSurface *surface;
VoodooInstanceID instance;
DIRECT_INTERFACE_GET_DATA(IDirectFBSurface_Dispatcher)
VOODOO_PARSER_BEGIN( parser, msg );
VOODOO_PARSER_GET_ODATA( parser, rect );
VOODOO_PARSER_END( parser );
ret = real->GetSubSurface( real, rect, &surface );
if (ret)
return ret;
ret = voodoo_construct_dispatcher( manager, "IDirectFBSurface", surface,
data->super, NULL, &instance, NULL );
if (ret) {
surface->Release( surface );
return ret;
}
return voodoo_manager_respond( manager, true, msg->header.serial,
DFB_OK, instance,
VMBT_NONE );
}
static DirectResult
Dispatch_DisableAcceleration( IDirectFBSurface *thiz, IDirectFBSurface *real,
VoodooManager *manager, VoodooRequestMessage *msg )
{
VoodooMessageParser parser;
DFBAccelerationMask mask;
DIRECT_INTERFACE_GET_DATA(IDirectFBSurface_Dispatcher)
VOODOO_PARSER_BEGIN( parser, msg );
VOODOO_PARSER_GET_INT( parser, mask );
VOODOO_PARSER_END( parser );
real->DisableAcceleration( real, mask );
return DFB_OK;
}
static DirectResult
Dispatch_ReleaseSource( IDirectFBSurface *thiz, IDirectFBSurface *real,
VoodooManager *manager, VoodooRequestMessage *msg )
{
DIRECT_INTERFACE_GET_DATA(IDirectFBSurface_Dispatcher)
real->ReleaseSource( real );
return DFB_OK;
}
#define RLE16_KEY 0xf001
static void
rle16_decode( const u16 *src,
u16 *dst,
unsigned int num )
{
unsigned int n = 0, last, count, out = 0;
while (out < num) {
last = src[n++];
if (last == RLE16_KEY) {
count = src[n++];
if (count == RLE16_KEY) {
dst[out++] = RLE16_KEY;
}
else {
last = src[n++];
while (count >= 4) {
dst[out+0] =
dst[out+1] =
dst[out+2] =
dst[out+3] = last;
out += 4;
count -= 4;
}
while (count >= 2) {
dst[out+0] =
dst[out+1] = last;
out += 2;
count -= 2;
}
while (count--)
dst[out++] = last;
}
}
else
dst[out++] = last;
}
D_ASSERT( out == num );
}
#define RLE32_KEY 0xf0012345
static void
rle32_decode( const u32 *src,
u32 *dst,
unsigned int num )
{
unsigned int n = 0, last, count, out = 0;
while (out < num) {
last = src[n++];
if (last == RLE32_KEY) {
count = src[n++];
if (count == RLE32_KEY) {
dst[out++] = RLE32_KEY;
}
else {
last = src[n++];
while (count >= 4) {
dst[out+0] =
dst[out+1] =
dst[out+2] =
dst[out+3] = last;
out += 4;
count -= 4;
}
while (count >= 2) {
dst[out+0] =
dst[out+1] = last;
out += 2;
count -= 2;
}
while (count--)
dst[out++] = last;
}
}
else
dst[out++] = last;
}
D_ASSERT( out == num );
}
static DirectResult
Dispatch_Write( IDirectFBSurface *thiz, IDirectFBSurface *real,
VoodooManager *manager, VoodooRequestMessage *msg )
{
VoodooMessageParser parser;
unsigned int encoded;
const DFBRectangle *rect;
const void *ptr;
int pitch;
DIRECT_INTERFACE_GET_DATA(IDirectFBSurface_Dispatcher)
VOODOO_PARSER_BEGIN( parser, msg );
VOODOO_PARSER_GET_UINT( parser, encoded );
VOODOO_PARSER_GET_DATA( parser, rect );
VOODOO_PARSER_GET_DATA( parser, ptr );
VOODOO_PARSER_GET_INT( parser, pitch );
VOODOO_PARSER_END( parser );
if (encoded) {
switch (encoded) {
case 2: {
if (rect->w > 2048) {
u16 *buf = D_MALLOC( rect->w * 2 );
if (buf) {
rle16_decode( ptr, buf, rect->w );
real->Write( real, rect, buf, pitch );
D_FREE( buf );
}
else
D_OOM();
}
else {
u16 buf[2048];
rle16_decode( ptr, buf, rect->w );
real->Write( real, rect, buf, pitch );
}
break;
}
case 4: {
if (rect->w > 1024) {
u32 *buf = D_MALLOC( rect->w * 4 );
if (buf) {
rle32_decode( ptr, buf, rect->w );
real->Write( real, rect, buf, pitch );
D_FREE( buf );
}
else
D_OOM();
}
else {
u32 buf[1024];
rle32_decode( ptr, buf, rect->w );
real->Write( real, rect, buf, pitch );
}
break;
}
default:
D_UNIMPLEMENTED();
break;
}
}
else
real->Write( real, rect, ptr, pitch );
return DFB_OK;
}
#define RLE16_KEY 0xf001
static bool
rle16_encode( const u16 *src,
u16 *dst,
unsigned int num,
unsigned int *ret_num )
{
unsigned int n, last, count = 0, out = 0;
for (n=0; n<num; n++) {
if (out + 3 > num) {
*ret_num = num;
return false;
}
if (count > 0) {
D_ASSERT( src[n] == last );
count++;
}
else {
count = 1;
last = src[n];
}
if (n == num-1 || src[n+1] != last) {
if (count > 2 || (count > 1 && last == RLE16_KEY)) {
dst[out++] = RLE16_KEY;
dst[out++] = count;
dst[out++] = last;
}
else {
if (count > 1 || last == RLE16_KEY)
dst[out++] = last;
dst[out++] = last;
}
count = 0;
}
}
*ret_num = out;
return true;
}
#define RLE32_KEY 0xf0012345
static bool
rle32_encode( const u32 *src,
u32 *dst,
unsigned int num,
unsigned int *ret_num )
{
unsigned int n, last, count = 0, out = 0;
for (n=0; n<num; n++) {
if (out + 3 > num) {
*ret_num = num;
return false;
}
if (count > 0) {
D_ASSERT( src[n] == last );
count++;
}
else {
count = 1;
last = src[n];
}
if (n == num-1 || src[n+1] != last) {
if (count > 2 || (count > 1 && last == RLE32_KEY)) {
dst[out++] = RLE32_KEY;
dst[out++] = count;
dst[out++] = last;
}
else {
if (count > 1 || last == RLE32_KEY)
dst[out++] = last;
dst[out++] = last;
}
count = 0;
}
}
*ret_num = out;
return true;
}
static DirectResult
Dispatch_Read( IDirectFBSurface *thiz, IDirectFBSurface *real,
VoodooManager *manager, VoodooRequestMessage *msg )
{
DirectResult ret;
VoodooMessageParser parser;
const DFBRectangle *rect;
int len;
int y;
void *buf;
DFBSurfacePixelFormat format;
unsigned int encoded;
DIRECT_INTERFACE_GET_DATA(IDirectFBSurface_Dispatcher)
VOODOO_PARSER_BEGIN( parser, msg );
VOODOO_PARSER_GET_DATA( parser, rect );
VOODOO_PARSER_END( parser );
real->GetPixelFormat( real, &format );
len = DFB_BYTES_PER_LINE( format, rect->w );
buf = alloca( len );
switch (voodoo_config->compression_min ? DSPF_UNKNOWN : format) {
case DSPF_RGB16: {
u16 tmp[rect->w];
for (y=0; y<rect->h; y++) {
unsigned int num;
DFBRectangle r = { rect->x, rect->y + y, rect->w, 1 };
real->Read( real, &r, buf, len );
encoded = rle16_encode( buf, tmp, rect->w, &num );
ret = voodoo_manager_respond( manager, y == rect->h - 1, msg->header.serial,
DFB_OK, VOODOO_INSTANCE_NONE,
VMBT_UINT, encoded ? 2 : 0,
VMBT_DATA, DFB_BYTES_PER_LINE( format, num ),
encoded ? tmp : buf,
VMBT_NONE );
if (ret)
break;
}
break;
}
case DSPF_RGB32:
case DSPF_ARGB: {
u32 tmp[rect->w];
for (y=0; y<rect->h; y++) {
unsigned int num;
DFBRectangle r = { rect->x, rect->y + y, rect->w, 1 };
real->Read( real, &r, buf, len );
encoded = rle32_encode( buf, tmp, rect->w, &num );
ret = voodoo_manager_respond( manager, y == rect->h - 1, msg->header.serial,
DFB_OK, VOODOO_INSTANCE_NONE,
VMBT_UINT, encoded ? 4 : 0,
VMBT_DATA, DFB_BYTES_PER_LINE( format, num ),
encoded ? tmp : buf,
VMBT_NONE );
if (ret)
break;
}
break;
}
default:
for (y=0; y<rect->h; y++) {
DFBRectangle r = { rect->x, rect->y + y, rect->w, 1 };
real->Read( real, &r, buf, len );
voodoo_manager_respond( manager, y == rect->h - 1, msg->header.serial,
DFB_OK, VOODOO_INSTANCE_NONE,
VMBT_UINT, 0,
VMBT_DATA, len, buf,
VMBT_NONE );
}
break;
}
return DFB_OK;
}
static DirectResult
Dispatch_SetRenderOptions( IDirectFBSurface *thiz, IDirectFBSurface *real,
VoodooManager *manager, VoodooRequestMessage *msg )
{
VoodooMessageParser parser;
DFBSurfaceRenderOptions options;
DIRECT_INTERFACE_GET_DATA(IDirectFBSurface_Dispatcher)
VOODOO_PARSER_BEGIN( parser, msg );
VOODOO_PARSER_GET_INT( parser, options );
VOODOO_PARSER_END( parser );
real->SetRenderOptions( real, options );
return DFB_OK;
}
static DirectResult
Dispatch_SetMatrix( IDirectFBSurface *thiz, IDirectFBSurface *real,
VoodooManager *manager, VoodooRequestMessage *msg )
{
VoodooMessageParser parser;
const s32 *matrix;
DIRECT_INTERFACE_GET_DATA(IDirectFBSurface_Dispatcher)
VOODOO_PARSER_BEGIN( parser, msg );
VOODOO_PARSER_GET_DATA( parser, matrix );
VOODOO_PARSER_END( parser );
real->SetMatrix( real, matrix );
return DFB_OK;
}
static DirectResult
Dispatch_SetRemoteInstance( IDirectFBSurface *thiz, IDirectFBSurface *real,
VoodooManager *manager, VoodooRequestMessage *msg )
{
VoodooMessageParser parser;
DIRECT_INTERFACE_GET_DATA(IDirectFBSurface_Dispatcher)
VOODOO_PARSER_BEGIN( parser, msg );
VOODOO_PARSER_GET_ID( parser, data->remote );
VOODOO_PARSER_END( parser );
return voodoo_manager_respond( manager, true, msg->header.serial, DR_OK, VOODOO_INSTANCE_NONE, VMBT_NONE );
}
static DirectResult
Dispatch( void *dispatcher, void *real, VoodooManager *manager, VoodooRequestMessage *msg )
{
D_DEBUG( "IDirectFBSurface/Dispatcher: "
"Handling request for instance %u with method %u...\n", msg->instance, msg->method );
switch (msg->method) {
case IDIRECTFBSURFACE_METHOD_ID_Release:
return Dispatch_Release( dispatcher, real, manager, msg );
case IDIRECTFBSURFACE_METHOD_ID_GetPosition:
return Dispatch_GetPosition( dispatcher, real, manager, msg );
case IDIRECTFBSURFACE_METHOD_ID_GetSize:
return Dispatch_GetSize( dispatcher, real, manager, msg );
case IDIRECTFBSURFACE_METHOD_ID_GetVisibleRectangle:
return Dispatch_GetVisibleRectangle( dispatcher, real, manager, msg );
case IDIRECTFBSURFACE_METHOD_ID_GetPixelFormat:
return Dispatch_GetPixelFormat( dispatcher, real, manager, msg );
case IDIRECTFBSURFACE_METHOD_ID_GetAccelerationMask:
return Dispatch_GetAccelerationMask( dispatcher, real, manager, msg );
case IDIRECTFBSURFACE_METHOD_ID_GetPalette:
return Dispatch_GetPalette( dispatcher, real, manager, msg );
case IDIRECTFBSURFACE_METHOD_ID_SetPalette:
return Dispatch_SetPalette( dispatcher, real, manager, msg );
case IDIRECTFBSURFACE_METHOD_ID_Flip:
return Dispatch_Flip( dispatcher, real, manager, msg );
case IDIRECTFBSURFACE_METHOD_ID_Clear:
return Dispatch_Clear( dispatcher, real, manager, msg );
case IDIRECTFBSURFACE_METHOD_ID_SetClip:
return Dispatch_SetClip( dispatcher, real, manager, msg );
case IDIRECTFBSURFACE_METHOD_ID_SetColor:
return Dispatch_SetColor( dispatcher, real, manager, msg );
case IDIRECTFBSURFACE_METHOD_ID_SetSrcColorKey:
return Dispatch_SetSrcColorKey( dispatcher, real, manager, msg );
case IDIRECTFBSURFACE_METHOD_ID_SetSrcColorKeyIndex:
return Dispatch_SetSrcColorKeyIndex( dispatcher, real, manager, msg );
case IDIRECTFBSURFACE_METHOD_ID_SetDstColorKey:
return Dispatch_SetDstColorKey( dispatcher, real, manager, msg );
case IDIRECTFBSURFACE_METHOD_ID_SetDstColorKeyIndex:
return Dispatch_SetDstColorKeyIndex( dispatcher, real, manager, msg );
case IDIRECTFBSURFACE_METHOD_ID_SetBlittingFlags:
return Dispatch_SetBlittingFlags( dispatcher, real, manager, msg );
case IDIRECTFBSURFACE_METHOD_ID_Blit:
return Dispatch_Blit( dispatcher, real, manager, msg );
case IDIRECTFBSURFACE_METHOD_ID_TileBlit:
return Dispatch_TileBlit( dispatcher, real, manager, msg );
case IDIRECTFBSURFACE_METHOD_ID_BatchBlit:
return Dispatch_BatchBlit( dispatcher, real, manager, msg );
case IDIRECTFBSURFACE_METHOD_ID_StretchBlit:
return Dispatch_StretchBlit( dispatcher, real, manager, msg );
case IDIRECTFBSURFACE_METHOD_ID_TextureTriangles:
return Dispatch_TextureTriangles( dispatcher, real, manager, msg );
case IDIRECTFBSURFACE_METHOD_ID_SetDrawingFlags:
return Dispatch_SetDrawingFlags( dispatcher, real, manager, msg );
case IDIRECTFBSURFACE_METHOD_ID_FillRectangle:
return Dispatch_FillRectangle( dispatcher, real, manager, msg );
case IDIRECTFBSURFACE_METHOD_ID_DrawLine:
return Dispatch_DrawLine( dispatcher, real, manager, msg );
case IDIRECTFBSURFACE_METHOD_ID_DrawLines:
return Dispatch_DrawLines( dispatcher, real, manager, msg );
case IDIRECTFBSURFACE_METHOD_ID_DrawRectangle:
return Dispatch_DrawRectangle( dispatcher, real, manager, msg );
case IDIRECTFBSURFACE_METHOD_ID_FillTriangle:
return Dispatch_FillTriangle( dispatcher, real, manager, msg );
case IDIRECTFBSURFACE_METHOD_ID_SetFont:
return Dispatch_SetFont( dispatcher, real, manager, msg );
case IDIRECTFBSURFACE_METHOD_ID_DrawString:
return Dispatch_DrawString( dispatcher, real, manager, msg );
case IDIRECTFBSURFACE_METHOD_ID_DrawGlyph:
return Dispatch_DrawGlyph( dispatcher, real, manager, msg );
case IDIRECTFBSURFACE_METHOD_ID_SetEncoding:
return Dispatch_SetEncoding( dispatcher, real, manager, msg );
case IDIRECTFBSURFACE_METHOD_ID_GetSubSurface:
return Dispatch_GetSubSurface( dispatcher, real, manager, msg );
case IDIRECTFBSURFACE_METHOD_ID_FillRectangles:
return Dispatch_FillRectangles( dispatcher, real, manager, msg );
case IDIRECTFBSURFACE_METHOD_ID_FillTrapezoids:
return Dispatch_FillTrapezoids( dispatcher, real, manager, msg );
case IDIRECTFBSURFACE_METHOD_ID_FillSpans:
return Dispatch_FillSpans( dispatcher, real, manager, msg );
case IDIRECTFBSURFACE_METHOD_ID_DisableAcceleration:
return Dispatch_DisableAcceleration( dispatcher, real, manager, msg );
case IDIRECTFBSURFACE_METHOD_ID_ReleaseSource:
return Dispatch_ReleaseSource( dispatcher, real, manager, msg );
case IDIRECTFBSURFACE_METHOD_ID_Write:
return Dispatch_Write( dispatcher, real, manager, msg );
case IDIRECTFBSURFACE_METHOD_ID_Read:
return Dispatch_Read( dispatcher, real, manager, msg );
case IDIRECTFBSURFACE_METHOD_ID_SetRenderOptions:
return Dispatch_SetRenderOptions( dispatcher, real, manager, msg );
case IDIRECTFBSURFACE_METHOD_ID_SetMatrix:
return Dispatch_SetMatrix( dispatcher, real, manager, msg );
case IDIRECTFBSURFACE_METHOD_ID_SetRemoteInstance:
return Dispatch_SetRemoteInstance( dispatcher, real, manager, msg );
}
return DFB_NOSUCHMETHOD;
}
/**************************************************************************************************/
static DFBResult
Probe()
{
/* This implementation has to be loaded explicitly. */
return DFB_UNSUPPORTED;
}
static DFBResult
Construct( IDirectFBSurface *thiz,
IDirectFBSurface *real,
VoodooManager *manager,
VoodooInstanceID super,
void *arg, /* Optional arguments to constructor */
VoodooInstanceID *ret_instance )
{
DFBResult ret;
DIRECT_ALLOCATE_INTERFACE_DATA(thiz, IDirectFBSurface_Dispatcher)
ret = voodoo_manager_register_local( manager, super, thiz, real, Dispatch, ret_instance );
if (ret) {
DIRECT_DEALLOCATE_INTERFACE( thiz );
return ret;
}
data->ref = 1;
data->real = real;
data->super = super;
data->self = *ret_instance;
data->manager = manager;
thiz->AddRef = IDirectFBSurface_Dispatcher_AddRef;
thiz->Release = IDirectFBSurface_Dispatcher_Release;
thiz->GetCapabilities = IDirectFBSurface_Dispatcher_GetCapabilities;
thiz->GetPosition = IDirectFBSurface_Dispatcher_GetPosition;
thiz->GetSize = IDirectFBSurface_Dispatcher_GetSize;
thiz->GetVisibleRectangle = IDirectFBSurface_Dispatcher_GetVisibleRectangle;
thiz->GetPixelFormat = IDirectFBSurface_Dispatcher_GetPixelFormat;
thiz->GetAccelerationMask = IDirectFBSurface_Dispatcher_GetAccelerationMask;
thiz->GetPalette = IDirectFBSurface_Dispatcher_GetPalette;
thiz->SetPalette = IDirectFBSurface_Dispatcher_SetPalette;
thiz->SetAlphaRamp = IDirectFBSurface_Dispatcher_SetAlphaRamp;
thiz->Lock = IDirectFBSurface_Dispatcher_Lock;
thiz->GetFramebufferOffset = IDirectFBSurface_Dispatcher_GetFramebufferOffset;
thiz->GetPhysicalAddress = IDirectFBSurface_Dispatcher_GetPhysicalAddress;
thiz->Unlock = IDirectFBSurface_Dispatcher_Unlock;
thiz->Flip = IDirectFBSurface_Dispatcher_Flip;
thiz->SetField = IDirectFBSurface_Dispatcher_SetField;
thiz->Clear = IDirectFBSurface_Dispatcher_Clear;
thiz->SetClip = IDirectFBSurface_Dispatcher_SetClip;
thiz->GetClip = IDirectFBSurface_Dispatcher_GetClip;
thiz->SetColor = IDirectFBSurface_Dispatcher_SetColor;
thiz->SetColorIndex = IDirectFBSurface_Dispatcher_SetColorIndex;
thiz->SetSrcBlendFunction = IDirectFBSurface_Dispatcher_SetSrcBlendFunction;
thiz->SetDstBlendFunction = IDirectFBSurface_Dispatcher_SetDstBlendFunction;
thiz->SetPorterDuff = IDirectFBSurface_Dispatcher_SetPorterDuff;
thiz->SetSrcColorKey = IDirectFBSurface_Dispatcher_SetSrcColorKey;
thiz->SetSrcColorKeyIndex = IDirectFBSurface_Dispatcher_SetSrcColorKeyIndex;
thiz->SetDstColorKey = IDirectFBSurface_Dispatcher_SetDstColorKey;
thiz->SetDstColorKeyIndex = IDirectFBSurface_Dispatcher_SetDstColorKeyIndex;
thiz->SetBlittingFlags = IDirectFBSurface_Dispatcher_SetBlittingFlags;
thiz->Blit = IDirectFBSurface_Dispatcher_Blit;
thiz->TileBlit = IDirectFBSurface_Dispatcher_TileBlit;
thiz->BatchBlit = IDirectFBSurface_Dispatcher_BatchBlit;
thiz->StretchBlit = IDirectFBSurface_Dispatcher_StretchBlit;
thiz->TextureTriangles = IDirectFBSurface_Dispatcher_TextureTriangles;
thiz->SetDrawingFlags = IDirectFBSurface_Dispatcher_SetDrawingFlags;
thiz->FillRectangle = IDirectFBSurface_Dispatcher_FillRectangle;
thiz->FillRectangles = IDirectFBSurface_Dispatcher_FillRectangles;
thiz->FillTrapezoids = IDirectFBSurface_Dispatcher_FillTrapezoids;
thiz->FillSpans = IDirectFBSurface_Dispatcher_FillSpans;
thiz->DrawLine = IDirectFBSurface_Dispatcher_DrawLine;
thiz->DrawLines = IDirectFBSurface_Dispatcher_DrawLines;
thiz->DrawRectangle = IDirectFBSurface_Dispatcher_DrawRectangle;
thiz->FillTriangle = IDirectFBSurface_Dispatcher_FillTriangle;
thiz->SetFont = IDirectFBSurface_Dispatcher_SetFont;
thiz->GetFont = IDirectFBSurface_Dispatcher_GetFont;
thiz->DrawString = IDirectFBSurface_Dispatcher_DrawString;
thiz->DrawGlyph = IDirectFBSurface_Dispatcher_DrawGlyph;
thiz->SetEncoding = IDirectFBSurface_Dispatcher_SetEncoding;
thiz->GetSubSurface = IDirectFBSurface_Dispatcher_GetSubSurface;
thiz->GetGL = IDirectFBSurface_Dispatcher_GetGL;
thiz->Dump = IDirectFBSurface_Dispatcher_Dump;
thiz->DisableAcceleration = IDirectFBSurface_Dispatcher_DisableAcceleration;
thiz->ReleaseSource = IDirectFBSurface_Dispatcher_ReleaseSource;
thiz->SetIndexTranslation = IDirectFBSurface_Dispatcher_SetIndexTranslation;
return DFB_OK;
}
|
252140.c | /*
* testbase.c
*
* Created on: Jan 20, 2016
* Author: enerccio
*/
#include "testbase.h"
void* __kclib_open_file_u(const char* path, uint32_t mode) {
return NULL;
}
void __kclib_terminate_u(int exit_status) {
}
pid_t __kclib_get_pid_u() {
return 0;
}
thrd_t* __kclib_get_thread_structure_addr_u() {
return NULL;
}
void* __kclib_allocate(size_t aamount) {
return NULL;
}
void __kclib_deallocate(uintptr_t afrom, size_t aamount) {
}
void* __kclib_open_std_stream(uint8_t request_mode) {
return NULL;
}
ptrdiff_t __kclib_send_data(void* stream, uint8_t* array, size_t buffer_size) {
return 0;
}
ptrdiff_t __kclib_read_data(void* stream, uint8_t* buffer, size_t read_amount) {
return 0;
}
clock_t __kclib_clock() {
return 0;
}
tid_t __kclib_get_tid() {
return 0;
}
void __kclib_futex_wait(void* futex, int v) {
}
void __kclib_futex_wake(void* futex, int v) {
}
void ___exit(int x) {
__asm__ __volatile__ (
" syscall"
:
: "a"(60), "D"((long)x)
: "cc", "rcx", "r11", "memory"
);
}
void ___output(const char* message, size_t chlen, bool err) {
__asm__ __volatile__ (
" syscall"
:
: "a"(1), "D"((long)err? 2 : 0), "S" (message), "rdx" (chlen)
: "cc", "rcx", "r11", "memory"
);
__asm__ __volatile__ (
" syscall"
:
: "a"(74), "D"((long)err? 2 : 0)
: "cc", "rcx", "r11", "memory"
);
}
void shuffle(void** array, size_t l) {
for (size_t i=0; i<l-2; i++) {
size_t j = rand()%(l-i);
void* tmp = array[i];
array[i] = array[i+j];
array[i+j] = tmp;
}
}
extern int run_tests();
int testmain(int argc, char** argv) {
return run_tests();
}
|
275606.c | /*-------------------------------------------------------------------------
*
* xloginsert.c
* Functions for constructing WAL records
*
* Constructing a WAL record begins with a call to XLogBeginInsert,
* followed by a number of XLogRegister* calls. The registered data is
* collected in private working memory, and finally assembled into a chain
* of XLogRecData structs by a call to XLogRecordAssemble(). See
* access/transam/README for details.
*
* Portions Copyright (c) 1996-2020, PostgreSQL Global Development Group
* Portions Copyright (c) 1994, Regents of the University of California
*
* src/backend/access/transam/xloginsert.c
*
*-------------------------------------------------------------------------
*/
#include "postgres.h"
#include "access/xact.h"
#include "access/xlog.h"
#include "access/xlog_internal.h"
#include "access/xloginsert.h"
#include "catalog/pg_control.h"
#include "common/pg_lzcompress.h"
#include "executor/instrument.h"
#include "miscadmin.h"
#include "pg_trace.h"
#include "replication/origin.h"
#include "storage/bufmgr.h"
#include "storage/proc.h"
#include "utils/memutils.h"
/* Buffer size required to store a compressed version of backup block image */
#define PGLZ_MAX_BLCKSZ PGLZ_MAX_OUTPUT(BLCKSZ)
/*
* For each block reference registered with XLogRegisterBuffer, we fill in
* a registered_buffer struct.
*/
typedef struct
{
bool in_use; /* is this slot in use? */
uint8 flags; /* REGBUF_* flags */
RelFileNode rnode; /* identifies the relation and block */
ForkNumber forkno;
BlockNumber block;
Page page; /* page content */
uint32 rdata_len; /* total length of data in rdata chain */
XLogRecData *rdata_head; /* head of the chain of data registered with
* this block */
XLogRecData *rdata_tail; /* last entry in the chain, or &rdata_head if
* empty */
XLogRecData bkp_rdatas[2]; /* temporary rdatas used to hold references to
* backup block data in XLogRecordAssemble() */
/* buffer to store a compressed version of backup block image */
char compressed_page[PGLZ_MAX_BLCKSZ];
} registered_buffer;
static registered_buffer *registered_buffers;
static int max_registered_buffers; /* allocated size */
static int max_registered_block_id = 0; /* highest block_id + 1 currently
* registered */
/*
* A chain of XLogRecDatas to hold the "main data" of a WAL record, registered
* with XLogRegisterData(...).
*/
static XLogRecData *mainrdata_head;
static XLogRecData *mainrdata_last = (XLogRecData *) &mainrdata_head;
static uint32 mainrdata_len; /* total # of bytes in chain */
/* flags for the in-progress insertion */
static uint8 curinsert_flags = 0;
/*
* These are used to hold the record header while constructing a record.
* 'hdr_scratch' is not a plain variable, but is palloc'd at initialization,
* because we want it to be MAXALIGNed and padding bytes zeroed.
*
* For simplicity, it's allocated large enough to hold the headers for any
* WAL record.
*/
static XLogRecData hdr_rdt;
static char *hdr_scratch = NULL;
#define SizeOfXlogOrigin (sizeof(RepOriginId) + sizeof(char))
#define SizeOfXLogTransactionId (sizeof(TransactionId) + sizeof(char))
#define HEADER_SCRATCH_SIZE \
(SizeOfXLogRecord + \
MaxSizeOfXLogRecordBlockHeader * (XLR_MAX_BLOCK_ID + 1) + \
SizeOfXLogRecordDataHeaderLong + SizeOfXlogOrigin + \
SizeOfXLogTransactionId)
/*
* An array of XLogRecData structs, to hold registered data.
*/
static XLogRecData *rdatas;
static int num_rdatas; /* entries currently used */
static int max_rdatas; /* allocated size */
static bool begininsert_called = false;
/* Memory context to hold the registered buffer and data references. */
static MemoryContext xloginsert_cxt;
static XLogRecData *XLogRecordAssemble(RmgrId rmid, uint8 info,
XLogRecPtr RedoRecPtr, bool doPageWrites,
XLogRecPtr *fpw_lsn, int *num_fpi);
static bool XLogCompressBackupBlock(char *page, uint16 hole_offset,
uint16 hole_length, char *dest, uint16 *dlen);
/*
* Begin constructing a WAL record. This must be called before the
* XLogRegister* functions and XLogInsert().
*/
void
XLogBeginInsert(void)
{
Assert(max_registered_block_id == 0);
Assert(mainrdata_last == (XLogRecData *) &mainrdata_head);
Assert(mainrdata_len == 0);
/* cross-check on whether we should be here or not */
if (!XLogInsertAllowed())
elog(ERROR, "cannot make new WAL entries during recovery");
if (begininsert_called)
elog(ERROR, "XLogBeginInsert was already called");
begininsert_called = true;
}
/*
* Ensure that there are enough buffer and data slots in the working area,
* for subsequent XLogRegisterBuffer, XLogRegisterData and XLogRegisterBufData
* calls.
*
* There is always space for a small number of buffers and data chunks, enough
* for most record types. This function is for the exceptional cases that need
* more.
*/
void
XLogEnsureRecordSpace(int max_block_id, int ndatas)
{
int nbuffers;
/*
* This must be called before entering a critical section, because
* allocating memory inside a critical section can fail. repalloc() will
* check the same, but better to check it here too so that we fail
* consistently even if the arrays happen to be large enough already.
*/
Assert(CritSectionCount == 0);
/* the minimum values can't be decreased */
if (max_block_id < XLR_NORMAL_MAX_BLOCK_ID)
max_block_id = XLR_NORMAL_MAX_BLOCK_ID;
if (ndatas < XLR_NORMAL_RDATAS)
ndatas = XLR_NORMAL_RDATAS;
if (max_block_id > XLR_MAX_BLOCK_ID)
elog(ERROR, "maximum number of WAL record block references exceeded");
nbuffers = max_block_id + 1;
if (nbuffers > max_registered_buffers)
{
registered_buffers = (registered_buffer *)
repalloc(registered_buffers, sizeof(registered_buffer) * nbuffers);
/*
* At least the padding bytes in the structs must be zeroed, because
* they are included in WAL data, but initialize it all for tidiness.
*/
MemSet(®istered_buffers[max_registered_buffers], 0,
(nbuffers - max_registered_buffers) * sizeof(registered_buffer));
max_registered_buffers = nbuffers;
}
if (ndatas > max_rdatas)
{
rdatas = (XLogRecData *) repalloc(rdatas, sizeof(XLogRecData) * ndatas);
max_rdatas = ndatas;
}
}
/*
* Reset WAL record construction buffers.
*/
void
XLogResetInsertion(void)
{
int i;
/* reset the subxact assignment flag (if needed) */
if (curinsert_flags & XLOG_INCLUDE_XID)
MarkSubTransactionAssigned();
for (i = 0; i < max_registered_block_id; i++)
registered_buffers[i].in_use = false;
num_rdatas = 0;
max_registered_block_id = 0;
mainrdata_len = 0;
mainrdata_last = (XLogRecData *) &mainrdata_head;
curinsert_flags = 0;
begininsert_called = false;
}
/*
* Register a reference to a buffer with the WAL record being constructed.
* This must be called for every page that the WAL-logged operation modifies.
*/
void
XLogRegisterBuffer(uint8 block_id, Buffer buffer, uint8 flags)
{
registered_buffer *regbuf;
/* NO_IMAGE doesn't make sense with FORCE_IMAGE */
Assert(!((flags & REGBUF_FORCE_IMAGE) && (flags & (REGBUF_NO_IMAGE))));
Assert(begininsert_called);
if (block_id >= max_registered_block_id)
{
if (block_id >= max_registered_buffers)
elog(ERROR, "too many registered buffers");
max_registered_block_id = block_id + 1;
}
regbuf = ®istered_buffers[block_id];
BufferGetTag(buffer, ®buf->rnode, ®buf->forkno, ®buf->block);
regbuf->page = BufferGetPage(buffer);
regbuf->flags = flags;
regbuf->rdata_tail = (XLogRecData *) ®buf->rdata_head;
regbuf->rdata_len = 0;
/*
* Check that this page hasn't already been registered with some other
* block_id.
*/
#ifdef USE_ASSERT_CHECKING
{
int i;
for (i = 0; i < max_registered_block_id; i++)
{
registered_buffer *regbuf_old = ®istered_buffers[i];
if (i == block_id || !regbuf_old->in_use)
continue;
Assert(!RelFileNodeEquals(regbuf_old->rnode, regbuf->rnode) ||
regbuf_old->forkno != regbuf->forkno ||
regbuf_old->block != regbuf->block);
}
}
#endif
regbuf->in_use = true;
}
/*
* Like XLogRegisterBuffer, but for registering a block that's not in the
* shared buffer pool (i.e. when you don't have a Buffer for it).
*/
void
XLogRegisterBlock(uint8 block_id, RelFileNode *rnode, ForkNumber forknum,
BlockNumber blknum, Page page, uint8 flags)
{
registered_buffer *regbuf;
/* This is currently only used to WAL-log a full-page image of a page */
Assert(flags & REGBUF_FORCE_IMAGE);
Assert(begininsert_called);
if (block_id >= max_registered_block_id)
max_registered_block_id = block_id + 1;
if (block_id >= max_registered_buffers)
elog(ERROR, "too many registered buffers");
regbuf = ®istered_buffers[block_id];
regbuf->rnode = *rnode;
regbuf->forkno = forknum;
regbuf->block = blknum;
regbuf->page = page;
regbuf->flags = flags;
regbuf->rdata_tail = (XLogRecData *) ®buf->rdata_head;
regbuf->rdata_len = 0;
/*
* Check that this page hasn't already been registered with some other
* block_id.
*/
#ifdef USE_ASSERT_CHECKING
{
int i;
for (i = 0; i < max_registered_block_id; i++)
{
registered_buffer *regbuf_old = ®istered_buffers[i];
if (i == block_id || !regbuf_old->in_use)
continue;
Assert(!RelFileNodeEquals(regbuf_old->rnode, regbuf->rnode) ||
regbuf_old->forkno != regbuf->forkno ||
regbuf_old->block != regbuf->block);
}
}
#endif
regbuf->in_use = true;
}
/*
* Add data to the WAL record that's being constructed.
*
* The data is appended to the "main chunk", available at replay with
* XLogRecGetData().
*/
void
XLogRegisterData(char *data, int len)
{
XLogRecData *rdata;
Assert(begininsert_called);
if (num_rdatas >= max_rdatas)
elog(ERROR, "too much WAL data");
rdata = &rdatas[num_rdatas++];
rdata->data = data;
rdata->len = len;
/*
* we use the mainrdata_last pointer to track the end of the chain, so no
* need to clear 'next' here.
*/
mainrdata_last->next = rdata;
mainrdata_last = rdata;
mainrdata_len += len;
}
/*
* Add buffer-specific data to the WAL record that's being constructed.
*
* Block_id must reference a block previously registered with
* XLogRegisterBuffer(). If this is called more than once for the same
* block_id, the data is appended.
*
* The maximum amount of data that can be registered per block is 65535
* bytes. That should be plenty; if you need more than BLCKSZ bytes to
* reconstruct the changes to the page, you might as well just log a full
* copy of it. (the "main data" that's not associated with a block is not
* limited)
*/
void
XLogRegisterBufData(uint8 block_id, char *data, int len)
{
registered_buffer *regbuf;
XLogRecData *rdata;
Assert(begininsert_called);
/* find the registered buffer struct */
regbuf = ®istered_buffers[block_id];
if (!regbuf->in_use)
elog(ERROR, "no block with id %d registered with WAL insertion",
block_id);
if (num_rdatas >= max_rdatas)
elog(ERROR, "too much WAL data");
rdata = &rdatas[num_rdatas++];
rdata->data = data;
rdata->len = len;
regbuf->rdata_tail->next = rdata;
regbuf->rdata_tail = rdata;
regbuf->rdata_len += len;
}
/*
* Set insert status flags for the upcoming WAL record.
*
* The flags that can be used here are:
* - XLOG_INCLUDE_ORIGIN, to determine if the replication origin should be
* included in the record.
* - XLOG_MARK_UNIMPORTANT, to signal that the record is not important for
* durability, which allows to avoid triggering WAL archiving and other
* background activity.
*/
void
XLogSetRecordFlags(uint8 flags)
{
Assert(begininsert_called);
curinsert_flags |= flags;
}
/*
* Insert an XLOG record having the specified RMID and info bytes, with the
* body of the record being the data and buffer references registered earlier
* with XLogRegister* calls.
*
* Returns XLOG pointer to end of record (beginning of next record).
* This can be used as LSN for data pages affected by the logged action.
* (LSN is the XLOG point up to which the XLOG must be flushed to disk
* before the data page can be written out. This implements the basic
* WAL rule "write the log before the data".)
*/
XLogRecPtr
XLogInsert(RmgrId rmid, uint8 info)
{
XLogRecPtr EndPos;
/* XLogBeginInsert() must have been called. */
if (!begininsert_called)
elog(ERROR, "XLogBeginInsert was not called");
/*
* The caller can set rmgr bits, XLR_SPECIAL_REL_UPDATE and
* XLR_CHECK_CONSISTENCY; the rest are reserved for use by me.
*/
if ((info & ~(XLR_RMGR_INFO_MASK |
XLR_SPECIAL_REL_UPDATE |
XLR_CHECK_CONSISTENCY)) != 0)
elog(PANIC, "invalid xlog info mask %02X", info);
TRACE_POSTGRESQL_WAL_INSERT(rmid, info);
/*
* In bootstrap mode, we don't actually log anything but XLOG resources;
* return a phony record pointer.
*/
if (IsBootstrapProcessingMode() && rmid != RM_XLOG_ID)
{
XLogResetInsertion();
EndPos = SizeOfXLogLongPHD; /* start of 1st chkpt record */
return EndPos;
}
do
{
XLogRecPtr RedoRecPtr;
bool doPageWrites;
XLogRecPtr fpw_lsn;
XLogRecData *rdt;
int num_fpi = 0;
/*
* Get values needed to decide whether to do full-page writes. Since
* we don't yet have an insertion lock, these could change under us,
* but XLogInsertRecord will recheck them once it has a lock.
*/
GetFullPageWriteInfo(&RedoRecPtr, &doPageWrites);
rdt = XLogRecordAssemble(rmid, info, RedoRecPtr, doPageWrites,
&fpw_lsn, &num_fpi);
EndPos = XLogInsertRecord(rdt, fpw_lsn, curinsert_flags, num_fpi);
} while (EndPos == InvalidXLogRecPtr);
XLogResetInsertion();
return EndPos;
}
/*
* Assemble a WAL record from the registered data and buffers into an
* XLogRecData chain, ready for insertion with XLogInsertRecord().
*
* The record header fields are filled in, except for the xl_prev field. The
* calculated CRC does not include the record header yet.
*
* If there are any registered buffers, and a full-page image was not taken
* of all of them, *fpw_lsn is set to the lowest LSN among such pages. This
* signals that the assembled record is only good for insertion on the
* assumption that the RedoRecPtr and doPageWrites values were up-to-date.
*/
static XLogRecData *
XLogRecordAssemble(RmgrId rmid, uint8 info,
XLogRecPtr RedoRecPtr, bool doPageWrites,
XLogRecPtr *fpw_lsn, int *num_fpi)
{
XLogRecData *rdt;
uint32 total_len = 0;
int block_id;
pg_crc32c rdata_crc;
registered_buffer *prev_regbuf = NULL;
XLogRecData *rdt_datas_last;
XLogRecord *rechdr;
char *scratch = hdr_scratch;
/*
* Note: this function can be called multiple times for the same record.
* All the modifications we do to the rdata chains below must handle that.
*/
/* The record begins with the fixed-size header */
rechdr = (XLogRecord *) scratch;
scratch += SizeOfXLogRecord;
hdr_rdt.next = NULL;
rdt_datas_last = &hdr_rdt;
hdr_rdt.data = hdr_scratch;
/*
* Enforce consistency checks for this record if user is looking for it.
* Do this before at the beginning of this routine to give the possibility
* for callers of XLogInsert() to pass XLR_CHECK_CONSISTENCY directly for
* a record.
*/
if (wal_consistency_checking[rmid])
info |= XLR_CHECK_CONSISTENCY;
/*
* Make an rdata chain containing all the data portions of all block
* references. This includes the data for full-page images. Also append
* the headers for the block references in the scratch buffer.
*/
*fpw_lsn = InvalidXLogRecPtr;
for (block_id = 0; block_id < max_registered_block_id; block_id++)
{
registered_buffer *regbuf = ®istered_buffers[block_id];
bool needs_backup;
bool needs_data;
XLogRecordBlockHeader bkpb;
XLogRecordBlockImageHeader bimg;
XLogRecordBlockCompressHeader cbimg = {0};
bool samerel;
bool is_compressed = false;
bool include_image;
if (!regbuf->in_use)
continue;
/* Determine if this block needs to be backed up */
if (regbuf->flags & REGBUF_FORCE_IMAGE)
needs_backup = true;
else if (regbuf->flags & REGBUF_NO_IMAGE)
needs_backup = false;
else if (!doPageWrites)
needs_backup = false;
else
{
/*
* We assume page LSN is first data on *every* page that can be
* passed to XLogInsert, whether it has the standard page layout
* or not.
*/
XLogRecPtr page_lsn = PageGetLSN(regbuf->page);
needs_backup = (page_lsn <= RedoRecPtr);
if (!needs_backup)
{
if (*fpw_lsn == InvalidXLogRecPtr || page_lsn < *fpw_lsn)
*fpw_lsn = page_lsn;
}
}
/* Determine if the buffer data needs to included */
if (regbuf->rdata_len == 0)
needs_data = false;
else if ((regbuf->flags & REGBUF_KEEP_DATA) != 0)
needs_data = true;
else
needs_data = !needs_backup;
bkpb.id = block_id;
bkpb.fork_flags = regbuf->forkno;
bkpb.data_length = 0;
if ((regbuf->flags & REGBUF_WILL_INIT) == REGBUF_WILL_INIT)
bkpb.fork_flags |= BKPBLOCK_WILL_INIT;
/*
* If needs_backup is true or WAL checking is enabled for current
* resource manager, log a full-page write for the current block.
*/
include_image = needs_backup || (info & XLR_CHECK_CONSISTENCY) != 0;
if (include_image)
{
Page page = regbuf->page;
uint16 compressed_len = 0;
/*
* The page needs to be backed up, so calculate its hole length
* and offset.
*/
if (regbuf->flags & REGBUF_STANDARD)
{
/* Assume we can omit data between pd_lower and pd_upper */
uint16 lower = ((PageHeader) page)->pd_lower;
uint16 upper = ((PageHeader) page)->pd_upper;
if (lower >= SizeOfPageHeaderData &&
upper > lower &&
upper <= BLCKSZ)
{
bimg.hole_offset = lower;
cbimg.hole_length = upper - lower;
}
else
{
/* No "hole" to remove */
bimg.hole_offset = 0;
cbimg.hole_length = 0;
}
}
else
{
/* Not a standard page header, don't try to eliminate "hole" */
bimg.hole_offset = 0;
cbimg.hole_length = 0;
}
/*
* Try to compress a block image if wal_compression is enabled
*/
if (wal_compression)
{
is_compressed =
XLogCompressBackupBlock(page, bimg.hole_offset,
cbimg.hole_length,
regbuf->compressed_page,
&compressed_len);
}
/*
* Fill in the remaining fields in the XLogRecordBlockHeader
* struct
*/
bkpb.fork_flags |= BKPBLOCK_HAS_IMAGE;
/* Report a full page image constructed for the WAL record */
*num_fpi += 1;
/*
* Construct XLogRecData entries for the page content.
*/
rdt_datas_last->next = ®buf->bkp_rdatas[0];
rdt_datas_last = rdt_datas_last->next;
bimg.bimg_info = (cbimg.hole_length == 0) ? 0 : BKPIMAGE_HAS_HOLE;
/*
* If WAL consistency checking is enabled for the resource manager
* of this WAL record, a full-page image is included in the record
* for the block modified. During redo, the full-page is replayed
* only if BKPIMAGE_APPLY is set.
*/
if (needs_backup)
bimg.bimg_info |= BKPIMAGE_APPLY;
if (is_compressed)
{
bimg.length = compressed_len;
bimg.bimg_info |= BKPIMAGE_IS_COMPRESSED;
rdt_datas_last->data = regbuf->compressed_page;
rdt_datas_last->len = compressed_len;
}
else
{
bimg.length = BLCKSZ - cbimg.hole_length;
if (cbimg.hole_length == 0)
{
rdt_datas_last->data = page;
rdt_datas_last->len = BLCKSZ;
}
else
{
/* must skip the hole */
rdt_datas_last->data = page;
rdt_datas_last->len = bimg.hole_offset;
rdt_datas_last->next = ®buf->bkp_rdatas[1];
rdt_datas_last = rdt_datas_last->next;
rdt_datas_last->data =
page + (bimg.hole_offset + cbimg.hole_length);
rdt_datas_last->len =
BLCKSZ - (bimg.hole_offset + cbimg.hole_length);
}
}
total_len += bimg.length;
}
if (needs_data)
{
/*
* Link the caller-supplied rdata chain for this buffer to the
* overall list.
*/
bkpb.fork_flags |= BKPBLOCK_HAS_DATA;
bkpb.data_length = regbuf->rdata_len;
total_len += regbuf->rdata_len;
rdt_datas_last->next = regbuf->rdata_head;
rdt_datas_last = regbuf->rdata_tail;
}
if (prev_regbuf && RelFileNodeEquals(regbuf->rnode, prev_regbuf->rnode))
{
samerel = true;
bkpb.fork_flags |= BKPBLOCK_SAME_REL;
}
else
samerel = false;
prev_regbuf = regbuf;
/* Ok, copy the header to the scratch buffer */
memcpy(scratch, &bkpb, SizeOfXLogRecordBlockHeader);
scratch += SizeOfXLogRecordBlockHeader;
if (include_image)
{
memcpy(scratch, &bimg, SizeOfXLogRecordBlockImageHeader);
scratch += SizeOfXLogRecordBlockImageHeader;
if (cbimg.hole_length != 0 && is_compressed)
{
memcpy(scratch, &cbimg,
SizeOfXLogRecordBlockCompressHeader);
scratch += SizeOfXLogRecordBlockCompressHeader;
}
}
if (!samerel)
{
memcpy(scratch, ®buf->rnode, sizeof(RelFileNode));
scratch += sizeof(RelFileNode);
}
memcpy(scratch, ®buf->block, sizeof(BlockNumber));
scratch += sizeof(BlockNumber);
}
/* followed by the record's origin, if any */
if ((curinsert_flags & XLOG_INCLUDE_ORIGIN) &&
replorigin_session_origin != InvalidRepOriginId)
{
*(scratch++) = (char) XLR_BLOCK_ID_ORIGIN;
memcpy(scratch, &replorigin_session_origin, sizeof(replorigin_session_origin));
scratch += sizeof(replorigin_session_origin);
}
/* followed by toplevel XID, if not already included in previous record */
if (IsSubTransactionAssignmentPending())
{
TransactionId xid = GetTopTransactionIdIfAny();
/* update the flag (later used by XLogResetInsertion) */
XLogSetRecordFlags(XLOG_INCLUDE_XID);
*(scratch++) = (char) XLR_BLOCK_ID_TOPLEVEL_XID;
memcpy(scratch, &xid, sizeof(TransactionId));
scratch += sizeof(TransactionId);
}
/* followed by main data, if any */
if (mainrdata_len > 0)
{
if (mainrdata_len > 255)
{
*(scratch++) = (char) XLR_BLOCK_ID_DATA_LONG;
memcpy(scratch, &mainrdata_len, sizeof(uint32));
scratch += sizeof(uint32);
}
else
{
*(scratch++) = (char) XLR_BLOCK_ID_DATA_SHORT;
*(scratch++) = (uint8) mainrdata_len;
}
rdt_datas_last->next = mainrdata_head;
rdt_datas_last = mainrdata_last;
total_len += mainrdata_len;
}
rdt_datas_last->next = NULL;
hdr_rdt.len = (scratch - hdr_scratch);
total_len += hdr_rdt.len;
/*
* Calculate CRC of the data
*
* Note that the record header isn't added into the CRC initially since we
* don't know the prev-link yet. Thus, the CRC will represent the CRC of
* the whole record in the order: rdata, then backup blocks, then record
* header.
*/
INIT_CRC32C(rdata_crc);
COMP_CRC32C(rdata_crc, hdr_scratch + SizeOfXLogRecord, hdr_rdt.len - SizeOfXLogRecord);
for (rdt = hdr_rdt.next; rdt != NULL; rdt = rdt->next)
COMP_CRC32C(rdata_crc, rdt->data, rdt->len);
/*
* Fill in the fields in the record header. Prev-link is filled in later,
* once we know where in the WAL the record will be inserted. The CRC does
* not include the record header yet.
*/
rechdr->xl_xid = GetCurrentTransactionIdIfAny();
rechdr->xl_tot_len = total_len;
rechdr->xl_info = info;
rechdr->xl_rmid = rmid;
rechdr->xl_prev = InvalidXLogRecPtr;
rechdr->xl_crc = rdata_crc;
return &hdr_rdt;
}
/*
* Create a compressed version of a backup block image.
*
* Returns false if compression fails (i.e., compressed result is actually
* bigger than original). Otherwise, returns true and sets 'dlen' to
* the length of compressed block image.
*/
static bool
XLogCompressBackupBlock(char *page, uint16 hole_offset, uint16 hole_length,
char *dest, uint16 *dlen)
{
int32 orig_len = BLCKSZ - hole_length;
int32 len;
int32 extra_bytes = 0;
char *source;
PGAlignedBlock tmp;
if (hole_length != 0)
{
/* must skip the hole */
source = tmp.data;
memcpy(source, page, hole_offset);
memcpy(source + hole_offset,
page + (hole_offset + hole_length),
BLCKSZ - (hole_length + hole_offset));
/*
* Extra data needs to be stored in WAL record for the compressed
* version of block image if the hole exists.
*/
extra_bytes = SizeOfXLogRecordBlockCompressHeader;
}
else
source = page;
/*
* We recheck the actual size even if pglz_compress() reports success and
* see if the number of bytes saved by compression is larger than the
* length of extra data needed for the compressed version of block image.
*/
len = pglz_compress(source, orig_len, dest, PGLZ_strategy_default);
if (len >= 0 &&
len + extra_bytes < orig_len)
{
*dlen = (uint16) len; /* successful compression */
return true;
}
return false;
}
/*
* Determine whether the buffer referenced has to be backed up.
*
* Since we don't yet have the insert lock, fullPageWrites and forcePageWrites
* could change later, so the result should be used for optimization purposes
* only.
*/
bool
XLogCheckBufferNeedsBackup(Buffer buffer)
{
XLogRecPtr RedoRecPtr;
bool doPageWrites;
Page page;
GetFullPageWriteInfo(&RedoRecPtr, &doPageWrites);
page = BufferGetPage(buffer);
if (doPageWrites && PageGetLSN(page) <= RedoRecPtr)
return true; /* buffer requires backup */
return false; /* buffer does not need to be backed up */
}
/*
* Write a backup block if needed when we are setting a hint. Note that
* this may be called for a variety of page types, not just heaps.
*
* Callable while holding just share lock on the buffer content.
*
* We can't use the plain backup block mechanism since that relies on the
* Buffer being exclusively locked. Since some modifications (setting LSN, hint
* bits) are allowed in a sharelocked buffer that can lead to wal checksum
* failures. So instead we copy the page and insert the copied data as normal
* record data.
*
* We only need to do something if page has not yet been full page written in
* this checkpoint round. The LSN of the inserted wal record is returned if we
* had to write, InvalidXLogRecPtr otherwise.
*
* It is possible that multiple concurrent backends could attempt to write WAL
* records. In that case, multiple copies of the same block would be recorded
* in separate WAL records by different backends, though that is still OK from
* a correctness perspective.
*/
XLogRecPtr
XLogSaveBufferForHint(Buffer buffer, bool buffer_std)
{
XLogRecPtr recptr = InvalidXLogRecPtr;
XLogRecPtr lsn;
XLogRecPtr RedoRecPtr;
/*
* Ensure no checkpoint can change our view of RedoRecPtr.
*/
Assert(MyProc->delayChkpt);
/*
* Update RedoRecPtr so that we can make the right decision
*/
RedoRecPtr = GetRedoRecPtr();
/*
* We assume page LSN is first data on *every* page that can be passed to
* XLogInsert, whether it has the standard page layout or not. Since we're
* only holding a share-lock on the page, we must take the buffer header
* lock when we look at the LSN.
*/
lsn = BufferGetLSNAtomic(buffer);
if (lsn <= RedoRecPtr)
{
int flags;
PGAlignedBlock copied_buffer;
char *origdata = (char *) BufferGetBlock(buffer);
RelFileNode rnode;
ForkNumber forkno;
BlockNumber blkno;
/*
* Copy buffer so we don't have to worry about concurrent hint bit or
* lsn updates. We assume pd_lower/upper cannot be changed without an
* exclusive lock, so the contents bkp are not racy.
*/
if (buffer_std)
{
/* Assume we can omit data between pd_lower and pd_upper */
Page page = BufferGetPage(buffer);
uint16 lower = ((PageHeader) page)->pd_lower;
uint16 upper = ((PageHeader) page)->pd_upper;
memcpy(copied_buffer.data, origdata, lower);
memcpy(copied_buffer.data + upper, origdata + upper, BLCKSZ - upper);
}
else
memcpy(copied_buffer.data, origdata, BLCKSZ);
XLogBeginInsert();
flags = REGBUF_FORCE_IMAGE;
if (buffer_std)
flags |= REGBUF_STANDARD;
BufferGetTag(buffer, &rnode, &forkno, &blkno);
XLogRegisterBlock(0, &rnode, forkno, blkno, copied_buffer.data, flags);
recptr = XLogInsert(RM_XLOG_ID, XLOG_FPI_FOR_HINT);
}
return recptr;
}
/*
* Write a WAL record containing a full image of a page. Caller is responsible
* for writing the page to disk after calling this routine.
*
* Note: If you're using this function, you should be building pages in private
* memory and writing them directly to smgr. If you're using buffers, call
* log_newpage_buffer instead.
*
* If the page follows the standard page layout, with a PageHeader and unused
* space between pd_lower and pd_upper, set 'page_std' to true. That allows
* the unused space to be left out from the WAL record, making it smaller.
*/
XLogRecPtr
log_newpage(RelFileNode *rnode, ForkNumber forkNum, BlockNumber blkno,
Page page, bool page_std)
{
int flags;
XLogRecPtr recptr;
flags = REGBUF_FORCE_IMAGE;
if (page_std)
flags |= REGBUF_STANDARD;
XLogBeginInsert();
XLogRegisterBlock(0, rnode, forkNum, blkno, page, flags);
recptr = XLogInsert(RM_XLOG_ID, XLOG_FPI);
/*
* The page may be uninitialized. If so, we can't set the LSN because that
* would corrupt the page.
*/
if (!PageIsNew(page))
{
PageSetLSN(page, recptr);
}
return recptr;
}
/*
* Like log_newpage(), but allows logging multiple pages in one operation.
* It is more efficient than calling log_newpage() for each page separately,
* because we can write multiple pages in a single WAL record.
*/
void
log_newpages(RelFileNode *rnode, ForkNumber forkNum, int num_pages,
BlockNumber *blknos, Page *pages, bool page_std)
{
int flags;
XLogRecPtr recptr;
int i;
int j;
flags = REGBUF_FORCE_IMAGE;
if (page_std)
flags |= REGBUF_STANDARD;
/*
* Iterate over all the pages. They are collected into batches of
* XLR_MAX_BLOCK_ID pages, and a single WAL-record is written for each
* batch.
*/
XLogEnsureRecordSpace(XLR_MAX_BLOCK_ID - 1, 0);
i = 0;
while (i < num_pages)
{
int batch_start = i;
int nbatch;
XLogBeginInsert();
nbatch = 0;
while (nbatch < XLR_MAX_BLOCK_ID && i < num_pages)
{
XLogRegisterBlock(nbatch, rnode, forkNum, blknos[i], pages[i], flags);
i++;
nbatch++;
}
recptr = XLogInsert(RM_XLOG_ID, XLOG_FPI);
for (j = batch_start; j < i; j++)
{
/*
* The page may be uninitialized. If so, we can't set the LSN because that
* would corrupt the page.
*/
if (!PageIsNew(pages[j]))
{
PageSetLSN(pages[j], recptr);
}
}
}
}
/*
* Write a WAL record containing a full image of a page.
*
* Caller should initialize the buffer and mark it dirty before calling this
* function. This function will set the page LSN.
*
* If the page follows the standard page layout, with a PageHeader and unused
* space between pd_lower and pd_upper, set 'page_std' to true. That allows
* the unused space to be left out from the WAL record, making it smaller.
*/
XLogRecPtr
log_newpage_buffer(Buffer buffer, bool page_std)
{
Page page = BufferGetPage(buffer);
RelFileNode rnode;
ForkNumber forkNum;
BlockNumber blkno;
/* Shared buffers should be modified in a critical section. */
Assert(CritSectionCount > 0);
BufferGetTag(buffer, &rnode, &forkNum, &blkno);
return log_newpage(&rnode, forkNum, blkno, page, page_std);
}
/*
* WAL-log a range of blocks in a relation.
*
* An image of all pages with block numbers 'startblk' <= X < 'endblk' is
* written to the WAL. If the range is large, this is done in multiple WAL
* records.
*
* If all page follows the standard page layout, with a PageHeader and unused
* space between pd_lower and pd_upper, set 'page_std' to true. That allows
* the unused space to be left out from the WAL records, making them smaller.
*
* NOTE: This function acquires exclusive-locks on the pages. Typically, this
* is used on a newly-built relation, and the caller is holding a
* AccessExclusiveLock on it, so no other backend can be accessing it at the
* same time. If that's not the case, you must ensure that this does not
* cause a deadlock through some other means.
*/
void
log_newpage_range(Relation rel, ForkNumber forkNum,
BlockNumber startblk, BlockNumber endblk,
bool page_std)
{
int flags;
BlockNumber blkno;
flags = REGBUF_FORCE_IMAGE;
if (page_std)
flags |= REGBUF_STANDARD;
/*
* Iterate over all the pages in the range. They are collected into
* batches of XLR_MAX_BLOCK_ID pages, and a single WAL-record is written
* for each batch.
*/
XLogEnsureRecordSpace(XLR_MAX_BLOCK_ID - 1, 0);
blkno = startblk;
while (blkno < endblk)
{
Buffer bufpack[XLR_MAX_BLOCK_ID];
XLogRecPtr recptr;
int nbufs;
int i;
CHECK_FOR_INTERRUPTS();
/* Collect a batch of blocks. */
nbufs = 0;
while (nbufs < XLR_MAX_BLOCK_ID && blkno < endblk)
{
Buffer buf = ReadBufferExtended(rel, forkNum, blkno,
RBM_NORMAL, NULL);
LockBuffer(buf, BUFFER_LOCK_EXCLUSIVE);
/*
* Completely empty pages are not WAL-logged. Writing a WAL record
* would change the LSN, and we don't want that. We want the page
* to stay empty.
*/
if (!PageIsNew(BufferGetPage(buf)))
bufpack[nbufs++] = buf;
else
UnlockReleaseBuffer(buf);
blkno++;
}
/* Write WAL record for this batch. */
XLogBeginInsert();
START_CRIT_SECTION();
for (i = 0; i < nbufs; i++)
{
XLogRegisterBuffer(i, bufpack[i], flags);
MarkBufferDirty(bufpack[i]);
}
recptr = XLogInsert(RM_XLOG_ID, XLOG_FPI);
for (i = 0; i < nbufs; i++)
{
PageSetLSN(BufferGetPage(bufpack[i]), recptr);
UnlockReleaseBuffer(bufpack[i]);
}
END_CRIT_SECTION();
}
}
/*
* Allocate working buffers needed for WAL record construction.
*/
void
InitXLogInsert(void)
{
/* Initialize the working areas */
if (xloginsert_cxt == NULL)
{
xloginsert_cxt = AllocSetContextCreate(TopMemoryContext,
"WAL record construction",
ALLOCSET_DEFAULT_SIZES);
}
if (registered_buffers == NULL)
{
registered_buffers = (registered_buffer *)
MemoryContextAllocZero(xloginsert_cxt,
sizeof(registered_buffer) * (XLR_NORMAL_MAX_BLOCK_ID + 1));
max_registered_buffers = XLR_NORMAL_MAX_BLOCK_ID + 1;
}
if (rdatas == NULL)
{
rdatas = MemoryContextAlloc(xloginsert_cxt,
sizeof(XLogRecData) * XLR_NORMAL_RDATAS);
max_rdatas = XLR_NORMAL_RDATAS;
}
/*
* Allocate a buffer to hold the header information for a WAL record.
*/
if (hdr_scratch == NULL)
hdr_scratch = MemoryContextAllocZero(xloginsert_cxt,
HEADER_SCRATCH_SIZE);
}
|
373665.c | // © 2013, Eric Shook, CIGI, University of Illinois at Urbana-Champaign. All rights reserved.
#include "hdr.h"
// Global variables
mpistruct *mpi;
envstruct *env;
agentsstruct *agents;
simstruct *sim;
simstruct simstr;
int main(int argc, char **argv) {
mpistruct mpistr;
envstruct envstr;
agentsstruct agentsstr;
double iterstart,iterstop;
// Initialize global variables
mpi=&mpistr;
env=&envstr;
agents=&agentsstr;
sim=&simstr;
// Initialize sim,agents,env,mpi
init(argc,argv);
// Run the simulation
iterstart=MPI_Wtime();
for(sim->iteration=0;sim->iteration<sim->maxiter;sim->iteration++) {
MPI_Pcontrol(1,"iteration");
MPI_Pcontrol(1,"sim");
simupdate();
MPI_Pcontrol(-1,"sim");
MPI_Pcontrol(1,"env");
envupdate();
MPI_Pcontrol(-1,"env");
MPI_Pcontrol(1,"agent");
agentsupdate();
MPI_Pcontrol(-1,"agent");
MPI_Pcontrol(-1,"iteration");
}
// Make sure all cores are finished
MPI_Barrier(MPI_COMM_WORLD);
iterstop=MPI_Wtime();
EXEC0(printf("Iteration time=%f\n",iterstop-iterstart));
// Cleanup
del();
return 0;
}
void EXIT() {
if(sim->iteration<sim->maxiter) {
printf("EXITing\n");
MPI_Abort(MPI_COMM_WORLD,-1);
del();
} else {
EXEC0(printf("Simulation exiting ...\n"));
EXEC0(printf("IPM captures simulation performance characteristics, please refer to documentation for compilation instructions\n"));
}
}
int init(int argc, char **argv) {
siminit(argc,argv);
mpiinit();
envinit();
agentsinit();
atexit(&EXIT); // exit at the end
}
int del() {
agentsdel();
envdel();
mpidel();
simdel();
}
int DIE(char *str) {
printf(" [ Died : %s ]\n",str);
del();
return 13;
}
|
354123.c | /* The following is the NetBSD libc qsort implementation modified in order to
* support partial sorting of ranges for Redis.
*
* Copyright(C) 2009 Salvatore Sanfilippo. All rights reserved.
*
* The original copyright notice follows. */
/* $NetBSD: qsort.c,v 1.19 2009/01/30 23:38:44 lukem Exp $ */
/*-
* Copyright (c) 1992, 1993
* The Regents of the University of California. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the 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.
*/
#include <sys/types.h>
#include <assert.h>
#include <errno.h>
#include <stdlib.h>
static inline char *med3 (char *, char *, char *,
int (*)(const void *, const void *));
static inline void swapfunc (char *, char *, size_t, int);
#define min(a, b) (a) < (b) ? a : b
/*
* Qsort routine from Bentley & McIlroy's "Engineering a Sort Function".
*/
#define swapcode(TYPE, parmi, parmj, n) { \
size_t i = (n) / sizeof (TYPE); \
TYPE *pi = (TYPE *)(void *)(parmi); \
TYPE *pj = (TYPE *)(void *)(parmj); \
do { \
TYPE t = *pi; \
*pi++ = *pj; \
*pj++ = t; \
} while (--i > 0); \
}
#define SWAPINIT(a, es) swaptype = ((char *)a - (char *)0) % sizeof(long) || \
es % sizeof(long) ? 2 : es == sizeof(long)? 0 : 1;
static inline void
swapfunc(char *a, char *b, size_t n, int swaptype)
{
if (swaptype <= 1)
swapcode(long, a, b, n)
else
swapcode(char, a, b, n)
}
#define swap(a, b) \
if (swaptype == 0) { \
long t = *(long *)(void *)(a); \
*(long *)(void *)(a) = *(long *)(void *)(b); \
*(long *)(void *)(b) = t; \
} else \
swapfunc(a, b, es, swaptype)
#define vecswap(a, b, n) if ((n) > 0) swapfunc((a), (b), (size_t)(n), swaptype)
static inline char *
med3(char *a, char *b, char *c,
int (*cmp) (const void *, const void *))
{
return cmp(a, b) < 0 ?
(cmp(b, c) < 0 ? b : (cmp(a, c) < 0 ? c : a ))
:(cmp(b, c) > 0 ? b : (cmp(a, c) < 0 ? a : c ));
}
static void
_pqsort(void *a, size_t n, size_t es,
int (*cmp) (const void *, const void *), void *lrange, void *rrange)
{
char *pa, *pb, *pc, *pd, *pl, *pm, *pn;
size_t d, r;
int swaptype, swap_cnt, cmp_result;
loop: SWAPINIT(a, es);
swap_cnt = 0;
if (n < 7) {
for (pm = (char *) a + es; pm < (char *) a + n * es; pm += es)
for (pl = pm; pl > (char *) a && cmp(pl - es, pl) > 0;
pl -= es)
swap(pl, pl - es);
return;
}
pm = (char *) a + (n / 2) * es;
if (n > 7) {
pl = (char *) a;
pn = (char *) a + (n - 1) * es;
if (n > 40) {
d = (n / 8) * es;
pl = med3(pl, pl + d, pl + 2 * d, cmp);
pm = med3(pm - d, pm, pm + d, cmp);
pn = med3(pn - 2 * d, pn - d, pn, cmp);
}
pm = med3(pl, pm, pn, cmp);
}
swap(a, pm);
pa = pb = (char *) a + es;
pc = pd = (char *) a + (n - 1) * es;
for (;;) {
while (pb <= pc && (cmp_result = cmp(pb, a)) <= 0) {
if (cmp_result == 0) {
swap_cnt = 1;
swap(pa, pb);
pa += es;
}
pb += es;
}
while (pb <= pc && (cmp_result = cmp(pc, a)) >= 0) {
if (cmp_result == 0) {
swap_cnt = 1;
swap(pc, pd);
pd -= es;
}
pc -= es;
}
if (pb > pc)
break;
swap(pb, pc);
swap_cnt = 1;
pb += es;
pc -= es;
}
if (swap_cnt == 0) { /* Switch to insertion sort */
for (pm = (char *) a + es; pm < (char *) a + n * es; pm += es)
for (pl = pm; pl > (char *) a && cmp(pl - es, pl) > 0;
pl -= es)
swap(pl, pl - es);
return;
}
pn = (char *) a + n * es;
r = min(pa - (char *) a, pb - pa);
vecswap(a, pb - r, r);
r = min((size_t)(pd - pc), pn - pd - es);
vecswap(pb, pn - r, r);
if ((r = pb - pa) > es) {
void *_l = a, *_r = ((unsigned char*)a)+r-1;
if (!((lrange < _l && rrange < _l) ||
(lrange > _r && rrange > _r)))
_pqsort(a, r / es, es, cmp, lrange, rrange);
}
if ((r = pd - pc) > es) {
void *_l, *_r;
/* Iterate rather than recurse to save stack space */
a = pn - r;
n = r / es;
_l = a;
_r = ((unsigned char*)a)+r-1;
if (!((lrange < _l && rrange < _l) ||
(lrange > _r && rrange > _r)))
goto loop;
}
/* qsort(pn - r, r / es, es, cmp);*/
}
void
pqsort(void *a, size_t n, size_t es,
int (*cmp) (const void *, const void *), size_t lrange, size_t rrange)
{
_pqsort(a,n,es,cmp,((unsigned char*)a)+(lrange*es),
((unsigned char*)a)+((rrange+1)*es)-1);
}
|
114371.c | /*
* Stack-less Just-In-Time compiler
*
* Copyright Zoltan Herczeg ([email protected]). All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are
* permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this list
* of conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER(S) AND CONTRIBUTORS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
* SHALL THE COPYRIGHT HOLDER(S) 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.
*/
/* ppc 32-bit arch dependent functions. */
static sljit_s32 load_immediate(struct sljit_compiler *compiler, sljit_s32 reg, sljit_sw imm)
{
if (imm <= SIMM_MAX && imm >= SIMM_MIN)
return push_inst(compiler, ADDI | D(reg) | A(0) | IMM(imm));
if (!(imm & ~0xffff))
return push_inst(compiler, ORI | S(TMP_ZERO) | A(reg) | IMM(imm));
FAIL_IF(push_inst(compiler, ADDIS | D(reg) | A(0) | IMM(imm >> 16)));
return (imm & 0xffff) ? push_inst(compiler, ORI | S(reg) | A(reg) | IMM(imm)) : SLJIT_SUCCESS;
}
#define INS_CLEAR_LEFT(dst, src, from) \
(RLWINM | S(src) | A(dst) | ((from) << 6) | (31 << 1))
static SLJIT_INLINE sljit_s32 emit_single_op(struct sljit_compiler *compiler, sljit_s32 op, sljit_s32 flags,
sljit_s32 dst, sljit_s32 src1, sljit_s32 src2)
{
switch (op) {
case SLJIT_MOV:
case SLJIT_MOV_U32:
case SLJIT_MOV_S32:
case SLJIT_MOV_P:
SLJIT_ASSERT(src1 == TMP_REG1);
if (dst != src2)
return push_inst(compiler, OR | S(src2) | A(dst) | B(src2));
return SLJIT_SUCCESS;
case SLJIT_MOV_U8:
case SLJIT_MOV_S8:
SLJIT_ASSERT(src1 == TMP_REG1);
if ((flags & (REG_DEST | REG2_SOURCE)) == (REG_DEST | REG2_SOURCE)) {
if (op == SLJIT_MOV_S8)
return push_inst(compiler, EXTSB | S(src2) | A(dst));
return push_inst(compiler, INS_CLEAR_LEFT(dst, src2, 24));
}
else if ((flags & REG_DEST) && op == SLJIT_MOV_S8)
return push_inst(compiler, EXTSB | S(src2) | A(dst));
else {
SLJIT_ASSERT(dst == src2);
}
return SLJIT_SUCCESS;
case SLJIT_MOV_U16:
case SLJIT_MOV_S16:
SLJIT_ASSERT(src1 == TMP_REG1);
if ((flags & (REG_DEST | REG2_SOURCE)) == (REG_DEST | REG2_SOURCE)) {
if (op == SLJIT_MOV_S16)
return push_inst(compiler, EXTSH | S(src2) | A(dst));
return push_inst(compiler, INS_CLEAR_LEFT(dst, src2, 16));
}
else {
SLJIT_ASSERT(dst == src2);
}
return SLJIT_SUCCESS;
case SLJIT_NOT:
SLJIT_ASSERT(src1 == TMP_REG1);
return push_inst(compiler, NOR | RC(flags) | S(src2) | A(dst) | B(src2));
case SLJIT_NEG:
SLJIT_ASSERT(src1 == TMP_REG1);
/* Setting XER SO is not enough, CR SO is also needed. */
return push_inst(compiler, NEG | OE((flags & ALT_FORM1) ? ALT_SET_FLAGS : 0) | RC(flags) | D(dst) | A(src2));
case SLJIT_CLZ:
SLJIT_ASSERT(src1 == TMP_REG1);
return push_inst(compiler, CNTLZW | S(src2) | A(dst));
case SLJIT_ADD:
if (flags & ALT_FORM1) {
/* Setting XER SO is not enough, CR SO is also needed. */
return push_inst(compiler, ADD | OE(ALT_SET_FLAGS) | RC(ALT_SET_FLAGS) | D(dst) | A(src1) | B(src2));
}
if (flags & ALT_FORM2) {
/* Flags does not set: BIN_IMM_EXTS unnecessary. */
SLJIT_ASSERT(src2 == TMP_REG2);
if (flags & ALT_FORM3)
return push_inst(compiler, ADDIS | D(dst) | A(src1) | compiler->imm);
if (flags & ALT_FORM4) {
FAIL_IF(push_inst(compiler, ADDIS | D(dst) | A(src1) | (((compiler->imm >> 16) & 0xffff) + ((compiler->imm >> 15) & 0x1))));
src1 = dst;
}
return push_inst(compiler, ADDI | D(dst) | A(src1) | (compiler->imm & 0xffff));
}
if (flags & ALT_FORM3) {
SLJIT_ASSERT(src2 == TMP_REG2);
return push_inst(compiler, ADDIC | D(dst) | A(src1) | compiler->imm);
}
if (!(flags & ALT_SET_FLAGS))
return push_inst(compiler, ADD | D(dst) | A(src1) | B(src2));
if (flags & ALT_FORM4)
return push_inst(compiler, ADDC | RC(ALT_SET_FLAGS) | D(dst) | A(src1) | B(src2));
return push_inst(compiler, ADD | RC(flags) | D(dst) | A(src1) | B(src2));
case SLJIT_ADDC:
return push_inst(compiler, ADDE | D(dst) | A(src1) | B(src2));
case SLJIT_SUB:
if (flags & ALT_FORM1) {
if (flags & ALT_FORM2) {
FAIL_IF(push_inst(compiler, CMPLI | CRD(0) | A(src1) | compiler->imm));
if (!(flags & ALT_FORM3))
return SLJIT_SUCCESS;
return push_inst(compiler, ADDI | D(dst) | A(src1) | (-compiler->imm & 0xffff));
}
FAIL_IF(push_inst(compiler, CMPL | CRD(0) | A(src1) | B(src2)));
if (!(flags & ALT_FORM3))
return SLJIT_SUCCESS;
return push_inst(compiler, SUBF | D(dst) | A(src2) | B(src1));
}
if (flags & ALT_FORM2) {
/* Setting XER SO is not enough, CR SO is also needed. */
return push_inst(compiler, SUBF | OE(ALT_SET_FLAGS) | RC(ALT_SET_FLAGS) | D(dst) | A(src2) | B(src1));
}
if (flags & ALT_FORM3) {
/* Flags does not set: BIN_IMM_EXTS unnecessary. */
SLJIT_ASSERT(src2 == TMP_REG2);
return push_inst(compiler, SUBFIC | D(dst) | A(src1) | compiler->imm);
}
if (flags & ALT_FORM4) {
if (flags & ALT_FORM5) {
SLJIT_ASSERT(src2 == TMP_REG2);
return push_inst(compiler, CMPI | CRD(0) | A(src1) | compiler->imm);
}
return push_inst(compiler, CMP | CRD(0) | A(src1) | B(src2));
}
if (!(flags & ALT_SET_FLAGS))
return push_inst(compiler, SUBF | D(dst) | A(src2) | B(src1));
if (flags & ALT_FORM5)
return push_inst(compiler, SUBFC | RC(ALT_SET_FLAGS) | D(dst) | A(src2) | B(src1));
return push_inst(compiler, SUBF | RC(flags) | D(dst) | A(src2) | B(src1));
case SLJIT_SUBC:
return push_inst(compiler, SUBFE | D(dst) | A(src2) | B(src1));
case SLJIT_MUL:
if (flags & ALT_FORM1) {
SLJIT_ASSERT(src2 == TMP_REG2);
return push_inst(compiler, MULLI | D(dst) | A(src1) | compiler->imm);
}
return push_inst(compiler, MULLW | OE(flags) | RC(flags) | D(dst) | A(src2) | B(src1));
case SLJIT_AND:
if (flags & ALT_FORM1) {
SLJIT_ASSERT(src2 == TMP_REG2);
return push_inst(compiler, ANDI | S(src1) | A(dst) | compiler->imm);
}
if (flags & ALT_FORM2) {
SLJIT_ASSERT(src2 == TMP_REG2);
return push_inst(compiler, ANDIS | S(src1) | A(dst) | compiler->imm);
}
return push_inst(compiler, AND | RC(flags) | S(src1) | A(dst) | B(src2));
case SLJIT_OR:
if (flags & ALT_FORM1) {
SLJIT_ASSERT(src2 == TMP_REG2);
return push_inst(compiler, ORI | S(src1) | A(dst) | compiler->imm);
}
if (flags & ALT_FORM2) {
SLJIT_ASSERT(src2 == TMP_REG2);
return push_inst(compiler, ORIS | S(src1) | A(dst) | compiler->imm);
}
if (flags & ALT_FORM3) {
SLJIT_ASSERT(src2 == TMP_REG2);
FAIL_IF(push_inst(compiler, ORI | S(src1) | A(dst) | IMM(compiler->imm)));
return push_inst(compiler, ORIS | S(dst) | A(dst) | IMM(compiler->imm >> 16));
}
return push_inst(compiler, OR | RC(flags) | S(src1) | A(dst) | B(src2));
case SLJIT_XOR:
if (flags & ALT_FORM1) {
SLJIT_ASSERT(src2 == TMP_REG2);
return push_inst(compiler, XORI | S(src1) | A(dst) | compiler->imm);
}
if (flags & ALT_FORM2) {
SLJIT_ASSERT(src2 == TMP_REG2);
return push_inst(compiler, XORIS | S(src1) | A(dst) | compiler->imm);
}
if (flags & ALT_FORM3) {
SLJIT_ASSERT(src2 == TMP_REG2);
FAIL_IF(push_inst(compiler, XORI | S(src1) | A(dst) | IMM(compiler->imm)));
return push_inst(compiler, XORIS | S(dst) | A(dst) | IMM(compiler->imm >> 16));
}
return push_inst(compiler, XOR | RC(flags) | S(src1) | A(dst) | B(src2));
case SLJIT_SHL:
if (flags & ALT_FORM1) {
SLJIT_ASSERT(src2 == TMP_REG2);
compiler->imm &= 0x1f;
return push_inst(compiler, RLWINM | RC(flags) | S(src1) | A(dst) | (compiler->imm << 11) | ((31 - compiler->imm) << 1));
}
return push_inst(compiler, SLW | RC(flags) | S(src1) | A(dst) | B(src2));
case SLJIT_LSHR:
if (flags & ALT_FORM1) {
SLJIT_ASSERT(src2 == TMP_REG2);
compiler->imm &= 0x1f;
return push_inst(compiler, RLWINM | RC(flags) | S(src1) | A(dst) | (((32 - compiler->imm) & 0x1f) << 11) | (compiler->imm << 6) | (31 << 1));
}
return push_inst(compiler, SRW | RC(flags) | S(src1) | A(dst) | B(src2));
case SLJIT_ASHR:
if (flags & ALT_FORM1) {
SLJIT_ASSERT(src2 == TMP_REG2);
compiler->imm &= 0x1f;
return push_inst(compiler, SRAWI | RC(flags) | S(src1) | A(dst) | (compiler->imm << 11));
}
return push_inst(compiler, SRAW | RC(flags) | S(src1) | A(dst) | B(src2));
}
SLJIT_UNREACHABLE();
return SLJIT_SUCCESS;
}
static SLJIT_INLINE sljit_s32 emit_const(struct sljit_compiler *compiler, sljit_s32 reg, sljit_sw init_value)
{
FAIL_IF(push_inst(compiler, ADDIS | D(reg) | A(0) | IMM(init_value >> 16)));
return push_inst(compiler, ORI | S(reg) | A(reg) | IMM(init_value));
}
SLJIT_API_FUNC_ATTRIBUTE void sljit_set_jump_addr(sljit_uw addr, sljit_uw new_target, sljit_sw executable_offset)
{
sljit_ins *inst = (sljit_ins *)addr;
inst[0] = (inst[0] & 0xffff0000) | ((new_target >> 16) & 0xffff);
inst[1] = (inst[1] & 0xffff0000) | (new_target & 0xffff);
inst = (sljit_ins *)SLJIT_ADD_EXEC_OFFSET(inst, executable_offset);
SLJIT_CACHE_FLUSH(inst, inst + 2);
}
SLJIT_API_FUNC_ATTRIBUTE void sljit_set_const(sljit_uw addr, sljit_sw new_constant, sljit_sw executable_offset)
{
sljit_ins *inst = (sljit_ins *)addr;
inst[0] = (inst[0] & 0xffff0000) | ((new_constant >> 16) & 0xffff);
inst[1] = (inst[1] & 0xffff0000) | (new_constant & 0xffff);
inst = (sljit_ins *)SLJIT_ADD_EXEC_OFFSET(inst, executable_offset);
SLJIT_CACHE_FLUSH(inst, inst + 2);
}
|
133437.c | /*-
* Copyright (c) 2006 Verdens Gang AS
* Copyright (c) 2006-2015 Varnish Software AS
* All rights reserved.
*
* Author: Poul-Henning Kamp <[email protected]>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
#include "config.h"
#include "cache_varnishd.h"
#include "cache_filter.h"
#include "cache_objhead.h"
#include "hash/hash_slinger.h"
#include "storage/storage.h"
#include "vcl.h"
#include "vtim.h"
/*--------------------------------------------------------------------
* Allocate an object, with fall-back to Transient.
* XXX: This somewhat overlaps the stuff in stevedore.c
* XXX: Should this be merged over there ?
*/
static int
vbf_allocobj(struct busyobj *bo, unsigned l)
{
struct objcore *oc;
const struct stevedore *stv;
vtim_dur lifetime;
CHECK_OBJ_NOTNULL(bo, BUSYOBJ_MAGIC);
oc = bo->fetch_objcore;
CHECK_OBJ_NOTNULL(oc, OBJCORE_MAGIC);
lifetime = oc->ttl + oc->grace + oc->keep;
if (bo->uncacheable || lifetime < cache_param->shortlived)
stv = stv_transient;
else
stv = bo->storage;
bo->storage = NULL;
if (stv == NULL)
return (0);
if (STV_NewObject(bo->wrk, bo->fetch_objcore, stv, l))
return (1);
if (stv == stv_transient)
return (0);
/*
* Try to salvage the transaction by allocating a shortlived object
* on Transient storage.
*/
if (oc->ttl > cache_param->shortlived)
oc->ttl = cache_param->shortlived;
oc->grace = 0.0;
oc->keep = 0.0;
return (STV_NewObject(bo->wrk, bo->fetch_objcore, stv_transient, l));
}
static void
vbf_cleanup(struct busyobj *bo)
{
struct vfp_ctx *vfc;
CHECK_OBJ_NOTNULL(bo, BUSYOBJ_MAGIC);
vfc = bo->vfc;
CHECK_OBJ_NOTNULL(vfc, VFP_CTX_MAGIC);
VFP_Close(vfc);
bo->filter_list = NULL;
if (bo->director_state != DIR_S_NULL)
VDI_Finish(bo);
}
void Bereq_Rollback(struct busyobj *bo)
{
CHECK_OBJ_NOTNULL(bo, BUSYOBJ_MAGIC);
vbf_cleanup(bo);
VCL_TaskLeave(bo->privs);
VCL_TaskEnter(bo->privs);
HTTP_Clone(bo->bereq, bo->bereq0);
WS_Reset(bo->bereq->ws, bo->ws_bo);
WS_Reset(bo->ws, bo->ws_bo);
}
/*--------------------------------------------------------------------
* Turn the beresp into a obj
*/
static int
vbf_beresp2obj(struct busyobj *bo)
{
unsigned l, l2;
const char *b;
uint8_t *bp;
struct vsb *vary = NULL;
int varyl = 0;
l = 0;
/* Create Vary instructions */
if (!(bo->fetch_objcore->flags & OC_F_PRIVATE)) {
varyl = VRY_Create(bo, &vary);
if (varyl > 0) {
AN(vary);
assert(varyl == VSB_len(vary));
l += PRNDUP((intptr_t)varyl);
} else if (varyl < 0) {
/*
* Vary parse error
* Complain about it, and make this a pass.
*/
VSLb(bo->vsl, SLT_Error,
"Illegal 'Vary' header from backend, "
"making this a pass.");
bo->uncacheable = 1;
AZ(vary);
} else
/* No vary */
AZ(vary);
}
l2 = http_EstimateWS(bo->beresp,
bo->uncacheable ? HTTPH_A_PASS : HTTPH_A_INS);
l += l2;
if (bo->uncacheable)
bo->fetch_objcore->flags |= OC_F_HFM;
if (!vbf_allocobj(bo, l)) {
if (vary != NULL)
VSB_destroy(&vary);
AZ(vary);
return (-1);
}
if (vary != NULL) {
AN(ObjSetAttr(bo->wrk, bo->fetch_objcore, OA_VARY, varyl,
VSB_data(vary)));
VSB_destroy(&vary);
}
AZ(ObjSetU32(bo->wrk, bo->fetch_objcore, OA_VXID, VXID(bo->vsl->wid)));
/* for HTTP_Encode() VSLH call */
bo->beresp->logtag = SLT_ObjMethod;
/* Filter into object */
bp = ObjSetAttr(bo->wrk, bo->fetch_objcore, OA_HEADERS, l2, NULL);
AN(bp);
HTTP_Encode(bo->beresp, bp, l2,
bo->uncacheable ? HTTPH_A_PASS : HTTPH_A_INS);
if (http_GetHdr(bo->beresp, H_Last_Modified, &b))
AZ(ObjSetDouble(bo->wrk, bo->fetch_objcore, OA_LASTMODIFIED,
VTIM_parse(b)));
else
AZ(ObjSetDouble(bo->wrk, bo->fetch_objcore, OA_LASTMODIFIED,
floor(bo->fetch_objcore->t_origin)));
return (0);
}
/*--------------------------------------------------------------------
* Copy req->bereq and release req if no body
*/
static enum fetch_step
vbf_stp_mkbereq(struct worker *wrk, struct busyobj *bo)
{
const char *q;
CHECK_OBJ_NOTNULL(wrk, WORKER_MAGIC);
CHECK_OBJ_NOTNULL(bo, BUSYOBJ_MAGIC);
CHECK_OBJ_NOTNULL(bo->req, REQ_MAGIC);
assert(bo->fetch_objcore->boc->state == BOS_INVALID);
AZ(bo->storage);
HTTP_Setup(bo->bereq0, bo->ws, bo->vsl, SLT_BereqMethod);
http_FilterReq(bo->bereq0, bo->req->http,
bo->do_pass ? HTTPH_R_PASS : HTTPH_R_FETCH);
if (bo->do_pass)
AZ(bo->stale_oc);
else {
http_ForceField(bo->bereq0, HTTP_HDR_METHOD, "GET");
if (cache_param->http_gzip_support)
http_ForceHeader(bo->bereq0, H_Accept_Encoding, "gzip");
}
http_ForceField(bo->bereq0, HTTP_HDR_PROTO, "HTTP/1.1");
http_CopyHome(bo->bereq0);
if (bo->stale_oc != NULL &&
ObjCheckFlag(bo->wrk, bo->stale_oc, OF_IMSCAND) &&
(bo->stale_oc->boc != NULL || ObjGetLen(wrk, bo->stale_oc) != 0)) {
AZ(bo->stale_oc->flags & (OC_F_HFM|OC_F_PRIVATE));
q = HTTP_GetHdrPack(bo->wrk, bo->stale_oc, H_Last_Modified);
if (q != NULL)
http_PrintfHeader(bo->bereq0,
"If-Modified-Since: %s", q);
q = HTTP_GetHdrPack(bo->wrk, bo->stale_oc, H_ETag);
if (q != NULL)
http_PrintfHeader(bo->bereq0,
"If-None-Match: %s", q);
}
HTTP_Setup(bo->bereq, bo->ws, bo->vsl, SLT_BereqMethod);
bo->ws_bo = WS_Snapshot(bo->ws);
HTTP_Clone(bo->bereq, bo->bereq0);
if (bo->req->req_body_status == REQ_BODY_NONE) {
bo->req = NULL;
ObjSetState(bo->wrk, bo->fetch_objcore, BOS_REQ_DONE);
}
return (F_STP_STARTFETCH);
}
/*--------------------------------------------------------------------
* Start a new VSL transaction and try again
* Prepare the busyobj and fetch processors
*/
static enum fetch_step
vbf_stp_retry(struct worker *wrk, struct busyobj *bo)
{
CHECK_OBJ_NOTNULL(wrk, WORKER_MAGIC);
CHECK_OBJ_NOTNULL(bo, BUSYOBJ_MAGIC);
assert(bo->fetch_objcore->boc->state <= BOS_REQ_DONE);
VSLb_ts_busyobj(bo, "Retry", W_TIM_real(wrk));
/* VDI_Finish (via vbf_cleanup) must have been called before */
assert(bo->director_state == DIR_S_NULL);
/* reset other bo attributes - See VBO_GetBusyObj */
bo->storage = NULL;
bo->do_esi = 0;
bo->do_stream = 1;
bo->was_304 = 0;
// XXX: BereqEnd + BereqAcct ?
VSL_ChgId(bo->vsl, "bereq", "retry", VXID_Get(wrk, VSL_BACKENDMARKER));
VSLb_ts_busyobj(bo, "Start", bo->t_prev);
http_VSL_log(bo->bereq);
return (F_STP_STARTFETCH);
}
/*--------------------------------------------------------------------
* Setup bereq from bereq0, run vcl_backend_fetch
*/
static enum fetch_step
vbf_stp_startfetch(struct worker *wrk, struct busyobj *bo)
{
int i;
vtim_real now;
unsigned handling;
CHECK_OBJ_NOTNULL(wrk, WORKER_MAGIC);
CHECK_OBJ_NOTNULL(bo, BUSYOBJ_MAGIC);
AZ(bo->storage);
bo->storage = bo->do_pass ? stv_transient : STV_next();
if (bo->retries > 0)
http_Unset(bo->bereq, "\012X-Varnish:");
http_PrintfHeader(bo->bereq, "X-Varnish: %u", VXID(bo->vsl->wid));
VCL_backend_fetch_method(bo->vcl, wrk, NULL, bo, NULL);
bo->uncacheable = bo->do_pass;
if (wrk->handling == VCL_RET_ABANDON || wrk->handling == VCL_RET_FAIL)
return (F_STP_FAIL);
assert (wrk->handling == VCL_RET_FETCH || wrk->handling == VCL_RET_ERROR);
HTTP_Setup(bo->beresp, bo->ws, bo->vsl, SLT_BerespMethod);
assert(bo->fetch_objcore->boc->state <= BOS_REQ_DONE);
AZ(bo->htc);
VFP_Setup(bo->vfc, wrk);
bo->vfc->oc = bo->fetch_objcore;
bo->vfc->resp = bo->beresp;
bo->vfc->req = bo->bereq;
if (wrk->handling == VCL_RET_ERROR)
return (F_STP_ERROR);
i = VDI_GetHdr(bo);
now = W_TIM_real(wrk);
VSLb_ts_busyobj(bo, "Beresp", now);
if (i) {
assert(bo->director_state == DIR_S_NULL);
return (F_STP_ERROR);
}
http_VSL_log(bo->beresp);
if (bo->htc->body_status == BS_ERROR) {
bo->htc->doclose = SC_RX_BODY;
vbf_cleanup(bo);
VSLb(bo->vsl, SLT_Error, "Body cannot be fetched");
assert(bo->director_state == DIR_S_NULL);
return (F_STP_ERROR);
}
if (!http_GetHdr(bo->beresp, H_Date, NULL)) {
/*
* RFC 2616 14.18 Date: The Date general-header field
* represents the date and time at which the message was
* originated, having the same semantics as orig-date in
* RFC 822. ... A received message that does not have a
* Date header field MUST be assigned one by the recipient
* if the message will be cached by that recipient or
* gatewayed via a protocol which requires a Date.
*
* If we didn't get a Date header, we assign one here.
*/
http_TimeHeader(bo->beresp, "Date: ", now);
}
/*
* These two headers can be spread over multiple actual headers
* and we rely on their content outside of VCL, so collect them
* into one line here.
*/
http_CollectHdr(bo->beresp, H_Cache_Control);
http_CollectHdr(bo->beresp, H_Vary);
if (bo->fetch_objcore->flags & OC_F_PRIVATE) {
/* private objects have negative TTL */
bo->fetch_objcore->t_origin = now;
bo->fetch_objcore->ttl = -1.;
bo->fetch_objcore->grace = 0;
bo->fetch_objcore->keep = 0;
} else {
/* What does RFC2616 think about TTL ? */
RFC2616_Ttl(bo, now,
&bo->fetch_objcore->t_origin,
&bo->fetch_objcore->ttl,
&bo->fetch_objcore->grace,
&bo->fetch_objcore->keep
);
}
AZ(bo->do_esi);
AZ(bo->was_304);
if (http_IsStatus(bo->beresp, 304)) {
if (bo->stale_oc != NULL &&
ObjCheckFlag(bo->wrk, bo->stale_oc, OF_IMSCAND)) {
AZ(bo->stale_oc->flags & (OC_F_HFM|OC_F_PRIVATE));
if (ObjCheckFlag(bo->wrk, bo->stale_oc, OF_CHGCE)) {
/*
* If a VFP changed C-E in the stored
* object, then don't overwrite C-E from
* the IMS fetch, and we must weaken any
* new ETag we get.
*/
http_Unset(bo->beresp, H_Content_Encoding);
RFC2616_Weaken_Etag(bo->beresp);
}
http_Unset(bo->beresp, H_Content_Length);
HTTP_Merge(bo->wrk, bo->stale_oc, bo->beresp);
assert(http_IsStatus(bo->beresp, 200));
bo->was_304 = 1;
} else if (!bo->do_pass) {
/*
* Backend sent unallowed 304
*/
VSLb(bo->vsl, SLT_Error,
"304 response but not conditional fetch");
bo->htc->doclose = SC_RX_BAD;
vbf_cleanup(bo);
return (F_STP_ERROR);
}
}
VCL_backend_response_method(bo->vcl, wrk, NULL, bo, NULL);
if (wrk->handling == VCL_RET_ABANDON || wrk->handling == VCL_RET_FAIL ||
wrk->handling == VCL_RET_ERROR) {
/* do not count deliberately ending the backend connection as
* fetch failure
*/
handling = wrk->handling;
if (bo->htc)
bo->htc->doclose = SC_RESP_CLOSE;
vbf_cleanup(bo);
wrk->handling = handling;
if (wrk->handling == VCL_RET_ERROR)
return (F_STP_ERROR);
else
return (F_STP_FAIL);
}
if (wrk->handling == VCL_RET_RETRY) {
if (bo->htc && bo->htc->body_status != BS_NONE)
bo->htc->doclose = SC_RESP_CLOSE;
vbf_cleanup(bo);
if (bo->retries++ < cache_param->max_retries)
return (F_STP_RETRY);
VSLb(bo->vsl, SLT_VCL_Error,
"Too many retries, delivering 503");
assert(bo->director_state == DIR_S_NULL);
return (F_STP_ERROR);
}
assert(bo->fetch_objcore->boc->state <= BOS_REQ_DONE);
if (bo->fetch_objcore->boc->state != BOS_REQ_DONE) {
bo->req = NULL;
ObjSetState(wrk, bo->fetch_objcore, BOS_REQ_DONE);
}
if (bo->do_esi)
bo->do_stream = 0;
if (wrk->handling == VCL_RET_PASS) {
bo->fetch_objcore->flags |= OC_F_HFP;
bo->uncacheable = 1;
wrk->handling = VCL_RET_DELIVER;
}
if (bo->do_pass || bo->uncacheable)
bo->fetch_objcore->flags |= OC_F_HFM;
assert(wrk->handling == VCL_RET_DELIVER);
return (bo->was_304 ? F_STP_CONDFETCH : F_STP_FETCH);
}
/*--------------------------------------------------------------------
*/
static enum fetch_step
vbf_stp_fetchbody(struct worker *wrk, struct busyobj *bo)
{
ssize_t l;
uint8_t *ptr;
enum vfp_status vfps = VFP_ERROR;
ssize_t est;
struct vfp_ctx *vfc;
CHECK_OBJ_NOTNULL(bo, BUSYOBJ_MAGIC);
vfc = bo->vfc;
CHECK_OBJ_NOTNULL(vfc, VFP_CTX_MAGIC);
AN(vfc->vfp_nxt);
est = bo->htc->content_length;
if (est < 0)
est = 0;
do {
if (vfc->oc->flags & OC_F_ABANDON) {
/*
* A pass object and delivery was terminated
* We don't fail the fetch, in order for HitMiss
* objects to be created.
*/
AN(vfc->oc->flags & OC_F_HFM);
VSLb(wrk->vsl, SLT_Debug,
"Fetch: Pass delivery abandoned");
bo->htc->doclose = SC_RX_BODY;
break;
}
AZ(vfc->failed);
l = est;
assert(l >= 0);
if (VFP_GetStorage(vfc, &l, &ptr) != VFP_OK) {
bo->htc->doclose = SC_RX_BODY;
break;
}
AZ(vfc->failed);
vfps = VFP_Suck(vfc, ptr, &l);
if (l > 0 && vfps != VFP_ERROR) {
bo->acct.beresp_bodybytes += l;
VFP_Extend(vfc, l);
if (est >= l)
est -= l;
else
est = 0;
}
} while (vfps == VFP_OK);
if (vfc->failed) {
(void)VFP_Error(vfc, "Fetch pipeline failed to process");
bo->htc->doclose = SC_RX_BODY;
vbf_cleanup(bo);
if (!bo->do_stream) {
assert(bo->fetch_objcore->boc->state < BOS_STREAM);
// XXX: doclose = ?
return (F_STP_ERROR);
} else {
wrk->stats->fetch_failed++;
return (F_STP_FAIL);
}
}
ObjTrimStore(wrk, vfc->oc);
return (F_STP_FETCHEND);
}
static enum fetch_step
vbf_stp_fetch(struct worker *wrk, struct busyobj *bo)
{
CHECK_OBJ_NOTNULL(wrk, WORKER_MAGIC);
CHECK_OBJ_NOTNULL(bo, BUSYOBJ_MAGIC);
CHECK_OBJ_NOTNULL(bo->fetch_objcore, OBJCORE_MAGIC);
assert(wrk->handling == VCL_RET_DELIVER);
if (bo->htc == NULL) {
(void)VFP_Error(bo->vfc, "No backend connection (rollback?)");
vbf_cleanup(bo);
return (F_STP_ERROR);
}
/* No body -> done */
if (bo->htc->body_status == BS_NONE || bo->htc->content_length == 0) {
http_Unset(bo->beresp, H_Content_Encoding);
bo->do_gzip = bo->do_gunzip = 0;
bo->do_stream = 0;
bo->filter_list = "";
} else if (bo->filter_list == NULL) {
bo->filter_list = VBF_Get_Filter_List(bo);
}
if (bo->filter_list == NULL ||
VCL_StackVFP(bo->vfc, bo->vcl, bo->filter_list)) {
(bo)->htc->doclose = SC_OVERLOAD;
vbf_cleanup(bo);
return (F_STP_ERROR);
}
if (bo->fetch_objcore->flags & OC_F_PRIVATE)
AN(bo->uncacheable);
bo->fetch_objcore->boc->len_so_far = 0;
if (VFP_Open(bo->vfc)) {
(void)VFP_Error(bo->vfc, "Fetch pipeline failed to open");
bo->htc->doclose = SC_RX_BODY;
vbf_cleanup(bo);
return (F_STP_ERROR);
}
if (vbf_beresp2obj(bo)) {
(void)VFP_Error(bo->vfc, "Could not get storage");
bo->htc->doclose = SC_RX_BODY;
vbf_cleanup(bo);
return (F_STP_ERROR);
}
#define OBJ_FLAG(U, l, v) \
if (bo->vfc->obj_flags & OF_##U) \
ObjSetFlag(bo->wrk, bo->fetch_objcore, OF_##U, 1);
#include "tbl/obj_attr.h"
if (!(bo->fetch_objcore->flags & OC_F_HFM) &&
http_IsStatus(bo->beresp, 200) && (
http_GetHdr(bo->beresp, H_Last_Modified, NULL) ||
http_GetHdr(bo->beresp, H_ETag, NULL)))
ObjSetFlag(bo->wrk, bo->fetch_objcore, OF_IMSCAND, 1);
assert(bo->fetch_objcore->boc->refcount >= 1);
assert(bo->fetch_objcore->boc->state == BOS_REQ_DONE);
if (bo->do_stream) {
ObjSetState(wrk, bo->fetch_objcore, BOS_PREP_STREAM);
HSH_Unbusy(wrk, bo->fetch_objcore);
ObjSetState(wrk, bo->fetch_objcore, BOS_STREAM);
}
VSLb(bo->vsl, SLT_Fetch_Body, "%u %s %s",
bo->htc->body_status, body_status_2str(bo->htc->body_status),
bo->do_stream ? "stream" : "-");
if (bo->htc->body_status != BS_NONE) {
assert(bo->htc->body_status != BS_ERROR);
return (F_STP_FETCHBODY);
}
AZ(bo->vfc->failed);
return (F_STP_FETCHEND);
}
static enum fetch_step
vbf_stp_fetchend(struct worker *wrk, struct busyobj *bo)
{
AZ(bo->vfc->failed);
/* Recycle the backend connection before setting BOS_FINISHED to
give predictable backend reuse behavior for varnishtest */
vbf_cleanup(bo);
AZ(ObjSetU64(wrk, bo->fetch_objcore, OA_LEN,
bo->fetch_objcore->boc->len_so_far));
if (bo->do_stream)
assert(bo->fetch_objcore->boc->state == BOS_STREAM);
else {
assert(bo->fetch_objcore->boc->state == BOS_REQ_DONE);
ObjSetState(wrk, bo->fetch_objcore, BOS_PREP_STREAM);
HSH_Unbusy(wrk, bo->fetch_objcore);
}
ObjSetState(wrk, bo->fetch_objcore, BOS_FINISHED);
VSLb_ts_busyobj(bo, "BerespBody", W_TIM_real(wrk));
if (bo->stale_oc != NULL)
HSH_Kill(bo->stale_oc);
return (F_STP_DONE);
}
/*--------------------------------------------------------------------
*/
static int v_matchproto_(objiterate_f)
vbf_objiterator(void *priv, unsigned flush, const void *ptr, ssize_t len)
{
struct busyobj *bo;
ssize_t l;
const uint8_t *ps = ptr;
uint8_t *pd;
CAST_OBJ_NOTNULL(bo, priv, BUSYOBJ_MAGIC);
(void)flush;
while (len > 0) {
l = len;
if (VFP_GetStorage(bo->vfc, &l, &pd) != VFP_OK)
return (1);
if (len < l)
l = len;
memcpy(pd, ps, l);
VFP_Extend(bo->vfc, l);
ps += l;
len -= l;
}
return (0);
}
static enum fetch_step
vbf_stp_condfetch(struct worker *wrk, struct busyobj *bo)
{
CHECK_OBJ_NOTNULL(wrk, WORKER_MAGIC);
CHECK_OBJ_NOTNULL(bo, BUSYOBJ_MAGIC);
AZ(vbf_beresp2obj(bo));
if (ObjHasAttr(bo->wrk, bo->stale_oc, OA_ESIDATA))
AZ(ObjCopyAttr(bo->wrk, bo->fetch_objcore, bo->stale_oc,
OA_ESIDATA));
AZ(ObjCopyAttr(bo->wrk, bo->fetch_objcore, bo->stale_oc, OA_FLAGS));
if (bo->fetch_objcore->flags & OC_F_HFM)
ObjSetFlag(bo->wrk, bo->fetch_objcore, OF_IMSCAND, 0);
AZ(ObjCopyAttr(bo->wrk, bo->fetch_objcore, bo->stale_oc, OA_GZIPBITS));
if (bo->do_stream) {
ObjSetState(wrk, bo->fetch_objcore, BOS_PREP_STREAM);
HSH_Unbusy(wrk, bo->fetch_objcore);
ObjSetState(wrk, bo->fetch_objcore, BOS_STREAM);
}
if (ObjIterate(wrk, bo->stale_oc, bo, vbf_objiterator, 0))
(void)VFP_Error(bo->vfc, "Template object failed");
if (bo->stale_oc->flags & OC_F_FAILED)
(void)VFP_Error(bo->vfc, "Template object failed");
if (bo->vfc->failed) {
vbf_cleanup(bo);
wrk->stats->fetch_failed++;
return (F_STP_FAIL);
}
return (F_STP_FETCHEND);
}
/*--------------------------------------------------------------------
* Create synth object
*
* replaces a stale object unless
* - abandoning the bereq or
* - leaving vcl_backend_error with return (deliver) and beresp.ttl == 0s or
* - there is a waitinglist on this object because in this case the default ttl
* would be 1s, so we might be looking at the same case as the previous
*
* We do want the stale replacement to avoid an object pileup with short ttl and
* long grace/keep, yet there could exist cases where a cache object is
* deliberately created to momentarily override a stale object.
*
* If this case exists, we should add a vcl veto (e.g. beresp.replace_stale with
* default true)
*/
static enum fetch_step
vbf_stp_error(struct worker *wrk, struct busyobj *bo)
{
ssize_t l, ll, o;
vtim_real now;
uint8_t *ptr;
struct vsb *synth_body;
struct objcore *stale;
CHECK_OBJ_NOTNULL(wrk, WORKER_MAGIC);
CHECK_OBJ_NOTNULL(bo, BUSYOBJ_MAGIC);
CHECK_OBJ_NOTNULL(bo->fetch_objcore, OBJCORE_MAGIC);
AN(bo->fetch_objcore->flags & OC_F_BUSY);
assert(bo->director_state == DIR_S_NULL);
if (wrk->handling != VCL_RET_ERROR)
wrk->stats->fetch_failed++;
now = W_TIM_real(wrk);
VSLb_ts_busyobj(bo, "Error", now);
if (bo->fetch_objcore->stobj->stevedore != NULL)
ObjFreeObj(bo->wrk, bo->fetch_objcore);
if (bo->storage == NULL)
bo->storage = STV_next();
// XXX: reset all beresp flags ?
HTTP_Setup(bo->beresp, bo->ws, bo->vsl, SLT_BerespMethod);
if (bo->err_code > 0)
http_PutResponse(bo->beresp, "HTTP/1.1", bo->err_code,
bo->err_reason);
else
http_PutResponse(bo->beresp, "HTTP/1.1", 503,
"Backend fetch failed");
http_TimeHeader(bo->beresp, "Date: ", now);
http_SetHeader(bo->beresp, "Server: Varnish");
stale = bo->stale_oc;
bo->fetch_objcore->t_origin = now;
if (!VTAILQ_EMPTY(&bo->fetch_objcore->objhead->waitinglist)) {
/*
* If there is a waitinglist, it means that there is no
* grace-able object, so cache the error return for a
* short time, so the waiting list can drain, rather than
* each objcore on the waiting list sequentially attempt
* to fetch from the backend.
*/
bo->fetch_objcore->ttl = 1;
bo->fetch_objcore->grace = 5;
bo->fetch_objcore->keep = 5;
stale = NULL;
} else {
bo->fetch_objcore->ttl = 0;
bo->fetch_objcore->grace = 0;
bo->fetch_objcore->keep = 0;
}
synth_body = VSB_new_auto();
AN(synth_body);
VCL_backend_error_method(bo->vcl, wrk, NULL, bo, synth_body);
AZ(VSB_finish(synth_body));
if (wrk->handling == VCL_RET_ABANDON || wrk->handling == VCL_RET_FAIL) {
VSB_destroy(&synth_body);
return (F_STP_FAIL);
}
if (wrk->handling == VCL_RET_RETRY) {
VSB_destroy(&synth_body);
if (bo->retries++ < cache_param->max_retries)
return (F_STP_RETRY);
VSLb(bo->vsl, SLT_VCL_Error, "Too many retries, failing");
return (F_STP_FAIL);
}
assert(wrk->handling == VCL_RET_DELIVER);
assert(bo->vfc->wrk == bo->wrk);
assert(bo->vfc->oc == bo->fetch_objcore);
assert(bo->vfc->resp == bo->beresp);
assert(bo->vfc->req == bo->bereq);
if (vbf_beresp2obj(bo)) {
(void)VFP_Error(bo->vfc, "Could not get storage");
VSB_destroy(&synth_body);
return (F_STP_FAIL);
}
ll = VSB_len(synth_body);
o = 0;
while (ll > 0) {
l = ll;
if (VFP_GetStorage(bo->vfc, &l, &ptr) != VFP_OK)
break;
if (l > ll)
l = ll;
memcpy(ptr, VSB_data(synth_body) + o, l);
VFP_Extend(bo->vfc, l);
ll -= l;
o += l;
}
AZ(ObjSetU64(wrk, bo->fetch_objcore, OA_LEN, o));
VSB_destroy(&synth_body);
ObjSetState(wrk, bo->fetch_objcore, BOS_PREP_STREAM);
HSH_Unbusy(wrk, bo->fetch_objcore);
if (stale != NULL && bo->fetch_objcore->ttl > 0)
HSH_Kill(stale);
ObjSetState(wrk, bo->fetch_objcore, BOS_FINISHED);
return (F_STP_DONE);
}
/*--------------------------------------------------------------------
*/
static enum fetch_step
vbf_stp_fail(struct worker *wrk, const struct busyobj *bo)
{
CHECK_OBJ_NOTNULL(wrk, WORKER_MAGIC);
CHECK_OBJ_NOTNULL(bo, BUSYOBJ_MAGIC);
CHECK_OBJ_NOTNULL(bo->fetch_objcore, OBJCORE_MAGIC);
assert(bo->fetch_objcore->boc->state < BOS_FINISHED);
HSH_Fail(bo->fetch_objcore);
if (!(bo->fetch_objcore->flags & OC_F_BUSY))
HSH_Kill(bo->fetch_objcore);
ObjSetState(wrk, bo->fetch_objcore, BOS_FAILED);
return (F_STP_DONE);
}
/*--------------------------------------------------------------------
*/
static enum fetch_step
vbf_stp_done(void)
{
WRONG("Just plain wrong");
NEEDLESS(return (F_STP_DONE));
}
static void v_matchproto_(task_func_t)
vbf_fetch_thread(struct worker *wrk, void *priv)
{
struct busyobj *bo;
enum fetch_step stp;
CHECK_OBJ_NOTNULL(wrk, WORKER_MAGIC);
CAST_OBJ_NOTNULL(bo, priv, BUSYOBJ_MAGIC);
CHECK_OBJ_NOTNULL(bo->req, REQ_MAGIC);
CHECK_OBJ_NOTNULL(bo->fetch_objcore, OBJCORE_MAGIC);
THR_SetBusyobj(bo);
stp = F_STP_MKBEREQ;
assert(isnan(bo->t_first));
assert(isnan(bo->t_prev));
VSLb_ts_busyobj(bo, "Start", W_TIM_real(wrk));
bo->wrk = wrk;
wrk->vsl = bo->vsl;
#if 0
if (bo->stale_oc != NULL) {
CHECK_OBJ_NOTNULL(bo->stale_oc, OBJCORE_MAGIC);
/* We don't want the oc/stevedore ops in fetching thread */
if (!ObjCheckFlag(wrk, bo->stale_oc, OF_IMSCAND))
(void)HSH_DerefObjCore(wrk, &bo->stale_oc, 0);
}
#endif
VCL_TaskEnter(bo->privs);
while (stp != F_STP_DONE) {
CHECK_OBJ_NOTNULL(bo, BUSYOBJ_MAGIC);
assert(bo->fetch_objcore->boc->refcount >= 1);
if (bo->fetch_objcore->boc->state < BOS_REQ_DONE)
AN(bo->req);
else
AZ(bo->req);
switch (stp) {
#define FETCH_STEP(l, U, arg) \
case F_STP_##U: \
stp = vbf_stp_##l arg; \
break;
#include "tbl/steps.h"
default:
WRONG("Illegal fetch_step");
}
}
assert(bo->director_state == DIR_S_NULL);
VCL_TaskLeave(bo->privs);
http_Teardown(bo->bereq);
http_Teardown(bo->beresp);
if (bo->fetch_objcore->boc->state == BOS_FINISHED) {
AZ(bo->fetch_objcore->flags & OC_F_FAILED);
VSLb(bo->vsl, SLT_Length, "%ju",
(uintmax_t)ObjGetLen(bo->wrk, bo->fetch_objcore));
}
// AZ(bo->fetch_objcore->boc); // XXX
if (bo->stale_oc != NULL)
(void)HSH_DerefObjCore(wrk, &bo->stale_oc, 0);
wrk->vsl = NULL;
HSH_DerefBoc(wrk, bo->fetch_objcore);
SES_Rel(bo->sp);
VBO_ReleaseBusyObj(wrk, &bo);
THR_SetBusyobj(NULL);
}
/*--------------------------------------------------------------------
*/
void
VBF_Fetch(struct worker *wrk, struct req *req, struct objcore *oc,
struct objcore *oldoc, enum vbf_fetch_mode_e mode)
{
struct boc *boc;
struct busyobj *bo;
const char *how;
CHECK_OBJ_NOTNULL(wrk, WORKER_MAGIC);
CHECK_OBJ_NOTNULL(req, REQ_MAGIC);
CHECK_OBJ_NOTNULL(oc, OBJCORE_MAGIC);
AN(oc->flags & OC_F_BUSY);
CHECK_OBJ_ORNULL(oldoc, OBJCORE_MAGIC);
bo = VBO_GetBusyObj(wrk, req);
CHECK_OBJ_NOTNULL(bo, BUSYOBJ_MAGIC);
AN(bo->vcl);
boc = HSH_RefBoc(oc);
CHECK_OBJ_NOTNULL(boc, BOC_MAGIC);
switch (mode) {
case VBF_PASS:
how = "pass";
bo->do_pass = 1;
break;
case VBF_NORMAL:
how = "fetch";
break;
case VBF_BACKGROUND:
how = "bgfetch";
bo->is_bgfetch = 1;
break;
default:
WRONG("Wrong fetch mode");
}
VSLb(bo->vsl, SLT_Begin, "bereq %u %s", VXID(req->vsl->wid), how);
VSLb(bo->vsl, SLT_VCL_use, "%s", VCL_Name(bo->vcl));
VSLb(req->vsl, SLT_Link, "bereq %u %s", VXID(bo->vsl->wid), how);
THR_SetBusyobj(bo);
bo->sp = req->sp;
SES_Ref(bo->sp);
oc->boc->vary = req->vary_b;
req->vary_b = NULL;
HSH_Ref(oc);
AZ(bo->fetch_objcore);
bo->fetch_objcore = oc;
AZ(bo->stale_oc);
if (oldoc != NULL) {
assert(oldoc->refcnt > 0);
HSH_Ref(oldoc);
bo->stale_oc = oldoc;
}
AZ(bo->req);
bo->req = req;
bo->fetch_task.priv = bo;
bo->fetch_task.func = vbf_fetch_thread;
if (Pool_Task(wrk->pool, &bo->fetch_task, TASK_QUEUE_BO)) {
wrk->stats->fetch_no_thread++;
(void)vbf_stp_fail(req->wrk, bo);
if (bo->stale_oc != NULL)
(void)HSH_DerefObjCore(wrk, &bo->stale_oc, 0);
HSH_DerefBoc(wrk, oc);
SES_Rel(bo->sp);
VBO_ReleaseBusyObj(wrk, &bo);
} else {
bo = NULL; /* ref transferred to fetch thread */
if (mode == VBF_BACKGROUND) {
ObjWaitState(oc, BOS_REQ_DONE);
(void)VRB_Ignore(req);
} else {
ObjWaitState(oc, BOS_STREAM);
if (oc->boc->state == BOS_FAILED) {
AN((oc->flags & OC_F_FAILED));
} else {
AZ(oc->flags & OC_F_BUSY);
}
}
}
AZ(bo);
VSLb_ts_req(req, "Fetch", W_TIM_real(wrk));
assert(oc->boc == boc);
HSH_DerefBoc(wrk, oc);
if (mode == VBF_BACKGROUND)
(void)HSH_DerefObjCore(wrk, &oc, HSH_RUSH_POLICY);
THR_SetBusyobj(NULL);
}
|
735349.c | /*
* This file is part of the MicroPython project, http://micropython.org/
*
* The MIT License (MIT)
*
* Copyright (c) 2013, 2014 Damien P. George
*
* 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 <stdlib.h>
#include <assert.h>
#include "py/objtuple.h"
#include "py/runtime.h"
typedef struct _mp_obj_zip_t {
mp_obj_base_t base;
size_t n_iters;
mp_obj_t iters[];
} mp_obj_zip_t;
STATIC mp_obj_t zip_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *args) {
mp_arg_check_num(n_args, n_kw, 0, MP_OBJ_FUN_ARGS_MAX, false);
mp_obj_zip_t *o = m_new_obj_var(mp_obj_zip_t, mp_obj_t, n_args);
o->base.type = type;
o->n_iters = n_args;
for (size_t i = 0; i < n_args; i++) {
o->iters[i] = mp_getiter(args[i], NULL);
}
return MP_OBJ_FROM_PTR(o);
}
STATIC mp_obj_t zip_iternext(mp_obj_t self_in) {
mp_check_self(mp_obj_is_type(self_in, &mp_type_zip));
mp_obj_zip_t *self = MP_OBJ_TO_PTR(self_in);
if (self->n_iters == 0) {
return MP_OBJ_STOP_ITERATION;
}
mp_obj_tuple_t *tuple = MP_OBJ_TO_PTR(mp_obj_new_tuple(self->n_iters, NULL));
for (size_t i = 0; i < self->n_iters; i++) {
mp_obj_t next = mp_iternext(self->iters[i]);
if (next == MP_OBJ_STOP_ITERATION) {
mp_obj_tuple_del(MP_OBJ_FROM_PTR(tuple));
return MP_OBJ_STOP_ITERATION;
}
tuple->items[i] = next;
}
return MP_OBJ_FROM_PTR(tuple);
}
const mp_obj_type_t mp_type_zip = {
{ &mp_type_type },
.name = MP_QSTR_zip,
.make_new = zip_make_new,
.getiter = mp_identity_getiter,
.iternext = zip_iternext,
};
|
909050.c | /* Unit testing.
Copyright (C) 2005, 2006, 2007, 2008, 2009, 2010, 2011 Free Software
Foundation, Inc.
This file is part of GNU Wget.
GNU Wget is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
GNU Wget 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 Wget. If not, see <http://www.gnu.org/licenses/>.
Additional permission under GNU GPL version 3 section 7
If you modify this program, or any covered work, by linking or
combining it with the OpenSSL project's OpenSSL library (or a
modified version of that library), containing parts covered by the
terms of the OpenSSL or SSLeay licenses, the Free Software Foundation
grants you additional permission to convey the resulting work.
Corresponding Source for a non-source form of such a combination
shall include the source code for the parts of OpenSSL used as well
as that of the covered work. */
#include "wget.h"
#include <stdio.h>
#include "test.h"
#ifndef TESTING
#error "TESTING not set!!!"
#endif
const char *test_parse_content_disposition();
const char *test_subdir_p();
const char *test_dir_matches_p();
const char *test_commands_sorted();
const char *test_cmd_spec_restrict_file_names();
const char *test_path_simplify ();
const char *test_append_uri_pathel();
const char *test_are_urls_equal();
const char *test_is_robots_txt_url();
const char *program_argstring = "TEST";
int tests_run;
static const char *
all_tests()
{
mu_run_test (test_parse_content_disposition);
mu_run_test (test_subdir_p);
mu_run_test (test_dir_matches_p);
mu_run_test (test_commands_sorted);
mu_run_test (test_cmd_spec_restrict_file_names);
mu_run_test (test_path_simplify);
mu_run_test (test_append_uri_pathel);
mu_run_test (test_are_urls_equal);
mu_run_test (test_is_robots_txt_url);
return NULL;
}
char *program_name; /* Needed by lib/error.c. */
int
main (int argc, char *argv[])
{
const char *result;
program_name = argv[0];
result = all_tests();
if (result != NULL)
{
puts (result);
}
else
{
printf ("ALL TESTS PASSED\n");
}
printf ("Tests run: %d\n", tests_run);
return result != 0;
}
/*
* vim: et ts=2 sw=2
*/
|
393323.c | /*
Copyright (C) 2000, 2001 Silicon Graphics, Inc. All Rights Reserved.
This program is free software; you can redistribute it and/or modify it
under the terms of version 2.1 of the GNU Lesser General Public License
as published by the Free Software Foundation.
This program is distributed in the hope that it would be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
Further, this software is distributed without any warranty that it is
free of the rightful claim of any third person regarding infringement
or the like. Any license provided herein, whether implied or
otherwise, applies only to this software file. Patent licenses, if
any, provided herein do not apply to combinations of this program with
other software, or any other product whatsoever.
You should have received a copy of the GNU Lesser General Public
License along with this program; if not, write the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston MA 02111-1307,
USA.
Contact information: Silicon Graphics, Inc., 1600 Amphitheatre Pky,
Mountain View, CA 94043, or:
http://www.sgi.com
For further information regarding this notice, see:
http://oss.sgi.com/projects/GenInfo/NoticeExplan
*/
#pragma ident "@(#) libfi/mathlb/alog.c 92.1 07/09/99 11:00:36"
#include <fortran.h>
#include <math.h>
extern _f_real8 _ALOG_( _f_real8 *x );
extern _f_real8 _ALOG( _f_real8 x );
/*
* ALOG: real(kind=8) - pass by address
*/
_f_real8
_ALOG_( _f_real8 *x )
{
return (_ALOG(*x));
}
/*
* ALOG: real(kind=8) - pass by value
*/
_f_real8
_ALOG( _f_real8 x )
{
_f_real8 __log(_f_real8 x);
return ((_f_real8) __log((_f_real8) x));
}
|
574293.c | /*******************************************************************************
*
* DO NOT EDIT THIS FILE!
* This file is auto-generated by fltg from Logical Table mapping files.
*
* Tool: $SDK/INTERNAL/fltg/bin/fltg
*
* Edits to this file will be lost when it is regenerated.
*
* This license is set out in https://raw.githubusercontent.com/Broadcom-Network-Switching-Software/OpenBCM/master/Legal/LICENSE file.
*
* Copyright 2007-2020 Broadcom Inc. All rights reserved.
*/
/* Logical Table Adaptor for component bcmltx */
/* Handler: bcm56990_b0_lta_bcmltx_field_demux_l3_ipv6_uc_route_overridet_ipv6u_lower_maskf_0_xfrm_handler */
#include <bcmlrd/bcmlrd_types.h>
#include <bcmltd/chip/bcmltd_id.h>
#include <bcmltx/bcmltx_field_demux.h>
#include <bcmdrd/chip/bcm56990_b0_enum.h>
#include <bcmlrd/chip/bcm56990_b0/bcm56990_b0_lrd_xfrm_field_desc.h>
extern const bcmltd_field_desc_t
bcm56990_b0_lrd_field_demux_l3_ipv6_uc_route_overridet_ipv6u_lower_maskf_0_src_field_desc_s0[];
extern const bcmltd_field_desc_t
bcm56990_b0_lrd_bcmltx_field_demux_l3_ipv6_uc_route_overridet_ipv6u_lower_maskf_0_dst_field_desc_d0[];
static const
bcmltd_field_list_t
bcm56990_b0_lta_bcmltx_field_demux_l3_ipv6_uc_route_overridet_ipv6u_lower_maskf_0_src_list_s0 = {
.field_num = 3,
.field_array = bcm56990_b0_lrd_field_demux_l3_ipv6_uc_route_overridet_ipv6u_lower_maskf_0_src_field_desc_s0
};
static const bcmltd_field_list_t
bcm56990_b0_lta_bcmltx_field_demux_l3_ipv6_uc_route_overridet_ipv6u_lower_maskf_0_dst_list_d0 = {
.field_num = 3,
.field_array = bcm56990_b0_lrd_bcmltx_field_demux_l3_ipv6_uc_route_overridet_ipv6u_lower_maskf_0_dst_field_desc_d0
};
static const uint32_t
bcm56990_b0_lta_bcmltx_field_demux_l3_ipv6_uc_route_overridet_ipv6u_lower_maskf_0_transform_src_s0[1] = {
L3_IPV6_UC_ROUTE_OVERRIDEt_IPV6u_LOWER_MASKf,
};
static const uint32_t
bcm56990_b0_lta_bcmltx_field_demux_l3_ipv6_uc_route_overridet_ipv6u_lower_maskf_0_transform_dst_d0[3] = {
UPR_MASK0_LPM_V6_KEY_D_IP_ADDR_1f,
LWR_MASK1_LPM_V6_KEY_D_IP_ADDR_2f,
LWR_MASK0_LPM_V6_KEY_D_IP_ADDR_3f,
};
static const bcmltd_generic_arg_t
bcm56990_b0_lta_bcmltx_field_demux_l3_ipv6_uc_route_overridet_ipv6u_lower_maskf_0_comp_data = {
.sid = L3_IPV6_UC_ROUTE_OVERRIDEt,
.values = 0,
.value = NULL,
.user_data = NULL
};
static const bcmltd_transform_arg_t
bcm56990_b0_lta_bcmltx_field_demux_l3_ipv6_uc_route_overridet_ipv6u_lower_maskf_0_xfrm_handler_fwd_arg_s0_d0 = {
.values = 0,
.value = NULL,
.tables = 0,
.table = NULL,
.fields = 1,
.field = bcm56990_b0_lta_bcmltx_field_demux_l3_ipv6_uc_route_overridet_ipv6u_lower_maskf_0_transform_src_s0,
.field_list = &bcm56990_b0_lta_bcmltx_field_demux_l3_ipv6_uc_route_overridet_ipv6u_lower_maskf_0_src_list_s0,
.rfields = 3,
.rfield = bcm56990_b0_lta_bcmltx_field_demux_l3_ipv6_uc_route_overridet_ipv6u_lower_maskf_0_transform_dst_d0,
.rfield_list = &bcm56990_b0_lta_bcmltx_field_demux_l3_ipv6_uc_route_overridet_ipv6u_lower_maskf_0_dst_list_d0,
.comp_data = &bcm56990_b0_lta_bcmltx_field_demux_l3_ipv6_uc_route_overridet_ipv6u_lower_maskf_0_comp_data
};
static const bcmltd_transform_arg_t
bcm56990_b0_lta_bcmltx_field_demux_l3_ipv6_uc_route_overridet_ipv6u_lower_maskf_0_xfrm_handler_rev_arg_s0_d0 = {
.values = 0,
.value = NULL,
.tables = 0,
.table = NULL,
.fields = 3,
.field = bcm56990_b0_lta_bcmltx_field_demux_l3_ipv6_uc_route_overridet_ipv6u_lower_maskf_0_transform_dst_d0,
.field_list = &bcm56990_b0_lta_bcmltx_field_demux_l3_ipv6_uc_route_overridet_ipv6u_lower_maskf_0_dst_list_d0,
.rfields = 1,
.rfield = bcm56990_b0_lta_bcmltx_field_demux_l3_ipv6_uc_route_overridet_ipv6u_lower_maskf_0_transform_src_s0,
.rfield_list = &bcm56990_b0_lta_bcmltx_field_demux_l3_ipv6_uc_route_overridet_ipv6u_lower_maskf_0_src_list_s0,
.comp_data = &bcm56990_b0_lta_bcmltx_field_demux_l3_ipv6_uc_route_overridet_ipv6u_lower_maskf_0_comp_data
};
const bcmltd_xfrm_handler_t
bcm56990_b0_lta_bcmltx_field_demux_l3_ipv6_uc_route_overridet_ipv6u_lower_maskf_0_xfrm_handler_fwd_s0_d0 = {
.transform = bcmltx_field_demux_transform,
.arg = &bcm56990_b0_lta_bcmltx_field_demux_l3_ipv6_uc_route_overridet_ipv6u_lower_maskf_0_xfrm_handler_fwd_arg_s0_d0
};
const bcmltd_xfrm_handler_t
bcm56990_b0_lta_bcmltx_field_demux_l3_ipv6_uc_route_overridet_ipv6u_lower_maskf_0_xfrm_handler_rev_s0_d0 = {
.transform = bcmltx_field_mux_transform,
.arg = &bcm56990_b0_lta_bcmltx_field_demux_l3_ipv6_uc_route_overridet_ipv6u_lower_maskf_0_xfrm_handler_rev_arg_s0_d0
};
|
800025.c | #include <errno.h>
#include "wrapper.h"
size_t encode_E2AP_PDU(E2AP_PDU_t* pdu, void* buffer, size_t buf_size)
{
asn_enc_rval_t encode_result;
encode_result = aper_encode_to_buffer(&asn_DEF_E2AP_PDU, NULL, pdu, buffer, buf_size);
ASN_STRUCT_FREE(asn_DEF_E2AP_PDU, pdu);
if(encode_result.encoded == -1) {
fprintf(stderr, "Cannot encode %s: %s\n", encode_result.failed_type->name, strerror(errno));
return -1;
} else {
return encode_result.encoded;
}
}
E2AP_PDU_t* decode_E2AP_PDU(const void* buffer, size_t buf_size)
{
asn_dec_rval_t decode_result;
E2AP_PDU_t *pdu = 0;
decode_result = aper_decode_complete(NULL, &asn_DEF_E2AP_PDU, (void **)&pdu, buffer, buf_size);
if(decode_result.code == RC_OK) {
return pdu;
} else {
ASN_STRUCT_FREE(asn_DEF_E2AP_PDU, pdu);
return 0;
}
}
/* RICsubscriptionRequest */
long e2ap_get_ric_subscription_request_sequence_number(void *buffer, size_t buf_size)
{
E2AP_PDU_t *pdu = decode_E2AP_PDU(buffer, buf_size);
if ( pdu != NULL && pdu->present == E2AP_PDU_PR_initiatingMessage)
{
InitiatingMessage_t* initiatingMessage = pdu->choice.initiatingMessage;
if ( initiatingMessage->procedureCode == ProcedureCode_id_RICsubscription
&& initiatingMessage->value.present == InitiatingMessage__value_PR_RICsubscriptionRequest)
{
RICsubscriptionRequest_t *ric_subscription_request = &(initiatingMessage->value.choice.RICsubscriptionRequest);
for (int i = 0; i < ric_subscription_request->protocolIEs.list.count; ++i )
{
if ( ric_subscription_request->protocolIEs.list.array[i]->id == ProtocolIE_ID_id_RICrequestID )
{
long sequenceNumber = ric_subscription_request->protocolIEs.list.array[i]->value.choice.RICrequestID.ricInstanceID;
ASN_STRUCT_FREE(asn_DEF_E2AP_PDU, pdu);
return sequenceNumber;
}
}
}
}
if(pdu != NULL)
ASN_STRUCT_FREE(asn_DEF_E2AP_PDU, pdu);
return -1;
}
ssize_t e2ap_set_ric_subscription_request_sequence_number(void *buffer, size_t buf_size, long sequence_number)
{
E2AP_PDU_t *pdu = decode_E2AP_PDU(buffer, buf_size);
if ( pdu != NULL && pdu->present == E2AP_PDU_PR_initiatingMessage)
{
InitiatingMessage_t* initiatingMessage = pdu->choice.initiatingMessage;
if ( initiatingMessage->procedureCode == ProcedureCode_id_RICsubscription
&& initiatingMessage->value.present == InitiatingMessage__value_PR_RICsubscriptionRequest)
{
RICsubscriptionRequest_t *ricSubscriptionRequest = &initiatingMessage->value.choice.RICsubscriptionRequest;
for (int i = 0; i < ricSubscriptionRequest->protocolIEs.list.count; ++i )
{
if ( ricSubscriptionRequest->protocolIEs.list.array[i]->id == ProtocolIE_ID_id_RICrequestID )
{
ricSubscriptionRequest->protocolIEs.list.array[i]->value.choice.RICrequestID.ricInstanceID = sequence_number;
return encode_E2AP_PDU(pdu, buffer, buf_size);
}
}
}
}
if(pdu != NULL)
ASN_STRUCT_FREE(asn_DEF_E2AP_PDU, pdu);
return -1;
}
ssize_t e2ap_encode_ric_subscription_request_message(void *buffer, size_t buf_size, long ricRequestorID, long ricRequestSequenceNumber, long ranFunctionID, void *eventTriggerDefinition, size_t eventTriggerDefinitionSize, int actionCount, long *actionIds, long* actionTypes, RICactionDefinition *actionDefinitions, RICSubsequentAction *subsequentActionTypes)
{
E2AP_PDU_t *init = (E2AP_PDU_t *)calloc(1, sizeof(E2AP_PDU_t));
if(!init) {
fprintf(stderr, "alloc E2AP_PDU failed\n");
return -1;
}
InitiatingMessage_t *initiatingMsg = (InitiatingMessage_t *)calloc(1, sizeof(InitiatingMessage_t));
if(!initiatingMsg) {
fprintf(stderr, "alloc InitiatingMessage failed\n");
ASN_STRUCT_FREE(asn_DEF_E2AP_PDU, init);
return -1;
}
init->choice.initiatingMessage = initiatingMsg;
init->present = E2AP_PDU_PR_initiatingMessage;
initiatingMsg->procedureCode = ProcedureCode_id_RICsubscription;
initiatingMsg->criticality = Criticality_reject;
initiatingMsg->value.present = InitiatingMessage__value_PR_RICsubscriptionRequest;
RICsubscriptionRequest_t *subscription_request = &initiatingMsg->value.choice.RICsubscriptionRequest;
// request contains 5 IEs
// RICrequestID
RICsubscriptionRequest_IEs_t *ies_reqID = (RICsubscriptionRequest_IEs_t *)calloc(1, sizeof(RICsubscriptionRequest_IEs_t));
if(!ies_reqID) {
fprintf(stderr, "alloc RICrequestID failed\n");
ASN_STRUCT_FREE(asn_DEF_E2AP_PDU, init);
return -1;
}
ies_reqID->criticality = Criticality_reject;
ies_reqID->id = ProtocolIE_ID_id_RICrequestID;
ies_reqID->value.present = RICsubscriptionRequest_IEs__value_PR_RICrequestID;
RICrequestID_t *ricrequest_ie = &ies_reqID->value.choice.RICrequestID;
ricrequest_ie->ricRequestorID = ricRequestorID;
ricrequest_ie->ricInstanceID = ricRequestSequenceNumber;
ASN_SEQUENCE_ADD(&subscription_request->protocolIEs.list, ies_reqID);
// RICfunctionID
RICsubscriptionRequest_IEs_t *ies_ranfunc = (RICsubscriptionRequest_IEs_t *)calloc(1, sizeof(RICsubscriptionRequest_IEs_t));
if(!ies_ranfunc) {
fprintf(stderr, "alloc RICfunctionID failed\n");
ASN_STRUCT_FREE(asn_DEF_E2AP_PDU, init);
return -1;
}
ies_ranfunc->criticality = Criticality_reject;
ies_ranfunc->id = ProtocolIE_ID_id_RANfunctionID;
ies_ranfunc->value.present = RICsubscriptionRequest_IEs__value_PR_RANfunctionID;
RANfunctionID_t *ranfunction_ie = &ies_ranfunc->value.choice.RANfunctionID;
*ranfunction_ie = ranFunctionID;
ASN_SEQUENCE_ADD(&subscription_request->protocolIEs.list, ies_ranfunc);
// RICsubscription
RICsubscriptionRequest_IEs_t *ies_subscription = (RICsubscriptionRequest_IEs_t *)calloc(1, sizeof(RICsubscriptionRequest_IEs_t));
if(!ies_subscription) {
fprintf(stderr, "alloc RICsubscription failed\n");
ASN_STRUCT_FREE(asn_DEF_E2AP_PDU, init);
return -1;
}
ies_subscription->criticality = Criticality_reject;
ies_subscription->id = ProtocolIE_ID_id_RICsubscriptionDetails;
ies_subscription->value.present = RICsubscriptionRequest_IEs__value_PR_RICsubscriptionDetails;
RICsubscriptionDetails_t *ricsubscription_ie = &ies_subscription->value.choice.RICsubscriptionDetails;
// RICeventTriggerDefinition
RICeventTriggerDefinition_t *eventTrigger = &ricsubscription_ie->ricEventTriggerDefinition;
eventTrigger->buf = (uint8_t *)calloc(1, eventTriggerDefinitionSize);
if(!eventTrigger->buf) {
fprintf(stderr, "alloc eventTrigger failed\n");
ASN_STRUCT_FREE(asn_DEF_E2AP_PDU, init);
return -1;
}
memcpy(eventTrigger->buf, eventTriggerDefinition, eventTriggerDefinitionSize);
eventTrigger->size = eventTriggerDefinitionSize;
// RICactions-ToBeSetup-List
RICactions_ToBeSetup_List_t *ricActions = &ricsubscription_ie->ricAction_ToBeSetup_List;
int index = 0;
while (index < actionCount) {
RICaction_ToBeSetup_ItemIEs_t *ies_action = (RICaction_ToBeSetup_ItemIEs_t *)calloc(1, sizeof(RICaction_ToBeSetup_ItemIEs_t));
if(!ies_action) {
fprintf(stderr, "alloc RICaction failed\n");
ASN_STRUCT_FREE(asn_DEF_E2AP_PDU, init);
return -1;
}
ies_action->criticality = Criticality_reject;
ies_action->id = ProtocolIE_ID_id_RICaction_ToBeSetup_Item;
ies_action->value.present = RICaction_ToBeSetup_ItemIEs__value_PR_RICaction_ToBeSetup_Item;
RICaction_ToBeSetup_Item_t *ricaction_ie = &ies_action->value.choice.RICaction_ToBeSetup_Item;
ricaction_ie->ricActionID = actionIds[index];
ricaction_ie->ricActionType = actionTypes[index];
int actionDefinitionSize = actionDefinitions[index].size;
if(actionDefinitionSize != 0) {
RICactionDefinition_t *actionDefinition = ricaction_ie->ricActionDefinition;
actionDefinition->buf = (uint8_t *)calloc(1, actionDefinitionSize);
if(!actionDefinition->buf) {
fprintf(stderr, "alloc actionDefinition[%d] failed\n", index);
ASN_STRUCT_FREE(asn_DEF_E2AP_PDU, init);
return -1;
}
memcpy(actionDefinition->buf, actionDefinitions[index].actionDefinition, actionDefinitionSize);
actionDefinition->size = actionDefinitionSize;
}
if(subsequentActionTypes[index].isValid != 0) {
RICsubsequentAction_t *subsequentAction = ricaction_ie->ricSubsequentAction;
subsequentAction->ricSubsequentActionType = subsequentActionTypes[index].subsequentActionType;
subsequentAction->ricTimeToWait = subsequentActionTypes[index].timeToWait;
}
ASN_SEQUENCE_ADD(&ricActions->list, ies_action);
index++;
}
ASN_SEQUENCE_ADD(&subscription_request->protocolIEs.list, ies_subscription);
return encode_E2AP_PDU(init, buffer, buf_size);
}
/* RICsubscriptionResponse */
long e2ap_get_ric_subscription_response_sequence_number(void *buffer, size_t buf_size)
{
E2AP_PDU_t *pdu = decode_E2AP_PDU(buffer, buf_size);
if ( pdu != NULL && pdu->present == E2AP_PDU_PR_successfulOutcome )
{
SuccessfulOutcome_t* successfulOutcome = pdu->choice.successfulOutcome;
if ( successfulOutcome->procedureCode == ProcedureCode_id_RICsubscription
&& successfulOutcome->value.present == SuccessfulOutcome__value_PR_RICsubscriptionResponse)
{
RICsubscriptionResponse_t *ricSubscriptionResponse = &successfulOutcome->value.choice.RICsubscriptionResponse;
for (int i = 0; i < ricSubscriptionResponse->protocolIEs.list.count; ++i )
{
if ( ricSubscriptionResponse->protocolIEs.list.array[i]->id == ProtocolIE_ID_id_RICrequestID )
{
long sequenceNumber = ricSubscriptionResponse->protocolIEs.list.array[i]->value.choice.RICrequestID.ricInstanceID;
ASN_STRUCT_FREE(asn_DEF_E2AP_PDU, pdu);
return sequenceNumber;
}
}
}
}
if(pdu != NULL)
ASN_STRUCT_FREE(asn_DEF_E2AP_PDU, pdu);
return -1;
}
ssize_t e2ap_set_ric_subscription_response_sequence_number(void *buffer, size_t buf_size, long sequence_number)
{
E2AP_PDU_t *pdu = decode_E2AP_PDU(buffer, buf_size);
if ( pdu != NULL && pdu->present == E2AP_PDU_PR_successfulOutcome )
{
SuccessfulOutcome_t* successfulOutcome = pdu->choice.successfulOutcome;
if ( successfulOutcome->procedureCode == ProcedureCode_id_RICsubscription
&& successfulOutcome->value.present == SuccessfulOutcome__value_PR_RICsubscriptionResponse)
{
RICsubscriptionResponse_t *ricSubscriptionResponse = &successfulOutcome->value.choice.RICsubscriptionResponse;
for (int i = 0; i < ricSubscriptionResponse->protocolIEs.list.count; ++i )
{
if ( ricSubscriptionResponse->protocolIEs.list.array[i]->id == ProtocolIE_ID_id_RICrequestID )
{
ricSubscriptionResponse->protocolIEs.list.array[i]->value.choice.RICrequestID.ricInstanceID = sequence_number;
return encode_E2AP_PDU(pdu, buffer, buf_size);
}
}
}
}
if(pdu != NULL)
ASN_STRUCT_FREE(asn_DEF_E2AP_PDU, pdu);
return -1;
}
RICsubscriptionResponseMsg* e2ap_decode_ric_subscription_response_message(void *buffer, size_t buf_size)
{
E2AP_PDU_t *pdu = decode_E2AP_PDU(buffer, buf_size);
if ( pdu != NULL && pdu->present == E2AP_PDU_PR_successfulOutcome)
{
SuccessfulOutcome_t* successfulOutcome = pdu->choice.successfulOutcome;
if ( successfulOutcome->procedureCode == ProcedureCode_id_RICsubscription
&& successfulOutcome->value.present == SuccessfulOutcome__value_PR_RICsubscriptionResponse)
{
RICsubscriptionResponse_t *subscriptionResponse = &(successfulOutcome->value.choice.RICsubscriptionResponse);
RICsubscriptionResponseMsg *msg = (RICsubscriptionResponseMsg *)calloc(1, sizeof(RICsubscriptionResponseMsg));
for (int i = 0; i < subscriptionResponse->protocolIEs.list.count; ++i )
{
if (subscriptionResponse->protocolIEs.list.array[i]->id == ProtocolIE_ID_id_RICrequestID) {
msg->requestorID = subscriptionResponse->protocolIEs.list.array[i]->value.choice.RICrequestID.ricRequestorID;
msg->requestSequenceNumber = subscriptionResponse->protocolIEs.list.array[i]->value.choice.RICrequestID.ricInstanceID;
}
else if (subscriptionResponse->protocolIEs.list.array[i]->id == ProtocolIE_ID_id_RANfunctionID) {
msg->ranfunctionID = subscriptionResponse->protocolIEs.list.array[i]->value.choice.RANfunctionID;
}
else if (subscriptionResponse->protocolIEs.list.array[i]->id == ProtocolIE_ID_id_RICactions_Admitted) {
RICaction_Admitted_List_t *ricActionAdmittedList = &(subscriptionResponse->protocolIEs.list.array[i]->value.choice.RICaction_Admitted_List);
int index = 0;
while (index < ricActionAdmittedList->list.count) {
RICaction_Admitted_ItemIEs_t *ricActionAdmittedItem = (RICaction_Admitted_ItemIEs_t *)ricActionAdmittedList->list.array[index];
if (ricActionAdmittedItem->id == ProtocolIE_ID_id_RICaction_Admitted_Item) {
msg->ricActionAdmittedList.ricActionID[index] = ricActionAdmittedItem->value.choice.RICaction_Admitted_Item.ricActionID;
}
index++;
}
msg->ricActionAdmittedList.count = index;
}
else if (subscriptionResponse->protocolIEs.list.array[i]->id == ProtocolIE_ID_id_RICactions_NotAdmitted) {
RICaction_NotAdmitted_List_t *ricActionNotAdmittedList = &(subscriptionResponse->protocolIEs.list.array[i]->value.choice.RICaction_NotAdmitted_List);
int index = 0;
while (index < ricActionNotAdmittedList->list.count) {
RICaction_NotAdmitted_ItemIEs_t *ricActionNotAdmittedItem = (RICaction_NotAdmitted_ItemIEs_t *)ricActionNotAdmittedList->list.array[index];
if (ricActionNotAdmittedItem->id == ProtocolIE_ID_id_RICaction_NotAdmitted_Item) {
msg->ricActionNotAdmittedList.ricActionID[index] = ricActionNotAdmittedItem->value.choice.RICaction_NotAdmitted_Item.ricActionID;
int RICcauseType = ricActionNotAdmittedItem->value.choice.RICaction_NotAdmitted_Item.cause.present;
switch(RICcauseType) {
case Cause_PR_ricRequest:
msg->ricActionNotAdmittedList.ricCause[index].ricCauseType = Cause_PR_ricRequest;
msg->ricActionNotAdmittedList.ricCause[index].ricCauseID = ricActionNotAdmittedItem->value.choice.RICaction_NotAdmitted_Item.cause.choice.ricRequest;
break;
case Cause_PR_ricService:
msg->ricActionNotAdmittedList.ricCause[index].ricCauseType = Cause_PR_ricService;
msg->ricActionNotAdmittedList.ricCause[index].ricCauseID = ricActionNotAdmittedItem->value.choice.RICaction_NotAdmitted_Item.cause.choice.ricService;
break;
case Cause_PR_transport:
msg->ricActionNotAdmittedList.ricCause[index].ricCauseType = Cause_PR_transport;
msg->ricActionNotAdmittedList.ricCause[index].ricCauseID = ricActionNotAdmittedItem->value.choice.RICaction_NotAdmitted_Item.cause.choice.transport;
break;
case Cause_PR_protocol:
msg->ricActionNotAdmittedList.ricCause[index].ricCauseType = Cause_PR_protocol;
msg->ricActionNotAdmittedList.ricCause[index].ricCauseID = ricActionNotAdmittedItem->value.choice.RICaction_NotAdmitted_Item.cause.choice.protocol;
break;
case Cause_PR_misc:
msg->ricActionNotAdmittedList.ricCause[index].ricCauseType = Cause_PR_misc;
msg->ricActionNotAdmittedList.ricCause[index].ricCauseID = ricActionNotAdmittedItem->value.choice.RICaction_NotAdmitted_Item.cause.choice.misc;
break;
}
}
index++;
}
msg->ricActionNotAdmittedList.count = index;
}
}
return msg;
}
}
return NULL;
}
/* RICsubscriptionFailure */
long e2ap_get_ric_subscription_failure_sequence_number(void *buffer, size_t buf_size)
{
E2AP_PDU_t *pdu = decode_E2AP_PDU(buffer, buf_size);
if ( pdu != NULL && pdu->present == E2AP_PDU_PR_unsuccessfulOutcome )
{
UnsuccessfulOutcome_t* unsuccessfulOutcome = pdu->choice.unsuccessfulOutcome;
if ( unsuccessfulOutcome->procedureCode == ProcedureCode_id_RICsubscription
&& unsuccessfulOutcome->value.present == UnsuccessfulOutcome__value_PR_RICsubscriptionFailure)
{
RICsubscriptionFailure_t *ricSubscriptionFailure = &unsuccessfulOutcome->value.choice.RICsubscriptionFailure;
for (int i = 0; i < ricSubscriptionFailure->protocolIEs.list.count; ++i )
{
if ( ricSubscriptionFailure->protocolIEs.list.array[i]->id == ProtocolIE_ID_id_RICrequestID )
{
long sequenceNumber = ricSubscriptionFailure->protocolIEs.list.array[i]->value.choice.RICrequestID.ricInstanceID;
ASN_STRUCT_FREE(asn_DEF_E2AP_PDU, pdu);
return sequenceNumber;
}
}
}
}
if(pdu != NULL)
ASN_STRUCT_FREE(asn_DEF_E2AP_PDU, pdu);
return -1;
}
/* RICsubscriptionDeleteRequest */
long e2ap_get_ric_subscription_delete_request_sequence_number(void *buffer, size_t buf_size)
{
E2AP_PDU_t *pdu = decode_E2AP_PDU(buffer, buf_size);
if ( pdu != NULL && pdu->present == E2AP_PDU_PR_initiatingMessage )
{
InitiatingMessage_t* initiatingMessage = pdu->choice.initiatingMessage;
if ( initiatingMessage->procedureCode == ProcedureCode_id_RICsubscriptionDelete
&& initiatingMessage->value.present == InitiatingMessage__value_PR_RICsubscriptionDeleteRequest )
{
RICsubscriptionDeleteRequest_t *subscriptionDeleteRequest = &initiatingMessage->value.choice.RICsubscriptionDeleteRequest;
for (int i = 0; i < subscriptionDeleteRequest->protocolIEs.list.count; ++i )
{
if ( subscriptionDeleteRequest->protocolIEs.list.array[i]->id == ProtocolIE_ID_id_RICrequestID )
{
long sequenceNumber = subscriptionDeleteRequest->protocolIEs.list.array[i]->value.choice.RICrequestID.ricInstanceID;
ASN_STRUCT_FREE(asn_DEF_E2AP_PDU, pdu);
return sequenceNumber;
}
}
}
}
if(pdu != NULL)
ASN_STRUCT_FREE(asn_DEF_E2AP_PDU, pdu);
return -1;
}
ssize_t e2ap_set_ric_subscription_delete_request_sequence_number(void *buffer, size_t buf_size, long sequence_number)
{
E2AP_PDU_t *pdu = decode_E2AP_PDU(buffer, buf_size);
if ( pdu != NULL && pdu->present == E2AP_PDU_PR_initiatingMessage )
{
InitiatingMessage_t* initiatingMessage = pdu->choice.initiatingMessage;
if ( initiatingMessage->procedureCode == ProcedureCode_id_RICsubscriptionDelete
&& initiatingMessage->value.present == InitiatingMessage__value_PR_RICsubscriptionDeleteRequest )
{
RICsubscriptionDeleteRequest_t* subscriptionDeleteRequest = &initiatingMessage->value.choice.RICsubscriptionDeleteRequest;
for (int i = 0; i < subscriptionDeleteRequest->protocolIEs.list.count; ++i )
{
if ( subscriptionDeleteRequest->protocolIEs.list.array[i]->id == ProtocolIE_ID_id_RICrequestID )
{
subscriptionDeleteRequest->protocolIEs.list.array[i]->value.choice.RICrequestID.ricInstanceID = sequence_number;
return encode_E2AP_PDU(pdu, buffer, buf_size);
}
}
}
}
if(pdu != NULL)
ASN_STRUCT_FREE(asn_DEF_E2AP_PDU, pdu);
return -1;
}
ssize_t e2ap_encode_ric_subscription_delete_request_message(void *buffer, size_t buf_size, long ricRequestorID, long ricRequestSequenceNumber, long ranFunctionID)
{
E2AP_PDU_t *init = (E2AP_PDU_t *)calloc(1, sizeof(E2AP_PDU_t));
if(!init) {
fprintf(stderr, "alloc E2AP_PDU failed\n");
return -1;
}
InitiatingMessage_t *initiatingMsg = (InitiatingMessage_t *)calloc(1, sizeof(InitiatingMessage_t));
if(!initiatingMsg) {
fprintf(stderr, "alloc InitiatingMessage failed\n");
ASN_STRUCT_FREE(asn_DEF_E2AP_PDU, init);
return -1;
}
init->choice.initiatingMessage = initiatingMsg;
init->present = E2AP_PDU_PR_initiatingMessage;
initiatingMsg->procedureCode = ProcedureCode_id_RICsubscriptionDelete;
initiatingMsg->criticality = Criticality_reject;
initiatingMsg->value.present = InitiatingMessage__value_PR_RICsubscriptionDeleteRequest;
RICsubscriptionDeleteRequest_t *subscription_delete_request = &initiatingMsg->value.choice.RICsubscriptionDeleteRequest;
// request contains 2 IEs
// RICrequestID
RICsubscriptionDeleteRequest_IEs_t *ies_reqID = (RICsubscriptionDeleteRequest_IEs_t *)calloc(1, sizeof(RICsubscriptionDeleteRequest_IEs_t));
if(!ies_reqID) {
fprintf(stderr, "alloc RICrequestID failed\n");
ASN_STRUCT_FREE(asn_DEF_E2AP_PDU, init);
return -1;
}
ies_reqID->criticality = Criticality_reject;
ies_reqID->id = ProtocolIE_ID_id_RICrequestID;
ies_reqID->value.present = RICsubscriptionDeleteRequest_IEs__value_PR_RICrequestID;
RICrequestID_t *ricrequest_ie = &ies_reqID->value.choice.RICrequestID;
ricrequest_ie->ricRequestorID = ricRequestorID;
ricrequest_ie->ricInstanceID = ricRequestSequenceNumber;
ASN_SEQUENCE_ADD(&subscription_delete_request->protocolIEs.list, ies_reqID);
// RICfunctionID
RICsubscriptionDeleteRequest_IEs_t *ies_ranfunc = (RICsubscriptionDeleteRequest_IEs_t *)calloc(1, sizeof(RICsubscriptionDeleteRequest_IEs_t));
if(!ies_ranfunc) {
fprintf(stderr, "alloc RICfunctionID failed\n");
ASN_STRUCT_FREE(asn_DEF_E2AP_PDU, init);
return -1;
}
ies_ranfunc->criticality = Criticality_reject;
ies_ranfunc->id = ProtocolIE_ID_id_RANfunctionID;
ies_ranfunc->value.present = RICsubscriptionDeleteRequest_IEs__value_PR_RANfunctionID;
RANfunctionID_t *ranfunction_ie = &ies_ranfunc->value.choice.RANfunctionID;
*ranfunction_ie = ranFunctionID;
ASN_SEQUENCE_ADD(&subscription_delete_request->protocolIEs.list, ies_ranfunc);
return encode_E2AP_PDU(init, buffer, buf_size);
}
/* RICsubscriptionDeleteResponse */
long e2ap_get_ric_subscription_delete_response_sequence_number(void *buffer, size_t buf_size)
{
E2AP_PDU_t *pdu = decode_E2AP_PDU(buffer, buf_size);
if ( pdu != NULL && pdu->present == E2AP_PDU_PR_successfulOutcome )
{
SuccessfulOutcome_t* successfulOutcome = pdu->choice.successfulOutcome;
if ( successfulOutcome->procedureCode == ProcedureCode_id_RICsubscriptionDelete
&& successfulOutcome->value.present == SuccessfulOutcome__value_PR_RICsubscriptionDeleteResponse )
{
RICsubscriptionDeleteResponse_t* subscriptionDeleteResponse = &successfulOutcome->value.choice.RICsubscriptionDeleteResponse;
for (int i = 0; i < subscriptionDeleteResponse->protocolIEs.list.count; ++i )
{
if ( subscriptionDeleteResponse->protocolIEs.list.array[i]->id == ProtocolIE_ID_id_RICrequestID )
{
long sequenceNumber = subscriptionDeleteResponse->protocolIEs.list.array[i]->value.choice.RICrequestID.ricInstanceID;
ASN_STRUCT_FREE(asn_DEF_E2AP_PDU, pdu);
return sequenceNumber;
}
}
}
}
if(pdu != NULL)
ASN_STRUCT_FREE(asn_DEF_E2AP_PDU, pdu);
return -1;
}
ssize_t e2ap_set_ric_subscription_delete_response_sequence_number(void *buffer, size_t buf_size, long sequence_number)
{
E2AP_PDU_t *pdu = decode_E2AP_PDU(buffer, buf_size);
if ( pdu != NULL && pdu->present == E2AP_PDU_PR_successfulOutcome )
{
SuccessfulOutcome_t* successfulOutcome = pdu->choice.successfulOutcome;
if ( successfulOutcome->procedureCode == ProcedureCode_id_RICsubscriptionDelete
&& successfulOutcome->value.present == SuccessfulOutcome__value_PR_RICsubscriptionDeleteResponse )
{
RICsubscriptionDeleteResponse_t* subscriptionDeleteResponse = &successfulOutcome->value.choice.RICsubscriptionDeleteResponse;
for (int i = 0; i < subscriptionDeleteResponse->protocolIEs.list.count; ++i )
{
if ( subscriptionDeleteResponse->protocolIEs.list.array[i]->id == ProtocolIE_ID_id_RICrequestID )
{
subscriptionDeleteResponse->protocolIEs.list.array[i]->value.choice.RICrequestID.ricInstanceID = sequence_number;
return encode_E2AP_PDU(pdu, buffer, buf_size);
}
}
}
}
if(pdu != NULL)
ASN_STRUCT_FREE(asn_DEF_E2AP_PDU, pdu);
return -1;
}
/* RICsubscriptionDeleteFailure */
long e2ap_get_ric_subscription_delete_failure_sequence_number(void *buffer, size_t buf_size)
{
E2AP_PDU_t *pdu = decode_E2AP_PDU(buffer, buf_size);
if ( pdu != NULL && pdu->present == E2AP_PDU_PR_unsuccessfulOutcome )
{
UnsuccessfulOutcome_t* unsuccessfulOutcome = pdu->choice.unsuccessfulOutcome;
if ( unsuccessfulOutcome->procedureCode == ProcedureCode_id_RICsubscriptionDelete
&& unsuccessfulOutcome->value.present == UnsuccessfulOutcome__value_PR_RICsubscriptionDeleteFailure)
{
RICsubscriptionDeleteFailure_t *ricSubscriptionDeleteFailure = &unsuccessfulOutcome->value.choice.RICsubscriptionDeleteFailure;
for (int i = 0; i < ricSubscriptionDeleteFailure->protocolIEs.list.count; ++i )
{
if ( ricSubscriptionDeleteFailure->protocolIEs.list.array[i]->id == ProtocolIE_ID_id_RICrequestID )
{
long sequenceNumber = ricSubscriptionDeleteFailure->protocolIEs.list.array[i]->value.choice.RICrequestID.ricInstanceID;
ASN_STRUCT_FREE(asn_DEF_E2AP_PDU, pdu);
return sequenceNumber;
}
}
}
}
if(pdu != NULL)
ASN_STRUCT_FREE(asn_DEF_E2AP_PDU, pdu);
return -1;
}
/* RICindication */
RICindicationMsg* e2ap_decode_ric_indication_message(void *buffer, size_t buf_size)
{
E2AP_PDU_t *pdu = decode_E2AP_PDU(buffer, buf_size);
if ( pdu != NULL && pdu->present == E2AP_PDU_PR_initiatingMessage)
{
InitiatingMessage_t* initiatingMessage = pdu->choice.initiatingMessage;
if ( initiatingMessage->procedureCode == ProcedureCode_id_RICindication
&& initiatingMessage->value.present == InitiatingMessage__value_PR_RICindication)
{
RICindication_t *indication = &(initiatingMessage->value.choice.RICindication);
RICindicationMsg *msg = (RICindicationMsg *)calloc(1, sizeof(RICindicationMsg));
for (int i = 0; i < indication->protocolIEs.list.count; ++i )
{
if (indication->protocolIEs.list.array[i]->id == ProtocolIE_ID_id_RICrequestID) {
msg->requestorID = indication->protocolIEs.list.array[i]->value.choice.RICrequestID.ricRequestorID;
msg->requestSequenceNumber = indication->protocolIEs.list.array[i]->value.choice.RICrequestID.ricInstanceID;
}
else if (indication->protocolIEs.list.array[i]->id == ProtocolIE_ID_id_RANfunctionID) {
msg->ranfunctionID = indication->protocolIEs.list.array[i]->value.choice.RANfunctionID;
}
else if (indication->protocolIEs.list.array[i]->id == ProtocolIE_ID_id_RICactionID) {
msg->actionID = indication->protocolIEs.list.array[i]->value.choice.RICactionID;
}
else if(indication->protocolIEs.list.array[i]->id == ProtocolIE_ID_id_RICindicationSN) {
msg->indicationSN = indication->protocolIEs.list.array[i]->value.choice.RICindicationSN;
}
else if(indication->protocolIEs.list.array[i]->id == ProtocolIE_ID_id_RICindicationType) {
msg->indicationType = indication->protocolIEs.list.array[i]->value.choice.RICindicationType;
}
else if(indication->protocolIEs.list.array[i]->id == ProtocolIE_ID_id_RICindicationHeader) {
size_t headerSize = indication->protocolIEs.list.array[i]->value.choice.RICindicationHeader.size;
msg->indicationHeader = calloc(1, headerSize);
if (!msg->indicationHeader) {
fprintf(stderr, "alloc RICindicationHeader failed\n");
e2ap_free_decoded_ric_indication_message(msg);
ASN_STRUCT_FREE(asn_DEF_E2AP_PDU, pdu);
return NULL;
}
memcpy(msg->indicationHeader, indication->protocolIEs.list.array[i]->value.choice.RICindicationHeader.buf, headerSize);
msg->indicationHeaderSize = headerSize;
}
else if(indication->protocolIEs.list.array[i]->id == ProtocolIE_ID_id_RICindicationMessage) {
size_t messsageSize = indication->protocolIEs.list.array[i]->value.choice.RICindicationMessage.size;
msg->indicationMessage = calloc(1, messsageSize);
if (!msg->indicationMessage) {
fprintf(stderr, "alloc RICindicationMessage failed\n");
e2ap_free_decoded_ric_indication_message(msg);
ASN_STRUCT_FREE(asn_DEF_E2AP_PDU, pdu);
return NULL;
}
memcpy(msg->indicationMessage, indication->protocolIEs.list.array[i]->value.choice.RICindicationMessage.buf, messsageSize);
msg->indicationMessageSize = messsageSize;
}
else if(indication->protocolIEs.list.array[i]->id == ProtocolIE_ID_id_RICcallProcessID) {
size_t callProcessIDSize = indication->protocolIEs.list.array[i]->value.choice.RICcallProcessID.size;
msg->callProcessID = calloc(1, callProcessIDSize);
if (!msg->callProcessID) {
fprintf(stderr, "alloc RICcallProcessID failed\n");
e2ap_free_decoded_ric_indication_message(msg);
ASN_STRUCT_FREE(asn_DEF_E2AP_PDU, pdu);
return NULL;
}
memcpy(msg->callProcessID, indication->protocolIEs.list.array[i]->value.choice.RICcallProcessID.buf, callProcessIDSize);
msg->callProcessIDSize = callProcessIDSize;
}
}
return msg;
}
}
if(pdu != NULL)
ASN_STRUCT_FREE(asn_DEF_E2AP_PDU, pdu);
return NULL;
}
void e2ap_free_decoded_ric_indication_message(RICindicationMsg* msg) {
if(msg == NULL) {
return;
}
if(msg->indicationHeader != NULL) {
free(msg->indicationHeader);
msg->indicationHeader = NULL;
}
if(msg->indicationMessage != NULL) {
free(msg->indicationMessage);
msg->indicationMessage = NULL;
}
if(msg->callProcessID != NULL) {
free(msg->callProcessID);
msg->callProcessID = NULL;
}
free(msg);
msg = NULL;
}
|
713787.c | #include <stdio.h>
void check_prime(int);
int main(void)
{
int a, i=0, num;
printf("Please enter how many numbers you want to enter\n");
scanf("%d", &a);
printf("Now enter the integers you want to check\n");
while(i < a)
{
scanf("%d", &num);
check_prime(num);
i++;
}
return 0;
}
void check_prime(int num)
{
int a=2;
while(a <= num-1)
{
if(num%a == 0)
{
printf("\nNot Prime\n");
break;
}
a++;
}
if(a == num)
{
printf("\nPrime\n");
}
}
|
827763.c | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_lstmap.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: parmarti <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/07/06 17:08:03 by parmarti #+# #+# */
/* Updated: 2020/07/08 19:21:20 by parmarti ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
t_list *ft_lstmap(t_list *lst, void *(*f)(void *), void (*del)(void *))
{
t_list *newlst;
t_list *tmp;
if (!lst)
return (NULL);
tmp = ft_lstnew(f(lst->content));
newlst = tmp;
lst = lst->next;
while (lst)
{
if (tmp == NULL)
{
ft_lstclear(&tmp, del);
return (NULL);
}
tmp->next = ft_lstnew(f(lst->content));
lst = lst->next;
tmp = tmp->next;
}
return (newlst);
}
|
463022.c | /* command */
/* gcc -Wall -g -o test inotify_example.c && gdb -q -args /tmp/swp ` */
/* TODO */
/* transform file format */
/* to create file to store the info */
/* the file store 500 lines */
#include <stdio.h>
#include <assert.h>
#include <unistd.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <limits.h>
#include <time.h>
#include <sys/wait.h>
#include <signal.h>
#include <mqueue.h>
#include <fcntl.h> /* For definition of O_NONBLOCK */
#include <sys/mman.h>
#include <sys/types.h>
#include <sys/inotify.h>
#include "tlpi_hdr.h"
#include "filter_file.h"
struct ifile {
char *path; /* file path */
char *lct; /* last created time */
};
#define BUF_LEN 1000
#define NAME_LEN 1000
#define MAXLINE 500
#define NOTIFY_SIG SIGUSR1
#define NOTIFY_SIG_SHM SIGUSR2
#define SIZE 500
#define NAME "/shmtest"
#define MQ_NAME "/mq"
#define MOVEBACK(i, count) \
do{\
for(int i = count; i > 0; --i) { \
ifiles[i] = ifiles[i-1]; \
}\
}while(0)
#define SIGACTION(sig, func) \
do{\
sigemptyset(&sa.sa_mask); \
sa.sa_flags = 0; \
sa.sa_handler = func; \
if(sigaction(sig, &sa, NULL) == -1) \
errExit("sigaction"); \
}while(0)
static struct ifile *ifiles[MAXLINE]={NULL};
static char filepath[100];
int sortifiles(struct ifile *ifiles[],int count);
char* substring(char* ch,int pos,int length);
struct ifile *lalloc(void);
char * getFPath(char *path);
void getCurrentTime(char *buffer);
void setifiletime(struct ifile *ifil);
int getcount(struct ifile *ifiles[], int count);
int isInIfiles(char *path, struct ifile *ifiles[],int count);
void readsourcefile(struct ifile *ifiles[]);
struct ifile *createifile(char *path);
int readshm(void);
void writeshm(int line);
void write2file(void);
void write2file()
{
FILE *fp = NULL;
if ((fp = fopen (filepath, "w+")) == NULL)
{
perror ("File open error!\n");
exit (1);
}
for (int i = 0; i < MAXLINE; ++i) {
char destination[200]={""};
if(ifiles[i])
{
strcat(destination,ifiles[i]->path);
strcat(destination,"%");
strcat(destination,ifiles[i]->lct);
strcat(destination,"\n");
fputs(destination,fp);
/* printf("comming %s %s \n",ifiles[i]->path,ifiles[i]->lct); */
}
}
fclose(fp);
fp = NULL;
}
void writeshm(int line){
int shm_fd;
char *addr;
shm_fd=shm_open(NAME,O_CREAT|O_EXCL|O_RDWR,0666);
if (shm_fd == -1)
{
if (errno == EEXIST)
{
shm_fd=shm_open(NAME, O_RDWR, 0666);
}else{
exit(EXIT_FAILURE);
}
}
ftruncate(shm_fd,SIZE);
if (ftruncate(shm_fd, SIZE) == -1) /* Resize object to hold string */
errExit("ftruncate");
addr = mmap(NULL, SIZE, PROT_READ | PROT_WRITE, MAP_SHARED, shm_fd, 0);
if (addr == MAP_FAILED)
errExit("mmap");
if (close(shm_fd) == -1) /* 'fd' is no longer needed */
errExit("close");
memcpy(addr, &line, SIZE); /* Copy string to shared memory */
kill(getppid(),SIGUSR2);
}
int readshm()
{
int shm;
int shm_fd;
char *addr;
shm_fd=shm_open(NAME,O_CREAT|O_EXCL|O_RDWR,0666);
if (shm_fd == -1)
{
if (errno == EEXIST)
{
shm_fd=shm_open(NAME, O_RDWR, 0666);
}else{
exit(EXIT_FAILURE);
}
}
ftruncate(shm_fd,SIZE);
if (ftruncate(shm_fd, SIZE) == -1) /* Resize object to hold string */
errExit("ftruncate");
printf("Resized to %ld bytes\n", (long) SIZE);
addr = mmap(NULL, SIZE, PROT_READ | PROT_WRITE, MAP_SHARED, shm_fd, 0);
if (addr == MAP_FAILED)
errExit("mmap");
if (close(shm_fd) == -1) /* 'fd' is no longer needed */
errExit("close");
printf("copying %ld bytes\n", (long) SIZE);
/* memcpy( &shm, addr, SIZE); /1* Copy string to shared memory *1/ */
shm = (int)*addr;
return shm;
}
static void getfilepath(void)
{
memset(filepath, '\0', 100);
strcat(filepath,getenv("HOME"));
strcat(filepath,"/.lrc");
}
static void handler(int sig)
{
/* Just interrupt sigsuspend() */
}
static void handler_shm(int sig)
{
int shm = 0;
int startline = 0;
int count = getcount(ifiles, MAXLINE);
shm = readshm();
if (shm) {
startline = shm-1;
free(ifiles[startline]);
while(startline < count)
{
ifiles[startline] = ifiles[startline+1];
startline += 1;
}
}
shm_unlink(NAME);
write2file();
}
char* substring(char* ch,int pos,int length)
{
//定义字符指针 指向传递进来的ch地址
char* pch=ch;
//通过calloc来分配一个length长度的字符数组,返回的是字符指针。
char* subch=(char*)calloc(sizeof(char),length+1);
int i;
//只有在C99下for循环中才可以声明变量,这里写在外面,提高兼容性。
pch=pch+pos;
//是pch指针指向pos位置。
for(i=0;i<length;i++)
{
subch[i]=*(pch++);
//循环遍历赋值数组。
}
subch[length]='\0';//加上字符串结束符。
return subch; //返回分配的字符数组地址。
}
struct ifile *lalloc(void)
{
return (struct ifile *)malloc(sizeof(struct ifile));
}
/*make path to correct path for example
* %home%chandler%test.swp -> /home/chandler/test*/
char * getFPath(char *path)
{
int pathlen = strlen(path)-4;
char *path1 = malloc(pathlen+1);
memset(path1, '\0', pathlen+1);
strncpy(path1, path, pathlen);
for (int j=0;j<pathlen; j++)
{
if (path1[j] == 37) /* 37 is % */
{
path1[j] = 47; /* 48 is / */
}
}
return path1;
}
/*getCurrentTime*/
void getCurrentTime(char *buffer)
{
time_t rawtime;
struct tm *info;
time( &rawtime );
info = localtime( &rawtime );
strftime(buffer, 80, "%Y-%m-%d %H:%M:%S", info);
}
void setifiletime(struct ifile *ifil)
{
char *localtime = (char *)malloc(20);
getCurrentTime(localtime);
ifil->lct = localtime;
}
int getcount(struct ifile *ifiles[], int count)
{
for (int i=0;i<count;i++)
{
if(!ifiles[i])
{
return i;
}
}
return -1;
}
struct ifile *createifile(char *path)
{
struct ifile *ifil;
ifil = (struct ifile *)lalloc();
setifiletime(ifil);
int pathlen = strlen(path);
char *path1 = (char *)malloc(pathlen+1);
ifil->path = strcpy(path1,path);
return ifil;
}
int isInIfiles(char *path, struct ifile *ifiles[],int count)
{
int flag = 0;
for (int i = 0; i < count; ++i)
{
if(!strcmp(ifiles[i]->path,path))
{
flag = 1;
break;
}
}
return flag;
}
int sortifiles(struct ifile *ifiles[],int count)
{
count = count - 1;
MOVEBACK(i, count);
return 0;
}
void readsourcefile(struct ifile *ifiles[])
{
char *p;
FILE *fp;
const char * split = "%";
char arr[MAXLINE+1];
memset(arr, '\0', MAXLINE+1);
int count = 0;
if ((fp = fopen (filepath, "r")) == NULL)
{
perror ("File open error!\n");
exit (1);
}
while ((fgets (arr, MAXLINE, fp)) != NULL)
{
ifiles[count] = lalloc();
p = strtok(arr,split);
char *tmp1=malloc(strlen(p));
ifiles[count]->path = strncpy(tmp1,p,strlen(p));
p = strtok(NULL,split);
char *tmp=malloc(strlen(p)-1);
ifiles[count]->lct = strncpy(tmp,p,strlen(p)-1);
count += 1;
}
fclose(fp);
fp = NULL;
}
int main(int argc,char **argv)
{
int count, flag = 0;
int inotifyFd,wd;
char buf[BUF_LEN];
ssize_t numRead;
char *p;
char *path;
char mode;
int opt;
char *message;
char fullpath1[200]={'\0'};
struct inotify_event *event;
getfilepath();
readsourcefile(ifiles);
/* for child process */
mqd_t mqd;
struct sigevent sev;
struct mq_attr attr = { .mq_maxmsg = 10, .mq_msgsize = 1024 };
void *buffer;
sigset_t blockMask, emptyMask;
struct sigaction sa;
if(argc < 2 )
{
printf("error\n");
}
while (( opt = getopt(argc, argv, "s:")) != -1) {
switch (opt) {
case 's': printf("here"); mode ='s';message = optarg; break;
default: errExit("wrong parameter");
}
}
/* if (optind + 1 >= argc) */
/* errExit("wrong parameter"); */
if (mode == 's')
{
if ((mqd = mq_open(MQ_NAME, O_RDWR | O_CREAT | O_EXCL | O_NONBLOCK, 0660, &attr)) > 0) {
printf("* Create MQ\n");
} else {
if (errno == EEXIST)
{
mqd = mq_open(MQ_NAME, O_RDWR | O_NONBLOCK);
}else{
exit(EXIT_FAILURE);
}
}
if (mq_send(mqd, message, strlen(message), 1) == -1)
errExit("mq_send");
exit(EXIT_SUCCESS);
return 0;
}
switch (fork()) {
case -1:
errExit("fork");
case 0: /* Child: change file offset and status flags */
if ((mqd = mq_open(MQ_NAME, O_RDWR | O_CREAT | O_EXCL | O_NONBLOCK, 0660, &attr)) > 0) {
printf("* Create MQ\n");
} else {
if (errno == EEXIST)
{
mqd = mq_open(MQ_NAME, O_RDONLY | O_NONBLOCK);
}else{
exit(EXIT_FAILURE);
}
}
/* Determine mq_msgsize for message queue, and allocate an input buffer
of that size */
if (mq_getattr(mqd, &attr) == -1)
errExit("mq_getattr");
buffer = malloc(attr.mq_msgsize);
if (buffer == NULL)
errExit("malloc");
/* Block the notification signal and establish a handler for it */
sigemptyset(&blockMask);
sigaddset(&blockMask, NOTIFY_SIG);
if (sigprocmask(SIG_BLOCK, &blockMask, NULL) == -1)
errExit("sigprocmask");
SIGACTION(NOTIFY_SIG, handler);
/* Register for message notification via a signal */
sev.sigev_notify = SIGEV_SIGNAL;
sev.sigev_signo = NOTIFY_SIG;
if (mq_notify(mqd, &sev) == -1)
errExit("mq_notify");
sigemptyset(&emptyMask);
for (;;) {
sigsuspend(&emptyMask); /* Wait for notification signal */
/* Reregister for message notification */
if (mq_notify(mqd, &sev) == -1)
errExit("mq_notify");
while ((numRead = mq_receive(mqd, buffer, attr.mq_msgsize, NULL)) >= 0)
{
/* printf("Read %ld bytes\n", (long) numRead); */
int line = atoi(buffer);
printf("line %d\n",line);
writeshm(line);
/*FIXME: above: should use %zd here, and remove (long) cast */
}
if (errno != EAGAIN) /* Unexpected error */
errExit("mq_receive");
}
default: /* Parent: can see file changes made by child */
SIGACTION(NOTIFY_SIG_SHM, handler_shm);
inotifyFd = inotify_init();
if(inotifyFd == -1)
{
printf("初始化失败");
}
wd = inotify_add_watch(inotifyFd,argv[1],IN_CREATE);
if(wd == -1)
{
printf("error\n");
}
printf("Watching %s using wd %d\n",argv[1],wd);
while(1)
{
/* sigaction for accept a signal to write to sharememory */
numRead = read(inotifyFd,buf,BUF_LEN);
if(numRead == -1)
{
printf("read error\n");
}
printf("Read %ldbytes from inotify fd\n",(long)numRead);
for(p=buf;p < buf+numRead;)
{
count = getcount(ifiles, MAXLINE);
event = (struct inotify_event *)p;
path = event->name;
run_table_script(path,fullpath1);
if(fullpath1[0] == '\0')
{
printf("fullpath is empty\n");
p+=sizeof(struct inotify_event) + event->len;
continue;
}
flag = isInIfiles(fullpath1,ifiles,count);
if(!flag)
{
struct ifile *ifil = createifile(fullpath1);
if (count == MAXLINE)
{
count =count-1;
free(ifiles[count]);
}else{
count = count;
}
MOVEBACK(i,count);
ifiles[0] = ifil;
}else{
for (int i = 0; i < count; ++i)
{
if(!strcmp(ifiles[i]->path,fullpath1))
{
struct ifile *tmp = ifiles[i];
for (int j = i; j > 0; --j) {
ifiles[j] = ifiles[j-1];
}
ifiles[0] = tmp;
break;
}
}
}
p+=sizeof(struct inotify_event) + event->len;
write2file();
}
}
if (wait(NULL) == -1)
errExit("wait"); /* Wait for child exit */
printf("Child has exited\n");
return 0;
}
}
|
444764.c | #include <stdlib.h>
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include "baselib.h"
int music_list_init(music_obj *m)
{
int retvalue = 1;
if (m == NULL) {
retvalue = -1;
print("error\n");
goto end;
}
music_info *tmp;
int i = 100;
while (i--) {
music_info_alloc(&tmp, "a", "b", "c");
music_list_insert(m, tmp);
music_info_alloc(&tmp, "d", "e", "f");
music_list_insert(m, tmp);
music_info_alloc(&tmp, "1", "2", "3");
music_list_insert(m, tmp);
music_info_alloc(&tmp, "4", "5", "6");
music_list_insert(m, tmp);
music_info_alloc(&tmp, "4", "5", "6");
music_list_insert(m, tmp);
}
end:
return retvalue;
}
int main()
{
int retvalue = 1;
int fd;
void *fp;
struct op *o_obj;
music_obj *m_obj;
/*music list init*/
music_list_alloc(&m_obj, 20);
/*config file init*/
fp = file_create("./config");
fd = *(int *)fp;
if (fd == -1) {
retvalue = -1;
goto end;
}
/*file operate init*/
op_init(&o_obj, &fd, m_obj);
op_reg_low_output(o_obj, low_output_cb);
op_reg_high_output(o_obj, high_output_cb);
op_reg_low_input(o_obj, low_input_cb);
op_reg_cur_output(o_obj, cur_output_cb);
/*machine open test*/
machine_open(o_obj);
music_list_print(m_obj);
#if 1
/*machine close test*/
music_list_init(m_obj);
//music_reset("config");
ftruncate(fd, 0);
lseek(fd, 0, SEEK_SET);
machine_close(o_obj, m_obj);
#endif
/*memory recycle*/
op_delete(&o_obj);
music_list_destroy(&m_obj);
close(fd);
end:
return retvalue;
}
|
604536.c | /* Hash Tables Implementation.
*
* This file implements in memory hash tables with insert/del/replace/find/
* get-random-element operations. Hash tables will auto resize if needed
* tables of power of two in size are used, collisions are handled by
* chaining. See the source code for more information... :)
*
* Copyright (c) 2006-2012, Salvatore Sanfilippo <antirez at gmail dot 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:
*
* * 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 Redis 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.
*/
#include "fmacros.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>
#include <limits.h>
#include <sys/time.h>
#include <ctype.h>
#include "dict.h"
#include "zmalloc.h"
#include "redisassert.h"
/* Using dictEnableResize() / dictDisableResize() we make possible to
* enable/disable resizing of the hash table as needed. This is very important
* for Redis, as we use copy-on-write and don't want to move too much memory
* around when there is a child performing saving operations.
*
* Note that even when dict_can_resize is set to 0, not all resizes are
* prevented: a hash table is still allowed to grow if the ratio between
* the number of elements and the buckets > dict_force_resize_ratio. */
static int dict_can_resize = 1;
static unsigned int dict_force_resize_ratio = 5;
/* -------------------------- private prototypes ---------------------------- */
static int _dictExpandIfNeeded(dict *ht);
static unsigned long _dictNextPower(unsigned long size);
static int _dictKeyIndex(dict *ht, const void *key);
static int _dictInit(dict *ht, dictType *type, void *privDataPtr);
/* -------------------------- hash functions -------------------------------- */
/* Thomas Wang's 32 bit Mix Function */
unsigned int dictIntHashFunction(unsigned int key)
{
key += ~(key << 15);
key ^= (key >> 10);
key += (key << 3);
key ^= (key >> 6);
key += ~(key << 11);
key ^= (key >> 16);
return key;
}
static uint32_t dict_hash_function_seed = 5381;
void dictSetHashFunctionSeed(uint32_t seed) {
dict_hash_function_seed = seed;
}
uint32_t dictGetHashFunctionSeed(void) {
return dict_hash_function_seed;
}
/* MurmurHash2, by Austin Appleby
* Note - This code makes a few assumptions about how your machine behaves -
* 1. We can read a 4-byte value from any address without crashing
* 2. sizeof(int) == 4
*
* And it has a few limitations -
*
* 1. It will not work incrementally.
* 2. It will not produce the same results on little-endian and big-endian
* machines.
*/
unsigned int dictGenHashFunction(const void *key, int len) {
/* 'm' and 'r' are mixing constants generated offline.
They're not really 'magic', they just happen to work well. */
uint32_t seed = dict_hash_function_seed;
const uint32_t m = 0x5bd1e995;
const int r = 24;
/* Initialize the hash to a 'random' value */
uint32_t h = seed ^ len;
/* Mix 4 bytes at a time into the hash */
const unsigned char *data = (const unsigned char *)key;
while(len >= 4) {
uint32_t k = *(uint32_t*)data;
k *= m;
k ^= k >> r;
k *= m;
h *= m;
h ^= k;
data += 4;
len -= 4;
}
/* Handle the last few bytes of the input array */
switch(len) {
case 3: h ^= data[2] << 16;
case 2: h ^= data[1] << 8;
case 1: h ^= data[0]; h *= m;
};
/* Do a few final mixes of the hash to ensure the last few
* bytes are well-incorporated. */
h ^= h >> 13;
h *= m;
h ^= h >> 15;
return (unsigned int)h;
}
/* And a case insensitive hash function (based on djb hash) */
unsigned int dictGenCaseHashFunction(const unsigned char *buf, int len) {
unsigned int hash = (unsigned int)dict_hash_function_seed;
while (len--)
hash = ((hash << 5) + hash) + (tolower(*buf++)); /* hash * 33 + c */
return hash;
}
/* ----------------------------- API implementation ------------------------- */
/* Reset a hash table already initialized with ht_init().
* NOTE: This function should only be called by ht_destroy(). */
static void _dictReset(dictht *ht)
{
ht->table = NULL;
ht->size = 0;
ht->sizemask = 0;
ht->used = 0;
}
/* Create a new hash table */
dict *dictCreate(dictType *type,
void *privDataPtr)
{
dict *d = zmalloc(sizeof(*d));
_dictInit(d,type,privDataPtr);
return d;
}
/* Initialize the hash table */
int _dictInit(dict *d, dictType *type,
void *privDataPtr)
{
_dictReset(&d->ht[0]);
_dictReset(&d->ht[1]);
d->type = type;
d->privdata = privDataPtr;
d->rehashidx = -1;
d->iterators = 0;
return DICT_OK;
}
/* Resize the table to the minimal size that contains all the elements,
* but with the invariant of a USED/BUCKETS ratio near to <= 1 */
int dictResize(dict *d)
{
int minimal;
if (!dict_can_resize || dictIsRehashing(d)) return DICT_ERR;
minimal = d->ht[0].used;
if (minimal < DICT_HT_INITIAL_SIZE)
minimal = DICT_HT_INITIAL_SIZE;
return dictExpand(d, minimal);
}
/* Expand or create the hash table */
int dictExpand(dict *d, unsigned long size)
{
dictht n; /* the new hash table */
unsigned long realsize = _dictNextPower(size);
/* the size is invalid if it is smaller than the number of
* elements already inside the hash table */
if (dictIsRehashing(d) || d->ht[0].used > size)
return DICT_ERR;
/* Rehashing to the same table size is not useful. */
if (realsize == d->ht[0].size) return DICT_ERR;
/* Allocate the new hash table and initialize all pointers to NULL */
n.size = realsize;
n.sizemask = realsize-1;
n.table = zcalloc(realsize*sizeof(dictEntry*));
n.used = 0;
/* Is this the first initialization? If so it's not really a rehashing
* we just set the first hash table so that it can accept keys. */
if (d->ht[0].table == NULL) {
d->ht[0] = n;
return DICT_OK;
}
/* Prepare a second hash table for incremental rehashing */
d->ht[1] = n;
d->rehashidx = 0;
return DICT_OK;
}
/* Performs N steps of incremental rehashing. Returns 1 if there are still
* keys to move from the old to the new hash table, otherwise 0 is returned.
*
* Note that a rehashing step consists in moving a bucket (that may have more
* than one key as we use chaining) from the old to the new hash table, however
* since part of the hash table may be composed of empty spaces, it is not
* guaranteed that this function will rehash even a single bucket, since it
* will visit at max N*10 empty buckets in total, otherwise the amount of
* work it does would be unbound and the function may block for a long time. */
int dictRehash(dict *d, int n) {
int empty_visits = n*10; /* Max number of empty buckets to visit. */
if (!dictIsRehashing(d)) return 0;
while(n-- && d->ht[0].used != 0) {
dictEntry *de, *nextde;
/* Note that rehashidx can't overflow as we are sure there are more
* elements because ht[0].used != 0 */
assert(d->ht[0].size > (unsigned long)d->rehashidx);
while(d->ht[0].table[d->rehashidx] == NULL) {
d->rehashidx++;
if (--empty_visits == 0) return 1;
}
de = d->ht[0].table[d->rehashidx];
/* Move all the keys in this bucket from the old to the new hash HT */
while(de) {
unsigned int h;
nextde = de->next;
/* Get the index in the new hash table */
h = dictHashKey(d, de->key) & d->ht[1].sizemask;
de->next = d->ht[1].table[h];
d->ht[1].table[h] = de;
d->ht[0].used--;
d->ht[1].used++;
de = nextde;
}
d->ht[0].table[d->rehashidx] = NULL;
d->rehashidx++;
}
/* Check if we already rehashed the whole table... */
if (d->ht[0].used == 0) {
zfree(d->ht[0].table);
d->ht[0] = d->ht[1];
_dictReset(&d->ht[1]);
d->rehashidx = -1;
return 0;
}
/* More to rehash... */
return 1;
}
long long timeInMilliseconds(void) {
struct timeval tv;
gettimeofday(&tv,NULL);
return (((long long)tv.tv_sec)*1000)+(tv.tv_usec/1000);
}
/* Rehash for an amount of time between ms milliseconds and ms+1 milliseconds */
int dictRehashMilliseconds(dict *d, int ms) {
long long start = timeInMilliseconds();
int rehashes = 0;
while(dictRehash(d,100)) {
rehashes += 100;
if (timeInMilliseconds()-start > ms) break;
}
return rehashes;
}
/* This function performs just a step of rehashing, and only if there are
* no safe iterators bound to our hash table. When we have iterators in the
* middle of a rehashing we can't mess with the two hash tables otherwise
* some element can be missed or duplicated.
*
* This function is called by common lookup or update operations in the
* dictionary so that the hash table automatically migrates from H1 to H2
* while it is actively used. */
static void _dictRehashStep(dict *d) {
if (d->iterators == 0) dictRehash(d,1);
}
/* Add an element to the target hash table */
int dictAdd(dict *d, void *key, void *val)
{
dictEntry *entry = dictAddRaw(d,key);
if (!entry) return DICT_ERR;
dictSetVal(d, entry, val);
return DICT_OK;
}
/* Low level add. This function adds the entry but instead of setting
* a value returns the dictEntry structure to the user, that will make
* sure to fill the value field as he wishes.
*
* This function is also directly exposed to the user API to be called
* mainly in order to store non-pointers inside the hash value, example:
*
* entry = dictAddRaw(dict,mykey);
* if (entry != NULL) dictSetSignedIntegerVal(entry,1000);
*
* Return values:
*
* If key already exists NULL is returned.
* If key was added, the hash entry is returned to be manipulated by the caller.
*/
dictEntry *dictAddRaw(dict *d, void *key)
{
int index;
dictEntry *entry;
dictht *ht;
if (dictIsRehashing(d)) _dictRehashStep(d);
/* Get the index of the new element, or -1 if
* the element already exists. */
if ((index = _dictKeyIndex(d, key)) == -1)
return NULL;
/* Allocate the memory and store the new entry */
ht = dictIsRehashing(d) ? &d->ht[1] : &d->ht[0];
entry = zmalloc(sizeof(*entry));
entry->next = ht->table[index];
ht->table[index] = entry;
ht->used++;
/* Set the hash entry fields. */
dictSetKey(d, entry, key);
return entry;
}
/* Add an element, discarding the old if the key already exists.
* Return 1 if the key was added from scratch, 0 if there was already an
* element with such key and dictReplace() just performed a value update
* operation. */
int dictReplace(dict *d, void *key, void *val)
{
dictEntry *entry, auxentry;
/* Try to add the element. If the key
* does not exists dictAdd will suceed. */
if (dictAdd(d, key, val) == DICT_OK)
return 1;
/* It already exists, get the entry */
entry = dictFind(d, key);
/* Set the new value and free the old one. Note that it is important
* to do that in this order, as the value may just be exactly the same
* as the previous one. In this context, think to reference counting,
* you want to increment (set), and then decrement (free), and not the
* reverse. */
auxentry = *entry;
dictSetVal(d, entry, val);
dictFreeVal(d, &auxentry);
return 0;
}
/* dictReplaceRaw() is simply a version of dictAddRaw() that always
* returns the hash entry of the specified key, even if the key already
* exists and can't be added (in that case the entry of the already
* existing key is returned.)
*
* See dictAddRaw() for more information. */
dictEntry *dictReplaceRaw(dict *d, void *key) {
dictEntry *entry = dictFind(d,key);
return entry ? entry : dictAddRaw(d,key);
}
/* Search and remove an element */
static int dictGenericDelete(dict *d, const void *key, int nofree)
{
unsigned int h, idx;
dictEntry *he, *prevHe;
int table;
if (d->ht[0].size == 0) return DICT_ERR; /* d->ht[0].table is NULL */
if (dictIsRehashing(d)) _dictRehashStep(d);
h = dictHashKey(d, key);
for (table = 0; table <= 1; table++) {
idx = h & d->ht[table].sizemask;
he = d->ht[table].table[idx];
prevHe = NULL;
while(he) {
if (dictCompareKeys(d, key, he->key)) {
/* Unlink the element from the list */
if (prevHe)
prevHe->next = he->next;
else
d->ht[table].table[idx] = he->next;
if (!nofree) {
dictFreeKey(d, he);
dictFreeVal(d, he);
}
zfree(he);
d->ht[table].used--;
return DICT_OK;
}
prevHe = he;
he = he->next;
}
if (!dictIsRehashing(d)) break;
}
return DICT_ERR; /* not found */
}
int dictDelete(dict *ht, const void *key) {
return dictGenericDelete(ht,key,0);
}
int dictDeleteNoFree(dict *ht, const void *key) {
return dictGenericDelete(ht,key,1);
}
/* Destroy an entire dictionary */
int _dictClear(dict *d, dictht *ht, void(callback)(void *)) {
unsigned long i;
/* Free all the elements */
for (i = 0; i < ht->size && ht->used > 0; i++) {
dictEntry *he, *nextHe;
if (callback && (i & 65535) == 0) callback(d->privdata);
if ((he = ht->table[i]) == NULL) continue;
while(he) {
nextHe = he->next;
dictFreeKey(d, he);
dictFreeVal(d, he);
zfree(he);
ht->used--;
he = nextHe;
}
}
/* Free the table and the allocated cache structure */
zfree(ht->table);
/* Re-initialize the table */
_dictReset(ht);
return DICT_OK; /* never fails */
}
/* Clear & Release the hash table */
void dictRelease(dict *d)
{
_dictClear(d,&d->ht[0],NULL);
_dictClear(d,&d->ht[1],NULL);
zfree(d);
}
dictEntry *dictFind(dict *d, const void *key)
{
dictEntry *he;
unsigned int h, idx, table;
if (d->ht[0].size == 0) return NULL; /* We don't have a table at all */
if (dictIsRehashing(d)) _dictRehashStep(d);
h = dictHashKey(d, key);
for (table = 0; table <= 1; table++) {
idx = h & d->ht[table].sizemask;
he = d->ht[table].table[idx];
while(he) {
if (dictCompareKeys(d, key, he->key))
return he;
he = he->next;
}
if (!dictIsRehashing(d)) return NULL;
}
return NULL;
}
void *dictFetchValue(dict *d, const void *key) {
dictEntry *he;
he = dictFind(d,key);
return he ? dictGetVal(he) : NULL;
}
/* A fingerprint is a 64 bit number that represents the state of the dictionary
* at a given time, it's just a few dict properties xored together.
* When an unsafe iterator is initialized, we get the dict fingerprint, and check
* the fingerprint again when the iterator is released.
* If the two fingerprints are different it means that the user of the iterator
* performed forbidden operations against the dictionary while iterating. */
long long dictFingerprint(dict *d) {
long long integers[6], hash = 0;
int j;
integers[0] = (long) d->ht[0].table;
integers[1] = d->ht[0].size;
integers[2] = d->ht[0].used;
integers[3] = (long) d->ht[1].table;
integers[4] = d->ht[1].size;
integers[5] = d->ht[1].used;
/* We hash N integers by summing every successive integer with the integer
* hashing of the previous sum. Basically:
*
* Result = hash(hash(hash(int1)+int2)+int3) ...
*
* This way the same set of integers in a different order will (likely) hash
* to a different number. */
for (j = 0; j < 6; j++) {
hash += integers[j];
/* For the hashing step we use Tomas Wang's 64 bit integer hash. */
hash = (~hash) + (hash << 21); // hash = (hash << 21) - hash - 1;
hash = hash ^ (hash >> 24);
hash = (hash + (hash << 3)) + (hash << 8); // hash * 265
hash = hash ^ (hash >> 14);
hash = (hash + (hash << 2)) + (hash << 4); // hash * 21
hash = hash ^ (hash >> 28);
hash = hash + (hash << 31);
}
return hash;
}
dictIterator *dictGetIterator(dict *d)
{
dictIterator *iter = zmalloc(sizeof(*iter));
iter->d = d;
iter->table = 0;
iter->index = -1;
iter->safe = 0;
iter->entry = NULL;
iter->nextEntry = NULL;
return iter;
}
dictIterator *dictGetSafeIterator(dict *d) {
dictIterator *i = dictGetIterator(d);
i->safe = 1;
return i;
}
dictEntry *dictNext(dictIterator *iter)
{
while (1) {
if (iter->entry == NULL) {
dictht *ht = &iter->d->ht[iter->table];
if (iter->index == -1 && iter->table == 0) {
if (iter->safe)
iter->d->iterators++;
else
iter->fingerprint = dictFingerprint(iter->d);
}
iter->index++;
if (iter->index >= (long) ht->size) {
if (dictIsRehashing(iter->d) && iter->table == 0) {
iter->table++;
iter->index = 0;
ht = &iter->d->ht[1];
} else {
break;
}
}
iter->entry = ht->table[iter->index];
} else {
iter->entry = iter->nextEntry;
}
if (iter->entry) {
/* We need to save the 'next' here, the iterator user
* may delete the entry we are returning. */
iter->nextEntry = iter->entry->next;
return iter->entry;
}
}
return NULL;
}
void dictReleaseIterator(dictIterator *iter)
{
if (!(iter->index == -1 && iter->table == 0)) {
if (iter->safe)
iter->d->iterators--;
else
assert(iter->fingerprint == dictFingerprint(iter->d));
}
zfree(iter);
}
/* Return a random entry from the hash table. Useful to
* implement randomized algorithms */
dictEntry *dictGetRandomKey(dict *d)
{
dictEntry *he, *orighe;
unsigned int h;
int listlen, listele;
if (dictSize(d) == 0) return NULL;
if (dictIsRehashing(d)) _dictRehashStep(d);
if (dictIsRehashing(d)) {
do {
/* We are sure there are no elements in indexes from 0
* to rehashidx-1 */
h = d->rehashidx + (random() % (d->ht[0].size +
d->ht[1].size -
d->rehashidx));
he = (h >= d->ht[0].size) ? d->ht[1].table[h - d->ht[0].size] :
d->ht[0].table[h];
} while(he == NULL);
} else {
do {
h = random() & d->ht[0].sizemask;
he = d->ht[0].table[h];
} while(he == NULL);
}
/* Now we found a non empty bucket, but it is a linked
* list and we need to get a random element from the list.
* The only sane way to do so is counting the elements and
* select a random index. */
listlen = 0;
orighe = he;
while(he) {
he = he->next;
listlen++;
}
listele = random() % listlen;
he = orighe;
while(listele--) he = he->next;
return he;
}
/* This function samples the dictionary to return a few keys from random
* locations.
*
* It does not guarantee to return all the keys specified in 'count', nor
* it does guarantee to return non-duplicated elements, however it will make
* some effort to do both things.
*
* Returned pointers to hash table entries are stored into 'des' that
* points to an array of dictEntry pointers. The array must have room for
* at least 'count' elements, that is the argument we pass to the function
* to tell how many random elements we need.
*
* The function returns the number of items stored into 'des', that may
* be less than 'count' if the hash table has less than 'count' elements
* inside, or if not enough elements were found in a reasonable amount of
* steps.
*
* Note that this function is not suitable when you need a good distribution
* of the returned items, but only when you need to "sample" a given number
* of continuous elements to run some kind of algorithm or to produce
* statistics. However the function is much faster than dictGetRandomKey()
* at producing N elements. */
unsigned int dictGetSomeKeys(dict *d, dictEntry **des, unsigned int count) {
unsigned int j; /* internal hash table id, 0 or 1. */
unsigned int tables; /* 1 or 2 tables? */
unsigned int stored = 0, maxsizemask;
unsigned int maxsteps;
if (dictSize(d) < count) count = dictSize(d);
maxsteps = count*10;
/* Try to do a rehashing work proportional to 'count'. */
for (j = 0; j < count; j++) {
if (dictIsRehashing(d))
_dictRehashStep(d);
else
break;
}
tables = dictIsRehashing(d) ? 2 : 1;
maxsizemask = d->ht[0].sizemask;
if (tables > 1 && maxsizemask < d->ht[1].sizemask)
maxsizemask = d->ht[1].sizemask;
/* Pick a random point inside the larger table. */
unsigned int i = random() & maxsizemask;
unsigned int emptylen = 0; /* Continuous empty entries so far. */
while(stored < count && maxsteps--) {
for (j = 0; j < tables; j++) {
/* Invariant of the dict.c rehashing: up to the indexes already
* visited in ht[0] during the rehashing, there are no populated
* buckets, so we can skip ht[0] for indexes between 0 and idx-1. */
if (tables == 2 && j == 0 && i < (unsigned int) d->rehashidx) {
/* Moreover, if we are currently out of range in the second
* table, there will be no elements in both tables up to
* the current rehashing index, so we jump if possible.
* (this happens when going from big to small table). */
if (i >= d->ht[1].size) i = d->rehashidx;
continue;
}
if (i >= d->ht[j].size) continue; /* Out of range for this table. */
dictEntry *he = d->ht[j].table[i];
/* Count contiguous empty buckets, and jump to other
* locations if they reach 'count' (with a minimum of 5). */
if (he == NULL) {
emptylen++;
if (emptylen >= 5 && emptylen > count) {
i = random() & maxsizemask;
emptylen = 0;
}
} else {
emptylen = 0;
while (he) {
/* Collect all the elements of the buckets found non
* empty while iterating. */
*des = he;
des++;
he = he->next;
stored++;
if (stored == count) return stored;
}
}
}
i = (i+1) & maxsizemask;
}
return stored;
}
/* Function to reverse bits. Algorithm from:
* http://graphics.stanford.edu/~seander/bithacks.html#ReverseParallel */
static unsigned long rev(unsigned long v) {
unsigned long s = 8 * sizeof(v); // bit size; must be power of 2
unsigned long mask = ~0;
while ((s >>= 1) > 0) {
mask ^= (mask << s);
v = ((v >> s) & mask) | ((v << s) & ~mask);
}
return v;
}
/* dictScan() is used to iterate over the elements of a dictionary.
*
* Iterating works the following way:
*
* 1) Initially you call the function using a cursor (v) value of 0.
* 2) The function performs one step of the iteration, and returns the
* new cursor value you must use in the next call.
* 3) When the returned cursor is 0, the iteration is complete.
*
* The function guarantees all elements present in the
* dictionary get returned between the start and end of the iteration.
* However it is possible some elements get returned multiple times.
*
* For every element returned, the callback argument 'fn' is
* called with 'privdata' as first argument and the dictionary entry
* 'de' as second argument.
*
* HOW IT WORKS.
*
* The iteration algorithm was designed by Pieter Noordhuis.
* The main idea is to increment a cursor starting from the higher order
* bits. That is, instead of incrementing the cursor normally, the bits
* of the cursor are reversed, then the cursor is incremented, and finally
* the bits are reversed again.
*
* This strategy is needed because the hash table may be resized between
* iteration calls.
*
* dict.c hash tables are always power of two in size, and they
* use chaining, so the position of an element in a given table is given
* by computing the bitwise AND between Hash(key) and SIZE-1
* (where SIZE-1 is always the mask that is equivalent to taking the rest
* of the division between the Hash of the key and SIZE).
*
* For example if the current hash table size is 16, the mask is
* (in binary) 1111. The position of a key in the hash table will always be
* the last four bits of the hash output, and so forth.
*
* WHAT HAPPENS IF THE TABLE CHANGES IN SIZE?
*
* If the hash table grows, elements can go anywhere in one multiple of
* the old bucket: for example let's say we already iterated with
* a 4 bit cursor 1100 (the mask is 1111 because hash table size = 16).
*
* If the hash table will be resized to 64 elements, then the new mask will
* be 111111. The new buckets you obtain by substituting in ??1100
* with either 0 or 1 can be targeted only by keys we already visited
* when scanning the bucket 1100 in the smaller hash table.
*
* By iterating the higher bits first, because of the inverted counter, the
* cursor does not need to restart if the table size gets bigger. It will
* continue iterating using cursors without '1100' at the end, and also
* without any other combination of the final 4 bits already explored.
*
* Similarly when the table size shrinks over time, for example going from
* 16 to 8, if a combination of the lower three bits (the mask for size 8
* is 111) were already completely explored, it would not be visited again
* because we are sure we tried, for example, both 0111 and 1111 (all the
* variations of the higher bit) so we don't need to test it again.
*
* WAIT... YOU HAVE *TWO* TABLES DURING REHASHING!
*
* Yes, this is true, but we always iterate the smaller table first, then
* we test all the expansions of the current cursor into the larger
* table. For example if the current cursor is 101 and we also have a
* larger table of size 16, we also test (0)101 and (1)101 inside the larger
* table. This reduces the problem back to having only one table, where
* the larger one, if it exists, is just an expansion of the smaller one.
*
* LIMITATIONS
*
* This iterator is completely stateless, and this is a huge advantage,
* including no additional memory used.
*
* The disadvantages resulting from this design are:
*
* 1) It is possible we return elements more than once. However this is usually
* easy to deal with in the application level.
* 2) The iterator must return multiple elements per call, as it needs to always
* return all the keys chained in a given bucket, and all the expansions, so
* we are sure we don't miss keys moving during rehashing.
* 3) The reverse cursor is somewhat hard to understand at first, but this
* comment is supposed to help.
*/
unsigned long dictScan(dict *d,
unsigned long v,
dictScanFunction *fn,
void *privdata)
{
dictht *t0, *t1;
const dictEntry *de;
unsigned long m0, m1;
if (dictSize(d) == 0) return 0;
if (!dictIsRehashing(d)) {
t0 = &(d->ht[0]);
m0 = t0->sizemask;
/* Emit entries at cursor */
de = t0->table[v & m0];
while (de) {
fn(privdata, de);
de = de->next;
}
} else {
t0 = &d->ht[0];
t1 = &d->ht[1];
/* Make sure t0 is the smaller and t1 is the bigger table */
if (t0->size > t1->size) {
t0 = &d->ht[1];
t1 = &d->ht[0];
}
m0 = t0->sizemask;
m1 = t1->sizemask;
/* Emit entries at cursor */
de = t0->table[v & m0];
while (de) {
fn(privdata, de);
de = de->next;
}
/* Iterate over indices in larger table that are the expansion
* of the index pointed to by the cursor in the smaller table */
do {
/* Emit entries at cursor */
de = t1->table[v & m1];
while (de) {
fn(privdata, de);
de = de->next;
}
/* Increment bits not covered by the smaller mask */
v = (((v | m0) + 1) & ~m0) | (v & m0);
/* Continue while bits covered by mask difference is non-zero */
} while (v & (m0 ^ m1));
}
/* Set unmasked bits so incrementing the reversed cursor
* operates on the masked bits of the smaller table */
v |= ~m0;
/* Increment the reverse cursor */
v = rev(v);
v++;
v = rev(v);
return v;
}
/* ------------------------- private functions ------------------------------ */
/* Expand the hash table if needed */
static int _dictExpandIfNeeded(dict *d)
{
/* Incremental rehashing already in progress. Return. */
if (dictIsRehashing(d)) return DICT_OK;
/* If the hash table is empty expand it to the initial size. */
if (d->ht[0].size == 0) return dictExpand(d, DICT_HT_INITIAL_SIZE);
/* If we reached the 1:1 ratio, and we are allowed to resize the hash
* table (global setting) or we should avoid it but the ratio between
* elements/buckets is over the "safe" threshold, we resize doubling
* the number of buckets. */
if (d->ht[0].used >= d->ht[0].size &&
(dict_can_resize ||
d->ht[0].used/d->ht[0].size > dict_force_resize_ratio))
{
return dictExpand(d, d->ht[0].used*2);
}
return DICT_OK;
}
/* Our hash table capability is a power of two */
static unsigned long _dictNextPower(unsigned long size)
{
unsigned long i = DICT_HT_INITIAL_SIZE;
if (size >= LONG_MAX) return LONG_MAX;
while(1) {
if (i >= size)
return i;
i *= 2;
}
}
/* Returns the index of a free slot that can be populated with
* a hash entry for the given 'key'.
* If the key already exists, -1 is returned.
*
* Note that if we are in the process of rehashing the hash table, the
* index is always returned in the context of the second (new) hash table. */
static int _dictKeyIndex(dict *d, const void *key)
{
unsigned int h, idx, table;
dictEntry *he;
/* Expand the hash table if needed */
if (_dictExpandIfNeeded(d) == DICT_ERR)
return -1;
/* Compute the key hash value */
h = dictHashKey(d, key);
for (table = 0; table <= 1; table++) {
idx = h & d->ht[table].sizemask;
/* Search if this slot does not already contain the given key */
he = d->ht[table].table[idx];
while(he) {
if (dictCompareKeys(d, key, he->key))
return -1;
he = he->next;
}
if (!dictIsRehashing(d)) break;
}
return idx;
}
void dictEmpty(dict *d, void(callback)(void*)) {
_dictClear(d,&d->ht[0],callback);
_dictClear(d,&d->ht[1],callback);
d->rehashidx = -1;
d->iterators = 0;
}
void dictEnableResize(void) {
dict_can_resize = 1;
}
void dictDisableResize(void) {
dict_can_resize = 0;
}
#if 0
/* The following is code that we don't use for Redis currently, but that is part
of the library. */
/* ----------------------- Debugging ------------------------*/
#define DICT_STATS_VECTLEN 50
static void _dictPrintStatsHt(dictht *ht) {
unsigned long i, slots = 0, chainlen, maxchainlen = 0;
unsigned long totchainlen = 0;
unsigned long clvector[DICT_STATS_VECTLEN];
if (ht->used == 0) {
printf("No stats available for empty dictionaries\n");
return;
}
for (i = 0; i < DICT_STATS_VECTLEN; i++) clvector[i] = 0;
for (i = 0; i < ht->size; i++) {
dictEntry *he;
if (ht->table[i] == NULL) {
clvector[0]++;
continue;
}
slots++;
/* For each hash entry on this slot... */
chainlen = 0;
he = ht->table[i];
while(he) {
chainlen++;
he = he->next;
}
clvector[(chainlen < DICT_STATS_VECTLEN) ? chainlen : (DICT_STATS_VECTLEN-1)]++;
if (chainlen > maxchainlen) maxchainlen = chainlen;
totchainlen += chainlen;
}
printf("Hash table stats:\n");
printf(" table size: %ld\n", ht->size);
printf(" number of elements: %ld\n", ht->used);
printf(" different slots: %ld\n", slots);
printf(" max chain length: %ld\n", maxchainlen);
printf(" avg chain length (counted): %.02f\n", (float)totchainlen/slots);
printf(" avg chain length (computed): %.02f\n", (float)ht->used/slots);
printf(" Chain length distribution:\n");
for (i = 0; i < DICT_STATS_VECTLEN-1; i++) {
if (clvector[i] == 0) continue;
printf(" %s%ld: %ld (%.02f%%)\n",(i == DICT_STATS_VECTLEN-1)?">= ":"", i, clvector[i], ((float)clvector[i]/ht->size)*100);
}
}
void dictPrintStats(dict *d) {
_dictPrintStatsHt(&d->ht[0]);
if (dictIsRehashing(d)) {
printf("-- Rehashing into ht[1]:\n");
_dictPrintStatsHt(&d->ht[1]);
}
}
/* ----------------------- StringCopy Hash Table Type ------------------------*/
static unsigned int _dictStringCopyHTHashFunction(const void *key)
{
return dictGenHashFunction(key, strlen(key));
}
static void *_dictStringDup(void *privdata, const void *key)
{
int len = strlen(key);
char *copy = zmalloc(len+1);
DICT_NOTUSED(privdata);
memcpy(copy, key, len);
copy[len] = '\0';
return copy;
}
static int _dictStringCopyHTKeyCompare(void *privdata, const void *key1,
const void *key2)
{
DICT_NOTUSED(privdata);
return strcmp(key1, key2) == 0;
}
static void _dictStringDestructor(void *privdata, void *key)
{
DICT_NOTUSED(privdata);
zfree(key);
}
dictType dictTypeHeapStringCopyKey = {
_dictStringCopyHTHashFunction, /* hash function */
_dictStringDup, /* key dup */
NULL, /* val dup */
_dictStringCopyHTKeyCompare, /* key compare */
_dictStringDestructor, /* key destructor */
NULL /* val destructor */
};
/* This is like StringCopy but does not auto-duplicate the key.
* It's used for intepreter's shared strings. */
dictType dictTypeHeapStrings = {
_dictStringCopyHTHashFunction, /* hash function */
NULL, /* key dup */
NULL, /* val dup */
_dictStringCopyHTKeyCompare, /* key compare */
_dictStringDestructor, /* key destructor */
NULL /* val destructor */
};
/* This is like StringCopy but also automatically handle dynamic
* allocated C strings as values. */
dictType dictTypeHeapStringCopyKeyValue = {
_dictStringCopyHTHashFunction, /* hash function */
_dictStringDup, /* key dup */
_dictStringDup, /* val dup */
_dictStringCopyHTKeyCompare, /* key compare */
_dictStringDestructor, /* key destructor */
_dictStringDestructor, /* val destructor */
};
#endif
|
623270.c | #include <stdio.h>
#include <math.h>
int main()
{
float num; scanf("%f", &num);
printf("|%.2f|\n", floor(num*100)/100);
printf("|%.5f|\n", floor(num*100000)/100000);
printf("| %.1f|\n", floor(num*10)/10);
printf("|%.1f |\n", floor(num*10)/10);
return(0);
}
|
917294.c | /*************************************************************************\
* Copyright (C) Michael Kerrisk, 2020. *
* *
* This program is free software. You may use, modify, and redistribute it *
* under the terms of the GNU General Public License as published by the *
* Free Software Foundation, either version 3 or (at your option) any *
* later version. This program is distributed without any warranty. See *
* the file COPYING.gpl-v3 for details. *
\*************************************************************************/
/* Listing 46-9 */
/* svmsg_file_client.c
Send a message to the server svmsg_file_server.c requesting the
contents of the file named on the command line, and then receive the
file contents via a series of messages sent back by the server. Display
the total number of bytes and messages received. The server and client
communicate using System V message queues.
*/
#include "svmsg_file.h"
static int clientId;
static void
removeQueue(void)
{
if (msgctl(clientId, IPC_RMID, NULL) == -1)
errExit("msgctl");
}
int
main(int argc, char *argv[])
{
struct requestMsg req;
struct responseMsg resp;
int serverId, numMsgs;
ssize_t msgLen, totBytes;
if (argc != 2 || strcmp(argv[1], "--help") == 0)
usageErr("%s pathname\n", argv[0]);
if (strlen(argv[1]) > sizeof(req.pathname) - 1)
cmdLineErr("pathname too long (max: %ld bytes)\n",
(long) sizeof(req.pathname) - 1);
/* Get server's queue identifier; create queue for response */
serverId = msgget(SERVER_KEY, S_IWUSR);
if (serverId == -1)
errExit("msgget - server message queue");
clientId = msgget(IPC_PRIVATE, S_IRUSR | S_IWUSR | S_IWGRP);
if (clientId == -1)
errExit("msgget - client message queue");
if (atexit(removeQueue) != 0)
errExit("atexit");
/* Send message asking for file named in argv[1] */
req.mtype = 1; /* Any type will do */
req.clientId = clientId;
strncpy(req.pathname, argv[1], sizeof(req.pathname) - 1);
req.pathname[sizeof(req.pathname) - 1] = '\0';
/* Ensure string is terminated */
if (msgsnd(serverId, &req, REQ_MSG_SIZE, 0) == -1)
errExit("msgsnd");
/* Get first response, which may be failure notification */
msgLen = msgrcv(clientId, &resp, RESP_MSG_SIZE, 0, 0);
if (msgLen == -1)
errExit("msgrcv");
if (resp.mtype == RESP_MT_FAILURE) {
printf("%s\n", resp.data); /* Display msg from server */
exit(EXIT_FAILURE);
}
/* File was opened successfully by server; process messages
(including the one already received) containing file data */
totBytes = msgLen; /* Count first message */
for (numMsgs = 1; resp.mtype == RESP_MT_DATA; numMsgs++) {
msgLen = msgrcv(clientId, &resp, RESP_MSG_SIZE, 0, 0);
if (msgLen == -1)
errExit("msgrcv");
totBytes += msgLen;
}
printf("Received %ld bytes (%d messages)\n", (long) totBytes, numMsgs);
exit(EXIT_SUCCESS);
}
|
284192.c | #include <stdio.h>
#include <linux/fiemap.h>
#include <linux/fs.h>
#include <linux/blktrace_api.h>
#ifdef USE_FSMAP
#include <linux/fsmap.h>
#endif
#include <linux/ioctl.h>
#include <asm/ioctls.h>
#include "ioctls.h"
#include "net.h"
#include "shm.h"
#include "utils.h"
static int vfs_fd_test(int fd, const struct stat *st __attribute__((unused)))
{
struct list_head *globallist, *node;
struct object *obj;
globallist = shm->global_objects[OBJ_FD_PIPE].list;
list_for_each(node, globallist) {
obj = (struct object *) node;
if (obj->pipeobj.fd == fd)
return 0;
}
globallist = shm->global_objects[OBJ_FD_FILE].list;
list_for_each(node, globallist) {
obj = (struct object *) node;
if (obj->fileobj.fd == fd)
return 0;
}
globallist = shm->global_objects[OBJ_FD_TESTFILE].list;
list_for_each(node, globallist) {
obj = (struct object *) node;
if (obj->testfileobj.fd == fd)
return 0;
}
/* TODO: There may be other fd types we can perform vfs ioctls on */
return -1;
}
#ifndef FICLONE
#define FICLONE _IOW(0x94, 9, int)
#endif
#ifndef FICLONERANGE
struct file_clone_range {
__s64 src_fd;
__u64 src_offset;
__u64 src_length;
__u64 dest_offset;
};
#define FICLONERANGE _IOW(0x94, 13, struct file_clone_range)
#endif
#ifndef FIDEDUPERANGE
/* from struct btrfs_ioctl_file_extent_same_info */
struct file_dedupe_range_info {
__s64 dest_fd; /* in - destination file */
__u64 dest_offset; /* in - start of extent in destination */
__u64 bytes_deduped; /* out - total # of bytes we were able
* to dedupe from this file. */
/* status of this dedupe operation:
* < 0 for error
* == FILE_DEDUPE_RANGE_SAME if dedupe succeeds
* == FILE_DEDUPE_RANGE_DIFFERS if data differs
*/
__s32 status; /* out - see above description */
__u32 reserved; /* must be zero */
};
/* from struct btrfs_ioctl_file_extent_same_args */
struct file_dedupe_range {
__u64 src_offset; /* in - start of extent in source */
__u64 src_length; /* in - length of extent */
__u16 dest_count; /* in - total elements in info array */
__u16 reserved1; /* must be zero */
__u32 reserved2; /* must be zero */
struct file_dedupe_range_info info[0];
};
#define FIDEDUPERANGE _IOWR(0x94, 54, struct file_dedupe_range)
#endif
#ifndef FS_IOC_RESVSP
struct space_resv {
__s16 l_type;
__s16 l_whence;
__s64 l_start;
__s64 l_len; /* len == 0 means until end of file */
__s32 l_sysid;
__u32 l_pid;
__s32 l_pad[4]; /* reserved area */
};
#define FS_IOC_RESVSP _IOW('X', 40, struct space_resv)
#endif
#ifndef FS_IOC_RESVSP64
#define FS_IOC_RESVSP64 _IOW('X', 42, struct space_resv)
#endif
static const struct ioctl vfs_ioctls[] = {
{ .name = "FIOCLEX", .request = FIOCLEX, },
{ .name = "FIONCLEX", .request = FIONCLEX, },
{ .name = "FIONBIO", .request = FIONBIO, },
{ .name = "FIOASYNC", .request = FIOASYNC, },
{ .name = "FIOQSIZE", .request = FIOQSIZE, },
{ .name = "FIFREEZE", .request = FIFREEZE, },
{ .name = "FITHAW", .request = FITHAW, },
{ .name = "FS_IOC_FIEMAP", .request = FS_IOC_FIEMAP, },
{ .name = "FIGETBSZ", .request = FIGETBSZ, },
{ .name = "FICLONE", .request = FICLONE, },
{ .name = "FICLONERANGE", .request = FICLONERANGE, },
{ .name = "FIDEDUPERANGE", .request = FIDEDUPERANGE, },
{ .name = "FIBMAP", .request = FIBMAP, },
{ .name = "FIONREAD", .request = FIONREAD, },
{ .name = "FS_IOC_RESVSP", .request = FS_IOC_RESVSP, },
{ .name = "FS_IOC_RESVSP64", .request = FS_IOC_RESVSP64, },
#ifdef BLKROSET
{ .name = "BLKROSET", .request = BLKROSET, },
#endif
#ifdef BLKROGET
{ .name = "BLKROGET", .request = BLKROGET, },
#endif
#ifdef BLKRRPART
{ .name = "BLKRRPART", .request = BLKRRPART, },
#endif
#ifdef BLKGETSIZE
{ .name = "BLKGETSIZE", .request = BLKGETSIZE, },
#endif
#ifdef BLKFLSBUF
{ .name = "BLKFLSBUF", .request = BLKFLSBUF, },
#endif
#ifdef BLKRASET
{ .name = "BLKRASET", .request = BLKRASET, },
#endif
#ifdef BLKRAGET
{ .name = "BLKRAGET", .request = BLKRAGET, },
#endif
#ifdef BLKFRASET
{ .name = "BLKFRASET", .request = BLKFRASET, },
#endif
#ifdef BLKFRAGET
{ .name = "BLKFRAGET", .request = BLKFRAGET, },
#endif
#ifdef BLKSECTSET
{ .name = "BLKSECTSET", .request = BLKSECTSET, },
#endif
#ifdef BLKSECTGET
{ .name = "BLKSECTGET", .request = BLKSECTGET, },
#endif
#ifdef BLKSSZGET
{ .name = "BLKSSZGET", .request = BLKSSZGET, },
#endif
#ifdef BLKBSZGET
{ .name = "BLKBSZGET", .request = BLKBSZGET, },
#endif
#ifdef BLKBSZSET
{ .name = "BLKBSZSET", .request = BLKBSZSET, },
#endif
#ifdef BLKGETSIZE64
{ .name = "BLKGETSIZE64", .request = BLKGETSIZE64, },
#endif
#ifdef BLKTRACESETUP
{ .name = "BLKTRACESETUP", .request = BLKTRACESETUP, },
#endif
#ifdef BLKTRACESTART
{ .name = "BLKTRACESTART", .request = BLKTRACESTART, },
#endif
#ifdef BLKTRACESTOP
{ .name = "BLKTRACESTOP", .request = BLKTRACESTOP, },
#endif
#ifdef BLKTRACETEARDOWN
{ .name = "BLKTRACETEARDOWN", .request = BLKTRACETEARDOWN, },
#endif
#ifdef BLKDISCARD
{ .name = "BLKDISCARD", .request = BLKDISCARD, },
#endif
#ifdef BLKIOMIN
{ .name = "BLKIOMIN", .request = BLKIOMIN, },
#endif
#ifdef BLKIOOPT
{ .name = "BLKIOOPT", .request = BLKIOOPT, },
#endif
#ifdef BLKALIGNOFF
{ .name = "BLKALIGNOFF", .request = BLKALIGNOFF, },
#endif
#ifdef BLKPBSZGET
{ .name = "BLKPBSZGET", .request = BLKPBSZGET, },
#endif
#ifdef BLKDISCARDZEROES
{ .name = "BLKDISCARDZEROES", .request = BLKDISCARDZEROES, },
#endif
#ifdef BLKSECDISCARD
{ .name = "BLKSECDISCARD", .request = BLKSECDISCARD, },
#endif
#ifdef BLKROTATIONAL
{ .name = "BLKROTATIONAL", .request = BLKROTATIONAL, },
#endif
#ifdef BLKZEROOUT
{ .name = "BLKZEROOUT", .request = BLKZEROOUT, },
#endif
#ifdef FITRIM
{ .name = "FITRIM", .request = FITRIM, },
#endif
#ifdef FS_IOC_GETFLAGS
{ .name = "FS_IOC_GETFLAGS", .request = FS_IOC_GETFLAGS, },
#endif
#ifdef FS_IOC_SETFLAGS
{ .name = "FS_IOC_SETFLAGS", .request = FS_IOC_SETFLAGS, },
#endif
#ifdef FS_IOC_GETVERSION
{ .name = "FS_IOC_GETVERSION", .request = FS_IOC_GETVERSION, },
#endif
#ifdef FS_IOC_SETVERSION
{ .name = "FS_IOC_SETVERSION", .request = FS_IOC_SETVERSION, },
#endif
#ifdef FS_IOC32_GETFLAGS
{ .name = "FS_IOC32_GETFLAGS", .request = FS_IOC32_GETFLAGS, },
#endif
#ifdef FS_IOC32_SETFLAGS
{ .name = "FS_IOC32_SETFLAGS", .request = FS_IOC32_SETFLAGS, },
#endif
#ifdef FS_IOC32_GETVERSION
{ .name = "FS_IOC32_GETVERSION", .request = FS_IOC32_GETVERSION, },
#endif
#ifdef FS_IOC32_SETVERSION
{ .name = "FS_IOC32_SETVERSION", .request = FS_IOC32_SETVERSION, },
#endif
#ifdef FS_IOC_FSGETXATTR
{ .name = "FS_IOC_FSGETXATTR", .request = FS_IOC_FSGETXATTR, },
#endif
#ifdef FS_IOC_FSSETXATTR
{ .name = "FS_IOC_FSSETXATTR", .request = FS_IOC_FSSETXATTR, },
#endif
#ifdef FS_IOC_SET_ENCRYPTION_POLICY
{ .name = "FS_IOC_SET_ENCRYPTION_POLICY", .request = FS_IOC_SET_ENCRYPTION_POLICY, },
#endif
#ifdef FS_IOC_GET_ENCRYPTION_PWSALT
{ .name = "FS_IOC_GET_ENCRYPTION_PWSALT", .request = FS_IOC_GET_ENCRYPTION_PWSALT, },
#endif
#ifdef FS_IOC_GET_ENCRYPTION_POLICY
{ .name = "FS_IOC_GET_ENCRYPTION_POLICY", .request = FS_IOC_GET_ENCRYPTION_POLICY, },
#endif
#ifdef FS_IOC_GETFSMAP
{ .name = "FS_IOC_GETFSMAP", .request = FS_IOC_GETFSMAP, },
#endif
};
static const struct ioctl_group vfs_grp = {
.name = "vfs",
.fd_test = vfs_fd_test,
.sanitise = pick_random_ioctl,
.ioctls = vfs_ioctls,
.ioctls_cnt = ARRAY_SIZE(vfs_ioctls),
};
REG_IOCTL_GROUP(vfs_grp)
|
483564.c | #include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
#include <conio.h>
#define N 20
typedef struct{
int vida;
int fuerza;
int mana;
}player1;
typedef struct{
int vida;
int fuerza;
int mana;
}player2;
int elegir();
void seleccion(int opcion,char *nombre);
void select(int opcion,int pok2);
void batalla(char *nombre,char *nombre2);
player1 poke1;
player2 poke2;
char *nombre,*nombre2;
int pok,pok2;
int main(){
int c;
c = elegir();
seleccion(c,nombre);
select(c,pok2);
batalla(nombre,nombre2);
//cambio();
return 0;
system("pause");
}
int elegir(){
int n,opc,opcion,a,aux;
opcion = 0;
printf("Elige un pokemon\n");
printf("1.Piplup\n");
printf("2.Chimchar\n" );
printf("3.Turtwig\n");
scanf("%i",&opcion);
srand(time(NULL));
nombre = (char *)malloc((N+1)*sizeof(char));
nombre2 = (char *)malloc((N+1)*sizeof(char));
switch(opcion){
case 1:{
strcpy(nombre,"Piplup");
break;
}
case 2:{
strcpy(nombre,"Chimchar");
break;
}
case 3:{
strcpy(nombre,"Turtwig");
break;
}
default:printf("Opcion no disponible\n");
}
opc = 1 + rand() % ((3+1)-1);
switch(opc){
case 1:{
strcpy(nombre2,"Piplup");
break;
}
case 2:{
strcpy(nombre2,"Chimchar");
break;
}
case 3:{
strcpy(nombre2,"Turtwig");
break;
}
}
return opcion;
}
void seleccion(int opcion,char *nombre){
poke1.vida = 500;
poke1.mana = 500;
poke1.fuerza =200;
switch(opcion){
case 1:
printf("\nTu elegiste a Piplup\nHealth:%i\nEnergia:%i\nFuerza:%i\n",poke1.vida,poke1.mana,poke1.fuerza);
strcpy(nombre,"Piplup");
printf("\n");
break;
case 2:
printf("\nTu elegiste a Chimchar\nHealth:%i\nEnergia:%i\nFuerza:%i\n",poke1.vida,poke1.mana,poke1.fuerza);
strcpy(nombre,"Chimchar");
printf("\n");
break;
case 3:
printf("\nTu elegiste a Turtwig \nHealth:%i\nEnergia:%i\nFuerza:%i\n",poke1.vida,poke1.mana,poke1.fuerza);
strcpy(nombre,"Turtwig");
printf("\n");
break;
default:printf("No esta esa opcion");
}
}
void select(int opcion,int pok2){
int opc;
pok2 = 3;
poke2.vida = 500;
poke2.mana = 500;
poke2.fuerza =200;
srand(time(NULL));
opcion = 1 + rand() % ((3+1)-1);
switch(opcion){
case 1:
printf("\nTu oponente eligio a Piplup\nHealth:%i\nEnergia:%i\nFuerza:%i\n",poke2.vida,poke2.mana,poke2.fuerza);
printf("\n");
break;
case 2:
printf("\nTu oponente eligio a Chimchar\nHealth:%i\nEnergia:%i\nFuerza:%i\n",poke2.vida,poke2.mana,poke2.fuerza);
printf("\n");
break;
case 3:
printf("\nTu oponente eligio a Turtwig \nHealth:%i\nEnergia:%i\nFuerza:%i\n",poke2.vida,poke2.mana,poke2.fuerza);
printf("\n");
break;
}
}
void batalla(char *nombre,char *nombre2){
int op,i,damage,salud,x,energy,pok1,pok2;
pok1 = 3;
pok2 = 3;
damage = 0;
poke1.vida = 500;
poke1.mana = 500;
poke1.fuerza =200;
poke2.vida = 500;
poke2.mana = 500;
poke2.fuerza =200;
srand(time(NULL));
do{
do{
printf("1.COMBATE\n");
printf("2.BOLSA\n");
scanf("%i",&x);
if(x == 1){
printf("\nSeleccione la accion\n");
printf("\n1.Atacar\n2.Pasar\n3.Salir\n");
scanf("%i",&op);
printf("\n");
switch(op){
case 1:{
damage = poke1.fuerza *(rand () % 5);
printf("%s ataca\n",nombre);
printf("Damage %i\n",poke1.fuerza);
poke2.vida -= poke1.fuerza;
if(poke2.vida < 0){
printf("Health:0");
}
else{
printf("Health:%i\n",poke2.vida);
}
break;
}
case 2:{
printf("%s pasa el turno",nombre);
break;
}
case 3:{
printf("Has abandonado la batalla\n");
exit(1);
break;
}
}
}
else if(x == 2){
printf("\nSeleccione la accion\n");
printf("\n1.Sanar\n2.Cambiar pokemon\n3.Usar fruta de mana\n");
scanf("%i",&op);
printf("\n");
switch(op){
case 1:{
if(poke1.mana > 0){
salud = (rand() % ((300+1)-1));
printf("\n");
printf("%s utiliza sanacion\n",nombre);
poke1.vida += salud;
poke1.mana-=salud;
printf("+%i\n",salud);
printf("Health:%i\n",poke1.vida);
printf("Energia:%i\n",poke1.mana);
printf("\n");
}
else{
printf("No tienes suficiente mana\n");
}
break;
}
case 2:{
int opcion = 0;
printf("Elige un pokemon\n");
printf("1.Piplup\n");
printf("2.Chimchar\n" );
printf("3.Turtwig\n");
scanf("%i",&opcion);
seleccion(opcion,nombre);
break;
}
case 3:{
energy = (rand() % ((300+1)-1));
//printf("\n");
printf("%s utiliza fruta de mana\n",nombre);
poke1.mana+= energy;
printf("+%i\n",energy);
printf("Energia:%i\n",poke1.mana);
printf("\n");
// + rand() % ((3+1)-1);
break;
}
}
}
}while(op < 1 || op > 2);
printf("\n");
if(poke2.vida < 0){
int opcion = 0;
pok2--;
if(pok2 == 0){
printf("Pl 1 Victoria");
}
else{
printf("VICTORIA\n");
printf("\npokemones pl2 = %i\n",pok2);
select(opcion,pok2);
}
}
else{
printf("Para terminar turno <pulse una tecla>\n");
getch();
printf("\n");
printf("Turno del oponente\n");
printf("\n");
damage = poke2.fuerza * (rand() % 3);
printf("%s ataca\n",nombre2);
printf("Damage %i\n",damage);
poke1.vida -= damage;
if(poke1.vida < 0){
printf("Health : 0");
}
else{
printf("Health:%i\n",poke1.vida);
}
printf("\n");
}
if(poke1.vida < 0){
printf("\nDERROTA\n");
pok1--;
if(pok1 == 0){
printf("\nPl 2 Victoria");
exit(1);
}
else{
int opcion = 0;
printf("\npokemones pl1 = %i\n",pok1);
printf("\nElige un pokemon\n");
printf("1.Piplup\n");
printf("2.Chimchar\n" );
printf("3.Turtwig\n");
scanf("%i",&opcion);
printf("\n");
seleccion(opcion,nombre);
}
}
}while(pok1 > 0 && pok2 > 0 );
}
|
742847.c | // program to sort the array using quick sort algorithm
/*
ALGO
Let A be a linear array of n elements A (1), A (2), A (3)......A (n), low represents the
lower bound pointer and up represents the upper bound pointer. Key represents the first
element of the array, which is going to become the middle element of the sub-arrays.
1. Input n number of elements in an array A
2. Initialize low = 2, up = n , key = A[(low + up)/2]
3. Repeat through step 8 while (low < = up)
4. Repeat step 5 while(A [low] > key)
5. low = low + 1
6. Repeat step 7 while(A [up] < key)
7. up = up–1
8. If (low < = up)
(a) Swap = A [low]
(b) A [low] = A [up]
(c) A [up] = swap
(d) low=low+1
(e) up=up–1
9. If (1 < up) Quick sort (A, 1, up)
10. If (low < n) Quick sort (A, low, n)
11. Exit
TIME COMPLEXITY
WORST CASE
The worst case occurs when the list is already sorted. In this case the given array is
partitioned into two sub arrays. One of them is an empty array and another one is an
array. After partition, when the first element is checked with other element, it will take n
comparison to recognize that it remain in the position so as (n – 1) comparisons for the
second position
f (n) = n + (n – 1) + ...... + 2 + 1
= (n (n + 1))/2
= O(n2)
AVG. CASE
AVERAGE CASE
In this case each reduction step of the algorithm produces two sub arrays. Accordingly :
(a) Reducing the array by placing one element and produces two sub arrays.
(b) Reducing the two sub-arrays by placing two elements and produces four subarrays.
(c) Reducing the four sub-arrays by placing four elements and produces eight subarrays.
And so on. Reduction step in the kth level finds the location at 2k–1 elements; however there will be approximately log2 n levels at reduction steps. Furthermore each level
uses at most n comparisons,
so f (n) = O(n log n)
BEST CASE
The base case analysis occurs when the array is always partitioned in half, That key
= A [(low+up)/2]
f (n) = Cn +f (n/2) + f (n/2)
= Cn + 2f (n/2)
= O(n) where C is a constant.
*/
#include <stdio.h>
#include <conio.h>
#define size 10
int partion(int *, int, int);
void quickSort(int *, int, int);
void printArray(int *, int);
int main()
{
int arr[size], n;
printf("\nEnter the size of the array :: ");
scanf("%d", &n);
for (int i = 0; i < n; i++)
{
printf("Enter the element :: ");
scanf("%d", &arr[i]);
}
printArray(arr, n); // printing the array before sorting
quickSort(arr, 0, n - 1); // calling the sorting function , passing low as 0 and high as n - 1
printArray(arr, n); // printing the array after sorting
return 0;
}
int partion(int arr[], int low, int high)
{
int pivot = arr[low]; // pivot is the element which we will kept at it's right position everytime
int start = low + 1, end = high; // initilazing the start and end variable to the start and end of the array
do // atleast one time we have to run the loop
{
while (arr[start] <= pivot)
start++; // finding the only large element then pivot (equal element not needed)
while (arr[end] > pivot)
end--; // finding the smaller or equal to element than pivot
if (start < end)
{ // if start doesn't exceed the end pointer then swap the start and end
int temp = arr[start];
arr[start] = arr[end];
arr[end] = temp;
}
} while (start < end);
// if start exceed the end pointer than swap the pivot with end (keep pivot at it's right postion)
int temp = arr[low];
arr[low] = arr[end];
arr[end] = temp;
return end; // returning the right postion of the pivot (means dividing the array into to subarray , right to pivot and left to pivot)
}
void quickSort(int arr[], int low, int high)
{
int partionIndex;
if (low < high) // base condition of the recursion ,if low exceed the high then array is sorted
{
partionIndex = partion(arr, low, high); // getting the left unsorted array and right unsorted array
quickSort(arr, low, partionIndex - 1); // will sort left
quickSort(arr, partionIndex + 1, high); // will sort right
}
}
void printArray(int arr[size], int n)
{ // function to print the array
printf("\n");
for (int i = 0; i < n; i++)
printf("%d ", arr[i]);
printf("\n");
} |
243392.c | /*
* Copyright (c) 2004-2010 The Trustees of Indiana University and Indiana
* University Research and Technology
* Corporation. All rights reserved.
* Copyright (c) 2004-2008 The University of Tennessee and The University
* of Tennessee Research Foundation. All rights
* reserved.
* Copyright (c) 2004-2006 High Performance Computing Center Stuttgart,
* University of Stuttgart. All rights reserved.
* Copyright (c) 2004-2006 The Regents of the University of California.
* All rights reserved.
* Copyright (c) 2007-2008 Cisco Systems, Inc. All rights reserved.
* Copyright (c) 2014-2015 Intel, Inc. All rights reserved.
* Copyright (c) 2015 Research Organization for Information Science
* and Technology (RIST). All rights reserved.
* $COPYRIGHT$
*
* Additional copyrights may follow
*
* $HEADER$
*/
#include <src/include/pmix_config.h>
#include <pmix/pmix_common.h>
#include <stdio.h>
#include <ctype.h>
#include <stdarg.h>
#include <stdlib.h>
#ifdef HAVE_SYSLOG_H
#include <syslog.h>
#endif
#include <string.h>
#include <fcntl.h>
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif
#ifdef HAVE_SYS_PARAM_H
#include <sys/param.h>
#endif
#include "src/util/pmix_environ.h"
#include "src/util/output.h"
/*
* Private data
*/
static int verbose_stream = -1;
static pmix_output_stream_t verbose;
static char *output_dir = NULL;
static char *output_prefix = NULL;
/*
* Internal data structures and helpers for the generalized output
* stream mechanism.
*/
typedef struct {
bool ldi_used;
bool ldi_enabled;
int ldi_verbose_level;
bool ldi_syslog;
int ldi_syslog_priority;
char *ldi_syslog_ident;
char *ldi_prefix;
int ldi_prefix_len;
char *ldi_suffix;
int ldi_suffix_len;
bool ldi_stdout;
bool ldi_stderr;
bool ldi_file;
bool ldi_file_want_append;
char *ldi_file_suffix;
int ldi_fd;
int ldi_file_num_lines_lost;
} output_desc_t;
/*
* Private functions
*/
static void construct(pmix_object_t *stream);
static int do_open(int output_id, pmix_output_stream_t * lds);
static int open_file(int i);
static void free_descriptor(int output_id);
static int make_string(char **no_newline_string, output_desc_t *ldi,
const char *format, va_list arglist);
static int output(int output_id, const char *format, va_list arglist);
#define PMIX_OUTPUT_MAX_STREAMS 64
#if defined(HAVE_SYSLOG)
#define USE_SYSLOG 1
#else
#define USE_SYSLOG 0
#endif
/* global state */
bool pmix_output_redirected_to_syslog = false;
int pmix_output_redirected_syslog_pri = 0;
/*
* Local state
*/
static bool initialized = false;
static int default_stderr_fd = -1;
static output_desc_t info[PMIX_OUTPUT_MAX_STREAMS];
static char *temp_str = 0;
static size_t temp_str_len = 0;
#if defined(HAVE_SYSLOG)
static bool syslog_opened = false;
#endif
static char *redirect_syslog_ident = NULL;
PMIX_CLASS_INSTANCE(pmix_output_stream_t, pmix_object_t, construct, NULL);
/*
* Setup the output stream infrastructure
*/
bool pmix_output_init(void)
{
int i;
char hostname[PMIX_MAXHOSTNAMELEN];
char *str;
if (initialized) {
return true;
}
str = getenv("PMIX_OUTPUT_STDERR_FD");
if (NULL != str) {
default_stderr_fd = atoi(str);
}
str = getenv("PMIX_OUTPUT_REDIRECT");
if (NULL != str) {
if (0 == strcasecmp(str, "syslog")) {
pmix_output_redirected_to_syslog = true;
}
}
str = getenv("PMIX_OUTPUT_SYSLOG_PRI");
if (NULL != str) {
if (0 == strcasecmp(str, "info")) {
pmix_output_redirected_syslog_pri = LOG_INFO;
} else if (0 == strcasecmp(str, "error")) {
pmix_output_redirected_syslog_pri = LOG_ERR;
} else if (0 == strcasecmp(str, "warn")) {
pmix_output_redirected_syslog_pri = LOG_WARNING;
} else {
pmix_output_redirected_syslog_pri = LOG_ERR;
}
} else {
pmix_output_redirected_syslog_pri = LOG_ERR;
}
str = getenv("PMIX_OUTPUT_SYSLOG_IDENT");
if (NULL != str) {
redirect_syslog_ident = strdup(str);
}
PMIX_CONSTRUCT(&verbose, pmix_output_stream_t);
if (pmix_output_redirected_to_syslog) {
verbose.lds_want_syslog = true;
verbose.lds_syslog_priority = pmix_output_redirected_syslog_pri;
if (NULL != str) {
verbose.lds_syslog_ident = strdup(redirect_syslog_ident);
}
verbose.lds_want_stderr = false;
verbose.lds_want_stdout = false;
} else {
verbose.lds_want_stderr = true;
}
gethostname(hostname, sizeof(hostname));
hostname[sizeof(hostname)-1] = '\0';
asprintf(&verbose.lds_prefix, "[%s:%05d] ", hostname, getpid());
for (i = 0; i < PMIX_OUTPUT_MAX_STREAMS; ++i) {
info[i].ldi_used = false;
info[i].ldi_enabled = false;
info[i].ldi_syslog = pmix_output_redirected_to_syslog;
info[i].ldi_file = false;
info[i].ldi_file_suffix = NULL;
info[i].ldi_file_want_append = false;
info[i].ldi_fd = -1;
info[i].ldi_file_num_lines_lost = 0;
}
initialized = true;
/* Set some defaults */
asprintf(&output_prefix, "output-pid%d-", getpid());
output_dir = strdup(pmix_tmp_directory());
/* Open the default verbose stream */
verbose_stream = pmix_output_open(&verbose);
return true;
}
/*
* Open a stream
*/
int pmix_output_open(pmix_output_stream_t * lds)
{
return do_open(-1, lds);
}
/*
* Reset the parameters on a stream
*/
int pmix_output_reopen(int output_id, pmix_output_stream_t * lds)
{
return do_open(output_id, lds);
}
/*
* Enable and disable output streams
*/
bool pmix_output_switch(int output_id, bool enable)
{
bool ret = false;
/* Setup */
if (!initialized) {
pmix_output_init();
}
if (output_id >= 0 && output_id < PMIX_OUTPUT_MAX_STREAMS) {
ret = info[output_id].ldi_enabled;
info[output_id].ldi_enabled = enable;
}
return ret;
}
/*
* Reopen all the streams; used during checkpoint/restart.
*/
void pmix_output_reopen_all(void)
{
char *str;
char hostname[PMIX_MAXHOSTNAMELEN];
str = getenv("PMIX_OUTPUT_STDERR_FD");
if (NULL != str) {
default_stderr_fd = atoi(str);
} else {
default_stderr_fd = -1;
}
gethostname(hostname, sizeof(hostname));
if( NULL != verbose.lds_prefix ) {
free(verbose.lds_prefix);
verbose.lds_prefix = NULL;
}
asprintf(&verbose.lds_prefix, "[%s:%05d] ", hostname, getpid());
#if 0
int i;
pmix_output_stream_t lds;
for (i = 0; i < PMIX_OUTPUT_MAX_STREAMS; ++i) {
/* scan till we find ldi_used == 0, which is the end-marker */
if (!info[i].ldi_used) {
break;
}
/*
* set this to zero to ensure that pmix_output_open will
* return this same index as the output stream id
*/
info[i].ldi_used = false;
#if USE_SYSLOG
lds.lds_want_syslog = info[i].ldi_syslog;
lds.lds_syslog_priority = info[i].ldi_syslog_priority;
lds.lds_syslog_ident = info[i].ldi_syslog_ident;
#else
lds.lds_want_syslog = false;
#endif
lds.lds_prefix = info[i].ldi_prefix;
lds.lds_suffix = info[i].ldi_suffix;
lds.lds_want_stdout = info[i].ldi_stdout;
lds.lds_want_stderr = info[i].ldi_stderr;
lds.lds_want_file = (-1 == info[i].ldi_fd) ? false : true;
/* open all streams in append mode */
lds.lds_want_file_append = true;
lds.lds_file_suffix = info[i].ldi_file_suffix;
/*
* call pmix_output_open to open the stream. The return value
* is guaranteed to be i. So we can ignore it.
*/
pmix_output_open(&lds);
}
#endif
}
/*
* Close a stream
*/
void pmix_output_close(int output_id)
{
int i;
/* Setup */
if (!initialized) {
return;
}
/* If it's valid, used, enabled, and has an open file descriptor,
* free the resources associated with the descriptor */
if (output_id >= 0 && output_id < PMIX_OUTPUT_MAX_STREAMS &&
info[output_id].ldi_used && info[output_id].ldi_enabled) {
free_descriptor(output_id);
/* If no one has the syslog open, we should close it */
for (i = 0; i < PMIX_OUTPUT_MAX_STREAMS; ++i) {
if (info[i].ldi_used && info[i].ldi_syslog) {
break;
}
}
#if defined(HAVE_SYSLOG)
if (i >= PMIX_OUTPUT_MAX_STREAMS && syslog_opened) {
closelog();
}
#endif
}
}
/*
* Main function to send output to a stream
*/
void pmix_output(int output_id, const char *format, ...)
{
if (output_id >= 0 && output_id < PMIX_OUTPUT_MAX_STREAMS) {
va_list arglist;
va_start(arglist, format);
output(output_id, format, arglist);
va_end(arglist);
}
}
/*
* Send a message to a stream if the verbose level is high enough
*/
void pmix_output_verbose(int level, int output_id, const char *format, ...)
{
if (output_id >= 0 && output_id < PMIX_OUTPUT_MAX_STREAMS &&
info[output_id].ldi_verbose_level >= level) {
va_list arglist;
va_start(arglist, format);
output(output_id, format, arglist);
va_end(arglist);
}
}
/*
* Send a message to a stream if the verbose level is high enough
*/
void pmix_output_vverbose(int level, int output_id, const char *format,
va_list arglist)
{
if (output_id >= 0 && output_id < PMIX_OUTPUT_MAX_STREAMS &&
info[output_id].ldi_verbose_level >= level) {
output(output_id, format, arglist);
}
}
/*
* Send a message to a string if the verbose level is high enough
*/
char *pmix_output_string(int level, int output_id, const char *format, ...)
{
int rc;
char *ret = NULL;
if (output_id >= 0 && output_id < PMIX_OUTPUT_MAX_STREAMS &&
info[output_id].ldi_verbose_level >= level) {
va_list arglist;
va_start(arglist, format);
rc = make_string(&ret, &info[output_id], format, arglist);
va_end(arglist);
if (PMIX_SUCCESS != rc) {
ret = NULL;
}
}
return ret;
}
/*
* Send a message to a string if the verbose level is high enough
*/
char *pmix_output_vstring(int level, int output_id, const char *format,
va_list arglist)
{
int rc;
char *ret = NULL;
if (output_id >= 0 && output_id < PMIX_OUTPUT_MAX_STREAMS &&
info[output_id].ldi_verbose_level >= level) {
rc = make_string(&ret, &info[output_id], format, arglist);
if (PMIX_SUCCESS != rc) {
ret = NULL;
}
}
return ret;
}
/*
* Set the verbosity level of a stream
*/
void pmix_output_set_verbosity(int output_id, int level)
{
if (output_id >= 0 && output_id < PMIX_OUTPUT_MAX_STREAMS) {
info[output_id].ldi_verbose_level = level;
}
}
/*
* Control where output flies will go
*/
void pmix_output_set_output_file_info(const char *dir,
const char *prefix,
char **olddir,
char **oldprefix)
{
if (NULL != olddir) {
*olddir = strdup(output_dir);
}
if (NULL != oldprefix) {
*oldprefix = strdup(output_prefix);
}
if (NULL != dir) {
free(output_dir);
output_dir = strdup(dir);
}
if (NULL != prefix) {
free(output_prefix);
output_prefix = strdup(prefix);
}
}
void pmix_output_hexdump(int verbose_level, int output_id,
void *ptr, int buflen)
{
unsigned char *buf = (unsigned char *) ptr;
char out_buf[120];
int ret = 0;
int out_pos = 0;
int i, j;
if (output_id >= 0 && output_id < PMIX_OUTPUT_MAX_STREAMS &&
info[output_id].ldi_verbose_level >= verbose_level) {
pmix_output_verbose(verbose_level, output_id, "dump data at %p %d bytes\n", ptr, buflen);
for (i = 0; i < buflen; i += 16) {
out_pos = 0;
ret = sprintf(out_buf + out_pos, "%06x: ", i);
if (ret < 0)
return;
out_pos += ret;
for (j = 0; j < 16; j++) {
if (i + j < buflen)
ret = sprintf(out_buf + out_pos, "%02x ",
buf[i + j]);
else
ret = sprintf(out_buf + out_pos, " ");
if (ret < 0)
return;
out_pos += ret;
}
ret = sprintf(out_buf + out_pos, " ");
if (ret < 0)
return;
out_pos += ret;
for (j = 0; j < 16; j++)
if (i + j < buflen) {
ret = sprintf(out_buf + out_pos, "%c",
isprint(buf[i+j]) ?
buf[i + j] :
'.');
if (ret < 0)
return;
out_pos += ret;
}
ret = sprintf(out_buf + out_pos, "\n");
if (ret < 0)
return;
pmix_output_verbose(verbose_level, output_id, "%s", out_buf);
}
}
}
/*
* Shut down the output stream system
*/
void pmix_output_finalize(void)
{
if (initialized) {
if (verbose_stream != -1) {
pmix_output_close(verbose_stream);
}
free(verbose.lds_prefix);
verbose_stream = -1;
free (output_prefix);
free (output_dir);
if(NULL != temp_str) {
free(temp_str);
temp_str = NULL;
temp_str_len = 0;
}
PMIX_DESTRUCT(&verbose);
}
}
/************************************************************************/
/*
* Constructor
*/
static void construct(pmix_object_t *obj)
{
pmix_output_stream_t *stream = (pmix_output_stream_t*) obj;
stream->lds_verbose_level = 0;
stream->lds_syslog_priority = 0;
stream->lds_syslog_ident = NULL;
stream->lds_prefix = NULL;
stream->lds_suffix = NULL;
stream->lds_is_debugging = false;
stream->lds_want_syslog = false;
stream->lds_want_stdout = false;
stream->lds_want_stderr = false;
stream->lds_want_file = false;
stream->lds_want_file_append = false;
stream->lds_file_suffix = NULL;
}
/*
* Back-end of open() and reopen().
*/
static int do_open(int output_id, pmix_output_stream_t * lds)
{
int i;
bool redirect_to_file = false;
char *str, *sfx;
/* Setup */
if (!initialized) {
pmix_output_init();
}
str = getenv("PMIX_OUTPUT_REDIRECT");
if (NULL != str && 0 == strcasecmp(str, "file")) {
redirect_to_file = true;
}
sfx = getenv("PMIX_OUTPUT_SUFFIX");
/* If output_id == -1, find an available stream, or return
* PMIX_ERROR */
if (-1 == output_id) {
for (i = 0; i < PMIX_OUTPUT_MAX_STREAMS; ++i) {
if (!info[i].ldi_used) {
break;
}
}
if (i >= PMIX_OUTPUT_MAX_STREAMS) {
return PMIX_ERR_OUT_OF_RESOURCE;
}
}
/* Otherwise, we're reopening, so we need to free all previous
* resources, close files, etc. */
else {
free_descriptor(output_id);
i = output_id;
}
/* Special case: if we got NULL for lds, then just use the default
* verbose */
if (NULL == lds) {
lds = &verbose;
}
/* Got a stream -- now initialize it and open relevant outputs */
info[i].ldi_used = true;
info[i].ldi_enabled = lds->lds_is_debugging ?
(bool) PMIX_ENABLE_DEBUG : true;
info[i].ldi_verbose_level = lds->lds_verbose_level;
#if USE_SYSLOG
#if defined(HAVE_SYSLOG)
if (pmix_output_redirected_to_syslog) {
info[i].ldi_syslog = true;
info[i].ldi_syslog_priority = pmix_output_redirected_syslog_pri;
if (NULL != redirect_syslog_ident) {
info[i].ldi_syslog_ident = strdup(redirect_syslog_ident);
openlog(redirect_syslog_ident, LOG_PID, LOG_USER);
} else {
info[i].ldi_syslog_ident = NULL;
openlog("pmix", LOG_PID, LOG_USER);
}
syslog_opened = true;
} else {
#endif
info[i].ldi_syslog = lds->lds_want_syslog;
if (lds->lds_want_syslog) {
#if defined(HAVE_SYSLOG)
if (NULL != lds->lds_syslog_ident) {
info[i].ldi_syslog_ident = strdup(lds->lds_syslog_ident);
openlog(lds->lds_syslog_ident, LOG_PID, LOG_USER);
} else {
info[i].ldi_syslog_ident = NULL;
openlog("pmix", LOG_PID, LOG_USER);
}
#endif
syslog_opened = true;
info[i].ldi_syslog_priority = lds->lds_syslog_priority;
}
#if defined(HAVE_SYSLOG)
}
#endif
#else
info[i].ldi_syslog = false;
#endif
if (NULL != lds->lds_prefix) {
info[i].ldi_prefix = strdup(lds->lds_prefix);
info[i].ldi_prefix_len = (int)strlen(lds->lds_prefix);
} else {
info[i].ldi_prefix = NULL;
info[i].ldi_prefix_len = 0;
}
if (NULL != lds->lds_suffix) {
info[i].ldi_suffix = strdup(lds->lds_suffix);
info[i].ldi_suffix_len = (int)strlen(lds->lds_suffix);
} else {
info[i].ldi_suffix = NULL;
info[i].ldi_suffix_len = 0;
}
if (pmix_output_redirected_to_syslog) {
/* since all is redirected to syslog, ensure
* we don't duplicate the output to the std places
*/
info[i].ldi_stdout = false;
info[i].ldi_stderr = false;
info[i].ldi_file = false;
info[i].ldi_fd = -1;
} else {
/* since we aren't redirecting to syslog, use what was
* given to us
*/
if (NULL != str && redirect_to_file) {
info[i].ldi_stdout = false;
info[i].ldi_stderr = false;
info[i].ldi_file = true;
} else {
info[i].ldi_stdout = lds->lds_want_stdout;
info[i].ldi_stderr = lds->lds_want_stderr;
info[i].ldi_fd = -1;
info[i].ldi_file = lds->lds_want_file;
}
if (NULL != sfx) {
info[i].ldi_file_suffix = strdup(sfx);
} else {
info[i].ldi_file_suffix = (NULL == lds->lds_file_suffix) ? NULL :
strdup(lds->lds_file_suffix);
}
info[i].ldi_file_want_append = lds->lds_want_file_append;
info[i].ldi_file_num_lines_lost = 0;
}
/* Don't open a file in the session directory now -- do that lazily
* so that if there's no output, we don't have an empty file */
return i;
}
static int open_file(int i)
{
int flags;
char *filename;
int n;
/* first check to see if this file is already open
* on someone else's stream - if so, we don't want
* to open it twice
*/
for (n=0; n < PMIX_OUTPUT_MAX_STREAMS; n++) {
if (i == n) {
continue;
}
if (!info[n].ldi_used) {
continue;
}
if (!info[n].ldi_file) {
continue;
}
if (NULL != info[i].ldi_file_suffix &&
NULL != info[n].ldi_file_suffix) {
if (0 != strcmp(info[i].ldi_file_suffix, info[n].ldi_file_suffix)) {
break;
}
}
if (NULL == info[i].ldi_file_suffix &&
NULL != info[n].ldi_file_suffix) {
break;
}
if (NULL != info[i].ldi_file_suffix &&
NULL == info[n].ldi_file_suffix) {
break;
}
if (info[n].ldi_fd < 0) {
break;
}
info[i].ldi_fd = info[n].ldi_fd;
return PMIX_SUCCESS;
}
/* Setup the filename and open flags */
if (NULL != output_dir) {
filename = (char *) malloc(PMIX_PATH_MAX);
if (NULL == filename) {
return PMIX_ERR_OUT_OF_RESOURCE;
}
strncpy(filename, output_dir, PMIX_PATH_MAX);
strcat(filename, "/");
if (NULL != output_prefix) {
strcat(filename, output_prefix);
}
if (info[i].ldi_file_suffix != NULL) {
strcat(filename, info[i].ldi_file_suffix);
} else {
info[i].ldi_file_suffix = NULL;
strcat(filename, "output.txt");
}
flags = O_CREAT | O_RDWR;
if (!info[i].ldi_file_want_append) {
flags |= O_TRUNC;
}
/* Actually open the file */
info[i].ldi_fd = open(filename, flags, 0644);
free(filename); /* release the filename in all cases */
if (-1 == info[i].ldi_fd) {
info[i].ldi_used = false;
return PMIX_ERR_IN_ERRNO;
}
/* Make the file be close-on-exec to prevent child inheritance
* problems */
if (-1 == fcntl(info[i].ldi_fd, F_SETFD, 1)) {
return PMIX_ERR_IN_ERRNO;
}
}
/* Return successfully even if the session dir did not exist yet;
* we'll try opening it later */
return PMIX_SUCCESS;
}
/*
* Free all the resources associated with a descriptor.
*/
static void free_descriptor(int output_id)
{
output_desc_t *ldi;
if (output_id >= 0 && output_id < PMIX_OUTPUT_MAX_STREAMS &&
info[output_id].ldi_used && info[output_id].ldi_enabled) {
ldi = &info[output_id];
if (-1 != ldi->ldi_fd) {
close(ldi->ldi_fd);
}
ldi->ldi_used = false;
/* If we strduped a prefix, suffix, or syslog ident, free it */
if (NULL != ldi->ldi_prefix) {
free(ldi->ldi_prefix);
}
ldi->ldi_prefix = NULL;
if (NULL != ldi->ldi_suffix) {
free(ldi->ldi_suffix);
}
ldi->ldi_suffix = NULL;
if (NULL != ldi->ldi_file_suffix) {
free(ldi->ldi_file_suffix);
}
ldi->ldi_file_suffix = NULL;
if (NULL != ldi->ldi_syslog_ident) {
free(ldi->ldi_syslog_ident);
}
ldi->ldi_syslog_ident = NULL;
}
}
static int make_string(char **no_newline_string, output_desc_t *ldi,
const char *format, va_list arglist)
{
size_t len, total_len;
bool want_newline = false;
/* Make the formatted string */
vasprintf(no_newline_string, format, arglist);
total_len = len = strlen(*no_newline_string);
if ('\n' != (*no_newline_string)[len - 1]) {
want_newline = true;
++total_len;
} else if (NULL != ldi->ldi_suffix) {
/* if we have a suffix, then we don't want a
* newline to appear before it
*/
(*no_newline_string)[len - 1] = '\0';
want_newline = true; /* add newline to end after suffix */
/* total_len won't change since we just moved the newline
* to appear after the suffix
*/
}
if (NULL != ldi->ldi_prefix) {
total_len += strlen(ldi->ldi_prefix);
}
if (NULL != ldi->ldi_suffix) {
total_len += strlen(ldi->ldi_suffix);
}
if (temp_str_len < total_len + want_newline) {
if (NULL != temp_str) {
free(temp_str);
}
temp_str = (char *) malloc(total_len * 2);
if (NULL == temp_str) {
return PMIX_ERR_OUT_OF_RESOURCE;
}
temp_str_len = total_len * 2;
}
if (NULL != ldi->ldi_prefix && NULL != ldi->ldi_suffix) {
if (want_newline) {
snprintf(temp_str, temp_str_len, "%s%s%s\n",
ldi->ldi_prefix, *no_newline_string, ldi->ldi_suffix);
} else {
snprintf(temp_str, temp_str_len, "%s%s%s", ldi->ldi_prefix,
*no_newline_string, ldi->ldi_suffix);
}
} else if (NULL != ldi->ldi_prefix) {
if (want_newline) {
snprintf(temp_str, temp_str_len, "%s%s\n",
ldi->ldi_prefix, *no_newline_string);
} else {
snprintf(temp_str, temp_str_len, "%s%s", ldi->ldi_prefix,
*no_newline_string);
}
} else if (NULL != ldi->ldi_suffix) {
if (want_newline) {
snprintf(temp_str, temp_str_len, "%s%s\n",
*no_newline_string, ldi->ldi_suffix);
} else {
snprintf(temp_str, temp_str_len, "%s%s",
*no_newline_string, ldi->ldi_suffix);
}
} else {
if (want_newline) {
snprintf(temp_str, temp_str_len, "%s\n", *no_newline_string);
} else {
snprintf(temp_str, temp_str_len, "%s", *no_newline_string);
}
}
return PMIX_SUCCESS;
}
/*
* Do the actual output. Take a va_list so that we can be called from
* multiple different places, even functions that took "..." as input
* arguments.
*/
static int output(int output_id, const char *format, va_list arglist)
{
int rc = PMIX_SUCCESS;
char *str, *out = NULL;
output_desc_t *ldi;
/* Setup */
if (!initialized) {
pmix_output_init();
}
/* If it's valid, used, and enabled, output */
if (output_id >= 0 && output_id < PMIX_OUTPUT_MAX_STREAMS &&
info[output_id].ldi_used && info[output_id].ldi_enabled) {
ldi = &info[output_id];
/* Make the strings */
if (PMIX_SUCCESS != (rc = make_string(&str, ldi, format, arglist))) {
return rc;
}
/* Syslog output -- does not use the newline-appended string */
#if defined(HAVE_SYSLOG)
if (ldi->ldi_syslog) {
syslog(ldi->ldi_syslog_priority, "%s", str);
}
#endif
/* All others (stdout, stderr, file) use temp_str, potentially
with a newline appended */
out = temp_str;
/* stdout output */
if (ldi->ldi_stdout) {
write(fileno(stdout), out, (int)strlen(out));
fflush(stdout);
}
/* stderr output */
if (ldi->ldi_stderr) {
write((-1 == default_stderr_fd) ?
fileno(stderr) : default_stderr_fd,
out, (int)strlen(out));
fflush(stderr);
}
/* File output -- first check to see if the file opening was
* delayed. If so, try to open it. If we failed to open it,
* then just discard (there are big warnings in the
* pmix_output.h docs about this!). */
if (ldi->ldi_file) {
if (ldi->ldi_fd == -1) {
if (PMIX_SUCCESS != open_file(output_id)) {
++ldi->ldi_file_num_lines_lost;
} else if (ldi->ldi_file_num_lines_lost > 0 && 0 <= ldi->ldi_fd) {
char buffer[BUFSIZ];
char *out = buffer;
memset(buffer, 0, BUFSIZ);
snprintf(buffer, BUFSIZ - 1,
"[WARNING: %d lines lost because the PMIx process session directory did\n not exist when pmix_output() was invoked]\n",
ldi->ldi_file_num_lines_lost);
write(ldi->ldi_fd, buffer, (int)strlen(buffer));
ldi->ldi_file_num_lines_lost = 0;
if (out != buffer) {
free(out);
}
}
}
if (ldi->ldi_fd != -1) {
write(ldi->ldi_fd, out, (int)strlen(out));
}
}
free(str);
}
return rc;
}
int pmix_output_get_verbosity(int output_id)
{
if (output_id >= 0 && output_id < PMIX_OUTPUT_MAX_STREAMS && info[output_id].ldi_used) {
return info[output_id].ldi_verbose_level;
} else {
return -1;
}
}
|
97270.c | #include <stdio.h>
#include <limits.h>
int main()
{
/* http://scc-forge.lancaster.ac.uk/open/char/types/ints */
printf("char: %ld byte\n", sizeof(char)); /* определяем размер в байтах как long int */
printf("%d\n", CHAR_MIN);
printf("%d\n", CHAR_MAX);
printf("unsigned char: %ld byte\n", sizeof(unsigned char));
printf("%d\n", UCHAR_MAX);
printf("short: %ld bytes\n", sizeof(short));
printf("%d\n", SHRT_MIN);
printf("%d\n", SHRT_MAX);
printf("unsigned short: %ld bytes\n", sizeof(unsigned short));
printf("%d\n", USHRT_MAX);
printf("int: %ld bytes\n", sizeof(int));
printf("%d\n", INT_MIN);
printf("%d\n", INT_MAX);
printf("unsigned int: %ld bytes\n", sizeof(unsigned int));
printf("%u\n", UINT_MAX);
printf("long int: %ld bytes\n", sizeof(long int));
printf("%ld\n", LONG_MIN);
printf("%ld\n", LONG_MAX);
printf("unsigned long int: %ld bytes\n", sizeof(unsigned long int));
printf("%lu\n", ULONG_MAX);
return 0;
}
|
875678.c | /*
* Copyright (c) 1999 - 2005 NetGroup, Politecnico di Torino (Italy)
* Copyright (c) 2005 - 2006 CACE Technologies, Davis (California)
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the Politecnico di Torino, CACE Technologies
* 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.
*
*/
#include <stdlib.h>
#include <stdio.h>
#include <pcap.h>
main(int argc, char **argv)
{
pcap_if_t *alldevs, *d;
pcap_t *fp;
u_int inum, i=0;
char errbuf[PCAP_ERRBUF_SIZE];
int res;
struct pcap_pkthdr *header;
const u_char *pkt_data;
struct pcap_pkthdr old;
char a[11];
printf("SMP_1\n");
printf("\nThis program tests the WinPcap kernel driver on SMP machines.\n");
printf("The program tests that timestamps on the captured packets are consistent,\n");
printf("and that the caplen is equal to the packet length.\n");
printf("If there is an error, it will print out a message saying \"Inconsistent XXX\"\n");
if (pcap_findalldevs_ex(PCAP_SRC_IF_STRING, NULL, &alldevs, errbuf) == -1)
{
fprintf(stderr,"Error in pcap_findalldevs: %s\n", errbuf);
exit(1);
}
/* Print the list */
for(d=alldevs; d; d=d->next)
{
printf("%d. %s", ++i, d->name);
if (d->description)
printf(" (%s)\n", d->description);
else
printf(" (No description available)\n");
}
if(i==0)
{
printf("\nNo interfaces found! Make sure WinPcap is installed.\n");
return -1;
}
printf("Enter the interface number (1-%d):",i);
scanf("%d", &inum);
if(inum < 1 || inum > i)
{
printf("\nInterface number out of range.\n");
/* Free the device list */
pcap_freealldevs(alldevs);
return -1;
}
/* Jump to the selected adapter */
for(d=alldevs, i=0; i< inum-1 ;d=d->next, i++);
/* Open the device */
if ( (fp= pcap_open(d->name, 65536, PCAP_OPENFLAG_PROMISCUOUS, 1000, NULL, errbuf) ) == NULL)
{
fprintf(stderr,"\nUnable to open the adapter. %s is not supported by WinPcap\n", d->name);
/* Free the device list */
pcap_freealldevs(alldevs);
return -1;
}
old.ts.tv_sec=0;
old.ts.tv_usec=0;
/* Read the packets */
while((res = pcap_next_ex( fp, &header, &pkt_data)) >= 0){
if(res == 0)
continue;
//check that caplen is equal to packet length
if (header->caplen!=header->len)
printf("Inconsistent header: CapLen %d\t Len %d\n",header->caplen,header->len);
//check that timestamps always grow
if ( old.ts.tv_sec > header->ts.tv_sec || (old.ts.tv_sec == header->ts.tv_sec && old.ts.tv_usec > header->ts.tv_usec))
printf("Inconsistent Timestamps! Old was %d.%.06d - New is %d.%.06d\n",old.ts.tv_sec,old.ts.tv_usec, header->ts.tv_sec,header->ts.tv_usec);
old=*header;
}
if(res == -1){
printf("Error reading the packets: %s\n", pcap_geterr(fp));
return -1;
}
scanf("%s",a);
return 0;
}
|
526388.c | /*
* Copyright 2008-2010 Freescale Semiconductor, Inc. All Rights Reserved.
*
* Freescale VIU video driver
*
* Authors: Hongjun Chen <[email protected]>
* Porting to 2.6.35 by DENX Software Engineering,
* Anatolij Gustschin <[email protected]>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
*/
#include <linux/module.h>
#include <linux/clk.h>
#include <linux/kernel.h>
#include <linux/i2c.h>
#include <linux/init.h>
#include <linux/interrupt.h>
#include <linux/io.h>
#include <linux/of_address.h>
#include <linux/of_irq.h>
#include <linux/of_platform.h>
#include <linux/slab.h>
#include <media/v4l2-common.h>
#include <media/v4l2-device.h>
#include <media/v4l2-ioctl.h>
#include <media/videobuf-dma-contig.h>
#define DRV_NAME "fsl_viu"
#define VIU_VERSION "0.5.1"
#define BUFFER_TIMEOUT msecs_to_jiffies(500) /* 0.5 seconds */
#define VIU_VID_MEM_LIMIT 4 /* Video memory limit, in Mb */
/* I2C address of video decoder chip is 0x4A */
#define VIU_VIDEO_DECODER_ADDR 0x25
/* supported controls */
static struct v4l2_queryctrl viu_qctrl[] = {
{
.id = V4L2_CID_BRIGHTNESS,
.type = V4L2_CTRL_TYPE_INTEGER,
.name = "Brightness",
.minimum = 0,
.maximum = 255,
.step = 1,
.default_value = 127,
.flags = 0,
}, {
.id = V4L2_CID_CONTRAST,
.type = V4L2_CTRL_TYPE_INTEGER,
.name = "Contrast",
.minimum = 0,
.maximum = 255,
.step = 0x1,
.default_value = 0x10,
.flags = 0,
}, {
.id = V4L2_CID_SATURATION,
.type = V4L2_CTRL_TYPE_INTEGER,
.name = "Saturation",
.minimum = 0,
.maximum = 255,
.step = 0x1,
.default_value = 127,
.flags = 0,
}, {
.id = V4L2_CID_HUE,
.type = V4L2_CTRL_TYPE_INTEGER,
.name = "Hue",
.minimum = -128,
.maximum = 127,
.step = 0x1,
.default_value = 0,
.flags = 0,
}
};
static int qctl_regs[ARRAY_SIZE(viu_qctrl)];
static int info_level;
#define dprintk(level, fmt, arg...) \
do { \
if (level <= info_level) \
printk(KERN_DEBUG "viu: " fmt , ## arg); \
} while (0)
/*
* Basic structures
*/
struct viu_fmt {
char name[32];
u32 fourcc; /* v4l2 format id */
u32 pixelformat;
int depth;
};
static struct viu_fmt formats[] = {
{
.name = "RGB-16 (5/B-6/G-5/R)",
.fourcc = V4L2_PIX_FMT_RGB565,
.pixelformat = V4L2_PIX_FMT_RGB565,
.depth = 16,
}, {
.name = "RGB-32 (A-R-G-B)",
.fourcc = V4L2_PIX_FMT_RGB32,
.pixelformat = V4L2_PIX_FMT_RGB32,
.depth = 32,
}
};
struct viu_dev;
struct viu_buf;
/* buffer for one video frame */
struct viu_buf {
/* common v4l buffer stuff -- must be first */
struct videobuf_buffer vb;
struct viu_fmt *fmt;
};
struct viu_dmaqueue {
struct viu_dev *dev;
struct list_head active;
struct list_head queued;
struct timer_list timeout;
};
struct viu_status {
u32 field_irq;
u32 vsync_irq;
u32 hsync_irq;
u32 vstart_irq;
u32 dma_end_irq;
u32 error_irq;
};
struct viu_reg {
u32 status_cfg;
u32 luminance;
u32 chroma_r;
u32 chroma_g;
u32 chroma_b;
u32 field_base_addr;
u32 dma_inc;
u32 picture_count;
u32 req_alarm;
u32 alpha;
} __attribute__ ((packed));
struct viu_dev {
struct v4l2_device v4l2_dev;
struct mutex lock;
spinlock_t slock;
int users;
struct device *dev;
/* various device info */
struct video_device *vdev;
struct viu_dmaqueue vidq;
enum v4l2_field capfield;
int field;
int first;
int dma_done;
/* Hardware register area */
struct viu_reg *vr;
/* Interrupt vector */
int irq;
struct viu_status irqs;
/* video overlay */
struct v4l2_framebuffer ovbuf;
struct viu_fmt *ovfmt;
unsigned int ovenable;
enum v4l2_field ovfield;
/* crop */
struct v4l2_rect crop_current;
/* clock pointer */
struct clk *clk;
/* decoder */
struct v4l2_subdev *decoder;
v4l2_std_id std;
};
struct viu_fh {
struct viu_dev *dev;
/* video capture */
struct videobuf_queue vb_vidq;
spinlock_t vbq_lock; /* spinlock for the videobuf queue */
/* video overlay */
struct v4l2_window win;
struct v4l2_clip clips[1];
/* video capture */
struct viu_fmt *fmt;
int width, height, sizeimage;
enum v4l2_buf_type type;
};
static struct viu_reg reg_val;
/*
* Macro definitions of VIU registers
*/
/* STATUS_CONFIG register */
enum status_config {
SOFT_RST = 1 << 0,
ERR_MASK = 0x0f << 4, /* Error code mask */
ERR_NO = 0x00, /* No error */
ERR_DMA_V = 0x01 << 4, /* DMA in vertical active */
ERR_DMA_VB = 0x02 << 4, /* DMA in vertical blanking */
ERR_LINE_TOO_LONG = 0x04 << 4, /* Line too long */
ERR_TOO_MANG_LINES = 0x05 << 4, /* Too many lines in field */
ERR_LINE_TOO_SHORT = 0x06 << 4, /* Line too short */
ERR_NOT_ENOUGH_LINE = 0x07 << 4, /* Not enough lines in field */
ERR_FIFO_OVERFLOW = 0x08 << 4, /* FIFO overflow */
ERR_FIFO_UNDERFLOW = 0x09 << 4, /* FIFO underflow */
ERR_1bit_ECC = 0x0a << 4, /* One bit ECC error */
ERR_MORE_ECC = 0x0b << 4, /* Two/more bits ECC error */
INT_FIELD_EN = 0x01 << 8, /* Enable field interrupt */
INT_VSYNC_EN = 0x01 << 9, /* Enable vsync interrupt */
INT_HSYNC_EN = 0x01 << 10, /* Enable hsync interrupt */
INT_VSTART_EN = 0x01 << 11, /* Enable vstart interrupt */
INT_DMA_END_EN = 0x01 << 12, /* Enable DMA end interrupt */
INT_ERROR_EN = 0x01 << 13, /* Enable error interrupt */
INT_ECC_EN = 0x01 << 14, /* Enable ECC interrupt */
INT_FIELD_STATUS = 0x01 << 16, /* field interrupt status */
INT_VSYNC_STATUS = 0x01 << 17, /* vsync interrupt status */
INT_HSYNC_STATUS = 0x01 << 18, /* hsync interrupt status */
INT_VSTART_STATUS = 0x01 << 19, /* vstart interrupt status */
INT_DMA_END_STATUS = 0x01 << 20, /* DMA end interrupt status */
INT_ERROR_STATUS = 0x01 << 21, /* error interrupt status */
DMA_ACT = 0x01 << 27, /* Enable DMA transfer */
FIELD_NO = 0x01 << 28, /* Field number */
DITHER_ON = 0x01 << 29, /* Dithering is on */
ROUND_ON = 0x01 << 30, /* Round is on */
MODE_32BIT = 0x01 << 31, /* Data in RGBa888,
* 0 in RGB565
*/
};
#define norm_maxw() 720
#define norm_maxh() 576
#define INT_ALL_STATUS (INT_FIELD_STATUS | INT_VSYNC_STATUS | \
INT_HSYNC_STATUS | INT_VSTART_STATUS | \
INT_DMA_END_STATUS | INT_ERROR_STATUS)
#define NUM_FORMATS ARRAY_SIZE(formats)
static irqreturn_t viu_intr(int irq, void *dev_id);
struct viu_fmt *format_by_fourcc(int fourcc)
{
int i;
for (i = 0; i < NUM_FORMATS; i++) {
if (formats[i].pixelformat == fourcc)
return formats + i;
}
dprintk(0, "unknown pixelformat:'%4.4s'\n", (char *)&fourcc);
return NULL;
}
void viu_start_dma(struct viu_dev *dev)
{
struct viu_reg *vr = dev->vr;
dev->field = 0;
/* Enable DMA operation */
out_be32(&vr->status_cfg, SOFT_RST);
out_be32(&vr->status_cfg, INT_FIELD_EN);
}
void viu_stop_dma(struct viu_dev *dev)
{
struct viu_reg *vr = dev->vr;
int cnt = 100;
u32 status_cfg;
out_be32(&vr->status_cfg, 0);
/* Clear pending interrupts */
status_cfg = in_be32(&vr->status_cfg);
if (status_cfg & 0x3f0000)
out_be32(&vr->status_cfg, status_cfg & 0x3f0000);
if (status_cfg & DMA_ACT) {
do {
status_cfg = in_be32(&vr->status_cfg);
if (status_cfg & INT_DMA_END_STATUS)
break;
} while (cnt--);
if (cnt < 0) {
/* timed out, issue soft reset */
out_be32(&vr->status_cfg, SOFT_RST);
out_be32(&vr->status_cfg, 0);
} else {
/* clear DMA_END and other pending irqs */
out_be32(&vr->status_cfg, status_cfg & 0x3f0000);
}
}
dev->field = 0;
}
static int restart_video_queue(struct viu_dmaqueue *vidq)
{
struct viu_buf *buf, *prev;
dprintk(1, "%s vidq=0x%08lx\n", __func__, (unsigned long)vidq);
if (!list_empty(&vidq->active)) {
buf = list_entry(vidq->active.next, struct viu_buf, vb.queue);
dprintk(2, "restart_queue [%p/%d]: restart dma\n",
buf, buf->vb.i);
viu_stop_dma(vidq->dev);
/* cancel all outstanding capture requests */
list_for_each_entry_safe(buf, prev, &vidq->active, vb.queue) {
list_del(&buf->vb.queue);
buf->vb.state = VIDEOBUF_ERROR;
wake_up(&buf->vb.done);
}
mod_timer(&vidq->timeout, jiffies+BUFFER_TIMEOUT);
return 0;
}
prev = NULL;
for (;;) {
if (list_empty(&vidq->queued))
return 0;
buf = list_entry(vidq->queued.next, struct viu_buf, vb.queue);
if (prev == NULL) {
list_move_tail(&buf->vb.queue, &vidq->active);
dprintk(1, "Restarting video dma\n");
viu_stop_dma(vidq->dev);
viu_start_dma(vidq->dev);
buf->vb.state = VIDEOBUF_ACTIVE;
mod_timer(&vidq->timeout, jiffies+BUFFER_TIMEOUT);
dprintk(2, "[%p/%d] restart_queue - first active\n",
buf, buf->vb.i);
} else if (prev->vb.width == buf->vb.width &&
prev->vb.height == buf->vb.height &&
prev->fmt == buf->fmt) {
list_move_tail(&buf->vb.queue, &vidq->active);
buf->vb.state = VIDEOBUF_ACTIVE;
dprintk(2, "[%p/%d] restart_queue - move to active\n",
buf, buf->vb.i);
} else {
return 0;
}
prev = buf;
}
}
static void viu_vid_timeout(unsigned long data)
{
struct viu_dev *dev = (struct viu_dev *)data;
struct viu_buf *buf;
struct viu_dmaqueue *vidq = &dev->vidq;
while (!list_empty(&vidq->active)) {
buf = list_entry(vidq->active.next, struct viu_buf, vb.queue);
list_del(&buf->vb.queue);
buf->vb.state = VIDEOBUF_ERROR;
wake_up(&buf->vb.done);
dprintk(1, "viu/0: [%p/%d] timeout\n", buf, buf->vb.i);
}
restart_video_queue(vidq);
}
/*
* Videobuf operations
*/
static int buffer_setup(struct videobuf_queue *vq, unsigned int *count,
unsigned int *size)
{
struct viu_fh *fh = vq->priv_data;
*size = fh->width * fh->height * fh->fmt->depth >> 3;
if (*count == 0)
*count = 32;
while (*size * *count > VIU_VID_MEM_LIMIT * 1024 * 1024)
(*count)--;
dprintk(1, "%s, count=%d, size=%d\n", __func__, *count, *size);
return 0;
}
static void free_buffer(struct videobuf_queue *vq, struct viu_buf *buf)
{
struct videobuf_buffer *vb = &buf->vb;
void *vaddr = NULL;
BUG_ON(in_interrupt());
videobuf_waiton(vq, &buf->vb, 0, 0);
if (vq->int_ops && vq->int_ops->vaddr)
vaddr = vq->int_ops->vaddr(vb);
if (vaddr)
videobuf_dma_contig_free(vq, &buf->vb);
buf->vb.state = VIDEOBUF_NEEDS_INIT;
}
inline int buffer_activate(struct viu_dev *dev, struct viu_buf *buf)
{
struct viu_reg *vr = dev->vr;
int bpp;
/* setup the DMA base address */
reg_val.field_base_addr = videobuf_to_dma_contig(&buf->vb);
dprintk(1, "buffer_activate [%p/%d]: dma addr 0x%lx\n",
buf, buf->vb.i, (unsigned long)reg_val.field_base_addr);
/* interlace is on by default, set horizontal DMA increment */
reg_val.status_cfg = 0;
bpp = buf->fmt->depth >> 3;
switch (bpp) {
case 2:
reg_val.status_cfg &= ~MODE_32BIT;
reg_val.dma_inc = buf->vb.width * 2;
break;
case 4:
reg_val.status_cfg |= MODE_32BIT;
reg_val.dma_inc = buf->vb.width * 4;
break;
default:
dprintk(0, "doesn't support color depth(%d)\n",
bpp * 8);
return -EINVAL;
}
/* setup picture_count register */
reg_val.picture_count = (buf->vb.height / 2) << 16 |
buf->vb.width;
reg_val.status_cfg |= DMA_ACT | INT_DMA_END_EN | INT_FIELD_EN;
buf->vb.state = VIDEOBUF_ACTIVE;
dev->capfield = buf->vb.field;
/* reset dma increment if needed */
if (!V4L2_FIELD_HAS_BOTH(buf->vb.field))
reg_val.dma_inc = 0;
out_be32(&vr->dma_inc, reg_val.dma_inc);
out_be32(&vr->picture_count, reg_val.picture_count);
out_be32(&vr->field_base_addr, reg_val.field_base_addr);
mod_timer(&dev->vidq.timeout, jiffies + BUFFER_TIMEOUT);
return 0;
}
static int buffer_prepare(struct videobuf_queue *vq,
struct videobuf_buffer *vb,
enum v4l2_field field)
{
struct viu_fh *fh = vq->priv_data;
struct viu_buf *buf = container_of(vb, struct viu_buf, vb);
int rc;
BUG_ON(fh->fmt == NULL);
if (fh->width < 48 || fh->width > norm_maxw() ||
fh->height < 32 || fh->height > norm_maxh())
return -EINVAL;
buf->vb.size = (fh->width * fh->height * fh->fmt->depth) >> 3;
if (buf->vb.baddr != 0 && buf->vb.bsize < buf->vb.size)
return -EINVAL;
if (buf->fmt != fh->fmt ||
buf->vb.width != fh->width ||
buf->vb.height != fh->height ||
buf->vb.field != field) {
buf->fmt = fh->fmt;
buf->vb.width = fh->width;
buf->vb.height = fh->height;
buf->vb.field = field;
}
if (buf->vb.state == VIDEOBUF_NEEDS_INIT) {
rc = videobuf_iolock(vq, &buf->vb, NULL);
if (rc != 0)
goto fail;
buf->vb.width = fh->width;
buf->vb.height = fh->height;
buf->vb.field = field;
buf->fmt = fh->fmt;
}
buf->vb.state = VIDEOBUF_PREPARED;
return 0;
fail:
free_buffer(vq, buf);
return rc;
}
static void buffer_queue(struct videobuf_queue *vq, struct videobuf_buffer *vb)
{
struct viu_buf *buf = container_of(vb, struct viu_buf, vb);
struct viu_fh *fh = vq->priv_data;
struct viu_dev *dev = fh->dev;
struct viu_dmaqueue *vidq = &dev->vidq;
struct viu_buf *prev;
if (!list_empty(&vidq->queued)) {
dprintk(1, "adding vb queue=0x%08lx\n",
(unsigned long)&buf->vb.queue);
dprintk(1, "vidq pointer 0x%p, queued 0x%p\n",
vidq, &vidq->queued);
dprintk(1, "dev %p, queued: self %p, next %p, head %p\n",
dev, &vidq->queued, vidq->queued.next,
vidq->queued.prev);
list_add_tail(&buf->vb.queue, &vidq->queued);
buf->vb.state = VIDEOBUF_QUEUED;
dprintk(2, "[%p/%d] buffer_queue - append to queued\n",
buf, buf->vb.i);
} else if (list_empty(&vidq->active)) {
dprintk(1, "adding vb active=0x%08lx\n",
(unsigned long)&buf->vb.queue);
list_add_tail(&buf->vb.queue, &vidq->active);
buf->vb.state = VIDEOBUF_ACTIVE;
mod_timer(&vidq->timeout, jiffies+BUFFER_TIMEOUT);
dprintk(2, "[%p/%d] buffer_queue - first active\n",
buf, buf->vb.i);
buffer_activate(dev, buf);
} else {
dprintk(1, "adding vb queue2=0x%08lx\n",
(unsigned long)&buf->vb.queue);
prev = list_entry(vidq->active.prev, struct viu_buf, vb.queue);
if (prev->vb.width == buf->vb.width &&
prev->vb.height == buf->vb.height &&
prev->fmt == buf->fmt) {
list_add_tail(&buf->vb.queue, &vidq->active);
buf->vb.state = VIDEOBUF_ACTIVE;
dprintk(2, "[%p/%d] buffer_queue - append to active\n",
buf, buf->vb.i);
} else {
list_add_tail(&buf->vb.queue, &vidq->queued);
buf->vb.state = VIDEOBUF_QUEUED;
dprintk(2, "[%p/%d] buffer_queue - first queued\n",
buf, buf->vb.i);
}
}
}
static void buffer_release(struct videobuf_queue *vq,
struct videobuf_buffer *vb)
{
struct viu_buf *buf = container_of(vb, struct viu_buf, vb);
struct viu_fh *fh = vq->priv_data;
struct viu_dev *dev = (struct viu_dev *)fh->dev;
viu_stop_dma(dev);
free_buffer(vq, buf);
}
static struct videobuf_queue_ops viu_video_qops = {
.buf_setup = buffer_setup,
.buf_prepare = buffer_prepare,
.buf_queue = buffer_queue,
.buf_release = buffer_release,
};
/*
* IOCTL vidioc handling
*/
static int vidioc_querycap(struct file *file, void *priv,
struct v4l2_capability *cap)
{
strcpy(cap->driver, "viu");
strcpy(cap->card, "viu");
cap->capabilities = V4L2_CAP_VIDEO_CAPTURE |
V4L2_CAP_STREAMING |
V4L2_CAP_VIDEO_OVERLAY |
V4L2_CAP_READWRITE;
return 0;
}
static int vidioc_enum_fmt(struct file *file, void *priv,
struct v4l2_fmtdesc *f)
{
int index = f->index;
if (f->index > NUM_FORMATS)
return -EINVAL;
strlcpy(f->description, formats[index].name, sizeof(f->description));
f->pixelformat = formats[index].fourcc;
return 0;
}
static int vidioc_g_fmt_cap(struct file *file, void *priv,
struct v4l2_format *f)
{
struct viu_fh *fh = priv;
f->fmt.pix.width = fh->width;
f->fmt.pix.height = fh->height;
f->fmt.pix.field = fh->vb_vidq.field;
f->fmt.pix.pixelformat = fh->fmt->pixelformat;
f->fmt.pix.bytesperline =
(f->fmt.pix.width * fh->fmt->depth) >> 3;
f->fmt.pix.sizeimage = fh->sizeimage;
return 0;
}
static int vidioc_try_fmt_cap(struct file *file, void *priv,
struct v4l2_format *f)
{
struct viu_fmt *fmt;
enum v4l2_field field;
unsigned int maxw, maxh;
fmt = format_by_fourcc(f->fmt.pix.pixelformat);
if (!fmt) {
dprintk(1, "Fourcc format (0x%08x) invalid.",
f->fmt.pix.pixelformat);
return -EINVAL;
}
field = f->fmt.pix.field;
if (field == V4L2_FIELD_ANY) {
field = V4L2_FIELD_INTERLACED;
} else if (field != V4L2_FIELD_INTERLACED) {
dprintk(1, "Field type invalid.\n");
return -EINVAL;
}
maxw = norm_maxw();
maxh = norm_maxh();
f->fmt.pix.field = field;
if (f->fmt.pix.height < 32)
f->fmt.pix.height = 32;
if (f->fmt.pix.height > maxh)
f->fmt.pix.height = maxh;
if (f->fmt.pix.width < 48)
f->fmt.pix.width = 48;
if (f->fmt.pix.width > maxw)
f->fmt.pix.width = maxw;
f->fmt.pix.width &= ~0x03;
f->fmt.pix.bytesperline =
(f->fmt.pix.width * fmt->depth) >> 3;
return 0;
}
static int vidioc_s_fmt_cap(struct file *file, void *priv,
struct v4l2_format *f)
{
struct viu_fh *fh = priv;
int ret;
ret = vidioc_try_fmt_cap(file, fh, f);
if (ret < 0)
return ret;
fh->fmt = format_by_fourcc(f->fmt.pix.pixelformat);
fh->width = f->fmt.pix.width;
fh->height = f->fmt.pix.height;
fh->sizeimage = f->fmt.pix.sizeimage;
fh->vb_vidq.field = f->fmt.pix.field;
fh->type = f->type;
dprintk(1, "set to pixelformat '%4.6s'\n", (char *)&fh->fmt->name);
return 0;
}
static int vidioc_g_fmt_overlay(struct file *file, void *priv,
struct v4l2_format *f)
{
struct viu_fh *fh = priv;
f->fmt.win = fh->win;
return 0;
}
static int verify_preview(struct viu_dev *dev, struct v4l2_window *win)
{
enum v4l2_field field;
int maxw, maxh;
if (dev->ovbuf.base == NULL)
return -EINVAL;
if (dev->ovfmt == NULL)
return -EINVAL;
if (win->w.width < 48 || win->w.height < 32)
return -EINVAL;
field = win->field;
maxw = dev->crop_current.width;
maxh = dev->crop_current.height;
if (field == V4L2_FIELD_ANY) {
field = (win->w.height > maxh/2)
? V4L2_FIELD_INTERLACED
: V4L2_FIELD_TOP;
}
switch (field) {
case V4L2_FIELD_TOP:
case V4L2_FIELD_BOTTOM:
maxh = maxh / 2;
break;
case V4L2_FIELD_INTERLACED:
break;
default:
return -EINVAL;
}
win->field = field;
if (win->w.width > maxw)
win->w.width = maxw;
if (win->w.height > maxh)
win->w.height = maxh;
return 0;
}
inline void viu_activate_overlay(struct viu_reg *viu_reg)
{
struct viu_reg *vr = viu_reg;
out_be32(&vr->field_base_addr, reg_val.field_base_addr);
out_be32(&vr->dma_inc, reg_val.dma_inc);
out_be32(&vr->picture_count, reg_val.picture_count);
}
static int viu_setup_preview(struct viu_dev *dev, struct viu_fh *fh)
{
int bpp;
dprintk(1, "%s %dx%d %s\n", __func__,
fh->win.w.width, fh->win.w.height, dev->ovfmt->name);
reg_val.status_cfg = 0;
/* setup window */
reg_val.picture_count = (fh->win.w.height / 2) << 16 |
fh->win.w.width;
/* setup color depth and dma increment */
bpp = dev->ovfmt->depth / 8;
switch (bpp) {
case 2:
reg_val.status_cfg &= ~MODE_32BIT;
reg_val.dma_inc = fh->win.w.width * 2;
break;
case 4:
reg_val.status_cfg |= MODE_32BIT;
reg_val.dma_inc = fh->win.w.width * 4;
break;
default:
dprintk(0, "device doesn't support color depth(%d)\n",
bpp * 8);
return -EINVAL;
}
dev->ovfield = fh->win.field;
if (!V4L2_FIELD_HAS_BOTH(dev->ovfield))
reg_val.dma_inc = 0;
reg_val.status_cfg |= DMA_ACT | INT_DMA_END_EN | INT_FIELD_EN;
/* setup the base address of the overlay buffer */
reg_val.field_base_addr = (u32)dev->ovbuf.base;
return 0;
}
static int vidioc_s_fmt_overlay(struct file *file, void *priv,
struct v4l2_format *f)
{
struct viu_fh *fh = priv;
struct viu_dev *dev = (struct viu_dev *)fh->dev;
unsigned long flags;
int err;
err = verify_preview(dev, &f->fmt.win);
if (err)
return err;
fh->win = f->fmt.win;
spin_lock_irqsave(&dev->slock, flags);
viu_setup_preview(dev, fh);
spin_unlock_irqrestore(&dev->slock, flags);
return 0;
}
static int vidioc_try_fmt_overlay(struct file *file, void *priv,
struct v4l2_format *f)
{
return 0;
}
static int vidioc_overlay(struct file *file, void *priv, unsigned int on)
{
struct viu_fh *fh = priv;
struct viu_dev *dev = (struct viu_dev *)fh->dev;
unsigned long flags;
if (on) {
spin_lock_irqsave(&dev->slock, flags);
viu_activate_overlay(dev->vr);
dev->ovenable = 1;
/* start dma */
viu_start_dma(dev);
spin_unlock_irqrestore(&dev->slock, flags);
} else {
viu_stop_dma(dev);
dev->ovenable = 0;
}
return 0;
}
int vidioc_g_fbuf(struct file *file, void *priv, struct v4l2_framebuffer *arg)
{
struct viu_fh *fh = priv;
struct viu_dev *dev = fh->dev;
struct v4l2_framebuffer *fb = arg;
*fb = dev->ovbuf;
fb->capability = V4L2_FBUF_CAP_LIST_CLIPPING;
return 0;
}
int vidioc_s_fbuf(struct file *file, void *priv, const struct v4l2_framebuffer *arg)
{
struct viu_fh *fh = priv;
struct viu_dev *dev = fh->dev;
const struct v4l2_framebuffer *fb = arg;
struct viu_fmt *fmt;
if (!capable(CAP_SYS_ADMIN) && !capable(CAP_SYS_RAWIO))
return -EPERM;
/* check args */
fmt = format_by_fourcc(fb->fmt.pixelformat);
if (fmt == NULL)
return -EINVAL;
/* ok, accept it */
dev->ovbuf = *fb;
dev->ovfmt = fmt;
if (dev->ovbuf.fmt.bytesperline == 0) {
dev->ovbuf.fmt.bytesperline =
dev->ovbuf.fmt.width * fmt->depth / 8;
}
return 0;
}
static int vidioc_reqbufs(struct file *file, void *priv,
struct v4l2_requestbuffers *p)
{
struct viu_fh *fh = priv;
return videobuf_reqbufs(&fh->vb_vidq, p);
}
static int vidioc_querybuf(struct file *file, void *priv,
struct v4l2_buffer *p)
{
struct viu_fh *fh = priv;
return videobuf_querybuf(&fh->vb_vidq, p);
}
static int vidioc_qbuf(struct file *file, void *priv, struct v4l2_buffer *p)
{
struct viu_fh *fh = priv;
return videobuf_qbuf(&fh->vb_vidq, p);
}
static int vidioc_dqbuf(struct file *file, void *priv, struct v4l2_buffer *p)
{
struct viu_fh *fh = priv;
return videobuf_dqbuf(&fh->vb_vidq, p,
file->f_flags & O_NONBLOCK);
}
static int vidioc_streamon(struct file *file, void *priv, enum v4l2_buf_type i)
{
struct viu_fh *fh = priv;
struct viu_dev *dev = fh->dev;
if (fh->type != V4L2_BUF_TYPE_VIDEO_CAPTURE)
return -EINVAL;
if (fh->type != i)
return -EINVAL;
if (dev->ovenable)
dev->ovenable = 0;
viu_start_dma(fh->dev);
return videobuf_streamon(&fh->vb_vidq);
}
static int vidioc_streamoff(struct file *file, void *priv, enum v4l2_buf_type i)
{
struct viu_fh *fh = priv;
if (fh->type != V4L2_BUF_TYPE_VIDEO_CAPTURE)
return -EINVAL;
if (fh->type != i)
return -EINVAL;
viu_stop_dma(fh->dev);
return videobuf_streamoff(&fh->vb_vidq);
}
#define decoder_call(viu, o, f, args...) \
v4l2_subdev_call(viu->decoder, o, f, ##args)
static int vidioc_querystd(struct file *file, void *priv, v4l2_std_id *std_id)
{
struct viu_fh *fh = priv;
decoder_call(fh->dev, video, querystd, std_id);
return 0;
}
static int vidioc_s_std(struct file *file, void *priv, v4l2_std_id id)
{
struct viu_fh *fh = priv;
fh->dev->std = id;
decoder_call(fh->dev, video, s_std, id);
return 0;
}
static int vidioc_g_std(struct file *file, void *priv, v4l2_std_id *std_id)
{
struct viu_fh *fh = priv;
*std_id = fh->dev->std;
return 0;
}
/* only one input in this driver */
static int vidioc_enum_input(struct file *file, void *priv,
struct v4l2_input *inp)
{
struct viu_fh *fh = priv;
if (inp->index != 0)
return -EINVAL;
inp->type = V4L2_INPUT_TYPE_CAMERA;
inp->std = fh->dev->vdev->tvnorms;
strcpy(inp->name, "Camera");
return 0;
}
static int vidioc_g_input(struct file *file, void *priv, unsigned int *i)
{
*i = 0;
return 0;
}
static int vidioc_s_input(struct file *file, void *priv, unsigned int i)
{
struct viu_fh *fh = priv;
if (i > 1)
return -EINVAL;
decoder_call(fh->dev, video, s_routing, i, 0, 0);
return 0;
}
/* Controls */
static int vidioc_queryctrl(struct file *file, void *priv,
struct v4l2_queryctrl *qc)
{
int i;
for (i = 0; i < ARRAY_SIZE(viu_qctrl); i++) {
if (qc->id && qc->id == viu_qctrl[i].id) {
memcpy(qc, &(viu_qctrl[i]), sizeof(*qc));
return 0;
}
}
return -EINVAL;
}
static int vidioc_g_ctrl(struct file *file, void *priv,
struct v4l2_control *ctrl)
{
int i;
for (i = 0; i < ARRAY_SIZE(viu_qctrl); i++) {
if (ctrl->id == viu_qctrl[i].id) {
ctrl->value = qctl_regs[i];
return 0;
}
}
return -EINVAL;
}
static int vidioc_s_ctrl(struct file *file, void *priv,
struct v4l2_control *ctrl)
{
int i;
for (i = 0; i < ARRAY_SIZE(viu_qctrl); i++) {
if (ctrl->id == viu_qctrl[i].id) {
if (ctrl->value < viu_qctrl[i].minimum
|| ctrl->value > viu_qctrl[i].maximum)
return -ERANGE;
qctl_regs[i] = ctrl->value;
return 0;
}
}
return -EINVAL;
}
inline void viu_activate_next_buf(struct viu_dev *dev,
struct viu_dmaqueue *viuq)
{
struct viu_dmaqueue *vidq = viuq;
struct viu_buf *buf;
/* launch another DMA operation for an active/queued buffer */
if (!list_empty(&vidq->active)) {
buf = list_entry(vidq->active.next, struct viu_buf,
vb.queue);
dprintk(1, "start another queued buffer: 0x%p\n", buf);
buffer_activate(dev, buf);
} else if (!list_empty(&vidq->queued)) {
buf = list_entry(vidq->queued.next, struct viu_buf,
vb.queue);
list_del(&buf->vb.queue);
dprintk(1, "start another queued buffer: 0x%p\n", buf);
list_add_tail(&buf->vb.queue, &vidq->active);
buf->vb.state = VIDEOBUF_ACTIVE;
buffer_activate(dev, buf);
}
}
inline void viu_default_settings(struct viu_reg *viu_reg)
{
struct viu_reg *vr = viu_reg;
out_be32(&vr->luminance, 0x9512A254);
out_be32(&vr->chroma_r, 0x03310000);
out_be32(&vr->chroma_g, 0x06600F38);
out_be32(&vr->chroma_b, 0x00000409);
out_be32(&vr->alpha, 0x000000ff);
out_be32(&vr->req_alarm, 0x00000090);
dprintk(1, "status reg: 0x%08x, field base: 0x%08x\n",
in_be32(&vr->status_cfg), in_be32(&vr->field_base_addr));
}
static void viu_overlay_intr(struct viu_dev *dev, u32 status)
{
struct viu_reg *vr = dev->vr;
if (status & INT_DMA_END_STATUS)
dev->dma_done = 1;
if (status & INT_FIELD_STATUS) {
if (dev->dma_done) {
u32 addr = reg_val.field_base_addr;
dev->dma_done = 0;
if (status & FIELD_NO)
addr += reg_val.dma_inc;
out_be32(&vr->field_base_addr, addr);
out_be32(&vr->dma_inc, reg_val.dma_inc);
out_be32(&vr->status_cfg,
(status & 0xffc0ffff) |
(status & INT_ALL_STATUS) |
reg_val.status_cfg);
} else if (status & INT_VSYNC_STATUS) {
out_be32(&vr->status_cfg,
(status & 0xffc0ffff) |
(status & INT_ALL_STATUS) |
reg_val.status_cfg);
}
}
}
static void viu_capture_intr(struct viu_dev *dev, u32 status)
{
struct viu_dmaqueue *vidq = &dev->vidq;
struct viu_reg *vr = dev->vr;
struct viu_buf *buf;
int field_num;
int need_two;
int dma_done = 0;
field_num = status & FIELD_NO;
need_two = V4L2_FIELD_HAS_BOTH(dev->capfield);
if (status & INT_DMA_END_STATUS) {
dma_done = 1;
if (((field_num == 0) && (dev->field == 0)) ||
(field_num && (dev->field == 1)))
dev->field++;
}
if (status & INT_FIELD_STATUS) {
dprintk(1, "irq: field %d, done %d\n",
!!field_num, dma_done);
if (unlikely(dev->first)) {
if (field_num == 0) {
dev->first = 0;
dprintk(1, "activate first buf\n");
viu_activate_next_buf(dev, vidq);
} else
dprintk(1, "wait field 0\n");
return;
}
/* setup buffer address for next dma operation */
if (!list_empty(&vidq->active)) {
u32 addr = reg_val.field_base_addr;
if (field_num && need_two) {
addr += reg_val.dma_inc;
dprintk(1, "field 1, 0x%lx, dev field %d\n",
(unsigned long)addr, dev->field);
}
out_be32(&vr->field_base_addr, addr);
out_be32(&vr->dma_inc, reg_val.dma_inc);
out_be32(&vr->status_cfg,
(status & 0xffc0ffff) |
(status & INT_ALL_STATUS) |
reg_val.status_cfg);
return;
}
}
if (dma_done && field_num && (dev->field == 2)) {
dev->field = 0;
buf = list_entry(vidq->active.next,
struct viu_buf, vb.queue);
dprintk(1, "viu/0: [%p/%d] 0x%lx/0x%lx: dma complete\n",
buf, buf->vb.i,
(unsigned long)videobuf_to_dma_contig(&buf->vb),
(unsigned long)in_be32(&vr->field_base_addr));
if (waitqueue_active(&buf->vb.done)) {
list_del(&buf->vb.queue);
v4l2_get_timestamp(&buf->vb.ts);
buf->vb.state = VIDEOBUF_DONE;
buf->vb.field_count++;
wake_up(&buf->vb.done);
}
/* activate next dma buffer */
viu_activate_next_buf(dev, vidq);
}
}
static irqreturn_t viu_intr(int irq, void *dev_id)
{
struct viu_dev *dev = (struct viu_dev *)dev_id;
struct viu_reg *vr = dev->vr;
u32 status;
u32 error;
status = in_be32(&vr->status_cfg);
if (status & INT_ERROR_STATUS) {
dev->irqs.error_irq++;
error = status & ERR_MASK;
if (error)
dprintk(1, "Err: error(%d), times:%d!\n",
error >> 4, dev->irqs.error_irq);
/* Clear interrupt error bit and error flags */
out_be32(&vr->status_cfg,
(status & 0xffc0ffff) | INT_ERROR_STATUS);
}
if (status & INT_DMA_END_STATUS) {
dev->irqs.dma_end_irq++;
dev->dma_done = 1;
dprintk(2, "VIU DMA end interrupt times: %d\n",
dev->irqs.dma_end_irq);
}
if (status & INT_HSYNC_STATUS)
dev->irqs.hsync_irq++;
if (status & INT_FIELD_STATUS) {
dev->irqs.field_irq++;
dprintk(2, "VIU field interrupt times: %d\n",
dev->irqs.field_irq);
}
if (status & INT_VSTART_STATUS)
dev->irqs.vstart_irq++;
if (status & INT_VSYNC_STATUS) {
dev->irqs.vsync_irq++;
dprintk(2, "VIU vsync interrupt times: %d\n",
dev->irqs.vsync_irq);
}
/* clear all pending irqs */
status = in_be32(&vr->status_cfg);
out_be32(&vr->status_cfg,
(status & 0xffc0ffff) | (status & INT_ALL_STATUS));
if (dev->ovenable) {
viu_overlay_intr(dev, status);
return IRQ_HANDLED;
}
/* Capture mode */
viu_capture_intr(dev, status);
return IRQ_HANDLED;
}
/*
* File operations for the device
*/
static int viu_open(struct file *file)
{
struct video_device *vdev = video_devdata(file);
struct viu_dev *dev = video_get_drvdata(vdev);
struct viu_fh *fh;
struct viu_reg *vr;
int minor = vdev->minor;
u32 status_cfg;
int i;
dprintk(1, "viu: open (minor=%d)\n", minor);
dev->users++;
if (dev->users > 1) {
dev->users--;
return -EBUSY;
}
vr = dev->vr;
dprintk(1, "open minor=%d type=%s users=%d\n", minor,
v4l2_type_names[V4L2_BUF_TYPE_VIDEO_CAPTURE], dev->users);
if (mutex_lock_interruptible(&dev->lock)) {
dev->users--;
return -ERESTARTSYS;
}
/* allocate and initialize per filehandle data */
fh = kzalloc(sizeof(*fh), GFP_KERNEL);
if (!fh) {
dev->users--;
mutex_unlock(&dev->lock);
return -ENOMEM;
}
file->private_data = fh;
fh->dev = dev;
fh->type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
fh->fmt = format_by_fourcc(V4L2_PIX_FMT_RGB32);
fh->width = norm_maxw();
fh->height = norm_maxh();
dev->crop_current.width = fh->width;
dev->crop_current.height = fh->height;
/* Put all controls at a sane state */
for (i = 0; i < ARRAY_SIZE(viu_qctrl); i++)
qctl_regs[i] = viu_qctrl[i].default_value;
dprintk(1, "Open: fh=0x%08lx, dev=0x%08lx, dev->vidq=0x%08lx\n",
(unsigned long)fh, (unsigned long)dev,
(unsigned long)&dev->vidq);
dprintk(1, "Open: list_empty queued=%d\n",
list_empty(&dev->vidq.queued));
dprintk(1, "Open: list_empty active=%d\n",
list_empty(&dev->vidq.active));
viu_default_settings(vr);
status_cfg = in_be32(&vr->status_cfg);
out_be32(&vr->status_cfg,
status_cfg & ~(INT_VSYNC_EN | INT_HSYNC_EN |
INT_FIELD_EN | INT_VSTART_EN |
INT_DMA_END_EN | INT_ERROR_EN | INT_ECC_EN));
status_cfg = in_be32(&vr->status_cfg);
out_be32(&vr->status_cfg, status_cfg | INT_ALL_STATUS);
spin_lock_init(&fh->vbq_lock);
videobuf_queue_dma_contig_init(&fh->vb_vidq, &viu_video_qops,
dev->dev, &fh->vbq_lock,
fh->type, V4L2_FIELD_INTERLACED,
sizeof(struct viu_buf), fh,
&fh->dev->lock);
mutex_unlock(&dev->lock);
return 0;
}
static ssize_t viu_read(struct file *file, char __user *data, size_t count,
loff_t *ppos)
{
struct viu_fh *fh = file->private_data;
struct viu_dev *dev = fh->dev;
int ret = 0;
dprintk(2, "%s\n", __func__);
if (dev->ovenable)
dev->ovenable = 0;
if (fh->type == V4L2_BUF_TYPE_VIDEO_CAPTURE) {
if (mutex_lock_interruptible(&dev->lock))
return -ERESTARTSYS;
viu_start_dma(dev);
ret = videobuf_read_stream(&fh->vb_vidq, data, count,
ppos, 0, file->f_flags & O_NONBLOCK);
mutex_unlock(&dev->lock);
return ret;
}
return 0;
}
static unsigned int viu_poll(struct file *file, struct poll_table_struct *wait)
{
struct viu_fh *fh = file->private_data;
struct videobuf_queue *q = &fh->vb_vidq;
struct viu_dev *dev = fh->dev;
unsigned int res;
if (V4L2_BUF_TYPE_VIDEO_CAPTURE != fh->type)
return POLLERR;
mutex_lock(&dev->lock);
res = videobuf_poll_stream(file, q, wait);
mutex_unlock(&dev->lock);
return res;
}
static int viu_release(struct file *file)
{
struct viu_fh *fh = file->private_data;
struct viu_dev *dev = fh->dev;
int minor = video_devdata(file)->minor;
mutex_lock(&dev->lock);
viu_stop_dma(dev);
videobuf_stop(&fh->vb_vidq);
videobuf_mmap_free(&fh->vb_vidq);
mutex_unlock(&dev->lock);
kfree(fh);
dev->users--;
dprintk(1, "close (minor=%d, users=%d)\n",
minor, dev->users);
return 0;
}
void viu_reset(struct viu_reg *reg)
{
out_be32(®->status_cfg, 0);
out_be32(®->luminance, 0x9512a254);
out_be32(®->chroma_r, 0x03310000);
out_be32(®->chroma_g, 0x06600f38);
out_be32(®->chroma_b, 0x00000409);
out_be32(®->field_base_addr, 0);
out_be32(®->dma_inc, 0);
out_be32(®->picture_count, 0x01e002d0);
out_be32(®->req_alarm, 0x00000090);
out_be32(®->alpha, 0x000000ff);
}
static int viu_mmap(struct file *file, struct vm_area_struct *vma)
{
struct viu_fh *fh = file->private_data;
struct viu_dev *dev = fh->dev;
int ret;
dprintk(1, "mmap called, vma=0x%08lx\n", (unsigned long)vma);
if (mutex_lock_interruptible(&dev->lock))
return -ERESTARTSYS;
ret = videobuf_mmap_mapper(&fh->vb_vidq, vma);
mutex_unlock(&dev->lock);
dprintk(1, "vma start=0x%08lx, size=%ld, ret=%d\n",
(unsigned long)vma->vm_start,
(unsigned long)vma->vm_end-(unsigned long)vma->vm_start,
ret);
return ret;
}
static struct v4l2_file_operations viu_fops = {
.owner = THIS_MODULE,
.open = viu_open,
.release = viu_release,
.read = viu_read,
.poll = viu_poll,
.unlocked_ioctl = video_ioctl2, /* V4L2 ioctl handler */
.mmap = viu_mmap,
};
static const struct v4l2_ioctl_ops viu_ioctl_ops = {
.vidioc_querycap = vidioc_querycap,
.vidioc_enum_fmt_vid_cap = vidioc_enum_fmt,
.vidioc_g_fmt_vid_cap = vidioc_g_fmt_cap,
.vidioc_try_fmt_vid_cap = vidioc_try_fmt_cap,
.vidioc_s_fmt_vid_cap = vidioc_s_fmt_cap,
.vidioc_enum_fmt_vid_overlay = vidioc_enum_fmt,
.vidioc_g_fmt_vid_overlay = vidioc_g_fmt_overlay,
.vidioc_try_fmt_vid_overlay = vidioc_try_fmt_overlay,
.vidioc_s_fmt_vid_overlay = vidioc_s_fmt_overlay,
.vidioc_overlay = vidioc_overlay,
.vidioc_g_fbuf = vidioc_g_fbuf,
.vidioc_s_fbuf = vidioc_s_fbuf,
.vidioc_reqbufs = vidioc_reqbufs,
.vidioc_querybuf = vidioc_querybuf,
.vidioc_qbuf = vidioc_qbuf,
.vidioc_dqbuf = vidioc_dqbuf,
.vidioc_g_std = vidioc_g_std,
.vidioc_s_std = vidioc_s_std,
.vidioc_querystd = vidioc_querystd,
.vidioc_enum_input = vidioc_enum_input,
.vidioc_g_input = vidioc_g_input,
.vidioc_s_input = vidioc_s_input,
.vidioc_queryctrl = vidioc_queryctrl,
.vidioc_g_ctrl = vidioc_g_ctrl,
.vidioc_s_ctrl = vidioc_s_ctrl,
.vidioc_streamon = vidioc_streamon,
.vidioc_streamoff = vidioc_streamoff,
};
static struct video_device viu_template = {
.name = "FSL viu",
.fops = &viu_fops,
.minor = -1,
.ioctl_ops = &viu_ioctl_ops,
.release = video_device_release,
.tvnorms = V4L2_STD_NTSC_M | V4L2_STD_PAL,
};
static int viu_of_probe(struct platform_device *op)
{
struct viu_dev *viu_dev;
struct video_device *vdev;
struct resource r;
struct viu_reg __iomem *viu_regs;
struct i2c_adapter *ad;
int ret, viu_irq;
struct clk *clk;
ret = of_address_to_resource(op->dev.of_node, 0, &r);
if (ret) {
dev_err(&op->dev, "Can't parse device node resource\n");
return -ENODEV;
}
viu_irq = irq_of_parse_and_map(op->dev.of_node, 0);
if (viu_irq == NO_IRQ) {
dev_err(&op->dev, "Error while mapping the irq\n");
return -EINVAL;
}
/* request mem region */
if (!devm_request_mem_region(&op->dev, r.start,
sizeof(struct viu_reg), DRV_NAME)) {
dev_err(&op->dev, "Error while requesting mem region\n");
ret = -EBUSY;
goto err;
}
/* remap registers */
viu_regs = devm_ioremap(&op->dev, r.start, sizeof(struct viu_reg));
if (!viu_regs) {
dev_err(&op->dev, "Can't map register set\n");
ret = -ENOMEM;
goto err;
}
/* Prepare our private structure */
viu_dev = devm_kzalloc(&op->dev, sizeof(struct viu_dev), GFP_ATOMIC);
if (!viu_dev) {
dev_err(&op->dev, "Can't allocate private structure\n");
ret = -ENOMEM;
goto err;
}
viu_dev->vr = viu_regs;
viu_dev->irq = viu_irq;
viu_dev->dev = &op->dev;
/* init video dma queues */
INIT_LIST_HEAD(&viu_dev->vidq.active);
INIT_LIST_HEAD(&viu_dev->vidq.queued);
snprintf(viu_dev->v4l2_dev.name,
sizeof(viu_dev->v4l2_dev.name), "%s", "VIU");
ret = v4l2_device_register(viu_dev->dev, &viu_dev->v4l2_dev);
if (ret < 0) {
dev_err(&op->dev, "v4l2_device_register() failed: %d\n", ret);
goto err;
}
ad = i2c_get_adapter(0);
viu_dev->decoder = v4l2_i2c_new_subdev(&viu_dev->v4l2_dev, ad,
"saa7113", VIU_VIDEO_DECODER_ADDR, NULL);
viu_dev->vidq.timeout.function = viu_vid_timeout;
viu_dev->vidq.timeout.data = (unsigned long)viu_dev;
init_timer(&viu_dev->vidq.timeout);
viu_dev->std = V4L2_STD_NTSC_M;
viu_dev->first = 1;
/* Allocate memory for video device */
vdev = video_device_alloc();
if (vdev == NULL) {
ret = -ENOMEM;
goto err_vdev;
}
memcpy(vdev, &viu_template, sizeof(viu_template));
vdev->v4l2_dev = &viu_dev->v4l2_dev;
viu_dev->vdev = vdev;
/* initialize locks */
mutex_init(&viu_dev->lock);
viu_dev->vdev->lock = &viu_dev->lock;
spin_lock_init(&viu_dev->slock);
video_set_drvdata(viu_dev->vdev, viu_dev);
mutex_lock(&viu_dev->lock);
ret = video_register_device(viu_dev->vdev, VFL_TYPE_GRABBER, -1);
if (ret < 0) {
video_device_release(viu_dev->vdev);
goto err_vdev;
}
/* enable VIU clock */
clk = devm_clk_get(&op->dev, "ipg");
if (IS_ERR(clk)) {
dev_err(&op->dev, "failed to lookup the clock!\n");
ret = PTR_ERR(clk);
goto err_clk;
}
ret = clk_prepare_enable(clk);
if (ret) {
dev_err(&op->dev, "failed to enable the clock!\n");
goto err_clk;
}
viu_dev->clk = clk;
/* reset VIU module */
viu_reset(viu_dev->vr);
/* install interrupt handler */
if (request_irq(viu_dev->irq, viu_intr, 0, "viu", (void *)viu_dev)) {
dev_err(&op->dev, "Request VIU IRQ failed.\n");
ret = -ENODEV;
goto err_irq;
}
mutex_unlock(&viu_dev->lock);
dev_info(&op->dev, "Freescale VIU Video Capture Board\n");
return ret;
err_irq:
clk_disable_unprepare(viu_dev->clk);
err_clk:
video_unregister_device(viu_dev->vdev);
err_vdev:
mutex_unlock(&viu_dev->lock);
i2c_put_adapter(ad);
v4l2_device_unregister(&viu_dev->v4l2_dev);
err:
irq_dispose_mapping(viu_irq);
return ret;
}
static int viu_of_remove(struct platform_device *op)
{
struct v4l2_device *v4l2_dev = dev_get_drvdata(&op->dev);
struct viu_dev *dev = container_of(v4l2_dev, struct viu_dev, v4l2_dev);
struct v4l2_subdev *sdev = list_entry(v4l2_dev->subdevs.next,
struct v4l2_subdev, list);
struct i2c_client *client = v4l2_get_subdevdata(sdev);
free_irq(dev->irq, (void *)dev);
irq_dispose_mapping(dev->irq);
clk_disable_unprepare(dev->clk);
video_unregister_device(dev->vdev);
i2c_put_adapter(client->adapter);
v4l2_device_unregister(&dev->v4l2_dev);
return 0;
}
#ifdef CONFIG_PM
static int viu_suspend(struct platform_device *op, pm_message_t state)
{
struct v4l2_device *v4l2_dev = dev_get_drvdata(&op->dev);
struct viu_dev *dev = container_of(v4l2_dev, struct viu_dev, v4l2_dev);
clk_disable(dev->clk);
return 0;
}
static int viu_resume(struct platform_device *op)
{
struct v4l2_device *v4l2_dev = dev_get_drvdata(&op->dev);
struct viu_dev *dev = container_of(v4l2_dev, struct viu_dev, v4l2_dev);
clk_enable(dev->clk);
return 0;
}
#endif
/*
* Initialization and module stuff
*/
static struct of_device_id mpc512x_viu_of_match[] = {
{
.compatible = "fsl,mpc5121-viu",
},
{},
};
MODULE_DEVICE_TABLE(of, mpc512x_viu_of_match);
static struct platform_driver viu_of_platform_driver = {
.probe = viu_of_probe,
.remove = viu_of_remove,
#ifdef CONFIG_PM
.suspend = viu_suspend,
.resume = viu_resume,
#endif
.driver = {
.name = DRV_NAME,
.owner = THIS_MODULE,
.of_match_table = mpc512x_viu_of_match,
},
};
module_platform_driver(viu_of_platform_driver);
MODULE_DESCRIPTION("Freescale Video-In(VIU)");
MODULE_AUTHOR("Hongjun Chen");
MODULE_LICENSE("GPL");
MODULE_VERSION(VIU_VERSION);
|
787714.c | #include <stdio.h>
int main() {
int N, i, M, PAR;
int E[61], D[61];
char Lado[5];
while (scanf("%d", &N) != EOF) {
PAR = 0;
if (N == 0) break;
for (i = 30; i < 61; i++) {
E[i] = 0;
D[i] = 0;
}
for (i = 0; i < N; i++) {
scanf("%d %s", &M, Lado);
if(Lado[0] == 'E') E[M]++;
else D[M]++;
}
for (i = 30; i < 61; i++) {
if (E[i] != 0 && D[i] != 0) {
if (E[i] < D[i]) PAR = PAR + E[i];
else PAR = PAR + D[i];
}
}
printf("%d\n", PAR);
}
return 0;
} |
229483.c | /*
* (c) copyright 1988 by the Vrije Universiteit, Amsterdam, The Netherlands.
* See the copyright notice in the ACK home directory, in the file "Copyright".
*
*
* Module: range checks for INTEGER, now for array indexing
* Author: Ceriel J.H. Jacobs
* Version: $Id$
*/
#include "libm2.h"
#include <em_abs.h>
void rcka(struct array_descr* descr, int indx)
{
if (indx < 0 || indx > descr->n_elts_min_one)
TRP(EARRAY);
}
|
932881.c | /*
* Copyright (c) 2014-2018, ARM Limited and Contributors. All rights reserved.
*
* SPDX-License-Identifier: BSD-3-Clause
*/
#include <assert.h>
#include <stdint.h>
#include <arch_helpers.h>
#include <common/debug.h>
#include <plat/common/platform.h>
#include <css_def.h>
#include "../mhu/css_mhu.h"
#include "../scpi/css_scpi.h"
#include "css_scp.h"
/* ID of the MHU slot used for the BOM protocol */
#define BOM_MHU_SLOT_ID 0
/* Boot commands sent from AP -> SCP */
#define BOOT_CMD_INFO 0x00
#define BOOT_CMD_DATA 0x01
/* BOM command header */
typedef struct {
uint32_t id : 8;
uint32_t reserved : 24;
} bom_cmd_t;
typedef struct {
uint32_t image_size;
uint32_t checksum;
} cmd_info_payload_t;
/*
* Unlike the SCPI protocol, the boot protocol uses the same memory region
* for both AP -> SCP and SCP -> AP transfers; define the address of this...
*/
#define BOM_SHARED_MEM PLAT_CSS_SCP_COM_SHARED_MEM_BASE
#define BOM_CMD_HEADER ((bom_cmd_t *) BOM_SHARED_MEM)
#define BOM_CMD_PAYLOAD ((void *) (BOM_SHARED_MEM + sizeof(bom_cmd_t)))
typedef struct {
/* Offset from the base address of the Trusted RAM */
uint32_t offset;
uint32_t block_size;
} cmd_data_payload_t;
/*
* All CSS platforms load SCP_BL2/SCP_BL2U just below BL2 (this is where BL31
* usually resides except when ARM_BL31_IN_DRAM is
* set). Ensure that SCP_BL2/SCP_BL2U do not overflow into shared RAM and
* the tb_fw_config.
*/
CASSERT(SCP_BL2_LIMIT <= BL2_BASE, assert_scp_bl2_overwrite_bl2);
CASSERT(SCP_BL2U_LIMIT <= BL2_BASE, assert_scp_bl2u_overwrite_bl2);
CASSERT(SCP_BL2_BASE >= ARM_TB_FW_CONFIG_LIMIT, assert_scp_bl2_overflow);
CASSERT(SCP_BL2U_BASE >= ARM_TB_FW_CONFIG_LIMIT, assert_scp_bl2u_overflow);
static void scp_boot_message_start(void)
{
mhu_secure_message_start(BOM_MHU_SLOT_ID);
}
static void scp_boot_message_send(size_t payload_size)
{
/* Ensure that any write to the BOM payload area is seen by SCP before
* we write to the MHU register. If these 2 writes were reordered by
* the CPU then SCP would read stale payload data */
dmbst();
/* Send command to SCP */
mhu_secure_message_send(BOM_MHU_SLOT_ID);
}
static uint32_t scp_boot_message_wait(size_t size)
{
uint32_t mhu_status;
mhu_status = mhu_secure_message_wait();
/* Expect an SCP Boot Protocol message, reject any other protocol */
if (mhu_status != (1 << BOM_MHU_SLOT_ID)) {
ERROR("MHU: Unexpected protocol (MHU status: 0x%x)\n",
mhu_status);
panic();
}
/* Ensure that any read to the BOM payload area is done after reading
* the MHU register. If these 2 reads were reordered then the CPU would
* read invalid payload data */
dmbld();
return *(uint32_t *) BOM_SHARED_MEM;
}
static void scp_boot_message_end(void)
{
mhu_secure_message_end(BOM_MHU_SLOT_ID);
}
int css_scp_boot_image_xfer(void *image, unsigned int image_size)
{
uint32_t response;
uint32_t checksum;
cmd_info_payload_t *cmd_info_payload;
cmd_data_payload_t *cmd_data_payload;
assert((uintptr_t) image == SCP_BL2_BASE);
if ((image_size == 0) || (image_size % 4 != 0)) {
ERROR("Invalid size for the SCP_BL2 image. Must be a multiple of "
"4 bytes and not zero (current size = 0x%x)\n",
image_size);
return -1;
}
/* Extract the checksum from the image */
checksum = *(uint32_t *) image;
image = (char *) image + sizeof(checksum);
image_size -= sizeof(checksum);
mhu_secure_init();
VERBOSE("Send info about the SCP_BL2 image to be transferred to SCP\n");
/*
* Send information about the SCP firmware image about to be transferred
* to SCP
*/
scp_boot_message_start();
BOM_CMD_HEADER->id = BOOT_CMD_INFO;
cmd_info_payload = BOM_CMD_PAYLOAD;
cmd_info_payload->image_size = image_size;
cmd_info_payload->checksum = checksum;
scp_boot_message_send(sizeof(*cmd_info_payload));
#if CSS_DETECT_PRE_1_7_0_SCP
{
const uint32_t deprecated_scp_nack_cmd = 0x404;
uint32_t mhu_status;
VERBOSE("Detecting SCP version incompatibility\n");
mhu_status = mhu_secure_message_wait();
if (mhu_status == deprecated_scp_nack_cmd) {
ERROR("Detected an incompatible version of the SCP firmware.\n");
ERROR("Only versions from v1.7.0 onwards are supported.\n");
ERROR("Please update the SCP firmware.\n");
return -1;
}
VERBOSE("SCP version looks OK\n");
}
#endif /* CSS_DETECT_PRE_1_7_0_SCP */
response = scp_boot_message_wait(sizeof(response));
scp_boot_message_end();
if (response != 0) {
ERROR("SCP BOOT_CMD_INFO returned error %u\n", response);
return -1;
}
VERBOSE("Transferring SCP_BL2 image to SCP\n");
/* Transfer SCP_BL2 image to SCP */
scp_boot_message_start();
BOM_CMD_HEADER->id = BOOT_CMD_DATA;
cmd_data_payload = BOM_CMD_PAYLOAD;
cmd_data_payload->offset = (uintptr_t) image - ARM_TRUSTED_SRAM_BASE;
cmd_data_payload->block_size = image_size;
scp_boot_message_send(sizeof(*cmd_data_payload));
response = scp_boot_message_wait(sizeof(response));
scp_boot_message_end();
if (response != 0) {
ERROR("SCP BOOT_CMD_DATA returned error %u\n", response);
return -1;
}
return 0;
}
int css_scp_boot_ready(void)
{
VERBOSE("Waiting for SCP to signal it is ready to go on\n");
/* Wait for SCP to signal it's ready */
return scpi_wait_ready();
}
|
606865.c | /*
* Copyright (c) 2018-2021, Arm Limited. All rights reserved.
*
* SPDX-License-Identifier: BSD-3-Clause
*
*/
#include "tfm_crypto_defs.h"
#include "psa/crypto.h"
#include "tfm_ns_interface.h"
#include "psa_manifest/sid.h"
#include "psa/client.h"
#define API_DISPATCH(sfn_name, sfn_id) \
psa_call(TFM_CRYPTO_HANDLE, PSA_IPC_CALL, \
in_vec, IOVEC_LEN(in_vec), \
out_vec, IOVEC_LEN(out_vec))
#define API_DISPATCH_NO_OUTVEC(sfn_name, sfn_id) \
psa_call(TFM_CRYPTO_HANDLE, PSA_IPC_CALL, \
in_vec, IOVEC_LEN(in_vec), \
(psa_outvec *)NULL, 0)
psa_status_t psa_crypto_init(void)
{
/* Service init is performed during TFM boot up,
* so application level initialisation is empty
*/
return PSA_SUCCESS;
}
psa_status_t psa_open_key(psa_key_id_t id,
psa_key_id_t *key)
{
psa_status_t status;
const struct tfm_crypto_pack_iovec iov = {
.sfn_id = TFM_CRYPTO_OPEN_KEY_SID,
};
psa_invec in_vec[] = {
{.base = &iov, .len = sizeof(struct tfm_crypto_pack_iovec)},
{.base = &id, .len = sizeof(psa_key_id_t)},
};
psa_outvec out_vec[] = {
{.base = key, .len = sizeof(psa_key_id_t)},
};
status = API_DISPATCH(tfm_crypto_open_key,
TFM_CRYPTO_OPEN_KEY);
return status;
}
psa_status_t psa_close_key(psa_key_id_t key)
{
psa_status_t status;
const struct tfm_crypto_pack_iovec iov = {
.sfn_id = TFM_CRYPTO_CLOSE_KEY_SID,
.key_id = key,
};
psa_invec in_vec[] = {
{.base = &iov, .len = sizeof(struct tfm_crypto_pack_iovec)},
};
status = API_DISPATCH_NO_OUTVEC(tfm_crypto_close_key,
TFM_CRYPTO_CLOSE_KEY);;
return status;
}
psa_status_t psa_import_key(const psa_key_attributes_t *attributes,
const uint8_t *data,
size_t data_length,
psa_key_id_t *key)
{
psa_status_t status;
struct tfm_crypto_pack_iovec iov = {
.sfn_id = TFM_CRYPTO_IMPORT_KEY_SID,
};
psa_invec in_vec[] = {
{.base = &iov, .len = sizeof(struct tfm_crypto_pack_iovec)},
{.base = attributes, .len = sizeof(psa_key_attributes_t)},
{.base = data, .len = data_length}
};
psa_outvec out_vec[] = {
{.base = key, .len = sizeof(psa_key_id_t)}
};
status = API_DISPATCH(tfm_crypto_import_key,
TFM_CRYPTO_IMPORT_KEY);
return status;
}
psa_status_t psa_destroy_key(psa_key_id_t key)
{
psa_status_t status;
struct tfm_crypto_pack_iovec iov = {
.sfn_id = TFM_CRYPTO_DESTROY_KEY_SID,
.key_id = key,
};
psa_invec in_vec[] = {
{.base = &iov, .len = sizeof(struct tfm_crypto_pack_iovec)},
};
status = API_DISPATCH_NO_OUTVEC(tfm_crypto_destroy_key,
TFM_CRYPTO_DESTROY_KEY);
return status;
}
psa_status_t psa_get_key_attributes(psa_key_id_t key,
psa_key_attributes_t *attributes)
{
psa_status_t status;
struct tfm_crypto_pack_iovec iov = {
.sfn_id = TFM_CRYPTO_GET_KEY_ATTRIBUTES_SID,
.key_id = key,
};
psa_invec in_vec[] = {
{.base = &iov, .len = sizeof(struct tfm_crypto_pack_iovec)},
};
psa_outvec out_vec[] = {
{.base = attributes, .len = sizeof(psa_key_attributes_t)},
};
status = API_DISPATCH(tfm_crypto_get_key_attributes,
TFM_CRYPTO_GET_KEY_ATTRIBUTES);
return status;
}
void psa_reset_key_attributes(psa_key_attributes_t *attributes)
{
struct tfm_crypto_pack_iovec iov = {
.sfn_id = TFM_CRYPTO_RESET_KEY_ATTRIBUTES_SID,
};
psa_invec in_vec[] = {
{.base = &iov, .len = sizeof(struct tfm_crypto_pack_iovec)},
};
psa_outvec out_vec[] = {
{.base = attributes, .len = sizeof(psa_key_attributes_t)},
};
(void)API_DISPATCH(tfm_crypto_reset_key_attributes,
TFM_CRYPTO_RESET_KEY_ATTRIBUTES);
return;
}
psa_status_t psa_export_key(psa_key_id_t key,
uint8_t *data,
size_t data_size,
size_t *data_length)
{
psa_status_t status;
struct tfm_crypto_pack_iovec iov = {
.sfn_id = TFM_CRYPTO_EXPORT_KEY_SID,
.key_id = key,
};
psa_invec in_vec[] = {
{.base = &iov, .len = sizeof(struct tfm_crypto_pack_iovec)},
};
psa_outvec out_vec[] = {
{.base = data, .len = data_size}
};
status = API_DISPATCH(tfm_crypto_export_key,
TFM_CRYPTO_EXPORT_KEY);
*data_length = out_vec[0].len;
return status;
}
psa_status_t psa_export_public_key(psa_key_id_t key,
uint8_t *data,
size_t data_size,
size_t *data_length)
{
psa_status_t status;
struct tfm_crypto_pack_iovec iov = {
.sfn_id = TFM_CRYPTO_EXPORT_PUBLIC_KEY_SID,
.key_id = key,
};
psa_invec in_vec[] = {
{.base = &iov, .len = sizeof(struct tfm_crypto_pack_iovec)},
};
psa_outvec out_vec[] = {
{.base = data, .len = data_size}
};
status = API_DISPATCH(tfm_crypto_export_public_key,
TFM_CRYPTO_EXPORT_PUBLIC_KEY);
*data_length = out_vec[0].len;
return status;
}
psa_status_t psa_purge_key(psa_key_id_t key)
{
psa_status_t status;
struct tfm_crypto_pack_iovec iov = {
.sfn_id = TFM_CRYPTO_PURGE_KEY_SID,
.key_id = key,
};
psa_invec in_vec[] = {
{.base = &iov, .len = sizeof(struct tfm_crypto_pack_iovec)},
};
status = API_DISPATCH_NO_OUTVEC(tfm_crypto_purge_key,
TFM_CRYPTO_PURGE_KEY);
return status;
}
psa_status_t psa_copy_key(psa_key_id_t source_key,
const psa_key_attributes_t *attributes,
psa_key_id_t *target_key)
{
psa_status_t status;
struct tfm_crypto_pack_iovec iov = {
.sfn_id = TFM_CRYPTO_COPY_KEY_SID,
.key_id = source_key,
};
psa_invec in_vec[] = {
{.base = &iov, .len = sizeof(struct tfm_crypto_pack_iovec)},
{.base = attributes, .len = sizeof(psa_key_attributes_t)},
};
psa_outvec out_vec[] = {
{.base = target_key, .len = sizeof(psa_key_id_t)},
};
status = API_DISPATCH(tfm_crypto_copy_key,
TFM_CRYPTO_COPY_KEY);
return status;
}
psa_status_t psa_cipher_generate_iv(psa_cipher_operation_t *operation,
unsigned char *iv,
size_t iv_size,
size_t *iv_length)
{
psa_status_t status;
struct tfm_crypto_pack_iovec iov = {
.sfn_id = TFM_CRYPTO_CIPHER_GENERATE_IV_SID,
.op_handle = operation->handle,
};
psa_invec in_vec[] = {
{.base = &iov, .len = sizeof(struct tfm_crypto_pack_iovec)},
};
psa_outvec out_vec[] = {
{.base = &(operation->handle), .len = sizeof(uint32_t)},
{.base = iv, .len = iv_size},
};
status = API_DISPATCH(tfm_crypto_cipher_generate_iv,
TFM_CRYPTO_CIPHER_GENERATE_IV);
*iv_length = out_vec[1].len;
return status;
}
psa_status_t psa_cipher_set_iv(psa_cipher_operation_t *operation,
const unsigned char *iv,
size_t iv_length)
{
psa_status_t status;
struct tfm_crypto_pack_iovec iov = {
.sfn_id = TFM_CRYPTO_CIPHER_SET_IV_SID,
.op_handle = operation->handle,
};
psa_invec in_vec[] = {
{.base = &iov, .len = sizeof(struct tfm_crypto_pack_iovec)},
{.base = iv, .len = iv_length},
};
psa_outvec out_vec[] = {
{.base = &(operation->handle), .len = sizeof(uint32_t)},
};
status = API_DISPATCH(tfm_crypto_cipher_set_iv,
TFM_CRYPTO_CIPHER_SET_IV);
return status;
}
psa_status_t psa_cipher_encrypt_setup(psa_cipher_operation_t *operation,
psa_key_id_t key,
psa_algorithm_t alg)
{
psa_status_t status;
struct tfm_crypto_pack_iovec iov = {
.sfn_id = TFM_CRYPTO_CIPHER_ENCRYPT_SETUP_SID,
.key_id = key,
.alg = alg,
.op_handle = operation->handle,
};
psa_invec in_vec[] = {
{.base = &iov, .len = sizeof(struct tfm_crypto_pack_iovec)},
};
psa_outvec out_vec[] = {
{.base = &(operation->handle), .len = sizeof(uint32_t)},
};
status = API_DISPATCH(tfm_crypto_cipher_encrypt_setup,
TFM_CRYPTO_CIPHER_ENCRYPT_SETUP);
return status;
}
psa_status_t psa_cipher_decrypt_setup(psa_cipher_operation_t *operation,
psa_key_id_t key,
psa_algorithm_t alg)
{
psa_status_t status;
struct tfm_crypto_pack_iovec iov = {
.sfn_id = TFM_CRYPTO_CIPHER_DECRYPT_SETUP_SID,
.key_id = key,
.alg = alg,
.op_handle = operation->handle,
};
psa_invec in_vec[] = {
{.base = &iov, .len = sizeof(struct tfm_crypto_pack_iovec)},
};
psa_outvec out_vec[] = {
{.base = &(operation->handle), .len = sizeof(uint32_t)},
};
status = API_DISPATCH(tfm_crypto_cipher_decrypt_setup,
TFM_CRYPTO_CIPHER_DECRYPT_SETUP);
return status;
}
psa_status_t psa_cipher_update(psa_cipher_operation_t *operation,
const uint8_t *input,
size_t input_length,
unsigned char *output,
size_t output_size,
size_t *output_length)
{
psa_status_t status;
struct tfm_crypto_pack_iovec iov = {
.sfn_id = TFM_CRYPTO_CIPHER_UPDATE_SID,
.op_handle = operation->handle,
};
psa_invec in_vec[] = {
{.base = &iov, .len = sizeof(struct tfm_crypto_pack_iovec)},
{.base = input, .len = input_length},
};
psa_outvec out_vec[] = {
{.base = &(operation->handle), .len = sizeof(uint32_t)},
{.base = output, .len = output_size}
};
status = API_DISPATCH(tfm_crypto_cipher_update,
TFM_CRYPTO_CIPHER_UPDATE);
*output_length = out_vec[1].len;
return status;
}
psa_status_t psa_cipher_abort(psa_cipher_operation_t *operation)
{
psa_status_t status;
struct tfm_crypto_pack_iovec iov = {
.sfn_id = TFM_CRYPTO_CIPHER_ABORT_SID,
.op_handle = operation->handle,
};
psa_invec in_vec[] = {
{.base = &iov, .len = sizeof(struct tfm_crypto_pack_iovec)},
};
psa_outvec out_vec[] = {
{.base = &(operation->handle), .len = sizeof(uint32_t)},
};
status = API_DISPATCH(tfm_crypto_cipher_abort,
TFM_CRYPTO_CIPHER_ABORT);
return status;
}
psa_status_t psa_cipher_finish(psa_cipher_operation_t *operation,
uint8_t *output,
size_t output_size,
size_t *output_length)
{
psa_status_t status;
struct tfm_crypto_pack_iovec iov = {
.sfn_id = TFM_CRYPTO_CIPHER_FINISH_SID,
.op_handle = operation->handle,
};
psa_invec in_vec[] = {
{.base = &iov, .len = sizeof(struct tfm_crypto_pack_iovec)},
};
psa_outvec out_vec[] = {
{.base = &(operation->handle), .len = sizeof(uint32_t)},
{.base = output, .len = output_size},
};
status = API_DISPATCH(tfm_crypto_cipher_finish,
TFM_CRYPTO_CIPHER_FINISH);
*output_length = out_vec[1].len;
return status;
}
psa_status_t psa_hash_setup(psa_hash_operation_t *operation,
psa_algorithm_t alg)
{
psa_status_t status;
struct tfm_crypto_pack_iovec iov = {
.sfn_id = TFM_CRYPTO_HASH_SETUP_SID,
.alg = alg,
.op_handle = operation->handle,
};
psa_invec in_vec[] = {
{.base = &iov, .len = sizeof(struct tfm_crypto_pack_iovec)},
};
psa_outvec out_vec[] = {
{.base = &(operation->handle), .len = sizeof(uint32_t)},
};
status = API_DISPATCH(tfm_crypto_hash_setup,
TFM_CRYPTO_HASH_SETUP);
return status;
}
psa_status_t psa_hash_update(psa_hash_operation_t *operation,
const uint8_t *input,
size_t input_length)
{
psa_status_t status;
struct tfm_crypto_pack_iovec iov = {
.sfn_id = TFM_CRYPTO_HASH_UPDATE_SID,
.op_handle = operation->handle,
};
psa_invec in_vec[] = {
{.base = &iov, .len = sizeof(struct tfm_crypto_pack_iovec)},
{.base = input, .len = input_length},
};
psa_outvec out_vec[] = {
{.base = &(operation->handle), .len = sizeof(uint32_t)},
};
status = API_DISPATCH(tfm_crypto_hash_update,
TFM_CRYPTO_HASH_UPDATE);
return status;
}
psa_status_t psa_hash_finish(psa_hash_operation_t *operation,
uint8_t *hash,
size_t hash_size,
size_t *hash_length)
{
psa_status_t status;
struct tfm_crypto_pack_iovec iov = {
.sfn_id = TFM_CRYPTO_HASH_FINISH_SID,
.op_handle = operation->handle,
};
psa_invec in_vec[] = {
{.base = &iov, .len = sizeof(struct tfm_crypto_pack_iovec)},
};
psa_outvec out_vec[] = {
{.base = &(operation->handle), .len = sizeof(uint32_t)},
{.base = hash, .len = hash_size},
};
status = API_DISPATCH(tfm_crypto_hash_finish,
TFM_CRYPTO_HASH_FINISH);
*hash_length = out_vec[1].len;
return status;
}
psa_status_t psa_hash_verify(psa_hash_operation_t *operation,
const uint8_t *hash,
size_t hash_length)
{
psa_status_t status;
struct tfm_crypto_pack_iovec iov = {
.sfn_id = TFM_CRYPTO_HASH_VERIFY_SID,
.op_handle = operation->handle,
};
psa_invec in_vec[] = {
{.base = &iov, .len = sizeof(struct tfm_crypto_pack_iovec)},
{.base = hash, .len = hash_length},
};
psa_outvec out_vec[] = {
{.base = &(operation->handle), .len = sizeof(uint32_t)},
};
status = API_DISPATCH(tfm_crypto_hash_verify,
TFM_CRYPTO_HASH_VERIFY);
return status;
}
psa_status_t psa_hash_abort(psa_hash_operation_t *operation)
{
psa_status_t status;
struct tfm_crypto_pack_iovec iov = {
.sfn_id = TFM_CRYPTO_HASH_ABORT_SID,
.op_handle = operation->handle,
};
psa_invec in_vec[] = {
{.base = &iov, .len = sizeof(struct tfm_crypto_pack_iovec)},
};
psa_outvec out_vec[] = {
{.base = &(operation->handle), .len = sizeof(uint32_t)},
};
status = API_DISPATCH(tfm_crypto_hash_abort,
TFM_CRYPTO_HASH_ABORT);
return status;
}
psa_status_t psa_hash_clone(const psa_hash_operation_t *source_operation,
psa_hash_operation_t *target_operation)
{
psa_status_t status;
struct tfm_crypto_pack_iovec iov = {
.sfn_id = TFM_CRYPTO_HASH_CLONE_SID,
.op_handle = source_operation->handle,
};
psa_invec in_vec[] = {
{.base = &iov, .len = sizeof(struct tfm_crypto_pack_iovec)},
};
psa_outvec out_vec[] = {
{.base = target_operation, .len = sizeof(psa_hash_operation_t)},
};
if (target_operation && (target_operation->handle != 0)) {
return PSA_ERROR_BAD_STATE;
}
status = API_DISPATCH(tfm_crypto_hash_clone,
TFM_CRYPTO_HASH_CLONE);
return status;
}
psa_status_t psa_hash_compute(psa_algorithm_t alg,
const uint8_t *input,
size_t input_length,
uint8_t *hash,
size_t hash_size,
size_t *hash_length)
{
psa_status_t status;
struct tfm_crypto_pack_iovec iov = {
.sfn_id = TFM_CRYPTO_HASH_COMPUTE_SID,
.alg = alg,
};
psa_invec in_vec[] = {
{.base = &iov, .len = sizeof(struct tfm_crypto_pack_iovec)},
{.base = input, .len = input_length},
};
psa_outvec out_vec[] = {
{.base = hash, .len = hash_size}
};
status = API_DISPATCH(tfm_crypto_hash_compute,
TFM_CRYPTO_HASH_COMPUTE);
*hash_length = out_vec[0].len;
return status;
}
psa_status_t psa_hash_compare(psa_algorithm_t alg,
const uint8_t *input,
size_t input_length,
const uint8_t *hash,
size_t hash_length)
{
psa_status_t status;
struct tfm_crypto_pack_iovec iov = {
.sfn_id = TFM_CRYPTO_HASH_COMPARE_SID,
.alg = alg,
};
psa_invec in_vec[] = {
{.base = &iov, .len = sizeof(struct tfm_crypto_pack_iovec)},
{.base = input, .len = input_length},
{.base = hash, .len = hash_length},
};
status = API_DISPATCH_NO_OUTVEC(tfm_crypto_hash_compare,
TFM_CRYPTO_HASH_COMPARE);
return status;
}
psa_status_t psa_mac_sign_setup(psa_mac_operation_t *operation,
psa_key_id_t key,
psa_algorithm_t alg)
{
psa_status_t status;
struct tfm_crypto_pack_iovec iov = {
.sfn_id = TFM_CRYPTO_MAC_SIGN_SETUP_SID,
.key_id = key,
.alg = alg,
.op_handle = operation->handle,
};
psa_invec in_vec[] = {
{.base = &iov, .len = sizeof(struct tfm_crypto_pack_iovec)},
};
psa_outvec out_vec[] = {
{.base = &(operation->handle), .len = sizeof(uint32_t)},
};
status = API_DISPATCH(tfm_crypto_mac_sign_setup,
TFM_CRYPTO_MAC_SIGN_SETUP);
return status;
}
psa_status_t psa_mac_verify_setup(psa_mac_operation_t *operation,
psa_key_id_t key,
psa_algorithm_t alg)
{
psa_status_t status;
struct tfm_crypto_pack_iovec iov = {
.sfn_id = TFM_CRYPTO_MAC_VERIFY_SETUP_SID,
.key_id = key,
.alg = alg,
.op_handle = operation->handle,
};
psa_invec in_vec[] = {
{.base = &iov, .len = sizeof(struct tfm_crypto_pack_iovec)},
};
psa_outvec out_vec[] = {
{.base = &(operation->handle), .len = sizeof(uint32_t)},
};
status = API_DISPATCH(tfm_crypto_mac_verify_setup,
TFM_CRYPTO_MAC_VERIFY_SETUP);
return status;
}
psa_status_t psa_mac_update(psa_mac_operation_t *operation,
const uint8_t *input,
size_t input_length)
{
psa_status_t status;
struct tfm_crypto_pack_iovec iov = {
.sfn_id = TFM_CRYPTO_MAC_UPDATE_SID,
.op_handle = operation->handle,
};
psa_invec in_vec[] = {
{.base = &iov, .len = sizeof(struct tfm_crypto_pack_iovec)},
{.base = input, .len = input_length},
};
psa_outvec out_vec[] = {
{.base = &(operation->handle), .len = sizeof(uint32_t)},
};
status = API_DISPATCH(tfm_crypto_mac_update,
TFM_CRYPTO_MAC_UPDATE);
return status;
}
psa_status_t psa_mac_sign_finish(psa_mac_operation_t *operation,
uint8_t *mac,
size_t mac_size,
size_t *mac_length)
{
psa_status_t status;
struct tfm_crypto_pack_iovec iov = {
.sfn_id = TFM_CRYPTO_MAC_SIGN_FINISH_SID,
.op_handle = operation->handle,
};
psa_invec in_vec[] = {
{.base = &iov, .len = sizeof(struct tfm_crypto_pack_iovec)},
};
psa_outvec out_vec[] = {
{.base = &(operation->handle), .len = sizeof(uint32_t)},
{.base = mac, .len = mac_size},
};
status = API_DISPATCH(tfm_crypto_mac_sign_finish,
TFM_CRYPTO_MAC_SIGN_FINISH);
*mac_length = out_vec[1].len;
return status;
}
psa_status_t psa_mac_verify_finish(psa_mac_operation_t *operation,
const uint8_t *mac,
size_t mac_length)
{
psa_status_t status;
struct tfm_crypto_pack_iovec iov = {
.sfn_id = TFM_CRYPTO_MAC_VERIFY_FINISH_SID,
.op_handle = operation->handle,
};
psa_invec in_vec[] = {
{.base = &iov, .len = sizeof(struct tfm_crypto_pack_iovec)},
{.base = mac, .len = mac_length},
};
psa_outvec out_vec[] = {
{.base = &(operation->handle), .len = sizeof(uint32_t)},
};
status = API_DISPATCH(tfm_crypto_mac_verify_finish,
TFM_CRYPTO_MAC_VERIFY_FINISH);
return status;
}
psa_status_t psa_mac_abort(psa_mac_operation_t *operation)
{
psa_status_t status;
struct tfm_crypto_pack_iovec iov = {
.sfn_id = TFM_CRYPTO_MAC_ABORT_SID,
.op_handle = operation->handle,
};
psa_invec in_vec[] = {
{.base = &iov, .len = sizeof(struct tfm_crypto_pack_iovec)},
};
psa_outvec out_vec[] = {
{.base = &(operation->handle), .len = sizeof(uint32_t)},
};
status = API_DISPATCH(tfm_crypto_mac_abort,
TFM_CRYPTO_MAC_ABORT);
return status;
}
psa_status_t psa_aead_encrypt(psa_key_id_t key,
psa_algorithm_t alg,
const uint8_t *nonce,
size_t nonce_length,
const uint8_t *additional_data,
size_t additional_data_length,
const uint8_t *plaintext,
size_t plaintext_length,
uint8_t *ciphertext,
size_t ciphertext_size,
size_t *ciphertext_length)
{
psa_status_t status;
struct tfm_crypto_pack_iovec iov = {
.sfn_id = TFM_CRYPTO_AEAD_ENCRYPT_SID,
.key_id = key,
.alg = alg,
.aead_in = {.nonce = {0}, .nonce_length = nonce_length}
};
/* Sanitize the optional input */
if ((additional_data == NULL) && (additional_data_length != 0)) {
return PSA_ERROR_INVALID_ARGUMENT;
}
size_t idx = 0;
psa_invec in_vec[] = {
{.base = &iov, .len = sizeof(struct tfm_crypto_pack_iovec)},
{.base = plaintext, .len = plaintext_length},
{.base = additional_data, .len = additional_data_length},
};
psa_outvec out_vec[] = {
{.base = ciphertext, .len = ciphertext_size},
};
if (nonce_length > TFM_CRYPTO_MAX_NONCE_LENGTH) {
return PSA_ERROR_INVALID_ARGUMENT;
}
if (nonce != NULL) {
for (idx = 0; idx < nonce_length; idx++) {
iov.aead_in.nonce[idx] = nonce[idx];
}
}
size_t in_len = IOVEC_LEN(in_vec);
if (additional_data == NULL) {
in_len--;
}
status = psa_call(TFM_CRYPTO_HANDLE, PSA_IPC_CALL, in_vec, in_len,
out_vec, IOVEC_LEN(out_vec));
*ciphertext_length = out_vec[0].len;
return status;
}
psa_status_t psa_aead_decrypt(psa_key_id_t key,
psa_algorithm_t alg,
const uint8_t *nonce,
size_t nonce_length,
const uint8_t *additional_data,
size_t additional_data_length,
const uint8_t *ciphertext,
size_t ciphertext_length,
uint8_t *plaintext,
size_t plaintext_size,
size_t *plaintext_length)
{
psa_status_t status;
struct tfm_crypto_pack_iovec iov = {
.sfn_id = TFM_CRYPTO_AEAD_DECRYPT_SID,
.key_id = key,
.alg = alg,
.aead_in = {.nonce = {0}, .nonce_length = nonce_length}
};
/* Sanitize the optional input */
if ((additional_data == NULL) && (additional_data_length != 0)) {
return PSA_ERROR_INVALID_ARGUMENT;
}
size_t idx = 0;
psa_invec in_vec[] = {
{.base = &iov, .len = sizeof(struct tfm_crypto_pack_iovec)},
{.base = ciphertext, .len = ciphertext_length},
{.base = additional_data, .len = additional_data_length},
};
psa_outvec out_vec[] = {
{.base = plaintext, .len = plaintext_size},
};
if (nonce_length > TFM_CRYPTO_MAX_NONCE_LENGTH) {
return PSA_ERROR_INVALID_ARGUMENT;
}
if (nonce != NULL) {
for (idx = 0; idx < nonce_length; idx++) {
iov.aead_in.nonce[idx] = nonce[idx];
}
}
size_t in_len = IOVEC_LEN(in_vec);
if (additional_data == NULL) {
in_len--;
}
status = psa_call(TFM_CRYPTO_HANDLE, PSA_IPC_CALL, in_vec, in_len,
out_vec, IOVEC_LEN(out_vec));
*plaintext_length = out_vec[0].len;
return status;
}
psa_status_t psa_sign_message(psa_key_id_t key,
psa_algorithm_t alg,
const uint8_t *input,
size_t input_length,
uint8_t *signature,
size_t signature_size,
size_t *signature_length)
{
psa_status_t status;
struct tfm_crypto_pack_iovec iov = {
.sfn_id = TFM_CRYPTO_SIGN_MESSAGE_SID,
.key_id = key,
.alg = alg,
};
psa_invec in_vec[] = {
{.base = &iov, .len = sizeof(struct tfm_crypto_pack_iovec)},
{.base = input, .len = input_length},
};
psa_outvec out_vec[] = {
{.base = signature, .len = signature_size},
};
status = API_DISPATCH(tfm_crypto_sign_message,
TFM_CRYPTO_SIGN_MESSAGE);
if (status == PSA_SUCCESS) {
*signature_length = out_vec[0].len;
}
return status;
}
psa_status_t psa_verify_message(psa_key_id_t key,
psa_algorithm_t alg,
const uint8_t *input,
size_t input_length,
const uint8_t *signature,
size_t signature_length)
{
psa_status_t status;
struct tfm_crypto_pack_iovec iov = {
.sfn_id = TFM_CRYPTO_VERIFY_MESSAGE_SID,
.key_id = key,
.alg = alg
};
psa_invec in_vec[] = {
{.base = &iov, .len = sizeof(struct tfm_crypto_pack_iovec)},
{.base = input, .len = input_length},
{.base = signature, .len = signature_length}
};
status = API_DISPATCH_NO_OUTVEC(tfm_crypto_verify_message,
TFM_CRYPTO_VERIFY_MESSAGE);
return status;
}
psa_status_t psa_sign_hash(psa_key_id_t key,
psa_algorithm_t alg,
const uint8_t *hash,
size_t hash_length,
uint8_t *signature,
size_t signature_size,
size_t *signature_length)
{
psa_status_t status;
struct tfm_crypto_pack_iovec iov = {
.sfn_id = TFM_CRYPTO_SIGN_HASH_SID,
.key_id = key,
.alg = alg,
};
psa_invec in_vec[] = {
{.base = &iov, .len = sizeof(struct tfm_crypto_pack_iovec)},
{.base = hash, .len = hash_length},
};
psa_outvec out_vec[] = {
{.base = signature, .len = signature_size},
};
status = API_DISPATCH(tfm_crypto_sign_hash,
TFM_CRYPTO_SIGN_HASH);
*signature_length = out_vec[0].len;
return status;
}
psa_status_t psa_verify_hash(psa_key_id_t key,
psa_algorithm_t alg,
const uint8_t *hash,
size_t hash_length,
const uint8_t *signature,
size_t signature_length)
{
psa_status_t status;
struct tfm_crypto_pack_iovec iov = {
.sfn_id = TFM_CRYPTO_VERIFY_HASH_SID,
.key_id = key,
.alg = alg
};
psa_invec in_vec[] = {
{.base = &iov, .len = sizeof(struct tfm_crypto_pack_iovec)},
{.base = hash, .len = hash_length},
{.base = signature, .len = signature_length}
};
status = API_DISPATCH_NO_OUTVEC(tfm_crypto_verify_hash,
TFM_CRYPTO_VERIFY_HASH);
return status;
}
psa_status_t psa_asymmetric_encrypt(psa_key_id_t key,
psa_algorithm_t alg,
const uint8_t *input,
size_t input_length,
const uint8_t *salt,
size_t salt_length,
uint8_t *output,
size_t output_size,
size_t *output_length)
{
psa_status_t status;
struct tfm_crypto_pack_iovec iov = {
.sfn_id = TFM_CRYPTO_ASYMMETRIC_ENCRYPT_SID,
.key_id = key,
.alg = alg
};
/* Sanitize the optional input */
if ((salt == NULL) && (salt_length != 0)) {
return PSA_ERROR_INVALID_ARGUMENT;
}
psa_invec in_vec[] = {
{.base = &iov, .len = sizeof(struct tfm_crypto_pack_iovec)},
{.base = input, .len = input_length},
{.base = salt, .len = salt_length}
};
psa_outvec out_vec[] = {
{.base = output, .len = output_size},
};
size_t in_len = IOVEC_LEN(in_vec);
if (salt == NULL) {
in_len--;
}
status = psa_call(TFM_CRYPTO_HANDLE, PSA_IPC_CALL, in_vec, in_len,
out_vec, IOVEC_LEN(out_vec));
*output_length = out_vec[0].len;
return status;
}
psa_status_t psa_asymmetric_decrypt(psa_key_id_t key,
psa_algorithm_t alg,
const uint8_t *input,
size_t input_length,
const uint8_t *salt,
size_t salt_length,
uint8_t *output,
size_t output_size,
size_t *output_length)
{
psa_status_t status;
struct tfm_crypto_pack_iovec iov = {
.sfn_id = TFM_CRYPTO_ASYMMETRIC_DECRYPT_SID,
.key_id = key,
.alg = alg
};
/* Sanitize the optional input */
if ((salt == NULL) && (salt_length != 0)) {
return PSA_ERROR_INVALID_ARGUMENT;
}
psa_invec in_vec[] = {
{.base = &iov, .len = sizeof(struct tfm_crypto_pack_iovec)},
{.base = input, .len = input_length},
{.base = salt, .len = salt_length}
};
psa_outvec out_vec[] = {
{.base = output, .len = output_size},
};
size_t in_len = IOVEC_LEN(in_vec);
if (salt == NULL) {
in_len--;
}
status = psa_call(TFM_CRYPTO_HANDLE, PSA_IPC_CALL, in_vec, in_len,
out_vec, IOVEC_LEN(out_vec));
*output_length = out_vec[0].len;
return status;
}
psa_status_t psa_key_derivation_get_capacity(
const psa_key_derivation_operation_t *operation,
size_t *capacity)
{
psa_status_t status;
struct tfm_crypto_pack_iovec iov = {
.sfn_id = TFM_CRYPTO_KEY_DERIVATION_GET_CAPACITY_SID,
.op_handle = operation->handle,
};
psa_invec in_vec[] = {
{.base = &iov, .len = sizeof(struct tfm_crypto_pack_iovec)},
};
psa_outvec out_vec[] = {
{.base = capacity, .len = sizeof(size_t)},
};
status = API_DISPATCH(tfm_crypto_key_derivation_get_capacity,
TFM_CRYPTO_KEY_DERIVATION_GET_CAPACITY);
return status;
}
psa_status_t psa_key_derivation_output_bytes(
psa_key_derivation_operation_t *operation,
uint8_t *output,
size_t output_length)
{
psa_status_t status;
struct tfm_crypto_pack_iovec iov = {
.sfn_id = TFM_CRYPTO_KEY_DERIVATION_OUTPUT_BYTES_SID,
.op_handle = operation->handle,
};
psa_invec in_vec[] = {
{.base = &iov, .len = sizeof(struct tfm_crypto_pack_iovec)},
};
psa_outvec out_vec[] = {
{.base = output, .len = output_length},
};
status = API_DISPATCH(tfm_crypto_key_derivation_output_bytes,
TFM_CRYPTO_KEY_DERIVATION_OUTPUT_BYTES);
return status;
}
psa_status_t psa_key_derivation_input_key(
psa_key_derivation_operation_t *operation,
psa_key_derivation_step_t step,
psa_key_id_t key)
{
psa_status_t status;
struct tfm_crypto_pack_iovec iov = {
.sfn_id = TFM_CRYPTO_KEY_DERIVATION_INPUT_KEY_SID,
.key_id = key,
.step = step,
.op_handle = operation->handle,
};
psa_invec in_vec[] = {
{.base = &iov, .len = sizeof(struct tfm_crypto_pack_iovec)},
};
status = API_DISPATCH_NO_OUTVEC(tfm_crypto_key_derivation_input_key,
TFM_CRYPTO_KEY_DERIVATION_INPUT_KEY);
return status;
}
psa_status_t psa_key_derivation_abort(
psa_key_derivation_operation_t *operation)
{
psa_status_t status;
struct tfm_crypto_pack_iovec iov = {
.sfn_id = TFM_CRYPTO_KEY_DERIVATION_ABORT_SID,
.op_handle = operation->handle,
};
psa_invec in_vec[] = {
{.base = &iov, .len = sizeof(struct tfm_crypto_pack_iovec)},
};
psa_outvec out_vec[] = {
{.base = &(operation->handle), .len = sizeof(uint32_t)},
};
status = API_DISPATCH(tfm_crypto_key_derivation_abort,
TFM_CRYPTO_KEY_DERIVATION_ABORT);
return status;
}
psa_status_t psa_key_derivation_key_agreement(
psa_key_derivation_operation_t *operation,
psa_key_derivation_step_t step,
psa_key_id_t private_key,
const uint8_t *peer_key,
size_t peer_key_length)
{
psa_status_t status;
struct tfm_crypto_pack_iovec iov = {
.sfn_id = TFM_CRYPTO_KEY_DERIVATION_KEY_AGREEMENT_SID,
.key_id = private_key,
.step = step,
.op_handle = operation->handle,
};
psa_invec in_vec[] = {
{.base = &iov, .len = sizeof(struct tfm_crypto_pack_iovec)},
{.base = peer_key, .len = peer_key_length},
};
status = API_DISPATCH_NO_OUTVEC(tfm_crypto_key_derivation_key_agreement,
TFM_CRYPTO_KEY_DERIVATION_KEY_AGREEMENT);
return status;
}
psa_status_t psa_generate_random(uint8_t *output,
size_t output_size)
{
psa_status_t status;
struct tfm_crypto_pack_iovec iov = {
.sfn_id = TFM_CRYPTO_GENERATE_RANDOM_SID,
};
psa_invec in_vec[] = {
{.base = &iov, .len = sizeof(struct tfm_crypto_pack_iovec)},
};
psa_outvec out_vec[] = {
{.base = output, .len = output_size},
};
if (output_size == 0) {
return PSA_SUCCESS;
}
status = API_DISPATCH(tfm_crypto_generate_random,
TFM_CRYPTO_GENERATE_RANDOM);
return status;
}
psa_status_t psa_generate_key(const psa_key_attributes_t *attributes,
psa_key_id_t *key)
{
psa_status_t status;
struct tfm_crypto_pack_iovec iov = {
.sfn_id = TFM_CRYPTO_GENERATE_KEY_SID,
};
psa_invec in_vec[] = {
{.base = &iov, .len = sizeof(struct tfm_crypto_pack_iovec)},
{.base = attributes, .len = sizeof(psa_key_attributes_t)},
};
psa_outvec out_vec[] = {
{.base = key, .len = sizeof(psa_key_id_t)},
};
status = API_DISPATCH(tfm_crypto_generate_key,
TFM_CRYPTO_GENERATE_KEY);
return status;
}
psa_status_t psa_aead_update_ad(psa_aead_operation_t *operation,
const uint8_t *input,
size_t input_length)
{
psa_status_t status;
status = PSA_ERROR_NOT_SUPPORTED;
return status;
}
psa_status_t psa_aead_finish(psa_aead_operation_t *operation,
uint8_t *ciphertext,
size_t ciphertext_size,
size_t *ciphertext_length,
uint8_t *tag,
size_t tag_size,
size_t *tag_length)
{
psa_status_t status;
status = PSA_ERROR_NOT_SUPPORTED;
return status;
}
psa_status_t psa_aead_verify(psa_aead_operation_t *operation,
uint8_t *plaintext,
size_t plaintext_size,
size_t *plaintext_length,
const uint8_t *tag,
size_t tag_length)
{
psa_status_t status;
status = PSA_ERROR_NOT_SUPPORTED;
return status;
}
psa_status_t psa_aead_abort(psa_aead_operation_t *operation)
{
psa_status_t status;
status = PSA_ERROR_NOT_SUPPORTED;
return status;
}
psa_status_t psa_mac_compute(psa_key_id_t key,
psa_algorithm_t alg,
const uint8_t *input,
size_t input_length,
uint8_t *mac,
size_t mac_size,
size_t *mac_length)
{
psa_status_t status;
struct tfm_crypto_pack_iovec iov = {
.sfn_id = TFM_CRYPTO_MAC_COMPUTE_SID,
.key_id = key,
.alg = alg,
};
psa_invec in_vec[] = {
{.base = &iov, .len = sizeof(struct tfm_crypto_pack_iovec)},
{.base = input, .len = input_length},
};
psa_outvec out_vec[] = {
{.base = mac, .len = mac_size},
};
status = API_DISPATCH(tfm_crypto_mac_compute,
TFM_CRYPTO_MAC_COMPUTE);
if (status == PSA_SUCCESS) {
*mac_length = out_vec[0].len;
}
return status;
}
psa_status_t psa_mac_verify(psa_key_id_t key,
psa_algorithm_t alg,
const uint8_t *input,
size_t input_length,
const uint8_t *mac,
const size_t mac_length)
{
psa_status_t status;
struct tfm_crypto_pack_iovec iov = {
.sfn_id = TFM_CRYPTO_MAC_VERIFY_SID,
.key_id = key,
.alg = alg,
};
psa_invec in_vec[] = {
{.base = &iov, .len = sizeof(struct tfm_crypto_pack_iovec)},
{.base = input, .len = input_length},
{.base = mac, .len = mac_length},
};
status = API_DISPATCH_NO_OUTVEC(tfm_crypto_mac_verify,
TFM_CRYPTO_MAC_VERIFY);
return status;
}
psa_status_t psa_cipher_encrypt(psa_key_id_t key,
psa_algorithm_t alg,
const uint8_t *input,
size_t input_length,
uint8_t *output,
size_t output_size,
size_t *output_length)
{
psa_status_t status;
struct tfm_crypto_pack_iovec iov = {
.sfn_id = TFM_CRYPTO_CIPHER_ENCRYPT_SID,
.key_id = key,
.alg = alg,
};
psa_invec in_vec[] = {
{.base = &iov, .len = sizeof(struct tfm_crypto_pack_iovec)},
{.base = input, .len = input_length},
};
psa_outvec out_vec[] = {
{.base = output, .len = output_size}
};
status = API_DISPATCH(tfm_crypto_cipher_encrypt,
TFM_CRYPTO_CIPHER_ENCRYPT);
if (status == PSA_SUCCESS) {
*output_length = out_vec[0].len;
}
return status;
}
psa_status_t psa_cipher_decrypt(psa_key_id_t key,
psa_algorithm_t alg,
const uint8_t *input,
size_t input_length,
uint8_t *output,
size_t output_size,
size_t *output_length)
{
psa_status_t status;
struct tfm_crypto_pack_iovec iov = {
.sfn_id = TFM_CRYPTO_CIPHER_DECRYPT_SID,
.key_id = key,
.alg = alg,
};
psa_invec in_vec[] = {
{.base = &iov, .len = sizeof(struct tfm_crypto_pack_iovec)},
{.base = input, .len = input_length},
};
psa_outvec out_vec[] = {
{.base = output, .len = output_size}
};
status = API_DISPATCH(tfm_crypto_cipher_decrypt,
TFM_CRYPTO_CIPHER_DECRYPT);
if (status == PSA_SUCCESS) {
*output_length = out_vec[0].len;
}
return status;
}
psa_status_t psa_raw_key_agreement(psa_algorithm_t alg,
psa_key_id_t private_key,
const uint8_t *peer_key,
size_t peer_key_length,
uint8_t *output,
size_t output_size,
size_t *output_length)
{
psa_status_t status;
struct tfm_crypto_pack_iovec iov = {
.sfn_id = TFM_CRYPTO_RAW_KEY_AGREEMENT_SID,
.alg = alg,
.key_id = private_key
};
psa_invec in_vec[] = {
{.base = &iov, .len = sizeof(struct tfm_crypto_pack_iovec)},
{.base = peer_key, .len = peer_key_length},
};
psa_outvec out_vec[] = {
{.base = output, .len = output_size},
};
status = API_DISPATCH(tfm_crypto_raw_key_agreement,
TFM_CRYPTO_RAW_KEY_AGREEMENT);
*output_length = out_vec[0].len;
return status;
}
psa_status_t psa_key_derivation_setup(psa_key_derivation_operation_t *operation,
psa_algorithm_t alg)
{
psa_status_t status;
struct tfm_crypto_pack_iovec iov = {
.sfn_id = TFM_CRYPTO_KEY_DERIVATION_SETUP_SID,
.alg = alg,
.op_handle = operation->handle,
};
psa_invec in_vec[] = {
{.base = &iov, .len = sizeof(struct tfm_crypto_pack_iovec)},
};
psa_outvec out_vec[] = {
{.base = &(operation->handle), .len = sizeof(uint32_t)},
};
status = API_DISPATCH(tfm_crypto_key_derivation_setup,
TFM_CRYPTO_KEY_DERIVATION_SETUP);
return status;
}
psa_status_t psa_key_derivation_set_capacity(
psa_key_derivation_operation_t *operation,
size_t capacity)
{
psa_status_t status;
struct tfm_crypto_pack_iovec iov = {
.sfn_id = TFM_CRYPTO_KEY_DERIVATION_SET_CAPACITY_SID,
.capacity = capacity,
.op_handle = operation->handle,
};
psa_invec in_vec[] = {
{.base = &iov, .len = sizeof(struct tfm_crypto_pack_iovec)},
};
status = API_DISPATCH_NO_OUTVEC(tfm_crypto_key_derivation_set_capacity,
TFM_CRYPTO_KEY_DERIVATION_SET_CAPACITY);
return status;
}
psa_status_t psa_key_derivation_input_bytes(
psa_key_derivation_operation_t *operation,
psa_key_derivation_step_t step,
const uint8_t *data,
size_t data_length)
{
psa_status_t status;
struct tfm_crypto_pack_iovec iov = {
.sfn_id = TFM_CRYPTO_KEY_DERIVATION_INPUT_BYTES_SID,
.step = step,
.op_handle = operation->handle,
};
psa_invec in_vec[] = {
{.base = &iov, .len = sizeof(struct tfm_crypto_pack_iovec)},
{.base = data, .len = data_length},
};
status = API_DISPATCH_NO_OUTVEC(tfm_crypto_key_derivation_input_bytes,
TFM_CRYPTO_KEY_DERIVATION_INPUT_BYTES);
return status;
}
psa_status_t psa_key_derivation_output_key(
const psa_key_attributes_t *attributes,
psa_key_derivation_operation_t *operation,
psa_key_id_t *key)
{
psa_status_t status;
struct tfm_crypto_pack_iovec iov = {
.sfn_id = TFM_CRYPTO_KEY_DERIVATION_OUTPUT_KEY_SID,
.op_handle = operation->handle,
};
psa_invec in_vec[] = {
{.base = &iov, .len = sizeof(struct tfm_crypto_pack_iovec)},
{.base = attributes, .len = sizeof(psa_key_attributes_t)},
};
psa_outvec out_vec[] = {
{.base = key, .len = sizeof(psa_key_id_t)}
};
status = API_DISPATCH(tfm_crypto_key_derivation_output_key,
TFM_CRYPTO_KEY_DERIVATION_OUTPUT_KEY);
return status;
}
psa_status_t psa_aead_encrypt_setup(psa_aead_operation_t *operation,
psa_key_id_t key,
psa_algorithm_t alg)
{
psa_status_t status;
status = PSA_ERROR_NOT_SUPPORTED;
return status;
}
psa_status_t psa_aead_decrypt_setup(psa_aead_operation_t *operation,
psa_key_id_t key,
psa_algorithm_t alg)
{
psa_status_t status;
status = PSA_ERROR_NOT_SUPPORTED;
return status;
}
psa_status_t psa_aead_generate_nonce(psa_aead_operation_t *operation,
uint8_t *nonce,
size_t nonce_size,
size_t *nonce_length)
{
psa_status_t status;
status = PSA_ERROR_NOT_SUPPORTED;
return status;
}
psa_status_t psa_aead_set_nonce(psa_aead_operation_t *operation,
const uint8_t *nonce,
size_t nonce_length)
{
psa_status_t status;
status = PSA_ERROR_NOT_SUPPORTED;
return status;
}
psa_status_t psa_aead_set_lengths(psa_aead_operation_t *operation,
size_t ad_length,
size_t plaintext_length)
{
psa_status_t status;
status = PSA_ERROR_NOT_SUPPORTED;
return status;
}
psa_status_t psa_aead_update(psa_aead_operation_t *operation,
const uint8_t *input,
size_t input_length,
uint8_t *output,
size_t output_size,
size_t *output_length)
{
psa_status_t status;
status = PSA_ERROR_NOT_SUPPORTED;
return status;
}
|
527000.c | /*
* linux/kernel/hd.c
*
* (C) 1991 Linus Torvalds
*/
/*
* This is the low-level hd interrupt support. It traverses the
* request-list, using interrupts to jump between functions. As
* all the functions are called within interrupts, we may not
* sleep. Special care is recommended.
*
* modified by Drew Eckhardt to check nr of hd's from the CMOS.
*/
#include <linux/config.h>
#include <linux/sched.h>
#include <linux/fs.h>
#include <linux/kernel.h>
#include <linux/hdreg.h>
#include <asm/system.h>
#include <asm/io.h>
#include <asm/segment.h>
#define MAJOR_NR 3
#include "blk.h"
#define CMOS_READ(addr) ({ \
outb_p(0x80|addr,0x70); \
inb_p(0x71); \
})
/* Max read/write errors/sector */
#define MAX_ERRORS 7
#define MAX_HD 2
static void recal_intr(void);
static int recalibrate = 0;
static int reset = 0;
/*
* This struct defines the HD's and their types.
*/
struct hd_i_struct {
int head,sect,cyl,wpcom,lzone,ctl;
};
#ifdef HD_TYPE
struct hd_i_struct hd_info[] = { HD_TYPE };
#define NR_HD ((sizeof (hd_info))/(sizeof (struct hd_i_struct)))
#else
struct hd_i_struct hd_info[] = { {0,0,0,0,0,0},{0,0,0,0,0,0} };
static int NR_HD = 0;
#endif
static struct hd_struct {
long start_sect;
long nr_sects;
} hd[5*MAX_HD]={{0,0},};
#define port_read(port,buf,nr) \
__asm__("cld;rep;insw"::"d" (port),"D" (buf),"c" (nr))
#define port_write(port,buf,nr) \
__asm__("cld;rep;outsw"::"d" (port),"S" (buf),"c" (nr))
extern void hd_interrupt(void);
extern void rd_load(void);
/* This may be used only once, enforced by 'static int callable' */
int sys_setup(void * BIOS)
{
static int callable = 1;
int i,drive;
unsigned char cmos_disks;
struct partition *p;
struct buffer_head * bh;
if (!callable)
return -1;
callable = 0;
#ifndef HD_TYPE
for (drive=0 ; drive<2 ; drive++) {
hd_info[drive].cyl = *(unsigned short *) BIOS;
hd_info[drive].head = *(unsigned char *) (2+BIOS);
hd_info[drive].wpcom = *(unsigned short *) (5+BIOS);
hd_info[drive].ctl = *(unsigned char *) (8+BIOS);
hd_info[drive].lzone = *(unsigned short *) (12+BIOS);
hd_info[drive].sect = *(unsigned char *) (14+BIOS);
BIOS += 16;
}
if (hd_info[1].cyl)
NR_HD=2;
else
NR_HD=1;
#endif
for (i=0 ; i<NR_HD ; i++) {
hd[i*5].start_sect = 0;
hd[i*5].nr_sects = hd_info[i].head*
hd_info[i].sect*hd_info[i].cyl;
}
/*
We querry CMOS about hard disks : it could be that
we have a SCSI/ESDI/etc controller that is BIOS
compatable with ST-506, and thus showing up in our
BIOS table, but not register compatable, and therefore
not present in CMOS.
Furthurmore, we will assume that our ST-506 drives
<if any> are the primary drives in the system, and
the ones reflected as drive 1 or 2.
The first drive is stored in the high nibble of CMOS
byte 0x12, the second in the low nibble. This will be
either a 4 bit drive type or 0xf indicating use byte 0x19
for an 8 bit type, drive 1, 0x1a for drive 2 in CMOS.
Needless to say, a non-zero value means we have
an AT controller hard disk for that drive.
*/
if ((cmos_disks = CMOS_READ(0x12)) & 0xf0)
if (cmos_disks & 0x0f)
NR_HD = 2;
else
NR_HD = 1;
else
NR_HD = 0;
for (i = NR_HD ; i < 2 ; i++) {
hd[i*5].start_sect = 0;
hd[i*5].nr_sects = 0;
}
for (drive=0 ; drive<NR_HD ; drive++) {
if (!(bh = bread(0x300 + drive*5,0))) {
printk("Unable to read partition table of drive %d\n\r",
drive);
panic("");
}
if (bh->b_data[510] != 0x55 || (unsigned char)
bh->b_data[511] != 0xAA) {
printk("Bad partition table on drive %d\n\r",drive);
panic("");
}
p = 0x1BE + (void *)bh->b_data;
for (i=1;i<5;i++,p++) {
hd[i+5*drive].start_sect = p->start_sect;
hd[i+5*drive].nr_sects = p->nr_sects;
}
brelse(bh);
}
if (NR_HD)
printk("Partition table%s ok.\n\r",(NR_HD>1)?"s":"");
rd_load();
mount_root();
return (0);
}
static int controller_ready(void)
{
int retries=100000;
while (--retries && (inb_p(HD_STATUS)&0x80));
return (retries);
}
static int win_result(void)
{
int i=inb_p(HD_STATUS);
if ((i & (BUSY_STAT | READY_STAT | WRERR_STAT | SEEK_STAT | ERR_STAT))
== (READY_STAT | SEEK_STAT))
return(0); /* ok */
if (i&1) i=inb(HD_ERROR);
return (1);
}
static void hd_out(unsigned int drive,unsigned int nsect,unsigned int sect,
unsigned int head,unsigned int cyl,unsigned int cmd,
void (*intr_addr)(void))
{
register int port asm("dx");
if (drive>1 || head>15)
panic("Trying to write bad sector");
if (!controller_ready())
panic("HD controller not ready");
do_hd = intr_addr;
outb_p(hd_info[drive].ctl,HD_CMD);
port=HD_DATA;
outb_p(hd_info[drive].wpcom>>2,++port);
outb_p(nsect,++port);
outb_p(sect,++port);
outb_p(cyl,++port);
outb_p(cyl>>8,++port);
outb_p(0xA0|(drive<<4)|head,++port);
outb(cmd,++port);
}
static int drive_busy(void)
{
unsigned int i;
for (i = 0; i < 10000; i++)
if (READY_STAT == (inb_p(HD_STATUS) & (BUSY_STAT|READY_STAT)))
break;
i = inb(HD_STATUS);
i &= BUSY_STAT | READY_STAT | SEEK_STAT;
if (i == (READY_STAT | SEEK_STAT))
return(0);
printk("HD controller times out\n\r");
return(1);
}
static void reset_controller(void)
{
int i;
outb(4,HD_CMD);
for(i = 0; i < 100; i++) nop();
outb(hd_info[0].ctl & 0x0f ,HD_CMD);
if (drive_busy())
printk("HD-controller still busy\n\r");
if ((i = inb(HD_ERROR)) != 1)
printk("HD-controller reset failed: %02x\n\r",i);
}
static void reset_hd(int nr)
{
reset_controller();
hd_out(nr,hd_info[nr].sect,hd_info[nr].sect,hd_info[nr].head-1,
hd_info[nr].cyl,WIN_SPECIFY,&recal_intr);
}
void unexpected_hd_interrupt(void)
{
printk("Unexpected HD interrupt\n\r");
}
static void bad_rw_intr(void)
{
if (++CURRENT->errors >= MAX_ERRORS)
end_request(0);
if (CURRENT->errors > MAX_ERRORS/2)
reset = 1;
}
static void read_intr(void)
{
if (win_result()) {
bad_rw_intr();
do_hd_request();
return;
}
port_read(HD_DATA,CURRENT->buffer,256);
CURRENT->errors = 0;
CURRENT->buffer += 512;
CURRENT->sector++;
if (--CURRENT->nr_sectors) {
do_hd = &read_intr;
return;
}
end_request(1);
do_hd_request();
}
static void write_intr(void)
{
if (win_result()) {
bad_rw_intr();
do_hd_request();
return;
}
if (--CURRENT->nr_sectors) {
CURRENT->sector++;
CURRENT->buffer += 512;
do_hd = &write_intr;
port_write(HD_DATA,CURRENT->buffer,256);
return;
}
end_request(1);
do_hd_request();
}
static void recal_intr(void)
{
if (win_result())
bad_rw_intr();
do_hd_request();
}
void do_hd_request(void)
{
int i,r = 0;
unsigned int block,dev;
unsigned int sec,head,cyl;
unsigned int nsect;
INIT_REQUEST;
dev = MINOR(CURRENT->dev);
block = CURRENT->sector;
if (dev >= 5*NR_HD || block+2 > hd[dev].nr_sects) {
end_request(0);
goto repeat;
}
block += hd[dev].start_sect;
dev /= 5;
__asm__("divl %4":"=a" (block),"=d" (sec):"0" (block),"1" (0),
"r" (hd_info[dev].sect));
__asm__("divl %4":"=a" (cyl),"=d" (head):"0" (block),"1" (0),
"r" (hd_info[dev].head));
sec++;
nsect = CURRENT->nr_sectors;
if (reset) {
reset = 0;
recalibrate = 1;
reset_hd(CURRENT_DEV);
return;
}
if (recalibrate) {
recalibrate = 0;
hd_out(dev,hd_info[CURRENT_DEV].sect,0,0,0,
WIN_RESTORE,&recal_intr);
return;
}
if (CURRENT->cmd == WRITE) {
hd_out(dev,nsect,sec,head,cyl,WIN_WRITE,&write_intr);
for(i=0 ; i<3000 && !(r=inb_p(HD_STATUS)&DRQ_STAT) ; i++)
/* nothing */ ;
if (!r) {
bad_rw_intr();
goto repeat;
}
port_write(HD_DATA,CURRENT->buffer,256);
} else if (CURRENT->cmd == READ) {
hd_out(dev,nsect,sec,head,cyl,WIN_READ,&read_intr);
} else
panic("unknown hd-command");
}
void hd_init(void)
{
blk_dev[MAJOR_NR].request_fn = DEVICE_REQUEST;
set_intr_gate(0x2E,&hd_interrupt);
outb_p(inb_p(0x21)&0xfb,0x21);
outb(inb_p(0xA1)&0xbf,0xA1);
}
|
50070.c | #include <rsync/rsync.h>
int main(int argc,char *argv[])
{
if (argc !=3)
{
printf("usage: %s from to\n", argv[0]);
return(1);
}
return(rsync(argc, argv));
}
|
588842.c | /*-
* See the file LICENSE for redistribution information.
*
* Copyright (c) 2010, 2016 Oracle and/or its affiliates. All rights reserved.
*
* $Id$
*/
#include "db_config.h"
#include "db_int.h"
#include "dbinc/db_page.h"
#include "dbinc/heap.h"
#include "dbinc/lock.h"
#include "dbinc/mp.h"
#ifdef HAVE_STATISTICS
/*
* __heap_stat --
* Gather/print the heap statistics
*
* PUBLIC: int __heap_stat __P((DBC *, void *, u_int32_t));
*/
int
__heap_stat(dbc, spp, flags)
DBC *dbc;
void *spp;
u_int32_t flags;
{
DB *dbp;
DB_HEAP_STAT *sp;
DB_LOCK metalock;
DB_MPOOLFILE *mpf;
ENV *env;
HEAPMETA *meta;
db_pgno_t metapgno;
int ret, t_ret, write_meta;
dbp = dbc->dbp;
env = dbp->env;
meta = NULL;
LOCK_INIT(metalock);
mpf = dbp->mpf;
sp = NULL;
ret = t_ret = write_meta = 0;
/* Allocate and clear the structure. */
if ((ret = __os_umalloc(env, sizeof(*sp), &sp)) != 0)
goto err;
memset(sp, 0, sizeof(*sp));
/* Get the metadata page for the entire database. */
metapgno = PGNO_BASE_MD;
if ((ret = __db_lget(dbc,
0, metapgno, DB_LOCK_READ, 0, &metalock)) != 0)
goto err;
if ((ret = __memp_fget(mpf, &metapgno,
dbc->thread_info, dbc->txn, 0, &meta)) != 0)
goto err;
sp->heap_metaflags = meta->dbmeta.flags;
sp->heap_pagecnt = meta->dbmeta.last_pgno + 1;
sp->heap_pagesize = meta->dbmeta.pagesize;
sp->heap_magic = meta->dbmeta.magic;
sp->heap_version = meta->dbmeta.version;
sp->heap_nregions = meta->nregions;
sp->heap_regionsize = meta->region_size;
if (LF_ISSET(DB_FAST_STAT)) {
sp->heap_nrecs = meta->dbmeta.record_count;
} else {
/* Count the entries in the database. */
if ((ret = __heap_traverse(dbc, __heap_stat_callback, sp)) != 0)
goto err;
write_meta = !F_ISSET(dbp, DB_AM_RDONLY) &&
(!MULTIVERSION(dbp) || dbc->txn != NULL);
if (write_meta) {
ret = __memp_fput(mpf,
dbc->thread_info, meta, dbc->priority);
meta = NULL;
if ((t_ret = __LPUT(dbc, metalock)) != 0 && ret == 0)
ret = t_ret;
if (ret != 0)
goto err;
if ((ret = __db_lget(dbc,
0, metapgno, DB_LOCK_WRITE, 0, &metalock)) != 0)
goto err;
if ((ret = __memp_fget(mpf, &metapgno, dbc->thread_info,
dbc->txn, DB_MPOOL_DIRTY, &meta)) != 0)
goto err;
meta->dbmeta.key_count = sp->heap_nrecs;
meta->dbmeta.record_count = sp->heap_nrecs;
}
}
*(DB_HEAP_STAT **)spp = sp;
err: /* Discard metadata page. */
if ((t_ret = __LPUT(dbc, metalock)) != 0 && ret == 0)
ret = t_ret;
if (meta != NULL && (t_ret = __memp_fput(mpf,
dbc->thread_info, meta, dbc->priority)) != 0 && ret == 0)
ret = t_ret;
if (ret != 0 && sp != NULL) {
__os_ufree(env, sp);
*(DB_BTREE_STAT **)spp = NULL;
}
return (ret);
}
/*
* __heap_stat_print --
* Display heap statistics.
*
* PUBLIC: int __heap_stat_print __P((DBC *, u_int32_t));
*/
int
__heap_stat_print(dbc, flags)
DBC *dbc;
u_int32_t flags;
{
DB *dbp;
DB_HEAP_STAT *sp;
ENV *env;
int ret;
dbp = dbc->dbp;
env = dbp->env;
if ((ret = __heap_stat(dbc, &sp, LF_ISSET(DB_FAST_STAT))) != 0)
return (ret);
if (LF_ISSET(DB_STAT_ALL)) {
__db_msg(env, "%s", DB_GLOBAL(db_line));
__db_msg(env, "Default Heap database information:");
}
__db_msg(env, "%lx\tHeap magic number", (u_long)sp->heap_magic);
__db_msg(env, "%lu\tHeap version number", (u_long)sp->heap_version);
__db_dl(env,
"Underlying database page size", (u_long)sp->heap_pagesize);
__db_dl(env,
"Number of records in the database", (u_long)sp->heap_nrecs);
__db_dl(env,
"Number of external files in the database",
(u_long)sp->heap_ext_files);
__db_dl(env, "Number of database pages", (u_long)sp->heap_pagecnt);
__db_dl(env, "Number of database regions", (u_long)sp->heap_nregions);
__db_dl(env,
"Number of pages in a region", (u_long)sp->heap_regionsize);
__os_ufree(env, sp);
return (0);
}
/*
* __heap_print_cursor --
* Display the current cursor.
*
* PUBLIC: void __heap_print_cursor __P((DBC *));
*/
void
__heap_print_cursor(dbc)
DBC *dbc;
{
COMPQUIET(dbc, NULL);
return;
}
/*
* __heap_stat_callback --
* Statistics callback.
*
* PUBLIC: int __heap_stat_callback __P((DBC *, PAGE *, void *, int *));
*/
int
__heap_stat_callback(dbc, h, cookie, putp)
DBC *dbc;
PAGE *h;
void *cookie;
int *putp;
{
DB *dbp;
DB_HEAP_STAT *sp;
HEAPHDR *hdr;
int i;
dbp = dbc->dbp;
sp = cookie;
*putp = 0;
switch (TYPE(h)) {
case P_HEAP:
/*
* We can't just use NUM_ENT, otherwise we'd mis-count split
* records.
*/
for (i = 0; i <= HEAP_HIGHINDX(h); i++) {
hdr = (HEAPHDR *)P_ENTRY(dbp, h, i);
if (!F_ISSET(hdr, HEAP_RECSPLIT) ||
F_ISSET(hdr, HEAP_RECFIRST))
sp->heap_nrecs++;
if (F_ISSET(hdr, HEAP_RECBLOB)) {
sp->heap_nblobs++;
sp->heap_ext_files++;
}
}
break;
case P_HEAPMETA: /* Fallthrough */
case P_IHEAP: /* Fallthrough */
default:
break;
}
return (0);
}
#else /* !HAVE_STATISTICS */
int
__heap_stat(dbc, spp, flags)
DBC *dbc;
void *spp;
u_int32_t flags;
{
COMPQUIET(spp, NULL);
COMPQUIET(flags, 0);
return (__db_stat_not_built(dbc->env));
}
#endif
/*
* __heap_traverse --
* Walk a Heap database.
*
* PUBLIC: int __heap_traverse __P((DBC *,
* PUBLIC: int (*)(DBC *, PAGE *, void *, int *), void *));
*/
int
__heap_traverse(dbc, callback, cookie)
DBC *dbc;
int (*callback)__P((DBC *, PAGE *, void *, int *));
void *cookie;
{
DB *dbp;
DB_LOCK lock;
DB_MPOOLFILE *mpf;
PAGE *h;
db_pgno_t pgno;
int already_put, ret, t_ret;
dbp = dbc->dbp;
mpf = dbp->mpf;
LOCK_INIT(lock);
pgno = FIRST_HEAP_DPAGE;
for (;;) {
already_put = 0;
h = NULL;
if ((ret = __db_lget(dbc,
0, pgno, DB_LOCK_READ, 0, &lock)) != 0)
break;
if ((ret = __memp_fget(mpf,
&pgno, dbc->thread_info, dbc->txn, 0, &h)) != 0) {
if (ret == DB_PAGE_NOTFOUND)
ret = 0;
if ((t_ret = __TLPUT(dbc, lock)) != 0 && ret == 0)
ret = t_ret;
break;
}
ret = callback(dbc, h, cookie, &already_put);
if (!already_put && (t_ret = __memp_fput(
mpf, dbc->thread_info, h, dbc->priority)) != 0 && ret == 0)
ret = t_ret;
if ((t_ret = __TLPUT(dbc, lock)) != 0 && ret == 0)
ret = t_ret;
if (ret != 0)
break;
pgno++;
}
return (ret);
}
|
77736.c | /*!
* @section LICENSE
* (C) Copyright 2013 Bosch Sensortec GmbH All Rights Reserved
*
* This software program is licensed subject to the GNU General
* Public License (GPL).Version 2,June 1991,
* available at http://www.fsf.org/copyleft/gpl.html
*
* @filename bmg160.c
* @date 2013/11/25
* @id "079d340"
* @version 1.5
*
* @brief BMG160API
*/
#include "bmg160.h"
static struct bmg160_t *p_bmg160;
/*****************************************************************************
* Description: *//**brief API Initialization routine
*
*
*
*
* \param bmg160_t *bmg160
* Pointer to a structure.
*
* structure members are
*
* unsigned char chip_id;
* unsigned char dev_addr;
* BMG160_BRD_FUNC_PTR;
* BMG160_WR_FUNC_PTR;
* BMG160_RD_FUNC_PTR;
* void(*delay_msec)( BMG160_MDELAY_DATA_TYPE );
*
*
*
*
*
* \return result of communication routines
*
*
*****************************************************************************/
/* Scheduling:
*
*
*
* Usage guide:
*
*
* Remarks:
*
*****************************************************************************/
BMG160_RETURN_FUNCTION_TYPE bmg160_init(struct bmg160_t *bmg160)
{
BMG160_RETURN_FUNCTION_TYPE comres = C_BMG160_Zero_U8X;
unsigned char a_data_u8r = C_BMG160_Zero_U8X;
p_bmg160 = bmg160;
p_bmg160->dev_addr = BMG160_I2C_ADDR;
/*Read CHIP_ID */
comres = p_bmg160->BMG160_BUS_READ_FUNC(p_bmg160->dev_addr,
BMG160_CHIP_ID_ADDR, &a_data_u8r, 1);
p_bmg160->chip_id = a_data_u8r;
return comres;
}
/* Compiler Switch if applicable
#ifdef
#endif
*/
/*****************************************************************************
* Description: *//**brief Reads Rate dataX from location 02h and 03h
* registers
*
*
*
*
* \param
* BMG160_S16 *data_x : Address of data_x
*
*
* \return
* result of communication routines
*
*****************************************************************************/
/* Scheduling:
*
*
*
* Usage guide:
*
*
* Remarks:
*
*****************************************************************************/
BMG160_RETURN_FUNCTION_TYPE bmg160_get_dataX(BMG160_S16 *data_x)
{
BMG160_RETURN_FUNCTION_TYPE comres = C_BMG160_Zero_U8X;
unsigned char a_data_u8r[2] = {0, 0};
if (p_bmg160 == BMG160_NULL) {
return E_BMG160_NULL_PTR;
} else {
comres = p_bmg160->BMG160_BUS_READ_FUNC(p_bmg160->dev_addr,
BMG160_RATE_X_LSB_VALUEX__REG, a_data_u8r, 2);
a_data_u8r[0] = BMG160_GET_BITSLICE(a_data_u8r[0],
BMG160_RATE_X_LSB_VALUEX);
*data_x = (BMG160_S16)
((((BMG160_S16)((signed char)a_data_u8r[1])) <<
BMG160_SHIFT_8_POSITION) | (a_data_u8r[0]));
}
return comres;
}
/* Compiler Switch if applicable
#ifdef
#endif
*/
/*****************************************************************************
* Description: *//**brief Reads rate dataY from location 04h and 05h
* registers
*
*
*
*
* \param
* BMG160_S16 *data_y : Address of data_y
*
*
* \return
* result of communication routines
*
*****************************************************************************/
/* Scheduling:
*
*
*
* Usage guide:
*
*
* Remarks:
*
*****************************************************************************/
BMG160_RETURN_FUNCTION_TYPE bmg160_get_dataY(BMG160_S16 *data_y)
{
BMG160_RETURN_FUNCTION_TYPE comres = C_BMG160_Zero_U8X;
unsigned char a_data_u8r[2] = {0, 0};
if (p_bmg160 == BMG160_NULL) {
return E_BMG160_NULL_PTR;
} else {
comres = p_bmg160->BMG160_BUS_READ_FUNC(p_bmg160->dev_addr,
BMG160_RATE_Y_LSB_VALUEY__REG, a_data_u8r, 2);
a_data_u8r[0] = BMG160_GET_BITSLICE(a_data_u8r[0],
BMG160_RATE_Y_LSB_VALUEY);
*data_y = (BMG160_S16)
((((BMG160_S16)((signed char)a_data_u8r[1]))
<< BMG160_SHIFT_8_POSITION) | (a_data_u8r[0]));
}
return comres;
}
/* Compiler Switch if applicable
#ifdef
#endif
*/
/*****************************************************************************
* Description: *//**brief Reads rate dataZ from location 06h and 07h
* registers
*
*
*
*
* \param
* BMG160_S16 *data_z : Address of data_z
*
*
* \return
* result of communication routines
*
*****************************************************************************/
/* Scheduling:
*
*
*
* Usage guide:
*
*
* Remarks:
*
*****************************************************************************/
BMG160_RETURN_FUNCTION_TYPE bmg160_get_dataZ(BMG160_S16 *data_z)
{
BMG160_RETURN_FUNCTION_TYPE comres = C_BMG160_Zero_U8X;
unsigned char a_data_u8r[2] = {0, 0};
if (p_bmg160 == BMG160_NULL) {
return E_BMG160_NULL_PTR;
} else {
comres = p_bmg160->BMG160_BUS_READ_FUNC(p_bmg160->dev_addr,
BMG160_RATE_Z_LSB_VALUEZ__REG, a_data_u8r, 2);
a_data_u8r[0] = BMG160_GET_BITSLICE(a_data_u8r[0],
BMG160_RATE_Z_LSB_VALUEZ);
*data_z = (BMG160_S16)
((((BMG160_S16)((signed char)a_data_u8r[1]))
<< BMG160_SHIFT_8_POSITION) | (a_data_u8r[0]));
}
return comres;
}
/* Compiler Switch if applicable
#ifdef
#endif
*/
/*****************************************************************************
* Description: *//**brief Reads data X,Y and Z from location 02h to 07h
*
*
*
*
* \param
* bmg160_data_t *data : Address of bmg160_data_t
*
*
* \return
* result of communication routines
*
*****************************************************************************/
/* Scheduling:
*
*
*
* Usage guide:
*
*
* Remarks:
*
*****************************************************************************/
BMG160_RETURN_FUNCTION_TYPE bmg160_get_dataXYZ(struct bmg160_data_t *data)
{
BMG160_RETURN_FUNCTION_TYPE comres = C_BMG160_Zero_U8X;
unsigned char a_data_u8r[6] = {0, 0, 0, 0, 0, 0};
if (p_bmg160 == BMG160_NULL) {
return E_BMG160_NULL_PTR;
} else {
comres = p_bmg160->BMG160_BUS_READ_FUNC(p_bmg160->dev_addr,
BMG160_RATE_X_LSB_VALUEX__REG, a_data_u8r, 6);
/* Data X */
a_data_u8r[0] =
BMG160_GET_BITSLICE(a_data_u8r[0], BMG160_RATE_X_LSB_VALUEX);
data->datax = (BMG160_S16)
((((BMG160_S16)((signed char)a_data_u8r[1]))
<< BMG160_SHIFT_8_POSITION) | (a_data_u8r[0]));
/* Data Y */
a_data_u8r[2] = BMG160_GET_BITSLICE(a_data_u8r[2],
BMG160_RATE_Y_LSB_VALUEY);
data->datay = (BMG160_S16)
((((BMG160_S16)((signed char)a_data_u8r[3]))
<< BMG160_SHIFT_8_POSITION) | (a_data_u8r[2]));
/* Data Z */
a_data_u8r[4] = BMG160_GET_BITSLICE(a_data_u8r[4],
BMG160_RATE_Z_LSB_VALUEZ);
data->dataz = (BMG160_S16)
((((BMG160_S16)((signed char)a_data_u8r[5]))
<< BMG160_SHIFT_8_POSITION) | (a_data_u8r[4]));
}
return comres;
}
/* Compiler Switch if applicable
#ifdef
#endif
*/
/*****************************************************************************
* Description: *//**brief Reads data X,Y,Z and Interrupts
* from location 02h to 07h
*
*
*
*
* \param
* bmg160_data_t *data : Address of bmg160_data_t
*
*
* \return
* result of communication routines
*
*****************************************************************************/
/* Scheduling:
*
*
*
* Usage guide:
*
*
* Remarks:
*
*****************************************************************************/
BMG160_RETURN_FUNCTION_TYPE bmg160_get_dataXYZI(struct bmg160_data_t *data)
{
BMG160_RETURN_FUNCTION_TYPE comres = C_BMG160_Zero_U8X;
unsigned char a_data_u8r[12] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
if (p_bmg160 == BMG160_NULL) {
return E_BMG160_NULL_PTR;
} else {
comres = p_bmg160->BMG160_BUS_READ_FUNC(p_bmg160->dev_addr,
BMG160_RATE_X_LSB_VALUEX__REG, a_data_u8r, 12);
/* Data X */
a_data_u8r[0] = BMG160_GET_BITSLICE(a_data_u8r[0],
BMG160_RATE_X_LSB_VALUEX);
data->datax = (BMG160_S16)
((((BMG160_S16)((signed char)a_data_u8r[1]))
<< BMG160_SHIFT_8_POSITION) | (a_data_u8r[0]));
/* Data Y */
a_data_u8r[2] = BMG160_GET_BITSLICE(a_data_u8r[2],
BMG160_RATE_Y_LSB_VALUEY);
data->datay = (BMG160_S16)
((((BMG160_S16)((signed char)a_data_u8r[3]))
<< BMG160_SHIFT_8_POSITION) | (a_data_u8r[2]));
/* Data Z */
a_data_u8r[4] = BMG160_GET_BITSLICE(a_data_u8r[4],
BMG160_RATE_Z_LSB_VALUEZ);
data->dataz = (BMG160_S16)
((((BMG160_S16)((signed char)a_data_u8r[5]))
<< BMG160_SHIFT_8_POSITION) | (a_data_u8r[4]));
data->intstatus[0] = a_data_u8r[7];
data->intstatus[1] = a_data_u8r[8];
data->intstatus[2] = a_data_u8r[9];
data->intstatus[3] = a_data_u8r[10];
data->intstatus[4] = a_data_u8r[11];
}
return comres;
}
/* Compiler Switch if applicable
#ifdef
#endif
*/
/*****************************************************************************
* Description: *//**brief Reads Temperature from location 08h
*
*
*
*
* \param
* unsigned char *temp : Address of temperature
*
*
* \return
* result of communication routines
*
*****************************************************************************/
/* Scheduling:
*
*
*
* Usage guide:
*
*
* Remarks:
*
*****************************************************************************/
BMG160_RETURN_FUNCTION_TYPE bmg160_get_Temperature(unsigned char *temperature)
{
BMG160_RETURN_FUNCTION_TYPE comres = C_BMG160_Zero_U8X;
unsigned char v_data_u8r = C_BMG160_Zero_U8X;
if (p_bmg160 == BMG160_NULL) {
return E_BMG160_NULL_PTR;
} else {
comres = p_bmg160->BMG160_BUS_READ_FUNC(p_bmg160->dev_addr,
BMG160_TEMP_ADDR, &v_data_u8r, 1);
*temperature = v_data_u8r;
}
return comres;
}
/* Compiler Switch if applicable
#ifdef
#endif
*/
/*****************************************************************************
* Description: *//**brief This API reads the data from the given register
*
*
*
*
*\param unsigned char addr, unsigned char *data unsigned char len
* addr -> Address of the register
* data -> address of the variable, read value will be
* kept
* len -> No of byte to be read.
* \return results of bus communication function
*
*
*****************************************************************************/
/* Scheduling:
*
*
*
* Usage guide:
*
*
* Remarks:
*
*****************************************************************************/
BMG160_RETURN_FUNCTION_TYPE bmg160_read_register(unsigned char addr,
unsigned char *data, unsigned char len)
{
BMG160_RETURN_FUNCTION_TYPE comres = C_BMG160_Zero_U8X;
if (p_bmg160 == BMG160_NULL) {
return E_BMG160_NULL_PTR;
} else {
comres = p_bmg160->BMG160_BUS_READ_FUNC
(p_bmg160->dev_addr, addr, data, len);
}
return comres;
}
/* Compiler Switch if applicable
#ifdef
#endif
*/
/*****************************************************************************
* Description: *//**brief This API reads the data from the given register
*
*
*
*
*\param unsigned char addr, unsigned char *data BMG160_S32 len
* addr -> Address of the register
* data -> address of the variable, read value will be
* kept
* len -> No of byte to be read.
* \return results of bus communication function
*
*
*****************************************************************************/
/* Scheduling:
*
*
*
* Usage guide:
*
*
* Remarks:
*
*****************************************************************************/
BMG160_RETURN_FUNCTION_TYPE bmg160_burst_read(unsigned char addr,
unsigned char *data, BMG160_S32 len)
{
BMG160_RETURN_FUNCTION_TYPE comres = C_BMG160_Zero_U8X;
if (p_bmg160 == BMG160_NULL) {
return E_BMG160_NULL_PTR;
} else {
comres = p_bmg160->BMG160_BURST_READ_FUNC(p_bmg160->dev_addr,
addr, data, len);
}
return comres;
}
/* Compiler Switch if applicable
#ifdef
#endif
*/
/*****************************************************************************
* Description: *//**brief This API given data to the given register
*
*
*
*
*\param unsigned char addr, unsigned char data,unsigned char len
* addr -> Address of the register
* data -> Data to be written to the register
* len -> No of byte to be read.
*
* \return Results of bus communication function
*
*
*****************************************************************************/
/* Scheduling:
*
*
*
* Usage guide:
*
*
* Remarks:
*
*****************************************************************************/
BMG160_RETURN_FUNCTION_TYPE bmg160_write_register(unsigned char addr,
unsigned char *data, unsigned char len)
{
BMG160_RETURN_FUNCTION_TYPE comres = C_BMG160_Zero_U8X;
if (p_bmg160 == BMG160_NULL) {
return E_BMG160_NULL_PTR;
} else {
comres = p_bmg160->BMG160_BUS_WRITE_FUNC
(p_bmg160->dev_addr, addr, data, len);
}
return comres;
}
/* Compiler Switch if applicable
#ifdef
#endif
*/
/*****************************************************************************
* Description: *//**brief Reads interrupt status 0 register byte from 09h
*
*
*
*
* \param
* unsigned char *status0_data : Address of status 0 register
*
*
* \return
* Result of bus communication function
*
*****************************************************************************/
/* Scheduling:
*
*
*
* Usage guide:
*
*
* Remarks:
*
*****************************************************************************/
BMG160_RETURN_FUNCTION_TYPE bmg160_get_interrupt_status_reg_0(
unsigned char *status0_data)
{
BMG160_RETURN_FUNCTION_TYPE comres = C_BMG160_Zero_U8X;
unsigned char v_data_u8r = C_BMG160_Zero_U8X;
if (p_bmg160 == BMG160_NULL) {
return E_BMG160_NULL_PTR;
} else {
comres = p_bmg160->BMG160_BUS_READ_FUNC
(p_bmg160->dev_addr,
BMG160_INT_STATUSZERO__REG, &v_data_u8r, 1);
*status0_data =
BMG160_GET_BITSLICE(v_data_u8r, BMG160_INT_STATUSZERO);
}
return comres;
}
/* Compiler Switch if applicable
#ifdef
#endif
*/
/*****************************************************************************
* Description: *//**brief Reads interrupt status 1 register byte from 0Ah
*
*
*
*
* \param
* unsigned char *status1_data : Address of status register
*
*
* \return
* Result of bus communication function
*
*****************************************************************************/
/* Scheduling:
*
*
*
* Usage guide:
*
*
* Remarks:
*
*****************************************************************************/
BMG160_RETURN_FUNCTION_TYPE bmg160_get_interrupt_status_reg_1(
unsigned char *status1_data)
{
BMG160_RETURN_FUNCTION_TYPE comres = C_BMG160_Zero_U8X;
unsigned char v_data_u8r = C_BMG160_Zero_U8X;
if (p_bmg160 == BMG160_NULL) {
return E_BMG160_NULL_PTR;
} else {
comres = p_bmg160->BMG160_BUS_READ_FUNC
(p_bmg160->dev_addr, BMG160_INT_STATUSONE__REG,
&v_data_u8r, 1);
*status1_data =
BMG160_GET_BITSLICE(v_data_u8r, BMG160_INT_STATUSONE);
}
return comres;
}
/* Compiler Switch if applicable
#ifdef
#endif
*/
/*****************************************************************************
* Description: *//**brief Reads interrupt status register byte from 0Bh
*
*
*
*
* \param
* unsigned char *status2_data : Address of status 2 register
*
*
* \return
* Result of bus communication function
*
*****************************************************************************/
/* Scheduling:
*
*
*
* Usage guide:
*
*
* Remarks:
*
*****************************************************************************/
BMG160_RETURN_FUNCTION_TYPE bmg160_get_interrupt_status_reg_2(
unsigned char *status2_data)
{
BMG160_RETURN_FUNCTION_TYPE comres = C_BMG160_Zero_U8X;
unsigned char v_data_u8r = C_BMG160_Zero_U8X;
if (p_bmg160 == BMG160_NULL) {
return E_BMG160_NULL_PTR;
} else {
comres = p_bmg160->BMG160_BUS_READ_FUNC
(p_bmg160->dev_addr,
BMG160_INT_STATUSTWO__REG, &v_data_u8r, 1);
*status2_data =
BMG160_GET_BITSLICE(v_data_u8r, BMG160_INT_STATUSTWO);
}
return comres;
}
/* Compiler Switch if applicable
#ifdef
#endif
*/
/*****************************************************************************
* Description: *//**brief Reads interrupt status 3 register byte from 0Ch
*
*
*
*
* \param
* unsigned char *status3_data : Address of status 3 register
*
*
* \return
* Result of bus communication function
*
*****************************************************************************/
/* Scheduling:
*
*
*
* Usage guide:
*
*
* Remarks:
*
*****************************************************************************/
BMG160_RETURN_FUNCTION_TYPE bmg160_get_interrupt_status_reg_3(
unsigned char *status3_data)
{
BMG160_RETURN_FUNCTION_TYPE comres = C_BMG160_Zero_U8X;
unsigned char v_data_u8r = C_BMG160_Zero_U8X;
if (p_bmg160 == BMG160_NULL) {
return E_BMG160_NULL_PTR;
} else {
comres = p_bmg160->BMG160_BUS_READ_FUNC
(p_bmg160->dev_addr,
BMG160_INT_STATUSTHREE__REG, &v_data_u8r, 1);
*status3_data =
BMG160_GET_BITSLICE(v_data_u8r, BMG160_INT_STATUSTHREE);
}
return comres;
}
/* Compiler Switch if applicable
#ifdef
#endif
*/
/*****************************************************************************
* Description: *//**brief This API reads the range from register 0x0Fh of
* (0 to 2) bits
*
*
*
*
*\param unsigned char *range
* Range[0....7]
* 0 2000/s
* 1 1000/s
* 2 500/s
* 3 250/s
* 4 125/s
*
*
*
*
*
* \return communication results
*
*
*****************************************************************************/
/* Scheduling:
*
*
*
* Usage guide:
*
*
* Remarks:
*
*****************************************************************************/
BMG160_RETURN_FUNCTION_TYPE bmg160_get_range_reg(unsigned char *range)
{
BMG160_RETURN_FUNCTION_TYPE comres = C_BMG160_Zero_U8X;
unsigned char v_data_u8r = C_BMG160_Zero_U8X;
if (p_bmg160 == BMG160_NULL) {
return E_BMG160_NULL_PTR;
} else {
comres = p_bmg160->BMG160_BUS_READ_FUNC
(p_bmg160->dev_addr,
BMG160_RANGE_ADDR_RANGE__REG, &v_data_u8r, 1);
*range =
BMG160_GET_BITSLICE(v_data_u8r, BMG160_RANGE_ADDR_RANGE);
}
return comres;
}
/* Compiler Switch if applicable
#ifdef
#endif
*/
/*****************************************************************************
* Description: *//**brief This API sets the range register 0x0Fh
* (0 to 2 bits)
*
*
*
*
*\param unsigned char range
*
* Range[0....7]
* 0 2000/s
* 1 1000/s
* 2 500/s
* 3 250/s
* 4 125/s
*
*
*
*
* \return Communication results
*
*
*****************************************************************************/
/* Scheduling:
*
*
*
* Usage guide:
*
*
* Remarks:
*
*****************************************************************************/
BMG160_RETURN_FUNCTION_TYPE bmg160_set_range_reg(unsigned char range)
{
BMG160_RETURN_FUNCTION_TYPE comres = C_BMG160_Zero_U8X;
unsigned char v_data_u8r = C_BMG160_Zero_U8X;
if (p_bmg160 == BMG160_NULL) {
return E_BMG160_NULL_PTR;
} else {
if (range < C_BMG160_Five_U8X) {
comres = p_bmg160->BMG160_BUS_READ_FUNC
(p_bmg160->dev_addr,
BMG160_RANGE_ADDR_RANGE__REG, &v_data_u8r, 1);
v_data_u8r = BMG160_SET_BITSLICE(v_data_u8r,
BMG160_RANGE_ADDR_RANGE,
range);
comres += p_bmg160->BMG160_BUS_WRITE_FUNC
(p_bmg160->dev_addr,
BMG160_RANGE_ADDR_RANGE__REG, &v_data_u8r, 1);
} else {
comres = E_BMG160_OUT_OF_RANGE;
}
}
return comres;
}
/* Compiler Switch if applicable
#ifdef
#endif
*/
/*****************************************************************************
* Description: *//**brief This API reads the high resolution bit of 0x10h
* Register 7th bit
*
*
*
*
*\param unsigned char *high_res
* Pointer to a variable passed as a parameter
*
*
*
* \return communication results
*
*
*****************************************************************************/
/* Scheduling:
*
*
*
* Usage guide:
*
*
* Remarks:
*
*****************************************************************************/
BMG160_RETURN_FUNCTION_TYPE bmg160_get_high_res(unsigned char *high_res)
{
BMG160_RETURN_FUNCTION_TYPE comres = C_BMG160_Zero_U8X;
unsigned char v_data_u8r = C_BMG160_Zero_U8X;
if (p_bmg160 == BMG160_NULL) {
return E_BMG160_NULL_PTR;
} else {
comres = p_bmg160->BMG160_BUS_READ_FUNC
(p_bmg160->dev_addr,
BMG160_BW_ADDR_HIGH_RES__REG, &v_data_u8r, 1);
*high_res =
BMG160_GET_BITSLICE(v_data_u8r, BMG160_BW_ADDR_HIGH_RES);
}
return comres;
}
/* Compiler Switch if applicable
#ifdef
#endif
*/
/*****************************************************************************
* Description: *//**brief This API reads the bandwidth register of 0x10h 0 to
* 3 bits
*
*
*
*
* \param unsigned char *bandwidth
* pointer to a variable passed as a parameter
*
* 0 no filter(523 Hz)
* 1 230Hz
* 2 116Hz
* 3 47Hz
* 4 23Hz
* 5 12Hz
* 6 64Hz
* 7 32Hz
*
*
*
* \return communication results
*
*
*****************************************************************************/
/* Scheduling:
*
*
*
* Usage guide:
*
*
* Remarks:
*
*****************************************************************************/
BMG160_RETURN_FUNCTION_TYPE bmg160_get_bw(unsigned char *bandwidth)
{
BMG160_RETURN_FUNCTION_TYPE comres = C_BMG160_Zero_U8X;
unsigned char v_data_u8r = C_BMG160_Zero_U8X;
if (p_bmg160 == BMG160_NULL) {
return E_BMG160_NULL_PTR;
} else {
comres = p_bmg160->BMG160_BUS_READ_FUNC
(p_bmg160->dev_addr, BMG160_BW_ADDR__REG, &v_data_u8r, 1);
*bandwidth = BMG160_GET_BITSLICE(v_data_u8r,
BMG160_BW_ADDR);
}
return comres;
}
/* Compiler Switch if applicable
#ifdef
#endif
*/
/*****************************************************************************
* Description: *//**brief This API writes the Bandwidth register (0x10h of 0
* to 3 bits)
*
*
*
*
*\param unsigned char bandwidth,
* The bandwidth to be set passed as a parameter
*
* 0 no filter(523 Hz)
* 1 230Hz
* 2 116Hz
* 3 47Hz
* 4 23Hz
* 5 12Hz
* 6 64Hz
* 7 32Hz
*
*
*
*
* \return communication results
*
*
*****************************************************************************/
/* Scheduling:
*
*
*
* Usage guide:
*
*
* Remarks:
*
*****************************************************************************/
BMG160_RETURN_FUNCTION_TYPE bmg160_set_bw(unsigned char bandwidth)
{
BMG160_RETURN_FUNCTION_TYPE comres = C_BMG160_Zero_U8X;
unsigned char v_data_u8r = C_BMG160_Zero_U8X;
unsigned char v_mode_u8r = C_BMG160_Zero_U8X;
unsigned char v_autosleepduration = C_BMG160_Zero_U8X;
if (p_bmg160 == BMG160_NULL) {
return E_BMG160_NULL_PTR;
} else {
if (bandwidth < C_BMG160_Eight_U8X) {
bmg160_get_mode(&v_mode_u8r);
if (v_mode_u8r == BMG160_MODE_ADVANCEDPOWERSAVING) {
bmg160_get_autosleepdur(&v_autosleepduration);
bmg160_set_autosleepdur(v_autosleepduration,
bandwidth);
}
comres = p_bmg160->BMG160_BUS_READ_FUNC
(p_bmg160->dev_addr,
BMG160_BW_ADDR__REG, &v_data_u8r, 1);
v_data_u8r = BMG160_SET_BITSLICE(v_data_u8r,
BMG160_BW_ADDR, bandwidth);
comres += p_bmg160->BMG160_BUS_WRITE_FUNC
(p_bmg160->dev_addr,
BMG160_BW_ADDR__REG, &v_data_u8r, 1);
} else {
comres = E_BMG160_OUT_OF_RANGE;
}
}
return comres;
}
/* Compiler Switch if applicable
#ifdef
#endif
*/
/* Compiler Switch if applicable
#ifdef
#endif
*/
/*****************************************************************************
* Description: *//**brief This API reads the status of External Trigger
* selection bits (4 and 5) of 0x12h registers
*
*
*
*
*\param unsigned char *pwu_ext_tri_sel
* Pointer to a variable passed as a parameter
*
*
*
* \return Communication Results
*
*
*****************************************************************************/
/* Scheduling:
*
*
*
* Usage guide:
*
*
* Remarks:
*
*****************************************************************************/
BMG160_RETURN_FUNCTION_TYPE bmg160_get_pmu_ext_tri_sel(
unsigned char *pwu_ext_tri_sel)
{
BMG160_RETURN_FUNCTION_TYPE comres = C_BMG160_Zero_U8X;
unsigned char v_data_u8r = C_BMG160_Zero_U8X;
if (p_bmg160 == BMG160_NULL) {
return E_BMG160_NULL_PTR;
} else {
comres = p_bmg160->BMG160_BUS_READ_FUNC(p_bmg160->dev_addr,
BMG160_MODE_LPM2_ADDR_EXT_TRI_SEL__REG, &v_data_u8r, 1);
*pwu_ext_tri_sel = BMG160_GET_BITSLICE(v_data_u8r,
BMG160_MODE_LPM2_ADDR_EXT_TRI_SEL);
}
return comres;
}
/* Compiler Switch if applicable
#ifdef
#endif
*/
/*****************************************************************************
* Description: *//**brief This API writes the External Trigger selection
* bits (4 and 5) of 0x12h registers
*
*
*
*
*\param unsigned char pwu_ext_tri_sel
* Value to be written passed as a parameter
*
*
*
* \return Communication Results
*
*
*****************************************************************************/
/* Scheduling:
*
*
*
* Usage guide:
*
*
* Remarks:
*
*****************************************************************************/
BMG160_RETURN_FUNCTION_TYPE bmg160_set_pmu_ext_tri_sel(
unsigned char pwu_ext_tri_sel)
{
BMG160_RETURN_FUNCTION_TYPE comres = C_BMG160_Zero_U8X;
unsigned char v_data_u8r = C_BMG160_Zero_U8X;
if (p_bmg160 == BMG160_NULL) {
return E_BMG160_NULL_PTR;
} else {
comres = p_bmg160->BMG160_BUS_READ_FUNC(p_bmg160->dev_addr,
BMG160_MODE_LPM2_ADDR_EXT_TRI_SEL__REG, &v_data_u8r, 1);
v_data_u8r = BMG160_SET_BITSLICE(v_data_u8r,
BMG160_MODE_LPM2_ADDR_EXT_TRI_SEL, pwu_ext_tri_sel);
comres += p_bmg160->BMG160_BUS_WRITE_FUNC(p_bmg160->dev_addr,
BMG160_MODE_LPM2_ADDR_EXT_TRI_SEL__REG, &v_data_u8r, 1);
}
return comres;
}
/* Compiler Switch if applicable
#ifdef
#endif
*/
/*****************************************************************************
* Description: *//**brief This API is used to get data high bandwidth
*
*
*
*
*\param unsigned char *high_bw : Address of high_bw
* Pointer to a variable passed as a parameter
*
*
*
* \return
*
*
*****************************************************************************/
/* Scheduling:
*
*
*
* Usage guide:
*
*
* Remarks:
*
*****************************************************************************/
BMG160_RETURN_FUNCTION_TYPE bmg160_get_high_bw(unsigned char *high_bw)
{
BMG160_RETURN_FUNCTION_TYPE comres = C_BMG160_Zero_U8X;
unsigned char v_data_u8r = C_BMG160_Zero_U8X;
if (p_bmg160 == BMG160_NULL) {
return E_BMG160_NULL_PTR;
} else {
comres = p_bmg160->BMG160_BUS_READ_FUNC(p_bmg160->dev_addr,
BMG160_RATED_HBW_ADDR_DATA_HIGHBW__REG, &v_data_u8r, 1);
*high_bw = BMG160_GET_BITSLICE(v_data_u8r,
BMG160_RATED_HBW_ADDR_DATA_HIGHBW);
}
return comres;
}
/* Compiler Switch if applicable
#ifdef
#endif
*/
/*****************************************************************************
* Description: *//**brief This API is used to set data high bandwidth
*
*
*
*
*\param unsigned char high_bw:
* Value to be written passed as a parameter
*
*
*
* \return communication results
*
*
*****************************************************************************/
/* Scheduling:
*
*
*
* Usage guide:
*
*
* Remarks:
*
*****************************************************************************/
BMG160_RETURN_FUNCTION_TYPE bmg160_set_high_bw(unsigned char high_bw)
{
BMG160_RETURN_FUNCTION_TYPE comres = C_BMG160_Zero_U8X;
unsigned char v_data_u8r = C_BMG160_Zero_U8X;
if (p_bmg160 == BMG160_NULL) {
return E_BMG160_NULL_PTR;
} else {
if (high_bw < C_BMG160_Two_U8X) {
comres = p_bmg160->BMG160_BUS_READ_FUNC
(p_bmg160->dev_addr,
BMG160_RATED_HBW_ADDR_DATA_HIGHBW__REG,
&v_data_u8r, 1);
v_data_u8r = BMG160_SET_BITSLICE(v_data_u8r,
BMG160_RATED_HBW_ADDR_DATA_HIGHBW, high_bw);
comres += p_bmg160->BMG160_BUS_WRITE_FUNC
(p_bmg160->dev_addr,
BMG160_RATED_HBW_ADDR_DATA_HIGHBW__REG,
&v_data_u8r, 1);
} else {
comres = E_BMG160_OUT_OF_RANGE;
}
}
return comres;
}
/* Compiler Switch if applicable
#ifdef
#endif
*/
/*****************************************************************************
* Description: *//**brief This API is used to get shadow dis
*
*
*
*
*\param unsigned char *shadow_dis : Address of shadow_dis
* Pointer to a variable passed as a parameter
*
*
*
* \return
*
*
*****************************************************************************/
/* Scheduling:
*
*
*
* Usage guide:
*
*
* Remarks:
*
*****************************************************************************/
BMG160_RETURN_FUNCTION_TYPE bmg160_get_shadow_dis(unsigned char *shadow_dis)
{
BMG160_RETURN_FUNCTION_TYPE comres = C_BMG160_Zero_U8X;
unsigned char v_data_u8r = C_BMG160_Zero_U8X;
if (p_bmg160 == BMG160_NULL) {
return E_BMG160_NULL_PTR;
} else {
comres = p_bmg160->BMG160_BUS_READ_FUNC(p_bmg160->dev_addr,
BMG160_RATED_HBW_ADDR_SHADOW_DIS__REG, &v_data_u8r, 1);
*shadow_dis = BMG160_GET_BITSLICE(v_data_u8r,
BMG160_RATED_HBW_ADDR_SHADOW_DIS);
}
return comres;
}
/* Compiler Switch if applicable
#ifdef
#endif
*/
/*****************************************************************************
* Description: *//**brief This API is used to set shadow dis
*
*
*
*
*\param unsigned char shadow_dis
* Value to be written passed as a parameter
*
*
*
*
* \return communication results
*
*
*****************************************************************************/
/* Scheduling:
*
*
*
* Usage guide:
*
*
* Remarks:
*
*****************************************************************************/
BMG160_RETURN_FUNCTION_TYPE bmg160_set_shadow_dis(unsigned char shadow_dis)
{
BMG160_RETURN_FUNCTION_TYPE comres = C_BMG160_Zero_U8X;
unsigned char v_data_u8r = C_BMG160_Zero_U8X;
if (p_bmg160 == BMG160_NULL) {
return E_BMG160_NULL_PTR;
} else {
if (shadow_dis < C_BMG160_Two_U8X) {
comres = p_bmg160->BMG160_BUS_READ_FUNC
(p_bmg160->dev_addr,
BMG160_RATED_HBW_ADDR_SHADOW_DIS__REG, &v_data_u8r, 1);
v_data_u8r = BMG160_SET_BITSLICE(v_data_u8r,
BMG160_RATED_HBW_ADDR_SHADOW_DIS, shadow_dis);
comres += p_bmg160->BMG160_BUS_WRITE_FUNC
(p_bmg160->dev_addr,
BMG160_RATED_HBW_ADDR_SHADOW_DIS__REG, &v_data_u8r, 1);
} else {
comres = E_BMG160_OUT_OF_RANGE;
}
}
return comres;
}
/* Compiler Switch if applicable
#ifdef
#endif
*/
/*****************************************************************************
* Description: *//**brief
* This function is used for the soft reset
* The soft reset register will be written with 0xB6.
*
*
*
* \param None
*
*
*
* \return Communication results.
*
*
*****************************************************************************/
/* Scheduling:
*
*
*
* Usage guide:
*
*
* Remarks:
*
*****************************************************************************/
BMG160_RETURN_FUNCTION_TYPE bmg160_set_soft_reset()
{
BMG160_RETURN_FUNCTION_TYPE comres = C_BMG160_Zero_U8X;
unsigned char v_SoftReset_u8r = C_BMG160_Zero_U8X;
v_SoftReset_u8r = 0xB6;
if (p_bmg160 == BMG160_NULL) {
return E_BMG160_NULL_PTR;
} else {
comres = p_bmg160->BMG160_BUS_WRITE_FUNC(p_bmg160->dev_addr,
BMG160_BGW_SOFTRESET_ADDR, &v_SoftReset_u8r, 1);
}
return comres;
}
/* Compiler Switch if applicable
#ifdef
#endif
*/
/*****************************************************************************
* Description: *//**brief This API is used to get data enable data
*
*
*
*
*\param unsigned char *data_en : Address of data_en
* Pointer to a variable passed as a parameter
*
*
*
* \return
*
*
*****************************************************************************/
/* Scheduling:
*
*
*
* Usage guide:
*
*
* Remarks:
*
*****************************************************************************/
BMG160_RETURN_FUNCTION_TYPE bmg160_get_data_enable(unsigned char *data_en)
{
BMG160_RETURN_FUNCTION_TYPE comres = C_BMG160_Zero_U8X;
unsigned char v_data_u8r = C_BMG160_Zero_U8X;
if (p_bmg160 == BMG160_NULL) {
return E_BMG160_NULL_PTR;
} else {
comres = p_bmg160->BMG160_BUS_READ_FUNC(p_bmg160->dev_addr,
BMG160_INT_ENABLE0_DATAEN__REG, &v_data_u8r, 1);
*data_en = BMG160_GET_BITSLICE(v_data_u8r,
BMG160_INT_ENABLE0_DATAEN);
}
return comres;
}
/* Compiler Switch if applicable
#ifdef
#endif
*/
/*****************************************************************************
* Description: *//**brief This API is used to set data enable data
*
*
*
*
* \param unsigned char data_en:
* Value to be written passed as a \parameter
* 0 --> Disable
* 1 --> Enable
*
*
*
* \return communication results
*
*
*****************************************************************************/
/* Scheduling:
*
*
*
* Usage guide:
*
*
* Remarks:
*
*****************************************************************************/
BMG160_RETURN_FUNCTION_TYPE bmg160_set_data_en(unsigned char data_en)
{
BMG160_RETURN_FUNCTION_TYPE comres = C_BMG160_Zero_U8X;
unsigned char v_data_u8r = C_BMG160_Zero_U8X;
if (p_bmg160 == BMG160_NULL) {
return E_BMG160_NULL_PTR;
} else {
comres = p_bmg160->BMG160_BUS_READ_FUNC
(p_bmg160->dev_addr,
BMG160_INT_ENABLE0_DATAEN__REG, &v_data_u8r, 1);
v_data_u8r = BMG160_SET_BITSLICE(v_data_u8r,
BMG160_INT_ENABLE0_DATAEN, data_en);
comres += p_bmg160->BMG160_BUS_WRITE_FUNC
(p_bmg160->dev_addr,
BMG160_INT_ENABLE0_DATAEN__REG, &v_data_u8r, 1);
}
return comres;
}
/* Compiler Switch if applicable
#ifdef
#endif
*/
/*****************************************************************************
* Description: *//**brief This API is used to get fifo enable bit
*
*
*
*
* \param unsigned char *fifo_en : Address of fifo_en
* Pointer to a variable passed as a parameter
*
*
*
* \return
*
*
*****************************************************************************/
/* Scheduling:
*
*
*
* Usage guide:
*
*
* Remarks:
*
*****************************************************************************/
BMG160_RETURN_FUNCTION_TYPE bmg160_get_fifo_enable(unsigned char *fifo_en)
{
BMG160_RETURN_FUNCTION_TYPE comres = C_BMG160_Zero_U8X;
unsigned char v_data_u8r = C_BMG160_Zero_U8X;
if (p_bmg160 == BMG160_NULL) {
return E_BMG160_NULL_PTR;
} else {
comres = p_bmg160->BMG160_BUS_READ_FUNC(p_bmg160->dev_addr,
BMG160_INT_ENABLE0_FIFOEN__REG, &v_data_u8r, 1);
*fifo_en = BMG160_GET_BITSLICE(v_data_u8r,
BMG160_INT_ENABLE0_FIFOEN);
}
return comres;
}
/* Compiler Switch if applicable
#ifdef
#endif
*/
/*****************************************************************************
* Description: *//**brief This API is used to set fifo enable bit
*
*
*
*
* \param unsigned char fifo_en:
* Value to be written passed as a parameter
* 0 --> Disable
* 1 --> Enable
*
*
*
* \return communication results
*
*
*****************************************************************************/
/* Scheduling:
*
*
*
* Usage guide:
*
*
* Remarks:
*
*****************************************************************************/
BMG160_RETURN_FUNCTION_TYPE bmg160_set_fifo_enable(unsigned char fifo_en)
{
BMG160_RETURN_FUNCTION_TYPE comres = C_BMG160_Zero_U8X;
unsigned char v_data_u8r = C_BMG160_Zero_U8X;
if (p_bmg160 == BMG160_NULL) {
return E_BMG160_NULL_PTR;
} else {
if (fifo_en < C_BMG160_Two_U8X) {
comres = p_bmg160->BMG160_BUS_READ_FUNC
(p_bmg160->dev_addr,
BMG160_INT_ENABLE0_FIFOEN__REG, &v_data_u8r, 1);
v_data_u8r = BMG160_SET_BITSLICE(v_data_u8r,
BMG160_INT_ENABLE0_FIFOEN, fifo_en);
comres += p_bmg160->BMG160_BUS_WRITE_FUNC
(p_bmg160->dev_addr,
BMG160_INT_ENABLE0_FIFOEN__REG, &v_data_u8r, 1);
} else {
comres = E_BMG160_OUT_OF_RANGE;
}
}
return comres;
}
/* Compiler Switch if applicable
#ifdef
#endif
*/
/*****************************************************************************
* Description: *//**brief This API reads the status of the Auto offset
* Enable bit
* (0x15 Reg 3rd Bit)
*
*
*
*
* \param unsigned char *offset_en
* address of a variable,
*
*
*
* \return Communication results
*
*
*****************************************************************************/
/* Scheduling:
*
*
*
* Usage guide:
*
*
* Remarks:
*
*****************************************************************************/
BMG160_RETURN_FUNCTION_TYPE bmg160_get_auto_offset_en(
unsigned char *offset_en)
{
BMG160_RETURN_FUNCTION_TYPE comres = C_BMG160_Zero_U8X;
unsigned char v_data_u8r = C_BMG160_Zero_U8X;
if (p_bmg160 == BMG160_NULL) {
return E_BMG160_NULL_PTR;
} else {
comres = p_bmg160->BMG160_BUS_READ_FUNC(p_bmg160->dev_addr,
BMG160_INT_ENABLE0_AUTO_OFFSETEN__REG, &v_data_u8r, 1);
*offset_en = BMG160_GET_BITSLICE(v_data_u8r,
BMG160_INT_ENABLE0_AUTO_OFFSETEN);
}
return comres;
}
/* Compiler Switch if applicable
#ifdef
#endif
*/
/*****************************************************************************
* Description: *//**brief This API sets the Auto offset enable bit
* (Reg 0x15 3rd Bit)
*
*
*
*
* \param unsigned char offset_en
* 0 --> Disable
* 1 --> Enable
*
* \return Communication results
*
*
*****************************************************************************/
/* Scheduling:
*
*
*
* Usage guide:
*
*
* Remarks:
*
*****************************************************************************/
BMG160_RETURN_FUNCTION_TYPE bmg160_set_auto_offset_en(unsigned char offset_en)
{
BMG160_RETURN_FUNCTION_TYPE comres = C_BMG160_Zero_U8X;
unsigned char v_data_u8r = C_BMG160_Zero_U8X;
if (p_bmg160 == BMG160_NULL) {
return E_BMG160_NULL_PTR;
} else {
comres = p_bmg160->BMG160_BUS_READ_FUNC(p_bmg160->dev_addr,
BMG160_INT_ENABLE0_AUTO_OFFSETEN__REG, &v_data_u8r, 1);
v_data_u8r = BMG160_SET_BITSLICE(v_data_u8r,
BMG160_INT_ENABLE0_AUTO_OFFSETEN, offset_en);
comres += p_bmg160->BMG160_BUS_WRITE_FUNC(p_bmg160->dev_addr,
BMG160_INT_ENABLE0_AUTO_OFFSETEN__REG, &v_data_u8r, 1);
}
return comres;
}
/* Compiler Switch if applicable
#ifdef
#endif
*/
/*****************************************************************************
* Description: *//**brief This API is used to get the output type status
*
*
*
*
* \param unsigned char channel,unsigned char *int_od
* BMG160_INT1 -> 0
* BMG160_INT2 -> 1
* int_od : open drain -> 1
* push pull -> 0
*
*
*
*
* \return
*
*
*****************************************************************************/
/* Scheduling:
*
*
*
* Usage guide:
*
*
* Remarks:
*
*****************************************************************************/
BMG160_RETURN_FUNCTION_TYPE bmg160_get_int_od(unsigned char param,
unsigned char *int_od)
{
BMG160_RETURN_FUNCTION_TYPE comres = C_BMG160_Zero_U8X;
unsigned char v_data_u8r = C_BMG160_Zero_U8X;
if (p_bmg160 == BMG160_NULL) {
return E_BMG160_NULL_PTR;
} else {
switch (param) {
case BMG160_INT1:
comres = p_bmg160->BMG160_BUS_READ_FUNC
(p_bmg160->dev_addr,
BMG160_INT_ENABLE1_IT1_OD__REG, &v_data_u8r, 1);
*int_od = BMG160_GET_BITSLICE(v_data_u8r,
BMG160_INT_ENABLE1_IT1_OD);
break;
case BMG160_INT2:
comres = p_bmg160->BMG160_BUS_READ_FUNC
(p_bmg160->dev_addr,
BMG160_INT_ENABLE1_IT2_OD__REG, &v_data_u8r, 1);
*int_od = BMG160_GET_BITSLICE(v_data_u8r,
BMG160_INT_ENABLE1_IT2_OD);
break;
default:
comres = E_BMG160_OUT_OF_RANGE;
break;
}
}
return comres;
}
/* Compiler Switch if applicable
#ifdef
#endif
*/
/*****************************************************************************
* Description: *//**brief This API is used to set the output type status
*
*
*
*
* \param unsigned char channel,unsigned char *int_od
* BMG160_INT1 -> 0
* BMG160_INT2 -> 1
* int_od : open drain -> 1
* push pull -> 0
*
*
*
* \return communication results
*
*
*****************************************************************************/
/* Scheduling:
*
*
*
* Usage guide:
*
*
* Remarks:
*
*****************************************************************************/
BMG160_RETURN_FUNCTION_TYPE bmg160_set_int_od(unsigned char param,
unsigned char int_od)
{
BMG160_RETURN_FUNCTION_TYPE comres = C_BMG160_Zero_U8X;
unsigned char v_data_u8r = C_BMG160_Zero_U8X;
if (p_bmg160 == BMG160_NULL) {
return E_BMG160_NULL_PTR;
} else {
switch (param) {
case BMG160_INT1:
comres = p_bmg160->BMG160_BUS_READ_FUNC
(p_bmg160->dev_addr,
BMG160_INT_ENABLE1_IT1_OD__REG, &v_data_u8r, 1);
v_data_u8r = BMG160_SET_BITSLICE(v_data_u8r,
BMG160_INT_ENABLE1_IT1_OD, int_od);
comres += p_bmg160->BMG160_BUS_WRITE_FUNC
(p_bmg160->dev_addr,
BMG160_INT_ENABLE1_IT1_OD__REG, &v_data_u8r, 1);
break;
case BMG160_INT2:
comres = p_bmg160->BMG160_BUS_READ_FUNC
(p_bmg160->dev_addr,
BMG160_INT_ENABLE1_IT2_OD__REG, &v_data_u8r, 1);
v_data_u8r = BMG160_SET_BITSLICE(v_data_u8r,
BMG160_INT_ENABLE1_IT2_OD, int_od);
comres += p_bmg160->BMG160_BUS_WRITE_FUNC
(p_bmg160->dev_addr,
BMG160_INT_ENABLE1_IT2_OD__REG, &v_data_u8r, 1);
break;
default:
comres = E_BMG160_OUT_OF_RANGE;
break;
}
}
return comres;
}
/* Compiler Switch if applicable
#ifdef
#endif
*/
/*****************************************************************************
* Description: *//**brief This API is used to get Active Level status
*
*
*
*
* \param unsigned char channel,unsigned char *int_lvl
* BMG160_INT1 -> 0
* BMG160_INT2 -> 1
* int_lvl : Active HI -> 1
* Active LO -> 0
*
*
*
* \return
*
*
*****************************************************************************/
/* Scheduling:
*
*
*
* Usage guide:
*
*
* Remarks:
*
*****************************************************************************/
BMG160_RETURN_FUNCTION_TYPE bmg160_get_int_lvl(unsigned char param,
unsigned char *int_lvl)
{
BMG160_RETURN_FUNCTION_TYPE comres = C_BMG160_Zero_U8X;
unsigned char v_data_u8r = C_BMG160_Zero_U8X;
if (p_bmg160 == BMG160_NULL) {
return E_BMG160_NULL_PTR;
} else {
switch (param) {
case BMG160_INT1:
comres = p_bmg160->BMG160_BUS_READ_FUNC
(p_bmg160->dev_addr,
BMG160_INT_ENABLE1_IT1_LVL__REG, &v_data_u8r, 1);
*int_lvl = BMG160_GET_BITSLICE(v_data_u8r,
BMG160_INT_ENABLE1_IT1_LVL);
break;
case BMG160_INT2:
comres = p_bmg160->BMG160_BUS_READ_FUNC
(p_bmg160->dev_addr,
BMG160_INT_ENABLE1_IT2_LVL__REG, &v_data_u8r, 1);
*int_lvl = BMG160_GET_BITSLICE(v_data_u8r,
BMG160_INT_ENABLE1_IT2_LVL);
break;
default:
comres = E_BMG160_OUT_OF_RANGE;
break;
}
}
return comres;
}
/* Compiler Switch if applicable
#ifdef
#endif
*/
/*****************************************************************************
* Description: *//**brief This API is used to set Active Level status
*
*
*
*
* \param unsigned char channel,unsigned char *int_lvl
* BMG160_INT1 -> 0
* BMG160_INT2 -> 1
* int_lvl : Active HI -> 1
* Active LO -> 0
*
*
*
* \return communication results
*
*
*****************************************************************************/
/* Scheduling:
*
*
*
* Usage guide:
*
*
* Remarks:
*
*****************************************************************************/
BMG160_RETURN_FUNCTION_TYPE bmg160_set_int_lvl(unsigned char param,
unsigned char int_lvl)
{
BMG160_RETURN_FUNCTION_TYPE comres = C_BMG160_Zero_U8X;
unsigned char v_data_u8r = C_BMG160_Zero_U8X;
if (p_bmg160 == BMG160_NULL) {
return E_BMG160_NULL_PTR;
} else {
switch (param) {
case BMG160_INT1:
comres = p_bmg160->BMG160_BUS_READ_FUNC
(p_bmg160->dev_addr,
BMG160_INT_ENABLE1_IT1_LVL__REG, &v_data_u8r, 1);
v_data_u8r = BMG160_SET_BITSLICE(v_data_u8r,
BMG160_INT_ENABLE1_IT1_LVL, int_lvl);
comres += p_bmg160->BMG160_BUS_WRITE_FUNC
(p_bmg160->dev_addr,
BMG160_INT_ENABLE1_IT1_LVL__REG, &v_data_u8r, 1);
break;
case BMG160_INT2:
comres = p_bmg160->BMG160_BUS_READ_FUNC
(p_bmg160->dev_addr,
BMG160_INT_ENABLE1_IT2_LVL__REG, &v_data_u8r, 1);
v_data_u8r = BMG160_SET_BITSLICE(v_data_u8r,
BMG160_INT_ENABLE1_IT2_LVL, int_lvl);
comres += p_bmg160->BMG160_BUS_WRITE_FUNC
(p_bmg160->dev_addr,
BMG160_INT_ENABLE1_IT2_LVL__REG, &v_data_u8r, 1);
break;
default:
comres = E_BMG160_OUT_OF_RANGE;
break;
}
}
return comres;
}
/* Compiler Switch if applicable
#ifdef
#endif
*/
/*****************************************************************************
* Description: *//**brief This API is used to get High Interrupt1
*
*
*
*
* \param unsigned char *int1_high : Address of high_bw
* Pointer to a variable passed as a parameter
*
*
*
* \return
*
*
*****************************************************************************/
/* Scheduling:
*
*
*
* Usage guide:
*
*
* Remarks:
*
*****************************************************************************/
BMG160_RETURN_FUNCTION_TYPE bmg160_get_int1_high(unsigned char *int1_high)
{
BMG160_RETURN_FUNCTION_TYPE comres = C_BMG160_Zero_U8X;
unsigned char v_data_u8r = C_BMG160_Zero_U8X;
if (p_bmg160 == BMG160_NULL) {
return E_BMG160_NULL_PTR;
} else {
comres = p_bmg160->BMG160_BUS_READ_FUNC(p_bmg160->dev_addr,
BMG160_INT_MAP_0_INT1_HIGH__REG, &v_data_u8r, 1);
*int1_high = BMG160_GET_BITSLICE(v_data_u8r,
BMG160_INT_MAP_0_INT1_HIGH);
}
return comres;
}
/* Compiler Switch if applicable
#ifdef
#endif
*/
/*****************************************************************************
* Description: *//**brief This API is used to set High Interrupt1
*
*
*
*
* \param unsigned char int1_high
* 0 -> Disable
* 1 -> Enable
*
* \return communication results
*
*
*****************************************************************************/
/* Scheduling:
*
*
*
* Usage guide:
*
*
* Remarks:
*
*****************************************************************************/
BMG160_RETURN_FUNCTION_TYPE bmg160_set_int1_high(unsigned char int1_high)
{
BMG160_RETURN_FUNCTION_TYPE comres = C_BMG160_Zero_U8X;
unsigned char v_data_u8r = C_BMG160_Zero_U8X;
if (p_bmg160 == BMG160_NULL) {
return E_BMG160_NULL_PTR;
} else {
comres = p_bmg160->BMG160_BUS_READ_FUNC(p_bmg160->dev_addr,
BMG160_INT_MAP_0_INT1_HIGH__REG, &v_data_u8r, 1);
v_data_u8r = BMG160_SET_BITSLICE(v_data_u8r,
BMG160_INT_MAP_0_INT1_HIGH, int1_high);
comres += p_bmg160->BMG160_BUS_WRITE_FUNC(p_bmg160->dev_addr,
BMG160_INT_MAP_0_INT1_HIGH__REG, &v_data_u8r, 1);
}
return comres;
}
/* Compiler Switch if applicable
#ifdef
#endif
*/
/*****************************************************************************
* Description: *//**brief This API is used to get Any Interrupt1
*
*
*
*
* \param unsigned char *int1_any : Address of high_bw
* Pointer to a variable passed as a parameter
*
*
*
* \return
*
*
*****************************************************************************/
/* Scheduling:
*
*
*
* Usage guide:
*
*
* Remarks:
*
*****************************************************************************/
BMG160_RETURN_FUNCTION_TYPE bmg160_get_int1_any(unsigned char *int1_any)
{
BMG160_RETURN_FUNCTION_TYPE comres = C_BMG160_Zero_U8X;
unsigned char v_data_u8r = C_BMG160_Zero_U8X;
if (p_bmg160 == BMG160_NULL) {
return E_BMG160_NULL_PTR;
} else {
comres = p_bmg160->BMG160_BUS_READ_FUNC(p_bmg160->dev_addr,
BMG160_INT_MAP_0_INT1_ANY__REG, &v_data_u8r, 1);
*int1_any = BMG160_GET_BITSLICE(v_data_u8r,
BMG160_INT_MAP_0_INT1_ANY);
}
return comres;
}
/* Compiler Switch if applicable
#ifdef
#endif
*/
/*****************************************************************************
* Description: *//**brief This API is used to set Any Interrupt1
*
*
*
*
*\param unsigned char int1_any
* 0 -> Disable
* 1 -> Enable
*
* \return communication results
*
*
*****************************************************************************/
/* Scheduling:
*
*
*
* Usage guide:
*
*
* Remarks:
*
*****************************************************************************/
BMG160_RETURN_FUNCTION_TYPE bmg160_set_int1_any(unsigned char int1_any)
{
BMG160_RETURN_FUNCTION_TYPE comres = C_BMG160_Zero_U8X;
unsigned char v_data_u8r = C_BMG160_Zero_U8X;
if (p_bmg160 == BMG160_NULL) {
return E_BMG160_NULL_PTR;
} else {
comres = p_bmg160->BMG160_BUS_READ_FUNC(p_bmg160->dev_addr,
BMG160_INT_MAP_0_INT1_ANY__REG, &v_data_u8r, 1);
v_data_u8r = BMG160_SET_BITSLICE(v_data_u8r,
BMG160_INT_MAP_0_INT1_ANY, int1_any);
comres += p_bmg160->BMG160_BUS_WRITE_FUNC(p_bmg160->dev_addr,
BMG160_INT_MAP_0_INT1_ANY__REG, &v_data_u8r, 1);
}
return comres;
}
/* Compiler Switch if applicable
#ifdef
#endif
*/
/*****************************************************************************
* Description: *//**brief This API is used to get data Interrupt1 and data
* Interrupt2
*
*
*
*
* \param unsigned char axis,unsigned char *int_data
* axis :
* BMG160_INT1_DATA -> 0
* BMG160_INT2_DATA -> 1
* int_data :
* Disable -> 0
* Enable -> 1
*
*
* \return
*
*
*****************************************************************************/
/* Scheduling:
*
*
*
* Usage guide:
*
*
* Remarks:
*
*****************************************************************************/
BMG160_RETURN_FUNCTION_TYPE bmg160_get_int_data(unsigned char axis,
unsigned char *int_data)
{
BMG160_RETURN_FUNCTION_TYPE comres = C_BMG160_Zero_U8X;
unsigned char v_data_u8r = C_BMG160_Zero_U8X;
if (p_bmg160 == BMG160_NULL) {
return E_BMG160_NULL_PTR;
} else {
switch (axis) {
case BMG160_INT1_DATA:
comres = p_bmg160->BMG160_BUS_READ_FUNC
(p_bmg160->dev_addr,
BMG160_MAP_1_INT1_DATA__REG, &v_data_u8r, 1);
*int_data = BMG160_GET_BITSLICE(v_data_u8r,
BMG160_MAP_1_INT1_DATA);
break;
case BMG160_INT2_DATA:
comres = p_bmg160->BMG160_BUS_READ_FUNC
(p_bmg160->dev_addr,
BMG160_MAP_1_INT2_DATA__REG, &v_data_u8r, 1);
*int_data = BMG160_GET_BITSLICE(v_data_u8r,
BMG160_MAP_1_INT2_DATA);
break;
default:
comres = E_BMG160_OUT_OF_RANGE;
break;
}
}
return comres;
}
/* Compiler Switch if applicable
#ifdef
#endif
*/
/*****************************************************************************
* Description: *//**brief This API is used to set data Interrupt1 and data
* Interrupt2
*
*
*
*
* \param unsigned char axis,unsigned char *int_data
* axis :
* BMG160_INT1_DATA -> 0
* BMG160_INT2_DATA -> 1
* int_data :
* Disable -> 0
* Enable -> 1
*
*
*
* \return communication results
*
*
*****************************************************************************/
/* Scheduling:
*
*
*
* Usage guide:
*
*
* Remarks:
*
*****************************************************************************/
BMG160_RETURN_FUNCTION_TYPE bmg160_set_int_data(unsigned char axis,
unsigned char int_data)
{
BMG160_RETURN_FUNCTION_TYPE comres = C_BMG160_Zero_U8X;
unsigned char v_data_u8r = C_BMG160_Zero_U8X;
if (p_bmg160 == BMG160_NULL) {
return E_BMG160_NULL_PTR;
} else {
switch (axis) {
case BMG160_INT1_DATA:
comres = p_bmg160->BMG160_BUS_READ_FUNC
(p_bmg160->dev_addr,
BMG160_MAP_1_INT1_DATA__REG, &v_data_u8r, 1);
v_data_u8r = BMG160_SET_BITSLICE(v_data_u8r,
BMG160_MAP_1_INT1_DATA, int_data);
comres += p_bmg160->BMG160_BUS_WRITE_FUNC
(p_bmg160->dev_addr,
BMG160_MAP_1_INT1_DATA__REG, &v_data_u8r, 1);
break;
case BMG160_INT2_DATA:
comres = p_bmg160->BMG160_BUS_READ_FUNC
(p_bmg160->dev_addr,
BMG160_MAP_1_INT2_DATA__REG, &v_data_u8r, 1);
v_data_u8r = BMG160_SET_BITSLICE(v_data_u8r,
BMG160_MAP_1_INT2_DATA, int_data);
comres += p_bmg160->BMG160_BUS_WRITE_FUNC
(p_bmg160->dev_addr,
BMG160_MAP_1_INT2_DATA__REG, &v_data_u8r, 1);
break;
default:
comres = E_BMG160_OUT_OF_RANGE;
break;
}
}
return comres;
}
/* Compiler Switch if applicable
#ifdef
#endif
*/
/*****************************************************************************
* Description: *//**brief This API is used to get fast offset and auto
* offset Interrupt2
*
*
*
*
*\param unsigned char axis,unsigned char *int2_offset
* axis :
* BMG160_AUTO_OFFSET -> 1
* BMG160_FAST_OFFSET -> 2
* int2_offset :
* Disable -> 0
* Enable -> 1
*
*
*
* \return
*
*
*****************************************************************************/
/* Scheduling:
*
*
*
* Usage guide:
*
*
* Remarks:
*
*****************************************************************************/
BMG160_RETURN_FUNCTION_TYPE bmg160_get_int2_offset(unsigned char axis,
unsigned char *int2_offset)
{
BMG160_RETURN_FUNCTION_TYPE comres = C_BMG160_Zero_U8X;
unsigned char v_data_u8r = C_BMG160_Zero_U8X;
if (p_bmg160 == BMG160_NULL) {
return E_BMG160_NULL_PTR;
} else {
switch (axis) {
case BMG160_FAST_OFFSET:
comres = p_bmg160->BMG160_BUS_READ_FUNC
(p_bmg160->dev_addr,
BMG160_MAP_1_INT2_FAST_OFFSET__REG, &v_data_u8r, 1);
*int2_offset = BMG160_GET_BITSLICE(v_data_u8r,
BMG160_MAP_1_INT2_FAST_OFFSET);
break;
case BMG160_AUTO_OFFSET:
comres = p_bmg160->BMG160_BUS_READ_FUNC
(p_bmg160->dev_addr,
BMG160_MAP_1_INT2_AUTO_OFFSET__REG, &v_data_u8r, 1);
*int2_offset = BMG160_GET_BITSLICE(v_data_u8r,
BMG160_MAP_1_INT2_AUTO_OFFSET);
break;
default:
comres = E_BMG160_OUT_OF_RANGE;
break;
}
}
return comres;
}
/* Compiler Switch if applicable
#ifdef
#endif
*/
/*****************************************************************************
* Description: *//**brief This API is used to set fast offset and auto
* offset Interrupt2
*
*
*
*
*\param unsigned char axis,unsigned char *int2_offset
* axis :
* BMG160_AUTO_OFFSET -> 1
* BMG160_FAST_OFFSET -> 2
* int2_offset :
* Disable -> 0
* Enable -> 1
*
*
*
* \return communication results
*
*
*****************************************************************************/
/* Scheduling:
*
*
*
* Usage guide:
*
*
* Remarks:
*
*****************************************************************************/
BMG160_RETURN_FUNCTION_TYPE bmg160_set_int2_offset(unsigned char axis,
unsigned char int2_offset)
{
BMG160_RETURN_FUNCTION_TYPE comres = C_BMG160_Zero_U8X;
unsigned char v_data_u8r = C_BMG160_Zero_U8X;
if (p_bmg160 == BMG160_NULL) {
return E_BMG160_NULL_PTR;
} else {
switch (axis) {
case BMG160_FAST_OFFSET:
comres = p_bmg160->BMG160_BUS_READ_FUNC
(p_bmg160->dev_addr,
BMG160_MAP_1_INT2_FAST_OFFSET__REG, &v_data_u8r, 1);
v_data_u8r = BMG160_SET_BITSLICE(v_data_u8r,
BMG160_MAP_1_INT2_FAST_OFFSET, int2_offset);
comres += p_bmg160->BMG160_BUS_WRITE_FUNC
(p_bmg160->dev_addr,
BMG160_MAP_1_INT2_FAST_OFFSET__REG, &v_data_u8r, 1);
break;
case BMG160_AUTO_OFFSET:
comres = p_bmg160->BMG160_BUS_READ_FUNC
(p_bmg160->dev_addr,
BMG160_MAP_1_INT2_AUTO_OFFSET__REG, &v_data_u8r, 1);
v_data_u8r = BMG160_SET_BITSLICE(v_data_u8r,
BMG160_MAP_1_INT2_AUTO_OFFSET, int2_offset);
comres += p_bmg160->BMG160_BUS_WRITE_FUNC
(p_bmg160->dev_addr,
BMG160_MAP_1_INT2_AUTO_OFFSET__REG, &v_data_u8r, 1);
break;
default:
comres = E_BMG160_OUT_OF_RANGE;
break;
}
}
return comres;
}
/* Compiler Switch if applicable
#ifdef
#endif
*/
/*****************************************************************************
* Description: *//**brief This API is used to get fast offset and auto
* offset Interrupt1
*
*
*
*
*\param unsigned char axis,unsigned char *int1_offset
* axis :
* BMG160_AUTO_OFFSET -> 1
* BMG160_FAST_OFFSET -> 2
* int2_offset :
* Disable -> 0
* Enable -> 1
*
*
*
* \return
*
*
*****************************************************************************/
/* Scheduling:
*
*
*
* Usage guide:
*
*
* Remarks:
*
*****************************************************************************/
BMG160_RETURN_FUNCTION_TYPE bmg160_get_int1_offset(unsigned char axis,
unsigned char *int1_offset)
{
BMG160_RETURN_FUNCTION_TYPE comres = C_BMG160_Zero_U8X;
unsigned char v_data_u8r = C_BMG160_Zero_U8X;
if (p_bmg160 == BMG160_NULL) {
return E_BMG160_NULL_PTR;
} else {
switch (axis) {
case BMG160_FAST_OFFSET:
comres = p_bmg160->BMG160_BUS_READ_FUNC
(p_bmg160->dev_addr,
BMG160_MAP_1_INT1_FAST_OFFSET__REG, &v_data_u8r, 1);
*int1_offset = BMG160_GET_BITSLICE(v_data_u8r,
BMG160_MAP_1_INT1_FAST_OFFSET);
break;
case BMG160_AUTO_OFFSET:
comres = p_bmg160->BMG160_BUS_READ_FUNC
(p_bmg160->dev_addr,
BMG160_MAP_1_INT1_AUTO_OFFSET__REG, &v_data_u8r, 1);
*int1_offset = BMG160_GET_BITSLICE(v_data_u8r,
BMG160_MAP_1_INT1_AUTO_OFFSET);
break;
default:
comres = E_BMG160_OUT_OF_RANGE;
break;
}
}
return comres;
}
/* Compiler Switch if applicable
#ifdef
#endif
*/
/*****************************************************************************
* Description: *//**brief This API is used to set fast offset and auto
* offset Interrupt1
*
*
*
*
*\param unsigned char axis,unsigned char *int1_offset
* axis :
* BMG160_AUTO_OFFSET -> 1
* BMG160_FAST_OFFSET -> 2
* int2_offset :
* Disable -> 0
* Enable -> 1
*
*
*
* \return communication results
*
*
*****************************************************************************/
/* Scheduling:
*
*
*
* Usage guide:
*
*
* Remarks:
*
*****************************************************************************/
BMG160_RETURN_FUNCTION_TYPE bmg160_set_int1_offset(unsigned char axis,
unsigned char int1_offset)
{
BMG160_RETURN_FUNCTION_TYPE comres = C_BMG160_Zero_U8X;
unsigned char v_data_u8r = C_BMG160_Zero_U8X;
if (p_bmg160 == BMG160_NULL) {
return E_BMG160_NULL_PTR;
} else {
switch (axis) {
case BMG160_FAST_OFFSET:
comres = p_bmg160->BMG160_BUS_READ_FUNC
(p_bmg160->dev_addr,
BMG160_MAP_1_INT1_FAST_OFFSET__REG, &v_data_u8r, 1);
v_data_u8r = BMG160_SET_BITSLICE(v_data_u8r,
BMG160_MAP_1_INT1_FAST_OFFSET, int1_offset);
comres += p_bmg160->BMG160_BUS_WRITE_FUNC
(p_bmg160->dev_addr,
BMG160_MAP_1_INT1_FAST_OFFSET__REG, &v_data_u8r, 1);
break;
case BMG160_AUTO_OFFSET:
comres = p_bmg160->BMG160_BUS_READ_FUNC
(p_bmg160->dev_addr,
BMG160_MAP_1_INT1_AUTO_OFFSET__REG, &v_data_u8r, 1);
v_data_u8r = BMG160_SET_BITSLICE(v_data_u8r,
BMG160_MAP_1_INT1_AUTO_OFFSET, int1_offset);
comres += p_bmg160->BMG160_BUS_WRITE_FUNC
(p_bmg160->dev_addr,
BMG160_MAP_1_INT1_AUTO_OFFSET__REG, &v_data_u8r, 1);
break;
default:
comres = E_BMG160_OUT_OF_RANGE;
break;
}
}
return comres;
}
/* Compiler Switch if applicable
#ifdef
#endif
*/
/*****************************************************************************
* Description: *//**brief This API is used to get status of FIFO Interrupt
*
*
*
*
*\param unsigned char *int_fifo : Address of int_fifo
* Pointer to a variable passed as a parameter
*
*
*
* \return
*
*
*****************************************************************************/
/* Scheduling:
*
*
*
* Usage guide:
*
*
* Remarks:
*
*****************************************************************************/
BMG160_RETURN_FUNCTION_TYPE bmg160_get_int_fifo(unsigned char *int_fifo)
{
BMG160_RETURN_FUNCTION_TYPE comres = C_BMG160_Zero_U8X;
unsigned char v_data_u8r = C_BMG160_Zero_U8X;
if (p_bmg160 == BMG160_NULL) {
return E_BMG160_NULL_PTR;
} else {
comres = p_bmg160->BMG160_BUS_READ_FUNC(p_bmg160->dev_addr,
BMG160_INT_STATUS1_FIFO_INT__REG, &v_data_u8r, 1);
*int_fifo = BMG160_GET_BITSLICE(v_data_u8r,
BMG160_INT_STATUS1_FIFO_INT);
}
return comres;
}
/* Compiler Switch if applicable
#ifdef
#endif
*/
/*****************************************************************************
* Description: *//**brief This API is used to get FIFO Interrupt2
*
*
*
*
*\param unsigned char *int_fifo
* int_fifo :
* Disable -> 0
* Enable -> 1
*
*
* \return
*
*
*****************************************************************************/
/* Scheduling:
*
*
*
* Usage guide:
*
*
* Remarks:
*
*****************************************************************************/
BMG160_RETURN_FUNCTION_TYPE bmg160_get_int2_fifo(unsigned char *int_fifo)
{
BMG160_RETURN_FUNCTION_TYPE comres = C_BMG160_Zero_U8X;
unsigned char v_data_u8r = C_BMG160_Zero_U8X;
if (p_bmg160 == BMG160_NULL) {
return E_BMG160_NULL_PTR;
} else {
comres = p_bmg160->BMG160_BUS_READ_FUNC(p_bmg160->dev_addr,
BMG160_MAP_1_INT2_FIFO__REG, &v_data_u8r, 1);
*int_fifo = BMG160_GET_BITSLICE(v_data_u8r,
BMG160_MAP_1_INT2_FIFO);
}
return comres;
}
/* Compiler Switch if applicable
#ifdef
#endif
*/
/*****************************************************************************
* Description: *//**brief This API is used to get FIFO Interrupt1
*
*
*
*
*\param unsigned char *int_fifo
* int_fifo :
* Disable -> 0
* Enable -> 1
*
*
*
* \return
*
*
*****************************************************************************/
/* Scheduling:
*
*
*
* Usage guide:
*
*
* Remarks:
*
*****************************************************************************/
BMG160_RETURN_FUNCTION_TYPE bmg160_get_int1_fifo(unsigned char *int_fifo)
{
BMG160_RETURN_FUNCTION_TYPE comres = C_BMG160_Zero_U8X;
unsigned char v_data_u8r = C_BMG160_Zero_U8X;
if (p_bmg160 == BMG160_NULL) {
return E_BMG160_NULL_PTR;
} else {
comres = p_bmg160->BMG160_BUS_READ_FUNC(p_bmg160->dev_addr,
BMG160_MAP_1_INT1_FIFO__REG, &v_data_u8r, 1);
*int_fifo = BMG160_GET_BITSLICE(v_data_u8r,
BMG160_MAP_1_INT1_FIFO);
}
return comres;
}
/* Compiler Switch if applicable
#ifdef
#endif
*/
/*****************************************************************************
* Description: *//**brief
*
*
*
*
* \param
*
*
*
* \return
*
*
*****************************************************************************/
/* Scheduling:
*
*
*
* Usage guide:
*
*
* Remarks:
*
*****************************************************************************/
BMG160_RETURN_FUNCTION_TYPE bmg160_set_int_fifo(unsigned char axis,
unsigned char int_fifo)
{
BMG160_RETURN_FUNCTION_TYPE comres = C_BMG160_Zero_U8X;
unsigned char v_data_u8r = C_BMG160_Zero_U8X;
if (p_bmg160 == BMG160_NULL) {
return E_BMG160_NULL_PTR;
} else {
switch (axis) {
case BMG160_INT1:
comres = p_bmg160->BMG160_BUS_READ_FUNC
(p_bmg160->dev_addr,
BMG160_MAP_1_INT1_FIFO__REG, &v_data_u8r, 1);
v_data_u8r = BMG160_SET_BITSLICE(v_data_u8r,
BMG160_MAP_1_INT1_FIFO, int_fifo);
comres += p_bmg160->BMG160_BUS_WRITE_FUNC
(p_bmg160->dev_addr,
BMG160_MAP_1_INT1_FIFO__REG, &v_data_u8r, 1);
break;
case BMG160_INT2:
comres = p_bmg160->BMG160_BUS_READ_FUNC
(p_bmg160->dev_addr,
BMG160_MAP_1_INT2_FIFO__REG, &v_data_u8r, 1);
v_data_u8r = BMG160_SET_BITSLICE(v_data_u8r,
BMG160_MAP_1_INT2_FIFO, int_fifo);
comres += p_bmg160->BMG160_BUS_WRITE_FUNC
(p_bmg160->dev_addr,
BMG160_MAP_1_INT2_FIFO__REG, &v_data_u8r, 1);
break;
default:
comres = E_BMG160_OUT_OF_RANGE;
break;
}
}
return comres;
}
/* Compiler Switch if applicable
#ifdef
#endif
*/
/*****************************************************************************
* Description: *//**brief This API is used to set FIFO Interrupt1
*
*
*
*
*\param unsigned char *fifo_int1
* fifo_int1 :
* Disable -> 0
* Enable -> 1
*
*
*
* \return communication results
*
*
*****************************************************************************/
/* Scheduling:
*
*
*
* Usage guide:
*
*
* Remarks:
*
*****************************************************************************/
BMG160_RETURN_FUNCTION_TYPE bmg160_set_int1_fifo(unsigned char fifo_int1)
{
BMG160_RETURN_FUNCTION_TYPE comres = C_BMG160_Zero_U8X;
unsigned char v_data_u8r = C_BMG160_Zero_U8X;
if (p_bmg160 == BMG160_NULL) {
return E_BMG160_NULL_PTR;
} else {
if (fifo_int1 < C_BMG160_Two_U8X) {
comres = p_bmg160->BMG160_BUS_READ_FUNC
(p_bmg160->dev_addr,
BMG160_MAP_1_INT1_FIFO__REG, &v_data_u8r, 1);
v_data_u8r = BMG160_SET_BITSLICE(v_data_u8r,
BMG160_MAP_1_INT1_FIFO, fifo_int1);
comres += p_bmg160->BMG160_BUS_WRITE_FUNC
(p_bmg160->dev_addr,
BMG160_MAP_1_INT1_FIFO__REG, &v_data_u8r, 1);
} else {
comres = E_BMG160_OUT_OF_RANGE;
}
}
return comres;
}
/* Compiler Switch if applicable
#ifdef
#endif
*/
/*****************************************************************************
* Description: *//**brief This API is used to set FIFO Interrupt2
*
*
*
*
*\param unsigned char *fifo_int2
* fifo_int2 :
* Disable -> 0
* Enable -> 1
*
*
*
* \return communication results
*
*
*****************************************************************************/
/* Scheduling:
*
*
*
* Usage guide:
*
*
* Remarks:
*
*****************************************************************************/
BMG160_RETURN_FUNCTION_TYPE bmg160_set_int2_fifo(unsigned char fifo_int2)
{
BMG160_RETURN_FUNCTION_TYPE comres = C_BMG160_Zero_U8X;
unsigned char v_data_u8r = C_BMG160_Zero_U8X;
if (p_bmg160 == BMG160_NULL) {
return E_BMG160_NULL_PTR;
} else {
if (fifo_int2 < C_BMG160_Two_U8X) {
comres = p_bmg160->BMG160_BUS_READ_FUNC
(p_bmg160->dev_addr,
BMG160_MAP_1_INT2_FIFO__REG, &v_data_u8r, 1);
v_data_u8r = BMG160_SET_BITSLICE(v_data_u8r,
BMG160_MAP_1_INT2_FIFO, fifo_int2);
comres = p_bmg160->BMG160_BUS_WRITE_FUNC
(p_bmg160->dev_addr,
BMG160_MAP_1_INT2_FIFO__REG, &v_data_u8r, 1);
} else {
comres = E_BMG160_OUT_OF_RANGE;
}
}
return comres;
}
/* Compiler Switch if applicable
#ifdef
#endif
*/
/*****************************************************************************
* Description: *//**brief This API is used to get High Interrupt2
*
*
*
*
*\param unsigned char *int2_high : Address of int2_high
* Pointer to a variable passed as a parameter
*
*
*
* \return
*
*
*****************************************************************************/
/* Scheduling:
*
*
*
* Usage guide:
*
*
* Remarks:
*
*****************************************************************************/
BMG160_RETURN_FUNCTION_TYPE bmg160_get_int2_high(unsigned char *int2_high)
{
BMG160_RETURN_FUNCTION_TYPE comres = C_BMG160_Zero_U8X;
unsigned char v_data_u8r = C_BMG160_Zero_U8X;
if (p_bmg160 == BMG160_NULL) {
return E_BMG160_NULL_PTR;
} else {
comres = p_bmg160->BMG160_BUS_READ_FUNC(p_bmg160->dev_addr,
BMG160_INT_MAP_2_INT2_HIGH__REG, &v_data_u8r, 1);
*int2_high = BMG160_GET_BITSLICE(v_data_u8r,
BMG160_INT_MAP_2_INT2_HIGH);
}
return comres;
}
/* Compiler Switch if applicable
#ifdef
#endif
*/
/*****************************************************************************
* Description: *//**brief This API is used to get High Interrupt2
*
*
*
*
*\param unsigned char int2_high
* 0 -> Disable
* 1 -> Enable
*
*
*
* \return communication results
*
*
*****************************************************************************/
/* Scheduling:
*
*
*
* Usage guide:
*
*
* Remarks:
*
*****************************************************************************/
BMG160_RETURN_FUNCTION_TYPE bmg160_set_int2_high(unsigned char int2_high)
{
BMG160_RETURN_FUNCTION_TYPE comres = C_BMG160_Zero_U8X;
unsigned char v_data_u8r = C_BMG160_Zero_U8X;
if (p_bmg160 == BMG160_NULL) {
return E_BMG160_NULL_PTR;
} else {
comres = p_bmg160->BMG160_BUS_READ_FUNC(p_bmg160->dev_addr,
BMG160_INT_MAP_2_INT2_HIGH__REG, &v_data_u8r, 1);
v_data_u8r = BMG160_SET_BITSLICE(v_data_u8r,
BMG160_INT_MAP_2_INT2_HIGH, int2_high);
comres += p_bmg160->BMG160_BUS_WRITE_FUNC(p_bmg160->dev_addr,
BMG160_INT_MAP_2_INT2_HIGH__REG, &v_data_u8r, 1);
}
return comres;
}
/* Compiler Switch if applicable
#ifdef
#endif
*/
/*****************************************************************************
* Description: *//**brief This API is used to get Any Interrupt2
*
*
*
*
*\param unsigned char *int2_any : Address of int2_any
* Pointer to a variable passed as a parameter
*
*
*
* \return
*
*
*****************************************************************************/
/* Scheduling:
*
*
*
* Usage guide:
*
*
* Remarks:
*
*****************************************************************************/
BMG160_RETURN_FUNCTION_TYPE bmg160_get_int2_any(unsigned char *int2_any)
{
BMG160_RETURN_FUNCTION_TYPE comres = C_BMG160_Zero_U8X;
unsigned char v_data_u8r = C_BMG160_Zero_U8X;
if (p_bmg160 == BMG160_NULL) {
return E_BMG160_NULL_PTR;
} else {
comres = p_bmg160->BMG160_BUS_READ_FUNC(p_bmg160->dev_addr,
BMG160_INT_MAP_2_INT2_ANY__REG, &v_data_u8r, 1);
*int2_any = BMG160_GET_BITSLICE(v_data_u8r,
BMG160_INT_MAP_2_INT2_ANY);
}
return comres;
}
/* Compiler Switch if applicable
#ifdef
#endif
*/
/*****************************************************************************
* Description: *//**brief This API is used to set Any Interrupt2
*
*
*
*
*\param unsigned char int2_any
* 0 -> Disable
* 1 -> Enable
*
*
*
*
* \return communication results
*
*
*****************************************************************************/
/* Scheduling:
*
*
*
* Usage guide:
*
*
* Remarks:
*
*****************************************************************************/
BMG160_RETURN_FUNCTION_TYPE bmg160_set_int2_any(unsigned char int2_any)
{
BMG160_RETURN_FUNCTION_TYPE comres = C_BMG160_Zero_U8X;
unsigned char v_data_u8r = C_BMG160_Zero_U8X;
if (p_bmg160 == BMG160_NULL) {
return E_BMG160_NULL_PTR;
} else {
comres = p_bmg160->BMG160_BUS_READ_FUNC(p_bmg160->dev_addr,
BMG160_INT_MAP_2_INT2_ANY__REG, &v_data_u8r, 1);
v_data_u8r = BMG160_SET_BITSLICE(v_data_u8r,
BMG160_INT_MAP_2_INT2_ANY, int2_any);
comres += p_bmg160->BMG160_BUS_WRITE_FUNC(p_bmg160->dev_addr,
BMG160_INT_MAP_2_INT2_ANY__REG, &v_data_u8r, 1);
}
return comres;
}
/* Compiler Switch if applicable
#ifdef
#endif
*/
/*****************************************************************************
* Description: *//**brief This API is used to get slow offset and fast
* offset unfilt data
*
*
*
*\param unsigned char param,unsigned char *offset_unfilt
* param :
* BMG160_SLOW_OFFSET -> 0
* BMG160_FAST_OFFSET -> 2
* offset_unfilt: Enable -> 1
* Disable -> 0
*
*
*
* \return
*
*
*****************************************************************************/
/* Scheduling:
*
*
*
* Usage guide:
*
*
* Remarks:
*
*****************************************************************************/
BMG160_RETURN_FUNCTION_TYPE bmg160_get_offset_unfilt(unsigned char param,
unsigned char *offset_unfilt)
{
BMG160_RETURN_FUNCTION_TYPE comres = C_BMG160_Zero_U8X;
unsigned char v_data_u8r = C_BMG160_Zero_U8X;
if (p_bmg160 == BMG160_NULL) {
return E_BMG160_NULL_PTR;
} else {
switch (param) {
case BMG160_SLOW_OFFSET:
comres = p_bmg160->BMG160_BUS_READ_FUNC
(p_bmg160->dev_addr,
BMG160_INT_0_ADDR_SLOW_OFFSET_UNFILT__REG,
&v_data_u8r, 1);
*offset_unfilt = BMG160_GET_BITSLICE(v_data_u8r,
BMG160_INT_0_ADDR_SLOW_OFFSET_UNFILT);
break;
case BMG160_FAST_OFFSET:
comres = p_bmg160->BMG160_BUS_READ_FUNC
(p_bmg160->dev_addr,
BMG160_INT_1_ADDR_FAST_OFFSET_UNFILT__REG,
&v_data_u8r, 1);
*offset_unfilt = BMG160_GET_BITSLICE(v_data_u8r,
BMG160_INT_1_ADDR_FAST_OFFSET_UNFILT);
break;
default:
comres = E_BMG160_OUT_OF_RANGE;
break;
}
}
return comres;
}
/* Compiler Switch if applicable
#ifdef
#endif
*/
/*****************************************************************************
* Description: *//**brief This API is used to set slow offset and fast
* offset unfilt data
*
*
*
*
*\param unsigned char param,unsigned char *offset_unfilt
* param :
* BMG160_SLOW_OFFSET -> 0
* BMG160_FAST_OFFSET -> 2
* offset_unfilt: Enable -> 1
* Disable -> 0
*
*
*
* \return
*
*
*****************************************************************************/
/* Scheduling:
*
*
*
* Usage guide:
*
*
* Remarks:
*
*****************************************************************************/
BMG160_RETURN_FUNCTION_TYPE bmg160_set_offset_unfilt(unsigned char param,
unsigned char offset_unfilt)
{
BMG160_RETURN_FUNCTION_TYPE comres = C_BMG160_Zero_U8X;
unsigned char v_data_u8r = C_BMG160_Zero_U8X;
if (p_bmg160 == BMG160_NULL) {
return E_BMG160_NULL_PTR;
} else {
switch (param) {
case BMG160_SLOW_OFFSET:
comres = p_bmg160->BMG160_BUS_READ_FUNC
(p_bmg160->dev_addr,
BMG160_INT_0_ADDR_SLOW_OFFSET_UNFILT__REG,
&v_data_u8r, 1);
v_data_u8r = BMG160_SET_BITSLICE(v_data_u8r,
BMG160_INT_0_ADDR_SLOW_OFFSET_UNFILT, offset_unfilt);
comres += p_bmg160->BMG160_BUS_WRITE_FUNC
(p_bmg160->dev_addr,
BMG160_INT_0_ADDR_SLOW_OFFSET_UNFILT__REG,
&v_data_u8r, 1);
break;
case BMG160_FAST_OFFSET:
comres = p_bmg160->BMG160_BUS_READ_FUNC
(p_bmg160->dev_addr,
BMG160_INT_1_ADDR_FAST_OFFSET_UNFILT__REG,
&v_data_u8r, 1);
v_data_u8r = BMG160_SET_BITSLICE(v_data_u8r,
BMG160_INT_1_ADDR_FAST_OFFSET_UNFILT, offset_unfilt);
comres += p_bmg160->BMG160_BUS_WRITE_FUNC
(p_bmg160->dev_addr,
BMG160_INT_1_ADDR_FAST_OFFSET_UNFILT__REG,
&v_data_u8r, 1);
break;
default:
comres = E_BMG160_OUT_OF_RANGE;
break;
}
}
return comres;
}
/* Compiler Switch if applicable
#ifdef
#endif
*/
/*****************************************************************************
* Description: *//**brief This API is used to get Tap, High, Constant, Any,
* Shake unfilt data
*
*
*
*
*\param unsigned char param,unsigned char *unfilt_data
* param :
*
* BMG160_HIGH_UNFILT_DATA -> 1
* BMG160_ANY_UNFILT_DATA -> 3
*
* unfilt_data: Enable -> 1
* Disable -> 0
*
*
*
* \return
*
*
*****************************************************************************/
/* Scheduling:
*
*
*
* Usage guide:
*
*
* Remarks:
*
*****************************************************************************/
BMG160_RETURN_FUNCTION_TYPE bmg160_get_unfilt_data(unsigned char param,
unsigned char *unfilt_data)
{
BMG160_RETURN_FUNCTION_TYPE comres = C_BMG160_Zero_U8X;
unsigned char v_data_u8r = C_BMG160_Zero_U8X;
if (p_bmg160 == BMG160_NULL) {
return E_BMG160_NULL_PTR;
} else {
switch (param) {
case BMG160_HIGH_UNFILT_DATA:
comres = p_bmg160->BMG160_BUS_READ_FUNC
(p_bmg160->dev_addr,
BMG160_INT_0_ADDR_HIGH_UNFILT_DATA__REG,
&v_data_u8r, 1);
*unfilt_data = BMG160_GET_BITSLICE(v_data_u8r,
BMG160_INT_0_ADDR_HIGH_UNFILT_DATA);
break;
case BMG160_ANY_UNFILT_DATA:
comres = p_bmg160->BMG160_BUS_READ_FUNC
(p_bmg160->dev_addr,
BMG160_INT_0_ADDR_ANY_UNFILT_DATA__REG, &v_data_u8r, 1);
*unfilt_data = BMG160_GET_BITSLICE(v_data_u8r,
BMG160_INT_0_ADDR_ANY_UNFILT_DATA);
break;
default:
comres = E_BMG160_OUT_OF_RANGE;
break;
}
}
return comres;
}
/* Compiler Switch if applicable
#ifdef
#endif
*/
/*****************************************************************************
* Description: *//**brief This API is used to set Tap, High, Constant, Any,
* Shake unfilt data
*
*
*
*
*\param unsigned char param,unsigned char *unfilt_data
* param :
*
* BMG160_HIGH_UNFILT_DATA -> 1
* BMG160_ANY_UNFILT_DATA -> 3
*
* unfilt_data: Enable -> 1
* Disable -> 0
*
*
*
* \return communication results
*
*
*****************************************************************************/
/* Scheduling:
*
*
*
* Usage guide:
*
*
* Remarks:
*
*****************************************************************************/
BMG160_RETURN_FUNCTION_TYPE bmg160_set_unfilt_data(unsigned char param,
unsigned char unfilt_data)
{
BMG160_RETURN_FUNCTION_TYPE comres = C_BMG160_Zero_U8X;
unsigned char v_data_u8r = C_BMG160_Zero_U8X;
if (p_bmg160 == BMG160_NULL) {
return E_BMG160_NULL_PTR;
} else {
switch (param) {
case BMG160_HIGH_UNFILT_DATA:
comres = p_bmg160->BMG160_BUS_READ_FUNC
(p_bmg160->dev_addr,
BMG160_INT_0_ADDR_HIGH_UNFILT_DATA__REG,
&v_data_u8r, 1);
v_data_u8r = BMG160_SET_BITSLICE(v_data_u8r,
BMG160_INT_0_ADDR_HIGH_UNFILT_DATA, unfilt_data);
comres += p_bmg160->BMG160_BUS_WRITE_FUNC
(p_bmg160->dev_addr,
BMG160_INT_0_ADDR_HIGH_UNFILT_DATA__REG,
&v_data_u8r, 1);
break;
case BMG160_ANY_UNFILT_DATA:
comres = p_bmg160->BMG160_BUS_READ_FUNC
(p_bmg160->dev_addr,
BMG160_INT_0_ADDR_ANY_UNFILT_DATA__REG, &v_data_u8r, 1);
v_data_u8r = BMG160_SET_BITSLICE(v_data_u8r,
BMG160_INT_0_ADDR_ANY_UNFILT_DATA, unfilt_data);
comres += p_bmg160->BMG160_BUS_WRITE_FUNC
(p_bmg160->dev_addr,
BMG160_INT_0_ADDR_ANY_UNFILT_DATA__REG, &v_data_u8r, 1);
break;
default:
comres = E_BMG160_OUT_OF_RANGE;
break;
}
}
return comres;
}
/* Compiler Switch if applicable
#ifdef
#endif
*/
/*****************************************************************************
* Description: *//**brief This API is used to get Any Threshold
*
*
*
*
*\param unsigned char *any_th : Address of any_th
* Pointer to a variable passed as a parameter
*
*
*
* \return
*
*
*****************************************************************************/
/* Scheduling:
*
*
*
* Usage guide:
*
*
* Remarks:
*
*****************************************************************************/
BMG160_RETURN_FUNCTION_TYPE bmg160_get_any_th(unsigned char *any_th)
{
BMG160_RETURN_FUNCTION_TYPE comres = C_BMG160_Zero_U8X;
unsigned char v_data_u8r = C_BMG160_Zero_U8X;
if (p_bmg160 == BMG160_NULL) {
return E_BMG160_NULL_PTR;
} else {
comres = p_bmg160->BMG160_BUS_READ_FUNC(p_bmg160->dev_addr,
BMG160_INT_1_ADDR_ANY_TH__REG, &v_data_u8r, 1);
*any_th = BMG160_GET_BITSLICE(v_data_u8r,
BMG160_INT_1_ADDR_ANY_TH);
}
return comres;
}
/* Compiler Switch if applicable
#ifdef
#endif
*/
/*****************************************************************************
* Description: *//**brief This API is used to set Any Threshold
*
*
*
*
*\param unsigned char any_th:
* Value to be written passed as a parameter
*
*
*
* \return communication results
*
*
*****************************************************************************/
/* Scheduling:
*
*
*
* Usage guide:
*
*
* Remarks:
*
*****************************************************************************/
BMG160_RETURN_FUNCTION_TYPE bmg160_set_any_th(unsigned char any_th)
{
BMG160_RETURN_FUNCTION_TYPE comres = C_BMG160_Zero_U8X;
unsigned char v_data_u8r = C_BMG160_Zero_U8X;
if (p_bmg160 == BMG160_NULL) {
return E_BMG160_NULL_PTR;
} else {
comres = p_bmg160->BMG160_BUS_READ_FUNC(p_bmg160->dev_addr,
BMG160_INT_1_ADDR_ANY_TH__REG, &v_data_u8r, 1);
v_data_u8r = BMG160_SET_BITSLICE(v_data_u8r,
BMG160_INT_1_ADDR_ANY_TH, any_th);
comres += p_bmg160->BMG160_BUS_WRITE_FUNC(p_bmg160->dev_addr,
BMG160_INT_1_ADDR_ANY_TH__REG, &v_data_u8r, 1);
}
return comres;
}
/* Compiler Switch if applicable
#ifdef
#endif
*/
/*****************************************************************************
* Description: *//**brief This API is used to get Awake Duration
*
*
*
*
*\param unsigned char *awake_dur : Address of awake_dur
* Pointer to a variable passed as a parameter
*
*
*
* \return
*
*
*****************************************************************************/
/* Scheduling:
*
*
*
* Usage guide:
*
*
* Remarks:
*
*****************************************************************************/
BMG160_RETURN_FUNCTION_TYPE bmg160_get_awake_dur(unsigned char *awake_dur)
{
BMG160_RETURN_FUNCTION_TYPE comres = C_BMG160_Zero_U8X;
unsigned char v_data_u8r = C_BMG160_Zero_U8X;
if (p_bmg160 == BMG160_NULL) {
return E_BMG160_NULL_PTR;
} else {
comres = p_bmg160->BMG160_BUS_READ_FUNC(p_bmg160->dev_addr,
BMG160_INT_2_ADDR_AWAKE_DUR__REG, &v_data_u8r, 1);
*awake_dur = BMG160_GET_BITSLICE(v_data_u8r,
BMG160_INT_2_ADDR_AWAKE_DUR);
}
return comres;
}
/* Compiler Switch if applicable
#ifdef
#endif
*/
/*****************************************************************************
* Description: *//**brief This API is used to set Awake Duration
*
*
*
*
*\param unsigned char awake_dur:
* Value to be written passed as a parameter
*
*
*
* \return communication results
*
*
*****************************************************************************
* Scheduling:
*
*
*
* Usage guide:
*
*
* Remarks:
*
*****************************************************************************/
BMG160_RETURN_FUNCTION_TYPE bmg160_set_awake_dur(unsigned char awake_dur)
{
BMG160_RETURN_FUNCTION_TYPE comres = C_BMG160_Zero_U8X;
unsigned char v_data_u8r = C_BMG160_Zero_U8X;
if (p_bmg160 == BMG160_NULL) {
return E_BMG160_NULL_PTR;
} else {
comres = p_bmg160->BMG160_BUS_READ_FUNC(p_bmg160->dev_addr,
BMG160_INT_2_ADDR_AWAKE_DUR__REG, &v_data_u8r, 1);
v_data_u8r = BMG160_SET_BITSLICE(v_data_u8r,
BMG160_INT_2_ADDR_AWAKE_DUR, awake_dur);
comres += p_bmg160->BMG160_BUS_WRITE_FUNC(p_bmg160->dev_addr,
BMG160_INT_2_ADDR_AWAKE_DUR__REG, &v_data_u8r, 1);
}
return comres;
}
/* Compiler Switch if applicable
#ifdef
#endif
*/
/*****************************************************************************
* Description: *//**brief This API is used to get Any Duration Sample
*
*
*
*
*\param unsigned char *dursample : Address of dursample
* Pointer to a variable passed as a parameter
*
*
*
* \return
*
*
*****************************************************************************/
/* Scheduling:
*
*
*
* Usage guide:
*
*
* Remarks:
*
*****************************************************************************/
BMG160_RETURN_FUNCTION_TYPE bmg160_get_any_dursample(unsigned char *dursample)
{
BMG160_RETURN_FUNCTION_TYPE comres = C_BMG160_Zero_U8X;
unsigned char v_data_u8r = C_BMG160_Zero_U8X;
if (p_bmg160 == BMG160_NULL) {
return E_BMG160_NULL_PTR;
} else {
comres = p_bmg160->BMG160_BUS_READ_FUNC(p_bmg160->dev_addr,
BMG160_INT_2_ADDR_ANY_DURSAMPLE__REG, &v_data_u8r, 1);
*dursample = BMG160_GET_BITSLICE(v_data_u8r,
BMG160_INT_2_ADDR_ANY_DURSAMPLE);
}
return comres;
}
/* Compiler Switch if applicable
#ifdef
#endif
*/
/*****************************************************************************
* Description: *//**brief This API is used to set Any Duration Sample
*
*
*
*
*\param unsigned char dursample:
* Value to be written passed as a parameter
*
*
*
* \return communication results
*
*
*****************************************************************************/
/* Scheduling:
*
*
*
* Usage guide:
*
*
* Remarks:
*
*****************************************************************************/
BMG160_RETURN_FUNCTION_TYPE bmg160_set_any_dursample(unsigned char dursample)
{
BMG160_RETURN_FUNCTION_TYPE comres = C_BMG160_Zero_U8X;
unsigned char v_data_u8r = C_BMG160_Zero_U8X;
if (p_bmg160 == BMG160_NULL) {
return E_BMG160_NULL_PTR;
} else {
comres = p_bmg160->BMG160_BUS_READ_FUNC(p_bmg160->dev_addr,
BMG160_INT_2_ADDR_ANY_DURSAMPLE__REG, &v_data_u8r, 1);
v_data_u8r = BMG160_SET_BITSLICE(v_data_u8r,
BMG160_INT_2_ADDR_ANY_DURSAMPLE, dursample);
comres += p_bmg160->BMG160_BUS_WRITE_FUNC(p_bmg160->dev_addr,
BMG160_INT_2_ADDR_ANY_DURSAMPLE__REG, &v_data_u8r, 1);
}
return comres;
}
/* Compiler Switch if applicable
#ifdef
#endif
*/
/*****************************************************************************
* Description: *//**brief This API is used to get the status of Any Enable
* Channel X,Y,Z
*
*
*
*
*\param unsigned char channel,unsigned char *data
* channel :
* BMG160_X_AXIS -> 0
* BMG160_Y_AXIS -> 1
* BMG160_Z_AXIS -> 2
* data :
* Enable -> 1
* disable -> 0
*
* \return
*
*
*****************************************************************************/
/* Scheduling:
*
*
*
* Usage guide:
*
*
* Remarks:
*
*****************************************************************************/
BMG160_RETURN_FUNCTION_TYPE bmg160_get_any_en_ch(unsigned char channel,
unsigned char *data)
{
BMG160_RETURN_FUNCTION_TYPE comres = C_BMG160_Zero_U8X;
unsigned char v_data_u8r = C_BMG160_Zero_U8X;
if (p_bmg160 == BMG160_NULL) {
return E_BMG160_NULL_PTR;
} else {
switch (channel) {
case BMG160_X_AXIS:
comres = p_bmg160->BMG160_BUS_READ_FUNC
(p_bmg160->dev_addr,
BMG160_INT_2_ADDR_ANY_EN_X__REG, &v_data_u8r, 1);
*data = BMG160_GET_BITSLICE(v_data_u8r,
BMG160_INT_2_ADDR_ANY_EN_X);
break;
case BMG160_Y_AXIS:
comres = p_bmg160->BMG160_BUS_READ_FUNC
(p_bmg160->dev_addr,
BMG160_INT_2_ADDR_ANY_EN_Y__REG, &v_data_u8r, 1);
*data = BMG160_GET_BITSLICE(v_data_u8r,
BMG160_INT_2_ADDR_ANY_EN_Y);
break;
case BMG160_Z_AXIS:
comres = p_bmg160->BMG160_BUS_READ_FUNC
(p_bmg160->dev_addr,
BMG160_INT_2_ADDR_ANY_EN_Z__REG, &v_data_u8r, 1);
*data = BMG160_GET_BITSLICE(v_data_u8r,
BMG160_INT_2_ADDR_ANY_EN_Z);
break;
default:
comres = E_BMG160_OUT_OF_RANGE;
break;
}
}
return comres;
}
/* Compiler Switch if applicable
#ifdef
#endif
*/
/*****************************************************************************
* Description: *//**brief This API is used to set the status of Any Enable
* Channel X,Y,Z
*
*
*
*
*\param unsigned char channel,unsigned char *data
* channel :
* BMG160_X_AXIS -> 0
* BMG160_Y_AXIS -> 1
* BMG160_Z_AXIS -> 2
* data :
* Enable -> 1
* disable -> 0
*
*
*
* \return communication results
*
*
*****************************************************************************/
/* Scheduling:
*
*
*
* Usage guide:
*
*
* Remarks:
*
*****************************************************************************/
BMG160_RETURN_FUNCTION_TYPE bmg160_set_any_en_ch(unsigned char channel,
unsigned char data)
{
BMG160_RETURN_FUNCTION_TYPE comres = C_BMG160_Zero_U8X;
unsigned char v_data_u8r = C_BMG160_Zero_U8X;
if (p_bmg160 == BMG160_NULL) {
return E_BMG160_NULL_PTR;
} else {
switch (channel) {
case BMG160_X_AXIS:
comres = p_bmg160->BMG160_BUS_READ_FUNC
(p_bmg160->dev_addr,
BMG160_INT_2_ADDR_ANY_EN_X__REG, &v_data_u8r, 1);
v_data_u8r = BMG160_SET_BITSLICE(v_data_u8r,
BMG160_INT_2_ADDR_ANY_EN_X, data);
comres += p_bmg160->BMG160_BUS_WRITE_FUNC
(p_bmg160->dev_addr,
BMG160_INT_2_ADDR_ANY_EN_X__REG, &v_data_u8r, 1);
break;
case BMG160_Y_AXIS:
comres = p_bmg160->BMG160_BUS_READ_FUNC
(p_bmg160->dev_addr,
BMG160_INT_2_ADDR_ANY_EN_Y__REG, &v_data_u8r, 1);
v_data_u8r = BMG160_SET_BITSLICE(v_data_u8r,
BMG160_INT_2_ADDR_ANY_EN_Y, data);
comres += p_bmg160->BMG160_BUS_WRITE_FUNC
(p_bmg160->dev_addr,
BMG160_INT_2_ADDR_ANY_EN_Y__REG, &v_data_u8r, 1);
break;
case BMG160_Z_AXIS:
comres = p_bmg160->BMG160_BUS_READ_FUNC
(p_bmg160->dev_addr,
BMG160_INT_2_ADDR_ANY_EN_Z__REG, &v_data_u8r, 1);
v_data_u8r = BMG160_SET_BITSLICE(v_data_u8r,
BMG160_INT_2_ADDR_ANY_EN_Z, data);
comres += p_bmg160->BMG160_BUS_WRITE_FUNC
(p_bmg160->dev_addr,
BMG160_INT_2_ADDR_ANY_EN_Z__REG, &v_data_u8r, 1);
break;
default:
comres = E_BMG160_OUT_OF_RANGE;
break;
}
}
return comres;
}
/* Compiler Switch if applicable
#ifdef
#endif
*/
/*****************************************************************************
* Description: *//**brief This API is used to get the status of FIFO WM
* Enable
*
*
*
*
*\param unsigned char *fifo_wn_en
* Enable -> 1
* Disable -> 0
*
*
* \return
*
*
*****************************************************************************/
/* Scheduling:
*
*
*
* Usage guide:
*
*
* Remarks:
*
*****************************************************************************/
BMG160_RETURN_FUNCTION_TYPE bmg160_get_fifo_watermark_enable(
unsigned char *fifo_wn_en)
{
BMG160_RETURN_FUNCTION_TYPE comres = C_BMG160_Zero_U8X;
unsigned char v_data_u8r = C_BMG160_Zero_U8X;
if (p_bmg160 == BMG160_NULL) {
return E_BMG160_NULL_PTR;
} else {
comres = p_bmg160->BMG160_BUS_READ_FUNC(p_bmg160->dev_addr,
BMG160_INT_4_FIFO_WM_EN__REG, &v_data_u8r, 1);
*fifo_wn_en = BMG160_GET_BITSLICE(v_data_u8r,
BMG160_INT_4_FIFO_WM_EN);
}
return comres;
}
/* Compiler Switch if applicable
#ifdef
#endif
*/
/*****************************************************************************
* Description: *//**brief This API is used to set FIFO WM Enable
*
*
*
*
*\param unsigned char *fifo_wn_en
* Enable -> 1
* Disable -> 0
*
*
*
* \return communication results
*
*
*****************************************************************************/
/* Scheduling:
*
*
*
* Usage guide:
*
*
* Remarks:
*
*****************************************************************************/
BMG160_RETURN_FUNCTION_TYPE bmg160_set_fifo_watermark_enable(
unsigned char fifo_wn_en)
{
BMG160_RETURN_FUNCTION_TYPE comres = C_BMG160_Zero_U8X;
unsigned char v_data_u8r = C_BMG160_Zero_U8X;
if (p_bmg160 == BMG160_NULL) {
return E_BMG160_NULL_PTR;
} else {
if (fifo_wn_en < C_BMG160_Two_U8X) {
comres = p_bmg160->BMG160_BUS_READ_FUNC
(p_bmg160->dev_addr,
BMG160_INT_4_FIFO_WM_EN__REG, &v_data_u8r, 1);
v_data_u8r = BMG160_SET_BITSLICE(v_data_u8r,
BMG160_INT_4_FIFO_WM_EN, fifo_wn_en);
comres += p_bmg160->BMG160_BUS_WRITE_FUNC
(p_bmg160->dev_addr,
BMG160_INT_4_FIFO_WM_EN__REG, &v_data_u8r, 1);
} else {
comres = E_BMG160_OUT_OF_RANGE;
}
}
return comres;
}
/* Compiler Switch if applicable
#ifdef
#endif
*/
/*****************************************************************************
* Description: *//**brief This API is used to set the Interrupt Reset
*
*
*
*
*\param unsigned char reset_int
* 1 -> Reset All Interrupts
*
*
*
* \return communication results
*
*
*****************************************************************************/
/* Scheduling:
*
*
*
* Usage guide:
*
*
* Remarks:
*
*****************************************************************************/
BMG160_RETURN_FUNCTION_TYPE bmg160_set_reset_int(unsigned char reset_int)
{
BMG160_RETURN_FUNCTION_TYPE comres = C_BMG160_Zero_U8X;
unsigned char v_data_u8r = C_BMG160_Zero_U8X;
if (p_bmg160 == BMG160_NULL) {
return E_BMG160_NULL_PTR;
} else {
comres = p_bmg160->BMG160_BUS_READ_FUNC(p_bmg160->dev_addr,
BMG160_RST_LATCH_ADDR_RESET_INT__REG, &v_data_u8r, 1);
v_data_u8r = BMG160_SET_BITSLICE(v_data_u8r,
BMG160_RST_LATCH_ADDR_RESET_INT, reset_int);
comres += p_bmg160->BMG160_BUS_WRITE_FUNC(p_bmg160->dev_addr,
BMG160_RST_LATCH_ADDR_RESET_INT__REG, &v_data_u8r, 1);
}
return comres;
}
/* Compiler Switch if applicable
#ifdef
#endif
*/
/*****************************************************************************
* Description: *//**brief This API is used to set the Offset Reset
*
*
*
*
*\param unsigned char offset_reset
* 1 -> Resets All the Offsets
*
*
*
* \return communication results
*
*
*****************************************************************************/
/* Scheduling:
*
*
*
* Usage guide:
*
*
* Remarks:
*
*****************************************************************************/
BMG160_RETURN_FUNCTION_TYPE bmg160_set_offset_reset(
unsigned char offset_reset)
{
BMG160_RETURN_FUNCTION_TYPE comres = C_BMG160_Zero_U8X;
unsigned char v_data_u8r = C_BMG160_Zero_U8X;
if (p_bmg160 == BMG160_NULL) {
return E_BMG160_NULL_PTR;
} else {
comres = p_bmg160->BMG160_BUS_READ_FUNC(p_bmg160->dev_addr,
BMG160_RST_LATCH_ADDR_OFFSET_RESET__REG, &v_data_u8r, 1);
v_data_u8r = BMG160_SET_BITSLICE(v_data_u8r,
BMG160_RST_LATCH_ADDR_OFFSET_RESET, offset_reset);
comres += p_bmg160->BMG160_BUS_WRITE_FUNC(p_bmg160->dev_addr,
BMG160_RST_LATCH_ADDR_OFFSET_RESET__REG, &v_data_u8r, 1);
}
return comres;
}
/* Compiler Switch if applicable
#ifdef
#endif
*/
/*****************************************************************************
* Description: *//**brief This API is used to get the Latch Status
*
*
*
*
*\param unsigned char *latch_status : Address of latch_status
* Pointer to a variable passed as a parameter
*
*
*
* \return
*
*
*****************************************************************************/
/* Scheduling:
*
*
*
* Usage guide:
*
*
* Remarks:
*
*****************************************************************************/
BMG160_RETURN_FUNCTION_TYPE bmg160_get_latch_status(
unsigned char *latch_status)
{
BMG160_RETURN_FUNCTION_TYPE comres = C_BMG160_Zero_U8X;
unsigned char v_data_u8r = C_BMG160_Zero_U8X;
if (p_bmg160 == BMG160_NULL) {
return E_BMG160_NULL_PTR;
} else {
comres = p_bmg160->BMG160_BUS_READ_FUNC(p_bmg160->dev_addr,
BMG160_RST_LATCH_ADDR_LATCH_STATUS__REG, &v_data_u8r, 1);
*latch_status = BMG160_GET_BITSLICE(v_data_u8r,
BMG160_RST_LATCH_ADDR_LATCH_STATUS);
}
return comres;
}
/* Compiler Switch if applicable
#ifdef
#endif
*/
/*****************************************************************************
* Description: *//**brief This API is used to set the Latch Status
*
*
*
*
*\param unsigned char latch_status:
* Value to be written passed as a parameter
*
*
*
* \return communication results
*
*
*****************************************************************************/
/* Scheduling:
*
*
*
* Usage guide:
*
*
* Remarks:
*
*****************************************************************************/
BMG160_RETURN_FUNCTION_TYPE bmg160_set_latch_status(
unsigned char latch_status)
{
BMG160_RETURN_FUNCTION_TYPE comres = C_BMG160_Zero_U8X;
unsigned char v_data_u8r = C_BMG160_Zero_U8X;
if (p_bmg160 == BMG160_NULL) {
return E_BMG160_NULL_PTR;
} else {
comres = p_bmg160->BMG160_BUS_READ_FUNC(p_bmg160->dev_addr,
BMG160_RST_LATCH_ADDR_LATCH_STATUS__REG, &v_data_u8r, 1);
v_data_u8r = BMG160_SET_BITSLICE(v_data_u8r,
BMG160_RST_LATCH_ADDR_LATCH_STATUS, latch_status);
comres += p_bmg160->BMG160_BUS_WRITE_FUNC(p_bmg160->dev_addr,
BMG160_RST_LATCH_ADDR_LATCH_STATUS__REG, &v_data_u8r, 1);
}
return comres;
}
/* Compiler Switch if applicable
#ifdef
#endif
*/
/*****************************************************************************
* Description: *//**brief This API is used to get the Latch Interrupt
*
*
*
*
*\param unsigned char *latch_int : Address of latch_int
* Pointer to a variable passed as a parameter
*
*
*
* \return
*
*
*****************************************************************************/
/* Scheduling:
*
*
*
* Usage guide:
*
*
* Remarks:
*
*****************************************************************************/
BMG160_RETURN_FUNCTION_TYPE bmg160_get_latch_int(unsigned char *latch_int)
{
BMG160_RETURN_FUNCTION_TYPE comres = C_BMG160_Zero_U8X;
unsigned char v_data_u8r = C_BMG160_Zero_U8X;
if (p_bmg160 == BMG160_NULL) {
return E_BMG160_NULL_PTR;
} else {
comres = p_bmg160->BMG160_BUS_READ_FUNC(p_bmg160->dev_addr,
BMG160_RST_LATCH_ADDR_LATCH_INT__REG, &v_data_u8r, 1);
*latch_int = BMG160_GET_BITSLICE(v_data_u8r,
BMG160_RST_LATCH_ADDR_LATCH_INT);
}
return comres;
}
/* Compiler Switch if applicable
#ifdef
#endif
*/
/*****************************************************************************
* Description: *//**brief This API is used to set the Latch Interrupt
*
*
*
*
*\param unsigned char latch_int:
* Value to be written passed as a parameter
*
*
*
* \return communication results
*
*
*****************************************************************************/
/* Scheduling:
*
*
*
* Usage guide:
*
*
* Remarks:
*
*****************************************************************************/
BMG160_RETURN_FUNCTION_TYPE bmg160_set_latch_int(unsigned char latch_int)
{
BMG160_RETURN_FUNCTION_TYPE comres = C_BMG160_Zero_U8X;
unsigned char v_data_u8r = C_BMG160_Zero_U8X;
if (p_bmg160 == BMG160_NULL) {
return E_BMG160_NULL_PTR;
} else {
comres = p_bmg160->BMG160_BUS_READ_FUNC(p_bmg160->dev_addr,
BMG160_RST_LATCH_ADDR_LATCH_INT__REG, &v_data_u8r, 1);
v_data_u8r = BMG160_SET_BITSLICE(v_data_u8r,
BMG160_RST_LATCH_ADDR_LATCH_INT, latch_int);
comres += p_bmg160->BMG160_BUS_WRITE_FUNC(p_bmg160->dev_addr,
BMG160_RST_LATCH_ADDR_LATCH_INT__REG, &v_data_u8r, 1);
}
return comres;
}
/* Compiler Switch if applicable
#ifdef
#endif
*/
/*****************************************************************************
* Description: *//**brief This API is used to get the status of High
* Hysteresis X,Y,Z
*
*
*
*
*\param unsigned char channel,unsigned char *high_hy
* channel :
* BMG160_X_AXIS -> 0
* BMG160_Y_AXIS -> 1
* BMG160_Z_AXIS -> 2
* high_hy :
* Enable -> 1
* disable -> 0
*
*
*
*
* \return
*
*
*****************************************************************************/
/* Scheduling:
*
*
*
* Usage guide:
*
*
* Remarks:
*
*****************************************************************************/
BMG160_RETURN_FUNCTION_TYPE bmg160_get_high_hy(unsigned char channel,
unsigned char *high_hy)
{
BMG160_RETURN_FUNCTION_TYPE comres = C_BMG160_Zero_U8X;
unsigned char v_data_u8r = C_BMG160_Zero_U8X;
if (p_bmg160 == BMG160_NULL) {
return E_BMG160_NULL_PTR;
} else {
switch (channel) {
case BMG160_X_AXIS:
comres = p_bmg160->BMG160_BUS_READ_FUNC
(p_bmg160->dev_addr,
BMG160_HIGH_HY_X__REG, &v_data_u8r, 1);
*high_hy = BMG160_GET_BITSLICE(v_data_u8r,
BMG160_HIGH_HY_X);
break;
case BMG160_Y_AXIS:
comres = p_bmg160->BMG160_BUS_READ_FUNC
(p_bmg160->dev_addr,
BMG160_HIGH_HY_Y__REG, &v_data_u8r, 1);
*high_hy = BMG160_GET_BITSLICE(v_data_u8r,
BMG160_HIGH_HY_Y);
break;
case BMG160_Z_AXIS:
comres = p_bmg160->BMG160_BUS_READ_FUNC
(p_bmg160->dev_addr,
BMG160_HIGH_HY_Z__REG, &v_data_u8r, 1);
*high_hy = BMG160_GET_BITSLICE(v_data_u8r,
BMG160_HIGH_HY_Z);
break;
default:
comres = E_BMG160_OUT_OF_RANGE;
break;
}
}
return comres;
}
/* Compiler Switch if applicable
#ifdef
#endif
*/
/*****************************************************************************
* Description: *//**brief This API is used to set the status of High
* Hysteresis X,Y,Z
*
*
*
*
*\param unsigned char channel,unsigned char *high_hy
* channel :
* BMG160_X_AXIS -> 0
* BMG160_Y_AXIS -> 1
* BMG160_Z_AXIS -> 2
* high_hy :
* Enable -> 1
* disable -> 0
*
*
*
*
*
* \return
*
*
*****************************************************************************/
/* Scheduling:
*
*
*
* Usage guide:
*
*
* Remarks:
*
*****************************************************************************/
BMG160_RETURN_FUNCTION_TYPE bmg160_set_high_hy(unsigned char channel,
unsigned char high_hy)
{
BMG160_RETURN_FUNCTION_TYPE comres = C_BMG160_Zero_U8X;
unsigned char v_data_u8r = C_BMG160_Zero_U8X;
if (p_bmg160 == BMG160_NULL) {
return E_BMG160_NULL_PTR;
} else {
switch (channel) {
case BMG160_X_AXIS:
comres = p_bmg160->BMG160_BUS_READ_FUNC
(p_bmg160->dev_addr,
BMG160_HIGH_HY_X__REG, &v_data_u8r, 1);
v_data_u8r = BMG160_SET_BITSLICE(v_data_u8r,
BMG160_HIGH_HY_X, high_hy);
comres += p_bmg160->BMG160_BUS_WRITE_FUNC
(p_bmg160->dev_addr,
BMG160_HIGH_HY_X__REG, &v_data_u8r, 1);
break;
case BMG160_Y_AXIS:
comres = p_bmg160->BMG160_BUS_READ_FUNC
(p_bmg160->dev_addr,
BMG160_HIGH_HY_Y__REG, &v_data_u8r, 1);
v_data_u8r = BMG160_SET_BITSLICE(v_data_u8r,
BMG160_HIGH_HY_Y, high_hy);
comres += p_bmg160->BMG160_BUS_WRITE_FUNC
(p_bmg160->dev_addr,
BMG160_HIGH_HY_Y__REG, &v_data_u8r, 1);
break;
case BMG160_Z_AXIS:
comres = p_bmg160->BMG160_BUS_READ_FUNC
(p_bmg160->dev_addr,
BMG160_HIGH_HY_Z__REG, &v_data_u8r, 1);
v_data_u8r = BMG160_SET_BITSLICE(v_data_u8r,
BMG160_HIGH_HY_Z, high_hy);
comres += p_bmg160->BMG160_BUS_WRITE_FUNC
(p_bmg160->dev_addr,
BMG160_HIGH_HY_Z__REG, &v_data_u8r, 1);
break;
default:
comres = E_BMG160_OUT_OF_RANGE;
break;
}
}
return comres;
}
/* Compiler Switch if applicable
#ifdef
#endif
*/
/*****************************************************************************
* Description: *//**brief This API is used to get the status of High
* Threshold X,Y,Z
*
*
*
*
*\param unsigned char channel,unsigned char *high_th
* channel :
* BMG160_X_AXIS -> 0
* BMG160_Y_AXIS -> 1
* BMG160_Z_AXIS -> 2
* high_th :
* Enable -> 1
* disable -> 0
*
*
*
*
*
* \return
*
*
*****************************************************************************/
/* Scheduling:
*
*
*
* Usage guide:
*
*
* Remarks:
*
*****************************************************************************/
BMG160_RETURN_FUNCTION_TYPE bmg160_get_high_th(unsigned char channel,
unsigned char *high_th)
{
BMG160_RETURN_FUNCTION_TYPE comres = C_BMG160_Zero_U8X;
unsigned char v_data_u8r = C_BMG160_Zero_U8X;
if (p_bmg160 == BMG160_NULL) {
return E_BMG160_NULL_PTR;
} else {
switch (channel) {
case BMG160_X_AXIS:
comres = p_bmg160->BMG160_BUS_READ_FUNC
(p_bmg160->dev_addr,
BMG160_HIGH_TH_X__REG, &v_data_u8r, 1);
*high_th = BMG160_GET_BITSLICE(v_data_u8r,
BMG160_HIGH_TH_X);
break;
case BMG160_Y_AXIS:
comres = p_bmg160->BMG160_BUS_READ_FUNC
(p_bmg160->dev_addr,
BMG160_HIGH_TH_Y__REG, &v_data_u8r, 1);
*high_th = BMG160_GET_BITSLICE(v_data_u8r,
BMG160_HIGH_TH_Y);
break;
case BMG160_Z_AXIS:
comres = p_bmg160->BMG160_BUS_READ_FUNC
(p_bmg160->dev_addr,
BMG160_HIGH_TH_Z__REG, &v_data_u8r, 1);
*high_th = BMG160_GET_BITSLICE(v_data_u8r,
BMG160_HIGH_TH_Z);
break;
default:
comres = E_BMG160_OUT_OF_RANGE;
break;
}
}
return comres;
}
/* Compiler Switch if applicable
#ifdef
#endif
*/
/*****************************************************************************
* Description: *//**brief This API is used to set the status of High
* Threshold X,Y,Z
*
*
*
*
*\param unsigned char channel,unsigned char *high_th
* channel :
* BMG160_X_AXIS -> 0
* BMG160_Y_AXIS -> 1
* BMG160_Z_AXIS -> 2
* high_th :
* Enable -> 1
* disable -> 0
*
*
*
*
*
* \return
*
*
*****************************************************************************/
/* Scheduling:
*
*
*
* Usage guide:
*
*
* Remarks:
*
*****************************************************************************/
BMG160_RETURN_FUNCTION_TYPE bmg160_set_high_th(unsigned char channel,
unsigned char high_th)
{
BMG160_RETURN_FUNCTION_TYPE comres = C_BMG160_Zero_U8X;
unsigned char v_data_u8r = C_BMG160_Zero_U8X;
if (p_bmg160 == BMG160_NULL) {
return E_BMG160_NULL_PTR;
} else {
switch (channel) {
case BMG160_X_AXIS:
comres = p_bmg160->BMG160_BUS_READ_FUNC
(p_bmg160->dev_addr,
BMG160_HIGH_TH_X__REG, &v_data_u8r, 1);
v_data_u8r = BMG160_SET_BITSLICE(v_data_u8r,
BMG160_HIGH_TH_X, high_th);
comres += p_bmg160->BMG160_BUS_WRITE_FUNC
(p_bmg160->dev_addr,
BMG160_HIGH_TH_X__REG, &v_data_u8r, 1);
break;
case BMG160_Y_AXIS:
comres = p_bmg160->BMG160_BUS_READ_FUNC
(p_bmg160->dev_addr,
BMG160_HIGH_TH_Y__REG, &v_data_u8r, 1);
v_data_u8r = BMG160_SET_BITSLICE(v_data_u8r,
BMG160_HIGH_TH_Y, high_th);
comres += p_bmg160->BMG160_BUS_WRITE_FUNC
(p_bmg160->dev_addr,
BMG160_HIGH_TH_Y__REG, &v_data_u8r, 1);
break;
case BMG160_Z_AXIS:
comres = p_bmg160->BMG160_BUS_READ_FUNC
(p_bmg160->dev_addr,
BMG160_HIGH_TH_Z__REG, &v_data_u8r, 1);
v_data_u8r = BMG160_SET_BITSLICE(v_data_u8r,
BMG160_HIGH_TH_Z, high_th);
comres += p_bmg160->BMG160_BUS_WRITE_FUNC
(p_bmg160->dev_addr,
BMG160_HIGH_TH_Z__REG, &v_data_u8r, 1);
break;
default:
comres = E_BMG160_OUT_OF_RANGE;
break;
}
}
return comres;
}
/* Compiler Switch if applicable
#ifdef
#endif
*/
/*****************************************************************************
* Description: *//**brief This API is used to get the status of High Enable
* Channel X,Y,Z
*
*
*
*
*\param unsigned char channel,unsigned char *high_en
* channel :
* BMG160_X_AXIS -> 0
* BMG160_Y_AXIS -> 1
* BMG160_Z_AXIS -> 2
* high_en :
* Enable -> 1
* disable -> 0
*
*
*
*
*
* \return
*
*
*****************************************************************************/
/* Scheduling:
*
*
*
* Usage guide:
*
*
* Remarks:
*
*****************************************************************************/
BMG160_RETURN_FUNCTION_TYPE bmg160_get_high_en_ch(unsigned char channel,
unsigned char *high_en)
{
BMG160_RETURN_FUNCTION_TYPE comres = C_BMG160_Zero_U8X;
unsigned char v_data_u8r = C_BMG160_Zero_U8X;
if (p_bmg160 == BMG160_NULL) {
return E_BMG160_NULL_PTR;
} else {
switch (channel) {
case BMG160_X_AXIS:
comres = p_bmg160->BMG160_BUS_READ_FUNC
(p_bmg160->dev_addr,
BMG160_HIGH_EN_X__REG, &v_data_u8r, 1);
*high_en = BMG160_GET_BITSLICE(v_data_u8r,
BMG160_HIGH_EN_X);
break;
case BMG160_Y_AXIS:
comres = p_bmg160->BMG160_BUS_READ_FUNC
(p_bmg160->dev_addr,
BMG160_HIGH_EN_Y__REG, &v_data_u8r, 1);
*high_en = BMG160_GET_BITSLICE(v_data_u8r,
BMG160_HIGH_EN_Y);
break;
case BMG160_Z_AXIS:
comres = p_bmg160->BMG160_BUS_READ_FUNC
(p_bmg160->dev_addr,
BMG160_HIGH_EN_Z__REG, &v_data_u8r, 1);
*high_en = BMG160_GET_BITSLICE(v_data_u8r,
BMG160_HIGH_EN_Z);
break;
default:
comres = E_BMG160_OUT_OF_RANGE;
break;
}
}
return comres;
}
/* Compiler Switch if applicable
#ifdef
#endif
*/
/*****************************************************************************
* Description: *//**brief This API is used to set the status of High Enable
* Channel X,Y,Z
*
*
*
*
*\param unsigned char channel,unsigned char *high_en
* channel :
* BMG160_X_AXIS -> 0
* BMG160_Y_AXIS -> 1
* BMG160_Z_AXIS -> 2
* high_en :
* Enable -> 1
* disable -> 0
*
*
*
*
*
* \return
*
*
*****************************************************************************/
/* Scheduling:
*
*
*
* Usage guide:
*
*
* Remarks:
*
*****************************************************************************/
BMG160_RETURN_FUNCTION_TYPE bmg160_set_high_en_ch(unsigned char channel,
unsigned char high_en)
{
BMG160_RETURN_FUNCTION_TYPE comres = C_BMG160_Zero_U8X;
unsigned char v_data_u8r = C_BMG160_Zero_U8X;
if (p_bmg160 == BMG160_NULL) {
return E_BMG160_NULL_PTR;
} else {
switch (channel) {
case BMG160_X_AXIS:
comres = p_bmg160->BMG160_BUS_READ_FUNC
(p_bmg160->dev_addr,
BMG160_HIGH_EN_X__REG, &v_data_u8r, 1);
v_data_u8r = BMG160_SET_BITSLICE(v_data_u8r,
BMG160_HIGH_EN_X, high_en);
comres += p_bmg160->BMG160_BUS_WRITE_FUNC
(p_bmg160->dev_addr,
BMG160_HIGH_EN_X__REG, &v_data_u8r, 1);
break;
case BMG160_Y_AXIS:
comres = p_bmg160->BMG160_BUS_READ_FUNC
(p_bmg160->dev_addr,
BMG160_HIGH_EN_Y__REG, &v_data_u8r, 1);
v_data_u8r = BMG160_SET_BITSLICE(v_data_u8r,
BMG160_HIGH_EN_Y, high_en);
comres += p_bmg160->BMG160_BUS_WRITE_FUNC
(p_bmg160->dev_addr,
BMG160_HIGH_EN_Y__REG, &v_data_u8r, 1);
break;
case BMG160_Z_AXIS:
comres = p_bmg160->BMG160_BUS_READ_FUNC
(p_bmg160->dev_addr,
BMG160_HIGH_EN_Z__REG, &v_data_u8r, 1);
v_data_u8r = BMG160_SET_BITSLICE(v_data_u8r,
BMG160_HIGH_EN_Z, high_en);
comres += p_bmg160->BMG160_BUS_WRITE_FUNC
(p_bmg160->dev_addr,
BMG160_HIGH_EN_Z__REG, &v_data_u8r, 1);
break;
default:
comres = E_BMG160_OUT_OF_RANGE;
break;
}
}
return comres;
}
/* Compiler Switch if applicable
#ifdef
#endif
*/
/*****************************************************************************
* Description: *//**brief This API is used to get High Duration
*
*
*
*
*\param unsigned char channel,unsigned char *high_dur
* channel :
* BMG160_X_AXIS -> 0
* BMG160_Y_AXIS -> 1
* BMG160_Z_AXIS -> 2
* *high_dur : Address of high_bw
* Pointer to a variable passed as a
* parameter
*
*
* \return
*
*
*****************************************************************************/
/* Scheduling:
*
*
*
* Usage guide:
*
*
* Remarks:
*
*****************************************************************************/
BMG160_RETURN_FUNCTION_TYPE bmg160_get_high_dur_ch(unsigned char channel,
unsigned char *high_dur)
{
BMG160_RETURN_FUNCTION_TYPE comres = C_BMG160_Zero_U8X;
unsigned char v_data_u8r = C_BMG160_Zero_U8X;
if (p_bmg160 == BMG160_NULL) {
return E_BMG160_NULL_PTR;
} else {
switch (channel) {
case BMG160_X_AXIS:
comres = p_bmg160->BMG160_BUS_READ_FUNC
(p_bmg160->dev_addr,
BMG160_HIGH_DUR_X_ADDR, &v_data_u8r, 1);
*high_dur = v_data_u8r;
break;
case BMG160_Y_AXIS:
comres = p_bmg160->BMG160_BUS_READ_FUNC
(p_bmg160->dev_addr,
BMG160_HIGH_DUR_Y_ADDR, &v_data_u8r, 1);
*high_dur = v_data_u8r;
break;
case BMG160_Z_AXIS:
comres = p_bmg160->BMG160_BUS_READ_FUNC
(p_bmg160->dev_addr,
BMG160_HIGH_DUR_Z_ADDR, &v_data_u8r, 1);
*high_dur = v_data_u8r;
break;
default:
comres = E_BMG160_OUT_OF_RANGE;
break;
}
}
return comres;
}
/* Compiler Switch if applicable
#ifdef
#endif
*/
/*****************************************************************************
* Description: *//**brief This API is used to set High Duration
*
*
*
*
*\param unsigned char channel,unsigned char *high_dur
* channel :
* BMG160_X_AXIS -> 0
* BMG160_Y_AXIS -> 1
* BMG160_Z_AXIS -> 2
* high_dur : Value to be written passed as a parameter
*
*
*
*
*
* \return communication results
*
*
*****************************************************************************/
/* Scheduling:
*
*
*
* Usage guide:
*
*
* Remarks:
*
*****************************************************************************/
BMG160_RETURN_FUNCTION_TYPE bmg160_set_high_dur_ch(unsigned char channel,
unsigned char high_dur)
{
BMG160_RETURN_FUNCTION_TYPE comres = C_BMG160_Zero_U8X;
unsigned char v_data_u8r = C_BMG160_Zero_U8X;
if (p_bmg160 == BMG160_NULL) {
return E_BMG160_NULL_PTR;
} else {
switch (channel) {
case BMG160_X_AXIS:
v_data_u8r = high_dur;
comres = p_bmg160->BMG160_BUS_WRITE_FUNC
(p_bmg160->dev_addr,
BMG160_HIGH_DUR_X_ADDR, &v_data_u8r, 1);
break;
case BMG160_Y_AXIS:
v_data_u8r = high_dur;
comres = p_bmg160->BMG160_BUS_WRITE_FUNC
(p_bmg160->dev_addr,
BMG160_HIGH_DUR_Y_ADDR, &v_data_u8r, 1);
break;
case BMG160_Z_AXIS:
v_data_u8r = high_dur;
comres = p_bmg160->BMG160_BUS_WRITE_FUNC
(p_bmg160->dev_addr,
BMG160_HIGH_DUR_Z_ADDR, &v_data_u8r, 1);
break;
default:
comres = E_BMG160_OUT_OF_RANGE;
break;
}
}
return comres;
}
/* Compiler Switch if applicable
#ifdef
#endif
*/
/*****************************************************************************
* Description: *//**brief This API is used to get Slow Offset Threshold
*
*
*
*
*\param unsigned char *offset_th : Address of offset_th
* Pointer to a variable passed as a parameter
*
*
*
* \return
*
*
*****************************************************************************/
/* Scheduling:
*
*
*
* Usage guide:
*
*
* Remarks:
*
*****************************************************************************/
BMG160_RETURN_FUNCTION_TYPE bmg160_get_slow_offset_th(
unsigned char *offset_th)
{
BMG160_RETURN_FUNCTION_TYPE comres = C_BMG160_Zero_U8X;
unsigned char v_data_u8r = C_BMG160_Zero_U8X;
if (p_bmg160 == BMG160_NULL) {
return E_BMG160_NULL_PTR;
} else {
comres = p_bmg160->BMG160_BUS_READ_FUNC(p_bmg160->dev_addr,
BMG160_SLOW_OFFSET_TH__REG, &v_data_u8r, 1);
*offset_th = BMG160_GET_BITSLICE(v_data_u8r,
BMG160_SLOW_OFFSET_TH);
}
return comres;
}
/* Compiler Switch if applicable
#ifdef
#endif
*/
/*****************************************************************************
* Description: *//**brief This API is used to set Slow Offset Threshold
*
*
*
*
*\param unsigned char offset_th:
* Value to be written passed as a parameter
*
*
*
* \return communication results
*
*
*****************************************************************************/
/* Scheduling:
*
*
*
* Usage guide:
*
*
* Remarks:
*
*****************************************************************************/
BMG160_RETURN_FUNCTION_TYPE bmg160_set_slow_offset_th(unsigned char offset_th)
{
BMG160_RETURN_FUNCTION_TYPE comres = C_BMG160_Zero_U8X;
unsigned char v_data_u8r = C_BMG160_Zero_U8X;
if (p_bmg160 == BMG160_NULL) {
return E_BMG160_NULL_PTR;
} else {
comres = p_bmg160->BMG160_BUS_READ_FUNC(p_bmg160->dev_addr,
BMG160_SLOW_OFFSET_TH__REG, &v_data_u8r, 1);
v_data_u8r = BMG160_SET_BITSLICE(v_data_u8r,
BMG160_SLOW_OFFSET_TH, offset_th);
comres += p_bmg160->BMG160_BUS_WRITE_FUNC(p_bmg160->dev_addr,
BMG160_SLOW_OFFSET_TH__REG, &v_data_u8r, 1);
}
return comres;
}
/* Compiler Switch if applicable
#ifdef
#endif
*/
/*****************************************************************************
* Description: *//**brief This API is used to get Slow Offset Duration
*
*
*
*
*\param unsigned char *offset_dur : Address of offset_dur
* Pointer to a variable passed as a parameter
*
*
*
* \return
*
*
*****************************************************************************/
/* Scheduling:
*
*
*
* Usage guide:
*
*
* Remarks:
*
*****************************************************************************/
BMG160_RETURN_FUNCTION_TYPE bmg160_get_slow_offset_dur(
unsigned char *offset_dur)
{
BMG160_RETURN_FUNCTION_TYPE comres = C_BMG160_Zero_U8X;
unsigned char v_data_u8r = C_BMG160_Zero_U8X;
if (p_bmg160 == BMG160_NULL) {
return E_BMG160_NULL_PTR;
} else {
comres = p_bmg160->BMG160_BUS_READ_FUNC(p_bmg160->dev_addr,
BMG160_SLOW_OFFSET_DUR__REG, &v_data_u8r, 1);
*offset_dur = BMG160_GET_BITSLICE(v_data_u8r,
BMG160_SLOW_OFFSET_DUR);
}
return comres;
}
/* Compiler Switch if applicable
#ifdef
#endif
*/
/*****************************************************************************
* Description: *//**brief This API is used to set Slow Offset Duration
*
*
*
*
*\param unsigned char offset_dur:
* Value to be written passed as a parameter
*
*
*
* \return communication results
*
*
*****************************************************************************/
/* Scheduling:
*
*
*
* Usage guide:
*
*
* Remarks:
*
*****************************************************************************/
BMG160_RETURN_FUNCTION_TYPE bmg160_set_slow_offset_dur(
unsigned char offset_dur)
{
BMG160_RETURN_FUNCTION_TYPE comres = C_BMG160_Zero_U8X;
unsigned char v_data_u8r = C_BMG160_Zero_U8X;
if (p_bmg160 == BMG160_NULL) {
return E_BMG160_NULL_PTR;
} else {
comres = p_bmg160->BMG160_BUS_READ_FUNC(p_bmg160->dev_addr,
BMG160_SLOW_OFFSET_DUR__REG, &v_data_u8r, 1);
v_data_u8r = BMG160_SET_BITSLICE(v_data_u8r,
BMG160_SLOW_OFFSET_DUR, offset_dur);
comres += p_bmg160->BMG160_BUS_WRITE_FUNC(p_bmg160->dev_addr,
BMG160_SLOW_OFFSET_DUR__REG, &v_data_u8r, 1);
}
return comres;
}
/* Compiler Switch if applicable
#ifdef
#endif
*/
/*****************************************************************************
* Description: *//**brief This API is used to get Slow Offset Enable channel
* X,Y,Z
*
*
*
*
*\param unsigned char channel,unsigned char *slow_offset
* channel :
* BMG160_X_AXIS -> 0
* BMG160_Y_AXIS -> 1
* BMG160_Z_AXIS -> 2
* slow_offset :
* Enable -> 1
* disable -> 0
*
*
*
*
*
* \return
*
*
*****************************************************************************/
/* Scheduling:
*
*
*
* Usage guide:
*
*
* Remarks:
*
*****************************************************************************/
BMG160_RETURN_FUNCTION_TYPE bmg160_get_slow_offset_en_ch(
unsigned char channel, unsigned char *slow_offset)
{
BMG160_RETURN_FUNCTION_TYPE comres = C_BMG160_Zero_U8X;
unsigned char v_data_u8r = C_BMG160_Zero_U8X;
if (p_bmg160 == BMG160_NULL) {
return E_BMG160_NULL_PTR;
} else {
switch (channel) {
case BMG160_X_AXIS:
comres = p_bmg160->BMG160_BUS_READ_FUNC
(p_bmg160->dev_addr,
BMG160_SLOW_OFFSET_EN_X__REG, &v_data_u8r, 1);
*slow_offset = BMG160_GET_BITSLICE(v_data_u8r,
BMG160_SLOW_OFFSET_EN_X);
break;
case BMG160_Y_AXIS:
comres = p_bmg160->BMG160_BUS_READ_FUNC
(p_bmg160->dev_addr,
BMG160_SLOW_OFFSET_EN_Y__REG, &v_data_u8r, 1);
*slow_offset = BMG160_GET_BITSLICE(v_data_u8r,
BMG160_SLOW_OFFSET_EN_Y);
break;
case BMG160_Z_AXIS:
comres = p_bmg160->BMG160_BUS_READ_FUNC
(p_bmg160->dev_addr,
BMG160_SLOW_OFFSET_EN_Z__REG, &v_data_u8r, 1);
*slow_offset = BMG160_GET_BITSLICE(v_data_u8r,
BMG160_SLOW_OFFSET_EN_Z);
break;
default:
comres = E_BMG160_OUT_OF_RANGE;
break;
}
}
return comres;
}
/* Compiler Switch if applicable
#ifdef
#endif
*/
/*****************************************************************************
* Description: *//**brief This API is used to set Slow Offset Enable channel
* X,Y,Z
*
*
*
*
*\param unsigned char channel,unsigned char *slow_offset
* channel :
* BMG160_X_AXIS -> 0
* BMG160_Y_AXIS -> 1
* BMG160_Z_AXIS -> 2
* slow_offset :
* Enable -> 1
* disable -> 0
*
*
*
*
*
* \return communication results
*
*
*****************************************************************************/
/* Scheduling:
*
*
*
* Usage guide:
*
*
* Remarks:
*
*****************************************************************************/
BMG160_RETURN_FUNCTION_TYPE bmg160_set_slow_offset_en_ch(
unsigned char channel, unsigned char slow_offset)
{
BMG160_RETURN_FUNCTION_TYPE comres = C_BMG160_Zero_U8X;
unsigned char v_data_u8r = C_BMG160_Zero_U8X;
if (p_bmg160 == BMG160_NULL) {
return E_BMG160_NULL_PTR;
} else {
switch (channel) {
case BMG160_X_AXIS:
comres = p_bmg160->BMG160_BUS_READ_FUNC
(p_bmg160->dev_addr,
BMG160_SLOW_OFFSET_EN_X__REG, &v_data_u8r, 1);
v_data_u8r = BMG160_SET_BITSLICE(v_data_u8r,
BMG160_SLOW_OFFSET_EN_X, slow_offset);
comres += p_bmg160->BMG160_BUS_WRITE_FUNC
(p_bmg160->dev_addr,
BMG160_SLOW_OFFSET_EN_X__REG, &v_data_u8r, 1);
break;
case BMG160_Y_AXIS:
comres = p_bmg160->BMG160_BUS_READ_FUNC
(p_bmg160->dev_addr,
BMG160_SLOW_OFFSET_EN_Y__REG, &v_data_u8r, 1);
v_data_u8r = BMG160_SET_BITSLICE(v_data_u8r,
BMG160_SLOW_OFFSET_EN_Y, slow_offset);
comres += p_bmg160->BMG160_BUS_WRITE_FUNC
(p_bmg160->dev_addr,
BMG160_SLOW_OFFSET_EN_Y__REG, &v_data_u8r, 1);
break;
case BMG160_Z_AXIS:
comres = p_bmg160->BMG160_BUS_READ_FUNC
(p_bmg160->dev_addr,
BMG160_SLOW_OFFSET_EN_Z__REG, &v_data_u8r, 1);
v_data_u8r = BMG160_SET_BITSLICE(v_data_u8r,
BMG160_SLOW_OFFSET_EN_Z,
slow_offset);
comres += p_bmg160->BMG160_BUS_WRITE_FUNC
(p_bmg160->dev_addr,
BMG160_SLOW_OFFSET_EN_Z__REG, &v_data_u8r, 1);
break;
default:
comres = E_BMG160_OUT_OF_RANGE;
break;
}
}
return comres;
}
/* Compiler Switch if applicable
#ifdef
#endif
*/
/*****************************************************************************
* Description: *//**brief This API is used to get Fast Offset WordLength and
* Auto Offset WordLength
*
*
*
*
*\param unsigned char channel,unsigned char *offset_wl
* channel :
* BMG160_AUTO_OFFSET_WL -> 0
* BMG160_FAST_OFFSET_WL -> 1
* *offset_wl : Address of high_bw
* Pointer to a variable passed as a
* parameter
*
* \return
*
*
*****************************************************************************/
/* Scheduling:
*
*
*
* Usage guide:
*
*
* Remarks:
*
*****************************************************************************/
BMG160_RETURN_FUNCTION_TYPE bmg160_get_offset_wl(unsigned char channel,
unsigned char *offset_wl)
{
BMG160_RETURN_FUNCTION_TYPE comres = C_BMG160_Zero_U8X;
unsigned char v_data_u8r = C_BMG160_Zero_U8X;
if (p_bmg160 == BMG160_NULL) {
return E_BMG160_NULL_PTR;
} else {
switch (channel) {
case BMG160_AUTO_OFFSET_WL:
comres = p_bmg160->BMG160_BUS_READ_FUNC
(p_bmg160->dev_addr,
BMG160_AUTO_OFFSET_WL__REG, &v_data_u8r, 1);
*offset_wl = BMG160_GET_BITSLICE(v_data_u8r,
BMG160_AUTO_OFFSET_WL);
break;
case BMG160_FAST_OFFSET_WL:
comres = p_bmg160->BMG160_BUS_READ_FUNC
(p_bmg160->dev_addr,
BMG160_FAST_OFFSET_WL__REG, &v_data_u8r, 1);
*offset_wl = BMG160_GET_BITSLICE(v_data_u8r,
BMG160_FAST_OFFSET_WL);
break;
default:
comres = E_BMG160_OUT_OF_RANGE;
break;
}
}
return comres;
}
/* Compiler Switch if applicable
#ifdef
#endif
*/
/*****************************************************************************
* Description: *//**brief This API is used to set Fast Offset WordLength and
* Auto Offset WordLength
*
*
*
*
*\param unsigned char channel,unsigned char *offset_wl
* channel :
* BMG160_AUTO_OFFSET_WL -> 0
* BMG160_FAST_OFFSET_WL -> 1
* offset_wl : Value to be written passed as a parameter
*
*
*
* \return communication results
*
*
*****************************************************************************/
/* Scheduling:
*
*
*
* Usage guide:
*
*
* Remarks:
*
*****************************************************************************/
BMG160_RETURN_FUNCTION_TYPE bmg160_set_offset_wl(
unsigned char channel, unsigned char offset_wl)
{
BMG160_RETURN_FUNCTION_TYPE comres = C_BMG160_Zero_U8X;
unsigned char v_data_u8r = C_BMG160_Zero_U8X;
if (p_bmg160 == BMG160_NULL) {
return E_BMG160_NULL_PTR;
} else {
switch (channel) {
case BMG160_AUTO_OFFSET_WL:
comres = p_bmg160->BMG160_BUS_READ_FUNC
(p_bmg160->dev_addr,
BMG160_AUTO_OFFSET_WL__REG, &v_data_u8r, 1);
v_data_u8r = BMG160_SET_BITSLICE(v_data_u8r,
BMG160_AUTO_OFFSET_WL, offset_wl);
comres += p_bmg160->BMG160_BUS_WRITE_FUNC
(p_bmg160->dev_addr,
BMG160_AUTO_OFFSET_WL__REG, &v_data_u8r, 1);
break;
case BMG160_FAST_OFFSET_WL:
comres = p_bmg160->BMG160_BUS_READ_FUNC
(p_bmg160->dev_addr,
BMG160_FAST_OFFSET_WL__REG, &v_data_u8r, 1);
v_data_u8r = BMG160_SET_BITSLICE(v_data_u8r,
BMG160_FAST_OFFSET_WL, offset_wl);
comres += p_bmg160->BMG160_BUS_WRITE_FUNC
(p_bmg160->dev_addr,
BMG160_FAST_OFFSET_WL__REG, &v_data_u8r, 1);
break;
default:
comres = E_BMG160_OUT_OF_RANGE;
break;
}
}
return comres;
}
/* Compiler Switch if applicable
#ifdef
#endif
*/
/*****************************************************************************
* Description: *//**brief This API is used to enable fast offset
*
*
*
*
* \param bmg160_enable_fast_offset
* Enable -> 1
* Disable -> 0
*
*
* \return communication results
*
*
*****************************************************************************/
/* Scheduling:
*
*
*
* Usage guide:
*
*
* Remarks:
*
*****************************************************************************/
BMG160_RETURN_FUNCTION_TYPE bmg160_enable_fast_offset()
{
BMG160_RETURN_FUNCTION_TYPE comres = C_BMG160_Zero_U8X;
unsigned char v_data_u8r = C_BMG160_Zero_U8X;
if (p_bmg160 == BMG160_NULL) {
return E_BMG160_NULL_PTR;
} else {
comres = p_bmg160->BMG160_BUS_READ_FUNC(p_bmg160->dev_addr,
BMG160_FAST_OFFSET_EN__REG, &v_data_u8r, 1);
v_data_u8r = BMG160_SET_BITSLICE(v_data_u8r,
BMG160_FAST_OFFSET_EN, 1);
comres += p_bmg160->BMG160_BUS_WRITE_FUNC(p_bmg160->dev_addr,
BMG160_FAST_OFFSET_EN__REG, &v_data_u8r, 1);
}
return comres;
}
/* Compiler Switch if applicable
#ifdef
#endif
*/
/*****************************************************************************
* Description: *//**brief This API read the Fast offset en status from the
* 0x32h of 0 to 2 bits.
*
*
*
*
*\param unsigned char *fast_offset
* Pointer to a variable passed as a parameter
*
*
*
* \return Communication results
*
*
*****************************************************************************/
/* Scheduling:
*
*
*
* Usage guide:
*
*
* Remarks:
*
*****************************************************************************/
BMG160_RETURN_FUNCTION_TYPE bmg160_get_fast_offset_en_ch(
unsigned char *fast_offset)
{
BMG160_RETURN_FUNCTION_TYPE comres = C_BMG160_Zero_U8X;
unsigned char v_data_u8r = C_BMG160_Zero_U8X;
if (p_bmg160 == BMG160_NULL) {
return E_BMG160_NULL_PTR;
} else {
comres = p_bmg160->BMG160_BUS_READ_FUNC
(p_bmg160->dev_addr,
BMG160_FAST_OFFSET_EN_XYZ__REG, &v_data_u8r, 1);
*fast_offset = BMG160_GET_BITSLICE(v_data_u8r,
BMG160_FAST_OFFSET_EN_XYZ);
}
return comres;
}
/* Compiler Switch if applicable
#ifdef
#endif
*/
/*****************************************************************************
* Description: *//**brief This API writes the Fast offset enable bit based
* on the Channel selection 0x32h of (0 to 2 bits)
*
*
*
*
* \param unsigned char channel,unsigned char fast_offset
*
* channel --> BMG160_X_AXIS,BMG160_Y_AXIS,BMG160_Z_AXIS
* fast_offset --> 0 - Disable
* 1 - Enable
*
*
*
* \return Communication results
*
*
*****************************************************************************/
/* Scheduling:
*
*
*
* Usage guide:
*
*
* Remarks:
*
*****************************************************************************/
BMG160_RETURN_FUNCTION_TYPE bmg160_set_fast_offset_en_ch(
unsigned char channel, unsigned char fast_offset)
{
BMG160_RETURN_FUNCTION_TYPE comres = C_BMG160_Zero_U8X;
unsigned char v_data_u8r = C_BMG160_Zero_U8X;
if (p_bmg160 == BMG160_NULL) {
return E_BMG160_NULL_PTR;
} else {
switch (channel) {
case BMG160_X_AXIS:
comres = p_bmg160->BMG160_BUS_READ_FUNC
(p_bmg160->dev_addr,
BMG160_FAST_OFFSET_EN_X__REG, &v_data_u8r, 1);
v_data_u8r = BMG160_SET_BITSLICE(v_data_u8r,
BMG160_FAST_OFFSET_EN_X, fast_offset);
comres += p_bmg160->BMG160_BUS_WRITE_FUNC
(p_bmg160->dev_addr,
BMG160_FAST_OFFSET_EN_X__REG, &v_data_u8r, 1);
break;
case BMG160_Y_AXIS:
comres = p_bmg160->BMG160_BUS_READ_FUNC
(p_bmg160->dev_addr,
BMG160_FAST_OFFSET_EN_Y__REG, &v_data_u8r, 1);
v_data_u8r = BMG160_SET_BITSLICE(v_data_u8r,
BMG160_FAST_OFFSET_EN_Y, fast_offset);
comres += p_bmg160->BMG160_BUS_WRITE_FUNC
(p_bmg160->dev_addr,
BMG160_FAST_OFFSET_EN_Y__REG, &v_data_u8r, 1);
break;
case BMG160_Z_AXIS:
comres = p_bmg160->BMG160_BUS_READ_FUNC
(p_bmg160->dev_addr,
BMG160_FAST_OFFSET_EN_Z__REG, &v_data_u8r, 1);
v_data_u8r = BMG160_SET_BITSLICE(v_data_u8r,
BMG160_FAST_OFFSET_EN_Z, fast_offset);
comres += p_bmg160->BMG160_BUS_WRITE_FUNC
(p_bmg160->dev_addr,
BMG160_FAST_OFFSET_EN_Z__REG, &v_data_u8r, 1);
break;
default:
comres = E_BMG160_OUT_OF_RANGE;
break;
}
}
return comres;
}
/* Compiler Switch if applicable
#ifdef
#endif
*/
/*****************************************************************************
* Description: *//**brief This API is used to get the status of nvm program
* remain
*
*
*
*
*\param unsigned char *nvm_remain
*
*
*
*
*
* \return
*
*
*****************************************************************************/
/* Scheduling:
*
*
*
* Usage guide:
*
*
* Remarks:
*
*****************************************************************************/
BMG160_RETURN_FUNCTION_TYPE bmg160_get_nvm_remain(unsigned char *nvm_remain)
{
BMG160_RETURN_FUNCTION_TYPE comres = C_BMG160_Zero_U8X;
unsigned char v_data_u8r = C_BMG160_Zero_U8X;
if (p_bmg160 == BMG160_NULL) {
return E_BMG160_NULL_PTR;
} else {
comres = p_bmg160->BMG160_BUS_READ_FUNC(p_bmg160->dev_addr,
BMG160_TRIM_NVM_CTRL_ADDR_NVM_REMAIN__REG, &v_data_u8r, 1);
*nvm_remain = BMG160_GET_BITSLICE(v_data_u8r,
BMG160_TRIM_NVM_CTRL_ADDR_NVM_REMAIN);
}
return comres;
}
/* Compiler Switch if applicable
#ifdef
#endif
*/
/*****************************************************************************
* Description: *//**brief This API is used to set the status of nvm load
*
*
*
*
*\param unsigned char nvm_load
* 1 -> load offset value from NVM
* 0 -> no action
*
*
*
*
*
*
* \return
*
*
*****************************************************************************/
/* Scheduling:
*
*
*
* Usage guide:
*
*
* Remarks:
*
*****************************************************************************/
BMG160_RETURN_FUNCTION_TYPE bmg160_set_nvm_load(unsigned char nvm_load)
{
BMG160_RETURN_FUNCTION_TYPE comres = C_BMG160_Zero_U8X;
unsigned char v_data_u8r = C_BMG160_Zero_U8X;
if (p_bmg160 == BMG160_NULL) {
return E_BMG160_NULL_PTR;
} else {
comres = p_bmg160->BMG160_BUS_READ_FUNC(p_bmg160->dev_addr,
BMG160_TRIM_NVM_CTRL_ADDR_NVM_LOAD__REG, &v_data_u8r, 1);
v_data_u8r = BMG160_SET_BITSLICE(v_data_u8r,
BMG160_TRIM_NVM_CTRL_ADDR_NVM_LOAD, nvm_load);
comres += p_bmg160->BMG160_BUS_WRITE_FUNC(p_bmg160->dev_addr,
BMG160_TRIM_NVM_CTRL_ADDR_NVM_LOAD__REG, &v_data_u8r, 1);
}
return comres;
}
/* Compiler Switch if applicable
#ifdef
#endif
*/
/*****************************************************************************
* Description: *//**brief This API is used to get the status of nvmprogram
* ready
*
*
*
*
*\param unsigned char *nvm_rdy
* 1 -> program seq finished
* 0 -> program seq in progress
*
*
*
*
*
* \return
*
*
*****************************************************************************/
/* Scheduling:
*
*
*
* Usage guide:
*
*
* Remarks:
*
*****************************************************************************/
BMG160_RETURN_FUNCTION_TYPE bmg160_get_nvm_rdy(unsigned char *nvm_rdy)
{
BMG160_RETURN_FUNCTION_TYPE comres = C_BMG160_Zero_U8X;
unsigned char v_data_u8r = C_BMG160_Zero_U8X;
if (p_bmg160 == BMG160_NULL) {
return E_BMG160_NULL_PTR;
} else {
comres = p_bmg160->BMG160_BUS_READ_FUNC(p_bmg160->dev_addr,
BMG160_TRIM_NVM_CTRL_ADDR_NVM_RDY__REG, &v_data_u8r, 1);
*nvm_rdy = BMG160_GET_BITSLICE(v_data_u8r,
BMG160_TRIM_NVM_CTRL_ADDR_NVM_RDY);
}
return comres;
}
/* Compiler Switch if applicable
#ifdef
#endif
*/
/*****************************************************************************
* Description: *//**brief This API is used to set the status of nvm program
* trigger
*
*
*
*
*\param unsigned char trig
* 1 -> trig program seq (wo)
* 0 -> No Action
*
*
*
*
* \return
*
*
*****************************************************************************/
/* Scheduling:
*
*
*
* Usage guide:
*
*
* Remarks:
*
*****************************************************************************/
BMG160_RETURN_FUNCTION_TYPE bmg160_set_nvm_prog_trig(unsigned char prog_trig)
{
BMG160_RETURN_FUNCTION_TYPE comres = C_BMG160_Zero_U8X;
unsigned char v_data_u8r = C_BMG160_Zero_U8X;
if (p_bmg160 == BMG160_NULL) {
return E_BMG160_NULL_PTR;
} else {
comres = p_bmg160->BMG160_BUS_READ_FUNC(p_bmg160->dev_addr,
BMG160_TRIM_NVM_CTRL_ADDR_NVM_PROG_TRIG__REG, &v_data_u8r, 1);
v_data_u8r = BMG160_SET_BITSLICE(v_data_u8r,
BMG160_TRIM_NVM_CTRL_ADDR_NVM_PROG_TRIG, prog_trig);
comres += p_bmg160->BMG160_BUS_WRITE_FUNC(p_bmg160->dev_addr,
BMG160_TRIM_NVM_CTRL_ADDR_NVM_PROG_TRIG__REG, &v_data_u8r, 1);
}
return comres;
}
/* Compiler Switch if applicable
#ifdef
#endif
*/
/*****************************************************************************
* Description: *//**brief This API is used to get the status of nvm program
* mode
*
*
*
*
* \param unsigned char *prog_mode : Address of *prog_mode
* 1 -> Enable program mode
* 0 -> Disable program mode
*
*
*
*
* \return
*
*
*****************************************************************************/
/* Scheduling:
*
*
*
* Usage guide:
*
*
* Remarks:
*
*****************************************************************************/
BMG160_RETURN_FUNCTION_TYPE bmg160_get_nvm_prog_mode(unsigned char *prog_mode)
{
BMG160_RETURN_FUNCTION_TYPE comres = C_BMG160_Zero_U8X;
unsigned char v_data_u8r = C_BMG160_Zero_U8X;
if (p_bmg160 == BMG160_NULL) {
return E_BMG160_NULL_PTR;
} else {
comres = p_bmg160->BMG160_BUS_READ_FUNC(p_bmg160->dev_addr,
BMG160_TRIM_NVM_CTRL_ADDR_NVM_PROG_MODE__REG, &v_data_u8r, 1);
*prog_mode = BMG160_GET_BITSLICE(v_data_u8r,
BMG160_TRIM_NVM_CTRL_ADDR_NVM_PROG_MODE);
}
return comres;
}
/* Compiler Switch if applicable
#ifdef
#endif
*/
/******************************************************************************
* Description: *//**brief This API is used to set the status of nvmprogram
* mode
*
*
*
*
* \param(unsigned char prog_mode)
* 1 -> Enable program mode
* 0 -> Disable program mode
*
*
*
*
* \return communication results
*
*
*****************************************************************************/
/* Scheduling:
*
*
*
* Usage guide:
*
*
* Remarks:
*
*****************************************************************************/
BMG160_RETURN_FUNCTION_TYPE bmg160_set_nvm_prog_mode(unsigned char prog_mode)
{
BMG160_RETURN_FUNCTION_TYPE comres = C_BMG160_Zero_U8X;
unsigned char v_data_u8r = C_BMG160_Zero_U8X;
if (p_bmg160 == BMG160_NULL) {
return E_BMG160_NULL_PTR;
} else {
comres = p_bmg160->BMG160_BUS_READ_FUNC(p_bmg160->dev_addr,
BMG160_TRIM_NVM_CTRL_ADDR_NVM_PROG_MODE__REG, &v_data_u8r, 1);
v_data_u8r = BMG160_SET_BITSLICE(v_data_u8r,
BMG160_TRIM_NVM_CTRL_ADDR_NVM_PROG_MODE, prog_mode);
comres += p_bmg160->BMG160_BUS_WRITE_FUNC(p_bmg160->dev_addr,
BMG160_TRIM_NVM_CTRL_ADDR_NVM_PROG_MODE__REG, &v_data_u8r, 1);
}
return comres;
}
/* Compiler Switch if applicable
#ifdef
#endif
*/
/*****************************************************************************
* Description: *//**brief This API is used to get the status of i2c wdt
*
*
*
*
*\param unsigned char channel,unsigned char *prog_mode
* BMG160_I2C_WDT_SEL 1
* BMG160_I2C_WDT_EN 0
* *prog_mode : Address of prog_mode
* Pointer to a variable passed as a parameter
*
*
*
* \return
*
*
*****************************************************************************/
/* Scheduling:
*
*
*
* Usage guide:
*
*
* Remarks:
*
*****************************************************************************/
BMG160_RETURN_FUNCTION_TYPE bmg160_get_i2c_wdt(unsigned char i2c_wdt,
unsigned char *prog_mode)
{
BMG160_RETURN_FUNCTION_TYPE comres = C_BMG160_Zero_U8X;
unsigned char v_data_u8r = C_BMG160_Zero_U8X;
if (p_bmg160 == BMG160_NULL) {
return E_BMG160_NULL_PTR;
} else {
switch (i2c_wdt) {
case BMG160_I2C_WDT_EN:
comres = p_bmg160->BMG160_BUS_READ_FUNC
(p_bmg160->dev_addr,
BMG160_BGW_SPI3_WDT_ADDR_I2C_WDT_EN__REG,
&v_data_u8r, 1);
*prog_mode = BMG160_GET_BITSLICE(v_data_u8r,
BMG160_BGW_SPI3_WDT_ADDR_I2C_WDT_EN);
break;
case BMG160_I2C_WDT_SEL:
comres = p_bmg160->BMG160_BUS_READ_FUNC
(p_bmg160->dev_addr,
BMG160_BGW_SPI3_WDT_ADDR_I2C_WDT_SEL__REG,
&v_data_u8r, 1);
*prog_mode = BMG160_GET_BITSLICE(v_data_u8r,
BMG160_BGW_SPI3_WDT_ADDR_I2C_WDT_SEL);
break;
default:
comres = E_BMG160_OUT_OF_RANGE;
break;
}
}
return comres;
}
/* Compiler Switch if applicable
#ifdef
#endif
*/
/*****************************************************************************
* Description: *//**brief This API is used to set the status of i2c wdt
*
*
*
*
*\param unsigned char channel,unsigned char prog_mode
* BMG160_I2C_WDT_SEL 1
* BMG160_I2C_WDT_EN 0
* prog_mode : Value to be written passed as a parameter
*
*
*
* \return communication results
*
*
*****************************************************************************/
/* Scheduling:
*
*
*
* Usage guide:
*
*
* Remarks:
*
*****************************************************************************/
BMG160_RETURN_FUNCTION_TYPE bmg160_set_i2c_wdt(unsigned char i2c_wdt,
unsigned char prog_mode)
{
BMG160_RETURN_FUNCTION_TYPE comres = C_BMG160_Zero_U8X;
unsigned char v_data_u8r = C_BMG160_Zero_U8X;
if (p_bmg160 == BMG160_NULL) {
return E_BMG160_NULL_PTR;
} else {
switch (i2c_wdt) {
case BMG160_I2C_WDT_EN:
comres = p_bmg160->BMG160_BUS_READ_FUNC
(p_bmg160->dev_addr,
BMG160_BGW_SPI3_WDT_ADDR_I2C_WDT_EN__REG,
&v_data_u8r, 1);
v_data_u8r = BMG160_SET_BITSLICE(v_data_u8r,
BMG160_BGW_SPI3_WDT_ADDR_I2C_WDT_EN, prog_mode);
comres += p_bmg160->BMG160_BUS_WRITE_FUNC
(p_bmg160->dev_addr,
BMG160_BGW_SPI3_WDT_ADDR_I2C_WDT_EN__REG,
&v_data_u8r, 1);
break;
case BMG160_I2C_WDT_SEL:
comres = p_bmg160->BMG160_BUS_READ_FUNC
(p_bmg160->dev_addr,
BMG160_BGW_SPI3_WDT_ADDR_I2C_WDT_SEL__REG,
&v_data_u8r, 1);
v_data_u8r = BMG160_SET_BITSLICE(v_data_u8r,
BMG160_BGW_SPI3_WDT_ADDR_I2C_WDT_SEL, prog_mode);
comres += p_bmg160->BMG160_BUS_WRITE_FUNC
(p_bmg160->dev_addr,
BMG160_BGW_SPI3_WDT_ADDR_I2C_WDT_SEL__REG,
&v_data_u8r, 1);
break;
default:
comres = E_BMG160_OUT_OF_RANGE;
break;
}
}
return comres;
}
/* Compiler Switch if applicable
#ifdef
#endif
*/
/*****************************************************************************
* Description: *//**brief This API is used to get the status of spi3
*
*
*
*
* \param unsigned char *spi3 : Address of spi3
* Pointer to a variable passed as a parameter
*
*
*
*
* \return
*
*
*****************************************************************************/
/* Scheduling:
*
*
*
* Usage guide:
*
*
* Remarks:
*
*****************************************************************************/
BMG160_RETURN_FUNCTION_TYPE bmg160_get_spi3(unsigned char *spi3)
{
BMG160_RETURN_FUNCTION_TYPE comres = C_BMG160_Zero_U8X;
unsigned char v_data_u8r = C_BMG160_Zero_U8X;
if (p_bmg160 == BMG160_NULL) {
return E_BMG160_NULL_PTR;
} else {
comres = p_bmg160->BMG160_BUS_READ_FUNC(p_bmg160->dev_addr,
BMG160_BGW_SPI3_WDT_ADDR_SPI3__REG, &v_data_u8r, 1);
*spi3 = BMG160_GET_BITSLICE(v_data_u8r,
BMG160_BGW_SPI3_WDT_ADDR_SPI3);
}
return comres;
}
/* Compiler Switch if applicable
#ifdef
#endif
*/
/*****************************************************************************
* Description: *//**brief This API is used to set the status of spi3
*
*
*
*
*\param unsigned char spi3
*
*
*
*
*
*
* \return communication results
*
*
*****************************************************************************/
/* Scheduling:
*
*
*
* Usage guide:
*
*
* Remarks:
*
*****************************************************************************/
BMG160_RETURN_FUNCTION_TYPE bmg160_set_spi3(unsigned char spi3)
{
BMG160_RETURN_FUNCTION_TYPE comres = C_BMG160_Zero_U8X;
unsigned char v_data_u8r = C_BMG160_Zero_U8X;
if (p_bmg160 == BMG160_NULL) {
return E_BMG160_NULL_PTR;
} else {
comres = p_bmg160->BMG160_BUS_READ_FUNC(p_bmg160->dev_addr,
BMG160_BGW_SPI3_WDT_ADDR_SPI3__REG, &v_data_u8r, 1);
v_data_u8r = BMG160_SET_BITSLICE(v_data_u8r,
BMG160_BGW_SPI3_WDT_ADDR_SPI3, spi3);
comres += p_bmg160->BMG160_BUS_WRITE_FUNC(p_bmg160->dev_addr,
BMG160_BGW_SPI3_WDT_ADDR_SPI3__REG, &v_data_u8r, 1);
}
return comres;
}
/* Scheduling:
*
*
*
* Usage guide:
*
*
* Remarks:
*
*****************************************************************************/
BMG160_RETURN_FUNCTION_TYPE bmg160_get_fifo_tag(unsigned char *tag)
{
BMG160_RETURN_FUNCTION_TYPE comres = C_BMG160_Zero_U8X;
unsigned char v_data_u8r = C_BMG160_Zero_U8X;
if (p_bmg160 == BMG160_NULL) {
return E_BMG160_NULL_PTR;
} else {
comres = p_bmg160->BMG160_BUS_READ_FUNC(p_bmg160->dev_addr,
BMG160_FIFO_CGF1_ADDR_TAG__REG, &v_data_u8r, 1);
*tag = BMG160_GET_BITSLICE(v_data_u8r,
BMG160_FIFO_CGF1_ADDR_TAG);
}
return comres;
}
/* Compiler Switch if applicable
#ifdef
#endif
*/
/*****************************************************************************
* Description: *//**brief This API is used to set the status of Tag
*
*
*
*
*\param unsigned char tag
* Enable -> 1
* Disable -> 0
*
*
*
*
*
* \return communication results
*
*
*****************************************************************************/
/* Scheduling:
*
*
*
* Usage guide:
*
*
* Remarks:
*
*****************************************************************************/
BMG160_RETURN_FUNCTION_TYPE bmg160_set_fifo_tag(unsigned char tag)
{
BMG160_RETURN_FUNCTION_TYPE comres = C_BMG160_Zero_U8X;
unsigned char v_data_u8r = C_BMG160_Zero_U8X;
if (p_bmg160 == BMG160_NULL) {
return E_BMG160_NULL_PTR;
} else {
if (tag < C_BMG160_Two_U8X) {
comres = p_bmg160->BMG160_BUS_READ_FUNC
(p_bmg160->dev_addr,
BMG160_FIFO_CGF1_ADDR_TAG__REG, &v_data_u8r, 1);
v_data_u8r = BMG160_SET_BITSLICE(v_data_u8r,
BMG160_FIFO_CGF1_ADDR_TAG, tag);
comres += p_bmg160->BMG160_BUS_WRITE_FUNC
(p_bmg160->dev_addr,
BMG160_FIFO_CGF1_ADDR_TAG__REG, &v_data_u8r, 1);
} else {
comres = E_BMG160_OUT_OF_RANGE;
}
}
return comres;
}
/* Compiler Switch if applicable
#ifdef
#endif
*/
/*****************************************************************************
* Description: *//**brief This API is used to get Water Mark Level
*
*
*
*
*\param unsigned char *water_mark_level : Address of water_mark_level
* Pointer to a variable passed as a parameter
*
*
*
* \return
*
*
*****************************************************************************/
/* Scheduling:
*
*
*
* Usage guide:
*
*
* Remarks:
*
*****************************************************************************/
BMG160_RETURN_FUNCTION_TYPE bmg160_get_fifo_watermarklevel(
unsigned char *water_mark_level)
{
BMG160_RETURN_FUNCTION_TYPE comres = C_BMG160_Zero_U8X;
unsigned char v_data_u8r = C_BMG160_Zero_U8X;
if (p_bmg160 == BMG160_NULL) {
return E_BMG160_NULL_PTR;
} else {
comres = p_bmg160->BMG160_BUS_READ_FUNC(p_bmg160->dev_addr,
BMG160_FIFO_CGF1_ADDR_WML__REG, &v_data_u8r, 1);
*water_mark_level = BMG160_GET_BITSLICE(v_data_u8r,
BMG160_FIFO_CGF1_ADDR_WML);
}
return comres;
}
/* Compiler Switch if applicable
#ifdef
#endif
*/
/*****************************************************************************
* Description: *//**brief This API is used to set Water Mark Level
*
*
*
*
*\param unsigned char water_mark_level:
* Value to be written passed as a parameter
*
*
*
* \return communication results
*
*
*****************************************************************************/
/* Scheduling:
*
*
*
* Usage guide:
*
*
* Remarks:
*
*****************************************************************************/
BMG160_RETURN_FUNCTION_TYPE bmg160_set_fifo_watermarklevel(
unsigned char water_mark_level)
{
BMG160_RETURN_FUNCTION_TYPE comres = C_BMG160_Zero_U8X;
unsigned char v_data_u8r = C_BMG160_Zero_U8X;
if (p_bmg160 == BMG160_NULL) {
return E_BMG160_NULL_PTR;
} else {
if (water_mark_level < C_BMG160_OneTwentyEight_U8X) {
comres = p_bmg160->BMG160_BUS_READ_FUNC
(p_bmg160->dev_addr,
BMG160_FIFO_CGF1_ADDR_WML__REG, &v_data_u8r, 1);
v_data_u8r = BMG160_SET_BITSLICE(v_data_u8r,
BMG160_FIFO_CGF1_ADDR_WML, water_mark_level);
comres += p_bmg160->BMG160_BUS_WRITE_FUNC
(p_bmg160->dev_addr,
BMG160_FIFO_CGF1_ADDR_WML__REG, &v_data_u8r, 1);
} else {
comres = E_BMG160_OUT_OF_RANGE;
}
}
return comres;
}
/* Compiler Switch if applicable
#ifdef
#endif
*/
/*****************************************************************************
* Description: *//**brief This API is used to get the status of offset
*
*
*
*
*\param unsigned char axis,unsigned char *offset
* axis ->
* BMG160_X_AXIS -> 0
* BMG160_Y_AXIS -> 1
* BMG160_Z_AXIS -> 2
* offset -> Any valid value
*
*
*
*
*
*
* \return
*
*
*****************************************************************************/
/* Scheduling:
*
*
*
* Usage guide:
*
*
* Remarks:
*
*****************************************************************************/
BMG160_RETURN_FUNCTION_TYPE bmg160_get_offset(unsigned char axis,
BMG160_S16 *offset)
{
BMG160_RETURN_FUNCTION_TYPE comres = C_BMG160_Zero_U8X;
unsigned char v_data1_u8r = C_BMG160_Zero_U8X;
unsigned char v_data2_u8r = C_BMG160_Zero_U8X;
if (p_bmg160 == BMG160_NULL) {
return E_BMG160_NULL_PTR;
} else {
switch (axis) {
case BMG160_X_AXIS:
comres = p_bmg160->BMG160_BUS_READ_FUNC
(p_bmg160->dev_addr,
BMG160_TRIM_GP0_ADDR_OFFSET_X__REG, &v_data1_u8r, 1);
v_data1_u8r = BMG160_GET_BITSLICE(v_data1_u8r,
BMG160_TRIM_GP0_ADDR_OFFSET_X);
comres = p_bmg160->BMG160_BUS_READ_FUNC
(p_bmg160->dev_addr,
BMG160_OFC1_ADDR_OFFSET_X__REG, &v_data2_u8r, 1);
v_data2_u8r = BMG160_GET_BITSLICE(v_data2_u8r,
BMG160_OFC1_ADDR_OFFSET_X);
v_data2_u8r = ((v_data2_u8r <<
BMG160_SHIFT_2_POSITION) | v_data1_u8r);
comres = p_bmg160->BMG160_BUS_READ_FUNC
(p_bmg160->dev_addr, BMG160_OFC2_ADDR, &v_data1_u8r, 1);
*offset = (BMG160_S16)((((BMG160_S16)
((signed char)v_data1_u8r))
<< BMG160_SHIFT_4_POSITION) | (v_data2_u8r));
break;
case BMG160_Y_AXIS:
comres = p_bmg160->BMG160_BUS_READ_FUNC
(p_bmg160->dev_addr,
BMG160_TRIM_GP0_ADDR_OFFSET_Y__REG, &v_data1_u8r, 1);
v_data1_u8r = BMG160_GET_BITSLICE(v_data1_u8r,
BMG160_TRIM_GP0_ADDR_OFFSET_Y);
comres = p_bmg160->BMG160_BUS_READ_FUNC
(p_bmg160->dev_addr,
BMG160_OFC1_ADDR_OFFSET_Y__REG, &v_data2_u8r, 1);
v_data2_u8r = BMG160_GET_BITSLICE(v_data2_u8r,
BMG160_OFC1_ADDR_OFFSET_Y);
v_data2_u8r = ((v_data2_u8r <<
BMG160_SHIFT_1_POSITION) | v_data1_u8r);
comres = p_bmg160->BMG160_BUS_READ_FUNC
(p_bmg160->dev_addr,
BMG160_OFC3_ADDR, &v_data1_u8r, 1);
*offset = (BMG160_S16)((((BMG160_S16)
((signed char)v_data1_u8r))
<< BMG160_SHIFT_4_POSITION) | (v_data2_u8r));
break;
case BMG160_Z_AXIS:
comres = p_bmg160->BMG160_BUS_READ_FUNC
(p_bmg160->dev_addr,
BMG160_TRIM_GP0_ADDR_OFFSET_Z__REG, &v_data1_u8r, 1);
v_data1_u8r = BMG160_GET_BITSLICE(v_data1_u8r,
BMG160_TRIM_GP0_ADDR_OFFSET_Z);
comres = p_bmg160->BMG160_BUS_READ_FUNC
(p_bmg160->dev_addr,
BMG160_OFC1_ADDR_OFFSET_Z__REG, &v_data2_u8r, 1);
v_data2_u8r = BMG160_GET_BITSLICE(v_data2_u8r,
BMG160_OFC1_ADDR_OFFSET_Z);
v_data2_u8r = ((v_data2_u8r << BMG160_SHIFT_1_POSITION)
| v_data1_u8r);
comres = p_bmg160->BMG160_BUS_READ_FUNC
(p_bmg160->dev_addr,
BMG160_OFC4_ADDR, &v_data1_u8r, 1);
*offset = (BMG160_S16)((((BMG160_S16)
((signed char)v_data1_u8r))
<< BMG160_SHIFT_4_POSITION) | (v_data2_u8r));
break;
default:
comres = E_BMG160_OUT_OF_RANGE;
break;
}
}
return comres;
}
/* Compiler Switch if applicable
#ifdef
#endif
*/
/*****************************************************************************
* Description: *//**brief This API is used to set the status of offset
*
*
*
*
*\param unsigned char axis,unsigned char offset
* axis ->
* BMG160_X_AXIS -> 0
* BMG160_Y_AXIS -> 1
* BMG160_Z_AXIS -> 2
* offset -> Any valid value
*
*
*
*
*
*
* \return
*
*
*****************************************************************************/
/* Scheduling:
*
*
*
* Usage guide:
*
*
* Remarks:
*
*****************************************************************************/
BMG160_RETURN_FUNCTION_TYPE bmg160_set_offset(
unsigned char axis, BMG160_S16 offset)
{
BMG160_RETURN_FUNCTION_TYPE comres = C_BMG160_Zero_U8X;
unsigned char v_data1_u8r = C_BMG160_Zero_U8X;
unsigned char v_data2_u8r = C_BMG160_Zero_U8X;
if (p_bmg160 == BMG160_NULL) {
return E_BMG160_NULL_PTR;
} else {
switch (axis) {
case BMG160_X_AXIS:
v_data1_u8r = ((signed char) (offset & 0x0FF0))
>> BMG160_SHIFT_4_POSITION;
comres = p_bmg160->BMG160_BUS_WRITE_FUNC
(p_bmg160->dev_addr,
BMG160_OFC2_ADDR, &v_data1_u8r, 1);
v_data1_u8r = (unsigned char) (offset & 0x000C);
v_data2_u8r = BMG160_SET_BITSLICE(v_data2_u8r,
BMG160_OFC1_ADDR_OFFSET_X, v_data1_u8r);
comres += p_bmg160->BMG160_BUS_READ_FUNC
(p_bmg160->dev_addr,
BMG160_OFC1_ADDR_OFFSET_X__REG, &v_data2_u8r, 1);
v_data1_u8r = (unsigned char) (offset & 0x0003);
v_data2_u8r = BMG160_SET_BITSLICE(v_data2_u8r,
BMG160_TRIM_GP0_ADDR_OFFSET_X, v_data1_u8r);
comres += p_bmg160->BMG160_BUS_WRITE_FUNC
(p_bmg160->dev_addr,
BMG160_TRIM_GP0_ADDR_OFFSET_X__REG, &v_data2_u8r, 1);
break;
case BMG160_Y_AXIS:
v_data1_u8r = ((signed char) (offset & 0x0FF0)) >>
BMG160_SHIFT_4_POSITION;
comres = p_bmg160->BMG160_BUS_WRITE_FUNC
(p_bmg160->dev_addr,
BMG160_OFC3_ADDR, &v_data1_u8r, 1);
v_data1_u8r = (unsigned char) (offset & 0x000E);
v_data2_u8r = BMG160_SET_BITSLICE(v_data2_u8r,
BMG160_OFC1_ADDR_OFFSET_Y, v_data1_u8r);
comres += p_bmg160->BMG160_BUS_READ_FUNC
(p_bmg160->dev_addr,
BMG160_OFC1_ADDR_OFFSET_Y__REG, &v_data2_u8r, 1);
v_data1_u8r = (unsigned char) (offset & 0x0001);
v_data2_u8r = BMG160_SET_BITSLICE(v_data2_u8r,
BMG160_TRIM_GP0_ADDR_OFFSET_Y, v_data1_u8r);
comres += p_bmg160->BMG160_BUS_WRITE_FUNC
(p_bmg160->dev_addr,
BMG160_TRIM_GP0_ADDR_OFFSET_Y__REG, &v_data2_u8r, 1);
break;
case BMG160_Z_AXIS:
v_data1_u8r = ((signed char) (offset & 0x0FF0)) >>
BMG160_SHIFT_4_POSITION;
comres = p_bmg160->BMG160_BUS_WRITE_FUNC
(p_bmg160->dev_addr,
BMG160_OFC4_ADDR, &v_data1_u8r, 1);
v_data1_u8r = (unsigned char) (offset & 0x000E);
v_data2_u8r = BMG160_SET_BITSLICE(v_data2_u8r,
BMG160_OFC1_ADDR_OFFSET_Z, v_data1_u8r);
comres += p_bmg160->BMG160_BUS_READ_FUNC
(p_bmg160->dev_addr,
BMG160_OFC1_ADDR_OFFSET_Z__REG, &v_data2_u8r, 1);
v_data1_u8r = (unsigned char) (offset & 0x0001);
v_data2_u8r = BMG160_SET_BITSLICE(v_data2_u8r,
BMG160_TRIM_GP0_ADDR_OFFSET_Z, v_data1_u8r);
comres += p_bmg160->BMG160_BUS_WRITE_FUNC
(p_bmg160->dev_addr,
BMG160_TRIM_GP0_ADDR_OFFSET_Z__REG, &v_data2_u8r, 1);
break;
default:
comres = E_BMG160_OUT_OF_RANGE;
break;
}
}
return comres;
}
/* Compiler Switch if applicable
#ifdef
#endif
*/
/*****************************************************************************
* Description: *//**brief This API is used to get the status of general
* purpose register
*
*
*
*
*\param unsigned char param,unsigned char *value
* param ->
* BMG160_GP0 0
* BMG160_GP0 1
* *value -> Address of high_bw
* Pointer to a variable passed as a parameter
*
*
*
*
*
* \return
*
*
*****************************************************************************/
/* Scheduling:
*
*
*
* Usage guide:
*
*
* Remarks:
*
*****************************************************************************/
BMG160_RETURN_FUNCTION_TYPE bmg160_get_gp(unsigned char param,
unsigned char *value)
{
BMG160_RETURN_FUNCTION_TYPE comres = C_BMG160_Zero_U8X;
unsigned char v_data_u8r = C_BMG160_Zero_U8X;
if (p_bmg160 == BMG160_NULL) {
return E_BMG160_NULL_PTR;
} else {
switch (param) {
case BMG160_GP0:
comres = p_bmg160->BMG160_BUS_READ_FUNC
(p_bmg160->dev_addr,
BMG160_TRIM_GP0_ADDR_GP0__REG, &v_data_u8r, 1);
*value = BMG160_GET_BITSLICE(v_data_u8r,
BMG160_TRIM_GP0_ADDR_GP0);
break;
case BMG160_GP1:
comres = p_bmg160->BMG160_BUS_READ_FUNC
(p_bmg160->dev_addr,
BMG160_TRIM_GP1_ADDR, &v_data_u8r, 1);
*value = v_data_u8r;
break;
default:
comres = E_BMG160_OUT_OF_RANGE;
break;
}
}
return comres;
}
/* Compiler Switch if applicable
#ifdef
#endif
*/
/*****************************************************************************
* Description: *//**brief This API is used to set the status of general
* purpose register
*
*
*
*
*\param unsigned char param,unsigned char value
* param ->
* BMG160_GP0 0
* BMG160_GP0 1
* value -> Value to be written passed as a parameter
*
*
*
* \return communication results
*
*
*****************************************************************************/
/* Scheduling:
*
*
*
* Usage guide:
*
*
* Remarks:
*
*****************************************************************************/
BMG160_RETURN_FUNCTION_TYPE bmg160_set_gp(unsigned char param,
unsigned char value)
{
BMG160_RETURN_FUNCTION_TYPE comres = C_BMG160_Zero_U8X;
unsigned char v_data_u8r = C_BMG160_Zero_U8X;
if (p_bmg160 == BMG160_NULL) {
return E_BMG160_NULL_PTR;
} else {
switch (param) {
case BMG160_GP0:
comres = p_bmg160->BMG160_BUS_READ_FUNC
(p_bmg160->dev_addr,
BMG160_TRIM_GP0_ADDR_GP0__REG, &v_data_u8r, 1);
v_data_u8r = BMG160_SET_BITSLICE(v_data_u8r,
BMG160_TRIM_GP0_ADDR_GP0, value);
comres += p_bmg160->BMG160_BUS_WRITE_FUNC
(p_bmg160->dev_addr,
BMG160_TRIM_GP0_ADDR_GP0__REG, &v_data_u8r, 1);
break;
case BMG160_GP1:
v_data_u8r = value;
comres = p_bmg160->BMG160_BUS_WRITE_FUNC
(p_bmg160->dev_addr,
BMG160_TRIM_GP1_ADDR, &v_data_u8r, 1);
break;
default:
comres = E_BMG160_OUT_OF_RANGE;
break;
}
}
return comres;
}
/* Compiler Switch if applicable
#ifdef
#endif
*/
/*****************************************************************************
* Description: *//**brief Reads FIFI data from location 3Fh
*
*
*
*
* \param
* unsigned char *fifo_data : Address of FIFO data bits
*
*
*
*
* \return result of communication routines
*
*
*****************************************************************************/
/* Scheduling:
*
*
*
* Usage guide:
*
*
* Remarks:
*
*****************************************************************************/
BMG160_RETURN_FUNCTION_TYPE bmg160_get_FIFO_data_reg(unsigned char *fifo_data)
{
BMG160_RETURN_FUNCTION_TYPE comres = C_BMG160_Zero_U8X;
unsigned char v_data_u8r = C_BMG160_Zero_U8X;
if (p_bmg160 == BMG160_NULL) {
return E_BMG160_NULL_PTR;
} else {
comres = p_bmg160->BMG160_BUS_READ_FUNC(p_bmg160->dev_addr,
BMG160_FIFO_DATA_ADDR, &v_data_u8r, 1);
*fifo_data = v_data_u8r;
}
return comres;
}
/* Compiler Switch if applicable
#ifdef
#endif
*/
/*****************************************************************************
* Description: *//**brief Reads interrupt fifo status register byte from 0Eh
*
*
*
*
* \param
* unsigned char *fifo_status : Address of Fifo status register
*
*
* \return
* Result of bus communication function
*
*****************************************************************************/
/* Scheduling:
*
*
*
* Usage guide:
*
*
* Remarks:
*
*****************************************************************************/
BMG160_RETURN_FUNCTION_TYPE bmg160_get_fifostatus_reg(
unsigned char *fifo_status)
{
BMG160_RETURN_FUNCTION_TYPE comres = C_BMG160_Zero_U8X;
if (p_bmg160 == BMG160_NULL) {
return E_BMG160_NULL_PTR;
} else {
comres = p_bmg160->BMG160_BUS_READ_FUNC(p_bmg160->dev_addr,
BMG160_FIFO_STATUS_ADDR, fifo_status, 1);
}
return comres;
}
/* Compiler Switch if applicable
#ifdef
#endif
*/
/*****************************************************************************
* Description: *//**brief Reads interrupt fifo status register byte from 0Eh
*
*
*
*
* \param
* unsigned char *fifo_framecount: Address of FIFO status register
*
*
* \return
* Result of bus communication function
*
*****************************************************************************/
/* Scheduling:
*
*
*
* Usage guide:
*
*
* Remarks:
*
*****************************************************************************/
BMG160_RETURN_FUNCTION_TYPE bmg160_get_fifo_framecount(
unsigned char *fifo_framecount)
{
BMG160_RETURN_FUNCTION_TYPE comres = C_BMG160_Zero_U8X;
unsigned char v_data_u8r = C_BMG160_Zero_U8X;
if (p_bmg160 == BMG160_NULL) {
return E_BMG160_NULL_PTR;
} else {
comres = p_bmg160->BMG160_BUS_READ_FUNC(p_bmg160->dev_addr,
BMG160_FIFO_STATUS_FRAME_COUNTER__REG, &v_data_u8r, 1);
*fifo_framecount = BMG160_GET_BITSLICE(v_data_u8r,
BMG160_FIFO_STATUS_FRAME_COUNTER);
}
return comres;
}
/* Compiler Switch if applicable
#ifdef
#endif
*/
/*****************************************************************************
* Description: *//**brief Reads interrupt fifo status register byte from 0Eh
*
*
*
*
* \param
* unsigned char *fifo_overrun: Address of FIFO status register
*
*
* \return
* Result of bus communication function
*
*****************************************************************************/
/* Scheduling:
*
*
*
* Usage guide:
*
*
* Remarks:
*
*****************************************************************************/
BMG160_RETURN_FUNCTION_TYPE bmg160_get_fifo_overrun(
unsigned char *fifo_overrun)
{
BMG160_RETURN_FUNCTION_TYPE comres = C_BMG160_Zero_U8X;
unsigned char v_data_u8r = C_BMG160_Zero_U8X;
if (p_bmg160 == BMG160_NULL) {
return E_BMG160_NULL_PTR;
} else {
comres = p_bmg160->BMG160_BUS_READ_FUNC(p_bmg160->dev_addr,
BMG160_FIFO_STATUS_OVERRUN__REG, &v_data_u8r, 1);
*fifo_overrun = BMG160_GET_BITSLICE(v_data_u8r,
BMG160_FIFO_STATUS_OVERRUN);
}
return comres;
}
/* Compiler Switch if applicable
#ifdef
#endif
*/
/*****************************************************************************
* Description: *//**brief This API is used to get the status of fifo mode
*
*
*
*
*\param unsigned char *mode : Address of mode
* fifo_mode 0 --> Bypass
* 1 --> FIFO
* 2 --> Stream
* 3 --> Reserved
*
*
*
*
* \return
*
*
*****************************************************************************/
/* Scheduling:
*
*
*
* Usage guide:
*
*
* Remarks:
*
*****************************************************************************/
BMG160_RETURN_FUNCTION_TYPE bmg160_get_fifo_mode(unsigned char *mode)
{
BMG160_RETURN_FUNCTION_TYPE comres = C_BMG160_Zero_U8X;
unsigned char v_data_u8r = C_BMG160_Zero_U8X;
if (p_bmg160 == BMG160_NULL) {
return E_BMG160_NULL_PTR;
} else {
comres = p_bmg160->BMG160_BUS_READ_FUNC(p_bmg160->dev_addr,
BMG160_FIFO_CGF0_ADDR_MODE__REG, &v_data_u8r, 1);
*mode = BMG160_GET_BITSLICE(v_data_u8r,
BMG160_FIFO_CGF0_ADDR_MODE);
}
return comres;
}
/* Compiler Switch if applicable
#ifdef
#endif
*/
/*****************************************************************************
* Description: *//**brief This API is used set to FIFO mode
*
*
*
*
* \param 0 --> BYPASS
* 1 --> FIFO
* 2 --> STREAM
*
*
* \return Communication Results
*
*
*****************************************************************************/
/* Scheduling:
*
*
*
* Usage guide:
*
*
*
*****************************************************************************/
BMG160_RETURN_FUNCTION_TYPE bmg160_set_fifo_mode(unsigned char mode)
{
int comres = C_BMG160_Zero_U8X;
unsigned char v_data_u8r = C_BMG160_Zero_U8X;
if (p_bmg160 == BMG160_NULL) {
return E_BMG160_NULL_PTR;
} else {
if (mode < C_BMG160_Four_U8X) {
comres = p_bmg160->BMG160_BUS_READ_FUNC
(p_bmg160->dev_addr,
BMG160_FIFO_CGF0_ADDR_MODE__REG, &v_data_u8r, 1);
v_data_u8r = BMG160_SET_BITSLICE(v_data_u8r,
BMG160_FIFO_CGF0_ADDR_MODE, mode);
comres += p_bmg160->BMG160_BUS_WRITE_FUNC
(p_bmg160->dev_addr,
BMG160_FIFO_CGF0_ADDR_MODE__REG, &v_data_u8r, 1);
} else {
comres = E_BMG160_OUT_OF_RANGE;
}
}
return comres;
}
/* Compiler Switch if applicable
#ifdef
#endif
*/
/*****************************************************************************
* Description: *//**brief This API is used to get the status of fifo data
* sel
*
*
*
*
*\param unsigned char *data_sel : Address of data_sel
* data_sel --> [0:3]
* 0 --> X,Y and Z (DEFAULT)
* 1 --> X only
* 2 --> Y only
* 3 --> Z only
*
*
*
*
*
* \return
*
*
*****************************************************************************/
/* Scheduling:
*
*
*
* Usage guide:
*
*
* Remarks:
*
*****************************************************************************/
BMG160_RETURN_FUNCTION_TYPE bmg160_get_fifo_data_sel(unsigned char *data_sel)
{
BMG160_RETURN_FUNCTION_TYPE comres = C_BMG160_Zero_U8X;
unsigned char v_data_u8r = C_BMG160_Zero_U8X;
if (p_bmg160 == BMG160_NULL) {
return E_BMG160_NULL_PTR;
} else {
comres = p_bmg160->BMG160_BUS_READ_FUNC(p_bmg160->dev_addr,
BMG160_FIFO_CGF0_ADDR_DATA_SEL__REG, &v_data_u8r, 1);
*data_sel = BMG160_GET_BITSLICE(v_data_u8r,
BMG160_FIFO_CGF0_ADDR_DATA_SEL);
}
return comres;
}
/* Compiler Switch if applicable
#ifdef
#endif
*/
/*****************************************************************************
* Description: *//**brief This API is used to set the status of fifo data
* sel
*
*
*
*
*\param unsigned char data_sel
* data_sel --> [0:3]
* 0 --> X,Y and Z (DEFAULT)
* 1 --> X only
* 2 --> Y only
* 3 --> Z only
*
*
*
* \return communication results
*
*
*
*
*****************************************************************************/
/* Scheduling:
*
*
*
* Usage guide:
*
*
* Remarks:
*
*****************************************************************************/
BMG160_RETURN_FUNCTION_TYPE bmg160_set_fifo_data_sel(unsigned char data_sel)
{
BMG160_RETURN_FUNCTION_TYPE comres = C_BMG160_Zero_U8X;
unsigned char v_data_u8r = C_BMG160_Zero_U8X;
if (p_bmg160 == BMG160_NULL) {
return E_BMG160_NULL_PTR;
} else {
if (data_sel < C_BMG160_Four_U8X) {
comres = p_bmg160->BMG160_BUS_READ_FUNC
(p_bmg160->dev_addr,
BMG160_FIFO_CGF0_ADDR_DATA_SEL__REG, &v_data_u8r, 1);
v_data_u8r = BMG160_SET_BITSLICE(v_data_u8r,
BMG160_FIFO_CGF0_ADDR_DATA_SEL, data_sel);
comres += p_bmg160->BMG160_BUS_WRITE_FUNC
(p_bmg160->dev_addr,
BMG160_FIFO_CGF0_ADDR_DATA_SEL__REG, &v_data_u8r, 1);
} else {
comres = E_BMG160_OUT_OF_RANGE;
}
}
return comres;
}
/* Compiler Switch if applicable
#ifdef
#endif
*/
/*****************************************************************************
* Description: *//**brief This API is used to get the operating modes of the
* sensor
*
*
*
*
*\param unsigned char * mode : Address of mode
* 0 -> NORMAL
* 1 -> SUSPEND
* 2 -> DEEP SUSPEND
* 3 -> FAST POWERUP
* 4 -> ADVANCED POWERSAVING
*
*
* \return
*
*
*****************************************************************************/
/* Scheduling:
*
*
*
* Usage guide:
*
*
* Remarks:
*
*****************************************************************************/
BMG160_RETURN_FUNCTION_TYPE bmg160_get_mode(unsigned char *mode)
{
BMG160_RETURN_FUNCTION_TYPE comres = C_BMG160_Zero_U8X;
unsigned char data1 = C_BMG160_Zero_U8X;
unsigned char data2 = C_BMG160_Zero_U8X;
unsigned char data3 = C_BMG160_Zero_U8X;
if (p_bmg160 == C_BMG160_Zero_U8X) {
return E_BMG160_NULL_PTR;
} else {
comres = p_bmg160->BMG160_BUS_READ_FUNC(p_bmg160->dev_addr,
BMG160_MODE_LPM1_ADDR, &data1, C_BMG160_One_U8X);
comres += p_bmg160->BMG160_BUS_READ_FUNC(p_bmg160->dev_addr,
BMG160_MODE_LPM2_ADDR, &data2, C_BMG160_One_U8X);
data1 = (data1 & 0xA0) >> 5;
data3 = (data2 & 0x40) >> 6;
data2 = (data2 & 0x80) >> 7;
if (data3 == 0x01) {
*mode = BMG160_MODE_ADVANCEDPOWERSAVING;
} else {
if ((data1 == 0x00) && (data2 == 0x00)) {
*mode = BMG160_MODE_NORMAL;
} else {
if ((data1 == 0x01) || (data1 == 0x05)) {
*mode = BMG160_MODE_DEEPSUSPEND;
} else {
if ((data1 == 0x04) &&
(data2 == 0x00)) {
*mode = BMG160_MODE_SUSPEND;
} else {
if ((data1 == 0x04) &&
(data2 == 0x01))
*mode =
BMG160_MODE_FASTPOWERUP;
}
}
}
}
}
return comres;
}
/* Compiler Switch if applicable
#ifdef
#endif
*/
/*****************************************************************************
* Description: *//**brief This API is used to set the operating Modes of the
* sensor
*
*
*
*
*\param unsigned char Mode
* 0 -> NORMAL
* 1 -> DEEPSUSPEND
* 2 -> SUSPEND
* 3 -> Fast Powerup
* 4 -> Advance Powerup
* \return communication results
*
*
*****************************************************************************/
/* Scheduling:
*
*
*
* Usage guide:
*
*
* Remarks:
*
*****************************************************************************/
BMG160_RETURN_FUNCTION_TYPE bmg160_set_mode(unsigned char mode)
{
BMG160_RETURN_FUNCTION_TYPE comres = C_BMG160_Zero_U8X;
unsigned char data1 = C_BMG160_Zero_U8X;
unsigned char data2 = C_BMG160_Zero_U8X;
unsigned char data3 = C_BMG160_Zero_U8X;
unsigned char v_autosleepduration = C_BMG160_Zero_U8X;
unsigned char v_bw_u8r = C_BMG160_Zero_U8X;
if (p_bmg160 == C_BMG160_Zero_U8X) {
return E_BMG160_NULL_PTR;
} else {
if (mode < C_BMG160_Five_U8X) {
comres = p_bmg160->BMG160_BUS_READ_FUNC
(p_bmg160->dev_addr,
BMG160_MODE_LPM1_ADDR, &data1, C_BMG160_One_U8X);
comres += p_bmg160->BMG160_BUS_READ_FUNC
(p_bmg160->dev_addr,
BMG160_MODE_LPM2_ADDR, &data2, C_BMG160_One_U8X);
switch (mode) {
case BMG160_MODE_NORMAL:
data1 = BMG160_SET_BITSLICE(data1,
BMG160_MODE_LPM1, C_BMG160_Zero_U8X);
data2 = BMG160_SET_BITSLICE(data2,
BMG160_MODE_LPM2_ADDR_FAST_POWERUP,
C_BMG160_Zero_U8X);
data3 = BMG160_SET_BITSLICE(data2,
BMG160_MODE_LPM2_ADDR_ADV_POWERSAVING,
C_BMG160_Zero_U8X);
comres += p_bmg160->BMG160_BUS_WRITE_FUNC
(p_bmg160->dev_addr,
BMG160_MODE_LPM1_ADDR, &data1, C_BMG160_One_U8X);
p_bmg160->delay_msec(1);/*A minimum delay of atleast
450us is required for Multiple write.*/
comres += p_bmg160->BMG160_BUS_WRITE_FUNC
(p_bmg160->dev_addr,
BMG160_MODE_LPM2_ADDR, &data3, C_BMG160_One_U8X);
break;
case BMG160_MODE_DEEPSUSPEND:
data1 = BMG160_SET_BITSLICE(data1,
BMG160_MODE_LPM1, C_BMG160_One_U8X);
data2 = BMG160_SET_BITSLICE(data2,
BMG160_MODE_LPM2_ADDR_FAST_POWERUP,
C_BMG160_Zero_U8X);
data3 = BMG160_SET_BITSLICE(data2,
BMG160_MODE_LPM2_ADDR_ADV_POWERSAVING,
C_BMG160_Zero_U8X);
comres += p_bmg160->BMG160_BUS_WRITE_FUNC
(p_bmg160->dev_addr,
BMG160_MODE_LPM1_ADDR, &data1, C_BMG160_One_U8X);
p_bmg160->delay_msec(1);/*A minimum delay of atleast
450us is required for Multiple write.*/
comres += p_bmg160->BMG160_BUS_WRITE_FUNC
(p_bmg160->dev_addr,
BMG160_MODE_LPM2_ADDR, &data3, C_BMG160_One_U8X);
break;
case BMG160_MODE_SUSPEND:
data1 = BMG160_SET_BITSLICE(data1,
BMG160_MODE_LPM1, C_BMG160_Four_U8X);
data2 = BMG160_SET_BITSLICE(data2,
BMG160_MODE_LPM2_ADDR_FAST_POWERUP,
C_BMG160_Zero_U8X);
data3 = BMG160_SET_BITSLICE(data2,
BMG160_MODE_LPM2_ADDR_ADV_POWERSAVING,
C_BMG160_Zero_U8X);
comres += p_bmg160->BMG160_BUS_WRITE_FUNC
(p_bmg160->dev_addr,
BMG160_MODE_LPM1_ADDR, &data1, C_BMG160_One_U8X);
p_bmg160->delay_msec(1);/*A minimum delay of atleast
450us is required for Multiple write.*/
comres += p_bmg160->BMG160_BUS_WRITE_FUNC
(p_bmg160->dev_addr,
BMG160_MODE_LPM2_ADDR, &data3, C_BMG160_One_U8X);
break;
case BMG160_MODE_FASTPOWERUP:
data1 = BMG160_SET_BITSLICE(data1,
BMG160_MODE_LPM1, C_BMG160_Four_U8X);
data2 = BMG160_SET_BITSLICE(data2,
BMG160_MODE_LPM2_ADDR_FAST_POWERUP,
C_BMG160_One_U8X);
data3 = BMG160_SET_BITSLICE(data2,
BMG160_MODE_LPM2_ADDR_ADV_POWERSAVING,
C_BMG160_Zero_U8X);
comres += p_bmg160->BMG160_BUS_WRITE_FUNC
(p_bmg160->dev_addr,
BMG160_MODE_LPM1_ADDR, &data1, C_BMG160_One_U8X);
p_bmg160->delay_msec(1);/*A minimum delay of atleast
450us is required for Multiple write.*/
comres += p_bmg160->BMG160_BUS_WRITE_FUNC
(p_bmg160->dev_addr,
BMG160_MODE_LPM2_ADDR, &data3, C_BMG160_One_U8X);
break;
case BMG160_MODE_ADVANCEDPOWERSAVING:
/* Configuring the proper settings for auto
sleep duration */
bmg160_get_bw(&v_bw_u8r);
bmg160_get_autosleepdur(&v_autosleepduration);
bmg160_set_autosleepdur(v_autosleepduration,
v_bw_u8r);
comres += p_bmg160->BMG160_BUS_READ_FUNC
(p_bmg160->dev_addr,
BMG160_MODE_LPM2_ADDR, &data2,
C_BMG160_One_U8X);
/* Configuring the advanced power saving mode*/
data1 = BMG160_SET_BITSLICE(data1,
BMG160_MODE_LPM1, C_BMG160_Zero_U8X);
data2 = BMG160_SET_BITSLICE(data2,
BMG160_MODE_LPM2_ADDR_FAST_POWERUP,
C_BMG160_Zero_U8X);
data3 = BMG160_SET_BITSLICE(data2,
BMG160_MODE_LPM2_ADDR_ADV_POWERSAVING,
C_BMG160_One_U8X);
comres += p_bmg160->BMG160_BUS_WRITE_FUNC
(p_bmg160->dev_addr,
BMG160_MODE_LPM1_ADDR, &data1, C_BMG160_One_U8X);
p_bmg160->delay_msec(1);/*A minimum delay of atleast
450us is required for Multiple write.*/
comres += p_bmg160->BMG160_BUS_WRITE_FUNC
(p_bmg160->dev_addr,
BMG160_MODE_LPM2_ADDR, &data3, C_BMG160_One_U8X);
break;
}
} else {
comres = E_BMG160_OUT_OF_RANGE;
}
}
return comres;
}
/* Compiler Switch if applicable
#ifdef
#endif
*/
/*****************************************************************************
* Description: *//**brief This API is used to to do selftest to sensor
* sensor
*
*
*
*
*\param unsigned char *result
*
*
*
*
* \return communication results
*
*
*****************************************************************************/
/* Scheduling:
*
*
*
* Usage guide:
*
*
* Remarks:
*
*****************************************************************************/
BMG160_RETURN_FUNCTION_TYPE bmg160_selftest(unsigned char *result)
{
BMG160_RETURN_FUNCTION_TYPE comres = C_BMG160_Zero_U8X;
unsigned char data1 = C_BMG160_Zero_U8X;
unsigned char data2 = C_BMG160_Zero_U8X;
comres = p_bmg160->BMG160_BUS_READ_FUNC(p_bmg160->dev_addr,
BMG160_SELF_TEST_ADDR, &data1, C_BMG160_One_U8X);
data2 = BMG160_GET_BITSLICE(data1, BMG160_SELF_TEST_ADDR_RATEOK);
data1 = BMG160_SET_BITSLICE(data1, BMG160_SELF_TEST_ADDR_TRIGBIST,
C_BMG160_One_U8X);
comres += p_bmg160->BMG160_BUS_WRITE_FUNC(p_bmg160->dev_addr,
BMG160_SELF_TEST_ADDR_TRIGBIST__REG, &data1, C_BMG160_One_U8X);
/* Waiting time to complete the selftest process */
p_bmg160->delay_msec(10);
/* Reading Selftest result bir bist_failure */
comres += p_bmg160->BMG160_BUS_READ_FUNC(p_bmg160->dev_addr,
BMG160_SELF_TEST_ADDR_BISTFAIL__REG, &data1, C_BMG160_One_U8X);
data1 = BMG160_GET_BITSLICE(data1, BMG160_SELF_TEST_ADDR_BISTFAIL);
if ((data1 == 0x00) && (data2 == 0x01))
*result = C_BMG160_SUCCESS;
else
*result = C_BMG160_FAILURE;
return comres;
}
/* Compiler Switch if applicable
#ifdef
#endif
*/
/*****************************************************************************
* Description: *//**brief This API is used to get data auto sleep duration
*
*
*
*
*\param unsigned char *duration : Address of auto sleep duration
* Pointer to a variable passed as a parameter
*
*
*
* \return
*
*
*****************************************************************************/
/* Scheduling:
*
*
*
* Usage guide:
*
*
* Remarks:
*
*****************************************************************************/
BMG160_RETURN_FUNCTION_TYPE bmg160_get_autosleepdur(unsigned char *duration)
{
BMG160_RETURN_FUNCTION_TYPE comres = C_BMG160_Zero_U8X;
unsigned char v_data_u8r = C_BMG160_Zero_U8X;
if (p_bmg160 == BMG160_NULL) {
return E_BMG160_NULL_PTR;
} else {
comres = p_bmg160->BMG160_BUS_READ_FUNC(p_bmg160->dev_addr,
BMG160_MODE_LPM2_ADDR_AUTOSLEEPDUR__REG, &v_data_u8r, 1);
*duration = BMG160_GET_BITSLICE(v_data_u8r,
BMG160_MODE_LPM2_ADDR_AUTOSLEEPDUR);
}
return comres;
}
/* Compiler Switch if applicable
#ifdef
#endif
*/
/*****************************************************************************
* Description: *//**brief This API is used to set duration
*
*
*
*
*\param unsigned char duration:
* Value to be written passed as a parameter
*
*
*
* \return communication results
*
*
*****************************************************************************/
/* Scheduling:
*
*
*
* Usage guide:
*
*
* Remarks:
*
*****************************************************************************/
BMG160_RETURN_FUNCTION_TYPE bmg160_set_autosleepdur(unsigned char duration,
unsigned char bandwith)
{
BMG160_RETURN_FUNCTION_TYPE comres = C_BMG160_Zero_U8X;
unsigned char v_data_u8r = C_BMG160_Zero_U8X;
unsigned char v_autosleepduration_u8r = C_BMG160_Zero_U8X;
if (p_bmg160 == BMG160_NULL) {
return E_BMG160_NULL_PTR;
} else {
comres = p_bmg160->BMG160_BUS_READ_FUNC
(p_bmg160->dev_addr,
BMG160_MODE_LPM2_ADDR_AUTOSLEEPDUR__REG,
&v_data_u8r, 1);
if (duration < C_BMG160_Eight_U8X) {
switch (bandwith) {
case C_BMG160_No_Filter_U8X:
if (duration >
C_BMG160_4ms_AutoSleepDur_U8X)
v_autosleepduration_u8r =
duration;
else
v_autosleepduration_u8r =
C_BMG160_4ms_AutoSleepDur_U8X;
break;
case C_BMG160_BW_230Hz_U8X:
if (duration >
C_BMG160_4ms_AutoSleepDur_U8X)
v_autosleepduration_u8r =
duration;
else
v_autosleepduration_u8r =
C_BMG160_4ms_AutoSleepDur_U8X;
break;
case C_BMG160_BW_116Hz_U8X:
if (duration >
C_BMG160_4ms_AutoSleepDur_U8X)
v_autosleepduration_u8r =
duration;
else
v_autosleepduration_u8r =
C_BMG160_4ms_AutoSleepDur_U8X;
break;
case C_BMG160_BW_47Hz_U8X:
if (duration >
C_BMG160_5ms_AutoSleepDur_U8X)
v_autosleepduration_u8r =
duration;
else
v_autosleepduration_u8r =
C_BMG160_5ms_AutoSleepDur_U8X;
break;
case C_BMG160_BW_23Hz_U8X:
if (duration >
C_BMG160_10ms_AutoSleepDur_U8X)
v_autosleepduration_u8r =
duration;
else
v_autosleepduration_u8r =
C_BMG160_10ms_AutoSleepDur_U8X;
break;
case C_BMG160_BW_12Hz_U8X:
if (duration >
C_BMG160_20ms_AutoSleepDur_U8X)
v_autosleepduration_u8r =
duration;
else
v_autosleepduration_u8r =
C_BMG160_20ms_AutoSleepDur_U8X;
break;
case C_BMG160_BW_64Hz_U8X:
if (duration >
C_BMG160_10ms_AutoSleepDur_U8X)
v_autosleepduration_u8r =
duration;
else
v_autosleepduration_u8r =
C_BMG160_10ms_AutoSleepDur_U8X;
break;
case C_BMG160_BW_32Hz_U8X:
if (duration >
C_BMG160_20ms_AutoSleepDur_U8X)
v_autosleepduration_u8r =
duration;
else
v_autosleepduration_u8r =
C_BMG160_20ms_AutoSleepDur_U8X;
break;
default:
if (duration >
C_BMG160_4ms_AutoSleepDur_U8X)
v_autosleepduration_u8r =
duration;
else
v_autosleepduration_u8r =
C_BMG160_4ms_AutoSleepDur_U8X;
break;
}
v_data_u8r = BMG160_SET_BITSLICE(v_data_u8r,
BMG160_MODE_LPM2_ADDR_AUTOSLEEPDUR,
v_autosleepduration_u8r);
comres += p_bmg160->BMG160_BUS_WRITE_FUNC
(p_bmg160->dev_addr,
BMG160_MODE_LPM2_ADDR_AUTOSLEEPDUR__REG,
&v_data_u8r, 1);
} else {
comres = E_BMG160_OUT_OF_RANGE;
}
}
return comres;
}
/* Compiler Switch if applicable
#ifdef
#endif
*/
/*****************************************************************************
* Description: *//**brief This API is used to get data sleep duration
*
*
*
*
*\param unsigned char *duration : Address of sleep duration
* Pointer to a variable passed as a parameter
*
*
*
* \return
*
*
*****************************************************************************/
/* Scheduling:
*
*
*
* Usage guide:
*
*
* Remarks:
*
*****************************************************************************/
BMG160_RETURN_FUNCTION_TYPE bmg160_get_sleepdur(unsigned char *duration)
{
BMG160_RETURN_FUNCTION_TYPE comres = C_BMG160_Zero_U8X;
unsigned char v_data_u8r = C_BMG160_Zero_U8X;
if (p_bmg160 == BMG160_NULL) {
return E_BMG160_NULL_PTR;
} else {
comres = p_bmg160->BMG160_BUS_READ_FUNC(p_bmg160->dev_addr,
BMG160_MODELPM1_ADDR_SLEEPDUR__REG, &v_data_u8r, 1);
*duration = BMG160_GET_BITSLICE(v_data_u8r,
BMG160_MODELPM1_ADDR_SLEEPDUR);
}
return comres;
}
/* Compiler Switch if applicable
#ifdef
#endif
*/
/*****************************************************************************
* Description: *//**brief This API is used to set duration
*
*
*
*
*\param unsigned char duration:
* Value to be written passed as a parameter
*
*
*
* \return communication results
*
*
*****************************************************************************/
/* Scheduling:
*
*
*
* Usage guide:
*
*
* Remarks:
*
*****************************************************************************/
BMG160_RETURN_FUNCTION_TYPE bmg160_set_sleepdur(unsigned char duration)
{
BMG160_RETURN_FUNCTION_TYPE comres = C_BMG160_Zero_U8X;
unsigned char v_data_u8r = C_BMG160_Zero_U8X;
if (p_bmg160 == BMG160_NULL) {
return E_BMG160_NULL_PTR;
} else {
if (duration < C_BMG160_Eight_U8X) {
comres = p_bmg160->BMG160_BUS_READ_FUNC
(p_bmg160->dev_addr,
BMG160_MODELPM1_ADDR_SLEEPDUR__REG,
&v_data_u8r, 1);
v_data_u8r = BMG160_SET_BITSLICE(v_data_u8r,
BMG160_MODELPM1_ADDR_SLEEPDUR, duration);
comres += p_bmg160->BMG160_BUS_WRITE_FUNC
(p_bmg160->dev_addr,
BMG160_MODELPM1_ADDR_SLEEPDUR__REG,
&v_data_u8r, 1);
} else {
comres = E_BMG160_OUT_OF_RANGE;
}
}
return comres;
}
|
500746.c | //------------------------------------------------------------------------------
// GB_mex_isequal: returns true if A and B are equal
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2020, All Rights Reserved.
// http://suitesparse.com See GraphBLAS/Doc/License.txt for license.
//------------------------------------------------------------------------------
#include "GB_mex.h"
#define USAGE "C = GB_mex_isequal (A, B)"
#define FREE_ALL \
{ \
GB_MATRIX_FREE (&A) ; \
GB_MATRIX_FREE (&B) ; \
GB_mx_put_global (true, 0) ; \
}
void mexFunction
(
int nargout,
mxArray *pargout [ ],
int nargin,
const mxArray *pargin [ ]
)
{
bool malloc_debug = GB_mx_get_global (true) ;
GrB_Matrix A = NULL ;
GrB_Matrix B = NULL ;
GB_WHERE (USAGE) ;
// check inputs
if (nargout > 1 || nargin != 2)
{
mexErrMsgTxt ("Usage: " USAGE) ;
}
#define GET_DEEP_COPY ;
#define FREE_DEEP_COPY ;
// get A and B
A = GB_mx_mxArray_to_Matrix (pargin [0], "A", false, true) ;
B = GB_mx_mxArray_to_Matrix (pargin [1], "B", false, true) ;
if (A == NULL || B == NULL)
{
FREE_ALL ;
mexErrMsgTxt ("failed") ;
}
GrB_BinaryOp op = NULL ;
if (mxIsComplex (pargin [0]))
{
op = Complex_eq ;
}
// C = all (A == B) using the op
bool result ;
METHOD (isequal (&result, A, B, op)) ;
// return C to MATLAB as a plain sparse matrix
pargout [0] = mxCreateDoubleScalar ((double) result) ;
FREE_ALL ;
}
|
740514.c | #include <ctype.h>
int tolower(int c)
{
if (isupper(c))
return c | 32;
return c;
}
|
266987.c | /*
* FB driver for the ILI9320 LCD Controller
*
* Copyright (C) 2013 Noralf Tronnes
*
* 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.
*/
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/gpio.h>
#include <linux/spi/spi.h>
#include <linux/delay.h>
#include "fbtft.h"
#define DRVNAME "fb_ili9320"
#define WIDTH 240
#define HEIGHT 320
#define DEFAULT_GAMMA "07 07 6 0 0 0 5 5 4 0\n" \
"07 08 4 7 5 1 2 0 7 7"
static unsigned int read_devicecode(struct fbtft_par *par)
{
int ret;
u8 rxbuf[8] = {0, };
write_reg(par, 0x0000);
ret = par->fbtftops.read(par, rxbuf, 4);
return (rxbuf[2] << 8) | rxbuf[3];
}
static int init_display(struct fbtft_par *par)
{
unsigned int devcode;
par->fbtftops.reset(par);
devcode = read_devicecode(par);
fbtft_par_dbg(DEBUG_INIT_DISPLAY, par, "Device code: 0x%04X\n",
devcode);
if ((devcode != 0x0000) && (devcode != 0x9320))
dev_warn(par->info->device,
"Unrecognized Device code: 0x%04X (expected 0x9320)\n",
devcode);
/* Initialization sequence from ILI9320 Application Notes */
/* *********** Start Initial Sequence ********* */
/* Set the Vcore voltage and this setting is must. */
write_reg(par, 0x00E5, 0x8000);
/* Start internal OSC. */
write_reg(par, 0x0000, 0x0001);
/* set SS and SM bit */
write_reg(par, 0x0001, 0x0100);
/* set 1 line inversion */
write_reg(par, 0x0002, 0x0700);
/* Resize register */
write_reg(par, 0x0004, 0x0000);
/* set the back and front porch */
write_reg(par, 0x0008, 0x0202);
/* set non-display area refresh cycle */
write_reg(par, 0x0009, 0x0000);
/* FMARK function */
write_reg(par, 0x000A, 0x0000);
/* RGB interface setting */
write_reg(par, 0x000C, 0x0000);
/* Frame marker Position */
write_reg(par, 0x000D, 0x0000);
/* RGB interface polarity */
write_reg(par, 0x000F, 0x0000);
/* ***********Power On sequence *************** */
/* SAP, BT[3:0], AP, DSTB, SLP, STB */
write_reg(par, 0x0010, 0x0000);
/* DC1[2:0], DC0[2:0], VC[2:0] */
write_reg(par, 0x0011, 0x0007);
/* VREG1OUT voltage */
write_reg(par, 0x0012, 0x0000);
/* VDV[4:0] for VCOM amplitude */
write_reg(par, 0x0013, 0x0000);
/* Dis-charge capacitor power voltage */
mdelay(200);
/* SAP, BT[3:0], AP, DSTB, SLP, STB */
write_reg(par, 0x0010, 0x17B0);
/* R11h=0x0031 at VCI=3.3V DC1[2:0], DC0[2:0], VC[2:0] */
write_reg(par, 0x0011, 0x0031);
mdelay(50);
/* R12h=0x0138 at VCI=3.3V VREG1OUT voltage */
write_reg(par, 0x0012, 0x0138);
mdelay(50);
/* R13h=0x1800 at VCI=3.3V VDV[4:0] for VCOM amplitude */
write_reg(par, 0x0013, 0x1800);
/* R29h=0x0008 at VCI=3.3V VCM[4:0] for VCOMH */
write_reg(par, 0x0029, 0x0008);
mdelay(50);
/* GRAM horizontal Address */
write_reg(par, 0x0020, 0x0000);
/* GRAM Vertical Address */
write_reg(par, 0x0021, 0x0000);
/* ------------------ Set GRAM area --------------- */
/* Horizontal GRAM Start Address */
write_reg(par, 0x0050, 0x0000);
/* Horizontal GRAM End Address */
write_reg(par, 0x0051, 0x00EF);
/* Vertical GRAM Start Address */
write_reg(par, 0x0052, 0x0000);
/* Vertical GRAM End Address */
write_reg(par, 0x0053, 0x013F);
/* Gate Scan Line */
write_reg(par, 0x0060, 0x2700);
/* NDL,VLE, REV */
write_reg(par, 0x0061, 0x0001);
/* set scrolling line */
write_reg(par, 0x006A, 0x0000);
/* -------------- Partial Display Control --------- */
write_reg(par, 0x0080, 0x0000);
write_reg(par, 0x0081, 0x0000);
write_reg(par, 0x0082, 0x0000);
write_reg(par, 0x0083, 0x0000);
write_reg(par, 0x0084, 0x0000);
write_reg(par, 0x0085, 0x0000);
/* -------------- Panel Control ------------------- */
write_reg(par, 0x0090, 0x0010);
write_reg(par, 0x0092, 0x0000);
write_reg(par, 0x0093, 0x0003);
write_reg(par, 0x0095, 0x0110);
write_reg(par, 0x0097, 0x0000);
write_reg(par, 0x0098, 0x0000);
write_reg(par, 0x0007, 0x0173); /* 262K color and display ON */
return 0;
}
static void set_addr_win(struct fbtft_par *par, int xs, int ys, int xe, int ye)
{
switch (par->info->var.rotate) {
/* R20h = Horizontal GRAM Start Address */
/* R21h = Vertical GRAM Start Address */
case 0:
write_reg(par, 0x0020, xs);
write_reg(par, 0x0021, ys);
break;
case 180:
write_reg(par, 0x0020, WIDTH - 1 - xs);
write_reg(par, 0x0021, HEIGHT - 1 - ys);
break;
case 270:
write_reg(par, 0x0020, WIDTH - 1 - ys);
write_reg(par, 0x0021, xs);
break;
case 90:
write_reg(par, 0x0020, ys);
write_reg(par, 0x0021, HEIGHT - 1 - xs);
break;
}
write_reg(par, 0x0022); /* Write Data to GRAM */
}
static int set_var(struct fbtft_par *par)
{
switch (par->info->var.rotate) {
case 0:
write_reg(par, 0x3, (par->bgr << 12) | 0x30);
break;
case 270:
write_reg(par, 0x3, (par->bgr << 12) | 0x28);
break;
case 180:
write_reg(par, 0x3, (par->bgr << 12) | 0x00);
break;
case 90:
write_reg(par, 0x3, (par->bgr << 12) | 0x18);
break;
}
return 0;
}
/*
* Gamma string format:
* VRP0 VRP1 RP0 RP1 KP0 KP1 KP2 KP3 KP4 KP5
* VRN0 VRN1 RN0 RN1 KN0 KN1 KN2 KN3 KN4 KN5
*/
#define CURVE(num, idx) curves[num * par->gamma.num_values + idx]
static int set_gamma(struct fbtft_par *par, u32 *curves)
{
unsigned long mask[] = {
0x1f, 0x1f, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07,
0x1f, 0x1f, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07,
};
int i, j;
/* apply mask */
for (i = 0; i < 2; i++)
for (j = 0; j < 10; j++)
CURVE(i, j) &= mask[i * par->gamma.num_values + j];
write_reg(par, 0x0030, CURVE(0, 5) << 8 | CURVE(0, 4));
write_reg(par, 0x0031, CURVE(0, 7) << 8 | CURVE(0, 6));
write_reg(par, 0x0032, CURVE(0, 9) << 8 | CURVE(0, 8));
write_reg(par, 0x0035, CURVE(0, 3) << 8 | CURVE(0, 2));
write_reg(par, 0x0036, CURVE(0, 1) << 8 | CURVE(0, 0));
write_reg(par, 0x0037, CURVE(1, 5) << 8 | CURVE(1, 4));
write_reg(par, 0x0038, CURVE(1, 7) << 8 | CURVE(1, 6));
write_reg(par, 0x0039, CURVE(1, 9) << 8 | CURVE(1, 8));
write_reg(par, 0x003C, CURVE(1, 3) << 8 | CURVE(1, 2));
write_reg(par, 0x003D, CURVE(1, 1) << 8 | CURVE(1, 0));
return 0;
}
#undef CURVE
static struct fbtft_display display = {
.regwidth = 16,
.width = WIDTH,
.height = HEIGHT,
.gamma_num = 2,
.gamma_len = 10,
.gamma = DEFAULT_GAMMA,
.fbtftops = {
.init_display = init_display,
.set_addr_win = set_addr_win,
.set_var = set_var,
.set_gamma = set_gamma,
},
};
FBTFT_REGISTER_DRIVER(DRVNAME, "ilitek,ili9320", &display);
MODULE_ALIAS("spi:" DRVNAME);
MODULE_ALIAS("platform:" DRVNAME);
MODULE_ALIAS("spi:ili9320");
MODULE_ALIAS("platform:ili9320");
MODULE_DESCRIPTION("FB driver for the ILI9320 LCD Controller");
MODULE_AUTHOR("Noralf Tronnes");
MODULE_LICENSE("GPL");
|
767252.c | // This file is part of CPAchecker,
// a tool for configurable software verification:
// https://cpachecker.sosy-lab.org
//
// SPDX-FileCopyrightText: 2007-2020 Dirk Beyer <https://www.sosy-lab.org>
//
// SPDX-License-Identifier: Apache-2.0
#include <stdlib.h>
int main(void) {
int a = 1;
switch (a) {
case 1 :
a = 1;
}
return (0);
}
|
649561.c | /* ---------------------------------------------------------------------
*
* -- PBLAS routine (version 2.0) --
* University of Tennessee, Knoxville, Oak Ridge National Laboratory,
* and University of California, Berkeley.
* April 1, 1998
*
* ---------------------------------------------------------------------
*/
/*
* Include files
*/
#include "pblas.h"
#include "PBpblas.h"
#include "PBtools.h"
#include "PBblacs.h"
#include "PBblas.h"
#ifdef __STDC__
void pzamax_( int * N, double * AMAX, int * INDX,
double * X, int * IX, int * JX, int * DESCX, int * INCX )
#else
void pzamax_( N, AMAX, INDX, X, IX, JX, DESCX, INCX )
/*
* .. Scalar Arguments ..
*/
int * INCX, * INDX, * IX, * JX, * N;
double * AMAX;
/*
* .. Array Arguments ..
*/
int * DESCX;
double * X;
#endif
{
/*
* Purpose
* =======
*
* PZAMAX computes the global index of the maximum element in absolute
* value of a subvector sub( X ). The global index is returned in INDX
* and the value of that element is returned in AMAX,
*
* where
*
* sub( X ) denotes X(IX,JX:JX+N-1) if INCX = M_X,
* X(IX:IX+N-1,JX) if INCX = 1 and INCX <> M_X.
*
* Notes
* =====
*
* A description vector is associated with each 2D block-cyclicly dis-
* tributed matrix. This vector stores the information required to
* establish the mapping between a matrix entry and its corresponding
* process and memory location.
*
* In the following comments, the character _ should be read as
* "of the distributed matrix". Let A be a generic term for any 2D
* block cyclicly distributed matrix. Its description vector is DESC_A:
*
* NOTATION STORED IN EXPLANATION
* ---------------- --------------- ------------------------------------
* DTYPE_A (global) DESCA[ DTYPE_ ] The descriptor type.
* CTXT_A (global) DESCA[ CTXT_ ] The BLACS context handle, indicating
* the NPROW x NPCOL BLACS process grid
* A is distributed over. The context
* itself is global, but the handle
* (the integer value) may vary.
* M_A (global) DESCA[ M_ ] The number of rows in the distribu-
* ted matrix A, M_A >= 0.
* N_A (global) DESCA[ N_ ] The number of columns in the distri-
* buted matrix A, N_A >= 0.
* IMB_A (global) DESCA[ IMB_ ] The number of rows of the upper left
* block of the matrix A, IMB_A > 0.
* INB_A (global) DESCA[ INB_ ] The number of columns of the upper
* left block of the matrix A,
* INB_A > 0.
* MB_A (global) DESCA[ MB_ ] The blocking factor used to distri-
* bute the last M_A-IMB_A rows of A,
* MB_A > 0.
* NB_A (global) DESCA[ NB_ ] The blocking factor used to distri-
* bute the last N_A-INB_A columns of
* A, NB_A > 0.
* RSRC_A (global) DESCA[ RSRC_ ] The process row over which the first
* row of the matrix A is distributed,
* NPROW > RSRC_A >= 0.
* CSRC_A (global) DESCA[ CSRC_ ] The process column over which the
* first column of A is distributed.
* NPCOL > CSRC_A >= 0.
* LLD_A (local) DESCA[ LLD_ ] The leading dimension of the local
* array storing the local blocks of
* the distributed matrix A,
* IF( Lc( 1, N_A ) > 0 )
* LLD_A >= MAX( 1, Lr( 1, M_A ) )
* ELSE
* LLD_A >= 1.
*
* Let K be the number of rows of a matrix A starting at the global in-
* dex IA,i.e, A( IA:IA+K-1, : ). Lr( IA, K ) denotes the number of rows
* that the process of row coordinate MYROW ( 0 <= MYROW < NPROW ) would
* receive if these K rows were distributed over NPROW processes. If K
* is the number of columns of a matrix A starting at the global index
* JA, i.e, A( :, JA:JA+K-1, : ), Lc( JA, K ) denotes the number of co-
* lumns that the process MYCOL ( 0 <= MYCOL < NPCOL ) would receive if
* these K columns were distributed over NPCOL processes.
*
* The values of Lr() and Lc() may be determined via a call to the func-
* tion PB_Cnumroc:
* Lr( IA, K ) = PB_Cnumroc( K, IA, IMB_A, MB_A, MYROW, RSRC_A, NPROW )
* Lc( JA, K ) = PB_Cnumroc( K, JA, INB_A, NB_A, MYCOL, CSRC_A, NPCOL )
*
* Arguments
* =========
*
* N (global input) INTEGER
* On entry, N specifies the length of the subvector sub( X ).
* N must be at least zero.
*
* AMAX (global output) COMPLEX*16 array
* On exit, AMAX specifies the largest entry in absolute value
* of the subvector sub( X ) only in its scope (See below for
* further details).
*
* INDX (global output) INTEGER
* On exit, INDX specifies the global index of the maximum ele-
* ment in absolute value of the subvector sub( X ) only in its
* scope (See below for further details).
*
* X (local input) COMPLEX*16 array
* On entry, X is an array of dimension (LLD_X, Kx), where LLD_X
* is at least MAX( 1, Lr( 1, IX ) ) when INCX = M_X and
* MAX( 1, Lr( 1, IX+N-1 ) ) otherwise, and, Kx is at least
* Lc( 1, JX+N-1 ) when INCX = M_X and Lc( 1, JX ) otherwise.
* Before entry, this array contains the local entries of the
* matrix X.
*
* IX (global input) INTEGER
* On entry, IX specifies X's global row index, which points to
* the beginning of the submatrix sub( X ).
*
* JX (global input) INTEGER
* On entry, JX specifies X's global column index, which points
* to the beginning of the submatrix sub( X ).
*
* DESCX (global and local input) INTEGER array
* On entry, DESCX is an integer array of dimension DLEN_. This
* is the array descriptor for the matrix X.
*
* INCX (global input) INTEGER
* On entry, INCX specifies the global increment for the
* elements of X. Only two values of INCX are supported in
* this version, namely 1 and M_X. INCX must not be zero.
*
* Further Details
* ===============
*
* When the result of a vector-oriented PBLAS call is a scalar, this
* scalar is set only within the process scope which owns the vector(s)
* being operated on. Let sub( X ) be a generic term for the input vec-
* tor(s). Then, the processes owning the correct the answer is determi-
* ned as follows: if an operation involves more than one vector, the
* processes receiving the result will be the union of the following set
* of processes for each vector:
*
* If N = 1, M_X = 1 and INCX = 1, then one cannot determine if a pro-
* cess row or process column owns the vector operand, therefore only
* the process owning sub( X ) receives the correct result;
*
* If INCX = M_X, then sub( X ) is a vector distributed over a process
* row. Each process in this row receives the result;
*
* If INCX = 1, then sub( X ) is a vector distributed over a process
* column. Each process in this column receives the result;
*
* -- Written on April 1, 1998 by
* Antoine Petitet, University of Tennessee, Knoxville 37996, USA.
*
* ---------------------------------------------------------------------
*/
/*
* .. Local Scalars ..
*/
char cbtop, cctop, rbtop, rctop;
int Xcol, Xgindx, Xi, Xii, Ximb, Xinb, Xj, Xjj, Xlindx, Xld, Xmb,
Xnb, Xnp, Xnq, Xrow, Xsrc, ctxt, dist, dst, idumm, info, k,
maxpos, mycol, mydist, myrow, npcol, nprow, src, size;
PBTYP_T * type;
/*
* .. Local Arrays ..
*/
char * Xptr;
int Xd[DLEN_];
cmplx16 work[4];
/* ..
* .. Executable Statements ..
*
*/
PB_CargFtoC( *IX, *JX, DESCX, &Xi, &Xj, Xd );
#ifndef NO_ARGCHK
/*
* Test the input parameters
*/
Cblacs_gridinfo( ( ctxt = Xd[CTXT_] ), &nprow, &npcol, &myrow, &mycol );
if( !( info = ( ( nprow == -1 ) ? -( 701 + CTXT_ ) : 0 ) ) )
PB_Cchkvec( ctxt, "PZAMAX", "X", *N, 1, Xi, Xj, Xd, *INCX, 7, &info );
if( info ) { PB_Cabort( ctxt, "PZAMAX", info ); return; }
#endif
/*
* Initialize INDX and AMAX
*/
*INDX = 0; AMAX[REAL_PART] = ZERO; AMAX[IMAG_PART] = ZERO;
/*
* Quick return if possible
*/
if( *N == 0 ) return;
/*
* Retrieve process grid information
*/
#ifdef NO_ARGCHK
Cblacs_gridinfo( ( ctxt = Xd[CTXT_] ), &nprow, &npcol, &myrow, &mycol );
#endif
/*
* Retrieve sub( X )'s local information: Xii, Xjj, Xrow, Xcol
*/
PB_Cinfog2l( Xi, Xj, Xd, nprow, npcol, myrow, mycol, &Xii, &Xjj,
&Xrow, &Xcol );
/*
* Handle degenerate case separately, sub( X )'s scope is just one process
*/
if( ( *INCX == 1 ) && ( Xd[M_] == 1 ) && ( *N == 1 ) )
{
/*
* Make sure I own some data and compute INDX and AMAX
*/
if( ( ( myrow == Xrow ) || ( Xrow < 0 ) ) &&
( ( mycol == Xcol ) || ( Xcol < 0 ) ) )
{
*INDX = *JX;
type = PB_Cztypeset();
Xptr = Mptr( ((char *) X), Xii, Xjj, Xd[LLD_], type->size );
AMAX[REAL_PART] = ((double*)(Xptr))[REAL_PART];
AMAX[IMAG_PART] = ((double*)(Xptr))[IMAG_PART];
}
return;
}
else if( *INCX == Xd[M_] )
{
/*
* sub( X ) resides in (a) process row(s)
*/
if( ( myrow == Xrow ) || ( Xrow < 0 ) )
{
rctop = *PB_Ctop( &ctxt, COMBINE, ROW, TOP_GET );
if( ( rctop == CTOP_DEFAULT ) || ( rctop == CTOP_TREE1 ) )
{
/*
* Inline the 1-tree combine for communication savings
*/
Xinb = Xd[INB_ ]; Xnb = Xd[NB_ ]; Xsrc = Xd[CSRC_];
Xnq = PB_Cnumroc( *N, Xj, Xinb, Xnb, mycol, Xsrc, npcol );
/*
* Make sure I own some data and compute local INDX and AMAX
*/
if( Xnq > 0 )
{
Xld = Xd[LLD_];
type = PB_Cztypeset(); size = type->size;
Xlindx = Xjj - 1 +
izamax_( &Xnq, Mptr( ((char *) X), Xii, Xjj, Xld,
size ), &Xld );
Mindxl2g( Xgindx, Xlindx, Xinb, Xnb, mycol, Xsrc, npcol );
Xptr = Mptr( ((char *) X), Xii, Xlindx, Xld, size );
work[0][REAL_PART] = ((double*)(Xptr))[REAL_PART];
work[0][IMAG_PART] = ((double*)(Xptr))[IMAG_PART];
work[1][REAL_PART] = ((double)( Xgindx+1 ));
work[1][IMAG_PART] = ZERO;
}
else
{
work[0][REAL_PART] = ZERO;
work[0][IMAG_PART] = ZERO;
work[1][REAL_PART] = ZERO;
work[1][IMAG_PART] = ZERO;
}
/*
* Combine the local results using a 1-tree topology within process column 0
* if npcol > 1 or Xcol >= 0, i.e sub( X ) is distributed.
*/
if( ( npcol >= 2 ) && ( Xcol >= 0 ) )
{
mydist = mycol;
k = 1;
l_10:
if( mydist & 1 )
{
dist = k * ( mydist - 1 );
dst = MPosMod( dist, npcol );
Czgesd2d( ctxt, 2, 1, ((char*)work), 2, myrow, dst );
goto l_20;
}
else
{
dist = mycol + k;
src = MPosMod( dist, npcol );
if( mycol < src )
{
Czgerv2d( ctxt, 2, 1, ((char*) work[2]), 2, myrow,
src );
if( ( ABS( work[0][REAL_PART] ) +
ABS( work[0][IMAG_PART] ) ) <
( ABS( work[2][REAL_PART] ) +
ABS( work[2][IMAG_PART] ) ) )
{
work[0][REAL_PART] = work[2][REAL_PART];
work[0][IMAG_PART] = work[2][IMAG_PART];
work[1][REAL_PART] = work[3][REAL_PART];
}
}
mydist >>= 1;
}
k <<= 1;
if( k < npcol ) goto l_10;
l_20:
/*
* Process column 0 broadcasts the combined values of INDX and AMAX within
* their process row.
*/
rbtop = *PB_Ctop( &ctxt, BCAST, ROW, TOP_GET );
if( mycol == 0 )
{
Czgebs2d( ctxt, ROW, &rbtop, 2, 1, ((char*)work), 2 );
}
else
{
Czgebr2d( ctxt, ROW, &rbtop, 2, 1, ((char*)work), 2,
myrow, 0 );
}
}
/*
* Set INDX and AMAX to the replicated answers contained in work. If AMAX is
* zero, then select a coherent INDX.
*/
AMAX[REAL_PART] = work[0][REAL_PART];
AMAX[IMAG_PART] = work[0][IMAG_PART];
*INDX = ( ( ( AMAX[REAL_PART] == ZERO ) &&
( AMAX[IMAG_PART] == ZERO ) ) ?
( *JX ) : ( (int)(work[1][REAL_PART]) ) );
}
else
{
/*
* Otherwise use the current topology settings to combine the results
*/
Xinb = Xd[INB_ ]; Xnb = Xd[NB_ ]; Xsrc = Xd[CSRC_];
Xnq = PB_Cnumroc( *N, Xj, Xinb, Xnb, mycol, Xsrc, npcol );
/*
* Make sure I own some data and compute local INDX and AMAX
*/
if( Xnq > 0 )
{
/*
* Compute the local maximum and its corresponding local index
*/
Xld = Xd[LLD_];
type = PB_Cztypeset(); size = type->size;
Xlindx = Xjj - 1 +
izamax_( &Xnq, Mptr( ((char *) X), Xii, Xjj, Xld,
size ), &Xld );
Xptr = Mptr( ((char *) X), Xii, Xlindx, Xld, size );
AMAX[REAL_PART] = ((double*)(Xptr))[REAL_PART];
AMAX[IMAG_PART] = ((double*)(Xptr))[IMAG_PART];
}
else
{
AMAX[REAL_PART] = ZERO;
AMAX[IMAG_PART] = ZERO;
}
if( Xcol >= 0 )
{
/*
* Combine leave on all the local maximum if Xcol >= 0, i.e sub( X ) is
* distributed
*/
Czgamx2d( ctxt, ROW, &rctop, 1, 1, ((char*)AMAX), 1,
&idumm, &maxpos, 1, -1, mycol );
/*
* Broadcast the corresponding global index
*/
if( ( AMAX[REAL_PART] != ZERO ) || ( AMAX[IMAG_PART] != ZERO ) )
{
rbtop = *PB_Ctop( &ctxt, BCAST, ROW, TOP_GET );
if( mycol == maxpos )
{
Mindxl2g( Xgindx, Xlindx, Xinb, Xnb, mycol, Xsrc, npcol );
*INDX = Xgindx + 1;
Cigebs2d( ctxt, ROW, &rbtop, 1, 1, ((char*)INDX), 1 );
}
else
{
Cigebr2d( ctxt, ROW, &rbtop, 1, 1, ((char*)INDX), 1,
myrow, maxpos );
}
}
else
{
/*
* If AMAX is zero, then select a coherent INDX.
*/
*INDX = *JX;
}
}
else
{
/*
* sub( X ) is not distributed. If AMAX is zero, then select a coherent INDX.
*/
*INDX = ( ( ( AMAX[REAL_PART] == ZERO ) &&
( AMAX[IMAG_PART] == ZERO ) ) ?
( *JX ) : Xlindx + 1 );
}
}
}
return;
}
else
{
/*
* sub( X ) resides in (a) process column(s)
*/
if( ( mycol == Xcol ) || ( Xcol < 0 ) )
{
cctop = *PB_Ctop( &ctxt, COMBINE, COLUMN, TOP_GET );
if( ( cctop == CTOP_DEFAULT ) || ( cctop == CTOP_TREE1 ) )
{
/*
* Inline the 1-tree combine for communication savings
*/
Ximb = Xd[IMB_ ]; Xmb = Xd[MB_ ]; Xsrc = Xd[RSRC_];
Xnp = PB_Cnumroc( *N, Xi, Ximb, Xmb, myrow, Xsrc, nprow );
/*
* Make sure I own some data and compute local INDX and AMAX
*/
if( Xnp > 0 )
{
Xld = Xd[LLD_];
type = PB_Cztypeset(); size = type->size;
Xlindx = Xii - 1 +
izamax_( &Xnp, Mptr( ((char *)X), Xii, Xjj, Xld,
size ), INCX );
Mindxl2g( Xgindx, Xlindx, Ximb, Xmb, myrow, Xsrc, nprow );
Xptr = Mptr( ((char *) X), Xlindx, Xjj, Xld, size );
work[0][REAL_PART] = ((double*)(Xptr))[REAL_PART];
work[0][IMAG_PART] = ((double*)(Xptr))[IMAG_PART];
work[1][REAL_PART] = ((double)( Xgindx+1 ));
work[1][IMAG_PART] = ZERO;
}
else
{
work[0][REAL_PART] = ZERO;
work[0][IMAG_PART] = ZERO;
work[1][REAL_PART] = ZERO;
work[1][IMAG_PART] = ZERO;
}
/*
* Combine the local results using a 1-tree topology within process row 0
* if nprow > 1 or Xrow >= 0, i.e sub( X ) is distributed.
*/
if( ( nprow >= 2 ) && ( Xrow >= 0 ) )
{
mydist = myrow;
k = 1;
l_30:
if( mydist & 1 )
{
dist = k * ( mydist - 1 );
dst = MPosMod( dist, nprow );
Czgesd2d( ctxt, 2, 1, ((char*)work), 2, dst, mycol );
goto l_40;
}
else
{
dist = myrow + k;
src = MPosMod( dist, nprow );
if( myrow < src )
{
Czgerv2d( ctxt, 2, 1, ((char*) work[2]), 2,
src, mycol );
if( ( ABS( work[0][REAL_PART] ) +
ABS( work[0][IMAG_PART] ) ) <
( ABS( work[2][REAL_PART] ) +
ABS( work[2][IMAG_PART] ) ) )
{
work[0][REAL_PART] = work[2][REAL_PART];
work[0][IMAG_PART] = work[2][IMAG_PART];
work[1][REAL_PART] = work[3][REAL_PART];
}
}
mydist >>= 1;
}
k <<= 1;
if( k < nprow ) goto l_30;
l_40:
/*
* Process row 0 broadcasts the combined values of INDX and AMAX within their
* process column.
*/
cbtop = *PB_Ctop( &ctxt, BCAST, COLUMN, TOP_GET );
if( myrow == 0 )
{
Czgebs2d( ctxt, COLUMN, &cbtop, 2, 1, ((char*)work), 2 );
}
else
{
Czgebr2d( ctxt, COLUMN, &cbtop, 2, 1, ((char*)work), 2,
0, mycol );
}
}
/*
* Set INDX and AMAX to the replicated answers contained in work. If AMAX is
* zero, then select a coherent INDX.
*/
AMAX[REAL_PART] = work[0][REAL_PART];
AMAX[IMAG_PART] = work[0][IMAG_PART];
*INDX = ( ( ( AMAX[REAL_PART] == ZERO ) &&
( AMAX[IMAG_PART] == ZERO ) ) ?
( *IX ) : ( (int)(work[1][REAL_PART]) ) );
}
else
{
/*
* Otherwise use the current topology settings to combine the results
*/
Ximb = Xd[IMB_ ]; Xmb = Xd[MB_ ]; Xsrc = Xd[RSRC_];
Xnp = PB_Cnumroc( *N, Xi, Ximb, Xmb, myrow, Xsrc, nprow );
/*
* Make sure I own some data and compute local INDX and AMAX
*/
if( Xnp > 0 )
{
/*
* Compute the local maximum and its corresponding local index
*/
Xld = Xd[LLD_];
type = PB_Cztypeset(); size = type->size;
Xlindx = Xii - 1 +
izamax_( &Xnp, Mptr( ((char *) X), Xii, Xjj, Xld,
size ), INCX );
Xptr = Mptr( ((char *) X), Xlindx, Xjj, Xld, size );
AMAX[REAL_PART] = ((double*)(Xptr))[REAL_PART];
AMAX[IMAG_PART] = ((double*)(Xptr))[IMAG_PART];
}
else
{
AMAX[REAL_PART] = ZERO;
AMAX[IMAG_PART] = ZERO;
}
if( Xrow >= 0 )
{
/*
* Combine leave on all the local maximum if Xrow >= 0, i.e sub( X ) is
* distributed.
*/
Czgamx2d( ctxt, COLUMN, &cctop, 1, 1, ((char*)AMAX), 1,
&maxpos, &idumm, 1, -1, mycol );
/*
* Broadcast the corresponding global index
*/
if( ( AMAX[REAL_PART] != ZERO ) || ( AMAX[IMAG_PART] != ZERO ) )
{
cbtop = *PB_Ctop( &ctxt, BCAST, COLUMN, TOP_GET );
if( myrow == maxpos )
{
Mindxl2g( Xgindx, Xlindx, Ximb, Xmb, myrow, Xsrc, nprow );
*INDX = Xgindx + 1;
Cigebs2d( ctxt, COLUMN, &cbtop, 1, 1, ((char*)INDX), 1 );
}
else
{
Cigebr2d( ctxt, COLUMN, &cbtop, 1, 1, ((char*)INDX), 1,
maxpos, mycol );
}
}
else
{
/*
* If AMAX is zero, then select a coherent INDX.
*/
*INDX = *IX;
}
}
else
{
/*
* sub( X ) is not distributed. If AMAX is zero, then select a coherent INDX.
*/
*INDX = ( ( ( AMAX[REAL_PART] == ZERO ) &&
( AMAX[IMAG_PART] == ZERO ) ) ?
( *IX ) : Xlindx + 1 );
}
}
}
return;
}
/*
* End of PZAMAX
*/
}
|
481837.c | /** @file
Random number generator services that uses RdRand instruction access
to provide high-quality random numbers.
Copyright (c) 2015, Intel Corporation. All rights reserved.<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 <Library/BaseLib.h>
#include <Library/DebugLib.h>
//
// Bit mask used to determine if RdRand instruction is supported.
//
#define RDRAND_MASK BIT30
//
// Limited retry number when valid random data is returned.
// Uses the recommended value defined in Section 7.3.17 of "Intel 64 and IA-32
// Architectures Software Developer's Mannual".
//
#define RDRAND_RETRY_LIMIT 10
/**
The constructor function checks whether or not RDRAND instruction is supported
by the host hardware.
The constructor function checks whether or not RDRAND instruction is supported.
It will ASSERT() if RDRAND instruction is not supported.
It will always return RETURN_SUCCESS.
@retval RETURN_SUCCESS The constructor always returns EFI_SUCCESS.
**/
RETURN_STATUS
EFIAPI
BaseRngLibConstructor (
VOID
)
{
UINT32 RegEcx;
//
// Determine RDRAND support by examining bit 30 of the ECX register returned by
// CPUID. A value of 1 indicates that processor support RDRAND instruction.
//
AsmCpuid (1, 0, 0, &RegEcx, 0);
ASSERT ((RegEcx & RDRAND_MASK) == RDRAND_MASK);
return RETURN_SUCCESS;
}
/**
Generates a 16-bit random number.
if Rand is NULL, then ASSERT().
@param[out] Rand Buffer pointer to store the 16-bit random value.
@retval TRUE Random number generated successfully.
@retval FALSE Failed to generate the random number.
**/
BOOLEAN
EFIAPI
GetRandomNumber16 (
OUT UINT16 *Rand
)
{
UINT32 Index;
ASSERT (Rand != NULL);
//
// A loop to fetch a 16 bit random value with a retry count limit.
//
for (Index = 0; Index < RDRAND_RETRY_LIMIT; Index++) {
if (AsmRdRand16 (Rand)) {
return TRUE;
}
}
return FALSE;
}
/**
Generates a 32-bit random number.
if Rand is NULL, then ASSERT().
@param[out] Rand Buffer pointer to store the 32-bit random value.
@retval TRUE Random number generated successfully.
@retval FALSE Failed to generate the random number.
**/
BOOLEAN
EFIAPI
GetRandomNumber32 (
OUT UINT32 *Rand
)
{
UINT32 Index;
ASSERT (Rand != NULL);
//
// A loop to fetch a 32 bit random value with a retry count limit.
//
for (Index = 0; Index < RDRAND_RETRY_LIMIT; Index++) {
if (AsmRdRand32 (Rand)) {
return TRUE;
}
}
return FALSE;
}
/**
Generates a 64-bit random number.
if Rand is NULL, then ASSERT().
@param[out] Rand Buffer pointer to store the 64-bit random value.
@retval TRUE Random number generated successfully.
@retval FALSE Failed to generate the random number.
**/
BOOLEAN
EFIAPI
GetRandomNumber64 (
OUT UINT64 *Rand
)
{
UINT32 Index;
ASSERT (Rand != NULL);
//
// A loop to fetch a 64 bit random value with a retry count limit.
//
for (Index = 0; Index < RDRAND_RETRY_LIMIT; Index++) {
if (AsmRdRand64 (Rand)) {
return TRUE;
}
}
return FALSE;
}
/**
Generates a 128-bit random number.
if Rand is NULL, then ASSERT().
@param[out] Rand Buffer pointer to store the 128-bit random value.
@retval TRUE Random number generated successfully.
@retval FALSE Failed to generate the random number.
**/
BOOLEAN
EFIAPI
GetRandomNumber128 (
OUT UINT64 *Rand
)
{
ASSERT (Rand != NULL);
//
// Read first 64 bits
//
if (!GetRandomNumber64 (Rand)) {
return FALSE;
}
//
// Read second 64 bits
//
return GetRandomNumber64 (++Rand);
}
|
306038.c | int main() {
return sizeof(unsigned long long int);
}
|
409733.c | /* BFD back-end for Apple M68K COFF A/UX 3.x files.
Copyright 1996, 1997, 2000, 2002, 2007 Free Software Foundation, Inc.
Written by Richard Henderson <[email protected]>.
This file is part of BFD, the Binary File Descriptor library.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 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. */
#define TARGET_SYM m68kaux_coff_vec
#define TARGET_NAME "coff-m68k-aux"
#ifndef TARG_AUX
#define TARG_AUX
#endif
#define COFF_LONG_FILENAMES
/* 4k pages */
#define COFF_PAGE_SIZE 0x1000
/* On AUX, a STYP_NOLOAD|STYP_BSS section is part of a shared library. */
#define BSS_NOLOAD_IS_SHARED_LIBRARY
#define STATIC_RELOCS
#define COFF_COMMON_ADDEND
#include "sysdep.h"
#include "bfd.h"
static bfd_boolean coff_m68k_aux_link_add_one_symbol
PARAMS ((struct bfd_link_info *, bfd *, const char *, flagword,
asection *, bfd_vma, const char *, bfd_boolean, bfd_boolean,
struct bfd_link_hash_entry **));
#define coff_link_add_one_symbol coff_m68k_aux_link_add_one_symbol
#include "coff/aux-coff.h" /* override coff/internal.h and coff/m68k.h */
#include "coff-m68k.c"
/* We need non-absolute symbols to override absolute symbols. This
mirrors Apple's "solution" to let a static library symbol override
a shared library symbol. On the whole not a good thing, given how
shared libraries work here, but can work if you are careful with
what you include in the shared object. */
static bfd_boolean
coff_m68k_aux_link_add_one_symbol (info, abfd, name, flags, section, value,
string, copy, collect, hashp)
struct bfd_link_info *info;
bfd *abfd;
const char *name;
flagword flags;
asection *section;
bfd_vma value;
const char *string;
bfd_boolean copy;
bfd_boolean collect;
struct bfd_link_hash_entry **hashp;
{
struct bfd_link_hash_entry *h;
if ((flags & (BSF_WARNING | BSF_CONSTRUCTOR | BSF_WEAK)) == 0 &&
!bfd_is_und_section (section) &&
!bfd_is_com_section (section))
{
/* The new symbol is a definition or an indirect definition */
/* This bit copied from linker.c */
if (hashp != NULL && *hashp != NULL)
{
h = *hashp;
BFD_ASSERT (strcmp (h->root.string, name) == 0);
}
else
{
h = bfd_link_hash_lookup (info->hash, name, TRUE, copy, FALSE);
if (h == NULL)
{
if (hashp != NULL)
*hashp = NULL;
return FALSE;
}
}
if (info->notice_hash != (struct bfd_hash_table *) NULL
&& (bfd_hash_lookup (info->notice_hash, name, FALSE, FALSE)
!= (struct bfd_hash_entry *) NULL))
{
if (! (*info->callbacks->notice) (info, name, abfd, section, value))
return FALSE;
}
if (hashp != (struct bfd_link_hash_entry **) NULL)
*hashp = h;
/* end duplication from linker.c */
if (h->type == bfd_link_hash_defined
|| h->type == bfd_link_hash_indirect)
{
asection *msec;
if (h->type == bfd_link_hash_defined)
msec = h->u.def.section;
else
msec = bfd_ind_section_ptr;
if (bfd_is_abs_section (msec) && !bfd_is_abs_section (section))
{
h->u.def.section = section;
h->u.def.value = value;
return TRUE;
}
else if (bfd_is_abs_section (section) && !bfd_is_abs_section (msec))
return TRUE;
}
}
/* If we didn't exit early, finish processing in the generic routine */
return _bfd_generic_link_add_one_symbol (info, abfd, name, flags, section,
value, string, copy, collect,
hashp);
}
|
779096.c | #include <pthread.h>
struct
{
int a, b;
} s;
void *t1(void *arg)
{
s.a=10; // not a race
}
void *t2(void *arg)
{
s.b=20; // not a race
}
int main()
{
pthread_t id1, id2;
pthread_create(&id1, NULL, t1, NULL);
pthread_create(&id2, NULL, t2, NULL);
}
|
211289.c | #include "ui.h"
#include<stdio.h>
#include<pthread.h>
#include<stdlib.h>
#include <unistd.h>
pthread_mutex_t lock;
int gold = 100;
int zombies = 1;
int soldiers = 0;
int health = 100;
void *minerfunc(void *ptr){
while(1){
pthread_mutex_lock(&lock);
gold = gold + 10;
print_gold(gold);
pthread_mutex_unlock(&lock);
sleep(1);
}
}
void *zombiefunc(void *ptr){
while(1){
for(int i = 5; i > 0; i--){
pthread_mutex_lock(&lock);
print_zombies(i, zombies);
pthread_mutex_unlock(&lock);
sleep(1);
}
pthread_mutex_lock(&lock);
if(zombies > soldiers){
health = health - (zombies - soldiers);
print_health(health);
print_fail("Zombie attack succeded ;(!");
if(health < 0){
game_end(zombies);
}
zombies = zombies * 2;
}
else{
print_succ("Zombie attack deflected! :)");
zombies = zombies * 2;
}
pthread_mutex_unlock(&lock);
}
}
int main() {
init();
print_gold(100);
print_soldiers(0);
print_zombies(5,1);
print_health(100);
pthread_t zombie;
pthread_create(&zombie, NULL, zombiefunc, NULL);
while(1) {
int ch = get_input();
pthread_t miner;
switch(ch) {
case 'q':
pthread_mutex_lock(&lock);
game_end(zombies);
break;
pthread_mutex_unlock(&lock);
case 'm':
pthread_mutex_lock(&lock);
if(gold > 99){
pthread_create(&miner, NULL, minerfunc, NULL);
gold = gold - 100;
print_gold(gold);
print_msg("Miner created!");
}
else{
print_fail("Not enough gold!");
}
pthread_mutex_unlock(&lock);
break;
case 's':
pthread_mutex_lock(&lock);
if(gold > 9){
soldiers = soldiers + 1;
gold = gold - 10;
print_soldiers(soldiers);
print_gold(gold);
print_msg("Soldier created!");
}
else{
print_fail("Not enough gold!");
}
pthread_mutex_unlock(&lock);
break;
case 'x':
pthread_mutex_lock(&lock);
if(gold > 99){
soldiers = soldiers + 10;
gold = gold - 100;
print_soldiers(soldiers);
print_gold(gold);
print_msg("10 x soldier created!");
}
else{
print_fail("Not enough gold!");
}
pthread_mutex_unlock(&lock);
break;
}
}
}
|
798658.c | #include<stdio.h>
int main(){
double n, temp;
int ceil, floor, round;
scanf("%lf", &n);
if(n>=0){
floor= (int) n;
ceil= (int) (n+1);
if(floor==n)
ceil-=1;
round=(int) (n+0.5);
}
else{
ceil= (int) n;
floor= (int) (n-1);
if(ceil==n)
floor+=1;
round= (int) (n-0.5);
temp= (int) n - 0.5;
if(temp==n)
round+=1;
}
printf("Ceil= %d Floor= %d Round= %d\n", ceil, floor, round);
return main();
}
|
619929.c | /**
AsmReadMm3 function
Copyright (c) 2006 - 2007, Intel Corporation. All rights reserved.<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 "BaseLibInternals.h"
UINT64
EFIAPI
AsmReadMm3 (
VOID
)
{
_asm {
push eax
push eax
movq [esp], mm3
pop eax
pop edx
emms
}
}
|
131964.c | /* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE191_Integer_Underflow__int_rand_postdec_01.c
Label Definition File: CWE191_Integer_Underflow__int.label.xml
Template File: sources-sinks-01.tmpl.c
*/
/*
* @description
* CWE: 191 Integer Underflow
* BadSource: rand Set data to result of rand(), which may be zero
* GoodSource: Set data to a small, non-zero number (negative two)
* Sinks: decrement
* GoodSink: Ensure there will not be an underflow before decrementing data
* BadSink : Decrement data, which can cause an Underflow
* Flow Variant: 01 Baseline
*
* */
#include "std_testcase.h"
#ifndef OMITBAD
void CWE191_Integer_Underflow__int_rand_postdec_01_bad()
{
int data;
/* Initialize data */
data = 0;
/* POTENTIAL FLAW: Set data to a random value */
data = RAND32();
{
/* POTENTIAL FLAW: Decrementing data could cause an underflow */
data--;
int result = data;
printIntLine(result);
}
}
#endif /* OMITBAD */
#ifndef OMITGOOD
/* goodG2B uses the GoodSource with the BadSink */
static void goodG2B()
{
int data;
/* Initialize data */
data = 0;
/* FIX: Use a small, non-zero value that will not cause an integer underflow in the sinks */
data = -2;
{
/* POTENTIAL FLAW: Decrementing data could cause an underflow */
data--;
int result = data;
printIntLine(result);
}
}
/* goodB2G uses the BadSource with the GoodSink */
static void goodB2G()
{
int data;
/* Initialize data */
data = 0;
/* POTENTIAL FLAW: Set data to a random value */
data = RAND32();
/* FIX: Add a check to prevent an underflow from occurring */
if (data > INT_MIN)
{
data--;
int result = data;
printIntLine(result);
}
else
{
printLine("data value is too large to perform arithmetic safely.");
}
}
void CWE191_Integer_Underflow__int_rand_postdec_01_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()...");
CWE191_Integer_Underflow__int_rand_postdec_01_good();
printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
printLine("Calling bad()...");
CWE191_Integer_Underflow__int_rand_postdec_01_bad();
printLine("Finished bad()");
#endif /* OMITBAD */
return 0;
}
#endif
|
944007.c | /*******************************************************************************
* LBF_SysClkCfg
*
* (c)2015 LimiFrog / CYMEYA
* This program is licensed under the terms of the MIT License.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND.
* Please refer to the License File LICENSE.txt located at the root of this
* project for full licensing conditions,
* or visit https://opensource.org/licenses/MIT.
******************************************************************************/
#include "LBF_SysClkCfg.h"
#include "LBF_lowlev_API.h"
/* Privates prototypes -------------------------------------------------------*/
/* Functions -----------------------------------------------------------------*/
/*******************************************************************************/
/* ----------------------------------------------------------------------------
* Assumption: 8MHz external oscillator (HSE), 32KHz external Xtal (LSE) *
* Want 80MHz core clock, 48 MHz USB clock, 1ms Timer Tick,
* 20MHz periph clock APB1 and APB2
* Must set Flash Latency according to core clock (80MHz here)
* ---------------------------------------------------------------------------*/
void LBF_SysClkCfg(void)
{
/* Begin CubeMX generated code - MODIFIED */
RCC_OscInitTypeDef RCC_OscInitStruct;
RCC_ClkInitTypeDef RCC_ClkInitStruct;
RCC_PeriphCLKInitTypeDef PeriphClkInit;
if (__HAL_PWR_GET_FLAG(PWR_FLAG_SB) != RESET)
{
RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSE;
// dont touch LSE if outof standby mode
}
else
{
RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSE|RCC_OSCILLATORTYPE_LSE;
}
RCC_OscInitStruct.HSEState = RCC_HSE_ON;
RCC_OscInitStruct.LSEState = RCC_LSE_ON;
RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE;
RCC_OscInitStruct.PLL.PLLM = 1;
RCC_OscInitStruct.PLL.PLLN = 36;
RCC_OscInitStruct.PLL.PLLP = RCC_PLLP_DIV7; // unused for now
RCC_OscInitStruct.PLL.PLLQ = RCC_PLLQ_DIV6; // 8MMHz/M*N/Q=48MHz
RCC_OscInitStruct.PLL.PLLR = RCC_PLLR_DIV4; // 8MMHz/M*N/Q=72MHz
HAL_RCC_OscConfig(&RCC_OscInitStruct);
RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK
|RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2;
RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK; // SYSCLK = 72MHz
RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1; // AHBCLK (HCLK) = 72MHz to Cortex
RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV4; // APB1 periph clock = 18MHz
RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV4; // APB2 periph clock = 18MHz
// RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV2; // APB1 periph clock = 36MHz
// RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV2; // APB2 periph clock = 36MHz
HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_4);
PeriphClkInit.PeriphClockSelection = RCC_PERIPHCLK_RTC|RCC_PERIPHCLK_USB;
PeriphClkInit.RTCClockSelection = RCC_RTCCLKSOURCE_LSE;
PeriphClkInit.UsbClockSelection = RCC_USBCLKSOURCE_PLL; //Div.Q output, 48MHz
HAL_RCCEx_PeriphCLKConfig(&PeriphClkInit);
__PWR_CLK_ENABLE();
HAL_PWREx_ControlVoltageScaling(PWR_REGULATOR_VOLTAGE_SCALE1);
HAL_SYSTICK_Config(HAL_RCC_GetHCLKFreq()/8000);
HAL_SYSTICK_CLKSourceConfig(SYSTICK_CLKSOURCE_HCLK_DIV8);
/* End of CubeMX generated code */
__SYSCFG_CLK_ENABLE();
// System Configuration Clock
// The system configuration controller is mainly used to remap the memory accessible in the
// code area, and manage the external interrupt line connection to the GPIOs.
}
/***************************************************************END OF FILE****/
|
963741.c | /*
* adler32.c - Adler-32 checksum algorithm
*
* Copyright 2016 Eric Biggers
*
* 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 "lib_common.h"
#include "libdeflate.h"
/* The Adler-32 divisor, or "base", value. */
#define DIVISOR 65521
/*
* MAX_CHUNK_SIZE is the most bytes that can be processed without the
* possibility of s2 overflowing when it is represented as an unsigned 32-bit
* integer. This value was computed using the following Python script:
*
* divisor = 65521
* count = 0
* s1 = divisor - 1
* s2 = divisor - 1
* while True:
* s1 += 0xFF
* s2 += s1
* if s2 > 0xFFFFFFFF:
* break
* count += 1
* print(count)
*
* Note that to get the correct worst-case value, we must assume that every byte
* has value 0xFF and that s1 and s2 started with the highest possible values
* modulo the divisor.
*/
#define MAX_CHUNK_SIZE 5552
typedef u32 (*adler32_func_t)(u32, const u8 *, size_t);
/* Include architecture-specific implementations if available */
#undef DEFAULT_IMPL
#undef DISPATCH
#if defined(__arm__) || defined(__aarch64__)
# include "arm/adler32_impl.h"
#elif defined(__i386__) || defined(__x86_64__)
# include "x86/adler32_impl.h"
#endif
/* Define a generic implementation if needed */
#ifndef DEFAULT_IMPL
#define DEFAULT_IMPL adler32_generic
static u32 adler32_generic(u32 adler, const u8 *p, size_t size)
{
u32 s1 = adler & 0xFFFF;
u32 s2 = adler >> 16;
const u8 * const end = p + size;
while (p != end) {
size_t chunk_size = MIN(end - p, MAX_CHUNK_SIZE);
const u8 *chunk_end = p + chunk_size;
size_t num_unrolled_iterations = chunk_size / 4;
while (num_unrolled_iterations--) {
s1 += *p++;
s2 += s1;
s1 += *p++;
s2 += s1;
s1 += *p++;
s2 += s1;
s1 += *p++;
s2 += s1;
}
while (p != chunk_end) {
s1 += *p++;
s2 += s1;
}
s1 %= DIVISOR;
s2 %= DIVISOR;
}
return (s2 << 16) | s1;
}
#endif /* !DEFAULT_IMPL */
#ifdef DISPATCH
static u32 dispatch(u32, const u8 *, size_t);
static volatile adler32_func_t adler32_impl = dispatch;
/* Choose the fastest implementation at runtime */
static u32 dispatch(u32 adler, const u8 *buffer, size_t size)
{
adler32_func_t f = arch_select_adler32_func();
if (f == NULL)
f = DEFAULT_IMPL;
adler32_impl = f;
return adler32_impl(adler, buffer, size);
}
#else
# define adler32_impl DEFAULT_IMPL /* only one implementation, use it */
#endif
LIBDEFLATEAPI u32
libdeflate_adler32(u32 adler, const void *buffer, size_t size)
{
if (buffer == NULL) /* return initial value */
return 1;
return adler32_impl(adler, buffer, size);
}
|
Subsets and Splits