filename
stringlengths 3
9
| code
stringlengths 4
1.05M
|
---|---|
395741.c | #if !defined(lint) && !defined(DOS)
static char rcsid[] = "$Id: mailcap.c 1012 2008-03-26 00:44:22Z [email protected] $";
#endif
/*
* ========================================================================
* Copyright 2006-2008 University of Washington
*
* 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
*
* ========================================================================
*/
#include "../pith/headers.h"
#include "../pith/mailcap.h"
#include "../pith/init.h"
#include "../pith/conf.h"
#include "../pith/mimetype.h"
#include "../pith/mimedesc.h"
#include "../pith/status.h"
#include "../pith/util.h"
#include "../pith/readfile.h"
/*
* We've decided not to implement the RFC1524 standard minimum path, because
* some of us think it is harder to debug a problem when you may be misled
* into looking at the wrong mailcap entry. Likewise for MIME.Types files.
*/
#if defined(DOS) || defined(OS2)
#define MC_PATH_SEPARATOR ';'
#define MC_USER_FILE "MAILCAP"
#define MC_STDPATH NULL
#else /* !DOS */
#define MC_PATH_SEPARATOR ':'
#define MC_USER_FILE NULL
#define MC_STDPATH \
".mailcap:/etc/mailcap:/usr/etc/mailcap:/usr/local/etc/mailcap"
#endif /* !DOS */
#ifdef _WINDOWS
#define MC_ADD_TMP " %s"
#else
#define MC_ADD_TMP " < %s"
#endif
typedef struct mcap_entry {
struct mcap_entry *next;
int needsterminal;
char *contenttype;
char *command;
char *testcommand;
char *label; /* unused */
char *printcommand; /* unused */
} MailcapEntry;
struct mailcap_data {
MailcapEntry *head, **tail;
STRINGLIST *raw;
} MailcapData;
#define MC_TOKEN_MAX 64
/*
* Internal prototypes
*/
void mc_init(void);
void mc_process_file(char *);
void mc_parse_file(char *);
int mc_parse_line(char **, char **);
int mc_comment(char **);
int mc_token(char **, char **);
void mc_build_entry(char **);
int mc_sane_command(char *);
MailcapEntry *mc_get_command(int, char *, BODY *, int, int *);
int mc_ctype_match(int, char *, char *);
int mc_passes_test(MailcapEntry *, int, char *, BODY *);
char *mc_bld_test_cmd(char *, int, char *, BODY *);
char *mc_cmd_bldr(char *, int, char *, BODY *, char *, char **);
MailcapEntry *mc_new_entry(void);
void mc_free_entry(MailcapEntry **);
char *
mc_conf_path(char *def_path, char *env_path, char *user_file, int separator, char *stdpath)
{
char *path;
/* We specify MIMETYPES as a path override */
if(def_path)
/* there may need to be an override specific to pine */
path = cpystr(def_path);
else if(env_path)
path = cpystr(env_path);
else{
#if defined(DOS) || defined(OS2)
char *s;
/*
* This gets interesting. Since we don't have any standard location
* for config/data files, look in the same directory as the PINERC
* and the same dir as PINE.EXE. This is similar to the UNIX
* situation with personal config info coming before
* potentially shared config data...
*/
if(s = last_cmpnt(ps_global->pinerc)){
strncpy(tmp_20k_buf+1000, ps_global->pinerc, MIN(s - ps_global->pinerc,SIZEOF_20KBUF-1000));
tmp_20k_buf[1000+MIN(s - ps_global->pinerc,SIZEOF_20KBUF-1000-1)] = '\0';
}
else
strncpy(tmp_20k_buf+1000, ".\\", SIZEOF_20KBUF-1000);
/* pinerc directory version of file */
build_path(tmp_20k_buf+2000, tmp_20k_buf+1000, user_file, SIZEOF_20KBUF-2000);
tmp_20k_buf[SIZEOF_20KBUF-1] = '\0';
/* pine.exe directory version of file */
build_path(tmp_20k_buf+3000, ps_global->pine_dir, user_file, SIZEOF_20KBUF-3000);
tmp_20k_buf[SIZEOF_20KBUF-1] = '\0';
/* combine them */
snprintf(tmp_20k_buf, SIZEOF_20KBUF, "%s%c%s", tmp_20k_buf+2000, separator, tmp_20k_buf+3000);
#else /* !DOS */
build_path(tmp_20k_buf, ps_global->home_dir, stdpath, SIZEOF_20KBUF);
#endif /* !DOS */
path = cpystr(tmp_20k_buf);
}
return(path);
}
/*
* mc_init - Run down the path gathering all the mailcap entries.
* Returns with the Mailcap list built.
*/
void
mc_init(void)
{
char *s,
*pathcopy,
*path,
image_viewer[MAILTMPLEN];
if(MailcapData.raw) /* already have the file? */
return;
else
MailcapData.tail = &MailcapData.head;
dprint((5, "- mc_init -\n"));
pathcopy = mc_conf_path(ps_global->VAR_MAILCAP_PATH, getenv("MAILCAPS"),
MC_USER_FILE, MC_PATH_SEPARATOR, MC_STDPATH);
path = pathcopy; /* overloaded "path" */
/*
* Insert an entry for the image-viewer variable from .pinerc, if present.
*/
if(ps_global->VAR_IMAGE_VIEWER && *ps_global->VAR_IMAGE_VIEWER){
MailcapEntry *mc = mc_new_entry();
snprintf(image_viewer, sizeof(image_viewer), "%s %%s", ps_global->VAR_IMAGE_VIEWER);
MailcapData.raw = mail_newstringlist();
MailcapData.raw->text.data = (unsigned char *) cpystr(image_viewer);
mc->command = (char *) MailcapData.raw->text.data;
mc->contenttype = "image/*";
mc->label = "Alpine Image Viewer";
dprint((5, "mailcap: using image-viewer=%s\n",
ps_global->VAR_IMAGE_VIEWER
? ps_global->VAR_IMAGE_VIEWER : "?"));
}
dprint((7, "mailcap: path: %s\n", path ? path : "?"));
while(path){
s = strindex(path, MC_PATH_SEPARATOR);
if(s)
*s++ = '\0';
mc_process_file(path);
path = s;
}
if(pathcopy)
fs_give((void **)&pathcopy);
#ifdef DEBUG
if(debug >= 11){
MailcapEntry *mc;
int i = 0;
dprint((11, "Collected mailcap entries\n"));
for(mc = MailcapData.head; mc; mc = mc->next){
dprint((11, "%d: ", i++));
if(mc->label)
dprint((11, "%s\n", mc->label ? mc->label : "?"));
if(mc->contenttype)
dprint((11, " %s",
mc->contenttype ? mc->contenttype : "?"));
if(mc->command)
dprint((11, " command: %s\n",
mc->command ? mc->command : "?"));
if(mc->testcommand)
dprint((11, " testcommand: %s",
mc->testcommand ? mc->testcommand : "?"));
if(mc->printcommand)
dprint((11, " printcommand: %s",
mc->printcommand ? mc->printcommand : "?"));
dprint((11, " needsterminal %d\n", mc->needsterminal));
}
}
#endif /* DEBUG */
}
/*
* Add all the entries from this file onto the Mailcap list.
*/
void
mc_process_file(char *file)
{
char filebuf[MAXPATH+1], *file_data;
dprint((5, "mailcap: process_file: %s\n", file ? file : "?"));
(void)strncpy(filebuf, file, MAXPATH);
filebuf[MAXPATH] = '\0';
file = fnexpand(filebuf, sizeof(filebuf));
dprint((7, "mailcap: processing file: %s\n", file ? file : "?"));
switch(is_writable_dir(file)){
case 0: case 1: /* is a directory */
dprint((1, "mailcap: %s is a directory, should be a file\n",
file ? file : "?"));
return;
case 2: /* ok */
break;
case 3: /* doesn't exist */
dprint((5, "mailcap: %s doesn't exist\n", file ? file : "?"));
return;
default:
panic("Programmer botch in mc_process_file");
/*NOTREACHED*/
}
if((file_data = read_file(file, READ_FROM_LOCALE)) != NULL){
STRINGLIST *newsl, **sl;
/* Create a new container */
newsl = mail_newstringlist();
newsl->text.data = (unsigned char *) file_data;
/* figure out where in the list it should go */
for(sl = &MailcapData.raw; *sl; sl = &((*sl)->next))
;
*sl = newsl; /* Add it to the list */
mc_parse_file(file_data); /* the process mailcap data */
}
else
dprint((5, "mailcap: %s can't be read\n", file ? file : "?"));
}
void
mc_parse_file(char *file)
{
char *tokens[MC_TOKEN_MAX];
while(mc_parse_line(&file, tokens))
mc_build_entry(tokens);
}
int
mc_parse_line(char **line, char **tokens)
{
char **tokenp = tokens;
while(mc_comment(line)) /* skip comment lines */
;
while(mc_token(tokenp, line)) /* collect ';' delim'd tokens */
if(++tokenp - tokens >= MC_TOKEN_MAX)
fatal("Ran out of tokens parsing mailcap file"); /* outch! */
*++tokenp = NULL; /* tie off list */
return(*tokens != NULL);
}
/*
* Retuns 1 if line is a comment, 0 otherwise
*/
int
mc_comment(char **line)
{
if(**line == '\n'){ /* blank line is a comment, too */
(*line)++;
return(1);
}
if(**line == '#'){
while(**line) /* !EOF */
if(*++(*line) == '\n'){ /* EOL? */
(*line)++;
break;
}
return(1);
}
return(0);
}
/*
* Retuns 0 if EOL, 1 otherwise
*/
int
mc_token(char **token, char **line)
{
int rv = 0;
char *start, *wsp = NULL;
*token = NULL; /* init the slot for this token */
/* skip leading white space */
while(**line && isspace((unsigned char) **line))
(*line)++;
start = *line;
/* Then see what's left */
while(1)
switch(**line){
case ';' : /* End-Of-Token */
rv = 1; /* let caller know more follows */
case '\n' : /* EOL */
if(wsp)
*wsp = '\0'; /* truncate white space? */
else
*start = '\0'; /* if we have a token, tie it off */
(*line)++; /* and get ready to parse next one */
if(rv == 1){ /* ignore trailing semicolon */
while(**line){
if(**line == '\n')
rv = 0;
if(isspace((unsigned char) **line))
(*line)++;
else
break;
}
}
case '\0' : /* EOF */
return(rv);
case '\\' : /* Quoted char */
(*line)++;
#if defined(DOS) || defined(OS2)
/*
* RFC 1524 says that backslash is used to quote
* the next character, but since backslash is part of pathnames
* on DOS we're afraid people will not put double backslashes
* in their mailcap files. Therefore, we violate the RFC by
* looking ahead to the next character. If it looks like it
* is just part of a pathname, then we consider a single
* backslash to *not* be a quoting character, but a literal
* backslash instead.
*
* SO:
* If next char is any of these, treat the backslash
* that preceded it like a regular character.
*/
if(**line && isascii(**line)
&& (isalnum((unsigned char) **line) || strchr("_+-=~" , **line))){
*start++ = '\\';
wsp = NULL;
break;
}
else
#endif /* !DOS */
if(**line == '\n'){ /* quoted line break */
*start = ' ';
(*line)++; /* just move on */
while(isspace((unsigned char) **line))
(*line)++;
break;
}
else if(**line == '%') /* quoted '%' becomes "%%" */
*--(*line) = '%'; /* overwrite '\' !! */
/* Fall thru and copy/advance pointers*/
default :
if(!*token)
*token = start;
*start = *(*line)++;
wsp = (isspace((unsigned char) *start) && !wsp) ? start : NULL;
start++;
break;
}
}
void
mc_build_entry(char **tokens)
{
MailcapEntry *mc;
if(!tokens[0]){
dprint((5, "mailcap: missing content type!\n"));
return;
}
else if(!tokens[1] || !mc_sane_command(tokens[1])){
dprint((5, "mailcap: missing/bogus command!\n"));
return;
}
mc = mc_new_entry();
mc->contenttype = *tokens++;
mc->command = *tokens++;
dprint((9, "mailcap: content type: %s\n command: %s\n",
mc->contenttype ? mc->contenttype : "?",
mc->command ? mc->command : "?"));
/* grok options */
for( ; *tokens; tokens++){
char *arg;
/* legit value? */
if(!isalnum((unsigned char) **tokens)){
dprint((5, "Unknown parameter = \"%s\"", *tokens));
continue;
}
if((arg = strindex(*tokens, '=')) != NULL){
*arg = ' ';
while(arg > *tokens && isspace((unsigned char) arg[-1]))
arg--;
*arg++ = '\0'; /* tie off parm arg */
while(*arg && isspace((unsigned char) *arg))
arg++;
if(!*arg)
arg = NULL;
}
if(!strucmp(*tokens, "needsterminal")){
mc->needsterminal = 1;
dprint((9, "mailcap: set needsterminal\n"));
}
else if(!strucmp(*tokens, "copiousoutput")){
mc->needsterminal = 2;
dprint((9, "mailcap: set copiousoutput\n"));
}
else if(arg && !strucmp(*tokens, "test")){
mc->testcommand = arg;
dprint((9, "mailcap: testcommand=%s\n",
mc->testcommand ? mc->testcommand : "?"));
}
else if(arg && !strucmp(*tokens, "description")){
mc->label = arg;
dprint((9, "mailcap: label=%s\n",
mc->label ? mc->label : "?"));
}
else if(arg && !strucmp(*tokens, "print")){
mc->printcommand = arg;
dprint((9, "mailcap: printcommand=%s\n",
mc->printcommand ? mc->printcommand : "?"));
}
else if(arg && !strucmp(*tokens, "compose")){
/* not used */
dprint((9, "mailcap: not using compose=%s\n",
arg ? arg : "?"));
}
else if(arg && !strucmp(arg, "composetyped")){
/* not used */
dprint((9, "mailcap: not using composetyped=%s\n",
arg ? arg : "?"));
}
else if(arg && !strucmp(arg, "textualnewlines")){
/* not used */
dprint((9,
"mailcap: not using texttualnewlines=%s\n",
arg ? arg : "?"));
}
else if(arg && !strucmp(arg, "edit")){
/* not used */
dprint((9, "mailcap: not using edit=%s\n",
arg ? arg : "?"));
}
else if(arg && !strucmp(arg, "x11-bitmap")){
/* not used */
dprint((9, "mailcap: not using x11-bitmap=%s\n",
arg ? arg : "?"));
}
else
dprint((9, "mailcap: ignoring unknown flag: %s\n",
arg ? arg : "?"));
}
}
/*
* Tests for mailcap defined command's sanity
*/
int
mc_sane_command(char *command)
{
/* First, test that a command string actually exists */
if(command && *command){
#ifdef LATER
/*
* NOTE: Maybe we'll do this later. The problem is when the
* mailcap's been misconfigured. We then end up supressing
* valuable output when the user actually tries to launch the
* spec'd viewer.
*/
/* Second, Make sure we can get at it */
if(can_access_in_path(getenv("PATH"), command, EXECUTE_ACCESS) >= 0)
#endif
return(1);
}
return(0); /* failed! */
}
/*
* Returns the mailcap entry for type/subtype from the successfull
* mailcap entry, or NULL if none. Command string still contains % stuff.
*/
MailcapEntry *
mc_get_command(int type, char *subtype, BODY *body,
int check_extension, int *sp_handlingp)
{
MailcapEntry *mc;
char tmp_subtype[256], tmp_ext[16], *ext = NULL;
dprint((5, "- mc_get_command(%s/%s) -\n",
body_type_names(type),
subtype ? subtype : "?"));
if(type == TYPETEXT
&& (!subtype || !strucmp(subtype, "plain"))
&& F_ON(F_SHOW_TEXTPLAIN_INT, ps_global))
return(NULL);
mc_init();
if(check_extension){
char *fname;
MT_MAP_T e2b;
/*
* Special handling for when we're looking at what's likely
* binary application data. Look for a file name extension
* that we might use to hook a helper app to.
*
* NOTE: This used to preclude an "app/o-s" mailcap entry
* since this took precedence. Now that there are
* typically two scans through the check_extension
* mechanism, the mailcap entry now takes precedence.
*/
if((fname = get_filename_parameter(NULL, 0, body, &e2b.from.ext)) != NULL
&& e2b.from.ext && e2b.from.ext[0]){
if(strlen(e2b.from.ext) < sizeof(tmp_ext) - 2){
strncpy(ext = tmp_ext, e2b.from.ext - 1, sizeof(tmp_ext)); /* remember it */
tmp_ext[sizeof(tmp_ext)-1] = '\0';
if(mt_srch_mime_type(mt_srch_by_ext, &e2b)){
type = e2b.to.mime.type; /* mapped type */
strncpy(subtype = tmp_subtype, e2b.to.mime.subtype,
sizeof(tmp_subtype)-1);
tmp_subtype[sizeof(tmp_subtype)-1] = '\0';
fs_give((void **) &e2b.to.mime.subtype);
body = NULL; /* the params no longer apply */
}
}
fs_give((void **) &fname);
}
else{
if(fname)
fs_give((void **) &fname);
return(NULL);
}
}
for(mc = MailcapData.head; mc; mc = mc->next)
if(mc_ctype_match(type, subtype, mc->contenttype)
&& mc_passes_test(mc, type, subtype, body)){
dprint((9,
"mc_get_command: type=%s/%s, command=%s\n",
body_type_names(type),
subtype ? subtype : "?",
mc->command ? mc->command : "?"));
return(mc);
}
if(mime_os_specific_access()){
static MailcapEntry fake_mc;
static char fake_cmd[1024];
char tmp_mime_type[256];
memset(&fake_mc, 0, sizeof(MailcapEntry));
fake_cmd[0] = '\0';
fake_mc.command = fake_cmd;
snprintf(tmp_mime_type, sizeof(tmp_mime_type), "%s/%s", body_types[type], subtype);
if(mime_get_os_mimetype_command(tmp_mime_type, ext, fake_cmd,
sizeof(fake_cmd), check_extension, sp_handlingp))
return(&fake_mc);
}
return(NULL);
}
/*
* Check whether the pattern "pat" matches this type/subtype.
* Returns 1 if it does, 0 if not.
*/
int
mc_ctype_match(int type, char *subtype, char *pat)
{
char *type_name = body_type_names(type);
int len = strlen(type_name);
dprint((5, "mc_ctype_match: %s == %s / %s ?\n",
pat ? pat : "?",
type_name ? type_name : "?",
subtype ? subtype : "?"));
return(!struncmp(type_name, pat, len)
&& ((pat[len] == '/'
&& (!pat[len+1] || pat[len+1] == '*'
|| !strucmp(subtype, &pat[len+1])))
|| !pat[len]));
}
/*
* Run the test command for entry mc to see if this entry currently applies to
* applies to this type/subtype.
*
* Returns 1 if it does pass test (exits with status 0), 0 otherwise.
*/
int
mc_passes_test(MailcapEntry *mc, int type, char *subtype, BODY *body)
{
char *cmd = NULL;
int rv;
dprint((5, "- mc_passes_test -\n"));
if(mc->testcommand
&& *mc->testcommand
&& !(cmd = mc_bld_test_cmd(mc->testcommand, type, subtype, body)))
return(FALSE); /* couldn't be built */
if(!mc->testcommand || !cmd || !*cmd){
if(cmd)
fs_give((void **)&cmd);
dprint((7, "no test command, so Pass\n"));
return 1;
}
rv = exec_mailcap_test_cmd(cmd);
dprint((7, "mc_passes_test: \"%s\" %s (rv=%d)\n",
cmd ? cmd : "?", rv ? "Failed" : "Passed", rv)) ;
fs_give((void **)&cmd);
return(!rv);
}
int
mailcap_can_display(int type, char *subtype, BODY *body, int check_extension)
{
dprint((5, "- mailcap_can_display -\n"));
return(mc_get_command(type, subtype, body,
check_extension, NULL) != NULL);
}
MCAP_CMD_S *
mailcap_build_command(int type, char *subtype, BODY *body,
char *tmp_file, int *needsterm, int chk_extension)
{
MailcapEntry *mc;
char *command, *err = NULL;
MCAP_CMD_S *mc_cmd = NULL;
int sp_handling = 0;
dprint((5, "- mailcap_build_command -\n"));
mc = mc_get_command(type, subtype, body, chk_extension, &sp_handling);
if(!mc){
q_status_message(SM_ORDER, 3, 4, "Error constructing viewer command");
dprint((1,
"mailcap_build_command: no command string for %s/%s\n",
body_type_names(type), subtype ? subtype : "?"));
return((MCAP_CMD_S *)NULL);
}
if(needsterm)
*needsterm = mc->needsterminal;
if(sp_handling)
command = cpystr(mc->command);
else if(!(command = mc_cmd_bldr(mc->command, type, subtype, body, tmp_file, &err)) && err && *err)
q_status_message(SM_ORDER, 5, 5, err);
dprint((5, "built command: %s\n", command ? command : "?"));
if(command){
mc_cmd = (MCAP_CMD_S *)fs_get(sizeof(MCAP_CMD_S));
mc_cmd->command = command;
mc_cmd->special_handling = sp_handling;
}
return(mc_cmd);
}
/*
* mc_bld_test_cmd - build the command to test if the given type flies
*
* mc_cmd_bldr's tmp_file argument is NULL as we're not going to
* decode and write each and every MIME segment's data to a temp file
* when no test's going to use the data anyway.
*/
char *
mc_bld_test_cmd(char *controlstring, int type, char *subtype, BODY *body)
{
return(mc_cmd_bldr(controlstring, type, subtype, body, NULL, NULL));
}
/*
* mc_cmd_bldr - construct a command string to execute
*
* If tmp_file is null, then the contents of the given MIME segment
* is not provided. This is useful for building the "test=" string
* as it doesn't operate on the segment's data.
*
* The return value is an alloc'd copy of the command to be executed.
*/
char *
mc_cmd_bldr(char *controlstring, int type, char *subtype,
BODY *body, char *tmp_file, char **err)
{
char *from, *to, *s, *parm;
int prefixed = 0, used_tmp_file = 0;
dprint((8, "- mc_cmd_bldr -\n"));
for(from = controlstring, to = tmp_20k_buf; *from; ++from){
if(prefixed){ /* previous char was % */
prefixed = 0;
switch(*from){
case '%': /* turned \% into this earlier */
if(to-tmp_20k_buf < SIZEOF_20KBUF)
*to++ = '%';
break;
case 's': /* insert tmp_file name in cmd */
if(tmp_file){
used_tmp_file = 1;
sstrncpy(&to, tmp_file, SIZEOF_20KBUF-(to-tmp_20k_buf));
}
else
dprint((1,
"mc_cmd_bldr: %%s in cmd but not supplied!\n"));
break;
case 't': /* insert MIME type/subtype */
/* quote to prevent funny business */
if(to-tmp_20k_buf < SIZEOF_20KBUF)
*to++ = '\'';
sstrncpy(&to, body_type_names(type), SIZEOF_20KBUF-(to-tmp_20k_buf));
if(to-tmp_20k_buf < SIZEOF_20KBUF)
*to++ = '/';
sstrncpy(&to, subtype, SIZEOF_20KBUF-(to-tmp_20k_buf));
if(to-tmp_20k_buf < SIZEOF_20KBUF)
*to++ = '\'';
break;
case '{': /* insert requested MIME param */
if(F_OFF(F_DO_MAILCAP_PARAM_SUBST, ps_global)){
int save;
dprint((2, "mc_cmd_bldr: param subs %s\n",
from ? from : "?"));
if(err){
if((s = strindex(from, '}')) != NULL){
save = *++s;
*s = '\0';
}
snprintf(tmp_20k_buf, SIZEOF_20KBUF,
"Mailcap: see hidden feature %.200s (%%%.200s)",
feature_list_name(F_DO_MAILCAP_PARAM_SUBST), from);
*err = tmp_20k_buf;
if(s)
*s = save;
}
return(NULL);
}
s = strindex(from, '}');
if(!s){
q_status_message1(SM_ORDER, 0, 4,
"Ignoring ill-formed parameter reference in mailcap file: %.200s", from);
break;
}
*s = '\0';
++from; /* from is the part inside the brackets now */
parm = parameter_val(body ? body->parameter : NULL, from);
dprint((9,
"mc_cmd_bldr: parameter %s = %s\n",
from ? from : "?", parm ? parm : "(not found)"));
/*
* Quote parameter values for /bin/sh.
* Put single quotes around the whole thing but every time
* there is an actual single quote put it outside of the
* single quotes with a backslash in front of it. So the
* parameter value fred's car
* turns into 'fred'\''s car'
*/
if(to-tmp_20k_buf < SIZEOF_20KBUF)
*to++ = '\''; /* opening quote */
if(parm){
char *p;
/*
* Copy value, but quote single quotes for /bin/sh
* Backslash quote is ignored inside single quotes so
* have to put those outside of the single quotes.
* (The parm+1000 nonsense is to protect against
* malicious mail trying to overflow our buffer.)
*
* TCH - Change 2/8/1999
* Also quote the ` to prevent execution of arbitrary code
*/
for(p = parm; *p && p < parm+1000; p++){
if((*p == '\'') || (*p == '`')){
if(to-tmp_20k_buf+4 < SIZEOF_20KBUF){
*to++ = '\''; /* closing quote */
*to++ = '\\';
*to++ = *p; /* quoted character */
*to++ = '\''; /* opening quote */
}
}
else if(to-tmp_20k_buf < SIZEOF_20KBUF)
*to++ = *p;
}
fs_give((void **) &parm);
}
if(to-tmp_20k_buf < SIZEOF_20KBUF)
*to++ = '\''; /* closing quote for /bin/sh */
*s = '}'; /* restore */
from = s;
break;
/*
* %n and %F are used by metamail to support otherwise
* unrecognized multipart Content-Types. Pine does
* not use these since we're only dealing with the individual
* parts at this point.
*/
case 'n':
case 'F':
default:
dprint((9,
"Ignoring %s format code in mailcap file: %%%c\n",
(*from == 'n' || *from == 'F') ? "unimplemented"
: "unrecognized",
*from));
break;
}
}
else if(*from == '%') /* next char is special */
prefixed = 1;
else if(to-tmp_20k_buf < SIZEOF_20KBUF) /* regular character, just copy */
*to++ = *from;
}
if(to-tmp_20k_buf < SIZEOF_20KBUF)
*to = '\0';
tmp_20k_buf[SIZEOF_20KBUF-1] = '\0';
/*
* file not specified, redirect to stdin
*/
if(!used_tmp_file && tmp_file)
snprintf(to, SIZEOF_20KBUF-(to-tmp_20k_buf), MC_ADD_TMP, tmp_file);
return(cpystr(tmp_20k_buf));
}
/*
*
*/
MailcapEntry *
mc_new_entry(void)
{
MailcapEntry *mc = (MailcapEntry *) fs_get(sizeof(MailcapEntry));
memset(mc, 0, sizeof(MailcapEntry));
*MailcapData.tail = mc;
MailcapData.tail = &mc->next;
return(mc);
}
/*
* Free a list of mailcap entries
*/
void
mc_free_entry(MailcapEntry **mc)
{
if(mc && *mc){
mc_free_entry(&(*mc)->next);
fs_give((void **) mc);
}
}
void
mailcap_free(void)
{
mail_free_stringlist(&MailcapData.raw);
mc_free_entry(&MailcapData.head);
}
|
435808.c | String Content = "";
Content += "<HTML><HEAD><meta name='viewport' content='width=device-width, initial-scale=1'></meta><title>ESPeensy Control Panel</title>";
Content += "<STYLE>* {font-family:verdana;font-size:14px;border-radius:3px;Margin:3px;Padding:2px;}div {Border:1px solid grey;Margin-Bottom:7px;background-color:#E6E6E6;}";
Content += "h4 {Margin-Top:-2px;Margin-Left:-2px;Margin-Right:-2px;Padding:3px;background-color:#BDBDBD;}div>a{font-family:verdana;font-size:16px;Color:White;}";
Content += "div>a.Mark{background-color:#E6E6E6;color:black}Input,Select,Button{Border:1px solid lightgrey;Height:30px;Width:99%;Margin:0px;}";
Content += "Input:Hover,Select:Hover,Button:Hover,tr:hover{box-shadow: 0 0 0 1px #0080FF inset}table {Margin-Top:8px;width:99%;border-collapse:collapse;}";
Content += "th {text-align:left;height:20px;}td{Padding-right:6px}tr:nth-child(even) {background-color: #D8D8D8;}tr:first-child {box-shadow: 0 0 0 0px #0080FF inset}";
Content += "</STYLE></HEAD><BODY><DIV Style='background-color:#696969;Color:White;border-top: 2px solid blue;'><a Href='/'>Teensy Controls</a>";
Content += "<a Href='wifi'>Wifi Settings</a><a Href='fupload'>File Manager</a><a Href='updatefwm'>Firmware Manager</a></DIV><DIV><H4>Wifi Attacks (Needs ESP8266 Reboot)</H4>";
Content += "<Table><TR><TD><Button>Wifi-Deauth</Button></TD><TD><Button>Wifi-FakeAP</Button></TD></TR></Table></DIV><DIV><H4>Additional Information</H4>";
Content += "<Table><TR><TH>Internal</TH><TH>External</TH></TR><TR><TD Width='50%'><i>IP-Adress: {IP}</i><BR><i>Subnetmask: {SUBNET}</i><BR>";
Content += "<i>DNS-Server: {DNS}</i><BR><i>Gateway: {GATE}</i></TD><TD Width='50%'><i>IP-Adress: {IP}</i><BR><i>API.IPIFY.ORG</i><BR>";
Content += "</TD></TR></Table></DIV><DIV class='div1'><H4>Wifi-APs</H4><table><TH>SSID</TH><TH>ENC</TH><TH>STRN</TH><TH>QUAL</TH><TH>PASS</TH>";
Content += "<TR><TD><a href='Filename'>AP1</a></TD><TD>WEP</TD><TD>15</TD><TD>10</TD><TD Width='20%'><Input Style='Height:22px;'></Input></TD><TD width='15%'><a href='Filename'>Connect</a></TD>";
Content += "</TR><TR><TD><a href='Filename'>AP2</a></TD><TD>WEP</TD><TD>15</TD><TD>10</TD><TD Width='20%'><Input Style='Height:22px;'></Input></TD><TD width='10%'><a href='Filename'>Connect</a></TD>";
Content += "</TR><TR><TD><a href='Filename'>AP3</a></TD><TD>WPA</TD><TD>15</TD><TD>10</TD><TD Width='20%'><Input Style='Height:22px;'></Input></TD><TD width='10%'><a href='Filename'>Connect</a></TD>";
Content += "</TR><TR><TD><a href='Filename'>AP4</a></TD><TD>WPA2</TD><TD>15</TD><TD>10</TD><TD Width='20%'><Input Style='Height:22px;'></Input></TD><TD width='10%'><a href='Filename'>Connect</a></TD>";
Content += "</TR></table></DIV></BODY></HTML>";
|
820089.c | /* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE789_Uncontrolled_Mem_Alloc__malloc_wchar_t_listen_socket_14.c
Label Definition File: CWE789_Uncontrolled_Mem_Alloc__malloc.label.xml
Template File: sources-sinks-14.tmpl.c
*/
/*
* @description
* CWE: 789 Uncontrolled Memory Allocation
* BadSource: listen_socket Read data using a listen socket (server side)
* GoodSource: Small number greater than zero
* Sinks:
* GoodSink: Allocate memory with malloc() and check the size of the memory to be allocated
* BadSink : Allocate memory with malloc(), but incorrectly check the size of the memory to be allocated
* Flow Variant: 14 Control flow: if(globalFive==5) and if(globalFive!=5)
*
* */
#include "std_testcase.h"
#ifndef _WIN32
#include <wchar.h>
#endif
#ifdef _WIN32
#include <winsock2.h>
#include <windows.h>
#include <direct.h>
#pragma comment(lib, "ws2_32") /* include ws2_32.lib when linking */
#define CLOSE_SOCKET closesocket
#else
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#define INVALID_SOCKET -1
#define SOCKET_ERROR -1
#define CLOSE_SOCKET close
#define SOCKET int
#endif
#define TCP_PORT 27015
#define LISTEN_BACKLOG 5
#define CHAR_ARRAY_SIZE (3 * sizeof(data) + 2)
#define HELLO_STRING L"hello"
#ifndef OMITBAD
void CWE789_Uncontrolled_Mem_Alloc__malloc_wchar_t_listen_socket_14_bad()
{
size_t data;
/* Initialize data */
data = 0;
if(globalFive==5)
{
{
#ifdef _WIN32
WSADATA wsaData;
int wsaDataInit = 0;
#endif
int recvResult;
struct sockaddr_in service;
SOCKET listenSocket = INVALID_SOCKET;
SOCKET acceptSocket = INVALID_SOCKET;
char inputBuffer[CHAR_ARRAY_SIZE];
do
{
#ifdef _WIN32
if (WSAStartup(MAKEWORD(2,2), &wsaData) != NO_ERROR)
{
break;
}
wsaDataInit = 1;
#endif
/* POTENTIAL FLAW: Read data using a listen socket */
listenSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (listenSocket == INVALID_SOCKET)
{
break;
}
memset(&service, 0, sizeof(service));
service.sin_family = AF_INET;
service.sin_addr.s_addr = INADDR_ANY;
service.sin_port = htons(TCP_PORT);
if (bind(listenSocket, (struct sockaddr*)&service, sizeof(service)) == SOCKET_ERROR)
{
break;
}
if (listen(listenSocket, LISTEN_BACKLOG) == SOCKET_ERROR)
{
break;
}
acceptSocket = accept(listenSocket, NULL, NULL);
if (acceptSocket == SOCKET_ERROR)
{
break;
}
/* Abort on error or the connection was closed */
recvResult = recv(acceptSocket, inputBuffer, CHAR_ARRAY_SIZE - 1, 0);
if (recvResult == SOCKET_ERROR || recvResult == 0)
{
break;
}
/* NUL-terminate the string */
inputBuffer[recvResult] = '\0';
/* Convert to unsigned int */
data = strtoul(inputBuffer, NULL, 0);
}
while (0);
if (listenSocket != INVALID_SOCKET)
{
CLOSE_SOCKET(listenSocket);
}
if (acceptSocket != INVALID_SOCKET)
{
CLOSE_SOCKET(acceptSocket);
}
#ifdef _WIN32
if (wsaDataInit)
{
WSACleanup();
}
#endif
}
}
if(globalFive==5)
{
{
wchar_t * myString;
/* POTENTIAL FLAW: No MAXIMUM limitation for memory allocation, but ensure data is large enough
* for the wcscpy() function to not cause a buffer overflow */
/* INCIDENTAL FLAW: The source could cause a type overrun in data or in the memory allocation */
if (data > wcslen(HELLO_STRING))
{
myString = (wchar_t *)malloc(data*sizeof(wchar_t));
if (myString == NULL) {exit(-1);}
/* Copy a small string into myString */
wcscpy(myString, HELLO_STRING);
printWLine(myString);
free(myString);
}
else
{
printLine("Input is less than the length of the source string");
}
}
}
}
#endif /* OMITBAD */
#ifndef OMITGOOD
/* goodB2G1() - use badsource and goodsink by changing the second globalFive==5 to globalFive!=5 */
static void goodB2G1()
{
size_t data;
/* Initialize data */
data = 0;
if(globalFive==5)
{
{
#ifdef _WIN32
WSADATA wsaData;
int wsaDataInit = 0;
#endif
int recvResult;
struct sockaddr_in service;
SOCKET listenSocket = INVALID_SOCKET;
SOCKET acceptSocket = INVALID_SOCKET;
char inputBuffer[CHAR_ARRAY_SIZE];
do
{
#ifdef _WIN32
if (WSAStartup(MAKEWORD(2,2), &wsaData) != NO_ERROR)
{
break;
}
wsaDataInit = 1;
#endif
/* POTENTIAL FLAW: Read data using a listen socket */
listenSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (listenSocket == INVALID_SOCKET)
{
break;
}
memset(&service, 0, sizeof(service));
service.sin_family = AF_INET;
service.sin_addr.s_addr = INADDR_ANY;
service.sin_port = htons(TCP_PORT);
if (bind(listenSocket, (struct sockaddr*)&service, sizeof(service)) == SOCKET_ERROR)
{
break;
}
if (listen(listenSocket, LISTEN_BACKLOG) == SOCKET_ERROR)
{
break;
}
acceptSocket = accept(listenSocket, NULL, NULL);
if (acceptSocket == SOCKET_ERROR)
{
break;
}
/* Abort on error or the connection was closed */
recvResult = recv(acceptSocket, inputBuffer, CHAR_ARRAY_SIZE - 1, 0);
if (recvResult == SOCKET_ERROR || recvResult == 0)
{
break;
}
/* NUL-terminate the string */
inputBuffer[recvResult] = '\0';
/* Convert to unsigned int */
data = strtoul(inputBuffer, NULL, 0);
}
while (0);
if (listenSocket != INVALID_SOCKET)
{
CLOSE_SOCKET(listenSocket);
}
if (acceptSocket != INVALID_SOCKET)
{
CLOSE_SOCKET(acceptSocket);
}
#ifdef _WIN32
if (wsaDataInit)
{
WSACleanup();
}
#endif
}
}
if(globalFive!=5)
{
/* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
printLine("Benign, fixed string");
}
else
{
{
wchar_t * myString;
/* FIX: Include a MAXIMUM limitation for memory allocation and a check to ensure data is large enough
* for the wcscpy() function to not cause a buffer overflow */
/* INCIDENTAL FLAW: The source could cause a type overrun in data or in the memory allocation */
if (data > wcslen(HELLO_STRING) && data < 100)
{
myString = (wchar_t *)malloc(data*sizeof(wchar_t));
if (myString == NULL) {exit(-1);}
/* Copy a small string into myString */
wcscpy(myString, HELLO_STRING);
printWLine(myString);
free(myString);
}
else
{
printLine("Input is less than the length of the source string or too large");
}
}
}
}
/* goodB2G2() - use badsource and goodsink by reversing the blocks in the second if */
static void goodB2G2()
{
size_t data;
/* Initialize data */
data = 0;
if(globalFive==5)
{
{
#ifdef _WIN32
WSADATA wsaData;
int wsaDataInit = 0;
#endif
int recvResult;
struct sockaddr_in service;
SOCKET listenSocket = INVALID_SOCKET;
SOCKET acceptSocket = INVALID_SOCKET;
char inputBuffer[CHAR_ARRAY_SIZE];
do
{
#ifdef _WIN32
if (WSAStartup(MAKEWORD(2,2), &wsaData) != NO_ERROR)
{
break;
}
wsaDataInit = 1;
#endif
/* POTENTIAL FLAW: Read data using a listen socket */
listenSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (listenSocket == INVALID_SOCKET)
{
break;
}
memset(&service, 0, sizeof(service));
service.sin_family = AF_INET;
service.sin_addr.s_addr = INADDR_ANY;
service.sin_port = htons(TCP_PORT);
if (bind(listenSocket, (struct sockaddr*)&service, sizeof(service)) == SOCKET_ERROR)
{
break;
}
if (listen(listenSocket, LISTEN_BACKLOG) == SOCKET_ERROR)
{
break;
}
acceptSocket = accept(listenSocket, NULL, NULL);
if (acceptSocket == SOCKET_ERROR)
{
break;
}
/* Abort on error or the connection was closed */
recvResult = recv(acceptSocket, inputBuffer, CHAR_ARRAY_SIZE - 1, 0);
if (recvResult == SOCKET_ERROR || recvResult == 0)
{
break;
}
/* NUL-terminate the string */
inputBuffer[recvResult] = '\0';
/* Convert to unsigned int */
data = strtoul(inputBuffer, NULL, 0);
}
while (0);
if (listenSocket != INVALID_SOCKET)
{
CLOSE_SOCKET(listenSocket);
}
if (acceptSocket != INVALID_SOCKET)
{
CLOSE_SOCKET(acceptSocket);
}
#ifdef _WIN32
if (wsaDataInit)
{
WSACleanup();
}
#endif
}
}
if(globalFive==5)
{
{
wchar_t * myString;
/* FIX: Include a MAXIMUM limitation for memory allocation and a check to ensure data is large enough
* for the wcscpy() function to not cause a buffer overflow */
/* INCIDENTAL FLAW: The source could cause a type overrun in data or in the memory allocation */
if (data > wcslen(HELLO_STRING) && data < 100)
{
myString = (wchar_t *)malloc(data*sizeof(wchar_t));
if (myString == NULL) {exit(-1);}
/* Copy a small string into myString */
wcscpy(myString, HELLO_STRING);
printWLine(myString);
free(myString);
}
else
{
printLine("Input is less than the length of the source string or too large");
}
}
}
}
/* goodG2B1() - use goodsource and badsink by changing the first globalFive==5 to globalFive!=5 */
static void goodG2B1()
{
size_t data;
/* Initialize data */
data = 0;
if(globalFive!=5)
{
/* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
printLine("Benign, fixed string");
}
else
{
/* FIX: Use a relatively small number for memory allocation */
data = 20;
}
if(globalFive==5)
{
{
wchar_t * myString;
/* POTENTIAL FLAW: No MAXIMUM limitation for memory allocation, but ensure data is large enough
* for the wcscpy() function to not cause a buffer overflow */
/* INCIDENTAL FLAW: The source could cause a type overrun in data or in the memory allocation */
if (data > wcslen(HELLO_STRING))
{
myString = (wchar_t *)malloc(data*sizeof(wchar_t));
if (myString == NULL) {exit(-1);}
/* Copy a small string into myString */
wcscpy(myString, HELLO_STRING);
printWLine(myString);
free(myString);
}
else
{
printLine("Input is less than the length of the source string");
}
}
}
}
/* goodG2B2() - use goodsource and badsink by reversing the blocks in the first if */
static void goodG2B2()
{
size_t data;
/* Initialize data */
data = 0;
if(globalFive==5)
{
/* FIX: Use a relatively small number for memory allocation */
data = 20;
}
if(globalFive==5)
{
{
wchar_t * myString;
/* POTENTIAL FLAW: No MAXIMUM limitation for memory allocation, but ensure data is large enough
* for the wcscpy() function to not cause a buffer overflow */
/* INCIDENTAL FLAW: The source could cause a type overrun in data or in the memory allocation */
if (data > wcslen(HELLO_STRING))
{
myString = (wchar_t *)malloc(data*sizeof(wchar_t));
if (myString == NULL) {exit(-1);}
/* Copy a small string into myString */
wcscpy(myString, HELLO_STRING);
printWLine(myString);
free(myString);
}
else
{
printLine("Input is less than the length of the source string");
}
}
}
}
void CWE789_Uncontrolled_Mem_Alloc__malloc_wchar_t_listen_socket_14_good()
{
goodB2G1();
goodB2G2();
goodG2B1();
goodG2B2();
}
#endif /* OMITGOOD */
/* Below is the main(). It is only used when building this testcase on
its own for testing or for building a binary to use in testing binary
analysis tools. It is not used when compiling all the testcases as one
application, which is how source code analysis tools are tested. */
#ifdef INCLUDEMAIN
int main(int argc, char * argv[])
{
/* seed randomness */
srand( (unsigned)time(NULL) );
#ifndef OMITGOOD
printLine("Calling good()...");
CWE789_Uncontrolled_Mem_Alloc__malloc_wchar_t_listen_socket_14_good();
printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
printLine("Calling bad()...");
CWE789_Uncontrolled_Mem_Alloc__malloc_wchar_t_listen_socket_14_bad();
printLine("Finished bad()");
#endif /* OMITBAD */
return 0;
}
#endif
|
849943.c | #include <stdio.h>
#include <conf.h>
#include <kernel.h>
#include <bufpool.h>
char** alloc_large_mem(unsigned int memory_size);
int poolid;
int xmain()
{
char** memArr; /* Array of pointers */
int i, arrSize ;
poolinit();
poolid = mkpool(64,50);
memArr = alloc_large_mem (200);
printf("The Array is:\n");
arrSize = 4; /*(200/64)+1*/
for (i=0; i< arrSize;i++)
printf ("%d ", memArr[i]);
return 0;
}
char** alloc_large_mem(unsigned int memory_size)
{
char** resP;
char** p;
char* buf;
int num_of_buf, i;
*resP = (char*) getbuf(poolid);
num_of_buf = memory_size/64;
if(memory_size%64 != 0) num_of_buf++;
p=resP;
for(i=0; i<num_of_buf; i++){
buf = (char*) getbuf(poolid);
*p = buf; /*resP[i] = buf; */
p++;
}
return resP;
} |
573579.c | /*
* This file is part of the coreboot project.
*
* Copyright (C) 2008-2009 coresystems GmbH
* Copyright (C) 2013-2015 Sage Electronic Engineering, LLC.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; version 2 of
* the License.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
#include <console/console.h>
#include <device/device.h>
#include <device/pci.h>
#include <device/pci_ids.h>
#include <pc80/mc146818rtc.h>
#include <pc80/isa-dma.h>
#include <pc80/i8259.h>
#include <arch/io.h>
#include <arch/ioapic.h>
#include <arch/acpi.h>
#include <cpu/cpu.h>
#include <elog.h>
#include <arch/acpigen.h>
#include <drivers/intel/gma/i915.h>
#include <cpu/x86/smm.h>
#include <cbmem.h>
#include <string.h>
#include "pch.h"
#include "nvs.h"
#define NMI_OFF 0
#define ENABLE_ACPI_MODE_IN_COREBOOT 0
typedef struct southbridge_intel_fsp_i89xx_config config_t;
static void pch_enable_apic(struct device *dev)
{
int i;
u32 reg32;
volatile u32 *ioapic_index = (volatile u32 *)(IO_APIC_ADDR);
volatile u32 *ioapic_data = (volatile u32 *)(IO_APIC_ADDR + 0x10);
/* Enable ACPI I/O and power management.
* Set SCI IRQ to IRQ9
*/
pci_write_config8(dev, ACPI_CNTL, 0x80);
*ioapic_index = 0;
*ioapic_data = (1 << 25);
/* affirm full set of redirection table entries ("write once") */
*ioapic_index = 1;
reg32 = *ioapic_data;
*ioapic_index = 1;
*ioapic_data = reg32;
*ioapic_index = 0;
reg32 = *ioapic_data;
printk(BIOS_DEBUG, "Southbridge APIC ID = %x\n", (reg32 >> 24) & 0x0f);
if (reg32 != (1 << 25))
die("APIC Error\n");
printk(BIOS_SPEW, "Dumping IOAPIC registers\n");
for (i=0; i<3; i++) {
*ioapic_index = i;
printk(BIOS_SPEW, " reg 0x%04x:", i);
reg32 = *ioapic_data;
printk(BIOS_SPEW, " 0x%08x\n", reg32);
}
*ioapic_index = 3; /* Select Boot Configuration register. */
*ioapic_data = 1; /* Use Processor System Bus to deliver interrupts. */
}
static void pch_enable_serial_irqs(struct device *dev)
{
/* Set packet length and toggle silent mode bit for one frame. */
pci_write_config8(dev, SERIRQ_CNTL,
(1 << 7) | (1 << 6) | ((21 - 17) << 2) | (0 << 0));
#if !IS_ENABLED(CONFIG_SERIRQ_CONTINUOUS_MODE)
pci_write_config8(dev, SERIRQ_CNTL,
(1 << 7) | (0 << 6) | ((21 - 17) << 2) | (0 << 0));
#endif
}
/* PIRQ[n]_ROUT[3:0] - PIRQ Routing Control
* 0x00 - 0000 = Reserved
* 0x01 - 0001 = Reserved
* 0x02 - 0010 = Reserved
* 0x03 - 0011 = IRQ3
* 0x04 - 0100 = IRQ4
* 0x05 - 0101 = IRQ5
* 0x06 - 0110 = IRQ6
* 0x07 - 0111 = IRQ7
* 0x08 - 1000 = Reserved
* 0x09 - 1001 = IRQ9
* 0x0A - 1010 = IRQ10
* 0x0B - 1011 = IRQ11
* 0x0C - 1100 = IRQ12
* 0x0D - 1101 = Reserved
* 0x0E - 1110 = IRQ14
* 0x0F - 1111 = IRQ15
* PIRQ[n]_ROUT[7] - PIRQ Routing Control
* 0x80 - The PIRQ is not routed.
*/
static void pch_pirq_init(struct device *dev)
{
struct device *irq_dev;
/* Get the chip configuration */
config_t *config = dev->chip_info;
pci_write_config8(dev, PIRQA_ROUT, config->pirqa_routing);
pci_write_config8(dev, PIRQB_ROUT, config->pirqb_routing);
pci_write_config8(dev, PIRQC_ROUT, config->pirqc_routing);
pci_write_config8(dev, PIRQD_ROUT, config->pirqd_routing);
pci_write_config8(dev, PIRQE_ROUT, config->pirqe_routing);
pci_write_config8(dev, PIRQF_ROUT, config->pirqf_routing);
pci_write_config8(dev, PIRQG_ROUT, config->pirqg_routing);
pci_write_config8(dev, PIRQH_ROUT, config->pirqh_routing);
/* Eric Biederman once said we should let the OS do this.
* I am not so sure anymore he was right.
*/
for (irq_dev = all_devices; irq_dev; irq_dev = irq_dev->next) {
u8 int_pin=0, int_line=0;
if (!irq_dev->enabled || irq_dev->path.type != DEVICE_PATH_PCI)
continue;
int_pin = pci_read_config8(irq_dev, PCI_INTERRUPT_PIN);
switch (int_pin) {
case 1: /* INTA# */ int_line = config->pirqa_routing; break;
case 2: /* INTB# */ int_line = config->pirqb_routing; break;
case 3: /* INTC# */ int_line = config->pirqc_routing; break;
case 4: /* INTD# */ int_line = config->pirqd_routing; break;
}
if (!int_line)
continue;
pci_write_config8(irq_dev, PCI_INTERRUPT_LINE, int_line);
}
}
static void pch_gpi_routing(struct device *dev)
{
/* Get the chip configuration */
config_t *config = dev->chip_info;
u32 reg32 = 0;
/* An array would be much nicer here, or some
* other method of doing this.
*/
reg32 |= (config->gpi0_routing & 0x03) << 0;
reg32 |= (config->gpi1_routing & 0x03) << 2;
reg32 |= (config->gpi2_routing & 0x03) << 4;
reg32 |= (config->gpi3_routing & 0x03) << 6;
reg32 |= (config->gpi4_routing & 0x03) << 8;
reg32 |= (config->gpi5_routing & 0x03) << 10;
reg32 |= (config->gpi6_routing & 0x03) << 12;
reg32 |= (config->gpi7_routing & 0x03) << 14;
reg32 |= (config->gpi8_routing & 0x03) << 16;
reg32 |= (config->gpi9_routing & 0x03) << 18;
reg32 |= (config->gpi10_routing & 0x03) << 20;
reg32 |= (config->gpi11_routing & 0x03) << 22;
reg32 |= (config->gpi12_routing & 0x03) << 24;
reg32 |= (config->gpi13_routing & 0x03) << 26;
reg32 |= (config->gpi14_routing & 0x03) << 28;
reg32 |= (config->gpi15_routing & 0x03) << 30;
pci_write_config32(dev, GPIO_ROUT, reg32);
}
static void pch_power_options(struct device *dev)
{
u8 reg8;
u16 reg16, pmbase;
u32 reg32;
const char *state;
/* Get the chip configuration */
config_t *config = dev->chip_info;
int pwr_on=CONFIG_MAINBOARD_POWER_ON_AFTER_POWER_FAIL;
int nmi_option;
/* Which state do we want to goto after g3 (power restored)?
* 0 == S0 Full On
* 1 == S5 Soft Off
*
* If the option is not existent (Laptops), use Kconfig setting.
*/
get_option(&pwr_on, "power_on_after_fail");
reg16 = pci_read_config16(dev, GEN_PMCON_3);
reg16 &= 0xfffe;
switch (pwr_on) {
case MAINBOARD_POWER_OFF:
reg16 |= 1;
state = "off";
break;
case MAINBOARD_POWER_ON:
reg16 &= ~1;
state = "on";
break;
case MAINBOARD_POWER_KEEP:
reg16 &= ~1;
state = "state keep";
break;
default:
state = "undefined";
}
reg16 &= ~(3 << 4); /* SLP_S4# Assertion Stretch 4s */
reg16 |= (1 << 3); /* SLP_S4# Assertion Stretch Enable */
reg16 &= ~(1 << 10);
reg16 |= (1 << 11); /* SLP_S3# Min Assertion Width 50ms */
reg16 |= (1 << 12); /* Disable SLP stretch after SUS well */
pci_write_config16(dev, GEN_PMCON_3, reg16);
printk(BIOS_INFO, "Set power %s after power failure.\n", state);
/* Set up NMI on errors. */
reg8 = inb(0x61);
reg8 &= 0x0f; /* Higher Nibble must be 0 */
reg8 &= ~(1 << 3); /* IOCHK# NMI Enable */
// reg8 &= ~(1 << 2); /* PCI SERR# Enable */
reg8 |= (1 << 2); /* PCI SERR# Disable for now */
outb(reg8, 0x61);
reg8 = inb(0x70);
nmi_option = NMI_OFF;
get_option(&nmi_option, "nmi");
if (nmi_option) {
printk(BIOS_INFO, "NMI sources enabled.\n");
reg8 &= ~(1 << 7); /* Set NMI. */
} else {
printk(BIOS_INFO, "NMI sources disabled.\n");
reg8 |= (1 << 7); /* Can't mask NMI from PCI-E and NMI_NOW */
}
outb(reg8, 0x70);
/* Enable CPU_SLP# and Intel Speedstep, set SMI# rate down */
reg16 = pci_read_config16(dev, GEN_PMCON_1);
reg16 &= ~(3 << 0); // SMI# rate 1 minute
reg16 &= ~(1 << 10); // Disable BIOS_PCI_EXP_EN for native PME
#if DEBUG_PERIODIC_SMIS
/* Set DEBUG_PERIODIC_SMIS in pch.h to debug using
* periodic SMIs.
*/
reg16 |= (3 << 0); // Periodic SMI every 8s
#endif
pci_write_config16(dev, GEN_PMCON_1, reg16);
// Set the board's GPI routing.
pch_gpi_routing(dev);
pmbase = pci_read_config16(dev, 0x40) & 0xfffe;
outl(config->gpe0_en, pmbase + GPE0_EN);
outw(config->alt_gp_smi_en, pmbase + ALT_GP_SMI_EN);
/* Set up power management block and determine sleep mode */
reg32 = inl(pmbase + 0x04); // PM1_CNT
reg32 &= ~(7 << 10); // SLP_TYP
reg32 |= (1 << 0); // SCI_EN
outl(reg32, pmbase + 0x04);
/* Clear magic status bits to prevent unexpected wake */
reg32 = RCBA32(0x3310);
reg32 |= (1 << 4)|(1 << 5)|(1 << 0);
RCBA32(0x3310) = reg32;
}
static void pch_rtc_init(struct device *dev)
{
u8 reg8;
int rtc_failed;
reg8 = pci_read_config8(dev, GEN_PMCON_3);
rtc_failed = reg8 & RTC_BATTERY_DEAD;
if (rtc_failed) {
reg8 &= ~RTC_BATTERY_DEAD;
pci_write_config8(dev, GEN_PMCON_3, reg8);
#if IS_ENABLED(CONFIG_ELOG)
elog_add_event(ELOG_TYPE_RTC_RESET);
#endif
}
printk(BIOS_DEBUG, "rtc_failed = 0x%x\n", rtc_failed);
cmos_init(rtc_failed);
}
static void enable_hpet(void)
{
u32 reg32;
/* Move HPET to default address 0xfed00000 and enable it */
reg32 = RCBA32(HPTC);
reg32 |= (1 << 7); // HPET Address Enable
reg32 &= ~(3 << 0);
RCBA32(HPTC) = reg32;
}
static void pch_set_acpi_mode(void)
{
if (!acpi_is_wakeup_s3() && CONFIG_HAVE_SMI_HANDLER) {
#if ENABLE_ACPI_MODE_IN_COREBOOT
printk(BIOS_DEBUG, "Enabling ACPI via APMC:\n");
outb(APM_CNT_ACPI_ENABLE, APM_CNT); // Enable ACPI mode
printk(BIOS_DEBUG, "done.\n");
#else
printk(BIOS_DEBUG, "Disabling ACPI via APMC:\n");
outb(APM_CNT_ACPI_DISABLE, APM_CNT); // Disable ACPI mode
printk(BIOS_DEBUG, "done.\n");
#endif
}
}
static void pch_disable_smm_only_flashing(struct device *dev)
{
u8 reg8;
printk(BIOS_SPEW, "Enabling BIOS updates outside of SMM... ");
reg8 = pci_read_config8(dev, 0xdc); /* BIOS_CNTL */
reg8 &= ~(1 << 5);
pci_write_config8(dev, 0xdc, reg8);
}
static void pch_fixups(struct device *dev)
{
u8 gen_pmcon_2;
/* Indicate DRAM init done for MRC S3 to know it can resume */
gen_pmcon_2 = pci_read_config8(dev, GEN_PMCON_2);
gen_pmcon_2 |= (1 << 7);
pci_write_config8(dev, GEN_PMCON_2, gen_pmcon_2);
}
static void pch_decode_init(struct device *dev)
{
config_t *config = dev->chip_info;
printk(BIOS_DEBUG, "pch_decode_init\n");
pci_write_config32(dev, LPC_GEN1_DEC, config->gen1_dec);
pci_write_config32(dev, LPC_GEN2_DEC, config->gen2_dec);
pci_write_config32(dev, LPC_GEN3_DEC, config->gen3_dec);
pci_write_config32(dev, LPC_GEN4_DEC, config->gen4_dec);
}
static void lpc_init(struct device *dev)
{
printk(BIOS_DEBUG, "pch: lpc_init\n");
/* Set the value for PCI command register. */
pci_write_config16(dev, PCI_COMMAND, 0x000f);
/* IO APIC initialization. */
pch_enable_apic(dev);
pch_enable_serial_irqs(dev);
/* Setup the PIRQ. */
pch_pirq_init(dev);
/* Setup power options. */
pch_power_options(dev);
/* Initialize power management */
switch (pch_silicon_type()) {
case PCH_TYPE_CC: /* CaveCreek */
break;
default:
printk(BIOS_ERR, "Unknown Chipset: 0x%04x\n", dev->device);
}
/* Set the state of the GPIO lines. */
//gpio_init(dev);
/* Initialize the real time clock. */
pch_rtc_init(dev);
/* Initialize ISA DMA. */
isa_dma_init();
/* Initialize the High Precision Event Timers, if present. */
enable_hpet();
setup_i8259();
/* The OS should do this? */
/* Interrupt 9 should be level triggered (SCI) */
i8259_configure_irq_trigger(9, 1);
pch_disable_smm_only_flashing(dev);
pch_set_acpi_mode();
pch_fixups(dev);
}
static void pch_lpc_read_resources(struct device *dev)
{
struct resource *res;
config_t *config = dev->chip_info;
u8 io_index = 0;
/* Get the normal PCI resources of this device. */
pci_dev_read_resources(dev);
/* Add an extra subtractive resource for both memory and I/O. */
res = new_resource(dev, IOINDEX_SUBTRACTIVE(io_index++, 0));
res->base = 0;
res->size = 0x1000;
res->flags = IORESOURCE_IO | IORESOURCE_SUBTRACTIVE |
IORESOURCE_ASSIGNED | IORESOURCE_FIXED;
res = new_resource(dev, IOINDEX_SUBTRACTIVE(io_index++, 0));
res->base = 0xff800000;
res->size = 0x00800000; /* 8 MB for flash */
res->flags = IORESOURCE_MEM | IORESOURCE_SUBTRACTIVE |
IORESOURCE_ASSIGNED | IORESOURCE_FIXED;
res = new_resource(dev, 3); /* IOAPIC */
res->base = IO_APIC_ADDR;
res->size = 0x00001000;
res->flags = IORESOURCE_MEM | IORESOURCE_ASSIGNED | IORESOURCE_FIXED;
/* Set PCH IO decode ranges if required.*/
if ((config->gen1_dec & 0xFFFC) > 0x1000) {
res = new_resource(dev, IOINDEX_SUBTRACTIVE(io_index++, 0));
res->base = config->gen1_dec & 0xFFFC;
res->size = (config->gen1_dec >> 16) & 0xFC;
res->flags = IORESOURCE_IO | IORESOURCE_SUBTRACTIVE |
IORESOURCE_ASSIGNED | IORESOURCE_FIXED;
}
if ((config->gen2_dec & 0xFFFC) > 0x1000) {
res = new_resource(dev, IOINDEX_SUBTRACTIVE(io_index++, 0));
res->base = config->gen2_dec & 0xFFFC;
res->size = (config->gen2_dec >> 16) & 0xFC;
res->flags = IORESOURCE_IO | IORESOURCE_SUBTRACTIVE |
IORESOURCE_ASSIGNED | IORESOURCE_FIXED;
}
if ((config->gen3_dec & 0xFFFC) > 0x1000) {
res = new_resource(dev, IOINDEX_SUBTRACTIVE(io_index++, 0));
res->base = config->gen3_dec & 0xFFFC;
res->size = (config->gen3_dec >> 16) & 0xFC;
res->flags = IORESOURCE_IO | IORESOURCE_SUBTRACTIVE |
IORESOURCE_ASSIGNED | IORESOURCE_FIXED;
}
if ((config->gen4_dec & 0xFFFC) > 0x1000) {
res = new_resource(dev, IOINDEX_SUBTRACTIVE(io_index++, 0));
res->base = config->gen4_dec & 0xFFFC;
res->size = (config->gen4_dec >> 16) & 0xFC;
res->flags = IORESOURCE_IO| IORESOURCE_SUBTRACTIVE |
IORESOURCE_ASSIGNED | IORESOURCE_FIXED;
}
}
static void pch_lpc_enable_resources(struct device *dev)
{
pch_decode_init(dev);
return pci_dev_enable_resources(dev);
}
static void pch_lpc_enable(struct device *dev)
{
pch_enable(dev);
}
static void set_subsystem(struct device *dev, unsigned vendor, unsigned device)
{
if (!vendor || !device) {
pci_write_config32(dev, PCI_SUBSYSTEM_VENDOR_ID,
pci_read_config32(dev, PCI_VENDOR_ID));
} else {
pci_write_config32(dev, PCI_SUBSYSTEM_VENDOR_ID,
((device & 0xffff) << 16) | (vendor & 0xffff));
}
}
static void southbridge_inject_dsdt(struct device *dev)
{
global_nvs_t *gnvs = cbmem_add (CBMEM_ID_ACPI_GNVS, sizeof(*gnvs));
if (gnvs) {
const struct i915_gpu_controller_info *gfx = intel_gma_get_controller_info();
memset(gnvs, 0, sizeof(*gnvs));
acpi_create_gnvs(gnvs);
gnvs->ndid = gfx->ndid;
memcpy(gnvs->did, gfx->did, sizeof(gnvs->did));
/* And tell SMI about it */
smm_setup_structures(gnvs, NULL, NULL);
/* Add it to DSDT. */
acpigen_write_scope("\\");
acpigen_write_name_dword("NVSA", (u32) gnvs);
acpigen_pop_len();
}
}
void acpi_fill_fadt(acpi_fadt_t *fadt)
{
struct device *dev = dev_find_slot(0, PCI_DEVFN(0x1f,0));
config_t *chip = dev->chip_info;
u16 pmbase = pci_read_config16(dev, 0x40) & 0xfffe;
int c2_latency;
fadt->model = 1;
fadt->sci_int = 0x9;
fadt->smi_cmd = APM_CNT;
fadt->acpi_enable = APM_CNT_ACPI_ENABLE;
fadt->acpi_disable = APM_CNT_ACPI_DISABLE;
fadt->s4bios_req = 0x0;
fadt->pstate_cnt = 0;
fadt->pm1a_evt_blk = pmbase;
fadt->pm1b_evt_blk = 0x0;
fadt->pm1a_cnt_blk = pmbase + 0x4;
fadt->pm1b_cnt_blk = 0x0;
fadt->pm2_cnt_blk = pmbase + 0x50;
fadt->pm_tmr_blk = pmbase + 0x8;
fadt->gpe0_blk = pmbase + 0x20;
fadt->gpe1_blk = 0;
fadt->pm1_evt_len = 4;
fadt->pm1_cnt_len = 2;
fadt->pm2_cnt_len = 1;
fadt->pm_tmr_len = 4;
fadt->gpe0_blk_len = 16;
fadt->gpe1_blk_len = 0;
fadt->gpe1_base = 0;
fadt->cst_cnt = 0;
c2_latency = chip->c2_latency;
if (!c2_latency) {
c2_latency = 101; /* c2 unsupported */
}
fadt->p_lvl2_lat = c2_latency;
fadt->p_lvl3_lat = 87;
fadt->flush_size = 1024;
fadt->flush_stride = 16;
fadt->duty_offset = 1;
if (chip->p_cnt_throttling_supported) {
fadt->duty_width = 3;
} else {
fadt->duty_width = 0;
}
fadt->day_alrm = 0xd;
fadt->mon_alrm = 0x00;
fadt->century = 0x00;
fadt->iapc_boot_arch = ACPI_FADT_LEGACY_DEVICES | ACPI_FADT_8042;
fadt->flags = ACPI_FADT_WBINVD |
ACPI_FADT_C1_SUPPORTED |
ACPI_FADT_SLEEP_BUTTON |
ACPI_FADT_RESET_REGISTER |
ACPI_FADT_SEALED_CASE |
ACPI_FADT_S4_RTC_WAKE |
ACPI_FADT_PLATFORM_CLOCK;
if (c2_latency < 100) {
fadt->flags |= ACPI_FADT_C2_MP_SUPPORTED;
}
fadt->reset_reg.space_id = 1;
fadt->reset_reg.bit_width = 8;
fadt->reset_reg.bit_offset = 0;
fadt->reset_reg.access_size = ACPI_ACCESS_SIZE_BYTE_ACCESS;
fadt->reset_reg.addrl = 0xcf9;
fadt->reset_reg.addrh = 0;
fadt->reset_value = 6;
fadt->x_pm1a_evt_blk.space_id = 1;
fadt->x_pm1a_evt_blk.bit_width = 32;
fadt->x_pm1a_evt_blk.bit_offset = 0;
fadt->x_pm1a_evt_blk.access_size = ACPI_ACCESS_SIZE_DWORD_ACCESS;
fadt->x_pm1a_evt_blk.addrl = pmbase;
fadt->x_pm1a_evt_blk.addrh = 0x0;
fadt->x_pm1b_evt_blk.space_id = 1;
fadt->x_pm1b_evt_blk.bit_width = 0;
fadt->x_pm1b_evt_blk.bit_offset = 0;
fadt->x_pm1b_evt_blk.access_size = 0;
fadt->x_pm1b_evt_blk.addrl = 0x0;
fadt->x_pm1b_evt_blk.addrh = 0x0;
fadt->x_pm1a_cnt_blk.space_id = 1;
fadt->x_pm1a_cnt_blk.bit_width = 16;
fadt->x_pm1a_cnt_blk.bit_offset = 0;
fadt->x_pm1a_cnt_blk.access_size = ACPI_ACCESS_SIZE_WORD_ACCESS;
fadt->x_pm1a_cnt_blk.addrl = pmbase + 0x4;
fadt->x_pm1a_cnt_blk.addrh = 0x0;
fadt->x_pm1b_cnt_blk.space_id = 1;
fadt->x_pm1b_cnt_blk.bit_width = 0;
fadt->x_pm1b_cnt_blk.bit_offset = 0;
fadt->x_pm1b_cnt_blk.access_size = 0;
fadt->x_pm1b_cnt_blk.addrl = 0x0;
fadt->x_pm1b_cnt_blk.addrh = 0x0;
fadt->x_pm2_cnt_blk.space_id = 1;
fadt->x_pm2_cnt_blk.bit_width = 8;
fadt->x_pm2_cnt_blk.bit_offset = 0;
fadt->x_pm2_cnt_blk.access_size = ACPI_ACCESS_SIZE_BYTE_ACCESS;
fadt->x_pm2_cnt_blk.addrl = pmbase + 0x50;
fadt->x_pm2_cnt_blk.addrh = 0x0;
fadt->x_pm_tmr_blk.space_id = 1;
fadt->x_pm_tmr_blk.bit_width = 32;
fadt->x_pm_tmr_blk.bit_offset = 0;
fadt->x_pm_tmr_blk.access_size = ACPI_ACCESS_SIZE_DWORD_ACCESS;
fadt->x_pm_tmr_blk.addrl = pmbase + 0x8;
fadt->x_pm_tmr_blk.addrh = 0x0;
fadt->x_gpe0_blk.space_id = 1;
fadt->x_gpe0_blk.bit_width = 128;
fadt->x_gpe0_blk.bit_offset = 0;
fadt->x_gpe0_blk.access_size = ACPI_ACCESS_SIZE_DWORD_ACCESS;
fadt->x_gpe0_blk.addrl = pmbase + 0x20;
fadt->x_gpe0_blk.addrh = 0x0;
fadt->x_gpe1_blk.space_id = 1;
fadt->x_gpe1_blk.bit_width = 0;
fadt->x_gpe1_blk.bit_offset = 0;
fadt->x_gpe1_blk.access_size = 0;
fadt->x_gpe1_blk.addrl = 0x0;
fadt->x_gpe1_blk.addrh = 0x0;
}
static struct pci_operations pci_ops = {
.set_subsystem = set_subsystem,
};
static struct device_operations device_ops = {
.read_resources = pch_lpc_read_resources,
.set_resources = pci_dev_set_resources,
.enable_resources = pch_lpc_enable_resources,
.write_acpi_tables = acpi_write_hpet,
.acpi_inject_dsdt_generator = southbridge_inject_dsdt,
.init = lpc_init,
.enable = pch_lpc_enable,
.scan_bus = scan_lpc_bus,
.ops_pci = &pci_ops,
};
/* IDs for LPC device of Intel 89xx Series Chipset */
static const unsigned short pci_device_ids[] = { 0x2310, 0 };
static const struct pci_driver pch_lpc __pci_driver = {
.ops = &device_ops,
.vendor = PCI_VENDOR_ID_INTEL,
.devices = pci_device_ids,
};
|
352541.c | #include <stdio.h>
#include <stdbool.h>
// Kendrick Ledet 2013
/* Insertion Sort: Efficient algorithm for sorting a small # of elements
* Definition:
* Input: A sequence of n elements {A1, A2, ..., An}
* Output: Permutation {A'1, A'2, ..., A'n} of Input such that A'1 <= A'2 <= ... <= A'n
*/
void print_sequence(int*, int);
void insertion_sort(int*, int);
bool test_insertion_sort(int*, int);
int main(int argc, char *argv[])
{
int sequence[] = {3, 3242, 21, 55, 653, 19, 139, 459, 138, 45349, 19, 2, 1};
int sequence_length = sizeof(sequence)/sizeof(sequence[0]);
printf("Sorting %d values in sequence ", sequence_length);
print_sequence(sequence, sequence_length);
insertion_sort(sequence, sequence_length);
printf("Done sorting. Result ");
print_sequence(sequence, sequence_length);
printf("Testing if result sort is valid....");
int pass = test_insertion_sort(sequence, sequence_length);
if (pass)
printf("Yes!\n");
else
printf("No!\n");
return 0;
}
void insertion_sort(int *sequence, int sequence_length)
{
int marker, key_index, key;
for (key_index = 1; key_index < sequence_length; key_index++) { // traverse sequence, start at 2nd index
key = sequence[key_index];
marker = key_index - 1; // set marker at first index left of current key index
while (marker > -1 && sequence[marker] > key) {
sequence[marker+1] = sequence[marker]; // if marker val greater than key, shift right
marker = marker - 1; // count left while current marker val is greater than key
}
sequence[marker+1] = key; // replace key
}
}
void print_sequence(int *sequence, int sequence_length)
{
printf("{");
for (int i = 0; i < sequence_length; i++)
printf("%d, ", sequence[i]);
printf("\b\b}\n");
}
bool test_insertion_sort(int *sequence, int sequence_length)
{
for (int i = 1; i < sequence_length; i++) {
if (sequence[i] < sequence[i-1]) // each value must be greater than the value before it.
return false;
}
return true;
}
|
940936.c | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/auth/credentials.h>
#include <aws/auth/external/cJSON.h>
#include <aws/auth/private/credentials_utils.h>
#include <aws/common/clock.h>
#include <aws/common/date_time.h>
#include <aws/common/string.h>
#include <aws/http/connection.h>
#include <aws/http/connection_manager.h>
#include <aws/http/request_response.h>
#include <aws/http/status_code.h>
#include <aws/io/logging.h>
#include <aws/io/socket.h>
#include <aws/io/tls_channel_handler.h>
#include <aws/io/uri.h>
#if defined(_MSC_VER)
# pragma warning(disable : 4204)
# pragma warning(disable : 4232)
#endif /* _MSC_VER */
/* ecs task role credentials body response is currently ~ 1300 characters + name length */
#define ECS_RESPONSE_SIZE_INITIAL 2048
#define ECS_RESPONSE_SIZE_LIMIT 10000
#define ECS_CONNECT_TIMEOUT_DEFAULT_IN_SECONDS 2
static void s_on_connection_manager_shutdown(void *user_data);
struct aws_credentials_provider_ecs_impl {
struct aws_http_connection_manager *connection_manager;
struct aws_auth_http_system_vtable *function_table;
struct aws_string *host;
struct aws_string *path_and_query;
struct aws_string *auth_token;
};
static struct aws_auth_http_system_vtable s_default_function_table = {
.aws_http_connection_manager_new = aws_http_connection_manager_new,
.aws_http_connection_manager_release = aws_http_connection_manager_release,
.aws_http_connection_manager_acquire_connection = aws_http_connection_manager_acquire_connection,
.aws_http_connection_manager_release_connection = aws_http_connection_manager_release_connection,
.aws_http_connection_make_request = aws_http_connection_make_request,
.aws_http_stream_activate = aws_http_stream_activate,
.aws_http_stream_get_incoming_response_status = aws_http_stream_get_incoming_response_status,
.aws_http_stream_release = aws_http_stream_release,
.aws_http_connection_close = aws_http_connection_close};
/*
* Tracking structure for each outstanding async query to an ecs provider
*/
struct aws_credentials_provider_ecs_user_data {
/* immutable post-creation */
struct aws_allocator *allocator;
struct aws_credentials_provider *ecs_provider;
aws_on_get_credentials_callback_fn *original_callback;
void *original_user_data;
/* mutable */
struct aws_http_connection *connection;
struct aws_http_message *request;
struct aws_byte_buf current_result;
int status_code;
int error_code;
};
static void s_aws_credentials_provider_ecs_user_data_destroy(struct aws_credentials_provider_ecs_user_data *user_data) {
if (user_data == NULL) {
return;
}
struct aws_credentials_provider_ecs_impl *impl = user_data->ecs_provider->impl;
if (user_data->connection) {
impl->function_table->aws_http_connection_manager_release_connection(
impl->connection_manager, user_data->connection);
}
aws_byte_buf_clean_up(&user_data->current_result);
if (user_data->request) {
aws_http_message_destroy(user_data->request);
}
aws_credentials_provider_release(user_data->ecs_provider);
aws_mem_release(user_data->allocator, user_data);
}
static struct aws_credentials_provider_ecs_user_data *s_aws_credentials_provider_ecs_user_data_new(
struct aws_credentials_provider *ecs_provider,
aws_on_get_credentials_callback_fn callback,
void *user_data) {
struct aws_credentials_provider_ecs_user_data *wrapped_user_data =
aws_mem_calloc(ecs_provider->allocator, 1, sizeof(struct aws_credentials_provider_ecs_user_data));
if (wrapped_user_data == NULL) {
goto on_error;
}
wrapped_user_data->allocator = ecs_provider->allocator;
wrapped_user_data->ecs_provider = ecs_provider;
aws_credentials_provider_acquire(ecs_provider);
wrapped_user_data->original_user_data = user_data;
wrapped_user_data->original_callback = callback;
if (aws_byte_buf_init(&wrapped_user_data->current_result, ecs_provider->allocator, ECS_RESPONSE_SIZE_INITIAL)) {
goto on_error;
}
return wrapped_user_data;
on_error:
s_aws_credentials_provider_ecs_user_data_destroy(wrapped_user_data);
return NULL;
}
static void s_aws_credentials_provider_ecs_user_data_reset_response(
struct aws_credentials_provider_ecs_user_data *ecs_user_data) {
ecs_user_data->current_result.len = 0;
ecs_user_data->status_code = 0;
if (ecs_user_data->request) {
aws_http_message_destroy(ecs_user_data->request);
ecs_user_data->request = NULL;
}
}
/*
* In general, the ECS document looks something like:
{
"Code" : "Success",
"LastUpdated" : "2019-05-28T18:03:09Z",
"Type" : "AWS-HMAC",
"AccessKeyId" : "...",
"SecretAccessKey" : "...",
"Token" : "...",
"Expiration" : "2019-05-29T00:21:43Z"
}
*
* No matter the result, this always gets called assuming that esc_user_data is successfully allocated
*/
static void s_ecs_finalize_get_credentials_query(struct aws_credentials_provider_ecs_user_data *ecs_user_data) {
/* Try to build credentials from whatever, if anything, was in the result */
struct aws_credentials *credentials = NULL;
struct aws_parse_credentials_from_json_doc_options parse_options = {
.access_key_id_name = "AccessKeyId",
.secrete_access_key_name = "SecretAccessKey",
.token_name = "Token",
.expiration_name = "Expiration",
.token_required = true,
.expiration_required = true,
};
if (aws_byte_buf_append_null_terminator(&ecs_user_data->current_result) == AWS_OP_SUCCESS) {
credentials = aws_parse_credentials_from_json_document(
ecs_user_data->allocator, (const char *)ecs_user_data->current_result.buffer, &parse_options);
} else {
AWS_LOGF_ERROR(
AWS_LS_AUTH_CREDENTIALS_PROVIDER,
"(id=%p) ECS credentials provider failed to add null terminating char to resulting buffer.",
(void *)ecs_user_data->ecs_provider);
}
if (credentials != NULL) {
AWS_LOGF_INFO(
AWS_LS_AUTH_CREDENTIALS_PROVIDER,
"(id=%p) ECS credentials provider successfully queried instance role credentials",
(void *)ecs_user_data->ecs_provider);
} else {
/* no credentials, make sure we have a valid error to report */
if (ecs_user_data->error_code == AWS_ERROR_SUCCESS) {
ecs_user_data->error_code = aws_last_error();
if (ecs_user_data->error_code == AWS_ERROR_SUCCESS) {
ecs_user_data->error_code = AWS_AUTH_CREDENTIALS_PROVIDER_ECS_SOURCE_FAILURE;
}
}
AWS_LOGF_WARN(
AWS_LS_AUTH_CREDENTIALS_PROVIDER,
"(id=%p) ECS credentials provider failed to query instance role credentials with error %d(%s)",
(void *)ecs_user_data->ecs_provider,
ecs_user_data->error_code,
aws_error_str(ecs_user_data->error_code));
}
/* pass the credentials back */
ecs_user_data->original_callback(credentials, ecs_user_data->error_code, ecs_user_data->original_user_data);
/* clean up */
s_aws_credentials_provider_ecs_user_data_destroy(ecs_user_data);
aws_credentials_release(credentials);
}
static int s_ecs_on_incoming_body_fn(
struct aws_http_stream *stream,
const struct aws_byte_cursor *data,
void *user_data) {
(void)stream;
struct aws_credentials_provider_ecs_user_data *ecs_user_data = user_data;
struct aws_credentials_provider_ecs_impl *impl = ecs_user_data->ecs_provider->impl;
AWS_LOGF_TRACE(
AWS_LS_AUTH_CREDENTIALS_PROVIDER,
"(id=%p) ECS credentials provider received %zu response bytes",
(void *)ecs_user_data->ecs_provider,
data->len);
if (data->len + ecs_user_data->current_result.len > ECS_RESPONSE_SIZE_LIMIT) {
impl->function_table->aws_http_connection_close(ecs_user_data->connection);
AWS_LOGF_ERROR(
AWS_LS_AUTH_CREDENTIALS_PROVIDER,
"(id=%p) ECS credentials provider query response exceeded maximum allowed length",
(void *)ecs_user_data->ecs_provider);
return aws_raise_error(AWS_ERROR_SHORT_BUFFER);
}
if (aws_byte_buf_append_dynamic(&ecs_user_data->current_result, data)) {
impl->function_table->aws_http_connection_close(ecs_user_data->connection);
AWS_LOGF_ERROR(
AWS_LS_AUTH_CREDENTIALS_PROVIDER,
"(id=%p) ECS credentials provider query error appending response",
(void *)ecs_user_data->ecs_provider);
return AWS_OP_ERR;
}
return AWS_OP_SUCCESS;
}
static int s_ecs_on_incoming_headers_fn(
struct aws_http_stream *stream,
enum aws_http_header_block header_block,
const struct aws_http_header *header_array,
size_t num_headers,
void *user_data) {
(void)header_array;
(void)num_headers;
if (header_block != AWS_HTTP_HEADER_BLOCK_MAIN) {
return AWS_OP_SUCCESS;
}
struct aws_credentials_provider_ecs_user_data *ecs_user_data = user_data;
if (header_block == AWS_HTTP_HEADER_BLOCK_MAIN) {
if (ecs_user_data->status_code == 0) {
struct aws_credentials_provider_ecs_impl *impl = ecs_user_data->ecs_provider->impl;
if (impl->function_table->aws_http_stream_get_incoming_response_status(
stream, &ecs_user_data->status_code)) {
AWS_LOGF_ERROR(
AWS_LS_AUTH_CREDENTIALS_PROVIDER,
"(id=%p) ECS credentials provider failed to get http status code",
(void *)ecs_user_data->ecs_provider);
return AWS_OP_ERR;
}
AWS_LOGF_DEBUG(
AWS_LS_AUTH_CREDENTIALS_PROVIDER,
"(id=%p) ECS credentials provider query received http status code %d",
(void *)ecs_user_data->ecs_provider,
ecs_user_data->status_code);
}
}
return AWS_OP_SUCCESS;
}
static void s_ecs_query_task_role_credentials(struct aws_credentials_provider_ecs_user_data *ecs_user_data);
static void s_ecs_on_stream_complete_fn(struct aws_http_stream *stream, int error_code, void *user_data) {
struct aws_credentials_provider_ecs_user_data *ecs_user_data = user_data;
aws_http_message_destroy(ecs_user_data->request);
ecs_user_data->request = NULL;
struct aws_credentials_provider_ecs_impl *impl = ecs_user_data->ecs_provider->impl;
impl->function_table->aws_http_stream_release(stream);
/*
* On anything other than a 200, nullify the response and pretend there was
* an error
*/
if (ecs_user_data->status_code != AWS_HTTP_STATUS_CODE_200_OK || error_code != AWS_OP_SUCCESS) {
ecs_user_data->current_result.len = 0;
if (error_code != AWS_OP_SUCCESS) {
ecs_user_data->error_code = error_code;
} else {
ecs_user_data->error_code = AWS_AUTH_CREDENTIALS_PROVIDER_HTTP_STATUS_FAILURE;
}
}
s_ecs_finalize_get_credentials_query(ecs_user_data);
}
AWS_STATIC_STRING_FROM_LITERAL(s_ecs_accept_header, "Accept");
AWS_STATIC_STRING_FROM_LITERAL(s_ecs_accept_header_value, "application/json");
AWS_STATIC_STRING_FROM_LITERAL(s_ecs_user_agent_header, "User-Agent");
AWS_STATIC_STRING_FROM_LITERAL(s_ecs_user_agent_header_value, "aws-sdk-crt/ecs-credentials-provider");
AWS_STATIC_STRING_FROM_LITERAL(s_ecs_authorization_header, "Authorization");
AWS_STATIC_STRING_FROM_LITERAL(s_ecs_accept_encoding_header, "Accept-Encoding");
AWS_STATIC_STRING_FROM_LITERAL(s_ecs_accept_encoding_header_value, "identity");
AWS_STATIC_STRING_FROM_LITERAL(s_ecs_host_header, "Host");
static int s_make_ecs_http_query(
struct aws_credentials_provider_ecs_user_data *ecs_user_data,
struct aws_byte_cursor *uri) {
AWS_FATAL_ASSERT(ecs_user_data->connection);
struct aws_http_stream *stream = NULL;
struct aws_http_message *request = aws_http_message_new_request(ecs_user_data->allocator);
if (request == NULL) {
return AWS_OP_ERR;
}
struct aws_credentials_provider_ecs_impl *impl = ecs_user_data->ecs_provider->impl;
struct aws_http_header host_header = {
.name = aws_byte_cursor_from_string(s_ecs_host_header),
.value = aws_byte_cursor_from_string(impl->host),
};
if (aws_http_message_add_header(request, host_header)) {
goto on_error;
}
if (impl->auth_token != NULL) {
struct aws_http_header auth_header = {
.name = aws_byte_cursor_from_string(s_ecs_authorization_header),
.value = aws_byte_cursor_from_string(impl->auth_token),
};
if (aws_http_message_add_header(request, auth_header)) {
goto on_error;
}
}
struct aws_http_header accept_header = {
.name = aws_byte_cursor_from_string(s_ecs_accept_header),
.value = aws_byte_cursor_from_string(s_ecs_accept_header_value),
};
if (aws_http_message_add_header(request, accept_header)) {
goto on_error;
}
struct aws_http_header accept_encoding_header = {
.name = aws_byte_cursor_from_string(s_ecs_accept_encoding_header),
.value = aws_byte_cursor_from_string(s_ecs_accept_encoding_header_value),
};
if (aws_http_message_add_header(request, accept_encoding_header)) {
goto on_error;
}
struct aws_http_header user_agent_header = {
.name = aws_byte_cursor_from_string(s_ecs_user_agent_header),
.value = aws_byte_cursor_from_string(s_ecs_user_agent_header_value),
};
if (aws_http_message_add_header(request, user_agent_header)) {
goto on_error;
}
if (aws_http_message_set_request_path(request, *uri)) {
goto on_error;
}
if (aws_http_message_set_request_method(request, aws_byte_cursor_from_c_str("GET"))) {
goto on_error;
}
ecs_user_data->request = request;
struct aws_http_make_request_options request_options = {
.self_size = sizeof(request_options),
.on_response_headers = s_ecs_on_incoming_headers_fn,
.on_response_header_block_done = NULL,
.on_response_body = s_ecs_on_incoming_body_fn,
.on_complete = s_ecs_on_stream_complete_fn,
.user_data = ecs_user_data,
.request = request,
};
stream = impl->function_table->aws_http_connection_make_request(ecs_user_data->connection, &request_options);
if (!stream) {
goto on_error;
}
if (impl->function_table->aws_http_stream_activate(stream)) {
goto on_error;
}
return AWS_OP_SUCCESS;
on_error:
impl->function_table->aws_http_stream_release(stream);
aws_http_message_destroy(request);
ecs_user_data->request = NULL;
return AWS_OP_ERR;
}
static void s_ecs_query_task_role_credentials(struct aws_credentials_provider_ecs_user_data *ecs_user_data) {
AWS_FATAL_ASSERT(ecs_user_data->connection);
struct aws_credentials_provider_ecs_impl *impl = ecs_user_data->ecs_provider->impl;
/* "Clear" the result */
s_aws_credentials_provider_ecs_user_data_reset_response(ecs_user_data);
struct aws_byte_cursor uri_cursor = aws_byte_cursor_from_string(impl->path_and_query);
if (s_make_ecs_http_query(ecs_user_data, &uri_cursor) == AWS_OP_ERR) {
s_ecs_finalize_get_credentials_query(ecs_user_data);
}
}
static void s_ecs_on_acquire_connection(struct aws_http_connection *connection, int error_code, void *user_data) {
struct aws_credentials_provider_ecs_user_data *ecs_user_data = user_data;
if (connection == NULL) {
AWS_LOGF_WARN(
AWS_LS_AUTH_CREDENTIALS_PROVIDER,
"id=%p: ECS provider failed to acquire a connection, error code %d(%s)",
(void *)ecs_user_data->ecs_provider,
error_code,
aws_error_str(error_code));
ecs_user_data->error_code = error_code;
s_ecs_finalize_get_credentials_query(ecs_user_data);
return;
}
ecs_user_data->connection = connection;
s_ecs_query_task_role_credentials(ecs_user_data);
}
static int s_credentials_provider_ecs_get_credentials_async(
struct aws_credentials_provider *provider,
aws_on_get_credentials_callback_fn callback,
void *user_data) {
struct aws_credentials_provider_ecs_impl *impl = provider->impl;
struct aws_credentials_provider_ecs_user_data *wrapped_user_data =
s_aws_credentials_provider_ecs_user_data_new(provider, callback, user_data);
if (wrapped_user_data == NULL) {
goto error;
}
impl->function_table->aws_http_connection_manager_acquire_connection(
impl->connection_manager, s_ecs_on_acquire_connection, wrapped_user_data);
return AWS_OP_SUCCESS;
error:
s_aws_credentials_provider_ecs_user_data_destroy(wrapped_user_data);
return AWS_OP_ERR;
}
static void s_credentials_provider_ecs_destroy(struct aws_credentials_provider *provider) {
struct aws_credentials_provider_ecs_impl *impl = provider->impl;
if (impl == NULL) {
return;
}
aws_string_destroy(impl->path_and_query);
aws_string_destroy(impl->auth_token);
aws_string_destroy(impl->host);
/* aws_http_connection_manager_release will eventually leads to call of s_on_connection_manager_shutdown,
* which will do memory release for provider and impl. So We should be freeing impl
* related memory first, then call aws_http_connection_manager_release.
*/
if (impl->connection_manager) {
impl->function_table->aws_http_connection_manager_release(impl->connection_manager);
} else {
/* If provider setup failed halfway through, connection_manager might not exist.
* In this case invoke shutdown completion callback directly to finish cleanup */
s_on_connection_manager_shutdown(provider);
}
/* freeing the provider takes place in the shutdown callback below */
}
static struct aws_credentials_provider_vtable s_aws_credentials_provider_ecs_vtable = {
.get_credentials = s_credentials_provider_ecs_get_credentials_async,
.destroy = s_credentials_provider_ecs_destroy,
};
static void s_on_connection_manager_shutdown(void *user_data) {
struct aws_credentials_provider *provider = user_data;
aws_credentials_provider_invoke_shutdown_callback(provider);
aws_mem_release(provider->allocator, provider);
}
struct aws_credentials_provider *aws_credentials_provider_new_ecs(
struct aws_allocator *allocator,
const struct aws_credentials_provider_ecs_options *options) {
struct aws_credentials_provider *provider = NULL;
struct aws_credentials_provider_ecs_impl *impl = NULL;
aws_mem_acquire_many(
allocator,
2,
&provider,
sizeof(struct aws_credentials_provider),
&impl,
sizeof(struct aws_credentials_provider_ecs_impl));
if (!provider) {
return NULL;
}
AWS_ZERO_STRUCT(*provider);
AWS_ZERO_STRUCT(*impl);
aws_credentials_provider_init_base(provider, allocator, &s_aws_credentials_provider_ecs_vtable, impl);
struct aws_tls_connection_options tls_connection_options;
AWS_ZERO_STRUCT(tls_connection_options);
if (options->tls_ctx) {
aws_tls_connection_options_init_from_ctx(&tls_connection_options, options->tls_ctx);
struct aws_byte_cursor host = options->host;
if (aws_tls_connection_options_set_server_name(&tls_connection_options, allocator, &host)) {
AWS_LOGF_ERROR(
AWS_LS_AUTH_CREDENTIALS_PROVIDER,
"(id=%p): failed to create a tls connection options with error %s",
(void *)provider,
aws_error_debug_str(aws_last_error()));
goto on_error;
}
}
struct aws_socket_options socket_options;
AWS_ZERO_STRUCT(socket_options);
socket_options.type = AWS_SOCKET_STREAM;
socket_options.domain = AWS_SOCKET_IPV4;
socket_options.connect_timeout_ms = (uint32_t)aws_timestamp_convert(
ECS_CONNECT_TIMEOUT_DEFAULT_IN_SECONDS, AWS_TIMESTAMP_SECS, AWS_TIMESTAMP_MILLIS, NULL);
struct aws_http_connection_manager_options manager_options;
AWS_ZERO_STRUCT(manager_options);
manager_options.bootstrap = options->bootstrap;
manager_options.initial_window_size = ECS_RESPONSE_SIZE_LIMIT;
manager_options.socket_options = &socket_options;
manager_options.host = options->host;
if (options->port == 0) {
manager_options.port = options->tls_ctx ? 443 : 80;
} else {
manager_options.port = options->port;
}
manager_options.max_connections = 2;
manager_options.shutdown_complete_callback = s_on_connection_manager_shutdown;
manager_options.shutdown_complete_user_data = provider;
manager_options.tls_connection_options = options->tls_ctx ? &tls_connection_options : NULL;
impl->function_table = options->function_table;
if (impl->function_table == NULL) {
impl->function_table = &s_default_function_table;
}
impl->connection_manager = impl->function_table->aws_http_connection_manager_new(allocator, &manager_options);
if (impl->connection_manager == NULL) {
goto on_error;
}
if (options->auth_token.len != 0) {
impl->auth_token = aws_string_new_from_cursor(allocator, &options->auth_token);
if (impl->auth_token == NULL) {
goto on_error;
}
}
impl->path_and_query = aws_string_new_from_cursor(allocator, &options->path_and_query);
if (impl->path_and_query == NULL) {
goto on_error;
}
impl->host = aws_string_new_from_cursor(allocator, &options->host);
if (impl->host == NULL) {
goto on_error;
}
provider->shutdown_options = options->shutdown_options;
aws_tls_connection_options_clean_up(&tls_connection_options);
return provider;
on_error:
aws_tls_connection_options_clean_up(&tls_connection_options);
aws_credentials_provider_destroy(provider);
return NULL;
}
|
375207.c | #include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include "../linear.h"
#include "mex.h"
#include "linear_model_matlab.h"
#ifdef MX_API_VER
#if MX_API_VER < 0x07030000
typedef int mwIndex;
#endif
#endif
#define CMD_LEN 2048
#define Malloc(type,n) (type *)malloc((n)*sizeof(type))
#define INF HUGE_VAL
void print_null(const char *s) {}
void print_string_matlab(const char *s) {mexPrintf(s);}
void exit_with_help()
{
mexPrintf(
"Usage: model = train_liblinear_weights(weight_vector, training_label_vector, training_instance_matrix, 'liblinear_options', 'col');\n"
"liblinear_options:\n"
"-s type : set type of solver (default 1)\n"
" 0 -- L2-regularized logistic regression (primal)\n"
" 1 -- L2-regularized L2-loss support vector classification (dual)\n"
" 2 -- L2-regularized L2-loss support vector classification (primal)\n"
" 3 -- L2-regularized L1-loss support vector classification (dual)\n"
" 4 -- multi-class support vector classification by Crammer and Singer\n"
" 5 -- L1-regularized L2-loss support vector classification\n"
" 6 -- L1-regularized logistic regression\n"
" 7 -- L2-regularized logistic regression (dual)\n"
" 11 -- L2-regularized L2-loss epsilon support vector regression (primal)\n"
" 12 -- L2-regularized L2-loss epsilon support vector regression (dual)\n"
" 13 -- L2-regularized L1-loss epsilon support vector regression (dual)\n"
"-c cost : set the parameter C (default 1)\n"
"-p epsilon : set the epsilon in loss function of epsilon-SVR (default 0.1)\n"
"-e epsilon : set tolerance of termination criterion\n"
" -s 0 and 2\n"
" |f'(w)|_2 <= eps*min(pos,neg)/l*|f'(w0)|_2,\n"
" where f is the primal function and pos/neg are # of\n"
" positive/negative data (default 0.01)\n"
" -s 11\n"
" |f'(w)|_2 <= eps*|f'(w0)|_2 (default 0.001)\n"
" -s 1, 3, 4 and 7\n"
" Dual maximal violation <= eps; similar to libsvm (default 0.1)\n"
" -s 5 and 6\n"
" |f'(w)|_1 <= eps*min(pos,neg)/l*|f'(w0)|_1,\n"
" where f is the primal function (default 0.01)\n"
" -s 12 and 13\n"
" |f'(alpha)|_1 <= eps |f'(alpha0)|,\n"
" where f is the dual function (default 0.1)\n"
"-B bias : if bias >= 0, instance x becomes [x; bias]; if < 0, no bias term added (default -1)\n"
"-wi weight: weights adjust the parameter C of different classes (see README for details)\n"
"-v n: n-fold cross validation mode\n"
"-q : quiet mode (no outputs)\n"
"col:\n"
" if 'col' is setted, training_instance_matrix is parsed in column format, otherwise is in row format\n"
);
}
// liblinear arguments
struct parameter param; // set by parse_command_line
struct problem prob; // set by read_problem
struct model *model_;
struct feature_node *x_space;
int cross_validation_flag;
int col_format_flag;
int nr_fold;
double bias;
double do_cross_validation()
{
int i;
int total_correct = 0;
double total_error = 0;
double sumv = 0, sumy = 0, sumvv = 0, sumyy = 0, sumvy = 0;
double *target = Malloc(double, prob.l);
double retval = 0.0;
cross_validation(&prob,¶m,nr_fold,target);
if(param.solver_type == L2R_L2LOSS_SVR ||
param.solver_type == L2R_L1LOSS_SVR_DUAL ||
param.solver_type == L2R_L2LOSS_SVR_DUAL)
{
for(i=0;i<prob.l;i++)
{
double y = prob.y[i];
double v = target[i];
total_error += (v-y)*(v-y);
sumv += v;
sumy += y;
sumvv += v*v;
sumyy += y*y;
sumvy += v*y;
}
printf("Cross Validation Mean squared error = %g\n",total_error/prob.l);
printf("Cross Validation Squared correlation coefficient = %g\n",
((prob.l*sumvy-sumv*sumy)*(prob.l*sumvy-sumv*sumy))/
((prob.l*sumvv-sumv*sumv)*(prob.l*sumyy-sumy*sumy))
);
retval = total_error/prob.l;
}
else
{
for(i=0;i<prob.l;i++)
if(target[i] == prob.y[i])
++total_correct;
printf("Cross Validation Accuracy = %g%%\n",100.0*total_correct/prob.l);
retval = 100.0*total_correct/prob.l;
}
free(target);
return retval;
}
// nrhs should be 4
int parse_command_line(int nrhs, const mxArray *prhs[], char *model_file_name)
{
int i, argc = 1;
char cmd[CMD_LEN];
char *argv[CMD_LEN/2];
void (*print_func)(const char *) = print_string_matlab; // default printing to matlab display
// default values
param.solver_type = L2R_L2LOSS_SVC_DUAL;
param.C = 1;
param.eps = INF; // see setting below
param.p = 0.1;
param.nr_weight = 0;
param.weight_label = NULL;
param.weight = NULL;
cross_validation_flag = 0;
col_format_flag = 0;
bias = -1;
if(nrhs <= 2)
return 1;
if(nrhs == 5)
{
mxGetString(prhs[4], cmd, mxGetN(prhs[4])+1);
if(strcmp(cmd, "col") == 0)
col_format_flag = 1;
}
// put options in argv[]
if(nrhs > 3)
{
mxGetString(prhs[3], cmd, mxGetN(prhs[3]) + 1);
if((argv[argc] = strtok(cmd, " ")) != NULL)
while((argv[++argc] = strtok(NULL, " ")) != NULL)
;
}
// parse options
for(i=1;i<argc;i++)
{
if(argv[i][0] != '-') break;
++i;
if(i>=argc && argv[i-1][1] != 'q') // since option -q has no parameter
return 1;
switch(argv[i-1][1])
{
case 's':
param.solver_type = atoi(argv[i]);
break;
case 'c':
param.C = atof(argv[i]);
break;
case 'p':
param.p = atof(argv[i]);
break;
case 'e':
param.eps = atof(argv[i]);
break;
case 'B':
bias = atof(argv[i]);
break;
case 'v':
cross_validation_flag = 1;
nr_fold = atoi(argv[i]);
if(nr_fold < 2)
{
mexPrintf("n-fold cross validation: n must >= 2\n");
return 1;
}
break;
case 'w':
++param.nr_weight;
param.weight_label = (int *) realloc(param.weight_label,sizeof(int)*param.nr_weight);
param.weight = (double *) realloc(param.weight,sizeof(double)*param.nr_weight);
param.weight_label[param.nr_weight-1] = atoi(&argv[i-1][2]);
param.weight[param.nr_weight-1] = atof(argv[i]);
break;
case 'q':
print_func = &print_null;
i--;
break;
default:
mexPrintf("unknown option\n");
return 1;
}
}
set_print_string_function(print_func);
if(param.eps == INF)
{
switch(param.solver_type)
{
case L2R_LR:
case L2R_L2LOSS_SVC:
param.eps = 0.01;
break;
case L2R_L2LOSS_SVR:
param.eps = 0.001;
break;
case L2R_L2LOSS_SVC_DUAL:
case L2R_L1LOSS_SVC_DUAL:
case MCSVM_CS:
case L2R_LR_DUAL:
param.eps = 0.1;
break;
case L1R_L2LOSS_SVC:
case L1R_LR:
param.eps = 0.01;
break;
case L2R_L1LOSS_SVR_DUAL:
case L2R_L2LOSS_SVR_DUAL:
param.eps = 0.1;
break;
}
}
return 0;
}
static void fake_answer(mxArray *plhs[])
{
plhs[0] = mxCreateDoubleMatrix(0, 0, mxREAL);
}
int read_problem_sparse(const mxArray *weight_vec, const mxArray *label_vec, const mxArray *instance_mat)
{
int i, j, k, low, high;
mwIndex *ir, *jc;
int elements, max_index, num_samples, label_vector_row_num, weight_vector_row_num;
double *samples, *labels, *weights;
mxArray *instance_mat_col; // instance sparse matrix in column format
prob.x = NULL;
prob.y = NULL;
prob.W = NULL;
x_space = NULL;
if(col_format_flag)
instance_mat_col = (mxArray *)instance_mat;
else
{
// transpose instance matrix
mxArray *prhs[1], *plhs[1];
prhs[0] = mxDuplicateArray(instance_mat);
if(mexCallMATLAB(1, plhs, 1, prhs, "transpose"))
{
mexPrintf("Error: cannot transpose training instance matrix\n");
return -1;
}
instance_mat_col = plhs[0];
mxDestroyArray(prhs[0]);
}
// the number of instance
prob.l = (int) mxGetN(instance_mat_col);
weight_vector_row_num = (int) mxGetM(weight_vec);
label_vector_row_num = (int) mxGetM(label_vec);
if(weight_vector_row_num == 0)
mexPrintf("Warning: treat each instance with weight 1.0\n");
else if(weight_vector_row_num!=prob.l)
{
mexPrintf("Length of weight vector does not match # of instances.\n");
return -1;
}
if(label_vector_row_num!=prob.l)
{
mexPrintf("Length of label vector does not match # of instances.\n");
return -1;
}
// each column is one instance
weights = mxGetPr(weight_vec);
labels = mxGetPr(label_vec);
samples = mxGetPr(instance_mat_col);
ir = mxGetIr(instance_mat_col);
jc = mxGetJc(instance_mat_col);
num_samples = (int) mxGetNzmax(instance_mat_col);
elements = num_samples + prob.l*2;
max_index = (int) mxGetM(instance_mat_col);
prob.y = Malloc(double, prob.l);
prob.W = Malloc(double,prob.l);
prob.x = Malloc(struct feature_node*, prob.l);
x_space = Malloc(struct feature_node, elements);
prob.bias=bias;
j = 0;
for(i=0;i<prob.l;i++)
{
prob.x[i] = &x_space[j];
prob.y[i] = labels[i];
prob.W[i] = 1;
if(weight_vector_row_num == prob.l)
prob.W[i] *= (double) weights[i];
low = (int) jc[i], high = (int) jc[i+1];
for(k=low;k<high;k++)
{
x_space[j].index = (int) ir[k]+1;
x_space[j].value = samples[k];
j++;
}
if(prob.bias>=0)
{
x_space[j].index = max_index+1;
x_space[j].value = prob.bias;
j++;
}
x_space[j++].index = -1;
}
if(prob.bias>=0)
prob.n = max_index+1;
else
prob.n = max_index;
return 0;
}
// Interface function of matlab
// now assume prhs[0]: label prhs[1]: features
void mexFunction( int nlhs, mxArray *plhs[],
int nrhs, const mxArray *prhs[] )
{
const char *error_msg;
// fix random seed to have same results for each run
// (for cross validation)
srand(1);
// Transform the input Matrix to libsvm format
if(nrhs > 2 && nrhs < 6)
{
int err=0;
if(!mxIsDouble(prhs[0]) || !mxIsDouble(prhs[1]) || !mxIsDouble(prhs[2])) {
mexPrintf("Error: weight vector, label vector and instance matrix must be double\n");
fake_answer(plhs);
return;
}
if(parse_command_line(nrhs, prhs, NULL))
{
exit_with_help();
destroy_param(¶m);
fake_answer(plhs);
return;
}
if(mxIsSparse(prhs[2]))
err = read_problem_sparse(prhs[0], prhs[1], prhs[2]);
else
{
mexPrintf("Training_instance_matrix must be sparse; "
"use sparse(Training_instance_matrix) first\n");
destroy_param(¶m);
fake_answer(plhs);
return;
}
// train's original code
error_msg = check_parameter(&prob, ¶m);
if(err || error_msg)
{
if (error_msg != NULL)
mexPrintf("Error: %s\n", error_msg);
destroy_param(¶m);
free(prob.y);
free(prob.x);
free(x_space);
fake_answer(plhs);
return;
}
if(cross_validation_flag)
{
double *ptr;
plhs[0] = mxCreateDoubleMatrix(1, 1, mxREAL);
ptr = mxGetPr(plhs[0]);
ptr[0] = do_cross_validation();
}
else
{
const char *error_msg;
model_ = train(&prob, ¶m);
error_msg = model_to_matlab_structure(plhs, model_);
if(error_msg)
mexPrintf("Error: can't convert libsvm model to matrix structure: %s\n", error_msg);
free_and_destroy_model(&model_);
}
destroy_param(¶m);
free(prob.y);
free(prob.x);
free(prob.W);
free(x_space);
}
else
{
exit_with_help();
fake_answer(plhs);
return;
}
}
|
135055.c | #include "ex.h"
#include "ex.h_ex_prims"
/* Reader */
// FIXME: make this thread-local when pthreads are supported. (like task.c)
static ex *thread_local_ex = NULL;
static _ ob = NIL;
static port *p = NULL;
#undef EX
#undef CONS
#define EX thread_local_ex
#define YYSTYPE object
// #define YY_DEBUG
#define SQUARE(x) x
#define CONS(car,cdr) EX->make_pair(EX, car, cdr)
#define NUMBER integer_to_object
// FIXME: this is in-band data!
#define JUNK(str) CONS(SYMBOL("__parse-junk__"), STRING(str))
#define QUOTE(ob) CONS(SYMBOL("quote"), CONS(ob, NIL))
#define UNQUOTE(ob) CONS(SYMBOL("unquote"), CONS(ob, NIL))
#define UNQUOTE_SPLICING(ob) CONS(SYMBOL("unquote-splicing"), CONS(ob, NIL))
#define QUASIQUOTE(ob) CONS(SYMBOL("quasiquote"), CONS(ob, NIL))
#define INTEGER(x) NUMBER(atoi(x))
// #define CHAR(c) STRING(c)
#define YY_INPUT(buf, result, max_size) \
{ \
int yyc= port_getc(p); \
result= (EOF == yyc) ? 0 : (*(buf)= yyc, 1); \
}
static inline void* _realloc(void *mem, size_t size) {
fprintf(stderr, "realloc %p %d\n", mem, (int)size);
return realloc(mem, size);
}
#include "sexp.h_leg"
_ _ex_read(ex *ex, port *input_port) {
p = input_port;
EX = ex;
ob = EOF_OBJECT;
yyparse();
// if (FALSE == ob) ERROR("parse", FALSE);
pair *_p;
symbol *_s;
if ((_p = object_to_pair(ob)) &&
(_s = object_to_symbol(_p->car, ex)) &&
!(strcmp("__parse-junk__", _s->name))) {
ERROR("eof", _p->cdr);
}
return ob;
}
|
112713.c | /*
* rscprint.c: A short test program to dump the contents of a rsc file.
*/
#include <stdio.h>
#include <stdlib.h>
#include "rscload.h"
static int num;
/***************************************************************************/
void Usage(void)
{
printf("Usage: rscprint <filename> ...\n");
exit(1);
}
/***************************************************************************/
/*
* test_callback: Just print out rscs.
*/
bool test_callback(char *filename, int rsc, char *name)
{
printf("rsc # = %d, string = %s\n", rsc, name);
num++;
return true;
}
/***************************************************************************/
int main(int argc, char **argv)
{
int i;
if (argc < 2)
Usage();
num = 0;
for (i=1; i < argc; i++)
{
printf("*** File %s\n", argv[i]);
if (!RscFileLoad(argv[i], test_callback))
printf("Failure reading rsc file!\n");
}
printf("Total: %d resources\n", num);
}
|
273264.c | /*
* Multi8 cas generator
*
* $Id: multi8.c,v 1.6 2016-06-26 00:46:55 aralbrec Exp $
*/
#include "appmake.h"
static char *binname = NULL;
static char *crtfile = NULL;
static char *outfile = NULL;
static int origin = -1;
static char help = 0;
/* Options that are available for this module */
option_t multi8_options[] = {
{ 'h', "help", "Display this help", OPT_BOOL, &help},
{ 'b', "binfile", "Linked binary file", OPT_STR, &binname },
{ 'c', "crt0file", "crt0 file used in linking", OPT_STR, &crtfile },
{ 'o', "output", "Name of output file", OPT_STR, &outfile },
{ 0 , "org", "Origin of the binary", OPT_INT, &origin },
{ 0 , NULL, NULL, OPT_NONE, NULL }
};
static void write_block(FILE *fpout, FILE *fpin, int pos, int len);
int multi8_exec(char *target)
{
char filename[FILENAME_MAX+1];
FILE *fpin, *fpout;
FILE *bootstrap_fp = NULL;
int bootlen;
long pos;
int len;
int bootstrap = 0;
if ( help )
return -1;
if ( binname == NULL || ( crtfile == NULL && origin == -1 ) ) {
return -1;
}
if ( outfile == NULL ) {
strcpy(filename,binname);
suffix_change(filename,".cas");
} else {
strcpy(filename,outfile);
}
if ( origin != -1 ) {
pos = origin;
} else {
if ( (pos = get_org_addr(crtfile)) == -1 ) {
exit_log(1,"Could not find parameter ZORG (not z88dk compiled?)\n");
}
}
if (parameter_search(crtfile, ".map", "__multi8_bootstrap_built") > 0) {
bootstrap = 1;
}
if ( (fpin=fopen_bin(binname, crtfile) ) == NULL ) {
exit_log(1,"Can't open input file %s\n",binname);
}
/* Determine size of input file */
if ( fseek(fpin,0,SEEK_END) ) {
exit_log(1,"Couldn't determine size of file\n");
fclose(fpin);
}
len=ftell(fpin);
fseek(fpin,0L,SEEK_SET);
if ( (fpout=fopen(filename,"wb") ) == NULL ) {
exit_log(1,"Can't open output file\n");
}
if ( bootstrap ) {
char bootname[FILENAME_MAX+1];
strcpy(bootname, binname);
suffix_change(bootname, "_BOOTSTRAP.bin");
if ( (bootstrap_fp=fopen_bin(bootname, crtfile) ) == NULL ) {
exit_log(1,"Can't open bootstrap file %s\n",bootname);
}
if ( fseek(bootstrap_fp,0,SEEK_END) ) {
fclose(bootstrap_fp);
exit_log(1,"Couldn't determine size of bootstrap file\n");
}
bootlen = ftell(bootstrap_fp);
fseek(bootstrap_fp,0L,SEEK_SET);
}
// Write the bootstrap if we need to
if ( bootstrap_fp != NULL ) {
write_block(fpout, bootstrap_fp, 0xc000, bootlen);
fclose(bootstrap_fp);
}
write_block(fpout, fpin, pos, len);
fclose(fpin);
fclose(fpout);
return 0;
}
static void write_block(FILE *fpout, FILE *fpin, int pos, int len)
{
int cksum = 0;
int i,c;
writebyte(0x3a, fpout);
writebyte(pos / 256, fpout);
writebyte(pos % 256, fpout);
writebyte((-((pos / 256) + (pos % 256))) & 0xff, fpout);
for (i=0; i<(len / 255) * 255;i++) {
if (((i%255)==0)&&(i!=len)) {
if ( i != 0 ) {
writebyte(-cksum,fpout);
}
writebyte(0x3a,fpout);
writebyte(0xff,fpout);
cksum = 255;
}
c=getc(fpin);
cksum += c;
writebyte(c,fpout);
}
if ( i ) {
writebyte(-cksum,fpout);
}
if ( len != i ) {
writebyte(0x3a,fpout);
writebyte(len - i,fpout);
cksum = len - i;
for ( ; i < len ; i++ ) {
c=getc(fpin);
writebyte(c,fpout);
cksum += c;
}
writebyte(-cksum,fpout);
}
writebyte(0x3a,fpout);
writebyte(0x00,fpout);
writebyte(0x00,fpout);
}
|
846955.c | #include <task.h>
typedef struct TaskContext {
int value;
} TaskContext;
void MyTask(ecs_iter_t *it) {
(void)it; // Unused
printf("Task executed every second\n");
}
void My2ndTask(ecs_iter_t *it) {
(void)it; // Unused
printf("Task executed every 2 seconds\n");
}
void My3rdTask(ecs_iter_t *it) {
ECS_COLUMN(it, TaskContext, ctx, 1);
printf("Task with context: %d\n", ctx->value);
}
int main(int argc, char *argv[]) {
ecs_world_t *world = ecs_init_w_args(argc, argv);
// Tasks are systems that are not matched with any entities.
ECS_COMPONENT(world, TaskContext);
// Basic task
ECS_SYSTEM(world, MyTask, EcsOnUpdate, 0);
// Task that is executed every 2 seconds
ECS_SYSTEM(world, My2ndTask, EcsOnUpdate, 0);
ecs_set_interval(world, My2ndTask, 2.0);
// It is possible to add components to a task, just like regular systems
ECS_SYSTEM(world, My3rdTask, EcsOnUpdate, SYSTEM:TaskContext);
ecs_set(world, My3rdTask, TaskContext, {10});
/* Set target FPS for main loop */
ecs_set_target_fps(world, 1);
printf("Application task is running, press CTRL-C to exit...\n");
/* Run systems */
while ( ecs_progress(world, 0));
/* Cleanup */
return ecs_fini(world);
}
|
254522.c | /*
* ESP hardware accelerated SHA1/256/512 implementation
* based on mbedTLS FIPS-197 compliant version.
*
* Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
* Additions Copyright (C) 2016-2020, Espressif Systems (Shanghai) PTE Ltd
* SPDX-License-Identifier: Apache-2.0
*
* 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.
*
*/
/*
* The SHA-1 standard was published by NIST in 1993.
*
* http://www.itl.nist.gov/fipspubs/fip180-1.htm
*/
#include <string.h>
#include <stdio.h>
#include <sys/lock.h>
#include "esp_log.h"
#include "esp_crypto_lock.h"
#include "esp_attr.h"
#include "soc/lldesc.h"
#include "soc/cache_memory.h"
#include "soc/periph_defs.h"
#include "freertos/FreeRTOS.h"
#include "freertos/semphr.h"
#include "esp_private/periph_ctrl.h"
#include "sys/param.h"
#include "sha/sha_dma.h"
#include "hal/sha_hal.h"
#include "soc/soc_caps.h"
#include "esp_sha_dma_priv.h"
#if CONFIG_IDF_TARGET_ESP32S2
#include "esp32s2/rom/cache.h"
#elif CONFIG_IDF_TARGET_ESP32S3
#include "esp32s3/rom/cache.h"
#elif CONFIG_IDF_TARGET_ESP32C3
#include "esp32s3/rom/cache.h"
#elif CONFIG_IDF_TARGET_ESP32H2
#include "esp32h2/rom/cache.h"
#elif CONFIG_IDF_TARGET_ESP32C2
#include "esp32c2/rom/cache.h"
#endif
#if SOC_SHA_GDMA
#define SHA_LOCK() esp_crypto_sha_aes_lock_acquire()
#define SHA_RELEASE() esp_crypto_sha_aes_lock_release()
#elif SOC_SHA_CRYPTO_DMA
#define SHA_LOCK() esp_crypto_dma_lock_acquire()
#define SHA_RELEASE() esp_crypto_dma_lock_release()
#endif
const static char *TAG = "esp-sha";
/* These are static due to:
* * Must be in DMA capable memory, so stack is not a safe place to put them
* * To avoid having to malloc/free them for every DMA operation
*/
static DRAM_ATTR lldesc_t s_dma_descr_input;
static DRAM_ATTR lldesc_t s_dma_descr_buf;
void esp_sha_write_digest_state(esp_sha_type sha_type, void *digest_state)
{
sha_hal_write_digest(sha_type, digest_state);
}
void esp_sha_read_digest_state(esp_sha_type sha_type, void *digest_state)
{
sha_hal_read_digest(sha_type, digest_state);
}
/* Return block size (in bytes) for a given SHA type */
inline static size_t block_length(esp_sha_type type)
{
switch (type) {
case SHA1:
case SHA2_224:
case SHA2_256:
return 64;
#if SOC_SHA_SUPPORT_SHA384
case SHA2_384:
#endif
#if SOC_SHA_SUPPORT_SHA512
case SHA2_512:
#endif
#if SOC_SHA_SUPPORT_SHA512_T
case SHA2_512224:
case SHA2_512256:
case SHA2_512T:
#endif
return 128;
default:
return 0;
}
}
/* Enable SHA peripheral and then lock it */
void esp_sha_acquire_hardware()
{
SHA_LOCK(); /* Released when releasing hw with esp_sha_release_hardware() */
/* Enable SHA and DMA hardware */
#if SOC_SHA_CRYPTO_DMA
periph_module_enable(PERIPH_SHA_DMA_MODULE);
#elif SOC_SHA_GDMA
periph_module_enable(PERIPH_SHA_MODULE);
#endif
}
/* Disable SHA peripheral block and then release it */
void esp_sha_release_hardware()
{
/* Disable SHA and DMA hardware */
#if SOC_SHA_CRYPTO_DMA
periph_module_disable(PERIPH_SHA_DMA_MODULE);
#elif SOC_SHA_GDMA
periph_module_disable(PERIPH_SHA_MODULE);
#endif
SHA_RELEASE();
}
#if SOC_SHA_SUPPORT_SHA512_T
/* The initial hash value for SHA512/t is generated according to the
algorithm described in the TRM, chapter SHA-Accelerator
*/
int esp_sha_512_t_init_hash(uint16_t t)
{
uint32_t t_string = 0;
uint8_t t0, t1, t2, t_len;
if (t == 384) {
ESP_LOGE(TAG, "Invalid t for SHA512/t, t = %u,cannot be 384", t);
return -1;
}
if (t <= 9) {
t_string = (uint32_t)((1 << 23) | ((0x30 + t) << 24));
t_len = 0x48;
} else if (t <= 99) {
t0 = t % 10;
t1 = (t / 10) % 10;
t_string = (uint32_t)((1 << 15) | ((0x30 + t0) << 16) |
(((0x30 + t1) << 24)));
t_len = 0x50;
} else if (t <= 512) {
t0 = t % 10;
t1 = (t / 10) % 10;
t2 = t / 100;
t_string = (uint32_t)((1 << 7) | ((0x30 + t0) << 8) |
(((0x30 + t1) << 16) + ((0x30 + t2) << 24)));
t_len = 0x58;
} else {
ESP_LOGE(TAG, "Invalid t for SHA512/t, t = %u, must equal or less than 512", t);
return -1;
}
sha_hal_sha512_init_hash(t_string, t_len);
return 0;
}
#endif //SOC_SHA_SUPPORT_SHA512_T
/* Hash the input block by block, using non-DMA mode */
static void esp_sha_block_mode(esp_sha_type sha_type, const uint8_t *input, uint32_t ilen,
const uint8_t *buf, uint32_t buf_len, bool is_first_block)
{
size_t blk_len = 0;
size_t blk_word_len = 0;
int num_block = 0;
blk_len = block_length(sha_type);
blk_word_len = blk_len / 4;
num_block = ilen / blk_len;
if (buf_len != 0) {
sha_hal_hash_block(sha_type, buf, blk_word_len, is_first_block);
is_first_block = false;
}
for (int i = 0; i < num_block; i++) {
sha_hal_hash_block(sha_type, input + blk_len * i, blk_word_len, is_first_block);
is_first_block = false;
}
}
static int esp_sha_dma_process(esp_sha_type sha_type, const void *input, uint32_t ilen,
const void *buf, uint32_t buf_len, bool is_first_block);
/* Performs SHA on multiple blocks at a time using DMA
splits up into smaller operations for inputs that exceed a single DMA list
*/
int esp_sha_dma(esp_sha_type sha_type, const void *input, uint32_t ilen,
const void *buf, uint32_t buf_len, bool is_first_block)
{
int ret = 0;
unsigned char *dma_cap_buf = NULL;
int dma_op_num = ( ilen / (SOC_SHA_DMA_MAX_BUFFER_SIZE + 1) ) + 1;
if (buf_len > block_length(sha_type)) {
ESP_LOGE(TAG, "SHA DMA buf_len cannot exceed max size for a single block");
return -1;
}
/* DMA cannot access memory in flash, hash block by block instead of using DMA */
if (!esp_ptr_dma_ext_capable(input) && !esp_ptr_dma_capable(input) && (ilen != 0)) {
esp_sha_block_mode(sha_type, input, ilen, buf, buf_len, is_first_block);
return 0;
}
#if (CONFIG_SPIRAM && SOC_PSRAM_DMA_CAPABLE)
if (esp_ptr_external_ram(input)) {
Cache_WriteBack_Addr((uint32_t)input, ilen);
}
if (esp_ptr_external_ram(buf)) {
Cache_WriteBack_Addr((uint32_t)buf, buf_len);
}
#endif
/* Copy to internal buf if buf is in non DMA capable memory */
if (!esp_ptr_dma_ext_capable(buf) && !esp_ptr_dma_capable(buf) && (buf_len != 0)) {
dma_cap_buf = heap_caps_malloc(sizeof(unsigned char) * buf_len, MALLOC_CAP_8BIT|MALLOC_CAP_DMA|MALLOC_CAP_INTERNAL);
if (dma_cap_buf == NULL) {
ESP_LOGE(TAG, "Failed to allocate buf memory");
ret = -1;
goto cleanup;
}
memcpy(dma_cap_buf, buf, buf_len);
buf = dma_cap_buf;
}
/* The max amount of blocks in a single hardware operation is 2^6 - 1 = 63
Thus we only do a single DMA input list + dma buf list,
which is max 3968/64 + 64/64 = 63 blocks */
for (int i = 0; i < dma_op_num; i++) {
int dma_chunk_len = MIN(ilen, SOC_SHA_DMA_MAX_BUFFER_SIZE);
ret = esp_sha_dma_process(sha_type, input, dma_chunk_len, buf, buf_len, is_first_block);
if (ret != 0) {
goto cleanup;
}
ilen -= dma_chunk_len;
input += dma_chunk_len;
// Only append buf to the first operation
buf_len = 0;
is_first_block = false;
}
cleanup:
free(dma_cap_buf);
return ret;
}
/* Performs SHA on multiple blocks at a time */
static esp_err_t esp_sha_dma_process(esp_sha_type sha_type, const void *input, uint32_t ilen,
const void *buf, uint32_t buf_len, bool is_first_block)
{
int ret = 0;
lldesc_t *dma_descr_head;
size_t num_blks = (ilen + buf_len) / block_length(sha_type);
memset(&s_dma_descr_input, 0, sizeof(lldesc_t));
memset(&s_dma_descr_buf, 0, sizeof(lldesc_t));
/* DMA descriptor for Memory to DMA-SHA transfer */
if (ilen) {
s_dma_descr_input.length = ilen;
s_dma_descr_input.size = ilen;
s_dma_descr_input.owner = 1;
s_dma_descr_input.eof = 1;
s_dma_descr_input.buf = (uint8_t *)input;
dma_descr_head = &s_dma_descr_input;
}
/* Check after input to overide head if there is any buf*/
if (buf_len) {
s_dma_descr_buf.length = buf_len;
s_dma_descr_buf.size = buf_len;
s_dma_descr_buf.owner = 1;
s_dma_descr_buf.eof = 1;
s_dma_descr_buf.buf = (uint8_t *)buf;
dma_descr_head = &s_dma_descr_buf;
}
/* Link DMA lists */
if (buf_len && ilen) {
s_dma_descr_buf.eof = 0;
s_dma_descr_buf.empty = (uint32_t)(&s_dma_descr_input);
}
if (esp_sha_dma_start(dma_descr_head) != ESP_OK) {
ESP_LOGE(TAG, "esp_sha_dma_start failed, no DMA channel available");
return -1;
}
sha_hal_hash_dma(sha_type, num_blks, is_first_block);
sha_hal_wait_idle();
return ret;
}
|
635748.c | /**
* @file kernel/vfs/pipe.c
* @brief Legacy buffered pipe, used for char devices.
*
* This is the legacy pipe implementation. If you are looking for
* the userspace pipes, @ref read_unixpipe.
*
* This implements a simple one-direction buffer suitable for use
* by, eg., device drivers that want to offer a character-driven
* interface to userspace without having to worry too much about
* timing or getting blocked.
*
* @copyright
* This file is part of ToaruOS and is released under the terms
* of the NCSA / University of Illinois License - see LICENSE.md
* Copyright (C) 2012-2021 K. Lange
*/
#include <errno.h>
#include <stdint.h>
#include <stddef.h>
#include <kernel/printf.h>
#include <kernel/vfs.h>
#include <kernel/pipe.h>
#include <kernel/process.h>
#include <kernel/string.h>
#include <kernel/spinlock.h>
#include <kernel/signal.h>
#include <kernel/time.h>
#include <sys/signal_defs.h>
#define DEBUG_PIPES 0
static inline size_t pipe_unread(pipe_device_t * pipe) {
if (pipe->read_ptr == pipe->write_ptr) {
return 0;
}
if (pipe->read_ptr > pipe->write_ptr) {
return (pipe->size - pipe->read_ptr) + pipe->write_ptr;
} else {
return (pipe->write_ptr - pipe->read_ptr);
}
}
int pipe_size(fs_node_t * node) {
pipe_device_t * pipe = (pipe_device_t *)node->device;
spin_lock(pipe->ptr_lock);
int out = pipe_unread(pipe);
spin_unlock(pipe->ptr_lock);
return out;
}
static inline size_t pipe_available(pipe_device_t * pipe) {
if (pipe->read_ptr == pipe->write_ptr) {
return pipe->size - 1;
}
if (pipe->read_ptr > pipe->write_ptr) {
return pipe->read_ptr - pipe->write_ptr - 1;
} else {
return (pipe->size - pipe->write_ptr) + pipe->read_ptr - 1;
}
}
int pipe_unsize(fs_node_t * node) {
pipe_device_t * pipe = (pipe_device_t *)node->device;
spin_lock(pipe->ptr_lock);
int out = pipe_available(pipe);
spin_unlock(pipe->ptr_lock);
return out;
}
static inline void pipe_increment_read(pipe_device_t * pipe) {
spin_lock(pipe->ptr_lock);
pipe->read_ptr++;
if (pipe->read_ptr == pipe->size) {
pipe->read_ptr = 0;
}
spin_unlock(pipe->ptr_lock);
}
static inline void pipe_increment_write(pipe_device_t * pipe) {
spin_lock(pipe->ptr_lock);
pipe->write_ptr++;
if (pipe->write_ptr == pipe->size) {
pipe->write_ptr = 0;
}
spin_unlock(pipe->ptr_lock);
}
static inline void pipe_increment_write_by(pipe_device_t * pipe, size_t amount) {
pipe->write_ptr = (pipe->write_ptr + amount) % pipe->size;
}
static void pipe_alert_waiters(pipe_device_t * pipe) {
spin_lock(pipe->alert_lock);
while (pipe->alert_waiters->head) {
node_t * node = list_dequeue(pipe->alert_waiters);
process_t * p = node->value;
free(node);
spin_unlock(pipe->alert_lock);
process_alert_node(p, pipe);
spin_lock(pipe->alert_lock);
}
spin_unlock(pipe->alert_lock);
}
ssize_t read_pipe(fs_node_t *node, off_t offset, size_t size, uint8_t *buffer) {
/* Retreive the pipe object associated with this file node */
pipe_device_t * pipe = (pipe_device_t *)node->device;
if (pipe->dead) {
send_signal(this_core->current_process->id, SIGPIPE, 1);
return 0;
}
size_t collected = 0;
while (collected == 0) {
spin_lock(pipe->lock_read);
if (pipe_unread(pipe) >= size) {
while (pipe_unread(pipe) > 0 && collected < size) {
buffer[collected] = pipe->buffer[pipe->read_ptr];
pipe_increment_read(pipe);
collected++;
}
}
spin_unlock(pipe->lock_read);
wakeup_queue(pipe->wait_queue_writers);
/* Deschedule and switch */
if (collected == 0) {
sleep_on(pipe->wait_queue_readers);
}
}
return collected;
}
ssize_t write_pipe(fs_node_t *node, off_t offset, size_t size, uint8_t *buffer) {
/* Retreive the pipe object associated with this file node */
pipe_device_t * pipe = (pipe_device_t *)node->device;
if (pipe->dead) {
send_signal(this_core->current_process->id, SIGPIPE, 1);
return 0;
}
size_t written = 0;
while (written < size) {
spin_lock(pipe->lock_write);
/* These pipes enforce atomic writes, poorly. */
if (pipe_available(pipe) > size) {
while (pipe_available(pipe) > 0 && written < size) {
pipe->buffer[pipe->write_ptr] = buffer[written];
pipe_increment_write(pipe);
written++;
}
}
spin_unlock(pipe->lock_write);
wakeup_queue(pipe->wait_queue_readers);
pipe_alert_waiters(pipe);
if (written < size) {
sleep_on(pipe->wait_queue_writers);
}
}
return written;
}
void open_pipe(fs_node_t * node, unsigned int flags) {
/* Retreive the pipe object associated with this file node */
pipe_device_t * pipe = (pipe_device_t *)node->device;
/* Add a reference */
pipe->refcount++;
return;
}
void close_pipe(fs_node_t * node) {
/* Retreive the pipe object associated with this file node */
pipe_device_t * pipe = (pipe_device_t *)node->device;
/* Drop one reference */
pipe->refcount--;
/* Check the reference count number */
if (pipe->refcount == 0) {
#if 0
/* No other references exist, free the pipe (but not its buffer) */
free(pipe->buffer);
list_free(pipe->wait_queue);
free(pipe->wait_queue);
free(pipe);
/* And let the creator know there are no more references */
node->device = 0;
#endif
}
return;
}
static int pipe_check(fs_node_t * node) {
pipe_device_t * pipe = (pipe_device_t *)node->device;
if (pipe_unread(pipe) > 0) {
return 0;
}
return 1;
}
static int pipe_wait(fs_node_t * node, void * process) {
pipe_device_t * pipe = (pipe_device_t *)node->device;
spin_lock(pipe->alert_lock);
if (!list_find(pipe->alert_waiters, process)) {
list_insert(pipe->alert_waiters, process);
}
spin_unlock(pipe->alert_lock);
spin_lock(pipe->wait_lock);
list_insert(((process_t *)process)->node_waits, pipe);
spin_unlock(pipe->wait_lock);
return 0;
}
void pipe_destroy(fs_node_t * node) {
pipe_device_t * pipe = (pipe_device_t *)node->device;
spin_lock(pipe->ptr_lock);
pipe->dead = 1;
pipe_alert_waiters(pipe);
wakeup_queue(pipe->wait_queue_writers);
wakeup_queue(pipe->wait_queue_readers);
free(pipe->alert_waiters);
free(pipe->wait_queue_writers);
free(pipe->wait_queue_readers);
free(pipe->buffer);
spin_unlock(pipe->ptr_lock);
free(pipe);
}
fs_node_t * make_pipe(size_t size) {
fs_node_t * fnode = malloc(sizeof(fs_node_t));
pipe_device_t * pipe = malloc(sizeof(pipe_device_t));
memset(fnode, 0, sizeof(fs_node_t));
memset(pipe, 0, sizeof(pipe_device_t));
fnode->device = 0;
fnode->name[0] = '\0';
snprintf(fnode->name, 100, "[pipe]");
fnode->uid = 0;
fnode->gid = 0;
fnode->mask = 0666;
fnode->flags = FS_PIPE;
fnode->read = read_pipe;
fnode->write = write_pipe;
fnode->open = open_pipe;
fnode->close = close_pipe;
fnode->readdir = NULL;
fnode->finddir = NULL;
fnode->ioctl = NULL; /* TODO ioctls for pipes? maybe */
fnode->get_size = pipe_size;
fnode->selectcheck = pipe_check;
fnode->selectwait = pipe_wait;
fnode->atime = now();
fnode->mtime = fnode->atime;
fnode->ctime = fnode->atime;
fnode->device = pipe;
pipe->buffer = malloc(size);
pipe->write_ptr = 0;
pipe->read_ptr = 0;
pipe->size = size;
pipe->refcount = 0;
pipe->dead = 0;
spin_init(pipe->lock_read);
spin_init(pipe->lock_write);
spin_init(pipe->alert_lock);
spin_init(pipe->wait_lock);
spin_init(pipe->ptr_lock);
pipe->wait_queue_writers = list_create("pipe writers",pipe);
pipe->wait_queue_readers = list_create("pip readers",pipe);
pipe->alert_waiters = list_create("pipe alert waiters",pipe);
return fnode;
}
|
195801.c | #include <stdio.h>
#include "unity.h"
#include "rom/ets_sys.h"
#include "rom/uart.h"
#include "soc/rtc.h"
#include "soc/rtc_cntl_reg.h"
#include "soc/rtc_io_reg.h"
#include "soc/sens_reg.h"
#include "soc/io_mux_reg.h"
#include "driver/rtc_io.h"
#include "test_utils.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "freertos/semphr.h"
#include "../esp_clk_internal.h"
#include "esp_clk.h"
#define CALIBRATE_ONE(cali_clk) calibrate_one(cali_clk, #cali_clk)
static uint32_t calibrate_one(rtc_cal_sel_t cal_clk, const char* name)
{
const uint32_t cal_count = 1000;
const float factor = (1 << 19) * 1000.0f;
uint32_t cali_val;
printf("%s:\n", name);
for (int i = 0; i < 5; ++i) {
printf("calibrate (%d): ", i);
cali_val = rtc_clk_cal(cal_clk, cal_count);
printf("%.3f kHz\n", factor / (float) cali_val);
}
return cali_val;
}
TEST_CASE("RTC_SLOW_CLK sources calibration", "[rtc_clk]")
{
rtc_clk_32k_enable(true);
rtc_clk_8m_enable(true, true);
CALIBRATE_ONE(RTC_CAL_RTC_MUX);
CALIBRATE_ONE(RTC_CAL_8MD256);
uint32_t cal_32k = CALIBRATE_ONE(RTC_CAL_32K_XTAL);
if (cal_32k == 0) {
printf("32K XTAL OSC has not started up");
} else {
printf("switching to RTC_SLOW_FREQ_32K_XTAL: ");
rtc_clk_slow_freq_set(RTC_SLOW_FREQ_32K_XTAL);
printf("done\n");
CALIBRATE_ONE(RTC_CAL_RTC_MUX);
CALIBRATE_ONE(RTC_CAL_8MD256);
CALIBRATE_ONE(RTC_CAL_32K_XTAL);
}
printf("switching to RTC_SLOW_FREQ_8MD256: ");
rtc_clk_slow_freq_set(RTC_SLOW_FREQ_8MD256);
printf("done\n");
CALIBRATE_ONE(RTC_CAL_RTC_MUX);
CALIBRATE_ONE(RTC_CAL_8MD256);
CALIBRATE_ONE(RTC_CAL_32K_XTAL);
}
/* The following two are not unit tests, but are added here to make it easy to
* check the frequency of 150k/32k oscillators. The following two "tests" will
* output either 32k or 150k clock to GPIO25.
*/
static void pull_out_clk(int sel)
{
REG_SET_BIT(RTC_IO_PAD_DAC1_REG, RTC_IO_PDAC1_MUX_SEL_M);
REG_CLR_BIT(RTC_IO_PAD_DAC1_REG, RTC_IO_PDAC1_RDE_M | RTC_IO_PDAC1_RUE_M);
REG_SET_FIELD(RTC_IO_PAD_DAC1_REG, RTC_IO_PDAC1_FUN_SEL, 1);
REG_SET_FIELD(SENS_SAR_DAC_CTRL1_REG, SENS_DEBUG_BIT_SEL, 0);
REG_SET_FIELD(RTC_IO_RTC_DEBUG_SEL_REG, RTC_IO_DEBUG_SEL0, sel);
}
TEST_CASE("Output 150k clock to GPIO25", "[rtc_clk][ignore]")
{
pull_out_clk(RTC_IO_DEBUG_SEL0_150K_OSC);
}
TEST_CASE("Output 32k XTAL clock to GPIO25", "[rtc_clk][ignore]")
{
rtc_clk_32k_enable(true);
pull_out_clk(RTC_IO_DEBUG_SEL0_32K_XTAL);
}
TEST_CASE("Output 8M XTAL clock to GPIO25", "[rtc_clk][ignore]")
{
rtc_clk_8m_enable(true, true);
SET_PERI_REG_MASK(RTC_IO_RTC_DEBUG_SEL_REG, RTC_IO_DEBUG_12M_NO_GATING);
pull_out_clk(RTC_IO_DEBUG_SEL0_8M);
}
static void test_clock_switching(void (*switch_func)(const rtc_cpu_freq_config_t* config))
{
uart_tx_wait_idle(CONFIG_CONSOLE_UART_NUM);
const int test_duration_sec = 10;
ref_clock_init();
uint64_t t_start = ref_clock_get();
rtc_cpu_freq_config_t cur_config;
rtc_clk_cpu_freq_get_config(&cur_config);
rtc_cpu_freq_config_t xtal_config;
rtc_clk_cpu_freq_mhz_to_config((uint32_t) rtc_clk_xtal_freq_get(), &xtal_config);
int count = 0;
while (ref_clock_get() - t_start < test_duration_sec * 1000000) {
switch_func(&xtal_config);
switch_func(&cur_config);
++count;
}
uint64_t t_end = ref_clock_get();
printf("Switch count: %d. Average time to switch PLL -> XTAL -> PLL: %d us\n", count, (int) ((t_end - t_start) / count));
ref_clock_deinit();
}
TEST_CASE("Calculate 8M clock frequency", "[rtc_clk]")
{
// calibrate 8M/256 clock against XTAL, get 8M/256 clock period
uint32_t rtc_8md256_period = rtc_clk_cal(RTC_CAL_8MD256, 100);
uint32_t rtc_fast_freq_hz = 1000000ULL * (1 << RTC_CLK_CAL_FRACT) * 256 / rtc_8md256_period;
printf("RTC_FAST_CLK=%d Hz\n", rtc_fast_freq_hz);
TEST_ASSERT_INT32_WITHIN(500000, RTC_FAST_CLK_FREQ_APPROX, rtc_fast_freq_hz);
}
TEST_CASE("Test switching between PLL and XTAL", "[rtc_clk]")
{
test_clock_switching(rtc_clk_cpu_freq_set_config);
}
TEST_CASE("Test fast switching between PLL and XTAL", "[rtc_clk]")
{
test_clock_switching(rtc_clk_cpu_freq_set_config_fast);
}
#define COUNT_TEST 3
#define TIMEOUT_TEST_MS (5 + CONFIG_ESP32_RTC_CLK_CAL_CYCLES / 16)
void stop_rtc_external_quartz(){
const uint8_t pin_32 = 32;
const uint8_t pin_33 = 33;
const uint8_t mask_32 = (1 << (pin_32 - 32));
const uint8_t mask_33 = (1 << (pin_33 - 32));
rtc_clk_32k_enable(false);
gpio_pad_select_gpio(pin_32);
gpio_pad_select_gpio(pin_33);
gpio_output_set_high(0, mask_32 | mask_33, mask_32 | mask_33, 0);
ets_delay_us(500000);
gpio_output_set_high(0, 0, 0, mask_32 | mask_33); // disable pins
}
static void start_freq(rtc_slow_freq_t required_src_freq, uint32_t start_delay_ms)
{
int i = 0, fail = 0;
uint32_t start_time;
uint32_t end_time;
rtc_slow_freq_t selected_src_freq;
stop_rtc_external_quartz();
#ifdef CONFIG_ESP32_RTC_CLOCK_SOURCE_EXTERNAL_CRYSTAL
uint32_t bootstrap_cycles = CONFIG_ESP32_RTC_XTAL_BOOTSTRAP_CYCLES;
printf("Test is started. Kconfig settings:\n External 32K crystal is selected,\n Oscillation cycles = %d,\n Calibration cycles = %d.\n",
bootstrap_cycles,
CONFIG_ESP32_RTC_CLK_CAL_CYCLES);
#else
uint32_t bootstrap_cycles = 5;
printf("Test is started. Kconfig settings:\n Internal RC is selected,\n Oscillation cycles = %d,\n Calibration cycles = %d.\n",
bootstrap_cycles,
CONFIG_ESP32_RTC_CLK_CAL_CYCLES);
#endif
if (start_delay_ms == 0 && CONFIG_ESP32_RTC_CLK_CAL_CYCLES < 1500){
start_delay_ms = 50;
printf("Recommended increase Number of cycles for RTC_SLOW_CLK calibration to 3000!\n");
}
while(i < COUNT_TEST){
start_time = xTaskGetTickCount() * (1000 / configTICK_RATE_HZ);
i++;
printf("attempt #%d/%d...", i, COUNT_TEST);
rtc_clk_32k_bootstrap(bootstrap_cycles);
ets_delay_us(start_delay_ms * 1000);
rtc_clk_select_rtc_slow_clk();
selected_src_freq = rtc_clk_slow_freq_get();
end_time = xTaskGetTickCount() * (1000 / configTICK_RATE_HZ);
printf(" [time=%d] ", (end_time - start_time) - start_delay_ms);
if(selected_src_freq != required_src_freq){
printf("FAIL. Time measurement...");
fail = 1;
} else {
printf("PASS. Time measurement...");
}
uint64_t clk_rtc_time;
uint32_t fail_measure = 0;
for (int j = 0; j < 3; ++j) {
clk_rtc_time = esp_clk_rtc_time();
ets_delay_us(1000000);
uint64_t delta = esp_clk_rtc_time() - clk_rtc_time;
if (delta < 900000LL || delta > 1100000){
printf("FAIL");
fail = 1;
fail_measure = 1;
break;
}
}
if(fail_measure == 0) {
printf("PASS");
}
printf(" [calibration val = %d] \n", esp_clk_slowclk_cal_get());
stop_rtc_external_quartz();
ets_delay_us(500000);
}
TEST_ASSERT_MESSAGE(fail == 0, "Test failed");
printf("Test passed successfully\n");
}
#ifdef CONFIG_SPIRAM_SUPPORT
// PSRAM tests run on ESP-WROVER-KIT boards, which have the 32k XTAL installed.
// Other tests may run on DevKitC boards, which don't have a 32k XTAL.
TEST_CASE("Test starting external RTC quartz", "[rtc_clk]")
{
int i = 0, fail = 0;
uint32_t start_time;
uint32_t end_time;
stop_rtc_external_quartz();
#ifdef CONFIG_ESP32_RTC_CLOCK_SOURCE_EXTERNAL_CRYSTAL
uint32_t bootstrap_cycles = CONFIG_ESP32_RTC_XTAL_BOOTSTRAP_CYCLES;
printf("Test is started. Kconfig settings:\n External 32K crystal is selected,\n Oscillation cycles = %d,\n Calibration cycles = %d.\n",
bootstrap_cycles,
CONFIG_ESP32_RTC_CLK_CAL_CYCLES);
#else
uint32_t bootstrap_cycles = 5;
printf("Test is started. Kconfig settings:\n Internal RC is selected,\n Oscillation cycles = %d,\n Calibration cycles = %d.\n",
bootstrap_cycles,
CONFIG_ESP32_RTC_CLK_CAL_CYCLES);
#endif
if (CONFIG_ESP32_RTC_CLK_CAL_CYCLES < 1500){
printf("Recommended increase Number of cycles for RTC_SLOW_CLK calibration to 3000!\n");
}
while(i < COUNT_TEST){
start_time = xTaskGetTickCount() * (1000 / configTICK_RATE_HZ);
i++;
printf("attempt #%d/%d...", i, COUNT_TEST);
rtc_clk_32k_bootstrap(bootstrap_cycles);
rtc_clk_select_rtc_slow_clk();
end_time = xTaskGetTickCount() * (1000 / configTICK_RATE_HZ);
printf(" [time=%d] ", end_time - start_time);
if((end_time - start_time) > TIMEOUT_TEST_MS){
printf("FAIL\n");
fail = 1;
} else {
printf("PASS\n");
}
stop_rtc_external_quartz();
ets_delay_us(100000);
}
TEST_ASSERT_MESSAGE(fail == 0, "Test failed");
printf("Test passed successfully\n");
}
TEST_CASE("Test starting 'External 32kHz XTAL' on the board with it.", "[rtc_clk]")
{
start_freq(RTC_SLOW_FREQ_32K_XTAL, 200);
start_freq(RTC_SLOW_FREQ_32K_XTAL, 0);
}
#else
TEST_CASE("Test starting 'External 32kHz XTAL' on the board without it.", "[rtc_clk][ignore]")
{
printf("Tries to start the 'External 32kHz XTAL' on the board without it. "
"Clock switching to 'Internal 150 kHz RC oscillator'.\n");
printf("This test will be successful for boards without an external crystal or non-working crystal. "
"First, there will be an attempt to start from the external crystal after a failure "
"will switch to the internal RC circuit. If the switch to the internal RC circuit "
"was successful then the test succeeded.\n");
start_freq(RTC_SLOW_FREQ_RTC, 200);
start_freq(RTC_SLOW_FREQ_RTC, 0);
}
#endif // CONFIG_SPIRAM_SUPPORT
|
153989.c | // SPDX-License-Identifier: GPL-2.0-or-later
/*******************************************************************************
*
* CTU CAN FD IP Core
*
* Copyright (C) 2015-2018 Ondrej Ille <[email protected]> FEE CTU
* Copyright (C) 2018-2020 Ondrej Ille <[email protected]> self-funded
* Copyright (C) 2018-2019 Martin Jerabek <[email protected]> FEE CTU
* Copyright (C) 2018-2020 Pavel Pisa <[email protected]> FEE CTU/self-funded
*
* Project advisors:
* Jiri Novak <[email protected]>
* Pavel Pisa <[email protected]>
*
* Department of Measurement (http://meas.fel.cvut.cz/)
* Faculty of Electrical Engineering (http://www.fel.cvut.cz)
* Czech Technical University (http://www.cvut.cz/)
*
* 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/errno.h>
#include <linux/init.h>
#include <linux/bitfield.h>
#include <linux/interrupt.h>
#include <linux/io.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/skbuff.h>
#include <linux/string.h>
#include <linux/types.h>
#include <linux/can/error.h>
#include <linux/can/led.h>
#include <linux/pm_runtime.h>
#include <linux/version.h>
#include "ctucanfd.h"
#include "ctucanfd_kregs.h"
#include "ctucanfd_kframe.h"
#define DRV_NAME "ctucanfd"
#ifdef DEBUG
#define ctucan_netdev_dbg(ndev, args...) \
netdev_dbg(ndev, args)
#else
#define ctucan_netdev_dbg(...) do { } while (0)
#endif
#if LINUX_VERSION_CODE < KERNEL_VERSION(5, 11, 0)
#define can_fd_len2dlc can_len2dlc
#endif
#define CTUCANFD_ID 0xCAFD
/* TX buffer rotation:
* - when a buffer transitions to empty state, rotate order and priorities
* - if more buffers seem to transition at the same time, rotate by the number of buffers
* - it may be assumed that buffers transition to empty state in FIFO order (because we manage
* priorities that way)
* - at frame filling, do not rotate anything, just increment buffer modulo counter
*/
#define CTUCANFD_FLAG_RX_FFW_BUFFERED 1
#define CTUCAN_STATE_TO_TEXT_ENTRY(st) \
[st] = #st
enum ctucan_txtb_status {
TXT_NOT_EXIST = 0x0,
TXT_RDY = 0x1,
TXT_TRAN = 0x2,
TXT_ABTP = 0x3,
TXT_TOK = 0x4,
TXT_ERR = 0x6,
TXT_ABT = 0x7,
TXT_ETY = 0x8,
};
enum ctucan_txtb_command {
TXT_CMD_SET_EMPTY = 0x01,
TXT_CMD_SET_READY = 0x02,
TXT_CMD_SET_ABORT = 0x04
};
const struct can_bittiming_const ctu_can_fd_bit_timing_max = {
.name = "ctu_can_fd",
.tseg1_min = 2,
.tseg1_max = 190,
.tseg2_min = 1,
.tseg2_max = 63,
.sjw_max = 31,
.brp_min = 1,
.brp_max = 8,
.brp_inc = 1,
};
const struct can_bittiming_const ctu_can_fd_bit_timing_data_max = {
.name = "ctu_can_fd",
.tseg1_min = 2,
.tseg1_max = 94,
.tseg2_min = 1,
.tseg2_max = 31,
.sjw_max = 31,
.brp_min = 1,
.brp_max = 2,
.brp_inc = 1,
};
static const char * const ctucan_state_strings[CAN_STATE_MAX] = {
CTUCAN_STATE_TO_TEXT_ENTRY(CAN_STATE_ERROR_ACTIVE),
CTUCAN_STATE_TO_TEXT_ENTRY(CAN_STATE_ERROR_WARNING),
CTUCAN_STATE_TO_TEXT_ENTRY(CAN_STATE_ERROR_PASSIVE),
CTUCAN_STATE_TO_TEXT_ENTRY(CAN_STATE_BUS_OFF),
CTUCAN_STATE_TO_TEXT_ENTRY(CAN_STATE_STOPPED),
CTUCAN_STATE_TO_TEXT_ENTRY(CAN_STATE_SLEEPING)
};
static void ctucan_write32_le(struct ctucan_priv *priv,
enum ctu_can_fd_can_registers reg, u32 val)
{
iowrite32(val, priv->mem_base + reg);
}
static void ctucan_write32_be(struct ctucan_priv *priv,
enum ctu_can_fd_can_registers reg, u32 val)
{
iowrite32be(val, priv->mem_base + reg);
}
static u32 ctucan_read32_le(struct ctucan_priv *priv,
enum ctu_can_fd_can_registers reg)
{
return ioread32(priv->mem_base + reg);
}
static u32 ctucan_read32_be(struct ctucan_priv *priv,
enum ctu_can_fd_can_registers reg)
{
return ioread32be(priv->mem_base + reg);
}
static inline void ctucan_write32(struct ctucan_priv *priv, enum ctu_can_fd_can_registers reg,
u32 val)
{
priv->write_reg(priv, reg, val);
}
static inline u32 ctucan_read32(struct ctucan_priv *priv, enum ctu_can_fd_can_registers reg)
{
return priv->read_reg(priv, reg);
}
static void ctucan_write_txt_buf(struct ctucan_priv *priv, enum ctu_can_fd_can_registers buf_base,
u32 offset, u32 val)
{
priv->write_reg(priv, buf_base + offset, val);
}
#define CTU_CAN_FD_TXTNF(priv) (!!FIELD_GET(REG_STATUS_TXNF, ctucan_read32(priv, CTUCANFD_STATUS)))
#define CTU_CAN_FD_ENABLED(priv) (!!FIELD_GET(REG_MODE_ENA, ctucan_read32(priv, CTUCANFD_MODE)))
/**
* ctucan_state_to_str() - Converts CAN controller state code to corresponding text
* @state: CAN controller state code
*
* Return: Pointer to string representation of the error state
*/
static const char *ctucan_state_to_str(enum can_state state)
{
const char *txt = NULL;
if (state >= 0 && state < CAN_STATE_MAX)
txt = ctucan_state_strings[state];
return txt ? txt : "UNKNOWN";
}
/**
* ctucan_reset() - Issues software reset request to CTU CAN FD
* @ndev: Pointer to net_device structure
*
* Return: 0 for success, -%ETIMEDOUT if CAN controller does not leave reset
*/
static int ctucan_reset(struct net_device *ndev)
{
int i = 100;
struct ctucan_priv *priv = netdev_priv(ndev);
ctucan_netdev_dbg(ndev, "%s\n", __func__);
ctucan_write32(priv, CTUCANFD_MODE, REG_MODE_RST);
clear_bit(CTUCANFD_FLAG_RX_FFW_BUFFERED, &priv->drv_flags);
do {
u16 device_id = FIELD_GET(REG_DEVICE_ID_DEVICE_ID, ctucan_read32(priv, CTUCANFD_DEVICE_ID));
if (device_id == 0xCAFD)
return 0;
if (!i--) {
netdev_warn(ndev, "device did not leave reset\n");
return -ETIMEDOUT;
}
usleep_range(100, 200);
} while (1);
}
/**
* ctucan_set_btr() - Sets CAN bus bit timing in CTU CAN FD
* @ndev: Pointer to net_device structure
* @bt: Pointer to Bit timing structure
* @nominal: True - Nominal bit timing, False - Data bit timing
*
* Return: 0 - OK, -%EPERM if controller is enabled
*/
static int ctucan_set_btr(struct net_device *ndev, struct can_bittiming *bt, bool nominal)
{
struct ctucan_priv *priv = netdev_priv(ndev);
int max_ph1_len = 31;
u32 btr = 0;
u32 prop_seg = bt->prop_seg;
u32 phase_seg1 = bt->phase_seg1;
if (CTU_CAN_FD_ENABLED(priv)) {
netdev_err(ndev, "BUG! Cannot set bittiming - CAN is enabled\n");
return -EPERM;
}
if (nominal)
max_ph1_len = 63;
/* The timing calculation functions have only constraints on tseg1, which is prop_seg +
* phase1_seg combined. tseg1 is then split in half and stored into prog_seg and phase_seg1.
* In CTU CAN FD, PROP is 6/7 bits wide but PH1 only 6/5, so we must re-distribute the
* values here.
*/
if (phase_seg1 > max_ph1_len) {
prop_seg += phase_seg1 - max_ph1_len;
phase_seg1 = max_ph1_len;
bt->prop_seg = prop_seg;
bt->phase_seg1 = phase_seg1;
}
if (nominal) {
btr = FIELD_PREP(REG_BTR_PROP, prop_seg);
btr |= FIELD_PREP(REG_BTR_PH1, phase_seg1);
btr |= FIELD_PREP(REG_BTR_PH2, bt->phase_seg2);
btr |= FIELD_PREP(REG_BTR_BRP, bt->brp);
btr |= FIELD_PREP(REG_BTR_SJW, bt->sjw);
ctucan_write32(priv, CTUCANFD_BTR, btr);
} else {
btr = FIELD_PREP(REG_BTR_FD_PROP_FD, prop_seg);
btr |= FIELD_PREP(REG_BTR_FD_PH1_FD, phase_seg1);
btr |= FIELD_PREP(REG_BTR_FD_PH2_FD, bt->phase_seg2);
btr |= FIELD_PREP(REG_BTR_FD_BRP_FD, bt->brp);
btr |= FIELD_PREP(REG_BTR_FD_SJW_FD, bt->sjw);
ctucan_write32(priv, CTUCANFD_BTR_FD, btr);
}
return 0;
}
/**
* ctucan_set_bittiming() - CAN set nominal bit timing routine
* @ndev: Pointer to net_device structure
*
* Return: 0 on success, -%EPERM on error
*/
static int ctucan_set_bittiming(struct net_device *ndev)
{
struct ctucan_priv *priv = netdev_priv(ndev);
struct can_bittiming *bt = &priv->can.bittiming;
ctucan_netdev_dbg(ndev, "%s\n", __func__);
/* Note that bt may be modified here */
return ctucan_set_btr(ndev, bt, true);
}
/**
* ctucan_set_data_bittiming() - CAN set data bit timing routine
* @ndev: Pointer to net_device structure
*
* Return: 0 on success, -%EPERM on error
*/
static int ctucan_set_data_bittiming(struct net_device *ndev)
{
struct ctucan_priv *priv = netdev_priv(ndev);
struct can_bittiming *dbt = &priv->can.data_bittiming;
ctucan_netdev_dbg(ndev, "%s\n", __func__);
/* Note that dbt may be modified here */
return ctucan_set_btr(ndev, dbt, false);
}
/**
* ctucan_set_secondary_sample_point() - Sets secondary sample point in CTU CAN FD
* @ndev: Pointer to net_device structure
*
* Return: 0 on success, -%EPERM if controller is enabled
*/
static int ctucan_set_secondary_sample_point(struct net_device *ndev)
{
struct ctucan_priv *priv = netdev_priv(ndev);
struct can_bittiming *dbt = &priv->can.data_bittiming;
int ssp_offset = 0;
u32 ssp_cfg = 0; /* No SSP by default */
ctucan_netdev_dbg(ndev, "%s\n", __func__);
if (CTU_CAN_FD_ENABLED(priv)) {
netdev_err(ndev, "BUG! Cannot set SSP - CAN is enabled\n");
return -EPERM;
}
/* Use SSP for bit-rates above 1 Mbits/s */
if (dbt->bitrate > 1000000) {
/* Calculate SSP in minimal time quanta */
ssp_offset = (priv->can.clock.freq / 1000) * dbt->sample_point / dbt->bitrate;
if (ssp_offset > 127) {
netdev_warn(ndev, "SSP offset saturated to 127\n");
ssp_offset = 127;
}
ssp_cfg = FIELD_PREP(REG_TRV_DELAY_SSP_OFFSET, ssp_offset);
ssp_cfg |= FIELD_PREP(REG_TRV_DELAY_SSP_SRC, 0x1);
}
ctucan_write32(priv, CTUCANFD_TRV_DELAY, ssp_cfg);
return 0;
}
/**
* ctucan_set_mode() - Sets CTU CAN FDs mode
* @priv: Pointer to private data
* @mode: Pointer to controller modes to be set
*/
static void ctucan_set_mode(struct ctucan_priv *priv, const struct can_ctrlmode *mode)
{
u32 mode_reg = ctucan_read32(priv, CTUCANFD_MODE);
mode_reg = (mode->flags & CAN_CTRLMODE_LOOPBACK) ?
(mode_reg | REG_MODE_ILBP) :
(mode_reg & ~REG_MODE_ILBP);
mode_reg = (mode->flags & CAN_CTRLMODE_LISTENONLY) ?
(mode_reg | REG_MODE_BMM) :
(mode_reg & ~REG_MODE_BMM);
mode_reg = (mode->flags & CAN_CTRLMODE_FD) ?
(mode_reg | REG_MODE_FDE) :
(mode_reg & ~REG_MODE_FDE);
mode_reg = (mode->flags & CAN_CTRLMODE_PRESUME_ACK) ?
(mode_reg | REG_MODE_ACF) :
(mode_reg & ~REG_MODE_ACF);
mode_reg = (mode->flags & CAN_CTRLMODE_FD_NON_ISO) ?
(mode_reg | REG_MODE_NISOFD) :
(mode_reg & ~REG_MODE_NISOFD);
/* One shot mode supported indirectly via Retransmit limit */
mode_reg &= ~FIELD_PREP(REG_MODE_RTRTH, 0xF);
mode_reg = (mode->flags & CAN_CTRLMODE_ONE_SHOT) ?
(mode_reg | REG_MODE_RTRLE) :
(mode_reg & ~REG_MODE_RTRLE);
/* Some bits fixed:
* TSTM - Off, User shall not be able to change REC/TEC by hand during operation
*/
mode_reg &= ~REG_MODE_TSTM;
ctucan_write32(priv, CTUCANFD_MODE, mode_reg);
}
/**
* ctucan_chip_start() - This routine starts the driver
* @ndev: Pointer to net_device structure
*
* Routine expects that chip is in reset state. It setups initial
* Tx buffers for FIFO priorities, sets bittiming, enables interrupts,
* switches core to operational mode and changes controller
* state to %CAN_STATE_STOPPED.
*
* Return: 0 on success and failure value on error
*/
static int ctucan_chip_start(struct net_device *ndev)
{
struct ctucan_priv *priv = netdev_priv(ndev);
u32 int_ena, int_msk;
u32 mode_reg;
int err;
struct can_ctrlmode mode;
ctucan_netdev_dbg(ndev, "%s\n", __func__);
priv->txb_prio = 0x01234567;
priv->txb_head = 0;
priv->txb_tail = 0;
ctucan_write32(priv, CTUCANFD_TX_PRIORITY, priv->txb_prio);
/* Configure bit-rates and ssp */
err = ctucan_set_bittiming(ndev);
if (err < 0)
return err;
err = ctucan_set_data_bittiming(ndev);
if (err < 0)
return err;
err = ctucan_set_secondary_sample_point(ndev);
if (err < 0)
return err;
/* Configure modes */
mode.flags = priv->can.ctrlmode;
mode.mask = 0xFFFFFFFF;
ctucan_set_mode(priv, &mode);
/* Configure interrupts */
int_ena = REG_INT_STAT_RBNEI |
REG_INT_STAT_TXBHCI |
REG_INT_STAT_EWLI |
REG_INT_STAT_FCSI;
/* Bus error reporting -> Allow Error/Arb.lost interrupts */
if (priv->can.ctrlmode & CAN_CTRLMODE_BERR_REPORTING) {
int_ena |= REG_INT_STAT_ALI |
REG_INT_STAT_BEI;
}
int_msk = ~int_ena; /* Mask all disabled interrupts */
/* It's after reset, so there is no need to clear anything */
ctucan_write32(priv, CTUCANFD_INT_MASK_SET, int_msk);
ctucan_write32(priv, CTUCANFD_INT_ENA_SET, int_ena);
/* Controller enters ERROR_ACTIVE on initial FCSI */
priv->can.state = CAN_STATE_STOPPED;
/* Enable the controller */
mode_reg = ctucan_read32(priv, CTUCANFD_MODE);
mode_reg |= REG_MODE_ENA;
ctucan_write32(priv, CTUCANFD_MODE, mode_reg);
return 0;
}
/**
* ctucan_do_set_mode() - Sets mode of the driver
* @ndev: Pointer to net_device structure
* @mode: Tells the mode of the driver
*
* This check the drivers state and calls the corresponding modes to set.
*
* Return: 0 on success and failure value on error
*/
static int ctucan_do_set_mode(struct net_device *ndev, enum can_mode mode)
{
int ret;
ctucan_netdev_dbg(ndev, "%s\n", __func__);
switch (mode) {
case CAN_MODE_START:
ret = ctucan_reset(ndev);
if (ret < 0)
return ret;
ret = ctucan_chip_start(ndev);
if (ret < 0) {
netdev_err(ndev, "ctucan_chip_start failed!\n");
return ret;
}
netif_wake_queue(ndev);
break;
default:
ret = -EOPNOTSUPP;
break;
}
return ret;
}
/**
* ctucan_get_tx_status() - Gets status of TXT buffer
* @priv: Pointer to private data
* @buf: Buffer index (0-based)
*
* Return: Status of TXT buffer
*/
static inline enum ctucan_txtb_status ctucan_get_tx_status(struct ctucan_priv *priv, u8 buf)
{
u32 tx_status = ctucan_read32(priv, CTUCANFD_TX_STATUS);
enum ctucan_txtb_status status = (tx_status >> (buf * 4)) & 0xf;
return status;
}
/**
* ctucan_is_txt_buf_writable() - Checks if frame can be inserted to TXT Buffer
* @priv: Pointer to private data
* @buf: Buffer index (0-based)
*
* Return: True - Frame can be inserted to TXT Buffer, False - If attempted, frame will not be
* inserted to TXT Buffer
*/
static bool ctucan_is_txt_buf_writable(struct ctucan_priv *priv, u8 buf)
{
enum ctucan_txtb_status buf_status;
buf_status = ctucan_get_tx_status(priv, buf);
if (buf_status == TXT_RDY || buf_status == TXT_TRAN || buf_status == TXT_ABTP || buf_status == TXT_NOT_EXIST)
return false;
return true;
}
/**
* ctucan_insert_frame() - Inserts frame to TXT buffer
* @priv: Pointer to private data
* @cf: Pointer to CAN frame to be inserted
* @buf: TXT Buffer index to which frame is inserted (0-based)
* @isfdf: True - CAN FD Frame, False - CAN 2.0 Frame
*
* Return: True - Frame inserted successfully
* False - Frame was not inserted due to one of:
* 1. TXT Buffer is not writable (it is in wrong state)
* 2. Invalid TXT buffer index
* 3. Invalid frame length
*/
static bool ctucan_insert_frame(struct ctucan_priv *priv, const struct canfd_frame *cf, u8 buf,
bool isfdf)
{
u32 buf_base;
u32 ffw = 0;
u32 idw = 0;
unsigned int i;
if (buf >= priv->ntxbufs)
return false;
if (!ctucan_is_txt_buf_writable(priv, buf))
return false;
if (cf->len > CANFD_MAX_DLEN)
return false;
/* Prepare Frame format */
if (cf->can_id & CAN_RTR_FLAG)
ffw |= REG_FRAME_FORMAT_W_RTR;
if (cf->can_id & CAN_EFF_FLAG)
ffw |= REG_FRAME_FORMAT_W_IDE;
if (isfdf) {
ffw |= REG_FRAME_FORMAT_W_FDF;
if (cf->flags & CANFD_BRS)
ffw |= REG_FRAME_FORMAT_W_BRS;
}
ffw |= FIELD_PREP(REG_FRAME_FORMAT_W_DLC, can_fd_len2dlc(cf->len));
/* Prepare identifier */
if (cf->can_id & CAN_EFF_FLAG)
idw = cf->can_id & CAN_EFF_MASK;
else
idw = FIELD_PREP(REG_IDENTIFIER_W_IDENTIFIER_BASE, cf->can_id & CAN_SFF_MASK);
/* Write ID, Frame format, Don't write timestamp -> Time triggered transmission disabled */
buf_base = (buf + 1) * 0x100;
ctucan_write_txt_buf(priv, buf_base, CTUCANFD_FRAME_FORMAT_W, ffw);
ctucan_write_txt_buf(priv, buf_base, CTUCANFD_IDENTIFIER_W, idw);
/* Write Data payload */
if (!(cf->can_id & CAN_RTR_FLAG)) {
for (i = 0; i < cf->len; i += 4) {
u32 data = le32_to_cpu(*(__le32 *)(cf->data + i));
ctucan_write_txt_buf(priv, buf_base, CTUCANFD_DATA_1_4_W + i, data);
}
}
return true;
}
/**
* ctucan_give_txtb_cmd() - Applies command on TXT buffer
* @priv: Pointer to private data
* @cmd: Command to give
* @buf: Buffer index (0-based)
*/
static void ctucan_give_txtb_cmd(struct ctucan_priv *priv, enum ctucan_txtb_command cmd, u8 buf)
{
u32 tx_cmd = cmd;
tx_cmd |= 1 << (buf + 8);
ctucan_write32(priv, CTUCANFD_TX_COMMAND, tx_cmd);
}
/**
* ctucan_start_xmit() - Starts the transmission
* @skb: sk_buff pointer that contains data to be Txed
* @ndev: Pointer to net_device structure
*
* Invoked from upper layers to initiate transmission. Uses the next available free TXT Buffer and
* populates its fields to start the transmission.
*
* Return: %NETDEV_TX_OK on success, %NETDEV_TX_BUSY when no free TXT buffer is available,
* negative return values reserved for error cases
*/
static netdev_tx_t ctucan_start_xmit(struct sk_buff *skb, struct net_device *ndev)
{
struct ctucan_priv *priv = netdev_priv(ndev);
struct net_device_stats *stats = &ndev->stats;
struct canfd_frame *cf = (struct canfd_frame *)skb->data;
u32 txtb_id;
bool ok;
unsigned long flags;
if (can_dropped_invalid_skb(ndev, skb))
return NETDEV_TX_OK;
if (unlikely(!CTU_CAN_FD_TXTNF(priv))) {
netif_stop_queue(ndev);
netdev_err(ndev, "BUG!, no TXB free when queue awake!\n");
return NETDEV_TX_BUSY;
}
txtb_id = priv->txb_head % priv->ntxbufs;
ctucan_netdev_dbg(ndev, "%s: using TXB#%u\n", __func__, txtb_id);
ok = ctucan_insert_frame(priv, cf, txtb_id, can_is_canfd_skb(skb));
if (!ok) {
netdev_err(ndev, "BUG! TXNF set but cannot insert frame into TXB#%x! HW Bug?", txtb_id);
kfree_skb(skb);
ndev->stats.tx_dropped++;
/* Try next TX buffer */
spin_lock_irqsave(&priv->tx_lock, flags);
priv->txb_head++;
spin_unlock_irqrestore(&priv->tx_lock, flags);
return NETDEV_TX_OK;
}
#if LINUX_VERSION_CODE >= KERNEL_VERSION(5, 12, 0)
can_put_echo_skb(skb, ndev, txtb_id, 0);
#else /* < 5.12.0 */
can_put_echo_skb(skb, ndev, txtb_id);
#endif /* < 5.12.0 */
if (!(cf->can_id & CAN_RTR_FLAG))
stats->tx_bytes += cf->len;
spin_lock_irqsave(&priv->tx_lock, flags);
ctucan_give_txtb_cmd(priv, TXT_CMD_SET_READY, txtb_id);
priv->txb_head++;
/* Check if all TX buffers are full */
if (!CTU_CAN_FD_TXTNF(priv))
netif_stop_queue(ndev);
spin_unlock_irqrestore(&priv->tx_lock, flags);
return NETDEV_TX_OK;
}
/**
* ctucan_read_rx_frame() - Reads frame from RX FIFO
* @priv: Pointer to CTU CAN FD's private data
* @cf: Pointer to CAN frame struct
* @ffw: Previously read frame format word
*
* Note: Frame format word must be read separately and provided in 'ffw'.
*/
static void ctucan_read_rx_frame(struct ctucan_priv *priv, struct canfd_frame *cf, u32 ffw)
{
u32 idw;
unsigned int i;
unsigned int wc;
unsigned int len;
idw = ctucan_read32(priv, CTUCANFD_RX_DATA);
if (FIELD_GET(REG_FRAME_FORMAT_W_IDE, ffw))
cf->can_id = (idw & CAN_EFF_MASK) | CAN_EFF_FLAG;
else
cf->can_id = (idw >> 18) & CAN_SFF_MASK;
/* BRS, ESI, RTR Flags */
cf->flags = 0;
if (FIELD_GET(REG_FRAME_FORMAT_W_FDF, ffw)) {
if (FIELD_GET(REG_FRAME_FORMAT_W_BRS, ffw))
cf->flags |= CANFD_BRS;
if (FIELD_GET(REG_FRAME_FORMAT_W_ESI_RSV, ffw))
cf->flags |= CANFD_ESI;
} else if (FIELD_GET(REG_FRAME_FORMAT_W_RTR, ffw)) {
cf->can_id |= CAN_RTR_FLAG;
}
wc = FIELD_GET(REG_FRAME_FORMAT_W_RWCNT, ffw) - 3;
/* DLC */
if (FIELD_GET(REG_FRAME_FORMAT_W_DLC, ffw) <= 8) {
len = FIELD_GET(REG_FRAME_FORMAT_W_DLC, ffw);
} else {
if (FIELD_GET(REG_FRAME_FORMAT_W_FDF, ffw))
len = wc << 2;
else
len = 8;
}
cf->len = len;
if (unlikely(len > wc * 4))
len = wc * 4;
/* Timestamp - Read and throw away */
ctucan_read32(priv, CTUCANFD_RX_DATA);
ctucan_read32(priv, CTUCANFD_RX_DATA);
/* Data */
for (i = 0; i < len; i += 4) {
u32 data = ctucan_read32(priv, CTUCANFD_RX_DATA);
*(__le32 *)(cf->data + i) = cpu_to_le32(data);
}
while (unlikely(i < wc * 4)) {
ctucan_read32(priv, CTUCANFD_RX_DATA);
i += 4;
}
}
/**
* ctucan_rx() - Called from CAN ISR to complete the received frame processing
* @ndev: Pointer to net_device structure
*
* This function is invoked from the CAN isr(poll) to process the Rx frames. It does minimal
* processing and invokes "netif_receive_skb" to complete further processing.
* Return: 1 when frame is passed to the network layer, 0 when the first frame word is read but
* system is out of free SKBs temporally and left code to resolve SKB allocation later,
* -%EAGAIN in a case of empty Rx FIFO.
*/
static int ctucan_rx(struct net_device *ndev)
{
struct ctucan_priv *priv = netdev_priv(ndev);
struct net_device_stats *stats = &ndev->stats;
struct canfd_frame *cf;
struct sk_buff *skb;
u32 ffw;
if (test_bit(CTUCANFD_FLAG_RX_FFW_BUFFERED, &priv->drv_flags)) {
ffw = priv->rxfrm_first_word;
clear_bit(CTUCANFD_FLAG_RX_FFW_BUFFERED, &priv->drv_flags);
} else {
ffw = ctucan_read32(priv, CTUCANFD_RX_DATA);
}
if (!FIELD_GET(REG_FRAME_FORMAT_W_RWCNT, ffw))
return -EAGAIN;
if (FIELD_GET(REG_FRAME_FORMAT_W_FDF, ffw))
skb = alloc_canfd_skb(ndev, &cf);
else
skb = alloc_can_skb(ndev, (struct can_frame **)&cf);
if (unlikely(!skb)) {
priv->rxfrm_first_word = ffw;
set_bit(CTUCANFD_FLAG_RX_FFW_BUFFERED, &priv->drv_flags);
return 0;
}
ctucan_read_rx_frame(priv, cf, ffw);
stats->rx_bytes += cf->len;
stats->rx_packets++;
netif_receive_skb(skb);
return 1;
}
/**
* ctucan_read_fault_state() - Reads CTU CAN FDs fault confinement state.
* @priv: Pointer to private data
*
* Returns: Fault confinement state of controller
*/
static enum can_state ctucan_read_fault_state(struct ctucan_priv *priv)
{
u32 fs;
u32 rec_tec;
u32 ewl;
fs = ctucan_read32(priv, CTUCANFD_EWL);
rec_tec = ctucan_read32(priv, CTUCANFD_REC);
ewl = FIELD_GET(REG_EWL_EW_LIMIT, fs);
if (FIELD_GET(REG_EWL_ERA, fs)) {
if (ewl > FIELD_GET(REG_REC_REC_VAL, rec_tec) &&
ewl > FIELD_GET(REG_REC_TEC_VAL, rec_tec))
return CAN_STATE_ERROR_ACTIVE;
else
return CAN_STATE_ERROR_WARNING;
} else if (FIELD_GET(REG_EWL_ERP, fs)) {
return CAN_STATE_ERROR_PASSIVE;
} else if (FIELD_GET(REG_EWL_BOF, fs)) {
return CAN_STATE_BUS_OFF;
}
WARN(true, "Invalid error state");
return CAN_STATE_ERROR_PASSIVE;
}
/**
* ctucan_get_rec_tec() - Reads REC/TEC counter values from controller
* @priv: Pointer to private data
* @bec: Pointer to Error counter structure
*/
static void ctucan_get_rec_tec(struct ctucan_priv *priv, struct can_berr_counter *bec)
{
u32 err_ctrs = ctucan_read32(priv, CTUCANFD_REC);
bec->rxerr = FIELD_GET(REG_REC_REC_VAL, err_ctrs);
bec->txerr = FIELD_GET(REG_REC_TEC_VAL, err_ctrs);
}
/**
* ctucan_err_interrupt() - Error frame ISR
* @ndev: net_device pointer
* @isr: interrupt status register value
*
* This is the CAN error interrupt and it will check the type of error and forward the error
* frame to upper layers.
*/
static void ctucan_err_interrupt(struct net_device *ndev, u32 isr)
{
struct ctucan_priv *priv = netdev_priv(ndev);
struct net_device_stats *stats = &ndev->stats;
struct can_frame *cf;
struct sk_buff *skb;
enum can_state state;
struct can_berr_counter bec;
u32 err_capt_alc;
int dologerr = net_ratelimit();
ctucan_get_rec_tec(priv, &bec);
state = ctucan_read_fault_state(priv);
err_capt_alc = ctucan_read32(priv, CTUCANFD_ERR_CAPT);
if (dologerr)
netdev_info(ndev, "%s: ISR = 0x%08x, rxerr %d, txerr %d, error type %lu, pos %lu, ALC id_field %lu, bit %lu\n",
__func__, isr, bec.rxerr, bec.txerr,
FIELD_GET(REG_ERR_CAPT_ERR_TYPE, err_capt_alc),
FIELD_GET(REG_ERR_CAPT_ERR_POS, err_capt_alc),
FIELD_GET(REG_ERR_CAPT_ALC_ID_FIELD, err_capt_alc),
FIELD_GET(REG_ERR_CAPT_ALC_BIT, err_capt_alc));
skb = alloc_can_err_skb(ndev, &cf);
/* EWLI: error warning limit condition met
* FCSI: fault confinement state changed
* ALI: arbitration lost (just informative)
* BEI: bus error interrupt
*/
if (FIELD_GET(REG_INT_STAT_FCSI, isr) || FIELD_GET(REG_INT_STAT_EWLI, isr)) {
netdev_info(ndev, "state changes from %s to %s\n",
ctucan_state_to_str(priv->can.state),
ctucan_state_to_str(state));
if (priv->can.state == state)
netdev_warn(ndev,
"current and previous state is the same! (missed interrupt?)\n");
priv->can.state = state;
switch (state) {
case CAN_STATE_BUS_OFF:
priv->can.can_stats.bus_off++;
can_bus_off(ndev);
if (skb)
cf->can_id |= CAN_ERR_BUSOFF;
break;
case CAN_STATE_ERROR_PASSIVE:
priv->can.can_stats.error_passive++;
if (skb) {
cf->can_id |= CAN_ERR_CRTL;
cf->data[1] = (bec.rxerr > 127) ?
CAN_ERR_CRTL_RX_PASSIVE :
CAN_ERR_CRTL_TX_PASSIVE;
cf->data[6] = bec.txerr;
cf->data[7] = bec.rxerr;
}
break;
case CAN_STATE_ERROR_WARNING:
priv->can.can_stats.error_warning++;
if (skb) {
cf->can_id |= CAN_ERR_CRTL;
cf->data[1] |= (bec.txerr > bec.rxerr) ?
CAN_ERR_CRTL_TX_WARNING :
CAN_ERR_CRTL_RX_WARNING;
cf->data[6] = bec.txerr;
cf->data[7] = bec.rxerr;
}
break;
case CAN_STATE_ERROR_ACTIVE:
cf->data[1] = CAN_ERR_CRTL_ACTIVE;
cf->data[6] = bec.txerr;
cf->data[7] = bec.rxerr;
break;
default:
netdev_warn(ndev, "unhandled error state (%d:%s)!\n",
state, ctucan_state_to_str(state));
break;
}
}
/* Check for Arbitration Lost interrupt */
if (FIELD_GET(REG_INT_STAT_ALI, isr)) {
if (dologerr)
netdev_info(ndev, "arbitration lost\n");
priv->can.can_stats.arbitration_lost++;
if (skb) {
cf->can_id |= CAN_ERR_LOSTARB;
cf->data[0] = CAN_ERR_LOSTARB_UNSPEC;
}
}
/* Check for Bus Error interrupt */
if (FIELD_GET(REG_INT_STAT_BEI, isr)) {
netdev_info(ndev, "bus error\n");
priv->can.can_stats.bus_error++;
stats->rx_errors++;
if (skb) {
cf->can_id |= CAN_ERR_PROT | CAN_ERR_BUSERROR;
cf->data[2] = CAN_ERR_PROT_UNSPEC;
cf->data[3] = CAN_ERR_PROT_LOC_UNSPEC;
}
}
if (skb) {
stats->rx_packets++;
stats->rx_bytes += cf->can_dlc;
netif_rx(skb);
}
}
/**
* ctucan_rx_poll() - Poll routine for rx packets (NAPI)
* @napi: NAPI structure pointer
* @quota: Max number of rx packets to be processed.
*
* This is the poll routine for rx part. It will process the packets maximux quota value.
*
* Return: Number of packets received
*/
static int ctucan_rx_poll(struct napi_struct *napi, int quota)
{
struct net_device *ndev = napi->dev;
struct ctucan_priv *priv = netdev_priv(ndev);
int work_done = 0;
u32 status;
u32 framecnt;
int res = 1;
framecnt = FIELD_GET(REG_RX_STATUS_RXFRC, ctucan_read32(priv, CTUCANFD_RX_STATUS));
while (framecnt && work_done < quota && res > 0) {
res = ctucan_rx(ndev);
work_done++;
framecnt = FIELD_GET(REG_RX_STATUS_RXFRC, ctucan_read32(priv, CTUCANFD_RX_STATUS));
}
/* Check for RX FIFO Overflow */
status = ctucan_read32(priv, CTUCANFD_STATUS);
if (FIELD_GET(REG_STATUS_DOR, status)) {
struct net_device_stats *stats = &ndev->stats;
struct can_frame *cf;
struct sk_buff *skb;
netdev_info(ndev, "rx_poll: rx fifo overflow\n");
stats->rx_over_errors++;
stats->rx_errors++;
skb = alloc_can_err_skb(ndev, &cf);
if (skb) {
cf->can_id |= CAN_ERR_CRTL;
cf->data[1] |= CAN_ERR_CRTL_RX_OVERFLOW;
stats->rx_packets++;
stats->rx_bytes += cf->can_dlc;
netif_rx(skb);
}
/* Clear Data Overrun */
ctucan_write32(priv, CTUCANFD_COMMAND, REG_COMMAND_CDO);
}
if (work_done)
can_led_event(ndev, CAN_LED_EVENT_RX);
if (!framecnt && res != 0) {
if (napi_complete_done(napi, work_done)) {
/* Clear and enable RBNEI. It is level-triggered, so
* there is no race condition.
*/
ctucan_write32(priv, CTUCANFD_INT_STAT, REG_INT_STAT_RBNEI);
ctucan_write32(priv, CTUCANFD_INT_MASK_CLR, REG_INT_STAT_RBNEI);
}
}
return work_done;
}
/**
* ctucan_rotate_txb_prio() - Rotates priorities of TXT Buffers
* @ndev: net_device pointer
*/
static void ctucan_rotate_txb_prio(struct net_device *ndev)
{
struct ctucan_priv *priv = netdev_priv(ndev);
u32 prio = priv->txb_prio;
prio = (prio << 4) | ((prio >> ((priv->ntxbufs - 1) * 4)) & 0xF);
ctucan_netdev_dbg(ndev, "%s: from 0x%08x to 0x%08x\n", __func__, priv->txb_prio, prio);
priv->txb_prio = prio;
ctucan_write32(priv, CTUCANFD_TX_PRIORITY, prio);
}
/**
* ctucan_tx_interrupt() - Tx done Isr
* @ndev: net_device pointer
*/
static void ctucan_tx_interrupt(struct net_device *ndev)
{
struct ctucan_priv *priv = netdev_priv(ndev);
struct net_device_stats *stats = &ndev->stats;
bool first = true;
bool some_buffers_processed;
unsigned long flags;
enum ctucan_txtb_status txtb_status;
u32 txtb_id;
/* read tx_status
* if txb[n].finished (bit 2)
* if ok -> echo
* if error / aborted -> ?? (find how to handle oneshot mode)
* txb_tail++
*/
do {
spin_lock_irqsave(&priv->tx_lock, flags);
some_buffers_processed = false;
while ((int)(priv->txb_head - priv->txb_tail) > 0) {
txtb_id = priv->txb_tail % priv->ntxbufs;
txtb_status = ctucan_get_tx_status(priv, txtb_id);
ctucan_netdev_dbg(ndev, "TXI: TXB#%u: status 0x%x\n", txtb_id, txtb_status);
switch (txtb_status) {
case TXT_TOK:
ctucan_netdev_dbg(ndev, "TXT_OK\n");
#if LINUX_VERSION_CODE >= KERNEL_VERSION(5, 12, 0)
can_get_echo_skb(ndev, txtb_id, NULL);
#else /* < 5.12.0 */
can_get_echo_skb(ndev, txtb_id);
#endif /* < 5.12.0 */
stats->tx_packets++;
break;
case TXT_ERR:
/* This indicated that retransmit limit has been reached. Obviously
* we should not echo the frame, but also not indicate any kind of
* error. If desired, it was already reported (possible multiple
* times) on each arbitration lost.
*/
netdev_warn(ndev, "TXB in Error state\n");
#if LINUX_VERSION_CODE >= KERNEL_VERSION(5, 12, 0)
can_free_echo_skb(ndev, txtb_id, NULL);
#else /* < 5.12.0 */
can_free_echo_skb(ndev, txtb_id);
#endif /* < 5.12.0 */
stats->tx_dropped++;
break;
case TXT_ABT:
/* Same as for TXT_ERR, only with different cause. We *could*
* re-queue the frame, but multiqueue/abort is not supported yet
* anyway.
*/
netdev_warn(ndev, "TXB in Aborted state\n");
#if LINUX_VERSION_CODE >= KERNEL_VERSION(5, 12, 0)
can_free_echo_skb(ndev, txtb_id, NULL);
#else /* < 5.12.0 */
can_free_echo_skb(ndev, txtb_id);
#endif /* < 5.12.0 */
stats->tx_dropped++;
break;
case TXT_NOT_EXIST:
/* "HW Bug?"" already reported so just advance tail */
priv->txb_tail++;
goto clear;
default:
/* Bug only if the first buffer is not finished, otherwise it is
* pretty much expected.
*/
if (first) {
netdev_err(ndev,
"BUG: TXB#%u not in a finished state (0x%x)!\n",
txtb_id, txtb_status);
spin_unlock_irqrestore(&priv->tx_lock, flags);
/* do not clear nor wake */
return;
}
goto clear;
}
priv->txb_tail++;
first = false;
some_buffers_processed = true;
/* Adjust priorities *before* marking the buffer as empty. */
ctucan_rotate_txb_prio(ndev);
ctucan_give_txtb_cmd(priv, TXT_CMD_SET_EMPTY, txtb_id);
}
clear:
spin_unlock_irqrestore(&priv->tx_lock, flags);
/* If no buffers were processed this time, we cannot clear - that would introduce
* a race condition.
*/
if (some_buffers_processed) {
/* Clear the interrupt again. We do not want to receive again interrupt for
* the buffer already handled. If it is the last finished one then it would
* cause log of spurious interrupt.
*/
ctucan_write32(priv, CTUCANFD_INT_STAT, REG_INT_STAT_TXBHCI);
}
} while (some_buffers_processed);
can_led_event(ndev, CAN_LED_EVENT_TX);
spin_lock_irqsave(&priv->tx_lock, flags);
/* Check if at least one TX buffer is free */
if (CTU_CAN_FD_TXTNF(priv))
netif_wake_queue(ndev);
spin_unlock_irqrestore(&priv->tx_lock, flags);
}
/**
* ctucan_interrupt() - CAN Isr
* @irq: irq number
* @dev_id: device id poniter
*
* This is the CTU CAN FD ISR. It checks for the type of interrupt
* and invokes the corresponding ISR.
*
* Return:
* IRQ_NONE - If CAN device is in sleep mode, IRQ_HANDLED otherwise
*/
static irqreturn_t ctucan_interrupt(int irq, void *dev_id)
{
struct net_device *ndev = (struct net_device *)dev_id;
struct ctucan_priv *priv = netdev_priv(ndev);
u32 isr, icr;
u32 imask;
int irq_loops;
ctucan_netdev_dbg(ndev, "%s\n", __func__);
for (irq_loops = 0; irq_loops < 10000; irq_loops++) {
/* Get the interrupt status */
isr = ctucan_read32(priv, CTUCANFD_INT_STAT);
if (!isr)
return irq_loops ? IRQ_HANDLED : IRQ_NONE;
/* Receive Buffer Not Empty Interrupt */
if (FIELD_GET(REG_INT_STAT_RBNEI, isr)) {
ctucan_netdev_dbg(ndev, "RXBNEI\n");
/* Mask RXBNEI the first, then clear interrupt and schedule NAPI. Even if
* another IRQ fires, RBNEI will always be 0 (masked).
*/
icr = REG_INT_STAT_RBNEI;
ctucan_write32(priv, CTUCANFD_INT_MASK_SET, icr);
ctucan_write32(priv, CTUCANFD_INT_STAT, icr);
napi_schedule(&priv->napi);
}
/* TXT Buffer HW Command Interrupt */
if (FIELD_GET(REG_INT_STAT_TXBHCI, isr)) {
ctucan_netdev_dbg(ndev, "TXBHCI\n");
/* Cleared inside */
ctucan_tx_interrupt(ndev);
}
/* Error interrupts */
if (FIELD_GET(REG_INT_STAT_EWLI, isr) ||
FIELD_GET(REG_INT_STAT_FCSI, isr) ||
FIELD_GET(REG_INT_STAT_ALI, isr)) {
icr = isr & (REG_INT_STAT_EWLI | REG_INT_STAT_FCSI | REG_INT_STAT_ALI);
ctucan_netdev_dbg(ndev, "some ERR interrupt: clearing 0x%08x\n", icr);
ctucan_write32(priv, CTUCANFD_INT_STAT, icr);
ctucan_err_interrupt(ndev, isr);
}
/* Ignore RI, TI, LFI, RFI, BSI */
}
netdev_err(ndev, "%s: stuck interrupt (isr=0x%08x), stopping\n", __func__, isr);
if (FIELD_GET(REG_INT_STAT_TXBHCI, isr)) {
int i;
netdev_err(ndev, "txb_head=0x%08x txb_tail=0x%08x\n",
priv->txb_head, priv->txb_tail);
for (i = 0; i < priv->ntxbufs; i++) {
u32 status = ctucan_get_tx_status(priv, i);
netdev_err(ndev, "txb[%d] txb status=0x%08x\n", i, status);
}
}
imask = 0xffffffff;
ctucan_write32(priv, CTUCANFD_INT_ENA_CLR, imask);
ctucan_write32(priv, CTUCANFD_INT_MASK_SET, imask);
return IRQ_HANDLED;
}
/**
* ctucan_chip_stop() - Driver stop routine
* @ndev: Pointer to net_device structure
*
* This is the drivers stop routine. It will disable the
* interrupts and disable the controller.
*/
static void ctucan_chip_stop(struct net_device *ndev)
{
struct ctucan_priv *priv = netdev_priv(ndev);
u32 mask = 0xffffffff;
u32 mode;
ctucan_netdev_dbg(ndev, "%s\n", __func__);
/* Disable interrupts and disable CAN */
ctucan_write32(priv, CTUCANFD_INT_ENA_CLR, mask);
ctucan_write32(priv, CTUCANFD_INT_MASK_SET, mask);
mode = ctucan_read32(priv, CTUCANFD_MODE);
mode &= ~REG_MODE_ENA;
ctucan_write32(priv, CTUCANFD_MODE, mode);
priv->can.state = CAN_STATE_STOPPED;
}
/**
* ctucan_open() - Driver open routine
* @ndev: Pointer to net_device structure
*
* This is the driver open routine.
* Return: 0 on success and failure value on error
*/
static int ctucan_open(struct net_device *ndev)
{
struct ctucan_priv *priv = netdev_priv(ndev);
int ret;
ctucan_netdev_dbg(ndev, "%s\n", __func__);
ret = pm_runtime_get_sync(priv->dev);
if (ret < 0) {
netdev_err(ndev, "%s: pm_runtime_get failed(%d)\n",
__func__, ret);
pm_runtime_put_noidle(priv->dev);
return ret;
}
ret = ctucan_reset(ndev);
if (ret < 0)
goto err_reset;
/* Common open */
ret = open_candev(ndev);
if (ret) {
netdev_warn(ndev, "open_candev failed!\n");
goto err_open;
}
ret = request_irq(ndev->irq, ctucan_interrupt, priv->irq_flags, ndev->name, ndev);
if (ret < 0) {
netdev_err(ndev, "irq allocation for CAN failed\n");
goto err_irq;
}
ret = ctucan_chip_start(ndev);
if (ret < 0) {
netdev_err(ndev, "ctucan_chip_start failed!\n");
goto err_chip_start;
}
netdev_info(ndev, "ctu_can_fd device registered\n");
can_led_event(ndev, CAN_LED_EVENT_OPEN);
napi_enable(&priv->napi);
netif_start_queue(ndev);
return 0;
err_chip_start:
free_irq(ndev->irq, ndev);
err_irq:
close_candev(ndev);
err_open:
err_reset:
pm_runtime_put(priv->dev);
return ret;
}
/**
* ctucan_close() - Driver close routine
* @ndev: Pointer to net_device structure
*
* Return: 0 always
*/
static int ctucan_close(struct net_device *ndev)
{
struct ctucan_priv *priv = netdev_priv(ndev);
ctucan_netdev_dbg(ndev, "%s\n", __func__);
netif_stop_queue(ndev);
napi_disable(&priv->napi);
ctucan_chip_stop(ndev);
free_irq(ndev->irq, ndev);
close_candev(ndev);
can_led_event(ndev, CAN_LED_EVENT_STOP);
pm_runtime_put(priv->dev);
return 0;
}
/**
* ctucan_get_berr_counter() - error counter routine
* @ndev: Pointer to net_device structure
* @bec: Pointer to can_berr_counter structure
*
* This is the driver error counter routine.
* Return: 0 on success and failure value on error
*/
static int ctucan_get_berr_counter(const struct net_device *ndev, struct can_berr_counter *bec)
{
struct ctucan_priv *priv = netdev_priv(ndev);
int ret;
ctucan_netdev_dbg(ndev, "%s\n", __func__);
ret = pm_runtime_get_sync(priv->dev);
if (ret < 0) {
netdev_err(ndev, "%s: pm_runtime_get failed(%d)\n", __func__, ret);
pm_runtime_put_noidle(priv->dev);
return ret;
}
ctucan_get_rec_tec(priv, bec);
pm_runtime_put(priv->dev);
return 0;
}
static const struct net_device_ops ctucan_netdev_ops = {
.ndo_open = ctucan_open,
.ndo_stop = ctucan_close,
.ndo_start_xmit = ctucan_start_xmit,
.ndo_change_mtu = can_change_mtu,
};
int ctucan_suspend(struct device *dev)
{
struct net_device *ndev = dev_get_drvdata(dev);
struct ctucan_priv *priv = netdev_priv(ndev);
ctucan_netdev_dbg(ndev, "%s\n", __func__);
if (netif_running(ndev)) {
netif_stop_queue(ndev);
netif_device_detach(ndev);
}
priv->can.state = CAN_STATE_SLEEPING;
return 0;
}
EXPORT_SYMBOL(ctucan_suspend);
int ctucan_resume(struct device *dev)
{
struct net_device *ndev = dev_get_drvdata(dev);
struct ctucan_priv *priv = netdev_priv(ndev);
ctucan_netdev_dbg(ndev, "%s\n", __func__);
priv->can.state = CAN_STATE_ERROR_ACTIVE;
if (netif_running(ndev)) {
netif_device_attach(ndev);
netif_start_queue(ndev);
}
return 0;
}
EXPORT_SYMBOL(ctucan_resume);
int ctucan_probe_common(struct device *dev, void __iomem *addr, int irq,
unsigned long can_clk_rate, int pm_enable_call,
void (*set_drvdata_fnc)(struct device *dev, struct net_device *ndev))
{
struct ctucan_priv *priv;
struct net_device *ndev;
int ret;
/* Create a CAN device instance for 8 (max) ntxbufs */
ndev = alloc_candev(sizeof(struct ctucan_priv), 8);
if (!ndev)
return -ENOMEM;
priv = netdev_priv(ndev);
spin_lock_init(&priv->tx_lock);
INIT_LIST_HEAD(&priv->peers_on_pdev);
priv->dev = dev;
priv->can.bittiming_const = &ctu_can_fd_bit_timing_max;
priv->can.data_bittiming_const = &ctu_can_fd_bit_timing_data_max;
priv->can.do_set_mode = ctucan_do_set_mode;
/* Needed for timing adjustment to be performed as soon as possible */
priv->can.do_set_bittiming = ctucan_set_bittiming;
priv->can.do_set_data_bittiming = ctucan_set_data_bittiming;
priv->can.do_get_berr_counter = ctucan_get_berr_counter;
priv->can.ctrlmode_supported = CAN_CTRLMODE_LOOPBACK
| CAN_CTRLMODE_LISTENONLY
| CAN_CTRLMODE_FD
| CAN_CTRLMODE_PRESUME_ACK
| CAN_CTRLMODE_BERR_REPORTING
| CAN_CTRLMODE_FD_NON_ISO
| CAN_CTRLMODE_ONE_SHOT;
priv->mem_base = addr;
/* Get IRQ for the device */
ndev->irq = irq;
ndev->flags |= IFF_ECHO; /* We support local echo */
if (set_drvdata_fnc)
set_drvdata_fnc(dev, ndev);
SET_NETDEV_DEV(ndev, dev);
ndev->netdev_ops = &ctucan_netdev_ops;
/* Getting the can_clk info */
if (!can_clk_rate) {
priv->can_clk = devm_clk_get(dev, NULL);
if (IS_ERR(priv->can_clk)) {
dev_err(dev, "Device clock not found.\n");
ret = PTR_ERR(priv->can_clk);
goto err_free;
}
can_clk_rate = clk_get_rate(priv->can_clk);
}
priv->write_reg = ctucan_write32_le;
priv->read_reg = ctucan_read32_le;
if (pm_enable_call)
pm_runtime_enable(dev);
ret = pm_runtime_get_sync(dev);
if (ret < 0) {
dev_err(dev, "%s: pm_runtime_get failed(%d)\n",
__func__, ret);
pm_runtime_put_noidle(priv->dev);
goto err_pmdisable;
}
/* Check for big-endianity and set according IO-accessors */
if ((ctucan_read32(priv, CTUCANFD_DEVICE_ID) & 0xFFFF) != CTUCANFD_ID) {
priv->write_reg = ctucan_write32_be;
priv->read_reg = ctucan_read32_be;
if ((ctucan_read32(priv, CTUCANFD_DEVICE_ID) & 0xFFFF) != CTUCANFD_ID) {
dev_err(dev, "CTU_CAN_FD signature not found\n");
ret = -ENODEV;
goto err_deviceoff;
}
}
priv->ntxbufs = FIELD_GET(REG_TX_COMMAND_TXT_BUFFER_COUNT, ctucan_read32(priv, CTUCANFD_TX_COMMAND));
dev_dbg(dev, "txt buffers: %d detected", priv->ntxbufs);
ret = ctucan_reset(ndev);
if (ret < 0)
goto err_deviceoff;
priv->can.clock.freq = can_clk_rate;
netif_napi_add(ndev, &priv->napi, ctucan_rx_poll, NAPI_POLL_WEIGHT);
ret = register_candev(ndev);
if (ret) {
dev_err(dev, "fail to register failed (err=%d)\n", ret);
goto err_deviceoff;
}
devm_can_led_init(ndev);
pm_runtime_put(dev);
netdev_dbg(ndev, "mem_base=0x%p irq=%d clock=%d, no. of txt buffers:%d\n",
priv->mem_base, ndev->irq, priv->can.clock.freq, priv->ntxbufs);
return 0;
err_deviceoff:
pm_runtime_put(priv->dev);
err_pmdisable:
if (pm_enable_call)
pm_runtime_disable(dev);
err_free:
list_del_init(&priv->peers_on_pdev);
free_candev(ndev);
return ret;
}
EXPORT_SYMBOL(ctucan_probe_common);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Martin Jerabek <[email protected]>");
MODULE_AUTHOR("Pavel Pisa <[email protected]>");
MODULE_AUTHOR("Ondrej Ille <[email protected]>");
MODULE_DESCRIPTION("CTU CAN FD interface");
|
809451.c | /*
* USB device quirk handling logic and table
*
* Copyright (c) 2007 Oliver Neukum
* Copyright (c) 2007 Greg Kroah-Hartman <[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, version 2.
*
*
*/
#include <linux/usb.h>
#include <linux/usb/quirks.h>
#include <linux/usb/hcd.h>
#include "usb.h"
/* Lists of quirky USB devices, split in device quirks and interface quirks.
* Device quirks are applied at the very beginning of the enumeration process,
* right after reading the device descriptor. They can thus only match on device
* information.
*
* Interface quirks are applied after reading all the configuration descriptors.
* They can match on both device and interface information.
*
* Note that the DELAY_INIT and HONOR_BNUMINTERFACES quirks do not make sense as
* interface quirks, as they only influence the enumeration process which is run
* before processing the interface quirks.
*
* Please keep the lists ordered by:
* 1) Vendor ID
* 2) Product ID
* 3) Class ID
*/
static const struct usb_device_id usb_quirk_list[] = {
/* CBM - Flash disk */
{ USB_DEVICE(0x0204, 0x6025), .driver_info = USB_QUIRK_RESET_RESUME },
/* HP 5300/5370C scanner */
{ USB_DEVICE(0x03f0, 0x0701), .driver_info =
USB_QUIRK_STRING_FETCH_255 },
/* Creative SB Audigy 2 NX */
{ USB_DEVICE(0x041e, 0x3020), .driver_info = USB_QUIRK_RESET_RESUME },
/* Microsoft Wireless Laser Mouse 6000 Receiver */
{ USB_DEVICE(0x045e, 0x00e1), .driver_info = USB_QUIRK_RESET_RESUME },
/* Microsoft LifeCam-VX700 v2.0 */
{ USB_DEVICE(0x045e, 0x0770), .driver_info = USB_QUIRK_RESET_RESUME },
/* Logitech HD Pro Webcams C920 and C930e */
{ USB_DEVICE(0x046d, 0x082d), .driver_info = USB_QUIRK_DELAY_INIT },
{ USB_DEVICE(0x046d, 0x0843), .driver_info = USB_QUIRK_DELAY_INIT },
/* Logitech ConferenceCam CC3000e */
{ USB_DEVICE(0x046d, 0x0847), .driver_info = USB_QUIRK_DELAY_INIT },
{ USB_DEVICE(0x046d, 0x0848), .driver_info = USB_QUIRK_DELAY_INIT },
/* Logitech PTZ Pro Camera */
{ USB_DEVICE(0x046d, 0x0853), .driver_info = USB_QUIRK_DELAY_INIT },
/* Logitech Quickcam Fusion */
{ USB_DEVICE(0x046d, 0x08c1), .driver_info = USB_QUIRK_RESET_RESUME },
/* Logitech Quickcam Orbit MP */
{ USB_DEVICE(0x046d, 0x08c2), .driver_info = USB_QUIRK_RESET_RESUME },
/* Logitech Quickcam Pro for Notebook */
{ USB_DEVICE(0x046d, 0x08c3), .driver_info = USB_QUIRK_RESET_RESUME },
/* Logitech Quickcam Pro 5000 */
{ USB_DEVICE(0x046d, 0x08c5), .driver_info = USB_QUIRK_RESET_RESUME },
/* Logitech Quickcam OEM Dell Notebook */
{ USB_DEVICE(0x046d, 0x08c6), .driver_info = USB_QUIRK_RESET_RESUME },
/* Logitech Quickcam OEM Cisco VT Camera II */
{ USB_DEVICE(0x046d, 0x08c7), .driver_info = USB_QUIRK_RESET_RESUME },
/* Logitech Harmony 700-series */
{ USB_DEVICE(0x046d, 0xc122), .driver_info = USB_QUIRK_DELAY_INIT },
/* Philips PSC805 audio device */
{ USB_DEVICE(0x0471, 0x0155), .driver_info = USB_QUIRK_RESET_RESUME },
/* Plantronic Audio 655 DSP */
{ USB_DEVICE(0x047f, 0xc008), .driver_info = USB_QUIRK_RESET_RESUME },
/* Plantronic Audio 648 USB */
{ USB_DEVICE(0x047f, 0xc013), .driver_info = USB_QUIRK_RESET_RESUME },
/* Artisman Watchdog Dongle */
{ USB_DEVICE(0x04b4, 0x0526), .driver_info =
USB_QUIRK_CONFIG_INTF_STRINGS },
/* Microchip Joss Optical infrared touchboard device */
{ USB_DEVICE(0x04d8, 0x000c), .driver_info =
USB_QUIRK_CONFIG_INTF_STRINGS },
/* CarrolTouch 4000U */
{ USB_DEVICE(0x04e7, 0x0009), .driver_info = USB_QUIRK_RESET_RESUME },
/* CarrolTouch 4500U */
{ USB_DEVICE(0x04e7, 0x0030), .driver_info = USB_QUIRK_RESET_RESUME },
/* Samsung Android phone modem - ID conflict with SPH-I500 */
{ USB_DEVICE(0x04e8, 0x6601), .driver_info =
USB_QUIRK_CONFIG_INTF_STRINGS },
/* Elan Touchscreen */
{ USB_DEVICE(0x04f3, 0x0089), .driver_info =
USB_QUIRK_DEVICE_QUALIFIER },
{ USB_DEVICE(0x04f3, 0x009b), .driver_info =
USB_QUIRK_DEVICE_QUALIFIER },
{ USB_DEVICE(0x04f3, 0x010c), .driver_info =
USB_QUIRK_DEVICE_QUALIFIER },
{ USB_DEVICE(0x04f3, 0x0125), .driver_info =
USB_QUIRK_DEVICE_QUALIFIER },
{ USB_DEVICE(0x04f3, 0x016f), .driver_info =
USB_QUIRK_DEVICE_QUALIFIER },
/* Roland SC-8820 */
{ USB_DEVICE(0x0582, 0x0007), .driver_info = USB_QUIRK_RESET_RESUME },
/* Edirol SD-20 */
{ USB_DEVICE(0x0582, 0x0027), .driver_info = USB_QUIRK_RESET_RESUME },
/* Alcor Micro Corp. Hub */
{ USB_DEVICE(0x058f, 0x9254), .driver_info = USB_QUIRK_RESET_RESUME },
/* appletouch */
{ USB_DEVICE(0x05ac, 0x021a), .driver_info = USB_QUIRK_RESET_RESUME },
/* Avision AV600U */
{ USB_DEVICE(0x0638, 0x0a13), .driver_info =
USB_QUIRK_STRING_FETCH_255 },
/* Saitek Cyborg Gold Joystick */
{ USB_DEVICE(0x06a3, 0x0006), .driver_info =
USB_QUIRK_CONFIG_INTF_STRINGS },
/* Guillemot Webcam Hercules Dualpix Exchange (2nd ID) */
{ USB_DEVICE(0x06f8, 0x0804), .driver_info = USB_QUIRK_RESET_RESUME },
/* Guillemot Webcam Hercules Dualpix Exchange*/
{ USB_DEVICE(0x06f8, 0x3005), .driver_info = USB_QUIRK_RESET_RESUME },
/* Midiman M-Audio Keystation 88es */
{ USB_DEVICE(0x0763, 0x0192), .driver_info = USB_QUIRK_RESET_RESUME },
/* M-Systems Flash Disk Pioneers */
{ USB_DEVICE(0x08ec, 0x1000), .driver_info = USB_QUIRK_RESET_RESUME },
/* Keytouch QWERTY Panel keyboard */
{ USB_DEVICE(0x0926, 0x3333), .driver_info =
USB_QUIRK_CONFIG_INTF_STRINGS },
/* X-Rite/Gretag-Macbeth Eye-One Pro display colorimeter */
{ USB_DEVICE(0x0971, 0x2000), .driver_info = USB_QUIRK_NO_SET_INTF },
/* Broadcom BCM92035DGROM BT dongle */
{ USB_DEVICE(0x0a5c, 0x2021), .driver_info = USB_QUIRK_RESET_RESUME },
/* MAYA44USB sound device */
{ USB_DEVICE(0x0a92, 0x0091), .driver_info = USB_QUIRK_RESET_RESUME },
/* Action Semiconductor flash disk */
{ USB_DEVICE(0x10d6, 0x2200), .driver_info =
USB_QUIRK_STRING_FETCH_255 },
/* SKYMEDI USB_DRIVE */
{ USB_DEVICE(0x1516, 0x8628), .driver_info = USB_QUIRK_RESET_RESUME },
/* Razer - Razer Blade Keyboard */
{ USB_DEVICE(0x1532, 0x0116), .driver_info =
USB_QUIRK_LINEAR_UFRAME_INTR_BINTERVAL },
/* BUILDWIN Photo Frame */
{ USB_DEVICE(0x1908, 0x1315), .driver_info =
USB_QUIRK_HONOR_BNUMINTERFACES },
/* INTEL VALUE SSD */
{ USB_DEVICE(0x8086, 0xf1a5), .driver_info = USB_QUIRK_RESET_RESUME },
/* USB3503 */
{ USB_DEVICE(0x0424, 0x3503), .driver_info = USB_QUIRK_RESET_RESUME },
/* ASUS Base Station(T100) */
{ USB_DEVICE(0x0b05, 0x17e0), .driver_info =
USB_QUIRK_IGNORE_REMOTE_WAKEUP },
/* Protocol and OTG Electrical Test Device */
{ USB_DEVICE(0x1a0a, 0x0200), .driver_info =
USB_QUIRK_LINEAR_UFRAME_INTR_BINTERVAL },
/* Blackmagic Design Intensity Shuttle */
{ USB_DEVICE(0x1edb, 0xbd3b), .driver_info = USB_QUIRK_NO_LPM },
/* Blackmagic Design UltraStudio SDI */
{ USB_DEVICE(0x1edb, 0xbd4f), .driver_info = USB_QUIRK_NO_LPM },
{ } /* terminating entry must be last */
};
static const struct usb_device_id usb_interface_quirk_list[] = {
/* Logitech UVC Cameras */
{ USB_VENDOR_AND_INTERFACE_INFO(0x046d, USB_CLASS_VIDEO, 1, 0),
.driver_info = USB_QUIRK_RESET_RESUME },
{ } /* terminating entry must be last */
};
static const struct usb_device_id usb_amd_resume_quirk_list[] = {
/* Lenovo Mouse with Pixart controller */
{ USB_DEVICE(0x17ef, 0x602e), .driver_info = USB_QUIRK_RESET_RESUME },
/* Pixart Mouse */
{ USB_DEVICE(0x093a, 0x2500), .driver_info = USB_QUIRK_RESET_RESUME },
{ USB_DEVICE(0x093a, 0x2510), .driver_info = USB_QUIRK_RESET_RESUME },
{ USB_DEVICE(0x093a, 0x2521), .driver_info = USB_QUIRK_RESET_RESUME },
/* Logitech Optical Mouse M90/M100 */
{ USB_DEVICE(0x046d, 0xc05a), .driver_info = USB_QUIRK_RESET_RESUME },
{ } /* terminating entry must be last */
};
static bool usb_match_any_interface(struct usb_device *udev,
const struct usb_device_id *id)
{
unsigned int i;
for (i = 0; i < udev->descriptor.bNumConfigurations; ++i) {
struct usb_host_config *cfg = &udev->config[i];
unsigned int j;
for (j = 0; j < cfg->desc.bNumInterfaces; ++j) {
struct usb_interface_cache *cache;
struct usb_host_interface *intf;
cache = cfg->intf_cache[j];
if (cache->num_altsetting == 0)
continue;
intf = &cache->altsetting[0];
if (usb_match_one_id_intf(udev, intf, id))
return true;
}
}
return false;
}
static int usb_amd_resume_quirk(struct usb_device *udev)
{
struct usb_hcd *hcd;
hcd = bus_to_hcd(udev->bus);
/* The device should be attached directly to root hub */
if (udev->level == 1 && hcd->amd_resume_bug == 1)
return 1;
return 0;
}
static u32 __usb_detect_quirks(struct usb_device *udev,
const struct usb_device_id *id)
{
u32 quirks = 0;
for (; id->match_flags; id++) {
if (!usb_match_device(udev, id))
continue;
if ((id->match_flags & USB_DEVICE_ID_MATCH_INT_INFO) &&
!usb_match_any_interface(udev, id))
continue;
quirks |= (u32)(id->driver_info);
}
return quirks;
}
/*
* Detect any quirks the device has, and do any housekeeping for it if needed.
*/
void usb_detect_quirks(struct usb_device *udev)
{
udev->quirks = __usb_detect_quirks(udev, usb_quirk_list);
/*
* Pixart-based mice would trigger remote wakeup issue on AMD
* Yangtze chipset, so set them as RESET_RESUME flag.
*/
if (usb_amd_resume_quirk(udev))
udev->quirks |= __usb_detect_quirks(udev,
usb_amd_resume_quirk_list);
if (udev->quirks)
dev_dbg(&udev->dev, "USB quirks for this device: %x\n",
udev->quirks);
#ifdef CONFIG_USB_DEFAULT_PERSIST
if (!(udev->quirks & USB_QUIRK_RESET))
udev->persist_enabled = 1;
#else
/* Hubs are automatically enabled for USB-PERSIST */
if (udev->descriptor.bDeviceClass == USB_CLASS_HUB)
udev->persist_enabled = 1;
#endif /* CONFIG_USB_DEFAULT_PERSIST */
}
void usb_detect_interface_quirks(struct usb_device *udev)
{
u32 quirks;
quirks = __usb_detect_quirks(udev, usb_interface_quirk_list);
if (quirks == 0)
return;
dev_dbg(&udev->dev, "USB interface quirks for this device: %x\n",
quirks);
udev->quirks |= quirks;
}
|
293722.c | /****************************************************************************
* @file main.c
* @version V3.00
* @brief Transmit and receive data in UART RS485 mode.
*
* @copyright SPDX-License-Identifier: Apache-2.0
* @copyright Copyright (C) 2020 Nuvoton Technology Corp. All rights reserved.
******************************************************************************/
#include <stdio.h>
#include "NuMicro.h"
#define RS485_ADDRSS1 0xC0
#define RS485_ADDRSS2 0xA2
#define RS485_ADDRSS3 0xB1
#define RS485_ADDRSS4 0xD3
#define ADDR_NUM 4
#define DATA_NUM 10
/*---------------------------------------------------------------------------------------------------------*/
/* Global variable */
/*---------------------------------------------------------------------------------------------------------*/
static volatile uint32_t g_au32AddrBuffer[ADDR_NUM];
static volatile uint32_t g_au32DataBuffer[ADDR_NUM][DATA_NUM];
static uint8_t g_u8AddrIndex = 0;
static uint8_t g_u8DataIndex = 0;
static volatile uint8_t g_u8ReceiveDone = 0;
/*---------------------------------------------------------------------------------------------------------*/
/* Define functions prototype */
/*---------------------------------------------------------------------------------------------------------*/
extern char GetChar(void);
void RS485_HANDLE(void);
void RS485_9bitModeSlave(void);
void RS485_FunctionTest(void);
void USCI0_IRQHandler(void);
void RS485_SendAddressByte(uint8_t u8data);
void RS485_SendDataByte(uint8_t *pu8TxBuf, uint32_t u32WriteBytes);
void RS485_9bitModeMaster(void);
void UART0_Init(void);
void USCI0_Init(void);
void SYS_Init(void);
/*---------------------------------------------------------------------------------------------------------*/
/* ISR to handle USCI interrupt event */
/*---------------------------------------------------------------------------------------------------------*/
void USCI0_IRQHandler(void)
{
RS485_HANDLE();
}
/*---------------------------------------------------------------------------------------------------------*/
/* RS485 Callback function */
/*---------------------------------------------------------------------------------------------------------*/
void RS485_HANDLE(void)
{
volatile uint32_t u32ProtSts = UUART_GET_PROT_STATUS(UUART0);
volatile uint32_t u32BufSts = UUART_GET_BUF_STATUS(UUART0);
uint32_t u32Data;
if(u32ProtSts & UUART_PROTSTS_RXENDIF_Msk) /* Receive end interrupt */
{
/* Handle received data */
UUART_CLR_PROT_INT_FLAG(UUART0, UUART_PROTSTS_RXENDIF_Msk);
u32Data = UUART_READ(UUART0);
if(u32Data & 0x100)
g_au32AddrBuffer[g_u8AddrIndex++] = u32Data;
else
{
g_au32DataBuffer[g_u8AddrIndex - 1][g_u8DataIndex++] = u32Data;
if(g_u8DataIndex == DATA_NUM)
{
if(g_u8AddrIndex == ADDR_NUM)
g_u8ReceiveDone = 1;
else
g_u8DataIndex = 0;
}
}
}
else if(u32BufSts & UUART_BUFSTS_RXOVIF_Msk) /* Receive buffer over-run error interrupt */
{
UUART_CLR_BUF_INT_FLAG(UUART0, UUART_BUFSTS_RXOVIF_Msk);
printf("\nBuffer Error...\n");
}
}
/*---------------------------------------------------------------------------------------------------------*/
/* RS485 Receive Test */
/*---------------------------------------------------------------------------------------------------------*/
void RS485_9bitModeSlave(void)
{
/* Set UART line configuration and control signal output inverse */
UUART_SetLine_Config(UUART0, 0, UUART_WORD_LEN_9, UUART_PARITY_NONE, UUART_STOP_BIT_1);
UUART0->LINECTL |= UUART_LINECTL_CTLOINV_Msk;
/* Enable RTS auto direction function */
UUART0->PROTCTL |= UUART_PROTCTL_RTSAUDIREN_Msk;
printf("+-----------------------------------------------------------+\n");
printf("| RS485 Mode |\n");
printf("+-----------------------------------------------------------+\n");
printf("| The function is used to test 9-bit slave mode. |\n");
printf("| Receive address and data byte. |\n");
printf("+-----------------------------------------------------------+\n");
/* Enable USCI receive end and receive buffer over-run error Interrupt */
UUART_ENABLE_TRANS_INT(UUART0, UUART_INTEN_RXENDIEN_Msk);
UUART_ENABLE_BUF_INT(UUART0, UUART_BUFCTL_RXOVIEN_Msk);
NVIC_EnableIRQ(USCI0_IRQn);
printf("Ready to receive data...\n");
/* Wait receive complete */
while(g_u8ReceiveDone == 0);
for(g_u8AddrIndex = 0; g_u8AddrIndex < ADDR_NUM; g_u8AddrIndex++)
{
printf("\nAddr=0x%x,Get:", (g_au32AddrBuffer[g_u8AddrIndex] & 0xFF));
for(g_u8DataIndex = 0; g_u8DataIndex < DATA_NUM; g_u8DataIndex++)
printf("%d,", (g_au32DataBuffer[g_u8AddrIndex][g_u8DataIndex] & 0xFF));
}
/* Disable USCI interrupt */
UUART_DISABLE_TRANS_INT(UUART0, UUART_INTEN_RXENDIEN_Msk);
UUART_DISABLE_BUF_INT(UUART0, UUART_BUFCTL_RXOVIEN_Msk);
NVIC_DisableIRQ(USCI0_IRQn);
printf("\nEnd test\n");
}
/*---------------------------------------------------------------------------------------------------------*/
/* RS485 Transmit Control (Address Byte: Parity Bit =1 , Data Byte:Parity Bit =0) */
/*---------------------------------------------------------------------------------------------------------*/
void RS485_SendAddressByte(uint8_t u8data)
{
UUART_WRITE(UUART0, (0x100 | u8data));
}
void RS485_SendDataByte(uint8_t *pu8TxBuf, uint32_t u32WriteBytes)
{
uint32_t u32Count;
for(u32Count = 0; u32Count != u32WriteBytes; u32Count++)
{
while(UUART_GET_TX_FULL(UUART0)); /* Wait if Tx is full */
UUART_WRITE(UUART0, pu8TxBuf[u32Count]); /* Send UART Data from buffer */
}
}
/*---------------------------------------------------------------------------------------------------------*/
/* RS485 Transmit Test */
/*---------------------------------------------------------------------------------------------------------*/
void RS485_9bitModeMaster(void)
{
int32_t i32Idx;
uint8_t g_u8SendDataGroup1[10] = {0};
uint8_t g_u8SendDataGroup2[10] = {0};
uint8_t g_u8SendDataGroup3[10] = {0};
uint8_t g_u8SendDataGroup4[10] = {0};
printf("\n");
printf("+-----------------------------------------------------------+\n");
printf("| RS485 9-bit Master Test |\n");
printf("+-----------------------------------------------------------+\n");
printf("| The function will send different address with 10 data |\n");
printf("| bytes to test RS485 9-bit mode. Please connect TX/RX to |\n");
printf("| another board and wait its ready to receive. |\n");
printf("| Press any key to start... |\n");
printf("+-----------------------------------------------------------+\n\n");
GetChar();
/* Set UART line configuration and control signal output inverse */
UUART_SetLine_Config(UUART0, 0, UUART_WORD_LEN_9, UUART_PARITY_NONE, UUART_STOP_BIT_1);
UUART0->LINECTL |= UUART_LINECTL_CTLOINV_Msk;
/* Enable RTS auto direction function */
UUART0->PROTCTL |= UUART_PROTCTL_RTSAUDIREN_Msk;
/* Prepare data to transmit */
for(i32Idx = 0; i32Idx < 10; i32Idx++)
{
g_u8SendDataGroup1[i32Idx] = (uint8_t)i32Idx;
g_u8SendDataGroup2[i32Idx] = (uint8_t)i32Idx + 10;
g_u8SendDataGroup3[i32Idx] = (uint8_t)i32Idx + 20;
g_u8SendDataGroup4[i32Idx] = (uint8_t)i32Idx + 30;
}
/* Send different address and data for test */
printf("Send Address %x and data 0~9\n", RS485_ADDRSS1);
RS485_SendAddressByte(RS485_ADDRSS1);
RS485_SendDataByte(g_u8SendDataGroup1, 10);
printf("Send Address %x and data 10~19\n", RS485_ADDRSS2);
RS485_SendAddressByte(RS485_ADDRSS2);
RS485_SendDataByte(g_u8SendDataGroup2, 10);
printf("Send Address %x and data 20~29\n", RS485_ADDRSS3);
RS485_SendAddressByte(RS485_ADDRSS3);
RS485_SendDataByte(g_u8SendDataGroup3, 10);
printf("Send Address %x and data 30~39\n", RS485_ADDRSS4);
RS485_SendAddressByte(RS485_ADDRSS4);
RS485_SendDataByte(g_u8SendDataGroup4, 10);
printf("Transfer Done\n");
}
/*---------------------------------------------------------------------------------------------------------*/
/* RS485 Function Test */
/*---------------------------------------------------------------------------------------------------------*/
void RS485_FunctionTest(void)
{
uint32_t u32Item;
printf("\n");
printf("+-----------------------------------------------------------+\n");
printf("| Pin Configure |\n");
printf("+-----------------------------------------------------------+\n");
printf("| ______ _____ |\n");
printf("| | | | | |\n");
printf("| |Master| |Slave| |\n");
printf("| | TX|--USCI0_DAT1(PE.4) USCI0_DAT0(PE.3)--|RX | |\n");
printf("| | RTS|--USCI0_CTL1(PE.5) USCI0_CTL1(PE.5)--|RTS | |\n");
printf("| |______| |_____| |\n");
printf("| |\n");
printf("+-----------------------------------------------------------+\n");
printf("| RS485 Function Test |\n");
printf("+-----------------------------------------------------------+\n");
printf("| Please select Master or Slave test |\n");
printf("| [0] Master [1] Slave |\n");
printf("+-----------------------------------------------------------+\n\n");
u32Item = (uint32_t)getchar();
/*
The sample code is used to test RS485 9-bit mode and needs
two Module test board to complete the test.
Master:
1.Set RTS auto direction enabled and HW will control RTS pin. CTLOINV is set to '1'.
2.Master will send four different address with 10 bytes data to test Slave.
3.Address bytes : the parity bit should be '1'.
4.Data bytes : the parity bit should be '0'.
5.RTS pin is low in idle state. When master is sending, RTS pin will be pull high.
Slave:
1.Set RTS auto direction enabled and HW will control RTS pin. CTLOINV is set to '1'.
2.The received byte, parity bit is '1' , is considered "ADDRESS".
3.The received byte, parity bit is '0' , is considered "DATA".
Note: User can measure transmitted data waveform on TX and RX pin.
RTS pin is used for RS485 transceiver to control transmission direction.
RTS pin is low in idle state. When master is sending data, RTS pin will be pull high.
The connection to RS485 transceiver is as following figure for reference.
__________ ___________ ___________ __________
| | | | | | | |
|Master | |RS485 | |RS485 | |Slave |
| UART_TX |---|Transceiver|<==>|Transceiver|----| UART_RX |
| UART_RTS |---| | | |----| UART_RTS |
|__________| |___________| |___________| |__________|
*/
if(u32Item == '0')
RS485_9bitModeMaster();
else
RS485_9bitModeSlave();
}
void SYS_Init(void)
{
/* Set PF multi-function pins for XT1_OUT(PF.2) and XT1_IN(PF.3) */
SYS->GPF_MFPL = (SYS->GPF_MFPL & (~SYS_GPF_MFPL_PF2MFP_Msk)) | SYS_GPF_MFPL_PF2MFP_XT1_OUT;
SYS->GPF_MFPL = (SYS->GPF_MFPL & (~SYS_GPF_MFPL_PF3MFP_Msk)) | SYS_GPF_MFPL_PF3MFP_XT1_IN;
/*---------------------------------------------------------------------------------------------------------*/
/* Init System Clock */
/*---------------------------------------------------------------------------------------------------------*/
/* Enable HIRC and HXT clock */
CLK_EnableXtalRC(CLK_PWRCTL_HIRCEN_Msk | CLK_PWRCTL_HXTEN_Msk);
/* Wait for HIRC and HXT clock ready */
CLK_WaitClockReady(CLK_STATUS_HIRCSTB_Msk | CLK_STATUS_HXTSTB_Msk);
/* Set core clock to 96MHz */
CLK_SetCoreClock(96000000);
/* Enable UART and USCI module clock */
CLK_EnableModuleClock(UART0_MODULE);
CLK_EnableModuleClock(USCI0_MODULE);
/* Select UART0 module clock source as HIRC and UART0 module clock divider as 1 */
CLK_SetModuleClock(UART0_MODULE, CLK_CLKSEL2_UART0SEL_HIRC, CLK_CLKDIV0_UART0(1));
/*---------------------------------------------------------------------------------------------------------*/
/* Init I/O Multi-function */
/*---------------------------------------------------------------------------------------------------------*/
/* Set multi-function pins for UART0 RXD and TXD */
SYS->GPA_MFPL = (SYS->GPA_MFPL & (~(UART0_RXD_PA6_Msk | UART0_TXD_PA7_Msk))) | UART0_RXD_PA6 | UART0_TXD_PA7;
/* Set PE multi-function pins for USCI0_DAT0(PE.3), USCI0_DAT1(PE.4) and USCI0_CTL1(PE.5) */
SYS->GPE_MFPL = (SYS->GPE_MFPL & (~SYS_GPE_MFPL_PE3MFP_Msk)) | SYS_GPE_MFPL_PE3MFP_USCI0_DAT0;
SYS->GPE_MFPL = (SYS->GPE_MFPL & (~SYS_GPE_MFPL_PE4MFP_Msk)) | SYS_GPE_MFPL_PE4MFP_USCI0_DAT1;
SYS->GPE_MFPL = (SYS->GPE_MFPL & (~SYS_GPE_MFPL_PE5MFP_Msk)) | SYS_GPE_MFPL_PE5MFP_USCI0_CTL1;
}
void UART0_Init(void)
{
/*---------------------------------------------------------------------------------------------------------*/
/* Init UART */
/*---------------------------------------------------------------------------------------------------------*/
/* Reset UART0 */
SYS_ResetModule(UART0_RST);
/* Configure UART0 and set UART0 baud rate */
UART_Open(UART0, 115200);
}
void USCI0_Init(void)
{
/*---------------------------------------------------------------------------------------------------------*/
/* Init USCI */
/*---------------------------------------------------------------------------------------------------------*/
/* Reset USCI0 */
SYS_ResetModule(USCI0_RST);
/* Configure USCI0 as UART mode */
UUART_Open(UUART0, 115200);
}
/*---------------------------------------------------------------------------------------------------------*/
/* Main Function */
/*---------------------------------------------------------------------------------------------------------*/
int32_t main(void)
{
/* Unlock protected registers */
SYS_UnlockReg();
/* Init System, peripheral clock and multi-function I/O */
SYS_Init();
/* Lock protected registers */
SYS_LockReg();
/* Init UART0 for printf */
UART0_Init();
/* Init USCI0 for test */
USCI0_Init();
/*---------------------------------------------------------------------------------------------------------*/
/* SAMPLE CODE */
/*---------------------------------------------------------------------------------------------------------*/
printf("\n\nCPU @ %dHz\n", SystemCoreClock);
printf("\nUART Sample Program\n");
/* USCI UART RS485 sample function */
RS485_FunctionTest();
printf("\nUART Sample Program End\n");
while(1);
}
|
82993.c | /***************************************************************************
* Humanistic Robotics VSC Interface Library *
* Version 1.1 *
* Copyright 2013, Humanistic Robotics, Inc *
***************************************************************************/
/*
* 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 <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <termios.h>
#include <string.h>
#include <fcntl.h>
#include "SerialInterface.h"
/**
* Open a serial port
*
* Supported baud rate for Linux:
* 110, 300, 600, 1200, 2400, 4800, 9600, 19200, 38400, 57600, 115200
*
*
* @param device Port name /dev/ttyS0, /dev/ttyACM0, /dev/ttyUSB0, ...
* @param baud Baud rate of the serial port
* @return fd success, -1 on error
*/
int open_serial_interface(const char *device, const unsigned int baud) {
struct termios options;
int fd = -1;
speed_t speed = B115200;
/* Open device */
fd = open(device, O_RDWR | O_NOCTTY | O_NDELAY | O_NONBLOCK);
if (fd == -1) {
return -1;
}
/* Set parameters */
tcgetattr(fd, &options); /* Get the current options of the port */
memset(&options, 0, sizeof(options)); /* Clear all the options */
switch (baud) {
case 110:
speed = B110;
break;
case 300:
speed = B300;
break;
case 600:
speed = B600;
break;
case 1200:
speed = B1200;
break;
case 2400:
speed = B2400;
break;
case 4800:
speed = B4800;
break;
case 9600:
speed = B9600;
break;
case 19200:
speed = B19200;
break;
case 38400:
speed = B38400;
break;
case 57600:
speed = B57600;
break;
case 115200:
speed = B115200;
break;
default:
return -1;
}
/* Set the speed (Bauds) */
options.c_cflag = speed | CS8 | CLOCAL | CREAD;
options.c_iflag = IGNPAR;
options.c_oflag = 0;
options.c_lflag = 0;
options.c_cc[VTIME] = 0; /* Timer unused */
options.c_cc[VMIN] = 0; /* At least on character before satisfy reading */
tcflush(fd, TCIFLUSH);
tcsetattr(fd, TCSANOW, &options); /* Activate the settings */
/* Return File Descriptor */
return fd;
}
/**
* Close the connection with the current device
*
* @param fd The file descriptor to close
*/
void close_serial_interface(int fd) {
if (fd != -1) {
close(fd);
}
}
/**
* Write bytes to serial port from buffer
*
* @param buffer The data buffer to write data from
* @param bytes The number of bytes to write from the buffer
* @return number of bytes written on success, -1 on error
*/
int write_to_serial(int fd, const void *buffer, const unsigned int bytes) {
if (fd == -1) {
return -1;
}
return write(fd, buffer, bytes);
}
/**
* Read bytes from serial port
*
* @param buffer The data buffer to write data into
* @param bytes The number of bytes to read into the buffer
* @return number of bytes read on success, -1 on error
*/
int read_from_serial(int fd, void *buffer, unsigned int bytes) {
if (fd == -1) {
return -1;
}
return read(fd, buffer, bytes);
}
|
474692.c | /**********************************************************************/
/* ____ ____ */
/* / /\/ / */
/* /___/ \ / */
/* \ \ \/ */
/* \ \ Copyright (c) 2003-2009 Xilinx, Inc. */
/* / / All Right Reserved. */
/* /---/ /\ */
/* \ \ / \ */
/* \___\/\___\ */
/***********************************************************************/
/* This file is designed for use with ISim build 0x7708f090 */
#define XSI_HIDE_SYMBOL_SPEC true
#include "xsi.h"
#include <memory.h>
#ifdef __GNUC__
#include <stdlib.h>
#else
#include <malloc.h>
#define alloca _alloca
#endif
extern void work_m_00000000002065796766_1217392590_init()
{
xsi_register_didat("work_m_00000000002065796766_1217392590", "isim/tb_MIPS_isim_beh.exe.sim/work/m_00000000002065796766_1217392590.didat");
}
|
900424.c | /*
* Copyright (C) 2019 Intel Corporation
*
* SPDX-License-Identifier: BSD-3-Clause
*/
#include <getopt.h>
#include <stdio.h>
#include <openssl/evp.h>
#include "app.h"
static struct option long_options[] = {
{"keygen", no_argument, 0, 0},
{"quote", no_argument, 0, 0},
{"sign", no_argument, 0, 0},
{"enclave-path", required_argument, 0, 0},
{"sealedprivkey", required_argument, 0, 0},
{"sealedpubkey", required_argument, 0, 0},
{"signature", required_argument, 0, 0},
{"public-key", required_argument, 0, 0},
{"quotefile", required_argument, 0, 0},
{"outputfile", required_argument, 0, 0},
{0, 0, 0, 0}};
/**
* main()
*/
int main(int argc, char **argv) {
bool opt_keygen = false;
bool opt_quote = false;
bool opt_sign = false;
const char *opt_enclave_path = NULL;
const char *opt_sealedprivkey_file = NULL;
const char *opt_sealedpubkey_file = NULL;
const char *opt_signature_file = NULL;
const char *opt_input_file = NULL;
const char *opt_public_key_file = NULL;
const char *opt_quote_file = NULL;
const char *opt_output_file = NULL;
int option_index = 0;
while (getopt_long_only(argc, argv, "", long_options, &option_index) !=
-1) {
switch (option_index) {
case 0:
opt_keygen = true;
break;
case 1:
opt_quote = true;
break;
case 2:
opt_sign = true;
break;
case 3:
opt_enclave_path = optarg;
break;
case 4:
opt_sealedprivkey_file = optarg;
break;
case 5:
opt_sealedpubkey_file = optarg;
break;
case 6:
opt_signature_file = optarg;
break;
case 7:
opt_public_key_file = optarg;
break;
case 8:
opt_quote_file = optarg;
break;
case 9:
opt_output_file = optarg;
break;
}
}
if (optind < argc) {
opt_input_file = argv[optind++];
}
if (!opt_keygen && !opt_sign && !opt_quote) {
fprintf(
stderr,
"Error: Must specifiy either --keygen or --sign or --quotegen\n");
return EXIT_FAILURE;
}
if (opt_keygen && (!opt_enclave_path || !opt_sealedprivkey_file ||
!opt_sealedprivkey_file || !opt_public_key_file)) {
fprintf(stderr, "Usage:\n");
fprintf(stderr,
" %s --keygen --enclave-path /path/to/enclave.signed.so "
"--sealedprivkey sealedprivkey.bin "
"--sealedpubkey sealedpubkey.bin "
"--public-key mykey.pem\n",
argv[0]);
return EXIT_FAILURE;
}
if (opt_quote &&
(!opt_enclave_path || !opt_sealedpubkey_file || !opt_quote_file)) {
fprintf(stderr, "Usage:\n");
fprintf(stderr,
" %s --quotegen --enclave-path /path/to/enclave.signed.so "
"--sealedpubkey sealedpubkey.bin --quotefile quote.json\n",
argv[0]);
return EXIT_FAILURE;
}
if (opt_sign &&
(!opt_enclave_path || !opt_sealedprivkey_file || !opt_signature_file ||
!opt_output_file || !opt_input_file)) {
fprintf(stderr, "Usage:\n");
fprintf(stderr,
" %s --sign --enclave-path /path/to/enclave.signed.so "
"--sealedprivkey "
"sealeddata.bin --signature inputfile.signature --outputfile "
"out inputfile\n",
argv[0]);
return EXIT_FAILURE;
}
OpenSSL_add_all_algorithms(); /* Init OpenSSL lib */
bool success_status =
create_enclave(opt_enclave_path) && enclave_get_buffer_sizes() &&
allocate_buffers() && (opt_keygen ? enclave_generate_key() : true) &&
(opt_keygen
? save_enclave_state(opt_sealedprivkey_file, opt_sealedpubkey_file)
: true) &&
// quote
(opt_quote ? load_sealedpubkey(opt_sealedpubkey_file) : true) &&
(opt_quote ? enclave_gen_quote() : true) &&
(opt_quote ? save_quote(opt_quote_file) : true) &&
//(opt_quote ? save_public_key(opt_public_key_file) : true) &&
// bsm
//(opt_bsm ? load_enclave_state(opt_sealedprivkey_file) : true) &&
//(opt_bsm ? load_bsm_input_file(opt_input_file) : true) &&
//(opt_bsm ? enclave_compute_bsm() : true) &&
//(opt_bsm ? save_bsm_signature(opt_signature_file) : true) &&
//(opt_bsm ? save_bsm_output(opt_output_file) : true) &&
// sign
(opt_sign ? load_enclave_state(opt_sealedprivkey_file) : true) &&
(opt_sign ? load_input_file(opt_input_file) : true) &&
(opt_sign ? enclave_sign_data() : true) &&
// save_enclave_state(opt_sealedprivkey_file) &&
(opt_sign ? save_output(opt_output_file) : true) &&
(opt_sign ? save_signature(opt_signature_file) : true);
// TODO call function to generate report with public key in it
//(opt_keygen ? enclave_generate_quote() : true);
if (sgx_lasterr != SGX_SUCCESS) {
fprintf(stderr, "[GatewayApp]: ERROR: %s\n",
decode_sgx_status(sgx_lasterr));
}
destroy_enclave();
cleanup_buffers();
return success_status ? EXIT_SUCCESS : EXIT_FAILURE;
}
|
613386.c |
int print();
int factor(int x){
int y;
int z;
y = x-1;
if(x != 1){
z = x*factor(y);
}
else{
z = x;
}
return z;
}
int main(){
int z;
int a;
a = 10;
z = factor(a);
print(z);
}
|
927362.c | /***********************************************************************
Copyright (c) 2006-2011, Skype Limited. 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 Internet Society, IETF or IETF Trust, nor the
names of specific 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.
***********************************************************************/
#ifdef OPUS_ENABLED
#include "opus/opus_config.h"
#endif
#include "opus/silk/fixed/main_FIX.h"
#include "opus/celt/stack_alloc.h"
#include "opus/silk/tuning_parameters.h"
/* Low Bitrate Redundancy (LBRR) encoding. Reuse all parameters but encode with lower bitrate */
static OPUS_INLINE void silk_LBRR_encode_FIX(
silk_encoder_state_FIX *psEnc, /* I/O Pointer to Silk FIX encoder state */
silk_encoder_control_FIX *psEncCtrl, /* I/O Pointer to Silk FIX encoder control struct */
const opus_int32 xfw_Q3[], /* I Input signal */
opus_int condCoding /* I The type of conditional coding used so far for this frame */
);
void silk_encode_do_VAD_FIX(
silk_encoder_state_FIX *psEnc /* I/O Pointer to Silk FIX encoder state */
)
{
/****************************/
/* Voice Activity Detection */
/****************************/
silk_VAD_GetSA_Q8( &psEnc->sCmn, psEnc->sCmn.inputBuf + 1 );
/**************************************************/
/* Convert speech activity into VAD and DTX flags */
/**************************************************/
if( psEnc->sCmn.speech_activity_Q8 < SILK_FIX_CONST( SPEECH_ACTIVITY_DTX_THRES, 8 ) ) {
psEnc->sCmn.indices.signalType = TYPE_NO_VOICE_ACTIVITY;
psEnc->sCmn.noSpeechCounter++;
if( psEnc->sCmn.noSpeechCounter < NB_SPEECH_FRAMES_BEFORE_DTX ) {
psEnc->sCmn.inDTX = 0;
} else if( psEnc->sCmn.noSpeechCounter > MAX_CONSECUTIVE_DTX + NB_SPEECH_FRAMES_BEFORE_DTX ) {
psEnc->sCmn.noSpeechCounter = NB_SPEECH_FRAMES_BEFORE_DTX;
psEnc->sCmn.inDTX = 0;
}
psEnc->sCmn.VAD_flags[ psEnc->sCmn.nFramesEncoded ] = 0;
} else {
psEnc->sCmn.noSpeechCounter = 0;
psEnc->sCmn.inDTX = 0;
psEnc->sCmn.indices.signalType = TYPE_UNVOICED;
psEnc->sCmn.VAD_flags[ psEnc->sCmn.nFramesEncoded ] = 1;
}
}
/****************/
/* Encode frame */
/****************/
opus_int silk_encode_frame_FIX(
silk_encoder_state_FIX *psEnc, /* I/O Pointer to Silk FIX encoder state */
opus_int32 *pnBytesOut, /* O Pointer to number of payload bytes; */
ec_enc *psRangeEnc, /* I/O compressor data structure */
opus_int condCoding, /* I The type of conditional coding to use */
opus_int maxBits, /* I If > 0: maximum number of output bits */
opus_int useCBR /* I Flag to force constant-bitrate operation */
)
{
silk_encoder_control_FIX sEncCtrl;
opus_int i, iter, maxIter, found_upper, found_lower, ret = 0;
opus_int16 *x_frame;
ec_enc sRangeEnc_copy, sRangeEnc_copy2;
silk_nsq_state sNSQ_copy, sNSQ_copy2;
opus_int32 seed_copy, nBits, nBits_lower, nBits_upper, gainMult_lower, gainMult_upper;
opus_int32 gainsID, gainsID_lower, gainsID_upper;
opus_int16 gainMult_Q8;
opus_int16 ec_prevLagIndex_copy;
opus_int ec_prevSignalType_copy;
opus_int8 LastGainIndex_copy2;
SAVE_STACK;
/* This is totally unnecessary but many compilers (including gcc) are too dumb to realise it */
LastGainIndex_copy2 = nBits_lower = nBits_upper = gainMult_lower = gainMult_upper = 0;
psEnc->sCmn.indices.Seed = psEnc->sCmn.frameCounter++ & 3;
/**************************************************************/
/* Set up Input Pointers, and insert frame in input buffer */
/*************************************************************/
/* start of frame to encode */
x_frame = psEnc->x_buf + psEnc->sCmn.ltp_mem_length;
/***************************************/
/* Ensure smooth bandwidth transitions */
/***************************************/
silk_LP_variable_cutoff( &psEnc->sCmn.sLP, psEnc->sCmn.inputBuf + 1, psEnc->sCmn.frame_length );
/*******************************************/
/* Copy new frame to front of input buffer */
/*******************************************/
silk_memcpy( x_frame + LA_SHAPE_MS * psEnc->sCmn.fs_kHz, psEnc->sCmn.inputBuf + 1, psEnc->sCmn.frame_length * sizeof( opus_int16 ) );
if( !psEnc->sCmn.prefillFlag ) {
VARDECL( opus_int32, xfw_Q3 );
VARDECL( opus_int16, res_pitch );
VARDECL( opus_uint8, ec_buf_copy );
opus_int16 *res_pitch_frame;
ALLOC( res_pitch,
psEnc->sCmn.la_pitch + psEnc->sCmn.frame_length
+ psEnc->sCmn.ltp_mem_length, opus_int16 );
/* start of pitch LPC residual frame */
res_pitch_frame = res_pitch + psEnc->sCmn.ltp_mem_length;
/*****************************************/
/* Find pitch lags, initial LPC analysis */
/*****************************************/
silk_find_pitch_lags_FIX( psEnc, &sEncCtrl, res_pitch, x_frame, psEnc->sCmn.arch );
/************************/
/* Noise shape analysis */
/************************/
silk_noise_shape_analysis_FIX( psEnc, &sEncCtrl, res_pitch_frame, x_frame, psEnc->sCmn.arch );
/***************************************************/
/* Find linear prediction coefficients (LPC + LTP) */
/***************************************************/
silk_find_pred_coefs_FIX( psEnc, &sEncCtrl, res_pitch, x_frame, condCoding );
/****************************************/
/* Process gains */
/****************************************/
silk_process_gains_FIX( psEnc, &sEncCtrl, condCoding );
/*****************************************/
/* Prefiltering for noise shaper */
/*****************************************/
ALLOC( xfw_Q3, psEnc->sCmn.frame_length, opus_int32 );
silk_prefilter_FIX( psEnc, &sEncCtrl, xfw_Q3, x_frame );
/****************************************/
/* Low Bitrate Redundant Encoding */
/****************************************/
silk_LBRR_encode_FIX( psEnc, &sEncCtrl, xfw_Q3, condCoding );
/* Loop over quantizer and entropy coding to control bitrate */
maxIter = 6;
gainMult_Q8 = SILK_FIX_CONST( 1, 8 );
found_lower = 0;
found_upper = 0;
gainsID = silk_gains_ID( psEnc->sCmn.indices.GainsIndices, psEnc->sCmn.nb_subfr );
gainsID_lower = -1;
gainsID_upper = -1;
/* Copy part of the input state */
silk_memcpy( &sRangeEnc_copy, psRangeEnc, sizeof( ec_enc ) );
silk_memcpy( &sNSQ_copy, &psEnc->sCmn.sNSQ, sizeof( silk_nsq_state ) );
seed_copy = psEnc->sCmn.indices.Seed;
ec_prevLagIndex_copy = psEnc->sCmn.ec_prevLagIndex;
ec_prevSignalType_copy = psEnc->sCmn.ec_prevSignalType;
ALLOC( ec_buf_copy, 1275, opus_uint8 );
for( iter = 0; ; iter++ ) {
if( gainsID == gainsID_lower ) {
nBits = nBits_lower;
} else if( gainsID == gainsID_upper ) {
nBits = nBits_upper;
} else {
/* Restore part of the input state */
if( iter > 0 ) {
silk_memcpy( psRangeEnc, &sRangeEnc_copy, sizeof( ec_enc ) );
silk_memcpy( &psEnc->sCmn.sNSQ, &sNSQ_copy, sizeof( silk_nsq_state ) );
psEnc->sCmn.indices.Seed = seed_copy;
psEnc->sCmn.ec_prevLagIndex = ec_prevLagIndex_copy;
psEnc->sCmn.ec_prevSignalType = ec_prevSignalType_copy;
}
/*****************************************/
/* Noise shaping quantization */
/*****************************************/
if( psEnc->sCmn.nStatesDelayedDecision > 1 || psEnc->sCmn.warping_Q16 > 0 ) {
silk_NSQ_del_dec( &psEnc->sCmn, &psEnc->sCmn.sNSQ, &psEnc->sCmn.indices, xfw_Q3, psEnc->sCmn.pulses,
sEncCtrl.PredCoef_Q12[ 0 ], sEncCtrl.LTPCoef_Q14, sEncCtrl.AR2_Q13, sEncCtrl.HarmShapeGain_Q14,
sEncCtrl.Tilt_Q14, sEncCtrl.LF_shp_Q14, sEncCtrl.Gains_Q16, sEncCtrl.pitchL, sEncCtrl.Lambda_Q10, sEncCtrl.LTP_scale_Q14 );
} else {
silk_NSQ( &psEnc->sCmn, &psEnc->sCmn.sNSQ, &psEnc->sCmn.indices, xfw_Q3, psEnc->sCmn.pulses,
sEncCtrl.PredCoef_Q12[ 0 ], sEncCtrl.LTPCoef_Q14, sEncCtrl.AR2_Q13, sEncCtrl.HarmShapeGain_Q14,
sEncCtrl.Tilt_Q14, sEncCtrl.LF_shp_Q14, sEncCtrl.Gains_Q16, sEncCtrl.pitchL, sEncCtrl.Lambda_Q10, sEncCtrl.LTP_scale_Q14 );
}
/****************************************/
/* Encode Parameters */
/****************************************/
silk_encode_indices( &psEnc->sCmn, psRangeEnc, psEnc->sCmn.nFramesEncoded, 0, condCoding );
/****************************************/
/* Encode Excitation Signal */
/****************************************/
silk_encode_pulses( psRangeEnc, psEnc->sCmn.indices.signalType, psEnc->sCmn.indices.quantOffsetType,
psEnc->sCmn.pulses, psEnc->sCmn.frame_length );
nBits = ec_tell( psRangeEnc );
if( useCBR == 0 && iter == 0 && nBits <= maxBits ) {
break;
}
}
if( iter == maxIter ) {
if( found_lower && ( gainsID == gainsID_lower || nBits > maxBits ) ) {
/* Restore output state from earlier iteration that did meet the bitrate budget */
silk_memcpy( psRangeEnc, &sRangeEnc_copy2, sizeof( ec_enc ) );
silk_assert( sRangeEnc_copy2.offs <= 1275 );
silk_memcpy( psRangeEnc->buf, ec_buf_copy, sRangeEnc_copy2.offs );
silk_memcpy( &psEnc->sCmn.sNSQ, &sNSQ_copy2, sizeof( silk_nsq_state ) );
psEnc->sShape.LastGainIndex = LastGainIndex_copy2;
}
break;
}
if( nBits > maxBits ) {
if( found_lower == 0 && iter >= 2 ) {
/* Adjust the quantizer's rate/distortion tradeoff and discard previous "upper" results */
sEncCtrl.Lambda_Q10 = silk_ADD_RSHIFT32( sEncCtrl.Lambda_Q10, sEncCtrl.Lambda_Q10, 1 );
found_upper = 0;
gainsID_upper = -1;
} else {
found_upper = 1;
nBits_upper = nBits;
gainMult_upper = gainMult_Q8;
gainsID_upper = gainsID;
}
} else if( nBits < maxBits - 5 ) {
found_lower = 1;
nBits_lower = nBits;
gainMult_lower = gainMult_Q8;
if( gainsID != gainsID_lower ) {
gainsID_lower = gainsID;
/* Copy part of the output state */
silk_memcpy( &sRangeEnc_copy2, psRangeEnc, sizeof( ec_enc ) );
silk_assert( psRangeEnc->offs <= 1275 );
silk_memcpy( ec_buf_copy, psRangeEnc->buf, psRangeEnc->offs );
silk_memcpy( &sNSQ_copy2, &psEnc->sCmn.sNSQ, sizeof( silk_nsq_state ) );
LastGainIndex_copy2 = psEnc->sShape.LastGainIndex;
}
} else {
/* Within 5 bits of budget: close enough */
break;
}
if( ( found_lower & found_upper ) == 0 ) {
/* Adjust gain according to high-rate rate/distortion curve */
opus_int32 gain_factor_Q16;
gain_factor_Q16 = silk_log2lin( silk_LSHIFT( nBits - maxBits, 7 ) / psEnc->sCmn.frame_length + SILK_FIX_CONST( 16, 7 ) );
gain_factor_Q16 = silk_min_32( gain_factor_Q16, SILK_FIX_CONST( 2, 16 ) );
if( nBits > maxBits ) {
gain_factor_Q16 = silk_max_32( gain_factor_Q16, SILK_FIX_CONST( 1.3, 16 ) );
}
gainMult_Q8 = silk_SMULWB( gain_factor_Q16, gainMult_Q8 );
} else {
/* Adjust gain by interpolating */
gainMult_Q8 = gainMult_lower + silk_DIV32_16( silk_MUL( gainMult_upper - gainMult_lower, maxBits - nBits_lower ), nBits_upper - nBits_lower );
/* New gain multplier must be between 25% and 75% of old range (note that gainMult_upper < gainMult_lower) */
if( gainMult_Q8 > silk_ADD_RSHIFT32( gainMult_lower, gainMult_upper - gainMult_lower, 2 ) ) {
gainMult_Q8 = silk_ADD_RSHIFT32( gainMult_lower, gainMult_upper - gainMult_lower, 2 );
} else
if( gainMult_Q8 < silk_SUB_RSHIFT32( gainMult_upper, gainMult_upper - gainMult_lower, 2 ) ) {
gainMult_Q8 = silk_SUB_RSHIFT32( gainMult_upper, gainMult_upper - gainMult_lower, 2 );
}
}
for( i = 0; i < psEnc->sCmn.nb_subfr; i++ ) {
sEncCtrl.Gains_Q16[ i ] = silk_LSHIFT_SAT32( silk_SMULWB( sEncCtrl.GainsUnq_Q16[ i ], gainMult_Q8 ), 8 );
}
/* Quantize gains */
psEnc->sShape.LastGainIndex = sEncCtrl.lastGainIndexPrev;
silk_gains_quant( psEnc->sCmn.indices.GainsIndices, sEncCtrl.Gains_Q16,
&psEnc->sShape.LastGainIndex, condCoding == CODE_CONDITIONALLY, psEnc->sCmn.nb_subfr );
/* Unique identifier of gains vector */
gainsID = silk_gains_ID( psEnc->sCmn.indices.GainsIndices, psEnc->sCmn.nb_subfr );
}
}
/* Update input buffer */
silk_memmove( psEnc->x_buf, &psEnc->x_buf[ psEnc->sCmn.frame_length ],
( psEnc->sCmn.ltp_mem_length + LA_SHAPE_MS * psEnc->sCmn.fs_kHz ) * sizeof( opus_int16 ) );
/* Exit without entropy coding */
if( psEnc->sCmn.prefillFlag ) {
/* No payload */
*pnBytesOut = 0;
RESTORE_STACK;
return ret;
}
/* Parameters needed for next frame */
psEnc->sCmn.prevLag = sEncCtrl.pitchL[ psEnc->sCmn.nb_subfr - 1 ];
psEnc->sCmn.prevSignalType = psEnc->sCmn.indices.signalType;
/****************************************/
/* Finalize payload */
/****************************************/
psEnc->sCmn.first_frame_after_reset = 0;
/* Payload size */
*pnBytesOut = silk_RSHIFT( ec_tell( psRangeEnc ) + 7, 3 );
RESTORE_STACK;
return ret;
}
/* Low-Bitrate Redundancy (LBRR) encoding. Reuse all parameters but encode excitation at lower bitrate */
static OPUS_INLINE void silk_LBRR_encode_FIX(
silk_encoder_state_FIX *psEnc, /* I/O Pointer to Silk FIX encoder state */
silk_encoder_control_FIX *psEncCtrl, /* I/O Pointer to Silk FIX encoder control struct */
const opus_int32 xfw_Q3[], /* I Input signal */
opus_int condCoding /* I The type of conditional coding used so far for this frame */
)
{
opus_int32 TempGains_Q16[ MAX_NB_SUBFR ];
SideInfoIndices *psIndices_LBRR = &psEnc->sCmn.indices_LBRR[ psEnc->sCmn.nFramesEncoded ];
silk_nsq_state sNSQ_LBRR;
/*******************************************/
/* Control use of inband LBRR */
/*******************************************/
if( psEnc->sCmn.LBRR_enabled && psEnc->sCmn.speech_activity_Q8 > SILK_FIX_CONST( LBRR_SPEECH_ACTIVITY_THRES, 8 ) ) {
psEnc->sCmn.LBRR_flags[ psEnc->sCmn.nFramesEncoded ] = 1;
/* Copy noise shaping quantizer state and quantization indices from regular encoding */
silk_memcpy( &sNSQ_LBRR, &psEnc->sCmn.sNSQ, sizeof( silk_nsq_state ) );
silk_memcpy( psIndices_LBRR, &psEnc->sCmn.indices, sizeof( SideInfoIndices ) );
/* Save original gains */
silk_memcpy( TempGains_Q16, psEncCtrl->Gains_Q16, psEnc->sCmn.nb_subfr * sizeof( opus_int32 ) );
if( psEnc->sCmn.nFramesEncoded == 0 || psEnc->sCmn.LBRR_flags[ psEnc->sCmn.nFramesEncoded - 1 ] == 0 ) {
/* First frame in packet or previous frame not LBRR coded */
psEnc->sCmn.LBRRprevLastGainIndex = psEnc->sShape.LastGainIndex;
/* Increase Gains to get target LBRR rate */
psIndices_LBRR->GainsIndices[ 0 ] = psIndices_LBRR->GainsIndices[ 0 ] + psEnc->sCmn.LBRR_GainIncreases;
psIndices_LBRR->GainsIndices[ 0 ] = silk_min_int( psIndices_LBRR->GainsIndices[ 0 ], N_LEVELS_QGAIN - 1 );
}
/* Decode to get gains in sync with decoder */
/* Overwrite unquantized gains with quantized gains */
silk_gains_dequant( psEncCtrl->Gains_Q16, psIndices_LBRR->GainsIndices,
&psEnc->sCmn.LBRRprevLastGainIndex, condCoding == CODE_CONDITIONALLY, psEnc->sCmn.nb_subfr );
/*****************************************/
/* Noise shaping quantization */
/*****************************************/
if( psEnc->sCmn.nStatesDelayedDecision > 1 || psEnc->sCmn.warping_Q16 > 0 ) {
silk_NSQ_del_dec( &psEnc->sCmn, &sNSQ_LBRR, psIndices_LBRR, xfw_Q3,
psEnc->sCmn.pulses_LBRR[ psEnc->sCmn.nFramesEncoded ], psEncCtrl->PredCoef_Q12[ 0 ], psEncCtrl->LTPCoef_Q14,
psEncCtrl->AR2_Q13, psEncCtrl->HarmShapeGain_Q14, psEncCtrl->Tilt_Q14, psEncCtrl->LF_shp_Q14,
psEncCtrl->Gains_Q16, psEncCtrl->pitchL, psEncCtrl->Lambda_Q10, psEncCtrl->LTP_scale_Q14 );
} else {
silk_NSQ( &psEnc->sCmn, &sNSQ_LBRR, psIndices_LBRR, xfw_Q3,
psEnc->sCmn.pulses_LBRR[ psEnc->sCmn.nFramesEncoded ], psEncCtrl->PredCoef_Q12[ 0 ], psEncCtrl->LTPCoef_Q14,
psEncCtrl->AR2_Q13, psEncCtrl->HarmShapeGain_Q14, psEncCtrl->Tilt_Q14, psEncCtrl->LF_shp_Q14,
psEncCtrl->Gains_Q16, psEncCtrl->pitchL, psEncCtrl->Lambda_Q10, psEncCtrl->LTP_scale_Q14 );
}
/* Restore original gains */
silk_memcpy( psEncCtrl->Gains_Q16, TempGains_Q16, psEnc->sCmn.nb_subfr * sizeof( opus_int32 ) );
}
}
|
312853.c | /**
* @file atcmd.c
* @brief AT Command Module - Interface Part Source File
* @version 1.0
* @date 2013/02/22
* @par Revision
* 2013/02/22 - 1.0 Release
* @author Mike Jeong
* \n\n @par Copyright (C) 2013 WIZnet. All rights reserved.
*/
//#define FILE_LOG_SILENCE
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
#include "stm32f10x.h"
#include "atcmd.h"
#include "cmdrun.h"
#include "library/util.h"
#include "ConfigData.h"
#include "uartHandler.h"
#include "boardutil.h"
#define CMD_CLEAR() { \
atci.tcmd.op[0] = atci.tcmd.sign = atci.tcmd.arg1[0] = atci.tcmd.arg2[0] = 0; \
atci.tcmd.arg3[0] = atci.tcmd.arg4[0] = atci.tcmd.arg5[0] = atci.tcmd.arg6[0] = 0; \
}
#define RESP_CR(type_v) do{CMD_CLEAR(); cmd_resp(type_v, VAL_NONE); return;}while(0)
#define RESP_CDR(type_v, dgt_v) do{ \
CMD_CLEAR(); sprintf((char*)atci.tcmd.arg1, "%d", dgt_v); \
cmd_resp(type_v, VAL_NONE); return; \
}while(0)
#define CMP_CHAR_1(str_p, c1_v) \
(str_p[1] != 0 || (str_p[0]=toupper(str_p[0]))!=c1_v)
#define CMP_CHAR_2(str_p, c1_v, c2_v) \
(str_p[1] != 0 || ((str_p[0]=toupper(str_p[0]))!=c1_v && str_p[0]!=c2_v))
#define CMP_CHAR_3(str_p, c1_v, c2_v, c3_v) \
(str_p[1] != 0 || ((str_p[0]=toupper(str_p[0]))!=c1_v && str_p[0]!=c2_v && str_p[0]!=c3_v))
#define CMP_CHAR_4(str_p, c1_v, c2_v, c3_v, c4_v) \
(str_p[1] != 0 || ((str_p[0]=toupper(str_p[0]))!=c1_v && str_p[0]!=c2_v && str_p[0]!=c3_v && str_p[0]!=c4_v))
#define CHK_DGT_RANGE(str_p, snum_v, minval_v, maxval_v) \
((snum_v=atoi((char*)str_p))>maxval_v || snum_v<minval_v)
#define CHK_ARG_LEN(arg_p, maxlen_v, ret_v) { \
if(maxlen_v == 0) { \
if(arg_p[0] != 0) RESP_CDR(RET_WRONG_ARG, ret_v); \
} else if(strlen((char*)arg_p) > maxlen_v) RESP_CDR(RET_WRONG_ARG, ret_v); \
}
uint8_t g_send_buf[WORK_BUF_SIZE+1];
uint8_t g_recv_buf[WORK_BUF_SIZE+1];
extern uint32_t baud_table[11];
static void cmd_set_prev(uint8_t buflen);
static int8_t cmd_divide(int8_t *buf);
static void cmd_assign(void);
static void hdl_nset(void);
static void hdl_nstat(void);
static void hdl_nmac(void);
static void hdl_mstat(void);
static void hdl_musart1(void);
static void hdl_musart2(void);
static void hdl_msave(void);
static void hdl_mrst(void);
static void hdl_fiodir(void);
static void hdl_fioval(void);
#define ATCMD_BUF_SIZE 100
#define PREVBUF_MAX_SIZE 250
#define PREVBUF_MAX_NUM 2
#define PREVBUF_LAST (PREVBUF_MAX_NUM-1)
#define CMD_SIGN_NONE 0
#define CMD_SIGN_QUEST 1
#define CMD_SIGN_INDIV 2
#define CMD_SIGN_EQUAL 3
const struct at_command g_cmd_table[] =
{
{ "NSET", hdl_nset, NULL, NULL },
{ "NSTAT", hdl_nstat, NULL, NULL },
{ "NMAC", hdl_nmac, NULL, NULL },
{ "MSTAT", hdl_mstat, NULL, NULL },
{ "MUSART1", hdl_musart1, NULL, NULL },
{ "MUSART2", hdl_musart2, NULL, NULL },
{ "MSAVE", hdl_msave, NULL, NULL },
{ "MRST", hdl_mrst, NULL, NULL },
{ "FIODIR", hdl_fiodir, NULL, NULL },
{ "FIOVAL", hdl_fioval, NULL, NULL },
{ NULL, NULL, NULL, NULL } // Should be last item
};
static int8_t termbuf[ATCMD_BUF_SIZE];
static int8_t *prevbuf[PREVBUF_MAX_NUM];
static uint8_t previdx = 0, prevcnt = 0;
static int16_t prevlen = 0;
struct atc_info atci;
/**
* @ingroup atcmd_module
* Initialize ATCMD Module.
* This should be called before @ref atc_run
*/
void atc_init()
{
int8_t i;
memset(termbuf, 0, ATCMD_BUF_SIZE);
for(i=0; i<PREVBUF_MAX_NUM; i++) prevbuf[i] = NULL;
atci.sendsock = VAL_NONE;
atci.echo = VAL_ENABLE;
atci.poll = POLL_MODE_SEMI;
atci.sendbuf = g_send_buf;
atci.recvbuf = g_recv_buf;
// sockwatch_open(0, atc_async_cb); // Assign socket 1 to ATC module
// UART_write("\r\n\r\n\r\n[W,0]\r\n", 13);
// UART_write("[S,0]\r\n", 7);
}
/**
* @ingroup atcmd_module
* ATCMD Module Handler.
* If you use ATCMD Module, this should run in the main loop
*/
void atc_run(void)
{
int8_t ret, recv_char;
static uint8_t buflen = 0;
if(UART_read(&recv_char, 1) <= 0) return; // �엯�젰 媛� �뾾�뒗 寃쎌?? printf("RECV: 0x%x\r\n", recv_char);
#if 0 // 2014.09.03
if(atci.sendsock != VAL_NONE)
{
atci.sendbuf[atci.worklen++] = recv_char;
if(atci.worklen >= atci.sendlen) { // �엯�젰�씠 �셿?�뚮릺硫�?
act_nsend(atci.sendsock, (int8_t *)atci.sendbuf, atci.worklen, atci.sendip, &atci.sendport);
atci.sendsock = VAL_NONE;
}
return;
}
#endif
if(isgraph(recv_char) == 0) // �젣�뼱 ?�몄??泥섎??
{ //printf("ctrl\r\n");
switch(recv_char) {
case 0x0d: // CR(\r)
#if defined(FACTORY_FW)
check_RS422((uint8_t *)termbuf);
#endif
break; // do nothing
case 0x0a: // LF(\n)
//printf("<ENT>");
if(atci.echo)
{
UART_write(termbuf, buflen);
UART_write("\r\n", 2);
}
termbuf[buflen] = 0;
break;
case 0x08: // BS
//printf("<BS>\r\n");
if(buflen != 0) {
buflen--;
termbuf[buflen] = 0;
if(atci.echo)
UART_write("\b \b", 3);
}
break;
case 0x1b: // ESC
//printf("<ESC>\r\n");
if(atci.echo)
UART_write(&recv_char, 1);
break;
}
}
else if(buflen < ATCMD_BUF_SIZE-1) // -1 �씠��? : 0 �씠 �븯�굹 �븘�슂�븯誘�濡�
{
if(buflen == 0) UART2_flush();
termbuf[buflen++] = (uint8_t)recv_char; //termbuf[buflen] = 0;
//if(atci.echo) UART_write(&recv_char, 1);
//printf(" termbuf(%c, %s)\r\n", recv_char, termbuf);
}
//else { printf("input buffer stuffed\r\n"); }
if(recv_char != 0x0a || buflen == 0)
return; //LOGA("Command: %d, %s\r\n", buflen, termbuf);
cmd_set_prev(buflen);
buflen = 0;
CMD_CLEAR();
ret = cmd_divide(termbuf);
if(ret == RET_OK) {
cmd_assign();
}
else if(ret != RET_DONE) {
cmd_resp(ret, VAL_NONE);
}
}
static void cmd_set_prev(uint8_t buflen)
{
int8_t idx;
while(prevcnt >= PREVBUF_MAX_NUM || (prevcnt && prevlen+buflen > PREVBUF_MAX_SIZE-1)) {
idx = (previdx + PREVBUF_MAX_NUM - prevcnt) % PREVBUF_MAX_NUM; // oldest index
if(prevbuf[idx]) {
prevlen -= strlen((char*)prevbuf[idx]) + 1;
free(prevbuf[idx]);
prevbuf[idx] = NULL;
prevcnt--;
} else CRITICAL_ERR("ring buf 1");
}
prevbuf[previdx] = malloc(buflen+1);
while(prevcnt && prevbuf[previdx] == NULL) {
idx = (previdx + PREVBUF_MAX_NUM - prevcnt) % PREVBUF_MAX_NUM; // oldest index
if(prevbuf[idx]) {
prevlen -= strlen((char*)prevbuf[idx]) + 1;
free(prevbuf[idx]);
prevbuf[idx] = NULL;
prevcnt--;
prevbuf[previdx] = malloc(buflen+1);
} else CRITICAL_ERR("ring buf 2");
}
if(prevbuf[previdx] == NULL) CRITICAL_ERR("malloc fail"); // 留뚯�?�떎�뙣�빐�룄 嫄� �븯?�� �떢�쑝硫� �닔�젙
else {
strcpy((char*)prevbuf[previdx], (char*)termbuf); //printf("$$%s## was set\r\n", prevbuf[previdx]);
if(previdx == PREVBUF_LAST) previdx = 0;
else previdx++;
prevcnt++;
prevlen += buflen + 1;
}
}
static int8_t cmd_divide(int8_t *buf)
{
int8_t ret, *split, *noteptr, *tmpptr = buf; //printf("cmd_divide 1 \r\n");
if(strchr((char*)tmpptr, '=')) atci.tcmd.sign = CMD_SIGN_EQUAL;
else if(strchr((char*)tmpptr, '?')) atci.tcmd.sign = CMD_SIGN_QUEST;
else if(strchr((char*)tmpptr, '-')) atci.tcmd.sign = CMD_SIGN_INDIV;
split = strsep_ex(&tmpptr, (int8_t *)"=-?");
if(split != NULL)
{
for (noteptr = split; *noteptr; noteptr++) *noteptr = toupper(*noteptr);
if(strlen((char*)split) > OP_SIZE+3-1 ||
split[0] != 'A' || split[1] != 'T' || split[2] != '+')
{
if(split[0] == 'A' && split[1] == 'T' && split[2] == 0) { // Just 'AT' input
if(atci.tcmd.sign == CMD_SIGN_QUEST) {
if(prevcnt < 2) UART_write("[D,,0]\r\n", 8);
else {
uint8_t idx = previdx;
uint8_t tmplen;
char tmpbuf[ATCMD_BUF_SIZE];
if(previdx < 2) idx += PREVBUF_MAX_NUM - 2; //printf("==%d,%d==", previdx, idx);}
else idx -= 2; //printf("++%d,%d++", previdx, idx);}printf("--%d--", idx);Delay_ms(5);
//printf("[D,,%d]\r\n%s\r\n", strlen((char*)prevbuf[idx]), prevbuf[idx]);
tmplen = sprintf(tmpbuf, "[D,,%d]\r\n%s\r\n", strlen((char*)prevbuf[idx]), prevbuf[idx]);
UART_write(tmpbuf, tmplen);
}
}
else if(atci.tcmd.sign == CMD_SIGN_NONE) UART_write("[S]\r\n", 5);
else return RET_WRONG_SIGN;
return RET_DONE;
} else {
strcpy((char*)atci.tcmd.op, (char*)split);
}
} else {
strcpy((char*)atci.tcmd.op, (char*)&split[3]);
}
}
else return RET_WRONG_OP; //printf("first splite is NULL\r\n");
#define ARG_PARSE(arg_v, size_v, dgt_v) \
{ \
split = strsep_ex(&tmpptr, (int8_t *)","); \
if(split != NULL) { \
if(strlen((char*)split) > size_v-1) { \
ret = RET_WRONG_ARG; \
CMD_CLEAR(); \
sprintf((char*)atci.tcmd.arg1, "%d", dgt_v); \
goto FAIL_END; \
} else strcpy((char*)arg_v, (char*)split); \
} else goto OK_END; \
} \
ARG_PARSE(atci.tcmd.arg1, ARG_1_SIZE, 1);
ARG_PARSE(atci.tcmd.arg2, ARG_2_SIZE, 2);
ARG_PARSE(atci.tcmd.arg3, ARG_3_SIZE, 3);
ARG_PARSE(atci.tcmd.arg4, ARG_4_SIZE, 4);
ARG_PARSE(atci.tcmd.arg5, ARG_5_SIZE, 5);
ARG_PARSE(atci.tcmd.arg6, ARG_6_SIZE, 6);
if(*tmpptr != 0) {
ret = RET_WRONG_ARG;
CMD_CLEAR();
goto FAIL_END;
}
DBGA("Debug: (%s)", tmpptr); //理쒕�?arg�꽆寃� �뱾�뼱�삩 寃� �솗�씤�슜 - Strict Param �젙�?��
OK_END:
ret = RET_OK;
FAIL_END:
DBGA("[%s] S(%d),OP(%s),A1(%s),A2(%s),A3(%s),A4(%s),A5(%s),A6(%s)",
ret==RET_OK?"OK":"ERR", atci.tcmd.sign, atci.tcmd.op?atci.tcmd.op:"<N>", atci.tcmd.arg1?atci.tcmd.arg1:"<N>",
atci.tcmd.arg2?atci.tcmd.arg2:"<N>", atci.tcmd.arg3?atci.tcmd.arg3:"<N>", atci.tcmd.arg4?atci.tcmd.arg4:"<N>",
atci.tcmd.arg5?atci.tcmd.arg5:"<N>", atci.tcmd.arg6?atci.tcmd.arg6:"<N>");
return ret;
}
static void cmd_assign(void)
{
int i;
for(i = 0 ; g_cmd_table[i].cmd != NULL ; i++) {
if(!strcmp((const char *)atci.tcmd.op, g_cmd_table[i].cmd)) {
g_cmd_table[i].process();
return;
}
}
/* CMD NOT FOUND */
CMD_CLEAR();
cmd_resp(RET_WRONG_OP, VAL_NONE);
}
void cmd_resp_dump(int8_t idval, int8_t *dump)
{
uint16_t len = dump!=NULL?strlen((char*)dump):0;
if(len == 0) {
if(idval == VAL_NONE) printf("[D,,0]\r\n");
else printf("[D,%d,0]\r\n", idval);
} else {
if(idval == VAL_NONE) printf("[D,,%d]\r\n%s\r\n", len, dump);
else printf("[D,%d,%d]\r\n%s\r\n", idval, len, dump);
DBG("going to free");
MEM_FREE(dump);
DBG("free done");
}
}
void cmd_resp(int8_t retval, int8_t idval)
{
uint8_t cnt, len, idx = 0;
DBGA("ret(%d), id(%d)", retval, idval);
cnt = (atci.tcmd.arg1[0] != 0) + (atci.tcmd.arg2[0] != 0) + (atci.tcmd.arg3[0] != 0) +
(atci.tcmd.arg4[0] != 0) + (atci.tcmd.arg5[0] != 0) + (atci.tcmd.arg6[0] != 0);
#define MAKE_RESP(item_v, size_v) \
{ \
if(item_v[0] != 0) { \
termbuf[idx++] = ','; \
len = strlen((char*)item_v); \
if(len > size_v-1) CRITICAL_ERR("resp buf overflow"); \
memcpy((char*)&termbuf[idx], (char*)item_v, len); \
idx += len; \
cnt--; \
} else if(cnt) { \
termbuf[idx++] = ','; \
} \
}//printf("MakeResp-(%s)(%d)", item_v, len);
termbuf[idx++] = '[';
if(retval >= RET_OK) {
if(retval == RET_OK) termbuf[idx++] = 'S';
else if(retval == RET_OK_DUMP) CRITICAL_ERR("use cmd_resp_dump for dump");
else if(retval == RET_ASYNC) termbuf[idx++] = 'W';
else if(retval == RET_RECV) termbuf[idx++] = 'R';
else CRITICAL_ERRA("undefined return value (%d)", retval);
if(idval != VAL_NONE) {
termbuf[idx++] = ',';
sprintf((char*)&termbuf[idx], "%d", idval);
len = digit_length(idval, 10);
idx += len;
} else if(cnt) termbuf[idx++] = ',';
} else {
termbuf[idx++] = 'F';
termbuf[idx++] = ',';
if(idval != VAL_NONE) {
sprintf((char*)&termbuf[idx], "%d", idval);
len = digit_length(idval, 10);
idx += len;
}
termbuf[idx++] = ',';
#define CMD_SWT_DEF(errval_v) termbuf[idx++] = errval_v;
#define CMD_SWT_EXT(base_v, errval_v) termbuf[idx++]=base_v;termbuf[idx++] = errval_v;
switch(retval) {
case RET_UNSPECIFIED: CMD_SWT_DEF(ERRVAL_UNSPECIFIED); break;
case RET_WRONG_OP: CMD_SWT_DEF(ERRVAL_WRONG_OP); break;
case RET_WRONG_SIGN: CMD_SWT_DEF(ERRVAL_WRONG_SIGN); break;
case RET_WRONG_ARG: CMD_SWT_DEF(ERRVAL_WRONG_ARG); break;
case RET_RANGE_OUT: CMD_SWT_DEF(ERRVAL_RANGE_OUT); break;
case RET_DISABLED: CMD_SWT_DEF(ERRVAL_DISABLED); break;
case RET_NOT_ALLOWED: CMD_SWT_DEF(ERRVAL_NOT_ALLOWED); break;
case RET_BUSY: CMD_SWT_DEF(ERRVAL_BUSY); break;
case RET_TIMEOUT: CMD_SWT_DEF(ERRVAL_TIMEOUT); break;
case RET_NO_SOCK: CMD_SWT_EXT('1', ERRVAL_NO_SOCK); break;
case RET_SOCK_CLS: CMD_SWT_EXT('1', ERRVAL_SOCK_CLS); break;
case RET_USING_PORT: CMD_SWT_EXT('1', ERRVAL_USING_PORT); break;
case RET_NOT_CONN: CMD_SWT_EXT('1', ERRVAL_NOT_CONN); break;
case RET_WRONG_ADDR: CMD_SWT_EXT('1', ERRVAL_WRONG_ADDR); break;
case RET_NO_DATA: CMD_SWT_EXT('1', ERRVAL_NO_DATA); break;
case RET_NO_FREEMEM: CMD_SWT_EXT('2', ERRVAL_NO_FREEMEM); break;
default:termbuf[idx++] = '0';break;
}
}
MAKE_RESP(atci.tcmd.arg1, ARG_1_SIZE);
MAKE_RESP(atci.tcmd.arg2, ARG_2_SIZE);
MAKE_RESP(atci.tcmd.arg3, ARG_3_SIZE);
MAKE_RESP(atci.tcmd.arg4, ARG_4_SIZE);
MAKE_RESP(atci.tcmd.arg5, ARG_5_SIZE);
MAKE_RESP(atci.tcmd.arg6, ARG_6_SIZE);
termbuf[idx++] = ']';
termbuf[idx++] = 0;
// print basic response
UART_write(termbuf, strlen((char*)termbuf));
UART_write("\r\n", 2);
}
static void hdl_nset(void)
{
int8_t mode, num = -1;
uint8_t ip[4];
if(atci.tcmd.sign == CMD_SIGN_NONE) atci.tcmd.sign = CMD_SIGN_QUEST; // x�뒗 ?濡� 移섑??
if(atci.tcmd.sign == CMD_SIGN_QUEST)
{
if(atci.tcmd.arg1[0] != 0) {
if(str_check(isdigit, atci.tcmd.arg1) != RET_OK) RESP_CDR(RET_WRONG_ARG, 1);
if(CHK_DGT_RANGE(atci.tcmd.arg1, num, 1, 6)) RESP_CDR(RET_RANGE_OUT, 1);
}
CMD_CLEAR();
act_nset_q(num);
}
else if(atci.tcmd.sign == CMD_SIGN_INDIV)
{
if(atci.tcmd.arg1[0] != 0) {
if(str_check(isdigit, atci.tcmd.arg1) != RET_OK) RESP_CDR(RET_WRONG_ARG, 1);
if(CHK_DGT_RANGE(atci.tcmd.arg1, num, 1, 6)) RESP_CDR(RET_RANGE_OUT, 1);
if(num == 1) {
if(CMP_CHAR_2(atci.tcmd.arg2, 'D', 'S')) RESP_CDR(RET_WRONG_ARG, 2);
mode = atci.tcmd.arg2[0];
CMD_CLEAR();
act_nset_a(mode, NULL, NULL, NULL, NULL, NULL);
} else {
if(ip_check(atci.tcmd.arg2, ip) != RET_OK) RESP_CDR(RET_WRONG_ARG, 2);
CMD_CLEAR();
switch(num) {
case 2: act_nset_a(0, ip, NULL, NULL, NULL, NULL); return;
case 3: act_nset_a(0, NULL, ip, NULL, NULL, NULL); return;
case 4: act_nset_a(0, NULL, NULL, ip, NULL, NULL); return;
case 5: act_nset_a(0, NULL, NULL, NULL, ip, NULL); return;
//case 6: act_nset_a(0, NULL, NULL, NULL, NULL, ip); return;
case 6: RESP_CDR(RET_NOT_ALLOWED, 2); return;
default: CRITICAL_ERR("nset wrong num");
}
}
} else RESP_CDR(RET_WRONG_ARG, 1);
}
else if(atci.tcmd.sign == CMD_SIGN_EQUAL)
{
uint8_t sn[4], gw[4], dns1[4], dns2[4], *ptr[5];
num = 0;
if(atci.tcmd.arg1[0] != 0) {
if(CMP_CHAR_2(atci.tcmd.arg1, 'D', 'S')) RESP_CDR(RET_WRONG_ARG, 1);
else num++;
}
#define NSET_ARG_SET(arg_p, addr_p, idx_v, ret_v) \
if(arg_p[0] != 0) { \
num++; \
if(ip_check(arg_p, addr_p) != RET_OK) RESP_CDR(RET_WRONG_ARG, ret_v); \
ptr[idx_v] = addr_p; \
} else ptr[idx_v] = NULL
NSET_ARG_SET(atci.tcmd.arg2, ip, 0, 2);
NSET_ARG_SET(atci.tcmd.arg3, sn, 1, 3);
NSET_ARG_SET(atci.tcmd.arg4, gw, 2, 4);
NSET_ARG_SET(atci.tcmd.arg5, dns1, 3, 5);
NSET_ARG_SET(atci.tcmd.arg6, dns2, 4, 6);
if(num == 0) RESP_CR(RET_NOT_ALLOWED);
mode = atci.tcmd.arg1[0];
CMD_CLEAR();
act_nset_a(mode, ptr[0], ptr[1], ptr[2], ptr[3], ptr[4]);
}
else CRITICAL_ERRA("wrong sign(%d)", atci.tcmd.sign);
}
static void hdl_nstat(void)
{
int8_t num = -1;
if(atci.tcmd.sign == CMD_SIGN_NONE) atci.tcmd.sign = CMD_SIGN_QUEST;
if(atci.tcmd.sign == CMD_SIGN_QUEST)
{
if(atci.tcmd.arg1[0] != 0) {
if(str_check(isdigit, atci.tcmd.arg1) != RET_OK) RESP_CDR(RET_WRONG_ARG, 1);
if(CHK_DGT_RANGE(atci.tcmd.arg1, num, 1, 6)) RESP_CDR(RET_RANGE_OUT, 1);
}
CMD_CLEAR();
act_nstat(num);
}
else if(atci.tcmd.sign == CMD_SIGN_INDIV) RESP_CR(RET_WRONG_SIGN);
else if(atci.tcmd.sign == CMD_SIGN_EQUAL) RESP_CR(RET_WRONG_SIGN);
else CRITICAL_ERRA("wrong sign(%d)", atci.tcmd.sign);
}
static void hdl_nmac(void)
{
int8_t num = -1;
uint8_t mac[6];
if(atci.tcmd.sign == CMD_SIGN_NONE) atci.tcmd.sign = CMD_SIGN_QUEST;
if(atci.tcmd.sign == CMD_SIGN_QUEST)
{
if(atci.tcmd.arg1[0] != 0) {
if(str_check(isdigit, atci.tcmd.arg1) != RET_OK) RESP_CDR(RET_WRONG_ARG, 1);
if(CHK_DGT_RANGE(atci.tcmd.arg1, num, 1, 1)) RESP_CDR(RET_RANGE_OUT, 1);
}
CMD_CLEAR();
act_nmac_q();
}
else if(atci.tcmd.sign == CMD_SIGN_INDIV) RESP_CR(RET_WRONG_SIGN);
else if(atci.tcmd.sign == CMD_SIGN_EQUAL)
{
if(mac_check(atci.tcmd.arg1, mac) != RET_OK) RESP_CDR(RET_WRONG_ARG, 1);
CMD_CLEAR();
act_nmac_a(mac);
}
else CRITICAL_ERRA("wrong sign(%d)", atci.tcmd.sign);
}
static void hdl_mstat(void)
{
int8_t num = -1;
if(atci.tcmd.sign == CMD_SIGN_NONE) atci.tcmd.sign = CMD_SIGN_QUEST;
if(atci.tcmd.sign == CMD_SIGN_QUEST)
{
if(atci.tcmd.arg1[0] != 0) {
if(str_check(isdigit, atci.tcmd.arg1) != RET_OK) RESP_CDR(RET_WRONG_ARG, 1);
if(CHK_DGT_RANGE(atci.tcmd.arg1, num, 1, 1)) RESP_CDR(RET_RANGE_OUT, 1);
}
CMD_CLEAR();
act_mstat();
}
else if(atci.tcmd.sign == CMD_SIGN_INDIV) RESP_CR(RET_WRONG_SIGN);
else if(atci.tcmd.sign == CMD_SIGN_EQUAL) RESP_CR(RET_WRONG_SIGN);
else CRITICAL_ERRA("wrong sign(%d)", atci.tcmd.sign);
}
static void hdl_musart1(void)
{
int8_t num = -1;
S2E_Packet *value = get_S2E_Packet_pointer();
if(atci.tcmd.sign == CMD_SIGN_NONE) atci.tcmd.sign = CMD_SIGN_QUEST;
if(atci.tcmd.sign == CMD_SIGN_QUEST)
{
if(atci.tcmd.arg1[0] != 0) {
if(str_check(isdigit, atci.tcmd.arg1) != RET_OK) RESP_CDR(RET_WRONG_ARG, 1);
if(CHK_DGT_RANGE(atci.tcmd.arg1, num, 1, 5)) RESP_CDR(RET_RANGE_OUT, 1);
}
CMD_CLEAR();
act_uart_q(USART1, num);
}
else if(atci.tcmd.sign == CMD_SIGN_INDIV)
{
if(atci.tcmd.arg1[0] != 0) {
if(str_check(isdigit, atci.tcmd.arg1) != RET_OK) RESP_CDR(RET_WRONG_ARG, 1);
if(CHK_DGT_RANGE(atci.tcmd.arg1, num, 1, 5)) RESP_CDR(RET_RANGE_OUT, 1);
if(num == 1) { // Baud Rate
uint32_t baud, i, loop, valid_arg = 0;
if(str_check(isdigit, atci.tcmd.arg2) != RET_OK) RESP_CDR(RET_WRONG_ARG, 2);
baud = atoi((const char *)atci.tcmd.arg2);
loop = sizeof(baud_table) / sizeof(baud_table[0]);
for(i = 0 ; i < loop ; i++) {
if(baud == baud_table[i]) {
value->serial_info[0].baud_rate = baud;
valid_arg = 1;
break;
}
}
if(valid_arg == 0) RESP_CDR(RET_WRONG_ARG, 2);
CMD_CLEAR();
act_uart_a(USART1, &(value->serial_info[0]));
} else if(num == 2) { // Word Length
if(str_check(isdigit, atci.tcmd.arg2) != RET_OK) RESP_CDR(RET_WRONG_ARG, 2);
if(CHK_DGT_RANGE(atci.tcmd.arg2, num, 8, 9)) RESP_CDR(RET_RANGE_OUT, 2);
else value->serial_info[0].data_bits = num;
CMD_CLEAR();
act_uart_a(USART1, &(value->serial_info[0]));
} else if(num == 3) { // Parity Bit
if(str_check(isalpha, atci.tcmd.arg2) != RET_OK) RESP_CDR(RET_WRONG_ARG, 2);
if(CMP_CHAR_3(atci.tcmd.arg2, 'N', 'O', 'E')) RESP_CDR(RET_WRONG_ARG, 2);
else {
if(atci.tcmd.arg2[0] == 'N') value->serial_info[0].parity = parity_none;
else if(atci.tcmd.arg2[0] == 'O') value->serial_info[0].parity = parity_odd;
else if(atci.tcmd.arg2[0] == 'E') value->serial_info[0].parity = parity_even;
}
CMD_CLEAR();
act_uart_a(USART1, &(value->serial_info[0]));
} else if(num == 4) { // Stop Bit
if(str_check(isdigit, atci.tcmd.arg2) != RET_OK) RESP_CDR(RET_WRONG_ARG, 2);
if(CHK_DGT_RANGE(atci.tcmd.arg2, num, 1, 2)) RESP_CDR(RET_RANGE_OUT, 2);
else value->serial_info[0].stop_bits = num;
CMD_CLEAR();
act_uart_a(USART1, &(value->serial_info[0]));
} else if(num == 5) { // Flow Control
if(str_check(isdigit, atci.tcmd.arg2) != RET_OK) RESP_CDR(RET_WRONG_ARG, 2);
if(CHK_DGT_RANGE(atci.tcmd.arg2, num, 0, 3)) RESP_CDR(RET_RANGE_OUT, 2);
else value->serial_info[0].flow_control = num;
CMD_CLEAR();
act_uart_a(USART1, &(value->serial_info[0]));
} else RESP_CDR(RET_NOT_ALLOWED, 2); // ?��媛� �꽕�젙 �븘吏� ?�ы쁽�븞�븿
} else RESP_CDR(RET_WRONG_ARG, 1);
}
else if(atci.tcmd.sign == CMD_SIGN_EQUAL)
{
num = 0;
if(atci.tcmd.arg1[0] != 0) { // Baud Rate
uint32_t baud, i, loop, valid_arg = 0;
if(str_check(isdigit, atci.tcmd.arg1) != RET_OK) RESP_CDR(RET_WRONG_ARG, 1);
baud = atoi((const char *)atci.tcmd.arg1);
loop = sizeof(baud_table) / sizeof(baud_table[0]);
for(i = 0 ; i < loop ; i++) {
if(baud == baud_table[i]) {
value->serial_info[0].baud_rate = baud;
valid_arg = 1;
break;
}
}
if(valid_arg == 0) RESP_CDR(RET_WRONG_ARG, 1);
}
if(atci.tcmd.arg2[0] != 0) { // Word Length
if(str_check(isdigit, atci.tcmd.arg2) != RET_OK) RESP_CDR(RET_WRONG_ARG, 2);
if(CHK_DGT_RANGE(atci.tcmd.arg2, num, 8, 9)) RESP_CDR(RET_RANGE_OUT, 2);
else value->serial_info[0].data_bits = num;
}
if(atci.tcmd.arg3[0] != 0) { // Parity Bit
if(str_check(isalpha, atci.tcmd.arg3) != RET_OK) RESP_CDR(RET_WRONG_ARG, 3);
if(CMP_CHAR_3(atci.tcmd.arg3, 'N', 'O', 'E')) RESP_CDR(RET_WRONG_ARG, 3);
else {
if(atci.tcmd.arg3[0] == 'N') value->serial_info[0].parity = parity_none;
else if(atci.tcmd.arg3[0] == 'O') value->serial_info[0].parity = parity_odd;
else if(atci.tcmd.arg3[0] == 'E') value->serial_info[0].parity = parity_even;
}
}
if(atci.tcmd.arg4[0] != 0) { // Stop Bit
if(str_check(isdigit, atci.tcmd.arg4) != RET_OK) RESP_CDR(RET_WRONG_ARG, 4);
if(CHK_DGT_RANGE(atci.tcmd.arg4, num, 1, 2)) RESP_CDR(RET_RANGE_OUT, 4);
else value->serial_info[0].stop_bits = num;
}
if(atci.tcmd.arg5[0] != 0) { // Flow Control
if(str_check(isdigit, atci.tcmd.arg5) != RET_OK) RESP_CDR(RET_WRONG_ARG, 5);
if(CHK_DGT_RANGE(atci.tcmd.arg5, num, 0, 1)) RESP_CDR(RET_RANGE_OUT, 5);
else value->serial_info[0].flow_control = num;
}
CMD_CLEAR();
act_uart_a(USART1, &(value->serial_info[0]));
}
else CRITICAL_ERRA("wrong sign(%d)", atci.tcmd.sign);
}
static void hdl_musart2(void)
{
int8_t num = -1;
S2E_Packet *value = get_S2E_Packet_pointer();
if(atci.tcmd.sign == CMD_SIGN_NONE) atci.tcmd.sign = CMD_SIGN_QUEST;
if(atci.tcmd.sign == CMD_SIGN_QUEST)
{
if(atci.tcmd.arg1[0] != 0) {
if(str_check(isdigit, atci.tcmd.arg1) != RET_OK) RESP_CDR(RET_WRONG_ARG, 1);
if(CHK_DGT_RANGE(atci.tcmd.arg1, num, 1, 5)) RESP_CDR(RET_RANGE_OUT, 1);
}
CMD_CLEAR();
act_uart_q(USART2, num);
}
else if(atci.tcmd.sign == CMD_SIGN_INDIV)
{
if(atci.tcmd.arg1[0] != 0) {
if(str_check(isdigit, atci.tcmd.arg1) != RET_OK) RESP_CDR(RET_WRONG_ARG, 1);
if(CHK_DGT_RANGE(atci.tcmd.arg1, num, 1, 5)) RESP_CDR(RET_RANGE_OUT, 1);
if(num == 1) { // Baud Rate
uint32_t baud, i, loop, valid_arg = 0;
if(str_check(isdigit, atci.tcmd.arg2) != RET_OK) RESP_CDR(RET_WRONG_ARG, 2);
baud = atoi((const char *)atci.tcmd.arg2);
loop = sizeof(baud_table) / sizeof(baud_table[0]);
for(i = 0 ; i < loop ; i++) {
if(baud == baud_table[i]) {
value->serial_info[1].baud_rate = baud;
valid_arg = 1;
break;
}
}
if(valid_arg == 0) RESP_CDR(RET_WRONG_ARG, 2);
CMD_CLEAR();
act_uart_a(USART2, &(value->serial_info[1]));
} else if(num == 2) { // Word Length
if(str_check(isdigit, atci.tcmd.arg2) != RET_OK) RESP_CDR(RET_WRONG_ARG, 2);
if(CHK_DGT_RANGE(atci.tcmd.arg2, num, 8, 9)) RESP_CDR(RET_RANGE_OUT, 2);
else value->serial_info[1].data_bits = num;
CMD_CLEAR();
act_uart_a(USART2, &(value->serial_info[1]));
} else if(num == 3) { // Parity Bit
if(str_check(isalpha, atci.tcmd.arg2) != RET_OK) RESP_CDR(RET_WRONG_ARG, 2);
if(CMP_CHAR_3(atci.tcmd.arg2, 'N', 'O', 'E')) RESP_CDR(RET_WRONG_ARG, 2);
else {
if(atci.tcmd.arg2[0] == 'N') value->serial_info[1].parity = parity_none;
else if(atci.tcmd.arg2[0] == 'O') value->serial_info[1].parity = parity_odd;
else if(atci.tcmd.arg2[0] == 'E') value->serial_info[1].parity = parity_even;
}
CMD_CLEAR();
act_uart_a(USART2, &(value->serial_info[1]));
} else if(num == 4) { // Stop Bit
if(str_check(isdigit, atci.tcmd.arg2) != RET_OK) RESP_CDR(RET_WRONG_ARG, 2);
if(CHK_DGT_RANGE(atci.tcmd.arg2, num, 1, 2)) RESP_CDR(RET_RANGE_OUT, 2);
else value->serial_info[1].stop_bits = num;
CMD_CLEAR();
act_uart_a(USART2, &(value->serial_info[1]));
} else if(num == 5) { // Flow Control
if(str_check(isdigit, atci.tcmd.arg2) != RET_OK) RESP_CDR(RET_WRONG_ARG, 2);
if(CHK_DGT_RANGE(atci.tcmd.arg2, num, 0, 3)) RESP_CDR(RET_RANGE_OUT, 2);
else value->serial_info[1].flow_control = num;
CMD_CLEAR();
act_uart_a(USART2, &(value->serial_info[1]));
} else RESP_CDR(RET_NOT_ALLOWED, 2); // ?��媛� �꽕�젙 �븘吏� ?�ы쁽�븞�븿
} else RESP_CDR(RET_WRONG_ARG, 1);
}
else if(atci.tcmd.sign == CMD_SIGN_EQUAL)
{
num = 0;
if(atci.tcmd.arg1[0] != 0) { // Baud Rate
uint32_t baud, i, loop, valid_arg = 0;
if(str_check(isdigit, atci.tcmd.arg1) != RET_OK) RESP_CDR(RET_WRONG_ARG, 1);
baud = atoi((const char *)atci.tcmd.arg1);
loop = sizeof(baud_table) / sizeof(baud_table[0]);
for(i = 0 ; i < loop ; i++) {
if(baud == baud_table[i]) {
value->serial_info[1].baud_rate = baud;
valid_arg = 1;
break;
}
}
if(valid_arg == 0) RESP_CDR(RET_WRONG_ARG, 1);
}
if(atci.tcmd.arg2[0] != 0) { // Word Length
if(str_check(isdigit, atci.tcmd.arg2) != RET_OK) RESP_CDR(RET_WRONG_ARG, 2);
if(CHK_DGT_RANGE(atci.tcmd.arg2, num, 8, 9)) RESP_CDR(RET_RANGE_OUT, 2);
else value->serial_info[1].data_bits = num;
}
if(atci.tcmd.arg3[0] != 0) { // Parity Bit
if(str_check(isalpha, atci.tcmd.arg3) != RET_OK) RESP_CDR(RET_WRONG_ARG, 3);
if(CMP_CHAR_3(atci.tcmd.arg3, 'N', 'O', 'E')) RESP_CDR(RET_WRONG_ARG, 3);
else {
if(atci.tcmd.arg3[0] == 'N') value->serial_info[1].parity = parity_none;
else if(atci.tcmd.arg3[0] == 'O') value->serial_info[1].parity = parity_odd;
else if(atci.tcmd.arg3[0] == 'E') value->serial_info[1].parity = parity_even;
}
}
if(atci.tcmd.arg4[0] != 0) { // Stop Bit
if(str_check(isdigit, atci.tcmd.arg4) != RET_OK) RESP_CDR(RET_WRONG_ARG, 4);
if(CHK_DGT_RANGE(atci.tcmd.arg4, num, 1, 2)) RESP_CDR(RET_RANGE_OUT, 4);
else value->serial_info[1].stop_bits = num;
}
if(atci.tcmd.arg5[0] != 0) { // Flow Control
if(str_check(isdigit, atci.tcmd.arg5) != RET_OK) RESP_CDR(RET_WRONG_ARG, 5);
if(CHK_DGT_RANGE(atci.tcmd.arg5, num, 0, 3)) RESP_CDR(RET_RANGE_OUT, 5);
else value->serial_info[1].flow_control = num;
}
CMD_CLEAR();
act_uart_a(USART2, &(value->serial_info[1]));
}
else CRITICAL_ERRA("wrong sign(%d)", atci.tcmd.sign);
}
static void hdl_msave(void)
{
if(atci.tcmd.sign == CMD_SIGN_NONE) {
CMD_CLEAR();
act_msave();
} else RESP_CR(RET_WRONG_SIGN);
}
static void hdl_mrst(void)
{
if(atci.tcmd.sign == CMD_SIGN_NONE) {
cmd_resp(RET_OK, VAL_NONE);
// whil(RingBuffer_GetCount(&txring) != 0);
NVIC_SystemReset();
} else RESP_CR(RET_WRONG_SIGN);
}
static void hdl_fiodir(void)
{
int8_t pin_num = -1, pin_dir = -1;
if(atci.tcmd.sign == CMD_SIGN_NONE) RESP_CR(RET_WRONG_SIGN);
else if(atci.tcmd.sign == CMD_SIGN_QUEST) RESP_CR(RET_WRONG_SIGN);
else if(atci.tcmd.sign == CMD_SIGN_INDIV) RESP_CR(RET_WRONG_SIGN);
else if(atci.tcmd.sign == CMD_SIGN_EQUAL) {
if(atci.tcmd.arg1[0] != 0) {
if(str_check(isdigit, atci.tcmd.arg1) != RET_OK) RESP_CDR(RET_WRONG_ARG, 1);
if(CHK_DGT_RANGE(atci.tcmd.arg1, pin_num, 1, 16)) RESP_CDR(RET_RANGE_OUT, 1);
}
if(atci.tcmd.arg2[0] != 0) {
if(str_check(isdigit, atci.tcmd.arg2) != RET_OK) RESP_CDR(RET_WRONG_ARG, 2);
if(CHK_DGT_RANGE(atci.tcmd.arg2, pin_dir, 1, 2)) RESP_CDR(RET_RANGE_OUT, 2);
}
CMD_CLEAR();
act_fiodir(pin_num, pin_dir);
} else CRITICAL_ERRA("wrong sign(%d)", atci.tcmd.sign);
}
static void hdl_fioval(void)
{
int8_t pin_num = -1, pin_output = -1;
if(atci.tcmd.sign == CMD_SIGN_NONE) RESP_CR(RET_WRONG_SIGN);
else if(atci.tcmd.sign == CMD_SIGN_QUEST) RESP_CR(RET_WRONG_SIGN);
else if(atci.tcmd.sign == CMD_SIGN_INDIV) RESP_CR(RET_WRONG_SIGN);
else if(atci.tcmd.sign == CMD_SIGN_EQUAL) {
if(atci.tcmd.arg1[0] != 0) {
if(str_check(isdigit, atci.tcmd.arg1) != RET_OK) RESP_CDR(RET_WRONG_ARG, 1);
if(CHK_DGT_RANGE(atci.tcmd.arg1, pin_num, 1, 16)) RESP_CDR(RET_RANGE_OUT, 1);
}
if(atci.tcmd.arg2[0] != 0) {
if(str_check(isdigit, atci.tcmd.arg2) != RET_OK) RESP_CDR(RET_WRONG_ARG, 2);
if(CHK_DGT_RANGE(atci.tcmd.arg2, pin_output, 0, 1)) RESP_CDR(RET_RANGE_OUT, 2);
}
CMD_CLEAR();
act_fioval(pin_num, pin_output);
} else CRITICAL_ERRA("wrong sign(%d)", atci.tcmd.sign);
}
|
14453.c | #include <stdio.h>
#include <string.h>
int main(){
char str[30];
scanf("%[^\n]%*c", str);
char* token = strtok(str, " ");
while (token != NULL) {
printf("%s\n", token);
token = strtok(NULL, " ");
}
return 0;
}
|
563423.c | /*!
* @file main.c
* @brief Brushlesss9 Click example
*
* # Description
* This application is a schowcase of controlling speed and direction of brushless motor with hall sesnor.
*
* The demo application is composed of two sections :
*
* ## Application Init
* Initialization of LOG, PWM module and additional pins for controlling motor.
*
* ## Application Task
* In span of 2 seconds changes duty cycle from 0 to 100% and then back to 0, at the end changes direction of motor.
*
* @author Luka Filipovic
*
*/
#include "board.h"
#include "log.h"
#include "brushless9.h"
#include "math.h"
#define DUTY_CHANGE_DELAY 2000
#define BREAK_DELAY 5000
static brushless9_t brushless9;
static log_t logger;
static uint8_t direction = 0;
void application_init ( void )
{
log_cfg_t log_cfg; /**< Logger config object. */
brushless9_cfg_t brushless9_cfg; /**< Click config object. */
// Logger initialization.
LOG_MAP_USB_UART( log_cfg );
log_cfg.level = LOG_LEVEL_DEBUG;
log_cfg.baud = 115200;
log_init( &logger, &log_cfg );
log_info( &logger, " Application Init " );
// Click initialization.
brushless9_cfg_setup( &brushless9_cfg );
BRUSHLESS9_MAP_MIKROBUS( brushless9_cfg, MIKROBUS_1 );
err_t init_flag = brushless9_init( &brushless9, &brushless9_cfg );
if ( init_flag == PWM_ERROR )
{
log_error( &logger, " Application Init Error. " );
log_info( &logger, " Please, run program again... " );
for ( ; ; );
}
brushless9_set_dir( &brushless9, direction );
brushless9_set_brk( &brushless9, 1 );
brushless9_set_duty_cycle ( &brushless9, 0 );
brushless9_pwm_start( &brushless9 );
log_info( &logger, " Application Task " );
}
void application_task ( void )
{
log_info( &logger, " Starting... " );
brushless9_set_brk( &brushless9, 0 );
for ( float duty = 0.1; duty < 1; duty += 0.1 )
{
Delay_ms( DUTY_CHANGE_DELAY );
brushless9_set_duty_cycle ( &brushless9, duty );
log_printf( &logger, "Duty: %u%%\r\n", ( uint16_t )ceil( duty * 100 ) );
}
for ( float duty = 0.9; duty >= 0; duty -= 0.1 )
{
Delay_ms( DUTY_CHANGE_DELAY );
brushless9_set_duty_cycle ( &brushless9, duty );
log_printf( &logger, "Duty: %u%%\r\n", ( uint16_t )ceil( duty * 100 ) );
}
Delay_ms( DUTY_CHANGE_DELAY );
log_info( &logger, " Stopping... " );
brushless9_set_duty_cycle ( &brushless9, 0 );
brushless9_set_brk( &brushless9, 1 );
Delay_ms( BREAK_DELAY );
log_info( &logger, " Changing direction... " );
direction = !direction;
brushless9_set_dir( &brushless9, direction );
}
void main ( void )
{
application_init( );
for ( ; ; )
{
application_task( );
}
}
// ------------------------------------------------------------------------ END
|
859819.c | // Auto-generated file. Do not edit!
// Template: src/qs8-igemm/MRx4c2-sse.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 <tmmintrin.h>
#include <xnnpack/igemm.h>
#include <xnnpack/math.h>
void xnn_qs8_igemm_minmax_ukernel_2x4c2__ssse3_ld64(
size_t mr,
size_t nc,
size_t kc,
size_t ks,
const int8_t** restrict a,
const void* restrict w,
int8_t* restrict c,
size_t cm_stride,
size_t cn_stride,
size_t a_offset,
const int8_t* zero,
const union xnn_qs8_gemm_params params[restrict XNN_MIN_ELEMENTS(1)]) XNN_DISABLE_TSAN
{
assert(mr != 0);
assert(mr <= 2);
assert(nc != 0);
assert(kc != 0);
assert(ks != 0);
assert(ks % (2 * sizeof(void*)) == 0);
assert(a_offset % sizeof(int8_t) == 0);
assert(a != NULL);
assert(w != NULL);
assert(c != NULL);
kc = round_up_po2(kc, 2);
int8_t* c0 = c;
int8_t* c1 = (int8_t*) ((uintptr_t) c0 + cm_stride);
if XNN_UNPREDICTABLE(mr != 2) {
c1 = c0;
}
do {
__m128i vacc0x0123 = _mm_loadu_si128((const __m128i*) w);
__m128i vacc1x0123 = vacc0x0123;
w = (const void*) ((uintptr_t) w + 4 * sizeof(int32_t));
size_t p = ks;
do {
const int8_t* restrict a0 = a[0];
if XNN_UNPREDICTABLE(a0 != zero) {
a0 = (const int8_t*) ((uintptr_t) a0 + a_offset);
}
const int8_t* restrict a1 = a[1];
if XNN_UNPREDICTABLE(a1 != zero) {
a1 = (const int8_t*) ((uintptr_t) a1 + a_offset);
}
a += 2;
size_t k = kc;
while (k >= 8 * sizeof(int8_t)) {
const __m128i va0 = _mm_loadl_epi64((const __m128i*) a0);
const __m128i vxa0 = _mm_unpacklo_epi8(va0, _mm_cmpgt_epi8(_mm_setzero_si128(), va0));
a0 += 8;
const __m128i va1 = _mm_loadl_epi64((const __m128i*) a1);
const __m128i vxa1 = _mm_unpacklo_epi8(va1, _mm_cmpgt_epi8(_mm_setzero_si128(), va1));
a1 += 8;
const __m128i vb0 = _mm_loadl_epi64((const __m128i*) w);
const __m128i vxb0 = _mm_unpacklo_epi8(vb0, _mm_cmpgt_epi8(_mm_setzero_si128(), vb0));
vacc0x0123 = _mm_add_epi32(vacc0x0123,
_mm_madd_epi16(_mm_shuffle_epi32(vxa0, _MM_SHUFFLE(0, 0, 0, 0)), vxb0));
vacc1x0123 = _mm_add_epi32(vacc1x0123,
_mm_madd_epi16(_mm_shuffle_epi32(vxa1, _MM_SHUFFLE(0, 0, 0, 0)), vxb0));
const __m128i vb1 = _mm_loadl_epi64((const __m128i*) ((uintptr_t) w + 8));
const __m128i vxb1 = _mm_unpacklo_epi8(vb1, _mm_cmpgt_epi8(_mm_setzero_si128(), vb1));
vacc0x0123 = _mm_add_epi32(vacc0x0123,
_mm_madd_epi16(_mm_shuffle_epi32(vxa0, _MM_SHUFFLE(1, 1, 1, 1)), vxb1));
vacc1x0123 = _mm_add_epi32(vacc1x0123,
_mm_madd_epi16(_mm_shuffle_epi32(vxa1, _MM_SHUFFLE(1, 1, 1, 1)), vxb1));
const __m128i vb2 = _mm_loadl_epi64((const __m128i*) ((uintptr_t) w + 16));
const __m128i vxb2 = _mm_unpacklo_epi8(vb2, _mm_cmpgt_epi8(_mm_setzero_si128(), vb2));
vacc0x0123 = _mm_add_epi32(vacc0x0123,
_mm_madd_epi16(_mm_shuffle_epi32(vxa0, _MM_SHUFFLE(2, 2, 2, 2)), vxb2));
vacc1x0123 = _mm_add_epi32(vacc1x0123,
_mm_madd_epi16(_mm_shuffle_epi32(vxa1, _MM_SHUFFLE(2, 2, 2, 2)), vxb2));
const __m128i vb3 = _mm_loadl_epi64((const __m128i*) ((uintptr_t) w + 24));
const __m128i vxb3 = _mm_unpacklo_epi8(vb3, _mm_cmpgt_epi8(_mm_setzero_si128(), vb3));
vacc0x0123 = _mm_add_epi32(vacc0x0123,
_mm_madd_epi16(_mm_shuffle_epi32(vxa0, _MM_SHUFFLE(3, 3, 3, 3)), vxb3));
vacc1x0123 = _mm_add_epi32(vacc1x0123,
_mm_madd_epi16(_mm_shuffle_epi32(vxa1, _MM_SHUFFLE(3, 3, 3, 3)), vxb3));
w = (const void*) ((uintptr_t) w + 32);
k -= 8 * sizeof(int8_t);
}
if (k != 0) {
const __m128i va0 = _mm_loadl_epi64((const __m128i*) a0);
const __m128i vxa0 = _mm_unpacklo_epi8(va0, _mm_cmpgt_epi8(_mm_setzero_si128(), va0));
a0 = (const int8_t*) ((uintptr_t) a0 + k);
const __m128i va1 = _mm_loadl_epi64((const __m128i*) a1);
const __m128i vxa1 = _mm_unpacklo_epi8(va1, _mm_cmpgt_epi8(_mm_setzero_si128(), va1));
a1 = (const int8_t*) ((uintptr_t) a1 + k);
const __m128i vb0 = _mm_loadl_epi64((const __m128i*) w);
w = (const void*) ((uintptr_t) w + 8);
const __m128i vxb0 = _mm_unpacklo_epi8(vb0, _mm_cmpgt_epi8(_mm_setzero_si128(), vb0));
vacc0x0123 = _mm_add_epi32(vacc0x0123,
_mm_madd_epi16(_mm_shuffle_epi32(vxa0, _MM_SHUFFLE(0, 0, 0, 0)), vxb0));
vacc1x0123 = _mm_add_epi32(vacc1x0123,
_mm_madd_epi16(_mm_shuffle_epi32(vxa1, _MM_SHUFFLE(0, 0, 0, 0)), vxb0));
if (k > 2 * sizeof(int8_t)) {
const __m128i vb1 = _mm_loadl_epi64((const __m128i*) w);
w = (const void*) ((uintptr_t) w + 8);
const __m128i vxb1 = _mm_unpacklo_epi8(vb1, _mm_cmpgt_epi8(_mm_setzero_si128(), vb1));
vacc0x0123 = _mm_add_epi32(vacc0x0123,
_mm_madd_epi16(_mm_shuffle_epi32(vxa0, _MM_SHUFFLE(1, 1, 1, 1)), vxb1));
vacc1x0123 = _mm_add_epi32(vacc1x0123,
_mm_madd_epi16(_mm_shuffle_epi32(vxa1, _MM_SHUFFLE(1, 1, 1, 1)), vxb1));
if (k > 4 * sizeof(int8_t)) {
const __m128i vb2 = _mm_loadl_epi64((const __m128i*) w);
w = (const void*) ((uintptr_t) w + 8);
const __m128i vxb2 = _mm_unpacklo_epi8(vb2, _mm_cmpgt_epi8(_mm_setzero_si128(), vb2));
vacc0x0123 = _mm_add_epi32(vacc0x0123,
_mm_madd_epi16(_mm_shuffle_epi32(vxa0, _MM_SHUFFLE(2, 2, 2, 2)), vxb2));
vacc1x0123 = _mm_add_epi32(vacc1x0123,
_mm_madd_epi16(_mm_shuffle_epi32(vxa1, _MM_SHUFFLE(2, 2, 2, 2)), vxb2));
}
}
}
p -= 2 * sizeof(void*);
} while (p != 0);
const __m128i vmultiplier = _mm_load_si128((const __m128i*) params->sse2.multiplier);
const __m128i vrounding = _mm_load_si128((const __m128i*) params->sse2.rounding);
const __m128i vnmask0x0123 = _mm_cmpgt_epi32(_mm_setzero_si128(), vacc0x0123);
const __m128i vnmask1x0123 = _mm_cmpgt_epi32(_mm_setzero_si128(), vacc1x0123);
const __m128i vabsacc0x0123 = _mm_abs_epi32(vacc0x0123);
const __m128i vabsacc1x0123 = _mm_abs_epi32(vacc1x0123);
const __m128i vabsacc0x1133 = _mm_shuffle_epi32(vabsacc0x0123, _MM_SHUFFLE(3, 3, 1, 1));
const __m128i vabsacc1x1133 = _mm_shuffle_epi32(vabsacc1x0123, _MM_SHUFFLE(3, 3, 1, 1));
const __m128i vabsprod0x02 = _mm_mul_epu32(vabsacc0x0123, vmultiplier);
const __m128i vabsprod1x02 = _mm_mul_epu32(vabsacc1x0123, vmultiplier);
const __m128i vnmask0x02 = _mm_shuffle_epi32(vnmask0x0123, _MM_SHUFFLE(2, 2, 0, 0));
const __m128i vnmask1x02 = _mm_shuffle_epi32(vnmask1x0123, _MM_SHUFFLE(2, 2, 0, 0));
const __m128i vprod0x02 = _mm_sub_epi64(_mm_xor_si128(vabsprod0x02, vnmask0x02), vnmask0x02);
const __m128i vprod1x02 = _mm_sub_epi64(_mm_xor_si128(vabsprod1x02, vnmask1x02), vnmask1x02);
const __m128i vq31prod0x02 = _mm_srli_epi64(_mm_add_epi64(vprod0x02, vrounding), 31);
const __m128i vq31prod1x02 = _mm_srli_epi64(_mm_add_epi64(vprod1x02, vrounding), 31);
const __m128i vabsprod0x13 = _mm_mul_epu32(vabsacc0x1133, vmultiplier);
const __m128i vabsprod1x13 = _mm_mul_epu32(vabsacc1x1133, vmultiplier);
const __m128i vnmask0x13 = _mm_shuffle_epi32(vnmask0x0123, _MM_SHUFFLE(3, 3, 1, 1));
const __m128i vnmask1x13 = _mm_shuffle_epi32(vnmask1x0123, _MM_SHUFFLE(3, 3, 1, 1));
const __m128i vprod0x13 = _mm_sub_epi64(_mm_xor_si128(vabsprod0x13, vnmask0x13), vnmask0x13);
const __m128i vprod1x13 = _mm_sub_epi64(_mm_xor_si128(vabsprod1x13, vnmask1x13), vnmask1x13);
const __m128i vq31prod0x13 = _mm_srli_epi64(_mm_add_epi64(vprod0x13, vrounding), 31);
const __m128i vq31prod1x13 = _mm_srli_epi64(_mm_add_epi64(vprod1x13, vrounding), 31);
const __m128i vq31prod0x0213 = _mm_castps_si128(_mm_shuffle_ps(
_mm_castsi128_ps(vq31prod0x02), _mm_castsi128_ps(vq31prod0x13), _MM_SHUFFLE(2, 0, 2, 0)));
const __m128i vq31prod1x0213 = _mm_castps_si128(_mm_shuffle_ps(
_mm_castsi128_ps(vq31prod1x02), _mm_castsi128_ps(vq31prod1x13), _MM_SHUFFLE(2, 0, 2, 0)));
const __m128i vq31prod0x0123 = _mm_shuffle_epi32(vq31prod0x0213, _MM_SHUFFLE(3, 1, 2, 0));
const __m128i vq31prod1x0123 = _mm_shuffle_epi32(vq31prod1x0213, _MM_SHUFFLE(3, 1, 2, 0));
const __m128i vremainder_mask = _mm_load_si128((const __m128i*) params->sse2.remainder_mask);
const __m128i vrem0x0123 =
_mm_add_epi32(_mm_and_si128(vq31prod0x0123, vremainder_mask), _mm_cmpgt_epi32(_mm_setzero_si128(), vq31prod0x0123));
const __m128i vrem1x0123 =
_mm_add_epi32(_mm_and_si128(vq31prod1x0123, vremainder_mask), _mm_cmpgt_epi32(_mm_setzero_si128(), vq31prod1x0123));
const __m128i vremainder_threshold = _mm_load_si128((const __m128i*) params->sse2.remainder_threshold);
const __m128i vshift = _mm_load_si128((const __m128i*) params->sse2.shift);
vacc0x0123 =
_mm_sub_epi32(_mm_sra_epi32(vq31prod0x0123, vshift), _mm_cmpgt_epi32(vrem0x0123, vremainder_threshold));
vacc1x0123 =
_mm_sub_epi32(_mm_sra_epi32(vq31prod1x0123, vshift), _mm_cmpgt_epi32(vrem1x0123, vremainder_threshold));
const __m128i voutput_zero_point = _mm_load_si128((const __m128i*) params->sse2.output_zero_point);
__m128i vacc01x0123 = _mm_adds_epi16(_mm_packs_epi32(vacc0x0123, vacc1x0123), voutput_zero_point);
const __m128i voutput_min = _mm_load_si128((const __m128i*) params->sse2.output_min);
const __m128i voutput_max = _mm_load_si128((const __m128i*) params->sse2.output_max);
vacc01x0123 = _mm_min_epi16(_mm_max_epi16(vacc01x0123, voutput_min), voutput_max);
__m128i vout = _mm_packs_epi16(vacc01x0123, vacc01x0123);
if (nc >= 4) {
*((uint32_t*) c1) = (uint32_t) _mm_cvtsi128_si32(_mm_shuffle_epi32(vout, _MM_SHUFFLE(1, 1, 1, 1)));
c1 = (int8_t*) ((uintptr_t) c1 + cn_stride);
*((uint32_t*) c0) = (uint32_t) _mm_cvtsi128_si32(vout);
c0 = (int8_t*) ((uintptr_t) c0 + cn_stride);
a = (const int8_t**restrict) ((uintptr_t) a - ks);
nc -= 4;
} else {
if (nc & 2) {
*((uint16_t*) c1) = (uint16_t) _mm_extract_epi16(vout, 2);
c1 += 2;
*((uint16_t*) c0) = (uint16_t) _mm_extract_epi16(vout, 0);
c0 += 2;
vout = _mm_srli_epi32(vout, 16);
}
if (nc & 1) {
*((int8_t*) c1) = (int8_t) _mm_extract_epi16(vout, 2);
*((int8_t*) c0) = (int8_t) _mm_cvtsi128_si32(vout);
}
nc = 0;
}
} while (nc != 0);
}
|
544365.c | /**
******************************************************************************
* @file Examples_LL/RCC/RCC_HWAutoMSICalibration/Src/stm32l4xx_it.c
* @author MCD Application Team
* @brief Main Interrupt Service Routines.
* This file provides template for all exceptions handler and
* peripherals interrupt service routine.
******************************************************************************
* @attention
*
* <h2><center>© COPYRIGHT(c) 2017 STMicroelectronics</center></h2>
*
* 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 STMicroelectronics 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.
*
******************************************************************************
*/
/* Includes ------------------------------------------------------------------*/
#include "stm32l4xx_it.h"
/** @addtogroup STM32L4xx_LL_Examples
* @{
*/
/** @addtogroup RCC_HWAutoMSICalibration
* @{
*/
/* Private typedef -----------------------------------------------------------*/
/* Private define ------------------------------------------------------------*/
/* Private macro -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
/* Private function prototypes -----------------------------------------------*/
/* Private functions ---------------------------------------------------------*/
/******************************************************************************/
/* Cortex-M4 Processor Exceptions Handlers */
/******************************************************************************/
/**
* @brief This function handles NMI exception.
* @param None
* @retval None
*/
void NMI_Handler(void)
{
}
/**
* @brief This function handles Hard Fault exception.
* @param None
* @retval None
*/
void HardFault_Handler(void)
{
/* Go to infinite loop when Hard Fault exception occurs */
while (1)
{
}
}
/**
* @brief This function handles Memory Manage exception.
* @param None
* @retval None
*/
void MemManage_Handler(void)
{
/* Go to infinite loop when Memory Manage exception occurs */
while (1)
{
}
}
/**
* @brief This function handles Bus Fault exception.
* @param None
* @retval None
*/
void BusFault_Handler(void)
{
/* Go to infinite loop when Bus Fault exception occurs */
while (1)
{
}
}
/**
* @brief This function handles Usage Fault exception.
* @param None
* @retval None
*/
void UsageFault_Handler(void)
{
/* Go to infinite loop when Usage Fault exception occurs */
while (1)
{
}
}
/**
* @brief This function handles SVCall exception.
* @param None
* @retval None
*/
void SVC_Handler(void)
{
}
/**
* @brief This function handles Debug Monitor exception.
* @param None
* @retval None
*/
void DebugMon_Handler(void)
{
}
/**
* @brief This function handles PendSVC exception.
* @param None
* @retval None
*/
void PendSV_Handler(void)
{
}
/**
* @brief This function handles SysTick Handler.
* @param None
* @retval None
*/
void SysTick_Handler(void)
{
}
/******************************************************************************/
/* STM32L4xx Peripherals Interrupt Handlers */
/* Add here the Interrupt Handler for the used peripheral(s) (PPP), for the */
/* available peripheral interrupt handler's name please refer to the startup */
/* file (startup_stm32l4xx.s). */
/******************************************************************************/
/**
* @brief This function handles external lines 10 to 15 interrupt request.
* @param None
* @retval None
*/
void USER_BUTTON_IRQHANDLER(void)
{
/* Manage Flags */
if(LL_EXTI_IsActiveFlag_0_31(USER_BUTTON_EXTI_LINE) != RESET)
{
LL_EXTI_ClearFlag_0_31(USER_BUTTON_EXTI_LINE);
/* Manage code in main.c. */
UserButton_Callback();
}
}
/**
* @}
*/
/**
* @}
*/
/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
|
33315.c | /****************************************************************************
* libs/libc/stdio/lib_libfflush.c
*
* Copyright (C) 2007-2008, 2011-2014, 2017 Gregory Nutt. All rights reserved.
* Author: Gregory Nutt <[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.
* 3. Neither the name NuttX nor the names of its contributors may be
* used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
****************************************************************************/
/****************************************************************************
* Included Files
****************************************************************************/
#include <nuttx/config.h>
#include <sys/types.h>
#include <stdbool.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <nuttx/fs/fs.h>
#include "libc.h"
/****************************************************************************
* Public Functions
****************************************************************************/
/****************************************************************************
* Name: lib_fflush
*
* Description:
* The function lib_fflush() forces a write of all user-space buffered data for
* the given output or update stream via the stream's underlying write
* function. The open status of the stream is unaffected.
*
* Input Parameters:
* stream - the stream to flush
* bforce - flush must be complete.
*
* Returned Value:
* A negated errno value on failure, otherwise the number of bytes remaining
* in the buffer.
*
****************************************************************************/
ssize_t lib_fflush(FAR FILE *stream, bool bforce)
{
#ifndef CONFIG_STDIO_DISABLE_BUFFERING
FAR const unsigned char *src;
ssize_t bytes_written;
ssize_t nbuffer;
int ret;
/* Return EBADF if the file is not opened for writing */
if (stream->fs_fd < 0 || (stream->fs_oflags & O_WROK) == 0)
{
return -EBADF;
}
/* Make sure that we have exclusive access to the stream */
lib_take_semaphore(stream);
/* Check if there is an allocated I/O buffer */
if (stream->fs_bufstart == NULL)
{
/* No, then there can be nothing remaining in the buffer. */
ret = 0;
goto errout_with_sem;
}
/* Make sure that the buffer holds valid data */
if (stream->fs_bufpos != stream->fs_bufstart)
{
/* Make sure that the buffer holds buffered write data. We do not
* support concurrent read/write buffer usage.
*/
if (stream->fs_bufread != stream->fs_bufstart)
{
/* The buffer holds read data... just return zero meaning "no bytes
* remaining in the buffer."
*/
ret = 0;
goto errout_with_sem;
}
/* How many bytes of write data are used in the buffer now */
nbuffer = stream->fs_bufpos - stream->fs_bufstart;
/* Try to write that amount */
src = stream->fs_bufstart;
do
{
/* Perform the write */
bytes_written = _NX_WRITE(stream->fs_fd, src, nbuffer);
if (bytes_written < 0)
{
/* Write failed. The cause of the failure is in 'errno'.
* returned the negated errno value.
*/
stream->fs_flags |= __FS_FLAG_ERROR;
ret = _NX_GETERRVAL(bytes_written);
goto errout_with_sem;
}
/* Handle partial writes. fflush() must either return with
* an error condition or with the data successfully flushed
* from the buffer.
*/
src += bytes_written;
nbuffer -= bytes_written;
}
while (bforce && nbuffer > 0);
/* Reset the buffer position to the beginning of the buffer */
stream->fs_bufpos = stream->fs_bufstart;
/* For the case of an incomplete write, nbuffer will be non-zero
* It will hold the number of bytes that were not written.
* Move the data down in the buffer to handle this (rare) case
*/
while (nbuffer)
{
*stream->fs_bufpos++ = *src++;
--nbuffer;
}
}
/* Restore normal access to the stream and return the number of bytes
* remaining in the buffer.
*/
lib_give_semaphore(stream);
return stream->fs_bufpos - stream->fs_bufstart;
errout_with_sem:
lib_give_semaphore(stream);
return ret;
#else
/* Return no bytes remaining in the buffer */
return 0;
#endif
}
|
704137.c | /* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE121_Stack_Based_Buffer_Overflow__CWE193_wchar_t_alloca_cpy_54c.c
Label Definition File: CWE121_Stack_Based_Buffer_Overflow__CWE193.label.xml
Template File: sources-sink-54c.tmpl.c
*/
/*
* @description
* CWE: 121 Stack Based Buffer Overflow
* BadSource: Point data to a buffer that does not have space for a NULL terminator
* GoodSource: Point data to a buffer that includes space for a NULL terminator
* Sink: cpy
* BadSink : Copy string to data using wcscpy()
* Flow Variant: 54 Data flow: data passed as an argument from one function through three others to a fifth; all five functions are in different source files
*
* */
#include "std_testcase.h"
#ifndef _WIN32
#include <wchar.h>
#endif
/* MAINTENANCE NOTE: The length of this string should equal the 10 */
#define SRC_STRING L"AAAAAAAAAA"
/* all the sinks are the same, we just want to know where the hit originated if a tool flags one */
#ifndef OMITBAD
/* bad function declaration */
void CWE121_Stack_Based_Buffer_Overflow__CWE193_wchar_t_alloca_cpy_54d_badSink(wchar_t * data);
void CWE121_Stack_Based_Buffer_Overflow__CWE193_wchar_t_alloca_cpy_54c_badSink(wchar_t * data)
{
CWE121_Stack_Based_Buffer_Overflow__CWE193_wchar_t_alloca_cpy_54d_badSink(data);
}
#endif /* OMITBAD */
#ifndef OMITGOOD
/* good function declaration */
void CWE121_Stack_Based_Buffer_Overflow__CWE193_wchar_t_alloca_cpy_54d_goodG2BSink(wchar_t * data);
/* goodG2B uses the GoodSource with the BadSink */
void CWE121_Stack_Based_Buffer_Overflow__CWE193_wchar_t_alloca_cpy_54c_goodG2BSink(wchar_t * data)
{
CWE121_Stack_Based_Buffer_Overflow__CWE193_wchar_t_alloca_cpy_54d_goodG2BSink(data);
}
#endif /* OMITGOOD */
|
723671.c | /**************************************************************************
* @file pn532.c
* @author Yehui from Waveshare
* @license BSD
*
* This is a library for the Waveshare PN532 NFC modules
*
* Check out the links above for our tutorials and wiring diagrams
* These chips use SPI communicate.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documnetation 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
* furished 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 OR 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 "pn532.h"
const uint8_t PN532_ACK[] = {0x00, 0x00, 0xFF, 0x00, 0xFF, 0x00};
const uint8_t PN532_FRAME_START[] = {0x00, 0x00, 0xFF};
#define PN532_FRAME_MAX_LENGTH 255
#define PN532_DEFAULT_TIMEOUT 1000
/**
* @brief: Write a frame to the PN532 of at most length bytes in size.
* Note that less than length bytes might be returned!
* @retval: Returns -1 if there is an error parsing the frame.
*/
int PN532_WriteFrame(PN532* pn532, uint8_t* data, uint16_t length) {
if (length > PN532_FRAME_MAX_LENGTH || length < 1) {
return PN532_STATUS_ERROR; // Data must be array of 1 to 255 bytes.
}
// Build frame to send as:
// - Preamble (0x00)
// - Start code (0x00, 0xFF)
// - Command length (1 byte)
// - Command length checksum
// - Command bytes
// - Checksum
// - Postamble (0x00)
uint8_t frame[PN532_FRAME_MAX_LENGTH + 7];
uint8_t checksum = 0;
frame[0] = PN532_PREAMBLE;
frame[1] = PN532_STARTCODE1;
frame[2] = PN532_STARTCODE2;
for (uint8_t i = 0; i < 3; i++) {
checksum += frame[i];
}
frame[3] = length & 0xFF;
frame[4] = (~length + 1) & 0xFF;
for (uint8_t i = 0; i < length; i++) {
frame[5 + i] = data[i];
checksum += data[i];
}
frame[length + 5] = ~checksum & 0xFF;
frame[length + 6] = PN532_POSTAMBLE;
if (pn532->write_data(frame, length + 7) != PN532_STATUS_OK) {
return PN532_STATUS_ERROR;
}
return PN532_STATUS_OK;
}
/**
* @brief: Read a response frame from the PN532 of at most length bytes in size.
* Note that less than length bytes might be returned!
* @retval: Returns frame length or -1 if there is an error parsing the frame.
*/
int PN532_ReadFrame(PN532* pn532, uint8_t* response, uint16_t length) {
uint8_t buff[PN532_FRAME_MAX_LENGTH + 7];
uint8_t checksum = 0;
// Read frame with expected length of data.
pn532->read_data(buff, length + 7);
// Swallow all the 0x00 values that preceed 0xFF.
uint8_t offset = 0;
while (buff[offset] == 0x00) {
offset += 1;
if (offset >= length + 8){
pn532->log("Response frame preamble does not contain 0x00FF!");
return PN532_STATUS_ERROR;
}
}
if (buff[offset] != 0xFF) {
pn532->log("Response frame preamble does not contain 0x00FF!");
return PN532_STATUS_ERROR;
}
offset += 1;
if (offset >= length + 8) {
pn532->log("Response contains no data!");
return PN532_STATUS_ERROR;
}
// Check length & length checksum match.
uint8_t frame_len = buff[offset];
if (((frame_len + buff[offset+1]) & 0xFF) != 0) {
pn532->log("Response length checksum did not match length!");
return PN532_STATUS_ERROR;
}
// Check frame checksum value matches bytes.
for (uint8_t i = 0; i < frame_len + 1; i++) {
checksum += buff[offset + 2 + i];
}
checksum &= 0xFF;
if (checksum != 0) {
pn532->log("Response checksum did not match expected checksum");
return PN532_STATUS_ERROR;
}
// Return frame data.
for (uint8_t i = 0; i < frame_len; i++) {
response[i] = buff[offset + 2 + i];
}
return frame_len;
}
/**
* @brief: Send specified command to the PN532 and expect up to response_length.
* Will wait up to timeout seconds for a response and read a bytearray into
* response buffer.
* @param pn532: PN532 handler
* @param command: command to send
* @param response: buffer returned
* @param response_length: expected response length
* @param params: can optionally specify an array of bytes to send as parameters
* to the function call, or NULL if there is no need to send parameters.
* @param params_length: length of the argument params
* @param timeout: timout of systick
* @retval: Returns the length of response or -1 if error.
*/
int PN532_CallFunction(
PN532* pn532,
uint8_t command,
uint8_t* response,
uint16_t response_length,
uint8_t* params,
uint16_t params_length,
uint32_t timeout
) {
// Build frame data with command and parameters.
uint8_t buff[PN532_FRAME_MAX_LENGTH];
buff[0] = PN532_HOSTTOPN532;
buff[1] = command & 0xFF;
for (uint8_t i = 0; i < params_length; i++) {
buff[2 + i] = params[i];
}
// Send frame and wait for response.
if (PN532_WriteFrame(pn532, buff, params_length + 2) != PN532_STATUS_OK) {
pn532->wakeup();
pn532->log("Trying to wakeup");
return PN532_STATUS_ERROR;
}
if (!pn532->wait_ready(timeout)) {
return PN532_STATUS_ERROR;
}
// Verify ACK response and wait to be ready for function response.
pn532->read_data(buff, sizeof(PN532_ACK));
for (uint8_t i = 0; i < sizeof(PN532_ACK); i++) {
if (PN532_ACK[i] != buff[i]) {
pn532->log("Did not receive expected ACK from PN532!");
return PN532_STATUS_ERROR;
}
}
if (!pn532->wait_ready(timeout)) {
return PN532_STATUS_ERROR;
}
// Read response bytes.
int frame_len = PN532_ReadFrame(pn532, buff, response_length + 2);
// Check that response is for the called function.
if (! ((buff[0] == PN532_PN532TOHOST) && (buff[1] == (command+1)))) {
pn532->log("Received unexpected command response!");
return PN532_STATUS_ERROR;
}
// Return response data.
for (uint8_t i = 0; i < response_length; i++) {
response[i] = buff[i + 2];
}
// The the number of bytes read
return frame_len - 2;
}
/**
* @brief: Call PN532 GetFirmwareVersion function and return a buff with the IC,
* Ver, Rev, and Support values.
*/
int PN532_GetFirmwareVersion(PN532* pn532, uint8_t* version) {
// length of version: 4
if (PN532_CallFunction(pn532, PN532_COMMAND_GETFIRMWAREVERSION,
version, 4, NULL, 0, 500) == PN532_STATUS_ERROR) {
pn532->log("Failed to detect the PN532");
return PN532_STATUS_ERROR;
}
return PN532_STATUS_OK;
}
/**
* @brief: Configure the PN532 to read MiFare cards.
*/
int PN532_SamConfiguration(PN532* pn532) {
// Send SAM configuration command with configuration for:
// - 0x01, normal mode
// - 0x14, timeout 50ms * 20 = 1 second
// - 0x01, use IRQ pin
// Note that no other verification is necessary as call_function will
// check the command was executed as expected.
uint8_t params[] = {0x01, 0x14, 0x01};
PN532_CallFunction(pn532, PN532_COMMAND_SAMCONFIGURATION,
NULL, 0, params, sizeof(params), PN532_DEFAULT_TIMEOUT);
return PN532_STATUS_OK;
}
/**
* @brief: Wait for a MiFare card to be available and return its UID when found.
* Will wait up to timeout seconds and return None if no card is found,
* otherwise a bytearray with the UID of the found card is returned.
* @retval: Length of UID, or -1 if error.
*/
int PN532_ReadPassiveTarget(
PN532* pn532,
uint8_t* response,
uint8_t card_baud,
uint32_t timeout
) {
// Send passive read command for 1 card. Expect at most a 7 byte UUID.
uint8_t params[] = {0x01, card_baud};
uint8_t buff[19];
int length = PN532_CallFunction(pn532, PN532_COMMAND_INLISTPASSIVETARGET,
buff, sizeof(buff), params, sizeof(params), timeout);
if (length < 0) {
return PN532_STATUS_ERROR; // No card found
}
// Check only 1 card with up to a 7 byte UID is present.
if (buff[0] != 0x01) {
pn532->log("More than one card detected!");
return PN532_STATUS_ERROR;
}
if (buff[5] > 7) {
pn532->log("Found card with unexpectedly long UID!");
return PN532_STATUS_ERROR;
}
for (uint8_t i = 0; i < buff[5]; i++) {
response[i] = buff[6 + i];
}
return buff[5];
}
/**
* @brief: Authenticate specified block number for a MiFare classic card.
* @param uid: A byte array with the UID of the card.
* @param uid_length: Length of the UID of the card.
* @param block_number: The block to authenticate.
* @param key_number: The key type (like MIFARE_CMD_AUTH_A or MIFARE_CMD_AUTH_B).
* @param key: A byte array with the key data.
* @retval: true if the block was authenticated, or false if not authenticated.
* @retval: PN532 error code.
*/
int PN532_MifareClassicAuthenticateBlock(
PN532* pn532,
uint8_t* uid,
uint8_t uid_length,
uint16_t block_number,
uint16_t key_number,
uint8_t* key
) {
// Build parameters for InDataExchange command to authenticate MiFare card.
uint8_t response[1] = {0xFF};
uint8_t params[3 + MIFARE_UID_MAX_LENGTH + MIFARE_KEY_LENGTH];
params[0] = 0x01;
params[1] = key_number & 0xFF;
params[2] = block_number & 0xFF;
// params[3:3+keylen] = key
for (uint8_t i = 0; i < MIFARE_KEY_LENGTH; i++) {
params[3 + i] = key[i];
}
// params[3+keylen:] = uid
for (uint8_t i = 0; i < uid_length; i++) {
params[3 + MIFARE_KEY_LENGTH + i] = uid[i];
}
// Send InDataExchange request
PN532_CallFunction(pn532, PN532_COMMAND_INDATAEXCHANGE, response, sizeof(response),
params, 3 + MIFARE_KEY_LENGTH + uid_length, PN532_DEFAULT_TIMEOUT);
return response[0];
}
/**
* @brief: Read a block of data from the card. Block number should be the block
* to read.
* @param response: buffer of length 16 returned if the block is successfully read.
* @param block_number: specify a block to read.
* @retval: PN532 error code.
*/
int PN532_MifareClassicReadBlock(PN532* pn532, uint8_t* response, uint16_t block_number) {
uint8_t params[] = {0x01, MIFARE_CMD_READ, block_number & 0xFF};
uint8_t buff[MIFARE_BLOCK_LENGTH + 1];
// Send InDataExchange request to read block of MiFare data.
PN532_CallFunction(pn532, PN532_COMMAND_INDATAEXCHANGE, buff, sizeof(buff),
params, sizeof(params), PN532_DEFAULT_TIMEOUT);
// Check first response is 0x00 to show success.
if (buff[0] != PN532_ERROR_NONE) {
return buff[0];
}
for (uint8_t i = 0; i < MIFARE_BLOCK_LENGTH; i++) {
response[i] = buff[i + 1];
}
return buff[0];
}
/**
* @brief: Write a block of data to the card. Block number should be the block
* to write and data should be a byte array of length 16 with the data to
* write.
* @param data: data to write.
* @param block_number: specify a block to write.
* @retval: PN532 error code.
*/
int PN532_MifareClassicWriteBlock(PN532* pn532, uint8_t* data, uint16_t block_number) {
uint8_t params[19];
uint8_t response[1];
params[0] = 0x01; // Max card numbers
params[1] = MIFARE_CMD_WRITE;
params[2] = block_number & 0xFF;
for (uint8_t i = 0; i < 16; i++) {
params[3 + i] = data[i];
}
PN532_CallFunction(pn532, PN532_COMMAND_INDATAEXCHANGE, response,
sizeof(response), params, sizeof(params), PN532_DEFAULT_TIMEOUT);
return response[0];
}
/**
* @brief: Read the GPIO states.
* @param pin_state: pin state buffer (3 bytes) returned.
* returns 3 bytes containing the pin state where:
* P3[0] = P30, P7[0] = 0, I[0] = I0,
* P3[1] = P31, P7[1] = P71, I[1] = I1,
* P3[2] = P32, P7[2] = P72, I[2] = 0,
* P3[3] = P33, P7[3] = 0, I[3] = 0,
* P3[4] = P34, P7[4] = 0, I[4] = 0,
* P3[5] = P35, P7[5] = 0, I[5] = 0,
* P3[6] = 0, P7[6] = 0, I[6] = 0,
* P3[7] = 0, P7[7] = 0, I[7] = 0,
* @retval: -1 if error
*/
int PN532_ReadGpio(PN532* pn532, uint8_t* pins_state) {
return PN532_CallFunction(pn532, PN532_COMMAND_READGPIO, pins_state, 3,
NULL, 0, PN532_DEFAULT_TIMEOUT);
}
/**
* @brief: Read the GPIO state of specified pins in (P30 ... P35).
* @param pin_number: specify the pin to read.
* @retval: true if HIGH, false if LOW
*/
bool PN532_ReadGpioP(PN532* pn532, uint8_t pin_number) {
uint8_t pins_state[3];
PN532_CallFunction(pn532, PN532_COMMAND_READGPIO, pins_state,
sizeof(pins_state), NULL, 0, PN532_DEFAULT_TIMEOUT);
if ((pin_number >= 30) && (pin_number <= 37)) {
return (pins_state[0] >> (pin_number - 30)) & 1 ? true : false;
}
if ((pin_number >= 70) && (pin_number <= 77)) {
return (pins_state[1] >> (pin_number - 70)) & 1 ? true : false;
}
return false;
}
/**
* @brief: Read the GPIO state of I0 or I1 pin.
* @param pin_number: specify the pin to read.
* @retval: true if HIGH, false if LOW
*/
bool PN532_ReadGpioI(PN532* pn532, uint8_t pin_number) {
uint8_t pins_state[3];
PN532_CallFunction(pn532, PN532_COMMAND_READGPIO, pins_state,
sizeof(pins_state), NULL, 0, PN532_DEFAULT_TIMEOUT);
if ((pin_number >= 0) && (pin_number <= 7)) {
return (pins_state[2] >> pin_number) & 1 ? true : false;
}
return false;
}
/**
* @brief: Write the GPIO states.
* @param pins_state: pin state buffer (2 bytes) to write.
* no need to read pin states before write with the param pin_state
* P3 = pin_state[0], P7 = pin_state[1]
* bits:
* P3[0] = P30, P7[0] = 0,
* P3[1] = P31, P7[1] = P71,
* P3[2] = P32, P7[2] = P72,
* P3[3] = P33, P7[3] = nu,
* P3[4] = P34, P7[4] = nu,
* P3[5] = P35, P7[5] = nu,
* P3[6] = nu, P7[6] = nu,
* P3[7] = Val, P7[7] = Val,
* For each port that is validated (bit Val = 1), all the bits are applied
* simultaneously. It is not possible for example to modify the state of
* the port P32 without applying a value to the ports P30, P31, P33, P34
* and P35.
* @retval: -1 if error
*/
int PN532_WriteGpio(PN532* pn532, uint8_t* pins_state) {
uint8_t params[2];
// 0x80, the validation bit.
params[0] = 0x80 | pins_state[0];
params[1] = 0x80 | pins_state[1];
return PN532_CallFunction(pn532, PN532_COMMAND_WRITEGPIO, NULL, 0,
params, sizeof(params), PN532_DEFAULT_TIMEOUT);
}
/**
* @brief: Write the specified pin with given states.
* @param pin_number: specify the pin to write.
* @param pin_state: specify the pin state. true for HIGH, false for LOW.
* @retval: -1 if error
*/
int PN532_WriteGpioP(PN532* pn532, uint8_t pin_number, bool pin_state) {
uint8_t pins_state[2];
uint8_t params[2];
if (PN532_ReadGpio(pn532, pins_state) == PN532_STATUS_ERROR) {
return PN532_STATUS_ERROR;
}
if ((pin_number >= 30) && (pin_number <= 37)) {
if (pin_state) {
params[0] = 0x80 | pins_state[0] | 1 << (pin_number - 30);
} else {
params[0] = (0x80 | pins_state[0]) & ~(1 << (pin_number - 30));
}
params[1] = 0x00; // leave p7 unchanged
}
if ((pin_number >= 70) && (pin_number <= 77)) {
if (pin_state) {
params[1] = 0x80 | pins_state[1] | 1 << (pin_number - 70);
} else {
params[1] = (0x80 | pins_state[1]) & ~(1 << (pin_number - 70));
}
params[0] = 0x00; // leave p3 unchanged
}
return PN532_CallFunction(pn532, PN532_COMMAND_WRITEGPIO, NULL, 0,
params, sizeof(params), PN532_DEFAULT_TIMEOUT);
}
|
817695.c | /** @file
Flash descriptor library.
Copyright (c) 2017-2018, Intel Corporation. All rights reserved.<BR>
SPDX-License-Identifier: BSD-2-Clause-Patent
**/
#include <Uefi/UefiBaseType.h>
#include <IndustryStandard/Pci30.h>
#include <Library/IoLib.h>
#include <Library/DebugLib.h>
#include <Library/BaseMemoryLib.h>
#include <RegAccess.h>
/**
Return SPI linear Base address of descriptor region section
@param[in] RegNum FLREG number of region section defined in the descriptor
@retval UINT32 Base address of the FLREG
**/
UINT32
GetSpiFlashRegionBase (
IN UINTN RegNum
)
{
UINTN SpiPciBase;
UINT32 SpiBar0;
UINT32 FlashRegBase;
SpiPciBase = GetDeviceAddr (OsBootDeviceSpi, 0);
SpiPciBase = TO_MM_PCI_ADDRESS (SpiPciBase);
SpiBar0 = MmioRead32 (SpiPciBase + R_SPI_BASE) & B_SPI_BASE_BAR;
DEBUG((EFI_D_INFO, "SpiBar0 = 0x%x\n", SpiBar0));
FlashRegBase = MmioRead32 (SpiBar0 + R_SPI_FREG0_FLASHD + RegNum * 4) & B_SPI_FREG0_BASE_MASK;
DEBUG((EFI_D_INFO, "FlashRegBase = 0x%x\n", FlashRegBase));
if (FlashRegBase == V_SPI_FLREG_DISABLED) {
FlashRegBase = 0;
DEBUG((EFI_D_ERROR, "SPI FLREG%d is disabled!!!\n", RegNum));
}
FlashRegBase <<= N_SPI_FREG0_BASE;
DEBUG((EFI_D_INFO, "SPI FLREG%d base = 0x%x\n", RegNum, FlashRegBase));
return FlashRegBase;
}
/**
Return SPI linear region limit of BIOS region
@retval UINTN Region Limit address of the BIOS region
**/
UINT32
GetSpiFlashRegionLimit (
IN UINTN RegNum
)
{
UINTN SpiPciBase;
UINT32 SpiBar0;
UINT32 FlashRegLimit;
SpiPciBase = GetDeviceAddr (OsBootDeviceSpi, 0);
SpiPciBase = TO_MM_PCI_ADDRESS (SpiPciBase);
SpiBar0 = MmioRead32 (SpiPciBase + R_SPI_BASE) & B_SPI_BASE_BAR;
FlashRegLimit = MmioRead32 (SpiBar0 + R_SPI_FREG0_FLASHD + RegNum * 4) & B_SPI_FREG0_LIMIT_MASK;
FlashRegLimit >>= N_SPI_FREG1_LIMIT;
FlashRegLimit |= 0xFFF;
DEBUG ((EFI_D_INFO, "SPI FLREG%d limit = 0x%x\n", RegNum, FlashRegLimit));
return FlashRegLimit;
}
|
102649.c | /**
* \file
* Routines for publishing metadata updates
*
* Copyright 2020 Microsoft
*
* Licensed under the MIT license. See LICENSE file in the project root for full license information.
*/
#include <config.h>
#include "mono/utils/mono-compiler.h"
#include "mono/metadata/metadata-update.h"
#include "mono/metadata/components.h"
#include "mono/metadata/class-internals.h"
#include "mono/component/hot_reload.h"
gboolean
mono_metadata_update_available (void)
{
return mono_component_hot_reload ()->component.available ();
}
MonoMetadataUpdateData mono_metadata_update_data_private;
void
mono_metadata_update_init (void)
{
memset (&mono_metadata_update_data_private, 0, sizeof (mono_metadata_update_data_private));
MonoComponentHotReload *comp = mono_component_hot_reload ();
comp->set_fastpath_data (&mono_metadata_update_data_private);
}
gboolean
mono_metadata_update_enabled (int *modifiable_assemblies_out)
{
return mono_component_hot_reload ()->update_enabled (modifiable_assemblies_out);
}
gboolean
mono_metadata_update_no_inline (MonoMethod *caller, MonoMethod *callee)
{
return mono_component_hot_reload ()->no_inline (caller, callee);
}
uint32_t
mono_metadata_update_thread_expose_published (void)
{
return mono_component_hot_reload ()->thread_expose_published ();
}
uint32_t
mono_metadata_update_get_thread_generation (void)
{
return mono_component_hot_reload ()->get_thread_generation ();
}
void
mono_metadata_update_cleanup_on_close (MonoImage *base_image)
{
mono_component_hot_reload ()->cleanup_on_close (base_image);
}
void
mono_image_effective_table_slow (const MonoTableInfo **t, int idx)
{
mono_component_hot_reload ()->effective_table_slow (t, idx);
}
void
mono_image_load_enc_delta (int origin, MonoImage *base_image, gconstpointer dmeta, uint32_t dmeta_len, gconstpointer dil, uint32_t dil_len, gconstpointer dpdb, uint32_t dpdb_len, MonoError *error)
{
mono_component_hot_reload ()->apply_changes (origin, base_image, dmeta, dmeta_len, dil, dil_len, dpdb, dpdb_len, error);
if (is_ok (error)) {
mono_component_debugger ()->send_enc_delta (base_image, dmeta, dmeta_len, dpdb, dpdb_len);
}
}
static void
mono_image_close_except_pools_all_list (GList *images)
{
for (GList *ptr = images; ptr; ptr = ptr->next) {
MonoImage *image = (MonoImage *)ptr->data;
if (image) {
if (!mono_image_close_except_pools (image))
ptr->data = NULL;
}
}
}
void
mono_metadata_update_image_close_except_pools_all (MonoImage *base_image)
{
mono_component_hot_reload ()->image_close_except_pools_all (base_image);
}
void
mono_metadata_update_image_close_all (MonoImage *base_image)
{
mono_component_hot_reload ()->image_close_all (base_image);
}
gpointer
mono_metadata_update_get_updated_method_rva (MonoImage *base_image, uint32_t idx)
{
return mono_component_hot_reload ()->get_updated_method_rva (base_image, idx);
}
gpointer
mono_metadata_update_get_updated_method_ppdb (MonoImage *base_image, uint32_t idx)
{
return mono_component_hot_reload ()->get_updated_method_ppdb (base_image, idx);
}
gboolean
mono_metadata_update_table_bounds_check (MonoImage *base_image, int table_index, int token_index)
{
return mono_component_hot_reload ()->table_bounds_check (base_image, table_index, token_index);
}
gboolean
mono_metadata_update_delta_heap_lookup (MonoImage *base_image, MetadataHeapGetterFunc get_heap, uint32_t orig_index, MonoImage **image_out, uint32_t *index_out)
{
return mono_component_hot_reload ()->delta_heap_lookup (base_image, get_heap, orig_index, image_out, index_out);
}
gboolean
mono_metadata_update_has_modified_rows (const MonoTableInfo *table)
{
return mono_component_hot_reload ()->has_modified_rows (table);
}
gboolean
mono_metadata_has_updates_api (void)
{
return mono_metadata_has_updates ();
}
/**
* mono_metadata_table_num_rows:
*
* Returns the number of rows from the specified table that the current thread can see.
* If there's a EnC metadata update, this number may change.
*/
int
mono_metadata_table_num_rows_slow (MonoImage *base_image, int table_index)
{
return mono_component_hot_reload()->table_num_rows_slow (base_image, table_index);
}
void*
mono_metadata_update_metadata_linear_search (MonoImage *base_image, MonoTableInfo *base_table, const void *key, BinarySearchComparer comparer)
{
return mono_component_hot_reload()->metadata_linear_search (base_image, base_table, key, comparer);
}
/*
* Returns the (1-based) table row index of the fielddef of the given field
* (which must have m_field_is_from_update set).
*/
uint32_t
mono_metadata_update_get_field_idx (MonoClassField *field)
{
return mono_component_hot_reload()->get_field_idx (field);
}
MonoClassField *
mono_metadata_update_get_field (MonoClass *klass, uint32_t fielddef_token)
{
return mono_component_hot_reload()->get_field (klass, fielddef_token);
}
gpointer
mono_metadata_update_get_static_field_addr (MonoClassField *field)
{
return mono_component_hot_reload()->get_static_field_addr (field);
}
MonoMethod *
mono_metadata_update_find_method_by_name (MonoClass *klass, const char *name, int param_count, int flags, MonoError *error)
{
return mono_component_hot_reload()->find_method_by_name (klass, name, param_count, flags, error);
}
gboolean
mono_metadata_update_get_typedef_skeleton (MonoImage *base_image, uint32_t typedef_token, uint32_t *first_method_idx, uint32_t *method_count, uint32_t *first_field_idx, uint32_t *field_count)
{
return mono_component_hot_reload()->get_typedef_skeleton (base_image, typedef_token, first_method_idx, method_count, first_field_idx, field_count);
}
gboolean
metadata_update_get_typedef_skeleton_properties (MonoImage *base_image, uint32_t typedef_token, uint32_t *first_prop_idx, uint32_t *prop_count)
{
return mono_component_hot_reload()->get_typedef_skeleton_properties (base_image, typedef_token, first_prop_idx, prop_count);
}
gboolean
metadata_update_get_typedef_skeleton_events (MonoImage *base_image, uint32_t typedef_token, uint32_t *first_event_idx, uint32_t *event_count)
{
return mono_component_hot_reload()->get_typedef_skeleton_events (base_image, typedef_token, first_event_idx, event_count);
}
MonoMethod *
mono_metadata_update_added_methods_iter (MonoClass *klass, gpointer *iter)
{
return mono_component_hot_reload()->added_methods_iter (klass, iter);
}
MonoClassField *
mono_metadata_update_added_fields_iter (MonoClass *klass, gboolean lazy, gpointer *iter)
{
return mono_component_hot_reload()->added_fields_iter (klass, lazy, iter);
}
uint32_t
mono_metadata_update_get_num_fields_added (MonoClass *klass)
{
return mono_component_hot_reload()->get_num_fields_added (klass);
} |
384593.c | #include<libtransistor/err.h>
#include<libtransistor/types.h>
#include<libtransistor/display/parcel.h>
#include<libtransistor/display/binder.h>
#include<string.h>
void parcel_initialize(parcel_t *parcel) {
parcel->read_head = 0;
parcel->write_head = 0;
parcel->writing_finalized = false;
}
result_t parcel_load(parcel_t *parcel, uint8_t *flattened) {
memcpy(&(parcel->contents), flattened, 0x10);
if(parcel->contents.data_size > sizeof(parcel->contents.payload)) {
return LIBTRANSISTOR_ERR_PARCEL_DATA_TOO_BIG;
}
memcpy(parcel->contents.payload, flattened + parcel->contents.data_offset, parcel->contents.data_size);
parcel->write_head = parcel->contents.data_size;
parcel->read_head = 0;
parcel->writing_finalized = true;
return RESULT_OK;
}
uint8_t *parcel_finalize_writing(parcel_t *parcel, size_t *length) {
parcel->writing_finalized = true;
parcel->contents.data_size = parcel->write_head;
parcel->contents.data_offset = 0x10;
parcel->contents.objects_size = 0;
parcel->contents.objects_offset = 0x10 + parcel->write_head;
*length = 0x10 + parcel->write_head;
return (uint8_t*) &(parcel->contents);
}
size_t parcel_read_remaining(parcel_t *parcel) {
return parcel->write_head - parcel->read_head;
}
void *parcel_read_inplace(parcel_t *parcel, size_t length) {
void *ptr = parcel->contents.payload + parcel->read_head;
parcel->read_head+= length;
return ptr;
}
result_t parcel_read_binder(parcel_t *parcel, binder_t *binder) {
flat_binder_object_t *fbo = parcel_read_inplace(parcel, sizeof(flat_binder_object_t));
// we really should check type/length, but I'm not sure how at the moment
binder->handle = fbo->handle;
// adjust refcount
result_t r;
if((r = binder_adjust_refcount(binder, 1, 0)) != RESULT_OK) { return r; }
if((r = binder_adjust_refcount(binder, 1, 1)) != RESULT_OK) { return r; }
return RESULT_OK;
}
uint32_t parcel_read_u32(parcel_t *parcel) {
return *(uint32_t*) parcel_read_inplace(parcel, sizeof(uint32_t));
}
const char *parcel_read_string(parcel_t *parcel) {
int32_t length = (int32_t) parcel_read_u32(parcel);
if(length == -1) { return NULL; }
size_t size = (length+1) * 2;
// condense the string in place
uint16_t *str16 = parcel_read_inplace(parcel, size);
uint8_t *str8 = (uint8_t*) str16;
for(int i = 0; i <= length; i++) {
str8[i] = str16[i];
}
return (const char*) str8;
}
size_t parcel_write_remaining(parcel_t *parcel) {
return sizeof(parcel->contents.payload) - parcel->write_head;
}
void *parcel_write_inplace(parcel_t *parcel, size_t length) {
void *ptr = parcel->contents.payload + parcel->write_head;
parcel->write_head+= (length + 3) & ~3;
return ptr;
}
void parcel_write_u32(parcel_t *parcel, uint32_t value) {
*(uint32_t*) parcel_write_inplace(parcel, sizeof(value)) = value;
}
void parcel_write_string16(parcel_t *parcel, const char *string) {
int32_t length = strlen(string);
parcel_write_u32(parcel, length);
uint16_t *str16 = parcel_write_inplace(parcel, (length+1) * 2);
for(int i = 0; i <= length; i++) {
str16[i] = string[i];
}
}
void parcel_write_interface_token(parcel_t *parcel, const char *token) {
parcel_write_u32(parcel, 0x100);
parcel_write_string16(parcel, token);
}
|
664888.c | /*
* FreeRTOS Kernel V10.4.3
* Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* https://www.FreeRTOS.org
* https://github.com/FreeRTOS
*
*/
/*-----------------------------------------------------------
* Implementation of functions defined in portable.h for the ARM CM3 port.
*----------------------------------------------------------*/
/* IAR includes. */
#include <intrinsics.h>
/* Scheduler includes. */
#include "FreeRTOS.h"
#include "task.h"
#if ( configMAX_SYSCALL_INTERRUPT_PRIORITY == 0 )
#error configMAX_SYSCALL_INTERRUPT_PRIORITY must not be set to 0. See http: /*www.FreeRTOS.org/RTOS-Cortex-M3-M4.html */
#endif
#ifndef configSYSTICK_CLOCK_HZ
#define configSYSTICK_CLOCK_HZ configCPU_CLOCK_HZ
/* Ensure the SysTick is clocked at the same frequency as the core. */
#define portNVIC_SYSTICK_CLK_BIT ( 1UL << 2UL )
#else
/* The way the SysTick is clocked is not modified in case it is not the same
* as the core. */
#define portNVIC_SYSTICK_CLK_BIT ( 0 )
#endif
/* Constants required to manipulate the core. Registers first... */
#define portNVIC_SYSTICK_CTRL_REG ( *( ( volatile uint32_t * ) 0xe000e010 ) )
#define portNVIC_SYSTICK_LOAD_REG ( *( ( volatile uint32_t * ) 0xe000e014 ) )
#define portNVIC_SYSTICK_CURRENT_VALUE_REG ( *( ( volatile uint32_t * ) 0xe000e018 ) )
#define portNVIC_SHPR3_REG ( *( ( volatile uint32_t * ) 0xe000ed20 ) )
/* ...then bits in the registers. */
#define portNVIC_SYSTICK_INT_BIT ( 1UL << 1UL )
#define portNVIC_SYSTICK_ENABLE_BIT ( 1UL << 0UL )
#define portNVIC_SYSTICK_COUNT_FLAG_BIT ( 1UL << 16UL )
#define portNVIC_PENDSVCLEAR_BIT ( 1UL << 27UL )
#define portNVIC_PEND_SYSTICK_CLEAR_BIT ( 1UL << 25UL )
#define portNVIC_PENDSV_PRI ( ( ( uint32_t ) configKERNEL_INTERRUPT_PRIORITY ) << 16UL )
#define portNVIC_SYSTICK_PRI ( ( ( uint32_t ) configKERNEL_INTERRUPT_PRIORITY ) << 24UL )
/* Constants required to check the validity of an interrupt priority. */
#define portFIRST_USER_INTERRUPT_NUMBER ( 16 )
#define portNVIC_IP_REGISTERS_OFFSET_16 ( 0xE000E3F0 )
#define portAIRCR_REG ( *( ( volatile uint32_t * ) 0xE000ED0C ) )
#define portMAX_8_BIT_VALUE ( ( uint8_t ) 0xff )
#define portTOP_BIT_OF_BYTE ( ( uint8_t ) 0x80 )
#define portMAX_PRIGROUP_BITS ( ( uint8_t ) 7 )
#define portPRIORITY_GROUP_MASK ( 0x07UL << 8UL )
#define portPRIGROUP_SHIFT ( 8UL )
/* Masks off all bits but the VECTACTIVE bits in the ICSR register. */
#define portVECTACTIVE_MASK ( 0xFFUL )
/* Constants required to set up the initial stack. */
#define portINITIAL_XPSR ( 0x01000000 )
/* The systick is a 24-bit counter. */
#define portMAX_24_BIT_NUMBER ( 0xffffffUL )
/* A fiddle factor to estimate the number of SysTick counts that would have
* occurred while the SysTick counter is stopped during tickless idle
* calculations. */
#define portMISSED_COUNTS_FACTOR ( 45UL )
/* For strict compliance with the Cortex-M spec the task start address should
* have bit-0 clear, as it is loaded into the PC on exit from an ISR. */
#define portSTART_ADDRESS_MASK ( ( StackType_t ) 0xfffffffeUL )
/* For backward compatibility, ensure configKERNEL_INTERRUPT_PRIORITY is
* defined. The value 255 should also ensure backward compatibility.
* FreeRTOS.org versions prior to V4.3.0 did not include this definition. */
#ifndef configKERNEL_INTERRUPT_PRIORITY
#define configKERNEL_INTERRUPT_PRIORITY 255
#endif
/*
* Setup the timer to generate the tick interrupts. The implementation in this
* file is weak to allow application writers to change the timer used to
* generate the tick interrupt.
*/
void vPortSetupTimerInterrupt( void );
/*
* Exception handlers.
*/
void xPortSysTickHandler( void );
/*
* Start first task is a separate function so it can be tested in isolation.
*/
extern void vPortStartFirstTask( void );
/*
* Used to catch tasks that attempt to return from their implementing function.
*/
static void prvTaskExitError( void );
/*-----------------------------------------------------------*/
/* Each task maintains its own interrupt status in the critical nesting
* variable. */
static UBaseType_t uxCriticalNesting = 0xaaaaaaaa;
/*
* The number of SysTick increments that make up one tick period.
*/
#if ( configUSE_TICKLESS_IDLE == 1 )
static uint32_t ulTimerCountsForOneTick = 0;
#endif /* configUSE_TICKLESS_IDLE */
/*
* The maximum number of tick periods that can be suppressed is limited by the
* 24 bit resolution of the SysTick timer.
*/
#if ( configUSE_TICKLESS_IDLE == 1 )
static uint32_t xMaximumPossibleSuppressedTicks = 0;
#endif /* configUSE_TICKLESS_IDLE */
/*
* Compensate for the CPU cycles that pass while the SysTick is stopped (low
* power functionality only.
*/
#if ( configUSE_TICKLESS_IDLE == 1 )
static uint32_t ulStoppedTimerCompensation = 0;
#endif /* configUSE_TICKLESS_IDLE */
/*
* Used by the portASSERT_IF_INTERRUPT_PRIORITY_INVALID() macro to ensure
* FreeRTOS API functions are not called from interrupts that have been assigned
* a priority above configMAX_SYSCALL_INTERRUPT_PRIORITY.
*/
#if ( configASSERT_DEFINED == 1 )
static uint8_t ucMaxSysCallPriority = 0;
static uint32_t ulMaxPRIGROUPValue = 0;
static const volatile uint8_t * const pcInterruptPriorityRegisters = ( const volatile uint8_t * const ) portNVIC_IP_REGISTERS_OFFSET_16;
#endif /* configASSERT_DEFINED */
/*-----------------------------------------------------------*/
/*
* See header file for description.
*/
StackType_t * pxPortInitialiseStack( StackType_t * pxTopOfStack,
TaskFunction_t pxCode,
void * pvParameters )
{
/* Simulate the stack frame as it would be created by a context switch
* interrupt. */
pxTopOfStack--; /* Offset added to account for the way the MCU uses the stack on entry/exit of interrupts. */
*pxTopOfStack = portINITIAL_XPSR; /* xPSR */
pxTopOfStack--;
*pxTopOfStack = ( ( StackType_t ) pxCode ) & portSTART_ADDRESS_MASK; /* PC */
pxTopOfStack--;
*pxTopOfStack = ( StackType_t ) prvTaskExitError; /* LR */
pxTopOfStack -= 5; /* R12, R3, R2 and R1. */
*pxTopOfStack = ( StackType_t ) pvParameters; /* R0 */
pxTopOfStack -= 8; /* R11, R10, R9, R8, R7, R6, R5 and R4. */
return pxTopOfStack;
}
/*-----------------------------------------------------------*/
static void prvTaskExitError( void )
{
/* A function that implements a task must not exit or attempt to return to
* its caller as there is nothing to return to. If a task wants to exit it
* should instead call vTaskDelete( NULL ).
*
* Artificially force an assert() to be triggered if configASSERT() is
* defined, then stop here so application writers can catch the error. */
configASSERT( uxCriticalNesting == ~0UL );
portDISABLE_INTERRUPTS();
for( ; ; )
{
}
}
/*-----------------------------------------------------------*/
/*
* See header file for description.
*/
BaseType_t xPortStartScheduler( void )
{
/* configMAX_SYSCALL_INTERRUPT_PRIORITY must not be set to 0.
* See https://www.FreeRTOS.org/RTOS-Cortex-M3-M4.html */
configASSERT( configMAX_SYSCALL_INTERRUPT_PRIORITY );
#if ( configASSERT_DEFINED == 1 )
{
volatile uint32_t ulOriginalPriority;
volatile uint8_t * const pucFirstUserPriorityRegister = ( volatile uint8_t * const ) ( portNVIC_IP_REGISTERS_OFFSET_16 + portFIRST_USER_INTERRUPT_NUMBER );
volatile uint8_t ucMaxPriorityValue;
/* Determine the maximum priority from which ISR safe FreeRTOS API
* functions can be called. ISR safe functions are those that end in
* "FromISR". FreeRTOS maintains separate thread and ISR API functions to
* ensure interrupt entry is as fast and simple as possible.
*
* Save the interrupt priority value that is about to be clobbered. */
ulOriginalPriority = *pucFirstUserPriorityRegister;
/* Determine the number of priority bits available. First write to all
* possible bits. */
*pucFirstUserPriorityRegister = portMAX_8_BIT_VALUE;
/* Read the value back to see how many bits stuck. */
ucMaxPriorityValue = *pucFirstUserPriorityRegister;
/* Use the same mask on the maximum system call priority. */
ucMaxSysCallPriority = configMAX_SYSCALL_INTERRUPT_PRIORITY & ucMaxPriorityValue;
/* Calculate the maximum acceptable priority group value for the number
* of bits read back. */
ulMaxPRIGROUPValue = portMAX_PRIGROUP_BITS;
while( ( ucMaxPriorityValue & portTOP_BIT_OF_BYTE ) == portTOP_BIT_OF_BYTE )
{
ulMaxPRIGROUPValue--;
ucMaxPriorityValue <<= ( uint8_t ) 0x01;
}
#ifdef __NVIC_PRIO_BITS
{
/* Check the CMSIS configuration that defines the number of
* priority bits matches the number of priority bits actually queried
* from the hardware. */
configASSERT( ( portMAX_PRIGROUP_BITS - ulMaxPRIGROUPValue ) == __NVIC_PRIO_BITS );
}
#endif
#ifdef configPRIO_BITS
{
/* Check the FreeRTOS configuration that defines the number of
* priority bits matches the number of priority bits actually queried
* from the hardware. */
configASSERT( ( portMAX_PRIGROUP_BITS - ulMaxPRIGROUPValue ) == configPRIO_BITS );
}
#endif
/* Shift the priority group value back to its position within the AIRCR
* register. */
ulMaxPRIGROUPValue <<= portPRIGROUP_SHIFT;
ulMaxPRIGROUPValue &= portPRIORITY_GROUP_MASK;
/* Restore the clobbered interrupt priority register to its original
* value. */
*pucFirstUserPriorityRegister = ulOriginalPriority;
}
#endif /* conifgASSERT_DEFINED */
/* Make PendSV and SysTick the lowest priority interrupts. */
portNVIC_SHPR3_REG |= portNVIC_PENDSV_PRI;
portNVIC_SHPR3_REG |= portNVIC_SYSTICK_PRI;
/* Start the timer that generates the tick ISR. Interrupts are disabled
* here already. */
vPortSetupTimerInterrupt();
/* Initialise the critical nesting count ready for the first task. */
uxCriticalNesting = 0;
/* Start the first task. */
vPortStartFirstTask();
/* Should not get here! */
return 0;
}
/*-----------------------------------------------------------*/
void vPortEndScheduler( void )
{
/* Not implemented in ports where there is nothing to return to.
* Artificially force an assert. */
configASSERT( uxCriticalNesting == 1000UL );
}
/*-----------------------------------------------------------*/
void vPortEnterCritical( void )
{
portDISABLE_INTERRUPTS();
uxCriticalNesting++;
/* This is not the interrupt safe version of the enter critical function so
* assert() if it is being called from an interrupt context. Only API
* functions that end in "FromISR" can be used in an interrupt. Only assert if
* the critical nesting count is 1 to protect against recursive calls if the
* assert function also uses a critical section. */
if( uxCriticalNesting == 1 )
{
configASSERT( ( portNVIC_INT_CTRL_REG & portVECTACTIVE_MASK ) == 0 );
}
}
/*-----------------------------------------------------------*/
void vPortExitCritical( void )
{
configASSERT( uxCriticalNesting );
uxCriticalNesting--;
if( uxCriticalNesting == 0 )
{
portENABLE_INTERRUPTS();
}
}
/*-----------------------------------------------------------*/
void xPortSysTickHandler( void )
{
/* The SysTick runs at the lowest interrupt priority, so when this interrupt
* executes all interrupts must be unmasked. There is therefore no need to
* save and then restore the interrupt mask value as its value is already
* known. */
portDISABLE_INTERRUPTS();
{
/* Increment the RTOS tick. */
if( xTaskIncrementTick() != pdFALSE )
{
/* A context switch is required. Context switching is performed in
* the PendSV interrupt. Pend the PendSV interrupt. */
portNVIC_INT_CTRL_REG = portNVIC_PENDSVSET_BIT;
}
}
portENABLE_INTERRUPTS();
}
/*-----------------------------------------------------------*/
#if ( configUSE_TICKLESS_IDLE == 1 )
__weak void vPortSuppressTicksAndSleep( TickType_t xExpectedIdleTime )
{
uint32_t ulReloadValue, ulCompleteTickPeriods, ulCompletedSysTickDecrements;
TickType_t xModifiableIdleTime;
/* Make sure the SysTick reload value does not overflow the counter. */
if( xExpectedIdleTime > xMaximumPossibleSuppressedTicks )
{
xExpectedIdleTime = xMaximumPossibleSuppressedTicks;
}
/* Stop the SysTick momentarily. The time the SysTick is stopped for
* is accounted for as best it can be, but using the tickless mode will
* inevitably result in some tiny drift of the time maintained by the
* kernel with respect to calendar time. */
portNVIC_SYSTICK_CTRL_REG &= ~portNVIC_SYSTICK_ENABLE_BIT;
/* Calculate the reload value required to wait xExpectedIdleTime
* tick periods. -1 is used because this code will execute part way
* through one of the tick periods. */
ulReloadValue = portNVIC_SYSTICK_CURRENT_VALUE_REG + ( ulTimerCountsForOneTick * ( xExpectedIdleTime - 1UL ) );
if( ulReloadValue > ulStoppedTimerCompensation )
{
ulReloadValue -= ulStoppedTimerCompensation;
}
/* Enter a critical section but don't use the taskENTER_CRITICAL()
* method as that will mask interrupts that should exit sleep mode. */
__disable_interrupt();
__DSB();
__ISB();
/* If a context switch is pending or a task is waiting for the scheduler
* to be unsuspended then abandon the low power entry. */
if( eTaskConfirmSleepModeStatus() == eAbortSleep )
{
/* Restart from whatever is left in the count register to complete
* this tick period. */
portNVIC_SYSTICK_LOAD_REG = portNVIC_SYSTICK_CURRENT_VALUE_REG;
/* Restart SysTick. */
portNVIC_SYSTICK_CTRL_REG |= portNVIC_SYSTICK_ENABLE_BIT;
/* Reset the reload register to the value required for normal tick
* periods. */
portNVIC_SYSTICK_LOAD_REG = ulTimerCountsForOneTick - 1UL;
/* Re-enable interrupts - see comments above __disable_interrupt()
* call above. */
__enable_interrupt();
}
else
{
/* Set the new reload value. */
portNVIC_SYSTICK_LOAD_REG = ulReloadValue;
/* Clear the SysTick count flag and set the count value back to
* zero. */
portNVIC_SYSTICK_CURRENT_VALUE_REG = 0UL;
/* Restart SysTick. */
portNVIC_SYSTICK_CTRL_REG |= portNVIC_SYSTICK_ENABLE_BIT;
/* Sleep until something happens. configPRE_SLEEP_PROCESSING() can
* set its parameter to 0 to indicate that its implementation contains
* its own wait for interrupt or wait for event instruction, and so wfi
* should not be executed again. However, the original expected idle
* time variable must remain unmodified, so a copy is taken. */
xModifiableIdleTime = xExpectedIdleTime;
configPRE_SLEEP_PROCESSING( xModifiableIdleTime );
if( xModifiableIdleTime > 0 )
{
__DSB();
__WFI();
__ISB();
}
configPOST_SLEEP_PROCESSING( xExpectedIdleTime );
/* Re-enable interrupts to allow the interrupt that brought the MCU
* out of sleep mode to execute immediately. see comments above
* __disable_interrupt() call above. */
__enable_interrupt();
__DSB();
__ISB();
/* Disable interrupts again because the clock is about to be stopped
* and interrupts that execute while the clock is stopped will increase
* any slippage between the time maintained by the RTOS and calendar
* time. */
__disable_interrupt();
__DSB();
__ISB();
/* Disable the SysTick clock without reading the
* portNVIC_SYSTICK_CTRL_REG register to ensure the
* portNVIC_SYSTICK_COUNT_FLAG_BIT is not cleared if it is set. Again,
* the time the SysTick is stopped for is accounted for as best it can
* be, but using the tickless mode will inevitably result in some tiny
* drift of the time maintained by the kernel with respect to calendar
* time*/
portNVIC_SYSTICK_CTRL_REG = ( portNVIC_SYSTICK_CLK_BIT | portNVIC_SYSTICK_INT_BIT );
/* Determine if the SysTick clock has already counted to zero and
* been set back to the current reload value (the reload back being
* correct for the entire expected idle time) or if the SysTick is yet
* to count to zero (in which case an interrupt other than the SysTick
* must have brought the system out of sleep mode). */
if( ( portNVIC_SYSTICK_CTRL_REG & portNVIC_SYSTICK_COUNT_FLAG_BIT ) != 0 )
{
uint32_t ulCalculatedLoadValue;
/* The tick interrupt is already pending, and the SysTick count
* reloaded with ulReloadValue. Reset the
* portNVIC_SYSTICK_LOAD_REG with whatever remains of this tick
* period. */
ulCalculatedLoadValue = ( ulTimerCountsForOneTick - 1UL ) - ( ulReloadValue - portNVIC_SYSTICK_CURRENT_VALUE_REG );
/* Don't allow a tiny value, or values that have somehow
* underflowed because the post sleep hook did something
* that took too long. */
if( ( ulCalculatedLoadValue < ulStoppedTimerCompensation ) || ( ulCalculatedLoadValue > ulTimerCountsForOneTick ) )
{
ulCalculatedLoadValue = ( ulTimerCountsForOneTick - 1UL );
}
portNVIC_SYSTICK_LOAD_REG = ulCalculatedLoadValue;
/* As the pending tick will be processed as soon as this
* function exits, the tick value maintained by the tick is stepped
* forward by one less than the time spent waiting. */
ulCompleteTickPeriods = xExpectedIdleTime - 1UL;
}
else
{
/* Something other than the tick interrupt ended the sleep.
* Work out how long the sleep lasted rounded to complete tick
* periods (not the ulReload value which accounted for part
* ticks). */
ulCompletedSysTickDecrements = ( xExpectedIdleTime * ulTimerCountsForOneTick ) - portNVIC_SYSTICK_CURRENT_VALUE_REG;
/* How many complete tick periods passed while the processor
* was waiting? */
ulCompleteTickPeriods = ulCompletedSysTickDecrements / ulTimerCountsForOneTick;
/* The reload value is set to whatever fraction of a single tick
* period remains. */
portNVIC_SYSTICK_LOAD_REG = ( ( ulCompleteTickPeriods + 1UL ) * ulTimerCountsForOneTick ) - ulCompletedSysTickDecrements;
}
/* Restart SysTick so it runs from portNVIC_SYSTICK_LOAD_REG
* again, then set portNVIC_SYSTICK_LOAD_REG back to its standard
* value. */
portNVIC_SYSTICK_CURRENT_VALUE_REG = 0UL;
portNVIC_SYSTICK_CTRL_REG |= portNVIC_SYSTICK_ENABLE_BIT;
vTaskStepTick( ulCompleteTickPeriods );
portNVIC_SYSTICK_LOAD_REG = ulTimerCountsForOneTick - 1UL;
/* Exit with interrupts enabled. */
__enable_interrupt();
}
}
#endif /* configUSE_TICKLESS_IDLE */
/*-----------------------------------------------------------*/
/*
* Setup the systick timer to generate the tick interrupts at the required
* frequency.
*/
__weak void vPortSetupTimerInterrupt( void )
{
/* Calculate the constants required to configure the tick interrupt. */
#if ( configUSE_TICKLESS_IDLE == 1 )
{
ulTimerCountsForOneTick = ( configSYSTICK_CLOCK_HZ / configTICK_RATE_HZ );
xMaximumPossibleSuppressedTicks = portMAX_24_BIT_NUMBER / ulTimerCountsForOneTick;
ulStoppedTimerCompensation = portMISSED_COUNTS_FACTOR / ( configCPU_CLOCK_HZ / configSYSTICK_CLOCK_HZ );
}
#endif /* configUSE_TICKLESS_IDLE */
/* Stop and clear the SysTick. */
portNVIC_SYSTICK_CTRL_REG = 0UL;
portNVIC_SYSTICK_CURRENT_VALUE_REG = 0UL;
/* Configure SysTick to interrupt at the requested rate. */
portNVIC_SYSTICK_LOAD_REG = ( configSYSTICK_CLOCK_HZ / configTICK_RATE_HZ ) - 1UL;
portNVIC_SYSTICK_CTRL_REG = ( portNVIC_SYSTICK_CLK_BIT | portNVIC_SYSTICK_INT_BIT | portNVIC_SYSTICK_ENABLE_BIT );
}
/*-----------------------------------------------------------*/
#if ( configASSERT_DEFINED == 1 )
void vPortValidateInterruptPriority( void )
{
uint32_t ulCurrentInterrupt;
uint8_t ucCurrentPriority;
/* Obtain the number of the currently executing interrupt. */
__asm volatile ( "mrs %0, ipsr" : "=r" ( ulCurrentInterrupt )::"memory" );
/* Is the interrupt number a user defined interrupt? */
if( ulCurrentInterrupt >= portFIRST_USER_INTERRUPT_NUMBER )
{
/* Look up the interrupt's priority. */
ucCurrentPriority = pcInterruptPriorityRegisters[ ulCurrentInterrupt ];
/* The following assertion will fail if a service routine (ISR) for
* an interrupt that has been assigned a priority above
* configMAX_SYSCALL_INTERRUPT_PRIORITY calls an ISR safe FreeRTOS API
* function. ISR safe FreeRTOS API functions must *only* be called
* from interrupts that have been assigned a priority at or below
* configMAX_SYSCALL_INTERRUPT_PRIORITY.
*
* Numerically low interrupt priority numbers represent logically high
* interrupt priorities, therefore the priority of the interrupt must
* be set to a value equal to or numerically *higher* than
* configMAX_SYSCALL_INTERRUPT_PRIORITY.
*
* Interrupts that use the FreeRTOS API must not be left at their
* default priority of zero as that is the highest possible priority,
* which is guaranteed to be above configMAX_SYSCALL_INTERRUPT_PRIORITY,
* and therefore also guaranteed to be invalid.
*
* FreeRTOS maintains separate thread and ISR API functions to ensure
* interrupt entry is as fast and simple as possible.
*
* The following links provide detailed information:
* https://www.FreeRTOS.org/RTOS-Cortex-M3-M4.html
* https://www.FreeRTOS.org/FAQHelp.html */
configASSERT( ucCurrentPriority >= ucMaxSysCallPriority );
}
/* Priority grouping: The interrupt controller (NVIC) allows the bits
* that define each interrupt's priority to be split between bits that
* define the interrupt's pre-emption priority bits and bits that define
* the interrupt's sub-priority. For simplicity all bits must be defined
* to be pre-emption priority bits. The following assertion will fail if
* this is not the case (if some bits represent a sub-priority).
*
* If the application only uses CMSIS libraries for interrupt
* configuration then the correct setting can be achieved on all Cortex-M
* devices by calling NVIC_SetPriorityGrouping( 0 ); before starting the
* scheduler. Note however that some vendor specific peripheral libraries
* assume a non-zero priority group setting, in which cases using a value
* of zero will result in unpredictable behaviour. */
configASSERT( ( portAIRCR_REG & portPRIORITY_GROUP_MASK ) <= ulMaxPRIGROUPValue );
}
#endif /* configASSERT_DEFINED */
|
583165.c | #include <stdio.h>
#include <time.h>
#define N 1000
#define N2 1000000
int M1[N2];
int M2[N2];
int R[N2];
void printMatrix(int *M) {
int i, j;
for (i=0; i<N; i++) {
for (j=0; j<N; j++)
printf("%d ", M[i+j]);
printf("\n");
}
}
int main()
{
int ii, i, j, k, suma;
for(i = 0; i < N2; i++){
M1[i] = 1;
M2[i] = 2;
R[i] = 0;
}
struct timespec cgt1,cgt2; double ncgt;
clock_gettime(CLOCK_REALTIME,&cgt1);
for(i = 0; i < N; i++)
for(j = 0; j < N; j++)
for(k = 0; k < N; k++)
R[i*N+j] += M1[i*N+k] * M2[k*N+j];
clock_gettime(CLOCK_REALTIME,&cgt2);
ncgt=(double) (cgt2.tv_sec-cgt1.tv_sec)+(double) ((cgt2.tv_nsec-cgt1.tv_nsec)/(1.e+9));
printf("Tiempo = %11.9f\t R[0][0]=%d\t R[N-1][N-1]=%d\n",ncgt,R[0],R[N2-1]);
//printMatrix(R);
return 0;
}
|
343793.c | /* ----------------------------------------------------------------------------
Copyright (c) 2018-2021, Microsoft Research, Daan Leijen
This is free software; you can redistribute it and/or modify it under the
terms of the MIT license. A copy of the license can be found in the file
"LICENSE" at the root of this distribution.
-----------------------------------------------------------------------------*/
#if !defined(MI_IN_ALLOC_C)
#if !defined(BUILD_MONOLITHIC)
#error "this file should be included from 'alloc.c' (so aliases can work)"
#endif
#else
#if defined(MI_MALLOC_OVERRIDE) && defined(_WIN32) && !(defined(MI_SHARED_LIB) && defined(_DLL))
#error "It is only possible to override "malloc" on Windows when building as a DLL (and linking the C runtime as a DLL)"
#endif
#if defined(MI_MALLOC_OVERRIDE) && !(defined(_WIN32))
#if defined(__APPLE__)
mi_decl_externc void vfree(void* p);
mi_decl_externc size_t malloc_size(const void* p);
mi_decl_externc size_t malloc_good_size(size_t size);
#endif
// helper definition for C override of C++ new
typedef struct mi_nothrow_s { int _tag; } mi_nothrow_t;
// ------------------------------------------------------
// Override system malloc
// ------------------------------------------------------
#if (defined(__GNUC__) || defined(__clang__)) && !defined(__APPLE__) && !defined(MI_VALGRIND)
// gcc, clang: use aliasing to alias the exported function to one of our `mi_` functions
#if (defined(__GNUC__) && __GNUC__ >= 9)
#pragma GCC diagnostic ignored "-Wattributes" // or we get warnings that nodiscard is ignored on a forward
#define MI_FORWARD(fun) __attribute__((alias(#fun), used, visibility("default"), copy(fun)));
#else
#define MI_FORWARD(fun) __attribute__((alias(#fun), used, visibility("default")));
#endif
#define MI_FORWARD1(fun,x) MI_FORWARD(fun)
#define MI_FORWARD2(fun,x,y) MI_FORWARD(fun)
#define MI_FORWARD3(fun,x,y,z) MI_FORWARD(fun)
#define MI_FORWARD0(fun,x) MI_FORWARD(fun)
#define MI_FORWARD02(fun,x,y) MI_FORWARD(fun)
#else
// otherwise use forwarding by calling our `mi_` function
#define MI_FORWARD1(fun,x) { return fun(x); }
#define MI_FORWARD2(fun,x,y) { return fun(x,y); }
#define MI_FORWARD3(fun,x,y,z) { return fun(x,y,z); }
#define MI_FORWARD0(fun,x) { fun(x); }
#define MI_FORWARD02(fun,x,y) { fun(x,y); }
#endif
#if defined(__APPLE__) && defined(MI_SHARED_LIB_EXPORT) && defined(MI_OSX_INTERPOSE)
// define MI_OSX_IS_INTERPOSED as we should not provide forwarding definitions for
// functions that are interposed (or the interposing does not work)
#define MI_OSX_IS_INTERPOSED
// use interposing so `DYLD_INSERT_LIBRARIES` works without `DYLD_FORCE_FLAT_NAMESPACE=1`
// See: <https://books.google.com/books?id=K8vUkpOXhN4C&pg=PA73>
struct mi_interpose_s {
const void* replacement;
const void* target;
};
#define MI_INTERPOSE_FUN(oldfun,newfun) { (const void*)&newfun, (const void*)&oldfun }
#define MI_INTERPOSE_MI(fun) MI_INTERPOSE_FUN(fun,mi_##fun)
__attribute__((used)) static struct mi_interpose_s _mi_interposes[] __attribute__((section("__DATA, __interpose"))) =
{
MI_INTERPOSE_MI(malloc),
MI_INTERPOSE_MI(calloc),
MI_INTERPOSE_MI(realloc),
MI_INTERPOSE_MI(strdup),
MI_INTERPOSE_MI(strndup),
MI_INTERPOSE_MI(realpath),
MI_INTERPOSE_MI(posix_memalign),
MI_INTERPOSE_MI(reallocf),
MI_INTERPOSE_MI(valloc),
MI_INTERPOSE_MI(malloc_size),
MI_INTERPOSE_MI(malloc_good_size),
MI_INTERPOSE_MI(aligned_alloc),
#ifdef MI_OSX_ZONE
// we interpose malloc_default_zone in alloc-override-osx.c so we can use mi_free safely
MI_INTERPOSE_MI(free),
MI_INTERPOSE_FUN(vfree,mi_free),
#else
// sometimes code allocates from default zone but deallocates using plain free :-( (like NxHashResizeToCapacity <https://github.com/nneonneo/osx-10.9-opensource/blob/master/objc4-551.1/runtime/hashtable2.mm>)
MI_INTERPOSE_FUN(free,mi_cfree), // use safe free that checks if pointers are from us
MI_INTERPOSE_FUN(vfree,mi_cfree),
#endif
};
#ifdef __cplusplus
extern "C" {
void _ZdlPv(void* p); // delete
void _ZdaPv(void* p); // delete[]
void _ZdlPvm(void* p, size_t n); // delete
void _ZdaPvm(void* p, size_t n); // delete[]
void* _Znwm(size_t n); // new
void* _Znam(size_t n); // new[]
void* _ZnwmRKSt9nothrow_t(size_t n, mi_nothrow_t tag); // new nothrow
void* _ZnamRKSt9nothrow_t(size_t n, mi_nothrow_t tag); // new[] nothrow
}
__attribute__((used)) static struct mi_interpose_s _mi_cxx_interposes[] __attribute__((section("__DATA, __interpose"))) =
{
MI_INTERPOSE_FUN(_ZdlPv,mi_free),
MI_INTERPOSE_FUN(_ZdaPv,mi_free),
MI_INTERPOSE_FUN(_ZdlPvm,mi_free_size),
MI_INTERPOSE_FUN(_ZdaPvm,mi_free_size),
MI_INTERPOSE_FUN(_Znwm,mi_new),
MI_INTERPOSE_FUN(_Znam,mi_new),
MI_INTERPOSE_FUN(_ZnwmRKSt9nothrow_t,mi_new_nothrow),
MI_INTERPOSE_FUN(_ZnamRKSt9nothrow_t,mi_new_nothrow),
};
#endif // __cplusplus
#elif defined(_MSC_VER)
// cannot override malloc unless using a dll.
// we just override new/delete which does work in a static library.
#else
// On all other systems forward to our API
void* malloc(size_t size) MI_FORWARD1(mi_malloc, size)
void* calloc(size_t size, size_t n) MI_FORWARD2(mi_calloc, size, n)
void* realloc(void* p, size_t newsize) MI_FORWARD2(mi_realloc, p, newsize)
void free(void* p) MI_FORWARD0(mi_free, p)
#endif
#if (defined(__GNUC__) || defined(__clang__)) && !defined(__APPLE__)
#pragma GCC visibility push(default)
#endif
// ------------------------------------------------------
// Override new/delete
// This is not really necessary as they usually call
// malloc/free anyway, but it improves performance.
// ------------------------------------------------------
#ifdef __cplusplus
// ------------------------------------------------------
// With a C++ compiler we override the new/delete operators.
// see <https://en.cppreference.com/w/cpp/memory/new/operator_new>
// ------------------------------------------------------
#include <new>
#ifndef MI_OSX_IS_INTERPOSED
void operator delete(void* p) noexcept MI_FORWARD0(mi_free,p)
void operator delete[](void* p) noexcept MI_FORWARD0(mi_free,p)
void* operator new(std::size_t n) noexcept(false) MI_FORWARD1(mi_new,n)
void* operator new[](std::size_t n) noexcept(false) MI_FORWARD1(mi_new,n)
void* operator new (std::size_t n, const std::nothrow_t& tag) noexcept { MI_UNUSED(tag); return mi_new_nothrow(n); }
void* operator new[](std::size_t n, const std::nothrow_t& tag) noexcept { MI_UNUSED(tag); return mi_new_nothrow(n); }
#if (__cplusplus >= 201402L || _MSC_VER >= 1916)
void operator delete (void* p, std::size_t n) noexcept MI_FORWARD02(mi_free_size,p,n)
void operator delete[](void* p, std::size_t n) noexcept MI_FORWARD02(mi_free_size,p,n)
#endif
#endif
#if (__cplusplus > 201402L && defined(__cpp_aligned_new)) && (!defined(__GNUC__) || (__GNUC__ > 5))
void operator delete (void* p, std::align_val_t al) noexcept { mi_free_aligned(p, static_cast<size_t>(al)); }
void operator delete[](void* p, std::align_val_t al) noexcept { mi_free_aligned(p, static_cast<size_t>(al)); }
void operator delete (void* p, std::size_t n, std::align_val_t al) noexcept { mi_free_size_aligned(p, n, static_cast<size_t>(al)); };
void operator delete[](void* p, std::size_t n, std::align_val_t al) noexcept { mi_free_size_aligned(p, n, static_cast<size_t>(al)); };
void* operator new( std::size_t n, std::align_val_t al) noexcept(false) { return mi_new_aligned(n, static_cast<size_t>(al)); }
void* operator new[]( std::size_t n, std::align_val_t al) noexcept(false) { return mi_new_aligned(n, static_cast<size_t>(al)); }
void* operator new (std::size_t n, std::align_val_t al, const std::nothrow_t&) noexcept { return mi_new_aligned_nothrow(n, static_cast<size_t>(al)); }
void* operator new[](std::size_t n, std::align_val_t al, const std::nothrow_t&) noexcept { return mi_new_aligned_nothrow(n, static_cast<size_t>(al)); }
#endif
#elif (defined(__GNUC__) || defined(__clang__))
// ------------------------------------------------------
// Override by defining the mangled C++ names of the operators (as
// used by GCC and CLang).
// See <https://itanium-cxx-abi.github.io/cxx-abi/abi.html#mangling>
// ------------------------------------------------------
void _ZdlPv(void* p) MI_FORWARD0(mi_free,p) // delete
void _ZdaPv(void* p) MI_FORWARD0(mi_free,p) // delete[]
void _ZdlPvm(void* p, size_t n) MI_FORWARD02(mi_free_size,p,n)
void _ZdaPvm(void* p, size_t n) MI_FORWARD02(mi_free_size,p,n)
void _ZdlPvSt11align_val_t(void* p, size_t al) { mi_free_aligned(p,al); }
void _ZdaPvSt11align_val_t(void* p, size_t al) { mi_free_aligned(p,al); }
void _ZdlPvmSt11align_val_t(void* p, size_t n, size_t al) { mi_free_size_aligned(p,n,al); }
void _ZdaPvmSt11align_val_t(void* p, size_t n, size_t al) { mi_free_size_aligned(p,n,al); }
#if (MI_INTPTR_SIZE==8)
void* _Znwm(size_t n) MI_FORWARD1(mi_new,n) // new 64-bit
void* _Znam(size_t n) MI_FORWARD1(mi_new,n) // new[] 64-bit
void* _ZnwmRKSt9nothrow_t(size_t n, mi_nothrow_t tag) { MI_UNUSED(tag); return mi_new_nothrow(n); }
void* _ZnamRKSt9nothrow_t(size_t n, mi_nothrow_t tag) { MI_UNUSED(tag); return mi_new_nothrow(n); }
void* _ZnwmSt11align_val_t(size_t n, size_t al) MI_FORWARD2(mi_new_aligned, n, al)
void* _ZnamSt11align_val_t(size_t n, size_t al) MI_FORWARD2(mi_new_aligned, n, al)
void* _ZnwmSt11align_val_tRKSt9nothrow_t(size_t n, size_t al, mi_nothrow_t tag) { MI_UNUSED(tag); return mi_new_aligned_nothrow(n,al); }
void* _ZnamSt11align_val_tRKSt9nothrow_t(size_t n, size_t al, mi_nothrow_t tag) { MI_UNUSED(tag); return mi_new_aligned_nothrow(n,al); }
#elif (MI_INTPTR_SIZE==4)
void* _Znwj(size_t n) MI_FORWARD1(mi_new,n) // new 64-bit
void* _Znaj(size_t n) MI_FORWARD1(mi_new,n) // new[] 64-bit
void* _ZnwjRKSt9nothrow_t(size_t n, mi_nothrow_t tag) { MI_UNUSED(tag); return mi_new_nothrow(n); }
void* _ZnajRKSt9nothrow_t(size_t n, mi_nothrow_t tag) { MI_UNUSED(tag); return mi_new_nothrow(n); }
void* _ZnwjSt11align_val_t(size_t n, size_t al) MI_FORWARD2(mi_new_aligned, n, al)
void* _ZnajSt11align_val_t(size_t n, size_t al) MI_FORWARD2(mi_new_aligned, n, al)
void* _ZnwjSt11align_val_tRKSt9nothrow_t(size_t n, size_t al, mi_nothrow_t tag) { MI_UNUSED(tag); return mi_new_aligned_nothrow(n,al); }
void* _ZnajSt11align_val_tRKSt9nothrow_t(size_t n, size_t al, mi_nothrow_t tag) { MI_UNUSED(tag); return mi_new_aligned_nothrow(n,al); }
#else
#error "define overloads for new/delete for this platform (just for performance, can be skipped)"
#endif
#endif // __cplusplus
// ------------------------------------------------------
// Further Posix & Unix functions definitions
// ------------------------------------------------------
#ifdef __cplusplus
extern "C" {
#endif
#ifndef MI_OSX_IS_INTERPOSED
// Forward Posix/Unix calls as well
void* reallocf(void* p, size_t newsize) MI_FORWARD2(mi_reallocf,p,newsize)
size_t malloc_size(const void* p) MI_FORWARD1(mi_usable_size,p)
#if !defined(__ANDROID__) && !defined(__FreeBSD__)
size_t malloc_usable_size(void *p) MI_FORWARD1(mi_usable_size,p)
#else
size_t malloc_usable_size(const void *p) MI_FORWARD1(mi_usable_size,p)
#endif
// No forwarding here due to aliasing/name mangling issues
void* valloc(size_t size) { return mi_valloc(size); }
void vfree(void* p) { mi_free(p); }
size_t malloc_good_size(size_t size) { return mi_malloc_good_size(size); }
int posix_memalign(void** p, size_t alignment, size_t size) { return mi_posix_memalign(p, alignment, size); }
// `aligned_alloc` is only available when __USE_ISOC11 is defined.
// Note: Conda has a custom glibc where `aligned_alloc` is declared `static inline` and we cannot
// override it, but both _ISOC11_SOURCE and __USE_ISOC11 are undefined in Conda GCC7 or GCC9.
// Fortunately, in the case where `aligned_alloc` is declared as `static inline` it
// uses internally `memalign`, `posix_memalign`, or `_aligned_malloc` so we can avoid overriding it ourselves.
#if __USE_ISOC11
void* aligned_alloc(size_t alignment, size_t size) { return mi_aligned_alloc(alignment, size); }
#endif
#endif
// no forwarding here due to aliasing/name mangling issues
void cfree(void* p) { mi_free(p); }
void* pvalloc(size_t size) { return mi_pvalloc(size); }
void* reallocarray(void* p, size_t count, size_t size) { return mi_reallocarray(p, count, size); }
void* memalign(size_t alignment, size_t size) { return mi_memalign(alignment, size); }
void* _aligned_malloc(size_t alignment, size_t size) { return mi_aligned_alloc(alignment, size); }
#if defined(__GLIBC__) && defined(__linux__)
// forward __libc interface (needed for glibc-based Linux distributions)
void* __libc_malloc(size_t size) MI_FORWARD1(mi_malloc,size)
void* __libc_calloc(size_t count, size_t size) MI_FORWARD2(mi_calloc,count,size)
void* __libc_realloc(void* p, size_t size) MI_FORWARD2(mi_realloc,p,size)
void __libc_free(void* p) MI_FORWARD0(mi_free,p)
void __libc_cfree(void* p) MI_FORWARD0(mi_free,p)
void* __libc_valloc(size_t size) { return mi_valloc(size); }
void* __libc_pvalloc(size_t size) { return mi_pvalloc(size); }
void* __libc_memalign(size_t alignment, size_t size) { return mi_memalign(alignment,size); }
int __posix_memalign(void** p, size_t alignment, size_t size) { return mi_posix_memalign(p,alignment,size); }
#endif
#ifdef __cplusplus
}
#endif
#if (defined(__GNUC__) || defined(__clang__)) && !defined(__APPLE__)
#pragma GCC visibility pop
#endif
#endif // MI_MALLOC_OVERRIDE && !_WIN32
#endif
|
425952.c | #include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include "die.h"
#include "e.h"
#include "savesync.h"
#include "randombytes.h"
#include "crypto_box.h"
void die_usage(void)
{
die_1(111,"curvecpmakekey: usage: curvecpmakekey keydir\n");
}
void die_fatal(const char *trouble,const char *d,const char *fn)
{
if (fn) die_9(111,"curvecpmakekey: fatal: ",trouble," ",d,"/",fn,": ",e_str(errno),"\n");
die_7(111,"curvecpmakekey: fatal: ",trouble," ",d,": ",e_str(errno),"\n");
}
unsigned char pk[crypto_box_PUBLICKEYBYTES];
unsigned char sk[crypto_box_SECRETKEYBYTES];
unsigned char lock[1];
unsigned char noncekey[32];
unsigned char noncecounter[8];
void create(const char *d,const char *fn,const unsigned char *x,long long xlen)
{
if (savesync(fn,x,xlen) == -1) die_fatal("unable to create",d,fn);
}
int main(int argc,char **argv)
{
char *d;
if (!argv[0]) die_usage();
if (!argv[1]) die_usage();
d = argv[1];
umask(022);
if (mkdir(d,0755) == -1) die_fatal("unable to create directory",d,0);
if (chdir(d) == -1) die_fatal("unable to chdir to directory",d,0);
if (mkdir(".expertsonly",0700) == -1) die_fatal("unable to create directory",d,".expertsonly");
crypto_box_keypair(pk,sk);
create(d,"publickey",pk,sizeof pk);
randombytes(noncekey,sizeof noncekey);
umask(077);
create(d,".expertsonly/secretkey",sk,sizeof sk);
create(d,".expertsonly/lock",lock,sizeof lock);
create(d,".expertsonly/noncekey",noncekey,sizeof noncekey);
create(d,".expertsonly/noncecounter",noncecounter,sizeof noncecounter);
return 0;
}
|
124287.c | /* shrink with a box filter
*
* Copyright: 1990, N. Dessipris.
*
* Authors: Nicos Dessipris and Kirk Martinez
* Written on: 29/04/1991
* Modified on: 2/11/92, 22/2/93 Kirk Martinez - Xres Yres & cleanup
incredibly inefficient for box filters as LUTs are used instead of +
Needs converting to a smoother filter: eg Gaussian! KM
* 15/7/93 JC
* - rewritten for partial v2
* - ANSIfied
* - now shrinks any non-complex type
* - no longer cloned from im_convsub()
* - could be much better! see km comments above
* 3/8/93 JC
* - rounding bug fixed
* 11/1/94 JC
* - problems with .000001 and round up/down ignored! Try shrink 3738
* pixel image by 9.345000000001
* 7/10/94 JC
* - IM_NEW and IM_ARRAY added
* - more typedef
* 3/7/95 JC
* - IM_CODING_LABQ handling added here
* 20/12/08
* - fall back to im_copy() for 1/1 shrink
* 2/2/11
* - gtk-doc
* 10/2/12
* - shrink in chunks to reduce peak memuse for large shrinks
* - simpler
* 12/6/12
* - redone as a class
* - warn about non-int shrinks
* - some tuning .. tried an int coordinate path, not worthwhile
* 16/11/12
* - don't change xres/yres, see comment below
* 8/4/13
* - oops demand_hint was incorrect, thanks Jan
* 6/6/13
* - don't chunk horizontally, fixes seq problems with large shrink
* factors
*/
/*
This file is part of VIPS.
VIPS is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301 USA
*/
/*
These files are distributed with VIPS - http://www.vips.ecs.soton.ac.uk
*/
/*
#define DEBUG
*/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif /*HAVE_CONFIG_H*/
#include <vips/intl.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>
#include <vips/vips.h>
#include <vips/debug.h>
#include <vips/internal.h>
#include "presample.h"
typedef struct _VipsShrinkv {
VipsResample parent_instance;
int yshrink;
size_t sizeof_line_buffer;
} VipsShrinkv;
typedef VipsResampleClass VipsShrinkvClass;
G_DEFINE_TYPE( VipsShrinkv, vips_shrinkv, VIPS_TYPE_RESAMPLE );
/* Our per-sequence parameter struct. Somewhere to sum band elements.
*/
typedef struct {
VipsRegion *ir;
VipsPel *sum;
} VipsShrinkvSequence;
/* Free a sequence value.
*/
static int
vips_shrinkv_stop( void *vseq, void *a, void *b )
{
VipsShrinkvSequence *seq = (VipsShrinkvSequence *) vseq;
VIPS_FREEF( g_object_unref, seq->ir );
return( 0 );
}
/* Make a sequence value.
*/
static void *
vips_shrinkv_start( VipsImage *out, void *a, void *b )
{
VipsImage *in = (VipsImage *) a;
VipsShrinkv *shrink = (VipsShrinkv *) b;
VipsShrinkvSequence *seq;
if( !(seq = VIPS_NEW( out, VipsShrinkvSequence )) )
return( NULL );
seq->ir = vips_region_new( in );
/* Big enough for the largest intermediate .. a whole scanline.
*/
seq->sum = VIPS_ARRAY( out, shrink->sizeof_line_buffer, VipsPel );
return( (void *) seq );
}
#define ADD( ACC_TYPE, TYPE ) { \
ACC_TYPE * restrict sum = (ACC_TYPE *) seq->sum; \
TYPE * restrict p = (TYPE *) in; \
\
for( x = 0; x < sz; x++ ) \
sum[x] += p[x]; \
}
/* Add a line of pixels to sum.
*/
static void
vips_shrinkv_add_line( VipsShrinkv *shrink, VipsShrinkvSequence *seq,
VipsRegion *ir, int left, int top, int width )
{
VipsResample *resample = VIPS_RESAMPLE( shrink );
const int bands = resample->in->Bands *
(vips_band_format_iscomplex( resample->in->BandFmt ) ?
2 : 1);
const int sz = bands * width;
int x;
VipsPel *in = VIPS_REGION_ADDR( ir, left, top );
switch( resample->in->BandFmt ) {
case VIPS_FORMAT_UCHAR:
ADD( int, unsigned char ); break;
case VIPS_FORMAT_CHAR:
ADD( int, char ); break;
case VIPS_FORMAT_USHORT:
ADD( int, unsigned short ); break;
case VIPS_FORMAT_SHORT:
ADD( int, short ); break;
case VIPS_FORMAT_UINT:
ADD( int, unsigned int ); break;
case VIPS_FORMAT_INT:
ADD( int, int ); break;
case VIPS_FORMAT_FLOAT:
ADD( double, float ); break;
case VIPS_FORMAT_DOUBLE:
ADD( double, double ); break;
case VIPS_FORMAT_COMPLEX:
ADD( double, float ); break;
case VIPS_FORMAT_DPCOMPLEX:
ADD( double, double ); break;
default:
g_assert_not_reached();
}
}
/* Integer average.
*/
#define IAVG( TYPE ) { \
int * restrict sum = (int *) seq->sum; \
TYPE * restrict q = (TYPE *) out; \
\
for( x = 0; x < sz; x++ ) \
q[x] = (sum[x] + shrink->yshrink / 2) / shrink->yshrink; \
}
/* Float average.
*/
#define FAVG( TYPE ) { \
double * restrict sum = (double *) seq->sum; \
TYPE * restrict q = (TYPE *) out; \
\
for( x = 0; x < sz; x++ ) \
q[x] = sum[x] / shrink->yshrink; \
}
/* Average the line of sums to out.
*/
static void
vips_shrinkv_write_line( VipsShrinkv *shrink, VipsShrinkvSequence *seq,
VipsRegion *or, int left, int top, int width )
{
VipsResample *resample = VIPS_RESAMPLE( shrink );
const int bands = resample->in->Bands *
(vips_band_format_iscomplex( resample->in->BandFmt ) ?
2 : 1);
const int sz = bands * width;
int x;
VipsPel *out = VIPS_REGION_ADDR( or, left, top );
switch( resample->in->BandFmt ) {
case VIPS_FORMAT_UCHAR:
IAVG( unsigned char ); break;
case VIPS_FORMAT_CHAR:
IAVG( char ); break;
case VIPS_FORMAT_USHORT:
IAVG( unsigned short ); break;
case VIPS_FORMAT_SHORT:
IAVG( short ); break;
case VIPS_FORMAT_UINT:
IAVG( unsigned int ); break;
case VIPS_FORMAT_INT:
IAVG( int ); break;
case VIPS_FORMAT_FLOAT:
FAVG( float ); break;
case VIPS_FORMAT_DOUBLE:
FAVG( double ); break;
case VIPS_FORMAT_COMPLEX:
FAVG( float ); break;
case VIPS_FORMAT_DPCOMPLEX:
FAVG( double ); break;
default:
g_assert_not_reached();
}
}
static int
vips_shrinkv_gen( VipsRegion *or, void *vseq,
void *a, void *b, gboolean *stop )
{
VipsShrinkvSequence *seq = (VipsShrinkvSequence *) vseq;
VipsShrinkv *shrink = (VipsShrinkv *) b;
VipsRegion *ir = seq->ir;
VipsRect *r = &or->valid;
int y, y1;
/* How do we chunk up the image? We don't want to prepare the whole of
* the input region corresponding to *r since it could be huge.
*
* Request input a line at a time, average to a line buffer.
*
* We don't chunk horizontally. We want "vips shrink x.jpg b.jpg 100
* 100" to run sequentially. If we chunk horizontally, we will fetch
* 100x100 lines from the top of the image, then 100x100 100 lines
* down, etc. for each thread, then when they've finished, fetch
* 100x100, 100 pixels across from the top of the image. This will
* break sequentiality.
*/
#ifdef DEBUG
printf( "vips_shrinkv_gen: generating %d x %d at %d x %d\n",
r->width, r->height, r->left, r->top );
#endif /*DEBUG*/
for( y = 0; y < r->height; y++ ) {
memset( seq->sum, 0, shrink->sizeof_line_buffer );
for( y1 = 0; y1 < shrink->yshrink; y1++ ) {
VipsRect s;
s.left = r->left;
s.top = y1 + (y + r->top) * shrink->yshrink;
s.width = r->width;
s.height = 1;
#ifdef DEBUG
printf( "shrink_gen: requesting line %d\n", s.top );
#endif /*DEBUG*/
if( vips_region_prepare( ir, &s ) )
return( -1 );
VIPS_GATE_START( "vips_shrinkv_gen: work" );
vips_shrinkv_add_line( shrink, seq, ir,
s.left, s.top, s.width );
VIPS_GATE_STOP( "vips_shrinkv_gen: work" );
}
VIPS_GATE_START( "vips_shrinkv_gen: work" );
vips_shrinkv_write_line( shrink, seq, or,
r->left, r->top + y, r->width );
VIPS_GATE_STOP( "vips_shrinkv_gen: work" );
}
return( 0 );
}
static int
vips_shrinkv_build( VipsObject *object )
{
VipsObjectClass *class = VIPS_OBJECT_GET_CLASS( object );
VipsResample *resample = VIPS_RESAMPLE( object );
VipsShrinkv *shrink = (VipsShrinkv *) object;
VipsImage **t = (VipsImage **)
vips_object_local_array( object, 1 );
VipsImage *in;
if( VIPS_OBJECT_CLASS( vips_shrinkv_parent_class )->build( object ) )
return( -1 );
in = resample->in;
if( shrink->yshrink < 1 ) {
vips_error( class->nickname,
"%s", _( "shrink factors should be >= 1" ) );
return( -1 );
}
if( shrink->yshrink == 1 )
return( vips_image_write( in, resample->out ) );
/* Unpack for processing.
*/
if( vips_image_decode( in, &t[0] ) )
return( -1 );
in = t[0];
/* We have to keep a line buffer as we sum columns.
*/
shrink->sizeof_line_buffer =
in->Xsize * in->Bands *
vips_format_sizeof( VIPS_FORMAT_DPCOMPLEX );
/* THINSTRIP will work, anything else will break seq mode. If you
* combine shrink with conv you'll need to use a line cache to maintain
* sequentiality.
*/
if( vips_image_pipelinev( resample->out,
VIPS_DEMAND_STYLE_THINSTRIP, in, NULL ) )
return( -1 );
/* Size output. Note: we round the output width down!
*
* Don't change xres/yres, leave that to the application layer. For
* example, vipsthumbnail knows the true shrink factor (including the
* fractional part), we just see the integer part here.
*/
resample->out->Ysize = in->Ysize / shrink->yshrink;
if( resample->out->Ysize <= 0 ) {
vips_error( class->nickname,
"%s", _( "image has shrunk to nothing" ) );
return( -1 );
}
#ifdef DEBUG
printf( "vips_shrinkv_build: shrinking %d x %d image to %d x %d\n",
in->Xsize, in->Ysize,
resample->out->Xsize, resample->out->Ysize );
#endif /*DEBUG*/
if( vips_image_generate( resample->out,
vips_shrinkv_start, vips_shrinkv_gen, vips_shrinkv_stop,
in, shrink ) )
return( -1 );
return( 0 );
}
static void
vips_shrinkv_class_init( VipsShrinkvClass *class )
{
GObjectClass *gobject_class = G_OBJECT_CLASS( class );
VipsObjectClass *vobject_class = VIPS_OBJECT_CLASS( class );
VipsOperationClass *operation_class = VIPS_OPERATION_CLASS( class );
VIPS_DEBUG_MSG( "vips_shrinkv_class_init\n" );
gobject_class->set_property = vips_object_set_property;
gobject_class->get_property = vips_object_get_property;
vobject_class->nickname = "shrinkv";
vobject_class->description = _( "shrink an image vertically" );
vobject_class->build = vips_shrinkv_build;
operation_class->flags = VIPS_OPERATION_SEQUENTIAL_UNBUFFERED;
VIPS_ARG_INT( class, "yshrink", 9,
_( "Yshrink" ),
_( "Vertical shrink factor" ),
VIPS_ARGUMENT_REQUIRED_INPUT,
G_STRUCT_OFFSET( VipsShrinkv, yshrink ),
1, 1000000, 1 );
}
static void
vips_shrinkv_init( VipsShrinkv *shrink )
{
}
/**
* vips_shrinkv:
* @in: input image
* @out: output image
* @yshrink: vertical shrink
* @...: %NULL-terminated list of optional named arguments
*
* Shrink @in vertically by an integer factor. Each pixel in the output is
* the average of the corresponding column of @yshrink pixels in the input.
*
* You will get aliasing for non-integer shrinks. In this case, shrink with
* this function to the nearest integer size above the target shrink, then
* downsample to the exact size with vips_affine() and your choice of
* interpolator. See vips_resize() for a convenient way to do this.
*
* This operation does not change xres or yres. The image resolution needs to
* be updated by the application.
*
* See also: vips_shrinkh(), vips_shrink(), vips_resize(), vips_affine().
*
* Returns: 0 on success, -1 on error
*/
int
vips_shrinkv( VipsImage *in, VipsImage **out, int yshrink, ... )
{
va_list ap;
int result;
va_start( ap, yshrink );
result = vips_call_split( "shrinkv", ap, in, out, yshrink );
va_end( ap );
return( result );
}
|
468905.c | /* mbed Microcontroller Library
* Copyright (c) 2006-2013 ARM Limited
*
* 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 "PeripheralPins.h"
/************RTC***************/
const PinMap PinMap_RTC[] = {
{NC, OSC32KCLK, 0},
};
/************ADC***************/
const PinMap PinMap_ADC[] = {
{GPIO_AD_B1_10, ADC1_15, 5},
{GPIO_AD_B1_11, ADC2_0, 5},
{GPIO_AD_B1_04, ADC1_9, 5},
{GPIO_AD_B1_05, ADC1_10, 5},
{GPIO_AD_B1_01, ADC1_6, 5},
{GPIO_AD_B1_00, ADC1_5, 5},
{NC , NC , 0}
};
/************DAC***************/
const PinMap PinMap_DAC[] = {
{NC , NC , 0}
};
/************I2C***************/
const PinMap PinMap_I2C_SDA[] = {
{GPIO_AD_B1_01, I2C_1, ((1U << DAISY_REG_VALUE_SHIFT) | (0x4D0 << DAISY_REG_SHIFT) | (1U << SION_BIT_SHIFT) | 3)},
{NC , NC , 0}
};
const PinMap PinMap_I2C_SCL[] = {
{GPIO_AD_B1_00, I2C_1, ((1U << DAISY_REG_VALUE_SHIFT) | (0x4CC << DAISY_REG_SHIFT) | (1U << SION_BIT_SHIFT) | 3)},
{NC , NC , 0}
};
/************UART***************/
const PinMap PinMap_UART_TX[] = {
{GPIO_AD_B0_12, UART_1, 2},
{NC , NC , 0}
};
const PinMap PinMap_UART_RX[] = {
{GPIO_AD_B0_13, UART_1, 2},
{NC , NC , 0}
};
/************SPI***************/
const PinMap PinMap_SPI_SCLK[] = {
{GPIO_SD_B0_00, SPI_1, ((1U << DAISY_REG_VALUE_SHIFT) | (0x4F0 << DAISY_REG_SHIFT) | 4)},
{GPIO_AD_B0_00, SPI_3, ((0U << DAISY_REG_VALUE_SHIFT) | (0x510 << DAISY_REG_SHIFT) | 7)},
{NC , NC , 0}
};
const PinMap PinMap_SPI_MOSI[] = {
{GPIO_SD_B0_02, SPI_1, ((1U << DAISY_REG_VALUE_SHIFT) | (0x4F8 << DAISY_REG_SHIFT) | 4)},
{GPIO_AD_B0_01, SPI_3, ((0U << DAISY_REG_VALUE_SHIFT) | (0x518 << DAISY_REG_SHIFT) | 7)},
{NC , NC , 0}
};
const PinMap PinMap_SPI_MISO[] = {
{GPIO_SD_B0_03, SPI_1, ((1U << DAISY_REG_VALUE_SHIFT) | (0x4F4 << DAISY_REG_SHIFT) | 4)},
{GPIO_AD_B0_02, SPI_3, ((0U << DAISY_REG_VALUE_SHIFT) | (0x514 << DAISY_REG_SHIFT) | 7)},
{NC , NC , 0}
};
const PinMap PinMap_SPI_SSEL[] = {
{GPIO_SD_B0_01, SPI_1, ((0U << DAISY_REG_VALUE_SHIFT) | (0x4EC << DAISY_REG_SHIFT) | 4)},
{GPIO_AD_B0_03, SPI_3, ((0U << DAISY_REG_VALUE_SHIFT) | (0x50C << DAISY_REG_SHIFT) | 7)},
{NC , NC , 0}
};
/************PWM***************/
const PinMap PinMap_PWM[] = {
{GPIO_AD_B0_10, PWM_7, ((3U << DAISY_REG_VALUE_SHIFT) | (0x454 << DAISY_REG_SHIFT) | 1)},
{GPIO_AD_B0_11, PWM_8, ((3U << DAISY_REG_VALUE_SHIFT) | (0x464 << DAISY_REG_SHIFT) | 1)},
{GPIO_AD_B1_08, PWM_25, ((1U << DAISY_REG_VALUE_SHIFT) | (0x494 << DAISY_REG_SHIFT) | 1)},
{GPIO_SD_B0_00, PWM_1, ((1U << DAISY_REG_VALUE_SHIFT) | (0x458 << DAISY_REG_SHIFT) | 1)},
{GPIO_SD_B0_01, PWM_2, ((1U << DAISY_REG_VALUE_SHIFT) | (0x468 << DAISY_REG_SHIFT) | 1)},
{NC , NC , 0}
};
|
340948.c | /*
* Copyright (c) 2020
* IoTech Ltd
*
* SPDX-License-Identifier: Apache-2.0
*/
#include "iot/component.h"
#include "iot/thread.h"
#ifdef NDEBUG
#define IOT_RET_CHECK(n) n
#else
#define IOT_RET_CHECK(n) assert ((n) == 0)
#endif
void iot_component_init (iot_component_t * component, const iot_component_factory_t * factory, iot_component_start_fn_t start, iot_component_stop_fn_t stop)
{
assert (component && start && stop);
component->start_fn = start;
component->stop_fn = stop;
component->factory = factory;
iot_mutex_init (&component->mutex);
pthread_cond_init (&component->cond, NULL);
atomic_store (&component->refs, 1);
}
bool iot_component_reconfig (iot_component_t * component, iot_container_t * cont, const iot_data_t * map)
{
assert (component && cont && map);
return (component->factory && component->factory->reconfig_fn) ? (component->factory->reconfig_fn) (component, cont, map) : false;
}
void iot_component_fini (iot_component_t * component)
{
pthread_cond_destroy (&component->cond);
pthread_mutex_destroy (&component->mutex);
}
void iot_component_add_ref (iot_component_t * component)
{
atomic_fetch_add (&component->refs, 1);
}
bool iot_component_dec_ref (iot_component_t * component)
{
return (atomic_fetch_add (&component->refs, -1) <= 1);
}
static bool iot_component_set_state (iot_component_t * component, uint32_t state)
{
assert (component);
bool valid = false;
bool changed = false;
IOT_RET_CHECK (pthread_mutex_lock (&component->mutex));
switch (state)
{
case IOT_COMPONENT_STOPPED:
case IOT_COMPONENT_RUNNING:
case IOT_COMPONENT_STARTING: valid = (component->state != IOT_COMPONENT_DELETED); break;
case IOT_COMPONENT_DELETED: valid = (component->state != IOT_COMPONENT_RUNNING); break;
default: break;
}
if (valid)
{
changed = component->state != state;
component->state = state;
IOT_RET_CHECK (pthread_cond_broadcast (&component->cond));
}
IOT_RET_CHECK (pthread_mutex_unlock (&component->mutex));
return changed;
}
extern iot_component_state_t iot_component_wait (iot_component_t * component, uint32_t states)
{
iot_component_state_t state = iot_component_wait_and_lock (component, states);
IOT_RET_CHECK (pthread_mutex_unlock (&component->mutex));
return state;
}
extern iot_component_state_t iot_component_wait_and_lock (iot_component_t * component, uint32_t states)
{
assert (component);
IOT_RET_CHECK (pthread_mutex_lock (&component->mutex));
while ((component->state & states) == 0)
{
pthread_cond_wait (&component->cond, &component->mutex);
}
return component->state;
}
iot_component_state_t iot_component_lock (iot_component_t * component)
{
IOT_RET_CHECK (pthread_mutex_lock (&component->mutex));
return component->state;
}
iot_component_state_t iot_component_unlock (iot_component_t * component)
{
iot_component_state_t state = component->state;
IOT_RET_CHECK (pthread_mutex_unlock (&component->mutex));
return state;
}
bool iot_component_set_running (iot_component_t * component)
{
return iot_component_set_state (component, IOT_COMPONENT_RUNNING);
}
bool iot_component_set_stopped (iot_component_t * component)
{
return iot_component_set_state (component, IOT_COMPONENT_STOPPED);
}
bool iot_component_set_deleted (iot_component_t * component)
{
return iot_component_set_state (component, IOT_COMPONENT_DELETED);
}
bool iot_component_set_starting (iot_component_t * component)
{
return iot_component_set_state (component, IOT_COMPONENT_STARTING);
}
extern const char * iot_component_state_name (iot_component_state_t state)
{
switch (state)
{
case IOT_COMPONENT_INITIAL: return "Initial";
case IOT_COMPONENT_STOPPED: return "Stopped";
case IOT_COMPONENT_RUNNING: return "Running";
case IOT_COMPONENT_DELETED: return "Deleted";
case IOT_COMPONENT_STARTING: return "Starting";
default: break;
}
return "Unknown";
}
extern void iot_component_info_free (iot_component_info_t * info)
{
if (info)
{
iot_component_data_t * data;
while (info->data)
{
data = info->data;
info->data = data->next;
free (data->name);
free (data->type);
free (data);
}
free (info);
}
} |
975279.c | /*!A cross-platform build utility based on Lua
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Copyright (C) 2015-2020, TBOOX Open Source Group.
*
* @author ruki
* @file filelock_open.c
*
*/
/* //////////////////////////////////////////////////////////////////////////////////////
* trace
*/
#define TB_TRACE_MODULE_NAME "filelock_open"
#define TB_TRACE_MODULE_DEBUG (0)
/* //////////////////////////////////////////////////////////////////////////////////////
* includes
*/
#include "prefix.h"
/* //////////////////////////////////////////////////////////////////////////////////////
* implementation
*/
/*
* io.filelock_open(path)
*/
tb_int_t xm_io_filelock_open(lua_State* lua)
{
// check
tb_assert_and_check_return_val(lua, 0);
// get file path
tb_char_t const* path = luaL_checkstring(lua, 1);
tb_assert_and_check_return_val(path, 0);
// init file lock
tb_long_t tryn = 2;
tb_filelock_ref_t lock = tb_null;
while (!lock && tryn-- > 0)
lock = tb_filelock_init_from_path(path, tb_file_info(path, tb_null)? TB_FILE_MODE_RO : TB_FILE_MODE_RW | TB_FILE_MODE_CREAT);
if (lock) lua_pushlightuserdata(lua, (tb_pointer_t)lock);
else lua_pushnil(lua);
return 1;
}
|
687315.c | #include <linux/mm.h>
#include <linux/init.h>
#include <linux/dma-mapping.h>
#include <linux/scatterlist.h>
#include <linux/swiotlb.h>
#include <linux/bootmem.h>
#include <asm/bootinfo.h>
#include <boot_param.h>
#include <dma-coherence.h>
static void *loongson_dma_alloc_coherent(struct device *dev, size_t size,
dma_addr_t *dma_handle, gfp_t gfp, unsigned long attrs)
{
void *ret;
/* ignore region specifiers */
gfp &= ~(__GFP_DMA | __GFP_DMA32 | __GFP_HIGHMEM);
if ((IS_ENABLED(CONFIG_ISA) && dev == NULL) ||
(IS_ENABLED(CONFIG_ZONE_DMA) &&
dev->coherent_dma_mask < DMA_BIT_MASK(32)))
gfp |= __GFP_DMA;
else if (IS_ENABLED(CONFIG_ZONE_DMA32) &&
dev->coherent_dma_mask < DMA_BIT_MASK(40))
gfp |= __GFP_DMA32;
gfp |= __GFP_NORETRY;
ret = swiotlb_alloc_coherent(dev, size, dma_handle, gfp);
mb();
return ret;
}
static void loongson_dma_free_coherent(struct device *dev, size_t size,
void *vaddr, dma_addr_t dma_handle, unsigned long attrs)
{
swiotlb_free_coherent(dev, size, vaddr, dma_handle);
}
static dma_addr_t loongson_dma_map_page(struct device *dev, struct page *page,
unsigned long offset, size_t size,
enum dma_data_direction dir,
unsigned long attrs)
{
dma_addr_t daddr = swiotlb_map_page(dev, page, offset, size,
dir, attrs);
mb();
return daddr;
}
static int loongson_dma_map_sg(struct device *dev, struct scatterlist *sg,
int nents, enum dma_data_direction dir,
unsigned long attrs)
{
int r = swiotlb_map_sg_attrs(dev, sg, nents, dir, attrs);
mb();
return r;
}
static void loongson_dma_sync_single_for_device(struct device *dev,
dma_addr_t dma_handle, size_t size,
enum dma_data_direction dir)
{
swiotlb_sync_single_for_device(dev, dma_handle, size, dir);
mb();
}
static void loongson_dma_sync_sg_for_device(struct device *dev,
struct scatterlist *sg, int nents,
enum dma_data_direction dir)
{
swiotlb_sync_sg_for_device(dev, sg, nents, dir);
mb();
}
static int loongson_dma_supported(struct device *dev, u64 mask)
{
if (mask > DMA_BIT_MASK(loongson_sysconf.dma_mask_bits))
return 0;
return swiotlb_dma_supported(dev, mask);
}
dma_addr_t phys_to_dma(struct device *dev, phys_addr_t paddr)
{
long nid;
#ifdef CONFIG_PHYS48_TO_HT40
/* We extract 2bit node id (bit 44~47, only bit 44~45 used now) from
* Loongson-3's 48bit address space and embed it into 40bit */
nid = (paddr >> 44) & 0x3;
paddr = ((nid << 44) ^ paddr) | (nid << 37);
#endif
return paddr;
}
phys_addr_t dma_to_phys(struct device *dev, dma_addr_t daddr)
{
long nid;
#ifdef CONFIG_PHYS48_TO_HT40
/* We extract 2bit node id (bit 44~47, only bit 44~45 used now) from
* Loongson-3's 48bit address space and embed it into 40bit */
nid = (daddr >> 37) & 0x3;
daddr = ((nid << 37) ^ daddr) | (nid << 44);
#endif
return daddr;
}
static const struct dma_map_ops loongson_dma_map_ops = {
.alloc = loongson_dma_alloc_coherent,
.free = loongson_dma_free_coherent,
.map_page = loongson_dma_map_page,
.unmap_page = swiotlb_unmap_page,
.map_sg = loongson_dma_map_sg,
.unmap_sg = swiotlb_unmap_sg_attrs,
.sync_single_for_cpu = swiotlb_sync_single_for_cpu,
.sync_single_for_device = loongson_dma_sync_single_for_device,
.sync_sg_for_cpu = swiotlb_sync_sg_for_cpu,
.sync_sg_for_device = loongson_dma_sync_sg_for_device,
.mapping_error = swiotlb_dma_mapping_error,
.dma_supported = loongson_dma_supported,
};
void __init plat_swiotlb_setup(void)
{
swiotlb_init(1);
mips_dma_map_ops = &loongson_dma_map_ops;
}
|
329082.c | /*
* Copyright (c) 2018 Intel Corporation.
*
* SPDX-License-Identifier: Apache-2.0
*/
#include <zephyr.h>
#include <kernel.h>
#include <string.h>
#include <soc.h>
#include <device.h>
#include "policy/pm_policy.h"
#if defined(CONFIG_SYS_POWER_MANAGEMENT)
#define LOG_LEVEL CONFIG_SYS_PM_LOG_LEVEL /* From power module Kconfig */
#include <logging/log.h>
LOG_MODULE_DECLARE(power);
/*
* FIXME: Remove the conditional inclusion of
* core_devices array once we enble the capability
* to build the device list based on devices power
* and clock domain dependencies.
*/
#if defined(CONFIG_SOC_SERIES_NRF52X) || defined(CONFIG_SOC_SERIES_NRF51X)
#define MAX_PM_DEVICES 15
#define NUM_CORE_DEVICES 4
#define MAX_DEV_NAME_LEN 16
static const char core_devices[NUM_CORE_DEVICES][MAX_DEV_NAME_LEN] = {
"CLOCK_32K",
"CLOCK_16M",
"sys_clock",
"UART_0",
};
#else
#error "Add SoC's core devices list for PM"
#endif
/*
* Ordered list to store devices on which
* device power policies would be executed.
*/
static int device_ordered_list[MAX_PM_DEVICES];
static int device_retval[MAX_PM_DEVICES];
static struct device *pm_device_list;
static int device_count;
int sys_pm_suspend_devices(void)
{
for (int i = device_count - 1; i >= 0; i--) {
int idx = device_ordered_list[i];
/* TODO: Improve the logic by checking device status
* and set the device states accordingly.
*/
device_retval[i] = device_set_power_state(&pm_device_list[idx],
DEVICE_PM_SUSPEND_STATE,
NULL, NULL);
if (device_retval[i]) {
LOG_DBG("%s did not enter suspend state",
pm_device_list[idx].config->name);
return device_retval[i];
}
}
return 0;
}
int sys_pm_low_power_devices(void)
{
for (int i = device_count - 1; i >= 0; i--) {
int idx = device_ordered_list[i];
device_retval[i] = device_set_power_state(&pm_device_list[idx],
DEVICE_PM_LOW_POWER_STATE,
NULL, NULL);
if (device_retval[i]) {
LOG_DBG("%s did not enter low power state",
pm_device_list[idx].config->name);
return device_retval[i];
}
}
return 0;
}
int sys_pm_force_suspend_devices(void)
{
for (int i = device_count - 1; i >= 0; i--) {
int idx = device_ordered_list[i];
device_retval[i] = device_set_power_state(&pm_device_list[idx],
DEVICE_PM_FORCE_SUSPEND_STATE,
NULL, NULL);
if (device_retval[i]) {
LOG_ERR("%s force suspend operation failed",
pm_device_list[idx].config->name);
return device_retval[i];
}
}
return 0;
}
void sys_pm_resume_devices(void)
{
int i;
for (i = 0; i < device_count; i++) {
if (!device_retval[i]) {
int idx = device_ordered_list[i];
device_set_power_state(&pm_device_list[idx],
DEVICE_PM_ACTIVE_STATE, NULL, NULL);
}
}
}
void sys_pm_create_device_list(void)
{
int count;
int i, j;
bool is_core_dev;
/*
* Create an ordered list of devices that will be suspended.
* Ordering should be done based on dependencies. Devices
* in the beginning of the list will be resumed first.
*/
device_list_get(&pm_device_list, &count);
/* Reserve for 32KHz, 16MHz, system clock, etc... */
device_count = NUM_CORE_DEVICES;
for (i = 0; (i < count) && (device_count < MAX_PM_DEVICES); i++) {
/* Check if the device is core device */
for (j = 0, is_core_dev = false; j < NUM_CORE_DEVICES; j++) {
if (!strcmp(pm_device_list[i].config->name,
&core_devices[j][0])) {
is_core_dev = true;
break;
}
}
if (is_core_dev) {
device_ordered_list[j] = i;
} else {
device_ordered_list[device_count++] = i;
}
}
}
#endif /* defined(CONFIG_SYS_POWER_MANAGEMENT) */
|
426789.c | /*
* Copyright (c) 2022 Calvin Rose
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*/
#ifndef JANET_AMALG
#include "features.h"
#include <janet.h>
#include "gc.h"
#include "util.h"
#include <math.h>
#endif
/* Begin creation of a struct */
JanetKV *janet_struct_begin(int32_t count) {
/* Calculate capacity as power of 2 after 2 * count. */
int32_t capacity = janet_tablen(2 * count);
if (capacity < 0) capacity = janet_tablen(count + 1);
size_t size = sizeof(JanetStructHead) + (size_t) capacity * sizeof(JanetKV);
JanetStructHead *head = janet_gcalloc(JANET_MEMORY_STRUCT, size);
head->length = count;
head->capacity = capacity;
head->hash = 0;
head->proto = NULL;
JanetKV *st = (JanetKV *)(head->data);
janet_memempty(st, capacity);
return st;
}
/* Find an item in a struct without looking for prototypes. Should be similar to janet_dict_find, but
* specialized to structs (slightly more compact). */
const JanetKV *janet_struct_find(const JanetKV *st, Janet key) {
int32_t cap = janet_struct_capacity(st);
int32_t index = janet_maphash(cap, janet_hash(key));
int32_t i;
for (i = index; i < cap; i++)
if (janet_checktype(st[i].key, JANET_NIL) || janet_equals(st[i].key, key))
return st + i;
for (i = 0; i < index; i++)
if (janet_checktype(st[i].key, JANET_NIL) || janet_equals(st[i].key, key))
return st + i;
return NULL;
}
/* Put a kv pair into a struct that has not yet been fully constructed.
* Nil keys and values are ignored, extra keys are ignore, and duplicate keys are
* ignored.
*
* Runs will be in sorted order, as the collisions resolver essentially
* preforms an in-place insertion sort. This ensures the internal structure of the
* hash map is independent of insertion order.
*/
void janet_struct_put_ext(JanetKV *st, Janet key, Janet value, int replace) {
int32_t cap = janet_struct_capacity(st);
int32_t hash = janet_hash(key);
int32_t index = janet_maphash(cap, hash);
int32_t i, j, dist;
int32_t bounds[4] = {index, cap, 0, index};
if (janet_checktype(key, JANET_NIL) || janet_checktype(value, JANET_NIL)) return;
if (janet_checktype(key, JANET_NUMBER) && isnan(janet_unwrap_number(key))) return;
/* Avoid extra items */
if (janet_struct_hash(st) == janet_struct_length(st)) return;
for (dist = 0, j = 0; j < 4; j += 2)
for (i = bounds[j]; i < bounds[j + 1]; i++, dist++) {
int status;
int32_t otherhash;
int32_t otherindex, otherdist;
JanetKV *kv = st + i;
/* We found an empty slot, so just add key and value */
if (janet_checktype(kv->key, JANET_NIL)) {
kv->key = key;
kv->value = value;
/* Update the temporary count */
janet_struct_hash(st)++;
return;
}
/* Robinhood hashing - check if colliding kv pair
* is closer to their source than current. We use robinhood
* hashing to ensure that equivalent structs that are constructed
* with different order have the same internal layout, and therefor
* will compare properly - i.e., {1 2 3 4} should equal {3 4 1 2}.
* Collisions are resolved via an insertion sort insertion. */
otherhash = janet_hash(kv->key);
otherindex = janet_maphash(cap, otherhash);
otherdist = (i + cap - otherindex) & (cap - 1);
if (dist < otherdist)
status = -1;
else if (otherdist < dist)
status = 1;
else if (hash < otherhash)
status = -1;
else if (otherhash < hash)
status = 1;
else
status = janet_compare(key, kv->key);
/* If other is closer to their ideal slot */
if (status == 1) {
/* Swap current kv pair with pair in slot */
JanetKV temp = *kv;
kv->key = key;
kv->value = value;
key = temp.key;
value = temp.value;
/* Save dist and hash of new kv pair */
dist = otherdist;
hash = otherhash;
} else if (status == 0) {
if (replace) {
/* A key was added to the struct more than once - replace old value */
kv->value = value;
}
return;
}
}
}
void janet_struct_put(JanetKV *st, Janet key, Janet value) {
janet_struct_put_ext(st, key, value, 1);
}
/* Finish building a struct */
const JanetKV *janet_struct_end(JanetKV *st) {
if (janet_struct_hash(st) != janet_struct_length(st)) {
/* Error building struct, probably duplicate values. We need to rebuild
* the struct using only the values that went in. The second creation should always
* succeed. */
JanetKV *newst = janet_struct_begin(janet_struct_hash(st));
for (int32_t i = 0; i < janet_struct_capacity(st); i++) {
JanetKV *kv = st + i;
if (!janet_checktype(kv->key, JANET_NIL)) {
janet_struct_put(newst, kv->key, kv->value);
}
}
janet_struct_proto(newst) = janet_struct_proto(st);
st = newst;
}
janet_struct_hash(st) = janet_kv_calchash(st, janet_struct_capacity(st));
if (janet_struct_proto(st)) {
janet_struct_hash(st) += 2654435761u * janet_struct_hash(janet_struct_proto(st));
}
return (const JanetKV *)st;
}
/* Get an item from a struct without looking into prototypes. */
Janet janet_struct_rawget(const JanetKV *st, Janet key) {
const JanetKV *kv = janet_struct_find(st, key);
return kv ? kv->value : janet_wrap_nil();
}
/* Get an item from a struct */
Janet janet_struct_get(const JanetKV *st, Janet key) {
for (int i = JANET_MAX_PROTO_DEPTH; st && i; --i, st = janet_struct_proto(st)) {
const JanetKV *kv = janet_struct_find(st, key);
if (NULL != kv && !janet_checktype(kv->key, JANET_NIL)) {
return kv->value;
}
}
return janet_wrap_nil();
}
/* Get an item from a struct, and record which prototype the item came from. */
Janet janet_struct_get_ex(const JanetKV *st, Janet key, JanetStruct *which) {
for (int i = JANET_MAX_PROTO_DEPTH; st && i; --i, st = janet_struct_proto(st)) {
const JanetKV *kv = janet_struct_find(st, key);
if (NULL != kv && !janet_checktype(kv->key, JANET_NIL)) {
*which = st;
return kv->value;
}
}
return janet_wrap_nil();
}
/* Convert struct to table */
JanetTable *janet_struct_to_table(const JanetKV *st) {
JanetTable *table = janet_table(janet_struct_capacity(st));
int32_t i;
for (i = 0; i < janet_struct_capacity(st); i++) {
const JanetKV *kv = st + i;
if (!janet_checktype(kv->key, JANET_NIL)) {
janet_table_put(table, kv->key, kv->value);
}
}
return table;
}
/* C Functions */
JANET_CORE_FN(cfun_struct_with_proto,
"(struct/with-proto proto & kvs)",
"Create a structure, as with the usual struct constructor but set the "
"struct prototype as well.") {
janet_arity(argc, 1, -1);
JanetStruct proto = janet_optstruct(argv, argc, 0, NULL);
if (!(argc & 1))
janet_panic("expected odd number of arguments");
JanetKV *st = janet_struct_begin(argc / 2);
for (int32_t i = 1; i < argc; i += 2) {
janet_struct_put(st, argv[i], argv[i + 1]);
}
janet_struct_proto(st) = proto;
return janet_wrap_struct(janet_struct_end(st));
}
JANET_CORE_FN(cfun_struct_getproto,
"(struct/getproto st)",
"Return the prototype of a struct, or nil if it doesn't have one.") {
janet_fixarity(argc, 1);
JanetStruct st = janet_getstruct(argv, 0);
return janet_struct_proto(st)
? janet_wrap_struct(janet_struct_proto(st))
: janet_wrap_nil();
}
JANET_CORE_FN(cfun_struct_flatten,
"(struct/proto-flatten st)",
"Convert a struct with prototypes to a struct with no prototypes by merging "
"all key value pairs from recursive prototypes into one new struct.") {
janet_fixarity(argc, 1);
JanetStruct st = janet_getstruct(argv, 0);
/* get an upper bounds on the number of items in the final struct */
int64_t pair_count = 0;
JanetStruct cursor = st;
while (cursor) {
pair_count += janet_struct_length(cursor);
cursor = janet_struct_proto(cursor);
}
if (pair_count > INT32_MAX) {
janet_panic("struct too large");
}
JanetKV *accum = janet_struct_begin((int32_t) pair_count);
cursor = st;
while (cursor) {
for (int32_t i = 0; i < janet_struct_capacity(cursor); i++) {
const JanetKV *kv = cursor + i;
if (!janet_checktype(kv->key, JANET_NIL)) {
janet_struct_put_ext(accum, kv->key, kv->value, 0);
}
}
cursor = janet_struct_proto(cursor);
}
return janet_wrap_struct(janet_struct_end(accum));
}
JANET_CORE_FN(cfun_struct_to_table,
"(struct/to-table st &opt recursive)",
"Convert a struct to a table. If recursive is true, also convert the "
"table's prototypes into the new struct's prototypes as well.") {
janet_arity(argc, 1, 2);
JanetStruct st = janet_getstruct(argv, 0);
int recursive = argc > 1 && janet_truthy(argv[1]);
JanetTable *tab = NULL;
JanetStruct cursor = st;
JanetTable *tab_cursor = tab;
do {
if (tab) {
tab_cursor->proto = janet_table(janet_struct_length(cursor));
tab_cursor = tab_cursor->proto;
} else {
tab = janet_table(janet_struct_length(cursor));
tab_cursor = tab;
}
/* TODO - implement as memcpy since struct memory should be compatible
* with table memory */
for (int32_t i = 0; i < janet_struct_capacity(cursor); i++) {
const JanetKV *kv = cursor + i;
if (!janet_checktype(kv->key, JANET_NIL)) {
janet_table_put(tab_cursor, kv->key, kv->value);
}
}
cursor = janet_struct_proto(cursor);
} while (recursive && cursor);
return janet_wrap_table(tab);
}
/* Load the struct module */
void janet_lib_struct(JanetTable *env) {
JanetRegExt struct_cfuns[] = {
JANET_CORE_REG("struct/with-proto", cfun_struct_with_proto),
JANET_CORE_REG("struct/getproto", cfun_struct_getproto),
JANET_CORE_REG("struct/proto-flatten", cfun_struct_flatten),
JANET_CORE_REG("struct/to-table", cfun_struct_to_table),
JANET_REG_END
};
janet_core_cfuns_ext(env, NULL, struct_cfuns);
}
|
16900.c | /*
VTun - Virtual Tunnel over TCP/IP network.
Copyright (C) 1998-2008 Maxim Krasnyansky <[email protected]>
VTun has been derived from VPPP package by Maxim Krasnyansky.
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.
*/
/*
* $Id: client.c,v 1.11.2.3 2012/07/08 05:32:57 mtbishop Exp $
*/
#include "config.h"
#include "vtun_socks.h"
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include <fcntl.h>
#include <syslog.h>
#ifdef HAVE_NETINET_IN_H
#include <netinet/in.h>
#endif
#ifdef HAVE_ARPA_INET_H
#include <arpa/inet.h>
#endif
#include "vtun.h"
#include "lib.h"
#include "llist.h"
#include "auth.h"
#include "compat.h"
#include "netlib.h"
static volatile sig_atomic_t client_term;
static void sig_term(int sig)
{
vtun_syslog(LOG_INFO,"Terminated");
client_term = VTUN_SIG_TERM;
}
void client(struct vtun_host *host)
{
struct sockaddr_in my_addr,svr_addr;
struct sigaction sa;
int s, opt, reconnect;
vtun_syslog(LOG_INFO,"VTun client ver %s started",VTUN_VER);
memset(&sa,0,sizeof(sa));
sa.sa_handler=SIG_IGN;
sa.sa_flags = SA_NOCLDWAIT;
sigaction(SIGHUP,&sa,NULL);
sigaction(SIGQUIT,&sa,NULL);
sigaction(SIGPIPE,&sa,NULL);
sigaction(SIGCHLD,&sa,NULL);
sa.sa_handler=sig_term;
sigaction(SIGTERM,&sa,NULL);
sigaction(SIGINT,&sa,NULL);
client_term = 0; reconnect = 0;
while( (!client_term) || (client_term == VTUN_SIG_HUP) ){
if( reconnect && (client_term != VTUN_SIG_HUP) ){
if( vtun.persist || host->persist ){
/* Persist mode. Sleep and reconnect. */
sleep(5);
} else {
/* Exit */
break;
}
} else {
reconnect = 1;
}
set_title("%s init initializing", host->host);
/* Set server address */
if( server_addr(&svr_addr, host) < 0 )
continue;
/* Set local address */
if( local_addr(&my_addr, host, 0) < 0 )
continue;
/* We have to create socket again every time
* we want to connect, since STREAM sockets
* can be successfully connected only once.
*/
if( (s = socket(AF_INET,SOCK_STREAM,0))==-1 ){
vtun_syslog(LOG_ERR,"Can't create socket. %s(%d)",
strerror(errno), errno);
continue;
}
/* Required when client is forced to bind to specific port */
opt=1;
setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
if( bind(s,(struct sockaddr *)&my_addr,sizeof(my_addr)) ){
vtun_syslog(LOG_ERR,"Can't bind socket. %s(%d)",
strerror(errno), errno);
continue;
}
/*
* Clear speed and flags which will be supplied by server.
*/
host->spd_in = host->spd_out = 0;
host->flags &= VTUN_CLNT_MASK;
io_init();
set_title("%s connecting to %s", host->host, vtun.svr_name);
if (!vtun.quiet)
vtun_syslog(LOG_INFO,"Connecting to %s", vtun.svr_name);
if( connect_t(s,(struct sockaddr *) &svr_addr, host->timeout) ){
if (!vtun.quiet || errno != ETIMEDOUT)
vtun_syslog(LOG_INFO,"Connect to %s failed. %s(%d)", vtun.svr_name,
strerror(errno), errno);
} else {
if( auth_client(s, host) ){
vtun_syslog(LOG_INFO,"Session %s[%s] opened",host->host,vtun.svr_name);
host->rmt_fd = s;
/* Start the tunnel */
client_term = tunnel(host);
vtun_syslog(LOG_INFO,"Session %s[%s] closed",host->host,vtun.svr_name);
} else {
vtun_syslog(LOG_INFO,"Connection denied by %s",vtun.svr_name);
}
}
close(s);
free_sopt(&host->sopt);
}
vtun_syslog(LOG_INFO, "Exit");
return;
}
|
561970.c | /*
* ALSA driver for Echoaudio soundcards.
* Copyright (C) 2009 Giuliano Pochini <[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; version 2 of the License.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
#define INDIGO_FAMILY
#define ECHOCARD_INDIGO_DJX
#define ECHOCARD_NAME "Indigo DJx"
#define ECHOCARD_HAS_SUPER_INTERLEAVE
#define ECHOCARD_HAS_VMIXER
#define ECHOCARD_HAS_STEREO_BIG_ENDIAN32
/* Pipe indexes */
#define PX_ANALOG_OUT 0 /* 8 */
#define PX_DIGITAL_OUT 8 /* 0 */
#define PX_ANALOG_IN 8 /* 0 */
#define PX_DIGITAL_IN 8 /* 0 */
#define PX_NUM 8
/* Bus indexes */
#define BX_ANALOG_OUT 0 /* 4 */
#define BX_DIGITAL_OUT 4 /* 0 */
#define BX_ANALOG_IN 4 /* 0 */
#define BX_DIGITAL_IN 4 /* 0 */
#define BX_NUM 4
#include <linux/delay.h>
#include <linux/init.h>
#include <linux/interrupt.h>
#include <linux/pci.h>
#include <linux/module.h>
#include <linux/firmware.h>
#include <linux/io.h>
#include <linux/slab.h>
#include <sound/core.h>
#include <sound/info.h>
#include <sound/control.h>
#include <sound/tlv.h>
#include <sound/pcm.h>
#include <sound/pcm_params.h>
#include <sound/asoundef.h>
#include <sound/initval.h>
#include <linux/atomic.h>
#include "echoaudio.h"
MODULE_FIRMWARE("ea/loader_dsp.fw");
MODULE_FIRMWARE("ea/indigo_djx_dsp.fw");
#define FW_361_LOADER 0
#define FW_INDIGO_DJX_DSP 1
static const struct firmware card_fw[] = {
{0, "loader_dsp.fw"},
{0, "indigo_djx_dsp.fw"}
};
static DEFINE_PCI_DEVICE_TABLE(snd_echo_ids) = {
{0x1057, 0x3410, 0xECC0, 0x00E0, 0, 0, 0}, /* Indigo DJx*/
{0,}
};
static struct snd_pcm_hardware pcm_hardware_skel = {
.info = SNDRV_PCM_INFO_MMAP |
SNDRV_PCM_INFO_INTERLEAVED |
SNDRV_PCM_INFO_BLOCK_TRANSFER |
SNDRV_PCM_INFO_MMAP_VALID |
SNDRV_PCM_INFO_PAUSE |
SNDRV_PCM_INFO_SYNC_START,
.formats = SNDRV_PCM_FMTBIT_U8 |
SNDRV_PCM_FMTBIT_S16_LE |
SNDRV_PCM_FMTBIT_S24_3LE |
SNDRV_PCM_FMTBIT_S32_LE |
SNDRV_PCM_FMTBIT_S32_BE,
.rates = SNDRV_PCM_RATE_32000 |
SNDRV_PCM_RATE_44100 |
SNDRV_PCM_RATE_48000 |
SNDRV_PCM_RATE_64000 |
SNDRV_PCM_RATE_88200 |
SNDRV_PCM_RATE_96000,
.rate_min = 32000,
.rate_max = 96000,
.channels_min = 1,
.channels_max = 4,
.buffer_bytes_max = 262144,
.period_bytes_min = 32,
.period_bytes_max = 131072,
.periods_min = 2,
.periods_max = 220,
};
#include "indigodjx_dsp.c"
#include "indigo_express_dsp.c"
#include "echoaudio_dsp.c"
#include "echoaudio.c"
|
189796.c | /* boxmuller.c Implements the Polar form of the Box-Muller
Transformation
(c) Copyright 1994, Everett F. Carter Jr.
Permission is granted by the author to use
this software for any application provided this
copyright notice is preserved.
*/
#include <math.h>
#include <stdlib.h>
double box_muller(double m, double s) /* normal random variate generator */
{ /* mean m, standard deviation s */
double x1, x2, w, y1;
static double y2;
static int use_last = 0;
if (use_last) /* use value from previous call */
{
y1 = y2;
use_last = 0;
}
else
{
do {
x1 = 2.0 * rand()/RAND_MAX - 1.0;
x2 = 2.0 * rand()/RAND_MAX - 1.0;
w = x1 * x1 + x2 * x2;
} while ( w >= 1.0 );
w = sqrt( (-2.0 * log( w ) ) / w );
y1 = x1 * w;
y2 = x2 * w;
use_last = 1;
}
return( m + y1 * s );
}
|
427401.c | #include "stats.h"
#include "hydromath.h"
#include <stdio.h>
int main(void)
{
double data[8] = {2, 4, 4, 4, 5, 5, 7, 9};
double x = sum(data, 8);
printf("%f\n", x);
double m = mean(data, 8);
printf("%f\n", m);
double v = variance_mean(data, m, 8);
printf("%f\n", v);
double sd = standard_dev_mean(data, m, 8);
printf("%f\n", sd);
double obs[5] = {13,17,18,20,24};
double sim[5] = {12,15,20,22,24};
double mean_square_error = mse_c(obs, sim, 5);
printf("%f\n", mean_square_error);
double pobs[5] = {1,2,3,4,5};
double psim[5] = {1,2,3,4,5};
double ns = nse_c(pobs, psim, 5);
printf("%f\n", ns);
double kge = kge_c(obs, sim, 5);
printf("KGE: %f\n", kge);
kge = kge_c(pobs, psim, 5);
printf("Perfect KGE: %f\n", kge);
double cv = covariance(obs, sim, 5);
printf("Covariance: %f\n", cv);
cv = covariance(pobs, psim, 5);
printf("Covariance: %f\n", cv);
double h_data[5] = {-3,-2,-1,1,2};
double out_data[6] = {0,0,0,0,0,0};
heaviside(h_data, out_data, 6);
int i;
for (i = 0; i < 5; i++) {
printf("Heaviside %d: %f\n", i, out_data[i]);
}
return 0;
}
|
101892.c | /* File:
* omp_mat_vect_rand_split.c
*
* Purpose:
* Computes a parallel matrix-vector product. Matrix
* is distributed by block rows. Vectors are distributed by
* blocks. This version uses a random number generator to
* generate A and x. There is some optimization.
*
* Compile:
* gcc -g -Wall -fopenmp -o omp_mat_vect_rand_split
* omp_mat_vect_rand_split.c
* Run:
* ./omp_mat_vect_rand_split <thread_count> <m> <n>
*
* Input:
* None unless compiled with DEBUG flag.
* With DEBUG flag, A, x
*
* Output:
* y: the product vector
* Elapsed time for the computation
*
* Notes:
* 1. Storage for A, x, y is dynamically allocated.
* 2. Number of threads (thread_count) should evenly divide both
* m and n. The program doesn't check for this.
* 3. We use a 1-dimensional array for A and compute subscripts
* using the formula A[i][j] = A[i*n + j]
* 4. Distribution of A, x, and y is logical: all three are
* globally shared.
* 5. DEBUG compile flag will prompt for input of A, x, and
* print y
*
* IPP: Exercise 5.12
*/
#include <stdio.h>
#include <stdlib.h>
#include <omp.h>
#include "timer.h"
/* Serial functions */
void Get_args(int argc, char* argv[], int* thread_count_p,
int* m_p, int* n_p);
void Usage(char* prog_name);
void Gen_matrix(double A[], int m, int n);
void Read_matrix(char* prompt, double A[], int m, int n);
void Gen_vector(double x[], int n);
void Read_vector(char* prompt, double x[], int n);
void Print_matrix(char* title, double A[], int m, int n);
void Print_vector(char* title, double y[], double m);
/* Parallel function */
void Omp_mat_vect(double A[], double x[], double y[],
int m, int n, int thread_count);
/*------------------------------------------------------------------*/
int main(int argc, char* argv[]) {
int thread_count;
int m, n;
double* A;
double* x;
double* y;
Get_args(argc, argv, &thread_count, &m, &n);
A = malloc(m*n*sizeof(double));
x = malloc(n*sizeof(double));
y = malloc(m*sizeof(double));
# ifdef DEBUG
Read_matrix("Enter the matrix", A, m, n);
Print_matrix("We read", A, m, n);
Read_vector("Enter the vector", x, n);
Print_vector("We read", x, n);
# else
Gen_matrix(A, m, n);
/* Print_matrix("We generated", A, m, n); */
Gen_vector(x, n);
/* Print_vector("We generated", x, n); */
# endif
Omp_mat_vect(A, x, y, m, n, thread_count);
# ifdef DEBUG
Print_vector("The product is", y, m);
# else
/* Print_vector("The product is", y, m); */
# endif
free(A);
free(x);
free(y);
return 0;
} /* main */
/*------------------------------------------------------------------
* Function: Get_args
* Purpose: Get command line args
* In args: argc, argv
* Out args: thread_count_p, m_p, n_p
*/
void Get_args(int argc, char* argv[], int* thread_count_p,
int* m_p, int* n_p) {
if (argc != 4) Usage(argv[0]);
*thread_count_p = strtol(argv[1], NULL, 10);
*m_p = strtol(argv[2], NULL, 10);
*n_p = strtol(argv[3], NULL, 10);
if (*thread_count_p <= 0 || *m_p <= 0 || *n_p <= 0) Usage(argv[0]);
} /* Get_args */
/*------------------------------------------------------------------
* Function: Usage
* Purpose: print a message showing what the command line should
* be, and terminate
* In arg : prog_name
*/
void Usage (char* prog_name) {
fprintf(stderr, "usage: %s <thread_count> <m> <n>\n", prog_name);
exit(0);
} /* Usage */
/*------------------------------------------------------------------
* Function: Read_matrix
* Purpose: Read in the matrix
* In args: prompt, m, n
* Out arg: A
*/
void Read_matrix(char* prompt, double A[], int m, int n) {
int i, j;
printf("%s\n", prompt);
for (i = 0; i < m; i++)
for (j = 0; j < n; j++)
scanf("%lf", &A[i*n+j]);
} /* Read_matrix */
/*------------------------------------------------------------------
* Function: Gen_matrix
* Purpose: Use the random number generator random to generate
* the entries in A
* In args: m, n
* Out arg: A
*/
void Gen_matrix(double A[], int m, int n) {
int i, j;
for (i = 0; i < m; i++)
for (j = 0; j < n; j++)
A[i*n+j] = random()/((double) RAND_MAX);
} /* Gen_matrix */
/*------------------------------------------------------------------
* Function: Gen_vector
* Purpose: Use the random number generator random to generate
* the entries in x
* In arg: n
* Out arg: A
*/
void Gen_vector(double x[], int n) {
int i;
for (i = 0; i < n; i++)
x[i] = random()/((double) RAND_MAX);
} /* Gen_vector */
/*------------------------------------------------------------------
* Function: Read_vector
* Purpose: Read in the vector x
* In arg: prompt, n
* Out arg: x
*/
void Read_vector(char* prompt, double x[], int n) {
int i;
printf("%s\n", prompt);
for (i = 0; i < n; i++)
scanf("%lf", &x[i]);
} /* Read_vector */
/*------------------------------------------------------------------
* Function: Omp_mat_vect
* Purpose: Multiply an mxn matrix by an nx1 column vector
* In args: A, x, m, n, thread_count
* Out arg: y
*/
void Omp_mat_vect(double A[], double x[], double y[],
int m, int n, int thread_count) {
int i, j;
double start, finish, elapsed, temp;
GET_TIME(start);
# pragma omp parallel for num_threads(thread_count) \
default(none) private(i, j, temp) shared(A, x, y, m, n)
for (i = 0; i < m; i++) {
y[i] = 0.0;
for (j = 0; j < n; j++) {
temp = A[i*n+j]*x[j];
y[i] += temp;
}
}
GET_TIME(finish);
elapsed = finish - start;
printf("Elapsed time = %e seconds\n", elapsed);
} /* Omp_mat_vect */
/*------------------------------------------------------------------
* Function: Print_matrix
* Purpose: Print the matrix
* In args: title, A, m, n
*/
void Print_matrix( char* title, double A[], int m, int n) {
int i, j;
printf("%s\n", title);
for (i = 0; i < m; i++) {
for (j = 0; j < n; j++)
printf("%4.1f ", A[i*n + j]);
printf("\n");
}
} /* Print_matrix */
/*------------------------------------------------------------------
* Function: Print_vector
* Purpose: Print a vector
* In args: title, y, m
*/
void Print_vector(char* title, double y[], double m) {
int i;
printf("%s\n", title);
for (i = 0; i < m; i++)
printf("%4.1f ", y[i]);
printf("\n");
} /* Print_vector */
|
400347.c | /**
AsmWriteCr3 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"
UINTN
EFIAPI
AsmWriteCr3 (
UINTN Value
)
{
_asm {
mov eax, Value
mov cr3, eax
}
}
|
640115.c | /* $OpenBSD: screen.c,v 1.17 2016/06/10 15:37:09 tb Exp $ */
/* $NetBSD: screen.c,v 1.4 1995/04/29 01:11:36 mycroft Exp $ */
/*-
* Copyright (c) 1992, 1993
* The Regents of the University of California. All rights reserved.
*
* This code is derived from software contributed to Berkeley by
* Chris Torek and Darren F. Provine.
*
* 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.
*
* @(#)screen.c 8.1 (Berkeley) 5/31/93
*/
/*
* Tetris screen control.
*/
#include <sys/ioctl.h>
#include <err.h>
#include <setjmp.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <term.h>
#include <unistd.h>
#include "screen.h"
#include "tetris.h"
static cell curscreen[B_SIZE]; /* 1 => standout (or otherwise marked) */
static int curscore;
static int isset; /* true => terminal is in game mode */
static struct termios oldtt;
static void (*tstp)(int);
static void scr_stop(int);
static void stopset(int);
/*
* Capabilities from TERMCAP.
*/
char PC, *BC, *UP; /* tgoto requires globals: ugh! */
static char
*bcstr, /* backspace char */
*CEstr, /* clear to end of line */
*CLstr, /* clear screen */
*CMstr, /* cursor motion string */
#ifdef unneeded
*CRstr, /* "\r" equivalent */
#endif
*HOstr, /* cursor home */
*LLstr, /* last line, first column */
*pcstr, /* pad character */
*TEstr, /* end cursor motion mode */
*TIstr, /* begin cursor motion mode */
*VIstr, /* make cursor invisible */
*VEstr; /* make cursor appear normal */
char
*SEstr, /* end standout mode */
*SOstr; /* begin standout mode */
static int
COnum, /* co# value */
LInum, /* li# value */
MSflag; /* can move in standout mode */
struct tcsinfo { /* termcap string info; some abbrevs above */
char tcname[3];
char **tcaddr;
} tcstrings[] = {
{"bc", &bcstr},
{"ce", &CEstr},
{"cl", &CLstr},
{"cm", &CMstr},
#ifdef unneeded
{"cr", &CRstr},
#endif
{"le", &BC}, /* move cursor left one space */
{"pc", &pcstr},
{"se", &SEstr},
{"so", &SOstr},
{"te", &TEstr},
{"ti", &TIstr},
{"vi", &VIstr},
{"ve", &VEstr},
{"up", &UP}, /* cursor up */
{ {0}, NULL}
};
/* This is where we will actually stuff the information */
static char combuf[1024], tbuf[1024];
/*
* Routine used by tputs().
*/
int
put(int c)
{
return (putchar(c));
}
/*
* putstr() is for unpadded strings (either as in termcap(5) or
* simply literal strings); putpad() is for padded strings with
* count=1. (See screen.h for putpad().)
*/
#define putstr(s) (void)fputs(s, stdout)
#define moveto(r, c) putpad(tgoto(CMstr, c, r))
/*
* Set up from termcap.
*/
void
scr_init(void)
{
static int bsflag, xsflag, sgnum;
#ifdef unneeded
static int ncflag;
#endif
char *term, *fill;
static struct tcninfo { /* termcap numeric and flag info */
char tcname[3];
int *tcaddr;
} tcflags[] = {
{"bs", &bsflag},
{"ms", &MSflag},
#ifdef unneeded
{"nc", &ncflag},
#endif
{"xs", &xsflag},
{ {0}, NULL}
}, tcnums[] = {
{"co", &COnum},
{"li", &LInum},
{"sg", &sgnum},
{ {0}, NULL}
};
if ((term = getenv("TERM")) == NULL)
stop("you must set the TERM environment variable");
if (tgetent(tbuf, term) <= 0)
stop("cannot find your termcap");
fill = combuf;
{
struct tcsinfo *p;
for (p = tcstrings; p->tcaddr; p++)
*p->tcaddr = tgetstr(p->tcname, &fill);
}
if (classic)
SOstr = SEstr = NULL;
{
struct tcninfo *p;
for (p = tcflags; p->tcaddr; p++)
*p->tcaddr = tgetflag(p->tcname);
for (p = tcnums; p->tcaddr; p++)
*p->tcaddr = tgetnum(p->tcname);
}
if (bsflag)
BC = "\b";
else if (BC == NULL && bcstr != NULL)
BC = bcstr;
if (CLstr == NULL)
stop("cannot clear screen");
if (CMstr == NULL || UP == NULL || BC == NULL)
stop("cannot do random cursor positioning via tgoto()");
PC = pcstr ? *pcstr : 0;
if (sgnum > 0 || xsflag)
SOstr = SEstr = NULL;
#ifdef unneeded
if (ncflag)
CRstr = NULL;
else if (CRstr == NULL)
CRstr = "\r";
#endif
}
/* this foolery is needed to modify tty state `atomically' */
static jmp_buf scr_onstop;
static void
stopset(int sig)
{
sigset_t sigset;
(void) signal(sig, SIG_DFL);
(void) kill(getpid(), sig);
sigemptyset(&sigset);
sigaddset(&sigset, sig);
(void) sigprocmask(SIG_UNBLOCK, &sigset, (sigset_t *)0);
longjmp(scr_onstop, 1);
}
static void
scr_stop(int sig)
{
sigset_t sigset;
scr_end();
(void) kill(getpid(), sig);
sigemptyset(&sigset);
sigaddset(&sigset, sig);
(void) sigprocmask(SIG_UNBLOCK, &sigset, (sigset_t *)0);
scr_set();
scr_msg(key_msg, 1);
}
/*
* Set up screen mode.
*/
void
scr_set(void)
{
struct winsize ws;
struct termios newtt;
sigset_t sigset, osigset;
void (*ttou)(int);
sigemptyset(&sigset);
sigaddset(&sigset, SIGTSTP);
sigaddset(&sigset, SIGTTOU);
(void) sigprocmask(SIG_BLOCK, &sigset, &osigset);
if ((tstp = signal(SIGTSTP, stopset)) == SIG_IGN)
(void) signal(SIGTSTP, SIG_IGN);
if ((ttou = signal(SIGTTOU, stopset)) == SIG_IGN)
(void) signal(SIGTTOU, SIG_IGN);
/*
* At last, we are ready to modify the tty state. If
* we stop while at it, stopset() above will longjmp back
* to the setjmp here and we will start over.
*/
(void) setjmp(scr_onstop);
(void) sigprocmask(SIG_SETMASK, &osigset, (sigset_t *)0);
Rows = 0, Cols = 0;
if (ioctl(0, TIOCGWINSZ, &ws) == 0) {
Rows = ws.ws_row;
Cols = ws.ws_col;
}
if (Rows == 0)
Rows = LInum;
if (Cols == 0)
Cols = COnum;
if (Rows < MINROWS || Cols < MINCOLS) {
char smallscr[55];
(void)snprintf(smallscr, sizeof(smallscr),
"the screen is too small (must be at least %dx%d)",
MINROWS, MINCOLS);
stop(smallscr);
}
if (tcgetattr(0, &oldtt) < 0)
stop("tcgetattr() fails");
newtt = oldtt;
newtt.c_lflag &= ~(ICANON|ECHO);
newtt.c_oflag &= ~OXTABS;
if (tcsetattr(0, TCSADRAIN, &newtt) < 0)
stop("tcsetattr() fails");
(void) sigprocmask(SIG_BLOCK, &sigset, &osigset);
/*
* We made it. We are now in screen mode, modulo TIstr
* (which we will fix immediately).
*/
if (TIstr)
putstr(TIstr); /* termcap(5) says this is not padded */
if (VIstr)
putstr(VIstr); /* termcap(5) says this is not padded */
if (tstp != SIG_IGN)
(void) signal(SIGTSTP, scr_stop);
if (ttou != SIG_IGN)
(void) signal(SIGTTOU, ttou);
isset = 1;
(void) sigprocmask(SIG_SETMASK, &osigset, (sigset_t *)0);
scr_clear();
}
/*
* End screen mode.
*/
void
scr_end(void)
{
sigset_t sigset, osigset;
sigemptyset(&sigset);
sigaddset(&sigset, SIGTSTP);
sigaddset(&sigset, SIGTTOU);
(void) sigprocmask(SIG_BLOCK, &sigset, &osigset);
/* move cursor to last line */
if (LLstr)
putstr(LLstr); /* termcap(5) says this is not padded */
else
moveto(Rows - 1, 0);
/* exit screen mode */
if (TEstr)
putstr(TEstr); /* termcap(5) says this is not padded */
if (VEstr)
putstr(VEstr); /* termcap(5) says this is not padded */
(void) fflush(stdout);
(void) tcsetattr(0, TCSADRAIN, &oldtt);
isset = 0;
/* restore signals */
(void) signal(SIGTSTP, tstp);
(void) sigprocmask(SIG_SETMASK, &osigset, (sigset_t *)0);
}
void
stop(char *why)
{
if (isset)
scr_end();
errx(1, "aborting: %s", why);
}
/*
* Clear the screen, forgetting the current contents in the process.
*/
void
scr_clear(void)
{
putpad(CLstr);
curscore = -1;
memset((char *)curscreen, 0, sizeof(curscreen));
}
typedef cell regcell;
/*
* Update the screen.
*/
void
scr_update(void)
{
cell *bp, *sp;
regcell so, cur_so = 0;
int i, ccol, j;
sigset_t sigset, osigset;
static const struct shape *lastshape;
sigemptyset(&sigset);
sigaddset(&sigset, SIGTSTP);
(void) sigprocmask(SIG_BLOCK, &sigset, &osigset);
/* always leave cursor after last displayed point */
curscreen[D_LAST * B_COLS - 1] = -1;
if (score != curscore) {
if (HOstr)
putpad(HOstr);
else
moveto(0, 0);
(void) printf("Score: %d", score);
curscore = score;
}
/* draw preview of next pattern */
if (showpreview && (nextshape != lastshape)) {
static int r=5, c=2;
int tr, tc, t;
lastshape = nextshape;
/* clean */
putpad(SEstr);
moveto(r-1, c-1); putstr(" ");
moveto(r, c-1); putstr(" ");
moveto(r+1, c-1); putstr(" ");
moveto(r+2, c-1); putstr(" ");
moveto(r-3, c-2);
putstr("Next shape:");
/* draw */
if (SOstr)
putpad(SOstr);
moveto(r, 2 * c);
putstr(SOstr ? " " : "[]");
for (i = 0; i < 3; i++) {
t = c + r * B_COLS;
t += nextshape->off[i];
tr = t / B_COLS;
tc = t % B_COLS;
moveto(tr, 2*tc);
putstr(SOstr ? " " : "[]");
}
putpad(SEstr);
}
bp = &board[D_FIRST * B_COLS];
sp = &curscreen[D_FIRST * B_COLS];
for (j = D_FIRST; j < D_LAST; j++) {
ccol = -1;
for (i = 0; i < B_COLS; bp++, sp++, i++) {
if (*sp == (so = *bp))
continue;
*sp = so;
if (i != ccol) {
if (cur_so && MSflag) {
putpad(SEstr);
cur_so = 0;
}
moveto(RTOD(j), CTOD(i));
}
if (SOstr) {
if (so != cur_so) {
putpad(so ? SOstr : SEstr);
cur_so = so;
}
putstr(" ");
} else
putstr(so ? "[]" : " ");
ccol = i + 1;
/*
* Look ahead a bit, to avoid extra motion if
* we will be redrawing the cell after the next.
* Motion probably takes four or more characters,
* so we save even if we rewrite two cells
* `unnecessarily'. Skip it all, though, if
* the next cell is a different color.
*/
#define STOP (B_COLS - 3)
if (i > STOP || sp[1] != bp[1] || so != bp[1])
continue;
if (sp[2] != bp[2])
sp[1] = -1;
else if (i < STOP && so == bp[2] && sp[3] != bp[3]) {
sp[2] = -1;
sp[1] = -1;
}
}
}
if (cur_so)
putpad(SEstr);
(void) fflush(stdout);
(void) sigprocmask(SIG_SETMASK, &osigset, (sigset_t *)0);
}
/*
* Write a message (set!=0), or clear the same message (set==0).
* (We need its length in case we have to overwrite with blanks.)
*/
void
scr_msg(char *s, int set)
{
if (set || CEstr == NULL) {
int l = strlen(s);
moveto(Rows - 2, ((Cols - l) >> 1) - 1);
if (set)
putstr(s);
else
while (--l >= 0)
(void) putchar(' ');
} else {
moveto(Rows - 2, 0);
putpad(CEstr);
}
}
|
667653.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.
*/
/*
Original code taken from mcuboot project at:
https://github.com/runtimeco/mcuboot
Modifications are Copyright (c) 2018 Arm Limited.
*/
/**
* This file provides an interface to the boot loader. Functions defined in
* this file should only be called while the boot loader is running.
*/
#include <assert.h>
#include <stddef.h>
#include <stdbool.h>
#include <inttypes.h>
#include <stdlib.h>
#include <string.h>
#include "flash_map/flash_map.h"
#include "bootutil/bootutil.h"
#include "bootutil/image.h"
#include "bootutil_priv.h"
#define BOOT_LOG_LEVEL BOOT_LOG_LEVEL_INFO
#include "bootutil/bootutil_log.h"
static struct boot_loader_state boot_data;
struct boot_status_table {
/**
* For each field, a value of 0 means "any".
*/
uint8_t bst_magic_slot0;
uint8_t bst_magic_scratch;
uint8_t bst_copy_done_slot0;
uint8_t bst_status_source;
};
/**
* This set of tables maps swap state contents to boot status location.
* When searching for a match, these tables must be iterated in order.
*/
static const struct boot_status_table boot_status_tables[] = {
{
/* | slot-0 | scratch |
* ----------+------------+------------|
* magic | Good | Any |
* copy-done | 0x01 | N/A |
* ----------+------------+------------'
* source: none |
* ------------------------------------'
*/
.bst_magic_slot0 = BOOT_MAGIC_GOOD,
.bst_magic_scratch = 0,
.bst_copy_done_slot0 = 0x01,
.bst_status_source = BOOT_STATUS_SOURCE_NONE,
},
{
/* | slot-0 | scratch |
* ----------+------------+------------|
* magic | Good | Any |
* copy-done | 0xff | N/A |
* ----------+------------+------------'
* source: slot 0 |
* ------------------------------------'
*/
.bst_magic_slot0 = BOOT_MAGIC_GOOD,
.bst_magic_scratch = 0,
.bst_copy_done_slot0 = 0xff,
.bst_status_source = BOOT_STATUS_SOURCE_SLOT0,
},
{
/* | slot-0 | scratch |
* ----------+------------+------------|
* magic | Any | Good |
* copy-done | Any | N/A |
* ----------+------------+------------'
* source: scratch |
* ------------------------------------'
*/
.bst_magic_slot0 = 0,
.bst_magic_scratch = BOOT_MAGIC_GOOD,
.bst_copy_done_slot0 = 0,
.bst_status_source = BOOT_STATUS_SOURCE_SCRATCH,
},
{
/* | slot-0 | scratch |
* ----------+------------+------------|
* magic | Unset | Any |
* copy-done | 0xff | N/A |
* ----------+------------+------------|
* source: varies |
* ------------------------------------+------------------------------+
* This represents one of two cases: |
* o No swaps ever (no status to read, so no harm in checking). |
* o Mid-revert; status in slot 0. |
* -------------------------------------------------------------------'
*/
.bst_magic_slot0 = BOOT_MAGIC_UNSET,
.bst_magic_scratch = 0,
.bst_copy_done_slot0 = 0xff,
.bst_status_source = BOOT_STATUS_SOURCE_SLOT0,
},
};
#define BOOT_STATUS_TABLES_COUNT \
(sizeof(boot_status_tables) / sizeof(boot_status_tables[0]))
#define BOOT_LOG_SWAP_STATE(area, state) \
BOOT_LOG_INF("%s: magic=%s, copy_done=0x%x, image_ok=0x%x", \
(area), \
((state)->magic == BOOT_MAGIC_GOOD ? "good" : \
(state)->magic == BOOT_MAGIC_UNSET ? "unset" : \
"bad"), \
(state)->copy_done, \
(state)->image_ok)
/**
* Determines where in flash the most recent boot status is stored. The boot
* status is necessary for completing a swap that was interrupted by a boot
* loader reset.
*
* @return BOOT_STATUS_SOURCE_[...] code indicating where
* status should be read from.
*/
static int
boot_status_source(void)
{
const struct boot_status_table *table;
struct boot_swap_state state_scratch;
struct boot_swap_state state_slot0;
int rc;
int i;
uint8_t source;
rc = boot_read_swap_state_by_id(FLASH_AREA_IMAGE_0, &state_slot0);
assert(rc == 0);
rc = boot_read_swap_state_by_id(FLASH_AREA_IMAGE_SCRATCH, &state_scratch);
assert(rc == 0);
BOOT_LOG_SWAP_STATE("Image 0", &state_slot0);
BOOT_LOG_SWAP_STATE("Scratch", &state_scratch);
for (i = 0; i < BOOT_STATUS_TABLES_COUNT; i++) {
table = &boot_status_tables[i];
if ((table->bst_magic_slot0 == 0 ||
table->bst_magic_slot0 == state_slot0.magic) &&
(table->bst_magic_scratch == 0 ||
table->bst_magic_scratch == state_scratch.magic) &&
(table->bst_copy_done_slot0 == 0 ||
table->bst_copy_done_slot0 == state_slot0.copy_done)) {
source = table->bst_status_source;
BOOT_LOG_INF("Boot source: %s",
source == BOOT_STATUS_SOURCE_NONE ? "none" :
source == BOOT_STATUS_SOURCE_SCRATCH ? "scratch" :
source == BOOT_STATUS_SOURCE_SLOT0 ? "slot 0" :
"BUG; can't happen");
return source;
}
}
BOOT_LOG_INF("Boot source: none");
return BOOT_STATUS_SOURCE_NONE;
}
/**
* Calculates the type of swap that just completed.
*
* This is used when a swap is interrupted by an external event. After
* finishing the swap operation determines what the initial request was.
*/
static int
boot_previous_swap_type(void)
{
int post_swap_type;
post_swap_type = boot_swap_type();
switch (post_swap_type) {
case BOOT_SWAP_TYPE_NONE: return BOOT_SWAP_TYPE_PERM;
case BOOT_SWAP_TYPE_REVERT: return BOOT_SWAP_TYPE_TEST;
case BOOT_SWAP_TYPE_PANIC: return BOOT_SWAP_TYPE_PANIC;
}
return BOOT_SWAP_TYPE_FAIL;
}
/*
* Compute the total size of the given image. Includes the size of
* the TLVs.
*/
#ifndef MCUBOOT_OVERWRITE_ONLY
static int
boot_read_image_size(int slot, struct image_header *hdr, uint32_t *size)
{
const struct flash_area *fap = NULL;
struct image_tlv_info info;
int area_id;
int rc;
area_id = flash_area_id_from_image_slot(slot);
rc = flash_area_open(area_id, &fap);
if (rc != 0) {
rc = BOOT_EFLASH;
goto done;
}
rc = flash_area_read(fap, hdr->ih_hdr_size + hdr->ih_img_size,
&info, sizeof(info));
if (rc != 0) {
rc = BOOT_EFLASH;
goto done;
}
if (info.it_magic != IMAGE_TLV_INFO_MAGIC) {
rc = BOOT_EBADIMAGE;
goto done;
}
*size = hdr->ih_hdr_size + hdr->ih_img_size + info.it_tlv_tot;
rc = 0;
done:
flash_area_close(fap);
return rc;
}
#endif /* !MCUBOOT_OVERWRITE_ONLY */
static int
boot_read_image_header(int slot, struct image_header *out_hdr)
{
const struct flash_area *fap = NULL;
int area_id;
int rc;
area_id = flash_area_id_from_image_slot(slot);
rc = flash_area_open(area_id, &fap);
if (rc != 0) {
rc = BOOT_EFLASH;
goto done;
}
rc = flash_area_read(fap, 0, out_hdr, sizeof(*out_hdr));
if (rc != 0) {
rc = BOOT_EFLASH;
goto done;
}
rc = 0;
done:
flash_area_close(fap);
return rc;
}
static int
boot_read_image_headers(void)
{
int rc;
int i;
for (i = 0; i < BOOT_NUM_SLOTS; i++) {
rc = boot_read_image_header(i, boot_img_hdr(&boot_data, i));
if (rc != 0) {
/* If at least the first slot's header was read successfully, then
* the boot loader can attempt a boot. Failure to read any headers
* is a fatal error.
*/
if (i > 0) {
return 0;
} else {
return rc;
}
}
}
return 0;
}
static uint8_t
boot_write_sz(void)
{
const struct flash_area *fap;
uint8_t elem_sz;
uint8_t align;
int rc;
/* Figure out what size to write update status update as. The size depends
* on what the minimum write size is for scratch area, active image slot.
* We need to use the bigger of those 2 values.
*/
rc = flash_area_open(FLASH_AREA_IMAGE_0, &fap);
assert(rc == 0);
elem_sz = flash_area_align(fap);
flash_area_close(fap);
rc = flash_area_open(FLASH_AREA_IMAGE_SCRATCH, &fap);
assert(rc == 0);
align = flash_area_align(fap);
flash_area_close(fap);
if (align > elem_sz) {
elem_sz = align;
}
return elem_sz;
}
static int
boot_slots_compatible(void)
{
size_t num_sectors_0 = boot_img_num_sectors(&boot_data, 0);
size_t num_sectors_1 = boot_img_num_sectors(&boot_data, 1);
size_t size_0, size_1;
size_t i;
/* Ensure both image slots have identical sector layouts. */
if (num_sectors_0 != num_sectors_1) {
return 0;
}
for (i = 0; i < num_sectors_0; i++) {
size_0 = boot_img_sector_size(&boot_data, 0, i);
size_1 = boot_img_sector_size(&boot_data, 1, i);
if (size_0 != size_1) {
return 0;
}
}
return 1;
}
/**
* Determines the sector layout of both image slots and the scratch area.
* This information is necessary for calculating the number of bytes to erase
* and copy during an image swap. The information collected during this
* function is used to populate the boot_data global.
*/
static int
boot_read_sectors(void)
{
int rc;
rc = boot_initialize_area(&boot_data, FLASH_AREA_IMAGE_0);
if (rc != 0) {
return BOOT_EFLASH;
}
rc = boot_initialize_area(&boot_data, FLASH_AREA_IMAGE_1);
if (rc != 0) {
return BOOT_EFLASH;
}
BOOT_WRITE_SZ(&boot_data) = boot_write_sz();
return 0;
}
static uint32_t
boot_status_internal_off(int idx, int state, int elem_sz)
{
int idx_sz;
idx_sz = elem_sz * BOOT_STATUS_STATE_COUNT;
return idx * idx_sz + state * elem_sz;
}
/**
* Reads the status of a partially-completed swap, if any. This is necessary
* to recover in case the boot lodaer was reset in the middle of a swap
* operation.
*/
static int
boot_read_status_bytes(const struct flash_area *fap, struct boot_status *bs)
{
uint32_t off;
uint8_t status;
int max_entries;
int found;
int rc;
int i;
off = boot_status_off(fap);
max_entries = boot_status_entries(fap);
found = 0;
for (i = 0; i < max_entries; i++) {
rc = flash_area_read(fap, off + i * BOOT_WRITE_SZ(&boot_data),
&status, 1);
if (rc != 0) {
return BOOT_EFLASH;
}
if (status == 0xff) {
if (found) {
break;
}
} else if (!found) {
found = 1;
}
}
if (found) {
i--;
bs->idx = i / BOOT_STATUS_STATE_COUNT;
bs->state = i % BOOT_STATUS_STATE_COUNT;
}
return 0;
}
/**
* Reads the boot status from the flash. The boot status contains
* the current state of an interrupted image copy operation. If the boot
* status is not present, or it indicates that previous copy finished,
* there is no operation in progress.
*/
static int
boot_read_status(struct boot_status *bs)
{
const struct flash_area *fap;
int status_loc;
int area_id;
int rc;
memset(bs, 0, sizeof(*bs));
status_loc = boot_status_source();
switch (status_loc) {
case BOOT_STATUS_SOURCE_NONE:
return 0;
case BOOT_STATUS_SOURCE_SCRATCH:
area_id = FLASH_AREA_IMAGE_SCRATCH;
break;
case BOOT_STATUS_SOURCE_SLOT0:
area_id = FLASH_AREA_IMAGE_0;
break;
default:
assert(0);
return BOOT_EBADARGS;
}
rc = flash_area_open(area_id, &fap);
if (rc != 0) {
return BOOT_EFLASH;
}
rc = boot_read_status_bytes(fap, bs);
flash_area_close(fap);
return rc;
}
/**
* Writes the supplied boot status to the flash file system. The boot status
* contains the current state of an in-progress image copy operation.
*
* @param bs The boot status to write.
*
* @return 0 on success; nonzero on failure.
*/
int
boot_write_status(struct boot_status *bs)
{
const struct flash_area *fap = NULL;
uint32_t off;
int area_id;
int rc;
uint8_t buf[BOOT_MAX_ALIGN];
uint8_t align;
/* NOTE: The first sector copied (that is the last sector on slot) contains
* the trailer. Since in the last step SLOT 0 is erased, the first
* two status writes go to the scratch which will be copied to SLOT 0!
*/
if (bs->use_scratch) {
/* Write to scratch. */
area_id = FLASH_AREA_IMAGE_SCRATCH;
} else {
/* Write to slot 0. */
area_id = FLASH_AREA_IMAGE_0;
}
rc = flash_area_open(area_id, &fap);
if (rc != 0) {
rc = BOOT_EFLASH;
goto done;
}
off = boot_status_off(fap) +
boot_status_internal_off(bs->idx, bs->state,
BOOT_WRITE_SZ(&boot_data));
align = flash_area_align(fap);
memset(buf, 0xFF, BOOT_MAX_ALIGN);
buf[0] = bs->state;
rc = flash_area_write(fap, off, buf, align);
if (rc != 0) {
rc = BOOT_EFLASH;
goto done;
}
rc = 0;
done:
flash_area_close(fap);
return rc;
}
/*
* Validate image hash/signature in a slot.
*/
static int
boot_image_check(struct image_header *hdr, const struct flash_area *fap)
{
static uint8_t tmpbuf[BOOT_TMPBUF_SZ];
if (bootutil_img_validate(hdr, fap, tmpbuf, BOOT_TMPBUF_SZ,
NULL, 0, NULL)) {
return BOOT_EBADIMAGE;
}
return 0;
}
static int
boot_validate_slot(int slot)
{
const struct flash_area *fap;
struct image_header *hdr;
int rc;
hdr = boot_img_hdr(&boot_data, slot);
if (hdr->ih_magic == 0xffffffff || hdr->ih_flags & IMAGE_F_NON_BOOTABLE) {
/* No bootable image in slot; continue booting from slot 0. */
return -1;
}
rc = flash_area_open(flash_area_id_from_image_slot(slot), &fap);
if (rc != 0) {
return BOOT_EFLASH;
}
if ((hdr->ih_magic != IMAGE_MAGIC || boot_image_check(hdr, fap) != 0)) {
if (slot != 0) {
flash_area_erase(fap, 0, fap->fa_size);
/* Image in slot 1 is invalid. Erase the image and
* continue booting from slot 0.
*/
}
BOOT_LOG_ERR("Image in slot %d is not valid!", slot);
return -1;
}
flash_area_close(fap);
/* Image in slot 1 is valid. */
return 0;
}
/**
* Determines which swap operation to perform, if any. If it is determined
* that a swap operation is required, the image in the second slot is checked
* for validity. If the image in the second slot is invalid, it is erased, and
* a swap type of "none" is indicated.
*
* @return The type of swap to perform (BOOT_SWAP_TYPE...)
*/
static int
boot_validated_swap_type(void)
{
int swap_type;
swap_type = boot_swap_type();
switch (swap_type) {
case BOOT_SWAP_TYPE_TEST:
case BOOT_SWAP_TYPE_PERM:
case BOOT_SWAP_TYPE_REVERT:
/* Boot loader wants to switch to slot 1. Ensure image is valid. */
if (boot_validate_slot(1) != 0) {
swap_type = BOOT_SWAP_TYPE_FAIL;
}
}
return swap_type;
}
/**
* Calculates the number of sectors the scratch area can contain. A "last"
* source sector is specified because images are copied backwards in flash
* (final index to index number 0).
*
* @param last_sector_idx The index of the last source sector
* (inclusive).
* @param out_first_sector_idx The index of the first source sector
* (inclusive) gets written here.
*
* @return The number of bytes comprised by the
* [first-sector, last-sector] range.
*/
#ifndef MCUBOOT_OVERWRITE_ONLY
static uint32_t
boot_copy_sz(int last_sector_idx, int *out_first_sector_idx)
{
size_t scratch_sz;
uint32_t new_sz;
uint32_t sz;
int i;
sz = 0;
scratch_sz = boot_scratch_area_size(&boot_data);
for (i = last_sector_idx; i >= 0; i--) {
new_sz = sz + boot_img_sector_size(&boot_data, 0, i);
if (new_sz > scratch_sz) {
break;
}
sz = new_sz;
}
/* i currently refers to a sector that doesn't fit or it is -1 because all
* sectors have been processed. In both cases, exclude sector i.
*/
*out_first_sector_idx = i + 1;
return sz;
}
#endif /* !MCUBOOT_OVERWRITE_ONLY */
/**
* Erases a region of flash.
*
* @param flash_area_id The ID of the flash area containing the region
* to erase.
* @param off The offset within the flash area to start the
* erase.
* @param sz The number of bytes to erase.
*
* @return 0 on success; nonzero on failure.
*/
static int
boot_erase_sector(int flash_area_id, uint32_t off, uint32_t sz)
{
const struct flash_area *fap = NULL;
int rc;
rc = flash_area_open(flash_area_id, &fap);
if (rc != 0) {
rc = BOOT_EFLASH;
goto done;
}
rc = flash_area_erase(fap, off, sz);
if (rc != 0) {
rc = BOOT_EFLASH;
goto done;
}
rc = 0;
done:
flash_area_close(fap);
return rc;
}
/**
* Copies the contents of one flash region to another. You must erase the
* destination region prior to calling this function.
*
* @param flash_area_id_src The ID of the source flash area.
* @param flash_area_id_dst The ID of the destination flash area.
* @param off_src The offset within the source flash area to
* copy from.
* @param off_dst The offset within the destination flash area to
* copy to.
* @param sz The number of bytes to copy.
*
* @return 0 on success; nonzero on failure.
*/
static int
boot_copy_sector(int flash_area_id_src, int flash_area_id_dst,
uint32_t off_src, uint32_t off_dst, uint32_t sz)
{
const struct flash_area *fap_src;
const struct flash_area *fap_dst;
uint32_t bytes_copied;
int chunk_sz;
int rc;
static uint8_t buf[1024];
fap_src = NULL;
fap_dst = NULL;
rc = flash_area_open(flash_area_id_src, &fap_src);
if (rc != 0) {
rc = BOOT_EFLASH;
goto done;
}
rc = flash_area_open(flash_area_id_dst, &fap_dst);
if (rc != 0) {
rc = BOOT_EFLASH;
goto done;
}
bytes_copied = 0;
while (bytes_copied < sz) {
if (sz - bytes_copied > sizeof(buf)) {
chunk_sz = sizeof(buf);
} else {
chunk_sz = sz - bytes_copied;
}
rc = flash_area_read(fap_src, off_src + bytes_copied, buf, chunk_sz);
if (rc != 0) {
rc = BOOT_EFLASH;
goto done;
}
rc = flash_area_write(fap_dst, off_dst + bytes_copied, buf, chunk_sz);
if (rc != 0) {
rc = BOOT_EFLASH;
goto done;
}
bytes_copied += chunk_sz;
}
rc = 0;
done:
if (fap_src) {
flash_area_close(fap_src);
}
if (fap_dst) {
flash_area_close(fap_dst);
}
return rc;
}
#ifndef MCUBOOT_OVERWRITE_ONLY
static inline int
boot_status_init_by_id(int flash_area_id, const struct boot_status *bs)
{
const struct flash_area *fap;
struct boot_swap_state swap_state;
int rc;
rc = flash_area_open(flash_area_id, &fap);
assert(rc == 0);
rc = boot_read_swap_state_by_id(FLASH_AREA_IMAGE_1, &swap_state);
assert(rc == 0);
if (swap_state.image_ok == BOOT_FLAG_SET) {
rc = boot_write_image_ok(fap);
assert(rc == 0);
}
rc = boot_write_swap_size(fap, bs->swap_size);
assert(rc == 0);
rc = boot_write_magic(fap);
assert(rc == 0);
flash_area_close(fap);
return 0;
}
#endif
#ifndef MCUBOOT_OVERWRITE_ONLY
static int
boot_erase_last_sector_by_id(int flash_area_id)
{
uint8_t slot;
uint32_t last_sector;
int rc;
switch (flash_area_id) {
case FLASH_AREA_IMAGE_0:
slot = 0;
break;
case FLASH_AREA_IMAGE_1:
slot = 1;
break;
default:
return BOOT_EFLASH;
}
last_sector = boot_img_num_sectors(&boot_data, slot) - 1;
rc = boot_erase_sector(flash_area_id,
boot_img_sector_off(&boot_data, slot, last_sector),
boot_img_sector_size(&boot_data, slot, last_sector));
assert(rc == 0);
return rc;
}
#endif /* !MCUBOOT_OVERWRITE_ONLY */
/**
* Swaps the contents of two flash regions within the two image slots.
*
* @param idx The index of the first sector in the range of
* sectors being swapped.
* @param sz The number of bytes to swap.
* @param bs The current boot status. This struct gets
* updated according to the outcome.
*
* @return 0 on success; nonzero on failure.
*/
#ifndef MCUBOOT_OVERWRITE_ONLY
static void
boot_swap_sectors(int idx, uint32_t sz, struct boot_status *bs)
{
const struct flash_area *fap;
uint32_t copy_sz;
uint32_t trailer_sz;
uint32_t img_off;
uint32_t scratch_trailer_off;
struct boot_swap_state swap_state;
size_t last_sector;
int rc;
/* Calculate offset from start of image area. */
img_off = boot_img_sector_off(&boot_data, 0, idx);
copy_sz = sz;
trailer_sz = boot_slots_trailer_sz(BOOT_WRITE_SZ(&boot_data));
/* sz in this function is always is always sized on a multiple of the
* sector size. The check against the start offset of the last sector
* is to determine if we're swapping the last sector. The last sector
* needs special handling because it's where the trailer lives. If we're
* copying it, we need to use scratch to write the trailer temporarily.
*
* NOTE: `use_scratch` is a temporary flag (never written to flash) which
* controls if special handling is needed (swapping last sector).
*/
last_sector = boot_img_num_sectors(&boot_data, 0) - 1;
if (img_off + sz > boot_img_sector_off(&boot_data, 0, last_sector)) {
copy_sz -= trailer_sz;
}
bs->use_scratch = (bs->idx == 0 && copy_sz != sz);
if (bs->state == 0) {
rc = boot_erase_sector(FLASH_AREA_IMAGE_SCRATCH, 0, sz);
assert(rc == 0);
rc = boot_copy_sector(FLASH_AREA_IMAGE_1, FLASH_AREA_IMAGE_SCRATCH,
img_off, 0, copy_sz);
assert(rc == 0);
if (bs->idx == 0) {
if (bs->use_scratch) {
boot_status_init_by_id(FLASH_AREA_IMAGE_SCRATCH, bs);
} else {
/* Prepare the status area... here it is known that the
* last sector is not being used by the image data so it's
* safe to erase.
*/
rc = boot_erase_last_sector_by_id(FLASH_AREA_IMAGE_0);
assert(rc == 0);
boot_status_init_by_id(FLASH_AREA_IMAGE_0, bs);
}
}
bs->state = 1;
rc = boot_write_status(bs);
assert(rc == 0);
}
if (bs->state == 1) {
rc = boot_erase_sector(FLASH_AREA_IMAGE_1, img_off, sz);
assert(rc == 0);
rc = boot_copy_sector(FLASH_AREA_IMAGE_0, FLASH_AREA_IMAGE_1,
img_off, img_off, copy_sz);
assert(rc == 0);
if (bs->idx == 0 && !bs->use_scratch) {
/* If not all sectors of the slot are being swapped,
* guarantee here that only slot0 will have the state.
*/
rc = boot_erase_last_sector_by_id(FLASH_AREA_IMAGE_1);
assert(rc == 0);
}
bs->state = 2;
rc = boot_write_status(bs);
assert(rc == 0);
}
if (bs->state == 2) {
rc = boot_erase_sector(FLASH_AREA_IMAGE_0, img_off, sz);
assert(rc == 0);
/* NOTE: also copy trailer from scratch (has status info) */
rc = boot_copy_sector(FLASH_AREA_IMAGE_SCRATCH, FLASH_AREA_IMAGE_0,
0, img_off, copy_sz);
assert(rc == 0);
if (bs->use_scratch) {
rc = flash_area_open(FLASH_AREA_IMAGE_SCRATCH, &fap);
assert(rc == 0);
scratch_trailer_off = boot_status_off(fap);
flash_area_close(fap);
rc = flash_area_open(FLASH_AREA_IMAGE_0, &fap);
assert(rc == 0);
/* copy current status that is being maintained in scratch */
rc = boot_copy_sector(FLASH_AREA_IMAGE_SCRATCH, FLASH_AREA_IMAGE_0,
scratch_trailer_off,
img_off + copy_sz,
BOOT_STATUS_STATE_COUNT * BOOT_WRITE_SZ(&boot_data));
assert(rc == 0);
rc = boot_read_swap_state_by_id(FLASH_AREA_IMAGE_SCRATCH,
&swap_state);
assert(rc == 0);
if (swap_state.image_ok == BOOT_FLAG_SET) {
rc = boot_write_image_ok(fap);
assert(rc == 0);
}
rc = boot_write_swap_size(fap, bs->swap_size);
assert(rc == 0);
rc = boot_write_magic(fap);
assert(rc == 0);
flash_area_close(fap);
}
bs->idx++;
bs->state = 0;
bs->use_scratch = 0;
rc = boot_write_status(bs);
assert(rc == 0);
}
}
#endif /* !MCUBOOT_OVERWRITE_ONLY */
/**
* Swaps the two images in flash. If a prior copy operation was interrupted
* by a system reset, this function completes that operation.
*
* @param bs The current boot status. This function reads
* this struct to determine if it is resuming
* an interrupted swap operation. This
* function writes the updated status to this
* function on return.
*
* @return 0 on success; nonzero on failure.
*/
#ifdef MCUBOOT_OVERWRITE_ONLY
static int
boot_copy_image(struct boot_status *bs)
{
size_t sect_count;
size_t sect;
int rc;
size_t size = 0;
size_t this_size;
BOOT_LOG_INF("Image upgrade slot1 -> slot0");
BOOT_LOG_INF("Erasing slot0");
sect_count = boot_img_num_sectors(&boot_data, 0);
for (sect = 0; sect < sect_count; sect++) {
this_size = boot_img_sector_size(&boot_data, 0, sect);
rc = boot_erase_sector(FLASH_AREA_IMAGE_0,
size,
this_size);
assert(rc == 0);
size += this_size;
}
BOOT_LOG_INF("Copying slot 1 to slot 0: 0x%lx bytes", size);
rc = boot_copy_sector(FLASH_AREA_IMAGE_1, FLASH_AREA_IMAGE_0,
0, 0, size);
/* Erase slot 1 so that we don't do the upgrade on every boot.
* TODO: Perhaps verify slot 0's signature again? */
rc = boot_erase_sector(FLASH_AREA_IMAGE_1,
0, boot_img_sector_size(&boot_data, 1, 0));
assert(rc == 0);
return 0;
}
#else
static int
boot_copy_image(struct boot_status *bs)
{
uint32_t sz;
int first_sector_idx;
int last_sector_idx;
int swap_idx;
struct image_header *hdr;
uint32_t size;
uint32_t copy_size;
int rc;
/* FIXME: just do this if asked by user? */
size = copy_size = 0;
if (bs->idx == 0 && bs->state == 0) {
/*
* No swap ever happened, so need to find the largest image which
* will be used to determine the amount of sectors to swap.
*/
hdr = boot_img_hdr(&boot_data, 0);
if (hdr->ih_magic == IMAGE_MAGIC) {
rc = boot_read_image_size(0, hdr, ©_size);
assert(rc == 0);
}
hdr = boot_img_hdr(&boot_data, 1);
if (hdr->ih_magic == IMAGE_MAGIC) {
rc = boot_read_image_size(1, hdr, &size);
assert(rc == 0);
}
if (size > copy_size) {
copy_size = size;
}
bs->swap_size = copy_size;
} else {
/*
* If a swap was under way, the swap_size should already be present
* in the trailer...
*/
rc = boot_read_swap_size(&bs->swap_size);
assert(rc == 0);
copy_size = bs->swap_size;
}
size = 0;
last_sector_idx = 0;
while (1) {
size += boot_img_sector_size(&boot_data, 0, last_sector_idx);
if (size >= copy_size) {
break;
}
last_sector_idx++;
}
swap_idx = 0;
while (last_sector_idx >= 0) {
sz = boot_copy_sz(last_sector_idx, &first_sector_idx);
if (swap_idx >= bs->idx) {
boot_swap_sectors(first_sector_idx, sz, bs);
}
last_sector_idx = first_sector_idx - 1;
swap_idx++;
}
return 0;
}
#endif
/**
* Marks the image in slot 0 as fully copied.
*/
#ifndef MCUBOOT_OVERWRITE_ONLY
static int
boot_set_copy_done(void)
{
const struct flash_area *fap;
int rc;
rc = flash_area_open(FLASH_AREA_IMAGE_0, &fap);
if (rc != 0) {
return BOOT_EFLASH;
}
rc = boot_write_copy_done(fap);
flash_area_close(fap);
return rc;
}
#endif /* !MCUBOOT_OVERWRITE_ONLY */
/**
* Marks a reverted image in slot 0 as confirmed. This is necessary to ensure
* the status bytes from the image revert operation don't get processed on a
* subsequent boot.
*
* NOTE: image_ok is tested before writing because if there's a valid permanent
* image installed on slot0 and the new image to be upgrade to has a bad sig,
* image_ok would be overwritten.
*/
#ifndef MCUBOOT_OVERWRITE_ONLY
static int
boot_set_image_ok(void)
{
const struct flash_area *fap;
struct boot_swap_state state;
int rc;
rc = flash_area_open(FLASH_AREA_IMAGE_0, &fap);
if (rc != 0) {
return BOOT_EFLASH;
}
rc = boot_read_swap_state(fap, &state);
if (rc != 0) {
rc = BOOT_EFLASH;
goto out;
}
if (state.image_ok == BOOT_FLAG_UNSET) {
rc = boot_write_image_ok(fap);
}
out:
flash_area_close(fap);
return rc;
}
#endif /* !MCUBOOT_OVERWRITE_ONLY */
/**
* Performs an image swap if one is required.
*
* @param out_swap_type On success, the type of swap performed gets
* written here.
*
* @return 0 on success; nonzero on failure.
*/
static int
boot_swap_if_needed(int *out_swap_type)
{
struct boot_status bs;
int swap_type;
int rc;
/* Determine if we rebooted in the middle of an image swap
* operation.
*/
rc = boot_read_status(&bs);
assert(rc == 0);
if (rc != 0) {
return rc;
}
/* If a partial swap was detected, complete it. */
if (bs.idx != 0 || bs.state != 0) {
rc = boot_copy_image(&bs);
assert(rc == 0);
/* NOTE: here we have finished a swap resume. The initial request
* was either a TEST or PERM swap, which now after the completed
* swap will be determined to be respectively REVERT (was TEST)
* or NONE (was PERM).
*/
/* Extrapolate the type of the partial swap. We need this
* information to know how to mark the swap complete in flash.
*/
swap_type = boot_previous_swap_type();
} else {
swap_type = boot_validated_swap_type();
switch (swap_type) {
case BOOT_SWAP_TYPE_TEST:
case BOOT_SWAP_TYPE_PERM:
case BOOT_SWAP_TYPE_REVERT:
rc = boot_copy_image(&bs);
assert(rc == 0);
break;
}
}
*out_swap_type = swap_type;
return 0;
}
/**
* Prepares the booting process. This function moves images around in flash as
* appropriate, and tells you what address to boot from.
*
* @param rsp On success, indicates how booting should occur.
*
* @return 0 on success; nonzero on failure.
*/
int
boot_go(struct boot_rsp *rsp)
{
int swap_type;
size_t slot;
int rc;
int fa_id;
bool reload_headers = false;
/* The array of slot sectors are defined here (as opposed to file scope) so
* that they don't get allocated for non-boot-loader apps. This is
* necessary because the gcc option "-fdata-sections" doesn't seem to have
* any effect in older gcc versions (e.g., 4.8.4).
*/
static boot_sector_t slot0_sectors[BOOT_MAX_IMG_SECTORS];
static boot_sector_t slot1_sectors[BOOT_MAX_IMG_SECTORS];
boot_data.imgs[0].sectors = slot0_sectors;
boot_data.imgs[1].sectors = slot1_sectors;
/* Open boot_data image areas for the duration of this call. */
for (slot = 0; slot < BOOT_NUM_SLOTS; slot++) {
fa_id = flash_area_id_from_image_slot(slot);
rc = flash_area_open(fa_id, &BOOT_IMG_AREA(&boot_data, slot));
assert(rc == 0);
}
rc = flash_area_open(FLASH_AREA_IMAGE_SCRATCH,
&BOOT_SCRATCH_AREA(&boot_data));
assert(rc == 0);
/* Determine the sector layout of the image slots and scratch area. */
rc = boot_read_sectors();
if (rc != 0) {
goto out;
}
/* Attempt to read an image header from each slot. */
rc = boot_read_image_headers();
if (rc != 0) {
goto out;
}
/* If the image slots aren't compatible, no swap is possible. Just boot
* into slot 0.
*/
if (boot_slots_compatible()) {
rc = boot_swap_if_needed(&swap_type);
assert(rc == 0);
if (rc != 0) {
goto out;
}
/*
* The following states need image_ok be explicitly set after the
* swap was finished to avoid a new revert.
*/
if (swap_type == BOOT_SWAP_TYPE_REVERT ||
swap_type == BOOT_SWAP_TYPE_FAIL) {
#ifndef MCUBOOT_OVERWRITE_ONLY
rc = boot_set_image_ok();
if (rc != 0) {
swap_type = BOOT_SWAP_TYPE_PANIC;
}
#endif /* !MCUBOOT_OVERWRITE_ONLY */
}
} else {
swap_type = BOOT_SWAP_TYPE_NONE;
}
switch (swap_type) {
case BOOT_SWAP_TYPE_NONE:
slot = 0;
break;
case BOOT_SWAP_TYPE_TEST: /* fallthrough */
case BOOT_SWAP_TYPE_PERM: /* fallthrough */
case BOOT_SWAP_TYPE_REVERT:
slot = 1;
reload_headers = true;
#ifndef MCUBOOT_OVERWRITE_ONLY
rc = boot_set_copy_done();
if (rc != 0) {
swap_type = BOOT_SWAP_TYPE_PANIC;
}
#endif /* !MCUBOOT_OVERWRITE_ONLY */
break;
case BOOT_SWAP_TYPE_FAIL:
/* The image in slot 1 was invalid and is now erased. Ensure we don't
* try to boot into it again on the next reboot. Do this by pretending
* we just reverted back to slot 0.
*/
slot = 0;
reload_headers = true;
break;
default:
swap_type = BOOT_SWAP_TYPE_PANIC;
}
if (swap_type == BOOT_SWAP_TYPE_PANIC) {
BOOT_LOG_ERR("panic!");
assert(0);
/* Loop forever... */
while (1)
;
}
#ifdef MCUBOOT_VALIDATE_SLOT0
if (reload_headers) {
rc = boot_read_image_headers();
if (rc != 0) {
goto out;
}
/* Since headers were reloaded, it can be assumed we just performed a
* swap or overwrite. Now the header info that should be used to
* provide the data for the bootstrap, which previously was at Slot 1,
* was updated to Slot 0.
*/
slot = 0;
}
rc = boot_validate_slot(0);
if (rc != 0) {
rc = BOOT_EBADIMAGE;
goto out;
}
#else
(void)reload_headers;
#endif
/* Always boot from the primary slot. */
rsp->br_flash_dev_id = boot_img_fa_device_id(&boot_data, 0);
rsp->br_image_off = boot_img_slot_off(&boot_data, 0);
rsp->br_hdr = boot_img_hdr(&boot_data, slot);
out:
flash_area_close(BOOT_SCRATCH_AREA(&boot_data));
for (slot = 0; slot < BOOT_NUM_SLOTS; slot++) {
flash_area_close(BOOT_IMG_AREA(&boot_data, BOOT_NUM_SLOTS - 1 - slot));
}
return rc;
}
|
168158.c | /* --COPYRIGHT--,BSD
* Copyright (c) 2017, Texas Instruments Incorporated
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of Texas Instruments Incorporated nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
* OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
* EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
* --/COPYRIGHT--*/
//******************************************************************************
//!
//! RTC in Counter Mode toggles LED1 every 1s
//!
//! This program demonstrates RTC in counter mode configured to source from SMCLK
//! to toggle LED1 every 1s.
//! SMCLK = REFO = ~32kHz
//!
//! MSP430FR2xx_4xx Board
//! -----------------
//! /|\ | |
//! | | |
//! ---|RST |
//! | |
//! | |-->LED1
//!
//!
//! This example uses the following peripherals and I/O signals. You must
//! review these and change as needed for your own board:
//! - RTC peripheral
//! - GPIO Port peripheral
//!
//! This example uses the following interrupt handlers. To use this example
//! in your own application you must add these interrupt handlers to your
//! vector table.
//! - RTC_VECTOR
//!
//******************************************************************************
#include "driverlib.h"
#include "Board.h"
//*****************************************************************************
//
//Interval time used for RTC
//
//*****************************************************************************
#define INTERVAL_TIME 32768
void main (void)
{
WDT_A_hold(WDT_A_BASE);
//Set LED1 to output direction
GPIO_setAsOutputPin(
GPIO_PORT_LED1,
GPIO_PIN_LED1
);
/*
* Disable the GPIO power-on default high-impedance mode to activate
* previously configured port settings
*/
PMM_unlockLPM5();
//Set DCO FLL reference = REFO
CS_initClockSignal(
CS_FLLREF,
CS_REFOCLK_SELECT,
CS_CLOCK_DIVIDER_1
);
//Set SMCLK = REFO
CS_initClockSignal(
CS_SMCLK,
CS_REFOCLK_SELECT,
CS_CLOCK_DIVIDER_1
);
//Initialize RTC
RTC_init(RTC_BASE,
INTERVAL_TIME,
RTC_CLOCKPREDIVIDER_1);
RTC_clearInterrupt(RTC_BASE,
RTC_OVERFLOW_INTERRUPT_FLAG);
//Enable interrupt for RTC overflow
RTC_enableInterrupt(RTC_BASE,
RTC_OVERFLOW_INTERRUPT);
//Start RTC Clock with clock source SMCLK
RTC_start(RTC_BASE, RTC_CLOCKSOURCE_SMCLK);
//Enter LPM3 mode with interrupts enabled
__bis_SR_register(LPM0_bits + GIE);
__no_operation();
}
#if defined(__TI_COMPILER_VERSION__) || defined(__IAR_SYSTEMS_ICC__)
#pragma vector=RTC_VECTOR
__interrupt
#elif defined(__GNUC__)
__attribute__((interrupt(RTC_VECTOR)))
#endif
void RTC_ISR (void)
{
switch (__even_in_range(RTCIV,2)){
case 0: break; //No interrupts
case 2: //RTC overflow
//Toggle LED1
GPIO_toggleOutputOnPin(
GPIO_PORT_LED1,
GPIO_PIN_LED1);
break;
default: break;
}
}
|
749160.c | /* $NetBSD: longjmp.c,v 1.6 2016/01/24 16:01:43 christos Exp $ */
/*-
* Copyright (c) 2003 The NetBSD Foundation, Inc.
* All rights reserved.
*
* This code is derived from software contributed to The NetBSD Foundation
* by Christian Limpach and Matt Thomas.
*
* 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 <ucontext.h>
#include <signal.h>
#include <stdlib.h>
#include <string.h>
#include <setjmp.h>
#include <machine/regnum.h>
void longjmp(jmp_buf env, int val) {
struct sigcontext *sc = (void *)env;
ucontext_t uc;
/* Ensure non-zero SP and sigcontext magic number is present */
if (sc->sc_regs[_R_SP] == 0 ||
sc->sc_regs[_R_ZERO] != (register_t)0xACEDBADEU)
goto err;
/* Ensure non-zero return value */
if (val == 0)
val = 1;
/*
* Set _UC_{SET,CLR}STACK according to SS_ONSTACK.
*
* Restore the signal mask with sigprocmask() instead of _UC_SIGMASK,
* since libpthread may want to interpose on signal handling.
*/
uc.uc_flags = _UC_CPU | (sc->sc_onstack ? _UC_SETSTACK : _UC_CLRSTACK);
sigprocmask(SIG_SETMASK, &sc->sc_mask, NULL);
/* Clear uc_link */
uc.uc_link = 0;
/* Save return value in context */
uc.uc_mcontext.__gregs[_REG_V0] = val;
/* Copy saved registers */
uc.uc_mcontext.__gregs[_REG_S0] = sc->sc_regs[_R_S0];
uc.uc_mcontext.__gregs[_REG_S1] = sc->sc_regs[_R_S1];
uc.uc_mcontext.__gregs[_REG_S2] = sc->sc_regs[_R_S2];
uc.uc_mcontext.__gregs[_REG_S3] = sc->sc_regs[_R_S3];
uc.uc_mcontext.__gregs[_REG_S4] = sc->sc_regs[_R_S4];
uc.uc_mcontext.__gregs[_REG_S5] = sc->sc_regs[_R_S5];
uc.uc_mcontext.__gregs[_REG_S6] = sc->sc_regs[_R_S6];
uc.uc_mcontext.__gregs[_REG_S7] = sc->sc_regs[_R_S7];
uc.uc_mcontext.__gregs[_REG_S8] = sc->sc_regs[_R_S8];
#if !defined(__mips_abicalls)
uc.uc_mcontext.__gregs[_REG_GP] = sc->sc_regs[_R_GP];
#endif
uc.uc_mcontext.__gregs[_REG_SP] = sc->sc_regs[_R_SP];
uc.uc_mcontext.__gregs[_REG_RA] = sc->sc_regs[_R_RA];
uc.uc_mcontext.__gregs[_REG_EPC] = sc->sc_pc;
/* Copy FP state */
if (sc->sc_fpused) {
/* FP saved regs are $f20 .. $f31 */
memcpy(&uc.uc_mcontext.__fpregs.__fp_r.__fp_regs[20], &sc->sc_fpregs[20],
32 - 20);
uc.uc_mcontext.__fpregs.__fp_csr = sc->sc_fpregs[_R_FSR - _FPBASE];
/* XXX sc_fp_control */
uc.uc_flags |= _UC_FPU;
}
setcontext(&uc);
err:
longjmperror();
abort();
/* NOTREACHED */
}
|
59404.c | /* OpenCL runtime library: clReleaseCommandQueue()
Copyright (c) 2011-2012 Universidad Rey Juan Carlos and Pekka Jääskeläinen
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 "pocl_cl.h"
#include "pocl_util.h"
CL_API_ENTRY cl_int CL_API_CALL
POname(clReleaseCommandQueue)(cl_command_queue command_queue) CL_API_SUFFIX__VERSION_1_0
{
POCL_RETURN_ERROR_COND ((!IS_CL_OBJECT_VALID (command_queue)),
CL_INVALID_COMMAND_QUEUE);
int new_refcount;
cl_context context = command_queue->context;
cl_device_id device = command_queue->device;
POname(clFlush)(command_queue);
POCL_RELEASE_OBJECT(command_queue, new_refcount);
POCL_MSG_PRINT_REFCOUNTS ("Release Command Queue %p %d\n", command_queue, new_refcount);
if (new_refcount == 0)
{
VG_REFC_ZERO (command_queue);
TP_FREE_QUEUE (context->id, command_queue->id);
assert (command_queue->command_count == 0);
POCL_MSG_PRINT_REFCOUNTS ("Free Command Queue %p\n", command_queue);
if (command_queue->device->ops->free_queue)
command_queue->device->ops->free_queue (device, command_queue);
POCL_DESTROY_OBJECT (command_queue);
POCL_MEM_FREE(command_queue);
POname(clReleaseContext) (context);
}
else
{
VG_REFC_NONZERO (command_queue);
}
return CL_SUCCESS;
}
POsym(clReleaseCommandQueue)
|
509332.c | /* ../netlib/v3.9.0/csysv_rk.f -- translated by f2c (version 20160102). You must link the resulting object file with libf2c: on Microsoft Windows system, link with libf2c.lib;
on Linux or Unix systems, link with .../path/to/libf2c.a -lm or, if you install libf2c.a in a standard place, with -lf2c -lm -- in that order, at the end of the command line, as in cc *.o -lf2c -lm Source for libf2c is in /netlib/f2c/libf2c.zip, e.g., http://www.netlib.org/f2c/libf2c.zip */
#include "FLA_f2c.h" /* Table of constant values */
static integer c_n1 = -1;
/* > \brief <b> CSYSV_RK computes the solution to system of linear equations A * X = B for SY matrices</b> */
/* =========== DOCUMENTATION =========== */
/* Online html documentation available at */
/* http://www.netlib.org/lapack/explore-html/ */
/* > \htmlonly */
/* > Download CSYSV_RK + dependencies */
/* > <a href="http://www.netlib.org/cgi-bin/netlibfiles.tgz?format=tgz&filename=/lapack/lapack_routine/csysv_r k.f"> */
/* > [TGZ]</a> */
/* > <a href="http://www.netlib.org/cgi-bin/netlibfiles.zip?format=zip&filename=/lapack/lapack_routine/csysv_r k.f"> */
/* > [ZIP]</a> */
/* > <a href="http://www.netlib.org/cgi-bin/netlibfiles.txt?format=txt&filename=/lapack/lapack_routine/csysv_r k.f"> */
/* > [TXT]</a> */
/* > \endhtmlonly */
/* Definition: */
/* =========== */
/* SUBROUTINE CSYSV_RK( UPLO, N, NRHS, A, LDA, E, IPIV, B, LDB, */
/* WORK, LWORK, INFO ) */
/* .. Scalar Arguments .. */
/* CHARACTER UPLO */
/* INTEGER INFO, LDA, LDB, LWORK, N, NRHS */
/* .. */
/* .. Array Arguments .. */
/* INTEGER IPIV( * ) */
/* COMPLEX A( LDA, * ), B( LDB, * ), E( * ), WORK( * ) */
/* .. */
/* > \par Purpose: */
/* ============= */
/* > */
/* > \verbatim */
/* > CSYSV_RK computes the solution to a complex system of linear */
/* > equations A * X = B, where A is an N-by-N symmetric matrix */
/* > and X and B are N-by-NRHS matrices. */
/* > */
/* > The bounded Bunch-Kaufman (rook) diagonal pivoting method is used */
/* > to factor A as */
/* > A = P*U*D*(U**T)*(P**T), if UPLO = 'U', or */
/* > A = P*L*D*(L**T)*(P**T), if UPLO = 'L', */
/* > where U (or L) is unit upper (or lower) triangular matrix, */
/* > U**T (or L**T) is the transpose of U (or L), P is a permutation */
/* > matrix, P**T is the transpose of P, and D is symmetric and block */
/* > diagonal with 1-by-1 and 2-by-2 diagonal blocks. */
/* > */
/* > CSYTRF_RK is called to compute the factorization of a complex */
/* > symmetric matrix. The factored form of A is then used to solve */
/* > the system of equations A * X = B by calling BLAS3 routine CSYTRS_3. */
/* > \endverbatim */
/* Arguments: */
/* ========== */
/* > \param[in] UPLO */
/* > \verbatim */
/* > UPLO is CHARACTER*1 */
/* > Specifies whether the upper or lower triangular part of the */
/* > symmetric matrix A is stored: */
/* > = 'U': Upper triangle of A is stored;
*/
/* > = 'L': Lower triangle of A is stored. */
/* > \endverbatim */
/* > */
/* > \param[in] N */
/* > \verbatim */
/* > N is INTEGER */
/* > The number of linear equations, i.e., the order of the */
/* > matrix A. N >= 0. */
/* > \endverbatim */
/* > */
/* > \param[in] NRHS */
/* > \verbatim */
/* > NRHS is INTEGER */
/* > The number of right hand sides, i.e., the number of columns */
/* > of the matrix B. NRHS >= 0. */
/* > \endverbatim */
/* > */
/* > \param[in,out] A */
/* > \verbatim */
/* > A is COMPLEX array, dimension (LDA,N) */
/* > On entry, the symmetric matrix A. */
/* > If UPLO = 'U': the leading N-by-N upper triangular part */
/* > of A contains the upper triangular part of the matrix A, */
/* > and the strictly lower triangular part of A is not */
/* > referenced. */
/* > */
/* > If UPLO = 'L': the leading N-by-N lower triangular part */
/* > of A contains the lower triangular part of the matrix A, */
/* > and the strictly upper triangular part of A is not */
/* > referenced. */
/* > */
/* > On exit, if INFO = 0, diagonal of the block diagonal */
/* > matrix D and factors U or L as computed by CSYTRF_RK: */
/* > a) ONLY diagonal elements of the symmetric block diagonal */
/* > matrix D on the diagonal of A, i.e. D(k,k) = A(k,k);
*/
/* > (superdiagonal (or subdiagonal) elements of D */
/* > are stored on exit in array E), and */
/* > b) If UPLO = 'U': factor U in the superdiagonal part of A. */
/* > If UPLO = 'L': factor L in the subdiagonal part of A. */
/* > */
/* > For more info see the description of CSYTRF_RK routine. */
/* > \endverbatim */
/* > */
/* > \param[in] LDA */
/* > \verbatim */
/* > LDA is INTEGER */
/* > The leading dimension of the array A. LDA >= max(1,N). */
/* > \endverbatim */
/* > */
/* > \param[out] E */
/* > \verbatim */
/* > E is COMPLEX array, dimension (N) */
/* > On exit, contains the output computed by the factorization */
/* > routine CSYTRF_RK, i.e. the superdiagonal (or subdiagonal) */
/* > elements of the symmetric block diagonal matrix D */
/* > with 1-by-1 or 2-by-2 diagonal blocks, where */
/* > If UPLO = 'U': E(i) = D(i-1,i), i=2:N, E(1) is set to 0;
*/
/* > If UPLO = 'L': E(i) = D(i+1,i), i=1:N-1, E(N) is set to 0. */
/* > */
/* > NOTE: For 1-by-1 diagonal block D(k), where */
/* > 1 <= k <= N, the element E(k) is set to 0 in both */
/* > UPLO = 'U' or UPLO = 'L' cases. */
/* > */
/* > For more info see the description of CSYTRF_RK routine. */
/* > \endverbatim */
/* > */
/* > \param[out] IPIV */
/* > \verbatim */
/* > IPIV is INTEGER array, dimension (N) */
/* > Details of the interchanges and the block structure of D, */
/* > as determined by CSYTRF_RK. */
/* > */
/* > For more info see the description of CSYTRF_RK routine. */
/* > \endverbatim */
/* > */
/* > \param[in,out] B */
/* > \verbatim */
/* > B is COMPLEX array, dimension (LDB,NRHS) */
/* > On entry, the N-by-NRHS right hand side matrix B. */
/* > On exit, if INFO = 0, the N-by-NRHS solution matrix X. */
/* > \endverbatim */
/* > */
/* > \param[in] LDB */
/* > \verbatim */
/* > LDB is INTEGER */
/* > The leading dimension of the array B. LDB >= max(1,N). */
/* > \endverbatim */
/* > */
/* > \param[out] WORK */
/* > \verbatim */
/* > WORK is COMPLEX array, dimension ( MAX(1,LWORK) ). */
/* > Work array used in the factorization stage. */
/* > On exit, if INFO = 0, WORK(1) returns the optimal LWORK. */
/* > \endverbatim */
/* > */
/* > \param[in] LWORK */
/* > \verbatim */
/* > LWORK is INTEGER */
/* > The length of WORK. LWORK >= 1. For best performance */
/* > of factorization stage LWORK >= max(1,N*NB), where NB is */
/* > the optimal blocksize for CSYTRF_RK. */
/* > */
/* > If LWORK = -1, then a workspace query is assumed;
*/
/* > the routine only calculates the optimal size of the WORK */
/* > array for factorization stage, returns this value as */
/* > the first entry of the WORK array, and no error message */
/* > related to LWORK is issued by XERBLA. */
/* > \endverbatim */
/* > */
/* > \param[out] INFO */
/* > \verbatim */
/* > INFO is INTEGER */
/* > = 0: successful exit */
/* > */
/* > < 0: If INFO = -k, the k-th argument had an illegal value */
/* > */
/* > > 0: If INFO = k, the matrix A is singular, because: */
/* > If UPLO = 'U': column k in the upper */
/* > triangular part of A contains all zeros. */
/* > If UPLO = 'L': column k in the lower */
/* > triangular part of A contains all zeros. */
/* > */
/* > Therefore D(k,k) is exactly zero, and superdiagonal */
/* > elements of column k of U (or subdiagonal elements of */
/* > column k of L ) are all zeros. The factorization has */
/* > been completed, but the block diagonal matrix D is */
/* > exactly singular, and division by zero will occur if */
/* > it is used to solve a system of equations. */
/* > */
/* > NOTE: INFO only stores the first occurrence of */
/* > a singularity, any subsequent occurrence of singularity */
/* > is not stored in INFO even though the factorization */
/* > always completes. */
/* > \endverbatim */
/* Authors: */
/* ======== */
/* > \author Univ. of Tennessee */
/* > \author Univ. of California Berkeley */
/* > \author Univ. of Colorado Denver */
/* > \author NAG Ltd. */
/* > \date December 2016 */
/* > \ingroup complexSYsolve */
/* > \par Contributors: */
/* ================== */
/* > */
/* > \verbatim */
/* > */
/* > December 2016, Igor Kozachenko, */
/* > Computer Science Division, */
/* > University of California, Berkeley */
/* > */
/* > September 2007, Sven Hammarling, Nicholas J. Higham, Craig Lucas, */
/* > School of Mathematics, */
/* > University of Manchester */
/* > */
/* > \endverbatim */
/* ===================================================================== */
/* Subroutine */
int csysv_rk_(char *uplo, integer *n, integer *nrhs, complex *a, integer *lda, complex *e, integer *ipiv, complex *b, integer *ldb, complex *work, integer *lwork, integer *info) {
AOCL_DTL_TRACE_ENTRY(AOCL_DTL_LEVEL_TRACE_5);
#if AOCL_DTL_LOG_ENABLE
char buffer[256];
#if FLA_ENABLE_ILP64
snprintf(buffer, 256,"csysv_rk inputs: uplo %c, n %lld, nrhs %lld, lda %lld, ldb %lld, lwork %lld",*uplo, *n, *nrhs, *lda, *ldb, *lwork);
#else
snprintf(buffer, 256,"csysv_rk inputs: uplo %c, n %d, nrhs %d, lda %d, ldb %d, lwork %d",*uplo, *n, *nrhs, *lda, *ldb, *lwork);
#endif
AOCL_DTL_LOG(AOCL_DTL_LEVEL_TRACE_5, buffer);
#endif
/* System generated locals */
integer a_dim1, a_offset, b_dim1, b_offset, i__1;
/* Local variables */
extern /* Subroutine */
int csytrs_3_(char *, integer *, integer *, complex *, integer *, complex *, integer *, complex *, integer *, integer *), csytrf_rk_(char *, integer *, complex *, integer *, complex *, integer *, complex *, integer *, integer *);
extern logical lsame_(char *, char *);
extern /* Subroutine */
int xerbla_(char *, integer *);
integer lwkopt;
logical lquery;
/* -- LAPACK driver routine (version 3.7.0) -- */
/* -- LAPACK is a software package provided by Univ. of Tennessee, -- */
/* -- Univ. of California Berkeley, Univ. of Colorado Denver and NAG Ltd..-- */
/* December 2016 */
/* .. Scalar Arguments .. */
/* .. */
/* .. Array Arguments .. */
/* .. */
/* ===================================================================== */
/* .. Local Scalars .. */
/* .. */
/* .. External Functions .. */
/* .. */
/* .. External Subroutines .. */
/* .. */
/* .. Intrinsic Functions .. */
/* .. */
/* .. Executable Statements .. */
/* Test the input parameters. */
/* Parameter adjustments */
a_dim1 = *lda;
a_offset = 1 + a_dim1;
a -= a_offset;
--e;
--ipiv;
b_dim1 = *ldb;
b_offset = 1 + b_dim1;
b -= b_offset;
--work;
/* Function Body */
*info = 0;
lquery = *lwork == -1;
if (! lsame_(uplo, "U") && ! lsame_(uplo, "L")) {
*info = -1;
}
else if (*n < 0) {
*info = -2;
}
else if (*nrhs < 0) {
*info = -3;
}
else if (*lda < max(1,*n)) {
*info = -5;
}
else if (*ldb < max(1,*n)) {
*info = -9;
}
else if (*lwork < 1 && ! lquery) {
*info = -11;
}
if (*info == 0) {
if (*n == 0) {
lwkopt = 1;
}
else {
csytrf_rk_(uplo, n, &a[a_offset], lda, &e[1], &ipiv[1], &work[1], &c_n1, info);
lwkopt = work[1].r;
}
work[1].r = (real) lwkopt; work[1].i = 0.f; // , expr subst
}
if (*info != 0) {
i__1 = -(*info);
xerbla_("CSYSV_RK ", &i__1);
AOCL_DTL_TRACE_EXIT(AOCL_DTL_LEVEL_TRACE_5);
return 0;
}
else if (lquery) {
AOCL_DTL_TRACE_EXIT(AOCL_DTL_LEVEL_TRACE_5);
return 0;
}
/* Compute the factorization A = U*D*U**T or A = L*D*L**T. */
csytrf_rk_(uplo, n, &a[a_offset], lda, &e[1], &ipiv[1], &work[1], lwork, info);
if (*info == 0) {
/* Solve the system A*X = B with BLAS3 solver, overwriting B with X. */
csytrs_3_(uplo, n, nrhs, &a[a_offset], lda, &e[1], &ipiv[1], &b[ b_offset], ldb, info);
}
work[1].r = (real) lwkopt; work[1].i = 0.f; // , expr subst
AOCL_DTL_TRACE_EXIT(AOCL_DTL_LEVEL_TRACE_5);
return 0;
/* End of CSYSV_RK */
}
/* csysv_rk__ */
|
206439.c | // vi:nu:et:sts=4 ts=4 sw=4
/*
* File: scandate.c
* Author: bob
*
* Created on October 25, 2014
*/
/*
This is free and unencumbered software released into the public domain.
Anyone is free to copy, modify, publish, use, compile, sell, or
distribute this software, either in source code form or as a compiled
binary, for any purpose, commercial or non-commercial, and by any
means.
In jurisdictions that recognize copyright laws, the author or authors
of this software dedicate any and all copyright interest in the
software to the public domain. We make this dedication for the benefit
of the public at large and to the detriment of our heirs and
successors. We intend this dedication to be an overt act of
relinquishment in perpetuity of all present and future rights to this
software under copyright law.
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 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.
For more information, please refer to <http://unlicense.org/>
*/
#include <stdbool.h>
#include <stdint.h>
#include "hex.h"
//****************************************************************
//* * * * * * * * * * * * Data Definitions * * * * * * * * * * *
//****************************************************************
/****************************************************************
* * * * * * * * * * * Internal Subroutines * * * * * * * * * *
****************************************************************/
/****************************************************************
* * * * * * * * * * * External Subroutines * * * * * * * * * *
****************************************************************/
//**********************************************************
// S c a n D a t e
//**********************************************************
/* CmdStr is scanned one character at a time into the Output
* buffer supplied. The scan will go until it hits end of line
* the end of the string. It will copy at most maxLen characters
* to the output.
*/
bool scanDate(
char **ppCmdStr, // NUL terminated string pointer
uint32_t *pScannedLen, // (returned) Scanned Length
// (not including leading whitespace)
uint32_t *pValue // (returned) Scanned Number
)
{
bool fRc = false;
char *pCurChr = NULL;
uint32_t cOutput = 0;
//char Quote = 0;
char dd10 = 0;
char dd1 = 0;
char mm10 = 0;
char mm1 = 0;
uint8_t mm = 0;
uint8_t dd = 0;
//uint16_t yyyy = 0;
//uint8_t wday = 0;
//char szDate[11] = "MM/DD/YYYY";
// Do initialization.
if( NULL == ppCmdStr ) {
fRc = false;
goto Exit00;
}
pCurChr = *ppCmdStr;
// Scan off leading white-space.
scanWhite( &pCurChr, NULL );
// Scan the paramter.
if( *pCurChr ) {
// MM
if( ('0' <= *pCurChr) || ('1' >= *pCurChr) ) {
mm10 = *pCurChr;
++pCurChr;
}
else
return false;
if( ('0' <= *pCurChr) || ('1' >= *pCurChr) ) {
mm1 = *pCurChr;
++pCurChr;
}
// DD
if( (*pCurChr >= '0') || (*pCurChr <= '3') ) {
dd10 = *pCurChr;
++pCurChr;
}
else
return false;
if( (*pCurChr >= '0') || ('1' >= *pCurChr) ) {
dd1 = *pCurChr;
++pCurChr;
}
if( ('0' <= *pCurChr) || ('1' >= *pCurChr) ) {
mm = *pCurChr - '0';
++pCurChr;
}
else {
return false;
}
if( ('0' <= *pCurChr) || ('9' >= *pCurChr) ) {
mm *= 10;
mm += *pCurChr - '0';
++pCurChr;
}
else {
return false;
}
if ( !((mm > 0) && (mm < 13)) ) {
return false;
}
if( '/' == *pCurChr ) {
++pCurChr;
}
else {
return false;
}
// DD/
if( ('0' <= *pCurChr) || ('3' >= *pCurChr) ) {
dd += *pCurChr - '0';
++pCurChr;
}
if( ('0' <= *pCurChr) || ('9' >= *pCurChr) ) {
dd *= 10;
dd += *pCurChr - '0';
++pCurChr;
}
}
// Return to caller.
fRc = true;
Exit00:
if( ppCmdStr ) {
*ppCmdStr = pCurChr;
}
if( pScannedLen ) {
*pScannedLen = cOutput;
}
return( fRc );
}
|
679497.c | #include <multiboot.h>
#include <setup.h>
#include <print.h>
#include <serial.h>
#include <text_device.h>
#include <utils.h>
#include <pic.h>
#include <apic.h>
#include <system.h>
#include <fpu.h>
#include <memory.h>
#include <smp.h>
#include <pit.h>
#include <scheduler.h>
#include <renderer.h>
#include <acpi.h>
#include <vbe.h>
#include <render/software.h>
#include <math.h>
#include <render/textures.h>
#define LOAD_TEXTURES
#include "resources/textures.c"
#undef LOAD_TEXTURES
#define LOAD_MODELS
#include "resources/triangles_1.c"
#undef LOAD_MODELS
#include <console.h>
#include <temp.h>
#define SYSBENCH_VERSION "0.1"
#define PRINT_FPS
struct text_device* setup_serial_textdev;
void setup_putchar(char c) {
setup_serial_textdev->putchar(c);
console_putchar(c);
}
char setup_getcolor() { return 0; };
char setup_canprint() { return 1; };
void setup_setcolor(char color) {};
struct text_device setup_textdev;
void __setup_kernel_entry(struct multiboot_info* mbinfo, uint32_t bootloader_return) {
if (bootloader_return != MULTIBOOT_BOOTLOADER_MAGIC) {
stop();
}
setup_textdev.putchar = &setup_putchar;
setup_textdev.setcolor = &setup_setcolor;
setup_textdev.getcolor = &setup_getcolor;
setup_textdev.canprint = &setup_canprint;
// initialize serial and printing
serial_initialize();
setup_serial_textdev = serial_get_text_device();
print_set_output(&setup_textdev);
console_clear_screen();
printf("\n _____ __ __ \n");
printf(" / ___/__ _______/ /_ ___ ____ _____/ /_ \n");
printf(" \\__ \\/ / / / ___/ __ \\/ _ \\/ __ \\/ ___/ __ \\\n");
printf(" ___/ / /_/ (__ ) /_/ / __/ / / / /__/ / / /\n");
printf("/____/\\__, /____/_.___/\\___/_/ /_/\\___/_/ /_/ \n");
printf(" /____/ \n\n");
printf("##############################################\n\n");
printf("[[init]: Starting Sysbench %s\n", SYSBENCH_VERSION);
// enable the FPU and set up SSE
fpu_init();
// initialize memory management
memory_init();
// disable the 8259 PICs
pic_map(32, 40);
pic_disable();
// scan for ACPI tables and parse them
char acpi_supported = acpi_initialize();
// enable the APIC
uint8_t core_id;
if (acpi_supported) {
core_id = apic_enable();
}else{
printf("[[main]: ACPI and APIC are required to run SysBench!\n");
printf("[[main]: Halting...\n");
stop();
}
scheduler_add_worker(core_id);
pit_setup_sleep();
uint8_t* cpu_ids = smp_ids();
uint32_t cpus = smp_count();
for (uint32_t i = 0; i < cpus; i++) {
char status = smp_boot(cpu_ids[i]);
if (status == SMP_STATUS_RUNNING) {
scheduler_add_worker(cpu_ids[i]);
}
}
// initialize the framebuffer
if (vbe_initialize(core_id, mbinfo)) {
printf("[[main]: A VBE framebuffer is required to run SysBench!\n");
printf("[[main]: Halting...\n");
stop();
}
char temp_support = temp_supported();
struct gfx_device *gfx_vbe = vbe_get_gfx_device();
struct gfx_render *renderer = gfx_vbe->renderer;
uint32_t fps = 0;
uint64_t last_update = current_time();
matrix_t projection;
matrix_t transformation;
//TODO: get monitor width and height from EDID
matrix_perspective(&projection, radians(70.0f), 16, 9, 0.01f, 500.0f);
matrix_identity(&transformation);
renderer->set_projection(&projection);
renderer->set_transformation(&transformation);
renderer->set_viewport(0, 0, renderer->get_width(), renderer->get_height());
//renderer->texture_bind(0, &texture_dirt);
float* triangles_vertices = memory_reserve(TRIANGLES_1_COUNT * 48);
float* triangles_colors = memory_reserve(TRIANGLES_1_COUNT * 48);
memcpy(triangles_1_vertices, triangles_vertices, TRIANGLES_1_COUNT * 48);
memcpy(triangles_1_colors, triangles_colors, TRIANGLES_1_COUNT * 48);
while (1) {
// TODO: change to near -inf
renderer->clear(0xFF000000, -2000000.0f);
// vertices have to be re-copied every frame
memcpy(triangles_1_vertices, triangles_vertices, TRIANGLES_1_COUNT * 48);
float rotation = (current_time() % 10000) / 10000.0f * 360.0f;
matrix_identity(&transformation);
matrix_translate(&transformation, 0.0f, 0.0f, -75.0f);
matrix_rotate_translation(&transformation, radians(rotation), 0, 1, 0);
renderer->set_transformation(&transformation);
renderer->draw_triangles(TRIANGLES_1_COUNT, triangles_vertices, 0, triangles_colors, 0);
gfx_vbe->update_screen();
fps++;
if (last_update + 1000 < current_time()) {
last_update = current_time();
printf("[[GFX ]: %u FPS\n", fps);
fps = 0;
if (temp_support) {
printf("[[temp]: CPU: %i°C\n", get_temperature());
}
}
}
printf("[[main]: Halting...\n");
stop();
}
|
477849.c | /*
* 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.
*
* The Original Code is Copyright (C) 2009 by Nicholas Bishop
* All rights reserved.
*/
/** \file
* \ingroup bke
*/
#include <stdlib.h>
#include <string.h>
#include "MEM_guardedalloc.h"
#include "DNA_object_types.h"
#include "DNA_mesh_types.h"
#include "DNA_meshdata_types.h"
#include "DNA_modifier_types.h"
#include "DNA_scene_types.h"
#include "DNA_brush_types.h"
#include "DNA_space_types.h"
#include "DNA_gpencil_types.h"
#include "DNA_view3d_types.h"
#include "DNA_workspace_types.h"
#include "BLI_bitmap.h"
#include "BLI_utildefines.h"
#include "BLI_math_vector.h"
#include "BLI_listbase.h"
#include "BLT_translation.h"
#include "BKE_animsys.h"
#include "BKE_brush.h"
#include "BKE_ccg.h"
#include "BKE_colortools.h"
#include "BKE_deform.h"
#include "BKE_main.h"
#include "BKE_context.h"
#include "BKE_crazyspace.h"
#include "BKE_gpencil.h"
#include "BKE_image.h"
#include "BKE_key.h"
#include "BKE_library.h"
#include "BKE_mesh.h"
#include "BKE_mesh_mapping.h"
#include "BKE_mesh_runtime.h"
#include "BKE_modifier.h"
#include "BKE_object.h"
#include "BKE_paint.h"
#include "BKE_pbvh.h"
#include "BKE_subdiv_ccg.h"
#include "BKE_subsurf.h"
#include "DEG_depsgraph.h"
#include "DEG_depsgraph_query.h"
#include "RNA_enum_types.h"
#include "bmesh.h"
const char PAINT_CURSOR_SCULPT[3] = {255, 100, 100};
const char PAINT_CURSOR_VERTEX_PAINT[3] = {255, 255, 255};
const char PAINT_CURSOR_WEIGHT_PAINT[3] = {200, 200, 255};
const char PAINT_CURSOR_TEXTURE_PAINT[3] = {255, 255, 255};
static eOverlayControlFlags overlay_flags = 0;
void BKE_paint_invalidate_overlay_tex(Scene *scene, ViewLayer *view_layer, const Tex *tex)
{
Paint *p = BKE_paint_get_active(scene, view_layer);
if (!p) {
return;
}
Brush *br = p->brush;
if (!br) {
return;
}
if (br->mtex.tex == tex) {
overlay_flags |= PAINT_OVERLAY_INVALID_TEXTURE_PRIMARY;
}
if (br->mask_mtex.tex == tex) {
overlay_flags |= PAINT_OVERLAY_INVALID_TEXTURE_SECONDARY;
}
}
void BKE_paint_invalidate_cursor_overlay(Scene *scene, ViewLayer *view_layer, CurveMapping *curve)
{
Paint *p = BKE_paint_get_active(scene, view_layer);
if (p == NULL) {
return;
}
Brush *br = p->brush;
if (br && br->curve == curve) {
overlay_flags |= PAINT_OVERLAY_INVALID_CURVE;
}
}
void BKE_paint_invalidate_overlay_all(void)
{
overlay_flags |= (PAINT_OVERLAY_INVALID_TEXTURE_SECONDARY |
PAINT_OVERLAY_INVALID_TEXTURE_PRIMARY | PAINT_OVERLAY_INVALID_CURVE);
}
eOverlayControlFlags BKE_paint_get_overlay_flags(void)
{
return overlay_flags;
}
void BKE_paint_set_overlay_override(eOverlayFlags flags)
{
if (flags & BRUSH_OVERLAY_OVERRIDE_MASK) {
if (flags & BRUSH_OVERLAY_CURSOR_OVERRIDE_ON_STROKE) {
overlay_flags |= PAINT_OVERLAY_OVERRIDE_CURSOR;
}
if (flags & BRUSH_OVERLAY_PRIMARY_OVERRIDE_ON_STROKE) {
overlay_flags |= PAINT_OVERLAY_OVERRIDE_PRIMARY;
}
if (flags & BRUSH_OVERLAY_SECONDARY_OVERRIDE_ON_STROKE) {
overlay_flags |= PAINT_OVERLAY_OVERRIDE_SECONDARY;
}
}
else {
overlay_flags &= ~(PAINT_OVERRIDE_MASK);
}
}
void BKE_paint_reset_overlay_invalid(eOverlayControlFlags flag)
{
overlay_flags &= ~(flag);
}
bool BKE_paint_ensure_from_paintmode(Scene *sce, ePaintMode mode)
{
ToolSettings *ts = sce->toolsettings;
Paint **paint_ptr = NULL;
switch (mode) {
case PAINT_MODE_SCULPT:
paint_ptr = (Paint **)&ts->sculpt;
break;
case PAINT_MODE_VERTEX:
paint_ptr = (Paint **)&ts->vpaint;
break;
case PAINT_MODE_WEIGHT:
paint_ptr = (Paint **)&ts->wpaint;
break;
case PAINT_MODE_TEXTURE_2D:
case PAINT_MODE_TEXTURE_3D:
break;
case PAINT_MODE_SCULPT_UV:
paint_ptr = (Paint **)&ts->uvsculpt;
break;
case PAINT_MODE_GPENCIL:
paint_ptr = (Paint **)&ts->gp_paint;
break;
case PAINT_MODE_INVALID:
break;
}
if (paint_ptr && (*paint_ptr == NULL)) {
BKE_paint_ensure(ts, paint_ptr);
return true;
}
return false;
}
Paint *BKE_paint_get_active_from_paintmode(Scene *sce, ePaintMode mode)
{
if (sce) {
ToolSettings *ts = sce->toolsettings;
switch (mode) {
case PAINT_MODE_SCULPT:
return &ts->sculpt->paint;
case PAINT_MODE_VERTEX:
return &ts->vpaint->paint;
case PAINT_MODE_WEIGHT:
return &ts->wpaint->paint;
case PAINT_MODE_TEXTURE_2D:
case PAINT_MODE_TEXTURE_3D:
return &ts->imapaint.paint;
case PAINT_MODE_SCULPT_UV:
return &ts->uvsculpt->paint;
case PAINT_MODE_GPENCIL:
return &ts->gp_paint->paint;
case PAINT_MODE_INVALID:
return NULL;
default:
return &ts->imapaint.paint;
}
}
return NULL;
}
const EnumPropertyItem *BKE_paint_get_tool_enum_from_paintmode(ePaintMode mode)
{
switch (mode) {
case PAINT_MODE_SCULPT:
return rna_enum_brush_sculpt_tool_items;
case PAINT_MODE_VERTEX:
return rna_enum_brush_vertex_tool_items;
case PAINT_MODE_WEIGHT:
return rna_enum_brush_weight_tool_items;
case PAINT_MODE_TEXTURE_2D:
case PAINT_MODE_TEXTURE_3D:
return rna_enum_brush_image_tool_items;
case PAINT_MODE_SCULPT_UV:
return rna_enum_brush_uv_sculpt_tool_items;
case PAINT_MODE_GPENCIL:
return rna_enum_brush_gpencil_types_items;
case PAINT_MODE_INVALID:
break;
}
return NULL;
}
const char *BKE_paint_get_tool_prop_id_from_paintmode(ePaintMode mode)
{
switch (mode) {
case PAINT_MODE_SCULPT:
return "sculpt_tool";
case PAINT_MODE_VERTEX:
return "vertex_tool";
case PAINT_MODE_WEIGHT:
return "weight_tool";
case PAINT_MODE_TEXTURE_2D:
case PAINT_MODE_TEXTURE_3D:
return "image_tool";
case PAINT_MODE_SCULPT_UV:
return "uv_sculpt_tool";
case PAINT_MODE_GPENCIL:
return "gpencil_tool";
default:
/* invalid paint mode */
return NULL;
}
}
Paint *BKE_paint_get_active(Scene *sce, ViewLayer *view_layer)
{
if (sce && view_layer) {
ToolSettings *ts = sce->toolsettings;
if (view_layer->basact && view_layer->basact->object) {
switch (view_layer->basact->object->mode) {
case OB_MODE_SCULPT:
return &ts->sculpt->paint;
case OB_MODE_VERTEX_PAINT:
return &ts->vpaint->paint;
case OB_MODE_WEIGHT_PAINT:
return &ts->wpaint->paint;
case OB_MODE_TEXTURE_PAINT:
return &ts->imapaint.paint;
case OB_MODE_PAINT_GPENCIL:
return &ts->gp_paint->paint;
case OB_MODE_EDIT:
return &ts->uvsculpt->paint;
default:
break;
}
}
/* default to image paint */
return &ts->imapaint.paint;
}
return NULL;
}
Paint *BKE_paint_get_active_from_context(const bContext *C)
{
Scene *sce = CTX_data_scene(C);
ViewLayer *view_layer = CTX_data_view_layer(C);
SpaceImage *sima;
if (sce && view_layer) {
ToolSettings *ts = sce->toolsettings;
Object *obact = NULL;
if (view_layer->basact && view_layer->basact->object) {
obact = view_layer->basact->object;
}
if ((sima = CTX_wm_space_image(C)) != NULL) {
if (obact && obact->mode == OB_MODE_EDIT) {
if (sima->mode == SI_MODE_PAINT) {
return &ts->imapaint.paint;
}
else if (sima->mode == SI_MODE_UV) {
return &ts->uvsculpt->paint;
}
}
else {
return &ts->imapaint.paint;
}
}
else {
return BKE_paint_get_active(sce, view_layer);
}
}
return NULL;
}
ePaintMode BKE_paintmode_get_active_from_context(const bContext *C)
{
Scene *sce = CTX_data_scene(C);
ViewLayer *view_layer = CTX_data_view_layer(C);
SpaceImage *sima;
if (sce && view_layer) {
Object *obact = NULL;
if (view_layer->basact && view_layer->basact->object) {
obact = view_layer->basact->object;
}
if ((sima = CTX_wm_space_image(C)) != NULL) {
if (obact && obact->mode == OB_MODE_EDIT) {
if (sima->mode == SI_MODE_PAINT) {
return PAINT_MODE_TEXTURE_2D;
}
else if (sima->mode == SI_MODE_UV) {
return PAINT_MODE_SCULPT_UV;
}
}
else {
return PAINT_MODE_TEXTURE_2D;
}
}
else if (obact) {
switch (obact->mode) {
case OB_MODE_SCULPT:
return PAINT_MODE_SCULPT;
case OB_MODE_VERTEX_PAINT:
return PAINT_MODE_VERTEX;
case OB_MODE_WEIGHT_PAINT:
return PAINT_MODE_WEIGHT;
case OB_MODE_TEXTURE_PAINT:
return PAINT_MODE_TEXTURE_3D;
case OB_MODE_EDIT:
return PAINT_MODE_SCULPT_UV;
default:
return PAINT_MODE_TEXTURE_2D;
}
}
else {
/* default to image paint */
return PAINT_MODE_TEXTURE_2D;
}
}
return PAINT_MODE_INVALID;
}
ePaintMode BKE_paintmode_get_from_tool(const struct bToolRef *tref)
{
if (tref->space_type == SPACE_VIEW3D) {
switch (tref->mode) {
case CTX_MODE_SCULPT:
return PAINT_MODE_SCULPT;
case CTX_MODE_PAINT_VERTEX:
return PAINT_MODE_VERTEX;
case CTX_MODE_PAINT_WEIGHT:
return PAINT_MODE_WEIGHT;
case CTX_MODE_PAINT_GPENCIL:
return PAINT_MODE_GPENCIL;
case CTX_MODE_PAINT_TEXTURE:
return PAINT_MODE_TEXTURE_3D;
}
}
else if (tref->space_type == SPACE_IMAGE) {
switch (tref->mode) {
case SI_MODE_PAINT:
return PAINT_MODE_TEXTURE_2D;
case SI_MODE_UV:
return PAINT_MODE_SCULPT_UV;
}
}
return PAINT_MODE_INVALID;
}
Brush *BKE_paint_brush(Paint *p)
{
return p ? p->brush : NULL;
}
void BKE_paint_brush_set(Paint *p, Brush *br)
{
if (p) {
id_us_min((ID *)p->brush);
id_us_plus((ID *)br);
p->brush = br;
BKE_paint_toolslots_brush_update(p);
}
}
void BKE_paint_runtime_init(const ToolSettings *ts, Paint *paint)
{
if (paint == &ts->imapaint.paint) {
paint->runtime.tool_offset = offsetof(Brush, imagepaint_tool);
paint->runtime.ob_mode = OB_MODE_TEXTURE_PAINT;
}
else if (paint == &ts->sculpt->paint) {
paint->runtime.tool_offset = offsetof(Brush, sculpt_tool);
paint->runtime.ob_mode = OB_MODE_SCULPT;
}
else if (paint == &ts->vpaint->paint) {
paint->runtime.tool_offset = offsetof(Brush, vertexpaint_tool);
paint->runtime.ob_mode = OB_MODE_VERTEX_PAINT;
}
else if (paint == &ts->wpaint->paint) {
paint->runtime.tool_offset = offsetof(Brush, weightpaint_tool);
paint->runtime.ob_mode = OB_MODE_WEIGHT_PAINT;
}
else if (paint == &ts->uvsculpt->paint) {
paint->runtime.tool_offset = offsetof(Brush, uv_sculpt_tool);
paint->runtime.ob_mode = OB_MODE_EDIT;
}
else if (paint == &ts->gp_paint->paint) {
paint->runtime.tool_offset = offsetof(Brush, gpencil_tool);
paint->runtime.ob_mode = OB_MODE_PAINT_GPENCIL;
}
else {
BLI_assert(0);
}
}
uint BKE_paint_get_brush_tool_offset_from_paintmode(const ePaintMode mode)
{
switch (mode) {
case PAINT_MODE_TEXTURE_2D:
case PAINT_MODE_TEXTURE_3D:
return offsetof(Brush, imagepaint_tool);
case PAINT_MODE_SCULPT:
return offsetof(Brush, sculpt_tool);
case PAINT_MODE_VERTEX:
return offsetof(Brush, vertexpaint_tool);
case PAINT_MODE_WEIGHT:
return offsetof(Brush, weightpaint_tool);
case PAINT_MODE_SCULPT_UV:
return offsetof(Brush, uv_sculpt_tool);
case PAINT_MODE_GPENCIL:
return offsetof(Brush, gpencil_tool);
case PAINT_MODE_INVALID:
break; /* We don't use these yet. */
}
return 0;
}
/** Free (or release) any data used by this paint curve (does not free the pcurve itself). */
void BKE_paint_curve_free(PaintCurve *pc)
{
MEM_SAFE_FREE(pc->points);
pc->tot_points = 0;
}
PaintCurve *BKE_paint_curve_add(Main *bmain, const char *name)
{
PaintCurve *pc;
pc = BKE_libblock_alloc(bmain, ID_PC, name, 0);
return pc;
}
/**
* Only copy internal data of PaintCurve ID from source to
* already allocated/initialized destination.
* You probably never want to use that directly,
* use #BKE_id_copy or #BKE_id_copy_ex for typical needs.
*
* WARNING! This function will not handle ID user count!
*
* \param flag: Copying options (see BKE_library.h's LIB_ID_COPY_... flags for more).
*/
void BKE_paint_curve_copy_data(Main *UNUSED(bmain),
PaintCurve *pc_dst,
const PaintCurve *pc_src,
const int UNUSED(flag))
{
if (pc_src->tot_points != 0) {
pc_dst->points = MEM_dupallocN(pc_src->points);
}
}
PaintCurve *BKE_paint_curve_copy(Main *bmain, const PaintCurve *pc)
{
PaintCurve *pc_copy;
BKE_id_copy(bmain, &pc->id, (ID **)&pc_copy);
return pc_copy;
}
void BKE_paint_curve_make_local(Main *bmain, PaintCurve *pc, const bool lib_local)
{
BKE_id_make_local_generic(bmain, &pc->id, true, lib_local);
}
Palette *BKE_paint_palette(Paint *p)
{
return p ? p->palette : NULL;
}
void BKE_paint_palette_set(Paint *p, Palette *palette)
{
if (p) {
id_us_min((ID *)p->palette);
p->palette = palette;
id_us_plus((ID *)p->palette);
}
}
void BKE_paint_curve_set(Brush *br, PaintCurve *pc)
{
if (br) {
id_us_min((ID *)br->paint_curve);
br->paint_curve = pc;
id_us_plus((ID *)br->paint_curve);
}
}
void BKE_paint_curve_clamp_endpoint_add_index(PaintCurve *pc, const int add_index)
{
pc->add_index = (add_index || pc->tot_points == 1) ? (add_index + 1) : 0;
}
/** Remove color from palette. Must be certain color is inside the palette! */
void BKE_palette_color_remove(Palette *palette, PaletteColor *color)
{
if (BLI_listbase_count_at_most(&palette->colors, palette->active_color) ==
palette->active_color) {
palette->active_color--;
}
BLI_remlink(&palette->colors, color);
if (palette->active_color < 0 && !BLI_listbase_is_empty(&palette->colors)) {
palette->active_color = 0;
}
MEM_freeN(color);
}
void BKE_palette_clear(Palette *palette)
{
BLI_freelistN(&palette->colors);
palette->active_color = 0;
}
Palette *BKE_palette_add(Main *bmain, const char *name)
{
Palette *palette = BKE_id_new(bmain, ID_PAL, name);
return palette;
}
/**
* Only copy internal data of Palette ID from source
* to already allocated/initialized destination.
* You probably never want to use that directly,
* use #BKE_id_copy or #BKE_id_copy_ex for typical needs.
*
* WARNING! This function will not handle ID user count!
*
* \param flag: Copying options (see BKE_library.h's LIB_ID_COPY_... flags for more).
*/
void BKE_palette_copy_data(Main *UNUSED(bmain),
Palette *palette_dst,
const Palette *palette_src,
const int UNUSED(flag))
{
BLI_duplicatelist(&palette_dst->colors, &palette_src->colors);
}
Palette *BKE_palette_copy(Main *bmain, const Palette *palette)
{
Palette *palette_copy;
BKE_id_copy(bmain, &palette->id, (ID **)&palette_copy);
return palette_copy;
}
void BKE_palette_make_local(Main *bmain, Palette *palette, const bool lib_local)
{
BKE_id_make_local_generic(bmain, &palette->id, true, lib_local);
}
void BKE_palette_init(Palette *palette)
{
/* Enable fake user by default. */
id_fake_user_set(&palette->id);
}
/** Free (or release) any data used by this palette (does not free the palette itself). */
void BKE_palette_free(Palette *palette)
{
BLI_freelistN(&palette->colors);
}
PaletteColor *BKE_palette_color_add(Palette *palette)
{
PaletteColor *color = MEM_callocN(sizeof(*color), "Palette Color");
BLI_addtail(&palette->colors, color);
return color;
}
bool BKE_palette_is_empty(const struct Palette *palette)
{
return BLI_listbase_is_empty(&palette->colors);
}
/* are we in vertex paint or weight paint face select mode? */
bool BKE_paint_select_face_test(Object *ob)
{
return ((ob != NULL) && (ob->type == OB_MESH) && (ob->data != NULL) &&
(((Mesh *)ob->data)->editflag & ME_EDIT_PAINT_FACE_SEL) &&
(ob->mode & (OB_MODE_VERTEX_PAINT | OB_MODE_WEIGHT_PAINT | OB_MODE_TEXTURE_PAINT)));
}
/* are we in weight paint vertex select mode? */
bool BKE_paint_select_vert_test(Object *ob)
{
return ((ob != NULL) && (ob->type == OB_MESH) && (ob->data != NULL) &&
(((Mesh *)ob->data)->editflag & ME_EDIT_PAINT_VERT_SEL) &&
(ob->mode & OB_MODE_WEIGHT_PAINT || ob->mode & OB_MODE_VERTEX_PAINT));
}
/**
* used to check if selection is possible
* (when we don't care if its face or vert)
*/
bool BKE_paint_select_elem_test(Object *ob)
{
return (BKE_paint_select_vert_test(ob) || BKE_paint_select_face_test(ob));
}
void BKE_paint_cavity_curve_preset(Paint *p, int preset)
{
CurveMap *cm = NULL;
if (!p->cavity_curve) {
p->cavity_curve = BKE_curvemapping_add(1, 0, 0, 1, 1);
}
cm = p->cavity_curve->cm;
cm->flag &= ~CUMA_EXTEND_EXTRAPOLATE;
p->cavity_curve->preset = preset;
BKE_curvemap_reset(
cm, &p->cavity_curve->clipr, p->cavity_curve->preset, CURVEMAP_SLOPE_POSITIVE);
BKE_curvemapping_changed(p->cavity_curve, false);
}
eObjectMode BKE_paint_object_mode_from_paintmode(ePaintMode mode)
{
switch (mode) {
case PAINT_MODE_SCULPT:
return OB_MODE_SCULPT;
case PAINT_MODE_VERTEX:
return OB_MODE_VERTEX_PAINT;
case PAINT_MODE_WEIGHT:
return OB_MODE_WEIGHT_PAINT;
case PAINT_MODE_TEXTURE_2D:
case PAINT_MODE_TEXTURE_3D:
return OB_MODE_TEXTURE_PAINT;
case PAINT_MODE_SCULPT_UV:
return OB_MODE_EDIT;
case PAINT_MODE_INVALID:
default:
return 0;
}
}
/**
* Call when entering each respective paint mode.
*/
bool BKE_paint_ensure(const ToolSettings *ts, struct Paint **r_paint)
{
Paint *paint = NULL;
if (*r_paint) {
/* Note: 'ts->imapaint' is ignored, it's not allocated. */
BLI_assert(ELEM(*r_paint,
&ts->gp_paint->paint,
&ts->sculpt->paint,
&ts->vpaint->paint,
&ts->wpaint->paint,
&ts->uvsculpt->paint));
#ifdef DEBUG
struct Paint paint_test = **r_paint;
BKE_paint_runtime_init(ts, *r_paint);
/* Swap so debug doesn't hide errors when release fails. */
SWAP(Paint, **r_paint, paint_test);
BLI_assert(paint_test.runtime.ob_mode == (*r_paint)->runtime.ob_mode);
BLI_assert(paint_test.runtime.tool_offset == (*r_paint)->runtime.tool_offset);
#endif
return true;
}
if (((VPaint **)r_paint == &ts->vpaint) || ((VPaint **)r_paint == &ts->wpaint)) {
VPaint *data = MEM_callocN(sizeof(*data), __func__);
paint = &data->paint;
}
else if ((Sculpt **)r_paint == &ts->sculpt) {
Sculpt *data = MEM_callocN(sizeof(*data), __func__);
paint = &data->paint;
/* Turn on X plane mirror symmetry by default */
paint->symmetry_flags |= PAINT_SYMM_X;
/* Make sure at least dyntopo subdivision is enabled */
data->flags |= SCULPT_DYNTOPO_SUBDIVIDE | SCULPT_DYNTOPO_COLLAPSE;
}
else if ((GpPaint **)r_paint == &ts->gp_paint) {
GpPaint *data = MEM_callocN(sizeof(*data), __func__);
paint = &data->paint;
}
else if ((UvSculpt **)r_paint == &ts->uvsculpt) {
UvSculpt *data = MEM_callocN(sizeof(*data), __func__);
paint = &data->paint;
}
paint->flags |= PAINT_SHOW_BRUSH;
*r_paint = paint;
BKE_paint_runtime_init(ts, paint);
return false;
}
void BKE_paint_init(Main *bmain, Scene *sce, ePaintMode mode, const char col[3])
{
UnifiedPaintSettings *ups = &sce->toolsettings->unified_paint_settings;
Paint *paint = BKE_paint_get_active_from_paintmode(sce, mode);
/* If there's no brush, create one */
if (PAINT_MODE_HAS_BRUSH(mode)) {
Brush *brush = BKE_paint_brush(paint);
if (brush == NULL) {
eObjectMode ob_mode = BKE_paint_object_mode_from_paintmode(mode);
brush = BKE_brush_first_search(bmain, ob_mode);
if (!brush) {
brush = BKE_brush_add(bmain, "Brush", ob_mode);
id_us_min(&brush->id); /* fake user only */
}
BKE_paint_brush_set(paint, brush);
}
}
memcpy(paint->paint_cursor_col, col, 3);
paint->paint_cursor_col[3] = 128;
ups->last_stroke_valid = false;
zero_v3(ups->average_stroke_accum);
ups->average_stroke_counter = 0;
if (!paint->cavity_curve) {
BKE_paint_cavity_curve_preset(paint, CURVE_PRESET_LINE);
}
}
void BKE_paint_free(Paint *paint)
{
BKE_curvemapping_free(paint->cavity_curve);
MEM_SAFE_FREE(paint->tool_slots);
}
/* called when copying scene settings, so even if 'src' and 'tar' are the same
* still do a id_us_plus(), rather then if we were copying between 2 existing
* scenes where a matching value should decrease the existing user count as
* with paint_brush_set() */
void BKE_paint_copy(Paint *src, Paint *tar, const int flag)
{
tar->brush = src->brush;
tar->cavity_curve = BKE_curvemapping_copy(src->cavity_curve);
tar->tool_slots = MEM_dupallocN(src->tool_slots);
if ((flag & LIB_ID_CREATE_NO_USER_REFCOUNT) == 0) {
id_us_plus((ID *)tar->brush);
id_us_plus((ID *)tar->palette);
if (src->tool_slots != NULL) {
for (int i = 0; i < tar->tool_slots_len; i++) {
id_us_plus((ID *)tar->tool_slots[i].brush);
}
}
}
}
void BKE_paint_stroke_get_average(Scene *scene, Object *ob, float stroke[3])
{
UnifiedPaintSettings *ups = &scene->toolsettings->unified_paint_settings;
if (ups->last_stroke_valid && ups->average_stroke_counter > 0) {
float fac = 1.0f / ups->average_stroke_counter;
mul_v3_v3fl(stroke, ups->average_stroke_accum, fac);
}
else {
copy_v3_v3(stroke, ob->obmat[3]);
}
}
/* returns non-zero if any of the face's vertices
* are hidden, zero otherwise */
bool paint_is_face_hidden(const MLoopTri *lt, const MVert *mvert, const MLoop *mloop)
{
return ((mvert[mloop[lt->tri[0]].v].flag & ME_HIDE) ||
(mvert[mloop[lt->tri[1]].v].flag & ME_HIDE) ||
(mvert[mloop[lt->tri[2]].v].flag & ME_HIDE));
}
/* returns non-zero if any of the corners of the grid
* face whose inner corner is at (x, y) are hidden,
* zero otherwise */
bool paint_is_grid_face_hidden(const unsigned int *grid_hidden, int gridsize, int x, int y)
{
/* skip face if any of its corners are hidden */
return (BLI_BITMAP_TEST(grid_hidden, y * gridsize + x) ||
BLI_BITMAP_TEST(grid_hidden, y * gridsize + x + 1) ||
BLI_BITMAP_TEST(grid_hidden, (y + 1) * gridsize + x + 1) ||
BLI_BITMAP_TEST(grid_hidden, (y + 1) * gridsize + x));
}
/* Return true if all vertices in the face are visible, false otherwise */
bool paint_is_bmesh_face_hidden(BMFace *f)
{
BMLoop *l_iter;
BMLoop *l_first;
l_iter = l_first = BM_FACE_FIRST_LOOP(f);
do {
if (BM_elem_flag_test(l_iter->v, BM_ELEM_HIDDEN)) {
return true;
}
} while ((l_iter = l_iter->next) != l_first);
return false;
}
float paint_grid_paint_mask(const GridPaintMask *gpm, unsigned level, unsigned x, unsigned y)
{
int factor = BKE_ccg_factor(level, gpm->level);
int gridsize = BKE_ccg_gridsize(gpm->level);
return gpm->data[(y * factor) * gridsize + (x * factor)];
}
/* threshold to move before updating the brush rotation */
#define RAKE_THRESHHOLD 20
void paint_update_brush_rake_rotation(UnifiedPaintSettings *ups, Brush *brush, float rotation)
{
if (brush->mtex.brush_angle_mode & MTEX_ANGLE_RAKE) {
ups->brush_rotation = rotation;
}
else {
ups->brush_rotation = 0.0f;
}
if (brush->mask_mtex.brush_angle_mode & MTEX_ANGLE_RAKE) {
ups->brush_rotation_sec = rotation;
}
else {
ups->brush_rotation_sec = 0.0f;
}
}
bool paint_calculate_rake_rotation(UnifiedPaintSettings *ups,
Brush *brush,
const float mouse_pos[2])
{
bool ok = false;
if ((brush->mtex.brush_angle_mode & MTEX_ANGLE_RAKE) ||
(brush->mask_mtex.brush_angle_mode & MTEX_ANGLE_RAKE)) {
const float r = RAKE_THRESHHOLD;
float rotation;
float dpos[2];
sub_v2_v2v2(dpos, ups->last_rake, mouse_pos);
if (len_squared_v2(dpos) >= r * r) {
rotation = atan2f(dpos[0], dpos[1]);
copy_v2_v2(ups->last_rake, mouse_pos);
ups->last_rake_angle = rotation;
paint_update_brush_rake_rotation(ups, brush, rotation);
ok = true;
}
/* make sure we reset here to the last rotation to avoid accumulating
* values in case a random rotation is also added */
else {
paint_update_brush_rake_rotation(ups, brush, ups->last_rake_angle);
ok = false;
}
}
else {
ups->brush_rotation = ups->brush_rotation_sec = 0.0f;
ok = true;
}
return ok;
}
void BKE_sculptsession_free_deformMats(SculptSession *ss)
{
MEM_SAFE_FREE(ss->orig_cos);
MEM_SAFE_FREE(ss->deform_cos);
MEM_SAFE_FREE(ss->deform_imats);
}
void BKE_sculptsession_free_vwpaint_data(struct SculptSession *ss)
{
struct SculptVertexPaintGeomMap *gmap = NULL;
if (ss->mode_type == OB_MODE_VERTEX_PAINT) {
gmap = &ss->mode.vpaint.gmap;
MEM_SAFE_FREE(ss->mode.vpaint.previous_color);
}
else if (ss->mode_type == OB_MODE_WEIGHT_PAINT) {
gmap = &ss->mode.wpaint.gmap;
MEM_SAFE_FREE(ss->mode.wpaint.alpha_weight);
if (ss->mode.wpaint.dvert_prev) {
BKE_defvert_array_free_elems(ss->mode.wpaint.dvert_prev, ss->totvert);
MEM_freeN(ss->mode.wpaint.dvert_prev);
ss->mode.wpaint.dvert_prev = NULL;
}
}
else {
return;
}
MEM_SAFE_FREE(gmap->vert_to_loop);
MEM_SAFE_FREE(gmap->vert_map_mem);
MEM_SAFE_FREE(gmap->vert_to_poly);
MEM_SAFE_FREE(gmap->poly_map_mem);
}
/* Write out the sculpt dynamic-topology BMesh to the Mesh */
static void sculptsession_bm_to_me_update_data_only(Object *ob, bool reorder)
{
SculptSession *ss = ob->sculpt;
if (ss->bm) {
if (ob->data) {
BMIter iter;
BMFace *efa;
BM_ITER_MESH (efa, &iter, ss->bm, BM_FACES_OF_MESH) {
BM_elem_flag_set(efa, BM_ELEM_SMOOTH, ss->bm_smooth_shading);
}
if (reorder) {
BM_log_mesh_elems_reorder(ss->bm, ss->bm_log);
}
BM_mesh_bm_to_me(NULL,
ss->bm,
ob->data,
(&(struct BMeshToMeshParams){
.calc_object_remap = false,
}));
}
}
}
void BKE_sculptsession_bm_to_me(Object *ob, bool reorder)
{
if (ob && ob->sculpt) {
sculptsession_bm_to_me_update_data_only(ob, reorder);
/* Ensure the objects evaluated mesh doesn't hold onto arrays
* now realloc'd in the mesh T34473. */
DEG_id_tag_update(&ob->id, ID_RECALC_GEOMETRY);
}
}
static void sculptsession_free_pbvh(Object *object)
{
SculptSession *ss = object->sculpt;
if (!ss) {
return;
}
if (ss->pbvh) {
BKE_pbvh_free(ss->pbvh);
ss->pbvh = NULL;
}
if (ss->pmap) {
MEM_freeN(ss->pmap);
ss->pmap = NULL;
}
if (ss->pmap_mem) {
MEM_freeN(ss->pmap_mem);
ss->pmap_mem = NULL;
}
}
void BKE_sculptsession_bm_to_me_for_render(Object *object)
{
if (object && object->sculpt) {
if (object->sculpt->bm) {
/* Ensure no points to old arrays are stored in DM
*
* Apparently, we could not use DEG_id_tag_update
* here because this will lead to the while object
* surface to disappear, so we'll release DM in place.
*/
BKE_object_free_derived_caches(object);
sculptsession_bm_to_me_update_data_only(object, false);
/* In contrast with sculptsession_bm_to_me no need in
* DAG tag update here - derived mesh was freed and
* old pointers are nowhere stored.
*/
}
}
}
void BKE_sculptsession_free(Object *ob)
{
if (ob && ob->sculpt) {
SculptSession *ss = ob->sculpt;
if (ss->bm) {
BKE_sculptsession_bm_to_me(ob, true);
BM_mesh_free(ss->bm);
}
sculptsession_free_pbvh(ob);
MEM_SAFE_FREE(ss->pmap);
MEM_SAFE_FREE(ss->pmap_mem);
if (ss->bm_log) {
BM_log_free(ss->bm_log);
}
if (ss->texcache) {
MEM_freeN(ss->texcache);
}
if (ss->tex_pool) {
BKE_image_pool_free(ss->tex_pool);
}
if (ss->layer_co) {
MEM_freeN(ss->layer_co);
}
if (ss->orig_cos) {
MEM_freeN(ss->orig_cos);
}
if (ss->deform_cos) {
MEM_freeN(ss->deform_cos);
}
if (ss->deform_imats) {
MEM_freeN(ss->deform_imats);
}
if (ss->preview_vert_index_list) {
MEM_freeN(ss->preview_vert_index_list);
}
BKE_sculptsession_free_vwpaint_data(ob->sculpt);
MEM_freeN(ss);
ob->sculpt = NULL;
}
}
/* Sculpt mode handles multires differently from regular meshes, but only if
* it's the last modifier on the stack and it is not on the first level */
MultiresModifierData *BKE_sculpt_multires_active(Scene *scene, Object *ob)
{
Mesh *me = (Mesh *)ob->data;
ModifierData *md;
VirtualModifierData virtualModifierData;
if (ob->sculpt && ob->sculpt->bm) {
/* can't combine multires and dynamic topology */
return NULL;
}
if (!CustomData_get_layer(&me->ldata, CD_MDISPS)) {
/* multires can't work without displacement layer */
return NULL;
}
/* Weight paint operates on original vertices, and needs to treat multires as regular modifier
* to make it so that PBVH vertices are at the multires surface. */
if ((ob->mode & OB_MODE_SCULPT) == 0) {
return NULL;
}
for (md = modifiers_getVirtualModifierList(ob, &virtualModifierData); md; md = md->next) {
if (md->type == eModifierType_Multires) {
MultiresModifierData *mmd = (MultiresModifierData *)md;
if (!modifier_isEnabled(scene, md, eModifierMode_Realtime)) {
continue;
}
if (mmd->sculptlvl > 0) {
return mmd;
}
else {
return NULL;
}
}
}
return NULL;
}
/* Checks if there are any supported deformation modifiers active */
static bool sculpt_modifiers_active(Scene *scene, Sculpt *sd, Object *ob)
{
ModifierData *md;
Mesh *me = (Mesh *)ob->data;
MultiresModifierData *mmd = BKE_sculpt_multires_active(scene, ob);
VirtualModifierData virtualModifierData;
if (mmd || ob->sculpt->bm) {
return false;
}
/* non-locked shape keys could be handled in the same way as deformed mesh */
if ((ob->shapeflag & OB_SHAPE_LOCK) == 0 && me->key && ob->shapenr) {
return true;
}
md = modifiers_getVirtualModifierList(ob, &virtualModifierData);
/* exception for shape keys because we can edit those */
for (; md; md = md->next) {
const ModifierTypeInfo *mti = modifierType_getInfo(md->type);
if (!modifier_isEnabled(scene, md, eModifierMode_Realtime)) {
continue;
}
if (md->type == eModifierType_Multires && (ob->mode & OB_MODE_SCULPT)) {
continue;
}
if (md->type == eModifierType_ShapeKey) {
continue;
}
if (mti->type == eModifierTypeType_OnlyDeform) {
return true;
}
else if ((sd->flags & SCULPT_ONLY_DEFORM) == 0) {
return true;
}
}
return false;
}
/**
* \param need_mask: So that the evaluated mesh that is returned has mask data.
*/
static void sculpt_update_object(
Depsgraph *depsgraph, Object *ob, Mesh *me_eval, bool need_pmap, bool need_mask)
{
Scene *scene = DEG_get_input_scene(depsgraph);
Sculpt *sd = scene->toolsettings->sculpt;
SculptSession *ss = ob->sculpt;
Mesh *me = BKE_object_get_original_mesh(ob);
MultiresModifierData *mmd = BKE_sculpt_multires_active(scene, ob);
ss->deform_modifiers_active = sculpt_modifiers_active(scene, sd, ob);
ss->show_mask = (sd->flags & SCULPT_HIDE_MASK) == 0;
ss->building_vp_handle = false;
if (need_mask) {
if (mmd == NULL) {
if (!CustomData_has_layer(&me->vdata, CD_PAINT_MASK)) {
BKE_sculpt_mask_layers_ensure(ob, NULL);
}
}
else {
if (!CustomData_has_layer(&me->ldata, CD_GRID_PAINT_MASK)) {
BKE_sculpt_mask_layers_ensure(ob, mmd);
}
}
}
/* tessfaces aren't used and will become invalid */
BKE_mesh_tessface_clear(me);
ss->shapekey_active = (mmd == NULL) ? BKE_keyblock_from_object(ob) : NULL;
/* NOTE: Weight pPaint require mesh info for loop lookup, but it never uses multires code path,
* so no extra checks is needed here. */
if (mmd) {
ss->multires = mmd;
ss->totvert = me_eval->totvert;
ss->totpoly = me_eval->totpoly;
ss->mvert = NULL;
ss->mpoly = NULL;
ss->mloop = NULL;
}
else {
ss->totvert = me->totvert;
ss->totpoly = me->totpoly;
ss->mvert = me->mvert;
ss->mpoly = me->mpoly;
ss->mloop = me->mloop;
ss->multires = NULL;
ss->vmask = CustomData_get_layer(&me->vdata, CD_PAINT_MASK);
}
ss->subdiv_ccg = me_eval->runtime.subdiv_ccg;
PBVH *pbvh = BKE_sculpt_object_pbvh_ensure(depsgraph, ob);
BLI_assert(pbvh == ss->pbvh);
UNUSED_VARS_NDEBUG(pbvh);
if (need_pmap && ob->type == OB_MESH && !ss->pmap) {
BKE_mesh_vert_poly_map_create(
&ss->pmap, &ss->pmap_mem, me->mpoly, me->mloop, me->totvert, me->totpoly, me->totloop);
}
pbvh_show_mask_set(ss->pbvh, ss->show_mask);
if (ss->deform_modifiers_active) {
if (!ss->orig_cos) {
int a;
BKE_sculptsession_free_deformMats(ss);
ss->orig_cos = (ss->shapekey_active) ?
BKE_keyblock_convert_to_vertcos(ob, ss->shapekey_active) :
BKE_mesh_vert_coords_alloc(me, NULL);
BKE_crazyspace_build_sculpt(depsgraph, scene, ob, &ss->deform_imats, &ss->deform_cos);
BKE_pbvh_vert_coords_apply(ss->pbvh, ss->deform_cos, me->totvert);
for (a = 0; a < me->totvert; a++) {
invert_m3(ss->deform_imats[a]);
}
}
}
else {
BKE_sculptsession_free_deformMats(ss);
}
if (ss->shapekey_active != NULL && ss->deform_cos == NULL) {
ss->deform_cos = BKE_keyblock_convert_to_vertcos(ob, ss->shapekey_active);
}
/* if pbvh is deformed, key block is already applied to it */
if (ss->shapekey_active) {
bool pbvh_deformed = BKE_pbvh_is_deformed(ss->pbvh);
if (!pbvh_deformed || ss->deform_cos == NULL) {
float(*vertCos)[3] = BKE_keyblock_convert_to_vertcos(ob, ss->shapekey_active);
if (vertCos) {
if (!pbvh_deformed) {
/* apply shape keys coordinates to PBVH */
BKE_pbvh_vert_coords_apply(ss->pbvh, vertCos, me->totvert);
}
if (ss->deform_cos == NULL) {
ss->deform_cos = vertCos;
}
if (vertCos != ss->deform_cos) {
MEM_freeN(vertCos);
}
}
}
}
}
void BKE_sculpt_update_object_before_eval(Object *ob)
{
/* Update before mesh evaluation in the dependency graph. */
SculptSession *ss = ob->sculpt;
if (ss && ss->building_vp_handle == false) {
if (!ss->cache && !ss->filter_cache) {
/* We free pbvh on changes, except in the middle of drawing a stroke
* since it can't deal with changing PVBH node organization, we hope
* topology does not change in the meantime .. weak. */
sculptsession_free_pbvh(ob);
BKE_sculptsession_free_deformMats(ob->sculpt);
/* In vertex/weight paint, force maps to be rebuilt. */
BKE_sculptsession_free_vwpaint_data(ob->sculpt);
}
else {
PBVHNode **nodes;
int n, totnode;
BKE_pbvh_search_gather(ss->pbvh, NULL, NULL, &nodes, &totnode);
for (n = 0; n < totnode; n++) {
BKE_pbvh_node_mark_update(nodes[n]);
}
MEM_freeN(nodes);
}
}
}
void BKE_sculpt_update_object_after_eval(Depsgraph *depsgraph, Object *ob_eval)
{
/* Update after mesh evaluation in the dependency graph, to rebuild PBVH or
* other data when modifiers change the mesh. */
Object *ob_orig = DEG_get_original_object(ob_eval);
Mesh *me_eval = ob_eval->runtime.mesh_eval;
BLI_assert(me_eval != NULL);
sculpt_update_object(depsgraph, ob_orig, me_eval, false, false);
}
void BKE_sculpt_update_object_for_edit(Depsgraph *depsgraph,
Object *ob_orig,
bool need_pmap,
bool need_mask)
{
/* Update from sculpt operators and undo, to update sculpt session
* and PBVH after edits. */
Scene *scene_eval = DEG_get_evaluated_scene(depsgraph);
Object *ob_eval = DEG_get_evaluated_object(depsgraph, ob_orig);
Mesh *me_eval = mesh_get_eval_final(depsgraph, scene_eval, ob_eval, &CD_MASK_BAREMESH);
BLI_assert(ob_orig == DEG_get_original_object(ob_orig));
sculpt_update_object(depsgraph, ob_orig, me_eval, need_pmap, need_mask);
}
int BKE_sculpt_mask_layers_ensure(Object *ob, MultiresModifierData *mmd)
{
const float *paint_mask;
Mesh *me = ob->data;
int ret = 0;
paint_mask = CustomData_get_layer(&me->vdata, CD_PAINT_MASK);
/* if multires is active, create a grid paint mask layer if there
* isn't one already */
if (mmd && !CustomData_has_layer(&me->ldata, CD_GRID_PAINT_MASK)) {
GridPaintMask *gmask;
int level = max_ii(1, mmd->sculptlvl);
int gridsize = BKE_ccg_gridsize(level);
int gridarea = gridsize * gridsize;
int i, j;
gmask = CustomData_add_layer(&me->ldata, CD_GRID_PAINT_MASK, CD_CALLOC, NULL, me->totloop);
for (i = 0; i < me->totloop; i++) {
GridPaintMask *gpm = &gmask[i];
gpm->level = level;
gpm->data = MEM_callocN(sizeof(float) * gridarea, "GridPaintMask.data");
}
/* if vertices already have mask, copy into multires data */
if (paint_mask) {
for (i = 0; i < me->totpoly; i++) {
const MPoly *p = &me->mpoly[i];
float avg = 0;
/* mask center */
for (j = 0; j < p->totloop; j++) {
const MLoop *l = &me->mloop[p->loopstart + j];
avg += paint_mask[l->v];
}
avg /= (float)p->totloop;
/* fill in multires mask corner */
for (j = 0; j < p->totloop; j++) {
GridPaintMask *gpm = &gmask[p->loopstart + j];
const MLoop *l = &me->mloop[p->loopstart + j];
const MLoop *prev = ME_POLY_LOOP_PREV(me->mloop, p, j);
const MLoop *next = ME_POLY_LOOP_NEXT(me->mloop, p, j);
gpm->data[0] = avg;
gpm->data[1] = (paint_mask[l->v] + paint_mask[next->v]) * 0.5f;
gpm->data[2] = (paint_mask[l->v] + paint_mask[prev->v]) * 0.5f;
gpm->data[3] = paint_mask[l->v];
}
}
}
ret |= SCULPT_MASK_LAYER_CALC_LOOP;
}
/* create vertex paint mask layer if there isn't one already */
if (!paint_mask) {
CustomData_add_layer(&me->vdata, CD_PAINT_MASK, CD_CALLOC, NULL, me->totvert);
ret |= SCULPT_MASK_LAYER_CALC_VERT;
}
return ret;
}
void BKE_sculpt_toolsettings_data_ensure(struct Scene *scene)
{
BKE_paint_ensure(scene->toolsettings, (Paint **)&scene->toolsettings->sculpt);
Sculpt *sd = scene->toolsettings->sculpt;
if (!sd->detail_size) {
sd->detail_size = 12;
}
if (!sd->detail_percent) {
sd->detail_percent = 25;
}
if (sd->constant_detail == 0.0f) {
sd->constant_detail = 3.0f;
}
/* Set sane default tiling offsets */
if (!sd->paint.tile_offset[0]) {
sd->paint.tile_offset[0] = 1.0f;
}
if (!sd->paint.tile_offset[1]) {
sd->paint.tile_offset[1] = 1.0f;
}
if (!sd->paint.tile_offset[2]) {
sd->paint.tile_offset[2] = 1.0f;
}
}
static bool check_sculpt_object_deformed(Object *object, const bool for_construction)
{
bool deformed = false;
/* Active modifiers means extra deformation, which can't be handled correct
* on birth of PBVH and sculpt "layer" levels, so use PBVH only for internal brush
* stuff and show final evaluated mesh so user would see actual object shape.
*/
deformed |= object->sculpt->deform_modifiers_active;
if (for_construction) {
deformed |= object->sculpt->shapekey_active != NULL;
}
else {
/* As in case with modifiers, we can't synchronize deformation made against
* PBVH and non-locked keyblock, so also use PBVH only for brushes and
* final DM to give final result to user.
*/
deformed |= object->sculpt->shapekey_active && (object->shapeflag & OB_SHAPE_LOCK) == 0;
}
return deformed;
}
static PBVH *build_pbvh_for_dynamic_topology(Object *ob)
{
PBVH *pbvh = BKE_pbvh_new();
BKE_pbvh_build_bmesh(pbvh,
ob->sculpt->bm,
ob->sculpt->bm_smooth_shading,
ob->sculpt->bm_log,
ob->sculpt->cd_vert_node_offset,
ob->sculpt->cd_face_node_offset);
pbvh_show_mask_set(pbvh, ob->sculpt->show_mask);
return pbvh;
}
static PBVH *build_pbvh_from_regular_mesh(Object *ob, Mesh *me_eval_deform)
{
Mesh *me = BKE_object_get_original_mesh(ob);
const int looptris_num = poly_to_tri_count(me->totpoly, me->totloop);
PBVH *pbvh = BKE_pbvh_new();
MLoopTri *looptri = MEM_malloc_arrayN(looptris_num, sizeof(*looptri), __func__);
BKE_mesh_recalc_looptri(me->mloop, me->mpoly, me->mvert, me->totloop, me->totpoly, looptri);
BKE_pbvh_build_mesh(pbvh,
me->mpoly,
me->mloop,
me->mvert,
me->totvert,
&me->vdata,
&me->ldata,
looptri,
looptris_num);
pbvh_show_mask_set(pbvh, ob->sculpt->show_mask);
const bool is_deformed = check_sculpt_object_deformed(ob, true);
if (is_deformed && me_eval_deform != NULL) {
int totvert;
float(*v_cos)[3] = BKE_mesh_vert_coords_alloc(me_eval_deform, &totvert);
BKE_pbvh_vert_coords_apply(pbvh, v_cos, totvert);
MEM_freeN(v_cos);
}
return pbvh;
}
static PBVH *build_pbvh_from_ccg(Object *ob, SubdivCCG *subdiv_ccg)
{
CCGKey key;
BKE_subdiv_ccg_key_top_level(&key, subdiv_ccg);
PBVH *pbvh = BKE_pbvh_new();
BKE_pbvh_build_grids(pbvh,
subdiv_ccg->grids,
subdiv_ccg->num_grids,
&key,
(void **)subdiv_ccg->grid_faces,
subdiv_ccg->grid_flag_mats,
subdiv_ccg->grid_hidden);
pbvh_show_mask_set(pbvh, ob->sculpt->show_mask);
return pbvh;
}
PBVH *BKE_sculpt_object_pbvh_ensure(Depsgraph *depsgraph, Object *ob)
{
if (ob == NULL || ob->sculpt == NULL) {
return NULL;
}
PBVH *pbvh = ob->sculpt->pbvh;
if (pbvh != NULL) {
/* NOTE: It is possible that grids were re-allocated due to modifier
* stack. Need to update those pointers. */
if (BKE_pbvh_type(pbvh) == PBVH_GRIDS) {
Object *object_eval = DEG_get_evaluated_object(depsgraph, ob);
Mesh *mesh_eval = object_eval->data;
SubdivCCG *subdiv_ccg = mesh_eval->runtime.subdiv_ccg;
if (subdiv_ccg != NULL) {
BKE_sculpt_bvh_update_from_ccg(pbvh, subdiv_ccg);
}
}
return pbvh;
}
if (ob->sculpt->bm != NULL) {
/* Sculpting on a BMesh (dynamic-topology) gets a special PBVH. */
pbvh = build_pbvh_for_dynamic_topology(ob);
}
else {
Object *object_eval = DEG_get_evaluated_object(depsgraph, ob);
Mesh *mesh_eval = object_eval->data;
if (mesh_eval->runtime.subdiv_ccg != NULL) {
pbvh = build_pbvh_from_ccg(ob, mesh_eval->runtime.subdiv_ccg);
}
else if (ob->type == OB_MESH) {
Mesh *me_eval_deform = object_eval->runtime.mesh_deform_eval;
pbvh = build_pbvh_from_regular_mesh(ob, me_eval_deform);
}
}
ob->sculpt->pbvh = pbvh;
return pbvh;
}
void BKE_sculpt_bvh_update_from_ccg(PBVH *pbvh, SubdivCCG *subdiv_ccg)
{
BKE_pbvh_grids_update(pbvh,
subdiv_ccg->grids,
(void **)subdiv_ccg->grid_faces,
subdiv_ccg->grid_flag_mats,
subdiv_ccg->grid_hidden);
}
/* Test if PBVH can be used directly for drawing, which is faster than
* drawing the mesh and all updates that come with it. */
bool BKE_sculptsession_use_pbvh_draw(const Object *ob, const View3D *v3d)
{
SculptSession *ss = ob->sculpt;
if (ss == NULL || ss->pbvh == NULL || ss->mode_type != OB_MODE_SCULPT) {
return false;
}
if (BKE_pbvh_type(ss->pbvh) == PBVH_FACES) {
/* Regular mesh only draws from PBVH without modifiers and shape keys. */
const bool full_shading = (v3d && (v3d->shading.type > OB_SOLID));
return !(ss->shapekey_active || ss->deform_modifiers_active || full_shading);
}
else {
/* Multires and dyntopo always draw directly from the PBVH. */
return true;
}
}
|
311688.c | /*
// mod_mruby.c - mod_mruby core module
//
// See Copyright Notice in mod_mruby.h
*/
#define CORE_PRIVATE
#include "apr_strings.h"
#include "ap_config.h"
#include "ap_provider.h"
#include "httpd.h"
#include "http_config.h"
#include "http_core.h"
#include "http_log.h"
#include "http_protocol.h"
#include "http_request.h"
#include "apr_thread_proc.h"
#include <mruby.h>
#include <mruby/proc.h>
#include <mruby/compile.h>
#include <mruby/version.h>
#include <unistd.h>
#include <sys/stat.h>
//#include <sys/prctl.h>
#include "mod_mruby.h"
#include "ap_mrb_request.h"
#include "ap_mrb_authnprovider.h"
#include "ap_mrb_core.h"
#include "ap_mrb_filter.h"
apr_thread_mutex_t *mod_mruby_mutex;
module AP_MODULE_DECLARE_DATA mruby_module;
int ap_mruby_class_init(mrb_state *mrb);
static int mod_mruby_init(apr_pool_t *p, apr_pool_t *plog, apr_pool_t *ptemp, server_rec *s);
static int ap_mruby_run(mrb_state *mrb, request_rec *r, mod_mruby_code_t *code, int module_status);
static void mod_mruby_compile_code(mrb_state *mrb, mod_mruby_code_t *c, server_rec *s);
//
// Set/Get/Cleanup functions for mrb_state
//
static mrb_state *ap_mrb_create_mrb_state()
{
TRACER;
mrb_state *mrb = mrb_open();
ap_mruby_class_init(mrb);
return mrb;
}
static apr_status_t cleanup_mrb_state(void *p)
{
TRACER;
mrb_close((mrb_state *)p);
return APR_SUCCESS;
}
static void ap_mrb_set_mrb_state(apr_pool_t *pool, mrb_state *mrb)
{
TRACER;
apr_pool_userdata_set(mrb, "mod_mruby_state", cleanup_mrb_state, pool);
ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, ap_server_conf, "%s DEBUG %s: set mrb_state to mod_mruby_state", MODULE_NAME,
__func__);
}
static mrb_state *ap_mrb_get_mrb_state(apr_pool_t *pool)
{
mrb_state *mrb = NULL;
TRACER;
if (apr_pool_userdata_get((void **)&mrb, "mod_mruby_state", pool) == APR_SUCCESS) {
if (mrb == NULL) {
ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, ap_server_conf, "%s DEBUG %s: get mrb_state is NULL, reopen mrb_state",
MODULE_NAME, __func__);
mrb = mrb_open();
ap_mruby_class_init(mrb);
ap_mrb_set_mrb_state(pool, mrb);
return mrb;
} else {
ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, ap_server_conf, "%s DEBUG %s: mrb_state found from mod_mruby_state",
MODULE_NAME, __func__);
return mrb;
}
}
ap_log_error(APLOG_MARK, APLOG_ERR, 0, ap_server_conf, "%s ERROR %s: apr_pool_userdata_get mod_mruby_state faled",
MODULE_NAME, __func__);
return NULL;
}
//
// Set code functions
//
static mod_mruby_code_t *ap_mrb_set_file(apr_pool_t *p, const char *path, const char *cache_opt, const char *phase)
{
mod_mruby_code_t *c = (mod_mruby_code_t *)apr_pcalloc(p, sizeof(mod_mruby_code_t));
TRACER;
c->type = MOD_MRUBY_FILE;
c->code.path = apr_pstrdup(p, path);
if (cache_opt && !strcmp(cache_opt, "cache")) {
c->cache = CACHE_ENABLE;
ap_log_error(APLOG_MARK, APLOG_NOTICE, 0, ap_server_conf, "%s NOTICE %s: phase=[%s] file=[%s] cache enabled",
MODULE_NAME, __func__, phase, c->code.path);
} else {
c->cache = CACHE_DISABLE;
}
return c;
}
static mod_mruby_code_t *ap_mrb_set_string(apr_pool_t *p, const char *arg)
{
mod_mruby_code_t *c = (mod_mruby_code_t *)apr_pcalloc(p, sizeof(mod_mruby_code_t));
TRACER;
c->type = MOD_MRUBY_STRING;
c->code.code = apr_pstrdup(p, arg);
return c;
}
static void mod_mruby_compile_code(mrb_state *mrb, mod_mruby_code_t *c, server_rec *s)
{
struct mrb_parser_state *p = NULL;
FILE *mrb_file;
c->ctx = mrbc_context_new(mrb);
TRACER;
if (c != NULL) {
if (c->type == MOD_MRUBY_STRING) {
mrbc_filename(mrb, c->ctx, "inline_conf");
p = mrb_parse_string(mrb, c->code.code, c->ctx);
c->proc = mrb_generate_code(mrb, p);
ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s, "%s DEBUG %s: mruby code string compiled: string=[%s] from "
"irep_idx_start=[%d] to irep_idx_end=[%d]",
MODULE_NAME, __func__, c->code.code, c->irep_idx_start, c->irep_idx_end);
} else if (c->type == MOD_MRUBY_FILE) {
if ((mrb_file = fopen(c->code.path, "r")) == NULL) {
ap_log_error(APLOG_MARK, APLOG_ERR, 0, s, "%s ERROR %s: mrb file open failed: %s", MODULE_NAME, __func__,
c->code.path);
c->proc = NULL;
return;
}
mrbc_filename(mrb, c->ctx, c->code.path);
p = mrb_parse_file(mrb, mrb_file, c->ctx);
fclose(mrb_file);
c->proc = mrb_generate_code(mrb, p);
ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s, "%s DEBUG %s: mruby code file compiled: path=[%s]from "
"irep_idx_start=[%d] to irep_idx_end=[%d]",
MODULE_NAME, __func__, c->code.path, c->irep_idx_start, c->irep_idx_end);
} else {
return;
}
mrb_pool_close(p->pool);
}
}
static void *mod_mruby_create_dir_config(apr_pool_t *p, char *dummy)
{
mruby_dir_config_t *dir_conf = (mruby_dir_config_t *)apr_pcalloc(p, sizeof(*dir_conf));
TRACER;
// inlinde core in httpd.conf
dir_conf->mod_mruby_handler_inline_code = NULL;
dir_conf->mod_mruby_handler_first_inline_code = NULL;
dir_conf->mod_mruby_handler_middle_inline_code = NULL;
dir_conf->mod_mruby_handler_last_inline_code = NULL;
dir_conf->mod_mruby_post_read_request_first_inline_code = NULL;
dir_conf->mod_mruby_post_read_request_middle_inline_code = NULL;
dir_conf->mod_mruby_post_read_request_last_inline_code = NULL;
dir_conf->mod_mruby_translate_name_first_inline_code = NULL;
dir_conf->mod_mruby_translate_name_middle_inline_code = NULL;
dir_conf->mod_mruby_translate_name_last_inline_code = NULL;
dir_conf->mod_mruby_map_to_storage_first_inline_code = NULL;
dir_conf->mod_mruby_map_to_storage_middle_inline_code = NULL;
dir_conf->mod_mruby_map_to_storage_last_inline_code = NULL;
dir_conf->mod_mruby_access_checker_first_inline_code = NULL;
dir_conf->mod_mruby_access_checker_middle_inline_code = NULL;
dir_conf->mod_mruby_access_checker_last_inline_code = NULL;
dir_conf->mod_mruby_check_user_id_first_inline_code = NULL;
dir_conf->mod_mruby_check_user_id_middle_inline_code = NULL;
dir_conf->mod_mruby_check_user_id_last_inline_code = NULL;
dir_conf->mod_mruby_auth_checker_first_inline_code = NULL;
dir_conf->mod_mruby_auth_checker_middle_inline_code = NULL;
dir_conf->mod_mruby_auth_checker_last_inline_code = NULL;
dir_conf->mod_mruby_fixups_first_inline_code = NULL;
dir_conf->mod_mruby_fixups_middle_inline_code = NULL;
dir_conf->mod_mruby_fixups_last_inline_code = NULL;
dir_conf->mod_mruby_log_transaction_first_inline_code = NULL;
dir_conf->mod_mruby_log_transaction_middle_inline_code = NULL;
dir_conf->mod_mruby_log_transaction_last_inline_code = NULL;
// hook script file
dir_conf->mod_mruby_handler_code = NULL;
dir_conf->mod_mruby_handler_first_code = NULL;
dir_conf->mod_mruby_handler_middle_code = NULL;
dir_conf->mod_mruby_handler_last_code = NULL;
dir_conf->mod_mruby_post_read_request_first_code = NULL;
dir_conf->mod_mruby_post_read_request_middle_code = NULL;
dir_conf->mod_mruby_post_read_request_last_code = NULL;
dir_conf->mod_mruby_translate_name_first_code = NULL;
dir_conf->mod_mruby_translate_name_middle_code = NULL;
dir_conf->mod_mruby_translate_name_last_code = NULL;
dir_conf->mod_mruby_map_to_storage_first_code = NULL;
dir_conf->mod_mruby_map_to_storage_middle_code = NULL;
dir_conf->mod_mruby_map_to_storage_last_code = NULL;
dir_conf->mod_mruby_access_checker_first_code = NULL;
dir_conf->mod_mruby_access_checker_middle_code = NULL;
dir_conf->mod_mruby_access_checker_last_code = NULL;
dir_conf->mod_mruby_check_user_id_first_code = NULL;
dir_conf->mod_mruby_check_user_id_middle_code = NULL;
dir_conf->mod_mruby_check_user_id_last_code = NULL;
dir_conf->mod_mruby_auth_checker_first_code = NULL;
dir_conf->mod_mruby_auth_checker_middle_code = NULL;
dir_conf->mod_mruby_auth_checker_last_code = NULL;
dir_conf->mod_mruby_fixups_first_code = NULL;
dir_conf->mod_mruby_fixups_middle_code = NULL;
dir_conf->mod_mruby_fixups_last_code = NULL;
dir_conf->mod_mruby_log_transaction_first_code = NULL;
dir_conf->mod_mruby_log_transaction_middle_code = NULL;
dir_conf->mod_mruby_log_transaction_last_code = NULL;
dir_conf->mod_mruby_authn_check_password_code = NULL;
dir_conf->mod_mruby_authn_get_realm_hash_code = NULL;
dir_conf->mod_mruby_output_filter_code = NULL;
return dir_conf;
}
static void *mod_mruby_create_config(apr_pool_t *p, server_rec *server)
{
mrb_state *mrb = ap_mrb_create_mrb_state();
ap_mrb_set_mrb_state(server->process->pconf, mrb);
TRACER;
mruby_config_t *conf = (mruby_config_t *)apr_pcalloc(p, sizeof(mruby_config_t));
conf->mod_mruby_child_init_first_code = NULL;
conf->mod_mruby_child_init_middle_code = NULL;
conf->mod_mruby_child_init_last_code = NULL;
conf->mod_mruby_post_config_first_code = NULL;
conf->mod_mruby_post_config_middle_code = NULL;
conf->mod_mruby_post_config_last_code = NULL;
conf->mod_mruby_quick_handler_first_code = NULL;
conf->mod_mruby_quick_handler_middle_code = NULL;
conf->mod_mruby_quick_handler_last_code = NULL;
conf->mod_mruby_insert_filter_first_code = NULL;
conf->mod_mruby_insert_filter_middle_code = NULL;
conf->mod_mruby_insert_filter_last_code = NULL;
conf->mruby_cache_table_size = 0;
conf->mruby_handler_enable = OFF;
return conf;
}
static const char *set_mod_mruby_handler_enable(cmd_parms *cmd, void *mconfig, int flag)
{
mruby_config_t *conf = (mruby_config_t *)ap_get_module_config(cmd->server->module_config, &mruby_module);
conf->mruby_handler_enable = flag;
return NULL;
}
//
// set cmds functions (for Ruby inline code)
//
#define SET_MOD_MRUBY_SERVER_INLINE_CMDS(hook) \
static const char *set_mod_mruby_##hook##_inline(cmd_parms * cmd, void *mconfig, const char *arg); \
static const char *set_mod_mruby_##hook##_inline(cmd_parms * cmd, void *mconfig, const char *arg) \
{ \
const char *err = ap_check_cmd_context(cmd, NOT_IN_LIMIT); \
mruby_config_t *conf = (mruby_config_t *)ap_get_module_config(cmd->server->module_config, &mruby_module); \
if (err != NULL) \
return err; \
conf->mod_mruby_##hook##_inline_code = ap_mrb_set_string(cmd->pool, arg); \
mod_mruby_compile_code(ap_mrb_get_mrb_state(cmd->server->process->pconf), conf->mod_mruby_##hook##_inline_code, \
cmd->server); \
return NULL; \
}
//
// set cmds functions (for Ruby file path)
//
#define SET_MOD_MRUBY_SERVER_CMDS(hook) \
static const char *set_mod_mruby_##hook(cmd_parms *cmd, void *mconfig, const char *path, const char *cache_opt); \
static const char *set_mod_mruby_##hook(cmd_parms *cmd, void *mconfig, const char *path, const char *cache_opt) \
{ \
const char *err = ap_check_cmd_context(cmd, NOT_IN_LIMIT); \
mruby_config_t *conf = (mruby_config_t *)ap_get_module_config(cmd->server->module_config, &mruby_module); \
TRACER; \
if (err != NULL) \
return err; \
conf->mod_mruby_##hook##_code = ap_mrb_set_file(cmd->pool, path, cache_opt, "" #hook ""); \
mod_mruby_compile_code(ap_mrb_get_mrb_state(cmd->server->process->pconf), conf->mod_mruby_##hook##_code, \
cmd->server); \
return NULL; \
}
SET_MOD_MRUBY_SERVER_CMDS(post_config_first);
SET_MOD_MRUBY_SERVER_CMDS(post_config_middle);
SET_MOD_MRUBY_SERVER_CMDS(post_config_last);
SET_MOD_MRUBY_SERVER_CMDS(child_init_first);
SET_MOD_MRUBY_SERVER_CMDS(child_init_middle);
SET_MOD_MRUBY_SERVER_CMDS(child_init_last);
SET_MOD_MRUBY_SERVER_CMDS(quick_handler_first);
SET_MOD_MRUBY_SERVER_CMDS(quick_handler_middle);
SET_MOD_MRUBY_SERVER_CMDS(quick_handler_last);
SET_MOD_MRUBY_SERVER_CMDS(insert_filter_first);
SET_MOD_MRUBY_SERVER_CMDS(insert_filter_middle);
SET_MOD_MRUBY_SERVER_CMDS(insert_filter_last);
#define SET_MOD_MRUBY_DIR_CMDS(hook) \
static const char *set_mod_mruby_##hook(cmd_parms *cmd, void *mconfig, const char *path, const char *cache_opt); \
static const char *set_mod_mruby_##hook(cmd_parms *cmd, void *mconfig, const char *path, const char *cache_opt) \
{ \
const char *err = ap_check_cmd_context(cmd, NOT_IN_LIMIT); \
mruby_dir_config_t *dir_conf = (mruby_dir_config_t *)mconfig; \
TRACER; \
if (err != NULL) \
return err; \
dir_conf->mod_mruby_##hook##_code = ap_mrb_set_file(cmd->pool, path, cache_opt, "" #hook ""); \
mod_mruby_compile_code(ap_mrb_get_mrb_state(cmd->server->process->pconf), dir_conf->mod_mruby_##hook##_code, \
cmd->server); \
return NULL; \
}
SET_MOD_MRUBY_DIR_CMDS(handler);
SET_MOD_MRUBY_DIR_CMDS(handler_first);
SET_MOD_MRUBY_DIR_CMDS(handler_middle);
SET_MOD_MRUBY_DIR_CMDS(handler_last);
SET_MOD_MRUBY_DIR_CMDS(post_read_request_first);
SET_MOD_MRUBY_DIR_CMDS(post_read_request_middle);
SET_MOD_MRUBY_DIR_CMDS(post_read_request_last);
SET_MOD_MRUBY_DIR_CMDS(translate_name_first);
SET_MOD_MRUBY_DIR_CMDS(translate_name_middle);
SET_MOD_MRUBY_DIR_CMDS(translate_name_last);
SET_MOD_MRUBY_DIR_CMDS(map_to_storage_first);
SET_MOD_MRUBY_DIR_CMDS(map_to_storage_middle);
SET_MOD_MRUBY_DIR_CMDS(map_to_storage_last);
SET_MOD_MRUBY_DIR_CMDS(access_checker_first);
SET_MOD_MRUBY_DIR_CMDS(access_checker_middle);
SET_MOD_MRUBY_DIR_CMDS(access_checker_last);
SET_MOD_MRUBY_DIR_CMDS(check_user_id_first);
SET_MOD_MRUBY_DIR_CMDS(check_user_id_middle);
SET_MOD_MRUBY_DIR_CMDS(check_user_id_last);
SET_MOD_MRUBY_DIR_CMDS(auth_checker_first);
SET_MOD_MRUBY_DIR_CMDS(auth_checker_middle);
SET_MOD_MRUBY_DIR_CMDS(auth_checker_last);
SET_MOD_MRUBY_DIR_CMDS(fixups_first);
SET_MOD_MRUBY_DIR_CMDS(fixups_middle);
SET_MOD_MRUBY_DIR_CMDS(fixups_last);
SET_MOD_MRUBY_DIR_CMDS(log_transaction_first);
SET_MOD_MRUBY_DIR_CMDS(log_transaction_middle);
SET_MOD_MRUBY_DIR_CMDS(log_transaction_last);
SET_MOD_MRUBY_DIR_CMDS(authn_check_password);
SET_MOD_MRUBY_DIR_CMDS(authn_get_realm_hash);
SET_MOD_MRUBY_DIR_CMDS(output_filter);
#define SET_MOD_MRUBY_DIR_INLINE_CMDS(hook) \
static const char *set_mod_mruby_##hook##_inline(cmd_parms * cmd, void *mconfig, const char *arg); \
static const char *set_mod_mruby_##hook##_inline(cmd_parms * cmd, void *mconfig, const char *arg) \
{ \
const char *err = ap_check_cmd_context(cmd, NOT_IN_LIMIT); \
mruby_dir_config_t *dir_conf = (mruby_dir_config_t *)mconfig; \
if (err != NULL) \
return err; \
dir_conf->mod_mruby_##hook##_inline_code = ap_mrb_set_string(cmd->pool, arg); \
mod_mruby_compile_code(ap_mrb_get_mrb_state(cmd->server->process->pconf), \
dir_conf->mod_mruby_##hook##_inline_code, cmd->server); \
return NULL; \
}
SET_MOD_MRUBY_DIR_INLINE_CMDS(handler);
SET_MOD_MRUBY_DIR_INLINE_CMDS(handler_first);
SET_MOD_MRUBY_DIR_INLINE_CMDS(handler_middle);
SET_MOD_MRUBY_DIR_INLINE_CMDS(handler_last);
SET_MOD_MRUBY_DIR_INLINE_CMDS(post_read_request_first);
SET_MOD_MRUBY_DIR_INLINE_CMDS(post_read_request_middle);
SET_MOD_MRUBY_DIR_INLINE_CMDS(post_read_request_last);
SET_MOD_MRUBY_DIR_INLINE_CMDS(translate_name_first);
SET_MOD_MRUBY_DIR_INLINE_CMDS(translate_name_middle);
SET_MOD_MRUBY_DIR_INLINE_CMDS(translate_name_last);
SET_MOD_MRUBY_DIR_INLINE_CMDS(map_to_storage_first);
SET_MOD_MRUBY_DIR_INLINE_CMDS(map_to_storage_middle);
SET_MOD_MRUBY_DIR_INLINE_CMDS(map_to_storage_last);
SET_MOD_MRUBY_DIR_INLINE_CMDS(access_checker_first);
SET_MOD_MRUBY_DIR_INLINE_CMDS(access_checker_middle);
SET_MOD_MRUBY_DIR_INLINE_CMDS(access_checker_last);
SET_MOD_MRUBY_DIR_INLINE_CMDS(check_user_id_first);
SET_MOD_MRUBY_DIR_INLINE_CMDS(check_user_id_middle);
SET_MOD_MRUBY_DIR_INLINE_CMDS(check_user_id_last);
SET_MOD_MRUBY_DIR_INLINE_CMDS(auth_checker_first);
SET_MOD_MRUBY_DIR_INLINE_CMDS(auth_checker_middle);
SET_MOD_MRUBY_DIR_INLINE_CMDS(auth_checker_last);
SET_MOD_MRUBY_DIR_INLINE_CMDS(fixups_first);
SET_MOD_MRUBY_DIR_INLINE_CMDS(fixups_middle);
SET_MOD_MRUBY_DIR_INLINE_CMDS(fixups_last);
SET_MOD_MRUBY_DIR_INLINE_CMDS(log_transaction_first);
SET_MOD_MRUBY_DIR_INLINE_CMDS(log_transaction_middle);
SET_MOD_MRUBY_DIR_INLINE_CMDS(log_transaction_last);
//
// run mruby core functions
//
static void ap_mruby_code_clean(mrb_state *mrb, struct RProc *proc, mod_mruby_code_t *code, request_rec *r)
{
TRACER;
mrbc_context_free(mrb, code->ctx);
}
static void ap_mruby_state_clean(mrb_state *mrb)
{
TRACER;
mrb->exc = 0;
}
// mruby_run for not request phase.
static int ap_mruby_run_nr(server_rec *s, mod_mruby_code_t *code)
{
mrb_state *mrb = ap_mrb_get_mrb_state(s->process->pconf);
// code->cache force enabled since this function only run at startup server
// phase
code->cache = CACHE_ENABLE;
ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, ap_server_conf,
"%s DEBUG %s: [CONFIG PHASE] [CACHE FORCE ENABLED] run mruby code: %s", MODULE_NAME, __func__,
code->code.path);
mrb_toplevel_run(mrb, code->proc);
if (mrb->exc) {
ap_mrb_raise_error(mrb, mrb_obj_value(mrb->exc), code);
}
ap_mruby_state_clean(mrb);
return APR_SUCCESS;
}
static int ap_mruby_run(mrb_state *mrb, request_rec *r, mod_mruby_code_t *code, int module_status)
{
int ai;
TRACER;
// mutex lock
if (apr_thread_mutex_lock(mod_mruby_mutex) != APR_SUCCESS) {
ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "%s ERROR %s: mod_mruby_mutex lock failed", MODULE_NAME, __func__);
return DECLINED;
}
ap_mrb_push_request(r);
if (code->cache == CACHE_DISABLE) {
// must be code->path
mod_mruby_compile_code(mrb, code, r->server);
if (code->proc == NULL) {
ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "%s ERROR %s: mruby proc is NULL, DECLINED phase, hook file: %s",
MODULE_NAME, __func__, code->code.path);
return DECLINED;
}
}
ai = mrb_gc_arena_save(mrb);
ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, "%s DEBUG %s: run mruby code: path=[%s] irep_idx=[%d]~[%d] cache=[%d]",
MODULE_NAME, __func__, code->code.path, code->irep_idx_start, code->irep_idx_end, code->cache);
ap_mrb_set_status_code(OK);
mrb_toplevel_run(mrb, code->proc);
mrb_gc_arena_restore(mrb, ai);
if (mrb->exc) {
ap_mrb_raise_error(mrb, mrb_obj_value(mrb->exc), code);
}
ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, "%s DEBUG %s: irep_idx=%d return mruby code(%d): %s", MODULE_NAME,
__func__, code->irep_idx_start, ap_mrb_get_status_code(), code->code.path);
if (code->cache == CACHE_DISABLE) {
ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, "%s DEBUG %s: irep cleaning", MODULE_NAME, __func__);
ap_mruby_code_clean(mrb, code->proc, code, r);
}
ap_mruby_state_clean(mrb);
// mutex unlock
if (apr_thread_mutex_unlock(mod_mruby_mutex) != APR_SUCCESS) {
ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "%s ERROR %s: mod_mruby_mutex unlock failed", MODULE_NAME, __func__);
return OK;
}
return ap_mrb_get_status_code();
}
static int ap_mruby_run_inline(mrb_state *mrb, request_rec *r, mod_mruby_code_t *c)
{
int ai;
// mutex lock
if (apr_thread_mutex_lock(mod_mruby_mutex) != APR_SUCCESS) {
ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "%s ERROR %s: mod_mruby_mutex lock failed", MODULE_NAME, __func__);
return OK;
}
ap_mrb_push_request(r);
ai = mrb_gc_arena_save(mrb);
ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, "%s DEBUG %s: irep[%d] inline core run: inline code = %s", MODULE_NAME,
__func__, c->irep_idx_start, c->code.code);
ap_mrb_set_status_code(OK);
mrb_toplevel_run(mrb, c->proc);
if (mrb->exc) {
ap_mrb_raise_error(mrb, mrb_obj_value(mrb->exc), c);
}
mrb_gc_arena_restore(mrb, ai);
ap_mruby_state_clean(mrb);
// mutex unlock
if (apr_thread_mutex_unlock(mod_mruby_mutex) != APR_SUCCESS) {
ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "%s ERROR %s: mod_mruby_mutex unlock failed", MODULE_NAME, __func__);
return OK;
}
return ap_mrb_get_status_code();
;
}
/*
static apr_status_t mod_mruby_hook_term(void *data)
{
mrb_close(mod_mruby_share_state);
return APR_SUCCESS;
}
*/
//
// hook functions (hook Ruby file path)
//
static int mod_mruby_preinit(apr_pool_t *p, apr_pool_t *plog, apr_pool_t *ptemp)
{
return OK;
}
static int mod_mruby_init(apr_pool_t *p, apr_pool_t *plog, apr_pool_t *ptemp, server_rec *s)
{
apr_status_t status = apr_thread_mutex_create(&mod_mruby_mutex, APR_THREAD_MUTEX_DEFAULT, p);
TRACER;
if (status != APR_SUCCESS) {
ap_log_error(APLOG_MARK, APLOG_ERR, 0, ap_server_conf, APLOGNO(05001) "%s ERROR %s: Error creating thread mutex.",
MODULE_NAME, __func__);
return DECLINED;
}
void *data = NULL;
const char *userdata_key = "mruby_init";
ap_log_error(APLOG_MARK, APLOG_INFO, 0, ap_server_conf,
APLOGNO(05002) "%s %s: main process / thread (pid=%d) initialized.", MODULE_NAME, __func__, getpid());
apr_pool_userdata_get(&data, userdata_key, p);
if (!data) {
apr_pool_userdata_set((const void *)1, userdata_key, apr_pool_cleanup_null, p);
}
ap_log_error(APLOG_MARK, APLOG_NOTICE, 0, ap_server_conf, APLOGNO(05003) "%s/%s (%s/%s) mechanism enabled",
MODULE_NAME, MODULE_VERSION, MRUBY_RUBY_ENGINE, MRUBY_VERSION);
return DECLINED;
}
static void mod_mruby_child_init(apr_pool_t *pool, server_rec *server)
{
TRACER;
ap_log_error(APLOG_MARK, APLOG_INFO, 0, ap_server_conf, "%s %s: child process (pid=%d) initialized.", MODULE_NAME,
__func__, getpid());
}
//
// register hook func before request phase (nr is not using request_rec)
//
#define MOD_MRUBY_REGISTER_HOOK_FUNC_NR_VOID(hook) \
static void mod_mruby_##hook(apr_pool_t *pool, server_rec *server); \
static void mod_mruby_##hook(apr_pool_t *pool, server_rec *server) \
{ \
mruby_config_t *conf = ap_get_module_config(server->module_config, &mruby_module); \
if (conf->mod_mruby_##hook##_code == NULL) \
return; \
ap_mruby_run_nr(server, conf->mod_mruby_##hook##_code); \
}
MOD_MRUBY_REGISTER_HOOK_FUNC_NR_VOID(child_init_first);
MOD_MRUBY_REGISTER_HOOK_FUNC_NR_VOID(child_init_middle);
MOD_MRUBY_REGISTER_HOOK_FUNC_NR_VOID(child_init_last);
#define MOD_MRUBY_REGISTER_HOOK_FUNC_NR_INT(hook) \
static int mod_mruby_##hook(apr_pool_t *p, apr_pool_t *plog, apr_pool_t *ptemp, server_rec *server); \
static int mod_mruby_##hook(apr_pool_t *p, apr_pool_t *plog, apr_pool_t *ptemp, server_rec *server) \
{ \
mruby_config_t *conf = ap_get_module_config(server->module_config, &mruby_module); \
if (conf->mod_mruby_##hook##_code == NULL) \
return DECLINED; \
ap_mruby_run_nr(server, conf->mod_mruby_##hook##_code); \
return OK; \
}
MOD_MRUBY_REGISTER_HOOK_FUNC_NR_INT(post_config_first);
MOD_MRUBY_REGISTER_HOOK_FUNC_NR_INT(post_config_middle);
MOD_MRUBY_REGISTER_HOOK_FUNC_NR_INT(post_config_last);
static int mod_mruby_handler(request_rec *r)
{
mruby_dir_config_t *dir_conf = ap_get_module_config(r->per_dir_config, &mruby_module);
mruby_config_t *conf = ap_get_module_config(r->server->module_config, &mruby_module);
TRACER;
if (!r->handler) {
return DECLINED;
}
if (!conf->mruby_handler_enable) {
return DECLINED;
}
if (strcmp(r->handler, "mruby-script") == 0) {
dir_conf->mod_mruby_handler_code = ap_mrb_set_file(r->pool, r->filename, NULL, "mruby-script");
} else {
return DECLINED;
}
return ap_mruby_run(ap_mrb_get_mrb_state(r->server->process->pconf), r, dir_conf->mod_mruby_handler_code, DECLINED);
}
//
// register hook func
//
#define MOD_MRUBY_REGISTER_HOOK_FUNC(hook) \
static int mod_mruby_##hook(request_rec *r); \
static int mod_mruby_##hook(request_rec *r) \
{ \
mruby_dir_config_t *dir_conf = ap_get_module_config(r->per_dir_config, &mruby_module); \
TRACER; \
if (dir_conf->mod_mruby_##hook##_code == NULL) \
return DECLINED; \
return ap_mruby_run(ap_mrb_get_mrb_state(r->server->process->pconf), r, dir_conf->mod_mruby_##hook##_code, OK); \
}
MOD_MRUBY_REGISTER_HOOK_FUNC(handler_first);
MOD_MRUBY_REGISTER_HOOK_FUNC(handler_middle);
MOD_MRUBY_REGISTER_HOOK_FUNC(handler_last);
MOD_MRUBY_REGISTER_HOOK_FUNC(post_read_request_first);
MOD_MRUBY_REGISTER_HOOK_FUNC(post_read_request_middle);
MOD_MRUBY_REGISTER_HOOK_FUNC(post_read_request_last);
MOD_MRUBY_REGISTER_HOOK_FUNC(translate_name_first);
MOD_MRUBY_REGISTER_HOOK_FUNC(translate_name_middle);
MOD_MRUBY_REGISTER_HOOK_FUNC(translate_name_last);
MOD_MRUBY_REGISTER_HOOK_FUNC(map_to_storage_first);
MOD_MRUBY_REGISTER_HOOK_FUNC(map_to_storage_middle);
MOD_MRUBY_REGISTER_HOOK_FUNC(map_to_storage_last);
MOD_MRUBY_REGISTER_HOOK_FUNC(access_checker_first);
MOD_MRUBY_REGISTER_HOOK_FUNC(access_checker_middle);
MOD_MRUBY_REGISTER_HOOK_FUNC(access_checker_last);
MOD_MRUBY_REGISTER_HOOK_FUNC(check_user_id_first);
MOD_MRUBY_REGISTER_HOOK_FUNC(check_user_id_middle);
MOD_MRUBY_REGISTER_HOOK_FUNC(check_user_id_last);
MOD_MRUBY_REGISTER_HOOK_FUNC(auth_checker_first);
MOD_MRUBY_REGISTER_HOOK_FUNC(auth_checker_middle);
MOD_MRUBY_REGISTER_HOOK_FUNC(auth_checker_last);
MOD_MRUBY_REGISTER_HOOK_FUNC(fixups_first);
MOD_MRUBY_REGISTER_HOOK_FUNC(fixups_middle);
MOD_MRUBY_REGISTER_HOOK_FUNC(fixups_last);
MOD_MRUBY_REGISTER_HOOK_FUNC(log_transaction_first);
MOD_MRUBY_REGISTER_HOOK_FUNC(log_transaction_middle);
MOD_MRUBY_REGISTER_HOOK_FUNC(log_transaction_last);
//
// register hook func with lookup
//
#define MOD_MRUBY_REGISTER_HOOK_FUNC_LOOKUP(hook) \
static int mod_mruby_##hook(request_rec *r, int lookup); \
static int mod_mruby_##hook(request_rec *r, int lookup) \
{ \
mruby_config_t *conf = ap_get_module_config(r->server->module_config, &mruby_module); \
if (conf->mod_mruby_##hook##_code == NULL) \
return DECLINED; \
return ap_mruby_run(ap_mrb_get_mrb_state(r->server->process->pconf), r, conf->mod_mruby_##hook##_code, OK); \
}
MOD_MRUBY_REGISTER_HOOK_FUNC_LOOKUP(quick_handler_first);
MOD_MRUBY_REGISTER_HOOK_FUNC_LOOKUP(quick_handler_middle);
MOD_MRUBY_REGISTER_HOOK_FUNC_LOOKUP(quick_handler_last);
//
// register hook void func
//
#define MOD_MRUBY_REGISTER_HOOK_FUNC_VOID(hook) \
static void mod_mruby_##hook(request_rec *r); \
static void mod_mruby_##hook(request_rec *r) \
{ \
mruby_config_t *conf = ap_get_module_config(r->server->module_config, &mruby_module); \
if (conf->mod_mruby_##hook##_code == NULL) \
return; \
ap_mruby_run(ap_mrb_get_mrb_state(r->server->process->pconf), r, conf->mod_mruby_##hook##_code, OK); \
}
MOD_MRUBY_REGISTER_HOOK_FUNC_VOID(insert_filter_first);
MOD_MRUBY_REGISTER_HOOK_FUNC_VOID(insert_filter_middle);
MOD_MRUBY_REGISTER_HOOK_FUNC_VOID(insert_filter_last);
static authn_status mod_mruby_authn_check_password(request_rec *r, const char *user, const char *password)
{
mruby_dir_config_t *dir_conf = ap_get_module_config(r->per_dir_config, &mruby_module);
if (dir_conf->mod_mruby_authn_check_password_code == NULL) {
return AUTH_GENERAL_ERROR;
}
ap_mrb_init_authnprovider_basic(r, user, password);
return ap_mruby_run(ap_mrb_get_mrb_state(r->server->process->pconf), r, dir_conf->mod_mruby_authn_check_password_code,
OK);
}
static authn_status mod_mruby_authn_get_realm_hash(request_rec *r, const char *user, const char *realm, char **rethash)
{
authn_status ret;
mruby_dir_config_t *dir_conf = ap_get_module_config(r->per_dir_config, &mruby_module);
if (dir_conf->mod_mruby_authn_get_realm_hash_code == NULL) {
return AUTH_GENERAL_ERROR;
}
ap_mrb_init_authnprovider_digest(r, user, realm);
ret = ap_mruby_run(ap_mrb_get_mrb_state(r->server->process->pconf), r, dir_conf->mod_mruby_authn_get_realm_hash_code,
OK);
*rethash = ap_mrb_get_authnprovider_digest_rethash();
return ret;
}
static apr_status_t mod_mruby_output_filter(ap_filter_t *f, apr_bucket_brigade *bb)
{
request_rec *r = f->r;
mruby_dir_config_t *dir_conf = ap_get_module_config(r->per_dir_config, &mruby_module);
if (dir_conf->mod_mruby_output_filter_code == NULL) {
return ap_pass_brigade(f->next, bb);
}
ap_mrb_set_filter_rec(f, bb, r->pool);
ap_mrb_push_request(r);
ap_mruby_run(ap_mrb_get_mrb_state(r->server->process->pconf), r, dir_conf->mod_mruby_output_filter_code, OK);
return ap_pass_brigade(f->next, bb);
}
static const authn_provider authn_mruby_provider = {&mod_mruby_authn_check_password, &mod_mruby_authn_get_realm_hash};
//
// hook functions (hook Ruby inline code in httpd.conf)
//
static int mod_mruby_handler_inline(request_rec *r)
{
mruby_dir_config_t *dir_conf = ap_get_module_config(r->per_dir_config, &mruby_module);
if (strcmp(r->handler, "mruby-native-script") != 0) {
return DECLINED;
}
return ap_mruby_run_inline(ap_mrb_get_mrb_state(r->server->process->pconf), r,
dir_conf->mod_mruby_handler_inline_code);
}
#define MOD_MRUBY_REGISTER_HOOK_FUNC_INLINE(hook) \
static int mod_mruby_##hook##_inline(request_rec * r); \
static int mod_mruby_##hook##_inline(request_rec * r) \
{ \
mruby_dir_config_t *dir_conf = ap_get_module_config(r->per_dir_config, &mruby_module); \
if (dir_conf->mod_mruby_##hook##_inline_code == NULL) \
return DECLINED; \
return ap_mruby_run_inline(ap_mrb_get_mrb_state(r->server->process->pconf), r, \
dir_conf->mod_mruby_##hook##_inline_code); \
}
MOD_MRUBY_REGISTER_HOOK_FUNC_INLINE(handler_first);
MOD_MRUBY_REGISTER_HOOK_FUNC_INLINE(handler_middle);
MOD_MRUBY_REGISTER_HOOK_FUNC_INLINE(handler_last);
MOD_MRUBY_REGISTER_HOOK_FUNC_INLINE(post_read_request_first);
MOD_MRUBY_REGISTER_HOOK_FUNC_INLINE(post_read_request_middle);
MOD_MRUBY_REGISTER_HOOK_FUNC_INLINE(post_read_request_last);
MOD_MRUBY_REGISTER_HOOK_FUNC_INLINE(translate_name_first);
MOD_MRUBY_REGISTER_HOOK_FUNC_INLINE(translate_name_middle);
MOD_MRUBY_REGISTER_HOOK_FUNC_INLINE(translate_name_last);
MOD_MRUBY_REGISTER_HOOK_FUNC_INLINE(map_to_storage_first);
MOD_MRUBY_REGISTER_HOOK_FUNC_INLINE(map_to_storage_middle);
MOD_MRUBY_REGISTER_HOOK_FUNC_INLINE(map_to_storage_last);
MOD_MRUBY_REGISTER_HOOK_FUNC_INLINE(access_checker_first);
MOD_MRUBY_REGISTER_HOOK_FUNC_INLINE(access_checker_middle);
MOD_MRUBY_REGISTER_HOOK_FUNC_INLINE(access_checker_last);
MOD_MRUBY_REGISTER_HOOK_FUNC_INLINE(check_user_id_first);
MOD_MRUBY_REGISTER_HOOK_FUNC_INLINE(check_user_id_middle);
MOD_MRUBY_REGISTER_HOOK_FUNC_INLINE(check_user_id_last);
MOD_MRUBY_REGISTER_HOOK_FUNC_INLINE(auth_checker_first);
MOD_MRUBY_REGISTER_HOOK_FUNC_INLINE(auth_checker_middle);
MOD_MRUBY_REGISTER_HOOK_FUNC_INLINE(auth_checker_last);
MOD_MRUBY_REGISTER_HOOK_FUNC_INLINE(fixups_first);
MOD_MRUBY_REGISTER_HOOK_FUNC_INLINE(fixups_middle);
MOD_MRUBY_REGISTER_HOOK_FUNC_INLINE(fixups_last);
MOD_MRUBY_REGISTER_HOOK_FUNC_INLINE(log_transaction_first);
MOD_MRUBY_REGISTER_HOOK_FUNC_INLINE(log_transaction_middle);
MOD_MRUBY_REGISTER_HOOK_FUNC_INLINE(log_transaction_last);
#define MOD_MRUBY_SET_ALL_REGISTER_INLINE(hook) \
ap_hook_##hook(mod_mruby_##hook##_first_inline, NULL, NULL, APR_HOOK_FIRST); \
ap_hook_##hook(mod_mruby_##hook##_middle_inline, NULL, NULL, APR_HOOK_MIDDLE); \
ap_hook_##hook(mod_mruby_##hook##_last_inline, NULL, NULL, APR_HOOK_LAST);
#define MOD_MRUBY_SET_ALL_REGISTER(hook) \
ap_hook_##hook(mod_mruby_##hook##_first, NULL, NULL, APR_HOOK_FIRST); \
ap_hook_##hook(mod_mruby_##hook##_middle, NULL, NULL, APR_HOOK_MIDDLE); \
ap_hook_##hook(mod_mruby_##hook##_last, NULL, NULL, APR_HOOK_LAST);
static void register_hooks(apr_pool_t *p)
{
TRACER;
// inline code in httpd.conf
ap_hook_handler(mod_mruby_handler_inline, NULL, NULL, APR_HOOK_MIDDLE);
MOD_MRUBY_SET_ALL_REGISTER_INLINE(handler);
MOD_MRUBY_SET_ALL_REGISTER_INLINE(post_read_request);
MOD_MRUBY_SET_ALL_REGISTER_INLINE(translate_name);
MOD_MRUBY_SET_ALL_REGISTER_INLINE(map_to_storage);
MOD_MRUBY_SET_ALL_REGISTER_INLINE(access_checker);
MOD_MRUBY_SET_ALL_REGISTER_INLINE(check_user_id);
MOD_MRUBY_SET_ALL_REGISTER_INLINE(auth_checker);
MOD_MRUBY_SET_ALL_REGISTER_INLINE(fixups);
MOD_MRUBY_SET_ALL_REGISTER_INLINE(log_transaction);
// hook script file
ap_hook_pre_config(mod_mruby_preinit, NULL, NULL, APR_HOOK_MIDDLE);
ap_hook_post_config(mod_mruby_init, NULL, NULL, APR_HOOK_MIDDLE);
ap_hook_child_init(mod_mruby_child_init, NULL, NULL, APR_HOOK_MIDDLE);
ap_hook_handler(mod_mruby_handler, NULL, NULL, APR_HOOK_REALLY_FIRST);
MOD_MRUBY_SET_ALL_REGISTER(handler);
MOD_MRUBY_SET_ALL_REGISTER(child_init);
MOD_MRUBY_SET_ALL_REGISTER(post_config);
MOD_MRUBY_SET_ALL_REGISTER(post_read_request);
MOD_MRUBY_SET_ALL_REGISTER(quick_handler);
MOD_MRUBY_SET_ALL_REGISTER(translate_name);
MOD_MRUBY_SET_ALL_REGISTER(map_to_storage);
MOD_MRUBY_SET_ALL_REGISTER(access_checker);
MOD_MRUBY_SET_ALL_REGISTER(check_user_id);
MOD_MRUBY_SET_ALL_REGISTER(auth_checker);
MOD_MRUBY_SET_ALL_REGISTER(fixups);
MOD_MRUBY_SET_ALL_REGISTER(insert_filter);
MOD_MRUBY_SET_ALL_REGISTER(log_transaction);
ap_register_provider(p, AUTHN_PROVIDER_GROUP, "mruby", "0", &authn_mruby_provider);
ap_register_output_filter("mruby", mod_mruby_output_filter, NULL, AP_FTYPE_CONTENT_SET);
// ap_register_input_filter( "MODMRUBYFILTER", mod_mruby_input_filter, NULL,
// AP_FTYPE_CONTENT_SET);
}
#define MOD_MRUBY_SET_ALL_CMDS_INLINE(hook, dir_name) \
AP_INIT_TAKE1("mruby" #dir_name "FirstCode", set_mod_mruby_##hook##_first_inline, NULL, RSRC_CONF | ACCESS_CONF, \
"hook inline code for " #hook " first phase."), \
AP_INIT_TAKE1("mruby" #dir_name "MiddleCode", set_mod_mruby_##hook##_middle_inline, NULL, \
RSRC_CONF | ACCESS_CONF, "hook inline code for " #hook " middle phase."), \
AP_INIT_TAKE1("mruby" #dir_name "LastCode", set_mod_mruby_##hook##_last_inline, NULL, RSRC_CONF | ACCESS_CONF, \
"hook inline code for " #hook " last phase.")
#define MOD_MRUBY_SET_ALL_CMDS(hook, dir_name) \
AP_INIT_TAKE12("mruby" #dir_name "First", set_mod_mruby_##hook##_first, NULL, RSRC_CONF | ACCESS_CONF, \
"hook Ruby file for " #hook " first phase."), \
AP_INIT_TAKE12("mruby" #dir_name "Middle", set_mod_mruby_##hook##_middle, NULL, RSRC_CONF | ACCESS_CONF, \
"hook Ruby file for " #hook " middle phase."), \
AP_INIT_TAKE12("mruby" #dir_name "Last", set_mod_mruby_##hook##_last, NULL, RSRC_CONF | ACCESS_CONF, \
"hook Ruby file for " #hook " last phase.")
static const command_rec mod_mruby_cmds[] = {
AP_INIT_FLAG("mrubyHandlerEnable", set_mod_mruby_handler_enable, NULL, RSRC_CONF | ACCESS_CONF,
"can use addhandler or sethandler for mruby-script. (default Off)"),
AP_INIT_TAKE1("mrubyHandlerCode", set_mod_mruby_handler_inline, NULL, RSRC_CONF | ACCESS_CONF,
"hook inline code for handler phase."),
MOD_MRUBY_SET_ALL_CMDS_INLINE(handler, Handler),
MOD_MRUBY_SET_ALL_CMDS_INLINE(post_read_request, PostReadRequest),
MOD_MRUBY_SET_ALL_CMDS_INLINE(translate_name, TranslateName),
MOD_MRUBY_SET_ALL_CMDS_INLINE(map_to_storage, MapToStorage),
MOD_MRUBY_SET_ALL_CMDS_INLINE(access_checker, AccessChecker),
MOD_MRUBY_SET_ALL_CMDS_INLINE(check_user_id, CheckUserId),
MOD_MRUBY_SET_ALL_CMDS_INLINE(auth_checker, AuthChecker),
MOD_MRUBY_SET_ALL_CMDS_INLINE(fixups, Fixups),
MOD_MRUBY_SET_ALL_CMDS_INLINE(log_transaction, LogTransaction),
AP_INIT_TAKE12("mrubyHandler", set_mod_mruby_handler, NULL, RSRC_CONF | ACCESS_CONF, "hook for handler phase."),
MOD_MRUBY_SET_ALL_CMDS(handler, Handler),
MOD_MRUBY_SET_ALL_CMDS(post_config, PostConfig),
MOD_MRUBY_SET_ALL_CMDS(child_init, ChildInit),
MOD_MRUBY_SET_ALL_CMDS(post_read_request, PostReadRequest),
MOD_MRUBY_SET_ALL_CMDS(quick_handler, QuickHandler),
MOD_MRUBY_SET_ALL_CMDS(translate_name, TranslateName),
MOD_MRUBY_SET_ALL_CMDS(map_to_storage, MapToStorage),
MOD_MRUBY_SET_ALL_CMDS(access_checker, AccessChecker),
MOD_MRUBY_SET_ALL_CMDS(check_user_id, CheckUserId),
MOD_MRUBY_SET_ALL_CMDS(auth_checker, AuthChecker),
MOD_MRUBY_SET_ALL_CMDS(fixups, Fixups),
MOD_MRUBY_SET_ALL_CMDS(insert_filter, InsertFilter),
MOD_MRUBY_SET_ALL_CMDS(log_transaction, LogTransaction),
AP_INIT_TAKE12("mrubyAuthnCheckPassword", set_mod_mruby_authn_check_password, NULL, RSRC_CONF | ACCESS_CONF,
"hook for authn basic."),
AP_INIT_TAKE12("mrubyAuthnGetRealmHash", set_mod_mruby_authn_get_realm_hash, NULL, RSRC_CONF | ACCESS_CONF,
"hook for authn digest."),
AP_INIT_TAKE12("mrubyOutputFilter", set_mod_mruby_output_filter, NULL, RSRC_CONF | ACCESS_CONF,
"set mruby output filter script."),
{NULL}};
#ifdef __APACHE24__
AP_DECLARE_MODULE(mruby) = {
#else
module AP_MODULE_DECLARE_DATA mruby_module = {
#endif
STANDARD20_MODULE_STUFF, mod_mruby_create_dir_config, /* dir config creater */
NULL, /* dir merger */
mod_mruby_create_config, /* server config */
NULL, /* merge server config */
mod_mruby_cmds, /* command apr_table_t */
register_hooks /* register hooks */
};
|
698259.c | /* Control flow instruction */
#include <stdint.h>
void main(void)
{
volatile int32_t a = 0xc907830f, b = 0xc27c9d8b, c = 0;
if (a > b) {
c = 1; //$br
} else {
c = -1; //$br
}
return; //$bre
}
|
197552.c | /*
* Copyright 2018 The Emscripten Authors. All rights reserved.
* Emscripten is available under two separate licenses, the MIT license and the
* University of Illinois/NCSA Open Source License. Both these licenses can be
* found in the LICENSE file.
*/
#include <stdlib.h>
#include <setjmp.h>
#include <stdio.h>
#include <assert.h>
#include <stdint.h>
jmp_buf jb;
__attribute__((noinline)) void foo(int64_t x) {
printf("foo: %lld.\n", x);
longjmp(jb, 1);
}
__attribute__((noinline)) int64_t bar() {
return (uint64_t)-2;
}
int main()
{
if (!setjmp(jb)) {
foo((uint64_t)-1);
return 0;
} else {
printf("bar: %lld.\n", bar());
return 1;
}
}
|
60186.c | /** @file
LZMA Decompress GUIDed Section Extraction Library.
It wraps Lzma decompress interfaces to GUIDed Section Extraction interfaces
and registers them into GUIDed handler table.
Copyright (c) 2009 - 2011, 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 "LzmaDecompressLibInternal.h"
/**
Examines a GUIDed section and returns the size of the decoded buffer and the
size of an scratch buffer required to actually decode the data in a GUIDed section.
Examines a GUIDed section specified by InputSection.
If GUID for InputSection does not match the GUID that this handler supports,
then RETURN_UNSUPPORTED is returned.
If the required information can not be retrieved from InputSection,
then RETURN_INVALID_PARAMETER is returned.
If the GUID of InputSection does match the GUID that this handler supports,
then the size required to hold the decoded buffer is returned in OututBufferSize,
the size of an optional scratch buffer is returned in ScratchSize, and the Attributes field
from EFI_GUID_DEFINED_SECTION header of InputSection is returned in SectionAttribute.
If InputSection is NULL, then ASSERT().
If OutputBufferSize is NULL, then ASSERT().
If ScratchBufferSize is NULL, then ASSERT().
If SectionAttribute is NULL, then ASSERT().
@param[in] InputSection A pointer to a GUIDed section of an FFS formatted file.
@param[out] OutputBufferSize A pointer to the size, in bytes, of an output buffer required
if the buffer specified by InputSection were decoded.
@param[out] ScratchBufferSize A pointer to the size, in bytes, required as scratch space
if the buffer specified by InputSection were decoded.
@param[out] SectionAttribute A pointer to the attributes of the GUIDed section. See the Attributes
field of EFI_GUID_DEFINED_SECTION in the PI Specification.
@retval RETURN_SUCCESS The information about InputSection was returned.
@retval RETURN_UNSUPPORTED The section specified by InputSection does not match the GUID this handler supports.
@retval RETURN_INVALID_PARAMETER The information can not be retrieved from the section specified by InputSection.
**/
RETURN_STATUS
EFIAPI
LzmaGuidedSectionGetInfo (
IN CONST VOID *InputSection,
OUT UINT32 *OutputBufferSize,
OUT UINT32 *ScratchBufferSize,
OUT UINT16 *SectionAttribute
)
{
ASSERT (InputSection != NULL);
ASSERT (OutputBufferSize != NULL);
ASSERT (ScratchBufferSize != NULL);
ASSERT (SectionAttribute != NULL);
if (IS_SECTION2 (InputSection)) {
if (!CompareGuid (
&gLzmaCustomDecompressGuid,
&(((EFI_GUID_DEFINED_SECTION2 *) InputSection)->SectionDefinitionGuid))) {
return RETURN_INVALID_PARAMETER;
}
*SectionAttribute = ((EFI_GUID_DEFINED_SECTION2 *) InputSection)->Attributes;
return LzmaUefiDecompressGetInfo (
(UINT8 *) InputSection + ((EFI_GUID_DEFINED_SECTION2 *) InputSection)->DataOffset,
SECTION2_SIZE (InputSection) - ((EFI_GUID_DEFINED_SECTION2 *) InputSection)->DataOffset,
OutputBufferSize,
ScratchBufferSize
);
} else {
if (!CompareGuid (
&gLzmaCustomDecompressGuid,
&(((EFI_GUID_DEFINED_SECTION *) InputSection)->SectionDefinitionGuid))) {
return RETURN_INVALID_PARAMETER;
}
*SectionAttribute = ((EFI_GUID_DEFINED_SECTION *) InputSection)->Attributes;
return LzmaUefiDecompressGetInfo (
(UINT8 *) InputSection + ((EFI_GUID_DEFINED_SECTION *) InputSection)->DataOffset,
SECTION_SIZE (InputSection) - ((EFI_GUID_DEFINED_SECTION *) InputSection)->DataOffset,
OutputBufferSize,
ScratchBufferSize
);
}
}
/**
Decompress a LZAM compressed GUIDed section into a caller allocated output buffer.
Decodes the GUIDed section specified by InputSection.
If GUID for InputSection does not match the GUID that this handler supports, then RETURN_UNSUPPORTED is returned.
If the data in InputSection can not be decoded, then RETURN_INVALID_PARAMETER is returned.
If the GUID of InputSection does match the GUID that this handler supports, then InputSection
is decoded into the buffer specified by OutputBuffer and the authentication status of this
decode operation is returned in AuthenticationStatus. If the decoded buffer is identical to the
data in InputSection, then OutputBuffer is set to point at the data in InputSection. Otherwise,
the decoded data will be placed in caller allocated buffer specified by OutputBuffer.
If InputSection is NULL, then ASSERT().
If OutputBuffer is NULL, then ASSERT().
If ScratchBuffer is NULL and this decode operation requires a scratch buffer, then ASSERT().
If AuthenticationStatus is NULL, then ASSERT().
@param[in] InputSection A pointer to a GUIDed section of an FFS formatted file.
@param[out] OutputBuffer A pointer to a buffer that contains the result of a decode operation.
@param[out] ScratchBuffer A caller allocated buffer that may be required by this function
as a scratch buffer to perform the decode operation.
@param[out] AuthenticationStatus
A pointer to the authentication status of the decoded output buffer.
See the definition of authentication status in the EFI_PEI_GUIDED_SECTION_EXTRACTION_PPI
section of the PI Specification. EFI_AUTH_STATUS_PLATFORM_OVERRIDE must
never be set by this handler.
@retval RETURN_SUCCESS The buffer specified by InputSection was decoded.
@retval RETURN_UNSUPPORTED The section specified by InputSection does not match the GUID this handler supports.
@retval RETURN_INVALID_PARAMETER The section specified by InputSection can not be decoded.
**/
RETURN_STATUS
EFIAPI
LzmaGuidedSectionExtraction (
IN CONST VOID *InputSection,
OUT VOID **OutputBuffer,
OUT VOID *ScratchBuffer, OPTIONAL
OUT UINT32 *AuthenticationStatus
)
{
ASSERT (OutputBuffer != NULL);
ASSERT (InputSection != NULL);
if (IS_SECTION2 (InputSection)) {
if (!CompareGuid (
&gLzmaCustomDecompressGuid,
&(((EFI_GUID_DEFINED_SECTION2 *) InputSection)->SectionDefinitionGuid))) {
return RETURN_INVALID_PARAMETER;
}
//
// Authentication is set to Zero, which may be ignored.
//
*AuthenticationStatus = 0;
return LzmaUefiDecompress (
(UINT8 *) InputSection + ((EFI_GUID_DEFINED_SECTION2 *) InputSection)->DataOffset,
SECTION2_SIZE (InputSection) - ((EFI_GUID_DEFINED_SECTION2 *) InputSection)->DataOffset,
*OutputBuffer,
ScratchBuffer
);
} else {
if (!CompareGuid (
&gLzmaCustomDecompressGuid,
&(((EFI_GUID_DEFINED_SECTION *) InputSection)->SectionDefinitionGuid))) {
return RETURN_INVALID_PARAMETER;
}
//
// Authentication is set to Zero, which may be ignored.
//
*AuthenticationStatus = 0;
return LzmaUefiDecompress (
(UINT8 *) InputSection + ((EFI_GUID_DEFINED_SECTION *) InputSection)->DataOffset,
SECTION_SIZE (InputSection) - ((EFI_GUID_DEFINED_SECTION *) InputSection)->DataOffset,
*OutputBuffer,
ScratchBuffer
);
}
}
/**
Register LzmaDecompress and LzmaDecompressGetInfo handlers with LzmaCustomerDecompressGuid.
@retval RETURN_SUCCESS Register successfully.
@retval RETURN_OUT_OF_RESOURCES No enough memory to store this handler.
**/
EFI_STATUS
EFIAPI
LzmaDecompressLibConstructor (
)
{
return ExtractGuidedSectionRegisterHandlers (
&gLzmaCustomDecompressGuid,
LzmaGuidedSectionGetInfo,
LzmaGuidedSectionExtraction
);
}
|
844406.c | /*
* Copyright (c) 2014 The WebM project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include <emmintrin.h> // SSE2
#include "./vpx_dsp_rtcd.h"
#include "vpx_ports/mem.h"
#include "vpx_ports/emmintrin_compat.h"
static INLINE __m128i signed_char_clamp_bd_sse2(__m128i value, int bd) {
__m128i ubounded;
__m128i lbounded;
__m128i retval;
const __m128i zero = _mm_set1_epi16(0);
const __m128i one = _mm_set1_epi16(1);
__m128i t80, max, min;
if (bd == 8) {
t80 = _mm_set1_epi16(0x80);
max = _mm_subs_epi16(
_mm_subs_epi16(_mm_slli_epi16(one, 8), one), t80);
} else if (bd == 10) {
t80 = _mm_set1_epi16(0x200);
max = _mm_subs_epi16(
_mm_subs_epi16(_mm_slli_epi16(one, 10), one), t80);
} else { // bd == 12
t80 = _mm_set1_epi16(0x800);
max = _mm_subs_epi16(
_mm_subs_epi16(_mm_slli_epi16(one, 12), one), t80);
}
min = _mm_subs_epi16(zero, t80);
ubounded = _mm_cmpgt_epi16(value, max);
lbounded = _mm_cmplt_epi16(value, min);
retval = _mm_andnot_si128(_mm_or_si128(ubounded, lbounded), value);
ubounded = _mm_and_si128(ubounded, max);
lbounded = _mm_and_si128(lbounded, min);
retval = _mm_or_si128(retval, ubounded);
retval = _mm_or_si128(retval, lbounded);
return retval;
}
// TODO(debargha, peter): Break up large functions into smaller ones
// in this file.
static void highbd_mb_lpf_horizontal_edge_w_sse2_8(uint16_t *s,
int p,
const uint8_t *_blimit,
const uint8_t *_limit,
const uint8_t *_thresh,
int bd) {
const __m128i zero = _mm_set1_epi16(0);
const __m128i one = _mm_set1_epi16(1);
__m128i blimit, limit, thresh;
__m128i q7, p7, q6, p6, q5, p5, q4, p4, q3, p3, q2, p2, q1, p1, q0, p0;
__m128i mask, hev, flat, flat2, abs_p1p0, abs_q1q0;
__m128i ps1, qs1, ps0, qs0;
__m128i abs_p0q0, abs_p1q1, ffff, work;
__m128i filt, work_a, filter1, filter2;
__m128i flat2_q6, flat2_p6, flat2_q5, flat2_p5, flat2_q4, flat2_p4;
__m128i flat2_q3, flat2_p3, flat2_q2, flat2_p2, flat2_q1, flat2_p1;
__m128i flat2_q0, flat2_p0;
__m128i flat_q2, flat_p2, flat_q1, flat_p1, flat_q0, flat_p0;
__m128i pixelFilter_p, pixelFilter_q;
__m128i pixetFilter_p2p1p0, pixetFilter_q2q1q0;
__m128i sum_p7, sum_q7, sum_p3, sum_q3;
__m128i t4, t3, t80, t1;
__m128i eight, four;
if (bd == 8) {
blimit = _mm_unpacklo_epi8(_mm_load_si128((const __m128i *)_blimit), zero);
limit = _mm_unpacklo_epi8(_mm_load_si128((const __m128i *)_limit), zero);
thresh = _mm_unpacklo_epi8(_mm_load_si128((const __m128i *)_thresh), zero);
} else if (bd == 10) {
blimit = _mm_slli_epi16(
_mm_unpacklo_epi8(_mm_load_si128((const __m128i *)_blimit), zero), 2);
limit = _mm_slli_epi16(
_mm_unpacklo_epi8(_mm_load_si128((const __m128i *)_limit), zero), 2);
thresh = _mm_slli_epi16(
_mm_unpacklo_epi8(_mm_load_si128((const __m128i *)_thresh), zero), 2);
} else { // bd == 12
blimit = _mm_slli_epi16(
_mm_unpacklo_epi8(_mm_load_si128((const __m128i *)_blimit), zero), 4);
limit = _mm_slli_epi16(
_mm_unpacklo_epi8(_mm_load_si128((const __m128i *)_limit), zero), 4);
thresh = _mm_slli_epi16(
_mm_unpacklo_epi8(_mm_load_si128((const __m128i *)_thresh), zero), 4);
}
q4 = _mm_load_si128((__m128i *)(s + 4 * p));
p4 = _mm_load_si128((__m128i *)(s - 5 * p));
q3 = _mm_load_si128((__m128i *)(s + 3 * p));
p3 = _mm_load_si128((__m128i *)(s - 4 * p));
q2 = _mm_load_si128((__m128i *)(s + 2 * p));
p2 = _mm_load_si128((__m128i *)(s - 3 * p));
q1 = _mm_load_si128((__m128i *)(s + 1 * p));
p1 = _mm_load_si128((__m128i *)(s - 2 * p));
q0 = _mm_load_si128((__m128i *)(s + 0 * p));
p0 = _mm_load_si128((__m128i *)(s - 1 * p));
// highbd_filter_mask
abs_p1p0 = _mm_or_si128(_mm_subs_epu16(p1, p0), _mm_subs_epu16(p0, p1));
abs_q1q0 = _mm_or_si128(_mm_subs_epu16(q1, q0), _mm_subs_epu16(q0, q1));
ffff = _mm_cmpeq_epi16(abs_p1p0, abs_p1p0);
abs_p0q0 = _mm_or_si128(_mm_subs_epu16(p0, q0), _mm_subs_epu16(q0, p0));
abs_p1q1 = _mm_or_si128(_mm_subs_epu16(p1, q1), _mm_subs_epu16(q1, p1));
// highbd_hev_mask (in C code this is actually called from highbd_filter4)
flat = _mm_max_epi16(abs_p1p0, abs_q1q0);
hev = _mm_subs_epu16(flat, thresh);
hev = _mm_xor_si128(_mm_cmpeq_epi16(hev, zero), ffff);
abs_p0q0 =_mm_adds_epu16(abs_p0q0, abs_p0q0); // abs(p0 - q0) * 2
abs_p1q1 = _mm_srli_epi16(abs_p1q1, 1); // abs(p1 - q1) / 2
mask = _mm_subs_epu16(_mm_adds_epu16(abs_p0q0, abs_p1q1), blimit);
mask = _mm_xor_si128(_mm_cmpeq_epi16(mask, zero), ffff);
mask = _mm_and_si128(mask, _mm_adds_epu16(limit, one));
work = _mm_max_epi16(_mm_or_si128(_mm_subs_epu16(p1, p0),
_mm_subs_epu16(p0, p1)),
_mm_or_si128(_mm_subs_epu16(q1, q0),
_mm_subs_epu16(q0, q1)));
mask = _mm_max_epi16(work, mask);
work = _mm_max_epi16(_mm_or_si128(_mm_subs_epu16(p2, p1),
_mm_subs_epu16(p1, p2)),
_mm_or_si128(_mm_subs_epu16(q2, q1),
_mm_subs_epu16(q1, q2)));
mask = _mm_max_epi16(work, mask);
work = _mm_max_epi16(_mm_or_si128(_mm_subs_epu16(p3, p2),
_mm_subs_epu16(p2, p3)),
_mm_or_si128(_mm_subs_epu16(q3, q2),
_mm_subs_epu16(q2, q3)));
mask = _mm_max_epi16(work, mask);
mask = _mm_subs_epu16(mask, limit);
mask = _mm_cmpeq_epi16(mask, zero); // return ~mask
// lp filter
// highbd_filter4
t4 = _mm_set1_epi16(4);
t3 = _mm_set1_epi16(3);
if (bd == 8)
t80 = _mm_set1_epi16(0x80);
else if (bd == 10)
t80 = _mm_set1_epi16(0x200);
else // bd == 12
t80 = _mm_set1_epi16(0x800);
t1 = _mm_set1_epi16(0x1);
ps1 = _mm_subs_epi16(p1, t80);
qs1 = _mm_subs_epi16(q1, t80);
ps0 = _mm_subs_epi16(p0, t80);
qs0 = _mm_subs_epi16(q0, t80);
filt = _mm_and_si128(
signed_char_clamp_bd_sse2(_mm_subs_epi16(ps1, qs1), bd), hev);
work_a = _mm_subs_epi16(qs0, ps0);
filt = _mm_adds_epi16(filt, work_a);
filt = _mm_adds_epi16(filt, work_a);
filt = signed_char_clamp_bd_sse2(_mm_adds_epi16(filt, work_a), bd);
filt = _mm_and_si128(filt, mask);
filter1 = signed_char_clamp_bd_sse2(_mm_adds_epi16(filt, t4), bd);
filter2 = signed_char_clamp_bd_sse2(_mm_adds_epi16(filt, t3), bd);
// Filter1 >> 3
filter1 = _mm_srai_epi16(filter1, 0x3);
filter2 = _mm_srai_epi16(filter2, 0x3);
qs0 = _mm_adds_epi16(
signed_char_clamp_bd_sse2(_mm_subs_epi16(qs0, filter1), bd),
t80);
ps0 = _mm_adds_epi16(
signed_char_clamp_bd_sse2(_mm_adds_epi16(ps0, filter2), bd),
t80);
filt = _mm_adds_epi16(filter1, t1);
filt = _mm_srai_epi16(filt, 1);
filt = _mm_andnot_si128(hev, filt);
qs1 = _mm_adds_epi16(
signed_char_clamp_bd_sse2(_mm_subs_epi16(qs1, filt), bd),
t80);
ps1 = _mm_adds_epi16(
signed_char_clamp_bd_sse2(_mm_adds_epi16(ps1, filt), bd),
t80);
// end highbd_filter4
// loopfilter done
// highbd_flat_mask4
flat = _mm_max_epi16(_mm_or_si128(_mm_subs_epu16(p2, p0),
_mm_subs_epu16(p0, p2)),
_mm_or_si128(_mm_subs_epu16(p3, p0),
_mm_subs_epu16(p0, p3)));
work = _mm_max_epi16(_mm_or_si128(_mm_subs_epu16(q2, q0),
_mm_subs_epu16(q0, q2)),
_mm_or_si128(_mm_subs_epu16(q3, q0),
_mm_subs_epu16(q0, q3)));
flat = _mm_max_epi16(work, flat);
work = _mm_max_epi16(abs_p1p0, abs_q1q0);
flat = _mm_max_epi16(work, flat);
if (bd == 8)
flat = _mm_subs_epu16(flat, one);
else if (bd == 10)
flat = _mm_subs_epu16(flat, _mm_slli_epi16(one, 2));
else // bd == 12
flat = _mm_subs_epu16(flat, _mm_slli_epi16(one, 4));
flat = _mm_cmpeq_epi16(flat, zero);
// end flat_mask4
// flat & mask = flat && mask (as used in filter8)
// (because, in both vars, each block of 16 either all 1s or all 0s)
flat = _mm_and_si128(flat, mask);
p5 = _mm_load_si128((__m128i *)(s - 6 * p));
q5 = _mm_load_si128((__m128i *)(s + 5 * p));
p6 = _mm_load_si128((__m128i *)(s - 7 * p));
q6 = _mm_load_si128((__m128i *)(s + 6 * p));
p7 = _mm_load_si128((__m128i *)(s - 8 * p));
q7 = _mm_load_si128((__m128i *)(s + 7 * p));
// highbd_flat_mask5 (arguments passed in are p0, q0, p4-p7, q4-q7
// but referred to as p0-p4 & q0-q4 in fn)
flat2 = _mm_max_epi16(_mm_or_si128(_mm_subs_epu16(p4, p0),
_mm_subs_epu16(p0, p4)),
_mm_or_si128(_mm_subs_epu16(q4, q0),
_mm_subs_epu16(q0, q4)));
work = _mm_max_epi16(_mm_or_si128(_mm_subs_epu16(p5, p0),
_mm_subs_epu16(p0, p5)),
_mm_or_si128(_mm_subs_epu16(q5, q0),
_mm_subs_epu16(q0, q5)));
flat2 = _mm_max_epi16(work, flat2);
work = _mm_max_epi16(_mm_or_si128(_mm_subs_epu16(p6, p0),
_mm_subs_epu16(p0, p6)),
_mm_or_si128(_mm_subs_epu16(q6, q0),
_mm_subs_epu16(q0, q6)));
flat2 = _mm_max_epi16(work, flat2);
work = _mm_max_epi16(_mm_or_si128(_mm_subs_epu16(p7, p0),
_mm_subs_epu16(p0, p7)),
_mm_or_si128(_mm_subs_epu16(q7, q0),
_mm_subs_epu16(q0, q7)));
flat2 = _mm_max_epi16(work, flat2);
if (bd == 8)
flat2 = _mm_subs_epu16(flat2, one);
else if (bd == 10)
flat2 = _mm_subs_epu16(flat2, _mm_slli_epi16(one, 2));
else // bd == 12
flat2 = _mm_subs_epu16(flat2, _mm_slli_epi16(one, 4));
flat2 = _mm_cmpeq_epi16(flat2, zero);
flat2 = _mm_and_si128(flat2, flat); // flat2 & flat & mask
// end highbd_flat_mask5
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// flat and wide flat calculations
eight = _mm_set1_epi16(8);
four = _mm_set1_epi16(4);
pixelFilter_p = _mm_add_epi16(_mm_add_epi16(p6, p5),
_mm_add_epi16(p4, p3));
pixelFilter_q = _mm_add_epi16(_mm_add_epi16(q6, q5),
_mm_add_epi16(q4, q3));
pixetFilter_p2p1p0 = _mm_add_epi16(p0, _mm_add_epi16(p2, p1));
pixelFilter_p = _mm_add_epi16(pixelFilter_p, pixetFilter_p2p1p0);
pixetFilter_q2q1q0 = _mm_add_epi16(q0, _mm_add_epi16(q2, q1));
pixelFilter_q = _mm_add_epi16(pixelFilter_q, pixetFilter_q2q1q0);
pixelFilter_p = _mm_add_epi16(eight, _mm_add_epi16(pixelFilter_p,
pixelFilter_q));
pixetFilter_p2p1p0 = _mm_add_epi16(four,
_mm_add_epi16(pixetFilter_p2p1p0,
pixetFilter_q2q1q0));
flat2_p0 = _mm_srli_epi16(_mm_add_epi16(pixelFilter_p,
_mm_add_epi16(p7, p0)), 4);
flat2_q0 = _mm_srli_epi16(_mm_add_epi16(pixelFilter_p,
_mm_add_epi16(q7, q0)), 4);
flat_p0 = _mm_srli_epi16(_mm_add_epi16(pixetFilter_p2p1p0,
_mm_add_epi16(p3, p0)), 3);
flat_q0 = _mm_srli_epi16(_mm_add_epi16(pixetFilter_p2p1p0,
_mm_add_epi16(q3, q0)), 3);
sum_p7 = _mm_add_epi16(p7, p7);
sum_q7 = _mm_add_epi16(q7, q7);
sum_p3 = _mm_add_epi16(p3, p3);
sum_q3 = _mm_add_epi16(q3, q3);
pixelFilter_q = _mm_sub_epi16(pixelFilter_p, p6);
pixelFilter_p = _mm_sub_epi16(pixelFilter_p, q6);
flat2_p1 = _mm_srli_epi16(
_mm_add_epi16(pixelFilter_p, _mm_add_epi16(sum_p7, p1)), 4);
flat2_q1 = _mm_srli_epi16(
_mm_add_epi16(pixelFilter_q, _mm_add_epi16(sum_q7, q1)), 4);
pixetFilter_q2q1q0 = _mm_sub_epi16(pixetFilter_p2p1p0, p2);
pixetFilter_p2p1p0 = _mm_sub_epi16(pixetFilter_p2p1p0, q2);
flat_p1 = _mm_srli_epi16(_mm_add_epi16(pixetFilter_p2p1p0,
_mm_add_epi16(sum_p3, p1)), 3);
flat_q1 = _mm_srli_epi16(_mm_add_epi16(pixetFilter_q2q1q0,
_mm_add_epi16(sum_q3, q1)), 3);
sum_p7 = _mm_add_epi16(sum_p7, p7);
sum_q7 = _mm_add_epi16(sum_q7, q7);
sum_p3 = _mm_add_epi16(sum_p3, p3);
sum_q3 = _mm_add_epi16(sum_q3, q3);
pixelFilter_p = _mm_sub_epi16(pixelFilter_p, q5);
pixelFilter_q = _mm_sub_epi16(pixelFilter_q, p5);
flat2_p2 = _mm_srli_epi16(_mm_add_epi16(pixelFilter_p,
_mm_add_epi16(sum_p7, p2)), 4);
flat2_q2 = _mm_srli_epi16(_mm_add_epi16(pixelFilter_q,
_mm_add_epi16(sum_q7, q2)), 4);
pixetFilter_p2p1p0 = _mm_sub_epi16(pixetFilter_p2p1p0, q1);
pixetFilter_q2q1q0 = _mm_sub_epi16(pixetFilter_q2q1q0, p1);
flat_p2 = _mm_srli_epi16(_mm_add_epi16(pixetFilter_p2p1p0,
_mm_add_epi16(sum_p3, p2)), 3);
flat_q2 = _mm_srli_epi16(_mm_add_epi16(pixetFilter_q2q1q0,
_mm_add_epi16(sum_q3, q2)), 3);
sum_p7 = _mm_add_epi16(sum_p7, p7);
sum_q7 = _mm_add_epi16(sum_q7, q7);
pixelFilter_p = _mm_sub_epi16(pixelFilter_p, q4);
pixelFilter_q = _mm_sub_epi16(pixelFilter_q, p4);
flat2_p3 = _mm_srli_epi16(_mm_add_epi16(pixelFilter_p,
_mm_add_epi16(sum_p7, p3)), 4);
flat2_q3 = _mm_srli_epi16(_mm_add_epi16(pixelFilter_q,
_mm_add_epi16(sum_q7, q3)), 4);
sum_p7 = _mm_add_epi16(sum_p7, p7);
sum_q7 = _mm_add_epi16(sum_q7, q7);
pixelFilter_p = _mm_sub_epi16(pixelFilter_p, q3);
pixelFilter_q = _mm_sub_epi16(pixelFilter_q, p3);
flat2_p4 = _mm_srli_epi16(_mm_add_epi16(pixelFilter_p,
_mm_add_epi16(sum_p7, p4)), 4);
flat2_q4 = _mm_srli_epi16(_mm_add_epi16(pixelFilter_q,
_mm_add_epi16(sum_q7, q4)), 4);
sum_p7 = _mm_add_epi16(sum_p7, p7);
sum_q7 = _mm_add_epi16(sum_q7, q7);
pixelFilter_p = _mm_sub_epi16(pixelFilter_p, q2);
pixelFilter_q = _mm_sub_epi16(pixelFilter_q, p2);
flat2_p5 = _mm_srli_epi16(_mm_add_epi16(pixelFilter_p,
_mm_add_epi16(sum_p7, p5)), 4);
flat2_q5 = _mm_srli_epi16(_mm_add_epi16(pixelFilter_q,
_mm_add_epi16(sum_q7, q5)), 4);
sum_p7 = _mm_add_epi16(sum_p7, p7);
sum_q7 = _mm_add_epi16(sum_q7, q7);
pixelFilter_p = _mm_sub_epi16(pixelFilter_p, q1);
pixelFilter_q = _mm_sub_epi16(pixelFilter_q, p1);
flat2_p6 = _mm_srli_epi16(_mm_add_epi16(pixelFilter_p,
_mm_add_epi16(sum_p7, p6)), 4);
flat2_q6 = _mm_srli_epi16(_mm_add_epi16(pixelFilter_q,
_mm_add_epi16(sum_q7, q6)), 4);
// wide flat
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// highbd_filter8
p2 = _mm_andnot_si128(flat, p2);
// p2 remains unchanged if !(flat && mask)
flat_p2 = _mm_and_si128(flat, flat_p2);
// when (flat && mask)
p2 = _mm_or_si128(p2, flat_p2); // full list of p2 values
q2 = _mm_andnot_si128(flat, q2);
flat_q2 = _mm_and_si128(flat, flat_q2);
q2 = _mm_or_si128(q2, flat_q2); // full list of q2 values
ps1 = _mm_andnot_si128(flat, ps1);
// p1 takes the value assigned to in in filter4 if !(flat && mask)
flat_p1 = _mm_and_si128(flat, flat_p1);
// when (flat && mask)
p1 = _mm_or_si128(ps1, flat_p1); // full list of p1 values
qs1 = _mm_andnot_si128(flat, qs1);
flat_q1 = _mm_and_si128(flat, flat_q1);
q1 = _mm_or_si128(qs1, flat_q1); // full list of q1 values
ps0 = _mm_andnot_si128(flat, ps0);
// p0 takes the value assigned to in in filter4 if !(flat && mask)
flat_p0 = _mm_and_si128(flat, flat_p0);
// when (flat && mask)
p0 = _mm_or_si128(ps0, flat_p0); // full list of p0 values
qs0 = _mm_andnot_si128(flat, qs0);
flat_q0 = _mm_and_si128(flat, flat_q0);
q0 = _mm_or_si128(qs0, flat_q0); // full list of q0 values
// end highbd_filter8
// highbd_filter16
p6 = _mm_andnot_si128(flat2, p6);
// p6 remains unchanged if !(flat2 && flat && mask)
flat2_p6 = _mm_and_si128(flat2, flat2_p6);
// get values for when (flat2 && flat && mask)
p6 = _mm_or_si128(p6, flat2_p6); // full list of p6 values
q6 = _mm_andnot_si128(flat2, q6);
// q6 remains unchanged if !(flat2 && flat && mask)
flat2_q6 = _mm_and_si128(flat2, flat2_q6);
// get values for when (flat2 && flat && mask)
q6 = _mm_or_si128(q6, flat2_q6); // full list of q6 values
_mm_store_si128((__m128i *)(s - 7 * p), p6);
_mm_store_si128((__m128i *)(s + 6 * p), q6);
p5 = _mm_andnot_si128(flat2, p5);
// p5 remains unchanged if !(flat2 && flat && mask)
flat2_p5 = _mm_and_si128(flat2, flat2_p5);
// get values for when (flat2 && flat && mask)
p5 = _mm_or_si128(p5, flat2_p5);
// full list of p5 values
q5 = _mm_andnot_si128(flat2, q5);
// q5 remains unchanged if !(flat2 && flat && mask)
flat2_q5 = _mm_and_si128(flat2, flat2_q5);
// get values for when (flat2 && flat && mask)
q5 = _mm_or_si128(q5, flat2_q5);
// full list of q5 values
_mm_store_si128((__m128i *)(s - 6 * p), p5);
_mm_store_si128((__m128i *)(s + 5 * p), q5);
p4 = _mm_andnot_si128(flat2, p4);
// p4 remains unchanged if !(flat2 && flat && mask)
flat2_p4 = _mm_and_si128(flat2, flat2_p4);
// get values for when (flat2 && flat && mask)
p4 = _mm_or_si128(p4, flat2_p4); // full list of p4 values
q4 = _mm_andnot_si128(flat2, q4);
// q4 remains unchanged if !(flat2 && flat && mask)
flat2_q4 = _mm_and_si128(flat2, flat2_q4);
// get values for when (flat2 && flat && mask)
q4 = _mm_or_si128(q4, flat2_q4); // full list of q4 values
_mm_store_si128((__m128i *)(s - 5 * p), p4);
_mm_store_si128((__m128i *)(s + 4 * p), q4);
p3 = _mm_andnot_si128(flat2, p3);
// p3 takes value from highbd_filter8 if !(flat2 && flat && mask)
flat2_p3 = _mm_and_si128(flat2, flat2_p3);
// get values for when (flat2 && flat && mask)
p3 = _mm_or_si128(p3, flat2_p3); // full list of p3 values
q3 = _mm_andnot_si128(flat2, q3);
// q3 takes value from highbd_filter8 if !(flat2 && flat && mask)
flat2_q3 = _mm_and_si128(flat2, flat2_q3);
// get values for when (flat2 && flat && mask)
q3 = _mm_or_si128(q3, flat2_q3); // full list of q3 values
_mm_store_si128((__m128i *)(s - 4 * p), p3);
_mm_store_si128((__m128i *)(s + 3 * p), q3);
p2 = _mm_andnot_si128(flat2, p2);
// p2 takes value from highbd_filter8 if !(flat2 && flat && mask)
flat2_p2 = _mm_and_si128(flat2, flat2_p2);
// get values for when (flat2 && flat && mask)
p2 = _mm_or_si128(p2, flat2_p2);
// full list of p2 values
q2 = _mm_andnot_si128(flat2, q2);
// q2 takes value from highbd_filter8 if !(flat2 && flat && mask)
flat2_q2 = _mm_and_si128(flat2, flat2_q2);
// get values for when (flat2 && flat && mask)
q2 = _mm_or_si128(q2, flat2_q2); // full list of q2 values
_mm_store_si128((__m128i *)(s - 3 * p), p2);
_mm_store_si128((__m128i *)(s + 2 * p), q2);
p1 = _mm_andnot_si128(flat2, p1);
// p1 takes value from highbd_filter8 if !(flat2 && flat && mask)
flat2_p1 = _mm_and_si128(flat2, flat2_p1);
// get values for when (flat2 && flat && mask)
p1 = _mm_or_si128(p1, flat2_p1); // full list of p1 values
q1 = _mm_andnot_si128(flat2, q1);
// q1 takes value from highbd_filter8 if !(flat2 && flat && mask)
flat2_q1 = _mm_and_si128(flat2, flat2_q1);
// get values for when (flat2 && flat && mask)
q1 = _mm_or_si128(q1, flat2_q1); // full list of q1 values
_mm_store_si128((__m128i *)(s - 2 * p), p1);
_mm_store_si128((__m128i *)(s + 1 * p), q1);
p0 = _mm_andnot_si128(flat2, p0);
// p0 takes value from highbd_filter8 if !(flat2 && flat && mask)
flat2_p0 = _mm_and_si128(flat2, flat2_p0);
// get values for when (flat2 && flat && mask)
p0 = _mm_or_si128(p0, flat2_p0); // full list of p0 values
q0 = _mm_andnot_si128(flat2, q0);
// q0 takes value from highbd_filter8 if !(flat2 && flat && mask)
flat2_q0 = _mm_and_si128(flat2, flat2_q0);
// get values for when (flat2 && flat && mask)
q0 = _mm_or_si128(q0, flat2_q0); // full list of q0 values
_mm_store_si128((__m128i *)(s - 1 * p), p0);
_mm_store_si128((__m128i *)(s - 0 * p), q0);
}
static void highbd_mb_lpf_horizontal_edge_w_sse2_16(uint16_t *s,
int p,
const uint8_t *_blimit,
const uint8_t *_limit,
const uint8_t *_thresh,
int bd) {
highbd_mb_lpf_horizontal_edge_w_sse2_8(s, p, _blimit, _limit, _thresh, bd);
highbd_mb_lpf_horizontal_edge_w_sse2_8(s + 8, p, _blimit, _limit, _thresh,
bd);
}
// TODO(yunqingwang): remove count and call these 2 functions(8 or 16) directly.
void vpx_highbd_lpf_horizontal_16_sse2(uint16_t *s, int p,
const uint8_t *_blimit,
const uint8_t *_limit,
const uint8_t *_thresh,
int count, int bd) {
if (count == 1)
highbd_mb_lpf_horizontal_edge_w_sse2_8(s, p, _blimit, _limit, _thresh, bd);
else
highbd_mb_lpf_horizontal_edge_w_sse2_16(s, p, _blimit, _limit, _thresh, bd);
}
void vpx_highbd_lpf_horizontal_8_sse2(uint16_t *s, int p,
const uint8_t *_blimit,
const uint8_t *_limit,
const uint8_t *_thresh,
int count, int bd) {
DECLARE_ALIGNED(16, uint16_t, flat_op2[16]);
DECLARE_ALIGNED(16, uint16_t, flat_op1[16]);
DECLARE_ALIGNED(16, uint16_t, flat_op0[16]);
DECLARE_ALIGNED(16, uint16_t, flat_oq2[16]);
DECLARE_ALIGNED(16, uint16_t, flat_oq1[16]);
DECLARE_ALIGNED(16, uint16_t, flat_oq0[16]);
const __m128i zero = _mm_set1_epi16(0);
__m128i blimit, limit, thresh;
__m128i mask, hev, flat;
__m128i p3 = _mm_load_si128((__m128i *)(s - 4 * p));
__m128i q3 = _mm_load_si128((__m128i *)(s + 3 * p));
__m128i p2 = _mm_load_si128((__m128i *)(s - 3 * p));
__m128i q2 = _mm_load_si128((__m128i *)(s + 2 * p));
__m128i p1 = _mm_load_si128((__m128i *)(s - 2 * p));
__m128i q1 = _mm_load_si128((__m128i *)(s + 1 * p));
__m128i p0 = _mm_load_si128((__m128i *)(s - 1 * p));
__m128i q0 = _mm_load_si128((__m128i *)(s + 0 * p));
const __m128i one = _mm_set1_epi16(1);
const __m128i ffff = _mm_cmpeq_epi16(one, one);
__m128i abs_p1q1, abs_p0q0, abs_q1q0, abs_p1p0, work;
const __m128i four = _mm_set1_epi16(4);
__m128i workp_a, workp_b, workp_shft;
const __m128i t4 = _mm_set1_epi16(4);
const __m128i t3 = _mm_set1_epi16(3);
__m128i t80;
const __m128i t1 = _mm_set1_epi16(0x1);
__m128i ps1, ps0, qs0, qs1;
__m128i filt;
__m128i work_a;
__m128i filter1, filter2;
(void)count;
if (bd == 8) {
blimit = _mm_unpacklo_epi8(_mm_load_si128((const __m128i *)_blimit), zero);
limit = _mm_unpacklo_epi8(_mm_load_si128((const __m128i *)_limit), zero);
thresh = _mm_unpacklo_epi8(_mm_load_si128((const __m128i *)_thresh), zero);
t80 = _mm_set1_epi16(0x80);
} else if (bd == 10) {
blimit = _mm_slli_epi16(
_mm_unpacklo_epi8(_mm_load_si128((const __m128i *)_blimit), zero), 2);
limit = _mm_slli_epi16(
_mm_unpacklo_epi8(_mm_load_si128((const __m128i *)_limit), zero), 2);
thresh = _mm_slli_epi16(
_mm_unpacklo_epi8(_mm_load_si128((const __m128i *)_thresh), zero), 2);
t80 = _mm_set1_epi16(0x200);
} else { // bd == 12
blimit = _mm_slli_epi16(
_mm_unpacklo_epi8(_mm_load_si128((const __m128i *)_blimit), zero), 4);
limit = _mm_slli_epi16(
_mm_unpacklo_epi8(_mm_load_si128((const __m128i *)_limit), zero), 4);
thresh = _mm_slli_epi16(
_mm_unpacklo_epi8(_mm_load_si128((const __m128i *)_thresh), zero), 4);
t80 = _mm_set1_epi16(0x800);
}
ps1 = _mm_subs_epi16(p1, t80);
ps0 = _mm_subs_epi16(p0, t80);
qs0 = _mm_subs_epi16(q0, t80);
qs1 = _mm_subs_epi16(q1, t80);
// filter_mask and hev_mask
abs_p1p0 = _mm_or_si128(_mm_subs_epu16(p1, p0),
_mm_subs_epu16(p0, p1));
abs_q1q0 = _mm_or_si128(_mm_subs_epu16(q1, q0),
_mm_subs_epu16(q0, q1));
abs_p0q0 = _mm_or_si128(_mm_subs_epu16(p0, q0),
_mm_subs_epu16(q0, p0));
abs_p1q1 = _mm_or_si128(_mm_subs_epu16(p1, q1),
_mm_subs_epu16(q1, p1));
flat = _mm_max_epi16(abs_p1p0, abs_q1q0);
hev = _mm_subs_epu16(flat, thresh);
hev = _mm_xor_si128(_mm_cmpeq_epi16(hev, zero), ffff);
abs_p0q0 =_mm_adds_epu16(abs_p0q0, abs_p0q0);
abs_p1q1 = _mm_srli_epi16(abs_p1q1, 1);
mask = _mm_subs_epu16(_mm_adds_epu16(abs_p0q0, abs_p1q1), blimit);
mask = _mm_xor_si128(_mm_cmpeq_epi16(mask, zero), ffff);
// mask |= (abs(p0 - q0) * 2 + abs(p1 - q1) / 2 > blimit) * -1;
// So taking maximums continues to work:
mask = _mm_and_si128(mask, _mm_adds_epu16(limit, one));
mask = _mm_max_epi16(abs_p1p0, mask);
// mask |= (abs(p1 - p0) > limit) * -1;
mask = _mm_max_epi16(abs_q1q0, mask);
// mask |= (abs(q1 - q0) > limit) * -1;
work = _mm_max_epi16(_mm_or_si128(_mm_subs_epu16(p2, p1),
_mm_subs_epu16(p1, p2)),
_mm_or_si128(_mm_subs_epu16(q2, q1),
_mm_subs_epu16(q1, q2)));
mask = _mm_max_epi16(work, mask);
work = _mm_max_epi16(_mm_or_si128(_mm_subs_epu16(p3, p2),
_mm_subs_epu16(p2, p3)),
_mm_or_si128(_mm_subs_epu16(q3, q2),
_mm_subs_epu16(q2, q3)));
mask = _mm_max_epi16(work, mask);
mask = _mm_subs_epu16(mask, limit);
mask = _mm_cmpeq_epi16(mask, zero);
// flat_mask4
flat = _mm_max_epi16(_mm_or_si128(_mm_subs_epu16(p2, p0),
_mm_subs_epu16(p0, p2)),
_mm_or_si128(_mm_subs_epu16(q2, q0),
_mm_subs_epu16(q0, q2)));
work = _mm_max_epi16(_mm_or_si128(_mm_subs_epu16(p3, p0),
_mm_subs_epu16(p0, p3)),
_mm_or_si128(_mm_subs_epu16(q3, q0),
_mm_subs_epu16(q0, q3)));
flat = _mm_max_epi16(work, flat);
flat = _mm_max_epi16(abs_p1p0, flat);
flat = _mm_max_epi16(abs_q1q0, flat);
if (bd == 8)
flat = _mm_subs_epu16(flat, one);
else if (bd == 10)
flat = _mm_subs_epu16(flat, _mm_slli_epi16(one, 2));
else // bd == 12
flat = _mm_subs_epu16(flat, _mm_slli_epi16(one, 4));
flat = _mm_cmpeq_epi16(flat, zero);
flat = _mm_and_si128(flat, mask); // flat & mask
// Added before shift for rounding part of ROUND_POWER_OF_TWO
workp_a = _mm_add_epi16(_mm_add_epi16(p3, p3), _mm_add_epi16(p2, p1));
workp_a = _mm_add_epi16(_mm_add_epi16(workp_a, four), p0);
workp_b = _mm_add_epi16(_mm_add_epi16(q0, p2), p3);
workp_shft = _mm_srli_epi16(_mm_add_epi16(workp_a, workp_b), 3);
_mm_store_si128((__m128i *)&flat_op2[0], workp_shft);
workp_b = _mm_add_epi16(_mm_add_epi16(q0, q1), p1);
workp_shft = _mm_srli_epi16(_mm_add_epi16(workp_a, workp_b), 3);
_mm_store_si128((__m128i *)&flat_op1[0], workp_shft);
workp_a = _mm_add_epi16(_mm_sub_epi16(workp_a, p3), q2);
workp_b = _mm_add_epi16(_mm_sub_epi16(workp_b, p1), p0);
workp_shft = _mm_srli_epi16(_mm_add_epi16(workp_a, workp_b), 3);
_mm_store_si128((__m128i *)&flat_op0[0], workp_shft);
workp_a = _mm_add_epi16(_mm_sub_epi16(workp_a, p3), q3);
workp_b = _mm_add_epi16(_mm_sub_epi16(workp_b, p0), q0);
workp_shft = _mm_srli_epi16(_mm_add_epi16(workp_a, workp_b), 3);
_mm_store_si128((__m128i *)&flat_oq0[0], workp_shft);
workp_a = _mm_add_epi16(_mm_sub_epi16(workp_a, p2), q3);
workp_b = _mm_add_epi16(_mm_sub_epi16(workp_b, q0), q1);
workp_shft = _mm_srli_epi16(_mm_add_epi16(workp_a, workp_b), 3);
_mm_store_si128((__m128i *)&flat_oq1[0], workp_shft);
workp_a = _mm_add_epi16(_mm_sub_epi16(workp_a, p1), q3);
workp_b = _mm_add_epi16(_mm_sub_epi16(workp_b, q1), q2);
workp_shft = _mm_srli_epi16(_mm_add_epi16(workp_a, workp_b), 3);
_mm_store_si128((__m128i *)&flat_oq2[0], workp_shft);
// lp filter
filt = signed_char_clamp_bd_sse2(_mm_subs_epi16(ps1, qs1), bd);
filt = _mm_and_si128(filt, hev);
work_a = _mm_subs_epi16(qs0, ps0);
filt = _mm_adds_epi16(filt, work_a);
filt = _mm_adds_epi16(filt, work_a);
filt = _mm_adds_epi16(filt, work_a);
// (vpx_filter + 3 * (qs0 - ps0)) & mask
filt = signed_char_clamp_bd_sse2(filt, bd);
filt = _mm_and_si128(filt, mask);
filter1 = _mm_adds_epi16(filt, t4);
filter2 = _mm_adds_epi16(filt, t3);
// Filter1 >> 3
filter1 = signed_char_clamp_bd_sse2(filter1, bd);
filter1 = _mm_srai_epi16(filter1, 3);
// Filter2 >> 3
filter2 = signed_char_clamp_bd_sse2(filter2, bd);
filter2 = _mm_srai_epi16(filter2, 3);
// filt >> 1
filt = _mm_adds_epi16(filter1, t1);
filt = _mm_srai_epi16(filt, 1);
// filter = ROUND_POWER_OF_TWO(filter1, 1) & ~hev;
filt = _mm_andnot_si128(hev, filt);
work_a = signed_char_clamp_bd_sse2(_mm_subs_epi16(qs0, filter1), bd);
work_a = _mm_adds_epi16(work_a, t80);
q0 = _mm_load_si128((__m128i *)flat_oq0);
work_a = _mm_andnot_si128(flat, work_a);
q0 = _mm_and_si128(flat, q0);
q0 = _mm_or_si128(work_a, q0);
work_a = signed_char_clamp_bd_sse2(_mm_subs_epi16(qs1, filt), bd);
work_a = _mm_adds_epi16(work_a, t80);
q1 = _mm_load_si128((__m128i *)flat_oq1);
work_a = _mm_andnot_si128(flat, work_a);
q1 = _mm_and_si128(flat, q1);
q1 = _mm_or_si128(work_a, q1);
work_a = _mm_loadu_si128((__m128i *)(s + 2 * p));
q2 = _mm_load_si128((__m128i *)flat_oq2);
work_a = _mm_andnot_si128(flat, work_a);
q2 = _mm_and_si128(flat, q2);
q2 = _mm_or_si128(work_a, q2);
work_a = signed_char_clamp_bd_sse2(_mm_adds_epi16(ps0, filter2), bd);
work_a = _mm_adds_epi16(work_a, t80);
p0 = _mm_load_si128((__m128i *)flat_op0);
work_a = _mm_andnot_si128(flat, work_a);
p0 = _mm_and_si128(flat, p0);
p0 = _mm_or_si128(work_a, p0);
work_a = signed_char_clamp_bd_sse2(_mm_adds_epi16(ps1, filt), bd);
work_a = _mm_adds_epi16(work_a, t80);
p1 = _mm_load_si128((__m128i *)flat_op1);
work_a = _mm_andnot_si128(flat, work_a);
p1 = _mm_and_si128(flat, p1);
p1 = _mm_or_si128(work_a, p1);
work_a = _mm_loadu_si128((__m128i *)(s - 3 * p));
p2 = _mm_load_si128((__m128i *)flat_op2);
work_a = _mm_andnot_si128(flat, work_a);
p2 = _mm_and_si128(flat, p2);
p2 = _mm_or_si128(work_a, p2);
_mm_store_si128((__m128i *)(s - 3 * p), p2);
_mm_store_si128((__m128i *)(s - 2 * p), p1);
_mm_store_si128((__m128i *)(s - 1 * p), p0);
_mm_store_si128((__m128i *)(s + 0 * p), q0);
_mm_store_si128((__m128i *)(s + 1 * p), q1);
_mm_store_si128((__m128i *)(s + 2 * p), q2);
}
void vpx_highbd_lpf_horizontal_8_dual_sse2(uint16_t *s, int p,
const uint8_t *_blimit0,
const uint8_t *_limit0,
const uint8_t *_thresh0,
const uint8_t *_blimit1,
const uint8_t *_limit1,
const uint8_t *_thresh1,
int bd) {
vpx_highbd_lpf_horizontal_8_sse2(s, p, _blimit0, _limit0, _thresh0, 1, bd);
vpx_highbd_lpf_horizontal_8_sse2(s + 8, p, _blimit1, _limit1, _thresh1,
1, bd);
}
void vpx_highbd_lpf_horizontal_4_sse2(uint16_t *s, int p,
const uint8_t *_blimit,
const uint8_t *_limit,
const uint8_t *_thresh,
int count, int bd) {
const __m128i zero = _mm_set1_epi16(0);
__m128i blimit, limit, thresh;
__m128i mask, hev, flat;
__m128i p3 = _mm_loadu_si128((__m128i *)(s - 4 * p));
__m128i p2 = _mm_loadu_si128((__m128i *)(s - 3 * p));
__m128i p1 = _mm_loadu_si128((__m128i *)(s - 2 * p));
__m128i p0 = _mm_loadu_si128((__m128i *)(s - 1 * p));
__m128i q0 = _mm_loadu_si128((__m128i *)(s - 0 * p));
__m128i q1 = _mm_loadu_si128((__m128i *)(s + 1 * p));
__m128i q2 = _mm_loadu_si128((__m128i *)(s + 2 * p));
__m128i q3 = _mm_loadu_si128((__m128i *)(s + 3 * p));
const __m128i abs_p1p0 = _mm_or_si128(_mm_subs_epu16(p1, p0),
_mm_subs_epu16(p0, p1));
const __m128i abs_q1q0 = _mm_or_si128(_mm_subs_epu16(q1, q0),
_mm_subs_epu16(q0, q1));
const __m128i ffff = _mm_cmpeq_epi16(abs_p1p0, abs_p1p0);
const __m128i one = _mm_set1_epi16(1);
__m128i abs_p0q0 = _mm_or_si128(_mm_subs_epu16(p0, q0),
_mm_subs_epu16(q0, p0));
__m128i abs_p1q1 = _mm_or_si128(_mm_subs_epu16(p1, q1),
_mm_subs_epu16(q1, p1));
__m128i work;
const __m128i t4 = _mm_set1_epi16(4);
const __m128i t3 = _mm_set1_epi16(3);
__m128i t80;
__m128i tff80;
__m128i tffe0;
__m128i t1f;
// equivalent to shifting 0x1f left by bitdepth - 8
// and setting new bits to 1
const __m128i t1 = _mm_set1_epi16(0x1);
__m128i t7f;
// equivalent to shifting 0x7f left by bitdepth - 8
// and setting new bits to 1
__m128i ps1, ps0, qs0, qs1;
__m128i filt;
__m128i work_a;
__m128i filter1, filter2;
(void)count;
if (bd == 8) {
blimit = _mm_unpacklo_epi8(_mm_load_si128((const __m128i *)_blimit), zero);
limit = _mm_unpacklo_epi8(_mm_load_si128((const __m128i *)_limit), zero);
thresh = _mm_unpacklo_epi8(_mm_load_si128((const __m128i *)_thresh), zero);
t80 = _mm_set1_epi16(0x80);
tff80 = _mm_set1_epi16(0xff80);
tffe0 = _mm_set1_epi16(0xffe0);
t1f = _mm_srli_epi16(_mm_set1_epi16(0x1fff), 8);
t7f = _mm_srli_epi16(_mm_set1_epi16(0x7fff), 8);
} else if (bd == 10) {
blimit = _mm_slli_epi16(
_mm_unpacklo_epi8(_mm_load_si128((const __m128i *)_blimit), zero), 2);
limit = _mm_slli_epi16(
_mm_unpacklo_epi8(_mm_load_si128((const __m128i *)_limit), zero), 2);
thresh = _mm_slli_epi16(
_mm_unpacklo_epi8(_mm_load_si128((const __m128i *)_thresh), zero), 2);
t80 = _mm_slli_epi16(_mm_set1_epi16(0x80), 2);
tff80 = _mm_slli_epi16(_mm_set1_epi16(0xff80), 2);
tffe0 = _mm_slli_epi16(_mm_set1_epi16(0xffe0), 2);
t1f = _mm_srli_epi16(_mm_set1_epi16(0x1fff), 6);
t7f = _mm_srli_epi16(_mm_set1_epi16(0x7fff), 6);
} else { // bd == 12
blimit = _mm_slli_epi16(
_mm_unpacklo_epi8(_mm_load_si128((const __m128i *)_blimit), zero), 4);
limit = _mm_slli_epi16(
_mm_unpacklo_epi8(_mm_load_si128((const __m128i *)_limit), zero), 4);
thresh = _mm_slli_epi16(
_mm_unpacklo_epi8(_mm_load_si128((const __m128i *)_thresh), zero), 4);
t80 = _mm_slli_epi16(_mm_set1_epi16(0x80), 4);
tff80 = _mm_slli_epi16(_mm_set1_epi16(0xff80), 4);
tffe0 = _mm_slli_epi16(_mm_set1_epi16(0xffe0), 4);
t1f = _mm_srli_epi16(_mm_set1_epi16(0x1fff), 4);
t7f = _mm_srli_epi16(_mm_set1_epi16(0x7fff), 4);
}
ps1 = _mm_subs_epi16(_mm_loadu_si128((__m128i *)(s - 2 * p)), t80);
ps0 = _mm_subs_epi16(_mm_loadu_si128((__m128i *)(s - 1 * p)), t80);
qs0 = _mm_subs_epi16(_mm_loadu_si128((__m128i *)(s + 0 * p)), t80);
qs1 = _mm_subs_epi16(_mm_loadu_si128((__m128i *)(s + 1 * p)), t80);
// filter_mask and hev_mask
flat = _mm_max_epi16(abs_p1p0, abs_q1q0);
hev = _mm_subs_epu16(flat, thresh);
hev = _mm_xor_si128(_mm_cmpeq_epi16(hev, zero), ffff);
abs_p0q0 =_mm_adds_epu16(abs_p0q0, abs_p0q0);
abs_p1q1 = _mm_srli_epi16(abs_p1q1, 1);
mask = _mm_subs_epu16(_mm_adds_epu16(abs_p0q0, abs_p1q1), blimit);
mask = _mm_xor_si128(_mm_cmpeq_epi16(mask, zero), ffff);
// mask |= (abs(p0 - q0) * 2 + abs(p1 - q1) / 2 > blimit) * -1;
// So taking maximums continues to work:
mask = _mm_and_si128(mask, _mm_adds_epu16(limit, one));
mask = _mm_max_epi16(flat, mask);
// mask |= (abs(p1 - p0) > limit) * -1;
// mask |= (abs(q1 - q0) > limit) * -1;
work = _mm_max_epi16(_mm_or_si128(_mm_subs_epu16(p2, p1),
_mm_subs_epu16(p1, p2)),
_mm_or_si128(_mm_subs_epu16(p3, p2),
_mm_subs_epu16(p2, p3)));
mask = _mm_max_epi16(work, mask);
work = _mm_max_epi16(_mm_or_si128(_mm_subs_epu16(q2, q1),
_mm_subs_epu16(q1, q2)),
_mm_or_si128(_mm_subs_epu16(q3, q2),
_mm_subs_epu16(q2, q3)));
mask = _mm_max_epi16(work, mask);
mask = _mm_subs_epu16(mask, limit);
mask = _mm_cmpeq_epi16(mask, zero);
// filter4
filt = signed_char_clamp_bd_sse2(_mm_subs_epi16(ps1, qs1), bd);
filt = _mm_and_si128(filt, hev);
work_a = _mm_subs_epi16(qs0, ps0);
filt = _mm_adds_epi16(filt, work_a);
filt = _mm_adds_epi16(filt, work_a);
filt = signed_char_clamp_bd_sse2(_mm_adds_epi16(filt, work_a), bd);
// (vpx_filter + 3 * (qs0 - ps0)) & mask
filt = _mm_and_si128(filt, mask);
filter1 = signed_char_clamp_bd_sse2(_mm_adds_epi16(filt, t4), bd);
filter2 = signed_char_clamp_bd_sse2(_mm_adds_epi16(filt, t3), bd);
// Filter1 >> 3
work_a = _mm_cmpgt_epi16(zero, filter1); // get the values that are <0
filter1 = _mm_srli_epi16(filter1, 3);
work_a = _mm_and_si128(work_a, tffe0); // sign bits for the values < 0
filter1 = _mm_and_si128(filter1, t1f); // clamp the range
filter1 = _mm_or_si128(filter1, work_a); // reinsert the sign bits
// Filter2 >> 3
work_a = _mm_cmpgt_epi16(zero, filter2);
filter2 = _mm_srli_epi16(filter2, 3);
work_a = _mm_and_si128(work_a, tffe0);
filter2 = _mm_and_si128(filter2, t1f);
filter2 = _mm_or_si128(filter2, work_a);
// filt >> 1
filt = _mm_adds_epi16(filter1, t1);
work_a = _mm_cmpgt_epi16(zero, filt);
filt = _mm_srli_epi16(filt, 1);
work_a = _mm_and_si128(work_a, tff80);
filt = _mm_and_si128(filt, t7f);
filt = _mm_or_si128(filt, work_a);
filt = _mm_andnot_si128(hev, filt);
q0 = _mm_adds_epi16(
signed_char_clamp_bd_sse2(_mm_subs_epi16(qs0, filter1), bd), t80);
q1 = _mm_adds_epi16(
signed_char_clamp_bd_sse2(_mm_subs_epi16(qs1, filt), bd), t80);
p0 = _mm_adds_epi16(
signed_char_clamp_bd_sse2(_mm_adds_epi16(ps0, filter2), bd), t80);
p1 = _mm_adds_epi16(
signed_char_clamp_bd_sse2(_mm_adds_epi16(ps1, filt), bd), t80);
_mm_storeu_si128((__m128i *)(s - 2 * p), p1);
_mm_storeu_si128((__m128i *)(s - 1 * p), p0);
_mm_storeu_si128((__m128i *)(s + 0 * p), q0);
_mm_storeu_si128((__m128i *)(s + 1 * p), q1);
}
void vpx_highbd_lpf_horizontal_4_dual_sse2(uint16_t *s, int p,
const uint8_t *_blimit0,
const uint8_t *_limit0,
const uint8_t *_thresh0,
const uint8_t *_blimit1,
const uint8_t *_limit1,
const uint8_t *_thresh1,
int bd) {
vpx_highbd_lpf_horizontal_4_sse2(s, p, _blimit0, _limit0, _thresh0, 1, bd);
vpx_highbd_lpf_horizontal_4_sse2(s + 8, p, _blimit1, _limit1, _thresh1, 1,
bd);
}
static INLINE void highbd_transpose(uint16_t *src[], int in_p,
uint16_t *dst[], int out_p,
int num_8x8_to_transpose) {
int idx8x8 = 0;
__m128i p0, p1, p2, p3, p4, p5, p6, p7, x0, x1, x2, x3, x4, x5, x6, x7;
do {
uint16_t *in = src[idx8x8];
uint16_t *out = dst[idx8x8];
p0 = _mm_loadu_si128((__m128i *)(in + 0*in_p)); // 00 01 02 03 04 05 06 07
p1 = _mm_loadu_si128((__m128i *)(in + 1*in_p)); // 10 11 12 13 14 15 16 17
p2 = _mm_loadu_si128((__m128i *)(in + 2*in_p)); // 20 21 22 23 24 25 26 27
p3 = _mm_loadu_si128((__m128i *)(in + 3*in_p)); // 30 31 32 33 34 35 36 37
p4 = _mm_loadu_si128((__m128i *)(in + 4*in_p)); // 40 41 42 43 44 45 46 47
p5 = _mm_loadu_si128((__m128i *)(in + 5*in_p)); // 50 51 52 53 54 55 56 57
p6 = _mm_loadu_si128((__m128i *)(in + 6*in_p)); // 60 61 62 63 64 65 66 67
p7 = _mm_loadu_si128((__m128i *)(in + 7*in_p)); // 70 71 72 73 74 75 76 77
// 00 10 01 11 02 12 03 13
x0 = _mm_unpacklo_epi16(p0, p1);
// 20 30 21 31 22 32 23 33
x1 = _mm_unpacklo_epi16(p2, p3);
// 40 50 41 51 42 52 43 53
x2 = _mm_unpacklo_epi16(p4, p5);
// 60 70 61 71 62 72 63 73
x3 = _mm_unpacklo_epi16(p6, p7);
// 00 10 20 30 01 11 21 31
x4 = _mm_unpacklo_epi32(x0, x1);
// 40 50 60 70 41 51 61 71
x5 = _mm_unpacklo_epi32(x2, x3);
// 00 10 20 30 40 50 60 70
x6 = _mm_unpacklo_epi64(x4, x5);
// 01 11 21 31 41 51 61 71
x7 = _mm_unpackhi_epi64(x4, x5);
_mm_storeu_si128((__m128i *)(out + 0*out_p), x6);
// 00 10 20 30 40 50 60 70
_mm_storeu_si128((__m128i *)(out + 1*out_p), x7);
// 01 11 21 31 41 51 61 71
// 02 12 22 32 03 13 23 33
x4 = _mm_unpackhi_epi32(x0, x1);
// 42 52 62 72 43 53 63 73
x5 = _mm_unpackhi_epi32(x2, x3);
// 02 12 22 32 42 52 62 72
x6 = _mm_unpacklo_epi64(x4, x5);
// 03 13 23 33 43 53 63 73
x7 = _mm_unpackhi_epi64(x4, x5);
_mm_storeu_si128((__m128i *)(out + 2*out_p), x6);
// 02 12 22 32 42 52 62 72
_mm_storeu_si128((__m128i *)(out + 3*out_p), x7);
// 03 13 23 33 43 53 63 73
// 04 14 05 15 06 16 07 17
x0 = _mm_unpackhi_epi16(p0, p1);
// 24 34 25 35 26 36 27 37
x1 = _mm_unpackhi_epi16(p2, p3);
// 44 54 45 55 46 56 47 57
x2 = _mm_unpackhi_epi16(p4, p5);
// 64 74 65 75 66 76 67 77
x3 = _mm_unpackhi_epi16(p6, p7);
// 04 14 24 34 05 15 25 35
x4 = _mm_unpacklo_epi32(x0, x1);
// 44 54 64 74 45 55 65 75
x5 = _mm_unpacklo_epi32(x2, x3);
// 04 14 24 34 44 54 64 74
x6 = _mm_unpacklo_epi64(x4, x5);
// 05 15 25 35 45 55 65 75
x7 = _mm_unpackhi_epi64(x4, x5);
_mm_storeu_si128((__m128i *)(out + 4*out_p), x6);
// 04 14 24 34 44 54 64 74
_mm_storeu_si128((__m128i *)(out + 5*out_p), x7);
// 05 15 25 35 45 55 65 75
// 06 16 26 36 07 17 27 37
x4 = _mm_unpackhi_epi32(x0, x1);
// 46 56 66 76 47 57 67 77
x5 = _mm_unpackhi_epi32(x2, x3);
// 06 16 26 36 46 56 66 76
x6 = _mm_unpacklo_epi64(x4, x5);
// 07 17 27 37 47 57 67 77
x7 = _mm_unpackhi_epi64(x4, x5);
_mm_storeu_si128((__m128i *)(out + 6*out_p), x6);
// 06 16 26 36 46 56 66 76
_mm_storeu_si128((__m128i *)(out + 7*out_p), x7);
// 07 17 27 37 47 57 67 77
} while (++idx8x8 < num_8x8_to_transpose);
}
static INLINE void highbd_transpose8x16(uint16_t *in0, uint16_t *in1,
int in_p, uint16_t *out, int out_p) {
uint16_t *src0[1];
uint16_t *src1[1];
uint16_t *dest0[1];
uint16_t *dest1[1];
src0[0] = in0;
src1[0] = in1;
dest0[0] = out;
dest1[0] = out + 8;
highbd_transpose(src0, in_p, dest0, out_p, 1);
highbd_transpose(src1, in_p, dest1, out_p, 1);
}
void vpx_highbd_lpf_vertical_4_sse2(uint16_t *s, int p,
const uint8_t *blimit,
const uint8_t *limit,
const uint8_t *thresh,
int count, int bd) {
DECLARE_ALIGNED(16, uint16_t, t_dst[8 * 8]);
uint16_t *src[1];
uint16_t *dst[1];
(void)count;
// Transpose 8x8
src[0] = s - 4;
dst[0] = t_dst;
highbd_transpose(src, p, dst, 8, 1);
// Loop filtering
vpx_highbd_lpf_horizontal_4_sse2(t_dst + 4 * 8, 8, blimit, limit, thresh, 1,
bd);
src[0] = t_dst;
dst[0] = s - 4;
// Transpose back
highbd_transpose(src, 8, dst, p, 1);
}
void vpx_highbd_lpf_vertical_4_dual_sse2(uint16_t *s, int p,
const uint8_t *blimit0,
const uint8_t *limit0,
const uint8_t *thresh0,
const uint8_t *blimit1,
const uint8_t *limit1,
const uint8_t *thresh1,
int bd) {
DECLARE_ALIGNED(16, uint16_t, t_dst[16 * 8]);
uint16_t *src[2];
uint16_t *dst[2];
// Transpose 8x16
highbd_transpose8x16(s - 4, s - 4 + p * 8, p, t_dst, 16);
// Loop filtering
vpx_highbd_lpf_horizontal_4_dual_sse2(t_dst + 4 * 16, 16, blimit0, limit0,
thresh0, blimit1, limit1, thresh1, bd);
src[0] = t_dst;
src[1] = t_dst + 8;
dst[0] = s - 4;
dst[1] = s - 4 + p * 8;
// Transpose back
highbd_transpose(src, 16, dst, p, 2);
}
void vpx_highbd_lpf_vertical_8_sse2(uint16_t *s, int p,
const uint8_t *blimit,
const uint8_t *limit,
const uint8_t *thresh,
int count, int bd) {
DECLARE_ALIGNED(16, uint16_t, t_dst[8 * 8]);
uint16_t *src[1];
uint16_t *dst[1];
(void)count;
// Transpose 8x8
src[0] = s - 4;
dst[0] = t_dst;
highbd_transpose(src, p, dst, 8, 1);
// Loop filtering
vpx_highbd_lpf_horizontal_8_sse2(t_dst + 4 * 8, 8, blimit, limit, thresh, 1,
bd);
src[0] = t_dst;
dst[0] = s - 4;
// Transpose back
highbd_transpose(src, 8, dst, p, 1);
}
void vpx_highbd_lpf_vertical_8_dual_sse2(uint16_t *s, int p,
const uint8_t *blimit0,
const uint8_t *limit0,
const uint8_t *thresh0,
const uint8_t *blimit1,
const uint8_t *limit1,
const uint8_t *thresh1,
int bd) {
DECLARE_ALIGNED(16, uint16_t, t_dst[16 * 8]);
uint16_t *src[2];
uint16_t *dst[2];
// Transpose 8x16
highbd_transpose8x16(s - 4, s - 4 + p * 8, p, t_dst, 16);
// Loop filtering
vpx_highbd_lpf_horizontal_8_dual_sse2(t_dst + 4 * 16, 16, blimit0, limit0,
thresh0, blimit1, limit1, thresh1, bd);
src[0] = t_dst;
src[1] = t_dst + 8;
dst[0] = s - 4;
dst[1] = s - 4 + p * 8;
// Transpose back
highbd_transpose(src, 16, dst, p, 2);
}
void vpx_highbd_lpf_vertical_16_sse2(uint16_t *s, int p,
const uint8_t *blimit,
const uint8_t *limit,
const uint8_t *thresh,
int bd) {
DECLARE_ALIGNED(16, uint16_t, t_dst[8 * 16]);
uint16_t *src[2];
uint16_t *dst[2];
src[0] = s - 8;
src[1] = s;
dst[0] = t_dst;
dst[1] = t_dst + 8 * 8;
// Transpose 16x8
highbd_transpose(src, p, dst, 8, 2);
// Loop filtering
highbd_mb_lpf_horizontal_edge_w_sse2_8(t_dst + 8 * 8, 8, blimit, limit,
thresh, bd);
src[0] = t_dst;
src[1] = t_dst + 8 * 8;
dst[0] = s - 8;
dst[1] = s;
// Transpose back
highbd_transpose(src, 8, dst, p, 2);
}
void vpx_highbd_lpf_vertical_16_dual_sse2(uint16_t *s,
int p,
const uint8_t *blimit,
const uint8_t *limit,
const uint8_t *thresh,
int bd) {
DECLARE_ALIGNED(16, uint16_t, t_dst[256]);
// Transpose 16x16
highbd_transpose8x16(s - 8, s - 8 + 8 * p, p, t_dst, 16);
highbd_transpose8x16(s, s + 8 * p, p, t_dst + 8 * 16, 16);
// Loop filtering
highbd_mb_lpf_horizontal_edge_w_sse2_16(t_dst + 8 * 16, 16, blimit, limit,
thresh, bd);
// Transpose back
highbd_transpose8x16(t_dst, t_dst + 8 * 16, 16, s - 8, p);
highbd_transpose8x16(t_dst + 8, t_dst + 8 + 8 * 16, 16, s - 8 + 8 * p, p);
}
|
863340.c |
// gcc -Wall test_1.c
// -Xlinker -rpath=../lib/LNX-64
// -L ../lib/LNX-64 -ljigsaw64r -o test_1
# include "../inc/lib_jigsaw.h"
# include "stdio.h"
int main (
int _argc ,
char **_argv
)
{
int _retv = 0;
/*-------------------------------- setup JIGSAW types */
jigsaw_jig_t _jjig ;
jigsaw_msh_t _geom ;
jigsaw_msh_t _mesh ;
jigsaw_init_jig_t(&_jjig) ;
jigsaw_init_msh_t(&_geom) ;
jigsaw_init_msh_t(&_mesh) ;
/*
--------------------------------------------------------
* JIGSAW's "mesh" is a piecewise linear complex:
--------------------------------------------------------
*
* e:2
* v:3 o---------------o v:2
* | |
* | |
* | |
* e:3 | | e:1
* | |
* | |
* | |
* v:0 o---------------o v:1
* e:0
*
--------------------------------------------------------
*/
jigsaw_VERT2_t _vert2[4] = { // setup geom.
{ {0., 0.}, +0 } ,
{ {1., 0.}, +0 } ,
{ {1., 1.}, +0 } ,
{ {0., 1.}, +0 }
} ;
jigsaw_EDGE2_t _edge2[4] = {
{ {+0, +1}, +0 } ,
{ {+1, +2}, +0 } ,
{ {+2, +3}, +0 } ,
{ {+3, +0}, +0 }
} ;
_geom._flags
= JIGSAW_EUCLIDEAN_MESH;
_geom._vert2._data = &_vert2[0] ;
_geom._vert2._size = +4 ;
_geom._edge2._data = &_edge2[0] ;
_geom._edge2._size = +4 ;
/*-------------------------------- build JIGSAW tria. */
_jjig._verbosity = +1 ;
_jjig._hfun_hmax = 0.10 ;
_jjig._hfun_scal =
JIGSAW_HFUN_RELATIVE;
_jjig._mesh_dims = +2 ;
_retv = jigsaw (
&_jjig, // the config. opts
&_geom, // geom. data
NULL, // empty init. data
NULL, // empty hfun. data
&_mesh) ;
/*-------------------------------- print JIGSAW tria. */
printf("\n VERT2: \n\n") ;
for (indx_t _ipos = +0;
_ipos != _mesh._vert2._size ;
++_ipos )
{
printf("%1.4f, %1.4f\n",
_mesh._vert2.
_data[_ipos]._ppos[0],
_mesh._vert2.
_data[_ipos]._ppos[1]
) ;
}
printf("\n TRIA3: \n\n") ;
for (indx_t _ipos = +0;
_ipos != _mesh._tria3._size ;
++_ipos )
{
printf("%d, %d, %d\n",
_mesh._tria3.
_data[_ipos]._node[0],
_mesh._tria3.
_data[_ipos]._node[1],
_mesh._tria3.
_data[_ipos]._node[2]
) ;
}
jigsaw_free_msh_t(&_mesh);
printf (
"JIGSAW returned code: %d \n", _retv) ;
return _retv ;
}
|
81748.c | // SPDX-License-Identifier: GPL-2.0
#include <linux/compiler.h>
#include <linux/export.h>
#include <linux/kasan-checks.h>
#include <linux/thread_info.h>
#include <linux/uaccess.h>
#include <linux/kernel.h>
#include <linux/errno.h>
#include <linux/mm.h>
#include <asm/byteorder.h>
#include <asm/word-at-a-time.h>
#ifdef CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS
#define IS_UNALIGNED(src, dst) 0
#else
#define IS_UNALIGNED(src, dst) \
(((long) dst | (long) src) & (sizeof(long) - 1))
#endif
/*
* Do a strncpy, return length of string without final '\0'.
* 'count' is the user-supplied count (return 'count' if we
* hit it), 'max' is the address space maximum (and we return
* -EFAULT if we hit it).
*/
static inline long do_strncpy_from_user(char *dst, const char __user *src,
unsigned long count, unsigned long max)
{
const struct word_at_a_time constants = WORD_AT_A_TIME_CONSTANTS;
unsigned long res = 0;
if (IS_UNALIGNED(src, dst))
goto byte_at_a_time;
while (max >= sizeof(unsigned long)) {
unsigned long c, data;
/* Fall back to byte-at-a-time if we get a page fault */
unsafe_get_user(c, (unsigned long __user *)(src+res), byte_at_a_time);
*(unsigned long *)(dst+res) = c;
if (has_zero(c, &data, &constants)) {
data = prep_zero_mask(c, data, &constants);
data = create_zero_mask(data);
return res + find_zero(data);
}
res += sizeof(unsigned long);
max -= sizeof(unsigned long);
}
byte_at_a_time:
while (max) {
char c;
unsafe_get_user(c,src+res, efault);
dst[res] = c;
if (!c)
return res;
res++;
max--;
}
/*
* Uhhuh. We hit 'max'. But was that the user-specified maximum
* too? If so, that's ok - we got as much as the user asked for.
*/
if (res >= count)
return res;
/*
* Nope: we hit the address space limit, and we still had more
* characters the caller would have wanted. That's an EFAULT.
*/
efault:
return -EFAULT;
}
/**
* strncpy_from_user: - Copy a NUL terminated string from userspace.
* @dst: Destination address, in kernel space. This buffer must be at
* least @count bytes long.
* @src: Source address, in user space.
* @count: Maximum number of bytes to copy, including the trailing NUL.
*
* Copies a NUL-terminated string from userspace to kernel space.
*
* On success, returns the length of the string (not including the trailing
* NUL).
*
* If access to userspace fails, returns -EFAULT (some data may have been
* copied).
*
* If @count is smaller than the length of the string, copies @count bytes
* and returns @count.
*/
long strncpy_from_user(char *dst, const char __user *src, long count)
{
unsigned long max_addr, src_addr;
might_fault();
if (unlikely(count <= 0))
return 0;
max_addr = user_addr_max();
src_addr = (unsigned long)untagged_addr(src);
if (likely(src_addr < max_addr)) {
unsigned long max = max_addr - src_addr;
long retval;
/*
* Truncate 'max' to the user-specified limit, so that
* we only have one limit we need to check in the loop
*/
if (max > count)
max = count;
kasan_check_write(dst, count);
check_object_size(dst, count, false);
if (user_read_access_begin(src, max)) {
retval = do_strncpy_from_user(dst, src, count, max);
user_read_access_end();
return retval;
}
}
return -EFAULT;
}
EXPORT_SYMBOL(strncpy_from_user);
|
256871.c | // UARTTestMain.c
// Runs on LM3S8962
// Used to test the UART.c driver
// Daniel Valvano
// July 26, 2011
/* This example accompanies the book
"Embedded Systems: Real Time Interfacing to the Arm Cortex M3",
ISBN: 978-1463590154, Jonathan Valvano, copyright (c) 2011
Program 4.12, Section 4.9.4, Figures 4.26 and 4.40
Copyright 2011 by Jonathan W. Valvano, [email protected]
You may use, edit, run or distribute this file
as long as the above copyright notice remains
THIS SOFTWARE IS PROVIDED "AS IS". NO WARRANTIES, WHETHER EXPRESS, IMPLIED
OR STATUTORY, INCLUDING, BUT NOT LIMITED TO, IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE APPLY TO THIS SOFTWARE.
VALVANO SHALL NOT, IN ANY CIRCUMSTANCES, BE LIABLE FOR SPECIAL, INCIDENTAL,
OR CONSEQUENTIAL DAMAGES, FOR ANY REASON WHATSOEVER.
For more information about my classes, my research, and my books, see
http://users.ece.utexas.edu/~valvano/
*/
// U0Rx (VCP receive) connected to PA0
// U0Tx (VCP transmit) connected to PA1
#include "inc/hw_types.h"
#include "driverlib/sysctl.h"
#include "UART.h"
//---------------------OutCRLF---------------------
// Output a CR,LF to UART to go to a new line
// Input: none
// Output: none
void OutCRLF(void){
UART_OutChar(CR);
UART_OutChar(LF);
}
//debug code
int main(void){
unsigned char i;
char string[20]; // global to assist in debugging
unsigned long n;
//
// Set the clocking to run at 50MHz from the PLL.
//
SysCtlClockSet(SYSCTL_SYSDIV_4 | SYSCTL_USE_PLL | SYSCTL_OSC_MAIN |
SYSCTL_XTAL_8MHZ);
UART_Init(); // initialize UART
OutCRLF();
for(i='A'; i<='Z'; i=i+1){// print the uppercase alphabet
UART_OutChar(i);
}
OutCRLF();
UART_OutChar(' ');
for(i='a'; i<='z'; i=i+1){// print the lowercase alphabet
UART_OutChar(i);
}
OutCRLF();
UART_OutChar('-');
UART_OutChar('-');
UART_OutChar('>');
while(1){
UART_OutString("InString: ");
UART_InString(string,19);
UART_OutString(" OutString="); UART_OutString(string); OutCRLF();
UART_OutString("InUDec: "); n=UART_InUDec();
UART_OutString(" OutUDec="); UART_OutUDec(n); OutCRLF();
UART_OutString("InUHex: "); n=UART_InUHex();
UART_OutString(" OutUHex="); UART_OutUHex(n); OutCRLF();
}
}
|
337246.c | /* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE404_Improper_Resource_Shutdown__w32CreateFile_close_65b.c
Label Definition File: CWE404_Improper_Resource_Shutdown__w32CreateFile.label.xml
Template File: source-sinks-65b.tmpl.c
*/
/*
* @description
* CWE: 404 Improper Resource Shutdown or Release
* BadSource: Open a file using CreateFile()
* Sinks: close
* GoodSink: Close the file using CloseHandle()
* BadSink : Close the file using close()
* Flow Variant: 65 Data/control flow: data passed as an argument from one function to a function in a different source file called via a function pointer
*
* */
#include "std_testcase.h"
#include <windows.h>
#ifdef _WIN32
# define CLOSE _close
#else
# define CLOSE close
#endif
#ifndef OMITBAD
void CWE404_Improper_Resource_Shutdown__w32CreateFile_close_65b_bad_sink(HANDLE data)
{
if (data != INVALID_HANDLE_VALUE)
{
/* FLAW: Attempt to close the file using close() instead of CloseHandle() */
CLOSE((int)data);
}
}
#endif /* OMITBAD */
#ifndef OMITGOOD
/* goodB2G uses the BadSource with the GoodSink */
void CWE404_Improper_Resource_Shutdown__w32CreateFile_close_65b_goodB2G_sink(HANDLE data)
{
if (data != INVALID_HANDLE_VALUE)
{
/* FIX: Close the file using CloseHandle() */
CloseHandle(data);
}
}
#endif /* OMITGOOD */
|
902977.c | /* --COPYRIGHT--,BSD_EX
* Copyright (c) 2013, Texas Instruments Incorporated
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of Texas Instruments Incorporated nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
* OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
* EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*******************************************************************************
*
* MSP432 CODE EXAMPLE DISCLAIMER
*
* MSP432 code examples are self-contained low-level programs that typically
* demonstrate a single peripheral function or device feature in a highly
* concise manner. For this the code may rely on the device's power-on default
* register values and settings such as the clock configuration and care must
* be taken when combining code from several examples to avoid potential side
* effects. Also see http://www.ti.com/tool/mspdriverlib for an API functional
* library & https://dev.ti.com/pinmux/ for a GUI approach to peripheral configuration.
*
* --/COPYRIGHT--*/
//******************************************************************************
// MSP432P401 Demo - Enter Low-Frequency Active mode
//
//
// Description: Use low-frequency mode for low-frequency low-power CPU
// operation. For more LF examples, refer to msp432_pcm_06, which is
// based on code example and demonstrates peripheral operation (TimerA) in
// LF mode. For LF LPM0 example, refer to msp432_pcm_06 for TimerA
// operation in LF_LPM0.
//
// Note: the code in this example assumes the device is currently in LDO mode
// AM0_LDO or AM1_LDO (Active Mode using LDO, VCore=0/1 respectively)
//
// Transition from DCDC mode to LF mode requires intermediate transition through
// LDO mode. For more information refer to the PCM chapter in the device user's
// guide.
//
// AM1_DCDC <-----> AM1_LDO <--@--> AM1_LF
// ^
// |
// |
// v
// AM0_DCDC <-----> AM0_LDO* <--@--> AM0_LF
//
// *: power state condition after reset
// @: transitions demonstrated in this code example
//
// MSP432P401x
// -----------------
// /|\| |
// | | |
// --|RST |
// | P1.0|----> LED
// | |
//
// William Goh
// Texas Instruments Inc.
// June 2016 (updated) | November 2013 (created)
// Built with CCSv6.1, IAR, Keil, GCC
//******************************************************************************
#include "ti/devices/msp432p4xx/inc/msp.h"
#include <stdint.h>
void error(void);
int main(void)
{
uint32_t currentPowerState;
WDT_A->CTL = WDT_A_CTL_PW | // Stop WDT
WDT_A_CTL_HOLD;
// Terminate all remaining pins on the device
P1->DIR |= 0xFF; P1->OUT = 0;
P2->DIR |= 0xFF; P2->OUT = 0;
P3->DIR |= 0xFF; P3->OUT = 0;
P4->DIR |= 0xFF; P4->OUT = 0;
P5->DIR |= 0xFF; P5->OUT = 0;
P6->DIR |= 0xFF; P6->OUT = 0;
P7->DIR |= 0xFF; P7->OUT = 0;
P8->DIR |= 0xFF; P8->OUT = 0;
P9->DIR |= 0xFF; P9->OUT = 0;
P10->DIR |= 0xFF; P10->OUT = 0;
PJ->DIR |= 0xFF; PJ->OUT = 0;
// Switch MCLK over to REFO clock for low frequency operation first
CS->KEY = CS_KEY_VAL; // Unlock CS module
CS->CTL1 = (CS->CTL1 & ~(CS_CTL1_SELM_MASK | CS_CTL1_DIVM_MASK |
CS_CTL1_SELS_MASK | CS_CTL1_DIVS_MASK)) |
CS_CTL1_SELM_2 |
CS_CTL1_SELS_2;
CS->KEY = 0; // Lock CS module
// Get current power state
currentPowerState = PCM->CTL0 & PCM_CTL0_CPM_MASK;
// Transition to Low-Frequency Mode from current LDO power state properly
switch (currentPowerState)
{
case PCM_CTL0_CPM_0: // AM0_LDO, need to switch to AM0_Low-Frequency Mode
while ((PCM->CTL1 & PCM_CTL1_PMR_BUSY));
PCM->CTL0 = PCM_CTL0_KEY_VAL | PCM_CTL0_AMR_8;
while ((PCM->CTL1 & PCM_CTL1_PMR_BUSY));
if (PCM->IFG & PCM_IFG_AM_INVALID_TR_IFG)
error(); // Error if transition was not successful
break;
case PCM_CTL0_CPM_1: // AM1_LDO, need to switch to AM1_Low-Frequency Mode
while ((PCM->CTL1 & PCM_CTL1_PMR_BUSY));
PCM->CTL0 = PCM_CTL0_KEY_VAL | PCM_CTL0_AMR_9;
while ((PCM->CTL1 & PCM_CTL1_PMR_BUSY));
if (PCM->IFG & PCM_IFG_AM_INVALID_TR_IFG)
error(); // Error if transition was not successful
break;
case PCM_CTL0_CPM_8: // Device is already in AM0_Low-Frequency Mode
break;
case PCM_CTL0_CPM_9: // Device is already in AM1_Low-Frequency Mode
break;
default: // Device is in some other state, which is unexpected
error();
}
P1->OUT |= BIT0; // Transition LDO to Low-Frequency Mode successful
while(1);
}
void error(void)
{
volatile uint32_t i;
while (1)
{
P1->OUT ^= BIT0;
for(i = 0; i < 20000; i++); // Blink LED forever
}
}
|
636993.c | #include <onnx.h>
void resolver_default_op_Det(onnx_node_t *n) {
EMPTY_OPERATOR();
if (n->opset >= 11) {
}
}
|
310500.c | //------------------------------------------------------------------------------
// i8255-test.c
//------------------------------------------------------------------------------
#define CHIPS_IMPL
#include "chips/i8255.h"
#include "utest.h"
#define T(b) ASSERT_TRUE(b)
UTEST(i8255, mode_select) {
i8255_t ppi;
i8255_init(&ppi);
/* configure mode:
Port A: input
Port B: output
Port C: upper half: output, lower half: input
all on 'basic input/output' (the only one supported)
*/
uint8_t ctrl =
I8255_CTRL_CONTROL_MODE |
I8255_CTRL_A_INPUT |
I8255_CTRL_B_OUTPUT |
I8255_CTRL_CHI_OUTPUT |
I8255_CTRL_CLO_INPUT |
I8255_CTRL_BCLO_MODE_0 |
I8255_CTRL_ACHI_MODE_0;
uint64_t pins = I8255_CS|I8255_WR|I8255_A0|I8255_A1;
I8255_SET_PA(pins, 0x12);
I8255_SET_PB(pins, 0x34);
I8255_SET_PC(pins, 0x45);
I8255_SET_DATA(pins, ctrl);
uint64_t res_pins = i8255_tick(&ppi, pins);
T(I8255_GET_PA(res_pins) == 0x00);
T(I8255_GET_PB(res_pins) == 0x00);
T(I8255_GET_PC(res_pins) == 0x05);
T(ppi.control == ctrl);
/* test reading the control word back */
pins = I8255_CS|I8255_RD|I8255_A0|I8255_A1;
pins = i8255_tick(&ppi, pins);
uint8_t res_ctrl = I8255_GET_DATA(pins);
T(res_ctrl == ctrl);
}
UTEST(i8255, test_bit_set_clear) {
i8255_t ppi;
i8255_init(&ppi);
/* set port C to output */
uint8_t ctrl =
I8255_CTRL_CONTROL_MODE |
I8255_CTRL_CHI_OUTPUT |
I8255_CTRL_CLO_OUTPUT;
uint64_t pins = I8255_CS|I8255_WR|I8255_A0|I8255_A1;
I8255_SET_PA(pins, 0x12);
I8255_SET_PB(pins, 0x34);
I8255_SET_PC(pins, 0x45);
I8255_SET_DATA(pins, ctrl);
i8255_tick(&ppi, pins);
/* set bit 3 on port C */
ctrl = I8255_CTRL_CONTROL_BIT|I8255_CTRL_BIT_SET|(3<<1);
I8255_SET_DATA(pins, ctrl);
uint64_t res_pins = i8255_tick(&ppi, pins);
T(I8255_GET_PC(res_pins) == (1<<3)); // bit 3 must be set
/* set bit 5 on port C */
ctrl = I8255_CTRL_CONTROL_BIT|I8255_CTRL_BIT_SET|(5<<1);
I8255_SET_DATA(pins, ctrl);
res_pins = i8255_tick(&ppi, pins);
T(I8255_GET_PC(res_pins) == ((1<<5)|(1<<3))) // bit 3 and 5 must be set
/* clear bit 3 on port C */
ctrl = I8255_CTRL_CONTROL_BIT|I8255_CTRL_BIT_RESET|(5<<1);
I8255_SET_DATA(pins, ctrl);
res_pins = i8255_tick(&ppi, pins);
T(I8255_GET_PC(res_pins) == (1<<3)); // only bit 3 must be set
}
UTEST(i8255, in_out) {
i8255_t ppi;
i8255_init(&ppi);
/* configure mode:
Port A: input
Port B: output
Port C: upper half: output, lower half: input
all on 'basic input/output' (the only one supported)
*/
uint8_t ctrl =
I8255_CTRL_CONTROL_MODE |
I8255_CTRL_A_INPUT |
I8255_CTRL_B_OUTPUT |
I8255_CTRL_CHI_OUTPUT |
I8255_CTRL_CLO_INPUT |
I8255_CTRL_BCLO_MODE_0 |
I8255_CTRL_ACHI_MODE_0;
uint64_t pins = I8255_CS|I8255_WR|I8255_A0|I8255_A1;
I8255_SET_PA(pins, 0x12);
I8255_SET_PB(pins, 0x34);
I8255_SET_PC(pins, 0x45);
I8255_SET_DATA(pins, ctrl);
i8255_tick(&ppi, pins);
/* writing to an input port shouldn't do anything */
pins &= ~(I8255_A1|I8255_A0);
I8255_SET_PA(pins, 0x12);
I8255_SET_PB(pins, 0x34);
I8255_SET_PC(pins, 0x45);
I8255_SET_DATA(pins, 0x33);
uint64_t res_pins = i8255_tick(&ppi, pins);
T(I8255_GET_PA(res_pins) == 0);
/* writing to an output port (B) should invoke the out callback and set the output latch */
pins &= ~(I8255_A1|I8255_A0);
pins |= I8255_A0;
I8255_SET_DATA(pins, 0xAA);
res_pins = i8255_tick(&ppi, pins);
T(I8255_GET_PB(res_pins) == 0xAA);
T(ppi.pb.outp == 0xAA);
/* writing to port C should only affect the 'output half', and set all input half bits */
pins &= ~(I8255_A1|I8255_A0);
pins |= I8255_A1;
I8255_SET_DATA(pins, 0x77);
I8255_SET_PCLO(pins, 0x0F);
res_pins = i8255_tick(&ppi, pins);
T(I8255_GET_PC(res_pins) == 0x7F);
T(ppi.pc.outp == 0x77);
pins &= ~(I8255_A1|I8255_A0|I8255_RD|I8255_WR);
pins |= I8255_RD;
I8255_SET_PA(pins, 0xAB);
res_pins = i8255_tick(&ppi, pins);
T(I8255_GET_DATA(res_pins) == 0xAB);
/* reading an output port (B) should return the last output value */
pins &= ~(I8255_A1|I8255_A0|I8255_RD|I8255_WR);
pins |= I8255_RD|I8255_A0;
I8255_SET_PB(pins, 0x23);
res_pins = i8255_tick(&ppi, pins);
T(I8255_GET_DATA(res_pins) == 0xAA);
/* reading from mixed input/output return a mixed latched/input result */
pins &= ~(I8255_A1|I8255_A0|I8255_RD|I8255_WR);
pins |= I8255_RD|I8255_A1;
I8255_SET_PC(pins, 0x34);
res_pins = i8255_tick(&ppi, pins);
T(I8255_GET_DATA(res_pins) == 0x74);
}
|
150752.c | // SoftEther VPN Source Code - Developer Edition Master Branch
// Cedar Communication Module
// Sam.c
// Security Accounts Manager
#include "Sam.h"
#include "Account.h"
#include "Cedar.h"
#include "Hub.h"
#include "IPC.h"
#include "Proto_PPP.h"
#include "Radius.h"
#include "Server.h"
#include "Mayaqua/Encoding.h"
#include "Mayaqua/Internat.h"
#include "Mayaqua/Memory.h"
#include "Mayaqua/Microsoft.h"
#include "Mayaqua/Object.h"
#include "Mayaqua/Str.h"
#include <string.h>
#ifdef OS_UNIX
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <unistd.h>
#endif
PID OpenChildProcess(const char* path, char* const parameter[], int fd[] )
{
#ifdef OS_WIN32
// not implemented
return -1;
#else // OS_WIN32
// UNIX
int fds[2][2];
PID pid;
if (path == NULL || parameter == NULL || fd == NULL)
{
return (PID)-1;
}
if (pipe(fds[0]) != 0)
{
return (PID)-1;
}
if (pipe(fds[1]) != 0)
{
close(fds[0][0]);
close(fds[0][1]);
return (PID)-1;
}
pid = fork();
if (pid == (PID)0) {
int iError;
close(fds[0][1]);
close(fds[1][0]);
if (dup2(fds[0][0], fileno(stdin)) < 0 || dup2(fds[1][1], fileno(stdout)) < 0 )
{
close(fds[0][0]);
close(fds[1][1]);
_exit(EXIT_FAILURE);
}
iError = execvp(path, parameter);
// We should never come here
close(fds[0][0]);
close(fds[1][1]);
_exit(iError);
}
else if (pid > (PID)0)
{
close(fds[0][0]);
close(fds[1][1]);
fd[0] = fds[1][0];
fd[1] = fds[0][1];
return pid;
}
else
{
close(fds[0][0]);
close(fds[1][1]);
close(fds[0][1]);
close(fds[1][0]);
return -1;
}
#endif // OS_WIN32
}
void CloseChildProcess(PID pid, int* fd )
{
#ifdef OS_WIN32
// not implemented
#else // OS_WIN32
if( fd != 0 )
{
close(fd[0]);
close(fd[1]);
}
if( pid > 0 )
{
kill(pid, SIGTERM);
}
#endif // OS_WIN32
}
bool SmbAuthenticate(char* name, char* password, char* domainname, char* groupname, UINT timeout, UCHAR* challenge8, UCHAR* MsChapV2_ClientResponse, UCHAR* nt_pw_hash_hash)
{
bool auth = false;
int fds[2];
FILE* out, *in;
PID pid;
char ntlm_timeout[32];
char* proc_parameter[6];
// DNS Name 255 chars + OU names are limited to 64 characters + cmdline 32 + 1
char requiremember[352];
if (name == NULL || password == NULL || domainname == NULL || groupname == NULL)
{
Debug("Sam.c - SmbAuthenticate - wrong password parameter\n");
return false;
}
if (password[0] == '\0' && (challenge8 == NULL || MsChapV2_ClientResponse == NULL || nt_pw_hash_hash == NULL))
{
Debug("Sam.c - SmbAuthenticate - wrong MsCHAPv2 parameter\n");
return false;
}
// Truncate string if unsafe char
EnSafeStr(domainname, '\0');
if (strlen(domainname) > 255)
{
// there is no domainname longer then 255 chars!
// http://tools.ietf.org/html/rfc1035 section 2.3.4
domainname[255] = '\0';
}
// set timeout to 15 minutes even if timeout is disabled, to prevent ntlm_auth from hung up
if (timeout <= 0 || timeout > 900)
{
timeout = 999;
}
snprintf(ntlm_timeout, sizeof(ntlm_timeout), "%is", timeout);
Debug("Sam.c - timeout for ntlm_auth %s\n", ntlm_timeout);
proc_parameter[0] = "timeout";
proc_parameter[1] = ntlm_timeout;
proc_parameter[2] = "ntlm_auth";
proc_parameter[3] = "--helper-protocol=ntlm-server-1";
proc_parameter[4] = 0;
if (strlen(groupname) > 1)
{
// Truncate string if unsafe char
EnSafeStr(groupname, '\0');
snprintf(requiremember, sizeof(requiremember), "--require-membership-of=%s\\%s", domainname, groupname);
proc_parameter[4] = requiremember;
proc_parameter[5] = 0;
}
pid = OpenChildProcess("timeout", proc_parameter, fds);
if (pid < 0)
{
Debug("Sam.c - SmbCheckLogon - error fork child process (ntlm_auth)\n");
return false;
}
out = fdopen(fds[1], "w");
if (out == 0)
{
CloseChildProcess(pid, fds);
Debug("Sam.c - cant open out pipe (ntlm_auth)\n");
return false;
}
in = fdopen(fds[0], "r");
if (in == 0)
{
fclose(out);
CloseChildProcess(pid, fds);
Debug("Sam.c - cant open in pipe (ntlm_auth)\n");
return false;
}
{
char *base64 = Base64FromBin(NULL, name, StrLen(name));
fputs("Username:: ", out);
fputs(base64, out);
fputs("\n", out);
Free(base64);
base64 = Base64FromBin(NULL, domainname, StrLen(domainname));
fputs("NT-Domain:: ", out);
fputs(base64, out);
fputs("\n", out);
Free(base64);
if (IsEmptyStr(password) == false)
{
Debug("SmbAuthenticate(): Using password authentication...\n");
base64 = Base64FromBin(NULL, password, StrLen(password));
fputs("Password:: ", out);
fputs(base64, out);
fputs("\n", out);
Free(base64);
}
else
{
Debug("SmbAuthenticate(): Using MsChapV2 authentication...\n");
char *mschapv2_client_response = CopyBinToStr(MsChapV2_ClientResponse, 24);
base64 = Base64FromBin(NULL, mschapv2_client_response, 48);
Free(mschapv2_client_response);
fputs("NT-Response:: ", out);
fputs(base64, out);
fputs("\n", out);
Free(base64);
char *base64_challenge8 = CopyBinToStr(challenge8, 8);
base64 = Base64FromBin(NULL, base64_challenge8, 16);
Free(base64_challenge8);
fputs("LANMAN-Challenge:: ", out);
fputs(base64, out);
fputs("\n", out);
Free(base64);
fputs("Request-User-Session-Key: Yes\n", out);
}
// Start authentication
fputs( ".\n", out );
fflush (out);
// Request send!
char answer[300];
Zero(answer, sizeof(answer));
while (fgets(answer, sizeof(answer)-1, in))
{
char* response_parameter;
if (strncmp(answer, ".\n", sizeof(answer)-1 ) == 0)
{
break;
}
/* Indicates a base64 encoded structure */
response_parameter = strstr(answer, ":: ");
if (!response_parameter) {
char* newline;
response_parameter = strstr(answer, ": ");
if (!response_parameter) {
continue;
}
response_parameter[0] ='\0';
response_parameter++;
response_parameter[0] ='\0';
response_parameter++;
newline = strstr(response_parameter, "\n");
if( newline )
newline[0] = '\0';
} else {
response_parameter[0] ='\0';
response_parameter++;
response_parameter[0] ='\0';
response_parameter++;
response_parameter[0] ='\0';
response_parameter++;
const UINT end = Base64Decode(response_parameter, response_parameter, StrLen(response_parameter));
response_parameter[end] = '\0';
}
if (strncmp(answer, "Authenticated", sizeof(answer)-1 ) == 0)
{
if (strcmp(response_parameter, "Yes") == 0)
{
Debug("Authenticated!\n");
auth = true;
}
else if (strcmp(response_parameter, "No") == 0)
{
Debug("Authentication failed!\n");
auth = false;
}
}
else if (strncmp(answer, "User-Session-Key", sizeof(answer)-1 ) == 0)
{
if (nt_pw_hash_hash != NULL)
{
BUF* Buf = StrToBin(response_parameter);
Copy(nt_pw_hash_hash, Buf->Buf, 16);
FreeBuf(Buf);
}
}
}
}
fclose(in);
fclose(out);
CloseChildProcess(pid, fds);
return auth;
}
bool SmbCheckLogon(char* name, char* password, char* domainname, char* groupname, UINT timeout)
{
return SmbAuthenticate(name, password, domainname, groupname, timeout, NULL, NULL, NULL);
}
bool SmbPerformMsChapV2Auth(char* name, char* domainname, char* groupname, UCHAR* challenge8, UCHAR* MsChapV2_ClientResponse, UCHAR* nt_pw_hash_hash, UINT timeout)
{
return SmbAuthenticate(name, "", domainname, groupname, timeout, challenge8, MsChapV2_ClientResponse, nt_pw_hash_hash);
}
// Password encryption
void SecurePassword(void *secure_password, void *password, void *random)
{
BUF *b;
// Validate arguments
if (secure_password == NULL || password == NULL || random == NULL)
{
return;
}
b = NewBuf();
WriteBuf(b, password, SHA1_SIZE);
WriteBuf(b, random, SHA1_SIZE);
Sha0(secure_password, b->Buf, b->Size);
FreeBuf(b);
}
// Generate 160bit random number
void GenRandom(void *random)
{
// Validate arguments
if (random == NULL)
{
return;
}
Rand(random, SHA1_SIZE);
}
// Anonymous authentication of user
bool SamAuthUserByAnonymous(HUB *h, char *username)
{
bool b = false;
// Validate arguments
if (h == NULL || username == NULL)
{
return false;
}
AcLock(h);
{
USER *u = AcGetUser(h, username);
if (u)
{
Lock(u->lock);
{
if (u->AuthType == AUTHTYPE_ANONYMOUS)
{
b = true;
}
}
Unlock(u->lock);
}
ReleaseUser(u);
}
AcUnlock(h);
return b;
}
// Plaintext password authentication of user
bool SamAuthUserByPlainPassword(CONNECTION *c, HUB *hub, char *username, char *password, bool ast, UCHAR *mschap_v2_server_response_20, RADIUS_LOGIN_OPTION *opt)
{
bool b = false;
wchar_t *name = NULL;
wchar_t *groupname = NULL;
UINT timeout = 90;
bool auth_by_nt = false;
HUB *h;
// Validate arguments
if (hub == NULL || c == NULL || username == NULL)
{
return false;
}
if (GetGlobalServerFlag(GSF_DISABLE_RADIUS_AUTH) != 0)
{
return false;
}
h = hub;
AddRef(h->ref);
// Get the user name on authentication system
AcLock(hub);
{
USER *u;
u = AcGetUser(hub, ast == false ? username : "*");
if (u)
{
Lock(u->lock);
{
if (u->AuthType == AUTHTYPE_RADIUS)
{
// Radius authentication
AUTHRADIUS *auth = (AUTHRADIUS *)u->AuthData;
if (ast || auth->RadiusUsername == NULL || UniStrLen(auth->RadiusUsername) == 0)
{
if( IsEmptyStr(h->RadiusRealm) == false )
{
char name_and_realm[MAX_SIZE];
StrCpy(name_and_realm, sizeof(name_and_realm), username);
StrCat(name_and_realm, sizeof(name_and_realm), "@");
StrCat(name_and_realm, sizeof(name_and_realm), h->RadiusRealm);
name = CopyStrToUni(name_and_realm);
}
else
{
name = CopyStrToUni(username);
}
}
else
{
name = CopyUniStr(auth->RadiusUsername);
}
auth_by_nt = false;
}
else if (u->AuthType == AUTHTYPE_NT)
{
// NT authentication
AUTHNT *auth = (AUTHNT *)u->AuthData;
if (ast || auth->NtUsername == NULL || UniStrLen(auth->NtUsername) == 0)
{
name = CopyStrToUni(username);
}
else
{
name = CopyUniStr(auth->NtUsername);
}
groupname = CopyStrToUni(u->GroupName);
if (u->Policy)
{
timeout = u->Policy->TimeOut;
}
auth_by_nt = true;
}
}
Unlock(u->lock);
ReleaseUser(u);
}
}
AcUnlock(hub);
if (name != NULL)
{
if (auth_by_nt == false)
{
// Radius authentication
char radius_server_addr[MAX_SIZE];
UINT radius_server_port;
char radius_secret[MAX_SIZE];
char suffix_filter[MAX_SIZE];
wchar_t suffix_filter_w[MAX_SIZE];
UINT interval;
Zero(suffix_filter, sizeof(suffix_filter));
Zero(suffix_filter_w, sizeof(suffix_filter_w));
// Get the Radius server information
if (GetRadiusServerEx2(hub, radius_server_addr, sizeof(radius_server_addr), &radius_server_port, radius_secret, sizeof(radius_secret), &interval, suffix_filter, sizeof(suffix_filter)))
{
Unlock(hub->lock);
StrToUni(suffix_filter_w, sizeof(suffix_filter_w), suffix_filter);
if (UniIsEmptyStr(suffix_filter_w) || UniEndWith(name, suffix_filter_w))
{
// Attempt to login
b = RadiusLogin(c, radius_server_addr, radius_server_port,
radius_secret, StrLen(radius_secret),
name, password, interval, mschap_v2_server_response_20, opt, hub->Name);
if (b)
{
if (opt != NULL)
{
opt->Out_IsRadiusLogin = true;
}
}
}
Lock(hub->lock);
}
else
{
HLog(hub, "LH_NO_RADIUS_SETTING", name);
}
}
else
{
// NT authentication
#ifdef OS_WIN32
IPC_MSCHAP_V2_AUTHINFO mschap;
Unlock(hub->lock);
if (ParseAndExtractMsChapV2InfoFromPassword(&mschap, password) == false)
{
// Plaintext password authentication
b = MsCheckLogon(name, password);
}
else
{
UCHAR challenge8[8];
UCHAR nt_pw_hash_hash[16];
char nt_name[MAX_SIZE];
UniToStr(nt_name, sizeof(nt_name), name);
// MS-CHAPv2 authentication
MsChapV2_GenerateChallenge8(challenge8, mschap.MsChapV2_ClientChallenge,
mschap.MsChapV2_ServerChallenge,
mschap.MsChapV2_PPPUsername);
Debug("MsChapV2_PPPUsername = %s, nt_name = %s\n", mschap.MsChapV2_PPPUsername, nt_name);
b = MsPerformMsChapV2AuthByLsa(nt_name, challenge8, mschap.MsChapV2_ClientResponse, nt_pw_hash_hash);
if (b)
{
if (mschap_v2_server_response_20 != NULL)
{
MsChapV2Server_GenerateResponse(mschap_v2_server_response_20, nt_pw_hash_hash,
mschap.MsChapV2_ClientResponse, challenge8);
}
}
}
Lock(hub->lock);
#else // OS_WIN32
// Unix / Samba Winbind
IPC_MSCHAP_V2_AUTHINFO mschap;
Unlock(hub->lock);
char nt_name[MAX_SIZE];
char nt_username[MAX_SIZE];
char nt_groupname[MAX_SIZE];
char nt_domainname[MAX_SIZE];
UCHAR challenge8[8];
UCHAR nt_pw_hash_hash[16];
nt_groupname[0] = 0;
UniToStr(nt_name, sizeof(nt_name), name);
if (groupname != NULL)
UniToStr(nt_groupname, sizeof(nt_groupname), groupname);
ParseNtUsername(nt_name, nt_username, sizeof(nt_username), nt_domainname, sizeof(nt_domainname), false);
if (ParseAndExtractMsChapV2InfoFromPassword(&mschap, password) == false)
{
// Plaintext password authentication
b = SmbCheckLogon(nt_username, password, nt_domainname, nt_groupname, timeout);
}
else
{
// MS-CHAPv2 authentication
MsChapV2_GenerateChallenge8(challenge8, mschap.MsChapV2_ClientChallenge,
mschap.MsChapV2_ServerChallenge,
mschap.MsChapV2_PPPUsername);
Debug("MsChapV2_PPPUsername = %s, nt_name = %s\n", mschap.MsChapV2_PPPUsername, nt_name);
b = SmbPerformMsChapV2Auth(nt_username, nt_domainname, nt_groupname, challenge8, mschap.MsChapV2_ClientResponse, nt_pw_hash_hash, timeout);
if (b)
{
if (mschap_v2_server_response_20 != NULL)
{
MsChapV2Server_GenerateResponse(mschap_v2_server_response_20, nt_pw_hash_hash,
mschap.MsChapV2_ClientResponse, challenge8);
}
}
}
Lock(hub->lock);
#endif // OS_WIN32 / OS_LINUX
}
// Memory release
if( groupname != NULL )
Free(groupname);
Free(name);
}
ReleaseHub(h);
return b;
}
// Certificate authentication of user
bool SamAuthUserByCert(HUB *h, char *username, X *x)
{
bool b = false;
// Validate arguments
if (h == NULL || username == NULL || x == NULL)
{
return false;
}
if (GetGlobalServerFlag(GSF_DISABLE_CERT_AUTH) != 0)
{
return false;
}
// Check expiration date
if (CheckXDateNow(x) == false)
{
return false;
}
// Check the Certification Revocation List
if (IsValidCertInHub(h, x) == false)
{
// Bad
wchar_t tmp[MAX_SIZE * 2];
// Log the contents of the certificate
GetAllNameFromX(tmp, sizeof(tmp), x);
HLog(h, "LH_AUTH_NG_CERT", username, tmp);
return false;
}
AcLock(h);
{
USER *u;
u = AcGetUser(h, username);
if (u)
{
Lock(u->lock);
{
if (u->AuthType == AUTHTYPE_USERCERT)
{
// Check whether to matche with the registered certificate
AUTHUSERCERT *auth = (AUTHUSERCERT *)u->AuthData;
if (CompareX(auth->UserX, x))
{
b = true;
}
}
else if (u->AuthType == AUTHTYPE_ROOTCERT)
{
// Check whether the certificate has been signed by the root certificate
AUTHROOTCERT *auth = (AUTHROOTCERT *)u->AuthData;
if (h->HubDb != NULL)
{
LockList(h->HubDb->RootCertList);
{
X *root_cert;
root_cert = GetIssuerFromList(h->HubDb->RootCertList, x);
if (root_cert != NULL)
{
b = true;
if (auth->CommonName != NULL && UniIsEmptyStr(auth->CommonName) == false)
{
// Compare the CN
if (UniStrCmpi(x->subject_name->CommonName, auth->CommonName) != 0)
{
b = false;
}
}
if (auth->Serial != NULL && auth->Serial->size >= 1)
{
// Compare the serial number
if (CompareXSerial(x->serial, auth->Serial) == false)
{
b = false;
}
}
}
}
UnlockList(h->HubDb->RootCertList);
}
}
}
Unlock(u->lock);
ReleaseUser(u);
}
}
AcUnlock(h);
if (b)
{
wchar_t tmp[MAX_SIZE * 2];
// Log the contents of the certificate
GetAllNameFromX(tmp, sizeof(tmp), x);
HLog(h, "LH_AUTH_OK_CERT", username, tmp);
}
return b;
}
// Get the root certificate that signed the specified certificate from the list
X *GetIssuerFromList(LIST *cert_list, X *cert)
{
UINT i;
X *ret = NULL;
// Validate arguments
if (cert_list == NULL || cert == NULL)
{
return NULL;
}
for (i = 0;i < LIST_NUM(cert_list);i++)
{
X *x = LIST_DATA(cert_list, i);
// Name comparison
if (CheckXDateNow(x))
{
if (CompareName(x->subject_name, cert->issuer_name))
{
// Get the public key of the root certificate
K *k = GetKFromX(x);
if (k != NULL)
{
// Check the signature
if (CheckSignature(cert, k))
{
ret = x;
}
FreeK(k);
}
}
}
if (CompareX(x, cert))
{
// Complete identical
ret = x;
}
}
return ret;
}
// Get the policy to be applied for the user
POLICY *SamGetUserPolicy(HUB *h, char *username)
{
POLICY *ret = NULL;
// Validate arguments
if (h == NULL || username == NULL)
{
return NULL;
}
AcLock(h);
{
USER *u;
u = AcGetUser(h, username);
if (u)
{
USERGROUP *g = NULL;
Lock(u->lock);
{
if (u->Policy != NULL)
{
ret = ClonePolicy(u->Policy);
}
g = u->Group;
if (g != NULL)
{
AddRef(g->ref);
}
}
Unlock(u->lock);
ReleaseUser(u);
u = NULL;
if (ret == NULL)
{
if (g != NULL)
{
Lock(g->lock);
{
ret = ClonePolicy(g->Policy);
}
Unlock(g->lock);
}
}
if (g != NULL)
{
ReleaseGroup(g);
}
}
}
AcUnlock(h);
return ret;
}
// Password authentication of user
bool SamAuthUserByPassword(HUB *h, char *username, void *random, void *secure_password, char *mschap_v2_password, UCHAR *mschap_v2_server_response_20, UINT *err)
{
bool b = false;
UCHAR secure_password_check[SHA1_SIZE];
bool is_mschap = false;
IPC_MSCHAP_V2_AUTHINFO mschap;
UINT dummy = 0;
// Validate arguments
if (h == NULL || username == NULL || secure_password == NULL)
{
return false;
}
if (err == NULL)
{
err = &dummy;
}
*err = 0;
Zero(&mschap, sizeof(mschap));
is_mschap = ParseAndExtractMsChapV2InfoFromPassword(&mschap, mschap_v2_password);
if (StrCmpi(username, ADMINISTRATOR_USERNAME) == 0)
{
// Administrator mode
SecurePassword(secure_password_check, h->SecurePassword, random);
if (Cmp(secure_password_check, secure_password, SHA1_SIZE) == 0)
{
return true;
}
else
{
return false;
}
}
AcLock(h);
{
USER *u;
u = AcGetUser(h, username);
if (u)
{
Lock(u->lock);
{
if (u->AuthType == AUTHTYPE_PASSWORD)
{
AUTHPASSWORD *auth = (AUTHPASSWORD *)u->AuthData;
if (is_mschap == false)
{
// Normal password authentication
SecurePassword(secure_password_check, auth->HashedKey, random);
if (Cmp(secure_password_check, secure_password, SHA1_SIZE) == 0)
{
b = true;
}
}
else
{
// MS-CHAP v2 authentication via PPP
UCHAR challenge8[8];
UCHAR client_response[24];
if (IsZero(auth->NtLmSecureHash, MD5_SIZE))
{
// NTLM hash is not registered in the user account
*err = ERR_MSCHAP2_PASSWORD_NEED_RESET;
}
else
{
UCHAR nt_pw_hash_hash[16];
Zero(challenge8, sizeof(challenge8));
Zero(client_response, sizeof(client_response));
MsChapV2_GenerateChallenge8(challenge8, mschap.MsChapV2_ClientChallenge, mschap.MsChapV2_ServerChallenge,
mschap.MsChapV2_PPPUsername);
MsChapV2Client_GenerateResponse(client_response, challenge8, auth->NtLmSecureHash);
if (Cmp(client_response, mschap.MsChapV2_ClientResponse, 24) == 0)
{
// Hash matched
b = true;
// Calculate the response
GenerateNtPasswordHashHash(nt_pw_hash_hash, auth->NtLmSecureHash);
MsChapV2Server_GenerateResponse(mschap_v2_server_response_20, nt_pw_hash_hash,
client_response, challenge8);
}
}
}
}
}
Unlock(u->lock);
ReleaseUser(u);
}
}
AcUnlock(h);
return b;
}
// Make sure that the user exists
bool SamIsUser(HUB *h, char *username)
{
bool b;
// Validate arguments
if (h == NULL || username == NULL)
{
return false;
}
AcLock(h);
{
b = AcIsUser(h, username);
}
AcUnlock(h);
return b;
}
// Get the type of authentication used by the user
UINT SamGetUserAuthType(HUB *h, char *username)
{
UINT authtype;
// Validate arguments
if (h == NULL || username == NULL)
{
return INFINITE;
}
AcLock(h);
{
USER *u = AcGetUser(h, username);
if (u == NULL)
{
authtype = INFINITE;
}
else
{
authtype = u->AuthType;
ReleaseUser(u);
}
}
AcUnlock(h);
return authtype;
}
|
177014.c | /****************************************************************************
*
* Copyright 2019 Samsung Electronics 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.
*
****************************************************************************/
/****************************************************************************
* Included Files
****************************************************************************/
#include <tinyara/config.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <debug.h>
#include <errno.h>
#include <fcntl.h>
#include <tinyara/os_api_test_drv.h>
#include <tinyara/binfmt/compression/compress_read.h>
#include <tinyara/kmalloc.h>
#define READSIZE 2048
/****************************************************************************
* Private Declarations
****************************************************************************/
/****************************************************************************
* Private Function
****************************************************************************/
static int test_compress_decompress_function(unsigned long arg)
{
int i;
FILE *filefp;
int filefd;
int ret;
off_t filelen;
unsigned int size;
size_t readsize = READSIZE;
uint8_t *dst_buffer;
struct s_header *compression_header;
filefp = fopen("/mnt/myfile_comp", "r");
filefd = fileno(filefp);
if (filefd < 0) {
int errval = get_errno();
berr("Failed to open file ERROR = %d\n", errval);
return -errval;
}
ret = compress_init(filefd, 0, &filelen);
if (ret != OK) {
berr("Failed to read header for compressed binary : %d\n", ret);
return ret;
}
compression_header = get_compression_header();
dst_buffer = (uint8_t *)kmm_malloc(READSIZE * sizeof(uint8_t));
if (dst_buffer == NULL) {
berr("Allocation of memory failed\n");
compress_uninit();
return ERROR;
}
for (i = 0; i < (compression_header->sections - 1); i++) {
size = compress_read(filefd, 0, dst_buffer, readsize, i * READSIZE);
if (size != READSIZE) {
berr("Read for compressed block %d failed\n", i);
compress_uninit();
kmm_free(dst_buffer);
return ERROR;
}
}
compress_uninit();
kmm_free(dst_buffer);
return OK;
}
/****************************************************************************
* Public Functions
****************************************************************************/
int test_compress_decompress(int cmd, unsigned long arg)
{
int ret = -EINVAL;
switch (cmd) {
case TESTIOC_COMPRESSION_TEST:
ret = test_compress_decompress_function(arg);
break;
}
return ret;
}
|
531538.c | #include <std.h>
#include "../../serakii.h"
inherit STORAGE"trade_road.c";
void create(){
::create();
set_long(::query_long()+"\n%^C252%^To the north you can see a massive fortress%^CRST%^\n");
set_exits(([
"south" : ROAD"2",
"north" : ROAD"7",
]));
}
|
46548.c | /****************************************************************************
* boards/arm/stm32l4/nucleo-l452re/src/stm32_autoleds.c
*
* Copyright (C) 2017-2018 Gregory Nutt. All rights reserved.
* Author: Gregory Nutt <[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.
* 3. Neither the name NuttX nor the names of its contributors may be
* used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
****************************************************************************/
/****************************************************************************
* Included Files
****************************************************************************/
#include <nuttx/config.h>
#include <stdint.h>
#include <stdbool.h>
#include <debug.h>
#include <nuttx/board.h>
#include "chip.h"
#include "up_arch.h"
#include "up_internal.h"
#include "stm32l4_gpio.h"
#include "nucleo-l452re.h"
#include <arch/board/board.h>
#ifdef CONFIG_ARCH_LEDS
/****************************************************************************
* Public Functions
****************************************************************************/
/****************************************************************************
* Name: board_autoled_initialize
****************************************************************************/
void board_autoled_initialize(void)
{
/* Configure LD2 GPIO for output */
stm32l4_configgpio(GPIO_LD2);
}
/****************************************************************************
* Name: board_autoled_on
****************************************************************************/
void board_autoled_on(int led)
{
if (led == 1)
{
stm32l4_gpiowrite(GPIO_LD2, true);
}
}
/****************************************************************************
* Name: board_autoled_off
****************************************************************************/
void board_autoled_off(int led)
{
if (led == 1)
{
stm32l4_gpiowrite(GPIO_LD2, false);
}
}
#endif /* CONFIG_ARCH_LEDS */
|
883606.c | // 編號:19-0330N0L2_Array-Exercise_For.c
// 程式類別:C語言
// 基礎題:陣列 ( 難度 ** )
// 題目:奇偶順序重組
// 時間:NULL ( 不限 ) //最佳 1s內
// 內存大小:128MB
// 創建一個SIZE為100的Arr 陣列並給予預設值 100 到 0,
// 其次將所有奇數順序(由小到大)存放到Arr,而偶數則
// 尾隨其後, 依序存放(由小到大)到Arr陣列中。
// 輸出格式:
// printf(“Arr[%d] = %d\n”, ??); //問號為自定變數
// *注意:
// 不能使用外部覆蓋法,例如直接引用for i++ i<=50
// 來儲存奇數到Arr。
// *提示:
// 可以使用Arr2 來轉儲 Arr 中所有的奇數,
// 再使用Arr3 來轉儲 Arr 中所有的偶數,
// 再依次 轉儲到 Arr中。
// //缺點:需要額外更多的空間來做為暫時性儲存,浪費空間資源
// Input 格式: NULL(無)
// Output 格式:
// Arr[0] = 1
// Arr[1] = 3
// Arr[2] = 5
// …
// Arr[51] = 2
// Arr[52] = 4
// Arr[53] = 6
// …
#include <stdio.h>
#define SIZE 100
int main(void){
/*變量宣告*/
int i;
int count_Odd, count_Even;
int Arr[SIZE];
int Arr_odd_Num[50];
int Arr_Even_Num[50];
/*初始化Arr陣列中的數值:由100~1*/
int counter = 0;
for(i=SIZE; i>0; i--){
Arr[counter] = i;
//printf("Arr[%d] = %d\n", j, Arr[j]); // Testing
counter++;
}
/*奇偶分隔——分別存放在不同陣列中*/
count_Odd = 50-1; //50-1是因為 陣列編號為 0~49
count_Even = 50-1; //同上
for(i=0; i<SIZE; i++){
if(Arr[i]%2 == 1){//判斷是否為奇數,是:存放到 Arr_odd_Num陣列中; 否:存放到 Arr_Even_Num陣列中
Arr_odd_Num[count_Odd] = Arr[i];
count_Odd--; //由於Arr是由大到小排序, 利用減減把較大的數值由後往前存,實現由小到大排序的反轉效果
}else{
Arr_Even_Num[count_Odd] = Arr[i];
count_Even--; //原理同上
}
}
/*回存資料——奇偶同時存放到Arr陣列中*/
for(i=0; i<SIZE-50; i++){//已知內100的奇偶數為50:50,因此可以同時儲存,這使得for循環上限為50次即可
Arr[i] = Arr_odd_Num[i]; //存放奇數:Arr[0~49]
/*偶數需要由50開始存放*/
Arr[i+50] = Arr_Even_Num[i];//存放偶數:Arr[50~99]
}
/*輸出*/
for(i=0; i<SIZE; i++){
printf("Arr[%d] = %d\n", i, Arr[i]);
}
return 0;
}
|
219575.c | /* mafIndex - Index maf file based on a particular target. */
/* Copyright (C) 2011 The Regents of the University of California
* See kent/LICENSE or http://genome.ucsc.edu/license/ for licensing information. */
#include "common.h"
#include "linefile.h"
#include "hash.h"
#include "options.h"
#include "maf.h"
void usage()
/* Explain usage and exit. */
{
errAbort(
"mafIndex - Index maf file based on a particular target\n"
"usage:\n"
" mafIndex targetSeq in.maf out.maf.ix\n"
"options:\n"
" -xxx=XXX\n"
);
}
static struct optionSpec options[] = {
{NULL, 0},
};
void mafIndex(char *target, char *in, char *out)
/* mafIndex - Index maf file based on a particular target. */
{
struct mafFile *mf = mafOpen(in);
FILE *f = mustOpen(out, "w");
struct mafAli *maf;
struct mafComp *mc;
off_t pos;
while ((maf = mafNextWithPos(mf, &pos)) != NULL)
{
mc = mafMayFindComponent(maf, target);
if (mc != NULL)
fprintf(f, "%d %d %llu\n", mc->start, mc->size, (unsigned long long)pos);
}
mafFileFree(&mf);
carefulClose(&f);
}
int main(int argc, char *argv[])
/* Process command line. */
{
optionInit(&argc, argv, options);
if (argc != 4)
usage();
mafIndex(argv[1], argv[2], argv[3]);
return 0;
}
|
927229.c | /*
* Copyright (c) 2009-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 "server.h"
#include <math.h> /* isnan(), isinf() */
/* Forward declarations */
int getGenericCommand(client *c);
/*-----------------------------------------------------------------------------
* String Commands
*----------------------------------------------------------------------------*/
static int checkStringLength(client *c, long long size) {
if (!(c->flags & CLIENT_MASTER) && size > server.proto_max_bulk_len) {
addReplyError(c,"string exceeds maximum allowed size (proto-max-bulk-len)");
return C_ERR;
}
return C_OK;
}
/* The setGenericCommand() function implements the SET operation with different
* options and variants. This function is called in order to implement the
* following commands: SET, SETEX, PSETEX, SETNX, GETSET.
*
* 'flags' changes the behavior of the command (NX, XX or GET, see below).
*
* 'expire' represents an expire to set in form of a Redis object as passed
* by the user. It is interpreted according to the specified 'unit'.
*
* 'ok_reply' and 'abort_reply' is what the function will reply to the client
* if the operation is performed, or when it is not because of NX or
* XX flags.
*
* If ok_reply is NULL "+OK" is used.
* If abort_reply is NULL, "$-1" is used. */
#define OBJ_SET_NO_FLAGS 0
#define OBJ_SET_NX (1<<0) /* Set if key not exists. */
#define OBJ_SET_XX (1<<1) /* Set if key exists. */
#define OBJ_SET_EX (1<<2) /* Set if time in seconds is given */
#define OBJ_SET_PX (1<<3) /* Set if time in ms in given */
#define OBJ_SET_KEEPTTL (1<<4) /* Set and keep the ttl */
#define OBJ_SET_GET (1<<5) /* Set if want to get key before set */
void setGenericCommand(client *c, int flags, robj *key, robj *val, robj *expire, int unit, robj *ok_reply, robj *abort_reply) {
long long milliseconds = 0; /* initialized to avoid any harmness warning */
if (expire) {
if (getLongLongFromObjectOrReply(c, expire, &milliseconds, NULL) != C_OK)
return;
if (milliseconds <= 0) {
addReplyErrorFormat(c,"invalid expire time in %s",c->cmd->name);
return;
}
if (unit == UNIT_SECONDS) milliseconds *= 1000;
}
if ((flags & OBJ_SET_NX && lookupKeyWrite(c->db,key) != NULL) ||
(flags & OBJ_SET_XX && lookupKeyWrite(c->db,key) == NULL))
{
addReply(c, abort_reply ? abort_reply : shared.null[c->resp]);
return;
}
if (flags & OBJ_SET_GET) {
if (getGenericCommand(c) == C_ERR) return;
}
genericSetKey(c,c->db,key,val,flags & OBJ_SET_KEEPTTL,1);
server.dirty++;
if (expire) setExpire(c,c->db,key,mstime()+milliseconds);
notifyKeyspaceEvent(NOTIFY_STRING,"set",key,c->db->id);
if (expire) notifyKeyspaceEvent(NOTIFY_GENERIC,
"expire",key,c->db->id);
if (!(flags & OBJ_SET_GET)) {
addReply(c, ok_reply ? ok_reply : shared.ok);
}
}
/* SET key value [NX] [XX] [KEEPTTL] [GET] [EX <seconds>] [PX <milliseconds>] */
void setCommand(client *c) {
int j;
robj *expire = NULL;
int unit = UNIT_SECONDS;
int flags = OBJ_SET_NO_FLAGS;
for (j = 3; j < c->argc; j++) {
char *a = c->argv[j]->ptr;
robj *next = (j == c->argc-1) ? NULL : c->argv[j+1];
if ((a[0] == 'n' || a[0] == 'N') &&
(a[1] == 'x' || a[1] == 'X') && a[2] == '\0' &&
!(flags & OBJ_SET_XX) && !(flags & OBJ_SET_GET))
{
flags |= OBJ_SET_NX;
} else if ((a[0] == 'x' || a[0] == 'X') &&
(a[1] == 'x' || a[1] == 'X') && a[2] == '\0' &&
!(flags & OBJ_SET_NX))
{
flags |= OBJ_SET_XX;
} else if ((a[0] == 'g' || a[0] == 'G') &&
(a[1] == 'e' || a[1] == 'E') &&
(a[2] == 't' || a[2] == 'T') && a[3] == '\0' &&
!(flags & OBJ_SET_NX)) {
flags |= OBJ_SET_GET;
} else if (!strcasecmp(c->argv[j]->ptr,"KEEPTTL") &&
!(flags & OBJ_SET_EX) && !(flags & OBJ_SET_PX))
{
flags |= OBJ_SET_KEEPTTL;
} else if ((a[0] == 'e' || a[0] == 'E') &&
(a[1] == 'x' || a[1] == 'X') && a[2] == '\0' &&
!(flags & OBJ_SET_KEEPTTL) &&
!(flags & OBJ_SET_PX) && next)
{
flags |= OBJ_SET_EX;
unit = UNIT_SECONDS;
expire = next;
j++;
} else if ((a[0] == 'p' || a[0] == 'P') &&
(a[1] == 'x' || a[1] == 'X') && a[2] == '\0' &&
!(flags & OBJ_SET_KEEPTTL) &&
!(flags & OBJ_SET_EX) && next)
{
flags |= OBJ_SET_PX;
unit = UNIT_MILLISECONDS;
expire = next;
j++;
} else {
addReplyErrorObject(c,shared.syntaxerr);
return;
}
}
c->argv[2] = tryObjectEncoding(c->argv[2]);
setGenericCommand(c,flags,c->argv[1],c->argv[2],expire,unit,NULL,NULL);
/* Propagate without the GET argument */
if (flags & OBJ_SET_GET) {
int argc = 0;
robj **argv = zmalloc((c->argc-1)*sizeof(robj*));
for (j=0; j < c->argc; j++) {
char *a = c->argv[j]->ptr;
/* Skip GET which may be repeated multiple times. */
if (j >= 3 &&
(a[0] == 'g' || a[0] == 'G') &&
(a[1] == 'e' || a[1] == 'E') &&
(a[2] == 't' || a[2] == 'T') && a[3] == '\0')
continue;
argv[argc++] = c->argv[j];
incrRefCount(c->argv[j]);
}
replaceClientCommandVector(c, argc, argv);
}
}
void setnxCommand(client *c) {
c->argv[2] = tryObjectEncoding(c->argv[2]);
setGenericCommand(c,OBJ_SET_NX,c->argv[1],c->argv[2],NULL,0,shared.cone,shared.czero);
}
void setexCommand(client *c) {
c->argv[3] = tryObjectEncoding(c->argv[3]);
setGenericCommand(c,OBJ_SET_NO_FLAGS,c->argv[1],c->argv[3],c->argv[2],UNIT_SECONDS,NULL,NULL);
}
void psetexCommand(client *c) {
c->argv[3] = tryObjectEncoding(c->argv[3]);
setGenericCommand(c,OBJ_SET_NO_FLAGS,c->argv[1],c->argv[3],c->argv[2],UNIT_MILLISECONDS,NULL,NULL);
}
int getGenericCommand(client *c) {
robj *o;
if ((o = lookupKeyReadOrReply(c,c->argv[1],shared.null[c->resp])) == NULL)
return C_OK;
if (checkType(c,o,OBJ_STRING)) {
return C_ERR;
}
addReplyBulk(c,o);
return C_OK;
}
void getCommand(client *c) {
getGenericCommand(c);
}
void getsetCommand(client *c) {
if (getGenericCommand(c) == C_ERR) return;
c->argv[2] = tryObjectEncoding(c->argv[2]);
setKey(c,c->db,c->argv[1],c->argv[2]);
notifyKeyspaceEvent(NOTIFY_STRING,"set",c->argv[1],c->db->id);
server.dirty++;
/* Propagate as SET command */
robj *setcmd = createStringObject("SET",3);
rewriteClientCommandArgument(c,0,setcmd);
decrRefCount(setcmd);
}
void setrangeCommand(client *c) {
robj *o;
long offset;
sds value = c->argv[3]->ptr;
if (getLongFromObjectOrReply(c,c->argv[2],&offset,NULL) != C_OK)
return;
if (offset < 0) {
addReplyError(c,"offset is out of range");
return;
}
o = lookupKeyWrite(c->db,c->argv[1]);
if (o == NULL) {
/* Return 0 when setting nothing on a non-existing string */
if (sdslen(value) == 0) {
addReply(c,shared.czero);
return;
}
/* Return when the resulting string exceeds allowed size */
if (checkStringLength(c,offset+sdslen(value)) != C_OK)
return;
o = createObject(OBJ_STRING,sdsnewlen(NULL, offset+sdslen(value)));
dbAdd(c->db,c->argv[1],o);
} else {
size_t olen;
/* Key exists, check type */
if (checkType(c,o,OBJ_STRING))
return;
/* Return existing string length when setting nothing */
olen = stringObjectLen(o);
if (sdslen(value) == 0) {
addReplyLongLong(c,olen);
return;
}
/* Return when the resulting string exceeds allowed size */
if (checkStringLength(c,offset+sdslen(value)) != C_OK)
return;
/* Create a copy when the object is shared or encoded. */
o = dbUnshareStringValue(c->db,c->argv[1],o);
}
if (sdslen(value) > 0) {
o->ptr = sdsgrowzero(o->ptr,offset+sdslen(value));
memcpy((char*)o->ptr+offset,value,sdslen(value));
signalModifiedKey(c,c->db,c->argv[1]);
notifyKeyspaceEvent(NOTIFY_STRING,
"setrange",c->argv[1],c->db->id);
server.dirty++;
}
addReplyLongLong(c,sdslen(o->ptr));
}
void getrangeCommand(client *c) {
robj *o;
long long start, end;
char *str, llbuf[32];
size_t strlen;
if (getLongLongFromObjectOrReply(c,c->argv[2],&start,NULL) != C_OK)
return;
if (getLongLongFromObjectOrReply(c,c->argv[3],&end,NULL) != C_OK)
return;
if ((o = lookupKeyReadOrReply(c,c->argv[1],shared.emptybulk)) == NULL ||
checkType(c,o,OBJ_STRING)) return;
if (o->encoding == OBJ_ENCODING_INT) {
str = llbuf;
strlen = ll2string(llbuf,sizeof(llbuf),(long)o->ptr);
} else {
str = o->ptr;
strlen = sdslen(str);
}
/* Convert negative indexes */
if (start < 0 && end < 0 && start > end) {
addReply(c,shared.emptybulk);
return;
}
if (start < 0) start = strlen+start;
if (end < 0) end = strlen+end;
if (start < 0) start = 0;
if (end < 0) end = 0;
if ((unsigned long long)end >= strlen) end = strlen-1;
/* Precondition: end >= 0 && end < strlen, so the only condition where
* nothing can be returned is: start > end. */
if (start > end || strlen == 0) {
addReply(c,shared.emptybulk);
} else {
addReplyBulkCBuffer(c,(char*)str+start,end-start+1);
}
}
void mgetCommand(client *c) {
int j;
addReplyArrayLen(c,c->argc-1);
for (j = 1; j < c->argc; j++) {
robj *o = lookupKeyRead(c->db,c->argv[j]);
if (o == NULL) {
addReplyNull(c);
} else {
if (o->type != OBJ_STRING) {
addReplyNull(c);
} else {
addReplyBulk(c,o);
}
}
}
}
void msetGenericCommand(client *c, int nx) {
int j;
if ((c->argc % 2) == 0) {
addReplyError(c,"wrong number of arguments for MSET");
return;
}
/* Handle the NX flag. The MSETNX semantic is to return zero and don't
* set anything if at least one key already exists. */
if (nx) {
for (j = 1; j < c->argc; j += 2) {
if (lookupKeyWrite(c->db,c->argv[j]) != NULL) {
addReply(c, shared.czero);
return;
}
}
}
for (j = 1; j < c->argc; j += 2) {
c->argv[j+1] = tryObjectEncoding(c->argv[j+1]);
setKey(c,c->db,c->argv[j],c->argv[j+1]);
notifyKeyspaceEvent(NOTIFY_STRING,"set",c->argv[j],c->db->id);
}
server.dirty += (c->argc-1)/2;
addReply(c, nx ? shared.cone : shared.ok);
}
void msetCommand(client *c) {
msetGenericCommand(c,0);
}
void msetnxCommand(client *c) {
msetGenericCommand(c,1);
}
void incrDecrCommand(client *c, long long incr) {
long long value, oldvalue;
robj *o, *new;
o = lookupKeyWrite(c->db,c->argv[1]);
if (checkType(c,o,OBJ_STRING)) return;
if (getLongLongFromObjectOrReply(c,o,&value,NULL) != C_OK) return;
oldvalue = value;
if ((incr < 0 && oldvalue < 0 && incr < (LLONG_MIN-oldvalue)) ||
(incr > 0 && oldvalue > 0 && incr > (LLONG_MAX-oldvalue))) {
addReplyError(c,"increment or decrement would overflow");
return;
}
value += incr;
if (o && o->refcount == 1 && o->encoding == OBJ_ENCODING_INT &&
(value < 0 || value >= OBJ_SHARED_INTEGERS) &&
value >= LONG_MIN && value <= LONG_MAX)
{
new = o;
o->ptr = (void*)((long)value);
} else {
new = createStringObjectFromLongLongForValue(value);
if (o) {
dbOverwrite(c->db,c->argv[1],new);
} else {
dbAdd(c->db,c->argv[1],new);
}
}
signalModifiedKey(c,c->db,c->argv[1]);
notifyKeyspaceEvent(NOTIFY_STRING,"incrby",c->argv[1],c->db->id);
server.dirty++;
addReply(c,shared.colon);
addReply(c,new);
addReply(c,shared.crlf);
}
void incrCommand(client *c) {
incrDecrCommand(c,1);
}
void decrCommand(client *c) {
incrDecrCommand(c,-1);
}
void incrbyCommand(client *c) {
long long incr;
if (getLongLongFromObjectOrReply(c, c->argv[2], &incr, NULL) != C_OK) return;
incrDecrCommand(c,incr);
}
void decrbyCommand(client *c) {
long long incr;
if (getLongLongFromObjectOrReply(c, c->argv[2], &incr, NULL) != C_OK) return;
incrDecrCommand(c,-incr);
}
void incrbyfloatCommand(client *c) {
long double incr, value;
robj *o, *new, *aux1, *aux2;
o = lookupKeyWrite(c->db,c->argv[1]);
if (checkType(c,o,OBJ_STRING)) return;
if (getLongDoubleFromObjectOrReply(c,o,&value,NULL) != C_OK ||
getLongDoubleFromObjectOrReply(c,c->argv[2],&incr,NULL) != C_OK)
return;
value += incr;
if (isnan(value) || isinf(value)) {
addReplyError(c,"increment would produce NaN or Infinity");
return;
}
new = createStringObjectFromLongDouble(value,1);
if (o)
dbOverwrite(c->db,c->argv[1],new);
else
dbAdd(c->db,c->argv[1],new);
signalModifiedKey(c,c->db,c->argv[1]);
notifyKeyspaceEvent(NOTIFY_STRING,"incrbyfloat",c->argv[1],c->db->id);
server.dirty++;
addReplyBulk(c,new);
/* Always replicate INCRBYFLOAT as a SET command with the final value
* in order to make sure that differences in float precision or formatting
* will not create differences in replicas or after an AOF restart. */
aux1 = createStringObject("SET",3);
rewriteClientCommandArgument(c,0,aux1);
decrRefCount(aux1);
rewriteClientCommandArgument(c,2,new);
aux2 = createStringObject("KEEPTTL",7);
rewriteClientCommandArgument(c,3,aux2);
decrRefCount(aux2);
}
void appendCommand(client *c) {
size_t totlen;
robj *o, *append;
o = lookupKeyWrite(c->db,c->argv[1]);
if (o == NULL) {
/* Create the key */
c->argv[2] = tryObjectEncoding(c->argv[2]);
dbAdd(c->db,c->argv[1],c->argv[2]);
incrRefCount(c->argv[2]);
totlen = stringObjectLen(c->argv[2]);
} else {
/* Key exists, check type */
if (checkType(c,o,OBJ_STRING))
return;
/* "append" is an argument, so always an sds */
append = c->argv[2];
totlen = stringObjectLen(o)+sdslen(append->ptr);
if (checkStringLength(c,totlen) != C_OK)
return;
/* Append the value */
o = dbUnshareStringValue(c->db,c->argv[1],o);
o->ptr = sdscatlen(o->ptr,append->ptr,sdslen(append->ptr));
totlen = sdslen(o->ptr);
}
signalModifiedKey(c,c->db,c->argv[1]);
notifyKeyspaceEvent(NOTIFY_STRING,"append",c->argv[1],c->db->id);
server.dirty++;
addReplyLongLong(c,totlen);
}
void strlenCommand(client *c) {
robj *o;
if ((o = lookupKeyReadOrReply(c,c->argv[1],shared.czero)) == NULL ||
checkType(c,o,OBJ_STRING)) return;
addReplyLongLong(c,stringObjectLen(o));
}
/* STRALGO -- Implement complex algorithms on strings.
*
* STRALGO <algorithm> ... arguments ... */
void stralgoLCS(client *c); /* This implements the LCS algorithm. */
void stralgoCommand(client *c) {
/* Select the algorithm. */
if (!strcasecmp(c->argv[1]->ptr,"lcs")) {
stralgoLCS(c);
} else {
addReplyErrorObject(c,shared.syntaxerr);
}
}
/* STRALGO <algo> [IDX] [MINMATCHLEN <len>] [WITHMATCHLEN]
* STRINGS <string> <string> | KEYS <keya> <keyb>
*/
void stralgoLCS(client *c) {
uint32_t i, j;
long long minmatchlen = 0;
sds a = NULL, b = NULL;
int getlen = 0, getidx = 0, withmatchlen = 0;
robj *obja = NULL, *objb = NULL;
for (j = 2; j < (uint32_t)c->argc; j++) {
char *opt = c->argv[j]->ptr;
int moreargs = (c->argc-1) - j;
if (!strcasecmp(opt,"IDX")) {
getidx = 1;
} else if (!strcasecmp(opt,"LEN")) {
getlen = 1;
} else if (!strcasecmp(opt,"WITHMATCHLEN")) {
withmatchlen = 1;
} else if (!strcasecmp(opt,"MINMATCHLEN") && moreargs) {
if (getLongLongFromObjectOrReply(c,c->argv[j+1],&minmatchlen,NULL)
!= C_OK) goto cleanup;
if (minmatchlen < 0) minmatchlen = 0;
j++;
} else if (!strcasecmp(opt,"STRINGS") && moreargs > 1) {
if (a != NULL) {
addReplyError(c,"Either use STRINGS or KEYS");
goto cleanup;
}
a = c->argv[j+1]->ptr;
b = c->argv[j+2]->ptr;
j += 2;
} else if (!strcasecmp(opt,"KEYS") && moreargs > 1) {
if (a != NULL) {
addReplyError(c,"Either use STRINGS or KEYS");
goto cleanup;
}
obja = lookupKeyRead(c->db,c->argv[j+1]);
objb = lookupKeyRead(c->db,c->argv[j+2]);
if ((obja && obja->type != OBJ_STRING) ||
(objb && objb->type != OBJ_STRING))
{
addReplyError(c,
"The specified keys must contain string values");
/* Don't cleanup the objects, we need to do that
* only after callign getDecodedObject(). */
obja = NULL;
objb = NULL;
goto cleanup;
}
obja = obja ? getDecodedObject(obja) : createStringObject("",0);
objb = objb ? getDecodedObject(objb) : createStringObject("",0);
a = obja->ptr;
b = objb->ptr;
j += 2;
} else {
addReplyErrorObject(c,shared.syntaxerr);
goto cleanup;
}
}
/* Complain if the user passed ambiguous parameters. */
if (a == NULL) {
addReplyError(c,"Please specify two strings: "
"STRINGS or KEYS options are mandatory");
goto cleanup;
} else if (getlen && getidx) {
addReplyError(c,
"If you want both the length and indexes, please "
"just use IDX.");
goto cleanup;
}
/* Compute the LCS using the vanilla dynamic programming technique of
* building a table of LCS(x,y) substrings. */
uint32_t alen = sdslen(a);
uint32_t blen = sdslen(b);
/* Setup an uint32_t array to store at LCS[i,j] the length of the
* LCS A0..i-1, B0..j-1. Note that we have a linear array here, so
* we index it as LCS[j+(blen+1)*j] */
uint32_t *lcs = zmalloc((alen+1)*(blen+1)*sizeof(uint32_t));
#define LCS(A,B) lcs[(B)+((A)*(blen+1))]
/* Start building the LCS table. */
for (uint32_t i = 0; i <= alen; i++) {
for (uint32_t j = 0; j <= blen; j++) {
if (i == 0 || j == 0) {
/* If one substring has length of zero, the
* LCS length is zero. */
LCS(i,j) = 0;
} else if (a[i-1] == b[j-1]) {
/* The len LCS (and the LCS itself) of two
* sequences with the same final character, is the
* LCS of the two sequences without the last char
* plus that last char. */
LCS(i,j) = LCS(i-1,j-1)+1;
} else {
/* If the last character is different, take the longest
* between the LCS of the first string and the second
* minus the last char, and the reverse. */
uint32_t lcs1 = LCS(i-1,j);
uint32_t lcs2 = LCS(i,j-1);
LCS(i,j) = lcs1 > lcs2 ? lcs1 : lcs2;
}
}
}
/* Store the actual LCS string in "result" if needed. We create
* it backward, but the length is already known, we store it into idx. */
uint32_t idx = LCS(alen,blen);
sds result = NULL; /* Resulting LCS string. */
void *arraylenptr = NULL; /* Deffered length of the array for IDX. */
uint32_t arange_start = alen, /* alen signals that values are not set. */
arange_end = 0,
brange_start = 0,
brange_end = 0;
/* Do we need to compute the actual LCS string? Allocate it in that case. */
int computelcs = getidx || !getlen;
if (computelcs) result = sdsnewlen(SDS_NOINIT,idx);
/* Start with a deferred array if we have to emit the ranges. */
uint32_t arraylen = 0; /* Number of ranges emitted in the array. */
if (getidx) {
addReplyMapLen(c,2);
addReplyBulkCString(c,"matches");
arraylenptr = addReplyDeferredLen(c);
}
i = alen, j = blen;
while (computelcs && i > 0 && j > 0) {
int emit_range = 0;
if (a[i-1] == b[j-1]) {
/* If there is a match, store the character and reduce
* the indexes to look for a new match. */
result[idx-1] = a[i-1];
/* Track the current range. */
if (arange_start == alen) {
arange_start = i-1;
arange_end = i-1;
brange_start = j-1;
brange_end = j-1;
} else {
/* Let's see if we can extend the range backward since
* it is contiguous. */
if (arange_start == i && brange_start == j) {
arange_start--;
brange_start--;
} else {
emit_range = 1;
}
}
/* Emit the range if we matched with the first byte of
* one of the two strings. We'll exit the loop ASAP. */
if (arange_start == 0 || brange_start == 0) emit_range = 1;
idx--; i--; j--;
} else {
/* Otherwise reduce i and j depending on the largest
* LCS between, to understand what direction we need to go. */
uint32_t lcs1 = LCS(i-1,j);
uint32_t lcs2 = LCS(i,j-1);
if (lcs1 > lcs2)
i--;
else
j--;
if (arange_start != alen) emit_range = 1;
}
/* Emit the current range if needed. */
uint32_t match_len = arange_end - arange_start + 1;
if (emit_range) {
if (minmatchlen == 0 || match_len >= minmatchlen) {
if (arraylenptr) {
addReplyArrayLen(c,2+withmatchlen);
addReplyArrayLen(c,2);
addReplyLongLong(c,arange_start);
addReplyLongLong(c,arange_end);
addReplyArrayLen(c,2);
addReplyLongLong(c,brange_start);
addReplyLongLong(c,brange_end);
if (withmatchlen) addReplyLongLong(c,match_len);
arraylen++;
}
}
arange_start = alen; /* Restart at the next match. */
}
}
/* Signal modified key, increment dirty, ... */
/* Reply depending on the given options. */
if (arraylenptr) {
addReplyBulkCString(c,"len");
addReplyLongLong(c,LCS(alen,blen));
setDeferredArrayLen(c,arraylenptr,arraylen);
} else if (getlen) {
addReplyLongLong(c,LCS(alen,blen));
} else {
addReplyBulkSds(c,result);
result = NULL;
}
/* Cleanup. */
sdsfree(result);
zfree(lcs);
cleanup:
if (obja) decrRefCount(obja);
if (objb) decrRefCount(objb);
return;
}
|
312918.c | #include <stdio.h>
#include <stdbool.h>
#define sarr 16
int main()
{
printf("Goodbye, world.\n");
short array[sarr] = {0};
unsigned char crc[65536][sarr] = {0};
unsigned long long step;
bool stop = false;
for (short i = 0; i < sarr; i++) {
scanf("%hd", &array[i]);
}
for (step = 0; ; step++) {
short max = 0;
for (short i = 0; i < sarr; i++) {
if (array[i] > array[max]) max = i;
}
for (short i = 0; i < sarr; i++) {
crc[step][i] = (unsigned char)array[i];
}
// printf("\n%I64u", step);
if (step) {
for (short i = 0; i < step; i++) {
for (short j = 0; j < sarr; j++) {
stop = true;
if (crc[step][j] != crc[i][j]) {
stop = false;
break;
}
}
if (stop) {
printf("\n%I64u", step);
return 0;
}
}
}
short buffer = array[max];
array[max] = 0;
max++;
if (buffer > 200) return -1;
for (; buffer; max++) {
if (max > sarr) max = 0;
array[max]++;
buffer--;
}
}
return 0;
}
|
495117.c | /*
* Copyright (c) 2014-2015, Google, Inc. All rights reserved
*
* 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 <assert.h>
#include <compiler.h>
#include <err.h>
#include <reflist.h>
#include <kernel/mutex.h>
#include <kernel/thread.h>
#include <platform/interrupts.h>
#include <stddef.h>
#include <stdlib.h>
#include <string.h>
#include <trace.h>
#include <lk/init.h>
#include "vqueue.h"
#include <virtio/virtio_ring.h>
#include <virtio/virtio_config.h>
#include "l4virtio_priv.h"
#include <lib/trusty/handle.h>
#include <lib/trusty/ipc.h>
#include <lib/trusty/ipc_msg.h>
#include <lib/trusty/tipc_dev.h>
#define LOCAL_TRACE 0
#define MAX_RX_IOVS 1
#define MAX_TX_IOVS 1
/*
* Control endpoint address
*/
#define TIPC_CTRL_ADDR (53)
/*
* Max number of opned channels supported
*/
#define TIPC_ADDR_MAX_NUM 256
/*
* Local adresses base
*/
#define TIPC_ADDR_BASE 1000
/*
* Maximum service name size
*/
#define TIPC_MAX_SRV_NAME_LEN (256)
/*
* Timeout for rx thread ipc send retry (msec)
*/
#define TIPC_RX_RETRY_TIMEOUT 5000
enum {
VDEV_STATE_RESET = 0,
VDEV_STATE_GOING_ONLINE,
VDEV_STATE_ACTIVE,
};
struct tipc_ept {
uint32_t remote;
handle_t *chan;
};
struct tipc_dev {
volatile int state;
const uuid_t *uuid;
const void *descr_ptr;
size_t descr_size;
struct l4virtio_config *cfg;
struct l4virtio_queue_config *queue_cfg;
vaddr_t driver_window;
struct vqueue vqs[TIPC_VQ_NUM];
struct tipc_ept epts[TIPC_ADDR_MAX_NUM];
unsigned long inuse[BITMAP_NUM_WORDS(TIPC_ADDR_MAX_NUM)];
event_t rx_retry;
event_t have_handles;
handle_list_t handle_list;
mutex_t ept_lock;
thread_t *rx_thread;
thread_t *tx_thread;
bool tx_stop;
bool rx_stop;
};
struct tipc_hdr {
uint32_t src;
uint32_t dst;
uint32_t reserved;
uint16_t len;
uint16_t flags;
uint8_t data[0];
} __PACKED;
enum tipc_ctrl_msg_types {
TIPC_CTRL_MSGTYPE_GO_ONLINE = 1,
TIPC_CTRL_MSGTYPE_GO_OFFLINE,
TIPC_CTRL_MSGTYPE_CONN_REQ,
TIPC_CTRL_MSGTYPE_CONN_RSP,
TIPC_CTRL_MSGTYPE_DISC_REQ,
};
/*
* TIPC control message consists of common tipc_ctrl_msg_hdr
* immediately followed by message specific body which also
* could be empty.
*
* struct tipc_ctrl_msg {
* struct tipc_ctrl_msg_hdr hdr;
* uint8_t body[0];
* } __PACKED;
*
*/
struct tipc_ctrl_msg_hdr {
uint32_t type;
uint32_t body_len;
} __PACKED;
struct tipc_conn_req_body {
char name[TIPC_MAX_SRV_NAME_LEN];
} __PACKED;
struct tipc_conn_rsp_body {
uint32_t target;
uint32_t status;
uint32_t remote;
uint32_t max_msg_size;
uint32_t max_msg_cnt;
} __PACKED;
struct tipc_disc_req_body {
uint32_t target;
} __PACKED;
typedef int (*tipc_data_cb_t) (uint8_t *dst, size_t sz, void *ctx);
static int
tipc_send_data(struct tipc_dev *dev, uint32_t local, uint32_t remote,
tipc_data_cb_t cb, void *cb_ctx, uint16_t data_len,
bool wait);
static int
tipc_send_buf(struct tipc_dev *dev, uint32_t local, uint32_t remote,
void *data, uint16_t data_len, bool wait);
static inline uint addr_to_slot(uint32_t addr)
{
return (uint)(addr - TIPC_ADDR_BASE);
}
static inline uint32_t slot_to_addr(uint slot)
{
return (uint32_t) (slot + TIPC_ADDR_BASE);
}
static uint32_t alloc_local_addr(struct tipc_dev *dev, uint32_t remote,
handle_t *chan)
{
int slot = bitmap_ffz(dev->inuse, TIPC_ADDR_MAX_NUM);
if (slot >= 0) {
bitmap_set(dev->inuse, slot);
dev->epts[slot].chan = chan;
dev->epts[slot].remote = remote;
return slot_to_addr(slot);
}
return 0;
}
static struct tipc_ept *lookup_ept(struct tipc_dev *dev, uint32_t local)
{
uint slot = addr_to_slot(local);
if (slot < TIPC_ADDR_MAX_NUM) {
if (bitmap_test(dev->inuse, slot)) {
return &dev->epts[slot];
}
}
return NULL;
}
static uint32_t ept_to_addr(struct tipc_dev *dev, struct tipc_ept *ept)
{
return slot_to_addr(ept - dev->epts);
}
static void free_local_addr(struct tipc_dev *dev, uint32_t local)
{
uint slot = addr_to_slot(local);
if (slot < TIPC_ADDR_MAX_NUM) {
bitmap_clear(dev->inuse, slot);
dev->epts[slot].chan = NULL;
dev->epts[slot].remote = 0;
}
}
static int virtio_dev_to_kvaddr(struct tipc_dev *dev, paddr_t da, size_t size,
void **va)
{
struct tipc_vdev_descr *desc = (struct tipc_vdev_descr *) dev->descr_ptr;
if (size > desc->driver_mem_size || da > desc->driver_mem_size - size)
return ERR_NO_RESOURCES;
*va = (void *)(dev->driver_window + da);
return NO_ERROR;
}
int virtio_dev_to_phys(struct tipc_dev *dev, paddr_t da, size_t size,
paddr_t *pa)
{
void *va;
status_t ret;
ret = virtio_dev_to_kvaddr(dev, da, size, &va);
if (ret)
return ret;
*pa = vaddr_to_paddr(va);
if (*pa == (paddr_t)NULL)
return ERR_NO_RESOURCES;
return NO_ERROR;
}
static int virtio_map_iovs(struct tipc_dev *dev, struct vqueue_iovs *vqiovs, u_int flags)
{
uint i;
int ret = NO_ERROR;
for (i = 0; i < vqiovs->used; i++) {
void *va;
ret = virtio_dev_to_kvaddr(dev, vqiovs->phys[i],
vqiovs->iovs[i].len, &va);
if (ret)
break;
vqiovs->iovs[i].base = va;
}
return ret;
}
static void virtio_unmap_iovs(struct vqueue_iovs *vqiovs)
{
for (uint i = 0; i < vqiovs->used; i++) {
/* base is expected to be set */
DEBUG_ASSERT(vqiovs->iovs[i].base);
/* don't do anything at the moment, the memory is fixed */
vqiovs->iovs[i].base = NULL;
}
}
static int _go_online(struct tipc_dev *dev)
{
struct {
struct tipc_ctrl_msg_hdr hdr;
/* body is empty */
} msg;
msg.hdr.type = TIPC_CTRL_MSGTYPE_GO_ONLINE;
msg.hdr.body_len = 0;
dev->state = VDEV_STATE_GOING_ONLINE;
return tipc_send_buf(dev, TIPC_CTRL_ADDR, TIPC_CTRL_ADDR,
&msg, sizeof(msg), true);
}
/*
* When getting a notify for the TX vq, it is the other side telling us
* that buffers are now available
*/
static int tipc_tx_vq_notify_cb(struct vqueue *vq, void *priv)
{
vqueue_signal_avail(vq);
return 0;
}
static int tipc_rx_vq_notify_cb(struct vqueue *vq, void *priv)
{
vqueue_signal_avail(vq);
return 0;
}
static const vqueue_cb_t notify_cbs[TIPC_VQ_NUM] = {
[TIPC_VQ_TX] = tipc_tx_vq_notify_cb,
[TIPC_VQ_RX] = tipc_rx_vq_notify_cb,
};
static int send_conn_rsp(struct tipc_dev *dev, uint32_t local,
uint32_t remote, uint32_t status,
uint32_t msg_sz, uint32_t msg_cnt)
{
struct {
struct tipc_ctrl_msg_hdr hdr;
struct tipc_conn_rsp_body body;
} msg;
msg.hdr.type = TIPC_CTRL_MSGTYPE_CONN_RSP;
msg.hdr.body_len = sizeof(msg.body);
msg.body.target = remote;
msg.body.status = status;
msg.body.remote = local;
msg.body.max_msg_size = msg_sz;
msg.body.max_msg_cnt = msg_cnt;
return tipc_send_buf(dev, TIPC_CTRL_ADDR, TIPC_CTRL_ADDR,
&msg, sizeof(msg), true);
}
static int send_disc_req(struct tipc_dev *dev, uint32_t local, uint32_t remote)
{
struct {
struct tipc_ctrl_msg_hdr hdr;
struct tipc_disc_req_body body;
} msg;
msg.hdr.type = TIPC_CTRL_MSGTYPE_DISC_REQ;
msg.hdr.body_len = sizeof(msg.body);
msg.body.target = remote;
return tipc_send_buf(dev, local, TIPC_CTRL_ADDR,
&msg, sizeof(msg), true);
}
static int handle_conn_req(struct tipc_dev *dev, uint32_t remote,
const volatile struct tipc_conn_req_body *ns_req)
{
int err;
uint32_t local = 0;
handle_t *chan = NULL;
struct tipc_conn_req_body req;
LTRACEF("remote %u\n", remote);
strncpy(req.name, (const char *)ns_req->name, sizeof(req.name));
/* open ipc channel */
err = ipc_port_connect_async(dev->uuid, req.name, sizeof(req.name),
0, &chan);
if (err == NO_ERROR) {
mutex_acquire(&dev->ept_lock);
local = alloc_local_addr(dev, remote, chan);
if (local == 0) {
LTRACEF("failed to alloc local address\n");
handle_close(chan);
chan = NULL;
}
mutex_release(&dev->ept_lock);
}
if (chan) {
LTRACEF("new handle: local = 0x%x remote = 0x%x\n",
local, remote);
handle_set_cookie(chan, lookup_ept(dev, local));
handle_list_add(&dev->handle_list, chan);
event_signal(&dev->have_handles, false);
return NO_ERROR;
}
err = send_conn_rsp(dev, local, remote, ERR_NO_RESOURCES, 0, 0);
if (err) {
TRACEF("failed (%d) to send response\n", err);
}
return err;
}
static int handle_disc_req(struct tipc_dev *dev, uint32_t remote,
const volatile struct tipc_disc_req_body *ns_req)
{
struct tipc_ept *ept;
uint32_t target = ns_req->target;
LTRACEF("remote %u: target %u\n", remote, target);
mutex_acquire(&dev->ept_lock);
/* Ultimately we have to lookup channel by remote address.
* Local address is also provided by remote side but there
* is a scenario when it might not be valid. Nevertheless,
* we can try to use it first before doing full lookup.
*/
ept = lookup_ept(dev, target);
if (!ept || ept->remote != remote) {
ept = NULL;
/* do full search: TODO search handle list */
for (uint slot = 0; slot < countof(dev->epts); slot++) {
if (bitmap_test(dev->inuse, slot)) {
if (dev->epts[slot].remote == remote) {
ept = &dev->epts[slot];
break;
}
}
}
}
if (ept) {
handle_t *chan = ept->chan;
if (chan) {
/* detach handle from handle list */
handle_list_del(&dev->handle_list, chan);
/* detach ept */
handle_set_cookie(chan, NULL);
/* close handle */
handle_close(chan);
}
free_local_addr(dev, ept_to_addr(dev, ept));
}
mutex_release(&dev->ept_lock);
return NO_ERROR;
}
static int handle_ctrl_msg(struct tipc_dev *dev, uint32_t remote,
const volatile void *ns_data, size_t msg_len)
{
uint32_t msg_type;
size_t msg_body_len;
const volatile void *ns_msg_body;
const volatile struct tipc_ctrl_msg_hdr *ns_msg_hdr = ns_data;
DEBUG_ASSERT(ns_data);
/* do some sanity checks */
if (msg_len < sizeof(struct tipc_ctrl_msg_hdr)) {
LTRACEF("%s: remote=%u: ttl_len=%zu\n",
"malformed msg", remote, msg_len);
return ERR_NOT_VALID;
}
msg_type = ns_msg_hdr->type;
msg_body_len = ns_msg_hdr->body_len;
ns_msg_body = (const volatile uint8_t *)ns_data + sizeof(struct tipc_ctrl_msg_hdr);
if (sizeof(struct tipc_ctrl_msg_hdr) + msg_body_len != msg_len)
goto err_mailformed_msg;
switch (msg_type) {
case TIPC_CTRL_MSGTYPE_CONN_REQ:
if (msg_body_len != sizeof(struct tipc_conn_req_body))
break;
return handle_conn_req(dev, remote, ns_msg_body);
case TIPC_CTRL_MSGTYPE_DISC_REQ:
if (msg_body_len != sizeof(struct tipc_disc_req_body))
break;
return handle_disc_req(dev, remote, ns_msg_body);
default:
break;
}
err_mailformed_msg:
LTRACEF("%s: remote=%u: ttl_len=%zu msg_type=%u msg_len=%zu\n",
"malformed msg", remote, msg_len, msg_type, msg_body_len);
return ERR_NOT_VALID;
}
static void signal_rx_retry(struct tipc_dev *dev)
{
/* unblock and set reschedule=true for the rx thread */
LTRACEF("sending rx_retry signal\n");
event_signal(&dev->rx_retry, true);
}
static int handle_chan_msg(struct tipc_dev *dev, uint32_t remote, uint32_t local,
const volatile void *ns_data, size_t len)
{
struct tipc_ept *ept;
int ret;
ipc_msg_kern_t msg = {
.iov = (iovec_kern_t []) {
[0] = {
.base = (void *)ns_data,
.len = len,
},
},
.num_iov = 1,
.num_handles = 0,
};
event_unsignal(&dev->rx_retry);
retry_send_msg:
ret = ERR_NOT_FOUND;
mutex_acquire(&dev->ept_lock);
ept = lookup_ept(dev, local);
if (ept && ept->remote == remote) {
if (ept->chan)
ret = ipc_send_msg(ept->chan, &msg);
}
mutex_release(&dev->ept_lock);
if (ret == ERR_NOT_ENOUGH_BUFFER) {
LTRACEF("waiting for rx_retry signal...\n");
ret = event_wait_timeout(&dev->rx_retry,
TIPC_RX_RETRY_TIMEOUT);
if (ret == NO_ERROR) {
LTRACEF("... retrying ipc_send_msg\n");
goto retry_send_msg;
}
/* timeout not fatal; just not expected and will drop a msg */
DEBUG_ASSERT(ret != ERR_TIMED_OUT);
}
return ret;
}
static int handle_rx_msg(struct tipc_dev *dev, struct vqueue_buf *buf)
{
const volatile struct tipc_hdr *ns_hdr;
const volatile void *ns_data;
size_t ns_data_len;
uint32_t src_addr;
uint32_t dst_addr;
DEBUG_ASSERT(dev);
DEBUG_ASSERT(buf);
LTRACEF("got RX buf: head %hu buf in %d out %d\n",
buf->head, buf->in_iovs.used, buf->out_iovs.used);
/* we will need at least 1 iovec */
if (buf->in_iovs.used == 0) {
LTRACEF("unexpected in_iovs num %d\n", buf->in_iovs.used);
return ERR_INVALID_ARGS;
}
/* there should be exactly 1 in_iov but it is not fatal if the first
one is big enough */
if (buf->in_iovs.used != 1) {
LTRACEF("unexpected in_iovs num %d\n", buf->in_iovs.used);
}
/* out_iovs are not supported: just log message and ignore it */
if (buf->out_iovs.used != 0) {
LTRACEF("unexpected out_iovs num %d\n", buf->in_iovs.used);
}
/* map in_iovs, Non-secure, no-execute, cached, read-only */
uint map_flags = ARCH_MMU_FLAG_NS | ARCH_MMU_FLAG_PERM_NO_EXECUTE |
ARCH_MMU_FLAG_CACHED | ARCH_MMU_FLAG_PERM_RO;
int ret = virtio_map_iovs(dev, &buf->in_iovs, map_flags);
if (ret) {
TRACEF("failed to map iovs %d\n", ret);
return ret;
}
/* check message size */
if (buf->in_iovs.iovs[0].len < sizeof(struct tipc_hdr)) {
LTRACEF("msg too short %zu\n", buf->in_iovs.iovs[0].len);
ret = ERR_INVALID_ARGS;
goto done;
}
ns_hdr = buf->in_iovs.iovs[0].base;
ns_data = (uint8_t *)buf->in_iovs.iovs[0].base + sizeof(struct tipc_hdr);
ns_data_len = ns_hdr->len;
src_addr = ns_hdr->src;
dst_addr = ns_hdr->dst;
if (ns_data_len + sizeof(struct tipc_hdr) != buf->in_iovs.iovs[0].len) {
LTRACEF("malformed message len %zu msglen %zu\n",
ns_data_len, buf->in_iovs.iovs[0].len);
ret = ERR_INVALID_ARGS;
goto done;
}
if (dst_addr == TIPC_CTRL_ADDR)
ret = handle_ctrl_msg(dev, src_addr, ns_data, ns_data_len);
else
ret = handle_chan_msg(dev, src_addr, dst_addr, ns_data, ns_data_len);
done:
virtio_unmap_iovs(&buf->in_iovs);
return ret;
}
static int tipc_rx_thread_func(void *arg)
{
struct tipc_dev *dev = arg;
paddr_t in_phys[MAX_RX_IOVS];
iovec_kern_t in_iovs[MAX_RX_IOVS];
struct vqueue *vq = &dev->vqs[TIPC_VQ_RX];
struct vqueue_buf buf;
int ret;
LTRACEF("enter\n");
ret = _go_online(dev);
if (ret == NO_ERROR) {
dev->state = VDEV_STATE_ACTIVE;
}
LTRACEF("Device is online\n");
memset(&buf, 0, sizeof(buf));
buf.in_iovs.cnt = MAX_RX_IOVS;
buf.in_iovs.phys = in_phys;
buf.in_iovs.iovs = in_iovs;
while(!dev->rx_stop) {
/* wait for next available buffer */
event_wait(&vq->avail_event);
ret = vqueue_get_avail_buf(vq, &buf);
if (ret == ERR_CHANNEL_CLOSED)
break; /* need to terminate */
if (ret == ERR_NOT_ENOUGH_BUFFER)
continue; /* no new messages */
if (likely(ret == NO_ERROR)) {
ret = handle_rx_msg(dev, &buf);
if (ret < 0)
TRACEF("Error (%d) dropping msg!\n", ret);
}
ret = vqueue_add_buf(vq, &buf, ret);
if (ret == ERR_CHANNEL_CLOSED)
break; /* need to terminate */
if (ret != NO_ERROR) {
/* any other error is only possible if
* vqueue is corrupted.
*/
panic("Unable (%d) to return buffer to vqueue\n", ret);
}
}
LTRACEF("exit\n");
return 0;
}
typedef struct data_cb_ctx {
handle_t *chan;
ipc_msg_info_t msg_inf;
} data_cb_ctx_t;
static int tx_data_cb(uint8_t *buf, size_t buf_len, void *ctx)
{
int rc;
data_cb_ctx_t *cb_ctx = (data_cb_ctx_t *) ctx;
DEBUG_ASSERT(buf);
DEBUG_ASSERT(cb_ctx);
iovec_kern_t dst_iov = { buf, buf_len };
ipc_msg_kern_t dst_kern_msg = {
.iov = &dst_iov,
.num_iov = 1,
.num_handles = 0,
.handles = NULL,
};
/* read data */
rc = ipc_read_msg(cb_ctx->chan, cb_ctx->msg_inf.id, 0,
&dst_kern_msg);
/* retire msg */
ipc_put_msg(cb_ctx->chan, cb_ctx->msg_inf.id);
return rc;
}
static void handle_tx_msg(struct tipc_dev *dev, handle_t *chan)
{
int ret;
uint32_t local = 0;
uint32_t remote = 0;
struct tipc_ept *ept;
data_cb_ctx_t cb_ctx = { .chan = chan };
mutex_acquire(&dev->ept_lock);
ept = handle_get_cookie(chan);
if (!ept) {
mutex_release(&dev->ept_lock);
return;
}
remote = ept->remote;
mutex_release(&dev->ept_lock);
/* for all available messages */
for (;;) {
/* get next message info */
ret = ipc_get_msg(chan, &cb_ctx.msg_inf);
if (ret == ERR_NO_MSG)
break; /* no new messages */
if (ret != NO_ERROR) {
/* should never happen */
panic ("%s: failed (%d) to get message\n",
__func__, ret);
}
uint16_t ttl_size = cb_ctx.msg_inf.len;
LTRACEF("forward message (%d bytes)\n", ttl_size);
/* send message using data callback */
ret = tipc_send_data(dev, local, remote,
tx_data_cb, &cb_ctx, ttl_size, true);
if (ret != NO_ERROR) {
/* nothing we can do about it: log it */
TRACEF("tipc_send_data failed (%d)\n", ret);
}
}
}
static void handle_hup(struct tipc_dev *dev, handle_t *chan)
{
uint32_t local = 0;
uint32_t remote = 0;
struct tipc_ept *ept;
bool send_disc = false;
mutex_acquire(&dev->ept_lock);
ept = handle_get_cookie(chan);
if (ept) {
/* get remote address */
remote = ept->remote;
local = ept_to_addr(dev, ept);
send_disc = true;
/* remove handle from handle list */
handle_list_del(&dev->handle_list, chan);
/* kill cookie */
handle_set_cookie(chan, NULL);
/* close it */
handle_close(chan);
/* free_local_address */
free_local_addr(dev, local);
}
mutex_release(&dev->ept_lock);
if (send_disc) {
/* send disconnect request */
(void) send_disc_req(dev, local, remote);
}
/* unblock rx thread potentially waiting to retry */
signal_rx_retry(dev);
}
static void handle_ready(struct tipc_dev *dev, handle_t *chan)
{
uint32_t local = 0;
uint32_t remote = 0;
struct tipc_ept *ept;
bool send_rsp = false;
mutex_acquire(&dev->ept_lock);
ept = handle_get_cookie(chan);
if (ept) {
/* get remote address */
remote = ept->remote;
local = ept_to_addr(dev, ept);
send_rsp = true;
}
mutex_release(&dev->ept_lock);
if (send_rsp) {
/* send connect response */
(void) send_conn_rsp(dev, local, remote, 0,
IPC_CHAN_MAX_BUF_SIZE, 1);
}
}
static void handle_tx(struct tipc_dev *dev)
{
int ret;
handle_t *chan;
uint32_t chan_event;
DEBUG_ASSERT(dev);
for (;;) {
/* wait for incoming messgages */
ret = handle_list_wait(&dev->handle_list, &chan,
&chan_event, INFINITE_TIME);
if (ret == ERR_NOT_FOUND) {
/* no handles left */
return;
}
if (ret < 0) {
/* only possible if somebody else is waiting
on the same handle which should never happen */
panic("%s: couldn't wait for handle events (%d)\n",
__func__, ret);
}
DEBUG_ASSERT(chan);
DEBUG_ASSERT(ipc_is_channel(chan));
if (chan_event & IPC_HANDLE_POLL_READY) {
handle_ready(dev, chan);
} else if (chan_event & IPC_HANDLE_POLL_MSG) {
handle_tx_msg(dev, chan);
} else if (chan_event & IPC_HANDLE_POLL_HUP) {
handle_hup(dev, chan);
} else if (chan_event & IPC_HANDLE_POLL_SEND_UNBLOCKED) {
signal_rx_retry(dev);
} else {
LTRACEF("Unhandled event %x\n", chan_event);
}
handle_decref(chan);
}
}
static int tipc_tx_thread_func(void *arg)
{
struct tipc_dev *dev = arg;
LTRACEF("enter\n");
while (!dev->tx_stop) {
LTRACEF("waiting for handles\n");
/* wait forever until we have handles */
event_wait(&dev->have_handles);
LTRACEF("have handles\n");
/* handle messsages */
handle_tx(dev);
LTRACEF("no handles\n");
}
LTRACEF("exit\n");
return 0;
}
static status_t tipc_dev_reset(struct tipc_dev *dev)
{
status_t rc;
struct tipc_ept *ept;
if (dev->state == VDEV_STATE_RESET)
return NO_ERROR;
/* Shutdown rx thread to block all incomming requests */
dev->rx_stop = true;
vqueue_signal_avail(&dev->vqs[TIPC_VQ_RX]);
rc = thread_join(dev->rx_thread, NULL, 1000);
LTRACEF("rx thread join: returned %d\n", rc);
if (rc != NO_ERROR) {
panic("unable to shutdown rx thread: %d\n", rc);
}
dev->rx_thread = NULL;
dev->rx_stop = false;
/* Set stop tx thread */
dev->tx_stop = true;
/* close all channels */
mutex_acquire(&dev->ept_lock);
ept = dev->epts;
for (uint slot = 0; slot < countof(dev->epts); slot++, ept++) {
if (!bitmap_test(dev->inuse, slot))
continue;
if (!ept->chan)
continue;
handle_list_del(&dev->handle_list, ept->chan);
handle_set_cookie(ept->chan, NULL);
handle_close(ept->chan);
free_local_addr(dev, ept_to_addr(dev, ept));
}
mutex_release(&dev->ept_lock);
/* kick tx thread and tx vq */
event_signal(&dev->have_handles, false);
vqueue_signal_avail(&dev->vqs[TIPC_VQ_TX]);
/* wait it to terminate */
rc = thread_join(dev->tx_thread, NULL, 1000);
LTRACEF("tx thread join: returned %d\n", rc);
if (rc != NO_ERROR) {
panic("unable to shutdown tx thread: %d\n", rc);
}
dev->tx_thread = NULL;
dev->tx_stop = false;
/* destroy vqs */
vqueue_destroy(&dev->vqs[TIPC_VQ_RX]);
vqueue_destroy(&dev->vqs[TIPC_VQ_TX]);
/* enter reset state */
dev->state = VDEV_STATE_RESET;
return NO_ERROR;
}
static status_t validate_descr(struct tipc_dev *dev,
struct tipc_vdev_descr *vdev_descr)
{
if (vdev_descr->hdr.type != RSC_VDEV) {
LTRACEF("unexpected type %d\n", vdev_descr->hdr.type);
return ERR_INVALID_ARGS;
}
if (vdev_descr->vdev.id != VIRTIO_ID_L4TRUSTY_IPC) {
LTRACEF("unexpected vdev id%d\n", vdev_descr->vdev.id);
return ERR_INVALID_ARGS;
}
if (vdev_descr->vdev.num_of_vrings != TIPC_VQ_NUM) {
LTRACEF("unexpected number of vrings (%d vs. %d)\n",
vdev_descr->vdev.num_of_vrings, TIPC_VQ_NUM);
return ERR_INVALID_ARGS;
}
/* check if NS driver successfully initilized */
if (vdev_descr->vdev.status != (VIRTIO_CONFIG_S_ACKNOWLEDGE |
VIRTIO_CONFIG_S_DRIVER |
VIRTIO_CONFIG_S_DRIVER_OK | VIRTIO_STATUS_FEATURES_OK)) {
LTRACEF("unexpected status %d\n",
(int)vdev_descr->vdev.status);
return ERR_INVALID_ARGS;
}
return NO_ERROR;
}
static int virtio_kick_cb(struct vqueue *vq, void *priv)
{
struct tipc_dev *dev = (struct tipc_dev *)priv;
// kick other side
dev->cfg->interrupt_status |= 1;
wmb();
dev->cfg->queue_notify =
dev->queue_cfg[vqueue_id(vq)].device_notify_index;
return 0;
}
/*
* Should be only called once.
*/
static status_t tipc_dev_probe(struct tipc_dev *dev,
struct tipc_vdev_descr *dscr)
{
status_t ret;
uint vring_cnt;
char tname[32];
LTRACEF("%p: descr = %p\n", dev, dscr);
if (dev->state != VDEV_STATE_RESET)
return ERR_BAD_STATE;
ret = validate_descr(dev, dscr);
if (ret != NO_ERROR)
return ret;
/* vring[0] == TX queue (host's RX) */
/* vring[1] == RX queue (host's TX) */
for (vring_cnt = 0; vring_cnt < dscr->vdev.num_of_vrings; vring_cnt++) {
struct fw_rsc_vdev_vring *vring = &dscr->vrings[vring_cnt];
struct l4virtio_queue_config *qcfg = &dev->queue_cfg[vring_cnt];
void *daddr;
void *aaddr;
void *uaddr;
if (virtio_dev_to_kvaddr(dev, qcfg->desc_addr, 0, &daddr))
goto err_vq_init;
if (virtio_dev_to_kvaddr(dev, qcfg->avail_addr, 0, &aaddr))
goto err_vq_init;
if (virtio_dev_to_kvaddr(dev, qcfg->used_addr, 0, &uaddr))
goto err_vq_init;
ret = vqueue_init(&dev->vqs[vring_cnt], vring_cnt,
daddr, aaddr, uaddr, vring->num, dev,
notify_cbs[vring_cnt], &virtio_kick_cb);
if (ret)
goto err_vq_init;
}
/* create rx thread */
snprintf(tname, sizeof(tname), "tipc-dev%u-rx", dscr->vdev.notifyid);
dev->rx_thread =
thread_create(tname, tipc_rx_thread_func, dev,
DEFAULT_PRIORITY, DEFAULT_STACK_SIZE);
if (dev->rx_thread) {
thread_resume(dev->rx_thread);
}
/* create tx thread */
snprintf(tname, sizeof(tname), "tipc-dev%u-tx", dscr->vdev.notifyid);
dev->tx_thread =
thread_create(tname, tipc_tx_thread_func, dev,
DEFAULT_PRIORITY, DEFAULT_STACK_SIZE);
if (dev->tx_thread) {
thread_resume(dev->tx_thread);
}
return ret;
err_vq_init:
while (vring_cnt--) {
vqueue_destroy(&dev->vqs[vring_cnt]);
}
return ret;
}
static int
tipc_send_data(struct tipc_dev *dev, uint32_t local, uint32_t remote,
tipc_data_cb_t cb, void *cb_ctx, uint16_t data_len,
bool wait)
{
paddr_t out_phys[MAX_TX_IOVS];
iovec_kern_t out_iovs[MAX_TX_IOVS];
struct vqueue *vq = &dev->vqs[TIPC_VQ_TX];
struct vqueue_buf buf;
int ret = 0;
DEBUG_ASSERT(dev);
/* check if data callback specified */
if (!cb)
return ERR_INVALID_ARGS;
size_t ttl_len =
sizeof(struct tipc_hdr) + data_len;
memset(&buf, 0, sizeof(buf));
buf.out_iovs.cnt = MAX_TX_IOVS;
buf.out_iovs.phys = out_phys;
buf.out_iovs.iovs = out_iovs;
/* get buffer or wait if needed */
do {
/* get buffer */
ret = vqueue_get_avail_buf(vq, &buf);
if (ret == NO_ERROR) {
/* got it */
break;
}
if (ret != ERR_NOT_ENOUGH_BUFFER || !wait) {
/* no buffers and no wait */
goto err;
}
/* wait for buffers */
event_wait(&vq->avail_event);
if (dev->tx_stop) {
return ERR_CHANNEL_CLOSED;
}
} while (true);
/* we only support and expect single out_iovec for now */
if (buf.out_iovs.used == 0) {
LTRACEF("unexpected iovec cnt in = %d out = %d\n",
buf.in_iovs.used, buf.out_iovs.used);
ret = ERR_NOT_ENOUGH_BUFFER;
goto done;
}
if (buf.out_iovs.used != 1 || buf.in_iovs.used != 0) {
LTRACEF("unexpected iovec cnt in = %d out = %d\n",
buf.in_iovs.used, buf.out_iovs.used);
}
/* the first iovec should be large enough to hold header */
if (sizeof(struct tipc_hdr) > buf.out_iovs.iovs[0].len) {
/* not enough space to even place header */
LTRACEF("buf is too small (%zu < %zu)\n",
buf.out_iovs.iovs[0].len, ttl_len);
ret = ERR_NOT_ENOUGH_BUFFER;
goto done;
}
/* map in provided buffers (Non-secure, no-execute, cached, read-write) */
uint map_flags = ARCH_MMU_FLAG_NS | ARCH_MMU_FLAG_PERM_NO_EXECUTE |
ARCH_MMU_FLAG_CACHED;
ret = virtio_map_iovs(dev, &buf.out_iovs, map_flags);
if (ret == NO_ERROR) {
struct tipc_hdr *hdr = buf.out_iovs.iovs[0].base;
hdr->src = local;
hdr->dst = remote;
hdr->reserved = 0;
hdr->len = data_len;
hdr->flags = 0;
if (ttl_len > buf.out_iovs.iovs[0].len) {
/* not enough space to put the whole message
so it will be truncated */
LTRACEF("buf is too small (%zu < %zu)\n",
buf.out_iovs.iovs[0].len, ttl_len);
data_len = buf.out_iovs.iovs[0].len -
sizeof(struct tipc_hdr);
}
/* invoke data_cb to add actual data */
ret = cb(hdr->data, data_len, cb_ctx);
if (ret >= 0) {
/* add header */
ret += sizeof(struct tipc_hdr);
}
virtio_unmap_iovs(&buf.out_iovs);
}
done:
ret = vqueue_add_buf(vq, &buf, ret);
err:
return ret;
}
struct buf_ctx {
uint8_t *data;
size_t len;
};
static int _send_buf(uint8_t *dst, size_t sz, void *ctx)
{
struct buf_ctx *buf = (struct buf_ctx *) ctx;
DEBUG_ASSERT(dst);
DEBUG_ASSERT(buf);
DEBUG_ASSERT(buf->data);
DEBUG_ASSERT(sz <= buf->len);
memcpy (dst, buf->data, sz);
return (int) sz;
}
static int
tipc_send_buf(struct tipc_dev *dev, uint32_t local, uint32_t remote,
void *data, uint16_t data_len, bool wait)
{
struct buf_ctx ctx = {data, data_len};
return tipc_send_data(dev, local, remote,
_send_buf, &ctx, data_len, wait);
}
static void virtio_disable_queues(struct tipc_dev *dev)
{
uint i;
for (i = 0; i < TIPC_VQ_NUM; ++i)
dev->vqs[i].vring_addr = 0;
}
static enum handler_return virtio_handle_irq(void *arg)
{
struct tipc_dev *dev = (struct tipc_dev *)arg;
struct tipc_vdev_descr *desc = (struct tipc_vdev_descr *) dev->descr_ptr;
uint i;
uint32_t cmd = dev->cfg->cmd;
uint32_t payload = cmd & ~VIRTIO_L4CMD_MASK;
u8 *shadow_status = &desc->vdev.status;
if (cmd) {
switch (cmd & VIRTIO_L4CMD_MASK) {
case VIRTIO_L4CMD_SET_STATUS:
if (payload == 0) {
/* reset */
tipc_dev_reset(dev);
*shadow_status = 0;
} else if (!(*shadow_status & VIRTIO_STATUS_FAILED)) {
*shadow_status = payload;
if (payload & VIRTIO_STATUS_FAILED) {
/* stop device */
virtio_disable_queues(dev);
dev->state = VDEV_STATE_RESET;
} else if (payload == VIRTIO_STATUS_READY) {
/* all is well, start up the device */
if (tipc_dev_probe(dev, desc) != NO_ERROR) {
virtio_disable_queues(dev);
*shadow_status |= VIRTIO_STATUS_FAILED;
}
}
}
dev->cfg->status = *shadow_status;
break;
case VIRTIO_L4CMD_CFG_QUEUE:
/* check that all queues are still ready */
if (payload < TIPC_VQ_NUM
&& dev->vqs[payload].vring_addr
&& !dev->queue_cfg[payload].ready)
dev->state = VDEV_STATE_RESET;
break;
}
}
/* always kick the queues when the device is ready */
if (*shadow_status == VIRTIO_STATUS_READY) {
if (dev->state == VDEV_STATE_ACTIVE) {
// don't know which queue, so kick them all
for (i = 0; i < TIPC_VQ_NUM; ++i)
vqueue_notify(dev->vqs + i);
} else if (dev->state == VDEV_STATE_GOING_ONLINE) {
vqueue_notify(&dev->vqs[TIPC_VQ_TX]);
}
}
/* acknowledge interrupt and mark command as done */
dev->cfg->cmd = 0;
return INT_RESCHEDULE;
}
status_t create_tipc_device(const struct tipc_vdev_descr *descr, size_t size,
const uuid_t *uuid, struct tipc_dev **dev_ptr)
{
status_t ret;
struct tipc_dev *dev;
uint i;
DEBUG_ASSERT(uuid);
DEBUG_ASSERT(descr);
DEBUG_ASSERT(size);
dev = calloc(1, sizeof(*dev));
if (!dev)
return ERR_NO_MEMORY;
mutex_init(&dev->ept_lock);
dev->state = VDEV_STATE_RESET;
dev->uuid = uuid;
dev->descr_ptr = descr;
dev->descr_size = size;
handle_list_init(&dev->handle_list);
event_init(&dev->have_handles, false, EVENT_FLAG_AUTOUNSIGNAL);
event_init(&dev->rx_retry, false, EVENT_FLAG_AUTOUNSIGNAL);
/* init virtio device */
dev->cfg = (struct l4virtio_config *) (descr->config_base + 0x80000000);
dev->queue_cfg = (struct l4virtio_queue_config *)
&dev->cfg->config[descr->vdev.config_len / 4 + 1];
dev->driver_window = (vaddr_t)descr->driver_mem_base + 0x80000000;
dev->cfg->version = 2;
dev->cfg->device_id = descr->vdev.id;
dev->cfg->vendor_id = 0x44; // virtio
dev->cfg->dev_features_map[0] = descr->vdev.dfeatures;
dev->cfg->queue_num_max = 0x200;
dev->cfg->num_queues = descr->vdev.num_of_vrings;
dev->cfg->queues_offset = (char *)dev->queue_cfg - (char *)dev->cfg;
// setup queues
for (i = 0; i < descr->vdev.num_of_vrings; ++i) {
dev->queue_cfg[i].num_max = descr->vrings[i].num;
dev->queue_cfg[i].device_notify_index = i;
}
// setup config space
// NOT IMPLEMENTED: private tipc dev config space at 0x100;
// register and enable interrupts
mask_interrupt(descr->notify_irq);
register_int_handler(descr->notify_irq, &virtio_handle_irq, dev);
unmask_interrupt(descr->notify_irq);
// write magic to signal that we are ready.
dev->cfg->magic = VIRTIO_MMIO_MAGIC;
if (dev_ptr)
*dev_ptr = dev;
return NO_ERROR;
err_register:
free(dev);
return ret;
}
|
44950.c | // Copyright 2018 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <stdint.h>
#include "debug.h"
#define MX8_UTXD (0x40)
#define MX8_UTS (0xB4)
#define UTS_TXFULL (1 << 4)
#define UARTREG(reg) (*(volatile uint32_t*)(0x30890000 + (reg)))
void uart_pputc(char c) {
while (UARTREG(MX8_UTS) & UTS_TXFULL)
;
UARTREG(MX8_UTXD) = c;
}
|
293669.c | /*
* Copyright (C) 2017 Marvell International Ltd.
*
* SPDX-License-Identifier: GPL-2.0
* https://spdx.org/licenses
*/
#include <debug.h>
#include <thermal.h>
int marvell_thermal_init(struct tsen_config *tsen_cfg)
{
if (tsen_cfg->tsen_ready == 1) {
INFO("thermal sensor is already initialized\n");
return 0;
}
if (tsen_cfg->ptr_tsen_probe == NULL) {
ERROR("initial thermal sensor configuration is missing\n");
return -1;
}
if (tsen_cfg->ptr_tsen_probe(tsen_cfg)) {
ERROR("thermal sensor initialization failed\n");
return -1;
}
INFO("thermal sensor was initialized\n");
return 0;
}
int marvell_thermal_read(struct tsen_config *tsen_cfg, int *temp)
{
if (temp == NULL) {
ERROR("NULL pointer for temperature read\n");
return -1;
}
if (tsen_cfg->ptr_tsen_read == NULL ||
tsen_cfg->tsen_ready == 0) {
ERROR("thermal sensor was not initialized\n");
return -1;
}
if (tsen_cfg->ptr_tsen_read(tsen_cfg, temp)) {
ERROR("temperature read failed\n");
return -1;
}
return 0;
}
|
533920.c | /* Konami Ultra Sports hardware
Driver by Ville Linde
*/
#include "driver.h"
#include "cpu/powerpc/ppc.h"
#include "sound/k054539.h"
#include "machine/eeprom.h"
#include "machine/konppc.h"
#include "machine/konamiic.h"
static UINT32 *vram;
static VIDEO_START( ultrsprt )
{
}
static VIDEO_UPDATE( ultrsprt )
{
int i, j;
UINT8 *ram = (UINT8*)vram;
if (ram != NULL)
{
for (j=0; j < 400; j++)
{
UINT16 *bmp = BITMAP_ADDR16(bitmap, j, 0);
int fb_index = j * 1024;
for (i=0; i < 512; i++)
{
UINT8 p1 = ram[BYTE4_XOR_BE(fb_index + i + 512)];
if (p1 == 0)
{
UINT8 p2 = ram[BYTE4_XOR_BE(fb_index + i)];
bmp[i] = machine->remapped_colortable[0x000 + p2];
}
else
{
bmp[i] = machine->remapped_colortable[0x100 + p1];
}
}
}
}
return 0;
}
static WRITE32_HANDLER(palette_w)
{
int r1, g1, b1, r2, g2, b2;
COMBINE_DATA(&paletteram32[offset]);
data = paletteram32[offset];
b1 = ((data >> 16) & 0x1f);
g1 = ((data >> 21) & 0x1f);
r1 = ((data >> 26) & 0x1f);
r1 = (r1 << 3) | (r1 >> 2);
g1 = (g1 << 3) | (g1 >> 2);
b1 = (b1 << 3) | (b1 >> 2);
b2 = ((data >> 0) & 0x1f);
g2 = ((data >> 5) & 0x1f);
r2 = ((data >> 10) & 0x1f);
r2 = (r2 << 3) | (r2 >> 2);
g2 = (g2 << 3) | (g2 >> 2);
b2 = (b2 << 3) | (b2 >> 2);
palette_set_color(Machine, (offset*2)+0, MAKE_RGB(r1, g1, b1));
palette_set_color(Machine, (offset*2)+1, MAKE_RGB(r2, g2, b2));
}
static READ32_HANDLER(eeprom_r)
{
UINT32 r = 0;
if (!(mem_mask & 0xff000000))
{
r |= (((EEPROM_read_bit()) << 1) | (readinputport(6) << 3)) << 24;
}
return r;
}
static WRITE32_HANDLER(eeprom_w)
{
if (!(mem_mask & 0xff000000))
{
EEPROM_write_bit((data & 0x01000000) ? 1 : 0);
EEPROM_set_clock_line((data & 0x02000000) ? CLEAR_LINE : ASSERT_LINE);
EEPROM_set_cs_line((data & 0x04000000) ? CLEAR_LINE : ASSERT_LINE);
}
}
static READ32_HANDLER(control1_r)
{
return (readinputport(0) << 28) | ((readinputport(1) & 0xfff) << 16) | (readinputport(2) & 0xfff);
}
static READ32_HANDLER(control2_r)
{
return (readinputport(3) << 28) | ((readinputport(4) & 0xfff) << 16) | (readinputport(5) & 0xfff);
}
static WRITE32_HANDLER(int_ack_w)
{
cpunum_set_input_line(0, INPUT_LINE_IRQ1, CLEAR_LINE);
}
static ADDRESS_MAP_START( ultrsprt_map, ADDRESS_SPACE_PROGRAM, 32 )
AM_RANGE(0x00000000, 0x0007ffff) AM_MIRROR(0x80000000) AM_RAM AM_BASE(&vram)
AM_RANGE(0x70000000, 0x70000003) AM_MIRROR(0x80000000) AM_READWRITE(eeprom_r, eeprom_w)
AM_RANGE(0x70000020, 0x70000023) AM_MIRROR(0x80000000) AM_READ(control1_r)
AM_RANGE(0x70000040, 0x70000043) AM_MIRROR(0x80000000) AM_READ(control2_r)
AM_RANGE(0x70000080, 0x70000087) AM_MIRROR(0x80000000) AM_WRITE(K056800_host_w)
AM_RANGE(0x70000088, 0x7000008f) AM_MIRROR(0x80000000) AM_READ(K056800_host_r)
AM_RANGE(0x700000e0, 0x700000e3) AM_MIRROR(0x80000000) AM_WRITE(int_ack_w)
AM_RANGE(0x7f000000, 0x7f01ffff) AM_MIRROR(0x80000000) AM_RAM
AM_RANGE(0x7f700000, 0x7f703fff) AM_MIRROR(0x80000000) AM_READWRITE(MRA32_RAM, palette_w) AM_BASE(&paletteram32)
AM_RANGE(0x7fa00000, 0x7fbfffff) AM_MIRROR(0x80000000) AM_ROM AM_SHARE(1)
AM_RANGE(0x7fc00000, 0x7fdfffff) AM_MIRROR(0x80000000) AM_ROM AM_SHARE(1)
AM_RANGE(0x7fe00000, 0x7fffffff) AM_MIRROR(0x80000000) AM_ROM AM_REGION(REGION_USER1, 0) AM_SHARE(1)
ADDRESS_MAP_END
/*****************************************************************************/
static READ16_HANDLER(sound_r)
{
UINT16 r = 0;
int reg = offset * 2;
if (ACCESSING_MSB16)
{
r |= K054539_0_r(reg+0) << 8;
}
if (ACCESSING_LSB16)
{
r |= K054539_0_r(reg+1) << 0;
}
return r;
}
static WRITE16_HANDLER(sound_w)
{
int reg = offset * 2;
if (ACCESSING_MSB16)
{
K054539_0_w(reg+0, (data >> 8) & 0xff);
}
if (ACCESSING_LSB16)
{
K054539_0_w(reg+1, (data >> 0) & 0xff);
}
}
static READ16_HANDLER(K056800_68k_r)
{
UINT16 r = 0;
if (!(mem_mask & 0xff00))
{
r |= K056800_sound_r((offset*2)+0, 0xffff) << 8;
}
if (!(mem_mask & 0x00ff))
{
r |= K056800_sound_r((offset*2)+1, 0xffff) << 0;
}
return r;
}
static WRITE16_HANDLER(K056800_68k_w)
{
if (!(mem_mask & 0xff00))
{
K056800_sound_w((offset*2)+0, (data >> 8) & 0xff, 0xffff);
}
if (!(mem_mask & 0x00ff))
{
K056800_sound_w((offset*2)+1, (data >> 0) & 0xff, 0xffff);
}
}
static ADDRESS_MAP_START( sound_map, ADDRESS_SPACE_PROGRAM, 16 )
AM_RANGE(0x00000000, 0x0001ffff) AM_READ(MRA16_ROM)
AM_RANGE(0x00100000, 0x00101fff) AM_RAM
AM_RANGE(0x00200000, 0x00200007) AM_WRITE(K056800_68k_w)
AM_RANGE(0x00200008, 0x0020000f) AM_READ(K056800_68k_r)
AM_RANGE(0x00400000, 0x004002ff) AM_READWRITE(sound_r, sound_w)
ADDRESS_MAP_END
/*****************************************************************************/
INPUT_PORTS_START( ultrsprt )
PORT_START
PORT_BIT( 0x4, IP_ACTIVE_HIGH, IPT_COIN1 )
PORT_BIT( 0x2, IP_ACTIVE_HIGH, IPT_BUTTON1 ) PORT_PLAYER(1)
PORT_BIT( 0x1, IP_ACTIVE_HIGH, IPT_START1 )
PORT_START
PORT_BIT( 0xfff, 0x800, IPT_AD_STICK_X ) PORT_MINMAX(0x000,0xfff) PORT_SENSITIVITY(70) PORT_KEYDELTA(10) PORT_PLAYER(1)
PORT_START
PORT_BIT( 0xfff, 0x800, IPT_AD_STICK_Y ) PORT_MINMAX(0x000,0xfff) PORT_SENSITIVITY(70) PORT_KEYDELTA(10) PORT_REVERSE PORT_PLAYER(1)
PORT_START
PORT_BIT( 0x4, IP_ACTIVE_HIGH, IPT_SERVICE1 )
PORT_BIT( 0x2, IP_ACTIVE_HIGH, IPT_BUTTON1 ) PORT_PLAYER(2)
PORT_BIT( 0x1, IP_ACTIVE_HIGH, IPT_START2 )
PORT_START
PORT_BIT( 0xfff, 0x800, IPT_AD_STICK_X ) PORT_MINMAX(0x000,0xfff) PORT_SENSITIVITY(70) PORT_KEYDELTA(10) PORT_PLAYER(2)
PORT_START
PORT_BIT( 0xfff, 0x800, IPT_AD_STICK_Y ) PORT_MINMAX(0x000,0xfff) PORT_SENSITIVITY(70) PORT_KEYDELTA(10) PORT_REVERSE PORT_PLAYER(2)
PORT_START
PORT_BIT( 0x1, IP_ACTIVE_LOW, IPT_SERVICE ) PORT_NAME( DEF_STR( Service_Mode )) PORT_CODE(KEYCODE_F2) /* Test Button */
INPUT_PORTS_END
static void eeprom_handler(mame_file *file, int read_or_write)
{
if (read_or_write)
{
EEPROM_save(file);
}
else
{
EEPROM_init(&eeprom_interface_93C46);
if (file)
{
EEPROM_load(file);
}
}
}
static NVRAM_HANDLER(ultrsprt)
{
eeprom_handler(file, read_or_write);
}
static ppc_config ultrsprt_ppc_cfg =
{
PPC_MODEL_403GA
};
static struct K054539interface k054539_interface =
{
REGION_SOUND1
};
static INTERRUPT_GEN( ultrsprt_vblank )
{
cpunum_set_input_line(0, INPUT_LINE_IRQ1, ASSERT_LINE);
}
static MACHINE_RESET( ultrsprt )
{
}
static MACHINE_DRIVER_START( ultrsprt )
/* basic machine hardware */
MDRV_CPU_ADD(PPC403, 25000000) /* PowerPC 403GA 25MHz */
MDRV_CPU_CONFIG(ultrsprt_ppc_cfg)
MDRV_CPU_PROGRAM_MAP(ultrsprt_map, 0)
MDRV_CPU_VBLANK_INT(ultrsprt_vblank, 1)
MDRV_CPU_ADD(M68000, 8000000) /* Not sure about the frequency */
MDRV_CPU_PROGRAM_MAP(sound_map, 0)
MDRV_CPU_PERIODIC_INT(irq5_line_hold, 1) // ???
MDRV_SCREEN_REFRESH_RATE(60)
MDRV_SCREEN_VBLANK_TIME(USEC_TO_SUBSECONDS(0))
MDRV_INTERLEAVE(200)
MDRV_NVRAM_HANDLER(ultrsprt)
MDRV_MACHINE_RESET(ultrsprt)
/* video hardware */
MDRV_VIDEO_ATTRIBUTES(VIDEO_TYPE_RASTER )
MDRV_SCREEN_FORMAT(BITMAP_FORMAT_RGB15)
MDRV_SCREEN_SIZE(512, 400)
MDRV_SCREEN_VISIBLE_AREA(0, 511, 0, 399)
MDRV_PALETTE_LENGTH(8192)
MDRV_VIDEO_START(ultrsprt)
MDRV_VIDEO_UPDATE(ultrsprt)
/* sound hardware */
MDRV_SPEAKER_STANDARD_STEREO("left", "right")
MDRV_SOUND_ADD(K054539, 48000)
MDRV_SOUND_CONFIG(k054539_interface)
MDRV_SOUND_ROUTE(0, "left", 1.0)
MDRV_SOUND_ROUTE(1, "right", 1.0)
MACHINE_DRIVER_END
static void sound_irq_callback(int irq)
{
if (irq == 0)
{
//cpunum_set_input_line(1, INPUT_LINE_IRQ5, PULSE_LINE);
}
else
{
cpunum_set_input_line(1, INPUT_LINE_IRQ6, PULSE_LINE);
}
}
static DRIVER_INIT( ultrsprt )
{
cpunum_set_input_line(1, INPUT_LINE_HALT, ASSERT_LINE);
K056800_init(sound_irq_callback);
}
/*****************************************************************************/
ROM_START(fiveside)
ROM_REGION(0x200000, REGION_USER1, 0) /* PowerPC program roms */
ROM_LOAD32_BYTE("479uaa01.bin", 0x000003, 0x80000, CRC(1bc4893d) SHA1(2c9df38ecb7efa7b686221ee98fa3aad9a63e152))
ROM_LOAD32_BYTE("479uaa02.bin", 0x000002, 0x80000, CRC(ae74a6d0) SHA1(6113c2eea1628b22737c7b87af0e673d94984e88))
ROM_LOAD32_BYTE("479uaa03.bin", 0x000001, 0x80000, CRC(5c0b176f) SHA1(9560259bc081d4cfd72eb485c3fdcecf484ba7a8))
ROM_LOAD32_BYTE("479uaa04.bin", 0x000000, 0x80000, CRC(01a3e4cb) SHA1(819df79909d57fa12481698ffdb32b00586131d8))
ROM_REGION(0x20000, REGION_CPU2, 0) /* M68K program */
ROM_LOAD("479_a05.bin", 0x000000, 0x20000, CRC(251ae299) SHA1(5ffd74357e3c6ddb3a208c39a3b32b53fea90282))
ROM_REGION(0x100000, REGION_SOUND1, 0) /* Sound roms */
ROM_LOAD("479_a06.bin", 0x000000, 0x80000, CRC(8d6ac8a2) SHA1(7c4b8bd47cddc766cbdb6a486acc9221be55b579))
ROM_LOAD("479_a07.bin", 0x080000, 0x80000, CRC(75835df8) SHA1(105b95c16f2ce6902c2e4c9c2fd9f2f7a848c546))
ROM_END
GAME(1995, fiveside, 0, ultrsprt, ultrsprt, ultrsprt, ROT90, "Konami", "Five a Side Soccer (ver UAA)", GAME_IMPERFECT_SOUND)
|
635603.c | //*****************************************************************************
//
// board.c - Board functions for EK-TM4C123GXL Tiva C Series LaunchPad.
//
// Copyright (c) 2014 Texas Instruments Incorporated. All rights reserved.
// Software License Agreement
//
// Texas Instruments (TI) is supplying this software for use solely and
// exclusively on TI's microcontroller products. The software is owned by
// TI and/or its suppliers, and is protected under applicable copyright
// laws. You may not combine this software with "viral" open-source
// software in order to form a larger program.
//
// THIS SOFTWARE IS PROVIDED "AS IS" AND WITH ALL FAULTS.
// NO WARRANTIES, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING, BUT
// NOT LIMITED TO, IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE APPLY TO THIS SOFTWARE. TI SHALL NOT, UNDER ANY
// CIRCUMSTANCES, BE LIABLE FOR SPECIAL, INCIDENTAL, OR CONSEQUENTIAL
// DAMAGES, FOR ANY REASON WHATSOEVER.
//
// This is part of revision 2.1.0.12573 of the Tiva Firmware Development Package.
//
//*****************************************************************************
#include <stdint.h>
#include <stdbool.h>
#include "inc/hw_types.h"
#include "driverlib/timer.h"
#include "driverlib/rom_map.h"
#include "driverlib/systick.h"
#include "driverlib/fpu.h"
#include "driverlib/debug.h"
#include "utils/uartstdio.h"
#include "driverlib/uart.h"
#include "driverlib/ssi.h"
#include "wlan.h"
#include "evnt_handler.h"
#include "nvmem.h"
#include "socket.h"
#include "cc3000_common.h"
#include "netapp.h"
#include "spi.h"
#include "hci.h"
#include "dispatcher.h"
#include "spi_version.h"
#include "board.h"
//*****************************************************************************
//
// A structure used to hold information defining the location of a single LED
// on the board.
//
//*****************************************************************************
typedef struct
{
tBoardLED eLED;
uint32_t ui32Periph;
uint32_t ui32Base;
uint8_t ui8Pin;
bool bHighIsOn;
}
tLEDInfo;
//*****************************************************************************
//
// A structure defining all the LEDs on this board.
//
//*****************************************************************************
const tLEDInfo g_psLEDs[] =
{
{RED_LED, CC3000_LED_RED_SYSCTL_PERIPH, CC3000_LED_RED_PORT,
CC3000_LED_RED_PIN, true},
{GREEN_LED, CC3000_LED_GREEN_SYSCTL_PERIPH, CC3000_LED_GREEN_PORT,
CC3000_LED_GREEN_PIN, true},
{BLUE_LED, CC3000_LED_BLUE_SYSCTL_PERIPH, CC3000_LED_BLUE_PORT,
CC3000_LED_BLUE_PIN, true},
};
#define NUM_LEDS (sizeof(g_psLEDs) / sizeof(tLEDInfo))
//*****************************************************************************
//
//! pio_init
//!
//! \param none
//!
//! \return none
//!
//! \brief Initialize the board's I/O
//
//*****************************************************************************
void pio_init()
{
// Board Initialization start
//
//
// The FPU should be enabled because some compilers will use floating-
// point registers, even for non-floating-point code. If the FPU is not
// enabled this will cause a fault. This also ensures that floating-
// point operations could be added to this application and would work
// correctly and use the hardware floating-point unit. Finally, lazy
// stacking is enabled for interrupt handlers. This allows floating-
// point instructions to be used within interrupt handlers, but at the
// expense of extra stack usage.
//
FPUEnable();
FPULazyStackingEnable();
//
// Initialize the system clock.
//
initClk();
//
// Configure the system peripheral bus that IRQ & EN pin are mapped to.
//
MAP_SysCtlPeripheralEnable( SYSCTL_PERIPH_IRQ_PORT);
MAP_SysCtlPeripheralEnable( SYSCTL_PERIPH_SW_EN_PORT);
//
// Disable all the interrupts before configuring the lines.
//
MAP_GPIOIntDisable(SPI_GPIO_IRQ_BASE, 0xFF);
//
// Configure the WLAN_IRQ pin as an input.
//
MAP_GPIOPinTypeGPIOInput(SPI_GPIO_IRQ_BASE, SPI_IRQ_PIN);
GPIOPadConfigSet(SPI_GPIO_IRQ_BASE, SPI_IRQ_PIN, GPIO_STRENGTH_2MA,
GPIO_PIN_TYPE_STD_WPU);
//
// Setup the GPIO interrupt for this pin
//
MAP_GPIOIntTypeSet(SPI_GPIO_IRQ_BASE, SPI_IRQ_PIN, GPIO_FALLING_EDGE);
//
// Configure the pins for the enable signal to the CC3000.
//
MAP_GPIOPinTypeGPIOOutput(SPI_GPIO_SW_EN_BASE, SPI_EN_PIN);
MAP_GPIODirModeSet( SPI_GPIO_SW_EN_BASE, SPI_EN_PIN, GPIO_DIR_MODE_OUT );
MAP_GPIOPadConfigSet( SPI_GPIO_SW_EN_BASE, SPI_EN_PIN, GPIO_STRENGTH_2MA, GPIO_PIN_TYPE_STD_WPD );
MAP_GPIOPinWrite(SPI_GPIO_SW_EN_BASE, SPI_EN_PIN, PIN_LOW);
SysCtlDelay(600000);
SysCtlDelay(600000);
SysCtlDelay(600000);
//
// Disable WLAN CS with pull up Resistor
//
MAP_SysCtlPeripheralEnable(SYSCTL_PERIPH_SPI_PORT);
MAP_GPIOPinTypeGPIOOutput(SPI_CS_PORT, SPI_CS_PIN);
GPIOPadConfigSet(SPI_CS_PORT, SPI_CS_PIN, GPIO_STRENGTH_2MA,
GPIO_PIN_TYPE_STD_WPU);
MAP_GPIOPinWrite(SPI_CS_PORT, SPI_CS_PIN, PIN_HIGH);
//
// Enable interrupt for WLAN_IRQ pin
//
MAP_GPIOIntEnable(SPI_GPIO_IRQ_BASE, SPI_IRQ_PIN);
//
// Clear interrupt status
//
SpiCleanGPIOISR();
MAP_IntEnable(INT_GPIO_SPI);
//
// Initialize LED Pins and state.
//
initLEDs();
}
//*****************************************************************************
//
//! ReadWlanInterruptPin
//!
//! \param none
//!
//! \return none
//!
//! \brief return wlan interrup pin
//
//*****************************************************************************
long ReadWlanInterruptPin(void)
{
return MAP_GPIOPinRead(SPI_GPIO_IRQ_BASE, SPI_IRQ_PIN);
}
//*****************************************************************************
//
//! Enable waln IrQ pin
//!
//! \param none
//!
//! \return none
//!
//! \brief Nonr
//
//*****************************************************************************
void WlanInterruptEnable()
{
MAP_GPIOIntEnable(SPI_GPIO_IRQ_BASE, SPI_IRQ_PIN);
}
//*****************************************************************************
//
//! Disable waln IrQ pin
//!
//! \param none
//!
//! \return none
//!
//! \brief Nonr
//
//*****************************************************************************
void WlanInterruptDisable()
{
MAP_GPIOIntDisable(SPI_GPIO_IRQ_BASE, SPI_IRQ_PIN);
}
//*****************************************************************************
//
//! WriteWlanPin
//!
//! \param new val
//!
//! \return none
//!
//! \brief This functions enables and disables the CC3000 Radio
//
//*****************************************************************************
void WriteWlanPin( unsigned char val )
{
if(val)
{
MAP_GPIOPinWrite(SPI_GPIO_SW_EN_BASE, SPI_EN_PIN,PIN_HIGH);
}
else
{
MAP_GPIOPinWrite(SPI_GPIO_SW_EN_BASE, SPI_EN_PIN, PIN_LOW);
}
}
//*****************************************************************************
//
// Init SysTick timer.
//
//
//*****************************************************************************
void
InitSysTick(void)
{
//
// Configure SysTick to occur 10 times per second and enable its interrupt.
//
SysTickPeriodSet(SysCtlClockGet() / SYSTICK_PER_SECOND);
SysTickIntEnable();
SysTickEnable();
}
//*****************************************************************************
//
// The interrupt handler for the SysTick timer. This handler is called every 1ms
//
//
//*****************************************************************************
void
SysTickHandler(void)
{
static unsigned long ulTickCount = 0;
//
// Increment the tick counter.
//
ulTickCount++;
//
// Has half a second passed since we last called the event handler?
//
if(ulTickCount >= (SYSTICK_PER_SECOND / 2))
{
//
// Yes = call the unsolicited event handler. We need to do this a
// few times each second.
//
hci_unsolicited_event_handler();
ulTickCount = 0;
}
}
//*****************************************************************************
//
//! init clk
//!
//! \param None
//!
//! \return none
//!
//! \Init the device with 16 MHz clock.
//
//*****************************************************************************
void initClk(void)
{
//
// 16 MHz Crystal on Board. SSI Freq - configure M4 Clock to be ~50 MHz
//
MAP_SysCtlClockSet(SYSCTL_SYSDIV_3 | SYSCTL_USE_PLL | SYSCTL_OSC_MAIN |
SYSCTL_XTAL_16MHZ);
}
//*****************************************************************************
//
// Initialize all LEDs on the board.
//
//*****************************************************************************
void initLEDs()
{
uint32_t ui32Loop;
//
// Loop through each of the configured LEDs
//
for(ui32Loop = 0; ui32Loop < NUM_LEDS; ui32Loop++)
{
//
// Enable the GPIO peripheral containing the LED control line.
//
MAP_SysCtlPeripheralEnable(g_psLEDs[ui32Loop].ui32Periph);
//
// Configure the LED pin as an output.
//
MAP_GPIOPinTypeGPIOOutput(g_psLEDs[ui32Loop].ui32Base,
g_psLEDs[ui32Loop].ui8Pin);
//
// Turn the LED off.
//
MAP_GPIOPinWrite(g_psLEDs[ui32Loop].ui32Base,
g_psLEDs[ui32Loop].ui8Pin,
(g_psLEDs[ui32Loop].bHighIsOn ?
0 : g_psLEDs[ui32Loop].ui8Pin));
}
}
//*****************************************************************************
//
// Turns a single board LED on.
//
//*****************************************************************************
void turnLedOn(tBoardLED eLED)
{
uint32_t ui32Loop;
//
// Loop through each of the LEDs on this board looking for the one we've
// been asked for.
//
for(ui32Loop = 0; ui32Loop < NUM_LEDS; ui32Loop++)
{
//
// Have we found the requested LED's information?
//
if(g_psLEDs[ui32Loop].eLED == eLED)
{
//
// Yes - turn it on.
//
MAP_GPIOPinWrite(g_psLEDs[ui32Loop].ui32Base,
g_psLEDs[ui32Loop].ui8Pin,
(g_psLEDs[ui32Loop].bHighIsOn ?
g_psLEDs[ui32Loop].ui8Pin : 0));
//
// We found the LED so there's no point in continuing the loop.
//
return;
}
}
}
//*****************************************************************************
//
// Turns off a single LED on the board.
//
//*****************************************************************************
void turnLedOff(tBoardLED eLED)
{
uint32_t ui32Loop;
//
// Loop through each of the LEDs on this board looking for the one we've
// been asked for.
//
for(ui32Loop = 0; ui32Loop < NUM_LEDS; ui32Loop++)
{
//
// Have we found the requested LED's information?
//
if(g_psLEDs[ui32Loop].eLED == eLED)
{
//
// Yes - turn it off.
//
MAP_GPIOPinWrite(g_psLEDs[ui32Loop].ui32Base,
g_psLEDs[ui32Loop].ui8Pin,
(g_psLEDs[ui32Loop].bHighIsOn ?
0 : g_psLEDs[ui32Loop].ui8Pin));
//
// We found the LED so there's no point in continuing the loop.
//
return;
}
}
}
|
612145.c | /* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE134_Uncontrolled_Format_String__char_fromFile_vfprintf_45.c
Label Definition File: CWE134_Uncontrolled_Format_String.vasinks.label.xml
Template File: sources-vasinks-45.tmpl.c
*/
/*
* @description
* CWE: 134 Uncontrolled Format String
* BadSource: fromFile Read input from a file
* GoodSource: Copy a fixed string into data
* Sinks: vfprintf
* GoodSink: vfprintf with a format string
* BadSink : vfprintf without a format string
* Flow Variant: 45 Data flow: data passed as a static global variable from one function to another in the same source file
*
* */
#include <stdarg.h>
#include "std_testcase.h"
#ifdef _WIN32
# define FOPEN fopen
#else
/* fopen is used on unix-based OSs */
# define FOPEN fopen
#endif
#ifndef OMITBAD
static char * CWE134_Uncontrolled_Format_String__char_fromFile_vfprintf_45_bad_data;
static char * CWE134_Uncontrolled_Format_String__char_fromFile_vfprintf_45_goodG2B_data;
static char * CWE134_Uncontrolled_Format_String__char_fromFile_vfprintf_45_goodB2G_data;
static void bad_vasink(char * data, ...)
{
{
va_list args;
va_start(args, data);
/* POTENTIAL FLAW: Do not specify the format allowing a possible format string vulnerability */
vfprintf(stdout, data, args);
va_end(args);
}
}
static void bad_sink()
{
char * data = CWE134_Uncontrolled_Format_String__char_fromFile_vfprintf_45_bad_data;
bad_vasink(data, data);
}
void CWE134_Uncontrolled_Format_String__char_fromFile_vfprintf_45_bad()
{
char * data;
char data_buf[100] = "";
data = data_buf;
{
/* Read input from a file */
size_t data_len = strlen(data);
FILE * pFile;
/* if there is room in data, attempt to read the input from a file */
if(100-data_len > 1)
{
pFile = FOPEN("C:\\temp\\file.txt", "r");
if (pFile != NULL)
{
fgets(data+data_len, (int)(100-data_len), pFile);
fclose(pFile);
}
}
}
CWE134_Uncontrolled_Format_String__char_fromFile_vfprintf_45_bad_data = data;
bad_sink();
}
#endif /* OMITBAD */
#ifndef OMITGOOD
/* goodG2B uses the GoodSource with the BadSink */
static void goodG2B_vasink(char * data, ...)
{
{
va_list args;
va_start(args, data);
/* POTENTIAL FLAW: Do not specify the format allowing a possible format string vulnerability */
vfprintf(stdout, data, args);
va_end(args);
}
}
static void goodG2B_sink()
{
char * data = CWE134_Uncontrolled_Format_String__char_fromFile_vfprintf_45_goodG2B_data;
goodG2B_vasink(data, data);
}
static void goodG2B()
{
char * data;
char data_buf[100] = "";
data = data_buf;
/* FIX: Use a fixed string that does not contain a format specifier */
strcpy(data, "fixedstringtest");
CWE134_Uncontrolled_Format_String__char_fromFile_vfprintf_45_goodG2B_data = data;
goodG2B_sink();
}
/* goodB2G uses the BadSource with the GoodSink */
static void goodB2G_vasink(char * data, ...)
{
{
va_list args;
va_start(args, data);
/* FIX: Specify the format disallowing a format string vulnerability */
vfprintf(stdout, "%s", args);
va_end(args);
}
}
static void goodB2G_sink()
{
char * data = CWE134_Uncontrolled_Format_String__char_fromFile_vfprintf_45_goodB2G_data;
goodB2G_vasink(data, data);
}
static void goodB2G()
{
char * data;
char data_buf[100] = "";
data = data_buf;
{
/* Read input from a file */
size_t data_len = strlen(data);
FILE * pFile;
/* if there is room in data, attempt to read the input from a file */
if(100-data_len > 1)
{
pFile = FOPEN("C:\\temp\\file.txt", "r");
if (pFile != NULL)
{
fgets(data+data_len, (int)(100-data_len), pFile);
fclose(pFile);
}
}
}
CWE134_Uncontrolled_Format_String__char_fromFile_vfprintf_45_goodB2G_data = data;
goodB2G_sink();
}
void CWE134_Uncontrolled_Format_String__char_fromFile_vfprintf_45_good()
{
goodG2B();
goodB2G();
}
#endif /* OMITGOOD */
/* Below is the main(). It is only used when building this testcase on
its own for testing or for building a binary to use in testing binary
analysis tools. It is not used when compiling all the testcases as one
application, which is how source code analysis tools are tested. */
#ifdef INCLUDEMAIN
int main(int argc, char * argv[])
{
/* seed randomness */
srand( (unsigned)time(NULL) );
#ifndef OMITGOOD
printLine("Calling good()...");
CWE134_Uncontrolled_Format_String__char_fromFile_vfprintf_45_good();
printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
printLine("Calling bad()...");
CWE134_Uncontrolled_Format_String__char_fromFile_vfprintf_45_bad();
printLine("Finished bad()");
#endif /* OMITBAD */
return 0;
}
#endif
|
452317.c | /* s_fabsf.c -- float version of s_fabs.c.
* Conversion to float by Ian Lance Taylor, Cygnus Support, [email protected].
*/
/*
* ====================================================
* Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved.
*
* Developed at SunPro, a Sun Microsystems, Inc. business.
* Permission to use, copy, modify, and distribute this
* software is freely granted, provided that this notice
* is preserved.
* ====================================================
*/
#include <sys/cdefs.h>
__FBSDID("$FreeBSD: releng/11.0/lib/msun/src/s_fabsf.c 176451 2008-02-22 02:30:36Z das $");
/*
* fabsf(x) returns the absolute value of x.
*/
#include "math.h"
#include "math_private.h"
float
fabsf(float x)
{
u_int32_t ix;
GET_FLOAT_WORD(ix,x);
SET_FLOAT_WORD(x,ix&0x7fffffff);
return x;
}
|
475451.c | /*
* copyright (C) 1999/2000 by Henning Zabel <[email protected]>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
/*
* USB-Kernel Driver for the Mustek MDC800 Digital Camera
* (c) 1999/2000 Henning Zabel <[email protected]>
*
*
* The driver brings the USB functions of the MDC800 to Linux.
* To use the Camera you must support the USB Protocol of the camera
* to the Kernel Node.
* The Driver uses a misc device Node. Create it with :
* mknod /dev/mustek c 180 32
*
* The driver supports only one camera.
*
* Fix: mdc800 used sleep_on and slept with io_lock held.
* Converted sleep_on to waitqueues with schedule_timeout and made io_lock
* a semaphore from a spinlock.
* by Oliver Neukum <[email protected]>
* (02/12/2001)
*
* Identify version on module load.
* (08/04/2001) gb
*
* version 0.7.5
* Fixed potential SMP races with Spinlocks.
* Thanks to Oliver Neukum <[email protected]> who
* noticed the race conditions.
* (30/10/2000)
*
* Fixed: Setting urb->dev before submitting urb.
* by Greg KH <[email protected]>
* (13/10/2000)
*
* version 0.7.3
* bugfix : The mdc800->state field gets set to READY after the
* the diconnect function sets it to NOT_CONNECTED. This makes the
* driver running like the camera is connected and causes some
* hang ups.
*
* version 0.7.1
* MOD_INC and MOD_DEC are changed in usb_probe to prevent load/unload
* problems when compiled as Module.
* (04/04/2000)
*
* The mdc800 driver gets assigned the USB Minor 32-47. The Registration
* was updated to use these values.
* (26/03/2000)
*
* The Init und Exit Module Function are updated.
* (01/03/2000)
*
* version 0.7.0
* Rewrite of the driver : The driver now uses URB's. The old stuff
* has been removed.
*
* version 0.6.0
* Rewrite of this driver: The Emulation of the rs232 protocoll
* has been removed from the driver. A special executeCommand function
* for this driver is included to gphoto.
* The driver supports two kind of communication to bulk endpoints.
* Either with the dev->bus->ops->bulk... or with callback function.
* (09/11/1999)
*
* version 0.5.0:
* first Version that gets a version number. Most of the needed
* functions work.
* (20/10/1999)
*/
#include <linux/sched.h>
#include <linux/signal.h>
#include <linux/spinlock.h>
#include <linux/errno.h>
#include <linux/random.h>
#include <linux/poll.h>
#include <linux/init.h>
#include <linux/slab.h>
#include <linux/module.h>
#include <linux/wait.h>
#include <linux/mutex.h>
#include <linux/usb.h>
#include <linux/fs.h>
/*
* Version Information
*/
#define DRIVER_VERSION "v0.7.5 (30/10/2000)"
#define DRIVER_AUTHOR "Henning Zabel <[email protected]>"
#define DRIVER_DESC "USB Driver for Mustek MDC800 Digital Camera"
/* Vendor and Product Information */
#define MDC800_VENDOR_ID 0x055f
#define MDC800_PRODUCT_ID 0xa800
/* Timeouts (msec) */
#define TO_DOWNLOAD_GET_READY 1500
#define TO_DOWNLOAD_GET_BUSY 1500
#define TO_WRITE_GET_READY 1000
#define TO_DEFAULT_COMMAND 5000
#define TO_READ_FROM_IRQ TO_DEFAULT_COMMAND
#define TO_GET_READY TO_DEFAULT_COMMAND
/* Minor Number of the device (create with mknod /dev/mustek c 180 32) */
#define MDC800_DEVICE_MINOR_BASE 32
/**************************************************************************
Data and structs
***************************************************************************/
typedef enum {
NOT_CONNECTED, READY, WORKING, DOWNLOAD
} mdc800_state;
/* Data for the driver */
struct mdc800_data
{
struct usb_device * dev; // Device Data
mdc800_state state;
unsigned int endpoint [4];
struct urb * irq_urb;
wait_queue_head_t irq_wait;
int irq_woken;
char* irq_urb_buffer;
int camera_busy; // is camera busy ?
int camera_request_ready; // Status to synchronize with irq
char camera_response [8]; // last Bytes send after busy
struct urb * write_urb;
char* write_urb_buffer;
wait_queue_head_t write_wait;
int written;
struct urb * download_urb;
char* download_urb_buffer;
wait_queue_head_t download_wait;
int downloaded;
int download_left; // Bytes left to download ?
/* Device Data */
char out [64]; // Answer Buffer
int out_ptr; // Index to the first not readen byte
int out_count; // Bytes in the buffer
int open; // Camera device open ?
struct mutex io_lock; // IO -lock
char in [8]; // Command Input Buffer
int in_count;
int pic_index; // Cache for the Imagesize (-1 for nothing cached )
int pic_len;
int minor;
};
/* Specification of the Endpoints */
static struct usb_endpoint_descriptor mdc800_ed [4] =
{
{
.bLength = 0,
.bDescriptorType = 0,
.bEndpointAddress = 0x01,
.bmAttributes = 0x02,
.wMaxPacketSize = cpu_to_le16(8),
.bInterval = 0,
.bRefresh = 0,
.bSynchAddress = 0,
},
{
.bLength = 0,
.bDescriptorType = 0,
.bEndpointAddress = 0x82,
.bmAttributes = 0x03,
.wMaxPacketSize = cpu_to_le16(8),
.bInterval = 0,
.bRefresh = 0,
.bSynchAddress = 0,
},
{
.bLength = 0,
.bDescriptorType = 0,
.bEndpointAddress = 0x03,
.bmAttributes = 0x02,
.wMaxPacketSize = cpu_to_le16(64),
.bInterval = 0,
.bRefresh = 0,
.bSynchAddress = 0,
},
{
.bLength = 0,
.bDescriptorType = 0,
.bEndpointAddress = 0x84,
.bmAttributes = 0x02,
.wMaxPacketSize = cpu_to_le16(64),
.bInterval = 0,
.bRefresh = 0,
.bSynchAddress = 0,
},
};
/* The Variable used by the driver */
static struct mdc800_data* mdc800;
/***************************************************************************
The USB Part of the driver
****************************************************************************/
static int mdc800_endpoint_equals (struct usb_endpoint_descriptor *a,struct usb_endpoint_descriptor *b)
{
return (
( a->bEndpointAddress == b->bEndpointAddress )
&& ( a->bmAttributes == b->bmAttributes )
&& ( a->wMaxPacketSize == b->wMaxPacketSize )
);
}
/*
* Checks whether the camera responds busy
*/
static int mdc800_isBusy (char* ch)
{
int i=0;
while (i<8)
{
if (ch [i] != (char)0x99)
return 0;
i++;
}
return 1;
}
/*
* Checks whether the Camera is ready
*/
static int mdc800_isReady (char *ch)
{
int i=0;
while (i<8)
{
if (ch [i] != (char)0xbb)
return 0;
i++;
}
return 1;
}
/*
* USB IRQ Handler for InputLine
*/
static void mdc800_usb_irq (struct urb *urb)
{
int data_received=0, wake_up;
unsigned char* b=urb->transfer_buffer;
struct mdc800_data* mdc800=urb->context;
int status = urb->status;
if (status >= 0) {
//dbg ("%i %i %i %i %i %i %i %i \n",b[0],b[1],b[2],b[3],b[4],b[5],b[6],b[7]);
if (mdc800_isBusy (b))
{
if (!mdc800->camera_busy)
{
mdc800->camera_busy=1;
dbg ("gets busy");
}
}
else
{
if (mdc800->camera_busy && mdc800_isReady (b))
{
mdc800->camera_busy=0;
dbg ("gets ready");
}
}
if (!(mdc800_isBusy (b) || mdc800_isReady (b)))
{
/* Store Data in camera_answer field */
dbg ("%i %i %i %i %i %i %i %i ",b[0],b[1],b[2],b[3],b[4],b[5],b[6],b[7]);
memcpy (mdc800->camera_response,b,8);
data_received=1;
}
}
wake_up= ( mdc800->camera_request_ready > 0 )
&&
(
((mdc800->camera_request_ready == 1) && (!mdc800->camera_busy))
||
((mdc800->camera_request_ready == 2) && data_received)
||
((mdc800->camera_request_ready == 3) && (mdc800->camera_busy))
||
(status < 0)
);
if (wake_up)
{
mdc800->camera_request_ready=0;
mdc800->irq_woken=1;
wake_up (&mdc800->irq_wait);
}
}
/*
* Waits a while until the irq responds that camera is ready
*
* mode : 0: Wait for camera gets ready
* 1: Wait for receiving data
* 2: Wait for camera gets busy
*
* msec: Time to wait
*/
static int mdc800_usb_waitForIRQ (int mode, int msec)
{
mdc800->camera_request_ready=1+mode;
wait_event_timeout(mdc800->irq_wait, mdc800->irq_woken, msec*HZ/1000);
mdc800->irq_woken = 0;
if (mdc800->camera_request_ready>0)
{
mdc800->camera_request_ready=0;
dev_err(&mdc800->dev->dev, "timeout waiting for camera.\n");
return -1;
}
if (mdc800->state == NOT_CONNECTED)
{
printk(KERN_WARNING "mdc800: Camera gets disconnected "
"during waiting for irq.\n");
mdc800->camera_request_ready=0;
return -2;
}
return 0;
}
/*
* The write_urb callback function
*/
static void mdc800_usb_write_notify (struct urb *urb)
{
struct mdc800_data* mdc800=urb->context;
int status = urb->status;
if (status != 0)
dev_err(&mdc800->dev->dev,
"writing command fails (status=%i)\n", status);
else
mdc800->state=READY;
mdc800->written = 1;
wake_up (&mdc800->write_wait);
}
/*
* The download_urb callback function
*/
static void mdc800_usb_download_notify (struct urb *urb)
{
struct mdc800_data* mdc800=urb->context;
int status = urb->status;
if (status == 0) {
/* Fill output buffer with these data */
memcpy (mdc800->out, urb->transfer_buffer, 64);
mdc800->out_count=64;
mdc800->out_ptr=0;
mdc800->download_left-=64;
if (mdc800->download_left == 0)
{
mdc800->state=READY;
}
} else {
dev_err(&mdc800->dev->dev,
"request bytes fails (status:%i)\n", status);
}
mdc800->downloaded = 1;
wake_up (&mdc800->download_wait);
}
/***************************************************************************
Probing for the Camera
***************************************************************************/
static struct usb_driver mdc800_usb_driver;
static const struct file_operations mdc800_device_ops;
static struct usb_class_driver mdc800_class = {
.name = "mdc800%d",
.fops = &mdc800_device_ops,
.minor_base = MDC800_DEVICE_MINOR_BASE,
};
/*
* Callback to search the Mustek MDC800 on the USB Bus
*/
static int mdc800_usb_probe (struct usb_interface *intf,
const struct usb_device_id *id)
{
int i,j;
struct usb_host_interface *intf_desc;
struct usb_device *dev = interface_to_usbdev (intf);
int irq_interval=0;
int retval;
dbg ("(mdc800_usb_probe) called.");
if (mdc800->dev != NULL)
{
dev_warn(&intf->dev, "only one Mustek MDC800 is supported.\n");
return -ENODEV;
}
if (dev->descriptor.bNumConfigurations != 1)
{
dev_err(&intf->dev,
"probe fails -> wrong Number of Configuration\n");
return -ENODEV;
}
intf_desc = intf->cur_altsetting;
if (
( intf_desc->desc.bInterfaceClass != 0xff )
|| ( intf_desc->desc.bInterfaceSubClass != 0 )
|| ( intf_desc->desc.bInterfaceProtocol != 0 )
|| ( intf_desc->desc.bNumEndpoints != 4)
)
{
dev_err(&intf->dev, "probe fails -> wrong Interface\n");
return -ENODEV;
}
/* Check the Endpoints */
for (i=0; i<4; i++)
{
mdc800->endpoint[i]=-1;
for (j=0; j<4; j++)
{
if (mdc800_endpoint_equals (&intf_desc->endpoint [j].desc,&mdc800_ed [i]))
{
mdc800->endpoint[i]=intf_desc->endpoint [j].desc.bEndpointAddress ;
if (i==1)
{
irq_interval=intf_desc->endpoint [j].desc.bInterval;
}
}
}
if (mdc800->endpoint[i] == -1)
{
dev_err(&intf->dev, "probe fails -> Wrong Endpoints.\n");
return -ENODEV;
}
}
dev_info(&intf->dev, "Found Mustek MDC800 on USB.\n");
mutex_lock(&mdc800->io_lock);
retval = usb_register_dev(intf, &mdc800_class);
if (retval) {
dev_err(&intf->dev, "Not able to get a minor for this device.\n");
mutex_unlock(&mdc800->io_lock);
return -ENODEV;
}
mdc800->dev=dev;
mdc800->open=0;
/* Setup URB Structs */
usb_fill_int_urb (
mdc800->irq_urb,
mdc800->dev,
usb_rcvintpipe (mdc800->dev,mdc800->endpoint [1]),
mdc800->irq_urb_buffer,
8,
mdc800_usb_irq,
mdc800,
irq_interval
);
usb_fill_bulk_urb (
mdc800->write_urb,
mdc800->dev,
usb_sndbulkpipe (mdc800->dev, mdc800->endpoint[0]),
mdc800->write_urb_buffer,
8,
mdc800_usb_write_notify,
mdc800
);
usb_fill_bulk_urb (
mdc800->download_urb,
mdc800->dev,
usb_rcvbulkpipe (mdc800->dev, mdc800->endpoint [3]),
mdc800->download_urb_buffer,
64,
mdc800_usb_download_notify,
mdc800
);
mdc800->state=READY;
mutex_unlock(&mdc800->io_lock);
usb_set_intfdata(intf, mdc800);
return 0;
}
/*
* Disconnect USB device (maybe the MDC800)
*/
static void mdc800_usb_disconnect (struct usb_interface *intf)
{
struct mdc800_data* mdc800 = usb_get_intfdata(intf);
dbg ("(mdc800_usb_disconnect) called");
if (mdc800) {
if (mdc800->state == NOT_CONNECTED)
return;
usb_deregister_dev(intf, &mdc800_class);
/* must be under lock to make sure no URB
is submitted after usb_kill_urb() */
mutex_lock(&mdc800->io_lock);
mdc800->state=NOT_CONNECTED;
usb_kill_urb(mdc800->irq_urb);
usb_kill_urb(mdc800->write_urb);
usb_kill_urb(mdc800->download_urb);
mutex_unlock(&mdc800->io_lock);
mdc800->dev = NULL;
usb_set_intfdata(intf, NULL);
}
dev_info(&intf->dev, "Mustek MDC800 disconnected from USB.\n");
}
/***************************************************************************
The Misc device Part (file_operations)
****************************************************************************/
/*
* This Function calc the Answersize for a command.
*/
static int mdc800_getAnswerSize (char command)
{
switch ((unsigned char) command)
{
case 0x2a:
case 0x49:
case 0x51:
case 0x0d:
case 0x20:
case 0x07:
case 0x01:
case 0x25:
case 0x00:
return 8;
case 0x05:
case 0x3e:
return mdc800->pic_len;
case 0x09:
return 4096;
default:
return 0;
}
}
/*
* Init the device: (1) alloc mem (2) Increase MOD Count ..
*/
static int mdc800_device_open (struct inode* inode, struct file *file)
{
int retval=0;
int errn=0;
mutex_lock(&mdc800->io_lock);
if (mdc800->state == NOT_CONNECTED)
{
errn=-EBUSY;
goto error_out;
}
if (mdc800->open)
{
errn=-EBUSY;
goto error_out;
}
mdc800->in_count=0;
mdc800->out_count=0;
mdc800->out_ptr=0;
mdc800->pic_index=0;
mdc800->pic_len=-1;
mdc800->download_left=0;
mdc800->camera_busy=0;
mdc800->camera_request_ready=0;
retval=0;
mdc800->irq_urb->dev = mdc800->dev;
retval = usb_submit_urb (mdc800->irq_urb, GFP_KERNEL);
if (retval) {
dev_err(&mdc800->dev->dev,
"request USB irq fails (submit_retval=%i).\n", retval);
errn = -EIO;
goto error_out;
}
mdc800->open=1;
dbg ("Mustek MDC800 device opened.");
error_out:
mutex_unlock(&mdc800->io_lock);
return errn;
}
/*
* Close the Camera and release Memory
*/
static int mdc800_device_release (struct inode* inode, struct file *file)
{
int retval=0;
dbg ("Mustek MDC800 device closed.");
mutex_lock(&mdc800->io_lock);
if (mdc800->open && (mdc800->state != NOT_CONNECTED))
{
usb_kill_urb(mdc800->irq_urb);
usb_kill_urb(mdc800->write_urb);
usb_kill_urb(mdc800->download_urb);
mdc800->open=0;
}
else
{
retval=-EIO;
}
mutex_unlock(&mdc800->io_lock);
return retval;
}
/*
* The Device read callback Function
*/
static ssize_t mdc800_device_read (struct file *file, char __user *buf, size_t len, loff_t *pos)
{
size_t left=len, sts=len; /* single transfer size */
char __user *ptr = buf;
int retval;
mutex_lock(&mdc800->io_lock);
if (mdc800->state == NOT_CONNECTED)
{
mutex_unlock(&mdc800->io_lock);
return -EBUSY;
}
if (mdc800->state == WORKING)
{
printk(KERN_WARNING "mdc800: Illegal State \"working\""
"reached during read ?!\n");
mutex_unlock(&mdc800->io_lock);
return -EBUSY;
}
if (!mdc800->open)
{
mutex_unlock(&mdc800->io_lock);
return -EBUSY;
}
while (left)
{
if (signal_pending (current))
{
mutex_unlock(&mdc800->io_lock);
return -EINTR;
}
sts=left > (mdc800->out_count-mdc800->out_ptr)?mdc800->out_count-mdc800->out_ptr:left;
if (sts <= 0)
{
/* Too less Data in buffer */
if (mdc800->state == DOWNLOAD)
{
mdc800->out_count=0;
mdc800->out_ptr=0;
/* Download -> Request new bytes */
mdc800->download_urb->dev = mdc800->dev;
retval = usb_submit_urb (mdc800->download_urb, GFP_KERNEL);
if (retval) {
dev_err(&mdc800->dev->dev,
"Can't submit download urb "
"(retval=%i)\n", retval);
mutex_unlock(&mdc800->io_lock);
return len-left;
}
wait_event_timeout(mdc800->download_wait, mdc800->downloaded,
TO_DOWNLOAD_GET_READY*HZ/1000);
mdc800->downloaded = 0;
if (mdc800->download_urb->status != 0)
{
dev_err(&mdc800->dev->dev,
"request download-bytes fails "
"(status=%i)\n",
mdc800->download_urb->status);
mutex_unlock(&mdc800->io_lock);
return len-left;
}
}
else
{
/* No more bytes -> that's an error*/
mutex_unlock(&mdc800->io_lock);
return -EIO;
}
}
else
{
/* Copy Bytes */
if (copy_to_user(ptr, &mdc800->out [mdc800->out_ptr],
sts)) {
mutex_unlock(&mdc800->io_lock);
return -EFAULT;
}
ptr+=sts;
left-=sts;
mdc800->out_ptr+=sts;
}
}
mutex_unlock(&mdc800->io_lock);
return len-left;
}
/*
* The Device write callback Function
* If a 8Byte Command is received, it will be send to the camera.
* After this the driver initiates the request for the answer or
* just waits until the camera becomes ready.
*/
static ssize_t mdc800_device_write (struct file *file, const char __user *buf, size_t len, loff_t *pos)
{
size_t i=0;
int retval;
mutex_lock(&mdc800->io_lock);
if (mdc800->state != READY)
{
mutex_unlock(&mdc800->io_lock);
return -EBUSY;
}
if (!mdc800->open )
{
mutex_unlock(&mdc800->io_lock);
return -EBUSY;
}
while (i<len)
{
unsigned char c;
if (signal_pending (current))
{
mutex_unlock(&mdc800->io_lock);
return -EINTR;
}
if(get_user(c, buf+i))
{
mutex_unlock(&mdc800->io_lock);
return -EFAULT;
}
/* check for command start */
if (c == 0x55)
{
mdc800->in_count=0;
mdc800->out_count=0;
mdc800->out_ptr=0;
mdc800->download_left=0;
}
/* save command byte */
if (mdc800->in_count < 8)
{
mdc800->in[mdc800->in_count] = c;
mdc800->in_count++;
}
else
{
mutex_unlock(&mdc800->io_lock);
return -EIO;
}
/* Command Buffer full ? -> send it to camera */
if (mdc800->in_count == 8)
{
int answersize;
if (mdc800_usb_waitForIRQ (0,TO_GET_READY))
{
dev_err(&mdc800->dev->dev,
"Camera didn't get ready.\n");
mutex_unlock(&mdc800->io_lock);
return -EIO;
}
answersize=mdc800_getAnswerSize (mdc800->in[1]);
mdc800->state=WORKING;
memcpy (mdc800->write_urb->transfer_buffer, mdc800->in,8);
mdc800->write_urb->dev = mdc800->dev;
retval = usb_submit_urb (mdc800->write_urb, GFP_KERNEL);
if (retval) {
dev_err(&mdc800->dev->dev,
"submitting write urb fails "
"(retval=%i)\n", retval);
mutex_unlock(&mdc800->io_lock);
return -EIO;
}
wait_event_timeout(mdc800->write_wait, mdc800->written, TO_WRITE_GET_READY*HZ/1000);
mdc800->written = 0;
if (mdc800->state == WORKING)
{
usb_kill_urb(mdc800->write_urb);
mutex_unlock(&mdc800->io_lock);
return -EIO;
}
switch ((unsigned char) mdc800->in[1])
{
case 0x05: /* Download Image */
case 0x3e: /* Take shot in Fine Mode (WCam Mode) */
if (mdc800->pic_len < 0)
{
dev_err(&mdc800->dev->dev,
"call 0x07 before "
"0x05,0x3e\n");
mdc800->state=READY;
mutex_unlock(&mdc800->io_lock);
return -EIO;
}
mdc800->pic_len=-1;
case 0x09: /* Download Thumbnail */
mdc800->download_left=answersize+64;
mdc800->state=DOWNLOAD;
mdc800_usb_waitForIRQ (0,TO_DOWNLOAD_GET_BUSY);
break;
default:
if (answersize)
{
if (mdc800_usb_waitForIRQ (1,TO_READ_FROM_IRQ))
{
dev_err(&mdc800->dev->dev, "requesting answer from irq fails\n");
mutex_unlock(&mdc800->io_lock);
return -EIO;
}
/* Write dummy data, (this is ugly but part of the USB Protocol */
/* if you use endpoint 1 as bulk and not as irq) */
memcpy (mdc800->out, mdc800->camera_response,8);
/* This is the interpreted answer */
memcpy (&mdc800->out[8], mdc800->camera_response,8);
mdc800->out_ptr=0;
mdc800->out_count=16;
/* Cache the Imagesize, if command was getImageSize */
if (mdc800->in [1] == (char) 0x07)
{
mdc800->pic_len=(int) 65536*(unsigned char) mdc800->camera_response[0]+256*(unsigned char) mdc800->camera_response[1]+(unsigned char) mdc800->camera_response[2];
dbg ("cached imagesize = %i",mdc800->pic_len);
}
}
else
{
if (mdc800_usb_waitForIRQ (0,TO_DEFAULT_COMMAND))
{
dev_err(&mdc800->dev->dev, "Command Timeout.\n");
mutex_unlock(&mdc800->io_lock);
return -EIO;
}
}
mdc800->state=READY;
break;
}
}
i++;
}
mutex_unlock(&mdc800->io_lock);
return i;
}
/***************************************************************************
Init and Cleanup this driver (Structs and types)
****************************************************************************/
/* File Operations of this drivers */
static const struct file_operations mdc800_device_ops =
{
.owner = THIS_MODULE,
.read = mdc800_device_read,
.write = mdc800_device_write,
.open = mdc800_device_open,
.release = mdc800_device_release,
};
static const struct usb_device_id mdc800_table[] = {
{ USB_DEVICE(MDC800_VENDOR_ID, MDC800_PRODUCT_ID) },
{ } /* Terminating entry */
};
MODULE_DEVICE_TABLE (usb, mdc800_table);
/*
* USB Driver Struct for this device
*/
static struct usb_driver mdc800_usb_driver =
{
.name = "mdc800",
.probe = mdc800_usb_probe,
.disconnect = mdc800_usb_disconnect,
.id_table = mdc800_table
};
/************************************************************************
Init and Cleanup this driver (Main Functions)
*************************************************************************/
static int __init usb_mdc800_init (void)
{
int retval = -ENODEV;
/* Allocate Memory */
mdc800=kzalloc (sizeof (struct mdc800_data), GFP_KERNEL);
if (!mdc800)
goto cleanup_on_fail;
mdc800->dev = NULL;
mdc800->state=NOT_CONNECTED;
mutex_init (&mdc800->io_lock);
init_waitqueue_head (&mdc800->irq_wait);
init_waitqueue_head (&mdc800->write_wait);
init_waitqueue_head (&mdc800->download_wait);
mdc800->irq_woken = 0;
mdc800->downloaded = 0;
mdc800->written = 0;
mdc800->irq_urb_buffer=kmalloc (8, GFP_KERNEL);
if (!mdc800->irq_urb_buffer)
goto cleanup_on_fail;
mdc800->write_urb_buffer=kmalloc (8, GFP_KERNEL);
if (!mdc800->write_urb_buffer)
goto cleanup_on_fail;
mdc800->download_urb_buffer=kmalloc (64, GFP_KERNEL);
if (!mdc800->download_urb_buffer)
goto cleanup_on_fail;
mdc800->irq_urb=usb_alloc_urb (0, GFP_KERNEL);
if (!mdc800->irq_urb)
goto cleanup_on_fail;
mdc800->download_urb=usb_alloc_urb (0, GFP_KERNEL);
if (!mdc800->download_urb)
goto cleanup_on_fail;
mdc800->write_urb=usb_alloc_urb (0, GFP_KERNEL);
if (!mdc800->write_urb)
goto cleanup_on_fail;
/* Register the driver */
retval = usb_register(&mdc800_usb_driver);
if (retval)
goto cleanup_on_fail;
printk(KERN_INFO KBUILD_MODNAME ": " DRIVER_VERSION ":"
DRIVER_DESC "\n");
return 0;
/* Clean driver up, when something fails */
cleanup_on_fail:
if (mdc800 != NULL)
{
printk(KERN_ERR "mdc800: can't alloc memory!\n");
kfree(mdc800->download_urb_buffer);
kfree(mdc800->write_urb_buffer);
kfree(mdc800->irq_urb_buffer);
usb_free_urb(mdc800->write_urb);
usb_free_urb(mdc800->download_urb);
usb_free_urb(mdc800->irq_urb);
kfree (mdc800);
}
mdc800 = NULL;
return retval;
}
static void __exit usb_mdc800_cleanup (void)
{
usb_deregister (&mdc800_usb_driver);
usb_free_urb (mdc800->irq_urb);
usb_free_urb (mdc800->download_urb);
usb_free_urb (mdc800->write_urb);
kfree (mdc800->irq_urb_buffer);
kfree (mdc800->write_urb_buffer);
kfree (mdc800->download_urb_buffer);
kfree (mdc800);
mdc800 = NULL;
}
module_init (usb_mdc800_init);
module_exit (usb_mdc800_cleanup);
MODULE_AUTHOR( DRIVER_AUTHOR );
MODULE_DESCRIPTION( DRIVER_DESC );
MODULE_LICENSE("GPL");
|
254469.c | //
// Created by Ruibin on 2020/2/28.
//
/*
* Example code to run and test the process pool. To compile use something like mpicc -o test test.c pool.c
*/
#include <stdio.h>
#include <math.h>
#include <mpi.h>
#include "../include/pool.h"
#include "../include/main.h"
#include "../include/squirrel-functions.h"
static long seed;
int cellWorkers[LENGTH_OF_LAND];
int controllerWorkerPid;
MPI_Group worldGroup, landGroup;
MPI_Comm landComm;
MPI_Request request;
struct Squirrel initialiseSquirrel();
struct LandCell initialiseLandCell();
static void workerCode(WorkerFunc workerFunc);
int squirrelWorker();
int landWorker();
int controllerWorker();
struct LandCell updateLand(int month, MPI_Status status, struct LandCell cell);
struct LandCell renewMonth(int month, struct LandCell cell);
void terminateSquirrel(MPI_Status status);
struct Squirrel squirlGo(int rank, struct Squirrel squirl);
int main(int argc, char* argv[]) {
// Call MPI initialize first
MPI_Init(&argc, &argv);
int rank, size;
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
MPI_Comm_size(MPI_COMM_WORLD, &size);
seed = -1-rank;
initialiseRNG(&seed);
MPI_Comm_group(MPI_COMM_WORLD, &worldGroup);
/*
* Initialise the process pool.
* The return code is = 1 for worker to do some work, 0 for do nothing and stop and 2 for this is the master so call master poll
* For workers this subroutine will block until the master has woken it up to do some work
*/
int statusCode = processPoolInit();
if (statusCode == 1) {
int identity;
MPI_Recv(&identity, 1, MPI_INT, MPI_ANY_SOURCE, 10, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
// A worker so do the worker tasks
WorkerFunc wf;
switch (identity){
case CONTROLLER_ACTOR:
wf = controllerWorker;
break;
case LAND_ACTOR:
wf = landWorker;
break;
case SQUIRREL_ACTOR:
wf = squirrelWorker;
break;
}
workerCode(wf);
} else if (statusCode == 2) {
/*
* This is the master, each call to master poll will block until a message is received and then will handle it and return
* 1 to continue polling and running the pool and 0 to quit.
* Basically it just starts 10 workers and then registers when each one has completed. When they have all completed it
* shuts the entire pool down
*/
int i, sickCount = 0, identity;
// Initial controller
int workerPid = startWorkerProcess();
identity = CONTROLLER_ACTOR;
// Tell the process that it is a controller
MPI_Send(&identity, 1, MPI_INT, workerPid, 10, MPI_COMM_WORLD);
controllerWorkerPid = workerPid;
// Initial land actors
for (i=0;i<LENGTH_OF_LAND;i++) {
int workerPid = startWorkerProcess();
identity = LAND_ACTOR;
// Tell processes that they are land actors
MPI_Send(&identity, 1, MPI_INT, workerPid, 10, MPI_COMM_WORLD);
MPI_Send(&controllerWorkerPid, 1, MPI_INT, workerPid, 10, MPI_COMM_WORLD);
cellWorkers[i] = workerPid;
}
MPI_Send(cellWorkers, LENGTH_OF_LAND, MPI_INT, controllerWorkerPid, 10086, MPI_COMM_WORLD);
for (i=0;i<LENGTH_OF_LAND;i++) {
// Send the message to tell the land's pids to all land actors.
MPI_Send(cellWorkers, LENGTH_OF_LAND, MPI_INT, cellWorkers[i], 10, MPI_COMM_WORLD);
}
// Initial squirrel actors
for (i=0;i<INITIAL_NUMBER_OF_SQUIRRELS;i++) {
int workerPid = startWorkerProcess();
identity = SQUIRREL_ACTOR;
// Tell processes that they are squirrel actors
MPI_Send(&identity, 1, MPI_INT, workerPid, 10, MPI_COMM_WORLD);
int SquirlState;
if (sickCount < INITIAL_INFECTION_LEVEL){
SquirlState = SICK;
sickCount++;
} else {
SquirlState = HEALTHY;
}
MPI_Send(&SquirlState, 1, MPI_INT, workerPid, 1, MPI_COMM_WORLD);
// Tell Squirrels who is controller
MPI_Send(&controllerWorkerPid, 1, MPI_INT, workerPid, 11, MPI_COMM_WORLD);
// Tell Squirrels who are land actors
MPI_Send(&cellWorkers, LENGTH_OF_LAND, MPI_INT, workerPid, 12, MPI_COMM_WORLD);
}
double start, end;
start = MPI_Wtime();
int masterStatus = masterPoll();
while (masterStatus) {
masterStatus=masterPoll();
}
end = MPI_Wtime();
printf("Master Quit. Runtime %f\n", end-start);
}
// Finalizes the process pool, call this before closing down MPI
processPoolFinalise();
// Finalize MPI, ensure you have closed the process pool first
MPI_Finalize();
return 0;
}
static void workerCode(WorkerFunc workerFunc) {
int workerStatus = 1;
while (workerStatus) {
workerFunc();
workerStatus=workerSleep(); // This MPI process will sleep, further workers may be run on this process now
}
}
int squirrelWorker(){
struct Squirrel squirl = initialiseSquirrel();
int rank;
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
while (squirl.state != NOT_EXIST && squirl.state != TERMINATE){
squirl = squirlGo(rank, squirl);
if (squirl.state == NOT_EXIST){
// Tell controller I am dead.
MPI_Send(&squirl.state, 1, MPI_INT, controllerWorkerPid, 99, MPI_COMM_WORLD);
} else if (squirl.state == CATCH_DISEASE) {
// Tell controller I am sick.
MPI_Send(&squirl.state, 1, MPI_INT, controllerWorkerPid, 99, MPI_COMM_WORLD);
squirl.state = SICK;
} else if (squirl.state == TERMINATE) {
MPI_Send(&squirl.state, 1, MPI_INT, controllerWorkerPid, 99, MPI_COMM_WORLD);
}
}
return 0;
}
int landWorker(){
MPI_Recv(&controllerWorkerPid, 1, MPI_INT, 0, 10, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
MPI_Recv(cellWorkers, LENGTH_OF_LAND, MPI_INT, 0, 10, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
// Create a communicator for land actors group
MPI_Group_incl(worldGroup, LENGTH_OF_LAND, cellWorkers, &landGroup);
MPI_Comm_create(MPI_COMM_WORLD, landGroup, &landComm);
struct LandCell cell = initialiseLandCell();
int permissionSignal, terminateSignal, squirrelPid, activeSignal, probeFlag,
receiveMonth, month, squirrelStopSignal, flag, sendBuffer[2], i;
MPI_Request request;
MPI_Status status;
permissionSignal = 1;
terminateSignal = 1;
squirrelStopSignal = 0;
month = 0;
receiveMonth = 0;
int rank;
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
while (1){
if (squirrelStopSignal) {
permissionSignal = 0;
}
// Recv the request from other workers
MPI_Iprobe(MPI_ANY_SOURCE, 0, MPI_COMM_WORLD, &probeFlag, &status);
if (probeFlag) {
if (status.MPI_SOURCE == controllerWorkerPid) {
// This is the message from controller for update month
MPI_Recv(&receiveMonth, 1, MPI_INT, status.MPI_SOURCE, 0, MPI_COMM_WORLD, &status);
if (receiveMonth == LAND_STOP_SIGNAL) {
sendBuffer[0] = cell.population[month % LAST_POPULATION_MONTHS];
sendBuffer[1] = cell.infection[month % LAST_INFECTION_MONTHS];
MPI_Send(sendBuffer, 2, MPI_INT, status.MPI_SOURCE, 199, MPI_COMM_WORLD);
break;
} else if (receiveMonth == SQUIRREL_STOP_SIGNAL) {
squirrelStopSignal = 1;
continue;
}
month = receiveMonth;
sendBuffer[0] = cell.population[(month - 1) % LAST_POPULATION_MONTHS];
sendBuffer[1] = cell.infection[(month - 1) % LAST_INFECTION_MONTHS];
MPI_Send(sendBuffer, 2, MPI_INT, status.MPI_SOURCE, 199, MPI_COMM_WORLD);
cell = renewMonth(month, cell);
MPI_Barrier(landComm);
} else {
// This is the message from squirrels for update cell
if (permissionSignal) {
cell = updateLand(month, status, cell);
} else {
terminateSquirrel(status);
}
}
}
}
return 0;
}
int controllerWorker(){
MPI_Recv(cellWorkers, LENGTH_OF_LAND, MPI_INT, 0, 10086, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
int i, flag, activeLandWorkers, activeSquirrelWorkers, month, permissionSignal, stopSignal,
remainSquirrel, infectedSquirrel, totalDeadSquirrel, squirlSignal,
populationBuffer[LENGTH_OF_LAND], infectionBuffer[LENGTH_OF_LAND], receiveBuffer[2];
MPI_Status status;
permissionSignal = 1;
remainSquirrel = INITIAL_NUMBER_OF_SQUIRRELS;
activeSquirrelWorkers = INITIAL_NUMBER_OF_SQUIRRELS;
activeLandWorkers = LENGTH_OF_LAND;
infectedSquirrel = INITIAL_INFECTION_LEVEL;
totalDeadSquirrel = 0;
month = 0;
double start, end, duration, commStart, commEnd, commDuration;
int rank;
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
start = MPI_Wtime();
while(activeLandWorkers){
if (month < MONTH_LIMIT && activeSquirrelWorkers > 0 && activeSquirrelWorkers < MAX_SQUIRREL_NUMBER) {
end = MPI_Wtime();
duration = end - start;
if (duration > LAND_RENEW_RATE) {
month++;
for (i=0; i<LENGTH_OF_LAND; i++) {
MPI_Send(&month, 1, MPI_INT, cellWorkers[i], 0, MPI_COMM_WORLD);
MPI_Recv(receiveBuffer, 2, MPI_INT, cellWorkers[i], 199, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
populationBuffer[i] = receiveBuffer[0];
infectionBuffer[i] = receiveBuffer[1];
}
printf("Month %d\talive %d\tinfected %d\tdead %d\n", month, remainSquirrel, infectedSquirrel, totalDeadSquirrel);
printf("POP\t[\t"); for (i=0; i<LENGTH_OF_LAND; i++) printf("%d\t", populationBuffer[i]); printf("]\n");
printf("INF\t[\t"); for (i=0; i<LENGTH_OF_LAND; i++) printf("%d\t", infectionBuffer[i]); printf("]\n\n");
start = MPI_Wtime();
continue;
}
commStart = MPI_Wtime();
MPI_Recv(&squirlSignal, 1, MPI_INT, MPI_ANY_SOURCE, 99, MPI_COMM_WORLD, &status);
if (squirlSignal == NOT_EXIST) {
remainSquirrel--;
infectedSquirrel--;
totalDeadSquirrel++;
activeSquirrelWorkers--;
} else if (squirlSignal == BORN){
// Check if the number of squirrel out of limit,
// then decide the squirrel can give birth or not
if (remainSquirrel < MAX_SQUIRREL_NUMBER) {
squirlSignal = HEALTHY;
remainSquirrel++;
activeSquirrelWorkers++;
} else {
squirlSignal = NOT_EXIST;
activeSquirrelWorkers++;
}
MPI_Send(&squirlSignal, 1, MPI_INT, status.MPI_SOURCE, 100, MPI_COMM_WORLD);
} else if (squirlSignal == CATCH_DISEASE) {
infectedSquirrel++;
} else if (squirlSignal == TERMINATE) {
activeSquirrelWorkers--;
}
commEnd = MPI_Wtime();
commDuration = commEnd - commStart;
start += commDuration;
} else if (activeSquirrelWorkers > 0) {
stopSignal = SQUIRREL_STOP_SIGNAL; // Let the land actor tell squirrels to stop
MPI_Request requestList[LENGTH_OF_LAND];
MPI_Status statusList[LENGTH_OF_LAND];
for (i=0; i<LENGTH_OF_LAND; i++) {
MPI_Isend(&stopSignal, 1, MPI_INT, cellWorkers[i], 0, MPI_COMM_WORLD, &requestList[i]);
}
MPI_Waitall(LENGTH_OF_LAND, requestList, statusList);
while (activeSquirrelWorkers) {
MPI_Recv(&squirlSignal, 1, MPI_INT, MPI_ANY_SOURCE, 99, MPI_COMM_WORLD, &status);
if (squirlSignal == NOT_EXIST || squirlSignal == TERMINATE)
activeSquirrelWorkers--;
else if (squirlSignal == BORN){
// Check if the number of squirrel out of limit,
// then decide the squirrel can give birth or not
squirlSignal = NOT_EXIST;
MPI_Send(&squirlSignal, 1, MPI_INT, status.MPI_SOURCE, 100, MPI_COMM_WORLD);
}
}
} else {
stopSignal = LAND_STOP_SIGNAL;
for (i=0; i<LENGTH_OF_LAND; i++) {
MPI_Send(&stopSignal, 1, MPI_INT, cellWorkers[i], 0, MPI_COMM_WORLD);
MPI_Recv(receiveBuffer, 2, MPI_INT, cellWorkers[i], 199, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
populationBuffer[i] = receiveBuffer[0];
infectionBuffer[i] = receiveBuffer[1];
activeLandWorkers--;
}
}
}
printf("[Last output] Month %d\talive %d\tinfected %d\tdead %d\n", month, remainSquirrel, infectedSquirrel, totalDeadSquirrel);
printf("POP\t[\t"); for (i=0; i<LENGTH_OF_LAND; i++) printf("%d\t", populationBuffer[i]); printf("]\n");
printf("INF\t[\t"); for (i=0; i<LENGTH_OF_LAND; i++) printf("%d\t", infectionBuffer[i]); printf("]\n\n");
printf("Controller Stop\n");
shutdownPool();
return 0;
}
struct Squirrel initialiseSquirrel(){
int i, parentId;
struct Squirrel squirl;
MPI_Status status;
float coord[2];
squirl.x = 0;
squirl.y = 0;
parentId = getCommandData();
MPI_Probe(parentId, MPI_ANY_TAG, MPI_COMM_WORLD, &status);
if (status.MPI_TAG == 10) { // This means the process was a squirrel but dead. Now restart it.
// This is a redundant identity, will be covered
MPI_Recv(&squirl.state, 1, MPI_INT, parentId, 10, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
}
MPI_Recv(&squirl.state, 1, MPI_INT, parentId, 1, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
MPI_Recv(&controllerWorkerPid, 1, MPI_INT, parentId, 11, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
MPI_Recv(&cellWorkers, LENGTH_OF_LAND, MPI_INT, parentId, 12, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
if (parentId == 0) { // This means the squirrel is created by master, therefore, the x and y are randomised
squirrelStep(squirl.x, squirl.y, &coord[0], &coord[1], &seed);
squirl.x = coord[0];
squirl.y = coord[1];
} else { // This means the squirrel is birthed by a existed squirrel, therefore, inherit parent's x and y
MPI_Recv(&coord, 2, MPI_FLOAT, parentId, 12, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
squirl.x = coord[0];
squirl.y = coord[1];
}
squirl.steps = 0;
squirl.sickSteps = 0;
for (i=0; i<LAST_POPULATION_STEPS; i++)
squirl.pop[i] = 0;
for (i=0; i<LAST_INFECTION_STEPS; i++)
squirl.inf[i] = 0;
return squirl;
}
struct LandCell initialiseLandCell(){
struct LandCell cell;
int i, j;
// Initialise population
for (i=0; i<LAST_POPULATION_MONTHS; i++) {
cell.population[i] = 0;
}
// Initialise infection
for (i=0; i<LAST_INFECTION_MONTHS; i++) {
cell.infection[i] = 0;
}
return cell;
}
struct Squirrel squirlGo(int rank, struct Squirrel squirl) {
int i, position;
position = getCellFromPosition(squirl.x, squirl.y);
// Send the squirrel's position
int recvBuffer[2], count;
MPI_Status status;
float x_new, y_new;
squirrelStep(squirl.x, squirl.y, &x_new, &y_new, &seed);
squirl.x = x_new;
squirl.y = y_new;
// Send squirrel state to Land Actor
MPI_Send(&squirl.state, 1, MPI_INT, cellWorkers[position], 0, MPI_COMM_WORLD);
// Recv the population and infection level at this position
MPI_Probe(MPI_ANY_SOURCE, 6, MPI_COMM_WORLD, &status);
MPI_Get_count(&status, MPI_INT, &count);
if (count == 0) {
MPI_Recv(NULL, 0, MPI_INT, cellWorkers[position], 6, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
squirl.state = TERMINATE;
return squirl;
} else if (count == 2) {
MPI_Recv(recvBuffer, 2, MPI_INT, cellWorkers[position], 6, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
}
// Update population and infection level
squirl.pop[squirl.steps % LAST_POPULATION_STEPS] = recvBuffer[0];
squirl.inf[squirl.steps % LAST_INFECTION_STEPS] = recvBuffer[1];
squirl.steps++;
if (squirl.state == SICK){
squirl.sickSteps++;
}
// The squirrel will catches disease
if (squirl.steps > 50 && squirl.state == HEALTHY) {
float avg_inf_level;
avg_inf_level = 0.0;
for (i = 0; i < LAST_INFECTION_STEPS; i++) {
avg_inf_level += squirl.inf[i];
}
avg_inf_level /= LAST_INFECTION_STEPS;
if (willCatchDisease(avg_inf_level, &seed)) {
squirl.state = CATCH_DISEASE;
}
}
// The squirrel will give birth
if (squirl.steps % GIVE_BIRTH_STEPS == 0) {
float avg_pop;
avg_pop = 0.0;
for (i=0; i<LAST_POPULATION_STEPS; i++) {
avg_pop += squirl.pop[i];
}
avg_pop /= LAST_POPULATION_STEPS;
if (willGiveBirth(avg_pop, &seed)){
/* Create a new process and squirrel */
int childPid, childState, identity;
childState = BORN;
// Enquiry controller whether I can give birth
MPI_Send(&childState, 1, MPI_INT, controllerWorkerPid, 99, MPI_COMM_WORLD);
MPI_Recv(&childState, 1, MPI_INT, controllerWorkerPid, 100, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
// If it does not recv the BORN signal, it means the number of squirrels out of limit.
if (childState == HEALTHY) {
childPid = startWorkerProcess();
identity = SQUIRREL_ACTOR;
float coord[2];
coord[0] = squirl.x;
coord[1] = squirl.y;
MPI_Send(&identity, 1, MPI_INT, childPid, 10, MPI_COMM_WORLD);
MPI_Send(&childState, 1, MPI_INT, childPid, 1, MPI_COMM_WORLD);
// Tell baby squirrel who is controller
MPI_Send(&controllerWorkerPid, 1, MPI_INT, childPid, 11, MPI_COMM_WORLD);
// Tell baby squirrel who are land actors
MPI_Send(&cellWorkers, LENGTH_OF_LAND, MPI_INT, childPid, 12, MPI_COMM_WORLD);
MPI_Send(coord, 2, MPI_FLOAT, childPid, 12, MPI_COMM_WORLD);
}
}
}
// The squirrel will die
if (squirl.sickSteps > 50 && squirl.state == SICK) {
if (willDie(&seed)) {
squirl.state = NOT_EXIST;
}
}
return squirl;
}
struct LandCell updateLand(int month, MPI_Status status, struct LandCell cell){
int squirlState, sendBuffer[2];
MPI_Recv(&squirlState, 1, MPI_INT, status.MPI_SOURCE, 0, MPI_COMM_WORLD, &status);
cell.population[month % LAST_POPULATION_MONTHS]+=1;
if (squirlState == SICK)
cell.infection[month % LAST_INFECTION_MONTHS]+=1;
// According to the recv position, send the population and infection level back
sendBuffer[0]=cell.population[month % LAST_POPULATION_MONTHS];
sendBuffer[1]=cell.infection[month % LAST_INFECTION_MONTHS];
MPI_Send(sendBuffer, 2, MPI_INT, status.MPI_SOURCE, 6, MPI_COMM_WORLD);
return cell;
}
void terminateSquirrel(MPI_Status status){
int squirlState;
MPI_Recv(&squirlState, 1, MPI_INT, status.MPI_SOURCE, 0, MPI_COMM_WORLD, &status);
MPI_Send(NULL, 0, MPI_INT, status.MPI_SOURCE, 6, MPI_COMM_WORLD);
}
struct LandCell renewMonth(int month, struct LandCell cell){
cell.population[month % LAST_POPULATION_MONTHS] = 0;
cell.infection[month % LAST_INFECTION_MONTHS] = 0;
return cell;
}
|
808692.c | #include <stdio.h>
int main()
{
int n,i,j;
scanf("%d",&n);
int isprime;
for(i=n+1;;i++){
isprime=1;
for(j=2;j<i;j++){
if(i%j==0){
isprime=0;
break;
}
}
if(isprime){
printf("%d",i);
break;
}
}
return 0;
} |
880996.c | /* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
file Copyright.txt or https://cmake.org/licensing#kwsys for details. */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int testFail(int argc, char* argv[])
{
char* env = getenv("DASHBOARD_TEST_FROM_CTEST");
int oldCtest = 0;
if (env) {
if (strcmp(env, "1") == 0) {
oldCtest = 1;
}
printf("DASHBOARD_TEST_FROM_CTEST = %s\n", env);
}
printf("%s: This test intentionally fails\n", argv[0]);
if (oldCtest) {
printf("The version of ctest is not able to handle intentionally failing "
"tests, so pass.\n");
return 0;
}
return argc;
}
|
938365.c | /*
** FFT and FHT routines
** Copyright 1988, 1993; Ron Mayer
** Copyright (c) 1999-2000 Takehiro Tominaga
**
** fht(fz,n);
** Does a hartley transform of "n" points in the array "fz".
**
** NOTE: This routine uses at least 2 patented algorithms, and may be
** under the restrictions of a bunch of different organizations.
** Although I wrote it completely myself; it is kind of a derivative
** of a routine I once authored and released under the GPL, so it
** may fall under the free software foundation's restrictions;
** it was worked on as a Stanford Univ project, so they claim
** some rights to it; it was further optimized at work here, so
** I think this company claims parts of it. The patents are
** held by R. Bracewell (the FHT algorithm) and O. Buneman (the
** trig generator), both at Stanford Univ.
** If it were up to me, I'd say go do whatever you want with it;
** but it would be polite to give credit to the following people
** if you use this anywhere:
** Euler - probable inventor of the fourier transform.
** Gauss - probable inventor of the FFT.
** Hartley - probable inventor of the hartley transform.
** Buneman - for a really cool trig generator
** Mayer(me) - for authoring this particular version and
** including all the optimizations in one package.
** Thanks,
** Ron Mayer; [email protected]
** and added some optimization by
** Mather - idea of using lookup table
** Takehiro - some dirty hack for speed up
*/
/* $Id: fft.c,v 1.39 2017/09/06 15:07:29 robert Exp $ */
#ifdef HAVE_CONFIG_H
# include <config.h>
#endif
#include "lame.h"
#include "machine.h"
#include "encoder.h"
#include "util.h"
#include "fft.h"
//#include "vector/lame_intrin.h"
#define TRI_SIZE (5-1) /* 1024 = 4**5 */
/* fft.c */
static const FLOAT costab[TRI_SIZE * 2] = {
9.238795325112867e-01, 3.826834323650898e-01,
9.951847266721969e-01, 9.801714032956060e-02,
9.996988186962042e-01, 2.454122852291229e-02,
9.999811752826011e-01, 6.135884649154475e-03
};
static void
fht(FLOAT * fz, int n)
{
const FLOAT *tri = costab;
int k4;
FLOAT *fi, *gi;
FLOAT const *fn;
n <<= 1; /* to get BLKSIZE, because of 3DNow! ASM routine */
fn = fz + n;
k4 = 4;
do {
FLOAT s1, c1;
int i, k1, k2, k3, kx;
kx = k4 >> 1;
k1 = k4;
k2 = k4 << 1;
k3 = k2 + k1;
k4 = k2 << 1;
fi = fz;
gi = fi + kx;
do {
FLOAT f0, f1, f2, f3;
f1 = fi[0] - fi[k1];
f0 = fi[0] + fi[k1];
f3 = fi[k2] - fi[k3];
f2 = fi[k2] + fi[k3];
fi[k2] = f0 - f2;
fi[0] = f0 + f2;
fi[k3] = f1 - f3;
fi[k1] = f1 + f3;
f1 = gi[0] - gi[k1];
f0 = gi[0] + gi[k1];
f3 = SQRT2 * gi[k3];
f2 = SQRT2 * gi[k2];
gi[k2] = f0 - f2;
gi[0] = f0 + f2;
gi[k3] = f1 - f3;
gi[k1] = f1 + f3;
gi += k4;
fi += k4;
} while (fi < fn);
c1 = tri[0];
s1 = tri[1];
for (i = 1; i < kx; i++) {
FLOAT c2, s2;
c2 = 1 - (2 * s1) * s1;
s2 = (2 * s1) * c1;
fi = fz + i;
gi = fz + k1 - i;
do {
FLOAT a, b, g0, f0, f1, g1, f2, g2, f3, g3;
b = s2 * fi[k1] - c2 * gi[k1];
a = c2 * fi[k1] + s2 * gi[k1];
f1 = fi[0] - a;
f0 = fi[0] + a;
g1 = gi[0] - b;
g0 = gi[0] + b;
b = s2 * fi[k3] - c2 * gi[k3];
a = c2 * fi[k3] + s2 * gi[k3];
f3 = fi[k2] - a;
f2 = fi[k2] + a;
g3 = gi[k2] - b;
g2 = gi[k2] + b;
b = s1 * f2 - c1 * g3;
a = c1 * f2 + s1 * g3;
fi[k2] = f0 - a;
fi[0] = f0 + a;
gi[k3] = g1 - b;
gi[k1] = g1 + b;
b = c1 * g2 - s1 * f3;
a = s1 * g2 + c1 * f3;
gi[k2] = g0 - a;
gi[0] = g0 + a;
fi[k3] = f1 - b;
fi[k1] = f1 + b;
gi += k4;
fi += k4;
} while (fi < fn);
c2 = c1;
c1 = c2 * tri[0] - s1 * tri[1];
s1 = c2 * tri[1] + s1 * tri[0];
}
tri += 2;
} while (k4 < n);
}
static const unsigned char rv_tbl[] = {
0x00, 0x80, 0x40, 0xc0, 0x20, 0xa0, 0x60, 0xe0,
0x10, 0x90, 0x50, 0xd0, 0x30, 0xb0, 0x70, 0xf0,
0x08, 0x88, 0x48, 0xc8, 0x28, 0xa8, 0x68, 0xe8,
0x18, 0x98, 0x58, 0xd8, 0x38, 0xb8, 0x78, 0xf8,
0x04, 0x84, 0x44, 0xc4, 0x24, 0xa4, 0x64, 0xe4,
0x14, 0x94, 0x54, 0xd4, 0x34, 0xb4, 0x74, 0xf4,
0x0c, 0x8c, 0x4c, 0xcc, 0x2c, 0xac, 0x6c, 0xec,
0x1c, 0x9c, 0x5c, 0xdc, 0x3c, 0xbc, 0x7c, 0xfc,
0x02, 0x82, 0x42, 0xc2, 0x22, 0xa2, 0x62, 0xe2,
0x12, 0x92, 0x52, 0xd2, 0x32, 0xb2, 0x72, 0xf2,
0x0a, 0x8a, 0x4a, 0xca, 0x2a, 0xaa, 0x6a, 0xea,
0x1a, 0x9a, 0x5a, 0xda, 0x3a, 0xba, 0x7a, 0xfa,
0x06, 0x86, 0x46, 0xc6, 0x26, 0xa6, 0x66, 0xe6,
0x16, 0x96, 0x56, 0xd6, 0x36, 0xb6, 0x76, 0xf6,
0x0e, 0x8e, 0x4e, 0xce, 0x2e, 0xae, 0x6e, 0xee,
0x1e, 0x9e, 0x5e, 0xde, 0x3e, 0xbe, 0x7e, 0xfe
};
#define ch01(index) (buffer[chn][index])
#define ml00(f) (window[i ] * f(i))
#define ml10(f) (window[i + 0x200] * f(i + 0x200))
#define ml20(f) (window[i + 0x100] * f(i + 0x100))
#define ml30(f) (window[i + 0x300] * f(i + 0x300))
#define ml01(f) (window[i + 0x001] * f(i + 0x001))
#define ml11(f) (window[i + 0x201] * f(i + 0x201))
#define ml21(f) (window[i + 0x101] * f(i + 0x101))
#define ml31(f) (window[i + 0x301] * f(i + 0x301))
#define ms00(f) (window_s[i ] * f(i + k))
#define ms10(f) (window_s[0x7f - i] * f(i + k + 0x80))
#define ms20(f) (window_s[i + 0x40] * f(i + k + 0x40))
#define ms30(f) (window_s[0x3f - i] * f(i + k + 0xc0))
#define ms01(f) (window_s[i + 0x01] * f(i + k + 0x01))
#define ms11(f) (window_s[0x7e - i] * f(i + k + 0x81))
#define ms21(f) (window_s[i + 0x41] * f(i + k + 0x41))
#define ms31(f) (window_s[0x3e - i] * f(i + k + 0xc1))
void
fft_short(lame_internal_flags const *const gfc,
FLOAT x_real[3][BLKSIZE_s], int chn, const sample_t *const buffer[2])
{
int i;
int j;
int b;
#define window_s gfc->cd_psy->window_s
#define window gfc->cd_psy->window
for (b = 0; b < 3; b++) {
FLOAT *x = &x_real[b][BLKSIZE_s / 2];
short const k = (576 / 3) * (b + 1);
j = BLKSIZE_s / 8 - 1;
do {
FLOAT f0, f1, f2, f3, w;
i = rv_tbl[j << 2];
f0 = ms00(ch01);
w = ms10(ch01);
f1 = f0 - w;
f0 = f0 + w;
f2 = ms20(ch01);
w = ms30(ch01);
f3 = f2 - w;
f2 = f2 + w;
x -= 4;
x[0] = f0 + f2;
x[2] = f0 - f2;
x[1] = f1 + f3;
x[3] = f1 - f3;
f0 = ms01(ch01);
w = ms11(ch01);
f1 = f0 - w;
f0 = f0 + w;
f2 = ms21(ch01);
w = ms31(ch01);
f3 = f2 - w;
f2 = f2 + w;
x[BLKSIZE_s / 2 + 0] = f0 + f2;
x[BLKSIZE_s / 2 + 2] = f0 - f2;
x[BLKSIZE_s / 2 + 1] = f1 + f3;
x[BLKSIZE_s / 2 + 3] = f1 - f3;
} while (--j >= 0);
#undef window
#undef window_s
gfc->fft_fht(x, BLKSIZE_s / 2);
/* BLKSIZE_s/2 because of 3DNow! ASM routine */
}
}
void
fft_long(lame_internal_flags const *const gfc,
FLOAT x[BLKSIZE], int chn, const sample_t *const buffer[2])
{
int i;
int jj = BLKSIZE / 8 - 1;
x += BLKSIZE / 2;
#define window_s gfc->cd_psy->window_s
#define window gfc->cd_psy->window
do {
FLOAT f0, f1, f2, f3, w;
i = rv_tbl[jj];
f0 = ml00(ch01);
w = ml10(ch01);
f1 = f0 - w;
f0 = f0 + w;
f2 = ml20(ch01);
w = ml30(ch01);
f3 = f2 - w;
f2 = f2 + w;
x -= 4;
x[0] = f0 + f2;
x[2] = f0 - f2;
x[1] = f1 + f3;
x[3] = f1 - f3;
f0 = ml01(ch01);
w = ml11(ch01);
f1 = f0 - w;
f0 = f0 + w;
f2 = ml21(ch01);
w = ml31(ch01);
f3 = f2 - w;
f2 = f2 + w;
x[BLKSIZE / 2 + 0] = f0 + f2;
x[BLKSIZE / 2 + 2] = f0 - f2;
x[BLKSIZE / 2 + 1] = f1 + f3;
x[BLKSIZE / 2 + 3] = f1 - f3;
} while (--jj >= 0);
#undef window
#undef window_s
gfc->fft_fht(x, BLKSIZE / 2);
/* BLKSIZE/2 because of 3DNow! ASM routine */
}
#ifdef HAVE_NASM
extern void fht_3DN(FLOAT * fz, int n);
extern void fht_SSE(FLOAT * fz, int n);
#endif
void
init_fft(lame_internal_flags * const gfc)
{
int i;
/* The type of window used here will make no real difference, but */
/* in the interest of merging nspsytune stuff - switch to blackman window */
for (i = 0; i < BLKSIZE; i++)
/* blackman window */
gfc->cd_psy->window[i] = 0.42 - 0.5 * cos(2 * PI * (i + .5) / BLKSIZE) +
0.08 * cos(4 * PI * (i + .5) / BLKSIZE);
for (i = 0; i < BLKSIZE_s / 2; i++)
gfc->cd_psy->window_s[i] = 0.5 * (1.0 - cos(2.0 * PI * (i + 0.5) / BLKSIZE_s));
gfc->fft_fht = fht;
#ifdef HAVE_NASM
if (gfc->CPU_features.AMD_3DNow) {
gfc->fft_fht = fht_3DN;
}
else if (gfc->CPU_features.SSE) {
gfc->fft_fht = fht_SSE;
}
else {
gfc->fft_fht = fht;
}
#else
#ifdef HAVE_XMMINTRIN_H
#ifdef MIN_ARCH_SSE
gfc->fft_fht = fht_SSE2;
#endif
#endif
#endif
}
|
385750.c | // SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2020-2021, Intel Corporation */
/*
* conn_req-connect.c -- the rpma_conn_req_connect() unit tests
*
* APIs covered:
* - rpma_conn_req_connect()
*/
#include "conn_req-common.h"
#include "test-common.h"
static struct conn_req_new_test_state prestate_conn_cfg_default;
/*
* connect__req_ptr_NULL -- NULL req_ptr is invalid
*/
static void
connect__req_ptr_NULL(void **unused)
{
/* run test */
struct rpma_conn *conn = NULL;
int ret = rpma_conn_req_connect(NULL, NULL, &conn);
/* verify the results */
assert_int_equal(ret, RPMA_E_INVAL);
assert_null(conn);
}
/*
* connect__conn_ptr_NULL -- NULL conn_ptr is invalid
*/
static void
connect__conn_ptr_NULL(void **cstate_ptr)
{
struct conn_req_test_state *cstate = *cstate_ptr;
/* run test */
int ret = rpma_conn_req_connect(&cstate->req, NULL, NULL);
/* verify the results */
assert_int_equal(ret, RPMA_E_INVAL);
assert_non_null(cstate->req);
}
/*
* connect__req_NULL -- NULL *req_ptr is invalid
*/
static void
connect__req_NULL(void **unused)
{
/* run test */
struct rpma_conn_req *req = NULL;
struct rpma_conn *conn = NULL;
int ret = rpma_conn_req_connect(&req, NULL, &conn);
/* verify the results */
assert_int_equal(ret, RPMA_E_INVAL);
assert_null(conn);
assert_null(req);
}
/*
* connect__pdata_NULL_pdata_ptr_NULL -- pdata->ptr == NULL is invalid
*/
static void
connect__pdata_NULL_pdata_ptr_NULL(void **cstate_ptr)
{
struct conn_req_test_state *cstate = *cstate_ptr;
/* run test */
struct rpma_conn *conn = NULL;
struct rpma_conn_private_data pdata = {NULL, 1};
int ret = rpma_conn_req_connect(&cstate->req, &pdata, &conn);
/* verify the results */
assert_int_equal(ret, RPMA_E_INVAL);
assert_non_null(cstate->req);
assert_null(conn);
}
/*
* connect__pdata_NULL_pdata_len_0 -- pdata->len == 0 is invalid
*/
static void
connect__pdata_NULL_pdata_len_0(void **cstate_ptr)
{
struct conn_req_test_state *cstate = *cstate_ptr;
char buff = 0;
/* run test */
struct rpma_conn *conn = NULL;
struct rpma_conn_private_data pdata = {&buff, 0};
int ret = rpma_conn_req_connect(&cstate->req, &pdata, &conn);
/* verify the results */
assert_int_equal(ret, RPMA_E_INVAL);
assert_non_null(cstate->req);
assert_null(conn);
}
/*
* connect__pdata_NULL_pdata_ptr_NULL_len_0 -- pdata->ptr == NULL and
* pdata->len == 0 are invalid
*/
static void
connect__pdata_NULL_pdata_ptr_NULL_len_0(void **cstate_ptr)
{
struct conn_req_test_state *cstate = *cstate_ptr;
/* run test */
struct rpma_conn *conn = NULL;
struct rpma_conn_private_data pdata = {NULL, 0};
int ret = rpma_conn_req_connect(&cstate->req, &pdata, &conn);
/* verify the results */
assert_int_equal(ret, RPMA_E_INVAL);
assert_non_null(cstate->req);
assert_null(conn);
}
/*
* connect_via_accept__accept_EAGAIN -- rdma_accept() fails with EAGAIN
*/
static void
connect_via_accept__accept_EAGAIN(void **unused)
{
/* WA for cmocka/issues#47 */
struct conn_req_test_state *cstate = NULL;
assert_int_equal(setup__conn_req_from_cm_event((void **)&cstate), 0);
assert_non_null(cstate);
/* configure mocks */
expect_value(rdma_accept, id, &cstate->id);
will_return(rdma_accept, EAGAIN);
expect_value(rdma_ack_cm_event, event, &cstate->event);
will_return(rdma_ack_cm_event, MOCK_OK);
expect_value(rdma_destroy_qp, id, &cstate->id);
will_return(ibv_destroy_cq, MOCK_OK);
will_return(ibv_destroy_comp_channel, MOCK_OK);
/* run test */
struct rpma_conn *conn = NULL;
int ret = rpma_conn_req_connect(&cstate->req, NULL, &conn);
/* verify the results */
assert_int_equal(ret, RPMA_E_PROVIDER);
assert_null(cstate->req);
assert_null(conn);
}
/*
* connect_via_accept__accept_EAGAIN_subsequent_EIO -- rdma_accept()
* fails with EAGAIN whereas subsequent (rdma_ack_cm_event(),
* ibv_destroy_cq()) fail with EIO
*/
static void
connect_via_accept__accept_EAGAIN_subsequent_EIO(void **unused)
{
/* WA for cmocka/issues#47 */
struct conn_req_test_state *cstate = NULL;
assert_int_equal(setup__conn_req_from_cm_event((void **)&cstate), 0);
assert_non_null(cstate);
/* configure mocks */
expect_value(rdma_accept, id, &cstate->id);
will_return(rdma_accept, EAGAIN); /* first error */
expect_value(rdma_ack_cm_event, event, &cstate->event);
will_return(rdma_ack_cm_event, EIO); /* second error */
expect_value(rdma_destroy_qp, id, &cstate->id);
will_return(ibv_destroy_cq, EIO); /* third error */
will_return(ibv_destroy_comp_channel, EIO); /* fourth error */
/* run test */
struct rpma_conn *conn = NULL;
int ret = rpma_conn_req_connect(&cstate->req, NULL, &conn);
/* verify the results */
assert_int_equal(ret, RPMA_E_PROVIDER);
assert_null(cstate->req);
assert_null(conn);
}
/*
* connect_via_accept__ack_EAGAIN -- rdma_ack_cm_event() fails with EAGAIN
*/
static void
connect_via_accept__ack_EAGAIN(void **unused)
{
/* WA for cmocka/issues#47 */
struct conn_req_test_state *cstate = NULL;
assert_int_equal(setup__conn_req_from_cm_event((void **)&cstate), 0);
assert_non_null(cstate);
/* configure mocks */
expect_value(rdma_accept, id, &cstate->id);
will_return(rdma_accept, MOCK_OK);
expect_value(rdma_ack_cm_event, event, &cstate->event);
will_return(rdma_ack_cm_event, EAGAIN);
expect_value(rdma_disconnect, id, &cstate->id);
will_return(rdma_disconnect, MOCK_OK);
expect_value(rdma_destroy_qp, id, &cstate->id);
will_return(ibv_destroy_cq, MOCK_OK);
will_return(ibv_destroy_comp_channel, MOCK_OK);
/* run test */
struct rpma_conn *conn = NULL;
int ret = rpma_conn_req_connect(&cstate->req, NULL, &conn);
/* verify the results */
assert_int_equal(ret, RPMA_E_PROVIDER);
assert_null(cstate->req);
assert_null(conn);
}
/*
* connect_via_accept__ack_EAGAIN_subsequent_EIO -- rdma_ack_cm_event()
* fails with EAGAIN whereas subsequent (rdma_disconnect(), ibv_destroy_cq())
* fail with EIO
*/
static void
connect_via_accept__ack_EAGAIN_subsequent_EIO(void **unused)
{
/* WA for cmocka/issues#47 */
struct conn_req_test_state *cstate = NULL;
assert_int_equal(setup__conn_req_from_cm_event((void **)&cstate), 0);
assert_non_null(cstate);
/* configure mocks */
expect_value(rdma_accept, id, &cstate->id);
will_return(rdma_accept, MOCK_OK);
expect_value(rdma_ack_cm_event, event, &cstate->event);
will_return(rdma_ack_cm_event, EAGAIN); /* first error */
expect_value(rdma_disconnect, id, &cstate->id);
will_return(rdma_disconnect, EIO); /* second error */
expect_value(rdma_destroy_qp, id, &cstate->id);
will_return(ibv_destroy_cq, EIO); /* third error */
will_return(ibv_destroy_comp_channel, EIO); /* fourth error */
/* run test */
struct rpma_conn *conn = NULL;
int ret = rpma_conn_req_connect(&cstate->req, NULL, &conn);
/* verify the results */
assert_int_equal(ret, RPMA_E_PROVIDER);
assert_null(cstate->req);
assert_null(conn);
}
/*
* connect_via_accept__conn_new_EAGAIN -- rpma_conn_new() fails with
* RPMA_E_PROVIDER + EAGAIN
*/
static void
connect_via_accept__conn_new_EAGAIN(void **unused)
{
/* WA for cmocka/issues#47 */
struct conn_req_test_state *cstate = NULL;
assert_int_equal(setup__conn_req_from_cm_event((void **)&cstate), 0);
assert_non_null(cstate);
/* configure mocks */
expect_value(rdma_accept, id, &cstate->id);
will_return(rdma_accept, MOCK_OK);
expect_value(rdma_ack_cm_event, event, &cstate->event);
will_return(rdma_ack_cm_event, MOCK_OK);
expect_value(rpma_conn_new, id, &cstate->id);
will_return(rpma_conn_new, NULL);
will_return(rpma_conn_new, RPMA_E_PROVIDER);
will_return(rpma_conn_new, EAGAIN);
expect_value(rdma_disconnect, id, &cstate->id);
will_return(rdma_disconnect, MOCK_OK);
expect_value(rdma_destroy_qp, id, &cstate->id);
will_return(ibv_destroy_cq, MOCK_OK);
will_return(ibv_destroy_comp_channel, MOCK_OK);
/* run test */
struct rpma_conn *conn = NULL;
int ret = rpma_conn_req_connect(&cstate->req, NULL, &conn);
/* verify the results */
assert_int_equal(ret, RPMA_E_PROVIDER);
assert_null(cstate->req);
assert_null(conn);
}
/*
* connect_via_accept__conn_new_EAGAIN_subsequent_EIO --
* rpma_conn_new() fails with RPMA_E_PROVIDER + EAGAIN
* whereas subsequent (rdma_disconnect(), ibv_destroy_cq()) fail with EIO
*/
static void
connect_via_accept__conn_new_EAGAIN_subsequent_EIO(void **unused)
{
/* WA for cmocka/issues#47 */
struct conn_req_test_state *cstate = NULL;
assert_int_equal(setup__conn_req_from_cm_event((void **)&cstate), 0);
assert_non_null(cstate);
/* configure mocks */
expect_value(rdma_accept, id, &cstate->id);
will_return(rdma_accept, MOCK_OK);
expect_value(rdma_ack_cm_event, event, &cstate->event);
will_return(rdma_ack_cm_event, MOCK_OK);
expect_value(rpma_conn_new, id, &cstate->id);
will_return(rpma_conn_new, NULL);
will_return(rpma_conn_new, RPMA_E_PROVIDER);
will_return(rpma_conn_new, EAGAIN); /* first error */
expect_value(rdma_disconnect, id, &cstate->id);
will_return(rdma_disconnect, EIO); /* second error */
expect_value(rdma_destroy_qp, id, &cstate->id);
will_return(ibv_destroy_cq, EIO); /* third error */
will_return(ibv_destroy_comp_channel, EIO); /* fourth error */
/* run test */
struct rpma_conn *conn = NULL;
int ret = rpma_conn_req_connect(&cstate->req, NULL, &conn);
/* verify the results */
assert_int_equal(ret, RPMA_E_PROVIDER);
assert_null(cstate->req);
assert_null(conn);
}
/*
* connect_via_accept__set_private_data_ENOMEM -- rpma_conn_set_private_data()
* fails with ENOMEM
*/
static void
connect_via_accept__set_private_data_ENOMEM(void **unused)
{
/* WA for cmocka/issues#47 */
struct conn_req_test_state *cstate = NULL;
assert_int_equal(setup__conn_req_from_cm_event((void **)&cstate), 0);
assert_non_null(cstate);
/* configure mocks */
expect_value(rdma_accept, id, &cstate->id);
will_return(rdma_accept, MOCK_OK);
expect_value(rdma_ack_cm_event, event, &cstate->event);
will_return(rdma_ack_cm_event, MOCK_OK);
expect_value(rpma_conn_new, id, &cstate->id);
will_return(rpma_conn_new, MOCK_CONN);
expect_value(rpma_conn_set_private_data, conn, MOCK_CONN);
expect_value(rpma_conn_set_private_data, pdata->ptr, MOCK_PRIVATE_DATA);
expect_value(rpma_conn_set_private_data, pdata->len, MOCK_PDATA_LEN);
will_return(rpma_conn_set_private_data, RPMA_E_NOMEM);
expect_value(rpma_conn_delete, conn, MOCK_CONN);
will_return(rpma_conn_delete, MOCK_OK);
expect_value(rdma_disconnect, id, &cstate->id);
will_return(rdma_disconnect, MOCK_OK);
expect_value(rdma_destroy_qp, id, &cstate->id);
will_return(ibv_destroy_cq, MOCK_OK);
will_return(ibv_destroy_comp_channel, MOCK_OK);
/* run test */
struct rpma_conn *conn = NULL;
int ret = rpma_conn_req_connect(&cstate->req, NULL, &conn);
/* verify the results */
assert_int_equal(ret, RPMA_E_NOMEM);
assert_null(cstate->req);
assert_null(conn);
}
/*
* connect_via_accept__success_incoming -- rpma_conn_req_connect()
* success (using an incoming connection request)
*/
static void
connect_via_accept__success_incoming(void **unused)
{
/* WA for cmocka/issues#47 */
struct conn_req_test_state *cstate = NULL;
assert_int_equal(setup__conn_req_from_cm_event((void **)&cstate), 0);
assert_non_null(cstate);
/* configure mocks */
expect_value(rdma_accept, id, &cstate->id);
will_return(rdma_accept, MOCK_OK);
expect_value(rdma_ack_cm_event, event, &cstate->event);
will_return(rdma_ack_cm_event, MOCK_OK);
expect_value(rpma_conn_new, id, &cstate->id);
will_return(rpma_conn_new, MOCK_CONN);
expect_value(rpma_conn_set_private_data, conn, MOCK_CONN);
expect_value(rpma_conn_set_private_data, pdata->ptr, MOCK_PRIVATE_DATA);
expect_value(rpma_conn_set_private_data, pdata->len, MOCK_PDATA_LEN);
will_return(rpma_conn_set_private_data, 0);
expect_function_call(rpma_private_data_discard);
/* run test */
struct rpma_conn *conn = NULL;
int ret = rpma_conn_req_connect(&cstate->req, NULL, &conn);
/* verify the results */
assert_int_equal(ret, MOCK_OK);
assert_null(cstate->req);
assert_int_equal(conn, MOCK_CONN);
}
/*
* connect_via_connect__connect_EAGAIN -- rdma_connect() fails with EAGAIN
*/
static void
connect_via_connect__connect_EAGAIN(void **unused)
{
/* WA for cmocka/issues#47 */
struct conn_req_new_test_state *cstate = &prestate_conn_cfg_default;
assert_int_equal(setup__conn_req_new((void **)&cstate), 0);
assert_non_null(cstate);
/* configure mocks */
expect_value(rpma_conn_new, id, &cstate->id);
will_return(rpma_conn_new, MOCK_CONN);
expect_value(rdma_connect, id, &cstate->id);
will_return(rdma_connect, EAGAIN);
expect_value(rpma_conn_delete, conn, MOCK_CONN);
will_return(rpma_conn_delete, MOCK_OK);
/* run test */
struct rpma_conn *conn = NULL;
int ret = rpma_conn_req_connect(&cstate->req, NULL, &conn);
/* verify the results */
assert_int_equal(ret, RPMA_E_PROVIDER);
assert_null(cstate->req);
assert_null(conn);
}
/*
* connect_via_connect__connect_EAGAIN_subsequent_EIO -- rdma_connect()
* fails with EAGAIN whereas subsequent (ibv_destroy_cq(), rdma_destroy_id())
* fail with EIO
*/
static void
connect_via_connect__connect_EAGAIN_subsequent_EIO(void **unused)
{
/* WA for cmocka/issues#47 */
struct conn_req_new_test_state *cstate = &prestate_conn_cfg_default;
assert_int_equal(setup__conn_req_new((void **)&cstate), 0);
assert_non_null(cstate);
/* configure mocks */
expect_value(rpma_conn_new, id, &cstate->id);
will_return(rpma_conn_new, MOCK_CONN);
expect_value(rdma_connect, id, &cstate->id);
will_return(rdma_connect, EAGAIN); /* first error */
expect_value(rpma_conn_delete, conn, MOCK_CONN);
will_return(rpma_conn_delete, RPMA_E_PROVIDER);
will_return(rpma_conn_delete, EIO); /* second error */
/* run test */
struct rpma_conn *conn = NULL;
int ret = rpma_conn_req_connect(&cstate->req, NULL, &conn);
/* verify the results */
assert_int_equal(ret, RPMA_E_PROVIDER);
assert_null(cstate->req);
assert_null(conn);
}
/*
* connect_via_connect__conn_new_EAGAIN -- rpma_conn_new() fails with
* RPMA_E_PROVIDER + EAGAIN
*/
static void
connect_via_connect__conn_new_EAGAIN(void **unused)
{
/* WA for cmocka/issues#47 */
struct conn_req_new_test_state *cstate = &prestate_conn_cfg_default;
assert_int_equal(setup__conn_req_new((void **)&cstate), 0);
assert_non_null(cstate);
/* configure mocks */
expect_value(rpma_conn_new, id, &cstate->id);
will_return(rpma_conn_new, NULL);
will_return(rpma_conn_new, RPMA_E_PROVIDER);
will_return(rpma_conn_new, EAGAIN);
expect_value(rdma_destroy_qp, id, &cstate->id);
will_return(ibv_destroy_cq, MOCK_OK);
will_return(ibv_destroy_comp_channel, MOCK_OK);
expect_value(rdma_destroy_id, id, &cstate->id);
will_return(rdma_destroy_id, MOCK_OK);
/* run test */
struct rpma_conn *conn = NULL;
int ret = rpma_conn_req_connect(&cstate->req, NULL, &conn);
/* verify the results */
assert_int_equal(ret, RPMA_E_PROVIDER);
assert_null(cstate->req);
assert_null(conn);
}
/*
* connect_via_connect__conn_new_EAGAIN_subsequent_EIO --
* rpma_conn_new() fails with RPMA_E_PROVIDER + EAGAIN whereas subsequent
* (rdma_disconnect(), ibv_destroy_cq(), rdma_destroy_id()) fail with EIO
*/
static void
connect_via_connect__conn_new_EAGAIN_subsequent_EIO(void **unused)
{
/* WA for cmocka/issues#47 */
struct conn_req_new_test_state *cstate = &prestate_conn_cfg_default;
assert_int_equal(setup__conn_req_new((void **)&cstate), 0);
assert_non_null(cstate);
/* configure mocks */
expect_value(rpma_conn_new, id, &cstate->id);
will_return(rpma_conn_new, NULL);
will_return(rpma_conn_new, RPMA_E_PROVIDER);
will_return(rpma_conn_new, EAGAIN); /* first error */
expect_value(rdma_destroy_qp, id, &cstate->id);
will_return(ibv_destroy_cq, EIO); /* second error */
will_return(ibv_destroy_comp_channel, EIO); /* third error */
expect_value(rdma_destroy_id, id, &cstate->id);
will_return(rdma_destroy_id, EIO); /* fourth error */
/* run test */
struct rpma_conn *conn = NULL;
int ret = rpma_conn_req_connect(&cstate->req, NULL, &conn);
/* verify the results */
assert_int_equal(ret, RPMA_E_PROVIDER);
assert_null(cstate->req);
assert_null(conn);
}
/*
* connect_via_connect__success_outgoing -- rpma_conn_req_connect()
* success (using an outgoing connection request)
*/
static void
connect_via_connect__success_outgoing(void **unused)
{
/* WA for cmocka/issues#47 */
struct conn_req_new_test_state *cstate = &prestate_conn_cfg_default;
assert_int_equal(setup__conn_req_new((void **)&cstate), 0);
assert_non_null(cstate);
/* configure mocks */
expect_value(rdma_connect, id, &cstate->id);
will_return(rdma_connect, MOCK_OK);
expect_value(rpma_conn_new, id, &cstate->id);
will_return(rpma_conn_new, MOCK_CONN);
/* run test */
struct rpma_conn *conn = NULL;
int ret = rpma_conn_req_connect(&cstate->req, NULL, &conn);
/* verify the results */
assert_int_equal(ret, MOCK_OK);
assert_null(cstate->req);
assert_int_equal(conn, MOCK_CONN);
}
static const struct CMUnitTest test_connect[] = {
/* rpma_conn_req_connect() unit tests */
cmocka_unit_test(connect__req_ptr_NULL),
cmocka_unit_test_setup_teardown(connect__conn_ptr_NULL,
setup__conn_req_from_cm_event,
teardown__conn_req_from_cm_event),
cmocka_unit_test(connect__req_NULL),
cmocka_unit_test_setup_teardown(
connect__pdata_NULL_pdata_ptr_NULL,
setup__conn_req_from_cm_event,
teardown__conn_req_from_cm_event),
cmocka_unit_test_setup_teardown(
connect__pdata_NULL_pdata_len_0,
setup__conn_req_from_cm_event,
teardown__conn_req_from_cm_event),
cmocka_unit_test_setup_teardown(
connect__pdata_NULL_pdata_ptr_NULL_len_0,
setup__conn_req_from_cm_event,
teardown__conn_req_from_cm_event),
/* connect via rdma_accept() */
cmocka_unit_test(connect_via_accept__accept_EAGAIN),
cmocka_unit_test(
connect_via_accept__accept_EAGAIN_subsequent_EIO),
cmocka_unit_test(connect_via_accept__ack_EAGAIN),
cmocka_unit_test(
connect_via_accept__ack_EAGAIN_subsequent_EIO),
cmocka_unit_test(
connect_via_accept__conn_new_EAGAIN),
cmocka_unit_test(
connect_via_accept__conn_new_EAGAIN_subsequent_EIO),
cmocka_unit_test(connect_via_accept__set_private_data_ENOMEM),
cmocka_unit_test(connect_via_accept__success_incoming),
/* connect via rdma_connect() */
cmocka_unit_test(connect_via_connect__connect_EAGAIN),
cmocka_unit_test(
connect_via_connect__connect_EAGAIN_subsequent_EIO),
cmocka_unit_test(connect_via_connect__conn_new_EAGAIN),
cmocka_unit_test(
connect_via_connect__conn_new_EAGAIN_subsequent_EIO),
cmocka_unit_test(connect_via_connect__success_outgoing),
cmocka_unit_test(NULL)
};
int
main(int argc, char *argv[])
{
/* prepare prestate - default conn_cfg */
prestate_init(&prestate_conn_cfg_default, MOCK_CONN_CFG_DEFAULT,
RPMA_DEFAULT_TIMEOUT_MS, MOCK_CQ_SIZE_DEFAULT);
return cmocka_run_group_tests(test_connect, group_setup_conn_req, NULL);
}
|
425819.c | /*
* Chronomaster DFA Format Demuxer
* Copyright (c) 2011 Konstantin Shishkov
*
* This file is part of FFmpeg.
*
* FFmpeg is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* FFmpeg is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with FFmpeg; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <inttypes.h>
#include "libavutil/intreadwrite.h"
#include "avformat.h"
#include "internal.h"
static int dfa_probe(AVProbeData *p)
{
if (p->buf_size < 4 || AV_RL32(p->buf) != MKTAG('D', 'F', 'I', 'A'))
return 0;
if (AV_RL32(p->buf + 16) != 0x80)
return AVPROBE_SCORE_MAX / 4;
return AVPROBE_SCORE_MAX;
}
static int dfa_read_header(AVFormatContext *s)
{
AVIOContext *pb = s->pb;
AVStream *st;
int frames;
int version;
uint32_t mspf;
if (avio_rl32(pb) != MKTAG('D', 'F', 'I', 'A')) {
av_log(s, AV_LOG_ERROR, "Invalid magic for DFA\n");
return AVERROR_INVALIDDATA;
}
version = avio_rl16(pb);
frames = avio_rl16(pb);
st = avformat_new_stream(s, NULL);
if (!st)
return AVERROR(ENOMEM);
st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
st->codec->codec_id = AV_CODEC_ID_DFA;
st->codec->width = avio_rl16(pb);
st->codec->height = avio_rl16(pb);
mspf = avio_rl32(pb);
if (!mspf) {
av_log(s, AV_LOG_WARNING, "Zero FPS reported, defaulting to 10\n");
mspf = 100;
}
avpriv_set_pts_info(st, 24, mspf, 1000);
avio_skip(pb, 128 - 16); // padding
st->duration = frames;
if (ff_alloc_extradata(st->codec, 2))
return AVERROR(ENOMEM);
AV_WL16(st->codec->extradata, version);
if (version == 0x100)
st->sample_aspect_ratio = (AVRational){2, 1};
return 0;
}
static int dfa_read_packet(AVFormatContext *s, AVPacket *pkt)
{
AVIOContext *pb = s->pb;
uint32_t frame_size;
int ret, first = 1;
if (pb->eof_reached)
return AVERROR_EOF;
if (av_get_packet(pb, pkt, 12) != 12)
return AVERROR(EIO);
while (!pb->eof_reached) {
if (!first) {
ret = av_append_packet(pb, pkt, 12);
if (ret < 0) {
av_free_packet(pkt);
return ret;
}
} else
first = 0;
frame_size = AV_RL32(pkt->data + pkt->size - 8);
if (frame_size > INT_MAX - 4) {
av_log(s, AV_LOG_ERROR, "Too large chunk size: %"PRIu32"\n", frame_size);
return AVERROR(EIO);
}
if (AV_RL32(pkt->data + pkt->size - 12) == MKTAG('E', 'O', 'F', 'R')) {
if (frame_size) {
av_log(s, AV_LOG_WARNING,
"skipping %"PRIu32" bytes of end-of-frame marker chunk\n",
frame_size);
avio_skip(pb, frame_size);
}
return 0;
}
ret = av_append_packet(pb, pkt, frame_size);
if (ret < 0) {
av_free_packet(pkt);
return ret;
}
}
return 0;
}
AVInputFormat ff_dfa_demuxer = {
.name = "dfa",
.long_name = NULL_IF_CONFIG_SMALL("Chronomaster DFA"),
.read_probe = dfa_probe,
.read_header = dfa_read_header,
.read_packet = dfa_read_packet,
.flags = AVFMT_GENERIC_INDEX,
};
|
204821.c | #include "sms_fm_apu.h"
#include "blargg_source.h"
void Fm_apu_create( struct Sms_Fm_Apu* this )
{
Synth_init( &this->synth );
Ym2413_init( &this->apu );
}
blargg_err_t Fm_apu_init( struct Sms_Fm_Apu* this, int clock_rate, int sample_rate )
{
this->period_ = (blip_time_t) (clock_rate / sample_rate);
CHECK_ALLOC( !Ym2413_set_rate( &this->apu, sample_rate, clock_rate ) );
Fm_apu_set_output( this, 0 );
Fm_apu_volume( this, (int)FP_ONE_VOLUME );
Fm_apu_reset( this );
return 0;
}
void Fm_apu_reset( struct Sms_Fm_Apu* this )
{
this->addr = 0;
this->next_time = 0;
this->last_amp = 0;
Ym2413_reset( &this->apu );
}
void fm_run_until( struct Sms_Fm_Apu* this, blip_time_t end_time );
void Fm_apu_write_data( struct Sms_Fm_Apu* this, blip_time_t time, int data )
{
if ( time > this->next_time )
fm_run_until( this, time );
Ym2413_write( &this->apu, this->addr, data );
}
void fm_run_until( struct Sms_Fm_Apu* this, blip_time_t end_time )
{
assert( end_time > this->next_time );
struct Blip_Buffer* const output = this->output_;
if ( !output )
{
this->next_time = end_time;
return;
}
blip_time_t time = this->next_time;
struct Ym2413_Emu* emu = &this->apu;
do
{
short samples [2];
Ym2413_run( emu, 1, samples );
int amp = (samples [0] + samples [1]) >> 1;
int delta = amp - this->last_amp;
if ( delta )
{
this->last_amp = amp;
Synth_offset_inline( &this->synth, time, delta, output );
}
time += this->period_;
}
while ( time < end_time );
this->next_time = time;
}
void Fm_apu_end_frame( struct Sms_Fm_Apu* this, blip_time_t time )
{
if ( time > this->next_time )
fm_run_until( this, time );
this->next_time -= time;
assert( this->next_time >= 0 );
if ( this->output_ )
Blip_set_modified( this->output_ );
}
|
831310.c | /*
** FOLD: Constant Folding, Algebraic Simplifications and Reassociation.
** ABCelim: Array Bounds Check Elimination.
** CSE: Common-Subexpression Elimination.
** Copyright (C) 2005-2016 Mike Pall. See Copyright Notice in luajit.h
*/
#define lj_opt_fold_c
#define LUA_CORE
#include <math.h>
#include "lj_obj.h"
#if LJ_HASJIT
#include "lj_buf.h"
#include "lj_str.h"
#include "lj_tab.h"
#include "lj_ir.h"
#include "lj_jit.h"
#include "lj_ircall.h"
#include "lj_iropt.h"
#include "lj_trace.h"
#if LJ_HASFFI
#include "lj_ctype.h"
#include "lj_carith.h"
#endif
#include "lj_vm.h"
#include "lj_strscan.h"
#include "lj_strfmt.h"
/* Here's a short description how the FOLD engine processes instructions:
**
** The FOLD engine receives a single instruction stored in fins (J->fold.ins).
** The instruction and its operands are used to select matching fold rules.
** These are applied iteratively until a fixed point is reached.
**
** The 8 bit opcode of the instruction itself plus the opcodes of the
** two instructions referenced by its operands form a 24 bit key
** 'ins left right' (unused operands -> 0, literals -> lowest 8 bits).
**
** This key is used for partial matching against the fold rules. The
** left/right operand fields of the key are successively masked with
** the 'any' wildcard, from most specific to least specific:
**
** ins left right
** ins any right
** ins left any
** ins any any
**
** The masked key is used to lookup a matching fold rule in a semi-perfect
** hash table. If a matching rule is found, the related fold function is run.
** Multiple rules can share the same fold function. A fold rule may return
** one of several special values:
**
** - NEXTFOLD means no folding was applied, because an additional test
** inside the fold function failed. Matching continues against less
** specific fold rules. Finally the instruction is passed on to CSE.
**
** - RETRYFOLD means the instruction was modified in-place. Folding is
** retried as if this instruction had just been received.
**
** All other return values are terminal actions -- no further folding is
** applied:
**
** - INTFOLD(i) returns a reference to the integer constant i.
**
** - LEFTFOLD and RIGHTFOLD return the left/right operand reference
** without emitting an instruction.
**
** - CSEFOLD and EMITFOLD pass the instruction directly to CSE or emit
** it without passing through any further optimizations.
**
** - FAILFOLD, DROPFOLD and CONDFOLD only apply to instructions which have
** no result (e.g. guarded assertions): FAILFOLD means the guard would
** always fail, i.e. the current trace is pointless. DROPFOLD means
** the guard is always true and has been eliminated. CONDFOLD is a
** shortcut for FAILFOLD + cond (i.e. drop if true, otherwise fail).
**
** - Any other return value is interpreted as an IRRef or TRef. This
** can be a reference to an existing or a newly created instruction.
** Only the least-significant 16 bits (IRRef1) are used to form a TRef
** which is finally returned to the caller.
**
** The FOLD engine receives instructions both from the trace recorder and
** substituted instructions from LOOP unrolling. This means all types
** of instructions may end up here, even though the recorder bypasses
** FOLD in some cases. Thus all loads, stores and allocations must have
** an any/any rule to avoid being passed on to CSE.
**
** Carefully read the following requirements before adding or modifying
** any fold rules:
**
** Requirement #1: All fold rules must preserve their destination type.
**
** Consistently use INTFOLD() (KINT result) or lj_ir_knum() (KNUM result).
** Never use lj_ir_knumint() which can have either a KINT or KNUM result.
**
** Requirement #2: Fold rules should not create *new* instructions which
** reference operands *across* PHIs.
**
** E.g. a RETRYFOLD with 'fins->op1 = fleft->op1' is invalid if the
** left operand is a PHI. Then fleft->op1 would point across the PHI
** frontier to an invariant instruction. Adding a PHI for this instruction
** would be counterproductive. The solution is to add a barrier which
** prevents folding across PHIs, i.e. 'PHIBARRIER(fleft)' in this case.
** The only exception is for recurrences with high latencies like
** repeated int->num->int conversions.
**
** One could relax this condition a bit if the referenced instruction is
** a PHI, too. But this often leads to worse code due to excessive
** register shuffling.
**
** Note: returning *existing* instructions (e.g. LEFTFOLD) is ok, though.
** Even returning fleft->op1 would be ok, because a new PHI will added,
** if needed. But again, this leads to excessive register shuffling and
** should be avoided.
**
** Requirement #3: The set of all fold rules must be monotonic to guarantee
** termination.
**
** The goal is optimization, so one primarily wants to add strength-reducing
** rules. This means eliminating an instruction or replacing an instruction
** with one or more simpler instructions. Don't add fold rules which point
** into the other direction.
**
** Some rules (like commutativity) do not directly reduce the strength of
** an instruction, but enable other fold rules (e.g. by moving constants
** to the right operand). These rules must be made unidirectional to avoid
** cycles.
**
** Rule of thumb: the trace recorder expands the IR and FOLD shrinks it.
*/
/* Some local macros to save typing. Undef'd at the end. */
#define IR(ref) (&J->cur.ir[(ref)])
#define fins (&J->fold.ins)
#define fleft (&J->fold.left)
#define fright (&J->fold.right)
#define knumleft (ir_knum(fleft)->n)
#define knumright (ir_knum(fright)->n)
/* Pass IR on to next optimization in chain (FOLD). */
#define emitir(ot, a, b) (lj_ir_set(J, (ot), (a), (b)), lj_opt_fold(J))
/* Fold function type. Fastcall on x86 significantly reduces their size. */
typedef IRRef (LJ_FASTCALL *FoldFunc)(jit_State *J);
/* Macros for the fold specs, so buildvm can recognize them. */
#define LJFOLD(x)
#define LJFOLDX(x)
#define LJFOLDF(name) static TRef LJ_FASTCALL fold_##name(jit_State *J)
/* Note: They must be at the start of a line or buildvm ignores them! */
/* Barrier to prevent using operands across PHIs. */
#define PHIBARRIER(ir) if (irt_isphi((ir)->t)) return NEXTFOLD
/* Barrier to prevent folding across a GC step.
** GC steps can only happen at the head of a trace and at LOOP.
** And the GC is only driven forward if there's at least one allocation.
*/
#define gcstep_barrier(J, ref) \
((ref) < J->chain[IR_LOOP] && \
(J->chain[IR_SNEW] || J->chain[IR_XSNEW] || \
J->chain[IR_TNEW] || J->chain[IR_TDUP] || \
J->chain[IR_CNEW] || J->chain[IR_CNEWI] || \
J->chain[IR_BUFSTR] || J->chain[IR_TOSTR] || J->chain[IR_CALLA]))
/* -- Constant folding for FP numbers ------------------------------------- */
LJFOLD(ADD KNUM KNUM)
LJFOLD(SUB KNUM KNUM)
LJFOLD(MUL KNUM KNUM)
LJFOLD(DIV KNUM KNUM)
LJFOLD(NEG KNUM KNUM)
LJFOLD(ABS KNUM KNUM)
LJFOLD(ATAN2 KNUM KNUM)
LJFOLD(LDEXP KNUM KNUM)
LJFOLD(MIN KNUM KNUM)
LJFOLD(MAX KNUM KNUM)
LJFOLDF(kfold_numarith)
{
lua_Number a = knumleft;
lua_Number b = knumright;
lua_Number y = lj_vm_foldarith(a, b, fins->o - IR_ADD);
return lj_ir_knum(J, y);
}
LJFOLD(LDEXP KNUM KINT)
LJFOLDF(kfold_ldexp)
{
#if LJ_TARGET_X86ORX64
UNUSED(J);
return NEXTFOLD;
#else
return lj_ir_knum(J, ldexp(knumleft, fright->i));
#endif
}
LJFOLD(FPMATH KNUM any)
LJFOLDF(kfold_fpmath)
{
lua_Number a = knumleft;
lua_Number y = lj_vm_foldfpm(a, fins->op2);
return lj_ir_knum(J, y);
}
LJFOLD(POW KNUM KINT)
LJFOLDF(kfold_numpow)
{
lua_Number a = knumleft;
lua_Number b = (lua_Number)fright->i;
lua_Number y = lj_vm_foldarith(a, b, IR_POW - IR_ADD);
return lj_ir_knum(J, y);
}
/* Must not use kfold_kref for numbers (could be NaN). */
LJFOLD(EQ KNUM KNUM)
LJFOLD(NE KNUM KNUM)
LJFOLD(LT KNUM KNUM)
LJFOLD(GE KNUM KNUM)
LJFOLD(LE KNUM KNUM)
LJFOLD(GT KNUM KNUM)
LJFOLD(ULT KNUM KNUM)
LJFOLD(UGE KNUM KNUM)
LJFOLD(ULE KNUM KNUM)
LJFOLD(UGT KNUM KNUM)
LJFOLDF(kfold_numcomp)
{
return CONDFOLD(lj_ir_numcmp(knumleft, knumright, (IROp)fins->o));
}
/* -- Constant folding for 32 bit integers -------------------------------- */
static int32_t kfold_intop(int32_t k1, int32_t k2, IROp op)
{
switch (op) {
case IR_ADD: k1 += k2; break;
case IR_SUB: k1 -= k2; break;
case IR_MUL: k1 *= k2; break;
case IR_MOD: k1 = lj_vm_modi(k1, k2); break;
case IR_NEG: k1 = -k1; break;
case IR_BAND: k1 &= k2; break;
case IR_BOR: k1 |= k2; break;
case IR_BXOR: k1 ^= k2; break;
case IR_BSHL: k1 <<= (k2 & 31); break;
case IR_BSHR: k1 = (int32_t)((uint32_t)k1 >> (k2 & 31)); break;
case IR_BSAR: k1 >>= (k2 & 31); break;
case IR_BROL: k1 = (int32_t)lj_rol((uint32_t)k1, (k2 & 31)); break;
case IR_BROR: k1 = (int32_t)lj_ror((uint32_t)k1, (k2 & 31)); break;
case IR_MIN: k1 = k1 < k2 ? k1 : k2; break;
case IR_MAX: k1 = k1 > k2 ? k1 : k2; break;
default: lua_assert(0); break;
}
return k1;
}
LJFOLD(ADD KINT KINT)
LJFOLD(SUB KINT KINT)
LJFOLD(MUL KINT KINT)
LJFOLD(MOD KINT KINT)
LJFOLD(NEG KINT KINT)
LJFOLD(BAND KINT KINT)
LJFOLD(BOR KINT KINT)
LJFOLD(BXOR KINT KINT)
LJFOLD(BSHL KINT KINT)
LJFOLD(BSHR KINT KINT)
LJFOLD(BSAR KINT KINT)
LJFOLD(BROL KINT KINT)
LJFOLD(BROR KINT KINT)
LJFOLD(MIN KINT KINT)
LJFOLD(MAX KINT KINT)
LJFOLDF(kfold_intarith)
{
return INTFOLD(kfold_intop(fleft->i, fright->i, (IROp)fins->o));
}
LJFOLD(ADDOV KINT KINT)
LJFOLD(SUBOV KINT KINT)
LJFOLD(MULOV KINT KINT)
LJFOLDF(kfold_intovarith)
{
lua_Number n = lj_vm_foldarith((lua_Number)fleft->i, (lua_Number)fright->i,
fins->o - IR_ADDOV);
int32_t k = lj_num2int(n);
if (n != (lua_Number)k)
return FAILFOLD;
return INTFOLD(k);
}
LJFOLD(BNOT KINT)
LJFOLDF(kfold_bnot)
{
return INTFOLD(~fleft->i);
}
LJFOLD(BSWAP KINT)
LJFOLDF(kfold_bswap)
{
return INTFOLD((int32_t)lj_bswap((uint32_t)fleft->i));
}
LJFOLD(LT KINT KINT)
LJFOLD(GE KINT KINT)
LJFOLD(LE KINT KINT)
LJFOLD(GT KINT KINT)
LJFOLD(ULT KINT KINT)
LJFOLD(UGE KINT KINT)
LJFOLD(ULE KINT KINT)
LJFOLD(UGT KINT KINT)
LJFOLD(ABC KINT KINT)
LJFOLDF(kfold_intcomp)
{
int32_t a = fleft->i, b = fright->i;
switch ((IROp)fins->o) {
case IR_LT: return CONDFOLD(a < b);
case IR_GE: return CONDFOLD(a >= b);
case IR_LE: return CONDFOLD(a <= b);
case IR_GT: return CONDFOLD(a > b);
case IR_ULT: return CONDFOLD((uint32_t)a < (uint32_t)b);
case IR_UGE: return CONDFOLD((uint32_t)a >= (uint32_t)b);
case IR_ULE: return CONDFOLD((uint32_t)a <= (uint32_t)b);
case IR_ABC:
case IR_UGT: return CONDFOLD((uint32_t)a > (uint32_t)b);
default: lua_assert(0); return FAILFOLD;
}
}
LJFOLD(UGE any KINT)
LJFOLDF(kfold_intcomp0)
{
if (fright->i == 0)
return DROPFOLD;
return NEXTFOLD;
}
/* -- Constant folding for 64 bit integers -------------------------------- */
static uint64_t kfold_int64arith(uint64_t k1, uint64_t k2, IROp op)
{
switch (op) {
#if LJ_HASFFI
case IR_ADD: k1 += k2; break;
case IR_SUB: k1 -= k2; break;
case IR_MUL: k1 *= k2; break;
case IR_BAND: k1 &= k2; break;
case IR_BOR: k1 |= k2; break;
case IR_BXOR: k1 ^= k2; break;
#endif
default: UNUSED(k2); lua_assert(0); break;
}
return k1;
}
LJFOLD(ADD KINT64 KINT64)
LJFOLD(SUB KINT64 KINT64)
LJFOLD(MUL KINT64 KINT64)
LJFOLD(BAND KINT64 KINT64)
LJFOLD(BOR KINT64 KINT64)
LJFOLD(BXOR KINT64 KINT64)
LJFOLDF(kfold_int64arith)
{
return INT64FOLD(kfold_int64arith(ir_k64(fleft)->u64,
ir_k64(fright)->u64, (IROp)fins->o));
}
LJFOLD(DIV KINT64 KINT64)
LJFOLD(MOD KINT64 KINT64)
LJFOLD(POW KINT64 KINT64)
LJFOLDF(kfold_int64arith2)
{
#if LJ_HASFFI
uint64_t k1 = ir_k64(fleft)->u64, k2 = ir_k64(fright)->u64;
if (irt_isi64(fins->t)) {
k1 = fins->o == IR_DIV ? lj_carith_divi64((int64_t)k1, (int64_t)k2) :
fins->o == IR_MOD ? lj_carith_modi64((int64_t)k1, (int64_t)k2) :
lj_carith_powi64((int64_t)k1, (int64_t)k2);
} else {
k1 = fins->o == IR_DIV ? lj_carith_divu64(k1, k2) :
fins->o == IR_MOD ? lj_carith_modu64(k1, k2) :
lj_carith_powu64(k1, k2);
}
return INT64FOLD(k1);
#else
UNUSED(J); lua_assert(0); return FAILFOLD;
#endif
}
LJFOLD(BSHL KINT64 KINT)
LJFOLD(BSHR KINT64 KINT)
LJFOLD(BSAR KINT64 KINT)
LJFOLD(BROL KINT64 KINT)
LJFOLD(BROR KINT64 KINT)
LJFOLDF(kfold_int64shift)
{
#if LJ_HASFFI
uint64_t k = ir_k64(fleft)->u64;
int32_t sh = (fright->i & 63);
return INT64FOLD(lj_carith_shift64(k, sh, fins->o - IR_BSHL));
#else
UNUSED(J); lua_assert(0); return FAILFOLD;
#endif
}
LJFOLD(BNOT KINT64)
LJFOLDF(kfold_bnot64)
{
#if LJ_HASFFI
return INT64FOLD(~ir_k64(fleft)->u64);
#else
UNUSED(J); lua_assert(0); return FAILFOLD;
#endif
}
LJFOLD(BSWAP KINT64)
LJFOLDF(kfold_bswap64)
{
#if LJ_HASFFI
return INT64FOLD(lj_bswap64(ir_k64(fleft)->u64));
#else
UNUSED(J); lua_assert(0); return FAILFOLD;
#endif
}
LJFOLD(LT KINT64 KINT64)
LJFOLD(GE KINT64 KINT64)
LJFOLD(LE KINT64 KINT64)
LJFOLD(GT KINT64 KINT64)
LJFOLD(ULT KINT64 KINT64)
LJFOLD(UGE KINT64 KINT64)
LJFOLD(ULE KINT64 KINT64)
LJFOLD(UGT KINT64 KINT64)
LJFOLDF(kfold_int64comp)
{
#if LJ_HASFFI
uint64_t a = ir_k64(fleft)->u64, b = ir_k64(fright)->u64;
switch ((IROp)fins->o) {
case IR_LT: return CONDFOLD(a < b);
case IR_GE: return CONDFOLD(a >= b);
case IR_LE: return CONDFOLD(a <= b);
case IR_GT: return CONDFOLD(a > b);
case IR_ULT: return CONDFOLD((uint64_t)a < (uint64_t)b);
case IR_UGE: return CONDFOLD((uint64_t)a >= (uint64_t)b);
case IR_ULE: return CONDFOLD((uint64_t)a <= (uint64_t)b);
case IR_UGT: return CONDFOLD((uint64_t)a > (uint64_t)b);
default: lua_assert(0); return FAILFOLD;
}
#else
UNUSED(J); lua_assert(0); return FAILFOLD;
#endif
}
LJFOLD(UGE any KINT64)
LJFOLDF(kfold_int64comp0)
{
#if LJ_HASFFI
if (ir_k64(fright)->u64 == 0)
return DROPFOLD;
return NEXTFOLD;
#else
UNUSED(J); lua_assert(0); return FAILFOLD;
#endif
}
/* -- Constant folding for strings ---------------------------------------- */
LJFOLD(SNEW KKPTR KINT)
LJFOLDF(kfold_snew_kptr)
{
GCstr *s = lj_str_new(J->L, (const char *)ir_kptr(fleft), (size_t)fright->i);
return lj_ir_kstr(J, s);
}
LJFOLD(SNEW any KINT)
LJFOLDF(kfold_snew_empty)
{
if (fright->i == 0)
return lj_ir_kstr(J, &J2G(J)->strempty);
return NEXTFOLD;
}
LJFOLD(STRREF KGC KINT)
LJFOLDF(kfold_strref)
{
GCstr *str = ir_kstr(fleft);
lua_assert((MSize)fright->i <= str->len);
return lj_ir_kkptr(J, (char *)strdata(str) + fright->i);
}
LJFOLD(STRREF SNEW any)
LJFOLDF(kfold_strref_snew)
{
PHIBARRIER(fleft);
if (irref_isk(fins->op2) && fright->i == 0) {
return fleft->op1; /* strref(snew(ptr, len), 0) ==> ptr */
} else {
/* Reassociate: strref(snew(strref(str, a), len), b) ==> strref(str, a+b) */
IRIns *ir = IR(fleft->op1);
if (ir->o == IR_STRREF) {
IRRef1 str = ir->op1; /* IRIns * is not valid across emitir. */
PHIBARRIER(ir);
fins->op2 = emitir(IRTI(IR_ADD), ir->op2, fins->op2); /* Clobbers fins! */
fins->op1 = str;
fins->ot = IRT(IR_STRREF, IRT_P32);
return RETRYFOLD;
}
}
return NEXTFOLD;
}
LJFOLD(CALLN CARG IRCALL_lj_str_cmp)
LJFOLDF(kfold_strcmp)
{
if (irref_isk(fleft->op1) && irref_isk(fleft->op2)) {
GCstr *a = ir_kstr(IR(fleft->op1));
GCstr *b = ir_kstr(IR(fleft->op2));
return INTFOLD(lj_str_cmp(a, b));
}
return NEXTFOLD;
}
/* -- Constant folding and forwarding for buffers ------------------------- */
/*
** Buffer ops perform stores, but their effect is limited to the buffer
** itself. Also, buffer ops are chained: a use of an op implies a use of
** all other ops up the chain. Conversely, if an op is unused, all ops
** up the chain can go unsed. This largely eliminates the need to treat
** them as stores.
**
** Alas, treating them as normal (IRM_N) ops doesn't work, because they
** cannot be CSEd in isolation. CSE for IRM_N is implicitly done in LOOP
** or if FOLD is disabled.
**
** The compromise is to declare them as loads, emit them like stores and
** CSE whole chains manually when the BUFSTR is to be emitted. Any chain
** fragments left over from CSE are eliminated by DCE.
*/
/* BUFHDR is emitted like a store, see below. */
LJFOLD(BUFPUT BUFHDR BUFSTR)
LJFOLDF(bufput_append)
{
/* New buffer, no other buffer op inbetween and same buffer? */
if ((J->flags & JIT_F_OPT_FWD) &&
!(fleft->op2 & IRBUFHDR_APPEND) &&
fleft->prev == fright->op2 &&
fleft->op1 == IR(fright->op2)->op1) {
IRRef ref = fins->op1;
IR(ref)->op2 = (fleft->op2 | IRBUFHDR_APPEND); /* Modify BUFHDR. */
IR(ref)->op1 = fright->op1;
return ref;
}
return EMITFOLD; /* Always emit, CSE later. */
}
LJFOLD(BUFPUT any any)
LJFOLDF(bufput_kgc)
{
if (LJ_LIKELY(J->flags & JIT_F_OPT_FOLD) && fright->o == IR_KGC) {
GCstr *s2 = ir_kstr(fright);
if (s2->len == 0) { /* Empty string? */
return LEFTFOLD;
} else {
if (fleft->o == IR_BUFPUT && irref_isk(fleft->op2) &&
!irt_isphi(fleft->t)) { /* Join two constant string puts in a row. */
GCstr *s1 = ir_kstr(IR(fleft->op2));
IRRef kref = lj_ir_kstr(J, lj_buf_cat2str(J->L, s1, s2));
/* lj_ir_kstr() may realloc the IR and invalidates any IRIns *. */
IR(fins->op1)->op2 = kref; /* Modify previous BUFPUT. */
return fins->op1;
}
}
}
return EMITFOLD; /* Always emit, CSE later. */
}
LJFOLD(BUFSTR any any)
LJFOLDF(bufstr_kfold_cse)
{
lua_assert(fleft->o == IR_BUFHDR || fleft->o == IR_BUFPUT ||
fleft->o == IR_CALLL);
if (LJ_LIKELY(J->flags & JIT_F_OPT_FOLD)) {
if (fleft->o == IR_BUFHDR) { /* No put operations? */
if (!(fleft->op2 & IRBUFHDR_APPEND)) /* Empty buffer? */
return lj_ir_kstr(J, &J2G(J)->strempty);
fins->op1 = fleft->op1;
fins->op2 = fleft->prev; /* Relies on checks in bufput_append. */
return CSEFOLD;
} else if (fleft->o == IR_BUFPUT) {
IRIns *irb = IR(fleft->op1);
if (irb->o == IR_BUFHDR && !(irb->op2 & IRBUFHDR_APPEND))
return fleft->op2; /* Shortcut for a single put operation. */
}
}
/* Try to CSE the whole chain. */
if (LJ_LIKELY(J->flags & JIT_F_OPT_CSE)) {
IRRef ref = J->chain[IR_BUFSTR];
while (ref) {
IRIns *irs = IR(ref), *ira = fleft, *irb = IR(irs->op1);
while (ira->o == irb->o && ira->op2 == irb->op2) {
lua_assert(ira->o == IR_BUFHDR || ira->o == IR_BUFPUT ||
ira->o == IR_CALLL || ira->o == IR_CARG);
if (ira->o == IR_BUFHDR && !(ira->op2 & IRBUFHDR_APPEND))
return ref; /* CSE succeeded. */
if (ira->o == IR_CALLL && ira->op2 == IRCALL_lj_buf_puttab)
break;
ira = IR(ira->op1);
irb = IR(irb->op1);
}
ref = irs->prev;
}
}
return EMITFOLD; /* No CSE possible. */
}
LJFOLD(CALLL CARG IRCALL_lj_buf_putstr_reverse)
LJFOLD(CALLL CARG IRCALL_lj_buf_putstr_upper)
LJFOLD(CALLL CARG IRCALL_lj_buf_putstr_lower)
LJFOLD(CALLL CARG IRCALL_lj_strfmt_putquoted)
LJFOLDF(bufput_kfold_op)
{
if (irref_isk(fleft->op2)) {
const CCallInfo *ci = &lj_ir_callinfo[fins->op2];
SBuf *sb = lj_buf_tmp_(J->L);
sb = ((SBuf * (LJ_FASTCALL *)(SBuf *, GCstr *))ci->func)(sb,
ir_kstr(IR(fleft->op2)));
fins->o = IR_BUFPUT;
fins->op1 = fleft->op1;
fins->op2 = lj_ir_kstr(J, lj_buf_tostr(sb));
return RETRYFOLD;
}
return EMITFOLD; /* Always emit, CSE later. */
}
LJFOLD(CALLL CARG IRCALL_lj_buf_putstr_rep)
LJFOLDF(bufput_kfold_rep)
{
if (irref_isk(fleft->op2)) {
IRIns *irc = IR(fleft->op1);
if (irref_isk(irc->op2)) {
SBuf *sb = lj_buf_tmp_(J->L);
sb = lj_buf_putstr_rep(sb, ir_kstr(IR(irc->op2)), IR(fleft->op2)->i);
fins->o = IR_BUFPUT;
fins->op1 = irc->op1;
fins->op2 = lj_ir_kstr(J, lj_buf_tostr(sb));
return RETRYFOLD;
}
}
return EMITFOLD; /* Always emit, CSE later. */
}
LJFOLD(CALLL CARG IRCALL_lj_strfmt_putfxint)
LJFOLD(CALLL CARG IRCALL_lj_strfmt_putfnum_int)
LJFOLD(CALLL CARG IRCALL_lj_strfmt_putfnum_uint)
LJFOLD(CALLL CARG IRCALL_lj_strfmt_putfnum)
LJFOLD(CALLL CARG IRCALL_lj_strfmt_putfstr)
LJFOLD(CALLL CARG IRCALL_lj_strfmt_putfchar)
LJFOLDF(bufput_kfold_fmt)
{
IRIns *irc = IR(fleft->op1);
lua_assert(irref_isk(irc->op2)); /* SFormat must be const. */
if (irref_isk(fleft->op2)) {
SFormat sf = (SFormat)IR(irc->op2)->i;
IRIns *ira = IR(fleft->op2);
SBuf *sb = lj_buf_tmp_(J->L);
switch (fins->op2) {
case IRCALL_lj_strfmt_putfxint:
sb = lj_strfmt_putfxint(sb, sf, ir_k64(ira)->u64);
break;
case IRCALL_lj_strfmt_putfstr:
sb = lj_strfmt_putfstr(sb, sf, ir_kstr(ira));
break;
case IRCALL_lj_strfmt_putfchar:
sb = lj_strfmt_putfchar(sb, sf, ira->i);
break;
case IRCALL_lj_strfmt_putfnum_int:
case IRCALL_lj_strfmt_putfnum_uint:
case IRCALL_lj_strfmt_putfnum:
default: {
const CCallInfo *ci = &lj_ir_callinfo[fins->op2];
sb = ((SBuf * (*)(SBuf *, SFormat, lua_Number))ci->func)(sb, sf,
ir_knum(ira)->n);
break;
}
}
fins->o = IR_BUFPUT;
fins->op1 = irc->op1;
fins->op2 = lj_ir_kstr(J, lj_buf_tostr(sb));
return RETRYFOLD;
}
return EMITFOLD; /* Always emit, CSE later. */
}
/* -- Constant folding of pointer arithmetic ------------------------------ */
LJFOLD(ADD KGC KINT)
LJFOLD(ADD KGC KINT64)
LJFOLDF(kfold_add_kgc)
{
GCobj *o = ir_kgc(fleft);
#if LJ_64
ptrdiff_t ofs = (ptrdiff_t)ir_kint64(fright)->u64;
#else
ptrdiff_t ofs = fright->i;
#endif
#if LJ_HASFFI
if (irt_iscdata(fleft->t)) {
CType *ct = ctype_raw(ctype_ctsG(J2G(J)), gco2cd(o)->ctypeid);
if (ctype_isnum(ct->info) || ctype_isenum(ct->info) ||
ctype_isptr(ct->info) || ctype_isfunc(ct->info) ||
ctype_iscomplex(ct->info) || ctype_isvector(ct->info))
return lj_ir_kkptr(J, (char *)o + ofs);
}
#endif
return lj_ir_kptr(J, (char *)o + ofs);
}
LJFOLD(ADD KPTR KINT)
LJFOLD(ADD KPTR KINT64)
LJFOLD(ADD KKPTR KINT)
LJFOLD(ADD KKPTR KINT64)
LJFOLDF(kfold_add_kptr)
{
void *p = ir_kptr(fleft);
#if LJ_64
ptrdiff_t ofs = (ptrdiff_t)ir_kint64(fright)->u64;
#else
ptrdiff_t ofs = fright->i;
#endif
return lj_ir_kptr_(J, fleft->o, (char *)p + ofs);
}
LJFOLD(ADD any KGC)
LJFOLD(ADD any KPTR)
LJFOLD(ADD any KKPTR)
LJFOLDF(kfold_add_kright)
{
if (fleft->o == IR_KINT || fleft->o == IR_KINT64) {
IRRef1 tmp = fins->op1; fins->op1 = fins->op2; fins->op2 = tmp;
return RETRYFOLD;
}
return NEXTFOLD;
}
/* -- Constant folding of conversions ------------------------------------- */
LJFOLD(TOBIT KNUM KNUM)
LJFOLDF(kfold_tobit)
{
return INTFOLD(lj_num2bit(knumleft));
}
LJFOLD(CONV KINT IRCONV_NUM_INT)
LJFOLDF(kfold_conv_kint_num)
{
return lj_ir_knum(J, (lua_Number)fleft->i);
}
LJFOLD(CONV KINT IRCONV_NUM_U32)
LJFOLDF(kfold_conv_kintu32_num)
{
return lj_ir_knum(J, (lua_Number)(uint32_t)fleft->i);
}
LJFOLD(CONV KINT IRCONV_INT_I8)
LJFOLD(CONV KINT IRCONV_INT_U8)
LJFOLD(CONV KINT IRCONV_INT_I16)
LJFOLD(CONV KINT IRCONV_INT_U16)
LJFOLDF(kfold_conv_kint_ext)
{
int32_t k = fleft->i;
if ((fins->op2 & IRCONV_SRCMASK) == IRT_I8) k = (int8_t)k;
else if ((fins->op2 & IRCONV_SRCMASK) == IRT_U8) k = (uint8_t)k;
else if ((fins->op2 & IRCONV_SRCMASK) == IRT_I16) k = (int16_t)k;
else k = (uint16_t)k;
return INTFOLD(k);
}
LJFOLD(CONV KINT IRCONV_I64_INT)
LJFOLD(CONV KINT IRCONV_U64_INT)
LJFOLD(CONV KINT IRCONV_I64_U32)
LJFOLD(CONV KINT IRCONV_U64_U32)
LJFOLDF(kfold_conv_kint_i64)
{
if ((fins->op2 & IRCONV_SEXT))
return INT64FOLD((uint64_t)(int64_t)fleft->i);
else
return INT64FOLD((uint64_t)(int64_t)(uint32_t)fleft->i);
}
LJFOLD(CONV KINT64 IRCONV_NUM_I64)
LJFOLDF(kfold_conv_kint64_num_i64)
{
return lj_ir_knum(J, (lua_Number)(int64_t)ir_kint64(fleft)->u64);
}
LJFOLD(CONV KINT64 IRCONV_NUM_U64)
LJFOLDF(kfold_conv_kint64_num_u64)
{
return lj_ir_knum(J, (lua_Number)ir_kint64(fleft)->u64);
}
LJFOLD(CONV KINT64 IRCONV_INT_I64)
LJFOLD(CONV KINT64 IRCONV_U32_I64)
LJFOLDF(kfold_conv_kint64_int_i64)
{
return INTFOLD((int32_t)ir_kint64(fleft)->u64);
}
LJFOLD(CONV KNUM IRCONV_INT_NUM)
LJFOLDF(kfold_conv_knum_int_num)
{
lua_Number n = knumleft;
int32_t k = lj_num2int(n);
if (irt_isguard(fins->t) && n != (lua_Number)k) {
/* We're about to create a guard which always fails, like CONV +1.5.
** Some pathological loops cause this during LICM, e.g.:
** local x,k,t = 0,1.5,{1,[1.5]=2}
** for i=1,200 do x = x+ t[k]; k = k == 1 and 1.5 or 1 end
** assert(x == 300)
*/
return FAILFOLD;
}
return INTFOLD(k);
}
LJFOLD(CONV KNUM IRCONV_U32_NUM)
LJFOLDF(kfold_conv_knum_u32_num)
{
#ifdef _MSC_VER
{ /* Workaround for MSVC bug. */
volatile uint32_t u = (uint32_t)knumleft;
return INTFOLD((int32_t)u);
}
#else
return INTFOLD((int32_t)(uint32_t)knumleft);
#endif
}
LJFOLD(CONV KNUM IRCONV_I64_NUM)
LJFOLDF(kfold_conv_knum_i64_num)
{
return INT64FOLD((uint64_t)(int64_t)knumleft);
}
LJFOLD(CONV KNUM IRCONV_U64_NUM)
LJFOLDF(kfold_conv_knum_u64_num)
{
return INT64FOLD(lj_num2u64(knumleft));
}
LJFOLD(TOSTR KNUM any)
LJFOLDF(kfold_tostr_knum)
{
return lj_ir_kstr(J, lj_strfmt_num(J->L, ir_knum(fleft)));
}
LJFOLD(TOSTR KINT any)
LJFOLDF(kfold_tostr_kint)
{
return lj_ir_kstr(J, fins->op2 == IRTOSTR_INT ?
lj_strfmt_int(J->L, fleft->i) :
lj_strfmt_char(J->L, fleft->i));
}
LJFOLD(STRTO KGC)
LJFOLDF(kfold_strto)
{
TValue n;
if (lj_strscan_num(ir_kstr(fleft), &n))
return lj_ir_knum(J, numV(&n));
return FAILFOLD;
}
/* -- Constant folding of equality checks --------------------------------- */
/* Don't constant-fold away FLOAD checks against KNULL. */
LJFOLD(EQ FLOAD KNULL)
LJFOLD(NE FLOAD KNULL)
LJFOLDX(lj_opt_cse)
/* But fold all other KNULL compares, since only KNULL is equal to KNULL. */
LJFOLD(EQ any KNULL)
LJFOLD(NE any KNULL)
LJFOLD(EQ KNULL any)
LJFOLD(NE KNULL any)
LJFOLD(EQ KINT KINT) /* Constants are unique, so same refs <==> same value. */
LJFOLD(NE KINT KINT)
LJFOLD(EQ KINT64 KINT64)
LJFOLD(NE KINT64 KINT64)
LJFOLD(EQ KGC KGC)
LJFOLD(NE KGC KGC)
LJFOLDF(kfold_kref)
{
return CONDFOLD((fins->op1 == fins->op2) ^ (fins->o == IR_NE));
}
/* -- Algebraic shortcuts ------------------------------------------------- */
LJFOLD(FPMATH FPMATH IRFPM_FLOOR)
LJFOLD(FPMATH FPMATH IRFPM_CEIL)
LJFOLD(FPMATH FPMATH IRFPM_TRUNC)
LJFOLDF(shortcut_round)
{
IRFPMathOp op = (IRFPMathOp)fleft->op2;
if (op == IRFPM_FLOOR || op == IRFPM_CEIL || op == IRFPM_TRUNC)
return LEFTFOLD; /* round(round_left(x)) = round_left(x) */
return NEXTFOLD;
}
LJFOLD(ABS ABS KNUM)
LJFOLDF(shortcut_left)
{
return LEFTFOLD; /* f(g(x)) ==> g(x) */
}
LJFOLD(ABS NEG KNUM)
LJFOLDF(shortcut_dropleft)
{
PHIBARRIER(fleft);
fins->op1 = fleft->op1; /* abs(neg(x)) ==> abs(x) */
return RETRYFOLD;
}
/* Note: no safe shortcuts with STRTO and TOSTR ("1e2" ==> +100 ==> "100"). */
LJFOLD(NEG NEG any)
LJFOLD(BNOT BNOT)
LJFOLD(BSWAP BSWAP)
LJFOLDF(shortcut_leftleft)
{
PHIBARRIER(fleft); /* See above. Fold would be ok, but not beneficial. */
return fleft->op1; /* f(g(x)) ==> x */
}
/* -- FP algebraic simplifications ---------------------------------------- */
/* FP arithmetic is tricky -- there's not much to simplify.
** Please note the following common pitfalls before sending "improvements":
** x+0 ==> x is INVALID for x=-0
** 0-x ==> -x is INVALID for x=+0
** x*0 ==> 0 is INVALID for x=-0, x=+-Inf or x=NaN
*/
LJFOLD(ADD NEG any)
LJFOLDF(simplify_numadd_negx)
{
PHIBARRIER(fleft);
fins->o = IR_SUB; /* (-a) + b ==> b - a */
fins->op1 = fins->op2;
fins->op2 = fleft->op1;
return RETRYFOLD;
}
LJFOLD(ADD any NEG)
LJFOLDF(simplify_numadd_xneg)
{
PHIBARRIER(fright);
fins->o = IR_SUB; /* a + (-b) ==> a - b */
fins->op2 = fright->op1;
return RETRYFOLD;
}
LJFOLD(SUB any KNUM)
LJFOLDF(simplify_numsub_k)
{
lua_Number n = knumright;
if (n == 0.0) /* x - (+-0) ==> x */
return LEFTFOLD;
return NEXTFOLD;
}
LJFOLD(SUB NEG KNUM)
LJFOLDF(simplify_numsub_negk)
{
PHIBARRIER(fleft);
fins->op2 = fleft->op1; /* (-x) - k ==> (-k) - x */
fins->op1 = (IRRef1)lj_ir_knum(J, -knumright);
return RETRYFOLD;
}
LJFOLD(SUB any NEG)
LJFOLDF(simplify_numsub_xneg)
{
PHIBARRIER(fright);
fins->o = IR_ADD; /* a - (-b) ==> a + b */
fins->op2 = fright->op1;
return RETRYFOLD;
}
LJFOLD(MUL any KNUM)
LJFOLD(DIV any KNUM)
LJFOLDF(simplify_nummuldiv_k)
{
lua_Number n = knumright;
if (n == 1.0) { /* x o 1 ==> x */
return LEFTFOLD;
} else if (n == -1.0) { /* x o -1 ==> -x */
fins->o = IR_NEG;
fins->op2 = (IRRef1)lj_ir_knum_neg(J);
return RETRYFOLD;
} else if (fins->o == IR_MUL && n == 2.0) { /* x * 2 ==> x + x */
fins->o = IR_ADD;
fins->op2 = fins->op1;
return RETRYFOLD;
} else if (fins->o == IR_DIV) { /* x / 2^k ==> x * 2^-k */
uint64_t u = ir_knum(fright)->u64;
uint32_t ex = ((uint32_t)(u >> 52) & 0x7ff);
if ((u & U64x(000fffff,ffffffff)) == 0 && ex - 1 < 0x7fd) {
u = (u & ((uint64_t)1 << 63)) | ((uint64_t)(0x7fe - ex) << 52);
fins->o = IR_MUL; /* Multiply by exact reciprocal. */
fins->op2 = lj_ir_knum_u64(J, u);
return RETRYFOLD;
}
}
return NEXTFOLD;
}
LJFOLD(MUL NEG KNUM)
LJFOLD(DIV NEG KNUM)
LJFOLDF(simplify_nummuldiv_negk)
{
PHIBARRIER(fleft);
fins->op1 = fleft->op1; /* (-a) o k ==> a o (-k) */
fins->op2 = (IRRef1)lj_ir_knum(J, -knumright);
return RETRYFOLD;
}
LJFOLD(MUL NEG NEG)
LJFOLD(DIV NEG NEG)
LJFOLDF(simplify_nummuldiv_negneg)
{
PHIBARRIER(fleft);
PHIBARRIER(fright);
fins->op1 = fleft->op1; /* (-a) o (-b) ==> a o b */
fins->op2 = fright->op1;
return RETRYFOLD;
}
LJFOLD(POW any KINT)
LJFOLDF(simplify_numpow_xk)
{
int32_t k = fright->i;
TRef ref = fins->op1;
if (k == 0) /* x ^ 0 ==> 1 */
return lj_ir_knum_one(J); /* Result must be a number, not an int. */
if (k == 1) /* x ^ 1 ==> x */
return LEFTFOLD;
if ((uint32_t)(k+65536) > 2*65536u) /* Limit code explosion. */
return NEXTFOLD;
if (k < 0) { /* x ^ (-k) ==> (1/x) ^ k. */
ref = emitir(IRTN(IR_DIV), lj_ir_knum_one(J), ref);
k = -k;
}
/* Unroll x^k for 1 <= k <= 65536. */
for (; (k & 1) == 0; k >>= 1) /* Handle leading zeros. */
ref = emitir(IRTN(IR_MUL), ref, ref);
if ((k >>= 1) != 0) { /* Handle trailing bits. */
TRef tmp = emitir(IRTN(IR_MUL), ref, ref);
for (; k != 1; k >>= 1) {
if (k & 1)
ref = emitir(IRTN(IR_MUL), ref, tmp);
tmp = emitir(IRTN(IR_MUL), tmp, tmp);
}
ref = emitir(IRTN(IR_MUL), ref, tmp);
}
return ref;
}
LJFOLD(POW KNUM any)
LJFOLDF(simplify_numpow_kx)
{
lua_Number n = knumleft;
if (n == 2.0) { /* 2.0 ^ i ==> ldexp(1.0, tonum(i)) */
fins->o = IR_CONV;
#if LJ_TARGET_X86ORX64
fins->op1 = fins->op2;
fins->op2 = IRCONV_NUM_INT;
fins->op2 = (IRRef1)lj_opt_fold(J);
#endif
fins->op1 = (IRRef1)lj_ir_knum_one(J);
fins->o = IR_LDEXP;
return RETRYFOLD;
}
return NEXTFOLD;
}
/* -- Simplify conversions ------------------------------------------------ */
LJFOLD(CONV CONV IRCONV_NUM_INT) /* _NUM */
LJFOLDF(shortcut_conv_num_int)
{
PHIBARRIER(fleft);
/* Only safe with a guarded conversion to int. */
if ((fleft->op2 & IRCONV_SRCMASK) == IRT_NUM && irt_isguard(fleft->t))
return fleft->op1; /* f(g(x)) ==> x */
return NEXTFOLD;
}
LJFOLD(CONV CONV IRCONV_INT_NUM) /* _INT */
LJFOLD(CONV CONV IRCONV_U32_NUM) /* _U32*/
LJFOLDF(simplify_conv_int_num)
{
/* Fold even across PHI to avoid expensive num->int conversions in loop. */
if ((fleft->op2 & IRCONV_SRCMASK) ==
((fins->op2 & IRCONV_DSTMASK) >> IRCONV_DSH))
return fleft->op1;
return NEXTFOLD;
}
LJFOLD(CONV CONV IRCONV_I64_NUM) /* _INT or _U32 */
LJFOLD(CONV CONV IRCONV_U64_NUM) /* _INT or _U32 */
LJFOLDF(simplify_conv_i64_num)
{
PHIBARRIER(fleft);
if ((fleft->op2 & IRCONV_SRCMASK) == IRT_INT) {
/* Reduce to a sign-extension. */
fins->op1 = fleft->op1;
fins->op2 = ((IRT_I64<<5)|IRT_INT|IRCONV_SEXT);
return RETRYFOLD;
} else if ((fleft->op2 & IRCONV_SRCMASK) == IRT_U32) {
#if LJ_TARGET_X64
return fleft->op1;
#else
/* Reduce to a zero-extension. */
fins->op1 = fleft->op1;
fins->op2 = (IRT_I64<<5)|IRT_U32;
return RETRYFOLD;
#endif
}
return NEXTFOLD;
}
LJFOLD(CONV CONV IRCONV_INT_I64) /* _INT or _U32 */
LJFOLD(CONV CONV IRCONV_INT_U64) /* _INT or _U32 */
LJFOLD(CONV CONV IRCONV_U32_I64) /* _INT or _U32 */
LJFOLD(CONV CONV IRCONV_U32_U64) /* _INT or _U32 */
LJFOLDF(simplify_conv_int_i64)
{
int src;
PHIBARRIER(fleft);
src = (fleft->op2 & IRCONV_SRCMASK);
if (src == IRT_INT || src == IRT_U32) {
if (src == ((fins->op2 & IRCONV_DSTMASK) >> IRCONV_DSH)) {
return fleft->op1;
} else {
fins->op2 = ((fins->op2 & IRCONV_DSTMASK) | src);
fins->op1 = fleft->op1;
return RETRYFOLD;
}
}
return NEXTFOLD;
}
LJFOLD(CONV CONV IRCONV_FLOAT_NUM) /* _FLOAT */
LJFOLDF(simplify_conv_flt_num)
{
PHIBARRIER(fleft);
if ((fleft->op2 & IRCONV_SRCMASK) == IRT_FLOAT)
return fleft->op1;
return NEXTFOLD;
}
/* Shortcut TOBIT + IRT_NUM <- IRT_INT/IRT_U32 conversion. */
LJFOLD(TOBIT CONV KNUM)
LJFOLDF(simplify_tobit_conv)
{
/* Fold even across PHI to avoid expensive num->int conversions in loop. */
if ((fleft->op2 & IRCONV_SRCMASK) == IRT_INT) {
lua_assert(irt_isnum(fleft->t));
return fleft->op1;
} else if ((fleft->op2 & IRCONV_SRCMASK) == IRT_U32) {
lua_assert(irt_isnum(fleft->t));
fins->o = IR_CONV;
fins->op1 = fleft->op1;
fins->op2 = (IRT_INT<<5)|IRT_U32;
return RETRYFOLD;
}
return NEXTFOLD;
}
/* Shortcut floor/ceil/round + IRT_NUM <- IRT_INT/IRT_U32 conversion. */
LJFOLD(FPMATH CONV IRFPM_FLOOR)
LJFOLD(FPMATH CONV IRFPM_CEIL)
LJFOLD(FPMATH CONV IRFPM_TRUNC)
LJFOLDF(simplify_floor_conv)
{
if ((fleft->op2 & IRCONV_SRCMASK) == IRT_INT ||
(fleft->op2 & IRCONV_SRCMASK) == IRT_U32)
return LEFTFOLD;
return NEXTFOLD;
}
/* Strength reduction of widening. */
LJFOLD(CONV any IRCONV_I64_INT)
LJFOLD(CONV any IRCONV_U64_INT)
LJFOLDF(simplify_conv_sext)
{
IRRef ref = fins->op1;
int64_t ofs = 0;
if (!(fins->op2 & IRCONV_SEXT))
return NEXTFOLD;
PHIBARRIER(fleft);
if (fleft->o == IR_XLOAD && (irt_isu8(fleft->t) || irt_isu16(fleft->t)))
goto ok_reduce;
if (fleft->o == IR_ADD && irref_isk(fleft->op2)) {
ofs = (int64_t)IR(fleft->op2)->i;
ref = fleft->op1;
}
/* Use scalar evolution analysis results to strength-reduce sign-extension. */
if (ref == J->scev.idx) {
IRRef lo = J->scev.dir ? J->scev.start : J->scev.stop;
lua_assert(irt_isint(J->scev.t));
if (lo && IR(lo)->i + ofs >= 0) {
ok_reduce:
#if LJ_TARGET_X64
/* Eliminate widening. All 32 bit ops do an implicit zero-extension. */
return LEFTFOLD;
#else
/* Reduce to a (cheaper) zero-extension. */
fins->op2 &= ~IRCONV_SEXT;
return RETRYFOLD;
#endif
}
}
return NEXTFOLD;
}
/* Strength reduction of narrowing. */
LJFOLD(CONV ADD IRCONV_INT_I64)
LJFOLD(CONV SUB IRCONV_INT_I64)
LJFOLD(CONV MUL IRCONV_INT_I64)
LJFOLD(CONV ADD IRCONV_INT_U64)
LJFOLD(CONV SUB IRCONV_INT_U64)
LJFOLD(CONV MUL IRCONV_INT_U64)
LJFOLD(CONV ADD IRCONV_U32_I64)
LJFOLD(CONV SUB IRCONV_U32_I64)
LJFOLD(CONV MUL IRCONV_U32_I64)
LJFOLD(CONV ADD IRCONV_U32_U64)
LJFOLD(CONV SUB IRCONV_U32_U64)
LJFOLD(CONV MUL IRCONV_U32_U64)
LJFOLDF(simplify_conv_narrow)
{
IROp op = (IROp)fleft->o;
IRType t = irt_type(fins->t);
IRRef op1 = fleft->op1, op2 = fleft->op2, mode = fins->op2;
PHIBARRIER(fleft);
op1 = emitir(IRTI(IR_CONV), op1, mode);
op2 = emitir(IRTI(IR_CONV), op2, mode);
fins->ot = IRT(op, t);
fins->op1 = op1;
fins->op2 = op2;
return RETRYFOLD;
}
/* Special CSE rule for CONV. */
LJFOLD(CONV any any)
LJFOLDF(cse_conv)
{
if (LJ_LIKELY(J->flags & JIT_F_OPT_CSE)) {
IRRef op1 = fins->op1, op2 = (fins->op2 & IRCONV_MODEMASK);
uint8_t guard = irt_isguard(fins->t);
IRRef ref = J->chain[IR_CONV];
while (ref > op1) {
IRIns *ir = IR(ref);
/* Commoning with stronger checks is ok. */
if (ir->op1 == op1 && (ir->op2 & IRCONV_MODEMASK) == op2 &&
irt_isguard(ir->t) >= guard)
return ref;
ref = ir->prev;
}
}
return EMITFOLD; /* No fallthrough to regular CSE. */
}
/* FP conversion narrowing. */
LJFOLD(TOBIT ADD KNUM)
LJFOLD(TOBIT SUB KNUM)
LJFOLD(CONV ADD IRCONV_INT_NUM)
LJFOLD(CONV SUB IRCONV_INT_NUM)
LJFOLD(CONV ADD IRCONV_I64_NUM)
LJFOLD(CONV SUB IRCONV_I64_NUM)
LJFOLDF(narrow_convert)
{
PHIBARRIER(fleft);
/* Narrowing ignores PHIs and repeating it inside the loop is not useful. */
if (J->chain[IR_LOOP])
return NEXTFOLD;
lua_assert(fins->o != IR_CONV || (fins->op2&IRCONV_CONVMASK) != IRCONV_TOBIT);
return lj_opt_narrow_convert(J);
}
/* -- Integer algebraic simplifications ----------------------------------- */
LJFOLD(ADD any KINT)
LJFOLD(ADDOV any KINT)
LJFOLD(SUBOV any KINT)
LJFOLDF(simplify_intadd_k)
{
if (fright->i == 0) /* i o 0 ==> i */
return LEFTFOLD;
return NEXTFOLD;
}
LJFOLD(MULOV any KINT)
LJFOLDF(simplify_intmul_k)
{
if (fright->i == 0) /* i * 0 ==> 0 */
return RIGHTFOLD;
if (fright->i == 1) /* i * 1 ==> i */
return LEFTFOLD;
if (fright->i == 2) { /* i * 2 ==> i + i */
fins->o = IR_ADDOV;
fins->op2 = fins->op1;
return RETRYFOLD;
}
return NEXTFOLD;
}
LJFOLD(SUB any KINT)
LJFOLDF(simplify_intsub_k)
{
if (fright->i == 0) /* i - 0 ==> i */
return LEFTFOLD;
fins->o = IR_ADD; /* i - k ==> i + (-k) */
fins->op2 = (IRRef1)lj_ir_kint(J, -fright->i); /* Overflow for -2^31 ok. */
return RETRYFOLD;
}
LJFOLD(SUB KINT any)
LJFOLD(SUB KINT64 any)
LJFOLDF(simplify_intsub_kleft)
{
if (fleft->o == IR_KINT ? (fleft->i == 0) : (ir_kint64(fleft)->u64 == 0)) {
fins->o = IR_NEG; /* 0 - i ==> -i */
fins->op1 = fins->op2;
return RETRYFOLD;
}
return NEXTFOLD;
}
LJFOLD(ADD any KINT64)
LJFOLDF(simplify_intadd_k64)
{
if (ir_kint64(fright)->u64 == 0) /* i + 0 ==> i */
return LEFTFOLD;
return NEXTFOLD;
}
LJFOLD(SUB any KINT64)
LJFOLDF(simplify_intsub_k64)
{
uint64_t k = ir_kint64(fright)->u64;
if (k == 0) /* i - 0 ==> i */
return LEFTFOLD;
fins->o = IR_ADD; /* i - k ==> i + (-k) */
fins->op2 = (IRRef1)lj_ir_kint64(J, (uint64_t)-(int64_t)k);
return RETRYFOLD;
}
static TRef simplify_intmul_k(jit_State *J, int32_t k)
{
/* Note: many more simplifications are possible, e.g. 2^k1 +- 2^k2.
** But this is mainly intended for simple address arithmetic.
** Also it's easier for the backend to optimize the original multiplies.
*/
if (k == 0) { /* i * 0 ==> 0 */
return RIGHTFOLD;
} else if (k == 1) { /* i * 1 ==> i */
return LEFTFOLD;
} else if ((k & (k-1)) == 0) { /* i * 2^k ==> i << k */
fins->o = IR_BSHL;
fins->op2 = lj_ir_kint(J, lj_fls((uint32_t)k));
return RETRYFOLD;
}
return NEXTFOLD;
}
LJFOLD(MUL any KINT)
LJFOLDF(simplify_intmul_k32)
{
if (fright->i >= 0)
return simplify_intmul_k(J, fright->i);
return NEXTFOLD;
}
LJFOLD(MUL any KINT64)
LJFOLDF(simplify_intmul_k64)
{
#if LJ_HASFFI
if (ir_kint64(fright)->u64 < 0x80000000u)
return simplify_intmul_k(J, (int32_t)ir_kint64(fright)->u64);
return NEXTFOLD;
#else
UNUSED(J); lua_assert(0); return FAILFOLD;
#endif
}
LJFOLD(MOD any KINT)
LJFOLDF(simplify_intmod_k)
{
int32_t k = fright->i;
lua_assert(k != 0);
if (k > 0 && (k & (k-1)) == 0) { /* i % (2^k) ==> i & (2^k-1) */
fins->o = IR_BAND;
fins->op2 = lj_ir_kint(J, k-1);
return RETRYFOLD;
}
return NEXTFOLD;
}
LJFOLD(MOD KINT any)
LJFOLDF(simplify_intmod_kleft)
{
if (fleft->i == 0)
return INTFOLD(0);
return NEXTFOLD;
}
LJFOLD(SUB any any)
LJFOLD(SUBOV any any)
LJFOLDF(simplify_intsub)
{
if (fins->op1 == fins->op2 && !irt_isnum(fins->t)) /* i - i ==> 0 */
return irt_is64(fins->t) ? INT64FOLD(0) : INTFOLD(0);
return NEXTFOLD;
}
LJFOLD(SUB ADD any)
LJFOLDF(simplify_intsubadd_leftcancel)
{
if (!irt_isnum(fins->t)) {
PHIBARRIER(fleft);
if (fins->op2 == fleft->op1) /* (i + j) - i ==> j */
return fleft->op2;
if (fins->op2 == fleft->op2) /* (i + j) - j ==> i */
return fleft->op1;
}
return NEXTFOLD;
}
LJFOLD(SUB SUB any)
LJFOLDF(simplify_intsubsub_leftcancel)
{
if (!irt_isnum(fins->t)) {
PHIBARRIER(fleft);
if (fins->op2 == fleft->op1) { /* (i - j) - i ==> 0 - j */
fins->op1 = (IRRef1)lj_ir_kint(J, 0);
fins->op2 = fleft->op2;
return RETRYFOLD;
}
}
return NEXTFOLD;
}
LJFOLD(SUB any SUB)
LJFOLDF(simplify_intsubsub_rightcancel)
{
if (!irt_isnum(fins->t)) {
PHIBARRIER(fright);
if (fins->op1 == fright->op1) /* i - (i - j) ==> j */
return fright->op2;
}
return NEXTFOLD;
}
LJFOLD(SUB any ADD)
LJFOLDF(simplify_intsubadd_rightcancel)
{
if (!irt_isnum(fins->t)) {
PHIBARRIER(fright);
if (fins->op1 == fright->op1) { /* i - (i + j) ==> 0 - j */
fins->op2 = fright->op2;
fins->op1 = (IRRef1)lj_ir_kint(J, 0);
return RETRYFOLD;
}
if (fins->op1 == fright->op2) { /* i - (j + i) ==> 0 - j */
fins->op2 = fright->op1;
fins->op1 = (IRRef1)lj_ir_kint(J, 0);
return RETRYFOLD;
}
}
return NEXTFOLD;
}
LJFOLD(SUB ADD ADD)
LJFOLDF(simplify_intsubaddadd_cancel)
{
if (!irt_isnum(fins->t)) {
PHIBARRIER(fleft);
PHIBARRIER(fright);
if (fleft->op1 == fright->op1) { /* (i + j1) - (i + j2) ==> j1 - j2 */
fins->op1 = fleft->op2;
fins->op2 = fright->op2;
return RETRYFOLD;
}
if (fleft->op1 == fright->op2) { /* (i + j1) - (j2 + i) ==> j1 - j2 */
fins->op1 = fleft->op2;
fins->op2 = fright->op1;
return RETRYFOLD;
}
if (fleft->op2 == fright->op1) { /* (j1 + i) - (i + j2) ==> j1 - j2 */
fins->op1 = fleft->op1;
fins->op2 = fright->op2;
return RETRYFOLD;
}
if (fleft->op2 == fright->op2) { /* (j1 + i) - (j2 + i) ==> j1 - j2 */
fins->op1 = fleft->op1;
fins->op2 = fright->op1;
return RETRYFOLD;
}
}
return NEXTFOLD;
}
LJFOLD(BAND any KINT)
LJFOLD(BAND any KINT64)
LJFOLDF(simplify_band_k)
{
int64_t k = fright->o == IR_KINT ? (int64_t)fright->i :
(int64_t)ir_k64(fright)->u64;
if (k == 0) /* i & 0 ==> 0 */
return RIGHTFOLD;
if (k == -1) /* i & -1 ==> i */
return LEFTFOLD;
return NEXTFOLD;
}
LJFOLD(BOR any KINT)
LJFOLD(BOR any KINT64)
LJFOLDF(simplify_bor_k)
{
int64_t k = fright->o == IR_KINT ? (int64_t)fright->i :
(int64_t)ir_k64(fright)->u64;
if (k == 0) /* i | 0 ==> i */
return LEFTFOLD;
if (k == -1) /* i | -1 ==> -1 */
return RIGHTFOLD;
return NEXTFOLD;
}
LJFOLD(BXOR any KINT)
LJFOLD(BXOR any KINT64)
LJFOLDF(simplify_bxor_k)
{
int64_t k = fright->o == IR_KINT ? (int64_t)fright->i :
(int64_t)ir_k64(fright)->u64;
if (k == 0) /* i xor 0 ==> i */
return LEFTFOLD;
if (k == -1) { /* i xor -1 ==> ~i */
fins->o = IR_BNOT;
fins->op2 = 0;
return RETRYFOLD;
}
return NEXTFOLD;
}
LJFOLD(BSHL any KINT)
LJFOLD(BSHR any KINT)
LJFOLD(BSAR any KINT)
LJFOLD(BROL any KINT)
LJFOLD(BROR any KINT)
LJFOLDF(simplify_shift_ik)
{
int32_t mask = irt_is64(fins->t) ? 63 : 31;
int32_t k = (fright->i & mask);
if (k == 0) /* i o 0 ==> i */
return LEFTFOLD;
if (k == 1 && fins->o == IR_BSHL) { /* i << 1 ==> i + i */
fins->o = IR_ADD;
fins->op2 = fins->op1;
return RETRYFOLD;
}
if (k != fright->i) { /* i o k ==> i o (k & mask) */
fins->op2 = (IRRef1)lj_ir_kint(J, k);
return RETRYFOLD;
}
#ifndef LJ_TARGET_UNIFYROT
if (fins->o == IR_BROR) { /* bror(i, k) ==> brol(i, (-k)&mask) */
fins->o = IR_BROL;
fins->op2 = (IRRef1)lj_ir_kint(J, (-k)&mask);
return RETRYFOLD;
}
#endif
return NEXTFOLD;
}
LJFOLD(BSHL any BAND)
LJFOLD(BSHR any BAND)
LJFOLD(BSAR any BAND)
LJFOLD(BROL any BAND)
LJFOLD(BROR any BAND)
LJFOLDF(simplify_shift_andk)
{
IRIns *irk = IR(fright->op2);
PHIBARRIER(fright);
if ((fins->o < IR_BROL ? LJ_TARGET_MASKSHIFT : LJ_TARGET_MASKROT) &&
irk->o == IR_KINT) { /* i o (j & mask) ==> i o j */
int32_t mask = irt_is64(fins->t) ? 63 : 31;
int32_t k = irk->i & mask;
if (k == mask) {
fins->op2 = fright->op1;
return RETRYFOLD;
}
}
return NEXTFOLD;
}
LJFOLD(BSHL KINT any)
LJFOLD(BSHR KINT any)
LJFOLD(BSHL KINT64 any)
LJFOLD(BSHR KINT64 any)
LJFOLDF(simplify_shift1_ki)
{
int64_t k = fleft->o == IR_KINT ? (int64_t)fleft->i :
(int64_t)ir_k64(fleft)->u64;
if (k == 0) /* 0 o i ==> 0 */
return LEFTFOLD;
return NEXTFOLD;
}
LJFOLD(BSAR KINT any)
LJFOLD(BROL KINT any)
LJFOLD(BROR KINT any)
LJFOLD(BSAR KINT64 any)
LJFOLD(BROL KINT64 any)
LJFOLD(BROR KINT64 any)
LJFOLDF(simplify_shift2_ki)
{
int64_t k = fleft->o == IR_KINT ? (int64_t)fleft->i :
(int64_t)ir_k64(fleft)->u64;
if (k == 0 || k == -1) /* 0 o i ==> 0; -1 o i ==> -1 */
return LEFTFOLD;
return NEXTFOLD;
}
LJFOLD(BSHL BAND KINT)
LJFOLD(BSHR BAND KINT)
LJFOLD(BROL BAND KINT)
LJFOLD(BROR BAND KINT)
LJFOLDF(simplify_shiftk_andk)
{
IRIns *irk = IR(fleft->op2);
PHIBARRIER(fleft);
if (irk->o == IR_KINT) { /* (i & k1) o k2 ==> (i o k2) & (k1 o k2) */
int32_t k = kfold_intop(irk->i, fright->i, (IROp)fins->o);
fins->op1 = fleft->op1;
fins->op1 = (IRRef1)lj_opt_fold(J);
fins->op2 = (IRRef1)lj_ir_kint(J, k);
fins->ot = IRTI(IR_BAND);
return RETRYFOLD;
}
return NEXTFOLD;
}
LJFOLD(BAND BSHL KINT)
LJFOLD(BAND BSHR KINT)
LJFOLDF(simplify_andk_shiftk)
{
IRIns *irk = IR(fleft->op2);
if (irk->o == IR_KINT &&
kfold_intop(-1, irk->i, (IROp)fleft->o) == fright->i)
return LEFTFOLD; /* (i o k1) & k2 ==> i, if (-1 o k1) == k2 */
return NEXTFOLD;
}
/* -- Reassociation ------------------------------------------------------- */
LJFOLD(ADD ADD KINT)
LJFOLD(MUL MUL KINT)
LJFOLD(BAND BAND KINT)
LJFOLD(BOR BOR KINT)
LJFOLD(BXOR BXOR KINT)
LJFOLDF(reassoc_intarith_k)
{
IRIns *irk = IR(fleft->op2);
if (irk->o == IR_KINT) {
int32_t k = kfold_intop(irk->i, fright->i, (IROp)fins->o);
if (k == irk->i) /* (i o k1) o k2 ==> i o k1, if (k1 o k2) == k1. */
return LEFTFOLD;
PHIBARRIER(fleft);
fins->op1 = fleft->op1;
fins->op2 = (IRRef1)lj_ir_kint(J, k);
return RETRYFOLD; /* (i o k1) o k2 ==> i o (k1 o k2) */
}
return NEXTFOLD;
}
LJFOLD(ADD ADD KINT64)
LJFOLD(MUL MUL KINT64)
LJFOLD(BAND BAND KINT64)
LJFOLD(BOR BOR KINT64)
LJFOLD(BXOR BXOR KINT64)
LJFOLDF(reassoc_intarith_k64)
{
#if LJ_HASFFI
IRIns *irk = IR(fleft->op2);
if (irk->o == IR_KINT64) {
uint64_t k = kfold_int64arith(ir_k64(irk)->u64,
ir_k64(fright)->u64, (IROp)fins->o);
PHIBARRIER(fleft);
fins->op1 = fleft->op1;
fins->op2 = (IRRef1)lj_ir_kint64(J, k);
return RETRYFOLD; /* (i o k1) o k2 ==> i o (k1 o k2) */
}
return NEXTFOLD;
#else
UNUSED(J); lua_assert(0); return FAILFOLD;
#endif
}
LJFOLD(MIN MIN any)
LJFOLD(MAX MAX any)
LJFOLD(BAND BAND any)
LJFOLD(BOR BOR any)
LJFOLDF(reassoc_dup)
{
if (fins->op2 == fleft->op1 || fins->op2 == fleft->op2)
return LEFTFOLD; /* (a o b) o a ==> a o b; (a o b) o b ==> a o b */
return NEXTFOLD;
}
LJFOLD(BXOR BXOR any)
LJFOLDF(reassoc_bxor)
{
PHIBARRIER(fleft);
if (fins->op2 == fleft->op1) /* (a xor b) xor a ==> b */
return fleft->op2;
if (fins->op2 == fleft->op2) /* (a xor b) xor b ==> a */
return fleft->op1;
return NEXTFOLD;
}
LJFOLD(BSHL BSHL KINT)
LJFOLD(BSHR BSHR KINT)
LJFOLD(BSAR BSAR KINT)
LJFOLD(BROL BROL KINT)
LJFOLD(BROR BROR KINT)
LJFOLDF(reassoc_shift)
{
IRIns *irk = IR(fleft->op2);
PHIBARRIER(fleft); /* The (shift any KINT) rule covers k2 == 0 and more. */
if (irk->o == IR_KINT) { /* (i o k1) o k2 ==> i o (k1 + k2) */
int32_t mask = irt_is64(fins->t) ? 63 : 31;
int32_t k = (irk->i & mask) + (fright->i & mask);
if (k > mask) { /* Combined shift too wide? */
if (fins->o == IR_BSHL || fins->o == IR_BSHR)
return mask == 31 ? INTFOLD(0) : INT64FOLD(0);
else if (fins->o == IR_BSAR)
k = mask;
else
k &= mask;
}
fins->op1 = fleft->op1;
fins->op2 = (IRRef1)lj_ir_kint(J, k);
return RETRYFOLD;
}
return NEXTFOLD;
}
LJFOLD(MIN MIN KNUM)
LJFOLD(MAX MAX KNUM)
LJFOLD(MIN MIN KINT)
LJFOLD(MAX MAX KINT)
LJFOLDF(reassoc_minmax_k)
{
IRIns *irk = IR(fleft->op2);
if (irk->o == IR_KNUM) {
lua_Number a = ir_knum(irk)->n;
lua_Number y = lj_vm_foldarith(a, knumright, fins->o - IR_ADD);
if (a == y) /* (x o k1) o k2 ==> x o k1, if (k1 o k2) == k1. */
return LEFTFOLD;
PHIBARRIER(fleft);
fins->op1 = fleft->op1;
fins->op2 = (IRRef1)lj_ir_knum(J, y);
return RETRYFOLD; /* (x o k1) o k2 ==> x o (k1 o k2) */
} else if (irk->o == IR_KINT) {
int32_t a = irk->i;
int32_t y = kfold_intop(a, fright->i, fins->o);
if (a == y) /* (x o k1) o k2 ==> x o k1, if (k1 o k2) == k1. */
return LEFTFOLD;
PHIBARRIER(fleft);
fins->op1 = fleft->op1;
fins->op2 = (IRRef1)lj_ir_kint(J, y);
return RETRYFOLD; /* (x o k1) o k2 ==> x o (k1 o k2) */
}
return NEXTFOLD;
}
LJFOLD(MIN MAX any)
LJFOLD(MAX MIN any)
LJFOLDF(reassoc_minmax_left)
{
if (fins->op2 == fleft->op1 || fins->op2 == fleft->op2)
return RIGHTFOLD; /* (b o1 a) o2 b ==> b; (a o1 b) o2 b ==> b */
return NEXTFOLD;
}
LJFOLD(MIN any MAX)
LJFOLD(MAX any MIN)
LJFOLDF(reassoc_minmax_right)
{
if (fins->op1 == fright->op1 || fins->op1 == fright->op2)
return LEFTFOLD; /* a o2 (a o1 b) ==> a; a o2 (b o1 a) ==> a */
return NEXTFOLD;
}
/* -- Array bounds check elimination -------------------------------------- */
/* Eliminate ABC across PHIs to handle t[i-1] forwarding case.
** ABC(asize, (i+k)+(-k)) ==> ABC(asize, i), but only if it already exists.
** Could be generalized to (i+k1)+k2 ==> i+(k1+k2), but needs better disambig.
*/
LJFOLD(ABC any ADD)
LJFOLDF(abc_fwd)
{
if (LJ_LIKELY(J->flags & JIT_F_OPT_ABC)) {
if (irref_isk(fright->op2)) {
IRIns *add2 = IR(fright->op1);
if (add2->o == IR_ADD && irref_isk(add2->op2) &&
IR(fright->op2)->i == -IR(add2->op2)->i) {
IRRef ref = J->chain[IR_ABC];
IRRef lim = add2->op1;
if (fins->op1 > lim) lim = fins->op1;
while (ref > lim) {
IRIns *ir = IR(ref);
if (ir->op1 == fins->op1 && ir->op2 == add2->op1)
return DROPFOLD;
ref = ir->prev;
}
}
}
}
return NEXTFOLD;
}
/* Eliminate ABC for constants.
** ABC(asize, k1), ABC(asize k2) ==> ABC(asize, max(k1, k2))
** Drop second ABC if k2 is lower. Otherwise patch first ABC with k2.
*/
LJFOLD(ABC any KINT)
LJFOLDF(abc_k)
{
if (LJ_LIKELY(J->flags & JIT_F_OPT_ABC)) {
IRRef ref = J->chain[IR_ABC];
IRRef asize = fins->op1;
while (ref > asize) {
IRIns *ir = IR(ref);
if (ir->op1 == asize && irref_isk(ir->op2)) {
int32_t k = IR(ir->op2)->i;
if (fright->i > k)
ir->op2 = fins->op2;
return DROPFOLD;
}
ref = ir->prev;
}
return EMITFOLD; /* Already performed CSE. */
}
return NEXTFOLD;
}
/* Eliminate invariant ABC inside loop. */
LJFOLD(ABC any any)
LJFOLDF(abc_invar)
{
/* Invariant ABC marked as PTR. Drop if op1 is invariant, too. */
if (!irt_isint(fins->t) && fins->op1 < J->chain[IR_LOOP] &&
!irt_isphi(IR(fins->op1)->t))
return DROPFOLD;
return NEXTFOLD;
}
/* -- Commutativity ------------------------------------------------------- */
/* The refs of commutative ops are canonicalized. Lower refs go to the right.
** Rationale behind this:
** - It (also) moves constants to the right.
** - It reduces the number of FOLD rules (e.g. (BOR any KINT) suffices).
** - It helps CSE to find more matches.
** - The assembler generates better code with constants at the right.
*/
LJFOLD(ADD any any)
LJFOLD(MUL any any)
LJFOLD(ADDOV any any)
LJFOLD(MULOV any any)
LJFOLDF(comm_swap)
{
if (fins->op1 < fins->op2) { /* Move lower ref to the right. */
IRRef1 tmp = fins->op1;
fins->op1 = fins->op2;
fins->op2 = tmp;
return RETRYFOLD;
}
return NEXTFOLD;
}
LJFOLD(EQ any any)
LJFOLD(NE any any)
LJFOLDF(comm_equal)
{
/* For non-numbers only: x == x ==> drop; x ~= x ==> fail */
if (fins->op1 == fins->op2 && !irt_isnum(fins->t))
return CONDFOLD(fins->o == IR_EQ);
return fold_comm_swap(J);
}
LJFOLD(LT any any)
LJFOLD(GE any any)
LJFOLD(LE any any)
LJFOLD(GT any any)
LJFOLD(ULT any any)
LJFOLD(UGE any any)
LJFOLD(ULE any any)
LJFOLD(UGT any any)
LJFOLDF(comm_comp)
{
/* For non-numbers only: x <=> x ==> drop; x <> x ==> fail */
if (fins->op1 == fins->op2 && !irt_isnum(fins->t))
return CONDFOLD((fins->o ^ (fins->o >> 1)) & 1);
if (fins->op1 < fins->op2) { /* Move lower ref to the right. */
IRRef1 tmp = fins->op1;
fins->op1 = fins->op2;
fins->op2 = tmp;
fins->o ^= 3; /* GT <-> LT, GE <-> LE, does not affect U */
return RETRYFOLD;
}
return NEXTFOLD;
}
LJFOLD(BAND any any)
LJFOLD(BOR any any)
LJFOLD(MIN any any)
LJFOLD(MAX any any)
LJFOLDF(comm_dup)
{
if (fins->op1 == fins->op2) /* x o x ==> x */
return LEFTFOLD;
return fold_comm_swap(J);
}
LJFOLD(BXOR any any)
LJFOLDF(comm_bxor)
{
if (fins->op1 == fins->op2) /* i xor i ==> 0 */
return irt_is64(fins->t) ? INT64FOLD(0) : INTFOLD(0);
return fold_comm_swap(J);
}
/* -- Simplification of compound expressions ------------------------------ */
static TRef kfold_xload(jit_State *J, IRIns *ir, const void *p)
{
int32_t k;
switch (irt_type(ir->t)) {
case IRT_NUM: return lj_ir_knum_u64(J, *(uint64_t *)p);
case IRT_I8: k = (int32_t)*(int8_t *)p; break;
case IRT_U8: k = (int32_t)*(uint8_t *)p; break;
case IRT_I16: k = (int32_t)(int16_t)lj_getu16(p); break;
case IRT_U16: k = (int32_t)(uint16_t)lj_getu16(p); break;
case IRT_INT: case IRT_U32: k = (int32_t)lj_getu32(p); break;
case IRT_I64: case IRT_U64: return lj_ir_kint64(J, *(uint64_t *)p);
default: return 0;
}
return lj_ir_kint(J, k);
}
/* Turn: string.sub(str, a, b) == kstr
** into: string.byte(str, a) == string.byte(kstr, 1) etc.
** Note: this creates unaligned XLOADs on x86/x64.
*/
LJFOLD(EQ SNEW KGC)
LJFOLD(NE SNEW KGC)
LJFOLDF(merge_eqne_snew_kgc)
{
GCstr *kstr = ir_kstr(fright);
int32_t len = (int32_t)kstr->len;
lua_assert(irt_isstr(fins->t));
#if LJ_TARGET_UNALIGNED
#define FOLD_SNEW_MAX_LEN 4 /* Handle string lengths 0, 1, 2, 3, 4. */
#define FOLD_SNEW_TYPE8 IRT_I8 /* Creates shorter immediates. */
#else
#define FOLD_SNEW_MAX_LEN 1 /* Handle string lengths 0 or 1. */
#define FOLD_SNEW_TYPE8 IRT_U8 /* Prefer unsigned loads. */
#endif
PHIBARRIER(fleft);
if (len <= FOLD_SNEW_MAX_LEN) {
IROp op = (IROp)fins->o;
IRRef strref = fleft->op1;
if (IR(strref)->o != IR_STRREF)
return NEXTFOLD;
if (op == IR_EQ) {
emitir(IRTGI(IR_EQ), fleft->op2, lj_ir_kint(J, len));
/* Caveat: fins/fleft/fright is no longer valid after emitir. */
} else {
/* NE is not expanded since this would need an OR of two conds. */
if (!irref_isk(fleft->op2)) /* Only handle the constant length case. */
return NEXTFOLD;
if (IR(fleft->op2)->i != len)
return DROPFOLD;
}
if (len > 0) {
/* A 4 byte load for length 3 is ok -- all strings have an extra NUL. */
uint16_t ot = (uint16_t)(len == 1 ? IRT(IR_XLOAD, FOLD_SNEW_TYPE8) :
len == 2 ? IRT(IR_XLOAD, IRT_U16) :
IRTI(IR_XLOAD));
TRef tmp = emitir(ot, strref,
IRXLOAD_READONLY | (len > 1 ? IRXLOAD_UNALIGNED : 0));
TRef val = kfold_xload(J, IR(tref_ref(tmp)), strdata(kstr));
if (len == 3)
tmp = emitir(IRTI(IR_BAND), tmp,
lj_ir_kint(J, LJ_ENDIAN_SELECT(0x00ffffff, 0xffffff00)));
fins->op1 = (IRRef1)tmp;
fins->op2 = (IRRef1)val;
fins->ot = (IROpT)IRTGI(op);
return RETRYFOLD;
} else {
return DROPFOLD;
}
}
return NEXTFOLD;
}
/* -- Loads --------------------------------------------------------------- */
/* Loads cannot be folded or passed on to CSE in general.
** Alias analysis is needed to check for forwarding opportunities.
**
** Caveat: *all* loads must be listed here or they end up at CSE!
*/
LJFOLD(ALOAD any)
LJFOLDX(lj_opt_fwd_aload)
/* From HREF fwd (see below). Must eliminate, not supported by fwd/backend. */
LJFOLD(HLOAD KKPTR)
LJFOLDF(kfold_hload_kkptr)
{
UNUSED(J);
lua_assert(ir_kptr(fleft) == niltvg(J2G(J)));
return TREF_NIL;
}
LJFOLD(HLOAD any)
LJFOLDX(lj_opt_fwd_hload)
LJFOLD(ULOAD any)
LJFOLDX(lj_opt_fwd_uload)
LJFOLD(CALLL any IRCALL_lj_tab_len)
LJFOLDX(lj_opt_fwd_tab_len)
/* Upvalue refs are really loads, but there are no corresponding stores.
** So CSE is ok for them, except for UREFO across a GC step (see below).
** If the referenced function is const, its upvalue addresses are const, too.
** This can be used to improve CSE by looking for the same address,
** even if the upvalues originate from a different function.
*/
LJFOLD(UREFO KGC any)
LJFOLD(UREFC KGC any)
LJFOLDF(cse_uref)
{
if (LJ_LIKELY(J->flags & JIT_F_OPT_CSE)) {
IRRef ref = J->chain[fins->o];
GCfunc *fn = ir_kfunc(fleft);
GCupval *uv = gco2uv(gcref(fn->l.uvptr[(fins->op2 >> 8)]));
while (ref > 0) {
IRIns *ir = IR(ref);
if (irref_isk(ir->op1)) {
GCfunc *fn2 = ir_kfunc(IR(ir->op1));
if (gco2uv(gcref(fn2->l.uvptr[(ir->op2 >> 8)])) == uv) {
if (fins->o == IR_UREFO && gcstep_barrier(J, ref))
break;
return ref;
}
}
ref = ir->prev;
}
}
return EMITFOLD;
}
LJFOLD(HREFK any any)
LJFOLDX(lj_opt_fwd_hrefk)
LJFOLD(HREF TNEW any)
LJFOLDF(fwd_href_tnew)
{
if (lj_opt_fwd_href_nokey(J))
return lj_ir_kkptr(J, niltvg(J2G(J)));
return NEXTFOLD;
}
LJFOLD(HREF TDUP KPRI)
LJFOLD(HREF TDUP KGC)
LJFOLD(HREF TDUP KNUM)
LJFOLDF(fwd_href_tdup)
{
TValue keyv;
lj_ir_kvalue(J->L, &keyv, fright);
if (lj_tab_get(J->L, ir_ktab(IR(fleft->op1)), &keyv) == niltvg(J2G(J)) &&
lj_opt_fwd_href_nokey(J))
return lj_ir_kkptr(J, niltvg(J2G(J)));
return NEXTFOLD;
}
/* We can safely FOLD/CSE array/hash refs and field loads, since there
** are no corresponding stores. But we need to check for any NEWREF with
** an aliased table, as it may invalidate all of the pointers and fields.
** Only HREF needs the NEWREF check -- AREF and HREFK already depend on
** FLOADs. And NEWREF itself is treated like a store (see below).
** LREF is constant (per trace) since coroutine switches are not inlined.
*/
LJFOLD(FLOAD TNEW IRFL_TAB_ASIZE)
LJFOLDF(fload_tab_tnew_asize)
{
if (LJ_LIKELY(J->flags & JIT_F_OPT_FOLD) && lj_opt_fwd_tptr(J, fins->op1))
return INTFOLD(fleft->op1);
return NEXTFOLD;
}
LJFOLD(FLOAD TNEW IRFL_TAB_HMASK)
LJFOLDF(fload_tab_tnew_hmask)
{
if (LJ_LIKELY(J->flags & JIT_F_OPT_FOLD) && lj_opt_fwd_tptr(J, fins->op1))
return INTFOLD((1 << fleft->op2)-1);
return NEXTFOLD;
}
LJFOLD(FLOAD TDUP IRFL_TAB_ASIZE)
LJFOLDF(fload_tab_tdup_asize)
{
if (LJ_LIKELY(J->flags & JIT_F_OPT_FOLD) && lj_opt_fwd_tptr(J, fins->op1))
return INTFOLD((int32_t)ir_ktab(IR(fleft->op1))->asize);
return NEXTFOLD;
}
LJFOLD(FLOAD TDUP IRFL_TAB_HMASK)
LJFOLDF(fload_tab_tdup_hmask)
{
if (LJ_LIKELY(J->flags & JIT_F_OPT_FOLD) && lj_opt_fwd_tptr(J, fins->op1))
return INTFOLD((int32_t)ir_ktab(IR(fleft->op1))->hmask);
return NEXTFOLD;
}
LJFOLD(HREF any any)
LJFOLD(FLOAD any IRFL_TAB_ARRAY)
LJFOLD(FLOAD any IRFL_TAB_NODE)
LJFOLD(FLOAD any IRFL_TAB_ASIZE)
LJFOLD(FLOAD any IRFL_TAB_HMASK)
LJFOLDF(fload_tab_ah)
{
TRef tr = lj_opt_cse(J);
return lj_opt_fwd_tptr(J, tref_ref(tr)) ? tr : EMITFOLD;
}
/* Strings are immutable, so we can safely FOLD/CSE the related FLOAD. */
LJFOLD(FLOAD KGC IRFL_STR_LEN)
LJFOLDF(fload_str_len_kgc)
{
if (LJ_LIKELY(J->flags & JIT_F_OPT_FOLD))
return INTFOLD((int32_t)ir_kstr(fleft)->len);
return NEXTFOLD;
}
LJFOLD(FLOAD SNEW IRFL_STR_LEN)
LJFOLDF(fload_str_len_snew)
{
if (LJ_LIKELY(J->flags & JIT_F_OPT_FOLD)) {
PHIBARRIER(fleft);
return fleft->op2;
}
return NEXTFOLD;
}
LJFOLD(FLOAD TOSTR IRFL_STR_LEN)
LJFOLDF(fload_str_len_tostr)
{
if (LJ_LIKELY(J->flags & JIT_F_OPT_FOLD) && fleft->op2 == IRTOSTR_CHAR)
return INTFOLD(1);
return NEXTFOLD;
}
/* The C type ID of cdata objects is immutable. */
LJFOLD(FLOAD KGC IRFL_CDATA_CTYPEID)
LJFOLDF(fload_cdata_typeid_kgc)
{
if (LJ_LIKELY(J->flags & JIT_F_OPT_FOLD))
return INTFOLD((int32_t)ir_kcdata(fleft)->ctypeid);
return NEXTFOLD;
}
/* Get the contents of immutable cdata objects. */
LJFOLD(FLOAD KGC IRFL_CDATA_PTR)
LJFOLD(FLOAD KGC IRFL_CDATA_INT)
LJFOLD(FLOAD KGC IRFL_CDATA_INT64)
LJFOLDF(fload_cdata_int64_kgc)
{
if (LJ_LIKELY(J->flags & JIT_F_OPT_FOLD)) {
void *p = cdataptr(ir_kcdata(fleft));
if (irt_is64(fins->t))
return INT64FOLD(*(uint64_t *)p);
else
return INTFOLD(*(int32_t *)p);
}
return NEXTFOLD;
}
LJFOLD(FLOAD CNEW IRFL_CDATA_CTYPEID)
LJFOLD(FLOAD CNEWI IRFL_CDATA_CTYPEID)
LJFOLDF(fload_cdata_typeid_cnew)
{
if (LJ_LIKELY(J->flags & JIT_F_OPT_FOLD))
return fleft->op1; /* No PHI barrier needed. CNEW/CNEWI op1 is const. */
return NEXTFOLD;
}
/* Pointer, int and int64 cdata objects are immutable. */
LJFOLD(FLOAD CNEWI IRFL_CDATA_PTR)
LJFOLD(FLOAD CNEWI IRFL_CDATA_INT)
LJFOLD(FLOAD CNEWI IRFL_CDATA_INT64)
LJFOLDF(fload_cdata_ptr_int64_cnew)
{
if (LJ_LIKELY(J->flags & JIT_F_OPT_FOLD))
return fleft->op2; /* Fold even across PHI to avoid allocations. */
return NEXTFOLD;
}
LJFOLD(FLOAD any IRFL_STR_LEN)
LJFOLD(FLOAD any IRFL_FUNC_ENV)
LJFOLD(FLOAD any IRFL_THREAD_ENV)
LJFOLD(FLOAD any IRFL_CDATA_CTYPEID)
LJFOLD(FLOAD any IRFL_CDATA_PTR)
LJFOLD(FLOAD any IRFL_CDATA_INT)
LJFOLD(FLOAD any IRFL_CDATA_INT64)
LJFOLD(VLOAD any any) /* Vararg loads have no corresponding stores. */
LJFOLDX(lj_opt_cse)
/* All other field loads need alias analysis. */
LJFOLD(FLOAD any any)
LJFOLDX(lj_opt_fwd_fload)
/* This is for LOOP only. Recording handles SLOADs internally. */
LJFOLD(SLOAD any any)
LJFOLDF(fwd_sload)
{
if ((fins->op2 & IRSLOAD_FRAME)) {
TRef tr = lj_opt_cse(J);
return tref_ref(tr) < J->chain[IR_RETF] ? EMITFOLD : tr;
} else {
lua_assert(J->slot[fins->op1] != 0);
return J->slot[fins->op1];
}
}
/* Only fold for KKPTR. The pointer _and_ the contents must be const. */
LJFOLD(XLOAD KKPTR any)
LJFOLDF(xload_kptr)
{
TRef tr = kfold_xload(J, fins, ir_kptr(fleft));
return tr ? tr : NEXTFOLD;
}
LJFOLD(XLOAD any any)
LJFOLDX(lj_opt_fwd_xload)
/* -- Write barriers ------------------------------------------------------ */
/* Write barriers are amenable to CSE, but not across any incremental
** GC steps.
**
** The same logic applies to open upvalue references, because a stack
** may be resized during a GC step (not the current stack, but maybe that
** of a coroutine).
*/
LJFOLD(TBAR any)
LJFOLD(OBAR any any)
LJFOLD(UREFO any any)
LJFOLDF(barrier_tab)
{
TRef tr = lj_opt_cse(J);
if (gcstep_barrier(J, tref_ref(tr))) /* CSE across GC step? */
return EMITFOLD; /* Raw emit. Assumes fins is left intact by CSE. */
return tr;
}
LJFOLD(TBAR TNEW)
LJFOLD(TBAR TDUP)
LJFOLDF(barrier_tnew_tdup)
{
/* New tables are always white and never need a barrier. */
if (fins->op1 < J->chain[IR_LOOP]) /* Except across a GC step. */
return NEXTFOLD;
return DROPFOLD;
}
/* -- Profiling ----------------------------------------------------------- */
LJFOLD(PROF any any)
LJFOLDF(prof)
{
IRRef ref = J->chain[IR_PROF];
if (ref+1 == J->cur.nins) /* Drop neighbouring IR_PROF. */
return ref;
return EMITFOLD;
}
/* -- Stores and allocations ---------------------------------------------- */
/* Stores and allocations cannot be folded or passed on to CSE in general.
** But some stores can be eliminated with dead-store elimination (DSE).
**
** Caveat: *all* stores and allocs must be listed here or they end up at CSE!
*/
LJFOLD(ASTORE any any)
LJFOLD(HSTORE any any)
LJFOLDX(lj_opt_dse_ahstore)
LJFOLD(USTORE any any)
LJFOLDX(lj_opt_dse_ustore)
LJFOLD(FSTORE any any)
LJFOLDX(lj_opt_dse_fstore)
LJFOLD(XSTORE any any)
LJFOLDX(lj_opt_dse_xstore)
LJFOLD(NEWREF any any) /* Treated like a store. */
LJFOLD(CALLA any any)
LJFOLD(CALLL any any) /* Safeguard fallback. */
LJFOLD(CALLS any any)
LJFOLD(CALLXS any any)
LJFOLD(XBAR)
LJFOLD(RETF any any) /* Modifies BASE. */
LJFOLD(TNEW any any)
LJFOLD(TDUP any)
LJFOLD(CNEW any any)
LJFOLD(XSNEW any any)
LJFOLD(BUFHDR any any)
LJFOLDX(lj_ir_emit)
/* ------------------------------------------------------------------------ */
/* Every entry in the generated hash table is a 32 bit pattern:
**
** xxxxxxxx iiiiiii lllllll rrrrrrrrrr
**
** xxxxxxxx = 8 bit index into fold function table
** iiiiiii = 7 bit folded instruction opcode
** lllllll = 7 bit left instruction opcode
** rrrrrrrrrr = 8 bit right instruction opcode or 10 bits from literal field
*/
#include "lj_folddef.h"
/* ------------------------------------------------------------------------ */
/* Fold IR instruction. */
TRef LJ_FASTCALL lj_opt_fold(jit_State *J)
{
uint32_t key, any;
IRRef ref;
if (LJ_UNLIKELY((J->flags & JIT_F_OPT_MASK) != JIT_F_OPT_DEFAULT)) {
lua_assert(((JIT_F_OPT_FOLD|JIT_F_OPT_FWD|JIT_F_OPT_CSE|JIT_F_OPT_DSE) |
JIT_F_OPT_DEFAULT) == JIT_F_OPT_DEFAULT);
/* Folding disabled? Chain to CSE, but not for loads/stores/allocs. */
if (!(J->flags & JIT_F_OPT_FOLD) && irm_kind(lj_ir_mode[fins->o]) == IRM_N)
return lj_opt_cse(J);
/* No FOLD, forwarding or CSE? Emit raw IR for loads, except for SLOAD. */
if ((J->flags & (JIT_F_OPT_FOLD|JIT_F_OPT_FWD|JIT_F_OPT_CSE)) !=
(JIT_F_OPT_FOLD|JIT_F_OPT_FWD|JIT_F_OPT_CSE) &&
irm_kind(lj_ir_mode[fins->o]) == IRM_L && fins->o != IR_SLOAD)
return lj_ir_emit(J);
/* No FOLD or DSE? Emit raw IR for stores. */
if ((J->flags & (JIT_F_OPT_FOLD|JIT_F_OPT_DSE)) !=
(JIT_F_OPT_FOLD|JIT_F_OPT_DSE) &&
irm_kind(lj_ir_mode[fins->o]) == IRM_S)
return lj_ir_emit(J);
}
/* Fold engine start/retry point. */
retry:
/* Construct key from opcode and operand opcodes (unless literal/none). */
key = ((uint32_t)fins->o << 17);
if (fins->op1 >= J->cur.nk) {
key += (uint32_t)IR(fins->op1)->o << 10;
*fleft = *IR(fins->op1);
}
if (fins->op2 >= J->cur.nk) {
key += (uint32_t)IR(fins->op2)->o;
*fright = *IR(fins->op2);
} else {
key += (fins->op2 & 0x3ffu); /* Literal mask. Must include IRCONV_*MASK. */
}
/* Check for a match in order from most specific to least specific. */
any = 0;
for (;;) {
uint32_t k = key | (any & 0x1ffff);
uint32_t h = fold_hashkey(k);
uint32_t fh = fold_hash[h]; /* Lookup key in semi-perfect hash table. */
if ((fh & 0xffffff) == k || (fh = fold_hash[h+1], (fh & 0xffffff) == k)) {
ref = (IRRef)tref_ref(fold_func[fh >> 24](J));
if (ref != NEXTFOLD)
break;
}
if (any == 0xfffff) /* Exhausted folding. Pass on to CSE. */
return lj_opt_cse(J);
any = (any | (any >> 10)) ^ 0xffc00;
}
/* Return value processing, ordered by frequency. */
if (LJ_LIKELY(ref >= MAX_FOLD))
return TREF(ref, irt_t(IR(ref)->t));
if (ref == RETRYFOLD)
goto retry;
if (ref == KINTFOLD)
return lj_ir_kint(J, fins->i);
if (ref == FAILFOLD)
lj_trace_err(J, LJ_TRERR_GFAIL);
lua_assert(ref == DROPFOLD);
return REF_DROP;
}
/* -- Common-Subexpression Elimination ------------------------------------ */
/* CSE an IR instruction. This is very fast due to the skip-list chains. */
TRef LJ_FASTCALL lj_opt_cse(jit_State *J)
{
/* Avoid narrow to wide store-to-load forwarding stall */
IRRef2 op12 = (IRRef2)fins->op1 + ((IRRef2)fins->op2 << 16);
IROp op = fins->o;
if (LJ_LIKELY(J->flags & JIT_F_OPT_CSE)) {
/* Limited search for same operands in per-opcode chain. */
IRRef ref = J->chain[op];
IRRef lim = fins->op1;
if (fins->op2 > lim) lim = fins->op2; /* Relies on lit < REF_BIAS. */
while (ref > lim) {
if (IR(ref)->op12 == op12)
return TREF(ref, irt_t(IR(ref)->t)); /* Common subexpression found. */
ref = IR(ref)->prev;
}
}
/* Otherwise emit IR (inlined for speed). */
{
IRRef ref = lj_ir_nextins(J);
IRIns *ir = IR(ref);
ir->prev = J->chain[op];
ir->op12 = op12;
J->chain[op] = (IRRef1)ref;
ir->o = fins->o;
J->guardemit.irt |= fins->t.irt;
return TREF(ref, irt_t((ir->t = fins->t)));
}
}
/* CSE with explicit search limit. */
TRef LJ_FASTCALL lj_opt_cselim(jit_State *J, IRRef lim)
{
IRRef ref = J->chain[fins->o];
IRRef2 op12 = (IRRef2)fins->op1 + ((IRRef2)fins->op2 << 16);
while (ref > lim) {
if (IR(ref)->op12 == op12)
return ref;
ref = IR(ref)->prev;
}
return lj_ir_emit(J);
}
/* ------------------------------------------------------------------------ */
#undef IR
#undef fins
#undef fleft
#undef fright
#undef knumleft
#undef knumright
#undef emitir
#endif
|
816456.c | #include <ctype.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "stack.h"
#include "ap.h"
#include "fmt.h"
// calc data
Stack_T sp;
// calc functions
AP_T pop(void) {
if (!Stack_empty(sp)) {
return Stack_pop(sp);
} else {
Fmt_fprint(stderr, "?stack underflow\n");
return AP_new(0);
}
}
int main(int argc, char* argv[]){
int c;
// initialization
sp = Stack_new();
Fmt_register('D', AP_fmt);
while ((c = getchar()) != EOF)
switch (c) {
// cases
case ' ': case '\t': case '\n': case '\f': case '\r':
break;
case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9': {
char buf[512];
// gather up digits into buf
int i = 0;
for (; c != EOF && isdigit(c); c = getchar(), i++)
if (i < (int)sizeof (buf) - 1) buf[i] = c;
if (i > (int)sizeof (buf) - 1) {
i = (int)sizeof (buf) - 1;
Fmt_fprint(stderr, "?integer constant exceeds %d digits\n", i);
}
buf[i] = 0;
if (c != EOF)
ungetc(c, stdin);
Stack_push(sp, AP_fromstr(buf, 10, NULL));
break;
}
case '+': {
// pop x and y off the stack
AP_T y = pop(), x = pop();
Stack_push(sp, AP_add(x, y));
// free x and y
AP_free(&x);
AP_free(&y);
break;
}
case '-': {
// pop x and y off the stack
AP_T y = pop(), x = pop();
Stack_push(sp, AP_sub(x, y));
// free x and y
AP_free(&x);
AP_free(&y);
break;
}
case '*': {
// pop x and y off the stack
AP_T y = pop(), x = pop();
Stack_push(sp, AP_mul(x, y));
// free x and y
AP_free(&x);
AP_free(&y);
break;
}
case '/': {
// pop x and y off the stack
AP_T y = pop(), x = pop();
if (AP_cmpi(y, 0) == 0) {
Fmt_fprint(stderr, "?/ by 0\n");
Stack_push(sp, AP_new(0));
} else {
Stack_push(sp, AP_div(x, y));
}
// free x and y
AP_free(&x);
AP_free(&y);
break;
}
case '%': {
// pop x and y off the stack
AP_T y = pop(), x = pop();
if (AP_cmpi(y, 0) == 0) {
Fmt_fprint(stderr, "?%% by 0\n");
Stack_push(sp, AP_new(0));
} else {
Stack_push(sp, AP_mod(x, y));
}
// free x and y
AP_free(&x);
AP_free(&y);
break;
}
case '^': {
// pop x and y off the stack
AP_T y = pop(), x = pop();
if (AP_cmpi(y, 0) <= 0) {
Fmt_fprint(stderr, "?nonpositive power\n");
Stack_push(sp, AP_new(0));
} else {
Stack_push(sp, AP_pow(x, y, NULL));
}
// free x and y
AP_free(&x);
AP_free(&y);
break;
}
case 'd': {
AP_T x = pop();
Stack_push(sp, x);
Stack_push(sp, AP_addi(x, 0));
break;
}
case 'p': {
AP_T x = pop();
Fmt_print("%D\n", x);
Stack_push(sp, x);
break;
}
case 'f': {
if (!Stack_empty(sp)) {
Stack_T tmp = Stack_new();
while (!Stack_empty(sp)) {
AP_T x = pop();
Fmt_print("%D\n", x);
Stack_push(tmp, x);
}
while (!Stack_empty(tmp))
Stack_push(sp, Stack_pop(tmp));
Stack_free(&tmp);
}
break;
}
case '~': {
AP_T x = pop();
Stack_push(sp, AP_neg(x));
AP_free(&x);
break;
}
case 'c':
// clear the stack
while (!Stack_empty(sp)) {
AP_T x = Stack_pop(sp);
AP_free(&x);
}
break;
case 'q':
// clean up end exit
// clear the stack
while (!Stack_empty(sp)) {
AP_T x = Stack_pop(sp);
AP_free(&x);
}
Stack_free(&sp);
return EXIT_SUCCESS;
default:
if (isprint(c))
Fmt_fprint(stderr, "?'%c'", c);
else
Fmt_fprint(stderr, "?'\\%03o'", c);
Fmt_fprint(stderr, " is unimplemented\n");
break;
}
// clean up end exit
// clear the stack
while (!Stack_empty(sp)) {
AP_T x = Stack_pop(sp);
AP_free(&x);
}
Stack_free(&sp);
return EXIT_SUCCESS;
}
|
15690.c | #ifdef PROTOTYPE
int isEqual(int, int);
int test_isEqual(int, int);
#endif
#ifdef DECL
{"isEqual", (funct_t) isEqual, (funct_t) test_isEqual, 2,
"! ~ & ^ | + << >>", 5, 2,
{{TMin, TMax},{TMin,TMax},{TMin,TMax}}},
#endif
#ifdef CODE
/*
* isEqual - return 1 if x == y, and 0 otherwise
* Examples: isEqual(5,5) = 1, isEqual(4,5) = 0
* Legal ops: ! ~ & ^ | + << >>
* Max ops: 5
* Rating: 2
*/
int isEqual(int x, int y) {
#ifdef FIX
return !(x ^ y);
#else
return 2;
#endif
}
#endif
#ifdef TEST
int test_isEqual(int x, int y)
{
return x == y;
}
#endif
|
125044.c | /*
* PCI Express PCI Hot Plug Driver
*
* Copyright (C) 1995,2001 Compaq Computer Corporation
* Copyright (C) 2001 Greg Kroah-Hartman ([email protected])
* Copyright (C) 2001 IBM Corp.
* Copyright (C) 2003-2004 Intel Corporation
*
* 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, GOOD TITLE or
* NON INFRINGEMENT. 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., 675 Mass Ave, Cambridge, MA 02139, USA.
*
* Send feedback to <[email protected]>,<[email protected]>
*
*/
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/types.h>
#include <linux/signal.h>
#include <linux/jiffies.h>
#include <linux/timer.h>
#include <linux/pci.h>
#include <linux/interrupt.h>
#include <linux/time.h>
#include <linux/slab.h>
#include "../pci.h"
#include "pciehp.h"
static inline struct pci_dev *ctrl_dev(struct controller *ctrl)
{
return ctrl->pcie->port;
}
static irqreturn_t pcie_isr(int irq, void *dev_id);
static void start_int_poll_timer(struct controller *ctrl, int sec);
/* This is the interrupt polling timeout function. */
static void int_poll_timeout(unsigned long data)
{
struct controller *ctrl = (struct controller *)data;
/* Poll for interrupt events. regs == NULL => polling */
pcie_isr(0, ctrl);
init_timer(&ctrl->poll_timer);
if (!pciehp_poll_time)
pciehp_poll_time = 2; /* default polling interval is 2 sec */
start_int_poll_timer(ctrl, pciehp_poll_time);
}
/* This function starts the interrupt polling timer. */
static void start_int_poll_timer(struct controller *ctrl, int sec)
{
/* Clamp to sane value */
if ((sec <= 0) || (sec > 60))
sec = 2;
ctrl->poll_timer.function = &int_poll_timeout;
ctrl->poll_timer.data = (unsigned long)ctrl;
ctrl->poll_timer.expires = jiffies + sec * HZ;
add_timer(&ctrl->poll_timer);
}
static inline int pciehp_request_irq(struct controller *ctrl)
{
int retval, irq = ctrl->pcie->irq;
/* Install interrupt polling timer. Start with 10 sec delay */
if (pciehp_poll_mode) {
init_timer(&ctrl->poll_timer);
start_int_poll_timer(ctrl, 10);
return 0;
}
/* Installs the interrupt handler */
retval = request_irq(irq, pcie_isr, IRQF_SHARED, MY_NAME, ctrl);
if (retval)
ctrl_err(ctrl, "Cannot get irq %d for the hotplug controller\n",
irq);
return retval;
}
static inline void pciehp_free_irq(struct controller *ctrl)
{
if (pciehp_poll_mode)
del_timer_sync(&ctrl->poll_timer);
else
free_irq(ctrl->pcie->irq, ctrl);
}
static int pcie_poll_cmd(struct controller *ctrl, int timeout)
{
struct pci_dev *pdev = ctrl_dev(ctrl);
u16 slot_status;
pcie_capability_read_word(pdev, PCI_EXP_SLTSTA, &slot_status);
if (slot_status & PCI_EXP_SLTSTA_CC) {
pcie_capability_write_word(pdev, PCI_EXP_SLTSTA,
PCI_EXP_SLTSTA_CC);
return 1;
}
while (timeout > 0) {
msleep(10);
timeout -= 10;
pcie_capability_read_word(pdev, PCI_EXP_SLTSTA, &slot_status);
if (slot_status & PCI_EXP_SLTSTA_CC) {
pcie_capability_write_word(pdev, PCI_EXP_SLTSTA,
PCI_EXP_SLTSTA_CC);
return 1;
}
}
return 0; /* timeout */
}
static void pcie_wait_cmd(struct controller *ctrl)
{
unsigned int msecs = pciehp_poll_mode ? 2500 : 1000;
unsigned long duration = msecs_to_jiffies(msecs);
unsigned long cmd_timeout = ctrl->cmd_started + duration;
unsigned long now, timeout;
int rc;
/*
* If the controller does not generate notifications for command
* completions, we never need to wait between writes.
*/
if (NO_CMD_CMPL(ctrl))
return;
if (!ctrl->cmd_busy)
return;
/*
* Even if the command has already timed out, we want to call
* pcie_poll_cmd() so it can clear PCI_EXP_SLTSTA_CC.
*/
now = jiffies;
if (time_before_eq(cmd_timeout, now))
timeout = 1;
else
timeout = cmd_timeout - now;
if (ctrl->slot_ctrl & PCI_EXP_SLTCTL_HPIE &&
ctrl->slot_ctrl & PCI_EXP_SLTCTL_CCIE)
rc = wait_event_timeout(ctrl->queue, !ctrl->cmd_busy, timeout);
else
rc = pcie_poll_cmd(ctrl, jiffies_to_msecs(timeout));
/*
* Controllers with errata like Intel CF118 don't generate
* completion notifications unless the power/indicator/interlock
* control bits are changed. On such controllers, we'll emit this
* timeout message when we wait for completion of commands that
* don't change those bits, e.g., commands that merely enable
* interrupts.
*/
if (!rc)
ctrl_info(ctrl, "Timeout on hotplug command %#06x (issued %u msec ago)\n",
ctrl->slot_ctrl,
jiffies_to_msecs(jiffies - ctrl->cmd_started));
}
static void pcie_do_write_cmd(struct controller *ctrl, u16 cmd,
u16 mask, bool wait)
{
struct pci_dev *pdev = ctrl_dev(ctrl);
u16 slot_ctrl;
mutex_lock(&ctrl->ctrl_lock);
/*
* Always wait for any previous command that might still be in progress
*/
pcie_wait_cmd(ctrl);
pcie_capability_read_word(pdev, PCI_EXP_SLTCTL, &slot_ctrl);
slot_ctrl &= ~mask;
slot_ctrl |= (cmd & mask);
ctrl->cmd_busy = 1;
smp_mb();
pcie_capability_write_word(pdev, PCI_EXP_SLTCTL, slot_ctrl);
ctrl->cmd_started = jiffies;
ctrl->slot_ctrl = slot_ctrl;
/*
* Optionally wait for the hardware to be ready for a new command,
* indicating completion of the above issued command.
*/
if (wait)
pcie_wait_cmd(ctrl);
mutex_unlock(&ctrl->ctrl_lock);
}
/**
* pcie_write_cmd - Issue controller command
* @ctrl: controller to which the command is issued
* @cmd: command value written to slot control register
* @mask: bitmask of slot control register to be modified
*/
static void pcie_write_cmd(struct controller *ctrl, u16 cmd, u16 mask)
{
pcie_do_write_cmd(ctrl, cmd, mask, true);
}
/* Same as above without waiting for the hardware to latch */
static void pcie_write_cmd_nowait(struct controller *ctrl, u16 cmd, u16 mask)
{
pcie_do_write_cmd(ctrl, cmd, mask, false);
}
bool pciehp_check_link_active(struct controller *ctrl)
{
struct pci_dev *pdev = ctrl_dev(ctrl);
u16 lnk_status;
bool ret;
pcie_capability_read_word(pdev, PCI_EXP_LNKSTA, &lnk_status);
ret = !!(lnk_status & PCI_EXP_LNKSTA_DLLLA);
if (ret)
ctrl_dbg(ctrl, "%s: lnk_status = %x\n", __func__, lnk_status);
return ret;
}
static void __pcie_wait_link_active(struct controller *ctrl, bool active)
{
int timeout = 1000;
if (pciehp_check_link_active(ctrl) == active)
return;
while (timeout > 0) {
msleep(10);
timeout -= 10;
if (pciehp_check_link_active(ctrl) == active)
return;
}
ctrl_dbg(ctrl, "Data Link Layer Link Active not %s in 1000 msec\n",
active ? "set" : "cleared");
}
static void pcie_wait_link_active(struct controller *ctrl)
{
__pcie_wait_link_active(ctrl, true);
}
static bool pci_bus_check_dev(struct pci_bus *bus, int devfn)
{
u32 l;
int count = 0;
int delay = 1000, step = 20;
bool found = false;
do {
found = pci_bus_read_dev_vendor_id(bus, devfn, &l, 0);
count++;
if (found)
break;
msleep(step);
delay -= step;
} while (delay > 0);
if (count > 1 && pciehp_debug)
printk(KERN_DEBUG "pci %04x:%02x:%02x.%d id reading try %d times with interval %d ms to get %08x\n",
pci_domain_nr(bus), bus->number, PCI_SLOT(devfn),
PCI_FUNC(devfn), count, step, l);
return found;
}
int pciehp_check_link_status(struct controller *ctrl)
{
struct pci_dev *pdev = ctrl_dev(ctrl);
bool found;
u16 lnk_status;
/*
* Data Link Layer Link Active Reporting must be capable for
* hot-plug capable downstream port. But old controller might
* not implement it. In this case, we wait for 1000 ms.
*/
if (ctrl->link_active_reporting)
pcie_wait_link_active(ctrl);
else
msleep(1000);
/* wait 100ms before read pci conf, and try in 1s */
msleep(100);
found = pci_bus_check_dev(ctrl->pcie->port->subordinate,
PCI_DEVFN(0, 0));
pcie_capability_read_word(pdev, PCI_EXP_LNKSTA, &lnk_status);
ctrl_dbg(ctrl, "%s: lnk_status = %x\n", __func__, lnk_status);
if ((lnk_status & PCI_EXP_LNKSTA_LT) ||
!(lnk_status & PCI_EXP_LNKSTA_NLW)) {
ctrl_err(ctrl, "Link Training Error occurs\n");
return -1;
}
pcie_update_link_speed(ctrl->pcie->port->subordinate, lnk_status);
if (!found)
return -1;
return 0;
}
static int __pciehp_link_set(struct controller *ctrl, bool enable)
{
struct pci_dev *pdev = ctrl_dev(ctrl);
u16 lnk_ctrl;
pcie_capability_read_word(pdev, PCI_EXP_LNKCTL, &lnk_ctrl);
if (enable)
lnk_ctrl &= ~PCI_EXP_LNKCTL_LD;
else
lnk_ctrl |= PCI_EXP_LNKCTL_LD;
pcie_capability_write_word(pdev, PCI_EXP_LNKCTL, lnk_ctrl);
ctrl_dbg(ctrl, "%s: lnk_ctrl = %x\n", __func__, lnk_ctrl);
return 0;
}
static int pciehp_link_enable(struct controller *ctrl)
{
return __pciehp_link_set(ctrl, true);
}
void pciehp_get_attention_status(struct slot *slot, u8 *status)
{
struct controller *ctrl = slot->ctrl;
struct pci_dev *pdev = ctrl_dev(ctrl);
u16 slot_ctrl;
pcie_capability_read_word(pdev, PCI_EXP_SLTCTL, &slot_ctrl);
ctrl_dbg(ctrl, "%s: SLOTCTRL %x, value read %x\n", __func__,
pci_pcie_cap(ctrl->pcie->port) + PCI_EXP_SLTCTL, slot_ctrl);
switch (slot_ctrl & PCI_EXP_SLTCTL_AIC) {
case PCI_EXP_SLTCTL_ATTN_IND_ON:
*status = 1; /* On */
break;
case PCI_EXP_SLTCTL_ATTN_IND_BLINK:
*status = 2; /* Blink */
break;
case PCI_EXP_SLTCTL_ATTN_IND_OFF:
*status = 0; /* Off */
break;
default:
*status = 0xFF;
break;
}
}
void pciehp_get_power_status(struct slot *slot, u8 *status)
{
struct controller *ctrl = slot->ctrl;
struct pci_dev *pdev = ctrl_dev(ctrl);
u16 slot_ctrl;
pcie_capability_read_word(pdev, PCI_EXP_SLTCTL, &slot_ctrl);
ctrl_dbg(ctrl, "%s: SLOTCTRL %x value read %x\n", __func__,
pci_pcie_cap(ctrl->pcie->port) + PCI_EXP_SLTCTL, slot_ctrl);
switch (slot_ctrl & PCI_EXP_SLTCTL_PCC) {
case PCI_EXP_SLTCTL_PWR_ON:
*status = 1; /* On */
break;
case PCI_EXP_SLTCTL_PWR_OFF:
*status = 0; /* Off */
break;
default:
*status = 0xFF;
break;
}
}
void pciehp_get_latch_status(struct slot *slot, u8 *status)
{
struct pci_dev *pdev = ctrl_dev(slot->ctrl);
u16 slot_status;
pcie_capability_read_word(pdev, PCI_EXP_SLTSTA, &slot_status);
*status = !!(slot_status & PCI_EXP_SLTSTA_MRLSS);
}
void pciehp_get_adapter_status(struct slot *slot, u8 *status)
{
struct pci_dev *pdev = ctrl_dev(slot->ctrl);
u16 slot_status;
pcie_capability_read_word(pdev, PCI_EXP_SLTSTA, &slot_status);
*status = !!(slot_status & PCI_EXP_SLTSTA_PDS);
}
int pciehp_query_power_fault(struct slot *slot)
{
struct pci_dev *pdev = ctrl_dev(slot->ctrl);
u16 slot_status;
pcie_capability_read_word(pdev, PCI_EXP_SLTSTA, &slot_status);
return !!(slot_status & PCI_EXP_SLTSTA_PFD);
}
void pciehp_set_attention_status(struct slot *slot, u8 value)
{
struct controller *ctrl = slot->ctrl;
u16 slot_cmd;
if (!ATTN_LED(ctrl))
return;
switch (value) {
case 0: /* turn off */
slot_cmd = PCI_EXP_SLTCTL_ATTN_IND_OFF;
break;
case 1: /* turn on */
slot_cmd = PCI_EXP_SLTCTL_ATTN_IND_ON;
break;
case 2: /* turn blink */
slot_cmd = PCI_EXP_SLTCTL_ATTN_IND_BLINK;
break;
default:
return;
}
pcie_write_cmd_nowait(ctrl, slot_cmd, PCI_EXP_SLTCTL_AIC);
ctrl_dbg(ctrl, "%s: SLOTCTRL %x write cmd %x\n", __func__,
pci_pcie_cap(ctrl->pcie->port) + PCI_EXP_SLTCTL, slot_cmd);
}
void pciehp_green_led_on(struct slot *slot)
{
struct controller *ctrl = slot->ctrl;
if (!PWR_LED(ctrl))
return;
pcie_write_cmd_nowait(ctrl, PCI_EXP_SLTCTL_PWR_IND_ON,
PCI_EXP_SLTCTL_PIC);
ctrl_dbg(ctrl, "%s: SLOTCTRL %x write cmd %x\n", __func__,
pci_pcie_cap(ctrl->pcie->port) + PCI_EXP_SLTCTL,
PCI_EXP_SLTCTL_PWR_IND_ON);
}
void pciehp_green_led_off(struct slot *slot)
{
struct controller *ctrl = slot->ctrl;
if (!PWR_LED(ctrl))
return;
pcie_write_cmd_nowait(ctrl, PCI_EXP_SLTCTL_PWR_IND_OFF,
PCI_EXP_SLTCTL_PIC);
ctrl_dbg(ctrl, "%s: SLOTCTRL %x write cmd %x\n", __func__,
pci_pcie_cap(ctrl->pcie->port) + PCI_EXP_SLTCTL,
PCI_EXP_SLTCTL_PWR_IND_OFF);
}
void pciehp_green_led_blink(struct slot *slot)
{
struct controller *ctrl = slot->ctrl;
if (!PWR_LED(ctrl))
return;
pcie_write_cmd_nowait(ctrl, PCI_EXP_SLTCTL_PWR_IND_BLINK,
PCI_EXP_SLTCTL_PIC);
ctrl_dbg(ctrl, "%s: SLOTCTRL %x write cmd %x\n", __func__,
pci_pcie_cap(ctrl->pcie->port) + PCI_EXP_SLTCTL,
PCI_EXP_SLTCTL_PWR_IND_BLINK);
}
int pciehp_power_on_slot(struct slot *slot)
{
struct controller *ctrl = slot->ctrl;
struct pci_dev *pdev = ctrl_dev(ctrl);
u16 slot_status;
int retval;
/* Clear sticky power-fault bit from previous power failures */
pcie_capability_read_word(pdev, PCI_EXP_SLTSTA, &slot_status);
if (slot_status & PCI_EXP_SLTSTA_PFD)
pcie_capability_write_word(pdev, PCI_EXP_SLTSTA,
PCI_EXP_SLTSTA_PFD);
ctrl->power_fault_detected = 0;
pcie_write_cmd(ctrl, PCI_EXP_SLTCTL_PWR_ON, PCI_EXP_SLTCTL_PCC);
ctrl_dbg(ctrl, "%s: SLOTCTRL %x write cmd %x\n", __func__,
pci_pcie_cap(ctrl->pcie->port) + PCI_EXP_SLTCTL,
PCI_EXP_SLTCTL_PWR_ON);
retval = pciehp_link_enable(ctrl);
if (retval)
ctrl_err(ctrl, "%s: Can not enable the link!\n", __func__);
return retval;
}
void pciehp_power_off_slot(struct slot *slot)
{
struct controller *ctrl = slot->ctrl;
pcie_write_cmd(ctrl, PCI_EXP_SLTCTL_PWR_OFF, PCI_EXP_SLTCTL_PCC);
ctrl_dbg(ctrl, "%s: SLOTCTRL %x write cmd %x\n", __func__,
pci_pcie_cap(ctrl->pcie->port) + PCI_EXP_SLTCTL,
PCI_EXP_SLTCTL_PWR_OFF);
}
static irqreturn_t pcie_isr(int irq, void *dev_id)
{
struct controller *ctrl = (struct controller *)dev_id;
struct pci_dev *pdev = ctrl_dev(ctrl);
struct pci_bus *subordinate = pdev->subordinate;
struct pci_dev *dev;
struct slot *slot = ctrl->slot;
u16 detected, intr_loc;
/*
* In order to guarantee that all interrupt events are
* serviced, we need to re-inspect Slot Status register after
* clearing what is presumed to be the last pending interrupt.
*/
intr_loc = 0;
do {
pcie_capability_read_word(pdev, PCI_EXP_SLTSTA, &detected);
detected &= (PCI_EXP_SLTSTA_ABP | PCI_EXP_SLTSTA_PFD |
PCI_EXP_SLTSTA_MRLSC | PCI_EXP_SLTSTA_PDC |
PCI_EXP_SLTSTA_CC | PCI_EXP_SLTSTA_DLLSC);
detected &= ~intr_loc;
intr_loc |= detected;
if (!intr_loc)
return IRQ_NONE;
if (detected)
pcie_capability_write_word(pdev, PCI_EXP_SLTSTA,
intr_loc);
} while (detected);
ctrl_dbg(ctrl, "%s: intr_loc %x\n", __func__, intr_loc);
/* Check Command Complete Interrupt Pending */
if (intr_loc & PCI_EXP_SLTSTA_CC) {
ctrl->cmd_busy = 0;
smp_mb();
wake_up(&ctrl->queue);
}
if (subordinate) {
list_for_each_entry(dev, &subordinate->devices, bus_list) {
if (dev->ignore_hotplug) {
ctrl_dbg(ctrl, "ignoring hotplug event %#06x (%s requested no hotplug)\n",
intr_loc, pci_name(dev));
return IRQ_HANDLED;
}
}
}
if (!(intr_loc & ~PCI_EXP_SLTSTA_CC))
return IRQ_HANDLED;
/* Check MRL Sensor Changed */
if (intr_loc & PCI_EXP_SLTSTA_MRLSC)
pciehp_handle_switch_change(slot);
/* Check Attention Button Pressed */
if (intr_loc & PCI_EXP_SLTSTA_ABP)
pciehp_handle_attention_button(slot);
/* Check Presence Detect Changed */
if (intr_loc & PCI_EXP_SLTSTA_PDC)
pciehp_handle_presence_change(slot);
/* Check Power Fault Detected */
if ((intr_loc & PCI_EXP_SLTSTA_PFD) && !ctrl->power_fault_detected) {
ctrl->power_fault_detected = 1;
pciehp_handle_power_fault(slot);
}
if (intr_loc & PCI_EXP_SLTSTA_DLLSC)
pciehp_handle_linkstate_change(slot);
return IRQ_HANDLED;
}
static void pcie_enable_notification(struct controller *ctrl)
{
u16 cmd, mask;
/*
* TBD: Power fault detected software notification support.
*
* Power fault detected software notification is not enabled
* now, because it caused power fault detected interrupt storm
* on some machines. On those machines, power fault detected
* bit in the slot status register was set again immediately
* when it is cleared in the interrupt service routine, and
* next power fault detected interrupt was notified again.
*/
/*
* Always enable link events: thus link-up and link-down shall
* always be treated as hotplug and unplug respectively. Enable
* presence detect only if Attention Button is not present.
*/
cmd = PCI_EXP_SLTCTL_DLLSCE;
if (ATTN_BUTTN(ctrl))
cmd |= PCI_EXP_SLTCTL_ABPE;
else
cmd |= PCI_EXP_SLTCTL_PDCE;
if (MRL_SENS(ctrl))
cmd |= PCI_EXP_SLTCTL_MRLSCE;
if (!pciehp_poll_mode)
cmd |= PCI_EXP_SLTCTL_HPIE | PCI_EXP_SLTCTL_CCIE;
mask = (PCI_EXP_SLTCTL_PDCE | PCI_EXP_SLTCTL_ABPE |
PCI_EXP_SLTCTL_MRLSCE | PCI_EXP_SLTCTL_PFDE |
PCI_EXP_SLTCTL_HPIE | PCI_EXP_SLTCTL_CCIE |
PCI_EXP_SLTCTL_DLLSCE);
pcie_write_cmd_nowait(ctrl, cmd, mask);
ctrl_dbg(ctrl, "%s: SLOTCTRL %x write cmd %x\n", __func__,
pci_pcie_cap(ctrl->pcie->port) + PCI_EXP_SLTCTL, cmd);
}
void pcie_reenable_notification(struct controller *ctrl)
{
/*
* Clear both Presence and Data Link Layer Changed to make sure
* those events still fire after we have re-enabled them.
*/
pcie_capability_write_word(ctrl->pcie->port, PCI_EXP_SLTSTA,
PCI_EXP_SLTSTA_PDC | PCI_EXP_SLTSTA_DLLSC);
pcie_enable_notification(ctrl);
}
static void pcie_disable_notification(struct controller *ctrl)
{
u16 mask;
mask = (PCI_EXP_SLTCTL_PDCE | PCI_EXP_SLTCTL_ABPE |
PCI_EXP_SLTCTL_MRLSCE | PCI_EXP_SLTCTL_PFDE |
PCI_EXP_SLTCTL_HPIE | PCI_EXP_SLTCTL_CCIE |
PCI_EXP_SLTCTL_DLLSCE);
pcie_write_cmd(ctrl, 0, mask);
ctrl_dbg(ctrl, "%s: SLOTCTRL %x write cmd %x\n", __func__,
pci_pcie_cap(ctrl->pcie->port) + PCI_EXP_SLTCTL, 0);
}
/*
* pciehp has a 1:1 bus:slot relationship so we ultimately want a secondary
* bus reset of the bridge, but at the same time we want to ensure that it is
* not seen as a hot-unplug, followed by the hot-plug of the device. Thus,
* disable link state notification and presence detection change notification
* momentarily, if we see that they could interfere. Also, clear any spurious
* events after.
*/
int pciehp_reset_slot(struct slot *slot, int probe)
{
struct controller *ctrl = slot->ctrl;
struct pci_dev *pdev = ctrl_dev(ctrl);
u16 stat_mask = 0, ctrl_mask = 0;
if (probe)
return 0;
if (!ATTN_BUTTN(ctrl)) {
ctrl_mask |= PCI_EXP_SLTCTL_PDCE;
stat_mask |= PCI_EXP_SLTSTA_PDC;
}
ctrl_mask |= PCI_EXP_SLTCTL_DLLSCE;
stat_mask |= PCI_EXP_SLTSTA_DLLSC;
pcie_write_cmd(ctrl, 0, ctrl_mask);
ctrl_dbg(ctrl, "%s: SLOTCTRL %x write cmd %x\n", __func__,
pci_pcie_cap(ctrl->pcie->port) + PCI_EXP_SLTCTL, 0);
if (pciehp_poll_mode)
del_timer_sync(&ctrl->poll_timer);
pci_reset_bridge_secondary_bus(ctrl->pcie->port);
pcie_capability_write_word(pdev, PCI_EXP_SLTSTA, stat_mask);
pcie_write_cmd_nowait(ctrl, ctrl_mask, ctrl_mask);
ctrl_dbg(ctrl, "%s: SLOTCTRL %x write cmd %x\n", __func__,
pci_pcie_cap(ctrl->pcie->port) + PCI_EXP_SLTCTL, ctrl_mask);
if (pciehp_poll_mode)
int_poll_timeout(ctrl->poll_timer.data);
return 0;
}
int pcie_init_notification(struct controller *ctrl)
{
if (pciehp_request_irq(ctrl))
return -1;
pcie_enable_notification(ctrl);
ctrl->notification_enabled = 1;
return 0;
}
static void pcie_shutdown_notification(struct controller *ctrl)
{
if (ctrl->notification_enabled) {
pcie_disable_notification(ctrl);
pciehp_free_irq(ctrl);
ctrl->notification_enabled = 0;
}
}
static int pcie_init_slot(struct controller *ctrl)
{
struct slot *slot;
slot = kzalloc(sizeof(*slot), GFP_KERNEL);
if (!slot)
return -ENOMEM;
slot->wq = alloc_workqueue("pciehp-%u", 0, 0, PSN(ctrl));
if (!slot->wq)
goto abort;
slot->ctrl = ctrl;
mutex_init(&slot->lock);
mutex_init(&slot->hotplug_lock);
INIT_DELAYED_WORK(&slot->work, pciehp_queue_pushbutton_work);
ctrl->slot = slot;
return 0;
abort:
kfree(slot);
return -ENOMEM;
}
static void pcie_cleanup_slot(struct controller *ctrl)
{
struct slot *slot = ctrl->slot;
cancel_delayed_work(&slot->work);
destroy_workqueue(slot->wq);
kfree(slot);
}
static inline void dbg_ctrl(struct controller *ctrl)
{
int i;
u16 reg16;
struct pci_dev *pdev = ctrl->pcie->port;
if (!pciehp_debug)
return;
ctrl_info(ctrl, "Hotplug Controller:\n");
ctrl_info(ctrl, " Seg/Bus/Dev/Func/IRQ : %s IRQ %d\n",
pci_name(pdev), pdev->irq);
ctrl_info(ctrl, " Vendor ID : 0x%04x\n", pdev->vendor);
ctrl_info(ctrl, " Device ID : 0x%04x\n", pdev->device);
ctrl_info(ctrl, " Subsystem ID : 0x%04x\n",
pdev->subsystem_device);
ctrl_info(ctrl, " Subsystem Vendor ID : 0x%04x\n",
pdev->subsystem_vendor);
ctrl_info(ctrl, " PCIe Cap offset : 0x%02x\n",
pci_pcie_cap(pdev));
for (i = 0; i < DEVICE_COUNT_RESOURCE; i++) {
if (!pci_resource_len(pdev, i))
continue;
ctrl_info(ctrl, " PCI resource [%d] : %pR\n",
i, &pdev->resource[i]);
}
ctrl_info(ctrl, "Slot Capabilities : 0x%08x\n", ctrl->slot_cap);
ctrl_info(ctrl, " Physical Slot Number : %d\n", PSN(ctrl));
ctrl_info(ctrl, " Attention Button : %3s\n",
ATTN_BUTTN(ctrl) ? "yes" : "no");
ctrl_info(ctrl, " Power Controller : %3s\n",
POWER_CTRL(ctrl) ? "yes" : "no");
ctrl_info(ctrl, " MRL Sensor : %3s\n",
MRL_SENS(ctrl) ? "yes" : "no");
ctrl_info(ctrl, " Attention Indicator : %3s\n",
ATTN_LED(ctrl) ? "yes" : "no");
ctrl_info(ctrl, " Power Indicator : %3s\n",
PWR_LED(ctrl) ? "yes" : "no");
ctrl_info(ctrl, " Hot-Plug Surprise : %3s\n",
HP_SUPR_RM(ctrl) ? "yes" : "no");
ctrl_info(ctrl, " EMI Present : %3s\n",
EMI(ctrl) ? "yes" : "no");
ctrl_info(ctrl, " Command Completed : %3s\n",
NO_CMD_CMPL(ctrl) ? "no" : "yes");
pcie_capability_read_word(pdev, PCI_EXP_SLTSTA, ®16);
ctrl_info(ctrl, "Slot Status : 0x%04x\n", reg16);
pcie_capability_read_word(pdev, PCI_EXP_SLTCTL, ®16);
ctrl_info(ctrl, "Slot Control : 0x%04x\n", reg16);
}
#define FLAG(x, y) (((x) & (y)) ? '+' : '-')
struct controller *pcie_init(struct pcie_device *dev)
{
struct controller *ctrl;
u32 slot_cap, link_cap;
struct pci_dev *pdev = dev->port;
ctrl = kzalloc(sizeof(*ctrl), GFP_KERNEL);
if (!ctrl) {
dev_err(&dev->device, "%s: Out of memory\n", __func__);
goto abort;
}
ctrl->pcie = dev;
pcie_capability_read_dword(pdev, PCI_EXP_SLTCAP, &slot_cap);
ctrl->slot_cap = slot_cap;
mutex_init(&ctrl->ctrl_lock);
init_waitqueue_head(&ctrl->queue);
dbg_ctrl(ctrl);
/* Check if Data Link Layer Link Active Reporting is implemented */
pcie_capability_read_dword(pdev, PCI_EXP_LNKCAP, &link_cap);
if (link_cap & PCI_EXP_LNKCAP_DLLLARC) {
ctrl_dbg(ctrl, "Link Active Reporting supported\n");
ctrl->link_active_reporting = 1;
}
/* Clear all remaining event bits in Slot Status register */
pcie_capability_write_word(pdev, PCI_EXP_SLTSTA,
PCI_EXP_SLTSTA_ABP | PCI_EXP_SLTSTA_PFD |
PCI_EXP_SLTSTA_MRLSC | PCI_EXP_SLTSTA_PDC |
PCI_EXP_SLTSTA_CC | PCI_EXP_SLTSTA_DLLSC);
ctrl_info(ctrl, "Slot #%d AttnBtn%c AttnInd%c PwrInd%c PwrCtrl%c MRL%c Interlock%c NoCompl%c LLActRep%c\n",
(slot_cap & PCI_EXP_SLTCAP_PSN) >> 19,
FLAG(slot_cap, PCI_EXP_SLTCAP_ABP),
FLAG(slot_cap, PCI_EXP_SLTCAP_AIP),
FLAG(slot_cap, PCI_EXP_SLTCAP_PIP),
FLAG(slot_cap, PCI_EXP_SLTCAP_PCP),
FLAG(slot_cap, PCI_EXP_SLTCAP_MRLSP),
FLAG(slot_cap, PCI_EXP_SLTCAP_EIP),
FLAG(slot_cap, PCI_EXP_SLTCAP_NCCS),
FLAG(link_cap, PCI_EXP_LNKCAP_DLLLARC));
if (pcie_init_slot(ctrl))
goto abort_ctrl;
return ctrl;
abort_ctrl:
kfree(ctrl);
abort:
return NULL;
}
void pciehp_release_ctrl(struct controller *ctrl)
{
pcie_shutdown_notification(ctrl);
pcie_cleanup_slot(ctrl);
kfree(ctrl);
}
|
102702.c | /*
* Copyright 2017, Data61
* Commonwealth Scientific and Industrial Research Organisation (CSIRO)
* ABN 41 687 119 230.
*
* This software may be distributed and modified according to the terms of
* the BSD 2-Clause license. Note that NO WARRANTY is provided.
* See "LICENSE_BSD2.txt" for details.
*
* @TAG(DATA61_BSD)
*/
#include <assert.h>
#include <camkes/allocator.h>
#include <sel4/sel4.h>
#include <stdbool.h>
#include <stdlib.h>
/* Super dumb (and simple) bookkeeping where we keep everything in a single
* linked-list and search this every time we need to alloc/free.
*/
typedef struct _node {
seL4_ObjectType type;
size_t size;
seL4_CPtr ptr;
bool used;
unsigned attributes;
struct _node *next;
} node_t;
static node_t *resources;
int camkes_provide(seL4_ObjectType type, seL4_CPtr ptr, size_t size,
unsigned attributes)
{
node_t *n = calloc(1, sizeof(*n));
if (n == NULL) {
return -1;
}
n->type = type;
n->size = size;
n->ptr = ptr;
n->attributes = attributes;
n->next = resources;
resources = n;
return 0;
}
seL4_CPtr camkes_alloc(seL4_ObjectType type, size_t size, unsigned flags)
{
for (node_t *n = resources; n != NULL; n = n->next) {
if (n->type == type && !n->used && (n->attributes & flags) == flags &&
(size == 0 || size == n->size)) {
n->used = true;
return n->ptr;
}
}
return seL4_CapNull;
}
void camkes_free(seL4_CPtr ptr)
{
for (node_t *n = resources; n != NULL; n = n->next) {
if (n->ptr == ptr) {
assert(n->used && "double free of a cap pointer");
n->used = false;
return;
}
}
assert(!"free of a cap pointer that was never allocated");
}
|
Subsets and Splits