filename
stringlengths 3
9
| code
stringlengths 4
1.05M
|
---|---|
600417.c | /* Copyright (c) 2013 Scott Lembcke and Howling Moon Software
*
* 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 "chipmunk_private.h"
static void
preStep(cpSlideJoint *joint, cpFloat dt)
{
cpBody *a = joint->constraint.a;
cpBody *b = joint->constraint.b;
joint->r1 = cpTransformVect(a->transform, cpvsub(joint->anchorA, a->cog));
joint->r2 = cpTransformVect(b->transform, cpvsub(joint->anchorB, b->cog));
cpVect delta = cpvsub(cpvadd(b->p, joint->r2), cpvadd(a->p, joint->r1));
cpFloat dist = cpvlength(delta);
cpFloat pdist = 0.0f;
if(dist > joint->max) {
pdist = dist - joint->max;
joint->n = cpvnormalize(delta);
} else if(dist < joint->min) {
pdist = joint->min - dist;
joint->n = cpvneg(cpvnormalize(delta));
} else {
joint->n = cpvzero;
joint->jnAcc = 0.0f;
}
// calculate mass normal
joint->nMass = 1.0f/k_scalar(a, b, joint->r1, joint->r2, joint->n);
// calculate bias velocity
cpFloat maxBias = joint->constraint.maxBias;
joint->bias = cpfclamp(-bias_coef(joint->constraint.errorBias, dt)*pdist/dt, -maxBias, maxBias);
}
static void
applyCachedImpulse(cpSlideJoint *joint, cpFloat dt_coef)
{
cpBody *a = joint->constraint.a;
cpBody *b = joint->constraint.b;
cpVect j = cpvmult(joint->n, joint->jnAcc*dt_coef);
apply_impulses(a, b, joint->r1, joint->r2, j);
}
static void
applyImpulse(cpSlideJoint *joint, cpFloat dt)
{
if(cpveql(joint->n, cpvzero)) return; // early exit
cpBody *a = joint->constraint.a;
cpBody *b = joint->constraint.b;
cpVect n = joint->n;
cpVect r1 = joint->r1;
cpVect r2 = joint->r2;
// compute relative velocity
cpVect vr = relative_velocity(a, b, r1, r2);
cpFloat vrn = cpvdot(vr, n);
// compute normal impulse
cpFloat jn = (joint->bias - vrn)*joint->nMass;
cpFloat jnOld = joint->jnAcc;
joint->jnAcc = cpfclamp(jnOld + jn, -joint->constraint.maxForce*dt, 0.0f);
jn = joint->jnAcc - jnOld;
// apply impulse
apply_impulses(a, b, joint->r1, joint->r2, cpvmult(n, jn));
}
static cpFloat
getImpulse(cpConstraint *joint)
{
return cpfabs(((cpSlideJoint *)joint)->jnAcc);
}
static const cpConstraintClass klass = {
(cpConstraintPreStepImpl)preStep,
(cpConstraintApplyCachedImpulseImpl)applyCachedImpulse,
(cpConstraintApplyImpulseImpl)applyImpulse,
(cpConstraintGetImpulseImpl)getImpulse,
};
cpSlideJoint *
cpSlideJointAlloc(void)
{
return (cpSlideJoint *)cpcalloc(1, sizeof(cpSlideJoint));
}
cpSlideJoint *
cpSlideJointInit(cpSlideJoint *joint, cpBody *a, cpBody *b, cpVect anchorA, cpVect anchorB, cpFloat min, cpFloat max)
{
cpConstraintInit((cpConstraint *)joint, &klass, a, b);
joint->anchorA = anchorA;
joint->anchorB = anchorB;
joint->min = min;
joint->max = max;
joint->jnAcc = 0.0f;
return joint;
}
cpConstraint *
cpSlideJointNew(cpBody *a, cpBody *b, cpVect anchorA, cpVect anchorB, cpFloat min, cpFloat max)
{
return (cpConstraint *)cpSlideJointInit(cpSlideJointAlloc(), a, b, anchorA, anchorB, min, max);
}
cpBool
cpConstraintIsSlideJoint(const cpConstraint *constraint)
{
return (constraint->klass == &klass);
}
cpVect
cpSlideJointGetAnchorA(const cpConstraint *constraint)
{
cpAssertHard(cpConstraintIsSlideJoint(constraint), "Constraint is not a slide joint.");
return ((cpSlideJoint *)constraint)->anchorA;
}
void
cpSlideJointSetAnchorA(cpConstraint *constraint, cpVect anchorA)
{
cpAssertHard(cpConstraintIsSlideJoint(constraint), "Constraint is not a slide joint.");
cpConstraintActivateBodies(constraint);
((cpSlideJoint *)constraint)->anchorA = anchorA;
}
cpVect
cpSlideJointGetAnchorB(const cpConstraint *constraint)
{
cpAssertHard(cpConstraintIsSlideJoint(constraint), "Constraint is not a slide joint.");
return ((cpSlideJoint *)constraint)->anchorB;
}
void
cpSlideJointSetAnchorB(cpConstraint *constraint, cpVect anchorB)
{
cpAssertHard(cpConstraintIsSlideJoint(constraint), "Constraint is not a slide joint.");
cpConstraintActivateBodies(constraint);
((cpSlideJoint *)constraint)->anchorB = anchorB;
}
cpFloat
cpSlideJointGetMin(const cpConstraint *constraint)
{
cpAssertHard(cpConstraintIsSlideJoint(constraint), "Constraint is not a slide joint.");
return ((cpSlideJoint *)constraint)->min;
}
void
cpSlideJointSetMin(cpConstraint *constraint, cpFloat min)
{
cpAssertHard(cpConstraintIsSlideJoint(constraint), "Constraint is not a slide joint.");
cpConstraintActivateBodies(constraint);
((cpSlideJoint *)constraint)->min = min;
}
cpFloat
cpSlideJointGetMax(const cpConstraint *constraint)
{
cpAssertHard(cpConstraintIsSlideJoint(constraint), "Constraint is not a slide joint.");
return ((cpSlideJoint *)constraint)->max;
}
void
cpSlideJointSetMax(cpConstraint *constraint, cpFloat max)
{
cpAssertHard(cpConstraintIsSlideJoint(constraint), "Constraint is not a slide joint.");
cpConstraintActivateBodies(constraint);
((cpSlideJoint *)constraint)->max = max;
}
|
440645.c | /* Copyright (C) 1991-2015 Free Software Foundation, Inc.
This file is part of the GNU C Library.
The GNU C Library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
The GNU C Library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with the GNU C Library; if not, see
<http://www.gnu.org/licenses/>. */
#include <errno.h>
#include <stddef.h>
#include <termios.h>
#include <unistd.h>
#include "bsdtty.h"
/* Suspend or restart transmission on FD. */
int
tcflow (fd, action)
int fd;
int action;
{
switch (action)
{
case TCOOFF:
return __ioctl (fd, TIOCSTOP, (void *) NULL);
case TCOON:
return __ioctl (fd, TIOCSTART, (void *) NULL);
case TCIOFF:
case TCION:
{
/* This just writes the START or STOP character with
`write'. Is there another way to do this? */
struct termios attr;
unsigned char c;
if (tcgetattr (fd, &attr) < 0)
return -1;
c = attr.c_cc[action == TCIOFF ? VSTOP : VSTART];
if (c != _POSIX_VDISABLE && write (fd, &c, 1) < 1)
return -1;
return 0;
}
default:
__set_errno (EINVAL);
return -1;
}
}
|
368608.c | /*
* Copyright (c) 2014-2019 - uPmem
*/
#include <mram.h>
#include "mram_access.h"
#include "mram_structure.h"
void read_query(query_t *query) { mram_read((__mram_ptr void *)QUERY_BUFFER_OFFSET, query, QUERY_BUFFER_SIZE); }
void fetch_cache_line(uint8_t *cache, uintptr_t mram_addr) { mram_read((__mram_ptr void *)mram_addr, cache, CACHE_SIZE); }
|
467103.c |
#include <stdlib.h>
#include <string.h>
#include "../include/libstemmer.h"
#include "../runtime/api.h"
#include "modules.h"
struct sb_stemmer {
struct SN_env * (*create)(void);
void (*close)(struct SN_env *);
int (*stem)(struct SN_env *);
struct SN_env * env;
};
extern const char **
sb_stemmer_list(void)
{
return algorithm_names;
}
static stemmer_encoding sb_getenc(const char * charenc)
{
struct stemmer_encoding * encoding;
if (charenc == NULL) return ENC_UTF_8;
for (encoding = encodings; encoding->name != 0; encoding++) {
if (strcmp(encoding->name, charenc) == 0) break;
}
if (encoding->name == NULL) return ENC_UNKNOWN;
return encoding->enc;
}
extern struct sb_stemmer *
sb_stemmer_new(const char * algorithm, const char * charenc)
{
stemmer_encoding enc;
struct stemmer_modules * module;
struct sb_stemmer * stemmer;
enc = sb_getenc(charenc);
if (enc == ENC_UNKNOWN) return NULL;
for (module = modules; module->name != 0; module++) {
if (strcmp(module->name, algorithm) == 0 && module->enc == enc) break;
}
if (module->name == NULL) return NULL;
stemmer = (struct sb_stemmer *) malloc(sizeof(struct sb_stemmer));
if (stemmer == NULL) return NULL;
stemmer->create = module->create;
stemmer->close = module->close;
stemmer->stem = module->stem;
stemmer->env = stemmer->create();
if (stemmer->env == NULL)
{
sb_stemmer_delete(stemmer);
return NULL;
}
return stemmer;
}
void
sb_stemmer_delete(struct sb_stemmer * stemmer)
{
if (stemmer == 0) return;
if (stemmer->close == 0) return;
stemmer->close(stemmer->env);
stemmer->close = 0;
free(stemmer);
}
const sb_symbol *
sb_stemmer_stem(struct sb_stemmer * stemmer, const sb_symbol * word, int size)
{
int ret;
if (SN_set_current(stemmer->env, size, word))
{
stemmer->env->l = 0;
return NULL;
}
ret = stemmer->stem(stemmer->env);
if (ret < 0) return NULL;
stemmer->env->p[stemmer->env->l] = 0;
return stemmer->env->p;
}
int
sb_stemmer_length(struct sb_stemmer * stemmer)
{
return stemmer->env->l;
}
|
872982.c | /*
File: main.c
License: MIT
Copyright (c) 2019, 2020 André van Schoubroeck
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 "usbd_stm.h"
void usbd_reenumerate(){
__HAL_RCC_GPIOA_CLK_ENABLE();
GPIO_InitTypeDef GPIO_InitStruct;
// Configure USB DM/DP pins
GPIO_InitStruct.Pin = (GPIO_PIN_11 | GPIO_PIN_12);
GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
GPIO_InitStruct.Pull = GPIO_PULLUP;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_HIGH;
HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);
HAL_GPIO_WritePin(GPIOA, GPIO_PIN_11 | GPIO_PIN_12, GPIO_PIN_RESET);
HAL_Delay(1);
}
void SystemClock_Config(void) {
RCC_ClkInitTypeDef RCC_ClkInitStruct;
RCC_OscInitTypeDef RCC_OscInitStruct;
RCC_PeriphCLKInitTypeDef RCC_PeriphClkInit;
/* Enable HSE Oscillator and activate PLL with HSE as source */
RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSE;
RCC_OscInitStruct.HSEState = RCC_HSE_ON;
RCC_OscInitStruct.HSEPredivValue = RCC_HSE_PREDIV_DIV1;
RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE;
RCC_OscInitStruct.PLL.PLLMUL = RCC_PLL_MUL9;
HAL_RCC_OscConfig(&RCC_OscInitStruct);
/* Configures the USB clock */
HAL_RCCEx_GetPeriphCLKConfig(&RCC_PeriphClkInit);
RCC_PeriphClkInit.USBClockSelection = RCC_USBCLKSOURCE_PLL_DIV1_5;
HAL_RCCEx_PeriphCLKConfig(&RCC_PeriphClkInit);
/* Select PLL as system clock source and configure the HCLK, PCLK1 and PCLK2
clocks dividers */
RCC_ClkInitStruct.ClockType = (RCC_CLOCKTYPE_SYSCLK | RCC_CLOCKTYPE_HCLK
| RCC_CLOCKTYPE_PCLK1 | RCC_CLOCKTYPE_PCLK2);
RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV2;
RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1;
HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_2);
}
int main() {
HAL_Init();
SystemClock_Config();
SystemCoreClockUpdate();
usbd_reenumerate();
usbd_init();
while (1)
;;
}
|
746966.c | /*
* ch12/1_miscdrv_rdwr_mutexlock/miscdrv_rdwr_mutexlock.c
***************************************************************
* This program is part of the source code released for the book
* "Linux Kernel Programming"
* (c) Author: Kaiwan N Billimoria
* Publisher: Packt
* GitHub repository:
* https://github.com/PacktPublishing/Linux-Kernel-Programming
*
* From: Ch 12 : Kernel Synchronization - Part 1
****************************************************************
* Brief Description:
* This driver is built upon our previous ch12/miscdrv_rdwr/ misc driver.
* The really important and key difference: previously, we used a few global data
* items throughout *without* protection; this time, we fix this egregious error
* by using a mutex lock to protect the critical sections - the places in the
* code where we access global / shared writeable data.
* The functionality (the get and set of the 'secret') remains identical to the
* original implementation.
*
* For details, please refer the book, Ch 12.
*/
#define pr_fmt(fmt) "%s:%s(): " fmt, KBUILD_MODNAME, __func__
#include <linux/init.h>
#include <linux/module.h>
#include <linux/miscdevice.h>
#include <linux/slab.h> // k[m|z]alloc(), k[z]free(), ...
#include <linux/mm.h> // kvmalloc()
#include <linux/fs.h> // the fops structure
// copy_[to|from]_user()
#include <linux/version.h>
#if LINUX_VERSION_CODE > KERNEL_VERSION(4, 11, 0)
#include <linux/uaccess.h>
#else
#include <asm/uaccess.h>
#endif
#include <linux/mutex.h> // mutex lock, unlock, etc
#include "../../convenient.h"
#define OURMODNAME "miscdrv_rdwr_mutexlock"
MODULE_AUTHOR("Kaiwan N Billimoria");
MODULE_DESCRIPTION
("LKP book:ch12/1_miscdrv_rdwr_mutexlock: simple misc char driver rewritten with mutex locking");
MODULE_LICENSE("Dual MIT/GPL");
MODULE_VERSION("0.1");
static int ga, gb = 1;
DEFINE_MUTEX(lock1); // this mutex lock is meant to protect the integers ga and gb
/*
* The driver 'context' (or private) data structure;
* all relevant 'state info' regarding the driver is here.
*/
struct drv_ctx {
struct device *dev;
int tx, rx, err, myword;
u32 config1, config2;
u64 config3;
#define MAXBYTES 128
char oursecret[MAXBYTES];
struct mutex lock; // this mutex protects this data structure
};
static struct drv_ctx *ctx;
/*--- The driver 'methods' follow ---*/
/*
* open_miscdrv_rdwr()
* The driver's open 'method'; this 'hook' will get invoked by the kernel VFS
* when the device file is opened. Here, we simply print out some relevant info.
* The POSIX standard requires open() to return the file descriptor in success;
* note, though, that this is done within the kernel VFS (when we return). So,
* all we do here is return 0 indicating success.
*/
static int open_miscdrv_rdwr(struct inode *inode, struct file *filp)
{
struct device *dev = ctx->dev;
PRINT_CTX(); // displays process (or intr) context info
mutex_lock(&lock1);
ga++; gb--;
mutex_unlock(&lock1);
dev_info(dev, " filename: \"%s\"\n"
" wrt open file: f_flags = 0x%x\n"
" ga = %d, gb = %d\n", filp->f_path.dentry->d_iname, filp->f_flags, ga, gb);
return 0;
}
/*
* read_miscdrv_rdwr()
* The driver's read 'method'; it has effectively 'taken over' the read syscall
* functionality!
* The POSIX standard requires that the read() and write() system calls return
* the number of bytes read or written on success, 0 on EOF and -1 (-ve errno)
* on failure; here, we copy the 'secret' from our driver context structure
* to the userspace app.
*/
static ssize_t read_miscdrv_rdwr(struct file *filp, char __user *ubuf,
size_t count, loff_t *off)
{
int ret = count, secret_len;
struct device *dev = ctx->dev;
mutex_lock(&ctx->lock);
secret_len = strlen(ctx->oursecret);
mutex_unlock(&ctx->lock);
PRINT_CTX();
dev_info(dev, "%s wants to read (upto) %zu bytes\n", current->comm, count);
ret = -EINVAL;
if (count < MAXBYTES) {
dev_warn(dev, "request # of bytes (%zu) is < required size"
" (%d), aborting read\n", count, MAXBYTES);
goto out_notok;
}
if (secret_len <= 0) {
dev_warn(dev, "whoops, something's wrong, the 'secret' isn't"
" available..; aborting read\n");
goto out_notok;
}
/* In a 'real' driver, we would now actually read the content of the
* device hardware (or whatever) into the user supplied buffer 'ubuf'
* for 'count' bytes, and then copy it to the userspace process (via
* the copy_to_user() routine).
* (FYI, the copy_to_user() routine is the *right* way to copy data from
* userspace to kernel-space; the parameters are:
* 'to-buffer' (dest), 'from-buffer' (src), count (# of bytes)
* Returns 0 on success, i.e., non-zero return implies an I/O fault).
* Here, we simply copy the content of our context structure's 'secret'
* member to userspace.
*/
ret = -EFAULT;
mutex_lock(&ctx->lock);
if (copy_to_user(ubuf, ctx->oursecret, secret_len)) {
dev_warn(dev, "copy_to_user() failed\n");
goto out_ctu;
}
ret = secret_len;
// Update stats
ctx->tx += secret_len; // our 'transmit' is wrt this driver
dev_info(dev, " %d bytes read, returning... (stats: tx=%d, rx=%d)\n",
secret_len, ctx->tx, ctx->rx);
out_ctu:
mutex_unlock(&ctx->lock);
out_notok:
return ret;
}
/*
* write_miscdrv_rdwr()
* The driver's write 'method'; it has effectively 'taken over' the write syscall
* functionality!
* The POSIX standard requires that the read() and write() system calls return
* the number of bytes read or written on success, 0 on EOF and -1 (-ve errno)
* on failure; Here, we accept the string passed to us and update our 'secret'
* value to it.
*/
static ssize_t write_miscdrv_rdwr(struct file *filp, const char __user *ubuf,
size_t count, loff_t *off)
{
int ret;
void *kbuf = NULL;
struct device *dev = ctx->dev;
PRINT_CTX();
dev_info(dev, "%s wants to write %zu bytes\n", current->comm, count);
ret = -ENOMEM;
kbuf = kvmalloc(count, GFP_KERNEL);
if (unlikely(!kbuf)) {
dev_warn(dev, "kvmalloc() failed!\n");
goto out_nomem;
}
memset(kbuf, 0, count);
/* Copy in the user supplied buffer 'ubuf' - the data content to write -
* via the copy_from_user() macro.
* (FYI, the copy_from_user() macro is the *right* way to copy data from
* userspace to kernel-space; the parameters are:
* 'to-buffer', 'from-buffer', count
* Returns 0 on success, i.e., non-zero return implies an I/O fault).
*/
ret = -EFAULT;
if (copy_from_user(kbuf, ubuf, count)) {
dev_warn(dev, "copy_from_user() failed\n");
goto out_cfu;
}
/* In a 'real' driver, we would now actually write (for 'count' bytes)
* the content of the 'ubuf' buffer to the device hardware (or whatever),
* and then return.
* Here, we first acquire the mutex lock, then write the just-accepted
* new 'secret' into our driver 'context' structure, and unlock.
*/
mutex_lock(&ctx->lock);
strscpy(ctx->oursecret, kbuf, (count > MAXBYTES ? MAXBYTES : count));
#if 0
print_hex_dump_bytes("ctx ", DUMP_PREFIX_OFFSET, ctx, sizeof(struct drv_ctx));
#endif
// Update stats
ctx->rx += count; // our 'receive' is wrt userspace
ret = count;
dev_info(dev, " %zu bytes written, returning... (stats: tx=%d, rx=%d)\n",
count, ctx->tx, ctx->rx);
mutex_unlock(&ctx->lock);
out_cfu:
kvfree(kbuf);
out_nomem:
return ret;
}
/*
* close_miscdrv_rdwr()
* The driver's close 'method'; this 'hook' will get invoked by the kernel VFS
* when the device file is closed (technically, when the file ref count drops
* to 0). Here, we simply print out some info, and return 0 indicating success.
*/
static int close_miscdrv_rdwr(struct inode *inode, struct file *filp)
{
struct device *dev = ctx->dev;
PRINT_CTX(); // displays process (or intr) context info
mutex_lock(&lock1);
ga--; gb++;
mutex_unlock(&lock1);
dev_info(dev, "filename: \"%s\"\n ga = %d, gb = %d\n",
filp->f_path.dentry->d_iname, ga, gb);
return 0;
}
/* The driver 'functionality' is encoded via the fops */
static const struct file_operations llkd_misc_fops = {
.open = open_miscdrv_rdwr,
.read = read_miscdrv_rdwr,
.write = write_miscdrv_rdwr,
.llseek = no_llseek, // dummy, we don't support lseek(2)
.release = close_miscdrv_rdwr,
/* As you learn more reg device drivers (refer this book's companion guide
* 'Linux Kernel Programming (Part 2): Writing character device drivers: Learn
* to work with user-kernel interfaces, handle peripheral I/O & hardware
* interrupts '), you'll realize that the ioctl() would be a very useful method
* here. As an exercise, implement an ioctl method; when issued with the
* 'GETSTATS' 'command', it should return the statistics (tx, rx, errors) to
* the calling app.
*/
};
static struct miscdevice llkd_miscdev = {
.minor = MISC_DYNAMIC_MINOR, // kernel dynamically assigns a free minor#
.name = "llkd_miscdrv_rdwr_mutexlock",
// populated within /sys/class/misc/ and /sys/devices/virtual/misc/
.mode = 0666, /* ... dev node perms set as specified here */
.fops = &llkd_misc_fops, // connect to 'functionality'
};
static int __init miscdrv_init_mutexlock(void)
{
int ret;
ret = misc_register(&llkd_miscdev);
if (ret < 0) {
pr_notice("misc device registration failed, aborting\n");
return ret;
}
pr_info("LLKD misc driver (major # 10) registered, minor# = %d,"
" dev node is /dev/llkd_miscdrv_rdwr\n", llkd_miscdev.minor);
/*
* A 'managed' kzalloc(): use the 'devres' API devm_kzalloc() for mem
* alloc; why? as the underlying kernel devres framework will take care of
* freeing the memory automatically upon driver 'detach' or when the driver
* is unloaded from memory
*/
ctx = kzalloc(sizeof(struct drv_ctx), GFP_KERNEL);
if (unlikely(!ctx))
return -ENOMEM;
mutex_init(&ctx->lock);
/* Retrieve the device pointer for this device */
ctx->dev = llkd_miscdev.this_device;
/* Initialize the "secret" value :-) */
strscpy(ctx->oursecret, "initmsg", 8);
/* Why don't we protect the above strscpy() with the mutex lock?
* It's working on shared writable data, yes?
* Yes, BUT this is the init code; it's guaranteed to run in exactly
* one context (typically the insmod(8) process), thus there is
* no concurrency possible here. The same goes for the cleanup
* code path.
*/
dev_dbg(ctx->dev, "A sample print via the dev_dbg(): driver initialized\n");
return 0; /* success */
}
static void __exit miscdrv_exit_mutexlock(void)
{
mutex_destroy(&lock1);
mutex_destroy(&ctx->lock);
misc_deregister(&llkd_miscdev);
pr_info("LLKD misc driver deregistered, bye\n");
}
module_init(miscdrv_init_mutexlock);
module_exit(miscdrv_exit_mutexlock);
|
369580.c | #include "NUS_image_view.h"
#include "../NUS_log.h"
#include "NUS_texture.h"
NUS_result nus_image_view_build
(NUS_image_view *p_image_view, NUS_texture texture, VkImageAspectFlags aspect_flags)
{
VkImageViewCreateInfo view_create_info = {
.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO,
.pNext = NULL,
.flags = 0,
.image = texture.image,
.viewType = VK_IMAGE_VIEW_TYPE_2D,
.format = texture.format,
.components = {
.r = VK_COMPONENT_SWIZZLE_IDENTITY,
.g = VK_COMPONENT_SWIZZLE_IDENTITY,
.b = VK_COMPONENT_SWIZZLE_IDENTITY,
.a = VK_COMPONENT_SWIZZLE_IDENTITY
},
.subresourceRange = {
.aspectMask = aspect_flags,
.baseMipLevel = 0,
.levelCount = 1,
.baseArrayLayer = 0,
.layerCount = 1
}
};
if(vkCreateImageView(nus_get_bound_device(), &view_create_info, NULL,
&p_image_view->vk_image_view) != VK_SUCCESS){
NUS_LOG_ERROR("failed to create image view\n");
return NUS_FAILURE;
}
p_image_view->binding = nus_get_binding();
return NUS_SUCCESS;
}
void nus_image_view_free(NUS_image_view *p_image_view)
{
nus_bind_binding(&p_image_view->binding);
vkDestroyImageView(nus_get_bound_device(), p_image_view->vk_image_view, NULL);
p_image_view->vk_image_view = VK_NULL_HANDLE;
nus_unbind_binding(&p_image_view->binding);
}
|
487445.c | /* ************************************************************************** */
/* LE - / */
/* / */
/* ft_findflag.c .:: .:/ . .:: */
/* +:+:+ +: +: +:+:+ */
/* By: jjanin-r <[email protected]> +:+ +: +: +:+ */
/* #+# #+ #+ #+# */
/* Created: 2018/01/10 15:36:32 by jjanin-r #+# ## ## #+# */
/* Updated: 2018/01/10 15:38:39 by jjanin-r ### #+. /#+ ###.fr */
/* / */
/* / */
/* ************************************************************************** */
#include "libftprintf.h"
int ft_findflag(t_param *ptr, char c)
{
if (ptr->flag == c)
return (0);
else if (ptr->flag1 == c)
return (1);
else if (ptr->flag2 == c)
return (2);
else if (ptr->flag3 == c)
return (3);
else if (ptr->flag4 == c)
return (4);
else
return (-1);
}
|
164785.c | /*
* Copyright (C) 2016, Bin Meng <[email protected]>
*
* SPDX-License-Identifier: GPL-2.0+
*/
#include <common.h>
#include <cpu.h>
#include <dm.h>
#include <dm/uclass-internal.h>
#include <asm/acpi_table.h>
#include <asm/ioapic.h>
#include <asm/mpspec.h>
#include <asm/tables.h>
#include <asm/arch/global_nvs.h>
#include <asm/arch/iomap.h>
void acpi_create_fadt(struct acpi_fadt *fadt, struct acpi_facs *facs,
void *dsdt)
{
struct acpi_table_header *header = &(fadt->header);
u16 pmbase = ACPI_BASE_ADDRESS;
memset((void *)fadt, 0, sizeof(struct acpi_fadt));
acpi_fill_header(header, "FACP");
header->length = sizeof(struct acpi_fadt);
header->revision = 4;
fadt->firmware_ctrl = (u32)facs;
fadt->dsdt = (u32)dsdt;
fadt->preferred_pm_profile = ACPI_PM_MOBILE;
fadt->sci_int = 9;
fadt->smi_cmd = 0;
fadt->acpi_enable = 0;
fadt->acpi_disable = 0;
fadt->s4bios_req = 0;
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 = 8;
fadt->gpe1_blk_len = 0;
fadt->gpe1_base = 0;
fadt->cst_cnt = 0;
fadt->p_lvl2_lat = ACPI_FADT_C2_NOT_SUPPORTED;
fadt->p_lvl3_lat = ACPI_FADT_C3_NOT_SUPPORTED;
fadt->flush_size = 0;
fadt->flush_stride = 0;
fadt->duty_offset = 1;
fadt->duty_width = 0;
fadt->day_alrm = 0x0d;
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_C2_MP_SUPPORTED | ACPI_FADT_SLEEP_BUTTON |
ACPI_FADT_S4_RTC_WAKE | ACPI_FADT_RESET_REGISTER |
ACPI_FADT_PLATFORM_CLOCK;
fadt->reset_reg.space_id = ACPI_ADDRESS_SPACE_IO;
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 = IO_PORT_RESET;
fadt->reset_reg.addrh = 0;
fadt->reset_value = SYS_RST | RST_CPU;
fadt->x_firmware_ctl_l = (u32)facs;
fadt->x_firmware_ctl_h = 0;
fadt->x_dsdt_l = (u32)dsdt;
fadt->x_dsdt_h = 0;
fadt->x_pm1a_evt_blk.space_id = ACPI_ADDRESS_SPACE_IO;
fadt->x_pm1a_evt_blk.bit_width = fadt->pm1_evt_len * 8;
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 = fadt->pm1a_evt_blk;
fadt->x_pm1a_evt_blk.addrh = 0x0;
fadt->x_pm1b_evt_blk.space_id = ACPI_ADDRESS_SPACE_IO;
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 = ACPI_ADDRESS_SPACE_IO;
fadt->x_pm1a_cnt_blk.bit_width = fadt->pm1_cnt_len * 8;
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 = fadt->pm1a_cnt_blk;
fadt->x_pm1a_cnt_blk.addrh = 0x0;
fadt->x_pm1b_cnt_blk.space_id = ACPI_ADDRESS_SPACE_IO;
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 = ACPI_ADDRESS_SPACE_IO;
fadt->x_pm2_cnt_blk.bit_width = fadt->pm2_cnt_len * 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 = fadt->pm2_cnt_blk;
fadt->x_pm2_cnt_blk.addrh = 0x0;
fadt->x_pm_tmr_blk.space_id = ACPI_ADDRESS_SPACE_IO;
fadt->x_pm_tmr_blk.bit_width = fadt->pm_tmr_len * 8;
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 = fadt->pm_tmr_blk;
fadt->x_pm_tmr_blk.addrh = 0x0;
fadt->x_gpe0_blk.space_id = ACPI_ADDRESS_SPACE_IO;
fadt->x_gpe0_blk.bit_width = fadt->gpe0_blk_len * 8;
fadt->x_gpe0_blk.bit_offset = 0;
fadt->x_gpe0_blk.access_size = ACPI_ACCESS_SIZE_DWORD_ACCESS;
fadt->x_gpe0_blk.addrl = fadt->gpe0_blk;
fadt->x_gpe0_blk.addrh = 0x0;
fadt->x_gpe1_blk.space_id = ACPI_ADDRESS_SPACE_IO;
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;
header->checksum = table_compute_checksum(fadt, header->length);
}
static int acpi_create_madt_irq_overrides(u32 current)
{
struct acpi_madt_irqoverride *irqovr;
u16 sci_flags = MP_IRQ_TRIGGER_LEVEL | MP_IRQ_POLARITY_HIGH;
int length = 0;
irqovr = (void *)current;
length += acpi_create_madt_irqoverride(irqovr, 0, 0, 2, 0);
irqovr = (void *)(current + length);
length += acpi_create_madt_irqoverride(irqovr, 0, 9, 9, sci_flags);
return length;
}
u32 acpi_fill_madt(u32 current)
{
current += acpi_create_madt_lapics(current);
current += acpi_create_madt_ioapic((struct acpi_madt_ioapic *)current,
io_apic_read(IO_APIC_ID) >> 24, IO_APIC_ADDR, 0);
current += acpi_create_madt_irq_overrides(current);
return current;
}
void acpi_create_gnvs(struct acpi_global_nvs *gnvs)
{
struct udevice *dev;
int ret;
/* at least we have one processor */
gnvs->pcnt = 1;
/* override the processor count with actual number */
ret = uclass_find_first_device(UCLASS_CPU, &dev);
if (ret == 0 && dev != NULL) {
ret = cpu_get_count(dev);
if (ret > 0)
gnvs->pcnt = ret;
}
/* determine whether internal uart is on */
if (IS_ENABLED(CONFIG_INTERNAL_UART))
gnvs->iuart_en = 1;
else
gnvs->iuart_en = 0;
}
|
602944.c | #pragma config(I2C_Usage, I2C1, i2cSensors)
#pragma config(Sensor, in1, leftLineFollower, sensorLineFollower)
#pragma config(Sensor, in2, centerLineFollower, sensorLineFollower)
#pragma config(Sensor, in3, rightLineFollower, sensorLineFollower)
#pragma config(Sensor, in6, gyro, sensorGyro)
#pragma config(Sensor, dgtl1, rightEncoder, sensorQuadEncoder)
#pragma config(Sensor, dgtl3, leftEncoder, sensorQuadEncoder)
#pragma config(Sensor, dgtl5, touchSensor, sensorTouch)
#pragma config(Sensor, dgtl12, led, sensorLEDtoVCC)
#pragma config(Sensor, I2C_1, rightIME, sensorNone)
#pragma config(Sensor, I2C_2, leftIME, sensorNone)
#pragma config(Sensor, I2C_3, armIME, sensorQuadEncoderOnI2CPort, , AutoAssign )
#pragma config(Motor, port1, leftMotor, tmotorVex393_HBridge, openLoop, driveLeft, encoderPort, dgtl3)
#pragma config(Motor, port6, clawMotor, tmotorVex393_MC29, openLoop)
#pragma config(Motor, port7, armMotor, tmotorVex393_MC29, openLoop, reversed, encoderPort, I2C_3)
#pragma config(Motor, port10, rightMotor, tmotorVex393_HBridge, openLoop, reversed, driveRight, encoderPort, dgtl1)
//*!!Code automatically generated by 'ROBOTC' configuration wizard !!*//
task main()
{
repeat(forever);
{
if (vexRT[touchSensor] == 0)
armControl(armMotor, Btn7U, Btn7D, 25);
}
}
|
303291.c | #include "chainedQueue.h"
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include "../../utils/utils.h"
// Private
ChainQueueHead *initChainQueue() {
ChainQueueHead *head = (ChainQueueHead *)calloc(1, sizeof(ChainQueueHead));
head->first = NULL;
head->last = NULL;
head->length = 0;
return head;
}
static ChainQueue *initChainQueueNode() {
ChainQueue *chainQueue = (ChainQueue *) calloc(1, sizeof(ChainQueue));
return chainQueue;
}
CHAIN_QUEUE_DATA getChainQueueFirstData(ChainQueueHead *chainHead) {
if (isChainQueueEmpty(chainHead)) {
println("Nao e possivel pegar o item, lista vazia");
return NULL;
}
return (chainHead->first)->data;
}
void addToChainQueue(ChainQueueHead *chainHead, CHAIN_QUEUE_DATA data) {
ChainQueue *oldLast = chainHead->last;
ChainQueue *newLast = initChainQueueNode();
newLast->data = data;
if (isChainQueueEmpty(chainHead)) {
chainHead->first = newLast;
} else {
// Coloco na chain
oldLast->next = newLast;
}
// Head
chainHead->last = newLast;
chainHead->length++;
}
CHAIN_QUEUE_DATA removeFromChainQueue(ChainQueueHead *chainHead) {
if (isChainQueueEmpty(chainHead)) {
println("Nao e possivel remover, fila encadeada vazia");
return NULL;
}
ChainQueue *first = chainHead->first;
if (getChainQueueLength(chainHead) > 1) {
ChainQueue *newFirst = first->next;
chainHead->first = newFirst;
}
CHAIN_QUEUE_DATA data = first->data;
free(first);
chainHead->length--;
return data;
}
int getChainQueueLength(ChainQueueHead *chainHead) {
return chainHead->length;
}
bool isChainQueueEmpty(ChainQueueHead *chainHead) { return !chainHead->length; } |
783635.c | #define _POSIX_C_SOURCE 200809L
#include <assert.h>
#include <ctype.h>
#include <glob.h>
#include <mrsh/buffer.h>
#include <pwd.h>
#include <stdbool.h>
#include <stdlib.h>
#include <string.h>
#include "shell/shell.h"
#include "shell/word.h"
static bool is_logname_char(char c) {
// See https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap03.html#tag_03_282
return (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') ||
(c >= '0' && c <= '9') || c == '.' || c == '_' || c == '-';
}
static ssize_t expand_tilde_at(struct mrsh_state *state, const char *str,
bool last, char **expanded_ptr) {
if (str[0] != '~') {
return -1;
}
const char *cur;
for (cur = str + 1; cur[0] != '\0' && cur[0] != '/'; cur++) {
if (!is_logname_char(cur[0])) {
return -1;
}
}
if (cur[0] == '\0' && !last) {
return -1;
}
const char *slash = cur;
char *name = NULL;
if (slash > str + 1) {
name = strndup(str + 1, slash - str - 1);
}
const char *dir = NULL;
if (name == NULL) {
dir = mrsh_env_get(state, "HOME", NULL);
} else {
struct passwd *pw = getpwnam(name);
if (pw != NULL) {
dir = pw->pw_dir;
}
}
free(name);
if (dir == NULL) {
return -1;
}
*expanded_ptr = strdup(dir);
return slash - str;
}
static void _expand_tilde(struct mrsh_state *state, struct mrsh_word **word_ptr,
bool assignment, bool first, bool last) {
struct mrsh_word *word = *word_ptr;
switch (word->type) {
case MRSH_WORD_STRING:;
struct mrsh_word_string *ws = mrsh_word_get_string(word);
if (ws->single_quoted) {
break;
}
struct mrsh_array words = {0};
const char *str = ws->str;
if (first) {
char *expanded;
ssize_t offset = expand_tilde_at(state, str, last, &expanded);
if (offset >= 0) {
mrsh_array_add(&words,
mrsh_word_string_create(expanded, true));
str += offset;
}
}
if (assignment) {
while (true) {
const char *colon = strchr(str, ':');
if (colon == NULL) {
break;
}
char *slice = strndup(str, colon - str + 1);
mrsh_array_add(&words,
mrsh_word_string_create(slice, false));
str = colon + 1;
char *expanded;
ssize_t offset = expand_tilde_at(state, str, last, &expanded);
if (offset >= 0) {
mrsh_array_add(&words,
mrsh_word_string_create(expanded, true));
str += offset;
}
}
}
if (words.len > 0) {
char *trailing = strdup(str);
mrsh_array_add(&words,
mrsh_word_string_create(trailing, false));
struct mrsh_word_list *wl = mrsh_word_list_create(&words, false);
*word_ptr = &wl->word;
mrsh_word_destroy(word);
}
break;
case MRSH_WORD_LIST:;
struct mrsh_word_list *wl = mrsh_word_get_list(word);
if (wl->double_quoted) {
break;
}
for (size_t i = 0; i < wl->children.len; ++i) {
struct mrsh_word **child_ptr =
(struct mrsh_word **)&wl->children.data[i];
_expand_tilde(state, child_ptr, assignment, first && i == 0,
last && i == wl->children.len - 1);
}
break;
default:
break;
}
}
void expand_tilde(struct mrsh_state *state, struct mrsh_word **word_ptr,
bool assignment) {
_expand_tilde(state, word_ptr, assignment, true, true);
}
struct split_fields_data {
struct mrsh_array *fields;
struct mrsh_word_list *cur_field;
const char *ifs, *ifs_non_space;
bool in_ifs, in_ifs_non_space;
};
static void add_to_cur_field(struct split_fields_data *data,
struct mrsh_word *word) {
if (data->cur_field == NULL) {
data->cur_field = mrsh_word_list_create(NULL, false);
mrsh_array_add(data->fields, data->cur_field);
}
mrsh_array_add(&data->cur_field->children, word);
}
static void _split_fields(struct split_fields_data *data,
const struct mrsh_word *word) {
switch (word->type) {
case MRSH_WORD_STRING:;
const struct mrsh_word_string *ws = mrsh_word_get_string(word);
if (ws->single_quoted || !ws->split_fields) {
add_to_cur_field(data, mrsh_word_copy(word));
data->in_ifs = data->in_ifs_non_space = false;
return;
}
struct mrsh_buffer buf = {0};
size_t len = strlen(ws->str);
for (size_t i = 0; i < len; ++i) {
char c = ws->str[i];
if (strchr(data->ifs, c) == NULL) {
mrsh_buffer_append_char(&buf, c);
data->in_ifs = data->in_ifs_non_space = false;
continue;
}
bool is_ifs_non_space = strchr(data->ifs_non_space, c) != NULL;
if (!data->in_ifs || (is_ifs_non_space && data->in_ifs_non_space)) {
mrsh_buffer_append_char(&buf, '\0');
char *str = mrsh_buffer_steal(&buf);
add_to_cur_field(data,
&mrsh_word_string_create(str, false)->word);
data->cur_field = NULL;
data->in_ifs = true;
} else if (is_ifs_non_space) {
data->in_ifs_non_space = true;
}
}
if (!data->in_ifs) {
mrsh_buffer_append_char(&buf, '\0');
char *str = mrsh_buffer_steal(&buf);
add_to_cur_field(data,
&mrsh_word_string_create(str, false)->word);
}
mrsh_buffer_finish(&buf);
break;
case MRSH_WORD_LIST:;
const struct mrsh_word_list *wl = mrsh_word_get_list(word);
if (wl->double_quoted) {
add_to_cur_field(data, mrsh_word_copy(word));
return;
}
for (size_t i = 0; i < wl->children.len; ++i) {
const struct mrsh_word *child = wl->children.data[i];
_split_fields(data, child);
}
break;
default:
abort();
}
}
void split_fields(struct mrsh_array *fields, const struct mrsh_word *word,
const char *ifs) {
if (ifs == NULL) {
ifs = " \t\n";
} else if (ifs[0] == '\0') {
mrsh_array_add(fields, mrsh_word_copy(word));
return;
}
size_t ifs_len = strlen(ifs);
char *ifs_non_space = calloc(ifs_len, sizeof(char));
size_t ifs_non_space_len = 0;
for (size_t i = 0; i < ifs_len; ++i) {
if (!isspace(ifs[i])) {
ifs_non_space[ifs_non_space_len++] = ifs[i];
}
}
struct split_fields_data data = {
.fields = fields,
.ifs = ifs,
.ifs_non_space = ifs_non_space,
.in_ifs = true,
};
_split_fields(&data, word);
free(ifs_non_space);
}
void get_fields_str(struct mrsh_array *strs, const struct mrsh_array *fields) {
for (size_t i = 0; i < fields->len; i++) {
struct mrsh_word *word = fields->data[i];
mrsh_array_add(strs, mrsh_word_str(word));
}
}
static bool is_pathname_metachar(char c) {
switch (c) {
case '*':
case '?':
case '[':
case ']':
return true;
default:
return false;
}
}
static bool needs_pathname_expansion(const struct mrsh_word *word) {
switch (word->type) {
case MRSH_WORD_STRING:;
const struct mrsh_word_string *ws = mrsh_word_get_string(word);
if (ws->single_quoted) {
return false;
}
size_t len = strlen(ws->str);
for (size_t i = 0; i < len; i++) {
if (is_pathname_metachar(ws->str[i])) {
return true;
}
}
return false;
case MRSH_WORD_LIST:;
const struct mrsh_word_list *wl = mrsh_word_get_list(word);
if (wl->double_quoted) {
return false;
}
for (size_t i = 0; i < wl->children.len; i++) {
const struct mrsh_word *child = wl->children.data[i];
if (needs_pathname_expansion(child)) {
return true;
}
}
return false;
default:
abort();
}
}
static void _word_to_pattern(struct mrsh_buffer *buf,
const struct mrsh_word *word, bool quoted) {
switch (word->type) {
case MRSH_WORD_STRING:;
const struct mrsh_word_string *ws = mrsh_word_get_string(word);
size_t len = strlen(ws->str);
for (size_t i = 0; i < len; i++) {
char c = ws->str[i];
if (is_pathname_metachar(c) && (quoted || ws->single_quoted)) {
mrsh_buffer_append_char(buf, '\\');
}
mrsh_buffer_append_char(buf, c);
}
break;
case MRSH_WORD_LIST:;
const struct mrsh_word_list *wl = mrsh_word_get_list(word);
for (size_t i = 0; i < wl->children.len; i++) {
const struct mrsh_word *child = wl->children.data[i];
_word_to_pattern(buf, child, quoted || wl->double_quoted);
}
break;
default:
abort();
}
}
char *word_to_pattern(const struct mrsh_word *word) {
if (!needs_pathname_expansion(word)) {
return NULL;
}
struct mrsh_buffer buf = {0};
_word_to_pattern(&buf, word, false);
mrsh_buffer_append_char(&buf, '\0');
return mrsh_buffer_steal(&buf);
}
bool expand_pathnames(struct mrsh_array *expanded,
const struct mrsh_array *fields) {
for (size_t i = 0; i < fields->len; ++i) {
const struct mrsh_word *field = fields->data[i];
char *pattern = word_to_pattern(field);
if (pattern == NULL) {
mrsh_array_add(expanded, mrsh_word_str(field));
continue;
}
glob_t glob_buf;
int ret = glob(pattern, GLOB_NOSORT, NULL, &glob_buf);
if (ret == 0) {
for (size_t i = 0; i < glob_buf.gl_pathc; ++i) {
mrsh_array_add(expanded, strdup(glob_buf.gl_pathv[i]));
}
globfree(&glob_buf);
} else if (ret == GLOB_NOMATCH) {
mrsh_array_add(expanded, mrsh_word_str(field));
} else {
fprintf(stderr, "glob failed: %d\n", ret);
free(pattern);
return false;
}
free(pattern);
}
return true;
}
|
890197.c | /* See LICENSE for license details. */
#include <errno.h>
#include <math.h>
#include <limits.h>
#include <locale.h>
#include <signal.h>
#include <sys/select.h>
#include <time.h>
#include <unistd.h>
#include <libgen.h>
#include <X11/Xatom.h>
#include <X11/Xlib.h>
#include <X11/cursorfont.h>
#include <X11/keysym.h>
#include <X11/Xft/Xft.h>
#include <X11/XKBlib.h>
static char *argv0;
#include "arg.h"
#include "st.h"
#include "win.h"
/* types used in config.h */
typedef struct {
uint mod;
KeySym keysym;
void (*func)(const Arg *);
const Arg arg;
} Shortcut;
typedef struct {
uint mod;
uint button;
void (*func)(const Arg *);
const Arg arg;
uint release;
} MouseShortcut;
typedef struct {
KeySym k;
uint mask;
char *s;
/* three-valued logic variables: 0 indifferent, 1 on, -1 off */
signed char appkey; /* application keypad */
signed char appcursor; /* application cursor */
} Key;
/* X modifiers */
#define XK_ANY_MOD UINT_MAX
#define XK_NO_MOD 0
#define XK_SWITCH_MOD (1<<13)
/* function definitions used in config.h */
static void clipcopy(const Arg *);
static void clippaste(const Arg *);
static void numlock(const Arg *);
static void selpaste(const Arg *);
static void zoom(const Arg *);
static void zoomabs(const Arg *);
static void zoomreset(const Arg *);
static void ttysend(const Arg *);
/* config.h for applying patches and the configuration. */
#include "config.h"
/* XEMBED messages */
#define XEMBED_FOCUS_IN 4
#define XEMBED_FOCUS_OUT 5
/* macros */
#define IS_SET(flag) ((win.mode & (flag)) != 0)
#define TRUERED(x) (((x) & 0xff0000) >> 8)
#define TRUEGREEN(x) (((x) & 0xff00))
#define TRUEBLUE(x) (((x) & 0xff) << 8)
typedef XftDraw *Draw;
typedef XftColor Color;
typedef XftGlyphFontSpec GlyphFontSpec;
/* Purely graphic info */
typedef struct {
int tw, th; /* tty width and height */
int w, h; /* window width and height */
int ch; /* char height */
int cw; /* char width */
int mode; /* window state/mode flags */
int cursor; /* cursor style */
} TermWindow;
typedef struct {
Display *dpy;
Colormap cmap;
Window win;
Drawable buf;
GlyphFontSpec *specbuf; /* font spec buffer used for rendering */
Atom xembed, wmdeletewin, netwmname, netwmpid;
struct {
XIM xim;
XIC xic;
XPoint spot;
XVaNestedList spotlist;
} ime;
Draw draw;
Visual *vis;
XSetWindowAttributes attrs;
int scr;
int isfixed; /* is fixed geometry? */
int depth; /* bit depth */
int l, t; /* left and top offset */
int gm; /* geometry mask */
} XWindow;
typedef struct {
Atom xtarget;
char *primary, *clipboard;
struct timespec tclick1;
struct timespec tclick2;
} XSelection;
/* Font structure */
#define Font Font_
typedef struct {
int height;
int width;
int ascent;
int descent;
int badslant;
int badweight;
short lbearing;
short rbearing;
XftFont *match;
FcFontSet *set;
FcPattern *pattern;
} Font;
/* Drawing Context */
typedef struct {
Color *col;
size_t collen;
Font font, bfont, ifont, ibfont;
GC gc;
} DC;
static inline ushort sixd_to_16bit(int);
static int xmakeglyphfontspecs(XftGlyphFontSpec *, const Glyph *, int, int, int);
static void xdrawglyphfontspecs(const XftGlyphFontSpec *, Glyph, int, int, int);
static void xdrawglyph(Glyph, int, int);
static void xclear(int, int, int, int);
static int xgeommasktogravity(int);
static int ximopen(Display *);
static void ximinstantiate(Display *, XPointer, XPointer);
static void ximdestroy(XIM, XPointer, XPointer);
static int xicdestroy(XIC, XPointer, XPointer);
static void xinit(int, int);
static void cresize(int, int);
static void xresize(int, int);
static void xhints(void);
static int xloadcolor(int, const char *, Color *);
static int xloadfont(Font *, FcPattern *);
static void xloadfonts(char *, double);
static void xunloadfont(Font *);
static void xunloadfonts(void);
static void xsetenv(void);
static void xseturgency(int);
static int evcol(XEvent *);
static int evrow(XEvent *);
static void expose(XEvent *);
static void visibility(XEvent *);
static void unmap(XEvent *);
static void kpress(XEvent *);
static void cmessage(XEvent *);
static void resize(XEvent *);
static void focus(XEvent *);
static int mouseaction(XEvent *, uint);
static void brelease(XEvent *);
static void bpress(XEvent *);
static void bmotion(XEvent *);
static void propnotify(XEvent *);
static void selnotify(XEvent *);
static void selclear_(XEvent *);
static void selrequest(XEvent *);
static void setsel(char *, Time);
static void mousesel(XEvent *, int);
static void mousereport(XEvent *);
static char *kmap(KeySym, uint);
static int match(uint, uint);
static void run(void);
static void usage(void);
static void (*handler[LASTEvent])(XEvent *) = {
[KeyPress] = kpress,
[ClientMessage] = cmessage,
[ConfigureNotify] = resize,
[VisibilityNotify] = visibility,
[UnmapNotify] = unmap,
[Expose] = expose,
[FocusIn] = focus,
[FocusOut] = focus,
[MotionNotify] = bmotion,
[ButtonPress] = bpress,
[ButtonRelease] = brelease,
/*
* Uncomment if you want the selection to disappear when you select something
* different in another window.
*/
/* [SelectionClear] = selclear_, */
[SelectionNotify] = selnotify,
/*
* PropertyNotify is only turned on when there is some INCR transfer happening
* for the selection retrieval.
*/
[PropertyNotify] = propnotify,
[SelectionRequest] = selrequest,
};
/* Globals */
static DC dc;
static XWindow xw;
static XSelection xsel;
static TermWindow win;
/* Font Ring Cache */
enum {
FRC_NORMAL,
FRC_ITALIC,
FRC_BOLD,
FRC_ITALICBOLD
};
typedef struct {
XftFont *font;
int flags;
Rune unicodep;
} Fontcache;
/* Fontcache is an array now. A new font will be appended to the array. */
static Fontcache *frc = NULL;
static int frclen = 0;
static int frccap = 0;
static char *usedfont = NULL;
static double usedfontsize = 0;
static double defaultfontsize = 0;
static char *opt_alpha = NULL;
static char *opt_class = NULL;
static char **opt_cmd = NULL;
static char *opt_embed = NULL;
static char *opt_font = NULL;
static char *opt_io = NULL;
static char *opt_line = NULL;
static char *opt_name = NULL;
static char *opt_title = NULL;
static char *opt_dir = NULL;
static int oldbutton = 3; /* button event on startup: 3 = release */
void
clipcopy(const Arg *dummy)
{
Atom clipboard;
free(xsel.clipboard);
xsel.clipboard = NULL;
if (xsel.primary != NULL) {
xsel.clipboard = xstrdup(xsel.primary);
clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
XSetSelectionOwner(xw.dpy, clipboard, xw.win, CurrentTime);
}
}
void
clippaste(const Arg *dummy)
{
Atom clipboard;
clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
XConvertSelection(xw.dpy, clipboard, xsel.xtarget, clipboard,
xw.win, CurrentTime);
}
void
selpaste(const Arg *dummy)
{
XConvertSelection(xw.dpy, XA_PRIMARY, xsel.xtarget, XA_PRIMARY,
xw.win, CurrentTime);
}
void
numlock(const Arg *dummy)
{
win.mode ^= MODE_NUMLOCK;
}
void
zoom(const Arg *arg)
{
Arg larg;
larg.f = usedfontsize + arg->f;
zoomabs(&larg);
}
void
zoomabs(const Arg *arg)
{
xunloadfonts();
xloadfonts(usedfont, arg->f);
cresize(0, 0);
redraw();
xhints();
}
void
zoomreset(const Arg *arg)
{
Arg larg;
if (defaultfontsize > 0) {
larg.f = defaultfontsize;
zoomabs(&larg);
}
}
void
ttysend(const Arg *arg)
{
ttywrite(arg->s, strlen(arg->s), 1);
}
int
evcol(XEvent *e)
{
int x = e->xbutton.x - borderpx;
LIMIT(x, 0, win.tw - 1);
return x / win.cw;
}
int
evrow(XEvent *e)
{
int y = e->xbutton.y - borderpx;
LIMIT(y, 0, win.th - 1);
return y / win.ch;
}
void
mousesel(XEvent *e, int done)
{
int type, seltype = SEL_REGULAR;
uint state = e->xbutton.state & ~(Button1Mask | forcemousemod);
for (type = 1; type < LEN(selmasks); ++type) {
if (match(selmasks[type], state)) {
seltype = type;
break;
}
}
selextend(evcol(e), evrow(e), seltype, done);
if (done)
setsel(getsel(), e->xbutton.time);
}
void
mousereport(XEvent *e)
{
int len, x = evcol(e), y = evrow(e),
button = e->xbutton.button, state = e->xbutton.state;
char buf[40];
static int ox, oy;
/* from urxvt */
if (e->xbutton.type == MotionNotify) {
if (x == ox && y == oy)
return;
if (!IS_SET(MODE_MOUSEMOTION) && !IS_SET(MODE_MOUSEMANY))
return;
/* MOUSE_MOTION: no reporting if no button is pressed */
if (IS_SET(MODE_MOUSEMOTION) && oldbutton == 3)
return;
button = oldbutton + 32;
ox = x;
oy = y;
} else {
if (!IS_SET(MODE_MOUSESGR) && e->xbutton.type == ButtonRelease) {
button = 3;
} else {
button -= Button1;
if (button >= 3)
button += 64 - 3;
}
if (e->xbutton.type == ButtonPress) {
oldbutton = button;
ox = x;
oy = y;
} else if (e->xbutton.type == ButtonRelease) {
oldbutton = 3;
/* MODE_MOUSEX10: no button release reporting */
if (IS_SET(MODE_MOUSEX10))
return;
if (button == 64 || button == 65)
return;
}
}
if (!IS_SET(MODE_MOUSEX10)) {
button += ((state & ShiftMask ) ? 4 : 0)
+ ((state & Mod4Mask ) ? 8 : 0)
+ ((state & ControlMask) ? 16 : 0);
}
if (IS_SET(MODE_MOUSESGR)) {
len = snprintf(buf, sizeof(buf), "\033[<%d;%d;%d%c",
button, x+1, y+1,
e->xbutton.type == ButtonRelease ? 'm' : 'M');
} else if (x < 223 && y < 223) {
len = snprintf(buf, sizeof(buf), "\033[M%c%c%c",
32+button, 32+x+1, 32+y+1);
} else {
return;
}
ttywrite(buf, len, 0);
}
int
mouseaction(XEvent *e, uint release)
{
MouseShortcut *ms;
for (ms = mshortcuts; ms < mshortcuts + LEN(mshortcuts); ms++) {
if (ms->release == release &&
ms->button == e->xbutton.button &&
(match(ms->mod, e->xbutton.state) || /* exact or forced */
match(ms->mod, e->xbutton.state & ~forcemousemod))) {
ms->func(&(ms->arg));
return 1;
}
}
return 0;
}
void
bpress(XEvent *e)
{
struct timespec now;
int snap;
if (IS_SET(MODE_MOUSE) && !(e->xbutton.state & forcemousemod)) {
mousereport(e);
return;
}
if (mouseaction(e, 0))
return;
if (e->xbutton.button == Button1) {
/*
* If the user clicks below predefined timeouts specific
* snapping behaviour is exposed.
*/
clock_gettime(CLOCK_MONOTONIC, &now);
if (TIMEDIFF(now, xsel.tclick2) <= tripleclicktimeout) {
snap = SNAP_LINE;
} else if (TIMEDIFF(now, xsel.tclick1) <= doubleclicktimeout) {
snap = SNAP_WORD;
} else {
snap = 0;
}
xsel.tclick2 = xsel.tclick1;
xsel.tclick1 = now;
selstart(evcol(e), evrow(e), snap);
}
}
void
propnotify(XEvent *e)
{
XPropertyEvent *xpev;
Atom clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
xpev = &e->xproperty;
if (xpev->state == PropertyNewValue &&
(xpev->atom == XA_PRIMARY ||
xpev->atom == clipboard)) {
selnotify(e);
}
}
void
selnotify(XEvent *e)
{
ulong nitems, ofs, rem;
int format;
uchar *data, *last, *repl;
Atom type, incratom, property = None;
incratom = XInternAtom(xw.dpy, "INCR", 0);
ofs = 0;
if (e->type == SelectionNotify)
property = e->xselection.property;
else if (e->type == PropertyNotify)
property = e->xproperty.atom;
if (property == None)
return;
do {
if (XGetWindowProperty(xw.dpy, xw.win, property, ofs,
BUFSIZ/4, False, AnyPropertyType,
&type, &format, &nitems, &rem,
&data)) {
fprintf(stderr, "Clipboard allocation failed\n");
return;
}
if (e->type == PropertyNotify && nitems == 0 && rem == 0) {
/*
* If there is some PropertyNotify with no data, then
* this is the signal of the selection owner that all
* data has been transferred. We won't need to receive
* PropertyNotify events anymore.
*/
MODBIT(xw.attrs.event_mask, 0, PropertyChangeMask);
XChangeWindowAttributes(xw.dpy, xw.win, CWEventMask,
&xw.attrs);
}
if (type == incratom) {
/*
* Activate the PropertyNotify events so we receive
* when the selection owner does send us the next
* chunk of data.
*/
MODBIT(xw.attrs.event_mask, 1, PropertyChangeMask);
XChangeWindowAttributes(xw.dpy, xw.win, CWEventMask,
&xw.attrs);
/*
* Deleting the property is the transfer start signal.
*/
XDeleteProperty(xw.dpy, xw.win, (int)property);
continue;
}
/*
* As seen in getsel:
* Line endings are inconsistent in the terminal and GUI world
* copy and pasting. When receiving some selection data,
* replace all '\n' with '\r'.
* FIXME: Fix the computer world.
*/
repl = data;
last = data + nitems * format / 8;
while ((repl = memchr(repl, '\n', last - repl))) {
*repl++ = '\r';
}
if (IS_SET(MODE_BRCKTPASTE) && ofs == 0)
ttywrite("\033[200~", 6, 0);
ttywrite((char *)data, nitems * format / 8, 1);
if (IS_SET(MODE_BRCKTPASTE) && rem == 0)
ttywrite("\033[201~", 6, 0);
XFree(data);
/* number of 32-bit chunks returned */
ofs += nitems * format / 32;
} while (rem > 0);
/*
* Deleting the property again tells the selection owner to send the
* next data chunk in the property.
*/
XDeleteProperty(xw.dpy, xw.win, (int)property);
}
void
xclipcopy(void)
{
clipcopy(NULL);
}
void
selclear_(XEvent *e)
{
selclear();
}
void
selrequest(XEvent *e)
{
XSelectionRequestEvent *xsre;
XSelectionEvent xev;
Atom xa_targets, string, clipboard;
char *seltext;
xsre = (XSelectionRequestEvent *) e;
xev.type = SelectionNotify;
xev.requestor = xsre->requestor;
xev.selection = xsre->selection;
xev.target = xsre->target;
xev.time = xsre->time;
if (xsre->property == None)
xsre->property = xsre->target;
/* reject */
xev.property = None;
xa_targets = XInternAtom(xw.dpy, "TARGETS", 0);
if (xsre->target == xa_targets) {
/* respond with the supported type */
string = xsel.xtarget;
XChangeProperty(xsre->display, xsre->requestor, xsre->property,
XA_ATOM, 32, PropModeReplace,
(uchar *) &string, 1);
xev.property = xsre->property;
} else if (xsre->target == xsel.xtarget || xsre->target == XA_STRING) {
/*
* xith XA_STRING non ascii characters may be incorrect in the
* requestor. It is not our problem, use utf8.
*/
clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
if (xsre->selection == XA_PRIMARY) {
seltext = xsel.primary;
} else if (xsre->selection == clipboard) {
seltext = xsel.clipboard;
} else {
fprintf(stderr,
"Unhandled clipboard selection 0x%lx\n",
xsre->selection);
return;
}
if (seltext != NULL) {
XChangeProperty(xsre->display, xsre->requestor,
xsre->property, xsre->target,
8, PropModeReplace,
(uchar *)seltext, strlen(seltext));
xev.property = xsre->property;
}
}
/* all done, send a notification to the listener */
if (!XSendEvent(xsre->display, xsre->requestor, 1, 0, (XEvent *) &xev))
fprintf(stderr, "Error sending SelectionNotify event\n");
}
void
setsel(char *str, Time t)
{
if (!str)
return;
free(xsel.primary);
xsel.primary = str;
XSetSelectionOwner(xw.dpy, XA_PRIMARY, xw.win, t);
if (XGetSelectionOwner(xw.dpy, XA_PRIMARY) != xw.win)
selclear();
}
void
xsetsel(char *str)
{
setsel(str, CurrentTime);
}
void
brelease(XEvent *e)
{
if (IS_SET(MODE_MOUSE) && !(e->xbutton.state & forcemousemod)) {
mousereport(e);
return;
}
if (mouseaction(e, 1))
return;
if (e->xbutton.button == Button1)
mousesel(e, 1);
else if (e->xbutton.button == Button3)
clippaste(NULL);
}
void
bmotion(XEvent *e)
{
if (IS_SET(MODE_MOUSE) && !(e->xbutton.state & forcemousemod)) {
mousereport(e);
return;
}
mousesel(e, 0);
}
void
cresize(int width, int height)
{
int col, row;
if (width != 0)
win.w = width;
if (height != 0)
win.h = height;
col = (win.w - 2 * borderpx) / win.cw;
row = (win.h - 2 * borderpx) / win.ch;
col = MAX(1, col);
row = MAX(1, row);
tresize(col, row);
xresize(col, row);
ttyresize(win.tw, win.th);
}
void
xresize(int col, int row)
{
win.tw = col * win.cw;
win.th = row * win.ch;
XFreePixmap(xw.dpy, xw.buf);
xw.buf = XCreatePixmap(xw.dpy, xw.win, win.w, win.h,
xw.depth);
XftDrawChange(xw.draw, xw.buf);
xclear(0, 0, win.w, win.h);
/* resize to new width */
xw.specbuf = xrealloc(xw.specbuf, col * sizeof(GlyphFontSpec));
}
ushort
sixd_to_16bit(int x)
{
return x == 0 ? 0 : 0x3737 + 0x2828 * x;
}
int
xloadcolor(int i, const char *name, Color *ncolor)
{
XRenderColor color = { .alpha = 0xffff };
if (!name) {
if (BETWEEN(i, 16, 255)) { /* 256 color */
if (i < 6*6*6+16) { /* same colors as xterm */
color.red = sixd_to_16bit( ((i-16)/36)%6 );
color.green = sixd_to_16bit( ((i-16)/6) %6 );
color.blue = sixd_to_16bit( ((i-16)/1) %6 );
} else { /* greyscale */
color.red = 0x0808 + 0x0a0a * (i - (6*6*6+16));
color.green = color.blue = color.red;
}
return XftColorAllocValue(xw.dpy, xw.vis,
xw.cmap, &color, ncolor);
} else
name = colorname[i];
}
return XftColorAllocName(xw.dpy, xw.vis, xw.cmap, name, ncolor);
}
void
xloadcols(void)
{
int i;
static int loaded;
Color *cp;
if (loaded) {
for (cp = dc.col; cp < &dc.col[dc.collen]; ++cp)
XftColorFree(xw.dpy, xw.vis, xw.cmap, cp);
} else {
dc.collen = MAX(LEN(colorname), 256);
dc.col = xmalloc(dc.collen * sizeof(Color));
}
for (i = 0; i < dc.collen; i++)
if (!xloadcolor(i, NULL, &dc.col[i])) {
if (colorname[i])
die("could not allocate color '%s'\n", colorname[i]);
else
die("could not allocate color %d\n", i);
}
/* set alpha value of bg color */
if (opt_alpha)
alpha = strtof(opt_alpha, NULL);
dc.col[defaultbg].color.alpha = (unsigned short)(0xffff * alpha);
dc.col[defaultbg].pixel &= 0x00FFFFFF;
dc.col[defaultbg].pixel |= (unsigned char)(0xff * alpha) << 24;
loaded = 1;
}
int
xsetcolorname(int x, const char *name)
{
Color ncolor;
if (!BETWEEN(x, 0, dc.collen))
return 1;
if (!xloadcolor(x, name, &ncolor))
return 1;
XftColorFree(xw.dpy, xw.vis, xw.cmap, &dc.col[x]);
dc.col[x] = ncolor;
return 0;
}
/*
* Absolute coordinates.
*/
void
xclear(int x1, int y1, int x2, int y2)
{
XftDrawRect(xw.draw,
&dc.col[IS_SET(MODE_REVERSE)? defaultfg : defaultbg],
x1, y1, x2-x1, y2-y1);
}
void
xhints(void)
{
XClassHint class = {opt_name ? opt_name : termname,
opt_class ? opt_class : termname};
XWMHints wm = {.flags = InputHint, .input = 1};
XSizeHints *sizeh;
sizeh = XAllocSizeHints();
sizeh->flags = PSize | PResizeInc | PBaseSize | PMinSize;
sizeh->height = win.h;
sizeh->width = win.w;
sizeh->height_inc = win.ch;
sizeh->width_inc = win.cw;
sizeh->base_height = 2 * borderpx;
sizeh->base_width = 2 * borderpx;
sizeh->min_height = win.ch + 2 * borderpx;
sizeh->min_width = win.cw + 2 * borderpx;
if (xw.isfixed) {
sizeh->flags |= PMaxSize;
sizeh->min_width = sizeh->max_width = win.w;
sizeh->min_height = sizeh->max_height = win.h;
}
if (xw.gm & (XValue|YValue)) {
sizeh->flags |= USPosition | PWinGravity;
sizeh->x = xw.l;
sizeh->y = xw.t;
sizeh->win_gravity = xgeommasktogravity(xw.gm);
}
XSetWMProperties(xw.dpy, xw.win, NULL, NULL, NULL, 0, sizeh, &wm,
&class);
XFree(sizeh);
}
int
xgeommasktogravity(int mask)
{
switch (mask & (XNegative|YNegative)) {
case 0:
return NorthWestGravity;
case XNegative:
return NorthEastGravity;
case YNegative:
return SouthWestGravity;
}
return SouthEastGravity;
}
int
xloadfont(Font *f, FcPattern *pattern)
{
FcPattern *configured;
FcPattern *match;
FcResult result;
XGlyphInfo extents;
int wantattr, haveattr;
/*
* Manually configure instead of calling XftMatchFont
* so that we can use the configured pattern for
* "missing glyph" lookups.
*/
configured = FcPatternDuplicate(pattern);
if (!configured)
return 1;
FcConfigSubstitute(NULL, configured, FcMatchPattern);
XftDefaultSubstitute(xw.dpy, xw.scr, configured);
match = FcFontMatch(NULL, configured, &result);
if (!match) {
FcPatternDestroy(configured);
return 1;
}
if (!(f->match = XftFontOpenPattern(xw.dpy, match))) {
FcPatternDestroy(configured);
FcPatternDestroy(match);
return 1;
}
if ((XftPatternGetInteger(pattern, "slant", 0, &wantattr) ==
XftResultMatch)) {
/*
* Check if xft was unable to find a font with the appropriate
* slant but gave us one anyway. Try to mitigate.
*/
if ((XftPatternGetInteger(f->match->pattern, "slant", 0,
&haveattr) != XftResultMatch) || haveattr < wantattr) {
f->badslant = 1;
fputs("font slant does not match\n", stderr);
}
}
if ((XftPatternGetInteger(pattern, "weight", 0, &wantattr) ==
XftResultMatch)) {
if ((XftPatternGetInteger(f->match->pattern, "weight", 0,
&haveattr) != XftResultMatch) || haveattr != wantattr) {
f->badweight = 1;
fputs("font weight does not match\n", stderr);
}
}
XftTextExtentsUtf8(xw.dpy, f->match,
(const FcChar8 *) ascii_printable,
strlen(ascii_printable), &extents);
f->set = NULL;
f->pattern = configured;
f->ascent = f->match->ascent;
f->descent = f->match->descent;
f->lbearing = 0;
f->rbearing = f->match->max_advance_width;
f->height = f->ascent + f->descent;
f->width = DIVCEIL(extents.xOff, strlen(ascii_printable));
return 0;
}
void
xloadfonts(char *fontstr, double fontsize)
{
FcPattern *pattern;
double fontval;
if (fontstr[0] == '-')
pattern = XftXlfdParse(fontstr, False, False);
else
pattern = FcNameParse((FcChar8 *)fontstr);
if (!pattern)
die("can't open font %s\n", fontstr);
if (fontsize > 1) {
FcPatternDel(pattern, FC_PIXEL_SIZE);
FcPatternDel(pattern, FC_SIZE);
FcPatternAddDouble(pattern, FC_PIXEL_SIZE, (double)fontsize);
usedfontsize = fontsize;
} else {
if (FcPatternGetDouble(pattern, FC_PIXEL_SIZE, 0, &fontval) ==
FcResultMatch) {
usedfontsize = fontval;
} else if (FcPatternGetDouble(pattern, FC_SIZE, 0, &fontval) ==
FcResultMatch) {
usedfontsize = -1;
} else {
/*
* Default font size is 12, if none given. This is to
* have a known usedfontsize value.
*/
FcPatternAddDouble(pattern, FC_PIXEL_SIZE, 12);
usedfontsize = 12;
}
defaultfontsize = usedfontsize;
}
if (xloadfont(&dc.font, pattern))
die("can't open font %s\n", fontstr);
if (usedfontsize < 0) {
FcPatternGetDouble(dc.font.match->pattern,
FC_PIXEL_SIZE, 0, &fontval);
usedfontsize = fontval;
if (fontsize == 0)
defaultfontsize = fontval;
}
/* Setting character width and height. */
win.cw = ceilf(dc.font.width * cwscale);
win.ch = ceilf(dc.font.height * chscale);
FcPatternDel(pattern, FC_SLANT);
FcPatternAddInteger(pattern, FC_SLANT, FC_SLANT_ITALIC);
if (xloadfont(&dc.ifont, pattern))
die("can't open font %s\n", fontstr);
FcPatternDel(pattern, FC_WEIGHT);
FcPatternAddInteger(pattern, FC_WEIGHT, FC_WEIGHT_BOLD);
if (xloadfont(&dc.ibfont, pattern))
die("can't open font %s\n", fontstr);
FcPatternDel(pattern, FC_SLANT);
FcPatternAddInteger(pattern, FC_SLANT, FC_SLANT_ROMAN);
if (xloadfont(&dc.bfont, pattern))
die("can't open font %s\n", fontstr);
FcPatternDestroy(pattern);
}
void
xunloadfont(Font *f)
{
XftFontClose(xw.dpy, f->match);
FcPatternDestroy(f->pattern);
if (f->set)
FcFontSetDestroy(f->set);
}
void
xunloadfonts(void)
{
/* Free the loaded fonts in the font cache. */
while (frclen > 0)
XftFontClose(xw.dpy, frc[--frclen].font);
xunloadfont(&dc.font);
xunloadfont(&dc.bfont);
xunloadfont(&dc.ifont);
xunloadfont(&dc.ibfont);
}
int
ximopen(Display *dpy)
{
XIMCallback imdestroy = { .client_data = NULL, .callback = ximdestroy };
XICCallback icdestroy = { .client_data = NULL, .callback = xicdestroy };
xw.ime.xim = XOpenIM(xw.dpy, NULL, NULL, NULL);
if (xw.ime.xim == NULL)
return 0;
if (XSetIMValues(xw.ime.xim, XNDestroyCallback, &imdestroy, NULL))
fprintf(stderr, "XSetIMValues: "
"Could not set XNDestroyCallback.\n");
xw.ime.spotlist = XVaCreateNestedList(0, XNSpotLocation, &xw.ime.spot,
NULL);
if (xw.ime.xic == NULL) {
xw.ime.xic = XCreateIC(xw.ime.xim, XNInputStyle,
XIMPreeditNothing | XIMStatusNothing,
XNClientWindow, xw.win,
XNDestroyCallback, &icdestroy,
NULL);
}
if (xw.ime.xic == NULL)
fprintf(stderr, "XCreateIC: Could not create input context.\n");
return 1;
}
void
ximinstantiate(Display *dpy, XPointer client, XPointer call)
{
if (ximopen(dpy))
XUnregisterIMInstantiateCallback(xw.dpy, NULL, NULL, NULL,
ximinstantiate, NULL);
}
void
ximdestroy(XIM xim, XPointer client, XPointer call)
{
xw.ime.xim = NULL;
XRegisterIMInstantiateCallback(xw.dpy, NULL, NULL, NULL,
ximinstantiate, NULL);
XFree(xw.ime.spotlist);
}
int
xicdestroy(XIC xim, XPointer client, XPointer call)
{
xw.ime.xic = NULL;
return 1;
}
void
xinit(int cols, int rows)
{
XGCValues gcvalues;
Cursor cursor;
Window parent;
pid_t thispid = getpid();
XColor xmousefg, xmousebg;
XWindowAttributes attr;
XVisualInfo vis;
if (!(xw.dpy = XOpenDisplay(NULL)))
die("can't open display\n");
xw.scr = XDefaultScreen(xw.dpy);
if (!(opt_embed && (parent = strtol(opt_embed, NULL, 0)))) {
parent = XRootWindow(xw.dpy, xw.scr);
xw.depth = 32;
} else {
XGetWindowAttributes(xw.dpy, parent, &attr);
xw.depth = attr.depth;
}
XMatchVisualInfo(xw.dpy, xw.scr, xw.depth, TrueColor, &vis);
xw.vis = vis.visual;
/* font */
if (!FcInit())
die("could not init fontconfig.\n");
usedfont = (opt_font == NULL)? font : opt_font;
xloadfonts(usedfont, 0);
/* colors */
xw.cmap = XCreateColormap(xw.dpy, parent, xw.vis, None);
xloadcols();
/* adjust fixed window geometry */
win.w = 2 * borderpx + cols * win.cw;
win.h = 2 * borderpx + rows * win.ch;
if (xw.gm & XNegative)
xw.l += DisplayWidth(xw.dpy, xw.scr) - win.w - 2;
if (xw.gm & YNegative)
xw.t += DisplayHeight(xw.dpy, xw.scr) - win.h - 2;
/* Events */
xw.attrs.background_pixel = dc.col[defaultbg].pixel;
xw.attrs.border_pixel = dc.col[defaultbg].pixel;
xw.attrs.bit_gravity = NorthWestGravity;
xw.attrs.event_mask = FocusChangeMask | KeyPressMask | KeyReleaseMask
| ExposureMask | VisibilityChangeMask | StructureNotifyMask
| ButtonMotionMask | ButtonPressMask | ButtonReleaseMask;
xw.attrs.colormap = xw.cmap;
xw.win = XCreateWindow(xw.dpy, parent, xw.l, xw.t,
win.w, win.h, 0, xw.depth, InputOutput,
xw.vis, CWBackPixel | CWBorderPixel | CWBitGravity
| CWEventMask | CWColormap, &xw.attrs);
memset(&gcvalues, 0, sizeof(gcvalues));
gcvalues.graphics_exposures = False;
xw.buf = XCreatePixmap(xw.dpy, xw.win, win.w, win.h, xw.depth);
dc.gc = XCreateGC(xw.dpy, xw.buf, GCGraphicsExposures, &gcvalues);
XSetForeground(xw.dpy, dc.gc, dc.col[defaultbg].pixel);
XFillRectangle(xw.dpy, xw.buf, dc.gc, 0, 0, win.w, win.h);
/* font spec buffer */
xw.specbuf = xmalloc(cols * sizeof(GlyphFontSpec));
/* Xft rendering context */
xw.draw = XftDrawCreate(xw.dpy, xw.buf, xw.vis, xw.cmap);
/* input methods */
if (!ximopen(xw.dpy)) {
XRegisterIMInstantiateCallback(xw.dpy, NULL, NULL, NULL,
ximinstantiate, NULL);
}
/* white cursor, black outline */
cursor = XCreateFontCursor(xw.dpy, mouseshape);
XDefineCursor(xw.dpy, xw.win, cursor);
if (XParseColor(xw.dpy, xw.cmap, colorname[mousefg], &xmousefg) == 0) {
xmousefg.red = 0xffff;
xmousefg.green = 0xffff;
xmousefg.blue = 0xffff;
}
if (XParseColor(xw.dpy, xw.cmap, colorname[mousebg], &xmousebg) == 0) {
xmousebg.red = 0x0000;
xmousebg.green = 0x0000;
xmousebg.blue = 0x0000;
}
XRecolorCursor(xw.dpy, cursor, &xmousefg, &xmousebg);
xw.xembed = XInternAtom(xw.dpy, "_XEMBED", False);
xw.wmdeletewin = XInternAtom(xw.dpy, "WM_DELETE_WINDOW", False);
xw.netwmname = XInternAtom(xw.dpy, "_NET_WM_NAME", False);
XSetWMProtocols(xw.dpy, xw.win, &xw.wmdeletewin, 1);
xw.netwmpid = XInternAtom(xw.dpy, "_NET_WM_PID", False);
XChangeProperty(xw.dpy, xw.win, xw.netwmpid, XA_CARDINAL, 32,
PropModeReplace, (uchar *)&thispid, 1);
win.mode = MODE_NUMLOCK;
resettitle();
xhints();
XMapWindow(xw.dpy, xw.win);
XSync(xw.dpy, False);
clock_gettime(CLOCK_MONOTONIC, &xsel.tclick1);
clock_gettime(CLOCK_MONOTONIC, &xsel.tclick2);
xsel.primary = NULL;
xsel.clipboard = NULL;
xsel.xtarget = XInternAtom(xw.dpy, "UTF8_STRING", 0);
if (xsel.xtarget == None)
xsel.xtarget = XA_STRING;
boxdraw_xinit(xw.dpy, xw.cmap, xw.draw, xw.vis);
}
int
xmakeglyphfontspecs(XftGlyphFontSpec *specs, const Glyph *glyphs, int len, int x, int y)
{
float winx = borderpx + x * win.cw, winy = borderpx + y * win.ch, xp, yp;
ushort mode, prevmode = USHRT_MAX;
Font *font = &dc.font;
int frcflags = FRC_NORMAL;
float runewidth = win.cw;
Rune rune;
FT_UInt glyphidx;
FcResult fcres;
FcPattern *fcpattern, *fontpattern;
FcFontSet *fcsets[] = { NULL };
FcCharSet *fccharset;
int i, f, numspecs = 0;
for (i = 0, xp = winx, yp = winy + font->ascent; i < len; ++i) {
/* Fetch rune and mode for current glyph. */
rune = glyphs[i].u;
mode = glyphs[i].mode;
/* Skip dummy wide-character spacing. */
if (mode == ATTR_WDUMMY)
continue;
/* Determine font for glyph if different from previous glyph. */
if (prevmode != mode) {
prevmode = mode;
font = &dc.font;
frcflags = FRC_NORMAL;
runewidth = win.cw * ((mode & ATTR_WIDE) ? 2.0f : 1.0f);
if ((mode & ATTR_ITALIC) && (mode & ATTR_BOLD)) {
font = &dc.ibfont;
frcflags = FRC_ITALICBOLD;
} else if (mode & ATTR_ITALIC) {
font = &dc.ifont;
frcflags = FRC_ITALIC;
} else if (mode & ATTR_BOLD) {
font = &dc.bfont;
frcflags = FRC_BOLD;
}
yp = winy + font->ascent;
}
if (mode & ATTR_BOXDRAW) {
/* minor shoehorning: boxdraw uses only this ushort */
glyphidx = boxdrawindex(&glyphs[i]);
} else {
/* Lookup character index with default font. */
glyphidx = XftCharIndex(xw.dpy, font->match, rune);
}
if (glyphidx) {
specs[numspecs].font = font->match;
specs[numspecs].glyph = glyphidx;
specs[numspecs].x = (short)xp;
specs[numspecs].y = (short)yp;
xp += runewidth;
numspecs++;
continue;
}
/* Fallback on font cache, search the font cache for match. */
for (f = 0; f < frclen; f++) {
glyphidx = XftCharIndex(xw.dpy, frc[f].font, rune);
/* Everything correct. */
if (glyphidx && frc[f].flags == frcflags)
break;
/* We got a default font for a not found glyph. */
if (!glyphidx && frc[f].flags == frcflags
&& frc[f].unicodep == rune) {
break;
}
}
/* Nothing was found. Use fontconfig to find matching font. */
if (f >= frclen) {
if (!font->set)
font->set = FcFontSort(0, font->pattern,
1, 0, &fcres);
fcsets[0] = font->set;
/*
* Nothing was found in the cache. Now use
* some dozen of Fontconfig calls to get the
* font for one single character.
*
* Xft and fontconfig are design failures.
*/
fcpattern = FcPatternDuplicate(font->pattern);
fccharset = FcCharSetCreate();
FcCharSetAddChar(fccharset, rune);
FcPatternAddCharSet(fcpattern, FC_CHARSET,
fccharset);
FcPatternAddBool(fcpattern, FC_SCALABLE, 1);
FcConfigSubstitute(0, fcpattern,
FcMatchPattern);
FcDefaultSubstitute(fcpattern);
fontpattern = FcFontSetMatch(0, fcsets, 1,
fcpattern, &fcres);
/* Allocate memory for the new cache entry. */
if (frclen >= frccap) {
frccap += 16;
frc = xrealloc(frc, frccap * sizeof(Fontcache));
}
frc[frclen].font = XftFontOpenPattern(xw.dpy,
fontpattern);
if (!frc[frclen].font)
die("XftFontOpenPattern failed seeking fallback font: %s\n",
strerror(errno));
frc[frclen].flags = frcflags;
frc[frclen].unicodep = rune;
glyphidx = XftCharIndex(xw.dpy, frc[frclen].font, rune);
f = frclen;
frclen++;
FcPatternDestroy(fcpattern);
FcCharSetDestroy(fccharset);
}
specs[numspecs].font = frc[f].font;
specs[numspecs].glyph = glyphidx;
specs[numspecs].x = (short)xp;
specs[numspecs].y = (short)yp;
xp += runewidth;
numspecs++;
}
return numspecs;
}
void
xdrawglyphfontspecs(const XftGlyphFontSpec *specs, Glyph base, int len, int x, int y)
{
int charlen = len * ((base.mode & ATTR_WIDE) ? 2 : 1);
int winx = borderpx + x * win.cw, winy = borderpx + y * win.ch,
width = charlen * win.cw;
Color *fg, *bg, *temp, revfg, revbg, truefg, truebg;
XRenderColor colfg, colbg;
XRectangle r;
/* Fallback on color display for attributes not supported by the font */
if (base.mode & ATTR_ITALIC && base.mode & ATTR_BOLD) {
if (dc.ibfont.badslant || dc.ibfont.badweight)
base.fg = defaultattr;
} else if ((base.mode & ATTR_ITALIC && dc.ifont.badslant) ||
(base.mode & ATTR_BOLD && dc.bfont.badweight)) {
base.fg = defaultattr;
}
if (IS_TRUECOL(base.fg)) {
colfg.alpha = 0xffff;
colfg.red = TRUERED(base.fg);
colfg.green = TRUEGREEN(base.fg);
colfg.blue = TRUEBLUE(base.fg);
XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg, &truefg);
fg = &truefg;
} else {
fg = &dc.col[base.fg];
}
if (IS_TRUECOL(base.bg)) {
colbg.alpha = 0xffff;
colbg.green = TRUEGREEN(base.bg);
colbg.red = TRUERED(base.bg);
colbg.blue = TRUEBLUE(base.bg);
XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colbg, &truebg);
bg = &truebg;
} else {
bg = &dc.col[base.bg];
}
if (IS_SET(MODE_REVERSE)) {
if (fg == &dc.col[defaultfg]) {
fg = &dc.col[defaultbg];
} else {
colfg.red = ~fg->color.red;
colfg.green = ~fg->color.green;
colfg.blue = ~fg->color.blue;
colfg.alpha = fg->color.alpha;
XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg,
&revfg);
fg = &revfg;
}
if (bg == &dc.col[defaultbg]) {
bg = &dc.col[defaultfg];
} else {
colbg.red = ~bg->color.red;
colbg.green = ~bg->color.green;
colbg.blue = ~bg->color.blue;
colbg.alpha = bg->color.alpha;
XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colbg,
&revbg);
bg = &revbg;
}
}
if ((base.mode & ATTR_BOLD_FAINT) == ATTR_FAINT) {
colfg.red = fg->color.red / 2;
colfg.green = fg->color.green / 2;
colfg.blue = fg->color.blue / 2;
colfg.alpha = fg->color.alpha;
XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg, &revfg);
fg = &revfg;
}
if (base.mode & ATTR_REVERSE) {
temp = fg;
fg = bg;
bg = temp;
}
if (base.mode & ATTR_BLINK && win.mode & MODE_BLINK)
fg = bg;
if (base.mode & ATTR_INVISIBLE)
fg = bg;
/* Intelligent cleaning up of the borders. */
if (x == 0) {
xclear(0, (y == 0)? 0 : winy, borderpx,
winy + win.ch +
((winy + win.ch >= borderpx + win.th)? win.h : 0));
}
if (winx + width >= borderpx + win.tw) {
xclear(winx + width, (y == 0)? 0 : winy, win.w,
((winy + win.ch >= borderpx + win.th)? win.h : (winy + win.ch)));
}
if (y == 0)
xclear(winx, 0, winx + width, borderpx);
if (winy + win.ch >= borderpx + win.th)
xclear(winx, winy + win.ch, winx + width, win.h);
/* Clean up the region we want to draw to. */
XftDrawRect(xw.draw, bg, winx, winy, width, win.ch);
/* Set the clip region because Xft is sometimes dirty. */
r.x = 0;
r.y = 0;
r.height = win.ch;
r.width = width;
XftDrawSetClipRectangles(xw.draw, winx, winy, &r, 1);
if (base.mode & ATTR_BOXDRAW) {
drawboxes(winx, winy, width / len, win.ch, fg, bg, specs, len);
} else {
/* Render the glyphs. */
XftDrawGlyphFontSpec(xw.draw, fg, specs, len);
}
/* Render underline and strikethrough. */
if (base.mode & ATTR_UNDERLINE) {
XftDrawRect(xw.draw, fg, winx, winy + dc.font.ascent + 1,
width, 1);
}
if (base.mode & ATTR_STRUCK) {
XftDrawRect(xw.draw, fg, winx, winy + 2 * dc.font.ascent / 3,
width, 1);
}
/* Reset clip to none. */
XftDrawSetClip(xw.draw, 0);
}
void
xdrawglyph(Glyph g, int x, int y)
{
int numspecs;
XftGlyphFontSpec spec;
numspecs = xmakeglyphfontspecs(&spec, &g, 1, x, y);
xdrawglyphfontspecs(&spec, g, numspecs, x, y);
}
void
xdrawcursor(int cx, int cy, Glyph g, int ox, int oy, Glyph og)
{
Color drawcol;
/* remove the old cursor */
if (selected(ox, oy))
og.mode ^= ATTR_REVERSE;
xdrawglyph(og, ox, oy);
if (IS_SET(MODE_HIDE))
return;
/*
* Select the right color for the right mode.
*/
g.mode &= ATTR_BOLD|ATTR_ITALIC|ATTR_UNDERLINE|ATTR_STRUCK|ATTR_WIDE|ATTR_BOXDRAW;
if (IS_SET(MODE_REVERSE)) {
g.mode |= ATTR_REVERSE;
g.bg = defaultfg;
if (selected(cx, cy)) {
drawcol = dc.col[defaultcs];
g.fg = defaultrcs;
} else {
drawcol = dc.col[defaultrcs];
g.fg = defaultcs;
}
} else {
if (selected(cx, cy)) {
g.fg = defaultfg;
g.bg = defaultrcs;
} else {
g.fg = defaultbg;
g.bg = defaultcs;
}
drawcol = dc.col[g.bg];
}
/* draw the new one */
if (IS_SET(MODE_FOCUSED)) {
switch (win.cursor) {
case 7: /* st extension: snowman (U+2603) */
g.u = 0x2603;
case 0: /* Blinking Block */
case 1: /* Blinking Block (Default) */
case 2: /* Steady Block */
xdrawglyph(g, cx, cy);
break;
case 3: /* Blinking Underline */
case 4: /* Steady Underline */
XftDrawRect(xw.draw, &drawcol,
borderpx + cx * win.cw,
borderpx + (cy + 1) * win.ch - \
cursorthickness,
win.cw, cursorthickness);
break;
case 5: /* Blinking bar */
case 6: /* Steady bar */
XftDrawRect(xw.draw, &drawcol,
borderpx + cx * win.cw,
borderpx + cy * win.ch,
cursorthickness, win.ch);
break;
}
} else {
XftDrawRect(xw.draw, &drawcol,
borderpx + cx * win.cw,
borderpx + cy * win.ch,
win.cw - 1, 1);
XftDrawRect(xw.draw, &drawcol,
borderpx + cx * win.cw,
borderpx + cy * win.ch,
1, win.ch - 1);
XftDrawRect(xw.draw, &drawcol,
borderpx + (cx + 1) * win.cw - 1,
borderpx + cy * win.ch,
1, win.ch - 1);
XftDrawRect(xw.draw, &drawcol,
borderpx + cx * win.cw,
borderpx + (cy + 1) * win.ch - 1,
win.cw, 1);
}
}
void
xsetenv(void)
{
char buf[sizeof(long) * 8 + 1];
snprintf(buf, sizeof(buf), "%lu", xw.win);
setenv("WINDOWID", buf, 1);
}
void
xsettitle(char *p)
{
XTextProperty prop;
DEFAULT(p, opt_title);
Xutf8TextListToTextProperty(xw.dpy, &p, 1, XUTF8StringStyle,
&prop);
XSetWMName(xw.dpy, xw.win, &prop);
XSetTextProperty(xw.dpy, xw.win, &prop, xw.netwmname);
XFree(prop.value);
}
int
xstartdraw(void)
{
return IS_SET(MODE_VISIBLE);
}
void
xdrawline(Line line, int x1, int y1, int x2)
{
int i, x, ox, numspecs;
Glyph base, new;
XftGlyphFontSpec *specs = xw.specbuf;
numspecs = xmakeglyphfontspecs(specs, &line[x1], x2 - x1, x1, y1);
i = ox = 0;
for (x = x1; x < x2 && i < numspecs; x++) {
new = line[x];
if (new.mode == ATTR_WDUMMY)
continue;
if (selected(x, y1))
new.mode ^= ATTR_REVERSE;
if (i > 0 && ATTRCMP(base, new)) {
xdrawglyphfontspecs(specs, base, i, ox, y1);
specs += i;
numspecs -= i;
i = 0;
}
if (i == 0) {
ox = x;
base = new;
}
i++;
}
if (i > 0)
xdrawglyphfontspecs(specs, base, i, ox, y1);
}
void
xfinishdraw(void)
{
XCopyArea(xw.dpy, xw.buf, xw.win, dc.gc, 0, 0, win.w,
win.h, 0, 0);
XSetForeground(xw.dpy, dc.gc,
dc.col[IS_SET(MODE_REVERSE)?
defaultfg : defaultbg].pixel);
}
void
xximspot(int x, int y)
{
if (xw.ime.xic == NULL)
return;
xw.ime.spot.x = borderpx + x * win.cw;
xw.ime.spot.y = borderpx + (y + 1) * win.ch;
XSetICValues(xw.ime.xic, XNPreeditAttributes, xw.ime.spotlist, NULL);
}
void
expose(XEvent *ev)
{
redraw();
}
void
visibility(XEvent *ev)
{
XVisibilityEvent *e = &ev->xvisibility;
MODBIT(win.mode, e->state != VisibilityFullyObscured, MODE_VISIBLE);
}
void
unmap(XEvent *ev)
{
win.mode &= ~MODE_VISIBLE;
}
void
xsetpointermotion(int set)
{
MODBIT(xw.attrs.event_mask, set, PointerMotionMask);
XChangeWindowAttributes(xw.dpy, xw.win, CWEventMask, &xw.attrs);
}
void
xsetmode(int set, unsigned int flags)
{
int mode = win.mode;
MODBIT(win.mode, set, flags);
if ((win.mode & MODE_REVERSE) != (mode & MODE_REVERSE))
redraw();
}
int
xsetcursor(int cursor)
{
DEFAULT(cursor, 1);
if (!BETWEEN(cursor, 0, 6))
return 1;
win.cursor = cursor;
return 0;
}
void
xseturgency(int add)
{
XWMHints *h = XGetWMHints(xw.dpy, xw.win);
MODBIT(h->flags, add, XUrgencyHint);
XSetWMHints(xw.dpy, xw.win, h);
XFree(h);
}
void
xbell(void)
{
if (!(IS_SET(MODE_FOCUSED)))
xseturgency(1);
if (bellvolume)
XkbBell(xw.dpy, xw.win, bellvolume, (Atom)NULL);
}
void
focus(XEvent *ev)
{
XFocusChangeEvent *e = &ev->xfocus;
if (e->mode == NotifyGrab)
return;
if (ev->type == FocusIn) {
if (xw.ime.xic)
XSetICFocus(xw.ime.xic);
win.mode |= MODE_FOCUSED;
xseturgency(0);
if (IS_SET(MODE_FOCUS))
ttywrite("\033[I", 3, 0);
} else {
if (xw.ime.xic)
XUnsetICFocus(xw.ime.xic);
win.mode &= ~MODE_FOCUSED;
if (IS_SET(MODE_FOCUS))
ttywrite("\033[O", 3, 0);
}
}
int
match(uint mask, uint state)
{
return mask == XK_ANY_MOD || mask == (state & ~ignoremod);
}
char*
kmap(KeySym k, uint state)
{
Key *kp;
int i;
/* Check for mapped keys out of X11 function keys. */
for (i = 0; i < LEN(mappedkeys); i++) {
if (mappedkeys[i] == k)
break;
}
if (i == LEN(mappedkeys)) {
if ((k & 0xFFFF) < 0xFD00)
return NULL;
}
for (kp = key; kp < key + LEN(key); kp++) {
if (kp->k != k)
continue;
if (!match(kp->mask, state))
continue;
if (IS_SET(MODE_APPKEYPAD) ? kp->appkey < 0 : kp->appkey > 0)
continue;
if (IS_SET(MODE_NUMLOCK) && kp->appkey == 2)
continue;
if (IS_SET(MODE_APPCURSOR) ? kp->appcursor < 0 : kp->appcursor > 0)
continue;
return kp->s;
}
return NULL;
}
void
kpress(XEvent *ev)
{
XKeyEvent *e = &ev->xkey;
KeySym ksym;
char buf[64], *customkey;
int len;
Rune c;
Status status;
Shortcut *bp;
if (IS_SET(MODE_KBDLOCK))
return;
if (xw.ime.xic)
len = XmbLookupString(xw.ime.xic, e, buf, sizeof buf, &ksym, &status);
else
len = XLookupString(e, buf, sizeof buf, &ksym, NULL);
/* 1. shortcuts */
for (bp = shortcuts; bp < shortcuts + LEN(shortcuts); bp++) {
if (ksym == bp->keysym && match(bp->mod, e->state)) {
bp->func(&(bp->arg));
return;
}
}
/* 2. custom keys from config.h */
if ((customkey = kmap(ksym, e->state))) {
ttywrite(customkey, strlen(customkey), 1);
return;
}
/* 3. composed string from input method */
if (len == 0)
return;
if (len == 1 && e->state & Mod1Mask) {
if (IS_SET(MODE_8BIT)) {
if (*buf < 0177) {
c = *buf | 0x80;
len = utf8encode(c, buf);
}
} else {
buf[1] = buf[0];
buf[0] = '\033';
len = 2;
}
}
ttywrite(buf, len, 1);
}
void
cmessage(XEvent *e)
{
/*
* See xembed specs
* http://standards.freedesktop.org/xembed-spec/xembed-spec-latest.html
*/
if (e->xclient.message_type == xw.xembed && e->xclient.format == 32) {
if (e->xclient.data.l[1] == XEMBED_FOCUS_IN) {
win.mode |= MODE_FOCUSED;
xseturgency(0);
} else if (e->xclient.data.l[1] == XEMBED_FOCUS_OUT) {
win.mode &= ~MODE_FOCUSED;
}
} else if (e->xclient.data.l[0] == xw.wmdeletewin) {
ttyhangup();
exit(0);
}
}
void
resize(XEvent *e)
{
if (e->xconfigure.width == win.w && e->xconfigure.height == win.h)
return;
cresize(e->xconfigure.width, e->xconfigure.height);
}
void
run(void)
{
XEvent ev;
int w = win.w, h = win.h;
fd_set rfd;
int xfd = XConnectionNumber(xw.dpy), xev, blinkset = 0, dodraw = 0;
int ttyfd;
struct timespec drawtimeout, *tv = NULL, now, last, lastblink;
long deltatime;
/* Waiting for window mapping */
do {
XNextEvent(xw.dpy, &ev);
/*
* This XFilterEvent call is required because of XOpenIM. It
* does filter out the key event and some client message for
* the input method too.
*/
if (XFilterEvent(&ev, None))
continue;
if (ev.type == ConfigureNotify) {
w = ev.xconfigure.width;
h = ev.xconfigure.height;
}
} while (ev.type != MapNotify);
ttyfd = ttynew(opt_line, shell, opt_io, opt_cmd);
cresize(w, h);
clock_gettime(CLOCK_MONOTONIC, &last);
lastblink = last;
for (xev = actionfps;;) {
FD_ZERO(&rfd);
FD_SET(ttyfd, &rfd);
FD_SET(xfd, &rfd);
if (pselect(MAX(xfd, ttyfd)+1, &rfd, NULL, NULL, tv, NULL) < 0) {
if (errno == EINTR)
continue;
die("select failed: %s\n", strerror(errno));
}
if (FD_ISSET(ttyfd, &rfd)) {
ttyread();
if (blinktimeout) {
blinkset = tattrset(ATTR_BLINK);
if (!blinkset)
MODBIT(win.mode, 0, MODE_BLINK);
}
}
if (FD_ISSET(xfd, &rfd))
xev = actionfps;
clock_gettime(CLOCK_MONOTONIC, &now);
drawtimeout.tv_sec = 0;
drawtimeout.tv_nsec = (1000 * 1E6)/ xfps;
tv = &drawtimeout;
dodraw = 0;
if (blinktimeout && TIMEDIFF(now, lastblink) > blinktimeout) {
tsetdirtattr(ATTR_BLINK);
win.mode ^= MODE_BLINK;
lastblink = now;
dodraw = 1;
}
deltatime = TIMEDIFF(now, last);
if (deltatime > 1000 / (xev ? xfps : actionfps)) {
dodraw = 1;
last = now;
}
if (dodraw) {
while (XPending(xw.dpy)) {
XNextEvent(xw.dpy, &ev);
if (XFilterEvent(&ev, None))
continue;
if (handler[ev.type])
(handler[ev.type])(&ev);
}
draw();
XFlush(xw.dpy);
if (xev && !FD_ISSET(xfd, &rfd))
xev--;
if (!FD_ISSET(ttyfd, &rfd) && !FD_ISSET(xfd, &rfd)) {
if (blinkset) {
if (TIMEDIFF(now, lastblink) \
> blinktimeout) {
drawtimeout.tv_nsec = 1000;
} else {
drawtimeout.tv_nsec = (1E6 * \
(blinktimeout - \
TIMEDIFF(now,
lastblink)));
}
drawtimeout.tv_sec = \
drawtimeout.tv_nsec / 1E9;
drawtimeout.tv_nsec %= (long)1E9;
} else {
tv = NULL;
}
}
}
}
}
void
usage(void)
{
die("usage: %s [-aiv] [-c class] [-d path] [-f font]"
" [-g geometry] [-n name] [-o file]\n"
" [-T title] [-t title] [-w windowid]"
" [[-e] command [args ...]]\n"
" %s [-aiv] [-c class] [-d path] [-f font]"
" [-g geometry] [-n name] [-o file]\n"
" [-T title] [-t title] [-w windowid] -l line"
" [stty_args ...]\n", argv0, argv0);
}
int
main(int argc, char *argv[])
{
xw.l = xw.t = 0;
xw.isfixed = False;
win.cursor = cursorshape;
ARGBEGIN {
case 'a':
allowaltscreen = 0;
break;
case 'A':
opt_alpha = EARGF(usage());
break;
case 'c':
opt_class = EARGF(usage());
break;
case 'e':
if (argc > 0)
--argc, ++argv;
goto run;
case 'f':
opt_font = EARGF(usage());
break;
case 'g':
xw.gm = XParseGeometry(EARGF(usage()),
&xw.l, &xw.t, &cols, &rows);
break;
case 'i':
xw.isfixed = 1;
break;
case 'o':
opt_io = EARGF(usage());
break;
case 'l':
opt_line = EARGF(usage());
break;
case 'n':
opt_name = EARGF(usage());
break;
case 't':
case 'T':
opt_title = EARGF(usage());
break;
case 'w':
opt_embed = EARGF(usage());
break;
case 'v':
die("%s " VERSION "\n", argv0);
break;
case 'd':
opt_dir = EARGF(usage());
break;
default:
usage();
} ARGEND;
run:
if (argc > 0) /* eat all remaining arguments */
opt_cmd = argv;
if (!opt_title)
opt_title = (opt_line || !opt_cmd) ? "st" : opt_cmd[0];
setlocale(LC_CTYPE, "");
XSetLocaleModifiers("");
cols = MAX(cols, 1);
rows = MAX(rows, 1);
tnew(cols, rows);
xinit(cols, rows);
xsetenv();
selinit();
chdir(opt_dir);
run();
return 0;
}
void
opencopied(const Arg *arg)
{
const size_t max_cmd = 2048;
const char *clip = xsel.clipboard;
if(!clip) {
fprintf(stderr, "Warning: nothing copied to clipboard\n");
return;
}
/* account for space/quote (3) and \0 (1) and & (1) */
char cmd[max_cmd + strlen(clip) + 5];
strncpy(cmd, (char *)arg->v, max_cmd);
cmd[max_cmd] = '\0';
strcat(cmd, " \"");
strcat(cmd, clip);
strcat(cmd, "\"");
strcat(cmd, "&");
system(cmd);
}
|
93351.c | /*
* Copyright (C) 1989-2015, Craig E. Kolb
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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 "texture.h"
#include "bump.h"
/*
* Create and return a reference to a "bump" texture.
*/
Bump *
BumpCreate(size)
Float size;
{
Bump *bump;
bump = (Bump *)Malloc(sizeof(Bump));
bump->size = size;
return bump;
}
/*
* Apply a "bump" texture.
*/
void
BumpApply(bump, prim, ray, pos, norm, gnorm, surf)
Bump *bump;
Geom *prim;
Ray *ray;
Vector *pos, *norm, *gnorm;
Surface *surf;
{
Vector disp;
DNoise3(pos, &disp);
norm->x += disp.x * bump->size;
norm->y += disp.y * bump->size;
norm->z += disp.z * bump->size;
(void)VecNormalize(norm);
}
|
871759.c | struct Foo {
int a;
int b;
};
struct Foo *GetAFoo() {
return 0;
}
int main() {
return GetAFoo()->b;
}
|
302119.c | /***********************************************************************************
* Copyright (c) 2013, Sepehr Taghdisian
* 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.
*
***********************************************************************************/
#include "app.h"
#include "dhcore/core.h"
#include "dhcore/json.h"
#include "dhcore/util.h"
#define PHX_DEFAULT_SUBSTEPS 2
/* fwd */
void gfx_parseparams(struct gfx_params* params, json_t j);
void phx_parseparams(struct phx_params* params, json_t j);
void sct_parseparams(struct sct_params* params, json_t j);
/* */
struct init_params* app_config_load(const char* cfg_jsonfile)
{
struct init_params* params = (struct init_params*)ALLOC(sizeof(struct init_params), 0);
ASSERT(params);
memset(params, 0x00, sizeof(struct init_params));
char* buffer = util_readtextfile(cfg_jsonfile, mem_heap());
if (buffer == NULL) {
err_printf(__FILE__, __LINE__, "loading confing file '%s' failed", cfg_jsonfile);
FREE(params);
return NULL;
}
json_t root = json_parsestring(buffer);
FREE(buffer);
if (root == NULL) {
err_printf(__FILE__, __LINE__, "parsing confing file '%s' failed: invalid json",
cfg_jsonfile);
FREE(params);
return NULL;
}
/* fill paramters from json data */
/* general */
json_t general = json_getitem(root, "general");
if (general != NULL) {
if (json_getb_child(general, "debug", FALSE))
BIT_ADD(params->flags, ENG_FLAG_DEBUG);
if (json_getb_child(general, "dev", FALSE))
BIT_ADD(params->flags, ENG_FLAG_DEV);
if (json_getb_child(general, "console", FALSE))
BIT_ADD(params->flags, ENG_FLAG_CONSOLE);
if (json_getb_child(general, "no-physics", FALSE))
BIT_ADD(params->flags, ENG_FLAG_DISABLEPHX);
if (json_getb_child(general, "optimize-mem", FALSE))
BIT_ADD(params->flags, ENG_FLAG_OPTIMIZEMEMORY);
if (json_getb_child(general, "no-bgload", FALSE))
BIT_ADD(params->flags, ENG_FLAG_DISABLEBGLOAD);
params->console_lines_max = json_geti_child(general, "console-lines", 1000);
} else {
params->console_lines_max = 1000;
}
/* gfx */
gfx_parseparams(¶ms->gfx, root);
/* physics */
phx_parseparams(¶ms->phx, root);
/* script */
sct_parseparams(¶ms->sct, root);
/* developer */
json_t dev = json_getitem(root, "dev");
if (dev != NULL) {
params->dev.webserver_port = json_geti_child(dev, "webserver-port", 8888);
params->dev.buffsize_data = json_geti_child(dev, "buffsize-data", 0);
params->dev.buffsize_tmp = json_geti_child(dev, "buffsize-tmp", 0);
}
else {
params->dev.webserver_port = 8888;
}
/* console commands */
json_t console = json_getitem(root, "console");
if (console != NULL) {
params->console_cmds_cnt = json_getarr_count(console);
params->console_cmds = (char*)ALLOC(params->console_cmds_cnt*128, 0);
ASSERT(params->console_cmds != NULL);
for (uint i = 0; i < params->console_cmds_cnt; i++) {
char* data = params->console_cmds + i*128;
strcpy(data, json_gets(json_getarr_item(console, i)));
}
}
json_destroy(root);
return params;
}
void app_config_unload(struct init_params* cfg)
{
if (cfg->console_cmds != NULL)
FREE(cfg->console_cmds);
FREE(cfg);
}
struct init_params* app_config_default()
{
struct init_params* params = (struct init_params*)ALLOC(sizeof(struct init_params), 0);
ASSERT(params);
memset(params, 0x00, sizeof(struct init_params));
params->console_lines_max = 1000;
params->dev.webserver_port = 8888;
params->gfx.width = 1280;
params->gfx.height = 720;
params->gfx.refresh_rate = 60;
params->phx.substeps_max = PHX_DEFAULT_SUBSTEPS;
#if defined(_OSX_)
params->gfx.hwver = GFX_HWVER_GL3_2;
#endif
return params;
}
void app_config_addconsolecmd(struct init_params* cfg, const char* cmd)
{
if (cfg->console_cmds != NULL) {
uint size = cfg->console_cmds_cnt*128;
char* tmp = (char*)ALLOC(size + 128, 0);
ASSERT(tmp);
memcpy(tmp, cfg->console_cmds, size);
str_safecpy(tmp + size, 128, cmd);
FREE(cfg->console_cmds);
cfg->console_cmds = tmp;
cfg->console_cmds_cnt ++;
} else {
cfg->console_cmds = (char*)ALLOC(128, 0);
ASSERT(cfg->console_cmds);
str_safecpy(cfg->console_cmds, 128, cmd);
cfg->console_cmds_cnt ++;
}
}
void gfx_parseparams(struct gfx_params* params, json_t j)
{
memset(params, 0x00, sizeof(struct gfx_params));
/* graphics */
json_t gfx = json_getitem(j, "gfx");
if (gfx != NULL) {
if (json_getb_child(gfx, "fullscreen", FALSE))
BIT_ADD(params->flags, GFX_FLAG_FULLSCREEN);
if (json_getb_child(gfx, "vsync", FALSE))
BIT_ADD(params->flags, GFX_FLAG_VSYNC);
if (json_getb_child(gfx, "debug", FALSE))
BIT_ADD(params->flags, GFX_FLAG_DEBUG);
if (json_getb_child(gfx, "fxaa", FALSE))
BIT_ADD(params->flags, GFX_FLAG_FXAA);
if (json_getb_child(gfx, "rebuild-shaders", FALSE))
BIT_ADD(params->flags, GFX_FLAG_REBUILDSHADERS);
int msaa = json_geti_child(gfx, "msaa", 0);
switch (msaa) {
case 2: params->msaa = MSAA_2X; break;
case 4: params->msaa = MSAA_4X; break;
case 8: params->msaa = MSAA_8X; break;
default: params->msaa = MSAA_NONE; break;
}
const char* texq = json_gets_child(gfx, "texture-quality", "highest");
if (str_isequal_nocase(texq, "high"))
params->tex_quality = TEXTURE_QUALITY_HIGH;
else if(str_isequal_nocase(texq, "normal"))
params->tex_quality = TEXTURE_QUALITY_NORMAL;
else if(str_isequal_nocase(texq, "low"))
params->tex_quality = TEXTURE_QUALITY_LOW;
else
params->tex_quality = TEXTURE_QUALITY_HIGHEST;
const char* texf = json_gets_child(gfx, "texture-filter", "trilinear");
if (str_isequal_nocase(texf, "trilinear"))
params->tex_filter = TEXTURE_FILTER_TRILINEAR;
else if(str_isequal_nocase(texf, "bilinear"))
params->tex_filter = TEXTURE_FILTER_BILINEAR;
else if(str_isequal_nocase(texf, "aniso2x"))
params->tex_filter = TEXTURE_FILTER_ANISO2X;
else if(str_isequal_nocase(texf, "aniso4x"))
params->tex_filter = TEXTURE_FILTER_ANISO4X;
else if(str_isequal_nocase(texf, "aniso8x"))
params->tex_filter = TEXTURE_FILTER_ANISO8X;
else if(str_isequal_nocase(texf, "aniso16x"))
params->tex_filter = TEXTURE_FILTER_ANISO16X;
else
params->tex_filter = TEXTURE_FILTER_TRILINEAR;
const char* shq = json_gets_child(gfx, "shading-quality", "high");
if (str_isequal_nocase(shq, "normal"))
params->shading_quality = SHADING_QUALITY_NORMAL;
else if(str_isequal_nocase(shq, "low"))
params->shading_quality = SHADING_QUALITY_LOW;
else
params->shading_quality = SHADING_QUALITY_HIGH;
const char* ver = json_gets_child(gfx, "hw-version", "");
if (str_isequal_nocase(ver, "d3d10"))
params->hwver = GFX_HWVER_D3D10_0;
else if (str_isequal_nocase(ver, "d3d10.1"))
params->hwver = GFX_HWVER_D3D10_1;
else if (str_isequal_nocase(ver, "d3d11"))
params->hwver = GFX_HWVER_D3D11_0;
else if (str_isequal_nocase(ver, "d3d11.1"))
params->hwver = GFX_HWVER_D3D11_1;
else if (str_isequal_nocase(ver, "gl3.2"))
params->hwver = GFX_HWVER_GL3_2;
else if (str_isequal_nocase(ver, "gl3.3"))
params->hwver = GFX_HWVER_GL3_3;
else if (str_isequal_nocase(ver, "gl4.0"))
params->hwver = GFX_HWVER_GL4_0;
else if (str_isequal_nocase(ver, "gl4.1"))
params->hwver = GFX_HWVER_GL4_1;
else if (str_isequal_nocase(ver, "gl4.2"))
params->hwver = GFX_HWVER_GL4_2;
else if (str_isequal_nocase(ver, "gl4.3"))
params->hwver = GFX_HWVER_GL4_3;
else if (str_isequal_nocase(ver, "gl4.4"))
params->hwver = GFX_HWVER_GL4_4;
else
params->hwver = GFX_HWVER_UNKNOWN;
params->adapter_id = json_geti_child(gfx, "adapter-id", 0);
params->width = json_geti_child(gfx, "width", 1280);
params->height = json_geti_child(gfx, "height", 720);
params->refresh_rate = json_geti_child(gfx, "refresh-rate", 60);
} else {
params->width = 1280;
params->height = 720;
}
}
void phx_parseparams(struct phx_params* params, json_t j)
{
memset(params, 0x00, sizeof(struct phx_params));
/* physics */
json_t jphx = json_getitem(j, "physics");
if (jphx != NULL) {
if (json_getb_child(jphx, "track-mem", FALSE))
BIT_ADD(params->flags, PHX_FLAG_TRACKMEM);
if (json_getb_child(jphx, "profile", FALSE))
BIT_ADD(params->flags, PHX_FLAG_PROFILE);
params->mem_sz = json_geti_child(jphx, "mem-size", 0);
params->substeps_max = json_geti_child(jphx, "substeps-max", PHX_DEFAULT_SUBSTEPS);
params->scratch_sz = json_geti_child(jphx, "scratch-size", 0);
} else {
params->flags = 0;
params->mem_sz = 0;
params->substeps_max = PHX_DEFAULT_SUBSTEPS;
params->scratch_sz = 0;
}
}
void sct_parseparams(struct sct_params* params, json_t j)
{
memset(params, 0x00, sizeof(struct sct_params));
/* script */
json_t jsct = json_getitem(j, "script");
if (jsct != NULL) {
params->mem_sz = json_geti_child(jsct, "mem-size", 0);
} else {
params->mem_sz = 0;
}
}
|
485916.c | /* SPDX-License-Identifier: BSD-3-Clause
* Copyright(c) 2010-2014 Intel Corporation.
* Copyright (c) 2009, Olivier MATZ <[email protected]>
* All rights reserved.
*/
#include <stdlib.h>
#include <stdio.h>
#include <stdint.h>
#include <string.h>
#include <stdarg.h>
#include <errno.h>
#include <ctype.h>
#include "cmdline_cirbuf.h"
#include "cmdline_rdline.h"
static void rdline_puts(struct rdline *rdl, const char *buf);
static void rdline_miniprintf(struct rdline *rdl,
const char *buf, unsigned int val);
static void rdline_remove_old_history_item(struct rdline *rdl);
static void rdline_remove_first_history_item(struct rdline *rdl);
static unsigned int rdline_get_history_size(struct rdline *rdl);
/* isblank() needs _XOPEN_SOURCE >= 600 || _ISOC99_SOURCE, so use our
* own. */
static int
isblank2(char c)
{
if (c == ' ' ||
c == '\t' )
return 1;
return 0;
}
int
rdline_init(struct rdline *rdl,
rdline_write_char_t *write_char,
rdline_validate_t *validate,
rdline_complete_t *complete)
{
if (!rdl || !write_char || !validate || !complete)
return -EINVAL;
memset(rdl, 0, sizeof(*rdl));
rdl->validate = validate;
rdl->complete = complete;
rdl->write_char = write_char;
rdl->status = RDLINE_INIT;
return cirbuf_init(&rdl->history, rdl->history_buf, 0, RDLINE_HISTORY_BUF_SIZE);
}
void
rdline_newline(struct rdline *rdl, const char *prompt)
{
unsigned int i;
if (!rdl || !prompt)
return;
vt100_init(&rdl->vt100);
cirbuf_init(&rdl->left, rdl->left_buf, 0, RDLINE_BUF_SIZE);
cirbuf_init(&rdl->right, rdl->right_buf, 0, RDLINE_BUF_SIZE);
rdl->prompt_size = strnlen(prompt, RDLINE_PROMPT_SIZE-1);
if (prompt != rdl->prompt)
memcpy(rdl->prompt, prompt, rdl->prompt_size);
rdl->prompt[RDLINE_PROMPT_SIZE-1] = '\0';
for (i=0 ; i<rdl->prompt_size ; i++)
rdl->write_char(rdl, rdl->prompt[i]);
rdl->status = RDLINE_RUNNING;
rdl->history_cur_line = -1;
}
void
rdline_stop(struct rdline *rdl)
{
if (!rdl)
return;
rdl->status = RDLINE_INIT;
}
void
rdline_quit(struct rdline *rdl)
{
if (!rdl)
return;
rdl->status = RDLINE_EXITED;
}
void
rdline_restart(struct rdline *rdl)
{
if (!rdl)
return;
rdl->status = RDLINE_RUNNING;
}
void
rdline_reset(struct rdline *rdl)
{
if (!rdl)
return;
vt100_init(&rdl->vt100);
cirbuf_init(&rdl->left, rdl->left_buf, 0, RDLINE_BUF_SIZE);
cirbuf_init(&rdl->right, rdl->right_buf, 0, RDLINE_BUF_SIZE);
rdl->status = RDLINE_RUNNING;
rdl->history_cur_line = -1;
}
const char *
rdline_get_buffer(struct rdline *rdl)
{
if (!rdl)
return NULL;
unsigned int len_l, len_r;
cirbuf_align_left(&rdl->left);
cirbuf_align_left(&rdl->right);
len_l = CIRBUF_GET_LEN(&rdl->left);
len_r = CIRBUF_GET_LEN(&rdl->right);
memcpy(rdl->left_buf+len_l, rdl->right_buf, len_r);
rdl->left_buf[len_l + len_r] = '\n';
rdl->left_buf[len_l + len_r + 1] = '\0';
return rdl->left_buf;
}
static void
display_right_buffer(struct rdline *rdl, int force)
{
unsigned int i;
char tmp;
if (!force && CIRBUF_IS_EMPTY(&rdl->right))
return;
rdline_puts(rdl, vt100_clear_right);
CIRBUF_FOREACH(&rdl->right, i, tmp) {
rdl->write_char(rdl, tmp);
}
if (!CIRBUF_IS_EMPTY(&rdl->right))
rdline_miniprintf(rdl, vt100_multi_left,
CIRBUF_GET_LEN(&rdl->right));
}
void
rdline_redisplay(struct rdline *rdl)
{
unsigned int i;
char tmp;
if (!rdl)
return;
rdline_puts(rdl, vt100_home);
for (i=0 ; i<rdl->prompt_size ; i++)
rdl->write_char(rdl, rdl->prompt[i]);
CIRBUF_FOREACH(&rdl->left, i, tmp) {
rdl->write_char(rdl, tmp);
}
display_right_buffer(rdl, 1);
}
int
rdline_char_in(struct rdline *rdl, char c)
{
unsigned int i;
int cmd;
char tmp;
char *buf;
if (!rdl)
return -EINVAL;
if (rdl->status == RDLINE_EXITED)
return RDLINE_RES_EXITED;
if (rdl->status != RDLINE_RUNNING)
return RDLINE_RES_NOT_RUNNING;
cmd = vt100_parser(&rdl->vt100, c);
if (cmd == -2)
return RDLINE_RES_SUCCESS;
if (cmd >= 0) {
switch (cmd) {
/* move caret 1 char to the left */
case CMDLINE_KEY_CTRL_B:
case CMDLINE_KEY_LEFT_ARR:
if (CIRBUF_IS_EMPTY(&rdl->left))
break;
tmp = cirbuf_get_tail(&rdl->left);
cirbuf_del_tail(&rdl->left);
cirbuf_add_head(&rdl->right, tmp);
rdline_puts(rdl, vt100_left_arr);
break;
/* move caret 1 char to the right */
case CMDLINE_KEY_CTRL_F:
case CMDLINE_KEY_RIGHT_ARR:
if (CIRBUF_IS_EMPTY(&rdl->right))
break;
tmp = cirbuf_get_head(&rdl->right);
cirbuf_del_head(&rdl->right);
cirbuf_add_tail(&rdl->left, tmp);
rdline_puts(rdl, vt100_right_arr);
break;
/* move caret 1 word to the left */
/* keyboard equivalent: Alt+B */
case CMDLINE_KEY_WLEFT:
while (! CIRBUF_IS_EMPTY(&rdl->left) &&
(tmp = cirbuf_get_tail(&rdl->left)) &&
isblank2(tmp)) {
rdline_puts(rdl, vt100_left_arr);
cirbuf_del_tail(&rdl->left);
cirbuf_add_head(&rdl->right, tmp);
}
while (! CIRBUF_IS_EMPTY(&rdl->left) &&
(tmp = cirbuf_get_tail(&rdl->left)) &&
!isblank2(tmp)) {
rdline_puts(rdl, vt100_left_arr);
cirbuf_del_tail(&rdl->left);
cirbuf_add_head(&rdl->right, tmp);
}
break;
/* move caret 1 word to the right */
/* keyboard equivalent: Alt+F */
case CMDLINE_KEY_WRIGHT:
while (! CIRBUF_IS_EMPTY(&rdl->right) &&
(tmp = cirbuf_get_head(&rdl->right)) &&
isblank2(tmp)) {
rdline_puts(rdl, vt100_right_arr);
cirbuf_del_head(&rdl->right);
cirbuf_add_tail(&rdl->left, tmp);
}
while (! CIRBUF_IS_EMPTY(&rdl->right) &&
(tmp = cirbuf_get_head(&rdl->right)) &&
!isblank2(tmp)) {
rdline_puts(rdl, vt100_right_arr);
cirbuf_del_head(&rdl->right);
cirbuf_add_tail(&rdl->left, tmp);
}
break;
/* move caret to the left */
case CMDLINE_KEY_CTRL_A:
if (CIRBUF_IS_EMPTY(&rdl->left))
break;
rdline_miniprintf(rdl, vt100_multi_left,
CIRBUF_GET_LEN(&rdl->left));
while (! CIRBUF_IS_EMPTY(&rdl->left)) {
tmp = cirbuf_get_tail(&rdl->left);
cirbuf_del_tail(&rdl->left);
cirbuf_add_head(&rdl->right, tmp);
}
break;
/* move caret to the right */
case CMDLINE_KEY_CTRL_E:
if (CIRBUF_IS_EMPTY(&rdl->right))
break;
rdline_miniprintf(rdl, vt100_multi_right,
CIRBUF_GET_LEN(&rdl->right));
while (! CIRBUF_IS_EMPTY(&rdl->right)) {
tmp = cirbuf_get_head(&rdl->right);
cirbuf_del_head(&rdl->right);
cirbuf_add_tail(&rdl->left, tmp);
}
break;
/* delete 1 char from the left */
case CMDLINE_KEY_BKSPACE:
case CMDLINE_KEY_BKSPACE2:
if(!cirbuf_del_tail_safe(&rdl->left)) {
rdline_puts(rdl, vt100_bs);
display_right_buffer(rdl, 1);
}
break;
/* delete 1 char from the right */
case CMDLINE_KEY_SUPPR:
case CMDLINE_KEY_CTRL_D:
if (cmd == CMDLINE_KEY_CTRL_D &&
CIRBUF_IS_EMPTY(&rdl->left) &&
CIRBUF_IS_EMPTY(&rdl->right)) {
return RDLINE_RES_EOF;
}
if (!cirbuf_del_head_safe(&rdl->right)) {
display_right_buffer(rdl, 1);
}
break;
/* delete 1 word from the left */
case CMDLINE_KEY_META_BKSPACE:
case CMDLINE_KEY_CTRL_W:
while (! CIRBUF_IS_EMPTY(&rdl->left) && isblank2(cirbuf_get_tail(&rdl->left))) {
rdline_puts(rdl, vt100_bs);
cirbuf_del_tail(&rdl->left);
}
while (! CIRBUF_IS_EMPTY(&rdl->left) && !isblank2(cirbuf_get_tail(&rdl->left))) {
rdline_puts(rdl, vt100_bs);
cirbuf_del_tail(&rdl->left);
}
display_right_buffer(rdl, 1);
break;
/* delete 1 word from the right */
case CMDLINE_KEY_META_D:
while (! CIRBUF_IS_EMPTY(&rdl->right) && isblank2(cirbuf_get_head(&rdl->right)))
cirbuf_del_head(&rdl->right);
while (! CIRBUF_IS_EMPTY(&rdl->right) && !isblank2(cirbuf_get_head(&rdl->right)))
cirbuf_del_head(&rdl->right);
display_right_buffer(rdl, 1);
break;
/* set kill buffer to contents on the right side of caret */
case CMDLINE_KEY_CTRL_K:
cirbuf_get_buf_head(&rdl->right, rdl->kill_buf, RDLINE_BUF_SIZE);
rdl->kill_size = CIRBUF_GET_LEN(&rdl->right);
cirbuf_del_buf_head(&rdl->right, rdl->kill_size);
rdline_puts(rdl, vt100_clear_right);
break;
/* paste contents of kill buffer to the left side of caret */
case CMDLINE_KEY_CTRL_Y:
i=0;
while(CIRBUF_GET_LEN(&rdl->right) + CIRBUF_GET_LEN(&rdl->left) <
RDLINE_BUF_SIZE &&
i < rdl->kill_size) {
cirbuf_add_tail(&rdl->left, rdl->kill_buf[i]);
rdl->write_char(rdl, rdl->kill_buf[i]);
i++;
}
display_right_buffer(rdl, 0);
break;
/* clear and newline */
case CMDLINE_KEY_CTRL_C:
rdline_puts(rdl, "\r\n");
rdline_newline(rdl, rdl->prompt);
break;
/* redisplay (helps when prompt is lost in other output) */
case CMDLINE_KEY_CTRL_L:
rdline_redisplay(rdl);
break;
/* autocomplete */
case CMDLINE_KEY_TAB:
case CMDLINE_KEY_HELP:
cirbuf_align_left(&rdl->left);
rdl->left_buf[CIRBUF_GET_LEN(&rdl->left)] = '\0';
if (rdl->complete) {
char tmp_buf[BUFSIZ];
int complete_state;
int ret;
unsigned int tmp_size;
if (cmd == CMDLINE_KEY_TAB)
complete_state = 0;
else
complete_state = -1;
/* see in parse.h for help on complete() */
ret = rdl->complete(rdl, rdl->left_buf,
tmp_buf, sizeof(tmp_buf),
&complete_state);
/* no completion or error */
if (ret <= 0) {
return RDLINE_RES_COMPLETE;
}
tmp_size = strnlen(tmp_buf, sizeof(tmp_buf));
/* add chars */
if (ret == RDLINE_RES_COMPLETE) {
i=0;
while(CIRBUF_GET_LEN(&rdl->right) + CIRBUF_GET_LEN(&rdl->left) <
RDLINE_BUF_SIZE &&
i < tmp_size) {
cirbuf_add_tail(&rdl->left, tmp_buf[i]);
rdl->write_char(rdl, tmp_buf[i]);
i++;
}
display_right_buffer(rdl, 1);
return RDLINE_RES_COMPLETE; /* ?? */
}
/* choice */
rdline_puts(rdl, "\r\n");
while (ret) {
rdl->write_char(rdl, ' ');
for (i=0 ; tmp_buf[i] ; i++)
rdl->write_char(rdl, tmp_buf[i]);
rdline_puts(rdl, "\r\n");
ret = rdl->complete(rdl, rdl->left_buf,
tmp_buf, sizeof(tmp_buf),
&complete_state);
}
rdline_redisplay(rdl);
}
return RDLINE_RES_COMPLETE;
/* complete buffer */
case CMDLINE_KEY_RETURN:
case CMDLINE_KEY_RETURN2:
rdline_get_buffer(rdl);
rdl->status = RDLINE_INIT;
rdline_puts(rdl, "\r\n");
if (rdl->history_cur_line != -1)
rdline_remove_first_history_item(rdl);
if (rdl->validate)
rdl->validate(rdl, rdl->left_buf, CIRBUF_GET_LEN(&rdl->left)+2);
/* user may have stopped rdline */
if (rdl->status == RDLINE_EXITED)
return RDLINE_RES_EXITED;
return RDLINE_RES_VALIDATED;
/* previous element in history */
case CMDLINE_KEY_UP_ARR:
case CMDLINE_KEY_CTRL_P:
if (rdl->history_cur_line == 0) {
rdline_remove_first_history_item(rdl);
}
if (rdl->history_cur_line <= 0) {
rdline_add_history(rdl, rdline_get_buffer(rdl));
rdl->history_cur_line = 0;
}
buf = rdline_get_history_item(rdl, rdl->history_cur_line + 1);
if (!buf)
break;
rdl->history_cur_line ++;
vt100_init(&rdl->vt100);
cirbuf_init(&rdl->left, rdl->left_buf, 0, RDLINE_BUF_SIZE);
cirbuf_init(&rdl->right, rdl->right_buf, 0, RDLINE_BUF_SIZE);
cirbuf_add_buf_tail(&rdl->left, buf, strnlen(buf, RDLINE_BUF_SIZE));
rdline_redisplay(rdl);
break;
/* next element in history */
case CMDLINE_KEY_DOWN_ARR:
case CMDLINE_KEY_CTRL_N:
if (rdl->history_cur_line - 1 < 0)
break;
rdl->history_cur_line --;
buf = rdline_get_history_item(rdl, rdl->history_cur_line);
if (!buf)
break;
vt100_init(&rdl->vt100);
cirbuf_init(&rdl->left, rdl->left_buf, 0, RDLINE_BUF_SIZE);
cirbuf_init(&rdl->right, rdl->right_buf, 0, RDLINE_BUF_SIZE);
cirbuf_add_buf_tail(&rdl->left, buf, strnlen(buf, RDLINE_BUF_SIZE));
rdline_redisplay(rdl);
break;
default:
break;
}
return RDLINE_RES_SUCCESS;
}
if (!isprint((int)c))
return RDLINE_RES_SUCCESS;
/* standard chars */
if (CIRBUF_GET_LEN(&rdl->left) + CIRBUF_GET_LEN(&rdl->right) >= RDLINE_BUF_SIZE)
return RDLINE_RES_SUCCESS;
if (cirbuf_add_tail_safe(&rdl->left, c))
return RDLINE_RES_SUCCESS;
rdl->write_char(rdl, c);
display_right_buffer(rdl, 0);
return RDLINE_RES_SUCCESS;
}
/* HISTORY */
static void
rdline_remove_old_history_item(struct rdline * rdl)
{
char tmp;
while (! CIRBUF_IS_EMPTY(&rdl->history) ) {
tmp = cirbuf_get_head(&rdl->history);
cirbuf_del_head(&rdl->history);
if (!tmp)
break;
}
}
static void
rdline_remove_first_history_item(struct rdline * rdl)
{
char tmp;
if ( CIRBUF_IS_EMPTY(&rdl->history) ) {
return;
}
else {
cirbuf_del_tail(&rdl->history);
}
while (! CIRBUF_IS_EMPTY(&rdl->history) ) {
tmp = cirbuf_get_tail(&rdl->history);
if (!tmp)
break;
cirbuf_del_tail(&rdl->history);
}
}
static unsigned int
rdline_get_history_size(struct rdline * rdl)
{
unsigned int i, tmp, ret=0;
CIRBUF_FOREACH(&rdl->history, i, tmp) {
if (tmp == 0)
ret ++;
}
return ret;
}
char *
rdline_get_history_item(struct rdline * rdl, unsigned int idx)
{
unsigned int len, i, tmp;
if (!rdl)
return NULL;
len = rdline_get_history_size(rdl);
if ( idx >= len ) {
return NULL;
}
cirbuf_align_left(&rdl->history);
CIRBUF_FOREACH(&rdl->history, i, tmp) {
if ( idx == len - 1) {
return rdl->history_buf + i;
}
if (tmp == 0)
len --;
}
return NULL;
}
int
rdline_add_history(struct rdline * rdl, const char * buf)
{
unsigned int len, i;
if (!rdl || !buf)
return -EINVAL;
len = strnlen(buf, RDLINE_BUF_SIZE);
for (i=0; i<len ; i++) {
if (buf[i] == '\n') {
len = i;
break;
}
}
if ( len >= RDLINE_HISTORY_BUF_SIZE )
return -1;
while ( len >= CIRBUF_GET_FREELEN(&rdl->history) ) {
rdline_remove_old_history_item(rdl);
}
cirbuf_add_buf_tail(&rdl->history, buf, len);
cirbuf_add_tail(&rdl->history, 0);
return 0;
}
void
rdline_clear_history(struct rdline * rdl)
{
if (!rdl)
return;
cirbuf_init(&rdl->history, rdl->history_buf, 0, RDLINE_HISTORY_BUF_SIZE);
}
/* STATIC USEFUL FUNCS */
static void
rdline_puts(struct rdline * rdl, const char * buf)
{
char c;
while ( (c = *(buf++)) != '\0' ) {
rdl->write_char(rdl, c);
}
}
/* a very very basic printf with one arg and one format 'u' */
static void
rdline_miniprintf(struct rdline *rdl, const char * buf, unsigned int val)
{
char c, started=0, div=100;
while ( (c=*(buf++)) ) {
if (c != '%') {
rdl->write_char(rdl, c);
continue;
}
c = *(buf++);
if (c != 'u') {
rdl->write_char(rdl, '%');
rdl->write_char(rdl, c);
continue;
}
/* val is never more than 255 */
while (div) {
c = (char)(val / div);
if (c || started) {
rdl->write_char(rdl, (char)(c+'0'));
started = 1;
}
val %= div;
div /= 10;
}
}
}
|
763373.c | /*
* Copyright (c) 2015, Freescale Semiconductor, Inc.
* Copyright 2016-2017 NXP
* All rights reserved.
*
* SPDX-License-Identifier: BSD-3-Clause
*/
/* Standard C Included Files */
#include <string.h>
/* SDK Included Files */
#include "pin_mux.h"
#include "clock_config.h"
#include "board.h"
#include "fsl_debug_console.h"
#include "fsl_i2c.h"
/*******************************************************************************
* Definitions
******************************************************************************/
#define EXAMPLE_I2C_SLAVE_BASEADDR I2C3
#define I2C_MASTER_SLAVE_ADDR_7BIT 0x7EU
#define I2C_DATA_LENGTH 32U
/*******************************************************************************
* Prototypes
******************************************************************************/
/*******************************************************************************
* Variables
******************************************************************************/
uint8_t g_slave_buff[I2C_DATA_LENGTH];
i2c_slave_handle_t g_s_handle;
volatile bool g_SlaveCompletionFlag = false;
/*******************************************************************************
* Code
******************************************************************************/
static void i2c_slave_callback(I2C_Type *base, i2c_slave_transfer_t *xfer, void *userData)
{
switch (xfer->event)
{
/* Transmit request */
case kI2C_SlaveTransmitEvent:
/* Update information for transmit process */
xfer->data = g_slave_buff;
xfer->dataSize = I2C_DATA_LENGTH;
break;
/* Receive request */
case kI2C_SlaveReceiveEvent:
/* Update information for received process */
xfer->data = g_slave_buff;
xfer->dataSize = I2C_DATA_LENGTH;
break;
/* Transfer done */
case kI2C_SlaveCompletionEvent:
g_SlaveCompletionFlag = true;
break;
default:
g_SlaveCompletionFlag = true;
break;
}
}
/*!
* @brief Main function
*/
int main(void)
{
i2c_slave_config_t slaveConfig;
/* Board specific RDC settings */
BOARD_RdcInit();
BOARD_InitPins();
BOARD_BootClockRUN();
BOARD_InitDebugConsole();
BOARD_InitMemory();
PRINTF("\r\nI2C board2board interrupt example -- Slave transfer.\r\n\r\n");
/*1.Set up i2c slave first*/
/*
* slaveConfig->addressingMode = kI2C_Address7bit;
* slaveConfig->enableGeneralCall = false;
* slaveConfig->enableWakeUp = false;
* slaveConfig->enableHighDrive = false;
* slaveConfig->enableBaudRateCtl = false;
* slaveConfig->enableSlave = true;
*/
I2C_SlaveGetDefaultConfig(&slaveConfig);
slaveConfig.slaveAddress = I2C_MASTER_SLAVE_ADDR_7BIT;
I2C_SlaveInit(EXAMPLE_I2C_SLAVE_BASEADDR, &slaveConfig);
for (uint32_t i = 0U; i < I2C_DATA_LENGTH; i++)
{
g_slave_buff[i] = 0;
}
memset(&g_s_handle, 0, sizeof(g_s_handle));
I2C_SlaveTransferCreateHandle(EXAMPLE_I2C_SLAVE_BASEADDR, &g_s_handle, i2c_slave_callback, NULL);
/* Set up slave transfer. */
I2C_SlaveTransferNonBlocking(EXAMPLE_I2C_SLAVE_BASEADDR, &g_s_handle, kI2C_SlaveCompletionEvent);
/* Wait for transfer completed. */
while (!g_SlaveCompletionFlag)
{
}
g_SlaveCompletionFlag = false;
PRINTF("Slave received data :");
for (uint32_t i = 0U; i < I2C_DATA_LENGTH; i++)
{
if (i % 8 == 0)
{
PRINTF("\r\n");
}
PRINTF("0x%2x ", g_slave_buff[i]);
}
PRINTF("\r\n\r\n");
/* Wait for master receive completed.*/
while (!g_SlaveCompletionFlag)
{
}
g_SlaveCompletionFlag = false;
PRINTF("\r\nEnd of I2C example .\r\n");
while (1)
{
}
}
|
857397.c | /*
* QEMU SCI/SCIF serial port emulation
*
* Copyright (c) 2007 Magnus Damm
*
* Based on serial.c - QEMU 16450 UART emulation
* Copyright (c) 2003-2004 Fabrice Bellard
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include "qemu/osdep.h"
#include "hw/hw.h"
#include "hw/sh4/sh.h"
#include "chardev/char-fe.h"
#include "qapi/error.h"
#include "qemu/timer.h"
//#define DEBUG_SERIAL
#define SH_SERIAL_FLAG_TEND (1 << 0)
#define SH_SERIAL_FLAG_TDE (1 << 1)
#define SH_SERIAL_FLAG_RDF (1 << 2)
#define SH_SERIAL_FLAG_BRK (1 << 3)
#define SH_SERIAL_FLAG_DR (1 << 4)
#define SH_RX_FIFO_LENGTH (16)
typedef struct {
MemoryRegion iomem;
MemoryRegion iomem_p4;
MemoryRegion iomem_a7;
uint8_t smr;
uint8_t brr;
uint8_t scr;
uint8_t dr; /* ftdr / tdr */
uint8_t sr; /* fsr / ssr */
uint16_t fcr;
uint8_t sptr;
uint8_t rx_fifo[SH_RX_FIFO_LENGTH]; /* frdr / rdr */
uint8_t rx_cnt;
uint8_t rx_tail;
uint8_t rx_head;
int freq;
int feat;
int flags;
int rtrg;
CharBackend chr;
QEMUTimer *fifo_timeout_timer;
uint64_t etu; /* Elementary Time Unit (ns) */
qemu_irq eri;
qemu_irq rxi;
qemu_irq txi;
qemu_irq tei;
qemu_irq bri;
} sh_serial_state;
static void sh_serial_clear_fifo(sh_serial_state * s)
{
memset(s->rx_fifo, 0, SH_RX_FIFO_LENGTH);
s->rx_cnt = 0;
s->rx_head = 0;
s->rx_tail = 0;
}
static void sh_serial_write(void *opaque, hwaddr offs,
uint64_t val, unsigned size)
{
sh_serial_state *s = opaque;
unsigned char ch;
#ifdef DEBUG_SERIAL
printf("sh_serial: write offs=0x%02x val=0x%02x\n",
offs, val);
#endif
switch(offs) {
case 0x00: /* SMR */
s->smr = val & ((s->feat & SH_SERIAL_FEAT_SCIF) ? 0x7b : 0xff);
return;
case 0x04: /* BRR */
s->brr = val;
return;
case 0x08: /* SCR */
/* TODO : For SH7751, SCIF mask should be 0xfb. */
s->scr = val & ((s->feat & SH_SERIAL_FEAT_SCIF) ? 0xfa : 0xff);
if (!(val & (1 << 5)))
s->flags |= SH_SERIAL_FLAG_TEND;
if ((s->feat & SH_SERIAL_FEAT_SCIF) && s->txi) {
qemu_set_irq(s->txi, val & (1 << 7));
}
if (!(val & (1 << 6))) {
qemu_set_irq(s->rxi, 0);
}
return;
case 0x0c: /* FTDR / TDR */
if (qemu_chr_fe_backend_connected(&s->chr)) {
ch = val;
/* XXX this blocks entire thread. Rewrite to use
* qemu_chr_fe_write and background I/O callbacks */
qemu_chr_fe_write_all(&s->chr, &ch, 1);
}
s->dr = val;
s->flags &= ~SH_SERIAL_FLAG_TDE;
return;
#if 0
case 0x14: /* FRDR / RDR */
ret = 0;
break;
#endif
}
if (s->feat & SH_SERIAL_FEAT_SCIF) {
switch(offs) {
case 0x10: /* FSR */
if (!(val & (1 << 6)))
s->flags &= ~SH_SERIAL_FLAG_TEND;
if (!(val & (1 << 5)))
s->flags &= ~SH_SERIAL_FLAG_TDE;
if (!(val & (1 << 4)))
s->flags &= ~SH_SERIAL_FLAG_BRK;
if (!(val & (1 << 1)))
s->flags &= ~SH_SERIAL_FLAG_RDF;
if (!(val & (1 << 0)))
s->flags &= ~SH_SERIAL_FLAG_DR;
if (!(val & (1 << 1)) || !(val & (1 << 0))) {
if (s->rxi) {
qemu_set_irq(s->rxi, 0);
}
}
return;
case 0x18: /* FCR */
s->fcr = val;
switch ((val >> 6) & 3) {
case 0:
s->rtrg = 1;
break;
case 1:
s->rtrg = 4;
break;
case 2:
s->rtrg = 8;
break;
case 3:
s->rtrg = 14;
break;
}
if (val & (1 << 1)) {
sh_serial_clear_fifo(s);
s->sr &= ~(1 << 1);
}
return;
case 0x20: /* SPTR */
s->sptr = val & 0xf3;
return;
case 0x24: /* LSR */
return;
}
}
else {
switch(offs) {
#if 0
case 0x0c:
ret = s->dr;
break;
case 0x10:
ret = 0;
break;
#endif
case 0x1c:
s->sptr = val & 0x8f;
return;
}
}
fprintf(stderr, "sh_serial: unsupported write to 0x%02"
HWADDR_PRIx "\n", offs);
abort();
}
static uint64_t sh_serial_read(void *opaque, hwaddr offs,
unsigned size)
{
sh_serial_state *s = opaque;
uint32_t ret = ~0;
#if 0
switch(offs) {
case 0x00:
ret = s->smr;
break;
case 0x04:
ret = s->brr;
break;
case 0x08:
ret = s->scr;
break;
case 0x14:
ret = 0;
break;
}
#endif
if (s->feat & SH_SERIAL_FEAT_SCIF) {
switch(offs) {
case 0x00: /* SMR */
ret = s->smr;
break;
case 0x08: /* SCR */
ret = s->scr;
break;
case 0x10: /* FSR */
ret = 0;
if (s->flags & SH_SERIAL_FLAG_TEND)
ret |= (1 << 6);
if (s->flags & SH_SERIAL_FLAG_TDE)
ret |= (1 << 5);
if (s->flags & SH_SERIAL_FLAG_BRK)
ret |= (1 << 4);
if (s->flags & SH_SERIAL_FLAG_RDF)
ret |= (1 << 1);
if (s->flags & SH_SERIAL_FLAG_DR)
ret |= (1 << 0);
if (s->scr & (1 << 5))
s->flags |= SH_SERIAL_FLAG_TDE | SH_SERIAL_FLAG_TEND;
break;
case 0x14:
if (s->rx_cnt > 0) {
ret = s->rx_fifo[s->rx_tail++];
s->rx_cnt--;
if (s->rx_tail == SH_RX_FIFO_LENGTH)
s->rx_tail = 0;
if (s->rx_cnt < s->rtrg)
s->flags &= ~SH_SERIAL_FLAG_RDF;
}
break;
case 0x18:
ret = s->fcr;
break;
case 0x1c:
ret = s->rx_cnt;
break;
case 0x20:
ret = s->sptr;
break;
case 0x24:
ret = 0;
break;
}
}
else {
switch(offs) {
#if 0
case 0x0c:
ret = s->dr;
break;
case 0x10:
ret = 0;
break;
case 0x14:
ret = s->rx_fifo[0];
break;
#endif
case 0x1c:
ret = s->sptr;
break;
}
}
#ifdef DEBUG_SERIAL
printf("sh_serial: read offs=0x%02x val=0x%x\n",
offs, ret);
#endif
if (ret & ~((1 << 16) - 1)) {
fprintf(stderr, "sh_serial: unsupported read from 0x%02"
HWADDR_PRIx "\n", offs);
abort();
}
return ret;
}
static int sh_serial_can_receive(sh_serial_state *s)
{
return s->scr & (1 << 4);
}
static void sh_serial_receive_break(sh_serial_state *s)
{
if (s->feat & SH_SERIAL_FEAT_SCIF)
s->sr |= (1 << 4);
}
static int sh_serial_can_receive1(void *opaque)
{
sh_serial_state *s = opaque;
return sh_serial_can_receive(s);
}
static void sh_serial_timeout_int(void *opaque)
{
sh_serial_state *s = opaque;
s->flags |= SH_SERIAL_FLAG_RDF;
if (s->scr & (1 << 6) && s->rxi) {
qemu_set_irq(s->rxi, 1);
}
}
static void sh_serial_receive1(void *opaque, const uint8_t *buf, int size)
{
sh_serial_state *s = opaque;
if (s->feat & SH_SERIAL_FEAT_SCIF) {
int i;
for (i = 0; i < size; i++) {
if (s->rx_cnt < SH_RX_FIFO_LENGTH) {
s->rx_fifo[s->rx_head++] = buf[i];
if (s->rx_head == SH_RX_FIFO_LENGTH) {
s->rx_head = 0;
}
s->rx_cnt++;
if (s->rx_cnt >= s->rtrg) {
s->flags |= SH_SERIAL_FLAG_RDF;
if (s->scr & (1 << 6) && s->rxi) {
timer_del(s->fifo_timeout_timer);
qemu_set_irq(s->rxi, 1);
}
} else {
timer_mod(s->fifo_timeout_timer,
qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) + 15 * s->etu);
}
}
}
} else {
s->rx_fifo[0] = buf[0];
}
}
static void sh_serial_event(void *opaque, int event)
{
sh_serial_state *s = opaque;
if (event == CHR_EVENT_BREAK)
sh_serial_receive_break(s);
}
static const MemoryRegionOps sh_serial_ops = {
.read = sh_serial_read,
.write = sh_serial_write,
.endianness = DEVICE_NATIVE_ENDIAN,
};
void sh_serial_init(MemoryRegion *sysmem,
hwaddr base, int feat,
uint32_t freq, Chardev *chr,
qemu_irq eri_source,
qemu_irq rxi_source,
qemu_irq txi_source,
qemu_irq tei_source,
qemu_irq bri_source)
{
sh_serial_state *s;
s = g_malloc0(sizeof(sh_serial_state));
s->feat = feat;
s->flags = SH_SERIAL_FLAG_TEND | SH_SERIAL_FLAG_TDE;
s->rtrg = 1;
s->smr = 0;
s->brr = 0xff;
s->scr = 1 << 5; /* pretend that TX is enabled so early printk works */
s->sptr = 0;
if (feat & SH_SERIAL_FEAT_SCIF) {
s->fcr = 0;
}
else {
s->dr = 0xff;
}
sh_serial_clear_fifo(s);
memory_region_init_io(&s->iomem, NULL, &sh_serial_ops, s,
"serial", 0x100000000ULL);
memory_region_init_alias(&s->iomem_p4, NULL, "serial-p4", &s->iomem,
0, 0x28);
memory_region_add_subregion(sysmem, P4ADDR(base), &s->iomem_p4);
memory_region_init_alias(&s->iomem_a7, NULL, "serial-a7", &s->iomem,
0, 0x28);
memory_region_add_subregion(sysmem, A7ADDR(base), &s->iomem_a7);
if (chr) {
qemu_chr_fe_init(&s->chr, chr, &error_abort);
qemu_chr_fe_set_handlers(&s->chr, sh_serial_can_receive1,
sh_serial_receive1,
sh_serial_event, NULL, s, NULL, true);
}
s->fifo_timeout_timer = timer_new_ns(QEMU_CLOCK_VIRTUAL,
sh_serial_timeout_int, s);
s->etu = NANOSECONDS_PER_SECOND / 9600;
s->eri = eri_source;
s->rxi = rxi_source;
s->txi = txi_source;
s->tei = tei_source;
s->bri = bri_source;
}
|
744435.c | // SPDX-License-Identifier: GPL-2.0
/*
* file.c - part of debugfs, a tiny little debug file system
*
* Copyright (C) 2004 Greg Kroah-Hartman <[email protected]>
* Copyright (C) 2004 IBM Inc.
*
* debugfs is for people to use instead of /proc or /sys.
* See Documentation/filesystems/ for more details.
*/
#include <linux/module.h>
#include <linux/fs.h>
#include <linux/seq_file.h>
#include <linux/pagemap.h>
#include <linux/debugfs.h>
#include <linux/io.h>
#include <linux/slab.h>
#include <linux/atomic.h>
#include <linux/device.h>
#include <linux/pm_runtime.h>
#include <linux/poll.h>
#include <linux/security.h>
#include "internal.h"
struct poll_table_struct;
static ssize_t default_read_file(struct file *file, char __user *buf,
size_t count, loff_t *ppos)
{
return 0;
}
static ssize_t default_write_file(struct file *file, const char __user *buf,
size_t count, loff_t *ppos)
{
return count;
}
const struct file_operations debugfs_noop_file_operations = {
.read = default_read_file,
.write = default_write_file,
.open = simple_open,
.llseek = noop_llseek,
};
#define F_DENTRY(filp) ((filp)->f_path.dentry)
const struct file_operations *debugfs_real_fops(const struct file *filp)
{
struct debugfs_fsdata *fsd = F_DENTRY(filp)->d_fsdata;
if ((unsigned long)fsd & DEBUGFS_FSDATA_IS_REAL_FOPS_BIT) {
/*
* Urgh, we've been called w/o a protecting
* debugfs_file_get().
*/
WARN_ON(1);
return NULL;
}
return fsd->real_fops;
}
EXPORT_SYMBOL_GPL(debugfs_real_fops);
/**
* debugfs_file_get - mark the beginning of file data access
* @dentry: the dentry object whose data is being accessed.
*
* Up to a matching call to debugfs_file_put(), any successive call
* into the file removing functions debugfs_remove() and
* debugfs_remove_recursive() will block. Since associated private
* file data may only get freed after a successful return of any of
* the removal functions, you may safely access it after a successful
* call to debugfs_file_get() without worrying about lifetime issues.
*
* If -%EIO is returned, the file has already been removed and thus,
* it is not safe to access any of its data. If, on the other hand,
* it is allowed to access the file data, zero is returned.
*/
int debugfs_file_get(struct dentry *dentry)
{
struct debugfs_fsdata *fsd;
void *d_fsd;
d_fsd = READ_ONCE(dentry->d_fsdata);
if (!((unsigned long)d_fsd & DEBUGFS_FSDATA_IS_REAL_FOPS_BIT)) {
fsd = d_fsd;
} else {
fsd = kmalloc(sizeof(*fsd), GFP_KERNEL);
if (!fsd)
return -ENOMEM;
fsd->real_fops = (void *)((unsigned long)d_fsd &
~DEBUGFS_FSDATA_IS_REAL_FOPS_BIT);
refcount_set(&fsd->active_users, 1);
init_completion(&fsd->active_users_drained);
if (cmpxchg(&dentry->d_fsdata, d_fsd, fsd) != d_fsd) {
kfree(fsd);
fsd = READ_ONCE(dentry->d_fsdata);
}
}
/*
* In case of a successful cmpxchg() above, this check is
* strictly necessary and must follow it, see the comment in
* __debugfs_remove_file().
* OTOH, if the cmpxchg() hasn't been executed or wasn't
* successful, this serves the purpose of not starving
* removers.
*/
if (d_unlinked(dentry))
return -EIO;
if (!refcount_inc_not_zero(&fsd->active_users))
return -EIO;
return 0;
}
EXPORT_SYMBOL_GPL(debugfs_file_get);
/**
* debugfs_file_put - mark the end of file data access
* @dentry: the dentry object formerly passed to
* debugfs_file_get().
*
* Allow any ongoing concurrent call into debugfs_remove() or
* debugfs_remove_recursive() blocked by a former call to
* debugfs_file_get() to proceed and return to its caller.
*/
void debugfs_file_put(struct dentry *dentry)
{
struct debugfs_fsdata *fsd = READ_ONCE(dentry->d_fsdata);
if (refcount_dec_and_test(&fsd->active_users))
complete(&fsd->active_users_drained);
}
EXPORT_SYMBOL_GPL(debugfs_file_put);
/*
* Only permit access to world-readable files when the kernel is locked down.
* We also need to exclude any file that has ways to write or alter it as root
* can bypass the permissions check.
*/
static int debugfs_locked_down(struct inode *inode,
struct file *filp,
const struct file_operations *real_fops)
{
if ((inode->i_mode & 07777) == 0444 &&
!(filp->f_mode & FMODE_WRITE) &&
!real_fops->unlocked_ioctl &&
!real_fops->compat_ioctl &&
!real_fops->mmap)
return 0;
if (security_locked_down(LOCKDOWN_DEBUGFS))
return -EPERM;
return 0;
}
static int open_proxy_open(struct inode *inode, struct file *filp)
{
struct dentry *dentry = F_DENTRY(filp);
const struct file_operations *real_fops = NULL;
int r;
r = debugfs_file_get(dentry);
if (r)
return r == -EIO ? -ENOENT : r;
real_fops = debugfs_real_fops(filp);
r = debugfs_locked_down(inode, filp, real_fops);
if (r)
goto out;
if (!fops_get(real_fops)) {
#ifdef CONFIG_MODULES
if (real_fops->owner &&
real_fops->owner->state == MODULE_STATE_GOING)
goto out;
#endif
/* Huh? Module did not clean up after itself at exit? */
WARN(1, "debugfs file owner did not clean up at exit: %pd",
dentry);
r = -ENXIO;
goto out;
}
replace_fops(filp, real_fops);
if (real_fops->open)
r = real_fops->open(inode, filp);
out:
debugfs_file_put(dentry);
return r;
}
const struct file_operations debugfs_open_proxy_file_operations = {
.open = open_proxy_open,
};
#define PROTO(args...) args
#define ARGS(args...) args
#define FULL_PROXY_FUNC(name, ret_type, filp, proto, args) \
static ret_type full_proxy_ ## name(proto) \
{ \
struct dentry *dentry = F_DENTRY(filp); \
const struct file_operations *real_fops; \
ret_type r; \
\
r = debugfs_file_get(dentry); \
if (unlikely(r)) \
return r; \
real_fops = debugfs_real_fops(filp); \
r = real_fops->name(args); \
debugfs_file_put(dentry); \
return r; \
}
FULL_PROXY_FUNC(llseek, loff_t, filp,
PROTO(struct file *filp, loff_t offset, int whence),
ARGS(filp, offset, whence));
FULL_PROXY_FUNC(read, ssize_t, filp,
PROTO(struct file *filp, char __user *buf, size_t size,
loff_t *ppos),
ARGS(filp, buf, size, ppos));
FULL_PROXY_FUNC(write, ssize_t, filp,
PROTO(struct file *filp, const char __user *buf, size_t size,
loff_t *ppos),
ARGS(filp, buf, size, ppos));
FULL_PROXY_FUNC(unlocked_ioctl, long, filp,
PROTO(struct file *filp, unsigned int cmd, unsigned long arg),
ARGS(filp, cmd, arg));
static __poll_t full_proxy_poll(struct file *filp,
struct poll_table_struct *wait)
{
struct dentry *dentry = F_DENTRY(filp);
__poll_t r = 0;
const struct file_operations *real_fops;
if (debugfs_file_get(dentry))
return EPOLLHUP;
real_fops = debugfs_real_fops(filp);
r = real_fops->poll(filp, wait);
debugfs_file_put(dentry);
return r;
}
static int full_proxy_release(struct inode *inode, struct file *filp)
{
const struct dentry *dentry = F_DENTRY(filp);
const struct file_operations *real_fops = debugfs_real_fops(filp);
const struct file_operations *proxy_fops = filp->f_op;
int r = 0;
/*
* We must not protect this against removal races here: the
* original releaser should be called unconditionally in order
* not to leak any resources. Releasers must not assume that
* ->i_private is still being meaningful here.
*/
if (real_fops->release)
r = real_fops->release(inode, filp);
replace_fops(filp, d_inode(dentry)->i_fop);
kfree(proxy_fops);
fops_put(real_fops);
return r;
}
static void __full_proxy_fops_init(struct file_operations *proxy_fops,
const struct file_operations *real_fops)
{
proxy_fops->release = full_proxy_release;
if (real_fops->llseek)
proxy_fops->llseek = full_proxy_llseek;
if (real_fops->read)
proxy_fops->read = full_proxy_read;
if (real_fops->write)
proxy_fops->write = full_proxy_write;
if (real_fops->poll)
proxy_fops->poll = full_proxy_poll;
if (real_fops->unlocked_ioctl)
proxy_fops->unlocked_ioctl = full_proxy_unlocked_ioctl;
}
static int full_proxy_open(struct inode *inode, struct file *filp)
{
struct dentry *dentry = F_DENTRY(filp);
const struct file_operations *real_fops = NULL;
struct file_operations *proxy_fops = NULL;
int r;
r = debugfs_file_get(dentry);
if (r)
return r == -EIO ? -ENOENT : r;
real_fops = debugfs_real_fops(filp);
r = debugfs_locked_down(inode, filp, real_fops);
if (r)
goto out;
if (!fops_get(real_fops)) {
#ifdef CONFIG_MODULES
if (real_fops->owner &&
real_fops->owner->state == MODULE_STATE_GOING)
goto out;
#endif
/* Huh? Module did not cleanup after itself at exit? */
WARN(1, "debugfs file owner did not clean up at exit: %pd",
dentry);
r = -ENXIO;
goto out;
}
proxy_fops = kzalloc(sizeof(*proxy_fops), GFP_KERNEL);
if (!proxy_fops) {
r = -ENOMEM;
goto free_proxy;
}
__full_proxy_fops_init(proxy_fops, real_fops);
replace_fops(filp, proxy_fops);
if (real_fops->open) {
r = real_fops->open(inode, filp);
if (r) {
replace_fops(filp, d_inode(dentry)->i_fop);
goto free_proxy;
} else if (filp->f_op != proxy_fops) {
/* No protection against file removal anymore. */
WARN(1, "debugfs file owner replaced proxy fops: %pd",
dentry);
goto free_proxy;
}
}
goto out;
free_proxy:
kfree(proxy_fops);
fops_put(real_fops);
out:
debugfs_file_put(dentry);
return r;
}
const struct file_operations debugfs_full_proxy_file_operations = {
.open = full_proxy_open,
};
ssize_t debugfs_attr_read(struct file *file, char __user *buf,
size_t len, loff_t *ppos)
{
struct dentry *dentry = F_DENTRY(file);
ssize_t ret;
ret = debugfs_file_get(dentry);
if (unlikely(ret))
return ret;
ret = simple_attr_read(file, buf, len, ppos);
debugfs_file_put(dentry);
return ret;
}
EXPORT_SYMBOL_GPL(debugfs_attr_read);
ssize_t debugfs_attr_write(struct file *file, const char __user *buf,
size_t len, loff_t *ppos)
{
struct dentry *dentry = F_DENTRY(file);
ssize_t ret;
ret = debugfs_file_get(dentry);
if (unlikely(ret))
return ret;
ret = simple_attr_write(file, buf, len, ppos);
debugfs_file_put(dentry);
return ret;
}
EXPORT_SYMBOL_GPL(debugfs_attr_write);
static struct dentry *debugfs_create_mode_unsafe(const char *name, umode_t mode,
struct dentry *parent, void *value,
const struct file_operations *fops,
const struct file_operations *fops_ro,
const struct file_operations *fops_wo)
{
/* if there are no write bits set, make read only */
if (!(mode & S_IWUGO))
return debugfs_create_file_unsafe(name, mode, parent, value,
fops_ro);
/* if there are no read bits set, make write only */
if (!(mode & S_IRUGO))
return debugfs_create_file_unsafe(name, mode, parent, value,
fops_wo);
return debugfs_create_file_unsafe(name, mode, parent, value, fops);
}
static int debugfs_u8_set(void *data, u64 val)
{
*(u8 *)data = val;
return 0;
}
static int debugfs_u8_get(void *data, u64 *val)
{
*val = *(u8 *)data;
return 0;
}
DEFINE_DEBUGFS_ATTRIBUTE(fops_u8, debugfs_u8_get, debugfs_u8_set, "%llu\n");
DEFINE_DEBUGFS_ATTRIBUTE(fops_u8_ro, debugfs_u8_get, NULL, "%llu\n");
DEFINE_DEBUGFS_ATTRIBUTE(fops_u8_wo, NULL, debugfs_u8_set, "%llu\n");
/**
* debugfs_create_u8 - create a debugfs file that is used to read and write an unsigned 8-bit value
* @name: a pointer to a string containing the name of the file to create.
* @mode: the permission that the file should have
* @parent: a pointer to the parent dentry for this file. This should be a
* directory dentry if set. If this parameter is %NULL, then the
* file will be created in the root of the debugfs filesystem.
* @value: a pointer to the variable that the file should read to and write
* from.
*
* This function creates a file in debugfs with the given name that
* contains the value of the variable @value. If the @mode variable is so
* set, it can be read from, and written to.
*/
void debugfs_create_u8(const char *name, umode_t mode, struct dentry *parent,
u8 *value)
{
debugfs_create_mode_unsafe(name, mode, parent, value, &fops_u8,
&fops_u8_ro, &fops_u8_wo);
}
EXPORT_SYMBOL_GPL(debugfs_create_u8);
static int debugfs_u16_set(void *data, u64 val)
{
*(u16 *)data = val;
return 0;
}
static int debugfs_u16_get(void *data, u64 *val)
{
*val = *(u16 *)data;
return 0;
}
DEFINE_DEBUGFS_ATTRIBUTE(fops_u16, debugfs_u16_get, debugfs_u16_set, "%llu\n");
DEFINE_DEBUGFS_ATTRIBUTE(fops_u16_ro, debugfs_u16_get, NULL, "%llu\n");
DEFINE_DEBUGFS_ATTRIBUTE(fops_u16_wo, NULL, debugfs_u16_set, "%llu\n");
/**
* debugfs_create_u16 - create a debugfs file that is used to read and write an unsigned 16-bit value
* @name: a pointer to a string containing the name of the file to create.
* @mode: the permission that the file should have
* @parent: a pointer to the parent dentry for this file. This should be a
* directory dentry if set. If this parameter is %NULL, then the
* file will be created in the root of the debugfs filesystem.
* @value: a pointer to the variable that the file should read to and write
* from.
*
* This function creates a file in debugfs with the given name that
* contains the value of the variable @value. If the @mode variable is so
* set, it can be read from, and written to.
*/
void debugfs_create_u16(const char *name, umode_t mode, struct dentry *parent,
u16 *value)
{
debugfs_create_mode_unsafe(name, mode, parent, value, &fops_u16,
&fops_u16_ro, &fops_u16_wo);
}
EXPORT_SYMBOL_GPL(debugfs_create_u16);
static int debugfs_u32_set(void *data, u64 val)
{
*(u32 *)data = val;
return 0;
}
static int debugfs_u32_get(void *data, u64 *val)
{
*val = *(u32 *)data;
return 0;
}
DEFINE_DEBUGFS_ATTRIBUTE(fops_u32, debugfs_u32_get, debugfs_u32_set, "%llu\n");
DEFINE_DEBUGFS_ATTRIBUTE(fops_u32_ro, debugfs_u32_get, NULL, "%llu\n");
DEFINE_DEBUGFS_ATTRIBUTE(fops_u32_wo, NULL, debugfs_u32_set, "%llu\n");
/**
* debugfs_create_u32 - create a debugfs file that is used to read and write an unsigned 32-bit value
* @name: a pointer to a string containing the name of the file to create.
* @mode: the permission that the file should have
* @parent: a pointer to the parent dentry for this file. This should be a
* directory dentry if set. If this parameter is %NULL, then the
* file will be created in the root of the debugfs filesystem.
* @value: a pointer to the variable that the file should read to and write
* from.
*
* This function creates a file in debugfs with the given name that
* contains the value of the variable @value. If the @mode variable is so
* set, it can be read from, and written to.
*/
void debugfs_create_u32(const char *name, umode_t mode, struct dentry *parent,
u32 *value)
{
debugfs_create_mode_unsafe(name, mode, parent, value, &fops_u32,
&fops_u32_ro, &fops_u32_wo);
}
EXPORT_SYMBOL_GPL(debugfs_create_u32);
static int debugfs_u64_set(void *data, u64 val)
{
*(u64 *)data = val;
return 0;
}
static int debugfs_u64_get(void *data, u64 *val)
{
*val = *(u64 *)data;
return 0;
}
DEFINE_DEBUGFS_ATTRIBUTE(fops_u64, debugfs_u64_get, debugfs_u64_set, "%llu\n");
DEFINE_DEBUGFS_ATTRIBUTE(fops_u64_ro, debugfs_u64_get, NULL, "%llu\n");
DEFINE_DEBUGFS_ATTRIBUTE(fops_u64_wo, NULL, debugfs_u64_set, "%llu\n");
/**
* debugfs_create_u64 - create a debugfs file that is used to read and write an unsigned 64-bit value
* @name: a pointer to a string containing the name of the file to create.
* @mode: the permission that the file should have
* @parent: a pointer to the parent dentry for this file. This should be a
* directory dentry if set. If this parameter is %NULL, then the
* file will be created in the root of the debugfs filesystem.
* @value: a pointer to the variable that the file should read to and write
* from.
*
* This function creates a file in debugfs with the given name that
* contains the value of the variable @value. If the @mode variable is so
* set, it can be read from, and written to.
*/
void debugfs_create_u64(const char *name, umode_t mode, struct dentry *parent,
u64 *value)
{
debugfs_create_mode_unsafe(name, mode, parent, value, &fops_u64,
&fops_u64_ro, &fops_u64_wo);
}
EXPORT_SYMBOL_GPL(debugfs_create_u64);
static int debugfs_ulong_set(void *data, u64 val)
{
*(unsigned long *)data = val;
return 0;
}
static int debugfs_ulong_get(void *data, u64 *val)
{
*val = *(unsigned long *)data;
return 0;
}
DEFINE_DEBUGFS_ATTRIBUTE(fops_ulong, debugfs_ulong_get, debugfs_ulong_set,
"%llu\n");
DEFINE_DEBUGFS_ATTRIBUTE(fops_ulong_ro, debugfs_ulong_get, NULL, "%llu\n");
DEFINE_DEBUGFS_ATTRIBUTE(fops_ulong_wo, NULL, debugfs_ulong_set, "%llu\n");
/**
* debugfs_create_ulong - create a debugfs file that is used to read and write
* an unsigned long value.
* @name: a pointer to a string containing the name of the file to create.
* @mode: the permission that the file should have
* @parent: a pointer to the parent dentry for this file. This should be a
* directory dentry if set. If this parameter is %NULL, then the
* file will be created in the root of the debugfs filesystem.
* @value: a pointer to the variable that the file should read to and write
* from.
*
* This function creates a file in debugfs with the given name that
* contains the value of the variable @value. If the @mode variable is so
* set, it can be read from, and written to.
*
* This function will return a pointer to a dentry if it succeeds. This
* pointer must be passed to the debugfs_remove() function when the file is
* to be removed (no automatic cleanup happens if your module is unloaded,
* you are responsible here.) If an error occurs, ERR_PTR(-ERROR) will be
* returned.
*
* If debugfs is not enabled in the kernel, the value ERR_PTR(-ENODEV) will
* be returned.
*/
struct dentry *debugfs_create_ulong(const char *name, umode_t mode,
struct dentry *parent, unsigned long *value)
{
return debugfs_create_mode_unsafe(name, mode, parent, value,
&fops_ulong, &fops_ulong_ro,
&fops_ulong_wo);
}
EXPORT_SYMBOL_GPL(debugfs_create_ulong);
DEFINE_DEBUGFS_ATTRIBUTE(fops_x8, debugfs_u8_get, debugfs_u8_set, "0x%02llx\n");
DEFINE_DEBUGFS_ATTRIBUTE(fops_x8_ro, debugfs_u8_get, NULL, "0x%02llx\n");
DEFINE_DEBUGFS_ATTRIBUTE(fops_x8_wo, NULL, debugfs_u8_set, "0x%02llx\n");
DEFINE_DEBUGFS_ATTRIBUTE(fops_x16, debugfs_u16_get, debugfs_u16_set,
"0x%04llx\n");
DEFINE_DEBUGFS_ATTRIBUTE(fops_x16_ro, debugfs_u16_get, NULL, "0x%04llx\n");
DEFINE_DEBUGFS_ATTRIBUTE(fops_x16_wo, NULL, debugfs_u16_set, "0x%04llx\n");
DEFINE_DEBUGFS_ATTRIBUTE(fops_x32, debugfs_u32_get, debugfs_u32_set,
"0x%08llx\n");
DEFINE_DEBUGFS_ATTRIBUTE(fops_x32_ro, debugfs_u32_get, NULL, "0x%08llx\n");
DEFINE_DEBUGFS_ATTRIBUTE(fops_x32_wo, NULL, debugfs_u32_set, "0x%08llx\n");
DEFINE_DEBUGFS_ATTRIBUTE(fops_x64, debugfs_u64_get, debugfs_u64_set,
"0x%016llx\n");
DEFINE_DEBUGFS_ATTRIBUTE(fops_x64_ro, debugfs_u64_get, NULL, "0x%016llx\n");
DEFINE_DEBUGFS_ATTRIBUTE(fops_x64_wo, NULL, debugfs_u64_set, "0x%016llx\n");
/*
* debugfs_create_x{8,16,32,64} - create a debugfs file that is used to read and write an unsigned {8,16,32,64}-bit value
*
* These functions are exactly the same as the above functions (but use a hex
* output for the decimal challenged). For details look at the above unsigned
* decimal functions.
*/
/**
* debugfs_create_x8 - create a debugfs file that is used to read and write an unsigned 8-bit value
* @name: a pointer to a string containing the name of the file to create.
* @mode: the permission that the file should have
* @parent: a pointer to the parent dentry for this file. This should be a
* directory dentry if set. If this parameter is %NULL, then the
* file will be created in the root of the debugfs filesystem.
* @value: a pointer to the variable that the file should read to and write
* from.
*/
void debugfs_create_x8(const char *name, umode_t mode, struct dentry *parent,
u8 *value)
{
debugfs_create_mode_unsafe(name, mode, parent, value, &fops_x8,
&fops_x8_ro, &fops_x8_wo);
}
EXPORT_SYMBOL_GPL(debugfs_create_x8);
/**
* debugfs_create_x16 - create a debugfs file that is used to read and write an unsigned 16-bit value
* @name: a pointer to a string containing the name of the file to create.
* @mode: the permission that the file should have
* @parent: a pointer to the parent dentry for this file. This should be a
* directory dentry if set. If this parameter is %NULL, then the
* file will be created in the root of the debugfs filesystem.
* @value: a pointer to the variable that the file should read to and write
* from.
*/
void debugfs_create_x16(const char *name, umode_t mode, struct dentry *parent,
u16 *value)
{
debugfs_create_mode_unsafe(name, mode, parent, value, &fops_x16,
&fops_x16_ro, &fops_x16_wo);
}
EXPORT_SYMBOL_GPL(debugfs_create_x16);
/**
* debugfs_create_x32 - create a debugfs file that is used to read and write an unsigned 32-bit value
* @name: a pointer to a string containing the name of the file to create.
* @mode: the permission that the file should have
* @parent: a pointer to the parent dentry for this file. This should be a
* directory dentry if set. If this parameter is %NULL, then the
* file will be created in the root of the debugfs filesystem.
* @value: a pointer to the variable that the file should read to and write
* from.
*/
void debugfs_create_x32(const char *name, umode_t mode, struct dentry *parent,
u32 *value)
{
debugfs_create_mode_unsafe(name, mode, parent, value, &fops_x32,
&fops_x32_ro, &fops_x32_wo);
}
EXPORT_SYMBOL_GPL(debugfs_create_x32);
/**
* debugfs_create_x64 - create a debugfs file that is used to read and write an unsigned 64-bit value
* @name: a pointer to a string containing the name of the file to create.
* @mode: the permission that the file should have
* @parent: a pointer to the parent dentry for this file. This should be a
* directory dentry if set. If this parameter is %NULL, then the
* file will be created in the root of the debugfs filesystem.
* @value: a pointer to the variable that the file should read to and write
* from.
*/
void debugfs_create_x64(const char *name, umode_t mode, struct dentry *parent,
u64 *value)
{
debugfs_create_mode_unsafe(name, mode, parent, value, &fops_x64,
&fops_x64_ro, &fops_x64_wo);
}
EXPORT_SYMBOL_GPL(debugfs_create_x64);
static int debugfs_size_t_set(void *data, u64 val)
{
*(size_t *)data = val;
return 0;
}
static int debugfs_size_t_get(void *data, u64 *val)
{
*val = *(size_t *)data;
return 0;
}
DEFINE_DEBUGFS_ATTRIBUTE(fops_size_t, debugfs_size_t_get, debugfs_size_t_set,
"%llu\n"); /* %llu and %zu are more or less the same */
DEFINE_DEBUGFS_ATTRIBUTE(fops_size_t_ro, debugfs_size_t_get, NULL, "%llu\n");
DEFINE_DEBUGFS_ATTRIBUTE(fops_size_t_wo, NULL, debugfs_size_t_set, "%llu\n");
/**
* debugfs_create_size_t - create a debugfs file that is used to read and write an size_t value
* @name: a pointer to a string containing the name of the file to create.
* @mode: the permission that the file should have
* @parent: a pointer to the parent dentry for this file. This should be a
* directory dentry if set. If this parameter is %NULL, then the
* file will be created in the root of the debugfs filesystem.
* @value: a pointer to the variable that the file should read to and write
* from.
*/
void debugfs_create_size_t(const char *name, umode_t mode,
struct dentry *parent, size_t *value)
{
debugfs_create_mode_unsafe(name, mode, parent, value, &fops_size_t,
&fops_size_t_ro, &fops_size_t_wo);
}
EXPORT_SYMBOL_GPL(debugfs_create_size_t);
static int debugfs_atomic_t_set(void *data, u64 val)
{
atomic_set((atomic_t *)data, val);
return 0;
}
static int debugfs_atomic_t_get(void *data, u64 *val)
{
*val = atomic_read((atomic_t *)data);
return 0;
}
DEFINE_DEBUGFS_ATTRIBUTE(fops_atomic_t, debugfs_atomic_t_get,
debugfs_atomic_t_set, "%lld\n");
DEFINE_DEBUGFS_ATTRIBUTE(fops_atomic_t_ro, debugfs_atomic_t_get, NULL,
"%lld\n");
DEFINE_DEBUGFS_ATTRIBUTE(fops_atomic_t_wo, NULL, debugfs_atomic_t_set,
"%lld\n");
/**
* debugfs_create_atomic_t - create a debugfs file that is used to read and
* write an atomic_t value
* @name: a pointer to a string containing the name of the file to create.
* @mode: the permission that the file should have
* @parent: a pointer to the parent dentry for this file. This should be a
* directory dentry if set. If this parameter is %NULL, then the
* file will be created in the root of the debugfs filesystem.
* @value: a pointer to the variable that the file should read to and write
* from.
*/
void debugfs_create_atomic_t(const char *name, umode_t mode,
struct dentry *parent, atomic_t *value)
{
debugfs_create_mode_unsafe(name, mode, parent, value, &fops_atomic_t,
&fops_atomic_t_ro, &fops_atomic_t_wo);
}
EXPORT_SYMBOL_GPL(debugfs_create_atomic_t);
ssize_t debugfs_read_file_bool(struct file *file, char __user *user_buf,
size_t count, loff_t *ppos)
{
char buf[3];
bool val;
int r;
struct dentry *dentry = F_DENTRY(file);
r = debugfs_file_get(dentry);
if (unlikely(r))
return r;
val = *(bool *)file->private_data;
debugfs_file_put(dentry);
if (val)
buf[0] = 'Y';
else
buf[0] = 'N';
buf[1] = '\n';
buf[2] = 0x00;
return simple_read_from_buffer(user_buf, count, ppos, buf, 2);
}
EXPORT_SYMBOL_GPL(debugfs_read_file_bool);
ssize_t debugfs_write_file_bool(struct file *file, const char __user *user_buf,
size_t count, loff_t *ppos)
{
bool bv;
int r;
bool *val = file->private_data;
struct dentry *dentry = F_DENTRY(file);
r = kstrtobool_from_user(user_buf, count, &bv);
if (!r) {
r = debugfs_file_get(dentry);
if (unlikely(r))
return r;
*val = bv;
debugfs_file_put(dentry);
}
return count;
}
EXPORT_SYMBOL_GPL(debugfs_write_file_bool);
static const struct file_operations fops_bool = {
.read = debugfs_read_file_bool,
.write = debugfs_write_file_bool,
.open = simple_open,
.llseek = default_llseek,
};
static const struct file_operations fops_bool_ro = {
.read = debugfs_read_file_bool,
.open = simple_open,
.llseek = default_llseek,
};
static const struct file_operations fops_bool_wo = {
.write = debugfs_write_file_bool,
.open = simple_open,
.llseek = default_llseek,
};
/**
* debugfs_create_bool - create a debugfs file that is used to read and write a boolean value
* @name: a pointer to a string containing the name of the file to create.
* @mode: the permission that the file should have
* @parent: a pointer to the parent dentry for this file. This should be a
* directory dentry if set. If this parameter is %NULL, then the
* file will be created in the root of the debugfs filesystem.
* @value: a pointer to the variable that the file should read to and write
* from.
*
* This function creates a file in debugfs with the given name that
* contains the value of the variable @value. If the @mode variable is so
* set, it can be read from, and written to.
*
* This function will return a pointer to a dentry if it succeeds. This
* pointer must be passed to the debugfs_remove() function when the file is
* to be removed (no automatic cleanup happens if your module is unloaded,
* you are responsible here.) If an error occurs, ERR_PTR(-ERROR) will be
* returned.
*
* If debugfs is not enabled in the kernel, the value ERR_PTR(-ENODEV) will
* be returned.
*/
struct dentry *debugfs_create_bool(const char *name, umode_t mode,
struct dentry *parent, bool *value)
{
return debugfs_create_mode_unsafe(name, mode, parent, value, &fops_bool,
&fops_bool_ro, &fops_bool_wo);
}
EXPORT_SYMBOL_GPL(debugfs_create_bool);
static ssize_t read_file_blob(struct file *file, char __user *user_buf,
size_t count, loff_t *ppos)
{
struct debugfs_blob_wrapper *blob = file->private_data;
struct dentry *dentry = F_DENTRY(file);
ssize_t r;
r = debugfs_file_get(dentry);
if (unlikely(r))
return r;
r = simple_read_from_buffer(user_buf, count, ppos, blob->data,
blob->size);
debugfs_file_put(dentry);
return r;
}
static const struct file_operations fops_blob = {
.read = read_file_blob,
.open = simple_open,
.llseek = default_llseek,
};
/**
* debugfs_create_blob - create a debugfs file that is used to read a binary blob
* @name: a pointer to a string containing the name of the file to create.
* @mode: the permission that the file should have
* @parent: a pointer to the parent dentry for this file. This should be a
* directory dentry if set. If this parameter is %NULL, then the
* file will be created in the root of the debugfs filesystem.
* @blob: a pointer to a struct debugfs_blob_wrapper which contains a pointer
* to the blob data and the size of the data.
*
* This function creates a file in debugfs with the given name that exports
* @blob->data as a binary blob. If the @mode variable is so set it can be
* read from. Writing is not supported.
*
* This function will return a pointer to a dentry if it succeeds. This
* pointer must be passed to the debugfs_remove() function when the file is
* to be removed (no automatic cleanup happens if your module is unloaded,
* you are responsible here.) If an error occurs, ERR_PTR(-ERROR) will be
* returned.
*
* If debugfs is not enabled in the kernel, the value ERR_PTR(-ENODEV) will
* be returned.
*/
struct dentry *debugfs_create_blob(const char *name, umode_t mode,
struct dentry *parent,
struct debugfs_blob_wrapper *blob)
{
return debugfs_create_file_unsafe(name, mode, parent, blob, &fops_blob);
}
EXPORT_SYMBOL_GPL(debugfs_create_blob);
static size_t u32_format_array(char *buf, size_t bufsize,
u32 *array, int array_size)
{
size_t ret = 0;
while (--array_size >= 0) {
size_t len;
char term = array_size ? ' ' : '\n';
len = snprintf(buf, bufsize, "%u%c", *array++, term);
ret += len;
buf += len;
bufsize -= len;
}
return ret;
}
static int u32_array_open(struct inode *inode, struct file *file)
{
struct debugfs_u32_array *data = inode->i_private;
int size, elements = data->n_elements;
char *buf;
/*
* Max size:
* - 10 digits + ' '/'\n' = 11 bytes per number
* - terminating NUL character
*/
size = elements*11;
buf = kmalloc(size+1, GFP_KERNEL);
if (!buf)
return -ENOMEM;
buf[size] = 0;
file->private_data = buf;
u32_format_array(buf, size, data->array, data->n_elements);
return nonseekable_open(inode, file);
}
static ssize_t u32_array_read(struct file *file, char __user *buf, size_t len,
loff_t *ppos)
{
size_t size = strlen(file->private_data);
return simple_read_from_buffer(buf, len, ppos,
file->private_data, size);
}
static int u32_array_release(struct inode *inode, struct file *file)
{
kfree(file->private_data);
return 0;
}
static const struct file_operations u32_array_fops = {
.owner = THIS_MODULE,
.open = u32_array_open,
.release = u32_array_release,
.read = u32_array_read,
.llseek = no_llseek,
};
/**
* debugfs_create_u32_array - create a debugfs file that is used to read u32
* array.
* @name: a pointer to a string containing the name of the file to create.
* @mode: the permission that the file should have.
* @parent: a pointer to the parent dentry for this file. This should be a
* directory dentry if set. If this parameter is %NULL, then the
* file will be created in the root of the debugfs filesystem.
* @array: wrapper struct containing data pointer and size of the array.
*
* This function creates a file in debugfs with the given name that exports
* @array as data. If the @mode variable is so set it can be read from.
* Writing is not supported. Seek within the file is also not supported.
* Once array is created its size can not be changed.
*/
void debugfs_create_u32_array(const char *name, umode_t mode,
struct dentry *parent,
struct debugfs_u32_array *array)
{
debugfs_create_file_unsafe(name, mode, parent, array, &u32_array_fops);
}
EXPORT_SYMBOL_GPL(debugfs_create_u32_array);
#ifdef CONFIG_HAS_IOMEM
/*
* The regset32 stuff is used to print 32-bit registers using the
* seq_file utilities. We offer printing a register set in an already-opened
* sequential file or create a debugfs file that only prints a regset32.
*/
/**
* debugfs_print_regs32 - use seq_print to describe a set of registers
* @s: the seq_file structure being used to generate output
* @regs: an array if struct debugfs_reg32 structures
* @nregs: the length of the above array
* @base: the base address to be used in reading the registers
* @prefix: a string to be prefixed to every output line
*
* This function outputs a text block describing the current values of
* some 32-bit hardware registers. It is meant to be used within debugfs
* files based on seq_file that need to show registers, intermixed with other
* information. The prefix argument may be used to specify a leading string,
* because some peripherals have several blocks of identical registers,
* for example configuration of dma channels
*/
void debugfs_print_regs32(struct seq_file *s, const struct debugfs_reg32 *regs,
int nregs, void __iomem *base, char *prefix)
{
int i;
for (i = 0; i < nregs; i++, regs++) {
if (prefix)
seq_printf(s, "%s", prefix);
seq_printf(s, "%s = 0x%08x\n", regs->name,
readl(base + regs->offset));
if (seq_has_overflowed(s))
break;
}
}
EXPORT_SYMBOL_GPL(debugfs_print_regs32);
static int debugfs_show_regset32(struct seq_file *s, void *data)
{
struct debugfs_regset32 *regset = s->private;
if (regset->dev)
pm_runtime_get_sync(regset->dev);
debugfs_print_regs32(s, regset->regs, regset->nregs, regset->base, "");
if (regset->dev)
pm_runtime_put(regset->dev);
return 0;
}
static int debugfs_open_regset32(struct inode *inode, struct file *file)
{
return single_open(file, debugfs_show_regset32, inode->i_private);
}
static const struct file_operations fops_regset32 = {
.open = debugfs_open_regset32,
.read = seq_read,
.llseek = seq_lseek,
.release = single_release,
};
/**
* debugfs_create_regset32 - create a debugfs file that returns register values
* @name: a pointer to a string containing the name of the file to create.
* @mode: the permission that the file should have
* @parent: a pointer to the parent dentry for this file. This should be a
* directory dentry if set. If this parameter is %NULL, then the
* file will be created in the root of the debugfs filesystem.
* @regset: a pointer to a struct debugfs_regset32, which contains a pointer
* to an array of register definitions, the array size and the base
* address where the register bank is to be found.
*
* This function creates a file in debugfs with the given name that reports
* the names and values of a set of 32-bit registers. If the @mode variable
* is so set it can be read from. Writing is not supported.
*/
void debugfs_create_regset32(const char *name, umode_t mode,
struct dentry *parent,
struct debugfs_regset32 *regset)
{
debugfs_create_file(name, mode, parent, regset, &fops_regset32);
}
EXPORT_SYMBOL_GPL(debugfs_create_regset32);
#endif /* CONFIG_HAS_IOMEM */
struct debugfs_devm_entry {
int (*read)(struct seq_file *seq, void *data);
struct device *dev;
};
static int debugfs_devm_entry_open(struct inode *inode, struct file *f)
{
struct debugfs_devm_entry *entry = inode->i_private;
return single_open(f, entry->read, entry->dev);
}
static const struct file_operations debugfs_devm_entry_ops = {
.owner = THIS_MODULE,
.open = debugfs_devm_entry_open,
.release = single_release,
.read = seq_read,
.llseek = seq_lseek
};
/**
* debugfs_create_devm_seqfile - create a debugfs file that is bound to device.
*
* @dev: device related to this debugfs file.
* @name: name of the debugfs file.
* @parent: a pointer to the parent dentry for this file. This should be a
* directory dentry if set. If this parameter is %NULL, then the
* file will be created in the root of the debugfs filesystem.
* @read_fn: function pointer called to print the seq_file content.
*/
void debugfs_create_devm_seqfile(struct device *dev, const char *name,
struct dentry *parent,
int (*read_fn)(struct seq_file *s, void *data))
{
struct debugfs_devm_entry *entry;
if (IS_ERR(parent))
return;
entry = devm_kzalloc(dev, sizeof(*entry), GFP_KERNEL);
if (!entry)
return;
entry->read = read_fn;
entry->dev = dev;
debugfs_create_file(name, S_IRUGO, parent, entry,
&debugfs_devm_entry_ops);
}
EXPORT_SYMBOL_GPL(debugfs_create_devm_seqfile);
|
504667.c | /*
* The MIT License
*
* Copyright (C) 2010-2016 Alexander Saprykin <[email protected]>
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* 'Software'), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include "pprocess.h"
#ifndef P_OS_WIN
# include <sys/types.h>
# include <signal.h>
# include <unistd.h>
#endif
P_LIB_API puint32
p_process_get_current_pid (void)
{
#ifdef P_OS_WIN
return (puint32) GetCurrentProcessId ();
#else
return (puint32) getpid ();
#endif
}
P_LIB_API pboolean
p_process_is_running (puint32 pid)
{
#ifdef P_OS_WIN
HANDLE proc;
DWORD ret;
if ((proc = OpenProcess (SYNCHRONIZE, FALSE, pid)) == NULL)
return FALSE;
ret = WaitForSingleObject (proc, 0);
CloseHandle (proc);
return ret == WAIT_TIMEOUT;
#else
return kill ((pid_t) pid, 0) == 0;
#endif
}
|
73617.c | /*
* Copyright 2012 Red Hat Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice 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 COPYRIGHT HOLDER(S) OR AUTHOR(S) 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.
*
* Authors: Ben Skeggs
*/
#include <core/gpuobj.h>
#include <core/class.h>
#include <subdev/fb.h>
#include <engine/dmaobj.h>
struct nv50_dmaeng_priv {
struct nouveau_dmaeng base;
};
struct nv50_dmaobj_priv {
struct nouveau_dmaobj base;
};
static int
nv50_dmaobj_bind(struct nouveau_dmaeng *dmaeng,
struct nouveau_object *parent,
struct nouveau_dmaobj *dmaobj,
struct nouveau_gpuobj **pgpuobj)
{
u32 flags = nv_mclass(dmaobj);
int ret;
switch (dmaobj->target) {
case NV_MEM_TARGET_VM:
flags |= 0x00000000;
flags |= 0x60000000; /* COMPRESSION_USEVM */
flags |= 0x1fc00000; /* STORAGE_TYPE_USEVM */
break;
case NV_MEM_TARGET_VRAM:
flags |= 0x00010000;
flags |= 0x00100000; /* ACCESSUS_USER_SYSTEM */
break;
case NV_MEM_TARGET_PCI:
flags |= 0x00020000;
flags |= 0x00100000; /* ACCESSUS_USER_SYSTEM */
break;
case NV_MEM_TARGET_PCI_NOSNOOP:
flags |= 0x00030000;
flags |= 0x00100000; /* ACCESSUS_USER_SYSTEM */
break;
default:
return -EINVAL;
}
switch (dmaobj->access) {
case NV_MEM_ACCESS_VM:
break;
case NV_MEM_ACCESS_RO:
flags |= 0x00040000;
break;
case NV_MEM_ACCESS_WO:
case NV_MEM_ACCESS_RW:
flags |= 0x00080000;
break;
}
ret = nouveau_gpuobj_new(parent, parent, 24, 32, 0, pgpuobj);
if (ret == 0) {
nv_wo32(*pgpuobj, 0x00, flags);
nv_wo32(*pgpuobj, 0x04, lower_32_bits(dmaobj->limit));
nv_wo32(*pgpuobj, 0x08, lower_32_bits(dmaobj->start));
nv_wo32(*pgpuobj, 0x0c, upper_32_bits(dmaobj->limit) << 24 |
upper_32_bits(dmaobj->start));
nv_wo32(*pgpuobj, 0x10, 0x00000000);
nv_wo32(*pgpuobj, 0x14, 0x00000000);
}
return ret;
}
static int
nv50_dmaobj_ctor(struct nouveau_object *parent, struct nouveau_object *engine,
struct nouveau_oclass *oclass, void *data, u32 size,
struct nouveau_object **pobject)
{
struct nouveau_dmaeng *dmaeng = (void *)engine;
struct nv50_dmaobj_priv *dmaobj;
struct nouveau_gpuobj *gpuobj;
int ret;
ret = nouveau_dmaobj_create(parent, engine, oclass,
data, size, &dmaobj);
*pobject = nv_object(dmaobj);
if (ret)
return ret;
switch (nv_mclass(parent)) {
case NV_DEVICE_CLASS:
break;
case NV50_CHANNEL_DMA_CLASS:
case NV84_CHANNEL_DMA_CLASS:
case NV50_CHANNEL_IND_CLASS:
case NV84_CHANNEL_IND_CLASS:
ret = dmaeng->bind(dmaeng, *pobject, &dmaobj->base, &gpuobj);
nouveau_object_ref(NULL, pobject);
*pobject = nv_object(gpuobj);
break;
default:
return -EINVAL;
}
return ret;
}
static struct nouveau_ofuncs
nv50_dmaobj_ofuncs = {
.ctor = nv50_dmaobj_ctor,
.dtor = _nouveau_dmaobj_dtor,
.init = _nouveau_dmaobj_init,
.fini = _nouveau_dmaobj_fini,
};
static struct nouveau_oclass
nv50_dmaobj_sclass[] = {
{ 0x0002, &nv50_dmaobj_ofuncs },
{ 0x0003, &nv50_dmaobj_ofuncs },
{ 0x003d, &nv50_dmaobj_ofuncs },
{}
};
static int
nv50_dmaeng_ctor(struct nouveau_object *parent, struct nouveau_object *engine,
struct nouveau_oclass *oclass, void *data, u32 size,
struct nouveau_object **pobject)
{
struct nv50_dmaeng_priv *priv;
int ret;
ret = nouveau_dmaeng_create(parent, engine, oclass, &priv);
*pobject = nv_object(priv);
if (ret)
return ret;
priv->base.base.sclass = nv50_dmaobj_sclass;
priv->base.bind = nv50_dmaobj_bind;
return 0;
}
struct nouveau_oclass
nv50_dmaeng_oclass = {
.handle = NV_ENGINE(DMAOBJ, 0x50),
.ofuncs = &(struct nouveau_ofuncs) {
.ctor = nv50_dmaeng_ctor,
.dtor = _nouveau_dmaeng_dtor,
.init = _nouveau_dmaeng_init,
.fini = _nouveau_dmaeng_fini,
},
};
|
54151.c | // Implementation of Shell Sort algorithm in C
// Harris Ransom
/** Includes **/
#include <stdio.h>
/** Functions **/
// Shell sort implementation
void shellSort(int arr[], int len) {
int temp;
// Traverse gaps large to small
for (int gap = len / 2; gap > 0; gap /= 2) {
// Insertion sort for non-sorted elements
for (int i = gap; i < len; i++) {
temp = arr[i]; // Grabs element to be sorted
// Shift elements until correct location found
int j;
for (j = i; j >= gap && arr[j - gap] > temp; j-= gap)
arr[j] = arr[j - gap];
arr[j] = temp; // Insert element at correct position
}
}
}
// Prints given array
void printArr(int arr[], int len) {
for (int i = 0; i < len; i++) {
if (i <= 9) {
printf("\tIndex %d - %d\n", i, arr[i]);
}
else {
printf("\tIndex %d - %d\n", i, arr[i]);
}
}
}
/** MAIN **/
int main() {
int nums[] = {7, 4, 2, 6, 10, 3, 5, 9, 1, 8};
int len = sizeof(nums) / sizeof(int);
printf("Initial array: \n");
printArr(nums, len);
shellSort(nums, len);
printf("Sorted array: \n");
printArr(nums, len);
}
|
523121.c | /*
+----------------------------------------------------------------------+
| PHP Version 7 |
+----------------------------------------------------------------------+
| Copyright (c) 1997-2018 The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| http://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| [email protected] so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Authors: Anthony Ferrara <[email protected]> |
| Charles R. Portwood II <[email protected]> |
+----------------------------------------------------------------------+
*/
/* $Id$ */
#include <stdlib.h>
#include "php.h"
#include "fcntl.h"
#include "php_password.h"
#include "php_rand.h"
#include "php_crypt.h"
#include "base64.h"
#include "zend_interfaces.h"
#include "info.h"
#include "php_random.h"
#if HAVE_ARGON2LIB
#include "argon2.h"
#endif
#ifdef PHP_WIN32
#include "win32/winutil.h"
#endif
PHP_MINIT_FUNCTION(password) /* {{{ */
{
REGISTER_LONG_CONSTANT("PASSWORD_DEFAULT", PHP_PASSWORD_DEFAULT, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("PASSWORD_BCRYPT", PHP_PASSWORD_BCRYPT, CONST_CS | CONST_PERSISTENT);
#if HAVE_ARGON2LIB
REGISTER_LONG_CONSTANT("PASSWORD_ARGON2I", PHP_PASSWORD_ARGON2I, CONST_CS | CONST_PERSISTENT);
#endif
REGISTER_LONG_CONSTANT("PASSWORD_BCRYPT_DEFAULT_COST", PHP_PASSWORD_BCRYPT_COST, CONST_CS | CONST_PERSISTENT);
#if HAVE_ARGON2LIB
REGISTER_LONG_CONSTANT("PASSWORD_ARGON2_DEFAULT_MEMORY_COST", PHP_PASSWORD_ARGON2_MEMORY_COST, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("PASSWORD_ARGON2_DEFAULT_TIME_COST", PHP_PASSWORD_ARGON2_TIME_COST, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("PASSWORD_ARGON2_DEFAULT_THREADS", PHP_PASSWORD_ARGON2_THREADS, CONST_CS | CONST_PERSISTENT);
#endif
return SUCCESS;
}
/* }}} */
static zend_string* php_password_get_algo_name(const php_password_algo algo)
{
switch (algo) {
case PHP_PASSWORD_BCRYPT:
return zend_string_init("bcrypt", sizeof("bcrypt") - 1, 0);
#if HAVE_ARGON2LIB
case PHP_PASSWORD_ARGON2I:
return zend_string_init("argon2i", sizeof("argon2i") - 1, 0);
#endif
case PHP_PASSWORD_UNKNOWN:
default:
return zend_string_init("unknown", sizeof("unknown") - 1, 0);
}
}
static php_password_algo php_password_determine_algo(const zend_string *hash)
{
const char *h = ZSTR_VAL(hash);
const size_t len = ZSTR_LEN(hash);
if (len == 60 && h[0] == '$' && h[1] == '2' && h[2] == 'y') {
return PHP_PASSWORD_BCRYPT;
}
#if HAVE_ARGON2LIB
if (len >= sizeof("$argon2i$")-1 && !memcmp(h, "$argon2i$", sizeof("$argon2i$")-1)) {
return PHP_PASSWORD_ARGON2I;
}
#endif
return PHP_PASSWORD_UNKNOWN;
}
static int php_password_salt_is_alphabet(const char *str, const size_t len) /* {{{ */
{
size_t i = 0;
for (i = 0; i < len; i++) {
if (!((str[i] >= 'A' && str[i] <= 'Z') || (str[i] >= 'a' && str[i] <= 'z') || (str[i] >= '0' && str[i] <= '9') || str[i] == '.' || str[i] == '/')) {
return FAILURE;
}
}
return SUCCESS;
}
/* }}} */
static int php_password_salt_to64(const char *str, const size_t str_len, const size_t out_len, char *ret) /* {{{ */
{
size_t pos = 0;
zend_string *buffer;
if ((int) str_len < 0) {
return FAILURE;
}
buffer = php_base64_encode((unsigned char*) str, str_len);
if (ZSTR_LEN(buffer) < out_len) {
/* Too short of an encoded string generated */
zend_string_release_ex(buffer, 0);
return FAILURE;
}
for (pos = 0; pos < out_len; pos++) {
if (ZSTR_VAL(buffer)[pos] == '+') {
ret[pos] = '.';
} else if (ZSTR_VAL(buffer)[pos] == '=') {
zend_string_free(buffer);
return FAILURE;
} else {
ret[pos] = ZSTR_VAL(buffer)[pos];
}
}
zend_string_free(buffer);
return SUCCESS;
}
/* }}} */
static zend_string* php_password_make_salt(size_t length) /* {{{ */
{
zend_string *ret, *buffer;
if (length > (INT_MAX / 3)) {
php_error_docref(NULL, E_WARNING, "Length is too large to safely generate");
return NULL;
}
buffer = zend_string_alloc(length * 3 / 4 + 1, 0);
if (FAILURE == php_random_bytes_silent(ZSTR_VAL(buffer), ZSTR_LEN(buffer))) {
php_error_docref(NULL, E_WARNING, "Unable to generate salt");
zend_string_release_ex(buffer, 0);
return NULL;
}
ret = zend_string_alloc(length, 0);
if (php_password_salt_to64(ZSTR_VAL(buffer), ZSTR_LEN(buffer), length, ZSTR_VAL(ret)) == FAILURE) {
php_error_docref(NULL, E_WARNING, "Generated salt too short");
zend_string_release_ex(buffer, 0);
zend_string_release_ex(ret, 0);
return NULL;
}
zend_string_release_ex(buffer, 0);
ZSTR_VAL(ret)[length] = 0;
return ret;
}
/* }}} */
/* {{{ proto array password_get_info(string $hash)
Retrieves information about a given hash */
PHP_FUNCTION(password_get_info)
{
php_password_algo algo;
zend_string *hash, *algo_name;
zval options;
ZEND_PARSE_PARAMETERS_START(1, 1)
Z_PARAM_STR(hash)
ZEND_PARSE_PARAMETERS_END();
array_init(&options);
algo = php_password_determine_algo(hash);
algo_name = php_password_get_algo_name(algo);
switch (algo) {
case PHP_PASSWORD_BCRYPT:
{
zend_long cost = PHP_PASSWORD_BCRYPT_COST;
sscanf(ZSTR_VAL(hash), "$2y$" ZEND_LONG_FMT "$", &cost);
add_assoc_long(&options, "cost", cost);
}
break;
#if HAVE_ARGON2LIB
case PHP_PASSWORD_ARGON2I:
{
zend_long v = 0;
zend_long memory_cost = PHP_PASSWORD_ARGON2_MEMORY_COST;
zend_long time_cost = PHP_PASSWORD_ARGON2_TIME_COST;
zend_long threads = PHP_PASSWORD_ARGON2_THREADS;
sscanf(ZSTR_VAL(hash), "$%*[argon2i]$v=" ZEND_LONG_FMT "$m=" ZEND_LONG_FMT ",t=" ZEND_LONG_FMT ",p=" ZEND_LONG_FMT, &v, &memory_cost, &time_cost, &threads);
add_assoc_long(&options, "memory_cost", memory_cost);
add_assoc_long(&options, "time_cost", time_cost);
add_assoc_long(&options, "threads", threads);
}
break;
#endif
case PHP_PASSWORD_UNKNOWN:
default:
break;
}
array_init(return_value);
add_assoc_long(return_value, "algo", algo);
add_assoc_str(return_value, "algoName", algo_name);
add_assoc_zval(return_value, "options", &options);
}
/** }}} */
/* {{{ proto bool password_needs_rehash(string $hash, int $algo[, array $options])
Determines if a given hash requires re-hashing based upon parameters */
PHP_FUNCTION(password_needs_rehash)
{
zend_long new_algo = 0;
php_password_algo algo;
zend_string *hash;
HashTable *options = 0;
zval *option_buffer;
ZEND_PARSE_PARAMETERS_START(2, 3)
Z_PARAM_STR(hash)
Z_PARAM_LONG(new_algo)
Z_PARAM_OPTIONAL
Z_PARAM_ARRAY_OR_OBJECT_HT(options)
ZEND_PARSE_PARAMETERS_END();
algo = php_password_determine_algo(hash);
if ((zend_long)algo != new_algo) {
RETURN_TRUE;
}
switch (algo) {
case PHP_PASSWORD_BCRYPT:
{
zend_long new_cost = PHP_PASSWORD_BCRYPT_COST, cost = 0;
if (options && (option_buffer = zend_hash_str_find(options, "cost", sizeof("cost")-1)) != NULL) {
new_cost = zval_get_long(option_buffer);
}
sscanf(ZSTR_VAL(hash), "$2y$" ZEND_LONG_FMT "$", &cost);
if (cost != new_cost) {
RETURN_TRUE;
}
}
break;
#if HAVE_ARGON2LIB
case PHP_PASSWORD_ARGON2I:
{
zend_long v = 0;
zend_long new_memory_cost = PHP_PASSWORD_ARGON2_MEMORY_COST, memory_cost = 0;
zend_long new_time_cost = PHP_PASSWORD_ARGON2_TIME_COST, time_cost = 0;
zend_long new_threads = PHP_PASSWORD_ARGON2_THREADS, threads = 0;
if (options && (option_buffer = zend_hash_str_find(options, "memory_cost", sizeof("memory_cost")-1)) != NULL) {
new_memory_cost = zval_get_long(option_buffer);
}
if (options && (option_buffer = zend_hash_str_find(options, "time_cost", sizeof("time_cost")-1)) != NULL) {
new_time_cost = zval_get_long(option_buffer);
}
if (options && (option_buffer = zend_hash_str_find(options, "threads", sizeof("threads")-1)) != NULL) {
new_threads = zval_get_long(option_buffer);
}
sscanf(ZSTR_VAL(hash), "$%*[argon2i]$v=" ZEND_LONG_FMT "$m=" ZEND_LONG_FMT ",t=" ZEND_LONG_FMT ",p=" ZEND_LONG_FMT, &v, &memory_cost, &time_cost, &threads);
if (new_time_cost != time_cost || new_memory_cost != memory_cost || new_threads != threads) {
RETURN_TRUE;
}
}
break;
#endif
case PHP_PASSWORD_UNKNOWN:
default:
break;
}
RETURN_FALSE;
}
/* }}} */
/* {{{ proto bool password_verify(string password, string hash)
Verify a hash created using crypt() or password_hash() */
PHP_FUNCTION(password_verify)
{
zend_string *password, *hash;
php_password_algo algo;
ZEND_PARSE_PARAMETERS_START(2, 2)
Z_PARAM_STR(password)
Z_PARAM_STR(hash)
ZEND_PARSE_PARAMETERS_END_EX(RETURN_FALSE);
algo = php_password_determine_algo(hash);
switch(algo) {
#if HAVE_ARGON2LIB
case PHP_PASSWORD_ARGON2I:
RETURN_BOOL(ARGON2_OK == argon2_verify(ZSTR_VAL(hash), ZSTR_VAL(password), ZSTR_LEN(password), Argon2_i));
break;
#endif
case PHP_PASSWORD_BCRYPT:
case PHP_PASSWORD_UNKNOWN:
default:
{
size_t i;
int status = 0;
zend_string *ret = php_crypt(ZSTR_VAL(password), (int)ZSTR_LEN(password), ZSTR_VAL(hash), (int)ZSTR_LEN(hash), 1);
if (!ret) {
RETURN_FALSE;
}
if (ZSTR_LEN(ret) != ZSTR_LEN(hash) || ZSTR_LEN(hash) < 13) {
zend_string_free(ret);
RETURN_FALSE;
}
/* We're using this method instead of == in order to provide
* resistance towards timing attacks. This is a constant time
* equality check that will always check every byte of both
* values. */
for (i = 0; i < ZSTR_LEN(hash); i++) {
status |= (ZSTR_VAL(ret)[i] ^ ZSTR_VAL(hash)[i]);
}
zend_string_free(ret);
RETURN_BOOL(status == 0);
}
}
RETURN_FALSE;
}
/* }}} */
static zend_string* php_password_get_salt(zval *return_value, size_t required_salt_len, HashTable *options) {
zend_string *buffer;
zval *option_buffer;
if (!options || !(option_buffer = zend_hash_str_find(options, "salt", sizeof("salt") - 1))) {
buffer = php_password_make_salt(required_salt_len);
if (!buffer) {
RETVAL_FALSE;
}
return buffer;
}
php_error_docref(NULL, E_DEPRECATED, "Use of the 'salt' option to password_hash is deprecated");
switch (Z_TYPE_P(option_buffer)) {
case IS_STRING:
buffer = zend_string_copy(Z_STR_P(option_buffer));
break;
case IS_LONG:
case IS_DOUBLE:
case IS_OBJECT:
buffer = zval_get_string(option_buffer);
break;
case IS_FALSE:
case IS_TRUE:
case IS_NULL:
case IS_RESOURCE:
case IS_ARRAY:
default:
php_error_docref(NULL, E_WARNING, "Non-string salt parameter supplied");
return NULL;
}
/* XXX all the crypt related APIs work with int for string length.
That should be revised for size_t and then we maybe don't require
the > INT_MAX check. */
if (ZEND_SIZE_T_INT_OVFL(ZSTR_LEN(buffer))) {
php_error_docref(NULL, E_WARNING, "Supplied salt is too long");
zend_string_release_ex(buffer, 0);
return NULL;
}
if (ZSTR_LEN(buffer) < required_salt_len) {
php_error_docref(NULL, E_WARNING, "Provided salt is too short: %zd expecting %zd", ZSTR_LEN(buffer), required_salt_len);
zend_string_release_ex(buffer, 0);
return NULL;
}
if (php_password_salt_is_alphabet(ZSTR_VAL(buffer), ZSTR_LEN(buffer)) == FAILURE) {
zend_string *salt = zend_string_alloc(required_salt_len, 0);
if (php_password_salt_to64(ZSTR_VAL(buffer), ZSTR_LEN(buffer), required_salt_len, ZSTR_VAL(salt)) == FAILURE) {
php_error_docref(NULL, E_WARNING, "Provided salt is too short: %zd", ZSTR_LEN(buffer));
zend_string_release_ex(salt, 0);
zend_string_release_ex(buffer, 0);
return NULL;
}
zend_string_release_ex(buffer, 0);
return salt;
} else {
zend_string *salt = zend_string_alloc(required_salt_len, 0);
memcpy(ZSTR_VAL(salt), ZSTR_VAL(buffer), required_salt_len);
zend_string_release_ex(buffer, 0);
return salt;
}
}
/* {{{ proto string password_hash(string password, int algo[, array options = array()])
Hash a password */
PHP_FUNCTION(password_hash)
{
zend_string *password;
zend_long algo = PHP_PASSWORD_DEFAULT;
HashTable *options = NULL;
ZEND_PARSE_PARAMETERS_START(2, 3)
Z_PARAM_STR(password)
Z_PARAM_LONG(algo)
Z_PARAM_OPTIONAL
Z_PARAM_ARRAY_OR_OBJECT_HT(options)
ZEND_PARSE_PARAMETERS_END();
switch (algo) {
case PHP_PASSWORD_BCRYPT:
{
char hash_format[10];
size_t hash_format_len;
zend_string *result, *hash, *salt;
zval *option_buffer;
zend_long cost = PHP_PASSWORD_BCRYPT_COST;
if (options && (option_buffer = zend_hash_str_find(options, "cost", sizeof("cost")-1)) != NULL) {
cost = zval_get_long(option_buffer);
}
if (cost < 4 || cost > 31) {
php_error_docref(NULL, E_WARNING, "Invalid bcrypt cost parameter specified: " ZEND_LONG_FMT, cost);
RETURN_NULL();
}
hash_format_len = snprintf(hash_format, sizeof(hash_format), "$2y$%02" ZEND_LONG_FMT_SPEC "$", cost);
if (!(salt = php_password_get_salt(return_value, Z_UL(22), options))) {
return;
}
ZSTR_VAL(salt)[ZSTR_LEN(salt)] = 0;
hash = zend_string_alloc(ZSTR_LEN(salt) + hash_format_len, 0);
sprintf(ZSTR_VAL(hash), "%s%s", hash_format, ZSTR_VAL(salt));
ZSTR_VAL(hash)[hash_format_len + ZSTR_LEN(salt)] = 0;
zend_string_release_ex(salt, 0);
/* This cast is safe, since both values are defined here in code and cannot overflow */
result = php_crypt(ZSTR_VAL(password), (int)ZSTR_LEN(password), ZSTR_VAL(hash), (int)ZSTR_LEN(hash), 1);
zend_string_release_ex(hash, 0);
if (!result) {
RETURN_FALSE;
}
if (ZSTR_LEN(result) < 13) {
zend_string_free(result);
RETURN_FALSE;
}
RETURN_STR(result);
}
break;
#if HAVE_ARGON2LIB
case PHP_PASSWORD_ARGON2I:
{
zval *option_buffer;
zend_string *salt, *out, *encoded;
size_t time_cost = PHP_PASSWORD_ARGON2_TIME_COST;
size_t memory_cost = PHP_PASSWORD_ARGON2_MEMORY_COST;
size_t threads = PHP_PASSWORD_ARGON2_THREADS;
argon2_type type = Argon2_i;
size_t encoded_len;
int status = 0;
if (options && (option_buffer = zend_hash_str_find(options, "memory_cost", sizeof("memory_cost")-1)) != NULL) {
memory_cost = zval_get_long(option_buffer);
}
if (memory_cost > ARGON2_MAX_MEMORY || memory_cost < ARGON2_MIN_MEMORY) {
php_error_docref(NULL, E_WARNING, "Memory cost is outside of allowed memory range", memory_cost);
RETURN_NULL();
}
if (options && (option_buffer = zend_hash_str_find(options, "time_cost", sizeof("time_cost")-1)) != NULL) {
time_cost = zval_get_long(option_buffer);
}
if (time_cost > ARGON2_MAX_TIME || time_cost < ARGON2_MIN_TIME) {
php_error_docref(NULL, E_WARNING, "Time cost is outside of allowed time range", time_cost);
RETURN_NULL();
}
if (options && (option_buffer = zend_hash_str_find(options, "threads", sizeof("threads")-1)) != NULL) {
threads = zval_get_long(option_buffer);
}
if (threads > ARGON2_MAX_LANES || threads == 0) {
php_error_docref(NULL, E_WARNING, "Invalid number of threads", threads);
RETURN_NULL();
}
if (!(salt = php_password_get_salt(return_value, Z_UL(16), options))) {
return;
}
out = zend_string_alloc(32, 0);
encoded_len = argon2_encodedlen(
time_cost,
memory_cost,
threads,
(uint32_t)ZSTR_LEN(salt),
ZSTR_LEN(out)
#if HAVE_ARGON2ID
, type
#endif
);
encoded = zend_string_alloc(encoded_len - 1, 0);
status = argon2_hash(
time_cost,
memory_cost,
threads,
ZSTR_VAL(password),
ZSTR_LEN(password),
ZSTR_VAL(salt),
ZSTR_LEN(salt),
ZSTR_VAL(out),
ZSTR_LEN(out),
ZSTR_VAL(encoded),
encoded_len,
type,
ARGON2_VERSION_NUMBER
);
zend_string_release_ex(out, 0);
zend_string_release_ex(salt, 0);
if (status != ARGON2_OK) {
zend_string_efree(encoded);
php_error_docref(NULL, E_WARNING, "%s", argon2_error_message(status));
RETURN_FALSE;
}
ZSTR_VAL(encoded)[ZSTR_LEN(encoded)] = 0;
RETURN_NEW_STR(encoded);
}
break;
#endif
case PHP_PASSWORD_UNKNOWN:
default:
php_error_docref(NULL, E_WARNING, "Unknown password hashing algorithm: " ZEND_LONG_FMT, algo);
RETURN_NULL();
}
}
/* }}} */
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* End:
* vim600: sw=4 ts=4 fdm=marker
* vim<600: sw=4 ts=4
*/
|
653684.c |
#ifdef HAVE_CONFIG_H
#include "../../../../ext_config.h"
#endif
#include <php.h>
#include "../../../../php_ext.h"
#include "../../../../ext.h"
#include <Zend/zend_operators.h>
#include <Zend/zend_exceptions.h>
#include <Zend/zend_interfaces.h>
#include "kernel/main.h"
/*
This file is part of the php-ext-zendframework package.
For the full copyright and license information, please view the LICENSE
file that was distributed with this source code.
*/
ZEPHIR_INIT_CLASS(ZendFramework_Code_Reflection_Exception_RuntimeException) {
ZEPHIR_REGISTER_CLASS_EX(Zend\\Code\\Reflection\\Exception, RuntimeException, zendframework, code_reflection_exception_runtimeexception, zendframework_code_exception_runtimeexception_ce, NULL, 0);
zend_class_implements(zendframework_code_reflection_exception_runtimeexception_ce TSRMLS_CC, 1, zendframework_code_reflection_exception_exceptioninterface_ce);
return SUCCESS;
}
|
967660.c | /*
Copyright (C) 1999 Aladdin Enterprises. All rights reserved.
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
L. Peter Deutsch
[email protected]
*/
/*$Id: md5.c,v 1.1 2003/10/10 11:37:57 prokushev Exp $ */
/*
Independent implementation of MD5 (RFC 1321).
This code implements the MD5 Algorithm defined in RFC 1321.
It is derived directly from the text of the RFC and not from the
reference implementation.
The original and principal author of md5.c is L. Peter Deutsch
<[email protected]>. Other authors are noted in the change history
that follows (in reverse chronological order):
*** ALTERED 2003: make it compile in 16bit Turbo C ***
1999-11-04 lpd Edited comments slightly for automatic TOC extraction.
1999-10-18 lpd Fixed typo in header comment (ansi2knr rather than md5).
1999-05-03 lpd Original version.
*/
#include "md5.h"
#include <mem.h> /* ALTERED */
#ifdef TEST
/*
* Compile with -DTEST to create a self-contained executable test program.
* The test program should print out the same values as given in section
* A.5 of RFC 1321, reproduced below.
*/
#include <string.h>
main()
{
static const char *const test[8] = {
"", /*d41d8cd98f00b204e9800998ecf8427e*/
" ",
"a", /*0cc175b9c0f1b6a831c399e269772661*/
"abc", /*900150983cd24fb0d6963f7d28e17f72*/
"message digest", /*f96b697d7cb7938d525a2f31aaf161d0*/
"abcdefghijklmnopqrstuvwxyz", /*c3fcd3d76192e4007dfb496cca67e13b*/
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",
/*d174ab98d277d9f5a5611c2c9f419d9f*/
"12345678901234567890123456789012345678901234567890123456789012345678901234567890" /*57edf4a22be3c955ac49da2e2107b67a*/
};
int i;
for (i = 0; i < 7; ++i) {
md5_state_t state;
md5_byte_t digest[16];
int di;
md5_init(&state);
md5_append(&state, (const md5_byte_t *)test[i], strlen(test[i]));
md5_finish(&state, digest);
printf("MD5 (\"%s\") = ", test[i]);
for (di = 0; di < 16; ++di)
printf("%02x", digest[di]);
printf("\n");
}
return 0;
}
#endif /* TEST */
/*
* For reference, here is the program that computed the T values.
*/
#if 0
#include <math.h>
main()
{
int i;
for (i = 1; i <= 64; ++i) {
unsigned long v = (unsigned long)(4294967296.0 * fabs(sin((double)i)));
printf("#define T%d 0x%08lx\n", i, v);
}
return 0;
}
#endif
/*
* End of T computation program.
*/
#define T1 0xd76aa478L
#define T2 0xe8c7b756L
#define T3 0x242070dbL
#define T4 0xc1bdceeeL
#define T5 0xf57c0fafL
#define T6 0x4787c62aL
#define T7 0xa8304613L
#define T8 0xfd469501L
#define T9 0x698098d8L
#define T10 0x8b44f7afL
#define T11 0xffff5bb1L
#define T12 0x895cd7beL
#define T13 0x6b901122L
#define T14 0xfd987193L
#define T15 0xa679438eL
#define T16 0x49b40821L
#define T17 0xf61e2562L
#define T18 0xc040b340L
#define T19 0x265e5a51L
#define T20 0xe9b6c7aaL
#define T21 0xd62f105dL
#define T22 0x02441453L
#define T23 0xd8a1e681L
#define T24 0xe7d3fbc8L
#define T25 0x21e1cde6L
#define T26 0xc33707d6L
#define T27 0xf4d50d87L
#define T28 0x455a14edL
#define T29 0xa9e3e905L
#define T30 0xfcefa3f8L
#define T31 0x676f02d9L
#define T32 0x8d2a4c8aL
#define T33 0xfffa3942L
#define T34 0x8771f681L
#define T35 0x6d9d6122L
#define T36 0xfde5380cL
#define T37 0xa4beea44L
#define T38 0x4bdecfa9L
#define T39 0xf6bb4b60L
#define T40 0xbebfbc70L
#define T41 0x289b7ec6L
#define T42 0xeaa127faL
#define T43 0xd4ef3085L
#define T44 0x04881d05L
#define T45 0xd9d4d039L
#define T46 0xe6db99e5L
#define T47 0x1fa27cf8L
#define T48 0xc4ac5665L
#define T49 0xf4292244L
#define T50 0x432aff97L
#define T51 0xab9423a7L
#define T52 0xfc93a039L
#define T53 0x655b59c3L
#define T54 0x8f0ccc92L
#define T55 0xffeff47dL
#define T56 0x85845dd1L
#define T57 0x6fa87e4fL
#define T58 0xfe2ce6e0L
#define T59 0xa3014314L
#define T60 0x4e0811a1L
#define T61 0xf7537e82L
#define T62 0xbd3af235L
#define T63 0x2ad7d2bbL
#define T64 0xeb86d391L
static void
md5_process(md5_state_t *pms, const md5_byte_t *data /*[64]*/)
{
md5_word_t
a = pms->abcd[0], b = pms->abcd[1],
c = pms->abcd[2], d = pms->abcd[3];
md5_word_t t;
#ifndef ARCH_IS_BIG_ENDIAN
# define ARCH_IS_BIG_ENDIAN 1 /* slower, default implementation */
#endif
#if ARCH_IS_BIG_ENDIAN
/*
* On big-endian machines, we must arrange the bytes in the right
* order. (This also works on machines of unknown byte order.)
*/
md5_word_t X[16];
const md5_byte_t *xp = data;
int i;
for (i = 0; i < 16; ++i, xp += 4)
X[i] = xp[0] + (xp[1] << 8) + (xp[2] << 16) + (xp[3] << 24);
#else /* !ARCH_IS_BIG_ENDIAN */
/*
* On little-endian machines, we can process properly aligned data
* without copying it.
*/
md5_word_t xbuf[16];
const md5_word_t *X;
if (!((data - (const md5_byte_t *)0) & 3)) {
/* data are properly aligned */
X = (const md5_word_t *)data;
} else {
/* not aligned */
memcpy(xbuf, data, 64);
X = xbuf;
}
#endif
#define ROTATE_LEFT(x, n) (((x) << (n)) | ((x) >> (32 - (n))))
/* Round 1. */
/* Let [abcd k s i] denote the operation
a = b + ((a + F(b,c,d) + X[k] + T[i]) <<< s). */
#define F(x, y, z) (((x) & (y)) | (~(x) & (z)))
#define SET(a, b, c, d, k, s, Ti)\
t = a + F(b,c,d) + X[k] + Ti;\
a = ROTATE_LEFT(t, s) + b
/* Do the following 16 operations. */
SET(a, b, c, d, 0, 7, T1);
SET(d, a, b, c, 1, 12, T2);
SET(c, d, a, b, 2, 17, T3);
SET(b, c, d, a, 3, 22, T4);
SET(a, b, c, d, 4, 7, T5);
SET(d, a, b, c, 5, 12, T6);
SET(c, d, a, b, 6, 17, T7);
SET(b, c, d, a, 7, 22, T8);
SET(a, b, c, d, 8, 7, T9);
SET(d, a, b, c, 9, 12, T10);
SET(c, d, a, b, 10, 17, T11);
SET(b, c, d, a, 11, 22, T12);
SET(a, b, c, d, 12, 7, T13);
SET(d, a, b, c, 13, 12, T14);
SET(c, d, a, b, 14, 17, T15);
SET(b, c, d, a, 15, 22, T16);
#undef SET
/* Round 2. */
/* Let [abcd k s i] denote the operation
a = b + ((a + G(b,c,d) + X[k] + T[i]) <<< s). */
#define G(x, y, z) (((x) & (z)) | ((y) & ~(z)))
#define SET(a, b, c, d, k, s, Ti)\
t = a + G(b,c,d) + X[k] + Ti;\
a = ROTATE_LEFT(t, s) + b
/* Do the following 16 operations. */
SET(a, b, c, d, 1, 5, T17);
SET(d, a, b, c, 6, 9, T18);
SET(c, d, a, b, 11, 14, T19);
SET(b, c, d, a, 0, 20, T20);
SET(a, b, c, d, 5, 5, T21);
SET(d, a, b, c, 10, 9, T22);
SET(c, d, a, b, 15, 14, T23);
SET(b, c, d, a, 4, 20, T24);
SET(a, b, c, d, 9, 5, T25);
SET(d, a, b, c, 14, 9, T26);
SET(c, d, a, b, 3, 14, T27);
SET(b, c, d, a, 8, 20, T28);
SET(a, b, c, d, 13, 5, T29);
SET(d, a, b, c, 2, 9, T30);
SET(c, d, a, b, 7, 14, T31);
SET(b, c, d, a, 12, 20, T32);
#undef SET
/* Round 3. */
/* Let [abcd k s t] denote the operation
a = b + ((a + H(b,c,d) + X[k] + T[i]) <<< s). */
#define H(x, y, z) ((x) ^ (y) ^ (z))
#define SET(a, b, c, d, k, s, Ti)\
t = a + H(b,c,d) + X[k] + Ti;\
a = ROTATE_LEFT(t, s) + b
/* Do the following 16 operations. */
SET(a, b, c, d, 5, 4, T33);
SET(d, a, b, c, 8, 11, T34);
SET(c, d, a, b, 11, 16, T35);
SET(b, c, d, a, 14, 23, T36);
SET(a, b, c, d, 1, 4, T37);
SET(d, a, b, c, 4, 11, T38);
SET(c, d, a, b, 7, 16, T39);
SET(b, c, d, a, 10, 23, T40);
SET(a, b, c, d, 13, 4, T41);
SET(d, a, b, c, 0, 11, T42);
SET(c, d, a, b, 3, 16, T43);
SET(b, c, d, a, 6, 23, T44);
SET(a, b, c, d, 9, 4, T45);
SET(d, a, b, c, 12, 11, T46);
SET(c, d, a, b, 15, 16, T47);
SET(b, c, d, a, 2, 23, T48);
#undef SET
/* Round 4. */
/* Let [abcd k s t] denote the operation
a = b + ((a + I(b,c,d) + X[k] + T[i]) <<< s). */
#define I(x, y, z) ((y) ^ ((x) | ~(z)))
#define SET(a, b, c, d, k, s, Ti)\
t = a + I(b,c,d) + X[k] + Ti;\
a = ROTATE_LEFT(t, s) + b
/* Do the following 16 operations. */
SET(a, b, c, d, 0, 6, T49);
SET(d, a, b, c, 7, 10, T50);
SET(c, d, a, b, 14, 15, T51);
SET(b, c, d, a, 5, 21, T52);
SET(a, b, c, d, 12, 6, T53);
SET(d, a, b, c, 3, 10, T54);
SET(c, d, a, b, 10, 15, T55);
SET(b, c, d, a, 1, 21, T56);
SET(a, b, c, d, 8, 6, T57);
SET(d, a, b, c, 15, 10, T58);
SET(c, d, a, b, 6, 15, T59);
SET(b, c, d, a, 13, 21, T60);
SET(a, b, c, d, 4, 6, T61);
SET(d, a, b, c, 11, 10, T62);
SET(c, d, a, b, 2, 15, T63);
SET(b, c, d, a, 9, 21, T64);
#undef SET
/* Then perform the following additions. (That is increment each
of the four registers by the value it had before this block
was started.) */
pms->abcd[0] += a;
pms->abcd[1] += b;
pms->abcd[2] += c;
pms->abcd[3] += d;
}
void
md5_init(md5_state_t *pms)
{
pms->count[0] = pms->count[1] = 0;
pms->abcd[0] = 0x67452301L;
pms->abcd[1] = 0xefcdab89L;
pms->abcd[2] = 0x98badcfeL;
pms->abcd[3] = 0x10325476L;
}
void
md5_append(md5_state_t *pms, const md5_byte_t *data, int nbytes)
{
const md5_byte_t *p = data;
int left = nbytes;
int offset = (int) ( (pms->count[0] >> 3) & 63 );
/* ALTERED: typecast to int */
md5_word_t nbits = (md5_word_t)(nbytes << 3);
if (nbytes <= 0)
return;
/* Update the message length. */
pms->count[1] += nbytes >> 29;
pms->count[0] += nbits;
if (pms->count[0] < nbits)
pms->count[1]++;
/* Process an initial partial block. */
if (offset) {
int copy = (offset + nbytes > 64 ? 64 - offset : nbytes);
memcpy(pms->buf + offset, p, copy);
if (offset + copy < 64)
return;
p += copy;
left -= copy;
md5_process(pms, pms->buf);
}
/* Process full blocks. */
for (; left >= 64; p += 64, left -= 64)
md5_process(pms, p);
/* Process a final partial block. */
if (left)
memcpy(pms->buf, p, left);
}
void
md5_finish(md5_state_t *pms, md5_byte_t digest[16])
{
static const md5_byte_t pad[64] = {
0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
};
md5_byte_t data[8];
int i;
/* Save the length before padding. */
for (i = 0; i < 8; ++i)
data[i] = (md5_byte_t)(pms->count[i >> 2] >> ((i & 3) << 3));
/* Pad to 56 bytes mod 64. */
md5_append(pms, pad, (int) ( ((55 - (pms->count[0] >> 3)) & 63) + 1 ));
/* ALTERED: typecast to int */
/* Append the length. */
md5_append(pms, data, 8);
for (i = 0; i < 16; ++i)
digest[i] = (md5_byte_t)(pms->abcd[i >> 2] >> ((i & 3) << 3));
}
|
940126.c |
/*============================================================================
This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic
Package, Release 3b, by John R. Hauser.
Copyright 2011, 2012, 2013, 2014 The Regents of the University of California.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions, and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions, and the following disclaimer in the documentation
and/or other materials provided with the distribution.
3. Neither the name of the University nor the names of its contributors may
be used to endorse or promote products derived from this software without
specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE
DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
=============================================================================*/
#include <stdbool.h>
#include <stdint.h>
#include "platform.h"
#include "internals.h"
#include "specialize.h"
#include "softfloat.h"
extFloat80_t extF80_div( extFloat80_t a, extFloat80_t b )
{
union { struct extFloat80M s; extFloat80_t f; } uA;
uint_fast16_t uiA64;
uint_fast64_t uiA0;
bool signA;
int_fast32_t expA;
uint_fast64_t sigA;
union { struct extFloat80M s; extFloat80_t f; } uB;
uint_fast16_t uiB64;
uint_fast64_t uiB0;
bool signB;
int_fast32_t expB;
uint_fast64_t sigB;
bool signZ;
struct exp32_sig64 normExpSig;
int_fast32_t expZ;
struct uint128 rem;
uint_fast32_t recip32;
uint_fast64_t sigZ;
int ix;
uint_fast64_t q64;
uint_fast32_t q;
struct uint128 term;
uint_fast64_t sigZExtra;
struct uint128 uiZ;
uint_fast16_t uiZ64;
uint_fast64_t uiZ0;
union { struct extFloat80M s; extFloat80_t f; } uZ;
/*------------------------------------------------------------------------
*------------------------------------------------------------------------*/
uA.f = a;
uiA64 = uA.s.signExp;
uiA0 = uA.s.signif;
signA = signExtF80UI64( uiA64 );
expA = expExtF80UI64( uiA64 );
sigA = uiA0;
uB.f = b;
uiB64 = uB.s.signExp;
uiB0 = uB.s.signif;
signB = signExtF80UI64( uiB64 );
expB = expExtF80UI64( uiB64 );
sigB = uiB0;
signZ = signA ^ signB;
/*------------------------------------------------------------------------
*------------------------------------------------------------------------*/
if ( expA == 0x7FFF ) {
if ( sigA & UINT64_C( 0x7FFFFFFFFFFFFFFF ) ) goto propagateNaN;
if ( expB == 0x7FFF ) {
if ( sigB & UINT64_C( 0x7FFFFFFFFFFFFFFF ) ) goto propagateNaN;
goto invalid;
}
goto infinity;
}
if ( expB == 0x7FFF ) {
if ( sigB & UINT64_C( 0x7FFFFFFFFFFFFFFF ) ) goto propagateNaN;
goto zero;
}
/*------------------------------------------------------------------------
*------------------------------------------------------------------------*/
if ( ! expB ) expB = 1;
if ( ! (sigB & UINT64_C( 0x8000000000000000 )) ) {
if ( ! sigB ) {
if ( ! sigA ) goto invalid;
softfloat_raiseFlags( softfloat_flag_infinite );
goto infinity;
}
normExpSig = softfloat_normSubnormalExtF80Sig( sigB );
expB += normExpSig.exp;
sigB = normExpSig.sig;
}
if ( ! expA ) expA = 1;
if ( ! (sigA & UINT64_C( 0x8000000000000000 )) ) {
if ( ! sigA ) goto zero;
normExpSig = softfloat_normSubnormalExtF80Sig( sigA );
expA += normExpSig.exp;
sigA = normExpSig.sig;
}
/*------------------------------------------------------------------------
*------------------------------------------------------------------------*/
expZ = expA - expB + 0x3FFF;
if ( sigA < sigB ) {
--expZ;
rem = softfloat_shortShiftLeft128( 0, sigA, 32 );
} else {
rem = softfloat_shortShiftLeft128( 0, sigA, 31 );
}
recip32 = softfloat_approxRecip32_1( sigB>>32 );
sigZ = 0;
ix = 2;
for (;;) {
q64 = (uint_fast64_t) (uint32_t) (rem.v64>>2) * recip32;
q = (q64 + 0x80000000)>>32;
--ix;
if ( ix < 0 ) break;
rem = softfloat_shortShiftLeft128( rem.v64, rem.v0, 29 );
term = softfloat_mul64ByShifted32To128( sigB, q );
rem = softfloat_sub128( rem.v64, rem.v0, term.v64, term.v0 );
if ( rem.v64 & UINT64_C( 0x8000000000000000 ) ) {
--q;
rem = softfloat_add128( rem.v64, rem.v0, sigB>>32, sigB<<32 );
}
sigZ = (sigZ<<29) + q;
}
/*------------------------------------------------------------------------
*------------------------------------------------------------------------*/
if ( ((q + 1) & 0x3FFFFF) < 2 ) {
rem = softfloat_shortShiftLeft128( rem.v64, rem.v0, 29 );
term = softfloat_mul64ByShifted32To128( sigB, q );
rem = softfloat_sub128( rem.v64, rem.v0, term.v64, term.v0 );
term = softfloat_shortShiftLeft128( 0, sigB, 32 );
if ( rem.v64 & UINT64_C( 0x8000000000000000 ) ) {
--q;
rem = softfloat_add128( rem.v64, rem.v0, term.v64, term.v0 );
} else if ( softfloat_le128( term.v64, term.v0, rem.v64, rem.v0 ) ) {
++q;
rem = softfloat_sub128( rem.v64, rem.v0, term.v64, term.v0 );
}
if ( rem.v64 | rem.v0 ) q |= 1;
}
/*------------------------------------------------------------------------
*------------------------------------------------------------------------*/
sigZ = (sigZ<<6) + (q>>23);
sigZExtra = (uint64_t) ((uint_fast64_t) q<<41);
return
softfloat_roundPackToExtF80(
signZ, expZ, sigZ, sigZExtra, extF80_roundingPrecision );
/*------------------------------------------------------------------------
*------------------------------------------------------------------------*/
propagateNaN:
uiZ = softfloat_propagateNaNExtF80UI( uiA64, uiA0, uiB64, uiB0 );
uiZ64 = uiZ.v64;
uiZ0 = uiZ.v0;
goto uiZ;
/*------------------------------------------------------------------------
*------------------------------------------------------------------------*/
invalid:
softfloat_raiseFlags( softfloat_flag_invalid );
uiZ64 = defaultNaNExtF80UI64;
uiZ0 = defaultNaNExtF80UI0;
goto uiZ;
/*------------------------------------------------------------------------
*------------------------------------------------------------------------*/
infinity:
uiZ64 = packToExtF80UI64( signZ, 0x7FFF );
uiZ0 = UINT64_C( 0x8000000000000000 );
goto uiZ;
/*------------------------------------------------------------------------
*------------------------------------------------------------------------*/
zero:
uiZ64 = packToExtF80UI64( signZ, 0 );
uiZ0 = 0;
uiZ:
uZ.s.signExp = uiZ64;
uZ.s.signif = uiZ0;
return uZ.f;
}
|
434390.c | // This file is a part of Julia. License is MIT: https://julialang.org/license
// Note that this file is `#include`d by "signal-handling.c"
#include <signal.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/mman.h>
#include <pthread.h>
#include <errno.h>
#if defined(_OS_DARWIN_) && !defined(MAP_ANONYMOUS)
#define MAP_ANONYMOUS MAP_ANON
#endif
#ifdef __APPLE__
#include <AvailabilityMacros.h>
#ifdef MAC_OS_X_VERSION_10_9
#include <sys/_types/_ucontext64.h>
#else
#define __need_ucontext64_t
#include <machine/_structs.h>
#endif
#endif
// Figure out the best signals/timers to use for this platform
#ifdef __APPLE__ // Darwin's mach ports allow signal-free thread management
#define HAVE_MACH
#define HAVE_KEVENT
#elif defined(__FreeBSD__) // generic bsd
#define HAVE_ITIMER
#else // generic linux
#define HAVE_TIMER
#endif
#ifdef HAVE_KEVENT
#include <sys/event.h>
#endif
// 8M signal stack, same as default stack size and enough
// for reasonable finalizers.
// Should also be enough for parallel GC when we have it =)
#define sig_stack_size (8 * 1024 * 1024)
#include "julia_assert.h"
// helper function for returning the unw_context_t inside a ucontext_t
static bt_context_t *jl_to_bt_context(void *sigctx)
{
#ifdef __APPLE__
return (bt_context_t*)&((ucontext64_t*)sigctx)->uc_mcontext64->__ss;
#elif defined(_CPU_ARM_)
// libunwind does not use `ucontext_t` on ARM.
// `unw_context_t` is a struct of 16 `unsigned long` which should
// have the same layout as the `arm_r0` to `arm_pc` fields in `sigcontext`
ucontext_t *ctx = (ucontext_t*)sigctx;
return (bt_context_t*)&ctx->uc_mcontext.arm_r0;
#else
return (bt_context_t*)sigctx;
#endif
}
static int thread0_exit_count = 0;
static inline __attribute__((unused)) uintptr_t jl_get_rsp_from_ctx(const void *_ctx)
{
#if defined(_OS_LINUX_) && defined(_CPU_X86_64_)
const ucontext_t *ctx = (const ucontext_t*)_ctx;
return ctx->uc_mcontext.gregs[REG_RSP];
#elif defined(_OS_LINUX_) && defined(_CPU_X86_)
const ucontext_t *ctx = (const ucontext_t*)_ctx;
return ctx->uc_mcontext.gregs[REG_ESP];
#elif defined(_OS_LINUX_) && defined(_CPU_AARCH64_)
const ucontext_t *ctx = (const ucontext_t*)_ctx;
return ctx->uc_mcontext.sp;
#elif defined(_OS_LINUX_) && defined(_CPU_ARM_)
const ucontext_t *ctx = (const ucontext_t*)_ctx;
return ctx->uc_mcontext.arm_sp;
#elif defined(_OS_DARWIN_) && defined(_CPU_X86_64_)
const ucontext64_t *ctx = (const ucontext64_t*)_ctx;
return ctx->uc_mcontext64->__ss.__rsp;
#elif defined(_OS_DARWIN_) && defined(_CPU_AARCH64_)
const ucontext64_t *ctx = (const ucontext64_t*)_ctx;
return ctx->uc_mcontext64->__ss.__sp;
#else
// TODO Add support for FreeBSD and PowerPC(64)?
return 0;
#endif
}
// Modify signal context `_ctx` so that `fptr` will execute when the signal
// returns. `fptr` will execute on the signal stack, and must not return.
static void jl_call_in_ctx(jl_ptls_t ptls, void (*fptr)(void), int sig, void *_ctx)
{
// Modifying the ucontext should work but there is concern that
// sigreturn oriented programming mitigation can work against us
// by rejecting ucontext that is modified.
// The current (staged) implementation in the Linux Kernel only
// checks that the syscall is made in the signal handler and that
// the ucontext address is valid. Hopefully the value of the ucontext
// will not be part of the validation...
if (!ptls->signal_stack) {
sigset_t sset;
sigemptyset(&sset);
sigaddset(&sset, sig);
sigprocmask(SIG_UNBLOCK, &sset, NULL);
fptr();
return;
}
uintptr_t rsp = (uintptr_t)ptls->signal_stack + sig_stack_size;
assert(rsp % 16 == 0);
#if defined(_OS_LINUX_) && defined(_CPU_X86_64_)
ucontext_t *ctx = (ucontext_t*)_ctx;
rsp -= sizeof(void*);
*(void**)rsp = NULL;
ctx->uc_mcontext.gregs[REG_RSP] = rsp;
ctx->uc_mcontext.gregs[REG_RIP] = (uintptr_t)fptr;
#elif defined(_OS_FREEBSD_) && defined(_CPU_X86_64_)
ucontext_t *ctx = (ucontext_t*)_ctx;
rsp -= sizeof(void*);
*(void**)rsp = NULL;
ctx->uc_mcontext.mc_rsp = rsp;
ctx->uc_mcontext.mc_rip = (uintptr_t)fptr;
#elif defined(_OS_LINUX_) && defined(_CPU_X86_)
ucontext_t *ctx = (ucontext_t*)_ctx;
rsp -= sizeof(void*);
*(void**)rsp = NULL;
ctx->uc_mcontext.gregs[REG_ESP] = rsp;
ctx->uc_mcontext.gregs[REG_EIP] = (uintptr_t)fptr;
#elif defined(_OS_FREEBSD_) && defined(_CPU_X86_)
ucontext_t *ctx = (ucontext_t*)_ctx;
rsp -= sizeof(void*);
*(void**)rsp = NULL;
ctx->uc_mcontext.mc_esp = rsp;
ctx->uc_mcontext.mc_eip = (uintptr_t)fptr;
#elif defined(_OS_LINUX_) && defined(_CPU_AARCH64_)
ucontext_t *ctx = (ucontext_t*)_ctx;
ctx->uc_mcontext.sp = rsp;
ctx->uc_mcontext.regs[29] = 0; // Clear link register (x29)
ctx->uc_mcontext.pc = (uintptr_t)fptr;
#elif defined(_OS_LINUX_) && defined(_CPU_ARM_)
ucontext_t *ctx = (ucontext_t*)_ctx;
uintptr_t target = (uintptr_t)fptr;
// Apparently some glibc's sigreturn target is running in thumb state.
// Mimic a `bx` instruction by setting the T(5) bit of CPSR
// depending on the target address.
uintptr_t cpsr = ctx->uc_mcontext.arm_cpsr;
// Thumb mode function pointer should have the lowest bit set
if (target & 1) {
target = target & ~((uintptr_t)1);
cpsr = cpsr | (1 << 5);
}
else {
cpsr = cpsr & ~(1 << 5);
}
ctx->uc_mcontext.arm_cpsr = cpsr;
ctx->uc_mcontext.arm_sp = rsp;
ctx->uc_mcontext.arm_lr = 0; // Clear link register
ctx->uc_mcontext.arm_pc = target;
#elif defined(_OS_DARWIN_) && (defined(_CPU_X86_64_) || defined(_CPU_AARCH64_))
// Only used for SIGFPE.
// This doesn't seems to be reliable when the SIGFPE is generated
// from a divide-by-zero exception, which is now handled by
// `catch_exception_raise`. It works fine when a signal is received
// due to `kill`/`raise` though.
ucontext64_t *ctx = (ucontext64_t*)_ctx;
#if defined(_CPU_X86_64_)
rsp -= sizeof(void*);
*(void**)rsp = NULL;
ctx->uc_mcontext64->__ss.__rsp = rsp;
ctx->uc_mcontext64->__ss.__rip = (uintptr_t)fptr;
#else
ctx->uc_mcontext64->__ss.__sp = rsp;
ctx->uc_mcontext64->__ss.__pc = (uintptr_t)fptr;
ctx->uc_mcontext64->__ss.__lr = 0;
#endif
#else
#warning "julia: throw-in-context not supported on this platform"
// TODO Add support for PowerPC(64)?
sigset_t sset;
sigemptyset(&sset);
sigaddset(&sset, sig);
sigprocmask(SIG_UNBLOCK, &sset, NULL);
fptr();
#endif
}
static void jl_throw_in_ctx(jl_ptls_t ptls, jl_value_t *e, int sig, void *sigctx)
{
if (!ptls->safe_restore)
ptls->bt_size = rec_backtrace_ctx(ptls->bt_data, JL_MAX_BT_SIZE,
jl_to_bt_context(sigctx), ptls->pgcstack);
ptls->sig_exception = e;
jl_call_in_ctx(ptls, &jl_sig_throw, sig, sigctx);
}
static pthread_t signals_thread;
static int is_addr_on_stack(jl_ptls_t ptls, void *addr)
{
jl_task_t *t = ptls->current_task;
if (t->copy_stack)
return ((char*)addr > (char*)ptls->stackbase - ptls->stacksize &&
(char*)addr < (char*)ptls->stackbase);
else
return ((char*)addr > (char*)t->stkbuf &&
(char*)addr < (char*)t->stkbuf + t->bufsz);
}
static void sigdie_handler(int sig, siginfo_t *info, void *context)
{
jl_ptls_t ptls = jl_get_ptls_states();
sigset_t sset;
uv_tty_reset_mode();
if (sig == SIGILL)
jl_show_sigill(context);
jl_critical_error(sig, jl_to_bt_context(context),
ptls->bt_data, &ptls->bt_size);
sigfillset(&sset);
sigprocmask(SIG_UNBLOCK, &sset, NULL);
signal(sig, SIG_DFL);
if (sig != SIGSEGV &&
sig != SIGBUS &&
sig != SIGILL) {
raise(sig);
}
// fall-through return to re-execute faulting statement (but without the error handler)
}
#if defined(_CPU_X86_64_) || defined(_CPU_X86_)
enum x86_trap_flags {
USER_MODE = 0x4,
WRITE_FAULT = 0x2,
PAGE_PRESENT = 0x1
};
int exc_reg_is_write_fault(uintptr_t err) {
return err & WRITE_FAULT;
}
#elif defined(_CPU_AARCH64_)
enum aarch64_esr_layout {
EC_MASK = ((uint32_t)0b111111) << 26,
EC_DATA_ABORT = ((uint32_t)0b100100) << 26,
ISR_DA_WnR = ((uint32_t)1) << 6
};
int exc_reg_is_write_fault(uintptr_t esr) {
return (esr & EC_MASK) == EC_DATA_ABORT && (esr & ISR_DA_WnR);
}
#endif
#if defined(HAVE_MACH)
#include "signals-mach.c"
#else
#if defined(_OS_LINUX_) && (defined(_CPU_X86_64_) || defined(_CPU_X86_))
int is_write_fault(void *context) {
ucontext_t *ctx = (ucontext_t*)context;
return exc_reg_is_write_fault(ctx->uc_mcontext.gregs[REG_ERR]);
}
#elif defined(_OS_LINUX_) && defined(_CPU_AARCH64_)
struct linux_aarch64_ctx_header {
uint32_t magic;
uint32_t size;
};
const uint32_t linux_esr_magic = 0x45535201;
int is_write_fault(void *context) {
ucontext_t *ctx = (ucontext_t*)context;
struct linux_aarch64_ctx_header *extra =
(struct linux_aarch64_ctx_header *)ctx->uc_mcontext.__reserved;
while (extra->magic != 0) {
if (extra->magic == linux_esr_magic) {
return exc_reg_is_write_fault(*(uint64_t*)&extra[1]);
}
extra = (struct linux_aarch64_ctx_header *)
(((uint8_t*)extra) + extra->size);
}
return 0;
}
#elif defined(_OS_FREEBSD_) && (defined(_CPU_X86_64_) || defined(_CPU_X86_))
int is_write_fault(void *context) {
ucontext_t *ctx = (ucontext_t*)context;
return exc_reg_is_write_fault(ctx->uc_mcontext.mc_err);
}
#else
#warning Implement this query for consistent PROT_NONE handling
int is_write_fault(void *context) {
return 0;
}
#endif
static int is_addr_on_sigstack(jl_ptls_t ptls, void *ptr)
{
// One guard page for signal_stack.
return !((char*)ptr < (char*)ptls->signal_stack - jl_page_size ||
(char*)ptr > (char*)ptls->signal_stack + sig_stack_size);
}
static int jl_is_on_sigstack(jl_ptls_t ptls, void *ptr, void *context)
{
return (is_addr_on_sigstack(ptls, ptr) &&
is_addr_on_sigstack(ptls, (void*)jl_get_rsp_from_ctx(context)));
}
static void segv_handler(int sig, siginfo_t *info, void *context)
{
jl_ptls_t ptls = jl_get_ptls_states();
assert(sig == SIGSEGV || sig == SIGBUS);
if (jl_addr_is_safepoint((uintptr_t)info->si_addr)) {
jl_set_gc_and_wait();
// Do not raise sigint on worker thread
if (ptls->tid != 0)
return;
if (ptls->defer_signal) {
jl_safepoint_defer_sigint();
}
else if (jl_safepoint_consume_sigint()) {
jl_clear_force_sigint();
jl_throw_in_ctx(ptls, jl_interrupt_exception, sig, context);
}
return;
}
if (ptls->safe_restore || is_addr_on_stack(ptls, info->si_addr)) { // stack overflow, or restarting jl_
jl_throw_in_ctx(ptls, jl_stackovf_exception, sig, context);
}
else if (jl_is_on_sigstack(ptls, info->si_addr, context)) {
// This mainly happens when one of the finalizers during final cleanup
// on the signal stack has a deep/infinite recursion.
// There isn't anything more we can do
// (we are already corrupting that stack running this function)
// so just call `_exit` to terminate immediately.
jl_safe_printf("ERROR: Signal stack overflow, exit\n");
_exit(sig + 128);
}
else if (sig == SIGSEGV && info->si_code == SEGV_ACCERR && is_write_fault(context)) { // writing to read-only memory (e.g., mmap)
jl_throw_in_ctx(ptls, jl_readonlymemory_exception, sig, context);
}
else {
#ifdef SEGV_EXCEPTION
jl_throw_in_ctx(ptls, jl_segv_exception, sig, context);
#else
sigdie_handler(sig, info, context);
#endif
}
}
static void allocate_segv_handler(void)
{
struct sigaction act;
memset(&act, 0, sizeof(struct sigaction));
sigemptyset(&act.sa_mask);
act.sa_sigaction = segv_handler;
act.sa_flags = SA_ONSTACK | SA_SIGINFO;
if (sigaction(SIGSEGV, &act, NULL) < 0) {
jl_errorf("fatal error: sigaction: %s", strerror(errno));
}
// On AArch64, stack overflow triggers a SIGBUS
if (sigaction(SIGBUS, &act, NULL) < 0) {
jl_errorf("fatal error: sigaction: %s", strerror(errno));
}
}
#if !defined(JL_DISABLE_LIBUNWIND)
static unw_context_t *volatile signal_context;
static pthread_mutex_t in_signal_lock;
static pthread_cond_t exit_signal_cond;
static pthread_cond_t signal_caught_cond;
static void jl_thread_suspend_and_get_state(int tid, unw_context_t **ctx)
{
pthread_mutex_lock(&in_signal_lock);
jl_ptls_t ptls2 = jl_all_tls_states[tid];
jl_atomic_store_release(&ptls2->signal_request, 1);
pthread_kill(ptls2->system_id, SIGUSR2);
pthread_cond_wait(&signal_caught_cond, &in_signal_lock); // wait for thread to acknowledge
assert(jl_atomic_load_acquire(&ptls2->signal_request) == 0);
*ctx = signal_context;
}
static void jl_thread_resume(int tid, int sig)
{
(void)sig;
jl_ptls_t ptls2 = jl_all_tls_states[tid];
jl_atomic_store_release(&ptls2->signal_request, 1);
pthread_cond_broadcast(&exit_signal_cond);
pthread_cond_wait(&signal_caught_cond, &in_signal_lock); // wait for thread to acknowledge
assert(jl_atomic_load_acquire(&ptls2->signal_request) == 0);
pthread_mutex_unlock(&in_signal_lock);
}
#endif
// Throw jl_interrupt_exception if the master thread is in a signal async region
// or if SIGINT happens too often.
static void jl_try_deliver_sigint(void)
{
jl_ptls_t ptls2 = jl_all_tls_states[0];
jl_safepoint_enable_sigint();
jl_wake_libuv();
jl_atomic_store_release(&ptls2->signal_request, 2);
// This also makes sure `sleep` is aborted.
pthread_kill(ptls2->system_id, SIGUSR2);
}
// Write only by signal handling thread, read only by main thread
// no sync necessary.
static int thread0_exit_state = 0;
static void jl_exit_thread0_cb(void)
{
// This can get stuck if it happens at an unfortunate spot
// (unavoidable due to its async nature).
// Try harder to exit each time if we get multiple exit requests.
if (thread0_exit_count <= 1) {
jl_exit(thread0_exit_state);
}
else if (thread0_exit_count == 2) {
exit(thread0_exit_state);
}
else {
_exit(thread0_exit_state);
}
}
static void jl_exit_thread0(int state)
{
jl_ptls_t ptls2 = jl_all_tls_states[0];
thread0_exit_state = state;
jl_atomic_store_release(&ptls2->signal_request, 3);
pthread_kill(ptls2->system_id, SIGUSR2);
}
// request:
// 0: nothing
// 1: get state
// 2: throw sigint if `!defer_signal && io_wait` or if force throw threshold
// is reached
// 3: exit with `thread0_exit_state`
void usr2_handler(int sig, siginfo_t *info, void *ctx)
{
jl_ptls_t ptls = jl_get_ptls_states();
int errno_save = errno;
sig_atomic_t request = jl_atomic_exchange(&ptls->signal_request, 0);
#if !defined(JL_DISABLE_LIBUNWIND)
if (request == 1) {
signal_context = jl_to_bt_context(ctx);
pthread_mutex_lock(&in_signal_lock);
pthread_cond_broadcast(&signal_caught_cond);
pthread_cond_wait(&exit_signal_cond, &in_signal_lock);
request = jl_atomic_exchange(&ptls->signal_request, 0);
assert(request == 1);
(void)request;
pthread_cond_broadcast(&signal_caught_cond);
pthread_mutex_unlock(&in_signal_lock);
}
else
#endif
if (request == 2) {
int force = jl_check_force_sigint();
if (force || (!ptls->defer_signal && ptls->io_wait)) {
jl_safepoint_consume_sigint();
if (force)
jl_safe_printf("WARNING: Force throwing a SIGINT\n");
// Force a throw
jl_clear_force_sigint();
jl_throw_in_ctx(ptls, jl_interrupt_exception, sig, ctx);
}
}
else if (request == 3) {
jl_call_in_ctx(ptls, jl_exit_thread0_cb, sig, ctx);
}
errno = errno_save;
}
#if defined(HAVE_TIMER)
// Linux-style
#include <time.h>
#include <string.h> // for memset
static timer_t timerprof;
static struct itimerspec itsprof;
JL_DLLEXPORT int jl_profile_start_timer(void)
{
struct sigevent sigprof;
// Establish the signal event
memset(&sigprof, 0, sizeof(struct sigevent));
sigprof.sigev_notify = SIGEV_SIGNAL;
sigprof.sigev_signo = SIGUSR1;
sigprof.sigev_value.sival_ptr = &timerprof;
if (timer_create(CLOCK_REALTIME, &sigprof, &timerprof) == -1)
return -2;
// Start the timer
itsprof.it_interval.tv_sec = 0;
itsprof.it_interval.tv_nsec = 0;
itsprof.it_value.tv_sec = nsecprof / GIGA;
itsprof.it_value.tv_nsec = nsecprof % GIGA;
if (timer_settime(timerprof, 0, &itsprof, NULL) == -1)
return -3;
running = 1;
return 0;
}
JL_DLLEXPORT void jl_profile_stop_timer(void)
{
if (running)
timer_delete(timerprof);
running = 0;
}
#elif defined(HAVE_ITIMER)
// BSD-style timers
#include <string.h>
#include <sys/time.h>
struct itimerval timerprof;
JL_DLLEXPORT int jl_profile_start_timer(void)
{
timerprof.it_interval.tv_sec = 0;
timerprof.it_interval.tv_usec = 0;
timerprof.it_value.tv_sec = nsecprof / GIGA;
timerprof.it_value.tv_usec = ((nsecprof % GIGA) + 999) / 1000;
if (setitimer(ITIMER_PROF, &timerprof, NULL) == -1)
return -3;
running = 1;
return 0;
}
JL_DLLEXPORT void jl_profile_stop_timer(void)
{
if (running) {
running = 0;
memset(&timerprof, 0, sizeof(timerprof));
setitimer(ITIMER_PROF, &timerprof, NULL);
}
}
#else
#error no profile tools available
#endif
#endif // HAVE_MACH
static void *alloc_sigstack(size_t size)
{
size_t pagesz = jl_getpagesize();
// Add one guard page to catch stack overflow in the signal handler
size = LLT_ALIGN(size, pagesz) + pagesz;
void *stackbuff = mmap(0, size, PROT_READ | PROT_WRITE,
MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
if (stackbuff == MAP_FAILED)
jl_errorf("fatal error allocating signal stack: mmap: %s",
strerror(errno));
mprotect(stackbuff, pagesz, PROT_NONE);
return (void*)((char*)stackbuff + pagesz);
}
void jl_install_thread_signal_handler(jl_ptls_t ptls)
{
void *signal_stack = alloc_sigstack(sig_stack_size);
stack_t ss;
ss.ss_flags = 0;
ss.ss_size = sig_stack_size - 16;
ss.ss_sp = signal_stack;
if (sigaltstack(&ss, NULL) < 0) {
jl_errorf("fatal error: sigaltstack: %s", strerror(errno));
}
#if !defined(HAVE_MACH)
struct sigaction act;
memset(&act, 0, sizeof(struct sigaction));
sigemptyset(&act.sa_mask);
act.sa_sigaction = usr2_handler;
act.sa_flags = SA_ONSTACK | SA_SIGINFO | SA_RESTART;
if (sigaction(SIGUSR2, &act, NULL) < 0) {
jl_errorf("fatal error: sigaction: %s", strerror(errno));
}
#endif
ptls->signal_stack = signal_stack;
}
static void jl_sigsetset(sigset_t *sset)
{
sigemptyset(sset);
sigaddset(sset, SIGINT);
sigaddset(sset, SIGTERM);
sigaddset(sset, SIGABRT);
sigaddset(sset, SIGQUIT);
#ifdef SIGINFO
sigaddset(sset, SIGINFO);
#else
sigaddset(sset, SIGUSR1);
#endif
#if defined(HAVE_TIMER)
sigaddset(sset, SIGUSR1);
#elif defined(HAVE_ITIMER)
sigaddset(sset, SIGPROF);
#endif
}
#ifdef HAVE_KEVENT
static void kqueue_signal(int *sigqueue, struct kevent *ev, int sig)
{
if (*sigqueue == -1)
return;
EV_SET(ev, sig, EVFILT_SIGNAL, EV_ADD, 0, 0, 0);
if (kevent(*sigqueue, ev, 1, NULL, 0, NULL)) {
perror("signal kevent");
close(*sigqueue);
*sigqueue = -1;
}
else {
signal(sig, SIG_IGN);
}
}
#endif
static void *signal_listener(void *arg)
{
static jl_bt_element_t bt_data[JL_MAX_BT_SIZE + 1];
static size_t bt_size = 0;
sigset_t sset;
int sig, critical, profile;
jl_sigsetset(&sset);
#if defined(_POSIX_C_SOURCE) && _POSIX_C_SOURCE >= 199309L
siginfo_t info;
#endif
#ifdef HAVE_KEVENT
struct kevent ev;
int sigqueue = kqueue();
if (sigqueue == -1) {
perror("signal kqueue");
}
else {
kqueue_signal(&sigqueue, &ev, SIGINT);
kqueue_signal(&sigqueue, &ev, SIGTERM);
kqueue_signal(&sigqueue, &ev, SIGABRT);
kqueue_signal(&sigqueue, &ev, SIGQUIT);
#ifdef SIGINFO
kqueue_signal(&sigqueue, &ev, SIGINFO);
#else
kqueue_signal(&sigqueue, &ev, SIGUSR1);
#endif
#if defined(HAVE_TIMER)
kqueue_signal(&sigqueue, &ev, SIGUSR1);
#elif defined(HAVE_ITIMER)
kqueue_signal(&sigqueue, &ev, SIGPROF);
#endif
}
#endif
while (1) {
sig = 0;
errno = 0;
#ifdef HAVE_KEVENT
if (sigqueue != -1) {
int nevents = kevent(sigqueue, NULL, 0, &ev, 1, NULL);
if (nevents == -1) {
if (errno == EINTR)
continue;
perror("signal kevent");
}
if (nevents != 1) {
close(sigqueue);
sigqueue = -1;
continue;
}
sig = ev.ident;
}
else
#endif
#if defined(_POSIX_C_SOURCE) && _POSIX_C_SOURCE >= 199309L
sig = sigwaitinfo(&sset, &info);
#else
if (sigwait(&sset, &sig))
sig = -1;
#endif
if (sig == -1) {
if (errno == EINTR)
continue;
sig = SIGABRT; // this branch can't occur, unless we had stack memory corruption of sset
}
profile = 0;
#ifndef HAVE_MACH
#if defined(HAVE_TIMER)
profile = (sig == SIGUSR1);
#if _POSIX_C_SOURCE >= 199309L
if (profile && !(info.si_code == SI_TIMER &&
info.si_value.sival_ptr == &timerprof))
profile = 0;
#endif
#elif defined(HAVE_ITIMER)
profile = (sig == SIGPROF);
#endif
#endif
if (sig == SIGINT) {
if (jl_ignore_sigint()) {
continue;
}
else if (exit_on_sigint) {
critical = 1;
}
else {
jl_try_deliver_sigint();
continue;
}
}
else {
critical = 0;
}
critical |= (sig == SIGTERM);
critical |= (sig == SIGABRT);
critical |= (sig == SIGQUIT);
#ifdef SIGINFO
critical |= (sig == SIGINFO);
#else
critical |= (sig == SIGUSR1 && !profile);
#endif
int doexit = critical;
#ifdef SIGINFO
if (sig == SIGINFO)
doexit = 0;
#else
if (sig == SIGUSR1)
doexit = 0;
#endif
bt_size = 0;
#if !defined(JL_DISABLE_LIBUNWIND)
unw_context_t *signal_context;
// sample each thread, round-robin style in reverse order
// (so that thread zero gets notified last)
if (critical || profile)
jl_lock_profile();
for (int i = jl_n_threads; i-- > 0; ) {
// notify thread to stop
jl_thread_suspend_and_get_state(i, &signal_context);
// do backtrace on thread contexts for critical signals
// this part must be signal-handler safe
if (critical) {
bt_size += rec_backtrace_ctx(bt_data + bt_size,
JL_MAX_BT_SIZE / jl_n_threads - 1,
signal_context, NULL);
bt_data[bt_size++].uintptr = 0;
}
// do backtrace for profiler
if (profile && running) {
if (jl_profile_is_buffer_full()) {
// Buffer full: Delete the timer
jl_profile_stop_timer();
}
else {
// unwinding can fail, so keep track of the current state
// and restore from the SEGV handler if anything happens.
jl_ptls_t ptls = jl_get_ptls_states();
jl_jmp_buf *old_buf = ptls->safe_restore;
jl_jmp_buf buf;
ptls->safe_restore = &buf;
if (jl_setjmp(buf, 0)) {
jl_safe_printf("WARNING: profiler attempt to access an invalid memory location\n");
} else {
// Get backtrace data
bt_size_cur += rec_backtrace_ctx((jl_bt_element_t*)bt_data_prof + bt_size_cur,
bt_size_max - bt_size_cur - 1, signal_context, NULL);
}
ptls->safe_restore = old_buf;
// Mark the end of this block with 0
bt_data_prof[bt_size_cur++].uintptr = 0;
}
}
// notify thread to resume
jl_thread_resume(i, sig);
}
if (critical || profile)
jl_unlock_profile();
#ifndef HAVE_MACH
if (profile && running) {
#if defined(HAVE_TIMER)
timer_settime(timerprof, 0, &itsprof, NULL);
#elif defined(HAVE_ITIMER)
setitimer(ITIMER_PROF, &timerprof, NULL);
#endif
}
#endif
#endif
// this part is async with the running of the rest of the program
// and must be thread-safe, but not necessarily signal-handler safe
if (critical) {
jl_critical_error(sig, NULL, bt_data, &bt_size);
if (doexit) {
thread0_exit_count++;
jl_exit_thread0(128 + sig);
}
}
}
return NULL;
}
void restore_signals(void)
{
sigemptyset(&jl_sigint_sset);
sigaddset(&jl_sigint_sset, SIGINT);
sigset_t sset;
jl_sigsetset(&sset);
sigprocmask(SIG_SETMASK, &sset, 0);
#if !defined(HAVE_MACH) && !defined(JL_DISABLE_LIBUNWIND)
if (pthread_mutex_init(&in_signal_lock, NULL) != 0 ||
pthread_cond_init(&exit_signal_cond, NULL) != 0 ||
pthread_cond_init(&signal_caught_cond, NULL) != 0) {
jl_error("SIGUSR pthread init failed");
}
#endif
if (pthread_create(&signals_thread, NULL, signal_listener, NULL) != 0) {
jl_error("pthread_create(signal_listener) failed");
}
}
static void fpe_handler(int sig, siginfo_t *info, void *context)
{
(void)info;
jl_ptls_t ptls = jl_get_ptls_states();
jl_throw_in_ctx(ptls, jl_diverror_exception, sig, context);
}
static void sigint_handler(int sig)
{
jl_sigint_passed = 1;
}
void jl_install_default_signal_handlers(void)
{
struct sigaction actf;
memset(&actf, 0, sizeof(struct sigaction));
sigemptyset(&actf.sa_mask);
actf.sa_sigaction = fpe_handler;
actf.sa_flags = SA_SIGINFO;
if (sigaction(SIGFPE, &actf, NULL) < 0) {
jl_errorf("fatal error: sigaction: %s", strerror(errno));
}
struct sigaction actint;
memset(&actint, 0, sizeof(struct sigaction));
sigemptyset(&actint.sa_mask);
actint.sa_handler = sigint_handler;
actint.sa_flags = 0;
if (sigaction(SIGINT, &actint, NULL) < 0) {
jl_errorf("fatal error: sigaction: %s", strerror(errno));
}
if (signal(SIGPIPE, SIG_IGN) == SIG_ERR) {
jl_error("fatal error: Couldn't set SIGPIPE");
}
if (signal(SIGTRAP, SIG_IGN) == SIG_ERR) {
jl_error("fatal error: Couldn't set SIGTRAP");
}
allocate_segv_handler();
struct sigaction act_die;
memset(&act_die, 0, sizeof(struct sigaction));
sigemptyset(&act_die.sa_mask);
act_die.sa_sigaction = sigdie_handler;
act_die.sa_flags = SA_SIGINFO;
if (sigaction(SIGILL, &act_die, NULL) < 0) {
jl_errorf("fatal error: sigaction: %s", strerror(errno));
}
if (sigaction(SIGABRT, &act_die, NULL) < 0) {
jl_errorf("fatal error: sigaction: %s", strerror(errno));
}
if (sigaction(SIGSYS, &act_die, NULL) < 0) {
jl_errorf("fatal error: sigaction: %s", strerror(errno));
}
// need to ensure the following signals are not SIG_IGN, even though they will be blocked
act_die.sa_flags = SA_SIGINFO | SA_RESTART;
#if defined(HAVE_ITIMER)
if (sigaction(SIGPROF, &act_die, NULL) < 0) {
jl_errorf("fatal error: sigaction: %s", strerror(errno));
}
#endif
#ifdef SIGINFO
if (sigaction(SIGINFO, &act_die, NULL) < 0) {
jl_errorf("fatal error: sigaction: %s", strerror(errno));
}
#else
if (sigaction(SIGUSR1, &act_die, NULL) < 0) {
jl_errorf("fatal error: sigaction: %s", strerror(errno));
}
#endif
}
JL_DLLEXPORT void jl_install_sigint_handler(void)
{
// TODO: ?
}
JL_DLLEXPORT int jl_repl_raise_sigtstp(void)
{
return raise(SIGTSTP);
}
|
135845.c | #include <assert.h>
#include <drm_fourcc.h>
#include <gbm.h>
#include <stdbool.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <wayland-util.h>
#include <wlr/render/egl.h>
#include <wlr/render/gles2.h>
#include <wlr/render/wlr_renderer.h>
#include <wlr/types/wlr_matrix.h>
#include <wlr/util/log.h>
#include "backend/drm/drm.h"
bool init_drm_renderer(struct wlr_drm_backend *drm,
struct wlr_drm_renderer *renderer, wlr_renderer_create_func_t create_renderer_func) {
renderer->gbm = gbm_create_device(drm->fd);
if (!renderer->gbm) {
wlr_log(WLR_ERROR, "Failed to create GBM device");
return false;
}
if (!create_renderer_func) {
create_renderer_func = wlr_renderer_autocreate;
}
static EGLint config_attribs[] = {
EGL_SURFACE_TYPE, EGL_WINDOW_BIT,
EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT,
EGL_RED_SIZE, 1,
EGL_GREEN_SIZE, 1,
EGL_BLUE_SIZE, 1,
EGL_ALPHA_SIZE, 1,
EGL_NONE,
};
renderer->gbm_format = GBM_FORMAT_ARGB8888;
renderer->wlr_rend = create_renderer_func(&renderer->egl,
EGL_PLATFORM_GBM_MESA, renderer->gbm,
config_attribs, renderer->gbm_format);
if (!renderer->wlr_rend) {
wlr_log(WLR_ERROR, "Failed to create EGL/WLR renderer");
goto error_gbm;
}
renderer->fd = drm->fd;
return true;
error_gbm:
gbm_device_destroy(renderer->gbm);
return false;
}
void finish_drm_renderer(struct wlr_drm_renderer *renderer) {
if (!renderer) {
return;
}
wlr_renderer_destroy(renderer->wlr_rend);
wlr_egl_finish(&renderer->egl);
gbm_device_destroy(renderer->gbm);
}
static bool init_drm_surface(struct wlr_drm_surface *surf,
struct wlr_drm_renderer *renderer, uint32_t width, uint32_t height,
uint32_t format, struct wlr_drm_format_set *set, uint32_t flags) {
if (surf->width == width && surf->height == height) {
return true;
}
surf->renderer = renderer;
surf->width = width;
surf->height = height;
if (surf->gbm) {
gbm_surface_destroy(surf->gbm);
surf->gbm = NULL;
}
wlr_egl_destroy_surface(&surf->renderer->egl, surf->egl);
if (!(flags & GBM_BO_USE_LINEAR) && set != NULL) {
const struct wlr_drm_format *drm_format =
wlr_drm_format_set_get(set, format);
if (drm_format != NULL) {
surf->gbm = gbm_surface_create_with_modifiers(renderer->gbm,
width, height, format, drm_format->modifiers, drm_format->len);
}
}
if (surf->gbm == NULL) {
surf->gbm = gbm_surface_create(renderer->gbm, width, height,
format, GBM_BO_USE_RENDERING | flags);
}
if (!surf->gbm) {
wlr_log_errno(WLR_ERROR, "Failed to create GBM surface");
goto error_zero;
}
surf->egl = wlr_egl_create_surface(&renderer->egl, surf->gbm);
if (surf->egl == EGL_NO_SURFACE) {
wlr_log(WLR_ERROR, "Failed to create EGL surface");
goto error_gbm;
}
return true;
error_gbm:
gbm_surface_destroy(surf->gbm);
error_zero:
memset(surf, 0, sizeof(*surf));
return false;
}
static void finish_drm_surface(struct wlr_drm_surface *surf) {
if (!surf || !surf->renderer) {
return;
}
wlr_egl_destroy_surface(&surf->renderer->egl, surf->egl);
if (surf->gbm) {
gbm_surface_destroy(surf->gbm);
}
memset(surf, 0, sizeof(*surf));
}
bool drm_surface_make_current(struct wlr_drm_surface *surf,
int *buffer_damage) {
return wlr_egl_make_current(&surf->renderer->egl, surf->egl, buffer_damage);
}
bool export_drm_bo(struct gbm_bo *bo, struct wlr_dmabuf_attributes *attribs) {
memset(attribs, 0, sizeof(struct wlr_dmabuf_attributes));
attribs->n_planes = gbm_bo_get_plane_count(bo);
if (attribs->n_planes > WLR_DMABUF_MAX_PLANES) {
return false;
}
attribs->width = gbm_bo_get_width(bo);
attribs->height = gbm_bo_get_height(bo);
attribs->format = gbm_bo_get_format(bo);
attribs->modifier = gbm_bo_get_modifier(bo);
for (int i = 0; i < attribs->n_planes; ++i) {
attribs->offset[i] = gbm_bo_get_offset(bo, i);
attribs->stride[i] = gbm_bo_get_stride_for_plane(bo, i);
attribs->fd[i] = gbm_bo_get_fd(bo);
if (attribs->fd[i] < 0) {
for (int j = 0; j < i; ++j) {
close(attribs->fd[j]);
}
return false;
}
}
return true;
}
static void free_tex(struct gbm_bo *bo, void *data) {
struct wlr_texture *tex = data;
wlr_texture_destroy(tex);
}
static struct wlr_texture *get_tex_for_bo(struct wlr_drm_renderer *renderer,
struct gbm_bo *bo) {
struct wlr_texture *tex = gbm_bo_get_user_data(bo);
if (tex) {
return tex;
}
struct wlr_dmabuf_attributes attribs;
if (!export_drm_bo(bo, &attribs)) {
return NULL;
}
tex = wlr_texture_from_dmabuf(renderer->wlr_rend, &attribs);
if (tex) {
gbm_bo_set_user_data(bo, tex, free_tex);
}
return tex;
}
void drm_plane_finish_surface(struct wlr_drm_plane *plane) {
if (!plane) {
return;
}
drm_fb_clear(&plane->pending_fb);
drm_fb_clear(&plane->queued_fb);
drm_fb_clear(&plane->current_fb);
finish_drm_surface(&plane->surf);
finish_drm_surface(&plane->mgpu_surf);
}
static uint32_t strip_alpha_channel(uint32_t format) {
switch (format) {
case DRM_FORMAT_ARGB8888:
return DRM_FORMAT_XRGB8888;
default:
return DRM_FORMAT_INVALID;
}
}
bool drm_plane_init_surface(struct wlr_drm_plane *plane,
struct wlr_drm_backend *drm, int32_t width, uint32_t height,
uint32_t format, uint32_t flags, bool with_modifiers) {
if (!wlr_drm_format_set_has(&plane->formats, format, DRM_FORMAT_MOD_INVALID)) {
format = strip_alpha_channel(format);
}
if (!wlr_drm_format_set_has(&plane->formats, format, DRM_FORMAT_MOD_INVALID)) {
wlr_log(WLR_ERROR, "Plane %"PRIu32" doesn't support format 0x%"PRIX32,
plane->id, format);
return false;
}
struct wlr_drm_format_set *format_set =
with_modifiers ? &plane->formats : NULL;
drm_plane_finish_surface(plane);
if (!drm->parent) {
return init_drm_surface(&plane->surf, &drm->renderer, width, height,
format, format_set, flags | GBM_BO_USE_SCANOUT);
}
if (!init_drm_surface(&plane->surf, &drm->parent->renderer,
width, height, format, NULL,
flags | GBM_BO_USE_LINEAR)) {
return false;
}
if (!init_drm_surface(&plane->mgpu_surf, &drm->renderer,
width, height, format, format_set,
flags | GBM_BO_USE_SCANOUT)) {
finish_drm_surface(&plane->surf);
return false;
}
return true;
}
void drm_fb_clear(struct wlr_drm_fb *fb) {
switch (fb->type) {
case WLR_DRM_FB_TYPE_NONE:
assert(!fb->bo);
break;
case WLR_DRM_FB_TYPE_SURFACE:
gbm_surface_release_buffer(fb->surf->gbm, fb->bo);
break;
case WLR_DRM_FB_TYPE_WLR_BUFFER:
gbm_bo_destroy(fb->bo);
wlr_buffer_unlock(fb->wlr_buf);
fb->wlr_buf = NULL;
break;
}
fb->type = WLR_DRM_FB_TYPE_NONE;
fb->bo = NULL;
if (fb->mgpu_bo) {
assert(fb->mgpu_surf);
gbm_surface_release_buffer(fb->mgpu_surf->gbm, fb->mgpu_bo);
fb->mgpu_bo = NULL;
fb->mgpu_surf = NULL;
}
}
bool drm_fb_lock_surface(struct wlr_drm_fb *fb, struct wlr_drm_surface *surf) {
drm_fb_clear(fb);
if (!wlr_egl_swap_buffers(&surf->renderer->egl, surf->egl, NULL)) {
wlr_log(WLR_ERROR, "Failed to swap buffers");
return false;
}
fb->bo = gbm_surface_lock_front_buffer(surf->gbm);
if (!fb->bo) {
wlr_log(WLR_ERROR, "Failed to lock front buffer");
return false;
}
fb->type = WLR_DRM_FB_TYPE_SURFACE;
fb->surf = surf;
return true;
}
bool drm_fb_import_wlr(struct wlr_drm_fb *fb, struct wlr_drm_renderer *renderer,
struct wlr_buffer *buf, struct wlr_drm_format_set *set) {
drm_fb_clear(fb);
struct wlr_dmabuf_attributes attribs;
if (!wlr_buffer_get_dmabuf(buf, &attribs)) {
return false;
}
if (!wlr_drm_format_set_has(set, attribs.format, attribs.modifier)) {
// The format isn't supported by the plane. Try stripping the alpha
// channel, if any.
uint32_t format = strip_alpha_channel(attribs.format);
if (wlr_drm_format_set_has(set, format, attribs.modifier)) {
attribs.format = format;
} else {
return false;
}
}
if (attribs.modifier != DRM_FORMAT_MOD_INVALID ||
attribs.n_planes > 1 || attribs.offset[0] != 0) {
struct gbm_import_fd_modifier_data data = {
.width = attribs.width,
.height = attribs.height,
.format = attribs.format,
.num_fds = attribs.n_planes,
.modifier = attribs.modifier,
};
if ((size_t)attribs.n_planes > sizeof(data.fds) / sizeof(data.fds[0])) {
return false;
}
for (size_t i = 0; i < (size_t)attribs.n_planes; ++i) {
data.fds[i] = attribs.fd[i];
data.strides[i] = attribs.stride[i];
data.offsets[i] = attribs.offset[i];
}
fb->bo = gbm_bo_import(renderer->gbm, GBM_BO_IMPORT_FD_MODIFIER,
&data, GBM_BO_USE_SCANOUT);
} else {
struct gbm_import_fd_data data = {
.fd = attribs.fd[0],
.width = attribs.width,
.height = attribs.height,
.stride = attribs.stride[0],
.format = attribs.format,
};
fb->bo = gbm_bo_import(renderer->gbm, GBM_BO_IMPORT_FD,
&data, GBM_BO_USE_SCANOUT);
}
if (!fb->bo) {
return false;
}
fb->type = WLR_DRM_FB_TYPE_WLR_BUFFER;
fb->wlr_buf = wlr_buffer_lock(buf);
return true;
}
void drm_fb_move(struct wlr_drm_fb *new, struct wlr_drm_fb *old) {
drm_fb_clear(new);
*new = *old;
memset(old, 0, sizeof(*old));
}
bool drm_surface_render_black_frame(struct wlr_drm_surface *surf) {
if (!drm_surface_make_current(surf, NULL)) {
return false;
}
struct wlr_renderer *renderer = surf->renderer->wlr_rend;
wlr_renderer_begin(renderer, surf->width, surf->height);
wlr_renderer_clear(renderer, (float[]){ 0.0, 0.0, 0.0, 1.0 });
wlr_renderer_end(renderer);
return true;
}
struct gbm_bo *drm_fb_acquire(struct wlr_drm_fb *fb, struct wlr_drm_backend *drm,
struct wlr_drm_surface *mgpu) {
if (!fb->bo) {
wlr_log(WLR_ERROR, "Tried to acquire an FB with a NULL BO");
return NULL;
}
if (!drm->parent) {
return fb->bo;
}
if (fb->mgpu_bo) {
return fb->mgpu_bo;
}
/* Perform copy across GPUs */
struct wlr_texture *tex = get_tex_for_bo(mgpu->renderer, fb->bo);
if (!tex) {
return NULL;
}
if (!drm_surface_make_current(mgpu, NULL)) {
return NULL;
}
float mat[9];
wlr_matrix_projection(mat, 1, 1, WL_OUTPUT_TRANSFORM_NORMAL);
struct wlr_renderer *renderer = mgpu->renderer->wlr_rend;
wlr_renderer_begin(renderer, mgpu->width, mgpu->height);
wlr_renderer_clear(renderer, (float[]){ 0.0, 0.0, 0.0, 0.0 });
wlr_render_texture_with_matrix(renderer, tex, mat, 1.0f);
wlr_renderer_end(renderer);
if (!wlr_egl_swap_buffers(&mgpu->renderer->egl, mgpu->egl, NULL)) {
wlr_log(WLR_ERROR, "Failed to swap buffers");
return NULL;
}
fb->mgpu_bo = gbm_surface_lock_front_buffer(mgpu->gbm);
if (!fb->mgpu_bo) {
wlr_log(WLR_ERROR, "Failed to lock front buffer");
return NULL;
}
fb->mgpu_surf = mgpu;
return fb->mgpu_bo;
}
|
820899.c | /*
* Copyright 2019 Gianluca Frison, Dimitris Kouzoupis, Robin Verschueren,
* Andrea Zanelli, Niels van Duijkeren, Jonathan Frey, Tommaso Sartor,
* Branimir Novoselnik, Rien Quirynen, Rezart Qelibari, Dang Doan,
* Jonas Koenemann, Yutao Chen, Tobias Schöls, Jonas Schlagenhauf, Moritz Diehl
*
* This file is part of acados.
*
* The 2-Clause BSD License
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 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.;
*/
// standard
#include <stdio.h>
#include <stdlib.h>
// acados
#include "acados/utils/print.h"
#include "acados_c/ocp_nlp_interface.h"
#include "acados_c/external_function_interface.h"
// example specific
#include "{{ model.name }}_model/{{ model.name }}_model.h"
{% if constraints.constr_type == "BGP" and dims.nphi %}
#include "{{ model.name }}_constraints/{{ model.name }}_phi_constraint.h"
{% endif %}
{% if constraints.constr_type_e == "BGP" and dims.nphi_e > 0 %}
#include "{{ model.name }}_constraints/{{ model.name }}_phi_e_constraint.h"
{% endif %}
{% if constraints.constr_type == "BGH" and dims.nh > 0 %}
#include "{{ model.name }}_constraints/{{ model.name }}_h_constraint.h"
{% endif %}
{% if constraints.constr_type_e == "BGH" and dims.nh_e > 0 %}
#include "{{ model.name }}_constraints/{{ model.name }}_h_e_constraint.h"
{% endif %}
{%- if cost.cost_type == "NONLINEAR_LS" %}
#include "{{ model.name }}_cost/{{ model.name }}_cost_y_fun.h"
{%- elif cost.cost_type == "EXTERNAL" %}
#include "{{ model.name }}_cost/{{ model.name }}_external_cost.h"
{% endif %}
{%- if cost.cost_type_e == "NONLINEAR_LS" %}
#include "{{ model.name }}_cost/{{ model.name }}_cost_y_e_fun.h"
{%- elif cost.cost_type_e == "EXTERNAL" %}
#include "{{ model.name }}_cost/{{ model.name }}_external_cost_e.h"
{% endif %}
#include "acados_solver_{{ model.name }}.h"
#define NX {{ dims.nx }}
#define NZ {{ dims.nz }}
#define NU {{ dims.nu }}
#define NP {{ dims.np }}
#define NBX {{ dims.nbx }}
#define NBX0 {{ dims.nbx_0 }}
#define NBU {{ dims.nbu }}
#define NSBX {{ dims.nsbx }}
#define NSBU {{ dims.nsbu }}
#define NSH {{ dims.nsh }}
#define NSG {{ dims.nsg }}
#define NSPHI {{ dims.nsphi }}
#define NSHN {{ dims.nsh_e }}
#define NSGN {{ dims.nsg_e }}
#define NSPHIN {{ dims.nsphi_e }}
#define NSBXN {{ dims.nsbx_e }}
#define NS {{ dims.ns }}
#define NSN {{ dims.ns_e }}
#define NG {{ dims.ng }}
#define NBXN {{ dims.nbx_e }}
#define NGN {{ dims.ng_e }}
#define NY {{ dims.ny }}
#define NYN {{ dims.ny_e }}
#define N {{ dims.N }}
#define NH {{ dims.nh }}
#define NPHI {{ dims.nphi }}
#define NHN {{ dims.nh_e }}
#define NPHIN {{ dims.nphi_e }}
#define NR {{ dims.nr }}
// ** global data **
ocp_nlp_in * nlp_in;
ocp_nlp_out * nlp_out;
ocp_nlp_solver * nlp_solver;
void * nlp_opts;
ocp_nlp_plan * nlp_solver_plan;
ocp_nlp_config * nlp_config;
ocp_nlp_dims * nlp_dims;
// number of expected runtime parameters
const unsigned int nlp_np = NP;
{% if solver_options.integrator_type == "ERK" %}
external_function_param_casadi * forw_vde_casadi;
external_function_param_casadi * expl_ode_fun;
{% if solver_options.hessian_approx == "EXACT" %}
external_function_param_casadi * hess_vde_casadi;
{%- endif %}
{%- elif solver_options.integrator_type == "IRK" %}
external_function_param_casadi * impl_dae_fun;
external_function_param_casadi * impl_dae_fun_jac_x_xdot_z;
external_function_param_casadi * impl_dae_jac_x_xdot_u_z;
{%- if solver_options.hessian_approx == "EXACT" %}
external_function_param_casadi * impl_dae_hess;
{%- endif %}
{%- elif solver_options.integrator_type == "GNSF" %}
external_function_param_casadi * gnsf_phi_fun;
external_function_param_casadi * gnsf_phi_fun_jac_y;
external_function_param_casadi * gnsf_phi_jac_y_uhat;
external_function_param_casadi * gnsf_f_lo_jac_x1_x1dot_u_z;
external_function_param_casadi * gnsf_get_matrices_fun;
{% elif solver_options.integrator_type == "DISCRETE" %}
external_function_param_casadi * discr_dyn_phi_fun;
external_function_param_casadi * discr_dyn_phi_fun_jac_ut_xt;
{%- if solver_options.hessian_approx == "EXACT" %}
external_function_param_casadi * discr_dyn_phi_fun_jac_ut_xt_hess;
{%- endif %}
{%- endif %}
{% if constraints.constr_type == "BGH" %}
external_function_param_casadi * nl_constr_h_fun;
external_function_param_casadi * nl_constr_h_fun_jac;
{%- if solver_options.hessian_approx == "EXACT" %}
external_function_param_casadi * nl_constr_h_fun_jac_hess;
{%- endif %}
{%- elif constraints.constr_type == "BGP" %}
external_function_param_casadi * phi_constraint;
{%- endif %}
{% if constraints.constr_type_e == "BGH" %}
external_function_param_casadi nl_constr_h_e_fun_jac;
external_function_param_casadi nl_constr_h_e_fun;
{%- if solver_options.hessian_approx == "EXACT" %}
external_function_param_casadi nl_constr_h_e_fun_jac_hess;
{%- endif %}
{%- elif constraints.constr_type_e == "BGP" %}
external_function_param_casadi phi_e_constraint;
{%- endif %}
{%- if cost.cost_type == "NONLINEAR_LS" %}
external_function_param_casadi * cost_y_fun;
external_function_param_casadi * cost_y_fun_jac_ut_xt;
external_function_param_casadi * cost_y_hess;
{%- elif cost.cost_type == "EXTERNAL" %}
external_function_param_casadi * ext_cost_fun;
external_function_param_casadi * ext_cost_fun_jac;
external_function_param_casadi * ext_cost_fun_jac_hess;
{%- endif %}
{%- if cost.cost_type_e == "NONLINEAR_LS" %}
external_function_param_casadi cost_y_e_fun;
external_function_param_casadi cost_y_e_fun_jac_ut_xt;
external_function_param_casadi cost_y_e_hess;
{%- elif cost.cost_type_e == "EXTERNAL" %}
external_function_param_casadi ext_cost_e_fun;
external_function_param_casadi ext_cost_e_fun_jac;
external_function_param_casadi ext_cost_e_fun_jac_hess;
{%- endif %}
int acados_create()
{
int status = 0;
/************************************************
* plan & config
************************************************/
nlp_solver_plan = ocp_nlp_plan_create(N);
{%- if solver_options.nlp_solver_type == "SQP" %}
nlp_solver_plan->nlp_solver = SQP;
{% else %}
nlp_solver_plan->nlp_solver = SQP_RTI;
{%- endif %}
nlp_solver_plan->ocp_qp_solver_plan.qp_solver = {{ solver_options.qp_solver }};
for (int i = 0; i < N; i++)
nlp_solver_plan->nlp_cost[i] = {{ cost.cost_type }};
nlp_solver_plan->nlp_cost[N] = {{ cost.cost_type_e }};
for (int i = 0; i < N; i++)
{
{% if solver_options.integrator_type == "DISCRETE" %}
nlp_solver_plan->nlp_dynamics[i] = DISCRETE_MODEL;
// discrete dynamics does not need sim solver option, this field is ignored
nlp_solver_plan->sim_solver_plan[i].sim_solver = INVALID_SIM_SOLVER;
{% else %}
nlp_solver_plan->nlp_dynamics[i] = CONTINUOUS_MODEL;
nlp_solver_plan->sim_solver_plan[i].sim_solver = {{ solver_options.integrator_type }};
{%- endif %}
}
for (int i = 0; i < N; i++)
{
{% if constraints.constr_type == "BGP" %}
nlp_solver_plan->nlp_constraints[i] = BGP;
{%- else -%}
nlp_solver_plan->nlp_constraints[i] = BGH;
{%- endif %}
}
{%- if constraints.constr_type_e == "BGP" %}
nlp_solver_plan->nlp_constraints[N] = BGP;
{% else %}
nlp_solver_plan->nlp_constraints[N] = BGH;
{%- endif %}
{%- if solver_options.hessian_approx == "EXACT" %}
{%- if solver_options.regularize_method == "NO_REGULARIZE" %}
nlp_solver_plan->regularization = NO_REGULARIZE;
{%- elif solver_options.regularize_method == "MIRROR" %}
nlp_solver_plan->regularization = MIRROR;
{%- elif solver_options.regularize_method == "PROJECT" %}
nlp_solver_plan->regularization = PROJECT;
{%- elif solver_options.regularize_method == "PROJECT_REDUC_HESS" %}
nlp_solver_plan->regularization = PROJECT_REDUC_HESS;
{%- elif solver_options.regularize_method == "CONVEXIFY" %}
nlp_solver_plan->regularization = CONVEXIFY;
{%- endif %}
{%- endif %}
nlp_config = ocp_nlp_config_create(*nlp_solver_plan);
/************************************************
* dimensions
************************************************/
int nx[N+1];
int nu[N+1];
int nbx[N+1];
int nbu[N+1];
int nsbx[N+1];
int nsbu[N+1];
int nsg[N+1];
int nsh[N+1];
int nsphi[N+1];
int ns[N+1];
int ng[N+1];
int nh[N+1];
int nphi[N+1];
int nz[N+1];
int ny[N+1];
int nr[N+1];
int nbxe[N+1];
for (int i = 0; i < N+1; i++)
{
// common
nx[i] = NX;
nu[i] = NU;
nz[i] = NZ;
ns[i] = NS;
// cost
ny[i] = NY;
// constraints
nbx[i] = NBX;
nbu[i] = NBU;
nsbx[i] = NSBX;
nsbu[i] = NSBU;
nsg[i] = NSG;
nsh[i] = NSH;
nsphi[i] = NSPHI;
ng[i] = NG;
nh[i] = NH;
nphi[i] = NPHI;
nr[i] = NR;
nbxe[i] = 0;
}
// for initial state
nbx[0] = NBX0;
nsbx[0] = 0;
ns[0] = NS - NSBX;
nbxe[0] = {{ dims.nbxe_0 }};
// terminal - common
nu[N] = 0;
nz[N] = 0;
ns[N] = NSN;
// cost
ny[N] = NYN;
// constraint
nbx[N] = NBXN;
nbu[N] = 0;
ng[N] = NGN;
nh[N] = NHN;
nphi[N] = NPHIN;
nr[N] = {{ dims.nr_e }};
nsbx[N] = NSBXN;
nsbu[N] = 0;
nsg[N] = NSGN;
nsh[N] = NSHN;
nsphi[N] = NSPHIN;
/* create and set ocp_nlp_dims */
nlp_dims = ocp_nlp_dims_create(nlp_config);
ocp_nlp_dims_set_opt_vars(nlp_config, nlp_dims, "nx", nx);
ocp_nlp_dims_set_opt_vars(nlp_config, nlp_dims, "nu", nu);
ocp_nlp_dims_set_opt_vars(nlp_config, nlp_dims, "nz", nz);
ocp_nlp_dims_set_opt_vars(nlp_config, nlp_dims, "ns", ns);
for (int i = 0; i <= N; i++)
{
ocp_nlp_dims_set_constraints(nlp_config, nlp_dims, i, "nbx", &nbx[i]);
ocp_nlp_dims_set_constraints(nlp_config, nlp_dims, i, "nbu", &nbu[i]);
ocp_nlp_dims_set_constraints(nlp_config, nlp_dims, i, "nsbx", &nsbx[i]);
ocp_nlp_dims_set_constraints(nlp_config, nlp_dims, i, "nsbu", &nsbu[i]);
ocp_nlp_dims_set_constraints(nlp_config, nlp_dims, i, "ng", &ng[i]);
ocp_nlp_dims_set_constraints(nlp_config, nlp_dims, i, "nsg", &nsg[i]);
ocp_nlp_dims_set_constraints(nlp_config, nlp_dims, i, "nbxe", &nbxe[i]);
}
for (int i = 0; i < N; i++)
{
{%- if constraints.constr_type == "BGH" and dims.nh > 0 %}
ocp_nlp_dims_set_constraints(nlp_config, nlp_dims, i, "nh", &nh[i]);
ocp_nlp_dims_set_constraints(nlp_config, nlp_dims, i, "nsh", &nsh[i]);
{%- elif constraints.constr_type == "BGP" and dims.nphi > 0 %}
ocp_nlp_dims_set_constraints(nlp_config, nlp_dims, i, "nr", &nr[i]);
ocp_nlp_dims_set_constraints(nlp_config, nlp_dims, i, "nphi", &nphi[i]);
ocp_nlp_dims_set_constraints(nlp_config, nlp_dims, i, "nsphi", &nsphi[i]);
{%- endif %}
{%- if cost.cost_type == "NONLINEAR_LS" or cost.cost_type == "LINEAR_LS" %}
ocp_nlp_dims_set_cost(nlp_config, nlp_dims, i, "ny", &ny[i]);
{%- endif %}
}
{%- if constraints.constr_type_e == "BGH" %}
ocp_nlp_dims_set_constraints(nlp_config, nlp_dims, N, "nh", &nh[N]);
ocp_nlp_dims_set_constraints(nlp_config, nlp_dims, N, "nsh", &nsh[N]);
{%- elif constraints.constr_type_e == "BGP" %}
ocp_nlp_dims_set_constraints(nlp_config, nlp_dims, N, "nr", &nr[N]);
ocp_nlp_dims_set_constraints(nlp_config, nlp_dims, N, "nphi", &nphi[N]);
ocp_nlp_dims_set_constraints(nlp_config, nlp_dims, N, "nsphi", &nsphi[N]);
{%- endif %}
{%- if cost.cost_type_e == "NONLINEAR_LS" or cost.cost_type_e == "LINEAR_LS" %}
ocp_nlp_dims_set_cost(nlp_config, nlp_dims, N, "ny", &ny[N]);
{%- endif %}
{% if solver_options.integrator_type == "GNSF" -%}
// GNSF specific dimensions
int gnsf_nx1 = {{ dims.gnsf_nx1 }};
int gnsf_nz1 = {{ dims.gnsf_nz1 }};
int gnsf_nout = {{ dims.gnsf_nout }};
int gnsf_ny = {{ dims.gnsf_ny }};
int gnsf_nuhat = {{ dims.gnsf_nuhat }};
for (int i = 0; i < N; i++)
{
if (nlp_solver_plan->sim_solver_plan[i].sim_solver == GNSF)
{
ocp_nlp_dims_set_dynamics(nlp_config, nlp_dims, i, "gnsf_nx1", &gnsf_nx1);
ocp_nlp_dims_set_dynamics(nlp_config, nlp_dims, i, "gnsf_nz1", &gnsf_nz1);
ocp_nlp_dims_set_dynamics(nlp_config, nlp_dims, i, "gnsf_nout", &gnsf_nout);
ocp_nlp_dims_set_dynamics(nlp_config, nlp_dims, i, "gnsf_ny", &gnsf_ny);
ocp_nlp_dims_set_dynamics(nlp_config, nlp_dims, i, "gnsf_nuhat", &gnsf_nuhat);
}
}
{%- endif %}
/************************************************
* external functions
************************************************/
{%- if constraints.constr_type == "BGP" %}
phi_constraint = (external_function_param_casadi *) malloc(sizeof(external_function_param_casadi)*N);
for (int i = 0; i < N; i++)
{
// nonlinear part of convex-composite constraint
phi_constraint[i].casadi_fun = &{{ model.name }}_phi_constraint;
phi_constraint[i].casadi_n_in = &{{ model.name }}_phi_constraint_n_in;
phi_constraint[i].casadi_n_out = &{{ model.name }}_phi_constraint_n_out;
phi_constraint[i].casadi_sparsity_in = &{{ model.name }}_phi_constraint_sparsity_in;
phi_constraint[i].casadi_sparsity_out = &{{ model.name }}_phi_constraint_sparsity_out;
phi_constraint[i].casadi_work = &{{ model.name }}_phi_constraint_work;
external_function_param_casadi_create(&phi_constraint[i], {{ dims.np }});
}
{%- endif %}
{%- if constraints.constr_type_e == "BGP" %}
// nonlinear part of convex-composite constraint
phi_e_constraint.casadi_fun = &{{ model.name }}_phi_e_constraint;
phi_e_constraint.casadi_n_in = &{{ model.name }}_phi_e_constraint_n_in;
phi_e_constraint.casadi_n_out = &{{ model.name }}_phi_e_constraint_n_out;
phi_e_constraint.casadi_sparsity_in = &{{ model.name }}_phi_e_constraint_sparsity_in;
phi_e_constraint.casadi_sparsity_out = &{{ model.name }}_phi_e_constraint_sparsity_out;
phi_e_constraint.casadi_work = &{{ model.name }}_phi_e_constraint_work;
external_function_param_casadi_create(&phi_e_constraint, {{ dims.np }});
{% endif %}
{%- if constraints.constr_type == "BGH" and dims.nh > 0 %}
nl_constr_h_fun_jac = (external_function_param_casadi *) malloc(sizeof(external_function_param_casadi)*N);
for (int i = 0; i < N; i++) {
nl_constr_h_fun_jac[i].casadi_fun = &{{ model.name }}_constr_h_fun_jac_uxt_zt;
nl_constr_h_fun_jac[i].casadi_n_in = &{{ model.name }}_constr_h_fun_jac_uxt_zt_n_in;
nl_constr_h_fun_jac[i].casadi_n_out = &{{ model.name }}_constr_h_fun_jac_uxt_zt_n_out;
nl_constr_h_fun_jac[i].casadi_sparsity_in = &{{ model.name }}_constr_h_fun_jac_uxt_zt_sparsity_in;
nl_constr_h_fun_jac[i].casadi_sparsity_out = &{{ model.name }}_constr_h_fun_jac_uxt_zt_sparsity_out;
nl_constr_h_fun_jac[i].casadi_work = &{{ model.name }}_constr_h_fun_jac_uxt_zt_work;
external_function_param_casadi_create(&nl_constr_h_fun_jac[i], {{ dims.np }});
}
nl_constr_h_fun = (external_function_param_casadi *) malloc(sizeof(external_function_param_casadi)*N);
for (int i = 0; i < N; i++) {
nl_constr_h_fun[i].casadi_fun = &{{ model.name }}_constr_h_fun;
nl_constr_h_fun[i].casadi_n_in = &{{ model.name }}_constr_h_fun_n_in;
nl_constr_h_fun[i].casadi_n_out = &{{ model.name }}_constr_h_fun_n_out;
nl_constr_h_fun[i].casadi_sparsity_in = &{{ model.name }}_constr_h_fun_sparsity_in;
nl_constr_h_fun[i].casadi_sparsity_out = &{{ model.name }}_constr_h_fun_sparsity_out;
nl_constr_h_fun[i].casadi_work = &{{ model.name }}_constr_h_fun_work;
external_function_param_casadi_create(&nl_constr_h_fun[i], {{ dims.np }});
}
{% if solver_options.hessian_approx == "EXACT" %}
nl_constr_h_fun_jac_hess = (external_function_param_casadi *) malloc(sizeof(external_function_param_casadi)*N);
for (int i = 0; i < N; i++) {
nl_constr_h_fun_jac_hess[i].casadi_fun = &{{ model.name }}_constr_h_fun_jac_uxt_hess;
nl_constr_h_fun_jac_hess[i].casadi_n_in = &{{ model.name }}_constr_h_fun_jac_uxt_hess_n_in;
nl_constr_h_fun_jac_hess[i].casadi_n_out = &{{ model.name }}_constr_h_fun_jac_uxt_hess_n_out;
nl_constr_h_fun_jac_hess[i].casadi_sparsity_in = &{{ model.name }}_constr_h_fun_jac_uxt_hess_sparsity_in;
nl_constr_h_fun_jac_hess[i].casadi_sparsity_out = &{{ model.name }}_constr_h_fun_jac_uxt_hess_sparsity_out;
nl_constr_h_fun_jac_hess[i].casadi_work = &{{ model.name }}_constr_h_fun_jac_uxt_hess_work;
external_function_param_casadi_create(&nl_constr_h_fun_jac_hess[i], {{ dims.np }});
}
{% endif %}
{% endif %}
{%- if constraints.constr_type_e == "BGH" and dims.nh_e > 0 %}
nl_constr_h_e_fun_jac.casadi_fun = &{{ model.name }}_constr_h_e_fun_jac_uxt_zt;
nl_constr_h_e_fun_jac.casadi_n_in = &{{ model.name }}_constr_h_e_fun_jac_uxt_zt_n_in;
nl_constr_h_e_fun_jac.casadi_n_out = &{{ model.name }}_constr_h_e_fun_jac_uxt_zt_n_out;
nl_constr_h_e_fun_jac.casadi_sparsity_in = &{{ model.name }}_constr_h_e_fun_jac_uxt_zt_sparsity_in;
nl_constr_h_e_fun_jac.casadi_sparsity_out = &{{ model.name }}_constr_h_e_fun_jac_uxt_zt_sparsity_out;
nl_constr_h_e_fun_jac.casadi_work = &{{ model.name }}_constr_h_e_fun_jac_uxt_zt_work;
external_function_param_casadi_create(&nl_constr_h_e_fun_jac, {{ dims.np }});
nl_constr_h_e_fun.casadi_fun = &{{ model.name }}_constr_h_e_fun;
nl_constr_h_e_fun.casadi_n_in = &{{ model.name }}_constr_h_e_fun_n_in;
nl_constr_h_e_fun.casadi_n_out = &{{ model.name }}_constr_h_e_fun_n_out;
nl_constr_h_e_fun.casadi_sparsity_in = &{{ model.name }}_constr_h_e_fun_sparsity_in;
nl_constr_h_e_fun.casadi_sparsity_out = &{{ model.name }}_constr_h_e_fun_sparsity_out;
nl_constr_h_e_fun.casadi_work = &{{ model.name }}_constr_h_e_fun_work;
external_function_param_casadi_create(&nl_constr_h_e_fun, {{ dims.np }});
{% if solver_options.hessian_approx == "EXACT" %}
nl_constr_h_e_fun_jac_hess.casadi_fun = &{{ model.name }}_constr_h_e_fun_jac_uxt_hess;
nl_constr_h_e_fun_jac_hess.casadi_n_in = &{{ model.name }}_constr_h_e_fun_jac_uxt_hess_n_in;
nl_constr_h_e_fun_jac_hess.casadi_n_out = &{{ model.name }}_constr_h_e_fun_jac_uxt_hess_n_out;
nl_constr_h_e_fun_jac_hess.casadi_sparsity_in = &{{ model.name }}_constr_h_e_fun_jac_uxt_hess_sparsity_in;
nl_constr_h_e_fun_jac_hess.casadi_sparsity_out = &{{ model.name }}_constr_h_e_fun_jac_uxt_hess_sparsity_out;
nl_constr_h_e_fun_jac_hess.casadi_work = &{{ model.name }}_constr_h_e_fun_jac_uxt_hess_work;
external_function_param_casadi_create(&nl_constr_h_e_fun_jac_hess, {{ dims.np }});
{% endif %}
{%- endif %}
{% if solver_options.integrator_type == "ERK" %}
// explicit ode
forw_vde_casadi = (external_function_param_casadi *) malloc(sizeof(external_function_param_casadi)*N);
for (int i = 0; i < N; i++) {
forw_vde_casadi[i].casadi_fun = &{{ model.name }}_expl_vde_forw;
forw_vde_casadi[i].casadi_n_in = &{{ model.name }}_expl_vde_forw_n_in;
forw_vde_casadi[i].casadi_n_out = &{{ model.name }}_expl_vde_forw_n_out;
forw_vde_casadi[i].casadi_sparsity_in = &{{ model.name }}_expl_vde_forw_sparsity_in;
forw_vde_casadi[i].casadi_sparsity_out = &{{ model.name }}_expl_vde_forw_sparsity_out;
forw_vde_casadi[i].casadi_work = &{{ model.name }}_expl_vde_forw_work;
external_function_param_casadi_create(&forw_vde_casadi[i], {{ dims.np }});
}
expl_ode_fun = (external_function_param_casadi *) malloc(sizeof(external_function_param_casadi)*N);
for (int i = 0; i < N; i++) {
expl_ode_fun[i].casadi_fun = &{{ model.name }}_expl_ode_fun;
expl_ode_fun[i].casadi_n_in = &{{ model.name }}_expl_ode_fun_n_in;
expl_ode_fun[i].casadi_n_out = &{{ model.name }}_expl_ode_fun_n_out;
expl_ode_fun[i].casadi_sparsity_in = &{{ model.name }}_expl_ode_fun_sparsity_in;
expl_ode_fun[i].casadi_sparsity_out = &{{ model.name }}_expl_ode_fun_sparsity_out;
expl_ode_fun[i].casadi_work = &{{ model.name }}_expl_ode_fun_work;
external_function_param_casadi_create(&expl_ode_fun[i], {{ dims.np }});
}
{%- if solver_options.hessian_approx == "EXACT" %}
hess_vde_casadi = (external_function_param_casadi *) malloc(sizeof(external_function_param_casadi)*N);
for (int i = 0; i < N; i++) {
hess_vde_casadi[i].casadi_fun = &{{ model.name }}_expl_ode_hess;
hess_vde_casadi[i].casadi_n_in = &{{ model.name }}_expl_ode_hess_n_in;
hess_vde_casadi[i].casadi_n_out = &{{ model.name }}_expl_ode_hess_n_out;
hess_vde_casadi[i].casadi_sparsity_in = &{{ model.name }}_expl_ode_hess_sparsity_in;
hess_vde_casadi[i].casadi_sparsity_out = &{{ model.name }}_expl_ode_hess_sparsity_out;
hess_vde_casadi[i].casadi_work = &{{ model.name }}_expl_ode_hess_work;
external_function_param_casadi_create(&hess_vde_casadi[i], {{ dims.np }});
}
{%- endif %}
{% elif solver_options.integrator_type == "IRK" %}
// implicit dae
impl_dae_fun = (external_function_param_casadi *) malloc(sizeof(external_function_param_casadi)*N);
for (int i = 0; i < N; i++) {
impl_dae_fun[i].casadi_fun = &{{ model.name }}_impl_dae_fun;
impl_dae_fun[i].casadi_work = &{{ model.name }}_impl_dae_fun_work;
impl_dae_fun[i].casadi_sparsity_in = &{{ model.name }}_impl_dae_fun_sparsity_in;
impl_dae_fun[i].casadi_sparsity_out = &{{ model.name }}_impl_dae_fun_sparsity_out;
impl_dae_fun[i].casadi_n_in = &{{ model.name }}_impl_dae_fun_n_in;
impl_dae_fun[i].casadi_n_out = &{{ model.name }}_impl_dae_fun_n_out;
external_function_param_casadi_create(&impl_dae_fun[i], {{ dims.np }});
}
impl_dae_fun_jac_x_xdot_z = (external_function_param_casadi *) malloc(sizeof(external_function_param_casadi)*N);
for (int i = 0; i < N; i++) {
impl_dae_fun_jac_x_xdot_z[i].casadi_fun = &{{ model.name }}_impl_dae_fun_jac_x_xdot_z;
impl_dae_fun_jac_x_xdot_z[i].casadi_work = &{{ model.name }}_impl_dae_fun_jac_x_xdot_z_work;
impl_dae_fun_jac_x_xdot_z[i].casadi_sparsity_in = &{{ model.name }}_impl_dae_fun_jac_x_xdot_z_sparsity_in;
impl_dae_fun_jac_x_xdot_z[i].casadi_sparsity_out = &{{ model.name }}_impl_dae_fun_jac_x_xdot_z_sparsity_out;
impl_dae_fun_jac_x_xdot_z[i].casadi_n_in = &{{ model.name }}_impl_dae_fun_jac_x_xdot_z_n_in;
impl_dae_fun_jac_x_xdot_z[i].casadi_n_out = &{{ model.name }}_impl_dae_fun_jac_x_xdot_z_n_out;
external_function_param_casadi_create(&impl_dae_fun_jac_x_xdot_z[i], {{ dims.np }});
}
impl_dae_jac_x_xdot_u_z = (external_function_param_casadi *) malloc(sizeof(external_function_param_casadi)*N);
for (int i = 0; i < N; i++) {
impl_dae_jac_x_xdot_u_z[i].casadi_fun = &{{ model.name }}_impl_dae_jac_x_xdot_u_z;
impl_dae_jac_x_xdot_u_z[i].casadi_work = &{{ model.name }}_impl_dae_jac_x_xdot_u_z_work;
impl_dae_jac_x_xdot_u_z[i].casadi_sparsity_in = &{{ model.name }}_impl_dae_jac_x_xdot_u_z_sparsity_in;
impl_dae_jac_x_xdot_u_z[i].casadi_sparsity_out = &{{ model.name }}_impl_dae_jac_x_xdot_u_z_sparsity_out;
impl_dae_jac_x_xdot_u_z[i].casadi_n_in = &{{ model.name }}_impl_dae_jac_x_xdot_u_z_n_in;
impl_dae_jac_x_xdot_u_z[i].casadi_n_out = &{{ model.name }}_impl_dae_jac_x_xdot_u_z_n_out;
external_function_param_casadi_create(&impl_dae_jac_x_xdot_u_z[i], {{ dims.np }});
}
{%- if solver_options.hessian_approx == "EXACT" %}
impl_dae_hess = (external_function_param_casadi *) malloc(sizeof(external_function_param_casadi)*N);
for (int i = 0; i < N; i++) {
impl_dae_hess[i].casadi_fun = &{{ model.name }}_impl_dae_hess;
impl_dae_hess[i].casadi_work = &{{ model.name }}_impl_dae_hess_work;
impl_dae_hess[i].casadi_sparsity_in = &{{ model.name }}_impl_dae_hess_sparsity_in;
impl_dae_hess[i].casadi_sparsity_out = &{{ model.name }}_impl_dae_hess_sparsity_out;
impl_dae_hess[i].casadi_n_in = &{{ model.name }}_impl_dae_hess_n_in;
impl_dae_hess[i].casadi_n_out = &{{ model.name }}_impl_dae_hess_n_out;
external_function_param_casadi_create(&impl_dae_hess[i], {{ dims.np }});
}
{%- endif %}
{% elif solver_options.integrator_type == "GNSF" %}
gnsf_phi_fun = (external_function_param_casadi *) malloc(sizeof(external_function_param_casadi)*N);
for (int i = 0; i < N; i++) {
gnsf_phi_fun[i].casadi_fun = &{{ model.name }}_gnsf_phi_fun;
gnsf_phi_fun[i].casadi_work = &{{ model.name }}_gnsf_phi_fun_work;
gnsf_phi_fun[i].casadi_sparsity_in = &{{ model.name }}_gnsf_phi_fun_sparsity_in;
gnsf_phi_fun[i].casadi_sparsity_out = &{{ model.name }}_gnsf_phi_fun_sparsity_out;
gnsf_phi_fun[i].casadi_n_in = &{{ model.name }}_gnsf_phi_fun_n_in;
gnsf_phi_fun[i].casadi_n_out = &{{ model.name }}_gnsf_phi_fun_n_out;
external_function_param_casadi_create(&gnsf_phi_fun[i], {{ dims.np }});
}
gnsf_phi_fun_jac_y = (external_function_param_casadi *) malloc(sizeof(external_function_param_casadi)*N);
for (int i = 0; i < N; i++) {
gnsf_phi_fun_jac_y[i].casadi_fun = &{{ model.name }}_gnsf_phi_fun_jac_y;
gnsf_phi_fun_jac_y[i].casadi_work = &{{ model.name }}_gnsf_phi_fun_jac_y_work;
gnsf_phi_fun_jac_y[i].casadi_sparsity_in = &{{ model.name }}_gnsf_phi_fun_jac_y_sparsity_in;
gnsf_phi_fun_jac_y[i].casadi_sparsity_out = &{{ model.name }}_gnsf_phi_fun_jac_y_sparsity_out;
gnsf_phi_fun_jac_y[i].casadi_n_in = &{{ model.name }}_gnsf_phi_fun_jac_y_n_in;
gnsf_phi_fun_jac_y[i].casadi_n_out = &{{ model.name }}_gnsf_phi_fun_jac_y_n_out;
external_function_param_casadi_create(&gnsf_phi_fun_jac_y[i], {{ dims.np }});
}
gnsf_phi_jac_y_uhat = (external_function_param_casadi *) malloc(sizeof(external_function_param_casadi)*N);
for (int i = 0; i < N; i++) {
gnsf_phi_jac_y_uhat[i].casadi_fun = &{{ model.name }}_gnsf_phi_jac_y_uhat;
gnsf_phi_jac_y_uhat[i].casadi_work = &{{ model.name }}_gnsf_phi_jac_y_uhat_work;
gnsf_phi_jac_y_uhat[i].casadi_sparsity_in = &{{ model.name }}_gnsf_phi_jac_y_uhat_sparsity_in;
gnsf_phi_jac_y_uhat[i].casadi_sparsity_out = &{{ model.name }}_gnsf_phi_jac_y_uhat_sparsity_out;
gnsf_phi_jac_y_uhat[i].casadi_n_in = &{{ model.name }}_gnsf_phi_jac_y_uhat_n_in;
gnsf_phi_jac_y_uhat[i].casadi_n_out = &{{ model.name }}_gnsf_phi_jac_y_uhat_n_out;
external_function_param_casadi_create(&gnsf_phi_jac_y_uhat[i], {{ dims.np }});
}
gnsf_f_lo_jac_x1_x1dot_u_z = (external_function_param_casadi *) malloc(sizeof(external_function_param_casadi)*N);
for (int i = 0; i < N; i++) {
gnsf_f_lo_jac_x1_x1dot_u_z[i].casadi_fun = &{{ model.name }}_gnsf_f_lo_fun_jac_x1k1uz;
gnsf_f_lo_jac_x1_x1dot_u_z[i].casadi_work = &{{ model.name }}_gnsf_f_lo_fun_jac_x1k1uz_work;
gnsf_f_lo_jac_x1_x1dot_u_z[i].casadi_sparsity_in = &{{ model.name }}_gnsf_f_lo_fun_jac_x1k1uz_sparsity_in;
gnsf_f_lo_jac_x1_x1dot_u_z[i].casadi_sparsity_out = &{{ model.name }}_gnsf_f_lo_fun_jac_x1k1uz_sparsity_out;
gnsf_f_lo_jac_x1_x1dot_u_z[i].casadi_n_in = &{{ model.name }}_gnsf_f_lo_fun_jac_x1k1uz_n_in;
gnsf_f_lo_jac_x1_x1dot_u_z[i].casadi_n_out = &{{ model.name }}_gnsf_f_lo_fun_jac_x1k1uz_n_out;
external_function_param_casadi_create(&gnsf_f_lo_jac_x1_x1dot_u_z[i], {{ dims.np }});
}
gnsf_get_matrices_fun = (external_function_param_casadi *) malloc(sizeof(external_function_param_casadi)*N);
for (int i = 0; i < N; i++) {
gnsf_get_matrices_fun[i].casadi_fun = &{{ model.name }}_gnsf_get_matrices_fun;
gnsf_get_matrices_fun[i].casadi_work = &{{ model.name }}_gnsf_get_matrices_fun_work;
gnsf_get_matrices_fun[i].casadi_sparsity_in = &{{ model.name }}_gnsf_get_matrices_fun_sparsity_in;
gnsf_get_matrices_fun[i].casadi_sparsity_out = &{{ model.name }}_gnsf_get_matrices_fun_sparsity_out;
gnsf_get_matrices_fun[i].casadi_n_in = &{{ model.name }}_gnsf_get_matrices_fun_n_in;
gnsf_get_matrices_fun[i].casadi_n_out = &{{ model.name }}_gnsf_get_matrices_fun_n_out;
external_function_param_casadi_create(&gnsf_get_matrices_fun[i], {{ dims.np }});
}
{% elif solver_options.integrator_type == "DISCRETE" %}
// discrete dynamics
discr_dyn_phi_fun = (external_function_param_casadi *) malloc(sizeof(external_function_param_casadi)*N);
for (int i = 0; i < N; i++)
{
discr_dyn_phi_fun[i].casadi_fun = &{{ model.name }}_dyn_disc_phi_fun;
discr_dyn_phi_fun[i].casadi_n_in = &{{ model.name }}_dyn_disc_phi_fun_n_in;
discr_dyn_phi_fun[i].casadi_n_out = &{{ model.name }}_dyn_disc_phi_fun_n_out;
discr_dyn_phi_fun[i].casadi_sparsity_in = &{{ model.name }}_dyn_disc_phi_fun_sparsity_in;
discr_dyn_phi_fun[i].casadi_sparsity_out = &{{ model.name }}_dyn_disc_phi_fun_sparsity_out;
discr_dyn_phi_fun[i].casadi_work = &{{ model.name }}_dyn_disc_phi_fun_work;
external_function_param_casadi_create(&discr_dyn_phi_fun[i], {{ dims.np }});
}
discr_dyn_phi_fun_jac_ut_xt = (external_function_param_casadi *) malloc(sizeof(external_function_param_casadi)*N);
for (int i = 0; i < N; i++)
{
discr_dyn_phi_fun_jac_ut_xt[i].casadi_fun = &{{ model.name }}_dyn_disc_phi_fun_jac;
discr_dyn_phi_fun_jac_ut_xt[i].casadi_n_in = &{{ model.name }}_dyn_disc_phi_fun_jac_n_in;
discr_dyn_phi_fun_jac_ut_xt[i].casadi_n_out = &{{ model.name }}_dyn_disc_phi_fun_jac_n_out;
discr_dyn_phi_fun_jac_ut_xt[i].casadi_sparsity_in = &{{ model.name }}_dyn_disc_phi_fun_jac_sparsity_in;
discr_dyn_phi_fun_jac_ut_xt[i].casadi_sparsity_out = &{{ model.name }}_dyn_disc_phi_fun_jac_sparsity_out;
discr_dyn_phi_fun_jac_ut_xt[i].casadi_work = &{{ model.name }}_dyn_disc_phi_fun_jac_work;
external_function_param_casadi_create(&discr_dyn_phi_fun_jac_ut_xt[i], {{ dims.np }});
}
{%- if solver_options.hessian_approx == "EXACT" %}
discr_dyn_phi_fun_jac_ut_xt_hess = (external_function_param_casadi *) malloc(sizeof(external_function_param_casadi)*N);
for (int i = 0; i < N; i++)
{
discr_dyn_phi_fun_jac_ut_xt_hess[i].casadi_fun = &{{ model.name }}_dyn_disc_phi_fun_jac_hess;
discr_dyn_phi_fun_jac_ut_xt_hess[i].casadi_n_in = &{{ model.name }}_dyn_disc_phi_fun_jac_hess_n_in;
discr_dyn_phi_fun_jac_ut_xt_hess[i].casadi_n_out = &{{ model.name }}_dyn_disc_phi_fun_jac_hess_n_out;
discr_dyn_phi_fun_jac_ut_xt_hess[i].casadi_sparsity_in = &{{ model.name }}_dyn_disc_phi_fun_jac_hess_sparsity_in;
discr_dyn_phi_fun_jac_ut_xt_hess[i].casadi_sparsity_out = &{{ model.name }}_dyn_disc_phi_fun_jac_hess_sparsity_out;
discr_dyn_phi_fun_jac_ut_xt_hess[i].casadi_work = &{{ model.name }}_dyn_disc_phi_fun_jac_hess_work;
external_function_param_casadi_create(&discr_dyn_phi_fun_jac_ut_xt_hess[i], {{ dims.np }});
}
{%- endif %}
{%- endif %}
{%- if cost.cost_type == "NONLINEAR_LS" %}
// nonlinear least squares cost
cost_y_fun = (external_function_param_casadi *) malloc(sizeof(external_function_param_casadi)*N);
for (int i = 0; i < N; i++)
{
cost_y_fun[i].casadi_fun = &{{ model.name }}_cost_y_fun;
cost_y_fun[i].casadi_n_in = &{{ model.name }}_cost_y_fun_n_in;
cost_y_fun[i].casadi_n_out = &{{ model.name }}_cost_y_fun_n_out;
cost_y_fun[i].casadi_sparsity_in = &{{ model.name }}_cost_y_fun_sparsity_in;
cost_y_fun[i].casadi_sparsity_out = &{{ model.name }}_cost_y_fun_sparsity_out;
cost_y_fun[i].casadi_work = &{{ model.name }}_cost_y_fun_work;
external_function_param_casadi_create(&cost_y_fun[i], {{ dims.np }});
}
cost_y_fun_jac_ut_xt = (external_function_param_casadi *) malloc(sizeof(external_function_param_casadi)*N);
for (int i = 0; i < N; i++)
{
cost_y_fun_jac_ut_xt[i].casadi_fun = &{{ model.name }}_cost_y_fun_jac_ut_xt;
cost_y_fun_jac_ut_xt[i].casadi_n_in = &{{ model.name }}_cost_y_fun_jac_ut_xt_n_in;
cost_y_fun_jac_ut_xt[i].casadi_n_out = &{{ model.name }}_cost_y_fun_jac_ut_xt_n_out;
cost_y_fun_jac_ut_xt[i].casadi_sparsity_in = &{{ model.name }}_cost_y_fun_jac_ut_xt_sparsity_in;
cost_y_fun_jac_ut_xt[i].casadi_sparsity_out = &{{ model.name }}_cost_y_fun_jac_ut_xt_sparsity_out;
cost_y_fun_jac_ut_xt[i].casadi_work = &{{ model.name }}_cost_y_fun_jac_ut_xt_work;
external_function_param_casadi_create(&cost_y_fun_jac_ut_xt[i], {{ dims.np }});
}
cost_y_hess = (external_function_param_casadi *) malloc(sizeof(external_function_param_casadi)*N);
for (int i = 0; i < N; i++)
{
cost_y_hess[i].casadi_fun = &{{ model.name }}_cost_y_hess;
cost_y_hess[i].casadi_n_in = &{{ model.name }}_cost_y_hess_n_in;
cost_y_hess[i].casadi_n_out = &{{ model.name }}_cost_y_hess_n_out;
cost_y_hess[i].casadi_sparsity_in = &{{ model.name }}_cost_y_hess_sparsity_in;
cost_y_hess[i].casadi_sparsity_out = &{{ model.name }}_cost_y_hess_sparsity_out;
cost_y_hess[i].casadi_work = &{{ model.name }}_cost_y_hess_work;
external_function_param_casadi_create(&cost_y_hess[i], {{ dims.np }});
}
{%- elif cost.cost_type == "EXTERNAL" %}
// external cost
ext_cost_fun = (external_function_param_casadi *) malloc(sizeof(external_function_param_casadi)*N);
for (int i = 0; i < N; i++)
{
ext_cost_fun[i].casadi_fun = &{{ model.name }}_cost_ext_cost_fun;
ext_cost_fun[i].casadi_n_in = &{{ model.name }}_cost_ext_cost_fun_n_in;
ext_cost_fun[i].casadi_n_out = &{{ model.name }}_cost_ext_cost_fun_n_out;
ext_cost_fun[i].casadi_sparsity_in = &{{ model.name }}_cost_ext_cost_fun_sparsity_in;
ext_cost_fun[i].casadi_sparsity_out = &{{ model.name }}_cost_ext_cost_fun_sparsity_out;
ext_cost_fun[i].casadi_work = &{{ model.name }}_cost_ext_cost_fun_work;
external_function_param_casadi_create(&ext_cost_fun[i], {{ dims.np }});
}
ext_cost_fun_jac = (external_function_param_casadi *) malloc(sizeof(external_function_param_casadi)*N);
for (int i = 0; i < N; i++)
{
// residual function
ext_cost_fun_jac[i].casadi_fun = &{{ model.name }}_cost_ext_cost_fun_jac;
ext_cost_fun_jac[i].casadi_n_in = &{{ model.name }}_cost_ext_cost_fun_jac_n_in;
ext_cost_fun_jac[i].casadi_n_out = &{{ model.name }}_cost_ext_cost_fun_jac_n_out;
ext_cost_fun_jac[i].casadi_sparsity_in = &{{ model.name }}_cost_ext_cost_fun_jac_sparsity_in;
ext_cost_fun_jac[i].casadi_sparsity_out = &{{ model.name }}_cost_ext_cost_fun_jac_sparsity_out;
ext_cost_fun_jac[i].casadi_work = &{{ model.name }}_cost_ext_cost_fun_jac_work;
external_function_param_casadi_create(&ext_cost_fun_jac[i], {{ dims.np }});
}
ext_cost_fun_jac_hess = (external_function_param_casadi *) malloc(sizeof(external_function_param_casadi)*N);
for (int i = 0; i < N; i++)
{
// residual function
ext_cost_fun_jac_hess[i].casadi_fun = &{{ model.name }}_cost_ext_cost_fun_jac_hess;
ext_cost_fun_jac_hess[i].casadi_n_in = &{{ model.name }}_cost_ext_cost_fun_jac_hess_n_in;
ext_cost_fun_jac_hess[i].casadi_n_out = &{{ model.name }}_cost_ext_cost_fun_jac_hess_n_out;
ext_cost_fun_jac_hess[i].casadi_sparsity_in = &{{ model.name }}_cost_ext_cost_fun_jac_hess_sparsity_in;
ext_cost_fun_jac_hess[i].casadi_sparsity_out = &{{ model.name }}_cost_ext_cost_fun_jac_hess_sparsity_out;
ext_cost_fun_jac_hess[i].casadi_work = &{{ model.name }}_cost_ext_cost_fun_jac_hess_work;
external_function_param_casadi_create(&ext_cost_fun_jac_hess[i], {{ dims.np }});
}
{%- endif %}
{%- if cost.cost_type_e == "NONLINEAR_LS" %}
// nonlinear least square function
cost_y_e_fun.casadi_fun = &{{ model.name }}_cost_y_e_fun;
cost_y_e_fun.casadi_n_in = &{{ model.name }}_cost_y_e_fun_n_in;
cost_y_e_fun.casadi_n_out = &{{ model.name }}_cost_y_e_fun_n_out;
cost_y_e_fun.casadi_sparsity_in = &{{ model.name }}_cost_y_e_fun_sparsity_in;
cost_y_e_fun.casadi_sparsity_out = &{{ model.name }}_cost_y_e_fun_sparsity_out;
cost_y_e_fun.casadi_work = &{{ model.name }}_cost_y_e_fun_work;
external_function_param_casadi_create(&cost_y_e_fun, {{ dims.np }});
cost_y_e_fun_jac_ut_xt.casadi_fun = &{{ model.name }}_cost_y_e_fun_jac_ut_xt;
cost_y_e_fun_jac_ut_xt.casadi_n_in = &{{ model.name }}_cost_y_e_fun_jac_ut_xt_n_in;
cost_y_e_fun_jac_ut_xt.casadi_n_out = &{{ model.name }}_cost_y_e_fun_jac_ut_xt_n_out;
cost_y_e_fun_jac_ut_xt.casadi_sparsity_in = &{{ model.name }}_cost_y_e_fun_jac_ut_xt_sparsity_in;
cost_y_e_fun_jac_ut_xt.casadi_sparsity_out = &{{ model.name }}_cost_y_e_fun_jac_ut_xt_sparsity_out;
cost_y_e_fun_jac_ut_xt.casadi_work = &{{ model.name }}_cost_y_e_fun_jac_ut_xt_work;
external_function_param_casadi_create(&cost_y_e_fun_jac_ut_xt, {{ dims.np }});
cost_y_e_hess.casadi_fun = &{{ model.name }}_cost_y_e_hess;
cost_y_e_hess.casadi_n_in = &{{ model.name }}_cost_y_e_hess_n_in;
cost_y_e_hess.casadi_n_out = &{{ model.name }}_cost_y_e_hess_n_out;
cost_y_e_hess.casadi_sparsity_in = &{{ model.name }}_cost_y_e_hess_sparsity_in;
cost_y_e_hess.casadi_sparsity_out = &{{ model.name }}_cost_y_e_hess_sparsity_out;
cost_y_e_hess.casadi_work = &{{ model.name }}_cost_y_e_hess_work;
external_function_param_casadi_create(&cost_y_e_hess, {{ dims.np }});
{%- elif cost.cost_type_e == "EXTERNAL" %}
// external cost
ext_cost_e_fun.casadi_fun = &{{ model.name }}_cost_ext_cost_e_fun;
ext_cost_e_fun.casadi_n_in = &{{ model.name }}_cost_ext_cost_e_fun_n_in;
ext_cost_e_fun.casadi_n_out = &{{ model.name }}_cost_ext_cost_e_fun_n_out;
ext_cost_e_fun.casadi_sparsity_in = &{{ model.name }}_cost_ext_cost_e_fun_sparsity_in;
ext_cost_e_fun.casadi_sparsity_out = &{{ model.name }}_cost_ext_cost_e_fun_sparsity_out;
ext_cost_e_fun.casadi_work = &{{ model.name }}_cost_ext_cost_e_fun_work;
external_function_param_casadi_create(&ext_cost_e_fun, {{ dims.np }});
// external cost
ext_cost_e_fun_jac.casadi_fun = &{{ model.name }}_cost_ext_cost_e_fun_jac;
ext_cost_e_fun_jac.casadi_n_in = &{{ model.name }}_cost_ext_cost_e_fun_jac_n_in;
ext_cost_e_fun_jac.casadi_n_out = &{{ model.name }}_cost_ext_cost_e_fun_jac_n_out;
ext_cost_e_fun_jac.casadi_sparsity_in = &{{ model.name }}_cost_ext_cost_e_fun_jac_sparsity_in;
ext_cost_e_fun_jac.casadi_sparsity_out = &{{ model.name }}_cost_ext_cost_e_fun_jac_sparsity_out;
ext_cost_e_fun_jac.casadi_work = &{{ model.name }}_cost_ext_cost_e_fun_jac_work;
external_function_param_casadi_create(&ext_cost_e_fun_jac, {{ dims.np }});
// external cost
ext_cost_e_fun_jac_hess.casadi_fun = &{{ model.name }}_cost_ext_cost_e_fun_jac_hess;
ext_cost_e_fun_jac_hess.casadi_n_in = &{{ model.name }}_cost_ext_cost_e_fun_jac_hess_n_in;
ext_cost_e_fun_jac_hess.casadi_n_out = &{{ model.name }}_cost_ext_cost_e_fun_jac_hess_n_out;
ext_cost_e_fun_jac_hess.casadi_sparsity_in = &{{ model.name }}_cost_ext_cost_e_fun_jac_hess_sparsity_in;
ext_cost_e_fun_jac_hess.casadi_sparsity_out = &{{ model.name }}_cost_ext_cost_e_fun_jac_hess_sparsity_out;
ext_cost_e_fun_jac_hess.casadi_work = &{{ model.name }}_cost_ext_cost_e_fun_jac_hess_work;
external_function_param_casadi_create(&ext_cost_e_fun_jac_hess, {{ dims.np }});
{%- endif %}
/************************************************
* nlp_in
************************************************/
nlp_in = ocp_nlp_in_create(nlp_config, nlp_dims);
double time_steps[N];
{%- for j in range(end=dims.N) %}
time_steps[{{ j }}] = {{ solver_options.time_steps[j] }};
{%- endfor %}
for (int i = 0; i < N; i++)
{
ocp_nlp_in_set(nlp_config, nlp_dims, nlp_in, i, "Ts", &time_steps[i]);
ocp_nlp_cost_model_set(nlp_config, nlp_dims, nlp_in, i, "scaling", &time_steps[i]);
}
/**** Dynamics ****/
for (int i = 0; i < N; i++)
{
{%- if solver_options.integrator_type == "ERK" %}
ocp_nlp_dynamics_model_set(nlp_config, nlp_dims, nlp_in, i, "expl_vde_forw", &forw_vde_casadi[i]);
ocp_nlp_dynamics_model_set(nlp_config, nlp_dims, nlp_in, i, "expl_ode_fun", &expl_ode_fun[i]);
{%- if solver_options.hessian_approx == "EXACT" %}
ocp_nlp_dynamics_model_set(nlp_config, nlp_dims, nlp_in, i, "expl_ode_hess", &hess_vde_casadi[i]);
{%- endif %}
{% elif solver_options.integrator_type == "IRK" %}
ocp_nlp_dynamics_model_set(nlp_config, nlp_dims, nlp_in, i, "impl_dae_fun", &impl_dae_fun[i]);
ocp_nlp_dynamics_model_set(nlp_config, nlp_dims, nlp_in, i,
"impl_dae_fun_jac_x_xdot_z", &impl_dae_fun_jac_x_xdot_z[i]);
ocp_nlp_dynamics_model_set(nlp_config, nlp_dims, nlp_in, i,
"impl_dae_jac_x_xdot_u", &impl_dae_jac_x_xdot_u_z[i]);
{%- if solver_options.hessian_approx == "EXACT" %}
ocp_nlp_dynamics_model_set(nlp_config, nlp_dims, nlp_in, i, "impl_dae_hess", &impl_dae_hess[i]);
{%- endif %}
{% elif solver_options.integrator_type == "GNSF" %}
ocp_nlp_dynamics_model_set(nlp_config, nlp_dims, nlp_in, i, "phi_fun", &gnsf_phi_fun[i]);
ocp_nlp_dynamics_model_set(nlp_config, nlp_dims, nlp_in, i, "phi_fun_jac_y", &gnsf_phi_fun_jac_y[i]);
ocp_nlp_dynamics_model_set(nlp_config, nlp_dims, nlp_in, i, "phi_jac_y_uhat", &gnsf_phi_jac_y_uhat[i]);
ocp_nlp_dynamics_model_set(nlp_config, nlp_dims, nlp_in, i, "f_lo_jac_x1_x1dot_u_z",
&gnsf_f_lo_jac_x1_x1dot_u_z[i]);
ocp_nlp_dynamics_model_set(nlp_config, nlp_dims, nlp_in, i, "gnsf_get_matrices_fun",
&gnsf_get_matrices_fun[i]);
{% elif solver_options.integrator_type == "DISCRETE" %}
ocp_nlp_dynamics_model_set(nlp_config, nlp_dims, nlp_in, i, "disc_dyn_fun", &discr_dyn_phi_fun[i]);
ocp_nlp_dynamics_model_set(nlp_config, nlp_dims, nlp_in, i, "disc_dyn_fun_jac", &discr_dyn_phi_fun_jac_ut_xt[i]);
{%- if solver_options.hessian_approx == "EXACT" %}
ocp_nlp_dynamics_model_set(nlp_config, nlp_dims, nlp_in, i, "disc_dyn_fun_jac_hess", &discr_dyn_phi_fun_jac_ut_xt_hess[i]);
{%- endif %}
{%- endif %}
}
/**** Cost ****/
{%- if cost.cost_type == "NONLINEAR_LS" or cost.cost_type == "LINEAR_LS" %}
{% if dims.ny > 0 %}
double W[NY*NY];
{% for j in range(end=dims.ny) %}
{%- for k in range(end=dims.ny) %}
W[{{ j }}+(NY) * {{ k }}] = {{ cost.W[j][k] }};
{%- endfor %}
{%- endfor %}
double yref[NY];
{% for j in range(end=dims.ny) %}
yref[{{ j }}] = {{ cost.yref[j] }};
{%- endfor %}
for (int i = 0; i < N; i++)
{
ocp_nlp_cost_model_set(nlp_config, nlp_dims, nlp_in, i, "W", W);
ocp_nlp_cost_model_set(nlp_config, nlp_dims, nlp_in, i, "yref", yref);
}
{% endif %}
{% endif %}
{%- if cost.cost_type == "LINEAR_LS" %}
double Vx[NY*NX];
{% for j in range(end=dims.ny) %}
{%- for k in range(end=dims.nx) %}
Vx[{{ j }}+(NY) * {{ k }}] = {{ cost.Vx[j][k] }};
{%- endfor %}
{%- endfor %}
for (int i = 0; i < N; i++)
{
ocp_nlp_cost_model_set(nlp_config, nlp_dims, nlp_in, i, "Vx", Vx);
}
{% if dims.ny > 0 and dims.nu > 0 %}
double Vu[NY*NU];
{% for j in range(end=dims.ny) %}
{%- for k in range(end=dims.nu) %}
Vu[{{ j }}+(NY) * {{ k }}] = {{ cost.Vu[j][k] }};
{%- endfor %}
{%- endfor %}
for (int i = 0; i < N; i++)
{
ocp_nlp_cost_model_set(nlp_config, nlp_dims, nlp_in, i, "Vu", Vu);
}
{% endif %}
{% if dims.ny > 0 and dims.nz > 0 %}
double Vz[NY*NZ];
{% for j in range(end=dims.ny) %}
{%- for k in range(end=dims.nz) %}
Vz[{{ j }}+(NY) * {{ k }}] = {{ cost.Vz[j][k] }};
{%- endfor %}
{%- endfor %}
for (int i = 0; i < N; i++)
{
ocp_nlp_cost_model_set(nlp_config, nlp_dims, nlp_in, i, "Vz", Vz);
}
{%- endif %}
{%- endif %}{# LINEAR LS #}
{%- if cost.cost_type == "NONLINEAR_LS" %}
for (int i = 0; i < N; i++)
{
ocp_nlp_cost_model_set(nlp_config, nlp_dims, nlp_in, i, "nls_y_fun", &cost_y_fun[i]);
ocp_nlp_cost_model_set(nlp_config, nlp_dims, nlp_in, i, "nls_y_fun_jac", &cost_y_fun_jac_ut_xt[i]);
ocp_nlp_cost_model_set(nlp_config, nlp_dims, nlp_in, i, "nls_y_hess", &cost_y_hess[i]);
}
{%- elif cost.cost_type == "EXTERNAL" %}
for (int i = 0; i < N; i++)
{
ocp_nlp_cost_model_set(nlp_config, nlp_dims, nlp_in, i, "ext_cost_fun", &ext_cost_fun[i]);
ocp_nlp_cost_model_set(nlp_config, nlp_dims, nlp_in, i, "ext_cost_fun_jac", &ext_cost_fun_jac[i]);
ocp_nlp_cost_model_set(nlp_config, nlp_dims, nlp_in, i, "ext_cost_fun_jac_hess", &ext_cost_fun_jac_hess[i]);
}
{%- endif %}
{% if dims.ns > 0 %}
double Zl[NS];
double Zu[NS];
double zl[NS];
double zu[NS];
{% for j in range(end=dims.ns) %}
Zl[{{ j }}] = {{ cost.Zl[j] }};
{%- endfor %}
{% for j in range(end=dims.ns) %}
Zu[{{ j }}] = {{ cost.Zu[j] }};
{%- endfor %}
{% for j in range(end=dims.ns) %}
zl[{{ j }}] = {{ cost.zl[j] }};
{%- endfor %}
{% for j in range(end=dims.ns) %}
zu[{{ j }}] = {{ cost.zu[j] }};
{%- endfor %}
for (int i = 0; i < N; i++)
{
ocp_nlp_cost_model_set(nlp_config, nlp_dims, nlp_in, i, "Zl", Zl);
ocp_nlp_cost_model_set(nlp_config, nlp_dims, nlp_in, i, "Zu", Zu);
ocp_nlp_cost_model_set(nlp_config, nlp_dims, nlp_in, i, "zl", zl);
ocp_nlp_cost_model_set(nlp_config, nlp_dims, nlp_in, i, "zu", zu);
}
{% endif %}
// terminal cost
{% if cost.cost_type_e == "LINEAR_LS" or cost.cost_type_e == "NONLINEAR_LS" %}
{% if dims.ny_e > 0 %}
double yref_e[NYN];
{% for j in range(end=dims.ny_e) %}
yref_e[{{ j }}] = {{ cost.yref_e[j] }};
{%- endfor %}
ocp_nlp_cost_model_set(nlp_config, nlp_dims, nlp_in, N, "yref", yref_e);
double W_e[NYN*NYN];
{% for j in range(end=dims.ny_e) %}
{%- for k in range(end=dims.ny_e) %}
W_e[{{ j }}+(NYN) * {{ k }}] = {{ cost.W_e[j][k] }};
{%- endfor %}
{%- endfor %}
ocp_nlp_cost_model_set(nlp_config, nlp_dims, nlp_in, N, "W", W_e);
{%- if cost.cost_type_e == "LINEAR_LS" %}
double Vx_e[NYN*NX];
{% for j in range(end=dims.ny_e) %}
{%- for k in range(end=dims.nx) %}
Vx_e[{{ j }}+(NYN) * {{ k }}] = {{ cost.Vx_e[j][k] }};
{%- endfor %}
{%- endfor %}
ocp_nlp_cost_model_set(nlp_config, nlp_dims, nlp_in, N, "Vx", Vx_e);
{%- endif %}
{%- if cost.cost_type_e == "NONLINEAR_LS" %}
ocp_nlp_cost_model_set(nlp_config, nlp_dims, nlp_in, N, "nls_y_fun", &cost_y_e_fun);
ocp_nlp_cost_model_set(nlp_config, nlp_dims, nlp_in, N, "nls_y_fun_jac", &cost_y_e_fun_jac_ut_xt);
ocp_nlp_cost_model_set(nlp_config, nlp_dims, nlp_in, N, "nls_y_hess", &cost_y_e_hess);
{%- endif %}
{%- endif %}{# ny_e > 0 #}
{%- elif cost.cost_type_e == "EXTERNAL" %}
ocp_nlp_cost_model_set(nlp_config, nlp_dims, nlp_in, N, "ext_cost_fun", &ext_cost_e_fun);
ocp_nlp_cost_model_set(nlp_config, nlp_dims, nlp_in, N, "ext_cost_fun_jac", &ext_cost_e_fun_jac);
ocp_nlp_cost_model_set(nlp_config, nlp_dims, nlp_in, N, "ext_cost_fun_jac_hess", &ext_cost_e_fun_jac_hess);
{%- endif %}
{% if dims.ns_e > 0 %}
double Zl_e[NSN];
double Zu_e[NSN];
double zl_e[NSN];
double zu_e[NSN];
{% for j in range(end=dims.ns_e) %}
Zl_e[{{ j }}] = {{ cost.Zl_e[j] }};
{%- endfor %}
{% for j in range(end=dims.ns_e) %}
Zu_e[{{ j }}] = {{ cost.Zu_e[j] }};
{%- endfor %}
{% for j in range(end=dims.ns_e) %}
zl_e[{{ j }}] = {{ cost.zl_e[j] }};
{%- endfor %}
{% for j in range(end=dims.ns_e) %}
zu_e[{{ j }}] = {{ cost.zu_e[j] }};
{%- endfor %}
ocp_nlp_cost_model_set(nlp_config, nlp_dims, nlp_in, N, "Zl", Zl_e);
ocp_nlp_cost_model_set(nlp_config, nlp_dims, nlp_in, N, "Zu", Zu_e);
ocp_nlp_cost_model_set(nlp_config, nlp_dims, nlp_in, N, "zl", zl_e);
ocp_nlp_cost_model_set(nlp_config, nlp_dims, nlp_in, N, "zu", zu_e);
{%- endif %}
/**** Constraints ****/
// bounds for initial stage
{% if dims.nbx_0 > 0 %}
// x0
int idxbx0[{{ dims.nbx_0 }}];
{% for i in range(end=dims.nbx_0) %}
idxbx0[{{ i }}] = {{ constraints.idxbx_0[i] }};
{%- endfor %}
double lbx0[{{ dims.nbx_0 }}];
double ubx0[{{ dims.nbx_0 }}];
{% for i in range(end=dims.nbx_0) %}
lbx0[{{ i }}] = {{ constraints.lbx_0[i] }};
ubx0[{{ i }}] = {{ constraints.ubx_0[i] }};
{%- endfor %}
ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, 0, "idxbx", idxbx0);
ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, 0, "lbx", lbx0);
ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, 0, "ubx", ubx0);
{% endif %}
{% if dims.nbxe_0 > 0 %}
// idxbxe_0
int idxbxe_0[{{ dims.nbxe_0 }}];
{% for i in range(end=dims.nbxe_0) %}
idxbxe_0[{{ i }}] = {{ constraints.idxbxe_0[i] }};
{%- endfor %}
ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, 0, "idxbxe", idxbxe_0);
{% endif %}
/* constraints that are the same for initial and intermediate */
{%- if dims.nsbx > 0 %}
{# TODO: introduce nsbx0 & REMOVE SETTING lsbx, usbx for stage 0!!! move this block down!! #}
// ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, 0, "idxsbx", idxsbx);
// ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, 0, "lsbx", lsbx);
// ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, 0, "usbx", usbx);
// soft bounds on x
int idxsbx[NSBX];
{% for i in range(end=dims.nsbx) %}
idxsbx[{{ i }}] = {{ constraints.idxsbx[i] }};
{%- endfor %}
double lsbx[NSBX];
double usbx[NSBX];
{% for i in range(end=dims.nsbx) %}
lsbx[{{ i }}] = {{ constraints.lsbx[i] }};
usbx[{{ i }}] = {{ constraints.usbx[i] }};
{%- endfor %}
for (int i = 1; i < N; i++)
{
ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, i, "idxsbx", idxsbx);
ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, i, "lsbx", lsbx);
ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, i, "usbx", usbx);
}
{%- endif %}
{% if dims.nbu > 0 %}
// u
int idxbu[NBU];
{% for i in range(end=dims.nbu) %}
idxbu[{{ i }}] = {{ constraints.idxbu[i] }};
{%- endfor %}
double lbu[NBU];
double ubu[NBU];
{% for i in range(end=dims.nbu) %}
lbu[{{ i }}] = {{ constraints.lbu[i] }};
ubu[{{ i }}] = {{ constraints.ubu[i] }};
{%- endfor %}
for (int i = 0; i < N; i++)
{
ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, i, "idxbu", idxbu);
ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, i, "lbu", lbu);
ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, i, "ubu", ubu);
}
{% endif %}
{% if dims.nsbu > 0 %}
// set up soft bounds for u
int idxsbu[NSBU];
{% for i in range(end=dims.nsbu) %}
idxsbu[{{ i }}] = {{ constraints.idxsbu[i] }};
{%- endfor %}
double lsbu[NSBU];
double usbu[NSBU];
{% for i in range(end=dims.nsbu) %}
lsbu[{{ i }}] = {{ constraints.lsbu[i] }};
usbu[{{ i }}] = {{ constraints.usbu[i] }};
{%- endfor %}
for (int i = 0; i < N; i++)
{
ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, i, "idxsbu", idxsbu);
ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, i, "lsbu", lsbu);
ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, i, "usbu", usbu);
}
{% endif %}
{% if dims.nsg > 0 %}
// set up soft bounds for general linear constraints
int idxsg[NSG];
{% for i in range(end=dims.nsg) %}
idxsg[{{ i }}] = {{ constraints.idxsg[i] }};
{%- endfor %}
double lsg[NSG];
double usg[NSG];
{% for i in range(end=dims.nsg) %}
lsg[{{ i }}] = {{ constraints.lsg[i] }};
usg[{{ i }}] = {{ constraints.usg[i] }};
{%- endfor %}
for (int i = 0; i < N; i++)
{
ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, i, "idxsg", idxsg);
ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, i, "lsg", lsg);
ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, i, "usg", usg);
}
{% endif %}
{% if dims.nsh > 0 %}
// set up soft bounds for nonlinear constraints
int idxsh[NSH];
{% for i in range(end=dims.nsh) %}
idxsh[{{ i }}] = {{ constraints.idxsh[i] }};
{%- endfor %}
double lsh[NSH];
double ush[NSH];
{% for i in range(end=dims.nsh) %}
lsh[{{ i }}] = {{ constraints.lsh[i] }};
ush[{{ i }}] = {{ constraints.ush[i] }};
{%- endfor %}
for (int i = 0; i < N; i++)
{
ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, i, "idxsh", idxsh);
ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, i, "lsh", lsh);
ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, i, "ush", ush);
}
{% endif %}
{% if dims.nsphi > 0 %}
// set up soft bounds for convex-over-nonlinear constraints
int idxsphi[NSPHI];
{% for i in range(end=dims.nsphi) %}
idxsphi[{{ i }}] = {{ constraints.idxsphi[i] }};
{%- endfor %}
double lsphi[NSPHI];
double usphi[NSPHI];
{% for i in range(end=dims.nsphi) %}
lsphi[{{ i }}] = {{ constraints.lsphi[i] }};
usphi[{{ i }}] = {{ constraints.usphi[i] }};
{%- endfor %}
for (int i = 0; i < N; i++)
{
ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, i, "idxsphi", idxsphi);
ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, i, "lsphi", lsphi);
ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, i, "usphi", usphi);
}
{% endif %}
{% if dims.nbx > 0 %}
// x
int idxbx[NBX];
{% for i in range(end=dims.nbx) %}
idxbx[{{ i }}] = {{ constraints.idxbx[i] }};
{%- endfor %}
double lbx[NBX];
double ubx[NBX];
{% for i in range(end=dims.nbx) %}
lbx[{{ i }}] = {{ constraints.lbx[i] }};
ubx[{{ i }}] = {{ constraints.ubx[i] }};
{%- endfor %}
for (int i = 1; i < N; i++)
{
ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, i, "idxbx", idxbx);
ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, i, "lbx", lbx);
ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, i, "ubx", ubx);
}
{% endif %}
{% if dims.ng > 0 %}
// set up general constraints for stage 0 to N-1
double D[NG*NU];
double C[NG*NX];
double lg[NG];
double ug[NG];
{% for j in range(end=dims.ng) %}
{%- for k in range(end=dims.nu) %}
D[{{ j }}+NG * {{ k }}] = {{ constraints.D[j][k] }};
{%- endfor %}
{%- endfor %}
{% for j in range(end=dims.ng) %}
{%- for k in range(end=dims.nx) %}
C[{{ j }}+NG * {{ k }}] = {{ constraints.C[j][k] }};
{%- endfor %}
{%- endfor %}
{% for i in range(end=dims.ng) %}
lg[{{ i }}] = {{ constraints.lg[i] }};
{%- endfor %}
{% for i in range(end=dims.ng) %}
ug[{{ i }}] = {{ constraints.ug[i] }};
{%- endfor %}
for (int i = 0; i < N; i++)
{
ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, i, "D", D);
ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, i, "C", C);
ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, i, "lg", lg);
ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, i, "ug", ug);
}
{% endif %}
{% if dims.nh > 0 %}
// set up nonlinear constraints for stage 0 to N-1
double lh[NH];
double uh[NH];
{% for i in range(end=dims.nh) %}
lh[{{ i }}] = {{ constraints.lh[i] }};
{%- endfor %}
{% for i in range(end=dims.nh) %}
uh[{{ i }}] = {{ constraints.uh[i] }};
{%- endfor %}
for (int i = 0; i < N; i++)
{
// nonlinear constraints for stages 0 to N-1
ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, i, "nl_constr_h_fun_jac",
&nl_constr_h_fun_jac[i]);
ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, i, "nl_constr_h_fun",
&nl_constr_h_fun[i]);
{% if solver_options.hessian_approx == "EXACT" %}
ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, i,
"nl_constr_h_fun_jac_hess", &nl_constr_h_fun_jac_hess[i]);
{% endif %}
ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, i, "lh", lh);
ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, i, "uh", uh);
}
{% endif %}
{% if dims.nphi > 0 and constraints.constr_type == "BGP" %}
// set up convex-over-nonlinear constraints for stage 0 to N-1
double lphi[NPHI];
double uphi[NPHI];
{% for i in range(end=dims.nphi) %}
lphi[{{ i }}] = {{ constraints.lphi[i] }};
{%- endfor %}
{% for i in range(end=dims.nphi) %}
uphi[{{ i }}] = {{ constraints.uphi[i] }};
{%- endfor %}
for (int i = 0; i < N; i++)
{
ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, i,
"nl_constr_phi_o_r_fun_phi_jac_ux_z_phi_hess_r_jac_ux", &phi_constraint[i]);
ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, i, "lphi", lphi);
ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, i, "uphi", uphi);
}
{% endif %}
/* terminal constraints */
{% if dims.nbx_e > 0 %}
// set up bounds for last stage
// x
int idxbx_e[NBXN];
{% for i in range(end=dims.nbx_e) %}
idxbx_e[{{ i }}] = {{ constraints.idxbx_e[i] }};
{%- endfor %}
double lbx_e[NBXN];
double ubx_e[NBXN];
{% for i in range(end=dims.nbx_e) %}
lbx_e[{{ i }}] = {{ constraints.lbx_e[i] }};
ubx_e[{{ i }}] = {{ constraints.ubx_e[i] }};
{%- endfor %}
ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, N, "idxbx", idxbx_e);
ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, N, "lbx", lbx_e);
ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, N, "ubx", ubx_e);
{%- endif %}
{% if dims.nsg_e > 0 %}
// set up soft bounds for general linear constraints
int idxsg_e[NSGN];
{% for i in range(end=dims.nsg_e) %}
idxsg_e[{{ i }}] = {{ constraints.idxsg_e[i] }};
{%- endfor %}
double lsg_e[NSGN];
double usg_e[NSGN];
{% for i in range(end=dims.nsg_e) %}
lsg_e[{{ i }}] = {{ constraints.lsg_e[i] }};
usg_e[{{ i }}] = {{ constraints.usg_e[i] }};
{%- endfor %}
ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, N, "idxsg", idxsg_e);
ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, N, "lsg", lsg_e);
ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, N, "usg", usg_e);
{%- endif %}
{% if dims.nsh_e > 0 %}
// set up soft bounds for nonlinear constraints
int idxsh_e[NSHN];
{% for i in range(end=dims.nsh_e) %}
idxsh_e[{{ i }}] = {{ constraints.idxsh_e[i] }};
{%- endfor %}
double lsh_e[NSHN];
double ush_e[NSHN];
{% for i in range(end=dims.nsh_e) %}
lsh_e[{{ i }}] = {{ constraints.lsh_e[i] }};
ush_e[{{ i }}] = {{ constraints.ush_e[i] }};
{%- endfor %}
ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, N, "idxsh", idxsh_e);
ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, N, "lsh", lsh_e);
ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, N, "ush", ush_e);
{%- endif %}
{% if dims.nsphi_e > 0 %}
// set up soft bounds for convex-over-nonlinear constraints
int idxsphi_e[NSPHIN];
{% for i in range(end=dims.nsphi_e) %}
idxsphi_e[{{ i }}] = {{ constraints.idxsphi_e[i] }};
{%- endfor %}
double lsphi_e[NSPHIN];
double usphi_e[NSPHIN];
{% for i in range(end=dims.nsphi_e) %}
lsphi_e[{{ i }}] = {{ constraints.lsphi_e[i] }};
usphi_e[{{ i }}] = {{ constraints.usphi_e[i] }};
{%- endfor %}
ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, N, "idxsphi", idxsphi_e);
ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, N, "lsphi", lsphi_e);
ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, N, "usphi", usphi_e);
{%- endif %}
{% if dims.nsbx_e > 0 %}
// soft bounds on x
int idxsbx_e[NSBXN];
{% for i in range(end=dims.nsbx_e) %}
idxsbx_e[{{ i }}] = {{ constraints.idxsbx_e[i] }};
{%- endfor %}
double lsbx_e[NSBXN];
double usbx_e[NSBXN];
{% for i in range(end=dims.nsbx_e) %}
lsbx_e[{{ i }}] = {{ constraints.lsbx_e[i] }};
usbx_e[{{ i }}] = {{ constraints.usbx_e[i] }};
{%- endfor %}
ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, N, "idxsbx", idxsbx_e);
ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, N, "lsbx", lsbx_e);
ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, N, "usbx", usbx_e);
{% endif %}
{% if dims.ng_e > 0 %}
// set up general constraints for last stage
double C_e[NGN*NX];
double lg_e[NGN];
double ug_e[NGN];
{% for j in range(end=dims.ng) %}
{%- for k in range(end=dims.nx) %}
C_e[{{ j }}+NG * {{ k }}] = {{ constraints.C_e[j][k] }};
{%- endfor %}
{%- endfor %}
{% for i in range(end=dims.ng_e) %}
lg_e[{{ i }}] = {{ constraints.lg_e[i] }};
ug_e[{{ i }}] = {{ constraints.ug_e[i] }};
{%- endfor %}
ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, N, "C", C_e);
ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, N, "lg", lg_e);
ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, N, "ug", ug_e);
{%- endif %}
{% if dims.nh_e > 0 %}
// set up nonlinear constraints for last stage
double lh_e[NHN];
double uh_e[NHN];
{% for i in range(end=dims.nh_e) %}
lh_e[{{ i }}] = {{ constraints.lh_e[i] }};
{%- endfor %}
{% for i in range(end=dims.nh_e) %}
uh_e[{{ i }}] = {{ constraints.uh_e[i] }};
{%- endfor %}
ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, N, "nl_constr_h_fun_jac", &nl_constr_h_e_fun_jac);
ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, N, "nl_constr_h_fun", &nl_constr_h_e_fun);
{% if solver_options.hessian_approx == "EXACT" %}
ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, N, "nl_constr_h_fun_jac_hess", &nl_constr_h_e_fun_jac_hess);
{% endif %}
ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, N, "lh", lh_e);
ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, N, "uh", uh_e);
{%- endif %}
{% if dims.nphi_e > 0 and constraints.constr_type_e == "BGP" %}
// set up convex-over-nonlinear constraints for last stage
double lphi_e[NPHIN];
double uphi_e[NPHIN];
{% for i in range(end=dims.nphi_e) %}
lphi_e[{{ i }}] = {{ constraints.lphi_e[i] }};
{%- endfor %}
{% for i in range(end=dims.nphi_e) %}
uphi_e[{{ i }}] = {{ constraints.uphi_e[i] }};
{%- endfor %}
ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, N, "lphi", lphi_e);
ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, N, "uphi", uphi_e);
ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, N,
"nl_constr_phi_o_r_fun_phi_jac_ux_z_phi_hess_r_jac_ux", &phi_e_constraint);
{% endif %}
/************************************************
* opts
************************************************/
nlp_opts = ocp_nlp_solver_opts_create(nlp_config, nlp_dims);
{% if solver_options.hessian_approx == "EXACT" %}
bool nlp_solver_exact_hessian = true;
// TODO: this if should not be needed! however, calling the setter with false leads to weird behavior. Investigate!
if (nlp_solver_exact_hessian)
{
ocp_nlp_solver_opts_set(nlp_config, nlp_opts, "exact_hess", &nlp_solver_exact_hessian);
}
int exact_hess_dyn = {{ solver_options.exact_hess_dyn }};
ocp_nlp_solver_opts_set(nlp_config, nlp_opts, "exact_hess_dyn", &exact_hess_dyn);
int exact_hess_cost = {{ solver_options.exact_hess_cost }};
ocp_nlp_solver_opts_set(nlp_config, nlp_opts, "exact_hess_cost", &exact_hess_cost);
int exact_hess_constr = {{ solver_options.exact_hess_constr }};
ocp_nlp_solver_opts_set(nlp_config, nlp_opts, "exact_hess_constr", &exact_hess_constr);
{%- endif -%}
{%- if dims.nz > 0 %}
// TODO: these options are lower level -> should be encapsulated! maybe through hessian approx option.
bool output_z_val = true;
bool sens_algebraic_val = true;
for (int i = 0; i < N; i++)
ocp_nlp_solver_opts_set_at_stage(nlp_config, nlp_opts, i, "dynamics_output_z", &output_z_val);
for (int i = 0; i < N; i++)
ocp_nlp_solver_opts_set_at_stage(nlp_config, nlp_opts, i, "dynamics_sens_algebraic", &sens_algebraic_val);
{%- endif %}
{%- if solver_options.integrator_type != "DISCRETE" %}
int num_steps_val = {{ solver_options.sim_method_num_steps }};
for (int i = 0; i < N; i++)
ocp_nlp_solver_opts_set_at_stage(nlp_config, nlp_opts, i, "dynamics_num_steps", &num_steps_val);
int ns_val = {{ solver_options.sim_method_num_stages }};
for (int i = 0; i < N; i++)
ocp_nlp_solver_opts_set_at_stage(nlp_config, nlp_opts, i, "dynamics_num_stages", &ns_val);
int newton_iter_val = {{ solver_options.sim_method_newton_iter }};
for (int i = 0; i < N; i++)
ocp_nlp_solver_opts_set_at_stage(nlp_config, nlp_opts, i, "dynamics_newton_iter", &newton_iter_val);
bool tmp_bool = {{ solver_options.sim_method_jac_reuse }};
for (int i = 0; i < N; i++)
ocp_nlp_solver_opts_set_at_stage(nlp_config, nlp_opts, i, "dynamics_jac_reuse", &tmp_bool);
{%- endif %}
double nlp_solver_step_length = {{ solver_options.nlp_solver_step_length }};
ocp_nlp_solver_opts_set(nlp_config, nlp_opts, "step_length", &nlp_solver_step_length);
{%- if solver_options.nlp_solver_warm_start_first_qp %}
int nlp_solver_warm_start_first_qp = {{ solver_options.nlp_solver_warm_start_first_qp }};
ocp_nlp_solver_opts_set(nlp_config, nlp_opts, "warm_start_first_qp", &nlp_solver_warm_start_first_qp);
{%- endif %}
double levenberg_marquardt = {{ solver_options.levenberg_marquardt }};
ocp_nlp_solver_opts_set(nlp_config, nlp_opts, "levenberg_marquardt", &levenberg_marquardt);
/* options QP solver */
{%- if solver_options.qp_solver is starting_with("PARTIAL_CONDENSING") %}
int qp_solver_cond_N;
{%- if solver_options.qp_solver_cond_N %}
qp_solver_cond_N = {{ solver_options.qp_solver_cond_N }};
{% else %}
// NOTE: there is no condensing happening here!
qp_solver_cond_N = N;
{%- endif %}
ocp_nlp_solver_opts_set(nlp_config, nlp_opts, "qp_cond_N", &qp_solver_cond_N);
{% endif %}
int qp_solver_iter_max = {{ solver_options.qp_solver_iter_max }};
ocp_nlp_solver_opts_set(nlp_config, nlp_opts, "qp_iter_max", &qp_solver_iter_max);
{%- if solver_options.qp_solver_tol_stat %}
double qp_solver_tol_stat = {{ solver_options.qp_solver_tol_stat }};
ocp_nlp_solver_opts_set(nlp_config, nlp_opts, "qp_tol_stat", &qp_solver_tol_stat);
{%- endif -%}
{%- if solver_options.qp_solver_tol_eq %}
double qp_solver_tol_eq = {{ solver_options.qp_solver_tol_eq }};
ocp_nlp_solver_opts_set(nlp_config, nlp_opts, "qp_tol_eq", &qp_solver_tol_eq);
{%- endif -%}
{%- if solver_options.qp_solver_tol_ineq %}
double qp_solver_tol_ineq = {{ solver_options.qp_solver_tol_ineq }};
ocp_nlp_solver_opts_set(nlp_config, nlp_opts, "qp_tol_ineq", &qp_solver_tol_ineq);
{%- endif -%}
{%- if solver_options.qp_solver_tol_comp %}
double qp_solver_tol_comp = {{ solver_options.qp_solver_tol_comp }};
ocp_nlp_solver_opts_set(nlp_config, nlp_opts, "qp_tol_comp", &qp_solver_tol_comp);
{%- endif -%}
{%- if solver_options.qp_solver_warm_start %}
int qp_solver_warm_start = {{ solver_options.qp_solver_warm_start }};
ocp_nlp_solver_opts_set(nlp_config, nlp_opts, "qp_warm_start", &qp_solver_warm_start);
{%- endif -%}
{% if solver_options.nlp_solver_type == "SQP" %}
// set SQP specific options
double nlp_solver_tol_stat = {{ solver_options.nlp_solver_tol_stat }};
ocp_nlp_solver_opts_set(nlp_config, nlp_opts, "tol_stat", &nlp_solver_tol_stat);
double nlp_solver_tol_eq = {{ solver_options.nlp_solver_tol_eq }};
ocp_nlp_solver_opts_set(nlp_config, nlp_opts, "tol_eq", &nlp_solver_tol_eq);
double nlp_solver_tol_ineq = {{ solver_options.nlp_solver_tol_ineq }};
ocp_nlp_solver_opts_set(nlp_config, nlp_opts, "tol_ineq", &nlp_solver_tol_ineq);
double nlp_solver_tol_comp = {{ solver_options.nlp_solver_tol_comp }};
ocp_nlp_solver_opts_set(nlp_config, nlp_opts, "tol_comp", &nlp_solver_tol_comp);
int nlp_solver_max_iter = {{ solver_options.nlp_solver_max_iter }};
ocp_nlp_solver_opts_set(nlp_config, nlp_opts, "max_iter", &nlp_solver_max_iter);
int initialize_t_slacks = {{ solver_options.initialize_t_slacks }};
ocp_nlp_solver_opts_set(nlp_config, nlp_opts, "initialize_t_slacks", &initialize_t_slacks);
{%- endif %}
int print_level = {{ solver_options.print_level }};
ocp_nlp_solver_opts_set(nlp_config, nlp_opts, "print_level", &print_level);
int ext_cost_num_hess = {{ solver_options.ext_cost_num_hess }};
{%- if cost.cost_type == "EXTERNAL" %}
for (int i = 0; i < N; i++)
{
ocp_nlp_solver_opts_set_at_stage(nlp_config, nlp_opts, i, "cost_numerical_hessian", &ext_cost_num_hess);
}
{%- endif %}
{%- if cost.cost_type_e == "EXTERNAL" %}
ocp_nlp_solver_opts_set_at_stage(nlp_config, nlp_opts, N, "cost_numerical_hessian", &ext_cost_num_hess);
{%- endif %}
/* out */
nlp_out = ocp_nlp_out_create(nlp_config, nlp_dims);
// initialize primal solution
double x0[{{ dims.nx }}];
{% if dims.nbx_0 == dims.nx %}
// initialize with x0
{% for item in constraints.lbx_0 %}
x0[{{ loop.index0 }}] = {{ item }};
{%- endfor %}
{% else %}
// initialize with zeros
{% for i in range(end=dims.nx) %}
x0[{{ i }}] = 0.0;
{%- endfor %}
{%- endif %}
double u0[NU];
{% for i in range(end=dims.nu) %}
u0[{{ i }}] = 0.0;
{%- endfor %}
for (int i = 0; i < N; i++)
{
// x0
ocp_nlp_out_set(nlp_config, nlp_dims, nlp_out, i, "x", x0);
// u0
ocp_nlp_out_set(nlp_config, nlp_dims, nlp_out, i, "u", u0);
}
ocp_nlp_out_set(nlp_config, nlp_dims, nlp_out, N, "x", x0);
nlp_solver = ocp_nlp_solver_create(nlp_config, nlp_dims, nlp_opts);
{% if dims.np > 0 %}
// initialize parameters to nominal value
double p[{{ dims.np }}];
{% for i in range(end=dims.np) %}
p[{{ i }}] = {{ parameter_values[i] }};
{%- endfor %}
{% if solver_options.integrator_type == "IRK" %}
for (int ii = 0; ii < N; ii++)
{
impl_dae_fun[ii].set_param(impl_dae_fun+ii, p);
impl_dae_fun_jac_x_xdot_z[ii].set_param(impl_dae_fun_jac_x_xdot_z+ii, p);
impl_dae_jac_x_xdot_u_z[ii].set_param(impl_dae_jac_x_xdot_u_z+ii, p);
{%- if solver_options.hessian_approx == "EXACT" %}
impl_dae_hess[ii].set_param(impl_dae_hess+ii, p);
{%- endif %}
}
{% elif solver_options.integrator_type == "ERK" %}
for (int ii = 0; ii < N; ii++)
{
forw_vde_casadi[ii].set_param(forw_vde_casadi+ii, p);
expl_ode_fun[ii].set_param(expl_ode_fun+ii, p);
}
{% elif solver_options.integrator_type == "GNSF" %}
for (int ii = 0; ii < N; ii++)
{
gnsf_phi_fun[ii].set_param(gnsf_phi_fun+ii, p);
gnsf_phi_fun_jac_y[ii].set_param(gnsf_phi_fun_jac_y+ii, p);
gnsf_phi_jac_y_uhat[ii].set_param(gnsf_phi_jac_y_uhat+ii, p);
gnsf_f_lo_jac_x1_x1dot_u_z[ii].set_param(gnsf_f_lo_jac_x1_x1dot_u_z+ii, p);
}
{% elif solver_options.integrator_type == "DISCRETE" %}
for (int ii = 0; ii < N; ii++)
{
discr_dyn_phi_fun[ii].set_param(discr_dyn_phi_fun+ii, p);
discr_dyn_phi_fun_jac_ut_xt[ii].set_param(discr_dyn_phi_fun_jac_ut_xt+ii, p);
{%- if solver_options.hessian_approx == "EXACT" %}
discr_dyn_phi_fun_jac_ut_xt_hess[ii].set_param(discr_dyn_phi_fun_jac_ut_xt_hess+ii, p);
{% endif %}
}
{% endif %}
// cost
{%- if cost.cost_type == "NONLINEAR_LS" %}
for (int ii = 0; ii < N; ii++)
{
cost_y_fun[ii].set_param(cost_y_fun+ii, p);
cost_y_fun_jac_ut_xt[ii].set_param(cost_y_fun_jac_ut_xt+ii, p);
cost_y_hess[ii].set_param(cost_y_hess+ii, p);
}
{%- elif cost.cost_type == "EXTERNAL" %}
for (int ii = 0; ii < N; ii++)
{
ext_cost_fun[ii].set_param(ext_cost_fun+ii, p);
ext_cost_fun_jac[ii].set_param(ext_cost_fun_jac+ii, p);
ext_cost_fun_jac_hess[ii].set_param(ext_cost_fun_jac_hess+ii, p);
}
{%- endif %}
{%- if cost.cost_type_e == "NONLINEAR_LS" %}
cost_y_e_fun.set_param(&cost_y_e_fun, p);
cost_y_e_fun_jac_ut_xt.set_param(&cost_y_e_fun_jac_ut_xt, p);
cost_y_e_hess.set_param(&cost_y_e_hess, p);
{%- elif cost.cost_type_e == "EXTERNAL" %}
ext_cost_e_fun.set_param(&ext_cost_e_fun, p);
ext_cost_e_fun_jac.set_param(&ext_cost_e_fun_jac, p);
ext_cost_e_fun_jac_hess.set_param(&ext_cost_e_fun_jac_hess, p);
{%- endif %}
// constraints
{%- if constraints.constr_type == "BGP" %}
for (int ii = 0; ii < N; ii++)
{
phi_constraint[ii].set_param(phi_constraint+ii, p);
}
{%- elif dims.nh > 0 and constraints.constr_type == "BGH" %}
for (int ii = 0; ii < N; ii++)
{
nl_constr_h_fun_jac[ii].set_param(nl_constr_h_fun_jac+ii, p);
nl_constr_h_fun[ii].set_param(nl_constr_h_fun+ii, p);
}
{%- if solver_options.hessian_approx == "EXACT" %}
for (int ii = 0; ii < N; ii++)
{
nl_constr_h_fun_jac_hess[ii].set_param(nl_constr_h_fun_jac_hess+ii, p);
}
{%- endif %}
{%- endif %}
{%- if constraints.constr_type_e == "BGP" %}
phi_e_constraint.set_param(&phi_e_constraint, p);
{%- elif constraints.constr_type_e == "BGH" and dims.nh_e > 0 %}
nl_constr_h_e_fun_jac.set_param(&nl_constr_h_e_fun_jac, p);
nl_constr_h_e_fun.set_param(&nl_constr_h_e_fun, p);
{%- if solver_options.hessian_approx == "EXACT" %}
nl_constr_h_e_fun_jac_hess.set_param(&nl_constr_h_e_fun_jac_hess, p);
{%- endif %}
{%- endif %}
{%- endif %}{# if dims.np #}
status = ocp_nlp_precompute(nlp_solver, nlp_in, nlp_out);
if (status != ACADOS_SUCCESS)
{
printf("\nocp_precompute failed!\n\n");
exit(1);
}
return status;
}
int acados_update_params(int stage, double *p, int np)
{
int solver_status = 0;
int casadi_np = {{ dims.np }};
if (casadi_np != np) {
printf("acados_update_params: trying to set %i parameters for external functions."
" External function has %i parameters. Exiting.\n", np, casadi_np);
exit(1);
}
{%- if dims.np > 0 %}
if (stage < {{ dims.N }})
{
{%- if solver_options.integrator_type == "IRK" %}
impl_dae_fun[stage].set_param(impl_dae_fun+stage, p);
impl_dae_fun_jac_x_xdot_z[stage].set_param(impl_dae_fun_jac_x_xdot_z+stage, p);
impl_dae_jac_x_xdot_u_z[stage].set_param(impl_dae_jac_x_xdot_u_z+stage, p);
{%- if solver_options.hessian_approx == "EXACT" %}
impl_dae_hess[stage].set_param(impl_dae_hess+stage, p);
{%- endif %}
{% elif solver_options.integrator_type == "ERK" %}
forw_vde_casadi[stage].set_param(forw_vde_casadi+stage, p);
expl_ode_fun[stage].set_param(expl_ode_fun+stage, p);
{%- if solver_options.hessian_approx == "EXACT" %}
hess_vde_casadi[stage].set_param(hess_vde_casadi+stage, p);
{%- endif %}
{% elif solver_options.integrator_type == "GNSF" %}
gnsf_phi_fun[stage].set_param(gnsf_phi_fun+stage, p);
gnsf_phi_fun_jac_y[stage].set_param(gnsf_phi_fun_jac_y+stage, p);
gnsf_phi_jac_y_uhat[stage].set_param(gnsf_phi_jac_y_uhat+stage, p);
gnsf_f_lo_jac_x1_x1dot_u_z[stage].set_param(gnsf_f_lo_jac_x1_x1dot_u_z+stage, p);
{% elif solver_options.integrator_type == "DISCRETE" %}
discr_dyn_phi_fun[stage].set_param(discr_dyn_phi_fun+stage, p);
discr_dyn_phi_fun_jac_ut_xt[stage].set_param(discr_dyn_phi_fun_jac_ut_xt+stage, p);
{%- if solver_options.hessian_approx == "EXACT" %}
discr_dyn_phi_fun_jac_ut_xt_hess[stage].set_param(discr_dyn_phi_fun_jac_ut_xt_hess+stage, p);
{% endif %}
{%- endif %}{# integrator_type #}
// constraints
{% if constraints.constr_type == "BGP" %}
phi_constraint[stage].set_param(phi_constraint+stage, p);
{% elif constraints.constr_type == "BGH" and dims.nh > 0 %}
nl_constr_h_fun_jac[stage].set_param(nl_constr_h_fun_jac+stage, p);
nl_constr_h_fun[stage].set_param(nl_constr_h_fun+stage, p);
{%- if solver_options.hessian_approx == "EXACT" %}
nl_constr_h_fun_jac_hess[stage].set_param(nl_constr_h_fun_jac_hess+stage, p);
{%- endif %}
{%- endif %}
// cost
{%- if cost.cost_type == "NONLINEAR_LS" %}
cost_y_fun[stage].set_param(cost_y_fun+stage, p);
cost_y_fun_jac_ut_xt[stage].set_param(cost_y_fun_jac_ut_xt+stage, p);
cost_y_hess[stage].set_param(cost_y_hess+stage, p);
{%- elif cost.cost_type == "EXTERNAL" %}
ext_cost_fun[stage].set_param(ext_cost_fun+stage, p);
ext_cost_fun_jac[stage].set_param(ext_cost_fun_jac+stage, p);
ext_cost_fun_jac_hess[stage].set_param(ext_cost_fun_jac_hess+stage, p);
{%- endif %}
}
else // stage == N
{
// terminal shooting node has no dynamics
// cost
{%- if cost.cost_type_e == "NONLINEAR_LS" %}
cost_y_e_fun.set_param(&cost_y_e_fun, p);
cost_y_e_fun_jac_ut_xt.set_param(&cost_y_e_fun_jac_ut_xt, p);
cost_y_e_hess.set_param(&cost_y_e_hess, p);
{%- elif cost.cost_type_e == "EXTERNAL" %}
ext_cost_e_fun.set_param(&ext_cost_e_fun, p);
ext_cost_e_fun_jac.set_param(&ext_cost_e_fun_jac, p);
{%- if solver_options.hessian_approx == "EXACT" %}
ext_cost_e_fun_jac_hess.set_param(&ext_cost_e_fun_jac_hess, p);
{%- endif %}
{% endif %}
// constraints
{% if constraints.constr_type_e == "BGP" %}
phi_e_constraint.set_param(&phi_e_constraint, p);
{% elif constraints.constr_type_e == "BGH" and dims.nh_e > 0 %}
nl_constr_h_e_fun_jac.set_param(&nl_constr_h_e_fun_jac, p);
nl_constr_h_e_fun.set_param(&nl_constr_h_e_fun, p);
{%- if solver_options.hessian_approx == "EXACT" %}
nl_constr_h_e_fun_jac_hess[stage].set_param(nl_constr_h_e_fun_jac_hess+stage, p);
{%- endif %}
{% endif %}
}
{% endif %}{# if dims.np #}
return solver_status;
}
int acados_solve()
{
// solve NLP
int solver_status = ocp_nlp_solve(nlp_solver, nlp_in, nlp_out);
return solver_status;
}
int acados_free()
{
// free memory
ocp_nlp_solver_opts_destroy(nlp_opts);
ocp_nlp_in_destroy(nlp_in);
ocp_nlp_out_destroy(nlp_out);
ocp_nlp_solver_destroy(nlp_solver);
ocp_nlp_dims_destroy(nlp_dims);
ocp_nlp_config_destroy(nlp_config);
ocp_nlp_plan_destroy(nlp_solver_plan);
/* free external function */
// dynamics
{%- if solver_options.integrator_type == "IRK" %}
for (int i = 0; i < {{ dims.N }}; i++)
{
external_function_param_casadi_free(&impl_dae_fun[i]);
external_function_param_casadi_free(&impl_dae_fun_jac_x_xdot_z[i]);
external_function_param_casadi_free(&impl_dae_jac_x_xdot_u_z[i]);
{%- if solver_options.hessian_approx == "EXACT" %}
external_function_param_casadi_free(&impl_dae_hess[i]);
{%- endif %}
}
free(impl_dae_fun);
free(impl_dae_fun_jac_x_xdot_z);
free(impl_dae_jac_x_xdot_u_z);
{%- if solver_options.hessian_approx == "EXACT" %}
free(impl_dae_hess);
{%- endif %}
{%- elif solver_options.integrator_type == "ERK" %}
for (int i = 0; i < {{ dims.N }}; i++)
{
external_function_param_casadi_free(&forw_vde_casadi[i]);
external_function_param_casadi_free(&expl_ode_fun[i]);
{%- if solver_options.hessian_approx == "EXACT" %}
external_function_param_casadi_free(&hess_vde_casadi[i]);
{%- endif %}
}
free(forw_vde_casadi);
free(expl_ode_fun);
{%- if solver_options.hessian_approx == "EXACT" %}
free(hess_vde_casadi);
{%- endif %}
{%- elif solver_options.integrator_type == "GNSF" %}
for (int i = 0; i < {{ dims.N }}; i++)
{
external_function_param_casadi_free(&gnsf_phi_fun[i]);
external_function_param_casadi_free(&gnsf_phi_fun_jac_y[i]);
external_function_param_casadi_free(&gnsf_phi_jac_y_uhat[i]);
external_function_param_casadi_free(&gnsf_f_lo_jac_x1_x1dot_u_z[i]);
external_function_param_casadi_free(&gnsf_get_matrices_fun[i]);
}
free(gnsf_phi_fun);
free(gnsf_phi_fun_jac_y);
free(gnsf_phi_jac_y_uhat);
free(gnsf_f_lo_jac_x1_x1dot_u_z);
free(gnsf_get_matrices_fun);
{%- elif solver_options.integrator_type == "DISCRETE" %}
for (int i = 0; i < {{ dims.N }}; i++)
{
external_function_param_casadi_free(&discr_dyn_phi_fun[i]);
external_function_param_casadi_free(&discr_dyn_phi_fun_jac_ut_xt[i]);
{%- if solver_options.hessian_approx == "EXACT" %}
external_function_param_casadi_free(&discr_dyn_phi_fun_jac_ut_xt_hess[i]);
{%- endif %}
}
free(discr_dyn_phi_fun);
free(discr_dyn_phi_fun_jac_ut_xt);
{%- if solver_options.hessian_approx == "EXACT" %}
free(discr_dyn_phi_fun_jac_ut_xt_hess);
{%- endif %}
{%- endif %}
// cost
{%- if cost.cost_type == "NONLINEAR_LS" %}
for (int i = 0; i < {{ dims.N }}; i++)
{
external_function_param_casadi_free(&cost_y_fun[i]);
external_function_param_casadi_free(&cost_y_fun_jac_ut_xt[i]);
external_function_param_casadi_free(&cost_y_hess[i]);
}
free(cost_y_fun);
free(cost_y_fun_jac_ut_xt);
free(cost_y_hess);
{%- elif cost.cost_type == "EXTERNAL" %}
for (int i = 0; i < {{ dims.N }}; i++)
{
external_function_param_casadi_free(&ext_cost_fun[i]);
external_function_param_casadi_free(&ext_cost_fun_jac[i]);
external_function_param_casadi_free(&ext_cost_fun_jac_hess[i]);
}
free(ext_cost_fun);
free(ext_cost_fun_jac);
free(ext_cost_fun_jac_hess);
{%- endif %}
{%- if cost.cost_type_e == "NONLINEAR_LS" %}
external_function_param_casadi_free(&cost_y_e_fun);
external_function_param_casadi_free(&cost_y_e_fun_jac_ut_xt);
external_function_param_casadi_free(&cost_y_e_hess);
{%- elif cost.cost_type_e == "EXTERNAL" %}
external_function_param_casadi_free(&ext_cost_e_fun);
external_function_param_casadi_free(&ext_cost_e_fun_jac);
external_function_param_casadi_free(&ext_cost_e_fun_jac_hess);
{%- endif %}
// constraints
{%- if constraints.constr_type == "BGH" and dims.nh > 0 %}
for (int i = 0; i < {{ dims.N }}; i++)
{
external_function_param_casadi_free(&nl_constr_h_fun_jac[i]);
external_function_param_casadi_free(&nl_constr_h_fun[i]);
}
{%- if solver_options.hessian_approx == "EXACT" %}
for (int i = 0; i < {{ dims.N }}; i++)
{
external_function_param_casadi_free(&nl_constr_h_fun_jac_hess[i]);
}
{%- endif %}
free(nl_constr_h_fun_jac);
free(nl_constr_h_fun);
{%- if solver_options.hessian_approx == "EXACT" %}
free(nl_constr_h_fun_jac_hess);
{%- endif %}
{%- elif constraints.constr_type == "BGP" and dims.nphi > 0 %}
for (int i = 0; i < {{ dims.N }}; i++)
{
external_function_param_casadi_free(&phi_constraint[i]);
}
free(phi_constraint);
{%- endif %}
{%- if constraints.constr_type_e == "BGH" and dims.nh_e > 0 %}
external_function_param_casadi_free(&nl_constr_h_e_fun_jac);
external_function_param_casadi_free(&nl_constr_h_e_fun);
{%- if solver_options.hessian_approx == "EXACT" %}
external_function_param_casadi_free(&nl_constr_h_e_fun_jac_hess);
{%- endif %}
{%- elif constraints.constr_type_e == "BGP" and dims.nphi_e > 0 %}
external_function_param_casadi_free(&phi_e_constraint);
{%- endif %}
return 0;
}
ocp_nlp_in * acados_get_nlp_in() { return nlp_in; }
ocp_nlp_out * acados_get_nlp_out() { return nlp_out; }
ocp_nlp_solver * acados_get_nlp_solver() { return nlp_solver; }
ocp_nlp_config * acados_get_nlp_config() { return nlp_config; }
void * acados_get_nlp_opts() { return nlp_opts; }
ocp_nlp_dims * acados_get_nlp_dims() { return nlp_dims; }
ocp_nlp_plan * acados_get_nlp_plan() { return nlp_solver_plan; }
void acados_print_stats()
{
int sqp_iter, stat_m, stat_n, tmp_int;
ocp_nlp_get(nlp_config, nlp_solver, "sqp_iter", &sqp_iter);
ocp_nlp_get(nlp_config, nlp_solver, "stat_n", &stat_n);
ocp_nlp_get(nlp_config, nlp_solver, "stat_m", &stat_m);
{% set stat_n_max = 10 %}
double stat[{{ solver_options.nlp_solver_max_iter * stat_n_max }}];
ocp_nlp_get(nlp_config, nlp_solver, "statistics", stat);
int nrow = sqp_iter+1 < stat_m ? sqp_iter+1 : stat_m;
printf("iter\tres_stat\tres_eq\t\tres_ineq\tres_comp\tqp_stat\tqp_iter\n");
for (int i = 0; i < nrow; i++)
{
for (int j = 0; j < stat_n + 1; j++)
{
if (j == 0 || j > 4)
{
tmp_int = (int) stat[i + j * nrow];
printf("%d\t", tmp_int);
}
else
{
printf("%e\t", stat[i + j * nrow]);
}
}
printf("\n");
}
}
|
849153.c | /****************************************************************************
* configs/stm32l4discovery/src/stm32_pm.c
*
* Copyright (C) 2012 Gregory Nutt. All rights reserved.
* Authors: Gregory Nutt <[email protected]>
* Diego Sanchez <[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 <nuttx/power/pm.h>
#include <arch/board/board.h>
#include "stm32_waste.h"
#ifdef CONFIG_PM
/****************************************************************************
* Pre-processor Definitions
****************************************************************************/
#define FLASH_KEY1 0x45670123
#define FLASH_KEY2 0xCDEF89AB
#define OPT_KEY1 0x08192A3B
#define OPT_KEY2 0x4C5D6E7F
/****************************************************************************
* Private Data
****************************************************************************/
/****************************************************************************
* Public Data
****************************************************************************/
/****************************************************************************
* Private Functions
****************************************************************************/
#ifdef CONFIG_STM32_IWDG
static void stm32_wait_if_busy(void)
{
while (getreg32(STM32_FLASH_SR) & FLASH_SR_BSY)
{
up_waste();
}
}
static void stm32_options_unlock(void)
{
stm32_wait_if_busy();
if (getreg32(STM32_FLASH_CR) & FLASH_CR_LOCK)
{
/* Flash unlock sequence */
putreg32(FLASH_KEY1, STM32_FLASH_KEYR);
putreg32(FLASH_KEY2, STM32_FLASH_KEYR);
}
if (getreg32(STM32_FLASH_CR) & FLASH_CR_OPTLOCK)
{
/* Options unlock sequence */
putreg32(OPT_KEY1, STM32_FLASH_OPTKEYR);
putreg32(OPT_KEY2, STM32_FLASH_OPTKEYR);
}
}
static void stm32_options_start(void)
{
modifyreg32(STM32_FLASH_CR, 0, FLASH_CR_OPTSTRT);
stm32_wait_if_busy();
/* When the BSY bit is cleared, the options are saved to flash, but not yet
* applied to the system. Set OBL_LAUNCH to generate a reset and reload
* of the option bytes.
*/
modifyreg32(STM32_FLASH_CR, 0, FLASH_CR_OBL_LAUNCH);
}
static void stm32_options_lock(void)
{
modifyreg32(STM32_FLASH_CR, 0, FLASH_CR_OPTLOCK | FLASH_CR_LOCK);
}
static void stm32_freeze_iwdg_stop(void)
{
uint32_t regval;
regval = getreg32(STM32_FLASH_OPTR);
if (regval & (FLASH_OPTR_IWDG_STOP | FLASH_OPTR_IWDG_STDBY))
{
stm32_options_unlock();
regval &= ~(FLASH_OPTR_IWDG_STOP | FLASH_OPTR_IWDG_STDBY);
putreg32(regval, STM32_FLASH_OPTR);
stm32_options_start();
stm32_options_lock();
}
}
#endif
/****************************************************************************
* Public Functions
****************************************************************************/
/****************************************************************************
* Name: stm32_pminitialize
*
* Description:
* This function is called by MCU-specific logic at power-on reset in
* order to provide one-time initialization the power management subystem.
* This function must be called *very* early in the initialization sequence
* *before* any other device drivers are initialized (since they may
* attempt to register with the power management subsystem).
*
* Input parameters:
* None.
*
* Returned value:
* None.
*
****************************************************************************/
void up_pminitialize(void)
{
uint32_t regval;
/* Enable USART2 in Stop Mode */
regval = getreg32(STM32_USART2_CR1);
regval |= USART_CR1_UESM;
putreg32(regval, STM32_USART2_CR1);
#ifdef CONFIG_STM32_IWDG
/* IWDG must be frozen in Stop Mode */
stm32_freeze_iwdg_stop();
#endif
/* Then initialize the NuttX power management subsystem proper */
pm_initialize();
}
#endif /* CONFIG_PM */
|
987326.c | /*************************************************************************************************/
/*!
* \file mesh_security_main.c
*
* \brief Security main implementation.
*
* Copyright (c) 2010-2018 Arm Ltd.
*
* Copyright (c) 2019 Packetcraft, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
/*************************************************************************************************/
#include <string.h>
#include "wsf_types.h"
#include "wsf_msg.h"
#include "wsf_os.h"
#include "wsf_assert.h"
#include "mesh_defs.h"
#include "mesh_network_beacon_defs.h"
#include "mesh_security_defs.h"
#include "mesh_types.h"
#include "mesh_error_codes.h"
#include "mesh_utils.h"
#include "mesh_api.h"
#include "mesh_main.h"
#include "mesh_seq_manager.h"
#include "mesh_local_config_types.h"
#include "mesh_local_config.h"
#include "mesh_security_toolbox.h"
#include "mesh_security.h"
#include "mesh_security_main.h"
#include "mesh_security_deriv.h"
#include "mesh_security_crypto.h"
#if ((defined MESH_ENABLE_TEST) && (MESH_ENABLE_TEST==1))
#include "mesh_test_api.h"
#endif
/**************************************************************************************************
Local Variables
**************************************************************************************************/
/*! Storage for security material. */
meshSecMaterial_t secMatLocals =
{
.appKeyInfoListSize = 0,
.netKeyInfoListSize = 0,
.friendMatListSize = 0,
};
/*! Security control block */
meshSecCb_t meshSecCb = { NULL };
/*! Request sources for crypto operations. */
meshSecCryptoRequests_t secCryptoReq;
/*! Request sources for key derivation operations. */
meshSecKeyDerivRequests_t secKeyDerivReq;
/**************************************************************************************************
Local Functions
**************************************************************************************************/
/*************************************************************************************************/
/*!
* \brief Computes memory requirements based on configured number of Application Keys.
*
* \param[in] numAppKeys Maximum number of Application Keys.
*
* \return Required memory in bytes for Application Keys material and information.
*/
/*************************************************************************************************/
static inline uint32_t meshSecGetAppKeyMatRequiredMemory(uint16_t numAppKeys)
{
return MESH_UTILS_ALIGN(numAppKeys * sizeof(meshSecAppKeyInfo_t));
}
/*************************************************************************************************/
/*!
* \brief Computes memory requirements based on configured number of Network Keys.
*
* \param[in] numNetKeys Maximum number of Network Keys.
*
* \return Required memory in bytes for Network Keys material and information.
*/
/*************************************************************************************************/
static inline uint32_t meshSecGetNetKeyMatRequiredMemory(uint16_t numNetKeys)
{
return MESH_UTILS_ALIGN(numNetKeys * sizeof(meshSecNetKeyInfo_t));
}
/*************************************************************************************************/
/*!
* \brief Computes memory requirements based on configured number of friendships.
*
* \param[in] numFriendships Maximum number of friendships.
*
* \return Required memory in bytes for friendship credentials material and information.
*/
/*************************************************************************************************/
static inline uint32_t meshSecGetFriendMatRequiredMemory(uint16_t numFriendships)
{
return MESH_UTILS_ALIGN(numFriendships * sizeof(meshSecFriendMat_t));
}
/**************************************************************************************************
Global Functions
**************************************************************************************************/
/*************************************************************************************************/
/*!
* \brief Computes the required memory to be provided based on the global configuration.
*
* \return Required memory in bytes or ::MESH_MEM_REQ_INVALID_CFG in case of error.
*/
/*************************************************************************************************/
uint32_t MeshSecGetRequiredMemory(void)
{
uint32_t reqMem = MESH_MEM_REQ_INVALID_CFG;
if (pMeshConfig->pMemoryConfig->netKeyListSize == 0)
{
return reqMem;
}
/* Get memory required by AppKey, NetKey and Friendship material. */
uint32_t totalMem =
meshSecGetAppKeyMatRequiredMemory(pMeshConfig->pMemoryConfig->appKeyListSize) +
meshSecGetNetKeyMatRequiredMemory(pMeshConfig->pMemoryConfig->netKeyListSize) +
meshSecGetFriendMatRequiredMemory(pMeshConfig->pMemoryConfig->maxNumFriendships);
return totalMem;
}
/*************************************************************************************************/
/*!
* \brief Initializes the Security module and allocates configuration memory.
*
* \return None.
*/
/*************************************************************************************************/
void MeshSecInit(void)
{
uint32_t memReq = 0;
uint16_t idx;
memReq = MeshSecGetRequiredMemory();
/* Set number of AppKeys. */
secMatLocals.appKeyInfoListSize = pMeshConfig->pMemoryConfig->appKeyListSize;
/* Set number of NetKeys. */
secMatLocals.netKeyInfoListSize = pMeshConfig->pMemoryConfig->netKeyListSize;
/* Set number of friendships. */
secMatLocals.friendMatListSize = pMeshConfig->pMemoryConfig->maxNumFriendships;
/* Set start of memory for AppKey material. */
secMatLocals.pAppKeyInfoArray = (meshSecAppKeyInfo_t *)(meshCb.pMemBuff);
/* Forward pointer. */
meshCb.pMemBuff += meshSecGetAppKeyMatRequiredMemory(secMatLocals.appKeyInfoListSize);
/* Set start of memory for the NetKey material. */
secMatLocals.pNetKeyInfoArray = (meshSecNetKeyInfo_t *)(meshCb.pMemBuff);
/* Forward pointer. */
meshCb.pMemBuff += meshSecGetNetKeyMatRequiredMemory(secMatLocals.netKeyInfoListSize);
/* Set start of memory for the Friendship material. */
secMatLocals.pFriendMatArray = (meshSecFriendMat_t *)(meshCb.pMemBuff);
/* Forward pointer. */
meshCb.pMemBuff += meshSecGetFriendMatRequiredMemory(secMatLocals.friendMatListSize);
/* Subtract used memory. */
meshCb.memBuffSize -= memReq;
/* Reset Network Key derivation material. */
memset(secMatLocals.pNetKeyInfoArray, 0, secMatLocals.netKeyInfoListSize * sizeof(meshSecNetKeyInfo_t));
/* Reset Application Key derivation material. */
memset(secMatLocals.pAppKeyInfoArray, 0, secMatLocals.appKeyInfoListSize * sizeof(meshSecAppKeyInfo_t));
/* Reset Friendship material. */
for (idx = 0; idx < secMatLocals.friendMatListSize; idx++)
{
secMatLocals.pFriendMatArray[idx].netKeyInfoIndex = MESH_SEC_INVALID_ENTRY_INDEX;
secMatLocals.pFriendMatArray[idx].hasUpdtMaterial = FALSE;
}
/* Reset key derivation requests. */
secKeyDerivReq.friendMatDerivReq.friendListIdx = MESH_SEC_INVALID_ENTRY_INDEX;
secKeyDerivReq.netKeyDerivReq.netKeyListIdx = MESH_SEC_INVALID_ENTRY_INDEX;
secKeyDerivReq.appKeyDerivReq.appKeyListIdx = MESH_SEC_INVALID_ENTRY_INDEX;
/* Reset Upper Transport security requests. */
secCryptoReq.utrEncReq.cback = NULL;
secCryptoReq.utrDecReq.cback = NULL;
/* Reset Network security requests. */
secCryptoReq.nwkEncObfReq[MESH_SEC_NWK_ENC_SRC_NWK].cback = NULL;
secCryptoReq.nwkEncObfReq[MESH_SEC_NWK_ENC_SRC_PROXY].cback = NULL;
secCryptoReq.nwkEncObfReq[MESH_SEC_NWK_ENC_SRC_FRIEND].cback = NULL;
secCryptoReq.nwkDeobfDecReq[MESH_SEC_NWK_DEC_SRC_NWK_FRIEND].cback = NULL;
secCryptoReq.nwkDeobfDecReq[MESH_SEC_NWK_DEC_SRC_PROXY].cback = NULL;
/* Reset Beacon Authentication requests. */
secCryptoReq.beaconAuthReq.cback = NULL;
secCryptoReq.beaconCompAuthReq.cback = NULL;
}
/*************************************************************************************************/
/*!
* \brief Registers the reader function for remote Device Keys.
*
* \param[in] devKeyReader Function (callback) called when Security needs to read a remote node's
* Device Key.
*
* \return None.
*
* \note This function should be called only when an instance of Configuration Client is
* present on the local node.
*/
/*************************************************************************************************/
void MeshSecRegisterRemoteDevKeyReader(meshSecRemoteDevKeyReadCback_t devKeyReader)
{
/* Store the callback provided by the caller for reading remote Device Keys. */
meshSecCb.secRemoteDevKeyReader = devKeyReader;
}
#if ((defined MESH_ENABLE_TEST) && (MESH_ENABLE_TEST==1))
/*************************************************************************************************/
/*!
* \brief Alters the NetKey list size in Security for Mesh Test.
*
* \param[in] listSize NetKey list size.
*
* \return None.
*/
/*************************************************************************************************/
void MeshTestSecAlterNetKeyListSize(uint16_t listSize)
{
secMatLocals.netKeyInfoListSize = listSize;
}
#endif
|
694484.c | double foo(double S) {
for (int J = 0; J < 10; ++J) {
for (int I = 0; I < 10; ++I)
S *= I * J;
for (int I = 0; I < 10; ++I)
S += I;
}
return S;
}
//CHECK: Printing analysis 'Dependency Analysis (Metadata)' for function 'foo':
//CHECK: loop at depth 1 reduction_5.c:2:3
//CHECK: private:
//CHECK: <I:3[3:5], 4> | <I:5[5:5], 4>
//CHECK: induction:
//CHECK: <J:2[2:3], 4>:[Int,0,10,1]
//CHECK: reduction:
//CHECK: <S:1, 8>
//CHECK: lock:
//CHECK: <J:2[2:3], 4>
//CHECK: header access:
//CHECK: <J:2[2:3], 4>
//CHECK: explicit access:
//CHECK: <I:3[3:5], 4> | <I:5[5:5], 4> | <J:2[2:3], 4> | <S:1, 8>
//CHECK: explicit access (separate):
//CHECK: <I:3[3:5], 4> <I:5[5:5], 4> <J:2[2:3], 4> <S:1, 8>
//CHECK: lock (separate):
//CHECK: <J:2[2:3], 4>
//CHECK: direct access (separate):
//CHECK: <I:3[3:5], 4> <I:5[5:5], 4> <J:2[2:3], 4> <S:1, 8>
//CHECK: loop at depth 2 reduction_5.c:5:5
//CHECK: induction:
//CHECK: <I:5[5:5], 4>:[Int,0,10,1]
//CHECK: reduction:
//CHECK: <S:1, 8>:add
//CHECK: lock:
//CHECK: <I:5[5:5], 4>
//CHECK: header access:
//CHECK: <I:5[5:5], 4>
//CHECK: explicit access:
//CHECK: <I:5[5:5], 4> | <S:1, 8>
//CHECK: explicit access (separate):
//CHECK: <I:5[5:5], 4> <S:1, 8>
//CHECK: lock (separate):
//CHECK: <I:5[5:5], 4>
//CHECK: direct access (separate):
//CHECK: <I:5[5:5], 4> <S:1, 8>
//CHECK: loop at depth 2 reduction_5.c:3:5
//CHECK: induction:
//CHECK: <I:3[3:5], 4>:[Int,0,10,1]
//CHECK: reduction:
//CHECK: <S:1, 8>:mult
//CHECK: read only:
//CHECK: <J:2[2:3], 4>
//CHECK: lock:
//CHECK: <I:3[3:5], 4>
//CHECK: header access:
//CHECK: <I:3[3:5], 4>
//CHECK: explicit access:
//CHECK: <I:3[3:5], 4> | <J:2[2:3], 4> | <S:1, 8>
//CHECK: explicit access (separate):
//CHECK: <I:3[3:5], 4> <J:2[2:3], 4> <S:1, 8>
//CHECK: lock (separate):
//CHECK: <I:3[3:5], 4>
//CHECK: direct access (separate):
//CHECK: <I:3[3:5], 4> <J:2[2:3], 4> <S:1, 8>
|
435018.c | /**
* Interfaccia privata dalla libreria list.h
*
* @author Giorgio Paoletti
* [email protected]
* matricola: 105056
*
* @version Seconda Consegna 25/09/2020
*
*/
#include <stdio.h>
#include <stdlib.h>
#include "list.h"
void add_node(unsigned char*, byte_list_t **, byte_list_t **, int);
byte_list_t* create_node(unsigned char*, int);
/**
* Struct che permette la memorizzazione dei byte di un file senza conoscerne la lunghezza
* La struct corrisponde a un nodo composto da un blocco di byte (massimo 256), un size del blocco e il puntatore al nodo successivo
*/
typedef struct byte_list_t {
unsigned char *byte_block;
byte_list_t *next;
int size;
} byte_list_t;
/**
* Alloca la struct prendendo i byte dal file passato per argomento
* Il file viene aperto tramite il flag 'rb' che permette la lettura in formato binario
* vengono letti blocchi di 256 byte alla volta e ne viene costruito il nodo corrispondente
* che poi viene collocato nella lista
*
* @param in path del file da cui prendere i byte
* @return puntatore alla struct
*/
byte_list_t* list_create(char* in){
byte_list_t *first = NULL;
byte_list_t *last = NULL;
FILE* fin = fopen(in, "rb");
if(fin == NULL) perror("Errore: ");
unsigned char buffer[256];
int size=0;
do{
size = fread(buffer, sizeof(unsigned char), 256, fin);
if(size != 0) add_node(buffer, &first, &last, size);
}while(size != 0);
fclose(fin);
return first;
}
/**
* Aggiunge un nodo alla lista
*/
void add_node(unsigned char* content, byte_list_t **first, byte_list_t **last, int size){
byte_list_t *new_node = create_node(content, size);
if(*first == NULL){
*first = new_node;
} else {
(*last)->next = new_node;
}
*last = new_node;
}
/**
* Crea un nodo dato il blocco di byte e la corrispondente size
*/
byte_list_t* create_node(unsigned char* block_content, int size){
byte_list_t *new_node = malloc(sizeof(struct byte_list_t));
new_node->byte_block = malloc(sizeof(unsigned char) * size);
for(int i=0; i<= size; i++){
new_node->byte_block[i] = block_content[i];
}
new_node->size = size;
new_node->next = NULL;
return new_node;
}
/**
* Dealloca la struct passata per argomento
* @param list puntatore alla struct da deallocare
*/
void list_destroy(byte_list_t **list){
while((*list)->next){
free((*list)->byte_block);
*list = (*list)->next;
}
free((*list)->byte_block);
free(*list);
}
/**
* Restituisce il numero di byte che compongono il file
* @param list lista da cui ricavare la size
* @return il numero di byte che compongono il file
*/
int list_get_size(byte_list_t *list){
int size = 0;
while(list->next){
size+= list->size;
list = list->next;
}
size+= list->size;
return size;
}
/**
* Restituisce il byte corrispondente all'indice passato per argomento
* @param list lista da cui estrarre il byte
* @param index indice del byte desiderato
* @return byte corrispondente all'indice
*/
unsigned char list_get_element(byte_list_t *list, int index){
if(list_get_size(list) < index) perror("Errore: index not exist");
int i =0;
if(list_get_size(list) > 256)
while (i+256 <= index){
i+=256;
list = list->next;
}
return list->byte_block[index-i];
}
|
214020.c | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <time.h>
#include <inttypes.h>
#include <sys/time.h>
#include "logger.h"
#include "shared_func.h"
#include "sched_thread.h"
#include "ini_file_reader.h"
#include "fast_task_queue.h"
#include "fast_blocked_queue.h"
static bool g_continue_flag = true;
static int64_t produce_count = 0;
static int64_t consume_count = 0;
static struct fast_blocked_queue blocked_queue;
#define MAX_USLEEP 10000
void *producer_thread(void *arg)
{
int usleep_time;
int64_t count;
struct fast_task_info *pTask;
while (g_continue_flag) {
usleep_time = (int64_t) MAX_USLEEP * (int64_t)rand() / RAND_MAX;
if (usleep_time > 0) {
usleep(usleep_time);
}
count = __sync_add_and_fetch(&produce_count, 1);
if (count % 10000 == 0) {
printf("produce count: %"PRId64"\n", count);
}
pTask = free_queue_pop();
if (pTask != NULL) {
blocked_queue_push(&blocked_queue, pTask);
}
}
return NULL;
}
static void sigQuitHandler(int sig)
{
g_continue_flag = false;
blocked_queue_terminate(&blocked_queue);
logCrit("file: "__FILE__", line: %d, " \
"catch signal %d, program exiting...", \
__LINE__, sig);
}
int main(int argc, char *argv[])
{
pthread_t tid;
struct sigaction act;
const int min_buff_size = 1024;
const int max_buff_size = 1024;
const int arg_size = 0;
int result;
int64_t count;
struct fast_task_info *pTask;
srand(time(NULL));
log_init();
g_log_context.log_level = LOG_DEBUG;
memset(&act, 0, sizeof(act));
sigemptyset(&act.sa_mask);
act.sa_handler = sigQuitHandler;
if(sigaction(SIGINT, &act, NULL) < 0 ||
sigaction(SIGTERM, &act, NULL) < 0 ||
sigaction(SIGQUIT, &act, NULL) < 0)
{
logCrit("file: "__FILE__", line: %d, " \
"call sigaction fail, errno: %d, error info: %s", \
__LINE__, errno, STRERROR(errno));
logCrit("exit abnormally!\n");
return errno;
}
result = free_queue_init(1024, min_buff_size, \
max_buff_size, arg_size);
if (result != 0) {
return result;
}
if ((result=blocked_queue_init(&blocked_queue)) != 0) {
return result;
}
pthread_create(&tid, NULL, producer_thread, NULL);
pthread_create(&tid, NULL, producer_thread, NULL);
pthread_create(&tid, NULL, producer_thread, NULL);
pthread_create(&tid, NULL, producer_thread, NULL);
while (g_continue_flag) {
pTask = blocked_queue_pop(&blocked_queue);
if (pTask != NULL) {
count = __sync_add_and_fetch(&consume_count, 1);
if (count % 10000 == 0) {
printf("consume count: %"PRId64"\n", count);
}
free_queue_push(pTask);
usleep(1000);
}
}
return 0;
}
|
233766.c | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "../svm.h"
#include "mex.h"
#include "svm_model_matlab.h"
#ifdef MX_API_VER
#if MX_API_VER < 0x07030000
typedef int mwIndex;
#endif
#endif
#define CMD_LEN 2048
void read_sparse_instance(const mxArray *prhs, int index, struct svm_node *x)
{
int i, j, low, high;
mwIndex *ir, *jc;
double *samples;
ir = mxGetIr(prhs);
jc = mxGetJc(prhs);
samples = mxGetPr(prhs);
// each column is one instance
j = 0;
low = (int)jc[index], high = (int)jc[index+1];
for(i=low;i<high;i++)
{
x[j].index = (int)ir[i] + 1;
x[j].value = samples[i];
j++;
}
x[j].index = -1;
}
static void fake_answer(mxArray *plhs[])
{
plhs[0] = mxCreateDoubleMatrix(0, 0, mxREAL);
plhs[1] = mxCreateDoubleMatrix(0, 0, mxREAL);
plhs[2] = mxCreateDoubleMatrix(0, 0, mxREAL);
}
void predict(mxArray *plhs[], const mxArray *prhs[], struct svm_model *model, const int predict_probability)
{
int label_vector_row_num, label_vector_col_num;
int feature_number, testing_instance_number;
int instance_index;
double *ptr_instance, *ptr_label, *ptr_predict_label;
double *ptr_prob_estimates, *ptr_dec_values, *ptr;
struct svm_node *x;
mxArray *pplhs[1]; // transposed instance sparse matrix
int correct = 0;
int total = 0;
double error = 0;
double sump = 0, sumt = 0, sumpp = 0, sumtt = 0, sumpt = 0;
int svm_type=svm_get_svm_type(model);
int nr_class=svm_get_nr_class(model);
double *prob_estimates=NULL;
// prhs[1] = testing instance matrix
feature_number = (int)mxGetN(prhs[1]);
testing_instance_number = (int)mxGetM(prhs[1]);
label_vector_row_num = (int)mxGetM(prhs[0]);
label_vector_col_num = (int)mxGetN(prhs[0]);
if(label_vector_row_num!=testing_instance_number)
{
mexPrintf("Length of label vector does not match # of instances.\n");
fake_answer(plhs);
return;
}
if(label_vector_col_num!=1)
{
mexPrintf("label (1st argument) should be a vector (# of column is 1).\n");
fake_answer(plhs);
return;
}
ptr_instance = mxGetPr(prhs[1]);
ptr_label = mxGetPr(prhs[0]);
// transpose instance matrix
if(mxIsSparse(prhs[1]))
{
if(model->param.kernel_type == PRECOMPUTED)
{
// precomputed kernel requires dense matrix, so we make one
mxArray *rhs[1], *lhs[1];
rhs[0] = mxDuplicateArray(prhs[1]);
if(mexCallMATLAB(1, lhs, 1, rhs, "full"))
{
mexPrintf("Error: cannot full testing instance matrix\n");
fake_answer(plhs);
return;
}
ptr_instance = mxGetPr(lhs[0]);
mxDestroyArray(rhs[0]);
}
else
{
mxArray *pprhs[1];
pprhs[0] = mxDuplicateArray(prhs[1]);
if(mexCallMATLAB(1, pplhs, 1, pprhs, "transpose"))
{
mexPrintf("Error: cannot transpose testing instance matrix\n");
fake_answer(plhs);
return;
}
}
}
if(predict_probability)
{
if(svm_type==NU_SVR || svm_type==EPSILON_SVR)
mexPrintf("Prob. model for test data: target value = predicted value + z,\nz: Laplace distribution e^(-|z|/sigma)/(2sigma),sigma=%g\n",svm_get_svr_probability(model));
else
prob_estimates = (double *) malloc(nr_class*sizeof(double));
}
plhs[0] = mxCreateDoubleMatrix(testing_instance_number, 1, mxREAL);
if(predict_probability)
{
// prob estimates are in plhs[2]
if(svm_type==C_SVC || svm_type==NU_SVC)
plhs[2] = mxCreateDoubleMatrix(testing_instance_number, nr_class, mxREAL);
else
plhs[2] = mxCreateDoubleMatrix(0, 0, mxREAL);
}
else
{
// decision values are in plhs[2]
if(svm_type == ONE_CLASS ||
svm_type == EPSILON_SVR ||
svm_type == NU_SVR ||
nr_class == 1) // if only one class in training data, decision values are still returned.
plhs[2] = mxCreateDoubleMatrix(testing_instance_number, 1, mxREAL);
else
plhs[2] = mxCreateDoubleMatrix(testing_instance_number, nr_class*(nr_class-1)/2, mxREAL);
}
ptr_predict_label = mxGetPr(plhs[0]);
ptr_prob_estimates = mxGetPr(plhs[2]);
ptr_dec_values = mxGetPr(plhs[2]);
x = (struct svm_node*)malloc((feature_number+1)*sizeof(struct svm_node) );
for(instance_index=0;instance_index<testing_instance_number;instance_index++)
{
int i;
double target_label, predict_label;
target_label = ptr_label[instance_index];
if(mxIsSparse(prhs[1]) && model->param.kernel_type != PRECOMPUTED) // prhs[1]^T is still sparse
read_sparse_instance(pplhs[0], instance_index, x);
else
{
for(i=0;i<feature_number;i++)
{
x[i].index = i+1;
x[i].value = ptr_instance[testing_instance_number*i+instance_index];
}
x[feature_number].index = -1;
}
if(predict_probability)
{
if(svm_type==C_SVC || svm_type==NU_SVC)
{
predict_label = svm_predict_probability(model, x, prob_estimates);
ptr_predict_label[instance_index] = predict_label;
for(i=0;i<nr_class;i++)
ptr_prob_estimates[instance_index + i * testing_instance_number] = prob_estimates[i];
} else {
predict_label = svm_predict(model,x);
ptr_predict_label[instance_index] = predict_label;
}
}
else
{
if(svm_type == ONE_CLASS ||
svm_type == EPSILON_SVR ||
svm_type == NU_SVR)
{
double res;
predict_label = svm_predict_values(model, x, &res);
ptr_dec_values[instance_index] = res;
}
else
{
double *dec_values = (double *) malloc(sizeof(double) * nr_class*(nr_class-1)/2);
predict_label = svm_predict_values(model, x, dec_values);
if(nr_class == 1)
ptr_dec_values[instance_index] = 1;
else
for(i=0;i<(nr_class*(nr_class-1))/2;i++)
ptr_dec_values[instance_index + i * testing_instance_number] = dec_values[i];
free(dec_values);
}
ptr_predict_label[instance_index] = predict_label;
}
if(predict_label == target_label)
++correct;
error += (predict_label-target_label)*(predict_label-target_label);
sump += predict_label;
sumt += target_label;
sumpp += predict_label*predict_label;
sumtt += target_label*target_label;
sumpt += predict_label*target_label;
++total;
}
if(svm_type==NU_SVR || svm_type==EPSILON_SVR)
{
//mexPrintf("Mean squared error = %g (regression)\n",error/total);
//mexPrintf("Squared correlation coefficient = %g (regression)\n",
//((total*sumpt-sump*sumt)*(total*sumpt-sump*sumt))/
//((total*sumpp-sump*sump)*(total*sumtt-sumt*sumt))
//);
}
else
//mexPrintf("Accuracy = %g%% (%d/%d) (classification)\n",
// (double)correct/total*100,correct,total);
;
// return accuracy, mean squared error, squared correlation coefficient
plhs[1] = mxCreateDoubleMatrix(3, 1, mxREAL);
ptr = mxGetPr(plhs[1]);
ptr[0] = (double)correct/total*100;
ptr[1] = error/total;
ptr[2] = ((total*sumpt-sump*sumt)*(total*sumpt-sump*sumt))/
((total*sumpp-sump*sump)*(total*sumtt-sumt*sumt));
free(x);
if(prob_estimates != NULL)
free(prob_estimates);
}
void exit_with_help()
{
mexPrintf(
"Usage: [predicted_label, accuracy, decision_values/prob_estimates] = svmpredict(testing_label_vector, testing_instance_matrix, model, 'libsvm_options')\n"
"Parameters:\n"
" model: SVM model structure from svmtrain.\n"
" libsvm_options:\n"
" -b probability_estimates: whether to predict probability estimates, 0 or 1 (default 0); one-class SVM not supported yet\n"
"Returns:\n"
" predicted_label: SVM prediction output vector.\n"
" accuracy: a vector with accuracy, mean squared error, squared correlation coefficient.\n"
" prob_estimates: If selected, probability estimate vector.\n"
);
}
void mexFunction( int nlhs, mxArray *plhs[],
int nrhs, const mxArray *prhs[] )
{
int prob_estimate_flag = 0;
struct svm_model *model;
if(nrhs > 4 || nrhs < 3)
{
exit_with_help();
fake_answer(plhs);
return;
}
if(!mxIsDouble(prhs[0]) || !mxIsDouble(prhs[1])) {
mexPrintf("Error: label vector and instance matrix must be double\n");
fake_answer(plhs);
return;
}
if(mxIsStruct(prhs[2]))
{
const char *error_msg;
// parse options
if(nrhs==4)
{
int i, argc = 1;
char cmd[CMD_LEN], *argv[CMD_LEN/2];
// put options in argv[]
mxGetString(prhs[3], cmd, mxGetN(prhs[3]) + 1);
if((argv[argc] = strtok(cmd, " ")) != NULL)
while((argv[++argc] = strtok(NULL, " ")) != NULL)
;
for(i=1;i<argc;i++)
{
if(argv[i][0] != '-') break;
if(++i>=argc)
{
exit_with_help();
fake_answer(plhs);
return;
}
switch(argv[i-1][1])
{
case 'b':
prob_estimate_flag = atoi(argv[i]);
break;
default:
mexPrintf("Unknown option: -%c\n", argv[i-1][1]);
exit_with_help();
fake_answer(plhs);
return;
}
}
}
model = matlab_matrix_to_model(prhs[2], &error_msg);
if (model == NULL)
{
mexPrintf("Error: can't read model: %s\n", error_msg);
fake_answer(plhs);
return;
}
if(prob_estimate_flag)
{
if(svm_check_probability_model(model)==0)
{
mexPrintf("Model does not support probabiliy estimates\n");
fake_answer(plhs);
svm_free_and_destroy_model(&model);
return;
}
}
else
{
if(svm_check_probability_model(model)!=0)
mexPrintf("Model supports probability estimates, but disabled in predicton.\n");
}
predict(plhs, prhs, model, prob_estimate_flag);
// destroy model
svm_free_and_destroy_model(&model);
}
else
{
mexPrintf("model file should be a struct array\n");
fake_answer(plhs);
}
return;
}
|
172378.c | /*
FreeRTOS V7.0.0 - Copyright (C) 2011 Real Time Engineers Ltd.
***************************************************************************
* *
* FreeRTOS tutorial books are available in pdf and paperback. *
* Complete, revised, and edited pdf reference manuals are also *
* available. *
* *
* Purchasing FreeRTOS documentation will not only help you, by *
* ensuring you get running as quickly as possible and with an *
* in-depth knowledge of how to use FreeRTOS, it will also help *
* the FreeRTOS project to continue with its mission of providing *
* professional grade, cross platform, de facto standard solutions *
* for microcontrollers - completely free of charge! *
* *
* >>> See http://www.FreeRTOS.org/Documentation for details. <<< *
* *
* Thank you for using FreeRTOS, and thank you for your support! *
* *
***************************************************************************
This file is part of the FreeRTOS distribution.
FreeRTOS is free software; you can redistribute it and/or modify it under
the terms of the GNU General Public License (version 2) as published by the
Free Software Foundation AND MODIFIED BY the FreeRTOS exception.
>>>NOTE<<< The modification to the GPL is included to allow you to
distribute a combined work that includes FreeRTOS without being obliged to
provide the source code for proprietary components outside of the FreeRTOS
kernel. FreeRTOS 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 and the FreeRTOS license exception along with FreeRTOS; if not it
can be viewed here: http://www.freertos.org/a00114.html and also obtained
by writing to Richard Barry, contact details for whom are available on the
FreeRTOS WEB site.
1 tab == 4 spaces!
http://www.FreeRTOS.org - Documentation, latest information, license and
contact details.
http://www.SafeRTOS.com - A version that is certified for use in safety
critical systems.
http://www.OpenRTOS.com - Commercial support, development, porting,
licensing and training services.
*/
/*
* Implementation of pvPortMalloc() and vPortFree() that relies on the
* compilers own malloc() and free() implementations.
*
* This file can only be used if the linker is configured to to generate
* a heap memory area.
*
* See heap_2.c and heap_1.c for alternative implementations, and the memory
* management pages of http://www.FreeRTOS.org for more information.
*/
/**
* Support and FAQ: visit <a href="http://www.atmel.com/design-support/">Atmel Support</a>
*/
#include <stdlib.h>
/* Defining MPU_WRAPPERS_INCLUDED_FROM_API_FILE prevents task.h from redefining
all the API functions to use the MPU wrappers. That should only be done when
task.h is included from an application file. */
#define MPU_WRAPPERS_INCLUDED_FROM_API_FILE
#include "../../include/FreeRTOS.h"
#include "../../include/task.h"
#undef MPU_WRAPPERS_INCLUDED_FROM_API_FILE
/*-----------------------------------------------------------*/
void *pvPortMalloc( size_t xWantedSize )
{
void *pvReturn;
vTaskSuspendAll();
{
pvReturn = malloc( xWantedSize );
}
xTaskResumeAll();
#if( configUSE_MALLOC_FAILED_HOOK == 1 )
{
if( pvReturn == NULL )
{
extern void vApplicationMallocFailedHook( void );
vApplicationMallocFailedHook();
}
}
#endif
return pvReturn;
}
/*-----------------------------------------------------------*/
void vPortFree( void *pv )
{
if( pv )
{
vTaskSuspendAll();
{
free( pv );
}
xTaskResumeAll();
}
}
|
949497.c | /*
* helper functions for physically contiguous capture buffers
*
* The functions support hardware lacking scatter gather support
* (i.e. the buffers must be linear in physical memory)
*
* Copyright (c) 2008 Magnus Damm
*
* Based on videobuf-vmalloc.c,
* (c) 2007 Mauro Carvalho Chehab, <[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
*/
#include <linux/init.h>
#include <linux/module.h>
#include <linux/mm.h>
#include <linux/pagemap.h>
#include <linux/dma-mapping.h>
#include <linux/sched.h>
#include <linux/slab.h>
#include <media/videobuf-dma-contig.h>
struct videobuf_dma_contig_memory {
u32 magic;
void *vaddr;
dma_addr_t dma_handle;
unsigned long size;
};
#define MAGIC_DC_MEM 0x0733ac61
#define MAGIC_CHECK(is, should) \
if (unlikely((is) != (should))) { \
pr_err("magic mismatch: %x expected %x\n", (is), (should)); \
BUG(); \
}
static int __videobuf_dc_alloc(struct device *dev,
struct videobuf_dma_contig_memory *mem,
unsigned long size, gfp_t flags)
{
mem->size = size;
mem->vaddr = dma_alloc_coherent(dev, mem->size,
&mem->dma_handle, flags);
if (!mem->vaddr) {
dev_err(dev, "memory alloc size %ld failed\n", mem->size);
return -ENOMEM;
}
dev_dbg(dev, "dma mapped data is at %p (%ld)\n", mem->vaddr, mem->size);
return 0;
}
static void __videobuf_dc_free(struct device *dev,
struct videobuf_dma_contig_memory *mem)
{
dma_free_coherent(dev, mem->size, mem->vaddr, mem->dma_handle);
mem->vaddr = NULL;
}
static void videobuf_vm_open(struct vm_area_struct *vma)
{
struct videobuf_mapping *map = vma->vm_private_data;
dev_dbg(map->q->dev, "vm_open %p [count=%u,vma=%08lx-%08lx]\n",
map, map->count, vma->vm_start, vma->vm_end);
map->count++;
}
static void videobuf_vm_close(struct vm_area_struct *vma)
{
struct videobuf_mapping *map = vma->vm_private_data;
struct videobuf_queue *q = map->q;
int i;
dev_dbg(q->dev, "vm_close %p [count=%u,vma=%08lx-%08lx]\n",
map, map->count, vma->vm_start, vma->vm_end);
map->count--;
if (0 == map->count) {
struct videobuf_dma_contig_memory *mem;
dev_dbg(q->dev, "munmap %p q=%p\n", map, q);
videobuf_queue_lock(q);
/* We need first to cancel streams, before unmapping */
if (q->streaming)
videobuf_queue_cancel(q);
for (i = 0; i < VIDEO_MAX_FRAME; i++) {
if (NULL == q->bufs[i])
continue;
if (q->bufs[i]->map != map)
continue;
mem = q->bufs[i]->priv;
if (mem) {
/* This callback is called only if kernel has
allocated memory and this memory is mmapped.
In this case, memory should be freed,
in order to do memory unmap.
*/
MAGIC_CHECK(mem->magic, MAGIC_DC_MEM);
/* vfree is not atomic - can't be
called with IRQ's disabled
*/
dev_dbg(q->dev, "buf[%d] freeing %p\n",
i, mem->vaddr);
__videobuf_dc_free(q->dev, mem);
mem->vaddr = NULL;
}
q->bufs[i]->map = NULL;
q->bufs[i]->baddr = 0;
}
kfree(map);
videobuf_queue_unlock(q);
}
}
static const struct vm_operations_struct videobuf_vm_ops = {
.open = videobuf_vm_open,
.close = videobuf_vm_close,
};
/**
* videobuf_dma_contig_user_put() - reset pointer to user space buffer
* @mem: per-buffer private videobuf-dma-contig data
*
* This function resets the user space pointer
*/
static void videobuf_dma_contig_user_put(struct videobuf_dma_contig_memory *mem)
{
mem->dma_handle = 0;
mem->size = 0;
}
/**
* videobuf_dma_contig_user_get() - setup user space memory pointer
* @mem: per-buffer private videobuf-dma-contig data
* @vb: video buffer to map
*
* This function validates and sets up a pointer to user space memory.
* Only physically contiguous pfn-mapped memory is accepted.
*
* Returns 0 if successful.
*/
static int videobuf_dma_contig_user_get(struct videobuf_dma_contig_memory *mem,
struct videobuf_buffer *vb)
{
struct mm_struct *mm = current->mm;
struct vm_area_struct *vma;
unsigned long prev_pfn, this_pfn;
unsigned long pages_done, user_address;
unsigned int offset;
int ret;
offset = vb->baddr & ~PAGE_MASK;
mem->size = PAGE_ALIGN(vb->size + offset);
ret = -EINVAL;
down_read(&mm->mmap_sem);
vma = find_vma(mm, vb->baddr);
if (!vma)
goto out_up;
if ((vb->baddr + mem->size) > vma->vm_end)
goto out_up;
pages_done = 0;
prev_pfn = 0; /* kill warning */
user_address = vb->baddr;
while (pages_done < (mem->size >> PAGE_SHIFT)) {
ret = follow_pfn(vma, user_address, &this_pfn);
if (ret)
break;
if (pages_done == 0)
mem->dma_handle = (this_pfn << PAGE_SHIFT) + offset;
else if (this_pfn != (prev_pfn + 1))
ret = -EFAULT;
if (ret)
break;
prev_pfn = this_pfn;
user_address += PAGE_SIZE;
pages_done++;
}
out_up:
up_read(¤t->mm->mmap_sem);
return ret;
}
static struct videobuf_buffer *__videobuf_alloc(size_t size)
{
struct videobuf_dma_contig_memory *mem;
struct videobuf_buffer *vb;
vb = kzalloc(size + sizeof(*mem), GFP_KERNEL);
if (vb) {
vb->priv = ((char *)vb) + size;
mem = vb->priv;
mem->magic = MAGIC_DC_MEM;
}
return vb;
}
static void *__videobuf_to_vaddr(struct videobuf_buffer *buf)
{
struct videobuf_dma_contig_memory *mem = buf->priv;
BUG_ON(!mem);
MAGIC_CHECK(mem->magic, MAGIC_DC_MEM);
return mem->vaddr;
}
static int __videobuf_iolock(struct videobuf_queue *q,
struct videobuf_buffer *vb,
struct v4l2_framebuffer *fbuf)
{
struct videobuf_dma_contig_memory *mem = vb->priv;
BUG_ON(!mem);
MAGIC_CHECK(mem->magic, MAGIC_DC_MEM);
switch (vb->memory) {
case V4L2_MEMORY_MMAP:
dev_dbg(q->dev, "%s memory method MMAP\n", __func__);
/* All handling should be done by __videobuf_mmap_mapper() */
if (!mem->vaddr) {
dev_err(q->dev, "memory is not alloced/mmapped.\n");
return -EINVAL;
}
break;
case V4L2_MEMORY_USERPTR:
dev_dbg(q->dev, "%s memory method USERPTR\n", __func__);
/* handle pointer from user space */
if (vb->baddr)
return videobuf_dma_contig_user_get(mem, vb);
/* allocate memory for the read() method */
if (__videobuf_dc_alloc(q->dev, mem, PAGE_ALIGN(vb->size),
GFP_KERNEL))
return -ENOMEM;
break;
case V4L2_MEMORY_OVERLAY:
default:
dev_dbg(q->dev, "%s memory method OVERLAY/unknown\n", __func__);
return -EINVAL;
}
return 0;
}
static int __videobuf_mmap_mapper(struct videobuf_queue *q,
struct videobuf_buffer *buf,
struct vm_area_struct *vma)
{
struct videobuf_dma_contig_memory *mem;
struct videobuf_mapping *map;
int retval;
unsigned long size;
dev_dbg(q->dev, "%s\n", __func__);
/* create mapping + update buffer list */
map = kzalloc(sizeof(struct videobuf_mapping), GFP_KERNEL);
if (!map)
return -ENOMEM;
buf->map = map;
map->q = q;
buf->baddr = vma->vm_start;
mem = buf->priv;
BUG_ON(!mem);
MAGIC_CHECK(mem->magic, MAGIC_DC_MEM);
if (__videobuf_dc_alloc(q->dev, mem, PAGE_ALIGN(buf->bsize),
GFP_KERNEL | __GFP_COMP))
goto error;
/* Try to remap memory */
size = vma->vm_end - vma->vm_start;
vma->vm_page_prot = pgprot_noncached(vma->vm_page_prot);
retval = vm_iomap_memory(vma, vma->vm_start, size);
if (retval) {
dev_err(q->dev, "mmap: remap failed with error %d. ",
retval);
dma_free_coherent(q->dev, mem->size,
mem->vaddr, mem->dma_handle);
goto error;
}
vma->vm_ops = &videobuf_vm_ops;
vma->vm_flags |= VM_DONTEXPAND;
vma->vm_private_data = map;
dev_dbg(q->dev, "mmap %p: q=%p %08lx-%08lx (%lx) pgoff %08lx buf %d\n",
map, q, vma->vm_start, vma->vm_end,
(long int)buf->bsize, vma->vm_pgoff, buf->i);
videobuf_vm_open(vma);
return 0;
error:
kfree(map);
return -ENOMEM;
}
static struct videobuf_qtype_ops qops = {
.magic = MAGIC_QTYPE_OPS,
.alloc_vb = __videobuf_alloc,
.iolock = __videobuf_iolock,
.mmap_mapper = __videobuf_mmap_mapper,
.vaddr = __videobuf_to_vaddr,
};
void videobuf_queue_dma_contig_init(struct videobuf_queue *q,
const struct videobuf_queue_ops *ops,
struct device *dev,
spinlock_t *irqlock,
enum v4l2_buf_type type,
enum v4l2_field field,
unsigned int msize,
void *priv,
struct mutex *ext_lock)
{
videobuf_queue_core_init(q, ops, dev, irqlock, type, field, msize,
priv, &qops, ext_lock);
}
EXPORT_SYMBOL_GPL(videobuf_queue_dma_contig_init);
dma_addr_t videobuf_to_dma_contig(struct videobuf_buffer *buf)
{
struct videobuf_dma_contig_memory *mem = buf->priv;
BUG_ON(!mem);
MAGIC_CHECK(mem->magic, MAGIC_DC_MEM);
return mem->dma_handle;
}
EXPORT_SYMBOL_GPL(videobuf_to_dma_contig);
void videobuf_dma_contig_free(struct videobuf_queue *q,
struct videobuf_buffer *buf)
{
struct videobuf_dma_contig_memory *mem = buf->priv;
/* mmapped memory can't be freed here, otherwise mmapped region
would be released, while still needed. In this case, the memory
release should happen inside videobuf_vm_close().
So, it should free memory only if the memory were allocated for
read() operation.
*/
if (buf->memory != V4L2_MEMORY_USERPTR)
return;
if (!mem)
return;
MAGIC_CHECK(mem->magic, MAGIC_DC_MEM);
/* handle user space pointer case */
if (buf->baddr) {
videobuf_dma_contig_user_put(mem);
return;
}
/* read() method */
if (mem->vaddr) {
__videobuf_dc_free(q->dev, mem);
mem->vaddr = NULL;
}
}
EXPORT_SYMBOL_GPL(videobuf_dma_contig_free);
MODULE_DESCRIPTION("helper module to manage video4linux dma contig buffers");
MODULE_AUTHOR("Magnus Damm");
MODULE_LICENSE("GPL");
|
43624.c | /*
* CWAVE (RWAVE==WAV) input plugin / quad modulator for WinAmp (XMPlay) player
*
* adv_modulator.c -- advanced analitic signal modulator
* (there is no any "simple" renders / mods from in_cwave V1.5.0)
*
* Copyright (c) 2010-2021, Rat and Catcher Technologies
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the Rat and Catcher Technologies nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL RAT AND CATCHER TECHNOLOGIES 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 "in_cwave.h"
// get scaled frequency as scaled unsigned
#define UGET_SCALED_FR(df) ((unsigned)((df) * ((double)HZ_SCALE) + 0.5))
// get scaled frequency as scaled double
#define DGET_SCALED_FR(df) ((double)UGET_SCALED_FR(df))
// get scaled frequency as unscaled double
#define DGET_USCALED_FR(df) (DGET_SCALED_FR(df) / ((double)HZ_SCALE))
/*
* global statics
* ------ -------
*/
typedef struct tagADVANCED_MODULATOR
{
NODE_DSP *head; // head/base .master of DSP list
NODE_DSP *tail; // pointer of the tail of DSP list
CRITICAL_SECTION cs_dsp_list; // DSP-list protector
unsigned l_clips, r_clips; // clips per channel
double l_peak, r_peak; // peak values per chaannel, dB
BOOL is_bypass_list; // DSP list bypass flag
BOOL is_frmod_scaled; // copyed from config at one-time init
} ADVANCED_MODULATOR;
static ADVANCED_MODULATOR am; // one and only one copy
static const TCHAR *dsp_names[] = // Names (or prefixes) of DSP-node
{
_T("Master"), // MODE_MASTER (0)
_T("Shift-"), // MODE_SHIFT (1)
_T("PM-"), // MODE_PM (2)
_T("MIX-") // MODE_MIX (3)
};
/* Helpers
* -------
*/
/* helper to create new node
*/
static NODE_DSP *create_node_dsp(const TCHAR *name, int mode, int force_master)
{
NODE_DSP *temp = (NODE_DSP *)cmalloc(sizeof(NODE_DSP));
int i;
memset(temp, 0, sizeof(NODE_DSP));
temp -> prev = temp -> next = NULL;
temp -> mode = mode;
// from here we fill ALL the fields of new node with
// adequate values; this don't mean, that the caller will not
// redefine them to it's own defaults.
temp -> l_gain = temp -> r_gain = DEF_GAIN_MOD;
for(i = 0; i < N_INPUTS; ++i)
temp -> inputs[i] = 0;
temp -> xch_mode = XCH_DEF;
temp -> l_iq_invert = temp -> r_iq_invert = 0;
switch(mode)
{
default:
case MODE_MASTER: // only if force_master != 0
temp -> l_gain = temp -> r_gain = DEF_GAIN_MASTER;
if(force_master)
{
temp -> dsp.mk_master.le.tout = temp -> dsp.mk_master.ri.tout = S_RE;
temp -> inputs[0] = 1; // master initially always has 'in' On
}
else
{
free(temp);
return NULL;
}
break;
case MODE_SHIFT:
temp -> dsp.mk_shift.le.fr_shift = DEF_FSHIFT;
temp -> dsp.mk_shift.le.is_shift = 1;
temp -> dsp.mk_shift.ri.fr_shift = -DEF_FSHIFT;
temp -> dsp.mk_shift.ri.is_shift = 1;
temp -> dsp.mk_shift.n_out = N_INPUTS - 1;
temp -> dsp.mk_shift.lock_shift = 1;
temp -> dsp.mk_shift.sign_lock_shift = 1;
break;
case MODE_PM:
temp -> dsp.mk_pm.le.freq = DEF_PMFREQ;
temp -> dsp.mk_pm.le.phase = 0.0;
temp -> dsp.mk_pm.le.level = DEF_PMLEVEL;
temp -> dsp.mk_pm.le.angle = 0.0;
temp -> dsp.mk_pm.le.is_pm = 1;
temp -> dsp.mk_pm.ri.freq = DEF_PMFREQ;
temp -> dsp.mk_pm.ri.phase = DEF_PMPHASE;
temp -> dsp.mk_pm.ri.level = DEF_PMLEVEL;
temp -> dsp.mk_pm.ri.angle = DEF_PMANGLE;
temp -> dsp.mk_pm.ri.is_pm = 1;
temp -> dsp.mk_pm.n_out = N_INPUTS - 1;
temp -> dsp.mk_pm.lock_freq = 1;
temp -> dsp.mk_pm.lock_phase = 0;
temp -> dsp.mk_pm.lock_level = 1;
temp -> dsp.mk_pm.lock_angle = 0;
break;
case MODE_MIX:
temp -> dsp.mk_mix.n_out = N_INPUTS - 1;
break;
}
// the name
_tcscpy(temp -> name, dsp_names[mode]);
if(name)
_tcscat(temp -> name, name);
temp -> lock_gain = 1;
// ready to include to list
return temp;
}
/* remove (replace) node outplug -- thread unsafe
*/
static void replace_output_plug(NODE_DSP *ndEd, int n) // n == -1 -> remove only
{
int nrem = -1;
switch(ndEd -> mode)
{
default:
case MODE_MASTER:
// just in case...
break;
case MODE_SHIFT:
nrem = ndEd -> dsp.mk_shift.n_out;
if(n >= 0)
ndEd -> dsp.mk_shift.n_out = n;
break;
case MODE_PM:
nrem = ndEd -> dsp.mk_pm.n_out;
if(n >= 0)
ndEd -> dsp.mk_pm.n_out = n;
break;
case MODE_MIX:
nrem = ndEd -> dsp.mk_mix.n_out;
if(n >= 0)
ndEd -> dsp.mk_mix.n_out = n;
break;
}
// clear unused inout
if(nrem >= 0)
mod_context_clear_all_inouts(nrem);
}
/* Front-end functions
* --------- ---------
*/
/* one-time initialization of advanced modulator
*/
int amod_init(NODE_DSP *cfg_list, BOOL is_frmod_scaled) // !0, if list accepted
{
int res = 0;
int was_master = 0;
memset(&am, 0, sizeof(am));
am.head = NULL; // paranoja ** 2
if(cfg_list)
{
NODE_DSP *temp;
// Try to aacept external DSP-list. We assume, that all of the fields of a single node are
// correct; we just check, that the master is one and only one and she live at head of the
// list position. If cfg_list not accepted, _we shall free() it_.
if(cfg_list -> mode == MODE_MASTER)
{
temp = am.head = cfg_list;
// no chance to change the master's name from config ;)
_tcscpy(cfg_list -> name, dsp_names[MODE_MASTER]);
do
{
// make few semantic checks
if(temp -> lock_gain)
{
temp -> r_gain = temp -> l_gain;
temp -> r_iq_invert = temp -> l_iq_invert;
}
switch(temp -> mode)
{
case MODE_MASTER:
// to be sure that master is one and only one, and stay first in the list
if(was_master)
am.head = NULL;
else
was_master = 1;
break;
case MODE_SHIFT:
if(temp -> dsp.mk_shift.lock_shift)
{
temp -> dsp.mk_shift.ri.fr_shift =
temp -> dsp.mk_shift.sign_lock_shift?
-temp -> dsp.mk_shift.le.fr_shift
:
temp -> dsp.mk_shift.le.fr_shift;
temp -> dsp.mk_shift.ri.is_shift = temp -> dsp.mk_shift.le.is_shift;
}
break;
case MODE_PM:
if(temp -> dsp.mk_pm.lock_freq)
{
temp -> dsp.mk_pm.ri.freq = temp -> dsp.mk_pm.le.freq;
temp -> dsp.mk_pm.ri.is_pm = temp -> dsp.mk_pm.le.is_pm;
}
if(temp -> dsp.mk_pm.lock_phase)
{
temp -> dsp.mk_pm.ri.phase = temp -> dsp.mk_pm.le.phase;
}
if(temp -> dsp.mk_pm.lock_level)
{
temp -> dsp.mk_pm.ri.level = temp -> dsp.mk_pm.le.level;
}
if(temp -> dsp.mk_pm.lock_angle)
{
temp -> dsp.mk_pm.ri.angle = temp -> dsp.mk_pm.le.angle;
}
break;
case MODE_MIX:
break;
default:
am.head = NULL;
break;
}
am.tail = temp;
temp = temp -> next;
}
while(temp && am.head);
}
if(am.head)
{
res = 1;
}
else
{
while(cfg_list)
{
temp = cfg_list;
cfg_list = cfg_list -> next;
free(temp);
}
}
}
if(!am.head)
{
// create the master node -- one and only one
am.head = create_node_dsp(NULL, MODE_MASTER, 1 /* enable to create master */);
am.tail = am.head;
}
// the rest of modulator's object
InitializeCriticalSection(&am.cs_dsp_list);
am.l_clips = am.r_clips = 0;
am.l_peak = am.r_peak = SR_ZERO_SIGNAL_DB;
am.is_bypass_list = FALSE;
am.is_frmod_scaled = is_frmod_scaled; // need restart to change
return res;
}
/* cleanup advanced modulator (+, probably transfer DSP-list)
*/
NODE_DSP *amod_cleanup(int is_transfer)
{
NODE_DSP *res = NULL;
if(is_transfer)
{
res = am.head;
}
else
{
if(am.head)
{
amod_del_dsplist();
free(am.head);
}
}
// ok, looks mad:
am.head = am.tail = NULL;
DeleteCriticalSection(&am.cs_dsp_list);
return res; // may be NULL in lots of cases
}
/* delete the whole DSP list
*/
void amod_del_dsplist(void)
{
EnterCriticalSection(&am.cs_dsp_list);
while(am.tail -> prev)
{
am.tail = am.tail -> prev;
replace_output_plug(am.tail -> next, -1); // clear unused plug
free(am.tail -> next);
am.tail -> next = NULL;
}
LeaveCriticalSection(&am.cs_dsp_list);
}
/* delete the last DSP list element
*/
void amod_del_lastdsp(void)
{
EnterCriticalSection(&am.cs_dsp_list);
if(am.tail -> prev)
{
am.tail = am.tail -> prev;
replace_output_plug(am.tail -> next, -1); // clear unused plug
free(am.tail -> next);
am.tail -> next = NULL;
}
LeaveCriticalSection(&am.cs_dsp_list);
}
/* add the last element to the DSP list
*/
NODE_DSP *amod_add_lastdsp(const TCHAR *name, int mode)
{
NODE_DSP *temp = create_node_dsp(name, mode, 0 /* can't create master from here */);
if(NULL == temp)
return temp;
// ok, include to the list
EnterCriticalSection(&am.cs_dsp_list);
temp -> prev = am.tail;
am.tail -> next = temp;
am.tail = temp;
LeaveCriticalSection(&am.cs_dsp_list);
return am.tail;
}
/* get the state of bypass list flag
*/
BOOL amod_get_bypass_list_flag(void)
{
return am.is_bypass_list;
}
/* set the state of bypass list flag
*/
void amod_set_bypass_list_flag(BOOL bypass)
{
am.is_bypass_list = bypass;
}
/* get DSP list head for keep-the-structure operation
*/
NODE_DSP *amod_get_headdsp(void)
{
return am.head;
}
/* set DSP node outplug -- thread safe
*/
void amod_set_output_plug(NODE_DSP *ndEd, int n) // n == -1 -> remove only
{
EnterCriticalSection(&am.cs_dsp_list);
replace_output_plug(ndEd, n);
LeaveCriticalSection(&am.cs_dsp_list);
}
/* get channel's clips counters and peak values
*/
void amod_get_clips_peaks
( unsigned *lc
, unsigned *rc
, double *lpv
, double *rpv
, BOOL isReset
)
{
if(isReset)
{
am.l_clips = am.r_clips = 0;
am.l_peak = am.r_peak = SR_ZERO_SIGNAL_DB;
}
// asynchronious changes of X_clips uncritical
*lc = am.l_clips;
*rc = am.r_clips;
// asynchronious changes of X_peak uncritical
adbl_write(lpv, am.l_peak);
adbl_write(rpv, am.r_peak);
}
/* convert a frequency to it's "true" value
*/
double amod_true_freq(double raw_freq)
{
return am.is_frmod_scaled?
(raw_freq < 0? -DGET_USCALED_FR(-raw_freq) : DGET_USCALED_FR(raw_freq))
:
raw_freq;
}
/* DSP helpers
* --- -------
*/
/* NOTE:: We trying to use volatile variables only once and don't
* include them to complicated expressions...
*/
/* make one channel for CMAKE_MASTER
*/
static __inline double dsp_master(CMAKE_MASTER *master, CCOMPLEX *input)
{
switch(master -> tout)
{
case S_RE:
return input -> re;
break;
case S_IM:
return input -> im;
break;
}
// default -- some sort of 'assert'
return 0.0;
}
/* make copy of complex (CCOMPLEX *)
*/
static __inline void dsp_copy(CCOMPLEX *output, CCOMPLEX *input)
{
output -> re = input -> re;
output -> im = input -> im;
}
/* make one channel for CMAKE_SHIFT
*/
static __inline void dsp_shift(CMAKE_SHIFT *shift, CCOMPLEX *output,
CCOMPLEX *input, double norm_omega)
{
if(shift -> is_shift)
{
double sh_freq, phase, cos_v, sin_v;
BOOL sh_sign = FALSE;
adbl_read(&sh_freq, &(shift -> fr_shift));
if(sh_freq < 0.0)
{
sh_freq = -sh_freq;
sh_sign = TRUE;
}
if(am.is_frmod_scaled)
{
sh_freq = DGET_SCALED_FR(sh_freq);
}
phase = fmod(norm_omega * sh_freq, 2.0 * PI); // fmod() don't need
cos_v = cos(phase);
sin_v = sin(phase);
if(sh_sign)
sin_v = -sin_v;
output -> re = input -> re * cos_v - input -> im * sin_v;
output -> im = input -> re * sin_v + input -> im * cos_v;
}
else
{
dsp_copy(output, input);
}
}
/* make one channel for CMAKE_PM
*/
static __inline void dsp_pm(CMAKE_PM *pm, CCOMPLEX *output,
CCOMPLEX *input, double norm_omega)
{
if(pm -> is_pm)
{
double freq, fphase, flevel, fangle, phase;
adbl_read(&freq, &(pm -> freq));
adbl_read(&fphase, &(pm -> phase));
adbl_read(&flevel, &(pm -> level));
adbl_read(&fangle, &(pm -> angle));
if(am.is_frmod_scaled)
{
freq = DGET_SCALED_FR(freq);
}
phase = fmod(norm_omega * freq, 2.0 * PI); // fmod() don't need
{
double psi = flevel * PI * (sin(phase + fphase * PI) + fangle);
double cos_v = cos(psi);
double sin_v = sin(psi);
output -> re = input -> re * cos_v - input -> im * sin_v;
output -> im = input -> re * sin_v + input -> im * cos_v;
}
}
else
{
dsp_copy(output, input);
}
}
/* render ns <= NS_PERTIME samples into buf
*/
int amod_process_samples(char *buf, MOD_CONTEXT *mc)
{
// this function is only used by DecodeThread. (NO-NO-NO!! transcode too!! ;))
// note that if you adjust the size of sample_buffer, for say, 1024
// sample blocks, it will be still work, but some of the visualization
// might not look as good as it could. Stick with NS_PERTIME (576) sample blocks
// if you can, and have an additional auxiliary (overflow) buffer if
// necessary..
double norm_omega;
double lOut = 0.0, rOut = 0.0; // to shut up code analiser
NODE_DSP *cur;
unsigned ix_mix;
if(!xwave_read_samples(mc -> xr))
return 0;
while(mc -> xr -> unpacked < mc -> xr -> really_readed)
{
// In V02.00.00 this was:
// norm_omega = (2.0 * PI) * (double)(mc -> n_frame) / mc -> xr -> sample_rate;
// mc -> n_frame = (mc -> n_frame + 1) % mc -> xr -> sample_rate;
// Its sound proudly, but worked correctly only for integer modulation freqs.
mod_context_lock_framecnt(mc);
if(am.is_frmod_scaled)
{
unsigned scale_sr = mc -> xr -> sample_rate * HZ_SCALE;
norm_omega = (2.0 * PI) * ((double)(mc -> n_frame)) / ((double)scale_sr);
mc -> n_frame = (mc -> n_frame + 1) % (uint64_t)scale_sr;
}
else
{
// directly and literally
norm_omega = (2.0 * PI) * ((double)(mc -> n_frame)) / (double)(mc -> xr -> sample_rate);
++(mc -> n_frame); // ..unlimitly.. ..to hell..
}
mod_context_unlock_framecnt(mc);
all_hilberts_lock();
xwave_unpack_csample(
&mc -> inout[0].le.re, &mc -> inout[0].le.im,
&mc -> inout[0].ri.re, &mc -> inout[0].ri.im,
mc, mc -> xr);
all_hilberts_unlock();
// loop by the DSP list from TAIL to HEAD
EnterCriticalSection(&am.cs_dsp_list);
for(cur = am.is_bypass_list? am.head : am.tail; cur; cur = cur -> prev)
{
LRCOMPLEX data, *pout;
double lg, rg;
double xt;
// make mix
if(am.is_bypass_list)
{
// take raw "in" only
data.le.re = mc -> inout[0].le.re;
data.le.im = mc -> inout[0].le.im;
data.ri.re = mc -> inout[0].ri.re;
data.ri.im = mc -> inout[0].ri.im;
}
else
{
// the true mix
data.le.re = data.le.im = data.ri.re = data.ri.im = 0.0;
for(ix_mix = 0; ix_mix < N_INPUTS; ++ix_mix)
{
if(cur -> inputs[ix_mix])
{
data.le.re += mc -> inout[ix_mix].le.re;
data.le.im += mc -> inout[ix_mix].le.im;
data.ri.re += mc -> inout[ix_mix].ri.re;
data.ri.im += mc -> inout[ix_mix].ri.im;
}
}
}
// channels exchange
switch(cur -> xch_mode)
{
case XCH_SWAP: // swap left and right
xt = data.le.re;
data.le.re = data.ri.re;
data.ri.re = xt;
xt = data.le.im;
data.le.im = data.ri.im;
data.ri.im = xt;
break;
case XCH_LEFTONLY: // both set to left
data.ri.re = data.le.re;
data.ri.im = data.le.im;
break;
case XCH_RIGHTONLY: // both set to right
data.le.re = data.ri.re;
data.le.im = data.ri.im;
break;
case XCH_MIXLR: // both set to (L + R) / 2
data.le.re = data.ri.re = (data.le.re + data.ri.re) / 2.0;
data.le.im = data.ri.im = (data.le.im + data.ri.im) / 2.0;
break;
case XCH_NORMAL: // leave as is
default:
break;
}
// spectrum inversion (swap I<>Q)
if(cur -> l_iq_invert)
{
xt = data.le.re;
data.le.re = data.le.im;
data.le.im = xt;
}
if(cur -> r_iq_invert)
{
xt = data.ri.re;
data.ri.re = data.ri.im;
data.ri.im = xt;
}
// adjust levels (make _after_ channels exchange)
adbl_read(&lg, &(cur -> l_gain));
adbl_read(&rg, &(cur -> r_gain));
data.le.re *= lg;
data.le.im *= lg;
data.ri.re *= rg;
data.ri.im *= rg;
// exec DSP
switch(cur -> mode)
{
case MODE_MASTER:
lOut = dsp_master(&(cur -> dsp.mk_master.le), &data.le);
rOut = dsp_master(&(cur -> dsp.mk_master.ri), &data.ri);
// .. here we should be sure, that lOut/rOut is the final product of DSP ..
break;
case MODE_SHIFT:
pout = &(mc -> inout[cur -> dsp.mk_shift.n_out]);
dsp_shift(&(cur -> dsp.mk_shift.le), &(pout -> le), &data.le, norm_omega);
dsp_shift(&(cur -> dsp.mk_shift.ri), &(pout -> ri), &data.ri, norm_omega);
break;
case MODE_PM:
pout = &(mc -> inout[cur -> dsp.mk_pm.n_out]);
dsp_pm(&(cur -> dsp.mk_pm.le), &(pout -> le), &data.le, norm_omega);
dsp_pm(&(cur -> dsp.mk_pm.ri), &(pout -> ri), &data.ri, norm_omega);
break;
case MODE_MIX:
pout = &(mc -> inout[cur -> dsp.mk_mix.n_out]);
dsp_copy(&(pout -> le), &data.le);
dsp_copy(&(pout -> ri), &data.ri);
break;
} // switch .mode
} // END of DSP loop
LeaveCriticalSection(&am.cs_dsp_list);
// place into out buffer
all_srenders_lock();
sound_render_value(&buf, lOut, &am.l_clips, &am.l_peak, &mc -> sr_left, &mc -> fes_sr_left);
sound_render_value(&buf, rOut, &am.r_clips, &am.r_peak, &mc -> sr_right, &mc -> fes_sr_right);
all_srenders_unlock();
}
return mc -> xr -> unpacked;
}
/* the end...
*/
|
534654.c | #include <time.h>
#include "datetime.h"
#include "now.h"
datetime_sec now(void)
{
return time((void *)0);
}
|
513112.c | /**
*****************************************************************************************
* Copyright(c) 2015, Realtek Semiconductor Corporation. All rights reserved.
*****************************************************************************************
* @file light_xyl_server.c
* @brief Source file for light xyl server model.
* @details Data types and external functions declaration.
* @author hector_huang
* @date 2019-07-09
* @version v1.0
* *************************************************************************************
*/
#include <math.h>
#include "light_xyl.h"
#include "delay_execution.h"
#if MODEL_ENABLE_DELAY_MSG_RSP
#include "delay_msg_rsp.h"
#endif
typedef struct
{
uint8_t tid;
light_xyl_t target_xyl;
generic_transition_time_t trans_time;
uint32_t delay_time;
#if MODEL_ENABLE_DELAY_MSG_RSP
uint32_t delay_pub_time;
#endif
} light_xyl_info_t;
typedef struct
{
bool state_changed;
bool use_transition;
} light_xyl_process_result_t;
double light_xyl_x_to_cie1931_x(uint16_t xyl_x)
{
return xyl_x / 65535.0;
}
uint16_t light_cie1931_x_to_xyl_x(double cie1931_x)
{
return cie1931_x * 65535;
}
double light_xyl_y_to_cie1931_y(uint16_t xyl_y)
{
return xyl_y / 65535.0;
}
uint16_t light_cie1931_y_to_xyl_y(double cie1931_y)
{
return cie1931_y * 65535;
}
uint16_t light_intensity_to_xyl_lightness(uint16_t intensity)
{
return (uint16_t)(65535 * sqrt(intensity / 65535.0));
}
uint16_t light_xyl_lightness_to_internsity(uint16_t lightness)
{
return (uint16_t)(lightness / 65535.0 * lightness);
}
static mesh_msg_send_cause_t light_xyl_server_send(mesh_model_info_p pmodel_info,
uint16_t dst, uint8_t *pmsg, uint16_t msg_len, uint16_t app_key_index,
uint32_t delay_time)
{
mesh_msg_t mesh_msg;
mesh_msg.pmodel_info = pmodel_info;
access_cfg(&mesh_msg);
mesh_msg.pbuffer = pmsg;
mesh_msg.msg_len = msg_len;
if (0 != dst)
{
mesh_msg.dst = dst;
mesh_msg.app_key_index = app_key_index;
}
mesh_msg.delay_time = delay_time;
return access_send(&mesh_msg);
}
static mesh_msg_send_cause_t light_xyl_status(mesh_model_info_p pmodel_info, uint16_t dst,
uint16_t app_key_index, light_xyl_t xyl,
bool optional, generic_transition_time_t remaining_time,
uint32_t delay_time)
{
light_xyl_status_t msg;
ACCESS_OPCODE_BYTE(msg.opcode, MESH_MSG_LIGHT_XYL_STATUS);
uint16_t msg_len;
if (optional)
{
msg_len = sizeof(light_xyl_status_t);
msg.remaining_time = remaining_time;
}
else
{
msg_len = MEMBER_OFFSET(light_xyl_status_t, remaining_time);
}
msg.xyl = xyl;
return light_xyl_server_send(pmodel_info, dst, (uint8_t *)&msg, msg_len, app_key_index,
delay_time);
}
static mesh_msg_send_cause_t light_xyl_target_status(mesh_model_info_p pmodel_info, uint16_t dst,
uint16_t app_key_index, light_xyl_t xyl,
bool optional, generic_transition_time_t remaining_time,
uint32_t delay_time)
{
light_xyl_target_status_t msg;
ACCESS_OPCODE_BYTE(msg.opcode, MESH_MSG_LIGHT_XYL_TARGET_STATUS);
uint16_t msg_len;
if (optional)
{
msg_len = sizeof(light_xyl_target_status_t);
msg.remaining_time = remaining_time;
}
else
{
msg_len = MEMBER_OFFSET(light_xyl_target_status_t, remaining_time);
}
msg.xyl = xyl;
return light_xyl_server_send(pmodel_info, dst, (uint8_t *)&msg, msg_len, app_key_index,
delay_time);
}
static mesh_msg_send_cause_t light_xyl_delay_publish(const mesh_model_info_p pmodel_info,
light_xyl_t xyl,
uint32_t delay_time)
{
mesh_msg_send_cause_t ret = MESH_MSG_SEND_CAUSE_INVALID_DST;
if (mesh_model_pub_check(pmodel_info))
{
generic_transition_time_t remaining_time;
ret = light_xyl_status(pmodel_info, 0, 0, xyl, FALSE, remaining_time, delay_time);
}
return ret;
}
mesh_msg_send_cause_t light_xyl_publish(const mesh_model_info_p pmodel_info, light_xyl_t xyl)
{
return light_xyl_delay_publish(pmodel_info, xyl, 0);
}
#if !MODEL_ENABLE_DELAY_MSG_RSP
static void light_xyl_state_change_publish(const mesh_model_info_p pmodel_info, light_xyl_t xyl,
light_xyl_process_result_t result)
{
if (result.use_transition)
{
return ;
}
#if !MODEL_ENABLE_PUBLISH_ALL_TIME
if (result.state_changed)
#endif
{
light_xyl_delay_publish(pmodel_info, xyl, 0);
}
}
#endif
mesh_msg_send_cause_t light_xyl_default_status(mesh_model_info_p pmodel_info, uint16_t dst,
uint16_t app_key_index, light_xyl_t xyl, uint32_t delay_time)
{
light_xyl_default_status_t msg;
ACCESS_OPCODE_BYTE(msg.opcode, MESH_MSG_LIGHT_XYL_DEFAULT_STATUS);
msg.xyl = xyl;
return light_xyl_server_send(pmodel_info, dst, (uint8_t *)&msg, sizeof(msg), app_key_index,
delay_time);
}
mesh_msg_send_cause_t light_xyl_range_status(mesh_model_info_p pmodel_info, uint16_t dst,
uint16_t app_key_index, generic_stat_t status, uint16_t xyl_x_range_min, uint16_t xyl_x_range_max,
uint16_t xyl_y_range_min, uint16_t xyl_y_range_max, uint32_t delay_time)
{
light_xyl_range_status_t msg;
ACCESS_OPCODE_BYTE(msg.opcode, MESH_MSG_LIGHT_XYL_RANGE_STATUS);
msg.status_code = status;
msg.xyl_x_range_min = xyl_x_range_min;
msg.xyl_x_range_max = xyl_x_range_max;
msg.xyl_y_range_min = xyl_y_range_min;
msg.xyl_y_range_max = xyl_y_range_max;
return light_xyl_server_send(pmodel_info, dst, (uint8_t *)&msg, sizeof(msg), app_key_index,
delay_time);
}
static light_xyl_t get_present_xyl(const mesh_model_info_p pmodel_info)
{
light_xyl_server_get_t get_data = {0, 0, 0};
if (NULL != pmodel_info->model_data_cb)
{
pmodel_info->model_data_cb(pmodel_info, LIGHT_XYL_SERVER_GET, &get_data);
}
return get_data;
}
static int32_t light_xyl_trans_step_change(const mesh_model_info_p pmodel_info,
uint32_t type,
generic_transition_time_t total_time,
generic_transition_time_t remaining_time)
{
int32_t ret = MODEL_SUCCESS;
light_xyl_server_set_t set_data;
light_xyl_info_t *pxyl_info = pmodel_info->pargs;
if (NULL == pxyl_info)
{
return 0;
}
set_data.xyl = pxyl_info->target_xyl;
set_data.total_time = total_time;
set_data.remaining_time = remaining_time;
if (NULL != pmodel_info->model_data_cb)
{
ret = pmodel_info->model_data_cb(pmodel_info, LIGHT_XYL_SERVER_SET, &set_data);
}
if (0 == remaining_time.num_steps)
{
uint32_t delay_rsp_time = 0;
#if MODEL_ENABLE_DELAY_MSG_RSP
delay_rsp_time = pxyl_info->delay_pub_time;
#endif
light_xyl_t present_xyl = get_present_xyl(pmodel_info);
light_xyl_delay_publish(pmodel_info, present_xyl, delay_rsp_time);
}
return ret;
}
static light_xyl_t light_xyl_process(const mesh_model_info_p pmodel_info,
light_xyl_t target_xyl,
generic_transition_time_t trans_time,
light_xyl_process_result_t *presult)
{
light_xyl_t xyl_before_set = {0, 0, 0};
light_xyl_t xyl_after_set = {0, 0, 0};
/* get xyl before set */
xyl_before_set = get_present_xyl(pmodel_info);
xyl_after_set = xyl_before_set;
int32_t ret = MODEL_SUCCESS;
light_xyl_server_set_t trans_set_data;
trans_set_data.xyl = target_xyl;
trans_set_data.total_time = trans_time;
trans_set_data.remaining_time = trans_time;
if (NULL != pmodel_info->model_data_cb)
{
ret = pmodel_info->model_data_cb(pmodel_info, LIGHT_XYL_SERVER_SET, &trans_set_data);
}
if (GENERIC_TRANSITION_NUM_STEPS_IMMEDIATE != trans_time.num_steps)
{
if ((ret >= 0) && (MODEL_STOP_TRANSITION != ret))
{
if (NULL != presult)
{
presult->use_transition = TRUE;
}
generic_transition_timer_start(pmodel_info, GENERIC_TRANSITION_TYPE_LIGHT_XYL, trans_time,
light_xyl_trans_step_change);
}
#if MODEL_ENABLE_USER_STOP_TRANSITION_NOTIFICATION
else if (MODEL_STOP_TRANSITION == ret)
{
if (NULL != pmodel_info->model_data_cb)
{
ret = pmodel_info->model_data_cb(pmodel_info, GENERIC_TRANSITION_TYPE_LIGHT_XYL, &trans_set_data);
}
}
#endif
}
else
{
/* get xyl after set */
xyl_after_set = get_present_xyl(pmodel_info);
}
if ((xyl_before_set.xyl_lightness != xyl_after_set.xyl_lightness) &&
(xyl_before_set.xyl_x != xyl_after_set.xyl_x) &&
(xyl_before_set.xyl_y != xyl_after_set.xyl_y))
{
if (NULL != presult)
{
presult->state_changed = TRUE;
}
}
return xyl_after_set;
}
static int32_t light_xyl_delay_execution(mesh_model_info_t *pmodel_info, uint32_t delay_type)
{
switch (delay_type)
{
case DELAY_EXECUTION_TYPE_LIGHT_XYL:
{
light_xyl_info_t *pxyl_info = pmodel_info->pargs;
if (NULL == pxyl_info)
{
return 0;
}
light_xyl_process_result_t result =
{
.state_changed = FALSE,
.use_transition = FALSE
};
generic_transition_time_t trans_time;
light_xyl_t target_xyl;
pxyl_info->delay_time = 0;
target_xyl = pxyl_info->target_xyl;
trans_time = pxyl_info->trans_time;
light_xyl_t present_xyl = light_xyl_process(pmodel_info, target_xyl, trans_time, &result);
#if MODEL_ENABLE_DELAY_MSG_RSP
if (!result.use_transition)
{
#if !MODEL_ENABLE_PUBLISH_ALL_TIME
if (result.state_changed)
#endif
{
uint32_t delay_rsp_time = pxyl_info->delay_pub_time;
light_xyl_delay_publish(pmodel_info, present_xyl, delay_rsp_time);
}
}
#else
light_xyl_state_change_publish(pmodel_info, present_xyl, result);
#endif
}
break;
default:
break;
}
return 0;
}
static bool light_xyl_server_receive(mesh_msg_p pmesh_msg)
{
bool ret = TRUE;
uint8_t *pbuffer = pmesh_msg->pbuffer + pmesh_msg->msg_offset;
mesh_model_info_p pmodel_info = pmesh_msg->pmodel_info;
switch (pmesh_msg->access_opcode)
{
case MESH_MSG_LIGHT_XYL_GET:
if (pmesh_msg->msg_len == sizeof(light_xyl_get_t))
{
light_xyl_info_t *pxyl_info = pmodel_info->pargs;
generic_transition_time_t remaining_time;
if (pxyl_info->delay_time > 0)
{
remaining_time = pxyl_info->trans_time;
}
else
{
remaining_time = generic_transition_time_get(pmodel_info, GENERIC_TRANSITION_TYPE_LIGHT_XYL);
}
uint32_t delay_rsp_time = 0;
#if MODEL_ENABLE_DELAY_MSG_RSP
delay_rsp_time = delay_msg_get_rsp_delay(pmesh_msg->dst);
#endif
light_xyl_status(pmodel_info, pmesh_msg->src, pmesh_msg->app_key_index,
get_present_xyl(pmodel_info),
(GENERIC_TRANSITION_NUM_STEPS_IMMEDIATE == remaining_time.num_steps) ? FALSE : TRUE,
remaining_time, delay_rsp_time);
}
break;
case MESH_MSG_LIGHT_XYL_SET:
case MESH_MSG_LIGHT_XYL_SET_UNACK:
{
light_xyl_set_t *pmsg = (light_xyl_set_t *)pbuffer;
generic_transition_time_t trans_time = {GENERIC_TRANSITION_NUM_STEPS_IMMEDIATE, 0};
uint32_t delay_time = 0;
if (pmesh_msg->msg_len == MEMBER_OFFSET(light_xyl_set_t, trans_time))
{
if (NULL != pmodel_info->model_data_cb)
{
pmodel_info->model_data_cb(pmodel_info, LIGHT_XYL_SERVER_GET_DEFAULT_TRANSITION_TIME,
&trans_time);
}
}
else if (pmesh_msg->msg_len == sizeof(light_xyl_set_t))
{
trans_time = pmsg->trans_time;
delay_time = pmsg->delay * DELAY_EXECUTION_STEP_RESOLUTION;
}
if (IS_GENERIC_TRANSITION_STEPS_VALID(trans_time.num_steps))
{
light_xyl_info_t *pxyl_info = pmodel_info->pargs;
light_xyl_server_get_range_t range = {0, 0, 0, 0};
if (NULL != pmodel_info->model_data_cb)
{
pmodel_info->model_data_cb(pmodel_info, LIGHT_XYL_SERVER_GET_RANGE, &range);
}
pxyl_info->target_xyl.xyl_lightness = pmsg->xyl.xyl_lightness;
if ((0 != range.xyl_x_range_min) && (0 != range.xyl_x_range_max))
{
/* need to clamp xyl_x */
pxyl_info->target_xyl.xyl_x = CLAMP(pmsg->xyl.xyl_x, range.xyl_x_range_min, range.xyl_x_range_max);
}
else
{
pxyl_info->target_xyl.xyl_x = pmsg->xyl.xyl_x;
}
if ((0 != range.xyl_y_range_min) && (0 != range.xyl_y_range_max))
{
/* need to clamp xyl_y */
pxyl_info->target_xyl.xyl_y = CLAMP(pmsg->xyl.xyl_y, range.xyl_y_range_min, range.xyl_y_range_max);
}
else
{
pxyl_info->target_xyl.xyl_y = pmsg->xyl.xyl_y;
}
pxyl_info->tid = pmsg->tid;
pxyl_info->trans_time = trans_time;
pxyl_info->delay_time = delay_time;
light_xyl_t present_xyl;
light_xyl_process_result_t result =
{
.state_changed = FALSE,
.use_transition = FALSE
};
if (delay_time > 0)
{
result.use_transition = TRUE;
present_xyl = get_present_xyl(pmodel_info);
delay_execution_timer_start(pmodel_info, DELAY_EXECUTION_TYPE_LIGHT_XYL, delay_time,
light_xyl_delay_execution);
}
else
{
present_xyl = light_xyl_process(pmodel_info, pxyl_info->target_xyl,
trans_time, &result);
}
uint32_t delay_rsp_time = 0;
#if MODEL_ENABLE_DELAY_MSG_RSP
delay_rsp_time = delay_msg_get_rsp_delay(pmesh_msg->dst);
#endif
if (pmesh_msg->access_opcode == MESH_MSG_LIGHT_XYL_SET)
{
light_xyl_status(pmodel_info, pmesh_msg->src, pmesh_msg->app_key_index,
present_xyl,
(GENERIC_TRANSITION_NUM_STEPS_IMMEDIATE == trans_time.num_steps) ? FALSE : TRUE,
trans_time, delay_rsp_time);
}
#if MODEL_ENABLE_DELAY_MSG_RSP
bool ack = (pmesh_msg->access_opcode == MESH_MSG_LIGHT_XYL_SET_UNACK) ? FALSE : TRUE;
if (!result.use_transition)
{
#if !MODEL_ENABLE_PUBLISH_ALL_TIME
if (result.state_changed)
#endif
{
uint32_t delay_pub_time = delay_msg_get_trans_delay(delay_time, trans_time, delay_rsp_time, TRUE,
ack);
light_xyl_delay_publish(pmodel_info, present_xyl, delay_pub_time);
}
}
else
{
pxyl_info->delay_pub_time = delay_msg_get_trans_delay(delay_time, trans_time, delay_rsp_time,
FALSE, ack);
}
#else
light_xyl_state_change_publish(pmodel_info, present_xyl, result);
#endif
}
}
break;
case MESH_MSG_LIGHT_XYL_TARGET_GET:
if (pmesh_msg->msg_len == sizeof(light_xyl_target_get_t))
{
light_xyl_info_t *pxyl_info = pmodel_info->pargs;
generic_transition_time_t remaining_time;
if (pxyl_info->delay_time > 0)
{
remaining_time = pxyl_info->trans_time;
}
else
{
remaining_time = generic_transition_time_get(pmodel_info, GENERIC_TRANSITION_TYPE_LIGHT_XYL);
}
uint32_t delay_rsp_time = 0;
#if MODEL_ENABLE_DELAY_MSG_RSP
delay_rsp_time = delay_msg_get_rsp_delay(pmesh_msg->dst);
#endif
light_xyl_target_status(pmodel_info, pmesh_msg->src, pmesh_msg->app_key_index,
pxyl_info->target_xyl,
(GENERIC_TRANSITION_NUM_STEPS_IMMEDIATE == remaining_time.num_steps) ? FALSE : TRUE,
remaining_time, delay_rsp_time);
}
break;
case MESH_MSG_LIGHT_XYL_DEFAULT_GET:
if (pmesh_msg->msg_len == sizeof(light_xyl_default_get_t))
{
light_xyl_server_get_default_t default_data = {0};
if (NULL != pmodel_info->model_data_cb)
{
pmodel_info->model_data_cb(pmodel_info, LIGHT_XYL_SERVER_GET_DEFAULT,
&default_data);
}
uint32_t delay_rsp_time = 0;
#if MODEL_ENABLE_DELAY_MSG_RSP
delay_rsp_time = delay_msg_get_rsp_delay(pmesh_msg->dst);
#endif
light_xyl_default_status(pmodel_info, pmesh_msg->src,
pmesh_msg->app_key_index, default_data, delay_rsp_time);
}
break;
case MESH_MSG_LIGHT_XYL_RANGE_GET:
if (pmesh_msg->msg_len == sizeof(light_xyl_range_get_t))
{
light_xyl_server_get_range_t range_data = {0, 0, 0, 0};
if (NULL != pmodel_info->model_data_cb)
{
pmodel_info->model_data_cb(pmodel_info, LIGHT_XYL_SERVER_GET_RANGE,
&range_data);
}
uint32_t delay_rsp_time = 0;
#if MODEL_ENABLE_DELAY_MSG_RSP
delay_rsp_time = delay_msg_get_rsp_delay(pmesh_msg->dst);
#endif
light_xyl_range_status(pmodel_info, pmesh_msg->src, pmesh_msg->app_key_index,
GENERIC_STAT_SUCCESS, range_data.xyl_x_range_min, range_data.xyl_x_range_max,
range_data.xyl_y_range_min, range_data.xyl_y_range_max,
delay_rsp_time);
}
break;
default:
ret = FALSE;
break;
}
return ret;
}
static int32_t light_xyl_server_publish(mesh_model_info_p pmodel_info, bool retrans)
{
generic_transition_time_t remaining_time;
light_xyl_status(pmodel_info, 0, 0, get_present_xyl(pmodel_info), FALSE,
remaining_time, 0);
return 0;
}
#if MESH_MODEL_ENABLE_DEINIT
static void light_xyl_server_deinit(mesh_model_info_t *pmodel_info)
{
if (pmodel_info->model_receive == light_xyl_server_receive)
{
/* stop delay execution */
delay_execution_timer_stop(pmodel_info, DELAY_EXECUTION_TYPE_LIGHT_XYL);
/* stop step transition */
generic_transition_timer_stop(pmodel_info, GENERIC_TRANSITION_TYPE_LIGHT_XYL);
/* now we can remove */
if (NULL != pmodel_info->pargs)
{
plt_free(pmodel_info->pargs, RAM_TYPE_DATA_ON);
pmodel_info->pargs = NULL;
}
pmodel_info->model_receive = NULL;
}
}
#endif
bool light_xyl_server_reg(uint8_t element_index, mesh_model_info_t *pmodel_info)
{
if (NULL == pmodel_info)
{
return FALSE;
}
pmodel_info->model_id = MESH_MODEL_LIGHT_XYL_SERVER;
if (NULL == pmodel_info->model_receive)
{
light_xyl_info_t *pxyl_info = plt_malloc(sizeof(light_xyl_info_t), RAM_TYPE_DATA_ON);
if (NULL == pxyl_info)
{
printe("light_xyl_server_reg: fail to allocate memory for the new model extension data!");
return FALSE;
}
memset(pxyl_info, 0, sizeof(light_xyl_info_t));
pmodel_info->pargs = pxyl_info;
pmodel_info->model_receive = light_xyl_server_receive;
if (NULL == pmodel_info->model_data_cb)
{
printw("light_xyl_server_reg: missing model data process callback!");
}
#if MESH_MODEL_ENABLE_DEINIT
pmodel_info->model_deinit = light_xyl_server_deinit;
#endif
}
if (NULL == pmodel_info->model_pub_cb)
{
pmodel_info->model_pub_cb = light_xyl_server_publish;
}
generic_transition_time_init();
delay_execution_init();
return mesh_model_reg(element_index, pmodel_info);
}
|
64162.c |
/*
* Odyssey.
*
* Scalable PostgreSQL connection pooler.
*/
#include <stdlib.h>
#include <stdarg.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <inttypes.h>
#include <assert.h>
#include <machinarium.h>
#include <kiwi.h>
#include <odyssey.h>
void
od_router_init(od_router_t *router)
{
pthread_mutex_init(&router->lock, NULL);
od_rules_init(&router->rules);
od_route_pool_init(&router->route_pool);
router->clients = 0;
}
void
od_router_free(od_router_t *router)
{
od_route_pool_free(&router->route_pool);
od_rules_free(&router->rules);
pthread_mutex_destroy(&router->lock);
}
inline int
od_router_foreach(od_router_t *router,
od_route_pool_cb_t callback,
void **argv)
{
od_router_lock(router);
int rc;
rc = od_route_pool_foreach(&router->route_pool, callback, argv);
od_router_unlock(router);
return rc;
}
static inline int
od_router_kill_clients_cb(od_route_t *route, void **argv)
{
(void)argv;
if (! route->rule->obsolete)
return 0;
od_route_lock(route);
od_route_kill_client_pool(route);
od_route_unlock(route);
return 0;
}
int
od_router_reconfigure(od_router_t *router, od_rules_t *rules)
{
od_router_lock(router);
int updates;
updates = od_rules_merge(&router->rules, rules);
if (updates > 0) {
od_route_pool_foreach(&router->route_pool, od_router_kill_clients_cb,
NULL);
}
od_router_unlock(router);
return updates;
}
static inline int
od_router_expire_server_cb(od_server_t *server, void **argv)
{
od_route_t *route = server->route;
od_list_t *expire_list = argv[0];
int *count = argv[1];
/* remove server for server pool */
od_server_pool_set(&route->server_pool, server, OD_SERVER_UNDEF);
od_list_append(expire_list, &server->link);
(*count)++;
return 0;
}
static inline int
od_router_expire_server_tick_cb(od_server_t *server, void **argv)
{
od_route_t *route = server->route;
od_list_t *expire_list = argv[0];
int *count = argv[1];
/* advance idle time for 1 sec */
if (server->idle_time < route->rule->pool_ttl) {
server->idle_time++;
return 0;
}
/* remove server for server pool */
od_server_pool_set(&route->server_pool, server, OD_SERVER_UNDEF);
/* add to expire list */
od_list_append(expire_list, &server->link);
(*count)++;
return 0;
}
static inline int
od_router_expire_cb(od_route_t *route, void **argv)
{
od_route_lock(route);
/* expire by config obsoletion */
if (route->rule->obsolete && !od_client_pool_total(&route->client_pool))
{
od_server_pool_foreach(&route->server_pool,
OD_SERVER_IDLE,
od_router_expire_server_cb,
argv);
od_route_unlock(route);
return 0;
}
if (! route->rule->pool_ttl) {
od_route_unlock(route);
return 0;
}
od_server_pool_foreach(&route->server_pool,
OD_SERVER_IDLE,
od_router_expire_server_tick_cb,
argv);
od_route_unlock(route);
return 0;
}
int
od_router_expire(od_router_t *router, od_list_t *expire_list)
{
int count = 0;
void *argv[] = { expire_list, &count };
od_router_foreach(router, od_router_expire_cb, argv);
return count;
}
static inline int
od_router_gc_cb(od_route_t *route, void **argv)
{
od_route_pool_t *pool = argv[0];
od_route_lock(route);
if (od_server_pool_total(&route->server_pool) > 0 ||
od_client_pool_total(&route->client_pool) > 0)
goto done;
if (!od_route_is_dynamic(route) && !route->rule->obsolete)
goto done;
/* remove route from route pool */
assert(pool->count > 0);
pool->count--;
od_list_unlink(&route->link);
od_route_unlock(route);
/* unref route rule and free route object */
od_rules_unref(route->rule);
od_route_free(route);
return 0;
done:
od_route_unlock(route);
return 0;
}
void
od_router_gc(od_router_t *router)
{
void *argv[] = { &router->route_pool };
od_router_foreach(router, od_router_gc_cb, argv);
}
void
od_router_stat(od_router_t *router,
uint64_t prev_time_us,
int prev_update,
od_route_pool_stat_cb_t callback,
void **argv)
{
od_router_lock(router);
od_route_pool_stat(&router->route_pool, prev_time_us, prev_update,
callback, argv);
od_router_unlock(router);
}
od_router_status_t
od_router_route(od_router_t *router, od_config_t *config, od_client_t *client)
{
kiwi_be_startup_t *startup = &client->startup;
/* match route */
assert(startup->database.value_len);
assert(startup->user.value_len);
od_router_lock(router);
/* match latest version of route rule */
od_rule_t *rule;
rule = od_rules_forward(&router->rules, startup->database.value,
startup->user.value);
if (rule == NULL) {
od_router_unlock(router);
return OD_ROUTER_ERROR_NOT_FOUND;
}
/* force settings required by route */
od_route_id_t id = {
.database = startup->database.value,
.user = startup->user.value,
.database_len = startup->database.value_len,
.user_len = startup->user.value_len,
.physical_rep = false
};
if (rule->storage_db) {
id.database = rule->storage_db;
id.database_len = strlen(rule->storage_db) + 1;
}
if (rule->storage_user) {
id.user = rule->storage_user;
id.user_len = strlen(rule->storage_user) + 1;
}
if (rule->storage->storage_type == OD_RULE_STORAGE_REPLICATION_LOGICAL &&
startup->replication.value_len != 0) {
switch (startup->replication.value[0]) {
case 'o': /* on */
case 't': /* true */
case 'y': /* yes */
case '1': /* 1 */
id.physical_rep = true;
break;
default:
break;
}
}
/* ensure global client_max limit */
if (config->client_max_set && router->clients >= config->client_max) {
od_router_unlock(router);
return OD_ROUTER_ERROR_LIMIT;
}
/* match or create dynamic route */
od_route_t *route;
route = od_route_pool_match(&router->route_pool, &id, rule);
if (route == NULL) {
int is_shared;
is_shared = od_config_is_multi_workers(config);
route = od_route_pool_new(&router->route_pool, is_shared, &id, rule);
if (route == NULL) {
od_router_unlock(router);
return OD_ROUTER_ERROR;
}
}
router->clients++;
od_rules_ref(rule);
od_route_lock(route);
od_router_unlock(router);
/* ensure route client_max limit */
if (rule->client_max_set &&
od_client_pool_total(&route->client_pool) >= rule->client_max) {
od_route_unlock(route);
od_router_lock(router);
router->clients--;
od_rules_unref(rule);
od_router_unlock(router);
return OD_ROUTER_ERROR_LIMIT_ROUTE;
}
/* add client to route client pool */
od_client_pool_set(&route->client_pool, client, OD_CLIENT_PENDING);
client->rule = rule;
client->route = route;
od_route_unlock(route);
return OD_ROUTER_OK;
}
void
od_router_unroute(od_router_t *router, od_client_t *client)
{
/* detach client from route */
assert(client->route);
assert(client->server == NULL);
od_router_lock(router);
assert(router->clients > 0);
router->clients--;
od_router_unlock(router);
od_route_t *route = client->route;
od_route_lock(route);
od_client_pool_set(&route->client_pool, client, OD_CLIENT_UNDEF);
client->route = NULL;
od_route_unlock(route);
}
od_router_status_t
od_router_attach(od_router_t *router, od_config_t *config, od_client_t *client)
{
(void)router;
od_route_t *route = client->route;
assert(route != NULL);
od_route_lock(route);
/* enqueue client (pending -> queue) */
od_client_pool_set(&route->client_pool, client, OD_CLIENT_QUEUE);
/* get client server from route server pool */
od_server_t *server;
for (;;)
{
server = od_server_pool_next(&route->server_pool, OD_SERVER_IDLE);
if (server)
goto attach;
/* always start new connection, if pool_size is zero */
if (route->rule->pool_size == 0)
break;
/* maybe start new connection */
if (od_server_pool_total(&route->server_pool) < route->rule->pool_size)
break;
od_route_unlock(route);
/* pool_size limit implementation.
*
* If the limit reached, wait wakeup condition for
* pool_timeout milliseconds.
*
* The condition triggered when a server connection
* put into idle state by DETACH events.
*/
uint32_t timeout = route->rule->pool_timeout;
if (timeout == 0)
timeout = UINT32_MAX;
int rc;
rc = od_route_wait(route, timeout);
if (rc == -1)
return OD_ROUTER_ERROR_TIMEDOUT;
od_route_lock(route);
}
od_route_unlock(route);
/* create new server object */
server = od_server_allocate();
if (server == NULL)
return OD_ROUTER_ERROR;
od_id_generate(&server->id, "s");
server->global = client->global;
server->route = route;
od_route_lock(route);
/* xxx: maybe retry check for free server again */
attach:
od_server_pool_set(&route->server_pool, server, OD_SERVER_ACTIVE);
od_client_pool_set(&route->client_pool, client, OD_CLIENT_ACTIVE);
client->server = server;
server->client = client;
server->idle_time = 0;
server->key_client = client->key;
od_route_unlock(route);
/* attach server io to clients machine context */
if (server->io.io && od_config_is_multi_workers(config))
od_io_attach(&server->io);
return OD_ROUTER_OK;
}
void
od_router_detach(od_router_t *router, od_config_t *config, od_client_t *client)
{
(void)router;
od_route_t *route = client->route;
assert(route != NULL);
/* detach from current machine event loop */
od_server_t *server = client->server;
if (od_config_is_multi_workers(config))
od_io_detach(&server->io);
od_route_lock(route);
client->server = NULL;
server->client = NULL;
od_server_pool_set(&route->server_pool, server, OD_SERVER_IDLE);
od_client_pool_set(&route->client_pool, client, OD_CLIENT_PENDING);
/* notify waiters */
if (route->client_pool.count_queue > 0)
od_route_signal(route);
od_route_unlock(route);
}
void
od_router_close(od_router_t *router, od_client_t *client)
{
(void)router;
od_route_t *route = client->route;
assert(route != NULL);
od_server_t *server = client->server;
od_backend_close_connection(server);
od_route_lock(route);
od_client_pool_set(&route->client_pool, client, OD_CLIENT_PENDING);
od_server_pool_set(&route->server_pool, server, OD_SERVER_UNDEF);
client->server = NULL;
server->client = NULL;
server->route = NULL;
od_route_unlock(route);
assert(server->io.io == NULL);
od_server_free(server);
}
static inline int
od_router_cancel_cmp(od_server_t *server, void **argv)
{
return kiwi_key_cmp(&server->key_client, argv[0]);
}
static inline int
od_router_cancel_cb(od_route_t *route, void **argv)
{
od_route_lock(route);
od_server_t *server;
server = od_server_pool_foreach(&route->server_pool, OD_SERVER_ACTIVE,
od_router_cancel_cmp, argv);
if (server)
{
od_router_cancel_t *cancel = argv[1];
cancel->id = server->id;
cancel->key = server->key;
cancel->storage = od_rules_storage_copy(route->rule->storage);
od_route_unlock(route);
if (cancel->storage == NULL)
return -1;
return 1;
}
od_route_unlock(route);
return 0;
}
od_router_status_t
od_router_cancel(od_router_t *router, kiwi_key_t *key, od_router_cancel_t *cancel)
{
/* match server by client forged key */
void *argv[] = { key, cancel };
int rc;
rc = od_router_foreach(router, od_router_cancel_cb, argv);
if (rc <= 0)
return OD_ROUTER_ERROR_NOT_FOUND;
return OD_ROUTER_OK;
}
static inline int
od_router_kill_cb(od_route_t *route, void **argv)
{
od_route_lock(route);
od_route_kill_client(route, argv[0]);
od_route_unlock(route);
return 0;
}
void
od_router_kill(od_router_t *router, od_id_t *id)
{
void *argv[] = { id };
od_router_foreach(router, od_router_kill_cb, argv);
}
|
252895.c | //*****************************************************************************
//
// bl_usbfuncs.c - The subset of USB library functions required by the USB DFU
// boot loader.
//
// Copyright (c) 2008-2015 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.2.111 of the Tiva Firmware Development Package.
//
//*****************************************************************************
#include <stdbool.h>
#include <stdint.h>
#include "inc/hw_types.h"
#include "inc/hw_memmap.h"
#include "inc/hw_usb.h"
#include "inc/hw_sysctl.h"
#include "inc/hw_nvic.h"
#include "inc/hw_ints.h"
#include "inc/hw_gpio.h"
#include "bl_config.h"
#include "boot_loader/bl_usbfuncs.h"
//*****************************************************************************
//
//! \addtogroup bl_usb_api
//! @{
//
//*****************************************************************************
#if defined(USB_ENABLE_UPDATE) || defined(DOXYGEN)
//*****************************************************************************
//
// Local functions prototypes.
//
//*****************************************************************************
static void USBDGetStatus(tUSBRequest *pUSBRequest);
static void USBDClearFeature(tUSBRequest *pUSBRequest);
static void USBDSetFeature(tUSBRequest *pUSBRequest);
static void USBDSetAddress(tUSBRequest *pUSBRequest);
static void USBDGetDescriptor(tUSBRequest *pUSBRequest);
static void USBDSetDescriptor(tUSBRequest *pUSBRequest);
static void USBDGetConfiguration(tUSBRequest *pUSBRequest);
static void USBDSetConfiguration(tUSBRequest *pUSBRequest);
static void USBDGetInterface(tUSBRequest *pUSBRequest);
static void USBDSetInterface(tUSBRequest *pUSBRequest);
static void USBDEP0StateTx(void);
static int32_t USBDStringIndexFromRequest(uint16_t ui16Lang,
uint16_t ui16Index);
//*****************************************************************************
//
// This structure holds the full state for the device enumeration.
//
//*****************************************************************************
typedef struct
{
//
// The devices current address, this also has a change pending bit in the
// MSB of this value specified by DEV_ADDR_PENDING.
//
volatile uint32_t ui32DevAddress;
//
// This holds the current active configuration for this device.
//
uint32_t ui32Configuration;
//
// This holds the current alternate interface for this device. We only have
// 1 interface so only need to hold 1 setting.
//
uint8_t ui8AltSetting;
//
// This is the pointer to the current data being sent out or received
// on endpoint zero.
//
uint8_t *pui8EP0Data;
//
// This is the number of bytes that remain to be sent from or received
// into the g_sUSBDeviceState.pui8EP0Data data buffer.
//
volatile uint32_t ui32EP0DataRemain;
//
// The amount of data being sent/received due to a custom request.
//
uint32_t ui32OUTDataSize;
//
// Holds the current device status.
//
uint8_t ui8Status;
//
// This flag indicates whether or not remote wakeup signalling is in
// progress.
//
bool bRemoteWakeup;
//
// During remote wakeup signalling, this counter is used to track the
// number of milliseconds since the signalling was initiated.
//
uint8_t ui8RemoteWakeupCount;
}
tDeviceState;
//*****************************************************************************
//
// The states for endpoint zero during enumeration.
//
//*****************************************************************************
typedef enum
{
//
// The USB device is waiting on a request from the host controller on
// endpoint zero.
//
USB_STATE_IDLE,
//
// The USB device is sending data back to the host due to an IN request.
//
USB_STATE_TX,
//
// The USB device is receiving data from the host due to an OUT
// request from the host.
//
USB_STATE_RX,
//
// The USB device has completed the IN or OUT request and is now waiting
// for the host to acknowledge the end of the IN/OUT transaction. This
// is the status phase for a USB control transaction.
//
USB_STATE_STATUS,
//
// This endpoint has signaled a stall condition and is waiting for the
// stall to be acknowledged by the host controller.
//
USB_STATE_STALL
}
tEP0State;
//*****************************************************************************
//
// Define the max packet size for endpoint zero.
//
//*****************************************************************************
#define EP0_MAX_PACKET_SIZE 64
//*****************************************************************************
//
// This is a flag used with g_sUSBDeviceState.ui32DevAddress to indicate that a
// device address change is pending.
//
//*****************************************************************************
#define DEV_ADDR_PENDING 0x80000000
//*****************************************************************************
//
// This label defines the default configuration number to use after a bus
// reset.
//
//*****************************************************************************
#define DEFAULT_CONFIG_ID 1
//*****************************************************************************
//
// This label defines the number of milliseconds that the remote wakeup signal
// must remain asserted before removing it. Section 7.1.7.7 of the USB 2.0 spec
// states that "the remote wakeup device must hold the resume signaling for at
// least 1ms but for no more than 15ms" so 10mS seems a reasonable choice.
//
//*****************************************************************************
#define REMOTE_WAKEUP_PULSE_MS 10
//*****************************************************************************
//
// This label defines the number of milliseconds between the point where we
// assert the remote wakeup signal and calling the client back to tell it that
// bus operation has been resumed. This value is based on the timings provided
// in section 7.1.7.7 of the USB 2.0 specification which indicates that the host
// (which takes over resume signalling when the device's initial signal is
// detected) must hold the resume signalling for at least 20mS.
//
//*****************************************************************************
#define REMOTE_WAKEUP_READY_MS 20
//*****************************************************************************
//
// The buffer for reading data coming into EP0
//
//*****************************************************************************
static uint8_t g_pui8DataBufferIn[EP0_MAX_PACKET_SIZE];
//*****************************************************************************
//
// This global holds the current state information for the USB device.
//
//*****************************************************************************
static volatile tDeviceState g_sUSBDeviceState;
//*****************************************************************************
//
// This global holds the current state of endpoint zero.
//
//*****************************************************************************
static volatile tEP0State g_eUSBDEP0State = USB_STATE_IDLE;
//*****************************************************************************
//
// Function table to handle standard requests.
//
//*****************************************************************************
static const tStdRequest g_ppfnUSBDStdRequests[] =
{
USBDGetStatus,
USBDClearFeature,
0,
USBDSetFeature,
0,
USBDSetAddress,
USBDGetDescriptor,
USBDSetDescriptor,
USBDGetConfiguration,
USBDSetConfiguration,
USBDGetInterface,
USBDSetInterface,
};
//*****************************************************************************
//
// Amount to shift the RX interrupt sources by in the flags used in the
// interrupt calls.
//
//*****************************************************************************
#define USB_INT_RX_SHIFT 8
//*****************************************************************************
//
// Amount to shift the status interrupt sources by in the flags used in the
// interrupt calls.
//
//*****************************************************************************
#define USB_INT_STATUS_SHIFT 24
//*****************************************************************************
//
// Amount to shift the RX endpoint status sources by in the flags used in the
// calls.
//
//*****************************************************************************
#define USB_RX_EPSTATUS_SHIFT 16
//*****************************************************************************
//
// Converts from an endpoint specifier to the offset of the endpoint's
// control/status registers.
//
//*****************************************************************************
#define EP_OFFSET(Endpoint) (Endpoint - 0x10)
//*****************************************************************************
//
// Retrieves data from endpoint 0's FIFO.
//
// \param pui8Data is a pointer to the data area used to return the data from
// the FIFO.
// \param pui32Size is initially the size of the buffer passed into this call
// via the \e pui8Data parameter. It will be set to the amount of data
// returned in the buffer.
//
// This function will return the data from the FIFO for endpoint 0.
// The \e pui32Size parameter should indicate the size of the buffer passed in
// the \e pui32Data parameter. The data in the \e pui32Size parameter will be
// changed to match the amount of data returned in the \e pui8Data parameter.
// If a zero byte packet was received this call will not return a error but
// will instead just return a zero in the \e pui32Size parameter. The only
// error case occurs when there is no data packet available.
//
// \return This call will return 0, or -1 if no packet was received.
//
//*****************************************************************************
int32_t
USBEndpoint0DataGet(uint8_t *pui8Data, uint32_t *pui32Size)
{
uint32_t ui32ByteCount;
//
// Don't allow reading of data if the RxPktRdy bit is not set.
//
if((HWREGH(USB0_BASE + USB_O_CSRL0) & USB_CSRL0_RXRDY) == 0)
{
//
// Can't read the data because none is available.
//
*pui32Size = 0;
//
// Return a failure since there is no data to read.
//
return(-1);
}
//
// Get the byte count in the FIFO.
//
ui32ByteCount = HWREGH(USB0_BASE + USB_O_COUNT0 + USB_EP_0);
//
// Determine how many bytes we will actually copy.
//
ui32ByteCount = (ui32ByteCount < *pui32Size) ? ui32ByteCount : *pui32Size;
//
// Return the number of bytes we are going to read.
//
*pui32Size = ui32ByteCount;
//
// Read the data out of the FIFO.
//
for(; ui32ByteCount > 0; ui32ByteCount--)
{
//
// Read a byte at a time from the FIFO.
//
*pui8Data++ = HWREGB(USB0_BASE + USB_O_FIFO0 + (USB_EP_0 >> 2));
}
//
// Success.
//
return(0);
}
//*****************************************************************************
//
// Acknowledge that data was read from endpoint 0's FIFO.
//
// \param bIsLastPacket indicates if this is the last packet.
//
// This function acknowledges that the data was read from the endpoint 0's
// FIFO. The \e bIsLastPacket parameter is set to a \b true value if this is
// the last in a series of data packets. This call can be used if processing
// is required between reading the data and acknowledging that the data has
// been read.
//
// \return None.
//
//*****************************************************************************
void
USBDevEndpoint0DataAck(bool bIsLastPacket)
{
//
// Clear RxPktRdy, and optionally DataEnd, on endpoint zero.
//
HWREGB(USB0_BASE + USB_O_CSRL0) =
USB_CSRL0_RXRDYC | (bIsLastPacket ? USB_CSRL0_DATAEND : 0);
}
//*****************************************************************************
//
// Puts data into endpoint 0's FIFO.
//
// \param pui8Data is a pointer to the data area used as the source for the
// data to put into the FIFO.
// \param ui32Size is the amount of data to put into the FIFO.
//
// This function will put the data from the \e pui8Data parameter into the FIFO
// for endpoint 0. If a packet is already pending for transmission then
// this call will not put any of the data into the FIFO and will return -1.
//
// \return This call will return 0 on success, or -1 to indicate that the FIFO
// is in use and cannot be written.
//
//*****************************************************************************
int32_t
USBEndpoint0DataPut(uint8_t *pui8Data, uint32_t ui32Size)
{
//
// Don't allow transmit of data if the TxPktRdy bit is already set.
//
if(HWREGB(USB0_BASE + USB_O_CSRL0 + USB_EP_0) & USB_CSRL0_TXRDY)
{
return(-1);
}
//
// Write the data to the FIFO.
//
for(; ui32Size > 0; ui32Size--)
{
HWREGB(USB0_BASE + USB_O_FIFO0 + (USB_EP_0 >> 2)) = *pui8Data++;
}
//
// Success.
//
return(0);
}
//*****************************************************************************
//
// Starts the transfer of data from endpoint 0's FIFO.
//
// \param ui32TransType is set to indicate what type of data is being sent.
//
// This function will start the transfer of data from the FIFO for
// endpoint 0. This is necessary if the \b USB_EP_AUTO_SET bit was not enabled
// for the endpoint. Setting the \e ui32TransType parameter will allow the
// appropriate signaling on the USB bus for the type of transaction being
// requested. The \e ui32TransType parameter should be one of the following:
//
// - USB_TRANS_OUT for OUT transaction on any endpoint in host mode.
// - USB_TRANS_IN for IN transaction on any endpoint in device mode.
// - USB_TRANS_IN_LAST for the last IN transactions on endpoint zero in a
// sequence of IN transactions.
// - USB_TRANS_SETUP for setup transactions on endpoint zero.
// - USB_TRANS_STATUS for status results on endpoint zero.
//
// \return This call will return 0 on success, or -1 if a transmission is
// already in progress.
//
//*****************************************************************************
int32_t
USBEndpoint0DataSend(uint32_t ui32TransType)
{
//
// Don't allow transmit of data if the TxPktRdy bit is already set.
//
if(HWREGB(USB0_BASE + USB_O_CSRL0 + USB_EP_0) & USB_CSRL0_TXRDY)
{
return(-1);
}
//
// Set TxPktRdy in order to send the data.
//
HWREGB(USB0_BASE + USB_O_CSRL0 + USB_EP_0) = ui32TransType & 0xff;
//
// Success.
//
return(0);
}
#if defined(USB_VBUS_CONFIG) || defined(USB_ID_CONFIG) || \
defined(USB_DP_CONFIG) || defined(USB_DM_CONFIG) || defined(DOXYGEN)
//*****************************************************************************
//
//! Initialize the pins used by USB functions.
//!
//! This function configures the pins for USB functions depending on defines
//! from the bl_config.h file.
//!
//! \return None.
//
//*****************************************************************************
void
USBConfigurePins(void)
{
//
// Enable the clocks to the GPIOs.
//
HWREG(SYSCTL_RCGCGPIO) |=
(0x0 |
#if defined(USB_VBUS_CONFIG)
USB_VBUS_PERIPH |
#endif
#if defined(USB_ID_CONFIG)
USB_ID_PERIPH |
#endif
#if defined(USB_DP_CONFIG)
USB_DP_PERIPH |
#endif
#if defined(USB_DM_CONFIG)
USB_DM_PERIPH
#endif
);
//
// Wait for the Peripherals to be Ready before accessing the register
// address space.
//
while((HWREG(SYSCTL_PRGPIO) &
(0x0 |
#if defined(USB_VBUS_CONFIG)
USB_VBUS_PERIPH |
#endif
#if defined(USB_ID_CONFIG)
USB_ID_PERIPH |
#endif
#if defined(USB_DP_CONFIG)
USB_DP_PERIPH |
#endif
#if defined(USB_DM_CONFIG)
USB_DM_PERIPH
#endif
)) !=
(0x0 |
#if defined(USB_VBUS_CONFIG)
USB_VBUS_PERIPH |
#endif
#if defined(USB_ID_CONFIG)
USB_ID_PERIPH |
#endif
#if defined(USB_DP_CONFIG)
USB_DP_PERIPH |
#endif
#if defined(USB_DM_CONFIG)
USB_DM_PERIPH
#endif
));
//
// Setup the pins based on bl_config.h
//
#if defined(USB_VBUS_CONFIG)
//
// Set the VBUS pin to be an analog input.
//
HWREG(USB_VBUS_PORT + GPIO_O_DIR) &= ~(1 << USB_VBUS_PIN);
HWREG(USB_VBUS_PORT + GPIO_O_AMSEL) |= (1 << USB_VBUS_PIN);
#endif
#if defined(USB_ID_CONFIG)
//
// Set the ID pin to be an analog input.
//
HWREG(USB_ID_PORT + GPIO_O_DIR) &= ~(1 << USB_ID_PIN);
HWREG(USB_ID_PORT + GPIO_O_AMSEL) |= (1 << USB_ID_PIN);
#endif
#if defined(USB_DP_CONFIG)
//
// Set the DP pin to be an analog input.
//
HWREG(USB_DP_PORT + GPIO_O_DIR) &= ~(1 << USB_DP_PIN);
HWREG(USB_DP_PORT + GPIO_O_AMSEL) |= (1 << USB_DP_PIN);
#endif
#if defined(USB_DM_CONFIG)
//
// Set the DM pin to be an analog input.
//
HWREG(USB_DM_PORT + GPIO_O_DIR) &= ~(1 << USB_DM_PIN);
HWREG(USB_DM_PORT + GPIO_O_AMSEL) |= (1 << USB_DM_PIN);
#endif
}
#endif
//*****************************************************************************
//
//! Initialize the boot loader USB functions.
//!
//! This function initializes the boot loader USB functions and places the DFU
//! device onto the USB bus.
//!
//! \return None.
//
//*****************************************************************************
void
USBBLInit(void)
{
//
// Configure the USB Pins based on the bl_config.h settings.
//
#if defined(USB_VBUS_CONFIG) || defined(USB_ID_CONFIG) || \
defined(USB_DP_CONFIG) || defined(USB_DM_CONFIG)
USBConfigurePins();
#endif
//
// Initialize a couple of fields in the device state structure.
//
g_sUSBDeviceState.ui32Configuration = DEFAULT_CONFIG_ID;
//
// Enable the USB controller.
//
HWREG(SYSCTL_RCGCUSB) = SYSCTL_RCGCUSB_R0;
//
// Wait for the peripheral ready
//
while((HWREG(SYSCTL_PRUSB) & SYSCTL_PRUSB_R0) != SYSCTL_PRUSB_R0)
{
}
#if defined(TARGET_IS_TM4C129_RA0) || \
defined(TARGET_IS_TM4C129_RA1) || \
defined(TARGET_IS_TM4C129_RA2)
//
// Turn on USB Phy clock from PLL VCO
//
HWREG(USB0_BASE + USB_O_CC) = (USB_CC_CLKEN | (7 << USB_CC_CLKDIV_S));
#else
//
// Turn on USB Phy clock.
//
HWREG(SYSCTL_RCC2) &= ~SYSCTL_RCC2_USBPWRDN;
#endif
//
// Clear any pending interrupts.
//
HWREGH(USB0_BASE + USB_O_TXIS);
HWREGB(USB0_BASE + USB_O_IS);
//
// Enable USB Interrupts.
//
HWREGH(USB0_BASE + USB_O_TXIE) = USB_TXIS_EP0;
HWREGB(USB0_BASE + USB_O_IE) = (USB_IS_DISCON | USB_IS_RESET);
//
// Default to the state where remote wakeup is disabled.
//
g_sUSBDeviceState.ui8Status = 0;
g_sUSBDeviceState.bRemoteWakeup = false;
//
// Determine the self- or bus-powered state based on bl_config.h setting.
//
#if USB_BUS_POWERED
g_sUSBDeviceState.ui8Status &= ~USB_STATUS_SELF_PWR;
#else
g_sUSBDeviceState.ui8Status |= USB_STATUS_SELF_PWR;
#endif
//
// Attach the device using the soft connect.
//
HWREGB(USB0_BASE + USB_O_POWER) |= USB_POWER_SOFTCONN;
//
// Enable the USB interrupt.
//
HWREG(NVIC_EN1) = 1 << (INT_USB0 - 48);
}
//*****************************************************************************
//
// This function starts the request for data from the host on endpoint zero.
//
// \param pui8Data is a pointer to the buffer to fill with data from the USB
// host.
// \param ui32Size is the size of the buffer or data to return from the USB
// host.
//
// This function handles retrieving data from the host when a custom command
// has been issued on endpoint zero. When the requested data is received,
// the function HandleEP0Data() will be called.
//
// \return None.
//
//*****************************************************************************
void
USBBLRequestDataEP0(uint8_t *pui8Data, uint32_t ui32Size)
{
//
// Enter the RX state on end point 0.
//
g_eUSBDEP0State = USB_STATE_RX;
//
// Save the pointer to the data.
//
g_sUSBDeviceState.pui8EP0Data = pui8Data;
//
// Location to save the current number of bytes received.
//
g_sUSBDeviceState.ui32OUTDataSize = ui32Size;
//
// Bytes remaining to be received.
//
g_sUSBDeviceState.ui32EP0DataRemain = ui32Size;
}
//*****************************************************************************
//
//! This function requests transfer of data to the host on endpoint zero.
//!
//! \param pui8Data is a pointer to the buffer to send via endpoint zero.
//! \param ui32Size is the amount of data to send in bytes.
//!
//! This function handles sending data to the host when a custom command is
//! issued or non-standard descriptor has been requested on endpoint zero.
//!
//! \return None.
//
//*****************************************************************************
void
USBBLSendDataEP0(uint8_t *pui8Data, uint32_t ui32Size)
{
//
// Return the externally provided device descriptor.
//
g_sUSBDeviceState.pui8EP0Data = pui8Data;
//
// The size of the device descriptor is in the first byte.
//
g_sUSBDeviceState.ui32EP0DataRemain = ui32Size;
//
// Save the total size of the data sent.
//
g_sUSBDeviceState.ui32OUTDataSize = ui32Size;
//
// Now in the transmit data state.
//
USBDEP0StateTx();
}
//*****************************************************************************
//
//! This function generates a stall condition on endpoint zero.
//!
//! This function is typically called to signal an error condition to the host
//! when an unsupported request is received by the device. It should be
//! called from within the callback itself (in interrupt context) and not
//! deferred until later since it affects the operation of the endpoint zero
//! state machine.
//!
//! \return None.
//
//*****************************************************************************
void
USBBLStallEP0(void)
{
//
// Perform a stall on endpoint zero.
//
HWREGB(USB0_BASE + USB_O_CSRL0) |= (USB_CSRL0_STALL | USB_CSRL0_RXRDYC);
//
// Enter the stalled state.
//
g_eUSBDEP0State = USB_STATE_STALL;
}
//*****************************************************************************
//
// This internal function reads a request data packet and dispatches it to
// either a standard request handler or the registered device request
// callback depending upon the request type.
//
// \return None.
//
//*****************************************************************************
static void
USBDReadAndDispatchRequest(void)
{
uint32_t ui32Size;
tUSBRequest *pRequest;
//
// Cast the buffer to a request structure.
//
pRequest = (tUSBRequest *)g_pui8DataBufferIn;
//
// Set the buffer size.
//
ui32Size = EP0_MAX_PACKET_SIZE;
//
// Get the data from the USB controller end point 0.
//
USBEndpoint0DataGet(g_pui8DataBufferIn, &ui32Size);
if(!ui32Size)
{
return;
}
//
// See if this is a standard request or not.
//
if((pRequest->bmRequestType & USB_RTYPE_TYPE_M) != USB_RTYPE_STANDARD)
{
//
// Pass this non-standard request on to the DFU handler
//
HandleRequests(pRequest);
}
else
{
//
// Assure that the jump table is not out of bounds.
//
if((pRequest->bRequest <
(sizeof(g_ppfnUSBDStdRequests) / sizeof(tStdRequest))) &&
(g_ppfnUSBDStdRequests[pRequest->bRequest] != 0))
{
//
// Jump table to the appropriate handler.
//
g_ppfnUSBDStdRequests[pRequest->bRequest](pRequest);
}
else
{
//
// If there is no handler then stall this request.
//
USBBLStallEP0();
}
}
}
//*****************************************************************************
//
// This is the low level interrupt handler for endpoint zero.
//
// This function handles all interrupts on endpoint zero in order to maintain
// the state needed for the control endpoint on endpoint zero. In order to
// successfully enumerate and handle all USB standard requests, all requests
// on endpoint zero must pass through this function. The endpoint has the
// following states: \b USB_STATE_IDLE, \b USB_STATE_TX, \b USB_STATE_RX,
// \b USB_STATE_STALL, and \b USB_STATE_STATUS. In the \b USB_STATE_IDLE
// state the USB controller has not received the start of a request, and once
// it does receive the data for the request it will either enter the
// \b USB_STATE_TX, \b USB_STATE_RX, or \b USB_STATE_STALL depending on the
// command. If the controller enters the \b USB_STATE_TX or \b USB_STATE_RX
// then once all data has been sent or received, it must pass through the
// \b USB_STATE_STATUS state to allow the host to acknowledge completion of
// the request. The \b USB_STATE_STALL is entered from \b USB_STATE_IDLE in
// the event that the USB request was not valid. Both the \b USB_STATE_STALL
// and \b USB_STATE_STATUS are transitional states that return to the
// \b USB_STATE_IDLE state.
//
// \return None.
//
// USB_STATE_IDLE -*--> USB_STATE_TX -*-> USB_STATE_STATUS -*->USB_STATE_IDLE
// | | |
// |--> USB_STATE_RX - |
// | |
// |--> USB_STATE_STALL ---------->---------
//
// ----------------------------------------------------------------
// | Current State | State 0 | State 1 |
// | --------------------|-------------------|----------------------
// | USB_STATE_IDLE | USB_STATE_TX/RX | USB_STATE_STALL |
// | USB_STATE_TX | USB_STATE_STATUS | |
// | USB_STATE_RX | USB_STATE_STATUS | |
// | USB_STATE_STATUS | USB_STATE_IDLE | |
// | USB_STATE_STALL | USB_STATE_IDLE | |
// ----------------------------------------------------------------
//
//*****************************************************************************
void
USBDeviceEnumHandler(void)
{
uint32_t ui32EPStatus;
//
// Get the TX portion of the endpoint status.
//
ui32EPStatus = HWREGH(USB0_BASE + EP_OFFSET(USB_EP_0) + USB_O_TXCSRL1);
//
// Get the RX portion of the endpoint status.
//
ui32EPStatus |=
((HWREGH(USB0_BASE + EP_OFFSET(USB_EP_0) + USB_O_RXCSRL1)) <<
USB_RX_EPSTATUS_SHIFT);
//
// What state are we currently in?
//
switch(g_eUSBDEP0State)
{
//
// Handle the status state, this is a transitory state from
// USB_STATE_TX or USB_STATE_RX back to USB_STATE_IDLE.
//
case USB_STATE_STATUS:
{
//
// Just go back to the idle state.
//
g_eUSBDEP0State = USB_STATE_IDLE;
//
// If there is a pending address change then set the address.
//
if(g_sUSBDeviceState.ui32DevAddress & DEV_ADDR_PENDING)
{
//
// Clear the pending address change and set the address.
//
g_sUSBDeviceState.ui32DevAddress &= ~DEV_ADDR_PENDING;
HWREGB(USB0_BASE + USB_O_FADDR) =
(uint8_t)g_sUSBDeviceState.ui32DevAddress;
}
//
// If a new packet is already pending, we need to read it
// and handle whatever request it contains.
//
if(ui32EPStatus & USB_DEV_EP0_OUT_PKTRDY)
{
//
// Process the newly arrived packet.
//
USBDReadAndDispatchRequest();
}
break;
}
//
// In the IDLE state the code is waiting to receive data from the host.
//
case USB_STATE_IDLE:
{
//
// Is there a packet waiting for us?
//
if(ui32EPStatus & USB_DEV_EP0_OUT_PKTRDY)
{
//
// Yes - process it.
//
USBDReadAndDispatchRequest();
}
break;
}
//
// Data is still being sent to the host so handle this in the
// EP0StateTx() function.
//
case USB_STATE_TX:
{
USBDEP0StateTx();
break;
}
//
// Handle the receive state for commands that are receiving data on
// endpoint zero.
//
case USB_STATE_RX:
{
uint32_t ui32DataSize;
//
// Set the number of bytes to get out of this next packet.
//
if(g_sUSBDeviceState.ui32EP0DataRemain > EP0_MAX_PACKET_SIZE)
{
//
// Don't send more than EP0_MAX_PACKET_SIZE bytes.
//
ui32DataSize = EP0_MAX_PACKET_SIZE;
}
else
{
//
// There was space so send the remaining bytes.
//
ui32DataSize = g_sUSBDeviceState.ui32EP0DataRemain;
}
//
// Get the data from the USB controller end point 0.
//
USBEndpoint0DataGet(g_sUSBDeviceState.pui8EP0Data, &ui32DataSize);
//
// If there we not more that EP0_MAX_PACKET_SIZE or more bytes
// remaining then this transfer is complete. If there were exactly
// EP0_MAX_PACKET_SIZE remaining then there still needs to be
// null packet sent before this is complete.
//
if(g_sUSBDeviceState.ui32EP0DataRemain < EP0_MAX_PACKET_SIZE)
{
//
// Need to ack the data on end point 0 in this case
// without setting data end.
//
USBDevEndpoint0DataAck(true);
//
// Return to the idle state.
//
g_eUSBDEP0State = USB_STATE_IDLE;
//
// If there is a receive callback then call it.
//
if(g_sUSBDeviceState.ui32OUTDataSize != 0)
{
//
// Call the receive handler to handle the data
// that was received.
//
HandleEP0Data(g_sUSBDeviceState.ui32OUTDataSize);
//
// Indicate that there is no longer any data being waited
// on.
//
g_sUSBDeviceState.ui32OUTDataSize = 0;
}
}
else
{
//
// Need to ack the data on end point 0 in this case
// without setting data end.
//
USBDevEndpoint0DataAck(false);
}
//
// Advance the pointer.
//
g_sUSBDeviceState.pui8EP0Data += ui32DataSize;
//
// Decrement the number of bytes that are being waited on.
//
g_sUSBDeviceState.ui32EP0DataRemain -= ui32DataSize;
break;
}
//
// The device stalled endpoint zero so check if the stall needs to be
// cleared once it has been successfully sent.
//
case USB_STATE_STALL:
{
//
// If we sent a stall then acknowledge this interrupt.
//
if(ui32EPStatus & USB_DEV_EP0_SENT_STALL)
{
//
// Clear the stall condition.
//
HWREGB(USB0_BASE + USB_O_CSRL0) &= ~(USB_DEV_EP0_SENT_STALL);
//
// Reset the global end point 0 state to IDLE.
//
g_eUSBDEP0State = USB_STATE_IDLE;
}
break;
}
//
// Halt on an unknown state, but only in DEBUG mode builds.
//
default:
{
#ifdef DEBUG
while(1);
#endif
break;
}
}
}
//*****************************************************************************
//
// This function handles bus reset notifications.
//
// This function is called from the low level USB interrupt handler whenever
// a bus reset is detected. It performs tidy-up as required and resets the
// configuration back to defaults in preparation for descriptor queries from
// the host.
//
// \return None.
//
//*****************************************************************************
void
USBDeviceEnumResetHandler(void)
{
//
// Disable remote wakeup signalling (as per USB 2.0 spec 9.1.1.6).
//
g_sUSBDeviceState.ui8Status &= ~USB_STATUS_REMOTE_WAKE;
g_sUSBDeviceState.bRemoteWakeup = false;
//
// Call the device dependent code to indicate a bus reset has occurred.
//
HandleReset();
//
// Reset the default configuration identifier and alternate function
// selections.
//
g_sUSBDeviceState.ui32Configuration = DEFAULT_CONFIG_ID;
g_sUSBDeviceState.ui8AltSetting = 0;
}
//*****************************************************************************
//
// This function handles the GET_STATUS standard USB request.
//
// \param pUSBRequest holds the request type and endpoint number if endpoint
// status is requested.
//
// This function handles responses to a Get Status request from the host
// controller. A status request can be for the device, an interface or an
// endpoint. If any other type of request is made this function will cause
// a stall condition to indicate that the command is not supported. The
// \e pUSBRequest structure holds the type of the request in the
// bmRequestType field. If the type indicates that this is a request for an
// endpoint's status, then the wIndex field holds the endpoint number.
//
// \return None.
//
//*****************************************************************************
static void
USBDGetStatus(tUSBRequest *pUSBRequest)
{
uint16_t ui16Data;
//
// Determine what type of status was requested.
//
switch(pUSBRequest->bmRequestType & USB_RTYPE_RECIPIENT_M)
{
//
// This was a Device Status request.
//
case USB_RTYPE_DEVICE:
{
//
// Return the current status for the device.
//
ui16Data = g_sUSBDeviceState.ui8Status;
break;
}
//
// This was a Interface status request.
//
case USB_RTYPE_INTERFACE:
{
//
// Interface status always returns 0.
//
ui16Data = 0;
break;
}
//
// This was an unknown request or a request for an endpoint (of which
// we have none) so set a stall.
//
case USB_RTYPE_ENDPOINT:
default:
{
//
// Anything else causes a stall condition to indicate that the
// command was not supported.
//
USBBLStallEP0();
return;
}
}
//
// Send the two byte status response.
//
g_sUSBDeviceState.ui32EP0DataRemain = 2;
g_sUSBDeviceState.pui8EP0Data = (uint8_t *)&ui16Data;
//
// Send the response.
//
USBDEP0StateTx();
}
//*****************************************************************************
//
// This function handles the CLEAR_FEATURE standard USB request.
//
// \param pUSBRequest holds the options for the Clear Feature USB request.
//
// This function handles device or endpoint clear feature requests. The
// \e pUSBRequest structure holds the type of the request in the bmRequestType
// field and the feature is held in the wValue field. For device, the only
// clearable feature is the Remote Wake feature. This device request
// should only be made if the descriptor indicates that Remote Wake is
// implemented by the device. For endpoint requests the only clearable
// feature is the ability to clear a halt on a given endpoint. If any other
// requests are made, then the device will stall the request to indicate to
// the host that the command was not supported.
//
// \return None.
//
//*****************************************************************************
static void
USBDClearFeature(tUSBRequest *pUSBRequest)
{
//
// Determine what type of status was requested.
//
switch(pUSBRequest->bmRequestType & USB_RTYPE_RECIPIENT_M)
{
//
// This is a clear feature request at the device level.
//
case USB_RTYPE_DEVICE:
{
//
// Only remote wake is clearable by this function.
//
if(USB_FEATURE_REMOTE_WAKE & pUSBRequest->wValue)
{
//
// Clear the remote wake up state.
//
g_sUSBDeviceState.ui8Status &= ~USB_STATUS_REMOTE_WAKE;
//
// Need to ack the data on end point 0.
//
USBDevEndpoint0DataAck(true);
}
else
{
USBBLStallEP0();
}
break;
}
//
// This is an unknown request or one destined for an invalid endpoint.
//
case USB_RTYPE_ENDPOINT:
default:
{
USBBLStallEP0();
return;
}
}
}
//*****************************************************************************
//
// This function handles the SET_FEATURE standard USB request.
//
// \param pUSBRequest holds the feature in the wValue field of the USB
// request.
//
// This function handles device or endpoint set feature requests. The
// \e pUSBRequest structure holds the type of the request in the bmRequestType
// field and the feature is held in the wValue field. For device, the only
// settable feature is the Remote Wake feature. This device request
// should only be made if the descriptor indicates that Remote Wake is
// implemented by the device. For endpoint requests the only settable feature
// is the ability to issue a halt on a given endpoint. If any other requests
// are made, then the device will stall the request to indicate to the host
// that the command was not supported.
//
// \return None.
//
//*****************************************************************************
static void
USBDSetFeature(tUSBRequest *pUSBRequest)
{
//
// Determine what type of status was requested.
//
switch(pUSBRequest->bmRequestType & USB_RTYPE_RECIPIENT_M)
{
//
// This is a set feature request at the device level.
//
case USB_RTYPE_DEVICE:
{
//
// Only remote wake is setable by this function.
//
if(USB_FEATURE_REMOTE_WAKE & pUSBRequest->wValue)
{
//
// Set the remote wakeup state.
//
g_sUSBDeviceState.ui8Status |= USB_STATUS_REMOTE_WAKE;
//
// Need to ack the data on end point 0.
//
USBDevEndpoint0DataAck(true);
}
else
{
USBBLStallEP0();
}
break;
}
//
// This is an unknown request or one destined for an invalid endpoint.
//
case USB_RTYPE_ENDPOINT:
default:
{
USBBLStallEP0();
return;
}
}
}
//*****************************************************************************
//
// This function handles the SET_ADDRESS standard USB request.
//
// \param pUSBRequest holds the new address to use in the wValue field of the
// USB request.
//
// This function is called to handle the change of address request from the
// host controller. This can only start the sequence as the host must
// acknowledge that the device has changed address. Thus this function sets
// the address change as pending until the status phase of the request has
// been completed successfully. This prevents the devices address from
// changing and not properly responding to the status phase.
//
// \return None.
//
//*****************************************************************************
static void
USBDSetAddress(tUSBRequest *pUSBRequest)
{
//
// The data needs to be acknowledged on end point 0 without setting data
// end because there is no data coming.
//
USBDevEndpoint0DataAck(true);
//
// Save the device address as we cannot change address until the status
// phase is complete.
//
g_sUSBDeviceState.ui32DevAddress = pUSBRequest->wValue | DEV_ADDR_PENDING;
//
// Transition directly to the status state since there is no data phase
// for this request.
//
g_eUSBDEP0State = USB_STATE_STATUS;
//
// Clear the DFU status just in case we were in an error state last time
// the device was accessed and we were unplugged and replugged (for a self-
// powered implementation, of course).
//
HandleSetAddress();
}
//*****************************************************************************
//
// This function handles the GET_DESCRIPTOR standard USB request.
//
// \param pUSBRequest holds the data for this request.
//
// This function will return all configured standard USB descriptors to the
// host - device, config and string descriptors. Any request for a descriptor
// which is not available will result in endpoint 0 being stalled.
//
// \return None.
//
//*****************************************************************************
static void
USBDGetDescriptor(tUSBRequest *pUSBRequest)
{
uint32_t ui32Stall;
//
// Default to no stall.
//
ui32Stall = 0;
//
// Which descriptor are we being asked for?
//
switch(pUSBRequest->wValue >> 8)
{
//
// This request was for a device descriptor.
//
case USB_DTYPE_DEVICE:
{
//
// Return the externally provided device descriptor.
//
g_sUSBDeviceState.pui8EP0Data =
(uint8_t *)g_pui8DFUDeviceDescriptor;
//
// The size of the device descriptor is in the first byte.
//
g_sUSBDeviceState.ui32EP0DataRemain =
g_pui8DFUDeviceDescriptor[0];
break;
}
//
// This request was for a configuration descriptor.
//
case USB_DTYPE_CONFIGURATION:
{
uint8_t ui8Index;
//
// Which configuration are we being asked for?
//
ui8Index = (uint8_t)(pUSBRequest->wValue & 0xFF);
//
// Is this valid?
//
if(ui8Index != 0)
{
//
// This is an invalid configuration index. Stall EP0 to
// indicate a request error.
//
USBBLStallEP0();
g_sUSBDeviceState.pui8EP0Data = 0;
g_sUSBDeviceState.ui32EP0DataRemain = 0;
}
else
{
//
// Start by sending data from the beginning of the first
// descriptor.
//
g_sUSBDeviceState.pui8EP0Data =
(uint8_t *)g_pui8DFUConfigDescriptor;
//
// Get the size of the config descriptor (remembering that in
// this case, we only have a single section)
//
g_sUSBDeviceState.ui32EP0DataRemain =
*(uint16_t *)&(g_pui8DFUConfigDescriptor[2]);
}
break;
}
//
// This request was for a string descriptor.
//
case USB_DTYPE_STRING:
{
int32_t i32Index;
//
// Determine the correct descriptor index based on the requested
// language ID and index.
//
i32Index = USBDStringIndexFromRequest(pUSBRequest->wIndex,
pUSBRequest->wValue & 0xFF);
//
// If the mapping function returned -1 then stall the request to
// indicate that the request was not valid.
//
if(i32Index == -1)
{
USBBLStallEP0();
break;
}
//
// Return the externally specified configuration descriptor.
//
g_sUSBDeviceState.pui8EP0Data =
(uint8_t *)g_ppui8StringDescriptors[i32Index];
//
// The total size of a string descriptor is in byte 0.
//
g_sUSBDeviceState.ui32EP0DataRemain =
g_ppui8StringDescriptors[i32Index][0];
break;
}
//
// Any other request is not handled by the default enumeration handler
// so see if it needs to be passed on to another handler.
//
default:
{
//
// All other requests are not handled.
//
USBBLStallEP0();
ui32Stall = 1;
break;
}
}
//
// If there was no stall, ACK the data and see if data needs to be sent.
//
if(ui32Stall == 0)
{
//
// Need to ack the data on end point 0 in this case without
// setting data end.
//
USBDevEndpoint0DataAck(false);
//
// If this request has data to send, then send it.
//
if(g_sUSBDeviceState.pui8EP0Data)
{
//
// If there is more data to send than is requested then just
// send the requested amount of data.
//
if(g_sUSBDeviceState.ui32EP0DataRemain > pUSBRequest->wLength)
{
g_sUSBDeviceState.ui32EP0DataRemain = pUSBRequest->wLength;
}
//
// Now in the transmit data state. Be careful to call the correct
// function since we need to handle the config descriptor
// differently from the others.
//
USBDEP0StateTx();
}
}
}
//*****************************************************************************
//
// This function determines which string descriptor to send to satisfy a
// request for a given index and language.
//
// \param ui16Lang is the requested string language ID.
// \param ui16Index is the requested string descriptor index.
//
// When a string descriptor is requested, the host provides a language ID and
// index to identify the string ("give me string number 5 in French"). This
// function maps these two parameters to an index within our device's string
// descriptor array which is arranged as multiple groups of strings with
// one group for each language advertised via string descriptor 0.
//
// We assume that there are an equal number of strings per language and
// that the first descriptor is the language descriptor and use this fact to
// perform the mapping.
//
// \return The index of the string descriptor to return or -1 if the string
// could not be found.
//
//*****************************************************************************
static int32_t
USBDStringIndexFromRequest(uint16_t ui16Lang, uint16_t ui16Index)
{
tString0Descriptor *pLang;
uint32_t ui32NumLangs;
uint32_t ui32NumStringsPerLang;
uint32_t ui32Loop;
//
// First look for the trivial case where descriptor 0 is being
// requested. This is the special case since descriptor 0 contains the
// language codes supported by the device.
//
if(ui16Index == 0)
{
return(0);
}
//
// How many languages does this device support? This is determined by
// looking at the length of the first descriptor in the string table,
// subtracting 2 for the header and dividing by two (the size of each
// language code).
//
ui32NumLangs = (g_ppui8StringDescriptors[0][0] - 2) / 2;
//
// We assume that the table includes the same number of strings for each
// supported language. We know the number of entries in the string table,
// so how many are there for each language? This may seem an odd way to
// do this (why not just have the application tell us in the device info
// structure?) but it's needed since we didn't want to change the API
// after the first release which did not support multiple languages.
//
ui32NumStringsPerLang = ((NUM_STRING_DESCRIPTORS - 1) / ui32NumLangs);
//
// Just to be sure, make sure that the calculation indicates an equal
// number of strings per language. We expect the string table to contain
// (1 + (strings_per_language * languages)) entries.
//
if((1 + (ui32NumStringsPerLang * ui32NumLangs)) != NUM_STRING_DESCRIPTORS)
{
return(-1);
}
//
// Now determine which language we are looking for. It is assumed that
// the order of the groups of strings per language in the table is the
// same as the order of the language IDs listed in the first descriptor.
//
pLang = (tString0Descriptor *)(g_ppui8StringDescriptors[0]);
//
// Look through the supported languages looking for the one we were asked
// for.
//
for(ui32Loop = 0; ui32Loop < ui32NumLangs; ui32Loop++)
{
//
// Have we found the requested language?
//
if(pLang->wLANGID[ui32Loop] == ui16Lang)
{
//
// Yes - calculate the index of the descriptor to send.
//
return((ui32NumStringsPerLang * ui32Loop) + ui16Index);
}
}
//
// If we drop out of the loop, the requested language was not found so
// return -1 to indicate the error.
//
return(-1);
}
//*****************************************************************************
//
// This function handles the SET_DESCRIPTOR standard USB request.
//
// \param pUSBRequest holds the data for this request.
//
// This function currently is not supported and will respond with a Stall
// to indicate that this command is not supported by the device.
//
// \return None.
//
//*****************************************************************************
static void
USBDSetDescriptor(tUSBRequest *pUSBRequest)
{
//
// This function is not handled by default.
//
USBBLStallEP0();
}
//*****************************************************************************
//
// This function handles the GET_CONFIGURATION standard USB request.
//
// \param pUSBRequest holds the data for this request.
//
// This function responds to a host request to return the current
// configuration of the USB device. The function will send the configuration
// response to the host and return. This value will either be 0 or the last
// value received from a call to SetConfiguration().
//
// \return None.
//
//*****************************************************************************
static void
USBDGetConfiguration(tUSBRequest *pUSBRequest)
{
uint8_t ui8Value;
//
// If we still have an address pending then the device is still not
// configured.
//
if(g_sUSBDeviceState.ui32DevAddress & DEV_ADDR_PENDING)
{
ui8Value = 0;
}
else
{
ui8Value = (uint8_t)g_sUSBDeviceState.ui32Configuration;
}
g_sUSBDeviceState.ui32EP0DataRemain = 1;
g_sUSBDeviceState.pui8EP0Data = &ui8Value;
//
// Send the single byte response.
//
USBDEP0StateTx();
}
//*****************************************************************************
//
// This function handles the SET_CONFIGURATION standard USB request.
//
// \param pUSBRequest holds the data for this request.
//
// This function responds to a host request to change the current
// configuration of the USB device. The actual configuration number is taken
// from the structure passed in via \e pUSBRequest.
//
// \return None.
//
//*****************************************************************************
static void
USBDSetConfiguration(tUSBRequest *pUSBRequest)
{
//
// Cannot set the configuration to one that does not exist so check the
// enumeration structure to see how many valid configurations are present.
//
if(pUSBRequest->wValue > 1)
{
//
// The passed configuration number is not valid. Stall the endpoint to
// signal the error to the host.
//
USBBLStallEP0();
}
else
{
//
// Need to ack the data on end point 0.
//
USBDevEndpoint0DataAck(true);
//
// Save the configuration.
//
g_sUSBDeviceState.ui32Configuration = pUSBRequest->wValue;
//
// If passed a configuration other than 0 (which tells us that we are
// not currently configured), configure the endpoints (other than EP0)
// appropriately.
//
if(g_sUSBDeviceState.ui32Configuration)
{
//
// Set the power state
//
#if USB_BUS_POWERED
g_sUSBDeviceState.ui8Status &= ~USB_STATUS_SELF_PWR;
#else
g_sUSBDeviceState.ui8Status |= USB_STATUS_SELF_PWR;
#endif
}
//
// Do whatever needs to be done as a result of the config change.
//
HandleConfigChange(g_sUSBDeviceState.ui32Configuration);
}
}
//*****************************************************************************
//
// This function handles the GET_INTERFACE standard USB request.
//
// \param pUSBRequest holds the data for this request.
//
// This function is called when the host controller request the current
// interface that is in use by the device. This simply returns the value set
// by the last call to SetInterface().
//
// \return None.
//
//*****************************************************************************
static void
USBDGetInterface(tUSBRequest *pUSBRequest)
{
uint8_t ui8Value;
//
// If we still have an address pending then the device is still not
// configured.
//
if(g_sUSBDeviceState.ui32DevAddress & DEV_ADDR_PENDING)
{
ui8Value = 0;
}
else
{
//
// Is the interface number valid?
//
if(pUSBRequest->wIndex == 0)
{
//
// Read the current alternate setting for the required interface.
//
ui8Value = g_sUSBDeviceState.ui8AltSetting;
}
else
{
//
// An invalid interface number was specified.
//
USBBLStallEP0();
return;
}
}
//
// Send the single byte response.
//
g_sUSBDeviceState.ui32EP0DataRemain = 1;
g_sUSBDeviceState.pui8EP0Data = &ui8Value;
//
// Send the single byte response.
//
USBDEP0StateTx();
}
//*****************************************************************************
//
// This function handles the SET_INTERFACE standard USB request.
//
// \param pUSBRequest holds the data for this request.
//
// The DFU device supports a single interface with no alternate settings so
// this handler is hardcoded assuming this configuration.
//
// \return None.
//
//*****************************************************************************
static void
USBDSetInterface(tUSBRequest *pUSBRequest)
{
if((pUSBRequest->wIndex == 0) && (pUSBRequest->wValue == 0))
{
//
// We were passed a valid interface number so acknowledge the request.
//
USBDevEndpoint0DataAck(true);
}
else
{
//
// The values passed were not valid so stall endpoint 0.
//
USBBLStallEP0();
}
}
//*****************************************************************************
//
// This internal function handles sending data on endpoint zero.
//
// \return None.
//
//*****************************************************************************
static void
USBDEP0StateTx(void)
{
uint32_t ui32NumBytes;
uint8_t *pui8Data;
//
// In the TX state on endpoint zero.
//
g_eUSBDEP0State = USB_STATE_TX;
//
// Set the number of bytes to send this iteration.
//
ui32NumBytes = g_sUSBDeviceState.ui32EP0DataRemain;
//
// Limit individual transfers to 64 bytes.
//
if(ui32NumBytes > EP0_MAX_PACKET_SIZE)
{
ui32NumBytes = EP0_MAX_PACKET_SIZE;
}
//
// Save the pointer so that it can be passed to the USBEndpointDataPut()
// function.
//
pui8Data = g_sUSBDeviceState.pui8EP0Data;
//
// Advance the data pointer and counter to the next data to be sent.
//
g_sUSBDeviceState.ui32EP0DataRemain -= ui32NumBytes;
g_sUSBDeviceState.pui8EP0Data += ui32NumBytes;
//
// Put the data in the correct FIFO.
//
USBEndpoint0DataPut(pui8Data, ui32NumBytes);
//
// If this is exactly 64 then don't set the last packet yet.
//
if(ui32NumBytes == EP0_MAX_PACKET_SIZE)
{
//
// There is more data to send or exactly 64 bytes were sent, this
// means that there is either more data coming or a null packet needs
// to be sent to complete the transaction.
//
USBEndpoint0DataSend(USB_TRANS_IN);
}
else
{
//
// Now go to the status state and wait for the transmit to complete.
//
g_eUSBDEP0State = USB_STATE_STATUS;
//
// Send the last bit of data.
//
USBEndpoint0DataSend(USB_TRANS_IN_LAST);
g_sUSBDeviceState.ui32OUTDataSize = 0;
}
}
//*****************************************************************************
//
// Close the Doxygen group.
//! @}
//
//*****************************************************************************
#endif // USB_ENABLE_UPDATE
|
753340.c | #define XX_PREDECLS
#define XX_INFO \
"pcg_mcg_16_xsh_rs_8_random_r:\n" \
" - result: 8-bit unsigned int (uint8_t)\n" \
" - period: 2^14\n" \
" - state type: struct pcg_state_16 (%zu bytes)\n" \
" - output func: XSH-RS\n" \
"\n", sizeof(struct pcg_state_16)
#define XX_NUMBITS " 8bit:"
#define XX_NUMVALUES 14
#define XX_NUMWRAP 14
#define XX_PRINT_RNGVAL(value) printf(" 0x%02x", value)
#define XX_RAND_DECL struct pcg_state_16 rng;
#define XX_SEEDSDECL(seeds) uint16_t seeds[1];
#define XX_SRANDOM_SEEDARGS(seeds) seeds[0]
#define XX_SRANDOM_SEEDCONSTS 42u
#define XX_SRANDOM(...) \
pcg_mcg_16_srandom_r(&rng, __VA_ARGS__)
#define XX_RANDOM() \
pcg_mcg_16_xsh_rs_8_random_r(&rng)
#define XX_BOUNDEDRAND(bound) \
pcg_mcg_16_xsh_rs_8_boundedrand_r(&rng, bound)
#define XX_ADVANCE(delta) \
pcg_mcg_16_advance_r(&rng, delta)
#include "pcg_variants.h"
#include "check-base.c"
|
774406.c | /*
* Academic License - for use in teaching, academic research, and meeting
* course requirements at degree granting institutions only. Not for
* government, commercial, or other organizational use.
*
* ifWhileCond.c
*
* Code generation for function 'ifWhileCond'
*
*/
/* Include files */
#include "rt_nonfinite.h"
#include "ExtractWindowTrajectory.h"
#include "ifWhileCond.h"
#include "eml_int_forloop_overflow_check.h"
#include "ExtractWindowTrajectory_data.h"
/* Variable Definitions */
static emlrtRSInfo cd_emlrtRSI = { 17, /* lineNo */
"ifWhileCond", /* fcnName */
"C:\\Program Files\\MATLAB\\R2018a\\toolbox\\eml\\eml\\+coder\\+internal\\ifWhileCond.m"/* pathName */
};
static emlrtRSInfo dd_emlrtRSI = { 30, /* lineNo */
"ifWhileCond", /* fcnName */
"C:\\Program Files\\MATLAB\\R2018a\\toolbox\\eml\\eml\\+coder\\+internal\\ifWhileCond.m"/* pathName */
};
/* Function Definitions */
boolean_T ifWhileCond(const emlrtStack *sp, const emxArray_boolean_T *x)
{
boolean_T y;
boolean_T overflow;
int32_T k;
boolean_T exitg1;
emlrtStack st;
emlrtStack b_st;
emlrtStack c_st;
st.prev = sp;
st.tls = sp->tls;
b_st.prev = &st;
b_st.tls = st.tls;
c_st.prev = &b_st;
c_st.tls = b_st.tls;
y = !(x->size[0] == 0);
if (y) {
st.site = &cd_emlrtRSI;
b_st.site = &dd_emlrtRSI;
overflow = ((!(1 > x->size[0])) && (x->size[0] > 2147483646));
if (overflow) {
c_st.site = &x_emlrtRSI;
check_forloop_overflow_error(&c_st);
}
k = 1;
exitg1 = false;
while ((!exitg1) && (k <= x->size[0])) {
if (!x->data[k - 1]) {
y = false;
exitg1 = true;
} else {
k++;
}
}
}
return y;
}
/* End of code generation (ifWhileCond.c) */
|
906993.c | /*
* Copyright (c) 2006-2018, RT-Thread Development Team
*
* SPDX-License-Identifier: Apache-2.0
*
* Change Logs:
* Date Author Notes
* 2018-08-06 tyx the first version
*/
#include <rthw.h>
#include <rtthread.h>
#include <wlan_dev.h>
#include <wlan_cfg.h>
#include <wlan_mgnt.h>
#include <wlan_prot.h>
#include <wlan_workqueue.h>
#define DBG_TAG "WLAN.mgnt"
#ifdef RT_WLAN_MGNT_DEBUG
#define DBG_LVL DBG_LOG
#else
#define DBG_LVL DBG_INFO
#endif /* RT_WLAN_MGNT_DEBUG */
#include <rtdbg.h>
#ifdef RT_WLAN_MANAGE_ENABLE
#ifndef RT_WLAN_DEVICE
#define RT_WLAN_DEVICE(__device) ((struct rt_wlan_device *)__device)
#endif
#define RT_WLAN_LOG_D(_fmt, ...) LOG_D("L:%d "_fmt"", __LINE__, ##__VA_ARGS__)
#define RT_WLAN_LOG_I(...) LOG_I(__VA_ARGS__)
#define RT_WLAN_LOG_W(_fmt, ...) LOG_W("F:%s L:%d "_fmt"", __FUNCTION__, __LINE__, ##__VA_ARGS__)
#define RT_WLAN_LOG_E(_fmt, ...) LOG_E("F:%s L:%d "_fmt"", __FUNCTION__, __LINE__, ##__VA_ARGS__)
#define STA_DEVICE() (_sta_mgnt.device)
#define AP_DEVICE() (_ap_mgnt.device)
#define SRESULT_LOCK() (rt_mutex_take(&scan_result_mutex, RT_WAITING_FOREVER))
#define SRESULT_UNLOCK() (rt_mutex_release(&scan_result_mutex))
#define STAINFO_LOCK() (rt_mutex_take(&sta_info_mutex, RT_WAITING_FOREVER))
#define STAINFO_UNLOCK() (rt_mutex_release(&sta_info_mutex))
#define MGNT_LOCK() (rt_mutex_take(&mgnt_mutex, RT_WAITING_FOREVER))
#define MGNT_UNLOCK() (rt_mutex_release(&mgnt_mutex))
#define COMPLETE_LOCK() (rt_mutex_take(&complete_mutex, RT_WAITING_FOREVER))
#define COMPLETE_UNLOCK() (rt_mutex_release(&complete_mutex))
#ifdef RT_WLAN_AUTO_CONNECT_ENABLE
#define TIME_STOP() (rt_timer_stop(&reconnect_time))
#define TIME_START() (rt_timer_start(&reconnect_time))
#else
#define TIME_STOP()
#define TIME_START()
#endif
#if RT_WLAN_EBOX_NUM < 1
#error "event box num Too few"
#endif
struct rt_wlan_mgnt_des
{
struct rt_wlan_device *device;
struct rt_wlan_info info;
struct rt_wlan_key key;
rt_uint8_t state;
rt_uint8_t flags;
};
struct rt_wlan_event_desc
{
rt_wlan_event_handler handler;
void *parameter;
};
struct rt_wlan_sta_list
{
struct rt_wlan_sta_list *next;
struct rt_wlan_info info;
};
struct rt_wlan_sta_des
{
int num;
struct rt_wlan_sta_list *node;
};
struct rt_wlan_msg
{
rt_int32_t event;
rt_int32_t len;
void *buff;
};
struct rt_wlan_complete_des
{
struct rt_event complete;
rt_uint32_t event_flag;
int index;
};
static struct rt_mutex mgnt_mutex;
static struct rt_wlan_mgnt_des _sta_mgnt;
static struct rt_wlan_mgnt_des _ap_mgnt;
static struct rt_wlan_scan_result scan_result;
static struct rt_mutex scan_result_mutex;
static struct rt_wlan_sta_des sta_info;
static struct rt_mutex sta_info_mutex;
static struct rt_wlan_event_desc event_tab[RT_WLAN_EVT_MAX];
static struct rt_wlan_complete_des *complete_tab[5];
static struct rt_mutex complete_mutex;
static struct rt_wlan_info *scan_filter;
#ifdef RT_WLAN_AUTO_CONNECT_ENABLE
static struct rt_timer reconnect_time;
#endif
rt_inline int _sta_is_null(void)
{
if (_sta_mgnt.device == RT_NULL)
{
return 1;
}
return 0;
}
rt_inline int _ap_is_null(void)
{
if (_ap_mgnt.device == RT_NULL)
{
return 1;
}
return 0;
}
rt_inline rt_bool_t _is_do_connect(void)
{
if ((rt_wlan_get_autoreconnect_mode() == RT_FALSE) ||
(rt_wlan_is_connected() == RT_TRUE) ||
(_sta_mgnt.state & RT_WLAN_STATE_CONNECTING))
{
return RT_FALSE;
}
return RT_TRUE;
}
#ifdef RT_WLAN_WORK_THREAD_ENABLE
static rt_bool_t rt_wlan_info_isequ(struct rt_wlan_info *info1, struct rt_wlan_info *info2)
{
rt_bool_t is_equ = 1;
rt_uint8_t bssid_zero[RT_WLAN_BSSID_MAX_LENGTH] = { 0 };
if (is_equ && (info1->security != SECURITY_UNKNOWN) && (info2->security != SECURITY_UNKNOWN))
{
is_equ &= info2->security == info1->security;
}
if (is_equ && ((info1->ssid.len > 0) && (info2->ssid.len > 0)))
{
is_equ &= info1->ssid.len == info2->ssid.len;
is_equ &= rt_memcmp(&info2->ssid.val[0], &info1->ssid.val[0], info1->ssid.len) == 0;
}
if (is_equ && (rt_memcmp(&info1->bssid[0], bssid_zero, RT_WLAN_BSSID_MAX_LENGTH)) &&
(rt_memcmp(&info2->bssid[0], bssid_zero, RT_WLAN_BSSID_MAX_LENGTH)))
{
is_equ &= rt_memcmp(&info1->bssid[0], &info2->bssid[0], RT_WLAN_BSSID_MAX_LENGTH) == 0;
}
if (is_equ && info1->datarate && info2->datarate)
{
is_equ &= info1->datarate == info2->datarate;
}
if (is_equ && (info1->channel >= 0) && (info2->channel >= 0))
{
is_equ &= info1->channel == info2->channel;
}
if (is_equ && (info1->rssi < 0) && (info2->rssi < 0))
{
is_equ &= info1->rssi == info2->rssi;
}
return is_equ;
}
static void rt_wlan_mgnt_work(void *parameter)
{
struct rt_wlan_msg *msg = parameter;
void *user_parameter;
rt_wlan_event_handler handler = RT_NULL;
struct rt_wlan_buff user_buff = { 0 };
rt_base_t level;
/* Get user callback */
if (msg->event < RT_WLAN_EVT_MAX)
{
level = rt_hw_interrupt_disable();
handler = event_tab[msg->event].handler;
user_parameter = event_tab[msg->event].parameter;
rt_hw_interrupt_enable(level);
}
/* run user callback fun */
if (handler)
{
user_buff.data = msg->buff;
user_buff.len = msg->len;
RT_WLAN_LOG_D("wlan work thread run user callback, event:%d", msg->event);
handler(msg->event, &user_buff, user_parameter);
}
switch (msg->event)
{
case RT_WLAN_EVT_STA_CONNECTED:
{
struct rt_wlan_cfg_info cfg_info;
rt_memset(&cfg_info, 0, sizeof(cfg_info));
/* save config */
if (rt_wlan_is_connected() == RT_TRUE)
{
rt_enter_critical();
cfg_info.info = _sta_mgnt.info;
cfg_info.key = _sta_mgnt.key;
rt_exit_critical();
RT_WLAN_LOG_D("run save config! ssid:%s len%d", _sta_mgnt.info.ssid.val, _sta_mgnt.info.ssid.len);
#ifdef RT_WLAN_CFG_ENABLE
rt_wlan_cfg_save(&cfg_info);
#endif
}
break;
}
default :
break;
}
rt_free(msg);
}
static rt_err_t rt_wlan_send_to_thread(rt_wlan_event_t event, void *buff, int len)
{
struct rt_wlan_msg *msg;
RT_WLAN_LOG_D("F:%s is run event:%d", __FUNCTION__, event);
/* Event packing */
msg = rt_malloc(sizeof(struct rt_wlan_msg) + len);
if (msg == RT_NULL)
{
RT_WLAN_LOG_E("wlan mgnt send msg err! No memory");
return -RT_ENOMEM;
}
rt_memset(msg, 0, sizeof(struct rt_wlan_msg) + len);
msg->event = event;
if (len != 0)
{
msg->buff = ((char *)msg) + sizeof(struct rt_wlan_msg);
msg->len = len;
}
/* send event to wlan thread */
if (rt_wlan_workqueue_dowork(rt_wlan_mgnt_work, msg) != RT_EOK)
{
rt_free(msg);
RT_WLAN_LOG_E("wlan mgnt do work fail");
return -RT_ERROR;
}
return RT_EOK;
}
#endif
static rt_err_t rt_wlan_scan_result_cache(struct rt_wlan_info *info, int timeout)
{
struct rt_wlan_info *ptable;
rt_err_t err = RT_EOK;
int i, insert = -1;
rt_base_t level;
if (_sta_is_null() || (info == RT_NULL) || (info->ssid.len == 0)) return RT_EOK;
RT_WLAN_LOG_D("ssid:%s len:%d mac:%02x:%02x:%02x:%02x:%02x:%02x", info->ssid.val, info->ssid.len,
info->bssid[0], info->bssid[1], info->bssid[2], info->bssid[3], info->bssid[4], info->bssid[5]);
err = rt_mutex_take(&scan_result_mutex, rt_tick_from_millisecond(timeout));
if (err != RT_EOK)
return err;
/* scanning result filtering */
level = rt_hw_interrupt_disable();
if (scan_filter)
{
struct rt_wlan_info _tmp_info = *scan_filter;
rt_hw_interrupt_enable(level);
if (rt_wlan_info_isequ(&_tmp_info, info) != RT_TRUE)
{
rt_mutex_release(&scan_result_mutex);
return RT_EOK;
}
}
else
{
rt_hw_interrupt_enable(level);
}
/* de-duplicatio */
for (i = 0; i < scan_result.num; i++)
{
if ((info->ssid.len == scan_result.info[i].ssid.len) &&
(rt_memcmp(&info->bssid[0], &scan_result.info[i].bssid[0], RT_WLAN_BSSID_MAX_LENGTH) == 0))
{
rt_mutex_release(&scan_result_mutex);
return RT_EOK;
}
#ifdef RT_WLAN_SCAN_SORT
if (insert >= 0)
{
continue;
}
/* Signal intensity comparison */
if ((info->rssi < 0) && (scan_result.info[i].rssi < 0))
{
if (info->rssi > scan_result.info[i].rssi)
{
insert = i;
continue;
}
else if (info->rssi < scan_result.info[i].rssi)
{
continue;
}
}
/* Channel comparison */
if (info->channel < scan_result.info[i].channel)
{
insert = i;
continue;
}
else if (info->channel > scan_result.info[i].channel)
{
continue;
}
/* data rate comparison */
if ((info->datarate > scan_result.info[i].datarate))
{
insert = i;
continue;
}
else if (info->datarate < scan_result.info[i].datarate)
{
continue;
}
#endif
}
/* Insert the end */
if (insert == -1)
insert = scan_result.num;
if (scan_result.num >= RT_WLAN_SCAN_CACHE_NUM)
return RT_EOK;
/* malloc memory */
ptable = rt_malloc(sizeof(struct rt_wlan_info) * (scan_result.num + 1));
if (ptable == RT_NULL)
{
rt_mutex_release(&scan_result_mutex);
RT_WLAN_LOG_E("wlan info malloc failed!");
return -RT_ENOMEM;
}
scan_result.num ++;
/* copy info */
for (i = 0; i < scan_result.num; i++)
{
if (i < insert)
{
ptable[i] = scan_result.info[i];
}
else if (i > insert)
{
ptable[i] = scan_result.info[i - 1];
}
else if (i == insert)
{
ptable[i] = *info;
}
}
rt_free(scan_result.info);
scan_result.info = ptable;
rt_mutex_release(&scan_result_mutex);
return err;
}
static rt_err_t rt_wlan_sta_info_add(struct rt_wlan_info *info, int timeout)
{
struct rt_wlan_sta_list *sta_list;
rt_err_t err = RT_EOK;
if (_ap_is_null() || (info == RT_NULL)) return RT_EOK;
err = rt_mutex_take(&sta_info_mutex, rt_tick_from_millisecond(timeout));
if (err == RT_EOK)
{
/* malloc memory */
sta_list = rt_malloc(sizeof(struct rt_wlan_sta_list));
if (sta_list == RT_NULL)
{
rt_mutex_release(&sta_info_mutex);
RT_WLAN_LOG_E("sta list malloc failed!");
return -RT_ENOMEM;
}
sta_list->next = RT_NULL;
sta_list->info = *info;
/* Append sta info */
sta_list->next = sta_info.node;
sta_info.node = sta_list;
/* num++ */
sta_info.num ++;
rt_mutex_release(&sta_info_mutex);
RT_WLAN_LOG_I("sta associated mac:%02x:%02x:%02x:%02x:%02x:%02x",
info->bssid[0], info->bssid[1], info->bssid[2],
info->bssid[3], info->bssid[4], info->bssid[5]);
}
return err;
}
static rt_err_t rt_wlan_sta_info_del(struct rt_wlan_info *info, int timeout)
{
struct rt_wlan_sta_list *sta_list, *sta_prve;
rt_err_t err = RT_EOK;
if (_ap_is_null() || (info == RT_NULL)) return RT_EOK;
err = rt_mutex_take(&sta_info_mutex, rt_tick_from_millisecond(timeout));
if (err == RT_EOK)
{
/* traversing the list */
for (sta_list = sta_info.node, sta_prve = RT_NULL; sta_list != RT_NULL;
sta_prve = sta_list, sta_list = sta_list->next)
{
/* find mac addr */
if (rt_memcmp(&sta_list->info.bssid[0], &info->bssid[0], RT_WLAN_BSSID_MAX_LENGTH) == 0)
{
if (sta_prve == RT_NULL)
{
sta_info.node = sta_list->next;
}
else
{
sta_prve->next = sta_list->next;
}
sta_info.num --;
rt_free(sta_list);
break;
}
}
rt_mutex_release(&sta_info_mutex);
RT_WLAN_LOG_I("sta exit mac:%02x:%02x:%02x:%02x:%02x:%02x",
info->bssid[0], info->bssid[1], info->bssid[2],
info->bssid[3], info->bssid[4], info->bssid[5]);
}
return err;
}
static rt_err_t rt_wlan_sta_info_del_all(int timeout)
{
struct rt_wlan_sta_list *sta_list, *sta_next;
rt_err_t err = RT_EOK;
err = rt_mutex_take(&sta_info_mutex, rt_tick_from_millisecond(timeout));
if (err == RT_EOK)
{
/* traversing the list */
for (sta_list = sta_info.node; sta_list != RT_NULL; sta_list = sta_next)
{
sta_next = sta_list->next;
sta_info.num --;
rt_free(sta_list);
}
rt_mutex_release(&sta_info_mutex);
}
if (sta_info.num != 0)
{
RT_WLAN_LOG_W("\n\n!!!Program runing exception!!!\n\n");
}
sta_info.num = 0;
sta_info.node = RT_NULL;
return err;
}
#ifdef RT_WLAN_AUTO_CONNECT_ENABLE
static void rt_wlan_auto_connect_run(struct rt_work *work, void *parameter)
{
static rt_uint32_t id = 0;
struct rt_wlan_cfg_info cfg_info;
char *password = RT_NULL;
rt_base_t level;
RT_WLAN_LOG_D("F:%s is run", __FUNCTION__);
if (rt_mutex_take(&mgnt_mutex, 0) != RT_EOK)
goto exit;
/* auto connect status is disable or wifi is connect or connecting, exit */
if (_is_do_connect() == RT_FALSE)
{
id = 0;
RT_WLAN_LOG_D("not connection");
goto exit;
}
/* Read the next configuration */
rt_memset(&cfg_info, 0, sizeof(struct rt_wlan_cfg_info));
if (rt_wlan_cfg_read_index(&cfg_info, id ++) == 0)
{
RT_WLAN_LOG_D("read cfg fail");
id = 0;
goto exit;
}
if (id >= rt_wlan_cfg_get_num()) id = 0;
if ((cfg_info.key.len > 0) && (cfg_info.key.len <= RT_WLAN_PASSWORD_MAX_LENGTH))
{
cfg_info.key.val[cfg_info.key.len] = '\0';
password = (char *)(&cfg_info.key.val[0]);
}
rt_wlan_connect((char *)cfg_info.info.ssid.val, password);
exit:
rt_mutex_release(&mgnt_mutex);
level = rt_hw_interrupt_disable();
rt_memset(work, 0, sizeof(struct rt_work));
rt_hw_interrupt_enable(level);
}
static void rt_wlan_cyclic_check(void *parameter)
{
struct rt_workqueue *workqueue;
static struct rt_work work;
rt_base_t level;
if ((_is_do_connect() == RT_TRUE) && (work.work_func == RT_NULL))
{
workqueue = rt_wlan_get_workqueue();
if (workqueue != RT_NULL)
{
level = rt_hw_interrupt_disable();
rt_work_init(&work, rt_wlan_auto_connect_run, RT_NULL);
rt_hw_interrupt_enable(level);
if (rt_workqueue_dowork(workqueue, &work) != RT_EOK)
{
level = rt_hw_interrupt_disable();
rt_memset(&work, 0, sizeof(struct rt_work));
rt_hw_interrupt_enable(level);
}
}
}
}
#endif
static void rt_wlan_event_dispatch(struct rt_wlan_device *device, rt_wlan_dev_event_t event, struct rt_wlan_buff *buff, void *parameter)
{
rt_err_t err = RT_NULL;
rt_wlan_event_t user_event = RT_WLAN_EVT_MAX;
int i;
struct rt_wlan_buff user_buff = { 0 };
if (buff)
{
user_buff = *buff;
}
/* Event Handle */
switch (event)
{
case RT_WLAN_DEV_EVT_CONNECT:
{
RT_WLAN_LOG_D("event: CONNECT");
_sta_mgnt.state |= RT_WLAN_STATE_CONNECT;
_sta_mgnt.state &= ~RT_WLAN_STATE_CONNECTING;
user_event = RT_WLAN_EVT_STA_CONNECTED;
TIME_STOP();
user_buff.data = &_sta_mgnt.info;
user_buff.len = sizeof(struct rt_wlan_info);
RT_WLAN_LOG_I("wifi connect success ssid:%s", &_sta_mgnt.info.ssid.val[0]);
break;
}
case RT_WLAN_DEV_EVT_CONNECT_FAIL:
{
RT_WLAN_LOG_D("event: CONNECT_FAIL");
_sta_mgnt.state &= ~RT_WLAN_STATE_CONNECT;
_sta_mgnt.state &= ~RT_WLAN_STATE_CONNECTING;
_sta_mgnt.state &= ~RT_WLAN_STATE_READY;
user_event = RT_WLAN_EVT_STA_CONNECTED_FAIL;
user_buff.data = &_sta_mgnt.info;
user_buff.len = sizeof(struct rt_wlan_info);
if (rt_wlan_get_autoreconnect_mode())
{
TIME_START();
}
break;
}
case RT_WLAN_DEV_EVT_DISCONNECT:
{
RT_WLAN_LOG_D("event: DISCONNECT");
_sta_mgnt.state &= ~RT_WLAN_STATE_CONNECT;
_sta_mgnt.state &= ~RT_WLAN_STATE_READY;
user_event = RT_WLAN_EVT_STA_DISCONNECTED;
user_buff.data = &_sta_mgnt.info;
user_buff.len = sizeof(struct rt_wlan_info);
if (rt_wlan_get_autoreconnect_mode())
{
TIME_START();
}
break;
}
case RT_WLAN_DEV_EVT_AP_START:
{
RT_WLAN_LOG_D("event: AP_START");
_ap_mgnt.state |= RT_WLAN_STATE_ACTIVE;
user_event = RT_WLAN_EVT_AP_START;
user_buff.data = &_ap_mgnt.info;
user_buff.len = sizeof(struct rt_wlan_info);
break;
}
case RT_WLAN_DEV_EVT_AP_STOP:
{
RT_WLAN_LOG_D("event: AP_STOP");
_ap_mgnt.state &= ~RT_WLAN_STATE_ACTIVE;
user_event = RT_WLAN_EVT_AP_STOP;
err = rt_wlan_sta_info_del_all(RT_WAITING_FOREVER);
if (err != RT_NULL)
{
RT_WLAN_LOG_W("AP_STOP event handle fail");
}
user_buff.data = &_ap_mgnt.info;
user_buff.len = sizeof(struct rt_wlan_info);
break;
}
case RT_WLAN_DEV_EVT_AP_ASSOCIATED:
{
RT_WLAN_LOG_D("event: ASSOCIATED");
user_event = RT_WLAN_EVT_AP_ASSOCIATED;
if (user_buff.len != sizeof(struct rt_wlan_info))
break;
err = rt_wlan_sta_info_add(user_buff.data, RT_WAITING_FOREVER);
if (err != RT_EOK)
{
RT_WLAN_LOG_W("AP_ASSOCIATED event handle fail");
}
break;
}
case RT_WLAN_DEV_EVT_AP_DISASSOCIATED:
{
RT_WLAN_LOG_D("event: DISASSOCIATED");
user_event = RT_WLAN_EVT_AP_DISASSOCIATED;
if (user_buff.len != sizeof(struct rt_wlan_info))
break;
err = rt_wlan_sta_info_del(user_buff.data, RT_WAITING_FOREVER);
if (err != RT_EOK)
{
RT_WLAN_LOG_W("AP_DISASSOCIATED event handle fail");
}
break;
}
case RT_WLAN_DEV_EVT_AP_ASSOCIATE_FAILED:
{
RT_WLAN_LOG_D("event: AP_ASSOCIATE_FAILED");
break;
}
case RT_WLAN_DEV_EVT_SCAN_REPORT:
{
RT_WLAN_LOG_D("event: SCAN_REPORT");
user_event = RT_WLAN_EVT_SCAN_REPORT;
if (user_buff.len != sizeof(struct rt_wlan_info))
break;
rt_wlan_scan_result_cache(user_buff.data, 0);
break;
}
case RT_WLAN_DEV_EVT_SCAN_DONE:
{
RT_WLAN_LOG_D("event: SCAN_DONE");
user_buff.data = &scan_result;
user_buff.len = sizeof(scan_result);
user_event = RT_WLAN_EVT_SCAN_DONE;
break;
}
default :
{
RT_WLAN_LOG_D("event: UNKNOWN");
return;
}
}
/* send event */
COMPLETE_LOCK();
for (i = 0; i < sizeof(complete_tab) / sizeof(complete_tab[0]); i++)
{
if ((complete_tab[i] != RT_NULL))
{
complete_tab[i]->event_flag |= 0x1 << event;
rt_event_send(&complete_tab[i]->complete, 0x1 << event);
RT_WLAN_LOG_D("&complete_tab[i]->complete:0x%08x", &complete_tab[i]->complete);
}
}
COMPLETE_UNLOCK();
#ifdef RT_WLAN_WORK_THREAD_ENABLE
rt_wlan_send_to_thread(user_event, RT_NULL, 0);
#else
{
void *user_parameter;
rt_wlan_event_handler handler = RT_NULL;
rt_base_t level;
/* Get user callback */
if (user_event < RT_WLAN_EVT_MAX)
{
level = rt_hw_interrupt_disable();
handler = event_tab[user_event].handler;
user_parameter = event_tab[user_event].parameter;
rt_hw_interrupt_enable(level);
}
/* run user callback fun */
if (handler)
{
RT_WLAN_LOG_D("unknown thread run user callback, event:%d", user_event);
handler(user_event, &user_buff, user_parameter);
}
}
#endif
}
static struct rt_wlan_complete_des *rt_wlan_complete_create(const char *name)
{
struct rt_wlan_complete_des *complete;
int i;
complete = rt_malloc(sizeof(struct rt_wlan_complete_des));
if (complete == RT_NULL)
{
RT_WLAN_LOG_E("complete event create failed");
MGNT_UNLOCK();
return complete;
}
rt_event_init(&complete->complete, name, RT_IPC_FLAG_FIFO);
complete->event_flag = 0;
//protect
COMPLETE_LOCK();
for (i = 0; i < sizeof(complete_tab) / sizeof(complete_tab[0]); i++)
{
if (complete_tab[i] == RT_NULL)
{
complete->index = i;
complete_tab[i] = complete;
break;
}
}
COMPLETE_UNLOCK();
if (i >= sizeof(complete_tab) / sizeof(complete_tab[0]))
{
rt_event_detach(&complete->complete);
rt_free(complete);
complete = RT_NULL;
}
return complete;
}
static rt_err_t rt_wlan_complete_wait(struct rt_wlan_complete_des *complete, rt_uint32_t event,
rt_uint32_t timeout, rt_uint32_t *recved)
{
if (complete == RT_NULL)
{
return -RT_ERROR;
}
/* Check whether there is a waiting event */
if (complete->event_flag & event)
{
*recved = complete->event_flag;
return RT_EOK;
}
else
{
return rt_event_recv(&complete->complete, event, RT_EVENT_FLAG_OR,
rt_tick_from_millisecond(timeout), recved);
}
}
static void rt_wlan_complete_delete(struct rt_wlan_complete_des *complete)
{
if (complete == RT_NULL)
{
return;
}
COMPLETE_LOCK();
complete_tab[complete->index] = RT_NULL;
COMPLETE_UNLOCK();
rt_event_detach(&complete->complete);
rt_free(complete);
}
rt_err_t rt_wlan_set_mode(const char *dev_name, rt_wlan_mode_t mode)
{
rt_device_t device = RT_NULL;
rt_err_t err;
rt_int8_t up_event_flag = 0;
rt_wlan_dev_event_handler handler = RT_NULL;
if ((dev_name == RT_NULL) || (mode >= RT_WLAN_MODE_MAX))
{
RT_WLAN_LOG_E("Parameter Wrongful name:%s mode:%d", dev_name, mode);
return -RT_EINVAL;
}
RT_WLAN_LOG_D("%s is run dev_name:%s mode:%s%s%s", __FUNCTION__, dev_name,
mode == RT_WLAN_NONE ? "NONE" : "",
mode == RT_WLAN_STATION ? "STA" : "",
mode == RT_WLAN_AP ? "AP" : ""
);
/* find device */
device = rt_device_find(dev_name);
if (device == RT_NULL)
{
RT_WLAN_LOG_E("not find device, set mode failed! name:%s", dev_name);
return -RT_EIO;
}
MGNT_LOCK();
if (RT_WLAN_DEVICE(device)->mode == mode)
{
RT_WLAN_LOG_D("L:%d this device mode is set");
MGNT_UNLOCK();
return RT_EOK;
}
if ((mode == RT_WLAN_STATION) &&
(RT_WLAN_DEVICE(device)->flags & RT_WLAN_FLAG_AP_ONLY))
{
RT_WLAN_LOG_I("this device ap mode only");
MGNT_UNLOCK();
return -RT_ERROR;
}
else if ((mode == RT_WLAN_AP) &&
(RT_WLAN_DEVICE(device)->flags & RT_WLAN_FLAG_STA_ONLY))
{
RT_WLAN_LOG_I("this device sta mode only");
MGNT_UNLOCK();
return -RT_ERROR;
}
/*
* device == sta and change to ap, should deinit
* device == ap and change to sta, should deinit
*/
if (((mode == RT_WLAN_STATION) && (RT_WLAN_DEVICE(device) == AP_DEVICE())) ||
((mode == RT_WLAN_AP) && (RT_WLAN_DEVICE(device) == STA_DEVICE())))
{
err = rt_wlan_set_mode(dev_name, RT_WLAN_NONE);
if (err != RT_EOK)
{
RT_WLAN_LOG_E("change mode failed!");
MGNT_UNLOCK();
return err;
}
}
/* init device */
err = rt_wlan_dev_init(RT_WLAN_DEVICE(device), mode);
if (err != RT_EOK)
{
RT_WLAN_LOG_E("F:%s L:%d wlan init failed", __FUNCTION__, __LINE__);
MGNT_UNLOCK();
return err;
}
/* the mode is none */
if (mode == RT_WLAN_NONE)
{
if (_sta_mgnt.device == RT_WLAN_DEVICE(device))
{
_sta_mgnt.device = RT_NULL;
_sta_mgnt.state = 0;
up_event_flag = 1;
handler = RT_NULL;
}
else if (_ap_mgnt.device == RT_WLAN_DEVICE(device))
{
_ap_mgnt.state = 0;
_ap_mgnt.device = RT_NULL;
up_event_flag = 1;
handler = RT_NULL;
}
}
/* save sta device */
else if (mode == RT_WLAN_STATION)
{
up_event_flag = 1;
handler = rt_wlan_event_dispatch;
_sta_mgnt.device = RT_WLAN_DEVICE(device);
}
/* save ap device */
else if (mode == RT_WLAN_AP)
{
up_event_flag = 1;
handler = rt_wlan_event_dispatch;
_ap_mgnt.device = RT_WLAN_DEVICE(device);
}
/* update dev event handle */
if (up_event_flag == 1)
{
if (handler)
{
if (mode == RT_WLAN_STATION)
{
rt_wlan_dev_register_event_handler(RT_WLAN_DEVICE(device), RT_WLAN_DEV_EVT_CONNECT, handler, RT_NULL);
rt_wlan_dev_register_event_handler(RT_WLAN_DEVICE(device), RT_WLAN_DEV_EVT_CONNECT_FAIL, handler, RT_NULL);
rt_wlan_dev_register_event_handler(RT_WLAN_DEVICE(device), RT_WLAN_DEV_EVT_DISCONNECT, handler, RT_NULL);
rt_wlan_dev_register_event_handler(RT_WLAN_DEVICE(device), RT_WLAN_DEV_EVT_SCAN_REPORT, handler, RT_NULL);
rt_wlan_dev_register_event_handler(RT_WLAN_DEVICE(device), RT_WLAN_DEV_EVT_SCAN_DONE, handler, RT_NULL);
}
else if (mode == RT_WLAN_AP)
{
rt_wlan_dev_register_event_handler(RT_WLAN_DEVICE(device), RT_WLAN_DEV_EVT_AP_START, handler, RT_NULL);
rt_wlan_dev_register_event_handler(RT_WLAN_DEVICE(device), RT_WLAN_DEV_EVT_AP_STOP, handler, RT_NULL);
rt_wlan_dev_register_event_handler(RT_WLAN_DEVICE(device), RT_WLAN_DEV_EVT_AP_ASSOCIATED, handler, RT_NULL);
rt_wlan_dev_register_event_handler(RT_WLAN_DEVICE(device), RT_WLAN_DEV_EVT_AP_DISASSOCIATED, handler, RT_NULL);
rt_wlan_dev_register_event_handler(RT_WLAN_DEVICE(device), RT_WLAN_DEV_EVT_AP_ASSOCIATE_FAILED, handler, RT_NULL);
}
}
else
{
rt_wlan_dev_event_t event;
handler = rt_wlan_event_dispatch;
for (event = RT_WLAN_DEV_EVT_INIT_DONE; event < RT_WLAN_DEV_EVT_MAX; event++)
{
rt_wlan_dev_unregister_event_handler(RT_WLAN_DEVICE(device), event, handler);
}
}
}
MGNT_UNLOCK();
/* Mount protocol */
#if defined(RT_WLAN_PROT_ENABLE) && defined(RT_WLAN_DEFAULT_PROT)
if (err == RT_EOK)
{
rt_wlan_prot_attach(dev_name, RT_WLAN_DEFAULT_PROT);
}
#endif
return err;
}
rt_wlan_mode_t rt_wlan_get_mode(const char *dev_name)
{
rt_device_t device = RT_NULL;
rt_wlan_mode_t mode;
if (dev_name == RT_NULL)
{
RT_WLAN_LOG_E("name is null");
return RT_WLAN_NONE;
}
/* find device */
device = rt_device_find(dev_name);
if (device == RT_NULL)
{
RT_WLAN_LOG_E("device not find! name:%s", dev_name);
return RT_WLAN_NONE;
}
/* get mode */
mode = RT_WLAN_DEVICE(device)->mode;
RT_WLAN_LOG_D("%s is run dev_name:%s mode:%s%s%s", __FUNCTION__, dev_name,
mode == RT_WLAN_NONE ? "NONE" : "",
mode == RT_WLAN_STATION ? "STA" : "",
mode == RT_WLAN_AP ? "AP" : "");
return mode;
}
rt_bool_t rt_wlan_find_best_by_cache(const char *ssid, struct rt_wlan_info *info)
{
int i, ssid_len;
struct rt_wlan_info *info_best;
struct rt_wlan_scan_result *result;
ssid_len = rt_strlen(ssid);
result = &scan_result;
info_best = RT_NULL;
SRESULT_LOCK();
for (i = 0; i < result->num; i++)
{
/* SSID is equal. */
if ((result->info[i].ssid.len == ssid_len) &&
(rt_memcmp((char *)&result->info[i].ssid.val[0], ssid, ssid_len) == 0))
{
if (info_best == RT_NULL)
{
info_best = &result->info[i];
continue;
}
/* Signal strength effective */
if ((result->info[i].rssi < 0) && (info_best->rssi < 0))
{
/* Find the strongest signal. */
if (result->info[i].rssi > info_best->rssi)
{
info_best = &result->info[i];
continue;
}
else if (result->info[i].rssi < info_best->rssi)
{
continue;
}
}
/* Finding the fastest signal */
if (result->info[i].datarate > info_best->datarate)
{
info_best = &result->info[i];
continue;
}
}
}
SRESULT_UNLOCK();
if (info_best == RT_NULL)
return RT_FALSE;
*info = *info_best;
return RT_TRUE;
}
rt_err_t rt_wlan_connect(const char *ssid, const char *password)
{
rt_err_t err = RT_EOK;
int ssid_len = 0;
struct rt_wlan_info info;
struct rt_wlan_complete_des *complete;
rt_uint32_t set = 0, recved = 0;
rt_uint32_t scan_retry = RT_WLAN_SCAN_RETRY_CNT;
/* sta dev Can't be NULL */
if (_sta_is_null())
{
return -RT_EIO;
}
RT_WLAN_LOG_D("%s is run ssid:%s password:%s", __FUNCTION__, ssid, password);
if (ssid == RT_NULL)
{
RT_WLAN_LOG_E("ssid is null!");
return -RT_EINVAL;
}
ssid_len = rt_strlen(ssid);
if (ssid_len > RT_WLAN_SSID_MAX_LENGTH)
{
RT_WLAN_LOG_E("ssid is to long! ssid:%s len:%d", ssid, ssid_len);
return -RT_EINVAL;
}
if ((rt_wlan_is_connected() == RT_TRUE) &&
(rt_strcmp((char *)&_sta_mgnt.info.ssid.val[0], ssid) == 0))
{
RT_WLAN_LOG_I("wifi is connect ssid:%s", ssid);
return RT_EOK;
}
/* get info from cache */
INVALID_INFO(&info);
MGNT_LOCK();
while (scan_retry-- && rt_wlan_find_best_by_cache(ssid, &info) != RT_TRUE)
{
rt_wlan_scan_sync();
}
rt_wlan_scan_result_clean();
if (info.ssid.len <= 0)
{
RT_WLAN_LOG_W("not find ap! ssid:%s", ssid);
MGNT_UNLOCK();
return -RT_ERROR;
}
RT_WLAN_LOG_D("find best info ssid:%s mac: %02x %02x %02x %02x %02x %02x",
info.ssid.val, info.bssid[0], info.bssid[1], info.bssid[2], info.bssid[3], info.bssid[4], info.bssid[5]);
/* create event wait complete */
complete = rt_wlan_complete_create("join");
if (complete == RT_NULL)
{
MGNT_UNLOCK();
return -RT_ENOMEM;
}
/* run connect adv */
err = rt_wlan_connect_adv(&info, password);
if (err != RT_EOK)
{
rt_wlan_complete_delete(complete);
MGNT_UNLOCK();
return err;
}
/* Initializing events that need to wait */
set |= 0x1 << RT_WLAN_DEV_EVT_CONNECT;
set |= 0x1 << RT_WLAN_DEV_EVT_CONNECT_FAIL;
/* Check whether there is a waiting event */
rt_wlan_complete_wait(complete, set, RT_WLAN_CONNECT_WAIT_MS, &recved);
rt_wlan_complete_delete(complete);
/* check event */
set = 0x1 << RT_WLAN_DEV_EVT_CONNECT;
if (!(recved & set))
{
RT_WLAN_LOG_I("wifi connect failed!");
MGNT_UNLOCK();
return -RT_ERROR;
}
MGNT_UNLOCK();
return err;
}
rt_err_t rt_wlan_connect_adv(struct rt_wlan_info *info, const char *password)
{
int password_len = 0;
rt_err_t err = RT_EOK;
if (_sta_is_null())
{
return -RT_EIO;
}
if (info == RT_NULL)
{
RT_WLAN_LOG_E("info is null!");
return -RT_EINVAL;
}
RT_WLAN_LOG_D("%s is run ssid:%s password:%s", __FUNCTION__, info->ssid.val, password);
/* Parameter checking */
if (password != RT_NULL)
{
password_len = rt_strlen(password);
if (password_len > RT_WLAN_PASSWORD_MAX_LENGTH)
{
RT_WLAN_LOG_E("password is to long! password:%s len:%d", password, password_len);
return -RT_EINVAL;
}
}
if (info->ssid.len == 0 || info->ssid.len > RT_WLAN_SSID_MAX_LENGTH)
{
RT_WLAN_LOG_E("ssid is zero or to long! ssid:%s len:%d", info->ssid.val, info->ssid.len);
return -RT_EINVAL;
}
/* is connect ? */
MGNT_LOCK();
if (rt_wlan_is_connected())
{
if ((_sta_mgnt.info.ssid.len == info->ssid.len) &&
(_sta_mgnt.key.len == password_len) &&
(rt_memcmp(&_sta_mgnt.info.ssid.val[0], &info->ssid.val[0], info->ssid.len) == 0) &&
(rt_memcmp(&_sta_mgnt.info.bssid[0], &info->bssid[0], RT_WLAN_BSSID_MAX_LENGTH) == 0) &&
(rt_memcmp(&_sta_mgnt.key.val[0], password, password_len) == 0))
{
RT_WLAN_LOG_I("wifi Already Connected");
MGNT_UNLOCK();
return RT_EOK;
}
err = rt_wlan_disconnect();
if (err != RT_EOK)
{
MGNT_UNLOCK();
return err;
}
}
/* save info */
rt_enter_critical();
_sta_mgnt.info = *info;
rt_memcpy(&_sta_mgnt.key.val, password, password_len);
_sta_mgnt.key.len = password_len;
_sta_mgnt.key.val[password_len] = '\0';
rt_exit_critical();
/* run wifi connect */
_sta_mgnt.state |= RT_WLAN_STATE_CONNECTING;
err = rt_wlan_dev_connect(_sta_mgnt.device, info, password, password_len);
if (err != RT_EOK)
{
rt_enter_critical();
rt_memset(&_sta_mgnt.info, 0, sizeof(struct rt_wlan_ssid));
rt_memset(&_sta_mgnt.key, 0, sizeof(struct rt_wlan_key));
rt_exit_critical();
_sta_mgnt.state &= ~RT_WLAN_STATE_CONNECTING;
MGNT_UNLOCK();
return err;
}
MGNT_UNLOCK();
return err;
}
rt_err_t rt_wlan_disconnect(void)
{
rt_err_t err;
struct rt_wlan_complete_des *complete;
rt_uint32_t recved = 0, set = 0;
/* ap dev Can't be empty */
if (_sta_is_null())
{
return -RT_EIO;
}
RT_WLAN_LOG_D("%s is run", __FUNCTION__);
/* run disconnect */
MGNT_LOCK();
/* create event wait complete */
complete = rt_wlan_complete_create("disc");
if (complete == RT_NULL)
{
MGNT_UNLOCK();
return -RT_ENOMEM;
}
err = rt_wlan_dev_disconnect(_sta_mgnt.device);
if (err != RT_EOK)
{
RT_WLAN_LOG_E("wifi disconnect fail");
rt_wlan_complete_delete(complete);
MGNT_UNLOCK();
return err;
}
/* Initializing events that need to wait */
set |= 0x1 << RT_WLAN_DEV_EVT_DISCONNECT;
/* Check whether there is a waiting event */
rt_wlan_complete_wait(complete, set, RT_WLAN_CONNECT_WAIT_MS, &recved);
rt_wlan_complete_delete(complete);
/* check event */
set = 0x1 << RT_WLAN_DEV_EVT_DISCONNECT;
if (!(recved & set))
{
RT_WLAN_LOG_E("disconnect failed!");
MGNT_UNLOCK();
return -RT_ERROR;
}
RT_WLAN_LOG_I("disconnect success!");
MGNT_UNLOCK();
return err;
}
rt_bool_t rt_wlan_is_connected(void)
{
rt_bool_t _connect;
if (_sta_is_null())
{
return RT_FALSE;
}
_connect = _sta_mgnt.state & RT_WLAN_STATE_CONNECT ? RT_TRUE : RT_FALSE;
RT_WLAN_LOG_D("%s is run : %s", __FUNCTION__, _connect ? "connect" : "disconnect");
return _connect;
}
rt_bool_t rt_wlan_is_ready(void)
{
rt_bool_t _ready;
if (_sta_is_null())
{
return RT_FALSE;
}
_ready = _sta_mgnt.state & RT_WLAN_STATE_READY ? RT_TRUE : RT_FALSE;
RT_WLAN_LOG_D("%s is run : %s", __FUNCTION__, _ready ? "ready" : "not ready");
return _ready;
}
rt_err_t rt_wlan_set_mac(rt_uint8_t mac[6])
{
rt_err_t err = RT_EOK;
if (_sta_is_null())
{
return -RT_EIO;
}
RT_WLAN_LOG_D("%s is run mac: %02x:%02x:%02x:%02x:%02x:%02x",
__FUNCTION__, mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
MGNT_LOCK();
err = rt_wlan_dev_set_mac(STA_DEVICE(), mac);
if (err != RT_EOK)
{
RT_WLAN_LOG_E("set sta mac addr fail");
MGNT_UNLOCK();
return err;
}
MGNT_UNLOCK();
return err;
}
rt_err_t rt_wlan_get_mac(rt_uint8_t mac[6])
{
rt_err_t err = RT_EOK;
if (_sta_is_null())
{
return -RT_EIO;
}
MGNT_LOCK();
err = rt_wlan_dev_get_mac(STA_DEVICE(), mac);
if (err != RT_EOK)
{
RT_WLAN_LOG_E("get sta mac addr fail");
MGNT_UNLOCK();
return err;
}
RT_WLAN_LOG_D("%s is run mac: %02x:%02x:%02x:%02x:%02x:%02x",
__FUNCTION__, mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
MGNT_UNLOCK();
return err;
}
rt_err_t rt_wlan_get_info(struct rt_wlan_info *info)
{
if (_sta_is_null())
{
return -RT_EIO;
}
RT_WLAN_LOG_D("%s is run", __FUNCTION__);
if (rt_wlan_is_connected() == RT_TRUE)
{
*info = _sta_mgnt.info;
info->rssi = rt_wlan_get_rssi();
return RT_EOK;
}
return -RT_ERROR;
}
int rt_wlan_get_rssi(void)
{
int rssi = 0;
if (_sta_is_null())
{
return -RT_EIO;
}
MGNT_LOCK();
rssi = rt_wlan_dev_get_rssi(STA_DEVICE());
RT_WLAN_LOG_D("%s is run rssi:%d", __FUNCTION__, rssi);
MGNT_UNLOCK();
return rssi;
}
rt_err_t rt_wlan_start_ap(const char *ssid, const char *password)
{
rt_err_t err = RT_EOK;
int ssid_len = 0;
struct rt_wlan_info info;
struct rt_wlan_complete_des *complete;
rt_uint32_t set = 0, recved = 0;
if (_ap_is_null())
{
return -RT_EIO;
}
if (ssid == RT_NULL) return -RT_EINVAL;
rt_memset(&info, 0, sizeof(struct rt_wlan_info));
RT_WLAN_LOG_D("%s is run ssid:%s password:%s", __FUNCTION__, ssid, password);
if (password)
{
info.security = SECURITY_WPA2_AES_PSK;
}
ssid_len = rt_strlen(ssid);
if (ssid_len > RT_WLAN_SSID_MAX_LENGTH)
{
RT_WLAN_LOG_E("ssid is to long! len:%d", ssid_len);
}
/* copy info */
rt_memcpy(&info.ssid.val, ssid, ssid_len);
info.ssid.len = ssid_len;
info.channel = 6;
info.band = RT_802_11_BAND_2_4GHZ;
/* Initializing events that need to wait */
MGNT_LOCK();
/* create event wait complete */
complete = rt_wlan_complete_create("start_ap");
if (complete == RT_NULL)
{
MGNT_UNLOCK();
return -RT_ENOMEM;
}
/* start ap */
err = rt_wlan_start_ap_adv(&info, password);
if (err != RT_EOK)
{
rt_wlan_complete_delete(complete);
RT_WLAN_LOG_I("start ap failed!");
MGNT_UNLOCK();
return err;
}
/* Initializing events that need to wait */
set |= 0x1 << RT_WLAN_DEV_EVT_AP_START;
set |= 0x1 << RT_WLAN_DEV_EVT_AP_STOP;
/* Check whether there is a waiting event */
rt_wlan_complete_wait(complete, set, RT_WLAN_START_AP_WAIT_MS, &recved);
rt_wlan_complete_delete(complete);
/* check event */
set = 0x1 << RT_WLAN_DEV_EVT_AP_START;
if (!(recved & set))
{
RT_WLAN_LOG_I("start ap failed!");
MGNT_UNLOCK();
return -RT_ERROR;
}
RT_WLAN_LOG_I("start ap successs!");
MGNT_UNLOCK();
return err;
}
rt_err_t rt_wlan_start_ap_adv(struct rt_wlan_info *info, const char *password)
{
rt_err_t err = RT_EOK;
int password_len = 0;
if (_ap_is_null())
{
return -RT_EIO;
}
RT_WLAN_LOG_D("%s is run", __FUNCTION__);
if (password != RT_NULL)
{
password_len = rt_strlen(password);
}
if (password_len > RT_WLAN_PASSWORD_MAX_LENGTH)
{
RT_WLAN_LOG_E("key is to long! len:%d", password_len);
return -RT_EINVAL;
}
/* is start up ? */
MGNT_LOCK();
if (rt_wlan_ap_is_active())
{
if ((_ap_mgnt.info.ssid.len == info->ssid.len) &&
(_ap_mgnt.info.security == info->security) &&
(_ap_mgnt.info.channel == info->channel) &&
(_ap_mgnt.info.hidden == info->hidden) &&
(_ap_mgnt.key.len == password_len) &&
(rt_memcmp(&_ap_mgnt.info.ssid.val[0], &info->ssid.val[0], info->ssid.len) == 0) &&
(rt_memcmp(&_ap_mgnt.key.val[0], password, password_len)))
{
RT_WLAN_LOG_D("wifi Already Start");
MGNT_UNLOCK();
return RT_EOK;
}
}
err = rt_wlan_dev_ap_start(AP_DEVICE(), info, password, password_len);
if (err != RT_EOK)
{
MGNT_UNLOCK();
return err;
}
rt_memcpy(&_ap_mgnt.info, info, sizeof(struct rt_wlan_info));
rt_memcpy(&_ap_mgnt.key.val, password, password_len);
_ap_mgnt.key.len = password_len;
MGNT_UNLOCK();
return err;
}
rt_bool_t rt_wlan_ap_is_active(void)
{
rt_bool_t _active = RT_FALSE;
if (_ap_is_null())
{
return RT_FALSE;
}
_active = _ap_mgnt.state & RT_WLAN_STATE_ACTIVE ? RT_TRUE : RT_FALSE;
RT_WLAN_LOG_D("%s is run active:%s", __FUNCTION__, _active ? "Active" : "Inactive");
return _active;
}
rt_err_t rt_wlan_ap_stop(void)
{
rt_err_t err = RT_EOK;
struct rt_wlan_complete_des *complete;
rt_uint32_t set = 0, recved = 0;
if (_ap_is_null())
{
return -RT_EIO;
}
RT_WLAN_LOG_D("%s is run", __FUNCTION__);
MGNT_LOCK();
/* create event wait complete */
complete = rt_wlan_complete_create("stop_ap");
if (complete == RT_NULL)
{
MGNT_UNLOCK();
return -RT_ENOMEM;
}
err = rt_wlan_dev_ap_stop(AP_DEVICE());
if (err != RT_EOK)
{
RT_WLAN_LOG_E("ap stop fail");
rt_wlan_complete_delete(complete);
MGNT_UNLOCK();
return err;
}
/* Initializing events that need to wait */
set |= 0x1 << RT_WLAN_DEV_EVT_AP_STOP;
/* Check whether there is a waiting event */
rt_wlan_complete_wait(complete, set, RT_WLAN_START_AP_WAIT_MS, &recved);
rt_wlan_complete_delete(complete);
/* check event */
set = 0x1 << RT_WLAN_DEV_EVT_AP_STOP;
if (!(recved & set))
{
RT_WLAN_LOG_I("ap stop failed!");
MGNT_UNLOCK();
return -RT_ERROR;
}
RT_WLAN_LOG_I("ap stop success!");
MGNT_UNLOCK();
return err;
}
rt_err_t rt_wlan_ap_get_info(struct rt_wlan_info *info)
{
if (_ap_is_null())
{
return -RT_EIO;
}
RT_WLAN_LOG_D("%s is run", __FUNCTION__);
if (rt_wlan_ap_is_active() == RT_TRUE)
{
*info = _ap_mgnt.info;
return RT_EOK;
}
return -RT_ERROR;
}
/* get sta number */
int rt_wlan_ap_get_sta_num(void)
{
int sta_num = 0;
STAINFO_LOCK();
sta_num = sta_info.num;
STAINFO_UNLOCK();
RT_WLAN_LOG_D("%s is run num:%d", __FUNCTION__, sta_num);
return sta_num;
}
/* get sta info */
int rt_wlan_ap_get_sta_info(struct rt_wlan_info *info, int num)
{
int sta_num = 0, i = 0;
struct rt_wlan_sta_list *sta_list;
STAINFO_LOCK();
/* sta_num = min(sta_info.num, num) */
sta_num = sta_info.num > num ? num : sta_info.num;
for (sta_list = sta_info.node; sta_list != RT_NULL && i < sta_num; sta_list = sta_list->next)
{
info[i] = sta_list->info;
i ++;
}
STAINFO_UNLOCK();
RT_WLAN_LOG_D("%s is run num:%d", __FUNCTION__, i);
return i;
}
/* deauth sta */
rt_err_t rt_wlan_ap_deauth_sta(rt_uint8_t *mac)
{
rt_err_t err = RT_EOK;
struct rt_wlan_sta_list *sta_list;
rt_bool_t find_flag = RT_FALSE;
if (_ap_is_null())
{
return -RT_EIO;
}
RT_WLAN_LOG_D("%s is run mac: %02x:%02x:%02x:%02x:%02x:%02x:%d",
__FUNCTION__, mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
if (mac == RT_NULL)
{
RT_WLAN_LOG_E("mac addr is null");
return -RT_EINVAL;
}
MGNT_LOCK();
if (sta_info.node == RT_NULL || sta_info.num == 0)
{
RT_WLAN_LOG_E("No AP");
MGNT_UNLOCK();
return -RT_ERROR;
}
STAINFO_LOCK();
/* Search for MAC address from sta list */
for (sta_list = sta_info.node; sta_list != RT_NULL; sta_list = sta_list->next)
{
if (rt_memcmp(&sta_list->info.bssid[0], &mac[0], RT_WLAN_BSSID_MAX_LENGTH) == 0)
{
find_flag = RT_TRUE;
break;
}
}
STAINFO_UNLOCK();
/* No MAC address was found. return */
if (find_flag != RT_TRUE)
{
RT_WLAN_LOG_E("Not find mac addr");
MGNT_UNLOCK();
return -RT_ERROR;
}
/* Kill STA */
err = rt_wlan_dev_ap_deauth(AP_DEVICE(), mac);
if (err != RT_NULL)
{
RT_WLAN_LOG_E("deauth sta failed");
MGNT_UNLOCK();
return err;
}
MGNT_UNLOCK();
return err;
}
rt_err_t rt_wlan_ap_set_country(rt_country_code_t country_code)
{
rt_err_t err = RT_EOK;
if (_ap_is_null())
{
return -RT_EIO;
}
RT_WLAN_LOG_D("%s is run country:%d", __FUNCTION__, country_code);
MGNT_LOCK();
err = rt_wlan_dev_set_country(AP_DEVICE(), country_code);
MGNT_UNLOCK();
return err;
}
rt_country_code_t rt_wlan_ap_get_country(void)
{
rt_country_code_t country_code = RT_COUNTRY_UNKNOWN;
if (_ap_is_null())
{
return country_code;
}
MGNT_LOCK();
country_code = rt_wlan_dev_get_country(AP_DEVICE());
RT_WLAN_LOG_D("%s is run country:%d", __FUNCTION__, country_code);
MGNT_UNLOCK();
return country_code;
}
void rt_wlan_config_autoreconnect(rt_bool_t enable)
{
#ifdef RT_WLAN_AUTO_CONNECT_ENABLE
RT_WLAN_LOG_D("%s is run enable:%d", __FUNCTION__, enable);
MGNT_LOCK();
if (enable)
{
TIME_START();
_sta_mgnt.flags |= RT_WLAN_STATE_AUTOEN;
}
else
{
TIME_STOP();
_sta_mgnt.flags &= ~RT_WLAN_STATE_AUTOEN;
}
MGNT_UNLOCK();
#endif
}
rt_bool_t rt_wlan_get_autoreconnect_mode(void)
{
#ifdef RT_WLAN_AUTO_CONNECT_ENABLE
rt_bool_t enable = 0;
enable = _sta_mgnt.flags & RT_WLAN_STATE_AUTOEN ? 1 : 0;
RT_WLAN_LOG_D("%s is run enable:%d", __FUNCTION__, enable);
return enable;
#else
return RT_FALSE;
#endif
}
/* Call the underlying scan function, which is asynchronous.
The hotspots scanned are returned by callbacks */
rt_err_t rt_wlan_scan(void)
{
rt_err_t err = RT_EOK;
if (_sta_is_null())
{
return -RT_EIO;
}
RT_WLAN_LOG_D("%s is run", __FUNCTION__);
MGNT_LOCK();
err = rt_wlan_dev_scan(STA_DEVICE(), RT_NULL);
MGNT_UNLOCK();
return err;
}
struct rt_wlan_scan_result *rt_wlan_scan_sync(void)
{
struct rt_wlan_scan_result *result;
/* Execute synchronous scan function */
MGNT_LOCK();
result = rt_wlan_scan_with_info(RT_NULL);
MGNT_UNLOCK();
return result;
}
struct rt_wlan_scan_result *rt_wlan_scan_with_info(struct rt_wlan_info *info)
{
rt_err_t err = RT_EOK;
struct rt_wlan_complete_des *complete;
rt_uint32_t set = 0, recved = 0;
static struct rt_wlan_info scan_filter_info;
rt_base_t level;
struct rt_wlan_scan_result *result;
if (_sta_is_null())
{
return RT_NULL;
}
RT_WLAN_LOG_D("%s is run", __FUNCTION__);
if (info != RT_NULL && info->ssid.len > RT_WLAN_SSID_MAX_LENGTH)
{
RT_WLAN_LOG_E("ssid is to long!");
return RT_NULL;
}
/* Create an event that needs to wait. */
MGNT_LOCK();
complete = rt_wlan_complete_create("scan");
if (complete == RT_NULL)
{
MGNT_UNLOCK();
return &scan_result;
}
/* add scan info filter */
if (info)
{
scan_filter_info = *info;
level = rt_hw_interrupt_disable();
scan_filter = &scan_filter_info;
rt_hw_interrupt_enable(level);
}
/* run scan */
err = rt_wlan_dev_scan(STA_DEVICE(), info);
if (err != RT_EOK)
{
rt_wlan_complete_delete(complete);
RT_WLAN_LOG_E("scan sync fail");
result = RT_NULL;
goto scan_exit;
}
/* Initializing events that need to wait */
set |= 0x1 << RT_WLAN_DEV_EVT_SCAN_DONE;
/* Check whether there is a waiting event */
rt_wlan_complete_wait(complete, set, RT_WLAN_CONNECT_WAIT_MS, &recved);
rt_wlan_complete_delete(complete);
/* check event */
set = 0x1 << RT_WLAN_DEV_EVT_SCAN_DONE;
if (!(recved & set))
{
RT_WLAN_LOG_E("scan wait timeout!");
result = &scan_result;
goto scan_exit;
}
scan_exit:
MGNT_UNLOCK();
level = rt_hw_interrupt_disable();
scan_filter = RT_NULL;
rt_hw_interrupt_enable(level);
result = &scan_result;
return result;
}
int rt_wlan_scan_get_info_num(void)
{
int num = 0;
num = scan_result.num;
RT_WLAN_LOG_D("%s is run num:%d", __FUNCTION__, num);
return num;
}
int rt_wlan_scan_get_info(struct rt_wlan_info *info, int num)
{
int _num = 0;
SRESULT_LOCK();
if (scan_result.num && num > 0)
{
_num = scan_result.num > num ? num : scan_result.num;
rt_memcpy(info, scan_result.info, _num * sizeof(struct rt_wlan_info));
}
SRESULT_UNLOCK();
return _num;
}
struct rt_wlan_scan_result *rt_wlan_scan_get_result(void)
{
return &scan_result;
}
void rt_wlan_scan_result_clean(void)
{
MGNT_LOCK();
SRESULT_LOCK();
/* If there is data */
if (scan_result.num)
{
scan_result.num = 0;
rt_free(scan_result.info);
scan_result.info = RT_NULL;
}
SRESULT_UNLOCK();
MGNT_UNLOCK();
}
int rt_wlan_scan_find_cache(struct rt_wlan_info *info, struct rt_wlan_info *out_info, int num)
{
int i = 0, count = 0;
struct rt_wlan_info *scan_info;
rt_bool_t is_equ;
if ((out_info == RT_NULL) || (info == RT_NULL) || (num <= 0))
{
return 0;
}
SRESULT_LOCK();
/* Traversing the cache to find a qualified hot spot information */
for (i = 0; (i < scan_result.num) && (count < num); i++)
{
scan_info = &scan_result.info[i];
is_equ = rt_wlan_info_isequ(scan_info, info);
/* Determine whether to find */
if (is_equ)
{
rt_memcpy(&out_info[count], scan_info, sizeof(struct rt_wlan_info));
count ++;
}
}
SRESULT_UNLOCK();
return count;
}
rt_err_t rt_wlan_set_powersave(int level)
{
rt_err_t err = RT_EOK;
if (_sta_is_null())
{
return -RT_EIO;
}
RT_WLAN_LOG_D("%s is run", __FUNCTION__);
MGNT_LOCK();
err = rt_wlan_dev_set_powersave(STA_DEVICE(), level);
MGNT_UNLOCK();
return err;
}
int rt_wlan_get_powersave(void)
{
int level;
if (_sta_is_null())
{
return -1;
}
RT_WLAN_LOG_D("%s is run", __FUNCTION__);
MGNT_LOCK();
level = rt_wlan_dev_get_powersave(STA_DEVICE());
MGNT_UNLOCK();
return level;
}
rt_err_t rt_wlan_register_event_handler(rt_wlan_event_t event, rt_wlan_event_handler handler, void *parameter)
{
rt_base_t level;
if (event >= RT_WLAN_EVT_MAX)
{
return RT_EINVAL;
}
RT_WLAN_LOG_D("%s is run event:%d", __FUNCTION__, event);
MGNT_LOCK();
/* Registering Callbacks */
level = rt_hw_interrupt_disable();
event_tab[event].handler = handler;
event_tab[event].parameter = parameter;
rt_hw_interrupt_enable(level);
MGNT_UNLOCK();
return RT_EOK;
}
rt_err_t rt_wlan_unregister_event_handler(rt_wlan_event_t event)
{
rt_base_t level;
if (event >= RT_WLAN_EVT_MAX)
{
return RT_EINVAL;
}
RT_WLAN_LOG_D("%s is run event:%d", __FUNCTION__, event);
MGNT_LOCK();
/* unregister*/
level = rt_hw_interrupt_disable();
event_tab[event].handler = RT_NULL;
event_tab[event].parameter = RT_NULL;
rt_hw_interrupt_enable(level);
MGNT_UNLOCK();
return RT_EOK;
}
void rt_wlan_mgnt_lock(void)
{
MGNT_LOCK();
}
void rt_wlan_mgnt_unlock(void)
{
MGNT_UNLOCK();
}
int rt_wlan_prot_ready_event(struct rt_wlan_device *wlan, struct rt_wlan_buff *buff)
{
rt_base_t level;
if ((wlan == RT_NULL) || (_sta_mgnt.device != wlan) ||
(!(_sta_mgnt.state & RT_WLAN_STATE_CONNECT)))
{
return -1;
}
if (_sta_mgnt.state & RT_WLAN_STATE_READY)
{
return 0;
}
level = rt_hw_interrupt_disable();
_sta_mgnt.state |= RT_WLAN_STATE_READY;
rt_hw_interrupt_enable(level);
#ifdef RT_WLAN_WORK_THREAD_ENABLE
rt_wlan_send_to_thread(RT_WLAN_EVT_READY, buff->data, buff->len);
#else
{
void *user_parameter;
rt_wlan_event_handler handler = RT_NULL;
level = rt_hw_interrupt_disable();
handler = event_tab[RT_WLAN_EVT_READY].handler;
user_parameter = event_tab[RT_WLAN_EVT_READY].parameter;
rt_hw_interrupt_enable(level);
if (handler)
{
handler(RT_WLAN_EVT_READY, buff, user_parameter);
}
}
#endif
return 0;
}
int rt_wlan_init(void)
{
static rt_int8_t _init_flag = 0;
/* Execute only once */
if (_init_flag == 0)
{
rt_memset(&_sta_mgnt, 0, sizeof(struct rt_wlan_mgnt_des));
rt_memset(&_ap_mgnt, 0, sizeof(struct rt_wlan_mgnt_des));
rt_memset(&scan_result, 0, sizeof(struct rt_wlan_scan_result));
rt_memset(&sta_info, 0, sizeof(struct rt_wlan_sta_des));
rt_mutex_init(&mgnt_mutex, "mgnt", RT_IPC_FLAG_FIFO);
rt_mutex_init(&scan_result_mutex, "scan", RT_IPC_FLAG_FIFO);
rt_mutex_init(&sta_info_mutex, "sta", RT_IPC_FLAG_FIFO);
rt_mutex_init(&complete_mutex, "complete", RT_IPC_FLAG_FIFO);
#ifdef RT_WLAN_AUTO_CONNECT_ENABLE
rt_timer_init(&reconnect_time, "wifi_tim", rt_wlan_cyclic_check, RT_NULL,
rt_tick_from_millisecond(AUTO_CONNECTION_PERIOD_MS),
RT_TIMER_FLAG_PERIODIC | RT_TIMER_FLAG_SOFT_TIMER);
#endif
_init_flag = 1;
}
return 0;
}
INIT_PREV_EXPORT(rt_wlan_init);
#endif
|
632977.c | /*
* drivers/pci/iov.c
*
* Copyright (C) 2009 Intel Corporation, Yu Zhao <[email protected]>
*
* PCI Express I/O Virtualization (IOV) support.
* Single Root IOV 1.0
* Address Translation Service 1.0
*/
#include <linux/pci.h>
#include <linux/slab.h>
#include <linux/mutex.h>
#include <linux/export.h>
#include <linux/string.h>
#include <linux/delay.h>
#include <linux/pci-ats.h>
#include "pci.h"
#define VIRTFN_ID_LEN 16
int pci_iov_virtfn_bus(struct pci_dev *dev, int vf_id)
{
if (!dev->is_physfn)
return -EINVAL;
return dev->bus->number + ((dev->devfn + dev->sriov->offset +
dev->sriov->stride * vf_id) >> 8);
}
int pci_iov_virtfn_devfn(struct pci_dev *dev, int vf_id)
{
if (!dev->is_physfn)
return -EINVAL;
return (dev->devfn + dev->sriov->offset +
dev->sriov->stride * vf_id) & 0xff;
}
/*
* Per SR-IOV spec sec 3.3.10 and 3.3.11, First VF Offset and VF Stride may
* change when NumVFs changes.
*
* Update iov->offset and iov->stride when NumVFs is written.
*/
static inline void pci_iov_set_numvfs(struct pci_dev *dev, int nr_virtfn)
{
struct pci_sriov *iov = dev->sriov;
pci_write_config_word(dev, iov->pos + PCI_SRIOV_NUM_VF, nr_virtfn);
pci_read_config_word(dev, iov->pos + PCI_SRIOV_VF_OFFSET, &iov->offset);
pci_read_config_word(dev, iov->pos + PCI_SRIOV_VF_STRIDE, &iov->stride);
}
/*
* The PF consumes one bus number. NumVFs, First VF Offset, and VF Stride
* determine how many additional bus numbers will be consumed by VFs.
*
* Iterate over all valid NumVFs, validate offset and stride, and calculate
* the maximum number of bus numbers that could ever be required.
*/
static int compute_max_vf_buses(struct pci_dev *dev)
{
struct pci_sriov *iov = dev->sriov;
int nr_virtfn, busnr, rc = 0;
for (nr_virtfn = iov->total_VFs; nr_virtfn; nr_virtfn--) {
pci_iov_set_numvfs(dev, nr_virtfn);
if (!iov->offset || (nr_virtfn > 1 && !iov->stride)) {
rc = -EIO;
goto out;
}
busnr = pci_iov_virtfn_bus(dev, nr_virtfn - 1);
if (busnr > iov->max_VF_buses)
iov->max_VF_buses = busnr;
}
out:
pci_iov_set_numvfs(dev, 0);
return rc;
}
static struct pci_bus *virtfn_add_bus(struct pci_bus *bus, int busnr)
{
struct pci_bus *child;
if (bus->number == busnr)
return bus;
child = pci_find_bus(pci_domain_nr(bus), busnr);
if (child)
return child;
child = pci_add_new_bus(bus, NULL, busnr);
if (!child)
return NULL;
pci_bus_insert_busn_res(child, busnr, busnr);
return child;
}
static void virtfn_remove_bus(struct pci_bus *physbus, struct pci_bus *virtbus)
{
if (physbus != virtbus && list_empty(&virtbus->devices))
pci_remove_bus(virtbus);
}
resource_size_t pci_iov_resource_size(struct pci_dev *dev, int resno)
{
if (!dev->is_physfn)
return 0;
return dev->sriov->barsz[resno - PCI_IOV_RESOURCES];
}
static int virtfn_add(struct pci_dev *dev, int id, int reset)
{
int i;
int rc = -ENOMEM;
u64 size;
char buf[VIRTFN_ID_LEN];
struct pci_dev *virtfn;
struct resource *res;
struct pci_sriov *iov = dev->sriov;
struct pci_bus *bus;
mutex_lock(&iov->dev->sriov->lock);
bus = virtfn_add_bus(dev->bus, pci_iov_virtfn_bus(dev, id));
if (!bus)
goto failed;
virtfn = pci_alloc_dev(bus);
if (!virtfn)
goto failed0;
virtfn->devfn = pci_iov_virtfn_devfn(dev, id);
virtfn->vendor = dev->vendor;
pci_read_config_word(dev, iov->pos + PCI_SRIOV_VF_DID, &virtfn->device);
pci_setup_device(virtfn);
virtfn->dev.parent = dev->dev.parent;
virtfn->physfn = pci_dev_get(dev);
virtfn->is_virtfn = 1;
virtfn->multifunction = 0;
for (i = 0; i < PCI_SRIOV_NUM_BARS; i++) {
res = &dev->resource[i + PCI_IOV_RESOURCES];
if (!res->parent)
continue;
virtfn->resource[i].name = pci_name(virtfn);
virtfn->resource[i].flags = res->flags;
size = pci_iov_resource_size(dev, i + PCI_IOV_RESOURCES);
virtfn->resource[i].start = res->start + size * id;
virtfn->resource[i].end = virtfn->resource[i].start + size - 1;
rc = request_resource(res, &virtfn->resource[i]);
BUG_ON(rc);
}
if (reset)
__pci_reset_function(virtfn);
pci_device_add(virtfn, virtfn->bus);
mutex_unlock(&iov->dev->sriov->lock);
pci_bus_add_device(virtfn);
sprintf(buf, "virtfn%u", id);
rc = sysfs_create_link(&dev->dev.kobj, &virtfn->dev.kobj, buf);
if (rc)
goto failed1;
rc = sysfs_create_link(&virtfn->dev.kobj, &dev->dev.kobj, "physfn");
if (rc)
goto failed2;
kobject_uevent(&virtfn->dev.kobj, KOBJ_CHANGE);
return 0;
failed2:
sysfs_remove_link(&dev->dev.kobj, buf);
failed1:
pci_dev_put(dev);
mutex_lock(&iov->dev->sriov->lock);
pci_stop_and_remove_bus_device(virtfn);
failed0:
virtfn_remove_bus(dev->bus, bus);
failed:
mutex_unlock(&iov->dev->sriov->lock);
return rc;
}
static void virtfn_remove(struct pci_dev *dev, int id, int reset)
{
char buf[VIRTFN_ID_LEN];
struct pci_dev *virtfn;
struct pci_sriov *iov = dev->sriov;
virtfn = pci_get_domain_bus_and_slot(pci_domain_nr(dev->bus),
pci_iov_virtfn_bus(dev, id),
pci_iov_virtfn_devfn(dev, id));
if (!virtfn)
return;
if (reset) {
device_release_driver(&virtfn->dev);
__pci_reset_function(virtfn);
}
sprintf(buf, "virtfn%u", id);
sysfs_remove_link(&dev->dev.kobj, buf);
/*
* pci_stop_dev() could have been called for this virtfn already,
* so the directory for the virtfn may have been removed before.
* Double check to avoid spurious sysfs warnings.
*/
if (virtfn->dev.kobj.sd)
sysfs_remove_link(&virtfn->dev.kobj, "physfn");
mutex_lock(&iov->dev->sriov->lock);
pci_stop_and_remove_bus_device(virtfn);
virtfn_remove_bus(dev->bus, virtfn->bus);
mutex_unlock(&iov->dev->sriov->lock);
/* balance pci_get_domain_bus_and_slot() */
pci_dev_put(virtfn);
pci_dev_put(dev);
}
int __weak pcibios_sriov_enable(struct pci_dev *pdev, u16 num_vfs)
{
return 0;
}
static int sriov_enable(struct pci_dev *dev, int nr_virtfn)
{
int rc;
int i, j;
int nres;
u16 offset, stride, initial;
struct resource *res;
struct pci_dev *pdev;
struct pci_sriov *iov = dev->sriov;
int bars = 0;
int bus;
int retval;
if (!nr_virtfn)
return 0;
if (iov->num_VFs)
return -EINVAL;
pci_read_config_word(dev, iov->pos + PCI_SRIOV_INITIAL_VF, &initial);
if (initial > iov->total_VFs ||
(!(iov->cap & PCI_SRIOV_CAP_VFM) && (initial != iov->total_VFs)))
return -EIO;
if (nr_virtfn < 0 || nr_virtfn > iov->total_VFs ||
(!(iov->cap & PCI_SRIOV_CAP_VFM) && (nr_virtfn > initial)))
return -EINVAL;
pci_read_config_word(dev, iov->pos + PCI_SRIOV_VF_OFFSET, &offset);
pci_read_config_word(dev, iov->pos + PCI_SRIOV_VF_STRIDE, &stride);
if (!offset || (nr_virtfn > 1 && !stride))
return -EIO;
nres = 0;
for (i = 0; i < PCI_SRIOV_NUM_BARS; i++) {
bars |= (1 << (i + PCI_IOV_RESOURCES));
res = &dev->resource[i + PCI_IOV_RESOURCES];
if (res->parent)
nres++;
}
if (nres != iov->nres) {
dev_err(&dev->dev, "not enough MMIO resources for SR-IOV\n");
return -ENOMEM;
}
iov->offset = offset;
iov->stride = stride;
bus = pci_iov_virtfn_bus(dev, nr_virtfn - 1);
if (bus > dev->bus->busn_res.end) {
dev_err(&dev->dev, "can't enable %d VFs (bus %02x out of range of %pR)\n",
nr_virtfn, bus, &dev->bus->busn_res);
return -ENOMEM;
}
if (pci_enable_resources(dev, bars)) {
dev_err(&dev->dev, "SR-IOV: IOV BARS not allocated\n");
return -ENOMEM;
}
if (iov->link != dev->devfn) {
pdev = pci_get_slot(dev->bus, iov->link);
if (!pdev)
return -ENODEV;
if (!pdev->is_physfn) {
pci_dev_put(pdev);
return -ENOSYS;
}
rc = sysfs_create_link(&dev->dev.kobj,
&pdev->dev.kobj, "dep_link");
pci_dev_put(pdev);
if (rc)
return rc;
}
pci_iov_set_numvfs(dev, nr_virtfn);
iov->ctrl |= PCI_SRIOV_CTRL_VFE | PCI_SRIOV_CTRL_MSE;
pci_cfg_access_lock(dev);
pci_write_config_word(dev, iov->pos + PCI_SRIOV_CTRL, iov->ctrl);
msleep(100);
pci_cfg_access_unlock(dev);
iov->initial_VFs = initial;
if (nr_virtfn < initial)
initial = nr_virtfn;
if ((retval = pcibios_sriov_enable(dev, initial))) {
dev_err(&dev->dev, "failure %d from pcibios_sriov_enable()\n",
retval);
return retval;
}
for (i = 0; i < initial; i++) {
rc = virtfn_add(dev, i, 0);
if (rc)
goto failed;
}
kobject_uevent(&dev->dev.kobj, KOBJ_CHANGE);
iov->num_VFs = nr_virtfn;
return 0;
failed:
for (j = 0; j < i; j++)
virtfn_remove(dev, j, 0);
iov->ctrl &= ~(PCI_SRIOV_CTRL_VFE | PCI_SRIOV_CTRL_MSE);
pci_cfg_access_lock(dev);
pci_write_config_word(dev, iov->pos + PCI_SRIOV_CTRL, iov->ctrl);
pci_iov_set_numvfs(dev, 0);
ssleep(1);
pci_cfg_access_unlock(dev);
if (iov->link != dev->devfn)
sysfs_remove_link(&dev->dev.kobj, "dep_link");
return rc;
}
int __weak pcibios_sriov_disable(struct pci_dev *pdev)
{
return 0;
}
static void sriov_disable(struct pci_dev *dev)
{
int i;
struct pci_sriov *iov = dev->sriov;
if (!iov->num_VFs)
return;
for (i = 0; i < iov->num_VFs; i++)
virtfn_remove(dev, i, 0);
pcibios_sriov_disable(dev);
iov->ctrl &= ~(PCI_SRIOV_CTRL_VFE | PCI_SRIOV_CTRL_MSE);
pci_cfg_access_lock(dev);
pci_write_config_word(dev, iov->pos + PCI_SRIOV_CTRL, iov->ctrl);
ssleep(1);
pci_cfg_access_unlock(dev);
if (iov->link != dev->devfn)
sysfs_remove_link(&dev->dev.kobj, "dep_link");
iov->num_VFs = 0;
pci_iov_set_numvfs(dev, 0);
}
static int sriov_init(struct pci_dev *dev, int pos)
{
int i, bar64;
int rc;
int nres;
u32 pgsz;
u16 ctrl, total;
struct pci_sriov *iov;
struct resource *res;
struct pci_dev *pdev;
if (pci_pcie_type(dev) != PCI_EXP_TYPE_RC_END &&
pci_pcie_type(dev) != PCI_EXP_TYPE_ENDPOINT)
return -ENODEV;
pci_read_config_word(dev, pos + PCI_SRIOV_CTRL, &ctrl);
if (ctrl & PCI_SRIOV_CTRL_VFE) {
pci_write_config_word(dev, pos + PCI_SRIOV_CTRL, 0);
ssleep(1);
}
pci_read_config_word(dev, pos + PCI_SRIOV_TOTAL_VF, &total);
if (!total)
return 0;
ctrl = 0;
list_for_each_entry(pdev, &dev->bus->devices, bus_list)
if (pdev->is_physfn)
goto found;
pdev = NULL;
if (pci_ari_enabled(dev->bus))
ctrl |= PCI_SRIOV_CTRL_ARI;
found:
pci_write_config_word(dev, pos + PCI_SRIOV_CTRL, ctrl);
pci_read_config_dword(dev, pos + PCI_SRIOV_SUP_PGSIZE, &pgsz);
i = PAGE_SHIFT > 12 ? PAGE_SHIFT - 12 : 0;
pgsz &= ~((1 << i) - 1);
if (!pgsz)
return -EIO;
pgsz &= ~(pgsz - 1);
pci_write_config_dword(dev, pos + PCI_SRIOV_SYS_PGSIZE, pgsz);
iov = kzalloc(sizeof(*iov), GFP_KERNEL);
if (!iov)
return -ENOMEM;
nres = 0;
for (i = 0; i < PCI_SRIOV_NUM_BARS; i++) {
res = &dev->resource[i + PCI_IOV_RESOURCES];
bar64 = __pci_read_base(dev, pci_bar_unknown, res,
pos + PCI_SRIOV_BAR + i * 4);
if (!res->flags)
continue;
if (resource_size(res) & (PAGE_SIZE - 1)) {
rc = -EIO;
goto failed;
}
iov->barsz[i] = resource_size(res);
res->end = res->start + resource_size(res) * total - 1;
dev_info(&dev->dev, "VF(n) BAR%d space: %pR (contains BAR%d for %d VFs)\n",
i, res, i, total);
i += bar64;
nres++;
}
iov->pos = pos;
iov->nres = nres;
iov->ctrl = ctrl;
iov->total_VFs = total;
iov->pgsz = pgsz;
iov->self = dev;
pci_read_config_dword(dev, pos + PCI_SRIOV_CAP, &iov->cap);
pci_read_config_byte(dev, pos + PCI_SRIOV_FUNC_LINK, &iov->link);
if (pci_pcie_type(dev) == PCI_EXP_TYPE_RC_END)
iov->link = PCI_DEVFN(PCI_SLOT(dev->devfn), iov->link);
if (pdev)
iov->dev = pci_dev_get(pdev);
else
iov->dev = dev;
mutex_init(&iov->lock);
dev->sriov = iov;
dev->is_physfn = 1;
rc = compute_max_vf_buses(dev);
if (rc)
goto fail_max_buses;
return 0;
fail_max_buses:
dev->sriov = NULL;
dev->is_physfn = 0;
failed:
for (i = 0; i < PCI_SRIOV_NUM_BARS; i++) {
res = &dev->resource[i + PCI_IOV_RESOURCES];
res->flags = 0;
}
kfree(iov);
return rc;
}
static void sriov_release(struct pci_dev *dev)
{
BUG_ON(dev->sriov->num_VFs);
if (dev != dev->sriov->dev)
pci_dev_put(dev->sriov->dev);
mutex_destroy(&dev->sriov->lock);
kfree(dev->sriov);
dev->sriov = NULL;
}
static void sriov_restore_state(struct pci_dev *dev)
{
int i;
u16 ctrl;
struct pci_sriov *iov = dev->sriov;
pci_read_config_word(dev, iov->pos + PCI_SRIOV_CTRL, &ctrl);
if (ctrl & PCI_SRIOV_CTRL_VFE)
return;
for (i = PCI_IOV_RESOURCES; i <= PCI_IOV_RESOURCE_END; i++)
pci_update_resource(dev, i);
pci_write_config_dword(dev, iov->pos + PCI_SRIOV_SYS_PGSIZE, iov->pgsz);
pci_iov_set_numvfs(dev, iov->num_VFs);
pci_write_config_word(dev, iov->pos + PCI_SRIOV_CTRL, iov->ctrl);
if (iov->ctrl & PCI_SRIOV_CTRL_VFE)
msleep(100);
}
/**
* pci_iov_init - initialize the IOV capability
* @dev: the PCI device
*
* Returns 0 on success, or negative on failure.
*/
int pci_iov_init(struct pci_dev *dev)
{
int pos;
if (!pci_is_pcie(dev))
return -ENODEV;
pos = pci_find_ext_capability(dev, PCI_EXT_CAP_ID_SRIOV);
if (pos)
return sriov_init(dev, pos);
return -ENODEV;
}
/**
* pci_iov_release - release resources used by the IOV capability
* @dev: the PCI device
*/
void pci_iov_release(struct pci_dev *dev)
{
if (dev->is_physfn)
sriov_release(dev);
}
/**
* pci_iov_resource_bar - get position of the SR-IOV BAR
* @dev: the PCI device
* @resno: the resource number
*
* Returns position of the BAR encapsulated in the SR-IOV capability.
*/
int pci_iov_resource_bar(struct pci_dev *dev, int resno)
{
if (resno < PCI_IOV_RESOURCES || resno > PCI_IOV_RESOURCE_END)
return 0;
BUG_ON(!dev->is_physfn);
return dev->sriov->pos + PCI_SRIOV_BAR +
4 * (resno - PCI_IOV_RESOURCES);
}
resource_size_t __weak pcibios_iov_resource_alignment(struct pci_dev *dev,
int resno)
{
return pci_iov_resource_size(dev, resno);
}
/**
* pci_sriov_resource_alignment - get resource alignment for VF BAR
* @dev: the PCI device
* @resno: the resource number
*
* Returns the alignment of the VF BAR found in the SR-IOV capability.
* This is not the same as the resource size which is defined as
* the VF BAR size multiplied by the number of VFs. The alignment
* is just the VF BAR size.
*/
resource_size_t pci_sriov_resource_alignment(struct pci_dev *dev, int resno)
{
return pcibios_iov_resource_alignment(dev, resno);
}
/**
* pci_restore_iov_state - restore the state of the IOV capability
* @dev: the PCI device
*/
void pci_restore_iov_state(struct pci_dev *dev)
{
if (dev->is_physfn)
sriov_restore_state(dev);
}
/**
* pci_iov_bus_range - find bus range used by Virtual Function
* @bus: the PCI bus
*
* Returns max number of buses (exclude current one) used by Virtual
* Functions.
*/
int pci_iov_bus_range(struct pci_bus *bus)
{
int max = 0;
struct pci_dev *dev;
list_for_each_entry(dev, &bus->devices, bus_list) {
if (!dev->is_physfn)
continue;
if (dev->sriov->max_VF_buses > max)
max = dev->sriov->max_VF_buses;
}
return max ? max - bus->number : 0;
}
/**
* pci_enable_sriov - enable the SR-IOV capability
* @dev: the PCI device
* @nr_virtfn: number of virtual functions to enable
*
* Returns 0 on success, or negative on failure.
*/
int pci_enable_sriov(struct pci_dev *dev, int nr_virtfn)
{
might_sleep();
if (!dev->is_physfn)
return -ENOSYS;
return sriov_enable(dev, nr_virtfn);
}
EXPORT_SYMBOL_GPL(pci_enable_sriov);
/**
* pci_disable_sriov - disable the SR-IOV capability
* @dev: the PCI device
*/
void pci_disable_sriov(struct pci_dev *dev)
{
might_sleep();
if (!dev->is_physfn)
return;
sriov_disable(dev);
}
EXPORT_SYMBOL_GPL(pci_disable_sriov);
/**
* pci_num_vf - return number of VFs associated with a PF device_release_driver
* @dev: the PCI device
*
* Returns number of VFs, or 0 if SR-IOV is not enabled.
*/
int pci_num_vf(struct pci_dev *dev)
{
if (!dev->is_physfn)
return 0;
return dev->sriov->num_VFs;
}
EXPORT_SYMBOL_GPL(pci_num_vf);
/**
* pci_vfs_assigned - returns number of VFs are assigned to a guest
* @dev: the PCI device
*
* Returns number of VFs belonging to this device that are assigned to a guest.
* If device is not a physical function returns 0.
*/
int pci_vfs_assigned(struct pci_dev *dev)
{
struct pci_dev *vfdev;
unsigned int vfs_assigned = 0;
unsigned short dev_id;
/* only search if we are a PF */
if (!dev->is_physfn)
return 0;
/*
* determine the device ID for the VFs, the vendor ID will be the
* same as the PF so there is no need to check for that one
*/
pci_read_config_word(dev, dev->sriov->pos + PCI_SRIOV_VF_DID, &dev_id);
/* loop through all the VFs to see if we own any that are assigned */
vfdev = pci_get_device(dev->vendor, dev_id, NULL);
while (vfdev) {
/*
* It is considered assigned if it is a virtual function with
* our dev as the physical function and the assigned bit is set
*/
if (vfdev->is_virtfn && (vfdev->physfn == dev) &&
pci_is_dev_assigned(vfdev))
vfs_assigned++;
vfdev = pci_get_device(dev->vendor, dev_id, vfdev);
}
return vfs_assigned;
}
EXPORT_SYMBOL_GPL(pci_vfs_assigned);
/**
* pci_sriov_set_totalvfs -- reduce the TotalVFs available
* @dev: the PCI PF device
* @numvfs: number that should be used for TotalVFs supported
*
* Should be called from PF driver's probe routine with
* device's mutex held.
*
* Returns 0 if PF is an SRIOV-capable device and
* value of numvfs valid. If not a PF return -ENOSYS;
* if numvfs is invalid return -EINVAL;
* if VFs already enabled, return -EBUSY.
*/
int pci_sriov_set_totalvfs(struct pci_dev *dev, u16 numvfs)
{
if (!dev->is_physfn)
return -ENOSYS;
if (numvfs > dev->sriov->total_VFs)
return -EINVAL;
/* Shouldn't change if VFs already enabled */
if (dev->sriov->ctrl & PCI_SRIOV_CTRL_VFE)
return -EBUSY;
else
dev->sriov->driver_max_VFs = numvfs;
return 0;
}
EXPORT_SYMBOL_GPL(pci_sriov_set_totalvfs);
/**
* pci_sriov_get_totalvfs -- get total VFs supported on this device
* @dev: the PCI PF device
*
* For a PCIe device with SRIOV support, return the PCIe
* SRIOV capability value of TotalVFs or the value of driver_max_VFs
* if the driver reduced it. Otherwise 0.
*/
int pci_sriov_get_totalvfs(struct pci_dev *dev)
{
if (!dev->is_physfn)
return 0;
if (dev->sriov->driver_max_VFs)
return dev->sriov->driver_max_VFs;
return dev->sriov->total_VFs;
}
EXPORT_SYMBOL_GPL(pci_sriov_get_totalvfs);
|
84424.c | /*
FreeRTOS V9.0.0rc2 - Copyright (C) 2016 Real Time Engineers Ltd.
All rights reserved
VISIT http://www.FreeRTOS.org TO ENSURE YOU ARE USING THE LATEST VERSION.
This file is part of the FreeRTOS distribution.
FreeRTOS is free software; you can redistribute it and/or modify it under
the terms of the GNU General Public License (version 2) as published by the
Free Software Foundation >>>> AND MODIFIED BY <<<< the FreeRTOS exception.
***************************************************************************
>>! NOTE: The modification to the GPL is included to allow you to !<<
>>! distribute a combined work that includes FreeRTOS without being !<<
>>! obliged to provide the source code for proprietary components !<<
>>! outside of the FreeRTOS kernel. !<<
***************************************************************************
FreeRTOS 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. Full license text is available on the following
link: http://www.freertos.org/a00114.html
***************************************************************************
* *
* FreeRTOS provides completely free yet professionally developed, *
* robust, strictly quality controlled, supported, and cross *
* platform software that is more than just the market leader, it *
* is the industry's de facto standard. *
* *
* Help yourself get started quickly while simultaneously helping *
* to support the FreeRTOS project by purchasing a FreeRTOS *
* tutorial book, reference manual, or both: *
* http://www.FreeRTOS.org/Documentation *
* *
***************************************************************************
http://www.FreeRTOS.org/FAQHelp.html - Having a problem? Start by reading
the FAQ page "My application does not run, what could be wrong?". Have you
defined configASSERT()?
http://www.FreeRTOS.org/support - In return for receiving this top quality
embedded software for free we request you assist our global community by
participating in the support forum.
http://www.FreeRTOS.org/training - Investing in training allows your team to
be as productive as possible as early as possible. Now you can receive
FreeRTOS training directly from Richard Barry, CEO of Real Time Engineers
Ltd, and the world's leading authority on the world's leading RTOS.
http://www.FreeRTOS.org/plus - A selection of FreeRTOS ecosystem products,
including FreeRTOS+Trace - an indispensable productivity tool, a DOS
compatible FAT file system, and our tiny thread aware UDP/IP stack.
http://www.FreeRTOS.org/labs - Where new FreeRTOS products go to incubate.
Come and try FreeRTOS+TCP, our new open source TCP/IP stack for FreeRTOS.
http://www.OpenRTOS.com - Real Time Engineers ltd. license FreeRTOS to High
Integrity Systems ltd. to sell under the OpenRTOS brand. Low cost OpenRTOS
licenses offer ticketed support, indemnification and commercial middleware.
http://www.SafeRTOS.com - High Integrity Systems also provide a safety
engineered and independently SIL3 certified version for use in safety and
mission critical applications that require provable dependability.
1 tab == 4 spaces!
*/
/* FreeRTOS includes. */
#include "FreeRTOS.h"
#include "task.h"
/* Xilinx includes. */
#include "platform.h"
#include "xttcps.h"
#include "xscugic.h"
/* Timer used to generate the tick interrupt. */
static XTtcPs xRTOSTickTimerInstance;
/*-----------------------------------------------------------*/
void vConfigureTickInterrupt( void )
{
BaseType_t xStatus;
XTtcPs_Config *pxTimerConfiguration;
uint16_t usInterval;
uint8_t ucPrescale;
const uint8_t ucLevelSensitive = 1;
extern XScuGic xInterruptController;
pxTimerConfiguration = XTtcPs_LookupConfig( XPAR_XTTCPS_3_DEVICE_ID );
/* Initialise the device. */
xStatus = XTtcPs_CfgInitialize( &xRTOSTickTimerInstance, pxTimerConfiguration, pxTimerConfiguration->BaseAddress );
if( xStatus != XST_SUCCESS )
{
/* Not sure how to do this before XTtcPs_CfgInitialize is called as
*xRTOSTickTimerInstance is set within XTtcPs_CfgInitialize(). */
XTtcPs_Stop( &xRTOSTickTimerInstance );
xStatus = XTtcPs_CfgInitialize( &xRTOSTickTimerInstance, pxTimerConfiguration, pxTimerConfiguration->BaseAddress );
configASSERT( xStatus == XST_SUCCESS );
}
/* Set the options. */
XTtcPs_SetOptions( &xRTOSTickTimerInstance, ( XTTCPS_OPTION_INTERVAL_MODE | XTTCPS_OPTION_WAVE_DISABLE ) );
/* Derive values from the tick rate. */
XTtcPs_CalcIntervalFromFreq( &xRTOSTickTimerInstance, configTICK_RATE_HZ, &( usInterval ), &( ucPrescale ) );
/* Set the interval and prescale. */
XTtcPs_SetInterval( &xRTOSTickTimerInstance, usInterval );
XTtcPs_SetPrescaler( &xRTOSTickTimerInstance, ucPrescale );
/* The priority must be the lowest possible. */
XScuGic_SetPriorityTriggerType( &xInterruptController, XPAR_XTTCPS_3_INTR, portLOWEST_USABLE_INTERRUPT_PRIORITY << portPRIORITY_SHIFT, ucLevelSensitive );
/* Connect to the interrupt controller. */
xStatus = XScuGic_Connect( &xInterruptController, XPAR_XTTCPS_3_INTR, (Xil_ExceptionHandler) FreeRTOS_Tick_Handler, ( void * ) &xRTOSTickTimerInstance );
configASSERT( xStatus == XST_SUCCESS);
/* Enable the interrupt in the GIC. */
XScuGic_Enable( &xInterruptController, XPAR_XTTCPS_3_INTR );
/* Enable the interrupts in the timer. */
XTtcPs_EnableInterrupts( &xRTOSTickTimerInstance, XTTCPS_IXR_INTERVAL_MASK );
/* Start the timer. */
XTtcPs_Start( &xRTOSTickTimerInstance );
}
/*-----------------------------------------------------------*/
void vClearTickInterrupt( void )
{
volatile uint32_t ulInterruptStatus;
/* Read the interrupt status, then write it back to clear the interrupt. */
ulInterruptStatus = XTtcPs_GetInterruptStatus( &xRTOSTickTimerInstance );
XTtcPs_ClearInterruptStatus( &xRTOSTickTimerInstance, ulInterruptStatus );
__asm volatile( "DSB SY" );
__asm volatile( "ISB SY" );
}
/*-----------------------------------------------------------*/
void vApplicationIRQHandler( uint32_t ulICCIAR )
{
extern const XScuGic_Config XScuGic_ConfigTable[];
static const XScuGic_VectorTableEntry *pxVectorTable = XScuGic_ConfigTable[ XPAR_SCUGIC_SINGLE_DEVICE_ID ].HandlerTable;
uint32_t ulInterruptID;
const XScuGic_VectorTableEntry *pxVectorEntry;
/* Interrupts cannot be re-enabled until the source of the interrupt is
cleared. The ID of the interrupt is obtained by bitwise ANDing the ICCIAR
value with 0x3FF. */
ulInterruptID = ulICCIAR & 0x3FFUL;
if( ulInterruptID < XSCUGIC_MAX_NUM_INTR_INPUTS )
{
/* Call the function installed in the array of installed handler
functions. */
pxVectorEntry = &( pxVectorTable[ ulInterruptID ] );
configASSERT( pxVectorEntry );
pxVectorEntry->Handler( pxVectorEntry->CallBackRef );
}
}
|
794140.c | /*
* Generated by asn1c-0.9.29 (http://lionet.info/asn1c)
* From ASN.1 module "NGAP-IEs"
* found in "asn.1/Information Element Definitions.asn1"
* `asn1c -pdu=all -fcompound-names -fno-include-deps -findirect-choice -gen-PER -D src`
*/
#include "Ngap_CPTransportLayerInformation.h"
#include "Ngap_ProtocolIE-SingleContainer.h"
static asn_oer_constraints_t asn_OER_type_Ngap_CPTransportLayerInformation_constr_1 CC_NOTUSED = {
{ 0, 0 },
-1};
asn_per_constraints_t asn_PER_type_Ngap_CPTransportLayerInformation_constr_1 CC_NOTUSED = {
{ APC_CONSTRAINED, 1, 1, 0, 1 } /* (0..1) */,
{ APC_UNCONSTRAINED, -1, -1, 0, 0 },
0, 0 /* No PER value map */
};
asn_TYPE_member_t asn_MBR_Ngap_CPTransportLayerInformation_1[] = {
{ ATF_NOFLAGS, 0, offsetof(struct Ngap_CPTransportLayerInformation, choice.endpointIPAddress),
(ASN_TAG_CLASS_CONTEXT | (0 << 2)),
-1, /* IMPLICIT tag at current level */
&asn_DEF_Ngap_TransportLayerAddress,
0,
{ 0, 0, 0 },
0, 0, /* No default value */
"endpointIPAddress"
},
{ ATF_POINTER, 0, offsetof(struct Ngap_CPTransportLayerInformation, choice.choice_Extensions),
(ASN_TAG_CLASS_CONTEXT | (1 << 2)),
-1, /* IMPLICIT tag at current level */
&asn_DEF_Ngap_ProtocolIE_SingleContainer_127P5,
0,
{ 0, 0, 0 },
0, 0, /* No default value */
"choice-Extensions"
},
};
static const asn_TYPE_tag2member_t asn_MAP_Ngap_CPTransportLayerInformation_tag2el_1[] = {
{ (ASN_TAG_CLASS_CONTEXT | (0 << 2)), 0, 0, 0 }, /* endpointIPAddress */
{ (ASN_TAG_CLASS_CONTEXT | (1 << 2)), 1, 0, 0 } /* choice-Extensions */
};
asn_CHOICE_specifics_t asn_SPC_Ngap_CPTransportLayerInformation_specs_1 = {
sizeof(struct Ngap_CPTransportLayerInformation),
offsetof(struct Ngap_CPTransportLayerInformation, _asn_ctx),
offsetof(struct Ngap_CPTransportLayerInformation, present),
sizeof(((struct Ngap_CPTransportLayerInformation *)0)->present),
asn_MAP_Ngap_CPTransportLayerInformation_tag2el_1,
2, /* Count of tags in the map */
0, 0,
-1 /* Extensions start */
};
asn_TYPE_descriptor_t asn_DEF_Ngap_CPTransportLayerInformation = {
"CPTransportLayerInformation",
"CPTransportLayerInformation",
&asn_OP_CHOICE,
0, /* No effective tags (pointer) */
0, /* No effective tags (count) */
0, /* No tags (pointer) */
0, /* No tags (count) */
{ &asn_OER_type_Ngap_CPTransportLayerInformation_constr_1, &asn_PER_type_Ngap_CPTransportLayerInformation_constr_1, CHOICE_constraint },
asn_MBR_Ngap_CPTransportLayerInformation_1,
2, /* Elements count */
&asn_SPC_Ngap_CPTransportLayerInformation_specs_1 /* Additional specs */
};
|
645279.c | #include <stdio.h>
/* copy input to output; 1st version */
int main()
{
/* NOTE: we need 'c' as an int because getchar() can return EOF, which
* is outside the char range, so that it cannot be confused with valid
* data. See also man getchar */
int c;
//c = getchar();
//while (c != EOF) {
while ((c = getchar()) != EOF) {
putchar(c);
//c = getchar();
}
/* NOTE: c = getchar() is an expression, and has the value of the left
* hand side after assignemnt. This value can be used in a test, like
* for the while loop test
*
* The parantheses are mandtory as != has a higher precedence than = */
/* The exact value of EOF must not be relied upon, but you can print it */
//printf("EOF: %d\n", EOF);
}
|
382824.c | /* Copyright (C) 2004, 2006, 2008 Free Software Foundation, Inc.
This file is part of the GNU C Library.
Contributed by Ulrich Drepper <[email protected]>, 2004.
The GNU C Library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
The GNU C Library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with the GNU C Library; if not, see
<http://www.gnu.org/licenses/>. */
#include <errno.h>
#include <netdb.h>
#include <resolv.h>
#include <stdlib.h>
#include <arpa/nameser.h>
#include <nsswitch.h>
#if PACKETSZ > 65536
# define MAXPACKET PACKETSZ
#else
# define MAXPACKET 65536
#endif
/* We need this time later. */
typedef union querybuf
{
HEADER hdr;
unsigned char buf[MAXPACKET];
} querybuf;
static const short int qtypes[] = { ns_t_a, ns_t_aaaa };
#define nqtypes (sizeof (qtypes) / sizeof (qtypes[0]))
enum nss_status
_nss_dns_getcanonname_r (const char *name, char *buffer, size_t buflen,
char **result,int *errnop, int *h_errnop)
{
/* Just an alibi buffer, res_nquery will allocate a real buffer for
us. */
unsigned char buf[20];
union
{
querybuf *buf;
unsigned char *ptr;
} ansp = { .ptr = buf };
enum nss_status status = NSS_STATUS_UNAVAIL;
for (int i = 0; i < nqtypes; ++i)
{
int r = __libc_res_nquery (&_res, name, ns_c_in, qtypes[i],
buf, sizeof (buf), &ansp.ptr, NULL, NULL,
NULL);
if (r > 0)
{
/* We need to decode the response. Just one question record.
And if we got no answers we bail out, too. */
if (ansp.buf->hdr.qdcount != htons (1))
continue;
/* Number of answers. */
unsigned int ancount = ntohs (ansp.buf->hdr.ancount);
/* Beginning and end of the buffer with query, answer, and the
rest. */
unsigned char *ptr = &ansp.buf->buf[sizeof (HEADER)];
unsigned char *endptr = ansp.ptr + r;
/* Skip over the query. This is the name, type, and class. */
int s = __dn_skipname (ptr, endptr);
if (s < 0)
{
unavail:
status = NSS_STATUS_UNAVAIL;
break;
}
/* Skip over the name and the two 16-bit values containing type
and class. */
ptr += s + 2 * sizeof (uint16_t);
while (ancount-- > 0)
{
/* Now the reply. First again the name from the query,
then type, class, TTL, and the length of the RDATA.
We remember the name start. */
unsigned char *namestart = ptr;
s = __dn_skipname (ptr, endptr);
if (s < 0)
goto unavail;
ptr += s;
/* Check whether type and class match. */
uint_fast16_t type;
NS_GET16 (type, ptr);
if (type == qtypes[i])
{
/* We found the record. */
s = __dn_expand (ansp.buf->buf, endptr, namestart,
buffer, buflen);
if (s < 0)
{
if (errno != EMSGSIZE)
goto unavail;
/* The buffer is too small. */
*errnop = ERANGE;
status = NSS_STATUS_TRYAGAIN;
h_errno = NETDB_INTERNAL;
}
else
{
/* Success. */
*result = buffer;
status = NSS_STATUS_SUCCESS;
}
goto out;
}
if (type != ns_t_cname)
goto unavail;
if (__ns_get16 (ptr) != ns_c_in)
goto unavail;
/* Also skip over the TTL. */
ptr += sizeof (uint16_t) + sizeof (uint32_t);
/* Skip over the data length and data. */
ptr += sizeof (uint16_t) + __ns_get16 (ptr);
}
}
}
out:
*h_errnop = h_errno;
if (ansp.ptr != buf)
free (ansp.ptr);
return status;
}
|
990453.c | /*
* Copyright (c) 2012 The WebRTC 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.
*/
/*
* This file contains implementations of the iLBC specific functions
* WebRtcSpl_ReverseOrderMultArrayElements()
* WebRtcSpl_ElementwiseVectorMult()
* WebRtcSpl_AddVectorsAndShift()
* WebRtcSpl_AddAffineVectorToVector()
* WebRtcSpl_AffineTransformVector()
*
*/
#include "signal_processing_library.h"
void WebRtcSpl_ReverseOrderMultArrayElements(WebRtc_Word16 *out, G_CONST WebRtc_Word16 *in,
G_CONST WebRtc_Word16 *win,
WebRtc_Word16 vector_length,
WebRtc_Word16 right_shifts)
{
int i;
WebRtc_Word16 *outptr = out;
G_CONST WebRtc_Word16 *inptr = in;
G_CONST WebRtc_Word16 *winptr = win;
for (i = 0; i < vector_length; i++)
{
(*outptr++) = (WebRtc_Word16)WEBRTC_SPL_MUL_16_16_RSFT(*inptr++,
*winptr--, right_shifts);
}
}
void WebRtcSpl_ElementwiseVectorMult(WebRtc_Word16 *out, G_CONST WebRtc_Word16 *in,
G_CONST WebRtc_Word16 *win, WebRtc_Word16 vector_length,
WebRtc_Word16 right_shifts)
{
int i;
WebRtc_Word16 *outptr = out;
G_CONST WebRtc_Word16 *inptr = in;
G_CONST WebRtc_Word16 *winptr = win;
for (i = 0; i < vector_length; i++)
{
(*outptr++) = (WebRtc_Word16)WEBRTC_SPL_MUL_16_16_RSFT(*inptr++,
*winptr++, right_shifts);
}
}
void WebRtcSpl_AddVectorsAndShift(WebRtc_Word16 *out, G_CONST WebRtc_Word16 *in1,
G_CONST WebRtc_Word16 *in2, WebRtc_Word16 vector_length,
WebRtc_Word16 right_shifts)
{
int i;
WebRtc_Word16 *outptr = out;
G_CONST WebRtc_Word16 *in1ptr = in1;
G_CONST WebRtc_Word16 *in2ptr = in2;
for (i = vector_length; i > 0; i--)
{
(*outptr++) = (WebRtc_Word16)(((*in1ptr++) + (*in2ptr++)) >> right_shifts);
}
}
void WebRtcSpl_AddAffineVectorToVector(WebRtc_Word16 *out, WebRtc_Word16 *in,
WebRtc_Word16 gain, WebRtc_Word32 add_constant,
WebRtc_Word16 right_shifts, int vector_length)
{
WebRtc_Word16 *inPtr;
WebRtc_Word16 *outPtr;
int i;
inPtr = in;
outPtr = out;
for (i = 0; i < vector_length; i++)
{
(*outPtr++) += (WebRtc_Word16)((WEBRTC_SPL_MUL_16_16((*inPtr++), gain)
+ (WebRtc_Word32)add_constant) >> right_shifts);
}
}
void WebRtcSpl_AffineTransformVector(WebRtc_Word16 *out, WebRtc_Word16 *in,
WebRtc_Word16 gain, WebRtc_Word32 add_constant,
WebRtc_Word16 right_shifts, int vector_length)
{
WebRtc_Word16 *inPtr;
WebRtc_Word16 *outPtr;
int i;
inPtr = in;
outPtr = out;
for (i = 0; i < vector_length; i++)
{
(*outPtr++) = (WebRtc_Word16)((WEBRTC_SPL_MUL_16_16((*inPtr++), gain)
+ (WebRtc_Word32)add_constant) >> right_shifts);
}
}
|
224013.c | /* strncmp -- compare two strings, stop after n bytes.
This function is in the public domain. */
/*
@deftypefn Supplemental int strncmp (const char *@var{s1}, const char *@var{s2}, size_t @var{n})
Compares the first @var{n} bytes of two strings, returning a value as
@code{strcmp}.
@end deftypefn
*/
#include <ansidecl.h>
#include <stddef.h>
int
strncmp(const char *s1, const char *s2, register size_t n)
{
register unsigned char u1, u2;
while (n-- > 0)
{
u1 = (unsigned char) *s1++;
u2 = (unsigned char) *s2++;
if (u1 != u2)
return u1 - u2;
if (u1 == '\0')
return 0;
}
return 0;
}
|
203755.c | /* $OpenBSD: ssh-keyscan.c,v 1.106 2016/05/02 10:26:04 djm Exp $ */
/*
* Copyright 1995, 1996 by David Mazieres <[email protected]>.
*
* Modification and redistribution in source and binary forms is
* permitted provided that due credit is given to the author and the
* OpenBSD project by leaving this copyright notice intact.
*/
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/queue.h>
#include <sys/time.h>
#include <sys/resource.h>
#include <openssl/bn.h>
#include <errno.h>
#include <netdb.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <string.h>
#include <unistd.h>
#include "xmalloc.h"
#include "ssh.h"
#include "ssh1.h"
#include "sshbuf.h"
#include "sshkey.h"
#include "cipher.h"
#include "kex.h"
#include "compat.h"
#include "myproposal.h"
#include "packet.h"
#include "dispatch.h"
#include "log.h"
#include "atomicio.h"
#include "misc.h"
#include "hostfile.h"
#include "ssherr.h"
#include "ssh_api.h"
/* Flag indicating whether IPv4 or IPv6. This can be set on the command line.
Default value is AF_UNSPEC means both IPv4 and IPv6. */
int IPv4or6 = AF_UNSPEC;
int ssh_port = SSH_DEFAULT_PORT;
#define KT_RSA1 1
#define KT_DSA 2
#define KT_RSA 4
#define KT_ECDSA 8
#define KT_ED25519 16
int get_cert = 0;
int get_keytypes = KT_RSA|KT_ECDSA|KT_ED25519;
int hash_hosts = 0; /* Hash hostname on output */
#define MAXMAXFD 256
/* The number of seconds after which to give up on a TCP connection */
int timeout = 5;
int maxfd;
#define MAXCON (maxfd - 10)
extern char *__progname;
fd_set *read_wait;
size_t read_wait_nfdset;
int ncon;
/*
* Keep a connection structure for each file descriptor. The state
* associated with file descriptor n is held in fdcon[n].
*/
typedef struct Connection {
u_char c_status; /* State of connection on this file desc. */
#define CS_UNUSED 0 /* File descriptor unused */
#define CS_CON 1 /* Waiting to connect/read greeting */
#define CS_SIZE 2 /* Waiting to read initial packet size */
#define CS_KEYS 3 /* Waiting to read public key packet */
int c_fd; /* Quick lookup: c->c_fd == c - fdcon */
int c_plen; /* Packet length field for ssh packet */
int c_len; /* Total bytes which must be read. */
int c_off; /* Length of data read so far. */
int c_keytype; /* Only one of KT_RSA1, KT_DSA, or KT_RSA */
sig_atomic_t c_done; /* SSH2 done */
char *c_namebase; /* Address to free for c_name and c_namelist */
char *c_name; /* Hostname of connection for errors */
char *c_namelist; /* Pointer to other possible addresses */
char *c_output_name; /* Hostname of connection for output */
char *c_data; /* Data read from this fd */
struct ssh *c_ssh; /* SSH-connection */
struct timeval c_tv; /* Time at which connection gets aborted */
TAILQ_ENTRY(Connection) c_link; /* List of connections in timeout order. */
} con;
TAILQ_HEAD(conlist, Connection) tq; /* Timeout Queue */
con *fdcon;
static void keyprint(con *c, struct sshkey *key);
static int
fdlim_get(int hard)
{
struct rlimit rlfd;
if (getrlimit(RLIMIT_NOFILE, &rlfd) < 0)
return (-1);
if ((hard ? rlfd.rlim_max : rlfd.rlim_cur) == RLIM_INFINITY)
return sysconf(_SC_OPEN_MAX);
else
return hard ? rlfd.rlim_max : rlfd.rlim_cur;
}
static int
fdlim_set(int lim)
{
struct rlimit rlfd;
if (lim <= 0)
return (-1);
if (getrlimit(RLIMIT_NOFILE, &rlfd) < 0)
return (-1);
rlfd.rlim_cur = lim;
if (setrlimit(RLIMIT_NOFILE, &rlfd) < 0)
return (-1);
return (0);
}
/*
* This is an strsep function that returns a null field for adjacent
* separators. This is the same as the 4.4BSD strsep, but different from the
* one in the GNU libc.
*/
static char *
xstrsep(char **str, const char *delim)
{
char *s, *e;
if (!**str)
return (NULL);
s = *str;
e = s + strcspn(s, delim);
if (*e != '\0')
*e++ = '\0';
*str = e;
return (s);
}
/*
* Get the next non-null token (like GNU strsep). Strsep() will return a
* null token for two adjacent separators, so we may have to loop.
*/
static char *
strnnsep(char **stringp, char *delim)
{
char *tok;
do {
tok = xstrsep(stringp, delim);
} while (tok && *tok == '\0');
return (tok);
}
#ifdef WITH_SSH1
static struct sshkey *
keygrab_ssh1(con *c)
{
static struct sshkey *rsa;
static struct sshbuf *msg;
int r;
u_char type;
if (rsa == NULL) {
if ((rsa = sshkey_new(KEY_RSA1)) == NULL) {
error("%s: sshkey_new failed", __func__);
return NULL;
}
if ((msg = sshbuf_new()) == NULL)
fatal("%s: sshbuf_new failed", __func__);
}
if ((r = sshbuf_put(msg, c->c_data, c->c_plen)) != 0 ||
(r = sshbuf_consume(msg, 8 - (c->c_plen & 7))) != 0 || /* padding */
(r = sshbuf_get_u8(msg, &type)) != 0)
goto buf_err;
if (type != (int) SSH_SMSG_PUBLIC_KEY) {
error("%s: invalid packet type", c->c_name);
sshbuf_reset(msg);
return NULL;
}
if ((r = sshbuf_consume(msg, 8)) != 0 || /* cookie */
/* server key */
(r = sshbuf_get_u32(msg, NULL)) != 0 ||
(r = sshbuf_get_bignum1(msg, NULL)) != 0 ||
(r = sshbuf_get_bignum1(msg, NULL)) != 0 ||
/* host key */
(r = sshbuf_get_u32(msg, NULL)) != 0 ||
(r = sshbuf_get_bignum1(msg, rsa->rsa->e)) != 0 ||
(r = sshbuf_get_bignum1(msg, rsa->rsa->n)) != 0) {
buf_err:
error("%s: buffer error: %s", __func__, ssh_err(r));
sshbuf_reset(msg);
return NULL;
}
sshbuf_reset(msg);
return (rsa);
}
#endif
static int
key_print_wrapper(struct sshkey *hostkey, struct ssh *ssh)
{
con *c;
if ((c = ssh_get_app_data(ssh)) != NULL)
keyprint(c, hostkey);
/* always abort key exchange */
return -1;
}
static int
ssh2_capable(int remote_major, int remote_minor)
{
switch (remote_major) {
case 1:
if (remote_minor == 99)
return 1;
break;
case 2:
return 1;
default:
break;
}
return 0;
}
static void
keygrab_ssh2(con *c)
{
char *myproposal[PROPOSAL_MAX] = { KEX_CLIENT };
int r;
enable_compat20();
switch (c->c_keytype) {
case KT_DSA:
myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS] = get_cert ?
"[email protected]" : "ssh-dss";
break;
case KT_RSA:
myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS] = get_cert ?
"[email protected]" : "ssh-rsa";
break;
case KT_ED25519:
myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS] = get_cert ?
"[email protected]" : "ssh-ed25519";
break;
case KT_ECDSA:
myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS] = get_cert ?
"[email protected],"
"[email protected],"
"[email protected]" :
"ecdsa-sha2-nistp256,"
"ecdsa-sha2-nistp384,"
"ecdsa-sha2-nistp521";
break;
default:
fatal("unknown key type %d", c->c_keytype);
break;
}
if ((r = kex_setup(c->c_ssh, myproposal)) != 0) {
free(c->c_ssh);
fprintf(stderr, "kex_setup: %s\n", ssh_err(r));
exit(1);
}
#ifdef WITH_OPENSSL
c->c_ssh->kex->kex[KEX_DH_GRP1_SHA1] = kexdh_client;
c->c_ssh->kex->kex[KEX_DH_GRP14_SHA1] = kexdh_client;
c->c_ssh->kex->kex[KEX_DH_GRP14_SHA256] = kexdh_client;
c->c_ssh->kex->kex[KEX_DH_GRP16_SHA512] = kexdh_client;
c->c_ssh->kex->kex[KEX_DH_GRP18_SHA512] = kexdh_client;
c->c_ssh->kex->kex[KEX_DH_GEX_SHA1] = kexgex_client;
c->c_ssh->kex->kex[KEX_DH_GEX_SHA256] = kexgex_client;
c->c_ssh->kex->kex[KEX_ECDH_SHA2] = kexecdh_client;
#endif
c->c_ssh->kex->kex[KEX_C25519_SHA256] = kexc25519_client;
ssh_set_verify_host_key_callback(c->c_ssh, key_print_wrapper);
/*
* do the key-exchange until an error occurs or until
* the key_print_wrapper() callback sets c_done.
*/
ssh_dispatch_run(c->c_ssh, DISPATCH_BLOCK, &c->c_done, c->c_ssh);
}
static void
keyprint_one(char *host, struct sshkey *key)
{
char *hostport;
if (hash_hosts && (host = host_hash(host, NULL, 0)) == NULL)
fatal("host_hash failed");
hostport = put_host_port(host, ssh_port);
if (!get_cert)
fprintf(stdout, "%s ", hostport);
sshkey_write(key, stdout);
fputs("\n", stdout);
free(hostport);
}
static void
keyprint(con *c, struct sshkey *key)
{
char *hosts = c->c_output_name ? c->c_output_name : c->c_name;
char *host, *ohosts;
if (key == NULL)
return;
if (get_cert || (!hash_hosts && ssh_port == SSH_DEFAULT_PORT)) {
keyprint_one(hosts, key);
return;
}
ohosts = hosts = xstrdup(hosts);
while ((host = strsep(&hosts, ",")) != NULL)
keyprint_one(host, key);
free(ohosts);
}
static int
tcpconnect(char *host)
{
struct addrinfo hints, *ai, *aitop;
char strport[NI_MAXSERV];
int gaierr, s = -1;
snprintf(strport, sizeof strport, "%d", ssh_port);
memset(&hints, 0, sizeof(hints));
hints.ai_family = IPv4or6;
hints.ai_socktype = SOCK_STREAM;
if ((gaierr = getaddrinfo(host, strport, &hints, &aitop)) != 0) {
error("getaddrinfo %s: %s", host, ssh_gai_strerror(gaierr));
return -1;
}
for (ai = aitop; ai; ai = ai->ai_next) {
s = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
if (s < 0) {
error("socket: %s", strerror(errno));
continue;
}
if (set_nonblock(s) == -1)
fatal("%s: set_nonblock(%d)", __func__, s);
if (connect(s, ai->ai_addr, ai->ai_addrlen) < 0 &&
errno != EINPROGRESS)
error("connect (`%s'): %s", host, strerror(errno));
else
break;
close(s);
s = -1;
}
freeaddrinfo(aitop);
return s;
}
static int
conalloc(char *iname, char *oname, int keytype)
{
char *namebase, *name, *namelist;
int s;
namebase = namelist = xstrdup(iname);
do {
name = xstrsep(&namelist, ",");
if (!name) {
free(namebase);
return (-1);
}
} while ((s = tcpconnect(name)) < 0);
if (s >= maxfd)
fatal("conalloc: fdno %d too high", s);
if (fdcon[s].c_status)
fatal("conalloc: attempt to reuse fdno %d", s);
debug3("%s: oname %s kt %d", __func__, oname, keytype);
fdcon[s].c_fd = s;
fdcon[s].c_status = CS_CON;
fdcon[s].c_namebase = namebase;
fdcon[s].c_name = name;
fdcon[s].c_namelist = namelist;
fdcon[s].c_output_name = xstrdup(oname);
fdcon[s].c_data = (char *) &fdcon[s].c_plen;
fdcon[s].c_len = 4;
fdcon[s].c_off = 0;
fdcon[s].c_keytype = keytype;
gettimeofday(&fdcon[s].c_tv, NULL);
fdcon[s].c_tv.tv_sec += timeout;
TAILQ_INSERT_TAIL(&tq, &fdcon[s], c_link);
FD_SET(s, read_wait);
ncon++;
return (s);
}
static void
confree(int s)
{
if (s >= maxfd || fdcon[s].c_status == CS_UNUSED)
fatal("confree: attempt to free bad fdno %d", s);
close(s);
free(fdcon[s].c_namebase);
free(fdcon[s].c_output_name);
if (fdcon[s].c_status == CS_KEYS)
free(fdcon[s].c_data);
fdcon[s].c_status = CS_UNUSED;
fdcon[s].c_keytype = 0;
if (fdcon[s].c_ssh) {
ssh_packet_close(fdcon[s].c_ssh);
free(fdcon[s].c_ssh);
fdcon[s].c_ssh = NULL;
}
TAILQ_REMOVE(&tq, &fdcon[s], c_link);
FD_CLR(s, read_wait);
ncon--;
}
static void
contouch(int s)
{
TAILQ_REMOVE(&tq, &fdcon[s], c_link);
gettimeofday(&fdcon[s].c_tv, NULL);
fdcon[s].c_tv.tv_sec += timeout;
TAILQ_INSERT_TAIL(&tq, &fdcon[s], c_link);
}
static int
conrecycle(int s)
{
con *c = &fdcon[s];
int ret;
ret = conalloc(c->c_namelist, c->c_output_name, c->c_keytype);
confree(s);
return (ret);
}
static void
congreet(int s)
{
int n = 0, remote_major = 0, remote_minor = 0;
char buf[256], *cp;
char remote_version[sizeof buf];
size_t bufsiz;
con *c = &fdcon[s];
for (;;) {
memset(buf, '\0', sizeof(buf));
bufsiz = sizeof(buf);
cp = buf;
while (bufsiz-- &&
(n = atomicio(read, s, cp, 1)) == 1 && *cp != '\n') {
if (*cp == '\r')
*cp = '\n';
cp++;
}
if (n != 1 || strncmp(buf, "SSH-", 4) == 0)
break;
}
if (n == 0) {
switch (errno) {
case EPIPE:
error("%s: Connection closed by remote host", c->c_name);
break;
case ECONNREFUSED:
break;
default:
error("read (%s): %s", c->c_name, strerror(errno));
break;
}
conrecycle(s);
return;
}
if (*cp != '\n' && *cp != '\r') {
error("%s: bad greeting", c->c_name);
confree(s);
return;
}
*cp = '\0';
if ((c->c_ssh = ssh_packet_set_connection(NULL, s, s)) == NULL)
fatal("ssh_packet_set_connection failed");
ssh_packet_set_timeout(c->c_ssh, timeout, 1);
ssh_set_app_data(c->c_ssh, c); /* back link */
if (sscanf(buf, "SSH-%d.%d-%[^\n]\n",
&remote_major, &remote_minor, remote_version) == 3)
c->c_ssh->compat = compat_datafellows(remote_version);
else
c->c_ssh->compat = 0;
if (c->c_keytype != KT_RSA1) {
if (!ssh2_capable(remote_major, remote_minor)) {
debug("%s doesn't support ssh2", c->c_name);
confree(s);
return;
}
} else if (remote_major != 1) {
debug("%s doesn't support ssh1", c->c_name);
confree(s);
return;
}
fprintf(stderr, "# %s:%d %s\n", c->c_name, ssh_port, chop(buf));
n = snprintf(buf, sizeof buf, "SSH-%d.%d-OpenSSH-keyscan\r\n",
c->c_keytype == KT_RSA1? PROTOCOL_MAJOR_1 : PROTOCOL_MAJOR_2,
c->c_keytype == KT_RSA1? PROTOCOL_MINOR_1 : PROTOCOL_MINOR_2);
if (n < 0 || (size_t)n >= sizeof(buf)) {
error("snprintf: buffer too small");
confree(s);
return;
}
if (atomicio(vwrite, s, buf, n) != (size_t)n) {
error("write (%s): %s", c->c_name, strerror(errno));
confree(s);
return;
}
if (c->c_keytype != KT_RSA1) {
keygrab_ssh2(c);
confree(s);
return;
}
c->c_status = CS_SIZE;
contouch(s);
}
static void
conread(int s)
{
con *c = &fdcon[s];
size_t n;
if (c->c_status == CS_CON) {
congreet(s);
return;
}
n = atomicio(read, s, c->c_data + c->c_off, c->c_len - c->c_off);
if (n == 0) {
error("read (%s): %s", c->c_name, strerror(errno));
confree(s);
return;
}
c->c_off += n;
if (c->c_off == c->c_len)
switch (c->c_status) {
case CS_SIZE:
c->c_plen = htonl(c->c_plen);
c->c_len = c->c_plen + 8 - (c->c_plen & 7);
c->c_off = 0;
c->c_data = xmalloc(c->c_len);
c->c_status = CS_KEYS;
break;
#ifdef WITH_SSH1
case CS_KEYS:
keyprint(c, keygrab_ssh1(c));
confree(s);
return;
#endif
default:
fatal("conread: invalid status %d", c->c_status);
break;
}
contouch(s);
}
static void
conloop(void)
{
struct timeval seltime, now;
fd_set *r, *e;
con *c;
int i;
gettimeofday(&now, NULL);
c = TAILQ_FIRST(&tq);
if (c && (c->c_tv.tv_sec > now.tv_sec ||
(c->c_tv.tv_sec == now.tv_sec && c->c_tv.tv_usec > now.tv_usec))) {
seltime = c->c_tv;
seltime.tv_sec -= now.tv_sec;
seltime.tv_usec -= now.tv_usec;
if (seltime.tv_usec < 0) {
seltime.tv_usec += 1000000;
seltime.tv_sec--;
}
} else
timerclear(&seltime);
r = xcalloc(read_wait_nfdset, sizeof(fd_mask));
e = xcalloc(read_wait_nfdset, sizeof(fd_mask));
memcpy(r, read_wait, read_wait_nfdset * sizeof(fd_mask));
memcpy(e, read_wait, read_wait_nfdset * sizeof(fd_mask));
while (select(maxfd, r, NULL, e, &seltime) == -1 &&
(errno == EAGAIN || errno == EINTR))
;
for (i = 0; i < maxfd; i++) {
if (FD_ISSET(i, e)) {
error("%s: exception!", fdcon[i].c_name);
confree(i);
} else if (FD_ISSET(i, r))
conread(i);
}
free(r);
free(e);
c = TAILQ_FIRST(&tq);
while (c && (c->c_tv.tv_sec < now.tv_sec ||
(c->c_tv.tv_sec == now.tv_sec && c->c_tv.tv_usec < now.tv_usec))) {
int s = c->c_fd;
c = TAILQ_NEXT(c, c_link);
conrecycle(s);
}
}
static void
do_host(char *host)
{
char *name = strnnsep(&host, " \t\n");
int j;
if (name == NULL)
return;
for (j = KT_RSA1; j <= KT_ED25519; j *= 2) {
if (get_keytypes & j) {
while (ncon >= MAXCON)
conloop();
conalloc(name, *host ? host : name, j);
}
}
}
void
fatal(const char *fmt,...)
{
va_list args;
va_start(args, fmt);
do_log(SYSLOG_LEVEL_FATAL, fmt, args);
va_end(args);
exit(255);
}
static void
usage(void)
{
fprintf(stderr,
"usage: %s [-46cHv] [-f file] [-p port] [-T timeout] [-t type]\n"
"\t\t [host | addrlist namelist] ...\n",
__progname);
exit(1);
}
int
main(int argc, char **argv)
{
int debug_flag = 0, log_level = SYSLOG_LEVEL_INFO;
int opt, fopt_count = 0, j;
char *tname, *cp, line[NI_MAXHOST];
FILE *fp;
u_long linenum;
extern int optind;
extern char *optarg;
ssh_malloc_init(); /* must be called before any mallocs */
TAILQ_INIT(&tq);
/* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
sanitise_stdfd();
if (argc <= 1)
usage();
while ((opt = getopt(argc, argv, "cHv46p:T:t:f:")) != -1) {
switch (opt) {
case 'H':
hash_hosts = 1;
break;
case 'c':
get_cert = 1;
break;
case 'p':
ssh_port = a2port(optarg);
if (ssh_port <= 0) {
fprintf(stderr, "Bad port '%s'\n", optarg);
exit(1);
}
break;
case 'T':
timeout = convtime(optarg);
if (timeout == -1 || timeout == 0) {
fprintf(stderr, "Bad timeout '%s'\n", optarg);
usage();
}
break;
case 'v':
if (!debug_flag) {
debug_flag = 1;
log_level = SYSLOG_LEVEL_DEBUG1;
}
else if (log_level < SYSLOG_LEVEL_DEBUG3)
log_level++;
else
fatal("Too high debugging level.");
break;
case 'f':
if (strcmp(optarg, "-") == 0)
optarg = NULL;
argv[fopt_count++] = optarg;
break;
case 't':
get_keytypes = 0;
tname = strtok(optarg, ",");
while (tname) {
int type = sshkey_type_from_name(tname);
switch (type) {
case KEY_RSA1:
get_keytypes |= KT_RSA1;
break;
case KEY_DSA:
get_keytypes |= KT_DSA;
break;
case KEY_ECDSA:
get_keytypes |= KT_ECDSA;
break;
case KEY_RSA:
get_keytypes |= KT_RSA;
break;
case KEY_ED25519:
get_keytypes |= KT_ED25519;
break;
case KEY_UNSPEC:
fatal("unknown key type %s", tname);
}
tname = strtok(NULL, ",");
}
break;
case '4':
IPv4or6 = AF_INET;
break;
case '6':
IPv4or6 = AF_INET6;
break;
case '?':
default:
usage();
}
}
if (optind == argc && !fopt_count)
usage();
log_init("ssh-keyscan", log_level, SYSLOG_FACILITY_USER, 1);
maxfd = fdlim_get(1);
if (maxfd < 0)
fatal("%s: fdlim_get: bad value", __progname);
if (maxfd > MAXMAXFD)
maxfd = MAXMAXFD;
if (MAXCON <= 0)
fatal("%s: not enough file descriptors", __progname);
if (maxfd > fdlim_get(0))
fdlim_set(maxfd);
fdcon = xcalloc(maxfd, sizeof(con));
read_wait_nfdset = howmany(maxfd, NFDBITS);
read_wait = xcalloc(read_wait_nfdset, sizeof(fd_mask));
for (j = 0; j < fopt_count; j++) {
if (argv[j] == NULL)
fp = stdin;
else if ((fp = fopen(argv[j], "r")) == NULL)
fatal("%s: %s: %s", __progname, argv[j],
strerror(errno));
linenum = 0;
while (read_keyfile_line(fp,
argv[j] == NULL ? "(stdin)" : argv[j], line, sizeof(line),
&linenum) != -1) {
/* Chomp off trailing whitespace and comments */
if ((cp = strchr(line, '#')) == NULL)
cp = line + strlen(line) - 1;
while (cp >= line) {
if (*cp == ' ' || *cp == '\t' ||
*cp == '\n' || *cp == '#')
*cp-- = '\0';
else
break;
}
/* Skip empty lines */
if (*line == '\0')
continue;
do_host(line);
}
if (ferror(fp))
fatal("%s: %s: %s", __progname, argv[j],
strerror(errno));
fclose(fp);
}
while (optind < argc)
do_host(argv[optind++]);
while (ncon > 0)
conloop();
return (0);
}
|
899426.c | /*
* Author: Noel Eck <[email protected]>
* Copyright (c) 2015 Intel Corporation.
*
* 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 <string.h>
#include <stdlib.h>
#include "gsr.h"
gsr_context gsr_init(int16_t pin)
{
// make sure MRAA is initialized
int mraa_rv;
if ((mraa_rv = mraa_init()) != MRAA_SUCCESS)
{
printf("%s: mraa_init() failed (%d).\n", __FUNCTION__, mraa_rv);
return NULL;
}
gsr_context dev = (gsr_context) malloc(sizeof(struct _gsr_context));
if (dev == NULL)
return NULL;
/* Init aio pin */
dev->aio = mraa_aio_init(pin);
if (dev->aio == NULL) {
free(dev);
return NULL;
}
/* Set the ADC ref, scale, and offset defaults */
dev->m_aRef = 5.0;
dev->m_scale = 1.0;
dev->m_offset = 0.0;
return dev;
}
void gsr_close(gsr_context dev)
{
mraa_aio_close(dev->aio);
free(dev);
}
upm_result_t gsr_set_aref(const gsr_context dev, float aref)
{
dev->m_aRef = aref;
return UPM_SUCCESS;
}
upm_result_t gsr_set_scale(const gsr_context dev, float scale)
{
dev->m_scale = scale;
return UPM_SUCCESS;
}
upm_result_t gsr_set_offset(const gsr_context dev, float offset)
{
dev->m_offset = offset;
return UPM_SUCCESS;
}
float gsr_get_aref(const gsr_context dev)
{
return dev->m_aRef;
}
float gsr_get_scale(const gsr_context dev)
{
return dev->m_scale;
}
float gsr_get_offset(const gsr_context dev)
{
return dev->m_offset;
}
upm_result_t gsr_get_normalized(const gsr_context dev, float *value)
{
*value = mraa_aio_read_float(dev->aio);
if (*value < 0)
return UPM_ERROR_OPERATION_FAILED;
return UPM_SUCCESS;
}
upm_result_t gsr_get_raw_volts(const gsr_context dev, float *value)
{
*value = mraa_aio_read_float(dev->aio);
if (*value < 0)
return UPM_ERROR_OPERATION_FAILED;
/* Scale by the ADC reference voltage */
*value *= dev->m_aRef;
return UPM_SUCCESS;
}
upm_result_t gsr_get_volts(const gsr_context dev, float *value)
{
*value = mraa_aio_read_float(dev->aio);
if (*value < 0)
return UPM_ERROR_OPERATION_FAILED;
/* Apply raw scale */
*value *= dev->m_scale;
/* Scale to aRef */
*value *= dev->m_aRef;
/* Apply the offset in volts */
*value += dev->m_offset;
return UPM_SUCCESS;
}
|
4132.c | /*
u8g_state.c
backup and restore hardware state
Universal 8bit Graphics Library
Copyright (c) 2011, [email protected]
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this list
of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this
list of conditions and the following disclaimer in the documentation and/or other
materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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.
state callback: backup env U8G_STATE_MSG_BACKUP_ENV
device callback: DEV_MSG_INIT
state callback: backup u8g U8G_STATE_MSG_BACKUP_U8G
state callback: restore env U8G_STATE_MSG_RESTORE_ENV
state callback: backup env U8G_STATE_MSG_BACKUP_ENV
state callback: retore u8g U8G_STATE_MSG_RESTORE_U8G
DEV_MSG_PAGE_FIRST or DEV_MSG_PAGE_NEXT
state callback: restore env U8G_STATE_MSG_RESTORE_ENV
*/
#include <stddef.h>
#include "u8g.h"
void u8g_state_dummy_cb(uint8_t msg)
{
/* the dummy procedure does nothing */
(void) msg;
}
void u8g_SetHardwareBackup(u8g_t *u8g, u8g_state_cb backup_cb)
{
u8g->state_cb = backup_cb;
/* in most cases the init message was already sent, so this will backup the */
/* current u8g state */
backup_cb(U8G_STATE_MSG_BACKUP_U8G);
}
/*===============================================================*/
/* register variable for restoring interrupt state */
#if defined(__AVR__)
uint8_t global_SREG_backup;
#endif
/*===============================================================*/
/* AVR */
#if defined(__AVR__)
#define U8G_ATMEGA_HW_SPI
/* remove the definition for attiny */
#if __AVR_ARCH__ == 2
#undef U8G_ATMEGA_HW_SPI
#endif
#if __AVR_ARCH__ == 25
#undef U8G_ATMEGA_HW_SPI
#endif
#endif
#if defined(U8G_ATMEGA_HW_SPI)
#include <avr/interrupt.h>
static uint8_t u8g_state_avr_spi_memory[2];
void u8g_backup_spi(uint8_t msg)
{
if ( U8G_STATE_MSG_IS_BACKUP(msg) )
{
u8g_state_avr_spi_memory[U8G_STATE_MSG_GET_IDX(msg)] = SPCR;
}
else
{
uint8_t tmp = SREG;
cli();
SPCR = 0;
SPCR = u8g_state_avr_spi_memory[U8G_STATE_MSG_GET_IDX(msg)];
SREG = tmp;
}
}
#elif defined (U8G_RASPBERRY_PI)
#include <stdio.h>
void u8g_backup_spi(uint8_t msg) {
printf("u8g_backup_spi %d\r\n",msg);
}
#elif defined(ARDUINO) && defined(__SAM3X8E__) // Arduino Due, maybe we should better check for __SAM3X8E__
#include "sam.h"
struct sam_backup_struct
{
uint32_t mr;
uint32_t sr;
uint32_t csr[4];
} sam_backup[2];
void u8g_backup_spi(uint8_t msg)
{
uint8_t idx = U8G_STATE_MSG_GET_IDX(msg);
if ( U8G_STATE_MSG_IS_BACKUP(msg) )
{
sam_backup[idx].mr = SPI0->SPI_MR;
sam_backup[idx].sr = SPI0->SPI_SR;
sam_backup[idx].csr[0] = SPI0->SPI_CSR[0];
sam_backup[idx].csr[1] = SPI0->SPI_CSR[1];
sam_backup[idx].csr[2] = SPI0->SPI_CSR[2];
sam_backup[idx].csr[3] = SPI0->SPI_CSR[3];
}
else
{
SPI0->SPI_MR = sam_backup[idx].mr;
SPI0->SPI_CSR[0] = sam_backup[idx].csr[0];
SPI0->SPI_CSR[1] = sam_backup[idx].csr[1];
SPI0->SPI_CSR[2] = sam_backup[idx].csr[2];
SPI0->SPI_CSR[3] = sam_backup[idx].csr[3];
}
}
#else
void u8g_backup_spi(uint8_t msg)
{
(void) msg;
}
#endif
|
565994.c | /*
Authored 2016-2018. Phillip Stanley-Marbell.
Additional contributions, 2018 onwards: Jan Heck, Chatura Samarakoon, Youchao Wang, Sam Willis.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above
copyright notice, this list of conditions and the following
disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials
provided with the distribution.
* Neither the name of the author 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 <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "fsl_misc_utilities.h"
#include "fsl_device_registers.h"
#include "fsl_i2c_master_driver.h"
#include "fsl_spi_master_driver.h"
#include "fsl_rtc_driver.h"
#include "fsl_clock_manager.h"
#include "fsl_power_manager.h"
#include "fsl_mcglite_hal.h"
#include "fsl_port_hal.h"
#include "fsl_lpuart_driver.h"
#include "gpio_pins.h"
#include "SEGGER_RTT.h"
#include "warp.h"
#define WARP_FRDMKL03
/*
* Comment out the header file to disable devices
*/
#ifndef WARP_FRDMKL03
# include "devBMX055.h"
# include "devMMA8451Q.h"
# include "devHDC1000.h"
# include "devMAG3110.h"
# include "devL3GD20H.h"
# include "devBME680.h"
# include "devCCS811.h"
# include "devAMG8834.h"
//# include "devMAX11300.h"
//#include "devTCS34725.h"
//#include "devSI4705.h"
//#include "devSI7021.h"
//#include "devLPS25H.h"
//#include "devADXL362.h"
//#include "devPAN1326.h"
//#include "devAS7262.h"
//#include "devAS7263.h"
//#include "devRV8803C7.h"
//#include "devISL23415.h"
#else
# include "devMMA8451Q.h"
/*
* Add devSSD1331.h
*/
#endif
# include "devSSD1331.h"
#define WARP_BUILD_ENABLE_SEGGER_RTT_PRINTF
//#define WARP_BUILD_BOOT_TO_CSVSTREAM
/*
* BTstack includes WIP
*/
// #include "btstack_main.h"
#define kWarpConstantStringI2cFailure "\rI2C failed, reg 0x%02x, code %d\n"
#define kWarpConstantStringErrorInvalidVoltage "\rInvalid supply voltage [%d] mV!"
#define kWarpConstantStringErrorSanity "\rSanity check failed!"
#ifdef WARP_BUILD_ENABLE_DEVADXL362
volatile WarpSPIDeviceState deviceADXL362State;
#endif
#ifdef WARP_BUILD_ENABLE_DEVISL23415
volatile WarpSPIDeviceState deviceISL23415State;
#endif
#ifdef WARP_BUILD_ENABLE_DEVBMX055
volatile WarpI2CDeviceState deviceBMX055accelState;
volatile WarpI2CDeviceState deviceBMX055gyroState;
volatile WarpI2CDeviceState deviceBMX055magState;
#endif
#ifdef WARP_BUILD_ENABLE_DEVMMA8451Q
volatile WarpI2CDeviceState deviceMMA8451QState;
#endif
#ifdef WARP_BUILD_ENABLE_DEVLPS25H
volatile WarpI2CDeviceState deviceLPS25HState;
#endif
#ifdef WARP_BUILD_ENABLE_DEVHDC1000
volatile WarpI2CDeviceState deviceHDC1000State;
#endif
#ifdef WARP_BUILD_ENABLE_DEVMAG3110
volatile WarpI2CDeviceState deviceMAG3110State;
#endif
#ifdef WARP_BUILD_ENABLE_DEVSI7021
volatile WarpI2CDeviceState deviceSI7021State;
#endif
#ifdef WARP_BUILD_ENABLE_DEVL3GD20H
volatile WarpI2CDeviceState deviceL3GD20HState;
#endif
#ifdef WARP_BUILD_ENABLE_DEVBME680
volatile WarpI2CDeviceState deviceBME680State;
volatile uint8_t deviceBME680CalibrationValues[kWarpSizesBME680CalibrationValuesCount];
#endif
#ifdef WARP_BUILD_ENABLE_DEVTCS34725
volatile WarpI2CDeviceState deviceTCS34725State;
#endif
#ifdef WARP_BUILD_ENABLE_DEVSI4705
volatile WarpI2CDeviceState deviceSI4705State;
#endif
#ifdef WARP_BUILD_ENABLE_DEVCCS811
volatile WarpI2CDeviceState deviceCCS811State;
#endif
#ifdef WARP_BUILD_ENABLE_DEVAMG8834
volatile WarpI2CDeviceState deviceAMG8834State;
#endif
#ifdef WARP_BUILD_ENABLE_DEVPAN1326
volatile WarpUARTDeviceState devicePAN1326BState;
volatile WarpUARTDeviceState devicePAN1323ETUState;
#endif
#ifdef WARP_BUILD_ENABLE_DEVAS7262
volatile WarpI2CDeviceState deviceAS7262State;
#endif
#ifdef WARP_BUILD_ENABLE_DEVAS7263
volatile WarpI2CDeviceState deviceAS7263State;
#endif
#ifdef WARP_BUILD_ENABLE_DEVRV8803C7
volatile WarpI2CDeviceState deviceRV8803C7State;
#endif
/*
* TODO: move this and possibly others into a global structure
*/
volatile i2c_master_state_t i2cMasterState;
volatile spi_master_state_t spiMasterState;
volatile spi_master_user_config_t spiUserConfig;
volatile lpuart_user_config_t lpuartUserConfig;
volatile lpuart_state_t lpuartState;
/*
* TODO: move magic default numbers into constant definitions.
*/
volatile uint32_t gWarpI2cBaudRateKbps = 200;
volatile uint32_t gWarpUartBaudRateKbps = 1;
volatile uint32_t gWarpSpiBaudRateKbps = 200;
volatile uint32_t gWarpSleeptimeSeconds = 0;
volatile WarpModeMask gWarpMode = kWarpModeDisableAdcOnSleep;
volatile uint32_t gWarpI2cTimeoutMilliseconds = 5;
volatile uint32_t gWarpSpiTimeoutMicroseconds = 5;
volatile uint32_t gWarpMenuPrintDelayMilliseconds = 10;
volatile uint32_t gWarpSupplySettlingDelayMilliseconds = 1;
void sleepUntilReset(void);
void lowPowerPinStates(void);
void disableTPS82740A(void);
void disableTPS82740B(void);
void enableTPS82740A(uint16_t voltageMillivolts);
void enableTPS82740B(uint16_t voltageMillivolts);
void setTPS82740CommonControlLines(uint16_t voltageMillivolts);
void printPinDirections(void);
void dumpProcessorState(void);
void repeatRegisterReadForDeviceAndAddress(WarpSensorDevice warpSensorDevice, uint8_t baseAddress,
uint8_t pullupValue, bool autoIncrement, int chunkReadsPerAddress, bool chatty,
int spinDelay, int repetitionsPerAddress, uint16_t sssupplyMillivolts,
uint16_t adaptiveSssupplyMaxMillivolts, uint8_t referenceByte);
int char2int(int character);
void enableSssupply(uint16_t voltageMillivolts);
void disableSssupply(void);
void activateAllLowPowerSensorModes(bool verbose);
void powerupAllSensors(void);
uint8_t readHexByte(void);
int read4digits(void);
void printAllSensors(bool printHeadersAndCalibration, bool hexModeFlag, int menuDelayBetweenEachRun, int i2cPullupValue);
/*
* TODO: change the following to take byte arrays
*/
WarpStatus writeByteToI2cDeviceRegister(uint8_t i2cAddress, bool sendCommandByte, uint8_t commandByte, bool sendPayloadByte, uint8_t payloadByte);
WarpStatus writeBytesToSpi(uint8_t * payloadBytes, int payloadLength);
void warpLowPowerSecondsSleep(uint32_t sleepSeconds, bool forceAllPinsIntoLowPowerState);
/*
* From KSDK power_manager_demo.c <<BEGIN>>>
*/
clock_manager_error_code_t clockManagerCallbackRoutine(clock_notify_struct_t * notify, void * callbackData);
/*
* static clock callback table.
*/
clock_manager_callback_user_config_t clockManagerCallbackUserlevelStructure =
{
.callback = clockManagerCallbackRoutine,
.callbackType = kClockManagerCallbackBeforeAfter,
.callbackData = NULL
};
static clock_manager_callback_user_config_t * clockCallbackTable[] =
{
&clockManagerCallbackUserlevelStructure
};
clock_manager_error_code_t
clockManagerCallbackRoutine(clock_notify_struct_t * notify, void * callbackData)
{
clock_manager_error_code_t result = kClockManagerSuccess;
switch (notify->notifyType)
{
case kClockManagerNotifyBefore:
break;
case kClockManagerNotifyRecover:
case kClockManagerNotifyAfter:
break;
default:
result = kClockManagerError;
break;
}
return result;
}
/*
* Override the RTC IRQ handler
*/
void
RTC_IRQHandler(void)
{
if (RTC_DRV_IsAlarmPending(0))
{
RTC_DRV_SetAlarmIntCmd(0, false);
}
}
/*
* Override the RTC Second IRQ handler
*/
void
RTC_Seconds_IRQHandler(void)
{
gWarpSleeptimeSeconds++;
}
/*
* Power manager user callback
*/
power_manager_error_code_t callback0(power_manager_notify_struct_t * notify,
power_manager_callback_data_t * dataPtr)
{
WarpPowerManagerCallbackStructure * callbackUserData = (WarpPowerManagerCallbackStructure *) dataPtr;
power_manager_error_code_t status = kPowerManagerError;
switch (notify->notifyType)
{
case kPowerManagerNotifyBefore:
status = kPowerManagerSuccess;
break;
case kPowerManagerNotifyAfter:
status = kPowerManagerSuccess;
break;
default:
callbackUserData->errorCount++;
break;
}
return status;
}
/*
* From KSDK power_manager_demo.c <<END>>>
*/
void
sleepUntilReset(void)
{
while (1)
{
#ifdef WARP_BUILD_ENABLE_DEVSI4705
GPIO_DRV_SetPinOutput(kWarpPinSI4705_nRST);
#endif
warpLowPowerSecondsSleep(1, false /* forceAllPinsIntoLowPowerState */);
#ifdef WARP_BUILD_ENABLE_DEVSI4705
GPIO_DRV_ClearPinOutput(kWarpPinSI4705_nRST);
#endif
warpLowPowerSecondsSleep(60, true /* forceAllPinsIntoLowPowerState */);
}
}
void
enableLPUARTpins(void)
{
/* Enable UART CLOCK */
CLOCK_SYS_EnableLpuartClock(0);
/*
* set UART pin association
* see page 99 in https://www.nxp.com/docs/en/reference-manual/KL03P24M48SF0RM.pdf
*/
#ifdef WARP_BUILD_ENABLE_DEVPAN1326
/* Warp KL03_UART_HCI_TX --> PTB3 (ALT3) --> PAN1326 HCI_RX */
PORT_HAL_SetMuxMode(PORTB_BASE, 3, kPortMuxAlt3);
/* Warp KL03_UART_HCI_RX --> PTB4 (ALT3) --> PAN1326 HCI_RX */
PORT_HAL_SetMuxMode(PORTB_BASE, 4, kPortMuxAlt3);
/* TODO: Partial Implementation */
/* Warp PTA6 --> PAN1326 HCI_RTS */
/* Warp PTA7 --> PAN1326 HCI_CTS */
#endif
/*
* Initialize LPUART0. See KSDK13APIRM.pdf section 40.4.3, page 1353
*
*/
lpuartUserConfig.baudRate = 115;
lpuartUserConfig.parityMode = kLpuartParityDisabled;
lpuartUserConfig.stopBitCount = kLpuartOneStopBit;
lpuartUserConfig.bitCountPerChar = kLpuart8BitsPerChar;
LPUART_DRV_Init(0,(lpuart_state_t *)&lpuartState,(lpuart_user_config_t *)&lpuartUserConfig);
}
void
disableLPUARTpins(void)
{
/*
* LPUART deinit
*/
LPUART_DRV_Deinit(0);
/* Warp KL03_UART_HCI_RX --> PTB4 (GPIO) */
PORT_HAL_SetMuxMode(PORTB_BASE, 4, kPortMuxAsGpio);
/* Warp KL03_UART_HCI_TX --> PTB3 (GPIO) */
PORT_HAL_SetMuxMode(PORTB_BASE, 3, kPortMuxAsGpio);
#ifdef WARP_BUILD_ENABLE_DEVPAN1326
GPIO_DRV_ClearPinOutput(kWarpPinPAN1326_HCI_CTS);
GPIO_DRV_ClearPinOutput(kWarpPinPAN1326_HCI_CTS);
#endif
GPIO_DRV_ClearPinOutput(kWarpPinLPUART_HCI_TX);
GPIO_DRV_ClearPinOutput(kWarpPinLPUART_HCI_RX);
/* Disable LPUART CLOCK */
CLOCK_SYS_DisableLpuartClock(0);
}
void
enableSPIpins(void)
{
CLOCK_SYS_EnableSpiClock(0);
/* Warp KL03_SPI_MISO --> PTA6 (ALT3) */
PORT_HAL_SetMuxMode(PORTA_BASE, 6, kPortMuxAlt3);
/* Warp KL03_SPI_MOSI --> PTA7 (ALT3) */
PORT_HAL_SetMuxMode(PORTA_BASE, 7, kPortMuxAlt3);
/* Warp KL03_SPI_SCK --> PTB0 (ALT3) */
PORT_HAL_SetMuxMode(PORTB_BASE, 0, kPortMuxAlt3);
/*
* Initialize SPI master. See KSDK13APIRM.pdf Section 70.4
*
*/
uint32_t calculatedBaudRate;
spiUserConfig.polarity = kSpiClockPolarity_ActiveHigh;
spiUserConfig.phase = kSpiClockPhase_FirstEdge;
spiUserConfig.direction = kSpiMsbFirst;
spiUserConfig.bitsPerSec = gWarpSpiBaudRateKbps * 1000;
SPI_DRV_MasterInit(0 /* SPI master instance */, (spi_master_state_t *)&spiMasterState);
SPI_DRV_MasterConfigureBus(0 /* SPI master instance */, (spi_master_user_config_t *)&spiUserConfig, &calculatedBaudRate);
}
void
disableSPIpins(void)
{
SPI_DRV_MasterDeinit(0);
/* Warp KL03_SPI_MISO --> PTA6 (GPI) */
PORT_HAL_SetMuxMode(PORTA_BASE, 6, kPortMuxAsGpio);
/* Warp KL03_SPI_MOSI --> PTA7 (GPIO) */
PORT_HAL_SetMuxMode(PORTA_BASE, 7, kPortMuxAsGpio);
/* Warp KL03_SPI_SCK --> PTB0 (GPIO) */
PORT_HAL_SetMuxMode(PORTB_BASE, 0, kPortMuxAsGpio);
GPIO_DRV_ClearPinOutput(kWarpPinSPI_MOSI);
GPIO_DRV_ClearPinOutput(kWarpPinSPI_MISO);
GPIO_DRV_ClearPinOutput(kWarpPinSPI_SCK);
CLOCK_SYS_DisableSpiClock(0);
}
void
configureI2Cpins(uint8_t pullupValue)
{
#ifdef WARP_BUILD_ENABLE_DEVISL23415
/*
* Configure the two ISL23415 DCPs over SPI
*/
uint8_t valuesDCP[2] = {pullupValue, pullupValue};
writeDeviceRegisterISL23415(kWarpISL23415RegWR, valuesDCP, 4);
#endif
}
void
enableI2Cpins(uint8_t pullupValue)
{
CLOCK_SYS_EnableI2cClock(0);
/* Warp KL03_I2C0_SCL --> PTB3 (ALT2 == I2C) */
PORT_HAL_SetMuxMode(PORTB_BASE, 3, kPortMuxAlt2);
/* Warp KL03_I2C0_SDA --> PTB4 (ALT2 == I2C) */
PORT_HAL_SetMuxMode(PORTB_BASE, 4, kPortMuxAlt2);
I2C_DRV_MasterInit(0 /* I2C instance */, (i2c_master_state_t *)&i2cMasterState);
configureI2Cpins(pullupValue);
}
void
disableI2Cpins(void)
{
I2C_DRV_MasterDeinit(0 /* I2C instance */);
/* Warp KL03_I2C0_SCL --> PTB3 (GPIO) */
PORT_HAL_SetMuxMode(PORTB_BASE, 3, kPortMuxAsGpio);
/* Warp KL03_I2C0_SDA --> PTB4 (GPIO) */
PORT_HAL_SetMuxMode(PORTB_BASE, 4, kPortMuxAsGpio);
/*
* Reset DCP configuration
*/
configureI2Cpins(0x80); /* Defaults DCP configuration ISL datasheet FN7780 Rev 2.00 - page 14 */
/*
* Drive the I2C pins low
*/
GPIO_DRV_ClearPinOutput(kWarpPinI2C0_SDA);
GPIO_DRV_ClearPinOutput(kWarpPinI2C0_SCL);
CLOCK_SYS_DisableI2cClock(0);
}
// TODO: add pin states for pan1326 lp states
void
lowPowerPinStates(void)
{
/*
* Following Section 5 of "Power Management for Kinetis L Family" (AN5088.pdf),
* we configure all pins as output and set them to a known state. We choose
* to set them all to '0' since it happens that the devices we want to keep
* deactivated (SI4705, PAN1326) also need '0'.
*/
/*
* PORT A
*/
/*
* For now, don't touch the PTA0/1/2 SWD pins. Revisit in the future.
*/
/*
PORT_HAL_SetMuxMode(PORTA_BASE, 0, kPortMuxAsGpio);
PORT_HAL_SetMuxMode(PORTA_BASE, 1, kPortMuxAsGpio);
PORT_HAL_SetMuxMode(PORTA_BASE, 2, kPortMuxAsGpio);
*/
/*
* PTA3 and PTA4 are the EXTAL/XTAL
*/
PORT_HAL_SetMuxMode(PORTA_BASE, 3, kPortPinDisabled);
PORT_HAL_SetMuxMode(PORTA_BASE, 4, kPortPinDisabled);
PORT_HAL_SetMuxMode(PORTA_BASE, 5, kPortMuxAsGpio);
PORT_HAL_SetMuxMode(PORTA_BASE, 6, kPortMuxAsGpio);
PORT_HAL_SetMuxMode(PORTA_BASE, 7, kPortMuxAsGpio);
PORT_HAL_SetMuxMode(PORTA_BASE, 8, kPortMuxAsGpio);
PORT_HAL_SetMuxMode(PORTA_BASE, 9, kPortMuxAsGpio);
/*
* NOTE: The KL03 has no PTA10 or PTA11
*/
PORT_HAL_SetMuxMode(PORTA_BASE, 12, kPortMuxAsGpio);
/*
* PORT B
*/
PORT_HAL_SetMuxMode(PORTB_BASE, 0, kPortMuxAsGpio);
/*
* PTB1 is connected to KL03_VDD. We have a choice of:
* (1) Keep 'disabled as analog'.
* (2) Set as output and drive high.
*
* Pin state "disabled" means default functionality (ADC) is _active_
*/
if (gWarpMode & kWarpModeDisableAdcOnSleep)
{
PORT_HAL_SetMuxMode(PORTB_BASE, 1, kPortMuxAsGpio);
}
else
{
PORT_HAL_SetMuxMode(PORTB_BASE, 1, kPortPinDisabled);
}
PORT_HAL_SetMuxMode(PORTB_BASE, 2, kPortMuxAsGpio);
/*
* PTB3 and PTB3 (I2C pins) are true open-drain
* and we purposefully leave them disabled.
*/
PORT_HAL_SetMuxMode(PORTB_BASE, 3, kPortPinDisabled);
PORT_HAL_SetMuxMode(PORTB_BASE, 4, kPortPinDisabled);
PORT_HAL_SetMuxMode(PORTB_BASE, 5, kPortMuxAsGpio);
PORT_HAL_SetMuxMode(PORTB_BASE, 6, kPortMuxAsGpio);
PORT_HAL_SetMuxMode(PORTB_BASE, 7, kPortMuxAsGpio);
/*
* NOTE: The KL03 has no PTB8 or PTB9
*/
PORT_HAL_SetMuxMode(PORTB_BASE, 10, kPortMuxAsGpio);
PORT_HAL_SetMuxMode(PORTB_BASE, 11, kPortMuxAsGpio);
/*
* NOTE: The KL03 has no PTB12
*/
PORT_HAL_SetMuxMode(PORTB_BASE, 13, kPortMuxAsGpio);
/*
* Now, set all the pins (except kWarpPinKL03_VDD_ADC, the SWD pins, and the XTAL/EXTAL) to 0
*/
/*
* If we are in mode where we disable the ADC, then drive the pin high since it is tied to KL03_VDD
*/
if (gWarpMode & kWarpModeDisableAdcOnSleep)
{
GPIO_DRV_SetPinOutput(kWarpPinKL03_VDD_ADC);
}
#ifndef WARP_BUILD_ENABLE_THERMALCHAMBERANALYSIS
#ifdef WARP_BUILD_ENABLE_DEVPAN1326
GPIO_DRV_ClearPinOutput(kWarpPinPAN1326_nSHUTD);
#endif
#endif
GPIO_DRV_ClearPinOutput(kWarpPinTPS82740A_CTLEN);
GPIO_DRV_ClearPinOutput(kWarpPinTPS82740B_CTLEN);
GPIO_DRV_ClearPinOutput(kWarpPinTPS82740_VSEL1);
GPIO_DRV_ClearPinOutput(kWarpPinTPS82740_VSEL2);
GPIO_DRV_ClearPinOutput(kWarpPinTPS82740_VSEL3);
#ifndef WARP_BUILD_ENABLE_THERMALCHAMBERANALYSIS
GPIO_DRV_ClearPinOutput(kWarpPinCLKOUT32K);
#endif
GPIO_DRV_ClearPinOutput(kWarpPinTS5A3154_IN);
GPIO_DRV_ClearPinOutput(kWarpPinSI4705_nRST);
/*
* Drive these chip selects high since they are active low:
*/
#ifndef WARP_BUILD_ENABLE_THERMALCHAMBERANALYSIS
GPIO_DRV_SetPinOutput(kWarpPinISL23415_nCS);
#endif
#ifdef WARP_BUILD_ENABLE_DEVADXL362
GPIO_DRV_SetPinOutput(kWarpPinADXL362_CS);
#endif
/*
* When the PAN1326 is installed, note that it has the
* following pull-up/down by default:
*
* HCI_RX / kWarpPinI2C0_SCL : pull up
* HCI_TX / kWarpPinI2C0_SDA : pull up
* HCI_RTS / kWarpPinSPI_MISO : pull up
* HCI_CTS / kWarpPinSPI_MOSI : pull up
*
* These I/Os are 8mA (see panasonic_PAN13xx.pdf, page 10),
* so we really don't want to be driving them low. We
* however also have to be careful of the I2C pullup and
* pull-up gating. However, driving them high leads to
* higher board power dissipation even when SSSUPPLY is off
* by ~80mW on board #003 (PAN1326 populated).
*
* In revB board, with the ISL23415 DCP pullups, we also
* want I2C_SCL and I2C_SDA driven high since when we
* send a shutdown command to the DCP it will connect
* those lines to 25570_VOUT.
*
* For now, we therefore leave the SPI pins low and the
* I2C pins (PTB3, PTB4, which are true open-drain) disabled.
*/
GPIO_DRV_ClearPinOutput(kWarpPinI2C0_SDA);
GPIO_DRV_ClearPinOutput(kWarpPinI2C0_SCL);
GPIO_DRV_ClearPinOutput(kWarpPinSPI_MOSI);
GPIO_DRV_ClearPinOutput(kWarpPinSPI_MISO);
GPIO_DRV_ClearPinOutput(kWarpPinSPI_SCK);
/*
* HCI_RX / kWarpPinI2C0_SCL is an input. Set it low.
*/
//GPIO_DRV_SetPinOutput(kWarpPinI2C0_SCL);
/*
* HCI_TX / kWarpPinI2C0_SDA is an output. Set it high.
*/
//GPIO_DRV_SetPinOutput(kWarpPinI2C0_SDA);
/*
* HCI_RTS / kWarpPinSPI_MISO is an output. Set it high.
*/
//GPIO_DRV_SetPinOutput(kWarpPinSPI_MISO);
/*
* From PAN1326 manual, page 10:
*
* "When HCI_CTS is high, then CC256X is not allowed to send data to Host device"
*/
//GPIO_DRV_SetPinOutput(kWarpPinSPI_MOSI);
}
void
disableTPS82740A(void)
{
GPIO_DRV_ClearPinOutput(kWarpPinTPS82740A_CTLEN);
}
void
disableTPS82740B(void)
{
GPIO_DRV_ClearPinOutput(kWarpPinTPS82740B_CTLEN);
}
void
enableTPS82740A(uint16_t voltageMillivolts)
{
setTPS82740CommonControlLines(voltageMillivolts);
GPIO_DRV_SetPinOutput(kWarpPinTPS82740A_CTLEN);
GPIO_DRV_ClearPinOutput(kWarpPinTPS82740B_CTLEN);
/*
* Select the TS5A3154 to use the output of the TPS82740
*
* IN = high selects the output of the TPS82740B:
* IN = low selects the output of the TPS82740A:
*/
GPIO_DRV_ClearPinOutput(kWarpPinTS5A3154_IN);
}
void
enableTPS82740B(uint16_t voltageMillivolts)
{
setTPS82740CommonControlLines(voltageMillivolts);
GPIO_DRV_ClearPinOutput(kWarpPinTPS82740A_CTLEN);
GPIO_DRV_SetPinOutput(kWarpPinTPS82740B_CTLEN);
/*
* Select the TS5A3154 to use the output of the TPS82740
*
* IN = high selects the output of the TPS82740B:
* IN = low selects the output of the TPS82740A:
*/
GPIO_DRV_SetPinOutput(kWarpPinTS5A3154_IN);
}
void
setTPS82740CommonControlLines(uint16_t voltageMillivolts)
{
/*
* From Manual:
*
* TPS82740A: VSEL1 VSEL2 VSEL3: 000-->1.8V, 111-->2.5V
* TPS82740B: VSEL1 VSEL2 VSEL3: 000-->2.6V, 111-->3.3V
*/
switch(voltageMillivolts)
{
case 2600:
case 1800:
{
GPIO_DRV_ClearPinOutput(kWarpPinTPS82740_VSEL1);
GPIO_DRV_ClearPinOutput(kWarpPinTPS82740_VSEL2);
GPIO_DRV_ClearPinOutput(kWarpPinTPS82740_VSEL3);
break;
}
case 2700:
case 1900:
{
GPIO_DRV_SetPinOutput(kWarpPinTPS82740_VSEL1);
GPIO_DRV_ClearPinOutput(kWarpPinTPS82740_VSEL2);
GPIO_DRV_ClearPinOutput(kWarpPinTPS82740_VSEL3);
break;
}
case 2800:
case 2000:
{
GPIO_DRV_ClearPinOutput(kWarpPinTPS82740_VSEL1);
GPIO_DRV_SetPinOutput(kWarpPinTPS82740_VSEL2);
GPIO_DRV_ClearPinOutput(kWarpPinTPS82740_VSEL3);
break;
}
case 2900:
case 2100:
{
GPIO_DRV_SetPinOutput(kWarpPinTPS82740_VSEL1);
GPIO_DRV_SetPinOutput(kWarpPinTPS82740_VSEL2);
GPIO_DRV_ClearPinOutput(kWarpPinTPS82740_VSEL3);
break;
}
case 3000:
case 2200:
{
GPIO_DRV_ClearPinOutput(kWarpPinTPS82740_VSEL1);
GPIO_DRV_ClearPinOutput(kWarpPinTPS82740_VSEL2);
GPIO_DRV_SetPinOutput(kWarpPinTPS82740_VSEL3);
break;
}
case 3100:
case 2300:
{
GPIO_DRV_SetPinOutput(kWarpPinTPS82740_VSEL1);
GPIO_DRV_ClearPinOutput(kWarpPinTPS82740_VSEL2);
GPIO_DRV_SetPinOutput(kWarpPinTPS82740_VSEL3);
break;
}
case 3200:
case 2400:
{
GPIO_DRV_ClearPinOutput(kWarpPinTPS82740_VSEL1);
GPIO_DRV_SetPinOutput(kWarpPinTPS82740_VSEL2);
GPIO_DRV_SetPinOutput(kWarpPinTPS82740_VSEL3);
break;
}
case 3300:
case 2500:
{
GPIO_DRV_SetPinOutput(kWarpPinTPS82740_VSEL1);
GPIO_DRV_SetPinOutput(kWarpPinTPS82740_VSEL2);
GPIO_DRV_SetPinOutput(kWarpPinTPS82740_VSEL3);
break;
}
/*
* Should never happen, due to previous check in enableSssupply()
*/
default:
{
#ifdef WARP_BUILD_ENABLE_SEGGER_RTT_PRINTF
SEGGER_RTT_printf(0, RTT_CTRL_RESET RTT_CTRL_BG_BRIGHT_YELLOW RTT_CTRL_TEXT_BRIGHT_WHITE kWarpConstantStringErrorSanity RTT_CTRL_RESET "\n");
#endif
}
}
/*
* Vload ramp time of the TPS82740 is 800us max (datasheet, Section 8.5 / page 5)
*/
OSA_TimeDelay(gWarpSupplySettlingDelayMilliseconds);
}
void
enableSssupply(uint16_t voltageMillivolts)
{
if (voltageMillivolts >= 1800 && voltageMillivolts <= 2500)
{
enableTPS82740A(voltageMillivolts);
}
else if (voltageMillivolts >= 2600 && voltageMillivolts <= 3300)
{
enableTPS82740B(voltageMillivolts);
}
else
{
#ifdef WARP_BUILD_ENABLE_SEGGER_RTT_PRINTF
SEGGER_RTT_printf(0, RTT_CTRL_RESET RTT_CTRL_BG_BRIGHT_RED RTT_CTRL_TEXT_BRIGHT_WHITE kWarpConstantStringErrorInvalidVoltage RTT_CTRL_RESET "\n", voltageMillivolts);
#endif
}
}
void
disableSssupply(void)
{
disableTPS82740A();
disableTPS82740B();
/*
* Clear the pin. This sets the TS5A3154 to use the output of the TPS82740B,
* which shouldn't matter in any case. The main objective here is to clear
* the pin to reduce power drain.
*
* IN = high selects the output of the TPS82740B:
* IN = low selects the output of the TPS82740A:
*/
GPIO_DRV_SetPinOutput(kWarpPinTS5A3154_IN);
/*
* Vload ramp time of the TPS82740 is 800us max (datasheet, Section 8.5 / page 5)
*/
OSA_TimeDelay(gWarpSupplySettlingDelayMilliseconds);
}
void
warpLowPowerSecondsSleep(uint32_t sleepSeconds, bool forceAllPinsIntoLowPowerState)
{
/*
* Set all pins into low-power states. We don't just disable all pins,
* as the various devices hanging off will be left in higher power draw
* state. And manuals say set pins to output to reduce power.
*/
if (forceAllPinsIntoLowPowerState)
{
lowPowerPinStates();
}
warpSetLowPowerMode(kWarpPowerModeVLPR, 0);
warpSetLowPowerMode(kWarpPowerModeVLPS, sleepSeconds);
}
void
printPinDirections(void)
{
/*
#ifdef WARP_BUILD_ENABLE_SEGGER_RTT_PRINTF
SEGGER_RTT_printf(0, "KL03_VDD_ADC:%d\n", GPIO_DRV_GetPinDir(kWarpPinKL03_VDD_ADC));
OSA_TimeDelay(100);
SEGGER_RTT_printf(0, "I2C0_SDA:%d\n", GPIO_DRV_GetPinDir(kWarpPinI2C0_SDA));
OSA_TimeDelay(100);
SEGGER_RTT_printf(0, "I2C0_SCL:%d\n", GPIO_DRV_GetPinDir(kWarpPinI2C0_SCL));
OSA_TimeDelay(100);
SEGGER_RTT_printf(0, "SPI_MOSI:%d\n", GPIO_DRV_GetPinDir(kWarpPinSPI_MOSI));
OSA_TimeDelay(100);
SEGGER_RTT_printf(0, "SPI_MISO:%d\n", GPIO_DRV_GetPinDir(kWarpPinSPI_MISO));
OSA_TimeDelay(100);
SEGGER_RTT_printf(0, "SPI_SCK_I2C_PULLUP_EN:%d\n", GPIO_DRV_GetPinDir(kWarpPinSPI_SCK_I2C_PULLUP_EN));
OSA_TimeDelay(100);
SEGGER_RTT_printf(0, "TPS82740A_VSEL2:%d\n", GPIO_DRV_GetPinDir(kWarpPinTPS82740_VSEL2));
OSA_TimeDelay(100);
SEGGER_RTT_printf(0, "ADXL362_CS:%d\n", GPIO_DRV_GetPinDir(kWarpPinADXL362_CS));
OSA_TimeDelay(100);
SEGGER_RTT_printf(0, "kWarpPinPAN1326_nSHUTD:%d\n", GPIO_DRV_GetPinDir(kWarpPinPAN1326_nSHUTD));
OSA_TimeDelay(100);
SEGGER_RTT_printf(0, "TPS82740A_CTLEN:%d\n", GPIO_DRV_GetPinDir(kWarpPinTPS82740A_CTLEN));
OSA_TimeDelay(100);
SEGGER_RTT_printf(0, "TPS82740B_CTLEN:%d\n", GPIO_DRV_GetPinDir(kWarpPinTPS82740B_CTLEN));
OSA_TimeDelay(100);
SEGGER_RTT_printf(0, "TPS82740A_VSEL1:%d\n", GPIO_DRV_GetPinDir(kWarpPinTPS82740_VSEL1));
OSA_TimeDelay(100);
SEGGER_RTT_printf(0, "TPS82740A_VSEL3:%d\n", GPIO_DRV_GetPinDir(kWarpPinTPS82740_VSEL3));
OSA_TimeDelay(100);
SEGGER_RTT_printf(0, "CLKOUT32K:%d\n", GPIO_DRV_GetPinDir(kWarpPinCLKOUT32K));
OSA_TimeDelay(100);
SEGGER_RTT_printf(0, "TS5A3154_IN:%d\n", GPIO_DRV_GetPinDir(kWarpPinTS5A3154_IN));
OSA_TimeDelay(100);
SEGGER_RTT_printf(0, "SI4705_nRST:%d\n", GPIO_DRV_GetPinDir(kWarpPinSI4705_nRST));
OSA_TimeDelay(100);
#endif
*/
}
void
dumpProcessorState(void)
{
/*
uint32_t cpuClockFrequency;
CLOCK_SYS_GetFreq(kCoreClock, &cpuClockFrequency);
#ifdef WARP_BUILD_ENABLE_SEGGER_RTT_PRINTF
SEGGER_RTT_printf(0, "\r\n\n\tCPU @ %u KHz\n", (cpuClockFrequency / 1000));
SEGGER_RTT_printf(0, "\r\tCPU power mode: %u\n", POWER_SYS_GetCurrentMode());
SEGGER_RTT_printf(0, "\r\tCPU clock manager configuration: %u\n", CLOCK_SYS_GetCurrentConfiguration());
SEGGER_RTT_printf(0, "\r\tRTC clock: %d\n", CLOCK_SYS_GetRtcGateCmd(0));
SEGGER_RTT_printf(0, "\r\tSPI clock: %d\n", CLOCK_SYS_GetSpiGateCmd(0));
SEGGER_RTT_printf(0, "\r\tI2C clock: %d\n", CLOCK_SYS_GetI2cGateCmd(0));
SEGGER_RTT_printf(0, "\r\tLPUART clock: %d\n", CLOCK_SYS_GetLpuartGateCmd(0));
SEGGER_RTT_printf(0, "\r\tPORT A clock: %d\n", CLOCK_SYS_GetPortGateCmd(0));
SEGGER_RTT_printf(0, "\r\tPORT B clock: %d\n", CLOCK_SYS_GetPortGateCmd(1));
SEGGER_RTT_printf(0, "\r\tFTF clock: %d\n", CLOCK_SYS_GetFtfGateCmd(0));
SEGGER_RTT_printf(0, "\r\tADC clock: %d\n", CLOCK_SYS_GetAdcGateCmd(0));
SEGGER_RTT_printf(0, "\r\tCMP clock: %d\n", CLOCK_SYS_GetCmpGateCmd(0));
SEGGER_RTT_printf(0, "\r\tVREF clock: %d\n", CLOCK_SYS_GetVrefGateCmd(0));
SEGGER_RTT_printf(0, "\r\tTPM clock: %d\n", CLOCK_SYS_GetTpmGateCmd(0));
#endif
*/
}
#ifdef WARP_BUILD_ENABLE_THERMALCHAMBERANALYSIS
void
addAndMultiplicationBusyLoop(long iterations)
{
int value;
for (volatile long i = 0; i < iterations; i++)
{
value = kWarpThermalChamberBusyLoopAdder + value * kWarpThermalChamberBusyLoopMutiplier;
}
}
uint8_t
checkSum(uint8_t * pointer, uint16_t length) /* Adapted from https://stackoverflow.com/questions/31151032/writing-an-8-bit-checksum-in-c */
{
unsigned int sum;
for ( sum = 0 ; length != 0 ; length-- )
{
sum += *(pointer++);
}
return (uint8_t)sum;
}
#endif
int
main(void)
{
uint8_t key;
WarpSensorDevice menuTargetSensor = kWarpSensorBMX055accel;
volatile WarpI2CDeviceState * menuI2cDevice = NULL;
uint16_t menuI2cPullupValue = 32768;
uint8_t menuRegisterAddress = 0x00;
uint16_t menuSupplyVoltage = 0;
rtc_datetime_t warpBootDate;
power_manager_user_config_t warpPowerModeWaitConfig;
power_manager_user_config_t warpPowerModeStopConfig;
power_manager_user_config_t warpPowerModeVlpwConfig;
power_manager_user_config_t warpPowerModeVlpsConfig;
power_manager_user_config_t warpPowerModeVlls0Config;
power_manager_user_config_t warpPowerModeVlls1Config;
power_manager_user_config_t warpPowerModeVlls3Config;
power_manager_user_config_t warpPowerModeRunConfig;
const power_manager_user_config_t warpPowerModeVlprConfig = {
.mode = kPowerManagerVlpr,
.sleepOnExitValue = false,
.sleepOnExitOption = false
};
power_manager_user_config_t const * powerConfigs[] = {
/*
* NOTE: This order is depended on by POWER_SYS_SetMode()
*
* See KSDK13APIRM.pdf Section 55.5.3
*/
&warpPowerModeWaitConfig,
&warpPowerModeStopConfig,
&warpPowerModeVlprConfig,
&warpPowerModeVlpwConfig,
&warpPowerModeVlpsConfig,
&warpPowerModeVlls0Config,
&warpPowerModeVlls1Config,
&warpPowerModeVlls3Config,
&warpPowerModeRunConfig,
};
WarpPowerManagerCallbackStructure powerManagerCallbackStructure;
/*
* Callback configuration structure for power manager
*/
const power_manager_callback_user_config_t callbackCfg0 = {
callback0,
kPowerManagerCallbackBeforeAfter,
(power_manager_callback_data_t *) &powerManagerCallbackStructure};
/*
* Pointers to power manager callbacks.
*/
power_manager_callback_user_config_t const * callbacks[] = {
&callbackCfg0
};
/*
* Enable clock for I/O PORT A and PORT B
*/
CLOCK_SYS_EnablePortClock(0);
CLOCK_SYS_EnablePortClock(1);
/*
* Setup board clock source.
*/
g_xtal0ClkFreq = 32768U;
/*
* Initialize KSDK Operating System Abstraction layer (OSA) layer.
*/
OSA_Init();
/*
* Setup SEGGER RTT to output as much as fits in buffers.
*
* Using SEGGER_RTT_MODE_BLOCK_IF_FIFO_FULL can lead to deadlock, since
* we might have SWD disabled at time of blockage.
*/
SEGGER_RTT_ConfigUpBuffer(0, NULL, NULL, 0, SEGGER_RTT_MODE_NO_BLOCK_TRIM);
SEGGER_RTT_WriteString(0, "\n\n\n\rBooting Warp, in 3... ");
OSA_TimeDelay(200);
SEGGER_RTT_WriteString(0, "2... ");
OSA_TimeDelay(200);
SEGGER_RTT_WriteString(0, "1...\n\r");
OSA_TimeDelay(200);
/*
* Configure Clock Manager to default, and set callback for Clock Manager mode transition.
*
* See "Clocks and Low Power modes with KSDK and Processor Expert" document (Low_Power_KSDK_PEx.pdf)
*/
CLOCK_SYS_Init( g_defaultClockConfigurations,
CLOCK_CONFIG_NUM,
&clockCallbackTable,
ARRAY_SIZE(clockCallbackTable)
);
CLOCK_SYS_UpdateConfiguration(CLOCK_CONFIG_INDEX_FOR_RUN, kClockManagerPolicyForcible);
/*
* Initialize RTC Driver
*/
RTC_DRV_Init(0);
/*
* Set initial date to 1st January 2016 00:00, and set date via RTC driver
*/
warpBootDate.year = 2016U;
warpBootDate.month = 1U;
warpBootDate.day = 1U;
warpBootDate.hour = 0U;
warpBootDate.minute = 0U;
warpBootDate.second = 0U;
RTC_DRV_SetDatetime(0, &warpBootDate);
/*
* Setup Power Manager Driver
*/
memset(&powerManagerCallbackStructure, 0, sizeof(WarpPowerManagerCallbackStructure));
warpPowerModeVlpwConfig = warpPowerModeVlprConfig;
warpPowerModeVlpwConfig.mode = kPowerManagerVlpw;
warpPowerModeVlpsConfig = warpPowerModeVlprConfig;
warpPowerModeVlpsConfig.mode = kPowerManagerVlps;
warpPowerModeWaitConfig = warpPowerModeVlprConfig;
warpPowerModeWaitConfig.mode = kPowerManagerWait;
warpPowerModeStopConfig = warpPowerModeVlprConfig;
warpPowerModeStopConfig.mode = kPowerManagerStop;
warpPowerModeVlls0Config = warpPowerModeVlprConfig;
warpPowerModeVlls0Config.mode = kPowerManagerVlls0;
warpPowerModeVlls1Config = warpPowerModeVlprConfig;
warpPowerModeVlls1Config.mode = kPowerManagerVlls1;
warpPowerModeVlls3Config = warpPowerModeVlprConfig;
warpPowerModeVlls3Config.mode = kPowerManagerVlls3;
warpPowerModeRunConfig.mode = kPowerManagerRun;
POWER_SYS_Init( &powerConfigs,
sizeof(powerConfigs)/sizeof(power_manager_user_config_t *),
&callbacks,
sizeof(callbacks)/sizeof(power_manager_callback_user_config_t *)
);
/*
* Switch CPU to Very Low Power Run (VLPR) mode
*/
warpSetLowPowerMode(kWarpPowerModeVLPR, 0);
/*
* Initialize the GPIO pins with the appropriate pull-up, etc.,
* defined in the inputPins and outputPins arrays (gpio_pins.c).
*
* See also Section 30.3.3 GPIO Initialization of KSDK13APIRM.pdf
*/
GPIO_DRV_Init(inputPins /* input pins */, outputPins /* output pins */);
/*
* Note that it is lowPowerPinStates() that sets the pin mux mode,
* so until we call it pins are in their default state.
*/
lowPowerPinStates();
/*
* Toggle LED3 (kWarpPinSI4705_nRST)
*/
GPIO_DRV_SetPinOutput(kWarpPinSI4705_nRST);
OSA_TimeDelay(200);
GPIO_DRV_ClearPinOutput(kWarpPinSI4705_nRST);
OSA_TimeDelay(200);
GPIO_DRV_SetPinOutput(kWarpPinSI4705_nRST);
OSA_TimeDelay(200);
GPIO_DRV_ClearPinOutput(kWarpPinSI4705_nRST);
OSA_TimeDelay(200);
GPIO_DRV_SetPinOutput(kWarpPinSI4705_nRST);
OSA_TimeDelay(200);
GPIO_DRV_ClearPinOutput(kWarpPinSI4705_nRST);
/*
* Initialize all the sensors
*/
#ifdef WARP_BUILD_ENABLE_DEVBMX055
initBMX055accel(0x18 /* i2cAddress */, &deviceBMX055accelState );
initBMX055gyro( 0x68 /* i2cAddress */, &deviceBMX055gyroState );
initBMX055mag( 0x10 /* i2cAddress */, &deviceBMX055magState );
#endif
#ifdef WARP_BUILD_ENABLE_DEVMMA8451Q
initMMA8451Q( 0x1D /* i2cAddress */, &deviceMMA8451QState );
#endif
#ifdef WARP_BUILD_ENABLE_DEVLPS25H
initLPS25H( 0x5C /* i2cAddress */, &deviceLPS25HState );
#endif
#ifdef WARP_BUILD_ENABLE_DEVHDC1000
initHDC1000( 0x43 /* i2cAddress */, &deviceHDC1000State );
#endif
#ifdef WARP_BUILD_ENABLE_DEVMAG3110
initMAG3110( 0x0E /* i2cAddress */, &deviceMAG3110State );
#endif
#ifdef WARP_BUILD_ENABLE_DEVSI7021
initSI7021( 0x40 /* i2cAddress */, &deviceSI7021State );
#endif
#ifdef WARP_BUILD_ENABLE_DEVL3GD20H
initL3GD20H( 0x6A /* i2cAddress */, &deviceL3GD20HState );
#endif
#ifdef WARP_BUILD_ENABLE_DEVBME680
initBME680( 0x77 /* i2cAddress */, &deviceBME680State );
#endif
#ifdef WARP_BUILD_ENABLE_DEVTCS34725
initTCS34725( 0x29 /* i2cAddress */, &deviceTCS34725State );
#endif
#ifdef WARP_BUILD_ENABLE_DEVSI4705
initSI4705( 0x11 /* i2cAddress */, &deviceSI4705State );
#endif
#ifdef WARP_BUILD_ENABLE_DEVCCS811
initCCS811( 0x5A /* i2cAddress */, &deviceCCS811State );
#endif
#ifdef WARP_BUILD_ENABLE_DEVAMG8834
initAMG8834( 0x68 /* i2cAddress */, &deviceAMG8834State );
#endif
#ifdef WARP_BUILD_ENABLE_DEVAS7262
initAS7262( 0x49 /* i2cAddress */, &deviceAS7262State );
#endif
#ifdef WARP_BUILD_ENABLE_DEVAS7263
initAS7263( 0x49 /* i2cAddress */, &deviceAS7263State );
#endif
#ifdef WARP_BUILD_ENABLE_DEVRV8803C7
initRV8803C7(0x32 /* i2cAddress */, &deviceRV8803C7State);
enableI2Cpins(menuI2cPullupValue);
setRTCCountdownRV8803C7(0, TD_1HZ, false);
disableI2Cpins();
#endif
/*
* Initialization: Devices hanging off SPI
*/
#ifdef WARP_BUILD_ENABLE_DEVADXL362
initADXL362(&deviceADXL362State);
#endif
/*
* Initialization: the PAN1326, generating its 32k clock
*/
#ifdef WARP_BUILD_ENABLE_DEVPAN1326
initPAN1326B(&devicePAN1326BState);
#endif
#ifdef WARP_BUILD_ENABLE_DEVISL23415
initISL23415(&deviceISL23415State);
#endif
/*
* Make sure SCALED_SENSOR_SUPPLY is off.
*
* (There's no point in calling activateAllLowPowerSensorModes())
*/
disableSssupply();
/*
* TODO: initialize the kWarpPinKL03_VDD_ADC, write routines to read the VDD and temperature
*/
#ifdef WARP_BUILD_BOOT_TO_CSVSTREAM
/*
* Force to printAllSensors
*/
gWarpI2cBaudRateKbps = 300;
warpSetLowPowerMode(kWarpPowerModeRUN, 0 /* sleep seconds : irrelevant here */);
enableSssupply(3000);
enableI2Cpins(menuI2cPullupValue);
printAllSensors(false /* printHeadersAndCalibration */, true /* hexModeFlag */, 0 /* menuDelayBetweenEachRun */, menuI2cPullupValue);
/*
* Notreached
*/
#endif
/************************************************************** INA219 ***********************************************************************/
/* enableI2Cpins(menuI2cPullupValue);
extern volatile uint32_t gWarpI2cBaudRateKbps;
extern volatile uint32_t gWarpI2cTimeoutMilliseconds;
extern volatile uint32_t gWarpSupplySettlingDelayMilliseconds;
uint16_t ICONFIG_BVOLTAGERANGE_16V = (0x0000); // 0-16V Range
uint16_t ICONFIG_GAIN_1_40MV = (0x0000); // Gain 1, 40mV Range
uint16_t ICONFIG_BADCRES_12BIT = (0x0180); // 12-bit bus res = 0..4097
uint16_t ICONFIG_SADCRES_12BIT_128S_69MS = (0x0078); // 128 x 12-bit shunt samples averaged together
uint16_t ICONFIG_MODE_SANDBVOLT_CONTINUOUS = (0x0007);
uint8_t INA219_DEVICE_ADDR = (0x40);
uint8_t INA219_CONFIG_REG = (0x00);
uint8_t INA219_CALIB_REG = (0x05);
uint8_t INA219_CURRENT_REG = (0x04);
uint16_t calValue = 8192;
uint8_t currentDivider_mA = 20;
uint16_t config = ICONFIG_BVOLTAGERANGE_16V |
ICONFIG_GAIN_1_40MV |
ICONFIG_BADCRES_12BIT |
ICONFIG_SADCRES_12BIT_128S_69MS |
ICONFIG_MODE_SANDBVOLT_CONTINUOUS;
config = 0b10001000111;*/
/*
* Current_LSB = 0.00001 A (10 microAmps)
* calValue = 40960
* multiply current register by 1í to get actual current in microAmps
*/
/* calValue = 40960;
currentDivider_mA = 10;
*/
/*
uint8_t cmdBuf[1] = {0xFF};
uint8_t payloadBuf[2];
i2c_status_t status;
i2c_device_t slave =
{
.address = INA219_DEVICE_ADDR,
.baudRate_kbps = gWarpI2cBaudRateKbps
};
cmdBuf[0] = INA219_CONFIG_REG;
status = I2C_DRV_MasterReceiveDataBlocking(
0 ,
&slave,
cmdBuf,
1,
(uint8_t *) payloadBuf,
2,
gWarpI2cTimeoutMilliseconds);
uint16_t readSensorRegisterValueCombined = ((payloadBuf[0] << 8) | (payloadBuf[1] & 0xFF));
readSensorRegisterValueCombined *= currentDivider_mA;
SEGGER_RTT_printf(0, "\n %d,", readSensorRegisterValueCombined);
*/
// Write Configuration Register
/* uint8_t payloadByte[2];
uint8_t commandByte[1];
i2c_status_t status;
i2c_device_t slave =
{
.address = INA219_DEVICE_ADDR,
.baudRate_kbps = gWarpI2cBaudRateKbps
};
commandByte[0] = INA219_CONFIG_REG;
payloadByte[0] = (uint8_t)((config>>8) & 0xFF);
payloadByte[1] = (uint8_t)(config & 0xFF);
status = I2C_DRV_MasterSendDataBlocking(
0 ,
&slave,
commandByte,
1,
payloadByte,
2,
gWarpI2cTimeoutMilliseconds);
*/
/*
volatile WarpI2CDeviceState deviceINA219State;
initINA219(0x40, &deviceINA219State);
setCalibration_16V_400mA(menuI2cPullupValue);
*/
/**************************************************************************************************************************************************/
// Invite function to initialise display devSSD1331
devSSD1331init();
while (1)
{
#if 1
/*
* Do not, e.g., lowPowerPinStates() on each iteration, because we actually
* want to use menu to progressiveley change the machine state with various
* commands.
*/
/*
* We break up the prints with small delays to allow us to use small RTT print
* buffers without overrunning them when at max CPU speed.
*/
SEGGER_RTT_WriteString(0, "\r\n\n\n\n[ *\t\t\t\tW\ta\tr\tp\t(rev. b)\t\t\t* ]\n");
OSA_TimeDelay(gWarpMenuPrintDelayMilliseconds);
SEGGER_RTT_WriteString(0, "\r[ \t\t\t\t Cambridge / Physcomplab \t\t\t\t ]\n\n");
OSA_TimeDelay(gWarpMenuPrintDelayMilliseconds);
#ifdef WARP_BUILD_ENABLE_SEGGER_RTT_PRINTF
SEGGER_RTT_printf(0, "\r\tSupply=%dmV,\tDefault Target Read Register=0x%02x\n",
menuSupplyVoltage, menuRegisterAddress);
OSA_TimeDelay(gWarpMenuPrintDelayMilliseconds);
SEGGER_RTT_printf(0, "\r\tI2C=%dkb/s,\tSPI=%dkb/s,\tUART=%dkb/s,\tI2C Pull-Up=%d\n\n",
gWarpI2cBaudRateKbps, gWarpSpiBaudRateKbps, gWarpUartBaudRateKbps, menuI2cPullupValue);
OSA_TimeDelay(gWarpMenuPrintDelayMilliseconds);
SEGGER_RTT_printf(0, "\r\tSIM->SCGC6=0x%02x\t\tRTC->SR=0x%02x\t\tRTC->TSR=0x%02x\n", SIM->SCGC6, RTC->SR, RTC->TSR);
OSA_TimeDelay(gWarpMenuPrintDelayMilliseconds);
SEGGER_RTT_printf(0, "\r\tMCG_C1=0x%02x\t\t\tMCG_C2=0x%02x\t\tMCG_S=0x%02x\n", MCG_C1, MCG_C2, MCG_S);
OSA_TimeDelay(gWarpMenuPrintDelayMilliseconds);
SEGGER_RTT_printf(0, "\r\tMCG_SC=0x%02x\t\t\tMCG_MC=0x%02x\t\tOSC_CR=0x%02x\n", MCG_SC, MCG_MC, OSC_CR);
OSA_TimeDelay(gWarpMenuPrintDelayMilliseconds);
SEGGER_RTT_printf(0, "\r\tSMC_PMPROT=0x%02x\t\t\tSMC_PMCTRL=0x%02x\t\tSCB->SCR=0x%02x\n", SMC_PMPROT, SMC_PMCTRL, SCB->SCR);
OSA_TimeDelay(gWarpMenuPrintDelayMilliseconds);
SEGGER_RTT_printf(0, "\r\tPMC_REGSC=0x%02x\t\t\tSIM_SCGC4=0x%02x\tRTC->TPR=0x%02x\n\n", PMC_REGSC, SIM_SCGC4, RTC->TPR);
OSA_TimeDelay(gWarpMenuPrintDelayMilliseconds);
SEGGER_RTT_printf(0, "\r\t%ds in RTC Handler to-date,\t%d Pmgr Errors\n", gWarpSleeptimeSeconds, powerManagerCallbackStructure.errorCount);
OSA_TimeDelay(gWarpMenuPrintDelayMilliseconds);
#else
SEGGER_RTT_WriteString(0, "\r\n\n\t\tWARNING: SEGGER_RTT_printf disabled in this firmware build.\n\t\tOnly showing output that does not require value formatting.\n\n");
OSA_TimeDelay(gWarpMenuPrintDelayMilliseconds);
#endif
SEGGER_RTT_WriteString(0, "\rSelect:\n");
OSA_TimeDelay(gWarpMenuPrintDelayMilliseconds);
SEGGER_RTT_WriteString(0, "\r- 'a': set default sensor.\n");
OSA_TimeDelay(gWarpMenuPrintDelayMilliseconds);
SEGGER_RTT_WriteString(0, "\r- 'b': set I2C baud rate.\n");
OSA_TimeDelay(gWarpMenuPrintDelayMilliseconds);
SEGGER_RTT_WriteString(0, "\r- 'c': set SPI baud rate.\n");
OSA_TimeDelay(gWarpMenuPrintDelayMilliseconds);
SEGGER_RTT_WriteString(0, "\r- 'd': set UART baud rate.\n");
OSA_TimeDelay(gWarpMenuPrintDelayMilliseconds);
SEGGER_RTT_WriteString(0, "\r- 'e': set default register address.\n");
OSA_TimeDelay(gWarpMenuPrintDelayMilliseconds);
SEGGER_RTT_WriteString(0, "\r- 'f': write byte to sensor.\n");
OSA_TimeDelay(gWarpMenuPrintDelayMilliseconds);
SEGGER_RTT_WriteString(0, "\r- 'g': set default SSSUPPLY.\n");
OSA_TimeDelay(gWarpMenuPrintDelayMilliseconds);
SEGGER_RTT_WriteString(0, "\r- 'h': powerdown command to all sensors.\n");
OSA_TimeDelay(gWarpMenuPrintDelayMilliseconds);
SEGGER_RTT_WriteString(0, "\r- 'i': set pull-up enable value.\n");
OSA_TimeDelay(gWarpMenuPrintDelayMilliseconds);
#ifdef WARP_BUILD_ENABLE_SEGGER_RTT_PRINTF
SEGGER_RTT_printf(0, "\r- 'j': repeat read reg 0x%02x on sensor #%d.\n", menuRegisterAddress, menuTargetSensor);
OSA_TimeDelay(gWarpMenuPrintDelayMilliseconds);
#endif
SEGGER_RTT_WriteString(0, "\r- 'k': sleep until reset.\n");
OSA_TimeDelay(gWarpMenuPrintDelayMilliseconds);
SEGGER_RTT_WriteString(0, "\r- 'l': send repeated byte on I2C.\n");
OSA_TimeDelay(gWarpMenuPrintDelayMilliseconds);
SEGGER_RTT_WriteString(0, "\r- 'm': send repeated byte on SPI.\n");
OSA_TimeDelay(gWarpMenuPrintDelayMilliseconds);
SEGGER_RTT_WriteString(0, "\r- 'n': enable SSSUPPLY.\n");
OSA_TimeDelay(gWarpMenuPrintDelayMilliseconds);
SEGGER_RTT_WriteString(0, "\r- 'o': disable SSSUPPLY.\n");
OSA_TimeDelay(gWarpMenuPrintDelayMilliseconds);
SEGGER_RTT_WriteString(0, "\r- 'p': switch to VLPR mode.\n");
OSA_TimeDelay(gWarpMenuPrintDelayMilliseconds);
#ifdef WARP_BUILD_ENABLE_DEVMAX11300
SEGGER_RTT_WriteString(0, "\r- 'q': MAX11300.\n");
OSA_TimeDelay(gWarpMenuPrintDelayMilliseconds);
#endif
SEGGER_RTT_WriteString(0, "\r- 'r': switch to RUN mode.\n");
OSA_TimeDelay(gWarpMenuPrintDelayMilliseconds);
SEGGER_RTT_WriteString(0, "\r- 's': power up all sensors.\n");
OSA_TimeDelay(gWarpMenuPrintDelayMilliseconds);
SEGGER_RTT_WriteString(0, "\r- 't': dump processor state.\n");
OSA_TimeDelay(gWarpMenuPrintDelayMilliseconds);
SEGGER_RTT_WriteString(0, "\r- 'u': set I2C address.\n");
OSA_TimeDelay(gWarpMenuPrintDelayMilliseconds);
#ifdef WARP_BUILD_ENABLE_DEVRV8803C7
SEGGER_RTT_WriteString(0, "\r- 'v': Enter VLLS0 low-power mode for 3s, then reset\n");
OSA_TimeDelay(gWarpMenuPrintDelayMilliseconds);
#endif
SEGGER_RTT_WriteString(0, "\r- 'x': disable SWD and spin for 10 secs.\n");
OSA_TimeDelay(gWarpMenuPrintDelayMilliseconds);
#ifdef WARP_BUILD_ENABLE_THERMALCHAMBERANALYSIS
SEGGER_RTT_WriteString(0, "\r- 'y': stress test (need a force quit)\n");
OSA_TimeDelay(gWarpMenuPrintDelayMilliseconds);
#endif
SEGGER_RTT_WriteString(0, "\r- 'z': dump all sensors data.\n");
OSA_TimeDelay(gWarpMenuPrintDelayMilliseconds);
/*************************************** INA219 *******************************************/
SEGGER_RTT_WriteString(0, "\r- '0': take measurements with INA219.\n");
OSA_TimeDelay(gWarpMenuPrintDelayMilliseconds);
/**********************************************************************************************/
SEGGER_RTT_WriteString(0, "\rEnter selection> ");
OSA_TimeDelay(gWarpMenuPrintDelayMilliseconds);
key = SEGGER_RTT_WaitKey();
switch (key)
{
/*
* Select sensor
*/
case '0':
{
enableI2Cpins(menuI2cPullupValue);
extern volatile uint32_t gWarpI2cBaudRateKbps;
extern volatile uint32_t gWarpI2cTimeoutMilliseconds;
extern volatile uint32_t gWarpSupplySettlingDelayMilliseconds;
uint8_t INA219_DEVICE_ADDR = (0x40);
uint8_t INA219_CONFIG_REG = (0x00);
uint8_t INA219_CALIB_REG = (0x05);
uint8_t INA219_CURRENT_REG = (0x04);
uint16_t calValue = 40960;
uint8_t currentMultiplier = 20; // to microAmps
uint16_t config = 0b10001000111;
// Write Configuration Register
uint8_t payloadByte[2];
uint8_t commandByte[1];
i2c_status_t status;
i2c_device_t slave =
{
.address = INA219_DEVICE_ADDR,
.baudRate_kbps = gWarpI2cBaudRateKbps
};
commandByte[0] = INA219_CONFIG_REG;
payloadByte[0] = (uint8_t)((config>>8) & 0xFF);
payloadByte[1] = (uint8_t)(config & 0xFF);
status = I2C_DRV_MasterSendDataBlocking(
0 ,
&slave,
commandByte,
1,
payloadByte,
2,
gWarpI2cTimeoutMilliseconds);
SEGGER_RTT_printf(0, "\n Configuration Successful,");
// Write Calibration Register
commandByte[0] = INA219_CALIB_REG;
payloadByte[0] = (uint8_t)((config>>8) & 0xFF);
payloadByte[1] = (uint8_t)(config & 0xFF);
status = I2C_DRV_MasterSendDataBlocking(
0 ,
&slave,
commandByte,
1,
payloadByte,
2,
gWarpI2cTimeoutMilliseconds);
SEGGER_RTT_printf(0, "\n Calibration Successful,");
// Read 1000 times from the Current Register
uint8_t cmdBuf[1] = {0xFF};
uint8_t payloadBuf[2];
cmdBuf[0] = INA219_CURRENT_REG;
uint8_t receivebuff[2];
for(int i = 0; i < 1000; i++)
{
status = I2C_DRV_MasterReceiveDataBlocking(
0 /* I2C peripheral instance */,
&slave,
cmdBuf,
1,
receivebuff,
2,
gWarpI2cTimeoutMilliseconds);
uint16_t readSensorRegisterValueCombined = ((payloadBuf[0] << 8) | (payloadBuf[1] & 0xFF));
readSensorRegisterValueCombined *= currentMultiplier;
SEGGER_RTT_printf(0, "\n %d,", receivebuff[1]<<8 & 0xFF | receivebuff[0]);
}
break;
}
case 'a':
{
SEGGER_RTT_WriteString(0, "\r\tSelect:\n");
#ifdef WARP_BUILD_ENABLE_DEVADXL362
SEGGER_RTT_WriteString(0, "\r\t- '1' ADXL362 (0x00--0x2D): 1.6V -- 3.5V\n");
#else
SEGGER_RTT_WriteString(0, "\r\t- '1' ADXL362 (0x00--0x2D): 1.6V -- 3.5V (compiled out) \n");
#endif
OSA_TimeDelay(gWarpMenuPrintDelayMilliseconds);
#ifdef WARP_BUILD_ENABLE_DEVBMX055
SEGGER_RTT_WriteString(0, "\r\t- '2' BMX055accel (0x00--0x3F): 2.4V -- 3.6V\n");
SEGGER_RTT_WriteString(0, "\r\t- '3' BMX055gyro (0x00--0x3F): 2.4V -- 3.6V\n");
SEGGER_RTT_WriteString(0, "\r\t- '4' BMX055mag (0x40--0x52): 2.4V -- 3.6V\n");
#else
SEGGER_RTT_WriteString(0, "\r\t- '2' BMX055accel (0x00--0x3F): 2.4V -- 3.6V (compiled out) \n");
SEGGER_RTT_WriteString(0, "\r\t- '3' BMX055gyro (0x00--0x3F): 2.4V -- 3.6V (compiled out) \n");
SEGGER_RTT_WriteString(0, "\r\t- '4' BMX055mag (0x40--0x52): 2.4V -- 3.6V (compiled out) \n");
#endif
OSA_TimeDelay(gWarpMenuPrintDelayMilliseconds);
#ifdef WARP_BUILD_ENABLE_DEVMMA8451Q
SEGGER_RTT_WriteString(0, "\r\t- '5' MMA8451Q (0x00--0x31): 1.95V -- 3.6V\n");
#else
SEGGER_RTT_WriteString(0, "\r\t- '5' MMA8451Q (0x00--0x31): 1.95V -- 3.6V (compiled out) \n");
#endif
OSA_TimeDelay(gWarpMenuPrintDelayMilliseconds);
#ifdef WARP_BUILD_ENABLE_DEVLPS25H
SEGGER_RTT_WriteString(0, "\r\t- '6' LPS25H (0x08--0x24): 1.7V -- 3.6V\n");
#else
SEGGER_RTT_WriteString(0, "\r\t- '6' LPS25H (0x08--0x24): 1.7V -- 3.6V (compiled out) \n");
#endif
OSA_TimeDelay(gWarpMenuPrintDelayMilliseconds);
#ifdef WARP_BUILD_ENABLE_DEVMAG3110
SEGGER_RTT_WriteString(0, "\r\t- '7' MAG3110 (0x00--0x11): 1.95V -- 3.6V\n");
#else
SEGGER_RTT_WriteString(0, "\r\t- '7' MAG3110 (0x00--0x11): 1.95V -- 3.6V (compiled out) \n");
#endif
OSA_TimeDelay(gWarpMenuPrintDelayMilliseconds);
#ifdef WARP_BUILD_ENABLE_DEVHDC1000
SEGGER_RTT_WriteString(0, "\r\t- '8' HDC1000 (0x00--0x1F): 3.0V -- 5.0V\n");
#else
SEGGER_RTT_WriteString(0, "\r\t- '8' HDC1000 (0x00--0x1F): 3.0V -- 5.0V (compiled out) \n");
#endif
OSA_TimeDelay(gWarpMenuPrintDelayMilliseconds);
#ifdef WARP_BUILD_ENABLE_DEVSI7021
SEGGER_RTT_WriteString(0, "\r\t- '9' SI7021 (0x00--0x0F): 1.9V -- 3.6V\n");
#else
SEGGER_RTT_WriteString(0, "\r\t- '9' SI7021 (0x00--0x0F): 1.9V -- 3.6V (compiled out) \n");
#endif
OSA_TimeDelay(gWarpMenuPrintDelayMilliseconds);
#ifdef WARP_BUILD_ENABLE_DEVL3GD20H
SEGGER_RTT_WriteString(0, "\r\t- 'a' L3GD20H (0x0F--0x39): 2.2V -- 3.6V\n");
#else
SEGGER_RTT_WriteString(0, "\r\t- 'a' L3GD20H (0x0F--0x39): 2.2V -- 3.6V (compiled out) \n");
#endif
OSA_TimeDelay(gWarpMenuPrintDelayMilliseconds);
#ifdef WARP_BUILD_ENABLE_DEVBME680
SEGGER_RTT_WriteString(0, "\r\t- 'b' BME680 (0xAA--0xF8): 1.6V -- 3.6V\n");
#else
SEGGER_RTT_WriteString(0, "\r\t- 'b' BME680 (0xAA--0xF8): 1.6V -- 3.6V (compiled out) \n");
#endif
OSA_TimeDelay(gWarpMenuPrintDelayMilliseconds);
#ifdef WARP_BUILD_ENABLE_DEVTCS34725
SEGGER_RTT_WriteString(0, "\r\t- 'd' TCS34725 (0x00--0x1D): 2.7V -- 3.3V\n");
#else
SEGGER_RTT_WriteString(0, "\r\t- 'd' TCS34725 (0x00--0x1D): 2.7V -- 3.3V (compiled out) \n");
#endif
OSA_TimeDelay(gWarpMenuPrintDelayMilliseconds);
#ifdef WARP_BUILD_ENABLE_DEVSI4705
SEGGER_RTT_WriteString(0, "\r\t- 'e' SI4705 (n/a): 2.7V -- 5.5V\n");
#else
SEGGER_RTT_WriteString(0, "\r\t- 'e' SI4705 (n/a): 2.7V -- 5.5V (compiled out) \n");
#endif
OSA_TimeDelay(gWarpMenuPrintDelayMilliseconds);
#ifdef WARP_BUILD_ENABLE_DEVPAN1326
SEGGER_RTT_WriteString(0, "\r\t- 'f' PAN1326 (n/a)\n");
#else
SEGGER_RTT_WriteString(0, "\r\t- 'f' PAN1326 (n/a) (compiled out) \n");
#endif
OSA_TimeDelay(gWarpMenuPrintDelayMilliseconds);
#ifdef WARP_BUILD_ENABLE_DEVCCS811
SEGGER_RTT_WriteString(0, "\r\t- 'g' CCS811 (0x00--0xFF): 1.8V -- 3.6V\n");
#else
SEGGER_RTT_WriteString(0, "\r\t- 'g' CCS811 (0x00--0xFF): 1.8V -- 3.6V (compiled out) \n");
#endif
OSA_TimeDelay(gWarpMenuPrintDelayMilliseconds);
#ifdef WARP_BUILD_ENABLE_DEVAMG8834
SEGGER_RTT_WriteString(0, "\r\t- 'h' AMG8834 (0x00--?): ?V -- ?V\n");
#else
SEGGER_RTT_WriteString(0, "\r\t- 'h' AMG8834 (0x00--?): ?V -- ?V (compiled out) \n");
#endif
OSA_TimeDelay(gWarpMenuPrintDelayMilliseconds);
#ifdef WARP_BUILD_ENABLE_DEVAS7262
SEGGER_RTT_WriteString(0, "\r\t- 'j' AS7262 (0x00--0x2B): 2.7V -- 3.6V\n");
#else
SEGGER_RTT_WriteString(0, "\r\t- 'j' AS7262 (0x00--0x2B): 2.7V -- 3.6V (compiled out) \n");
#endif
OSA_TimeDelay(gWarpMenuPrintDelayMilliseconds);
#ifdef WARP_BUILD_ENABLE_DEVAS7263
SEGGER_RTT_WriteString(0, "\r\t- 'k' AS7263 (0x00--0x2B): 2.7V -- 3.6V\n");
#else
SEGGER_RTT_WriteString(0, "\r\t- 'k' AS7263 (0x00--0x2B): 2.7V -- 3.6V (compiled out) \n");
#endif
OSA_TimeDelay(gWarpMenuPrintDelayMilliseconds);
SEGGER_RTT_WriteString(0, "\r\tEnter selection> ");
OSA_TimeDelay(gWarpMenuPrintDelayMilliseconds);
key = SEGGER_RTT_WaitKey();
switch(key)
{
#ifdef WARP_BUILD_ENABLE_DEVADXL362
case '1':
{
menuTargetSensor = kWarpSensorADXL362;
break;
}
#endif
#ifdef WARP_BUILD_ENABLE_DEVBMX055
case '2':
{
menuTargetSensor = kWarpSensorBMX055accel;
menuI2cDevice = &deviceBMX055accelState;
break;
}
#endif
#ifdef WARP_BUILD_ENABLE_DEVBMX055
case '3':
{
menuTargetSensor = kWarpSensorBMX055gyro;
menuI2cDevice = &deviceBMX055gyroState;
break;
}
#endif
#ifdef WARP_BUILD_ENABLE_DEVBMX055
case '4':
{
menuTargetSensor = kWarpSensorBMX055mag;
menuI2cDevice = &deviceBMX055magState;
break;
}
#endif
#ifdef WARP_BUILD_ENABLE_DEVMMA8451Q
case '5':
{
menuTargetSensor = kWarpSensorMMA8451Q;
menuI2cDevice = &deviceMMA8451QState;
break;
}
#endif
#ifdef WARP_BUILD_ENABLE_DEVLPS25H
case '6':
{
menuTargetSensor = kWarpSensorLPS25H;
menuI2cDevice = &deviceLPS25HState;
break;
}
#endif
#ifdef WARP_BUILD_ENABLE_DEVMAG3110
case '7':
{
menuTargetSensor = kWarpSensorMAG3110;
menuI2cDevice = &deviceMAG3110State;
break;
}
#endif
#ifdef WARP_BUILD_ENABLE_DEVHDC1000
case '8':
{
menuTargetSensor = kWarpSensorHDC1000;
menuI2cDevice = &deviceHDC1000State;
break;
}
#endif
#ifdef WARP_BUILD_ENABLE_DEVSI7021
case '9':
{
menuTargetSensor = kWarpSensorSI7021;
menuI2cDevice = &deviceSI7021State;
break;
}
#endif
#ifdef WARP_BUILD_ENABLE_DEVL3GD20H
case 'a':
{
menuTargetSensor = kWarpSensorL3GD20H;
menuI2cDevice = &deviceL3GD20HState;
break;
}
#endif
#ifdef WARP_BUILD_ENABLE_DEVBME680
case 'b':
{
menuTargetSensor = kWarpSensorBME680;
menuI2cDevice = &deviceBME680State;
break;
}
#endif
#ifdef WARP_BUILD_ENABLE_DEVTCS34725
case 'd':
{
menuTargetSensor = kWarpSensorTCS34725;
menuI2cDevice = &deviceTCS34725State;
break;
}
#endif
#ifdef WARP_BUILD_ENABLE_DEVSI4705
case 'e':
{
menuTargetSensor = kWarpSensorSI4705;
menuI2cDevice = &deviceSI4705State;
break;
}
#endif
#ifdef WARP_BUILD_ENABLE_DEVPAN1326
case 'f':
{
menuTargetSensor = kWarpSensorPAN1326;
break;
}
#endif
#ifdef WARP_BUILD_ENABLE_DEVCCS811
case 'g':
{
menuTargetSensor = kWarpSensorCCS811;
menuI2cDevice = &deviceCCS811State;
break;
}
#endif
#ifdef WARP_BUILD_ENABLE_DEVAMG8834
case 'h':
{
menuTargetSensor = kWarpSensorAMG8834;
menuI2cDevice = &deviceAMG8834State;
break;
}
#endif
#ifdef WARP_BUILD_ENABLE_DEVAS7262
case 'j':
{
menuTargetSensor = kWarpSensorAS7262;
menuI2cDevice = &deviceAS7262State;
break;
}
#endif
#ifdef WARP_BUILD_ENABLE_DEVAS7263
case 'k':
{
menuTargetSensor = kWarpSensorAS7263;
menuI2cDevice = &deviceAS7263State;
break;
}
#endif
default:
{
#ifdef WARP_BUILD_ENABLE_SEGGER_RTT_PRINTF
SEGGER_RTT_printf(0, "\r\tInvalid selection '%c' !\n", key);
#endif
}
}
break;
}
/*
* Change default I2C baud rate
*/
case 'b':
{
SEGGER_RTT_WriteString(0, "\r\n\tSet I2C baud rate in kbps (e.g., '0001')> ");
gWarpI2cBaudRateKbps = read4digits();
/*
* Round 9999kbps to 10Mbps
*/
if (gWarpI2cBaudRateKbps == 9999)
{
gWarpI2cBaudRateKbps = 10000;
}
#ifdef WARP_BUILD_ENABLE_SEGGER_RTT_PRINTF
SEGGER_RTT_printf(0, "\r\n\tI2C baud rate set to %d kb/s", gWarpI2cBaudRateKbps);
#endif
break;
}
/*
* Change default SPI baud rate
*/
case 'c':
{
SEGGER_RTT_WriteString(0, "\r\n\tSet SPI baud rate in kbps (e.g., '0001')> ");
gWarpSpiBaudRateKbps = read4digits();
/*
* Round 9999kbps to 10Mbps
*/
if (gWarpSpiBaudRateKbps == 9999)
{
gWarpSpiBaudRateKbps = 10000;
}
#ifdef WARP_BUILD_ENABLE_SEGGER_RTT_PRINTF
SEGGER_RTT_printf(0, "\r\n\tSPI baud rate: %d kb/s", gWarpSpiBaudRateKbps);
#endif
break;
}
/*
* Change default UART baud rate
*/
case 'd':
{
SEGGER_RTT_WriteString(0, "\r\n\tSet UART baud rate in kbps (e.g., '0001')> ");
gWarpUartBaudRateKbps = read4digits();
#ifdef WARP_BUILD_ENABLE_SEGGER_RTT_PRINTF
SEGGER_RTT_printf(0, "\r\n\tUART baud rate: %d kb/s", gWarpUartBaudRateKbps);
#endif
break;
}
/*
* Set register address for subsequent operations
*/
case 'e':
{
SEGGER_RTT_WriteString(0, "\r\n\tEnter 2-nybble register hex address (e.g., '3e')> ");
menuRegisterAddress = readHexByte();
#ifdef WARP_BUILD_ENABLE_SEGGER_RTT_PRINTF
SEGGER_RTT_printf(0, "\r\n\tEntered [0x%02x].\n\n", menuRegisterAddress);
#endif
break;
}
/*
* Write byte to sensor
*/
case 'f':
{
uint8_t i2cAddress, payloadByte[1], commandByte[1];
i2c_status_t i2cStatus;
WarpStatus status;
USED(status);
SEGGER_RTT_WriteString(0, "\r\n\tEnter I2C addr. (e.g., '0f') or '99' for SPI > ");
i2cAddress = readHexByte();
#ifdef WARP_BUILD_ENABLE_SEGGER_RTT_PRINTF
SEGGER_RTT_printf(0, "\r\n\tEntered [0x%02x].\n", i2cAddress);
#endif
SEGGER_RTT_WriteString(0, "\r\n\tEnter hex byte to send (e.g., '0f')> ");
payloadByte[0] = readHexByte();
#ifdef WARP_BUILD_ENABLE_SEGGER_RTT_PRINTF
SEGGER_RTT_printf(0, "\r\n\tEntered [0x%02x].\n", payloadByte[0]);
#endif
if (i2cAddress == 0x99)
{
#ifdef WARP_BUILD_ENABLE_DEVADXL362
#ifdef WARP_BUILD_ENABLE_SEGGER_RTT_PRINTF
SEGGER_RTT_printf(0, "\r\n\tWriting [0x%02x] to SPI register [0x%02x]...\n", payloadByte[0], menuRegisterAddress);
#endif
status = writeSensorRegisterADXL362( 0x0A /* command == write register */,
menuRegisterAddress,
payloadByte[0] /* writeValue */
);
if (status != kWarpStatusOK)
{
#ifdef WARP_BUILD_ENABLE_SEGGER_RTT_PRINTF
SEGGER_RTT_printf(0, "\r\n\tSPI write failed, error %d.\n\n", status);
#endif
}
#else
SEGGER_RTT_WriteString(0, "\r\n\tSPI write failed. ADXL362 Disabled");
#endif
}
else
{
i2c_device_t slave =
{
.address = i2cAddress,
.baudRate_kbps = gWarpI2cBaudRateKbps
};
enableSssupply(menuSupplyVoltage);
enableI2Cpins(menuI2cPullupValue);
commandByte[0] = menuRegisterAddress;
i2cStatus = I2C_DRV_MasterSendDataBlocking(
0 /* I2C instance */,
&slave,
commandByte,
1,
payloadByte,
1,
gWarpI2cTimeoutMilliseconds);
if (i2cStatus != kStatus_I2C_Success)
{
#ifdef WARP_BUILD_ENABLE_SEGGER_RTT_PRINTF
SEGGER_RTT_printf(0, "\r\n\tI2C write failed, error %d.\n\n", i2cStatus);
#endif
}
disableI2Cpins();
}
/*
* NOTE: do not disable the supply here, because we typically want to build on the effect of this register write command.
*/
break;
}
/*
* Configure default TPS82740 voltage
*/
case 'g':
{
SEGGER_RTT_WriteString(0, "\r\n\tOverride SSSUPPLY in mV (e.g., '1800')> ");
menuSupplyVoltage = read4digits();
#ifdef WARP_BUILD_ENABLE_SEGGER_RTT_PRINTF
SEGGER_RTT_printf(0, "\r\n\tOverride SSSUPPLY set to %d mV", menuSupplyVoltage);
#endif
break;
}
/*
* Activate low-power modes in all sensors.
*/
case 'h':
{
SEGGER_RTT_WriteString(0, "\r\n\tNOTE: First power sensors and enable I2C\n\n");
activateAllLowPowerSensorModes(true /* verbose */);
break;
}
/*
* Configure default pullup enable value
*/
case 'i':
{
SEGGER_RTT_WriteString(0, "\r\n\tDefault pullup enable value in kiloOhms (e.g., '0000')> ");
menuI2cPullupValue = read4digits();
#ifdef WARP_BUILD_ENABLE_SEGGER_RTT_PRINTF
SEGGER_RTT_printf(0, "\r\n\tI2cPullupValue set to %d\n", menuI2cPullupValue);
#endif
break;
}
/*
* Start repeated read
*/
case 'j':
{
bool autoIncrement, chatty;
int spinDelay, repetitionsPerAddress, chunkReadsPerAddress;
int adaptiveSssupplyMaxMillivolts;
uint8_t referenceByte;
#ifdef WARP_BUILD_ENABLE_SEGGER_RTT_PRINTF
SEGGER_RTT_printf(0, "\r\n\tAuto-increment from base address 0x%02x? ['0' | '1']> ", menuRegisterAddress);
#else
SEGGER_RTT_WriteString(0, "\r\n\tChunk reads per address (e.g., '1')> ");
#endif
autoIncrement = SEGGER_RTT_WaitKey() - '0';
SEGGER_RTT_WriteString(0, "\r\n\tChunk reads per address (e.g., '1')> ");
chunkReadsPerAddress = SEGGER_RTT_WaitKey() - '0';
SEGGER_RTT_WriteString(0, "\r\n\tChatty? ['0' | '1']> ");
chatty = SEGGER_RTT_WaitKey() - '0';
SEGGER_RTT_WriteString(0, "\r\n\tInter-operation spin delay in milliseconds (e.g., '0000')> ");
spinDelay = read4digits();
SEGGER_RTT_WriteString(0, "\r\n\tRepetitions per address (e.g., '0000')> ");
repetitionsPerAddress = read4digits();
SEGGER_RTT_WriteString(0, "\r\n\tMaximum voltage for adaptive supply (e.g., '0000')> ");
adaptiveSssupplyMaxMillivolts = read4digits();
SEGGER_RTT_WriteString(0, "\r\n\tReference byte for comparisons (e.g., '3e')> ");
referenceByte = readHexByte();
#ifdef WARP_BUILD_ENABLE_SEGGER_RTT_PRINTF
SEGGER_RTT_printf(0, "\r\n\tRepeating dev%d @ 0x%02x, reps=%d, pull=%d, delay=%dms:\n\n",
menuTargetSensor, menuRegisterAddress, repetitionsPerAddress, menuI2cPullupValue, spinDelay);
#endif
repeatRegisterReadForDeviceAndAddress( menuTargetSensor /*warpSensorDevice*/,
menuRegisterAddress /*baseAddress */,
menuI2cPullupValue,
autoIncrement /*autoIncrement*/,
chunkReadsPerAddress,
chatty,
spinDelay,
repetitionsPerAddress,
menuSupplyVoltage,
adaptiveSssupplyMaxMillivolts,
referenceByte
);
break;
}
/*
* Sleep for 30 seconds.
*/
case 'k':
{
SEGGER_RTT_WriteString(0, "\r\n\tSleeping until system reset...\n");
sleepUntilReset();
break;
}
/*
* Send repeated byte on I2C or SPI
*/
case 'l':
case 'm':
{
uint8_t outBuffer[1];
int repetitions;
SEGGER_RTT_WriteString(0, "\r\n\tNOTE: First power sensors and enable I2C\n\n");
SEGGER_RTT_WriteString(0, "\r\n\tByte to send (e.g., 'F0')> ");
outBuffer[0] = readHexByte();
SEGGER_RTT_WriteString(0, "\r\n\tRepetitions (e.g., '0000')> ");
repetitions = read4digits();
if (key == 'l')
{
#ifdef WARP_BUILD_ENABLE_SEGGER_RTT_PRINTF
SEGGER_RTT_printf(0, "\r\n\tSending %d repetitions of [0x%02x] on I2C, i2cPullupEnable=%d, SSSUPPLY=%dmV\n\n",
repetitions, outBuffer[0], menuI2cPullupValue, menuSupplyVoltage);
#endif
for (int i = 0; i < repetitions; i++)
{
writeByteToI2cDeviceRegister(0xFF, true /* sedCommandByte */, outBuffer[0] /* commandByte */, false /* sendPayloadByte */, 0 /* payloadByte */);
}
}
else
{
#ifdef WARP_BUILD_ENABLE_SEGGER_RTT_PRINTF
SEGGER_RTT_printf(0, "\r\n\tSending %d repetitions of [0x%02x] on SPI, SSSUPPLY=%dmV\n\n",
repetitions, outBuffer[0], menuSupplyVoltage);
#endif
for (int i = 0; i < repetitions; i++)
{
writeBytesToSpi(outBuffer /* payloadByte */, 1 /* payloadLength */);
}
}
break;
}
/*
* enable SSSUPPLY
*/
case 'n':
{
enableSssupply(menuSupplyVoltage);
break;
}
/*
* disable SSSUPPLY
*/
case 'o':
{
disableSssupply();
break;
}
/*
* Switch to VLPR
*/
case 'p':
{
warpSetLowPowerMode(kWarpPowerModeVLPR, 0 /* sleep seconds : irrelevant here */);
break;
}
#ifdef WARP_BUILD_ENABLE_DEVMAX11300
case 'q':
{
SEGGER_RTT_printf(0, "\r\tMAX11300 Configuration\n");
devMAX11300();
break;
}
#endif
/*
* Switch to RUN
*/
case 'r':
{
warpSetLowPowerMode(kWarpPowerModeRUN, 0 /* sleep seconds : irrelevant here */);
break;
}
/*
* Power up all sensors
*/
case 's':
{
SEGGER_RTT_WriteString(0, "\r\n\tNOTE: First power sensors and enable I2C\n\n");
powerupAllSensors();
break;
}
/*
* Dump processor state
*/
case 't':
{
dumpProcessorState();
break;
}
case 'u':
{
if (menuI2cDevice == NULL)
{
SEGGER_RTT_WriteString(0, "\r\n\tCannot set I2C address: First set the default I2C device.\n");
}
else
{
SEGGER_RTT_WriteString(0, "\r\n\tSet I2C address of the selected sensor(e.g., '1C')> ");
uint8_t address = readHexByte();
menuI2cDevice->i2cAddress = address;
}
break;
}
#ifdef WARP_BUILD_ENABLE_DEVRV8803C7
case 'v':
{
SEGGER_RTT_WriteString(0, "\r\n\tEnabling I2C pins\n");
enableI2Cpins(menuI2cPullupValue);
SEGGER_RTT_WriteString(0, "\r\n\tSleeping for 3 seconds, then resetting\n");
warpSetLowPowerMode(kWarpPowerModeVLLS0, 3 /* sleep seconds */);
SEGGER_RTT_WriteString(0, "\r\n\tThis should never happen...\n");
}
#endif
/*
* Simply spin for 10 seconds. Since the SWD pins should only be enabled when we are waiting for key at top of loop (or toggling after printf), during this time there should be no interference from the SWD.
*/
case 'x':
{
SEGGER_RTT_WriteString(0, "\r\n\tSpinning for 10 seconds...\n");
OSA_TimeDelay(10000);
SEGGER_RTT_WriteString(0, "\r\tDone.\n\n");
break;
}
/*
* Stress test, including bit-wise toggling and checksum, as well as extensive add and mul, with continous read and write to I2C MMA8451Q
*/
#ifdef WARP_BUILD_ENABLE_THERMALCHAMBERANALYSIS
case 'y':
{
/*
* I2C MMA8451Q initialization
*/
WarpStatus i2cWriteStatusA, i2cWriteStatusB;
WarpStatus i2cReadStatusX = kWarpStatusDeviceCommunicationFailed;
WarpStatus i2cReadStatusY = kWarpStatusDeviceCommunicationFailed;
WarpStatus i2cReadStatusZ = kWarpStatusDeviceCommunicationFailed;
enableI2Cpins(menuI2cPullupValue);
i2cWriteStatusA = writeSensorRegisterMMA8451Q(0x09 /* register address F_SETUP */,
0x00 /* payload: Disable FIFO */,
1);
i2cWriteStatusB = writeSensorRegisterMMA8451Q(0x2A /* register address */,
0x03 /* payload: Enable fast read 8bit, 800Hz, normal, active mode */,
1);
if((i2cWriteStatusA != kWarpStatusOK) && (i2cWriteStatusB != kWarpStatusOK))
{
SEGGER_RTT_printf(0, "\nError when writing to I2C device");
for(int errorLED = 0; errorLED < 5; errorLED++)
{
/*
* Error when writing to I2C device
* LED pattern : All On -> All off -> Red
*/
GPIO_DRV_ClearPinOutput(kWarpPinFRDMKL03LED_Red);
GPIO_DRV_ClearPinOutput(kWarpPinFRDMKL03LED_Blue);
GPIO_DRV_ClearPinOutput(kWarpPinFRDMKL03LED_Green);
OSA_TimeDelay(100);
GPIO_DRV_SetPinOutput(kWarpPinFRDMKL03LED_Red);
GPIO_DRV_SetPinOutput(kWarpPinFRDMKL03LED_Blue);
GPIO_DRV_SetPinOutput(kWarpPinFRDMKL03LED_Green);
OSA_TimeDelay(100);
GPIO_DRV_ClearPinOutput(kWarpPinFRDMKL03LED_Red);
OSA_TimeDelay(1000);
}
}
/*
* Fill up the remaining memory space using a fixed size array
* The size of this array is highly dependent on the firmware code size
*/
WarpThermalChamberKL03MemoryFill KL03MemoryFill;
KL03MemoryFill.outputBuffer[0] = 0;
KL03MemoryFill.outputBuffer[1] = 0;
KL03MemoryFill.outputBuffer[2] = 0;
GPIO_DRV_ClearPinOutput(kWarpPinFRDMKL03LED_Blue);
GPIO_DRV_SetPinOutput(kWarpPinFRDMKL03LED_Red);
GPIO_DRV_SetPinOutput(kWarpPinFRDMKL03LED_Green);
OSA_TimeDelay(1000);
GPIO_DRV_SetPinOutput(kWarpPinFRDMKL03LED_Blue);
OSA_TimeDelay(1000);
GPIO_DRV_ClearPinOutput(kWarpPinFRDMKL03LED_Blue);
OSA_TimeDelay(1000);
SEGGER_RTT_printf(0, "\n\nFilling memory");
for (uint16_t i = 0; i < sizeof(KL03MemoryFill.memoryFillingBuffer); i++)
{
if(i % 2 == 0)
{
KL03MemoryFill.memoryFillingBuffer[i] = kWarpThermalChamberMemoryFillEvenComponent;
}
if(i % 2 != 0)
{
KL03MemoryFill.memoryFillingBuffer[i] = kWarpThermalChamberMemoryFillOddComponent;
}
}
uint8_t checkSumValue = checkSum(KL03MemoryFill.memoryFillingBuffer,
sizeof(KL03MemoryFill.memoryFillingBuffer));
while (1)
{
/*
* (1) addAndMultiplicationLoop performs basic multiplication and addition
* (2) bit-wise toggling and checksum operations are performed
* (3) checking the I2C read and write status
*/
GPIO_DRV_ClearPinOutput(kWarpPinFRDMKL03LED_Green);
GPIO_DRV_SetPinOutput(kWarpPinFRDMKL03LED_Red);
GPIO_DRV_SetPinOutput(kWarpPinFRDMKL03LED_Blue);
OSA_TimeDelay(100);
addAndMultiplicationBusyLoop(kWarpThermalChamberBusyLoopCountOffset);
/*
* Error-less operation
* LED pattern : Blue -> Red -> Blue
*/
GPIO_DRV_ClearPinOutput(kWarpPinFRDMKL03LED_Blue);
GPIO_DRV_SetPinOutput(kWarpPinFRDMKL03LED_Red);
GPIO_DRV_SetPinOutput(kWarpPinFRDMKL03LED_Green);
OSA_TimeDelay(100);
GPIO_DRV_ClearPinOutput(kWarpPinFRDMKL03LED_Red);
GPIO_DRV_SetPinOutput(kWarpPinFRDMKL03LED_Blue);
GPIO_DRV_SetPinOutput(kWarpPinFRDMKL03LED_Green);
OSA_TimeDelay(100);
GPIO_DRV_ClearPinOutput(kWarpPinFRDMKL03LED_Blue);
GPIO_DRV_SetPinOutput(kWarpPinFRDMKL03LED_Red);
GPIO_DRV_SetPinOutput(kWarpPinFRDMKL03LED_Green);
OSA_TimeDelay(100);
for(uint16_t j = 0; j < sizeof(KL03MemoryFill.memoryFillingBuffer); j++)
{
KL03MemoryFill.memoryFillingBuffer[j] = ~KL03MemoryFill.memoryFillingBuffer[j];
}
SEGGER_RTT_printf(0, "\nBit-wise flip");
uint8_t checkSumValueOnline = checkSum(KL03MemoryFill.memoryFillingBuffer,
sizeof(KL03MemoryFill.memoryFillingBuffer));
if(checkSumValue == checkSumValueOnline)
{
i2cWriteStatusA = writeSensorRegisterMMA8451Q(0x09 /* register address F_SETUP */,
0x00 /* payload: Disable FIFO */,
1);
i2cWriteStatusB = writeSensorRegisterMMA8451Q(0x2A /* register address */,
0x03 /* payload: Enable fast read 8bit, 800Hz, normal, active mode */,
1);
SEGGER_RTT_printf(0, "\nWriting to I2C device");
if((i2cWriteStatusA != kWarpStatusOK) && (i2cWriteStatusB != kWarpStatusOK))
{
SEGGER_RTT_printf(0, "\nError when writing to I2C device");
for(int errorLED = 0; errorLED < 5; errorLED++)
{
/*
* Error when writing to I2C device
* LED pattern : All On -> All off -> Red
*/
GPIO_DRV_ClearPinOutput(kWarpPinFRDMKL03LED_Red);
GPIO_DRV_ClearPinOutput(kWarpPinFRDMKL03LED_Blue);
GPIO_DRV_ClearPinOutput(kWarpPinFRDMKL03LED_Green);
OSA_TimeDelay(100);
GPIO_DRV_SetPinOutput(kWarpPinFRDMKL03LED_Red);
GPIO_DRV_SetPinOutput(kWarpPinFRDMKL03LED_Blue);
GPIO_DRV_SetPinOutput(kWarpPinFRDMKL03LED_Green);
OSA_TimeDelay(100);
GPIO_DRV_ClearPinOutput(kWarpPinFRDMKL03LED_Red);
OSA_TimeDelay(1000);
}
}
i2cReadStatusX = readSensorRegisterMMA8451Q(0x01);
if(i2cReadStatusX == kWarpStatusOK)
{
KL03MemoryFill.outputBuffer[0] = deviceMMA8451QState.i2cBuffer[0];
SEGGER_RTT_printf(0, "\nReading from sensor X: %d", KL03MemoryFill.outputBuffer[0]);
i2cReadStatusY = readSensorRegisterMMA8451Q(0x03);
if(i2cReadStatusY == kWarpStatusOK)
{
KL03MemoryFill.outputBuffer[1] = deviceMMA8451QState.i2cBuffer[0];
SEGGER_RTT_printf(0, "\nReading from sensor Y: %d", KL03MemoryFill.outputBuffer[1]);
i2cReadStatusZ = readSensorRegisterMMA8451Q(0x05);
if(i2cReadStatusZ == kWarpStatusOK)
{
KL03MemoryFill.outputBuffer[2] = deviceMMA8451QState.i2cBuffer[0];
SEGGER_RTT_printf(0, "\nReading from sensor Z: %d", KL03MemoryFill.outputBuffer[2]);
}
}
}
if((i2cReadStatusX != kWarpStatusOK) && (i2cReadStatusY != kWarpStatusOK) &&
(i2cReadStatusZ != kWarpStatusOK))
{
SEGGER_RTT_printf(0, "\nError when reading from I2C device");
for(int errorLED = 0; errorLED < 5; errorLED++)
{
/*
* Error when reading from I2C device
* LED pattern : Red -> All off
*/
GPIO_DRV_ClearPinOutput(kWarpPinFRDMKL03LED_Red);
GPIO_DRV_ClearPinOutput(kWarpPinFRDMKL03LED_Blue);
GPIO_DRV_ClearPinOutput(kWarpPinFRDMKL03LED_Green);
OSA_TimeDelay(100);
GPIO_DRV_SetPinOutput(kWarpPinFRDMKL03LED_Red);
GPIO_DRV_SetPinOutput(kWarpPinFRDMKL03LED_Blue);
GPIO_DRV_SetPinOutput(kWarpPinFRDMKL03LED_Green);
OSA_TimeDelay(100);
}
}
else
{
KL03MemoryFill.outputBuffer[0] = 0;
KL03MemoryFill.outputBuffer[1] = 0;
KL03MemoryFill.outputBuffer[2] = 0;
}
}
else
{
while(1)
{
/*
* Error in checksum leading to error in bit wise operation
* LED pattern : Red -> All off
*/
SEGGER_RTT_printf(0, "\nError in checksum");
GPIO_DRV_ClearPinOutput(kWarpPinFRDMKL03LED_Red);
GPIO_DRV_SetPinOutput(kWarpPinFRDMKL03LED_Blue);
GPIO_DRV_SetPinOutput(kWarpPinFRDMKL03LED_Green);
OSA_TimeDelay(100);
GPIO_DRV_SetPinOutput(kWarpPinFRDMKL03LED_Red);
OSA_TimeDelay(100);
SEGGER_RTT_printf(0, "\nWriting to I2C device");
i2cWriteStatusA = writeSensorRegisterMMA8451Q(0x09 /* register address F_SETUP */,
0x00 /* payload: Disable FIFO */,
1);
i2cWriteStatusB = writeSensorRegisterMMA8451Q(0x2A /* register address */,
0x03 /* payload: Enable fast read 8bit, 800Hz, normal, active mode */,
1);
if((i2cWriteStatusA != kWarpStatusOK) && (i2cWriteStatusB != kWarpStatusOK))
{
SEGGER_RTT_printf(0, "\nError when writing to I2C device");
for(int errorLED = 0; errorLED < 5; errorLED++)
{
/*
* Error when writing to I2C device
* LED pattern : All On -> All off -> Red
*/
GPIO_DRV_ClearPinOutput(kWarpPinFRDMKL03LED_Red);
GPIO_DRV_ClearPinOutput(kWarpPinFRDMKL03LED_Blue);
GPIO_DRV_ClearPinOutput(kWarpPinFRDMKL03LED_Green);
OSA_TimeDelay(100);
GPIO_DRV_SetPinOutput(kWarpPinFRDMKL03LED_Red);
GPIO_DRV_SetPinOutput(kWarpPinFRDMKL03LED_Blue);
GPIO_DRV_SetPinOutput(kWarpPinFRDMKL03LED_Green);
OSA_TimeDelay(100);
GPIO_DRV_ClearPinOutput(kWarpPinFRDMKL03LED_Red);
OSA_TimeDelay(1000);
}
}
i2cReadStatusX = readSensorRegisterMMA8451Q(0x01);
if(i2cReadStatusX == kWarpStatusOK)
{
KL03MemoryFill.outputBuffer[0] = deviceMMA8451QState.i2cBuffer[0];
SEGGER_RTT_printf(0, "\nReading from sensor X: %d", KL03MemoryFill.outputBuffer[0]);
i2cReadStatusY = readSensorRegisterMMA8451Q(0x03);
if(i2cReadStatusY == kWarpStatusOK)
{
KL03MemoryFill.outputBuffer[1] = deviceMMA8451QState.i2cBuffer[0];
SEGGER_RTT_printf(0, "\nReading from sensor Y: %d", KL03MemoryFill.outputBuffer[1]);
i2cReadStatusZ = readSensorRegisterMMA8451Q(0x05);
if(i2cReadStatusZ == kWarpStatusOK)
{
KL03MemoryFill.outputBuffer[2] = deviceMMA8451QState.i2cBuffer[0];
SEGGER_RTT_printf(0, "\nReading from sensor Z: %d", KL03MemoryFill.outputBuffer[2]);
}
}
}
if((i2cReadStatusX != kWarpStatusOK) && (i2cReadStatusY != kWarpStatusOK) &&
(i2cReadStatusZ != kWarpStatusOK))
{
SEGGER_RTT_printf(0, "\nError when reading from I2C device");
for(int errorLED = 0; errorLED < 5; errorLED++)
{
/*
* Error when reading from I2C device
* LED pattern : All on -> All off
*/
GPIO_DRV_ClearPinOutput(kWarpPinFRDMKL03LED_Red);
GPIO_DRV_ClearPinOutput(kWarpPinFRDMKL03LED_Blue);
GPIO_DRV_ClearPinOutput(kWarpPinFRDMKL03LED_Green);
OSA_TimeDelay(100);
GPIO_DRV_SetPinOutput(kWarpPinFRDMKL03LED_Red);
GPIO_DRV_SetPinOutput(kWarpPinFRDMKL03LED_Blue);
GPIO_DRV_SetPinOutput(kWarpPinFRDMKL03LED_Green);
OSA_TimeDelay(100);
}
}
}
}
}
disableI2Cpins();
break;
}
#endif
/*
* Dump all the sensor data in one go
*/
case 'z':
{
bool hexModeFlag;
SEGGER_RTT_WriteString(0, "\r\n\tEnabling I2C pins...\n");
enableI2Cpins(menuI2cPullupValue);
SEGGER_RTT_WriteString(0, "\r\n\tHex or converted mode? ('h' or 'c')> ");
key = SEGGER_RTT_WaitKey();
hexModeFlag = (key == 'h' ? 1 : 0);
SEGGER_RTT_WriteString(0, "\r\n\tSet the time delay between each run in milliseconds (e.g., '1234')> ");
uint16_t menuDelayBetweenEachRun = read4digits();
SEGGER_RTT_printf(0, "\r\n\tDelay between read batches set to %d milliseconds.\n\n", menuDelayBetweenEachRun);
OSA_TimeDelay(gWarpMenuPrintDelayMilliseconds);
printAllSensors(true /* printHeadersAndCalibration */, hexModeFlag, menuDelayBetweenEachRun, menuI2cPullupValue);
/*
* Not reached (printAllSensors() does not return)
*/
disableI2Cpins();
break;
}
/*
* Ignore naked returns.
*/
case '\n':
{
SEGGER_RTT_WriteString(0, "\r\tPayloads make rockets more than just fireworks.");
break;
}
default:
{
#ifdef WARP_BUILD_ENABLE_SEGGER_RTT_PRINTF
SEGGER_RTT_printf(0, "\r\tInvalid selection '%c' !\n", key);
#endif
}
}
#endif
}
return 0;
}
void
printAllSensors(bool printHeadersAndCalibration, bool hexModeFlag, int menuDelayBetweenEachRun, int i2cPullupValue)
{
/*
* A 32-bit counter gives us > 2 years of before it wraps, even if sampling at 60fps
*/
uint32_t readingCount = 0;
uint32_t numberOfConfigErrors = 0;
#ifdef WARP_BUILD_ENABLE_DEVAMG8834
numberOfConfigErrors += configureSensorAMG8834( 0x3F,/* Initial reset */
0x01,/* Frame rate 1 FPS */
i2cPullupValue
);
#endif
#ifdef WARP_BUILD_ENABLE_DEVMMA8451Q
numberOfConfigErrors += configureSensorMMA8451Q(0x00,/* Payload: Disable FIFO */
0x01,/* Normal read 8bit, 800Hz, normal, active mode */
i2cPullupValue
);
#endif
#ifdef WARP_BUILD_ENABLE_DEVMAG3110
numberOfConfigErrors += configureSensorMAG3110( 0x00,/* Payload: DR 000, OS 00, 80Hz, ADC 1280, Full 16bit, standby mode to set up register*/
0xA0,/* Payload: AUTO_MRST_EN enable, RAW value without offset */
i2cPullupValue
);
#endif
#ifdef WARP_BUILD_ENABLE_DEVL3GD20H
numberOfConfigErrors += configureSensorL3GD20H( 0b11111111,/* ODR 800Hz, Cut-off 100Hz, see table 21, normal mode, x,y,z enable */
0b00100000,
0b00000000,/* normal mode, disable FIFO, disable high pass filter */
i2cPullupValue
);
#endif
#ifdef WARP_BUILD_ENABLE_DEVBME680
numberOfConfigErrors += configureSensorBME680( 0b00000001, /* Humidity oversampling (OSRS) to 1x */
0b00100100, /* Temperature oversample 1x, pressure overdsample 1x, mode 00 */
0b00001000, /* Turn off heater */
i2cPullupValue
);
if (printHeadersAndCalibration)
{
SEGGER_RTT_WriteString(0, "\r\n\nBME680 Calibration Data: ");
for (uint8_t i = 0; i < kWarpSizesBME680CalibrationValuesCount; i++)
{
#ifdef WARP_BUILD_ENABLE_SEGGER_RTT_PRINTF
SEGGER_RTT_printf(0, "0x%02x", deviceBME680CalibrationValues[i]);
if (i < kWarpSizesBME680CalibrationValuesCount - 1)
{
SEGGER_RTT_WriteString(0, ", ");
}
else
{
SEGGER_RTT_WriteString(0, "\n\n");
}
OSA_TimeDelay(gWarpMenuPrintDelayMilliseconds);
#endif
}
}
#endif
#ifdef WARP_BUILD_ENABLE_DEVHDC1000
numberOfConfigErrors += writeSensorRegisterHDC1000(kWarpSensorConfigurationRegisterHDC1000Configuration,/* Configuration register */
(0b1000000<<8),
i2cPullupValue
);
#endif
#ifdef WARP_BUILD_ENABLE_DEVCCS811
uint8_t payloadCCS811[1];
payloadCCS811[0] = 0b01000000;/* Constant power, measurement every 250ms */
numberOfConfigErrors += configureSensorCCS811(payloadCCS811,
i2cPullupValue
);
#endif
#ifdef WARP_BUILD_ENABLE_DEVBMX055
numberOfConfigErrors += configureSensorBMX055accel(0b00000011,/* Payload:+-2g range */
0b10000000,/* Payload:unfiltered data, shadowing enabled */
i2cPullupValue
);
numberOfConfigErrors += configureSensorBMX055mag(0b00000001,/* Payload:from suspend mode to sleep mode*/
0b00000001,/* Default 10Hz data rate, forced mode*/
i2cPullupValue
);
numberOfConfigErrors += configureSensorBMX055gyro(0b00000100,/* +- 125degrees/s */
0b00000000,/* ODR 2000 Hz, unfiltered */
0b00000000,/* normal mode */
0b10000000,/* unfiltered data, shadowing enabled */
i2cPullupValue
);
#endif
if (printHeadersAndCalibration)
{
SEGGER_RTT_WriteString(0, "Measurement number, RTC->TSR, RTC->TPR,");
OSA_TimeDelay(gWarpMenuPrintDelayMilliseconds);
#ifdef WARP_BUILD_ENABLE_DEVAMG8834
for (uint8_t i = 0; i < 64; i++)
{
#ifdef WARP_BUILD_ENABLE_SEGGER_RTT_PRINTF
SEGGER_RTT_printf(0, " AMG8834 %d,", i);
OSA_TimeDelay(gWarpMenuPrintDelayMilliseconds);
#endif
}
SEGGER_RTT_WriteString(0, " AMG8834 Temp,");
OSA_TimeDelay(gWarpMenuPrintDelayMilliseconds);
#endif
#ifdef WARP_BUILD_ENABLE_DEVMMA8451Q
SEGGER_RTT_WriteString(0, " MMA8451 x, MMA8451 y, MMA8451 z,");
OSA_TimeDelay(gWarpMenuPrintDelayMilliseconds);
#endif
#ifdef WARP_BUILD_ENABLE_DEVMAG3110
SEGGER_RTT_WriteString(0, " MAG3110 x, MAG3110 y, MAG3110 z, MAG3110 Temp,");
OSA_TimeDelay(gWarpMenuPrintDelayMilliseconds);
#endif
#ifdef WARP_BUILD_ENABLE_DEVL3GD20H
SEGGER_RTT_WriteString(0, " L3GD20H x, L3GD20H y, L3GD20H z, L3GD20H Temp,");
OSA_TimeDelay(gWarpMenuPrintDelayMilliseconds);
#endif
#ifdef WARP_BUILD_ENABLE_DEVBME680
SEGGER_RTT_WriteString(0, " BME680 Press, BME680 Temp, BME680 Hum,");
OSA_TimeDelay(gWarpMenuPrintDelayMilliseconds);
#endif
#ifdef WARP_BUILD_ENABLE_DEVBMX055
SEGGER_RTT_WriteString(0, " BMX055acc x, BMX055acc y, BMX055acc z, BMX055acc Temp,");
OSA_TimeDelay(gWarpMenuPrintDelayMilliseconds);
SEGGER_RTT_WriteString(0, " BMX055mag x, BMX055mag y, BMX055mag z, BMX055mag RHALL,");
OSA_TimeDelay(gWarpMenuPrintDelayMilliseconds);
SEGGER_RTT_WriteString(0, " BMX055gyro x, BMX055gyro y, BMX055gyro z,");
OSA_TimeDelay(gWarpMenuPrintDelayMilliseconds);
#endif
#ifdef WARP_BUILD_ENABLE_DEVCCS811
SEGGER_RTT_WriteString(0, " CCS811 ECO2, CCS811 TVOC, CCS811 RAW ADC value, CCS811 RAW R_REF value, CCS811 RAW R_NTC value,");
OSA_TimeDelay(gWarpMenuPrintDelayMilliseconds);
#endif
#ifdef WARP_BUILD_ENABLE_DEVHDC1000
SEGGER_RTT_WriteString(0, " HDC1000 Temp, HDC1000 Hum,");
OSA_TimeDelay(gWarpMenuPrintDelayMilliseconds);
#endif
SEGGER_RTT_WriteString(0, " RTC->TSR, RTC->TPR, # Config Errors");
OSA_TimeDelay(gWarpMenuPrintDelayMilliseconds);
SEGGER_RTT_WriteString(0, "\n\n");
OSA_TimeDelay(gWarpMenuPrintDelayMilliseconds);
}
while(1)
{
#ifdef WARP_BUILD_ENABLE_SEGGER_RTT_PRINTF
SEGGER_RTT_printf(0, "%u, %d, %d,", readingCount, RTC->TSR, RTC->TPR);
#endif
#ifdef WARP_BUILD_ENABLE_DEVAMG8834
printSensorDataAMG8834(hexModeFlag);
#endif
#ifdef WARP_BUILD_ENABLE_DEVMMA8451Q
printSensorDataMMA8451Q(hexModeFlag);
#endif
#ifdef WARP_BUILD_ENABLE_DEVMAG3110
printSensorDataMAG3110(hexModeFlag);
#endif
#ifdef WARP_BUILD_ENABLE_DEVL3GD20H
printSensorDataL3GD20H(hexModeFlag);
#endif
#ifdef WARP_BUILD_ENABLE_DEVBME680
printSensorDataBME680(hexModeFlag);
#endif
#ifdef WARP_BUILD_ENABLE_DEVBMX055
printSensorDataBMX055accel(hexModeFlag);
printSensorDataBMX055mag(hexModeFlag);
printSensorDataBMX055gyro(hexModeFlag);
#endif
#ifdef WARP_BUILD_ENABLE_DEVCCS811
printSensorDataCCS811(hexModeFlag);
#endif
#ifdef WARP_BUILD_ENABLE_DEVHDC1000
printSensorDataHDC1000(hexModeFlag);
#endif
#ifdef WARP_BUILD_ENABLE_SEGGER_RTT_PRINTF
SEGGER_RTT_printf(0, " %d, %d, %d\n", RTC->TSR, RTC->TPR, numberOfConfigErrors);
#endif
if (menuDelayBetweenEachRun > 0)
{
OSA_TimeDelay(menuDelayBetweenEachRun);
}
readingCount++;
}
}
void
loopForSensor( const char * tagString,
WarpStatus (* readSensorRegisterFunction)(uint8_t deviceRegister, int numberOfBytes),
volatile WarpI2CDeviceState * i2cDeviceState,
volatile WarpSPIDeviceState * spiDeviceState,
uint8_t baseAddress,
uint8_t minAddress,
uint8_t maxAddress,
int repetitionsPerAddress,
int chunkReadsPerAddress,
int spinDelay,
bool autoIncrement,
uint16_t sssupplyMillivolts,
uint8_t referenceByte,
uint16_t adaptiveSssupplyMaxMillivolts,
bool chatty
)
{
WarpStatus status;
uint8_t address;
if((minAddress < baseAddress) || (baseAddress <= maxAddress))
{
address = baseAddress;
}
else
{
address = minAddress;
}
int readCount = repetitionsPerAddress + 1;
int nSuccesses = 0;
int nFailures = 0;
int nCorrects = 0;
int nBadCommands = 0;
uint16_t actualSssupplyMillivolts = sssupplyMillivolts;
if ( (!spiDeviceState && !i2cDeviceState) ||
(spiDeviceState && i2cDeviceState) )
{
#ifdef WARP_BUILD_ENABLE_SEGGER_RTT_PRINTF
SEGGER_RTT_printf(0, RTT_CTRL_RESET RTT_CTRL_BG_BRIGHT_YELLOW RTT_CTRL_TEXT_BRIGHT_WHITE kWarpConstantStringErrorSanity RTT_CTRL_RESET "\n");
#endif
}
enableSssupply(actualSssupplyMillivolts);
SEGGER_RTT_WriteString(0, tagString);
/*
* Keep on repeating until we are above the maxAddress, or just once if not autoIncrement-ing
* This is checked for at the tail end of the loop.
*/
while (true)
{
for (int i = 0; i < readCount; i++) for (int j = 0; j < chunkReadsPerAddress; j++)
{
status = readSensorRegisterFunction(address+j, 1 /* numberOfBytes */);
if (status == kWarpStatusOK)
{
nSuccesses++;
if (actualSssupplyMillivolts > sssupplyMillivolts)
{
actualSssupplyMillivolts -= 100;
enableSssupply(actualSssupplyMillivolts);
}
if (spiDeviceState)
{
if (referenceByte == spiDeviceState->spiSinkBuffer[2])
{
nCorrects++;
}
if (chatty)
{
#ifdef WARP_BUILD_ENABLE_SEGGER_RTT_PRINTF
SEGGER_RTT_printf(0, "\r\t0x%02x --> [0x%02x 0x%02x 0x%02x]\n",
address+j,
spiDeviceState->spiSinkBuffer[0],
spiDeviceState->spiSinkBuffer[1],
spiDeviceState->spiSinkBuffer[2]);
#endif
}
}
else
{
if (referenceByte == i2cDeviceState->i2cBuffer[0])
{
nCorrects++;
}
if (chatty)
{
#ifdef WARP_BUILD_ENABLE_SEGGER_RTT_PRINTF
SEGGER_RTT_printf(0, "\r\t0x%02x --> 0x%02x\n",
address+j,
i2cDeviceState->i2cBuffer[0]);
#endif
}
}
}
else if (status == kWarpStatusDeviceCommunicationFailed)
{
#ifdef WARP_BUILD_ENABLE_SEGGER_RTT_PRINTF
SEGGER_RTT_printf(0, "\r\t0x%02x --> ----\n",
address+j);
#endif
nFailures++;
if (actualSssupplyMillivolts < adaptiveSssupplyMaxMillivolts)
{
actualSssupplyMillivolts += 100;
enableSssupply(actualSssupplyMillivolts);
}
}
else if (status == kWarpStatusBadDeviceCommand)
{
nBadCommands++;
}
if (spinDelay > 0)
{
OSA_TimeDelay(spinDelay);
}
}
if (autoIncrement)
{
address++;
}
if (address > maxAddress || !autoIncrement)
{
/*
* We either iterated over all possible addresses, or were asked to do only
* one address anyway (i.e. don't increment), so we're done.
*/
break;
}
}
/*
* We intersperse RTT_printfs with forced delays to allow us to use small
* print buffers even in RUN mode.
*/
#ifdef WARP_BUILD_ENABLE_SEGGER_RTT_PRINTF
SEGGER_RTT_printf(0, "\r\n\t%d/%d success rate.\n", nSuccesses, (nSuccesses + nFailures));
OSA_TimeDelay(50);
SEGGER_RTT_printf(0, "\r\t%d/%d successes matched ref. value of 0x%02x.\n", nCorrects, nSuccesses, referenceByte);
OSA_TimeDelay(50);
SEGGER_RTT_printf(0, "\r\t%d bad commands.\n\n", nBadCommands);
OSA_TimeDelay(50);
#endif
return;
}
void
repeatRegisterReadForDeviceAndAddress(WarpSensorDevice warpSensorDevice, uint8_t baseAddress, uint8_t pullupValue, bool autoIncrement, int chunkReadsPerAddress, bool chatty, int spinDelay, int repetitionsPerAddress, uint16_t sssupplyMillivolts, uint16_t adaptiveSssupplyMaxMillivolts, uint8_t referenceByte)
{
if (warpSensorDevice != kWarpSensorADXL362)
{
enableI2Cpins(pullupValue);
}
switch (warpSensorDevice)
{
case kWarpSensorADXL362:
{
/*
* ADXL362: VDD 1.6--3.5
*/
#ifdef WARP_BUILD_ENABLE_DEVADXL362
loopForSensor( "\r\nADXL362:\n\r", /* tagString */
&readSensorRegisterADXL362, /* readSensorRegisterFunction */
NULL, /* i2cDeviceState */
&deviceADXL362State, /* spiDeviceState */
baseAddress, /* baseAddress */
0x00, /* minAddress */
0x2E, /* maxAddress */
repetitionsPerAddress, /* repetitionsPerAddress */
chunkReadsPerAddress, /* chunkReadsPerAddress */
spinDelay, /* spinDelay */
autoIncrement, /* autoIncrement */
sssupplyMillivolts, /* sssupplyMillivolts */
referenceByte, /* referenceByte */
adaptiveSssupplyMaxMillivolts, /* adaptiveSssupplyMaxMillivolts */
chatty /* chatty */
);
#else
SEGGER_RTT_WriteString(0, "\r\n\tADXL362 Read Aborted. Device Disabled :(");
#endif
break;
}
case kWarpSensorMMA8451Q:
{
/*
* MMA8451Q: VDD 1.95--3.6
*/
#ifdef WARP_BUILD_ENABLE_DEVMMA8451Q
loopForSensor( "\r\nMMA8451Q:\n\r", /* tagString */
&readSensorRegisterMMA8451Q, /* readSensorRegisterFunction */
&deviceMMA8451QState, /* i2cDeviceState */
NULL, /* spiDeviceState */
baseAddress, /* baseAddress */
0x00, /* minAddress */
0x31, /* maxAddress */
repetitionsPerAddress, /* repetitionsPerAddress */
chunkReadsPerAddress, /* chunkReadsPerAddress */
spinDelay, /* spinDelay */
autoIncrement, /* autoIncrement */
sssupplyMillivolts, /* sssupplyMillivolts */
referenceByte, /* referenceByte */
adaptiveSssupplyMaxMillivolts, /* adaptiveSssupplyMaxMillivolts */
chatty /* chatty */
);
#else
SEGGER_RTT_WriteString(0, "\r\n\tMMA8451Q Read Aborted. Device Disabled :(");
#endif
break;
}
case kWarpSensorBME680:
{
/*
* BME680: VDD 1.7--3.6
*/
#ifdef WARP_BUILD_ENABLE_DEVBME680
loopForSensor( "\r\nBME680:\n\r", /* tagString */
&readSensorRegisterBME680, /* readSensorRegisterFunction */
&deviceBME680State, /* i2cDeviceState */
NULL, /* spiDeviceState */
baseAddress, /* baseAddress */
0x1D, /* minAddress */
0x75, /* maxAddress */
repetitionsPerAddress, /* repetitionsPerAddress */
chunkReadsPerAddress, /* chunkReadsPerAddress */
spinDelay, /* spinDelay */
autoIncrement, /* autoIncrement */
sssupplyMillivolts, /* sssupplyMillivolts */
referenceByte, /* referenceByte */
adaptiveSssupplyMaxMillivolts, /* adaptiveSssupplyMaxMillivolts */
chatty /* chatty */
);
#else
SEGGER_RTT_WriteString(0, "\r\n\nBME680 Read Aborted. Device Disabled :(");
#endif
break;
}
case kWarpSensorBMX055accel:
{
/*
* BMX055accel: VDD 2.4V -- 3.6V
*/
#ifdef WARP_BUILD_ENABLE_DEVBMX055
loopForSensor( "\r\nBMX055accel:\n\r", /* tagString */
&readSensorRegisterBMX055accel, /* readSensorRegisterFunction */
&deviceBMX055accelState, /* i2cDeviceState */
NULL, /* spiDeviceState */
baseAddress, /* baseAddress */
0x00, /* minAddress */
0x39, /* maxAddress */
repetitionsPerAddress, /* repetitionsPerAddress */
chunkReadsPerAddress, /* chunkReadsPerAddress */
spinDelay, /* spinDelay */
autoIncrement, /* autoIncrement */
sssupplyMillivolts, /* sssupplyMillivolts */
referenceByte, /* referenceByte */
adaptiveSssupplyMaxMillivolts, /* adaptiveSssupplyMaxMillivolts */
chatty /* chatty */
);
#else
SEGGER_RTT_WriteString(0, "\r\n\tBMX055accel Read Aborted. Device Disabled :( ");
#endif
break;
}
case kWarpSensorBMX055gyro:
{
/*
* BMX055gyro: VDD 2.4V -- 3.6V
*/
#ifdef WARP_BUILD_ENABLE_DEVBMX055
loopForSensor( "\r\nBMX055gyro:\n\r", /* tagString */
&readSensorRegisterBMX055gyro, /* readSensorRegisterFunction */
&deviceBMX055gyroState, /* i2cDeviceState */
NULL, /* spiDeviceState */
baseAddress, /* baseAddress */
0x00, /* minAddress */
0x39, /* maxAddress */
repetitionsPerAddress, /* repetitionsPerAddress */
chunkReadsPerAddress, /* chunkReadsPerAddress */
spinDelay, /* spinDelay */
autoIncrement, /* autoIncrement */
sssupplyMillivolts, /* sssupplyMillivolts */
referenceByte, /* referenceByte */
adaptiveSssupplyMaxMillivolts, /* adaptiveSssupplyMaxMillivolts */
chatty /* chatty */
);
#else
SEGGER_RTT_WriteString(0, "\r\n\tBMX055gyro Read Aborted. Device Disabled :( ");
#endif
break;
}
case kWarpSensorBMX055mag:
{
/*
* BMX055mag: VDD 2.4V -- 3.6V
*/
#ifdef WARP_BUILD_ENABLE_DEVBMX055
loopForSensor( "\r\nBMX055mag:\n\r", /* tagString */
&readSensorRegisterBMX055mag, /* readSensorRegisterFunction */
&deviceBMX055magState, /* i2cDeviceState */
NULL, /* spiDeviceState */
baseAddress, /* baseAddress */
0x40, /* minAddress */
0x52, /* maxAddress */
repetitionsPerAddress, /* repetitionsPerAddress */
chunkReadsPerAddress, /* chunkReadsPerAddress */
spinDelay, /* spinDelay */
autoIncrement, /* autoIncrement */
sssupplyMillivolts, /* sssupplyMillivolts */
referenceByte, /* referenceByte */
adaptiveSssupplyMaxMillivolts, /* adaptiveSssupplyMaxMillivolts */
chatty /* chatty */
);
#else
SEGGER_RTT_WriteString(0, "\r\n\t BMX055mag Read Aborted. Device Disabled :( ");
#endif
break;
}
case kWarpSensorMAG3110:
{
/*
* MAG3110: VDD 1.95 -- 3.6
*/
#ifdef WARP_BUILD_ENABLE_DEVMAG3110
loopForSensor( "\r\nMAG3110:\n\r", /* tagString */
&readSensorRegisterMAG3110, /* readSensorRegisterFunction */
&deviceMAG3110State, /* i2cDeviceState */
NULL, /* spiDeviceState */
baseAddress, /* baseAddress */
0x00, /* minAddress */
0x11, /* maxAddress */
repetitionsPerAddress, /* repetitionsPerAddress */
chunkReadsPerAddress, /* chunkReadsPerAddress */
spinDelay, /* spinDelay */
autoIncrement, /* autoIncrement */
sssupplyMillivolts, /* sssupplyMillivolts */
referenceByte, /* referenceByte */
adaptiveSssupplyMaxMillivolts, /* adaptiveSssupplyMaxMillivolts */
chatty /* chatty */
);
#else
SEGGER_RTT_WriteString(0, "\r\n\tMAG3110 Read Aborted. Device Disabled :( ");
#endif
break;
}
case kWarpSensorL3GD20H:
{
/*
* L3GD20H: VDD 2.2V -- 3.6V
*/
#ifdef WARP_BUILD_ENABLE_DEVL3GD20H
loopForSensor( "\r\nL3GD20H:\n\r", /* tagString */
&readSensorRegisterL3GD20H, /* readSensorRegisterFunction */
&deviceL3GD20HState, /* i2cDeviceState */
NULL, /* spiDeviceState */
baseAddress, /* baseAddress */
0x0F, /* minAddress */
0x39, /* maxAddress */
repetitionsPerAddress, /* repetitionsPerAddress */
chunkReadsPerAddress, /* chunkReadsPerAddress */
spinDelay, /* spinDelay */
autoIncrement, /* autoIncrement */
sssupplyMillivolts, /* sssupplyMillivolts */
referenceByte, /* referenceByte */
adaptiveSssupplyMaxMillivolts, /* adaptiveSssupplyMaxMillivolts */
chatty /* chatty */
);
#else
SEGGER_RTT_WriteString(0, "\r\n\tL3GD20H Read Aborted. Device Disabled :( ");
#endif
break;
}
case kWarpSensorLPS25H:
{
/*
* LPS25H: VDD 1.7V -- 3.6V
*/
#ifdef WARP_BUILD_ENABLE_DEVLPS25H
loopForSensor( "\r\nLPS25H:\n\r", /* tagString */
&readSensorRegisterLPS25H, /* readSensorRegisterFunction */
&deviceLPS25HState, /* i2cDeviceState */
NULL, /* spiDeviceState */
baseAddress, /* baseAddress */
0x08, /* minAddress */
0x24, /* maxAddress */
repetitionsPerAddress, /* repetitionsPerAddress */
chunkReadsPerAddress, /* chunkReadsPerAddress */
spinDelay, /* spinDelay */
autoIncrement, /* autoIncrement */
sssupplyMillivolts, /* sssupplyMillivolts */
referenceByte, /* referenceByte */
adaptiveSssupplyMaxMillivolts, /* adaptiveSssupplyMaxMillivolts */
chatty /* chatty */
);
#else
SEGGER_RTT_WriteString(0, "\r\n\tLPS25H Read Aborted. Device Disabled :( ");
#endif
break;
}
case kWarpSensorTCS34725:
{
/*
* TCS34725: VDD 2.7V -- 3.3V
*/
#ifdef WARP_BUILD_ENABLE_DEVTCS34725
loopForSensor( "\r\nTCS34725:\n\r", /* tagString */
&readSensorRegisterTCS34725, /* readSensorRegisterFunction */
&deviceTCS34725State, /* i2cDeviceState */
NULL, /* spiDeviceState */
baseAddress, /* baseAddress */
0x00, /* minAddress */
0x1D, /* maxAddress */
repetitionsPerAddress, /* repetitionsPerAddress */
chunkReadsPerAddress, /* chunkReadsPerAddress */
spinDelay, /* spinDelay */
autoIncrement, /* autoIncrement */
sssupplyMillivolts, /* sssupplyMillivolts */
referenceByte, /* referenceByte */
adaptiveSssupplyMaxMillivolts, /* adaptiveSssupplyMaxMillivolts */
chatty /* chatty */
);
#else
SEGGER_RTT_WriteString(0, "\r\n\tTCS34725 Read Aborted. Device Disabled :( ");
#endif
break;
}
case kWarpSensorSI4705:
{
/*
* SI4705: VDD 2.7V -- 5.5V
*/
#ifdef WARP_BUILD_ENABLE_DEVSI4705
loopForSensor( "\r\nSI4705:\n\r", /* tagString */
&readSensorRegisterSI4705, /* readSensorRegisterFunction */
&deviceSI4705State, /* i2cDeviceState */
NULL, /* spiDeviceState */
baseAddress, /* baseAddress */
0x00, /* minAddress */
0x09, /* maxAddress */
repetitionsPerAddress, /* repetitionsPerAddress */
chunkReadsPerAddress, /* chunkReadsPerAddress */
spinDelay, /* spinDelay */
autoIncrement, /* autoIncrement */
sssupplyMillivolts, /* sssupplyMillivolts */
referenceByte, /* referenceByte */
adaptiveSssupplyMaxMillivolts, /* adaptiveSssupplyMaxMillivolts */
chatty /* chatty */
);
#else
SEGGER_RTT_WriteString(0, "\r\n\tSI4705 Read Aborted. Device Disabled :( ");
#endif
break;
}
case kWarpSensorHDC1000:
{
/*
* HDC1000: VDD 3V--5V
*/
#ifdef WARP_BUILD_ENABLE_DEVHDC1000
loopForSensor( "\r\nHDC1000:\n\r", /* tagString */
&readSensorRegisterHDC1000, /* readSensorRegisterFunction */
&deviceHDC1000State, /* i2cDeviceState */
NULL, /* spiDeviceState */
baseAddress, /* baseAddress */
0x00, /* minAddress */
0x1F, /* maxAddress */
repetitionsPerAddress, /* repetitionsPerAddress */
chunkReadsPerAddress, /* chunkReadsPerAddress */
spinDelay, /* spinDelay */
autoIncrement, /* autoIncrement */
sssupplyMillivolts, /* sssupplyMillivolts */
referenceByte, /* referenceByte */
adaptiveSssupplyMaxMillivolts, /* adaptiveSssupplyMaxMillivolts */
chatty /* chatty */
);
#else
SEGGER_RTT_WriteString(0, "\r\n\tHDC1000 Read Aborted. Device Disabled :( ");
#endif
break;
}
case kWarpSensorSI7021:
{
/*
* SI7021: VDD 1.9V -- 3.6V
*/
#ifdef WARP_BUILD_ENABLE_DEVSI7021
loopForSensor( "\r\nSI7021:\n\r", /* tagString */
&readSensorRegisterSI7021, /* readSensorRegisterFunction */
&deviceSI7021State, /* i2cDeviceState */
NULL, /* spiDeviceState */
baseAddress, /* baseAddress */
0x00, /* minAddress */
0x09, /* maxAddress */
repetitionsPerAddress, /* repetitionsPerAddress */
chunkReadsPerAddress, /* chunkReadsPerAddress */
spinDelay, /* spinDelay */
autoIncrement, /* autoIncrement */
sssupplyMillivolts, /* sssupplyMillivolts */
referenceByte, /* referenceByte */
adaptiveSssupplyMaxMillivolts, /* adaptiveSssupplyMaxMillivolts */
chatty /* chatty */
);
#else
SEGGER_RTT_WriteString(0, "\r\n\tSI7021 Read Aborted. Device Disabled :( ");
#endif
break;
}
case kWarpSensorCCS811:
{
/*
* CCS811: VDD 1.8V -- 3.6V
*/
#ifdef WARP_BUILD_ENABLE_DEVCCS811
loopForSensor( "\r\nCCS811:\n\r", /* tagString */
&readSensorRegisterCCS811, /* readSensorRegisterFunction */
&deviceCCS811State, /* i2cDeviceState */
NULL, /* spiDeviceState */
baseAddress, /* baseAddress */
0x00, /* minAddress */
0xFF, /* maxAddress */
repetitionsPerAddress, /* repetitionsPerAddress */
chunkReadsPerAddress, /* chunkReadsPerAddress */
spinDelay, /* spinDelay */
autoIncrement, /* autoIncrement */
sssupplyMillivolts, /* sssupplyMillivolts */
referenceByte, /* referenceByte */
adaptiveSssupplyMaxMillivolts, /* adaptiveSssupplyMaxMillivolts */
chatty /* chatty */
);
#else
SEGGER_RTT_WriteString(0, "\r\n\tCCS811 Read Aborted. Device Disabled :( ");
#endif
break;
}
case kWarpSensorAMG8834:
{
/*
* AMG8834: VDD ?V -- ?V
*/
#ifdef WARP_BUILD_ENABLE_DEVAMG8834
loopForSensor( "\r\nAMG8834:\n\r", /* tagString */
&readSensorRegisterAMG8834, /* readSensorRegisterFunction */
&deviceAMG8834State, /* i2cDeviceState */
NULL, /* spiDeviceState */
baseAddress, /* baseAddress */
0x00, /* minAddress */
0xFF, /* maxAddress */
repetitionsPerAddress, /* repetitionsPerAddress */
chunkReadsPerAddress, /* chunkReadsPerAddress */
spinDelay, /* spinDelay */
autoIncrement, /* autoIncrement */
sssupplyMillivolts, /* sssupplyMillivolts */
referenceByte, /* referenceByte */
adaptiveSssupplyMaxMillivolts, /* adaptiveSssupplyMaxMillivolts */
chatty /* chatty */
);
#else
SEGGER_RTT_WriteString(0, "\r\n\tAMG8834 Read Aborted. Device Disabled :( ");
#endif
break;
}
case kWarpSensorAS7262:
{
/*
* AS7262: VDD 2.7--3.6
*/
#ifdef WARP_BUILD_ENABLE_DEVAS7262
loopForSensor( "\r\nAS7262:\n\r", /* tagString */
&readSensorRegisterAS7262, /* readSensorRegisterFunction */
&deviceAS7262State, /* i2cDeviceState */
NULL, /* spiDeviceState */
baseAddress, /* baseAddress */
0x00, /* minAddress */
0x2B, /* maxAddress */
repetitionsPerAddress, /* repetitionsPerAddress */
chunkReadsPerAddress, /* chunkReadsPerAddress */
spinDelay, /* spinDelay */
autoIncrement, /* autoIncrement */
sssupplyMillivolts, /* sssupplyMillivolts */
referenceByte, /* referenceByte */
adaptiveSssupplyMaxMillivolts, /* adaptiveSssupplyMaxMillivolts */
chatty /* chatty */
);
#else
SEGGER_RTT_WriteString(0, "\r\n\tAS7262 Read Aborted. Device Disabled :( ");
#endif
break;
}
case kWarpSensorAS7263:
{
/*
* AS7263: VDD 2.7--3.6
*/
#ifdef WARP_BUILD_ENABLE_DEVAS7263
loopForSensor( "\r\nAS7263:\n\r", /* tagString */
&readSensorRegisterAS7263, /* readSensorRegisterFunction */
&deviceAS7263State, /* i2cDeviceState */
NULL, /* spiDeviceState */
baseAddress, /* baseAddress */
0x00, /* minAddress */
0x2B, /* maxAddress */
repetitionsPerAddress, /* repetitionsPerAddress */
chunkReadsPerAddress, /* chunkReadsPerAddress */
spinDelay, /* spinDelay */
autoIncrement, /* autoIncrement */
sssupplyMillivolts, /* sssupplyMillivolts */
referenceByte, /* referenceByte */
adaptiveSssupplyMaxMillivolts, /* adaptiveSssupplyMaxMillivolts */
chatty /* chatty */
);
#else
SEGGER_RTT_WriteString(0, "\r\n\tAS7263 Read Aborted. Device Disabled :( ");
#endif
break;
}
default:
{
#ifdef WARP_BUILD_ENABLE_SEGGER_RTT_PRINTF
SEGGER_RTT_printf(0, "\r\tInvalid warpSensorDevice [%d] passed to repeatRegisterReadForDeviceAndAddress.\n", warpSensorDevice);
#endif
}
}
if (warpSensorDevice != kWarpSensorADXL362)
{
disableI2Cpins();
}
}
int
char2int(int character)
{
if (character >= '0' && character <= '9')
{
return character - '0';
}
if (character >= 'a' && character <= 'f')
{
return character - 'a' + 10;
}
if (character >= 'A' && character <= 'F')
{
return character - 'A' + 10;
}
return 0;
}
uint8_t
readHexByte(void)
{
uint8_t topNybble, bottomNybble;
topNybble = SEGGER_RTT_WaitKey();
bottomNybble = SEGGER_RTT_WaitKey();
return (char2int(topNybble) << 4) + char2int(bottomNybble);
}
int
read4digits(void)
{
uint8_t digit1, digit2, digit3, digit4;
digit1 = SEGGER_RTT_WaitKey();
digit2 = SEGGER_RTT_WaitKey();
digit3 = SEGGER_RTT_WaitKey();
digit4 = SEGGER_RTT_WaitKey();
return (digit1 - '0')*1000 + (digit2 - '0')*100 + (digit3 - '0')*10 + (digit4 - '0');
}
WarpStatus
writeByteToI2cDeviceRegister(uint8_t i2cAddress, bool sendCommandByte, uint8_t commandByte, bool sendPayloadByte, uint8_t payloadByte)
{
i2c_status_t status;
uint8_t commandBuffer[1];
uint8_t payloadBuffer[1];
i2c_device_t i2cSlaveConfig =
{
.address = i2cAddress,
.baudRate_kbps = gWarpI2cBaudRateKbps
};
commandBuffer[0] = commandByte;
payloadBuffer[0] = payloadByte;
status = I2C_DRV_MasterSendDataBlocking(
0 /* instance */,
&i2cSlaveConfig,
commandBuffer,
(sendCommandByte ? 1 : 0),
payloadBuffer,
(sendPayloadByte ? 1 : 0),
gWarpI2cTimeoutMilliseconds);
return (status == kStatus_I2C_Success ? kWarpStatusOK : kWarpStatusDeviceCommunicationFailed);
}
WarpStatus
writeBytesToSpi(uint8_t * payloadBytes, int payloadLength)
{
uint8_t inBuffer[payloadLength];
spi_status_t status;
enableSPIpins();
status = SPI_DRV_MasterTransferBlocking(0 /* master instance */,
NULL /* spi_master_user_config_t */,
payloadBytes,
inBuffer,
payloadLength /* transfer size */,
1000 /* timeout in microseconds (unlike I2C which is ms) */);
disableSPIpins();
return (status == kStatus_SPI_Success ? kWarpStatusOK : kWarpStatusCommsError);
}
void
powerupAllSensors(void)
{
WarpStatus status;
/*
* BMX055mag
*
* Write '1' to power control bit of register 0x4B. See page 134.
*/
#ifdef WARP_BUILD_ENABLE_DEVBMX055
status = writeByteToI2cDeviceRegister( deviceBMX055magState.i2cAddress /* i2cAddress */,
true /* sendCommandByte */,
0x4B /* commandByte */,
true /* sendPayloadByte */,
(1 << 0) /* payloadByte */);
if (status != kWarpStatusOK)
{
#ifdef WARP_BUILD_ENABLE_SEGGER_RTT_PRINTF
SEGGER_RTT_printf(0, "\r\tPowerup command failed, code=%d, for BMX055mag @ 0x%02x.\n", status, deviceBMX055magState.i2cAddress);
#endif
}
#else
SEGGER_RTT_WriteString(0, "\r\tPowerup command failed. BMX055 disabled \n");
#endif
}
void
activateAllLowPowerSensorModes(bool verbose)
{
WarpStatus status;
/*
* ADXL362: See Power Control Register (Address: 0x2D, Reset: 0x00).
*
* POR values are OK.
*/
/*
* BMX055accel: At POR, device is in Normal mode. Move it to Deep Suspend mode.
*
* Write '1' to deep suspend bit of register 0x11, and write '0' to suspend bit of register 0x11. See page 23.
*/
#ifdef WARP_BUILD_ENABLE_DEVBMX055
status = writeByteToI2cDeviceRegister( deviceBMX055accelState.i2cAddress /* i2cAddress */,
true /* sendCommandByte */,
0x11 /* commandByte */,
true /* sendPayloadByte */,
(1 << 5) /* payloadByte */);
if ((status != kWarpStatusOK) && verbose)
{
#ifdef WARP_BUILD_ENABLE_SEGGER_RTT_PRINTF
SEGGER_RTT_printf(0, "\r\tPowerdown command failed, code=%d, for BMX055accel @ 0x%02x.\n", status, deviceBMX055accelState.i2cAddress);
#endif
}
#else
SEGGER_RTT_WriteString(0, "\r\tPowerdown command abandoned. BMX055 disabled\n");
#endif
/*
* BMX055gyro: At POR, device is in Normal mode. Move it to Deep Suspend mode.
*
* Write '1' to deep suspend bit of register 0x11. See page 81.
*/
#ifdef WARP_BUILD_ENABLE_DEVBMX055
status = writeByteToI2cDeviceRegister( deviceBMX055gyroState.i2cAddress /* i2cAddress */,
true /* sendCommandByte */,
0x11 /* commandByte */,
true /* sendPayloadByte */,
(1 << 5) /* payloadByte */);
if ((status != kWarpStatusOK) && verbose)
{
#ifdef WARP_BUILD_ENABLE_SEGGER_RTT_PRINTF
SEGGER_RTT_printf(0, "\r\tPowerdown command failed, code=%d, for BMX055gyro @ 0x%02x.\n", status, deviceBMX055gyroState.i2cAddress);
#endif
}
#else
SEGGER_RTT_WriteString(0, "\r\tPowerdown command abandoned. BMX055 disabled\n");
#endif
/*
* BMX055mag: At POR, device is in Suspend mode. See page 121.
*
* POR state seems to be powered down.
*/
/*
* MMA8451Q: See 0x2B: CTRL_REG2 System Control 2 Register (page 43).
*
* POR state seems to be not too bad.
*/
/*
* LPS25H: See Register CTRL_REG1, at address 0x20 (page 26).
*
* POR state seems to be powered down.
*/
/*
* MAG3110: See Register CTRL_REG1 at 0x10. (page 19).
*
* POR state seems to be powered down.
*/
/*
* HDC1000: currently can't turn it on (3V)
*/
/*
* SI7021: Can't talk to it correctly yet.
*/
/*
* L3GD20H: See CTRL1 at 0x20 (page 36).
*
* POR state seems to be powered down.
*/
#ifdef WARP_BUILD_ENABLE_DEVL3GD20H
status = writeByteToI2cDeviceRegister( deviceL3GD20HState.i2cAddress /* i2cAddress */,
true /* sendCommandByte */,
0x20 /* commandByte */,
true /* sendPayloadByte */,
0x00 /* payloadByte */);
if ((status != kWarpStatusOK) && verbose)
{
#ifdef WARP_BUILD_ENABLE_SEGGER_RTT_PRINTF
SEGGER_RTT_printf(0, "\r\tPowerdown command failed, code=%d, for L3GD20H @ 0x%02x.\n", status, deviceL3GD20HState.i2cAddress);
#endif
}
#else
SEGGER_RTT_WriteString(0, "\r\tPowerdown command abandoned. L3GD20H disabled\n");
#endif
/*
* BME680: TODO
*/
/*
* TCS34725: By default, is in the "start" state (see page 9).
*
* Make it go to sleep state. See page 17, 18, and 19.
*/
#ifdef WARP_BUILD_ENABLE_DEVTCS34725
status = writeByteToI2cDeviceRegister( deviceTCS34725State.i2cAddress /* i2cAddress */,
true /* sendCommandByte */,
0x00 /* commandByte */,
true /* sendPayloadByte */,
0x00 /* payloadByte */);
if ((status != kWarpStatusOK) && verbose)
{
#ifdef WARP_BUILD_ENABLE_SEGGER_RTT_PRINTF
SEGGER_RTT_printf(0, "\r\tPowerdown command failed, code=%d, for TCS34725 @ 0x%02x.\n", status, deviceTCS34725State.i2cAddress);
#endif
}
#else
SEGGER_RTT_WriteString(0, "\r\tPowerdown command abandoned. TCS34725 disabled\n");
#endif
/*
* SI4705: Send a POWER_DOWN command (byte 0x17). See AN332 page 124 and page 132.
*
* For now, simply hold its reset line low.
*/
#ifdef WARP_BUILD_ENABLE_DEVSI4705
GPIO_DRV_ClearPinOutput(kWarpPinSI4705_nRST);
#endif
/*
* PAN1326.
*
* For now, simply hold its reset line low.
*/
#ifndef WARP_BUILD_ENABLE_THERMALCHAMBERANALYSIS
#ifdef WARP_BUILD_ENABLE_DEVPAN1326
GPIO_DRV_ClearPinOutput(kWarpPinPAN1326_nSHUTD);
#endif
#endif
}
|
105876.c | /* -----------------------------------------------------------------------------
* Copyright (c) 2013-2016 ARM Ltd.
*
* This software is provided 'as-is', without any express or implied warranty.
* In no event will the authors be held liable for any damages arising from
* the use of this software. Permission is granted to anyone to use this
* software for any purpose, including commercial applications, and to alter
* it and redistribute it freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software in
* a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source distribution.
*
*
* $Date: 22. September 2016
* $Revision: V2.3
*
* Driver: Driver_USBD0
* Configured: via RTE_Device.h configuration file
* Project: USB Full/Low-Speed Device Driver for ST STM32F1xx
* --------------------------------------------------------------------------
* Use the following configuration settings in the middleware component
* to connect to this driver.
*
* Configuration Setting Value
* --------------------- -----
* Connect to hardware via Driver_USBD# = 0
* --------------------------------------------------------------------------
* Defines used for driver configuration (at compile time):
*
* USBD_MAX_ENDPOINT_NUM: defines maximum number of IN/OUT Endpoint pairs
* that driver will support with Control Endpoint 0
* not included, this value impacts driver memory
* requirements
* - default value: 3
* - maximum value: 3
* USBD_FS_VBUS_DETECT: defines if driver supports VBUS detection
* - default value: 1 (=enabled)
* -------------------------------------------------------------------------- */
/* History:
* Version 2.3
* Corrected resume event signaling
* Version 2.2
* Corrected initial resume signaling after USB Bus Reset
* VBUS sensing enabled by default
* Version 2.1
* Updated Isochronous transfer
* Updated IN Endpoint FIFO flush procedure
* Version 2.0
* Updated to CMSIS Driver API V2.01
* Version 1.4
* Multiple packet read
* Version 1.3
* Based on API V1.10 (namespace prefix ARM_ added)
* Version 1.2
* Removed include of rl_usb.h header
* Version 1.0
* Initial release
*/
#include <stdint.h>
#include <string.h>
#include "cmsis_os.h"
#include "Driver_USBD.h"
#include "stm32f10x.h"
#include "GPIO_STM32F10x.h"
#include "OTG_STM32F10x_cl.h"
#ifndef USBD_MAX_ENDPOINT_NUM
#define USBD_MAX_ENDPOINT_NUM (3U)
#endif
#if (USBD_MAX_ENDPOINT_NUM > 3)
#error Too many Endpoints, maximum IN/OUT Endpoint pairs that this driver supports is 3 !!!
#endif
#ifndef USBD_FS_VBUS_DETECT
#define USBD_FS_VBUS_DETECT (1U)
#endif
extern uint8_t otg_fs_role;
extern void OTG_FS_PinsConfigure (uint8_t pins_mask);
extern void OTG_FS_PinsUnconfigure (uint8_t pins_mask);
// USBD Driver *****************************************************************
#define ARM_USBD_DRV_VERSION ARM_DRIVER_VERSION_MAJOR_MINOR(2,3)
// Driver Version
static const ARM_DRIVER_VERSION usbd_driver_version = { ARM_USBD_API_VERSION, ARM_USBD_DRV_VERSION };
// Driver Capabilities
static const ARM_USBD_CAPABILITIES usbd_driver_capabilities = {
#if (USBD_FS_VBUS_DETECT == 1)
1U, // VBUS Detection
1U, // Event VBUS On
1U, // Event VBUS Off
#else
0U, // VBUS Detection
0U, // Event VBUS On
0U // Event VBUS Off
#endif
};
#define OTG (OTG_FS)
#define EP_NUM(ep_addr) ((ep_addr) & ARM_USB_ENDPOINT_NUMBER_MASK)
#define EP_ID(ep_addr) ((EP_NUM(ep_addr) * 2U) + (((ep_addr) >> 7) & 1U))
// FIFO sizes in bytes (total available memory for FIFOs is 1.25 kB)
#ifndef OTG_RX_FIFO_SIZE
#define OTG_RX_FIFO_SIZE (640U)
#endif
#ifndef OTG_TX0_FIFO_SIZE
#define OTG_TX0_FIFO_SIZE (160U)
#endif
#ifndef OTG_TX1_FIFO_SIZE
#define OTG_TX1_FIFO_SIZE (160U)
#endif
#ifndef OTG_TX2_FIFO_SIZE
#define OTG_TX2_FIFO_SIZE (160U)
#endif
#ifndef OTG_TX3_FIFO_SIZE
#define OTG_TX3_FIFO_SIZE (160U)
#endif
#define OTG_TX_FIFO(n) *((volatile uint32_t *)(OTG_FS_BASE + 0x1000U + (n * 0x1000U)))
#define OTG_RX_FIFO *((volatile uint32_t *)(OTG_FS_BASE + 0x1000U))
#define OTG_DIEPTSIZ(ep_num) *((volatile uint32_t *)(&OTG->DIEPTSIZ0 + (ep_num * 8U)))
#define OTG_DIEPCTL(ep_num) *((volatile uint32_t *)(&OTG->DIEPCTL0 + (ep_num * 8U)))
#define OTG_DTXFSTS(ep_num) *((volatile uint32_t *)(&OTG->DTXFSTS0 + (ep_num * 8U)))
#define OTG_DOEPTSIZ(ep_num) *((volatile uint32_t *)(&OTG->DOEPTSIZ0 + (ep_num * 8U)))
#define OTG_DOEPCTL(ep_num) *((volatile uint32_t *)(&OTG->DOEPCTL0 + (ep_num * 8U)))
#define OTG_DIEPINT(ep_num) *((volatile uint32_t *)(&OTG->DIEPINT0 + (ep_num * 8U)))
#define OTG_DOEPINT(ep_num) *((volatile uint32_t *)(&OTG->DOEPINT0 + (ep_num * 8U)))
#define OTG_EP_IN_TYPE(ep_num) ((OTG_DIEPCTL(ep_num) >> 18) & 3U)
#define OTG_EP_OUT_TYPE(ep_num) ((OTG_DOEPCTL(ep_num) >> 18) & 3U)
typedef struct { // Endpoint structure definition
uint8_t *data;
uint32_t num;
uint32_t num_transferred_total;
uint16_t num_transferring;
uint16_t max_packet_size;
uint8_t active;
uint8_t in_nak;
uint8_t in_zlp;
uint8_t in_flush;
} ENDPOINT_t;
static ARM_USBD_SignalDeviceEvent_t SignalDeviceEvent;
static ARM_USBD_SignalEndpointEvent_t SignalEndpointEvent;
static bool hw_powered = false;
static bool hw_initialized = false;
static ARM_USBD_STATE usbd_state;
static uint32_t setup_packet[2]; // Setup packet data
static volatile uint8_t setup_received; // Setup packet received
// Endpoints runtime information
static volatile ENDPOINT_t ep[(USBD_MAX_ENDPOINT_NUM + 1U) * 2U];
// Function prototypes
static uint16_t USBD_GetFrameNumber (void);
// Auxiliary functions
/**
\fn void USBD_FlushInEpFifo (uint8_t FIFO_num)
\brief Flush IN Endpoint FIFO
\param[in] FIFO_num IN Endpoint FIFO number
- FIFO_num.0..3: IN Endpoint FIFO to Flush
- FIFO_num.4: All IN Endpoint FIFOs to Flush
*/
static void USBD_FlushInEpFifo (uint8_t FIFO_num) {
while ((OTG->GRSTCTL & OTG_FS_GRSTCTL_TXFFLSH) != 0U);
OTG->GRSTCTL = (OTG->GRSTCTL & ~OTG_FS_GRSTCTL_TXFNUM_MSK) | OTG_FS_GRSTCTL_TXFNUM(FIFO_num);
OTG->GRSTCTL |= OTG_FS_GRSTCTL_TXFFLSH;
while ((OTG->GRSTCTL & OTG_FS_GRSTCTL_TXFFLSH) != 0U);
}
/**
\fn void USBD_Reset (void)
\brief Reset USB Endpoint settings and variables.
*/
static void USBD_Reset (void) {
uint8_t i;
uint32_t epctl;
// Reset global variables
setup_packet[0] = 0U;
setup_packet[1] = 0U;
setup_received = 0U;
memset((void *)(ep), 0U, sizeof(ep));
// Clear Endpoint mask registers
OTG->DOEPMSK = 0U;
OTG->DIEPMSK = 0U;
for (i = 1U; i <= USBD_MAX_ENDPOINT_NUM; i++) {
// Endpoint set NAK
epctl = OTG_FS_DOEPCTLx_SNAK;
if ((OTG_DOEPCTL(i) & OTG_FS_DOEPCTLx_EPENA) != 0U) {
// Disable enabled Endpoint
epctl |= OTG_FS_DOEPCTLx_EPDIS;
}
OTG_DOEPCTL(i) = epctl;
// Endpoint set NAK
epctl = OTG_FS_DIEPCTLx_SNAK;
if ((OTG_DIEPCTL(i) & OTG_FS_DIEPCTLx_EPENA) != 0U) {
// Disable enabled Endpoint
epctl |= OTG_FS_DIEPCTLx_EPDIS;
}
OTG_DIEPCTL(i) = epctl;
// Clear IN Endpoint interrupts
OTG_DIEPINT(i) = OTG_FS_DIEPINTx_XFCR |
OTG_FS_DIEPINTx_EPDISD |
OTG_FS_DIEPINTx_TOC |
OTG_FS_DIEPINTx_ITTXFE |
OTG_FS_DIEPINTx_INEPNE |
OTG_FS_DIEPINTx_TXFE ;
// Clear OUT Endpoint interrupts
OTG_DOEPINT(i) = OTG_FS_DOEPINTx_XFCR |
OTG_FS_DOEPINTx_EPDISD |
OTG_FS_DOEPINTx_STUP |
OTG_FS_DOEPINTx_OTEPDIS |
OTG_FS_DOEPINTx_B2BSTUP ;
}
// Flush all IN Endpoint FIFOs
USBD_FlushInEpFifo (0x10U);
// Set device address to 0
OTG->DCFG = (OTG->DCFG & ~OTG_FS_DCFG_DAD_MSK);
OTG->DAINTMSK = OTG_FS_DAINT_IEPINT(0U) | // Enable IN Endpoint0 interrupt
OTG_FS_DAINT_OEPINT(0U); // Enable OUT Endpoint0 interrupt
// Enable Setup phase done, OUT Endpoint disabled and OUT transfer complete interrupt
OTG->DOEPMSK = OTG_FS_DOEPMSK_STUPM |
OTG_FS_DOEPMSK_EPDM |
OTG_FS_DOEPMSK_XFRCM ;
// Enable In Endpoint disable and IN transfer complete interrupt
OTG->DIEPMSK = OTG_FS_DIEPMSK_EPDM |
OTG_FS_DIEPMSK_XFRCM ;
// Configure FIFOs
OTG->GRXFSIZ = OTG_RX_FIFO_SIZE / 4U;
OTG->DIEPTXF0 = (OTG_RX_FIFO_SIZE / 4U) |
((OTG_TX0_FIFO_SIZE / 4U) << OTG_FS_DIEPTXFx_INEPTXFD_POS);
OTG->DIEPTXF1 = ((OTG_RX_FIFO_SIZE + OTG_TX0_FIFO_SIZE) / 4U) |
((OTG_TX1_FIFO_SIZE / 4U) << OTG_FS_DIEPTXFx_INEPTXFD_POS);
OTG->DIEPTXF2 = ((OTG_RX_FIFO_SIZE + OTG_TX0_FIFO_SIZE + OTG_TX1_FIFO_SIZE) / 4U) |
((OTG_TX2_FIFO_SIZE / 4U) << OTG_FS_DIEPTXFx_INEPTXFD_POS);
OTG->DIEPTXF3 = ((OTG_RX_FIFO_SIZE + OTG_TX0_FIFO_SIZE + OTG_TX1_FIFO_SIZE +
OTG_TX2_FIFO_SIZE)/ 4U) |
((OTG_TX3_FIFO_SIZE / 4U) << OTG_FS_DIEPTXFx_INEPTXFD_POS);
}
/**
\fn void USBD_EndpointReadSet (uint8_t ep_addr)
\brief Set Endpoint for next read.
\param[in] ep_addr Endpoint Address
- ep_addr.0..3: Address
- ep_addr.7: Direction
*/
static void USBD_EndpointReadSet (uint8_t ep_addr) {
volatile ENDPOINT_t *ptr_ep;
uint16_t num;
uint8_t ep_num;
ptr_ep = &ep[EP_ID(ep_addr)];
ep_num = EP_NUM(ep_addr);
// Set packet count and transfer size
if (ptr_ep->num > ptr_ep->max_packet_size) { num = ptr_ep->max_packet_size; }
else { num = ptr_ep->num; }
if (ep_num != 0U) {
OTG_DOEPTSIZ(ep_num) = (1U << OTG_FS_DOEPTSIZx_PKTCNT_POS ) |
num ;
} else {
OTG_DOEPTSIZ(0U) = (1U << OTG_FS_DOEPTSIZx_PKTCNT_POS ) |
(3U << OTG_FS_DOEPTSIZ0_STUPCNT_POS) |
num ;
}
// Set correct frame for Isochronous Endpoint
if (OTG_EP_OUT_TYPE(ep_num) == ARM_USB_ENDPOINT_ISOCHRONOUS) {
if ((USBD_GetFrameNumber() & 1U) != 0U) { OTG_DOEPCTL(ep_num) |= OTG_FS_DOEPCTLx_SEVNFRM; }
else { OTG_DOEPCTL(ep_num) |= OTG_FS_DOEPCTLx_SODDFRM; }
}
// Clear NAK and enable Endpoint
OTG_DOEPCTL(ep_num) |= OTG_FS_DOEPCTLx_EPENA | OTG_FS_DOEPCTLx_CNAK;
}
/**
\fn int32_t USBD_ReadFromFifo (uint8_t ep_addr, uint16_t num)
\brief Read data from USB Endpoint.
\param[in] ep_addr Endpoint Address
- ep_addr.0..3: Address
- ep_addr.7: Direction
\param[in] num number of data bytes to read
\return number of data bytes read
*/
static int32_t USBD_ReadFromFifo (uint8_t ep_addr, uint16_t num) {
volatile ENDPOINT_t *ptr_ep;
uint32_t i, residue;
uint8_t *ptr_dest_8;
__packed uint32_t *ptr_dest_32;
volatile uint32_t *ptr_src;
uint8_t ep_num;
uint8_t tmp_buf[4];
ptr_ep = &ep[EP_ID(ep_addr)];
ep_num = EP_NUM(ep_addr);
// Check if Endpoint is activated and buffer available
if ((OTG_DOEPCTL(ep_num) & OTG_FS_DOEPCTLx_USBAEP) == 0U) { return 0U; }
if (ptr_ep->data == 0U) { return 0U; }
if (num > ptr_ep->num) { num = ptr_ep->num; }
// If Isochronous Endpoint
if (OTG_EP_OUT_TYPE(ep_num) == ARM_USB_ENDPOINT_ISOCHRONOUS) {
// If DATA PID = DATA0 and number of packets in
// which this payload was received = 1, then data is valid
if ((OTG_DOEPTSIZ(ep_num) & (OTG_FS_DOEPTSIZx_PKTCNT_MSK | OTG_FS_DOEPTSIZx_RXDPID_MSK)) != 0) { num = 0U; }
}
// Copy data from FIFO
ptr_src = (volatile uint32_t *)(OTG_FS_BASE + 0x1000U);
ptr_dest_32 = (__packed uint32_t *)(ptr_ep->data + ptr_ep->num_transferred_total);
i = num / 4U;
while (i != 0U) {
*ptr_dest_32++ = *ptr_src;
i--;
}
ptr_ep->num_transferred_total += num;
// If data size is not equal n*4
residue = num % 4U;
if (residue != 0U) {
ptr_dest_8 = (uint8_t *)(ptr_dest_32);
*((__packed uint32_t *)tmp_buf) = OTG_RX_FIFO;
for (i = 0U; i < residue; i++) {
*ptr_dest_8++ = tmp_buf[i];
}
}
if (num != ptr_ep->max_packet_size) { ptr_ep->num = 0U; }
else { ptr_ep->num -= num; }
return num;
}
/**
\fn void USBD_WriteToFifo (uint8_t ep_addr)
\brief Write data to Endpoint FIFO.
\param[in] ep_addr Endpoint Address
- ep_addr.0..3: Address
- ep_addr.7: Direction
*/
static void USBD_WriteToFifo (uint8_t ep_addr) {
volatile ENDPOINT_t *ptr_ep;
uint8_t ep_num;
uint16_t num, i;
volatile uint32_t *ptr_dest;
__packed uint32_t *ptr_src;
ptr_ep = &ep[EP_ID(ep_addr)];
ep_num = EP_NUM(ep_addr);
if (ptr_ep->num > ptr_ep->max_packet_size) { num = ptr_ep->max_packet_size; }
else { num = ptr_ep->num; }
// Check if enough space in FIFO
if ((OTG_DTXFSTS(ep_num) * 4U) < num) { return; }
// Set transfer size and packet count
OTG_DIEPTSIZ(ep_num) = (1U << OTG_FS_DIEPTSIZx_PKTCNT_POS) |
(1U << OTG_FS_DIEPTSIZx_MCNT_POS) |
num ;
// Set correct frame for Isochronous Endpoint
if (OTG_EP_IN_TYPE(ep_num) == ARM_USB_ENDPOINT_ISOCHRONOUS) {
if ((USBD_GetFrameNumber() & 1U) != 0U) { OTG_DIEPCTL(ep_num) |= OTG_FS_DIEPCTLx_SEVNFRM; }
else { OTG_DIEPCTL(ep_num) |= OTG_FS_DIEPCTLx_SODDFRM; }
}
// Enable Endpoint and clear NAK
OTG_DIEPCTL(ep_num) |= OTG_FS_DIEPCTLx_EPENA | OTG_FS_DIEPCTLx_CNAK;
ptr_src = (__packed uint32_t *)(ptr_ep->data + ptr_ep->num_transferred_total);
ptr_dest = (volatile uint32_t *)(OTG_FS_BASE + 0x1000U + (ep_num * 0x1000U));
ptr_ep->num_transferring = num;
ptr_ep->num -= num;
ptr_ep->in_zlp = 0U;
// Copy data to FIFO
i = (num + 3U) >> 2;
while (i != 0U) {
*ptr_dest = *ptr_src++;
i--;
}
}
// USBD Driver functions
/**
\fn ARM_DRIVER_VERSION USBD_GetVersion (void)
\brief Get driver version.
\return \ref ARM_DRIVER_VERSION
*/
static ARM_DRIVER_VERSION USBD_GetVersion (void) { return usbd_driver_version; }
/**
\fn ARM_USBD_CAPABILITIES USBD_GetCapabilities (void)
\brief Get driver capabilities.
\return \ref ARM_USBD_CAPABILITIES
*/
static ARM_USBD_CAPABILITIES USBD_GetCapabilities (void) { return usbd_driver_capabilities; }
/**
\fn int32_t USBD_Initialize (ARM_USBD_SignalDeviceEvent_t cb_device_event,
ARM_USBD_SignalEndpointEvent_t cb_endpoint_event)
\brief Initialize USB Device Interface.
\param[in] cb_device_event Pointer to \ref ARM_USBD_SignalDeviceEvent
\param[in] cb_endpoint_event Pointer to \ref ARM_USBD_SignalEndpointEvent
\return \ref execution_status
*/
static int32_t USBD_Initialize (ARM_USBD_SignalDeviceEvent_t cb_device_event,
ARM_USBD_SignalEndpointEvent_t cb_endpoint_event) {
if (hw_initialized == true) {
return ARM_DRIVER_OK;
}
SignalDeviceEvent = cb_device_event;
SignalEndpointEvent = cb_endpoint_event;
otg_fs_role = ARM_USB_ROLE_DEVICE;
OTG_FS_PinsConfigure (ARM_USB_PIN_DP | ARM_USB_PIN_DM
#if (USBD_FS_VBUS_DETECT == 1)
| ARM_USB_PIN_VBUS
#endif
);
hw_initialized = true;
return ARM_DRIVER_OK;
}
/**
\fn int32_t USBD_Uninitialize (void)
\brief De-initialize USB Device Interface.
\return \ref execution_status
*/
static int32_t USBD_Uninitialize (void) {
OTG_FS_PinsUnconfigure (ARM_USB_PIN_DP | ARM_USB_PIN_DM
#if (USBD_FS_VBUS_DETECT == 1)
| ARM_USB_PIN_VBUS
#endif
);
otg_fs_role = ARM_USB_ROLE_NONE;
hw_initialized = false;
return ARM_DRIVER_OK;
}
/**
\fn int32_t USBD_PowerControl (ARM_POWER_STATE state)
\brief Control USB Device Interface Power.
\param[in] state Power state
\return \ref execution_status
*/
static int32_t USBD_PowerControl (ARM_POWER_STATE state) {
switch (state) {
case ARM_POWER_OFF:
RCC->AHBENR |= RCC_AHBENR_OTGFSEN; // OTG FS clock enable
NVIC_DisableIRQ (OTG_FS_IRQn); // Disable interrupt
NVIC_ClearPendingIRQ (OTG_FS_IRQn); // Clear pending interrupt
hw_powered = false; // Clear powered flag
OTG->DCTL |= OTG_FS_DCTL_SDIS; // Soft disconnect enabled
OTG->GAHBCFG &= ~OTG_FS_GAHBCFG_GINTMSK; // Disable USB interrupts
RCC->AHBRSTR |= RCC_AHBRSTR_OTGFSRST; // Reset OTG FS module
// Reset variables
setup_received = 0U;
memset((void *)(&usbd_state), 0, sizeof(usbd_state));
memset((void *)(ep), 0, sizeof(ep));
OTG->GCCFG &= ~OTG_FS_GCCFG_PWRDWN; // Enable PHY power down
OTG->PCGCCTL |= OTG_FS_PCGCCTL_STPPCLK; // Stop PHY clock
OTG->GCCFG = 0U; // Reset core configuration
RCC->AHBENR &= ~RCC_AHBENR_OTGFSEN; // Disable OTG FS clock
break;
case ARM_POWER_FULL:
if (hw_initialized == false) {
return ARM_DRIVER_ERROR;
}
if (hw_powered == true) {
return ARM_DRIVER_OK;
}
RCC->AHBENR |= RCC_AHBENR_OTGFSEN; // OTG FS clock enable
RCC->AHBRSTR |= RCC_AHBRSTR_OTGFSRST; // Reset OTG FS module
osDelay(1U);
RCC->AHBRSTR &= ~RCC_AHBRSTR_OTGFSRST; // Clear reset of OTG FS module
osDelay(1U);
OTG->GCCFG |= OTG_FS_GCCFG_PWRDWN; // Disable power down
OTG->GUSBCFG |= OTG_FS_GUSBCFG_PHYSEL; // Full-speed transceiver
// Wait until AHB Master state machine is in the idle condition
while ((OTG->GRSTCTL & OTG_FS_GRSTCTL_AHBIDL) == 0U);
OTG->GRSTCTL |= OTG_FS_GRSTCTL_CSRST; // Core soft reset
while ((OTG->GRSTCTL & OTG_FS_GRSTCTL_CSRST) != 0U);
osDelay (1U);
// Wait until AHB Master state machine is in the idle condition
while ((OTG->GRSTCTL & OTG_FS_GRSTCTL_AHBIDL) == 0U);
OTG->DCTL |= OTG_FS_DCTL_SDIS; // Soft disconnect enabled
// Set turnaround time
OTG->GUSBCFG = ((OTG->GUSBCFG & ~OTG_FS_GUSBCFG_TRDT_MSK) |
OTG_FS_GUSBCFG_TRDT(15U)) ;
if (((OTG->GUSBCFG & OTG_FS_GUSBCFG_FDMOD) == 0U) || ((OTG->GUSBCFG & OTG_FS_GUSBCFG_FHMOD) != 0U)) {
OTG->GUSBCFG &= ~OTG_FS_GUSBCFG_FHMOD; // Clear force host mode
OTG->GUSBCFG |= OTG_FS_GUSBCFG_FDMOD; // Force device mode
osDelay (50U);
}
USBD_Reset (); // Reset variables and endpoint settings
#if (USBD_FS_VBUS_DETECT == 1)
OTG->GCCFG |= OTG_FS_GCCFG_VBUSBSEN; // Enable VBUS sensing device "B"
#else
OTG->GCCFG |= OTG_FS_GCCFG_NOVBUSSENS; // Disable VBUS sensing
#endif
OTG->DCFG |= OTG_FS_DCFG_DSPD_MSK; // Full Speed
OTG->GINTMSK = (OTG_FS_GINTMSK_USBSUSPM | // Unmask interrupts
OTG_FS_GINTMSK_USBRST |
OTG_FS_GINTMSK_ENUMDNEM |
OTG_FS_GINTMSK_RXFLVLM |
OTG_FS_GINTMSK_IEPINT |
OTG_FS_GINTMSK_OEPINT |
#if (USBD_FS_VBUS_DETECT == 1)
OTG_FS_GINTMSK_SRQIM |
OTG_FS_GINTMSK_OTGINT |
#endif
OTG_FS_GINTMSK_WUIM) ;
OTG->GAHBCFG |= (OTG_FS_GAHBCFG_GINTMSK | // Enable interrupts
OTG_FS_GAHBCFG_TXFELVL) ;
hw_powered = true; // Set powered flag
NVIC_EnableIRQ (OTG_FS_IRQn); // Enable interrupt
break;
default:
return ARM_DRIVER_ERROR_UNSUPPORTED;
}
return ARM_DRIVER_OK;
}
/**
\fn int32_t USBD_DeviceConnect (void)
\brief Connect USB Device.
\return \ref execution_status
*/
static int32_t USBD_DeviceConnect (void) {
if (hw_powered == false) { return ARM_DRIVER_ERROR; }
OTG->DCTL &= ~OTG_FS_DCTL_SDIS; // Soft disconnect disabled
OTG->GCCFG |= OTG_FS_GCCFG_PWRDWN; // Disable power down
return ARM_DRIVER_OK;
}
/**
\fn int32_t USBD_DeviceDisconnect (void)
\brief Disconnect USB Device.
\return \ref execution_status
*/
static int32_t USBD_DeviceDisconnect (void) {
if (hw_powered == false) { return ARM_DRIVER_ERROR; }
OTG->DCTL |= OTG_FS_DCTL_SDIS; // Soft disconnect enabled
OTG->GCCFG &= ~OTG_FS_GCCFG_PWRDWN; // Enable power down
return ARM_DRIVER_OK;
}
/**
\fn ARM_USBD_STATE USBD_DeviceGetState (void)
\brief Get current USB Device State.
\return Device State \ref ARM_USBD_STATE
*/
static ARM_USBD_STATE USBD_DeviceGetState (void) {
return usbd_state;
}
/**
\fn int32_t USBD_DeviceRemoteWakeup (void)
\brief Trigger USB Remote Wakeup.
\return \ref execution_status
*/
static int32_t USBD_DeviceRemoteWakeup (void) {
if (hw_powered == false) { return ARM_DRIVER_ERROR; }
OTG->DCTL |= OTG_FS_DCTL_RWUSIG; // Remote wakeup signaling
osDelay(5U);
OTG->DCTL &= ~OTG_FS_DCTL_RWUSIG;
return ARM_DRIVER_OK;
}
/**
\fn int32_t USBD_DeviceSetAddress (uint8_t dev_addr)
\brief Set USB Device Address.
\param[in] dev_addr Device Address
\return \ref execution_status
*/
static int32_t USBD_DeviceSetAddress (uint8_t dev_addr) {
if (hw_powered == false) { return ARM_DRIVER_ERROR; }
OTG->DCFG = (OTG->DCFG & ~OTG_FS_DCFG_DAD_MSK) | OTG_FS_DCFG_DAD(dev_addr);
return ARM_DRIVER_OK;
}
/**
\fn int32_t USBD_ReadSetupPacket (uint8_t *setup)
\brief Read setup packet received over Control Endpoint.
\param[out] setup Pointer to buffer for setup packet
\return \ref execution_status
*/
static int32_t USBD_ReadSetupPacket (uint8_t *setup) {
if (hw_powered == false) { return ARM_DRIVER_ERROR; }
if (setup_received == 0U) { return ARM_DRIVER_ERROR; }
setup_received = 0U;
memcpy(setup, setup_packet, 8);
if (setup_received != 0U) { // If new setup packet was received while this was being read
return ARM_DRIVER_ERROR;
}
return ARM_DRIVER_OK;
}
/**
\fn int32_t USBD_EndpointConfigure (uint8_t ep_addr,
uint8_t ep_type,
uint16_t ep_max_packet_size)
\brief Configure USB Endpoint.
\param[in] ep_addr Endpoint Address
- ep_addr.0..3: Address
- ep_addr.7: Direction
\param[in] ep_type Endpoint Type (ARM_USB_ENDPOINT_xxx)
\param[in] ep_max_packet_size Endpoint Maximum Packet Size
\return \ref execution_status
*/
static int32_t USBD_EndpointConfigure (uint8_t ep_addr,
uint8_t ep_type,
uint16_t ep_max_packet_size) {
volatile ENDPOINT_t *ptr_ep;
uint8_t ep_num;
uint16_t ep_mps;
bool ep_dir;
ep_num = EP_NUM(ep_addr);
if (ep_num > USBD_MAX_ENDPOINT_NUM) { return ARM_DRIVER_ERROR; }
if (hw_powered == false) { return ARM_DRIVER_ERROR; }
ptr_ep = &ep[EP_ID(ep_addr)];
if (ptr_ep->active != 0U) { return ARM_DRIVER_ERROR_BUSY; }
ep_dir = (ep_addr & ARM_USB_ENDPOINT_DIRECTION_MASK) == ARM_USB_ENDPOINT_DIRECTION_MASK;
ep_mps = ep_max_packet_size & ARM_USB_ENDPOINT_MAX_PACKET_SIZE_MASK;
// Clear Endpoint transfer and configuration information
memset((void *)(ptr_ep), 0, sizeof (ENDPOINT_t));
// Set maximum packet size to requested
ptr_ep->max_packet_size = ep_mps;
// IN Endpoint
if (ep_dir != 0U) {
ptr_ep->in_nak = 0U; // Clear IN Endpoint NAK flag
// Configure IN Endpoint
OTG_DIEPCTL(ep_num) = (ep_num << OTG_FS_DIEPCTLx_TXFNUM_POS) | // FIFO Number
(ep_type << OTG_FS_DIEPCTLx_EPTYP_POS ) | // Endpoint Type
ep_mps ; // Max Packet Size
// Set DATA0 PID for Interrupt or Bulk Endpoint
if (ep_type >= ARM_USB_ENDPOINT_BULK) {
OTG_DIEPCTL(ep_num) |= OTG_FS_DIEPCTLx_SD0PID;
}
OTG_DIEPCTL(ep_num) |= OTG_FS_DIEPCTLx_USBAEP; // Activate Endpoint
if ((OTG_DIEPCTL(ep_num) & OTG_FS_DIEPCTLx_EPENA) != 0U) {
OTG_DIEPCTL(ep_num) |= OTG_FS_DIEPCTLx_EPDIS; // Disable Endpoint
}
// Isochronous IN Endpoint Configuration
if (OTG_EP_IN_TYPE(ep_num) == ARM_USB_ENDPOINT_ISOCHRONOUS) {
OTG->GINTMSK |= OTG_FS_GINTMSK_EOPFM; // Enable End of Periodic Frame Interrupt
}
OTG->DAINTMSK |= (1U << ep_num); // Enable Endpoint interrupt
} else {
// OUT Endpoint
// Configure OUT Endpoint
OTG_DOEPCTL(ep_num) = (ep_type << OTG_FS_DOEPCTLx_EPTYP_POS) | // Endpoint Type
OTG_FS_DOEPCTLx_SNAK | // Set NAK
ep_mps ; // Max Packet Size
// Set DATA0 PID for Interrupt or Bulk Endpoint
if (ep_type >= ARM_USB_ENDPOINT_BULK) {
OTG_DOEPCTL(ep_num) |= OTG_FS_DOEPCTLx_SD0PID;
}
// Isochronous OUT Endpoint Configuration
if (OTG_EP_OUT_TYPE(ep_num) == ARM_USB_ENDPOINT_ISOCHRONOUS) {
OTG->GINTMSK |= OTG_FS_GINTMSK_EOPFM; // Enable End of Periodic Frame Interrupt
}
OTG_DOEPCTL(ep_num) |= OTG_FS_DOEPCTLx_USBAEP; // Activate Endpoint
OTG->DAINTMSK |= (1U << (ep_num + 16)); // Enable Endpoint interrupt
}
return ARM_DRIVER_OK;
}
/**
\fn int32_t USBD_EndpointUnconfigure (uint8_t ep_addr)
\brief Unconfigure USB Endpoint.
\param[in] ep_addr Endpoint Address
- ep_addr.0..3: Address
- ep_addr.7: Direction
\return \ref execution_status
*/
static int32_t USBD_EndpointUnconfigure (uint8_t ep_addr) {
volatile ENDPOINT_t *ptr_ep;
uint8_t ep_num, i, IsoEpEnCnt;
bool ep_dir;
ep_num = EP_NUM(ep_addr);
if (ep_num > USBD_MAX_ENDPOINT_NUM) { return ARM_DRIVER_ERROR; }
if (hw_powered == false) { return ARM_DRIVER_ERROR; }
ptr_ep = &ep[EP_ID(ep_addr)];
if (ptr_ep->active != 0U) { return ARM_DRIVER_ERROR_BUSY; }
ep_dir = (ep_addr & ARM_USB_ENDPOINT_DIRECTION_MASK) == ARM_USB_ENDPOINT_DIRECTION_MASK;
OTG->DAINTMSK &= ~(1U << (ep_num + ((ep_dir ^ 1U) << 4))); // Disable Endpoint interrupt
// Clear Endpoint transfer and configuration information
memset((void *)(ptr_ep), 0, sizeof (ENDPOINT_t));
IsoEpEnCnt = 0U;
// Count Active Isochronous OUT and IN Endpoints
if ((OTG_EP_OUT_TYPE(ep_num) == ARM_USB_ENDPOINT_ISOCHRONOUS) ||
(OTG_EP_IN_TYPE (ep_num) == ARM_USB_ENDPOINT_ISOCHRONOUS)) {
for (i = 1U; i <= USBD_MAX_ENDPOINT_NUM; i++) {
if ((OTG_DOEPCTL(i) & OTG_FS_DOEPCTLx_USBAEP) != 0U) {
if (OTG_EP_OUT_TYPE(i) == ARM_USB_ENDPOINT_ISOCHRONOUS) {
IsoEpEnCnt++;
}
}
if ((OTG_DIEPCTL(i) & OTG_FS_DIEPCTLx_USBAEP) != 0U) {
if (OTG_EP_IN_TYPE(i) == ARM_USB_ENDPOINT_ISOCHRONOUS) {
IsoEpEnCnt++;
}
}
}
// If Last Active Isochronous OUT or IN Endpoint, Disable EOPF
if (IsoEpEnCnt == 1U) { OTG->GINTMSK &= ~OTG_FS_GINTMSK_EOPFM; }
}
// IN Endpoint
if (ep_dir != 0U) {
// Disable Enabled IN Endpoint
if ((OTG_DIEPCTL(ep_num) & OTG_FS_DIEPCTLx_EPENA) != 0U) {
OTG_DIEPCTL(ep_num) |= OTG_FS_DIEPCTLx_EPDIS;
}
OTG_DIEPCTL(ep_num) |= OTG_FS_DIEPCTLx_SNAK; // Set Endpoint NAK
// Deactivate Endpoint
if (ep_num != 0U) { OTG_DIEPCTL(ep_num) &= ~OTG_FS_DIEPCTLx_USBAEP; }
} else {
// OUT Endpoint
OTG->DCTL |= OTG_FS_DCTL_SGONAK; // Set Global OUT NAK
while ((OTG->GINTSTS & OTG_FS_GINTSTS_GONAKEFF) == 0U);
OTG_DOEPCTL(ep_num) |= OTG_FS_DOEPCTLx_SNAK; // Set Endpoint NAK
if (ep_num != 0U) {
// Disable Enabled OUT Endpoint
if ((OTG_DOEPCTL(ep_num) & OTG_FS_DOEPCTLx_EPENA) != 0U) {
OTG_DOEPCTL(ep_num) |= OTG_FS_DOEPCTLx_EPDIS;
while ((OTG_DOEPINT(ep_num) & OTG_FS_DOEPINTx_EPDISD) == 0U);
}
OTG_DOEPCTL(ep_num) &= ~OTG_FS_DOEPCTLx_USBAEP; // Deactivate Endpoint
}
OTG->DCTL |= OTG_FS_DCTL_CGONAK; // Clear Global OUT NAK
}
return ARM_DRIVER_OK;
}
/**
\fn int32_t USBD_EndpointStall (uint8_t ep_addr, bool stall)
\brief Set/Clear Stall for USB Endpoint.
\param[in] ep_addr Endpoint Address
- ep_addr.0..3: Address
- ep_addr.7: Direction
\param[in] stall Operation
- \b false Clear
- \b true Set
\return \ref execution_status
*/
static int32_t USBD_EndpointStall (uint8_t ep_addr, bool stall) {
volatile ENDPOINT_t *ptr_ep;
uint8_t ep_num;
bool ep_dir;
ep_num = EP_NUM(ep_addr);
if (ep_num > USBD_MAX_ENDPOINT_NUM) { return ARM_DRIVER_ERROR; }
if (hw_powered == false) { return ARM_DRIVER_ERROR; }
ptr_ep = &ep[EP_ID(ep_addr)];
if (ptr_ep->active != 0U) { return ARM_DRIVER_ERROR_BUSY; }
ep_dir = (ep_addr & ARM_USB_ENDPOINT_DIRECTION_MASK) == ARM_USB_ENDPOINT_DIRECTION_MASK;
if (stall != 0U) { // Activate STALL
if (ep_dir != 0U) { // IN Endpoint
if ((OTG_DIEPCTL(ep_num) & OTG_FS_DIEPCTLx_EPENA) != 0U) {
// Set flush flag to Flush IN FIFO in Endpoint disabled interrupt
ptr_ep->in_flush = 1U;
OTG_DIEPCTL(ep_num) |= OTG_FS_DIEPCTLx_STALL | OTG_FS_DIEPCTLx_EPDIS;
} else {
OTG_DIEPCTL(ep_num) |= OTG_FS_DIEPCTLx_STALL;
USBD_FlushInEpFifo (ep_num);
}
} else { // OUT Endpoint
OTG->DCTL |= OTG_FS_DCTL_SGONAK; // Set Global OUT NAK
while ((OTG->GINTSTS & OTG_FS_GINTSTS_GONAKEFF) == 0U);
// Stall OUT Endpoint
if ((OTG_DOEPCTL(ep_num) & OTG_FS_DOEPCTLx_EPENA) != 0U) {
OTG_DOEPCTL(ep_num) |= OTG_FS_DOEPCTLx_STALL | OTG_FS_DOEPCTLx_EPDIS;
} else {
OTG_DOEPCTL(ep_num) |= OTG_FS_DOEPCTLx_STALL;
}
OTG->DCTL |= OTG_FS_DCTL_CGONAK; // Clear global NAK
}
} else { // Clear STALL
ptr_ep->in_nak = 0U;
ptr_ep->in_zlp = 0U;
if (ep_dir != 0U) { // IN Endpoint
if ((OTG_DIEPCTL(ep_num) & OTG_FS_DIEPCTLx_EPENA) != 0U) { // If Endpoint enabled
OTG_DIEPCTL(ep_num) |= OTG_FS_DIEPCTLx_EPDIS; // Disable Endpoint
}
// Set DATA0 PID for Interrupt and Bulk Endpoint
if (((OTG_DIEPCTL(ep_num) & OTG_FS_DIEPCTLx_EPTYP_MSK) >> OTG_FS_DIEPCTLx_EPTYP_POS) > 1U) {
OTG_DIEPCTL(ep_num) |= OTG_FS_DIEPCTLx_SD0PID;
}
OTG_DIEPCTL(ep_num) &= ~OTG_FS_DIEPCTLx_STALL; // Clear Stall
} else { // Clear OUT Endpoint stall
// Set DATA0 PID for Interrupt and Bulk Endpoint
if (((OTG_DOEPCTL(ep_num) & OTG_FS_DOEPCTLx_EPTYP_MSK) >> OTG_FS_DOEPCTLx_EPTYP_POS) > 1U) {
OTG_DOEPCTL(ep_num) |= OTG_FS_DOEPCTLx_SD0PID;
}
OTG_DOEPCTL(ep_num) &= ~OTG_FS_DOEPCTLx_STALL; // Clear Stall
}
}
return ARM_DRIVER_OK;
}
/**
\fn int32_t USBD_EndpointTransfer (uint8_t ep_addr, uint8_t *data, uint32_t num)
\brief Read data from or Write data to USB Endpoint.
\param[in] ep_addr Endpoint Address
- ep_addr.0..3: Address
- ep_addr.7: Direction
\param[out] data Pointer to buffer for data to read or with data to write
\param[in] num Number of data bytes to transfer
\return \ref execution_status
*/
static int32_t USBD_EndpointTransfer (uint8_t ep_addr, uint8_t *data, uint32_t num) {
volatile ENDPOINT_t *ptr_ep;
uint8_t ep_num;
bool ep_dir;
ep_num = EP_NUM(ep_addr);
if (ep_num > USBD_MAX_ENDPOINT_NUM) { return ARM_DRIVER_ERROR; }
if (hw_powered == false) { return ARM_DRIVER_ERROR; }
ptr_ep = &ep[EP_ID(ep_addr)];
if (ptr_ep->active != 0U) { return ARM_DRIVER_ERROR_BUSY; }
ep_dir = (ep_addr & ARM_USB_ENDPOINT_DIRECTION_MASK) == ARM_USB_ENDPOINT_DIRECTION_MASK;
ptr_ep->active = 1U;
ptr_ep->data = data;
ptr_ep->num = num;
ptr_ep->num_transferred_total = 0U;
ptr_ep->num_transferring = 0U;
if (ep_dir != 0U) { // IN Endpoint
if (OTG_EP_IN_TYPE(ep_num) != ARM_USB_ENDPOINT_ISOCHRONOUS) {
if (num == 0U) {
ptr_ep->in_zlp = 1U; // Send IN ZLP requested
}
ptr_ep->in_nak = 1U; // Set IN Endpoint NAK flag
OTG_DIEPCTL(ep_num) |= OTG_FS_DIEPCTLx_CNAK; // Clear NAK
OTG_DIEPCTL(ep_num) |= OTG_FS_DIEPCTLx_SNAK; // Set NAK
OTG->DIEPMSK |= OTG_FS_DIEPMSK_INEPNEM; // Enable NAK effective interrupt
}
} else { // OUT Endpoint
if (OTG_EP_OUT_TYPE(ep_num) != ARM_USB_ENDPOINT_ISOCHRONOUS) {
USBD_EndpointReadSet(ep_addr);
}
}
return ARM_DRIVER_OK;
}
/**
\fn uint32_t USBD_EndpointTransferGetResult (uint8_t ep_addr)
\brief Get result of USB Endpoint transfer.
\param[in] ep_addr Endpoint Address
- ep_addr.0..3: Address
- ep_addr.7: Direction
\return number of successfully transferred data bytes
*/
static uint32_t USBD_EndpointTransferGetResult (uint8_t ep_addr) {
if (EP_NUM(ep_addr) > USBD_MAX_ENDPOINT_NUM) { return 0U; }
return (ep[EP_ID(ep_addr)].num_transferred_total);
}
/**
\fn int32_t USBD_EndpointTransferAbort (uint8_t ep_addr)
\brief Abort current USB Endpoint transfer.
\param[in] ep_addr Endpoint Address
- ep_addr.0..3: Address
- ep_addr.7: Direction
\return \ref execution_status
*/
static int32_t USBD_EndpointTransferAbort (uint8_t ep_addr) {
volatile ENDPOINT_t *ptr_ep;
uint8_t ep_num;
ep_num = EP_NUM(ep_addr);
if (ep_num > USBD_MAX_ENDPOINT_NUM) { return ARM_DRIVER_ERROR; }
if (hw_powered == false) { return ARM_DRIVER_ERROR; }
ptr_ep = &ep[EP_ID(ep_addr)];
ptr_ep->num = 0U;
ptr_ep->in_nak = 0U;
ptr_ep->in_zlp = 0U;
if ((ep_addr & ARM_USB_ENDPOINT_DIRECTION_MASK) != 0U) {
if ((OTG_DIEPCTL(ep_num) & OTG_FS_DIEPCTLx_EPENA) != 0U) {
// Set flush flag to Flush IN FIFO in Endpoint disabled interrupt
ptr_ep->in_flush = 1U;
// Disable enabled Endpoint and set NAK
OTG_DIEPCTL(ep_num) |= OTG_FS_DIEPCTLx_EPDIS | OTG_FS_DIEPCTLx_SNAK;
} else {
// Endpoint is already disabled. Set NAK
OTG_DIEPCTL(ep_num) |= OTG_FS_DIEPCTLx_SNAK;
// Flush IN EP FIFO
USBD_FlushInEpFifo (ep_num);
}
} else {
if ((OTG_DOEPCTL(ep_num) & OTG_FS_DOEPCTLx_EPENA) != 0U) {
// Disable enabled Endpoint and set NAK
OTG_DOEPCTL(ep_num) |= OTG_FS_DOEPCTLx_EPDIS | OTG_FS_DOEPCTLx_SNAK;
} else {
// Endpoint is already disabled. Set NAK
OTG_DOEPCTL(ep_num) |= OTG_FS_DOEPCTLx_SNAK;
}
}
ptr_ep->active = 0U;
return ARM_DRIVER_OK;
}
/**
\fn uint16_t USBD_GetFrameNumber (void)
\brief Get current USB Frame Number.
\return Frame Number
*/
static uint16_t USBD_GetFrameNumber (void) {
if (hw_powered == false) { return 0U; }
return ((OTG->DSTS & OTG_FS_DSTS_FNSOF_MSK) >> OTG_FS_DSTS_FNSOF_POS);
}
/**
\fn void USBD_FS_IRQ (uint32_t gintsts)
\brief USB Device Interrupt Routine (IRQ).
*/
void USBD_FS_IRQ (uint32_t gintsts) {
volatile ENDPOINT_t *ptr_ep, *ptr_ep_in;
uint32_t val, msk, ep_int;
#if (USBD_FS_VBUS_DETECT == 1)
uint32_t gotgint;
#endif
uint16_t num;
uint8_t ep_num, i;
static uint32_t IsoInIncomplete = 0U;
if ((gintsts & OTG_FS_GINTSTS_USBRST) != 0U) { // Reset interrupt
OTG->GINTSTS = OTG_FS_GINTSTS_USBRST;
OTG->GINTMSK |= OTG_FS_GINTMSK_SOFM; // Unmask SOF interrupts (to detect initial SOF)
usbd_state.active = 0U;
USBD_Reset();
SignalDeviceEvent(ARM_USBD_EVENT_RESET);
}
if ((gintsts & OTG_FS_GINTSTS_USBSUSP) != 0U) { // Suspend interrupt
OTG->GINTSTS = OTG_FS_GINTSTS_USBSUSP;
OTG->PCGCCTL |= OTG_FS_PCGCCTL_STPPCLK; // Stop PHY clock
usbd_state.active = 0U;
SignalDeviceEvent(ARM_USBD_EVENT_SUSPEND);
}
if ((gintsts & OTG_FS_GINTSTS_WKUPINT) != 0U) { // Resume interrupt
OTG->GINTSTS = OTG_FS_GINTSTS_WKUPINT;
OTG->PCGCCTL &= ~OTG_FS_PCGCCTL_STPPCLK; // Start PHY clock
usbd_state.active = 1U;
SignalDeviceEvent(ARM_USBD_EVENT_RESUME);
}
if ((gintsts & OTG_FS_GINTSTS_ENUMDNE) != 0U) { // Speed enumeration completed
OTG->GINTSTS = OTG_FS_GINTSTS_ENUMDNE;
usbd_state.speed = ARM_USB_SPEED_FULL;
OTG->DCTL |= OTG_FS_DCTL_CGINAK; // Clear global IN NAK
OTG->DCTL |= OTG_FS_DCTL_CGONAK; // Clear global OUT NAK
}
if ((usbd_state.active == 0U) &&
(gintsts & OTG_FS_GINTSTS_SOF) != 0U) { // First SOF after Reset
OTG->GINTMSK &= ~OTG_FS_GINTMSK_SOFM; // Mask SOF interrupts
OTG->GINTSTS = OTG_FS_GINTSTS_SOF;
usbd_state.active = 1U;
SignalDeviceEvent(ARM_USBD_EVENT_RESUME);
}
if ((gintsts & OTG_FS_GINTSTS_RXFLVL) != 0U) { // Receive FIFO interrupt
val = OTG->GRXSTSP;
ep_num = val & 0x0FU;
num = (val >> 4) & 0x7FFU;
switch ((val >> 17) & 0x0FU) {
case 6: // Setup packet
// Read setup packet
setup_packet[0] = OTG_RX_FIFO;
setup_packet[1] = OTG_RX_FIFO;
// Analyze Setup packet for SetAddress
if ((setup_packet[0] & 0xFFFFU) == 0x0500U) {
USBD_DeviceSetAddress((setup_packet[0] >> 16) & 0xFFU);
}
setup_received = 1U;
break;
case 2: // OUT packet
USBD_ReadFromFifo(ep_num, num);
break;
case 1: // Global OUT NAK
case 3: // OUT transfer completed
case 4: // SETUP transaction completed
default:
break;
}
}
// OUT Packet
if ((gintsts & OTG_FS_GINTSTS_OEPINT) != 0U) {
msk = (((OTG->DAINT & OTG->DAINTMSK) >> 16) & 0xFFFFU);
ep_num = 0U;
do {
if (((msk >> ep_num) & 1U) != 0U) {
ep_int = OTG_DOEPINT(ep_num) & OTG->DOEPMSK;
ptr_ep = &ep[EP_ID(ep_num)];
if ((ep_int & OTG_FS_DOEPINTx_EPDISD) != 0U) { // If Endpoint disabled
if (OTG_EP_OUT_TYPE(ep_num) == ARM_USB_ENDPOINT_ISOCHRONOUS) {
// Isochronous OUT Endpoint
// Set packet count and transfer size
OTG_DOEPTSIZ(ep_num) = (1U << OTG_FS_DOEPTSIZx_PKTCNT_POS) |
(ptr_ep->max_packet_size);
// Set correct frame
if ((USBD_GetFrameNumber() & 1U) != 0U) { OTG_DOEPCTL(ep_num) |= OTG_FS_DOEPCTLx_SEVNFRM; }
else { OTG_DOEPCTL(ep_num) |= OTG_FS_DOEPCTLx_SODDFRM; }
OTG_DOEPCTL(ep_num) |= OTG_FS_DOEPCTLx_EPENA | OTG_FS_DOEPCTLx_CNAK;
}
OTG_DOEPINT(ep_num) = OTG_FS_DOEPINTx_EPDISD;
}
// Setup phase done interrupt
if ((ep_int & OTG_FS_DOEPINTx_STUP) != 0U) {
ptr_ep->num = 0U;
OTG_DOEPINT(ep_num) = OTG_FS_DOEPINTx_STUP;
SignalEndpointEvent(ep_num, ARM_USBD_EVENT_SETUP);
}
// Transfer complete interrupt
if ((ep_int & OTG_FS_DOEPINTx_XFCR) != 0U) {
OTG_DOEPINT(ep_num) = OTG_FS_DOEPINTx_XFCR;
if (ptr_ep->num != 0U) {
if (OTG_EP_OUT_TYPE(ep_num) != ARM_USB_ENDPOINT_ISOCHRONOUS) {
USBD_EndpointReadSet(ep_num);
}
} else {
ptr_ep->active = 0U;
SignalEndpointEvent(ep_num, ARM_USBD_EVENT_OUT);
}
}
}
ep_num++;
} while ((msk >> ep_num) != 0U);
}
// IN Packet
if ((gintsts & OTG_FS_GINTSTS_IEPINT) != 0U) {
msk = (OTG->DAINT & OTG->DAINTMSK & 0xFFFFU);
ep_num = 0U;
do {
if (((msk >> ep_num) & 1U) != 0U) {
ep_int = OTG_DIEPINT(ep_num) & OTG->DIEPMSK;
ptr_ep = &ep[EP_ID(ep_num | ARM_USB_ENDPOINT_DIRECTION_MASK)];
if ((ep_int & OTG_FS_DIEPINTx_EPDISD) != 0U) { // If Endpoint disabled
OTG_DIEPINT(ep_num) = OTG_FS_DIEPINTx_EPDISD;
if (ptr_ep->in_flush == 1U) {
// Clear flush flag
ptr_ep->in_flush = 0U;
// Flush IN Endpoint FIFO
USBD_FlushInEpFifo(ep_num);
} else if (OTG_EP_IN_TYPE(ep_num) == ARM_USB_ENDPOINT_ISOCHRONOUS) {
if ((IsoInIncomplete & (1U << ep_num)) != 0U) {
// Flush IN Endpoint FIFO and write new data if available
USBD_FlushInEpFifo(ep_num);
if (ptr_ep->data != NULL) {
ptr_ep->num += ptr_ep->num_transferring;
USBD_WriteToFifo(ep_num | ARM_USB_ENDPOINT_DIRECTION_MASK);
}
IsoInIncomplete &= ~(1U << ep_num);
}
}
}
// IN Endpoint NAK effective
if ((ep_int & OTG_FS_DIEPINTx_INEPNE) != 0U) {
if (ptr_ep->in_nak != 0U) {
ptr_ep->in_nak = 0U;
val = 0U;
ptr_ep_in = &ep[0];
for (i = 0U; i < USBD_MAX_ENDPOINT_NUM; i++) {
val |= ptr_ep_in->in_nak;
ptr_ep_in += 2U;
}
// If no more forced NAKs, disable IN NAK effective interrupt
if (val == 0U) { OTG->DIEPMSK &= ~OTG_FS_DIEPMSK_INEPNEM; }
// If Data available, write Data
if ((ptr_ep->num != 0U) || (ptr_ep->in_zlp != 0U)) {
USBD_WriteToFifo(ep_num | ARM_USB_ENDPOINT_DIRECTION_MASK);
}
}
OTG_DIEPINT(ep_num) = OTG_FS_DIEPINTx_INEPNE;
}
// Transmit completed
if ((ep_int & OTG_FS_DIEPINTx_XFCR) != 0U) {
OTG_DIEPINT(ep_num) = OTG_FS_DIEPINTx_XFCR;
ptr_ep->num_transferred_total += ptr_ep->num_transferring;
if (ptr_ep->num == 0U) {
ptr_ep->data = NULL;
ptr_ep->active = 0U;
SignalEndpointEvent(ep_num | ARM_USB_ENDPOINT_DIRECTION_MASK, ARM_USBD_EVENT_IN);
} else {
if (OTG_EP_IN_TYPE(ep_num) != ARM_USB_ENDPOINT_ISOCHRONOUS) {
USBD_WriteToFifo(ep_num | ARM_USB_ENDPOINT_DIRECTION_MASK);
}
}
}
}
ep_num++;
} while ((msk >> ep_num != 0U));
}
// End of periodic frame
if ((gintsts & OTG_FS_GINTSTS_EOPF) != 0U) {
// Clear interrupt flags
OTG->GINTSTS = OTG_FS_GINTSTS_EOPF | OTG_FS_GINTSTS_IPXFR | OTG_FS_GINTSTS_IISOIXFR;
// Check enabled isochronous OUT Endpoints
for (ep_num = 1U; ep_num <= USBD_MAX_ENDPOINT_NUM; ep_num++) {
if (OTG_EP_OUT_TYPE(ep_num) != ARM_USB_ENDPOINT_ISOCHRONOUS) { continue; }
if ((OTG_DOEPCTL(ep_num) & OTG_FS_DOEPCTLx_USBAEP) == 0U) { continue; }
if ((gintsts & OTG_FS_GINTSTS_IPXFR) != 0U) {
// Incomplete Isochronous OUT transfer
if ((USBD_GetFrameNumber() & 1U) == ((OTG_DOEPCTL(ep_num) >> OTG_FS_DOEPCTLx_EONUM_POS) & 1U)) {
if ((OTG_DOEPCTL(ep_num) & OTG_FS_DOEPCTLx_EPENA) != 0U) {
OTG_DOEPCTL(ep_num) |= OTG_FS_DOEPCTLx_EPDIS;
}
}
} else {
// Isochronous OUT transfer completed
if (ep[EP_ID(ep_num)].num != 0U) {
USBD_EndpointReadSet(ep_num);
}
}
}
// Check enabled isochronous IN Endpoints
for (ep_num = 1U; ep_num <= USBD_MAX_ENDPOINT_NUM; ep_num++) {
if (OTG_EP_IN_TYPE(ep_num) != ARM_USB_ENDPOINT_ISOCHRONOUS) { continue; }
if ((OTG_DIEPCTL(ep_num) & OTG_FS_DIEPCTLx_USBAEP) == 0U) { continue; }
if ((gintsts & OTG_FS_GINTSTS_IISOIXFR) != 0U) {
if ((OTG_DIEPCTL(ep_num) & OTG_FS_DIEPCTLx_EPENA) != 0U) {
if ((USBD_GetFrameNumber() & 1U) == ((OTG_DIEPCTL(ep_num) >> OTG_FS_DIEPCTLx_EONUM_POS) & 1U)) {
IsoInIncomplete |= (1U << ep_num);
OTG_DIEPCTL(ep_num) |= OTG_FS_DIEPCTLx_EPDIS | OTG_FS_DIEPCTLx_SNAK;
}
}
} else {
if (ep[EP_ID(ep_num | ARM_USB_ENDPOINT_DIRECTION_MASK)].num != 0U) {
USBD_WriteToFifo (ep_num | ARM_USB_ENDPOINT_DIRECTION_MASK);
}
}
}
}
#if (USBD_FS_VBUS_DETECT == 1)
if ((gintsts & OTG_FS_GINTSTS_SRQINT) != 0U) {
OTG->GINTSTS = OTG_FS_GINTSTS_SRQINT;
usbd_state.vbus = 1U;
SignalDeviceEvent(ARM_USBD_EVENT_VBUS_ON);
}
if ((gintsts & OTG_FS_GINTSTS_OTGINT) != 0U) {
gotgint = OTG->GOTGINT;
OTG->GOTGINT = gotgint;
if ((gotgint & OTG_FS_GOTGINT_SEDET) != 0U) {
usbd_state.vbus = 0U;
usbd_state.speed = 0U;
usbd_state.active = 0U;
SignalDeviceEvent(ARM_USBD_EVENT_VBUS_OFF);
}
}
#endif
}
ARM_DRIVER_USBD Driver_USBD0 = {
USBD_GetVersion,
USBD_GetCapabilities,
USBD_Initialize,
USBD_Uninitialize,
USBD_PowerControl,
USBD_DeviceConnect,
USBD_DeviceDisconnect,
USBD_DeviceGetState,
USBD_DeviceRemoteWakeup,
USBD_DeviceSetAddress,
USBD_ReadSetupPacket,
USBD_EndpointConfigure,
USBD_EndpointUnconfigure,
USBD_EndpointStall,
USBD_EndpointTransfer,
USBD_EndpointTransferGetResult,
USBD_EndpointTransferAbort,
USBD_GetFrameNumber
};
|
682079.c | /***************************************************************
* Description:
*
* This file is for RTL8723B Co-exist mechanism
*
* History
* 2012/11/15 Cosa first check in.
*
***************************************************************/
/***************************************************************
* include files
***************************************************************/
#include "halbt_precomp.h"
#if 1
/***************************************************************
* Global variables, these are static variables
***************************************************************/
static struct coex_dm_8723b_1ant glcoex_dm_8723b_1ant;
static struct coex_dm_8723b_1ant *coex_dm = &glcoex_dm_8723b_1ant;
static struct coex_sta_8723b_1ant glcoex_sta_8723b_1ant;
static struct coex_sta_8723b_1ant *coex_sta = &glcoex_sta_8723b_1ant;
const char *const GLBtInfoSrc8723b1Ant[]={
"BT Info[wifi fw]",
"BT Info[bt rsp]",
"BT Info[bt auto report]",
};
u32 glcoex_ver_date_8723b_1ant = 20130906;
u32 glcoex_ver_8723b_1ant = 0x45;
/***************************************************************
* local function proto type if needed
***************************************************************/
/***************************************************************
* local function start with halbtc8723b1ant_
***************************************************************/
u8 halbtc8723b1ant_bt_rssi_state(u8 level_num, u8 rssi_thresh, u8 rssi_thresh1)
{
s32 bt_rssi=0;
u8 bt_rssi_state = coex_sta->pre_bt_rssi_state;
bt_rssi = coex_sta->bt_rssi;
if (level_num == 2){
if ((coex_sta->pre_bt_rssi_state == BTC_RSSI_STATE_LOW) ||
(coex_sta->pre_bt_rssi_state == BTC_RSSI_STATE_STAY_LOW)) {
if (bt_rssi >= rssi_thresh +
BTC_RSSI_COEX_THRESH_TOL_8723B_1ANT) {
bt_rssi_state = BTC_RSSI_STATE_HIGH;
BTC_PRINT(BTC_MSG_ALGORITHM, ALGO_BT_RSSI_STATE,
"[BTCoex], BT Rssi state "
"switch to High\n");
} else {
bt_rssi_state = BTC_RSSI_STATE_STAY_LOW;
BTC_PRINT(BTC_MSG_ALGORITHM, ALGO_BT_RSSI_STATE,
"[BTCoex], BT Rssi state "
"stay at Low\n");
}
} else {
if (bt_rssi < rssi_thresh) {
bt_rssi_state = BTC_RSSI_STATE_LOW;
BTC_PRINT(BTC_MSG_ALGORITHM, ALGO_BT_RSSI_STATE,
"[BTCoex], BT Rssi state "
"switch to Low\n");
} else {
bt_rssi_state = BTC_RSSI_STATE_STAY_HIGH;
BTC_PRINT(BTC_MSG_ALGORITHM, ALGO_BT_RSSI_STATE,
"[BTCoex], BT Rssi state "
"stay at High\n");
}
}
} else if (level_num == 3) {
if (rssi_thresh > rssi_thresh1) {
BTC_PRINT(BTC_MSG_ALGORITHM, ALGO_BT_RSSI_STATE,
"[BTCoex], BT Rssi thresh error!!\n");
return coex_sta->pre_bt_rssi_state;
}
if ((coex_sta->pre_bt_rssi_state == BTC_RSSI_STATE_LOW) ||
(coex_sta->pre_bt_rssi_state == BTC_RSSI_STATE_STAY_LOW)) {
if (bt_rssi >= rssi_thresh +
BTC_RSSI_COEX_THRESH_TOL_8723B_1ANT) {
bt_rssi_state = BTC_RSSI_STATE_MEDIUM;
BTC_PRINT(BTC_MSG_ALGORITHM, ALGO_BT_RSSI_STATE,
"[BTCoex], BT Rssi state "
"switch to Medium\n");
} else {
bt_rssi_state = BTC_RSSI_STATE_STAY_LOW;
BTC_PRINT(BTC_MSG_ALGORITHM, ALGO_BT_RSSI_STATE,
"[BTCoex], BT Rssi state "
"stay at Low\n");
}
} else if ((coex_sta->pre_bt_rssi_state ==
BTC_RSSI_STATE_MEDIUM) ||
(coex_sta->pre_bt_rssi_state ==
BTC_RSSI_STATE_STAY_MEDIUM)) {
if (bt_rssi >= rssi_thresh1 +
BTC_RSSI_COEX_THRESH_TOL_8723B_1ANT) {
bt_rssi_state = BTC_RSSI_STATE_HIGH;
BTC_PRINT(BTC_MSG_ALGORITHM, ALGO_BT_RSSI_STATE,
"[BTCoex], BT Rssi state "
"switch to High\n");
} else if (bt_rssi < rssi_thresh) {
bt_rssi_state = BTC_RSSI_STATE_LOW;
BTC_PRINT(BTC_MSG_ALGORITHM, ALGO_BT_RSSI_STATE,
"[BTCoex], BT Rssi state "
"switch to Low\n");
} else {
bt_rssi_state = BTC_RSSI_STATE_STAY_MEDIUM;
BTC_PRINT(BTC_MSG_ALGORITHM, ALGO_BT_RSSI_STATE,
"[BTCoex], BT Rssi state "
"stay at Medium\n");
}
} else {
if (bt_rssi < rssi_thresh1) {
bt_rssi_state = BTC_RSSI_STATE_MEDIUM;
BTC_PRINT(BTC_MSG_ALGORITHM, ALGO_BT_RSSI_STATE,
"[BTCoex], BT Rssi state "
"switch to Medium\n");
} else {
bt_rssi_state = BTC_RSSI_STATE_STAY_HIGH;
BTC_PRINT(BTC_MSG_ALGORITHM, ALGO_BT_RSSI_STATE,
"[BTCoex], BT Rssi state "
"stay at High\n");
}
}
}
coex_sta->pre_bt_rssi_state = bt_rssi_state;
return bt_rssi_state;
}
u8 halbtc8723b1ant_wifi_rssi_state(struct btc_coexist *btcoexist,
u8 index, u8 level_num,
u8 rssi_thresh, u8 rssi_thresh1)
{
s32 wifi_rssi=0;
u8 wifi_rssi_state = coex_sta->pre_wifi_rssi_state[index];
btcoexist->btc_get(btcoexist,
BTC_GET_S4_WIFI_RSSI, &wifi_rssi);
if (level_num == 2) {
if ((coex_sta->pre_wifi_rssi_state[index] ==
BTC_RSSI_STATE_LOW) ||
(coex_sta->pre_wifi_rssi_state[index] ==
BTC_RSSI_STATE_STAY_LOW)) {
if (wifi_rssi >= rssi_thresh +
BTC_RSSI_COEX_THRESH_TOL_8723B_1ANT) {
wifi_rssi_state = BTC_RSSI_STATE_HIGH;
BTC_PRINT(BTC_MSG_ALGORITHM,
ALGO_WIFI_RSSI_STATE,
"[BTCoex], wifi RSSI state "
"switch to High\n");
} else {
wifi_rssi_state = BTC_RSSI_STATE_STAY_LOW;
BTC_PRINT(BTC_MSG_ALGORITHM,
ALGO_WIFI_RSSI_STATE,
"[BTCoex], wifi RSSI state "
"stay at Low\n");
}
} else {
if (wifi_rssi < rssi_thresh) {
wifi_rssi_state = BTC_RSSI_STATE_LOW;
BTC_PRINT(BTC_MSG_ALGORITHM,
ALGO_WIFI_RSSI_STATE,
"[BTCoex], wifi RSSI state "
"switch to Low\n");
} else {
wifi_rssi_state = BTC_RSSI_STATE_STAY_HIGH;
BTC_PRINT(BTC_MSG_ALGORITHM,
ALGO_WIFI_RSSI_STATE,
"[BTCoex], wifi RSSI state "
"stay at High\n");
}
}
} else if (level_num == 3) {
if (rssi_thresh > rssi_thresh1) {
BTC_PRINT(BTC_MSG_ALGORITHM, ALGO_WIFI_RSSI_STATE,
"[BTCoex], wifi RSSI thresh error!!\n");
return coex_sta->pre_wifi_rssi_state[index];
}
if ((coex_sta->pre_wifi_rssi_state[index] ==
BTC_RSSI_STATE_LOW) ||
(coex_sta->pre_wifi_rssi_state[index] ==
BTC_RSSI_STATE_STAY_LOW)) {
if (wifi_rssi >= rssi_thresh +
BTC_RSSI_COEX_THRESH_TOL_8723B_1ANT) {
wifi_rssi_state = BTC_RSSI_STATE_MEDIUM;
BTC_PRINT(BTC_MSG_ALGORITHM,
ALGO_WIFI_RSSI_STATE,
"[BTCoex], wifi RSSI state "
"switch to Medium\n");
} else {
wifi_rssi_state = BTC_RSSI_STATE_STAY_LOW;
BTC_PRINT(BTC_MSG_ALGORITHM,
ALGO_WIFI_RSSI_STATE,
"[BTCoex], wifi RSSI state "
"stay at Low\n");
}
} else if ((coex_sta->pre_wifi_rssi_state[index] ==
BTC_RSSI_STATE_MEDIUM) ||
(coex_sta->pre_wifi_rssi_state[index] ==
BTC_RSSI_STATE_STAY_MEDIUM)) {
if (wifi_rssi >= rssi_thresh1 +
BTC_RSSI_COEX_THRESH_TOL_8723B_1ANT) {
wifi_rssi_state = BTC_RSSI_STATE_HIGH;
BTC_PRINT(BTC_MSG_ALGORITHM,
ALGO_WIFI_RSSI_STATE,
"[BTCoex], wifi RSSI state "
"switch to High\n");
} else if (wifi_rssi < rssi_thresh) {
wifi_rssi_state = BTC_RSSI_STATE_LOW;
BTC_PRINT(BTC_MSG_ALGORITHM,
ALGO_WIFI_RSSI_STATE,
"[BTCoex], wifi RSSI state "
"switch to Low\n");
} else {
wifi_rssi_state = BTC_RSSI_STATE_STAY_MEDIUM;
BTC_PRINT(BTC_MSG_ALGORITHM,
ALGO_WIFI_RSSI_STATE,
"[BTCoex], wifi RSSI state "
"stay at Medium\n");
}
} else {
if (wifi_rssi < rssi_thresh1) {
wifi_rssi_state = BTC_RSSI_STATE_MEDIUM;
BTC_PRINT(BTC_MSG_ALGORITHM,
ALGO_WIFI_RSSI_STATE,
"[BTCoex], wifi RSSI state "
"switch to Medium\n");
} else {
wifi_rssi_state = BTC_RSSI_STATE_STAY_HIGH;
BTC_PRINT(BTC_MSG_ALGORITHM,
ALGO_WIFI_RSSI_STATE,
"[BTCoex], wifi RSSI state "
"stay at High\n");
}
}
}
coex_sta->pre_wifi_rssi_state[index] = wifi_rssi_state;
return wifi_rssi_state;
}
void halbtc8723b1ant_updatera_mask(struct btc_coexist *btcoexist,
bool force_exec, u32 dis_rate_mask)
{
coex_dm->curra_mask = dis_rate_mask;
if (force_exec || (coex_dm->prera_mask != coex_dm->curra_mask))
btcoexist->btc_set(btcoexist, BTC_SET_ACT_UPDATE_ra_mask,
&coex_dm->curra_mask);
coex_dm->prera_mask = coex_dm->curra_mask;
}
void halbtc8723b1ant_auto_rate_fallback_retry(struct btc_coexist *btcoexist,
bool force_exec, u8 type)
{
bool wifi_under_bmode = false;
coex_dm->cur_arfr_type = type;
if (force_exec || (coex_dm->pre_arfr_type != coex_dm->cur_arfr_type)) {
switch (coex_dm->cur_arfr_type) {
case 0: /* normal mode */
btcoexist->btc_write_4byte(btcoexist, 0x430,
coex_dm->backup_arfr_cnt1);
btcoexist->btc_write_4byte(btcoexist, 0x434,
coex_dm->backup_arfr_cnt2);
break;
case 1:
btcoexist->btc_get(btcoexist,
BTC_GET_BL_WIFI_UNDER_B_MODE,
&wifi_under_bmode);
if (wifi_under_bmode) {
btcoexist->btc_write_4byte(btcoexist,
0x430, 0x0);
btcoexist->btc_write_4byte(btcoexist,
0x434, 0x01010101);
} else {
btcoexist->btc_write_4byte(btcoexist,
0x430, 0x0);
btcoexist->btc_write_4byte(btcoexist,
0x434, 0x04030201);
}
break;
default:
break;
}
}
coex_dm->pre_arfr_type = coex_dm->cur_arfr_type;
}
void halbtc8723b1ant_retry_limit(struct btc_coexist *btcoexist,
bool force_exec, u8 type)
{
coex_dm->cur_retry_limit_type = type;
if (force_exec || (coex_dm->pre_retry_limit_type !=
coex_dm->cur_retry_limit_type)) {
switch (coex_dm->cur_retry_limit_type) {
case 0: /* normal mode */
btcoexist->btc_write_2byte(btcoexist, 0x42a,
coex_dm->backup_retry_limit);
break;
case 1: /* retry limit=8 */
btcoexist->btc_write_2byte(btcoexist, 0x42a, 0x0808);
break;
default:
break;
}
}
coex_dm->pre_retry_limit_type = coex_dm->cur_retry_limit_type;
}
void halbtc8723b1ant_ampdu_maxtime(struct btc_coexist *btcoexist,
bool force_exec, u8 type)
{
coex_dm->cur_ampdu_time_type = type;
if (force_exec || (coex_dm->pre_ampdu_time_type !=
coex_dm->cur_ampdu_time_type)) {
switch (coex_dm->cur_ampdu_time_type) {
case 0: /* normal mode */
btcoexist->btc_write_1byte(btcoexist, 0x456,
coex_dm->backup_ampdu_max_time);
break;
case 1: /* AMPDU timw = 0x38 * 32us */
btcoexist->btc_write_1byte(btcoexist,
0x456, 0x38);
break;
default:
break;
}
}
coex_dm->pre_ampdu_time_type = coex_dm->cur_ampdu_time_type;
}
void halbtc8723b1ant_limited_tx(struct btc_coexist *btcoexist,
bool force_exec, u8 ra_maskType, u8 arfr_type,
u8 retry_limit_type, u8 ampdu_time_type)
{
switch (ra_maskType) {
case 0: /* normal mode */
halbtc8723b1ant_updatera_mask(btcoexist, force_exec, 0x0);
break;
case 1: /* disable cck 1/2 */
halbtc8723b1ant_updatera_mask(btcoexist, force_exec,
0x00000003);
break;
/* disable cck 1/2/5.5, ofdm 6/9/12/18/24, mcs 0/1/2/3/4*/
case 2:
halbtc8723b1ant_updatera_mask(btcoexist, force_exec,
0x0001f1f7);
break;
default:
break;
}
halbtc8723b1ant_auto_rate_fallback_retry(btcoexist, force_exec,
arfr_type);
halbtc8723b1ant_retry_limit(btcoexist, force_exec, retry_limit_type);
halbtc8723b1ant_ampdu_maxtime(btcoexist, force_exec, ampdu_time_type);
}
void halbtc8723b1ant_limited_rx(struct btc_coexist *btcoexist,
bool force_exec, bool rej_ap_agg_pkt,
bool b_bt_ctrl_agg_buf_size, u8 agg_buf_size)
{
bool reject_rx_agg = rej_ap_agg_pkt;
bool bt_ctrl_rx_agg_size = b_bt_ctrl_agg_buf_size;
u8 rxAggSize = agg_buf_size;
/**********************************************
* Rx Aggregation related setting
**********************************************/
btcoexist->btc_set(btcoexist, BTC_SET_BL_TO_REJ_AP_AGG_PKT,
&reject_rx_agg);
/* decide BT control aggregation buf size or not */
btcoexist->btc_set(btcoexist, BTC_SET_BL_BT_CTRL_AGG_SIZE,
&bt_ctrl_rx_agg_size);
/* aggregation buf size, only work
*when BT control Rx aggregation size. */
btcoexist->btc_set(btcoexist, BTC_SET_U1_AGG_BUF_SIZE, &rxAggSize);
/* real update aggregation setting */
btcoexist->btc_set(btcoexist, BTC_SET_ACT_AGGREGATE_CTRL, NULL);
}
void halbtc8723b1ant_monitor_bt_ctr(struct btc_coexist *btcoexist)
{
u32 reg_hp_txrx, reg_lp_txrx, u32tmp;
u32 reg_hp_tx = 0, reg_hp_rx = 0;
u32 reg_lp_tx = 0, reg_lp_rx = 0;
reg_hp_txrx = 0x770;
reg_lp_txrx = 0x774;
u32tmp = btcoexist->btc_read_4byte(btcoexist, reg_hp_txrx);
reg_hp_tx = u32tmp & MASKLWORD;
reg_hp_rx = (u32tmp & MASKHWORD) >> 16;
u32tmp = btcoexist->btc_read_4byte(btcoexist, reg_lp_txrx);
reg_lp_tx = u32tmp & MASKLWORD;
reg_lp_rx = (u32tmp & MASKHWORD) >> 16;
coex_sta->high_priority_tx = reg_hp_tx;
coex_sta->high_priority_rx = reg_hp_rx;
coex_sta->low_priority_tx = reg_lp_tx;
coex_sta->low_priority_rx = reg_lp_rx;
/* reset counter */
btcoexist->btc_write_1byte(btcoexist, 0x76e, 0xc);
}
void halbtc8723b1ant_query_bt_info(struct btc_coexist *btcoexist)
{
u8 h2c_parameter[1] = {0};
coex_sta->c2h_bt_info_req_sent = true;
h2c_parameter[0] |= BIT0; /* trigger*/
BTC_PRINT(BTC_MSG_ALGORITHM, ALGO_TRACE_FW_EXEC,
"[BTCoex], Query Bt Info, FW write 0x61=0x%x\n",
h2c_parameter[0]);
btcoexist->btc_fill_h2c(btcoexist, 0x61, 1, h2c_parameter);
}
bool halbtc8723b1ant_is_wifi_status_changed(struct btc_coexist *btcoexist)
{
static bool pre_wifi_busy = false;
static bool pre_under_4way = false, pre_bt_hs_on = false;
bool wifi_busy = false, under_4way = false, bt_hs_on = false;
bool wifi_connected = false;
btcoexist->btc_get(btcoexist, BTC_GET_BL_WIFI_CONNECTED,
&wifi_connected);
btcoexist->btc_get(btcoexist, BTC_GET_BL_WIFI_BUSY, &wifi_busy);
btcoexist->btc_get(btcoexist, BTC_GET_BL_HS_OPERATION, &bt_hs_on);
btcoexist->btc_get(btcoexist, BTC_GET_BL_WIFI_4_WAY_PROGRESS,
&under_4way);
if (wifi_connected) {
if (wifi_busy != pre_wifi_busy) {
pre_wifi_busy = wifi_busy;
return true;
}
if (under_4way != pre_under_4way) {
pre_under_4way = under_4way;
return true;
}
if (bt_hs_on != pre_bt_hs_on) {
pre_bt_hs_on = bt_hs_on;
return true;
}
}
return false;
}
void halbtc8723b1ant_update_bt_link_info(struct btc_coexist *btcoexist)
{
struct btc_bt_link_info *bt_link_info = &btcoexist->bt_link_info;
bool bt_hs_on = false;
btcoexist->btc_get(btcoexist, BTC_GET_BL_HS_OPERATION, &bt_hs_on);
bt_link_info->bt_link_exist = coex_sta->bt_link_exist;
bt_link_info->sco_exist = coex_sta->sco_exist;
bt_link_info->a2dp_exist = coex_sta->a2dp_exist;
bt_link_info->pan_exist = coex_sta->pan_exist;
bt_link_info->hid_exist = coex_sta->hid_exist;
/* work around for HS mode. */
if (bt_hs_on) {
bt_link_info->pan_exist = true;
bt_link_info->bt_link_exist = true;
}
/* check if Sco only */
if (bt_link_info->sco_exist && !bt_link_info->a2dp_exist &&
!bt_link_info->pan_exist && !bt_link_info->hid_exist)
bt_link_info->sco_only = true;
else
bt_link_info->sco_only = false;
/* check if A2dp only */
if (!bt_link_info->sco_exist && bt_link_info->a2dp_exist &&
!bt_link_info->pan_exist && !bt_link_info->hid_exist)
bt_link_info->a2dp_only = true;
else
bt_link_info->a2dp_only = false;
/* check if Pan only */
if (!bt_link_info->sco_exist && !bt_link_info->a2dp_exist &&
bt_link_info->pan_exist && !bt_link_info->hid_exist)
bt_link_info->pan_only = true;
else
bt_link_info->pan_only = false;
/* check if Hid only */
if (!bt_link_info->sco_exist && !bt_link_info->a2dp_exist &&
!bt_link_info->pan_exist && bt_link_info->hid_exist )
bt_link_info->hid_only = true;
else
bt_link_info->hid_only = false;
}
u8 halbtc8723b1ant_action_algorithm(struct btc_coexist *btcoexist)
{
struct btc_bt_link_info *bt_link_info = &btcoexist->bt_link_info;
bool bt_hs_on = false;
u8 algorithm = BT_8723B_1ANT_COEX_ALGO_UNDEFINED;
u8 numOfDiffProfile = 0;
btcoexist->btc_get(btcoexist, BTC_GET_BL_HS_OPERATION, &bt_hs_on);
if (!bt_link_info->bt_link_exist) {
BTC_PRINT(BTC_MSG_ALGORITHM, ALGO_TRACE,
"[BTCoex], No BT link exists!!!\n");
return algorithm;
}
if (bt_link_info->sco_exist)
numOfDiffProfile++;
if (bt_link_info->hid_exist)
numOfDiffProfile++;
if (bt_link_info->pan_exist)
numOfDiffProfile++;
if (bt_link_info->a2dp_exist)
numOfDiffProfile++;
if (numOfDiffProfile == 1) {
if (bt_link_info->sco_exist) {
BTC_PRINT(BTC_MSG_ALGORITHM, ALGO_TRACE,
"[BTCoex], BT Profile = SCO only\n");
algorithm = BT_8723B_1ANT_COEX_ALGO_SCO;
} else {
if (bt_link_info->hid_exist) {
BTC_PRINT(BTC_MSG_ALGORITHM, ALGO_TRACE,
"[BTCoex], BT Profile = HID only\n");
algorithm = BT_8723B_1ANT_COEX_ALGO_HID;
} else if (bt_link_info->a2dp_exist) {
BTC_PRINT(BTC_MSG_ALGORITHM, ALGO_TRACE,
"[BTCoex], BT Profile = A2DP only\n");
algorithm = BT_8723B_1ANT_COEX_ALGO_A2DP;
} else if (bt_link_info->pan_exist) {
if (bt_hs_on) {
BTC_PRINT(BTC_MSG_ALGORITHM, ALGO_TRACE,
"[BTCoex], BT Profile = "
"PAN(HS) only\n");
algorithm =
BT_8723B_1ANT_COEX_ALGO_PANHS;
} else {
BTC_PRINT(BTC_MSG_ALGORITHM, ALGO_TRACE,
"[BTCoex], BT Profile = "
"PAN(EDR) only\n");
algorithm =
BT_8723B_1ANT_COEX_ALGO_PANEDR;
}
}
}
} else if (numOfDiffProfile == 2) {
if (bt_link_info->sco_exist) {
if (bt_link_info->hid_exist) {
BTC_PRINT(BTC_MSG_ALGORITHM, ALGO_TRACE,
"[BTCoex], BT Profile = SCO + HID\n");
algorithm = BT_8723B_1ANT_COEX_ALGO_HID;
} else if (bt_link_info->a2dp_exist) {
BTC_PRINT(BTC_MSG_ALGORITHM, ALGO_TRACE,
"[BTCoex], BT Profile = "
"SCO + A2DP ==> SCO\n");
algorithm = BT_8723B_1ANT_COEX_ALGO_SCO;
} else if (bt_link_info->pan_exist) {
if (bt_hs_on) {
BTC_PRINT(BTC_MSG_ALGORITHM, ALGO_TRACE,
"[BTCoex], BT Profile "
"= SCO + PAN(HS)\n");
algorithm = BT_8723B_1ANT_COEX_ALGO_SCO;
} else {
BTC_PRINT(BTC_MSG_ALGORITHM, ALGO_TRACE,
"[BTCoex], BT Profile "
"= SCO + PAN(EDR)\n");
algorithm =
BT_8723B_1ANT_COEX_ALGO_PANEDR_HID;
}
}
} else {
if (bt_link_info->hid_exist &&
bt_link_info->a2dp_exist) {
BTC_PRINT(BTC_MSG_ALGORITHM, ALGO_TRACE,
"[BTCoex], BT Profile = "
"HID + A2DP\n");
algorithm = BT_8723B_1ANT_COEX_ALGO_HID_A2DP;
} else if (bt_link_info->hid_exist &&
bt_link_info->pan_exist) {
if (bt_hs_on) {
BTC_PRINT(BTC_MSG_ALGORITHM, ALGO_TRACE,
"[BTCoex], BT Profile = "
"HID + PAN(HS)\n");
algorithm =
BT_8723B_1ANT_COEX_ALGO_HID_A2DP;
} else {
BTC_PRINT(BTC_MSG_ALGORITHM, ALGO_TRACE,
"[BTCoex], BT Profile = "
"HID + PAN(EDR)\n");
algorithm =
BT_8723B_1ANT_COEX_ALGO_PANEDR_HID;
}
} else if (bt_link_info->pan_exist &&
bt_link_info->a2dp_exist) {
if (bt_hs_on) {
BTC_PRINT(BTC_MSG_ALGORITHM, ALGO_TRACE,
"[BTCoex], BT Profile = "
"A2DP + PAN(HS)\n");
algorithm =
BT_8723B_1ANT_COEX_ALGO_A2DP_PANHS;
} else {
BTC_PRINT(BTC_MSG_ALGORITHM, ALGO_TRACE,
"[BTCoex], BT Profile = "
"A2DP + PAN(EDR)\n");
algorithm =
BT_8723B_1ANT_COEX_ALGO_PANEDR_A2DP;
}
}
}
} else if (numOfDiffProfile == 3) {
if (bt_link_info->sco_exist) {
if (bt_link_info->hid_exist &&
bt_link_info->a2dp_exist) {
BTC_PRINT(BTC_MSG_ALGORITHM, ALGO_TRACE,
"[BTCoex], BT Profile = "
"SCO + HID + A2DP ==> HID\n");
algorithm = BT_8723B_1ANT_COEX_ALGO_HID;
} else if (bt_link_info->hid_exist &&
bt_link_info->pan_exist) {
if (bt_hs_on) {
BTC_PRINT(BTC_MSG_ALGORITHM, ALGO_TRACE,
"[BTCoex], BT Profile = "
"SCO + HID + PAN(HS)\n");
algorithm =
BT_8723B_1ANT_COEX_ALGO_HID_A2DP;
} else {
BTC_PRINT(BTC_MSG_ALGORITHM, ALGO_TRACE,
"[BTCoex], BT Profile = "
"SCO + HID + PAN(EDR)\n");
algorithm =
BT_8723B_1ANT_COEX_ALGO_PANEDR_HID;
}
} else if (bt_link_info->pan_exist &&
bt_link_info->a2dp_exist) {
if (bt_hs_on) {
BTC_PRINT(BTC_MSG_ALGORITHM, ALGO_TRACE,
"[BTCoex], BT Profile = "
"SCO + A2DP + PAN(HS)\n");
algorithm = BT_8723B_1ANT_COEX_ALGO_SCO;
} else {
BTC_PRINT(BTC_MSG_ALGORITHM, ALGO_TRACE,
"[BTCoex], BT Profile = SCO + "
"A2DP + PAN(EDR) ==> HID\n");
algorithm =
BT_8723B_1ANT_COEX_ALGO_PANEDR_HID;
}
}
} else {
if (bt_link_info->hid_exist &&
bt_link_info->pan_exist &&
bt_link_info->a2dp_exist) {
if (bt_hs_on) {
BTC_PRINT(BTC_MSG_ALGORITHM, ALGO_TRACE,
"[BTCoex], BT Profile = "
"HID + A2DP + PAN(HS)\n");
algorithm =
BT_8723B_1ANT_COEX_ALGO_HID_A2DP;
} else {
BTC_PRINT(BTC_MSG_ALGORITHM, ALGO_TRACE,
"[BTCoex], BT Profile = "
"HID + A2DP + PAN(EDR)\n");
algorithm =
BT_8723B_1ANT_COEX_ALGO_HID_A2DP_PANEDR;
}
}
}
} else if (numOfDiffProfile >= 3) {
if (bt_link_info->sco_exist) {
if (bt_link_info->hid_exist &&
bt_link_info->pan_exist &&
bt_link_info->a2dp_exist) {
if (bt_hs_on) {
BTC_PRINT(BTC_MSG_ALGORITHM, ALGO_TRACE,
"[BTCoex], Error!!! "
"BT Profile = SCO + "
"HID + A2DP + PAN(HS)\n");
} else {
BTC_PRINT(BTC_MSG_ALGORITHM, ALGO_TRACE,
"[BTCoex], BT Profile = "
"SCO + HID + A2DP + PAN(EDR)"
"==>PAN(EDR)+HID\n");
algorithm =
BT_8723B_1ANT_COEX_ALGO_PANEDR_HID;
}
}
}
}
return algorithm;
}
bool halbtc8723b1ant_need_to_dec_bt_pwr(struct btc_coexist *btcoexist)
{
bool ret = false;
bool bt_hs_on = false, wifi_connected = false;
s32 bt_hs_rssi = 0;
u8 bt_rssi_state;
if (!btcoexist->btc_get(btcoexist, BTC_GET_BL_HS_OPERATION, &bt_hs_on))
return false;
if (!btcoexist->btc_get(btcoexist, BTC_GET_BL_WIFI_CONNECTED,
&wifi_connected))
return false;
if (!btcoexist->btc_get(btcoexist, BTC_GET_S4_HS_RSSI, &bt_hs_rssi))
return false;
bt_rssi_state = halbtc8723b1ant_bt_rssi_state(2, 35, 0);
if (wifi_connected) {
if (bt_hs_on) {
if (bt_hs_rssi > 37)
ret = true;
} else {
if ((bt_rssi_state == BTC_RSSI_STATE_HIGH) ||
(bt_rssi_state == BTC_RSSI_STATE_STAY_HIGH))
ret = true;
}
}
return ret;
}
void halbtc8723b1ant_set_fw_dac_swing_level(struct btc_coexist *btcoexist,
u8 dac_swing_lvl)
{
u8 h2c_parameter[1] = {0};
/* There are several type of dacswing
* 0x18/ 0x10/ 0xc/ 0x8/ 0x4/ 0x6 */
h2c_parameter[0] = dac_swing_lvl;
BTC_PRINT(BTC_MSG_ALGORITHM, ALGO_TRACE_FW_EXEC,
"[BTCoex], Set Dac Swing Level=0x%x\n", dac_swing_lvl);
BTC_PRINT(BTC_MSG_ALGORITHM, ALGO_TRACE_FW_EXEC,
"[BTCoex], FW write 0x64=0x%x\n", h2c_parameter[0]);
btcoexist->btc_fill_h2c(btcoexist, 0x64, 1, h2c_parameter);
}
void halbtc8723b1ant_set_fw_dec_bt_pwr(struct btc_coexist *btcoexist,
bool dec_bt_pwr)
{
u8 h2c_parameter[1] = {0};
h2c_parameter[0] = 0;
if (dec_bt_pwr)
h2c_parameter[0] |= BIT1;
BTC_PRINT(BTC_MSG_ALGORITHM, ALGO_TRACE_FW_EXEC,
"[BTCoex], decrease Bt Power : %s, FW write 0x62=0x%x\n",
(dec_bt_pwr? "Yes!!":"No!!"),h2c_parameter[0]);
btcoexist->btc_fill_h2c(btcoexist, 0x62, 1, h2c_parameter);
}
void halbtc8723b1ant_dec_bt_pwr(struct btc_coexist *btcoexist,
bool force_exec, bool dec_bt_pwr)
{
return;
BTC_PRINT(BTC_MSG_ALGORITHM, ALGO_TRACE_FW,
"[BTCoex], %s Dec BT power = %s\n",
(force_exec ? "force to" : ""), (dec_bt_pwr ? "ON" : "OFF"));
coex_dm->cur_dec_bt_pwr = dec_bt_pwr;
if (!force_exec) {
BTC_PRINT(BTC_MSG_ALGORITHM, ALGO_TRACE_FW_DETAIL,
"[BTCoex], bPreDecBtPwr=%d, bCurDecBtPwr=%d\n",
coex_dm->pre_dec_bt_pwr, coex_dm->cur_dec_bt_pwr);
if (coex_dm->pre_dec_bt_pwr == coex_dm->cur_dec_bt_pwr)
return;
}
halbtc8723b1ant_set_fw_dec_bt_pwr(btcoexist, coex_dm->cur_dec_bt_pwr);
coex_dm->pre_dec_bt_pwr = coex_dm->cur_dec_bt_pwr;
}
void halbtc8723b1ant_set_bt_auto_report(struct btc_coexist *btcoexist,
bool enable_auto_report)
{
u8 h2c_parameter[1] = {0};
h2c_parameter[0] = 0;
if (enable_auto_report)
h2c_parameter[0] |= BIT0;
BTC_PRINT(BTC_MSG_ALGORITHM, ALGO_TRACE_FW_EXEC,
"[BTCoex], BT FW auto report : %s, FW write 0x68=0x%x\n",
(enable_auto_report? "Enabled!!":"Disabled!!"),
h2c_parameter[0]);
btcoexist->btc_fill_h2c(btcoexist, 0x68, 1, h2c_parameter);
}
void halbtc8723b1ant_bt_auto_report(struct btc_coexist *btcoexist,
bool force_exec, bool enable_auto_report)
{
BTC_PRINT(BTC_MSG_ALGORITHM, ALGO_TRACE_FW,
"[BTCoex], %s BT Auto report = %s\n",
(force_exec? "force to":""),
((enable_auto_report)? "Enabled":"Disabled"));
coex_dm->cur_bt_auto_report = enable_auto_report;
if (!force_exec) {
BTC_PRINT(BTC_MSG_ALGORITHM, ALGO_TRACE_FW_DETAIL,
"[BTCoex], bPreBtAutoReport=%d, "
"bCurBtAutoReport=%d\n",
coex_dm->pre_bt_auto_report,
coex_dm->cur_bt_auto_report);
if (coex_dm->pre_bt_auto_report == coex_dm->cur_bt_auto_report)
return;
}
halbtc8723b1ant_set_bt_auto_report(btcoexist,
coex_dm->cur_bt_auto_report);
coex_dm->pre_bt_auto_report = coex_dm->cur_bt_auto_report;
}
void halbtc8723b1ant_fw_dac_swing_lvl(struct btc_coexist *btcoexist,
bool force_exec, u8 fw_dac_swing_lvl)
{
return;
BTC_PRINT(BTC_MSG_ALGORITHM, ALGO_TRACE_FW,
"[BTCoex], %s set FW Dac Swing level = %d\n",
(force_exec? "force to":""), fw_dac_swing_lvl);
coex_dm->cur_fw_dac_swing_lvl = fw_dac_swing_lvl;
if (!force_exec) {
BTC_PRINT(BTC_MSG_ALGORITHM, ALGO_TRACE_FW_DETAIL,
"[BTCoex], preFwDacSwingLvl=%d, "
"curFwDacSwingLvl=%d\n",
coex_dm->pre_fw_dac_swing_lvl,
coex_dm->cur_fw_dac_swing_lvl);
if (coex_dm->pre_fw_dac_swing_lvl ==
coex_dm->cur_fw_dac_swing_lvl)
return;
}
halbtc8723b1ant_set_fw_dac_swing_level(btcoexist,
coex_dm->cur_fw_dac_swing_lvl);
coex_dm->pre_fw_dac_swing_lvl = coex_dm->cur_fw_dac_swing_lvl;
}
void halbtc8723b1ant_set_sw_rf_rx_lpf_corner(struct btc_coexist *btcoexist,
bool rx_rf_shrink_on)
{
if (rx_rf_shrink_on) {
/*Shrink RF Rx LPF corner */
BTC_PRINT(BTC_MSG_ALGORITHM, ALGO_TRACE_SW_EXEC,
"[BTCoex], Shrink RF Rx LPF corner!!\n");
btcoexist->btc_set_rf_reg(btcoexist, BTC_RF_A, 0x1e,
0xfffff, 0xffff7);
} else {
/*Resume RF Rx LPF corner
* After initialized, we can use coex_dm->btRf0x1eBackup */
if (btcoexist->initilized) {
BTC_PRINT(BTC_MSG_ALGORITHM, ALGO_TRACE_SW_EXEC,
"[BTCoex], Resume RF Rx LPF corner!!\n");
btcoexist->btc_set_rf_reg(btcoexist, BTC_RF_A,
0x1e, 0xfffff,
coex_dm->bt_rf0x1e_backup);
}
}
}
void halbtc8723b1ant_rf_shrink(struct btc_coexist *btcoexist,
bool force_exec, bool rx_rf_shrink_on)
{
BTC_PRINT(BTC_MSG_ALGORITHM, ALGO_TRACE_SW,
"[BTCoex], %s turn Rx RF Shrink = %s\n",
(force_exec? "force to":""),
((rx_rf_shrink_on)? "ON":"OFF"));
coex_dm->cur_rf_rx_lpf_shrink = rx_rf_shrink_on;
if (!force_exec) {
BTC_PRINT(BTC_MSG_ALGORITHM, ALGO_TRACE_SW_DETAIL,
"[BTCoex], bPreRfRxLpfShrink=%d, "
"bCurRfRxLpfShrink=%d\n",
coex_dm->pre_rf_rx_lpf_shrink,
coex_dm->cur_rf_rx_lpf_shrink);
if (coex_dm->pre_rf_rx_lpf_shrink ==
coex_dm->cur_rf_rx_lpf_shrink)
return;
}
halbtc8723b1ant_set_sw_rf_rx_lpf_corner(btcoexist,
coex_dm->cur_rf_rx_lpf_shrink);
coex_dm->pre_rf_rx_lpf_shrink = coex_dm->cur_rf_rx_lpf_shrink;
}
void halbtc8723b1ant_set_sw_penalty_tx_rate_adaptive(
struct btc_coexist *btcoexist,
bool low_penalty_ra)
{
u8 h2c_parameter[6] = {0};
h2c_parameter[0] = 0x6; /* opCode, 0x6= Retry_Penalty */
if (low_penalty_ra) {
h2c_parameter[1] |= BIT0;
/*normal rate except MCS7/6/5, OFDM54/48/36 */
h2c_parameter[2] = 0x00;
h2c_parameter[3] = 0xf7; /*MCS7 or OFDM54 */
h2c_parameter[4] = 0xf8; /*MCS6 or OFDM48 */
h2c_parameter[5] = 0xf9; /*MCS5 or OFDM36 */
}
BTC_PRINT(BTC_MSG_ALGORITHM, ALGO_TRACE_FW_EXEC,
"[BTCoex], set WiFi Low-Penalty Retry: %s",
(low_penalty_ra ? "ON!!" : "OFF!!"));
btcoexist->btc_fill_h2c(btcoexist, 0x69, 6, h2c_parameter);
}
void halbtc8723b1ant_low_penalty_ra(struct btc_coexist *btcoexist,
bool force_exec, bool low_penalty_ra)
{
coex_dm->cur_low_penalty_ra = low_penalty_ra;
if (!force_exec) {
if (coex_dm->pre_low_penalty_ra == coex_dm->cur_low_penalty_ra)
return;
}
halbtc8723b1ant_set_sw_penalty_tx_rate_adaptive(btcoexist,
coex_dm->cur_low_penalty_ra);
coex_dm->pre_low_penalty_ra = coex_dm->cur_low_penalty_ra;
}
void halbtc8723b1ant_set_dac_swing_reg(struct btc_coexist *btcoexist, u32 level)
{
u8 val = (u8) level;
BTC_PRINT(BTC_MSG_ALGORITHM, ALGO_TRACE_SW_EXEC,
"[BTCoex], Write SwDacSwing = 0x%x\n", level);
btcoexist->btc_write_1byte_bitmask(btcoexist, 0x883, 0x3e, val);
}
void halbtc8723b1ant_set_sw_full_time_dac_swing(struct btc_coexist *btcoexist,
bool sw_dac_swing_on,
u32 sw_dac_swing_lvl)
{
if (sw_dac_swing_on)
halbtc8723b1ant_set_dac_swing_reg(btcoexist, sw_dac_swing_lvl);
else
halbtc8723b1ant_set_dac_swing_reg(btcoexist, 0x18);
}
void halbtc8723b1ant_dac_swing(struct btc_coexist *btcoexist, bool force_exec,
bool dac_swing_on, u32 dac_swing_lvl)
{
BTC_PRINT(BTC_MSG_ALGORITHM, ALGO_TRACE_SW,
"[BTCoex], %s turn DacSwing=%s, dac_swing_lvl=0x%x\n",
(force_exec ? "force to" : ""), (dac_swing_on ? "ON" : "OFF"),
dac_swing_lvl);
coex_dm->cur_dac_swing_on = dac_swing_on;
coex_dm->cur_dac_swing_lvl = dac_swing_lvl;
if (!force_exec) {
BTC_PRINT(BTC_MSG_ALGORITHM, ALGO_TRACE_SW_DETAIL,
"[BTCoex], bPreDacSwingOn=%d, preDacSwingLvl=0x%x, "
"bCurDacSwingOn=%d, curDacSwingLvl=0x%x\n",
coex_dm->pre_dac_swing_on, coex_dm->pre_dac_swing_lvl,
coex_dm->cur_dac_swing_on,
coex_dm->cur_dac_swing_lvl);
if ((coex_dm->pre_dac_swing_on == coex_dm->cur_dac_swing_on) &&
(coex_dm->pre_dac_swing_lvl == coex_dm->cur_dac_swing_lvl))
return;
}
mdelay(30);
halbtc8723b1ant_set_sw_full_time_dac_swing(btcoexist, dac_swing_on,
dac_swing_lvl);
coex_dm->pre_dac_swing_on = coex_dm->cur_dac_swing_on;
coex_dm->pre_dac_swing_lvl = coex_dm->cur_dac_swing_lvl;
}
void halbtc8723b1ant_set_adc_backoff(struct btc_coexist *btcoexist,
bool adc_backoff)
{
if (adc_backoff) {
BTC_PRINT(BTC_MSG_ALGORITHM, ALGO_TRACE_SW_EXEC,
"[BTCoex], BB BackOff Level On!\n");
btcoexist->btc_write_1byte_bitmask(btcoexist, 0x8db, 0x60, 0x3);
} else {
BTC_PRINT(BTC_MSG_ALGORITHM, ALGO_TRACE_SW_EXEC,
"[BTCoex], BB BackOff Level Off!\n");
btcoexist->btc_write_1byte_bitmask(btcoexist, 0x8db, 0x60, 0x1);
}
}
void halbtc8723b1ant_adc_backoff(struct btc_coexist *btcoexist,
bool force_exec, bool adc_backoff)
{
BTC_PRINT(BTC_MSG_ALGORITHM, ALGO_TRACE_SW,
"[BTCoex], %s turn AdcBackOff = %s\n",
(force_exec ? "force to" : ""), (adc_backoff ? "ON" : "OFF"));
coex_dm->cur_adc_backoff = adc_backoff;
if (!force_exec) {
BTC_PRINT(BTC_MSG_ALGORITHM, ALGO_TRACE_SW_DETAIL,
"[BTCoex], bPreAdcBackOff=%d, bCurAdcBackOff=%d\n",
coex_dm->pre_adc_backoff, coex_dm->cur_adc_backoff);
if(coex_dm->pre_adc_backoff == coex_dm->cur_adc_backoff)
return;
}
halbtc8723b1ant_set_adc_backoff(btcoexist, coex_dm->cur_adc_backoff);
coex_dm->pre_adc_backoff =
coex_dm->cur_adc_backoff;
}
void halbtc8723b1ant_set_agc_table(struct btc_coexist *btcoexist,
bool adc_table_en)
{
u8 rssi_adjust_val = 0;
btcoexist->btc_set_rf_reg(btcoexist,
BTC_RF_A, 0xef, 0xfffff, 0x02000);
if (adc_table_en) {
BTC_PRINT(BTC_MSG_ALGORITHM, ALGO_TRACE_SW_EXEC,
"[BTCoex], Agc Table On!\n");
btcoexist->btc_set_rf_reg(btcoexist, BTC_RF_A, 0x3b,
0xfffff, 0x3fa58);
btcoexist->btc_set_rf_reg(btcoexist, BTC_RF_A, 0x3b,
0xfffff, 0x37a58);
btcoexist->btc_set_rf_reg(btcoexist, BTC_RF_A, 0x3b,
0xfffff, 0x2fa58);
rssi_adjust_val = 8;
} else {
BTC_PRINT(BTC_MSG_ALGORITHM, ALGO_TRACE_SW_EXEC,
"[BTCoex], Agc Table Off!\n");
btcoexist->btc_set_rf_reg(btcoexist, BTC_RF_A, 0x3b,
0xfffff, 0x39258);
btcoexist->btc_set_rf_reg(btcoexist, BTC_RF_A, 0x3b,
0xfffff, 0x31258);
btcoexist->btc_set_rf_reg(btcoexist, BTC_RF_A, 0x3b,
0xfffff, 0x29258);
}
btcoexist->btc_set_rf_reg(btcoexist, BTC_RF_A, 0xef, 0xfffff, 0x0);
/* set rssi_adjust_val for wifi module. */
btcoexist->btc_set(btcoexist, BTC_SET_U1_RSSI_ADJ_VAL_FOR_AGC_TABLE_ON,
&rssi_adjust_val);
}
void halbtc8723b1ant_agc_table(struct btc_coexist *btcoexist,
bool force_exec, bool adc_table_en)
{
BTC_PRINT(BTC_MSG_ALGORITHM, ALGO_TRACE_SW,
"[BTCoex], %s %s Agc Table\n",
(force_exec ? "force to" : ""),
(adc_table_en ? "Enable" : "Disable"));
coex_dm->cur_agc_table_en = adc_table_en;
if (!force_exec) {
BTC_PRINT(BTC_MSG_ALGORITHM, ALGO_TRACE_SW_DETAIL,
"[BTCoex], bPreAgcTableEn=%d, bCurAgcTableEn=%d\n",
coex_dm->pre_agc_table_en,
coex_dm->cur_agc_table_en);
if(coex_dm->pre_agc_table_en == coex_dm->cur_agc_table_en)
return;
}
halbtc8723b1ant_set_agc_table(btcoexist, adc_table_en);
coex_dm->pre_agc_table_en = coex_dm->cur_agc_table_en;
}
void halbtc8723b1ant_set_coex_table(struct btc_coexist *btcoexist,
u32 val0x6c0, u32 val0x6c4,
u32 val0x6c8, u8 val0x6cc)
{
BTC_PRINT(BTC_MSG_ALGORITHM, ALGO_TRACE_SW_EXEC,
"[BTCoex], set coex table, set 0x6c0=0x%x\n", val0x6c0);
btcoexist->btc_write_4byte(btcoexist, 0x6c0, val0x6c0);
BTC_PRINT(BTC_MSG_ALGORITHM, ALGO_TRACE_SW_EXEC,
"[BTCoex], set coex table, set 0x6c4=0x%x\n", val0x6c4);
btcoexist->btc_write_4byte(btcoexist, 0x6c4, val0x6c4);
BTC_PRINT(BTC_MSG_ALGORITHM, ALGO_TRACE_SW_EXEC,
"[BTCoex], set coex table, set 0x6c8=0x%x\n", val0x6c8);
btcoexist->btc_write_4byte(btcoexist, 0x6c8, val0x6c8);
BTC_PRINT(BTC_MSG_ALGORITHM, ALGO_TRACE_SW_EXEC,
"[BTCoex], set coex table, set 0x6cc=0x%x\n", val0x6cc);
btcoexist->btc_write_1byte(btcoexist, 0x6cc, val0x6cc);
}
void halbtc8723b1ant_coex_table(struct btc_coexist *btcoexist,
bool force_exec, u32 val0x6c0,
u32 val0x6c4, u32 val0x6c8,
u8 val0x6cc)
{
BTC_PRINT(BTC_MSG_ALGORITHM, ALGO_TRACE_SW,
"[BTCoex], %s write Coex Table 0x6c0=0x%x,"
" 0x6c4=0x%x, 0x6cc=0x%x\n", (force_exec ? "force to" : ""),
val0x6c0, val0x6c4, val0x6cc);
coex_dm->cur_val0x6c0 = val0x6c0;
coex_dm->cur_val0x6c4 = val0x6c4;
coex_dm->cur_val0x6c8 = val0x6c8;
coex_dm->cur_val0x6cc = val0x6cc;
if (!force_exec) {
if ((coex_dm->pre_val0x6c0 == coex_dm->cur_val0x6c0) &&
(coex_dm->pre_val0x6c4 == coex_dm->cur_val0x6c4) &&
(coex_dm->pre_val0x6c8 == coex_dm->cur_val0x6c8) &&
(coex_dm->pre_val0x6cc == coex_dm->cur_val0x6cc))
return;
}
halbtc8723b1ant_set_coex_table(btcoexist, val0x6c0, val0x6c4,
val0x6c8, val0x6cc);
coex_dm->pre_val0x6c0 = coex_dm->cur_val0x6c0;
coex_dm->pre_val0x6c4 = coex_dm->cur_val0x6c4;
coex_dm->pre_val0x6c8 = coex_dm->cur_val0x6c8;
coex_dm->pre_val0x6cc = coex_dm->cur_val0x6cc;
}
void halbtc8723b1ant_coex_table_with_type(struct btc_coexist *btcoexist,
bool force_exec, u8 type)
{
switch (type) {
case 0:
halbtc8723b1ant_coex_table(btcoexist, force_exec, 0x55555555,
0x55555555, 0xffffff, 0x3);
break;
case 1:
halbtc8723b1ant_coex_table(btcoexist, force_exec, 0x55555555,
0x5a5a5a5a, 0xffffff, 0x3);
break;
case 2:
halbtc8723b1ant_coex_table(btcoexist, force_exec, 0x5a5a5a5a,
0x5a5a5a5a, 0xffffff, 0x3);
break;
case 3:
halbtc8723b1ant_coex_table(btcoexist, force_exec, 0x55555555,
0xaaaaaaaa, 0xffffff, 0x3);
break;
case 4:
halbtc8723b1ant_coex_table(btcoexist, force_exec, 0x55555555,
0x5aaa5aaa, 0xffffff, 0x3);
break;
case 5:
halbtc8723b1ant_coex_table(btcoexist, force_exec, 0x5a5a5a5a,
0xaaaa5a5a, 0xffffff, 0x3);
break;
case 6:
halbtc8723b1ant_coex_table(btcoexist, force_exec, 0x55555555,
0xaaaa5a5a, 0xffffff, 0x3);
break;
case 7:
halbtc8723b1ant_coex_table(btcoexist, force_exec, 0x5afa5afa,
0x5afa5afa, 0xffffff, 0x3);
break;
default:
break;
}
}
void halbtc8723b1ant_SetFwIgnoreWlanAct(struct btc_coexist *btcoexist,
bool enable)
{
u8 h2c_parameter[1] = {0};
if (enable)
h2c_parameter[0] |= BIT0; /* function enable */
BTC_PRINT(BTC_MSG_ALGORITHM, ALGO_TRACE_FW_EXEC,
"[BTCoex], set FW for BT Ignore Wlan_Act,"
" FW write 0x63=0x%x\n", h2c_parameter[0]);
btcoexist->btc_fill_h2c(btcoexist, 0x63, 1, h2c_parameter);
}
void halbtc8723b1ant_ignore_wlan_act(struct btc_coexist *btcoexist,
bool force_exec, bool enable)
{
BTC_PRINT(BTC_MSG_ALGORITHM, ALGO_TRACE_FW,
"[BTCoex], %s turn Ignore WlanAct %s\n",
(force_exec ? "force to" : ""), (enable ? "ON" : "OFF"));
coex_dm->cur_ignore_wlan_act = enable;
if (!force_exec) {
BTC_PRINT(BTC_MSG_ALGORITHM, ALGO_TRACE_FW_DETAIL,
"[BTCoex], bPreIgnoreWlanAct = %d, "
"bCurIgnoreWlanAct = %d!!\n",
coex_dm->pre_ignore_wlan_act,
coex_dm->cur_ignore_wlan_act);
if (coex_dm->pre_ignore_wlan_act ==
coex_dm->cur_ignore_wlan_act)
return;
}
halbtc8723b1ant_SetFwIgnoreWlanAct(btcoexist, enable);
coex_dm->pre_ignore_wlan_act = coex_dm->cur_ignore_wlan_act;
}
void halbtc8723b1ant_set_fw_ps_tdma(struct btc_coexist *btcoexist,
u8 byte1, u8 byte2, u8 byte3,
u8 byte4, u8 byte5)
{
u8 h2c_parameter[5] = {0};
u8 real_byte1 = byte1, real_byte5 = byte5;
bool ap_enable = false;
btcoexist->btc_get(btcoexist, BTC_GET_BL_WIFI_AP_MODE_ENABLE,
&ap_enable);
if (ap_enable) {
if ((byte1 & BIT4) && !(byte1 & BIT5)) {
BTC_PRINT(BTC_MSG_INTERFACE, INTF_NOTIFY,
"[BTCoex], FW for 1Ant AP mode\n");
real_byte1 &= ~BIT4;
real_byte1 |= BIT5;
real_byte5 |= BIT5;
real_byte5 &= ~BIT6;
}
}
h2c_parameter[0] = real_byte1;
h2c_parameter[1] = byte2;
h2c_parameter[2] = byte3;
h2c_parameter[3] = byte4;
h2c_parameter[4] = real_byte5;
coex_dm->ps_tdma_para[0] = real_byte1;
coex_dm->ps_tdma_para[1] = byte2;
coex_dm->ps_tdma_para[2] = byte3;
coex_dm->ps_tdma_para[3] = byte4;
coex_dm->ps_tdma_para[4] = real_byte5;
BTC_PRINT(BTC_MSG_ALGORITHM, ALGO_TRACE_FW_EXEC,
"[BTCoex], PS-TDMA H2C cmd =0x%x%08x\n",
h2c_parameter[0],
h2c_parameter[1] << 24 |
h2c_parameter[2] << 16 |
h2c_parameter[3] << 8 |
h2c_parameter[4]);
btcoexist->btc_fill_h2c(btcoexist, 0x60, 5, h2c_parameter);
}
void halbtc8723b1ant_SetLpsRpwm(struct btc_coexist *btcoexist,
u8 lps_val, u8 rpwm_val)
{
u8 lps = lps_val;
u8 rpwm = rpwm_val;
btcoexist->btc_set(btcoexist, BTC_SET_U1_1ANT_LPS, &lps);
btcoexist->btc_set(btcoexist, BTC_SET_U1_1ANT_RPWM, &rpwm);
}
void halbtc8723b1ant_LpsRpwm(struct btc_coexist *btcoexist, bool force_exec,
u8 lps_val, u8 rpwm_val)
{
BTC_PRINT(BTC_MSG_ALGORITHM, ALGO_TRACE_FW,
"[BTCoex], %s set lps/rpwm=0x%x/0x%x \n",
(force_exec ? "force to" : ""), lps_val, rpwm_val);
coex_dm->cur_lps = lps_val;
coex_dm->cur_rpwm = rpwm_val;
if (!force_exec) {
BTC_PRINT(BTC_MSG_ALGORITHM, ALGO_TRACE_FW_DETAIL,
"[BTCoex], LPS-RxBeaconMode=0x%x , LPS-RPWM=0x%x!!\n",
coex_dm->cur_lps, coex_dm->cur_rpwm);
if ((coex_dm->pre_lps == coex_dm->cur_lps) &&
(coex_dm->pre_rpwm == coex_dm->cur_rpwm)) {
BTC_PRINT(BTC_MSG_ALGORITHM, ALGO_TRACE_FW_DETAIL,
"[BTCoex], LPS-RPWM_Last=0x%x"
" , LPS-RPWM_Now=0x%x!!\n",
coex_dm->pre_rpwm, coex_dm->cur_rpwm);
return;
}
}
halbtc8723b1ant_SetLpsRpwm(btcoexist, lps_val, rpwm_val);
coex_dm->pre_lps = coex_dm->cur_lps;
coex_dm->pre_rpwm = coex_dm->cur_rpwm;
}
void halbtc8723b1ant_sw_mechanism1(struct btc_coexist *btcoexist,
bool shrink_rx_lpf, bool low_penalty_ra,
bool limited_dig, bool bt_lna_constrain)
{
BTC_PRINT(BTC_MSG_ALGORITHM, ALGO_BT_MONITOR,
"[BTCoex], SM1[ShRf/ LpRA/ LimDig/ btLna] = %d %d %d %d\n",
shrink_rx_lpf, low_penalty_ra, limited_dig, bt_lna_constrain);
halbtc8723b1ant_low_penalty_ra(btcoexist, NORMAL_EXEC, low_penalty_ra);
}
void halbtc8723b1ant_sw_mechanism2(struct btc_coexist *btcoexist,
bool agc_table_shift, bool adc_backoff,
bool sw_dac_swing, u32 dac_swing_lvl)
{
BTC_PRINT(BTC_MSG_ALGORITHM, ALGO_BT_MONITOR,
"[BTCoex], SM2[AgcT/ AdcB/ SwDacSwing(lvl)] = %d %d %d\n",
agc_table_shift, adc_backoff, sw_dac_swing);
}
void halbtc8723b1ant_SetAntPath(struct btc_coexist *btcoexist,
u8 ant_pos_type, bool init_hw_cfg,
bool wifi_off)
{
struct btc_board_info *board_info = &btcoexist->board_info;
u32 fw_ver = 0, u32tmp = 0;
bool pg_ext_switch = false;
bool use_ext_switch = false;
u8 h2c_parameter[2] = {0};
btcoexist->btc_get(btcoexist, BTC_GET_BL_EXT_SWITCH, &pg_ext_switch);
/* [31:16]=fw ver, [15:0]=fw sub ver */
btcoexist->btc_get(btcoexist, BTC_GET_U4_WIFI_FW_VER, &fw_ver);
if ((fw_ver < 0xc0000) || pg_ext_switch)
use_ext_switch = true;
if (init_hw_cfg){
/*BT select s0/s1 is controlled by WiFi */
btcoexist->btc_write_1byte_bitmask(btcoexist, 0x67, 0x20, 0x1);
/*Force GNT_BT to Normal */
btcoexist->btc_write_1byte_bitmask(btcoexist, 0x765, 0x18, 0x0);
} else if (wifi_off) {
/*Force GNT_BT to High */
btcoexist->btc_write_1byte_bitmask(btcoexist, 0x765, 0x18, 0x3);
/*BT select s0/s1 is controlled by BT */
btcoexist->btc_write_1byte_bitmask(btcoexist, 0x67, 0x20, 0x0);
/* 0x4c[24:23]=00, Set Antenna control by BT_RFE_CTRL
* BT Vendor 0xac=0xf002 */
u32tmp = btcoexist->btc_read_4byte(btcoexist, 0x4c);
u32tmp &= ~BIT23;
u32tmp &= ~BIT24;
btcoexist->btc_write_4byte(btcoexist, 0x4c, u32tmp);
}
if (use_ext_switch) {
if (init_hw_cfg) {
/* 0x4c[23]=0, 0x4c[24]=1 Antenna control by WL/BT */
u32tmp = btcoexist->btc_read_4byte(btcoexist, 0x4c);
u32tmp &= ~BIT23;
u32tmp |= BIT24;
btcoexist->btc_write_4byte(btcoexist, 0x4c, u32tmp);
if (board_info->btdm_ant_pos ==
BTC_ANTENNA_AT_MAIN_PORT) {
/* Main Ant to BT for IPS case 0x4c[23]=1 */
btcoexist->btc_write_1byte_bitmask(btcoexist,
0x64, 0x1,
0x1);
/*tell firmware "no antenna inverse"*/
h2c_parameter[0] = 0;
h2c_parameter[1] = 1; /*ext switch type*/
btcoexist->btc_fill_h2c(btcoexist, 0x65, 2,
h2c_parameter);
} else {
/*Aux Ant to BT for IPS case 0x4c[23]=1 */
btcoexist->btc_write_1byte_bitmask(btcoexist,
0x64, 0x1,
0x0);
/*tell firmware "antenna inverse"*/
h2c_parameter[0] = 1;
h2c_parameter[1] = 1; /*ext switch type*/
btcoexist->btc_fill_h2c(btcoexist, 0x65, 2,
h2c_parameter);
}
}
/* fixed internal switch first*/
/* fixed internal switch S1->WiFi, S0->BT*/
if (board_info->btdm_ant_pos == BTC_ANTENNA_AT_MAIN_PORT)
btcoexist->btc_write_2byte(btcoexist, 0x948, 0x0);
else/* fixed internal switch S0->WiFi, S1->BT*/
btcoexist->btc_write_2byte(btcoexist, 0x948, 0x280);
/* ext switch setting */
switch (ant_pos_type) {
case BTC_ANT_PATH_WIFI:
if (board_info->btdm_ant_pos ==
BTC_ANTENNA_AT_MAIN_PORT)
btcoexist->btc_write_1byte_bitmask(btcoexist,
0x92c, 0x3,
0x1);
else
btcoexist->btc_write_1byte_bitmask(btcoexist,
0x92c, 0x3,
0x2);
break;
case BTC_ANT_PATH_BT:
if (board_info->btdm_ant_pos ==
BTC_ANTENNA_AT_MAIN_PORT)
btcoexist->btc_write_1byte_bitmask(btcoexist,
0x92c, 0x3,
0x2);
else
btcoexist->btc_write_1byte_bitmask(btcoexist,
0x92c, 0x3,
0x1);
break;
default:
case BTC_ANT_PATH_PTA:
if (board_info->btdm_ant_pos ==
BTC_ANTENNA_AT_MAIN_PORT)
btcoexist->btc_write_1byte_bitmask(btcoexist,
0x92c, 0x3,
0x1);
else
btcoexist->btc_write_1byte_bitmask(btcoexist,
0x92c, 0x3,
0x2);
break;
}
} else {
if (init_hw_cfg) {
/* 0x4c[23]=1, 0x4c[24]=0 Antenna control by 0x64*/
u32tmp = btcoexist->btc_read_4byte(btcoexist, 0x4c);
u32tmp |= BIT23;
u32tmp &= ~BIT24;
btcoexist->btc_write_4byte(btcoexist, 0x4c, u32tmp);
if (board_info->btdm_ant_pos ==
BTC_ANTENNA_AT_MAIN_PORT) {
/*Main Ant to WiFi for IPS case 0x4c[23]=1*/
btcoexist->btc_write_1byte_bitmask(btcoexist,
0x64, 0x1,
0x0);
/*tell firmware "no antenna inverse"*/
h2c_parameter[0] = 0;
h2c_parameter[1] = 0; /*internal switch type*/
btcoexist->btc_fill_h2c(btcoexist, 0x65, 2,
h2c_parameter);
} else {
/*Aux Ant to BT for IPS case 0x4c[23]=1*/
btcoexist->btc_write_1byte_bitmask(btcoexist,
0x64, 0x1,
0x1);
/*tell firmware "antenna inverse"*/
h2c_parameter[0] = 1;
h2c_parameter[1] = 0; /*internal switch type*/
btcoexist->btc_fill_h2c(btcoexist, 0x65, 2,
h2c_parameter);
}
}
/* fixed external switch first*/
/*Main->WiFi, Aux->BT*/
if(board_info->btdm_ant_pos == BTC_ANTENNA_AT_MAIN_PORT)
btcoexist->btc_write_1byte_bitmask(btcoexist, 0x92c,
0x3, 0x1);
else/*Main->BT, Aux->WiFi */
btcoexist->btc_write_1byte_bitmask(btcoexist, 0x92c,
0x3, 0x2);
/* internal switch setting*/
switch (ant_pos_type) {
case BTC_ANT_PATH_WIFI:
if(board_info->btdm_ant_pos == BTC_ANTENNA_AT_MAIN_PORT)
btcoexist->btc_write_2byte(btcoexist, 0x948,
0x0);
else
btcoexist->btc_write_2byte(btcoexist, 0x948,
0x280);
break;
case BTC_ANT_PATH_BT:
if(board_info->btdm_ant_pos == BTC_ANTENNA_AT_MAIN_PORT)
btcoexist->btc_write_2byte(btcoexist, 0x948,
0x280);
else
btcoexist->btc_write_2byte(btcoexist, 0x948,
0x0);
break;
default:
case BTC_ANT_PATH_PTA:
if(board_info->btdm_ant_pos == BTC_ANTENNA_AT_MAIN_PORT)
btcoexist->btc_write_2byte(btcoexist, 0x948,
0x200);
else
btcoexist->btc_write_2byte(btcoexist, 0x948,
0x80);
break;
}
}
}
void halbtc8723b1ant_ps_tdma(struct btc_coexist *btcoexist, bool force_exec,
bool turn_on, u8 type)
{
bool wifi_busy = false;
u8 rssi_adjust_val = 0;
coex_dm->cur_ps_tdma_on = turn_on;
coex_dm->cur_ps_tdma = type;
btcoexist->btc_get(btcoexist, BTC_GET_BL_WIFI_BUSY, &wifi_busy);
if (!force_exec) {
if (coex_dm->cur_ps_tdma_on)
BTC_PRINT(BTC_MSG_ALGORITHM, ALGO_TRACE_FW_DETAIL,
"[BTCoex], ******** TDMA(on, %d) *********\n",
coex_dm->cur_ps_tdma);
else
BTC_PRINT(BTC_MSG_ALGORITHM, ALGO_TRACE_FW_DETAIL,
"[BTCoex], ******** TDMA(off, %d) ********\n",
coex_dm->cur_ps_tdma);
if ((coex_dm->pre_ps_tdma_on == coex_dm->cur_ps_tdma_on) &&
(coex_dm->pre_ps_tdma == coex_dm->cur_ps_tdma))
return;
}
if (turn_on) {
switch (type) {
default:
halbtc8723b1ant_set_fw_ps_tdma(btcoexist, 0x51, 0x1a,
0x1a, 0x0, 0x50);
break;
case 1:
if (wifi_busy)
halbtc8723b1ant_set_fw_ps_tdma(btcoexist, 0x51,
0x3a, 0x03,
0x10, 0x50);
else
halbtc8723b1ant_set_fw_ps_tdma(btcoexist,0x51,
0x3a, 0x03,
0x10, 0x51);
rssi_adjust_val = 11;
break;
case 2:
if (wifi_busy)
halbtc8723b1ant_set_fw_ps_tdma(btcoexist, 0x51,
0x2b, 0x03,
0x10, 0x50);
else
halbtc8723b1ant_set_fw_ps_tdma(btcoexist, 0x51,
0x2b, 0x03,
0x10, 0x51);
rssi_adjust_val = 14;
break;
case 3:
halbtc8723b1ant_set_fw_ps_tdma(btcoexist, 0x51, 0x1d,
0x1d, 0x0, 0x52);
break;
case 4:
halbtc8723b1ant_set_fw_ps_tdma(btcoexist, 0x93, 0x15,
0x3, 0x14, 0x0);
rssi_adjust_val = 17;
break;
case 5:
halbtc8723b1ant_set_fw_ps_tdma(btcoexist, 0x61, 0x15,
0x3, 0x11, 0x10);
break;
case 6:
halbtc8723b1ant_set_fw_ps_tdma(btcoexist, 0x61, 0x20,
0x3, 0x11, 0x13);
break;
case 7:
halbtc8723b1ant_set_fw_ps_tdma(btcoexist, 0x13, 0xc,
0x5, 0x0, 0x0);
break;
case 8:
halbtc8723b1ant_set_fw_ps_tdma(btcoexist, 0x93, 0x25,
0x3, 0x10, 0x0);
break;
case 9:
if(wifi_busy)
halbtc8723b1ant_set_fw_ps_tdma(btcoexist, 0x51,
0x21, 0x3,
0x10, 0x50);
else
halbtc8723b1ant_set_fw_ps_tdma(btcoexist, 0x51,
0x21, 0x3,
0x10, 0x50);
rssi_adjust_val = 18;
break;
case 10:
halbtc8723b1ant_set_fw_ps_tdma(btcoexist, 0x13, 0xa,
0xa, 0x0, 0x40);
break;
case 11:
if (wifi_busy)
halbtc8723b1ant_set_fw_ps_tdma(btcoexist, 0x51,
0x15, 0x03,
0x10, 0x50);
else
halbtc8723b1ant_set_fw_ps_tdma(btcoexist, 0x51,
0x15, 0x03,
0x10, 0x50);
rssi_adjust_val = 20;
break;
case 12:
halbtc8723b1ant_set_fw_ps_tdma(btcoexist, 0x51, 0x0a,
0x0a, 0x0, 0x50);
break;
case 13:
halbtc8723b1ant_set_fw_ps_tdma(btcoexist, 0x51, 0x15,
0x15, 0x0, 0x50);
break;
case 14:
halbtc8723b1ant_set_fw_ps_tdma(btcoexist, 0x51, 0x21,
0x3, 0x10, 0x52);
break;
case 15:
halbtc8723b1ant_set_fw_ps_tdma(btcoexist, 0x13, 0xa,
0x3, 0x8, 0x0);
break;
case 16:
halbtc8723b1ant_set_fw_ps_tdma(btcoexist, 0x93, 0x15,
0x3, 0x10, 0x0);
rssi_adjust_val = 18;
break;
case 18:
halbtc8723b1ant_set_fw_ps_tdma(btcoexist, 0x93, 0x25,
0x3, 0x10, 0x0);
rssi_adjust_val = 14;
break;
case 20:
halbtc8723b1ant_set_fw_ps_tdma(btcoexist, 0x61, 0x35,
0x03, 0x11, 0x10);
break;
case 21:
halbtc8723b1ant_set_fw_ps_tdma(btcoexist, 0x61, 0x15,
0x03, 0x11, 0x10);
break;
case 22:
halbtc8723b1ant_set_fw_ps_tdma(btcoexist, 0x61, 0x25,
0x03, 0x11, 0x10);
break;
case 23:
halbtc8723b1ant_set_fw_ps_tdma(btcoexist, 0xe3, 0x25,
0x3, 0x31, 0x18);
rssi_adjust_val = 22;
break;
case 24:
halbtc8723b1ant_set_fw_ps_tdma(btcoexist, 0xe3, 0x15,
0x3, 0x31, 0x18);
rssi_adjust_val = 22;
break;
case 25:
halbtc8723b1ant_set_fw_ps_tdma(btcoexist, 0xe3, 0xa,
0x3, 0x31, 0x18);
rssi_adjust_val = 22;
break;
case 26:
halbtc8723b1ant_set_fw_ps_tdma(btcoexist, 0xe3, 0xa,
0x3, 0x31, 0x18);
rssi_adjust_val = 22;
break;
case 27:
halbtc8723b1ant_set_fw_ps_tdma(btcoexist, 0xe3, 0x25,
0x3, 0x31, 0x98);
rssi_adjust_val = 22;
break;
case 28:
halbtc8723b1ant_set_fw_ps_tdma(btcoexist, 0x69, 0x25,
0x3, 0x31, 0x0);
break;
case 29:
halbtc8723b1ant_set_fw_ps_tdma(btcoexist, 0xab, 0x1a,
0x1a, 0x1, 0x10);
break;
case 30:
halbtc8723b1ant_set_fw_ps_tdma(btcoexist, 0x51, 0x14,
0x3, 0x10, 0x50);
break;
case 31:
halbtc8723b1ant_set_fw_ps_tdma(btcoexist, 0xd3, 0x1a,
0x1a, 0, 0x58);
break;
case 32:
halbtc8723b1ant_set_fw_ps_tdma(btcoexist, 0x61, 0xa,
0x3, 0x10, 0x0);
break;
case 33:
halbtc8723b1ant_set_fw_ps_tdma(btcoexist, 0xa3, 0x25,
0x3, 0x30, 0x90);
break;
case 34:
halbtc8723b1ant_set_fw_ps_tdma(btcoexist, 0x53, 0x1a,
0x1a, 0x0, 0x10);
break;
case 35:
halbtc8723b1ant_set_fw_ps_tdma(btcoexist, 0x63, 0x1a,
0x1a, 0x0, 0x10);
break;
case 36:
halbtc8723b1ant_set_fw_ps_tdma(btcoexist, 0xd3, 0x12,
0x3, 0x14, 0x50);
break;
/* SoftAP only with no sta associated,BT disable ,
* TDMA mode for power saving
* here softap mode screen off will cost 70-80mA for phone */
case 40:
halbtc8723b1ant_set_fw_ps_tdma(btcoexist, 0x23, 0x18,
0x00, 0x10, 0x24);
break;
}
} else {
switch (type) {
case 8: /*PTA Control */
halbtc8723b1ant_set_fw_ps_tdma(btcoexist, 0x8, 0x0,
0x0, 0x0, 0x0);
halbtc8723b1ant_SetAntPath(btcoexist, BTC_ANT_PATH_PTA,
false, false);
break;
case 0:
default: /*Software control, Antenna at BT side */
halbtc8723b1ant_set_fw_ps_tdma(btcoexist, 0x0, 0x0,
0x0, 0x0, 0x0);
halbtc8723b1ant_SetAntPath(btcoexist, BTC_ANT_PATH_BT,
false, false);
break;
case 9: /*Software control, Antenna at WiFi side */
halbtc8723b1ant_set_fw_ps_tdma(btcoexist, 0x0, 0x0,
0x0, 0x0, 0x0);
halbtc8723b1ant_SetAntPath(btcoexist, BTC_ANT_PATH_WIFI,
false, false);
break;
}
}
rssi_adjust_val = 0;
btcoexist->btc_set(btcoexist,
BTC_SET_U1_RSSI_ADJ_VAL_FOR_1ANT_COEX_TYPE,
&rssi_adjust_val);
/* update pre state */
coex_dm->pre_ps_tdma_on = coex_dm->cur_ps_tdma_on;
coex_dm->pre_ps_tdma = coex_dm->cur_ps_tdma;
}
void halbtc8723b1ant_coex_alloff(struct btc_coexist *btcoexist)
{
/* fw all off */
halbtc8723b1ant_fw_dac_swing_lvl(btcoexist, NORMAL_EXEC, 6);
halbtc8723b1ant_dec_bt_pwr(btcoexist, NORMAL_EXEC, false);
/* sw all off */
halbtc8723b1ant_sw_mechanism1(btcoexist, false, false, false, false);
halbtc8723b1ant_sw_mechanism2(btcoexist, false, false, false, 0x18);
/* hw all off */
halbtc8723b1ant_coex_table_with_type(btcoexist, NORMAL_EXEC, 0);
}
bool halbtc8723b1ant_is_common_action(struct btc_coexist *btcoexist)
{
bool commom = false, wifi_connected = false;
bool wifi_busy = false;
btcoexist->btc_get(btcoexist, BTC_GET_BL_WIFI_CONNECTED,
&wifi_connected);
btcoexist->btc_get(btcoexist, BTC_GET_BL_WIFI_BUSY, &wifi_busy);
if (!wifi_connected &&
BT_8723B_1ANT_BT_STATUS_NON_CONNECTED_IDLE == coex_dm->bt_status) {
BTC_PRINT(BTC_MSG_ALGORITHM, ALGO_TRACE,
"[BTCoex], Wifi non connected-idle + "
"BT non connected-idle!!\n");
halbtc8723b1ant_fw_dac_swing_lvl(btcoexist, NORMAL_EXEC, 6);
halbtc8723b1ant_dec_bt_pwr(btcoexist, NORMAL_EXEC, false);
halbtc8723b1ant_sw_mechanism1(btcoexist, false, false,
false, false);
halbtc8723b1ant_sw_mechanism2(btcoexist, false, false,
false, 0x18);
commom = true;
} else if (wifi_connected &&
(BT_8723B_1ANT_BT_STATUS_NON_CONNECTED_IDLE ==
coex_dm->bt_status)) {
BTC_PRINT(BTC_MSG_ALGORITHM, ALGO_TRACE,
"[BTCoex], Wifi connected + "
"BT non connected-idle!!\n");
halbtc8723b1ant_fw_dac_swing_lvl(btcoexist, NORMAL_EXEC, 6);
halbtc8723b1ant_dec_bt_pwr(btcoexist, NORMAL_EXEC, false);
halbtc8723b1ant_sw_mechanism1(btcoexist, false, false,
false, false);
halbtc8723b1ant_sw_mechanism2(btcoexist, false, false,
false, 0x18);
commom = true;
} else if (!wifi_connected &&
(BT_8723B_1ANT_BT_STATUS_CONNECTED_IDLE ==
coex_dm->bt_status)) {
BTC_PRINT(BTC_MSG_ALGORITHM, ALGO_TRACE,
"[BTCoex], Wifi non connected-idle + "
"BT connected-idle!!\n");
halbtc8723b1ant_fw_dac_swing_lvl(btcoexist, NORMAL_EXEC, 6);
halbtc8723b1ant_dec_bt_pwr(btcoexist, NORMAL_EXEC, false);
halbtc8723b1ant_sw_mechanism1(btcoexist, false, false,
false, false);
halbtc8723b1ant_sw_mechanism2(btcoexist, false, false,
false, 0x18);
commom = true;
} else if (wifi_connected &&
(BT_8723B_1ANT_BT_STATUS_CONNECTED_IDLE ==
coex_dm->bt_status)) {
BTC_PRINT(BTC_MSG_ALGORITHM, ALGO_TRACE,
"[BTCoex], Wifi connected + BT connected-idle!!\n");
halbtc8723b1ant_fw_dac_swing_lvl(btcoexist, NORMAL_EXEC, 6);
halbtc8723b1ant_dec_bt_pwr(btcoexist, NORMAL_EXEC, false);
halbtc8723b1ant_sw_mechanism1(btcoexist, false, false,
false, false);
halbtc8723b1ant_sw_mechanism2(btcoexist, false, false,
false, 0x18);
commom = true;
} else if (!wifi_connected &&
(BT_8723B_1ANT_BT_STATUS_CONNECTED_IDLE !=
coex_dm->bt_status)) {
BTC_PRINT(BTC_MSG_ALGORITHM, ALGO_TRACE,
("[BTCoex], Wifi non connected-idle + BT Busy!!\n"));
halbtc8723b1ant_fw_dac_swing_lvl(btcoexist, NORMAL_EXEC, 6);
halbtc8723b1ant_dec_bt_pwr(btcoexist, NORMAL_EXEC, false);
halbtc8723b1ant_sw_mechanism1(btcoexist, false, false,
false, false);
halbtc8723b1ant_sw_mechanism2(btcoexist, false, false,
false, 0x18);
commom = true;
} else {
if (wifi_busy)
BTC_PRINT(BTC_MSG_ALGORITHM, ALGO_TRACE,
"[BTCoex], Wifi Connected-Busy"
" + BT Busy!!\n");
else
BTC_PRINT(BTC_MSG_ALGORITHM, ALGO_TRACE,
"[BTCoex], Wifi Connected-Idle"
" + BT Busy!!\n");
commom = false;
}
return commom;
}
void halbtc8723b1ant_tdma_duration_adjust_for_acl(struct btc_coexist *btcoexist,
u8 wifi_status)
{
static s32 up, dn, m, n, wait_count;
/* 0: no change, +1: increase WiFi duration,
* -1: decrease WiFi duration */
s32 result;
u8 retry_count = 0, bt_info_ext;
static bool pre_wifi_busy = false;
bool wifi_busy = false;
BTC_PRINT(BTC_MSG_ALGORITHM, ALGO_TRACE_FW,
"[BTCoex], TdmaDurationAdjustForAcl()\n");
if (BT_8723B_1ANT_WIFI_STATUS_CONNECTED_BUSY == wifi_status)
wifi_busy = true;
else
wifi_busy = false;
if ((BT_8723B_1ANT_WIFI_STATUS_NON_CONNECTED_ASSO_AUTH_SCAN ==
wifi_status) ||
(BT_8723B_1ANT_WIFI_STATUS_CONNECTED_SCAN == wifi_status) ||
(BT_8723B_1ANT_WIFI_STATUS_CONNECTED_SPECIAL_PKT == wifi_status)) {
if (coex_dm->cur_ps_tdma != 1 && coex_dm->cur_ps_tdma != 2 &&
coex_dm->cur_ps_tdma != 3 && coex_dm->cur_ps_tdma != 9) {
halbtc8723b1ant_ps_tdma(btcoexist, NORMAL_EXEC,
true, 9);
coex_dm->ps_tdma_du_adj_type = 9;
up = 0;
dn = 0;
m = 1;
n = 3;
result = 0;
wait_count = 0;
}
return;
}
if (!coex_dm->auto_tdma_adjust) {
coex_dm->auto_tdma_adjust = true;
BTC_PRINT(BTC_MSG_ALGORITHM, ALGO_TRACE_FW_DETAIL,
"[BTCoex], first run TdmaDurationAdjust()!!\n");
halbtc8723b1ant_ps_tdma(btcoexist, NORMAL_EXEC, true, 2);
coex_dm->ps_tdma_du_adj_type = 2;
up = 0;
dn = 0;
m = 1;
n = 3;
result = 0;
wait_count = 0;
} else {
/*accquire the BT TRx retry count from BT_Info byte2 */
retry_count = coex_sta->bt_retry_cnt;
bt_info_ext = coex_sta->bt_info_ext;
result = 0;
wait_count++;
/* no retry in the last 2-second duration */
if (retry_count == 0) {
up++;
dn--;
if (dn <= 0)
dn = 0;
if (up >= n) {
wait_count = 0;
n = 3;
up = 0;
dn = 0;
result = 1;
BTC_PRINT(BTC_MSG_ALGORITHM,
ALGO_TRACE_FW_DETAIL,
"[BTCoex], Increase wifi "
"duration!!\n");
}
} else if (retry_count <= 3) {
up--;
dn++;
if (up <= 0)
up = 0;
if (dn == 2) {
if (wait_count <= 2)
m++;
else
m = 1;
if (m >= 20)
m = 20;
n = 3 * m;
up = 0;
dn = 0;
wait_count = 0;
result = -1;
BTC_PRINT(BTC_MSG_ALGORITHM,
ALGO_TRACE_FW_DETAIL,
"[BTCoex], Decrease wifi duration"
" for retryCounter<3!!\n");
}
} else {
if (wait_count == 1)
m++;
else
m = 1;
if (m >= 20)
m = 20;
n = 3 * m;
up = 0;
dn = 0;
wait_count = 0;
result = -1;
BTC_PRINT(BTC_MSG_ALGORITHM, ALGO_TRACE_FW_DETAIL,
"[BTCoex], Decrease wifi duration"
" for retryCounter>3!!\n");
}
if (result == -1) {
if ((BT_INFO_8723B_1ANT_A2DP_BASIC_RATE(bt_info_ext)) &&
((coex_dm->cur_ps_tdma == 1) ||
(coex_dm->cur_ps_tdma == 2))) {
halbtc8723b1ant_ps_tdma(btcoexist, NORMAL_EXEC,
true, 9);
coex_dm->ps_tdma_du_adj_type = 9;
} else if (coex_dm->cur_ps_tdma == 1) {
halbtc8723b1ant_ps_tdma(btcoexist, NORMAL_EXEC,
true, 2);
coex_dm->ps_tdma_du_adj_type = 2;
} else if (coex_dm->cur_ps_tdma == 2) {
halbtc8723b1ant_ps_tdma(btcoexist, NORMAL_EXEC,
true, 9);
coex_dm->ps_tdma_du_adj_type = 9;
} else if (coex_dm->cur_ps_tdma == 9) {
halbtc8723b1ant_ps_tdma(btcoexist, NORMAL_EXEC,
true, 11);
coex_dm->ps_tdma_du_adj_type = 11;
}
} else if(result == 1) {
if ((BT_INFO_8723B_1ANT_A2DP_BASIC_RATE(bt_info_ext)) &&
((coex_dm->cur_ps_tdma == 1) ||
(coex_dm->cur_ps_tdma == 2))) {
halbtc8723b1ant_ps_tdma(btcoexist, NORMAL_EXEC,
true, 9);
coex_dm->ps_tdma_du_adj_type = 9;
} else if (coex_dm->cur_ps_tdma == 11) {
halbtc8723b1ant_ps_tdma(btcoexist, NORMAL_EXEC,
true, 9);
coex_dm->ps_tdma_du_adj_type = 9;
} else if (coex_dm->cur_ps_tdma == 9) {
halbtc8723b1ant_ps_tdma(btcoexist, NORMAL_EXEC,
true, 2);
coex_dm->ps_tdma_du_adj_type = 2;
} else if (coex_dm->cur_ps_tdma == 2) {
halbtc8723b1ant_ps_tdma(btcoexist, NORMAL_EXEC,
true, 1);
coex_dm->ps_tdma_du_adj_type = 1;
}
} else { /*no change */
/*if busy / idle change */
if (wifi_busy != pre_wifi_busy) {
pre_wifi_busy = wifi_busy;
halbtc8723b1ant_ps_tdma(btcoexist, FORCE_EXEC,
true,
coex_dm->cur_ps_tdma);
}
BTC_PRINT(BTC_MSG_ALGORITHM, ALGO_TRACE_FW_DETAIL,
"[BTCoex],********* TDMA(on, %d) ********\n",
coex_dm->cur_ps_tdma);
}
if (coex_dm->cur_ps_tdma != 1 && coex_dm->cur_ps_tdma != 2 &&
coex_dm->cur_ps_tdma != 9 && coex_dm->cur_ps_tdma != 11) {
/* recover to previous adjust type */
halbtc8723b1ant_ps_tdma(btcoexist, NORMAL_EXEC, true,
coex_dm->ps_tdma_du_adj_type);
}
}
}
u8 halbtc8723b1ant_ps_tdma_type_by_wifi_rssi(s32 wifi_rssi, s32 pre_wifi_rssi,
u8 wifi_rssi_thresh)
{
u8 ps_tdma_type=0;
if (wifi_rssi > pre_wifi_rssi) {
if (wifi_rssi > (wifi_rssi_thresh + 5))
ps_tdma_type = 26;
else
ps_tdma_type = 25;
} else {
if (wifi_rssi > wifi_rssi_thresh)
ps_tdma_type = 26;
else
ps_tdma_type = 25;
}
return ps_tdma_type;
}
void halbtc8723b1ant_PsTdmaCheckForPowerSaveState(struct btc_coexist *btcoexist,
bool new_ps_state)
{
u8 lps_mode = 0x0;
btcoexist->btc_get(btcoexist, BTC_GET_U1_LPS_MODE, &lps_mode);
if (lps_mode) { /* already under LPS state */
if (new_ps_state) {
/* keep state under LPS, do nothing. */
} else {
/* will leave LPS state, turn off psTdma first */
halbtc8723b1ant_ps_tdma(btcoexist, NORMAL_EXEC,
false, 0);
}
} else { /* NO PS state */
if (new_ps_state) {
/* will enter LPS state, turn off psTdma first */
halbtc8723b1ant_ps_tdma(btcoexist, NORMAL_EXEC,
false, 0);
} else {
/* keep state under NO PS state, do nothing. */
}
}
}
void halbtc8723b1ant_power_save_state(struct btc_coexist *btcoexist,
u8 ps_type, u8 lps_val,
u8 rpwm_val)
{
bool low_pwr_disable = false;
switch (ps_type) {
case BTC_PS_WIFI_NATIVE:
/* recover to original 32k low power setting */
low_pwr_disable = false;
btcoexist->btc_set(btcoexist, BTC_SET_ACT_DISABLE_LOW_POWER,
&low_pwr_disable);
btcoexist->btc_set(btcoexist, BTC_SET_ACT_NORMAL_LPS, NULL);
break;
case BTC_PS_LPS_ON:
halbtc8723b1ant_PsTdmaCheckForPowerSaveState(btcoexist, true);
halbtc8723b1ant_LpsRpwm(btcoexist, NORMAL_EXEC, lps_val,
rpwm_val);
/* when coex force to enter LPS, do not enter 32k low power. */
low_pwr_disable = true;
btcoexist->btc_set(btcoexist, BTC_SET_ACT_DISABLE_LOW_POWER,
&low_pwr_disable);
/* power save must executed before psTdma. */
btcoexist->btc_set(btcoexist, BTC_SET_ACT_ENTER_LPS, NULL);
break;
case BTC_PS_LPS_OFF:
halbtc8723b1ant_PsTdmaCheckForPowerSaveState(btcoexist, false);
btcoexist->btc_set(btcoexist, BTC_SET_ACT_LEAVE_LPS, NULL);
break;
default:
break;
}
}
void halbtc8723b1ant_action_wifi_only(struct btc_coexist *btcoexist)
{
halbtc8723b1ant_coex_table_with_type(btcoexist, NORMAL_EXEC, 0);
halbtc8723b1ant_ps_tdma(btcoexist, NORMAL_EXEC, false, 9);
}
void halbtc8723b1ant_monitor_bt_enable_disable(struct btc_coexist *btcoexist)
{
static bool pre_bt_disabled = false;
static u32 bt_disable_cnt = 0;
bool bt_active = true, bt_disabled = false;
/* This function check if bt is disabled */
if (coex_sta->high_priority_tx == 0 &&
coex_sta->high_priority_rx == 0 &&
coex_sta->low_priority_tx == 0 &&
coex_sta->low_priority_rx == 0)
bt_active = false;
if (coex_sta->high_priority_tx == 0xffff &&
coex_sta->high_priority_rx == 0xffff &&
coex_sta->low_priority_tx == 0xffff &&
coex_sta->low_priority_rx == 0xffff)
bt_active = false;
if (bt_active) {
bt_disable_cnt = 0;
bt_disabled = false;
btcoexist->btc_set(btcoexist, BTC_SET_BL_BT_DISABLE,
&bt_disabled);
BTC_PRINT(BTC_MSG_ALGORITHM, ALGO_BT_MONITOR,
"[BTCoex], BT is enabled !!\n");
} else {
bt_disable_cnt++;
BTC_PRINT(BTC_MSG_ALGORITHM, ALGO_BT_MONITOR,
"[BTCoex], bt all counters=0, %d times!!\n",
bt_disable_cnt);
if (bt_disable_cnt >= 2) {
bt_disabled = true;
btcoexist->btc_set(btcoexist, BTC_SET_BL_BT_DISABLE,
&bt_disabled);
BTC_PRINT(BTC_MSG_ALGORITHM, ALGO_BT_MONITOR,
"[BTCoex], BT is disabled !!\n");
halbtc8723b1ant_action_wifi_only(btcoexist);
}
}
if (pre_bt_disabled != bt_disabled) {
BTC_PRINT(BTC_MSG_ALGORITHM, ALGO_BT_MONITOR,
"[BTCoex], BT is from %s to %s!!\n",
(pre_bt_disabled ? "disabled" : "enabled"),
(bt_disabled ? "disabled" : "enabled"));
pre_bt_disabled = bt_disabled;
if (!bt_disabled) {
} else {
btcoexist->btc_set(btcoexist, BTC_SET_ACT_LEAVE_LPS,
NULL);
btcoexist->btc_set(btcoexist, BTC_SET_ACT_NORMAL_LPS,
NULL);
}
}
}
/***************************************************
*
* Software Coex Mechanism start
*
***************************************************/
/* SCO only or SCO+PAN(HS) */
void halbtc8723b1ant_action_sco(struct btc_coexist *btcoexist)
{
u8 wifi_rssi_state;
u32 wifi_bw;
wifi_rssi_state =
halbtc8723b1ant_wifi_rssi_state(btcoexist, 0, 2, 25, 0);
halbtc8723b1ant_fw_dac_swing_lvl(btcoexist, NORMAL_EXEC, 4);
if (halbtc8723b1ant_need_to_dec_bt_pwr(btcoexist))
halbtc8723b1ant_dec_bt_pwr(btcoexist, NORMAL_EXEC, false);
else
halbtc8723b1ant_dec_bt_pwr(btcoexist, NORMAL_EXEC, false);
btcoexist->btc_get(btcoexist, BTC_GET_U4_WIFI_BW, &wifi_bw);
if (BTC_WIFI_BW_HT40 == wifi_bw) {
/* sw mechanism */
if ((wifi_rssi_state == BTC_RSSI_STATE_HIGH) ||
(wifi_rssi_state == BTC_RSSI_STATE_STAY_HIGH)) {
halbtc8723b1ant_sw_mechanism1(btcoexist, false, true,
false, false);
halbtc8723b1ant_sw_mechanism2(btcoexist, false, false,
false, 0x18);
} else {
halbtc8723b1ant_sw_mechanism1(btcoexist, false, true,
false, false);
halbtc8723b1ant_sw_mechanism2(btcoexist, false, false,
false, 0x18);
}
} else {
/* sw mechanism */
if ((wifi_rssi_state == BTC_RSSI_STATE_HIGH) ||
(wifi_rssi_state == BTC_RSSI_STATE_STAY_HIGH)) {
halbtc8723b1ant_sw_mechanism1(btcoexist, false, true,
false, false);
halbtc8723b1ant_sw_mechanism2(btcoexist, false, false,
false, 0x18);
} else {
halbtc8723b1ant_sw_mechanism1(btcoexist, false, true,
false, false);
halbtc8723b1ant_sw_mechanism2(btcoexist, false, false,
false, 0x18);
}
}
}
void halbtc8723b1ant_action_hid(struct btc_coexist *btcoexist)
{
u8 wifi_rssi_state, bt_rssi_state;
u32 wifi_bw;
wifi_rssi_state = halbtc8723b1ant_wifi_rssi_state(btcoexist,
0, 2, 25, 0);
bt_rssi_state = halbtc8723b1ant_bt_rssi_state(2, 50, 0);
halbtc8723b1ant_fw_dac_swing_lvl(btcoexist, NORMAL_EXEC, 6);
if (halbtc8723b1ant_need_to_dec_bt_pwr(btcoexist))
halbtc8723b1ant_dec_bt_pwr(btcoexist, NORMAL_EXEC, false);
else
halbtc8723b1ant_dec_bt_pwr(btcoexist, NORMAL_EXEC, false);
btcoexist->btc_get(btcoexist,
BTC_GET_U4_WIFI_BW, &wifi_bw);
if (BTC_WIFI_BW_HT40 == wifi_bw) {
/* sw mechanism */
if ((wifi_rssi_state == BTC_RSSI_STATE_HIGH) ||
(wifi_rssi_state == BTC_RSSI_STATE_STAY_HIGH)) {
halbtc8723b1ant_sw_mechanism1(btcoexist, false, true,
false, false);
halbtc8723b1ant_sw_mechanism2(btcoexist, false, false,
false, 0x18);
} else {
halbtc8723b1ant_sw_mechanism1(btcoexist, false, true,
false, false);
halbtc8723b1ant_sw_mechanism2(btcoexist, false, false,
false, 0x18);
}
} else {
/* sw mechanism */
if ((wifi_rssi_state == BTC_RSSI_STATE_HIGH) ||
(wifi_rssi_state == BTC_RSSI_STATE_STAY_HIGH)) {
halbtc8723b1ant_sw_mechanism1(btcoexist, false, true,
false, false);
halbtc8723b1ant_sw_mechanism2(btcoexist, false, false,
false, 0x18);
} else {
halbtc8723b1ant_sw_mechanism1(btcoexist, false, true,
false, false);
halbtc8723b1ant_sw_mechanism2(btcoexist, false, false,
false, 0x18);
}
}
}
/*A2DP only / PAN(EDR) only/ A2DP+PAN(HS) */
void halbtc8723b1ant_action_a2dp(struct btc_coexist *btcoexist)
{
u8 wifi_rssi_state, bt_rssi_state;
u32 wifi_bw;
wifi_rssi_state = halbtc8723b1ant_wifi_rssi_state(btcoexist,
0, 2, 25, 0);
bt_rssi_state = halbtc8723b1ant_bt_rssi_state(2, 50, 0);
halbtc8723b1ant_fw_dac_swing_lvl(btcoexist, NORMAL_EXEC, 6);
if (halbtc8723b1ant_need_to_dec_bt_pwr(btcoexist))
halbtc8723b1ant_dec_bt_pwr(btcoexist, NORMAL_EXEC, false);
else
halbtc8723b1ant_dec_bt_pwr(btcoexist, NORMAL_EXEC, false);
btcoexist->btc_get(btcoexist, BTC_GET_U4_WIFI_BW, &wifi_bw);
if (BTC_WIFI_BW_HT40 == wifi_bw) {
/* sw mechanism */
if ((wifi_rssi_state == BTC_RSSI_STATE_HIGH) ||
(wifi_rssi_state == BTC_RSSI_STATE_STAY_HIGH)) {
halbtc8723b1ant_sw_mechanism1(btcoexist, false, false,
false, false);
halbtc8723b1ant_sw_mechanism2(btcoexist, false, false,
false, 0x18);
} else {
halbtc8723b1ant_sw_mechanism1(btcoexist, false, false,
false, false);
halbtc8723b1ant_sw_mechanism2(btcoexist, false, false,
false, 0x18);
}
} else {
/* sw mechanism */
if ((wifi_rssi_state == BTC_RSSI_STATE_HIGH) ||
(wifi_rssi_state == BTC_RSSI_STATE_STAY_HIGH)) {
halbtc8723b1ant_sw_mechanism1(btcoexist, false, false,
false, false);
halbtc8723b1ant_sw_mechanism2(btcoexist, false, false,
false, 0x18);
} else {
halbtc8723b1ant_sw_mechanism1(btcoexist, false, false,
false, false);
halbtc8723b1ant_sw_mechanism2(btcoexist, false, false,
false, 0x18);
}
}
}
void halbtc8723b1ant_action_a2dp_pan_hs(struct btc_coexist *btcoexist)
{
u8 wifi_rssi_state, bt_rssi_state, bt_info_ext;
u32 wifi_bw;
bt_info_ext = coex_sta->bt_info_ext;
wifi_rssi_state = halbtc8723b1ant_wifi_rssi_state(btcoexist,
0, 2, 25, 0);
bt_rssi_state = halbtc8723b1ant_bt_rssi_state(2, 50, 0);
halbtc8723b1ant_fw_dac_swing_lvl(btcoexist, NORMAL_EXEC, 6);
if (halbtc8723b1ant_need_to_dec_bt_pwr(btcoexist))
halbtc8723b1ant_dec_bt_pwr(btcoexist, NORMAL_EXEC, false);
else
halbtc8723b1ant_dec_bt_pwr(btcoexist, NORMAL_EXEC, false);
btcoexist->btc_get(btcoexist, BTC_GET_U4_WIFI_BW, &wifi_bw);
if (BTC_WIFI_BW_HT40 == wifi_bw) {
/* sw mechanism */
if ((wifi_rssi_state == BTC_RSSI_STATE_HIGH) ||
(wifi_rssi_state == BTC_RSSI_STATE_STAY_HIGH)) {
halbtc8723b1ant_sw_mechanism1(btcoexist, false, false,
false, false);
halbtc8723b1ant_sw_mechanism2(btcoexist, false, false,
false, 0x18);
} else {
halbtc8723b1ant_sw_mechanism1(btcoexist, false, false,
false, false);
halbtc8723b1ant_sw_mechanism2(btcoexist, false, false,
false, 0x18);
}
} else {
/* sw mechanism */
if ((wifi_rssi_state == BTC_RSSI_STATE_HIGH) ||
(wifi_rssi_state == BTC_RSSI_STATE_STAY_HIGH)) {
halbtc8723b1ant_sw_mechanism1(btcoexist, false, false,
false, false);
halbtc8723b1ant_sw_mechanism2(btcoexist, false, false,
false, 0x18);
} else {
halbtc8723b1ant_sw_mechanism1(btcoexist, false, false,
false, false);
halbtc8723b1ant_sw_mechanism2(btcoexist, false, false,
false, 0x18);
}
}
}
void halbtc8723b1ant_action_pan_edr(struct btc_coexist *btcoexist)
{
u8 wifi_rssi_state, bt_rssi_state;
u32 wifi_bw;
wifi_rssi_state = halbtc8723b1ant_wifi_rssi_state(btcoexist,
0, 2, 25, 0);
bt_rssi_state = halbtc8723b1ant_bt_rssi_state(2, 50, 0);
halbtc8723b1ant_fw_dac_swing_lvl(btcoexist, NORMAL_EXEC, 6);
if (halbtc8723b1ant_need_to_dec_bt_pwr(btcoexist))
halbtc8723b1ant_dec_bt_pwr(btcoexist, NORMAL_EXEC, false);
else
halbtc8723b1ant_dec_bt_pwr(btcoexist, NORMAL_EXEC, false);
btcoexist->btc_get(btcoexist, BTC_GET_U4_WIFI_BW, &wifi_bw);
if (BTC_WIFI_BW_HT40 == wifi_bw) {
/* sw mechanism */
if ((wifi_rssi_state == BTC_RSSI_STATE_HIGH) ||
(wifi_rssi_state == BTC_RSSI_STATE_STAY_HIGH)) {
halbtc8723b1ant_sw_mechanism1(btcoexist, false, false,
false, false);
halbtc8723b1ant_sw_mechanism2(btcoexist, false, false,
false, 0x18);
} else {
halbtc8723b1ant_sw_mechanism1(btcoexist, false, false,
false, false);
halbtc8723b1ant_sw_mechanism2(btcoexist, false, false,
false, 0x18);
}
} else {
/* sw mechanism */
if ((wifi_rssi_state == BTC_RSSI_STATE_HIGH) ||
(wifi_rssi_state == BTC_RSSI_STATE_STAY_HIGH)) {
halbtc8723b1ant_sw_mechanism1(btcoexist, false, false,
false, false);
halbtc8723b1ant_sw_mechanism2(btcoexist, false, false,
false, 0x18);
} else {
halbtc8723b1ant_sw_mechanism1(btcoexist, false, false,
false, false);
halbtc8723b1ant_sw_mechanism2(btcoexist, false, false,
false, 0x18);
}
}
}
/* PAN(HS) only */
void halbtc8723b1ant_action_pan_hs(struct btc_coexist *btcoexist)
{
u8 wifi_rssi_state, bt_rssi_state;
u32 wifi_bw;
wifi_rssi_state = halbtc8723b1ant_wifi_rssi_state(btcoexist,
0, 2, 25, 0);
bt_rssi_state = halbtc8723b1ant_bt_rssi_state(2, 50, 0);
halbtc8723b1ant_fw_dac_swing_lvl(btcoexist, NORMAL_EXEC, 6);
btcoexist->btc_get(btcoexist, BTC_GET_U4_WIFI_BW, &wifi_bw);
if (BTC_WIFI_BW_HT40 == wifi_bw) {
/* fw mechanism */
if((wifi_rssi_state == BTC_RSSI_STATE_HIGH) ||
(wifi_rssi_state == BTC_RSSI_STATE_STAY_HIGH))
halbtc8723b1ant_dec_bt_pwr(btcoexist, NORMAL_EXEC,
false);
else
halbtc8723b1ant_dec_bt_pwr(btcoexist, NORMAL_EXEC,
false);
/* sw mechanism */
if ((wifi_rssi_state == BTC_RSSI_STATE_HIGH) ||
(wifi_rssi_state == BTC_RSSI_STATE_STAY_HIGH)) {
halbtc8723b1ant_sw_mechanism1(btcoexist, false, false,
false, false);
halbtc8723b1ant_sw_mechanism2(btcoexist, false, false,
false, 0x18);
} else {
halbtc8723b1ant_sw_mechanism1(btcoexist, false, false,
false, false);
halbtc8723b1ant_sw_mechanism2(btcoexist, false, false,
false, 0x18);
}
} else {
/* fw mechanism */
if ((wifi_rssi_state == BTC_RSSI_STATE_HIGH) ||
(wifi_rssi_state == BTC_RSSI_STATE_STAY_HIGH))
halbtc8723b1ant_dec_bt_pwr(btcoexist, NORMAL_EXEC,
false);
else
halbtc8723b1ant_dec_bt_pwr(btcoexist, NORMAL_EXEC,
false);
/* sw mechanism */
if ((wifi_rssi_state == BTC_RSSI_STATE_HIGH) ||
(wifi_rssi_state == BTC_RSSI_STATE_STAY_HIGH)) {
halbtc8723b1ant_sw_mechanism1(btcoexist, false, false,
false, false);
halbtc8723b1ant_sw_mechanism2(btcoexist, false, false,
false, 0x18);
} else {
halbtc8723b1ant_sw_mechanism1(btcoexist, false, false,
false, false);
halbtc8723b1ant_sw_mechanism2(btcoexist, false, false,
false, 0x18);
}
}
}
/*PAN(EDR)+A2DP */
void halbtc8723b1ant_action_pan_edr_a2dp(struct btc_coexist *btcoexist)
{
u8 wifi_rssi_state, bt_rssi_state, bt_info_ext;
u32 wifi_bw;
bt_info_ext = coex_sta->bt_info_ext;
wifi_rssi_state = halbtc8723b1ant_wifi_rssi_state(btcoexist,
0, 2, 25, 0);
bt_rssi_state = halbtc8723b1ant_bt_rssi_state(2, 50, 0);
halbtc8723b1ant_fw_dac_swing_lvl(btcoexist, NORMAL_EXEC, 6);
if (halbtc8723b1ant_need_to_dec_bt_pwr(btcoexist))
halbtc8723b1ant_dec_bt_pwr(btcoexist, NORMAL_EXEC, false);
else
halbtc8723b1ant_dec_bt_pwr(btcoexist, NORMAL_EXEC, false);
btcoexist->btc_get(btcoexist,
BTC_GET_U4_WIFI_BW, &wifi_bw);
if (BTC_WIFI_BW_HT40 == wifi_bw) {
/* sw mechanism */
if ((wifi_rssi_state == BTC_RSSI_STATE_HIGH) ||
(wifi_rssi_state == BTC_RSSI_STATE_STAY_HIGH)) {
halbtc8723b1ant_sw_mechanism1(btcoexist, false, false,
false, false);
halbtc8723b1ant_sw_mechanism2(btcoexist, false, false,
false, 0x18);
} else {
halbtc8723b1ant_sw_mechanism1(btcoexist, false, false,
false, false);
halbtc8723b1ant_sw_mechanism2(btcoexist, false, false,
false, 0x18);
}
} else {
/* sw mechanism */
if ((wifi_rssi_state == BTC_RSSI_STATE_HIGH) ||
(wifi_rssi_state == BTC_RSSI_STATE_STAY_HIGH)) {
halbtc8723b1ant_sw_mechanism1(btcoexist, false, false,
false, false);
halbtc8723b1ant_sw_mechanism2(btcoexist, false, false,
false, 0x18);
} else {
halbtc8723b1ant_sw_mechanism1(btcoexist, false, false,
false, false);
halbtc8723b1ant_sw_mechanism2(btcoexist, false, false,
false, 0x18);
}
}
}
void halbtc8723b1ant_action_pan_edr_hid(struct btc_coexist *btcoexist)
{
u8 wifi_rssi_state, bt_rssi_state;
u32 wifi_bw;
wifi_rssi_state = halbtc8723b1ant_wifi_rssi_state(btcoexist,
0, 2, 25, 0);
bt_rssi_state = halbtc8723b1ant_bt_rssi_state(2, 50, 0);
halbtc8723b1ant_fw_dac_swing_lvl(btcoexist, NORMAL_EXEC, 6);
if (halbtc8723b1ant_need_to_dec_bt_pwr(btcoexist))
halbtc8723b1ant_dec_bt_pwr(btcoexist, NORMAL_EXEC, false);
else
halbtc8723b1ant_dec_bt_pwr(btcoexist, NORMAL_EXEC, false);
btcoexist->btc_get(btcoexist, BTC_GET_U4_WIFI_BW, &wifi_bw);
if (BTC_WIFI_BW_HT40 == wifi_bw) {
/* sw mechanism */
if ((wifi_rssi_state == BTC_RSSI_STATE_HIGH) ||
(wifi_rssi_state == BTC_RSSI_STATE_STAY_HIGH)) {
halbtc8723b1ant_sw_mechanism1(btcoexist, false, true,
false, false);
halbtc8723b1ant_sw_mechanism2(btcoexist, false, false,
false, 0x18);
} else {
halbtc8723b1ant_sw_mechanism1(btcoexist, false, true,
false, false);
halbtc8723b1ant_sw_mechanism2(btcoexist, false, false,
false, 0x18);
}
} else {
/* sw mechanism */
if ((wifi_rssi_state == BTC_RSSI_STATE_HIGH) ||
(wifi_rssi_state == BTC_RSSI_STATE_STAY_HIGH)) {
halbtc8723b1ant_sw_mechanism1(btcoexist, false, true,
false, false);
halbtc8723b1ant_sw_mechanism2(btcoexist, false, false,
false, 0x18);
} else {
halbtc8723b1ant_sw_mechanism1(btcoexist, false, true,
false, false);
halbtc8723b1ant_sw_mechanism2(btcoexist, false, false,
false, 0x18);
}
}
}
/* HID+A2DP+PAN(EDR) */
void halbtc8723b1ant_action_hid_a2dp_pan_edr(struct btc_coexist *btcoexist)
{
u8 wifi_rssi_state, bt_rssi_state, bt_info_ext;
u32 wifi_bw;
bt_info_ext = coex_sta->bt_info_ext;
wifi_rssi_state = halbtc8723b1ant_wifi_rssi_state(btcoexist,
0, 2, 25, 0);
bt_rssi_state = halbtc8723b1ant_bt_rssi_state(2, 50, 0);
halbtc8723b1ant_fw_dac_swing_lvl(btcoexist, NORMAL_EXEC, 6);
if (halbtc8723b1ant_need_to_dec_bt_pwr(btcoexist))
halbtc8723b1ant_dec_bt_pwr(btcoexist, NORMAL_EXEC, false);
else
halbtc8723b1ant_dec_bt_pwr(btcoexist, NORMAL_EXEC, false);
btcoexist->btc_get(btcoexist, BTC_GET_U4_WIFI_BW, &wifi_bw);
if (BTC_WIFI_BW_HT40 == wifi_bw) {
/* sw mechanism */
if((wifi_rssi_state == BTC_RSSI_STATE_HIGH) ||
(wifi_rssi_state == BTC_RSSI_STATE_STAY_HIGH)) {
halbtc8723b1ant_sw_mechanism1(btcoexist, false, true,
false, false);
halbtc8723b1ant_sw_mechanism2(btcoexist, false, false,
false, 0x18);
} else {
halbtc8723b1ant_sw_mechanism1(btcoexist, false, true,
false, false);
halbtc8723b1ant_sw_mechanism2(btcoexist, false, false,
false, 0x18);
}
} else {
/* sw mechanism */
if ((wifi_rssi_state == BTC_RSSI_STATE_HIGH) ||
(wifi_rssi_state == BTC_RSSI_STATE_STAY_HIGH)) {
halbtc8723b1ant_sw_mechanism1(btcoexist, false, true,
false, false);
halbtc8723b1ant_sw_mechanism2(btcoexist, false, false,
false, 0x18);
} else {
halbtc8723b1ant_sw_mechanism1(btcoexist, false, true,
false, false);
halbtc8723b1ant_sw_mechanism2(btcoexist, false, false,
false, 0x18);
}
}
}
void halbtc8723b1ant_action_hid_a2dp(struct btc_coexist *btcoexist)
{
u8 wifi_rssi_state, bt_rssi_state, bt_info_ext;
u32 wifi_bw;
bt_info_ext = coex_sta->bt_info_ext;
wifi_rssi_state = halbtc8723b1ant_wifi_rssi_state(btcoexist,
0, 2, 25, 0);
bt_rssi_state = halbtc8723b1ant_bt_rssi_state(2, 50, 0);
if (halbtc8723b1ant_need_to_dec_bt_pwr(btcoexist))
halbtc8723b1ant_dec_bt_pwr(btcoexist, NORMAL_EXEC, false);
else
halbtc8723b1ant_dec_bt_pwr(btcoexist, NORMAL_EXEC, false);
btcoexist->btc_get(btcoexist, BTC_GET_U4_WIFI_BW, &wifi_bw);
if (BTC_WIFI_BW_HT40 == wifi_bw) {
/* sw mechanism */
if ((wifi_rssi_state == BTC_RSSI_STATE_HIGH) ||
(wifi_rssi_state == BTC_RSSI_STATE_STAY_HIGH)) {
halbtc8723b1ant_sw_mechanism1(btcoexist, false, true,
false, false);
halbtc8723b1ant_sw_mechanism2(btcoexist, false, false,
false, 0x18);
} else {
halbtc8723b1ant_sw_mechanism1(btcoexist, false, true,
false, false);
halbtc8723b1ant_sw_mechanism2(btcoexist, false, false,
false, 0x18);
}
} else {
/* sw mechanism */
if ((wifi_rssi_state == BTC_RSSI_STATE_HIGH) ||
(wifi_rssi_state == BTC_RSSI_STATE_STAY_HIGH)) {
halbtc8723b1ant_sw_mechanism1(btcoexist, false, true,
false, false);
halbtc8723b1ant_sw_mechanism2(btcoexist, false, false,
false, 0x18);
} else {
halbtc8723b1ant_sw_mechanism1(btcoexist, false, true,
false, false);
halbtc8723b1ant_sw_mechanism2(btcoexist, false, false,
false, 0x18);
}
}
}
/*****************************************************
*
* Non-Software Coex Mechanism start
*
*****************************************************/
void halbtc8723b1ant_action_hs(struct btc_coexist *btcoexist)
{
halbtc8723b1ant_ps_tdma(btcoexist, NORMAL_EXEC, true, 5);
halbtc8723b1ant_coex_table_with_type(btcoexist, FORCE_EXEC, 2);
}
void halbtc8723b1ant_action_bt_inquiry(struct btc_coexist *btcoexist)
{
struct btc_bt_link_info *bt_link_info = &btcoexist->bt_link_info;
bool wifi_connected = false, ap_enable = false;
btcoexist->btc_get(btcoexist, BTC_GET_BL_WIFI_AP_MODE_ENABLE,
&ap_enable);
btcoexist->btc_get(btcoexist, BTC_GET_BL_WIFI_CONNECTED,
&wifi_connected);
if (!wifi_connected) {
halbtc8723b1ant_power_save_state(btcoexist,
BTC_PS_WIFI_NATIVE, 0x0, 0x0);
halbtc8723b1ant_ps_tdma(btcoexist, NORMAL_EXEC, true, 5);
halbtc8723b1ant_coex_table_with_type(btcoexist, NORMAL_EXEC, 1);
} else if (bt_link_info->sco_exist || bt_link_info->hid_only) {
/* SCO/HID-only busy */
halbtc8723b1ant_power_save_state(btcoexist, BTC_PS_WIFI_NATIVE,
0x0, 0x0);
halbtc8723b1ant_ps_tdma(btcoexist, NORMAL_EXEC, true, 32);
halbtc8723b1ant_coex_table_with_type(btcoexist, NORMAL_EXEC, 1);
} else {
if (ap_enable)
halbtc8723b1ant_power_save_state(btcoexist,
BTC_PS_WIFI_NATIVE,
0x0, 0x0);
else
halbtc8723b1ant_power_save_state(btcoexist,
BTC_PS_LPS_ON,
0x50, 0x4);
halbtc8723b1ant_ps_tdma(btcoexist, NORMAL_EXEC, true, 30);
halbtc8723b1ant_coex_table_with_type(btcoexist, NORMAL_EXEC, 1);
}
}
void halbtc8723b1ant_action_bt_sco_hid_only_busy(struct btc_coexist * btcoexist,
u8 wifi_status)
{
struct btc_bt_link_info *bt_link_info = &btcoexist->bt_link_info;
bool wifi_connected = false;
btcoexist->btc_get(btcoexist, BTC_GET_BL_WIFI_CONNECTED,
&wifi_connected);
/* tdma and coex table */
if (bt_link_info->sco_exist) {
halbtc8723b1ant_ps_tdma(btcoexist, NORMAL_EXEC, true, 5);
halbtc8723b1ant_coex_table_with_type(btcoexist, NORMAL_EXEC, 2);
} else { /* HID */
halbtc8723b1ant_ps_tdma(btcoexist, NORMAL_EXEC, true, 6);
halbtc8723b1ant_coex_table_with_type(btcoexist, NORMAL_EXEC, 5);
}
}
void halbtc8723b1ant_action_wifi_connected_bt_acl_busy(
struct btc_coexist *btcoexist,
u8 wifi_status)
{
u8 bt_rssi_state;
struct btc_bt_link_info *bt_link_info = &btcoexist->bt_link_info;
bt_rssi_state = halbtc8723b1ant_bt_rssi_state(2, 28, 0);
if (bt_link_info->hid_only) { /*HID */
halbtc8723b1ant_action_bt_sco_hid_only_busy(btcoexist,
wifi_status);
coex_dm->auto_tdma_adjust = false;
return;
} else if (bt_link_info->a2dp_only) { /*A2DP */
if ((bt_rssi_state == BTC_RSSI_STATE_HIGH) ||
(bt_rssi_state == BTC_RSSI_STATE_STAY_HIGH)) {
halbtc8723b1ant_tdma_duration_adjust_for_acl(btcoexist,
wifi_status);
} else { /*for low BT RSSI */
halbtc8723b1ant_ps_tdma(btcoexist, NORMAL_EXEC,
true, 11);
coex_dm->auto_tdma_adjust = false;
}
halbtc8723b1ant_coex_table_with_type(btcoexist, NORMAL_EXEC, 1);
} else if (bt_link_info->hid_exist &&
bt_link_info->a2dp_exist) { /*HID+A2DP */
if ((bt_rssi_state == BTC_RSSI_STATE_HIGH) ||
(bt_rssi_state == BTC_RSSI_STATE_STAY_HIGH)) {
halbtc8723b1ant_ps_tdma(btcoexist, NORMAL_EXEC,
true, 14);
coex_dm->auto_tdma_adjust = false;
} else { /*for low BT RSSI*/
halbtc8723b1ant_ps_tdma(btcoexist, NORMAL_EXEC,
true, 14);
coex_dm->auto_tdma_adjust = false;
}
halbtc8723b1ant_coex_table_with_type(btcoexist, NORMAL_EXEC, 6);
/*PAN(OPP,FTP), HID+PAN(OPP,FTP) */
} else if (bt_link_info->pan_only ||
(bt_link_info->hid_exist && bt_link_info->pan_exist)) {
halbtc8723b1ant_ps_tdma(btcoexist, NORMAL_EXEC, true, 3);
halbtc8723b1ant_coex_table_with_type(btcoexist, NORMAL_EXEC, 6);
coex_dm->auto_tdma_adjust = false;
/*A2DP+PAN(OPP,FTP), HID+A2DP+PAN(OPP,FTP)*/
} else if ((bt_link_info->a2dp_exist && bt_link_info->pan_exist) ||
(bt_link_info->hid_exist && bt_link_info->a2dp_exist &&
bt_link_info->pan_exist)) {
halbtc8723b1ant_ps_tdma(btcoexist, NORMAL_EXEC, true, 13);
halbtc8723b1ant_coex_table_with_type(btcoexist, NORMAL_EXEC, 1);
coex_dm->auto_tdma_adjust = false;
} else {
halbtc8723b1ant_ps_tdma(btcoexist, NORMAL_EXEC, true, 11);
halbtc8723b1ant_coex_table_with_type(btcoexist, NORMAL_EXEC, 1);
coex_dm->auto_tdma_adjust = false;
}
}
void halbtc8723b1ant_action_wifi_not_connected(struct btc_coexist *btcoexist)
{
/* power save state */
halbtc8723b1ant_power_save_state(btcoexist, BTC_PS_WIFI_NATIVE,
0x0, 0x0);
/* tdma and coex table */
halbtc8723b1ant_ps_tdma(btcoexist, NORMAL_EXEC, false, 8);
halbtc8723b1ant_coex_table_with_type(btcoexist, NORMAL_EXEC, 0);
}
void halbtc8723b1ant_action_wifi_not_connected_asso_auth_scan(
struct btc_coexist *btcoexist)
{
halbtc8723b1ant_power_save_state(btcoexist, BTC_PS_WIFI_NATIVE,
0x0, 0x0);
halbtc8723b1ant_ps_tdma(btcoexist, NORMAL_EXEC, true, 22);
halbtc8723b1ant_coex_table_with_type(btcoexist, NORMAL_EXEC, 1);
}
void halbtc8723b1ant_ActionWifiConnectedScan(struct btc_coexist *btcoexist)
{
struct btc_bt_link_info *bt_link_info = &btcoexist->bt_link_info;
halbtc8723b1ant_power_save_state(btcoexist, BTC_PS_WIFI_NATIVE,
0x0, 0x0);
/* tdma and coex table */
if (BT_8723B_1ANT_BT_STATUS_ACL_BUSY == coex_dm->bt_status) {
if (bt_link_info->a2dp_exist &&
bt_link_info->pan_exist) {
halbtc8723b1ant_ps_tdma(btcoexist, NORMAL_EXEC,
true, 22);
halbtc8723b1ant_coex_table_with_type(btcoexist,
NORMAL_EXEC, 1);
} else {
halbtc8723b1ant_ps_tdma(btcoexist, NORMAL_EXEC, true, 20);
halbtc8723b1ant_coex_table_with_type(btcoexist, NORMAL_EXEC, 1);
}
} else if ((BT_8723B_1ANT_BT_STATUS_SCO_BUSY == coex_dm->bt_status) ||
(BT_8723B_1ANT_BT_STATUS_ACL_SCO_BUSY ==
coex_dm->bt_status)) {
halbtc8723b1ant_action_bt_sco_hid_only_busy(btcoexist,
BT_8723B_1ANT_WIFI_STATUS_CONNECTED_SCAN);
} else {
halbtc8723b1ant_ps_tdma(btcoexist, NORMAL_EXEC, true, 20);
halbtc8723b1ant_coex_table_with_type(btcoexist, NORMAL_EXEC, 1);
}
}
void halbtc8723b1ant_action_wifi_connected_special_packet(
struct btc_coexist *btcoexist)
{
bool hs_connecting = false;
struct btc_bt_link_info *bt_link_info = &btcoexist->bt_link_info;
btcoexist->btc_get(btcoexist, BTC_GET_BL_HS_CONNECTING, &hs_connecting);
halbtc8723b1ant_power_save_state(btcoexist, BTC_PS_WIFI_NATIVE,
0x0, 0x0);
/* tdma and coex table */
if (BT_8723B_1ANT_BT_STATUS_ACL_BUSY == coex_dm->bt_status) {
if (bt_link_info->a2dp_exist && bt_link_info->pan_exist) {
halbtc8723b1ant_ps_tdma(btcoexist, NORMAL_EXEC,
true, 22);
halbtc8723b1ant_coex_table_with_type(btcoexist,
NORMAL_EXEC, 1);
} else {
halbtc8723b1ant_ps_tdma(btcoexist, NORMAL_EXEC,
true, 20);
halbtc8723b1ant_coex_table_with_type(btcoexist,
NORMAL_EXEC, 1);
}
} else {
halbtc8723b1ant_ps_tdma(btcoexist, NORMAL_EXEC, true, 20);
halbtc8723b1ant_coex_table_with_type(btcoexist, NORMAL_EXEC, 1);
}
}
void halbtc8723b1ant_action_wifi_connected(struct btc_coexist *btcoexist)
{
bool wifi_busy = false;
bool scan = false, link = false, roam = false;
bool under_4way = false, ap_enable = false;
BTC_PRINT(BTC_MSG_ALGORITHM, ALGO_TRACE,
"[BTCoex], CoexForWifiConnect()===>\n");
btcoexist->btc_get(btcoexist, BTC_GET_BL_WIFI_4_WAY_PROGRESS,
&under_4way);
if (under_4way) {
halbtc8723b1ant_action_wifi_connected_special_packet(btcoexist);
BTC_PRINT(BTC_MSG_ALGORITHM, ALGO_TRACE,
"[BTCoex], CoexForWifiConnect(), "
"return for wifi is under 4way<===\n");
return;
}
btcoexist->btc_get(btcoexist, BTC_GET_BL_WIFI_SCAN, &scan);
btcoexist->btc_get(btcoexist, BTC_GET_BL_WIFI_LINK, &link);
btcoexist->btc_get(btcoexist, BTC_GET_BL_WIFI_ROAM, &roam);
if (scan || link || roam) {
halbtc8723b1ant_ActionWifiConnectedScan(btcoexist);
BTC_PRINT(BTC_MSG_ALGORITHM, ALGO_TRACE,
"[BTCoex], CoexForWifiConnect(), "
"return for wifi is under scan<===\n");
return;
}
btcoexist->btc_get(btcoexist, BTC_GET_BL_WIFI_AP_MODE_ENABLE,
&ap_enable);
/* power save state */
if (!ap_enable &&
BT_8723B_1ANT_BT_STATUS_ACL_BUSY == coex_dm->bt_status &&
!btcoexist->bt_link_info.hid_only)
halbtc8723b1ant_power_save_state(btcoexist, BTC_PS_LPS_ON,
0x50, 0x4);
else
halbtc8723b1ant_power_save_state(btcoexist, BTC_PS_WIFI_NATIVE,
0x0, 0x0);
/* tdma and coex table */
btcoexist->btc_get(btcoexist,
BTC_GET_BL_WIFI_BUSY, &wifi_busy);
if (!wifi_busy) {
if (BT_8723B_1ANT_BT_STATUS_ACL_BUSY == coex_dm->bt_status) {
halbtc8723b1ant_action_wifi_connected_bt_acl_busy(btcoexist,
BT_8723B_1ANT_WIFI_STATUS_CONNECTED_IDLE);
} else if ((BT_8723B_1ANT_BT_STATUS_SCO_BUSY ==
coex_dm->bt_status) ||
(BT_8723B_1ANT_BT_STATUS_ACL_SCO_BUSY ==
coex_dm->bt_status)) {
halbtc8723b1ant_action_bt_sco_hid_only_busy(btcoexist,
BT_8723B_1ANT_WIFI_STATUS_CONNECTED_IDLE);
} else {
halbtc8723b1ant_ps_tdma(btcoexist, NORMAL_EXEC,
false, 8);
halbtc8723b1ant_coex_table_with_type(btcoexist,
NORMAL_EXEC, 2);
}
} else {
if (BT_8723B_1ANT_BT_STATUS_ACL_BUSY == coex_dm->bt_status) {
halbtc8723b1ant_action_wifi_connected_bt_acl_busy(btcoexist,
BT_8723B_1ANT_WIFI_STATUS_CONNECTED_BUSY);
} else if ((BT_8723B_1ANT_BT_STATUS_SCO_BUSY ==
coex_dm->bt_status) ||
(BT_8723B_1ANT_BT_STATUS_ACL_SCO_BUSY ==
coex_dm->bt_status)) {
halbtc8723b1ant_action_bt_sco_hid_only_busy(btcoexist,
BT_8723B_1ANT_WIFI_STATUS_CONNECTED_BUSY);
} else {
halbtc8723b1ant_ps_tdma(btcoexist, NORMAL_EXEC, false, 8);
halbtc8723b1ant_coex_table_with_type(btcoexist,
NORMAL_EXEC, 2);
}
}
}
void halbtc8723b1ant_run_sw_coexist_mechanism(struct btc_coexist *btcoexist)
{
u8 algorithm = 0;
algorithm = halbtc8723b1ant_action_algorithm(btcoexist);
coex_dm->cur_algorithm = algorithm;
if (halbtc8723b1ant_is_common_action(btcoexist)) {
} else {
switch (coex_dm->cur_algorithm) {
case BT_8723B_1ANT_COEX_ALGO_SCO:
BTC_PRINT(BTC_MSG_ALGORITHM, ALGO_TRACE,
"[BTCoex], Action algorithm = SCO.\n");
halbtc8723b1ant_action_sco(btcoexist);
break;
case BT_8723B_1ANT_COEX_ALGO_HID:
BTC_PRINT(BTC_MSG_ALGORITHM, ALGO_TRACE,
"[BTCoex], Action algorithm = HID.\n");
halbtc8723b1ant_action_hid(btcoexist);
break;
case BT_8723B_1ANT_COEX_ALGO_A2DP:
BTC_PRINT(BTC_MSG_ALGORITHM, ALGO_TRACE,
"[BTCoex], Action algorithm = A2DP.\n");
halbtc8723b1ant_action_a2dp(btcoexist);
break;
case BT_8723B_1ANT_COEX_ALGO_A2DP_PANHS:
BTC_PRINT(BTC_MSG_ALGORITHM, ALGO_TRACE,
"[BTCoex], Action algorithm = "
"A2DP+PAN(HS).\n");
halbtc8723b1ant_action_a2dp_pan_hs(btcoexist);
break;
case BT_8723B_1ANT_COEX_ALGO_PANEDR:
BTC_PRINT(BTC_MSG_ALGORITHM, ALGO_TRACE,
"[BTCoex], Action algorithm = PAN(EDR).\n");
halbtc8723b1ant_action_pan_edr(btcoexist);
break;
case BT_8723B_1ANT_COEX_ALGO_PANHS:
BTC_PRINT(BTC_MSG_ALGORITHM, ALGO_TRACE,
"[BTCoex], Action algorithm = HS mode.\n");
halbtc8723b1ant_action_pan_hs(btcoexist);
break;
case BT_8723B_1ANT_COEX_ALGO_PANEDR_A2DP:
BTC_PRINT(BTC_MSG_ALGORITHM, ALGO_TRACE,
"[BTCoex], Action algorithm = PAN+A2DP.\n");
halbtc8723b1ant_action_pan_edr_a2dp(btcoexist);
break;
case BT_8723B_1ANT_COEX_ALGO_PANEDR_HID:
BTC_PRINT(BTC_MSG_ALGORITHM, ALGO_TRACE,
"[BTCoex], Action algorithm = "
"PAN(EDR)+HID.\n");
halbtc8723b1ant_action_pan_edr_hid(btcoexist);
break;
case BT_8723B_1ANT_COEX_ALGO_HID_A2DP_PANEDR:
BTC_PRINT(BTC_MSG_ALGORITHM, ALGO_TRACE,
"[BTCoex], Action algorithm = "
"HID+A2DP+PAN.\n");
halbtc8723b1ant_action_hid_a2dp_pan_edr(btcoexist);
break;
case BT_8723B_1ANT_COEX_ALGO_HID_A2DP:
BTC_PRINT(BTC_MSG_ALGORITHM, ALGO_TRACE,
"[BTCoex], Action algorithm = HID+A2DP.\n");
halbtc8723b1ant_action_hid_a2dp(btcoexist);
break;
default:
BTC_PRINT(BTC_MSG_ALGORITHM, ALGO_TRACE,
"[BTCoex], Action algorithm = "
"coexist All Off!!\n");
break;
}
coex_dm->pre_algorithm = coex_dm->cur_algorithm;
}
}
void halbtc8723b1ant_run_coexist_mechanism(struct btc_coexist *btcoexist)
{
struct btc_bt_link_info *bt_link_info = &btcoexist->bt_link_info;
bool wifi_connected = false, bt_hs_on = false;
bool limited_dig = false, bIncreaseScanDevNum = false;
bool b_bt_ctrl_agg_buf_size = false;
u8 agg_buf_size = 5;
u8 wifi_rssi_state = BTC_RSSI_STATE_HIGH;
BTC_PRINT(BTC_MSG_ALGORITHM, ALGO_TRACE,
"[BTCoex], RunCoexistMechanism()===>\n");
if (btcoexist->manual_control) {
BTC_PRINT(BTC_MSG_ALGORITHM, ALGO_TRACE,
"[BTCoex], RunCoexistMechanism(), "
"return for Manual CTRL <===\n");
return;
}
if (btcoexist->stop_coex_dm) {
BTC_PRINT(BTC_MSG_ALGORITHM, ALGO_TRACE,
"[BTCoex], RunCoexistMechanism(), "
"return for Stop Coex DM <===\n");
return;
}
if (coex_sta->under_ips) {
BTC_PRINT(BTC_MSG_ALGORITHM, ALGO_TRACE,
"[BTCoex], wifi is under IPS !!!\n");
return;
}
if ((BT_8723B_1ANT_BT_STATUS_ACL_BUSY == coex_dm->bt_status) ||
(BT_8723B_1ANT_BT_STATUS_SCO_BUSY == coex_dm->bt_status) ||
(BT_8723B_1ANT_BT_STATUS_ACL_SCO_BUSY == coex_dm->bt_status)) {
limited_dig = true;
bIncreaseScanDevNum = true;
}
btcoexist->btc_set(btcoexist, BTC_SET_BL_BT_LIMITED_DIG, &limited_dig);
btcoexist->btc_set(btcoexist, BTC_SET_BL_INC_SCAN_DEV_NUM,
&bIncreaseScanDevNum);
btcoexist->btc_get(btcoexist, BTC_GET_BL_WIFI_CONNECTED,
&wifi_connected);
if (!bt_link_info->sco_exist && !bt_link_info->hid_exist) {
halbtc8723b1ant_limited_tx(btcoexist, NORMAL_EXEC, 0, 0, 0, 0);
} else {
if (wifi_connected) {
wifi_rssi_state =
halbtc8723b1ant_wifi_rssi_state(btcoexist,
1, 2, 30, 0);
if ((wifi_rssi_state == BTC_RSSI_STATE_HIGH) ||
(wifi_rssi_state == BTC_RSSI_STATE_STAY_HIGH)) {
halbtc8723b1ant_limited_tx(btcoexist,
NORMAL_EXEC,
1, 1, 1, 1);
} else {
halbtc8723b1ant_limited_tx(btcoexist,
NORMAL_EXEC,
1, 1, 1, 1);
}
} else {
halbtc8723b1ant_limited_tx(btcoexist, NORMAL_EXEC,
0, 0, 0, 0);
}
}
if (bt_link_info->sco_exist) {
b_bt_ctrl_agg_buf_size = true;
agg_buf_size = 0x3;
} else if (bt_link_info->hid_exist) {
b_bt_ctrl_agg_buf_size = true;
agg_buf_size = 0x5;
} else if (bt_link_info->a2dp_exist || bt_link_info->pan_exist) {
b_bt_ctrl_agg_buf_size = true;
agg_buf_size = 0x8;
}
halbtc8723b1ant_limited_rx(btcoexist, NORMAL_EXEC, false,
b_bt_ctrl_agg_buf_size, agg_buf_size);
halbtc8723b1ant_run_sw_coexist_mechanism(btcoexist);
btcoexist->btc_get(btcoexist, BTC_GET_BL_HS_OPERATION, &bt_hs_on);
if (coex_sta->c2h_bt_inquiry_page) {
halbtc8723b1ant_action_bt_inquiry(btcoexist);
return;
} else if (bt_hs_on) {
halbtc8723b1ant_action_hs(btcoexist);
return;
}
if (!wifi_connected) {
bool scan = false, link = false, roam = false;
BTC_PRINT(BTC_MSG_ALGORITHM, ALGO_TRACE,
"[BTCoex], wifi is non connected-idle !!!\n");
btcoexist->btc_get(btcoexist, BTC_GET_BL_WIFI_SCAN, &scan);
btcoexist->btc_get(btcoexist, BTC_GET_BL_WIFI_LINK, &link);
btcoexist->btc_get(btcoexist, BTC_GET_BL_WIFI_ROAM, &roam);
if (scan || link || roam)
halbtc8723b1ant_action_wifi_not_connected_asso_auth_scan(btcoexist);
else
halbtc8723b1ant_action_wifi_not_connected(btcoexist);
} else { /* wifi LPS/Busy */
halbtc8723b1ant_action_wifi_connected(btcoexist);
}
}
void halbtc8723b1ant_init_coex_dm(struct btc_coexist *btcoexist)
{
/* force to reset coex mechanism */
halbtc8723b1ant_fw_dac_swing_lvl(btcoexist, FORCE_EXEC, 6);
halbtc8723b1ant_dec_bt_pwr(btcoexist, FORCE_EXEC, false);
/* sw all off */
halbtc8723b1ant_sw_mechanism1(btcoexist, false, false, false, false);
halbtc8723b1ant_sw_mechanism2(btcoexist,false, false, false, 0x18);
halbtc8723b1ant_ps_tdma(btcoexist, FORCE_EXEC, false, 8);
halbtc8723b1ant_coex_table_with_type(btcoexist, FORCE_EXEC, 0);
}
void halbtc8723b1ant_init_hw_config(struct btc_coexist *btcoexist, bool backup)
{
u32 u32tmp = 0;
u8 u8tmp = 0;
u32 cnt_bt_cal_chk = 0;
BTC_PRINT(BTC_MSG_INTERFACE, INTF_INIT,
"[BTCoex], 1Ant Init HW Config!!\n");
if (backup) {/* backup rf 0x1e value */
coex_dm->bt_rf0x1e_backup =
btcoexist->btc_get_rf_reg(btcoexist,
BTC_RF_A, 0x1e, 0xfffff);
coex_dm->backup_arfr_cnt1 =
btcoexist->btc_read_4byte(btcoexist, 0x430);
coex_dm->backup_arfr_cnt2 =
btcoexist->btc_read_4byte(btcoexist, 0x434);
coex_dm->backup_retry_limit =
btcoexist->btc_read_2byte(btcoexist, 0x42a);
coex_dm->backup_ampdu_max_time =
btcoexist->btc_read_1byte(btcoexist, 0x456);
}
/* WiFi goto standby while GNT_BT 0-->1 */
btcoexist->btc_set_rf_reg(btcoexist, BTC_RF_A, 0x1, 0xfffff, 0x780);
/* BT goto standby while GNT_BT 1-->0 */
btcoexist->btc_set_rf_reg(btcoexist, BTC_RF_A, 0x2, 0xfffff, 0x500);
btcoexist->btc_write_1byte(btcoexist, 0x974, 0xff);
btcoexist->btc_write_1byte_bitmask(btcoexist, 0x944, 0x3, 0x3);
btcoexist->btc_write_1byte(btcoexist, 0x930, 0x77);
/* BT calibration check */
while (cnt_bt_cal_chk <= 20) {
u32tmp = btcoexist->btc_read_4byte(btcoexist, 0x49d);
cnt_bt_cal_chk++;
if (u32tmp & BIT0) {
BTC_PRINT(BTC_MSG_INTERFACE, INTF_INIT,
"[BTCoex], ########### BT "
"calibration(cnt=%d) ###########\n",
cnt_bt_cal_chk);
mdelay(50);
} else {
BTC_PRINT(BTC_MSG_INTERFACE, INTF_INIT,
"[BTCoex], ********** BT NOT "
"calibration (cnt=%d)**********\n",
cnt_bt_cal_chk);
break;
}
}
/* 0x790[5:0]=0x5 */
u8tmp = btcoexist->btc_read_1byte(btcoexist, 0x790);
u8tmp &= 0xc0;
u8tmp |= 0x5;
btcoexist->btc_write_1byte(btcoexist, 0x790, u8tmp);
/* Enable counter statistics */
/*0x76e[3] =1, WLAN_Act control by PTA */
btcoexist->btc_write_1byte(btcoexist, 0x76e, 0xc);
btcoexist->btc_write_1byte(btcoexist, 0x778, 0x1);
btcoexist->btc_write_1byte_bitmask(btcoexist, 0x40, 0x20, 0x1);
/*Antenna config */
halbtc8723b1ant_SetAntPath(btcoexist, BTC_ANT_PATH_PTA, true, false);
/* PTA parameter */
halbtc8723b1ant_coex_table_with_type(btcoexist, FORCE_EXEC, 0);
}
void halbtc8723b1ant_wifi_off_hw_cfg(struct btc_coexist *btcoexist)
{
/* set wlan_act to low */
btcoexist->btc_write_1byte(btcoexist, 0x76e, 0);
}
/**************************************************************
* work around function start with wa_halbtc8723b1ant_
**************************************************************/
/**************************************************************
* extern function start with EXhalbtc8723b1ant_
**************************************************************/
void ex_halbtc8723b1ant_init_hwconfig(struct btc_coexist *btcoexist)
{
halbtc8723b1ant_init_hw_config(btcoexist, true);
}
void ex_halbtc8723b1ant_init_coex_dm(struct btc_coexist *btcoexist)
{
BTC_PRINT(BTC_MSG_INTERFACE, INTF_INIT,
"[BTCoex], Coex Mechanism Init!!\n");
btcoexist->stop_coex_dm = false;
halbtc8723b1ant_init_coex_dm(btcoexist);
halbtc8723b1ant_query_bt_info(btcoexist);
}
void ex_halbtc8723b1ant_display_coex_info(struct btc_coexist *btcoexist)
{
struct btc_board_info *board_info = &btcoexist->board_info;
struct btc_stack_info *stack_info = &btcoexist->stack_info;
struct btc_bt_link_info *bt_link_info = &btcoexist->bt_link_info;
u8 *cli_buf = btcoexist->cli_buf;
u8 u8tmp[4], i, bt_info_ext, psTdmaCase=0;
u16 u16tmp[4];
u32 u32tmp[4];
bool roam = false, scan = false;
bool link = false, wifi_under_5g = false;
bool bt_hs_on = false, wifi_busy = false;
s32 wifi_rssi =0, bt_hs_rssi = 0;
u32 wifi_bw, wifi_traffic_dir, fa_ofdm, fa_cck;
u8 wifi_dot11_chnl, wifi_hs_chnl;
u32 fw_ver = 0, bt_patch_ver = 0;
CL_SPRINTF(cli_buf, BT_TMP_BUF_SIZE,
"\r\n ============[BT Coexist info]============");
CL_PRINTF(cli_buf);
if (btcoexist->manual_control) {
CL_SPRINTF(cli_buf, BT_TMP_BUF_SIZE,
"\r\n ============[Under Manual Control]==========");
CL_PRINTF(cli_buf);
CL_SPRINTF(cli_buf, BT_TMP_BUF_SIZE,
"\r\n ==========================================");
CL_PRINTF(cli_buf);
}
if (btcoexist->stop_coex_dm) {
CL_SPRINTF(cli_buf, BT_TMP_BUF_SIZE,
"\r\n ============[Coex is STOPPED]============");
CL_PRINTF(cli_buf);
CL_SPRINTF(cli_buf, BT_TMP_BUF_SIZE,
"\r\n ==========================================");
CL_PRINTF(cli_buf);
}
if (!board_info->bt_exist) {
CL_SPRINTF(cli_buf, BT_TMP_BUF_SIZE, "\r\n BT not exists !!!");
CL_PRINTF(cli_buf);
return;
}
CL_SPRINTF(cli_buf, BT_TMP_BUF_SIZE, "\r\n %-35s = %d/ %d/ %d",
"Ant PG Num/ Ant Mech/ Ant Pos:", \
board_info->pg_ant_num, board_info->btdm_ant_num,
board_info->btdm_ant_pos);
CL_PRINTF(cli_buf);
CL_SPRINTF(cli_buf, BT_TMP_BUF_SIZE, "\r\n %-35s = %s / %d",
"BT stack/ hci ext ver", \
((stack_info->profile_notified)? "Yes":"No"),
stack_info->hci_version);
CL_PRINTF(cli_buf);
btcoexist->btc_get(btcoexist, BTC_GET_U4_BT_PATCH_VER, &bt_patch_ver);
btcoexist->btc_get(btcoexist, BTC_GET_U4_WIFI_FW_VER, &fw_ver);
CL_SPRINTF(cli_buf, BT_TMP_BUF_SIZE,
"\r\n %-35s = %d_%x/ 0x%x/ 0x%x(%d)",
"CoexVer/ FwVer/ PatchVer", \
glcoex_ver_date_8723b_1ant, glcoex_ver_8723b_1ant,
fw_ver, bt_patch_ver, bt_patch_ver);
CL_PRINTF(cli_buf);
btcoexist->btc_get(btcoexist, BTC_GET_BL_HS_OPERATION, &bt_hs_on);
btcoexist->btc_get(btcoexist, BTC_GET_U1_WIFI_DOT11_CHNL,
&wifi_dot11_chnl);
btcoexist->btc_get(btcoexist, BTC_GET_U1_WIFI_HS_CHNL, &wifi_hs_chnl);
CL_SPRINTF(cli_buf, BT_TMP_BUF_SIZE, "\r\n %-35s = %d / %d(%d)",
"Dot11 channel / HsChnl(HsMode)", \
wifi_dot11_chnl, wifi_hs_chnl, bt_hs_on);
CL_PRINTF(cli_buf);
CL_SPRINTF(cli_buf, BT_TMP_BUF_SIZE, "\r\n %-35s = %02x %02x %02x ",
"H2C Wifi inform bt chnl Info", \
coex_dm->wifi_chnl_info[0], coex_dm->wifi_chnl_info[1],
coex_dm->wifi_chnl_info[2]);
CL_PRINTF(cli_buf);
btcoexist->btc_get(btcoexist, BTC_GET_S4_WIFI_RSSI, &wifi_rssi);
btcoexist->btc_get(btcoexist, BTC_GET_S4_HS_RSSI, &bt_hs_rssi);
CL_SPRINTF(cli_buf, BT_TMP_BUF_SIZE, "\r\n %-35s = %d/ %d",
"Wifi rssi/ HS rssi", wifi_rssi, bt_hs_rssi);
CL_PRINTF(cli_buf);
btcoexist->btc_get(btcoexist, BTC_GET_BL_WIFI_SCAN, &scan);
btcoexist->btc_get(btcoexist, BTC_GET_BL_WIFI_LINK, &link);
btcoexist->btc_get(btcoexist, BTC_GET_BL_WIFI_ROAM, &roam);
CL_SPRINTF(cli_buf, BT_TMP_BUF_SIZE, "\r\n %-35s = %d/ %d/ %d ",
"Wifi link/ roam/ scan", link, roam, scan);
CL_PRINTF(cli_buf);
btcoexist->btc_get(btcoexist,BTC_GET_BL_WIFI_UNDER_5G,
&wifi_under_5g);
btcoexist->btc_get(btcoexist, BTC_GET_U4_WIFI_BW, &wifi_bw);
btcoexist->btc_get(btcoexist, BTC_GET_BL_WIFI_BUSY, &wifi_busy);
btcoexist->btc_get(btcoexist, BTC_GET_U4_WIFI_TRAFFIC_DIRECTION,
&wifi_traffic_dir);
CL_SPRINTF(cli_buf, BT_TMP_BUF_SIZE, "\r\n %-35s = %s / %s/ %s ",
"Wifi status", (wifi_under_5g? "5G":"2.4G"),
((BTC_WIFI_BW_LEGACY==wifi_bw)? "Legacy":
(((BTC_WIFI_BW_HT40==wifi_bw)? "HT40":"HT20"))),
((!wifi_busy)? "idle":
((BTC_WIFI_TRAFFIC_TX==wifi_traffic_dir)?
"uplink":"downlink")));
CL_PRINTF(cli_buf);
CL_SPRINTF(cli_buf, BT_TMP_BUF_SIZE, "\r\n %-35s = [%s/ %d/ %d] ",
"BT [status/ rssi/ retryCnt]",
((btcoexist->bt_info.bt_disabled)? ("disabled"):
((coex_sta->c2h_bt_inquiry_page)?("inquiry/page scan"):
((BT_8723B_1ANT_BT_STATUS_NON_CONNECTED_IDLE == coex_dm->bt_status)?
"non-connected idle":
((BT_8723B_1ANT_BT_STATUS_CONNECTED_IDLE == coex_dm->bt_status)?
"connected-idle":"busy")))),
coex_sta->bt_rssi, coex_sta->bt_retry_cnt);
CL_PRINTF(cli_buf);
CL_SPRINTF(cli_buf, BT_TMP_BUF_SIZE, "\r\n %-35s = %d / %d / %d / %d",
"SCO/HID/PAN/A2DP", bt_link_info->sco_exist,
bt_link_info->hid_exist, bt_link_info->pan_exist,
bt_link_info->a2dp_exist);
CL_PRINTF(cli_buf);
btcoexist->btc_disp_dbg_msg(btcoexist, BTC_DBG_DISP_BT_LINK_INFO);
bt_info_ext = coex_sta->bt_info_ext;
CL_SPRINTF(cli_buf, BT_TMP_BUF_SIZE, "\r\n %-35s = %s",
"BT Info A2DP rate",
(bt_info_ext & BIT0) ? "Basic rate" : "EDR rate");
CL_PRINTF(cli_buf);
for (i = 0; i < BT_INFO_SRC_8723B_1ANT_MAX; i++) {
if (coex_sta->bt_info_c2h_cnt[i]) {
CL_SPRINTF(cli_buf, BT_TMP_BUF_SIZE,
"\r\n %-35s = %02x %02x %02x "
"%02x %02x %02x %02x(%d)",
GLBtInfoSrc8723b1Ant[i],
coex_sta->bt_info_c2h[i][0],
coex_sta->bt_info_c2h[i][1],
coex_sta->bt_info_c2h[i][2],
coex_sta->bt_info_c2h[i][3],
coex_sta->bt_info_c2h[i][4],
coex_sta->bt_info_c2h[i][5],
coex_sta->bt_info_c2h[i][6],
coex_sta->bt_info_c2h_cnt[i]);
CL_PRINTF(cli_buf);
}
}
CL_SPRINTF(cli_buf, BT_TMP_BUF_SIZE,
"\r\n %-35s = %s/%s, (0x%x/0x%x)",
"PS state, IPS/LPS, (lps/rpwm)", \
((coex_sta->under_ips? "IPS ON":"IPS OFF")),
((coex_sta->under_lps? "LPS ON":"LPS OFF")),
btcoexist->bt_info.lps_1ant,
btcoexist->bt_info.rpwm_1ant);
CL_PRINTF(cli_buf);
btcoexist->btc_disp_dbg_msg(btcoexist, BTC_DBG_DISP_FW_PWR_MODE_CMD);
if (!btcoexist->manual_control) {
/* Sw mechanism */
CL_SPRINTF(cli_buf, BT_TMP_BUF_SIZE, "\r\n %-35s",
"============[Sw mechanism]============");
CL_PRINTF(cli_buf);
CL_SPRINTF(cli_buf, BT_TMP_BUF_SIZE, "\r\n %-35s = %d/ %d/ %d ",
"SM1[ShRf/ LpRA/ LimDig]", \
coex_dm->cur_rf_rx_lpf_shrink,
coex_dm->cur_low_penalty_ra,
btcoexist->bt_info.limited_dig);
CL_PRINTF(cli_buf);
CL_SPRINTF(cli_buf, BT_TMP_BUF_SIZE,
"\r\n %-35s = %d/ %d/ %d(0x%x) ",
"SM2[AgcT/ AdcB/ SwDacSwing(lvl)]", \
coex_dm->cur_agc_table_en,
coex_dm->cur_adc_backoff,
coex_dm->cur_dac_swing_on,
coex_dm->cur_dac_swing_lvl);
CL_PRINTF(cli_buf);
CL_PRINTF(cli_buf);
CL_SPRINTF(cli_buf, BT_TMP_BUF_SIZE, "\r\n %-35s = 0x%x ",
"Rate Mask", btcoexist->bt_info.ra_mask);
CL_PRINTF(cli_buf);
/* Fw mechanism */
CL_SPRINTF(cli_buf, BT_TMP_BUF_SIZE, "\r\n %-35s",
"============[Fw mechanism]============");
CL_PRINTF(cli_buf);
psTdmaCase = coex_dm->cur_ps_tdma;
CL_SPRINTF(cli_buf, BT_TMP_BUF_SIZE,
"\r\n %-35s = %02x %02x %02x %02x %02x "
"case-%d (auto:%d)",
"PS TDMA", coex_dm->ps_tdma_para[0],
coex_dm->ps_tdma_para[1], coex_dm->ps_tdma_para[2],
coex_dm->ps_tdma_para[3], coex_dm->ps_tdma_para[4],
psTdmaCase, coex_dm->auto_tdma_adjust);
CL_PRINTF(cli_buf);
CL_SPRINTF(cli_buf, BT_TMP_BUF_SIZE, "\r\n %-35s = 0x%x ",
"Latest error condition(should be 0)", \
coex_dm->error_condition);
CL_PRINTF(cli_buf);
CL_SPRINTF(cli_buf, BT_TMP_BUF_SIZE, "\r\n %-35s = %d/ %d ",
"DecBtPwr/ IgnWlanAct", coex_dm->cur_dec_bt_pwr,
coex_dm->cur_ignore_wlan_act);
CL_PRINTF(cli_buf);
}
/* Hw setting */
CL_SPRINTF(cli_buf, BT_TMP_BUF_SIZE, "\r\n %-35s",
"============[Hw setting]============");
CL_PRINTF(cli_buf);
CL_SPRINTF(cli_buf, BT_TMP_BUF_SIZE, "\r\n %-35s = 0x%x",
"RF-A, 0x1e initVal", coex_dm->bt_rf0x1e_backup);
CL_PRINTF(cli_buf);
CL_SPRINTF(cli_buf, BT_TMP_BUF_SIZE, "\r\n %-35s = 0x%x/0x%x/0x%x/0x%x",
"backup ARFR1/ARFR2/RL/AMaxTime", coex_dm->backup_arfr_cnt1,
coex_dm->backup_arfr_cnt2, coex_dm->backup_retry_limit,
coex_dm->backup_ampdu_max_time);
CL_PRINTF(cli_buf);
u32tmp[0] = btcoexist->btc_read_4byte(btcoexist, 0x430);
u32tmp[1] = btcoexist->btc_read_4byte(btcoexist, 0x434);
u16tmp[0] = btcoexist->btc_read_2byte(btcoexist, 0x42a);
u8tmp[0] = btcoexist->btc_read_1byte(btcoexist, 0x456);
CL_SPRINTF(cli_buf, BT_TMP_BUF_SIZE, "\r\n %-35s = 0x%x/0x%x/0x%x/0x%x",
"0x430/0x434/0x42a/0x456",
u32tmp[0], u32tmp[1], u16tmp[0], u8tmp[0]);
CL_PRINTF(cli_buf);
u8tmp[0] = btcoexist->btc_read_1byte(btcoexist, 0x778);
u32tmp[0] = btcoexist->btc_read_4byte(btcoexist, 0x6cc);
u32tmp[1] = btcoexist->btc_read_4byte(btcoexist, 0x880);
CL_SPRINTF(cli_buf, BT_TMP_BUF_SIZE, "\r\n %-35s = 0x%x/ 0x%x/ 0x%x",
"0x778/0x6cc/0x880[29:25]", u8tmp[0], u32tmp[0],
(u32tmp[1] & 0x3e000000) >> 25);
CL_PRINTF(cli_buf);
u32tmp[0] = btcoexist->btc_read_4byte(btcoexist, 0x948);
u8tmp[0] = btcoexist->btc_read_1byte(btcoexist, 0x67);
u8tmp[1] = btcoexist->btc_read_1byte(btcoexist, 0x765);
CL_SPRINTF(cli_buf, BT_TMP_BUF_SIZE, "\r\n %-35s = 0x%x/ 0x%x/ 0x%x",
"0x948/ 0x67[5] / 0x765",
u32tmp[0], ((u8tmp[0] & 0x20)>> 5), u8tmp[1]);
CL_PRINTF(cli_buf);
u32tmp[0] = btcoexist->btc_read_4byte(btcoexist, 0x92c);
u32tmp[1] = btcoexist->btc_read_4byte(btcoexist, 0x930);
u32tmp[2] = btcoexist->btc_read_4byte(btcoexist, 0x944);
CL_SPRINTF(cli_buf, BT_TMP_BUF_SIZE, "\r\n %-35s = 0x%x/ 0x%x/ 0x%x",
"0x92c[1:0]/ 0x930[7:0]/0x944[1:0]",
u32tmp[0] & 0x3, u32tmp[1] & 0xff, u32tmp[2] & 0x3);
CL_PRINTF(cli_buf);
u8tmp[0] = btcoexist->btc_read_1byte(btcoexist, 0x39);
u8tmp[1] = btcoexist->btc_read_1byte(btcoexist, 0x40);
u32tmp[0] = btcoexist->btc_read_4byte(btcoexist, 0x4c);
u8tmp[2] = btcoexist->btc_read_1byte(btcoexist, 0x64);
CL_SPRINTF(cli_buf, BT_TMP_BUF_SIZE,
"\r\n %-35s = 0x%x/ 0x%x/ 0x%x/ 0x%x",
"0x38[11]/0x40/0x4c[24:23]/0x64[0]",
((u8tmp[0] & 0x8)>>3), u8tmp[1],
((u32tmp[0] & 0x01800000) >> 23), u8tmp[2] & 0x1);
CL_PRINTF(cli_buf);
u32tmp[0] = btcoexist->btc_read_4byte(btcoexist, 0x550);
u8tmp[0] = btcoexist->btc_read_1byte(btcoexist, 0x522);
CL_SPRINTF(cli_buf, BT_TMP_BUF_SIZE, "\r\n %-35s = 0x%x/ 0x%x",
"0x550(bcn ctrl)/0x522", u32tmp[0], u8tmp[0]);
CL_PRINTF(cli_buf);
u32tmp[0] = btcoexist->btc_read_4byte(btcoexist, 0xc50);
u8tmp[0] = btcoexist->btc_read_1byte(btcoexist, 0x49c);
CL_SPRINTF(cli_buf, BT_TMP_BUF_SIZE, "\r\n %-35s = 0x%x/ 0x%x",
"0xc50(dig)/0x49c(null-drop)", u32tmp[0] & 0xff, u8tmp[0]);
CL_PRINTF(cli_buf);
u32tmp[0] = btcoexist->btc_read_4byte(btcoexist, 0xda0);
u32tmp[1] = btcoexist->btc_read_4byte(btcoexist, 0xda4);
u32tmp[2] = btcoexist->btc_read_4byte(btcoexist, 0xda8);
u32tmp[3] = btcoexist->btc_read_4byte(btcoexist, 0xcf0);
u8tmp[0] = btcoexist->btc_read_1byte(btcoexist, 0xa5b);
u8tmp[1] = btcoexist->btc_read_1byte(btcoexist, 0xa5c);
fa_ofdm = ((u32tmp[0] & 0xffff0000) >> 16) +
((u32tmp[1] & 0xffff0000) >> 16) +
(u32tmp[1] & 0xffff) +
(u32tmp[2] & 0xffff) + \
((u32tmp[3] & 0xffff0000) >> 16) +
(u32tmp[3] & 0xffff) ;
fa_cck = (u8tmp[0] << 8) + u8tmp[1];
CL_SPRINTF(cli_buf, BT_TMP_BUF_SIZE, "\r\n %-35s = 0x%x/ 0x%x/ 0x%x",
"OFDM-CCA/OFDM-FA/CCK-FA",
u32tmp[0] & 0xffff, fa_ofdm, fa_cck);
CL_PRINTF(cli_buf);
u32tmp[0] = btcoexist->btc_read_4byte(btcoexist, 0x6c0);
u32tmp[1] = btcoexist->btc_read_4byte(btcoexist, 0x6c4);
u32tmp[2] = btcoexist->btc_read_4byte(btcoexist, 0x6c8);
CL_SPRINTF(cli_buf, BT_TMP_BUF_SIZE, "\r\n %-35s = 0x%x/ 0x%x/ 0x%x",
"0x6c0/0x6c4/0x6c8(coexTable)",
u32tmp[0], u32tmp[1], u32tmp[2]);
CL_PRINTF(cli_buf);
CL_SPRINTF(cli_buf, BT_TMP_BUF_SIZE, "\r\n %-35s = %d/ %d",
"0x770(high-pri rx/tx)", coex_sta->high_priority_rx,
coex_sta->high_priority_tx);
CL_PRINTF(cli_buf);
CL_SPRINTF(cli_buf, BT_TMP_BUF_SIZE, "\r\n %-35s = %d/ %d",
"0x774(low-pri rx/tx)", coex_sta->low_priority_rx,
coex_sta->low_priority_tx);
CL_PRINTF(cli_buf);
#if(BT_AUTO_REPORT_ONLY_8723B_1ANT == 1)
halbtc8723b1ant_monitor_bt_ctr(btcoexist);
#endif
btcoexist->btc_disp_dbg_msg(btcoexist, BTC_DBG_DISP_COEX_STATISTICS);
}
void ex_halbtc8723b1ant_ips_notify(struct btc_coexist *btcoexist, u8 type)
{
if (btcoexist->manual_control || btcoexist->stop_coex_dm)
return;
if (BTC_IPS_ENTER == type) {
BTC_PRINT(BTC_MSG_INTERFACE, INTF_NOTIFY,
"[BTCoex], IPS ENTER notify\n");
coex_sta->under_ips = true;
halbtc8723b1ant_SetAntPath(btcoexist, BTC_ANT_PATH_BT,
false, true);
/* set PTA control */
halbtc8723b1ant_ps_tdma(btcoexist, NORMAL_EXEC, false, 0);
halbtc8723b1ant_coex_table_with_type(btcoexist,
NORMAL_EXEC, 0);
} else if (BTC_IPS_LEAVE == type) {
BTC_PRINT(BTC_MSG_INTERFACE, INTF_NOTIFY,
"[BTCoex], IPS LEAVE notify\n");
coex_sta->under_ips = false;
halbtc8723b1ant_run_coexist_mechanism(btcoexist);
}
}
void ex_halbtc8723b1ant_lps_notify(struct btc_coexist *btcoexist, u8 type)
{
if (btcoexist->manual_control || btcoexist->stop_coex_dm)
return;
if (BTC_LPS_ENABLE == type) {
BTC_PRINT(BTC_MSG_INTERFACE, INTF_NOTIFY,
"[BTCoex], LPS ENABLE notify\n");
coex_sta->under_lps = true;
} else if (BTC_LPS_DISABLE == type) {
BTC_PRINT(BTC_MSG_INTERFACE, INTF_NOTIFY,
"[BTCoex], LPS DISABLE notify\n");
coex_sta->under_lps = false;
}
}
void ex_halbtc8723b1ant_scan_notify(struct btc_coexist *btcoexist, u8 type)
{
bool wifi_connected = false, bt_hs_on = false;
if (btcoexist->manual_control || btcoexist->stop_coex_dm ||
btcoexist->bt_info.bt_disabled)
return;
btcoexist->btc_get(btcoexist, BTC_GET_BL_HS_OPERATION, &bt_hs_on);
btcoexist->btc_get(btcoexist, BTC_GET_BL_WIFI_CONNECTED,
&wifi_connected);
halbtc8723b1ant_query_bt_info(btcoexist);
if (coex_sta->c2h_bt_inquiry_page) {
halbtc8723b1ant_action_bt_inquiry(btcoexist);
return;
} else if (bt_hs_on) {
halbtc8723b1ant_action_hs(btcoexist);
return;
}
if (BTC_SCAN_START == type) {
BTC_PRINT(BTC_MSG_INTERFACE, INTF_NOTIFY,
"[BTCoex], SCAN START notify\n");
if (!wifi_connected) /* non-connected scan */
halbtc8723b1ant_action_wifi_not_connected_asso_auth_scan(btcoexist);
else /* wifi is connected */
halbtc8723b1ant_ActionWifiConnectedScan(btcoexist);
} else if (BTC_SCAN_FINISH == type) {
BTC_PRINT(BTC_MSG_INTERFACE, INTF_NOTIFY,
"[BTCoex], SCAN FINISH notify\n");
if (!wifi_connected) /* non-connected scan */
halbtc8723b1ant_action_wifi_not_connected(btcoexist);
else
halbtc8723b1ant_action_wifi_connected(btcoexist);
}
}
void ex_halbtc8723b1ant_connect_notify(struct btc_coexist *btcoexist, u8 type)
{
bool wifi_connected = false, bt_hs_on = false;
if (btcoexist->manual_control || btcoexist->stop_coex_dm ||
btcoexist->bt_info.bt_disabled)
return;
btcoexist->btc_get(btcoexist, BTC_GET_BL_HS_OPERATION, &bt_hs_on);
if (coex_sta->c2h_bt_inquiry_page) {
halbtc8723b1ant_action_bt_inquiry(btcoexist);
return;
} else if (bt_hs_on) {
halbtc8723b1ant_action_hs(btcoexist);
return;
}
if (BTC_ASSOCIATE_START == type) {
BTC_PRINT(BTC_MSG_INTERFACE, INTF_NOTIFY,
"[BTCoex], CONNECT START notify\n");
halbtc8723b1ant_action_wifi_not_connected_asso_auth_scan(btcoexist);
} else if (BTC_ASSOCIATE_FINISH == type) {
BTC_PRINT(BTC_MSG_INTERFACE, INTF_NOTIFY,
"[BTCoex], CONNECT FINISH notify\n");
btcoexist->btc_get(btcoexist, BTC_GET_BL_WIFI_CONNECTED,
&wifi_connected);
if (!wifi_connected) /* non-connected scan */
halbtc8723b1ant_action_wifi_not_connected(btcoexist);
else
halbtc8723b1ant_action_wifi_connected(btcoexist);
}
}
void ex_halbtc8723b1ant_media_status_notify(struct btc_coexist *btcoexist,
u8 type)
{
u8 h2c_parameter[3] ={0};
u32 wifi_bw;
u8 wifiCentralChnl;
if (btcoexist->manual_control || btcoexist->stop_coex_dm ||
btcoexist->bt_info.bt_disabled )
return;
if (BTC_MEDIA_CONNECT == type)
BTC_PRINT(BTC_MSG_INTERFACE, INTF_NOTIFY,
"[BTCoex], MEDIA connect notify\n");
else
BTC_PRINT(BTC_MSG_INTERFACE, INTF_NOTIFY,
"[BTCoex], MEDIA disconnect notify\n");
/* only 2.4G we need to inform bt the chnl mask */
btcoexist->btc_get(btcoexist, BTC_GET_U1_WIFI_CENTRAL_CHNL,
&wifiCentralChnl);
if ((BTC_MEDIA_CONNECT == type) &&
(wifiCentralChnl <= 14)) {
h2c_parameter[0] = 0x0;
h2c_parameter[1] = wifiCentralChnl;
btcoexist->btc_get(btcoexist, BTC_GET_U4_WIFI_BW, &wifi_bw);
if (BTC_WIFI_BW_HT40 == wifi_bw)
h2c_parameter[2] = 0x30;
else
h2c_parameter[2] = 0x20;
}
coex_dm->wifi_chnl_info[0] = h2c_parameter[0];
coex_dm->wifi_chnl_info[1] = h2c_parameter[1];
coex_dm->wifi_chnl_info[2] = h2c_parameter[2];
BTC_PRINT(BTC_MSG_ALGORITHM, ALGO_TRACE_FW_EXEC,
"[BTCoex], FW write 0x66=0x%x\n",
h2c_parameter[0] << 16 | h2c_parameter[1] << 8 |
h2c_parameter[2]);
btcoexist->btc_fill_h2c(btcoexist, 0x66, 3, h2c_parameter);
}
void ex_halbtc8723b1ant_special_packet_notify(struct btc_coexist *btcoexist,
u8 type)
{
bool bt_hs_on = false;
if (btcoexist->manual_control || btcoexist->stop_coex_dm ||
btcoexist->bt_info.bt_disabled)
return;
coex_sta->special_pkt_period_cnt = 0;
btcoexist->btc_get(btcoexist, BTC_GET_BL_HS_OPERATION, &bt_hs_on);
if (coex_sta->c2h_bt_inquiry_page) {
halbtc8723b1ant_action_bt_inquiry(btcoexist);
return;
} else if (bt_hs_on) {
halbtc8723b1ant_action_hs(btcoexist);
return;
}
if (BTC_PACKET_DHCP == type ||
BTC_PACKET_EAPOL == type) {
BTC_PRINT(BTC_MSG_INTERFACE, INTF_NOTIFY,
"[BTCoex], special Packet(%d) notify\n", type);
halbtc8723b1ant_action_wifi_connected_special_packet(btcoexist);
}
}
void ex_halbtc8723b1ant_bt_info_notify(struct btc_coexist *btcoexist,
u8 *tmp_buf, u8 length)
{
u8 bt_info = 0;
u8 i, rsp_source = 0;
bool wifi_connected = false;
bool bt_busy = false;
coex_sta->c2h_bt_info_req_sent = false;
rsp_source = tmp_buf[0] & 0xf;
if (rsp_source >= BT_INFO_SRC_8723B_1ANT_MAX)
rsp_source = BT_INFO_SRC_8723B_1ANT_WIFI_FW;
coex_sta->bt_info_c2h_cnt[rsp_source]++;
BTC_PRINT(BTC_MSG_INTERFACE, INTF_NOTIFY,
"[BTCoex], Bt info[%d], length=%d, hex data=[",
rsp_source, length);
for (i=0; i<length; i++) {
coex_sta->bt_info_c2h[rsp_source][i] = tmp_buf[i];
if (i == 1)
bt_info = tmp_buf[i];
if (i == length - 1)
BTC_PRINT(BTC_MSG_INTERFACE, INTF_NOTIFY,
"0x%02x]\n", tmp_buf[i]);
else
BTC_PRINT(BTC_MSG_INTERFACE, INTF_NOTIFY,
"0x%02x, ", tmp_buf[i]);
}
if (BT_INFO_SRC_8723B_1ANT_WIFI_FW != rsp_source) {
coex_sta->bt_retry_cnt = /* [3:0] */
coex_sta->bt_info_c2h[rsp_source][2] & 0xf;
coex_sta->bt_rssi =
coex_sta->bt_info_c2h[rsp_source][3] * 2 + 10;
coex_sta->bt_info_ext =
coex_sta->bt_info_c2h[rsp_source][4];
/* Here we need to resend some wifi info to BT
* because bt is reset and loss of the info.*/
if(coex_sta->bt_info_ext & BIT1)
{
BTC_PRINT(BTC_MSG_ALGORITHM, ALGO_TRACE,
"[BTCoex], BT ext info bit1 check, "
"send wifi BW&Chnl to BT!!\n");
btcoexist->btc_get(btcoexist, BTC_GET_BL_WIFI_CONNECTED,
&wifi_connected);
if(wifi_connected)
ex_halbtc8723b1ant_media_status_notify(btcoexist,
BTC_MEDIA_CONNECT);
else
ex_halbtc8723b1ant_media_status_notify(btcoexist,
BTC_MEDIA_DISCONNECT);
}
if (coex_sta->bt_info_ext & BIT3) {
if (!btcoexist->manual_control &&
!btcoexist->stop_coex_dm) {
BTC_PRINT(BTC_MSG_ALGORITHM, ALGO_TRACE,
"[BTCoex], BT ext info bit3 check, "
"set BT NOT ignore Wlan active!!\n");
halbtc8723b1ant_ignore_wlan_act(btcoexist,
FORCE_EXEC,
false);
}
} else {
/* BT already NOT ignore Wlan active, do nothing here.*/
}
#if(BT_AUTO_REPORT_ONLY_8723B_1ANT == 0)
if (coex_sta->bt_info_ext & BIT4) {
/* BT auto report already enabled, do nothing */
} else {
halbtc8723b1ant_bt_auto_report(btcoexist, FORCE_EXEC,
true);
}
#endif
}
/* check BIT2 first ==> check if bt is under inquiry or page scan */
if (bt_info & BT_INFO_8723B_1ANT_B_INQ_PAGE)
coex_sta->c2h_bt_inquiry_page = true;
else
coex_sta->c2h_bt_inquiry_page = false;
/* set link exist status */
if (!(bt_info & BT_INFO_8723B_1ANT_B_CONNECTION)) {
coex_sta->bt_link_exist = false;
coex_sta->pan_exist = false;
coex_sta->a2dp_exist = false;
coex_sta->hid_exist = false;
coex_sta->sco_exist = false;
} else { /* connection exists */
coex_sta->bt_link_exist = true;
if (bt_info & BT_INFO_8723B_1ANT_B_FTP)
coex_sta->pan_exist = true;
else
coex_sta->pan_exist = false;
if (bt_info & BT_INFO_8723B_1ANT_B_A2DP)
coex_sta->a2dp_exist = true;
else
coex_sta->a2dp_exist = false;
if (bt_info & BT_INFO_8723B_1ANT_B_HID)
coex_sta->hid_exist = true;
else
coex_sta->hid_exist = false;
if (bt_info & BT_INFO_8723B_1ANT_B_SCO_ESCO)
coex_sta->sco_exist = true;
else
coex_sta->sco_exist = false;
}
halbtc8723b1ant_update_bt_link_info(btcoexist);
if (!(bt_info&BT_INFO_8723B_1ANT_B_CONNECTION)) {
coex_dm->bt_status = BT_8723B_1ANT_BT_STATUS_NON_CONNECTED_IDLE;
BTC_PRINT(BTC_MSG_ALGORITHM, ALGO_TRACE,
"[BTCoex], BtInfoNotify(), "
"BT Non-Connected idle!!!\n");
/* connection exists but no busy */
} else if (bt_info == BT_INFO_8723B_1ANT_B_CONNECTION) {
coex_dm->bt_status = BT_8723B_1ANT_BT_STATUS_CONNECTED_IDLE;
BTC_PRINT(BTC_MSG_ALGORITHM, ALGO_TRACE,
"[BTCoex], BtInfoNotify(), BT Connected-idle!!!\n");
} else if ((bt_info & BT_INFO_8723B_1ANT_B_SCO_ESCO) ||
(bt_info & BT_INFO_8723B_1ANT_B_SCO_BUSY)) {
coex_dm->bt_status = BT_8723B_1ANT_BT_STATUS_SCO_BUSY;
BTC_PRINT(BTC_MSG_ALGORITHM, ALGO_TRACE,
"[BTCoex], BtInfoNotify(), "
"BT SCO busy!!!\n");
} else if (bt_info & BT_INFO_8723B_1ANT_B_ACL_BUSY) {
if (BT_8723B_1ANT_BT_STATUS_ACL_BUSY != coex_dm->bt_status)
coex_dm->auto_tdma_adjust = false;
coex_dm->bt_status = BT_8723B_1ANT_BT_STATUS_ACL_BUSY;
BTC_PRINT(BTC_MSG_ALGORITHM, ALGO_TRACE,
"[BTCoex], BtInfoNotify(), BT ACL busy!!!\n");
} else {
coex_dm->bt_status =
BT_8723B_1ANT_BT_STATUS_MAX;
BTC_PRINT(BTC_MSG_ALGORITHM, ALGO_TRACE,
"[BTCoex], BtInfoNotify(), BT Non-Defined state!!\n");
}
if ((BT_8723B_1ANT_BT_STATUS_ACL_BUSY == coex_dm->bt_status) ||
(BT_8723B_1ANT_BT_STATUS_SCO_BUSY == coex_dm->bt_status) ||
(BT_8723B_1ANT_BT_STATUS_ACL_SCO_BUSY == coex_dm->bt_status))
bt_busy = true;
else
bt_busy = false;
btcoexist->btc_set(btcoexist, BTC_SET_BL_BT_TRAFFIC_BUSY, &bt_busy);
halbtc8723b1ant_run_coexist_mechanism(btcoexist);
}
void ex_halbtc8723b1ant_halt_notify(struct btc_coexist *btcoexist)
{
BTC_PRINT(BTC_MSG_INTERFACE, INTF_NOTIFY, "[BTCoex], Halt notify\n");
btcoexist->stop_coex_dm = true;
halbtc8723b1ant_SetAntPath(btcoexist, BTC_ANT_PATH_BT, false, true);
halbtc8723b1ant_wifi_off_hw_cfg(btcoexist);
halbtc8723b1ant_ignore_wlan_act(btcoexist, FORCE_EXEC, true);
halbtc8723b1ant_power_save_state(btcoexist, BTC_PS_WIFI_NATIVE,
0x0, 0x0);
halbtc8723b1ant_ps_tdma(btcoexist, FORCE_EXEC, false, 0);
ex_halbtc8723b1ant_media_status_notify(btcoexist, BTC_MEDIA_DISCONNECT);
}
void ex_halbtc8723b1ant_pnp_notify(struct btc_coexist *btcoexist, u8 pnp_state)
{
BTC_PRINT(BTC_MSG_INTERFACE, INTF_NOTIFY, "[BTCoex], Pnp notify\n");
if (BTC_WIFI_PNP_SLEEP == pnp_state) {
BTC_PRINT(BTC_MSG_INTERFACE, INTF_NOTIFY,
"[BTCoex], Pnp notify to SLEEP\n");
btcoexist->stop_coex_dm = true;
halbtc8723b1ant_ignore_wlan_act(btcoexist, FORCE_EXEC, true);
halbtc8723b1ant_power_save_state(btcoexist, BTC_PS_WIFI_NATIVE,
0x0, 0x0);
halbtc8723b1ant_ps_tdma(btcoexist, NORMAL_EXEC, false, 9);
} else if (BTC_WIFI_PNP_WAKE_UP == pnp_state) {
BTC_PRINT(BTC_MSG_INTERFACE, INTF_NOTIFY,
"[BTCoex], Pnp notify to WAKE UP\n");
btcoexist->stop_coex_dm = false;
halbtc8723b1ant_init_hw_config(btcoexist, false);
halbtc8723b1ant_init_coex_dm(btcoexist);
halbtc8723b1ant_query_bt_info(btcoexist);
}
}
void ex_halbtc8723b1ant_periodical(struct btc_coexist *btcoexist)
{
struct btc_board_info *board_info = &btcoexist->board_info;
struct btc_stack_info *stack_info = &btcoexist->stack_info;
static u8 dis_ver_info_cnt = 0;
u32 fw_ver = 0, bt_patch_ver = 0;
BTC_PRINT(BTC_MSG_ALGORITHM, ALGO_TRACE,
"[BTCoex], =========================="
"Periodical===========================\n");
if (dis_ver_info_cnt <= 5) {
dis_ver_info_cnt += 1;
BTC_PRINT(BTC_MSG_INTERFACE, INTF_INIT,
"[BTCoex], *************************"
"***************************************\n");
BTC_PRINT(BTC_MSG_INTERFACE, INTF_INIT,
"[BTCoex], Ant PG Num/ Ant Mech/ "
"Ant Pos = %d/ %d/ %d\n", \
board_info->pg_ant_num, board_info->btdm_ant_num,
board_info->btdm_ant_pos);
BTC_PRINT(BTC_MSG_INTERFACE, INTF_INIT,
"[BTCoex], BT stack/ hci ext ver = %s / %d\n", \
((stack_info->profile_notified)? "Yes":"No"),
stack_info->hci_version);
btcoexist->btc_get(btcoexist, BTC_GET_U4_BT_PATCH_VER,
&bt_patch_ver);
btcoexist->btc_get(btcoexist, BTC_GET_U4_WIFI_FW_VER, &fw_ver);
BTC_PRINT(BTC_MSG_INTERFACE, INTF_INIT,
"[BTCoex], CoexVer/ FwVer/ PatchVer "
"= %d_%x/ 0x%x/ 0x%x(%d)\n", \
glcoex_ver_date_8723b_1ant,
glcoex_ver_8723b_1ant, fw_ver,
bt_patch_ver, bt_patch_ver);
BTC_PRINT(BTC_MSG_INTERFACE, INTF_INIT,
"[BTCoex], *****************************"
"***********************************\n");
}
#if(BT_AUTO_REPORT_ONLY_8723B_1ANT == 0)
halbtc8723b1ant_query_bt_info(btcoexist);
halbtc8723b1ant_monitor_bt_ctr(btcoexist);
halbtc8723b1ant_monitor_bt_enable_disable(btcoexist);
#else
if (halbtc8723b1ant_is_wifi_status_changed(btcoexist) ||
coex_dm->auto_tdma_adjust) {
if (coex_sta->special_pkt_period_cnt > 2)
halbtc8723b1ant_run_coexist_mechanism(btcoexist);
}
coex_sta->special_pkt_period_cnt++;
#endif
}
#endif
|
957653.c | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* 2-0____swap_bits.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: evgenkarlson <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/02/14 12:33:14 by evgenkarlson #+# #+# */
/* Updated: 2021/02/16 23:46:11 by evgenkarlson ### ########.fr */
/* */
/* ************************************************************************** */
/* ************************************************************************** */
/* ************************************************************************** **
Assignment name : swap_bits
Expected files : swap_bits.c
Allowed functions:
--------------------------------------------------------------------------------
Напишите функцию, которая берет байт, меняет местами содержимое своих половинок байта (как в примере) и возвращает результат.
Ваша функция должна быть объявлена следующим образом:
unsigned char swap_bits(unsigned char octet);
Пример:
1 byte
_____________
0100 | 0001
\ /
/ \
0001 | 0100
/* ************************************************************************** */
/* ************************************************************************** */
unsigned char swap_bits(unsigned char c)
{
return ((c >> 4) | (c << 4));
}
|
970115.c | /*
* File primary.c: 2.4 (84/11/27,16:26:07)
*/
#include <stdio.h>
#include "defs.h"
#include "data.h"
primary (LVALUE *lval) {
char sname[NAMESIZE];
int num[1], k, symbol_table_idx, offset, reg, otag;
SYMBOL *symbol;
lval->ptr_type = 0; /* clear pointer/array type */
lval->tagsym = 0;
if (match ("(")) {
k = hier1 (lval);
needbrack (")");
return (k);
}
if (amatch("sizeof", 6)) {
needbrack("(");
gen_immediate();
if (amatch("int", 3) || amatch("unsigned int", 12)){
blanks();
/* pointers and ints are both INTSIZE */
match("*");
output_number(INTSIZE);
}
else if (amatch("char", 4) || amatch("unsigned char", 13)){
/* if sizeof a char pointer, output INTSIZE */
if(match("*"))
output_number(INTSIZE);
else
output_number(1);
}
else if (amatch("struct", 6)){
if(symname(sname) == 0){
illname();
}
if((otag = find_tag(sname)) == -1){
error("struct tag undefined");
}
/* Write out struct size, or INTSIZE if struct pointer */
if(match("*"))
output_number(INTSIZE);
else
output_number(tag_table[otag].size);
} else if (symname(sname)) {
if (((symbol_table_idx = find_locale(sname)) > -1) ||
((symbol_table_idx = find_global(sname)) > -1)) {
symbol = &symbol_table[symbol_table_idx];
if (symbol->storage == LSTATIC)
error("sizeof local static");
offset = symbol->offset;
if ((symbol->type & CINT) ||
(symbol->identity == POINTER))
offset *= INTSIZE;
else if (symbol->type == STRUCT)
offset *= tag_table[symbol->tagidx].size;
output_number(offset);
} else {
error("sizeof undeclared variable");
output_number(0);
}
} else {
error("sizeof only on type or variable");
}
needbrack(")");
newline();
lval->symbol = 0;
lval->indirect = 0;
return(0);
}
if (symname (sname)) {
if ((symbol_table_idx = find_locale(sname)) > -1) {
symbol = &symbol_table[symbol_table_idx];
reg = gen_get_locale(symbol);
lval->symbol = symbol;
lval->indirect = symbol->type;
if (symbol->type == STRUCT) {
lval->tagsym = &tag_table[symbol->tagidx];
}
if (symbol->identity == ARRAY ||
(symbol->identity == VARIABLE && symbol->type == STRUCT)) {
lval->ptr_type = symbol->type;
return reg;
}
if (symbol->identity == POINTER) {
lval->indirect = CINT;
lval->ptr_type = symbol->type;
}
return FETCH | reg;
}
if ((symbol_table_idx = find_global(sname)) > -1) {
symbol = &symbol_table[symbol_table_idx];
if (symbol->identity != FUNCTION) {
lval->symbol = symbol;
lval->indirect = 0;
if (symbol->type == STRUCT) {
lval->tagsym = &tag_table[symbol->tagidx];
}
if (symbol->identity != ARRAY &&
(symbol->identity != VARIABLE || symbol->type != STRUCT)) {
if (symbol->identity == POINTER) {
lval->ptr_type = symbol->type;
}
return FETCH | HL_REG;
}
gen_immediate();
output_string(symbol->name);
newline();
lval->indirect = symbol->type;
lval->ptr_type = symbol->type;
return 0;
}
}
blanks();
if (ch() != '(')
error("undeclared variable");
symbol_table_idx = add_global(sname, FUNCTION, CINT, 0, PUBLIC);
symbol = &symbol_table[symbol_table_idx];
lval->symbol = symbol;
lval->indirect = 0;
return 0;
}
if (constant(num)) {
lval->symbol = 0;
lval->indirect = 0;
return 0;
}
else {
error("invalid expression");
gen_immediate();
output_number(0);
newline();
junk();
return 0;
}
}
/**
* true if val1 -> int pointer or int array and val2 not pointer or array
* @param val1
* @param val2
* @return
*/
dbltest (LVALUE *val1, LVALUE *val2) {
if (val1 == NULL)
return (FALSE);
if (val1->ptr_type) {
if (val1->ptr_type & CCHAR)
return (FALSE);
if (val2->ptr_type)
return (FALSE);
return (TRUE);
}
return (FALSE);
}
/**
* determine type of binary operation
* @param lval
* @param lval2
* @return
*/
result (LVALUE *lval, LVALUE *lval2) {
if (lval->ptr_type && lval2->ptr_type)
lval->ptr_type = 0;
else if (lval2->ptr_type) {
lval->symbol = lval2->symbol;
lval->indirect = lval2->indirect;
lval->ptr_type = lval2->ptr_type;
}
}
constant (int val[]) {
if (number (val))
gen_immediate ();
else if (quoted_char (val))
gen_immediate ();
else if (quoted_string (val)) {
gen_immediate ();
print_label (litlab);
output_byte ('+');
} else
return (0);
output_number (val[0]);
newline ();
return (1);
}
number (int val[]) {
int k, minus, base;
char c;
k = minus = 1;
while (k) {
k = 0;
if (match("+"))
k = 1;
if (match("-")) {
minus = (-minus);
k = 1;
}
}
if (!numeric(c = ch ()))
return (0);
if (match("0x") || match ("0X"))
while (numeric(c = ch ()) ||
(c >= 'a' && c <= 'f') ||
(c >= 'A' && c <= 'F')) {
inbyte ();
k = k * 16 + (numeric (c) ? (c - '0') : ((c & 07) + 9));
}
else {
base = (c == '0') ? 8 : 10;
while (numeric(ch())) {
c = inbyte ();
k = k * base + (c - '0');
}
}
if (minus < 0)
k = (-k);
val[0] = k;
if(k < 0) {
return (UINT);
} else {
return (CINT);
}
}
/**
* Test if we have one char enclosed in single quotes
* @param value returns the char found
* @return 1 if we have, 0 otherwise
*/
quoted_char (int *value) {
int k;
char c;
k = 0;
if (!match ("'"))
return (0);
while ((c = gch ()) != '\'') {
c = (c == '\\') ? spechar(): c;
k = (k & 255) * 256 + (c & 255);
}
*value = k;
return (1);
}
/**
* Test if we have string enclosed in double quotes. e.g. "abc".
* Load the string into literal pool.
* @param position returns beginning of the string
* @return 1 if such string found, 0 otherwise
*/
quoted_string (int *position) {
char c;
if (!match ("\""))
return (0);
*position = litptr;
while (ch () != '"') {
if (ch () == 0)
break;
if (litptr >= LITMAX) {
error ("string space exhausted");
while (!match ("\""))
if (gch () == 0)
break;
return (1);
}
c = gch();
litq[litptr++] = (c == '\\') ? spechar(): c;
}
gch ();
litq[litptr++] = 0;
return (1);
}
/**
* decode special characters (preceeded by back slashes)
*/
spechar() {
char c;
c = ch();
if (c == 'n') c = LF;
else if (c == 't') c = TAB;
else if (c == 'r') c = CR;
else if (c == 'f') c = FFEED;
else if (c == 'b') c = BKSP;
else if (c == '0') c = EOS;
else if (c == EOS) return 0;
gch();
return (c);
}
/**
* perform a function call
* called from "hier11", this routine will either call the named
* function, or if the supplied ptr is zero, will call the contents
* of HL
* @param ptr name of the function
*/
void callfunction (char *ptr) {
int nargs;
nargs = 0;
blanks ();
if (ptr == 0)
gen_push (HL_REG);
while (!streq (line + lptr, ")")) {
if (endst ())
break;
expression (NO);
if (ptr == 0)
gen_swap_stack ();
gen_push (HL_REG);
nargs = nargs + INTSIZE;
if (!match (","))
break;
}
needbrack (")");
if (aflag)
gnargs(nargs / INTSIZE);
if (ptr)
gen_call (ptr);
else
callstk ();
stkp = gen_modify_stack (stkp + nargs);
}
needlval () {
error ("must be lvalue");
}
|
879160.c | /****************************************************************************
* configs/stm32f334-disco/src/stm32_adc.c
*
* Copyright (C) 2017 Gregory Nutt. All rights reserved.
* Author: Ivan Ucherdzhiev <[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 <stdbool.h>
#include <errno.h>
#include <debug.h>
#include <nuttx/board.h>
#include <nuttx/analog/adc.h>
#include "stm32_gpio.h"
#include "stm32_adc.h"
#ifndef CONFIG_STM32F7_ADC3
# error "Only ADC3 channels are availiable on the arduino header of the board"
#endif
#if defined(CONFIG_ADC) && defined(CONFIG_STM32F7_ADC3)
/****************************************************************************
* Pre-processor Definitions
****************************************************************************/
/* Configuration ************************************************************/
/* If DMA support is not enabled, then only a single channel
* can be sampled. Otherwise, data overruns would occur.
*/
#ifdef ADC_HAVE_DMA
# define ADC3_NCHANNELS 6
#else
# define ADC3_NCHANNELS 1
#endif
/* The number of ADC channels in the conversion list */
/* TODO DMA */
/****************************************************************************
* Private Data
****************************************************************************/
/* Identifying number of each ADC channel (even if NCHANNELS is less ) */
static const uint8_t g_chanlist[6] =
{
0,
4,
5,
6,
7,
8
};
/* Configurations of pins used by each ADC channel */
static const uint32_t g_pinlist[6] =
{
GPIO_ADC3_IN0, /* PA0/A0 */
GPIO_ADC3_IN4, /* PF/A1 */
GPIO_ADC3_IN5, /* PF7/A3 */
GPIO_ADC3_IN6, /* PF8/A0 */
GPIO_ADC3_IN7, /* PF9/A1 */
GPIO_ADC3_IN8 /* PF10/A3 */
};
/****************************************************************************
* Public Functions
****************************************************************************/
/****************************************************************************
* Name: stm32_adc_setup
*
* Description:
* Initialize ADC and register the ADC driver.
*
****************************************************************************/
int stm32_adc_setup(void)
{
#ifdef CONFIG_STM32F7_ADC3
static bool initialized = false;
struct adc_dev_s *adc;
int ret;
int i;
/* Check if we have already initialized */
if (!initialized)
{
/* Configure the pins as analog inputs for the selected channels */
for (i = 0; i < ADC3_NCHANNELS; i++)
{
stm32_configgpio(g_pinlist[i]);
}
/* Call stm32_adcinitialize() to get an instance of the ADC interface */
adc = stm32_adc_initialize(3, g_chanlist, ADC3_NCHANNELS);
if (adc == NULL)
{
aerr("ERROR: Failed to get ADC interface\n");
return -ENODEV;
}
/* Register the ADC driver at "/dev/adc0" */
ret = adc_register("/dev/adc3", adc);
if (ret < 0)
{
aerr("ERROR: adc_register failed: %d\n", ret);
return ret;
}
/* Now we are initialized */
initialized = true;
}
return OK;
#else
return -ENOSYS;
#endif
}
#endif /* (CONFIG_ADC) && (CONFIG_STM32F7_ADC3) */
|
540381.c | /* $Id$ */
/*
* Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com)
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include <pjlib-util/http_client.h>
#include <pj/activesock.h>
#include <pj/assert.h>
#include <pj/ctype.h>
#include <pj/errno.h>
#include <pj/except.h>
#include <pj/pool.h>
#include <pj/string.h>
#include <pj/timer.h>
#include <pj/rand.h>
#include <pjlib-util/base64.h>
#include <pjlib-util/errno.h>
#include <pjlib-util/md5.h>
#include <pjlib-util/scanner.h>
#include <pjlib-util/string.h>
#define THIS_FILE "http_client.c"
#if 0
/* Enable some tracing */
#define TRACE_(arg) PJ_LOG(3,arg)
#else
#define TRACE_(arg)
#endif
#define NUM_PROTOCOL 2
#define HTTP_1_0 "1.0"
#define HTTP_1_1 "1.1"
#define CONTENT_LENGTH "Content-Length"
/* Buffer size for sending/receiving messages. */
#define BUF_SIZE 2048
/* Initial data buffer size to store the data in case content-
* length is not specified in the server's response.
*/
#define INITIAL_DATA_BUF_SIZE 2048
#define INITIAL_POOL_SIZE 1024
#define POOL_INCREMENT_SIZE 512
enum http_protocol
{
PROTOCOL_HTTP,
PROTOCOL_HTTPS
};
static const char *http_protocol_names[NUM_PROTOCOL] =
{
"HTTP",
"HTTPS"
};
static const unsigned int http_default_port[NUM_PROTOCOL] =
{
80,
443
};
enum http_method
{
HTTP_GET,
HTTP_PUT,
HTTP_DELETE
};
static const char *http_method_names[3] =
{
"GET",
"PUT",
"DELETE"
};
enum http_state
{
IDLE,
CONNECTING,
SENDING_REQUEST,
SENDING_REQUEST_BODY,
REQUEST_SENT,
READING_RESPONSE,
READING_DATA,
READING_COMPLETE,
ABORTING,
};
enum auth_state
{
AUTH_NONE, /* Not authenticating */
AUTH_RETRYING, /* New request with auth has been submitted */
AUTH_DONE /* Done retrying the request with auth. */
};
struct pj_http_req
{
pj_str_t url; /* Request URL */
pj_http_url hurl; /* Parsed request URL */
pj_sockaddr addr; /* The host's socket address */
pj_http_req_param param; /* HTTP request parameters */
pj_pool_t *pool; /* Pool to allocate memory from */
pj_timer_heap_t *timer; /* Timer for timeout management */
pj_ioqueue_t *ioqueue; /* Ioqueue to use */
pj_http_req_callback cb; /* Callbacks */
pj_activesock_t *asock; /* Active socket */
pj_status_t error; /* Error status */
pj_str_t buffer; /* Buffer to send/receive msgs */
enum http_state state; /* State of the HTTP request */
enum auth_state auth_state; /* Authentication state */
pj_timer_entry timer_entry;/* Timer entry */
pj_bool_t resolved; /* Whether URL's host is resolved */
pj_http_resp response; /* HTTP response */
pj_ioqueue_op_key_t op_key;
struct tcp_state
{
/* Total data sent so far if the data is sent in segments (i.e.
* if on_send_data() is not NULL and if param.reqdata.total_size > 0)
*/
pj_size_t tot_chunk_size;
/* Size of data to be sent (in a single activesock operation).*/
pj_size_t send_size;
/* Data size sent so far. */
pj_size_t current_send_size;
/* Total data received so far. */
pj_size_t current_read_size;
} tcp_state;
};
/* Start sending the request */
static pj_status_t http_req_start_sending(pj_http_req *hreq);
/* Start reading the response */
static pj_status_t http_req_start_reading(pj_http_req *hreq);
/* End the request */
static pj_status_t http_req_end_request(pj_http_req *hreq);
/* Parse the header data and populate the header fields with the result. */
static pj_status_t http_headers_parse(char *hdata, pj_size_t size,
pj_http_headers *headers);
/* Parse the response */
static pj_status_t http_response_parse(pj_pool_t *pool,
pj_http_resp *response,
void *data, pj_size_t size,
pj_size_t *remainder);
/* Restart the request with authentication */
static void restart_req_with_auth(pj_http_req *hreq);
/* Parse authentication challenge */
static pj_status_t parse_auth_chal(pj_pool_t *pool, pj_str_t *input,
pj_http_auth_chal *chal);
static pj_uint16_t get_http_default_port(const pj_str_t *protocol)
{
int i;
for (i = 0; i < NUM_PROTOCOL; i++) {
if (!pj_stricmp2(protocol, http_protocol_names[i])) {
return (pj_uint16_t)http_default_port[i];
}
}
return 0;
}
static const char * get_protocol(const pj_str_t *protocol)
{
int i;
for (i = 0; i < NUM_PROTOCOL; i++) {
if (!pj_stricmp2(protocol, http_protocol_names[i])) {
return http_protocol_names[i];
}
}
/* Should not happen */
pj_assert(0);
return NULL;
}
/* Syntax error handler for parser. */
static void on_syntax_error(pj_scanner *scanner)
{
PJ_UNUSED_ARG(scanner);
PJ_THROW(PJ_EINVAL); // syntax error
}
/* Callback when connection is established to the server */
static pj_bool_t http_on_connect(pj_activesock_t *asock,
pj_status_t status)
{
pj_http_req *hreq = (pj_http_req*) pj_activesock_get_user_data(asock);
if (hreq->state == ABORTING || hreq->state == IDLE)
return PJ_FALSE;
if (status != PJ_SUCCESS) {
hreq->error = status;
pj_http_req_cancel(hreq, PJ_TRUE);
return PJ_FALSE;
}
/* OK, we are connected. Start sending the request */
hreq->state = SENDING_REQUEST;
http_req_start_sending(hreq);
return PJ_TRUE;
}
static pj_bool_t http_on_data_sent(pj_activesock_t *asock,
pj_ioqueue_op_key_t *op_key,
pj_ssize_t sent)
{
pj_http_req *hreq = (pj_http_req*) pj_activesock_get_user_data(asock);
PJ_UNUSED_ARG(op_key);
if (hreq->state == ABORTING || hreq->state == IDLE)
return PJ_FALSE;
if (sent <= 0) {
hreq->error = (sent < 0 ? (pj_status_t)-sent : PJLIB_UTIL_EHTTPLOST);
pj_http_req_cancel(hreq, PJ_TRUE);
return PJ_FALSE;
}
hreq->tcp_state.current_send_size += sent;
TRACE_((THIS_FILE, "\nData sent: %d out of %d bytes",
hreq->tcp_state.current_send_size, hreq->tcp_state.send_size));
if (hreq->tcp_state.current_send_size == hreq->tcp_state.send_size) {
/* Find out whether there is a request body to send. */
if (hreq->param.reqdata.total_size > 0 ||
hreq->param.reqdata.size > 0)
{
if (hreq->state == SENDING_REQUEST) {
/* Start sending the request body */
hreq->state = SENDING_REQUEST_BODY;
hreq->tcp_state.tot_chunk_size = 0;
pj_assert(hreq->param.reqdata.total_size == 0 ||
(hreq->param.reqdata.total_size > 0 &&
hreq->param.reqdata.size == 0));
} else {
/* Continue sending the next chunk of the request body */
hreq->tcp_state.tot_chunk_size += hreq->tcp_state.send_size;
if (hreq->tcp_state.tot_chunk_size ==
hreq->param.reqdata.total_size ||
hreq->param.reqdata.total_size == 0)
{
/* Finish sending all the chunks, start reading
* the response.
*/
hreq->state = REQUEST_SENT;
http_req_start_reading(hreq);
return PJ_TRUE;
}
}
if (hreq->param.reqdata.total_size > 0 &&
hreq->cb.on_send_data)
{
/* Call the callback for the application to provide
* the next chunk of data to be sent.
*/
(*hreq->cb.on_send_data)(hreq, &hreq->param.reqdata.data,
&hreq->param.reqdata.size);
/* Make sure the total data size given by the user does not
* exceed what the user originally said.
*/
pj_assert(hreq->tcp_state.tot_chunk_size +
hreq->param.reqdata.size <=
hreq->param.reqdata.total_size);
}
http_req_start_sending(hreq);
} else {
/* No request body, proceed to reading the server's response. */
hreq->state = REQUEST_SENT;
http_req_start_reading(hreq);
}
}
return PJ_TRUE;
}
static pj_bool_t http_on_data_read(pj_activesock_t *asock,
void *data,
pj_size_t size,
pj_status_t status,
pj_size_t *remainder)
{
pj_http_req *hreq = (pj_http_req*) pj_activesock_get_user_data(asock);
TRACE_((THIS_FILE, "\nData received: %d bytes", size));
if (hreq->state == ABORTING || hreq->state == IDLE)
return PJ_FALSE;
if (hreq->state == READING_RESPONSE) {
pj_status_t st;
pj_size_t rem;
if (status != PJ_SUCCESS && status != PJ_EPENDING) {
hreq->error = status;
pj_http_req_cancel(hreq, PJ_TRUE);
return PJ_FALSE;
}
/* Parse the response. */
st = http_response_parse(hreq->pool, &hreq->response,
data, size, &rem);
if (st == PJLIB_UTIL_EHTTPINCHDR) {
/* If we already use up all our buffer and still
* hasn't received the whole header, return error
*/
if (size == BUF_SIZE) {
hreq->error = PJ_ETOOBIG; // response header size is too big
pj_http_req_cancel(hreq, PJ_TRUE);
return PJ_FALSE;
}
/* Keep the data if we do not get the whole response header */
*remainder = size;
} else {
hreq->state = READING_DATA;
if (st != PJ_SUCCESS) {
/* Server replied with an invalid (or unknown) response
* format. We'll just pass the whole (unparsed) response
* to the user.
*/
hreq->response.data = data;
hreq->response.size = size - rem;
}
/* If code is 401 or 407, find and parse WWW-Authenticate or
* Proxy-Authenticate header
*/
if (hreq->response.status_code == 401 ||
hreq->response.status_code == 407)
{
const pj_str_t STR_WWW_AUTH = { "WWW-Authenticate", 16 };
const pj_str_t STR_PROXY_AUTH = { "Proxy-Authenticate", 18 };
pj_http_resp *response = &hreq->response;
pj_http_headers *hdrs = &response->headers;
unsigned i;
status = PJ_ENOTFOUND;
for (i = 0; i < hdrs->count; i++) {
if (!pj_stricmp(&hdrs->header[i].name, &STR_WWW_AUTH) ||
!pj_stricmp(&hdrs->header[i].name, &STR_PROXY_AUTH))
{
status = parse_auth_chal(hreq->pool,
&hdrs->header[i].value,
&response->auth_chal);
break;
}
}
/* Check if we should perform authentication */
if (status == PJ_SUCCESS &&
hreq->auth_state == AUTH_NONE &&
hreq->response.auth_chal.scheme.slen &&
hreq->param.auth_cred.username.slen &&
(hreq->param.auth_cred.scheme.slen == 0 ||
!pj_stricmp(&hreq->response.auth_chal.scheme,
&hreq->param.auth_cred.scheme)) &&
(hreq->param.auth_cred.realm.slen == 0 ||
!pj_stricmp(&hreq->response.auth_chal.realm,
&hreq->param.auth_cred.realm))
)
{
/* Yes, authentication is required and we have been
* configured with credential.
*/
restart_req_with_auth(hreq);
if (hreq->auth_state == AUTH_RETRYING) {
/* We'll be resending the request with auth. This
* connection has been closed.
*/
return PJ_FALSE;
}
}
}
/* We already received the response header, call the
* appropriate callback.
*/
if (hreq->cb.on_response)
(*hreq->cb.on_response)(hreq, &hreq->response);
hreq->response.data = NULL;
hreq->response.size = 0;
if (rem > 0 || hreq->response.content_length == 0)
return http_on_data_read(asock, (rem == 0 ? NULL:
(char *)data + size - rem),
rem, PJ_SUCCESS, NULL);
}
return PJ_TRUE;
}
if (hreq->state != READING_DATA)
return PJ_FALSE;
if (hreq->cb.on_data_read) {
/* If application wishes to receive the data once available, call
* its callback.
*/
if (size > 0)
(*hreq->cb.on_data_read)(hreq, data, size);
} else {
if (hreq->response.size == 0) {
/* If we know the content length, allocate the data based
* on that, otherwise we'll use initial buffer size and grow
* it later if necessary.
*/
hreq->response.size = (hreq->response.content_length == -1 ?
INITIAL_DATA_BUF_SIZE :
hreq->response.content_length);
hreq->response.data = pj_pool_alloc(hreq->pool,
hreq->response.size);
}
/* If the size of data received exceeds its current size,
* grow the buffer by a factor of 2.
*/
if (hreq->tcp_state.current_read_size + size >
hreq->response.size)
{
void *olddata = hreq->response.data;
hreq->response.data = pj_pool_alloc(hreq->pool,
hreq->response.size << 1);
pj_memcpy(hreq->response.data, olddata, hreq->response.size);
hreq->response.size <<= 1;
}
/* Append the response data. */
pj_memcpy((char *)hreq->response.data +
hreq->tcp_state.current_read_size, data, size);
}
hreq->tcp_state.current_read_size += size;
/* If the total data received so far is equal to the content length
* or if it's already EOF.
*/
if ((hreq->response.content_length >=0 &&
(pj_ssize_t)hreq->tcp_state.current_read_size >=
hreq->response.content_length) ||
(status == PJ_EEOF && hreq->response.content_length == -1))
{
/* Finish reading */
http_req_end_request(hreq);
hreq->response.size = hreq->tcp_state.current_read_size;
/* HTTP request is completed, call the callback. */
if (hreq->cb.on_complete) {
(*hreq->cb.on_complete)(hreq, PJ_SUCCESS, &hreq->response);
}
return PJ_FALSE;
}
/* Error status or premature EOF. */
if ((status != PJ_SUCCESS && status != PJ_EPENDING && status != PJ_EEOF)
|| (status == PJ_EEOF && hreq->response.content_length > -1))
{
hreq->error = status;
pj_http_req_cancel(hreq, PJ_TRUE);
return PJ_FALSE;
}
return PJ_TRUE;
}
/* Callback to be called when query has timed out */
static void on_timeout( pj_timer_heap_t *timer_heap,
struct pj_timer_entry *entry)
{
pj_http_req *hreq = (pj_http_req *) entry->user_data;
PJ_UNUSED_ARG(timer_heap);
/* Recheck that the request is still not completed, since there is a
* slight possibility of race condition (timer elapsed while at the
* same time response arrives).
*/
if (hreq->state == READING_COMPLETE) {
/* Yeah, we finish on time */
return;
}
/* Invalidate id. */
hreq->timer_entry.id = 0;
/* Request timed out. */
hreq->error = PJ_ETIMEDOUT;
pj_http_req_cancel(hreq, PJ_TRUE);
}
/* Parse authentication challenge */
static pj_status_t parse_auth_chal(pj_pool_t *pool, pj_str_t *input,
pj_http_auth_chal *chal)
{
pj_scanner scanner;
const pj_str_t REALM_STR = { "realm", 5},
NONCE_STR = { "nonce", 5},
ALGORITHM_STR = { "algorithm", 9 },
STALE_STR = { "stale", 5},
QOP_STR = { "qop", 3},
OPAQUE_STR = { "opaque", 6};
pj_status_t status = PJ_SUCCESS;
PJ_USE_EXCEPTION ;
pj_scan_init(&scanner, input->ptr, input->slen, PJ_SCAN_AUTOSKIP_WS,
&on_syntax_error);
PJ_TRY {
/* Get auth scheme */
if (*scanner.curptr == '"') {
pj_scan_get_quote(&scanner, '"', '"', &chal->scheme);
chal->scheme.ptr++;
chal->scheme.slen -= 2;
} else {
pj_scan_get_until_chr(&scanner, " \t\r\n", &chal->scheme);
}
/* Loop parsing all parameters */
for (;;) {
const char *end_param = ", \t\r\n;";
pj_str_t name, value;
/* Get pair of parameter name and value */
value.ptr = NULL;
value.slen = 0;
pj_scan_get_until_chr(&scanner, "=, \t\r\n", &name);
if (*scanner.curptr == '=') {
pj_scan_get_char(&scanner);
if (!pj_scan_is_eof(&scanner)) {
if (*scanner.curptr == '"' || *scanner.curptr == '\'') {
int quote_char = *scanner.curptr;
pj_scan_get_quote(&scanner, quote_char, quote_char,
&value);
value.ptr++;
value.slen -= 2;
} else if (!strchr(end_param, *scanner.curptr)) {
pj_scan_get_until_chr(&scanner, end_param, &value);
}
}
value = pj_str_unescape(pool, &value);
}
if (!pj_stricmp(&name, &REALM_STR)) {
chal->realm = value;
} else if (!pj_stricmp(&name, &NONCE_STR)) {
chal->nonce = value;
} else if (!pj_stricmp(&name, &ALGORITHM_STR)) {
chal->algorithm = value;
} else if (!pj_stricmp(&name, &OPAQUE_STR)) {
chal->opaque = value;
} else if (!pj_stricmp(&name, &QOP_STR)) {
chal->qop = value;
} else if (!pj_stricmp(&name, &STALE_STR)) {
chal->stale = value.slen &&
(*value.ptr != '0') &&
(*value.ptr != 'f') &&
(*value.ptr != 'F');
}
/* Eat comma */
if (!pj_scan_is_eof(&scanner) && *scanner.curptr == ',')
pj_scan_get_char(&scanner);
else
break;
}
}
PJ_CATCH_ANY {
status = PJ_GET_EXCEPTION();
pj_bzero(chal, sizeof(*chal));
TRACE_((THIS_FILE, "Error: parsing of auth header failed"));
}
PJ_END;
pj_scan_fini(&scanner);
return status;
}
/* The same as #pj_http_headers_add_elmt() with char * as
* its parameters.
*/
PJ_DEF(pj_status_t) pj_http_headers_add_elmt2(pj_http_headers *headers,
char *name, char *val)
{
pj_str_t f, v;
pj_cstr(&f, name);
pj_cstr(&v, val);
return pj_http_headers_add_elmt(headers, &f, &v);
}
PJ_DEF(pj_status_t) pj_http_headers_add_elmt(pj_http_headers *headers,
pj_str_t *name,
pj_str_t *val)
{
PJ_ASSERT_RETURN(headers && name && val, PJ_FALSE);
if (headers->count >= PJ_HTTP_HEADER_SIZE)
return PJ_ETOOMANY;
pj_strassign(&headers->header[headers->count].name, name);
pj_strassign(&headers->header[headers->count++].value, val);
return PJ_SUCCESS;
}
static pj_status_t http_response_parse(pj_pool_t *pool,
pj_http_resp *response,
void *data, pj_size_t size,
pj_size_t *remainder)
{
pj_size_t i;
char *cptr;
char *end_status, *newdata;
pj_scanner scanner;
pj_str_t s;
const pj_str_t STR_CONTENT_LENGTH = { CONTENT_LENGTH, 14 };
pj_status_t status;
PJ_USE_EXCEPTION;
PJ_ASSERT_RETURN(response, PJ_EINVAL);
if (size < 2)
return PJLIB_UTIL_EHTTPINCHDR;
/* Detect whether we already receive the response's status-line
* and its headers. We're looking for a pair of CRLFs. A pair of
* LFs is also supported although it is not RFC standard.
*/
cptr = (char *)data;
for (i = 1, cptr++; i < size; i++, cptr++) {
if (*cptr == '\n') {
if (*(cptr - 1) == '\n')
break;
if (*(cptr - 1) == '\r') {
if (i >= 3 && *(cptr - 2) == '\n' && *(cptr - 3) == '\r')
break;
}
}
}
if (i == size)
return PJLIB_UTIL_EHTTPINCHDR;
*remainder = size - 1 - i;
pj_bzero(response, sizeof(*response));
response->content_length = -1;
newdata = (char*) pj_pool_alloc(pool, i);
pj_memcpy(newdata, data, i);
/* Parse the status-line. */
pj_scan_init(&scanner, newdata, i, 0, &on_syntax_error);
PJ_TRY {
pj_scan_get_until_ch(&scanner, ' ', &response->version);
pj_scan_advance_n(&scanner, 1, PJ_FALSE);
pj_scan_get_until_ch(&scanner, ' ', &s);
response->status_code = (pj_uint16_t)pj_strtoul(&s);
pj_scan_advance_n(&scanner, 1, PJ_FALSE);
pj_scan_get_until_ch(&scanner, '\n', &response->reason);
if (response->reason.ptr[response->reason.slen-1] == '\r')
response->reason.slen--;
}
PJ_CATCH_ANY {
pj_scan_fini(&scanner);
return PJ_GET_EXCEPTION();
}
PJ_END;
end_status = scanner.curptr;
pj_scan_fini(&scanner);
/* Parse the response headers. */
size = i - 2 - (end_status - newdata);
if (size > 0) {
status = http_headers_parse(end_status + 1, size,
&response->headers);
} else {
status = PJ_SUCCESS;
}
/* Find content-length header field. */
for (i = 0; i < response->headers.count; i++) {
if (!pj_stricmp(&response->headers.header[i].name,
&STR_CONTENT_LENGTH))
{
response->content_length =
pj_strtoul(&response->headers.header[i].value);
/* If content length is zero, make sure that it is because the
* header value is really zero and not due to parsing error.
*/
if (response->content_length == 0) {
if (pj_strcmp2(&response->headers.header[i].value, "0")) {
response->content_length = -1;
}
}
break;
}
}
return status;
}
static pj_status_t http_headers_parse(char *hdata, pj_size_t size,
pj_http_headers *headers)
{
pj_scanner scanner;
pj_str_t s, s2;
pj_status_t status;
PJ_USE_EXCEPTION;
PJ_ASSERT_RETURN(headers, PJ_EINVAL);
pj_scan_init(&scanner, hdata, size, 0, &on_syntax_error);
/* Parse each line of header field consisting of header field name and
* value, separated by ":" and any number of white spaces.
*/
PJ_TRY {
do {
pj_scan_get_until_chr(&scanner, ":\n", &s);
if (*scanner.curptr == ':') {
pj_scan_advance_n(&scanner, 1, PJ_TRUE);
pj_scan_get_until_ch(&scanner, '\n', &s2);
if (s2.ptr[s2.slen-1] == '\r')
s2.slen--;
status = pj_http_headers_add_elmt(headers, &s, &s2);
if (status != PJ_SUCCESS)
PJ_THROW(status);
}
pj_scan_advance_n(&scanner, 1, PJ_TRUE);
/* Finish parsing */
if (pj_scan_is_eof(&scanner))
break;
} while (1);
}
PJ_CATCH_ANY {
pj_scan_fini(&scanner);
return PJ_GET_EXCEPTION();
}
PJ_END;
pj_scan_fini(&scanner);
return PJ_SUCCESS;
}
PJ_DEF(void) pj_http_req_param_default(pj_http_req_param *param)
{
pj_assert(param);
pj_bzero(param, sizeof(*param));
param->addr_family = pj_AF_INET();
pj_strset2(¶m->method, (char*)http_method_names[HTTP_GET]);
pj_strset2(¶m->version, (char*)HTTP_1_0);
param->timeout.msec = PJ_HTTP_DEFAULT_TIMEOUT;
pj_time_val_normalize(¶m->timeout);
param->max_retries = 3;
}
/* Get the location of '@' character to indicate the end of
* user:passwd part of an URI. If user:passwd part is not
* present, NULL will be returned.
*/
static char *get_url_at_pos(const char *str, pj_size_t len)
{
const char *end = str + len;
const char *p = str;
/* skip scheme: */
while (p!=end && *p!='/') ++p;
if (p!=end && *p=='/') ++p;
if (p!=end && *p=='/') ++p;
if (p==end) return NULL;
for (; p!=end; ++p) {
switch (*p) {
case '/':
return NULL;
case '@':
return (char*)p;
}
}
return NULL;
}
PJ_DEF(pj_status_t) pj_http_req_parse_url(const pj_str_t *url,
pj_http_url *hurl)
{
pj_scanner scanner;
pj_size_t len = url->slen;
PJ_USE_EXCEPTION;
if (!len) return -1;
pj_bzero(hurl, sizeof(*hurl));
pj_scan_init(&scanner, url->ptr, url->slen, 0, &on_syntax_error);
PJ_TRY {
pj_str_t s;
/* Exhaust any whitespaces. */
pj_scan_skip_whitespace(&scanner);
/* Parse the protocol */
pj_scan_get_until_ch(&scanner, ':', &s);
if (!pj_stricmp2(&s, http_protocol_names[PROTOCOL_HTTP])) {
pj_strset2(&hurl->protocol,
(char*)http_protocol_names[PROTOCOL_HTTP]);
} else if (!pj_stricmp2(&s, http_protocol_names[PROTOCOL_HTTPS])) {
pj_strset2(&hurl->protocol,
(char*)http_protocol_names[PROTOCOL_HTTPS]);
} else {
PJ_THROW(PJ_ENOTSUP); // unsupported protocol
}
if (pj_scan_strcmp(&scanner, "://", 3)) {
PJ_THROW(PJLIB_UTIL_EHTTPINURL); // no "://" after protocol name
}
pj_scan_advance_n(&scanner, 3, PJ_FALSE);
if (get_url_at_pos(url->ptr, url->slen)) {
/* Parse username and password */
pj_scan_get_until_chr(&scanner, ":@", &hurl->username);
if (*scanner.curptr == ':') {
pj_scan_get_char(&scanner);
pj_scan_get_until_chr(&scanner, "@", &hurl->passwd);
} else {
hurl->passwd.slen = 0;
}
pj_scan_get_char(&scanner);
}
/* Parse the host and port number (if any) */
pj_scan_get_until_chr(&scanner, ":/", &s);
pj_strassign(&hurl->host, &s);
if (hurl->host.slen==0)
PJ_THROW(PJ_EINVAL);
if (pj_scan_is_eof(&scanner) || *scanner.curptr == '/') {
/* No port number specified */
/* Assume default http/https port number */
hurl->port = get_http_default_port(&hurl->protocol);
pj_assert(hurl->port > 0);
} else {
pj_scan_advance_n(&scanner, 1, PJ_FALSE);
pj_scan_get_until_ch(&scanner, '/', &s);
/* Parse the port number */
hurl->port = (pj_uint16_t)pj_strtoul(&s);
if (!hurl->port)
PJ_THROW(PJLIB_UTIL_EHTTPINPORT); // invalid port number
}
if (!pj_scan_is_eof(&scanner)) {
hurl->path.ptr = scanner.curptr;
hurl->path.slen = scanner.end - scanner.curptr;
} else {
/* no path, append '/' */
pj_cstr(&hurl->path, "/");
}
}
PJ_CATCH_ANY {
pj_scan_fini(&scanner);
return PJ_GET_EXCEPTION();
}
PJ_END;
pj_scan_fini(&scanner);
return PJ_SUCCESS;
}
PJ_DEF(void) pj_http_req_set_timeout(pj_http_req *http_req,
const pj_time_val* timeout)
{
pj_memcpy(&http_req->param.timeout, timeout, sizeof(*timeout));
}
PJ_DEF(pj_status_t) pj_http_req_create(pj_pool_t *pool,
const pj_str_t *url,
pj_timer_heap_t *timer,
pj_ioqueue_t *ioqueue,
const pj_http_req_param *param,
const pj_http_req_callback *hcb,
pj_http_req **http_req)
{
pj_pool_t *own_pool;
pj_http_req *hreq;
char *at_pos;
pj_status_t status;
PJ_ASSERT_RETURN(pool && url && timer && ioqueue &&
hcb && http_req, PJ_EINVAL);
*http_req = NULL;
own_pool = pj_pool_create(pool->factory, NULL, INITIAL_POOL_SIZE,
POOL_INCREMENT_SIZE, NULL);
hreq = PJ_POOL_ZALLOC_T(own_pool, struct pj_http_req);
if (!hreq)
return PJ_ENOMEM;
/* Initialization */
hreq->pool = own_pool;
hreq->ioqueue = ioqueue;
hreq->timer = timer;
hreq->asock = NULL;
pj_memcpy(&hreq->cb, hcb, sizeof(*hcb));
hreq->state = IDLE;
hreq->resolved = PJ_FALSE;
hreq->buffer.ptr = NULL;
pj_timer_entry_init(&hreq->timer_entry, 0, hreq, &on_timeout);
/* Initialize parameter */
if (param) {
pj_memcpy(&hreq->param, param, sizeof(*param));
/* TODO: validate the param here
* Should we validate the method as well? If yes, based on all HTTP
* methods or based on supported methods only? For the later, one
* drawback would be that you can't use this if the method is not
* officially supported
*/
PJ_ASSERT_RETURN(hreq->param.addr_family==pj_AF_UNSPEC() ||
hreq->param.addr_family==pj_AF_INET() ||
hreq->param.addr_family==pj_AF_INET6(), PJ_EAFNOTSUP);
PJ_ASSERT_RETURN(!pj_strcmp2(&hreq->param.version, HTTP_1_0) ||
!pj_strcmp2(&hreq->param.version, HTTP_1_1),
PJ_ENOTSUP);
pj_time_val_normalize(&hreq->param.timeout);
} else {
pj_http_req_param_default(&hreq->param);
}
/* Parse the URL */
if (!pj_strdup_with_null(hreq->pool, &hreq->url, url)) {
pj_pool_release(hreq->pool);
return PJ_ENOMEM;
}
status = pj_http_req_parse_url(&hreq->url, &hreq->hurl);
if (status != PJ_SUCCESS) {
pj_pool_release(hreq->pool);
return status; // Invalid URL supplied
}
/* If URL contains username/password, move them to credential and
* remove them from the URL.
*/
if ((at_pos=get_url_at_pos(hreq->url.ptr, hreq->url.slen)) != NULL) {
pj_str_t tmp;
char *user_pos = pj_strchr(&hreq->url, '/');
int removed_len;
/* Save credential first, unescape the string */
tmp = pj_str_unescape(hreq->pool, &hreq->hurl.username);;
pj_strdup(hreq->pool, &hreq->param.auth_cred.username, &tmp);
tmp = pj_str_unescape(hreq->pool, &hreq->hurl.passwd);
pj_strdup(hreq->pool, &hreq->param.auth_cred.data, &tmp);
hreq->hurl.username.ptr = hreq->hurl.passwd.ptr = NULL;
hreq->hurl.username.slen = hreq->hurl.passwd.slen = 0;
/* Remove "username:password@" from the URL */
pj_assert(user_pos != 0 && user_pos < at_pos);
user_pos += 2;
removed_len = (int)(at_pos + 1 - user_pos);
pj_memmove(user_pos, at_pos+1, hreq->url.ptr+hreq->url.slen-at_pos-1);
hreq->url.slen -= removed_len;
/* Need to adjust hostname and path pointers due to memmove*/
if (hreq->hurl.host.ptr > user_pos &&
hreq->hurl.host.ptr < user_pos + hreq->url.slen)
{
hreq->hurl.host.ptr -= removed_len;
}
/* path may come from a string constant, don't shift it if so */
if (hreq->hurl.path.ptr > user_pos &&
hreq->hurl.path.ptr < user_pos + hreq->url.slen)
{
hreq->hurl.path.ptr -= removed_len;
}
}
*http_req = hreq;
return PJ_SUCCESS;
}
PJ_DEF(pj_bool_t) pj_http_req_is_running(const pj_http_req *http_req)
{
PJ_ASSERT_RETURN(http_req, PJ_FALSE);
return (http_req->state != IDLE);
}
PJ_DEF(void*) pj_http_req_get_user_data(pj_http_req *http_req)
{
PJ_ASSERT_RETURN(http_req, NULL);
return http_req->param.user_data;
}
static pj_status_t start_http_req(pj_http_req *http_req,
pj_bool_t notify_on_fail)
{
pj_sock_t sock = PJ_INVALID_SOCKET;
pj_status_t status;
pj_activesock_cb asock_cb;
int retry = 0;
PJ_ASSERT_RETURN(http_req, PJ_EINVAL);
/* Http request is not idle, a request was initiated before and
* is still in progress
*/
PJ_ASSERT_RETURN(http_req->state == IDLE, PJ_EBUSY);
/* Reset few things to make sure restarting works */
http_req->error = 0;
http_req->response.headers.count = 0;
pj_bzero(&http_req->tcp_state, sizeof(http_req->tcp_state));
if (!http_req->resolved) {
/* Resolve the Internet address of the host */
status = pj_sockaddr_init(http_req->param.addr_family,
&http_req->addr, &http_req->hurl.host,
http_req->hurl.port);
if (status != PJ_SUCCESS ||
!pj_sockaddr_has_addr(&http_req->addr) ||
(http_req->param.addr_family==pj_AF_INET() &&
http_req->addr.ipv4.sin_addr.s_addr==PJ_INADDR_NONE))
{
goto on_return;
}
http_req->resolved = PJ_TRUE;
}
status = pj_sock_socket(http_req->param.addr_family, pj_SOCK_STREAM(),
0, &sock);
if (status != PJ_SUCCESS)
goto on_return; // error creating socket
pj_bzero(&asock_cb, sizeof(asock_cb));
asock_cb.on_data_read = &http_on_data_read;
asock_cb.on_data_sent = &http_on_data_sent;
asock_cb.on_connect_complete = &http_on_connect;
do
{
pj_sockaddr_in bound_addr;
pj_uint16_t port = 0;
/* If we are using port restriction.
* Get a random port within the range
*/
if (http_req->param.source_port_range_start != 0) {
port = (pj_uint16_t)
(http_req->param.source_port_range_start +
(pj_rand() % http_req->param.source_port_range_size));
}
pj_sockaddr_in_init(&bound_addr, NULL, port);
status = pj_sock_bind(sock, &bound_addr, sizeof(bound_addr));
} while (status != PJ_SUCCESS && (retry++ < http_req->param.max_retries));
if (status != PJ_SUCCESS) {
PJ_PERROR(1,(THIS_FILE, status,
"Unable to bind to the requested port"));
pj_sock_close(sock);
goto on_return;
}
// TODO: should we set whole data to 0 by default?
// or add it in the param?
status = pj_activesock_create(http_req->pool, sock, pj_SOCK_STREAM(),
NULL, http_req->ioqueue,
&asock_cb, http_req, &http_req->asock);
if (status != PJ_SUCCESS) {
pj_sock_close(sock);
goto on_return; // error creating activesock
}
/* Schedule timeout timer for the request */
pj_assert(http_req->timer_entry.id == 0);
http_req->timer_entry.id = 1;
status = pj_timer_heap_schedule(http_req->timer, &http_req->timer_entry,
&http_req->param.timeout);
if (status != PJ_SUCCESS) {
http_req->timer_entry.id = 0;
goto on_return; // error scheduling timer
}
/* Connect to host */
http_req->state = CONNECTING;
status = pj_activesock_start_connect(http_req->asock, http_req->pool,
(pj_sock_t *)&(http_req->addr),
pj_sockaddr_get_len(&http_req->addr));
if (status == PJ_SUCCESS) {
http_req->state = SENDING_REQUEST;
status = http_req_start_sending(http_req);
if (status != PJ_SUCCESS)
goto on_return;
} else if (status != PJ_EPENDING) {
goto on_return; // error connecting
}
return PJ_SUCCESS;
on_return:
http_req->error = status;
if (notify_on_fail)
pj_http_req_cancel(http_req, PJ_TRUE);
else
http_req_end_request(http_req);
return status;
}
/* Starts an asynchronous HTTP request to the URL specified. */
PJ_DEF(pj_status_t) pj_http_req_start(pj_http_req *http_req)
{
return start_http_req(http_req, PJ_FALSE);
}
/* Respond to basic authentication challenge */
static pj_status_t auth_respond_basic(pj_http_req *hreq)
{
/* Basic authentication:
* credentials = "Basic" basic-credentials
* basic-credentials = base64-user-pass
* base64-user-pass = <base64 [4] encoding of user-pass>
* user-pass = userid ":" password
*
* Sample:
* Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==
*/
pj_str_t user_pass;
pj_http_header_elmt *phdr;
int len;
/* Use send buffer to store userid ":" password */
user_pass.ptr = hreq->buffer.ptr;
pj_strcpy(&user_pass, &hreq->param.auth_cred.username);
pj_strcat2(&user_pass, ":");
pj_strcat(&user_pass, &hreq->param.auth_cred.data);
/* Create Authorization header */
phdr = &hreq->param.headers.header[hreq->param.headers.count++];
pj_bzero(phdr, sizeof(*phdr));
if (hreq->response.status_code == 401)
phdr->name = pj_str("Authorization");
else
phdr->name = pj_str("Proxy-Authorization");
len = (int)(PJ_BASE256_TO_BASE64_LEN(user_pass.slen) + 10);
phdr->value.ptr = (char*)pj_pool_alloc(hreq->pool, len);
phdr->value.slen = 0;
pj_strcpy2(&phdr->value, "Basic ");
len -= (int)phdr->value.slen;
pj_base64_encode((pj_uint8_t*)user_pass.ptr, (int)user_pass.slen,
phdr->value.ptr + phdr->value.slen, &len);
phdr->value.slen += len;
return PJ_SUCCESS;
}
/** Length of digest string. */
#define MD5_STRLEN 32
/* A macro just to get rid of type mismatch between char and unsigned char */
#define MD5_APPEND(pms,buf,len) pj_md5_update(pms, (const pj_uint8_t*)buf, \
(unsigned)len)
/* Transform digest to string.
* output must be at least PJSIP_MD5STRLEN+1 bytes.
*
* NOTE: THE OUTPUT STRING IS NOT NULL TERMINATED!
*/
static void digest2str(const unsigned char digest[], char *output)
{
int i;
for (i = 0; i<16; ++i) {
pj_val_to_hex_digit(digest[i], output);
output += 2;
}
}
static void auth_create_digest_response(pj_str_t *result,
const pj_http_auth_cred *cred,
const pj_str_t *nonce,
const pj_str_t *nc,
const pj_str_t *cnonce,
const pj_str_t *qop,
const pj_str_t *uri,
const pj_str_t *realm,
const pj_str_t *method)
{
char ha1[MD5_STRLEN];
char ha2[MD5_STRLEN];
unsigned char digest[16];
pj_md5_context pms;
pj_assert(result->slen >= MD5_STRLEN);
TRACE_((THIS_FILE, "Begin creating digest"));
if (cred->data_type == 0) {
/***
*** ha1 = MD5(username ":" realm ":" password)
***/
pj_md5_init(&pms);
MD5_APPEND( &pms, cred->username.ptr, cred->username.slen);
MD5_APPEND( &pms, ":", 1);
MD5_APPEND( &pms, realm->ptr, realm->slen);
MD5_APPEND( &pms, ":", 1);
MD5_APPEND( &pms, cred->data.ptr, cred->data.slen);
pj_md5_final(&pms, digest);
digest2str(digest, ha1);
} else if (cred->data_type == 1) {
pj_assert(cred->data.slen == 32);
pj_memcpy( ha1, cred->data.ptr, cred->data.slen );
} else {
pj_assert(!"Invalid data_type");
}
TRACE_((THIS_FILE, " ha1=%.32s", ha1));
/***
*** ha2 = MD5(method ":" req_uri)
***/
pj_md5_init(&pms);
MD5_APPEND( &pms, method->ptr, method->slen);
MD5_APPEND( &pms, ":", 1);
MD5_APPEND( &pms, uri->ptr, uri->slen);
pj_md5_final(&pms, digest);
digest2str(digest, ha2);
TRACE_((THIS_FILE, " ha2=%.32s", ha2));
/***
*** When qop is not used:
*** response = MD5(ha1 ":" nonce ":" ha2)
***
*** When qop=auth is used:
*** response = MD5(ha1 ":" nonce ":" nc ":" cnonce ":" qop ":" ha2)
***/
pj_md5_init(&pms);
MD5_APPEND( &pms, ha1, MD5_STRLEN);
MD5_APPEND( &pms, ":", 1);
MD5_APPEND( &pms, nonce->ptr, nonce->slen);
if (qop && qop->slen != 0) {
MD5_APPEND( &pms, ":", 1);
MD5_APPEND( &pms, nc->ptr, nc->slen);
MD5_APPEND( &pms, ":", 1);
MD5_APPEND( &pms, cnonce->ptr, cnonce->slen);
MD5_APPEND( &pms, ":", 1);
MD5_APPEND( &pms, qop->ptr, qop->slen);
}
MD5_APPEND( &pms, ":", 1);
MD5_APPEND( &pms, ha2, MD5_STRLEN);
/* This is the final response digest. */
pj_md5_final(&pms, digest);
/* Convert digest to string and store in chal->response. */
result->slen = MD5_STRLEN;
digest2str(digest, result->ptr);
TRACE_((THIS_FILE, " digest=%.32s", result->ptr));
TRACE_((THIS_FILE, "Digest created"));
}
/* Find out if qop offer contains "auth" token */
static pj_bool_t auth_has_qop( pj_pool_t *pool, const pj_str_t *qop_offer)
{
pj_str_t qop;
char *p;
pj_strdup_with_null( pool, &qop, qop_offer);
p = qop.ptr;
while (*p) {
*p = (char)pj_tolower(*p);
++p;
}
p = qop.ptr;
while (*p) {
if (*p=='a' && *(p+1)=='u' && *(p+2)=='t' && *(p+3)=='h') {
int e = *(p+4);
if (e=='"' || e==',' || e==0)
return PJ_TRUE;
else
p += 4;
} else {
++p;
}
}
return PJ_FALSE;
}
#define STR_PREC(s) (int)(s).slen, (s).ptr
/* Respond to digest authentication */
static pj_status_t auth_respond_digest(pj_http_req *hreq)
{
const pj_http_auth_chal *chal = &hreq->response.auth_chal;
const pj_http_auth_cred *cred = &hreq->param.auth_cred;
pj_http_header_elmt *phdr;
char digest_response_buf[MD5_STRLEN];
int len;
pj_str_t digest_response;
/* Check algorithm is supported. We only support MD5 */
if (chal->algorithm.slen!=0 &&
pj_stricmp2(&chal->algorithm, "MD5"))
{
TRACE_((THIS_FILE, "Error: Unsupported digest algorithm \"%.*s\"",
chal->algorithm.slen, chal->algorithm.ptr));
return PJ_ENOTSUP;
}
/* Add Authorization header */
phdr = &hreq->param.headers.header[hreq->param.headers.count++];
pj_bzero(phdr, sizeof(*phdr));
if (hreq->response.status_code == 401)
phdr->name = pj_str("Authorization");
else
phdr->name = pj_str("Proxy-Authorization");
/* Allocate space for the header */
len = (int)(8 + /* Digest */
16 + hreq->param.auth_cred.username.slen + /* username= */
12 + chal->realm.slen + /* realm= */
12 + chal->nonce.slen + /* nonce= */
8 + hreq->hurl.path.slen + /* uri= */
16 + /* algorithm=MD5 */
16 + MD5_STRLEN + /* response= */
12 + /* qop=auth */
8 + /* nc=.. */
30 + /* cnonce= */
12 + chal->opaque.slen + /* opaque=".." */
0);
phdr->value.ptr = (char*)pj_pool_alloc(hreq->pool, len);
/* Configure buffer to temporarily store the digest */
digest_response.ptr = digest_response_buf;
digest_response.slen = MD5_STRLEN;
if (chal->qop.slen == 0) {
const pj_str_t STR_MD5 = { "MD5", 3 };
int max_len;
/* Server doesn't require quality of protection. */
auth_create_digest_response(&digest_response, cred,
&chal->nonce, NULL, NULL, NULL,
&hreq->hurl.path, &chal->realm,
&hreq->param.method);
max_len = len;
len = pj_ansi_snprintf(
phdr->value.ptr, max_len,
"Digest username=\"%.*s\", "
"realm=\"%.*s\", "
"nonce=\"%.*s\", "
"uri=\"%.*s\", "
"algorithm=%.*s, "
"response=\"%.*s\"",
STR_PREC(cred->username),
STR_PREC(chal->realm),
STR_PREC(chal->nonce),
STR_PREC(hreq->hurl.path),
STR_PREC(STR_MD5),
STR_PREC(digest_response));
if (len < 0 || len >= max_len)
return PJ_ETOOSMALL;
phdr->value.slen = len;
} else if (auth_has_qop(hreq->pool, &chal->qop)) {
/* Server requires quality of protection.
* We respond with selecting "qop=auth" protection.
*/
const pj_str_t STR_MD5 = { "MD5", 3 };
const pj_str_t qop = pj_str("auth");
const pj_str_t nc = pj_str("00000001");
const pj_str_t cnonce = pj_str("b39971");
int max_len;
auth_create_digest_response(&digest_response, cred,
&chal->nonce, &nc, &cnonce, &qop,
&hreq->hurl.path, &chal->realm,
&hreq->param.method);
max_len = len;
len = pj_ansi_snprintf(
phdr->value.ptr, max_len,
"Digest username=\"%.*s\", "
"realm=\"%.*s\", "
"nonce=\"%.*s\", "
"uri=\"%.*s\", "
"algorithm=%.*s, "
"response=\"%.*s\", "
"qop=%.*s, "
"nc=%.*s, "
"cnonce=\"%.*s\"",
STR_PREC(cred->username),
STR_PREC(chal->realm),
STR_PREC(chal->nonce),
STR_PREC(hreq->hurl.path),
STR_PREC(STR_MD5),
STR_PREC(digest_response),
STR_PREC(qop),
STR_PREC(nc),
STR_PREC(cnonce));
if (len < 0 || len >= max_len)
return PJ_ETOOSMALL;
phdr->value.slen = len;
if (chal->opaque.slen) {
pj_strcat2(&phdr->value, ", opaque=\"");
pj_strcat(&phdr->value, &chal->opaque);
pj_strcat2(&phdr->value, "\"");
}
} else {
/* Server requires quality protection that we don't support. */
TRACE_((THIS_FILE, "Error: Unsupported qop offer %.*s",
chal->qop.slen, chal->qop.ptr));
return PJ_ENOTSUP;
}
return PJ_SUCCESS;
}
static void restart_req_with_auth(pj_http_req *hreq)
{
pj_http_auth_chal *chal = &hreq->response.auth_chal;
pj_http_auth_cred *cred = &hreq->param.auth_cred;
pj_status_t status;
if (hreq->param.headers.count >= PJ_HTTP_HEADER_SIZE) {
TRACE_((THIS_FILE, "Error: no place to put Authorization header"));
hreq->auth_state = AUTH_DONE;
return;
}
/* If credential specifies specific scheme, make sure they match */
if (cred->scheme.slen && pj_stricmp(&chal->scheme, &cred->scheme)) {
status = PJ_ENOTSUP;
TRACE_((THIS_FILE, "Error: auth schemes mismatch"));
goto on_error;
}
/* If credential specifies specific realm, make sure they match */
if (cred->realm.slen && pj_stricmp(&chal->realm, &cred->realm)) {
status = PJ_ENOTSUP;
TRACE_((THIS_FILE, "Error: auth realms mismatch"));
goto on_error;
}
if (!pj_stricmp2(&chal->scheme, "basic")) {
status = auth_respond_basic(hreq);
} else if (!pj_stricmp2(&chal->scheme, "digest")) {
status = auth_respond_digest(hreq);
} else {
TRACE_((THIS_FILE, "Error: unsupported HTTP auth scheme"));
status = PJ_ENOTSUP;
}
if (status != PJ_SUCCESS)
goto on_error;
http_req_end_request(hreq);
status = start_http_req(hreq, PJ_TRUE);
if (status != PJ_SUCCESS)
goto on_error;
hreq->auth_state = AUTH_RETRYING;
return;
on_error:
hreq->auth_state = AUTH_DONE;
}
/* snprintf() to a pj_str_t struct with an option to append the
* result at the back of the string.
*/
static void str_snprintf(pj_str_t *s, size_t size,
pj_bool_t append, const char *format, ...)
{
va_list arg;
int retval;
va_start(arg, format);
if (!append)
s->slen = 0;
size -= s->slen;
retval = pj_ansi_vsnprintf(s->ptr + s->slen,
size, format, arg);
s->slen += ((retval < (int)size) ? retval : size - 1);
va_end(arg);
}
static pj_status_t http_req_start_sending(pj_http_req *hreq)
{
pj_status_t status;
pj_str_t pkt;
pj_ssize_t len;
pj_size_t i;
PJ_ASSERT_RETURN(hreq->state == SENDING_REQUEST ||
hreq->state == SENDING_REQUEST_BODY, PJ_EBUG);
if (hreq->state == SENDING_REQUEST) {
/* Prepare the request data */
if (!hreq->buffer.ptr)
hreq->buffer.ptr = (char*)pj_pool_alloc(hreq->pool, BUF_SIZE);
pj_strassign(&pkt, &hreq->buffer);
pkt.slen = 0;
/* Start-line */
str_snprintf(&pkt, BUF_SIZE, PJ_TRUE, "%.*s %.*s %s/%.*s\r\n",
STR_PREC(hreq->param.method),
STR_PREC(hreq->hurl.path),
get_protocol(&hreq->hurl.protocol),
STR_PREC(hreq->param.version));
/* Header field "Host" */
str_snprintf(&pkt, BUF_SIZE, PJ_TRUE, "Host: %.*s:%d\r\n",
STR_PREC(hreq->hurl.host), hreq->hurl.port);
if (!pj_strcmp2(&hreq->param.method, http_method_names[HTTP_PUT])) {
char buf[16];
/* Header field "Content-Length" */
pj_utoa(hreq->param.reqdata.total_size ?
(unsigned long)hreq->param.reqdata.total_size:
(unsigned long)hreq->param.reqdata.size, buf);
str_snprintf(&pkt, BUF_SIZE, PJ_TRUE, "%s: %s\r\n",
CONTENT_LENGTH, buf);
}
/* Append user-specified headers */
for (i = 0; i < hreq->param.headers.count; i++) {
str_snprintf(&pkt, BUF_SIZE, PJ_TRUE, "%.*s: %.*s\r\n",
STR_PREC(hreq->param.headers.header[i].name),
STR_PREC(hreq->param.headers.header[i].value));
}
if (pkt.slen >= BUF_SIZE - 1) {
status = PJLIB_UTIL_EHTTPINSBUF;
goto on_return;
}
pj_strcat2(&pkt, "\r\n");
pkt.ptr[pkt.slen] = 0;
TRACE_((THIS_FILE, "%s", pkt.ptr));
} else {
pkt.ptr = (char*)hreq->param.reqdata.data;
pkt.slen = hreq->param.reqdata.size;
}
/* Send the request */
len = pj_strlen(&pkt);
pj_ioqueue_op_key_init(&hreq->op_key, sizeof(hreq->op_key));
hreq->tcp_state.send_size = len;
hreq->tcp_state.current_send_size = 0;
status = pj_activesock_send(hreq->asock, &hreq->op_key,
pkt.ptr, &len, 0);
if (status == PJ_SUCCESS) {
http_on_data_sent(hreq->asock, &hreq->op_key, len);
} else if (status != PJ_EPENDING) {
goto on_return; // error sending data
}
return PJ_SUCCESS;
on_return:
http_req_end_request(hreq);
return status;
}
static pj_status_t http_req_start_reading(pj_http_req *hreq)
{
pj_status_t status;
PJ_ASSERT_RETURN(hreq->state == REQUEST_SENT, PJ_EBUG);
/* Receive the response */
hreq->state = READING_RESPONSE;
hreq->tcp_state.current_read_size = 0;
pj_assert(hreq->buffer.ptr);
status = pj_activesock_start_read2(hreq->asock, hreq->pool, BUF_SIZE,
(void**)&hreq->buffer.ptr, 0);
if (status != PJ_SUCCESS) {
/* Error reading */
http_req_end_request(hreq);
return status;
}
return PJ_SUCCESS;
}
static pj_status_t http_req_end_request(pj_http_req *hreq)
{
if (hreq->asock) {
pj_activesock_close(hreq->asock);
hreq->asock = NULL;
}
/* Cancel query timeout timer. */
if (hreq->timer_entry.id != 0) {
pj_timer_heap_cancel(hreq->timer, &hreq->timer_entry);
/* Invalidate id. */
hreq->timer_entry.id = 0;
}
hreq->state = IDLE;
return PJ_SUCCESS;
}
PJ_DEF(pj_status_t) pj_http_req_cancel(pj_http_req *http_req,
pj_bool_t notify)
{
http_req->state = ABORTING;
http_req_end_request(http_req);
if (notify && http_req->cb.on_complete) {
(*http_req->cb.on_complete)(http_req, (!http_req->error?
PJ_ECANCELLED: http_req->error), NULL);
}
return PJ_SUCCESS;
}
PJ_DEF(pj_status_t) pj_http_req_destroy(pj_http_req *http_req)
{
PJ_ASSERT_RETURN(http_req, PJ_EINVAL);
/* If there is any pending request, cancel it */
if (http_req->state != IDLE) {
pj_http_req_cancel(http_req, PJ_FALSE);
}
pj_pool_release(http_req->pool);
return PJ_SUCCESS;
}
|
769819.c | /*******************************************************************************
******************************** BLUEBOTTLE ***********************************
*******************************************************************************
*
* Copyright 2012 - 2018 Adam Sierakowski and Daniel Willen,
* The Johns Hopkins University
*
* 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.
*
* Please contact the Johns Hopkins University to use Bluebottle for
* commercial and/or for-profit applications.
******************************************************************************/
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include "cgns.h"
void cgns_recorder_init(void)
{
if (rec_cgns_flow_dt > 0 || rec_cgns_part_dt > 0) {
#ifdef DDEBUG
cgns_grid_ghost();
#else
cgns_grid();
#endif // DDEBUG
}
}
void cgns_recorder_flow_write(void)
{
if (rec_cgns_flow_dt > 0) {
if (rec_cgns_flow_ttime_out >= rec_cgns_flow_dt || stepnum == 0) {
// Write
#ifdef DDEBUG
cgns_flow_field_ghost(rec_cgns_flow_dt);
#else
cgns_flow_field(rec_cgns_flow_dt);
#endif // DDEBUG
// Notify output
char fname[FILE_NAME_SIZE];
int sigfigs = ceil(log10(1. / rec_cgns_flow_dt));
if(sigfigs < 1) sigfigs = 1;
sprintf(fname, "flow-%.*f.cgns", sigfigs, ttime);
printf("N%d >> Writing %s at t = %e... done.\n", rank, fname, ttime);
// Don't want to subtract if first output
if (stepnum != 0) rec_cgns_flow_ttime_out -= rec_cgns_flow_dt;
}
}
}
void cgns_recorder_part_write(void)
{
if (rec_cgns_part_dt > 0) {
if (rec_cgns_part_ttime_out >= rec_cgns_part_dt || stepnum == 0) {
// Write
#ifdef DDEBUG
// NOTE: currently no debug output for cgns particles
cgns_particles(rec_cgns_part_dt);
#else
cgns_particles(rec_cgns_part_dt);
#endif
// Notify output
char fname[FILE_NAME_SIZE];
int sigfigs = ceil(log10(1. / rec_cgns_flow_dt));
if(sigfigs < 1) sigfigs = 1;
sprintf(fname, "part-%.*f.cgns", sigfigs, ttime);
printf("N%d >> Writing %s at t = %e... done.\n", rank, fname, ttime);
// Don't want to subtract if first output
if (stepnum != 0) rec_cgns_part_ttime_out -= rec_cgns_part_dt;
}
}
}
void cgns_grid(void)
{
printf("N%d >> Initializing CGNS grid...\n", rank);
if (rank == 0) {
// Create output directory if it doesn't exist
struct stat st = {0};
char buf[CHAR_BUF_SIZE];
sprintf(buf, "%s/%s", ROOT_DIR, OUTPUT_DIR);
if (stat(buf, &st) == -1) {
mkdir(buf, 0700);
}
}
// create the file
char fname[FILE_NAME_SIZE];
sprintf(fname, "%s/%s/%s", ROOT_DIR, OUTPUT_DIR, "grid.cgns");
int fn; // file index number
int bn; // base index number
int zn; // zone index number
int gn; // grid " "
int cx; // coord " "
int cy;
int cz;
// Set MPI communicator for CGNS
cgp_mpi_comm(MPI_COMM_WORLD);
// Open file in parallel
cgp_open(fname, CG_MODE_WRITE, &fn);
// Write base, zone
int cell_dim = 3; // volume cells
int phys_dim = 3; // # coords to define a vector
cg_base_write(fn, "Base", cell_dim, phys_dim, &bn);
cgsize_t size[9]; // number of vertices and cells
size[0] = DOM.xn + 1; // number of vertices
size[1] = DOM.yn + 1;
size[2] = DOM.zn + 1;
size[3] = DOM.xn; // number of cells
size[4] = DOM.yn;
size[5] = DOM.zn;
size[6] = 0; // 0
size[7] = 0;
size[8] = 0;
cg_zone_write(fn, bn, "Zone0", size, Structured, &zn);
// grid
cg_grid_write(fn, bn, zn, "GridCoordinates", &gn);
// create data nodes for coordinates
cgp_coord_write(fn, bn, zn, RealDouble, "CoordinateX", &cx);
cgp_coord_write(fn, bn, zn, RealDouble, "CoordinateY", &cy);
cgp_coord_write(fn, bn, zn, RealDouble, "CoordinateZ", &cz);
// number of vertices and range for current rank
int nverts = (dom[rank].xn + 1)*(dom[rank].yn + 1)*(dom[rank].zn + 1);
real *x = malloc(nverts * sizeof(real));
real *y = malloc(nverts * sizeof(real));
real *z = malloc(nverts * sizeof(real));
// find position
int s1 = dom[rank].xn + 1;
int s2 = (dom[rank].xn + 1)*(dom[rank].yn + 1);
for (int k = dom[rank].Gcc._ks; k <= (dom[rank].Gcc._ke + 1); k++) {
for (int j = dom[rank].Gcc._js; j <= (dom[rank].Gcc._je + 1); j++) {
for (int i = dom[rank].Gcc._is; i <= (dom[rank].Gcc._ie + 1); i++) {
int C = (i-1) + (j-1)*s1 + (k-1)*s2;
x[C] = dom[rank].xs + (i-1)*dom[rank].dx;
y[C] = dom[rank].ys + (j-1)*dom[rank].dy;
z[C] = dom[rank].zs + (k-1)*dom[rank].dz;
}
}
}
// start and end index for write (one-indexed)
cgsize_t nstart[3];
nstart[0] = dom[rank].Gcc.is;
nstart[1] = dom[rank].Gcc.js;
nstart[2] = dom[rank].Gcc.ks;
cgsize_t nend[3];
nend[0] = dom[rank].Gcc.ie + 1;
nend[1] = dom[rank].Gcc.je + 1;
nend[2] = dom[rank].Gcc.ke + 1;
// write the coordinate data in parallel
cgp_coord_write_data(fn, bn, zn, cx, nstart, nend, x);
cgp_coord_write_data(fn, bn, zn, cy, nstart, nend, y);
cgp_coord_write_data(fn, bn, zn, cz, nstart, nend, z);
free(x);
free(y);
free(z);
cgp_close(fn);
}
void cgns_grid_ghost(void)
{
printf("N%d >> Initializing CGNS ghost grid...\n", rank);
if (rank == 0) {
// Create output directory if it doesn't exist
struct stat st = {0};
char buf[CHAR_BUF_SIZE];
sprintf(buf, "%s/%s", ROOT_DIR, OUTPUT_DIR);
if (stat(buf, &st) == -1) {
mkdir(buf, 0700);
}
}
// create the file
char fname[FILE_NAME_SIZE];
sprintf(fname, "%s/%s/%s", ROOT_DIR, OUTPUT_DIR, "grid-ghost.cgns");
int fn; // cgns indices
int bn;
int zn;
int gn;
int cx, cy, cz;
int ierr;
// set mpi comm
cgp_mpi_comm(MPI_COMM_WORLD);
// Open file in parallel
ierr = cgp_open(fname, CG_MODE_WRITE, &fn);
if (ierr != 0) {
printf("N%d >> Line %d, ierr = %d\n", rank, __LINE__, ierr);
cgp_error_exit();
}
// Write base, zone
int cell_dim = 3; // volume cells
int phys_dim = 3; // # coords to define a vector
ierr = cg_base_write(fn, "Base", cell_dim, phys_dim, &bn);
if (ierr != 0) {
printf("N%d >> Line %d\n", rank, __LINE__);
cgp_error_exit();
}
cgsize_t size[9]; // number of vertices and cells
size[0] = DOM.Gcc.inb + 1; // number of vertices
size[1] = DOM.Gcc.jnb + 1;
size[2] = DOM.Gcc.knb + 1;
size[3] = DOM.Gcc.inb; // number of cells
size[4] = DOM.Gcc.jnb;
size[5] = DOM.Gcc.knb;
size[6] = 0; // 0
size[7] = 0;
size[8] = 0;
if (cg_zone_write(fn, bn, "Zone0", size, Structured, &zn))
cgp_error_exit();
// grid
if (cg_grid_write(fn, bn, zn, "GridCoordinates", &gn))
cgp_error_exit();
// create data nodes for coordinates
if (cgp_coord_write(fn, bn, zn, RealDouble, "CoordinateX", &cx))
cgp_error_exit();
if (cgp_coord_write(fn, bn, zn, RealDouble, "CoordinateY", &cy))
cgp_error_exit();
if (cgp_coord_write(fn, bn, zn, RealDouble, "CoordinateZ", &cz))
cgp_error_exit();
// number of vertices and range for current rank
//int nvert = (DOM.Gcc.inb + 1)*(DOM.Gcc.jnb + 1)*(DOM.Gcc.knb + 1);
int nvert = (dom[rank].Gcc.inb + 1)*(dom[rank].Gcc.jnb + 1)*(dom[rank].Gcc.knb + 1);
real *x = malloc(nvert * sizeof(real));
real *y = malloc(nvert * sizeof(real));
real *z = malloc(nvert * sizeof(real));
// find position
int s1 = dom[rank].Gcc.inb + 1;
int s2 = s1*(dom[rank].Gcc.jnb + 1);
int C;
for (int k = dom[rank].Gcc._ksb; k <= (dom[rank].Gcc._keb + 1); k++) {
for (int j = dom[rank].Gcc._jsb; j <= (dom[rank].Gcc._jeb + 1); j++) {
for (int i = dom[rank].Gcc._isb; i <= (dom[rank].Gcc._ieb + 1); i++) {
C = GCC_LOC(i, j, k, s1, s2);
x[C] = dom[rank].xs + (i-1)*dom[rank].dx;
y[C] = dom[rank].ys + (j-1)*dom[rank].dy;
z[C] = dom[rank].zs + (k-1)*dom[rank].dz;
}
}
}
// start and end index for writes (add 1 for one-indexed)
cgsize_t nstart[3];
nstart[0] = dom[rank].Gcc.isb + 1;
nstart[1] = dom[rank].Gcc.jsb + 1;
nstart[2] = dom[rank].Gcc.ksb + 1;
cgsize_t nend[3]; // +1 for 1-indexing, +1 for vertices = 2
nend[0] = dom[rank].Gcc.ieb + 1 + 1;
nend[1] = dom[rank].Gcc.jeb + 1 + 1;
nend[2] = dom[rank].Gcc.keb + 1 + 1;
// write the coordinate data in parallel
if (cgp_coord_write_data(fn, bn, zn, cx, nstart, nend, x))
cgp_error_exit();
if (cgp_coord_write_data(fn, bn, zn, cy, nstart, nend, y))
cgp_error_exit();
if (cgp_coord_write_data(fn, bn, zn, cz, nstart, nend, z))
cgp_error_exit();
free(x);
free(y);
free(z);
if (cgp_close(fn))
cgp_error_exit();
}
void cgns_flow_field(real dtout)
{
// create the solution file names
char fname[FILE_NAME_SIZE];
int sigfigs = ceil(log10(1. / dtout));
if(sigfigs < 1) sigfigs = 1;
sprintf(fname, "%s/%s/flow-%.*f.cgns", ROOT_DIR, OUTPUT_DIR, sigfigs, ttime);
char gname[FILE_NAME_SIZE];
sprintf(gname, "grid.cgns");
// cgns file indices
int fn;
int bn;
int zn;
int sn;
int fnp;
int fnu;
int fnv;
int fnw;
// set mpi comm
cgp_mpi_comm(MPI_COMM_WORLD);
// open file in parallel
cgp_open(fname, CG_MODE_WRITE, &fn);
// write base, zone
int cell_dim = 3; // volume cells
int phys_dim = 3; // # coords to define a vector
cg_base_write(fn, "Base", cell_dim, phys_dim, &bn);
cgsize_t size[9]; // number of vertices and cells
size[0] = DOM.xn + 1; // vertices
size[1] = DOM.yn + 1;
size[2] = DOM.zn + 1;
size[3] = DOM.xn; // cells
size[4] = DOM.yn;
size[5] = DOM.zn;
size[6] = 0;
size[7] = 0;
size[8] = 0;
cg_zone_write(fn, bn, "Zone0", size, Structured, &zn);
cg_goto(fn, bn, "Zone_t", zn, "end");
// check that grid.cgns exists
/*int fng;
if(cg_open(gnameall, CG_MODE_READ, &fng) != 0) {
fprintf(stderr, "CGNS flow field write failure: no grid.cgns\n");
exit(EXIT_FAILURE);
} else {
cg_close(fng);
}
cg_close(fng);
*/
// link grid.cgns
cg_link_write("GridCoordinates", gname, "Base/Zone0/GridCoordinates");
// create solution
cg_sol_write(fn, bn, zn, "Solution", CellCenter, &sn);
// start and end index for write
cgsize_t nstart[3];
nstart[0] = dom[rank].Gcc.is;
nstart[1] = dom[rank].Gcc.js;
nstart[2] = dom[rank].Gcc.ks;
cgsize_t nend[3];
nend[0] = dom[rank].Gcc.ie;
nend[1] = dom[rank].Gcc.je;
nend[2] = dom[rank].Gcc.ke;
// create and write the field data -- pressure
cgp_field_write(fn, bn, zn, sn, RealDouble, "Pressure", &fnp);
real *pout = malloc(dom[rank].Gcc.s3 * sizeof(real));
for (int k = dom[rank].Gcc._ks; k <= dom[rank].Gcc._ke; k++) {
for (int j = dom[rank].Gcc._js; j <= dom[rank].Gcc._je; j++) {
for (int i = dom[rank].Gcc._is; i <= dom[rank].Gcc._ie; i++) {
int C = GCC_LOC(i - DOM_BUF, j - DOM_BUF, k - DOM_BUF,
dom[rank].Gcc.s1, dom[rank].Gcc.s2);
int CC = GCC_LOC(i, j, k, dom[rank].Gcc.s1b, dom[rank].Gcc.s2b);
pout[C] = p[CC];
}
}
}
cgp_field_write_data(fn, bn, zn, sn, fnp, nstart, nend, pout);
free(pout);
// create and write the field data
cgp_field_write(fn, bn, zn, sn, RealDouble, "VelocityX", &fnu);
cgp_field_write(fn, bn, zn, sn, RealDouble, "VelocityY", &fnv);
cgp_field_write(fn, bn, zn, sn, RealDouble, "VelocityZ", &fnw);
real *uout = malloc(dom[rank].Gcc.s3 * sizeof(real));
real *vout = malloc(dom[rank].Gcc.s3 * sizeof(real));
real *wout = malloc(dom[rank].Gcc.s3 * sizeof(real));
for (int k = dom[rank].Gcc._ks; k <= dom[rank].Gcc._ke; k++) {
for (int j = dom[rank].Gcc._js; j <= dom[rank].Gcc._je; j++) {
for (int i = dom[rank].Gcc._is; i <= dom[rank].Gcc._ie; i++) {
int C = GCC_LOC(i - DOM_BUF, j - DOM_BUF, k - DOM_BUF,
dom[rank].Gcc.s1, dom[rank].Gcc.s2);
int Cfx_w = GFX_LOC(i - 1, j, k, dom[rank].Gfx.s1b, dom[rank].Gfx.s2b);
int Cfx = GFX_LOC(i, j, k, dom[rank].Gfx.s1b, dom[rank].Gfx.s2b);
int Cfx_e = GFX_LOC(i + 1, j, k, dom[rank].Gfx.s1b, dom[rank].Gfx.s2b);
int Cfx_ee = GFX_LOC(i + 2, j, k, dom[rank].Gfx.s1b, dom[rank].Gfx.s2b);
int Cfy_s = GFY_LOC(i, j - 1, k, dom[rank].Gfy.s1b, dom[rank].Gfy.s2b);
int Cfy = GFY_LOC(i, j, k, dom[rank].Gfy.s1b, dom[rank].Gfy.s2b);
int Cfy_n = GFY_LOC(i, j + 1, k, dom[rank].Gfy.s1b, dom[rank].Gfy.s2b);
int Cfy_nn = GFY_LOC(i, j + 2, k, dom[rank].Gfy.s1b, dom[rank].Gfy.s2b);
int Cfz_b = GFZ_LOC(i, j, k - 1, dom[rank].Gfz.s1b, dom[rank].Gfz.s2b);
int Cfz = GFZ_LOC(i, j, k, dom[rank].Gfz.s1b, dom[rank].Gfz.s2b);
int Cfz_t = GFZ_LOC(i, j, k + 1, dom[rank].Gfz.s1b, dom[rank].Gfz.s2b);
int Cfz_tt = GFZ_LOC(i, j, k + 2, dom[rank].Gfz.s1b, dom[rank].Gfz.s2b);
uout[C] = -0.0625*u[Cfx_w] + 0.5625*u[Cfx] + 0.5625*u[Cfx_e]
-0.0625*u[Cfx_ee];
vout[C] = -0.0625*v[Cfy_s] + 0.5625*v[Cfy] + 0.5625*v[Cfy_n]
-0.0625*v[Cfy_nn];
wout[C] = -0.0625*w[Cfz_b] + 0.5625*w[Cfz] + 0.5625*w[Cfz_t]
-0.0625*w[Cfz_tt];
}
}
}
cgp_field_write_data(fn, bn, zn, sn, fnu, nstart, nend, uout);
cgp_field_write_data(fn, bn, zn, sn, fnv, nstart, nend, vout);
cgp_field_write_data(fn, bn, zn, sn, fnw, nstart, nend, wout);
free(uout);
free(vout);
free(wout);
// phase
cgp_field_write(fn, bn, zn, sn, Integer, "Phase", &fnp);
int *phase_out = malloc(dom[rank].Gcc.s3 * sizeof(int));
for (int k = dom[rank].Gcc._ks; k <= dom[rank].Gcc._ke; k++) {
for (int j = dom[rank].Gcc._js; j <= dom[rank].Gcc._je; j++) {
for (int i = dom[rank].Gcc._is; i <= dom[rank].Gcc._ie; i++) {
int C = GCC_LOC(i - DOM_BUF, j - DOM_BUF, k - DOM_BUF,
dom[rank].Gcc.s1, dom[rank].Gcc.s2);
int CC = GCC_LOC(i, j, k, dom[rank].Gcc.s1b, dom[rank].Gcc.s2b);
// mask phase: -1 for fluid, 0 for particle
// This is because phase is set to the local particle index on the
// device, which includes ghost particles. When the part_struct is
// pulled to the host, we don't pull ghost particles, so the indexing
// in the part_struct changes
phase_out[C] = phase[CC] * (phase[CC] < 0);
}
}
}
cgp_field_write_data(fn, bn, zn, sn, fnp, nstart, nend, phase_out);
free(phase_out);
// phase_shell
cgp_field_write(fn, bn, zn, sn, Integer, "PhaseShell", &fnp);
int *phaseshell_out = malloc(dom[rank].Gcc.s3 * sizeof(int));
for (int k = dom[rank].Gcc._ks; k <= dom[rank].Gcc._ke; k++) {
for (int j = dom[rank].Gcc._js; j <= dom[rank].Gcc._je; j++) {
for (int i = dom[rank].Gcc._is; i <= dom[rank].Gcc._ie; i++) {
int C = GCC_LOC(i - DOM_BUF, j - DOM_BUF, k - DOM_BUF,
dom[rank].Gcc.s1, dom[rank].Gcc.s2);
int CC = GCC_LOC(i, j, k, dom[rank].Gcc.s1b, dom[rank].Gcc.s2b);
phaseshell_out[C] = phase_shell[CC];
}
}
}
cgp_field_write_data(fn, bn, zn, sn, fnp, nstart, nend, phaseshell_out);
free(phaseshell_out);
// Misc data -- scalars
cg_user_data_write("Etc");
cg_goto(fn, bn, "Zone_t", zn, "Etc", 0, "end");
int fnt, fnrho, fnnu;
cgsize_t nele = 1;
cgsize_t N[1];
N[0] = 1;
cgp_array_write("Time", RealDouble, 1, &nele, &fnt);
cgp_array_write("Density", RealDouble, 1, &nele, &fnrho);
cgp_array_write("KinematicViscosity", RealDouble, 1, &nele, &fnnu);
cgp_array_write_data(fnt, N, N, &ttime);
cgp_array_write_data(fnrho, N, N, &rho_f);
cgp_array_write_data(fnnu, N, N, &nu);
cgp_close(fn);
}
void cgns_particles(real dtout)
{
// Determine number of particles in subdomain (NOT ghost particles)
// Inherited from cuda_part_pull
// create a new communicator for particles that will write
// (cg calls are collective; i.e. all procs in communicator need to call)
int color = MPI_UNDEFINED * (nparts_subdom == 0);
int key = rank;
MPI_Comm part_comm;
MPI_Comm_split(MPI_COMM_WORLD, color, key, &part_comm);
if (NPARTS > 0 && nparts_subdom > 0) {
// create the solution file names
char fname[FILE_NAME_SIZE];
int sigfigs = ceil(log10(1. / dtout));
if(sigfigs < 1) sigfigs = 1;
sprintf(fname, "%s/%s/part-%.*f.cgns", ROOT_DIR, OUTPUT_DIR, sigfigs, ttime);
//printf("N%d >> Starting cgns output...\n", rank);
// cgns file indices
int fn;
int bn;
int zn;
int sn;
int en;
int cx;
int cy;
int cz;
int fnr;
// Set cg mpi communicator
cgp_mpi_comm(part_comm);
// open file in parallel
if (cgp_open(fname, CG_MODE_WRITE, &fn)) {
printf("N%d >> Line %d\n", rank, __LINE__);
cgp_error_exit();
}
// write base, zone
int cell_dim = 3; // volume cells
int phys_dim = 3; // # coords to define a vector
if (cg_base_write(fn, "Base", cell_dim, phys_dim, &bn)) {
printf("N%d >> Line %d\n", rank, __LINE__);
cgp_error_exit();
}
cgsize_t size[3][1];
size[0][0] = NPARTS;
size[1][0] = 0;
size[2][0] = 0;
if (cg_zone_write(fn, bn, "Zone0", size[0], Unstructured, &zn)) {
printf("N%d >> Line %d\n", rank, __LINE__);
cgp_error_exit();
}
if (cg_goto(fn, bn, "Zone_t", zn, "end")) {
cgp_error_exit();
}
// MPI_Excan destroys nparts_subdom, so make a tmp nparts that we can
// destroy
int tmp_nparts = nparts_subdom;
// Get offset in cgns file for current rank
int offset = 0;
MPI_Exscan(&tmp_nparts, &offset, 1, MPI_INT, MPI_SUM, part_comm);
// Start and ending indices for write (indexed from 1)
cgsize_t nstart[1];
cgsize_t nend[1];
nstart[0] = offset + 1;
nend[0] = offset + nparts_subdom; // + 1 - 1;
// write particle data to arrays
real *x = malloc(nparts_subdom * sizeof(real));
real *y = malloc(nparts_subdom * sizeof(real));
real *z = malloc(nparts_subdom * sizeof(real));
real *u = malloc(nparts_subdom * sizeof(real));
real *v = malloc(nparts_subdom * sizeof(real));
real *w = malloc(nparts_subdom * sizeof(real));
real *udot = malloc(nparts_subdom * sizeof(real)); // accel
real *vdot = malloc(nparts_subdom * sizeof(real));
real *wdot = malloc(nparts_subdom * sizeof(real));
real *ox = malloc(nparts_subdom * sizeof(real)); // anngular vel
real *oy = malloc(nparts_subdom * sizeof(real));
real *oz = malloc(nparts_subdom * sizeof(real));
real *oxdot = malloc(nparts_subdom * sizeof(real));
real *oydot = malloc(nparts_subdom * sizeof(real));
real *ozdot = malloc(nparts_subdom * sizeof(real));
real *Fx = malloc(nparts_subdom * sizeof(real)); // total
real *Fy = malloc(nparts_subdom * sizeof(real));
real *Fz = malloc(nparts_subdom * sizeof(real));
real *iFx = malloc(nparts_subdom * sizeof(real)); // interaction
real *iFy = malloc(nparts_subdom * sizeof(real));
real *iFz = malloc(nparts_subdom * sizeof(real));
real *hFx = malloc(nparts_subdom * sizeof(real)); // hydro
real *hFy = malloc(nparts_subdom * sizeof(real));
real *hFz = malloc(nparts_subdom * sizeof(real));
real *kFx = malloc(nparts_subdom * sizeof(real)); // hydro
real *kFy = malloc(nparts_subdom * sizeof(real));
real *kFz = malloc(nparts_subdom * sizeof(real));
real *Lx = malloc(nparts_subdom * sizeof(real)); // total
real *Ly = malloc(nparts_subdom * sizeof(real));
real *Lz = malloc(nparts_subdom * sizeof(real));
real *axx = malloc(nparts_subdom * sizeof(real));
real *axy = malloc(nparts_subdom * sizeof(real));
real *axz = malloc(nparts_subdom * sizeof(real));
real *ayx = malloc(nparts_subdom * sizeof(real));
real *ayy = malloc(nparts_subdom * sizeof(real));
real *ayz = malloc(nparts_subdom * sizeof(real));
real *azx = malloc(nparts_subdom * sizeof(real));
real *azy = malloc(nparts_subdom * sizeof(real));
real *azz = malloc(nparts_subdom * sizeof(real));
real *a = malloc(nparts_subdom * sizeof(real));
int *N = malloc(nparts_subdom * sizeof(int));
cgsize_t *conn = malloc(nparts_subdom * sizeof(cgsize_t));
real *density = malloc(nparts_subdom * sizeof(real));
real *E = malloc(nparts_subdom * sizeof(real));
real *sigma = malloc(nparts_subdom * sizeof(real));
real *coeff_fric = malloc(nparts_subdom * sizeof(real));
real *e_dry = malloc(nparts_subdom * sizeof(real));
int *order = malloc(nparts_subdom * sizeof(int));
for (int n = 0; n < nparts_subdom; n++) {
real mass = 4./3.*PI*(parts[n].rho - rho_f) *
parts[n].r * parts[n].r * parts[n].r;
x[n] = parts[n].x;
y[n] = parts[n].y;
z[n] = parts[n].z;
u[n] = parts[n].u;
v[n] = parts[n].v;
w[n] = parts[n].w;
udot[n] = parts[n].udot;
vdot[n] = parts[n].vdot;
wdot[n] = parts[n].wdot;
ox[n] = parts[n].ox;
oy[n] = parts[n].oy;
oz[n] = parts[n].oz;
oxdot[n] = parts[n].oxdot;
oydot[n] = parts[n].oydot;
ozdot[n] = parts[n].ozdot;
iFx[n] = parts[n].iFx;
iFy[n] = parts[n].iFy;
iFz[n] = parts[n].iFz;
hFx[n] = parts[n].Fx;
hFy[n] = parts[n].Fy;
hFz[n] = parts[n].Fz;
Fx[n] = parts[n].kFx + iFx[n] + hFx[n] + parts[n].aFx + mass*g.x;
Fy[n] = parts[n].kFy + iFy[n] + hFy[n] + parts[n].aFy + mass*g.y;
Fz[n] = parts[n].kFz + iFz[n] + hFz[n] + parts[n].aFz + mass*g.z;
kFx[n] = parts[n].kFx;
kFy[n] = parts[n].kFy;
kFz[n] = parts[n].kFz;
Lx[n] = parts[n].Lx;
Ly[n] = parts[n].Ly;
Lz[n] = parts[n].Lz;
axx[n] = parts[n].axx;
axy[n] = parts[n].axy;
axz[n] = parts[n].axz;
ayx[n] = parts[n].ayx;
ayy[n] = parts[n].ayy;
ayz[n] = parts[n].ayz;
azx[n] = parts[n].azx;
azy[n] = parts[n].azy;
azz[n] = parts[n].azz;
a[n] = parts[n].r;
N[n] = parts[n].N;
conn[n] = parts[n].N + 1; // because 0-indexed
density[n] = parts[n].rho;
E[n] = parts[n].E;
sigma[n] = parts[n].sigma;
coeff_fric[n] = parts[n].coeff_fric;
e_dry[n] = parts[n].e_dry;
order[n] = parts[n].order;
}
// create data nodes for coordinates
if (cgp_coord_write(fn, bn, zn, RealDouble, "CoordinateX", &cx))
cgp_error_exit();
if (cgp_coord_write(fn, bn, zn, RealDouble, "CoordinateY", &cy))
cgp_error_exit();
if (cgp_coord_write(fn, bn, zn, RealDouble, "CoordinateZ", &cz))
cgp_error_exit();
// write the coordinate data in parallel
if (cgp_coord_write_data(fn, bn, zn, cx, nstart, nend, x)) {
printf("N%d >> nstart = %zd, nend = %zd\n", rank, nstart[0], nend[0]);
printf("N%d >> Line %d\n", rank, __LINE__);
WAIT();
cgp_error_exit();
}
if (cgp_coord_write_data(fn, bn, zn, cy, nstart, nend, y))
cgp_error_exit();
if (cgp_coord_write_data(fn, bn, zn, cz, nstart, nend, z))
cgp_error_exit();
// create section for particle data
if (cgp_section_write(fn, bn, zn, "Elements", NODE, 0, NPARTS-1, 0, &en)) {
printf("N%d >> Line %d\n", rank, __LINE__);
cgp_error_exit();
}
// for some reason, this is 0-indexed
if (cgp_elements_write_data(fn, bn, zn, en, nstart[0] - 1, nend[0] - 1, conn))
cgp_error_exit();
//ier = cgp_section_write(int fn, int B, int Z, char *ElementSectionName,
// ElementType_t type, cgsize_t start, cgsize_t end, int nbndry, int *S);
//ier = cgp_elements_write_data(int fn, int B, int Z, int S, cgsize_t start,
// cgsize_t end, cgsize_t *Elements);
//
//ier = cg_section_write(int fn, int B, int Z, char *ElementSectionName,
// ElementType_t type, cgsize_t start, cgsize_t end, int nbndry,
// cgsize_t *Elements, int *S);
// create solution
if (cg_sol_write(fn, bn, zn, "Solution", Vertex, &sn))
cgp_error_exit();
// Create and write the field data
if (cgp_field_write(fn, bn, zn, sn, RealDouble, "Radius", &fnr))
cgp_error_exit();
if (cgp_field_write_data(fn, bn, zn, sn, fnr, nstart, nend, a))
cgp_error_exit();
if (cgp_field_write(fn, bn, zn, sn, Integer, "GlobalIndex", &fnr))
cgp_error_exit();
if (cgp_field_write_data(fn, bn, zn, sn, fnr, nstart, nend, N))
cgp_error_exit();
// Velocity
cgp_field_write(fn, bn, zn, sn, RealDouble, "VelocityX", &fnr);
cgp_field_write_data(fn, bn, zn, sn, fnr, nstart, nend, u);
cgp_field_write(fn, bn, zn, sn, RealDouble, "VelocityY", &fnr);
cgp_field_write_data(fn, bn, zn, sn, fnr, nstart, nend, v);
cgp_field_write(fn, bn, zn, sn, RealDouble, "VelocityZ", &fnr);
cgp_field_write_data(fn, bn, zn, sn, fnr, nstart, nend, w);
// Acceleration
cgp_field_write(fn, bn, zn, sn, RealDouble, "AccelerationX", &fnr);
cgp_field_write_data(fn, bn, zn, sn, fnr, nstart, nend, udot);
cgp_field_write(fn, bn, zn, sn, RealDouble, "AccelerationY", &fnr);
cgp_field_write_data(fn, bn, zn, sn, fnr, nstart, nend, vdot);
cgp_field_write(fn, bn, zn, sn, RealDouble, "AccelerationZ", &fnr);
cgp_field_write_data(fn, bn, zn, sn, fnr, nstart, nend, wdot);
// Angular Velocity
cgp_field_write(fn, bn, zn, sn, RealDouble, "AngularVelocityX", &fnr);
cgp_field_write_data(fn, bn, zn, sn, fnr, nstart, nend, ox);
cgp_field_write(fn, bn, zn, sn, RealDouble, "AngularVelocityY", &fnr);
cgp_field_write_data(fn, bn, zn, sn, fnr, nstart, nend, oy);
cgp_field_write(fn, bn, zn, sn, RealDouble, "AngularVelocityZ", &fnr);
cgp_field_write_data(fn, bn, zn, sn, fnr, nstart, nend, oz);
// Angular Velocity
cgp_field_write(fn, bn, zn, sn, RealDouble, "AngularVelocityXDot", &fnr);
cgp_field_write_data(fn, bn, zn, sn, fnr, nstart, nend, oxdot);
cgp_field_write(fn, bn, zn, sn, RealDouble, "AngularVelocityYDot", &fnr);
cgp_field_write_data(fn, bn, zn, sn, fnr, nstart, nend, oydot);
cgp_field_write(fn, bn, zn, sn, RealDouble, "AngularVelocityZDot", &fnr);
cgp_field_write_data(fn, bn, zn, sn, fnr, nstart, nend, ozdot);
// Total force
cgp_field_write(fn, bn, zn, sn, RealDouble, "TotalForceX", &fnr);
cgp_field_write_data(fn, bn, zn, sn, fnr, nstart, nend, Fx);
cgp_field_write(fn, bn, zn, sn, RealDouble, "TotalForceY", &fnr);
cgp_field_write_data(fn, bn, zn, sn, fnr, nstart, nend, Fy);
cgp_field_write(fn, bn, zn, sn, RealDouble, "TotalForceZ", &fnr);
cgp_field_write_data(fn, bn, zn, sn, fnr, nstart, nend, Fz);
// Interaction force
cgp_field_write(fn, bn, zn, sn, RealDouble, "InteractionForceX", &fnr);
cgp_field_write_data(fn, bn, zn, sn, fnr, nstart, nend, iFx);
cgp_field_write(fn, bn, zn, sn, RealDouble, "InteractionForceY", &fnr);
cgp_field_write_data(fn, bn, zn, sn, fnr, nstart, nend, iFy);
cgp_field_write(fn, bn, zn, sn, RealDouble, "InteractionForceZ", &fnr);
cgp_field_write_data(fn, bn, zn, sn, fnr, nstart, nend, iFz);
// Hydro force
cgp_field_write(fn, bn, zn, sn, RealDouble, "HydroForceX", &fnr);
cgp_field_write_data(fn, bn, zn, sn, fnr, nstart, nend, hFx);
cgp_field_write(fn, bn, zn, sn, RealDouble, "HydroForceY", &fnr);
cgp_field_write_data(fn, bn, zn, sn, fnr, nstart, nend, hFy);
cgp_field_write(fn, bn, zn, sn, RealDouble, "HydroForceZ", &fnr);
cgp_field_write_data(fn, bn, zn, sn, fnr, nstart, nend, hFz);
// Spring force
cgp_field_write(fn, bn, zn, sn, RealDouble, "SpringForceX", &fnr);
cgp_field_write_data(fn, bn, zn, sn, fnr, nstart, nend, kFx);
cgp_field_write(fn, bn, zn, sn, RealDouble, "SpringForceY", &fnr);
cgp_field_write_data(fn, bn, zn, sn, fnr, nstart, nend, kFy);
cgp_field_write(fn, bn, zn, sn, RealDouble, "SpringForceZ", &fnr);
cgp_field_write_data(fn, bn, zn, sn, fnr, nstart, nend, kFz);
// Moment
cgp_field_write(fn, bn, zn, sn, RealDouble, "MomentX", &fnr);
cgp_field_write_data(fn, bn, zn, sn, fnr, nstart, nend, Lx);
cgp_field_write(fn, bn, zn, sn, RealDouble, "MomentY", &fnr);
cgp_field_write_data(fn, bn, zn, sn, fnr, nstart, nend, Ly);
cgp_field_write(fn, bn, zn, sn, RealDouble, "MomentZ", &fnr);
cgp_field_write_data(fn, bn, zn, sn, fnr, nstart, nend, Lz);
cgp_field_write(fn, bn, zn, sn, RealDouble, "Density", &fnr);
cgp_field_write_data(fn, bn, zn, sn, fnr, nstart, nend, density);
cgp_field_write(fn, bn, zn, sn, RealDouble, "YoungsModulus", &fnr);
cgp_field_write_data(fn, bn, zn, sn, fnr, nstart, nend, E);
cgp_field_write(fn, bn, zn, sn, RealDouble, "PoissonRatio", &fnr);
cgp_field_write_data(fn, bn, zn, sn, fnr, nstart, nend, sigma);
cgp_field_write(fn, bn, zn, sn, RealDouble, "DryCoeffRest", &fnr);
cgp_field_write_data(fn, bn, zn, sn, fnr, nstart, nend, e_dry);
cgp_field_write(fn, bn, zn, sn, RealDouble, "FricCoeff", &fnr);
cgp_field_write_data(fn, bn, zn, sn, fnr, nstart, nend, coeff_fric);
cgp_field_write(fn, bn, zn, sn, Integer, "LambOrder", &fnr);
cgp_field_write_data(fn, bn, zn, sn, fnr, nstart, nend, order);
// Miscellaneous data - scalars, time
cgsize_t nele[1];
nele[0] = 1;
if (cg_user_data_write("Etc"))
cgp_error_exit();
if (cg_goto(fn, bn, "Zone_t", zn, "Etc", 0, "end"))
cgp_error_exit();
if (cgp_array_write("Time", RealDouble, 1, nele, &fnr))
cgp_error_exit();
if (cgp_array_write_data(fnr, nele, nele, &ttime))
cgp_error_exit();
// close and free
if (cgp_close(fn))
cgp_error_exit();
free(x);
free(y);
free(z);
free(u);
free(v);
free(w);
free(udot);
free(vdot);
free(wdot);
free(ox);
free(oy);
free(oz);
free(oxdot);
free(oydot);
free(ozdot);
free(Fx);
free(Fy);
free(Fz);
free(iFx);
free(iFy);
free(iFz);
free(hFx);
free(hFy);
free(hFz);
free(kFx);
free(kFy);
free(kFz);
free(Lx);
free(Ly);
free(Lz);
free(axx);
free(axy);
free(axz);
free(ayx);
free(ayy);
free(ayz);
free(azx);
free(azy);
free(azz);
free(a);
free(N);
free(conn);
free(density);
free(E);
free(sigma);
free(coeff_fric);
free(e_dry);
free(order);
}
// Only free communicator on proc's that have it -- procs not in the
// communicator are returned MPI_COMM_NULL; freeing a null is disallowed in 1.1
if (nparts_subdom > 0) {
MPI_Comm_free(&part_comm);
}
}
void cgns_flow_field_ghost(real dtout)
{
// create the solution file names
char fname[FILE_NAME_SIZE];
int sigfigs = ceil(log10(1. / dtout));
if(sigfigs < 1) sigfigs = 1;
sprintf(fname, "%s/%s/flow-ghost-%.*f.cgns", ROOT_DIR, OUTPUT_DIR, sigfigs, ttime);
char gname[FILE_NAME_SIZE];
sprintf(gname, "grid-ghost.cgns");
// cgns file indices
int fn;
int bn;
int zn;
int sn;
int fnp;
int fnphi;
int fnu;
int fnv;
int fnw;
int fnu_star;
int fnv_star;
int fnw_star;
int fnu_conv;
int fnv_conv;
int fnw_conv;
int fnu_diff;
int fnv_diff;
int fnw_diff;
cgp_mpi_comm(MPI_COMM_WORLD);
// open file in parallel
if (cgp_open(fname, CG_MODE_WRITE, &fn))
cgp_error_exit();
// write base, zone
int cell_dim = 3; // volume cells
int phys_dim = 3; // # coords to define a vector
if (cg_base_write(fn, "Base", cell_dim, phys_dim, &bn))
cgp_error_exit();
cgsize_t size[9]; // number of vertices and cells
size[0] = DOM.Gcc.inb + 1; // vertices
size[1] = DOM.Gcc.jnb + 1;
size[2] = DOM.Gcc.knb + 1;
size[3] = DOM.Gcc.inb; // cells
size[4] = DOM.Gcc.jnb;
size[5] = DOM.Gcc.knb;
size[6] = 0;
size[7] = 0;
size[8] = 0;
if (cg_zone_write(fn, bn, "Zone0", size, Structured, &zn))
cgp_error_exit();
if (cg_goto(fn, bn, "Zone_t", zn, "end"))
cgp_error_exit();
// check that grid.cgns exists
/*int fng;
if(cg_open(gnameall, CG_MODE_READ, &fng) != 0) {
fprintf(stderr, "CGNS flow field write failure: no grid.cgns\n");
exit(EXIT_FAILURE);
} else {
cg_close(fng);
}
cg_close(fng);
*/
// link grid.cgns
if (cg_link_write("GridCoordinates", gname, "Base/Zone0/GridCoordinates"))
cgp_error_exit();
// create solution
if (cg_sol_write(fn, bn, zn, "Solution", CellCenter, &sn))
cgp_error_exit();
// start and end index for write (+1 for 1 indexing)
cgsize_t nstart[3];
nstart[0] = dom[rank].Gcc.isb + 1;
nstart[1] = dom[rank].Gcc.jsb + 1;
nstart[2] = dom[rank].Gcc.ksb + 1;
cgsize_t nend[3];
nend[0] = dom[rank].Gcc.ieb + 1;
nend[1] = dom[rank].Gcc.jeb + 1;
nend[2] = dom[rank].Gcc.keb + 1;
// create and write the field data -- pressure
if (cgp_field_write(fn, bn, zn, sn, RealDouble, "Pressure", &fnp))
cgp_error_exit();
if (cgp_field_write_data(fn, bn, zn, sn, fnp, nstart, nend, p))
cgp_error_exit();
// phi
if (cgp_field_write(fn, bn, zn, sn, RealDouble, "Phi", &fnphi))
cgp_error_exit();
if (cgp_field_write_data(fn, bn, zn, sn, fnphi, nstart, nend, phi))
cgp_error_exit();
/* We can't use four centered points to interpolate the velocities in the
* ghost cells, so use two points.
* WARNING: This is lower accuracy!!
*/
real *uout = malloc(dom[rank].Gcc.s3b * sizeof(real));
real *vout = malloc(dom[rank].Gcc.s3b * sizeof(real));
real *wout = malloc(dom[rank].Gcc.s3b * sizeof(real));
// create and write the velocity fields
if (cgp_field_write(fn, bn, zn, sn, RealDouble, "VelocityX", &fnu))
cgp_error_exit();
if (cgp_field_write(fn, bn, zn, sn, RealDouble, "VelocityY", &fnv))
cgp_error_exit();
if (cgp_field_write(fn, bn, zn, sn, RealDouble, "VelocityZ", &fnw))
cgp_error_exit();
for (int k = dom[rank].Gcc._ksb; k <= dom[rank].Gcc._keb; k++) {
for (int j = dom[rank].Gcc._jsb; j <= dom[rank].Gcc._jeb; j++) {
for (int i = dom[rank].Gcc._isb; i <= dom[rank].Gcc._ieb; i++) {
int C = GCC_LOC(i, j, k, dom[rank].Gcc.s1b, dom[rank].Gcc.s2b);
int Cfx = GFX_LOC(i, j, k, dom[rank].Gfx.s1b, dom[rank].Gfx.s2b);
int Cfx_e = GFX_LOC(i + 1, j, k, dom[rank].Gfx.s1b, dom[rank].Gfx.s2b);
int Cfy = GFY_LOC(i, j, k, dom[rank].Gfy.s1b, dom[rank].Gfy.s2b);
int Cfy_n = GFY_LOC(i, j + 1, k, dom[rank].Gfy.s1b, dom[rank].Gfy.s2b);
int Cfz = GFZ_LOC(i, j, k, dom[rank].Gfz.s1b, dom[rank].Gfz.s2b);
int Cfz_t = GFZ_LOC(i, j, k + 1, dom[rank].Gfz.s1b, dom[rank].Gfz.s2b);
uout[C] = 0.5 * (u[Cfx] + u[Cfx_e]);
vout[C] = 0.5 * (v[Cfy] + v[Cfy_n]);
wout[C] = 0.5 * (w[Cfz] + w[Cfz_t]);
}
}
}
if (cgp_field_write_data(fn, bn, zn, sn, fnu, nstart, nend, uout))
cgp_error_exit();
if (cgp_field_write_data(fn, bn, zn, sn, fnv, nstart, nend, vout))
cgp_error_exit();
if (cgp_field_write_data(fn, bn, zn, sn, fnw, nstart, nend, wout))
cgp_error_exit();
// create and write the velocity star fields
if (cgp_field_write(fn, bn, zn, sn, RealDouble, "UStar", &fnu_star))
cgp_error_exit();
if (cgp_field_write(fn, bn, zn, sn, RealDouble, "VStar", &fnv_star))
cgp_error_exit();
if (cgp_field_write(fn, bn, zn, sn, RealDouble, "WStar", &fnw_star))
cgp_error_exit();
for (int k = dom[rank].Gcc._ksb; k <= dom[rank].Gcc._keb; k++) {
for (int j = dom[rank].Gcc._jsb; j <= dom[rank].Gcc._jeb; j++) {
for (int i = dom[rank].Gcc._isb; i <= dom[rank].Gcc._ieb; i++) {
int C = GCC_LOC(i, j, k, dom[rank].Gcc.s1b, dom[rank].Gcc.s2b);
int Cfx = GFX_LOC(i, j, k, dom[rank].Gfx.s1b, dom[rank].Gfx.s2b);
int Cfx_e = GFX_LOC(i + 1, j, k, dom[rank].Gfx.s1b, dom[rank].Gfx.s2b);
int Cfy = GFY_LOC(i, j, k, dom[rank].Gfy.s1b, dom[rank].Gfy.s2b);
int Cfy_n = GFY_LOC(i, j + 1, k, dom[rank].Gfy.s1b, dom[rank].Gfy.s2b);
int Cfz = GFZ_LOC(i, j, k, dom[rank].Gfz.s1b, dom[rank].Gfz.s2b);
int Cfz_t = GFZ_LOC(i, j, k + 1, dom[rank].Gfz.s1b, dom[rank].Gfz.s2b);
uout[C] = 0.5 * (u_star[Cfx] + u_star[Cfx_e]);
vout[C] = 0.5 * (v_star[Cfy] + v_star[Cfy_n]);
wout[C] = 0.5 * (w_star[Cfz] + w_star[Cfz_t]);
}
}
}
if (cgp_field_write_data(fn, bn, zn, sn, fnu_star, nstart, nend, uout))
cgp_error_exit();
if (cgp_field_write_data(fn, bn, zn, sn, fnv_star, nstart, nend, vout))
cgp_error_exit();
if (cgp_field_write_data(fn, bn, zn, sn, fnw_star, nstart, nend, wout))
cgp_error_exit();
// create and write the convective term fields
if (cgp_field_write(fn, bn, zn, sn, RealDouble, "UConv", &fnu_conv))
cgp_error_exit();
if (cgp_field_write(fn, bn, zn, sn, RealDouble, "VConv", &fnv_conv))
cgp_error_exit();
if (cgp_field_write(fn, bn, zn, sn, RealDouble, "WConv", &fnw_conv))
cgp_error_exit();
for (int k = dom[rank].Gcc._ksb; k <= dom[rank].Gcc._keb; k++) {
for (int j = dom[rank].Gcc._jsb; j <= dom[rank].Gcc._jeb; j++) {
for (int i = dom[rank].Gcc._isb; i <= dom[rank].Gcc._ieb; i++) {
int C = GCC_LOC(i, j, k, dom[rank].Gcc.s1b, dom[rank].Gcc.s2b);
int Cfx = GFX_LOC(i, j, k, dom[rank].Gfx.s1b, dom[rank].Gfx.s2b);
int Cfx_e = GFX_LOC(i + 1, j, k, dom[rank].Gfx.s1b, dom[rank].Gfx.s2b);
int Cfy = GFY_LOC(i, j, k, dom[rank].Gfy.s1b, dom[rank].Gfy.s2b);
int Cfy_n = GFY_LOC(i, j + 1, k, dom[rank].Gfy.s1b, dom[rank].Gfy.s2b);
int Cfz = GFZ_LOC(i, j, k, dom[rank].Gfz.s1b, dom[rank].Gfz.s2b);
int Cfz_t = GFZ_LOC(i, j, k + 1, dom[rank].Gfz.s1b, dom[rank].Gfz.s2b);
uout[C] = 0.5 * (conv_u[Cfx] + conv_u[Cfx_e]);
vout[C] = 0.5 * (conv_v[Cfy] + conv_v[Cfy_n]);
wout[C] = 0.5 * (conv_w[Cfz] + conv_w[Cfz_t]);
}
}
}
if (cgp_field_write_data(fn, bn, zn, sn, fnu_conv, nstart, nend, uout))
cgp_error_exit();
if (cgp_field_write_data(fn, bn, zn, sn, fnv_conv, nstart, nend, vout))
cgp_error_exit();
if (cgp_field_write_data(fn, bn, zn, sn, fnw_conv, nstart, nend, wout))
cgp_error_exit();
// create and write the diffusive term fields
if (cgp_field_write(fn, bn, zn, sn, RealDouble, "UDiff", &fnu_diff))
cgp_error_exit();
if (cgp_field_write(fn, bn, zn, sn, RealDouble, "VDiff", &fnv_diff))
cgp_error_exit();
if (cgp_field_write(fn, bn, zn, sn, RealDouble, "WDiff", &fnw_diff))
cgp_error_exit();
for (int k = dom[rank].Gcc._ksb; k <= dom[rank].Gcc._keb; k++) {
for (int j = dom[rank].Gcc._jsb; j <= dom[rank].Gcc._jeb; j++) {
for (int i = dom[rank].Gcc._isb; i <= dom[rank].Gcc._ieb; i++) {
int C = GCC_LOC(i, j, k, dom[rank].Gcc.s1b, dom[rank].Gcc.s2b);
int Cfx = GFX_LOC(i, j, k, dom[rank].Gfx.s1b, dom[rank].Gfx.s2b);
int Cfx_e = GFX_LOC(i + 1, j, k, dom[rank].Gfx.s1b, dom[rank].Gfx.s2b);
int Cfy = GFY_LOC(i, j, k, dom[rank].Gfy.s1b, dom[rank].Gfy.s2b);
int Cfy_n = GFY_LOC(i, j + 1, k, dom[rank].Gfy.s1b, dom[rank].Gfy.s2b);
int Cfz = GFZ_LOC(i, j, k, dom[rank].Gfz.s1b, dom[rank].Gfz.s2b);
int Cfz_t = GFZ_LOC(i, j, k + 1, dom[rank].Gfz.s1b, dom[rank].Gfz.s2b);
uout[C] = 0.5 * (diff_u[Cfx] + diff_u[Cfx_e]);
vout[C] = 0.5 * (diff_v[Cfy] + diff_v[Cfy_n]);
wout[C] = 0.5 * (diff_w[Cfz] + diff_w[Cfz_t]);
}
}
}
if (cgp_field_write_data(fn, bn, zn, sn, fnu_diff, nstart, nend, uout))
cgp_error_exit();
if (cgp_field_write_data(fn, bn, zn, sn, fnv_diff, nstart, nend, vout))
cgp_error_exit();
if (cgp_field_write_data(fn, bn, zn, sn, fnw_diff, nstart, nend, wout))
cgp_error_exit();
free(uout);
free(vout);
free(wout);
// phase, phase_shell
cgp_field_write(fn, bn, zn, sn, Integer, "Phase", &fnp);
cgp_field_write_data(fn, bn, zn, sn, fnp, nstart, nend, phase);
cgp_field_write(fn, bn, zn, sn, Integer, "PhaseShell", &fnp);
cgp_field_write_data(fn, bn, zn, sn, fnp, nstart, nend, phase);
// Misc data -- scalars
cg_user_data_write("Etc");
cg_goto(fn, bn, "Zone_t", zn, "Etc", 0, "end");
int fnt, fnrho, fnnu;
cgsize_t nele = 1;
cgsize_t N[1];
N[0] = 1;
cgp_array_write("Time", RealDouble, 1, &nele, &fnt);
cgp_array_write("Density", RealDouble, 1, &nele, &fnrho);
cgp_array_write("KinematicViscosity", RealDouble, 1, &nele, &fnnu);
cgp_array_write_data(fnt, N, N, &ttime);
cgp_array_write_data(fnrho, N, N, &rho_f);
cgp_array_write_data(fnnu, N, N, &nu);
if (cgp_close(fn))
cgp_error_exit();
}
|
586209.c | /*
* nginx-statsd module
* Copyright (C) 2012 Zebrafish Labs Inc.
*
* Much of this source code was derived from nginx-udplog-module which
* has the following copyright. Please refer to the LICENSE file for
* details.
*
* Copyright (C) 2010 Valery Kholodkov
*/
#include <ngx_config.h>
#include <ngx_core.h>
#include <ngx_http.h>
#include <nginx.h>
#define STATSD_DEFAULT_PORT 8125
#define STATSD_TYPE_COUNTER 0x0001
#define STATSD_TYPE_TIMING 0x0002
#define STATSD_MAX_STR 256
#define ngx_conf_merge_ptr_value(conf, prev, default) \
if (conf == NGX_CONF_UNSET_PTR) { \
conf = (prev == NGX_CONF_UNSET_PTR) ? default : prev; \
}
#if defined nginx_version && nginx_version >= 8021
typedef ngx_addr_t ngx_statsd_addr_t;
#else
typedef ngx_peer_addr_t ngx_statsd_addr_t;
#endif
typedef struct {
ngx_statsd_addr_t peer_addr;
ngx_resolver_connection_t *udp_connection;
ngx_log_t *log;
} ngx_udp_endpoint_t;
typedef struct {
ngx_array_t *endpoints;
} ngx_http_statsd_main_conf_t;
typedef struct {
ngx_uint_t type;
ngx_str_t key;
ngx_uint_t metric;
ngx_flag_t valid;
ngx_http_complex_value_t *ckey;
ngx_http_complex_value_t *cmetric;
ngx_http_complex_value_t *cvalid;
} ngx_statsd_stat_t;
typedef struct {
int off;
ngx_udp_endpoint_t *endpoint;
ngx_uint_t sample_rate;
ngx_array_t *stats;
} ngx_http_statsd_conf_t;
ngx_int_t ngx_udp_connect(ngx_resolver_connection_t *rec);
static void ngx_statsd_updater_cleanup(void *data);
static ngx_int_t ngx_http_statsd_udp_send(ngx_udp_endpoint_t *l, u_char *buf, size_t len);
static void *ngx_http_statsd_create_main_conf(ngx_conf_t *cf);
static void *ngx_http_statsd_create_loc_conf(ngx_conf_t *cf);
static char *ngx_http_statsd_merge_loc_conf(ngx_conf_t *cf, void *parent,
void *child);
static char *ngx_http_statsd_set_server(ngx_conf_t *cf, ngx_command_t *cmd, void *conf);
static char *ngx_http_statsd_add_stat(ngx_conf_t *cf, ngx_command_t *cmd, void *conf, ngx_uint_t type);
static char *ngx_http_statsd_add_count(ngx_conf_t *cf, ngx_command_t *cmd, void *conf);
static char *ngx_http_statsd_add_timing(ngx_conf_t *cf, ngx_command_t *cmd, void *conf);
static ngx_str_t ngx_http_statsd_key_get_value(ngx_http_request_t *r, ngx_http_complex_value_t *cv, ngx_str_t v);
static ngx_str_t ngx_http_statsd_key_value(ngx_str_t *str);
static ngx_uint_t ngx_http_statsd_metric_get_value(ngx_http_request_t *r, ngx_http_complex_value_t *cv, ngx_uint_t v);
static ngx_uint_t ngx_http_statsd_metric_value(ngx_str_t *str);
static ngx_flag_t ngx_http_statsd_valid_get_value(ngx_http_request_t *r, ngx_http_complex_value_t *cv, ngx_flag_t v);
static ngx_flag_t ngx_http_statsd_valid_value(ngx_str_t *str);
uintptr_t ngx_escape_statsd_key(u_char *dst, u_char *src, size_t size);
static ngx_int_t ngx_http_statsd_init(ngx_conf_t *cf);
static ngx_command_t ngx_http_statsd_commands[] = {
{ ngx_string("statsd_server"),
NGX_HTTP_MAIN_CONF|NGX_HTTP_SRV_CONF|NGX_HTTP_LOC_CONF|NGX_CONF_TAKE12,
ngx_http_statsd_set_server,
NGX_HTTP_LOC_CONF_OFFSET,
0,
NULL },
{ ngx_string("statsd_sample_rate"),
NGX_HTTP_MAIN_CONF|NGX_HTTP_SRV_CONF|NGX_HTTP_LOC_CONF|NGX_CONF_TAKE1,
ngx_conf_set_num_slot,
NGX_HTTP_LOC_CONF_OFFSET,
offsetof(ngx_http_statsd_conf_t, sample_rate),
NULL },
{ ngx_string("statsd_count"),
NGX_HTTP_SRV_CONF|NGX_HTTP_SIF_CONF|NGX_HTTP_LOC_CONF|NGX_HTTP_LIF_CONF|NGX_CONF_TAKE23,
ngx_http_statsd_add_count,
NGX_HTTP_LOC_CONF_OFFSET,
0,
NULL },
{ ngx_string("statsd_timing"),
NGX_HTTP_SRV_CONF|NGX_HTTP_SIF_CONF|NGX_HTTP_LOC_CONF|NGX_HTTP_LIF_CONF|NGX_CONF_TAKE23,
ngx_http_statsd_add_timing,
NGX_HTTP_LOC_CONF_OFFSET,
0,
NULL },
ngx_null_command
};
static ngx_http_module_t ngx_http_statsd_module_ctx = {
NULL, /* preconfiguration */
ngx_http_statsd_init, /* postconfiguration */
ngx_http_statsd_create_main_conf, /* create main configuration */
NULL, /* init main configuration */
NULL, /* create server configuration */
NULL, /* merge server configuration */
ngx_http_statsd_create_loc_conf, /* create location configration */
ngx_http_statsd_merge_loc_conf /* merge location configration */
};
ngx_module_t ngx_http_statsd_module = {
NGX_MODULE_V1,
&ngx_http_statsd_module_ctx, /* module context */
ngx_http_statsd_commands, /* module directives */
NGX_HTTP_MODULE, /* module type */
NULL, /* init master */
NULL, /* init module */
NULL, /* init process */
NULL, /* init thread */
NULL, /* exit thread */
NULL, /* exit process */
NULL, /* exit master */
NGX_MODULE_V1_PADDING
};
static ngx_str_t
ngx_http_statsd_key_get_value(ngx_http_request_t *r, ngx_http_complex_value_t *cv, ngx_str_t v)
{
ngx_str_t val;
if (cv == NULL) {
return v;
}
if (ngx_http_complex_value(r, cv, &val) != NGX_OK) {
return (ngx_str_t) ngx_null_string;
};
return ngx_http_statsd_key_value(&val);
};
static ngx_str_t
ngx_http_statsd_key_value(ngx_str_t *value)
{
return *value;
};
static ngx_uint_t
ngx_http_statsd_metric_get_value(ngx_http_request_t *r, ngx_http_complex_value_t *cv, ngx_uint_t v)
{
ngx_str_t val;
if (cv == NULL) {
return v;
}
if (ngx_http_complex_value(r, cv, &val) != NGX_OK) {
return 0;
};
return ngx_http_statsd_metric_value(&val);
};
static ngx_uint_t
ngx_http_statsd_metric_value(ngx_str_t *value)
{
ngx_int_t n, m;
if (value->len == 1 && value->data[0] == '-') {
return (ngx_uint_t) -1;
};
/* Hack to convert milliseconds to a number. */
if (value->len > 4 && value->data[value->len - 4] == '.') {
n = ngx_atoi(value->data, value->len - 4);
m = ngx_atoi(value->data + (value->len - 3), 3);
return (ngx_uint_t) ((n * 1000) + m);
} else {
n = ngx_atoi(value->data, value->len);
if (n > 0) {
return (ngx_uint_t) n;
};
};
return 0;
};
static ngx_flag_t
ngx_http_statsd_valid_get_value(ngx_http_request_t *r, ngx_http_complex_value_t *cv, ngx_flag_t v)
{
ngx_str_t val;
if (cv == NULL) {
return v;
}
if (ngx_http_complex_value(r, cv, &val) != NGX_OK) {
return 0;
};
return ngx_http_statsd_valid_value(&val);
};
static ngx_flag_t
ngx_http_statsd_valid_value(ngx_str_t *value)
{
return (ngx_flag_t) (value->len > 0 ? 1 : 0);
};
ngx_int_t
ngx_http_statsd_handler(ngx_http_request_t *r)
{
u_char line[STATSD_MAX_STR], *p;
const char * metric_type;
ngx_http_statsd_conf_t *ulcf;
ngx_statsd_stat_t *stats;
ngx_statsd_stat_t stat;
ngx_uint_t c;
ngx_uint_t n;
ngx_str_t s;
ngx_flag_t b;
ngx_log_debug0(NGX_LOG_DEBUG_HTTP, r->connection->log, 0,
"http statsd handler");
ulcf = ngx_http_get_module_loc_conf(r, ngx_http_statsd_module);
if (ulcf->off == 1 || ulcf->endpoint == NULL) {
ngx_log_debug0(NGX_LOG_DEBUG_HTTP, r->connection->log, 0, "statsd: handler off");
return NGX_OK;
}
// Use a random distribution to sample at sample rate.
if (ulcf->sample_rate < 100 && (uint) (ngx_random() % 100) >= ulcf->sample_rate) {
ngx_log_debug0(NGX_LOG_DEBUG_HTTP, r->connection->log, 0, "statsd: skipping sample");
return NGX_OK;
}
stats = ulcf->stats->elts;
for (c = 0; c < ulcf->stats->nelts; c++) {
stat = stats[c];
s = ngx_http_statsd_key_get_value(r, stat.ckey, stat.key);
ngx_escape_statsd_key(s.data, s.data, s.len);
n = ngx_http_statsd_metric_get_value(r, stat.cmetric, stat.metric);
b = ngx_http_statsd_valid_get_value(r, stat.cvalid, stat.valid);
if (b == 0 || s.len == 0 || n <= 0) {
// Do not log if not valid, key is invalid, or valud is lte 0.
ngx_log_debug0(NGX_LOG_DEBUG_HTTP, r->connection->log, 0, "statsd: no value to send");
continue;
};
if (stat.type == STATSD_TYPE_COUNTER) {
metric_type = "c";
} else if (stat.type == STATSD_TYPE_TIMING) {
metric_type = "ms";
} else {
metric_type = NULL;
}
if (metric_type) {
if (ulcf->sample_rate < 100) {
p = ngx_snprintf(line, STATSD_MAX_STR, "%V:%d|%s|@0.%02d", &s, n, metric_type, ulcf->sample_rate);
} else {
p = ngx_snprintf(line, STATSD_MAX_STR, "%V:%d|%s", &s, n, metric_type);
}
ngx_http_statsd_udp_send(ulcf->endpoint, line, p - line);
}
}
return NGX_OK;
}
static ngx_int_t ngx_statsd_init_endpoint(ngx_conf_t *cf, ngx_udp_endpoint_t *endpoint) {
ngx_pool_cleanup_t *cln;
ngx_resolver_connection_t *rec;
ngx_log_debug0(NGX_LOG_DEBUG_HTTP, cf->log, 0,
"statsd: initting endpoint");
cln = ngx_pool_cleanup_add(cf->pool, 0);
if(cln == NULL) {
return NGX_ERROR;
}
cln->handler = ngx_statsd_updater_cleanup;
cln->data = endpoint;
rec = ngx_calloc(sizeof(ngx_resolver_connection_t), cf->log);
if (rec == NULL) {
return NGX_ERROR;
}
endpoint->udp_connection = rec;
rec->sockaddr = endpoint->peer_addr.sockaddr;
rec->socklen = endpoint->peer_addr.socklen;
rec->server = endpoint->peer_addr.name;
endpoint->log = &cf->cycle->new_log;
return NGX_OK;
}
static void
ngx_statsd_updater_cleanup(void *data)
{
ngx_udp_endpoint_t *e = data;
ngx_log_debug0(NGX_LOG_DEBUG_CORE, ngx_cycle->log, 0,
"cleanup statsd_updater");
if(e->udp_connection) {
if(e->udp_connection->udp) {
ngx_close_connection(e->udp_connection->udp);
}
ngx_free(e->udp_connection);
}
}
static void ngx_http_statsd_udp_dummy_handler(ngx_event_t *ev)
{
}
static ngx_int_t
ngx_http_statsd_udp_send(ngx_udp_endpoint_t *l, u_char *buf, size_t len)
{
ssize_t n;
ngx_resolver_connection_t *rec;
rec = l->udp_connection;
if (rec->udp == NULL) {
rec->log = *l->log;
rec->log.handler = NULL;
rec->log.data = NULL;
rec->log.action = "logging";
if(ngx_udp_connect(rec) != NGX_OK) {
if(rec->udp != NULL) {
ngx_free_connection(rec->udp);
rec->udp = NULL;
}
return NGX_ERROR;
}
rec->udp->data = l;
rec->udp->read->handler = ngx_http_statsd_udp_dummy_handler;
rec->udp->read->resolver = 0;
}
n = ngx_send(rec->udp, buf, len);
if (n == -1) {
return NGX_ERROR;
}
if ((size_t) n != (size_t) len) {
#if defined nginx_version && nginx_version >= 8032
ngx_log_error(NGX_LOG_CRIT, &rec->log, 0, "send() incomplete");
#else
ngx_log_error(NGX_LOG_CRIT, rec->log, 0, "send() incomplete");
#endif
return NGX_ERROR;
}
return NGX_OK;
}
static void *
ngx_http_statsd_create_main_conf(ngx_conf_t *cf)
{
ngx_http_statsd_main_conf_t *conf;
conf = ngx_pcalloc(cf->pool, sizeof(ngx_http_statsd_main_conf_t));
if (conf == NULL) {
return NGX_CONF_ERROR;
}
return conf;
}
static void *
ngx_http_statsd_create_loc_conf(ngx_conf_t *cf)
{
ngx_http_statsd_conf_t *conf;
conf = ngx_pcalloc(cf->pool, sizeof(ngx_http_statsd_conf_t));
if (conf == NULL) {
return NGX_CONF_ERROR;
}
conf->endpoint = NGX_CONF_UNSET_PTR;
conf->off = NGX_CONF_UNSET;
conf->sample_rate = NGX_CONF_UNSET_UINT;
conf->stats = NULL;
return conf;
}
static char *
ngx_http_statsd_merge_loc_conf(ngx_conf_t *cf, void *parent, void *child)
{
ngx_http_statsd_conf_t *prev = parent;
ngx_http_statsd_conf_t *conf = child;
ngx_statsd_stat_t *stat;
ngx_statsd_stat_t prev_stat;
ngx_statsd_stat_t *prev_stats;
ngx_uint_t i;
ngx_uint_t sz;
ngx_conf_merge_ptr_value(conf->endpoint, prev->endpoint, NULL);
ngx_conf_merge_off_value(conf->off, prev->off, 1);
ngx_conf_merge_uint_value(conf->sample_rate, prev->sample_rate, 100);
if (conf->stats == NULL) {
sz = (prev->stats != NULL ? prev->stats->nelts : 2);
conf->stats = ngx_array_create(cf->pool, sz, sizeof(ngx_statsd_stat_t));
if (conf->stats == NULL) {
return NGX_CONF_ERROR;
}
}
if (prev->stats != NULL) {
prev_stats = prev->stats->elts;
for (i = 0; i < prev->stats->nelts; i++) {
stat = ngx_array_push(conf->stats);
ngx_memzero(stat, sizeof(ngx_statsd_stat_t));
prev_stat = prev_stats[i];
stat->type = prev_stat.type;
stat->key = prev_stat.key;
stat->metric = prev_stat.metric;
stat->ckey = prev_stat.ckey;
stat->cmetric = prev_stat.cmetric;
stat->valid = prev_stat.valid;
stat->cvalid = prev_stat.cvalid;
};
};
return NGX_CONF_OK;
}
static ngx_udp_endpoint_t *
ngx_http_statsd_add_endpoint(ngx_conf_t *cf, ngx_statsd_addr_t *peer_addr)
{
ngx_http_statsd_main_conf_t *umcf;
ngx_udp_endpoint_t *endpoint;
umcf = ngx_http_conf_get_module_main_conf(cf, ngx_http_statsd_module);
if(umcf->endpoints == NULL) {
umcf->endpoints = ngx_array_create(cf->pool, 2, sizeof(ngx_udp_endpoint_t));
if (umcf->endpoints == NULL) {
return NULL;
}
}
endpoint = ngx_array_push(umcf->endpoints);
if (endpoint == NULL) {
return NULL;
}
endpoint->peer_addr = *peer_addr;
return endpoint;
}
static char *
ngx_http_statsd_set_server(ngx_conf_t *cf, ngx_command_t *cmd, void *conf)
{
ngx_http_statsd_conf_t *ulcf = conf;
ngx_str_t *value;
ngx_url_t u;
value = cf->args->elts;
if (ngx_strcmp(value[1].data, "off") == 0) {
ulcf->off = 1;
return NGX_CONF_OK;
}
int statsd_port_override = STATSD_DEFAULT_PORT;
if (value[2].len <= 0) {
statsd_port_override = ngx_atoi(value[2].data, value[2].len);
}
else if (ngx_strcmp(value[2].data, "default") == 0) {
statsd_port_override = STATSD_DEFAULT_PORT;
}
ngx_log_debug1(NGX_LOG_DEBUG_HTTP, cf->log, 0,
"statsd: ngx_http_statsd_set_port %d", statsd_port_override);
ulcf->off = 0;
ngx_memzero(&u, sizeof(ngx_url_t));
u.url = value[1];
u.default_port = statsd_port_override;
u.no_resolve = 0;
if(ngx_parse_url(cf->pool, &u) != NGX_OK) {
ngx_conf_log_error(NGX_LOG_EMERG, cf, 0, "%V: %s", &u.host, u.err);
return NGX_CONF_ERROR;
}
ulcf->endpoint = ngx_http_statsd_add_endpoint(cf, &u.addrs[0]);
if(ulcf->endpoint == NULL) {
return NGX_CONF_ERROR;
}
return NGX_CONF_OK;
}
static char *
ngx_http_statsd_add_stat(ngx_conf_t *cf, ngx_command_t *cmd, void *conf, ngx_uint_t type) {
ngx_http_statsd_conf_t *ulcf = conf;
ngx_http_complex_value_t key_cv;
ngx_http_compile_complex_value_t key_ccv;
ngx_http_complex_value_t metric_cv;
ngx_http_compile_complex_value_t metric_ccv;
ngx_http_complex_value_t valid_cv;
ngx_http_compile_complex_value_t valid_ccv;
ngx_str_t *value;
ngx_statsd_stat_t *stat;
ngx_int_t n;
ngx_str_t s;
ngx_flag_t b;
value = cf->args->elts;
if (ulcf->stats == NULL) {
ulcf->stats = ngx_array_create(cf->pool, 10, sizeof(ngx_statsd_stat_t));
if (ulcf->stats == NULL) {
return NGX_CONF_ERROR;
}
}
stat = ngx_array_push(ulcf->stats);
if (stat == NULL) {
return NGX_CONF_ERROR;
}
ngx_memzero(stat, sizeof(ngx_statsd_stat_t));
stat->type = type;
stat->valid = 1;
ngx_memzero(&key_ccv, sizeof(ngx_http_compile_complex_value_t));
key_ccv.cf = cf;
key_ccv.value = &value[1];
key_ccv.complex_value = &key_cv;
if (ngx_http_compile_complex_value(&key_ccv) != NGX_OK) {
return NGX_CONF_ERROR;
}
if (key_cv.lengths == NULL) {
s = ngx_http_statsd_key_value(&value[1]);
/*if (n < 0) {
ngx_conf_log_error(NGX_LOG_EMERG, cf, 0, "invalid parameter \"%V\"", &value[2]);
return NGX_CONF_ERROR;
};*/
stat->key = (ngx_str_t) s;
} else {
stat->ckey = ngx_palloc(cf->pool, sizeof(ngx_http_complex_value_t));
if (stat->ckey == NULL) {
return NGX_CONF_ERROR;
}
*stat->ckey = key_cv;
}
ngx_memzero(&metric_ccv, sizeof(ngx_http_compile_complex_value_t));
metric_ccv.cf = cf;
metric_ccv.value = &value[2];
metric_ccv.complex_value = &metric_cv;
if (ngx_http_compile_complex_value(&metric_ccv) != NGX_OK) {
return NGX_CONF_ERROR;
}
if (metric_cv.lengths == NULL) {
n = ngx_http_statsd_metric_value(&value[2]);
if (n < 0) {
ngx_conf_log_error(NGX_LOG_EMERG, cf, 0, "invalid parameter \"%V\"", &value[2]);
return NGX_CONF_ERROR;
};
stat->metric = (ngx_uint_t) n;
} else {
stat->cmetric = ngx_palloc(cf->pool, sizeof(ngx_http_complex_value_t));
if (stat->cmetric == NULL) {
return NGX_CONF_ERROR;
}
*stat->cmetric = metric_cv;
}
if (cf->args->nelts > 3) {
ngx_memzero(&valid_ccv, sizeof(ngx_http_compile_complex_value_t));
valid_ccv.cf = cf;
valid_ccv.value = &value[3];
valid_ccv.complex_value = &valid_cv;
if (ngx_http_compile_complex_value(&valid_ccv) != NGX_OK) {
return NGX_CONF_ERROR;
}
if (valid_cv.lengths == NULL) {
b = ngx_http_statsd_valid_value(&value[3]);
if (b < 0) {
ngx_conf_log_error(NGX_LOG_EMERG, cf, 0, "invalid parameter \"%V\"", &value[3]);
return NGX_CONF_ERROR;
};
stat->valid = (ngx_flag_t) b;
} else {
stat->cvalid = ngx_palloc(cf->pool, sizeof(ngx_http_complex_value_t));
if (stat->cvalid == NULL) {
return NGX_CONF_ERROR;
}
*stat->cvalid = valid_cv;
}
}
return NGX_CONF_OK;
}
static char *
ngx_http_statsd_add_count(ngx_conf_t *cf, ngx_command_t *cmd, void *conf)
{
return ngx_http_statsd_add_stat(cf, cmd, conf, STATSD_TYPE_COUNTER);
}
static char *
ngx_http_statsd_add_timing(ngx_conf_t *cf, ngx_command_t *cmd, void *conf)
{
return ngx_http_statsd_add_stat(cf, cmd, conf, STATSD_TYPE_TIMING);
}
static ngx_int_t
ngx_http_statsd_init(ngx_conf_t *cf)
{
ngx_int_t rc;
ngx_uint_t i;
ngx_http_core_main_conf_t *cmcf;
ngx_http_statsd_main_conf_t *umcf;
ngx_http_handler_pt *h;
ngx_udp_endpoint_t *e;
umcf = ngx_http_conf_get_module_main_conf(cf, ngx_http_statsd_module);
if(umcf->endpoints != NULL) {
e = umcf->endpoints->elts;
for(i = 0;i < umcf->endpoints->nelts;i++) {
rc = ngx_statsd_init_endpoint(cf, e + i);
if(rc != NGX_OK) {
return NGX_ERROR;
}
}
cmcf = ngx_http_conf_get_module_main_conf(cf, ngx_http_core_module);
h = ngx_array_push(&cmcf->phases[NGX_HTTP_LOG_PHASE].handlers);
if (h == NULL) {
return NGX_ERROR;
}
*h = ngx_http_statsd_handler;
}
return NGX_OK;
}
uintptr_t
ngx_escape_statsd_key(u_char *dst, u_char *src, size_t size)
{
ngx_uint_t n;
uint32_t *escape;
/* " ", "#", """, "%", "'", %00-%1F, %7F-%FF */
static uint32_t statsd_key[] = {
0xffffffff, /* 1111 1111 1111 1111 1111 1111 1111 1111 */
/* ?>=< ;:98 7654 3210 /.-, +*)( '&%$ #"! */
0xdc00afff, /* 1101 1100 0000 0000 1010 1111 1111 1111 */
/* _^]\ [ZYX WVUT SRQP ONML KJIH GFED CBA@ */
0x78000001, /* 0111 1000 0000 0000 0000 0000 0000 0001 */
/* ~}| {zyx wvut srqp onml kjih gfed cba` */
0xf8000001, /* 1111 1000 0000 0000 0000 0000 0000 0001 */
0xffffffff, /* 1111 1111 1111 1111 1111 1111 1111 1111 */
0xffffffff, /* 1111 1111 1111 1111 1111 1111 1111 1111 */
0xffffffff, /* 1111 1111 1111 1111 1111 1111 1111 1111 */
0xffffffff /* 1111 1111 1111 1111 1111 1111 1111 1111 */
};
static uint32_t *map[] =
{ statsd_key };
escape = map[0];
if (dst == NULL) {
/* find the number of the characters to be escaped */
n = 0;
while (size) {
if (escape[*src >> 5] & (1 << (*src & 0x1f))) {
n++;
}
src++;
size--;
}
return (uintptr_t) n;
}
while (size) {
if (escape[*src >> 5] & (1 << (*src & 0x1f))) {
*dst++ = '_';
src++;
} else {
*dst++ = *src++;
}
size--;
}
return (uintptr_t) dst;
}
|
289502.c | /*
* FreeRTOS V202012.00
* 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.
*
* http://www.FreeRTOS.org
* http://aws.amazon.com/freertos
*
* 1 tab == 4 spaces!
*/
/*-----------------------------------------------------------
* Simple parallel port IO routines for the LED's.
*-----------------------------------------------------------*/
/* Scheduler includes. */
#include "FreeRTOS.h"
/* Demo application includes. */
#include "partest.h"
/* Board specific defines. */
#define partstFIRST_IO ( ( unsigned long ) 0x10000 )
#define partstNUM_LEDS ( 8 )
/*-----------------------------------------------------------*/
void vParTestInitialise( void )
{
/* The ports are setup within prvInitialiseHardware(), called by main(). */
}
/*-----------------------------------------------------------*/
void vParTestSetLED( unsigned portBASE_TYPE uxLED, signed portBASE_TYPE xValue )
{
unsigned long ulLED = partstFIRST_IO;
if( uxLED < partstNUM_LEDS )
{
/* Rotate to the wanted bit of port 1. Only P16 to P23 have an LED
attached. */
ulLED <<= ( unsigned long ) uxLED;
/* Set or clear the output. */
if( xValue )
{
IO1SET = ulLED;
}
else
{
IO1CLR = ulLED;
}
}
}
/*-----------------------------------------------------------*/
void vParTestToggleLED( unsigned portBASE_TYPE uxLED )
{
unsigned long ulLED = partstFIRST_IO, ulCurrentState;
if( uxLED < partstNUM_LEDS )
{
/* Rotate to the wanted bit of port 1. Only P10 to P13 have an LED
attached. */
ulLED <<= ( unsigned long ) uxLED;
/* If this bit is already set, clear it, and vice versa. */
ulCurrentState = IO1PIN;
if( ulCurrentState & ulLED )
{
IO1CLR = ulLED;
}
else
{
IO1SET = ulLED;
}
}
}
|
727695.c | /*
* Copyright (c) 1992, 1993
* The Regents of the University of California. All rights reserved.
*
* This code is derived from software contributed to Berkeley by
* Sony Corp. and Kazumasa Utashiro of Software Research Associates, Inc.
*
* %sccs.include.redist.c%
*
* from: $Hdr: fb_start.c,v 4.300 91/06/27 20:42:40 root Rel41 $ SONY
*
* @(#)fb_start.c 8.1 (Berkeley) 06/11/93
*/
#include <sys/param.h>
#include <sys/systm.h>
#ifdef IPC_MRX
#include "../../iop/framebuf.h"
#include "../../iop/fbreg.h"
#include "page.h"
#else
#include <news3400/iop/framebuf.h>
#include <news3400/iop/fbreg.h>
#endif
#include <news3400/fb/fbdefs.h>
#ifdef CPU_SINGLE
#include <machine/cpu.h>
extern struct tty cons;
extern int cnstart();
#define PRE_EMPT need_resched()
#endif
static struct fbdev *cfb = 0;
static lPoint mp;
#ifdef CPU_SINGLE
static int curs_pending = 0;
#endif
extern struct fbdevsw fbdevsw[];
extern int nfbdev;
#ifdef CPU_SINGLE
extern char *ext_fnt_addr[];
extern char *ext_fnt24_addr[];
#else
extern char **ext_fnt_addr;
extern char **ext_fnt24_addr;
#endif
static char copyfuncv[MAXPLANE] = {
BF_S, BF_S, BF_S, BF_S, BF_S, BF_S, BF_S, BF_S, /* SRC */
BF_S, BF_S, BF_S, BF_S, BF_S, BF_S, BF_S, BF_S, /* SRC */
BF_S, BF_S, BF_S, BF_S, BF_S, BF_S, BF_S, BF_S /* SRC */
};
unsigned short fb_color_pallet_def[48] = { /* define initial color */
/* R, G, B */
0, 0, 0,
0, 0, 0x44,
0, 0x44, 0,
0, 0x44, 0x44,
0x44, 0, 0,
0x44, 0, 0x44,
0x44, 0x44, 0,
0x44, 0x44, 0x44,
0x88, 0x88, 0x88,
0, 0, 0xff,
0, 0xff, 0,
0, 0xff, 0xff,
0xff, 0, 0,
0xff, 0, 0xff,
0xff, 0xff, 0,
0xff, 0xff, 0xff
};
unsigned short fb_gray_pallet_def[48] = { /* define initial color */
/* R, G, B */
0xff, 0xff, 0xff,
0xff, 0xff, 0,
0xff, 0, 0xff,
0xff, 0, 0,
0, 0xff, 0xff,
0, 0xff, 0,
0, 0, 0xff,
0x88, 0x88, 0x88,
0x44, 0x44, 0x44,
0x44, 0x44, 0,
0x44, 0, 0x44,
0x44, 0, 0,
0, 0x44, 0x44,
0, 0x44, 0,
0, 0, 0x44,
0, 0, 0
};
static int bitmap_use; /* shared variable for bitmap exclusion ctrl */
#ifdef IPC_MRX
struct fb_map rommap;
#endif
#ifdef CPU_SINGLE
void
lock_bitmap()
{
int s;
/* wait(bitmap_use) */
s = splbitmap();
while (bitmap_use & FB_BUSY) {
bitmap_use |= FB_WANTED;
sleep((caddr_t)&bitmap_use, FBPRI);
}
bitmap_use |= FB_BUSY;
splx(s);
}
void
unlock_bitmap()
{
int s;
/* signal(bitmap_use) */
s = splbitmap();
if (bitmap_use & FB_WANTED)
wakeup((caddr_t)&bitmap_use);
bitmap_use &= ~(FB_BUSY|FB_WANTED);
splx(s);
}
lock_bitmap_poll()
{
int s;
/* wait(bitmap_use) */
s = splbitmap();
if (bitmap_use & (FB_BUSY|FB_WANTED)) {
splx(s);
return (1);
}
bitmap_use |= FB_BUSY;
splx(s);
return (0);
}
void
unlock_bitmap_poll()
{
int s;
/* signal(bitmap_use) */
s = splbitmap();
if (bitmap_use & FB_WANTED)
wakeup((caddr_t)&bitmap_use);
bitmap_use &= ~(FB_BUSY|FB_WANTED);
splx(s);
}
bmlockedp()
{
return (bitmap_use & (FB_WANTED|FB_BUSY));
}
#ifdef NOTDEF /* KU:XXX not necessary for news3200 */
void
rop_wait(fb)
struct fbdev *fb;
{
register int s;
int i;
s = splbitmap();
/* KU:XXX trick! */
#define in_interrupt() ((caddr_t)&fb < (caddr_t)MACH_CODE_START)
if (in_interrupt() || (fb->run_flag & FB_WAITING)) {
splx(s);
fbbm_rop_wait(fb);
} else {
if (fbbm_ioctl(fb, FB_STATUSCHECK, 0) &
(FB_STATUS_ROPWAIT|FB_STATUS_ROPEXEC)) {
i = FB_INT_ROPDONE;
fbbm_ioctl(fb, FB_INTENABLE, &i);
if (!(fbbm_ioctl(fb, FB_STATUSCHECK, 0) &
(FB_STATUS_ROPWAIT|FB_STATUS_ROPEXEC))) {
i = FB_INT_ROPDONE;
fbbm_ioctl(fb, FB_INTCLEAR, &i);
} else {
fb->run_flag |= FB_WAITING;
sleep((caddr_t)&fb->run_flag, FBPRI);
}
}
splx(s);
}
}
#endif /* NOTDEF */
#else /* CPU_SINGLE */
#ifdef IPC_MRX
struct page {
char bytes[NBPG];
};
extern struct page *page_base;
extern struct page *page_max;
extern struct map pagemap[];
extern struct pte_iop page_pt[];
extern int mapped_page;
caddr_t
fb_map_page(map, n, prot)
register int *map;
register int n;
register int prot;
{
register int x;
register struct pte_iop *p;
register struct page *addr;
register int s = spl7();
static int last_x, last_n;
if (last_n >= n) {
x = last_x;
} else {
rmfree(pagemap, last_n, last_x);
mapped_page -= last_n;
last_x = 0;
last_n = 0;
if ((x = rmalloc(pagemap, n)) <= 0) {
splx(s);
return (NULL);
}
mapped_page += n;
last_x = x;
last_n = n;
}
addr = page_base + x;
prot |= PG_PAGE;
for (p = page_pt + x; n > 0; p++, n--) {
*(int *)p = prot | *map++;
tbis((caddr_t)addr);
addr++;
}
splx(s);
return ((caddr_t)(page_base + x));
}
caddr_t
fb_map_page2(map, n, prot)
register int *map;
register int n;
register int prot;
{
register int x;
register struct pte_iop *p;
register struct page *addr;
register int s;
if (n == 0)
return (NULL);
s = spl7();
if ((x = rmalloc(pagemap, n)) <= 0) {
splx(s);
return (NULL);
}
mapped_page += n;
addr = page_base + x;
prot |= PG_PAGE;
for (p = page_pt + x; n > 0; p++, n--) {
*(int *)p = prot | (*map++);
tbis((caddr_t)addr);
addr++;
}
splx(s);
return ((caddr_t)(page_base + x));
}
#endif /* IPC_MRX */
#endif /* CPU_SINGLE */
iopmemfbmap(addr, len, map)
register caddr_t addr;
register int len;
register struct fb_map *map;
{
register caddr_t *p;
register int i;
map->fm_vaddr = addr;
map->fm_offset = (unsigned)addr & CLOFSET;
map->fm_count = len;
len += map->fm_offset;
p = map->fm_addr;
addr -= map->fm_offset;
for (i = 0; i < NFBMAP && len > 0; i++) {
*p++ = addr;
addr += CLBYTES;
len -= CLBYTES;
}
}
int
nofunc()
{
return 0;
}
int
error()
{
return FB_RERROR;
}
void
checkArea(fb, x, y)
register struct fbdev *fb;
register int *x, *y;
{
if (*x < fb->moveArea.origin.x)
*x = fb->moveArea.origin.x;
if (*y < fb->moveArea.origin.y)
*y = fb->moveArea.origin.y;
if (*x >= (fb->moveArea.origin.x + fb->moveArea.extent.x))
*x = (fb->moveArea.origin.x + fb->moveArea.extent.x) - 1;
if (*y >= (fb->moveArea.origin.y + fb->moveArea.extent.y))
*y = (fb->moveArea.origin.y + fb->moveArea.extent.y) - 1;
}
cursorIn(fb, clip)
register struct fbdev *fb;
register lRectangle *clip;
{
if (clip == 0)
return (1);
if (cfb != fb)
return (0);
return (clip->origin.x < fb->cursorP.x + fb->size.x &&
clip->origin.x + clip->extent.x > fb->cursorP.x &&
clip->origin.y < fb->cursorP.y + fb->size.y &&
clip->origin.y + clip->extent.y > fb->cursorP.y);
}
void
fbcopy1(src, dst, fv)
lPoint src;
lPoint dst;
char *fv;
{
lRectangle sr, dr;
sr.origin = src;
sr.extent = cfb->size;
dr.origin = dst;
if (cliprect2(&sr, &cfb->FrameRect, &dr, &cfb->VisRect)) {
fbbm_rop_init(cfb, fv);
fbbm_rop_copy(cfb, &sr, &dr.origin, 1, FB_PLANEALL);
}
}
void
fbcopy2(src, dst)
lPoint src;
lPoint dst;
{
lRectangle sr, dr;
sr.origin = src;
sr.extent = cfb->size;
dr.origin = dst;
if (cliprect2(&sr, &cfb->FrameRect, &dr, &cfb->FrameRect)) {
fbbm_rop_init(cfb, copyfuncv);
fbbm_rop_copy(cfb, &sr, &dr.origin, 0, FB_PLANEALL);
}
}
void
fbcopy3(src, dst)
lPoint src;
lPoint dst;
{
lRectangle sr, dr;
sr.origin = src;
sr.extent = cfb->size;
dr.origin = dst;
if (cliprect2(&sr, &cfb->FrameRect, &dr, &cfb->VisRect)) {
fbbm_rop_init(cfb, copyfuncv);
fbbm_rop_copy(cfb, &sr, &dr.origin, 0, FB_PLANEALL);
}
}
void
cursorOn(fb)
register struct fbdev *fb;
{
#ifdef CPU_SINGLE
int s = splbitmap();
#endif
if (cfb == fb && fb->cursorShow && !fb->cursorVis) {
if (fb->hard_cursor) {
fbbm_cursor_on(fb);
} else {
fbcopy2(fb->cursorP, fb->SaveRect.origin);
fbcopy1(fb->MaskRect.origin, fb->cursorP,
fb->maskfuncv);
fbcopy1(fb->CursorRect.origin, fb->cursorP,
fb->curfuncv);
}
fb->cursorVis = 1;
}
#ifdef CPU_SINGLE
splx(s);
#endif
}
void
cursorOff(fb)
register struct fbdev *fb;
{
#ifdef CPU_SINGLE
int s = splbitmap();
#endif
if (cfb == fb && fb->cursorShow && fb->cursorVis) {
if (fb->hard_cursor)
fbbm_cursor_off(fb);
else
fbcopy3(fb->SaveRect.origin, fb->cursorP);
fb->cursorVis = 0;
}
#ifdef CPU_SINGLE
splx(s);
#endif
}
void
softCursorCheck(fb, stype, srect, dtype, drect)
struct fbdev *fb;
char stype, dtype;
lRectangle *srect, *drect;
{
if (cfb == fb && cfb->cursorVis &&
((stype == BM_FB && cursorIn(fb, srect)) ||
(dtype == BM_FB && cursorIn(fb, drect))))
cursorOff(cfb);
}
void
cursorCheck(fb, stype, srect, dtype, drect)
struct fbdev *fb;
char stype, dtype;
lRectangle *srect, *drect;
{
if (!fb->hard_cursor)
softCursorCheck(fb, stype, srect, dtype, drect);
}
int
redrawCursor(fb)
register struct fbdev *fb;
{
int s;
lPoint tmp;
if (cfb == fb && fb->cursorSet) {
s = spl7();
tmp = mp;
splx(s);
#ifdef CPU_SINGLE
s = splbitmap();
#endif
if (fb->cursorP.x != tmp.x || fb->cursorP.y != tmp.y) {
if (fb->cursorVis) {
if (! fb->hard_cursor) {
fbcopy3(fb->SaveRect.origin,
fb->cursorP);
}
}
fb->cursorP = tmp;
if (fb->hard_cursor) {
fbbm_cursor_off(fb);
fbbm_cursor_move(fb);
}
if (fb->cursorVis) {
if (fb->hard_cursor) {
fbbm_cursor_on(fb);
} else {
fbcopy2(fb->cursorP,
fb->SaveRect.origin);
fbcopy1(fb->MaskRect.origin,
fb->cursorP, fb->maskfuncv);
fbcopy1(fb->CursorRect.origin,
fb->cursorP, fb->curfuncv);
}
}
}
#ifdef CPU_SINGLE
splx(s);
#endif
}
return (0);
}
void
updateCursor(x, y, flag)
int *x, *y;
int flag;
{
int s;
if (cfb && cfb->cursorSet) {
checkArea(cfb, x, y);
s = spl7();
mp.x = *x - cfb->hot.x;
mp.y = *y - cfb->hot.y;
splx(s);
#ifdef CPU_SINGLE
if (flag || cfb->hard_cursor) {
curs_pending = 0;
redrawCursor(cfb);
} else if (cfb->type == FB_LCDM) {
if (!lock_bitmap_poll()) {
curs_pending = 0;
redrawCursor(cfb);
unlock_bitmap_poll();
} else {
curs_pending = 1;
}
}
#else
redrawCursor(cfb);
#endif
}
}
setCursor(fb, cursor)
register struct fbdev *fb;
register lCursor2 *cursor;
{
register char *fv;
register int f0, f1, i, color;
#ifdef CPU_SINGLE
register int s = splbitmap();
#endif
int data;
if (cfb == fb) {
cursorOff(cfb);
fb->cursorShow = 0;
fb->cursorP.x += cfb->hot.x;
fb->cursorP.y += cfb->hot.y;
#ifdef CPU_SINGLE
data = FB_INT_VSYNC;
fbbm_ioctl(fb, FB_INTCLEAR, &data);
#endif
cfb = NULL;
}
if (cursor) {
fb->CursorRect = cursor->cursorRect;
fb->MaskRect = cursor->maskRect;
fb->SaveRect = cursor->saveRect;
fb->moveArea = cursor->moveArea;
fb->hot = cursor->hot;
fb->size = cursor->size;
f0 = 0x4 | ((cursor->func >> 2) & 0x3);
f1 = 0x4 | (cursor->func & 0x3);
i = fb->fbNplane;
fv = fb->curfuncv;
color = cursor->cursor_color;
while (i-- > 0) {
*fv++ = (color & 1) ? f1 : f0;
color >>= 1;
}
i = fb->fbNplane;
fv = fb->maskfuncv;
color = cursor->mask_color;
while (i-- > 0) {
*fv++ = (color & 1) ? f1 : f0;
color >>= 1;
}
checkArea(fb, &fb->cursorP.x, &fb->cursorP.y);
fb->cursorP.x -= fb->hot.x;
fb->cursorP.y -= fb->hot.y;
fb->cursorSet = 1;
fb->cursorShow = 0;
fb->cursorVis = 0;
if (fb->hard_cursor) {
fbbm_cursor_off(fb);
fbbm_cursor_set(fb, cursor->cursor_color, cursor->mask_color);
fbbm_cursor_move(fb);
}
} else {
fb->cursorP.x = fb->VisRect.extent.x / 2;
fb->cursorP.y = fb->VisRect.extent.y / 2;
fb->cursorSet = 0;
fb->cursorShow = 0;
fb->cursorVis = 0;
if (fb->hard_cursor)
fbbm_cursor_off(fb);
}
#ifdef CPU_SINGLE
splx(s);
#endif
return (FB_ROK);
}
showCursor(fb)
register struct fbdev *fb;
{
int data;
#ifdef CPU_SINGLE
register int s = splbitmap();
#endif
if (fb->cursorSet && !fb->cursorShow) {
if (cfb && cfb != fb) {
cursorOff(cfb);
cfb->cursorShow = 0;
}
cfb = fb;
fb->cursorShow = 1;
mp = fb->cursorP;
cursorOn(fb);
#ifdef CPU_SINGLE
data = FB_INT_VSYNC;
fbbm_ioctl(fb, FB_INTENABLE, &data);
splx(s);
#endif
return (FB_ROK);
}
#ifdef CPU_SINGLE
splx(s);
#endif
return (FB_RERROR);
}
hideCursor(fb)
register struct fbdev *fb;
{
int data;
#ifdef CPU_SINGLE
int s = splbitmap();
#endif
if (cfb == fb) {
cursorOff(fb);
fb->cursorShow = 0;
#ifdef CPU_SINGLE
data = FB_INT_VSYNC;
fbbm_ioctl(fb, FB_INTCLEAR, &data);
splx(s);
#endif
return (FB_ROK);
}
#ifdef CPU_SINGLE
splx(s);
#endif
return (FB_RERROR);
}
moveCursor(fb, point)
struct fbdev *fb;
lPoint *point;
{
if (cfb == fb) {
updateCursor(&point->x, &point->y, 1);
return (FB_ROK);
}
return (FB_RERROR);
}
#ifdef CPU_SINGLE
rop_xint()
{
register struct fbdev *fb;
register int i;
register int done = 0;
int event, data;
int s = splbitmap();
for (i = 0, fb = fbdev; i < nfbdev; i++, fb++) {
if (fb->type && (event = fbbm_ioctl(fb, FB_INTCHECK, 0))) {
#ifdef notyet /* KU:XXX */
intrcnt[INTR_BITMAP]++;
#endif
done = 1;
if (event & FB_INT_VSYNC) {
data = FB_INT_VSYNC;
fbbm_ioctl(fb, FB_INTCLEAR, &data);
if (!lock_bitmap_poll()) {
curs_pending = 0;
redrawCursor(fb);
unlock_bitmap_poll();
} else {
curs_pending = 1;
}
data = FB_INT_VSYNC;
fbbm_ioctl(fb, FB_INTENABLE, &data);
}
if (event & FB_INT_ROPDONE) {
if(fb->run_flag & FB_WAITING) {
data = FB_INT_ROPDONE;
fbbm_ioctl(fb, FB_INTCLEAR, &data);
if (!(fbbm_ioctl(fb, FB_STATUSCHECK, 0)
& (FB_STATUS_ROPWAIT|FB_STATUS_ROPEXEC))) {
fb->run_flag &= ~FB_WAITING;
wakeup(&(fb->run_flag));
} else {
data = FB_INT_ROPDONE|0x100;
fbbm_ioctl(fb, FB_INTENABLE, &data);
}
}
}
}
}
splx(s);
return (done);
}
#endif /* CPU_SINGLE */
cliprect2(sr, sc, dr, dc)
register lRectangle *sr;
register lRectangle *sc;
register lRectangle *dr;
register lRectangle *dc;
{
register int d;
/* src left/right edge */
if ((d = sr->origin.x - sc->origin.x) < 0) {
sr->extent.x += d;
sr->origin.x -= d;
dr->origin.x -= d;
d = sr->extent.x - sc->extent.x;
} else
d += sr->extent.x - sc->extent.x;
if (d > 0)
sr->extent.x -= d;
/* src top/bottom edge */
if ((d = sr->origin.y - sc->origin.y) < 0) {
sr->extent.y += d;
sr->origin.y -= d;
dr->origin.y -= d;
d = sr->extent.y - sc->extent.y;
} else
d += sr->extent.y - sc->extent.y;
if (d > 0)
sr->extent.y -= d;
if (sr->extent.x <= 0 || sr->extent.y <= 0)
return (0);
/* dst left/right edge */
if ((d = dr->origin.x - dc->origin.x) < 0) {
dr->origin.x -= d;
sr->extent.x += d;
sr->origin.x -= d;
d = sr->extent.x - dc->extent.x;
} else
d += sr->extent.x - dc->extent.x;
if (d > 0)
sr->extent.x -= d;
/* dst top/bottom edge */
if ((d = dr->origin.y - dc->origin.y) < 0) {
dr->origin.y -= d;
sr->extent.y += d;
sr->origin.y -= d;
d = sr->extent.y - dc->extent.y;
} else
d += sr->extent.y - dc->extent.y;
if (d > 0)
sr->extent.y -= d;
if (sr->extent.x <= 0 || sr->extent.y <= 0)
return (0);
dr->extent = sr->extent;
return (1);
}
cliprect(r, crp, p)
register lRectangle *r;
register lRectangle *crp;
register lRectangle *p;
{
register int d;
/* left edge */
if ((d = r->origin.x - crp->origin.x) < 0) {
r->extent.x += d;
r->origin.x -= d;
if (p) {
p->extent.x += d;
p->origin.x -= d;
}
d = r->extent.x - crp->extent.x;
} else
d += r->extent.x - crp->extent.x;
/* right edge */
if (d > 0) {
r->extent.x -= d;
if (p)
p->extent.x -= d;
}
/* top edge */
if ((d = r->origin.y - crp->origin.y) < 0) {
r->extent.y += d;
r->origin.y -= d;
if (p) {
p->extent.y += d;
p->origin.y -= d;
}
d = r->extent.y - crp->extent.y;
} else
d += r->extent.y - crp->extent.y;
/* bottom edge */
if (d > 0) {
r->extent.y -= d;
if (p)
p->extent.y -= d;
}
return (r->extent.x > 0 && r->extent.y > 0);
}
getclip(fb, bmp, crp)
struct fbdev *fb;
lBitmap *bmp;
lRectangle *crp;
{
/* limit clip rectangle to bitmap rectangle */
if (!cliprect(crp, &bmp->rect, (lRectangle*)0))
return (0);
/* limit clip rectangle to frame buffer */
if ((bmp->type == BM_FB) &&
!cliprect(crp, &fb->FrameRect, (lRectangle*)0))
return (0);
return (1);
}
clipsrc(fb, bmp)
struct fbdev *fb;
lBitmap *bmp;
{
/* limit clip rectangle to frame buffer */
if (bmp->type == BM_FB &&
!cliprect(&bmp->rect, &fb->FrameRect, (lRectangle*)0))
return (0);
return (1);
}
setrop(fb, func, pmask, fore, aux, trans, sbp, dbp)
register struct fbdev *fb;
register unsigned int func;
int pmask;
register int fore, aux;
int trans;
lBitmap *sbp, *dbp;
{
register char *funcp;
register int i;
char tmp[4];
/* set plane register */
fb->Mode = 0;
fb->Pmask = pmask;
fb->func = func;
fb->fore = fore;
fb->aux = aux;
fb->trans = trans;
if (sbp->depth > 1)
fb->Mode |= 2;
if (dbp->depth > 1)
fb->Mode |= 1;
/* set rop function register */
func &= 0xf;
tmp[0] = TRANS(trans, (func & 0x0c) | (func>>2));
tmp[1] = TRANS(trans, (func>>2) | ((func<<2) & 0x0c));
tmp[2] = TRANS(trans, func);
tmp[3] = TRANS(trans, (func<<2) & 0x0c | func & 3);
funcp = fb->funcvec;
for (i = fb->fbNplane; --i >= 0;) {
*funcp++ = tmp[((fore & 1) << 1) | (aux & 1)];
fore >>= 1; aux >>= 1;
}
return (0);
}
/*
* bitblt within frame buffer
*/
bitblt_fb(fb, sbp, srp, dbp, dpp, crp)
register struct fbdev *fb;
register lBitmap *sbp; /* source bitmap (FB) */
lRectangle *srp; /* source rectangle */
lBitmap *dbp; /* destination bitmap (FB) */
lPoint *dpp; /* destination point */
lRectangle *crp; /* clip region in destination */
{
lRectangle sr;
lRectangle dr;
register int wplane, i, j;
sr = *srp;
dr.origin = *dpp;
if (crp && !cliprect2(&sr, &sbp->rect, &dr, crp))
return (0);
fbbm_rop_init(fb, fb->funcvec);
switch (fb->Mode) {
case MODE_1to1:
fb->Pmask &= 1;
case MODE_NtoN:
fbbm_rop_copy(fb, &sr, &dr.origin, 0, fb->Pmask);
break;
case MODE_1toN:
fbbm_rop_copy(fb, &sr, &dr.origin, 1, fb->Pmask);
break;
case MODE_Nto1:
wplane = 1;
for (i = 0, j = sbp->depth; i < j; i++) {
if (fb->Pmask & wplane) {
fbbm_rop_copy(fb, &sr, &dr.origin, i + 1,
fb->Pmask >> 16);
break;
}
wplane <<= 1;
}
break;
default:
return (-1);
}
return (0);
}
/*
* bitblt from main memory to frame buffer
*/
bitblt_tofb(fb, sbp, srp, dbp, dpp, crp)
register struct fbdev *fb;
register lBitmap *sbp; /* source bitmap (MEM) */
lRectangle *srp; /* source rectangle */
lBitmap *dbp; /* destination bitmap (FB) */
lPoint *dpp; /* destination point */
lRectangle *crp; /* clip region in destination */
{
register unsigned p;
register struct fb_map *smap;
register int i, n, m;
lRectangle sr;
lRectangle dr;
register int wplane;
#ifdef IPC_MRX
extern struct fb_map rommap;
register int pages;
#endif
smap = (struct fb_map*)sbp->base;
sr = *srp;
dr.origin = *dpp;
if (crp && !cliprect2(&sr, &sbp->rect, &dr, crp))
return (0);
dr.extent = sr.extent;
/* transform source rectangle */
sr.origin.x -= sbp->rect.origin.x;
sr.origin.y -= sbp->rect.origin.y;
/*
* check memory map specification
*/
p = smap->fm_offset;
#ifdef IPC_MRX
pages = btoc(smap->fm_offset + smap->fm_count);
rommap.fm_vaddr = fb_map_page(smap->fm_addr, pages,
fb->cache_off ? PG_S|PG_WP|PG_CI : PG_S|PG_WP);
rommap.fm_offset = 0;
smap = &rommap;
#endif
wplane = 1;
fbbm_rop_winit(fb);
switch (fb->Mode) {
case MODE_1to1:
fbbm_rop_write(fb, smap, p, sbp->width,
&sr, &dr, fb->Pmask & 0x01);
break;
case MODE_1toN:
fbbm_rop_write(fb, smap, p, sbp->width,
&sr, &dr, fb->Pmask);
break;
case MODE_Nto1:
m = sbp->width * sbp->rect.extent.y;
for (i = 0; i < sbp->depth; i++, wplane <<= 1) {
if (fb->Pmask & wplane) {
p += (m * i) << 1;
fbbm_rop_write(fb, smap, p, sbp->width,
&sr, &dr, wplane);
break;
}
wplane <<= 1;
}
break;
case MODE_NtoN:
n = min(sbp->depth, fb->fbNplane);
m = sbp->width * sbp->rect.extent.y;
p += (m << 1) * n;
wplane = 1 << (n - 1);
for (i = n; i > 0; i--) {
/* get next plane */
p -= m << 1;
if (fb->Pmask & wplane)
fbbm_rop_write(fb, smap, p, sbp->width,
&sr, &dr, wplane);
/* next plane mask */
wplane >>= 1;
}
break;
default:
return (-1);
}
return (0);
}
/*
* bitblt from frame buffer to main memroy
*/
bitblt_tomem(fb, sbp, srp, dbp, dpp, crp)
struct fbdev *fb;
lBitmap *sbp; /* source bitmap (FB) */
lRectangle *srp; /* source rectangle */
lBitmap *dbp; /* destination bitmap (MEM) */
lPoint *dpp; /* destination point */
lRectangle *crp; /* clip region in destination */
{
register struct fb_map *dmap;
register unsigned p;
register int i, n, m;
lRectangle sr;
lRectangle dr;
int plane;
#ifdef IPC_MRX
extern struct fb_map rommap;
register int pages;
#endif
dmap = (struct fb_map*)dbp->base;
sr = *srp;
dr.origin = *dpp;
if (crp && !cliprect2(&sr, &sbp->rect, &dr, crp))
return (0);
dr.extent = sr.extent;
dr.origin.x -= dbp->rect.origin.x;
dr.origin.y -= dbp->rect.origin.y;
p = dmap->fm_offset;
#ifdef IPC_MRX
pages = btoc(dmap->fm_offset + dmap->fm_count);
rommap.fm_vaddr = fb_map_page(dmap->fm_addr, pages, PG_S);
rommap.fm_offset = 0;
dmap = &rommap;
#endif
plane = 1;
/* Wait for rop busy */
switch (fb->Mode) {
case MODE_1to1:
if (fb->Pmask & plane)
fbbm_rop_read(fb, dmap, p, dbp->width,
&sr, &dr, 0, 0);
break;
case MODE_1toN:
m = (dbp->width * dbp->rect.extent.y) << 1;
for (i = 0; i < dbp->depth; i++) {
if (fb->Pmask & plane)
fbbm_rop_read(fb, dmap, p, dbp->width,
&sr, &dr, 0, i);
/* next plane */
p += m;
plane <<= 1;
}
break;
case MODE_Nto1:
for (i = 0; i < sbp->depth; i++, plane <<= 1) {
if (fb->Pmask & plane) {
fbbm_rop_read(fb, dmap, p, dbp->width,
&sr, &dr, i, 0);
break;
}
}
break;
case MODE_NtoN:
n = min(dbp->depth, fb->fbNplane);
m = (dbp->width * dbp->rect.extent.y) << 1;
for (i = 0; i < n; i++) {
if (fb->Pmask & plane)
fbbm_rop_read(fb, dmap, p, dbp->width,
&sr, &dr, i, i);
/* next plane */
p += m;
plane <<= 1;
}
break;
default:
return (-1);
}
return (0);
}
bitblt_mem(fb, sbp, srp, dbp, dpp, crp)
struct fbdev *fb;
register lBitmap *sbp;
lRectangle *srp;
register lBitmap *dbp;
lPoint *dpp;
lRectangle *crp;
{
register int i;
register int plane;
register struct fb_map *smap, *dmap;
register unsigned int ps, pd;
lRectangle sr;
lRectangle dr;
#ifdef IPC_MRX
static struct fb_map drommap;
int spages, dpages;
#endif
smap = (struct fb_map*)sbp->base;
dmap = (struct fb_map*)dbp->base;
sr = *srp;
dr.origin = *dpp;
if (crp && !cliprect2(&sr, &sbp->rect, &dr, crp))
return (0);
/* normalize source/destination coordinates */
sr.origin.x -= sbp->rect.origin.x;
sr.origin.y -= sbp->rect.origin.y;
dr.origin.x -= dbp->rect.origin.x;
dr.origin.y -= dbp->rect.origin.y;
ps = smap->fm_offset;
pd = dmap->fm_offset;
#ifdef IPC_MRX
spages = btoc(smap->fm_offset + smap->fm_count);
dpages = btoc(dmap->fm_offset + dmap->fm_count);
rommap.fm_vaddr = fb_map_page2(smap->fm_addr, spages, PG_S|PG_WP);
rommap.fm_offset = 0;
drommap.fm_vaddr = fb_map_page2(dmap->fm_addr, dpages, PG_S);
drommap.fm_offset = 0;
smap = &rommap;
dmap = &drommap;
#endif
plane = 0x1; /* plane 0 */
switch (fb->Mode) {
case MODE_1to1:
if (fb->Pmask & plane) {
mem_to_mem(fb->funcvec[0],
smap, ps, sbp->width, dmap, pd, dbp->width,
&sr, &dr.origin);
}
break;
case MODE_1toN:
for (i = 0; i < dbp->depth; i++) {
if (fb->Pmask & plane) {
mem_to_mem(fb->funcvec[i],
smap, ps, sbp->width,
dmap, pd, dbp->width,
&sr, &dr.origin);
}
pd += (dbp->width * dbp->rect.extent.y) << 1;
plane <<= 1;
}
break;
case MODE_Nto1:
for (i = 0; i < sbp->depth; i++, plane <<= 1) {
if (fb->Pmask & plane)
break;
}
if (i < sbp->depth) {
ps += (sbp->width * sbp->rect.extent.y * i) << 1;
mem_to_mem(fb->funcvec[i],
smap, ps, sbp->width, dmap, pd, dbp->width,
&sr, &dr.origin);
}
break;
case MODE_NtoN:
for (i = 0; i < dbp->depth; i++) {
if (fb->Pmask & plane) {
mem_to_mem(fb->funcvec[i],
smap, ps, sbp->width,
dmap, pd, dbp->width,
&sr, &dr.origin);
}
ps += (sbp->width * sbp->rect.extent.y) << 1;
pd += (dbp->width * dbp->rect.extent.y) << 1;
plane <<= 1;
}
break;
default:
return (-1);
}
#ifdef IPC_MRX
page_unmap(rommap.fm_vaddr, spages);
page_unmap(drommap.fm_vaddr, dpages);
#endif
return (0);
}
bitblt_nop()
{
return (0);
}
/*
* bitblt from '0' bitmap to frame buffer
*/
bitblt_0tofb(fb, sbp, srp, dbp, dpp, crp)
register struct fbdev *fb;
lBitmap *sbp; /* source bitmap (0) */
lRectangle *srp; /* source rectangle */
lBitmap *dbp; /* destination bitmap (FB) */
lPoint *dpp; /* destination point */
lRectangle *crp; /* clip region in destination */
{
lRectangle sr;
lRectangle dr;
sr = *srp;
dr.origin = *dpp;
if (crp && !cliprect2(&sr, &sbp->rect, &dr, crp))
return (0);
dr.extent = sr.extent;
switch (fb->Mode) {
case MODE_1to1:
case MODE_Nto1:
fb->Pmask &= 1;
break;
case MODE_1toN:
case MODE_NtoN:
break;
default:
return (-1);
}
/*
* write data into ROP data register
*/
fbbm_rop_cinit(fb, fb->Pmask, 0);
fbbm_rop_clear(fb, &dr);
return (0);
}
/*
* bitblt from '1' bitmap to frame buffer
*/
bitblt_1tofb(fb, sbp, srp, dbp, dpp, crp)
register struct fbdev *fb;
lBitmap *sbp; /* source bitmap (1) */
lRectangle *srp; /* source rectangle */
lBitmap *dbp; /* destination bitmap (FB) */
lPoint *dpp; /* destination point */
lRectangle *crp; /* clip region in destination */
{
lRectangle sr;
lRectangle dr;
sr = *srp;
dr.origin = *dpp;
if (crp && !cliprect2(&sr, &sbp->rect, &dr, crp))
return (0);
dr.extent = sr.extent;
switch (fb->Mode) {
case MODE_1to1:
case MODE_Nto1:
/* plane mask set */
fb->Pmask &= 0x1;
break;
case MODE_1toN:
case MODE_NtoN:
break;
default:
return (-1);
}
/*
* write data into ROP data register
*/
fbbm_rop_cinit(fb, fb->Pmask, 1);
fbbm_rop_clear(fb, &dr);
return (0);
}
#ifndef CPU_DOUBLE
/*
* bitblt from '0' bitmap to main memory
*/
bitblt_0tomem(fb, sbp, srp, dbp, dpp, crp)
register struct fbdev *fb;
lBitmap *sbp; /* source bitmap (0) */
lRectangle *srp; /* source rectangle */
register lBitmap *dbp; /* destination bitmap (MEM) */
lPoint *dpp; /* destination point */
lRectangle *crp; /* clip region in destination */
{
register struct fb_map *dmap;
register unsigned int p;
register int i, j;
register int plane;
lRectangle sr;
lRectangle dr;
int skip;
dmap = (struct fb_map*)dbp->base;
sr = *srp;
dr.origin = *dpp;
if (crp && !cliprect2(&sr, &sbp->rect, &dr, crp))
return (0);
dr.extent = sr.extent;
dr.origin.x -= dbp->rect.origin.x;
dr.origin.y -= dbp->rect.origin.y;
p = dmap->fm_offset;
plane = 0x1;
switch (fb->Mode) {
case MODE_1to1:
if (fb->Pmask & plane)
mem_clear(fb->funcvec[0], dmap, p, dbp->width, &dr, 0);
break;
case MODE_1toN:
case MODE_NtoN:
skip = (dbp->width * dbp->rect.extent.y) << 1;
for (i = 0, j = dbp->depth; i < j; i++) {
if (fb->Pmask & plane)
mem_clear(fb->funcvec[i], dmap, p, dbp->width,
&dr, 0);
/* next plane */
p += skip;
plane <<= 1;
}
break;
case MODE_Nto1:
for (i = 0, j = sbp->depth; i < j; i++) {
if (fb->Pmask & plane) {
mem_clear(fb->funcvec[i], dmap, p, dbp->width,
&dr, 0);
break;
}
plane <<= 1;
}
break;
default:
return (1);
}
return (0);
}
/*
* bitblt from '1' bitmap to main memory
*/
bitblt_1tomem(fb, sbp, srp, dbp, dpp, crp)
register struct fbdev *fb;
lBitmap *sbp; /* source bitmap (1) */
lRectangle *srp; /* source rectangle */
register lBitmap *dbp; /* destination bitmap (MEM) */
lPoint *dpp; /* destination point */
lRectangle *crp; /* clip region in destination */
{
register struct fb_map *dmap;
register unsigned p;
register int i, j;
register int plane;
lRectangle sr;
lRectangle dr;
int skip;
dmap = (struct fb_map*)dbp->base;
sr = *srp;
dr.origin = *dpp;
if (crp && !cliprect2(&sr, &sbp->rect, &dr, crp))
return (0);
dr.extent = sr.extent;
dr.origin.x -= dbp->rect.origin.x;
dr.origin.y -= dbp->rect.origin.y;
p = dmap->fm_offset;
plane = 0x1;
switch (fb->Mode) {
case MODE_1to1:
if (fb->Pmask & plane)
mem_clear(fb->funcvec[0], dmap, p, dbp->width, &dr, 1);
break;
case MODE_1toN:
case MODE_NtoN:
skip = (dbp->width * dbp->rect.extent.y) << 1;
for (i = 0, j = dbp->depth; i < j; i++) {
if (fb->Pmask & plane)
mem_clear(fb->funcvec[i], dmap, p, dbp->width,
&dr, 1);
/* next plane */
p += skip;
plane <<= 1;
}
break;
case MODE_Nto1:
for (i = 0, j = sbp->depth; i < j; i++) {
if (fb->Pmask & plane) {
mem_clear(fb->funcvec[i], dmap, p, dbp->width,
&dr, 1);
break;
}
plane <<= 1;
}
break;
default:
return (1);
}
return (0);
}
#endif /* !CPU_DOUBLE */
int
(*sel_ropfunc(stype, dtype))()
int stype; /* source bitmap type */
int dtype; /* dest bitmap type */
{
if (dtype == BM_0)
return (bitblt_nop);
if (dtype == BM_1)
return (bitblt_nop);
#ifdef CPU_DOUBLE
switch (stype) {
case BM_FB:
return (dtype == BM_FB) ? bitblt_fb : bitblt_tomem;
break;
case BM_MEM:
return (dtype == BM_FB) ? bitblt_tofb : bitblt_mem;
break;
case BM_0:
return (dtype == BM_FB) ? bitblt_0tofb : bitblt_nop;
break;
case BM_1:
return (dtype == BM_FB) ? bitblt_1tofb : bitblt_nop;
break;
}
#else /* CPU_DOUBLE */
switch (stype) {
case BM_FB:
return (dtype == BM_FB) ? bitblt_fb : bitblt_tomem;
break;
case BM_MEM:
return (dtype == BM_FB) ? bitblt_tofb : bitblt_mem;
break;
case BM_0:
return (dtype == BM_FB) ? bitblt_0tofb : bitblt_0tomem;
break;
case BM_1:
return (dtype == BM_FB) ? bitblt_1tofb : bitblt_1tomem;
break;
}
#endif /* CPU_DOUBLE */
return (bitblt_nop);
}
bitbltcmd(fb, cmd)
register struct fbdev *fb;
register lBitblt *cmd;
{
lRectangle cr;
int ret;
cr = cmd->destClip;
if (!getclip(fb, &cmd->destBitmap, &cr))
return (0);
if (!clipsrc(fb, &cmd->srcBitmap))
return (0);
if (setrop(fb, cmd->func, cmd->planemask, cmd->fore_color, cmd->aux_color,
cmd->transp, &cmd->srcBitmap, &cmd->destBitmap) < 0)
return (FB_RERROR);
cursorCheck(fb, cmd->srcBitmap.type, &cmd->srcRect,
cmd->destBitmap.type, &cr);
ret = (*sel_ropfunc(cmd->srcBitmap.type, cmd->destBitmap.type))
(fb, &cmd->srcBitmap, &cmd->srcRect, &cmd->destBitmap, &cmd->destPoint, &cr);
cursorOn(fb);
return (FB_ROK);
}
static
batch_bitblt_01tofb(fb, sbp, clip, sdp, n, sw)
register struct fbdev *fb;
lBitmap *sbp; /* source bitmap (MEM) */
register lRectangle *clip;
register lSrcDest *sdp;
register int n;
int sw;
{
register void (*rop_clear)();
lRectangle *srect = &sbp->rect;
switch (fb->Mode) {
case MODE_1to1:
case MODE_Nto1:
fb->Pmask &= 1;
break;
case MODE_1toN:
case MODE_NtoN:
break;
default:
return (FB_RERROR);
}
fbbm_rop_cinit(fb, fb->Pmask, sw);
rop_clear = fb->fbbm_op->fb_rop_clear;
while (--n >= 0) {
lRectangle sr;
lRectangle dr;
sr = sdp->srcRect;
dr.origin = sdp->destPoint;
if (cliprect2(&sr, srect, &dr, clip))
(*rop_clear)(fb, &dr);
sdp++;
}
return (FB_ROK);
}
static
batch_bitblt_fb(fb, sbp, clip, sdp, n)
register struct fbdev *fb;
register lBitmap *sbp;
register lRectangle *clip;
register lSrcDest *sdp;
register int n;
{
register int wplane, i, j;
lRectangle sr;
lRectangle dr;
fbbm_rop_init(fb, fb->funcvec);
switch (fb->Mode) {
case MODE_1to1:
fb->Pmask &= 1;
while (--n >= 0) {
sr = sdp->srcRect;
dr.origin = sdp->destPoint;
if (cliprect2(&sr, &sbp->rect, &dr, clip))
fbbm_rop_copy(fb, &sr, &dr.origin, 0, fb->Pmask);
sdp++;
}
break;
case MODE_NtoN:
while (--n >= 0) {
sr = sdp->srcRect;
dr.origin = sdp->destPoint;
if (cliprect2(&sr, &sbp->rect, &dr, clip))
fbbm_rop_copy(fb, &sr, &dr.origin, 0, fb->Pmask);
sdp++;
}
break;
case MODE_1toN:
while (--n >= 0) {
sr = sdp->srcRect;
dr.origin = sdp->destPoint;
if (cliprect2(&sr, &sbp->rect, &dr, clip))
fbbm_rop_copy(fb, &sr, &dr.origin, 1, fb->Pmask);
sdp++;
}
break;
case MODE_Nto1:
for (; --n >= 0; sdp++) {
sr = sdp->srcRect;
dr.origin = sdp->destPoint;
if (!cliprect2(&sr, &sbp->rect, &dr, clip))
continue;
wplane = 1;
for (i = 0, j = sbp->depth; i < j; i++) {
if (fb->Pmask & wplane) {
fbbm_rop_copy(fb, &sr, &dr.origin,
i + 1, fb->Pmask >> 16);
break;
}
wplane <<= 1;
}
}
break;
default:
return (FB_RERROR);
}
}
static
batch_bitblt_tofb(fb, sbp, dbp, crp, sdp, n)
register struct fbdev *fb;
register lBitmap *sbp; /* source bitmap (MEM) */
lBitmap *dbp; /* destination bitmap (FB) */
lRectangle *crp; /* clip region in destination */
register lSrcDest *sdp;
register int n;
{
register unsigned p;
register struct fb_map *smap;
register int i, j, m;
lRectangle sr;
lRectangle dr;
register int wplane;
#ifdef IPC_MRX
extern struct fb_map rommap;
register int pages;
#endif
fbbm_rop_winit(fb);
while (--n >= 0) {
sr = sdp->srcRect;
dr.origin = sdp->destPoint;
if (crp && !cliprect2(&sr, &sbp->rect, &dr, crp)) {
sdp++;
continue;
}
dr.extent = sr.extent;
/* transform source rectangle */
sr.origin.x -= sbp->rect.origin.x;
sr.origin.y -= sbp->rect.origin.y;
/*
* check memory map specification
*/
smap = (struct fb_map*)sbp->base;
p = smap->fm_offset;
#ifdef IPC_MRX
pages = btoc(smap->fm_offset + smap->fm_count);
rommap.fm_vaddr = fb_map_page(smap->fm_addr, pages,
fb->cache_off ? PG_S|PG_WP|PG_CI : PG_S|PG_WP);
rommap.fm_offset = 0;
smap = &rommap;
#endif
wplane = 1;
switch (fb->Mode) {
case MODE_1to1:
fbbm_rop_write(fb, smap, p, sbp->width,
&sr, &dr, fb->Pmask & 0x01);
break;
case MODE_1toN:
fbbm_rop_write(fb, smap, p, sbp->width,
&sr, &dr, fb->Pmask);
break;
case MODE_Nto1:
m = sbp->width * sbp->rect.extent.y;
for (i = 0; i < sbp->depth; i++, wplane <<= 1) {
if (fb->Pmask & wplane) {
p += (m * i) << 1;
fbbm_rop_write(fb, smap, p, sbp->width,
&sr, &dr, wplane);
break;
}
wplane <<= 1;
}
break;
case MODE_NtoN:
j = min(sbp->depth, fb->fbNplane);
m = sbp->width * sbp->rect.extent.y;
p += (m << 1) * j;
wplane = 1 << (j - 1);
for (i = j; i > 0; i--) {
/* get next plane */
p -= m << 1;
if (fb->Pmask & wplane)
fbbm_rop_write(fb, smap, p, sbp->width,
&sr, &dr, wplane);
/* next plane mask */
wplane >>= 1;
}
break;
default:
return (-1);
}
sdp++;
}
return (0);
}
batchbitbltcmd(fb, cmd)
register struct fbdev *fb;
register lBatchBitblt *cmd;
{
register int n;
register lSrcDest *sdp;
register int (*blt)();
lRectangle cr;
#ifdef CPU_SINGLE
struct fb_map *map;
unsigned int p;
#endif
int error;
if (setrop(fb, cmd->func, cmd->planemask,
cmd->fore_color, cmd->aux_color,
cmd->transp, &cmd->srcBitmap, &cmd->destBitmap) < 0)
return (FB_RERROR);
cr = cmd->destClip;
if (!getclip(fb, &cmd->destBitmap, &cr))
return (FB_ROK);
if (!clipsrc(fb, &cmd->srcBitmap))
return (0);
#ifdef CPU_SINGLE
map = (struct fb_map *)(cmd->srcDestList);
p = map->fm_offset;
sdp = (lSrcDest *)TypeAt(map, p);
#else
sdp = cmd->srcDestList;
#endif
n = cmd->nSrcDest;
cursorCheck(fb, cmd->srcBitmap.type, &cmd->srcBitmap.rect,
cmd->destBitmap.type, &cr);
blt = sel_ropfunc(cmd->srcBitmap.type, cmd->destBitmap.type);
if (blt == bitblt_0tofb || blt == bitblt_1tofb) {
if (error =
batch_bitblt_01tofb(fb, &cmd->srcBitmap, &cr, sdp, n,
blt == bitblt_1tofb)) {
cursorOn(fb);
return (error);
}
} else if (blt == bitblt_fb) {
if (error =
batch_bitblt_fb(fb, &cmd->srcBitmap, &cr, sdp, n)) {
cursorOn(fb);
return (error);
}
} else if (blt == bitblt_tofb) {
if (error =
batch_bitblt_tofb(fb, &cmd->srcBitmap, &cmd->destBitmap,
&cr, sdp, n)) {
cursorOn(fb);
return (error);
}
} else
while (--n >= 0) {
if ((*blt)(fb, &cmd->srcBitmap, &sdp->srcRect,
&cmd->destBitmap, &sdp->destPoint, &cr) < 0) {
cursorOn(fb);
return (FB_RERROR);
}
PRE_EMPT;
sdp++;
}
cursorOn(fb);
return (FB_ROK);
}
tilebitbltcmd(fb, cmd)
struct fbdev *fb;
register lTileBitblt *cmd;
{
lRectangle trect, rect, prect;
lPoint dp;
register int dx;
int dy;
register int offx, offy;
register int xlen, ylen;
int first;
register int (*blt)();
int t;
rect = cmd->destRect;
prect = cmd->ptnRect;
if (prect.extent.x <= 0 || prect.extent.y <= 0)
return;
if (cmd->ptnBitmap.type == BM_FB &&
!cliprect(&cmd->ptnBitmap.rect, &fb->FrameRect, (lRectangle*)0))
return;
/* clip pattern rectangle */
if (!cliprect(&prect, &cmd->ptnBitmap.rect, (lRectangle *)0))
return;
if (!getclip(fb, &cmd->destBitmap, &cmd->destClip)) return;
if (!cliprect(&rect, &cmd->destClip, (lRectangle *)0))
return;
if (setrop(fb, cmd->func, cmd->planemask, cmd->fore_color, cmd->aux_color,
cmd->transp, &cmd->ptnBitmap, &cmd->destBitmap) < 0)
return (FB_RERROR);
blt = sel_ropfunc(cmd->ptnBitmap.type, cmd->destBitmap.type);
offx = MOD(rect.origin.x - cmd->refPoint.x, prect.extent.x, t);
offy = MOD(rect.origin.y - cmd->refPoint.y, prect.extent.y, t);
dp = rect.origin;
trect.origin.x = prect.origin.x + offx;
trect.origin.y = prect.origin.y + offy;
dy = rect.extent.y;
cursorCheck(fb, cmd->ptnBitmap.type, &prect, cmd->destBitmap.type, &rect);
first = 1;
while (dy > 0) {
if (first) { /* for the first time */
ylen = prect.extent.y - offy;
ylen = min(ylen, dy);
trect.extent.y = ylen;
trect.origin.y = prect.origin.y + offy;
first = 0;
} else {
ylen = min(prect.extent.y, dy);
trect.extent.y = ylen;
trect.origin.y = prect.origin.y;
}
dp.x = rect.origin.x;
dx = rect.extent.x;
xlen = prect.extent.x - offx;
trect.origin.x = prect.origin.x + offx;
if (dx < xlen) {
trect.extent.x = dx;
(*blt)(fb, &cmd->ptnBitmap, &trect, &cmd->destBitmap, &dp, (lRectangle *)0);
} else {
trect.extent.x = xlen;
(*blt)(fb, &cmd->ptnBitmap, &trect, &cmd->destBitmap, &dp, (lRectangle *)0);
dp.x += xlen;
dx -= xlen;
trect.origin.x = prect.origin.x;
while (dx > 0) {
xlen = min(dx, prect.extent.x);
trect.extent.x = xlen;
(*blt)(fb, &cmd->ptnBitmap, &trect, &cmd->destBitmap, &dp, (lRectangle *)0);
dp.x += xlen;
dx -= xlen;
}
}
dp.y += ylen;
dy -= ylen;
}
cursorOn(fb);
}
bitblt3cmd(fb, cmd)
struct fbdev fb;
lBitblt3 *cmd;
{
return (FB_ROK);
}
draw_rectangle(fb, dp)
struct fbdev *fb;
lPrimRect *dp;
{
lRectangle trect, rect, prect;
lPoint p;
register int dx;
int dy;
register int offx, offy;
register int xlen, ylen;
int first;
register int (*blt)();
int t;
rect = dp->rect;
prect = dp->ptnRect;
if (prect.extent.x <= 0 || prect.extent.y <= 0)
return;
if (dp->ptnBM.type == BM_FB &&
!cliprect(&dp->ptnBM.rect, &fb->FrameRect, (lRectangle*)0))
return;
/* clip pattern rectangle */
if (!cliprect(&prect, &dp->ptnBM.rect, (lRectangle *)0))
return;
if (!getclip(fb, &dp->drawBM, &dp->clip)) return;
if (!cliprect(&rect, &dp->clip, (lRectangle *)0))
return;
if (setrop(fb, dp->func, dp->planemask, dp->fore_color, dp->aux_color,
dp->transp, &dp->ptnBM, &dp->drawBM) < 0)
return (FB_RERROR);
blt = sel_ropfunc(dp->ptnBM.type, dp->drawBM.type);
offx = MOD(rect.origin.x - dp->refPoint.x, prect.extent.x, t);
offy = MOD(rect.origin.y - dp->refPoint.y, prect.extent.y, t);
p = rect.origin;
trect.origin.x = prect.origin.x + offx;
trect.origin.y = prect.origin.y + offy;
dy = rect.extent.y;
cursorCheck(fb, dp->ptnBM.type, &prect, dp->drawBM.type, &rect);
first = 1;
while (dy > 0) {
if (first) { /* for the first time */
ylen = prect.extent.y - offy;
ylen = min(ylen, dy);
trect.extent.y = ylen;
trect.origin.y = prect.origin.y + offy;
first = 0;
} else {
ylen = min(prect.extent.y, dy);
trect.extent.y = ylen;
trect.origin.y = prect.origin.y;
}
p.x = rect.origin.x;
dx = rect.extent.x;
xlen = prect.extent.x - offx;
trect.origin.x = prect.origin.x + offx;
if (dx < xlen) {
trect.extent.x = dx;
(*blt)(fb, &dp->ptnBM, &trect, &dp->drawBM, &p, (lRectangle *)0);
} else {
trect.extent.x = xlen;
(*blt)(fb, &dp->ptnBM, &trect, &dp->drawBM, &p, (lRectangle *)0);
p.x += xlen;
dx -= xlen;
trect.origin.x = prect.origin.x;
while (dx > 0) {
xlen = min(dx, prect.extent.x);
trect.extent.x = xlen;
(*blt)(fb, &dp->ptnBM, &trect, &dp->drawBM, &p, (lRectangle *)0);
p.x += xlen;
dx -= xlen;
}
}
p.y += ylen;
dy -= ylen;
}
cursorOn(fb);
}
draw_polymarker(fb, dp)
struct fbdev *fb;
register lPrimMarker *dp;
{
register lPoint *ps;
register int np;
lRectangle cr;
register int (*blt)();
#ifdef CPU_SINGLE
struct fb_map *map;
unsigned int p;
#endif
cr = dp->clip;
if ((dp->drawBM.type == BM_FB) &&
!getclip(fb, &dp->drawBM, &cr))
return (FB_ROK);
if (dp->ptnBM.type == BM_FB &&
!cliprect(&dp->ptnBM.rect, &fb->FrameRect, (lRectangle*)0))
return (FB_ROK);
if (setrop(fb, dp->func, dp->planemask, dp->fore_color, dp->aux_color,
dp->transp, &dp->ptnBM, &dp->drawBM) < 0)
return (FB_RERROR);
blt = sel_ropfunc(dp->ptnBM.type, dp->drawBM.type);
cursorCheck(fb, dp->ptnBM.type, &(dp->ptnRect), dp->drawBM.type, &cr);
#ifdef CPU_SINGLE
map = (struct fb_map *)(dp->plist);
p = map->fm_offset;
ps = (lPoint *)TypeAt(map, p);
#else
ps = dp->plist;
#endif
np = dp->np;
while (--np >= 0) {
(*blt)(fb, &dp->ptnBM, &dp->ptnRect, &dp->drawBM, ps++, &cr);
PRE_EMPT;
}
cursorOn(fb);
return (FB_ROK);
}
static int patternx;
static int patterny;
static int patternwidth;
static lBitmap *pbm; /* pattern bitmap */
static lBitmap *drawbm; /* drawing bitmap */
static int (*blt)();
static
fill_line(fb, len, dp, offx, offy)
register struct fbdev *fb;
register int len;
register lPoint *dp;
int offx, offy;
{
register int plen;
static lRectangle srec = { 0, 0, 0, 1 };
srec.origin.x = patternx + offx;
srec.origin.y = patterny + offy;
if ((plen = patternwidth - offx) > len) {
srec.extent.x = len;
(*blt)(fb, pbm, &srec, drawbm, dp, (lRectangle *)0);
return;
}
srec.extent.x = plen;
(*blt)(fb, pbm, &srec, drawbm, dp, (lRectangle *)0);
dp->x += plen;
len -= plen;
srec.origin.x = patternx;
plen = patternwidth;
while (len > 0) {
srec.extent.x = min(plen, len);
(*blt)(fb, pbm, &srec, drawbm, dp, (lRectangle *)0);
dp->x += plen;
len -= plen;
}
}
fill_scan(fb, fdata)
register struct fbdev *fb;
register lPrimFill *fdata;
{
register lScanl *ls;
int nscan;
lRectangle clip;
lRectangle prect;
register int minx, maxx, miny, maxy;
#ifdef CPU_SINGLE
struct fb_map *map;
#endif
register void (*rop_clear)();
int (*sel_ropfunc())();
if ((nscan = fdata->nscan) <= 0)
return (FB_RERROR);
/* clip pattern rectangle */
prect = fdata->ptnRect;
if (!getclip(fb, &fdata->ptnBM, &prect))
return (0);
if (prect.extent.x <= 0 || prect.extent.y <= 0)
return (FB_RERROR);
/* clip clip rectangle */
clip = fdata->clip;
if (!getclip(fb, &fdata->drawBM, &clip))
return (0);
if (setrop(fb, fdata->func, fdata->planemask,
fdata->fore_color, fdata->aux_color, fdata->transp,
&fdata->ptnBM, &fdata->drawBM) < 0)
return (FB_RERROR);
#ifdef CPU_SINGLE
map = (struct fb_map *)(fdata->scan);
ls = (lScanl *)TypeAt(map, map->fm_offset);
#else
ls = fdata->scan;
#endif
minx = clip.origin.x;
maxx = minx + clip.extent.x - 1;
miny = clip.origin.y;
maxy = miny + clip.extent.y - 1;
cursorCheck(fb, fdata->ptnBM.type, &prect, fdata->drawBM.type, &clip);
blt = sel_ropfunc(fdata->ptnBM.type, fdata->drawBM.type);
if (blt == bitblt_1tofb || blt == bitblt_0tofb) {
lRectangle dr;
if (fb->fbbm_op->fb_rop_fillscan != (void (*)())nofunc) {
fbbm_rop_fillscan(fb, ls, nscan, &clip,
blt == bitblt_1tofb);
goto out;
}
dr.extent.y = 1;
fbbm_rop_cinit(fb, fb->Pmask, blt == bitblt_1tofb);
rop_clear = fb->fbbm_op->fb_rop_clear;
while (--nscan >= 0) {
if ((dr.origin.y = ls->y) >= miny &&
dr.origin.y <= maxy) {
dr.origin.x = max(ls->x0, minx);
if ((dr.extent.x =
min(ls->x1, maxx) - dr.origin.x + 1) > 0)
(*rop_clear)(fb, &dr);
}
ls++;
}
} else {
int len;
int refx, refy;
lPoint dp;
int sizex, sizey;
int t;
sizex = prect.extent.x;
sizey = prect.extent.y;
refx = fdata->refPoint.x;
refy = fdata->refPoint.y;
patternx = prect.origin.x;
patterny = prect.origin.y;
patternwidth = sizex;
pbm = &fdata->ptnBM;
drawbm = &fdata->drawBM;
while (--nscan >= 0) {
if ((dp.y = ls->y) >= miny && dp.y <= maxy) {
dp.x = max(ls->x0, minx);
if ((len = min(ls->x1, maxx) - dp.x + 1) > 0)
fill_line(fb, len, &dp,
MOD((dp.x - refx), sizex, t),
MOD((dp.y - refy), sizey, t));
}
ls++;
}
}
out:
cursorOn(fb);
return (FB_ROK);
}
put_string(fb, sdata)
struct fbdev *fb;
lPrimText *sdata;
{
register int x, y;
register int ex_factor = sdata->ex_factor;
register unsigned c;
register unsigned char *str;
int len = sdata->len;
int flen;
int i, j, k, l;
unsigned fchar = sdata->first_chr;
unsigned lchar = sdata->last_chr;
lRectangle cr, save;
register int (*bltfunc)();
register char *f_addr; /* font address */
register char **fnt_addr;
static struct fb_map rommap;
#ifdef CPU_SINGLE
struct fb_map *map;
unsigned int p;
#endif
lBitmap *fontBM;
lRectangle srec;
lPoint dp;
extern int tmode; /* in ../bm/vt100if.c */
x = sdata->p.x << 16;
y = sdata->p.y << 16;
srec.extent.x = sdata->width;
srec.extent.y = sdata->height;
switch (sdata->type) {
case ASCII:
fontBM = &sdata->fontBM;
break;
case ROM_ASCII:
case ROM_CONS:
if (sdata->width >= 12 && sdata->height >= 24) {
if (fb->Krom_BM1.type == (char)0xff) {
fontBM = &fb->Krom_BM0;
srec.extent.x = fb->Krom_font_extent0.x>>1;
srec.extent.y = fb->Krom_font_extent0.y;
fnt_addr = ext_fnt_addr;
} else {
fontBM = &fb->Krom_BM1;
srec.extent.x = fb->Krom_font_extent1.x>>1;
srec.extent.y = fb->Krom_font_extent1.y;
fnt_addr = ext_fnt24_addr;
}
} else {
if (fb->Krom_BM0.type == (char)0xff) {
fontBM = &fb->Krom_BM1;
srec.extent.x = fb->Krom_font_extent1.x>>1;
srec.extent.y = fb->Krom_font_extent1.y;
fnt_addr = ext_fnt24_addr;
} else {
fontBM = &fb->Krom_BM0;
srec.extent.x = fb->Krom_font_extent0.x>>1;
srec.extent.y = fb->Krom_font_extent0.y;
fnt_addr = ext_fnt_addr;
}
}
if (srec.extent.x > sdata->width)
srec.extent.x = sdata->width;
if (srec.extent.y > sdata->height)
srec.extent.y = sdata->height;
flen = (fontBM->width<<1) * fontBM->rect.extent.y;
fontBM->base = (Word *)&rommap;
break;
case ROM_KANJI:
if (sdata->width >= 24 && sdata->height >= 24) {
if (fb->Krom_BM1.type == (char)0xff) {
fontBM = &fb->Krom_BM0;
srec.extent = fb->Krom_font_extent0;
fnt_addr = ext_fnt_addr;
} else {
fontBM = &fb->Krom_BM1;
srec.extent = fb->Krom_font_extent1;
fnt_addr = ext_fnt24_addr;
}
} else {
if (fb->Krom_BM0.type == (char)0xff) {
fontBM = &fb->Krom_BM1;
srec.extent = fb->Krom_font_extent1;
fnt_addr = ext_fnt24_addr;
} else {
fontBM = &fb->Krom_BM0;
srec.extent = fb->Krom_font_extent0;
fnt_addr = ext_fnt_addr;
}
}
if (srec.extent.x > sdata->width)
srec.extent.x = sdata->width;
if (srec.extent.y > sdata->height)
srec.extent.y = sdata->height;
save.extent.x = srec.extent.x;
flen = (fontBM->width<<1) * fontBM->rect.extent.y;
fontBM->base = (Word *)&rommap;
break;
default:
return (FB_RERROR);
}
/* get clipping rectangle */
cr = sdata->clip;
if (!getclip(fb, &sdata->drawBM, &cr))
return (FB_ROK);
/* set rop code */
if (setrop(fb, sdata->func, sdata->planemask,
sdata->fore_color, sdata->aux_color,
sdata->transp, fontBM, &sdata->drawBM) < 0)
return (FB_RERROR);
/* select rop function */
bltfunc = sel_ropfunc(fontBM->type, sdata->drawBM.type);
#ifdef CPU_SINGLE
map = (struct fb_map *)(sdata->str);
p = map->fm_offset;
str = (unsigned char *)TypeAt(map, p);
#else
str = sdata->str;
#endif
cursorCheck(fb, fontBM->type, &fontBM->rect, sdata->drawBM.type, &cr);
switch (sdata->type) {
case ASCII:
if (sdata->column == 0)
return (FB_RERROR);
while (len-- > 0) {
c = *str++;
if (c < fchar || c > lchar)
continue;
c -= fchar;
srec.origin.x = sdata->fp.x
+ sdata->width * (c % sdata->column);
srec.origin.y = sdata->fp.y
+ sdata->height * (c / sdata->column);
dp.x = x >> 16;
dp.y = y >> 16;
if (ex_factor == 1) {
(*bltfunc)(fb, fontBM, &srec, &sdata->drawBM,
&dp, &cr);
} else {
srec.extent.x = 1;
for (i = 0; i < sdata->width; i++) {
for (j = 0; j < ex_factor; j++) {
(*bltfunc)(fb, fontBM, &srec,
&sdata->drawBM,
&dp, &cr);
dp.x++;
PRE_EMPT;
}
srec.origin.x++;
}
}
x += sdata->dx;
y += sdata->dy;
}
break;
case ROM_ASCII:
case ROM_CONS:
#ifdef IPC_MRX
if (fb->type == FB_NWB251)
fb->cache_off = 1;
#endif
while (len-- > 0) {
c = *str++;
dp.x = x >> 16;
dp.y = y >> 16;
k = 0;
srec.origin.x = srec.origin.y = 0;
f_addr = 0;
if ((c >= 0x20) && (c <= 0x7e)) {
/*
* ASCII char
*/
f_addr = fnt_addr[c];
goto disp;
}
if (sdata->type == ROM_ASCII) {
if ((c >= 0xa1) && (c <= 0xdf)) {
/*
* KANA char
*/
f_addr = fnt_addr[c + 64];
goto disp;
}
}
if (sdata->type == ROM_CONS) {
#ifdef KM_ASCII
if (tmode == KM_ASCII) {
#endif
if ((c >= 0xa0) && (c <= 0xff)) {
/*
* ISO char
*/
f_addr = fnt_addr[c - 32];
goto disp;
}
#ifdef KM_ASCII
} else {
if ((c >= 0xa1) && (c <= 0xdf)) {
/*
* KANA char
*/
f_addr = fnt_addr[c + 64];
goto disp;
}
}
#endif
}
disp:
if (f_addr) {
/*
* not ROM font
* (font is in kernel data area)
*/
bltfunc = sel_ropfunc(BM_MEM,
sdata->drawBM.type);
rommap.fm_vaddr = f_addr;
rommap.fm_offset = 0;
#ifdef IPC_MRX
iopmemfbmap(f_addr, flen, &rommap);
#endif
k = 1;
l = fontBM->width;
fontBM->width = 1;
save = fontBM->rect;
fontBM->rect.origin = srec.origin;
fontBM->rect.extent.x = 12;
} else if (fontBM->type == BM_MEM) {
/*
* KANJI ROM except pop[cm]fb
*/
f_addr = fbbm_Krom_addr(fb, c, &srec);
rommap.fm_vaddr = f_addr;
rommap.fm_offset = 0;
#ifdef IPC_MRX
iopmemfbmap(f_addr, flen, &rommap);
#endif
} else {
/*
* XXX
* fontBM->type == BM_FB -> fbbm_pop[cm]
*
* see fbpop[cm]_setup() routine
* in fbbm_pop[cm].c
*/
bltfunc = sel_ropfunc(fontBM->type,
sdata->drawBM.type);
bzero((caddr_t)fontBM->base,
sizeof (struct fb_map));
fbbm_Krom_addr(fb, c, &srec);
fontBM->rect.origin = srec.origin;
}
if (ex_factor == 1) {
(*bltfunc)(fb, fontBM, &srec, &sdata->drawBM,
&dp, &cr);
} else {
srec.extent.x = 1;
for (i = 0; i < sdata->width; i++) {
for (j = 0; j < ex_factor; j++) {
(*bltfunc)(fb, fontBM, &srec,
&sdata->drawBM,
&dp, &cr);
dp.x++;
}
srec.origin.x++;
}
}
PRE_EMPT;
if (k != 0) {
fontBM->rect = save;
fontBM->width = l;
}
x += sdata->dx;
y += sdata->dy;
}
#ifdef IPC_MRX
fb->cache_off = 0;
#endif
break;
case ROM_KANJI:
#ifdef IPC_MRX
if (fb->type == FB_NWB251)
fb->cache_off = 1;
#endif
while (len > 1) {
c = *str++;
c <<= 8;
c |= *str++;
dp.x = x >> 16;
dp.y = y >> 16;
srec.origin.x = srec.origin.y = 0;
if (fontBM->type == BM_MEM) {
/*
* KANJI ROM except pop[cm]fb
*/
f_addr = fbbm_Krom_addr(fb, c, &srec);
rommap.fm_vaddr = f_addr;
rommap.fm_offset = 0;
#ifdef IPC_MRX
iopmemfbmap(f_addr, flen, &rommap);
#endif
} else {
/*
* XXX
* fontBM->type == BM_FB ---> fbbm_pop[cm]
*
* see fbpop[cm]_setup() in fbbm_pop[cm].c
*/
bzero((caddr_t)fontBM->base,
sizeof (struct fb_map));
fbbm_Krom_addr(fb, c, &srec);
fontBM->rect.origin = srec.origin;
}
if (ex_factor == 1) {
(*bltfunc)(fb, fontBM, &srec, &sdata->drawBM,
&dp, &cr);
} else {
srec.extent.x = 1;
for (i = 0; i < sdata->width; i++) {
for (j = 0; j < ex_factor; j++) {
(*bltfunc)(fb, fontBM, &srec,
&sdata->drawBM,
&dp, &cr);
dp.x++;
}
srec.origin.x++;
}
srec.extent.x = save.extent.x;
}
PRE_EMPT;
x += sdata->dx;
y += sdata->dy;
len -= 2;
}
#ifdef IPC_MRX
fb->cache_off = 0;
#endif
break;
default:
cursorOn(fb);
return (FB_RERROR);
}
cursorOn(fb);
return (FB_ROK);
}
void
linerop(fb, func, fore, aux, trans)
struct fbdev *fb;
register unsigned func;
register int fore;
register int aux;
int trans;
{
register char *funcv;
register int i;
char tmp[4];
/* set rop function register */
func &= 0xf;
tmp[0] = TRANS(trans, (func & 0x0c) | (func >> 2));
tmp[1] = TRANS(trans, (func >> 2) | ((func << 2) & 0x0c));
tmp[2] = TRANS(trans, func);
tmp[3] = TRANS(trans, (func << 2) & 0x0c | func & 3);
funcv = fb->funcvec;
for (i = fb->fbNplane; --i >= 0;) {
*funcv++ = tmp[((fore & 1) << 1) | (aux & 1)];
fore >>= 1; aux >>= 1;
}
}
/*
* line clipping routine
*
* DRAW visual
* NODRAW not visual
*/
lineclip(p0, p1, r)
register lPoint *p0;
register lPoint *p1;
register lRectangle *r; /* clipping rectangle */
{
register lPoint *ptmp;
register int d0, d1, d2, limit;
/* sort 2 points by x-coordinate */
if (p0->x > p1->x) {
ptmp = p1;
p1 = p0;
p0 = ptmp;
}
limit = r->origin.x;
d0 = p1->y - p0->y;
d1 = p1->x - p0->x;
if ((d2 = limit - p0->x) > 0) {
if (p1->x < limit)
return (NODRAW);
p0->y += d2 * d0 / d1;
p0->x = limit;
}
limit += r->extent.x - 1;
if ((d2 = limit - p1->x) < 0) {
if (p0->x > limit)
return (NODRAW);
p1->y += d2 * d0 / d1;
p1->x = limit;
}
/* sort 2 points by y-coordinate */
if (p0->y > p1->y) {
ptmp = p1;
p1 = p0;
p0 = ptmp;
}
limit = r->origin.y;
d0 = p1->x - p0->x;
d1 = p1->y - p0->y;
if ((d2 = limit - p0->y) > 0) {
if (p1->y < limit)
return (NODRAW);
p0->x += d2 * d0 / d1;
p0->y = limit;
}
limit += r->extent.y - 1;
if ((d2 = limit - p1->y) < 0) {
if (p0->y > limit)
return (NODRAW);
p1->x += d2 * d0 / d1;
p1->y = limit;
}
return (DRAW);
}
#ifndef CPU_DOUBLE
/*
void
point(p, x, s, fp)
register char *p;
register int x;
register int s;
register char *fp;
{
x = 7 - (x & 7);
if ((1 << (3 - (((s & 1) << 1) | ((*p >> x) & 1)))) & *fp)
*p |= (1 << x);
else
*p &= ~(1 << x);
}
*/
#define point(p, x, s, fp) { \
int xx = 7 - ((x) & 7); \
if ((1 << (3 - ((((s) & 1) << 1) | ((*(p) >> xx) & 1)))) & *(fp)) \
*(p) |= (1 << xx); \
else \
*(p) &= ~(1 << xx); \
}
mem_vector(fb, p0, p1, mask, dbmp, lpf)
struct fbdev *fb;
lPoint *p0, *p1;
int mask; /* plane mask */
lBitmap *dbmp; /* drawing bitmap */
int lpf; /* if 0, don't draw last point */
{
register struct fb_map *map = (struct fb_map *)dbmp->base;
register char *funcv = fb->funcvec; /* rop function */
int p = (int)map->fm_offset;
register int pmask;
register unsigned int pat;
register int x = p0->x;
register int y = p0->y;
register char *fp;
int width = dbmp->width << 1;
int lim;
int size = width * dbmp->rect.extent.y;
int ddx, ddy;
int s, d, c;
int dx = p1->x - x;
int dy = p1->y - y;
int i, j;
int depth = dbmp->depth;
/* transformation */
x -= dbmp->rect.origin.x;
y -= dbmp->rect.origin.y;
pat = fb->pat;
ddx = 1;
ddy = dbmp->width << 1;
y = (int)p + y * ddy;
if (dx == 0)
ddx = 0;
else if (dx < 0) {
dx = -dx;
ddx = -ddx;
}
if (dy == 0)
ddy = 0;
else if (dy < 0) {
dy = -dy;
ddy = -ddy;
}
if (dx > dy) { /* case x */
lim = dx;
if (lpf)
lim++;
s = -dx;
d = dx << 1;
c = dy << 1;
for (i = lim; i > 0; i--) {
(int)p = y + (x >> 3);
pat = (pat << 1) | ((pat & 0x80000000) ? 1: 0);
fp = funcv;
pmask = mask;
for (j = depth; j > 0; j--) {
if (pmask & 1) {
point(_TypeAt(map, p), x, pat, fp);
}
p += size;
pmask >>= 1;
fp++;
}
if ((s += c) >= 0) {
s -= d;
y += ddy;
}
x += ddx;
}
} else { /* case y */
lim = dy;
if (lpf)
lim++;
s = -dy;
d = dy << 1;
c = dx << 1;
for (i = lim; i > 0; i--) {
(int)p = y + (x >> 3);
pat = (pat << 1) | ((pat & 0x80000000) ? 1: 0);
fp = funcv;
pmask = mask;
for (j = depth; j > 0; j--) {
if (pmask & 1) {
point(_TypeAt(map, p), x, pat, fp);
}
p += size;
pmask >>= 1;
fp++;
}
if ((s += c) >= 0) {
s -= d;
x += ddx;
}
y += ddy;
}
}
/* rotate pattern */
pat = fb->pat;
{
register int tmp;
tmp = lim & 31;
pat = (pat << tmp) | (pat >> (32 - tmp));
}
fb->pat = pat;
}
#endif /* !CPU_DOUBLE */
/* polyline drawing */
draw_polyline(fb, dp)
struct fbdev *fb;
register lPrimLine *dp;
{
register lPoint *ps;
lPoint p0, p1;
register int np;
lRectangle clip, *clipp;
#ifdef CPU_SINGLE
struct fb_map *map;
unsigned int p;
#endif
/* clip rectangle */
clip = dp->clip;
if (clip.origin.x == -1)
clipp = 0;
else {
clipp = &clip;
if (!getclip(fb, &dp->drawBM, clipp)) return 0;
}
#ifdef CPU_SINGLE
map = (struct fb_map *)(dp->plist);
p = map->fm_offset;
ps = (lPoint *)TypeAt(map, p);
#else
ps = dp->plist;
#endif
if (dp->drawBM.type == BM_FB) {
cursorCheck(fb, ~BM_FB, 0, dp->drawBM.type, clipp);
fbbm_rop_vect(fb, clipp, dp->func, dp->fore_color,
dp->aux_color, dp->transp, dp->planemask,
dp->np, ps, dp->lptn, (dp->dlpf)?1:0, 1);
cursorOn(fb);
return(FB_ROK);
}
#ifndef CPU_DOUBLE
linerop(fb, dp->func, dp->fore_color, dp->aux_color, dp->transp);
p0 = *ps++;
np = dp->np - 1;
fb->pat = dp->lptn;
if (clipp) {
while (--np > 0) {
p1 = *ps;
if (lineclip(&p0, &p1, clipp)) {
mem_vector(fb, &p0, &p1,
dp->planemask, &dp->drawBM,
ps->x != p1.x || ps->y != p1.y);
PRE_EMPT;
}
p0 = *ps++;
}
p1 = *ps;
if (lineclip(&p0, &p1, clipp)) {
mem_vector(fb, &p0, &p1, dp->planemask, &dp->drawBM,
ps->x != p1.x || ps->y != p1.y || dp->dlpf);
}
} else {
while (--np > 0) {
p1 = *ps;
mem_vector(fb, &p0, &p1, dp->planemask, &dp->drawBM, 0);
PRE_EMPT;
p0 = *ps++;
}
p1 = *ps;
mem_vector(fb, &p0, &p1, dp->planemask, &dp->drawBM, dp->dlpf);
}
#endif /* !CPU_DOUBLE */
return (FB_ROK);
}
/* disjoint polyline drawing */
draw_dj_polyline(fb, dp)
struct fbdev *fb;
register lPrimLine *dp;
{
register lPoint *ps;
lPoint p0, p1;
register int np;
lRectangle clip, *clipp;
#ifdef CPU_SINGLE
struct fb_map *map;
unsigned int p;
#endif
int lpf = (dp->dlpf)?1:0;
/* clip rectangle */
clip = dp->clip;
if (clip.origin.x == -1)
clipp = 0;
else {
clipp = &clip;
if(!getclip(fb, &dp->drawBM, clipp)) return (0);
}
#ifdef CPU_SINGLE
map = (struct fb_map *)(dp->plist);
p = map->fm_offset;
ps = (lPoint *)TypeAt(map, p);
#else
ps = dp->plist;
#endif
if (dp->drawBM.type == BM_FB) {
cursorCheck(fb, ~BM_FB, 0, dp->drawBM.type, clipp);
fbbm_rop_vect(fb, clipp, dp->func, dp->fore_color,
dp->aux_color, dp->transp, dp->planemask,
dp->np, ps, dp->lptn, lpf, 0);
cursorOn(fb);
PRE_EMPT;
return (FB_ROK);
}
#ifndef CPU_DOUBLE
linerop(fb, dp->func, dp->fore_color, dp->aux_color, dp->transp);
np = dp->np >> 1;
if (lpf) {
if (clipp) {
while (--np >= 0) {
p0 = *ps++;
p1 = *ps++;
fb->pat = dp->lptn;
if (lineclip(&p0, &p1, clipp)) {
mem_vector(fb, &p0, &p1,
dp->planemask, &dp->drawBM, 1);
PRE_EMPT;
}
}
} else {
while (--np >= 0) {
p0 = *ps++;
p1 = *ps++;
fb->pat = dp->lptn;
mem_vector(fb, &p0, &p1,
dp->planemask, &dp->drawBM, 1);
PRE_EMPT;
}
}
} else {
if (clipp) {
while (--np >= 0) {
p0 = *ps++;
p1 = *ps;
fb->pat = dp->lptn;
if (lineclip(&p0, &p1, clipp)) {
mem_vector(fb, &p0, &p1,
dp->planemask, &dp->drawBM,
ps->x != p1.x || ps->y != p1.y);
PRE_EMPT;
}
ps++;
}
} else {
while (--np >= 0) {
p0 = *ps++;
p1 = *ps++;
fb->pat = dp->lptn;
mem_vector(fb, &p0, &p1,
dp->planemask, &dp->drawBM, 0);
PRE_EMPT;
}
}
}
#endif /* !CPU_DOUBLE */
return (FB_ROK);
}
static lRectangle dotRect = {{ 0, 0 }, { 1, 1 }};
emulate_polydot(fb, dp)
struct fbdev *fb;
register lPrimDot *dp;
{
lPrimMarker marker;
lPrimMarker *cmdp;
register lPoint *ps;
register int np;
lRectangle cr;
register int (*blt)();
#ifdef CPU_SINGLE
struct fb_map *map;
unsigned int p;
#endif
cmdp = ▮
cmdp->func = dp->func;
cmdp->transp = dp->transp;
cmdp->fore_color = dp->fore_color;
cmdp->aux_color = dp->aux_color;
cmdp->planemask = dp->planemask;
cmdp->ptnRect = dotRect;
cmdp->ptnBM.type = BM_1;
cmdp->ptnBM.depth = 1;
cmdp->ptnBM.rect = dotRect;
cmdp->drawBM = dp->drawBM;
cmdp->clip = dp->clip;
cmdp->np = dp->np;
cmdp->plist = dp->plist;
return (draw_polymarker(fb, cmdp));
}
#ifndef CPU_DOUBLE
mem_dot(fb, p0, mask, dbmp)
struct fbdev *fb;
lPoint *p0;
register int mask; /* plane mask */
lBitmap *dbmp; /* drawing bitmap */
{
register struct fb_map *map = (struct fb_map *)dbmp->base;
register char *funcv; /* rop function */
register int p = (int)map->fm_offset;
register int depth;
int size;
int x, y;
x = p0->x - dbmp->rect.origin.x;
y = p0->y - dbmp->rect.origin.y;
size = (dbmp->width * dbmp->rect.extent.y) << 1;
p += y * (dbmp->width << 1) + (x >> 3);
funcv = fb->funcvec;
for (depth = dbmp->depth; --depth >= 0;) {
if (mask & 1) {
point(_TypeAt(map, p), x, ~0, funcv);
}
p += size;
mask >>= 1;
funcv++;
}
}
#endif /* !CPU_DOUBLE */
draw_polydot(fb, dp)
struct fbdev *fb;
register lPrimDot *dp;
{
register lPoint *ps;
lRectangle clip, *clipp;
register int np;
#ifdef CPU_SINGLE
struct fb_map *map;
unsigned int p;
#endif
if (fb->fbbm_op->fb_rop_dot == (void (*)())nofunc)
return (emulate_polydot(fb, dp));
/* clip rectangle */
clip = dp->clip;
if (clip.origin.x == -1)
clipp = 0;
else {
clipp = &clip;
if (!getclip(fb, &dp->drawBM, clipp)) return 0;
}
#ifdef CPU_SINGLE
map = (struct fb_map *)(dp->plist);
p = map->fm_offset;
ps = (lPoint *)TypeAt(map, p);
#else
ps = dp->plist;
#endif
if (dp->drawBM.type == BM_FB) {
cursorCheck(fb, ~BM_FB, 0, dp->drawBM.type, clipp);
fbbm_rop_dot(fb, clipp, dp->func, dp->fore_color,
dp->aux_color, dp->transp, dp->planemask,
dp->np, ps);
cursorOn(fb);
return(FB_ROK);
}
#ifndef CPU_DOUBLE
linerop(fb, dp->func, dp->fore_color, dp->aux_color, dp->transp);
np = dp->np;
if (clipp) {
register int x0, y0, x1, y1;
x0 = clipp->origin.x;
y0 = clipp->origin.y;
x1 = x0 + clipp->extent.x - 1;
y1 = y0 + clipp->extent.y - 1;
if (x1 <= 0 || y1 <= 0) return;
while (--np >= 0) {
if ((ps->x >= x0) && (ps->y >= y0) &&
(ps->x <= x1) && (ps->y <= y1)) {
mem_dot(fb, ps, dp->planemask, &dp->drawBM);
PRE_EMPT;
}
ps++;
}
} else {
while (--np >= 0) {
mem_dot(fb, ps, dp->planemask, &dp->drawBM);
PRE_EMPT;
ps++;
}
}
#endif /* !CPU_DOUBLE */
return (FB_ROK);
}
get_scrtype(fb, cmd)
register struct fbdev *fb;
register lScrType *cmd;
{
cmd->colorwidth = fb->Colorwidth;
cmd->plane = fb->fbNplane;
cmd->bufferrect = fb->FrameRect;
cmd->visiblerect = fb->VisRect;
cmd->type = fb->type;
cmd->unit = fb->unit;
return FB_ROK;
}
fbstart(fbaddr, dummy)
register struct fbreg *fbaddr;
int dummy;
{
register struct fbdev *fb = &fbdev[fbaddr->fb_device];
register int s;
FB_LOCK;
if (!fb) {
return (FB_RERROR);
}
/* reset dimmer count */
rst_dimmer_cnt();
switch(fbaddr->fb_command) {
case FB_CPROBE:
fbaddr->fb_data = search_fbdev(fbaddr->fb_device,
fbaddr->fb_unit);
fbaddr->fb_result = FB_ROK;
break;
case FB_CATTACH:
fbaddr->fb_result = get_scrtype(fb, &fbaddr->fb_scrtype);
break;
case FB_COPEN:
fbaddr->fb_result = fbbm_open(fb);
break;
case FB_CCLOSE:
fbaddr->fb_result = fbbm_close(fb);
break;
case FB_CSETDIM:
fbaddr->fb_result = fbbm_set_dimmer(fb, fbaddr->fb_data);
break;
case FB_CGETDIM:
if ((fbaddr->fb_data = fbbm_get_dimmer(fb)) == FB_RERROR)
fbaddr->fb_result = FB_RERROR;
else
fbaddr->fb_result = FB_ROK;
break;
case FB_CBITBLT:
fbaddr->fb_result = bitbltcmd(fb, &fbaddr->fb_bitblt);
break;
case FB_CBATCHBITBLT:
fbaddr->fb_result = batchbitbltcmd(fb, &fbaddr->fb_batchbitblt);
break;
case FB_CTILEBITBLT:
fbaddr->fb_result = tilebitbltcmd(fb, &fbaddr->fb_tilebitblt);
break;
case FB_CBITBLT3:
fbaddr->fb_result = bitblt3cmd(fb, &fbaddr->fb_bitblt3);
break;
case FB_CPOLYLINE:
fbaddr->fb_result = draw_polyline(fb, &fbaddr->fb_polyline);
break;
case FB_CDJPOLYLINE:
fbaddr->fb_result = draw_dj_polyline(fb, &fbaddr->fb_polyline);
break;
case FB_CRECTANGLE:
fbaddr->fb_result = draw_rectangle(fb, &fbaddr->fb_rectangle);
break;
case FB_CFILLSCAN:
fbaddr->fb_result = fill_scan(fb, &fbaddr->fb_fillscan);
break;
case FB_CPOLYMARKER:
fbaddr->fb_result = draw_polymarker(fb, &fbaddr->fb_polymarker);
break;
case FB_CTEXT:
fbaddr->fb_result = put_string(fb, &fbaddr->fb_text);
break;
case FB_CPOLYDOT:
fbaddr->fb_result = draw_polydot(fb, &fbaddr->fb_polydot);
break;
case FB_CGETSCRTYPE:
fbaddr->fb_result = get_scrtype(fb, &fbaddr->fb_scrtype);
break;
case FB_CSETPALETTE:
fbaddr->fb_result = fbbm_set_palette(fb, &fbaddr->fb_palette);
break;
case FB_CGETPALETTE:
fbaddr->fb_result = fbbm_get_palette(fb, &fbaddr->fb_palette);
break;
case FB_CSETCURSOR:
fbaddr->fb_result = setCursor(fb, &fbaddr->fb_cursor);
break;
case FB_CUNSETCURSOR:
fbaddr->fb_result = setCursor(fb, NULL);
break;
case FB_CSHOWCURSOR:
fbaddr->fb_result = showCursor(fb);
break;
case FB_CHIDECURSOR:
fbaddr->fb_result = hideCursor(fb);
break;
case FB_CSETXY:
fbaddr->fb_result = moveCursor(fb, &fbaddr->fb_point);
break;
case FB_CAUTODIM:
if (fbaddr->fb_data)
auto_dimmer_on(fb);
else
auto_dimmer_off(fb);
fbaddr->fb_result = FB_ROK;
break;
case FB_CSETVIDEO:
fbaddr->fb_result =
fbbm_ioctl(fb, FB_SETVIDEOCTL, &fbaddr->fb_videoctl);
break;
case FB_CGETVIDEO:
fbaddr->fb_result =
fbbm_ioctl(fb, FB_GETVIDEOSTATUS, &fbaddr->fb_videostatus);
break;
case FB_CSETPMODE:
fbaddr->fb_result =
fbbm_ioctl(fb, FB_SETPALETTEMODE, &fbaddr->fb_data);
break;
case FB_CGETPMODE:
fbaddr->fb_result =
fbbm_ioctl(fb, FB_GETPALETTEMODE, &fbaddr->fb_data);
break;
#ifdef CPU_SINGLE
case FB_CGETPAGE:
fbaddr->fb_data = fbbm_get_page(fb, fbaddr->fb_data);
if (fbaddr->fb_data == -1)
fbaddr->fb_result = FB_RERROR;
else
fbaddr->fb_result = FB_ROK;
break;
#endif
case FB_CIOCTL:
fbaddr->fb_fbioctl.request = fbbm_ioctl(fb,
fbaddr->fb_fbioctl.request, fbaddr->fb_fbioctl.param);
if (fbaddr->fb_fbioctl.request == -1)
fbaddr->fb_result = FB_RERROR;
else
fbaddr->fb_result = FB_ROK;
break;
default:
fbaddr->fb_result = FB_RERROR;
break;
}
#ifdef CPU_SINGLE
if (cfb && curs_pending) {
curs_pending = 0;
redrawCursor(cfb);
}
#endif
FB_UNLOCK;
}
|
813671.c | /**
* \file
* \brief Provides a generic startup function for the ARM OMAP platform
*/
/*
* Copyright (c) 2013, ETH Zurich.
* All rights reserved.
*
* This file is distributed under the terms in the attached LICENSE file.
* If you do not find this file, copies can be found by writing to:
* ETH Zurich D-INFK, Haldeneggsteig 4, CH-8092 Zurich. Attn: Systems Group.
*/
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <assert.h>
#include <barrelfish/barrelfish.h>
#include <barrelfish/spawn_client.h>
#include <arch/arm/omap44xx/device_registers.h>
#include "kaluga.h"
extern char **environ;
#ifdef __pandaboard__
struct allowed_registers
{
char* binary;
lpaddr_t registers[][2];
};
static struct allowed_registers usb = {
.binary = "hw.arm.omap44xx.usb",
.registers =
{
{OMAP44XX_HSUSBHOST, 0x1000},
{0x0, 0x0}
}
};
static struct allowed_registers fdif = {
.binary = "hw.arm.omap44xx.fdif",
.registers =
{
{OMAP44XX_CAM_CM2, 0x1000},
{OMAP44XX_DEVICE_PRM, 0x1000},
{OMAP44XX_CAM_PRM, 0x1000},
{OMAP44XX_FDIF, 0x1000},
{0x0, 0x0}
}
};
static struct allowed_registers mmchs = {
.binary = "hw.arm.omap44xx.mmchs",
.registers =
{
{OMAP44XX_CM2, 0x1000},
{OMAP44XX_CLKGEN_CM2, 0x1000},
{OMAP44XX_L4PER_CM2, 0x1000},
// i2c
{OMAP44XX_I2C1, 0x1000},
{OMAP44XX_I2C2, 0x1000},
{OMAP44XX_I2C3, 0x1000},
{OMAP44XX_I2C4, 0x1000},
// ctrlmodules
{OMAP44XX_SYSCTRL_GENERAL_CORE, 0X1000},
{OMAP44XX_SYSCTRL_GENERAL_WAKEUP, 0X1000},
{OMAP44XX_SYSCTRL_PADCONF_CORE, 0X1000},
{OMAP44XX_SYSCTRL_PADCONF_WAKEUP, 0X1000},
// MMCHS
{OMAP44XX_MMCHS1, 0x1000},
{OMAP44XX_MMCHS2, 0x1000},
{OMAP44XX_MMCHS3, 0x1000},
{OMAP44XX_MMCHS4, 0x1000},
{OMAP44XX_MMCHS5, 0x1000},
{0x0, 0x0}
}
};
static struct allowed_registers prcm = {
.binary = "hw.arm.omap44xx.prcm",
.registers =
{
{OMAP44XX_INTRCONN_SOCKET_PRM, 0x1000},
{OMAP44XX_DEVICE_PRM, 0x1000},
{OMAP44XX_I2C1, 0x1000},
{OMAP44XX_I2C2, 0x1000},
{OMAP44XX_I2C3, 0x1000},
{OMAP44XX_I2C4, 0x1000},
{0x0, 0x0}
}
};
static struct allowed_registers uart = {
.binary = "hw.arm.omap44xx.uart",
.registers =
{
{OMAP44XX_MAP_L4_PER_UART1,OMAP44XX_MAP_L4_PER_UART1_SIZE},
{OMAP44XX_MAP_L4_PER_UART2,OMAP44XX_MAP_L4_PER_UART2_SIZE},
{OMAP44XX_MAP_L4_PER_UART3,OMAP44XX_MAP_L4_PER_UART3_SIZE},
{OMAP44XX_MAP_L4_PER_UART4,OMAP44XX_MAP_L4_PER_UART4_SIZE},
{0x0, 0x0}
}
};
static struct allowed_registers sdma = {
.binary = "hw.arm.omap44xx.sdma",
.registers =
{
{OMAP44XX_SDMA, 0x1000},
{0x0, 0x0}
}
};
static struct allowed_registers* omap44xx[10] = {
&usb,
&fdif,
&mmchs,
&prcm,
&uart,
&sdma,
NULL,
};
/**
* \brief Startup function for OMAP drivers.
*
* Makes sure we get the device register capabilities.
*/
errval_t default_start_function(coreid_t where, struct module_info* driver,
char* record)
{
assert(driver != NULL);
assert(record != NULL);
errval_t err;
// TODO Request the right set of caps and put in device_range_cap
struct cnoderef dev_cnode;
struct capref dev_cnode_cap;
cslot_t retslots;
err = cnode_create(&dev_cnode_cap, &dev_cnode, 255, &retslots);
assert(err_is_ok(err));
struct capref device_cap;
device_cap.cnode = dev_cnode;
device_cap.slot = 0;
char* name;
err = oct_read(record, "%s", &name);
assert(err_is_ok(err));
KALUGA_DEBUG("%s:%d: Starting driver for %s\n", __FUNCTION__, __LINE__, name);
for (size_t i=0; omap44xx[i] != NULL; i++) {
if(strcmp(name, omap44xx[i]->binary) != 0) {
continue;
}
// Get the device cap from the managed capability tree
// put them all in a single cnode
for (size_t j=0; omap44xx[i]->registers[j][0] != 0x0; j++) {
struct capref device_frame;
KALUGA_DEBUG("%s:%d: mapping 0x%"PRIxLPADDR" %"PRIuLPADDR"\n", __FUNCTION__, __LINE__,
omap44xx[i]->registers[j][0], omap44xx[i]->registers[j][1]);
lpaddr_t base = omap44xx[i]->registers[j][0] & ~(BASE_PAGE_SIZE-1);
err = get_device_cap(base,
omap44xx[i]->registers[j][1],
&device_frame);
assert(err_is_ok(err));
err = cap_copy(device_cap, device_frame);
assert(err_is_ok(err));
device_cap.slot++;
}
}
free(name);
err = spawn_program_with_caps(0, driver->path, driver->argv, environ,
NULL_CAP, dev_cnode_cap, 0, driver->did);
if (err_is_fail(err)) {
DEBUG_ERR(err, "Spawning %s failed.", driver->path);
return err;
}
return SYS_ERR_OK;
}
#endif
|
834137.c | #include <u.h>
#include <libc.h>
void
main(int argc, char *argv[])
{
int nflag;
int i, len;
char *buf, *p;
nflag = 0;
if(argc > 1 && strcmp(argv[1], "-n") == 0)
nflag = 1;
len = 1;
for(i = 1+nflag; i < argc; i++)
len += strlen(argv[i])+1;
buf = malloc(len);
if(buf == 0)
exits("no memory");
p = buf;
for(i = 1+nflag; i < argc; i++)
p += sprint(p, i == argc-1 ? "%s":"%s ", argv[i]);
if(!nflag)
sprint(p, "\n");
if(write(1, buf, strlen(buf)) < 0)
fprint(2, "echo: write error: %r\n");
exits((char *)0);
}
|
380577.c | #include <stdio.h>
int main(void)
{
int number, digit_1, remainder, digit_2, digit_3;
printf("Enter a three-digit number:");
scanf("%d", &number);
digit_1 = number / 100;
remainder = number % 100;
digit_2 = remainder / 10;
digit_3 = remainder % 10;
printf("The reversal is: %d%d%d", digit_3, digit_2, digit_1);
return 0;
} |
992900.c | #ifndef lint
static char rcsid[] = "$Header: /usr/people/sam/tiff/libtiff/RCS/tif_lzw.c,v 1.37 92/02/12 11:27:28 sam Exp $";
#endif
/*
* Copyright (c) 1988, 1989, 1990, 1991, 1992 Sam Leffler
* Copyright (c) 1991, 1992 Silicon Graphics, Inc.
*
* Permission to use, copy, modify, distribute, and sell this software and
* its documentation for any purpose is hereby granted without fee, provided
* that (i) the above copyright notices and this permission notice appear in
* all copies of the software and related documentation, and (ii) the names of
* Sam Leffler and Silicon Graphics may not be used in any advertising or
* publicity relating to the software without the specific, prior written
* permission of Sam Leffler and Silicon Graphics.
*
* THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND,
* EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY
* WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
*
* IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR
* ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND,
* OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
* WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF
* LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
* OF THIS SOFTWARE.
*/
/*
* TIFF Library.
* Rev 5.0 Lempel-Ziv & Welch Compression Support
*
* This code is derived from the compress program whose code is
* derived from software contributed to Berkeley by James A. Woods,
* derived from original work by Spencer Thomas and Joseph Orost.
*
* The original Berkeley copyright notice appears below in its entirety.
*/
#include "tiffioP.h"
#include <stdio.h>
#include <assert.h>
#include "prototypes.h"
#define MAXCODE(n) ((1 << (n)) - 1)
/*
* The TIFF spec specifies that encoded bit strings range
* from 9 to 12 bits. This is somewhat unfortunate in that
* experience indicates full color RGB pictures often need
* ~14 bits for reasonable compression.
*/
#define BITS_MIN 9 /* start with 9 bits */
#define BITS_MAX 12 /* max of 12 bit strings */
/* predefined codes */
#define CODE_CLEAR 256 /* code to clear string table */
#define CODE_EOI 257 /* end-of-information code */
#define CODE_FIRST 258 /* first free code entry */
#define CODE_MAX MAXCODE(BITS_MAX)
#ifdef notdef
#define HSIZE 9001 /* 91% occupancy */
#define HSHIFT (8-(16-13))
#else
#define HSIZE 5003 /* 80% occupancy */
#define HSHIFT (8-(16-12))
#endif
/*
* NB: The 5.0 spec describes a different algorithm than Aldus
* implements. Specifically, Aldus does code length transitions
* one code earlier than should be done (for real LZW).
* Earlier versions of this library implemented the correct
* LZW algorithm, but emitted codes in a bit order opposite
* to the TIFF spec. Thus, to maintain compatibility w/ Aldus
* we interpret MSB-LSB ordered codes to be images written w/
* old versions of this library, but otherwise adhere to the
* Aldus "off by one" algorithm.
*
* Future revisions to the TIFF spec are expected to "clarify this issue".
*/
#define SetMaxCode(sp, v) { \
(sp)->lzw_maxcode = (v)-1; \
if ((sp)->lzw_flags & LZW_COMPAT) \
(sp)->lzw_maxcode++; \
}
/*
* Decoding-specific state.
*/
struct decode {
short prefixtab[HSIZE]; /* prefix(code) */
u_char suffixtab[CODE_MAX+1]; /* suffix(code) */
u_char stack[HSIZE-(CODE_MAX+1)];
u_char *stackp; /* stack pointer */
int firstchar; /* of string associated w/ last code */
};
/*
* Encoding-specific state.
*/
struct encode {
long checkpoint; /* point at which to clear table */
#define CHECK_GAP 10000 /* enc_ratio check interval */
long ratio; /* current compression ratio */
long incount; /* (input) data bytes encoded */
long outcount; /* encoded (output) bytes */
long htab[HSIZE]; /* hash table */
short codetab[HSIZE]; /* code table */
};
#if USE_PROTOTYPES
typedef void (*predictorFunc)(char* data, int nbytes, int stride);
#else
typedef void (*predictorFunc)();
#endif
/*
* State block for each open TIFF
* file using LZW compression/decompression.
*/
typedef struct {
int lzw_oldcode; /* last code encountered */
u_short lzw_flags;
#define LZW_RESTART 0x01 /* restart interrupted decode */
#define LZW_COMPAT 0x02 /* read old bit-reversed codes */
u_short lzw_nbits; /* number of bits/code */
u_short lzw_stride; /* horizontal diferencing stride */
u_short lzw_rowsize; /* XXX maybe should be a long? */
predictorFunc lzw_hordiff;
int lzw_maxcode; /* maximum code for lzw_nbits */
long lzw_bitoff; /* bit offset into data */
long lzw_bitsize; /* size of strip in bits */
int lzw_free_ent; /* next free entry in hash table */
union {
struct decode dec;
struct encode enc;
} u;
} LZWState;
#define dec_prefix u.dec.prefixtab
#define dec_suffix u.dec.suffixtab
#define dec_stack u.dec.stack
#define dec_stackp u.dec.stackp
#define dec_firstchar u.dec.firstchar
#define enc_checkpoint u.enc.checkpoint
#define enc_ratio u.enc.ratio
#define enc_incount u.enc.incount
#define enc_outcount u.enc.outcount
#define enc_htab u.enc.htab
#define enc_codetab u.enc.codetab
/* masks for extracting/inserting variable length bit codes */
static const u_char rmask[9] =
{ 0x00, 0x01, 0x03, 0x07, 0x0f, 0x1f, 0x3f, 0x7f, 0xff };
static const u_char lmask[9] =
{ 0x00, 0x80, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc, 0xfe, 0xff };
#if USE_PROTOTYPES
static int LZWPreEncode(TIFF*);
static int LZWEncode(TIFF*, u_char*, int, u_int);
static int LZWEncodePredRow(TIFF*, u_char*, int, u_int);
static int LZWEncodePredTile(TIFF*, u_char*, int, u_int);
static int LZWPostEncode(TIFF*);
static int LZWDecode(TIFF*, u_char*, int, u_int);
static int LZWDecodePredRow(TIFF*, u_char*, int, u_int);
static int LZWDecodePredTile(TIFF*, u_char*, int, u_int);
static int LZWPreDecode(TIFF*);
static int LZWCleanup(TIFF*);
static int GetNextCode(TIFF*);
static void PutNextCode(TIFF*, int);
static void cl_block(TIFF*);
static void cl_hash(LZWState*);
extern int TIFFFlushData1(TIFF *);
#else
static int LZWPreEncode(), LZWEncode(), LZWPostEncode();
static int LZWEncodePredRow(), LZWEncodePredTile();
static int LZWPreDecode(), LZWDecode();
static int LZWDecodePredRow(), LZWDecodePredTile();
static int LZWCleanup();
static int GetNextCode();
static void PutNextCode();
static void cl_block();
static void cl_hash();
extern int TIFFFlushData1();
#endif
TIFFInitLZW(tif)
TIFF *tif;
{
tif->tif_predecode = LZWPreDecode;
tif->tif_decoderow = LZWDecode;
tif->tif_decodestrip = LZWDecode;
tif->tif_decodetile = LZWDecode;
tif->tif_preencode = LZWPreEncode;
tif->tif_postencode = LZWPostEncode;
tif->tif_encoderow = LZWEncode;
tif->tif_encodestrip = LZWEncode;
tif->tif_encodetile = LZWEncode;
tif->tif_cleanup = LZWCleanup;
return (1);
}
static
DECLARE4(LZWCheckPredictor,
TIFF*, tif,
LZWState*, sp,
predictorFunc, pred8bit,
predictorFunc, pred16bit
)
{
TIFFDirectory *td = &tif->tif_dir;
switch (td->td_predictor) {
case 1:
break;
case 2:
sp->lzw_stride = (td->td_planarconfig == PLANARCONFIG_CONTIG ?
td->td_samplesperpixel : 1);
switch (td->td_bitspersample) {
case 8:
sp->lzw_hordiff = pred8bit;
break;
case 16:
sp->lzw_hordiff = pred16bit;
break;
default:
TIFFError(tif->tif_name,
"Horizontal differencing \"Predictor\" not supported with %d-bit samples",
td->td_bitspersample);
return (0);
}
break;
default:
TIFFError(tif->tif_name, "\"Predictor\" value %d not supported",
td->td_predictor);
return (0);
}
if (sp->lzw_hordiff) {
/*
* Calculate the scanline/tile-width size in bytes.
*/
if (isTiled(tif))
sp->lzw_rowsize = TIFFTileRowSize(tif);
else
sp->lzw_rowsize = TIFFScanlineSize(tif);
}
return (1);
}
/*
* LZW Decoder.
*/
#define REPEAT4(n, op) \
switch (n) { \
default: { int i; for (i = n-4; i > 0; i--) { op; } } \
case 4: op; \
case 3: op; \
case 2: op; \
case 1: op; \
case 0: ; \
}
static void
DECLARE3(horizontalAccumulate8,
register char*, cp,
register int, cc,
register int, stride
)
{
if (cc > stride) {
cc -= stride;
do {
REPEAT4(stride, cp[stride] += cp[0]; cp++)
cc -= stride;
} while (cc > 0);
}
}
static void
DECLARE3(horizontalAccumulate16,
char*, cp,
int, cc,
register int, stride
)
{
register short* wp = (short *)cp;
register int wc = cc / 2;
if (wc > stride) {
wc -= stride;
do {
REPEAT4(stride, wp[stride] += wp[0]; wp++)
wc -= stride;
} while (wc > 0);
}
}
/*
* Setup state for decoding a strip.
*/
static
LZWPreDecode(tif)
TIFF *tif;
{
register LZWState *sp = (LZWState *)tif->tif_data;
register int code;
if (sp == NULL) {
tif->tif_data = malloc(sizeof (LZWState));
if (tif->tif_data == NULL) {
TIFFError("LZWPreDecode",
"No space for LZW state block");
return (0);
}
sp = (LZWState *)tif->tif_data;
sp->lzw_flags = 0;
sp->lzw_hordiff = 0;
sp->lzw_rowsize = 0;
if (!LZWCheckPredictor(tif, sp,
horizontalAccumulate8, horizontalAccumulate16))
return (0);
if (sp->lzw_hordiff) {
/*
* Override default decoding method with
* one that does the predictor stuff.
*/
tif->tif_decoderow = LZWDecodePredRow;
tif->tif_decodestrip = LZWDecodePredTile;
tif->tif_decodetile = LZWDecodePredTile;
}
} else
sp->lzw_flags &= ~LZW_RESTART;
sp->lzw_nbits = BITS_MIN;
/*
* Pre-load the table.
*/
for (code = 255; code >= 0; code--)
sp->dec_suffix[code] = (u_char)code;
sp->lzw_free_ent = CODE_FIRST;
sp->lzw_bitoff = 0;
/* calculate data size in bits */
sp->lzw_bitsize = tif->tif_rawdatasize;
sp->lzw_bitsize = (sp->lzw_bitsize << 3) - (BITS_MAX-1);
sp->dec_stackp = sp->dec_stack;
sp->lzw_oldcode = -1;
sp->dec_firstchar = -1;
/*
* Check for old bit-reversed codes. All the flag
* manipulations are to insure only one warning is
* given for a file.
*/
if (tif->tif_rawdata[0] == 0 && (tif->tif_rawdata[1] & 0x1)) {
if ((sp->lzw_flags & LZW_COMPAT) == 0)
TIFFWarning(tif->tif_name,
"Old-style LZW codes, convert file");
sp->lzw_flags |= LZW_COMPAT;
} else
sp->lzw_flags &= ~LZW_COMPAT;
SetMaxCode(sp, MAXCODE(BITS_MIN));
return (1);
}
/*
* Decode a "hunk of data".
*/
static
LZWDecode(tif, op0, occ0, s)
TIFF *tif;
u_char *op0;
u_int s;
{
register char *op = (char *)op0;
register int occ = occ0;
register LZWState *sp = (LZWState *)tif->tif_data;
register int code;
register u_char *stackp;
int firstchar, oldcode, incode;
stackp = sp->dec_stackp;
/*
* Restart interrupted unstacking operations.
*/
if (sp->lzw_flags & LZW_RESTART) {
do {
if (--occ < 0) { /* end of scanline */
sp->dec_stackp = stackp;
return (1);
}
*op++ = *--stackp;
} while (stackp > sp->dec_stack);
sp->lzw_flags &= ~LZW_RESTART;
}
oldcode = sp->lzw_oldcode;
firstchar = sp->dec_firstchar;
while (occ > 0 && (code = GetNextCode(tif)) != CODE_EOI) {
if (code == CODE_CLEAR) {
bzero(sp->dec_prefix, sizeof (sp->dec_prefix));
sp->lzw_free_ent = CODE_FIRST;
sp->lzw_nbits = BITS_MIN;
SetMaxCode(sp, MAXCODE(BITS_MIN));
if ((code = GetNextCode(tif)) == CODE_EOI)
break;
*op++ = code, occ--;
oldcode = firstchar = code;
continue;
}
incode = code;
/*
* When a code is not in the table we use (as spec'd):
* StringFromCode(oldcode) +
* FirstChar(StringFromCode(oldcode))
*/
if (code >= sp->lzw_free_ent) { /* code not in table */
*stackp++ = firstchar;
code = oldcode;
}
/*
* Generate output string (first in reverse).
*/
for (; code >= 256; code = sp->dec_prefix[code])
*stackp++ = sp->dec_suffix[code];
*stackp++ = firstchar = sp->dec_suffix[code];
do {
if (--occ < 0) { /* end of scanline */
sp->lzw_flags |= LZW_RESTART;
break;
}
*op++ = *--stackp;
} while (stackp > sp->dec_stack);
/*
* Add the new entry to the code table.
*/
if ((code = sp->lzw_free_ent) < CODE_MAX) {
sp->dec_prefix[code] = (u_short)oldcode;
sp->dec_suffix[code] = firstchar;
sp->lzw_free_ent++;
/*
* If the next entry is too big for the
* current code size, then increase the
* size up to the maximum possible.
*/
if (sp->lzw_free_ent > sp->lzw_maxcode) {
sp->lzw_nbits++;
if (sp->lzw_nbits > BITS_MAX)
sp->lzw_nbits = BITS_MAX;
SetMaxCode(sp, MAXCODE(sp->lzw_nbits));
}
}
oldcode = incode;
}
sp->dec_stackp = stackp;
sp->lzw_oldcode = oldcode;
sp->dec_firstchar = firstchar;
if (occ > 0) {
TIFFError(tif->tif_name,
"LZWDecode: Not enough data at scanline %d (short %d bytes)",
tif->tif_row, occ);
return (0);
}
return (1);
}
/*
* Decode a scanline and apply the predictor routine.
*/
static
LZWDecodePredRow(tif, op0, occ0, s)
TIFF *tif;
u_char *op0;
u_int s;
{
LZWState *sp = (LZWState *)tif->tif_data;
if (LZWDecode(tif, op0, occ0, s)) {
(*sp->lzw_hordiff)((char *)op0, occ0, sp->lzw_stride);
return (1);
} else
return (0);
}
/*
* Decode a tile/strip and apply the predictor routine.
* Note that horizontal differencing must be done on a
* row-by-row basis. The width of a "row" has already
* been calculated at pre-decode time according to the
* strip/tile dimensions.
*/
static
LZWDecodePredTile(tif, op0, occ0, s)
TIFF *tif;
u_char *op0;
u_int s;
{
LZWState *sp = (LZWState *)tif->tif_data;
if (!LZWDecode(tif, op0, occ0, s))
return (0);
while (occ0 > 0) {
(*sp->lzw_hordiff)((char *)op0, sp->lzw_rowsize, sp->lzw_stride);
occ0 -= sp->lzw_rowsize;
op0 += sp->lzw_rowsize;
}
return (1);
}
/*
* Get the next code from the raw data buffer.
*/
static
GetNextCode(tif)
TIFF *tif;
{
register LZWState *sp = (LZWState *)tif->tif_data;
register int code, bits;
register long r_off;
register u_char *bp;
/*
* This check shouldn't be necessary because each
* strip is suppose to be terminated with CODE_EOI.
* At worst it's a substitute for the CODE_EOI that's
* supposed to be there (see calculation of lzw_bitsize
* in LZWPreDecode()).
*/
if (sp->lzw_bitoff > sp->lzw_bitsize) {
TIFFWarning(tif->tif_name,
"LZWDecode: Strip %d not terminated with EOI code",
tif->tif_curstrip);
return (CODE_EOI);
}
r_off = sp->lzw_bitoff;
bits = sp->lzw_nbits;
/*
* Get to the first byte.
*/
bp = (u_char *)tif->tif_rawdata + (r_off >> 3);
r_off &= 7;
if (sp->lzw_flags & LZW_COMPAT) {
/* Get first part (low order bits) */
code = (*bp++ >> r_off);
r_off = 8 - r_off; /* now, offset into code word */
bits -= r_off;
/* Get any 8 bit parts in the middle (<=1 for up to 16 bits). */
if (bits >= 8) {
code |= *bp++ << r_off;
r_off += 8;
bits -= 8;
}
/* high order bits. */
code |= (*bp & rmask[bits]) << r_off;
} else {
r_off = 8 - r_off; /* convert offset to count */
code = *bp++ & rmask[r_off]; /* high order bits */
bits -= r_off;
if (bits >= 8) {
code = (code<<8) | *bp++;
bits -= 8;
}
/* low order bits */
code = (code << bits) |
(((unsigned)(*bp & lmask[bits])) >> (8 - bits));
}
sp->lzw_bitoff += sp->lzw_nbits;
return (code);
}
/*
* LZW Encoding.
*/
static void
DECLARE3(horizontalDifference8,
register char*, cp,
register int, cc,
register int, stride
)
{
if (cc > stride) {
cc -= stride;
cp += cc - 1;
do {
REPEAT4(stride, cp[stride] -= cp[0]; cp--)
cc -= stride;
} while (cc > 0);
}
}
static void
DECLARE3(horizontalDifference16,
char*, cp,
int, cc,
register int, stride
)
{
register short *wp = (short *)cp;
register int wc = cc/2;
if (wc > stride) {
wc -= stride;
wp += wc - 1;
do {
REPEAT4(stride, wp[stride] -= wp[0]; wp--)
wc -= stride;
} while (wc > 0);
}
}
/*
* Reset encoding state at the start of a strip.
*/
static
LZWPreEncode(tif)
TIFF *tif;
{
register LZWState *sp = (LZWState *)tif->tif_data;
if (sp == NULL) {
tif->tif_data = malloc(sizeof (LZWState));
if (tif->tif_data == NULL) {
TIFFError("LZWPreEncode",
"No space for LZW state block");
return (0);
}
sp = (LZWState *)tif->tif_data;
sp->lzw_flags = 0;
sp->lzw_hordiff = 0;
if (!LZWCheckPredictor(tif, sp,
horizontalDifference8, horizontalDifference16))
return (0);
if (sp->lzw_hordiff) {
tif->tif_encoderow = LZWEncodePredRow;
tif->tif_encodestrip = LZWEncodePredTile;
tif->tif_encodetile = LZWEncodePredTile;
}
}
sp->enc_checkpoint = CHECK_GAP;
SetMaxCode(sp, MAXCODE(sp->lzw_nbits = BITS_MIN)+1);
cl_hash(sp); /* clear hash table */
sp->lzw_bitoff = 0;
sp->lzw_bitsize = (tif->tif_rawdatasize << 3) - (BITS_MAX-1);
sp->lzw_oldcode = -1; /* generates CODE_CLEAR in LZWEncode */
return (1);
}
/*
* Encode a scanline of pixels.
*
* Uses an open addressing double hashing (no chaining) on the
* prefix code/next character combination. We do a variant of
* Knuth's algorithm D (vol. 3, sec. 6.4) along with G. Knott's
* relatively-prime secondary probe. Here, the modular division
* first probe is gives way to a faster exclusive-or manipulation.
* Also do block compression with an adaptive reset, whereby the
* code table is cleared when the compression ratio decreases,
* but after the table fills. The variable-length output codes
* are re-sized at this point, and a CODE_CLEAR is generated
* for the decoder.
*/
static
LZWEncode(tif, bp, cc, s)
TIFF *tif;
u_char *bp;
int cc;
u_int s;
{
static char module[] = "LZWEncode";
register LZWState *sp;
register long fcode;
register int h, c, ent, disp;
if ((sp = (LZWState *)tif->tif_data) == NULL)
return (0);
ent = sp->lzw_oldcode;
if (ent == -1 && cc > 0) {
PutNextCode(tif, CODE_CLEAR);
ent = *bp++; cc--; sp->enc_incount++;
}
while (cc > 0) {
c = *bp++; cc--; sp->enc_incount++;
fcode = ((long)c << BITS_MAX) + ent;
h = (c << HSHIFT) ^ ent; /* xor hashing */
if (sp->enc_htab[h] == fcode) {
ent = sp->enc_codetab[h];
continue;
}
if (sp->enc_htab[h] >= 0) {
/*
* Primary hash failed, check secondary hash.
*/
disp = HSIZE - h;
if (h == 0)
disp = 1;
do {
if ((h -= disp) < 0)
h += HSIZE;
if (sp->enc_htab[h] == fcode) {
ent = sp->enc_codetab[h];
goto hit;
}
} while (sp->enc_htab[h] >= 0);
}
/*
* New entry, emit code and add to table.
*/
PutNextCode(tif, ent);
ent = c;
sp->enc_codetab[h] = sp->lzw_free_ent++;
sp->enc_htab[h] = fcode;
if (sp->lzw_free_ent == CODE_MAX-1) {
/* table is full, emit clear code and reset */
cl_hash(sp);
PutNextCode(tif, CODE_CLEAR);
SetMaxCode(sp, MAXCODE(sp->lzw_nbits = BITS_MIN)+1);
} else {
/*
* If the next entry is going to be too big for
* the code size, then increase it, if possible.
*/
if (sp->lzw_free_ent > sp->lzw_maxcode) {
sp->lzw_nbits++;
assert(sp->lzw_nbits <= BITS_MAX);
SetMaxCode(sp, MAXCODE(sp->lzw_nbits)+1);
} else if (sp->enc_incount >= sp->enc_checkpoint)
cl_block(tif);
}
hit:
;
}
sp->lzw_oldcode = ent;
return (1);
}
static
LZWEncodePredRow(tif, bp, cc, s)
TIFF *tif;
u_char *bp;
int cc;
u_int s;
{
LZWState *sp = (LZWState *)tif->tif_data;
/* XXX horizontal differencing alters user's data XXX */
(*sp->lzw_hordiff)((char *)bp, cc, sp->lzw_stride);
return (LZWEncode(tif, bp, cc, s));
}
static
LZWEncodePredTile(tif, bp0, cc0, s)
TIFF *tif;
u_char *bp0;
int cc0;
u_int s;
{
LZWState *sp = (LZWState *)tif->tif_data;
int cc = cc0;
u_char *bp = bp0;
while (cc > 0) {
(*sp->lzw_hordiff)((char *)bp, sp->lzw_rowsize, sp->lzw_stride);
cc -= sp->lzw_rowsize;
bp += sp->lzw_rowsize;
}
return (LZWEncode(tif, bp0, cc0, s));
}
/*
* Finish off an encoded strip by flushing the last
* string and tacking on an End Of Information code.
*/
static
LZWPostEncode(tif)
TIFF *tif;
{
LZWState *sp = (LZWState *)tif->tif_data;
if (sp->lzw_oldcode != -1) {
PutNextCode(tif, sp->lzw_oldcode);
sp->lzw_oldcode = -1;
}
PutNextCode(tif, CODE_EOI);
return (1);
}
static void
PutNextCode(tif, c)
TIFF *tif;
int c;
{
register LZWState *sp = (LZWState *)tif->tif_data;
register long r_off;
register int bits, code = c;
register char *bp;
r_off = sp->lzw_bitoff;
bits = sp->lzw_nbits;
/*
* Flush buffer if code doesn't fit.
*/
if (r_off + bits > sp->lzw_bitsize) {
/*
* Calculate the number of full bytes that can be
* written and save anything else for the next write.
*/
if (r_off & 7) {
tif->tif_rawcc = r_off >> 3;
bp = tif->tif_rawdata + tif->tif_rawcc;
(void) TIFFFlushData1(tif);
tif->tif_rawdata[0] = *bp;
} else {
/*
* Otherwise, on a byte boundary (in
* which tiff_rawcc is already correct).
*/
(void) TIFFFlushData1(tif);
}
bp = tif->tif_rawdata;
sp->lzw_bitoff = (r_off &= 7);
} else {
/*
* Get to the first byte.
*/
bp = tif->tif_rawdata + (r_off >> 3);
r_off &= 7;
}
/*
* Note that lzw_bitoff is maintained as the bit offset
* into the buffer w/ a right-to-left orientation (i.e.
* lsb-to-msb). The bits, however, go in the file in
* an msb-to-lsb order.
*/
bits -= (8 - r_off);
*bp = (*bp & lmask[r_off]) | (code >> bits);
bp++;
if (bits >= 8) {
bits -= 8;
*bp++ = code >> bits;
}
if (bits)
*bp = (code & rmask[bits]) << (8 - bits);
/*
* enc_outcount is used by the compression analysis machinery
* which resets the compression tables when the compression
* ratio goes up. lzw_bitoff is used here (in PutNextCode) for
* inserting codes into the output buffer. tif_rawcc must
* be updated for the mainline write code in TIFFWriteScanline()
* so that data is flushed when the end of a strip is reached.
* Note that the latter is rounded up to ensure that a non-zero
* byte count is present.
*/
sp->enc_outcount += sp->lzw_nbits;
sp->lzw_bitoff += sp->lzw_nbits;
tif->tif_rawcc = (sp->lzw_bitoff + 7) >> 3;
}
/*
* Check compression ratio and, if things seem to
* be slipping, clear the hash table and reset state.
*/
static void
cl_block(tif)
TIFF *tif;
{
register LZWState *sp = (LZWState *)tif->tif_data;
register long rat;
sp->enc_checkpoint = sp->enc_incount + CHECK_GAP;
if (sp->enc_incount > 0x007fffff) { /* shift will overflow */
rat = sp->enc_outcount >> 8;
rat = (rat == 0 ? 0x7fffffff : sp->enc_incount / rat);
} else
rat = (sp->enc_incount<<8)/sp->enc_outcount; /* 8 fract bits */
if (rat <= sp->enc_ratio) {
cl_hash(sp);
PutNextCode(tif, CODE_CLEAR);
SetMaxCode(sp, MAXCODE(sp->lzw_nbits = BITS_MIN)+1);
} else
sp->enc_ratio = rat;
}
/*
* Reset code table and related statistics.
*/
static void
cl_hash(sp)
LZWState *sp;
{
register long *htab_p = sp->enc_htab+HSIZE;
register long i, m1 = -1;
i = HSIZE - 16;
do {
*(htab_p-16) = m1;
*(htab_p-15) = m1;
*(htab_p-14) = m1;
*(htab_p-13) = m1;
*(htab_p-12) = m1;
*(htab_p-11) = m1;
*(htab_p-10) = m1;
*(htab_p-9) = m1;
*(htab_p-8) = m1;
*(htab_p-7) = m1;
*(htab_p-6) = m1;
*(htab_p-5) = m1;
*(htab_p-4) = m1;
*(htab_p-3) = m1;
*(htab_p-2) = m1;
*(htab_p-1) = m1;
htab_p -= 16;
} while ((i -= 16) >= 0);
for (i += 16; i > 0; i--)
*--htab_p = m1;
sp->enc_ratio = 0;
sp->enc_incount = 0;
sp->enc_outcount = 0;
sp->lzw_free_ent = CODE_FIRST;
}
static
LZWCleanup(tif)
TIFF *tif;
{
if (tif->tif_data) {
free(tif->tif_data);
tif->tif_data = NULL;
}
}
/*
* Copyright (c) 1985, 1986 The Regents of the University of California.
* All rights reserved.
*
* This code is derived from software contributed to Berkeley by
* James A. Woods, derived from original work by Spencer Thomas
* and Joseph Orost.
*
* Redistribution and use in source and binary forms are permitted
* provided that the above copyright notice and this paragraph are
* duplicated in all such forms and that any documentation,
* advertising materials, and other materials related to such
* distribution and use acknowledge that the software was developed
* by the University of California, Berkeley. The name of the
* University may not be used to endorse or promote products derived
* from this software without specific prior written permission.
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
|
148821.c | /***************************************************************************
* Copyright (C) 2005 by Dominic Rath *
* [email protected] *
* *
* Copyright (C) 2007-2010 Øyvind Harboe *
* [email protected] *
* *
* Copyright (C) 2008 by Spencer Oliver *
* [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, see <http://www.gnu.org/licenses/>. *
***************************************************************************/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "log.h"
#include "command.h"
#include "time_support.h"
#include <stdarg.h>
#ifdef _DEBUG_FREE_SPACE_
#ifdef HAVE_MALLOC_H
#include <malloc.h>
#else
#error "malloc.h is required to use --enable-malloc-logging"
#endif
#endif
int debug_level = -1;
static FILE *log_output;
static struct log_callback *log_callbacks;
static int64_t last_time;
static int64_t current_time;
static int64_t start;
static const char * const log_strings[6] = {
"User : ",
"Error: ",
"Warn : ", /* want a space after each colon, all same width, colons aligned */
"Info : ",
"Debug: ",
"Debug: "
};
static int count;
static struct store_log_forward *log_head;
static int log_forward_count;
struct store_log_forward {
struct store_log_forward *next;
const char *file;
int line;
const char *function;
const char *string;
};
/* either forward the log to the listeners or store it for possible forwarding later */
static void log_forward(const char *file, unsigned line, const char *function, const char *string)
{
if (log_forward_count == 0) {
struct log_callback *cb, *next;
cb = log_callbacks;
/* DANGER!!!! the log callback can remove itself!!!! */
while (cb) {
next = cb->next;
cb->fn(cb->priv, file, line, function, string);
cb = next;
}
} else {
struct store_log_forward *log = malloc(sizeof(struct store_log_forward));
log->file = strdup(file);
log->line = line;
log->function = strdup(function);
log->string = strdup(string);
log->next = NULL;
if (log_head == NULL)
log_head = log;
else {
/* append to tail */
struct store_log_forward *t;
t = log_head;
while (t->next != NULL)
t = t->next;
t->next = log;
}
}
}
/* The log_puts() serves two somewhat different goals:
*
* - logging
* - feeding low-level info to the user in GDB or Telnet
*
* The latter dictates that strings without newline are not logged, lest there
* will be *MANY log lines when sending one char at the time(e.g.
* target_request.c).
*
*/
static void log_puts(enum log_levels level,
const char *file,
int line,
const char *function,
const char *string)
{
char *f;
if (level == LOG_LVL_OUTPUT) {
/* do not prepend any headers, just print out what we were given and return */
fputs(string, log_output);
fflush(log_output);
return;
}
f = strrchr(file, '/');
if (f != NULL)
file = f + 1;
if (strlen(string) > 0) {
if (debug_level >= LOG_LVL_DEBUG) {
/* print with count and time information */
int64_t t = timeval_ms() - start;
#ifdef _DEBUG_FREE_SPACE_
struct mallinfo info;
info = mallinfo();
#endif
fprintf(log_output, "%s%d %" PRId64 " %s:%d %s()"
#ifdef _DEBUG_FREE_SPACE_
" %d"
#endif
": %s", log_strings[level + 1], count, t, file, line, function,
#ifdef _DEBUG_FREE_SPACE_
info.fordblks,
#endif
string);
} else {
/* if we are using gdb through pipes then we do not want any output
* to the pipe otherwise we get repeated strings */
fprintf(log_output, "%s%s",
(level > LOG_LVL_USER) ? log_strings[level + 1] : "", string);
}
} else {
/* Empty strings are sent to log callbacks to keep e.g. gdbserver alive, here we do
*nothing. */
}
fflush(log_output);
/* Never forward LOG_LVL_DEBUG, too verbose and they can be found in the log if need be */
if (level <= LOG_LVL_INFO)
log_forward(file, line, function, string);
}
void log_printf(enum log_levels level,
const char *file,
unsigned line,
const char *function,
const char *format,
...)
{
char *string;
va_list ap;
count++;
if (level > debug_level)
return;
va_start(ap, format);
string = alloc_vprintf(format, ap);
if (string != NULL) {
log_puts(level, file, line, function, string);
free(string);
}
va_end(ap);
}
void log_vprintf_lf(enum log_levels level, const char *file, unsigned line,
const char *function, const char *format, va_list args)
{
char *tmp;
count++;
if (level > debug_level)
return;
tmp = alloc_vprintf(format, args);
if (!tmp)
return;
/*
* Note: alloc_vprintf() guarantees that the buffer is at least one
* character longer.
*/
strcat(tmp, "\n");
log_puts(level, file, line, function, tmp);
free(tmp);
}
void log_printf_lf(enum log_levels level,
const char *file,
unsigned line,
const char *function,
const char *format,
...)
{
va_list ap;
va_start(ap, format);
log_vprintf_lf(level, file, line, function, format, ap);
va_end(ap);
}
COMMAND_HANDLER(handle_debug_level_command)
{
if (CMD_ARGC == 1) {
int new_level;
COMMAND_PARSE_NUMBER(int, CMD_ARGV[0], new_level);
if ((new_level > LOG_LVL_DEBUG_IO) || (new_level < LOG_LVL_SILENT)) {
LOG_ERROR("level must be between %d and %d", LOG_LVL_SILENT, LOG_LVL_DEBUG_IO);
return ERROR_COMMAND_SYNTAX_ERROR;
}
debug_level = new_level;
} else if (CMD_ARGC > 1)
return ERROR_COMMAND_SYNTAX_ERROR;
command_print(CMD_CTX, "debug_level: %i", debug_level);
return ERROR_OK;
}
COMMAND_HANDLER(handle_log_output_command)
{
if (CMD_ARGC == 1) {
FILE *file = fopen(CMD_ARGV[0], "w");
if (file == NULL) {
LOG_ERROR("failed to open output log '%s'", CMD_ARGV[0]);
return ERROR_FAIL;
}
if (log_output != stderr && log_output != NULL) {
/* Close previous log file, if it was open and wasn't stderr. */
fclose(log_output);
}
log_output = file;
}
return ERROR_OK;
}
static struct command_registration log_command_handlers[] = {
{
.name = "log_output",
.handler = handle_log_output_command,
.mode = COMMAND_ANY,
.help = "redirect logging to a file (default: stderr)",
.usage = "file_name",
},
{
.name = "debug_level",
.handler = handle_debug_level_command,
.mode = COMMAND_ANY,
.help = "Sets the verbosity level of debugging output. "
"0 shows errors only; 1 adds warnings; "
"2 (default) adds other info; 3 adds debugging; "
"4 adds extra verbose debugging.",
.usage = "number",
},
COMMAND_REGISTRATION_DONE
};
int log_register_commands(struct command_context *cmd_ctx)
{
return register_commands(cmd_ctx, NULL, log_command_handlers);
}
void log_init(void)
{
/* set defaults for daemon configuration,
* if not set by cmdline or cfgfile */
if (debug_level == -1)
debug_level = LOG_LVL_INFO;
char *debug_env = getenv("OPENOCD_DEBUG_LEVEL");
if (NULL != debug_env) {
int value;
int retval = parse_int(debug_env, &value);
if (ERROR_OK == retval &&
debug_level >= LOG_LVL_SILENT &&
debug_level <= LOG_LVL_DEBUG_IO)
debug_level = value;
}
if (log_output == NULL)
log_output = stderr;
start = last_time = timeval_ms();
}
int set_log_output(struct command_context *cmd_ctx, FILE *output)
{
log_output = output;
return ERROR_OK;
}
/* add/remove log callback handler */
int log_add_callback(log_callback_fn fn, void *priv)
{
struct log_callback *cb;
/* prevent the same callback to be registered more than once, just for sure */
for (cb = log_callbacks; cb; cb = cb->next) {
if (cb->fn == fn && cb->priv == priv)
return ERROR_COMMAND_SYNTAX_ERROR;
}
/* alloc memory, it is safe just to return in case of an error, no need for the caller to
*check this */
cb = malloc(sizeof(struct log_callback));
if (cb == NULL)
return ERROR_BUF_TOO_SMALL;
/* add item to the beginning of the linked list */
cb->fn = fn;
cb->priv = priv;
cb->next = log_callbacks;
log_callbacks = cb;
return ERROR_OK;
}
int log_remove_callback(log_callback_fn fn, void *priv)
{
struct log_callback *cb, **p;
for (p = &log_callbacks; (cb = *p); p = &(*p)->next) {
if (cb->fn == fn && cb->priv == priv) {
*p = cb->next;
free(cb);
return ERROR_OK;
}
}
/* no such item */
return ERROR_COMMAND_SYNTAX_ERROR;
}
/* return allocated string w/printf() result */
char *alloc_vprintf(const char *fmt, va_list ap)
{
va_list ap_copy;
int len;
char *string;
/* determine the length of the buffer needed */
va_copy(ap_copy, ap);
len = vsnprintf(NULL, 0, fmt, ap_copy);
va_end(ap_copy);
/* allocate and make room for terminating zero. */
/* FIXME: The old version always allocated at least one byte extra and
* other code depend on that. They should be probably be fixed, but for
* now reserve the extra byte. */
string = malloc(len + 2);
if (string == NULL)
return NULL;
/* do the real work */
vsnprintf(string, len + 1, fmt, ap);
return string;
}
char *alloc_printf(const char *format, ...)
{
char *string;
va_list ap;
va_start(ap, format);
string = alloc_vprintf(format, ap);
va_end(ap);
return string;
}
/* Code must return to the server loop before 1000ms has returned or invoke
* this function.
*
* The GDB connection will time out if it spends >2000ms and you'll get nasty
* error messages from GDB:
*
* Ignoring packet error, continuing...
* Reply contains invalid hex digit 116
*
* While it is possible use "set remotetimeout" to more than the default 2000ms
* in GDB, OpenOCD guarantees that it sends keep-alive packages on the
* GDB protocol and it is a bug in OpenOCD not to either return to the server
* loop or invoke keep_alive() every 1000ms.
*
* This function will send a keep alive packet if >500ms has passed since last time
* it was invoked.
*
* Note that this function can be invoked often, so it needs to be relatively
* fast when invoked more often than every 500ms.
*
*/
void keep_alive()
{
current_time = timeval_ms();
if (current_time-last_time > 1000) {
extern int gdb_actual_connections;
if (gdb_actual_connections)
LOG_WARNING("keep_alive() was not invoked in the "
"1000ms timelimit. GDB alive packet not "
"sent! (%" PRId64 "). Workaround: increase "
"\"set remotetimeout\" in GDB",
current_time-last_time);
else
LOG_DEBUG("keep_alive() was not invoked in the "
"1000ms timelimit (%" PRId64 "). This may cause "
"trouble with GDB connections.",
current_time-last_time);
}
if (current_time-last_time > 500) {
/* this will keep the GDB connection alive */
LOG_USER_N("%s", "");
/* DANGER!!!! do not add code to invoke e.g. target event processing,
* jim timer processing, etc. it can cause infinite recursion +
* jim event callbacks need to happen at a well defined time,
* not anywhere keep_alive() is invoked.
*
* These functions should be invoked at a well defined spot in server.c
*/
last_time = current_time;
}
}
/* reset keep alive timer without sending message */
void kept_alive()
{
current_time = timeval_ms();
last_time = current_time;
}
/* if we sleep for extended periods of time, we must invoke keep_alive() intermittantly */
void alive_sleep(uint64_t ms)
{
uint64_t napTime = 10;
for (uint64_t i = 0; i < ms; i += napTime) {
uint64_t sleep_a_bit = ms - i;
if (sleep_a_bit > napTime)
sleep_a_bit = napTime;
usleep(sleep_a_bit * 1000);
keep_alive();
}
}
void busy_sleep(uint64_t ms)
{
uint64_t then = timeval_ms();
while (timeval_ms() - then < ms) {
/*
* busy wait
*/
}
}
|
954888.c | /*
* Copyright 2020-2021 Telecom Paris
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.
*/
/*
* Generated by asn1c-0.9.29 (http://lionet.info/asn1c)
* From ASN.1 module "NR-RRC-Definitions"
* `asn1c -gen-PER -fcompound-names -findirect-choice -no-gen-example`
*/
#include "Phy-ParametersFR1.h"
/*
* This type is implemented using NativeEnumerated,
* so here we adjust the DEF accordingly.
*/
/*
* This type is implemented using NativeEnumerated,
* so here we adjust the DEF accordingly.
*/
/*
* This type is implemented using NativeEnumerated,
* so here we adjust the DEF accordingly.
*/
/*
* This type is implemented using NativeEnumerated,
* so here we adjust the DEF accordingly.
*/
/*
* This type is implemented using NativeEnumerated,
* so here we adjust the DEF accordingly.
*/
static asn_oer_constraints_t asn_OER_type_pdcch_MonitoringSingleOccasion_constr_2 CC_NOTUSED = {
{ 0, 0 },
-1};
static asn_per_constraints_t asn_PER_type_pdcch_MonitoringSingleOccasion_constr_2 CC_NOTUSED = {
{ APC_CONSTRAINED, 0, 0, 0, 0 } /* (0..0) */,
{ APC_UNCONSTRAINED, -1, -1, 0, 0 },
0, 0 /* No PER value map */
};
static asn_oer_constraints_t asn_OER_type_scs_60kHz_constr_4 CC_NOTUSED = {
{ 0, 0 },
-1};
static asn_per_constraints_t asn_PER_type_scs_60kHz_constr_4 CC_NOTUSED = {
{ APC_CONSTRAINED, 0, 0, 0, 0 } /* (0..0) */,
{ APC_UNCONSTRAINED, -1, -1, 0, 0 },
0, 0 /* No PER value map */
};
static asn_oer_constraints_t asn_OER_type_pdsch_256QAM_FR1_constr_6 CC_NOTUSED = {
{ 0, 0 },
-1};
static asn_per_constraints_t asn_PER_type_pdsch_256QAM_FR1_constr_6 CC_NOTUSED = {
{ APC_CONSTRAINED, 0, 0, 0, 0 } /* (0..0) */,
{ APC_UNCONSTRAINED, -1, -1, 0, 0 },
0, 0 /* No PER value map */
};
static asn_oer_constraints_t asn_OER_type_pdsch_RE_MappingFR1_PerSymbol_constr_8 CC_NOTUSED = {
{ 0, 0 },
-1};
static asn_per_constraints_t asn_PER_type_pdsch_RE_MappingFR1_PerSymbol_constr_8 CC_NOTUSED = {
{ APC_CONSTRAINED, 1, 1, 0, 1 } /* (0..1) */,
{ APC_UNCONSTRAINED, -1, -1, 0, 0 },
0, 0 /* No PER value map */
};
static asn_oer_constraints_t asn_OER_type_pdsch_RE_MappingFR1_PerSlot_constr_13 CC_NOTUSED = {
{ 0, 0 },
-1};
static asn_per_constraints_t asn_PER_type_pdsch_RE_MappingFR1_PerSlot_constr_13 CC_NOTUSED = {
{ APC_CONSTRAINED, 4, 4, 0, 15 } /* (0..15) */,
{ APC_UNCONSTRAINED, -1, -1, 0, 0 },
0, 0 /* No PER value map */
};
static const asn_INTEGER_enum_map_t asn_MAP_pdcch_MonitoringSingleOccasion_value2enum_2[] = {
{ 0, 9, "supported" }
};
static const unsigned int asn_MAP_pdcch_MonitoringSingleOccasion_enum2value_2[] = {
0 /* supported(0) */
};
static const asn_INTEGER_specifics_t asn_SPC_pdcch_MonitoringSingleOccasion_specs_2 = {
asn_MAP_pdcch_MonitoringSingleOccasion_value2enum_2, /* "tag" => N; sorted by tag */
asn_MAP_pdcch_MonitoringSingleOccasion_enum2value_2, /* N => "tag"; sorted by N */
1, /* Number of elements in the maps */
0, /* Enumeration is not extensible */
1, /* Strict enumeration */
0, /* Native long size */
0
};
static const ber_tlv_tag_t asn_DEF_pdcch_MonitoringSingleOccasion_tags_2[] = {
(ASN_TAG_CLASS_CONTEXT | (0 << 2)),
(ASN_TAG_CLASS_UNIVERSAL | (10 << 2))
};
static /* Use -fall-defs-global to expose */
asn_TYPE_descriptor_t asn_DEF_pdcch_MonitoringSingleOccasion_2 = {
"pdcch-MonitoringSingleOccasion",
"pdcch-MonitoringSingleOccasion",
&asn_OP_NativeEnumerated,
asn_DEF_pdcch_MonitoringSingleOccasion_tags_2,
sizeof(asn_DEF_pdcch_MonitoringSingleOccasion_tags_2)
/sizeof(asn_DEF_pdcch_MonitoringSingleOccasion_tags_2[0]) - 1, /* 1 */
asn_DEF_pdcch_MonitoringSingleOccasion_tags_2, /* Same as above */
sizeof(asn_DEF_pdcch_MonitoringSingleOccasion_tags_2)
/sizeof(asn_DEF_pdcch_MonitoringSingleOccasion_tags_2[0]), /* 2 */
{ &asn_OER_type_pdcch_MonitoringSingleOccasion_constr_2, &asn_PER_type_pdcch_MonitoringSingleOccasion_constr_2, NativeEnumerated_constraint },
0, 0, /* Defined elsewhere */
&asn_SPC_pdcch_MonitoringSingleOccasion_specs_2 /* Additional specs */
};
static const asn_INTEGER_enum_map_t asn_MAP_scs_60kHz_value2enum_4[] = {
{ 0, 9, "supported" }
};
static const unsigned int asn_MAP_scs_60kHz_enum2value_4[] = {
0 /* supported(0) */
};
static const asn_INTEGER_specifics_t asn_SPC_scs_60kHz_specs_4 = {
asn_MAP_scs_60kHz_value2enum_4, /* "tag" => N; sorted by tag */
asn_MAP_scs_60kHz_enum2value_4, /* N => "tag"; sorted by N */
1, /* Number of elements in the maps */
0, /* Enumeration is not extensible */
1, /* Strict enumeration */
0, /* Native long size */
0
};
static const ber_tlv_tag_t asn_DEF_scs_60kHz_tags_4[] = {
(ASN_TAG_CLASS_CONTEXT | (1 << 2)),
(ASN_TAG_CLASS_UNIVERSAL | (10 << 2))
};
static /* Use -fall-defs-global to expose */
asn_TYPE_descriptor_t asn_DEF_scs_60kHz_4 = {
"scs-60kHz",
"scs-60kHz",
&asn_OP_NativeEnumerated,
asn_DEF_scs_60kHz_tags_4,
sizeof(asn_DEF_scs_60kHz_tags_4)
/sizeof(asn_DEF_scs_60kHz_tags_4[0]) - 1, /* 1 */
asn_DEF_scs_60kHz_tags_4, /* Same as above */
sizeof(asn_DEF_scs_60kHz_tags_4)
/sizeof(asn_DEF_scs_60kHz_tags_4[0]), /* 2 */
{ &asn_OER_type_scs_60kHz_constr_4, &asn_PER_type_scs_60kHz_constr_4, NativeEnumerated_constraint },
0, 0, /* Defined elsewhere */
&asn_SPC_scs_60kHz_specs_4 /* Additional specs */
};
static const asn_INTEGER_enum_map_t asn_MAP_pdsch_256QAM_FR1_value2enum_6[] = {
{ 0, 9, "supported" }
};
static const unsigned int asn_MAP_pdsch_256QAM_FR1_enum2value_6[] = {
0 /* supported(0) */
};
static const asn_INTEGER_specifics_t asn_SPC_pdsch_256QAM_FR1_specs_6 = {
asn_MAP_pdsch_256QAM_FR1_value2enum_6, /* "tag" => N; sorted by tag */
asn_MAP_pdsch_256QAM_FR1_enum2value_6, /* N => "tag"; sorted by N */
1, /* Number of elements in the maps */
0, /* Enumeration is not extensible */
1, /* Strict enumeration */
0, /* Native long size */
0
};
static const ber_tlv_tag_t asn_DEF_pdsch_256QAM_FR1_tags_6[] = {
(ASN_TAG_CLASS_CONTEXT | (2 << 2)),
(ASN_TAG_CLASS_UNIVERSAL | (10 << 2))
};
static /* Use -fall-defs-global to expose */
asn_TYPE_descriptor_t asn_DEF_pdsch_256QAM_FR1_6 = {
"pdsch-256QAM-FR1",
"pdsch-256QAM-FR1",
&asn_OP_NativeEnumerated,
asn_DEF_pdsch_256QAM_FR1_tags_6,
sizeof(asn_DEF_pdsch_256QAM_FR1_tags_6)
/sizeof(asn_DEF_pdsch_256QAM_FR1_tags_6[0]) - 1, /* 1 */
asn_DEF_pdsch_256QAM_FR1_tags_6, /* Same as above */
sizeof(asn_DEF_pdsch_256QAM_FR1_tags_6)
/sizeof(asn_DEF_pdsch_256QAM_FR1_tags_6[0]), /* 2 */
{ &asn_OER_type_pdsch_256QAM_FR1_constr_6, &asn_PER_type_pdsch_256QAM_FR1_constr_6, NativeEnumerated_constraint },
0, 0, /* Defined elsewhere */
&asn_SPC_pdsch_256QAM_FR1_specs_6 /* Additional specs */
};
static const asn_INTEGER_enum_map_t asn_MAP_pdsch_RE_MappingFR1_PerSymbol_value2enum_8[] = {
{ 0, 3, "n10" },
{ 1, 3, "n20" }
};
static const unsigned int asn_MAP_pdsch_RE_MappingFR1_PerSymbol_enum2value_8[] = {
0, /* n10(0) */
1 /* n20(1) */
};
static const asn_INTEGER_specifics_t asn_SPC_pdsch_RE_MappingFR1_PerSymbol_specs_8 = {
asn_MAP_pdsch_RE_MappingFR1_PerSymbol_value2enum_8, /* "tag" => N; sorted by tag */
asn_MAP_pdsch_RE_MappingFR1_PerSymbol_enum2value_8, /* N => "tag"; sorted by N */
2, /* Number of elements in the maps */
0, /* Enumeration is not extensible */
1, /* Strict enumeration */
0, /* Native long size */
0
};
static const ber_tlv_tag_t asn_DEF_pdsch_RE_MappingFR1_PerSymbol_tags_8[] = {
(ASN_TAG_CLASS_CONTEXT | (3 << 2)),
(ASN_TAG_CLASS_UNIVERSAL | (10 << 2))
};
static /* Use -fall-defs-global to expose */
asn_TYPE_descriptor_t asn_DEF_pdsch_RE_MappingFR1_PerSymbol_8 = {
"pdsch-RE-MappingFR1-PerSymbol",
"pdsch-RE-MappingFR1-PerSymbol",
&asn_OP_NativeEnumerated,
asn_DEF_pdsch_RE_MappingFR1_PerSymbol_tags_8,
sizeof(asn_DEF_pdsch_RE_MappingFR1_PerSymbol_tags_8)
/sizeof(asn_DEF_pdsch_RE_MappingFR1_PerSymbol_tags_8[0]) - 1, /* 1 */
asn_DEF_pdsch_RE_MappingFR1_PerSymbol_tags_8, /* Same as above */
sizeof(asn_DEF_pdsch_RE_MappingFR1_PerSymbol_tags_8)
/sizeof(asn_DEF_pdsch_RE_MappingFR1_PerSymbol_tags_8[0]), /* 2 */
{ &asn_OER_type_pdsch_RE_MappingFR1_PerSymbol_constr_8, &asn_PER_type_pdsch_RE_MappingFR1_PerSymbol_constr_8, NativeEnumerated_constraint },
0, 0, /* Defined elsewhere */
&asn_SPC_pdsch_RE_MappingFR1_PerSymbol_specs_8 /* Additional specs */
};
static const asn_INTEGER_enum_map_t asn_MAP_pdsch_RE_MappingFR1_PerSlot_value2enum_13[] = {
{ 0, 3, "n16" },
{ 1, 3, "n32" },
{ 2, 3, "n48" },
{ 3, 3, "n64" },
{ 4, 3, "n80" },
{ 5, 3, "n96" },
{ 6, 4, "n112" },
{ 7, 4, "n128" },
{ 8, 4, "n144" },
{ 9, 4, "n160" },
{ 10, 4, "n176" },
{ 11, 4, "n192" },
{ 12, 4, "n208" },
{ 13, 4, "n224" },
{ 14, 4, "n240" },
{ 15, 4, "n256" }
};
static const unsigned int asn_MAP_pdsch_RE_MappingFR1_PerSlot_enum2value_13[] = {
6, /* n112(6) */
7, /* n128(7) */
8, /* n144(8) */
0, /* n16(0) */
9, /* n160(9) */
10, /* n176(10) */
11, /* n192(11) */
12, /* n208(12) */
13, /* n224(13) */
14, /* n240(14) */
15, /* n256(15) */
1, /* n32(1) */
2, /* n48(2) */
3, /* n64(3) */
4, /* n80(4) */
5 /* n96(5) */
};
static const asn_INTEGER_specifics_t asn_SPC_pdsch_RE_MappingFR1_PerSlot_specs_13 = {
asn_MAP_pdsch_RE_MappingFR1_PerSlot_value2enum_13, /* "tag" => N; sorted by tag */
asn_MAP_pdsch_RE_MappingFR1_PerSlot_enum2value_13, /* N => "tag"; sorted by N */
16, /* Number of elements in the maps */
0, /* Enumeration is not extensible */
1, /* Strict enumeration */
0, /* Native long size */
0
};
static const ber_tlv_tag_t asn_DEF_pdsch_RE_MappingFR1_PerSlot_tags_13[] = {
(ASN_TAG_CLASS_CONTEXT | (0 << 2)),
(ASN_TAG_CLASS_UNIVERSAL | (10 << 2))
};
static /* Use -fall-defs-global to expose */
asn_TYPE_descriptor_t asn_DEF_pdsch_RE_MappingFR1_PerSlot_13 = {
"pdsch-RE-MappingFR1-PerSlot",
"pdsch-RE-MappingFR1-PerSlot",
&asn_OP_NativeEnumerated,
asn_DEF_pdsch_RE_MappingFR1_PerSlot_tags_13,
sizeof(asn_DEF_pdsch_RE_MappingFR1_PerSlot_tags_13)
/sizeof(asn_DEF_pdsch_RE_MappingFR1_PerSlot_tags_13[0]) - 1, /* 1 */
asn_DEF_pdsch_RE_MappingFR1_PerSlot_tags_13, /* Same as above */
sizeof(asn_DEF_pdsch_RE_MappingFR1_PerSlot_tags_13)
/sizeof(asn_DEF_pdsch_RE_MappingFR1_PerSlot_tags_13[0]), /* 2 */
{ &asn_OER_type_pdsch_RE_MappingFR1_PerSlot_constr_13, &asn_PER_type_pdsch_RE_MappingFR1_PerSlot_constr_13, NativeEnumerated_constraint },
0, 0, /* Defined elsewhere */
&asn_SPC_pdsch_RE_MappingFR1_PerSlot_specs_13 /* Additional specs */
};
static asn_TYPE_member_t asn_MBR_ext1_12[] = {
{ ATF_POINTER, 1, offsetof(struct Phy_ParametersFR1__ext1, pdsch_RE_MappingFR1_PerSlot),
(ASN_TAG_CLASS_CONTEXT | (0 << 2)),
-1, /* IMPLICIT tag at current level */
&asn_DEF_pdsch_RE_MappingFR1_PerSlot_13,
0,
{ 0, 0, 0 },
0, 0, /* No default value */
"pdsch-RE-MappingFR1-PerSlot"
},
};
static const int asn_MAP_ext1_oms_12[] = { 0 };
static const ber_tlv_tag_t asn_DEF_ext1_tags_12[] = {
(ASN_TAG_CLASS_CONTEXT | (4 << 2)),
(ASN_TAG_CLASS_UNIVERSAL | (16 << 2))
};
static const asn_TYPE_tag2member_t asn_MAP_ext1_tag2el_12[] = {
{ (ASN_TAG_CLASS_CONTEXT | (0 << 2)), 0, 0, 0 } /* pdsch-RE-MappingFR1-PerSlot */
};
static asn_SEQUENCE_specifics_t asn_SPC_ext1_specs_12 = {
sizeof(struct Phy_ParametersFR1__ext1),
offsetof(struct Phy_ParametersFR1__ext1, _asn_ctx),
asn_MAP_ext1_tag2el_12,
1, /* Count of tags in the map */
asn_MAP_ext1_oms_12, /* Optional members */
1, 0, /* Root/Additions */
-1, /* First extension addition */
};
static /* Use -fall-defs-global to expose */
asn_TYPE_descriptor_t asn_DEF_ext1_12 = {
"ext1",
"ext1",
&asn_OP_SEQUENCE,
asn_DEF_ext1_tags_12,
sizeof(asn_DEF_ext1_tags_12)
/sizeof(asn_DEF_ext1_tags_12[0]) - 1, /* 1 */
asn_DEF_ext1_tags_12, /* Same as above */
sizeof(asn_DEF_ext1_tags_12)
/sizeof(asn_DEF_ext1_tags_12[0]), /* 2 */
{ 0, 0, SEQUENCE_constraint },
asn_MBR_ext1_12,
1, /* Elements count */
&asn_SPC_ext1_specs_12 /* Additional specs */
};
asn_TYPE_member_t asn_MBR_Phy_ParametersFR1_1[] = {
{ ATF_POINTER, 5, offsetof(struct Phy_ParametersFR1, pdcch_MonitoringSingleOccasion),
(ASN_TAG_CLASS_CONTEXT | (0 << 2)),
-1, /* IMPLICIT tag at current level */
&asn_DEF_pdcch_MonitoringSingleOccasion_2,
0,
{ 0, 0, 0 },
0, 0, /* No default value */
"pdcch-MonitoringSingleOccasion"
},
{ ATF_POINTER, 4, offsetof(struct Phy_ParametersFR1, scs_60kHz),
(ASN_TAG_CLASS_CONTEXT | (1 << 2)),
-1, /* IMPLICIT tag at current level */
&asn_DEF_scs_60kHz_4,
0,
{ 0, 0, 0 },
0, 0, /* No default value */
"scs-60kHz"
},
{ ATF_POINTER, 3, offsetof(struct Phy_ParametersFR1, pdsch_256QAM_FR1),
(ASN_TAG_CLASS_CONTEXT | (2 << 2)),
-1, /* IMPLICIT tag at current level */
&asn_DEF_pdsch_256QAM_FR1_6,
0,
{ 0, 0, 0 },
0, 0, /* No default value */
"pdsch-256QAM-FR1"
},
{ ATF_POINTER, 2, offsetof(struct Phy_ParametersFR1, pdsch_RE_MappingFR1_PerSymbol),
(ASN_TAG_CLASS_CONTEXT | (3 << 2)),
-1, /* IMPLICIT tag at current level */
&asn_DEF_pdsch_RE_MappingFR1_PerSymbol_8,
0,
{ 0, 0, 0 },
0, 0, /* No default value */
"pdsch-RE-MappingFR1-PerSymbol"
},
{ ATF_POINTER, 1, offsetof(struct Phy_ParametersFR1, ext1),
(ASN_TAG_CLASS_CONTEXT | (4 << 2)),
0,
&asn_DEF_ext1_12,
0,
{ 0, 0, 0 },
0, 0, /* No default value */
"ext1"
},
};
static const int asn_MAP_Phy_ParametersFR1_oms_1[] = { 0, 1, 2, 3, 4 };
static const ber_tlv_tag_t asn_DEF_Phy_ParametersFR1_tags_1[] = {
(ASN_TAG_CLASS_UNIVERSAL | (16 << 2))
};
static const asn_TYPE_tag2member_t asn_MAP_Phy_ParametersFR1_tag2el_1[] = {
{ (ASN_TAG_CLASS_CONTEXT | (0 << 2)), 0, 0, 0 }, /* pdcch-MonitoringSingleOccasion */
{ (ASN_TAG_CLASS_CONTEXT | (1 << 2)), 1, 0, 0 }, /* scs-60kHz */
{ (ASN_TAG_CLASS_CONTEXT | (2 << 2)), 2, 0, 0 }, /* pdsch-256QAM-FR1 */
{ (ASN_TAG_CLASS_CONTEXT | (3 << 2)), 3, 0, 0 }, /* pdsch-RE-MappingFR1-PerSymbol */
{ (ASN_TAG_CLASS_CONTEXT | (4 << 2)), 4, 0, 0 } /* ext1 */
};
asn_SEQUENCE_specifics_t asn_SPC_Phy_ParametersFR1_specs_1 = {
sizeof(struct Phy_ParametersFR1),
offsetof(struct Phy_ParametersFR1, _asn_ctx),
asn_MAP_Phy_ParametersFR1_tag2el_1,
5, /* Count of tags in the map */
asn_MAP_Phy_ParametersFR1_oms_1, /* Optional members */
4, 1, /* Root/Additions */
4, /* First extension addition */
};
asn_TYPE_descriptor_t asn_DEF_Phy_ParametersFR1 = {
"Phy-ParametersFR1",
"Phy-ParametersFR1",
&asn_OP_SEQUENCE,
asn_DEF_Phy_ParametersFR1_tags_1,
sizeof(asn_DEF_Phy_ParametersFR1_tags_1)
/sizeof(asn_DEF_Phy_ParametersFR1_tags_1[0]), /* 1 */
asn_DEF_Phy_ParametersFR1_tags_1, /* Same as above */
sizeof(asn_DEF_Phy_ParametersFR1_tags_1)
/sizeof(asn_DEF_Phy_ParametersFR1_tags_1[0]), /* 1 */
{ 0, 0, SEQUENCE_constraint },
asn_MBR_Phy_ParametersFR1_1,
5, /* Elements count */
&asn_SPC_Phy_ParametersFR1_specs_1 /* Additional specs */
};
|
587181.c | #include "utone.h"
#include "md5.h"
#include "tap.h"
#include "test.h"
typedef struct {
ut_noise *ns;
ut_tbvcf *tn;
} UserData;
int t_tbvcf(ut_test *tst, ut_data *ut, const char *hash)
{
uint32_t n;
int fail = 0;
ut_srand(ut, 0);
UserData ud;
ut_noise_create(&ud.ns);
ut_tbvcf_create(&ud.tn);
ut_noise_init(ut, ud.ns);
ut_tbvcf_init(ut, ud.tn);
ud.tn->dist = 1.0;
UTFLOAT in = 0;
for(n = 0; n < tst->size; n++) {
in = 0;
ut_noise_compute(ut, ud.ns, NULL, &in);
ut_tbvcf_compute(ut, ud.tn, &in, &ut->out[0]);
ut_test_add_sample(tst, ut->out[0]);
}
fail = ut_test_verify(tst, hash);
ut_noise_destroy(&ud.ns);
ut_tbvcf_destroy(&ud.tn);
if(fail) return UT_NOT_OK;
else return UT_OK;
}
|
269044.c | /*
* Copyright (c) 2013 Qualcomm Atheros, Inc.
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
* REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
* AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
* INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
* LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
* OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
* PERFORMANCE OF THIS SOFTWARE.
*/
#include "wbuf.h"
|
36079.c | /*
==============================================================================
Name: vertex.c
Contributors: Renan Augusto Starke, Caio Felipe Campoy, Rodrigo Luiz da Costa
Created on: 05/07/2016
Version: 1.0
Last modification: 16/06/2017
Copyright: MIT License
Description: Vertex structures for using in applications using graphs
==============================================================================
*/
#include <stdlib.h>
#include <stdio.h>
#include "vertex.h"
#include "../linkedList/linkedList.h"
//#define DEBUG
struct vertexes
{
linkedList_t* edges;
vertex_t* dadVertex;
//vertex_t* previousVertex;
int ID;
int groupID;
int distance;
int visited;
};
struct edges {
int weight;
vertex_t* sourceVertex;
vertex_t* destinyVertex;
edgeStatus_t status; // Status for file exportation
void* data; // temp name | Remember to initialize as 0
int used;
};
vertex_t* createVertex(int ID)
{
vertex_t* vertex = NULL;
vertex = malloc(sizeof(vertex_t));
if (vertex == NULL) {
perror("createVertex:");
exit(EXIT_FAILURE);
}
vertex->ID = ID;
vertex->edges = createLinkedList();
vertex->groupID = -1; // -1 = Non-visited vertex
vertex->dadVertex = NULL;
return vertex;
}
int vertexGetID(vertex_t* vertex)
{
if (vertex == NULL)
{
fprintf(stderr, "vertexGetID: Invalid vertex!\n");
exit(EXIT_FAILURE);
}
return vertex->ID;
}
edges_t* createEdge(vertex_t* source, vertex_t* vertex, void* data)
{
edges_t* edge;
edge = (edges_t*)malloc(sizeof(edges_t));
if (edge == NULL) {
perror("createEdge:");
exit(EXIT_FAILURE);
}
edge->data = data;
edge->sourceVertex = source;
edge->destinyVertex = vertex;
edge->used = 0;
return edge;
}
void addEdge(vertex_t* vertex, edges_t* edge)
{
node_t* node;
if (vertex == NULL || edge == NULL) {
fprintf(stderr, "addEdge: Invalid data!\n");
exit(EXIT_FAILURE);
}
node = createNode(edge);
addTail(vertex->edges, node);
#ifdef DEBUG
printf("addEdge: %d - %d to Vertex %d\n", edge->sourceVertex->ID, edge->destinyVertex->ID, vertex->ID);
#endif // DEBUG
}
linkedList_t* vertexGetEdges(vertex_t *vertex)
{
if (vertex == NULL){
fprintf(stderr, "vertexGetEdges: Invalid vertex!\n");
exit(EXIT_FAILURE);
}
return vertex->edges;
}
int edgeGetWeight(edges_t* edge)
{
if (edge == NULL)
{
fprintf(stderr, "edgeGetWeight: Invalid edge!\n");
exit(EXIT_FAILURE);
}
return edge->weight;
}
vertex_t* edgeGetAdjacent(edges_t* edge)
{
if (edge == NULL)
{
fprintf(stderr, "edgeGetAdjacent: Invalid edge!\n");
exit(EXIT_FAILURE);
}
return edge->destinyVertex;
}
vertex_t* edgeGetSource(edges_t* edge)
{
if (edge == NULL)
{
fprintf(stderr, "edgeGetSource: Invalid edge!\n");
exit(EXIT_FAILURE);
}
return edge->sourceVertex;
}
edges_t* searchAdjacent(vertex_t* vertex, vertex_t* adjacentVertex)
{
node_t* node;
edges_t* edge;
if (vertex == NULL)
{
fprintf(stderr, "searchAdjacent: Invalid edge!\n");
exit(EXIT_FAILURE);
}
// Edge list navegation
node = getHead(vertex->edges);
while (node)
{
edge = getData(node);
if (edge->destinyVertex == adjacentVertex || edge->sourceVertex == adjacentVertex)
return edge;
node = getNext(node);
}
return NULL;
}
edgeStatus_t edgeGetStatus(edges_t* edge)
{
if (edge == NULL){
fprintf(stderr, "edgeGetStatus: Invalid edge!\n");
exit(EXIT_FAILURE);
}
return edge->status;
}
void edgeSetStatus(edges_t* edge, edgeStatus_t status)
{
if (edge == NULL)
{
fprintf(stderr, "edgeSetStatus: Invalid edge!\n");
exit(EXIT_FAILURE);
}
edge->status = status;
}
/*------------------------------------------*/
void vertexSetGroup(vertex_t* vertex, int group)
{
if (vertex == NULL)
{
fprintf(stderr, "vertexSetGroup: Invalid vertex!\n");
exit(EXIT_FAILURE);
}
vertex->groupID = group;
}
int vertexGetGroup(vertex_t* vertex)
{
if (vertex == NULL)
{
fprintf(stderr, "vertexGetGroup: Invalid vertex\n");
exit(EXIT_FAILURE);
}
return vertex->groupID;
}
void vertexSetDad(vertex_t* vertex, vertex_t* dadVertex)
{
if (vertex == NULL)
{
fprintf(stderr, "vertexSetDad: Invalid vertex!\n");
exit(EXIT_FAILURE);
}
vertex->dadVertex = dadVertex;
}
vertex_t* vertexGetDad(vertex_t* vertex)
{
if (vertex == NULL)
{
fprintf(stderr, "vertexGetDad: Invalid vertex!\n");
exit(EXIT_FAILURE);
}
return vertex->dadVertex;
}
void printVertex(vertex_t* vertex)
{
if (vertex == NULL)
{
fprintf(stderr, "printVertex: Invalid vertex!\n");
exit(EXIT_FAILURE);
}
printf("Pointer: %p\nID: %d\n", vertex, vertex->ID);
}
void vertexSetVisited(vertex_t* vertex, int x)
{
if (vertex == NULL){
fprintf(stderr, "vertexSetVisited: invalid vertex\n");
exit(EXIT_FAILURE);
}
vertex->visited = x;
}
int vertexGetVisited(vertex_t* vertex){
if (vertex == NULL){
fprintf(stderr, "vertexGetVisited: invalid Vertex\n");
exit(EXIT_FAILURE);
}
return vertex->visited;
}
void printNeighborsList(vertex_t* vertex)
{
if (vertex == NULL)
{
fprintf(stderr, "printNeighborsList: Invalid vertex!");
exit(EXIT_FAILURE);
}
printList(vertex->edges);
}
edges_t* counterEdge(edges_t* edge)
{
if (edge == NULL)
{
fprintf(stderr, "counterEdge: Invalid edge!\n");
exit(EXIT_FAILURE);
}
vertex_t* sourceVertex = edge->sourceVertex;
vertex_t* destinyVertex = edge->destinyVertex;
node_t* node = getHead(destinyVertex->edges);
while (node)
{
edge = getData(node);
if (edge->destinyVertex == sourceVertex)
return edge;
node = getNext(node);
}
return edge;
}
void* edgeGetData(edges_t* edge)
{
if (edge == NULL)
{
fprintf(stderr, "edgeGetData: Invalid pointer!\n");
exit(EXIT_FAILURE);
}
return edge->data;
}
void createLoop(linkedList_t* loopsList, linkedList_t* visitedList, edges_t* edge)
{
if (loopsList == NULL)
{
fprintf(stderr, "createLoop: Invalid loopsList pointer!\n");
exit(EXIT_FAILURE);
}
if (visitedList == NULL)
{
fprintf(stderr, "createLoop: Invalid visitedList pointer!\n");
exit(EXIT_FAILURE);
}
if (edge == NULL)
{
fprintf(stderr, "createLoop: Invalid edge pointer!\n");
exit(EXIT_FAILURE);
}
linkedList_t* list = createLinkedList();
node_t* node = createNode(list);
addTail(loopsList, node); //create a new loop list
vertex_t* visitedVertex = NULL;
vertex_t* loopVertex = edge->destinyVertex;
vertex_t* vertex = edge->sourceVertex;
node_t* visitedNode = getTail(visitedList);
node = createNode(edge);
addTail(list, node); //add first edge to the list
#ifdef DEBUG
int i = listGetSize(loopsList);
printf("Loop %d:\n", i);
printf("\tEdge: %d - %d\n", edge->sourceVertex->ID, edge->destinyVertex->ID);
#endif // DEBUG
while (vertex != loopVertex) //search on visitedList for the edges forming the loop
{
edge = getData(visitedNode);
visitedVertex = edge->destinyVertex;
if(vertex == visitedVertex)
{
node = createNode(edge);
addTail(list, node);
vertex = edge->sourceVertex;
#ifdef DEBUG
printf("\tEdge: %d - %d\n", edge->sourceVertex->ID, edge->destinyVertex->ID);
#endif // DEBUG
}
visitedNode = getPrevious(visitedNode);
}
}
void printLoops(linkedList_t* loopsList)
{
if (loopsList == NULL)
{
fprintf(stderr, "printLoops: Invalid loopsList pointer!\n");
exit(EXIT_FAILURE);
}
node_t* node = getHead(loopsList);
linkedList_t* loopList;
int i = 1;
printf("SIMULATION-PROGRAM-USING-GRAPHS\n\n");
printf("Mesh analysis - Linearly independent equations: \n\n");
printf("Meshes - Vertexes paths: \n");
while(node)
{
printf("%d: ", i);
loopList = getData(node);
node_t* loopNode = getTail(loopList);
edges_t* edge;
while(loopNode)
{
edge = getData(loopNode);
printf("%d-", edge->sourceVertex->ID);
loopNode = getPrevious(loopNode);
}
printf("%d\n", edge->destinyVertex->ID);
node = getNext(node);
i++;
}
}
int isEdgeUsed(edges_t* edge)
{
if (edge == NULL)
{
fprintf(stderr, "isEdgeUsed: Invalid edge pointer!\n");
exit(EXIT_FAILURE);
}
return edge->used;
}
void setUsedEdge(edges_t* edge, int i)
{
if (edge == NULL)
{
fprintf(stderr, "setUsedEdge: Invalid edge pointer!\n");
exit(EXIT_FAILURE);
}
edge->used = i;
}
void printEdge(edges_t* edge)
{
printf("edge: %d - %d\n", edge->sourceVertex->ID, edge->destinyVertex->ID);
}
//void vertexSetDistance(vertex_t* vertex, int distance) {
//
// if (vertex == NULL)
// {
// fprintf(stderr, "vertexSetDistance: Invalid vertex!\n");
// exit(EXIT_FAILURE);
// }
//
// vertex->distance = distance;
//}
//
//int vertexGetDistance(vertex_t* vertex){
//
// if (vertex == NULL)
// {
// fprintf(stderr, "vertexGetDistance: Invalid vertex!\n");
// exit(EXIT_FAILURE);
// }
//
// return vertex->distance;
//}
//
//int vertexGetLenght(vertex_t* sourceVertex, vertex_t* destinyVertex)
//{
// edges_t* edge;
//
// if (sourceVertex == NULL || destinyVertex == NULL)
// {
// fprintf(stderr, "vertexGetLenght: Invalid vertexes!\n");
// exit(EXIT_FAILURE);
// }
//
// edge = searchAdjacent(sourceVertex, destinyVertex);
//
// if (edge == NULL)
// {
// fprintf(stderr, "vertexGetLenght: Non-adjacent vertexes!\n");
// exit(EXIT_FAILURE);
// }
//
// return edge->weight;
//}
//
//void vertexSetPrevious(vertex_t* vertex, vertex_t* previousVertex)
//{
// if (vertex == NULL || previousVertex == NULL)
// {
// fprintf(stderr, "vertexSetPrevious: Invalid vertexes!\n");
// exit(EXIT_FAILURE);
// }
//
// vertex->previousVertex = previousVertex;
//}
//
//vertex_t* vertexGetPrevious(vertex_t* vertex)
//{
// if (vertex == NULL)
// {
// fprintf(stderr, "vertexGetPrevious: Invalid vertex\n");
// exit(EXIT_FAILURE);
// }
//
// return vertex->previousVertex;
//}
|
541009.c | /*
Copyright (c) 2010, Florian Reuter
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 Florian Reuter nor the names of its contributors
may be used to endorse or promote products derived from this
software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <opc/opc.h>
#include "internal.h"
static void* ensureItem(void **array_, puint32_t items, puint32_t item_size) {
*array_=xmlRealloc(*array_, (items+1)*item_size);
return *array_;
}
static opcContainerPart* ensurePart(opcContainer *container) {
return ((opcContainerPart*)ensureItem((void**)&container->part_array, container->part_items, sizeof(opcContainerPart)))+container->part_items;
}
static opcContainerRelPrefix* ensureRelPrefix(opcContainer *container) {
return ((opcContainerRelPrefix*)ensureItem((void**)&container->relprefix_array, container->relprefix_items, sizeof(opcContainerRelPrefix)))+container->relprefix_items;
}
static opcContainerType* ensureType(opcContainer *container) {
return ((opcContainerType*)ensureItem((void**)&container->type_array, container->type_items, sizeof(opcContainerType)))+container->type_items;
}
static opcContainerExtension* ensureExtension(opcContainer *container) {
return ((opcContainerExtension*)ensureItem((void**)&container->extension_array, container->extension_items, sizeof(opcContainerExtension)))+container->extension_items;
}
static opcContainerRelationType* ensureRelationType(opcContainer *container) {
return ((opcContainerRelationType*)ensureItem((void**)&container->relationtype_array, container->relationtype_items, sizeof(opcContainerRelationType)))+container->relationtype_items;
}
static opcContainerExternalRelation* ensureExternalRelation(opcContainer *container) {
return ((opcContainerExternalRelation*)ensureItem((void**)&container->externalrelation_array, container->externalrelation_items, sizeof(opcContainerRelationType)))+container->externalrelation_items;
}
static opc_bool_t findItem(void *array_, opc_uint32_t items, const void *key1, opc_uint32_t key2, int (*cmp_fct)(const void *key1, opc_uint32_t key2, const void *array_, opc_uint32_t item), opc_uint32_t *pos) {
opc_uint32_t i=0;
opc_uint32_t j=items;
while(i<j) {
opc_uint32_t m=i+(j-i)/2;
OPC_ASSERT(i<=m && m<j);
int cmp=cmp_fct(key1, key2, array_, m);
if (cmp<0) {
j=m;
} else if (cmp>0) {
i=m+1;
} else {
*pos=m;
return OPC_TRUE;
}
}
OPC_ASSERT(i==j);
*pos=i;
return OPC_FALSE;
}
#define ensureGap(array_, items_, i) \
{\
for (opc_uint32_t k=items_;k>i;k--) { \
(array_)[k]=(array_)[k-1];\
}\
(items_)++;\
OPC_ASSERT(i>=0 && i<(items_));\
opc_bzero_mem(&(array_)[i], sizeof((array_)[i]));\
}
static inline int part_cmp_fct(const void *key, opc_uint32_t v, const void *array_, opc_uint32_t item) {
return xmlStrcmp((xmlChar*)key, ((opcContainerPart*)array_)[item].name);
}
opcContainerPart *opcContainerInsertPart(opcContainer *container, const xmlChar *name, opc_bool_t insert) {
opc_uint32_t i=0;
if (findItem(container->part_array, container->part_items, name, 0, part_cmp_fct, &i)) {
return &container->part_array[i];
} else if (insert && NULL!=ensurePart(container)) {
ensureGap(container->part_array, container->part_items, i);
container->part_array[i].first_segment_id=-1;
container->part_array[i].last_segment_id=-1;
container->part_array[i].name=xmlStrdup(name);
container->part_array[i].rel_segment_id=-1;
return &container->part_array[i];
} else {
return NULL;
}
}
#define deleteItem(array_, items_, i) \
{\
for(opc_uint32_t k=i+1;k<items_;k++) {\
array_[k-1]=array_[k];\
}\
items_--;\
}
static opc_error_t opcContainerDeleteAllRelationsToPart(opcContainer *container, opcPart part, opcContainerRelation **relation_array, opc_uint32_t *relation_items) {
for(opc_uint32_t i=0;i<*relation_items;) {
if (0==(*relation_array)[i].target_mode && part==(*relation_array)[i].target_ptr) {
deleteItem((*relation_array), (*relation_items), i);
} else {
i++;
}
}
return OPC_ERROR_NONE;
}
opc_error_t opcContainerDeletePart(opcContainer *container, const xmlChar *name) {
opc_error_t ret=OPC_ERROR_NONE;
opc_uint32_t i=0;
if (findItem(container->part_array, container->part_items, name, 0, part_cmp_fct, &i)) {
if (-1!=container->part_array[i].first_segment_id) {
opcContainerDeletePartEx(container, name, OPC_FALSE);
}
if (-1!=container->part_array[i].rel_segment_id) {
opcContainerDeletePartEx(container, name, OPC_TRUE);
}
OPC_ENSURE(OPC_ERROR_NONE==opcContainerDeleteAllRelationsToPart(container, container->part_array[i].name, &container->relation_array, &container->relation_items));
for(opc_uint32_t j=0;j<container->part_items;j++) {
OPC_ENSURE(OPC_ERROR_NONE==opcContainerDeleteAllRelationsToPart(container, container->part_array[i].name, &container->part_array[j].relation_array, &container->part_array[j].relation_items));
}
if (NULL!=container->part_array[i].relation_array){
xmlFree(container->part_array[i].relation_array);
}
if (NULL!=container->part_array[i].name){
xmlFree(container->part_array[i].name);
}
deleteItem(container->part_array, container->part_items, i);
}
return ret;
}
#define OPC_MAX_UINT16 65535
static opc_uint32_t insertRelPrefix(opcContainer *container, const xmlChar *relPrefix) {
opc_uint32_t i=container->relprefix_items;
for(;i>0 && 0!=xmlStrcmp(container->relprefix_array[i-1].prefix, relPrefix);) {
i--;
};
if (i>0) {
OPC_ASSERT(0==xmlStrcmp(container->relprefix_array[i-1].prefix, relPrefix));
return i-1;
} else {
if (container->relprefix_items<OPC_MAX_UINT16 && NULL!=ensureRelPrefix(container)) {
i=container->relprefix_items++;
container->relprefix_array[i].prefix=xmlStrdup(relPrefix);
return i;
} else {
return -1; // error
}
}
}
static opc_uint32_t findRelPrefix(opcContainer *container, const xmlChar *relPrefix, opc_uint32_t relPrefixLen) {
for(opc_uint32_t i=0;i<=container->relprefix_items;i++) {
if (0==xmlStrncmp(container->relprefix_array[i].prefix, relPrefix, relPrefixLen) && 0==container->relprefix_array[i].prefix[relPrefixLen]) {
return i;
}
}
return -1; // not found
}
static opc_uint32_t splitRelPrefix(opcContainer *container, const xmlChar *rel, opc_uint32_t *counter) {
opc_uint32_t len=xmlStrlen(rel);
while(len>0 && rel[len-1]>='0' && rel[len-1]<='9') len--;
if (NULL!=counter) {
if (rel[len]!=0) {
*counter=atoi((char*)(rel+len));
} else {
*counter=-1; // no counter
}
}
return len;
}
static opc_uint32_t assembleRelId(opc_uint32_t prefix, opc_uint16_t relCounter) {
opc_uint32_t ret=relCounter;
if (-1!=prefix) {
ret|=prefix<<16;
}
return ret;
}
static opc_uint32_t createRelId(opcContainer *container, const xmlChar *relPrefix, opc_uint16_t relCounter) {
opc_uint32_t prefix=insertRelPrefix(container, relPrefix);
opc_uint32_t ret=assembleRelId(prefix, relCounter);
return ret;
}
static inline int type_cmp_fct(const void *key, opc_uint32_t v, const void *array_, opc_uint32_t item) {
return xmlStrcmp((xmlChar*)key, ((opcContainerType*)array_)[item].type);
}
opcContainerType *insertType(opcContainer *container, const xmlChar *type, opc_bool_t insert) {
opc_uint32_t i=0;
if (findItem(container->type_array, container->type_items, type, 0, type_cmp_fct, &i)) {
return &container->type_array[i];
} else if (insert && NULL!=ensureType(container)) {
ensureGap(container->type_array, container->type_items, i);
container->type_array[i].type=xmlStrdup(type);
return &container->type_array[i];
} else {
return NULL;
}
}
static inline int extension_cmp_fct(const void *key, opc_uint32_t v, const void *array_, opc_uint32_t item) {
return xmlStrcmp((xmlChar*)key, ((opcContainerExtension*)array_)[item].extension);
}
opcContainerExtension *opcContainerInsertExtension(opcContainer *container, const xmlChar *extension, opc_bool_t insert) {
opc_uint32_t i=0;
if (findItem(container->extension_array, container->extension_items, extension, 0, extension_cmp_fct, &i)) {
return &container->extension_array[i];
} else if (insert && NULL!=ensureExtension(container)) {
ensureGap(container->extension_array, container->extension_items, i);
container->extension_array[i].extension=xmlStrdup(extension);
return &container->extension_array[i];
} else {
return NULL;
}
}
static inline int relationtype_cmp_fct(const void *key, opc_uint32_t v, const void *array_, opc_uint32_t item) {
return xmlStrcmp((xmlChar*)key, ((opcContainerRelationType*)array_)[item].type);
}
opcContainerRelationType *opcContainerInsertRelationType(opcContainer *container, const xmlChar *type, opc_bool_t insert) {
opc_uint32_t i=0;
if (findItem(container->relationtype_array, container->relationtype_items, type, 0, relationtype_cmp_fct, &i)) {
return &container->relationtype_array[i];
} else if (insert && NULL!=ensureRelationType(container)) {
ensureGap(container->relationtype_array, container->relationtype_items, i);
container->relationtype_array[i].type=xmlStrdup(type);
return &container->relationtype_array[i];
} else {
return NULL;
}
}
static inline int externalrelation_cmp_fct(const void *key, opc_uint32_t v, const void *array_, opc_uint32_t item) {
return xmlStrcmp((xmlChar*)key, ((opcContainerExternalRelation*)array_)[item].target);
}
opcContainerExternalRelation*insertExternalRelation(opcContainer *container, const xmlChar *target, opc_bool_t insert) {
opc_uint32_t i=0;
if (findItem(container->externalrelation_array, container->externalrelation_items, target, 0, externalrelation_cmp_fct, &i)) {
return &container->externalrelation_array[i];
} else if (insert && NULL!=ensureExternalRelation(container)) {
ensureGap(container->externalrelation_array, container->externalrelation_items, i);
container->externalrelation_array[i].target=xmlStrdup(target);
return &container->externalrelation_array[i];
} else {
return NULL;
}
}
static inline int relation_cmp_fct(const void *key, opc_uint32_t v, const void *array_, opc_uint32_t item) {
opcRelation r1=v;
opcRelation r2=((opcContainerRelation*)array_)[item].relation_id;
if (OPC_CONTAINER_RELID_PREFIX(r1)==OPC_CONTAINER_RELID_PREFIX(r2)) {
if (OPC_CONTAINER_RELID_COUNTER_NONE==OPC_CONTAINER_RELID_COUNTER(r1)) {
return (OPC_CONTAINER_RELID_COUNTER_NONE==OPC_CONTAINER_RELID_COUNTER(r2)?0:-1);
} else if (OPC_CONTAINER_RELID_COUNTER_NONE==OPC_CONTAINER_RELID_COUNTER(r2)) {
OPC_ASSERT(OPC_CONTAINER_RELID_COUNTER_NONE!=OPC_CONTAINER_RELID_COUNTER(r1));
return 1;
} else {
OPC_ASSERT(OPC_CONTAINER_RELID_COUNTER_NONE!=OPC_CONTAINER_RELID_COUNTER(r1) && OPC_CONTAINER_RELID_COUNTER_NONE!=OPC_CONTAINER_RELID_COUNTER(r2));
return OPC_CONTAINER_RELID_COUNTER(r1)-OPC_CONTAINER_RELID_COUNTER(r2);
}
} else {
return OPC_CONTAINER_RELID_PREFIX(r1)-OPC_CONTAINER_RELID_PREFIX(r2);
}
}
opcContainerRelation *opcContainerInsertRelation(opcContainerRelation **relation_array, opc_uint32_t *relation_items,
opc_uint32_t relation_id,
xmlChar *relation_type,
opc_uint32_t target_mode, xmlChar *target_ptr) {
OPC_ASSERT(NULL!=relation_items);
opc_uint32_t i=0;
if (*relation_items>0) {
opc_bool_t ret=findItem(*relation_array, *relation_items, NULL, relation_id, relation_cmp_fct, &i);
if (ret) { // error, relation already exists!
return NULL;
}
}
if (NULL!=ensureItem((void**)relation_array, *relation_items, sizeof(opcContainerRelation))) {
for (opc_uint32_t k=(*relation_items);k>i;k--) {
(*relation_array)[k]=(*relation_array)[k-1];
}
(*relation_items)++;
OPC_ASSERT(i>=0 && i<(*relation_items));\
opc_bzero_mem(&(*relation_array)[i], sizeof((*relation_array)[i]));\
(*relation_array)[i].relation_id=relation_id;
(*relation_array)[i].relation_type=relation_type;
(*relation_array)[i].target_mode=target_mode;
(*relation_array)[i].target_ptr=target_ptr;
return &(*relation_array)[i];
} else {
return NULL; // memory error!
}
}
opcContainerRelation *opcContainerFindRelation(opcContainer *container, opcContainerRelation *relation_array, opc_uint32_t relation_items, opcRelation relation) {
opc_uint32_t i=0;
opc_bool_t ret=findItem(relation_array, relation_items, NULL, relation, relation_cmp_fct, &i);
return (ret?&relation_array[i]:NULL);
}
opc_error_t opcContainerDeleteRelation(opcContainer *container, opcContainerRelation **relation_array, opc_uint32_t *relation_items, opcRelation relation) {
opc_error_t err=OPC_ERROR_NONE;
opc_uint32_t i=0;
opc_bool_t ret=findItem(*relation_array, *relation_items, NULL, relation, relation_cmp_fct, &i);
if (ret) {
deleteItem((*relation_array), (*relation_items), i);
}
return err;
}
opcContainerRelation *opcContainerFindRelationById(opcContainer *container, opcContainerRelation *relation_array, opc_uint32_t relation_items, const xmlChar *relation_id) {
opc_uint32_t counter=-1;
opc_uint32_t id_len=splitRelPrefix(container, relation_id, &counter);
opc_uint32_t rel=-1;
if (id_len>0) {
opc_uint32_t prefix=findRelPrefix(container, relation_id, id_len);
if (-1!=prefix) {
rel=assembleRelId(prefix, counter);
}
} else {
rel=assembleRelId(-1, counter);
}
opcContainerRelation *ret=(-1!=rel?opcContainerFindRelation(container, relation_array, relation_items, rel):NULL);
return ret;
}
static void opc_container_normalize_part_to_helper_buffer(xmlChar *buf, int buf_len,
const xmlChar *base,
const xmlChar *name) {
int j=xmlStrlen(base);
int i=0;
OPC_ASSERT(j<=buf_len);
if (j>0) {
memcpy(buf, base, j*sizeof(xmlChar));
}
while(j>0 && buf[j-1]!='/') j--; // so make sure base has a trailing "/"
while(name[i]!=0) {
if (name[i]=='/') {
j=0; /* absolute path */
while (name[i]=='/') i++;
} else if (name[i]=='.' && name[i+1]=='/') {
/* skip */
i+=1;
while (name[i]=='/') i++;
} else if (name[i]=='.' && name[i+1]=='.' && name[i+2]=='/') {
while(j>0 && buf[j-1]=='/') j--; /* skip base '/' */
while(j>0 && buf[j-1]!='/') j--; /* navigate one dir up */
i+=2;
while (name[i]=='/') i++;
} else {
/* copy step */
OPC_ASSERT(j+1<=buf_len);
while(j+1<buf_len && name[i]!=0 && name[i]!='/') {
buf[j++]=name[i++];
}
if (name[i]=='/' && j+1<buf_len) {
buf[j++]='/';
}
while (name[i]=='/') i++;
}
}
OPC_ASSERT(j+1<buf_len);
buf[j]=0;
}
static void opcConstainerParseRels(opcContainer *c, const xmlChar *partName, opcContainerRelation **relation_array, opc_uint32_t *relation_items) {
mceTextReader_t reader;
if (OPC_ERROR_NONE==opcXmlReaderOpenEx(c, &reader, partName, OPC_TRUE, NULL, NULL, 0)) {
static const char ns[]="http://schemas.openxmlformats.org/package/2006/relationships";
mce_start_document(&reader) {
mce_start_element(&reader, _X(ns), _X("Relationships")) {
mce_skip_attributes(&reader);
mce_start_children(&reader) {
mce_start_element(&reader, NULL, _X("Relationship")) {
const xmlChar *id=NULL;
const xmlChar *type=NULL;
const xmlChar *target=NULL;
const xmlChar *mode=NULL;
mce_start_attributes(&reader) {
mce_start_attribute(&reader, NULL, _X("Id")) {
id=xmlTextReaderConstValue(reader.reader);
} mce_end_attribute(&reader);
mce_start_attribute(&reader, NULL, _X("Type")) {
type=xmlTextReaderConstValue(reader.reader);
} mce_end_attribute(&reader);
mce_start_attribute(&reader, NULL, _X("Target")) {
target=xmlTextReaderConstValue(reader.reader);
} mce_end_attribute(&reader);
mce_start_attribute(&reader, NULL, _X("TargetMode")) {
mode=xmlTextReaderConstValue(reader.reader);
}
} mce_end_attributes(&reader);
mce_error_guard_start(&reader) {
mce_error(&reader, NULL==id || id[0]==0, MCE_ERROR_VALIDATION, "Missing @Id attribute!");
mce_error(&reader, NULL==type || type[0]==0, MCE_ERROR_VALIDATION, "Missing @Type attribute!");
mce_error(&reader, NULL==target || target[0]==0, MCE_ERROR_VALIDATION, "Missing @Id attribute!");
opcContainerRelationType *rel_type=opcContainerInsertRelationType(c, type, OPC_TRUE);
mce_error(&reader, NULL==rel_type, MCE_ERROR_MEMORY, NULL);
opc_uint32_t counter=-1;
opc_uint32_t id_len=splitRelPrefix(c, id, &counter);
((xmlChar *)id)[id_len]=0;
opc_uint32_t rel_id=createRelId(c, id, counter);
if (NULL==mode || 0==xmlStrcasecmp(mode, _X("Internal"))) {
xmlChar target_part_name[OPC_MAX_PATH];
opc_container_normalize_part_to_helper_buffer(target_part_name, sizeof(target_part_name), partName, target);
// printf("%s (%s;%s)\n", target_part_name, base, target);
opcContainerPart *target_part=opcContainerInsertPart(c, target_part_name, OPC_FALSE);
mce_errorf(&reader, NULL==target_part, MCE_ERROR_VALIDATION, "Referenced part %s (%s;%s) does not exists!", target_part_name, partName, target);
// printf("%s %i %s %s\n", id, counter, rel_type->type, target_part->name);
opcContainerRelation *rel=opcContainerInsertRelation(relation_array, relation_items, rel_id, rel_type->type, 0, target_part->name);
OPC_ASSERT(NULL!=rel);
} else if (0==xmlStrcasecmp(mode, _X("External"))) {
opcContainerExternalRelation *ext_rel=insertExternalRelation(c, target, OPC_TRUE);
mce_error(&reader, NULL==ext_rel, MCE_ERROR_MEMORY, NULL);
opcContainerRelation *rel=opcContainerInsertRelation(relation_array, relation_items, rel_id, rel_type->type, 1, ext_rel->target);
OPC_ASSERT(NULL!=rel);
} else {
mce_errorf(&reader, OPC_TRUE, MCE_ERROR_VALIDATION, "TargetMode %s unknown!\n", mode);
}
} mce_error_guard_end(reader);
mce_skip_children(&reader);
} mce_end_element(&reader);
} mce_end_children(&reader);
} mce_end_element(&reader);
} mce_end_document(reader);
OPC_ENSURE(0==mceTextReaderCleanup(&reader));
}
}
static const xmlChar OPC_SEGMENT_CONTENTTYPES[]={'[', 'C', 'o', 'n', 't', 'e', 'n', 't', '_', 'T', 'y', 'p', 'e', 's', ']', '.', 'x', 'm', 'l', 0};
static const xmlChar OPC_SEGMENT_ROOTRELS[]={0};
static opc_error_t opcContainerFree(opcContainer *c) {
if (NULL!=c) {
for(opc_uint32_t i=0;i<c->extension_items;i++) {
xmlFree(c->extension_array[i].extension);
}
for(opc_uint32_t i=0;i<c->type_items;i++) {
xmlFree(c->type_array[i].type);
}
for(opc_uint32_t i=0;i<c->relationtype_items;i++) {
xmlFree(c->relationtype_array[i].type);
}
for(opc_uint32_t i=0;i<c->externalrelation_items;i++) {
xmlFree(c->externalrelation_array[i].target);
}
for(opc_uint32_t i=0;i<c->part_items;i++) {
xmlFree(c->part_array[i].relation_array);
xmlFree(c->part_array[i].name);
}
for(opc_uint32_t i=0;i<c->relprefix_items;i++) {
xmlFree(c->relprefix_array[i].prefix);
}
if (NULL!=c->part_array) xmlFree(c->part_array);
if (NULL!=c->relprefix_array) xmlFree(c->relprefix_array);
if (NULL!=c->type_array) xmlFree(c->type_array);
if (NULL!=c->extension_array) xmlFree(c->extension_array);
if (NULL!=c->relationtype_array) xmlFree(c->relationtype_array);
if (NULL!=c->externalrelation_array) xmlFree(c->externalrelation_array);
if (NULL!=c->relation_array) xmlFree(c->relation_array);
opcZipClose(c->storage, NULL);
xmlFree(c);
}
return OPC_ERROR_NONE;
}
static void opcContainerDumpString(FILE *out, const xmlChar *str, opc_uint32_t max_len, opc_bool_t new_line) {
opc_uint32_t len=(NULL!=str?xmlStrlen(str):0);
if (len<=max_len) {
if (NULL!=str) fputs((const char *)str, out);
for(opc_uint32_t i=len;i<max_len;i++) fputc(' ', out);
} else {
static const char prefix[]="...";
static opc_uint32_t prefix_len=sizeof(prefix)-1;
opc_uint32_t ofs=len-max_len;
if (ofs+prefix_len<len) ofs+=prefix_len; else ofs=len;
fputs(prefix, out);
fputs((const char *)(str+ofs), out);
}
if (new_line) {
fputc('\n', out);
}
}
static void opcContainerDumpLine(FILE *out, const xmlChar line_char, opc_uint32_t max_len, opc_bool_t new_line) {
for(opc_uint32_t i=0;i<max_len;i++) {
fputc(line_char, out);
}
if (new_line) {
fputc('\n', out);
}
}
static void opcContainerRelCalcMax(opcContainer *c,
const xmlChar *part_name,
opcContainerRelation *relation_array, opc_uint32_t relation_items,
opc_uint32_t *max_rel_src,
opc_uint32_t *max_rel_id,
opc_uint32_t *max_rel_dest,
opc_uint32_t *max_rel_type) {
if (relation_items>0) {
opc_uint32_t const src_len=xmlStrlen(part_name);
if (src_len>*max_rel_src) *max_rel_src=src_len;
for(opc_uint32_t j=0;j<relation_items;j++) {
const xmlChar *prefix=NULL;
opc_uint32_t counter=-1;
const xmlChar *type=NULL;
char buf[20]="";
opcRelationGetInformation(c, (opcPart)part_name, relation_array[j].relation_id, &prefix, &counter, &type);
if (-1!=counter) {
sprintf(buf, "%i", counter);
}
opc_uint32_t const type_len=xmlStrlen(type);
if (type_len>*max_rel_type) *max_rel_type=type_len;
opc_uint32_t const id_len=xmlStrlen(prefix)+xmlStrlen(_X(buf));
if (id_len>*max_rel_id) *max_rel_id=id_len;
opc_uint32_t const dest_len=xmlStrlen(relation_array[j].target_ptr);
if (dest_len>*max_rel_dest) *max_rel_dest=dest_len;
}
}
}
static void opcContainerRelDump(opcContainer *c,
FILE *out,
const xmlChar *part_name,
opcContainerRelation *relation_array, opc_uint32_t relation_items,
opc_uint32_t max_rel_src,
opc_uint32_t max_rel_id,
opc_uint32_t max_rel_dest,
opc_uint32_t max_rel_type) {
for(opc_uint32_t j=0;j<relation_items;j++) {
opcContainerDumpString(out, (part_name==NULL?_X("[root]"):part_name), max_rel_src, OPC_FALSE); fputc('|', out);
const xmlChar *prefix=NULL;
opc_uint32_t counter=-1;
const xmlChar *type=NULL;
char buf[20]="";
opcRelationGetInformation(c, (opcPart)part_name, relation_array[j].relation_id, &prefix, &counter, &type);
if (-1!=counter) {
sprintf(buf, "%i", counter);
}
opc_uint32_t prefix_len=xmlStrlen(prefix);
opcContainerDumpString(out, prefix, prefix_len, OPC_FALSE);
OPC_ASSERT(xmlStrlen(_X(buf))+prefix_len<=max_rel_id);
opcContainerDumpString(out, _X(buf), max_rel_id-prefix_len, OPC_FALSE); fputc('|', out);
opcContainerDumpString(out, relation_array[j].target_ptr, max_rel_dest, OPC_FALSE); fputc('|', out);
opcContainerDumpString(out, type, max_rel_type, OPC_TRUE);
}
}
opc_error_t opcContainerDump(opcContainer *c, FILE *out) {
opc_uint32_t max_content_type_len=xmlStrlen(_X("Content Types"));
for(opc_uint32_t i=0;i<c->type_items;i++) {
opc_uint32_t const len=xmlStrlen(c->type_array[i].type);
if (len>max_content_type_len) max_content_type_len=len;
}
opc_uint32_t max_extension_len=xmlStrlen(_X("Extension"));
opc_uint32_t max_extension_type_len=xmlStrlen(_X("Type"));
for(opc_uint32_t i=0;i<c->extension_items;i++) {
opc_uint32_t const len=xmlStrlen(c->extension_array[i].extension);
if (len>max_extension_len) max_extension_len=len;
opc_uint32_t const type_len=xmlStrlen(c->extension_array[i].type);
if (type_len>max_extension_type_len) max_extension_type_len=type_len;
}
opc_uint32_t max_rel_type_len=xmlStrlen(_X("Relation Types"));
for(opc_uint32_t i=0;i<c->relationtype_items;i++) {
opc_uint32_t const len=xmlStrlen(c->relationtype_array[i].type);
if (len>max_rel_type_len) max_rel_type_len=len;
}
opc_uint32_t max_ext_rel_len=xmlStrlen(_X("External Relations"));
for(opc_uint32_t i=0;i<c->externalrelation_items;i++) {
opc_uint32_t const len=xmlStrlen(c->externalrelation_array[i].target);
if (len>max_ext_rel_len) max_ext_rel_len=len;
}
opc_uint32_t max_part_name=xmlStrlen(_X("Part"));
opc_uint32_t max_part_type=xmlStrlen(_X("Type"));
for(opc_uint32_t i=0;i<c->part_items;i++) {
if (-1!=c->part_array[i].first_segment_id) { // deleted?
opc_uint32_t const name_len=xmlStrlen(c->part_array[i].name);
if (name_len>max_part_name) max_part_name=name_len;
opc_uint32_t const type_len=xmlStrlen(opcPartGetType(c, c->part_array[i].name));
if (type_len>max_part_type) max_part_type=type_len;
}
}
opc_uint32_t max_rel_src=xmlStrlen(_X("Source"));
opc_uint32_t max_rel_id=xmlStrlen(_X("Id"));
opc_uint32_t max_rel_dest=xmlStrlen(_X("Destination"));
opc_uint32_t max_rel_type=xmlStrlen(_X("Type"));
if (c->relationtype_items>0) {
opc_uint32_t const src_len=xmlStrlen(_X("[root]"));
if (src_len>max_rel_src) max_rel_src=src_len;
opcContainerRelCalcMax(c, NULL, c->relation_array, c->relation_items, &max_rel_src, &max_rel_id, &max_rel_dest, &max_rel_type);
}
for(opc_uint32_t i=0;i<c->part_items;i++) {
if (c->part_array[i].relation_items>0) {
opcContainerRelCalcMax(c,
c->part_array[i].name,
c->part_array[i].relation_array, c->part_array[i].relation_items,
&max_rel_src,
&max_rel_id,
&max_rel_dest,
&max_rel_type);
}
}
opcContainerDumpString(out, _X("Content Types"), max_content_type_len, OPC_TRUE);
opcContainerDumpLine(out, '-', max_content_type_len, OPC_TRUE);
for(opc_uint32_t i=0;i<c->type_items;i++) {
opcContainerDumpString(out, c->type_array[i].type, max_content_type_len, OPC_TRUE);
}
opcContainerDumpLine(out, '-', max_content_type_len, OPC_TRUE);
opcContainerDumpString(out, _X(""), 0, OPC_TRUE);
opcContainerDumpString(out, _X("Extension"), max_extension_len, OPC_FALSE); fputc('|', out);
opcContainerDumpString(out, _X("Type"), max_extension_type_len, OPC_TRUE);
opcContainerDumpLine(out, '-', max_extension_len, OPC_FALSE); fputc('|', out);
opcContainerDumpLine(out, '-', max_extension_type_len, OPC_TRUE);
for(opc_uint32_t i=0;i<c->extension_items;i++) {
opcContainerDumpString(out, c->extension_array[i].extension, max_extension_len, OPC_FALSE); fputc('|', out);
opcContainerDumpString(out, c->extension_array[i].type, max_extension_type_len, OPC_TRUE);
}
opcContainerDumpLine(out, '-', max_extension_len, OPC_FALSE); fputc('|', out);
opcContainerDumpLine(out, '-', max_extension_type_len, OPC_TRUE);
opcContainerDumpString(out, _X(""), 0, OPC_TRUE);
opcContainerDumpString(out, _X("Relation Types"), max_rel_type_len, OPC_TRUE);
opcContainerDumpLine(out, '-', max_rel_type_len, OPC_TRUE);
for(opc_uint32_t i=0;i<c->relationtype_items;i++) {
opcContainerDumpString(out, c->relationtype_array[i].type, max_rel_type_len, OPC_TRUE);
}
opcContainerDumpLine(out, '-', max_rel_type_len, OPC_TRUE);
opcContainerDumpString(out, _X(""), 0, OPC_TRUE);
opcContainerDumpString(out, _X("External Relations"), max_ext_rel_len, OPC_TRUE);
opcContainerDumpLine(out, '-', max_ext_rel_len, OPC_TRUE);
for(opc_uint32_t i=0;i<c->externalrelation_items;i++) {
opcContainerDumpString(out, c->externalrelation_array[i].target, max_ext_rel_len, OPC_TRUE);
}
opcContainerDumpLine(out, '-', max_ext_rel_len, OPC_TRUE);
opcContainerDumpString(out, _X(""), 0, OPC_TRUE);
opcContainerDumpString(out, _X("Part"), max_part_name, OPC_FALSE); fputc('|', out);
opcContainerDumpString(out, _X("Type"), max_part_type, OPC_TRUE);
opcContainerDumpLine(out, '-', max_part_name, OPC_FALSE); fputc('|', out);
opcContainerDumpLine(out, '-', max_part_type, OPC_TRUE);
for(opc_uint32_t i=0;i<c->part_items;i++) {
if (-1!=c->part_array[i].first_segment_id) { // deleted?
opcContainerDumpString(out, c->part_array[i].name, max_part_name, OPC_FALSE); fputc('|', out);
opcContainerDumpString(out, opcPartGetType(c, c->part_array[i].name), max_part_type, OPC_TRUE);
}
}
opcContainerDumpLine(out, '-', max_part_name, OPC_FALSE); fputc('|', out);
opcContainerDumpLine(out, '-', max_part_type, OPC_TRUE);
opcContainerDumpString(out, _X(""), 0, OPC_TRUE);
opcContainerDumpString(out, _X("Source"), max_rel_src, OPC_FALSE); fputc('|', out);
opcContainerDumpString(out, _X("Id"), max_rel_id, OPC_FALSE); fputc('|', out);
opcContainerDumpString(out, _X("Destination"), max_rel_dest, OPC_FALSE); fputc('|', out);
opcContainerDumpString(out, _X("Type"), max_rel_type, OPC_TRUE);
opcContainerDumpLine(out, '-', max_rel_src, OPC_FALSE); fputc('|', out);
opcContainerDumpLine(out, '-', max_rel_id, OPC_FALSE); fputc('|', out);
opcContainerDumpLine(out, '-', max_rel_dest, OPC_FALSE); fputc('|', out);
opcContainerDumpLine(out, '-', max_rel_type, OPC_TRUE);
if (c->relation_items>0) {
opcContainerRelDump(c,
out,
NULL,
c->relation_array,
c->relation_items,
max_rel_src,
max_rel_id,
max_rel_dest,
max_rel_type);
}
for(opc_uint32_t i=0;i<c->part_items;i++) {
if (-1!=c->part_array[i].first_segment_id && c->part_array[i].relation_items>0) {
opcContainerRelDump(c,
out,
c->part_array[i].name,
c->part_array[i].relation_array, c->part_array[i].relation_items,
max_rel_src,
max_rel_id,
max_rel_dest,
max_rel_type);
}
}
opcContainerDumpLine(out, '-', max_rel_src, OPC_FALSE); fputc('|', out);
opcContainerDumpLine(out, '-', max_rel_id, OPC_FALSE); fputc('|', out);
opcContainerDumpLine(out, '-', max_rel_dest, OPC_FALSE); fputc('|', out);
opcContainerDumpLine(out, '-', max_rel_type, OPC_TRUE);
return OPC_ERROR_NONE;
}
static opc_error_t opcContainerZipLoaderLoadSegment(void *iocontext,
void *userctx,
opcZipSegmentInfo_t *info,
opcZipLoaderOpenCallback *open,
opcZipLoaderReadCallback *read,
opcZipLoaderCloseCallback *close,
opcZipLoaderSkipCallback *skip) {
opc_error_t err=OPC_ERROR_NONE;
opcContainer *c=(opcContainer *)userctx;
OPC_ENSURE(0==skip(iocontext));
if (info->rels_segment) {
if (info->name[0]==0) {
OPC_ASSERT(-1==c->rels_segment_id); // loaded twice??
c->rels_segment_id=opcZipLoadSegment(c->storage, OPC_SEGMENT_ROOTRELS, info->rels_segment, info);
OPC_ASSERT(-1!=c->rels_segment_id); // not loaded??
} else {
opcContainerPart *part=opcContainerInsertPart(c, info->name, OPC_TRUE);
if (NULL!=part) {
OPC_ASSERT(-1==part->rel_segment_id); // loaded twice??
OPC_ASSERT(NULL!=part->name); // no name given???
part->rel_segment_id=opcZipLoadSegment(c->storage, part->name, info->rels_segment, info);
OPC_ASSERT(-1!=part->rel_segment_id); // not loaded???
} else {
err=OPC_ERROR_MEMORY;
}
}
} else if (xmlStrcmp(info->name, OPC_SEGMENT_CONTENTTYPES)==0) {
OPC_ASSERT(-1==c->content_types_segment_id); // loaded twice??
c->content_types_segment_id=opcZipLoadSegment(c->storage, OPC_SEGMENT_CONTENTTYPES, info->rels_segment, info);
OPC_ASSERT(-1!=c->content_types_segment_id); // not loaded??
} else {
opcContainerPart *part=opcContainerInsertPart(c, info->name, OPC_TRUE);
if (NULL!=part) {
OPC_ASSERT(-1==part->first_segment_id); // loaded twice???
OPC_ASSERT(NULL!=part->name); // no name given???
part->first_segment_id=opcZipLoadSegment(c->storage, part->name, info->rels_segment, info);
OPC_ASSERT(-1!=part->first_segment_id); // not loaded???
part->last_segment_id=part->first_segment_id;
if (info->name_len>0 && ('/'==info->name[info->name_len-1] || '\\'==info->name[info->name_len-1])) {
// it is a directoy, get rid of it...
opcContainerDeletePartEx(c, part->name, info->rels_segment);
OPC_ASSERT(-1==part->first_segment_id && -1==part->last_segment_id);
part=NULL; // no longer valid
}
} else {
err=OPC_ERROR_MEMORY;
}
}
return err;
}
static void opcContainerGetOutputPartSegment(opcContainer *container, const xmlChar *name, opc_bool_t rels_segment, opc_uint32_t **first_segment_ref, opc_uint32_t **last_segment_ref) {
if (OPC_SEGMENT_CONTENTTYPES==name) {
OPC_ASSERT(!rels_segment);
*first_segment_ref=&container->content_types_segment_id;
*last_segment_ref=NULL;
} else if (OPC_SEGMENT_ROOTRELS==name) {
OPC_ASSERT(rels_segment);
*first_segment_ref=&container->rels_segment_id;
*last_segment_ref=NULL;
} else {
opcContainerPart *part=opcContainerInsertPart(container, name, OPC_FALSE);
if (NULL!=part) {
if (rels_segment) {
*first_segment_ref=&part->rel_segment_id;
*last_segment_ref=NULL;
} else {
*first_segment_ref=&part->first_segment_id;
*last_segment_ref=&part->last_segment_id;
}
} else {
OPC_ASSERT(OPC_FALSE); // should not happen
*first_segment_ref=NULL;
*last_segment_ref=NULL;
}
}
}
opcContainerInputStream* opcContainerOpenInputStreamEx(opcContainer *container, const xmlChar *name, opc_bool_t rels_segment) {
opcContainerInputStream* ret=NULL;
opc_uint32_t *first_segment=NULL;
opc_uint32_t *last_segment=NULL;
opcContainerGetOutputPartSegment(container, name, rels_segment, &first_segment, &last_segment);
OPC_ASSERT(NULL!=first_segment);
if (NULL!=first_segment) {
ret=(opcContainerInputStream*)xmlMalloc(sizeof(opcContainerInputStream));
if (NULL!=ret) {
opc_bzero_mem(ret, sizeof(*ret));
ret->container=container;
ret->stream=opcZipOpenInputStream(container->storage, *first_segment);
if (NULL==ret->stream) {
xmlFree(ret); ret=NULL; // error
}
}
}
return ret;
}
opcContainerInputStream* opcContainerOpenInputStream(opcContainer *container, const xmlChar *name) {
return opcContainerOpenInputStreamEx(container, name, OPC_FALSE);
}
opc_uint32_t opcContainerReadInputStream(opcContainerInputStream* stream, opc_uint8_t *buffer, opc_uint32_t buffer_len) {
return opcZipReadInputStream(stream->container->storage, stream->stream, buffer, buffer_len);
}
opc_error_t opcContainerCloseInputStream(opcContainerInputStream* stream) {
opc_error_t ret=opcZipCloseInputStream(stream->container->storage, stream->stream);
xmlFree(stream);
return ret;
}
opcCompressionOption_t opcContainerGetInputStreamCompressionOption(opcContainerInputStream* stream) {
opcCompressionOption_t ret=OPC_COMPRESSIONOPTION_NONE;
if (8==stream->stream->inflateState.compression_method) {
// for now its just enough to know that we have a compression...
ret=OPC_COMPRESSIONOPTION_NORMAL; //@TODO look at stream to figure out real compression i.e. NORMAL, FAST, etc...
}
return ret;
}
opcContainerOutputStream* opcContainerCreateOutputStreamEx(opcContainer *container, const xmlChar *name, opc_bool_t rels_segment, opcCompressionOption_t compression_option) {
opcContainerOutputStream* ret=NULL;
opc_uint32_t *first_segment=NULL;
opc_uint32_t *last_segment=NULL;
opcContainerGetOutputPartSegment(container, name, rels_segment, &first_segment, &last_segment);
OPC_ASSERT(NULL!=first_segment);
if (NULL!=first_segment) {
ret=(opcContainerOutputStream*)xmlMalloc(sizeof(opcContainerOutputStream));
if (NULL!=ret) {
opc_bzero_mem(ret, sizeof(*ret));
ret->container=container;
opc_uint16_t compression_method=0; // no compression by default
opc_uint16_t bit_flag=0;
switch(compression_option) {
case OPC_COMPRESSIONOPTION_NONE:
OPC_ASSERT(0==compression_method);
OPC_ASSERT(0==bit_flag);
break;
case OPC_COMPRESSIONOPTION_NORMAL:
compression_method=8;
bit_flag|=0<<1;
break;
case OPC_COMPRESSIONOPTION_MAXIMUM:
compression_method=8;
bit_flag|=1<<1;
break;
case OPC_COMPRESSIONOPTION_FAST:
compression_method=8;
bit_flag|=2<<1;
break;
case OPC_COMPRESSIONOPTION_SUPERFAST:
compression_method=8;
bit_flag|=3<<1;
break;
}
ret->stream=opcZipCreateOutputStream(container->storage, first_segment, name, rels_segment, 0, 0, compression_method, bit_flag);
ret->partName=name;
ret->rels_segment=rels_segment;
if (NULL==ret->stream) {
xmlFree(ret); ret=NULL; // error
}
}
}
return ret;
}
opcContainerOutputStream* opcContainerCreateOutputStream(opcContainer *container, const xmlChar *name, opcCompressionOption_t compression_option) {
return opcContainerCreateOutputStreamEx(container, name, OPC_FALSE, compression_option);
}
opc_uint32_t opcContainerWriteOutputStream(opcContainerOutputStream* stream, const opc_uint8_t *buffer, opc_uint32_t buffer_len) {
return opcZipWriteOutputStream(stream->container->storage, stream->stream, buffer, buffer_len);
}
opc_error_t opcContainerCloseOutputStream(opcContainerOutputStream* stream) {
opc_error_t ret=OPC_ERROR_MEMORY;
opc_uint32_t *first_segment=NULL;
opc_uint32_t *last_segment=NULL;
opcContainerGetOutputPartSegment(stream->container, stream->partName, stream->rels_segment, &first_segment, &last_segment);
OPC_ASSERT(NULL!=first_segment);
if (NULL!=first_segment) {
ret=opcZipCloseOutputStream(stream->container->storage, stream->stream, first_segment);
if (NULL!=last_segment) {
*last_segment=*first_segment;
}
xmlFree(stream);
}
return ret;
}
static opc_error_t opcContainerInit(opcContainer *c, opcContainerOpenMode mode, void *userContext) {
opc_bzero_mem(c, sizeof(*c));
c->content_types_segment_id=-1;
c->rels_segment_id=-1;
c->mode=mode;
c->userContext=userContext;
return OPC_ERROR_NONE;
}
static opcContainer *opcContainerLoadFromZip(opcContainer *c) {
OPC_ASSERT(NULL==c->storage); // loaded twice??
c->storage=opcZipCreate(&c->io);
if (NULL!=c->storage) {
if (OPC_ERROR_NONE==opcZipLoader(&c->io, c, opcContainerZipLoaderLoadSegment)) {
// successfull loaded!
OPC_ENSURE(OPC_ERROR_NONE==opcZipGC(c->storage));
if (-1!=c->content_types_segment_id) {
mceTextReader_t reader;
if (OPC_ERROR_NONE==opcXmlReaderOpenEx(c, &reader, OPC_SEGMENT_CONTENTTYPES, OPC_FALSE, NULL, NULL, 0)) {
static const char ns[]="http://schemas.openxmlformats.org/package/2006/content-types";
mce_start_document(&reader) {
mce_start_element(&reader, _X(ns), _X("Types")) {
mce_skip_attributes(&reader);
mce_start_children(&reader) {
mce_start_element(&reader, NULL, _X("Default")) {
const xmlChar *ext=NULL;
const xmlChar *type=NULL;
mce_start_attributes(&reader) {
mce_start_attribute(&reader, NULL, _X("Extension")) {
ext=xmlTextReaderConstValue(reader.reader);
} mce_end_attribute(&reader);
mce_start_attribute(&reader, NULL, _X("ContentType")) {
type=xmlTextReaderConstValue(reader.reader);
} mce_end_attribute(&reader);
} mce_end_attributes(&reader);
mce_error_guard_start(&reader) {
mce_error(&reader, NULL==ext || ext[0]==0, MCE_ERROR_VALIDATION, "Missing @Extension attribute!");
mce_error(&reader, NULL==type || type[0]==0, MCE_ERROR_VALIDATION, "Missing @ContentType attribute!");
opcContainerType *ct=insertType(c, type, OPC_TRUE);
mce_error(&reader, NULL==ct, MCE_ERROR_MEMORY, NULL);
opcContainerExtension *ce=opcContainerInsertExtension(c, ext, OPC_TRUE);
mce_error(&reader, NULL==ce, MCE_ERROR_MEMORY, NULL);
mce_errorf(&reader, NULL!=ce->type && 0!=xmlStrcmp(ce->type, type), MCE_ERROR_VALIDATION, "Extension \"%s\" is mapped to type \"%s\" as well as \"%s\"", ext, type, ce->type);
ce->type=ct->type;
} mce_error_guard_end(&reader);
mce_skip_children(&reader);
} mce_end_element(&reader);
mce_start_element(&reader, NULL, _X("Override")) {
const xmlChar *name=NULL;
const xmlChar *type=NULL;
mce_start_attributes(&reader) {
mce_start_attribute(&reader, NULL, _X("PartName")) {
name=xmlTextReaderConstValue(reader.reader);
} mce_end_attribute(&reader);
mce_start_attribute(&reader, NULL, _X("ContentType")) {
type=xmlTextReaderConstValue(reader.reader);
} mce_end_attribute(&reader);
} mce_end_attributes(&reader);
mce_error_guard_start(&reader) {
mce_error(&reader, NULL==name, MCE_ERROR_XML, "Attribute @PartName not given!");
mce_error(&reader, NULL==type, MCE_ERROR_XML, "Attribute @ContentType not given!");
opcContainerType*ct=insertType(c, type, OPC_TRUE);
mce_error(&reader, NULL==ct, MCE_ERROR_MEMORY, NULL);
mce_error_strictf(&reader, '/'!=name[0], MCE_ERROR_MEMORY, "Part %s MUST start with a '/'", name);
opcContainerPart *part=opcContainerInsertPart(c, (name[0]=='/'?name+1:name), OPC_FALSE);
mce_error_strictf(&reader, NULL==part, MCE_ERROR_MEMORY, "Part %s does not exist.", name);
if (NULL!=part) {
part->type=ct->type;
}
} mce_error_guard_end(&reader);
mce_skip_children(&reader);
} mce_end_element(&reader);
mce_start_text(&reader) {
//@TODO ensure whitespaces...
} mce_end_text(&reader);
} mce_end_children(&reader);
} mce_end_element(&reader);
} mce_end_document(&reader);
OPC_ENSURE(0==mceTextReaderCleanup(&reader));
}
}
if (NULL!=c && -1!=c->rels_segment_id) {
opcConstainerParseRels(c, OPC_SEGMENT_ROOTRELS, &c->relation_array, &c->relation_items);
}
for(opc_uint32_t i=0;NULL!=c && i<c->part_items;i++) {
opcContainerPart *part=&c->part_array[i];
if (-1!=part->rel_segment_id) {
opcConstainerParseRels(c, part->name, &part->relation_array, &part->relation_items);
}
}
} else {
opcFileCleanupIO(&c->io); // error loading
opcZipClose(c->storage, NULL);
xmlFree(c); c=NULL;
}
} else {
opcFileCleanupIO(&c->io); // error creating zip
xmlFree(c); c=NULL;
}
return c;
}
static opc_uint32_t opcContainerGenerateFileFlags(opcContainerOpenMode mode) {
opc_uint32_t flags=(OPC_OPEN_READ_ONLY!=mode?OPC_FILE_WRITE | OPC_FILE_READ:OPC_FILE_READ);
if (OPC_OPEN_WRITE_ONLY==mode) flags=flags | OPC_FILE_TRUNC;
return flags;
}
opcContainer* opcContainerOpen(const xmlChar *fileName,
opcContainerOpenMode mode,
void *userContext,
const xmlChar *destName) {
opcContainer*c=(opcContainer*)xmlMalloc(sizeof(opcContainer));
if (NULL!=c) {
OPC_ENSURE(OPC_ERROR_NONE==opcContainerInit(c, mode, userContext));
if (OPC_ERROR_NONE==opcFileInitIOFile(&c->io, fileName, opcContainerGenerateFileFlags(mode))) {
c=opcContainerLoadFromZip(c);
} else {
xmlFree(c); c=NULL; // error init io
}
}
return c;
}
opcContainer* opcContainerOpenMem(const opc_uint8_t *data, opc_uint32_t data_len,
opcContainerOpenMode mode,
void *userContext) {
opcContainer*c=(opcContainer*)xmlMalloc(sizeof(opcContainer));
if (NULL!=c) {
OPC_ENSURE(OPC_ERROR_NONE==opcContainerInit(c, mode, userContext));
if (OPC_ERROR_NONE==opcFileInitIOMemory(&c->io, data, data_len, opcContainerGenerateFileFlags(mode))) {
c=opcContainerLoadFromZip(c);
} else {
xmlFree(c); c=NULL; // error init io
}
}
return c;
}
opcContainer* opcContainerOpenIO(opcFileReadCallback *ioread,
opcFileWriteCallback *iowrite,
opcFileCloseCallback *ioclose,
opcFileSeekCallback *ioseek,
opcFileTrimCallback *iotrim,
opcFileFlushCallback *ioflush,
void *iocontext,
pofs_t file_size,
opcContainerOpenMode mode,
void *userContext) {
opcContainer*c=(opcContainer*)xmlMalloc(sizeof(opcContainer));
if (NULL!=c) {
OPC_ENSURE(OPC_ERROR_NONE==opcContainerInit(c, mode, userContext));
if (OPC_ERROR_NONE==opcFileInitIO(&c->io, ioread, iowrite, ioclose, ioseek, iotrim, ioflush, iocontext, file_size, opcContainerGenerateFileFlags(mode))) {
c=opcContainerLoadFromZip(c);
} else {
xmlFree(c); c=NULL; // error init io
}
}
return c;
}
static void opcContainerWriteUtf8Raw(opcContainerOutputStream *out, const xmlChar *str) {
opc_uint32_t str_len=xmlStrlen(str);
OPC_ENSURE(str_len==opcContainerWriteOutputStream(out, str, str_len));
}
static void opcContainerWriteUtf8(opcContainerOutputStream *out, const xmlChar *str) {
for(;0!=*str; str++) {
switch(*str) {
case '"':
OPC_ENSURE(6==opcContainerWriteOutputStream(out, _X("""), 6));
break;
case '\'':
OPC_ENSURE(6==opcContainerWriteOutputStream(out, _X("'"), 6));
break;
case '&':
OPC_ENSURE(5==opcContainerWriteOutputStream(out, _X("&"), 5));
break;
case '<':
OPC_ENSURE(4==opcContainerWriteOutputStream(out, _X("<"), 4));
break;
case '>':
OPC_ENSURE(4==opcContainerWriteOutputStream(out, _X(">"), 4));
break;
default:
OPC_ENSURE(1==opcContainerWriteOutputStream(out, str, 1));
break;
}
}
}
static void opcContainerWriteContentTypes(opcContainer *c) {
opcContainerOutputStream *out=opcContainerCreateOutputStreamEx(c, OPC_SEGMENT_CONTENTTYPES, OPC_FALSE, OPC_COMPRESSIONOPTION_NORMAL);
if (NULL!=out) {
opcContainerWriteUtf8Raw(out, _X("<Types xmlns=\"http://schemas.openxmlformats.org/package/2006/content-types\">"));
for(opc_uint32_t i=0;i<c->extension_items;i++) {
opcContainerWriteUtf8Raw(out, _X("<Default Extension=\""));
opcContainerWriteUtf8(out, c->extension_array[i].extension);
opcContainerWriteUtf8Raw(out, _X("\" ContentType=\""));
opcContainerWriteUtf8(out, c->extension_array[i].type);
opcContainerWriteUtf8Raw(out, _X("\"/>"));
}
for(opc_uint32_t i=0;i<c->part_items;i++) {
if (NULL!=c->part_array[i].type) {
opcContainerWriteUtf8Raw(out, _X("<Override PartName=\"/"));
opcContainerWriteUtf8(out, c->part_array[i].name);
opcContainerWriteUtf8Raw(out, _X("\" ContentType=\""));
opcContainerWriteUtf8(out, c->part_array[i].type);
opcContainerWriteUtf8Raw(out, _X("\"/>"));
}
}
opcContainerWriteUtf8Raw(out, _X("</Types>"));
opcContainerCloseOutputStream(out);
}
}
static void opcHelperCalcRelPath(xmlChar *rel_path, opc_uint32_t rel_path_max, const xmlChar *base, const xmlChar *path) {
opc_uint32_t base_pos=0;
opc_uint32_t path_pos=0;
opc_uint32_t rel_pos=0;
while(0!=base[base_pos]) {
opc_uint32_t base_next=base_pos; while(0!=base[base_next] && '/'!=base[base_next]) base_next++;
opc_uint32_t path_next=path_pos; while(0!=base[path_next] && '/'!=base[path_next]) path_next++;
if ('/'==base[base_next]) {
if (base_next==path_next && 0==xmlStrncmp(base+base_pos, path+path_pos, base_next-base_pos)) {
base_pos=base_next+1;
path_pos=path_next+1;
} else {
base_pos=base_next+1;
strncpy((char *)(rel_path+rel_pos), "../", rel_path_max-rel_pos);
rel_pos+=3;
}
} else {
OPC_ASSERT(0==base[base_next]);
base_pos=base_next;
OPC_ASSERT(0==base[base_pos]);
}
}
strncpy((char *)(rel_path+rel_pos), (const char *)(path+path_pos), rel_path_max-rel_pos);
#if 0 // for debugging only...
xmlChar helper[OPC_MAX_PATH];
opc_container_normalize_part_to_helper_buffer(helper, sizeof(helper), base, rel_path);
OPC_ASSERT(0==xmlStrcmp(path, helper));
#endif
}
static void opcContainerWriteRels(opcContainer *c, const xmlChar *part_name, opcContainerRelation *relation_array, opc_uint32_t relation_items) {
opcContainerOutputStream *out=opcContainerCreateOutputStreamEx(c, part_name, OPC_TRUE, OPC_COMPRESSIONOPTION_NORMAL);
if (NULL!=out) {
opcContainerWriteUtf8Raw(out, _X("<Relationships xmlns=\"http://schemas.openxmlformats.org/package/2006/relationships\">"));
for(opc_uint32_t i=0;i<relation_items;i++) {
opcContainerWriteUtf8Raw(out, _X("<Relationship Id=\""));
opcContainerWriteUtf8(out, c->relprefix_array[OPC_CONTAINER_RELID_PREFIX(relation_array[i].relation_id)].prefix);
if (OPC_CONTAINER_RELID_COUNTER_NONE!=OPC_CONTAINER_RELID_COUNTER(relation_array[i].relation_id)) {
char buf[20];
snprintf(buf, sizeof(buf), "%i", OPC_CONTAINER_RELID_COUNTER(relation_array[i].relation_id));
opcContainerWriteUtf8Raw(out, _X(buf));
}
opcContainerWriteUtf8Raw(out, _X("\" Type=\""));
opcContainerWriteUtf8(out, relation_array[i].relation_type);
if (0==relation_array[i].target_mode) {
opcContainerWriteUtf8Raw(out, _X("\" Target=\""));
xmlChar rel_path[OPC_MAX_PATH];
opcHelperCalcRelPath(rel_path, sizeof(rel_path), part_name, relation_array[i].target_ptr);
opcContainerWriteUtf8(out, rel_path);
} else {
OPC_ASSERT(1==relation_array[i].target_mode);
opcContainerWriteUtf8Raw(out, _X("\" TargetMode=\"External\" Target=\""));
opcContainerWriteUtf8(out, relation_array[i].target_ptr);
}
opcContainerWriteUtf8Raw(out, _X("\"/>"));
}
opcContainerWriteUtf8Raw(out, _X("</Relationships>"));
opcContainerCloseOutputStream(out);
}
}
static void opcContainerWriteAllRels(opcContainer *c) {
if (c->relation_items>0) {
opcContainerWriteRels(c, OPC_SEGMENT_ROOTRELS, c->relation_array, c->relation_items);
}
for(opc_uint32_t i=0;i<c->part_items;i++) {
if (c->part_array[i].relation_items>0) {
opcContainerWriteRels(c, c->part_array[i].name, c->part_array[i].relation_array, c->part_array[i].relation_items);
}
}
}
opc_error_t opcContainerCommit(opcContainer *c, opc_bool_t trim) {
opc_error_t ret=OPC_ERROR_NONE;
if (OPC_OPEN_READ_ONLY!=c->mode) {
opcContainerWriteContentTypes(c);
opcContainerWriteAllRels(c);
ret=opcZipCommit(c->storage, trim);
}
return ret;
}
opc_error_t opcContainerClose(opcContainer *c, opcContainerCloseMode mode) {
opc_bool_t trim=(mode!=OPC_CLOSE_NOW);
opc_error_t ret=opcContainerCommit(c, trim);
opcZipClose(c->storage, NULL); c->storage=NULL;
opcContainerFree(c);
return ret;
}
opc_bool_t opcContainerDeletePartEx(opcContainer *container, const xmlChar *partName, opc_bool_t rels_segment) {
opc_bool_t ret=OPC_FALSE;
if (OPC_SEGMENT_CONTENTTYPES==partName) {
OPC_ASSERT(!rels_segment);
ret=opcZipSegmentDelete(container->storage, &container->content_types_segment_id, NULL, NULL);
} else if (OPC_SEGMENT_ROOTRELS==partName) {
OPC_ASSERT(rels_segment);
ret=opcZipSegmentDelete(container->storage, &container->rels_segment_id, NULL, NULL);
} else {
opcContainerPart *part=opcContainerInsertPart(container, partName, OPC_FALSE);
if (NULL!=part) {
if (rels_segment) {
ret=opcZipSegmentDelete(container->storage, &part->rel_segment_id, NULL, NULL);
} else {
ret=opcZipSegmentDelete(container->storage, &part->first_segment_id, &part->last_segment_id, NULL);
}
}
}
return ret;
}
const xmlChar *opcContentTypeFirst(opcContainer *container) {
if (container->type_items>0) {
return container->type_array[0].type;
} else {
return NULL;
}
}
const xmlChar *opcContentTypeNext(opcContainer *container, const xmlChar *type) {
opcContainerType *t=insertType(container, type, OPC_FALSE);
if (NULL!=t && t>=container->type_array && t+1<container->type_array+container->type_items) {
return (t+1)->type;
} else {
return NULL;
}
}
const xmlChar *opcExtensionFirst(opcContainer *container) {
if (container->extension_items>0) {
return container->extension_array[0].extension;
} else {
return NULL;
}
}
const xmlChar *opcExtensionNext(opcContainer *container, const xmlChar *ext) {
opcContainerExtension *e=opcContainerInsertExtension(container, ext, OPC_FALSE);
if (NULL!=e && e>=container->extension_array && e+1<container->extension_array+container->extension_items) {
return (e+1)->extension;
} else {
return NULL;
}
}
const xmlChar *opcExtensionGetType(opcContainer *container, const xmlChar *ext) {
opcContainerExtension *e=opcContainerInsertExtension(container, ext, OPC_FALSE);
if (NULL!=e && e>=container->extension_array && e<container->extension_array+container->extension_items) {
return e->type;
} else {
return NULL;
}
}
const xmlChar *opcExtensionRegister(opcContainer *container, const xmlChar *ext, const xmlChar *type) {
opcContainerType *_type=insertType(container, type, OPC_TRUE);
opcContainerExtension *_ext=opcContainerInsertExtension(container, ext, OPC_TRUE);
if (_ext!=NULL && _type!=NULL) {
OPC_ASSERT(NULL==_ext->type);
_ext->type=_type->type;
return _ext->extension;
} else {
return NULL;
}
}
opc_uint32_t opcRelationAdd(opcContainer *container, opcPart src, const xmlChar *rid, opcPart dest, const xmlChar *type) {
opc_uint32_t ret=-1;
opcContainerRelation **relation_array=NULL;
opc_uint32_t *relation_items=NULL;
if (OPC_PART_INVALID==src) {
relation_array=&container->relation_array;
relation_items=&container->relation_items;
} else {
opcContainerPart *src_part=opcContainerInsertPart(container, src, OPC_FALSE);
if (NULL!=src_part) {
relation_array=&src_part->relation_array;
relation_items=&src_part->relation_items;
}
}
opcContainerPart *dest_part=opcContainerInsertPart(container, dest, OPC_FALSE);
char buf[OPC_MAX_PATH];
strncpy(buf, (const char *)rid, OPC_MAX_PATH);
opc_uint32_t counter=-1;
opc_uint32_t id_len=splitRelPrefix(container, _X(buf), &counter);
buf[id_len]=0;
opc_uint32_t rel_id=createRelId(container, _X(buf), counter);
if (NULL!=relation_array && NULL!=dest_part) {
opcContainerRelationType *rel_type=(NULL!=type?opcContainerInsertRelationType(container, type, OPC_TRUE):NULL);
opcContainerRelation *rel=opcContainerInsertRelation(relation_array, relation_items, rel_id, (NULL!=rel_type?rel_type->type:NULL), 0, dest_part->name);
if (NULL!=rel) {
OPC_ASSERT(rel>=*relation_array && rel<*relation_array+*relation_items);
OPC_ASSERT(0==rel->target_mode);
ret=rel_id;
}
}
return ret;
}
opc_uint32_t opcRelationAddExternal(opcContainer *container, opcPart src, const xmlChar *rid, const xmlChar *target, const xmlChar *type) {
opc_uint32_t ret=-1;
opcContainerRelation **relation_array=NULL;
opc_uint32_t *relation_items=NULL;
if (OPC_PART_INVALID==src) {
relation_array=&container->relation_array;
relation_items=&container->relation_items;
} else {
opcContainerPart *src_part=opcContainerInsertPart(container, src, OPC_FALSE);
if (NULL!=src_part) {
relation_array=&src_part->relation_array;
relation_items=&src_part->relation_items;
}
}
opcContainerExternalRelation *_target=insertExternalRelation(container, target, OPC_TRUE);
char buf[OPC_MAX_PATH];
strncpy(buf, (const char *)rid, OPC_MAX_PATH);
opc_uint32_t counter=-1;
opc_uint32_t id_len=splitRelPrefix(container, _X(buf), &counter);
buf[id_len]=0;
opc_uint32_t rel_id=createRelId(container, _X(buf), counter);
if (NULL!=relation_array && NULL!=_target) {
opcContainerRelationType *rel_type=(NULL!=type?opcContainerInsertRelationType(container, type, OPC_TRUE):NULL);
opcContainerRelation *rel=opcContainerInsertRelation(relation_array, relation_items, rel_id, (NULL!=rel_type?rel_type->type:NULL), 0, _target->target);
if (NULL!=rel) {
OPC_ASSERT(rel>=*relation_array && rel<*relation_array+*relation_items);
rel->target_mode=1;
ret=rel_id;
}
}
return ret;
}
static inline int qname_level_cmp_fct(const void *key, opc_uint32_t v, const void *array_, opc_uint32_t item) {
opcQNameLevel_t *q1=(opcQNameLevel_t*)key;
opcQNameLevel_t *q2=&((opcQNameLevel_t*)array_)[item];
int const ns_cmp=(NULL==q1->ns?(NULL==q2->ns?0:-1):(NULL==q2->ns?+1:xmlStrcmp(q1->ns, q2->ns)));
return (0==ns_cmp?xmlStrcmp(q1->ln, q2->ln):ns_cmp);
}
opc_error_t opcQNameLevelAdd(opcQNameLevel_t **list_array, opc_uint32_t *list_items, opcQNameLevel_t *item) {
opc_uint32_t i=0;
opc_error_t ret=OPC_ERROR_NONE;
if (!findItem(*list_array, *list_items, item, 0, qname_level_cmp_fct, &i)) {
if (NULL!=ensureItem((void**)list_array, *list_items, sizeof(opcQNameLevel_t))) {
ensureGap(*list_array, *list_items, i);
(*list_array)[i]=*item;
} else {
ret=OPC_ERROR_MEMORY;
}
}
return ret;
}
opcQNameLevel_t* opcQNameLevelLookup(opcQNameLevel_t *list_array, opc_uint32_t list_items, const xmlChar *ns, const xmlChar *ln) {
opcQNameLevel_t item;
item.level=0;
item.ln=(xmlChar *)ln;
item.ns=ns;
opc_uint32_t i=0;
opc_bool_t ret=NULL!=list_array && list_items>0 && findItem(list_array, list_items, &item, 0, qname_level_cmp_fct, &i);
return (ret?list_array+i:NULL);
}
opc_error_t opcQNameLevelCleanup(opcQNameLevel_t *list_array, opc_uint32_t *list_items, opc_uint32_t level, opc_uint32_t *max_level) {
opc_uint32_t i=0;
for(opc_uint32_t j=0;j<*list_items;j++) {
if (list_array[j].level>=level) {
OPC_ASSERT(list_array[j].level==level); // cleanup should be called for every level...
if (NULL!=list_array[j].ln) xmlFree(list_array[j].ln);
// list_array[j].ns is managed by ther parser...
} else {
if (NULL!=max_level && list_array[j].level>*max_level) *max_level=list_array[j].level;
list_array[i++]=list_array[j];
}
}
*list_items=i;
return OPC_ERROR_NONE;
}
opc_error_t opcQNameLevelPush(opcQNameLevel_t **list_array, opc_uint32_t *list_items, opcQNameLevel_t *item) {
opc_error_t ret=OPC_ERROR_NONE;
if (NULL!=(ensureItem((void**)list_array, *list_items, sizeof(opcQNameLevel_t)))) {
(*list_array)[*list_items]=*item;
(*list_items)++;
} else {
ret=OPC_ERROR_MEMORY;
}
return ret;
}
opc_bool_t opcQNameLevelPopIfMatch(opcQNameLevel_t *list_array, opc_uint32_t *list_items, const xmlChar *ns, const xmlChar *ln, opc_uint32_t level) {
opc_bool_t ret=*list_items>0 && list_array[(*list_items)-1].level==level;
if (ret) {
OPC_ASSERT(0==xmlStrcmp(list_array[(*list_items)-1].ln, ln) && 0==xmlStrcmp(list_array[(*list_items)-1].ns, ns));
OPC_ASSERT(*list_items>0);
if (NULL!=list_array[(*list_items)-1].ln) xmlFree(list_array[(*list_items)-1].ln);
(*list_items)--;
}
return ret;
}
const xmlChar *opcRelationTypeFirst(opcContainer *container) {
if (container->relationtype_items>0) {
return container->relationtype_array[0].type;
} else {
return NULL;
}
}
const xmlChar *opcRelationTypeNext(opcContainer *container, const xmlChar *type) {
opcContainerRelationType* t=opcContainerInsertRelationType(container, type, OPC_FALSE);
if (NULL!=t && t>=container->relationtype_array && t+1<container->relationtype_array+container->relationtype_items) {
return (t+1)->type;
} else {
return NULL;
}
}
const xmlChar *opcExternalTargetFirst(opcContainer *container) {
if (container->externalrelation_items>0) {
return container->externalrelation_array[0].target;
} else {
return NULL;
}
}
const xmlChar *opcExternalTargetNext(opcContainer *container, const xmlChar *target) {
opcContainerExternalRelation*e=insertExternalRelation(container, target, OPC_FALSE);
if (NULL!=e && e>=container->externalrelation_array && e+1<container->externalrelation_array+container->externalrelation_items) {
return (e+1)->target;
} else {
return NULL;
}
}
|
360031.c | /*
drm_edid_load.c: use a built-in EDID data set or load it via the firmware
interface
Copyright (C) 2012 Carsten Emde <[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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include <linux/module.h>
#include <linux/firmware.h>
#include "drmP.h"
#include "drm_crtc.h"
#include "drm_crtc_helper.h"
#include "drm_edid.h"
static char edid_firmware[PATH_MAX];
module_param_string(edid_firmware, edid_firmware, sizeof(edid_firmware), 0644);
MODULE_PARM_DESC(edid_firmware, "Do not probe monitor, use specified EDID blob "
"from built-in data or /lib/firmware instead. ");
#define GENERIC_EDIDS 4
static char *generic_edid_name[GENERIC_EDIDS] = {
"edid/1024x768.bin",
"edid/1280x1024.bin",
"edid/1680x1050.bin",
"edid/1920x1080.bin",
};
static u8 generic_edid[GENERIC_EDIDS][128] = {
{
0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00,
0x31, 0xd8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x05, 0x16, 0x01, 0x03, 0x6d, 0x23, 0x1a, 0x78,
0xea, 0x5e, 0xc0, 0xa4, 0x59, 0x4a, 0x98, 0x25,
0x20, 0x50, 0x54, 0x00, 0x08, 0x00, 0x61, 0x40,
0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x64, 0x19,
0x00, 0x40, 0x41, 0x00, 0x26, 0x30, 0x08, 0x90,
0x36, 0x00, 0x63, 0x0a, 0x11, 0x00, 0x00, 0x18,
0x00, 0x00, 0x00, 0xff, 0x00, 0x4c, 0x69, 0x6e,
0x75, 0x78, 0x20, 0x23, 0x30, 0x0a, 0x20, 0x20,
0x20, 0x20, 0x00, 0x00, 0x00, 0xfd, 0x00, 0x3b,
0x3d, 0x2f, 0x31, 0x07, 0x00, 0x0a, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x00, 0x00, 0x00, 0xfc,
0x00, 0x4c, 0x69, 0x6e, 0x75, 0x78, 0x20, 0x58,
0x47, 0x41, 0x0a, 0x20, 0x20, 0x20, 0x00, 0x55,
},
{
0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00,
0x31, 0xd8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x05, 0x16, 0x01, 0x03, 0x6d, 0x2c, 0x23, 0x78,
0xea, 0x5e, 0xc0, 0xa4, 0x59, 0x4a, 0x98, 0x25,
0x20, 0x50, 0x54, 0x00, 0x00, 0x00, 0x81, 0x80,
0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x30, 0x2a,
0x00, 0x98, 0x51, 0x00, 0x2a, 0x40, 0x30, 0x70,
0x13, 0x00, 0xbc, 0x63, 0x11, 0x00, 0x00, 0x1e,
0x00, 0x00, 0x00, 0xff, 0x00, 0x4c, 0x69, 0x6e,
0x75, 0x78, 0x20, 0x23, 0x30, 0x0a, 0x20, 0x20,
0x20, 0x20, 0x00, 0x00, 0x00, 0xfd, 0x00, 0x3b,
0x3d, 0x3e, 0x40, 0x0b, 0x00, 0x0a, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x00, 0x00, 0x00, 0xfc,
0x00, 0x4c, 0x69, 0x6e, 0x75, 0x78, 0x20, 0x53,
0x58, 0x47, 0x41, 0x0a, 0x20, 0x20, 0x00, 0xa0,
},
{
0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00,
0x31, 0xd8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x05, 0x16, 0x01, 0x03, 0x6d, 0x2b, 0x1b, 0x78,
0xea, 0x5e, 0xc0, 0xa4, 0x59, 0x4a, 0x98, 0x25,
0x20, 0x50, 0x54, 0x00, 0x00, 0x00, 0xb3, 0x00,
0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x21, 0x39,
0x90, 0x30, 0x62, 0x1a, 0x27, 0x40, 0x68, 0xb0,
0x36, 0x00, 0xb5, 0x11, 0x11, 0x00, 0x00, 0x1e,
0x00, 0x00, 0x00, 0xff, 0x00, 0x4c, 0x69, 0x6e,
0x75, 0x78, 0x20, 0x23, 0x30, 0x0a, 0x20, 0x20,
0x20, 0x20, 0x00, 0x00, 0x00, 0xfd, 0x00, 0x3b,
0x3d, 0x40, 0x42, 0x0f, 0x00, 0x0a, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x00, 0x00, 0x00, 0xfc,
0x00, 0x4c, 0x69, 0x6e, 0x75, 0x78, 0x20, 0x57,
0x53, 0x58, 0x47, 0x41, 0x0a, 0x20, 0x00, 0x26,
},
{
0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00,
0x31, 0xd8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x05, 0x16, 0x01, 0x03, 0x6d, 0x32, 0x1c, 0x78,
0xea, 0x5e, 0xc0, 0xa4, 0x59, 0x4a, 0x98, 0x25,
0x20, 0x50, 0x54, 0x00, 0x00, 0x00, 0xd1, 0xc0,
0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x02, 0x3a,
0x80, 0x18, 0x71, 0x38, 0x2d, 0x40, 0x58, 0x2c,
0x45, 0x00, 0xf4, 0x19, 0x11, 0x00, 0x00, 0x1e,
0x00, 0x00, 0x00, 0xff, 0x00, 0x4c, 0x69, 0x6e,
0x75, 0x78, 0x20, 0x23, 0x30, 0x0a, 0x20, 0x20,
0x20, 0x20, 0x00, 0x00, 0x00, 0xfd, 0x00, 0x3b,
0x3d, 0x42, 0x44, 0x0f, 0x00, 0x0a, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x00, 0x00, 0x00, 0xfc,
0x00, 0x4c, 0x69, 0x6e, 0x75, 0x78, 0x20, 0x46,
0x48, 0x44, 0x0a, 0x20, 0x20, 0x20, 0x00, 0x05,
},
};
static int edid_load(struct drm_connector *connector, char *name,
char *connector_name)
{
const struct firmware *fw;
struct platform_device *pdev;
u8 *fwdata = NULL, *edid;
int fwsize, expected;
int builtin = 0, err = 0;
int i, valid_extensions = 0;
pdev = platform_device_register_simple(connector_name, -1, NULL, 0);
if (IS_ERR(pdev)) {
DRM_ERROR("Failed to register EDID firmware platform device "
"for connector \"%s\"\n", connector_name);
err = -EINVAL;
goto out;
}
err = request_firmware(&fw, name, &pdev->dev);
platform_device_unregister(pdev);
if (err) {
i = 0;
while (i < GENERIC_EDIDS && strcmp(name, generic_edid_name[i]))
i++;
if (i < GENERIC_EDIDS) {
err = 0;
builtin = 1;
fwdata = generic_edid[i];
fwsize = sizeof(generic_edid[i]);
}
}
if (err) {
DRM_ERROR("Requesting EDID firmware \"%s\" failed (err=%d)\n",
name, err);
goto out;
}
if (fwdata == NULL) {
fwdata = (u8 *) fw->data;
fwsize = fw->size;
}
expected = (fwdata[0x7e] + 1) * EDID_LENGTH;
if (expected != fwsize) {
DRM_ERROR("Size of EDID firmware \"%s\" is invalid "
"(expected %d, got %d)\n", name, expected, (int) fwsize);
err = -EINVAL;
goto relfw_out;
}
edid = kmalloc(fwsize, GFP_KERNEL);
if (edid == NULL) {
err = -ENOMEM;
goto relfw_out;
}
memcpy(edid, fwdata, fwsize);
if (!drm_edid_block_valid(edid)) {
DRM_ERROR("Base block of EDID firmware \"%s\" is invalid ",
name);
kfree(edid);
err = -EINVAL;
goto relfw_out;
}
for (i = 1; i <= edid[0x7e]; i++) {
if (i != valid_extensions + 1)
memcpy(edid + (valid_extensions + 1) * EDID_LENGTH,
edid + i * EDID_LENGTH, EDID_LENGTH);
if (drm_edid_block_valid(edid + i * EDID_LENGTH))
valid_extensions++;
}
if (valid_extensions != edid[0x7e]) {
edid[EDID_LENGTH-1] += edid[0x7e] - valid_extensions;
DRM_INFO("Found %d valid extensions instead of %d in EDID data "
"\"%s\" for connector \"%s\"\n", valid_extensions,
edid[0x7e], name, connector_name);
edid[0x7e] = valid_extensions;
edid = krealloc(edid, (valid_extensions + 1) * EDID_LENGTH,
GFP_KERNEL);
if (edid == NULL) {
err = -ENOMEM;
goto relfw_out;
}
}
connector->display_info.raw_edid = edid;
DRM_INFO("Got %s EDID base block and %d extension%s from "
"\"%s\" for connector \"%s\"\n", builtin ? "built-in" :
"external", valid_extensions, valid_extensions == 1 ? "" : "s",
name, connector_name);
relfw_out:
release_firmware(fw);
out:
return err;
}
int drm_load_edid_firmware(struct drm_connector *connector)
{
char *connector_name = drm_get_connector_name(connector);
char *edidname = edid_firmware, *last, *colon;
int ret = 0;
if (*edidname == '\0')
return ret;
colon = strchr(edidname, ':');
if (colon != NULL) {
if (strncmp(connector_name, edidname, colon - edidname))
return ret;
edidname = colon + 1;
if (*edidname == '\0')
return ret;
}
last = edidname + strlen(edidname) - 1;
if (*last == '\n')
*last = '\0';
ret = edid_load(connector, edidname, connector_name);
if (ret)
return 0;
drm_mode_connector_update_edid_property(connector,
(struct edid *) connector->display_info.raw_edid);
return drm_add_edid_modes(connector, (struct edid *)
connector->display_info.raw_edid);
}
|
347777.c | /*
This file is part of libcapwap.
libcapwap is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
libcapwap 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 Foobar. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* @file
* @brief
*/
#include <stdio.h>
#include <errno.h>
#include <nettle/md5.h>
#include "capwap_crypto.h"
#define BLOCK_SIZE 4096
/**
* Calculate MD5 checksum for an opened file.
* @param digest destination buffer for calculated
* checksum (16 bytes, for a predifned constant use #CW_MD5_DIGEST_SIZE)
* @param infile file hanle
*
* Remember to set the file pointer to the beginning of the file, before
* calling this function. Therefore use fseek(file,0,SEEK_SET).
*/
int cw_fgetmd5sum ( uint8_t *digest, FILE *infile )
{
struct md5_ctx ctx;
uint8_t buffer[BLOCK_SIZE];
md5_init ( &ctx );
while ( !feof ( infile ) ) {
int bytes = fread ( buffer, 1, sizeof ( buffer ), infile );
md5_update ( &ctx, bytes, buffer );
}
if ( ferror ( infile ) )
return errno;
md5_digest ( &ctx, MD5_DIGEST_SIZE, digest );
return 0;
}
|
107525.c | /*
* Copyright (c) 2005, Bull S.A.. All rights reserved.
* Created by: Sebastien Decugis
* Copyright (c) 2013 Cyril Hrubis <[email protected]>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of version 2 of the GNU General Public License as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it would be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*
* This sample test aims to check the following assertions:
*
* If SA_SIGINFO is set in sa_flags and Real Time Signals extension is supported,
* sa_sigaction is used as the signal handling function.
*
* The steps are:
* -> test for RTS extension
* -> register a handler for SIGUSR1 with SA_SIGINFO, and a known function
* as sa_sigaction
* -> raise SIGUSR1, and check the function has been called.
*
* The test fails if the function is not called
*/
#include <pthread.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <signal.h>
#include <errno.h>
#include "posixtest.h"
#define WRITE(str) write(STDOUT_FILENO, str, sizeof(str) - 1)
static volatile sig_atomic_t called = 0;
static void handler(int sig, siginfo_t *info, void *context)
{
(void) sig;
(void) context;
if (info->si_signo != SIGUSR1) {
WRITE("Wrong signal generated?\n");
_exit(PTS_FAIL);
}
called = 1;
}
int main(void)
{
int ret;
long rts;
struct sigaction sa;
/* Test the RTS extension */
rts = sysconf(_SC_REALTIME_SIGNALS);
if (rts < 0L) {
fprintf(stderr, "This test needs the RTS extension");
return PTS_UNTESTED;
}
/* Set the signal handler */
sa.sa_flags = SA_SIGINFO;
sa.sa_sigaction = handler;
ret = sigemptyset(&sa.sa_mask);
if (ret != 0) {
perror("Failed to empty signal set");
return PTS_UNRESOLVED;
}
/* Install the signal handler for SIGUSR1 */
ret = sigaction(SIGUSR1, &sa, 0);
if (ret != 0) {
perror("Failed to set signal handler");
return PTS_UNTESTED;
}
if (called) {
fprintf(stderr,
"The signal handler has been called before signal was raised");
return PTS_FAIL;
}
ret = raise(SIGUSR1);
if (ret != 0) {
perror("Failed to raise SIGUSR1");
return PTS_UNRESOLVED;
}
if (!called) {
fprintf(stderr, "The sa_handler was not called");
return PTS_FAIL;
}
printf("Test PASSED\n");
return PTS_PASS;
}
|
120263.c | /*****************************************************************************
* boards/arm/stm32/stm32butterfly2/src/stm32_usb.c
*
* Copyright (C) 2016 Michał Łyszczek. All rights reserved.
* Author: Michał Łyszczek <[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.
****************************************************************************/
/*****************************************************************************
* Include Files
****************************************************************************/
#include <debug.h>
#include "stm32_gpio.h"
#include "stm32_butterfly2.h"
/*****************************************************************************
* Public Functions
****************************************************************************/
/*****************************************************************************
* Name: stm32_usb_initialize
*
* Description:
* Initializes USB pins
****************************************************************************/
void stm32_usb_initialize(void)
{
uinfo("INFO: Initializing usb otgfs gpio pins\n");
stm32_configgpio(GPIO_OTGFS_VBUS);
stm32_configgpio(GPIO_OTGFS_PWRON);
}
|
1002672.c | /*********************************************************************/
/* Copyright 2009, 2010 The University of Texas at Austin. */
/* All rights reserved. */
/* */
/* Redistribution and use in source and binary forms, with or */
/* without modification, are permitted provided that the following */
/* conditions are met: */
/* */
/* 1. Redistributions of source code must retain the above */
/* copyright notice, this list of conditions and the following */
/* disclaimer. */
/* */
/* 2. Redistributions in binary form must reproduce the above */
/* copyright notice, this list of conditions and the following */
/* disclaimer in the documentation and/or other materials */
/* provided with the distribution. */
/* */
/* THIS SOFTWARE IS PROVIDED BY THE UNIVERSITY OF TEXAS AT */
/* AUSTIN ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, */
/* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF */
/* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE */
/* DISCLAIMED. IN NO EVENT SHALL THE UNIVERSITY OF TEXAS AT */
/* AUSTIN OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, */
/* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES */
/* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE */
/* GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR */
/* BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF */
/* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT */
/* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT */
/* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE */
/* POSSIBILITY OF SUCH DAMAGE. */
/* */
/* The views and conclusions contained in the software and */
/* documentation are those of the authors and should not be */
/* interpreted as representing official policies, either expressed */
/* or implied, of The University of Texas at Austin. */
/*********************************************************************/
#include <stdio.h>
#include <string.h>
#include "common.h"
extern int openblas_block_factor();
int get_L2_size(void);
#define DEFAULT_GEMM_P 128
#define DEFAULT_GEMM_Q 128
#define DEFAULT_GEMM_R 128
#define DEFAULT_GEMM_OFFSET_A 0
#define DEFAULT_GEMM_OFFSET_B 0
/* Global Parameter */
#if GEMM_OFFSET_A == gemm_offset_a
BLASLONG gemm_offset_a = DEFAULT_GEMM_OFFSET_A;
#else
BLASLONG gemm_offset_a = GEMM_OFFSET_A;
#endif
#if GEMM_OFFSET_B == gemm_offset_b
BLASLONG gemm_offset_b = DEFAULT_GEMM_OFFSET_B;
#else
BLASLONG gemm_offset_b = GEMM_OFFSET_B;
#endif
#if SBGEMM_P == sbgemm_p
BLASLONG sbgemm_p = DEFAULT_GEMM_P;
#else
BLASLONG sbgemm_p = SBGEMM_P;
#endif
#if SGEMM_P == sgemm_p
BLASLONG sgemm_p = DEFAULT_GEMM_P;
#else
BLASLONG sgemm_p = SGEMM_P;
#endif
#if DGEMM_P == dgemm_p
BLASLONG dgemm_p = DEFAULT_GEMM_P;
#else
BLASLONG dgemm_p = DGEMM_P;
#endif
#if CGEMM_P == cgemm_p
BLASLONG cgemm_p = DEFAULT_GEMM_P;
#else
BLASLONG cgemm_p = CGEMM_P;
#endif
#if ZGEMM_P == zgemm_p
BLASLONG zgemm_p = DEFAULT_GEMM_P;
#else
BLASLONG zgemm_p = ZGEMM_P;
#endif
#if SBGEMM_Q == sbgemm_q
BLASLONG sbgemm_q = DEFAULT_GEMM_Q;
#else
BLASLONG sbgemm_q = SBGEMM_Q;
#endif
#if SGEMM_Q == sgemm_q
BLASLONG sgemm_q = DEFAULT_GEMM_Q;
#else
BLASLONG sgemm_q = SGEMM_Q;
#endif
#if DGEMM_Q == dgemm_q
BLASLONG dgemm_q = DEFAULT_GEMM_Q;
#else
BLASLONG dgemm_q = DGEMM_Q;
#endif
#if CGEMM_Q == cgemm_q
BLASLONG cgemm_q = DEFAULT_GEMM_Q;
#else
BLASLONG cgemm_q = CGEMM_Q;
#endif
#if ZGEMM_Q == zgemm_q
BLASLONG zgemm_q = DEFAULT_GEMM_Q;
#else
BLASLONG zgemm_q = ZGEMM_Q;
#endif
#if SBGEMM_R == sbgemm_r
BLASLONG sbgemm_r = DEFAULT_GEMM_R;
#else
BLASLONG sbgemm_r = SBGEMM_R;
#endif
#if SGEMM_R == sgemm_r
BLASLONG sgemm_r = DEFAULT_GEMM_R;
#else
BLASLONG sgemm_r = SGEMM_R;
#endif
#if DGEMM_R == dgemm_r
BLASLONG dgemm_r = DEFAULT_GEMM_R;
#else
BLASLONG dgemm_r = DGEMM_R;
#endif
#if CGEMM_R == cgemm_r
BLASLONG cgemm_r = DEFAULT_GEMM_R;
#else
BLASLONG cgemm_r = CGEMM_R;
#endif
#if ZGEMM_R == zgemm_r
BLASLONG zgemm_r = DEFAULT_GEMM_R;
#else
BLASLONG zgemm_r = ZGEMM_R;
#endif
#if defined(EXPRECISION) || defined(QUAD_PRECISION)
#if QGEMM_P == qgemm_p
BLASLONG qgemm_p = DEFAULT_GEMM_P;
#else
BLASLONG qgemm_p = QGEMM_P;
#endif
#if XGEMM_P == xgemm_p
BLASLONG xgemm_p = DEFAULT_GEMM_P;
#else
BLASLONG xgemm_p = XGEMM_P;
#endif
#if QGEMM_Q == qgemm_q
BLASLONG qgemm_q = DEFAULT_GEMM_Q;
#else
BLASLONG qgemm_q = QGEMM_Q;
#endif
#if XGEMM_Q == xgemm_q
BLASLONG xgemm_q = DEFAULT_GEMM_Q;
#else
BLASLONG xgemm_q = XGEMM_Q;
#endif
#if QGEMM_R == qgemm_r
BLASLONG qgemm_r = DEFAULT_GEMM_R;
#else
BLASLONG qgemm_r = QGEMM_R;
#endif
#if XGEMM_R == xgemm_r
BLASLONG xgemm_r = DEFAULT_GEMM_R;
#else
BLASLONG xgemm_r = XGEMM_R;
#endif
#endif
#if defined(ARCH_X86) || defined(ARCH_X86_64)
int get_L2_size(void){
int eax, ebx, ecx, edx;
#if defined(ATHLON) || defined(OPTERON) || defined(BARCELONA) || defined(BOBCAT) || defined(BULLDOZER) || \
defined(CORE_PRESCOTT) || defined(CORE_CORE2) || defined(PENRYN) || defined(DUNNINGTON) || \
defined(CORE_NEHALEM) || defined(CORE_SANDYBRIDGE) || defined(ATOM) || defined(GENERIC) || \
defined(PILEDRIVER) || defined(HASWELL) || defined(STEAMROLLER) || defined(EXCAVATOR) || \
defined(ZEN) || defined(SKYLAKEX) || defined(COOPERLAKE)
cpuid(0x80000006, &eax, &ebx, &ecx, &edx);
return BITMASK(ecx, 16, 0xffff);
#else
int info[15];
int i;
cpuid(2, &eax, &ebx, &ecx, &edx);
info[ 0] = BITMASK(eax, 8, 0xff);
info[ 1] = BITMASK(eax, 16, 0xff);
info[ 2] = BITMASK(eax, 24, 0xff);
info[ 3] = BITMASK(ebx, 0, 0xff);
info[ 4] = BITMASK(ebx, 8, 0xff);
info[ 5] = BITMASK(ebx, 16, 0xff);
info[ 6] = BITMASK(ebx, 24, 0xff);
info[ 7] = BITMASK(ecx, 0, 0xff);
info[ 8] = BITMASK(ecx, 8, 0xff);
info[ 9] = BITMASK(ecx, 16, 0xff);
info[10] = BITMASK(ecx, 24, 0xff);
info[11] = BITMASK(edx, 0, 0xff);
info[12] = BITMASK(edx, 8, 0xff);
info[13] = BITMASK(edx, 16, 0xff);
info[14] = BITMASK(edx, 24, 0xff);
for (i = 0; i < 15; i++){
switch (info[i]){
case 0x3b :
case 0x41 :
case 0x79 :
return 128;
break;
case 0x3c :
case 0x42 :
case 0x7a :
case 0x7e :
case 0x82 :
return 256;
break;
case 0x43 :
case 0x7b :
case 0x7f :
case 0x83 :
case 0x86 :
return 512;
break;
case 0x44 :
case 0x78 :
case 0x7c :
case 0x84 :
case 0x87 :
return 1024;
break;
case 0x45 :
case 0x7d :
case 0x85 :
return 2048;
case 0x49 :
return 4096;
break;
}
}
/* Never reached */
return 0;
#endif
}
void blas_set_parameter(void){
int factor;
#if defined(BULLDOZER) || defined(PILEDRIVER) || defined(SANDYBRIDGE) || defined(NEHALEM) || \
defined(HASWELL) || defined(STEAMROLLER) || defined(EXCAVATOR) || defined(ZEN) || \
defined(SKYLAKEX) || defined(COOPERLAKE)
int size = 16;
#else
int size = get_L2_size();
#endif
#if defined(CORE_KATMAI) || defined(CORE_COPPERMINE) || defined(CORE_BANIAS)
size >>= 7;
#if defined(CORE_BANIAS) && (HAVE_HIT > 1)
sgemm_p = 64 / HAVE_HIT * size;
dgemm_p = 32 / HAVE_HIT * size;
cgemm_p = 32 / HAVE_HIT * size;
zgemm_p = 16 / HAVE_HIT * size;
#ifdef EXPRECISION
qgemm_p = 16 / HAVE_HIT * size;
xgemm_p = 8 / HAVE_HIT * size;
#endif
#ifdef QUAD_PRECISION
qgemm_p = 8 / HAVE_HIT * size;
xgemm_p = 4 / HAVE_HIT * size;
#endif
#else
sgemm_p = 64 * size;
dgemm_p = 32 * size;
cgemm_p = 32 * size;
zgemm_p = 16 * size;
#ifdef EXPRECISION
qgemm_p = 16 * size;
xgemm_p = 8 * size;
#endif
#ifdef QUAD_PRECISION
qgemm_p = 8 * size;
xgemm_p = 4 * size;
#endif
#endif
#endif
#if defined(CORE_NORTHWOOD)
size >>= 7;
#ifdef ALLOC_HUGETLB
sgemm_p = 128 * size;
dgemm_p = 64 * size;
cgemm_p = 64 * size;
zgemm_p = 32 * size;
#ifdef EXPRECISION
qgemm_p = 32 * size;
xgemm_p = 16 * size;
#endif
#ifdef QUAD_PRECISION
qgemm_p = 16 * size;
xgemm_p = 8 * size;
#endif
#else
sgemm_p = 96 * size;
dgemm_p = 48 * size;
cgemm_p = 48 * size;
zgemm_p = 24 * size;
#ifdef EXPRECISION
qgemm_p = 24 * size;
xgemm_p = 12 * size;
#endif
#ifdef QUAD_PRECISION
qgemm_p = 12 * size;
xgemm_p = 6 * size;
#endif
#endif
#endif
#if defined(CORE_CORE2)
size >>= 9;
sgemm_p = 92 * size;
dgemm_p = 46 * size;
cgemm_p = 46 * size;
zgemm_p = 23 * size;
#ifdef EXPRECISION
qgemm_p = 23 * size;
xgemm_p = 11 * size;
#endif
#ifdef QUAD_PRECISION
qgemm_p = 11 * size;
xgemm_p = 5 * size;
#endif
#endif
#if defined(PENRYN)
size >>= 9;
sgemm_p = 1024;
dgemm_p = 512;
cgemm_p = 512;
zgemm_p = 256;
#ifdef EXPRECISION
qgemm_p = 256;
xgemm_p = 128;
#endif
#ifdef QUAD_PRECISION
qgemm_p = 21 * size + 4;
xgemm_p = 10 * size + 2;
#endif
#endif
#if defined(DUNNINGTON)
size >>= 9;
sgemm_p = 384;
dgemm_p = 384;
cgemm_p = 384;
zgemm_p = 384;
#ifdef EXPRECISION
qgemm_p = 384;
xgemm_p = 384;
#endif
#ifdef QUAD_PRECISION
qgemm_p = 21 * size + 4;
xgemm_p = 10 * size + 2;
#endif
#endif
#if defined(NEHALEM)
sgemm_p = 1024;
dgemm_p = 512;
cgemm_p = 512;
zgemm_p = 256;
#ifdef EXPRECISION
qgemm_p = 256;
xgemm_p = 128;
#endif
#endif
#if defined(SANDYBRIDGE)
sgemm_p = 1024;
dgemm_p = 512;
cgemm_p = 512;
zgemm_p = 256;
#ifdef EXPRECISION
qgemm_p = 256;
xgemm_p = 128;
#endif
#endif
#if defined(CORE_PRESCOTT) || defined(GENERIC)
size >>= 6;
if (size > 16) size = 16;
sgemm_p = 56 * size;
dgemm_p = 28 * size;
cgemm_p = 28 * size;
zgemm_p = 14 * size;
#ifdef EXPRECISION
qgemm_p = 14 * size;
xgemm_p = 7 * size;
#endif
#ifdef QUAD_PRECISION
qgemm_p = 7 * size;
xgemm_p = 3 * size;
#endif
#endif
#if defined(CORE_OPTERON)
sgemm_p = 224 + 14 * (size >> 5);
dgemm_p = 112 + 14 * (size >> 6);
cgemm_p = 116 + 14 * (size >> 6);
zgemm_p = 58 + 14 * (size >> 7);
#ifdef EXPRECISION
qgemm_p = 58 + 14 * (size >> 7);
xgemm_p = 29 + 14 * (size >> 8);
#endif
#ifdef QUAD_PRECISION
qgemm_p = 29 + 14 * (size >> 8);
xgemm_p = 15 + 14 * (size >> 9);
#endif
#endif
#if defined(ATOM)
size >>= 8;
sgemm_p = 256;
dgemm_p = 128;
cgemm_p = 128;
zgemm_p = 64;
#ifdef EXPRECISION
qgemm_p = 64;
xgemm_p = 32;
#endif
#ifdef QUAD_PRECISION
qgemm_p = 32;
xgemm_p = 16;
#endif
#endif
#if defined(CORE_BARCELONA) || defined(CORE_BOBCAT)
size >>= 8;
sgemm_p = 232 * size;
dgemm_p = 116 * size;
cgemm_p = 116 * size;
zgemm_p = 58 * size;
#ifdef EXPRECISION
qgemm_p = 58 * size;
xgemm_p = 26 * size;
#endif
#ifdef QUAD_PRECISION
qgemm_p = 26 * size;
xgemm_p = 13 * size;
#endif
#endif
factor=openblas_block_factor();
if (factor>0) {
if (factor < 10) factor = 10;
if (factor > 200) factor = 200;
sgemm_p = ((long)((double)sgemm_p * (double)factor * 1.e-2)) & ~7L;
dgemm_p = ((long)((double)dgemm_p * (double)factor * 1.e-2)) & ~7L;
cgemm_p = ((long)((double)cgemm_p * (double)factor * 1.e-2)) & ~7L;
zgemm_p = ((long)((double)zgemm_p * (double)factor * 1.e-2)) & ~7L;
#ifdef EXPRECISION
qgemm_p = ((long)((double)qgemm_p * (double)factor * 1.e-2)) & ~7L;
xgemm_p = ((long)((double)xgemm_p * (double)factor * 1.e-2)) & ~7L;
#endif
}
if (sgemm_p == 0) sgemm_p = 64;
if (dgemm_p == 0) dgemm_p = 64;
if (cgemm_p == 0) cgemm_p = 64;
if (zgemm_p == 0) zgemm_p = 64;
#ifdef EXPRECISION
if (qgemm_p == 0) qgemm_p = 64;
if (xgemm_p == 0) xgemm_p = 64;
#endif
#ifdef QUAD_PRECISION
if (qgemm_p == 0) qgemm_p = 64;
if (xgemm_p == 0) xgemm_p = 64;
#endif
sgemm_p = ((sgemm_p + SGEMM_UNROLL_M - 1)/SGEMM_UNROLL_M) * SGEMM_UNROLL_M;
dgemm_p = ((dgemm_p + DGEMM_UNROLL_M - 1)/DGEMM_UNROLL_M) * DGEMM_UNROLL_M;
cgemm_p = ((cgemm_p + CGEMM_UNROLL_M - 1)/CGEMM_UNROLL_M) * CGEMM_UNROLL_M;
zgemm_p = ((zgemm_p + ZGEMM_UNROLL_M - 1)/ZGEMM_UNROLL_M) * ZGEMM_UNROLL_M;
#ifdef QUAD_PRECISION
qgemm_p = ((qgemm_p + QGEMM_UNROLL_M - 1)/QGEMM_UNROLL_M) * QGEMM_UNROLL_M;
xgemm_p = ((xgemm_p + XGEMM_UNROLL_M - 1)/XGEMM_UNROLL_M) * XGEMM_UNROLL_M;
#endif
sgemm_r = (((BUFFER_SIZE - ((SGEMM_P * SGEMM_Q * 4 + GEMM_OFFSET_A + GEMM_ALIGN) & ~GEMM_ALIGN)) / (SGEMM_Q * 4)) - 15) & ~15;
dgemm_r = (((BUFFER_SIZE - ((DGEMM_P * DGEMM_Q * 8 + GEMM_OFFSET_A + GEMM_ALIGN) & ~GEMM_ALIGN)) / (DGEMM_Q * 8)) - 15) & ~15;
cgemm_r = (((BUFFER_SIZE - ((CGEMM_P * CGEMM_Q * 8 + GEMM_OFFSET_A + GEMM_ALIGN) & ~GEMM_ALIGN)) / (CGEMM_Q * 8)) - 15) & ~15;
zgemm_r = (((BUFFER_SIZE - ((ZGEMM_P * ZGEMM_Q * 16 + GEMM_OFFSET_A + GEMM_ALIGN) & ~GEMM_ALIGN)) / (ZGEMM_Q * 16)) - 15) & ~15;
#if defined(EXPRECISION) || defined(QUAD_PRECISION)
qgemm_r = (((BUFFER_SIZE - ((QGEMM_P * QGEMM_Q * 16 + GEMM_OFFSET_A + GEMM_ALIGN) & ~GEMM_ALIGN)) / (QGEMM_Q * 16)) - 15) & ~15;
xgemm_r = (((BUFFER_SIZE - ((XGEMM_P * XGEMM_Q * 32 + GEMM_OFFSET_A + GEMM_ALIGN) & ~GEMM_ALIGN)) / (XGEMM_Q * 32)) - 15) & ~15;
#endif
#if 0
fprintf(stderr, "SGEMM ... %3d, %3d, %3d\n", SGEMM_P, SGEMM_Q, SGEMM_R);
fprintf(stderr, "DGEMM ... %3d, %3d, %3d\n", DGEMM_P, DGEMM_Q, DGEMM_R);
fprintf(stderr, "CGEMM ... %3d, %3d, %3d\n", CGEMM_P, CGEMM_Q, CGEMM_R);
fprintf(stderr, "ZGEMM ... %3d, %3d, %3d\n", ZGEMM_P, ZGEMM_Q, ZGEMM_R);
#endif
return;
}
#if 0
int get_current_cpu_info(void){
int nlprocs, ncores, cmplegacy;
int htt = 0;
int apicid = 0;
#if defined(CORE_PRESCOTT) || defined(CORE_OPTERON)
int eax, ebx, ecx, edx;
cpuid(1, &eax, &ebx, &ecx, &edx);
nlprocs = BITMASK(ebx, 16, 0xff);
apicid = BITMASK(ebx, 24, 0xff);
htt = BITMASK(edx, 28, 0x01);
#endif
#if defined(CORE_PRESCOTT)
cpuid(4, &eax, &ebx, &ecx, &edx);
ncores = BITMASK(eax, 26, 0x3f);
if (htt == 0) nlprocs = 0;
#endif
#if defined(CORE_OPTERON)
cpuid(0x80000008, &eax, &ebx, &ecx, &edx);
ncores = BITMASK(ecx, 0, 0xff);
cpuid(0x80000001, &eax, &ebx, &ecx, &edx);
cmplegacy = BITMASK(ecx, 1, 0x01);
if (htt == 0) {
nlprocs = 0;
ncores = 0;
cmplegacy = 0;
}
#endif
ncores ++;
fprintf(stderr, "APICID = %d Number of core = %d\n", apicid, ncores);
return 0;
}
#endif
#endif
#if defined(ARCH_IA64)
static inline BLASULONG cpuid(BLASULONG regnum){
BLASULONG value;
#ifndef __ECC
asm ("mov %0=cpuid[%r1]" : "=r"(value) : "rO"(regnum));
#else
value = __getIndReg(_IA64_REG_INDR_CPUID, regnum);
#endif
return value;
}
#if 1
void blas_set_parameter(void){
BLASULONG cpuid3, size;
cpuid3 = cpuid(3);
size = BITMASK(cpuid3, 16, 0xff);
sbgemm_p = 192 * (size + 1);
sgemm_p = 192 * (size + 1);
dgemm_p = 96 * (size + 1);
cgemm_p = 96 * (size + 1);
zgemm_p = 48 * (size + 1);
#ifdef EXPRECISION
qgemm_p = 64 * (size + 1);
xgemm_p = 32 * (size + 1);
#endif
#ifdef QUAD_PRECISION
qgemm_p = 32 * (size + 1);
xgemm_p = 16 * (size + 1);
#endif
sbgemm_r = (((BUFFER_SIZE - ((SBGEMM_P * SBGEMM_Q * 4 + GEMM_OFFSET_A + GEMM_ALIGN) & ~GEMM_ALIGN)) / (SBGEMM_Q * 4)) - 15) & ~15;
sgemm_r = (((BUFFER_SIZE - ((SGEMM_P * SGEMM_Q * 4 + GEMM_OFFSET_A + GEMM_ALIGN) & ~GEMM_ALIGN)) / (SGEMM_Q * 4)) - 15) & ~15;
dgemm_r = (((BUFFER_SIZE - ((DGEMM_P * DGEMM_Q * 8 + GEMM_OFFSET_A + GEMM_ALIGN) & ~GEMM_ALIGN)) / (DGEMM_Q * 8)) - 15) & ~15;
cgemm_r = (((BUFFER_SIZE - ((CGEMM_P * CGEMM_Q * 8 + GEMM_OFFSET_A + GEMM_ALIGN) & ~GEMM_ALIGN)) / (CGEMM_Q * 8)) - 15) & ~15;
zgemm_r = (((BUFFER_SIZE - ((ZGEMM_P * ZGEMM_Q * 16 + GEMM_OFFSET_A + GEMM_ALIGN) & ~GEMM_ALIGN)) / (ZGEMM_Q * 16)) - 15) & ~15;
#if defined(EXPRECISION) || defined(QUAD_PRECISION)
qgemm_r = (((BUFFER_SIZE - ((QGEMM_P * QGEMM_Q * 16 + GEMM_OFFSET_A + GEMM_ALIGN) & ~GEMM_ALIGN)) / (QGEMM_Q * 16)) - 15) & ~15;
xgemm_r = (((BUFFER_SIZE - ((XGEMM_P * XGEMM_Q * 32 + GEMM_OFFSET_A + GEMM_ALIGN) & ~GEMM_ALIGN)) / (XGEMM_Q * 32)) - 15) & ~15;
#endif
return;
}
#else
#define IA64_SYS_NAME "/sys/devices/system/cpu/cpu0/cache/index3/size"
#define IA64_PROC_NAME "/proc/pal/cpu0/cache_info"
void blas_set_parameter(void){
BLASULONG cpuid3;
int size = 0;
#if 1
char buffer[128];
FILE *infile;
if ((infile = fopen(IA64_SYS_NAME, "r")) != NULL) {
fgets(buffer, sizeof(buffer), infile);
fclose(infile);
size = atoi(buffer) / 1536;
}
if (size <= 0) {
if ((infile = fopen(IA64_PROC_NAME, "r")) != NULL) {
while(fgets(buffer, sizeof(buffer), infile) != NULL) {
if ((!strncmp("Data/Instruction Cache level 3", buffer, 30))) break;
}
fgets(buffer, sizeof(buffer), infile);
fclose(infile);
*strstr(buffer, "bytes") = (char)NULL;
size = atoi(strchr(buffer, ':') + 1) / 1572864;
}
}
#endif
/* The last resort */
if (size <= 0) {
cpuid3 = cpuid(3);
size = BITMASK(cpuid3, 16, 0xff) + 1;
}
sgemm_p = 320 * size;
dgemm_p = 160 * size;
cgemm_p = 160 * size;
zgemm_p = 80 * size;
#ifdef EXPRECISION
qgemm_p = 80 * size;
xgemm_p = 40 * size;
#endif
sgemm_r = (((BUFFER_SIZE - ((SGEMM_P * SGEMM_Q * 4 + GEMM_OFFSET_A + GEMM_ALIGN) & ~GEMM_ALIGN)) / (SGEMM_Q * 4)) - 15) & ~15;
dgemm_r = (((BUFFER_SIZE - ((DGEMM_P * DGEMM_Q * 8 + GEMM_OFFSET_A + GEMM_ALIGN) & ~GEMM_ALIGN)) / (DGEMM_Q * 8)) - 15) & ~15;
cgemm_r = (((BUFFER_SIZE - ((CGEMM_P * CGEMM_Q * 8 + GEMM_OFFSET_A + GEMM_ALIGN) & ~GEMM_ALIGN)) / (CGEMM_Q * 8)) - 15) & ~15;
zgemm_r = (((BUFFER_SIZE - ((ZGEMM_P * ZGEMM_Q * 16 + GEMM_OFFSET_A + GEMM_ALIGN) & ~GEMM_ALIGN)) / (ZGEMM_Q * 16)) - 15) & ~15;
#ifdef EXPRECISION
qgemm_r = (((BUFFER_SIZE - ((QGEMM_P * QGEMM_Q * 16 + GEMM_OFFSET_A + GEMM_ALIGN) & ~GEMM_ALIGN)) / (QGEMM_Q * 16)) - 15) & ~15;
xgemm_r = (((BUFFER_SIZE - ((XGEMM_P * XGEMM_Q * 32 + GEMM_OFFSET_A + GEMM_ALIGN) & ~GEMM_ALIGN)) / (XGEMM_Q * 32)) - 15) & ~15;
#endif
return;
}
#endif
#endif
#if defined(ARCH_MIPS64)
void blas_set_parameter(void){
#if defined(LOONGSON3A)
#ifdef SMP
if(blas_num_threads == 1){
#endif
//single thread
dgemm_r = 1024;
#ifdef SMP
}else{
//multi thread
dgemm_r = 200;
}
#endif
#endif
#if defined(LOONGSON3B)
#ifdef SMP
if(blas_num_threads == 1 || blas_num_threads == 2){
#endif
//single thread
dgemm_r = 640;
#ifdef SMP
}else{
//multi thread
dgemm_r = 160;
}
#endif
#endif
}
#endif
#if defined(ARCH_ARM64)
void blas_set_parameter(void)
{
}
#endif
|
776955.c | #include "broadcasters.h"
#include "ble_utils.h"
#include <esp_log.h>
#include <esp_gap_ble_api.h>
#include <math.h>
#include <stdlib.h>
#include <string.h>
#include <endian.h>
/* Constants */
static const char *TAG = "Broadcaster";
/* Utilities */
static char *hex2a(char *s, uint8_t *buf, size_t len)
{
int i;
char *p;
for (i = 0, p = s; i < len; i++)
p += sprintf(p, "%02x", buf[i]);
return s;
}
/* UUID's in big-endian (compared to uuidtoa()) */
static char *_uuidtoa(ble_uuid_t uuid)
{
static char s[37];
sprintf(s,
"%02x%02x%02x%02x-%02x%02x-%02x%02x-%02x%02x-%02x%02x%02x%02x%02x%02x",
uuid[0], uuid[1], uuid[2], uuid[3],
uuid[4], uuid[5],
uuid[6], uuid[7],
uuid[8], uuid[9],
uuid[10], uuid[11], uuid[12], uuid[13], uuid[14], uuid[15]);
return s;
}
/* MAC addresses in little-endian (compared to mactoa()) */
char *_mactoa(mac_addr_t mac)
{
static char s[18];
sprintf(s, "%02x:%02x:%02x:%02x:%02x:%02x", mac[5], mac[3], mac[4], mac[2],
mac[1], mac[0]);
return s;
}
/* iBeacon */
typedef struct {
uint16_t company_id;
uint16_t beacon_type;
uint8_t proximity_uuid[16];
uint16_t major;
uint16_t minor;
int8_t measured_power;
} __attribute__((packed)) ibeacon_t;
static ibeacon_t *ibeacon_data_get(uint8_t *adv_data, uint8_t adv_data_len,
uint8_t *ibeacon_len)
{
uint8_t len;
uint8_t *data = esp_ble_resolve_adv_data(adv_data,
ESP_BLE_AD_MANUFACTURER_SPECIFIC_TYPE, &len);
if (ibeacon_len)
*ibeacon_len = len;
return (ibeacon_t *)data;
}
static int ibeacon_is_broadcaster(uint8_t *adv_data, size_t adv_data_len)
{
uint8_t len;
ibeacon_t *beacon = ibeacon_data_get(adv_data, adv_data_len, &len);
if (!beacon || len < sizeof(ibeacon_t))
return 0;
/* Technically, we should also check the device is BLE only and
* non-connectable, but most iBeacon simulators don't advertise as such */
return le16toh(beacon->company_id) == 0x004C /* Apple */ &&
le16toh(beacon->beacon_type) == 0x1502;
}
static void ibeacon_metadata_get(uint8_t *adv_data, size_t adv_data_len,
int rssi, broadcaster_meta_data_cb_t cb, void *ctx)
{
char s[6];
ibeacon_t *beacon = ibeacon_data_get(adv_data, adv_data_len, NULL);
cb("UUID", _uuidtoa(beacon->proximity_uuid), ctx);
sprintf(s, "%u", be16toh(beacon->major));
cb("Major", s, ctx);
sprintf(s, "%u", be16toh(beacon->minor));
cb("Minor", s, ctx);
sprintf(s, "%.2f", pow(10, (beacon->measured_power - rssi) / 20.0));
cb("Distance", s, ctx);
}
static broadcaster_ops_t ibeacon_ops = {
.name = "iBeacon",
.is_broadcaster = ibeacon_is_broadcaster,
.metadata_get = ibeacon_metadata_get,
};
/* Eddystone */
#define EDDYSTONE_SERVICE_UUID 0xFEAA
#define EDDYSTONE_FRAME_TYPE_UID 0x00
#define EDDYSTONE_FRAME_TYPE_URL 0x10
#define EDDYSTONE_FRAME_TYPE_TLM 0x20
typedef struct {
int8_t ranging_data; /* Calibrated Tx power at 0 m */
uint8_t nid[10]; /* Namespace */
uint8_t bid[6]; /* Instance */
uint8_t rfu[2]; /* Reserved for future use */
} __attribute__((packed)) eddystone_uid_t;
typedef struct {
int8_t tx_power; /* Calibrated Tx power at 0 m */
uint8_t url_scheme; /* Encoded Scheme Prefix */
uint8_t url[0]; /* Length 1-17 */
} __attribute__((packed)) eddystone_url_t;
typedef struct {
int8_t version;
uint16_t vbatt; /* Battery voltage, 1mV/bit */
uint16_t temp; /* Beacon temperature */
uint32_t adv_cnt; /* Advertising PDU count */
uint32_t sec_cnt; /* Time since power-on or reboot */
} __attribute__((packed)) eddystone_tlm_t;
typedef struct {
uint16_t service_uuid;
uint8_t frame_type;
union {
eddystone_uid_t uid;
eddystone_url_t url;
eddystone_tlm_t tlm;
} u;
} eddystone_t;
static eddystone_t *eddystone_data_get(uint8_t *adv_data, uint8_t adv_data_len,
uint8_t *eddystone_len)
{
uint8_t len;
uint8_t *data = esp_ble_resolve_adv_data(adv_data,
ESP_BLE_AD_TYPE_SERVICE_DATA, &len);
if (eddystone_len)
*eddystone_len = len;
return (eddystone_t *)data;
}
static int eddystone_is_broadcaster(uint8_t *adv_data, size_t adv_data_len)
{
uint8_t len;
uint8_t *data = esp_ble_resolve_adv_data(adv_data,
ESP_BLE_AD_TYPE_16SRV_CMPL, &len);
eddystone_t *eddystone;
if (!data || len != 2 ||
le16toh(*(uint16_t *)data) != EDDYSTONE_SERVICE_UUID)
{
return 0;
}
eddystone = eddystone_data_get(adv_data, adv_data_len, &len);
/* Make sure we have enough bytes to read UUID and type */
if (!eddystone || len < offsetof(eddystone_t, u) ||
le16toh(eddystone->service_uuid) != EDDYSTONE_SERVICE_UUID)
{
return 0;
}
/* Validate length */
if (eddystone->frame_type == EDDYSTONE_FRAME_TYPE_UID)
{
if (len - offsetof(eddystone_t, u) != sizeof(eddystone_uid_t) &&
/* RFU is not always available */
len - offsetof(eddystone_t, u) != offsetof(eddystone_uid_t, rfu))
{
return 0;
}
}
else if (eddystone->frame_type == EDDYSTONE_FRAME_TYPE_URL)
{
if (len - offsetof(eddystone_t, u) < sizeof(eddystone_url_t))
return 0;
}
else if (eddystone->frame_type == EDDYSTONE_FRAME_TYPE_TLM)
{
if (len - offsetof(eddystone_t, u) != sizeof(eddystone_tlm_t))
return 0;
}
else
return 0; /* Unsupported frame type */
return 1;
}
static char *eddystone_url_scheme_get(uint8_t url_scheme)
{
if (url_scheme == 0) return "http://www.";
if (url_scheme == 1) return "https://www.";
if (url_scheme == 2) return "http://";
if (url_scheme == 3) return "https://";
ESP_LOGE(TAG, "Unsupported URL scheme: %d", url_scheme);
return "";
}
static char *eddystone_url_get(char url)
{
static char c;
c = url;
if (c == 0) return ".com/";
if (c == 1) return ".org/";
if (c == 2) return ".edu/";
if (c == 3) return ".net/";
if (c == 4) return ".info/";
if (c == 5) return ".biz/";
if (c == 6) return ".gov/";
if (c == 7) return ".com";
if (c == 8) return ".org";
if (c == 9) return ".edu";
if (c == 10) return ".net";
if (c == 11) return ".info";
if (c == 12) return ".biz";
if (c == 13) return ".gov";
if (c > 32 && c < 127)
return &c;
ESP_LOGE(TAG, "Unsupported URL character: 0x%0x", url);
return "";
}
static void eddystone_metadata_get(uint8_t *adv_data, size_t adv_data_len,
int rssi, broadcaster_meta_data_cb_t cb, void *ctx)
{
char s[30];
uint8_t len;
eddystone_t *eddystone = eddystone_data_get(adv_data, adv_data_len, &len);
if (eddystone->frame_type == EDDYSTONE_FRAME_TYPE_UID)
{
/* Note: 41dBm is the signal loss that occurs over 1 meter */
sprintf(s, "%.2f",
pow(10, (eddystone->u.uid.ranging_data - rssi - 41) / 20.0));
cb("Distance", s, ctx);
cb("Namespace", hex2a(s, eddystone->u.uid.nid, 10), ctx);
cb("Instance", hex2a(s, eddystone->u.uid.bid, 6), ctx);
}
else if (eddystone->frame_type == EDDYSTONE_FRAME_TYPE_URL)
{
char *p = s;
int i;
/* Note: 41dBm is the signal loss that occurs over 1 meter */
sprintf(s, "%.2f",
pow(10, (eddystone->u.url.tx_power - rssi - 41) / 20.0));
cb("Distance", s, ctx);
p += sprintf(p, "%s",
eddystone_url_scheme_get(eddystone->u.url.url_scheme));
/* Calculate remaining size of URL */
len -= offsetof(eddystone_t, u) + offsetof(eddystone_url_t, url);
for (i = 0; len > 0; len--, i++)
p += sprintf(p, "%s", eddystone_url_get(eddystone->u.url.url[i]));
cb("URL", s, ctx);
}
else if (eddystone->frame_type == EDDYSTONE_FRAME_TYPE_TLM)
{
if (eddystone->u.tlm.version == 0)
{
sprintf(s, "%d", be16toh(eddystone->u.tlm.vbatt));
cb("Voltage", s, ctx);
sprintf(s, "%.2f", be16toh(eddystone->u.tlm.temp) / 256.0);
cb("Temperature", s, ctx);
sprintf(s, "%u", be32toh(eddystone->u.tlm.adv_cnt));
cb("Count", s, ctx);
sprintf(s, "%u", be32toh(eddystone->u.tlm.sec_cnt));
cb("Uptime", s, ctx);
}
else
{
ESP_LOGE(TAG, "Unsupported TLM verison %d",
eddystone->u.tlm.version);
}
}
}
static broadcaster_ops_t eddystone_ops = {
.name = "Eddystone",
.is_broadcaster = eddystone_is_broadcaster,
.metadata_get = eddystone_metadata_get,
};
/* Mijia Temperature and Humidity Sensor */
#define MIJIA_TEMP_HUM_SERVICE_UUID 0xFE95
#define MIJIA_TEMP_HUM_DATA_TYPE_TEMP 0x04
#define MIJIA_TEMP_HUM_DATA_TYPE_HUM 0x06
#define MIJIA_TEMP_HUM_DATA_TYPE_BATT 0x0A
#define MIJIA_TEMP_HUM_DATA_TYPE_TEMP_HUM 0x0D
typedef struct {
uint16_t service_uuid;
uint8_t tbd1[4];
uint8_t message_counter;
mac_addr_t mac;
uint8_t data_type;
uint8_t tbd2;
uint8_t data_len;
uint8_t data[0];
} __attribute__((packed)) mijia_temp_hum_t;
static mijia_temp_hum_t *mijia_temp_hum_data_get(uint8_t *adv_data,
uint8_t adv_data_len, uint8_t *mijia_temp_hum_len)
{
uint8_t len;
uint8_t *data = esp_ble_resolve_adv_data(adv_data,
ESP_BLE_AD_TYPE_SERVICE_DATA, &len);
if (mijia_temp_hum_len)
*mijia_temp_hum_len = len;
return (mijia_temp_hum_t *)data;
}
static int mijia_temp_hum_is_broadcaster(uint8_t *adv_data, size_t adv_data_len)
{
uint8_t len;
mijia_temp_hum_t *mijia_temp_hum = mijia_temp_hum_data_get(adv_data,
adv_data_len, &len);
if (!mijia_temp_hum || len < offsetof(mijia_temp_hum_t, data) ||
le16toh(mijia_temp_hum->service_uuid) != MIJIA_TEMP_HUM_SERVICE_UUID)
{
return 0;
}
return 1;
}
static void mijia_temp_hum_metadata_get(uint8_t *adv_data, size_t adv_data_len,
int rssi, broadcaster_meta_data_cb_t cb, void *ctx)
{
char s[7];
uint8_t len;
mijia_temp_hum_t *mijia_temp_hum = mijia_temp_hum_data_get(adv_data,
adv_data_len, &len);
cb("MACAddress", _mactoa(mijia_temp_hum->mac), ctx);
sprintf(s, "%hhu", mijia_temp_hum->message_counter);
cb("MessageCounter", s, ctx);
if (mijia_temp_hum->data_type == MIJIA_TEMP_HUM_DATA_TYPE_TEMP)
{
sprintf(s, "%.1f",
(int16_t)le16toh(*(uint16_t *)mijia_temp_hum->data) / 10.0);
cb("Temperature", s, ctx);
}
else if (mijia_temp_hum->data_type == MIJIA_TEMP_HUM_DATA_TYPE_HUM)
{
sprintf(s, "%.1f", le16toh(*(uint16_t *)mijia_temp_hum->data) / 10.0);
cb("Humidity", s, ctx);
}
else if (mijia_temp_hum->data_type == MIJIA_TEMP_HUM_DATA_TYPE_BATT)
{
sprintf(s, "%u", *mijia_temp_hum->data);
cb("BatteryLevel", s, ctx);
}
else if (mijia_temp_hum->data_type == MIJIA_TEMP_HUM_DATA_TYPE_TEMP_HUM)
{
sprintf(s, "%.1f",
(int16_t)le16toh(*(uint16_t *)mijia_temp_hum->data) / 10.0);
cb("Temperature", s, ctx);
sprintf(s, "%.1f",
le16toh(*(uint16_t *)(mijia_temp_hum->data + 2)) / 10.0);
cb("Humidity", s, ctx);
}
}
static broadcaster_ops_t mijia_temp_hum_ops = {
.name = "Mijia Temp+Hum",
.is_broadcaster = mijia_temp_hum_is_broadcaster,
.metadata_get = mijia_temp_hum_metadata_get,
};
/* Beewi Smart Door
* Note that the Beewi Smart Door sensor is also connectable. When connected, it
* provides battery information and door status history (without the current
* state). To overcome this, the sensor should be blacklisted so the app would
* not connect to it and the sensor would brodcast the current state. */
#define BEEWI_SMART_DOOR_COMPANY_ID 0x000D
#define BEEWI_SMART_DOOR_SERVICE_ID 0x08
#define BEEWI_SMART_DOOR_DATA_TBD1 0x0C
typedef struct {
uint16_t company_id;
uint8_t service_id;
uint8_t tbd1;
uint8_t status;
uint8_t tbd2;
uint8_t battery;
} __attribute__((packed)) beewi_smart_door_t;
static beewi_smart_door_t *beewi_smart_door_data_get(uint8_t *adv_data,
uint8_t adv_data_len, uint8_t *beewi_smart_door_len)
{
uint8_t len;
uint8_t *data = esp_ble_resolve_adv_data(adv_data,
ESP_BLE_AD_MANUFACTURER_SPECIFIC_TYPE, &len);
if (beewi_smart_door_len)
*beewi_smart_door_len = len;
return (beewi_smart_door_t *)data;
}
static int beewi_smart_door_is_broadcaster(uint8_t *adv_data,
size_t adv_data_len)
{
uint8_t len;
uint8_t *data = esp_ble_resolve_adv_data(adv_data,
ESP_BLE_AD_TYPE_NAME_CMPL, &len);
if (len == 16 && strncmp((char *)data, "BeeWi Smart Door", len))
return 0;
beewi_smart_door_t *beewi_smart_door = beewi_smart_door_data_get(adv_data,
adv_data_len, &len);
if (!beewi_smart_door || len != sizeof(beewi_smart_door_t))
return 0;
return 1;
}
static void beewi_smart_door_metadata_get(uint8_t *adv_data,
size_t adv_data_len, int rssi, broadcaster_meta_data_cb_t cb, void *ctx)
{
char s[4];
beewi_smart_door_t *beewi_smart_door = beewi_smart_door_data_get(adv_data,
adv_data_len, NULL);
if (beewi_smart_door->tbd1 == BEEWI_SMART_DOOR_DATA_TBD1)
{
sprintf(s,"%hhu",beewi_smart_door->status );
cb("Status", s, ctx);
sprintf(s,"%hhu",beewi_smart_door->battery);
cb("Battery", s, ctx);
}
}
static broadcaster_ops_t beewi_smart_door_ops = {
.name = "BeeWi Smart Door",
.is_broadcaster = beewi_smart_door_is_broadcaster,
.metadata_get = beewi_smart_door_metadata_get,
};
/* Common */
static broadcaster_ops_t *broadcaster_ops[] = {
&ibeacon_ops,
&eddystone_ops,
&mijia_temp_hum_ops,
&beewi_smart_door_ops,
NULL
};
broadcaster_ops_t *broadcaster_ops_get(uint8_t *adv_data, size_t adv_data_len)
{
broadcaster_ops_t **ops;
for (ops = broadcaster_ops; *ops; ops++)
{
if ((*ops)->is_broadcaster(adv_data, adv_data_len))
return (*ops);
}
return NULL;
}
|
277280.c | /** @file
Copyright (c) 2013-2021, Arm Ltd. All rights reserved.<BR>
SPDX-License-Identifier: BSD-2-Clause-Patent
**/
#include <PiDxe.h>
#include <Library/ArmShellCmdLib.h>
#include <Library/BaseMemoryLib.h>
#include <Library/DebugLib.h>
#include <Library/IoLib.h>
#include <Library/TimerLib.h>
#include <Library/UefiBootServicesTableLib.h>
#include <Library/VirtioMmioDeviceLib.h>
#include <VExpressMotherBoard.h>
#define ARM_FVP_BASE_VIRTIO_BLOCK_BASE 0x1c130000
// SMMUv3 Global Bypass Attribute (GBPA) register offset.
#define SMMU_GBPA 0x0044
// SMMU_GBPA register fields.
#define SMMU_GBPA_UPDATE BIT31
#define SMMU_GBPA_ABORT BIT20
#pragma pack(1)
typedef struct {
VENDOR_DEVICE_PATH Vendor;
EFI_DEVICE_PATH_PROTOCOL End;
} VIRTIO_BLK_DEVICE_PATH;
#pragma pack()
VIRTIO_BLK_DEVICE_PATH mVirtioBlockDevicePath =
{
{
{
HARDWARE_DEVICE_PATH,
HW_VENDOR_DP,
{
(UINT8)( sizeof(VENDOR_DEVICE_PATH) ),
(UINT8)((sizeof(VENDOR_DEVICE_PATH)) >> 8)
}
},
EFI_CALLER_ID_GUID,
},
{
END_DEVICE_PATH_TYPE,
END_ENTIRE_DEVICE_PATH_SUBTYPE,
{
sizeof (EFI_DEVICE_PATH_PROTOCOL),
0
}
}
};
/**
Poll the SMMU register and test the value based on the mask.
@param [in] SmmuReg Base address of the SMMU register.
@param [in] Mask Mask of register bits to monitor.
@param [in] Value Expected value.
@retval EFI_SUCCESS Success.
@retval EFI_TIMEOUT Timeout.
**/
STATIC
EFI_STATUS
EFIAPI
SmmuV3Poll (
IN UINT64 SmmuReg,
IN UINT32 Mask,
IN UINT32 Value
)
{
UINT32 RegVal;
UINTN Count;
// Set 1ms timeout value.
Count = 10;
do {
RegVal = MmioRead32 (SmmuReg);
if ((RegVal & Mask) == Value) {
return EFI_SUCCESS;
}
MicroSecondDelay (100);
} while ((--Count) > 0);
DEBUG ((DEBUG_ERROR, "Timeout polling SMMUv3 register @%p\n", SmmuReg));
DEBUG ((
DEBUG_ERROR,
"Read value 0x%x, expected 0x%x\n",
RegVal,
((Value == 0) ? (RegVal & ~Mask) : (RegVal | Mask))
));
return EFI_TIMEOUT;
}
/**
Initialise the SMMUv3 to set Non-secure streams to bypass the SMMU.
@param [in] SmmuReg Base address of the SMMUv3.
@retval EFI_SUCCESS Success.
@retval EFI_TIMEOUT Timeout.
**/
STATIC
EFI_STATUS
EFIAPI
SmmuV3Init (
IN UINT64 SmmuBase
)
{
EFI_STATUS Status;
UINT32 RegVal;
// Attribute update has completed when SMMU_(S)_GBPA.Update bit is 0.
Status = SmmuV3Poll (SmmuBase + SMMU_GBPA, SMMU_GBPA_UPDATE, 0);
if (EFI_ERROR (Status)) {
return Status;
}
// SMMU_(S)_CR0 resets to zero with all streams bypassing the SMMU,
// so just abort all incoming transactions.
RegVal = MmioRead32 (SmmuBase + SMMU_GBPA);
// TF-A configures the SMMUv3 to abort all incoming transactions.
// Clear the SMMU_GBPA.ABORT to allow Non-secure streams to bypass
// the SMMU.
RegVal &= ~SMMU_GBPA_ABORT;
RegVal |= SMMU_GBPA_UPDATE;
MmioWrite32 (SmmuBase + SMMU_GBPA, RegVal);
Status = SmmuV3Poll (SmmuBase + SMMU_GBPA, SMMU_GBPA_UPDATE, 0);
if (EFI_ERROR (Status)) {
return Status;
}
return EFI_SUCCESS;
}
/**
* Generic UEFI Entrypoint for 'ArmFvpDxe' driver
* See UEFI specification for the details of the parameters
*/
EFI_STATUS
EFIAPI
ArmFvpInitialise (
IN EFI_HANDLE ImageHandle,
IN EFI_SYSTEM_TABLE *SystemTable
)
{
EFI_STATUS Status;
UINT32 SysId;
Status = gBS->InstallProtocolInterface (&ImageHandle,
&gEfiDevicePathProtocolGuid, EFI_NATIVE_INTERFACE,
&mVirtioBlockDevicePath);
if (EFI_ERROR (Status)) {
return Status;
}
// Declare the Virtio BlockIo device
Status = VirtioMmioInstallDevice (ARM_FVP_BASE_VIRTIO_BLOCK_BASE, ImageHandle);
if (EFI_ERROR (Status)) {
DEBUG ((EFI_D_ERROR, "ArmFvpDxe: Failed to install Virtio block device\n"));
}
// Install dynamic Shell command to run baremetal binaries.
Status = ShellDynCmdRunAxfInstall (ImageHandle);
if (EFI_ERROR (Status)) {
DEBUG ((EFI_D_ERROR, "ArmFvpDxe: Failed to install ShellDynCmdRunAxf\n"));
}
// If FVP RevC - Configure SMMUv3 to set NS transactions in bypass mode.
SysId = MmioRead32 (ARM_VE_SYS_ID_REG);
if ((SysId & ARM_FVP_SYS_ID_REV_MASK) == ARM_FVP_BASE_REVC_REV) {
Status = SmmuV3Init (FVP_REVC_SMMUV3_BASE);
if (EFI_ERROR (Status)) {
DEBUG ((
DEBUG_ERROR,
"ArmFvpDxe: Failed to initialise SMMUv3 in bypass mode.\n"
));
}
}
return Status;
}
|
599345.c | #include <linux/module.h>
#include <linux/init.h>
#include <linux/platform_device.h>
#include <linux/types.h>
#include <linux/ioport.h>
#include <linux/of.h>
#include <linux/fs.h>
#include <asm/io.h>
#include <linux/cdev.h>
#include <linux/interrupt.h>
#include <linux/signal.h>
#include <linux/slab.h>
#include <linux/device.h>
#include <linux/sysfs.h>
#include <asm/uaccess.h>
#include <linux/of_irq.h>
#include <linux/of_platform.h>
#include <linux/wait.h>
#include <linux/param.h>
#include <linux/sched.h>
#include "z7nau_axigpio.h"
wait_queue_head_t wait_key;
static int z7nau_axigpio_open(struct inode *inode, struct file *filep)
{
struct cdev *chrdev = inode->i_cdev;
struct axi_gpio_dev *xdev = container_of(chrdev, struct axi_gpio_dev, cdev);
//enable interrupt
iowrite32(Z7GPIO_ISR_MASK,xdev->regs+Z7REG_IPISR_OFFSET);
iowrite32(Z7GPIO_IER_MASK,xdev->regs+Z7REG_IPIER_OFFSET);
iowrite32(Z7GPIO_GIER,xdev->regs+Z7REG_GIER_OFFSET);
return 0;
}
static long z7nau_axigpio_ioctl(struct file *filep, unsigned int cmd, unsigned long arg)
{
struct inode *inode = filep->f_inode;
struct cdev *chrdev = inode->i_cdev;
struct axi_gpio_dev *xdev = container_of(chrdev, struct axi_gpio_dev, cdev);
int value;
switch (cmd) {
case Z7AXIGPIO_RDATA:
value = ioread32(xdev->regs+Z7REG_GPIODATA_OFFSET);
break;
case Z7AXIGPIO_RTRI:
value = ioread32(xdev->regs+Z7REG_GPIOTRI_OFFSET);
break;
case Z7AXIGPIO2_RDATA:
if (arg == 0)
value = ioread32(xdev->regs+Z7REG_GPIO2DATA_OFFSET);
else {
arg = arg * HZ / 1000;//arg in msecond to system ticks
wait_event_interruptible_timeout(wait_key, xdev->wait_flag, arg);
value = ioread32(xdev->regs+Z7REG_GPIO2DATA_OFFSET);
}
break;
case Z7AXIGPIO2_RTRI:
value = ioread32(xdev->regs+Z7REG_GPIO2TRI_OFFSET);
break;
case Z7AXIGPIO_RGIER:
value = ioread32(xdev->regs+Z7REG_GIER_OFFSET);
value = (value >> 31) & Z7GPIO_GIER_MASK;
break;
case Z7AXIGPIO_RIER:
value = ioread32(xdev->regs+Z7REG_IPIER_OFFSET);
value = (value & Z7GPIO_IER_MASK) >> 1;
break;
case Z7AXIGPIO_RISR:
value = ioread32(xdev->regs+Z7REG_IPISR_OFFSET);
value = (value & Z7GPIO_ISR_MASK) >> 1;
break;
case Z7AXIGPIO_WDATA:
iowrite32(arg,xdev->regs+Z7REG_GPIODATA_OFFSET);
break;
case Z7AXIGPIO_WTRI:
iowrite32(arg,xdev->regs+Z7REG_GPIOTRI_OFFSET);
break;
case Z7AXIGPIO2_WTRI:
iowrite32(arg,xdev->regs+Z7REG_GPIO2TRI_OFFSET);
break;
case Z7AXIGPIO_WGIER:
arg = arg << 31;
iowrite32(arg,xdev->regs+Z7REG_GIER_OFFSET);
break;
case Z7AXIGPIO_WIER:
arg =( arg << 1 ) & Z7GPIO_IER_MASK;
iowrite32(arg,xdev->regs+Z7REG_IPIER_OFFSET);
break;
default:
return -EOPNOTSUPP;
}
return value;
}
static int z7nau_axigpio_release(struct inode * inode, struct file *filep)
{
struct cdev *chrdev = inode->i_cdev;
struct axi_gpio_dev *xdev = container_of(chrdev, struct axi_gpio_dev, cdev);
iowrite32(0xffffffff,xdev->regs+Z7REG_IPISR_OFFSET);
iowrite32(0x00000000,xdev->regs+Z7REG_IPIER_OFFSET);
iowrite32(0x00000000,xdev->regs+Z7REG_GIER_OFFSET);
return 0;
}
static const struct file_operations axigpio_fileops = {
//.read = z7nau_axigpio_read,
//.write = z7nau_axigpio_write,
.unlocked_ioctl = z7nau_axigpio_ioctl,
.release = z7nau_axigpio_release,
.open = z7nau_axigpio_open,
.owner = THIS_MODULE,
};
static irqreturn_t axigpio_interrupt_handler(int irq, void *devid)
{
struct axi_gpio_dev *xdev = devid;
printk("interrupt handler function! irq = %d\n",irq);
//clear int flag
iowrite32(0xffffffff,xdev->regs+Z7REG_IPISR_OFFSET);
if(waitqueue_active(&wait_key)){
xdev->wait_flag = 1;
wake_up_interruptible( &wait_key);
}
return IRQ_HANDLED;
}
static const struct of_device_id z7nau_axigpio_of_match_table[] = {
{ .compatible = "xlnx,z7nau-axi-GPIO-1.0", NULL },
{ },
};
MODULE_DEVICE_TABLE(of, z7nau_axigpio_of_match_table);
static int z7nau_axigpio_probe(struct platform_device *pdev)
{
struct axi_gpio_dev *xdev;
struct device_node *node;
struct resource *res;
struct device *devp;
int status,value;
printk("axi_gpio_probe start!!!\n");
xdev = devm_kzalloc(&pdev->dev, sizeof(*xdev), GFP_KERNEL);
if (!xdev)
return -ENOMEM;
xdev->dev = &(pdev->dev);
node = pdev->dev.of_node;
if (!node)
return -ENODEV;
/* Map the registers */
res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
xdev->regs = devm_ioremap_resource(&pdev->dev, res);
/*************Hardware initialization*******************/
of_property_read_u32(node, "xlnx,is-dual", &value);
if (value ==0){
printk("axigpio isn't dual port mode!!!\n");
return -EINVAL;
}
of_property_read_u32(node, "xlnx,all-outputs", &value);
if (value ==0){
printk("axigpio port1 isn't all output mode!!!\n");
return -EINVAL;
}
of_property_read_u32(node, "xlnx,all-inputs-2", &value);
if (value ==0){
printk("axigpio port2 isn't all input mode!!!\n");
return -EINVAL;
}
of_property_read_u32(node, "xlnx,gpio2-width", &value);
if (value != 1){
printk("Don't support axigpio port2 width more than 1!!!\n");
return -EINVAL;
}
of_property_read_u32(node, "xlnx,interrupt-present", &value);
if (value != 1){
printk("no axigpio interrupt defined!!\n");
return -EINVAL;
}
of_property_read_u32(node, "xlnx,dout-default", &value);
iowrite32(value,xdev->regs+Z7REG_GPIODATA_OFFSET);
iowrite32(Z7GPIO_DIR,xdev->regs+Z7REG_GPIOTRI_OFFSET);
iowrite32(Z7GPIO2_DIR,xdev->regs+Z7REG_GPIO2TRI_OFFSET);
iowrite32(0xffffffff,xdev->regs+Z7REG_IPISR_OFFSET);
iowrite32(0x00000000,xdev->regs+Z7REG_IPIER_OFFSET);
iowrite32(0x00000000,xdev->regs+Z7REG_GIER_OFFSET);
/* find the IRQ line, if it exists in the device tree */
xdev->irq = irq_of_parse_and_map(node, 0);
status = request_irq(xdev->irq, axigpio_interrupt_handler,
IRQF_TRIGGER_HIGH | IRQF_SHARED, MODULE_NAME, xdev);
if (status) {
dev_err(xdev->dev, "axi GPIO unable to request IRQ %d\n", xdev->irq);
return status;
}
status =alloc_chrdev_region(&xdev->devno,
AXIGPIO_MINOR_START, AXIGPIO_MINOR_COUNT,MODULE_NAME);
if (status < 0) {
dev_err(&pdev->dev, "unable to alloc axi GPIO chrdev \n");
return status;
}
cdev_init(&xdev->cdev, &axigpio_fileops);
xdev->cdev.owner = THIS_MODULE;
xdev->cdev.ops = &axigpio_fileops;
status = cdev_add(&xdev->cdev, xdev->devno,
AXIGPIO_MINOR_COUNT);
if (status){
dev_err(&pdev->dev,"Err: failed in registering axigpio cdev.\n");
return status;
}
platform_set_drvdata(pdev, xdev);
axigpio_class = class_create(THIS_MODULE,MODULE_NAME);
if(IS_ERR(axigpio_class))
{
printk("failed creat axigpio_class !\n");
}
devp = device_create( axigpio_class,NULL,xdev->devno,NULL,MODULE_NAME);
if(IS_ERR(devp))
printk("failed to creat device node!\n");
xdev->wait_flag = 0;
init_waitqueue_head (&wait_key);
printk("axigpio_probe end!!!\n");
return SUCCESS;
}
static int z7nau_axigpio_remove(struct platform_device *pdev)
{
struct axi_gpio_dev *xdev = platform_get_drvdata(pdev);
if (xdev->irq > 0)
free_irq(xdev->irq, xdev);
cdev_del(&xdev->cdev);
device_destroy(axigpio_class,MKDEV(MAJOR(xdev->devno),
AXIGPIO_MINOR_START));
unregister_chrdev_region(xdev->devno, AXIGPIO_MINOR_COUNT);
class_destroy(axigpio_class);
return SUCCESS;
}
static struct platform_driver z7nau_axigpio_driver = {
.probe = z7nau_axigpio_probe,
.remove = z7nau_axigpio_remove,
.driver = {
.name = MODULE_NAME,
.owner = THIS_MODULE,
.of_match_table =z7nau_axigpio_of_match_table,
},
};
module_platform_driver(z7nau_axigpio_driver);
MODULE_LICENSE("GPL v2");
MODULE_AUTHOR("seu");
MODULE_DESCRIPTION("axi GPIO and key interrupt driver");
MODULE_VERSION("1.00");
|
884839.c | /*
* tkEntry.c --
*
* This module implements entry and spinbox widgets for the Tk toolkit.
* An entry displays a string and allows the string to be edited. A
* spinbox expands on the entry by adding up/down buttons that control
* the value of the entry widget.
*
* Copyright © 1990-1994 The Regents of the University of California.
* Copyright © 1994-1997 Sun Microsystems, Inc.
* Copyright © 2000 Ajuba Solutions.
* Copyright © 2002 ActiveState Corporation.
*
* See the file "license.terms" for information on usage and redistribution of
* this file, and for a DISCLAIMER OF ALL WARRANTIES.
*/
#include "tkInt.h"
#include "tkEntry.h"
#include "default.h"
/*
* The following macro defines how many extra pixels to leave on each side of
* the text in the entry.
*/
#define XPAD 1
#define YPAD 1
/*
* A comparison function for double values. For Spinboxes.
*/
#define MIN_DBL_VAL 1E-9
#define DOUBLES_EQ(d1, d2) (fabs((d1) - (d2)) < MIN_DBL_VAL)
static const char *const stateStrings[] = {
"disabled", "normal", "readonly", NULL
};
/*
* Definitions for -validate option values:
*/
static const char *const validateStrings[] = {
"all", "key", "focus", "focusin", "focusout", "none", NULL
};
enum validateType {
VALIDATE_ALL, VALIDATE_KEY, VALIDATE_FOCUS,
VALIDATE_FOCUSIN, VALIDATE_FOCUSOUT, VALIDATE_NONE,
/*
* These extra enums are for use with EntryValidateChange
*/
VALIDATE_FORCED, VALIDATE_DELETE, VALIDATE_INSERT, VALIDATE_BUTTON
};
#define DEF_ENTRY_VALIDATE "none"
#define DEF_ENTRY_INVALIDCMD ""
/*
* Information used for Entry objv parsing.
*/
static const Tk_OptionSpec entryOptSpec[] = {
{TK_OPTION_BORDER, "-background", "background", "Background",
DEF_ENTRY_BG_COLOR, TCL_INDEX_NONE, offsetof(Entry, normalBorder),
0, DEF_ENTRY_BG_MONO, 0},
{TK_OPTION_SYNONYM, "-bd", NULL, NULL,
NULL, 0, TCL_INDEX_NONE, 0, "-borderwidth", 0},
{TK_OPTION_SYNONYM, "-bg", NULL, NULL,
NULL, 0, TCL_INDEX_NONE, 0, "-background", 0},
{TK_OPTION_PIXELS, "-borderwidth", "borderWidth", "BorderWidth",
DEF_ENTRY_BORDER_WIDTH, TCL_INDEX_NONE, offsetof(Entry, borderWidth), 0, 0, 0},
{TK_OPTION_CURSOR, "-cursor", "cursor", "Cursor",
DEF_ENTRY_CURSOR, TCL_INDEX_NONE, offsetof(Entry, cursor),
TK_OPTION_NULL_OK, 0, 0},
{TK_OPTION_BORDER, "-disabledbackground", "disabledBackground",
"DisabledBackground", DEF_ENTRY_DISABLED_BG_COLOR, TCL_INDEX_NONE,
offsetof(Entry, disabledBorder), TK_OPTION_NULL_OK,
(ClientData) DEF_ENTRY_DISABLED_BG_MONO, 0},
{TK_OPTION_COLOR, "-disabledforeground", "disabledForeground",
"DisabledForeground", DEF_ENTRY_DISABLED_FG, TCL_INDEX_NONE,
offsetof(Entry, dfgColorPtr), TK_OPTION_NULL_OK, 0, 0},
{TK_OPTION_BOOLEAN, "-exportselection", "exportSelection",
"ExportSelection", DEF_ENTRY_EXPORT_SELECTION, TCL_INDEX_NONE,
offsetof(Entry, exportSelection), 0, 0, 0},
{TK_OPTION_SYNONYM, "-fg", "foreground", NULL,
NULL, 0, TCL_INDEX_NONE, 0, "-foreground", 0},
{TK_OPTION_FONT, "-font", "font", "Font",
DEF_ENTRY_FONT, TCL_INDEX_NONE, offsetof(Entry, tkfont), 0, 0, 0},
{TK_OPTION_COLOR, "-foreground", "foreground", "Foreground",
DEF_ENTRY_FG, TCL_INDEX_NONE, offsetof(Entry, fgColorPtr), 0, 0, 0},
{TK_OPTION_COLOR, "-highlightbackground", "highlightBackground",
"HighlightBackground", DEF_ENTRY_HIGHLIGHT_BG,
TCL_INDEX_NONE, offsetof(Entry, highlightBgColorPtr), 0, 0, 0},
{TK_OPTION_COLOR, "-highlightcolor", "highlightColor", "HighlightColor",
DEF_ENTRY_HIGHLIGHT, TCL_INDEX_NONE, offsetof(Entry, highlightColorPtr), 0, 0, 0},
{TK_OPTION_PIXELS, "-highlightthickness", "highlightThickness",
"HighlightThickness", DEF_ENTRY_HIGHLIGHT_WIDTH, TCL_INDEX_NONE,
offsetof(Entry, highlightWidth), 0, 0, 0},
{TK_OPTION_BORDER, "-insertbackground", "insertBackground", "Foreground",
DEF_ENTRY_INSERT_BG, TCL_INDEX_NONE, offsetof(Entry, insertBorder), 0, 0, 0},
{TK_OPTION_PIXELS, "-insertborderwidth", "insertBorderWidth",
"BorderWidth", DEF_ENTRY_INSERT_BD_COLOR, TCL_INDEX_NONE,
offsetof(Entry, insertBorderWidth), 0,
(ClientData) DEF_ENTRY_INSERT_BD_MONO, 0},
{TK_OPTION_INT, "-insertofftime", "insertOffTime", "OffTime",
DEF_ENTRY_INSERT_OFF_TIME, TCL_INDEX_NONE, offsetof(Entry, insertOffTime),
0, 0, 0},
{TK_OPTION_INT, "-insertontime", "insertOnTime", "OnTime",
DEF_ENTRY_INSERT_ON_TIME, TCL_INDEX_NONE, offsetof(Entry, insertOnTime), 0, 0, 0},
{TK_OPTION_PIXELS, "-insertwidth", "insertWidth", "InsertWidth",
DEF_ENTRY_INSERT_WIDTH, TCL_INDEX_NONE, offsetof(Entry, insertWidth), 0, 0, 0},
{TK_OPTION_STRING, "-invalidcommand", "invalidCommand", "InvalidCommand",
DEF_ENTRY_INVALIDCMD, TCL_INDEX_NONE, offsetof(Entry, invalidCmd),
TK_OPTION_NULL_OK, 0, 0},
{TK_OPTION_SYNONYM, "-invcmd", NULL, NULL,
NULL, 0, TCL_INDEX_NONE, 0, "-invalidcommand", 0},
{TK_OPTION_JUSTIFY, "-justify", "justify", "Justify",
DEF_ENTRY_JUSTIFY, TCL_INDEX_NONE, offsetof(Entry, justify), 0, 0, 0},
{TK_OPTION_STRING, "-placeholder", "placeHolder", "PlaceHolder",
DEF_ENTRY_PLACEHOLDER, TCL_INDEX_NONE, offsetof(Entry, placeholderString),
TK_OPTION_NULL_OK, 0, 0},
{TK_OPTION_COLOR, "-placeholderforeground", "placeholderForeground",
"PlaceholderForeground", DEF_ENTRY_PLACEHOLDERFG, TCL_INDEX_NONE,
offsetof(Entry, placeholderColorPtr), 0, 0, 0},
{TK_OPTION_BORDER, "-readonlybackground", "readonlyBackground",
"ReadonlyBackground", DEF_ENTRY_READONLY_BG_COLOR, TCL_INDEX_NONE,
offsetof(Entry, readonlyBorder), TK_OPTION_NULL_OK,
(ClientData) DEF_ENTRY_READONLY_BG_MONO, 0},
{TK_OPTION_RELIEF, "-relief", "relief", "Relief",
DEF_ENTRY_RELIEF, TCL_INDEX_NONE, offsetof(Entry, relief), 0, 0, 0},
{TK_OPTION_BORDER, "-selectbackground", "selectBackground", "Foreground",
DEF_ENTRY_SELECT_COLOR, TCL_INDEX_NONE, offsetof(Entry, selBorder),
0, DEF_ENTRY_SELECT_MONO, 0},
{TK_OPTION_PIXELS, "-selectborderwidth", "selectBorderWidth",
"BorderWidth", DEF_ENTRY_SELECT_BD_COLOR, TCL_INDEX_NONE,
offsetof(Entry, selBorderWidth),
0, DEF_ENTRY_SELECT_BD_MONO, 0},
{TK_OPTION_COLOR, "-selectforeground", "selectForeground", "Background",
DEF_ENTRY_SELECT_FG_COLOR, TCL_INDEX_NONE, offsetof(Entry, selFgColorPtr),
TK_OPTION_NULL_OK, DEF_ENTRY_SELECT_FG_MONO, 0},
{TK_OPTION_STRING, "-show", "show", "Show",
DEF_ENTRY_SHOW, TCL_INDEX_NONE, offsetof(Entry, showChar),
TK_OPTION_NULL_OK, 0, 0},
{TK_OPTION_STRING_TABLE, "-state", "state", "State",
DEF_ENTRY_STATE, TCL_INDEX_NONE, offsetof(Entry, state),
0, stateStrings, 0},
{TK_OPTION_STRING, "-takefocus", "takeFocus", "TakeFocus",
DEF_ENTRY_TAKE_FOCUS, TCL_INDEX_NONE, offsetof(Entry, takeFocus),
TK_OPTION_NULL_OK, 0, 0},
{TK_OPTION_STRING, "-textvariable", "textVariable", "Variable",
DEF_ENTRY_TEXT_VARIABLE, TCL_INDEX_NONE, offsetof(Entry, textVarName),
TK_OPTION_NULL_OK, 0, 0},
{TK_OPTION_STRING_TABLE, "-validate", "validate", "Validate",
DEF_ENTRY_VALIDATE, TCL_INDEX_NONE, offsetof(Entry, validate),
0, validateStrings, 0},
{TK_OPTION_STRING, "-validatecommand", "validateCommand","ValidateCommand",
NULL, TCL_INDEX_NONE, offsetof(Entry, validateCmd), TK_OPTION_NULL_OK, 0, 0},
{TK_OPTION_SYNONYM, "-vcmd", NULL, NULL,
NULL, 0, TCL_INDEX_NONE, 0, "-validatecommand", 0},
{TK_OPTION_INT, "-width", "width", "Width",
DEF_ENTRY_WIDTH, TCL_INDEX_NONE, offsetof(Entry, prefWidth), 0, 0, 0},
{TK_OPTION_STRING, "-xscrollcommand", "xScrollCommand", "ScrollCommand",
DEF_ENTRY_SCROLL_COMMAND, TCL_INDEX_NONE, offsetof(Entry, scrollCmd),
TK_OPTION_NULL_OK, 0, 0},
{TK_OPTION_END, NULL, NULL, NULL, NULL, 0, TCL_INDEX_NONE, 0, 0, 0}
};
/*
* Information used for Spinbox objv parsing.
*/
#define DEF_SPINBOX_REPEAT_DELAY "400"
#define DEF_SPINBOX_REPEAT_INTERVAL "100"
#define DEF_SPINBOX_CMD ""
#define DEF_SPINBOX_FROM "0"
#define DEF_SPINBOX_TO "0"
#define DEF_SPINBOX_INCREMENT "1"
#define DEF_SPINBOX_FORMAT ""
#define DEF_SPINBOX_VALUES ""
#define DEF_SPINBOX_WRAP "0"
static const Tk_OptionSpec sbOptSpec[] = {
{TK_OPTION_BORDER, "-activebackground", "activeBackground", "Background",
DEF_BUTTON_ACTIVE_BG_COLOR, TCL_INDEX_NONE, offsetof(Spinbox, activeBorder),
0, DEF_BUTTON_ACTIVE_BG_MONO, 0},
{TK_OPTION_BORDER, "-background", "background", "Background",
DEF_ENTRY_BG_COLOR, TCL_INDEX_NONE, offsetof(Entry, normalBorder),
0, DEF_ENTRY_BG_MONO, 0},
{TK_OPTION_SYNONYM, "-bd", NULL, NULL,
NULL, 0, TCL_INDEX_NONE, 0, "-borderwidth", 0},
{TK_OPTION_SYNONYM, "-bg", NULL, NULL,
NULL, 0, TCL_INDEX_NONE, 0, "-background", 0},
{TK_OPTION_PIXELS, "-borderwidth", "borderWidth", "BorderWidth",
DEF_ENTRY_BORDER_WIDTH, TCL_INDEX_NONE, offsetof(Entry, borderWidth), 0, 0, 0},
{TK_OPTION_BORDER, "-buttonbackground", "buttonBackground", "Background",
DEF_BUTTON_BG_COLOR, TCL_INDEX_NONE, offsetof(Spinbox, buttonBorder),
0, DEF_BUTTON_BG_MONO, 0},
{TK_OPTION_CURSOR, "-buttoncursor", "buttonCursor", "Cursor",
DEF_BUTTON_CURSOR, TCL_INDEX_NONE, offsetof(Spinbox, bCursor),
TK_OPTION_NULL_OK, 0, 0},
{TK_OPTION_RELIEF, "-buttondownrelief", "buttonDownRelief", "Relief",
DEF_BUTTON_RELIEF, TCL_INDEX_NONE, offsetof(Spinbox, bdRelief), 0, 0, 0},
{TK_OPTION_RELIEF, "-buttonuprelief", "buttonUpRelief", "Relief",
DEF_BUTTON_RELIEF, TCL_INDEX_NONE, offsetof(Spinbox, buRelief), 0, 0, 0},
{TK_OPTION_STRING, "-command", "command", "Command",
DEF_SPINBOX_CMD, TCL_INDEX_NONE, offsetof(Spinbox, command),
TK_OPTION_NULL_OK, 0, 0},
{TK_OPTION_CURSOR, "-cursor", "cursor", "Cursor",
DEF_ENTRY_CURSOR, TCL_INDEX_NONE, offsetof(Entry, cursor),
TK_OPTION_NULL_OK, 0, 0},
{TK_OPTION_BORDER, "-disabledbackground", "disabledBackground",
"DisabledBackground", DEF_ENTRY_DISABLED_BG_COLOR, TCL_INDEX_NONE,
offsetof(Entry, disabledBorder), TK_OPTION_NULL_OK,
(ClientData) DEF_ENTRY_DISABLED_BG_MONO, 0},
{TK_OPTION_COLOR, "-disabledforeground", "disabledForeground",
"DisabledForeground", DEF_ENTRY_DISABLED_FG, TCL_INDEX_NONE,
offsetof(Entry, dfgColorPtr), TK_OPTION_NULL_OK, 0, 0},
{TK_OPTION_BOOLEAN, "-exportselection", "exportSelection",
"ExportSelection", DEF_ENTRY_EXPORT_SELECTION, TCL_INDEX_NONE,
offsetof(Entry, exportSelection), 0, 0, 0},
{TK_OPTION_SYNONYM, "-fg", "foreground", NULL,
NULL, 0, TCL_INDEX_NONE, 0, "-foreground", 0},
{TK_OPTION_FONT, "-font", "font", "Font",
DEF_ENTRY_FONT, TCL_INDEX_NONE, offsetof(Entry, tkfont), 0, 0, 0},
{TK_OPTION_COLOR, "-foreground", "foreground", "Foreground",
DEF_ENTRY_FG, TCL_INDEX_NONE, offsetof(Entry, fgColorPtr), 0, 0, 0},
{TK_OPTION_STRING, "-format", "format", "Format",
DEF_SPINBOX_FORMAT, TCL_INDEX_NONE, offsetof(Spinbox, reqFormat),
TK_OPTION_NULL_OK, 0, 0},
{TK_OPTION_DOUBLE, "-from", "from", "From",
DEF_SPINBOX_FROM, TCL_INDEX_NONE, offsetof(Spinbox, fromValue), 0, 0, 0},
{TK_OPTION_COLOR, "-highlightbackground", "highlightBackground",
"HighlightBackground", DEF_ENTRY_HIGHLIGHT_BG,
TCL_INDEX_NONE, offsetof(Entry, highlightBgColorPtr), 0, 0, 0},
{TK_OPTION_COLOR, "-highlightcolor", "highlightColor", "HighlightColor",
DEF_ENTRY_HIGHLIGHT, TCL_INDEX_NONE, offsetof(Entry, highlightColorPtr), 0, 0, 0},
{TK_OPTION_PIXELS, "-highlightthickness", "highlightThickness",
"HighlightThickness", DEF_ENTRY_HIGHLIGHT_WIDTH, TCL_INDEX_NONE,
offsetof(Entry, highlightWidth), 0, 0, 0},
{TK_OPTION_DOUBLE, "-increment", "increment", "Increment",
DEF_SPINBOX_INCREMENT, TCL_INDEX_NONE, offsetof(Spinbox, increment), 0, 0, 0},
{TK_OPTION_BORDER, "-insertbackground", "insertBackground", "Foreground",
DEF_ENTRY_INSERT_BG, TCL_INDEX_NONE, offsetof(Entry, insertBorder), 0, 0, 0},
{TK_OPTION_PIXELS, "-insertborderwidth", "insertBorderWidth",
"BorderWidth", DEF_ENTRY_INSERT_BD_COLOR, TCL_INDEX_NONE,
offsetof(Entry, insertBorderWidth), 0,
(ClientData) DEF_ENTRY_INSERT_BD_MONO, 0},
{TK_OPTION_INT, "-insertofftime", "insertOffTime", "OffTime",
DEF_ENTRY_INSERT_OFF_TIME, TCL_INDEX_NONE, offsetof(Entry, insertOffTime),
0, 0, 0},
{TK_OPTION_INT, "-insertontime", "insertOnTime", "OnTime",
DEF_ENTRY_INSERT_ON_TIME, TCL_INDEX_NONE, offsetof(Entry, insertOnTime), 0, 0, 0},
{TK_OPTION_PIXELS, "-insertwidth", "insertWidth", "InsertWidth",
DEF_ENTRY_INSERT_WIDTH, TCL_INDEX_NONE, offsetof(Entry, insertWidth), 0, 0, 0},
{TK_OPTION_STRING, "-invalidcommand", "invalidCommand", "InvalidCommand",
DEF_ENTRY_INVALIDCMD, TCL_INDEX_NONE, offsetof(Entry, invalidCmd),
TK_OPTION_NULL_OK, 0, 0},
{TK_OPTION_SYNONYM, "-invcmd", NULL, NULL,
NULL, 0, TCL_INDEX_NONE, 0, "-invalidcommand", 0},
{TK_OPTION_JUSTIFY, "-justify", "justify", "Justify",
DEF_ENTRY_JUSTIFY, TCL_INDEX_NONE, offsetof(Entry, justify), 0, 0, 0},
{TK_OPTION_STRING, "-placeholder", "placeHolder", "PlaceHolder",
DEF_ENTRY_PLACEHOLDER, TCL_INDEX_NONE, offsetof(Entry, placeholderString),
TK_OPTION_NULL_OK, 0, 0},
{TK_OPTION_COLOR, "-placeholderforeground", "placeholderForeground",
"PlaceholderForeground", DEF_ENTRY_PLACEHOLDERFG, TCL_INDEX_NONE,
offsetof(Entry, placeholderColorPtr), 0, 0, 0},
{TK_OPTION_RELIEF, "-relief", "relief", "Relief",
DEF_ENTRY_RELIEF, TCL_INDEX_NONE, offsetof(Entry, relief), 0, 0, 0},
{TK_OPTION_BORDER, "-readonlybackground", "readonlyBackground",
"ReadonlyBackground", DEF_ENTRY_READONLY_BG_COLOR, TCL_INDEX_NONE,
offsetof(Entry, readonlyBorder), TK_OPTION_NULL_OK,
(ClientData) DEF_ENTRY_READONLY_BG_MONO, 0},
{TK_OPTION_INT, "-repeatdelay", "repeatDelay", "RepeatDelay",
DEF_SPINBOX_REPEAT_DELAY, TCL_INDEX_NONE, offsetof(Spinbox, repeatDelay),
0, 0, 0},
{TK_OPTION_INT, "-repeatinterval", "repeatInterval", "RepeatInterval",
DEF_SPINBOX_REPEAT_INTERVAL, TCL_INDEX_NONE, offsetof(Spinbox, repeatInterval),
0, 0, 0},
{TK_OPTION_BORDER, "-selectbackground", "selectBackground", "Foreground",
DEF_ENTRY_SELECT_COLOR, TCL_INDEX_NONE, offsetof(Entry, selBorder),
0, DEF_ENTRY_SELECT_MONO, 0},
{TK_OPTION_PIXELS, "-selectborderwidth", "selectBorderWidth",
"BorderWidth", DEF_ENTRY_SELECT_BD_COLOR, TCL_INDEX_NONE,
offsetof(Entry, selBorderWidth),
0, DEF_ENTRY_SELECT_BD_MONO, 0},
{TK_OPTION_COLOR, "-selectforeground", "selectForeground", "Background",
DEF_ENTRY_SELECT_FG_COLOR, TCL_INDEX_NONE, offsetof(Entry, selFgColorPtr),
TK_OPTION_NULL_OK, DEF_ENTRY_SELECT_FG_MONO, 0},
{TK_OPTION_STRING_TABLE, "-state", "state", "State",
DEF_ENTRY_STATE, TCL_INDEX_NONE, offsetof(Entry, state),
0, stateStrings, 0},
{TK_OPTION_STRING, "-takefocus", "takeFocus", "TakeFocus",
DEF_ENTRY_TAKE_FOCUS, TCL_INDEX_NONE, offsetof(Entry, takeFocus),
TK_OPTION_NULL_OK, 0, 0},
{TK_OPTION_STRING, "-textvariable", "textVariable", "Variable",
DEF_ENTRY_TEXT_VARIABLE, TCL_INDEX_NONE, offsetof(Entry, textVarName),
TK_OPTION_NULL_OK, 0, 0},
{TK_OPTION_DOUBLE, "-to", "to", "To",
DEF_SPINBOX_TO, TCL_INDEX_NONE, offsetof(Spinbox, toValue), 0, 0, 0},
{TK_OPTION_STRING_TABLE, "-validate", "validate", "Validate",
DEF_ENTRY_VALIDATE, TCL_INDEX_NONE, offsetof(Entry, validate),
0, validateStrings, 0},
{TK_OPTION_STRING, "-validatecommand", "validateCommand","ValidateCommand",
NULL, TCL_INDEX_NONE, offsetof(Entry, validateCmd), TK_OPTION_NULL_OK, 0, 0},
{TK_OPTION_STRING, "-values", "values", "Values",
DEF_SPINBOX_VALUES, TCL_INDEX_NONE, offsetof(Spinbox, valueStr),
TK_OPTION_NULL_OK, 0, 0},
{TK_OPTION_SYNONYM, "-vcmd", NULL, NULL,
NULL, 0, TCL_INDEX_NONE, 0, "-validatecommand", 0},
{TK_OPTION_INT, "-width", "width", "Width",
DEF_ENTRY_WIDTH, TCL_INDEX_NONE, offsetof(Entry, prefWidth), 0, 0, 0},
{TK_OPTION_BOOLEAN, "-wrap", "wrap", "Wrap",
DEF_SPINBOX_WRAP, TCL_INDEX_NONE, offsetof(Spinbox, wrap), 0, 0, 0},
{TK_OPTION_STRING, "-xscrollcommand", "xScrollCommand", "ScrollCommand",
DEF_ENTRY_SCROLL_COMMAND, TCL_INDEX_NONE, offsetof(Entry, scrollCmd),
TK_OPTION_NULL_OK, 0, 0},
{TK_OPTION_END, NULL, NULL, NULL, NULL, 0, TCL_INDEX_NONE, 0, 0, 0}
};
/*
* The following tables define the entry widget commands (and sub-commands)
* and map the indexes into the string tables into enumerated types used to
* dispatch the entry widget command.
*/
static const char *const entryCmdNames[] = {
"bbox", "cget", "configure", "delete", "get", "icursor", "index",
"insert", "scan", "selection", "validate", "xview", NULL
};
enum entryCmd {
COMMAND_BBOX, COMMAND_CGET, COMMAND_CONFIGURE, COMMAND_DELETE,
COMMAND_GET, COMMAND_ICURSOR, COMMAND_INDEX, COMMAND_INSERT,
COMMAND_SCAN, COMMAND_SELECTION, COMMAND_VALIDATE, COMMAND_XVIEW
};
static const char *const selCmdNames[] = {
"adjust", "clear", "from", "present", "range", "to", NULL
};
enum selCmd {
SELECTION_ADJUST, SELECTION_CLEAR, SELECTION_FROM,
SELECTION_PRESENT, SELECTION_RANGE, SELECTION_TO
};
/*
* The following tables define the spinbox widget commands (and sub-commands)
* and map the indexes into the string tables into enumerated types used to
* dispatch the spinbox widget command.
*/
static const char *const sbCmdNames[] = {
"bbox", "cget", "configure", "delete", "get", "icursor", "identify",
"index", "insert", "invoke", "scan", "selection", "set",
"validate", "xview", NULL
};
enum sbCmd {
SB_CMD_BBOX, SB_CMD_CGET, SB_CMD_CONFIGURE, SB_CMD_DELETE,
SB_CMD_GET, SB_CMD_ICURSOR, SB_CMD_IDENTIFY, SB_CMD_INDEX,
SB_CMD_INSERT, SB_CMD_INVOKE, SB_CMD_SCAN, SB_CMD_SELECTION,
SB_CMD_SET, SB_CMD_VALIDATE, SB_CMD_XVIEW
};
static const char *const sbSelCmdNames[] = {
"adjust", "clear", "element", "from", "present", "range", "to", NULL
};
enum sbselCmd {
SB_SEL_ADJUST, SB_SEL_CLEAR, SB_SEL_ELEMENT, SB_SEL_FROM,
SB_SEL_PRESENT, SB_SEL_RANGE, SB_SEL_TO
};
/*
* Extra for selection of elements
*/
/*
* This is the string array corresponding to the enum in selelement. If you
* modify them, you must modify the strings here.
*/
static const char *const selElementNames[] = {
"none", "buttondown", "buttonup", NULL, "entry"
};
/*
* Flags for GetEntryIndex function:
*/
#define ZERO_OK 1
#define LAST_PLUS_ONE_OK 2
/*
* Forward declarations for functions defined later in this file:
*/
static int ConfigureEntry(Tcl_Interp *interp, Entry *entryPtr,
int objc, Tcl_Obj *const objv[]);
static int DeleteChars(Entry *entryPtr, TkSizeT index, TkSizeT count);
static void DestroyEntry(void *memPtr);
static void DisplayEntry(ClientData clientData);
static void EntryBlinkProc(ClientData clientData);
static void EntryCmdDeletedProc(ClientData clientData);
static void EntryComputeGeometry(Entry *entryPtr);
static void EntryEventProc(ClientData clientData,
XEvent *eventPtr);
static void EntryFocusProc(Entry *entryPtr, int gotFocus);
static TkSizeT EntryFetchSelection(ClientData clientData, TkSizeT offset,
char *buffer, TkSizeT maxBytes);
static void EntryLostSelection(ClientData clientData);
static void EventuallyRedraw(Entry *entryPtr);
static void EntryScanTo(Entry *entryPtr, int y);
static void EntrySetValue(Entry *entryPtr, const char *value);
static void EntrySelectTo(Entry *entryPtr, TkSizeT index);
static char * EntryTextVarProc(ClientData clientData,
Tcl_Interp *interp, const char *name1,
const char *name2, int flags);
static void EntryUpdateScrollbar(Entry *entryPtr);
static int EntryValidate(Entry *entryPtr, char *cmd);
static int EntryValidateChange(Entry *entryPtr, const char *change,
const char *newStr, TkSizeT index, int type);
static void ExpandPercents(Entry *entryPtr, const char *before,
const char *change, const char *newStr, TkSizeT index,
int type, Tcl_DString *dsPtr);
static int EntryValueChanged(Entry *entryPtr,
const char *newValue);
static void EntryVisibleRange(Entry *entryPtr,
double *firstPtr, double *lastPtr);
static int EntryWidgetObjCmd(ClientData clientData,
Tcl_Interp *interp, int objc,
Tcl_Obj *const objv[]);
static void EntryWorldChanged(ClientData instanceData);
static int GetEntryIndex(Tcl_Interp *interp, Entry *entryPtr,
Tcl_Obj *indexObj, TkSizeT *indexPtr);
static int InsertChars(Entry *entryPtr, TkSizeT index, const char *string);
/*
* These forward declarations are the spinbox specific ones:
*/
static int SpinboxWidgetObjCmd(ClientData clientData,
Tcl_Interp *interp, int objc,
Tcl_Obj *const objv[]);
static int GetSpinboxElement(Spinbox *sbPtr, int x, int y);
static int SpinboxInvoke(Tcl_Interp *interp, Spinbox *sbPtr,
int element);
static int ComputeFormat(Spinbox *sbPtr);
/*
* The structure below defines widget class behavior by means of functions
* that can be invoked from generic window code.
*/
static const Tk_ClassProcs entryClass = {
sizeof(Tk_ClassProcs), /* size */
EntryWorldChanged, /* worldChangedProc */
NULL, /* createProc */
NULL /* modalProc */
};
/*
*--------------------------------------------------------------
*
* Tk_EntryObjCmd --
*
* This function is invoked to process the "entry" Tcl command. See the
* user documentation for details on what it does.
*
* Results:
* A standard Tcl result.
*
* Side effects:
* See the user documentation.
*
*--------------------------------------------------------------
*/
int
Tk_EntryObjCmd(
ClientData dummy, /* NULL. */
Tcl_Interp *interp, /* Current interpreter. */
int objc, /* Number of arguments. */
Tcl_Obj *const objv[]) /* Argument objects. */
{
Entry *entryPtr;
Tk_OptionTable optionTable;
Tk_Window tkwin;
char *tmp;
(void)dummy;
if (objc < 2) {
Tcl_WrongNumArgs(interp, 1, objv, "pathName ?-option value ...?");
return TCL_ERROR;
}
tkwin = Tk_CreateWindowFromPath(interp, Tk_MainWindow(interp),
Tcl_GetString(objv[1]), NULL);
if (tkwin == NULL) {
return TCL_ERROR;
}
/*
* Create the option table for this widget class. If it has already been
* created, Tk will return the cached value.
*/
optionTable = Tk_CreateOptionTable(interp, entryOptSpec);
/*
* Initialize the fields of the structure that won't be initialized by
* ConfigureEntry, or that ConfigureEntry requires to be initialized
* already (e.g. resource pointers). Only the non-NULL/0 data must be
* initialized as memset covers the rest.
*/
entryPtr = (Entry *)ckalloc(sizeof(Entry));
memset(entryPtr, 0, sizeof(Entry));
entryPtr->tkwin = tkwin;
entryPtr->display = Tk_Display(tkwin);
entryPtr->interp = interp;
entryPtr->widgetCmd = Tcl_CreateObjCommand(interp,
Tk_PathName(entryPtr->tkwin), EntryWidgetObjCmd, entryPtr,
EntryCmdDeletedProc);
entryPtr->optionTable = optionTable;
entryPtr->type = TK_ENTRY;
tmp = (char *)ckalloc(1);
tmp[0] = '\0';
entryPtr->string = tmp;
entryPtr->selectFirst = TCL_INDEX_NONE;
entryPtr->selectLast = TCL_INDEX_NONE;
entryPtr->cursor = NULL;
entryPtr->exportSelection = 1;
entryPtr->justify = TK_JUSTIFY_LEFT;
entryPtr->relief = TK_RELIEF_FLAT;
entryPtr->state = STATE_NORMAL;
entryPtr->displayString = entryPtr->string;
entryPtr->inset = XPAD;
entryPtr->textGC = NULL;
entryPtr->selTextGC = NULL;
entryPtr->highlightGC = NULL;
entryPtr->avgWidth = 1;
entryPtr->validate = VALIDATE_NONE;
entryPtr->placeholderGC = NULL;
/*
* Keep a hold of the associated tkwin until we destroy the entry,
* otherwise Tk might free it while we still need it.
*/
Tcl_Preserve(entryPtr->tkwin);
Tk_SetClass(entryPtr->tkwin, "Entry");
Tk_SetClassProcs(entryPtr->tkwin, &entryClass, entryPtr);
Tk_CreateEventHandler(entryPtr->tkwin,
ExposureMask|StructureNotifyMask|FocusChangeMask,
EntryEventProc, entryPtr);
Tk_CreateSelHandler(entryPtr->tkwin, XA_PRIMARY, XA_STRING,
EntryFetchSelection, entryPtr, XA_STRING);
if ((Tk_InitOptions(interp, entryPtr, optionTable, tkwin)
!= TCL_OK) ||
(ConfigureEntry(interp, entryPtr, objc-2, objv+2) != TCL_OK)) {
Tk_DestroyWindow(entryPtr->tkwin);
return TCL_ERROR;
}
Tcl_SetObjResult(interp, Tk_NewWindowObj(entryPtr->tkwin));
return TCL_OK;
}
/*
*--------------------------------------------------------------
*
* EntryWidgetObjCmd --
*
* This function is invoked to process the Tcl command that corresponds
* to a widget managed by this module. See the user documentation for
* details on what it does.
*
* Results:
* A standard Tcl result.
*
* Side effects:
* See the user documentation.
*
*--------------------------------------------------------------
*/
static int
EntryWidgetObjCmd(
ClientData clientData, /* Information about entry widget. */
Tcl_Interp *interp, /* Current interpreter. */
int objc, /* Number of arguments. */
Tcl_Obj *const objv[]) /* Argument objects. */
{
Entry *entryPtr = (Entry *)clientData;
int cmdIndex, selIndex, result;
Tcl_Obj *objPtr;
if (objc < 2) {
Tcl_WrongNumArgs(interp, 1, objv, "option ?arg ...?");
return TCL_ERROR;
}
/*
* Parse the widget command by looking up the second token in the list of
* valid command names.
*/
result = Tcl_GetIndexFromObj(interp, objv[1], entryCmdNames, "option", 0,
&cmdIndex);
if (result != TCL_OK) {
return result;
}
Tcl_Preserve(entryPtr);
switch ((enum entryCmd) cmdIndex) {
case COMMAND_BBOX: {
TkSizeT index;
int x, y, width, height;
Tcl_Obj *bbox[4];
if (objc != 3) {
Tcl_WrongNumArgs(interp, 2, objv, "index");
goto error;
}
if (GetEntryIndex(interp, entryPtr, objv[2],
&index) != TCL_OK) {
goto error;
}
if ((index == entryPtr->numChars) && (index + 1 > 1)) {
index--;
}
Tk_CharBbox(entryPtr->textLayout, index, &x, &y, &width, &height);
bbox[0] = Tcl_NewWideIntObj(x + entryPtr->layoutX);
bbox[1] = Tcl_NewWideIntObj(y + entryPtr->layoutY);
bbox[2] = Tcl_NewWideIntObj(width);
bbox[3] = Tcl_NewWideIntObj(height);
Tcl_SetObjResult(interp, Tcl_NewListObj(4, bbox));
break;
}
case COMMAND_CGET:
if (objc != 3) {
Tcl_WrongNumArgs(interp, 2, objv, "option");
goto error;
}
objPtr = Tk_GetOptionValue(interp, entryPtr,
entryPtr->optionTable, objv[2], entryPtr->tkwin);
if (objPtr == NULL) {
goto error;
}
Tcl_SetObjResult(interp, objPtr);
break;
case COMMAND_CONFIGURE:
if (objc <= 3) {
objPtr = Tk_GetOptionInfo(interp, entryPtr,
entryPtr->optionTable,
(objc == 3) ? objv[2] : NULL,
entryPtr->tkwin);
if (objPtr == NULL) {
goto error;
}
Tcl_SetObjResult(interp, objPtr);
} else {
result = ConfigureEntry(interp, entryPtr, objc-2, objv+2);
}
break;
case COMMAND_DELETE: {
TkSizeT first, last;
int code;
if ((objc < 3) || (objc > 4)) {
Tcl_WrongNumArgs(interp, 2, objv, "firstIndex ?lastIndex?");
goto error;
}
if (GetEntryIndex(interp, entryPtr, objv[2],
&first) != TCL_OK) {
goto error;
}
if (objc == 3) {
last = first + 1;
} else if (GetEntryIndex(interp, entryPtr, objv[3],
&last) != TCL_OK) {
goto error;
}
if ((last + 1 >= first + 1 ) && (entryPtr->state == STATE_NORMAL)) {
code = DeleteChars(entryPtr, first, last - first);
if (code != TCL_OK) {
goto error;
}
}
break;
}
case COMMAND_GET:
if (objc != 2) {
Tcl_WrongNumArgs(interp, 2, objv, NULL);
goto error;
}
Tcl_SetObjResult(interp, Tcl_NewStringObj(entryPtr->string, -1));
break;
case COMMAND_ICURSOR:
if (objc != 3) {
Tcl_WrongNumArgs(interp, 2, objv, "pos");
goto error;
}
if (GetEntryIndex(interp, entryPtr, objv[2],
&entryPtr->insertPos) != TCL_OK) {
goto error;
}
EventuallyRedraw(entryPtr);
break;
case COMMAND_INDEX: {
TkSizeT index;
if (objc != 3) {
Tcl_WrongNumArgs(interp, 2, objv, "string");
goto error;
}
if (GetEntryIndex(interp, entryPtr, objv[2],
&index) != TCL_OK) {
goto error;
}
Tcl_SetObjResult(interp, TkNewIndexObj(index));
break;
}
case COMMAND_INSERT: {
TkSizeT index;
int code;
if (objc != 4) {
Tcl_WrongNumArgs(interp, 2, objv, "index text");
goto error;
}
if (GetEntryIndex(interp, entryPtr, objv[2],
&index) != TCL_OK) {
goto error;
}
if (entryPtr->state == STATE_NORMAL) {
code = InsertChars(entryPtr, index, Tcl_GetString(objv[3]));
if (code != TCL_OK) {
goto error;
}
}
break;
}
case COMMAND_SCAN: {
int x;
const char *minorCmd;
if (objc != 4) {
Tcl_WrongNumArgs(interp, 2, objv, "mark|dragto x");
goto error;
}
if (Tcl_GetIntFromObj(interp, objv[3], &x) != TCL_OK) {
goto error;
}
minorCmd = Tcl_GetString(objv[2]);
if (minorCmd[0] == 'm'
&& (strncmp(minorCmd, "mark", strlen(minorCmd)) == 0)) {
entryPtr->scanMarkX = x;
entryPtr->scanMarkIndex = entryPtr->leftIndex;
} else if ((minorCmd[0] == 'd')
&& (strncmp(minorCmd, "dragto", strlen(minorCmd)) == 0)) {
EntryScanTo(entryPtr, x);
} else {
Tcl_SetObjResult(interp, Tcl_ObjPrintf(
"bad scan option \"%s\": must be mark or dragto",
minorCmd));
Tcl_SetErrorCode(interp, "TCL", "LOOKUP", "INDEX", "scan option",
minorCmd, NULL);
goto error;
}
break;
}
case COMMAND_SELECTION: {
TkSizeT index, index2;
if (objc < 3) {
Tcl_WrongNumArgs(interp, 2, objv, "option ?index?");
goto error;
}
/*
* Parse the selection sub-command, using the command table
* "selCmdNames" defined above.
*/
result = Tcl_GetIndexFromObj(interp, objv[2], selCmdNames,
"selection option", 0, &selIndex);
if (result != TCL_OK) {
goto error;
}
/*
* Disabled entries don't allow the selection to be modified, but
* 'selection present' must return a boolean.
*/
if ((entryPtr->state == STATE_DISABLED)
&& (selIndex != SELECTION_PRESENT)) {
goto done;
}
switch (selIndex) {
case SELECTION_ADJUST:
if (objc != 4) {
Tcl_WrongNumArgs(interp, 3, objv, "index");
goto error;
}
if (GetEntryIndex(interp, entryPtr,
objv[3], &index) != TCL_OK) {
goto error;
}
if (entryPtr->selectFirst != TCL_INDEX_NONE) {
TkSizeT half1, half2;
half1 = (entryPtr->selectFirst + entryPtr->selectLast)/2;
half2 = (entryPtr->selectFirst + entryPtr->selectLast + 1)/2;
if (index + 1 < half1 + 1 ) {
entryPtr->selectAnchor = entryPtr->selectLast;
} else if (index + 1 > half2 + 1 ) {
entryPtr->selectAnchor = entryPtr->selectFirst;
} else {
/*
* We're at about the halfway point in the selection; just
* keep the existing anchor.
*/
}
}
EntrySelectTo(entryPtr, index);
break;
case SELECTION_CLEAR:
if (objc != 3) {
Tcl_WrongNumArgs(interp, 3, objv, NULL);
goto error;
}
if (entryPtr->selectFirst != TCL_INDEX_NONE) {
entryPtr->selectFirst = TCL_INDEX_NONE;
entryPtr->selectLast = TCL_INDEX_NONE;
EventuallyRedraw(entryPtr);
}
goto done;
case SELECTION_FROM:
if (objc != 4) {
Tcl_WrongNumArgs(interp, 3, objv, "index");
goto error;
}
if (GetEntryIndex(interp, entryPtr,
objv[3], &index) != TCL_OK) {
goto error;
}
entryPtr->selectAnchor = index;
break;
case SELECTION_PRESENT:
if (objc != 3) {
Tcl_WrongNumArgs(interp, 3, objv, NULL);
goto error;
}
Tcl_SetObjResult(interp,
Tcl_NewWideIntObj(entryPtr->selectFirst != TCL_INDEX_NONE));
goto done;
case SELECTION_RANGE:
if (objc != 5) {
Tcl_WrongNumArgs(interp, 3, objv, "start end");
goto error;
}
if (GetEntryIndex(interp, entryPtr, objv[3],
&index) != TCL_OK) {
goto error;
}
if (GetEntryIndex(interp, entryPtr, objv[4],
&index2) != TCL_OK) {
goto error;
}
if (index + 1 >= index2 + 1 ) {
entryPtr->selectFirst = TCL_INDEX_NONE;
entryPtr->selectLast = TCL_INDEX_NONE;
} else {
entryPtr->selectFirst = index;
entryPtr->selectLast = index2;
}
if (!(entryPtr->flags & GOT_SELECTION)
&& (entryPtr->exportSelection)
&& (!Tcl_IsSafe(entryPtr->interp))) {
Tk_OwnSelection(entryPtr->tkwin, XA_PRIMARY,
EntryLostSelection, entryPtr);
entryPtr->flags |= GOT_SELECTION;
}
EventuallyRedraw(entryPtr);
break;
case SELECTION_TO:
if (objc != 4) {
Tcl_WrongNumArgs(interp, 3, objv, "index");
goto error;
}
if (GetEntryIndex(interp, entryPtr,
objv[3], &index) != TCL_OK) {
goto error;
}
EntrySelectTo(entryPtr, index);
break;
}
break;
}
case COMMAND_VALIDATE: {
int code;
if (objc != 2) {
Tcl_WrongNumArgs(interp, 2, objv, NULL);
goto error;
}
selIndex = entryPtr->validate;
entryPtr->validate = VALIDATE_ALL;
code = EntryValidateChange(entryPtr, NULL, entryPtr->string,
-1, VALIDATE_FORCED);
if (entryPtr->validate != VALIDATE_NONE) {
entryPtr->validate = selIndex;
}
Tcl_SetObjResult(interp, Tcl_NewBooleanObj(code == TCL_OK));
break;
}
case COMMAND_XVIEW: {
TkSizeT index;
if (objc == 2) {
double first, last;
Tcl_Obj *span[2];
EntryVisibleRange(entryPtr, &first, &last);
span[0] = Tcl_NewDoubleObj(first);
span[1] = Tcl_NewDoubleObj(last);
Tcl_SetObjResult(interp, Tcl_NewListObj(2, span));
goto done;
} else if (objc == 3) {
if (GetEntryIndex(interp, entryPtr, objv[2],
&index) != TCL_OK) {
goto error;
}
} else {
double fraction;
int count;
index = entryPtr->leftIndex;
switch (Tk_GetScrollInfoObj(interp, objc, objv, &fraction,
&count)) {
case TK_SCROLL_ERROR:
goto error;
case TK_SCROLL_MOVETO:
index = (int) ((fraction * entryPtr->numChars) + 0.5);
break;
case TK_SCROLL_PAGES: {
int charsPerPage;
charsPerPage = ((Tk_Width(entryPtr->tkwin)
- 2 * entryPtr->inset) / entryPtr->avgWidth) - 2;
if (charsPerPage < 1) {
charsPerPage = 1;
}
index += count * charsPerPage;
break;
}
case TK_SCROLL_UNITS:
index += count;
break;
}
}
if (index + 1 >= entryPtr->numChars + 1) {
index = entryPtr->numChars - 1;
}
if ((int)index < 0) {
index = 0;
}
entryPtr->leftIndex = index;
entryPtr->flags |= UPDATE_SCROLLBAR;
EntryComputeGeometry(entryPtr);
EventuallyRedraw(entryPtr);
break;
}
}
done:
Tcl_Release(entryPtr);
return result;
error:
Tcl_Release(entryPtr);
return TCL_ERROR;
}
/*
*----------------------------------------------------------------------
*
* DestroyEntry --
*
* This function is invoked by Tcl_EventuallyFree or Tcl_Release to clean
* up the internal structure of an entry at a safe time (when no-one is
* using it anymore).
*
* Results:
* None.
*
* Side effects:
* Everything associated with the entry is freed up.
*
*----------------------------------------------------------------------
*/
static void
DestroyEntry(
void *memPtr) /* Info about entry widget. */
{
Entry *entryPtr = (Entry *)memPtr;
/*
* Free up all the stuff that requires special handling, then let
* Tk_FreeOptions handle all the standard option-related stuff.
*/
ckfree((char *)entryPtr->string);
if (entryPtr->textVarName != NULL) {
Tcl_UntraceVar2(entryPtr->interp, entryPtr->textVarName,
NULL, TCL_GLOBAL_ONLY|TCL_TRACE_WRITES|TCL_TRACE_UNSETS,
EntryTextVarProc, entryPtr);
entryPtr->flags &= ~ENTRY_VAR_TRACED;
}
if (entryPtr->textGC != NULL) {
Tk_FreeGC(entryPtr->display, entryPtr->textGC);
}
if (entryPtr->selTextGC != NULL) {
Tk_FreeGC(entryPtr->display, entryPtr->selTextGC);
}
Tcl_DeleteTimerHandler(entryPtr->insertBlinkHandler);
if (entryPtr->displayString != entryPtr->string) {
ckfree((char *)entryPtr->displayString);
}
if (entryPtr->type == TK_SPINBOX) {
Spinbox *sbPtr = (Spinbox *) entryPtr;
if (sbPtr->listObj != NULL) {
Tcl_DecrRefCount(sbPtr->listObj);
sbPtr->listObj = NULL;
}
if (sbPtr->formatBuf) {
ckfree(sbPtr->formatBuf);
}
}
Tk_FreeTextLayout(entryPtr->textLayout);
Tk_FreeConfigOptions((char *) entryPtr, entryPtr->optionTable,
entryPtr->tkwin);
Tcl_Release(entryPtr->tkwin);
entryPtr->tkwin = NULL;
ckfree(entryPtr);
}
/*
*----------------------------------------------------------------------
*
* ConfigureEntry --
*
* This function is called to process an argv/argc list, plus the Tk
* option database, in order to configure (or reconfigure) an entry
* widget.
*
* Results:
* The return value is a standard Tcl result. If TCL_ERROR is returned,
* then the interp's result contains an error message.
*
* Side effects:
* Configuration information, such as colors, border width, etc. get set
* for entryPtr; old resources get freed, if there were any.
*
*----------------------------------------------------------------------
*/
static int
ConfigureEntry(
Tcl_Interp *interp, /* Used for error reporting. */
Entry *entryPtr, /* Information about widget; may or may not
* already have values for some fields. */
int objc, /* Number of valid entries in argv. */
Tcl_Obj *const objv[]) /* Argument objects. */
{
Tk_SavedOptions savedOptions;
Tk_3DBorder border;
Tcl_Obj *errorResult = NULL;
Spinbox *sbPtr = (Spinbox *) entryPtr;
/* Only used when this widget is of type
* TK_SPINBOX */
char *oldValues = NULL;
char *oldFormat = NULL;
int error;
int oldExport = 0;
int valuesChanged = 0;
double oldFrom = 0.0;
double oldTo = 0.0;
int code;
/*
* Eliminate any existing trace on a variable monitored by the entry.
*/
if ((entryPtr->textVarName != NULL)
&& (entryPtr->flags & ENTRY_VAR_TRACED)) {
Tcl_UntraceVar2(interp, entryPtr->textVarName, NULL,
TCL_GLOBAL_ONLY|TCL_TRACE_WRITES|TCL_TRACE_UNSETS,
EntryTextVarProc, entryPtr);
entryPtr->flags &= ~ENTRY_VAR_TRACED;
}
/*
* Store old values that we need to effect certain behavior if they change
* value.
*/
oldExport = (entryPtr->exportSelection) && (!Tcl_IsSafe(entryPtr->interp));
if (entryPtr->type == TK_SPINBOX) {
oldValues = sbPtr->valueStr;
oldFormat = sbPtr->reqFormat;
oldFrom = sbPtr->fromValue;
oldTo = sbPtr->toValue;
}
for (error = 0; error <= 1; error++) {
if (!error) {
/*
* First pass: set options to new values.
*/
if (Tk_SetOptions(interp, entryPtr,
entryPtr->optionTable, objc, objv,
entryPtr->tkwin, &savedOptions, NULL) != TCL_OK) {
continue;
}
} else {
/*
* Second pass: restore options to old values.
*/
errorResult = Tcl_GetObjResult(interp);
Tcl_IncrRefCount(errorResult);
Tk_RestoreSavedOptions(&savedOptions);
}
/*
* A few other options also need special processing, such as parsing
* the geometry and setting the background from a 3-D border.
*/
if ((entryPtr->state == STATE_DISABLED) &&
(entryPtr->disabledBorder != NULL)) {
border = entryPtr->disabledBorder;
} else if ((entryPtr->state == STATE_READONLY) &&
(entryPtr->readonlyBorder != NULL)) {
border = entryPtr->readonlyBorder;
} else {
border = entryPtr->normalBorder;
}
Tk_SetBackgroundFromBorder(entryPtr->tkwin, border);
if (entryPtr->insertWidth <= 0) {
entryPtr->insertWidth = 2;
}
if (entryPtr->insertBorderWidth > entryPtr->insertWidth/2) {
entryPtr->insertBorderWidth = entryPtr->insertWidth/2;
}
if (entryPtr->type == TK_SPINBOX) {
if (sbPtr->fromValue > sbPtr->toValue) {
/*
* Swap -from and -to values.
*/
double tmpFromTo = sbPtr->fromValue;
sbPtr->fromValue = sbPtr->toValue;
sbPtr->toValue = tmpFromTo;
}
if (sbPtr->reqFormat && (oldFormat != sbPtr->reqFormat)) {
/*
* Make sure that the given format is somewhat correct, and
* calculate the minimum space we'll need for the values as
* strings.
*/
int min, max;
size_t formatLen, formatSpace = TCL_DOUBLE_SPACE;
char fbuf[4], *fmt = sbPtr->reqFormat;
formatLen = strlen(fmt);
if ((fmt[0] != '%') || (fmt[formatLen-1] != 'f')) {
badFormatOpt:
Tcl_SetObjResult(interp, Tcl_ObjPrintf(
"bad spinbox format specifier \"%s\"",
sbPtr->reqFormat));
Tcl_SetErrorCode(interp, "TK", "SPINBOX", "FORMAT_SANITY",
NULL);
continue;
}
if ((sscanf(fmt, "%%%d.%d%[f]", &min, &max, fbuf) == 3)
&& (max >= 0)) {
formatSpace = min + max + 1;
} else if (((sscanf(fmt, "%%.%d%[f]", &min, fbuf) == 2)
|| (sscanf(fmt, "%%%d%[f]", &min, fbuf) == 2)
|| (sscanf(fmt, "%%%d.%[f]", &min, fbuf) == 2))
&& (min >= 0)) {
formatSpace = min + 1;
} else {
goto badFormatOpt;
}
if (formatSpace < TCL_DOUBLE_SPACE) {
formatSpace = TCL_DOUBLE_SPACE;
}
sbPtr->formatBuf = (char *)ckrealloc(sbPtr->formatBuf, formatSpace);
/*
* We perturb the value of oldFrom to allow us to go into the
* branch below that will reformat the displayed value.
*/
oldFrom = sbPtr->fromValue - 1;
}
/*
* See if we have to rearrange our listObj data.
*/
if (oldValues != sbPtr->valueStr) {
if (sbPtr->listObj != NULL) {
Tcl_DecrRefCount(sbPtr->listObj);
}
sbPtr->listObj = NULL;
if (sbPtr->valueStr != NULL) {
Tcl_Obj *newObjPtr;
int nelems;
newObjPtr = Tcl_NewStringObj(sbPtr->valueStr, -1);
if (Tcl_ListObjLength(interp, newObjPtr, &nelems)
!= TCL_OK) {
valuesChanged = -1;
continue;
}
sbPtr->listObj = newObjPtr;
Tcl_IncrRefCount(sbPtr->listObj);
sbPtr->nElements = nelems;
sbPtr->eIndex = 0;
valuesChanged++;
}
}
}
/*
* Restart the cursor timing sequence in case the on-time or off-time
* just changed. Set validate temporarily to none, so the configure
* doesn't cause it to be triggered.
*/
if (entryPtr->flags & GOT_FOCUS) {
int validate = entryPtr->validate;
entryPtr->validate = VALIDATE_NONE;
EntryFocusProc(entryPtr, 1);
entryPtr->validate = validate;
}
/*
* Claim the selection if we've suddenly started exporting it.
*/
if (entryPtr->exportSelection && (!oldExport)
&& (!Tcl_IsSafe(entryPtr->interp))
&& (entryPtr->selectFirst != TCL_INDEX_NONE)
&& !(entryPtr->flags & GOT_SELECTION)) {
Tk_OwnSelection(entryPtr->tkwin, XA_PRIMARY, EntryLostSelection,
entryPtr);
entryPtr->flags |= GOT_SELECTION;
}
/*
* Recompute the window's geometry and arrange for it to be
* redisplayed.
*/
Tk_SetInternalBorder(entryPtr->tkwin,
entryPtr->borderWidth + entryPtr->highlightWidth);
if (entryPtr->highlightWidth <= 0) {
entryPtr->highlightWidth = 0;
}
entryPtr->inset = entryPtr->highlightWidth
+ entryPtr->borderWidth + XPAD;
break;
}
if (!error) {
Tk_FreeSavedOptions(&savedOptions);
}
/*
* If the entry is tied to the value of a variable, create the variable if
* it doesn't exist, and set the entry's value from the variable's value.
*/
if (entryPtr->textVarName != NULL) {
const char *value;
value = Tcl_GetVar2(interp, entryPtr->textVarName, NULL, TCL_GLOBAL_ONLY);
if (value == NULL) {
/*
* Since any trace on the textvariable was eliminated above,
* the only possible reason for EntryValueChanged to return
* an error is that the textvariable lives in a namespace
* that does not (yet) exist. Indeed, namespaces are not
* automatically created as needed. Don't trap this error
* here, better do it below when attempting to trace the
* variable.
*/
EntryValueChanged(entryPtr, NULL);
} else {
EntrySetValue(entryPtr, value);
}
}
if (entryPtr->type == TK_SPINBOX) {
ComputeFormat(sbPtr);
if (valuesChanged > 0) {
Tcl_Obj *objPtr;
/*
* No check for error return, because there shouldn't be one given
* the check for valid list above.
*/
Tcl_ListObjIndex(interp, sbPtr->listObj, 0, &objPtr);
/*
* No check for error return here as well, because any possible
* error will be trapped below when attempting tracing.
*/
EntryValueChanged(entryPtr, Tcl_GetString(objPtr));
} else if ((sbPtr->valueStr == NULL)
&& !DOUBLES_EQ(sbPtr->fromValue, sbPtr->toValue)
&& (!DOUBLES_EQ(sbPtr->fromValue, oldFrom)
|| !DOUBLES_EQ(sbPtr->toValue, oldTo))) {
/*
* If the valueStr is empty and -from && -to are specified, check
* to see if the current string is within the range. If not, it
* will be constrained to the nearest edge. If the current string
* isn't a double value, we set it to -from.
*/
double dvalue;
if (sscanf(entryPtr->string, "%lf", &dvalue) <= 0) {
/* Scan failure */
dvalue = sbPtr->fromValue;
} else if (dvalue > sbPtr->toValue) {
dvalue = sbPtr->toValue;
} else if (dvalue < sbPtr->fromValue) {
dvalue = sbPtr->fromValue;
}
sprintf(sbPtr->formatBuf, sbPtr->valueFormat, dvalue);
/*
* No check for error return here as well, because any possible
* error will be trapped below when attempting tracing.
*/
EntryValueChanged(entryPtr, sbPtr->formatBuf);
}
}
/*
* Set up a trace on the variable's value after we've possibly constrained
* the value according to new -from/-to values.
*/
if ((entryPtr->textVarName != NULL)
&& !(entryPtr->flags & ENTRY_VAR_TRACED)) {
code = Tcl_TraceVar2(interp, entryPtr->textVarName,
NULL, TCL_GLOBAL_ONLY|TCL_TRACE_WRITES|TCL_TRACE_UNSETS,
EntryTextVarProc, entryPtr);
if (code != TCL_OK) {
return TCL_ERROR;
}
entryPtr->flags |= ENTRY_VAR_TRACED;
}
EntryWorldChanged(entryPtr);
if (error) {
Tcl_SetObjResult(interp, errorResult);
Tcl_DecrRefCount(errorResult);
return TCL_ERROR;
} else {
return TCL_OK;
}
}
/*
*---------------------------------------------------------------------------
*
* EntryWorldChanged --
*
* This function is called when the world has changed in some way and the
* widget needs to recompute all its graphics contexts and determine its
* new geometry.
*
* Results:
* None.
*
* Side effects:
* Entry will be relayed out and redisplayed.
*
*---------------------------------------------------------------------------
*/
static void
EntryWorldChanged(
ClientData instanceData) /* Information about widget. */
{
XGCValues gcValues;
GC gc = NULL;
unsigned long mask;
Tk_3DBorder border;
XColor *colorPtr;
Entry *entryPtr = (Entry *)instanceData;
entryPtr->avgWidth = Tk_TextWidth(entryPtr->tkfont, "0", 1);
if (entryPtr->avgWidth == 0) {
entryPtr->avgWidth = 1;
}
if (entryPtr->type == TK_SPINBOX) {
/*
* Compute the button width for a spinbox
*/
entryPtr->xWidth = entryPtr->avgWidth + 2 * (1+XPAD);
if (entryPtr->xWidth < 11) {
entryPtr->xWidth = 11; /* we want a min visible size */
}
}
/*
* Default background and foreground are from the normal state. In a
* disabled state, both of those may be overridden; in the readonly state,
* the background may be overridden.
*/
border = entryPtr->normalBorder;
colorPtr = entryPtr->fgColorPtr;
switch (entryPtr->state) {
case STATE_DISABLED:
if (entryPtr->disabledBorder != NULL) {
border = entryPtr->disabledBorder;
}
if (entryPtr->dfgColorPtr != NULL) {
colorPtr = entryPtr->dfgColorPtr;
}
break;
case STATE_READONLY:
if (entryPtr->readonlyBorder != NULL) {
border = entryPtr->readonlyBorder;
}
break;
}
Tk_SetBackgroundFromBorder(entryPtr->tkwin, border);
gcValues.foreground = colorPtr->pixel;
gcValues.font = Tk_FontId(entryPtr->tkfont);
gcValues.graphics_exposures = False;
mask = GCForeground | GCFont | GCGraphicsExposures;
gc = Tk_GetGC(entryPtr->tkwin, mask, &gcValues);
if (entryPtr->textGC != NULL) {
Tk_FreeGC(entryPtr->display, entryPtr->textGC);
}
entryPtr->textGC = gc;
if (entryPtr->placeholderColorPtr != NULL) {
gcValues.foreground = entryPtr->placeholderColorPtr->pixel;
}
mask = GCForeground | GCFont | GCGraphicsExposures;
gc = Tk_GetGC(entryPtr->tkwin, mask, &gcValues);
if (entryPtr->placeholderGC != NULL) {
Tk_FreeGC(entryPtr->display, entryPtr->placeholderGC);
}
entryPtr->placeholderGC = gc;
if (entryPtr->selFgColorPtr != NULL) {
gcValues.foreground = entryPtr->selFgColorPtr->pixel;
} else {
gcValues.foreground = colorPtr->pixel;
}
gcValues.font = Tk_FontId(entryPtr->tkfont);
mask = GCForeground | GCFont;
gc = Tk_GetGC(entryPtr->tkwin, mask, &gcValues);
if (entryPtr->selTextGC != NULL) {
Tk_FreeGC(entryPtr->display, entryPtr->selTextGC);
}
entryPtr->selTextGC = gc;
/*
* Recompute the window's geometry and arrange for it to be redisplayed.
*/
EntryComputeGeometry(entryPtr);
entryPtr->flags |= UPDATE_SCROLLBAR;
EventuallyRedraw(entryPtr);
}
#ifndef MAC_OSX_TK
/*
*--------------------------------------------------------------
*
* TkpDrawEntryBorderAndFocus --
*
* Stub function for Tk on platforms other than Aqua
* (Windows and X11), which do not draw native entry borders.
* See macosx/tkMacOSXEntry.c for function definition in Tk Aqua.
*
* Results:
* Returns 0.
*
* Side effects:
* None.
*
*--------------------------------------------------------------
*/
int
TkpDrawEntryBorderAndFocus(
Entry *entryPtr,
Drawable pixmap,
int isSpinbox)
{
(void)entryPtr;
(void)pixmap;
(void)isSpinbox;
return 0;
}
/*
*--------------------------------------------------------------
*
* TkpDrawSpinboxButtons --
*
* Stub function for Tk on platforms other than Aqua
* (Windows and X11), which do not draw native spinbox buttons.
* See macosx/tkMacOSXEntry.c for function definition in Tk Aqua.
*
* Results:
* Returns 0.
*
* Side effects:
* None.
*
*--------------------------------------------------------------
*/
int
TkpDrawSpinboxButtons(
Spinbox *sbPtr,
Pixmap pixmap)
{
(void)sbPtr;
(void)pixmap;
return 0;
}
#endif /* Not MAC_OSX_TK */
/*
*--------------------------------------------------------------
*
* DisplayEntry --
*
* This function redraws the contents of an entry window.
*
* Results:
* None.
*
* Side effects:
* Information appears on the screen.
*
*--------------------------------------------------------------
*/
static void
DisplayEntry(
ClientData clientData) /* Information about window. */
{
Entry *entryPtr = (Entry *)clientData;
Tk_Window tkwin = entryPtr->tkwin;
int baseY, selStartX, selEndX, cursorX;
int showSelection, xBound;
Tk_FontMetrics fm;
Pixmap pixmap;
Tk_3DBorder border;
entryPtr->flags &= ~REDRAW_PENDING;
if ((entryPtr->flags & ENTRY_DELETED) || !Tk_IsMapped(tkwin)) {
return;
}
Tk_GetFontMetrics(entryPtr->tkfont, &fm);
/*
* Update the scrollbar if that's needed.
*/
if (entryPtr->flags & UPDATE_SCROLLBAR) {
entryPtr->flags &= ~UPDATE_SCROLLBAR;
/*
* Preserve/Release because updating the scrollbar can have the
* side-effect of destroying or unmapping the entry widget.
*/
Tcl_Preserve(entryPtr);
EntryUpdateScrollbar(entryPtr);
if ((entryPtr->flags & ENTRY_DELETED) || !Tk_IsMapped(tkwin)) {
Tcl_Release(entryPtr);
return;
}
Tcl_Release(entryPtr);
}
#ifndef TK_NO_DOUBLE_BUFFERING
/*
* In order to avoid screen flashes, this function redraws the textual
* area of the entry into off-screen memory, then copies it back on-screen
* in a single operation. This means there's no point in time where the
* on-screen image has been cleared.
*/
pixmap = Tk_GetPixmap(entryPtr->display, Tk_WindowId(tkwin),
Tk_Width(tkwin), Tk_Height(tkwin), Tk_Depth(tkwin));
#else
pixmap = Tk_WindowId(tkwin);
#endif /* TK_NO_DOUBLE_BUFFERING */
/*
* Compute x-coordinate of the pixel just after last visible one, plus
* vertical position of baseline of text.
*/
xBound = Tk_Width(tkwin) - entryPtr->inset - entryPtr->xWidth;
baseY = (Tk_Height(tkwin) + fm.ascent - fm.descent) / 2;
/*
* Hide the selection whenever we don't have the focus, unless we
* always want to show selection.
*/
if (Tk_AlwaysShowSelection(entryPtr->tkwin)) {
showSelection = 1;
} else {
showSelection = (entryPtr->flags & GOT_FOCUS);
}
/*
* Draw the background in three layers. From bottom to top the layers are:
* normal background, selection background, and insertion cursor
* background.
*/
if ((entryPtr->state == STATE_DISABLED) &&
(entryPtr->disabledBorder != NULL)) {
border = entryPtr->disabledBorder;
} else if ((entryPtr->state == STATE_READONLY) &&
(entryPtr->readonlyBorder != NULL)) {
border = entryPtr->readonlyBorder;
} else {
border = entryPtr->normalBorder;
}
Tk_Fill3DRectangle(tkwin, pixmap, border,
0, 0, Tk_Width(tkwin), Tk_Height(tkwin), 0, TK_RELIEF_FLAT);
if (showSelection && (entryPtr->state != STATE_DISABLED)
&& (entryPtr->selectLast + 1 > entryPtr->leftIndex + 1)) {
if (entryPtr->selectFirst <= entryPtr->leftIndex) {
selStartX = entryPtr->leftX;
} else {
Tk_CharBbox(entryPtr->textLayout, entryPtr->selectFirst,
&selStartX, NULL, NULL, NULL);
selStartX += entryPtr->layoutX;
}
if ((selStartX - entryPtr->selBorderWidth) < xBound) {
Tk_CharBbox(entryPtr->textLayout, entryPtr->selectLast,
&selEndX, NULL, NULL, NULL);
selEndX += entryPtr->layoutX;
Tk_Fill3DRectangle(tkwin, pixmap, entryPtr->selBorder,
selStartX - entryPtr->selBorderWidth,
baseY - fm.ascent - entryPtr->selBorderWidth,
(selEndX - selStartX) + 2*entryPtr->selBorderWidth,
(fm.ascent + fm.descent) + 2*entryPtr->selBorderWidth,
entryPtr->selBorderWidth,
#ifndef MAC_OSX_TK
TK_RELIEF_RAISED
#else
MAC_OSX_ENTRY_SELECT_RELIEF
#endif
);
}
}
/*
* Draw a special background for the insertion cursor, overriding even the
* selection background. As a special hack to keep the cursor visible when
* the insertion cursor color is the same as the color for selected text
* (e.g., on mono displays), write background in the cursor area (instead
* of nothing) when the cursor isn't on. Otherwise the selection would
* hide the cursor.
*/
if ((entryPtr->state == STATE_NORMAL) && (entryPtr->flags & GOT_FOCUS)) {
Tk_CharBbox(entryPtr->textLayout, entryPtr->insertPos, &cursorX, NULL,
NULL, NULL);
cursorX += entryPtr->layoutX;
cursorX -= (entryPtr->insertWidth == 1) ? 1 : (entryPtr->insertWidth)/2;
Tk_SetCaretPos(entryPtr->tkwin, cursorX, baseY - fm.ascent,
fm.ascent + fm.descent);
if ((entryPtr->insertPos + 1 >= entryPtr->leftIndex + 1) && cursorX < xBound) {
if (entryPtr->flags & CURSOR_ON) {
Tk_Fill3DRectangle(tkwin, pixmap, entryPtr->insertBorder,
cursorX, baseY - fm.ascent, entryPtr->insertWidth,
fm.ascent + fm.descent, entryPtr->insertBorderWidth,
TK_RELIEF_RAISED);
} else if (entryPtr->insertBorder == entryPtr->selBorder) {
Tk_Fill3DRectangle(tkwin, pixmap, border, cursorX,
baseY - fm.ascent, entryPtr->insertWidth,
fm.ascent + fm.descent, 0, TK_RELIEF_FLAT);
}
}
}
if ((entryPtr->numChars == 0) && (entryPtr->placeholderChars != 0)) {
/*
* Draw the placeholder text.
*/
Tk_DrawTextLayout(entryPtr->display, pixmap, entryPtr->placeholderGC,
entryPtr->placeholderLayout, entryPtr->placeholderX, entryPtr->layoutY,
entryPtr->placeholderLeftIndex, entryPtr->placeholderChars);
} else {
if (showSelection && (entryPtr->state != STATE_DISABLED)
&& (entryPtr->selTextGC != entryPtr->textGC)
&& (entryPtr->selectFirst + 1 < entryPtr->selectLast + 1)) {
/*
* Draw the selected and unselected portions separately.
*/
TkSizeT selFirst;
if (entryPtr->selectFirst + 1 < entryPtr->leftIndex + 1) {
selFirst = entryPtr->leftIndex;
} else {
selFirst = entryPtr->selectFirst;
}
if (entryPtr->leftIndex < selFirst) {
Tk_DrawTextLayout(entryPtr->display, pixmap, entryPtr->textGC,
entryPtr->textLayout, entryPtr->layoutX, entryPtr->layoutY,
entryPtr->leftIndex, selFirst);
}
Tk_DrawTextLayout(entryPtr->display, pixmap, entryPtr->selTextGC,
entryPtr->textLayout, entryPtr->layoutX, entryPtr->layoutY,
selFirst, entryPtr->selectLast);
if (entryPtr->selectLast < entryPtr->numChars) {
Tk_DrawTextLayout(entryPtr->display, pixmap, entryPtr->textGC,
entryPtr->textLayout, entryPtr->layoutX, entryPtr->layoutY,
entryPtr->selectLast, entryPtr->numChars);
}
} else {
/*
* Draw the entire visible text
*/
Tk_DrawTextLayout(entryPtr->display, pixmap, entryPtr->textGC,
entryPtr->textLayout, entryPtr->layoutX, entryPtr->layoutY,
entryPtr->leftIndex, entryPtr->numChars);
}
}
if (entryPtr->type == TK_SPINBOX) {
int startx, height, inset, pad, tHeight, xWidth;
Spinbox *sbPtr = (Spinbox *) entryPtr;
/*
* Draw the spin button controls.
*/
if (TkpDrawSpinboxButtons(sbPtr, pixmap) == 0) {
xWidth = entryPtr->xWidth;
pad = XPAD + 1;
inset = entryPtr->inset - XPAD;
startx = Tk_Width(tkwin) - (xWidth + inset);
height = (Tk_Height(tkwin) - 2*inset)/2;
#if 0
Tk_Fill3DRectangle(tkwin, pixmap, sbPtr->buttonBorder,
startx, inset, xWidth, height, 1, sbPtr->buRelief);
Tk_Fill3DRectangle(tkwin, pixmap, sbPtr->buttonBorder,
startx, inset+height, xWidth, height, 1, sbPtr->bdRelief);
#else
Tk_Fill3DRectangle(tkwin, pixmap, sbPtr->buttonBorder,
startx, inset, xWidth, height, 1,
(sbPtr->selElement == SEL_BUTTONUP) ?
TK_RELIEF_SUNKEN : TK_RELIEF_RAISED);
Tk_Fill3DRectangle(tkwin, pixmap, sbPtr->buttonBorder,
startx, inset+height, xWidth, height, 1,
(sbPtr->selElement == SEL_BUTTONDOWN) ?
TK_RELIEF_SUNKEN : TK_RELIEF_RAISED);
#endif
xWidth -= 2*pad;
/*
* Only draw the triangles if we have enough display space
*/
if ((xWidth > 1)) {
XPoint points[3];
int starty, space, offset;
space = height - 2*pad;
/*
* Ensure width of triangle is odd to guarantee a sharp tip
*/
if (!(xWidth % 2)) {
xWidth++;
}
tHeight = (xWidth + 1) / 2;
if (tHeight > space) {
tHeight = space;
}
space = (space - tHeight) / 2;
startx += pad;
starty = inset + height - pad - space;
offset = (sbPtr->selElement == SEL_BUTTONUP);
/*
* The points are slightly different for the up and down
* arrows because (for *.x), we need to account for a bug in
* the way XFillPolygon draws triangles, and we want to shift
* the arrows differently when allowing for depressed
* behavior.
*/
points[0].x = startx + offset;
points[0].y = starty + (offset ? 0 : -1);
points[1].x = startx + xWidth/2 + offset;
points[1].y = starty - tHeight + (offset ? 0 : -1);
points[2].x = startx + xWidth + offset;
points[2].y = points[0].y;
XFillPolygon(entryPtr->display, pixmap, entryPtr->textGC,
points, 3, Convex, CoordModeOrigin);
starty = inset + height + pad + space;
offset = (sbPtr->selElement == SEL_BUTTONDOWN);
points[0].x = startx + 1 + offset;
points[0].y = starty + (offset ? 1 : 0);
points[1].x = startx + xWidth/2 + offset;
points[1].y = starty + tHeight + (offset ? 0 : -1);
points[2].x = startx - 1 + xWidth + offset;
points[2].y = points[0].y;
XFillPolygon(entryPtr->display, pixmap, entryPtr->textGC,
points, 3, Convex, CoordModeOrigin);
}
}
}
/*
* Draw the border and focus highlight last, so they will overwrite any
* text that extends past the viewable part of the window.
*/
if (!TkpDrawEntryBorderAndFocus(entryPtr, pixmap,
(entryPtr->type == TK_SPINBOX))) {
xBound = entryPtr->highlightWidth;
if (entryPtr->relief != TK_RELIEF_FLAT) {
Tk_Draw3DRectangle(tkwin, pixmap, border, xBound, xBound,
Tk_Width(tkwin) - 2 * xBound,
Tk_Height(tkwin) - 2 * xBound,
entryPtr->borderWidth, entryPtr->relief);
}
if (xBound > 0) {
GC fgGC, bgGC;
bgGC = Tk_GCForColor(entryPtr->highlightBgColorPtr, pixmap);
if (entryPtr->flags & GOT_FOCUS) {
fgGC = Tk_GCForColor(entryPtr->highlightColorPtr, pixmap);
TkpDrawHighlightBorder(tkwin, fgGC, bgGC, xBound, pixmap);
} else {
TkpDrawHighlightBorder(tkwin, bgGC, bgGC, xBound, pixmap);
}
}
}
#ifndef TK_NO_DOUBLE_BUFFERING
/*
* Everything's been redisplayed; now copy the pixmap onto the screen and
* free up the pixmap.
*/
XCopyArea(entryPtr->display, pixmap, Tk_WindowId(tkwin), entryPtr->textGC,
0, 0, (unsigned) Tk_Width(tkwin), (unsigned) Tk_Height(tkwin),
0, 0);
Tk_FreePixmap(entryPtr->display, pixmap);
#endif /* TK_NO_DOUBLE_BUFFERING */
entryPtr->flags &= ~BORDER_NEEDED;
}
/*
*----------------------------------------------------------------------
*
* EntryComputeGeometry --
*
* This function is invoked to recompute information about where in its
* window an entry's string will be displayed. It also computes the
* requested size for the window.
*
* Results:
* None.
*
* Side effects:
* The leftX and tabOrigin fields are recomputed for entryPtr, and
* leftIndex may be adjusted. Tk_GeometryRequest is called to register
* the desired dimensions for the window.
*
*----------------------------------------------------------------------
*/
static void
EntryComputeGeometry(
Entry *entryPtr) /* Widget record for entry. */
{
int totalLength, overflow, rightX;
TkSizeT maxOffScreen;
int height, width, i;
Tk_FontMetrics fm;
char *p;
if (entryPtr->displayString != entryPtr->string) {
ckfree((char *)entryPtr->displayString);
entryPtr->displayString = entryPtr->string;
entryPtr->numDisplayBytes = entryPtr->numBytes;
}
/*
* If we're displaying a special character instead of the value of the
* entry, recompute the displayString.
*/
if (entryPtr->showChar != NULL) {
int ch;
char buf[6];
int size;
/*
* Normalize the special character so we can safely duplicate it in
* the display string. If we didn't do this, then two malformed
* characters might end up looking like one valid UTF character in the
* resulting string.
*/
TkUtfToUniChar(entryPtr->showChar, &ch);
size = TkUniCharToUtf(ch, buf);
entryPtr->numDisplayBytes = entryPtr->numChars * size;
p = (char *)ckalloc(entryPtr->numDisplayBytes + 1);
entryPtr->displayString = p;
for (i = entryPtr->numChars; i-- > 0; ) {
memcpy(p, buf, size);
p += size;
}
*p = '\0';
}
/* Recompute layout of placeholder text.
* Only the placeholderX and placeholderLeftIndex value is needed.
* We use the same font so we can use the layoutY value from below.
*/
Tk_FreeTextLayout(entryPtr->placeholderLayout);
if (entryPtr->placeholderString) {
entryPtr->placeholderChars = strlen(entryPtr->placeholderString);
entryPtr->placeholderLayout = Tk_ComputeTextLayout(entryPtr->tkfont,
entryPtr->placeholderString, entryPtr->placeholderChars, 0,
entryPtr->justify, TK_IGNORE_NEWLINES, &totalLength, NULL);
overflow = totalLength -
(Tk_Width(entryPtr->tkwin) - 2*entryPtr->inset - entryPtr->xWidth);
if (overflow <= 0) {
entryPtr->placeholderLeftIndex = 0;
if (entryPtr->justify == TK_JUSTIFY_LEFT) {
entryPtr->placeholderX = entryPtr->inset;
} else if (entryPtr->justify == TK_JUSTIFY_RIGHT) {
entryPtr->placeholderX = Tk_Width(entryPtr->tkwin) - entryPtr->inset
- entryPtr->xWidth - totalLength;
} else {
entryPtr->placeholderX = (Tk_Width(entryPtr->tkwin)
- entryPtr->xWidth - totalLength)/2;
}
} else {
/*
* The whole string can't fit in the window. Compute the maximum
* number of characters that may be off-screen to the left without
* leaving empty space on the right of the window, then don't let
* placeholderLeftIndex be any greater than that.
*/
maxOffScreen = Tk_PointToChar(entryPtr->placeholderLayout, overflow, 0);
Tk_CharBbox(entryPtr->placeholderLayout, maxOffScreen,
&rightX, NULL, NULL, NULL);
if (rightX < overflow) {
maxOffScreen++;
}
entryPtr->placeholderLeftIndex = maxOffScreen;
Tk_CharBbox(entryPtr->placeholderLayout, entryPtr->placeholderLeftIndex, &rightX,
NULL, NULL, NULL);
entryPtr->placeholderX = entryPtr->inset -rightX;
}
} else {
entryPtr->placeholderChars = 0;
entryPtr->placeholderLayout = Tk_ComputeTextLayout(entryPtr->tkfont,
entryPtr->placeholderString, 0, 0,
entryPtr->justify, TK_IGNORE_NEWLINES, NULL, NULL);
entryPtr->placeholderX = entryPtr->inset;
}
Tk_FreeTextLayout(entryPtr->textLayout);
entryPtr->textLayout = Tk_ComputeTextLayout(entryPtr->tkfont,
entryPtr->displayString, entryPtr->numChars, 0,
entryPtr->justify, TK_IGNORE_NEWLINES, &totalLength, &height);
entryPtr->layoutY = (Tk_Height(entryPtr->tkwin) - height) / 2;
/*
* Recompute where the leftmost character on the display will be drawn
* (entryPtr->leftX) and adjust leftIndex if necessary so that we don't
* let characters hang off the edge of the window unless the entire window
* is full.
*/
overflow = totalLength -
(Tk_Width(entryPtr->tkwin) - 2*entryPtr->inset - entryPtr->xWidth);
if (overflow <= 0) {
entryPtr->leftIndex = 0;
if (entryPtr->justify == TK_JUSTIFY_LEFT) {
entryPtr->leftX = entryPtr->inset;
} else if (entryPtr->justify == TK_JUSTIFY_RIGHT) {
entryPtr->leftX = Tk_Width(entryPtr->tkwin) - entryPtr->inset
- entryPtr->xWidth - totalLength;
} else {
entryPtr->leftX = (Tk_Width(entryPtr->tkwin)
- entryPtr->xWidth - totalLength)/2;
}
entryPtr->layoutX = entryPtr->leftX;
} else {
/*
* The whole string can't fit in the window. Compute the maximum
* number of characters that may be off-screen to the left without
* leaving empty space on the right of the window, then don't let
* leftIndex be any greater than that.
*/
maxOffScreen = Tk_PointToChar(entryPtr->textLayout, overflow, 0);
Tk_CharBbox(entryPtr->textLayout, maxOffScreen,
&rightX, NULL, NULL, NULL);
if (rightX < overflow) {
maxOffScreen++;
}
if (entryPtr->leftIndex + 1 > maxOffScreen + 1) {
entryPtr->leftIndex = maxOffScreen;
}
Tk_CharBbox(entryPtr->textLayout, entryPtr->leftIndex, &rightX,
NULL, NULL, NULL);
entryPtr->leftX = entryPtr->inset;
entryPtr->layoutX = entryPtr->leftX - rightX;
}
Tk_GetFontMetrics(entryPtr->tkfont, &fm);
height = fm.linespace + 2*entryPtr->inset + 2*(YPAD-XPAD);
if (entryPtr->prefWidth > 0) {
width = entryPtr->prefWidth*entryPtr->avgWidth + 2*entryPtr->inset;
} else if (totalLength == 0) {
width = entryPtr->avgWidth + 2*entryPtr->inset;
} else {
width = totalLength + 2*entryPtr->inset;
}
/*
* Add one extra length for the spin buttons
*/
width += entryPtr->xWidth;
Tk_GeometryRequest(entryPtr->tkwin, width, height);
}
/*
*----------------------------------------------------------------------
*
* InsertChars --
*
* Add new characters to an entry widget.
*
* Results:
* A standard Tcl result. If an error occurred then an error message is
* left in the interp's result.
*
* Side effects:
* New information gets added to entryPtr; it will be redisplayed soon,
* but not necessarily immediately.
*
*----------------------------------------------------------------------
*/
static int
InsertChars(
Entry *entryPtr, /* Entry that is to get the new elements. */
TkSizeT index, /* Add the new elements before this character
* index. */
const char *value) /* New characters to add (NULL-terminated
* string). */
{
size_t byteIndex, byteCount, newByteCount, oldChars, charsAdded;
const char *string;
char *newStr;
string = entryPtr->string;
byteIndex = Tcl_UtfAtIndex(string, index) - string;
byteCount = strlen(value);
if (byteCount == 0) {
return TCL_OK;
}
newByteCount = entryPtr->numBytes + byteCount + 1;
newStr = (char *)ckalloc(newByteCount);
memcpy(newStr, string, byteIndex);
strcpy(newStr + byteIndex, value);
strcpy(newStr + byteIndex + byteCount, string + byteIndex);
if ((entryPtr->validate == VALIDATE_KEY ||
entryPtr->validate == VALIDATE_ALL) &&
EntryValidateChange(entryPtr, value, newStr, index,
VALIDATE_INSERT) != TCL_OK) {
ckfree(newStr);
return TCL_OK;
}
ckfree((char *)string);
entryPtr->string = newStr;
/*
* The following construction is used because inserting improperly formed
* UTF-8 sequences between other improperly formed UTF-8 sequences could
* result in actually forming valid UTF-8 sequences; the number of
* characters added may not be Tcl_NumUtfChars(string, -1), because of
* context. The actual number of characters added is how many characters
* are in the string now minus the number that used to be there.
*/
oldChars = entryPtr->numChars;
entryPtr->numChars = Tcl_NumUtfChars(newStr, TCL_INDEX_NONE);
charsAdded = entryPtr->numChars - oldChars;
entryPtr->numBytes += byteCount;
if (entryPtr->displayString == string) {
entryPtr->displayString = newStr;
entryPtr->numDisplayBytes = entryPtr->numBytes;
}
/*
* Inserting characters invalidates all indexes into the string. Touch up
* the indexes so that they still refer to the same characters (at new
* positions). When updating the selection end-points, don't include the
* new text in the selection unless it was completely surrounded by the
* selection.
*/
if (entryPtr->selectFirst + 1 >= index + 1) {
entryPtr->selectFirst += charsAdded;
}
if (entryPtr->selectLast + 1 > index + 1) {
entryPtr->selectLast += charsAdded;
}
if ((entryPtr->selectAnchor + 1 > index + 1) || (entryPtr->selectFirst + 1 >= index + 1)) {
entryPtr->selectAnchor += charsAdded;
}
if (entryPtr->leftIndex + 1 > index + 1) {
entryPtr->leftIndex += charsAdded;
}
if (entryPtr->insertPos + 1 >= index + 1) {
entryPtr->insertPos += charsAdded;
}
return EntryValueChanged(entryPtr, NULL);
}
/*
*----------------------------------------------------------------------
*
* DeleteChars --
*
* Remove one or more characters from an entry widget.
*
* Results:
* A standard Tcl result. If an error occurred then an error message is
* left in the interp's result.
*
* Side effects:
* Memory gets freed, the entry gets modified and (eventually)
* redisplayed.
*
*----------------------------------------------------------------------
*/
static int
DeleteChars(
Entry *entryPtr, /* Entry widget to modify. */
TkSizeT index, /* Index of first character to delete. */
TkSizeT count) /* How many characters to delete. */
{
int byteIndex, byteCount, newByteCount;
const char *string;
char *newStr, *toDelete;
if (index + count + 1 > entryPtr->numChars + 1) {
count = entryPtr->numChars - index;
}
if ((int)count <= 0) {
return TCL_OK;
}
string = entryPtr->string;
byteIndex = Tcl_UtfAtIndex(string, index) - string;
byteCount = Tcl_UtfAtIndex(string + byteIndex, count) - (string+byteIndex);
newByteCount = entryPtr->numBytes + 1 - byteCount;
newStr = (char *)ckalloc(newByteCount);
memcpy(newStr, string, (size_t) byteIndex);
strcpy(newStr + byteIndex, string + byteIndex + byteCount);
toDelete = (char *)ckalloc(byteCount + 1);
memcpy(toDelete, string + byteIndex, (size_t) byteCount);
toDelete[byteCount] = '\0';
if ((entryPtr->validate == VALIDATE_KEY ||
entryPtr->validate == VALIDATE_ALL) &&
EntryValidateChange(entryPtr, toDelete, newStr, index,
VALIDATE_DELETE) != TCL_OK) {
ckfree(newStr);
ckfree(toDelete);
return TCL_OK;
}
ckfree(toDelete);
ckfree((char *)entryPtr->string);
entryPtr->string = newStr;
entryPtr->numChars -= count;
entryPtr->numBytes -= byteCount;
if (entryPtr->displayString == string) {
entryPtr->displayString = newStr;
entryPtr->numDisplayBytes = entryPtr->numBytes;
}
/*
* Deleting characters results in the remaining characters being
* renumbered. Update the various indexes into the string to reflect this
* change.
*/
if (entryPtr->selectFirst + 1 >= index + 1) {
if (entryPtr->selectFirst + 1 >= index + count + 1) {
entryPtr->selectFirst -= count;
} else {
entryPtr->selectFirst = index;
}
}
if (entryPtr->selectLast + 1 >= index + 1) {
if (entryPtr->selectLast + 1 >= index + count + 1) {
entryPtr->selectLast -= count;
} else {
entryPtr->selectLast = index;
}
}
if (entryPtr->selectLast + 1 <= entryPtr->selectFirst + 1) {
entryPtr->selectFirst = TCL_INDEX_NONE;
entryPtr->selectLast = TCL_INDEX_NONE;
}
if (entryPtr->selectAnchor + 1 >= index + 1) {
if (entryPtr->selectAnchor + 1 >= index + count + 1) {
entryPtr->selectAnchor -= count;
} else {
entryPtr->selectAnchor = index;
}
}
if (entryPtr->leftIndex + 1 > index + 1) {
if (entryPtr->leftIndex + 1 >= index + count + 1) {
entryPtr->leftIndex -= count;
} else {
entryPtr->leftIndex = index;
}
}
if (entryPtr->insertPos + 1 >= index + 1) {
if (entryPtr->insertPos + 1 >= index + count + 1) {
entryPtr->insertPos -= count;
} else {
entryPtr->insertPos = index;
}
}
return EntryValueChanged(entryPtr, NULL);
}
/*
*----------------------------------------------------------------------
*
* EntryValueChanged --
*
* This function is invoked when characters are inserted into an entry or
* deleted from it. It updates the entry's associated variable, if there
* is one, and does other bookkeeping such as arranging for redisplay.
*
* Results:
* A standard Tcl result. If an error occurred then an error message is
* left in the interp's result.
*
* Side effects:
* None.
*
*----------------------------------------------------------------------
*/
static int
EntryValueChanged(
Entry *entryPtr, /* Entry whose value just changed. */
const char *newValue) /* If this value is not NULL, we first force
* the value of the entry to this. */
{
if (newValue != NULL) {
EntrySetValue(entryPtr, newValue);
}
if (entryPtr->textVarName == NULL) {
newValue = NULL;
} else {
newValue = Tcl_SetVar2(entryPtr->interp, entryPtr->textVarName,
NULL, entryPtr->string, TCL_GLOBAL_ONLY|TCL_LEAVE_ERR_MSG);
}
if ((newValue != NULL) && (strcmp(newValue, entryPtr->string) != 0)) {
/*
* The value of the variable is different than what we asked for.
* This means that a trace on the variable modified it. In this case
* our trace function wasn't invoked since the modification came while
* a trace was already active on the variable. So, update our value to
* reflect the variable's latest value.
*/
EntrySetValue(entryPtr, newValue);
} else {
/*
* Arrange for redisplay.
*/
entryPtr->flags |= UPDATE_SCROLLBAR;
EntryComputeGeometry(entryPtr);
EventuallyRedraw(entryPtr);
}
/*
* An error may have happened when setting the textvariable in case there
* is a trace on that variable and the trace proc triggered an error.
* Another possibility is that the textvariable is in a namespace that
* does not (yet) exist.
* Signal this error.
*/
if ((entryPtr->textVarName != NULL) && (newValue == NULL)) {
return TCL_ERROR;
}
return TCL_OK;
}
/*
*----------------------------------------------------------------------
*
* EntrySetValue --
*
* Replace the contents of a text entry with a given value. This function
* is invoked when updating the entry from the entry's associated
* variable.
*
* Results:
* None.
*
* Side effects:
* The string displayed in the entry will change. The selection,
* insertion point, and view may have to be adjusted to keep them within
* the bounds of the new string. Note: this function does *not* update
* the entry's associated variable, since that could result in an
* infinite loop.
*
*----------------------------------------------------------------------
*/
static void
EntrySetValue(
Entry *entryPtr, /* Entry whose value is to be changed. */
const char *value) /* New text to display in entry. */
{
const char *oldSource;
int valueLen, malloced = 0;
if (strcmp(value, entryPtr->string) == 0) {
return;
}
valueLen = strlen(value);
if (entryPtr->flags & VALIDATE_VAR) {
entryPtr->flags |= VALIDATE_ABORT;
} else {
/*
* If we validate, we create a copy of the value, as it may point to
* volatile memory, like the value of the -textvar which may get freed
* during validation
*/
char *tmp = (char *)ckalloc(valueLen + 1);
strcpy(tmp, value);
value = tmp;
malloced = 1;
entryPtr->flags |= VALIDATE_VAR;
(void) EntryValidateChange(entryPtr, NULL, value, -1,
VALIDATE_FORCED);
entryPtr->flags &= ~VALIDATE_VAR;
/*
* If VALIDATE_ABORT has been set, then this operation should be
* aborted because the validatecommand did something else instead
*/
if (entryPtr->flags & VALIDATE_ABORT) {
entryPtr->flags &= ~VALIDATE_ABORT;
ckfree((char *)value);
return;
}
}
oldSource = entryPtr->string;
ckfree((char *)entryPtr->string);
if (malloced) {
entryPtr->string = value;
} else {
char *tmp = (char *)ckalloc(valueLen + 1);
strcpy(tmp, value);
entryPtr->string = tmp;
}
entryPtr->numBytes = valueLen;
entryPtr->numChars = Tcl_NumUtfChars(value, valueLen);
if (entryPtr->displayString == oldSource) {
entryPtr->displayString = entryPtr->string;
entryPtr->numDisplayBytes = entryPtr->numBytes;
}
if (entryPtr->selectFirst != TCL_INDEX_NONE) {
if (entryPtr->selectFirst + 1 >= entryPtr->numChars + 1) {
entryPtr->selectFirst = TCL_INDEX_NONE;
entryPtr->selectLast = TCL_INDEX_NONE;
} else if (entryPtr->selectLast + 1 > entryPtr->numChars + 1) {
entryPtr->selectLast = entryPtr->numChars;
}
}
if (entryPtr->leftIndex + 1 >= entryPtr->numChars + 1) {
if (entryPtr->numChars + 1 > 1) {
entryPtr->leftIndex = entryPtr->numChars - 1;
} else {
entryPtr->leftIndex = 0;
}
}
if (entryPtr->insertPos + 1 > entryPtr->numChars + 1) {
entryPtr->insertPos = entryPtr->numChars;
}
entryPtr->flags |= UPDATE_SCROLLBAR;
EntryComputeGeometry(entryPtr);
EventuallyRedraw(entryPtr);
}
/*
*--------------------------------------------------------------
*
* EntryEventProc --
*
* This function is invoked by the Tk dispatcher for various events on
* entries.
*
* Results:
* None.
*
* Side effects:
* When the window gets deleted, internal structures get cleaned up.
* When it gets exposed, it is redisplayed.
*
*--------------------------------------------------------------
*/
static void
EntryEventProc(
ClientData clientData, /* Information about window. */
XEvent *eventPtr) /* Information about event. */
{
Entry *entryPtr = (Entry *)clientData;
if ((entryPtr->type == TK_SPINBOX) && (eventPtr->type == MotionNotify)) {
Spinbox *sbPtr = (Spinbox *)clientData;
int elem;
elem = GetSpinboxElement(sbPtr, eventPtr->xmotion.x,
eventPtr->xmotion.y);
if (elem != sbPtr->curElement) {
Tk_Cursor cursor;
sbPtr->curElement = elem;
if (elem == SEL_ENTRY) {
cursor = entryPtr->cursor;
} else if ((elem == SEL_BUTTONDOWN) || (elem == SEL_BUTTONUP)) {
cursor = sbPtr->bCursor;
} else {
cursor = NULL;
}
if (cursor != NULL) {
Tk_DefineCursor(entryPtr->tkwin, cursor);
} else {
Tk_UndefineCursor(entryPtr->tkwin);
}
}
return;
}
switch (eventPtr->type) {
case Expose:
EventuallyRedraw(entryPtr);
entryPtr->flags |= BORDER_NEEDED;
break;
case DestroyNotify:
if (!(entryPtr->flags & ENTRY_DELETED)) {
entryPtr->flags |= (ENTRY_DELETED | VALIDATE_ABORT);
Tcl_DeleteCommandFromToken(entryPtr->interp, entryPtr->widgetCmd);
if (entryPtr->flags & REDRAW_PENDING) {
Tcl_CancelIdleCall(DisplayEntry, clientData);
}
Tcl_EventuallyFree(clientData, (Tcl_FreeProc *) DestroyEntry);
}
break;
case ConfigureNotify:
Tcl_Preserve(entryPtr);
entryPtr->flags |= UPDATE_SCROLLBAR;
EntryComputeGeometry(entryPtr);
EventuallyRedraw(entryPtr);
Tcl_Release(entryPtr);
break;
case FocusIn:
case FocusOut:
if (eventPtr->xfocus.detail != NotifyInferior) {
EntryFocusProc(entryPtr, (eventPtr->type == FocusIn));
}
break;
}
}
/*
*----------------------------------------------------------------------
*
* EntryCmdDeletedProc --
*
* This function is invoked when a widget command is deleted. If the
* widget isn't already in the process of being destroyed, this command
* destroys it.
*
* Results:
* None.
*
* Side effects:
* The widget is destroyed.
*
*----------------------------------------------------------------------
*/
static void
EntryCmdDeletedProc(
ClientData clientData) /* Pointer to widget record for widget. */
{
Entry *entryPtr = (Entry *)clientData;
/*
* This function could be invoked either because the window was destroyed
* and the command was then deleted (in which case tkwin is NULL) or
* because the command was deleted, and then this function destroys the
* widget.
*/
if (!(entryPtr->flags & ENTRY_DELETED)) {
Tk_DestroyWindow(entryPtr->tkwin);
}
}
/*
*---------------------------------------------------------------------------
*
* GetEntryIndex --
*
* Parse an index into an entry and return either its value or an error.
*
* Results:
* A standard Tcl result. If all went well, then *indexPtr is filled in
* with the character index (into entryPtr) corresponding to string. The
* index value is guaranteed to lie between 0 and the number of
* characters in the string, inclusive. If an error occurs then an error
* message is left in the interp's result.
*
* Side effects:
* None.
*
*---------------------------------------------------------------------------
*/
static int
GetEntryIndex(
Tcl_Interp *interp, /* For error messages. */
Entry *entryPtr, /* Entry for which the index is being
* specified. */
Tcl_Obj *indexObj, /* Specifies character in entryPtr. */
TkSizeT *indexPtr) /* Where to store converted character index */
{
TkSizeT length, idx;
const char *string;
if (TCL_OK == TkGetIntForIndex(indexObj, entryPtr->numChars - 1, 1, &idx)) {
if (idx == TCL_INDEX_NONE) {
idx = 0;
} else if (idx > entryPtr->numChars) {
idx = entryPtr->numChars;
}
*indexPtr = idx;
return TCL_OK;
}
string = Tcl_GetStringFromObj(indexObj, &length);
switch (string[0]) {
case 'a':
if (strncmp(string, "anchor", length) != 0) {
goto badIndex;
}
*indexPtr = entryPtr->selectAnchor;
break;
case 'i':
if (strncmp(string, "insert", length) != 0) {
goto badIndex;
}
*indexPtr = entryPtr->insertPos;
break;
case 's':
if (entryPtr->selectFirst == TCL_INDEX_NONE) {
Tcl_ResetResult(interp);
Tcl_SetObjResult(interp, Tcl_ObjPrintf(
"selection isn't in widget %s",
Tk_PathName(entryPtr->tkwin)));
Tcl_SetErrorCode(interp, "TK",
(entryPtr->type == TK_ENTRY) ? "ENTRY" : "SPINBOX",
"NO_SELECTION", NULL);
return TCL_ERROR;
}
if (length < 5) {
goto badIndex;
}
if (strncmp(string, "sel.first", length) == 0) {
*indexPtr = entryPtr->selectFirst;
} else if (strncmp(string, "sel.last", length) == 0) {
*indexPtr = entryPtr->selectLast;
} else {
goto badIndex;
}
break;
case '@': {
int x, roundUp, maxWidth;
if (Tcl_GetInt(NULL, string + 1, &x) != TCL_OK) {
goto badIndex;
}
if (x < entryPtr->inset) {
x = entryPtr->inset;
}
roundUp = 0;
maxWidth = Tk_Width(entryPtr->tkwin) - entryPtr->inset
- entryPtr->xWidth - 1;
if (x > maxWidth) {
x = maxWidth;
roundUp = 1;
}
*indexPtr = Tk_PointToChar(entryPtr->textLayout,
x - entryPtr->layoutX, 0);
/*
* Special trick: if the x-position was off-screen to the right, round
* the index up to refer to the character just after the last visible
* one on the screen. This is needed to enable the last character to
* be selected, for example.
*/
if (roundUp && (*indexPtr + 1 < entryPtr->numChars + 1)) {
*indexPtr += 1;
}
break;
}
default:
badIndex:
Tcl_SetObjResult(interp, Tcl_ObjPrintf("bad %s index \"%s\"",
(entryPtr->type == TK_ENTRY) ? "entry" : "spinbox", string));
Tcl_SetErrorCode(interp, "TK",
(entryPtr->type == TK_ENTRY) ? "ENTRY" : "SPINBOX",
"BAD_INDEX", NULL);
return TCL_ERROR;
}
return TCL_OK;
}
/*
*----------------------------------------------------------------------
*
* EntryScanTo --
*
* Given a y-coordinate (presumably of the curent mouse location) drag
* the view in the window to implement the scan operation.
*
* Results:
* None.
*
* Side effects:
* The view in the window may change.
*
*----------------------------------------------------------------------
*/
static void
EntryScanTo(
Entry *entryPtr, /* Information about widget. */
int x) /* X-coordinate to use for scan operation. */
{
TkSizeT newLeftIndex;
/*
* Compute new leftIndex for entry by amplifying the difference between
* the current position and the place where the scan started (the "mark"
* position). If we run off the left or right side of the entry, then
* reset the mark point so that the current position continues to
* correspond to the edge of the window. This means that the picture will
* start dragging as soon as the mouse reverses direction (without this
* reset, might have to slide mouse a long ways back before the picture
* starts moving again).
*/
newLeftIndex = entryPtr->scanMarkIndex
- (10 * (x - entryPtr->scanMarkX)) / entryPtr->avgWidth;
if (newLeftIndex + 1 >= entryPtr->numChars + 1) {
newLeftIndex = entryPtr->scanMarkIndex = entryPtr->numChars - 1;
entryPtr->scanMarkX = x;
}
if (newLeftIndex == TCL_INDEX_NONE) {
newLeftIndex = entryPtr->scanMarkIndex = 0;
entryPtr->scanMarkX = x;
}
if (newLeftIndex != entryPtr->leftIndex) {
entryPtr->leftIndex = newLeftIndex;
entryPtr->flags |= UPDATE_SCROLLBAR;
EntryComputeGeometry(entryPtr);
if (newLeftIndex != entryPtr->leftIndex) {
entryPtr->scanMarkIndex = entryPtr->leftIndex;
entryPtr->scanMarkX = x;
}
EventuallyRedraw(entryPtr);
}
}
/*
*----------------------------------------------------------------------
*
* EntrySelectTo --
*
* Modify the selection by moving its un-anchored end. This could make
* the selection either larger or smaller.
*
* Results:
* None.
*
* Side effects:
* The selection changes.
*
*----------------------------------------------------------------------
*/
static void
EntrySelectTo(
Entry *entryPtr, /* Information about widget. */
TkSizeT index) /* Character index of element that is to
* become the "other" end of the selection. */
{
TkSizeT newFirst, newLast;
/*
* Grab the selection if we don't own it already.
*/
if (!(entryPtr->flags & GOT_SELECTION) && (entryPtr->exportSelection)
&& (!Tcl_IsSafe(entryPtr->interp))) {
Tk_OwnSelection(entryPtr->tkwin, XA_PRIMARY, EntryLostSelection,
entryPtr);
entryPtr->flags |= GOT_SELECTION;
}
/*
* Pick new starting and ending points for the selection.
*/
if (entryPtr->selectAnchor + 1 > entryPtr->numChars + 1) {
entryPtr->selectAnchor = entryPtr->numChars;
}
if (entryPtr->selectAnchor + 1 <= index + 1) {
newFirst = entryPtr->selectAnchor;
newLast = index;
} else {
newFirst = index;
newLast = entryPtr->selectAnchor;
if (newLast == TCL_INDEX_NONE) {
newFirst = newLast = TCL_INDEX_NONE;
}
}
if ((entryPtr->selectFirst == newFirst)
&& (entryPtr->selectLast == newLast)) {
return;
}
entryPtr->selectFirst = newFirst;
entryPtr->selectLast = newLast;
EventuallyRedraw(entryPtr);
}
/*
*----------------------------------------------------------------------
*
* EntryFetchSelection --
*
* This function is called back by Tk when the selection is requested by
* someone. It returns part or all of the selection in a buffer provided
* by the caller.
*
* Results:
* The return value is the number of non-NULL bytes stored at buffer.
* Buffer is filled (or partially filled) with a NULL-terminated string
* containing part or all of the selection, as given by offset and
* maxBytes.
*
* Side effects:
* None.
*
*----------------------------------------------------------------------
*/
static TkSizeT
EntryFetchSelection(
ClientData clientData, /* Information about entry widget. */
TkSizeT offset, /* Byte offset within selection of first
* character to be returned. */
char *buffer, /* Location in which to place selection. */
TkSizeT maxBytes) /* Maximum number of bytes to place at buffer,
* not including terminating NUL character. */
{
Entry *entryPtr = (Entry *)clientData;
TkSizeT byteCount;
const char *string;
const char *selStart, *selEnd;
if ((entryPtr->selectFirst == TCL_INDEX_NONE) || (!entryPtr->exportSelection)
|| Tcl_IsSafe(entryPtr->interp)) {
return -1;
}
string = entryPtr->displayString;
selStart = Tcl_UtfAtIndex(string, entryPtr->selectFirst);
selEnd = Tcl_UtfAtIndex(selStart,
entryPtr->selectLast - entryPtr->selectFirst);
if (selEnd <= selStart + offset) {
return 0;
}
byteCount = selEnd - selStart - offset;
if (byteCount > maxBytes) {
byteCount = maxBytes;
}
memcpy(buffer, selStart + offset, byteCount);
buffer[byteCount] = '\0';
return byteCount;
}
/*
*----------------------------------------------------------------------
*
* EntryLostSelection --
*
* This function is called back by Tk when the selection is grabbed away
* from an entry widget.
*
* Results:
* None.
*
* Side effects:
* The existing selection is unhighlighted, and the window is marked as
* not containing a selection.
*
*----------------------------------------------------------------------
*/
static void
EntryLostSelection(
ClientData clientData) /* Information about entry widget. */
{
Entry *entryPtr = (Entry *)clientData;
entryPtr->flags &= ~GOT_SELECTION;
/*
* On Windows and Mac systems, we want to remember the selection for the
* next time the focus enters the window. On Unix, we need to clear the
* selection since it is always visible.
* This is controlled by ::tk::AlwaysShowSelection.
*/
if (Tk_AlwaysShowSelection(entryPtr->tkwin)
&& (entryPtr->selectFirst != TCL_INDEX_NONE) && entryPtr->exportSelection
&& (!Tcl_IsSafe(entryPtr->interp))) {
entryPtr->selectFirst = TCL_INDEX_NONE;
entryPtr->selectLast = TCL_INDEX_NONE;
EventuallyRedraw(entryPtr);
}
}
/*
*----------------------------------------------------------------------
*
* EventuallyRedraw --
*
* Ensure that an entry is eventually redrawn on the display.
*
* Results:
* None.
*
* Side effects:
* Information gets redisplayed. Right now we don't do selective
* redisplays: the whole window will be redrawn. This doesn't seem to
* hurt performance noticeably, but if it does then this could be
* changed.
*
*----------------------------------------------------------------------
*/
static void
EventuallyRedraw(
Entry *entryPtr) /* Information about widget. */
{
if ((entryPtr->flags & ENTRY_DELETED) || !Tk_IsMapped(entryPtr->tkwin)) {
return;
}
/*
* Right now we don't do selective redisplays: the whole window will be
* redrawn. This doesn't seem to hurt performance noticeably, but if it
* does then this could be changed.
*/
if (!(entryPtr->flags & REDRAW_PENDING)) {
entryPtr->flags |= REDRAW_PENDING;
Tcl_DoWhenIdle(DisplayEntry, entryPtr);
}
}
/*
*----------------------------------------------------------------------
*
* EntryVisibleRange --
*
* Return information about the range of the entry that is currently
* visible.
*
* Results:
* *firstPtr and *lastPtr are modified to hold fractions between 0 and 1
* identifying the range of characters visible in the entry.
*
* Side effects:
* None.
*
*----------------------------------------------------------------------
*/
static void
EntryVisibleRange(
Entry *entryPtr, /* Information about widget. */
double *firstPtr, /* Return position of first visible character
* in widget. */
double *lastPtr) /* Return position of char just after last
* visible one. */
{
int charsInWindow;
if (entryPtr->numChars == 0) {
*firstPtr = 0.0;
*lastPtr = 1.0;
} else {
charsInWindow = Tk_PointToChar(entryPtr->textLayout,
Tk_Width(entryPtr->tkwin) - entryPtr->inset
- entryPtr->xWidth - entryPtr->layoutX - 1, 0);
if (charsInWindow < (int)entryPtr->numChars) {
charsInWindow++;
}
charsInWindow -= entryPtr->leftIndex;
if (charsInWindow == 0) {
charsInWindow = 1;
}
*firstPtr = (double) entryPtr->leftIndex / entryPtr->numChars;
*lastPtr = (double) (entryPtr->leftIndex + charsInWindow)
/ entryPtr->numChars;
}
}
/*
*----------------------------------------------------------------------
*
* EntryUpdateScrollbar --
*
* This function is invoked whenever information has changed in an entry
* in a way that would invalidate a scrollbar display. If there is an
* associated scrollbar, then this function updates it by invoking a Tcl
* command.
*
* Results:
* None.
*
* Side effects:
* A Tcl command is invoked, and an additional command may be
* invoked to process errors in the command.
*
*----------------------------------------------------------------------
*/
static void
EntryUpdateScrollbar(
Entry *entryPtr) /* Information about widget. */
{
char firstStr[TCL_DOUBLE_SPACE], lastStr[TCL_DOUBLE_SPACE];
int code;
double first, last;
Tcl_Interp *interp;
Tcl_DString buf;
if (entryPtr->scrollCmd == NULL) {
return;
}
interp = entryPtr->interp;
Tcl_Preserve(interp);
EntryVisibleRange(entryPtr, &first, &last);
Tcl_PrintDouble(NULL, first, firstStr);
Tcl_PrintDouble(NULL, last, lastStr);
Tcl_DStringInit(&buf);
Tcl_DStringAppend(&buf, entryPtr->scrollCmd, TCL_INDEX_NONE);
Tcl_DStringAppend(&buf, " ", TCL_INDEX_NONE);
Tcl_DStringAppend(&buf, firstStr, TCL_INDEX_NONE);
Tcl_DStringAppend(&buf, " ", TCL_INDEX_NONE);
Tcl_DStringAppend(&buf, lastStr, TCL_INDEX_NONE);
code = Tcl_EvalEx(interp, Tcl_DStringValue(&buf), TCL_INDEX_NONE, TCL_EVAL_GLOBAL);
Tcl_DStringFree(&buf);
if (code != TCL_OK) {
Tcl_AppendObjToErrorInfo(interp, Tcl_ObjPrintf(
"\n (horizontal scrolling command executed by %s)",
Tk_PathName(entryPtr->tkwin)));
Tcl_BackgroundException(interp, code);
}
Tcl_ResetResult(interp);
Tcl_Release(interp);
}
/*
*----------------------------------------------------------------------
*
* EntryBlinkProc --
*
* This function is called as a timer handler to blink the insertion
* cursor off and on.
*
* Results:
* None.
*
* Side effects:
* The cursor gets turned on or off, redisplay gets invoked, and this
* function reschedules itself.
*
*----------------------------------------------------------------------
*/
static void
EntryBlinkProc(
ClientData clientData) /* Pointer to record describing entry. */
{
Entry *entryPtr = (Entry *)clientData;
if ((entryPtr->state == STATE_DISABLED) ||
(entryPtr->state == STATE_READONLY) ||
!(entryPtr->flags & GOT_FOCUS) || (entryPtr->insertOffTime == 0)) {
return;
}
if (entryPtr->flags & CURSOR_ON) {
entryPtr->flags &= ~CURSOR_ON;
entryPtr->insertBlinkHandler = Tcl_CreateTimerHandler(
entryPtr->insertOffTime, EntryBlinkProc, entryPtr);
} else {
entryPtr->flags |= CURSOR_ON;
entryPtr->insertBlinkHandler = Tcl_CreateTimerHandler(
entryPtr->insertOnTime, EntryBlinkProc, entryPtr);
}
EventuallyRedraw(entryPtr);
}
/*
*----------------------------------------------------------------------
*
* EntryFocusProc --
*
* This function is called whenever the entry gets or loses the input
* focus. It's also called whenever the window is reconfigured while it
* has the focus.
*
* Results:
* None.
*
* Side effects:
* The cursor gets turned on or off.
*
*----------------------------------------------------------------------
*/
static void
EntryFocusProc(
Entry *entryPtr, /* Entry that got or lost focus. */
int gotFocus) /* 1 means window is getting focus, 0 means
* it's losing it. */
{
Tcl_DeleteTimerHandler(entryPtr->insertBlinkHandler);
if (gotFocus) {
entryPtr->flags |= GOT_FOCUS | CURSOR_ON;
if (entryPtr->insertOffTime != 0) {
entryPtr->insertBlinkHandler = Tcl_CreateTimerHandler(
entryPtr->insertOnTime, EntryBlinkProc, entryPtr);
}
if (entryPtr->validate == VALIDATE_ALL ||
entryPtr->validate == VALIDATE_FOCUS ||
entryPtr->validate == VALIDATE_FOCUSIN) {
EntryValidateChange(entryPtr, NULL, entryPtr->string, -1,
VALIDATE_FOCUSIN);
}
} else {
entryPtr->flags &= ~(GOT_FOCUS | CURSOR_ON);
entryPtr->insertBlinkHandler = NULL;
if (entryPtr->validate == VALIDATE_ALL ||
entryPtr->validate == VALIDATE_FOCUS ||
entryPtr->validate == VALIDATE_FOCUSOUT) {
EntryValidateChange(entryPtr, NULL, entryPtr->string, -1,
VALIDATE_FOCUSOUT);
}
}
EventuallyRedraw(entryPtr);
}
/*
*--------------------------------------------------------------
*
* EntryTextVarProc --
*
* This function is invoked when someone changes the variable whose
* contents are to be displayed in an entry.
*
* Results:
* NULL is always returned.
*
* Side effects:
* The text displayed in the entry will change to match the variable.
*
*--------------------------------------------------------------
*/
static char *
EntryTextVarProc(
ClientData clientData, /* Information about button. */
Tcl_Interp *interp, /* Interpreter containing variable. */
const char *name1, /* Not used. */
const char *name2, /* Not used. */
int flags) /* Information about what happened. */
{
Entry *entryPtr = (Entry *)clientData;
const char *value;
(void)name1;
(void)name2;
if (entryPtr->flags & ENTRY_DELETED) {
/*
* Just abort early if we entered here while being deleted.
*/
return NULL;
}
/*
* If the variable is unset, then immediately recreate it unless the whole
* interpreter is going away.
*/
if (flags & TCL_TRACE_UNSETS) {
if (!Tcl_InterpDeleted(interp) && entryPtr->textVarName) {
ClientData probe = NULL;
do {
probe = Tcl_VarTraceInfo(interp,
entryPtr->textVarName,
TCL_GLOBAL_ONLY|TCL_TRACE_WRITES|TCL_TRACE_UNSETS,
EntryTextVarProc, probe);
if (probe == (ClientData)entryPtr) {
break;
}
} while (probe);
if (probe) {
/*
* We were able to fetch the unset trace for our
* textVarName, which means it is not unset and not
* the cause of this unset trace. Instead some outdated
* former variable must be, and we should ignore it.
*/
return NULL;
}
Tcl_SetVar2(interp, entryPtr->textVarName, NULL,
entryPtr->string, TCL_GLOBAL_ONLY);
Tcl_TraceVar2(interp, entryPtr->textVarName, NULL,
TCL_GLOBAL_ONLY|TCL_TRACE_WRITES|TCL_TRACE_UNSETS,
EntryTextVarProc, clientData);
entryPtr->flags |= ENTRY_VAR_TRACED;
}
return NULL;
}
/*
* Update the entry's text with the value of the variable, unless the
* entry already has that value (this happens when the variable changes
* value because we changed it because someone typed in the entry).
*/
value = Tcl_GetVar2(interp, entryPtr->textVarName, NULL, TCL_GLOBAL_ONLY);
if (value == NULL) {
value = "";
}
EntrySetValue(entryPtr, value);
return NULL;
}
/*
*--------------------------------------------------------------
*
* EntryValidate --
*
* This function is invoked when any character is added or removed from
* the entry widget, or a focus has trigerred validation.
*
* Results:
* TCL_OK if the validatecommand passes the new string. TCL_BREAK if the
* vcmd executed OK, but rejects the string. TCL_ERROR if an error
* occurred while executing the vcmd or a valid Tcl_Bool is not returned.
*
* Side effects:
* An error condition may arise
*
*--------------------------------------------------------------
*/
static int
EntryValidate(
Entry *entryPtr, /* Entry that needs validation. */
char *cmd) /* Validation command (NULL-terminated
* string). */
{
Tcl_Interp *interp = entryPtr->interp;
int code, isOK;
code = Tcl_EvalEx(interp, cmd, TCL_INDEX_NONE, TCL_EVAL_GLOBAL | TCL_EVAL_DIRECT);
/*
* We accept TCL_OK and TCL_RETURN as valid return codes from the command
* callback.
*/
if (code != TCL_OK && code != TCL_RETURN) {
Tcl_AppendObjToErrorInfo(interp, Tcl_ObjPrintf(
"\n (in validation command executed by %s)",
Tk_PathName(entryPtr->tkwin)));
Tcl_BackgroundException(interp, code);
return TCL_ERROR;
}
/*
* The command callback should return an acceptable Tcl boolean.
*/
if (Tcl_GetBooleanFromObj(interp, Tcl_GetObjResult(interp),
&isOK) != TCL_OK) {
Tcl_AddErrorInfo(interp,
"\n (invalid boolean result from validation command)");
Tcl_BackgroundException(interp, TCL_ERROR);
Tcl_ResetResult(interp);
return TCL_ERROR;
}
Tcl_ResetResult(interp);
return (isOK ? TCL_OK : TCL_BREAK);
}
/*
*--------------------------------------------------------------
*
* EntryValidateChange --
*
* This function is invoked when any character is added or removed from
* the entry widget, or a focus has trigerred validation.
*
* Results:
* TCL_OK if the validatecommand accepts the new string, TCL_ERROR if any
* problems occurred with validatecommand.
*
* Side effects:
* The insertion/deletion may be aborted, and the validatecommand might
* turn itself off (if an error or loop condition arises).
*
*--------------------------------------------------------------
*/
static int
EntryValidateChange(
Entry *entryPtr, /* Entry that needs validation. */
const char *change, /* Characters to be added/deleted
* (NUL-terminated string). */
const char *newValue, /* Potential new value of entry string */
TkSizeT index, /* index of insert/delete, -1 otherwise */
int type) /* forced, delete, insert, focusin or
* focusout */
{
int code, varValidate = (entryPtr->flags & VALIDATE_VAR);
char *p;
Tcl_DString script;
if (entryPtr->validateCmd == NULL ||
entryPtr->validate == VALIDATE_NONE) {
if (entryPtr->flags & VALIDATING) {
entryPtr->flags |= VALIDATE_ABORT;
}
return (varValidate ? TCL_ERROR : TCL_OK);
}
/*
* If we're already validating, then we're hitting a loop condition. Set
* validate to none to disallow further validations, arrange for flags
* to prevent current validation from finishing, and return.
*/
if (entryPtr->flags & VALIDATING) {
entryPtr->validate = VALIDATE_NONE;
entryPtr->flags |= VALIDATE_ABORT;
return (varValidate ? TCL_ERROR : TCL_OK);
}
entryPtr->flags |= VALIDATING;
/*
* Now form command string and run through the -validatecommand
*/
Tcl_DStringInit(&script);
ExpandPercents(entryPtr, entryPtr->validateCmd,
change, newValue, index, type, &script);
Tcl_DStringAppend(&script, "", 1);
p = Tcl_DStringValue(&script);
code = EntryValidate(entryPtr, p);
Tcl_DStringFree(&script);
/*
* If e->validate has become VALIDATE_NONE during the validation, or we
* now have VALIDATE_VAR set (from EntrySetValue) and didn't before, it
* means that a loop condition almost occurred. Do not allow this
* validation result to finish.
*/
if (entryPtr->validate == VALIDATE_NONE
|| (!varValidate && (entryPtr->flags & VALIDATE_VAR))) {
code = TCL_ERROR;
}
/*
* It's possible that the user deleted the entry during validation. In
* that case, abort future validation and return an error.
*/
if (entryPtr->flags & ENTRY_DELETED) {
return TCL_ERROR;
}
/*
* If validate will return ERROR, then disallow further validations
* Otherwise, if it didn't accept the new string (returned TCL_BREAK) then
* eval the invalidCmd (if it's set)
*/
if (code == TCL_ERROR) {
entryPtr->validate = VALIDATE_NONE;
} else if (code == TCL_BREAK) {
/*
* If we were doing forced validation (like via a variable trace) and
* the command returned 0, the we turn off validation because we
* assume that textvariables have precedence in managing the value.
* We also don't call the invcmd, as it may want to do entry
* manipulation which the setting of the var will later wipe anyway.
*/
if (varValidate) {
entryPtr->validate = VALIDATE_NONE;
} else if (entryPtr->invalidCmd != NULL) {
int result;
Tcl_DStringInit(&script);
ExpandPercents(entryPtr, entryPtr->invalidCmd,
change, newValue, index, type, &script);
Tcl_DStringAppend(&script, "", 1);
p = Tcl_DStringValue(&script);
result = Tcl_EvalEx(entryPtr->interp, p, -1,
TCL_EVAL_GLOBAL | TCL_EVAL_DIRECT);
if (result != TCL_OK) {
Tcl_AddErrorInfo(entryPtr->interp,
"\n (in invalidcommand executed by entry)");
Tcl_BackgroundException(entryPtr->interp, result);
code = TCL_ERROR;
entryPtr->validate = VALIDATE_NONE;
}
Tcl_DStringFree(&script);
/*
* It's possible that the user deleted the entry during
* validation. In that case, abort future validation and return an
* error.
*/
if (entryPtr->flags & ENTRY_DELETED) {
return TCL_ERROR;
}
}
}
entryPtr->flags &= ~VALIDATING;
return code;
}
/*
*--------------------------------------------------------------
*
* ExpandPercents --
*
* Given a command and an event, produce a new command by replacing %
* constructs in the original command with information from the X event.
*
* Results:
* The new expanded command is appended to the dynamic string given by
* dsPtr.
*
* Side effects:
* None.
*
*--------------------------------------------------------------
*/
static void
ExpandPercents(
Entry *entryPtr, /* Entry that needs validation. */
const char *before,
/* Command containing percent expressions to
* be replaced. */
const char *change, /* Characters to added/deleted (NUL-terminated
* string). */
const char *newValue, /* Potential new value of entry string */
TkSizeT index, /* index of insert/delete */
int type, /* INSERT or DELETE */
Tcl_DString *dsPtr) /* Dynamic string in which to append new
* command. */
{
int spaceNeeded, cvtFlags; /* Used to substitute string as proper Tcl
* list element. */
int number, length;
const char *string;
int ch;
char numStorage[2*TCL_INTEGER_SPACE];
while (1) {
if (*before == '\0') {
break;
}
/*
* Find everything up to the next % character and append it to the
* result string.
*/
string = before;
/*
* No need to convert '%', as it is in ascii range.
*/
string = Tcl_UtfFindFirst(before, '%');
if (string == NULL) {
Tcl_DStringAppend(dsPtr, before, -1);
break;
} else if (string != before) {
Tcl_DStringAppend(dsPtr, before, string-before);
before = string;
}
/*
* There's a percent sequence here. Process it.
*/
before++; /* skip over % */
if (*before != '\0') {
before += TkUtfToUniChar(before, &ch);
} else {
ch = '%';
}
if (type == VALIDATE_BUTTON) {
/*
* -command %-substitution
*/
switch (ch) {
case 's': /* Current string value of spinbox */
string = entryPtr->string;
break;
case 'd': /* direction, up or down */
string = change;
break;
case 'W': /* widget name */
string = Tk_PathName(entryPtr->tkwin);
break;
default:
length = TkUniCharToUtf(ch, numStorage);
numStorage[length] = '\0';
string = numStorage;
break;
}
} else {
/*
* -validatecommand / -invalidcommand %-substitution
*/
switch (ch) {
case 'd': /* Type of call that caused validation */
switch (type) {
case VALIDATE_INSERT:
number = 1;
break;
case VALIDATE_DELETE:
number = 0;
break;
default:
number = -1;
break;
}
sprintf(numStorage, "%d", number);
string = numStorage;
break;
case 'i': /* index of insert/delete */
sprintf(numStorage, "%d", (int)index);
string = numStorage;
break;
case 'P': /* 'Peeked' new value of the string */
string = newValue;
break;
case 's': /* Current string value of spinbox */
string = entryPtr->string;
break;
case 'S': /* string to be inserted/deleted, if any */
string = change;
break;
case 'v': /* type of validation currently set */
string = validateStrings[entryPtr->validate];
break;
case 'V': /* type of validation in effect */
switch (type) {
case VALIDATE_INSERT:
case VALIDATE_DELETE:
string = validateStrings[VALIDATE_KEY];
break;
case VALIDATE_FORCED:
string = "forced";
break;
default:
string = validateStrings[type];
break;
}
break;
case 'W': /* widget name */
string = Tk_PathName(entryPtr->tkwin);
break;
default:
length = TkUniCharToUtf(ch, numStorage);
numStorage[length] = '\0';
string = numStorage;
break;
}
}
spaceNeeded = Tcl_ScanCountedElement(string, -1, &cvtFlags);
length = Tcl_DStringLength(dsPtr);
Tcl_DStringSetLength(dsPtr, length + spaceNeeded);
spaceNeeded = Tcl_ConvertCountedElement(string, -1,
Tcl_DStringValue(dsPtr) + length,
cvtFlags | TCL_DONT_USE_BRACES);
Tcl_DStringSetLength(dsPtr, length + spaceNeeded);
}
}
/*
*--------------------------------------------------------------
*
* Tk_SpinboxObjCmd --
*
* This function is invoked to process the "spinbox" Tcl command. See the
* user documentation for details on what it does.
*
* Results:
* A standard Tcl result.
*
* Side effects:
* See the user documentation.
*
*--------------------------------------------------------------
*/
int
Tk_SpinboxObjCmd(
ClientData dummy, /* NULL. */
Tcl_Interp *interp, /* Current interpreter. */
int objc, /* Number of arguments. */
Tcl_Obj *const objv[]) /* Argument objects. */
{
Entry *entryPtr;
Spinbox *sbPtr;
Tk_OptionTable optionTable;
Tk_Window tkwin;
char *tmp;
(void)dummy;
if (objc < 2) {
Tcl_WrongNumArgs(interp, 1, objv, "pathName ?-option value ...?");
return TCL_ERROR;
}
tkwin = Tk_CreateWindowFromPath(interp, Tk_MainWindow(interp),
Tcl_GetString(objv[1]), NULL);
if (tkwin == NULL) {
return TCL_ERROR;
}
/*
* Create the option table for this widget class. If it has already been
* created, Tk will return the cached value.
*/
optionTable = Tk_CreateOptionTable(interp, sbOptSpec);
/*
* Initialize the fields of the structure that won't be initialized by
* ConfigureEntry, or that ConfigureEntry requires to be initialized
* already (e.g. resource pointers). Only the non-NULL/0 data must be
* initialized as memset covers the rest.
*/
sbPtr = (Spinbox *)ckalloc(sizeof(Spinbox));
entryPtr = (Entry *) sbPtr;
memset(sbPtr, 0, sizeof(Spinbox));
entryPtr->tkwin = tkwin;
entryPtr->display = Tk_Display(tkwin);
entryPtr->interp = interp;
entryPtr->widgetCmd = Tcl_CreateObjCommand(interp,
Tk_PathName(entryPtr->tkwin), SpinboxWidgetObjCmd, sbPtr,
EntryCmdDeletedProc);
entryPtr->optionTable = optionTable;
entryPtr->type = TK_SPINBOX;
tmp = (char *)ckalloc(1);
tmp[0] = '\0';
entryPtr->string = tmp;
entryPtr->selectFirst = TCL_INDEX_NONE;
entryPtr->selectLast = TCL_INDEX_NONE;
entryPtr->cursor = NULL;
entryPtr->exportSelection = 1;
entryPtr->justify = TK_JUSTIFY_LEFT;
entryPtr->relief = TK_RELIEF_FLAT;
entryPtr->state = STATE_NORMAL;
entryPtr->displayString = entryPtr->string;
entryPtr->inset = XPAD;
entryPtr->textGC = NULL;
entryPtr->selTextGC = NULL;
entryPtr->highlightGC = NULL;
entryPtr->avgWidth = 1;
entryPtr->validate = VALIDATE_NONE;
sbPtr->selElement = SEL_NONE;
sbPtr->curElement = SEL_NONE;
sbPtr->bCursor = NULL;
sbPtr->repeatDelay = 400;
sbPtr->repeatInterval = 100;
sbPtr->fromValue = 0.0;
sbPtr->toValue = 100.0;
sbPtr->increment = 1.0;
sbPtr->formatBuf = (char *)ckalloc(TCL_DOUBLE_SPACE);
sbPtr->bdRelief = TK_RELIEF_FLAT;
sbPtr->buRelief = TK_RELIEF_FLAT;
entryPtr->placeholderGC = NULL;
/*
* Keep a hold of the associated tkwin until we destroy the spinbox,
* otherwise Tk might free it while we still need it.
*/
Tcl_Preserve(entryPtr->tkwin);
Tk_SetClass(entryPtr->tkwin, "Spinbox");
Tk_SetClassProcs(entryPtr->tkwin, &entryClass, entryPtr);
Tk_CreateEventHandler(entryPtr->tkwin,
PointerMotionMask|ExposureMask|StructureNotifyMask|FocusChangeMask,
EntryEventProc, entryPtr);
Tk_CreateSelHandler(entryPtr->tkwin, XA_PRIMARY, XA_STRING,
EntryFetchSelection, entryPtr, XA_STRING);
if (Tk_InitOptions(interp, sbPtr, optionTable, tkwin)
!= TCL_OK) {
Tk_DestroyWindow(entryPtr->tkwin);
return TCL_ERROR;
}
if (ConfigureEntry(interp, entryPtr, objc-2, objv+2) != TCL_OK) {
goto error;
}
Tcl_SetObjResult(interp, Tk_NewWindowObj(entryPtr->tkwin));
return TCL_OK;
error:
Tk_DestroyWindow(entryPtr->tkwin);
return TCL_ERROR;
}
/*
*--------------------------------------------------------------
*
* SpinboxWidgetObjCmd --
*
* This function is invoked to process the Tcl command that corresponds
* to a widget managed by this module. See the user documentation for
* details on what it does.
*
* Results:
* A standard Tcl result.
*
* Side effects:
* See the user documentation.
*
*--------------------------------------------------------------
*/
static int
SpinboxWidgetObjCmd(
ClientData clientData, /* Information about spinbox widget. */
Tcl_Interp *interp, /* Current interpreter. */
int objc, /* Number of arguments. */
Tcl_Obj *const objv[]) /* Argument objects. */
{
Entry *entryPtr = (Entry *)clientData;
Spinbox *sbPtr = (Spinbox *)clientData;
int cmdIndex, selIndex, result;
Tcl_Obj *objPtr;
if (objc < 2) {
Tcl_WrongNumArgs(interp, 1, objv, "option ?arg ...?");
return TCL_ERROR;
}
/*
* Parse the widget command by looking up the second token in the list of
* valid command names.
*/
result = Tcl_GetIndexFromObj(interp, objv[1], sbCmdNames,
"option", 0, &cmdIndex);
if (result != TCL_OK) {
return result;
}
Tcl_Preserve(entryPtr);
switch ((enum sbCmd) cmdIndex) {
case SB_CMD_BBOX: {
TkSizeT index;
int x, y, width, height;
Tcl_Obj *bbox[4];
if (objc != 3) {
Tcl_WrongNumArgs(interp, 2, objv, "index");
goto error;
}
if (GetEntryIndex(interp, entryPtr, objv[2],
&index) != TCL_OK) {
goto error;
}
if ((index == entryPtr->numChars) && (index + 1 > 1)) {
index--;
}
Tk_CharBbox(entryPtr->textLayout, index, &x, &y, &width, &height);
bbox[0] = Tcl_NewWideIntObj(x + entryPtr->layoutX);
bbox[1] = Tcl_NewWideIntObj(y + entryPtr->layoutY);
bbox[2] = Tcl_NewWideIntObj(width);
bbox[3] = Tcl_NewWideIntObj(height);
Tcl_SetObjResult(interp, Tcl_NewListObj(4, bbox));
break;
}
case SB_CMD_CGET:
if (objc != 3) {
Tcl_WrongNumArgs(interp, 2, objv, "option");
goto error;
}
objPtr = Tk_GetOptionValue(interp, entryPtr,
entryPtr->optionTable, objv[2], entryPtr->tkwin);
if (objPtr == NULL) {
goto error;
}
Tcl_SetObjResult(interp, objPtr);
break;
case SB_CMD_CONFIGURE:
if (objc <= 3) {
objPtr = Tk_GetOptionInfo(interp, entryPtr,
entryPtr->optionTable, (objc == 3) ? objv[2] : NULL,
entryPtr->tkwin);
if (objPtr == NULL) {
goto error;
}
Tcl_SetObjResult(interp, objPtr);
} else {
result = ConfigureEntry(interp, entryPtr, objc-2, objv+2);
}
break;
case SB_CMD_DELETE: {
TkSizeT first, last;
int code;
if ((objc < 3) || (objc > 4)) {
Tcl_WrongNumArgs(interp, 2, objv, "firstIndex ?lastIndex?");
goto error;
}
if (GetEntryIndex(interp, entryPtr, objv[2],
&first) != TCL_OK) {
goto error;
}
if (objc == 3) {
last = first + 1;
} else {
if (GetEntryIndex(interp, entryPtr, objv[3],
&last) != TCL_OK) {
goto error;
}
}
if ((last + 1 >= first + 1) && (entryPtr->state == STATE_NORMAL)) {
code = DeleteChars(entryPtr, first, last - first);
if (code != TCL_OK) {
goto error;
}
}
break;
}
case SB_CMD_GET:
if (objc != 2) {
Tcl_WrongNumArgs(interp, 2, objv, NULL);
goto error;
}
Tcl_SetObjResult(interp, Tcl_NewStringObj(entryPtr->string, -1));
break;
case SB_CMD_ICURSOR:
if (objc != 3) {
Tcl_WrongNumArgs(interp, 2, objv, "pos");
goto error;
}
if (GetEntryIndex(interp, entryPtr, objv[2],
&entryPtr->insertPos) != TCL_OK) {
goto error;
}
EventuallyRedraw(entryPtr);
break;
case SB_CMD_IDENTIFY: {
int x, y, elem;
if (objc != 4) {
Tcl_WrongNumArgs(interp, 2, objv, "x y");
goto error;
}
if ((Tcl_GetIntFromObj(interp, objv[2], &x) != TCL_OK) ||
(Tcl_GetIntFromObj(interp, objv[3], &y) != TCL_OK)) {
goto error;
}
elem = GetSpinboxElement(sbPtr, x, y);
if (elem != SEL_NONE) {
Tcl_SetObjResult(interp,
Tcl_NewStringObj(selElementNames[elem], -1));
}
break;
}
case SB_CMD_INDEX: {
TkSizeT index;
if (objc != 3) {
Tcl_WrongNumArgs(interp, 2, objv, "string");
goto error;
}
if (GetEntryIndex(interp, entryPtr, objv[2],
&index) != TCL_OK) {
goto error;
}
Tcl_SetObjResult(interp, TkNewIndexObj(index));
break;
}
case SB_CMD_INSERT: {
TkSizeT index;
int code;
if (objc != 4) {
Tcl_WrongNumArgs(interp, 2, objv, "index text");
goto error;
}
if (GetEntryIndex(interp, entryPtr, objv[2],
&index) != TCL_OK) {
goto error;
}
if (entryPtr->state == STATE_NORMAL) {
code = InsertChars(entryPtr, index, Tcl_GetString(objv[3]));
if (code != TCL_OK) {
goto error;
}
}
break;
}
case SB_CMD_INVOKE:
if (objc != 3) {
Tcl_WrongNumArgs(interp, 2, objv, "elemName");
goto error;
}
result = Tcl_GetIndexFromObj(interp, objv[2],
selElementNames, "element", 0, &cmdIndex);
if (result != TCL_OK) {
goto error;
}
if (entryPtr->state != STATE_DISABLED) {
if (SpinboxInvoke(interp, sbPtr, cmdIndex) != TCL_OK) {
goto error;
}
}
break;
case SB_CMD_SCAN: {
int x;
const char *minorCmd;
if (objc != 4) {
Tcl_WrongNumArgs(interp, 2, objv, "mark|dragto x");
goto error;
}
if (Tcl_GetIntFromObj(interp, objv[3], &x) != TCL_OK) {
goto error;
}
minorCmd = Tcl_GetString(objv[2]);
if (minorCmd[0] == 'm'
&& (strncmp(minorCmd, "mark", strlen(minorCmd)) == 0)) {
entryPtr->scanMarkX = x;
entryPtr->scanMarkIndex = entryPtr->leftIndex;
} else if ((minorCmd[0] == 'd')
&& (strncmp(minorCmd, "dragto", strlen(minorCmd)) == 0)) {
EntryScanTo(entryPtr, x);
} else {
Tcl_SetObjResult(interp, Tcl_ObjPrintf(
"bad scan option \"%s\": must be mark or dragto",
minorCmd));
Tcl_SetErrorCode(interp, "TCL", "LOOKUP", "INDEX", "scan option",
minorCmd, NULL);
goto error;
}
break;
}
case SB_CMD_SELECTION: {
TkSizeT index, index2;
if (objc < 3) {
Tcl_WrongNumArgs(interp, 2, objv, "option ?index?");
goto error;
}
/*
* Parse the selection sub-command, using the command table
* "sbSelCmdNames" defined above.
*/
result = Tcl_GetIndexFromObj(interp, objv[2], sbSelCmdNames,
"selection option", 0, &selIndex);
if (result != TCL_OK) {
goto error;
}
/*
* Disabled entries don't allow the selection to be modified, but
* 'selection present' must return a boolean.
*/
if ((entryPtr->state == STATE_DISABLED)
&& (selIndex != SB_SEL_PRESENT)) {
goto done;
}
switch (selIndex) {
case SB_SEL_ADJUST:
if (objc != 4) {
Tcl_WrongNumArgs(interp, 3, objv, "index");
goto error;
}
if (GetEntryIndex(interp, entryPtr,
objv[3], &index) != TCL_OK) {
goto error;
}
if (entryPtr->selectFirst != TCL_INDEX_NONE) {
TkSizeT half1, half2;
half1 = (entryPtr->selectFirst + entryPtr->selectLast)/2;
half2 = (entryPtr->selectFirst + entryPtr->selectLast + 1)/2;
if (index + 1 < half1 + 1) {
entryPtr->selectAnchor = entryPtr->selectLast;
} else if (index + 1 > half2 + 1) {
entryPtr->selectAnchor = entryPtr->selectFirst;
} else {
/*
* We're at about the halfway point in the selection; just
* keep the existing anchor.
*/
}
}
EntrySelectTo(entryPtr, index);
break;
case SB_SEL_CLEAR:
if (objc != 3) {
Tcl_WrongNumArgs(interp, 3, objv, NULL);
goto error;
}
if (entryPtr->selectFirst != TCL_INDEX_NONE) {
entryPtr->selectFirst = TCL_INDEX_NONE;
entryPtr->selectLast = TCL_INDEX_NONE;
EventuallyRedraw(entryPtr);
}
goto done;
case SB_SEL_FROM:
if (objc != 4) {
Tcl_WrongNumArgs(interp, 3, objv, "index");
goto error;
}
if (GetEntryIndex(interp, entryPtr,
objv[3], &index) != TCL_OK) {
goto error;
}
entryPtr->selectAnchor = index;
break;
case SB_SEL_PRESENT:
if (objc != 3) {
Tcl_WrongNumArgs(interp, 3, objv, NULL);
goto error;
}
Tcl_SetObjResult(interp, Tcl_NewBooleanObj(
entryPtr->selectFirst != TCL_INDEX_NONE));
goto done;
case SB_SEL_RANGE:
if (objc != 5) {
Tcl_WrongNumArgs(interp, 3, objv, "start end");
goto error;
}
if (GetEntryIndex(interp, entryPtr,
objv[3], &index) != TCL_OK) {
goto error;
}
if (GetEntryIndex(interp, entryPtr,
objv[4],& index2) != TCL_OK) {
goto error;
}
if (index + 1 >= index2 + 1) {
entryPtr->selectFirst = TCL_INDEX_NONE;
entryPtr->selectLast = TCL_INDEX_NONE;
} else {
entryPtr->selectFirst = index;
entryPtr->selectLast = index2;
}
if (!(entryPtr->flags & GOT_SELECTION)
&& entryPtr->exportSelection
&& (!Tcl_IsSafe(entryPtr->interp))) {
Tk_OwnSelection(entryPtr->tkwin, XA_PRIMARY,
EntryLostSelection, entryPtr);
entryPtr->flags |= GOT_SELECTION;
}
EventuallyRedraw(entryPtr);
break;
case SB_SEL_TO:
if (objc != 4) {
Tcl_WrongNumArgs(interp, 3, objv, "index");
goto error;
}
if (GetEntryIndex(interp, entryPtr,
objv[3], &index) != TCL_OK) {
goto error;
}
EntrySelectTo(entryPtr, index);
break;
case SB_SEL_ELEMENT:
if ((objc < 3) || (objc > 4)) {
Tcl_WrongNumArgs(interp, 3, objv, "?elemName?");
goto error;
}
if (objc == 3) {
Tcl_SetObjResult(interp, Tcl_NewStringObj(
selElementNames[sbPtr->selElement], -1));
} else {
int lastElement = sbPtr->selElement;
result = Tcl_GetIndexFromObj(interp, objv[3], selElementNames,
"selection element", 0, &(sbPtr->selElement));
if (result != TCL_OK) {
goto error;
}
if (lastElement != sbPtr->selElement) {
EventuallyRedraw(entryPtr);
}
}
break;
}
break;
}
case SB_CMD_SET: {
int code = TCL_OK;
if (objc > 3) {
Tcl_WrongNumArgs(interp, 2, objv, "?string?");
goto error;
}
if (objc == 3) {
code = EntryValueChanged(entryPtr, Tcl_GetString(objv[2]));
if (code != TCL_OK) {
goto error;
}
}
Tcl_SetObjResult(interp, Tcl_NewStringObj(entryPtr->string, -1));
break;
}
case SB_CMD_VALIDATE: {
int code;
if (objc != 2) {
Tcl_WrongNumArgs(interp, 2, objv, NULL);
goto error;
}
selIndex = entryPtr->validate;
entryPtr->validate = VALIDATE_ALL;
code = EntryValidateChange(entryPtr, NULL, entryPtr->string,
-1, VALIDATE_FORCED);
if (entryPtr->validate != VALIDATE_NONE) {
entryPtr->validate = selIndex;
}
Tcl_SetObjResult(interp, Tcl_NewBooleanObj(code == TCL_OK));
break;
}
case SB_CMD_XVIEW: {
TkSizeT index;
if (objc == 2) {
double first, last;
Tcl_Obj *span[2];
EntryVisibleRange(entryPtr, &first, &last);
span[0] = Tcl_NewDoubleObj(first);
span[1] = Tcl_NewDoubleObj(last);
Tcl_SetObjResult(interp, Tcl_NewListObj(2, span));
goto done;
} else if (objc == 3) {
if (GetEntryIndex(interp, entryPtr, objv[2],
&index) != TCL_OK) {
goto error;
}
} else {
double fraction;
int count;
index = entryPtr->leftIndex;
switch (Tk_GetScrollInfoObj(interp, objc, objv, &fraction,
&count)) {
case TK_SCROLL_ERROR:
goto error;
case TK_SCROLL_MOVETO:
index = ((fraction * entryPtr->numChars) + 0.5);
break;
case TK_SCROLL_PAGES: {
int charsPerPage;
charsPerPage = ((Tk_Width(entryPtr->tkwin)
- 2 * entryPtr->inset - entryPtr->xWidth)
/ entryPtr->avgWidth) - 2;
if (charsPerPage < 1) {
charsPerPage = 1;
}
index += count * charsPerPage;
break;
}
case TK_SCROLL_UNITS:
index += count;
break;
}
}
if (index + 1 >= entryPtr->numChars + 1) {
index = entryPtr->numChars - 1;
}
if (index == TCL_INDEX_NONE) {
index = 0;
}
entryPtr->leftIndex = index;
entryPtr->flags |= UPDATE_SCROLLBAR;
EntryComputeGeometry(entryPtr);
EventuallyRedraw(entryPtr);
break;
}
}
done:
Tcl_Release(entryPtr);
return result;
error:
Tcl_Release(entryPtr);
return TCL_ERROR;
}
/*
*---------------------------------------------------------------------------
*
* GetSpinboxElement --
*
* Return the element associated with an x,y coord.
*
* Results:
* Element type as enum selelement.
*
* Side effects:
* None.
*
*---------------------------------------------------------------------------
*/
static int
GetSpinboxElement(
Spinbox *sbPtr, /* Spinbox for which the index is being
* specified. */
int x, int y) /* Widget-relative coordinates. */
{
Entry *entryPtr = (Entry *) sbPtr;
if ((x < 0) || (y < 0) || (y > Tk_Height(entryPtr->tkwin))
|| (x > Tk_Width(entryPtr->tkwin))) {
return SEL_NONE;
}
if (x > (Tk_Width(entryPtr->tkwin) - entryPtr->inset - entryPtr->xWidth)) {
if (y > (Tk_Height(entryPtr->tkwin) / 2)) {
return SEL_BUTTONDOWN;
} else {
return SEL_BUTTONUP;
}
}
return SEL_ENTRY;
}
/*
*--------------------------------------------------------------
*
* SpinboxInvoke --
*
* This function is invoked when the invoke method for the widget is
* called.
*
* Results:
* TCL_OK.
*
* Side effects:
* A background error condition may arise when invoking the callback.
* The widget value may change.
*
*--------------------------------------------------------------
*/
static int
SpinboxInvoke(
Tcl_Interp *interp,/* Current interpreter. */
Spinbox *sbPtr, /* Spinbox to invoke. */
int element) /* Element to invoke, either the "up" or
* "down" button. */
{
Entry *entryPtr = (Entry *) sbPtr;
const char *type;
int code, up;
Tcl_DString script;
switch (element) {
case SEL_BUTTONUP:
type = "up";
up = 1;
break;
case SEL_BUTTONDOWN:
type = "down";
up = 0;
break;
default:
return TCL_OK;
}
code = TCL_OK;
if (fabs(sbPtr->increment) > MIN_DBL_VAL) {
if (sbPtr->listObj != NULL) {
Tcl_Obj *objPtr;
Tcl_ListObjIndex(interp, sbPtr->listObj, sbPtr->eIndex, &objPtr);
if (strcmp(Tcl_GetString(objPtr), entryPtr->string)) {
/*
* Somehow the string changed from what we expected, so let's
* do a search on the list to see if the current value is
* there. If not, move to the first element of the list.
*/
int i, listc;
TkSizeT elemLen, length = entryPtr->numChars;
const char *bytes;
Tcl_Obj **listv;
Tcl_ListObjGetElements(interp, sbPtr->listObj, &listc, &listv);
for (i = 0; i < listc; i++) {
bytes = Tcl_GetStringFromObj(listv[i], &elemLen);
if ((length == elemLen) &&
(memcmp(bytes, entryPtr->string,
length) == 0)) {
sbPtr->eIndex = i;
break;
}
}
}
if (up) {
if (++sbPtr->eIndex >= sbPtr->nElements) {
if (sbPtr->wrap) {
sbPtr->eIndex = 0;
} else {
sbPtr->eIndex = sbPtr->nElements-1;
}
}
} else {
if (--sbPtr->eIndex < 0) {
if (sbPtr->wrap) {
sbPtr->eIndex = sbPtr->nElements-1;
} else {
sbPtr->eIndex = 0;
}
}
}
Tcl_ListObjIndex(interp, sbPtr->listObj, sbPtr->eIndex, &objPtr);
code = EntryValueChanged(entryPtr, Tcl_GetString(objPtr));
} else if (!DOUBLES_EQ(sbPtr->fromValue, sbPtr->toValue)) {
double dvalue;
if (sscanf(entryPtr->string, "%lf", &dvalue) <= 0) {
/*
* If the string doesn't scan as a double value, just
* use the -from value
*/
dvalue = sbPtr->fromValue;
} else if (up) {
dvalue += sbPtr->increment;
if (dvalue > sbPtr->toValue) {
if (sbPtr->wrap) {
dvalue = sbPtr->fromValue;
} else {
dvalue = sbPtr->toValue;
}
} else if (dvalue < sbPtr->fromValue) {
/*
* It's possible that when pressing up, we are still less
* than the fromValue, because the user may have
* manipulated the value by hand.
*/
dvalue = sbPtr->fromValue;
}
} else {
dvalue -= sbPtr->increment;
if (dvalue < sbPtr->fromValue) {
if (sbPtr->wrap) {
dvalue = sbPtr->toValue;
} else {
dvalue = sbPtr->fromValue;
}
} else if (dvalue > sbPtr->toValue) {
/*
* It's possible that when pressing down, we are still
* greater than the toValue, because the user may have
* manipulated the value by hand.
*/
dvalue = sbPtr->toValue;
}
}
sprintf(sbPtr->formatBuf, sbPtr->valueFormat, dvalue);
code = EntryValueChanged(entryPtr, sbPtr->formatBuf);
}
}
if (code != TCL_OK) {
return TCL_ERROR;
}
if (sbPtr->command != NULL) {
Tcl_DStringInit(&script);
ExpandPercents(entryPtr, sbPtr->command, type, "", 0,
VALIDATE_BUTTON, &script);
Tcl_DStringAppend(&script, "", 1);
code = Tcl_EvalEx(interp, Tcl_DStringValue(&script), -1,
TCL_EVAL_GLOBAL | TCL_EVAL_DIRECT);
Tcl_DStringFree(&script);
if (code != TCL_OK) {
Tcl_AddErrorInfo(interp,
"\n (in command executed by spinbox)");
Tcl_BackgroundException(interp, code);
/*
* Yes, it's an error, but a bg one, so we return OK
*/
return TCL_OK;
}
Tcl_ResetResult(interp);
}
return TCL_OK;
}
/*
*----------------------------------------------------------------------
*
* ComputeFormat --
*
* This function is invoked to recompute the "format" fields of a
* spinbox's widget record, which determines how the value of the dial is
* converted to a string.
*
* Results:
* Tcl result code.
*
* Side effects:
* The format fields of the spinbox are modified.
*
*----------------------------------------------------------------------
*/
static int
ComputeFormat(
Spinbox *sbPtr) /* Information about dial widget. */
{
double maxValue, x;
int mostSigDigit, numDigits, leastSigDigit, afterDecimal;
int eDigits, fDigits;
/*
* Compute the displacement from the decimal of the most significant digit
* required for any number in the dial's range.
*/
if (sbPtr->reqFormat) {
sbPtr->valueFormat = sbPtr->reqFormat;
return TCL_OK;
}
maxValue = fabs(sbPtr->fromValue);
x = fabs(sbPtr->toValue);
if (x > maxValue) {
maxValue = x;
}
if (maxValue == 0) {
maxValue = 1;
}
mostSigDigit = (int) floor(log10(maxValue));
if (fabs(sbPtr->increment) > MIN_DBL_VAL) {
/*
* A increment was specified, so use it.
*/
leastSigDigit = (int) floor(log10(sbPtr->increment));
} else {
leastSigDigit = 0;
}
numDigits = mostSigDigit - leastSigDigit + 1;
if (numDigits < 1) {
numDigits = 1;
}
/*
* Compute the number of characters required using "e" format and "f"
* format, and then choose whichever one takes fewer characters.
*/
eDigits = numDigits + 4;
if (numDigits > 1) {
eDigits++; /* Decimal point. */
}
afterDecimal = numDigits - mostSigDigit - 1;
if (afterDecimal < 0) {
afterDecimal = 0;
}
fDigits = (mostSigDigit >= 0) ? mostSigDigit + afterDecimal : afterDecimal;
if (afterDecimal > 0) {
fDigits++; /* Decimal point. */
}
if (mostSigDigit < 0) {
fDigits++; /* Zero to left of decimal point. */
}
if (fDigits <= eDigits) {
sprintf(sbPtr->digitFormat, "%%.%df", afterDecimal);
} else {
sprintf(sbPtr->digitFormat, "%%.%de", numDigits-1);
}
sbPtr->valueFormat = sbPtr->digitFormat;
return TCL_OK;
}
/*
* Local Variables:
* mode: c
* c-basic-offset: 4
* fill-column: 78
* End:
*/
|
490330.c | // SPDX-License-Identifier: GPL-2.0-or-later
/*
* Marvell 88E6xxx SERDES manipulation, via SMI bus
*
* Copyright (c) 2008 Marvell Semiconductor
*
* Copyright (c) 2017 Andrew Lunn <[email protected]>
*/
#include <linux/interrupt.h>
#include <linux/irqdomain.h>
#include <linux/mii.h>
#include "chip.h"
#include "global2.h"
#include "phy.h"
#include "port.h"
#include "serdes.h"
static int mv88e6352_serdes_read(struct mv88e6xxx_chip *chip, int reg,
u16 *val)
{
return mv88e6xxx_phy_page_read(chip, MV88E6352_ADDR_SERDES,
MV88E6352_SERDES_PAGE_FIBER,
reg, val);
}
static int mv88e6352_serdes_write(struct mv88e6xxx_chip *chip, int reg,
u16 val)
{
return mv88e6xxx_phy_page_write(chip, MV88E6352_ADDR_SERDES,
MV88E6352_SERDES_PAGE_FIBER,
reg, val);
}
static int mv88e6390_serdes_read(struct mv88e6xxx_chip *chip,
int lane, int device, int reg, u16 *val)
{
int reg_c45 = MII_ADDR_C45 | device << 16 | reg;
return mv88e6xxx_phy_read(chip, lane, reg_c45, val);
}
static int mv88e6390_serdes_write(struct mv88e6xxx_chip *chip,
int lane, int device, int reg, u16 val)
{
int reg_c45 = MII_ADDR_C45 | device << 16 | reg;
return mv88e6xxx_phy_write(chip, lane, reg_c45, val);
}
static int mv88e6xxx_serdes_pcs_get_state(struct mv88e6xxx_chip *chip,
u16 status, u16 lpa,
struct phylink_link_state *state)
{
if (status & MV88E6390_SGMII_PHY_STATUS_SPD_DPL_VALID) {
state->link = !!(status & MV88E6390_SGMII_PHY_STATUS_LINK);
state->duplex = status &
MV88E6390_SGMII_PHY_STATUS_DUPLEX_FULL ?
DUPLEX_FULL : DUPLEX_HALF;
if (status & MV88E6390_SGMII_PHY_STATUS_TX_PAUSE)
state->pause |= MLO_PAUSE_TX;
if (status & MV88E6390_SGMII_PHY_STATUS_RX_PAUSE)
state->pause |= MLO_PAUSE_RX;
switch (status & MV88E6390_SGMII_PHY_STATUS_SPEED_MASK) {
case MV88E6390_SGMII_PHY_STATUS_SPEED_1000:
if (state->interface == PHY_INTERFACE_MODE_2500BASEX)
state->speed = SPEED_2500;
else
state->speed = SPEED_1000;
break;
case MV88E6390_SGMII_PHY_STATUS_SPEED_100:
state->speed = SPEED_100;
break;
case MV88E6390_SGMII_PHY_STATUS_SPEED_10:
state->speed = SPEED_10;
break;
default:
dev_err(chip->dev, "invalid PHY speed\n");
return -EINVAL;
}
} else {
state->link = false;
}
if (state->interface == PHY_INTERFACE_MODE_2500BASEX)
mii_lpa_mod_linkmode_x(state->lp_advertising, lpa,
ETHTOOL_LINK_MODE_2500baseX_Full_BIT);
else if (state->interface == PHY_INTERFACE_MODE_1000BASEX)
mii_lpa_mod_linkmode_x(state->lp_advertising, lpa,
ETHTOOL_LINK_MODE_1000baseX_Full_BIT);
return 0;
}
int mv88e6352_serdes_power(struct mv88e6xxx_chip *chip, int port, u8 lane,
bool up)
{
u16 val, new_val;
int err;
err = mv88e6352_serdes_read(chip, MII_BMCR, &val);
if (err)
return err;
if (up)
new_val = val & ~BMCR_PDOWN;
else
new_val = val | BMCR_PDOWN;
if (val != new_val)
err = mv88e6352_serdes_write(chip, MII_BMCR, new_val);
return err;
}
int mv88e6352_serdes_pcs_config(struct mv88e6xxx_chip *chip, int port,
u8 lane, unsigned int mode,
phy_interface_t interface,
const unsigned long *advertise)
{
u16 adv, bmcr, val;
bool changed;
int err;
switch (interface) {
case PHY_INTERFACE_MODE_SGMII:
adv = 0x0001;
break;
case PHY_INTERFACE_MODE_1000BASEX:
adv = linkmode_adv_to_mii_adv_x(advertise,
ETHTOOL_LINK_MODE_1000baseX_Full_BIT);
break;
default:
return 0;
}
err = mv88e6352_serdes_read(chip, MII_ADVERTISE, &val);
if (err)
return err;
changed = val != adv;
if (changed) {
err = mv88e6352_serdes_write(chip, MII_ADVERTISE, adv);
if (err)
return err;
}
err = mv88e6352_serdes_read(chip, MII_BMCR, &val);
if (err)
return err;
if (phylink_autoneg_inband(mode))
bmcr = val | BMCR_ANENABLE;
else
bmcr = val & ~BMCR_ANENABLE;
if (bmcr == val)
return changed;
return mv88e6352_serdes_write(chip, MII_BMCR, bmcr);
}
int mv88e6352_serdes_pcs_get_state(struct mv88e6xxx_chip *chip, int port,
u8 lane, struct phylink_link_state *state)
{
u16 lpa, status;
int err;
err = mv88e6352_serdes_read(chip, 0x11, &status);
if (err) {
dev_err(chip->dev, "can't read Serdes PHY status: %d\n", err);
return err;
}
err = mv88e6352_serdes_read(chip, MII_LPA, &lpa);
if (err) {
dev_err(chip->dev, "can't read Serdes PHY LPA: %d\n", err);
return err;
}
return mv88e6xxx_serdes_pcs_get_state(chip, status, lpa, state);
}
int mv88e6352_serdes_pcs_an_restart(struct mv88e6xxx_chip *chip, int port,
u8 lane)
{
u16 bmcr;
int err;
err = mv88e6352_serdes_read(chip, MII_BMCR, &bmcr);
if (err)
return err;
return mv88e6352_serdes_write(chip, MII_BMCR, bmcr | BMCR_ANRESTART);
}
int mv88e6352_serdes_pcs_link_up(struct mv88e6xxx_chip *chip, int port,
u8 lane, int speed, int duplex)
{
u16 val, bmcr;
int err;
err = mv88e6352_serdes_read(chip, MII_BMCR, &val);
if (err)
return err;
bmcr = val & ~(BMCR_SPEED100 | BMCR_FULLDPLX | BMCR_SPEED1000);
switch (speed) {
case SPEED_1000:
bmcr |= BMCR_SPEED1000;
break;
case SPEED_100:
bmcr |= BMCR_SPEED100;
break;
case SPEED_10:
break;
}
if (duplex == DUPLEX_FULL)
bmcr |= BMCR_FULLDPLX;
if (bmcr == val)
return 0;
return mv88e6352_serdes_write(chip, MII_BMCR, bmcr);
}
u8 mv88e6352_serdes_get_lane(struct mv88e6xxx_chip *chip, int port)
{
u8 cmode = chip->ports[port].cmode;
u8 lane = 0;
if ((cmode == MV88E6XXX_PORT_STS_CMODE_100BASEX) ||
(cmode == MV88E6XXX_PORT_STS_CMODE_1000BASEX) ||
(cmode == MV88E6XXX_PORT_STS_CMODE_SGMII))
lane = 0xff; /* Unused */
return lane;
}
static bool mv88e6352_port_has_serdes(struct mv88e6xxx_chip *chip, int port)
{
if (mv88e6xxx_serdes_get_lane(chip, port))
return true;
return false;
}
struct mv88e6352_serdes_hw_stat {
char string[ETH_GSTRING_LEN];
int sizeof_stat;
int reg;
};
static struct mv88e6352_serdes_hw_stat mv88e6352_serdes_hw_stats[] = {
{ "serdes_fibre_rx_error", 16, 21 },
{ "serdes_PRBS_error", 32, 24 },
};
int mv88e6352_serdes_get_sset_count(struct mv88e6xxx_chip *chip, int port)
{
if (mv88e6352_port_has_serdes(chip, port))
return ARRAY_SIZE(mv88e6352_serdes_hw_stats);
return 0;
}
int mv88e6352_serdes_get_strings(struct mv88e6xxx_chip *chip,
int port, uint8_t *data)
{
struct mv88e6352_serdes_hw_stat *stat;
int i;
if (!mv88e6352_port_has_serdes(chip, port))
return 0;
for (i = 0; i < ARRAY_SIZE(mv88e6352_serdes_hw_stats); i++) {
stat = &mv88e6352_serdes_hw_stats[i];
memcpy(data + i * ETH_GSTRING_LEN, stat->string,
ETH_GSTRING_LEN);
}
return ARRAY_SIZE(mv88e6352_serdes_hw_stats);
}
static uint64_t mv88e6352_serdes_get_stat(struct mv88e6xxx_chip *chip,
struct mv88e6352_serdes_hw_stat *stat)
{
u64 val = 0;
u16 reg;
int err;
err = mv88e6352_serdes_read(chip, stat->reg, ®);
if (err) {
dev_err(chip->dev, "failed to read statistic\n");
return 0;
}
val = reg;
if (stat->sizeof_stat == 32) {
err = mv88e6352_serdes_read(chip, stat->reg + 1, ®);
if (err) {
dev_err(chip->dev, "failed to read statistic\n");
return 0;
}
val = val << 16 | reg;
}
return val;
}
int mv88e6352_serdes_get_stats(struct mv88e6xxx_chip *chip, int port,
uint64_t *data)
{
struct mv88e6xxx_port *mv88e6xxx_port = &chip->ports[port];
struct mv88e6352_serdes_hw_stat *stat;
u64 value;
int i;
if (!mv88e6352_port_has_serdes(chip, port))
return 0;
BUILD_BUG_ON(ARRAY_SIZE(mv88e6352_serdes_hw_stats) >
ARRAY_SIZE(mv88e6xxx_port->serdes_stats));
for (i = 0; i < ARRAY_SIZE(mv88e6352_serdes_hw_stats); i++) {
stat = &mv88e6352_serdes_hw_stats[i];
value = mv88e6352_serdes_get_stat(chip, stat);
mv88e6xxx_port->serdes_stats[i] += value;
data[i] = mv88e6xxx_port->serdes_stats[i];
}
return ARRAY_SIZE(mv88e6352_serdes_hw_stats);
}
static void mv88e6352_serdes_irq_link(struct mv88e6xxx_chip *chip, int port)
{
u16 bmsr;
int err;
/* If the link has dropped, we want to know about it. */
err = mv88e6352_serdes_read(chip, MII_BMSR, &bmsr);
if (err) {
dev_err(chip->dev, "can't read Serdes BMSR: %d\n", err);
return;
}
dsa_port_phylink_mac_change(chip->ds, port, !!(bmsr & BMSR_LSTATUS));
}
irqreturn_t mv88e6352_serdes_irq_status(struct mv88e6xxx_chip *chip, int port,
u8 lane)
{
irqreturn_t ret = IRQ_NONE;
u16 status;
int err;
err = mv88e6352_serdes_read(chip, MV88E6352_SERDES_INT_STATUS, &status);
if (err)
return ret;
if (status & MV88E6352_SERDES_INT_LINK_CHANGE) {
ret = IRQ_HANDLED;
mv88e6352_serdes_irq_link(chip, port);
}
return ret;
}
int mv88e6352_serdes_irq_enable(struct mv88e6xxx_chip *chip, int port, u8 lane,
bool enable)
{
u16 val = 0;
if (enable)
val |= MV88E6352_SERDES_INT_LINK_CHANGE;
return mv88e6352_serdes_write(chip, MV88E6352_SERDES_INT_ENABLE, val);
}
unsigned int mv88e6352_serdes_irq_mapping(struct mv88e6xxx_chip *chip, int port)
{
return irq_find_mapping(chip->g2_irq.domain, MV88E6352_SERDES_IRQ);
}
int mv88e6352_serdes_get_regs_len(struct mv88e6xxx_chip *chip, int port)
{
if (!mv88e6352_port_has_serdes(chip, port))
return 0;
return 32 * sizeof(u16);
}
void mv88e6352_serdes_get_regs(struct mv88e6xxx_chip *chip, int port, void *_p)
{
u16 *p = _p;
u16 reg;
int err;
int i;
if (!mv88e6352_port_has_serdes(chip, port))
return;
for (i = 0 ; i < 32; i++) {
err = mv88e6352_serdes_read(chip, i, ®);
if (!err)
p[i] = reg;
}
}
u8 mv88e6341_serdes_get_lane(struct mv88e6xxx_chip *chip, int port)
{
u8 cmode = chip->ports[port].cmode;
u8 lane = 0;
switch (port) {
case 5:
if (cmode == MV88E6XXX_PORT_STS_CMODE_1000BASEX ||
cmode == MV88E6XXX_PORT_STS_CMODE_SGMII ||
cmode == MV88E6XXX_PORT_STS_CMODE_2500BASEX)
lane = MV88E6341_PORT5_LANE;
break;
}
return lane;
}
int mv88e6185_serdes_power(struct mv88e6xxx_chip *chip, int port, u8 lane,
bool up)
{
/* The serdes power can't be controlled on this switch chip but we need
* to supply this function to avoid returning -EOPNOTSUPP in
* mv88e6xxx_serdes_power_up/mv88e6xxx_serdes_power_down
*/
return 0;
}
u8 mv88e6185_serdes_get_lane(struct mv88e6xxx_chip *chip, int port)
{
/* There are no configurable serdes lanes on this switch chip but we
* need to return a non-negative lane number so that callers of
* mv88e6xxx_serdes_get_lane() know this is a serdes port.
*/
switch (chip->ports[port].cmode) {
case MV88E6185_PORT_STS_CMODE_SERDES:
case MV88E6185_PORT_STS_CMODE_1000BASE_X:
return 0;
default:
return -ENODEV;
}
}
int mv88e6185_serdes_pcs_get_state(struct mv88e6xxx_chip *chip, int port,
u8 lane, struct phylink_link_state *state)
{
int err;
u16 status;
err = mv88e6xxx_port_read(chip, port, MV88E6XXX_PORT_STS, &status);
if (err)
return err;
state->link = !!(status & MV88E6XXX_PORT_STS_LINK);
if (state->link) {
state->duplex = status & MV88E6XXX_PORT_STS_DUPLEX ? DUPLEX_FULL : DUPLEX_HALF;
switch (status & MV88E6XXX_PORT_STS_SPEED_MASK) {
case MV88E6XXX_PORT_STS_SPEED_1000:
state->speed = SPEED_1000;
break;
case MV88E6XXX_PORT_STS_SPEED_100:
state->speed = SPEED_100;
break;
case MV88E6XXX_PORT_STS_SPEED_10:
state->speed = SPEED_10;
break;
default:
dev_err(chip->dev, "invalid PHY speed\n");
return -EINVAL;
}
} else {
state->duplex = DUPLEX_UNKNOWN;
state->speed = SPEED_UNKNOWN;
}
return 0;
}
int mv88e6097_serdes_irq_enable(struct mv88e6xxx_chip *chip, int port, u8 lane,
bool enable)
{
u8 cmode = chip->ports[port].cmode;
/* The serdes interrupts are enabled in the G2_INT_MASK register. We
* need to return 0 to avoid returning -EOPNOTSUPP in
* mv88e6xxx_serdes_irq_enable/mv88e6xxx_serdes_irq_disable
*/
switch (cmode) {
case MV88E6185_PORT_STS_CMODE_SERDES:
case MV88E6185_PORT_STS_CMODE_1000BASE_X:
return 0;
}
return -EOPNOTSUPP;
}
static void mv88e6097_serdes_irq_link(struct mv88e6xxx_chip *chip, int port)
{
u16 status;
int err;
err = mv88e6xxx_port_read(chip, port, MV88E6XXX_PORT_STS, &status);
if (err) {
dev_err(chip->dev, "can't read port status: %d\n", err);
return;
}
dsa_port_phylink_mac_change(chip->ds, port, !!(status & MV88E6XXX_PORT_STS_LINK));
}
irqreturn_t mv88e6097_serdes_irq_status(struct mv88e6xxx_chip *chip, int port,
u8 lane)
{
u8 cmode = chip->ports[port].cmode;
switch (cmode) {
case MV88E6185_PORT_STS_CMODE_SERDES:
case MV88E6185_PORT_STS_CMODE_1000BASE_X:
mv88e6097_serdes_irq_link(chip, port);
return IRQ_HANDLED;
}
return IRQ_NONE;
}
u8 mv88e6390_serdes_get_lane(struct mv88e6xxx_chip *chip, int port)
{
u8 cmode = chip->ports[port].cmode;
u8 lane = 0;
switch (port) {
case 9:
if (cmode == MV88E6XXX_PORT_STS_CMODE_1000BASEX ||
cmode == MV88E6XXX_PORT_STS_CMODE_SGMII ||
cmode == MV88E6XXX_PORT_STS_CMODE_2500BASEX)
lane = MV88E6390_PORT9_LANE0;
break;
case 10:
if (cmode == MV88E6XXX_PORT_STS_CMODE_1000BASEX ||
cmode == MV88E6XXX_PORT_STS_CMODE_SGMII ||
cmode == MV88E6XXX_PORT_STS_CMODE_2500BASEX)
lane = MV88E6390_PORT10_LANE0;
break;
}
return lane;
}
u8 mv88e6390x_serdes_get_lane(struct mv88e6xxx_chip *chip, int port)
{
u8 cmode_port = chip->ports[port].cmode;
u8 cmode_port10 = chip->ports[10].cmode;
u8 cmode_port9 = chip->ports[9].cmode;
u8 lane = 0;
switch (port) {
case 2:
if (cmode_port9 == MV88E6XXX_PORT_STS_CMODE_1000BASEX ||
cmode_port9 == MV88E6XXX_PORT_STS_CMODE_SGMII ||
cmode_port9 == MV88E6XXX_PORT_STS_CMODE_2500BASEX)
if (cmode_port == MV88E6XXX_PORT_STS_CMODE_1000BASEX)
lane = MV88E6390_PORT9_LANE1;
break;
case 3:
if (cmode_port9 == MV88E6XXX_PORT_STS_CMODE_1000BASEX ||
cmode_port9 == MV88E6XXX_PORT_STS_CMODE_SGMII ||
cmode_port9 == MV88E6XXX_PORT_STS_CMODE_2500BASEX ||
cmode_port9 == MV88E6XXX_PORT_STS_CMODE_RXAUI)
if (cmode_port == MV88E6XXX_PORT_STS_CMODE_1000BASEX)
lane = MV88E6390_PORT9_LANE2;
break;
case 4:
if (cmode_port9 == MV88E6XXX_PORT_STS_CMODE_1000BASEX ||
cmode_port9 == MV88E6XXX_PORT_STS_CMODE_SGMII ||
cmode_port9 == MV88E6XXX_PORT_STS_CMODE_2500BASEX ||
cmode_port9 == MV88E6XXX_PORT_STS_CMODE_RXAUI)
if (cmode_port == MV88E6XXX_PORT_STS_CMODE_1000BASEX)
lane = MV88E6390_PORT9_LANE3;
break;
case 5:
if (cmode_port10 == MV88E6XXX_PORT_STS_CMODE_1000BASEX ||
cmode_port10 == MV88E6XXX_PORT_STS_CMODE_SGMII ||
cmode_port10 == MV88E6XXX_PORT_STS_CMODE_2500BASEX)
if (cmode_port == MV88E6XXX_PORT_STS_CMODE_1000BASEX)
lane = MV88E6390_PORT10_LANE1;
break;
case 6:
if (cmode_port10 == MV88E6XXX_PORT_STS_CMODE_1000BASEX ||
cmode_port10 == MV88E6XXX_PORT_STS_CMODE_SGMII ||
cmode_port10 == MV88E6XXX_PORT_STS_CMODE_2500BASEX ||
cmode_port10 == MV88E6XXX_PORT_STS_CMODE_RXAUI)
if (cmode_port == MV88E6XXX_PORT_STS_CMODE_1000BASEX)
lane = MV88E6390_PORT10_LANE2;
break;
case 7:
if (cmode_port10 == MV88E6XXX_PORT_STS_CMODE_1000BASEX ||
cmode_port10 == MV88E6XXX_PORT_STS_CMODE_SGMII ||
cmode_port10 == MV88E6XXX_PORT_STS_CMODE_2500BASEX ||
cmode_port10 == MV88E6XXX_PORT_STS_CMODE_RXAUI)
if (cmode_port == MV88E6XXX_PORT_STS_CMODE_1000BASEX)
lane = MV88E6390_PORT10_LANE3;
break;
case 9:
if (cmode_port9 == MV88E6XXX_PORT_STS_CMODE_1000BASEX ||
cmode_port9 == MV88E6XXX_PORT_STS_CMODE_SGMII ||
cmode_port9 == MV88E6XXX_PORT_STS_CMODE_2500BASEX ||
cmode_port9 == MV88E6XXX_PORT_STS_CMODE_XAUI ||
cmode_port9 == MV88E6XXX_PORT_STS_CMODE_RXAUI)
lane = MV88E6390_PORT9_LANE0;
break;
case 10:
if (cmode_port10 == MV88E6XXX_PORT_STS_CMODE_1000BASEX ||
cmode_port10 == MV88E6XXX_PORT_STS_CMODE_SGMII ||
cmode_port10 == MV88E6XXX_PORT_STS_CMODE_2500BASEX ||
cmode_port10 == MV88E6XXX_PORT_STS_CMODE_XAUI ||
cmode_port10 == MV88E6XXX_PORT_STS_CMODE_RXAUI)
lane = MV88E6390_PORT10_LANE0;
break;
}
return lane;
}
/* Set power up/down for 10GBASE-R and 10GBASE-X4/X2 */
static int mv88e6390_serdes_power_10g(struct mv88e6xxx_chip *chip, u8 lane,
bool up)
{
u16 val, new_val;
int err;
err = mv88e6390_serdes_read(chip, lane, MDIO_MMD_PHYXS,
MV88E6390_10G_CTRL1, &val);
if (err)
return err;
if (up)
new_val = val & ~(MDIO_CTRL1_RESET |
MDIO_PCS_CTRL1_LOOPBACK |
MDIO_CTRL1_LPOWER);
else
new_val = val | MDIO_CTRL1_LPOWER;
if (val != new_val)
err = mv88e6390_serdes_write(chip, lane, MDIO_MMD_PHYXS,
MV88E6390_10G_CTRL1, new_val);
return err;
}
/* Set power up/down for SGMII and 1000Base-X */
static int mv88e6390_serdes_power_sgmii(struct mv88e6xxx_chip *chip, u8 lane,
bool up)
{
u16 val, new_val;
int err;
err = mv88e6390_serdes_read(chip, lane, MDIO_MMD_PHYXS,
MV88E6390_SGMII_BMCR, &val);
if (err)
return err;
if (up)
new_val = val & ~(BMCR_RESET | BMCR_LOOPBACK | BMCR_PDOWN);
else
new_val = val | BMCR_PDOWN;
if (val != new_val)
err = mv88e6390_serdes_write(chip, lane, MDIO_MMD_PHYXS,
MV88E6390_SGMII_BMCR, new_val);
return err;
}
struct mv88e6390_serdes_hw_stat {
char string[ETH_GSTRING_LEN];
int reg;
};
static struct mv88e6390_serdes_hw_stat mv88e6390_serdes_hw_stats[] = {
{ "serdes_rx_pkts", 0xf021 },
{ "serdes_rx_bytes", 0xf024 },
{ "serdes_rx_pkts_error", 0xf027 },
};
int mv88e6390_serdes_get_sset_count(struct mv88e6xxx_chip *chip, int port)
{
if (mv88e6390_serdes_get_lane(chip, port) == 0)
return 0;
return ARRAY_SIZE(mv88e6390_serdes_hw_stats);
}
int mv88e6390_serdes_get_strings(struct mv88e6xxx_chip *chip,
int port, uint8_t *data)
{
struct mv88e6390_serdes_hw_stat *stat;
int i;
if (mv88e6390_serdes_get_lane(chip, port) == 0)
return 0;
for (i = 0; i < ARRAY_SIZE(mv88e6390_serdes_hw_stats); i++) {
stat = &mv88e6390_serdes_hw_stats[i];
memcpy(data + i * ETH_GSTRING_LEN, stat->string,
ETH_GSTRING_LEN);
}
return ARRAY_SIZE(mv88e6390_serdes_hw_stats);
}
static uint64_t mv88e6390_serdes_get_stat(struct mv88e6xxx_chip *chip, int lane,
struct mv88e6390_serdes_hw_stat *stat)
{
u16 reg[3];
int err, i;
for (i = 0; i < 3; i++) {
err = mv88e6390_serdes_read(chip, lane, MDIO_MMD_PHYXS,
stat->reg + i, ®[i]);
if (err) {
dev_err(chip->dev, "failed to read statistic\n");
return 0;
}
}
return reg[0] | ((u64)reg[1] << 16) | ((u64)reg[2] << 32);
}
int mv88e6390_serdes_get_stats(struct mv88e6xxx_chip *chip, int port,
uint64_t *data)
{
struct mv88e6390_serdes_hw_stat *stat;
int lane;
int i;
lane = mv88e6390_serdes_get_lane(chip, port);
if (lane == 0)
return 0;
for (i = 0; i < ARRAY_SIZE(mv88e6390_serdes_hw_stats); i++) {
stat = &mv88e6390_serdes_hw_stats[i];
data[i] = mv88e6390_serdes_get_stat(chip, lane, stat);
}
return ARRAY_SIZE(mv88e6390_serdes_hw_stats);
}
static int mv88e6390_serdes_enable_checker(struct mv88e6xxx_chip *chip, u8 lane)
{
u16 reg;
int err;
err = mv88e6390_serdes_read(chip, lane, MDIO_MMD_PHYXS,
MV88E6390_PG_CONTROL, ®);
if (err)
return err;
reg |= MV88E6390_PG_CONTROL_ENABLE_PC;
return mv88e6390_serdes_write(chip, lane, MDIO_MMD_PHYXS,
MV88E6390_PG_CONTROL, reg);
}
int mv88e6390_serdes_power(struct mv88e6xxx_chip *chip, int port, u8 lane,
bool up)
{
u8 cmode = chip->ports[port].cmode;
int err = 0;
switch (cmode) {
case MV88E6XXX_PORT_STS_CMODE_SGMII:
case MV88E6XXX_PORT_STS_CMODE_1000BASEX:
case MV88E6XXX_PORT_STS_CMODE_2500BASEX:
err = mv88e6390_serdes_power_sgmii(chip, lane, up);
break;
case MV88E6XXX_PORT_STS_CMODE_XAUI:
case MV88E6XXX_PORT_STS_CMODE_RXAUI:
err = mv88e6390_serdes_power_10g(chip, lane, up);
break;
}
if (!err && up)
err = mv88e6390_serdes_enable_checker(chip, lane);
return err;
}
int mv88e6390_serdes_pcs_config(struct mv88e6xxx_chip *chip, int port,
u8 lane, unsigned int mode,
phy_interface_t interface,
const unsigned long *advertise)
{
u16 val, bmcr, adv;
bool changed;
int err;
switch (interface) {
case PHY_INTERFACE_MODE_SGMII:
adv = 0x0001;
break;
case PHY_INTERFACE_MODE_1000BASEX:
adv = linkmode_adv_to_mii_adv_x(advertise,
ETHTOOL_LINK_MODE_1000baseX_Full_BIT);
break;
case PHY_INTERFACE_MODE_2500BASEX:
adv = linkmode_adv_to_mii_adv_x(advertise,
ETHTOOL_LINK_MODE_2500baseX_Full_BIT);
break;
default:
return 0;
}
err = mv88e6390_serdes_read(chip, lane, MDIO_MMD_PHYXS,
MV88E6390_SGMII_ADVERTISE, &val);
if (err)
return err;
changed = val != adv;
if (changed) {
err = mv88e6390_serdes_write(chip, lane, MDIO_MMD_PHYXS,
MV88E6390_SGMII_ADVERTISE, adv);
if (err)
return err;
}
err = mv88e6390_serdes_read(chip, lane, MDIO_MMD_PHYXS,
MV88E6390_SGMII_BMCR, &val);
if (err)
return err;
if (phylink_autoneg_inband(mode))
bmcr = val | BMCR_ANENABLE;
else
bmcr = val & ~BMCR_ANENABLE;
/* setting ANENABLE triggers a restart of negotiation */
if (bmcr == val)
return changed;
return mv88e6390_serdes_write(chip, lane, MDIO_MMD_PHYXS,
MV88E6390_SGMII_BMCR, bmcr);
}
static int mv88e6390_serdes_pcs_get_state_sgmii(struct mv88e6xxx_chip *chip,
int port, u8 lane, struct phylink_link_state *state)
{
u16 lpa, status;
int err;
err = mv88e6390_serdes_read(chip, lane, MDIO_MMD_PHYXS,
MV88E6390_SGMII_PHY_STATUS, &status);
if (err) {
dev_err(chip->dev, "can't read Serdes PHY status: %d\n", err);
return err;
}
err = mv88e6390_serdes_read(chip, lane, MDIO_MMD_PHYXS,
MV88E6390_SGMII_LPA, &lpa);
if (err) {
dev_err(chip->dev, "can't read Serdes PHY LPA: %d\n", err);
return err;
}
return mv88e6xxx_serdes_pcs_get_state(chip, status, lpa, state);
}
static int mv88e6390_serdes_pcs_get_state_10g(struct mv88e6xxx_chip *chip,
int port, u8 lane, struct phylink_link_state *state)
{
u16 status;
int err;
err = mv88e6390_serdes_read(chip, lane, MDIO_MMD_PHYXS,
MV88E6390_10G_STAT1, &status);
if (err)
return err;
state->link = !!(status & MDIO_STAT1_LSTATUS);
if (state->link) {
state->speed = SPEED_10000;
state->duplex = DUPLEX_FULL;
}
return 0;
}
int mv88e6390_serdes_pcs_get_state(struct mv88e6xxx_chip *chip, int port,
u8 lane, struct phylink_link_state *state)
{
switch (state->interface) {
case PHY_INTERFACE_MODE_SGMII:
case PHY_INTERFACE_MODE_1000BASEX:
case PHY_INTERFACE_MODE_2500BASEX:
return mv88e6390_serdes_pcs_get_state_sgmii(chip, port, lane,
state);
case PHY_INTERFACE_MODE_XAUI:
case PHY_INTERFACE_MODE_RXAUI:
return mv88e6390_serdes_pcs_get_state_10g(chip, port, lane,
state);
default:
return -EOPNOTSUPP;
}
}
int mv88e6390_serdes_pcs_an_restart(struct mv88e6xxx_chip *chip, int port,
u8 lane)
{
u16 bmcr;
int err;
err = mv88e6390_serdes_read(chip, lane, MDIO_MMD_PHYXS,
MV88E6390_SGMII_BMCR, &bmcr);
if (err)
return err;
return mv88e6390_serdes_write(chip, lane, MDIO_MMD_PHYXS,
MV88E6390_SGMII_BMCR,
bmcr | BMCR_ANRESTART);
}
int mv88e6390_serdes_pcs_link_up(struct mv88e6xxx_chip *chip, int port,
u8 lane, int speed, int duplex)
{
u16 val, bmcr;
int err;
err = mv88e6390_serdes_read(chip, lane, MDIO_MMD_PHYXS,
MV88E6390_SGMII_BMCR, &val);
if (err)
return err;
bmcr = val & ~(BMCR_SPEED100 | BMCR_FULLDPLX | BMCR_SPEED1000);
switch (speed) {
case SPEED_2500:
case SPEED_1000:
bmcr |= BMCR_SPEED1000;
break;
case SPEED_100:
bmcr |= BMCR_SPEED100;
break;
case SPEED_10:
break;
}
if (duplex == DUPLEX_FULL)
bmcr |= BMCR_FULLDPLX;
if (bmcr == val)
return 0;
return mv88e6390_serdes_write(chip, lane, MDIO_MMD_PHYXS,
MV88E6390_SGMII_BMCR, bmcr);
}
static void mv88e6390_serdes_irq_link_sgmii(struct mv88e6xxx_chip *chip,
int port, u8 lane)
{
u16 bmsr;
int err;
/* If the link has dropped, we want to know about it. */
err = mv88e6390_serdes_read(chip, lane, MDIO_MMD_PHYXS,
MV88E6390_SGMII_BMSR, &bmsr);
if (err) {
dev_err(chip->dev, "can't read Serdes BMSR: %d\n", err);
return;
}
dsa_port_phylink_mac_change(chip->ds, port, !!(bmsr & BMSR_LSTATUS));
}
static int mv88e6390_serdes_irq_enable_sgmii(struct mv88e6xxx_chip *chip,
u8 lane, bool enable)
{
u16 val = 0;
if (enable)
val |= MV88E6390_SGMII_INT_LINK_DOWN |
MV88E6390_SGMII_INT_LINK_UP;
return mv88e6390_serdes_write(chip, lane, MDIO_MMD_PHYXS,
MV88E6390_SGMII_INT_ENABLE, val);
}
int mv88e6390_serdes_irq_enable(struct mv88e6xxx_chip *chip, int port, u8 lane,
bool enable)
{
u8 cmode = chip->ports[port].cmode;
switch (cmode) {
case MV88E6XXX_PORT_STS_CMODE_SGMII:
case MV88E6XXX_PORT_STS_CMODE_1000BASEX:
case MV88E6XXX_PORT_STS_CMODE_2500BASEX:
return mv88e6390_serdes_irq_enable_sgmii(chip, lane, enable);
}
return 0;
}
static int mv88e6390_serdes_irq_status_sgmii(struct mv88e6xxx_chip *chip,
u8 lane, u16 *status)
{
int err;
err = mv88e6390_serdes_read(chip, lane, MDIO_MMD_PHYXS,
MV88E6390_SGMII_INT_STATUS, status);
return err;
}
irqreturn_t mv88e6390_serdes_irq_status(struct mv88e6xxx_chip *chip, int port,
u8 lane)
{
u8 cmode = chip->ports[port].cmode;
irqreturn_t ret = IRQ_NONE;
u16 status;
int err;
switch (cmode) {
case MV88E6XXX_PORT_STS_CMODE_SGMII:
case MV88E6XXX_PORT_STS_CMODE_1000BASEX:
case MV88E6XXX_PORT_STS_CMODE_2500BASEX:
err = mv88e6390_serdes_irq_status_sgmii(chip, lane, &status);
if (err)
return ret;
if (status & (MV88E6390_SGMII_INT_LINK_DOWN |
MV88E6390_SGMII_INT_LINK_UP)) {
ret = IRQ_HANDLED;
mv88e6390_serdes_irq_link_sgmii(chip, port, lane);
}
}
return ret;
}
unsigned int mv88e6390_serdes_irq_mapping(struct mv88e6xxx_chip *chip, int port)
{
return irq_find_mapping(chip->g2_irq.domain, port);
}
static const u16 mv88e6390_serdes_regs[] = {
/* SERDES common registers */
0xf00a, 0xf00b, 0xf00c,
0xf010, 0xf011, 0xf012, 0xf013,
0xf016, 0xf017, 0xf018,
0xf01b, 0xf01c, 0xf01d, 0xf01e, 0xf01f,
0xf020, 0xf021, 0xf022, 0xf023, 0xf024, 0xf025, 0xf026, 0xf027,
0xf028, 0xf029,
0xf030, 0xf031, 0xf032, 0xf033, 0xf034, 0xf035, 0xf036, 0xf037,
0xf038, 0xf039,
/* SGMII */
0x2000, 0x2001, 0x2002, 0x2003, 0x2004, 0x2005, 0x2006, 0x2007,
0x2008,
0x200f,
0xa000, 0xa001, 0xa002, 0xa003,
/* 10Gbase-X */
0x1000, 0x1001, 0x1002, 0x1003, 0x1004, 0x1005, 0x1006, 0x1007,
0x1008,
0x100e, 0x100f,
0x1018, 0x1019,
0x9000, 0x9001, 0x9002, 0x9003, 0x9004,
0x9006,
0x9010, 0x9011, 0x9012, 0x9013, 0x9014, 0x9015, 0x9016,
/* 10Gbase-R */
0x1020, 0x1021, 0x1022, 0x1023, 0x1024, 0x1025, 0x1026, 0x1027,
0x1028, 0x1029, 0x102a, 0x102b,
};
int mv88e6390_serdes_get_regs_len(struct mv88e6xxx_chip *chip, int port)
{
if (mv88e6xxx_serdes_get_lane(chip, port) == 0)
return 0;
return ARRAY_SIZE(mv88e6390_serdes_regs) * sizeof(u16);
}
void mv88e6390_serdes_get_regs(struct mv88e6xxx_chip *chip, int port, void *_p)
{
u16 *p = _p;
int lane;
u16 reg;
int err;
int i;
lane = mv88e6xxx_serdes_get_lane(chip, port);
if (lane == 0)
return;
for (i = 0 ; i < ARRAY_SIZE(mv88e6390_serdes_regs); i++) {
err = mv88e6390_serdes_read(chip, lane, MDIO_MMD_PHYXS,
mv88e6390_serdes_regs[i], ®);
if (!err)
p[i] = reg;
}
}
|
905748.c | /*
* Samsung EXYNOS4x12 FIMC-IS (Imaging Subsystem) driver
*
* Copyright (C) 2012 - 2013 Samsung Electronics Co., Ltd.
*
* Authors: Younghwan Joo <[email protected]>
* Sylwester Nawrocki <[email protected]>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
#include <linux/delay.h>
#include "fimc-is.h"
#include "fimc-is-command.h"
#include "fimc-is-regs.h"
#include "fimc-is-sensor.h"
void fimc_is_fw_clear_irq1(struct fimc_is *is, unsigned int nr)
{
mcuctl_write(1UL << nr, is, MCUCTL_REG_INTCR1);
}
void fimc_is_fw_clear_irq2(struct fimc_is *is)
{
u32 cfg = mcuctl_read(is, MCUCTL_REG_INTSR2);
mcuctl_write(cfg, is, MCUCTL_REG_INTCR2);
}
void fimc_is_hw_set_intgr0_gd0(struct fimc_is *is)
{
mcuctl_write(INTGR0_INTGD(0), is, MCUCTL_REG_INTGR0);
}
int fimc_is_hw_wait_intmsr0_intmsd0(struct fimc_is *is)
{
unsigned int timeout = 2000;
u32 cfg, status;
do {
cfg = mcuctl_read(is, MCUCTL_REG_INTMSR0);
status = INTMSR0_GET_INTMSD(0, cfg);
if (--timeout == 0) {
dev_warn(&is->pdev->dev, "%s timeout\n",
__func__);
return -ETIMEDOUT;
}
udelay(1);
} while (status != 0);
return 0;
}
int fimc_is_hw_set_param(struct fimc_is *is)
{
struct chain_config *config = &is->config[is->config_index];
unsigned int param_count = __get_pending_param_count(is);
fimc_is_hw_wait_intmsr0_intmsd0(is);
mcuctl_write(HIC_SET_PARAMETER, is, MCUCTL_REG_ISSR(0));
mcuctl_write(is->sensor_index, is, MCUCTL_REG_ISSR(1));
mcuctl_write(is->config_index, is, MCUCTL_REG_ISSR(2));
mcuctl_write(param_count, is, MCUCTL_REG_ISSR(3));
mcuctl_write(config->p_region_index[0], is, MCUCTL_REG_ISSR(4));
mcuctl_write(config->p_region_index[1], is, MCUCTL_REG_ISSR(5));
fimc_is_hw_set_intgr0_gd0(is);
return 0;
}
static int __maybe_unused fimc_is_hw_set_tune(struct fimc_is *is)
{
fimc_is_hw_wait_intmsr0_intmsd0(is);
mcuctl_write(HIC_SET_TUNE, is, MCUCTL_REG_ISSR(0));
mcuctl_write(is->sensor_index, is, MCUCTL_REG_ISSR(1));
mcuctl_write(is->h2i_cmd.entry_id, is, MCUCTL_REG_ISSR(2));
fimc_is_hw_set_intgr0_gd0(is);
return 0;
}
#define FIMC_IS_MAX_PARAMS 4
int fimc_is_hw_get_params(struct fimc_is *is, unsigned int num_args)
{
int i;
if (num_args > FIMC_IS_MAX_PARAMS)
return -EINVAL;
is->i2h_cmd.num_args = num_args;
for (i = 0; i < FIMC_IS_MAX_PARAMS; i++) {
if (i < num_args)
is->i2h_cmd.args[i] = mcuctl_read(is,
MCUCTL_REG_ISSR(12 + i));
else
is->i2h_cmd.args[i] = 0;
}
return 0;
}
void fimc_is_hw_set_isp_buf_mask(struct fimc_is *is, unsigned int mask)
{
if (hweight32(mask) == 1) {
dev_err(&is->pdev->dev, "%s(): not enough buffers (mask %#x)\n",
__func__, mask);
return;
}
if (mcuctl_read(is, MCUCTL_REG_ISSR(23)) != 0)
dev_dbg(&is->pdev->dev, "non-zero DMA buffer mask\n");
mcuctl_write(mask, is, MCUCTL_REG_ISSR(23));
}
void fimc_is_hw_set_sensor_num(struct fimc_is *is)
{
pr_debug("setting sensor index to: %d\n", is->sensor_index);
mcuctl_write(IH_REPLY_DONE, is, MCUCTL_REG_ISSR(0));
mcuctl_write(is->sensor_index, is, MCUCTL_REG_ISSR(1));
mcuctl_write(IHC_GET_SENSOR_NUM, is, MCUCTL_REG_ISSR(2));
mcuctl_write(FIMC_IS_SENSORS_NUM, is, MCUCTL_REG_ISSR(3));
}
void fimc_is_hw_close_sensor(struct fimc_is *is, unsigned int index)
{
if (is->sensor_index != index)
return;
fimc_is_hw_wait_intmsr0_intmsd0(is);
mcuctl_write(HIC_CLOSE_SENSOR, is, MCUCTL_REG_ISSR(0));
mcuctl_write(is->sensor_index, is, MCUCTL_REG_ISSR(1));
mcuctl_write(is->sensor_index, is, MCUCTL_REG_ISSR(2));
fimc_is_hw_set_intgr0_gd0(is);
}
void fimc_is_hw_get_setfile_addr(struct fimc_is *is)
{
fimc_is_hw_wait_intmsr0_intmsd0(is);
mcuctl_write(HIC_GET_SET_FILE_ADDR, is, MCUCTL_REG_ISSR(0));
mcuctl_write(is->sensor_index, is, MCUCTL_REG_ISSR(1));
fimc_is_hw_set_intgr0_gd0(is);
}
void fimc_is_hw_load_setfile(struct fimc_is *is)
{
fimc_is_hw_wait_intmsr0_intmsd0(is);
mcuctl_write(HIC_LOAD_SET_FILE, is, MCUCTL_REG_ISSR(0));
mcuctl_write(is->sensor_index, is, MCUCTL_REG_ISSR(1));
fimc_is_hw_set_intgr0_gd0(is);
}
int fimc_is_hw_change_mode(struct fimc_is *is)
{
static const u8 cmd[] = {
HIC_PREVIEW_STILL, HIC_PREVIEW_VIDEO,
HIC_CAPTURE_STILL, HIC_CAPTURE_VIDEO,
};
if (WARN_ON(is->config_index >= ARRAY_SIZE(cmd)))
return -EINVAL;
mcuctl_write(cmd[is->config_index], is, MCUCTL_REG_ISSR(0));
mcuctl_write(is->sensor_index, is, MCUCTL_REG_ISSR(1));
mcuctl_write(is->setfile.sub_index, is, MCUCTL_REG_ISSR(2));
fimc_is_hw_set_intgr0_gd0(is);
return 0;
}
void fimc_is_hw_stream_on(struct fimc_is *is)
{
fimc_is_hw_wait_intmsr0_intmsd0(is);
mcuctl_write(HIC_STREAM_ON, is, MCUCTL_REG_ISSR(0));
mcuctl_write(is->sensor_index, is, MCUCTL_REG_ISSR(1));
mcuctl_write(0, is, MCUCTL_REG_ISSR(2));
fimc_is_hw_set_intgr0_gd0(is);
}
void fimc_is_hw_stream_off(struct fimc_is *is)
{
fimc_is_hw_wait_intmsr0_intmsd0(is);
mcuctl_write(HIC_STREAM_OFF, is, MCUCTL_REG_ISSR(0));
mcuctl_write(is->sensor_index, is, MCUCTL_REG_ISSR(1));
fimc_is_hw_set_intgr0_gd0(is);
}
void fimc_is_hw_subip_power_off(struct fimc_is *is)
{
fimc_is_hw_wait_intmsr0_intmsd0(is);
mcuctl_write(HIC_POWER_DOWN, is, MCUCTL_REG_ISSR(0));
mcuctl_write(is->sensor_index, is, MCUCTL_REG_ISSR(1));
fimc_is_hw_set_intgr0_gd0(is);
}
int fimc_is_itf_s_param(struct fimc_is *is, bool update)
{
int ret;
if (update)
__is_hw_update_params(is);
fimc_is_mem_barrier();
clear_bit(IS_ST_BLOCK_CMD_CLEARED, &is->state);
fimc_is_hw_set_param(is);
ret = fimc_is_wait_event(is, IS_ST_BLOCK_CMD_CLEARED, 1,
FIMC_IS_CONFIG_TIMEOUT);
if (ret < 0)
dev_err(&is->pdev->dev, "%s() timeout\n", __func__);
return ret;
}
int fimc_is_itf_mode_change(struct fimc_is *is)
{
int ret;
clear_bit(IS_ST_CHANGE_MODE, &is->state);
fimc_is_hw_change_mode(is);
ret = fimc_is_wait_event(is, IS_ST_CHANGE_MODE, 1,
FIMC_IS_CONFIG_TIMEOUT);
if (ret < 0)
dev_err(&is->pdev->dev, "%s(): mode change (%d) timeout\n",
__func__, is->config_index);
return ret;
}
|
739451.c | /*
* Format register and lookup
* Copyright (c) 2000, 2001, 2002 Fabrice Bellard
*
* 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 "libavutil/atomic.h"
#include "libavutil/avstring.h"
#include "libavutil/bprint.h"
#include "libavutil/opt.h"
#include "avio_internal.h"
#include "avformat.h"
#include "id3v2.h"
#include "internal.h"
/**
* @file
* Format register and lookup
*/
/** head of registered input format linked list */
static AVInputFormat *first_iformat = NULL;
/** head of registered output format linked list */
static AVOutputFormat *first_oformat = NULL;
static AVInputFormat **last_iformat = &first_iformat;
static AVOutputFormat **last_oformat = &first_oformat;
AVInputFormat *av_iformat_next(const AVInputFormat *f)
{
if (f)
return f->next;
else
return first_iformat;
}
AVOutputFormat *av_oformat_next(const AVOutputFormat *f)
{
if (f)
return f->next;
else
return first_oformat;
}
void av_register_input_format(AVInputFormat *format)
{
AVInputFormat **p = last_iformat;
format->next = NULL;
while(*p || avpriv_atomic_ptr_cas((void * volatile *)p, NULL, format))
p = &(*p)->next;
last_iformat = &format->next;
}
void av_register_output_format(AVOutputFormat *format)
{
AVOutputFormat **p = last_oformat;
format->next = NULL;
while(*p || avpriv_atomic_ptr_cas((void * volatile *)p, NULL, format))
p = &(*p)->next;
last_oformat = &format->next;
}
int av_match_ext(const char *filename, const char *extensions)
{
const char *ext;
if (!filename)
return 0;
ext = strrchr(filename, '.');
if (ext)
return av_match_name(ext + 1, extensions);
return 0;
}
AVOutputFormat *av_guess_format(const char *short_name, const char *filename,
const char *mime_type)
{
AVOutputFormat *fmt = NULL, *fmt_found;
int score_max, score;
/* specific test for image sequences */
#if CONFIG_IMAGE2_MUXER
if (!short_name && filename &&
av_filename_number_test(filename) &&
ff_guess_image2_codec(filename) != AV_CODEC_ID_NONE) {
return av_guess_format("image2", NULL, NULL);
}
#endif
/* Find the proper file type. */
fmt_found = NULL;
score_max = 0;
while ((fmt = av_oformat_next(fmt))) {
score = 0;
if (fmt->name && short_name && av_match_name(short_name, fmt->name))
score += 100;
if (fmt->mime_type && mime_type && !strcmp(fmt->mime_type, mime_type))
score += 10;
if (filename && fmt->extensions &&
av_match_ext(filename, fmt->extensions)) {
score += 5;
}
if (score > score_max) {
score_max = score;
fmt_found = fmt;
}
}
return fmt_found;
}
enum AVCodecID av_guess_codec(AVOutputFormat *fmt, const char *short_name,
const char *filename, const char *mime_type,
enum AVMediaType type)
{
if (av_match_name("segment", fmt->name) || av_match_name("ssegment", fmt->name)) {
AVOutputFormat *fmt2 = av_guess_format(NULL, filename, NULL);
if (fmt2)
fmt = fmt2;
}
if (type == AVMEDIA_TYPE_VIDEO) {
enum AVCodecID codec_id = AV_CODEC_ID_NONE;
#if CONFIG_IMAGE2_MUXER
if (!strcmp(fmt->name, "image2") || !strcmp(fmt->name, "image2pipe")) {
codec_id = ff_guess_image2_codec(filename);
}
#endif
if (codec_id == AV_CODEC_ID_NONE)
codec_id = fmt->video_codec;
return codec_id;
} else if (type == AVMEDIA_TYPE_AUDIO)
return fmt->audio_codec;
else if (type == AVMEDIA_TYPE_SUBTITLE)
return fmt->subtitle_codec;
else
return AV_CODEC_ID_NONE;
}
AVInputFormat *av_find_input_format(const char *short_name)
{
AVInputFormat *fmt = NULL;
while ((fmt = av_iformat_next(fmt)))
if (av_match_name(short_name, fmt->name))
return fmt;
return NULL;
}
AVInputFormat *av_probe_input_format3(AVProbeData *pd, int is_opened,
int *score_ret)
{
AVProbeData lpd = *pd;
AVInputFormat *fmt1 = NULL, *fmt;
int score, nodat = 0, score_max = 0;
const static uint8_t zerobuffer[AVPROBE_PADDING_SIZE];
if (!lpd.buf)
lpd.buf = zerobuffer;
if (lpd.buf_size > 10 && ff_id3v2_match(lpd.buf, ID3v2_DEFAULT_MAGIC)) {
int id3len = ff_id3v2_tag_len(lpd.buf);
if (lpd.buf_size > id3len + 16) {
lpd.buf += id3len;
lpd.buf_size -= id3len;
} else if (id3len >= PROBE_BUF_MAX) {
nodat = 2;
} else
nodat = 1;
}
fmt = NULL;
while ((fmt1 = av_iformat_next(fmt1))) {
if (!is_opened == !(fmt1->flags & AVFMT_NOFILE) && strcmp(fmt1->name, "image2"))
continue;
score = 0;
if (fmt1->read_probe) {
score = fmt1->read_probe(&lpd);
if (fmt1->extensions && av_match_ext(lpd.filename, fmt1->extensions)) {
if (nodat == 0) score = FFMAX(score, 1);
else if (nodat == 1) score = FFMAX(score, AVPROBE_SCORE_EXTENSION / 2 - 1);
else score = FFMAX(score, AVPROBE_SCORE_EXTENSION);
}
} else if (fmt1->extensions) {
if (av_match_ext(lpd.filename, fmt1->extensions))
score = AVPROBE_SCORE_EXTENSION;
}
if (av_match_name(lpd.mime_type, fmt1->mime_type))
score = FFMAX(score, AVPROBE_SCORE_MIME);
if (score > score_max) {
score_max = score;
fmt = fmt1;
} else if (score == score_max)
fmt = NULL;
}
if (nodat == 1)
score_max = FFMIN(AVPROBE_SCORE_EXTENSION / 2 - 1, score_max);
*score_ret = score_max;
return fmt;
}
AVInputFormat *av_probe_input_format2(AVProbeData *pd, int is_opened, int *score_max)
{
int score_ret;
AVInputFormat *fmt = av_probe_input_format3(pd, is_opened, &score_ret);
if (score_ret > *score_max) {
*score_max = score_ret;
return fmt;
} else
return NULL;
}
AVInputFormat *av_probe_input_format(AVProbeData *pd, int is_opened)
{
int score = 0;
return av_probe_input_format2(pd, is_opened, &score);
}
int av_probe_input_buffer2(AVIOContext *pb, AVInputFormat **fmt,
const char *filename, void *logctx,
unsigned int offset, unsigned int max_probe_size)
{
AVProbeData pd = { filename ? filename : "" };
uint8_t *buf = NULL;
int ret = 0, probe_size, buf_offset = 0;
int score = 0;
int ret2;
if (!max_probe_size)
max_probe_size = PROBE_BUF_MAX;
else if (max_probe_size < PROBE_BUF_MIN) {
av_log(logctx, AV_LOG_ERROR,
"Specified probe size value %u cannot be < %u\n", max_probe_size, PROBE_BUF_MIN);
return AVERROR(EINVAL);
}
if (offset >= max_probe_size)
return AVERROR(EINVAL);
if (pb->av_class) {
uint8_t *mime_type_opt = NULL;
av_opt_get(pb, "mime_type", AV_OPT_SEARCH_CHILDREN, &mime_type_opt);
pd.mime_type = (const char *)mime_type_opt;
}
#if 0
if (!*fmt && pb->av_class && av_opt_get(pb, "mime_type", AV_OPT_SEARCH_CHILDREN, &mime_type) >= 0 && mime_type) {
if (!av_strcasecmp(mime_type, "audio/aacp")) {
*fmt = av_find_input_format("aac");
}
av_freep(&mime_type);
}
#endif
for (probe_size = PROBE_BUF_MIN; probe_size <= max_probe_size && !*fmt;
probe_size = FFMIN(probe_size << 1,
FFMAX(max_probe_size, probe_size + 1))) {
score = probe_size < max_probe_size ? AVPROBE_SCORE_RETRY : 0;
/* Read probe data. */
if ((ret = av_reallocp(&buf, probe_size + AVPROBE_PADDING_SIZE)) < 0)
goto fail;
if ((ret = avio_read(pb, buf + buf_offset,
probe_size - buf_offset)) < 0) {
/* Fail if error was not end of file, otherwise, lower score. */
if (ret != AVERROR_EOF)
goto fail;
score = 0;
ret = 0; /* error was end of file, nothing read */
}
buf_offset += ret;
if (buf_offset < offset)
continue;
pd.buf_size = buf_offset - offset;
pd.buf = &buf[offset];
memset(pd.buf + pd.buf_size, 0, AVPROBE_PADDING_SIZE);
/* Guess file format. */
*fmt = av_probe_input_format2(&pd, 1, &score);
if (*fmt) {
/* This can only be true in the last iteration. */
if (score <= AVPROBE_SCORE_RETRY) {
av_log(logctx, AV_LOG_WARNING,
"Format %s detected only with low score of %d, "
"misdetection possible!\n", (*fmt)->name, score);
} else
av_log(logctx, AV_LOG_DEBUG,
"Format %s probed with size=%d and score=%d\n",
(*fmt)->name, probe_size, score);
#if 0
FILE *f = fopen("probestat.tmp", "ab");
fprintf(f, "probe_size:%d format:%s score:%d filename:%s\n", probe_size, (*fmt)->name, score, filename);
fclose(f);
#endif
}
}
if (!*fmt)
ret = AVERROR_INVALIDDATA;
fail:
/* Rewind. Reuse probe buffer to avoid seeking. */
ret2 = ffio_rewind_with_probe_data(pb, &buf, buf_offset);
if (ret >= 0)
ret = ret2;
av_freep(&pd.mime_type);
return ret < 0 ? ret : score;
}
int av_probe_input_buffer(AVIOContext *pb, AVInputFormat **fmt,
const char *filename, void *logctx,
unsigned int offset, unsigned int max_probe_size)
{
int ret = av_probe_input_buffer2(pb, fmt, filename, logctx, offset, max_probe_size);
return ret < 0 ? ret : 0;
}
|
579603.c | /*-*- linux-c -*-
* linux/drivers/video/i810_accel.c -- Hardware Acceleration
*
* Copyright (C) 2001 Antonino Daplas<[email protected]>
* All Rights Reserved
*
* This file is subject to the terms and conditions of the GNU General Public
* License. See the file COPYING in the main directory of this archive for
* more details.
*/
#include <linux/kernel.h>
#include <linux/string.h>
#include <linux/fb.h>
#include "i810_regs.h"
#include "i810.h"
#include "i810_main.h"
static u32 i810fb_rop[] = {
COLOR_COPY_ROP, /* ROP_COPY */
XOR_ROP /* ROP_XOR */
};
/* Macros */
#define PUT_RING(n) { \
i810_writel(par->cur_tail, par->iring.virtual, n); \
par->cur_tail += 4; \
par->cur_tail &= RING_SIZE_MASK; \
}
extern void flush_cache(void);
/************************************************************/
/* BLT Engine Routines */
static inline void i810_report_error(u8 __iomem *mmio)
{
printk("IIR : 0x%04x\n"
"EIR : 0x%04x\n"
"PGTBL_ER: 0x%04x\n"
"IPEIR : 0x%04x\n"
"IPEHR : 0x%04x\n",
i810_readw(IIR, mmio),
i810_readb(EIR, mmio),
i810_readl(PGTBL_ER, mmio),
i810_readl(IPEIR, mmio),
i810_readl(IPEHR, mmio));
}
/**
* wait_for_space - check ring buffer free space
* @space: amount of ringbuffer space needed in bytes
* @par: pointer to i810fb_par structure
*
* DESCRIPTION:
* The function waits until a free space from the ringbuffer
* is available
*/
static inline int wait_for_space(struct fb_info *info, u32 space)
{
struct i810fb_par *par = info->par;
u32 head, count = WAIT_COUNT, tail;
u8 __iomem *mmio = par->mmio_start_virtual;
tail = par->cur_tail;
while (count--) {
head = i810_readl(IRING + 4, mmio) & RBUFFER_HEAD_MASK;
if ((tail == head) ||
(tail > head &&
(par->iring.size - tail + head) >= space) ||
(tail < head && (head - tail) >= space)) {
return 0;
}
}
printk("ringbuffer lockup!!!\n");
i810_report_error(mmio);
par->dev_flags |= LOCKUP;
info->pixmap.scan_align = 1;
return 1;
}
/**
* wait_for_engine_idle - waits for all hardware engines to finish
* @par: pointer to i810fb_par structure
*
* DESCRIPTION:
* This waits for lring(0), iring(1), and batch(3), etc to finish and
* waits until ringbuffer is empty.
*/
static inline int wait_for_engine_idle(struct fb_info *info)
{
struct i810fb_par *par = info->par;
u8 __iomem *mmio = par->mmio_start_virtual;
int count = WAIT_COUNT;
if (wait_for_space(info, par->iring.size)) /* flush */
return 1;
while((i810_readw(INSTDONE, mmio) & 0x7B) != 0x7B && --count);
if (count) return 0;
printk("accel engine lockup!!!\n");
printk("INSTDONE: 0x%04x\n", i810_readl(INSTDONE, mmio));
i810_report_error(mmio);
par->dev_flags |= LOCKUP;
info->pixmap.scan_align = 1;
return 1;
}
/* begin_iring - prepares the ringbuffer
* @space: length of sequence in dwords
* @par: pointer to i810fb_par structure
*
* DESCRIPTION:
* Checks/waits for sufficent space in ringbuffer of size
* space. Returns the tail of the buffer
*/
static inline u32 begin_iring(struct fb_info *info, u32 space)
{
struct i810fb_par *par = info->par;
if (par->dev_flags & ALWAYS_SYNC)
wait_for_engine_idle(info);
return wait_for_space(info, space);
}
/**
* end_iring - advances the buffer
* @par: pointer to i810fb_par structure
*
* DESCRIPTION:
* This advances the tail of the ringbuffer, effectively
* beginning the execution of the graphics instruction sequence.
*/
static inline void end_iring(struct i810fb_par *par)
{
u8 __iomem *mmio = par->mmio_start_virtual;
i810_writel(IRING, mmio, par->cur_tail);
}
/**
* source_copy_blit - BLIT transfer operation
* @dwidth: width of rectangular graphics data
* @dheight: height of rectangular graphics data
* @dpitch: bytes per line of destination buffer
* @xdir: direction of copy (left to right or right to left)
* @src: address of first pixel to read from
* @dest: address of first pixel to write to
* @from: source address
* @where: destination address
* @rop: raster operation
* @blit_bpp: pixel format which can be different from the
* framebuffer's pixelformat
* @par: pointer to i810fb_par structure
*
* DESCRIPTION:
* This is a BLIT operation typically used when doing
* a 'Copy and Paste'
*/
static inline void source_copy_blit(int dwidth, int dheight, int dpitch,
int xdir, int src, int dest, int rop,
int blit_bpp, struct fb_info *info)
{
struct i810fb_par *par = info->par;
if (begin_iring(info, 24 + IRING_PAD)) return;
PUT_RING(BLIT | SOURCE_COPY_BLIT | 4);
PUT_RING(xdir | rop << 16 | dpitch | DYN_COLOR_EN | blit_bpp);
PUT_RING(dheight << 16 | dwidth);
PUT_RING(dest);
PUT_RING(dpitch);
PUT_RING(src);
end_iring(par);
}
/**
* color_blit - solid color BLIT operation
* @width: width of destination
* @height: height of destination
* @pitch: pixels per line of the buffer
* @dest: address of first pixel to write to
* @where: destination
* @rop: raster operation
* @what: color to transfer
* @blit_bpp: pixel format which can be different from the
* framebuffer's pixelformat
* @par: pointer to i810fb_par structure
*
* DESCRIPTION:
* A BLIT operation which can be used for color fill/rectangular fill
*/
static inline void color_blit(int width, int height, int pitch, int dest,
int rop, int what, int blit_bpp,
struct fb_info *info)
{
struct i810fb_par *par = info->par;
if (begin_iring(info, 24 + IRING_PAD)) return;
PUT_RING(BLIT | COLOR_BLT | 3);
PUT_RING(rop << 16 | pitch | SOLIDPATTERN | DYN_COLOR_EN | blit_bpp);
PUT_RING(height << 16 | width);
PUT_RING(dest);
PUT_RING(what);
PUT_RING(NOP);
end_iring(par);
}
/**
* mono_src_copy_imm_blit - color expand from system memory to framebuffer
* @dwidth: width of destination
* @dheight: height of destination
* @dpitch: pixels per line of the buffer
* @dsize: size of bitmap in double words
* @dest: address of first byte of pixel;
* @rop: raster operation
* @blit_bpp: pixelformat to use which can be different from the
* framebuffer's pixelformat
* @src: address of image data
* @bg: backgound color
* @fg: forground color
* @par: pointer to i810fb_par structure
*
* DESCRIPTION:
* A color expand operation where the source data is placed in the
* ringbuffer itself. Useful for drawing text.
*
* REQUIREMENT:
* The end of a scanline must be padded to the next word.
*/
static inline void mono_src_copy_imm_blit(int dwidth, int dheight, int dpitch,
int dsize, int blit_bpp, int rop,
int dest, const u32 *src, int bg,
int fg, struct fb_info *info)
{
struct i810fb_par *par = info->par;
if (begin_iring(info, 24 + (dsize << 2) + IRING_PAD)) return;
PUT_RING(BLIT | MONO_SOURCE_COPY_IMMEDIATE | (4 + dsize));
PUT_RING(DYN_COLOR_EN | blit_bpp | rop << 16 | dpitch);
PUT_RING(dheight << 16 | dwidth);
PUT_RING(dest);
PUT_RING(bg);
PUT_RING(fg);
while (dsize--)
PUT_RING(*src++);
end_iring(par);
}
static inline void load_front(int offset, struct fb_info *info)
{
struct i810fb_par *par = info->par;
if (begin_iring(info, 8 + IRING_PAD)) return;
PUT_RING(PARSER | FLUSH);
PUT_RING(NOP);
end_iring(par);
if (begin_iring(info, 8 + IRING_PAD)) return;
PUT_RING(PARSER | FRONT_BUFFER | ((par->pitch >> 3) << 8));
PUT_RING((par->fb.offset << 12) + offset);
end_iring(par);
}
/**
* i810fb_iring_enable - enables/disables the ringbuffer
* @mode: enable or disable
* @par: pointer to i810fb_par structure
*
* DESCRIPTION:
* Enables or disables the ringbuffer, effectively enabling or
* disabling the instruction/acceleration engine.
*/
static inline void i810fb_iring_enable(struct i810fb_par *par, u32 mode)
{
u32 tmp;
u8 __iomem *mmio = par->mmio_start_virtual;
tmp = i810_readl(IRING + 12, mmio);
if (mode == OFF)
tmp &= ~1;
else
tmp |= 1;
flush_cache();
i810_writel(IRING + 12, mmio, tmp);
}
void i810fb_fillrect(struct fb_info *info, const struct fb_fillrect *rect)
{
struct i810fb_par *par = info->par;
u32 dx, dy, width, height, dest, rop = 0, color = 0;
if (!info->var.accel_flags || par->dev_flags & LOCKUP ||
par->depth == 4) {
cfb_fillrect(info, rect);
return;
}
if (par->depth == 1)
color = rect->color;
else
color = ((u32 *) (info->pseudo_palette))[rect->color];
rop = i810fb_rop[rect->rop];
dx = rect->dx * par->depth;
width = rect->width * par->depth;
dy = rect->dy;
height = rect->height;
dest = info->fix.smem_start + (dy * info->fix.line_length) + dx;
color_blit(width, height, info->fix.line_length, dest, rop, color,
par->blit_bpp, info);
}
void i810fb_copyarea(struct fb_info *info, const struct fb_copyarea *region)
{
struct i810fb_par *par = info->par;
u32 sx, sy, dx, dy, pitch, width, height, src, dest, xdir;
if (!info->var.accel_flags || par->dev_flags & LOCKUP ||
par->depth == 4) {
cfb_copyarea(info, region);
return;
}
dx = region->dx * par->depth;
sx = region->sx * par->depth;
width = region->width * par->depth;
sy = region->sy;
dy = region->dy;
height = region->height;
if (dx <= sx) {
xdir = INCREMENT;
}
else {
xdir = DECREMENT;
sx += width - 1;
dx += width - 1;
}
if (dy <= sy) {
pitch = info->fix.line_length;
}
else {
pitch = (-(info->fix.line_length)) & 0xFFFF;
sy += height - 1;
dy += height - 1;
}
src = info->fix.smem_start + (sy * info->fix.line_length) + sx;
dest = info->fix.smem_start + (dy * info->fix.line_length) + dx;
source_copy_blit(width, height, pitch, xdir, src, dest,
PAT_COPY_ROP, par->blit_bpp, info);
}
void i810fb_imageblit(struct fb_info *info, const struct fb_image *image)
{
struct i810fb_par *par = info->par;
u32 fg = 0, bg = 0, size, dst;
if (!info->var.accel_flags || par->dev_flags & LOCKUP ||
par->depth == 4 || image->depth != 1) {
cfb_imageblit(info, image);
return;
}
switch (info->var.bits_per_pixel) {
case 8:
fg = image->fg_color;
bg = image->bg_color;
break;
case 16:
case 24:
fg = ((u32 *)(info->pseudo_palette))[image->fg_color];
bg = ((u32 *)(info->pseudo_palette))[image->bg_color];
break;
}
dst = info->fix.smem_start + (image->dy * info->fix.line_length) +
(image->dx * par->depth);
size = (image->width+7)/8 + 1;
size &= ~1;
size *= image->height;
size += 7;
size &= ~7;
mono_src_copy_imm_blit(image->width * par->depth,
image->height, info->fix.line_length,
size/4, par->blit_bpp,
PAT_COPY_ROP, dst, (u32 *) image->data,
bg, fg, info);
}
int i810fb_sync(struct fb_info *info)
{
struct i810fb_par *par = info->par;
if (!info->var.accel_flags || par->dev_flags & LOCKUP)
return 0;
return wait_for_engine_idle(info);
}
void i810fb_load_front(u32 offset, struct fb_info *info)
{
struct i810fb_par *par = info->par;
u8 __iomem *mmio = par->mmio_start_virtual;
if (!info->var.accel_flags || par->dev_flags & LOCKUP)
i810_writel(DPLYBASE, mmio, par->fb.physical + offset);
else
load_front(offset, info);
}
/**
* i810fb_init_ringbuffer - initialize the ringbuffer
* @par: pointer to i810fb_par structure
*
* DESCRIPTION:
* Initializes the ringbuffer by telling the device the
* size and location of the ringbuffer. It also sets
* the head and tail pointers = 0
*/
void i810fb_init_ringbuffer(struct fb_info *info)
{
struct i810fb_par *par = info->par;
u32 tmp1, tmp2;
u8 __iomem *mmio = par->mmio_start_virtual;
wait_for_engine_idle(info);
i810fb_iring_enable(par, OFF);
i810_writel(IRING, mmio, 0);
i810_writel(IRING + 4, mmio, 0);
par->cur_tail = 0;
tmp2 = i810_readl(IRING + 8, mmio) & ~RBUFFER_START_MASK;
tmp1 = par->iring.physical;
i810_writel(IRING + 8, mmio, tmp2 | tmp1);
tmp1 = i810_readl(IRING + 12, mmio);
tmp1 &= ~RBUFFER_SIZE_MASK;
tmp2 = (par->iring.size - I810_PAGESIZE) & RBUFFER_SIZE_MASK;
i810_writel(IRING + 12, mmio, tmp1 | tmp2);
i810fb_iring_enable(par, ON);
}
|
276108.c | /*----------------------------------------------------------------------------*/
/* Hobbit RRD handler module. */
/* */
/* Copyright (C) 2004-2009 Henrik Storner <[email protected]> */
/* */
/* This program is released under the GNU General Public License (GPL), */
/* version 2. See the file "COPYING" for details. */
/* */
/*----------------------------------------------------------------------------*/
static char bbproxy_rcsid[] = "$Id$";
int do_bbproxy_rrd(char *hostname, char *testname, char *classname, char *pagepaths, char *msg, time_t tstamp)
{
static char *bbproxy_params[] = { "DS:runtime:GAUGE:600:0:U", NULL };
static void *bbproxy_tpl = NULL;
char *p;
float runtime;
if (bbproxy_tpl == NULL) bbproxy_tpl = setup_template(bbproxy_params);
p = strstr(msg, "Average queue time");
if (p && (sscanf(p, "Average queue time : %f", &runtime) == 1)) {
if (strcmp("bbproxy", testname) != 0) {
setupfn2("%s.%s.rrd", "bbproxy", testname);
}
else {
setupfn("%s.rrd", "bbproxy");
}
sprintf(rrdvalues, "%d:%.2f", (int) tstamp, runtime);
return create_and_update_rrd(hostname, testname, classname, pagepaths, bbproxy_params, bbproxy_tpl);
}
return 0;
}
|
29135.c | /*
* Author: Thomas Ingleby <[email protected]>
* Copyright (c) 2014 Intel Corporation.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include <stdlib.h>
#include <string.h>
#include "mraa_internal.h"
#include "x86/intel_galileo_rev_d.h"
#include "x86/intel_galileo_rev_g.h"
#include "x86/intel_edison_fab_c.h"
#include "x86/intel_de3815.h"
#include "x86/intel_minnow_max.h"
mraa_platform_t
mraa_x86_platform()
{
mraa_platform_t platform_type = MRAA_UNKNOWN_PLATFORM;
char *line = NULL;
// let getline allocate memory for *line
size_t len = 0;
FILE *fh = fopen("/sys/devices/virtual/dmi/id/board_name", "r");
if (fh != NULL) {
if (getline(&line, &len, fh) != -1) {
if (strncmp(line, "GalileoGen2", 11) == 0) {
platform_type = MRAA_INTEL_GALILEO_GEN2;
plat = mraa_intel_galileo_gen2();
} else if (strncmp(line, "BODEGA BAY", 10) == 0) {
platform_type = MRAA_INTEL_EDISON_FAB_C;
plat = mraa_intel_edison_fab_c();
} else if (strncmp(line, "SALT BAY", 8) == 0) {
platform_type = MRAA_INTEL_EDISON_FAB_C;
plat = mraa_intel_edison_fab_c();
} else if (strncmp(line, "DE3815", 6) == 0) {
platform_type = MRAA_INTEL_DE3815;
plat = mraa_intel_de3815();
} else if (strncmp(line, "NOTEBOOK", 8) == 0) {
platform_type = MRAA_INTEL_MINNOWBOARD_MAX;
plat = mraa_intel_minnow_max();
} else if (strncasecmp(line, "MinnowBoard MAX", 15) == 0) {
platform_type = MRAA_INTEL_MINNOWBOARD_MAX;
plat = mraa_intel_minnow_max();
} else if (strncasecmp(line, "Galileo", 7) == 0) {
platform_type = MRAA_INTEL_GALILEO_GEN1;
plat = mraa_intel_galileo_rev_d();
} else {
syslog(LOG_ERR, "Platform not supported, initialising as MRAA_INTEL_GALILEO_GEN1");
platform_type = MRAA_INTEL_GALILEO_GEN1;
plat = mraa_intel_galileo_rev_d();
}
free(line);
}
fclose(fh);
}
return platform_type;
}
|
86977.c | /* -*- c-file-style: "ruby"; indent-tabs-mode: nil -*- */
/*
* Copyright (C) 2011 Ruby-GNOME2 Project Team
* Copyright (C) 2002,2003 Ruby-GNOME2 Project Team
* Copyright (C) 1998-2000 Yukihiro Matsumoto,
* Daisuke Kanda,
* Hiroshi Igarashi
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301 USA
*/
#include "global.h"
#if GTK_CHECK_VERSION(2,12,0)
#define RG_TARGET_NAMESPACE cVolumeButton
static VALUE
rg_initialize(VALUE self)
{
RBGTK_INITIALIZE(self, gtk_volume_button_new());
return Qnil;
}
#endif
void
Init_gtk_volumebutton(VALUE mGtk)
{
#if GTK_CHECK_VERSION(2,12,0)
VALUE RG_TARGET_NAMESPACE = G_DEF_CLASS(GTK_TYPE_VOLUME_BUTTON, "VolumeButton", mGtk);
RG_DEF_METHOD(initialize, 0);
#endif
}
|
470676.c | #include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include "ezsignformfield_request_compound.h"
ezsignformfield_request_compound_t *ezsignformfield_request_compound_create(
int pki_ezsignformfield_id,
int i_ezsignpage_pagenumber,
char *s_ezsignformfield_label,
char *s_ezsignformfield_value,
int i_ezsignformfield_x,
int i_ezsignformfield_y,
int i_ezsignformfield_width,
int i_ezsignformfield_height,
int b_ezsignformfield_selected,
char *s_ezsignformfield_enteredvalue
) {
ezsignformfield_request_compound_t *ezsignformfield_request_compound_local_var = malloc(sizeof(ezsignformfield_request_compound_t));
if (!ezsignformfield_request_compound_local_var) {
return NULL;
}
ezsignformfield_request_compound_local_var->pki_ezsignformfield_id = pki_ezsignformfield_id;
ezsignformfield_request_compound_local_var->i_ezsignpage_pagenumber = i_ezsignpage_pagenumber;
ezsignformfield_request_compound_local_var->s_ezsignformfield_label = s_ezsignformfield_label;
ezsignformfield_request_compound_local_var->s_ezsignformfield_value = s_ezsignformfield_value;
ezsignformfield_request_compound_local_var->i_ezsignformfield_x = i_ezsignformfield_x;
ezsignformfield_request_compound_local_var->i_ezsignformfield_y = i_ezsignformfield_y;
ezsignformfield_request_compound_local_var->i_ezsignformfield_width = i_ezsignformfield_width;
ezsignformfield_request_compound_local_var->i_ezsignformfield_height = i_ezsignformfield_height;
ezsignformfield_request_compound_local_var->b_ezsignformfield_selected = b_ezsignformfield_selected;
ezsignformfield_request_compound_local_var->s_ezsignformfield_enteredvalue = s_ezsignformfield_enteredvalue;
return ezsignformfield_request_compound_local_var;
}
void ezsignformfield_request_compound_free(ezsignformfield_request_compound_t *ezsignformfield_request_compound) {
if(NULL == ezsignformfield_request_compound){
return ;
}
listEntry_t *listEntry;
if (ezsignformfield_request_compound->s_ezsignformfield_label) {
free(ezsignformfield_request_compound->s_ezsignformfield_label);
ezsignformfield_request_compound->s_ezsignformfield_label = NULL;
}
if (ezsignformfield_request_compound->s_ezsignformfield_value) {
free(ezsignformfield_request_compound->s_ezsignformfield_value);
ezsignformfield_request_compound->s_ezsignformfield_value = NULL;
}
if (ezsignformfield_request_compound->s_ezsignformfield_enteredvalue) {
free(ezsignformfield_request_compound->s_ezsignformfield_enteredvalue);
ezsignformfield_request_compound->s_ezsignformfield_enteredvalue = NULL;
}
free(ezsignformfield_request_compound);
}
cJSON *ezsignformfield_request_compound_convertToJSON(ezsignformfield_request_compound_t *ezsignformfield_request_compound) {
cJSON *item = cJSON_CreateObject();
// ezsignformfield_request_compound->pki_ezsignformfield_id
if(ezsignformfield_request_compound->pki_ezsignformfield_id) {
if(cJSON_AddNumberToObject(item, "pkiEzsignformfieldID", ezsignformfield_request_compound->pki_ezsignformfield_id) == NULL) {
goto fail; //Numeric
}
}
// ezsignformfield_request_compound->i_ezsignpage_pagenumber
if (!ezsignformfield_request_compound->i_ezsignpage_pagenumber) {
goto fail;
}
if(cJSON_AddNumberToObject(item, "iEzsignpagePagenumber", ezsignformfield_request_compound->i_ezsignpage_pagenumber) == NULL) {
goto fail; //Numeric
}
// ezsignformfield_request_compound->s_ezsignformfield_label
if (!ezsignformfield_request_compound->s_ezsignformfield_label) {
goto fail;
}
if(cJSON_AddStringToObject(item, "sEzsignformfieldLabel", ezsignformfield_request_compound->s_ezsignformfield_label) == NULL) {
goto fail; //String
}
// ezsignformfield_request_compound->s_ezsignformfield_value
if(ezsignformfield_request_compound->s_ezsignformfield_value) {
if(cJSON_AddStringToObject(item, "sEzsignformfieldValue", ezsignformfield_request_compound->s_ezsignformfield_value) == NULL) {
goto fail; //String
}
}
// ezsignformfield_request_compound->i_ezsignformfield_x
if (!ezsignformfield_request_compound->i_ezsignformfield_x) {
goto fail;
}
if(cJSON_AddNumberToObject(item, "iEzsignformfieldX", ezsignformfield_request_compound->i_ezsignformfield_x) == NULL) {
goto fail; //Numeric
}
// ezsignformfield_request_compound->i_ezsignformfield_y
if (!ezsignformfield_request_compound->i_ezsignformfield_y) {
goto fail;
}
if(cJSON_AddNumberToObject(item, "iEzsignformfieldY", ezsignformfield_request_compound->i_ezsignformfield_y) == NULL) {
goto fail; //Numeric
}
// ezsignformfield_request_compound->i_ezsignformfield_width
if (!ezsignformfield_request_compound->i_ezsignformfield_width) {
goto fail;
}
if(cJSON_AddNumberToObject(item, "iEzsignformfieldWidth", ezsignformfield_request_compound->i_ezsignformfield_width) == NULL) {
goto fail; //Numeric
}
// ezsignformfield_request_compound->i_ezsignformfield_height
if (!ezsignformfield_request_compound->i_ezsignformfield_height) {
goto fail;
}
if(cJSON_AddNumberToObject(item, "iEzsignformfieldHeight", ezsignformfield_request_compound->i_ezsignformfield_height) == NULL) {
goto fail; //Numeric
}
// ezsignformfield_request_compound->b_ezsignformfield_selected
if(ezsignformfield_request_compound->b_ezsignformfield_selected) {
if(cJSON_AddBoolToObject(item, "bEzsignformfieldSelected", ezsignformfield_request_compound->b_ezsignformfield_selected) == NULL) {
goto fail; //Bool
}
}
// ezsignformfield_request_compound->s_ezsignformfield_enteredvalue
if(ezsignformfield_request_compound->s_ezsignformfield_enteredvalue) {
if(cJSON_AddStringToObject(item, "sEzsignformfieldEnteredvalue", ezsignformfield_request_compound->s_ezsignformfield_enteredvalue) == NULL) {
goto fail; //String
}
}
return item;
fail:
if (item) {
cJSON_Delete(item);
}
return NULL;
}
ezsignformfield_request_compound_t *ezsignformfield_request_compound_parseFromJSON(cJSON *ezsignformfield_request_compoundJSON){
ezsignformfield_request_compound_t *ezsignformfield_request_compound_local_var = NULL;
// ezsignformfield_request_compound->pki_ezsignformfield_id
cJSON *pki_ezsignformfield_id = cJSON_GetObjectItemCaseSensitive(ezsignformfield_request_compoundJSON, "pkiEzsignformfieldID");
if (pki_ezsignformfield_id) {
if(!cJSON_IsNumber(pki_ezsignformfield_id))
{
goto end; //Numeric
}
}
// ezsignformfield_request_compound->i_ezsignpage_pagenumber
cJSON *i_ezsignpage_pagenumber = cJSON_GetObjectItemCaseSensitive(ezsignformfield_request_compoundJSON, "iEzsignpagePagenumber");
if (!i_ezsignpage_pagenumber) {
goto end;
}
if(!cJSON_IsNumber(i_ezsignpage_pagenumber))
{
goto end; //Numeric
}
// ezsignformfield_request_compound->s_ezsignformfield_label
cJSON *s_ezsignformfield_label = cJSON_GetObjectItemCaseSensitive(ezsignformfield_request_compoundJSON, "sEzsignformfieldLabel");
if (!s_ezsignformfield_label) {
goto end;
}
if(!cJSON_IsString(s_ezsignformfield_label))
{
goto end; //String
}
// ezsignformfield_request_compound->s_ezsignformfield_value
cJSON *s_ezsignformfield_value = cJSON_GetObjectItemCaseSensitive(ezsignformfield_request_compoundJSON, "sEzsignformfieldValue");
if (s_ezsignformfield_value) {
if(!cJSON_IsString(s_ezsignformfield_value))
{
goto end; //String
}
}
// ezsignformfield_request_compound->i_ezsignformfield_x
cJSON *i_ezsignformfield_x = cJSON_GetObjectItemCaseSensitive(ezsignformfield_request_compoundJSON, "iEzsignformfieldX");
if (!i_ezsignformfield_x) {
goto end;
}
if(!cJSON_IsNumber(i_ezsignformfield_x))
{
goto end; //Numeric
}
// ezsignformfield_request_compound->i_ezsignformfield_y
cJSON *i_ezsignformfield_y = cJSON_GetObjectItemCaseSensitive(ezsignformfield_request_compoundJSON, "iEzsignformfieldY");
if (!i_ezsignformfield_y) {
goto end;
}
if(!cJSON_IsNumber(i_ezsignformfield_y))
{
goto end; //Numeric
}
// ezsignformfield_request_compound->i_ezsignformfield_width
cJSON *i_ezsignformfield_width = cJSON_GetObjectItemCaseSensitive(ezsignformfield_request_compoundJSON, "iEzsignformfieldWidth");
if (!i_ezsignformfield_width) {
goto end;
}
if(!cJSON_IsNumber(i_ezsignformfield_width))
{
goto end; //Numeric
}
// ezsignformfield_request_compound->i_ezsignformfield_height
cJSON *i_ezsignformfield_height = cJSON_GetObjectItemCaseSensitive(ezsignformfield_request_compoundJSON, "iEzsignformfieldHeight");
if (!i_ezsignformfield_height) {
goto end;
}
if(!cJSON_IsNumber(i_ezsignformfield_height))
{
goto end; //Numeric
}
// ezsignformfield_request_compound->b_ezsignformfield_selected
cJSON *b_ezsignformfield_selected = cJSON_GetObjectItemCaseSensitive(ezsignformfield_request_compoundJSON, "bEzsignformfieldSelected");
if (b_ezsignformfield_selected) {
if(!cJSON_IsBool(b_ezsignformfield_selected))
{
goto end; //Bool
}
}
// ezsignformfield_request_compound->s_ezsignformfield_enteredvalue
cJSON *s_ezsignformfield_enteredvalue = cJSON_GetObjectItemCaseSensitive(ezsignformfield_request_compoundJSON, "sEzsignformfieldEnteredvalue");
if (s_ezsignformfield_enteredvalue) {
if(!cJSON_IsString(s_ezsignformfield_enteredvalue))
{
goto end; //String
}
}
ezsignformfield_request_compound_local_var = ezsignformfield_request_compound_create (
pki_ezsignformfield_id ? pki_ezsignformfield_id->valuedouble : 0,
i_ezsignpage_pagenumber->valuedouble,
strdup(s_ezsignformfield_label->valuestring),
s_ezsignformfield_value ? strdup(s_ezsignformfield_value->valuestring) : NULL,
i_ezsignformfield_x->valuedouble,
i_ezsignformfield_y->valuedouble,
i_ezsignformfield_width->valuedouble,
i_ezsignformfield_height->valuedouble,
b_ezsignformfield_selected ? b_ezsignformfield_selected->valueint : 0,
s_ezsignformfield_enteredvalue ? strdup(s_ezsignformfield_enteredvalue->valuestring) : NULL
);
return ezsignformfield_request_compound_local_var;
end:
return NULL;
}
|
457130.c | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ksu_common.h>
#include <ksu_dates.h>
extern void ora_next_day(sqlite3_context * context,
int argc,
sqlite3_value ** argv) {
char *input_date;
int wday;
char date[DATE_LEN];
int delta;
KSU_TIME_T t;
KSU_TM_T tm;
if (ksu_prm_ok(context, argc, argv,
"next_day", KSU_PRM_DATETIME, KSU_PRM_TEXT)) {
input_date = (char *)sqlite3_value_text(argv[0]);
wday = ksu_weekday((char *)sqlite3_value_text(argv[1]));
if (wday == -1) {
ksu_err_msg(context, KSU_ERR_INV_DAY,
(char *)sqlite3_value_text(argv[1]), "next_day");
return;
}
if (!ksu_is_datetime(input_date, &t, (char)0)
|| !ksu_localtime(t, &tm)) {
ksu_err_msg(context, KSU_ERR_ARG_N_NOT_DATETIME,
1, "next_day");
return;
}
if (tm.wday < wday) {
delta = (wday - tm.wday) * 86400;
} else {
delta = (7 + wday - tm.wday) * 86400;
}
t = ksu_add_secs(t, delta);
if (!ksu_localtime(t, &tm)) {
ksu_err_msg(context, KSU_ERR_DATE_CONV, "next_day");
return;
}
if (strlen(input_date) > 15) {
// Give the time component
(void)sprintf((char *)date,
"%4hd-%02hd-%02hd %02hd:%02hd:%02hd",
tm.year, (short)(1 + tm.mon), tm.mday,
tm.hour, tm.min, tm.sec);
} else {
(void)sprintf((char *)date,
"%4hd-%02hd-%02hd",
tm.year, (short)(1 + tm.mon), tm.mday);
}
sqlite3_result_text(context, date, -1, SQLITE_TRANSIENT);
}
}
|
617362.c | /* SPDX-License-Identifier: BSD-3-Clause
* Copyright(c) 2018-2020 Intel Corporation
*/
#include <rte_ipsec.h>
#include <rte_esp.h>
#include <rte_ip.h>
#include <rte_errno.h>
#include <rte_cryptodev.h>
#include "sa.h"
#include "ipsec_sqn.h"
#include "crypto.h"
#include "iph.h"
#include "misc.h"
#include "pad.h"
typedef int32_t (*esp_outb_prepare_t)(struct rte_ipsec_sa *sa, rte_be64_t sqc,
const uint64_t ivp[IPSEC_MAX_IV_QWORD], struct rte_mbuf *mb,
union sym_op_data *icv, uint8_t sqh_len);
/*
* helper function to fill crypto_sym op for cipher+auth algorithms.
* used by outb_cop_prepare(), see below.
*/
static inline void
sop_ciph_auth_prepare(struct rte_crypto_sym_op *sop,
const struct rte_ipsec_sa *sa, const union sym_op_data *icv,
uint32_t pofs, uint32_t plen)
{
sop->cipher.data.offset = sa->ctp.cipher.offset + pofs;
sop->cipher.data.length = sa->ctp.cipher.length + plen;
sop->auth.data.offset = sa->ctp.auth.offset + pofs;
sop->auth.data.length = sa->ctp.auth.length + plen;
sop->auth.digest.data = icv->va;
sop->auth.digest.phys_addr = icv->pa;
}
/*
* helper function to fill crypto_sym op for cipher+auth algorithms.
* used by outb_cop_prepare(), see below.
*/
static inline void
sop_aead_prepare(struct rte_crypto_sym_op *sop,
const struct rte_ipsec_sa *sa, const union sym_op_data *icv,
uint32_t pofs, uint32_t plen)
{
sop->aead.data.offset = sa->ctp.cipher.offset + pofs;
sop->aead.data.length = sa->ctp.cipher.length + plen;
sop->aead.digest.data = icv->va;
sop->aead.digest.phys_addr = icv->pa;
sop->aead.aad.data = icv->va + sa->icv_len;
sop->aead.aad.phys_addr = icv->pa + sa->icv_len;
}
/*
* setup crypto op and crypto sym op for ESP outbound packet.
*/
static inline void
outb_cop_prepare(struct rte_crypto_op *cop,
const struct rte_ipsec_sa *sa, const uint64_t ivp[IPSEC_MAX_IV_QWORD],
const union sym_op_data *icv, uint32_t hlen, uint32_t plen)
{
struct rte_crypto_sym_op *sop;
struct aead_gcm_iv *gcm;
struct aesctr_cnt_blk *ctr;
uint32_t algo;
algo = sa->algo_type;
/* fill sym op fields */
sop = cop->sym;
switch (algo) {
case ALGO_TYPE_AES_CBC:
/* Cipher-Auth (AES-CBC *) case */
case ALGO_TYPE_3DES_CBC:
/* Cipher-Auth (3DES-CBC *) case */
case ALGO_TYPE_NULL:
/* NULL case */
sop_ciph_auth_prepare(sop, sa, icv, hlen, plen);
break;
case ALGO_TYPE_AES_GCM:
/* AEAD (AES_GCM) case */
sop_aead_prepare(sop, sa, icv, hlen, plen);
/* fill AAD IV (located inside crypto op) */
gcm = rte_crypto_op_ctod_offset(cop, struct aead_gcm_iv *,
sa->iv_ofs);
aead_gcm_iv_fill(gcm, ivp[0], sa->salt);
break;
case ALGO_TYPE_AES_CTR:
/* Cipher-Auth (AES-CTR *) case */
sop_ciph_auth_prepare(sop, sa, icv, hlen, plen);
/* fill CTR block (located inside crypto op) */
ctr = rte_crypto_op_ctod_offset(cop, struct aesctr_cnt_blk *,
sa->iv_ofs);
aes_ctr_cnt_blk_fill(ctr, ivp[0], sa->salt);
break;
}
}
/*
* setup/update packet data and metadata for ESP outbound tunnel case.
*/
static inline int32_t
outb_tun_pkt_prepare(struct rte_ipsec_sa *sa, rte_be64_t sqc,
const uint64_t ivp[IPSEC_MAX_IV_QWORD], struct rte_mbuf *mb,
union sym_op_data *icv, uint8_t sqh_len)
{
uint32_t clen, hlen, l2len, pdlen, pdofs, plen, tlen;
struct rte_mbuf *ml;
struct rte_esp_hdr *esph;
struct rte_esp_tail *espt;
char *ph, *pt;
uint64_t *iv;
/* calculate extra header space required */
hlen = sa->hdr_len + sa->iv_len + sizeof(*esph);
/* size of ipsec protected data */
l2len = mb->l2_len;
plen = mb->pkt_len - l2len;
/* number of bytes to encrypt */
clen = plen + sizeof(*espt);
clen = RTE_ALIGN_CEIL(clen, sa->pad_align);
/* pad length + esp tail */
pdlen = clen - plen;
tlen = pdlen + sa->icv_len + sqh_len;
/* do append and prepend */
ml = rte_pktmbuf_lastseg(mb);
if (tlen + sa->aad_len > rte_pktmbuf_tailroom(ml))
return -ENOSPC;
/* prepend header */
ph = rte_pktmbuf_prepend(mb, hlen - l2len);
if (ph == NULL)
return -ENOSPC;
/* append tail */
pdofs = ml->data_len;
ml->data_len += tlen;
mb->pkt_len += tlen;
pt = rte_pktmbuf_mtod_offset(ml, typeof(pt), pdofs);
/* update pkt l2/l3 len */
mb->tx_offload = (mb->tx_offload & sa->tx_offload.msk) |
sa->tx_offload.val;
/* copy tunnel pkt header */
rte_memcpy(ph, sa->hdr, sa->hdr_len);
/* update original and new ip header fields */
update_tun_outb_l3hdr(sa, ph + sa->hdr_l3_off, ph + hlen,
mb->pkt_len - sqh_len, sa->hdr_l3_off, sqn_low16(sqc));
/* update spi, seqn and iv */
esph = (struct rte_esp_hdr *)(ph + sa->hdr_len);
iv = (uint64_t *)(esph + 1);
copy_iv(iv, ivp, sa->iv_len);
esph->spi = sa->spi;
esph->seq = sqn_low32(sqc);
/* offset for ICV */
pdofs += pdlen + sa->sqh_len;
/* pad length */
pdlen -= sizeof(*espt);
/* copy padding data */
rte_memcpy(pt, esp_pad_bytes, pdlen);
/* update esp trailer */
espt = (struct rte_esp_tail *)(pt + pdlen);
espt->pad_len = pdlen;
espt->next_proto = sa->proto;
/* set icv va/pa value(s) */
icv->va = rte_pktmbuf_mtod_offset(ml, void *, pdofs);
icv->pa = rte_pktmbuf_iova_offset(ml, pdofs);
return clen;
}
/*
* for pure cryptodev (lookaside none) depending on SA settings,
* we might have to write some extra data to the packet.
*/
static inline void
outb_pkt_xprepare(const struct rte_ipsec_sa *sa, rte_be64_t sqc,
const union sym_op_data *icv)
{
uint32_t *psqh;
struct aead_gcm_aad *aad;
/* insert SQN.hi between ESP trailer and ICV */
if (sa->sqh_len != 0) {
psqh = (uint32_t *)(icv->va - sa->sqh_len);
psqh[0] = sqn_hi32(sqc);
}
/*
* fill IV and AAD fields, if any (aad fields are placed after icv),
* right now we support only one AEAD algorithm: AES-GCM .
*/
if (sa->aad_len != 0) {
aad = (struct aead_gcm_aad *)(icv->va + sa->icv_len);
aead_gcm_aad_fill(aad, sa->spi, sqc, IS_ESN(sa));
}
}
/*
* setup/update packets and crypto ops for ESP outbound tunnel case.
*/
uint16_t
esp_outb_tun_prepare(const struct rte_ipsec_session *ss, struct rte_mbuf *mb[],
struct rte_crypto_op *cop[], uint16_t num)
{
int32_t rc;
uint32_t i, k, n;
uint64_t sqn;
rte_be64_t sqc;
struct rte_ipsec_sa *sa;
struct rte_cryptodev_sym_session *cs;
union sym_op_data icv;
uint64_t iv[IPSEC_MAX_IV_QWORD];
uint32_t dr[num];
sa = ss->sa;
cs = ss->crypto.ses;
n = num;
sqn = esn_outb_update_sqn(sa, &n);
if (n != num)
rte_errno = EOVERFLOW;
k = 0;
for (i = 0; i != n; i++) {
sqc = rte_cpu_to_be_64(sqn + i);
gen_iv(iv, sqc);
/* try to update the packet itself */
rc = outb_tun_pkt_prepare(sa, sqc, iv, mb[i], &icv,
sa->sqh_len);
/* success, setup crypto op */
if (rc >= 0) {
outb_pkt_xprepare(sa, sqc, &icv);
lksd_none_cop_prepare(cop[k], cs, mb[i]);
outb_cop_prepare(cop[k], sa, iv, &icv, 0, rc);
k++;
/* failure, put packet into the death-row */
} else {
dr[i - k] = i;
rte_errno = -rc;
}
}
/* copy not prepared mbufs beyond good ones */
if (k != n && k != 0)
move_bad_mbufs(mb, dr, n, n - k);
return k;
}
/*
* setup/update packet data and metadata for ESP outbound transport case.
*/
static inline int32_t
outb_trs_pkt_prepare(struct rte_ipsec_sa *sa, rte_be64_t sqc,
const uint64_t ivp[IPSEC_MAX_IV_QWORD], struct rte_mbuf *mb,
union sym_op_data *icv, uint8_t sqh_len)
{
uint8_t np;
uint32_t clen, hlen, pdlen, pdofs, plen, tlen, uhlen;
struct rte_mbuf *ml;
struct rte_esp_hdr *esph;
struct rte_esp_tail *espt;
char *ph, *pt;
uint64_t *iv;
uint32_t l2len, l3len;
l2len = mb->l2_len;
l3len = mb->l3_len;
uhlen = l2len + l3len;
plen = mb->pkt_len - uhlen;
/* calculate extra header space required */
hlen = sa->iv_len + sizeof(*esph);
/* number of bytes to encrypt */
clen = plen + sizeof(*espt);
clen = RTE_ALIGN_CEIL(clen, sa->pad_align);
/* pad length + esp tail */
pdlen = clen - plen;
tlen = pdlen + sa->icv_len + sqh_len;
/* do append and insert */
ml = rte_pktmbuf_lastseg(mb);
if (tlen + sa->aad_len > rte_pktmbuf_tailroom(ml))
return -ENOSPC;
/* prepend space for ESP header */
ph = rte_pktmbuf_prepend(mb, hlen);
if (ph == NULL)
return -ENOSPC;
/* append tail */
pdofs = ml->data_len;
ml->data_len += tlen;
mb->pkt_len += tlen;
pt = rte_pktmbuf_mtod_offset(ml, typeof(pt), pdofs);
/* shift L2/L3 headers */
insert_esph(ph, ph + hlen, uhlen);
/* update ip header fields */
np = update_trs_l3hdr(sa, ph + l2len, mb->pkt_len - sqh_len, l2len,
l3len, IPPROTO_ESP);
/* update spi, seqn and iv */
esph = (struct rte_esp_hdr *)(ph + uhlen);
iv = (uint64_t *)(esph + 1);
copy_iv(iv, ivp, sa->iv_len);
esph->spi = sa->spi;
esph->seq = sqn_low32(sqc);
/* offset for ICV */
pdofs += pdlen + sa->sqh_len;
/* pad length */
pdlen -= sizeof(*espt);
/* copy padding data */
rte_memcpy(pt, esp_pad_bytes, pdlen);
/* update esp trailer */
espt = (struct rte_esp_tail *)(pt + pdlen);
espt->pad_len = pdlen;
espt->next_proto = np;
/* set icv va/pa value(s) */
icv->va = rte_pktmbuf_mtod_offset(ml, void *, pdofs);
icv->pa = rte_pktmbuf_iova_offset(ml, pdofs);
return clen;
}
/*
* setup/update packets and crypto ops for ESP outbound transport case.
*/
uint16_t
esp_outb_trs_prepare(const struct rte_ipsec_session *ss, struct rte_mbuf *mb[],
struct rte_crypto_op *cop[], uint16_t num)
{
int32_t rc;
uint32_t i, k, n, l2, l3;
uint64_t sqn;
rte_be64_t sqc;
struct rte_ipsec_sa *sa;
struct rte_cryptodev_sym_session *cs;
union sym_op_data icv;
uint64_t iv[IPSEC_MAX_IV_QWORD];
uint32_t dr[num];
sa = ss->sa;
cs = ss->crypto.ses;
n = num;
sqn = esn_outb_update_sqn(sa, &n);
if (n != num)
rte_errno = EOVERFLOW;
k = 0;
for (i = 0; i != n; i++) {
l2 = mb[i]->l2_len;
l3 = mb[i]->l3_len;
sqc = rte_cpu_to_be_64(sqn + i);
gen_iv(iv, sqc);
/* try to update the packet itself */
rc = outb_trs_pkt_prepare(sa, sqc, iv, mb[i], &icv,
sa->sqh_len);
/* success, setup crypto op */
if (rc >= 0) {
outb_pkt_xprepare(sa, sqc, &icv);
lksd_none_cop_prepare(cop[k], cs, mb[i]);
outb_cop_prepare(cop[k], sa, iv, &icv, l2 + l3, rc);
k++;
/* failure, put packet into the death-row */
} else {
dr[i - k] = i;
rte_errno = -rc;
}
}
/* copy not prepared mbufs beyond good ones */
if (k != n && k != 0)
move_bad_mbufs(mb, dr, n, n - k);
return k;
}
static inline uint32_t
outb_cpu_crypto_prepare(const struct rte_ipsec_sa *sa, uint32_t *pofs,
uint32_t plen, void *iv)
{
uint64_t *ivp = iv;
struct aead_gcm_iv *gcm;
struct aesctr_cnt_blk *ctr;
uint32_t clen;
switch (sa->algo_type) {
case ALGO_TYPE_AES_GCM:
gcm = iv;
aead_gcm_iv_fill(gcm, ivp[0], sa->salt);
break;
case ALGO_TYPE_AES_CTR:
ctr = iv;
aes_ctr_cnt_blk_fill(ctr, ivp[0], sa->salt);
break;
}
*pofs += sa->ctp.auth.offset;
clen = plen + sa->ctp.auth.length;
return clen;
}
static uint16_t
cpu_outb_pkt_prepare(const struct rte_ipsec_session *ss,
struct rte_mbuf *mb[], uint16_t num,
esp_outb_prepare_t prepare, uint32_t cofs_mask)
{
int32_t rc;
uint64_t sqn;
rte_be64_t sqc;
struct rte_ipsec_sa *sa;
uint32_t i, k, n;
uint32_t l2, l3;
union sym_op_data icv;
struct rte_crypto_va_iova_ptr iv[num];
struct rte_crypto_va_iova_ptr aad[num];
struct rte_crypto_va_iova_ptr dgst[num];
uint32_t dr[num];
uint32_t l4ofs[num];
uint32_t clen[num];
uint64_t ivbuf[num][IPSEC_MAX_IV_QWORD];
sa = ss->sa;
n = num;
sqn = esn_outb_update_sqn(sa, &n);
if (n != num)
rte_errno = EOVERFLOW;
for (i = 0, k = 0; i != n; i++) {
l2 = mb[i]->l2_len;
l3 = mb[i]->l3_len;
/* calculate ESP header offset */
l4ofs[k] = (l2 + l3) & cofs_mask;
sqc = rte_cpu_to_be_64(sqn + i);
gen_iv(ivbuf[k], sqc);
/* try to update the packet itself */
rc = prepare(sa, sqc, ivbuf[k], mb[i], &icv, sa->sqh_len);
/* success, proceed with preparations */
if (rc >= 0) {
outb_pkt_xprepare(sa, sqc, &icv);
/* get encrypted data offset and length */
clen[k] = outb_cpu_crypto_prepare(sa, l4ofs + k, rc,
ivbuf[k]);
/* fill iv, digest and aad */
iv[k].va = ivbuf[k];
aad[k].va = icv.va + sa->icv_len;
dgst[k++].va = icv.va;
} else {
dr[i - k] = i;
rte_errno = -rc;
}
}
/* copy not prepared mbufs beyond good ones */
if (k != n && k != 0)
move_bad_mbufs(mb, dr, n, n - k);
/* convert mbufs to iovecs and do actual crypto/auth processing */
if (k != 0)
cpu_crypto_bulk(ss, sa->cofs, mb, iv, aad, dgst,
l4ofs, clen, k);
return k;
}
uint16_t
cpu_outb_tun_pkt_prepare(const struct rte_ipsec_session *ss,
struct rte_mbuf *mb[], uint16_t num)
{
return cpu_outb_pkt_prepare(ss, mb, num, outb_tun_pkt_prepare, 0);
}
uint16_t
cpu_outb_trs_pkt_prepare(const struct rte_ipsec_session *ss,
struct rte_mbuf *mb[], uint16_t num)
{
return cpu_outb_pkt_prepare(ss, mb, num, outb_trs_pkt_prepare,
UINT32_MAX);
}
/*
* process outbound packets for SA with ESN support,
* for algorithms that require SQN.hibits to be implictly included
* into digest computation.
* In that case we have to move ICV bytes back to their proper place.
*/
uint16_t
esp_outb_sqh_process(const struct rte_ipsec_session *ss, struct rte_mbuf *mb[],
uint16_t num)
{
uint32_t i, k, icv_len, *icv;
struct rte_mbuf *ml;
struct rte_ipsec_sa *sa;
uint32_t dr[num];
sa = ss->sa;
k = 0;
icv_len = sa->icv_len;
for (i = 0; i != num; i++) {
if ((mb[i]->ol_flags & PKT_RX_SEC_OFFLOAD_FAILED) == 0) {
ml = rte_pktmbuf_lastseg(mb[i]);
/* remove high-order 32 bits of esn from packet len */
mb[i]->pkt_len -= sa->sqh_len;
ml->data_len -= sa->sqh_len;
icv = rte_pktmbuf_mtod_offset(ml, void *,
ml->data_len - icv_len);
remove_sqh(icv, icv_len);
k++;
} else
dr[i - k] = i;
}
/* handle unprocessed mbufs */
if (k != num) {
rte_errno = EBADMSG;
if (k != 0)
move_bad_mbufs(mb, dr, num, num - k);
}
return k;
}
/*
* prepare packets for inline ipsec processing:
* set ol_flags and attach metadata.
*/
static inline void
inline_outb_mbuf_prepare(const struct rte_ipsec_session *ss,
struct rte_mbuf *mb[], uint16_t num)
{
uint32_t i, ol_flags;
ol_flags = ss->security.ol_flags & RTE_SECURITY_TX_OLOAD_NEED_MDATA;
for (i = 0; i != num; i++) {
mb[i]->ol_flags |= PKT_TX_SEC_OFFLOAD;
if (ol_flags != 0)
rte_security_set_pkt_metadata(ss->security.ctx,
ss->security.ses, mb[i], NULL);
}
}
/*
* process group of ESP outbound tunnel packets destined for
* INLINE_CRYPTO type of device.
*/
uint16_t
inline_outb_tun_pkt_process(const struct rte_ipsec_session *ss,
struct rte_mbuf *mb[], uint16_t num)
{
int32_t rc;
uint32_t i, k, n;
uint64_t sqn;
rte_be64_t sqc;
struct rte_ipsec_sa *sa;
union sym_op_data icv;
uint64_t iv[IPSEC_MAX_IV_QWORD];
uint32_t dr[num];
sa = ss->sa;
n = num;
sqn = esn_outb_update_sqn(sa, &n);
if (n != num)
rte_errno = EOVERFLOW;
k = 0;
for (i = 0; i != n; i++) {
sqc = rte_cpu_to_be_64(sqn + i);
gen_iv(iv, sqc);
/* try to update the packet itself */
rc = outb_tun_pkt_prepare(sa, sqc, iv, mb[i], &icv, 0);
k += (rc >= 0);
/* failure, put packet into the death-row */
if (rc < 0) {
dr[i - k] = i;
rte_errno = -rc;
}
}
/* copy not processed mbufs beyond good ones */
if (k != n && k != 0)
move_bad_mbufs(mb, dr, n, n - k);
inline_outb_mbuf_prepare(ss, mb, k);
return k;
}
/*
* process group of ESP outbound transport packets destined for
* INLINE_CRYPTO type of device.
*/
uint16_t
inline_outb_trs_pkt_process(const struct rte_ipsec_session *ss,
struct rte_mbuf *mb[], uint16_t num)
{
int32_t rc;
uint32_t i, k, n;
uint64_t sqn;
rte_be64_t sqc;
struct rte_ipsec_sa *sa;
union sym_op_data icv;
uint64_t iv[IPSEC_MAX_IV_QWORD];
uint32_t dr[num];
sa = ss->sa;
n = num;
sqn = esn_outb_update_sqn(sa, &n);
if (n != num)
rte_errno = EOVERFLOW;
k = 0;
for (i = 0; i != n; i++) {
sqc = rte_cpu_to_be_64(sqn + i);
gen_iv(iv, sqc);
/* try to update the packet itself */
rc = outb_trs_pkt_prepare(sa, sqc, iv, mb[i], &icv, 0);
k += (rc >= 0);
/* failure, put packet into the death-row */
if (rc < 0) {
dr[i - k] = i;
rte_errno = -rc;
}
}
/* copy not processed mbufs beyond good ones */
if (k != n && k != 0)
move_bad_mbufs(mb, dr, n, n - k);
inline_outb_mbuf_prepare(ss, mb, k);
return k;
}
/*
* outbound for RTE_SECURITY_ACTION_TYPE_INLINE_PROTOCOL:
* actual processing is done by HW/PMD, just set flags and metadata.
*/
uint16_t
inline_proto_outb_pkt_process(const struct rte_ipsec_session *ss,
struct rte_mbuf *mb[], uint16_t num)
{
inline_outb_mbuf_prepare(ss, mb, num);
return num;
}
|
118469.c | /*-
* BSD LICENSE
*
* Copyright (c) Intel Corporation.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Intel Corporation nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "spdk/rpc.h"
#include "spdk/string.h"
#include "spdk/notify.h"
#include "spdk/env.h"
#include "spdk/util.h"
#include "spdk_internal/log.h"
static int
notify_get_types_cb(const struct spdk_notify_type *type, void *ctx)
{
spdk_json_write_string((struct spdk_json_write_ctx *)ctx, spdk_notify_type_get_name(type));
return 0;
}
static void
rpc_notify_get_types(struct spdk_jsonrpc_request *request,
const struct spdk_json_val *params)
{
struct spdk_json_write_ctx *w;
if (params != NULL) {
spdk_jsonrpc_send_error_response(request, SPDK_JSONRPC_ERROR_INVALID_PARAMS,
"No parameters required");
return;
}
w = spdk_jsonrpc_begin_result(request);
spdk_json_write_array_begin(w);
spdk_notify_foreach_type(notify_get_types_cb, w);
spdk_json_write_array_end(w);
spdk_jsonrpc_end_result(request, w);
}
SPDK_RPC_REGISTER("notify_get_types", rpc_notify_get_types, SPDK_RPC_RUNTIME)
SPDK_RPC_REGISTER_ALIAS_DEPRECATED(notify_get_types, get_notification_types)
struct rpc_notify_get_notifications {
uint64_t id;
uint64_t max;
struct spdk_json_write_ctx *w;
};
static const struct spdk_json_object_decoder rpc_notify_get_notifications_decoders[] = {
{"id", offsetof(struct rpc_notify_get_notifications, id), spdk_json_decode_uint64, true},
{"max", offsetof(struct rpc_notify_get_notifications, max), spdk_json_decode_uint64, true},
};
static int
notify_get_notifications_cb(uint64_t id, const struct spdk_notify_event *ev, void *ctx)
{
struct rpc_notify_get_notifications *req = ctx;
spdk_json_write_object_begin(req->w);
spdk_json_write_named_string(req->w, "type", ev->type);
spdk_json_write_named_string(req->w, "ctx", ev->ctx);
spdk_json_write_named_uint64(req->w, "id", id);
spdk_json_write_object_end(req->w);
return 0;
}
static void
rpc_notify_get_notifications(struct spdk_jsonrpc_request *request,
const struct spdk_json_val *params)
{
struct rpc_notify_get_notifications req = {0, UINT64_MAX};
if (params &&
spdk_json_decode_object(params, rpc_notify_get_notifications_decoders,
SPDK_COUNTOF(rpc_notify_get_notifications_decoders), &req)) {
SPDK_DEBUGLOG(SPDK_NOTIFY_RPC, "spdk_json_decode_object failed\n");
spdk_jsonrpc_send_error_response(request, SPDK_JSONRPC_ERROR_INVALID_PARAMS,
spdk_strerror(EINVAL));
return;
}
req.w = spdk_jsonrpc_begin_result(request);
spdk_json_write_array_begin(req.w);
spdk_notify_foreach_event(req.id, req.max, notify_get_notifications_cb, &req);
spdk_json_write_array_end(req.w);
spdk_jsonrpc_end_result(request, req.w);
}
SPDK_RPC_REGISTER("notify_get_notifications", rpc_notify_get_notifications, SPDK_RPC_RUNTIME)
SPDK_RPC_REGISTER_ALIAS_DEPRECATED(notify_get_notifications, get_notifications)
SPDK_LOG_REGISTER_COMPONENT("notify_rpc", SPDK_NOTIFY_RPC)
|
923386.c | /**********************************************************************
* Copyright (c) 2013, 2014, 2015 Pieter Wuille, Gregory Maxwell *
* Distributed under the MIT software license, see the accompanying *
* file COPYING or http://www.opensource.org/licenses/mit-license.php.*
**********************************************************************/
#if defined HAVE_CONFIG_H
#include "libsecp256k1-config.h"
#endif
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include "secp256k1.c"
#include "include/secp256k1.h"
#include "testrand_impl.h"
#ifdef ENABLE_OPENSSL_TESTS
#include "openssl/bn.h"
#include "openssl/ec.h"
#include "openssl/ecdsa.h"
#include "openssl/obj_mac.h"
# if OPENSSL_VERSION_NUMBER < 0x10100000L
void ECDSA_SIG_get0(const ECDSA_SIG *sig, const BIGNUM **pr, const BIGNUM **ps) {*pr = sig->r; *ps = sig->s;}
# endif
#endif
#include "contrib/lax_der_parsing.c"
#include "contrib/lax_der_privatekey_parsing.c"
#if !defined(VG_CHECK)
# if defined(VALGRIND)
# include <valgrind/memcheck.h>
# define VG_UNDEF(x,y) VALGRIND_MAKE_MEM_UNDEFINED((x),(y))
# define VG_CHECK(x,y) VALGRIND_CHECK_MEM_IS_DEFINED((x),(y))
# else
# define VG_UNDEF(x,y)
# define VG_CHECK(x,y)
# endif
#endif
static int count = 64;
static secp256k1_context *ctx = NULL;
static void counting_illegal_callback_fn(const char* str, void* data) {
/* Dummy callback function that just counts. */
int32_t *p;
(void)str;
p = data;
(*p)++;
}
static void uncounting_illegal_callback_fn(const char* str, void* data) {
/* Dummy callback function that just counts (backwards). */
int32_t *p;
(void)str;
p = data;
(*p)--;
}
void random_field_element_test(secp256k1_fe *fe) {
do {
unsigned char b32[32];
secp256k1_rand256_test(b32);
if (secp256k1_fe_set_b32(fe, b32)) {
break;
}
} while(1);
}
void random_field_element_magnitude(secp256k1_fe *fe) {
secp256k1_fe zero;
int n = secp256k1_rand_int(9);
secp256k1_fe_normalize(fe);
if (n == 0) {
return;
}
secp256k1_fe_clear(&zero);
secp256k1_fe_negate(&zero, &zero, 0);
secp256k1_fe_mul_int(&zero, n - 1);
secp256k1_fe_add(fe, &zero);
VERIFY_CHECK(fe->magnitude == n);
}
void random_group_element_test(secp256k1_ge *ge) {
secp256k1_fe fe;
do {
random_field_element_test(&fe);
if (secp256k1_ge_set_xo_var(ge, &fe, secp256k1_rand_bits(1))) {
secp256k1_fe_normalize(&ge->y);
break;
}
} while(1);
}
void random_group_element_jacobian_test(secp256k1_gej *gej, const secp256k1_ge *ge) {
secp256k1_fe z2, z3;
do {
random_field_element_test(&gej->z);
if (!secp256k1_fe_is_zero(&gej->z)) {
break;
}
} while(1);
secp256k1_fe_sqr(&z2, &gej->z);
secp256k1_fe_mul(&z3, &z2, &gej->z);
secp256k1_fe_mul(&gej->x, &ge->x, &z2);
secp256k1_fe_mul(&gej->y, &ge->y, &z3);
gej->infinity = ge->infinity;
}
void random_scalar_order_test(secp256k1_scalar *num) {
do {
unsigned char b32[32];
int overflow = 0;
secp256k1_rand256_test(b32);
secp256k1_scalar_set_b32(num, b32, &overflow);
if (overflow || secp256k1_scalar_is_zero(num)) {
continue;
}
break;
} while(1);
}
void random_scalar_order(secp256k1_scalar *num) {
do {
unsigned char b32[32];
int overflow = 0;
secp256k1_rand256(b32);
secp256k1_scalar_set_b32(num, b32, &overflow);
if (overflow || secp256k1_scalar_is_zero(num)) {
continue;
}
break;
} while(1);
}
void run_context_tests(void) {
secp256k1_pubkey pubkey;
secp256k1_pubkey zero_pubkey;
secp256k1_ecdsa_signature sig;
unsigned char ctmp[32];
int32_t ecount;
int32_t ecount2;
secp256k1_context *none = secp256k1_context_create(SECP256K1_CONTEXT_NONE);
secp256k1_context *sign = secp256k1_context_create(SECP256K1_CONTEXT_SIGN);
secp256k1_context *vrfy = secp256k1_context_create(SECP256K1_CONTEXT_VERIFY);
secp256k1_context *both = secp256k1_context_create(SECP256K1_CONTEXT_SIGN | SECP256K1_CONTEXT_VERIFY);
secp256k1_gej pubj;
secp256k1_ge pub;
secp256k1_scalar msg, key, nonce;
secp256k1_scalar sigr, sigs;
memset(&zero_pubkey, 0, sizeof(zero_pubkey));
ecount = 0;
ecount2 = 10;
secp256k1_context_set_illegal_callback(vrfy, counting_illegal_callback_fn, &ecount);
secp256k1_context_set_illegal_callback(sign, counting_illegal_callback_fn, &ecount2);
secp256k1_context_set_error_callback(sign, counting_illegal_callback_fn, NULL);
CHECK(vrfy->error_callback.fn != sign->error_callback.fn);
/*** clone and destroy all of them to make sure cloning was complete ***/
{
secp256k1_context *ctx_tmp;
ctx_tmp = none; none = secp256k1_context_clone(none); secp256k1_context_destroy(ctx_tmp);
ctx_tmp = sign; sign = secp256k1_context_clone(sign); secp256k1_context_destroy(ctx_tmp);
ctx_tmp = vrfy; vrfy = secp256k1_context_clone(vrfy); secp256k1_context_destroy(ctx_tmp);
ctx_tmp = both; both = secp256k1_context_clone(both); secp256k1_context_destroy(ctx_tmp);
}
/* Verify that the error callback makes it across the clone. */
CHECK(vrfy->error_callback.fn != sign->error_callback.fn);
/* And that it resets back to default. */
secp256k1_context_set_error_callback(sign, NULL, NULL);
CHECK(vrfy->error_callback.fn == sign->error_callback.fn);
/*** attempt to use them ***/
random_scalar_order_test(&msg);
random_scalar_order_test(&key);
secp256k1_ecmult_gen(&both->ecmult_gen_ctx, &pubj, &key);
secp256k1_ge_set_gej(&pub, &pubj);
/* Verify context-type checking illegal-argument errors. */
memset(ctmp, 1, 32);
CHECK(secp256k1_ec_pubkey_create(vrfy, &pubkey, ctmp) == 0);
CHECK(ecount == 1);
VG_UNDEF(&pubkey, sizeof(pubkey));
CHECK(secp256k1_ec_pubkey_create(sign, &pubkey, ctmp) == 1);
VG_CHECK(&pubkey, sizeof(pubkey));
CHECK(secp256k1_ecdsa_sign(vrfy, &sig, ctmp, ctmp, NULL, NULL) == 0);
CHECK(ecount == 2);
VG_UNDEF(&sig, sizeof(sig));
CHECK(secp256k1_ecdsa_sign(sign, &sig, ctmp, ctmp, NULL, NULL) == 1);
VG_CHECK(&sig, sizeof(sig));
CHECK(ecount2 == 10);
CHECK(secp256k1_ecdsa_verify(sign, &sig, ctmp, &pubkey) == 0);
CHECK(ecount2 == 11);
CHECK(secp256k1_ecdsa_verify(vrfy, &sig, ctmp, &pubkey) == 1);
CHECK(ecount == 2);
CHECK(secp256k1_ec_pubkey_tweak_add(sign, &pubkey, ctmp) == 0);
CHECK(ecount2 == 12);
CHECK(secp256k1_ec_pubkey_tweak_add(vrfy, &pubkey, ctmp) == 1);
CHECK(ecount == 2);
CHECK(secp256k1_ec_pubkey_tweak_mul(sign, &pubkey, ctmp) == 0);
CHECK(ecount2 == 13);
CHECK(secp256k1_ec_pubkey_negate(vrfy, &pubkey) == 1);
CHECK(ecount == 2);
CHECK(secp256k1_ec_pubkey_negate(sign, &pubkey) == 1);
CHECK(ecount == 2);
CHECK(secp256k1_ec_pubkey_negate(sign, NULL) == 0);
CHECK(ecount2 == 14);
CHECK(secp256k1_ec_pubkey_negate(vrfy, &zero_pubkey) == 0);
CHECK(ecount == 3);
CHECK(secp256k1_ec_pubkey_tweak_mul(vrfy, &pubkey, ctmp) == 1);
CHECK(ecount == 3);
CHECK(secp256k1_context_randomize(vrfy, ctmp) == 0);
CHECK(ecount == 4);
CHECK(secp256k1_context_randomize(sign, NULL) == 1);
CHECK(ecount2 == 14);
secp256k1_context_set_illegal_callback(vrfy, NULL, NULL);
secp256k1_context_set_illegal_callback(sign, NULL, NULL);
/* This shouldn't leak memory, due to already-set tests. */
secp256k1_ecmult_gen_context_build(&sign->ecmult_gen_ctx, NULL);
secp256k1_ecmult_context_build(&vrfy->ecmult_ctx, NULL);
/* obtain a working nonce */
do {
random_scalar_order_test(&nonce);
} while(!secp256k1_ecdsa_sig_sign(&both->ecmult_gen_ctx, &sigr, &sigs, &key, &msg, &nonce, NULL));
/* try signing */
CHECK(secp256k1_ecdsa_sig_sign(&sign->ecmult_gen_ctx, &sigr, &sigs, &key, &msg, &nonce, NULL));
CHECK(secp256k1_ecdsa_sig_sign(&both->ecmult_gen_ctx, &sigr, &sigs, &key, &msg, &nonce, NULL));
/* try verifying */
CHECK(secp256k1_ecdsa_sig_verify(&vrfy->ecmult_ctx, &sigr, &sigs, &pub, &msg));
CHECK(secp256k1_ecdsa_sig_verify(&both->ecmult_ctx, &sigr, &sigs, &pub, &msg));
/* cleanup */
secp256k1_context_destroy(none);
secp256k1_context_destroy(sign);
secp256k1_context_destroy(vrfy);
secp256k1_context_destroy(both);
/* Defined as no-op. */
secp256k1_context_destroy(NULL);
}
void run_scratch_tests(void) {
int32_t ecount = 0;
secp256k1_context *none = secp256k1_context_create(SECP256K1_CONTEXT_NONE);
secp256k1_scratch_space *scratch;
/* Test public API */
secp256k1_context_set_illegal_callback(none, counting_illegal_callback_fn, &ecount);
scratch = secp256k1_scratch_space_create(none, 100, 10);
CHECK(scratch == NULL);
CHECK(ecount == 1);
scratch = secp256k1_scratch_space_create(none, 100, 100);
CHECK(scratch != NULL);
CHECK(ecount == 1);
secp256k1_scratch_space_destroy(scratch);
scratch = secp256k1_scratch_space_create(none, 100, 1000);
CHECK(scratch != NULL);
CHECK(ecount == 1);
/* Test internal API */
CHECK(secp256k1_scratch_max_allocation(scratch, 0) == 1000);
CHECK(secp256k1_scratch_max_allocation(scratch, 1) < 1000);
CHECK(secp256k1_scratch_resize(scratch, 50, 1) == 1); /* no-op */
CHECK(secp256k1_scratch_resize(scratch, 200, 1) == 1);
CHECK(secp256k1_scratch_resize(scratch, 950, 1) == 1);
CHECK(secp256k1_scratch_resize(scratch, 1000, 1) == 0);
CHECK(secp256k1_scratch_resize(scratch, 2000, 1) == 0);
CHECK(secp256k1_scratch_max_allocation(scratch, 0) == 1000);
/* cleanup */
secp256k1_scratch_space_destroy(scratch);
secp256k1_context_destroy(none);
}
/***** HASH TESTS *****/
void run_sha256_tests(void) {
static const char *inputs[8] = {
"", "abc", "message digest", "secure hash algorithm", "SHA256 is considered to be safe",
"abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq",
"For this sample, this 63-byte string will be used as input data",
"This is exactly 64 bytes long, not counting the terminating byte"
};
static const unsigned char outputs[8][32] = {
{0xe3, 0xb0, 0xc4, 0x42, 0x98, 0xfc, 0x1c, 0x14, 0x9a, 0xfb, 0xf4, 0xc8, 0x99, 0x6f, 0xb9, 0x24, 0x27, 0xae, 0x41, 0xe4, 0x64, 0x9b, 0x93, 0x4c, 0xa4, 0x95, 0x99, 0x1b, 0x78, 0x52, 0xb8, 0x55},
{0xba, 0x78, 0x16, 0xbf, 0x8f, 0x01, 0xcf, 0xea, 0x41, 0x41, 0x40, 0xde, 0x5d, 0xae, 0x22, 0x23, 0xb0, 0x03, 0x61, 0xa3, 0x96, 0x17, 0x7a, 0x9c, 0xb4, 0x10, 0xff, 0x61, 0xf2, 0x00, 0x15, 0xad},
{0xf7, 0x84, 0x6f, 0x55, 0xcf, 0x23, 0xe1, 0x4e, 0xeb, 0xea, 0xb5, 0xb4, 0xe1, 0x55, 0x0c, 0xad, 0x5b, 0x50, 0x9e, 0x33, 0x48, 0xfb, 0xc4, 0xef, 0xa3, 0xa1, 0x41, 0x3d, 0x39, 0x3c, 0xb6, 0x50},
{0xf3, 0x0c, 0xeb, 0x2b, 0xb2, 0x82, 0x9e, 0x79, 0xe4, 0xca, 0x97, 0x53, 0xd3, 0x5a, 0x8e, 0xcc, 0x00, 0x26, 0x2d, 0x16, 0x4c, 0xc0, 0x77, 0x08, 0x02, 0x95, 0x38, 0x1c, 0xbd, 0x64, 0x3f, 0x0d},
{0x68, 0x19, 0xd9, 0x15, 0xc7, 0x3f, 0x4d, 0x1e, 0x77, 0xe4, 0xe1, 0xb5, 0x2d, 0x1f, 0xa0, 0xf9, 0xcf, 0x9b, 0xea, 0xea, 0xd3, 0x93, 0x9f, 0x15, 0x87, 0x4b, 0xd9, 0x88, 0xe2, 0xa2, 0x36, 0x30},
{0x24, 0x8d, 0x6a, 0x61, 0xd2, 0x06, 0x38, 0xb8, 0xe5, 0xc0, 0x26, 0x93, 0x0c, 0x3e, 0x60, 0x39, 0xa3, 0x3c, 0xe4, 0x59, 0x64, 0xff, 0x21, 0x67, 0xf6, 0xec, 0xed, 0xd4, 0x19, 0xdb, 0x06, 0xc1},
{0xf0, 0x8a, 0x78, 0xcb, 0xba, 0xee, 0x08, 0x2b, 0x05, 0x2a, 0xe0, 0x70, 0x8f, 0x32, 0xfa, 0x1e, 0x50, 0xc5, 0xc4, 0x21, 0xaa, 0x77, 0x2b, 0xa5, 0xdb, 0xb4, 0x06, 0xa2, 0xea, 0x6b, 0xe3, 0x42},
{0xab, 0x64, 0xef, 0xf7, 0xe8, 0x8e, 0x2e, 0x46, 0x16, 0x5e, 0x29, 0xf2, 0xbc, 0xe4, 0x18, 0x26, 0xbd, 0x4c, 0x7b, 0x35, 0x52, 0xf6, 0xb3, 0x82, 0xa9, 0xe7, 0xd3, 0xaf, 0x47, 0xc2, 0x45, 0xf8}
};
int i;
for (i = 0; i < 8; i++) {
unsigned char out[32];
secp256k1_sha256 hasher;
secp256k1_sha256_initialize(&hasher);
secp256k1_sha256_write(&hasher, (const unsigned char*)(inputs[i]), strlen(inputs[i]));
secp256k1_sha256_finalize(&hasher, out);
CHECK(memcmp(out, outputs[i], 32) == 0);
if (strlen(inputs[i]) > 0) {
int split = secp256k1_rand_int(strlen(inputs[i]));
secp256k1_sha256_initialize(&hasher);
secp256k1_sha256_write(&hasher, (const unsigned char*)(inputs[i]), split);
secp256k1_sha256_write(&hasher, (const unsigned char*)(inputs[i] + split), strlen(inputs[i]) - split);
secp256k1_sha256_finalize(&hasher, out);
CHECK(memcmp(out, outputs[i], 32) == 0);
}
}
}
void run_hmac_sha256_tests(void) {
static const char *keys[6] = {
"\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b",
"\x4a\x65\x66\x65",
"\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa",
"\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19",
"\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa",
"\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa"
};
static const char *inputs[6] = {
"\x48\x69\x20\x54\x68\x65\x72\x65",
"\x77\x68\x61\x74\x20\x64\x6f\x20\x79\x61\x20\x77\x61\x6e\x74\x20\x66\x6f\x72\x20\x6e\x6f\x74\x68\x69\x6e\x67\x3f",
"\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd",
"\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd",
"\x54\x65\x73\x74\x20\x55\x73\x69\x6e\x67\x20\x4c\x61\x72\x67\x65\x72\x20\x54\x68\x61\x6e\x20\x42\x6c\x6f\x63\x6b\x2d\x53\x69\x7a\x65\x20\x4b\x65\x79\x20\x2d\x20\x48\x61\x73\x68\x20\x4b\x65\x79\x20\x46\x69\x72\x73\x74",
"\x54\x68\x69\x73\x20\x69\x73\x20\x61\x20\x74\x65\x73\x74\x20\x75\x73\x69\x6e\x67\x20\x61\x20\x6c\x61\x72\x67\x65\x72\x20\x74\x68\x61\x6e\x20\x62\x6c\x6f\x63\x6b\x2d\x73\x69\x7a\x65\x20\x6b\x65\x79\x20\x61\x6e\x64\x20\x61\x20\x6c\x61\x72\x67\x65\x72\x20\x74\x68\x61\x6e\x20\x62\x6c\x6f\x63\x6b\x2d\x73\x69\x7a\x65\x20\x64\x61\x74\x61\x2e\x20\x54\x68\x65\x20\x6b\x65\x79\x20\x6e\x65\x65\x64\x73\x20\x74\x6f\x20\x62\x65\x20\x68\x61\x73\x68\x65\x64\x20\x62\x65\x66\x6f\x72\x65\x20\x62\x65\x69\x6e\x67\x20\x75\x73\x65\x64\x20\x62\x79\x20\x74\x68\x65\x20\x48\x4d\x41\x43\x20\x61\x6c\x67\x6f\x72\x69\x74\x68\x6d\x2e"
};
static const unsigned char outputs[6][32] = {
{0xb0, 0x34, 0x4c, 0x61, 0xd8, 0xdb, 0x38, 0x53, 0x5c, 0xa8, 0xaf, 0xce, 0xaf, 0x0b, 0xf1, 0x2b, 0x88, 0x1d, 0xc2, 0x00, 0xc9, 0x83, 0x3d, 0xa7, 0x26, 0xe9, 0x37, 0x6c, 0x2e, 0x32, 0xcf, 0xf7},
{0x5b, 0xdc, 0xc1, 0x46, 0xbf, 0x60, 0x75, 0x4e, 0x6a, 0x04, 0x24, 0x26, 0x08, 0x95, 0x75, 0xc7, 0x5a, 0x00, 0x3f, 0x08, 0x9d, 0x27, 0x39, 0x83, 0x9d, 0xec, 0x58, 0xb9, 0x64, 0xec, 0x38, 0x43},
{0x77, 0x3e, 0xa9, 0x1e, 0x36, 0x80, 0x0e, 0x46, 0x85, 0x4d, 0xb8, 0xeb, 0xd0, 0x91, 0x81, 0xa7, 0x29, 0x59, 0x09, 0x8b, 0x3e, 0xf8, 0xc1, 0x22, 0xd9, 0x63, 0x55, 0x14, 0xce, 0xd5, 0x65, 0xfe},
{0x82, 0x55, 0x8a, 0x38, 0x9a, 0x44, 0x3c, 0x0e, 0xa4, 0xcc, 0x81, 0x98, 0x99, 0xf2, 0x08, 0x3a, 0x85, 0xf0, 0xfa, 0xa3, 0xe5, 0x78, 0xf8, 0x07, 0x7a, 0x2e, 0x3f, 0xf4, 0x67, 0x29, 0x66, 0x5b},
{0x60, 0xe4, 0x31, 0x59, 0x1e, 0xe0, 0xb6, 0x7f, 0x0d, 0x8a, 0x26, 0xaa, 0xcb, 0xf5, 0xb7, 0x7f, 0x8e, 0x0b, 0xc6, 0x21, 0x37, 0x28, 0xc5, 0x14, 0x05, 0x46, 0x04, 0x0f, 0x0e, 0xe3, 0x7f, 0x54},
{0x9b, 0x09, 0xff, 0xa7, 0x1b, 0x94, 0x2f, 0xcb, 0x27, 0x63, 0x5f, 0xbc, 0xd5, 0xb0, 0xe9, 0x44, 0xbf, 0xdc, 0x63, 0x64, 0x4f, 0x07, 0x13, 0x93, 0x8a, 0x7f, 0x51, 0x53, 0x5c, 0x3a, 0x35, 0xe2}
};
int i;
for (i = 0; i < 6; i++) {
secp256k1_hmac_sha256 hasher;
unsigned char out[32];
secp256k1_hmac_sha256_initialize(&hasher, (const unsigned char*)(keys[i]), strlen(keys[i]));
secp256k1_hmac_sha256_write(&hasher, (const unsigned char*)(inputs[i]), strlen(inputs[i]));
secp256k1_hmac_sha256_finalize(&hasher, out);
CHECK(memcmp(out, outputs[i], 32) == 0);
if (strlen(inputs[i]) > 0) {
int split = secp256k1_rand_int(strlen(inputs[i]));
secp256k1_hmac_sha256_initialize(&hasher, (const unsigned char*)(keys[i]), strlen(keys[i]));
secp256k1_hmac_sha256_write(&hasher, (const unsigned char*)(inputs[i]), split);
secp256k1_hmac_sha256_write(&hasher, (const unsigned char*)(inputs[i] + split), strlen(inputs[i]) - split);
secp256k1_hmac_sha256_finalize(&hasher, out);
CHECK(memcmp(out, outputs[i], 32) == 0);
}
}
}
void run_rfc6979_hmac_sha256_tests(void) {
static const unsigned char key1[65] = {0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x00, 0x4b, 0xf5, 0x12, 0x2f, 0x34, 0x45, 0x54, 0xc5, 0x3b, 0xde, 0x2e, 0xbb, 0x8c, 0xd2, 0xb7, 0xe3, 0xd1, 0x60, 0x0a, 0xd6, 0x31, 0xc3, 0x85, 0xa5, 0xd7, 0xcc, 0xe2, 0x3c, 0x77, 0x85, 0x45, 0x9a, 0};
static const unsigned char out1[3][32] = {
{0x4f, 0xe2, 0x95, 0x25, 0xb2, 0x08, 0x68, 0x09, 0x15, 0x9a, 0xcd, 0xf0, 0x50, 0x6e, 0xfb, 0x86, 0xb0, 0xec, 0x93, 0x2c, 0x7b, 0xa4, 0x42, 0x56, 0xab, 0x32, 0x1e, 0x42, 0x1e, 0x67, 0xe9, 0xfb},
{0x2b, 0xf0, 0xff, 0xf1, 0xd3, 0xc3, 0x78, 0xa2, 0x2d, 0xc5, 0xde, 0x1d, 0x85, 0x65, 0x22, 0x32, 0x5c, 0x65, 0xb5, 0x04, 0x49, 0x1a, 0x0c, 0xbd, 0x01, 0xcb, 0x8f, 0x3a, 0xa6, 0x7f, 0xfd, 0x4a},
{0xf5, 0x28, 0xb4, 0x10, 0xcb, 0x54, 0x1f, 0x77, 0x00, 0x0d, 0x7a, 0xfb, 0x6c, 0x5b, 0x53, 0xc5, 0xc4, 0x71, 0xea, 0xb4, 0x3e, 0x46, 0x6d, 0x9a, 0xc5, 0x19, 0x0c, 0x39, 0xc8, 0x2f, 0xd8, 0x2e}
};
static const unsigned char key2[64] = {0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xe3, 0xb0, 0xc4, 0x42, 0x98, 0xfc, 0x1c, 0x14, 0x9a, 0xfb, 0xf4, 0xc8, 0x99, 0x6f, 0xb9, 0x24, 0x27, 0xae, 0x41, 0xe4, 0x64, 0x9b, 0x93, 0x4c, 0xa4, 0x95, 0x99, 0x1b, 0x78, 0x52, 0xb8, 0x55};
static const unsigned char out2[3][32] = {
{0x9c, 0x23, 0x6c, 0x16, 0x5b, 0x82, 0xae, 0x0c, 0xd5, 0x90, 0x65, 0x9e, 0x10, 0x0b, 0x6b, 0xab, 0x30, 0x36, 0xe7, 0xba, 0x8b, 0x06, 0x74, 0x9b, 0xaf, 0x69, 0x81, 0xe1, 0x6f, 0x1a, 0x2b, 0x95},
{0xdf, 0x47, 0x10, 0x61, 0x62, 0x5b, 0xc0, 0xea, 0x14, 0xb6, 0x82, 0xfe, 0xee, 0x2c, 0x9c, 0x02, 0xf2, 0x35, 0xda, 0x04, 0x20, 0x4c, 0x1d, 0x62, 0xa1, 0x53, 0x6c, 0x6e, 0x17, 0xae, 0xd7, 0xa9},
{0x75, 0x97, 0x88, 0x7c, 0xbd, 0x76, 0x32, 0x1f, 0x32, 0xe3, 0x04, 0x40, 0x67, 0x9a, 0x22, 0xcf, 0x7f, 0x8d, 0x9d, 0x2e, 0xac, 0x39, 0x0e, 0x58, 0x1f, 0xea, 0x09, 0x1c, 0xe2, 0x02, 0xba, 0x94}
};
secp256k1_rfc6979_hmac_sha256 rng;
unsigned char out[32];
int i;
secp256k1_rfc6979_hmac_sha256_initialize(&rng, key1, 64);
for (i = 0; i < 3; i++) {
secp256k1_rfc6979_hmac_sha256_generate(&rng, out, 32);
CHECK(memcmp(out, out1[i], 32) == 0);
}
secp256k1_rfc6979_hmac_sha256_finalize(&rng);
secp256k1_rfc6979_hmac_sha256_initialize(&rng, key1, 65);
for (i = 0; i < 3; i++) {
secp256k1_rfc6979_hmac_sha256_generate(&rng, out, 32);
CHECK(memcmp(out, out1[i], 32) != 0);
}
secp256k1_rfc6979_hmac_sha256_finalize(&rng);
secp256k1_rfc6979_hmac_sha256_initialize(&rng, key2, 64);
for (i = 0; i < 3; i++) {
secp256k1_rfc6979_hmac_sha256_generate(&rng, out, 32);
CHECK(memcmp(out, out2[i], 32) == 0);
}
secp256k1_rfc6979_hmac_sha256_finalize(&rng);
}
/***** RANDOM TESTS *****/
void test_rand_bits(int rand32, int bits) {
/* (1-1/2^B)^rounds[B] < 1/10^9, so rounds is the number of iterations to
* get a false negative chance below once in a billion */
static const unsigned int rounds[7] = {1, 30, 73, 156, 322, 653, 1316};
/* We try multiplying the results with various odd numbers, which shouldn't
* influence the uniform distribution modulo a power of 2. */
static const uint32_t mults[6] = {1, 3, 21, 289, 0x9999, 0x80402011};
/* We only select up to 6 bits from the output to analyse */
unsigned int usebits = bits > 6 ? 6 : bits;
unsigned int maxshift = bits - usebits;
/* For each of the maxshift+1 usebits-bit sequences inside a bits-bit
number, track all observed outcomes, one per bit in a uint64_t. */
uint64_t x[6][27] = {{0}};
unsigned int i, shift, m;
/* Multiply the output of all rand calls with the odd number m, which
should not change the uniformity of its distribution. */
for (i = 0; i < rounds[usebits]; i++) {
uint32_t r = (rand32 ? secp256k1_rand32() : secp256k1_rand_bits(bits));
CHECK((((uint64_t)r) >> bits) == 0);
for (m = 0; m < sizeof(mults) / sizeof(mults[0]); m++) {
uint32_t rm = r * mults[m];
for (shift = 0; shift <= maxshift; shift++) {
x[m][shift] |= (((uint64_t)1) << ((rm >> shift) & ((1 << usebits) - 1)));
}
}
}
for (m = 0; m < sizeof(mults) / sizeof(mults[0]); m++) {
for (shift = 0; shift <= maxshift; shift++) {
/* Test that the lower usebits bits of x[shift] are 1 */
CHECK(((~x[m][shift]) << (64 - (1 << usebits))) == 0);
}
}
}
/* Subrange must be a whole divisor of range, and at most 64 */
void test_rand_int(uint32_t range, uint32_t subrange) {
/* (1-1/subrange)^rounds < 1/10^9 */
int rounds = (subrange * 2073) / 100;
int i;
uint64_t x = 0;
CHECK((range % subrange) == 0);
for (i = 0; i < rounds; i++) {
uint32_t r = secp256k1_rand_int(range);
CHECK(r < range);
r = r % subrange;
x |= (((uint64_t)1) << r);
}
/* Test that the lower subrange bits of x are 1. */
CHECK(((~x) << (64 - subrange)) == 0);
}
void run_rand_bits(void) {
size_t b;
test_rand_bits(1, 32);
for (b = 1; b <= 32; b++) {
test_rand_bits(0, b);
}
}
void run_rand_int(void) {
static const uint32_t ms[] = {1, 3, 17, 1000, 13771, 999999, 33554432};
static const uint32_t ss[] = {1, 3, 6, 9, 13, 31, 64};
unsigned int m, s;
for (m = 0; m < sizeof(ms) / sizeof(ms[0]); m++) {
for (s = 0; s < sizeof(ss) / sizeof(ss[0]); s++) {
test_rand_int(ms[m] * ss[s], ss[s]);
}
}
}
/***** NUM TESTS *****/
#ifndef USE_NUM_NONE
void random_num_negate(secp256k1_num *num) {
if (secp256k1_rand_bits(1)) {
secp256k1_num_negate(num);
}
}
void random_num_order_test(secp256k1_num *num) {
secp256k1_scalar sc;
random_scalar_order_test(&sc);
secp256k1_scalar_get_num(num, &sc);
}
void random_num_order(secp256k1_num *num) {
secp256k1_scalar sc;
random_scalar_order(&sc);
secp256k1_scalar_get_num(num, &sc);
}
void test_num_negate(void) {
secp256k1_num n1;
secp256k1_num n2;
random_num_order_test(&n1); /* n1 = R */
random_num_negate(&n1);
secp256k1_num_copy(&n2, &n1); /* n2 = R */
secp256k1_num_sub(&n1, &n2, &n1); /* n1 = n2-n1 = 0 */
CHECK(secp256k1_num_is_zero(&n1));
secp256k1_num_copy(&n1, &n2); /* n1 = R */
secp256k1_num_negate(&n1); /* n1 = -R */
CHECK(!secp256k1_num_is_zero(&n1));
secp256k1_num_add(&n1, &n2, &n1); /* n1 = n2+n1 = 0 */
CHECK(secp256k1_num_is_zero(&n1));
secp256k1_num_copy(&n1, &n2); /* n1 = R */
secp256k1_num_negate(&n1); /* n1 = -R */
CHECK(secp256k1_num_is_neg(&n1) != secp256k1_num_is_neg(&n2));
secp256k1_num_negate(&n1); /* n1 = R */
CHECK(secp256k1_num_eq(&n1, &n2));
}
void test_num_add_sub(void) {
int i;
secp256k1_scalar s;
secp256k1_num n1;
secp256k1_num n2;
secp256k1_num n1p2, n2p1, n1m2, n2m1;
random_num_order_test(&n1); /* n1 = R1 */
if (secp256k1_rand_bits(1)) {
random_num_negate(&n1);
}
random_num_order_test(&n2); /* n2 = R2 */
if (secp256k1_rand_bits(1)) {
random_num_negate(&n2);
}
secp256k1_num_add(&n1p2, &n1, &n2); /* n1p2 = R1 + R2 */
secp256k1_num_add(&n2p1, &n2, &n1); /* n2p1 = R2 + R1 */
secp256k1_num_sub(&n1m2, &n1, &n2); /* n1m2 = R1 - R2 */
secp256k1_num_sub(&n2m1, &n2, &n1); /* n2m1 = R2 - R1 */
CHECK(secp256k1_num_eq(&n1p2, &n2p1));
CHECK(!secp256k1_num_eq(&n1p2, &n1m2));
secp256k1_num_negate(&n2m1); /* n2m1 = -R2 + R1 */
CHECK(secp256k1_num_eq(&n2m1, &n1m2));
CHECK(!secp256k1_num_eq(&n2m1, &n1));
secp256k1_num_add(&n2m1, &n2m1, &n2); /* n2m1 = -R2 + R1 + R2 = R1 */
CHECK(secp256k1_num_eq(&n2m1, &n1));
CHECK(!secp256k1_num_eq(&n2p1, &n1));
secp256k1_num_sub(&n2p1, &n2p1, &n2); /* n2p1 = R2 + R1 - R2 = R1 */
CHECK(secp256k1_num_eq(&n2p1, &n1));
/* check is_one */
secp256k1_scalar_set_int(&s, 1);
secp256k1_scalar_get_num(&n1, &s);
CHECK(secp256k1_num_is_one(&n1));
/* check that 2^n + 1 is never 1 */
secp256k1_scalar_get_num(&n2, &s);
for (i = 0; i < 250; ++i) {
secp256k1_num_add(&n1, &n1, &n1); /* n1 *= 2 */
secp256k1_num_add(&n1p2, &n1, &n2); /* n1p2 = n1 + 1 */
CHECK(!secp256k1_num_is_one(&n1p2));
}
}
void test_num_mod(void) {
int i;
secp256k1_scalar s;
secp256k1_num order, n;
/* check that 0 mod anything is 0 */
random_scalar_order_test(&s);
secp256k1_scalar_get_num(&order, &s);
secp256k1_scalar_set_int(&s, 0);
secp256k1_scalar_get_num(&n, &s);
secp256k1_num_mod(&n, &order);
CHECK(secp256k1_num_is_zero(&n));
/* check that anything mod 1 is 0 */
secp256k1_scalar_set_int(&s, 1);
secp256k1_scalar_get_num(&order, &s);
secp256k1_scalar_get_num(&n, &s);
secp256k1_num_mod(&n, &order);
CHECK(secp256k1_num_is_zero(&n));
/* check that increasing the number past 2^256 does not break this */
random_scalar_order_test(&s);
secp256k1_scalar_get_num(&n, &s);
/* multiply by 2^8, which'll test this case with high probability */
for (i = 0; i < 8; ++i) {
secp256k1_num_add(&n, &n, &n);
}
secp256k1_num_mod(&n, &order);
CHECK(secp256k1_num_is_zero(&n));
}
void test_num_jacobi(void) {
secp256k1_scalar sqr;
secp256k1_scalar small;
secp256k1_scalar five; /* five is not a quadratic residue */
secp256k1_num order, n;
int i;
/* squares mod 5 are 1, 4 */
const int jacobi5[10] = { 0, 1, -1, -1, 1, 0, 1, -1, -1, 1 };
/* check some small values with 5 as the order */
secp256k1_scalar_set_int(&five, 5);
secp256k1_scalar_get_num(&order, &five);
for (i = 0; i < 10; ++i) {
secp256k1_scalar_set_int(&small, i);
secp256k1_scalar_get_num(&n, &small);
CHECK(secp256k1_num_jacobi(&n, &order) == jacobi5[i]);
}
/** test large values with 5 as group order */
secp256k1_scalar_get_num(&order, &five);
/* we first need a scalar which is not a multiple of 5 */
do {
secp256k1_num fiven;
random_scalar_order_test(&sqr);
secp256k1_scalar_get_num(&fiven, &five);
secp256k1_scalar_get_num(&n, &sqr);
secp256k1_num_mod(&n, &fiven);
} while (secp256k1_num_is_zero(&n));
/* next force it to be a residue. 2 is a nonresidue mod 5 so we can
* just multiply by two, i.e. add the number to itself */
if (secp256k1_num_jacobi(&n, &order) == -1) {
secp256k1_num_add(&n, &n, &n);
}
/* test residue */
CHECK(secp256k1_num_jacobi(&n, &order) == 1);
/* test nonresidue */
secp256k1_num_add(&n, &n, &n);
CHECK(secp256k1_num_jacobi(&n, &order) == -1);
/** test with secp group order as order */
secp256k1_scalar_order_get_num(&order);
random_scalar_order_test(&sqr);
secp256k1_scalar_sqr(&sqr, &sqr);
/* test residue */
secp256k1_scalar_get_num(&n, &sqr);
CHECK(secp256k1_num_jacobi(&n, &order) == 1);
/* test nonresidue */
secp256k1_scalar_mul(&sqr, &sqr, &five);
secp256k1_scalar_get_num(&n, &sqr);
CHECK(secp256k1_num_jacobi(&n, &order) == -1);
/* test multiple of the order*/
CHECK(secp256k1_num_jacobi(&order, &order) == 0);
/* check one less than the order */
secp256k1_scalar_set_int(&small, 1);
secp256k1_scalar_get_num(&n, &small);
secp256k1_num_sub(&n, &order, &n);
CHECK(secp256k1_num_jacobi(&n, &order) == 1); /* sage confirms this is 1 */
}
void run_num_smalltests(void) {
int i;
for (i = 0; i < 100*count; i++) {
test_num_negate();
test_num_add_sub();
test_num_mod();
test_num_jacobi();
}
}
#endif
/***** SCALAR TESTS *****/
void scalar_test(void) {
secp256k1_scalar s;
secp256k1_scalar s1;
secp256k1_scalar s2;
#ifndef USE_NUM_NONE
secp256k1_num snum, s1num, s2num;
secp256k1_num order, half_order;
#endif
unsigned char c[32];
/* Set 's' to a random scalar, with value 'snum'. */
random_scalar_order_test(&s);
/* Set 's1' to a random scalar, with value 's1num'. */
random_scalar_order_test(&s1);
/* Set 's2' to a random scalar, with value 'snum2', and byte array representation 'c'. */
random_scalar_order_test(&s2);
secp256k1_scalar_get_b32(c, &s2);
#ifndef USE_NUM_NONE
secp256k1_scalar_get_num(&snum, &s);
secp256k1_scalar_get_num(&s1num, &s1);
secp256k1_scalar_get_num(&s2num, &s2);
secp256k1_scalar_order_get_num(&order);
half_order = order;
secp256k1_num_shift(&half_order, 1);
#endif
{
int i;
/* Test that fetching groups of 4 bits from a scalar and recursing n(i)=16*n(i-1)+p(i) reconstructs it. */
secp256k1_scalar n;
secp256k1_scalar_set_int(&n, 0);
for (i = 0; i < 256; i += 4) {
secp256k1_scalar t;
int j;
secp256k1_scalar_set_int(&t, secp256k1_scalar_get_bits(&s, 256 - 4 - i, 4));
for (j = 0; j < 4; j++) {
secp256k1_scalar_add(&n, &n, &n);
}
secp256k1_scalar_add(&n, &n, &t);
}
CHECK(secp256k1_scalar_eq(&n, &s));
}
{
/* Test that fetching groups of randomly-sized bits from a scalar and recursing n(i)=b*n(i-1)+p(i) reconstructs it. */
secp256k1_scalar n;
int i = 0;
secp256k1_scalar_set_int(&n, 0);
while (i < 256) {
secp256k1_scalar t;
int j;
int now = secp256k1_rand_int(15) + 1;
if (now + i > 256) {
now = 256 - i;
}
secp256k1_scalar_set_int(&t, secp256k1_scalar_get_bits_var(&s, 256 - now - i, now));
for (j = 0; j < now; j++) {
secp256k1_scalar_add(&n, &n, &n);
}
secp256k1_scalar_add(&n, &n, &t);
i += now;
}
CHECK(secp256k1_scalar_eq(&n, &s));
}
#ifndef USE_NUM_NONE
{
/* Test that adding the scalars together is equal to adding their numbers together modulo the order. */
secp256k1_num rnum;
secp256k1_num r2num;
secp256k1_scalar r;
secp256k1_num_add(&rnum, &snum, &s2num);
secp256k1_num_mod(&rnum, &order);
secp256k1_scalar_add(&r, &s, &s2);
secp256k1_scalar_get_num(&r2num, &r);
CHECK(secp256k1_num_eq(&rnum, &r2num));
}
{
/* Test that multiplying the scalars is equal to multiplying their numbers modulo the order. */
secp256k1_scalar r;
secp256k1_num r2num;
secp256k1_num rnum;
secp256k1_num_mul(&rnum, &snum, &s2num);
secp256k1_num_mod(&rnum, &order);
secp256k1_scalar_mul(&r, &s, &s2);
secp256k1_scalar_get_num(&r2num, &r);
CHECK(secp256k1_num_eq(&rnum, &r2num));
/* The result can only be zero if at least one of the factors was zero. */
CHECK(secp256k1_scalar_is_zero(&r) == (secp256k1_scalar_is_zero(&s) || secp256k1_scalar_is_zero(&s2)));
/* The results can only be equal to one of the factors if that factor was zero, or the other factor was one. */
CHECK(secp256k1_num_eq(&rnum, &snum) == (secp256k1_scalar_is_zero(&s) || secp256k1_scalar_is_one(&s2)));
CHECK(secp256k1_num_eq(&rnum, &s2num) == (secp256k1_scalar_is_zero(&s2) || secp256k1_scalar_is_one(&s)));
}
{
secp256k1_scalar neg;
secp256k1_num negnum;
secp256k1_num negnum2;
/* Check that comparison with zero matches comparison with zero on the number. */
CHECK(secp256k1_num_is_zero(&snum) == secp256k1_scalar_is_zero(&s));
/* Check that comparison with the half order is equal to testing for high scalar. */
CHECK(secp256k1_scalar_is_high(&s) == (secp256k1_num_cmp(&snum, &half_order) > 0));
secp256k1_scalar_negate(&neg, &s);
secp256k1_num_sub(&negnum, &order, &snum);
secp256k1_num_mod(&negnum, &order);
/* Check that comparison with the half order is equal to testing for high scalar after negation. */
CHECK(secp256k1_scalar_is_high(&neg) == (secp256k1_num_cmp(&negnum, &half_order) > 0));
/* Negating should change the high property, unless the value was already zero. */
CHECK((secp256k1_scalar_is_high(&s) == secp256k1_scalar_is_high(&neg)) == secp256k1_scalar_is_zero(&s));
secp256k1_scalar_get_num(&negnum2, &neg);
/* Negating a scalar should be equal to (order - n) mod order on the number. */
CHECK(secp256k1_num_eq(&negnum, &negnum2));
secp256k1_scalar_add(&neg, &neg, &s);
/* Adding a number to its negation should result in zero. */
CHECK(secp256k1_scalar_is_zero(&neg));
secp256k1_scalar_negate(&neg, &neg);
/* Negating zero should still result in zero. */
CHECK(secp256k1_scalar_is_zero(&neg));
}
{
/* Test secp256k1_scalar_mul_shift_var. */
secp256k1_scalar r;
secp256k1_num one;
secp256k1_num rnum;
secp256k1_num rnum2;
unsigned char cone[1] = {0x01};
unsigned int shift = 256 + secp256k1_rand_int(257);
secp256k1_scalar_mul_shift_var(&r, &s1, &s2, shift);
secp256k1_num_mul(&rnum, &s1num, &s2num);
secp256k1_num_shift(&rnum, shift - 1);
secp256k1_num_set_bin(&one, cone, 1);
secp256k1_num_add(&rnum, &rnum, &one);
secp256k1_num_shift(&rnum, 1);
secp256k1_scalar_get_num(&rnum2, &r);
CHECK(secp256k1_num_eq(&rnum, &rnum2));
}
{
/* test secp256k1_scalar_shr_int */
secp256k1_scalar r;
int i;
random_scalar_order_test(&r);
for (i = 0; i < 100; ++i) {
int low;
int shift = 1 + secp256k1_rand_int(15);
int expected = r.d[0] % (1 << shift);
low = secp256k1_scalar_shr_int(&r, shift);
CHECK(expected == low);
}
}
#endif
{
/* Test that scalar inverses are equal to the inverse of their number modulo the order. */
if (!secp256k1_scalar_is_zero(&s)) {
secp256k1_scalar inv;
#ifndef USE_NUM_NONE
secp256k1_num invnum;
secp256k1_num invnum2;
#endif
secp256k1_scalar_inverse(&inv, &s);
#ifndef USE_NUM_NONE
secp256k1_num_mod_inverse(&invnum, &snum, &order);
secp256k1_scalar_get_num(&invnum2, &inv);
CHECK(secp256k1_num_eq(&invnum, &invnum2));
#endif
secp256k1_scalar_mul(&inv, &inv, &s);
/* Multiplying a scalar with its inverse must result in one. */
CHECK(secp256k1_scalar_is_one(&inv));
secp256k1_scalar_inverse(&inv, &inv);
/* Inverting one must result in one. */
CHECK(secp256k1_scalar_is_one(&inv));
#ifndef USE_NUM_NONE
secp256k1_scalar_get_num(&invnum, &inv);
CHECK(secp256k1_num_is_one(&invnum));
#endif
}
}
{
/* Test commutativity of add. */
secp256k1_scalar r1, r2;
secp256k1_scalar_add(&r1, &s1, &s2);
secp256k1_scalar_add(&r2, &s2, &s1);
CHECK(secp256k1_scalar_eq(&r1, &r2));
}
{
secp256k1_scalar r1, r2;
secp256k1_scalar b;
int i;
/* Test add_bit. */
int bit = secp256k1_rand_bits(8);
secp256k1_scalar_set_int(&b, 1);
CHECK(secp256k1_scalar_is_one(&b));
for (i = 0; i < bit; i++) {
secp256k1_scalar_add(&b, &b, &b);
}
r1 = s1;
r2 = s1;
if (!secp256k1_scalar_add(&r1, &r1, &b)) {
/* No overflow happened. */
secp256k1_scalar_cadd_bit(&r2, bit, 1);
CHECK(secp256k1_scalar_eq(&r1, &r2));
/* cadd is a noop when flag is zero */
secp256k1_scalar_cadd_bit(&r2, bit, 0);
CHECK(secp256k1_scalar_eq(&r1, &r2));
}
}
{
/* Test commutativity of mul. */
secp256k1_scalar r1, r2;
secp256k1_scalar_mul(&r1, &s1, &s2);
secp256k1_scalar_mul(&r2, &s2, &s1);
CHECK(secp256k1_scalar_eq(&r1, &r2));
}
{
/* Test associativity of add. */
secp256k1_scalar r1, r2;
secp256k1_scalar_add(&r1, &s1, &s2);
secp256k1_scalar_add(&r1, &r1, &s);
secp256k1_scalar_add(&r2, &s2, &s);
secp256k1_scalar_add(&r2, &s1, &r2);
CHECK(secp256k1_scalar_eq(&r1, &r2));
}
{
/* Test associativity of mul. */
secp256k1_scalar r1, r2;
secp256k1_scalar_mul(&r1, &s1, &s2);
secp256k1_scalar_mul(&r1, &r1, &s);
secp256k1_scalar_mul(&r2, &s2, &s);
secp256k1_scalar_mul(&r2, &s1, &r2);
CHECK(secp256k1_scalar_eq(&r1, &r2));
}
{
/* Test distributitivity of mul over add. */
secp256k1_scalar r1, r2, t;
secp256k1_scalar_add(&r1, &s1, &s2);
secp256k1_scalar_mul(&r1, &r1, &s);
secp256k1_scalar_mul(&r2, &s1, &s);
secp256k1_scalar_mul(&t, &s2, &s);
secp256k1_scalar_add(&r2, &r2, &t);
CHECK(secp256k1_scalar_eq(&r1, &r2));
}
{
/* Test square. */
secp256k1_scalar r1, r2;
secp256k1_scalar_sqr(&r1, &s1);
secp256k1_scalar_mul(&r2, &s1, &s1);
CHECK(secp256k1_scalar_eq(&r1, &r2));
}
{
/* Test multiplicative identity. */
secp256k1_scalar r1, v1;
secp256k1_scalar_set_int(&v1,1);
secp256k1_scalar_mul(&r1, &s1, &v1);
CHECK(secp256k1_scalar_eq(&r1, &s1));
}
{
/* Test additive identity. */
secp256k1_scalar r1, v0;
secp256k1_scalar_set_int(&v0,0);
secp256k1_scalar_add(&r1, &s1, &v0);
CHECK(secp256k1_scalar_eq(&r1, &s1));
}
{
/* Test zero product property. */
secp256k1_scalar r1, v0;
secp256k1_scalar_set_int(&v0,0);
secp256k1_scalar_mul(&r1, &s1, &v0);
CHECK(secp256k1_scalar_eq(&r1, &v0));
}
}
void run_scalar_tests(void) {
int i;
for (i = 0; i < 128 * count; i++) {
scalar_test();
}
{
/* (-1)+1 should be zero. */
secp256k1_scalar s, o;
secp256k1_scalar_set_int(&s, 1);
CHECK(secp256k1_scalar_is_one(&s));
secp256k1_scalar_negate(&o, &s);
secp256k1_scalar_add(&o, &o, &s);
CHECK(secp256k1_scalar_is_zero(&o));
secp256k1_scalar_negate(&o, &o);
CHECK(secp256k1_scalar_is_zero(&o));
}
#ifndef USE_NUM_NONE
{
/* A scalar with value of the curve order should be 0. */
secp256k1_num order;
secp256k1_scalar zero;
unsigned char bin[32];
int overflow = 0;
secp256k1_scalar_order_get_num(&order);
secp256k1_num_get_bin(bin, 32, &order);
secp256k1_scalar_set_b32(&zero, bin, &overflow);
CHECK(overflow == 1);
CHECK(secp256k1_scalar_is_zero(&zero));
}
#endif
{
/* Does check_overflow check catch all ones? */
static const secp256k1_scalar overflowed = SECP256K1_SCALAR_CONST(
0xFFFFFFFFUL, 0xFFFFFFFFUL, 0xFFFFFFFFUL, 0xFFFFFFFFUL,
0xFFFFFFFFUL, 0xFFFFFFFFUL, 0xFFFFFFFFUL, 0xFFFFFFFFUL
);
CHECK(secp256k1_scalar_check_overflow(&overflowed));
}
{
/* Static test vectors.
* These were reduced from ~10^12 random vectors based on comparison-decision
* and edge-case coverage on 32-bit and 64-bit implementations.
* The responses were generated with Sage 5.9.
*/
secp256k1_scalar x;
secp256k1_scalar y;
secp256k1_scalar z;
secp256k1_scalar zz;
secp256k1_scalar one;
secp256k1_scalar r1;
secp256k1_scalar r2;
#if defined(USE_SCALAR_INV_NUM)
secp256k1_scalar zzv;
#endif
int overflow;
unsigned char chal[33][2][32] = {
{{0xff, 0xff, 0x03, 0x07, 0x00, 0x00, 0x00, 0x00,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x03,
0x00, 0x00, 0x00, 0x00, 0x00, 0xf8, 0xff, 0xff,
0xff, 0xff, 0x03, 0x00, 0xc0, 0xff, 0xff, 0xff},
{0xff, 0xff, 0xff, 0xff, 0xff, 0x0f, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf8,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0x03, 0x00, 0x00, 0x00, 0x00, 0xe0, 0xff}},
{{0xef, 0xff, 0x1f, 0x00, 0x00, 0x00, 0x00, 0x00,
0xfe, 0xff, 0xff, 0xff, 0xff, 0xff, 0x3f, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
{0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xe0,
0xff, 0xff, 0xff, 0xff, 0xfc, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0x7f, 0x00, 0x80, 0xff}},
{{0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00,
0x80, 0x00, 0x00, 0x80, 0xff, 0x3f, 0x00, 0x00,
0x00, 0x00, 0x00, 0xf8, 0xff, 0xff, 0xff, 0x00},
{0x00, 0x00, 0xfc, 0xff, 0xff, 0xff, 0xff, 0x80,
0xff, 0xff, 0xff, 0xff, 0xff, 0x0f, 0x00, 0xe0,
0xff, 0xff, 0xff, 0xff, 0xff, 0x7f, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x7f, 0xff, 0xff, 0xff}},
{{0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x80, 0x00, 0x00, 0x80,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00,
0x00, 0x1e, 0xf8, 0xff, 0xff, 0xff, 0xfd, 0xff},
{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x1f,
0x00, 0x00, 0x00, 0xf8, 0xff, 0x03, 0x00, 0xe0,
0xff, 0x0f, 0x00, 0x00, 0x00, 0x00, 0xf0, 0xff,
0xf3, 0xff, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00}},
{{0x80, 0x00, 0x00, 0x80, 0xff, 0xff, 0xff, 0x00,
0x00, 0x1c, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xe0, 0xff, 0xff, 0xff, 0x00,
0x00, 0x00, 0x00, 0x00, 0xe0, 0xff, 0xff, 0xff},
{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x03, 0x00,
0xf8, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0x1f, 0x00, 0x00, 0x80, 0xff, 0xff, 0x3f,
0x00, 0xfe, 0xff, 0xff, 0xff, 0xdf, 0xff, 0xff}},
{{0xff, 0xff, 0xff, 0xff, 0x00, 0x0f, 0xfc, 0x9f,
0xff, 0xff, 0xff, 0x00, 0x80, 0x00, 0x00, 0x80,
0xff, 0x0f, 0xfc, 0xff, 0x7f, 0x00, 0x00, 0x00,
0x00, 0xf8, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00},
{0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80,
0x00, 0x00, 0xf8, 0xff, 0x0f, 0xc0, 0xff, 0xff,
0xff, 0x1f, 0x00, 0x00, 0x00, 0xc0, 0xff, 0xff,
0xff, 0xff, 0xff, 0x07, 0x80, 0xff, 0xff, 0xff}},
{{0xff, 0xff, 0xff, 0xff, 0xff, 0x3f, 0x00, 0x00,
0x80, 0x00, 0x00, 0x80, 0xff, 0xff, 0xff, 0xff,
0xf7, 0xff, 0xff, 0xef, 0xff, 0xff, 0xff, 0x00,
0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0xf0},
{0x00, 0x00, 0x00, 0x00, 0xf8, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0x01, 0x00, 0x00, 0x00,
0x00, 0x00, 0x80, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff}},
{{0x00, 0xf8, 0xff, 0x03, 0xff, 0xff, 0xff, 0x00,
0x00, 0xfe, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00,
0x80, 0x00, 0x00, 0x80, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0x03, 0xc0, 0xff, 0x0f, 0xfc, 0xff},
{0xff, 0xff, 0xff, 0xff, 0xff, 0xe0, 0xff, 0xff,
0xff, 0x01, 0x00, 0x00, 0x00, 0x3f, 0x00, 0xc0,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff}},
{{0x8f, 0x0f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0xf8, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0x7f, 0x00, 0x00, 0x80, 0x00, 0x00, 0x80,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00},
{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0x0f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}},
{{0x00, 0x00, 0x00, 0xc0, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0x03, 0x00, 0x80, 0x00, 0x00, 0x80,
0xff, 0xff, 0xff, 0x00, 0x00, 0x80, 0xff, 0x7f},
{0xff, 0xcf, 0xff, 0xff, 0x01, 0x00, 0x00, 0x00,
0x00, 0xc0, 0xff, 0xcf, 0xff, 0xff, 0xff, 0xff,
0xbf, 0xff, 0x0e, 0x00, 0x00, 0x00, 0x00, 0x00,
0x80, 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00}},
{{0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0xff, 0xff,
0xff, 0xff, 0x00, 0xfc, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0x00, 0x80, 0x00, 0x00, 0x80,
0xff, 0x01, 0xfc, 0xff, 0x01, 0x00, 0xfe, 0xff},
{0xff, 0xff, 0xff, 0x03, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xc0,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x03, 0x00}},
{{0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00,
0xe0, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0x00, 0xf8, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0x7f, 0x00, 0x00, 0x00, 0x80, 0x00, 0x00, 0x80},
{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0xf8, 0xff, 0x01, 0x00, 0xf0, 0xff, 0xff,
0xe0, 0xff, 0x0f, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}},
{{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0xf8, 0xff, 0x00},
{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x00,
0xfc, 0xff, 0xff, 0x3f, 0xf0, 0xff, 0xff, 0x3f,
0x00, 0x00, 0xf8, 0x07, 0x00, 0x00, 0x00, 0xff,
0xff, 0xff, 0xff, 0xff, 0x0f, 0x7e, 0x00, 0x00}},
{{0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00,
0x00, 0x00, 0x00, 0x00, 0x80, 0x00, 0x00, 0x80,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0x1f, 0x00, 0x00, 0xfe, 0x07, 0x00},
{0x00, 0x00, 0x00, 0xf0, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xfb, 0xff, 0x07, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x60}},
{{0xff, 0x01, 0x00, 0xff, 0xff, 0xff, 0x0f, 0x00,
0x80, 0x7f, 0xfe, 0xff, 0xff, 0xff, 0xff, 0x03,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x80, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff},
{0xff, 0xff, 0x1f, 0x00, 0xf0, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0x3f, 0x00, 0x00, 0x00, 0x00}},
{{0x80, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff},
{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xf1, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x03,
0x00, 0x00, 0x00, 0xe0, 0xff, 0xff, 0xff, 0xff}},
{{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00,
0x7e, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0xc0, 0xff, 0xff, 0xcf, 0xff, 0x1f, 0x00, 0x00,
0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80},
{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0xe0, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0x3f, 0x00, 0x7e,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}},
{{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0xfc, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7c, 0x00},
{0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80,
0xff, 0xff, 0x7f, 0x00, 0x80, 0x00, 0x00, 0x00,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00,
0x00, 0x00, 0xe0, 0xff, 0xff, 0xff, 0xff, 0xff}},
{{0xff, 0xff, 0xff, 0xff, 0xff, 0x1f, 0x00, 0x80,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00,
0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00},
{0xf0, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0x3f, 0x00, 0x00, 0x80,
0xff, 0x01, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff,
0xff, 0x7f, 0xf8, 0xff, 0xff, 0x1f, 0x00, 0xfe}},
{{0xff, 0xff, 0xff, 0x3f, 0xf8, 0xff, 0xff, 0xff,
0xff, 0x03, 0xfe, 0x01, 0x00, 0x00, 0x00, 0x00,
0xf0, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x07},
{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00,
0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80,
0xff, 0xff, 0xff, 0xff, 0x01, 0x80, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00}},
{{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfe,
0xba, 0xae, 0xdc, 0xe6, 0xaf, 0x48, 0xa0, 0x3b,
0xbf, 0xd2, 0x5e, 0x8c, 0xd0, 0x36, 0x41, 0x40}},
{{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01},
{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}},
{{0x7f, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff},
{0x7f, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff}},
{{0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0xc0,
0xff, 0x0f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0xf0, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x7f},
{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x01, 0x00,
0xf0, 0xff, 0xff, 0xff, 0xff, 0x07, 0x00, 0x00,
0x00, 0x00, 0x00, 0xfe, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0x01, 0xff, 0xff, 0xff}},
{{0x7f, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff},
{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02}},
{{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfe,
0xba, 0xae, 0xdc, 0xe6, 0xaf, 0x48, 0xa0, 0x3b,
0xbf, 0xd2, 0x5e, 0x8c, 0xd0, 0x36, 0x41, 0x40},
{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01}},
{{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0x7e, 0x00, 0x00, 0xc0, 0xff, 0xff, 0x07, 0x00,
0x80, 0x00, 0x00, 0x00, 0x80, 0x00, 0x00, 0x00,
0xfc, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff},
{0xff, 0x01, 0x00, 0x00, 0x00, 0xe0, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0x1f, 0x00, 0x80,
0xff, 0xff, 0xff, 0xff, 0xff, 0x03, 0x00, 0x00,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff}},
{{0xff, 0xff, 0xf0, 0xff, 0xff, 0xff, 0xff, 0x00,
0xf0, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00,
0x00, 0xe0, 0xff, 0xff, 0xff, 0xff, 0xff, 0x01,
0x80, 0x00, 0x00, 0x80, 0xff, 0xff, 0xff, 0xff},
{0x00, 0x00, 0x00, 0x00, 0x00, 0xe0, 0xff, 0xff,
0xff, 0xff, 0x3f, 0x00, 0xf8, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0x3f, 0x00, 0x00, 0xc0, 0xf1, 0x7f, 0x00}},
{{0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0xc0, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00,
0x80, 0x00, 0x00, 0x80, 0xff, 0xff, 0xff, 0x00},
{0x00, 0xf8, 0xff, 0xff, 0xff, 0xff, 0xff, 0x01,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf8, 0xff,
0xff, 0x7f, 0x00, 0x00, 0x00, 0x00, 0x80, 0x1f,
0x00, 0x00, 0xfc, 0xff, 0xff, 0x01, 0xff, 0xff}},
{{0x00, 0xfe, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00,
0x80, 0x00, 0x00, 0x80, 0xff, 0x03, 0xe0, 0x01,
0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0xfc, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00},
{0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00,
0xfe, 0xff, 0xff, 0xf0, 0x07, 0x00, 0x3c, 0x80,
0xff, 0xff, 0xff, 0xff, 0xfc, 0xff, 0xff, 0xff,
0xff, 0xff, 0x07, 0xe0, 0xff, 0x00, 0x00, 0x00}},
{{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00,
0xfc, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x07, 0xf8,
0x00, 0x00, 0x00, 0x00, 0x80, 0x00, 0x00, 0x80},
{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0x0c, 0x80, 0x00,
0x00, 0x00, 0x00, 0xc0, 0x7f, 0xfe, 0xff, 0x1f,
0x00, 0xfe, 0xff, 0x03, 0x00, 0x00, 0xfe, 0xff}},
{{0xff, 0xff, 0x81, 0xff, 0xff, 0xff, 0xff, 0x00,
0x80, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x83,
0xff, 0xff, 0x00, 0x00, 0x80, 0x00, 0x00, 0x80,
0xff, 0xff, 0x7f, 0x00, 0x00, 0x00, 0x00, 0xf0},
{0xff, 0x01, 0x00, 0x00, 0x00, 0x00, 0xf8, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0x1f, 0x00, 0x00,
0xf8, 0x07, 0x00, 0x80, 0xff, 0xff, 0xff, 0xff,
0xff, 0xc7, 0xff, 0xff, 0xe0, 0xff, 0xff, 0xff}},
{{0x82, 0xc9, 0xfa, 0xb0, 0x68, 0x04, 0xa0, 0x00,
0x82, 0xc9, 0xfa, 0xb0, 0x68, 0x04, 0xa0, 0x00,
0xff, 0xff, 0xff, 0xff, 0xff, 0x6f, 0x03, 0xfb,
0xfa, 0x8a, 0x7d, 0xdf, 0x13, 0x86, 0xe2, 0x03},
{0x82, 0xc9, 0xfa, 0xb0, 0x68, 0x04, 0xa0, 0x00,
0x82, 0xc9, 0xfa, 0xb0, 0x68, 0x04, 0xa0, 0x00,
0xff, 0xff, 0xff, 0xff, 0xff, 0x6f, 0x03, 0xfb,
0xfa, 0x8a, 0x7d, 0xdf, 0x13, 0x86, 0xe2, 0x03}}
};
unsigned char res[33][2][32] = {
{{0x0c, 0x3b, 0x0a, 0xca, 0x8d, 0x1a, 0x2f, 0xb9,
0x8a, 0x7b, 0x53, 0x5a, 0x1f, 0xc5, 0x22, 0xa1,
0x07, 0x2a, 0x48, 0xea, 0x02, 0xeb, 0xb3, 0xd6,
0x20, 0x1e, 0x86, 0xd0, 0x95, 0xf6, 0x92, 0x35},
{0xdc, 0x90, 0x7a, 0x07, 0x2e, 0x1e, 0x44, 0x6d,
0xf8, 0x15, 0x24, 0x5b, 0x5a, 0x96, 0x37, 0x9c,
0x37, 0x7b, 0x0d, 0xac, 0x1b, 0x65, 0x58, 0x49,
0x43, 0xb7, 0x31, 0xbb, 0xa7, 0xf4, 0x97, 0x15}},
{{0xf1, 0xf7, 0x3a, 0x50, 0xe6, 0x10, 0xba, 0x22,
0x43, 0x4d, 0x1f, 0x1f, 0x7c, 0x27, 0xca, 0x9c,
0xb8, 0xb6, 0xa0, 0xfc, 0xd8, 0xc0, 0x05, 0x2f,
0xf7, 0x08, 0xe1, 0x76, 0xdd, 0xd0, 0x80, 0xc8},
{0xe3, 0x80, 0x80, 0xb8, 0xdb, 0xe3, 0xa9, 0x77,
0x00, 0xb0, 0xf5, 0x2e, 0x27, 0xe2, 0x68, 0xc4,
0x88, 0xe8, 0x04, 0xc1, 0x12, 0xbf, 0x78, 0x59,
0xe6, 0xa9, 0x7c, 0xe1, 0x81, 0xdd, 0xb9, 0xd5}},
{{0x96, 0xe2, 0xee, 0x01, 0xa6, 0x80, 0x31, 0xef,
0x5c, 0xd0, 0x19, 0xb4, 0x7d, 0x5f, 0x79, 0xab,
0xa1, 0x97, 0xd3, 0x7e, 0x33, 0xbb, 0x86, 0x55,
0x60, 0x20, 0x10, 0x0d, 0x94, 0x2d, 0x11, 0x7c},
{0xcc, 0xab, 0xe0, 0xe8, 0x98, 0x65, 0x12, 0x96,
0x38, 0x5a, 0x1a, 0xf2, 0x85, 0x23, 0x59, 0x5f,
0xf9, 0xf3, 0xc2, 0x81, 0x70, 0x92, 0x65, 0x12,
0x9c, 0x65, 0x1e, 0x96, 0x00, 0xef, 0xe7, 0x63}},
{{0xac, 0x1e, 0x62, 0xc2, 0x59, 0xfc, 0x4e, 0x5c,
0x83, 0xb0, 0xd0, 0x6f, 0xce, 0x19, 0xf6, 0xbf,
0xa4, 0xb0, 0xe0, 0x53, 0x66, 0x1f, 0xbf, 0xc9,
0x33, 0x47, 0x37, 0xa9, 0x3d, 0x5d, 0xb0, 0x48},
{0x86, 0xb9, 0x2a, 0x7f, 0x8e, 0xa8, 0x60, 0x42,
0x26, 0x6d, 0x6e, 0x1c, 0xa2, 0xec, 0xe0, 0xe5,
0x3e, 0x0a, 0x33, 0xbb, 0x61, 0x4c, 0x9f, 0x3c,
0xd1, 0xdf, 0x49, 0x33, 0xcd, 0x72, 0x78, 0x18}},
{{0xf7, 0xd3, 0xcd, 0x49, 0x5c, 0x13, 0x22, 0xfb,
0x2e, 0xb2, 0x2f, 0x27, 0xf5, 0x8a, 0x5d, 0x74,
0xc1, 0x58, 0xc5, 0xc2, 0x2d, 0x9f, 0x52, 0xc6,
0x63, 0x9f, 0xba, 0x05, 0x76, 0x45, 0x7a, 0x63},
{0x8a, 0xfa, 0x55, 0x4d, 0xdd, 0xa3, 0xb2, 0xc3,
0x44, 0xfd, 0xec, 0x72, 0xde, 0xef, 0xc0, 0x99,
0xf5, 0x9f, 0xe2, 0x52, 0xb4, 0x05, 0x32, 0x58,
0x57, 0xc1, 0x8f, 0xea, 0xc3, 0x24, 0x5b, 0x94}},
{{0x05, 0x83, 0xee, 0xdd, 0x64, 0xf0, 0x14, 0x3b,
0xa0, 0x14, 0x4a, 0x3a, 0x41, 0x82, 0x7c, 0xa7,
0x2c, 0xaa, 0xb1, 0x76, 0xbb, 0x59, 0x64, 0x5f,
0x52, 0xad, 0x25, 0x29, 0x9d, 0x8f, 0x0b, 0xb0},
{0x7e, 0xe3, 0x7c, 0xca, 0xcd, 0x4f, 0xb0, 0x6d,
0x7a, 0xb2, 0x3e, 0xa0, 0x08, 0xb9, 0xa8, 0x2d,
0xc2, 0xf4, 0x99, 0x66, 0xcc, 0xac, 0xd8, 0xb9,
0x72, 0x2a, 0x4a, 0x3e, 0x0f, 0x7b, 0xbf, 0xf4}},
{{0x8c, 0x9c, 0x78, 0x2b, 0x39, 0x61, 0x7e, 0xf7,
0x65, 0x37, 0x66, 0x09, 0x38, 0xb9, 0x6f, 0x70,
0x78, 0x87, 0xff, 0xcf, 0x93, 0xca, 0x85, 0x06,
0x44, 0x84, 0xa7, 0xfe, 0xd3, 0xa4, 0xe3, 0x7e},
{0xa2, 0x56, 0x49, 0x23, 0x54, 0xa5, 0x50, 0xe9,
0x5f, 0xf0, 0x4d, 0xe7, 0xdc, 0x38, 0x32, 0x79,
0x4f, 0x1c, 0xb7, 0xe4, 0xbb, 0xf8, 0xbb, 0x2e,
0x40, 0x41, 0x4b, 0xcc, 0xe3, 0x1e, 0x16, 0x36}},
{{0x0c, 0x1e, 0xd7, 0x09, 0x25, 0x40, 0x97, 0xcb,
0x5c, 0x46, 0xa8, 0xda, 0xef, 0x25, 0xd5, 0xe5,
0x92, 0x4d, 0xcf, 0xa3, 0xc4, 0x5d, 0x35, 0x4a,
0xe4, 0x61, 0x92, 0xf3, 0xbf, 0x0e, 0xcd, 0xbe},
{0xe4, 0xaf, 0x0a, 0xb3, 0x30, 0x8b, 0x9b, 0x48,
0x49, 0x43, 0xc7, 0x64, 0x60, 0x4a, 0x2b, 0x9e,
0x95, 0x5f, 0x56, 0xe8, 0x35, 0xdc, 0xeb, 0xdc,
0xc7, 0xc4, 0xfe, 0x30, 0x40, 0xc7, 0xbf, 0xa4}},
{{0xd4, 0xa0, 0xf5, 0x81, 0x49, 0x6b, 0xb6, 0x8b,
0x0a, 0x69, 0xf9, 0xfe, 0xa8, 0x32, 0xe5, 0xe0,
0xa5, 0xcd, 0x02, 0x53, 0xf9, 0x2c, 0xe3, 0x53,
0x83, 0x36, 0xc6, 0x02, 0xb5, 0xeb, 0x64, 0xb8},
{0x1d, 0x42, 0xb9, 0xf9, 0xe9, 0xe3, 0x93, 0x2c,
0x4c, 0xee, 0x6c, 0x5a, 0x47, 0x9e, 0x62, 0x01,
0x6b, 0x04, 0xfe, 0xa4, 0x30, 0x2b, 0x0d, 0x4f,
0x71, 0x10, 0xd3, 0x55, 0xca, 0xf3, 0x5e, 0x80}},
{{0x77, 0x05, 0xf6, 0x0c, 0x15, 0x9b, 0x45, 0xe7,
0xb9, 0x11, 0xb8, 0xf5, 0xd6, 0xda, 0x73, 0x0c,
0xda, 0x92, 0xea, 0xd0, 0x9d, 0xd0, 0x18, 0x92,
0xce, 0x9a, 0xaa, 0xee, 0x0f, 0xef, 0xde, 0x30},
{0xf1, 0xf1, 0xd6, 0x9b, 0x51, 0xd7, 0x77, 0x62,
0x52, 0x10, 0xb8, 0x7a, 0x84, 0x9d, 0x15, 0x4e,
0x07, 0xdc, 0x1e, 0x75, 0x0d, 0x0c, 0x3b, 0xdb,
0x74, 0x58, 0x62, 0x02, 0x90, 0x54, 0x8b, 0x43}},
{{0xa6, 0xfe, 0x0b, 0x87, 0x80, 0x43, 0x67, 0x25,
0x57, 0x5d, 0xec, 0x40, 0x50, 0x08, 0xd5, 0x5d,
0x43, 0xd7, 0xe0, 0xaa, 0xe0, 0x13, 0xb6, 0xb0,
0xc0, 0xd4, 0xe5, 0x0d, 0x45, 0x83, 0xd6, 0x13},
{0x40, 0x45, 0x0a, 0x92, 0x31, 0xea, 0x8c, 0x60,
0x8c, 0x1f, 0xd8, 0x76, 0x45, 0xb9, 0x29, 0x00,
0x26, 0x32, 0xd8, 0xa6, 0x96, 0x88, 0xe2, 0xc4,
0x8b, 0xdb, 0x7f, 0x17, 0x87, 0xcc, 0xc8, 0xf2}},
{{0xc2, 0x56, 0xe2, 0xb6, 0x1a, 0x81, 0xe7, 0x31,
0x63, 0x2e, 0xbb, 0x0d, 0x2f, 0x81, 0x67, 0xd4,
0x22, 0xe2, 0x38, 0x02, 0x25, 0x97, 0xc7, 0x88,
0x6e, 0xdf, 0xbe, 0x2a, 0xa5, 0x73, 0x63, 0xaa},
{0x50, 0x45, 0xe2, 0xc3, 0xbd, 0x89, 0xfc, 0x57,
0xbd, 0x3c, 0xa3, 0x98, 0x7e, 0x7f, 0x36, 0x38,
0x92, 0x39, 0x1f, 0x0f, 0x81, 0x1a, 0x06, 0x51,
0x1f, 0x8d, 0x6a, 0xff, 0x47, 0x16, 0x06, 0x9c}},
{{0x33, 0x95, 0xa2, 0x6f, 0x27, 0x5f, 0x9c, 0x9c,
0x64, 0x45, 0xcb, 0xd1, 0x3c, 0xee, 0x5e, 0x5f,
0x48, 0xa6, 0xaf, 0xe3, 0x79, 0xcf, 0xb1, 0xe2,
0xbf, 0x55, 0x0e, 0xa2, 0x3b, 0x62, 0xf0, 0xe4},
{0x14, 0xe8, 0x06, 0xe3, 0xbe, 0x7e, 0x67, 0x01,
0xc5, 0x21, 0x67, 0xd8, 0x54, 0xb5, 0x7f, 0xa4,
0xf9, 0x75, 0x70, 0x1c, 0xfd, 0x79, 0xdb, 0x86,
0xad, 0x37, 0x85, 0x83, 0x56, 0x4e, 0xf0, 0xbf}},
{{0xbc, 0xa6, 0xe0, 0x56, 0x4e, 0xef, 0xfa, 0xf5,
0x1d, 0x5d, 0x3f, 0x2a, 0x5b, 0x19, 0xab, 0x51,
0xc5, 0x8b, 0xdd, 0x98, 0x28, 0x35, 0x2f, 0xc3,
0x81, 0x4f, 0x5c, 0xe5, 0x70, 0xb9, 0xeb, 0x62},
{0xc4, 0x6d, 0x26, 0xb0, 0x17, 0x6b, 0xfe, 0x6c,
0x12, 0xf8, 0xe7, 0xc1, 0xf5, 0x2f, 0xfa, 0x91,
0x13, 0x27, 0xbd, 0x73, 0xcc, 0x33, 0x31, 0x1c,
0x39, 0xe3, 0x27, 0x6a, 0x95, 0xcf, 0xc5, 0xfb}},
{{0x30, 0xb2, 0x99, 0x84, 0xf0, 0x18, 0x2a, 0x6e,
0x1e, 0x27, 0xed, 0xa2, 0x29, 0x99, 0x41, 0x56,
0xe8, 0xd4, 0x0d, 0xef, 0x99, 0x9c, 0xf3, 0x58,
0x29, 0x55, 0x1a, 0xc0, 0x68, 0xd6, 0x74, 0xa4},
{0x07, 0x9c, 0xe7, 0xec, 0xf5, 0x36, 0x73, 0x41,
0xa3, 0x1c, 0xe5, 0x93, 0x97, 0x6a, 0xfd, 0xf7,
0x53, 0x18, 0xab, 0xaf, 0xeb, 0x85, 0xbd, 0x92,
0x90, 0xab, 0x3c, 0xbf, 0x30, 0x82, 0xad, 0xf6}},
{{0xc6, 0x87, 0x8a, 0x2a, 0xea, 0xc0, 0xa9, 0xec,
0x6d, 0xd3, 0xdc, 0x32, 0x23, 0xce, 0x62, 0x19,
0xa4, 0x7e, 0xa8, 0xdd, 0x1c, 0x33, 0xae, 0xd3,
0x4f, 0x62, 0x9f, 0x52, 0xe7, 0x65, 0x46, 0xf4},
{0x97, 0x51, 0x27, 0x67, 0x2d, 0xa2, 0x82, 0x87,
0x98, 0xd3, 0xb6, 0x14, 0x7f, 0x51, 0xd3, 0x9a,
0x0b, 0xd0, 0x76, 0x81, 0xb2, 0x4f, 0x58, 0x92,
0xa4, 0x86, 0xa1, 0xa7, 0x09, 0x1d, 0xef, 0x9b}},
{{0xb3, 0x0f, 0x2b, 0x69, 0x0d, 0x06, 0x90, 0x64,
0xbd, 0x43, 0x4c, 0x10, 0xe8, 0x98, 0x1c, 0xa3,
0xe1, 0x68, 0xe9, 0x79, 0x6c, 0x29, 0x51, 0x3f,
0x41, 0xdc, 0xdf, 0x1f, 0xf3, 0x60, 0xbe, 0x33},
{0xa1, 0x5f, 0xf7, 0x1d, 0xb4, 0x3e, 0x9b, 0x3c,
0xe7, 0xbd, 0xb6, 0x06, 0xd5, 0x60, 0x06, 0x6d,
0x50, 0xd2, 0xf4, 0x1a, 0x31, 0x08, 0xf2, 0xea,
0x8e, 0xef, 0x5f, 0x7d, 0xb6, 0xd0, 0xc0, 0x27}},
{{0x62, 0x9a, 0xd9, 0xbb, 0x38, 0x36, 0xce, 0xf7,
0x5d, 0x2f, 0x13, 0xec, 0xc8, 0x2d, 0x02, 0x8a,
0x2e, 0x72, 0xf0, 0xe5, 0x15, 0x9d, 0x72, 0xae,
0xfc, 0xb3, 0x4f, 0x02, 0xea, 0xe1, 0x09, 0xfe},
{0x00, 0x00, 0x00, 0x00, 0xfa, 0x0a, 0x3d, 0xbc,
0xad, 0x16, 0x0c, 0xb6, 0xe7, 0x7c, 0x8b, 0x39,
0x9a, 0x43, 0xbb, 0xe3, 0xc2, 0x55, 0x15, 0x14,
0x75, 0xac, 0x90, 0x9b, 0x7f, 0x9a, 0x92, 0x00}},
{{0x8b, 0xac, 0x70, 0x86, 0x29, 0x8f, 0x00, 0x23,
0x7b, 0x45, 0x30, 0xaa, 0xb8, 0x4c, 0xc7, 0x8d,
0x4e, 0x47, 0x85, 0xc6, 0x19, 0xe3, 0x96, 0xc2,
0x9a, 0xa0, 0x12, 0xed, 0x6f, 0xd7, 0x76, 0x16},
{0x45, 0xaf, 0x7e, 0x33, 0xc7, 0x7f, 0x10, 0x6c,
0x7c, 0x9f, 0x29, 0xc1, 0xa8, 0x7e, 0x15, 0x84,
0xe7, 0x7d, 0xc0, 0x6d, 0xab, 0x71, 0x5d, 0xd0,
0x6b, 0x9f, 0x97, 0xab, 0xcb, 0x51, 0x0c, 0x9f}},
{{0x9e, 0xc3, 0x92, 0xb4, 0x04, 0x9f, 0xc8, 0xbb,
0xdd, 0x9e, 0xc6, 0x05, 0xfd, 0x65, 0xec, 0x94,
0x7f, 0x2c, 0x16, 0xc4, 0x40, 0xac, 0x63, 0x7b,
0x7d, 0xb8, 0x0c, 0xe4, 0x5b, 0xe3, 0xa7, 0x0e},
{0x43, 0xf4, 0x44, 0xe8, 0xcc, 0xc8, 0xd4, 0x54,
0x33, 0x37, 0x50, 0xf2, 0x87, 0x42, 0x2e, 0x00,
0x49, 0x60, 0x62, 0x02, 0xfd, 0x1a, 0x7c, 0xdb,
0x29, 0x6c, 0x6d, 0x54, 0x53, 0x08, 0xd1, 0xc8}},
{{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}},
{{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01}},
{{0x27, 0x59, 0xc7, 0x35, 0x60, 0x71, 0xa6, 0xf1,
0x79, 0xa5, 0xfd, 0x79, 0x16, 0xf3, 0x41, 0xf0,
0x57, 0xb4, 0x02, 0x97, 0x32, 0xe7, 0xde, 0x59,
0xe2, 0x2d, 0x9b, 0x11, 0xea, 0x2c, 0x35, 0x92},
{0x27, 0x59, 0xc7, 0x35, 0x60, 0x71, 0xa6, 0xf1,
0x79, 0xa5, 0xfd, 0x79, 0x16, 0xf3, 0x41, 0xf0,
0x57, 0xb4, 0x02, 0x97, 0x32, 0xe7, 0xde, 0x59,
0xe2, 0x2d, 0x9b, 0x11, 0xea, 0x2c, 0x35, 0x92}},
{{0x28, 0x56, 0xac, 0x0e, 0x4f, 0x98, 0x09, 0xf0,
0x49, 0xfa, 0x7f, 0x84, 0xac, 0x7e, 0x50, 0x5b,
0x17, 0x43, 0x14, 0x89, 0x9c, 0x53, 0xa8, 0x94,
0x30, 0xf2, 0x11, 0x4d, 0x92, 0x14, 0x27, 0xe8},
{0x39, 0x7a, 0x84, 0x56, 0x79, 0x9d, 0xec, 0x26,
0x2c, 0x53, 0xc1, 0x94, 0xc9, 0x8d, 0x9e, 0x9d,
0x32, 0x1f, 0xdd, 0x84, 0x04, 0xe8, 0xe2, 0x0a,
0x6b, 0xbe, 0xbb, 0x42, 0x40, 0x67, 0x30, 0x6c}},
{{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01,
0x45, 0x51, 0x23, 0x19, 0x50, 0xb7, 0x5f, 0xc4,
0x40, 0x2d, 0xa1, 0x73, 0x2f, 0xc9, 0xbe, 0xbd},
{0x27, 0x59, 0xc7, 0x35, 0x60, 0x71, 0xa6, 0xf1,
0x79, 0xa5, 0xfd, 0x79, 0x16, 0xf3, 0x41, 0xf0,
0x57, 0xb4, 0x02, 0x97, 0x32, 0xe7, 0xde, 0x59,
0xe2, 0x2d, 0x9b, 0x11, 0xea, 0x2c, 0x35, 0x92}},
{{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfe,
0xba, 0xae, 0xdc, 0xe6, 0xaf, 0x48, 0xa0, 0x3b,
0xbf, 0xd2, 0x5e, 0x8c, 0xd0, 0x36, 0x41, 0x40},
{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01}},
{{0x1c, 0xc4, 0xf7, 0xda, 0x0f, 0x65, 0xca, 0x39,
0x70, 0x52, 0x92, 0x8e, 0xc3, 0xc8, 0x15, 0xea,
0x7f, 0x10, 0x9e, 0x77, 0x4b, 0x6e, 0x2d, 0xdf,
0xe8, 0x30, 0x9d, 0xda, 0xe8, 0x9a, 0x65, 0xae},
{0x02, 0xb0, 0x16, 0xb1, 0x1d, 0xc8, 0x57, 0x7b,
0xa2, 0x3a, 0xa2, 0xa3, 0x38, 0x5c, 0x8f, 0xeb,
0x66, 0x37, 0x91, 0xa8, 0x5f, 0xef, 0x04, 0xf6,
0x59, 0x75, 0xe1, 0xee, 0x92, 0xf6, 0x0e, 0x30}},
{{0x8d, 0x76, 0x14, 0xa4, 0x14, 0x06, 0x9f, 0x9a,
0xdf, 0x4a, 0x85, 0xa7, 0x6b, 0xbf, 0x29, 0x6f,
0xbc, 0x34, 0x87, 0x5d, 0xeb, 0xbb, 0x2e, 0xa9,
0xc9, 0x1f, 0x58, 0xd6, 0x9a, 0x82, 0xa0, 0x56},
{0xd4, 0xb9, 0xdb, 0x88, 0x1d, 0x04, 0xe9, 0x93,
0x8d, 0x3f, 0x20, 0xd5, 0x86, 0xa8, 0x83, 0x07,
0xdb, 0x09, 0xd8, 0x22, 0x1f, 0x7f, 0xf1, 0x71,
0xc8, 0xe7, 0x5d, 0x47, 0xaf, 0x8b, 0x72, 0xe9}},
{{0x83, 0xb9, 0x39, 0xb2, 0xa4, 0xdf, 0x46, 0x87,
0xc2, 0xb8, 0xf1, 0xe6, 0x4c, 0xd1, 0xe2, 0xa9,
0xe4, 0x70, 0x30, 0x34, 0xbc, 0x52, 0x7c, 0x55,
0xa6, 0xec, 0x80, 0xa4, 0xe5, 0xd2, 0xdc, 0x73},
{0x08, 0xf1, 0x03, 0xcf, 0x16, 0x73, 0xe8, 0x7d,
0xb6, 0x7e, 0x9b, 0xc0, 0xb4, 0xc2, 0xa5, 0x86,
0x02, 0x77, 0xd5, 0x27, 0x86, 0xa5, 0x15, 0xfb,
0xae, 0x9b, 0x8c, 0xa9, 0xf9, 0xf8, 0xa8, 0x4a}},
{{0x8b, 0x00, 0x49, 0xdb, 0xfa, 0xf0, 0x1b, 0xa2,
0xed, 0x8a, 0x9a, 0x7a, 0x36, 0x78, 0x4a, 0xc7,
0xf7, 0xad, 0x39, 0xd0, 0x6c, 0x65, 0x7a, 0x41,
0xce, 0xd6, 0xd6, 0x4c, 0x20, 0x21, 0x6b, 0xc7},
{0xc6, 0xca, 0x78, 0x1d, 0x32, 0x6c, 0x6c, 0x06,
0x91, 0xf2, 0x1a, 0xe8, 0x43, 0x16, 0xea, 0x04,
0x3c, 0x1f, 0x07, 0x85, 0xf7, 0x09, 0x22, 0x08,
0xba, 0x13, 0xfd, 0x78, 0x1e, 0x3f, 0x6f, 0x62}},
{{0x25, 0x9b, 0x7c, 0xb0, 0xac, 0x72, 0x6f, 0xb2,
0xe3, 0x53, 0x84, 0x7a, 0x1a, 0x9a, 0x98, 0x9b,
0x44, 0xd3, 0x59, 0xd0, 0x8e, 0x57, 0x41, 0x40,
0x78, 0xa7, 0x30, 0x2f, 0x4c, 0x9c, 0xb9, 0x68},
{0xb7, 0x75, 0x03, 0x63, 0x61, 0xc2, 0x48, 0x6e,
0x12, 0x3d, 0xbf, 0x4b, 0x27, 0xdf, 0xb1, 0x7a,
0xff, 0x4e, 0x31, 0x07, 0x83, 0xf4, 0x62, 0x5b,
0x19, 0xa5, 0xac, 0xa0, 0x32, 0x58, 0x0d, 0xa7}},
{{0x43, 0x4f, 0x10, 0xa4, 0xca, 0xdb, 0x38, 0x67,
0xfa, 0xae, 0x96, 0xb5, 0x6d, 0x97, 0xff, 0x1f,
0xb6, 0x83, 0x43, 0xd3, 0xa0, 0x2d, 0x70, 0x7a,
0x64, 0x05, 0x4c, 0xa7, 0xc1, 0xa5, 0x21, 0x51},
{0xe4, 0xf1, 0x23, 0x84, 0xe1, 0xb5, 0x9d, 0xf2,
0xb8, 0x73, 0x8b, 0x45, 0x2b, 0x35, 0x46, 0x38,
0x10, 0x2b, 0x50, 0xf8, 0x8b, 0x35, 0xcd, 0x34,
0xc8, 0x0e, 0xf6, 0xdb, 0x09, 0x35, 0xf0, 0xda}},
{{0xdb, 0x21, 0x5c, 0x8d, 0x83, 0x1d, 0xb3, 0x34,
0xc7, 0x0e, 0x43, 0xa1, 0x58, 0x79, 0x67, 0x13,
0x1e, 0x86, 0x5d, 0x89, 0x63, 0xe6, 0x0a, 0x46,
0x5c, 0x02, 0x97, 0x1b, 0x62, 0x43, 0x86, 0xf5},
{0xdb, 0x21, 0x5c, 0x8d, 0x83, 0x1d, 0xb3, 0x34,
0xc7, 0x0e, 0x43, 0xa1, 0x58, 0x79, 0x67, 0x13,
0x1e, 0x86, 0x5d, 0x89, 0x63, 0xe6, 0x0a, 0x46,
0x5c, 0x02, 0x97, 0x1b, 0x62, 0x43, 0x86, 0xf5}}
};
secp256k1_scalar_set_int(&one, 1);
for (i = 0; i < 33; i++) {
secp256k1_scalar_set_b32(&x, chal[i][0], &overflow);
CHECK(!overflow);
secp256k1_scalar_set_b32(&y, chal[i][1], &overflow);
CHECK(!overflow);
secp256k1_scalar_set_b32(&r1, res[i][0], &overflow);
CHECK(!overflow);
secp256k1_scalar_set_b32(&r2, res[i][1], &overflow);
CHECK(!overflow);
secp256k1_scalar_mul(&z, &x, &y);
CHECK(!secp256k1_scalar_check_overflow(&z));
CHECK(secp256k1_scalar_eq(&r1, &z));
if (!secp256k1_scalar_is_zero(&y)) {
secp256k1_scalar_inverse(&zz, &y);
CHECK(!secp256k1_scalar_check_overflow(&zz));
#if defined(USE_SCALAR_INV_NUM)
secp256k1_scalar_inverse_var(&zzv, &y);
CHECK(secp256k1_scalar_eq(&zzv, &zz));
#endif
secp256k1_scalar_mul(&z, &z, &zz);
CHECK(!secp256k1_scalar_check_overflow(&z));
CHECK(secp256k1_scalar_eq(&x, &z));
secp256k1_scalar_mul(&zz, &zz, &y);
CHECK(!secp256k1_scalar_check_overflow(&zz));
CHECK(secp256k1_scalar_eq(&one, &zz));
}
secp256k1_scalar_mul(&z, &x, &x);
CHECK(!secp256k1_scalar_check_overflow(&z));
secp256k1_scalar_sqr(&zz, &x);
CHECK(!secp256k1_scalar_check_overflow(&zz));
CHECK(secp256k1_scalar_eq(&zz, &z));
CHECK(secp256k1_scalar_eq(&r2, &zz));
}
}
}
/***** FIELD TESTS *****/
void random_fe(secp256k1_fe *x) {
unsigned char bin[32];
do {
secp256k1_rand256(bin);
if (secp256k1_fe_set_b32(x, bin)) {
return;
}
} while(1);
}
void random_fe_test(secp256k1_fe *x) {
unsigned char bin[32];
do {
secp256k1_rand256_test(bin);
if (secp256k1_fe_set_b32(x, bin)) {
return;
}
} while(1);
}
void random_fe_non_zero(secp256k1_fe *nz) {
int tries = 10;
while (--tries >= 0) {
random_fe(nz);
secp256k1_fe_normalize(nz);
if (!secp256k1_fe_is_zero(nz)) {
break;
}
}
/* Infinitesimal probability of spurious failure here */
CHECK(tries >= 0);
}
void random_fe_non_square(secp256k1_fe *ns) {
secp256k1_fe r;
random_fe_non_zero(ns);
if (secp256k1_fe_sqrt(&r, ns)) {
secp256k1_fe_negate(ns, ns, 1);
}
}
int check_fe_equal(const secp256k1_fe *a, const secp256k1_fe *b) {
secp256k1_fe an = *a;
secp256k1_fe bn = *b;
secp256k1_fe_normalize_weak(&an);
secp256k1_fe_normalize_var(&bn);
return secp256k1_fe_equal_var(&an, &bn);
}
int check_fe_inverse(const secp256k1_fe *a, const secp256k1_fe *ai) {
secp256k1_fe x;
secp256k1_fe one = SECP256K1_FE_CONST(0, 0, 0, 0, 0, 0, 0, 1);
secp256k1_fe_mul(&x, a, ai);
return check_fe_equal(&x, &one);
}
void run_field_convert(void) {
static const unsigned char b32[32] = {
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18,
0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29,
0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x40
};
static const secp256k1_fe_storage fes = SECP256K1_FE_STORAGE_CONST(
0x00010203UL, 0x04050607UL, 0x11121314UL, 0x15161718UL,
0x22232425UL, 0x26272829UL, 0x33343536UL, 0x37383940UL
);
static const secp256k1_fe fe = SECP256K1_FE_CONST(
0x00010203UL, 0x04050607UL, 0x11121314UL, 0x15161718UL,
0x22232425UL, 0x26272829UL, 0x33343536UL, 0x37383940UL
);
secp256k1_fe fe2;
unsigned char b322[32];
secp256k1_fe_storage fes2;
/* Check conversions to fe. */
CHECK(secp256k1_fe_set_b32(&fe2, b32));
CHECK(secp256k1_fe_equal_var(&fe, &fe2));
secp256k1_fe_from_storage(&fe2, &fes);
CHECK(secp256k1_fe_equal_var(&fe, &fe2));
/* Check conversion from fe. */
secp256k1_fe_get_b32(b322, &fe);
CHECK(memcmp(b322, b32, 32) == 0);
secp256k1_fe_to_storage(&fes2, &fe);
CHECK(memcmp(&fes2, &fes, sizeof(fes)) == 0);
}
int fe_memcmp(const secp256k1_fe *a, const secp256k1_fe *b) {
secp256k1_fe t = *b;
#ifdef VERIFY
t.magnitude = a->magnitude;
t.normalized = a->normalized;
#endif
return memcmp(a, &t, sizeof(secp256k1_fe));
}
void run_field_misc(void) {
secp256k1_fe x;
secp256k1_fe y;
secp256k1_fe z;
secp256k1_fe q;
secp256k1_fe fe5 = SECP256K1_FE_CONST(0, 0, 0, 0, 0, 0, 0, 5);
int i, j;
for (i = 0; i < 5*count; i++) {
secp256k1_fe_storage xs, ys, zs;
random_fe(&x);
random_fe_non_zero(&y);
/* Test the fe equality and comparison operations. */
CHECK(secp256k1_fe_cmp_var(&x, &x) == 0);
CHECK(secp256k1_fe_equal_var(&x, &x));
z = x;
secp256k1_fe_add(&z,&y);
/* Test fe conditional move; z is not normalized here. */
q = x;
secp256k1_fe_cmov(&x, &z, 0);
VERIFY_CHECK(!x.normalized && x.magnitude == z.magnitude);
secp256k1_fe_cmov(&x, &x, 1);
CHECK(fe_memcmp(&x, &z) != 0);
CHECK(fe_memcmp(&x, &q) == 0);
secp256k1_fe_cmov(&q, &z, 1);
VERIFY_CHECK(!q.normalized && q.magnitude == z.magnitude);
CHECK(fe_memcmp(&q, &z) == 0);
secp256k1_fe_normalize_var(&x);
secp256k1_fe_normalize_var(&z);
CHECK(!secp256k1_fe_equal_var(&x, &z));
secp256k1_fe_normalize_var(&q);
secp256k1_fe_cmov(&q, &z, (i&1));
VERIFY_CHECK(q.normalized && q.magnitude == 1);
for (j = 0; j < 6; j++) {
secp256k1_fe_negate(&z, &z, j+1);
secp256k1_fe_normalize_var(&q);
secp256k1_fe_cmov(&q, &z, (j&1));
VERIFY_CHECK(!q.normalized && q.magnitude == (j+2));
}
secp256k1_fe_normalize_var(&z);
/* Test storage conversion and conditional moves. */
secp256k1_fe_to_storage(&xs, &x);
secp256k1_fe_to_storage(&ys, &y);
secp256k1_fe_to_storage(&zs, &z);
secp256k1_fe_storage_cmov(&zs, &xs, 0);
secp256k1_fe_storage_cmov(&zs, &zs, 1);
CHECK(memcmp(&xs, &zs, sizeof(xs)) != 0);
secp256k1_fe_storage_cmov(&ys, &xs, 1);
CHECK(memcmp(&xs, &ys, sizeof(xs)) == 0);
secp256k1_fe_from_storage(&x, &xs);
secp256k1_fe_from_storage(&y, &ys);
secp256k1_fe_from_storage(&z, &zs);
/* Test that mul_int, mul, and add agree. */
secp256k1_fe_add(&y, &x);
secp256k1_fe_add(&y, &x);
z = x;
secp256k1_fe_mul_int(&z, 3);
CHECK(check_fe_equal(&y, &z));
secp256k1_fe_add(&y, &x);
secp256k1_fe_add(&z, &x);
CHECK(check_fe_equal(&z, &y));
z = x;
secp256k1_fe_mul_int(&z, 5);
secp256k1_fe_mul(&q, &x, &fe5);
CHECK(check_fe_equal(&z, &q));
secp256k1_fe_negate(&x, &x, 1);
secp256k1_fe_add(&z, &x);
secp256k1_fe_add(&q, &x);
CHECK(check_fe_equal(&y, &z));
CHECK(check_fe_equal(&q, &y));
}
}
void run_field_inv(void) {
secp256k1_fe x, xi, xii;
int i;
for (i = 0; i < 10*count; i++) {
random_fe_non_zero(&x);
secp256k1_fe_inv(&xi, &x);
CHECK(check_fe_inverse(&x, &xi));
secp256k1_fe_inv(&xii, &xi);
CHECK(check_fe_equal(&x, &xii));
}
}
void run_field_inv_var(void) {
secp256k1_fe x, xi, xii;
int i;
for (i = 0; i < 10*count; i++) {
random_fe_non_zero(&x);
secp256k1_fe_inv_var(&xi, &x);
CHECK(check_fe_inverse(&x, &xi));
secp256k1_fe_inv_var(&xii, &xi);
CHECK(check_fe_equal(&x, &xii));
}
}
void run_field_inv_all_var(void) {
secp256k1_fe x[16], xi[16], xii[16];
int i;
/* Check it's safe to call for 0 elements */
secp256k1_fe_inv_all_var(xi, x, 0);
for (i = 0; i < count; i++) {
size_t j;
size_t len = secp256k1_rand_int(15) + 1;
for (j = 0; j < len; j++) {
random_fe_non_zero(&x[j]);
}
secp256k1_fe_inv_all_var(xi, x, len);
for (j = 0; j < len; j++) {
CHECK(check_fe_inverse(&x[j], &xi[j]));
}
secp256k1_fe_inv_all_var(xii, xi, len);
for (j = 0; j < len; j++) {
CHECK(check_fe_equal(&x[j], &xii[j]));
}
}
}
void run_sqr(void) {
secp256k1_fe x, s;
{
int i;
secp256k1_fe_set_int(&x, 1);
secp256k1_fe_negate(&x, &x, 1);
for (i = 1; i <= 512; ++i) {
secp256k1_fe_mul_int(&x, 2);
secp256k1_fe_normalize(&x);
secp256k1_fe_sqr(&s, &x);
}
}
}
void test_sqrt(const secp256k1_fe *a, const secp256k1_fe *k) {
secp256k1_fe r1, r2;
int v = secp256k1_fe_sqrt(&r1, a);
CHECK((v == 0) == (k == NULL));
if (k != NULL) {
/* Check that the returned root is +/- the given known answer */
secp256k1_fe_negate(&r2, &r1, 1);
secp256k1_fe_add(&r1, k); secp256k1_fe_add(&r2, k);
secp256k1_fe_normalize(&r1); secp256k1_fe_normalize(&r2);
CHECK(secp256k1_fe_is_zero(&r1) || secp256k1_fe_is_zero(&r2));
}
}
void run_sqrt(void) {
secp256k1_fe ns, x, s, t;
int i;
/* Check sqrt(0) is 0 */
secp256k1_fe_set_int(&x, 0);
secp256k1_fe_sqr(&s, &x);
test_sqrt(&s, &x);
/* Check sqrt of small squares (and their negatives) */
for (i = 1; i <= 100; i++) {
secp256k1_fe_set_int(&x, i);
secp256k1_fe_sqr(&s, &x);
test_sqrt(&s, &x);
secp256k1_fe_negate(&t, &s, 1);
test_sqrt(&t, NULL);
}
/* Consistency checks for large random values */
for (i = 0; i < 10; i++) {
int j;
random_fe_non_square(&ns);
for (j = 0; j < count; j++) {
random_fe(&x);
secp256k1_fe_sqr(&s, &x);
test_sqrt(&s, &x);
secp256k1_fe_negate(&t, &s, 1);
test_sqrt(&t, NULL);
secp256k1_fe_mul(&t, &s, &ns);
test_sqrt(&t, NULL);
}
}
}
/***** GROUP TESTS *****/
void ge_equals_ge(const secp256k1_ge *a, const secp256k1_ge *b) {
CHECK(a->infinity == b->infinity);
if (a->infinity) {
return;
}
CHECK(secp256k1_fe_equal_var(&a->x, &b->x));
CHECK(secp256k1_fe_equal_var(&a->y, &b->y));
}
/* This compares jacobian points including their Z, not just their geometric meaning. */
int gej_xyz_equals_gej(const secp256k1_gej *a, const secp256k1_gej *b) {
secp256k1_gej a2;
secp256k1_gej b2;
int ret = 1;
ret &= a->infinity == b->infinity;
if (ret && !a->infinity) {
a2 = *a;
b2 = *b;
secp256k1_fe_normalize(&a2.x);
secp256k1_fe_normalize(&a2.y);
secp256k1_fe_normalize(&a2.z);
secp256k1_fe_normalize(&b2.x);
secp256k1_fe_normalize(&b2.y);
secp256k1_fe_normalize(&b2.z);
ret &= secp256k1_fe_cmp_var(&a2.x, &b2.x) == 0;
ret &= secp256k1_fe_cmp_var(&a2.y, &b2.y) == 0;
ret &= secp256k1_fe_cmp_var(&a2.z, &b2.z) == 0;
}
return ret;
}
void ge_equals_gej(const secp256k1_ge *a, const secp256k1_gej *b) {
secp256k1_fe z2s;
secp256k1_fe u1, u2, s1, s2;
CHECK(a->infinity == b->infinity);
if (a->infinity) {
return;
}
/* Check a.x * b.z^2 == b.x && a.y * b.z^3 == b.y, to avoid inverses. */
secp256k1_fe_sqr(&z2s, &b->z);
secp256k1_fe_mul(&u1, &a->x, &z2s);
u2 = b->x; secp256k1_fe_normalize_weak(&u2);
secp256k1_fe_mul(&s1, &a->y, &z2s); secp256k1_fe_mul(&s1, &s1, &b->z);
s2 = b->y; secp256k1_fe_normalize_weak(&s2);
CHECK(secp256k1_fe_equal_var(&u1, &u2));
CHECK(secp256k1_fe_equal_var(&s1, &s2));
}
void test_ge(void) {
int i, i1;
#ifdef USE_ENDOMORPHISM
int runs = 6;
#else
int runs = 4;
#endif
/* Points: (infinity, p1, p1, -p1, -p1, p2, p2, -p2, -p2, p3, p3, -p3, -p3, p4, p4, -p4, -p4).
* The second in each pair of identical points uses a random Z coordinate in the Jacobian form.
* All magnitudes are randomized.
* All 17*17 combinations of points are added to each other, using all applicable methods.
*
* When the endomorphism code is compiled in, p5 = lambda*p1 and p6 = lambda^2*p1 are added as well.
*/
secp256k1_ge *ge = (secp256k1_ge *)checked_malloc(&ctx->error_callback, sizeof(secp256k1_ge) * (1 + 4 * runs));
secp256k1_gej *gej = (secp256k1_gej *)checked_malloc(&ctx->error_callback, sizeof(secp256k1_gej) * (1 + 4 * runs));
secp256k1_fe *zinv = (secp256k1_fe *)checked_malloc(&ctx->error_callback, sizeof(secp256k1_fe) * (1 + 4 * runs));
secp256k1_fe zf;
secp256k1_fe zfi2, zfi3;
secp256k1_gej_set_infinity(&gej[0]);
secp256k1_ge_clear(&ge[0]);
secp256k1_ge_set_gej_var(&ge[0], &gej[0]);
for (i = 0; i < runs; i++) {
int j;
secp256k1_ge g;
random_group_element_test(&g);
#ifdef USE_ENDOMORPHISM
if (i >= runs - 2) {
secp256k1_ge_mul_lambda(&g, &ge[1]);
}
if (i >= runs - 1) {
secp256k1_ge_mul_lambda(&g, &g);
}
#endif
ge[1 + 4 * i] = g;
ge[2 + 4 * i] = g;
secp256k1_ge_neg(&ge[3 + 4 * i], &g);
secp256k1_ge_neg(&ge[4 + 4 * i], &g);
secp256k1_gej_set_ge(&gej[1 + 4 * i], &ge[1 + 4 * i]);
random_group_element_jacobian_test(&gej[2 + 4 * i], &ge[2 + 4 * i]);
secp256k1_gej_set_ge(&gej[3 + 4 * i], &ge[3 + 4 * i]);
random_group_element_jacobian_test(&gej[4 + 4 * i], &ge[4 + 4 * i]);
for (j = 0; j < 4; j++) {
random_field_element_magnitude(&ge[1 + j + 4 * i].x);
random_field_element_magnitude(&ge[1 + j + 4 * i].y);
random_field_element_magnitude(&gej[1 + j + 4 * i].x);
random_field_element_magnitude(&gej[1 + j + 4 * i].y);
random_field_element_magnitude(&gej[1 + j + 4 * i].z);
}
}
/* Compute z inverses. */
{
secp256k1_fe *zs = checked_malloc(&ctx->error_callback, sizeof(secp256k1_fe) * (1 + 4 * runs));
for (i = 0; i < 4 * runs + 1; i++) {
if (i == 0) {
/* The point at infinity does not have a meaningful z inverse. Any should do. */
do {
random_field_element_test(&zs[i]);
} while(secp256k1_fe_is_zero(&zs[i]));
} else {
zs[i] = gej[i].z;
}
}
secp256k1_fe_inv_all_var(zinv, zs, 4 * runs + 1);
free(zs);
}
/* Generate random zf, and zfi2 = 1/zf^2, zfi3 = 1/zf^3 */
do {
random_field_element_test(&zf);
} while(secp256k1_fe_is_zero(&zf));
random_field_element_magnitude(&zf);
secp256k1_fe_inv_var(&zfi3, &zf);
secp256k1_fe_sqr(&zfi2, &zfi3);
secp256k1_fe_mul(&zfi3, &zfi3, &zfi2);
for (i1 = 0; i1 < 1 + 4 * runs; i1++) {
int i2;
for (i2 = 0; i2 < 1 + 4 * runs; i2++) {
/* Compute reference result using gej + gej (var). */
secp256k1_gej refj, resj;
secp256k1_ge ref;
secp256k1_fe zr;
secp256k1_gej_add_var(&refj, &gej[i1], &gej[i2], secp256k1_gej_is_infinity(&gej[i1]) ? NULL : &zr);
/* Check Z ratio. */
if (!secp256k1_gej_is_infinity(&gej[i1]) && !secp256k1_gej_is_infinity(&refj)) {
secp256k1_fe zrz; secp256k1_fe_mul(&zrz, &zr, &gej[i1].z);
CHECK(secp256k1_fe_equal_var(&zrz, &refj.z));
}
secp256k1_ge_set_gej_var(&ref, &refj);
/* Test gej + ge with Z ratio result (var). */
secp256k1_gej_add_ge_var(&resj, &gej[i1], &ge[i2], secp256k1_gej_is_infinity(&gej[i1]) ? NULL : &zr);
ge_equals_gej(&ref, &resj);
if (!secp256k1_gej_is_infinity(&gej[i1]) && !secp256k1_gej_is_infinity(&resj)) {
secp256k1_fe zrz; secp256k1_fe_mul(&zrz, &zr, &gej[i1].z);
CHECK(secp256k1_fe_equal_var(&zrz, &resj.z));
}
/* Test gej + ge (var, with additional Z factor). */
{
secp256k1_ge ge2_zfi = ge[i2]; /* the second term with x and y rescaled for z = 1/zf */
secp256k1_fe_mul(&ge2_zfi.x, &ge2_zfi.x, &zfi2);
secp256k1_fe_mul(&ge2_zfi.y, &ge2_zfi.y, &zfi3);
random_field_element_magnitude(&ge2_zfi.x);
random_field_element_magnitude(&ge2_zfi.y);
secp256k1_gej_add_zinv_var(&resj, &gej[i1], &ge2_zfi, &zf);
ge_equals_gej(&ref, &resj);
}
/* Test gej + ge (const). */
if (i2 != 0) {
/* secp256k1_gej_add_ge does not support its second argument being infinity. */
secp256k1_gej_add_ge(&resj, &gej[i1], &ge[i2]);
ge_equals_gej(&ref, &resj);
}
/* Test doubling (var). */
if ((i1 == 0 && i2 == 0) || ((i1 + 3)/4 == (i2 + 3)/4 && ((i1 + 3)%4)/2 == ((i2 + 3)%4)/2)) {
secp256k1_fe zr2;
/* Normal doubling with Z ratio result. */
secp256k1_gej_double_var(&resj, &gej[i1], &zr2);
ge_equals_gej(&ref, &resj);
/* Check Z ratio. */
secp256k1_fe_mul(&zr2, &zr2, &gej[i1].z);
CHECK(secp256k1_fe_equal_var(&zr2, &resj.z));
/* Normal doubling. */
secp256k1_gej_double_var(&resj, &gej[i2], NULL);
ge_equals_gej(&ref, &resj);
}
/* Test adding opposites. */
if ((i1 == 0 && i2 == 0) || ((i1 + 3)/4 == (i2 + 3)/4 && ((i1 + 3)%4)/2 != ((i2 + 3)%4)/2)) {
CHECK(secp256k1_ge_is_infinity(&ref));
}
/* Test adding infinity. */
if (i1 == 0) {
CHECK(secp256k1_ge_is_infinity(&ge[i1]));
CHECK(secp256k1_gej_is_infinity(&gej[i1]));
ge_equals_gej(&ref, &gej[i2]);
}
if (i2 == 0) {
CHECK(secp256k1_ge_is_infinity(&ge[i2]));
CHECK(secp256k1_gej_is_infinity(&gej[i2]));
ge_equals_gej(&ref, &gej[i1]);
}
}
}
/* Test adding all points together in random order equals infinity. */
{
secp256k1_gej sum = SECP256K1_GEJ_CONST_INFINITY;
secp256k1_gej *gej_shuffled = (secp256k1_gej *)checked_malloc(&ctx->error_callback, (4 * runs + 1) * sizeof(secp256k1_gej));
for (i = 0; i < 4 * runs + 1; i++) {
gej_shuffled[i] = gej[i];
}
for (i = 0; i < 4 * runs + 1; i++) {
int swap = i + secp256k1_rand_int(4 * runs + 1 - i);
if (swap != i) {
secp256k1_gej t = gej_shuffled[i];
gej_shuffled[i] = gej_shuffled[swap];
gej_shuffled[swap] = t;
}
}
for (i = 0; i < 4 * runs + 1; i++) {
secp256k1_gej_add_var(&sum, &sum, &gej_shuffled[i], NULL);
}
CHECK(secp256k1_gej_is_infinity(&sum));
free(gej_shuffled);
}
/* Test batch gej -> ge conversion with and without known z ratios. */
{
secp256k1_fe *zr = (secp256k1_fe *)checked_malloc(&ctx->error_callback, (4 * runs + 1) * sizeof(secp256k1_fe));
secp256k1_ge *ge_set_table = (secp256k1_ge *)checked_malloc(&ctx->error_callback, (4 * runs + 1) * sizeof(secp256k1_ge));
secp256k1_ge *ge_set_all = (secp256k1_ge *)checked_malloc(&ctx->error_callback, (4 * runs + 1) * sizeof(secp256k1_ge));
for (i = 0; i < 4 * runs + 1; i++) {
/* Compute gej[i + 1].z / gez[i].z (with gej[n].z taken to be 1). */
if (i < 4 * runs) {
secp256k1_fe_mul(&zr[i + 1], &zinv[i], &gej[i + 1].z);
}
}
secp256k1_ge_set_table_gej_var(ge_set_table, gej, zr, 4 * runs + 1);
secp256k1_ge_set_all_gej_var(ge_set_all, gej, 4 * runs + 1, &ctx->error_callback);
for (i = 0; i < 4 * runs + 1; i++) {
secp256k1_fe s;
random_fe_non_zero(&s);
secp256k1_gej_rescale(&gej[i], &s);
ge_equals_gej(&ge_set_table[i], &gej[i]);
ge_equals_gej(&ge_set_all[i], &gej[i]);
}
free(ge_set_table);
free(ge_set_all);
free(zr);
}
free(ge);
free(gej);
free(zinv);
}
void test_add_neg_y_diff_x(void) {
/* The point of this test is to check that we can add two points
* whose y-coordinates are negatives of each other but whose x
* coordinates differ. If the x-coordinates were the same, these
* points would be negatives of each other and their sum is
* infinity. This is cool because it "covers up" any degeneracy
* in the addition algorithm that would cause the xy coordinates
* of the sum to be wrong (since infinity has no xy coordinates).
* HOWEVER, if the x-coordinates are different, infinity is the
* wrong answer, and such degeneracies are exposed. This is the
* root of https://github.com/bitcoin-core/secp256k1/issues/257
* which this test is a regression test for.
*
* These points were generated in sage as
* # secp256k1 params
* F = FiniteField (0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F)
* C = EllipticCurve ([F (0), F (7)])
* G = C.lift_x(0x79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798)
* N = FiniteField(G.order())
*
* # endomorphism values (lambda is 1^{1/3} in N, beta is 1^{1/3} in F)
* x = polygen(N)
* lam = (1 - x^3).roots()[1][0]
*
* # random "bad pair"
* P = C.random_element()
* Q = -int(lam) * P
* print " P: %x %x" % P.xy()
* print " Q: %x %x" % Q.xy()
* print "P + Q: %x %x" % (P + Q).xy()
*/
secp256k1_gej aj = SECP256K1_GEJ_CONST(
0x8d24cd95, 0x0a355af1, 0x3c543505, 0x44238d30,
0x0643d79f, 0x05a59614, 0x2f8ec030, 0xd58977cb,
0x001e337a, 0x38093dcd, 0x6c0f386d, 0x0b1293a8,
0x4d72c879, 0xd7681924, 0x44e6d2f3, 0x9190117d
);
secp256k1_gej bj = SECP256K1_GEJ_CONST(
0xc7b74206, 0x1f788cd9, 0xabd0937d, 0x164a0d86,
0x95f6ff75, 0xf19a4ce9, 0xd013bd7b, 0xbf92d2a7,
0xffe1cc85, 0xc7f6c232, 0x93f0c792, 0xf4ed6c57,
0xb28d3786, 0x2897e6db, 0xbb192d0b, 0x6e6feab2
);
secp256k1_gej sumj = SECP256K1_GEJ_CONST(
0x671a63c0, 0x3efdad4c, 0x389a7798, 0x24356027,
0xb3d69010, 0x278625c3, 0x5c86d390, 0x184a8f7a,
0x5f6409c2, 0x2ce01f2b, 0x511fd375, 0x25071d08,
0xda651801, 0x70e95caf, 0x8f0d893c, 0xbed8fbbe
);
secp256k1_ge b;
secp256k1_gej resj;
secp256k1_ge res;
secp256k1_ge_set_gej(&b, &bj);
secp256k1_gej_add_var(&resj, &aj, &bj, NULL);
secp256k1_ge_set_gej(&res, &resj);
ge_equals_gej(&res, &sumj);
secp256k1_gej_add_ge(&resj, &aj, &b);
secp256k1_ge_set_gej(&res, &resj);
ge_equals_gej(&res, &sumj);
secp256k1_gej_add_ge_var(&resj, &aj, &b, NULL);
secp256k1_ge_set_gej(&res, &resj);
ge_equals_gej(&res, &sumj);
}
void run_ge(void) {
int i;
for (i = 0; i < count * 32; i++) {
test_ge();
}
test_add_neg_y_diff_x();
}
void test_ec_combine(void) {
secp256k1_scalar sum = SECP256K1_SCALAR_CONST(0, 0, 0, 0, 0, 0, 0, 0);
secp256k1_pubkey data[6];
const secp256k1_pubkey* d[6];
secp256k1_pubkey sd;
secp256k1_pubkey sd2;
secp256k1_gej Qj;
secp256k1_ge Q;
int i;
for (i = 1; i <= 6; i++) {
secp256k1_scalar s;
random_scalar_order_test(&s);
secp256k1_scalar_add(&sum, &sum, &s);
secp256k1_ecmult_gen(&ctx->ecmult_gen_ctx, &Qj, &s);
secp256k1_ge_set_gej(&Q, &Qj);
secp256k1_pubkey_save(&data[i - 1], &Q);
d[i - 1] = &data[i - 1];
secp256k1_ecmult_gen(&ctx->ecmult_gen_ctx, &Qj, &sum);
secp256k1_ge_set_gej(&Q, &Qj);
secp256k1_pubkey_save(&sd, &Q);
CHECK(secp256k1_ec_pubkey_combine(ctx, &sd2, d, i) == 1);
CHECK(memcmp(&sd, &sd2, sizeof(sd)) == 0);
}
}
void run_ec_combine(void) {
int i;
for (i = 0; i < count * 8; i++) {
test_ec_combine();
}
}
void test_group_decompress(const secp256k1_fe* x) {
/* The input itself, normalized. */
secp256k1_fe fex = *x;
secp256k1_fe fez;
/* Results of set_xquad_var, set_xo_var(..., 0), set_xo_var(..., 1). */
secp256k1_ge ge_quad, ge_even, ge_odd;
secp256k1_gej gej_quad;
/* Return values of the above calls. */
int res_quad, res_even, res_odd;
secp256k1_fe_normalize_var(&fex);
res_quad = secp256k1_ge_set_xquad(&ge_quad, &fex);
res_even = secp256k1_ge_set_xo_var(&ge_even, &fex, 0);
res_odd = secp256k1_ge_set_xo_var(&ge_odd, &fex, 1);
CHECK(res_quad == res_even);
CHECK(res_quad == res_odd);
if (res_quad) {
secp256k1_fe_normalize_var(&ge_quad.x);
secp256k1_fe_normalize_var(&ge_odd.x);
secp256k1_fe_normalize_var(&ge_even.x);
secp256k1_fe_normalize_var(&ge_quad.y);
secp256k1_fe_normalize_var(&ge_odd.y);
secp256k1_fe_normalize_var(&ge_even.y);
/* No infinity allowed. */
CHECK(!ge_quad.infinity);
CHECK(!ge_even.infinity);
CHECK(!ge_odd.infinity);
/* Check that the x coordinates check out. */
CHECK(secp256k1_fe_equal_var(&ge_quad.x, x));
CHECK(secp256k1_fe_equal_var(&ge_even.x, x));
CHECK(secp256k1_fe_equal_var(&ge_odd.x, x));
/* Check that the Y coordinate result in ge_quad is a square. */
CHECK(secp256k1_fe_is_quad_var(&ge_quad.y));
/* Check odd/even Y in ge_odd, ge_even. */
CHECK(secp256k1_fe_is_odd(&ge_odd.y));
CHECK(!secp256k1_fe_is_odd(&ge_even.y));
/* Check secp256k1_gej_has_quad_y_var. */
secp256k1_gej_set_ge(&gej_quad, &ge_quad);
CHECK(secp256k1_gej_has_quad_y_var(&gej_quad));
do {
random_fe_test(&fez);
} while (secp256k1_fe_is_zero(&fez));
secp256k1_gej_rescale(&gej_quad, &fez);
CHECK(secp256k1_gej_has_quad_y_var(&gej_quad));
secp256k1_gej_neg(&gej_quad, &gej_quad);
CHECK(!secp256k1_gej_has_quad_y_var(&gej_quad));
do {
random_fe_test(&fez);
} while (secp256k1_fe_is_zero(&fez));
secp256k1_gej_rescale(&gej_quad, &fez);
CHECK(!secp256k1_gej_has_quad_y_var(&gej_quad));
secp256k1_gej_neg(&gej_quad, &gej_quad);
CHECK(secp256k1_gej_has_quad_y_var(&gej_quad));
}
}
void run_group_decompress(void) {
int i;
for (i = 0; i < count * 4; i++) {
secp256k1_fe fe;
random_fe_test(&fe);
test_group_decompress(&fe);
}
}
/***** ECMULT TESTS *****/
void run_ecmult_chain(void) {
/* random starting point A (on the curve) */
secp256k1_gej a = SECP256K1_GEJ_CONST(
0x8b30bbe9, 0xae2a9906, 0x96b22f67, 0x0709dff3,
0x727fd8bc, 0x04d3362c, 0x6c7bf458, 0xe2846004,
0xa357ae91, 0x5c4a6528, 0x1309edf2, 0x0504740f,
0x0eb33439, 0x90216b4f, 0x81063cb6, 0x5f2f7e0f
);
/* two random initial factors xn and gn */
secp256k1_scalar xn = SECP256K1_SCALAR_CONST(
0x84cc5452, 0xf7fde1ed, 0xb4d38a8c, 0xe9b1b84c,
0xcef31f14, 0x6e569be9, 0x705d357a, 0x42985407
);
secp256k1_scalar gn = SECP256K1_SCALAR_CONST(
0xa1e58d22, 0x553dcd42, 0xb2398062, 0x5d4c57a9,
0x6e9323d4, 0x2b3152e5, 0xca2c3990, 0xedc7c9de
);
/* two small multipliers to be applied to xn and gn in every iteration: */
static const secp256k1_scalar xf = SECP256K1_SCALAR_CONST(0, 0, 0, 0, 0, 0, 0, 0x1337);
static const secp256k1_scalar gf = SECP256K1_SCALAR_CONST(0, 0, 0, 0, 0, 0, 0, 0x7113);
/* accumulators with the resulting coefficients to A and G */
secp256k1_scalar ae = SECP256K1_SCALAR_CONST(0, 0, 0, 0, 0, 0, 0, 1);
secp256k1_scalar ge = SECP256K1_SCALAR_CONST(0, 0, 0, 0, 0, 0, 0, 0);
/* actual points */
secp256k1_gej x;
secp256k1_gej x2;
int i;
/* the point being computed */
x = a;
for (i = 0; i < 200*count; i++) {
/* in each iteration, compute X = xn*X + gn*G; */
secp256k1_ecmult(&ctx->ecmult_ctx, &x, &x, &xn, &gn);
/* also compute ae and ge: the actual accumulated factors for A and G */
/* if X was (ae*A+ge*G), xn*X + gn*G results in (xn*ae*A + (xn*ge+gn)*G) */
secp256k1_scalar_mul(&ae, &ae, &xn);
secp256k1_scalar_mul(&ge, &ge, &xn);
secp256k1_scalar_add(&ge, &ge, &gn);
/* modify xn and gn */
secp256k1_scalar_mul(&xn, &xn, &xf);
secp256k1_scalar_mul(&gn, &gn, &gf);
/* verify */
if (i == 19999) {
/* expected result after 19999 iterations */
secp256k1_gej rp = SECP256K1_GEJ_CONST(
0xD6E96687, 0xF9B10D09, 0x2A6F3543, 0x9D86CEBE,
0xA4535D0D, 0x409F5358, 0x6440BD74, 0xB933E830,
0xB95CBCA2, 0xC77DA786, 0x539BE8FD, 0x53354D2D,
0x3B4F566A, 0xE6580454, 0x07ED6015, 0xEE1B2A88
);
secp256k1_gej_neg(&rp, &rp);
secp256k1_gej_add_var(&rp, &rp, &x, NULL);
CHECK(secp256k1_gej_is_infinity(&rp));
}
}
/* redo the computation, but directly with the resulting ae and ge coefficients: */
secp256k1_ecmult(&ctx->ecmult_ctx, &x2, &a, &ae, &ge);
secp256k1_gej_neg(&x2, &x2);
secp256k1_gej_add_var(&x2, &x2, &x, NULL);
CHECK(secp256k1_gej_is_infinity(&x2));
}
void test_point_times_order(const secp256k1_gej *point) {
/* X * (point + G) + (order-X) * (pointer + G) = 0 */
secp256k1_scalar x;
secp256k1_scalar nx;
secp256k1_scalar zero = SECP256K1_SCALAR_CONST(0, 0, 0, 0, 0, 0, 0, 0);
secp256k1_scalar one = SECP256K1_SCALAR_CONST(0, 0, 0, 0, 0, 0, 0, 1);
secp256k1_gej res1, res2;
secp256k1_ge res3;
unsigned char pub[65];
size_t psize = 65;
random_scalar_order_test(&x);
secp256k1_scalar_negate(&nx, &x);
secp256k1_ecmult(&ctx->ecmult_ctx, &res1, point, &x, &x); /* calc res1 = x * point + x * G; */
secp256k1_ecmult(&ctx->ecmult_ctx, &res2, point, &nx, &nx); /* calc res2 = (order - x) * point + (order - x) * G; */
secp256k1_gej_add_var(&res1, &res1, &res2, NULL);
CHECK(secp256k1_gej_is_infinity(&res1));
CHECK(secp256k1_gej_is_valid_var(&res1) == 0);
secp256k1_ge_set_gej(&res3, &res1);
CHECK(secp256k1_ge_is_infinity(&res3));
CHECK(secp256k1_ge_is_valid_var(&res3) == 0);
CHECK(secp256k1_eckey_pubkey_serialize(&res3, pub, &psize, 0) == 0);
psize = 65;
CHECK(secp256k1_eckey_pubkey_serialize(&res3, pub, &psize, 1) == 0);
/* check zero/one edge cases */
secp256k1_ecmult(&ctx->ecmult_ctx, &res1, point, &zero, &zero);
secp256k1_ge_set_gej(&res3, &res1);
CHECK(secp256k1_ge_is_infinity(&res3));
secp256k1_ecmult(&ctx->ecmult_ctx, &res1, point, &one, &zero);
secp256k1_ge_set_gej(&res3, &res1);
ge_equals_gej(&res3, point);
secp256k1_ecmult(&ctx->ecmult_ctx, &res1, point, &zero, &one);
secp256k1_ge_set_gej(&res3, &res1);
ge_equals_ge(&res3, &secp256k1_ge_const_g);
}
void run_point_times_order(void) {
int i;
secp256k1_fe x = SECP256K1_FE_CONST(0, 0, 0, 0, 0, 0, 0, 2);
static const secp256k1_fe xr = SECP256K1_FE_CONST(
0x7603CB59, 0xB0EF6C63, 0xFE608479, 0x2A0C378C,
0xDB3233A8, 0x0F8A9A09, 0xA877DEAD, 0x31B38C45
);
for (i = 0; i < 500; i++) {
secp256k1_ge p;
if (secp256k1_ge_set_xo_var(&p, &x, 1)) {
secp256k1_gej j;
CHECK(secp256k1_ge_is_valid_var(&p));
secp256k1_gej_set_ge(&j, &p);
CHECK(secp256k1_gej_is_valid_var(&j));
test_point_times_order(&j);
}
secp256k1_fe_sqr(&x, &x);
}
secp256k1_fe_normalize_var(&x);
CHECK(secp256k1_fe_equal_var(&x, &xr));
}
void ecmult_const_random_mult(void) {
/* random starting point A (on the curve) */
secp256k1_ge a = SECP256K1_GE_CONST(
0x6d986544, 0x57ff52b8, 0xcf1b8126, 0x5b802a5b,
0xa97f9263, 0xb1e88044, 0x93351325, 0x91bc450a,
0x535c59f7, 0x325e5d2b, 0xc391fbe8, 0x3c12787c,
0x337e4a98, 0xe82a9011, 0x0123ba37, 0xdd769c7d
);
/* random initial factor xn */
secp256k1_scalar xn = SECP256K1_SCALAR_CONST(
0x649d4f77, 0xc4242df7, 0x7f2079c9, 0x14530327,
0xa31b876a, 0xd2d8ce2a, 0x2236d5c6, 0xd7b2029b
);
/* expected xn * A (from sage) */
secp256k1_ge expected_b = SECP256K1_GE_CONST(
0x23773684, 0x4d209dc7, 0x098a786f, 0x20d06fcd,
0x070a38bf, 0xc11ac651, 0x03004319, 0x1e2a8786,
0xed8c3b8e, 0xc06dd57b, 0xd06ea66e, 0x45492b0f,
0xb84e4e1b, 0xfb77e21f, 0x96baae2a, 0x63dec956
);
secp256k1_gej b;
secp256k1_ecmult_const(&b, &a, &xn);
CHECK(secp256k1_ge_is_valid_var(&a));
ge_equals_gej(&expected_b, &b);
}
void ecmult_const_commutativity(void) {
secp256k1_scalar a;
secp256k1_scalar b;
secp256k1_gej res1;
secp256k1_gej res2;
secp256k1_ge mid1;
secp256k1_ge mid2;
random_scalar_order_test(&a);
random_scalar_order_test(&b);
secp256k1_ecmult_const(&res1, &secp256k1_ge_const_g, &a);
secp256k1_ecmult_const(&res2, &secp256k1_ge_const_g, &b);
secp256k1_ge_set_gej(&mid1, &res1);
secp256k1_ge_set_gej(&mid2, &res2);
secp256k1_ecmult_const(&res1, &mid1, &b);
secp256k1_ecmult_const(&res2, &mid2, &a);
secp256k1_ge_set_gej(&mid1, &res1);
secp256k1_ge_set_gej(&mid2, &res2);
ge_equals_ge(&mid1, &mid2);
}
void ecmult_const_mult_zero_one(void) {
secp256k1_scalar zero = SECP256K1_SCALAR_CONST(0, 0, 0, 0, 0, 0, 0, 0);
secp256k1_scalar one = SECP256K1_SCALAR_CONST(0, 0, 0, 0, 0, 0, 0, 1);
secp256k1_scalar negone;
secp256k1_gej res1;
secp256k1_ge res2;
secp256k1_ge point;
secp256k1_scalar_negate(&negone, &one);
random_group_element_test(&point);
secp256k1_ecmult_const(&res1, &point, &zero);
secp256k1_ge_set_gej(&res2, &res1);
CHECK(secp256k1_ge_is_infinity(&res2));
secp256k1_ecmult_const(&res1, &point, &one);
secp256k1_ge_set_gej(&res2, &res1);
ge_equals_ge(&res2, &point);
secp256k1_ecmult_const(&res1, &point, &negone);
secp256k1_gej_neg(&res1, &res1);
secp256k1_ge_set_gej(&res2, &res1);
ge_equals_ge(&res2, &point);
}
void ecmult_const_chain_multiply(void) {
/* Check known result (randomly generated test problem from sage) */
const secp256k1_scalar scalar = SECP256K1_SCALAR_CONST(
0x4968d524, 0x2abf9b7a, 0x466abbcf, 0x34b11b6d,
0xcd83d307, 0x827bed62, 0x05fad0ce, 0x18fae63b
);
const secp256k1_gej expected_point = SECP256K1_GEJ_CONST(
0x5494c15d, 0x32099706, 0xc2395f94, 0x348745fd,
0x757ce30e, 0x4e8c90fb, 0xa2bad184, 0xf883c69f,
0x5d195d20, 0xe191bf7f, 0x1be3e55f, 0x56a80196,
0x6071ad01, 0xf1462f66, 0xc997fa94, 0xdb858435
);
secp256k1_gej point;
secp256k1_ge res;
int i;
secp256k1_gej_set_ge(&point, &secp256k1_ge_const_g);
for (i = 0; i < 100; ++i) {
secp256k1_ge tmp;
secp256k1_ge_set_gej(&tmp, &point);
secp256k1_ecmult_const(&point, &tmp, &scalar);
}
secp256k1_ge_set_gej(&res, &point);
ge_equals_gej(&res, &expected_point);
}
void run_ecmult_const_tests(void) {
ecmult_const_mult_zero_one();
ecmult_const_random_mult();
ecmult_const_commutativity();
ecmult_const_chain_multiply();
}
typedef struct {
secp256k1_scalar *sc;
secp256k1_ge *pt;
} ecmult_multi_data;
static int ecmult_multi_callback(secp256k1_scalar *sc, secp256k1_ge *pt, size_t idx, void *cbdata) {
ecmult_multi_data *data = (ecmult_multi_data*) cbdata;
*sc = data->sc[idx];
*pt = data->pt[idx];
return 1;
}
static int ecmult_multi_false_callback(secp256k1_scalar *sc, secp256k1_ge *pt, size_t idx, void *cbdata) {
(void)sc;
(void)pt;
(void)idx;
(void)cbdata;
return 0;
}
void test_ecmult_multi(secp256k1_scratch *scratch, secp256k1_ecmult_multi_func ecmult_multi) {
int ncount;
secp256k1_scalar szero;
secp256k1_scalar sc[32];
secp256k1_ge pt[32];
secp256k1_gej r;
secp256k1_gej r2;
ecmult_multi_data data;
secp256k1_scratch *scratch_empty;
data.sc = sc;
data.pt = pt;
secp256k1_scalar_set_int(&szero, 0);
secp256k1_scratch_reset(scratch);
/* No points to multiply */
CHECK(ecmult_multi(&ctx->ecmult_ctx, scratch, &r, NULL, ecmult_multi_callback, &data, 0));
/* Check 1- and 2-point multiplies against ecmult */
for (ncount = 0; ncount < count; ncount++) {
secp256k1_ge ptg;
secp256k1_gej ptgj;
random_scalar_order(&sc[0]);
random_scalar_order(&sc[1]);
random_group_element_test(&ptg);
secp256k1_gej_set_ge(&ptgj, &ptg);
pt[0] = ptg;
pt[1] = secp256k1_ge_const_g;
/* only G scalar */
secp256k1_ecmult(&ctx->ecmult_ctx, &r2, &ptgj, &szero, &sc[0]);
CHECK(ecmult_multi(&ctx->ecmult_ctx, scratch, &r, &sc[0], ecmult_multi_callback, &data, 0));
secp256k1_gej_neg(&r2, &r2);
secp256k1_gej_add_var(&r, &r, &r2, NULL);
CHECK(secp256k1_gej_is_infinity(&r));
/* 1-point */
secp256k1_ecmult(&ctx->ecmult_ctx, &r2, &ptgj, &sc[0], &szero);
CHECK(ecmult_multi(&ctx->ecmult_ctx, scratch, &r, &szero, ecmult_multi_callback, &data, 1));
secp256k1_gej_neg(&r2, &r2);
secp256k1_gej_add_var(&r, &r, &r2, NULL);
CHECK(secp256k1_gej_is_infinity(&r));
/* Try to multiply 1 point, but scratch space is empty */
scratch_empty = secp256k1_scratch_create(&ctx->error_callback, 0, 0);
CHECK(!ecmult_multi(&ctx->ecmult_ctx, scratch_empty, &r, &szero, ecmult_multi_callback, &data, 1));
secp256k1_scratch_destroy(scratch_empty);
/* Try to multiply 1 point, but callback returns false */
CHECK(!ecmult_multi(&ctx->ecmult_ctx, scratch, &r, &szero, ecmult_multi_false_callback, &data, 1));
/* 2-point */
secp256k1_ecmult(&ctx->ecmult_ctx, &r2, &ptgj, &sc[0], &sc[1]);
CHECK(ecmult_multi(&ctx->ecmult_ctx, scratch, &r, &szero, ecmult_multi_callback, &data, 2));
secp256k1_gej_neg(&r2, &r2);
secp256k1_gej_add_var(&r, &r, &r2, NULL);
CHECK(secp256k1_gej_is_infinity(&r));
/* 2-point with G scalar */
secp256k1_ecmult(&ctx->ecmult_ctx, &r2, &ptgj, &sc[0], &sc[1]);
CHECK(ecmult_multi(&ctx->ecmult_ctx, scratch, &r, &sc[1], ecmult_multi_callback, &data, 1));
secp256k1_gej_neg(&r2, &r2);
secp256k1_gej_add_var(&r, &r, &r2, NULL);
CHECK(secp256k1_gej_is_infinity(&r));
}
/* Check infinite outputs of various forms */
for (ncount = 0; ncount < count; ncount++) {
secp256k1_ge ptg;
size_t i, j;
size_t sizes[] = { 2, 10, 32 };
for (j = 0; j < 3; j++) {
for (i = 0; i < 32; i++) {
random_scalar_order(&sc[i]);
secp256k1_ge_set_infinity(&pt[i]);
}
CHECK(ecmult_multi(&ctx->ecmult_ctx, scratch, &r, &szero, ecmult_multi_callback, &data, sizes[j]));
CHECK(secp256k1_gej_is_infinity(&r));
}
for (j = 0; j < 3; j++) {
for (i = 0; i < 32; i++) {
random_group_element_test(&ptg);
pt[i] = ptg;
secp256k1_scalar_set_int(&sc[i], 0);
}
CHECK(ecmult_multi(&ctx->ecmult_ctx, scratch, &r, &szero, ecmult_multi_callback, &data, sizes[j]));
CHECK(secp256k1_gej_is_infinity(&r));
}
for (j = 0; j < 3; j++) {
random_group_element_test(&ptg);
for (i = 0; i < 16; i++) {
random_scalar_order(&sc[2*i]);
secp256k1_scalar_negate(&sc[2*i + 1], &sc[2*i]);
pt[2 * i] = ptg;
pt[2 * i + 1] = ptg;
}
CHECK(ecmult_multi(&ctx->ecmult_ctx, scratch, &r, &szero, ecmult_multi_callback, &data, sizes[j]));
CHECK(secp256k1_gej_is_infinity(&r));
random_scalar_order(&sc[0]);
for (i = 0; i < 16; i++) {
random_group_element_test(&ptg);
sc[2*i] = sc[0];
sc[2*i+1] = sc[0];
pt[2 * i] = ptg;
secp256k1_ge_neg(&pt[2*i+1], &pt[2*i]);
}
CHECK(ecmult_multi(&ctx->ecmult_ctx, scratch, &r, &szero, ecmult_multi_callback, &data, sizes[j]));
CHECK(secp256k1_gej_is_infinity(&r));
}
random_group_element_test(&ptg);
secp256k1_scalar_set_int(&sc[0], 0);
pt[0] = ptg;
for (i = 1; i < 32; i++) {
pt[i] = ptg;
random_scalar_order(&sc[i]);
secp256k1_scalar_add(&sc[0], &sc[0], &sc[i]);
secp256k1_scalar_negate(&sc[i], &sc[i]);
}
CHECK(ecmult_multi(&ctx->ecmult_ctx, scratch, &r, &szero, ecmult_multi_callback, &data, 32));
CHECK(secp256k1_gej_is_infinity(&r));
}
/* Check random points, constant scalar */
for (ncount = 0; ncount < count; ncount++) {
size_t i;
secp256k1_gej_set_infinity(&r);
random_scalar_order(&sc[0]);
for (i = 0; i < 20; i++) {
secp256k1_ge ptg;
sc[i] = sc[0];
random_group_element_test(&ptg);
pt[i] = ptg;
secp256k1_gej_add_ge_var(&r, &r, &pt[i], NULL);
}
secp256k1_ecmult(&ctx->ecmult_ctx, &r2, &r, &sc[0], &szero);
CHECK(ecmult_multi(&ctx->ecmult_ctx, scratch, &r, &szero, ecmult_multi_callback, &data, 20));
secp256k1_gej_neg(&r2, &r2);
secp256k1_gej_add_var(&r, &r, &r2, NULL);
CHECK(secp256k1_gej_is_infinity(&r));
}
/* Check random scalars, constant point */
for (ncount = 0; ncount < count; ncount++) {
size_t i;
secp256k1_ge ptg;
secp256k1_gej p0j;
secp256k1_scalar rs;
secp256k1_scalar_set_int(&rs, 0);
random_group_element_test(&ptg);
for (i = 0; i < 20; i++) {
random_scalar_order(&sc[i]);
pt[i] = ptg;
secp256k1_scalar_add(&rs, &rs, &sc[i]);
}
secp256k1_gej_set_ge(&p0j, &pt[0]);
secp256k1_ecmult(&ctx->ecmult_ctx, &r2, &p0j, &rs, &szero);
CHECK(ecmult_multi(&ctx->ecmult_ctx, scratch, &r, &szero, ecmult_multi_callback, &data, 20));
secp256k1_gej_neg(&r2, &r2);
secp256k1_gej_add_var(&r, &r, &r2, NULL);
CHECK(secp256k1_gej_is_infinity(&r));
}
/* Sanity check that zero scalars don't cause problems */
secp256k1_scalar_clear(&sc[0]);
CHECK(ecmult_multi(&ctx->ecmult_ctx, scratch, &r, &szero, ecmult_multi_callback, &data, 20));
secp256k1_scalar_clear(&sc[1]);
secp256k1_scalar_clear(&sc[2]);
secp256k1_scalar_clear(&sc[3]);
secp256k1_scalar_clear(&sc[4]);
CHECK(ecmult_multi(&ctx->ecmult_ctx, scratch, &r, &szero, ecmult_multi_callback, &data, 6));
CHECK(ecmult_multi(&ctx->ecmult_ctx, scratch, &r, &szero, ecmult_multi_callback, &data, 5));
CHECK(secp256k1_gej_is_infinity(&r));
/* Run through s0*(t0*P) + s1*(t1*P) exhaustively for many small values of s0, s1, t0, t1 */
{
const size_t TOP = 8;
size_t s0i, s1i;
size_t t0i, t1i;
secp256k1_ge ptg;
secp256k1_gej ptgj;
random_group_element_test(&ptg);
secp256k1_gej_set_ge(&ptgj, &ptg);
for(t0i = 0; t0i < TOP; t0i++) {
for(t1i = 0; t1i < TOP; t1i++) {
secp256k1_gej t0p, t1p;
secp256k1_scalar t0, t1;
secp256k1_scalar_set_int(&t0, (t0i + 1) / 2);
secp256k1_scalar_cond_negate(&t0, t0i & 1);
secp256k1_scalar_set_int(&t1, (t1i + 1) / 2);
secp256k1_scalar_cond_negate(&t1, t1i & 1);
secp256k1_ecmult(&ctx->ecmult_ctx, &t0p, &ptgj, &t0, &szero);
secp256k1_ecmult(&ctx->ecmult_ctx, &t1p, &ptgj, &t1, &szero);
for(s0i = 0; s0i < TOP; s0i++) {
for(s1i = 0; s1i < TOP; s1i++) {
secp256k1_scalar tmp1, tmp2;
secp256k1_gej expected, actual;
secp256k1_ge_set_gej(&pt[0], &t0p);
secp256k1_ge_set_gej(&pt[1], &t1p);
secp256k1_scalar_set_int(&sc[0], (s0i + 1) / 2);
secp256k1_scalar_cond_negate(&sc[0], s0i & 1);
secp256k1_scalar_set_int(&sc[1], (s1i + 1) / 2);
secp256k1_scalar_cond_negate(&sc[1], s1i & 1);
secp256k1_scalar_mul(&tmp1, &t0, &sc[0]);
secp256k1_scalar_mul(&tmp2, &t1, &sc[1]);
secp256k1_scalar_add(&tmp1, &tmp1, &tmp2);
secp256k1_ecmult(&ctx->ecmult_ctx, &expected, &ptgj, &tmp1, &szero);
CHECK(ecmult_multi(&ctx->ecmult_ctx, scratch, &actual, &szero, ecmult_multi_callback, &data, 2));
secp256k1_gej_neg(&expected, &expected);
secp256k1_gej_add_var(&actual, &actual, &expected, NULL);
CHECK(secp256k1_gej_is_infinity(&actual));
}
}
}
}
}
}
void test_secp256k1_pippenger_bucket_window_inv(void) {
int i;
CHECK(secp256k1_pippenger_bucket_window_inv(0) == 0);
for(i = 1; i <= PIPPENGER_MAX_BUCKET_WINDOW; i++) {
#ifdef USE_ENDOMORPHISM
/* Bucket_window of 8 is not used with endo */
if (i == 8) {
continue;
}
#endif
CHECK(secp256k1_pippenger_bucket_window(secp256k1_pippenger_bucket_window_inv(i)) == i);
if (i != PIPPENGER_MAX_BUCKET_WINDOW) {
CHECK(secp256k1_pippenger_bucket_window(secp256k1_pippenger_bucket_window_inv(i)+1) > i);
}
}
}
/**
* Probabilistically test the function returning the maximum number of possible points
* for a given scratch space.
*/
void test_ecmult_multi_pippenger_max_points(void) {
size_t scratch_size = secp256k1_rand_int(256);
size_t max_size = secp256k1_pippenger_scratch_size(secp256k1_pippenger_bucket_window_inv(PIPPENGER_MAX_BUCKET_WINDOW-1)+512, 12);
secp256k1_scratch *scratch;
size_t n_points_supported;
int bucket_window = 0;
for(; scratch_size < max_size; scratch_size+=256) {
scratch = secp256k1_scratch_create(&ctx->error_callback, 0, scratch_size);
CHECK(scratch != NULL);
n_points_supported = secp256k1_pippenger_max_points(scratch);
if (n_points_supported == 0) {
secp256k1_scratch_destroy(scratch);
continue;
}
bucket_window = secp256k1_pippenger_bucket_window(n_points_supported);
CHECK(secp256k1_scratch_resize(scratch, secp256k1_pippenger_scratch_size(n_points_supported, bucket_window), PIPPENGER_SCRATCH_OBJECTS));
secp256k1_scratch_destroy(scratch);
}
CHECK(bucket_window == PIPPENGER_MAX_BUCKET_WINDOW);
}
/**
* Run secp256k1_ecmult_multi_var with num points and a scratch space restricted to
* 1 <= i <= num points.
*/
void test_ecmult_multi_batching(void) {
static const int n_points = 2*ECMULT_PIPPENGER_THRESHOLD;
secp256k1_scalar scG;
secp256k1_scalar szero;
secp256k1_scalar *sc = (secp256k1_scalar *)checked_malloc(&ctx->error_callback, sizeof(secp256k1_scalar) * n_points);
secp256k1_ge *pt = (secp256k1_ge *)checked_malloc(&ctx->error_callback, sizeof(secp256k1_ge) * n_points);
secp256k1_gej r;
secp256k1_gej r2;
ecmult_multi_data data;
int i;
secp256k1_scratch *scratch;
secp256k1_gej_set_infinity(&r2);
secp256k1_scalar_set_int(&szero, 0);
/* Get random scalars and group elements and compute result */
random_scalar_order(&scG);
secp256k1_ecmult(&ctx->ecmult_ctx, &r2, &r2, &szero, &scG);
for(i = 0; i < n_points; i++) {
secp256k1_ge ptg;
secp256k1_gej ptgj;
random_group_element_test(&ptg);
secp256k1_gej_set_ge(&ptgj, &ptg);
pt[i] = ptg;
random_scalar_order(&sc[i]);
secp256k1_ecmult(&ctx->ecmult_ctx, &ptgj, &ptgj, &sc[i], NULL);
secp256k1_gej_add_var(&r2, &r2, &ptgj, NULL);
}
data.sc = sc;
data.pt = pt;
/* Test with empty scratch space */
scratch = secp256k1_scratch_create(&ctx->error_callback, 0, 0);
CHECK(!secp256k1_ecmult_multi_var(&ctx->ecmult_ctx, scratch, &r, &scG, ecmult_multi_callback, &data, 1));
secp256k1_scratch_destroy(scratch);
/* Test with space for 1 point in pippenger. That's not enough because
* ecmult_multi selects strauss which requires more memory. */
scratch = secp256k1_scratch_create(&ctx->error_callback, 0, secp256k1_pippenger_scratch_size(1, 1) + PIPPENGER_SCRATCH_OBJECTS*ALIGNMENT);
CHECK(!secp256k1_ecmult_multi_var(&ctx->ecmult_ctx, scratch, &r, &scG, ecmult_multi_callback, &data, 1));
secp256k1_scratch_destroy(scratch);
secp256k1_gej_neg(&r2, &r2);
for(i = 1; i <= n_points; i++) {
if (i > ECMULT_PIPPENGER_THRESHOLD) {
int bucket_window = secp256k1_pippenger_bucket_window(i);
size_t scratch_size = secp256k1_pippenger_scratch_size(i, bucket_window);
scratch = secp256k1_scratch_create(&ctx->error_callback, 0, scratch_size + PIPPENGER_SCRATCH_OBJECTS*ALIGNMENT);
} else {
size_t scratch_size = secp256k1_strauss_scratch_size(i);
scratch = secp256k1_scratch_create(&ctx->error_callback, 0, scratch_size + STRAUSS_SCRATCH_OBJECTS*ALIGNMENT);
}
CHECK(secp256k1_ecmult_multi_var(&ctx->ecmult_ctx, scratch, &r, &scG, ecmult_multi_callback, &data, n_points));
secp256k1_gej_add_var(&r, &r, &r2, NULL);
CHECK(secp256k1_gej_is_infinity(&r));
secp256k1_scratch_destroy(scratch);
}
free(sc);
free(pt);
}
void run_ecmult_multi_tests(void) {
secp256k1_scratch *scratch;
test_secp256k1_pippenger_bucket_window_inv();
test_ecmult_multi_pippenger_max_points();
scratch = secp256k1_scratch_create(&ctx->error_callback, 0, 819200);
test_ecmult_multi(scratch, secp256k1_ecmult_multi_var);
test_ecmult_multi(scratch, secp256k1_ecmult_pippenger_batch_single);
test_ecmult_multi(scratch, secp256k1_ecmult_strauss_batch_single);
secp256k1_scratch_destroy(scratch);
/* Run test_ecmult_multi with space for exactly one point */
scratch = secp256k1_scratch_create(&ctx->error_callback, 0, secp256k1_strauss_scratch_size(1) + STRAUSS_SCRATCH_OBJECTS*ALIGNMENT);
test_ecmult_multi(scratch, secp256k1_ecmult_multi_var);
secp256k1_scratch_destroy(scratch);
test_ecmult_multi_batching();
}
void test_wnaf(const secp256k1_scalar *number, int w) {
secp256k1_scalar x, two, t;
int wnaf[256];
int zeroes = -1;
int i;
int bits;
secp256k1_scalar_set_int(&x, 0);
secp256k1_scalar_set_int(&two, 2);
bits = secp256k1_ecmult_wnaf(wnaf, 256, number, w);
CHECK(bits <= 256);
for (i = bits-1; i >= 0; i--) {
int v = wnaf[i];
secp256k1_scalar_mul(&x, &x, &two);
if (v) {
CHECK(zeroes == -1 || zeroes >= w-1); /* check that distance between non-zero elements is at least w-1 */
zeroes=0;
CHECK((v & 1) == 1); /* check non-zero elements are odd */
CHECK(v <= (1 << (w-1)) - 1); /* check range below */
CHECK(v >= -(1 << (w-1)) - 1); /* check range above */
} else {
CHECK(zeroes != -1); /* check that no unnecessary zero padding exists */
zeroes++;
}
if (v >= 0) {
secp256k1_scalar_set_int(&t, v);
} else {
secp256k1_scalar_set_int(&t, -v);
secp256k1_scalar_negate(&t, &t);
}
secp256k1_scalar_add(&x, &x, &t);
}
CHECK(secp256k1_scalar_eq(&x, number)); /* check that wnaf represents number */
}
void test_constant_wnaf_negate(const secp256k1_scalar *number) {
secp256k1_scalar neg1 = *number;
secp256k1_scalar neg2 = *number;
int sign1 = 1;
int sign2 = 1;
if (!secp256k1_scalar_get_bits(&neg1, 0, 1)) {
secp256k1_scalar_negate(&neg1, &neg1);
sign1 = -1;
}
sign2 = secp256k1_scalar_cond_negate(&neg2, secp256k1_scalar_is_even(&neg2));
CHECK(sign1 == sign2);
CHECK(secp256k1_scalar_eq(&neg1, &neg2));
}
void test_constant_wnaf(const secp256k1_scalar *number, int w) {
secp256k1_scalar x, shift;
int wnaf[256] = {0};
int i;
int skew;
secp256k1_scalar num = *number;
secp256k1_scalar_set_int(&x, 0);
secp256k1_scalar_set_int(&shift, 1 << w);
/* With USE_ENDOMORPHISM on we only consider 128-bit numbers */
#ifdef USE_ENDOMORPHISM
for (i = 0; i < 16; ++i) {
secp256k1_scalar_shr_int(&num, 8);
}
#endif
skew = secp256k1_wnaf_const(wnaf, num, w);
for (i = WNAF_SIZE(w); i >= 0; --i) {
secp256k1_scalar t;
int v = wnaf[i];
CHECK(v != 0); /* check nonzero */
CHECK(v & 1); /* check parity */
CHECK(v > -(1 << w)); /* check range above */
CHECK(v < (1 << w)); /* check range below */
secp256k1_scalar_mul(&x, &x, &shift);
if (v >= 0) {
secp256k1_scalar_set_int(&t, v);
} else {
secp256k1_scalar_set_int(&t, -v);
secp256k1_scalar_negate(&t, &t);
}
secp256k1_scalar_add(&x, &x, &t);
}
/* Skew num because when encoding numbers as odd we use an offset */
secp256k1_scalar_cadd_bit(&num, skew == 2, 1);
CHECK(secp256k1_scalar_eq(&x, &num));
}
void test_fixed_wnaf(const secp256k1_scalar *number, int w) {
secp256k1_scalar x, shift;
int wnaf[256] = {0};
int i;
int skew;
secp256k1_scalar num = *number;
secp256k1_scalar_set_int(&x, 0);
secp256k1_scalar_set_int(&shift, 1 << w);
/* With USE_ENDOMORPHISM on we only consider 128-bit numbers */
#ifdef USE_ENDOMORPHISM
for (i = 0; i < 16; ++i) {
secp256k1_scalar_shr_int(&num, 8);
}
#endif
skew = secp256k1_wnaf_fixed(wnaf, &num, w);
for (i = WNAF_SIZE(w)-1; i >= 0; --i) {
secp256k1_scalar t;
int v = wnaf[i];
CHECK(v != 0); /* check nonzero */
CHECK(v & 1); /* check parity */
CHECK(v > -(1 << w)); /* check range above */
CHECK(v < (1 << w)); /* check range below */
secp256k1_scalar_mul(&x, &x, &shift);
if (v >= 0) {
secp256k1_scalar_set_int(&t, v);
} else {
secp256k1_scalar_set_int(&t, -v);
secp256k1_scalar_negate(&t, &t);
}
secp256k1_scalar_add(&x, &x, &t);
}
/* If skew is 1 then add 1 to num */
secp256k1_scalar_cadd_bit(&num, 0, skew == 1);
CHECK(secp256k1_scalar_eq(&x, &num));
}
void test_fixed_wnaf_zero(int w) {
int wnaf[256] = {0};
int i;
int skew;
secp256k1_scalar num;
secp256k1_scalar_set_int(&num, 0);
skew = secp256k1_wnaf_fixed(wnaf, &num, w);
for (i = WNAF_SIZE(w)-1; i >= 0; --i) {
int v = wnaf[i];
CHECK(v == 0);
}
CHECK(skew == 0);
}
void run_wnaf(void) {
int i;
secp256k1_scalar n = {{0}};
/* Sanity check: 1 and 2 are the smallest odd and even numbers and should
* have easier-to-diagnose failure modes */
n.d[0] = 1;
test_constant_wnaf(&n, 4);
n.d[0] = 2;
test_constant_wnaf(&n, 4);
/* Test 0 */
test_fixed_wnaf_zero(4);
/* Random tests */
for (i = 0; i < count; i++) {
random_scalar_order(&n);
test_wnaf(&n, 4+(i%10));
test_constant_wnaf_negate(&n);
test_constant_wnaf(&n, 4 + (i % 10));
test_fixed_wnaf(&n, 4 + (i % 10));
}
secp256k1_scalar_set_int(&n, 0);
CHECK(secp256k1_scalar_cond_negate(&n, 1) == -1);
CHECK(secp256k1_scalar_is_zero(&n));
CHECK(secp256k1_scalar_cond_negate(&n, 0) == 1);
CHECK(secp256k1_scalar_is_zero(&n));
}
void test_ecmult_constants(void) {
/* Test ecmult_gen() for [0..36) and [order-36..0). */
secp256k1_scalar x;
secp256k1_gej r;
secp256k1_ge ng;
int i;
int j;
secp256k1_ge_neg(&ng, &secp256k1_ge_const_g);
for (i = 0; i < 36; i++ ) {
secp256k1_scalar_set_int(&x, i);
secp256k1_ecmult_gen(&ctx->ecmult_gen_ctx, &r, &x);
for (j = 0; j < i; j++) {
if (j == i - 1) {
ge_equals_gej(&secp256k1_ge_const_g, &r);
}
secp256k1_gej_add_ge(&r, &r, &ng);
}
CHECK(secp256k1_gej_is_infinity(&r));
}
for (i = 1; i <= 36; i++ ) {
secp256k1_scalar_set_int(&x, i);
secp256k1_scalar_negate(&x, &x);
secp256k1_ecmult_gen(&ctx->ecmult_gen_ctx, &r, &x);
for (j = 0; j < i; j++) {
if (j == i - 1) {
ge_equals_gej(&ng, &r);
}
secp256k1_gej_add_ge(&r, &r, &secp256k1_ge_const_g);
}
CHECK(secp256k1_gej_is_infinity(&r));
}
}
void run_ecmult_constants(void) {
test_ecmult_constants();
}
void test_ecmult_gen_blind(void) {
/* Test ecmult_gen() blinding and confirm that the blinding changes, the affine points match, and the z's don't match. */
secp256k1_scalar key;
secp256k1_scalar b;
unsigned char seed32[32];
secp256k1_gej pgej;
secp256k1_gej pgej2;
secp256k1_gej i;
secp256k1_ge pge;
random_scalar_order_test(&key);
secp256k1_ecmult_gen(&ctx->ecmult_gen_ctx, &pgej, &key);
secp256k1_rand256(seed32);
b = ctx->ecmult_gen_ctx.blind;
i = ctx->ecmult_gen_ctx.initial;
secp256k1_ecmult_gen_blind(&ctx->ecmult_gen_ctx, seed32);
CHECK(!secp256k1_scalar_eq(&b, &ctx->ecmult_gen_ctx.blind));
secp256k1_ecmult_gen(&ctx->ecmult_gen_ctx, &pgej2, &key);
CHECK(!gej_xyz_equals_gej(&pgej, &pgej2));
CHECK(!gej_xyz_equals_gej(&i, &ctx->ecmult_gen_ctx.initial));
secp256k1_ge_set_gej(&pge, &pgej);
ge_equals_gej(&pge, &pgej2);
}
void test_ecmult_gen_blind_reset(void) {
/* Test ecmult_gen() blinding reset and confirm that the blinding is consistent. */
secp256k1_scalar b;
secp256k1_gej initial;
secp256k1_ecmult_gen_blind(&ctx->ecmult_gen_ctx, 0);
b = ctx->ecmult_gen_ctx.blind;
initial = ctx->ecmult_gen_ctx.initial;
secp256k1_ecmult_gen_blind(&ctx->ecmult_gen_ctx, 0);
CHECK(secp256k1_scalar_eq(&b, &ctx->ecmult_gen_ctx.blind));
CHECK(gej_xyz_equals_gej(&initial, &ctx->ecmult_gen_ctx.initial));
}
void run_ecmult_gen_blind(void) {
int i;
test_ecmult_gen_blind_reset();
for (i = 0; i < 10; i++) {
test_ecmult_gen_blind();
}
}
#ifdef USE_ENDOMORPHISM
/***** ENDOMORPHISH TESTS *****/
void test_scalar_split(void) {
secp256k1_scalar full;
secp256k1_scalar s1, slam;
const unsigned char zero[32] = {0};
unsigned char tmp[32];
random_scalar_order_test(&full);
secp256k1_scalar_split_lambda(&s1, &slam, &full);
/* check that both are <= 128 bits in size */
if (secp256k1_scalar_is_high(&s1)) {
secp256k1_scalar_negate(&s1, &s1);
}
if (secp256k1_scalar_is_high(&slam)) {
secp256k1_scalar_negate(&slam, &slam);
}
secp256k1_scalar_get_b32(tmp, &s1);
CHECK(memcmp(zero, tmp, 16) == 0);
secp256k1_scalar_get_b32(tmp, &slam);
CHECK(memcmp(zero, tmp, 16) == 0);
}
void run_endomorphism_tests(void) {
test_scalar_split();
}
#endif
void ec_pubkey_parse_pointtest(const unsigned char *input, int xvalid, int yvalid) {
unsigned char pubkeyc[65];
secp256k1_pubkey pubkey;
secp256k1_ge ge;
size_t pubkeyclen;
int32_t ecount;
ecount = 0;
secp256k1_context_set_illegal_callback(ctx, counting_illegal_callback_fn, &ecount);
for (pubkeyclen = 3; pubkeyclen <= 65; pubkeyclen++) {
/* Smaller sizes are tested exhaustively elsewhere. */
int32_t i;
memcpy(&pubkeyc[1], input, 64);
VG_UNDEF(&pubkeyc[pubkeyclen], 65 - pubkeyclen);
for (i = 0; i < 256; i++) {
/* Try all type bytes. */
int xpass;
int ypass;
int ysign;
pubkeyc[0] = i;
/* What sign does this point have? */
ysign = (input[63] & 1) + 2;
/* For the current type (i) do we expect parsing to work? Handled all of compressed/uncompressed/hybrid. */
xpass = xvalid && (pubkeyclen == 33) && ((i & 254) == 2);
/* Do we expect a parse and re-serialize as uncompressed to give a matching y? */
ypass = xvalid && yvalid && ((i & 4) == ((pubkeyclen == 65) << 2)) &&
((i == 4) || ((i & 251) == ysign)) && ((pubkeyclen == 33) || (pubkeyclen == 65));
if (xpass || ypass) {
/* These cases must parse. */
unsigned char pubkeyo[65];
size_t outl;
memset(&pubkey, 0, sizeof(pubkey));
VG_UNDEF(&pubkey, sizeof(pubkey));
ecount = 0;
CHECK(secp256k1_ec_pubkey_parse(ctx, &pubkey, pubkeyc, pubkeyclen) == 1);
VG_CHECK(&pubkey, sizeof(pubkey));
outl = 65;
VG_UNDEF(pubkeyo, 65);
CHECK(secp256k1_ec_pubkey_serialize(ctx, pubkeyo, &outl, &pubkey, SECP256K1_EC_COMPRESSED) == 1);
VG_CHECK(pubkeyo, outl);
CHECK(outl == 33);
CHECK(memcmp(&pubkeyo[1], &pubkeyc[1], 32) == 0);
CHECK((pubkeyclen != 33) || (pubkeyo[0] == pubkeyc[0]));
if (ypass) {
/* This test isn't always done because we decode with alternative signs, so the y won't match. */
CHECK(pubkeyo[0] == ysign);
CHECK(secp256k1_pubkey_load(ctx, &ge, &pubkey) == 1);
memset(&pubkey, 0, sizeof(pubkey));
VG_UNDEF(&pubkey, sizeof(pubkey));
secp256k1_pubkey_save(&pubkey, &ge);
VG_CHECK(&pubkey, sizeof(pubkey));
outl = 65;
VG_UNDEF(pubkeyo, 65);
CHECK(secp256k1_ec_pubkey_serialize(ctx, pubkeyo, &outl, &pubkey, SECP256K1_EC_UNCOMPRESSED) == 1);
VG_CHECK(pubkeyo, outl);
CHECK(outl == 65);
CHECK(pubkeyo[0] == 4);
CHECK(memcmp(&pubkeyo[1], input, 64) == 0);
}
CHECK(ecount == 0);
} else {
/* These cases must fail to parse. */
memset(&pubkey, 0xfe, sizeof(pubkey));
ecount = 0;
VG_UNDEF(&pubkey, sizeof(pubkey));
CHECK(secp256k1_ec_pubkey_parse(ctx, &pubkey, pubkeyc, pubkeyclen) == 0);
VG_CHECK(&pubkey, sizeof(pubkey));
CHECK(ecount == 0);
CHECK(secp256k1_pubkey_load(ctx, &ge, &pubkey) == 0);
CHECK(ecount == 1);
}
}
}
secp256k1_context_set_illegal_callback(ctx, NULL, NULL);
}
void run_ec_pubkey_parse_test(void) {
#define SECP256K1_EC_PARSE_TEST_NVALID (12)
const unsigned char valid[SECP256K1_EC_PARSE_TEST_NVALID][64] = {
{
/* Point with leading and trailing zeros in x and y serialization. */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x42, 0x52,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x64, 0xef, 0xa1, 0x7b, 0x77, 0x61, 0xe1, 0xe4, 0x27, 0x06, 0x98, 0x9f, 0xb4, 0x83,
0xb8, 0xd2, 0xd4, 0x9b, 0xf7, 0x8f, 0xae, 0x98, 0x03, 0xf0, 0x99, 0xb8, 0x34, 0xed, 0xeb, 0x00
},
{
/* Point with x equal to a 3rd root of unity.*/
0x7a, 0xe9, 0x6a, 0x2b, 0x65, 0x7c, 0x07, 0x10, 0x6e, 0x64, 0x47, 0x9e, 0xac, 0x34, 0x34, 0xe9,
0x9c, 0xf0, 0x49, 0x75, 0x12, 0xf5, 0x89, 0x95, 0xc1, 0x39, 0x6c, 0x28, 0x71, 0x95, 0x01, 0xee,
0x42, 0x18, 0xf2, 0x0a, 0xe6, 0xc6, 0x46, 0xb3, 0x63, 0xdb, 0x68, 0x60, 0x58, 0x22, 0xfb, 0x14,
0x26, 0x4c, 0xa8, 0xd2, 0x58, 0x7f, 0xdd, 0x6f, 0xbc, 0x75, 0x0d, 0x58, 0x7e, 0x76, 0xa7, 0xee,
},
{
/* Point with largest x. (1/2) */
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfe, 0xff, 0xff, 0xfc, 0x2c,
0x0e, 0x99, 0x4b, 0x14, 0xea, 0x72, 0xf8, 0xc3, 0xeb, 0x95, 0xc7, 0x1e, 0xf6, 0x92, 0x57, 0x5e,
0x77, 0x50, 0x58, 0x33, 0x2d, 0x7e, 0x52, 0xd0, 0x99, 0x5c, 0xf8, 0x03, 0x88, 0x71, 0xb6, 0x7d,
},
{
/* Point with largest x. (2/2) */
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfe, 0xff, 0xff, 0xfc, 0x2c,
0xf1, 0x66, 0xb4, 0xeb, 0x15, 0x8d, 0x07, 0x3c, 0x14, 0x6a, 0x38, 0xe1, 0x09, 0x6d, 0xa8, 0xa1,
0x88, 0xaf, 0xa7, 0xcc, 0xd2, 0x81, 0xad, 0x2f, 0x66, 0xa3, 0x07, 0xfb, 0x77, 0x8e, 0x45, 0xb2,
},
{
/* Point with smallest x. (1/2) */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01,
0x42, 0x18, 0xf2, 0x0a, 0xe6, 0xc6, 0x46, 0xb3, 0x63, 0xdb, 0x68, 0x60, 0x58, 0x22, 0xfb, 0x14,
0x26, 0x4c, 0xa8, 0xd2, 0x58, 0x7f, 0xdd, 0x6f, 0xbc, 0x75, 0x0d, 0x58, 0x7e, 0x76, 0xa7, 0xee,
},
{
/* Point with smallest x. (2/2) */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01,
0xbd, 0xe7, 0x0d, 0xf5, 0x19, 0x39, 0xb9, 0x4c, 0x9c, 0x24, 0x97, 0x9f, 0xa7, 0xdd, 0x04, 0xeb,
0xd9, 0xb3, 0x57, 0x2d, 0xa7, 0x80, 0x22, 0x90, 0x43, 0x8a, 0xf2, 0xa6, 0x81, 0x89, 0x54, 0x41,
},
{
/* Point with largest y. (1/3) */
0x1f, 0xe1, 0xe5, 0xef, 0x3f, 0xce, 0xb5, 0xc1, 0x35, 0xab, 0x77, 0x41, 0x33, 0x3c, 0xe5, 0xa6,
0xe8, 0x0d, 0x68, 0x16, 0x76, 0x53, 0xf6, 0xb2, 0xb2, 0x4b, 0xcb, 0xcf, 0xaa, 0xaf, 0xf5, 0x07,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfe, 0xff, 0xff, 0xfc, 0x2e,
},
{
/* Point with largest y. (2/3) */
0xcb, 0xb0, 0xde, 0xab, 0x12, 0x57, 0x54, 0xf1, 0xfd, 0xb2, 0x03, 0x8b, 0x04, 0x34, 0xed, 0x9c,
0xb3, 0xfb, 0x53, 0xab, 0x73, 0x53, 0x91, 0x12, 0x99, 0x94, 0xa5, 0x35, 0xd9, 0x25, 0xf6, 0x73,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfe, 0xff, 0xff, 0xfc, 0x2e,
},
{
/* Point with largest y. (3/3) */
0x14, 0x6d, 0x3b, 0x65, 0xad, 0xd9, 0xf5, 0x4c, 0xcc, 0xa2, 0x85, 0x33, 0xc8, 0x8e, 0x2c, 0xbc,
0x63, 0xf7, 0x44, 0x3e, 0x16, 0x58, 0x78, 0x3a, 0xb4, 0x1f, 0x8e, 0xf9, 0x7c, 0x2a, 0x10, 0xb5,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfe, 0xff, 0xff, 0xfc, 0x2e,
},
{
/* Point with smallest y. (1/3) */
0x1f, 0xe1, 0xe5, 0xef, 0x3f, 0xce, 0xb5, 0xc1, 0x35, 0xab, 0x77, 0x41, 0x33, 0x3c, 0xe5, 0xa6,
0xe8, 0x0d, 0x68, 0x16, 0x76, 0x53, 0xf6, 0xb2, 0xb2, 0x4b, 0xcb, 0xcf, 0xaa, 0xaf, 0xf5, 0x07,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01,
},
{
/* Point with smallest y. (2/3) */
0xcb, 0xb0, 0xde, 0xab, 0x12, 0x57, 0x54, 0xf1, 0xfd, 0xb2, 0x03, 0x8b, 0x04, 0x34, 0xed, 0x9c,
0xb3, 0xfb, 0x53, 0xab, 0x73, 0x53, 0x91, 0x12, 0x99, 0x94, 0xa5, 0x35, 0xd9, 0x25, 0xf6, 0x73,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01,
},
{
/* Point with smallest y. (3/3) */
0x14, 0x6d, 0x3b, 0x65, 0xad, 0xd9, 0xf5, 0x4c, 0xcc, 0xa2, 0x85, 0x33, 0xc8, 0x8e, 0x2c, 0xbc,
0x63, 0xf7, 0x44, 0x3e, 0x16, 0x58, 0x78, 0x3a, 0xb4, 0x1f, 0x8e, 0xf9, 0x7c, 0x2a, 0x10, 0xb5,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01
}
};
#define SECP256K1_EC_PARSE_TEST_NXVALID (4)
const unsigned char onlyxvalid[SECP256K1_EC_PARSE_TEST_NXVALID][64] = {
{
/* Valid if y overflow ignored (y = 1 mod p). (1/3) */
0x1f, 0xe1, 0xe5, 0xef, 0x3f, 0xce, 0xb5, 0xc1, 0x35, 0xab, 0x77, 0x41, 0x33, 0x3c, 0xe5, 0xa6,
0xe8, 0x0d, 0x68, 0x16, 0x76, 0x53, 0xf6, 0xb2, 0xb2, 0x4b, 0xcb, 0xcf, 0xaa, 0xaf, 0xf5, 0x07,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfe, 0xff, 0xff, 0xfc, 0x30,
},
{
/* Valid if y overflow ignored (y = 1 mod p). (2/3) */
0xcb, 0xb0, 0xde, 0xab, 0x12, 0x57, 0x54, 0xf1, 0xfd, 0xb2, 0x03, 0x8b, 0x04, 0x34, 0xed, 0x9c,
0xb3, 0xfb, 0x53, 0xab, 0x73, 0x53, 0x91, 0x12, 0x99, 0x94, 0xa5, 0x35, 0xd9, 0x25, 0xf6, 0x73,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfe, 0xff, 0xff, 0xfc, 0x30,
},
{
/* Valid if y overflow ignored (y = 1 mod p). (3/3)*/
0x14, 0x6d, 0x3b, 0x65, 0xad, 0xd9, 0xf5, 0x4c, 0xcc, 0xa2, 0x85, 0x33, 0xc8, 0x8e, 0x2c, 0xbc,
0x63, 0xf7, 0x44, 0x3e, 0x16, 0x58, 0x78, 0x3a, 0xb4, 0x1f, 0x8e, 0xf9, 0x7c, 0x2a, 0x10, 0xb5,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfe, 0xff, 0xff, 0xfc, 0x30,
},
{
/* x on curve, y is from y^2 = x^3 + 8. */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03
}
};
#define SECP256K1_EC_PARSE_TEST_NINVALID (7)
const unsigned char invalid[SECP256K1_EC_PARSE_TEST_NINVALID][64] = {
{
/* x is third root of -8, y is -1 * (x^3+7); also on the curve for y^2 = x^3 + 9. */
0x0a, 0x2d, 0x2b, 0xa9, 0x35, 0x07, 0xf1, 0xdf, 0x23, 0x37, 0x70, 0xc2, 0xa7, 0x97, 0x96, 0x2c,
0xc6, 0x1f, 0x6d, 0x15, 0xda, 0x14, 0xec, 0xd4, 0x7d, 0x8d, 0x27, 0xae, 0x1c, 0xd5, 0xf8, 0x53,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01,
},
{
/* Valid if x overflow ignored (x = 1 mod p). */
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfe, 0xff, 0xff, 0xfc, 0x30,
0x42, 0x18, 0xf2, 0x0a, 0xe6, 0xc6, 0x46, 0xb3, 0x63, 0xdb, 0x68, 0x60, 0x58, 0x22, 0xfb, 0x14,
0x26, 0x4c, 0xa8, 0xd2, 0x58, 0x7f, 0xdd, 0x6f, 0xbc, 0x75, 0x0d, 0x58, 0x7e, 0x76, 0xa7, 0xee,
},
{
/* Valid if x overflow ignored (x = 1 mod p). */
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfe, 0xff, 0xff, 0xfc, 0x30,
0xbd, 0xe7, 0x0d, 0xf5, 0x19, 0x39, 0xb9, 0x4c, 0x9c, 0x24, 0x97, 0x9f, 0xa7, 0xdd, 0x04, 0xeb,
0xd9, 0xb3, 0x57, 0x2d, 0xa7, 0x80, 0x22, 0x90, 0x43, 0x8a, 0xf2, 0xa6, 0x81, 0x89, 0x54, 0x41,
},
{
/* x is -1, y is the result of the sqrt ladder; also on the curve for y^2 = x^3 - 5. */
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfe, 0xff, 0xff, 0xfc, 0x2e,
0xf4, 0x84, 0x14, 0x5c, 0xb0, 0x14, 0x9b, 0x82, 0x5d, 0xff, 0x41, 0x2f, 0xa0, 0x52, 0xa8, 0x3f,
0xcb, 0x72, 0xdb, 0x61, 0xd5, 0x6f, 0x37, 0x70, 0xce, 0x06, 0x6b, 0x73, 0x49, 0xa2, 0xaa, 0x28,
},
{
/* x is -1, y is the result of the sqrt ladder; also on the curve for y^2 = x^3 - 5. */
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfe, 0xff, 0xff, 0xfc, 0x2e,
0x0b, 0x7b, 0xeb, 0xa3, 0x4f, 0xeb, 0x64, 0x7d, 0xa2, 0x00, 0xbe, 0xd0, 0x5f, 0xad, 0x57, 0xc0,
0x34, 0x8d, 0x24, 0x9e, 0x2a, 0x90, 0xc8, 0x8f, 0x31, 0xf9, 0x94, 0x8b, 0xb6, 0x5d, 0x52, 0x07,
},
{
/* x is zero, y is the result of the sqrt ladder; also on the curve for y^2 = x^3 - 7. */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x8f, 0x53, 0x7e, 0xef, 0xdf, 0xc1, 0x60, 0x6a, 0x07, 0x27, 0xcd, 0x69, 0xb4, 0xa7, 0x33, 0x3d,
0x38, 0xed, 0x44, 0xe3, 0x93, 0x2a, 0x71, 0x79, 0xee, 0xcb, 0x4b, 0x6f, 0xba, 0x93, 0x60, 0xdc,
},
{
/* x is zero, y is the result of the sqrt ladder; also on the curve for y^2 = x^3 - 7. */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x70, 0xac, 0x81, 0x10, 0x20, 0x3e, 0x9f, 0x95, 0xf8, 0xd8, 0x32, 0x96, 0x4b, 0x58, 0xcc, 0xc2,
0xc7, 0x12, 0xbb, 0x1c, 0x6c, 0xd5, 0x8e, 0x86, 0x11, 0x34, 0xb4, 0x8f, 0x45, 0x6c, 0x9b, 0x53
}
};
const unsigned char pubkeyc[66] = {
/* Serialization of G. */
0x04, 0x79, 0xBE, 0x66, 0x7E, 0xF9, 0xDC, 0xBB, 0xAC, 0x55, 0xA0, 0x62, 0x95, 0xCE, 0x87, 0x0B,
0x07, 0x02, 0x9B, 0xFC, 0xDB, 0x2D, 0xCE, 0x28, 0xD9, 0x59, 0xF2, 0x81, 0x5B, 0x16, 0xF8, 0x17,
0x98, 0x48, 0x3A, 0xDA, 0x77, 0x26, 0xA3, 0xC4, 0x65, 0x5D, 0xA4, 0xFB, 0xFC, 0x0E, 0x11, 0x08,
0xA8, 0xFD, 0x17, 0xB4, 0x48, 0xA6, 0x85, 0x54, 0x19, 0x9C, 0x47, 0xD0, 0x8F, 0xFB, 0x10, 0xD4,
0xB8, 0x00
};
unsigned char sout[65];
unsigned char shortkey[2];
secp256k1_ge ge;
secp256k1_pubkey pubkey;
size_t len;
int32_t i;
int32_t ecount;
int32_t ecount2;
ecount = 0;
/* Nothing should be reading this far into pubkeyc. */
VG_UNDEF(&pubkeyc[65], 1);
secp256k1_context_set_illegal_callback(ctx, counting_illegal_callback_fn, &ecount);
/* Zero length claimed, fail, zeroize, no illegal arg error. */
memset(&pubkey, 0xfe, sizeof(pubkey));
ecount = 0;
VG_UNDEF(shortkey, 2);
VG_UNDEF(&pubkey, sizeof(pubkey));
CHECK(secp256k1_ec_pubkey_parse(ctx, &pubkey, shortkey, 0) == 0);
VG_CHECK(&pubkey, sizeof(pubkey));
CHECK(ecount == 0);
CHECK(secp256k1_pubkey_load(ctx, &ge, &pubkey) == 0);
CHECK(ecount == 1);
/* Length one claimed, fail, zeroize, no illegal arg error. */
for (i = 0; i < 256 ; i++) {
memset(&pubkey, 0xfe, sizeof(pubkey));
ecount = 0;
shortkey[0] = i;
VG_UNDEF(&shortkey[1], 1);
VG_UNDEF(&pubkey, sizeof(pubkey));
CHECK(secp256k1_ec_pubkey_parse(ctx, &pubkey, shortkey, 1) == 0);
VG_CHECK(&pubkey, sizeof(pubkey));
CHECK(ecount == 0);
CHECK(secp256k1_pubkey_load(ctx, &ge, &pubkey) == 0);
CHECK(ecount == 1);
}
/* Length two claimed, fail, zeroize, no illegal arg error. */
for (i = 0; i < 65536 ; i++) {
memset(&pubkey, 0xfe, sizeof(pubkey));
ecount = 0;
shortkey[0] = i & 255;
shortkey[1] = i >> 8;
VG_UNDEF(&pubkey, sizeof(pubkey));
CHECK(secp256k1_ec_pubkey_parse(ctx, &pubkey, shortkey, 2) == 0);
VG_CHECK(&pubkey, sizeof(pubkey));
CHECK(ecount == 0);
CHECK(secp256k1_pubkey_load(ctx, &ge, &pubkey) == 0);
CHECK(ecount == 1);
}
memset(&pubkey, 0xfe, sizeof(pubkey));
ecount = 0;
VG_UNDEF(&pubkey, sizeof(pubkey));
/* 33 bytes claimed on otherwise valid input starting with 0x04, fail, zeroize output, no illegal arg error. */
CHECK(secp256k1_ec_pubkey_parse(ctx, &pubkey, pubkeyc, 33) == 0);
VG_CHECK(&pubkey, sizeof(pubkey));
CHECK(ecount == 0);
CHECK(secp256k1_pubkey_load(ctx, &ge, &pubkey) == 0);
CHECK(ecount == 1);
/* NULL pubkey, illegal arg error. Pubkey isn't rewritten before this step, since it's NULL into the parser. */
CHECK(secp256k1_ec_pubkey_parse(ctx, NULL, pubkeyc, 65) == 0);
CHECK(ecount == 2);
/* NULL input string. Illegal arg and zeroize output. */
memset(&pubkey, 0xfe, sizeof(pubkey));
ecount = 0;
VG_UNDEF(&pubkey, sizeof(pubkey));
CHECK(secp256k1_ec_pubkey_parse(ctx, &pubkey, NULL, 65) == 0);
VG_CHECK(&pubkey, sizeof(pubkey));
CHECK(ecount == 1);
CHECK(secp256k1_pubkey_load(ctx, &ge, &pubkey) == 0);
CHECK(ecount == 2);
/* 64 bytes claimed on input starting with 0x04, fail, zeroize output, no illegal arg error. */
memset(&pubkey, 0xfe, sizeof(pubkey));
ecount = 0;
VG_UNDEF(&pubkey, sizeof(pubkey));
CHECK(secp256k1_ec_pubkey_parse(ctx, &pubkey, pubkeyc, 64) == 0);
VG_CHECK(&pubkey, sizeof(pubkey));
CHECK(ecount == 0);
CHECK(secp256k1_pubkey_load(ctx, &ge, &pubkey) == 0);
CHECK(ecount == 1);
/* 66 bytes claimed, fail, zeroize output, no illegal arg error. */
memset(&pubkey, 0xfe, sizeof(pubkey));
ecount = 0;
VG_UNDEF(&pubkey, sizeof(pubkey));
CHECK(secp256k1_ec_pubkey_parse(ctx, &pubkey, pubkeyc, 66) == 0);
VG_CHECK(&pubkey, sizeof(pubkey));
CHECK(ecount == 0);
CHECK(secp256k1_pubkey_load(ctx, &ge, &pubkey) == 0);
CHECK(ecount == 1);
/* Valid parse. */
memset(&pubkey, 0, sizeof(pubkey));
ecount = 0;
VG_UNDEF(&pubkey, sizeof(pubkey));
CHECK(secp256k1_ec_pubkey_parse(ctx, &pubkey, pubkeyc, 65) == 1);
VG_CHECK(&pubkey, sizeof(pubkey));
CHECK(ecount == 0);
VG_UNDEF(&ge, sizeof(ge));
CHECK(secp256k1_pubkey_load(ctx, &ge, &pubkey) == 1);
VG_CHECK(&ge.x, sizeof(ge.x));
VG_CHECK(&ge.y, sizeof(ge.y));
VG_CHECK(&ge.infinity, sizeof(ge.infinity));
ge_equals_ge(&secp256k1_ge_const_g, &ge);
CHECK(ecount == 0);
/* secp256k1_ec_pubkey_serialize illegal args. */
ecount = 0;
len = 65;
CHECK(secp256k1_ec_pubkey_serialize(ctx, NULL, &len, &pubkey, SECP256K1_EC_UNCOMPRESSED) == 0);
CHECK(ecount == 1);
CHECK(len == 0);
CHECK(secp256k1_ec_pubkey_serialize(ctx, sout, NULL, &pubkey, SECP256K1_EC_UNCOMPRESSED) == 0);
CHECK(ecount == 2);
len = 65;
VG_UNDEF(sout, 65);
CHECK(secp256k1_ec_pubkey_serialize(ctx, sout, &len, NULL, SECP256K1_EC_UNCOMPRESSED) == 0);
VG_CHECK(sout, 65);
CHECK(ecount == 3);
CHECK(len == 0);
len = 65;
CHECK(secp256k1_ec_pubkey_serialize(ctx, sout, &len, &pubkey, ~0) == 0);
CHECK(ecount == 4);
CHECK(len == 0);
len = 65;
VG_UNDEF(sout, 65);
CHECK(secp256k1_ec_pubkey_serialize(ctx, sout, &len, &pubkey, SECP256K1_EC_UNCOMPRESSED) == 1);
VG_CHECK(sout, 65);
CHECK(ecount == 4);
CHECK(len == 65);
/* Multiple illegal args. Should still set arg error only once. */
ecount = 0;
ecount2 = 11;
CHECK(secp256k1_ec_pubkey_parse(ctx, NULL, NULL, 65) == 0);
CHECK(ecount == 1);
/* Does the illegal arg callback actually change the behavior? */
secp256k1_context_set_illegal_callback(ctx, uncounting_illegal_callback_fn, &ecount2);
CHECK(secp256k1_ec_pubkey_parse(ctx, NULL, NULL, 65) == 0);
CHECK(ecount == 1);
CHECK(ecount2 == 10);
secp256k1_context_set_illegal_callback(ctx, NULL, NULL);
/* Try a bunch of prefabbed points with all possible encodings. */
for (i = 0; i < SECP256K1_EC_PARSE_TEST_NVALID; i++) {
ec_pubkey_parse_pointtest(valid[i], 1, 1);
}
for (i = 0; i < SECP256K1_EC_PARSE_TEST_NXVALID; i++) {
ec_pubkey_parse_pointtest(onlyxvalid[i], 1, 0);
}
for (i = 0; i < SECP256K1_EC_PARSE_TEST_NINVALID; i++) {
ec_pubkey_parse_pointtest(invalid[i], 0, 0);
}
}
void run_eckey_edge_case_test(void) {
const unsigned char orderc[32] = {
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfe,
0xba, 0xae, 0xdc, 0xe6, 0xaf, 0x48, 0xa0, 0x3b,
0xbf, 0xd2, 0x5e, 0x8c, 0xd0, 0x36, 0x41, 0x41
};
const unsigned char zeros[sizeof(secp256k1_pubkey)] = {0x00};
unsigned char ctmp[33];
unsigned char ctmp2[33];
secp256k1_pubkey pubkey;
secp256k1_pubkey pubkey2;
secp256k1_pubkey pubkey_one;
secp256k1_pubkey pubkey_negone;
const secp256k1_pubkey *pubkeys[3];
size_t len;
int32_t ecount;
/* Group order is too large, reject. */
CHECK(secp256k1_ec_seckey_verify(ctx, orderc) == 0);
VG_UNDEF(&pubkey, sizeof(pubkey));
CHECK(secp256k1_ec_pubkey_create(ctx, &pubkey, orderc) == 0);
VG_CHECK(&pubkey, sizeof(pubkey));
CHECK(memcmp(&pubkey, zeros, sizeof(secp256k1_pubkey)) == 0);
/* Maximum value is too large, reject. */
memset(ctmp, 255, 32);
CHECK(secp256k1_ec_seckey_verify(ctx, ctmp) == 0);
memset(&pubkey, 1, sizeof(pubkey));
VG_UNDEF(&pubkey, sizeof(pubkey));
CHECK(secp256k1_ec_pubkey_create(ctx, &pubkey, ctmp) == 0);
VG_CHECK(&pubkey, sizeof(pubkey));
CHECK(memcmp(&pubkey, zeros, sizeof(secp256k1_pubkey)) == 0);
/* Zero is too small, reject. */
memset(ctmp, 0, 32);
CHECK(secp256k1_ec_seckey_verify(ctx, ctmp) == 0);
memset(&pubkey, 1, sizeof(pubkey));
VG_UNDEF(&pubkey, sizeof(pubkey));
CHECK(secp256k1_ec_pubkey_create(ctx, &pubkey, ctmp) == 0);
VG_CHECK(&pubkey, sizeof(pubkey));
CHECK(memcmp(&pubkey, zeros, sizeof(secp256k1_pubkey)) == 0);
/* One must be accepted. */
ctmp[31] = 0x01;
CHECK(secp256k1_ec_seckey_verify(ctx, ctmp) == 1);
memset(&pubkey, 0, sizeof(pubkey));
VG_UNDEF(&pubkey, sizeof(pubkey));
CHECK(secp256k1_ec_pubkey_create(ctx, &pubkey, ctmp) == 1);
VG_CHECK(&pubkey, sizeof(pubkey));
CHECK(memcmp(&pubkey, zeros, sizeof(secp256k1_pubkey)) > 0);
pubkey_one = pubkey;
/* Group order + 1 is too large, reject. */
memcpy(ctmp, orderc, 32);
ctmp[31] = 0x42;
CHECK(secp256k1_ec_seckey_verify(ctx, ctmp) == 0);
memset(&pubkey, 1, sizeof(pubkey));
VG_UNDEF(&pubkey, sizeof(pubkey));
CHECK(secp256k1_ec_pubkey_create(ctx, &pubkey, ctmp) == 0);
VG_CHECK(&pubkey, sizeof(pubkey));
CHECK(memcmp(&pubkey, zeros, sizeof(secp256k1_pubkey)) == 0);
/* -1 must be accepted. */
ctmp[31] = 0x40;
CHECK(secp256k1_ec_seckey_verify(ctx, ctmp) == 1);
memset(&pubkey, 0, sizeof(pubkey));
VG_UNDEF(&pubkey, sizeof(pubkey));
CHECK(secp256k1_ec_pubkey_create(ctx, &pubkey, ctmp) == 1);
VG_CHECK(&pubkey, sizeof(pubkey));
CHECK(memcmp(&pubkey, zeros, sizeof(secp256k1_pubkey)) > 0);
pubkey_negone = pubkey;
/* Tweak of zero leaves the value unchanged. */
memset(ctmp2, 0, 32);
CHECK(secp256k1_ec_privkey_tweak_add(ctx, ctmp, ctmp2) == 1);
CHECK(memcmp(orderc, ctmp, 31) == 0 && ctmp[31] == 0x40);
memcpy(&pubkey2, &pubkey, sizeof(pubkey));
CHECK(secp256k1_ec_pubkey_tweak_add(ctx, &pubkey, ctmp2) == 1);
CHECK(memcmp(&pubkey, &pubkey2, sizeof(pubkey)) == 0);
/* Multiply tweak of zero zeroizes the output. */
CHECK(secp256k1_ec_privkey_tweak_mul(ctx, ctmp, ctmp2) == 0);
CHECK(memcmp(zeros, ctmp, 32) == 0);
CHECK(secp256k1_ec_pubkey_tweak_mul(ctx, &pubkey, ctmp2) == 0);
CHECK(memcmp(&pubkey, zeros, sizeof(pubkey)) == 0);
memcpy(&pubkey, &pubkey2, sizeof(pubkey));
/* Overflowing key tweak zeroizes. */
memcpy(ctmp, orderc, 32);
ctmp[31] = 0x40;
CHECK(secp256k1_ec_privkey_tweak_add(ctx, ctmp, orderc) == 0);
CHECK(memcmp(zeros, ctmp, 32) == 0);
memcpy(ctmp, orderc, 32);
ctmp[31] = 0x40;
CHECK(secp256k1_ec_privkey_tweak_mul(ctx, ctmp, orderc) == 0);
CHECK(memcmp(zeros, ctmp, 32) == 0);
memcpy(ctmp, orderc, 32);
ctmp[31] = 0x40;
CHECK(secp256k1_ec_pubkey_tweak_add(ctx, &pubkey, orderc) == 0);
CHECK(memcmp(&pubkey, zeros, sizeof(pubkey)) == 0);
memcpy(&pubkey, &pubkey2, sizeof(pubkey));
CHECK(secp256k1_ec_pubkey_tweak_mul(ctx, &pubkey, orderc) == 0);
CHECK(memcmp(&pubkey, zeros, sizeof(pubkey)) == 0);
memcpy(&pubkey, &pubkey2, sizeof(pubkey));
/* Private key tweaks results in a key of zero. */
ctmp2[31] = 1;
CHECK(secp256k1_ec_privkey_tweak_add(ctx, ctmp2, ctmp) == 0);
CHECK(memcmp(zeros, ctmp2, 32) == 0);
ctmp2[31] = 1;
CHECK(secp256k1_ec_pubkey_tweak_add(ctx, &pubkey, ctmp2) == 0);
CHECK(memcmp(&pubkey, zeros, sizeof(pubkey)) == 0);
memcpy(&pubkey, &pubkey2, sizeof(pubkey));
/* Tweak computation wraps and results in a key of 1. */
ctmp2[31] = 2;
CHECK(secp256k1_ec_privkey_tweak_add(ctx, ctmp2, ctmp) == 1);
CHECK(memcmp(ctmp2, zeros, 31) == 0 && ctmp2[31] == 1);
ctmp2[31] = 2;
CHECK(secp256k1_ec_pubkey_tweak_add(ctx, &pubkey, ctmp2) == 1);
ctmp2[31] = 1;
CHECK(secp256k1_ec_pubkey_create(ctx, &pubkey2, ctmp2) == 1);
CHECK(memcmp(&pubkey, &pubkey2, sizeof(pubkey)) == 0);
/* Tweak mul * 2 = 1+1. */
CHECK(secp256k1_ec_pubkey_tweak_add(ctx, &pubkey, ctmp2) == 1);
ctmp2[31] = 2;
CHECK(secp256k1_ec_pubkey_tweak_mul(ctx, &pubkey2, ctmp2) == 1);
CHECK(memcmp(&pubkey, &pubkey2, sizeof(pubkey)) == 0);
/* Test argument errors. */
ecount = 0;
secp256k1_context_set_illegal_callback(ctx, counting_illegal_callback_fn, &ecount);
CHECK(ecount == 0);
/* Zeroize pubkey on parse error. */
memset(&pubkey, 0, 32);
CHECK(secp256k1_ec_pubkey_tweak_add(ctx, &pubkey, ctmp2) == 0);
CHECK(ecount == 1);
CHECK(memcmp(&pubkey, zeros, sizeof(pubkey)) == 0);
memcpy(&pubkey, &pubkey2, sizeof(pubkey));
memset(&pubkey2, 0, 32);
CHECK(secp256k1_ec_pubkey_tweak_mul(ctx, &pubkey2, ctmp2) == 0);
CHECK(ecount == 2);
CHECK(memcmp(&pubkey2, zeros, sizeof(pubkey2)) == 0);
/* Plain argument errors. */
ecount = 0;
CHECK(secp256k1_ec_seckey_verify(ctx, ctmp) == 1);
CHECK(ecount == 0);
CHECK(secp256k1_ec_seckey_verify(ctx, NULL) == 0);
CHECK(ecount == 1);
ecount = 0;
memset(ctmp2, 0, 32);
ctmp2[31] = 4;
CHECK(secp256k1_ec_pubkey_tweak_add(ctx, NULL, ctmp2) == 0);
CHECK(ecount == 1);
CHECK(secp256k1_ec_pubkey_tweak_add(ctx, &pubkey, NULL) == 0);
CHECK(ecount == 2);
ecount = 0;
memset(ctmp2, 0, 32);
ctmp2[31] = 4;
CHECK(secp256k1_ec_pubkey_tweak_mul(ctx, NULL, ctmp2) == 0);
CHECK(ecount == 1);
CHECK(secp256k1_ec_pubkey_tweak_mul(ctx, &pubkey, NULL) == 0);
CHECK(ecount == 2);
ecount = 0;
memset(ctmp2, 0, 32);
CHECK(secp256k1_ec_privkey_tweak_add(ctx, NULL, ctmp2) == 0);
CHECK(ecount == 1);
CHECK(secp256k1_ec_privkey_tweak_add(ctx, ctmp, NULL) == 0);
CHECK(ecount == 2);
ecount = 0;
memset(ctmp2, 0, 32);
ctmp2[31] = 1;
CHECK(secp256k1_ec_privkey_tweak_mul(ctx, NULL, ctmp2) == 0);
CHECK(ecount == 1);
CHECK(secp256k1_ec_privkey_tweak_mul(ctx, ctmp, NULL) == 0);
CHECK(ecount == 2);
ecount = 0;
CHECK(secp256k1_ec_pubkey_create(ctx, NULL, ctmp) == 0);
CHECK(ecount == 1);
memset(&pubkey, 1, sizeof(pubkey));
CHECK(secp256k1_ec_pubkey_create(ctx, &pubkey, NULL) == 0);
CHECK(ecount == 2);
CHECK(memcmp(&pubkey, zeros, sizeof(secp256k1_pubkey)) == 0);
/* secp256k1_ec_pubkey_combine tests. */
ecount = 0;
pubkeys[0] = &pubkey_one;
VG_UNDEF(&pubkeys[0], sizeof(secp256k1_pubkey *));
VG_UNDEF(&pubkeys[1], sizeof(secp256k1_pubkey *));
VG_UNDEF(&pubkeys[2], sizeof(secp256k1_pubkey *));
memset(&pubkey, 255, sizeof(secp256k1_pubkey));
VG_UNDEF(&pubkey, sizeof(secp256k1_pubkey));
CHECK(secp256k1_ec_pubkey_combine(ctx, &pubkey, pubkeys, 0) == 0);
VG_CHECK(&pubkey, sizeof(secp256k1_pubkey));
CHECK(memcmp(&pubkey, zeros, sizeof(secp256k1_pubkey)) == 0);
CHECK(ecount == 1);
CHECK(secp256k1_ec_pubkey_combine(ctx, NULL, pubkeys, 1) == 0);
CHECK(memcmp(&pubkey, zeros, sizeof(secp256k1_pubkey)) == 0);
CHECK(ecount == 2);
memset(&pubkey, 255, sizeof(secp256k1_pubkey));
VG_UNDEF(&pubkey, sizeof(secp256k1_pubkey));
CHECK(secp256k1_ec_pubkey_combine(ctx, &pubkey, NULL, 1) == 0);
VG_CHECK(&pubkey, sizeof(secp256k1_pubkey));
CHECK(memcmp(&pubkey, zeros, sizeof(secp256k1_pubkey)) == 0);
CHECK(ecount == 3);
pubkeys[0] = &pubkey_negone;
memset(&pubkey, 255, sizeof(secp256k1_pubkey));
VG_UNDEF(&pubkey, sizeof(secp256k1_pubkey));
CHECK(secp256k1_ec_pubkey_combine(ctx, &pubkey, pubkeys, 1) == 1);
VG_CHECK(&pubkey, sizeof(secp256k1_pubkey));
CHECK(memcmp(&pubkey, zeros, sizeof(secp256k1_pubkey)) > 0);
CHECK(ecount == 3);
len = 33;
CHECK(secp256k1_ec_pubkey_serialize(ctx, ctmp, &len, &pubkey, SECP256K1_EC_COMPRESSED) == 1);
CHECK(secp256k1_ec_pubkey_serialize(ctx, ctmp2, &len, &pubkey_negone, SECP256K1_EC_COMPRESSED) == 1);
CHECK(memcmp(ctmp, ctmp2, 33) == 0);
/* Result is infinity. */
pubkeys[0] = &pubkey_one;
pubkeys[1] = &pubkey_negone;
memset(&pubkey, 255, sizeof(secp256k1_pubkey));
VG_UNDEF(&pubkey, sizeof(secp256k1_pubkey));
CHECK(secp256k1_ec_pubkey_combine(ctx, &pubkey, pubkeys, 2) == 0);
VG_CHECK(&pubkey, sizeof(secp256k1_pubkey));
CHECK(memcmp(&pubkey, zeros, sizeof(secp256k1_pubkey)) == 0);
CHECK(ecount == 3);
/* Passes through infinity but comes out one. */
pubkeys[2] = &pubkey_one;
memset(&pubkey, 255, sizeof(secp256k1_pubkey));
VG_UNDEF(&pubkey, sizeof(secp256k1_pubkey));
CHECK(secp256k1_ec_pubkey_combine(ctx, &pubkey, pubkeys, 3) == 1);
VG_CHECK(&pubkey, sizeof(secp256k1_pubkey));
CHECK(memcmp(&pubkey, zeros, sizeof(secp256k1_pubkey)) > 0);
CHECK(ecount == 3);
len = 33;
CHECK(secp256k1_ec_pubkey_serialize(ctx, ctmp, &len, &pubkey, SECP256K1_EC_COMPRESSED) == 1);
CHECK(secp256k1_ec_pubkey_serialize(ctx, ctmp2, &len, &pubkey_one, SECP256K1_EC_COMPRESSED) == 1);
CHECK(memcmp(ctmp, ctmp2, 33) == 0);
/* Adds to two. */
pubkeys[1] = &pubkey_one;
memset(&pubkey, 255, sizeof(secp256k1_pubkey));
VG_UNDEF(&pubkey, sizeof(secp256k1_pubkey));
CHECK(secp256k1_ec_pubkey_combine(ctx, &pubkey, pubkeys, 2) == 1);
VG_CHECK(&pubkey, sizeof(secp256k1_pubkey));
CHECK(memcmp(&pubkey, zeros, sizeof(secp256k1_pubkey)) > 0);
CHECK(ecount == 3);
secp256k1_context_set_illegal_callback(ctx, NULL, NULL);
}
void random_sign(secp256k1_scalar *sigr, secp256k1_scalar *sigs, const secp256k1_scalar *key, const secp256k1_scalar *msg, int *recid) {
secp256k1_scalar nonce;
do {
random_scalar_order_test(&nonce);
} while(!secp256k1_ecdsa_sig_sign(&ctx->ecmult_gen_ctx, sigr, sigs, key, msg, &nonce, recid));
}
void test_ecdsa_sign_verify(void) {
secp256k1_gej pubj;
secp256k1_ge pub;
secp256k1_scalar one;
secp256k1_scalar msg, key;
secp256k1_scalar sigr, sigs;
int recid;
int getrec;
random_scalar_order_test(&msg);
random_scalar_order_test(&key);
secp256k1_ecmult_gen(&ctx->ecmult_gen_ctx, &pubj, &key);
secp256k1_ge_set_gej(&pub, &pubj);
getrec = secp256k1_rand_bits(1);
random_sign(&sigr, &sigs, &key, &msg, getrec?&recid:NULL);
if (getrec) {
CHECK(recid >= 0 && recid < 4);
}
CHECK(secp256k1_ecdsa_sig_verify(&ctx->ecmult_ctx, &sigr, &sigs, &pub, &msg));
secp256k1_scalar_set_int(&one, 1);
secp256k1_scalar_add(&msg, &msg, &one);
CHECK(!secp256k1_ecdsa_sig_verify(&ctx->ecmult_ctx, &sigr, &sigs, &pub, &msg));
}
void run_ecdsa_sign_verify(void) {
int i;
for (i = 0; i < 10*count; i++) {
test_ecdsa_sign_verify();
}
}
/** Dummy nonce generation function that just uses a precomputed nonce, and fails if it is not accepted. Use only for testing. */
static int precomputed_nonce_function(unsigned char *nonce32, const unsigned char *msg32, const unsigned char *key32, const unsigned char *algo16, void *data, unsigned int counter) {
(void)msg32;
(void)key32;
(void)algo16;
memcpy(nonce32, data, 32);
return (counter == 0);
}
static int nonce_function_test_fail(unsigned char *nonce32, const unsigned char *msg32, const unsigned char *key32, const unsigned char *algo16, void *data, unsigned int counter) {
/* Dummy nonce generator that has a fatal error on the first counter value. */
if (counter == 0) {
return 0;
}
return nonce_function_rfc6979(nonce32, msg32, key32, algo16, data, counter - 1);
}
static int nonce_function_test_retry(unsigned char *nonce32, const unsigned char *msg32, const unsigned char *key32, const unsigned char *algo16, void *data, unsigned int counter) {
/* Dummy nonce generator that produces unacceptable nonces for the first several counter values. */
if (counter < 3) {
memset(nonce32, counter==0 ? 0 : 255, 32);
if (counter == 2) {
nonce32[31]--;
}
return 1;
}
if (counter < 5) {
static const unsigned char order[] = {
0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFE,
0xBA,0xAE,0xDC,0xE6,0xAF,0x48,0xA0,0x3B,
0xBF,0xD2,0x5E,0x8C,0xD0,0x36,0x41,0x41
};
memcpy(nonce32, order, 32);
if (counter == 4) {
nonce32[31]++;
}
return 1;
}
/* Retry rate of 6979 is negligible esp. as we only call this in deterministic tests. */
/* If someone does fine a case where it retries for secp256k1, we'd like to know. */
if (counter > 5) {
return 0;
}
return nonce_function_rfc6979(nonce32, msg32, key32, algo16, data, counter - 5);
}
int is_empty_signature(const secp256k1_ecdsa_signature *sig) {
static const unsigned char res[sizeof(secp256k1_ecdsa_signature)] = {0};
return memcmp(sig, res, sizeof(secp256k1_ecdsa_signature)) == 0;
}
void test_ecdsa_end_to_end(void) {
unsigned char extra[32] = {0x00};
unsigned char privkey[32];
unsigned char message[32];
unsigned char privkey2[32];
secp256k1_ecdsa_signature signature[6];
secp256k1_scalar r, s;
unsigned char sig[74];
size_t siglen = 74;
unsigned char pubkeyc[65];
size_t pubkeyclen = 65;
secp256k1_pubkey pubkey;
secp256k1_pubkey pubkey_tmp;
unsigned char seckey[300];
size_t seckeylen = 300;
/* Generate a random key and message. */
{
secp256k1_scalar msg, key;
random_scalar_order_test(&msg);
random_scalar_order_test(&key);
secp256k1_scalar_get_b32(privkey, &key);
secp256k1_scalar_get_b32(message, &msg);
}
/* Construct and verify corresponding public key. */
CHECK(secp256k1_ec_seckey_verify(ctx, privkey) == 1);
CHECK(secp256k1_ec_pubkey_create(ctx, &pubkey, privkey) == 1);
/* Verify exporting and importing public key. */
CHECK(secp256k1_ec_pubkey_serialize(ctx, pubkeyc, &pubkeyclen, &pubkey, secp256k1_rand_bits(1) == 1 ? SECP256K1_EC_COMPRESSED : SECP256K1_EC_UNCOMPRESSED));
memset(&pubkey, 0, sizeof(pubkey));
CHECK(secp256k1_ec_pubkey_parse(ctx, &pubkey, pubkeyc, pubkeyclen) == 1);
/* Verify negation changes the key and changes it back */
memcpy(&pubkey_tmp, &pubkey, sizeof(pubkey));
CHECK(secp256k1_ec_pubkey_negate(ctx, &pubkey_tmp) == 1);
CHECK(memcmp(&pubkey_tmp, &pubkey, sizeof(pubkey)) != 0);
CHECK(secp256k1_ec_pubkey_negate(ctx, &pubkey_tmp) == 1);
CHECK(memcmp(&pubkey_tmp, &pubkey, sizeof(pubkey)) == 0);
/* Verify private key import and export. */
CHECK(ec_privkey_export_der(ctx, seckey, &seckeylen, privkey, secp256k1_rand_bits(1) == 1));
CHECK(ec_privkey_import_der(ctx, privkey2, seckey, seckeylen) == 1);
CHECK(memcmp(privkey, privkey2, 32) == 0);
/* Optionally tweak the keys using addition. */
if (secp256k1_rand_int(3) == 0) {
int ret1;
int ret2;
unsigned char rnd[32];
secp256k1_pubkey pubkey2;
secp256k1_rand256_test(rnd);
ret1 = secp256k1_ec_privkey_tweak_add(ctx, privkey, rnd);
ret2 = secp256k1_ec_pubkey_tweak_add(ctx, &pubkey, rnd);
CHECK(ret1 == ret2);
if (ret1 == 0) {
return;
}
CHECK(secp256k1_ec_pubkey_create(ctx, &pubkey2, privkey) == 1);
CHECK(memcmp(&pubkey, &pubkey2, sizeof(pubkey)) == 0);
}
/* Optionally tweak the keys using multiplication. */
if (secp256k1_rand_int(3) == 0) {
int ret1;
int ret2;
unsigned char rnd[32];
secp256k1_pubkey pubkey2;
secp256k1_rand256_test(rnd);
ret1 = secp256k1_ec_privkey_tweak_mul(ctx, privkey, rnd);
ret2 = secp256k1_ec_pubkey_tweak_mul(ctx, &pubkey, rnd);
CHECK(ret1 == ret2);
if (ret1 == 0) {
return;
}
CHECK(secp256k1_ec_pubkey_create(ctx, &pubkey2, privkey) == 1);
CHECK(memcmp(&pubkey, &pubkey2, sizeof(pubkey)) == 0);
}
/* Sign. */
CHECK(secp256k1_ecdsa_sign(ctx, &signature[0], message, privkey, NULL, NULL) == 1);
CHECK(secp256k1_ecdsa_sign(ctx, &signature[4], message, privkey, NULL, NULL) == 1);
CHECK(secp256k1_ecdsa_sign(ctx, &signature[1], message, privkey, NULL, extra) == 1);
extra[31] = 1;
CHECK(secp256k1_ecdsa_sign(ctx, &signature[2], message, privkey, NULL, extra) == 1);
extra[31] = 0;
extra[0] = 1;
CHECK(secp256k1_ecdsa_sign(ctx, &signature[3], message, privkey, NULL, extra) == 1);
CHECK(memcmp(&signature[0], &signature[4], sizeof(signature[0])) == 0);
CHECK(memcmp(&signature[0], &signature[1], sizeof(signature[0])) != 0);
CHECK(memcmp(&signature[0], &signature[2], sizeof(signature[0])) != 0);
CHECK(memcmp(&signature[0], &signature[3], sizeof(signature[0])) != 0);
CHECK(memcmp(&signature[1], &signature[2], sizeof(signature[0])) != 0);
CHECK(memcmp(&signature[1], &signature[3], sizeof(signature[0])) != 0);
CHECK(memcmp(&signature[2], &signature[3], sizeof(signature[0])) != 0);
/* Verify. */
CHECK(secp256k1_ecdsa_verify(ctx, &signature[0], message, &pubkey) == 1);
CHECK(secp256k1_ecdsa_verify(ctx, &signature[1], message, &pubkey) == 1);
CHECK(secp256k1_ecdsa_verify(ctx, &signature[2], message, &pubkey) == 1);
CHECK(secp256k1_ecdsa_verify(ctx, &signature[3], message, &pubkey) == 1);
/* Test lower-S form, malleate, verify and fail, test again, malleate again */
CHECK(!secp256k1_ecdsa_signature_normalize(ctx, NULL, &signature[0]));
secp256k1_ecdsa_signature_load(ctx, &r, &s, &signature[0]);
secp256k1_scalar_negate(&s, &s);
secp256k1_ecdsa_signature_save(&signature[5], &r, &s);
CHECK(secp256k1_ecdsa_verify(ctx, &signature[5], message, &pubkey) == 0);
CHECK(secp256k1_ecdsa_signature_normalize(ctx, NULL, &signature[5]));
CHECK(secp256k1_ecdsa_signature_normalize(ctx, &signature[5], &signature[5]));
CHECK(!secp256k1_ecdsa_signature_normalize(ctx, NULL, &signature[5]));
CHECK(!secp256k1_ecdsa_signature_normalize(ctx, &signature[5], &signature[5]));
CHECK(secp256k1_ecdsa_verify(ctx, &signature[5], message, &pubkey) == 1);
secp256k1_scalar_negate(&s, &s);
secp256k1_ecdsa_signature_save(&signature[5], &r, &s);
CHECK(!secp256k1_ecdsa_signature_normalize(ctx, NULL, &signature[5]));
CHECK(secp256k1_ecdsa_verify(ctx, &signature[5], message, &pubkey) == 1);
CHECK(memcmp(&signature[5], &signature[0], 64) == 0);
/* Serialize/parse DER and verify again */
CHECK(secp256k1_ecdsa_signature_serialize_der(ctx, sig, &siglen, &signature[0]) == 1);
memset(&signature[0], 0, sizeof(signature[0]));
CHECK(secp256k1_ecdsa_signature_parse_der(ctx, &signature[0], sig, siglen) == 1);
CHECK(secp256k1_ecdsa_verify(ctx, &signature[0], message, &pubkey) == 1);
/* Serialize/destroy/parse DER and verify again. */
siglen = 74;
CHECK(secp256k1_ecdsa_signature_serialize_der(ctx, sig, &siglen, &signature[0]) == 1);
sig[secp256k1_rand_int(siglen)] += 1 + secp256k1_rand_int(255);
CHECK(secp256k1_ecdsa_signature_parse_der(ctx, &signature[0], sig, siglen) == 0 ||
secp256k1_ecdsa_verify(ctx, &signature[0], message, &pubkey) == 0);
}
void test_random_pubkeys(void) {
secp256k1_ge elem;
secp256k1_ge elem2;
unsigned char in[65];
/* Generate some randomly sized pubkeys. */
size_t len = secp256k1_rand_bits(2) == 0 ? 65 : 33;
if (secp256k1_rand_bits(2) == 0) {
len = secp256k1_rand_bits(6);
}
if (len == 65) {
in[0] = secp256k1_rand_bits(1) ? 4 : (secp256k1_rand_bits(1) ? 6 : 7);
} else {
in[0] = secp256k1_rand_bits(1) ? 2 : 3;
}
if (secp256k1_rand_bits(3) == 0) {
in[0] = secp256k1_rand_bits(8);
}
if (len > 1) {
secp256k1_rand256(&in[1]);
}
if (len > 33) {
secp256k1_rand256(&in[33]);
}
if (secp256k1_eckey_pubkey_parse(&elem, in, len)) {
unsigned char out[65];
unsigned char firstb;
int res;
size_t size = len;
firstb = in[0];
/* If the pubkey can be parsed, it should round-trip... */
CHECK(secp256k1_eckey_pubkey_serialize(&elem, out, &size, len == 33));
CHECK(size == len);
CHECK(memcmp(&in[1], &out[1], len-1) == 0);
/* ... except for the type of hybrid inputs. */
if ((in[0] != 6) && (in[0] != 7)) {
CHECK(in[0] == out[0]);
}
size = 65;
CHECK(secp256k1_eckey_pubkey_serialize(&elem, in, &size, 0));
CHECK(size == 65);
CHECK(secp256k1_eckey_pubkey_parse(&elem2, in, size));
ge_equals_ge(&elem,&elem2);
/* Check that the X9.62 hybrid type is checked. */
in[0] = secp256k1_rand_bits(1) ? 6 : 7;
res = secp256k1_eckey_pubkey_parse(&elem2, in, size);
if (firstb == 2 || firstb == 3) {
if (in[0] == firstb + 4) {
CHECK(res);
} else {
CHECK(!res);
}
}
if (res) {
ge_equals_ge(&elem,&elem2);
CHECK(secp256k1_eckey_pubkey_serialize(&elem, out, &size, 0));
CHECK(memcmp(&in[1], &out[1], 64) == 0);
}
}
}
void run_random_pubkeys(void) {
int i;
for (i = 0; i < 10*count; i++) {
test_random_pubkeys();
}
}
void run_ecdsa_end_to_end(void) {
int i;
for (i = 0; i < 64*count; i++) {
test_ecdsa_end_to_end();
}
}
int test_ecdsa_der_parse(const unsigned char *sig, size_t siglen, int certainly_der, int certainly_not_der) {
static const unsigned char zeroes[32] = {0};
#ifdef ENABLE_OPENSSL_TESTS
static const unsigned char max_scalar[32] = {
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfe,
0xba, 0xae, 0xdc, 0xe6, 0xaf, 0x48, 0xa0, 0x3b,
0xbf, 0xd2, 0x5e, 0x8c, 0xd0, 0x36, 0x41, 0x40
};
#endif
int ret = 0;
secp256k1_ecdsa_signature sig_der;
unsigned char roundtrip_der[2048];
unsigned char compact_der[64];
size_t len_der = 2048;
int parsed_der = 0, valid_der = 0, roundtrips_der = 0;
secp256k1_ecdsa_signature sig_der_lax;
unsigned char roundtrip_der_lax[2048];
unsigned char compact_der_lax[64];
size_t len_der_lax = 2048;
int parsed_der_lax = 0, valid_der_lax = 0, roundtrips_der_lax = 0;
#ifdef ENABLE_OPENSSL_TESTS
ECDSA_SIG *sig_openssl;
const BIGNUM *r = NULL, *s = NULL;
const unsigned char *sigptr;
unsigned char roundtrip_openssl[2048];
int len_openssl = 2048;
int parsed_openssl, valid_openssl = 0, roundtrips_openssl = 0;
#endif
parsed_der = secp256k1_ecdsa_signature_parse_der(ctx, &sig_der, sig, siglen);
if (parsed_der) {
ret |= (!secp256k1_ecdsa_signature_serialize_compact(ctx, compact_der, &sig_der)) << 0;
valid_der = (memcmp(compact_der, zeroes, 32) != 0) && (memcmp(compact_der + 32, zeroes, 32) != 0);
}
if (valid_der) {
ret |= (!secp256k1_ecdsa_signature_serialize_der(ctx, roundtrip_der, &len_der, &sig_der)) << 1;
roundtrips_der = (len_der == siglen) && memcmp(roundtrip_der, sig, siglen) == 0;
}
parsed_der_lax = ecdsa_signature_parse_der_lax(ctx, &sig_der_lax, sig, siglen);
if (parsed_der_lax) {
ret |= (!secp256k1_ecdsa_signature_serialize_compact(ctx, compact_der_lax, &sig_der_lax)) << 10;
valid_der_lax = (memcmp(compact_der_lax, zeroes, 32) != 0) && (memcmp(compact_der_lax + 32, zeroes, 32) != 0);
}
if (valid_der_lax) {
ret |= (!secp256k1_ecdsa_signature_serialize_der(ctx, roundtrip_der_lax, &len_der_lax, &sig_der_lax)) << 11;
roundtrips_der_lax = (len_der_lax == siglen) && memcmp(roundtrip_der_lax, sig, siglen) == 0;
}
if (certainly_der) {
ret |= (!parsed_der) << 2;
}
if (certainly_not_der) {
ret |= (parsed_der) << 17;
}
if (valid_der) {
ret |= (!roundtrips_der) << 3;
}
if (valid_der) {
ret |= (!roundtrips_der_lax) << 12;
ret |= (len_der != len_der_lax) << 13;
ret |= (memcmp(roundtrip_der_lax, roundtrip_der, len_der) != 0) << 14;
}
ret |= (roundtrips_der != roundtrips_der_lax) << 15;
if (parsed_der) {
ret |= (!parsed_der_lax) << 16;
}
#ifdef ENABLE_OPENSSL_TESTS
sig_openssl = ECDSA_SIG_new();
sigptr = sig;
parsed_openssl = (d2i_ECDSA_SIG(&sig_openssl, &sigptr, siglen) != NULL);
if (parsed_openssl) {
ECDSA_SIG_get0(sig_openssl, &r, &s);
valid_openssl = !BN_is_negative(r) && !BN_is_negative(s) && BN_num_bits(r) > 0 && BN_num_bits(r) <= 256 && BN_num_bits(s) > 0 && BN_num_bits(s) <= 256;
if (valid_openssl) {
unsigned char tmp[32] = {0};
BN_bn2bin(r, tmp + 32 - BN_num_bytes(r));
valid_openssl = memcmp(tmp, max_scalar, 32) < 0;
}
if (valid_openssl) {
unsigned char tmp[32] = {0};
BN_bn2bin(s, tmp + 32 - BN_num_bytes(s));
valid_openssl = memcmp(tmp, max_scalar, 32) < 0;
}
}
len_openssl = i2d_ECDSA_SIG(sig_openssl, NULL);
if (len_openssl <= 2048) {
unsigned char *ptr = roundtrip_openssl;
CHECK(i2d_ECDSA_SIG(sig_openssl, &ptr) == len_openssl);
roundtrips_openssl = valid_openssl && ((size_t)len_openssl == siglen) && (memcmp(roundtrip_openssl, sig, siglen) == 0);
} else {
len_openssl = 0;
}
ECDSA_SIG_free(sig_openssl);
ret |= (parsed_der && !parsed_openssl) << 4;
ret |= (valid_der && !valid_openssl) << 5;
ret |= (roundtrips_openssl && !parsed_der) << 6;
ret |= (roundtrips_der != roundtrips_openssl) << 7;
if (roundtrips_openssl) {
ret |= (len_der != (size_t)len_openssl) << 8;
ret |= (memcmp(roundtrip_der, roundtrip_openssl, len_der) != 0) << 9;
}
#endif
return ret;
}
static void assign_big_endian(unsigned char *ptr, size_t ptrlen, uint32_t val) {
size_t i;
for (i = 0; i < ptrlen; i++) {
int shift = ptrlen - 1 - i;
if (shift >= 4) {
ptr[i] = 0;
} else {
ptr[i] = (val >> shift) & 0xFF;
}
}
}
static void damage_array(unsigned char *sig, size_t *len) {
int pos;
int action = secp256k1_rand_bits(3);
if (action < 1 && *len > 3) {
/* Delete a byte. */
pos = secp256k1_rand_int(*len);
memmove(sig + pos, sig + pos + 1, *len - pos - 1);
(*len)--;
return;
} else if (action < 2 && *len < 2048) {
/* Insert a byte. */
pos = secp256k1_rand_int(1 + *len);
memmove(sig + pos + 1, sig + pos, *len - pos);
sig[pos] = secp256k1_rand_bits(8);
(*len)++;
return;
} else if (action < 4) {
/* Modify a byte. */
sig[secp256k1_rand_int(*len)] += 1 + secp256k1_rand_int(255);
return;
} else { /* action < 8 */
/* Modify a bit. */
sig[secp256k1_rand_int(*len)] ^= 1 << secp256k1_rand_bits(3);
return;
}
}
static void random_ber_signature(unsigned char *sig, size_t *len, int* certainly_der, int* certainly_not_der) {
int der;
int nlow[2], nlen[2], nlenlen[2], nhbit[2], nhbyte[2], nzlen[2];
size_t tlen, elen, glen;
int indet;
int n;
*len = 0;
der = secp256k1_rand_bits(2) == 0;
*certainly_der = der;
*certainly_not_der = 0;
indet = der ? 0 : secp256k1_rand_int(10) == 0;
for (n = 0; n < 2; n++) {
/* We generate two classes of numbers: nlow==1 "low" ones (up to 32 bytes), nlow==0 "high" ones (32 bytes with 129 top bits set, or larger than 32 bytes) */
nlow[n] = der ? 1 : (secp256k1_rand_bits(3) != 0);
/* The length of the number in bytes (the first byte of which will always be nonzero) */
nlen[n] = nlow[n] ? secp256k1_rand_int(33) : 32 + secp256k1_rand_int(200) * secp256k1_rand_int(8) / 8;
CHECK(nlen[n] <= 232);
/* The top bit of the number. */
nhbit[n] = (nlow[n] == 0 && nlen[n] == 32) ? 1 : (nlen[n] == 0 ? 0 : secp256k1_rand_bits(1));
/* The top byte of the number (after the potential hardcoded 16 0xFF characters for "high" 32 bytes numbers) */
nhbyte[n] = nlen[n] == 0 ? 0 : (nhbit[n] ? 128 + secp256k1_rand_bits(7) : 1 + secp256k1_rand_int(127));
/* The number of zero bytes in front of the number (which is 0 or 1 in case of DER, otherwise we extend up to 300 bytes) */
nzlen[n] = der ? ((nlen[n] == 0 || nhbit[n]) ? 1 : 0) : (nlow[n] ? secp256k1_rand_int(3) : secp256k1_rand_int(300 - nlen[n]) * secp256k1_rand_int(8) / 8);
if (nzlen[n] > ((nlen[n] == 0 || nhbit[n]) ? 1 : 0)) {
*certainly_not_der = 1;
}
CHECK(nlen[n] + nzlen[n] <= 300);
/* The length of the length descriptor for the number. 0 means short encoding, anything else is long encoding. */
nlenlen[n] = nlen[n] + nzlen[n] < 128 ? 0 : (nlen[n] + nzlen[n] < 256 ? 1 : 2);
if (!der) {
/* nlenlen[n] max 127 bytes */
int add = secp256k1_rand_int(127 - nlenlen[n]) * secp256k1_rand_int(16) * secp256k1_rand_int(16) / 256;
nlenlen[n] += add;
if (add != 0) {
*certainly_not_der = 1;
}
}
CHECK(nlen[n] + nzlen[n] + nlenlen[n] <= 427);
}
/* The total length of the data to go, so far */
tlen = 2 + nlenlen[0] + nlen[0] + nzlen[0] + 2 + nlenlen[1] + nlen[1] + nzlen[1];
CHECK(tlen <= 856);
/* The length of the garbage inside the tuple. */
elen = (der || indet) ? 0 : secp256k1_rand_int(980 - tlen) * secp256k1_rand_int(8) / 8;
if (elen != 0) {
*certainly_not_der = 1;
}
tlen += elen;
CHECK(tlen <= 980);
/* The length of the garbage after the end of the tuple. */
glen = der ? 0 : secp256k1_rand_int(990 - tlen) * secp256k1_rand_int(8) / 8;
if (glen != 0) {
*certainly_not_der = 1;
}
CHECK(tlen + glen <= 990);
/* Write the tuple header. */
sig[(*len)++] = 0x30;
if (indet) {
/* Indeterminate length */
sig[(*len)++] = 0x80;
*certainly_not_der = 1;
} else {
int tlenlen = tlen < 128 ? 0 : (tlen < 256 ? 1 : 2);
if (!der) {
int add = secp256k1_rand_int(127 - tlenlen) * secp256k1_rand_int(16) * secp256k1_rand_int(16) / 256;
tlenlen += add;
if (add != 0) {
*certainly_not_der = 1;
}
}
if (tlenlen == 0) {
/* Short length notation */
sig[(*len)++] = tlen;
} else {
/* Long length notation */
sig[(*len)++] = 128 + tlenlen;
assign_big_endian(sig + *len, tlenlen, tlen);
*len += tlenlen;
}
tlen += tlenlen;
}
tlen += 2;
CHECK(tlen + glen <= 1119);
for (n = 0; n < 2; n++) {
/* Write the integer header. */
sig[(*len)++] = 0x02;
if (nlenlen[n] == 0) {
/* Short length notation */
sig[(*len)++] = nlen[n] + nzlen[n];
} else {
/* Long length notation. */
sig[(*len)++] = 128 + nlenlen[n];
assign_big_endian(sig + *len, nlenlen[n], nlen[n] + nzlen[n]);
*len += nlenlen[n];
}
/* Write zero padding */
while (nzlen[n] > 0) {
sig[(*len)++] = 0x00;
nzlen[n]--;
}
if (nlen[n] == 32 && !nlow[n]) {
/* Special extra 16 0xFF bytes in "high" 32-byte numbers */
int i;
for (i = 0; i < 16; i++) {
sig[(*len)++] = 0xFF;
}
nlen[n] -= 16;
}
/* Write first byte of number */
if (nlen[n] > 0) {
sig[(*len)++] = nhbyte[n];
nlen[n]--;
}
/* Generate remaining random bytes of number */
secp256k1_rand_bytes_test(sig + *len, nlen[n]);
*len += nlen[n];
nlen[n] = 0;
}
/* Generate random garbage inside tuple. */
secp256k1_rand_bytes_test(sig + *len, elen);
*len += elen;
/* Generate end-of-contents bytes. */
if (indet) {
sig[(*len)++] = 0;
sig[(*len)++] = 0;
tlen += 2;
}
CHECK(tlen + glen <= 1121);
/* Generate random garbage outside tuple. */
secp256k1_rand_bytes_test(sig + *len, glen);
*len += glen;
tlen += glen;
CHECK(tlen <= 1121);
CHECK(tlen == *len);
}
void run_ecdsa_der_parse(void) {
int i,j;
for (i = 0; i < 200 * count; i++) {
unsigned char buffer[2048];
size_t buflen = 0;
int certainly_der = 0;
int certainly_not_der = 0;
random_ber_signature(buffer, &buflen, &certainly_der, &certainly_not_der);
CHECK(buflen <= 2048);
for (j = 0; j < 16; j++) {
int ret = 0;
if (j > 0) {
damage_array(buffer, &buflen);
/* We don't know anything anymore about the DERness of the result */
certainly_der = 0;
certainly_not_der = 0;
}
ret = test_ecdsa_der_parse(buffer, buflen, certainly_der, certainly_not_der);
if (ret != 0) {
size_t k;
fprintf(stderr, "Failure %x on ", ret);
for (k = 0; k < buflen; k++) {
fprintf(stderr, "%02x ", buffer[k]);
}
fprintf(stderr, "\n");
}
CHECK(ret == 0);
}
}
}
/* Tests several edge cases. */
void test_ecdsa_edge_cases(void) {
int t;
secp256k1_ecdsa_signature sig;
/* Test the case where ECDSA recomputes a point that is infinity. */
{
secp256k1_gej keyj;
secp256k1_ge key;
secp256k1_scalar msg;
secp256k1_scalar sr, ss;
secp256k1_scalar_set_int(&ss, 1);
secp256k1_scalar_negate(&ss, &ss);
secp256k1_scalar_inverse(&ss, &ss);
secp256k1_scalar_set_int(&sr, 1);
secp256k1_ecmult_gen(&ctx->ecmult_gen_ctx, &keyj, &sr);
secp256k1_ge_set_gej(&key, &keyj);
msg = ss;
CHECK(secp256k1_ecdsa_sig_verify(&ctx->ecmult_ctx, &sr, &ss, &key, &msg) == 0);
}
/* Verify signature with r of zero fails. */
{
const unsigned char pubkey_mods_zero[33] = {
0x02, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xfe, 0xba, 0xae, 0xdc, 0xe6, 0xaf, 0x48, 0xa0,
0x3b, 0xbf, 0xd2, 0x5e, 0x8c, 0xd0, 0x36, 0x41,
0x41
};
secp256k1_ge key;
secp256k1_scalar msg;
secp256k1_scalar sr, ss;
secp256k1_scalar_set_int(&ss, 1);
secp256k1_scalar_set_int(&msg, 0);
secp256k1_scalar_set_int(&sr, 0);
CHECK(secp256k1_eckey_pubkey_parse(&key, pubkey_mods_zero, 33));
CHECK(secp256k1_ecdsa_sig_verify(&ctx->ecmult_ctx, &sr, &ss, &key, &msg) == 0);
}
/* Verify signature with s of zero fails. */
{
const unsigned char pubkey[33] = {
0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x01
};
secp256k1_ge key;
secp256k1_scalar msg;
secp256k1_scalar sr, ss;
secp256k1_scalar_set_int(&ss, 0);
secp256k1_scalar_set_int(&msg, 0);
secp256k1_scalar_set_int(&sr, 1);
CHECK(secp256k1_eckey_pubkey_parse(&key, pubkey, 33));
CHECK(secp256k1_ecdsa_sig_verify(&ctx->ecmult_ctx, &sr, &ss, &key, &msg) == 0);
}
/* Verify signature with message 0 passes. */
{
const unsigned char pubkey[33] = {
0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x02
};
const unsigned char pubkey2[33] = {
0x02, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xfe, 0xba, 0xae, 0xdc, 0xe6, 0xaf, 0x48, 0xa0,
0x3b, 0xbf, 0xd2, 0x5e, 0x8c, 0xd0, 0x36, 0x41,
0x43
};
secp256k1_ge key;
secp256k1_ge key2;
secp256k1_scalar msg;
secp256k1_scalar sr, ss;
secp256k1_scalar_set_int(&ss, 2);
secp256k1_scalar_set_int(&msg, 0);
secp256k1_scalar_set_int(&sr, 2);
CHECK(secp256k1_eckey_pubkey_parse(&key, pubkey, 33));
CHECK(secp256k1_eckey_pubkey_parse(&key2, pubkey2, 33));
CHECK(secp256k1_ecdsa_sig_verify(&ctx->ecmult_ctx, &sr, &ss, &key, &msg) == 1);
CHECK(secp256k1_ecdsa_sig_verify(&ctx->ecmult_ctx, &sr, &ss, &key2, &msg) == 1);
secp256k1_scalar_negate(&ss, &ss);
CHECK(secp256k1_ecdsa_sig_verify(&ctx->ecmult_ctx, &sr, &ss, &key, &msg) == 1);
CHECK(secp256k1_ecdsa_sig_verify(&ctx->ecmult_ctx, &sr, &ss, &key2, &msg) == 1);
secp256k1_scalar_set_int(&ss, 1);
CHECK(secp256k1_ecdsa_sig_verify(&ctx->ecmult_ctx, &sr, &ss, &key, &msg) == 0);
CHECK(secp256k1_ecdsa_sig_verify(&ctx->ecmult_ctx, &sr, &ss, &key2, &msg) == 0);
}
/* Verify signature with message 1 passes. */
{
const unsigned char pubkey[33] = {
0x02, 0x14, 0x4e, 0x5a, 0x58, 0xef, 0x5b, 0x22,
0x6f, 0xd2, 0xe2, 0x07, 0x6a, 0x77, 0xcf, 0x05,
0xb4, 0x1d, 0xe7, 0x4a, 0x30, 0x98, 0x27, 0x8c,
0x93, 0xe6, 0xe6, 0x3c, 0x0b, 0xc4, 0x73, 0x76,
0x25
};
const unsigned char pubkey2[33] = {
0x02, 0x8a, 0xd5, 0x37, 0xed, 0x73, 0xd9, 0x40,
0x1d, 0xa0, 0x33, 0xd2, 0xdc, 0xf0, 0xaf, 0xae,
0x34, 0xcf, 0x5f, 0x96, 0x4c, 0x73, 0x28, 0x0f,
0x92, 0xc0, 0xf6, 0x9d, 0xd9, 0xb2, 0x09, 0x10,
0x62
};
const unsigned char csr[32] = {
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01,
0x45, 0x51, 0x23, 0x19, 0x50, 0xb7, 0x5f, 0xc4,
0x40, 0x2d, 0xa1, 0x72, 0x2f, 0xc9, 0xba, 0xeb
};
secp256k1_ge key;
secp256k1_ge key2;
secp256k1_scalar msg;
secp256k1_scalar sr, ss;
secp256k1_scalar_set_int(&ss, 1);
secp256k1_scalar_set_int(&msg, 1);
secp256k1_scalar_set_b32(&sr, csr, NULL);
CHECK(secp256k1_eckey_pubkey_parse(&key, pubkey, 33));
CHECK(secp256k1_eckey_pubkey_parse(&key2, pubkey2, 33));
CHECK(secp256k1_ecdsa_sig_verify(&ctx->ecmult_ctx, &sr, &ss, &key, &msg) == 1);
CHECK(secp256k1_ecdsa_sig_verify(&ctx->ecmult_ctx, &sr, &ss, &key2, &msg) == 1);
secp256k1_scalar_negate(&ss, &ss);
CHECK(secp256k1_ecdsa_sig_verify(&ctx->ecmult_ctx, &sr, &ss, &key, &msg) == 1);
CHECK(secp256k1_ecdsa_sig_verify(&ctx->ecmult_ctx, &sr, &ss, &key2, &msg) == 1);
secp256k1_scalar_set_int(&ss, 2);
secp256k1_scalar_inverse_var(&ss, &ss);
CHECK(secp256k1_ecdsa_sig_verify(&ctx->ecmult_ctx, &sr, &ss, &key, &msg) == 0);
CHECK(secp256k1_ecdsa_sig_verify(&ctx->ecmult_ctx, &sr, &ss, &key2, &msg) == 0);
}
/* Verify signature with message -1 passes. */
{
const unsigned char pubkey[33] = {
0x03, 0xaf, 0x97, 0xff, 0x7d, 0x3a, 0xf6, 0xa0,
0x02, 0x94, 0xbd, 0x9f, 0x4b, 0x2e, 0xd7, 0x52,
0x28, 0xdb, 0x49, 0x2a, 0x65, 0xcb, 0x1e, 0x27,
0x57, 0x9c, 0xba, 0x74, 0x20, 0xd5, 0x1d, 0x20,
0xf1
};
const unsigned char csr[32] = {
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01,
0x45, 0x51, 0x23, 0x19, 0x50, 0xb7, 0x5f, 0xc4,
0x40, 0x2d, 0xa1, 0x72, 0x2f, 0xc9, 0xba, 0xee
};
secp256k1_ge key;
secp256k1_scalar msg;
secp256k1_scalar sr, ss;
secp256k1_scalar_set_int(&ss, 1);
secp256k1_scalar_set_int(&msg, 1);
secp256k1_scalar_negate(&msg, &msg);
secp256k1_scalar_set_b32(&sr, csr, NULL);
CHECK(secp256k1_eckey_pubkey_parse(&key, pubkey, 33));
CHECK(secp256k1_ecdsa_sig_verify(&ctx->ecmult_ctx, &sr, &ss, &key, &msg) == 1);
secp256k1_scalar_negate(&ss, &ss);
CHECK(secp256k1_ecdsa_sig_verify(&ctx->ecmult_ctx, &sr, &ss, &key, &msg) == 1);
secp256k1_scalar_set_int(&ss, 3);
secp256k1_scalar_inverse_var(&ss, &ss);
CHECK(secp256k1_ecdsa_sig_verify(&ctx->ecmult_ctx, &sr, &ss, &key, &msg) == 0);
}
/* Signature where s would be zero. */
{
secp256k1_pubkey pubkey;
size_t siglen;
int32_t ecount;
unsigned char signature[72];
static const unsigned char nonce[32] = {
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01,
};
static const unsigned char nonce2[32] = {
0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFE,
0xBA,0xAE,0xDC,0xE6,0xAF,0x48,0xA0,0x3B,
0xBF,0xD2,0x5E,0x8C,0xD0,0x36,0x41,0x40
};
const unsigned char key[32] = {
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01,
};
unsigned char msg[32] = {
0x86, 0x41, 0x99, 0x81, 0x06, 0x23, 0x44, 0x53,
0xaa, 0x5f, 0x9d, 0x6a, 0x31, 0x78, 0xf4, 0xf7,
0xb8, 0x12, 0xe0, 0x0b, 0x81, 0x7a, 0x77, 0x62,
0x65, 0xdf, 0xdd, 0x31, 0xb9, 0x3e, 0x29, 0xa9,
};
ecount = 0;
secp256k1_context_set_illegal_callback(ctx, counting_illegal_callback_fn, &ecount);
CHECK(secp256k1_ecdsa_sign(ctx, &sig, msg, key, precomputed_nonce_function, nonce) == 0);
CHECK(secp256k1_ecdsa_sign(ctx, &sig, msg, key, precomputed_nonce_function, nonce2) == 0);
msg[31] = 0xaa;
CHECK(secp256k1_ecdsa_sign(ctx, &sig, msg, key, precomputed_nonce_function, nonce) == 1);
CHECK(ecount == 0);
CHECK(secp256k1_ecdsa_sign(ctx, NULL, msg, key, precomputed_nonce_function, nonce2) == 0);
CHECK(ecount == 1);
CHECK(secp256k1_ecdsa_sign(ctx, &sig, NULL, key, precomputed_nonce_function, nonce2) == 0);
CHECK(ecount == 2);
CHECK(secp256k1_ecdsa_sign(ctx, &sig, msg, NULL, precomputed_nonce_function, nonce2) == 0);
CHECK(ecount == 3);
CHECK(secp256k1_ecdsa_sign(ctx, &sig, msg, key, precomputed_nonce_function, nonce2) == 1);
CHECK(secp256k1_ec_pubkey_create(ctx, &pubkey, key) == 1);
CHECK(secp256k1_ecdsa_verify(ctx, NULL, msg, &pubkey) == 0);
CHECK(ecount == 4);
CHECK(secp256k1_ecdsa_verify(ctx, &sig, NULL, &pubkey) == 0);
CHECK(ecount == 5);
CHECK(secp256k1_ecdsa_verify(ctx, &sig, msg, NULL) == 0);
CHECK(ecount == 6);
CHECK(secp256k1_ecdsa_verify(ctx, &sig, msg, &pubkey) == 1);
CHECK(ecount == 6);
CHECK(secp256k1_ec_pubkey_create(ctx, &pubkey, NULL) == 0);
CHECK(ecount == 7);
/* That pubkeyload fails via an ARGCHECK is a little odd but makes sense because pubkeys are an opaque data type. */
CHECK(secp256k1_ecdsa_verify(ctx, &sig, msg, &pubkey) == 0);
CHECK(ecount == 8);
siglen = 72;
CHECK(secp256k1_ecdsa_signature_serialize_der(ctx, NULL, &siglen, &sig) == 0);
CHECK(ecount == 9);
CHECK(secp256k1_ecdsa_signature_serialize_der(ctx, signature, NULL, &sig) == 0);
CHECK(ecount == 10);
CHECK(secp256k1_ecdsa_signature_serialize_der(ctx, signature, &siglen, NULL) == 0);
CHECK(ecount == 11);
CHECK(secp256k1_ecdsa_signature_serialize_der(ctx, signature, &siglen, &sig) == 1);
CHECK(ecount == 11);
CHECK(secp256k1_ecdsa_signature_parse_der(ctx, NULL, signature, siglen) == 0);
CHECK(ecount == 12);
CHECK(secp256k1_ecdsa_signature_parse_der(ctx, &sig, NULL, siglen) == 0);
CHECK(ecount == 13);
CHECK(secp256k1_ecdsa_signature_parse_der(ctx, &sig, signature, siglen) == 1);
CHECK(ecount == 13);
siglen = 10;
/* Too little room for a signature does not fail via ARGCHECK. */
CHECK(secp256k1_ecdsa_signature_serialize_der(ctx, signature, &siglen, &sig) == 0);
CHECK(ecount == 13);
ecount = 0;
CHECK(secp256k1_ecdsa_signature_normalize(ctx, NULL, NULL) == 0);
CHECK(ecount == 1);
CHECK(secp256k1_ecdsa_signature_serialize_compact(ctx, NULL, &sig) == 0);
CHECK(ecount == 2);
CHECK(secp256k1_ecdsa_signature_serialize_compact(ctx, signature, NULL) == 0);
CHECK(ecount == 3);
CHECK(secp256k1_ecdsa_signature_serialize_compact(ctx, signature, &sig) == 1);
CHECK(ecount == 3);
CHECK(secp256k1_ecdsa_signature_parse_compact(ctx, NULL, signature) == 0);
CHECK(ecount == 4);
CHECK(secp256k1_ecdsa_signature_parse_compact(ctx, &sig, NULL) == 0);
CHECK(ecount == 5);
CHECK(secp256k1_ecdsa_signature_parse_compact(ctx, &sig, signature) == 1);
CHECK(ecount == 5);
memset(signature, 255, 64);
CHECK(secp256k1_ecdsa_signature_parse_compact(ctx, &sig, signature) == 0);
CHECK(ecount == 5);
secp256k1_context_set_illegal_callback(ctx, NULL, NULL);
}
/* Nonce function corner cases. */
for (t = 0; t < 2; t++) {
static const unsigned char zero[32] = {0x00};
int i;
unsigned char key[32];
unsigned char msg[32];
secp256k1_ecdsa_signature sig2;
secp256k1_scalar sr[512], ss;
const unsigned char *extra;
extra = t == 0 ? NULL : zero;
memset(msg, 0, 32);
msg[31] = 1;
/* High key results in signature failure. */
memset(key, 0xFF, 32);
CHECK(secp256k1_ecdsa_sign(ctx, &sig, msg, key, NULL, extra) == 0);
CHECK(is_empty_signature(&sig));
/* Zero key results in signature failure. */
memset(key, 0, 32);
CHECK(secp256k1_ecdsa_sign(ctx, &sig, msg, key, NULL, extra) == 0);
CHECK(is_empty_signature(&sig));
/* Nonce function failure results in signature failure. */
key[31] = 1;
CHECK(secp256k1_ecdsa_sign(ctx, &sig, msg, key, nonce_function_test_fail, extra) == 0);
CHECK(is_empty_signature(&sig));
/* The retry loop successfully makes its way to the first good value. */
CHECK(secp256k1_ecdsa_sign(ctx, &sig, msg, key, nonce_function_test_retry, extra) == 1);
CHECK(!is_empty_signature(&sig));
CHECK(secp256k1_ecdsa_sign(ctx, &sig2, msg, key, nonce_function_rfc6979, extra) == 1);
CHECK(!is_empty_signature(&sig2));
CHECK(memcmp(&sig, &sig2, sizeof(sig)) == 0);
/* The default nonce function is deterministic. */
CHECK(secp256k1_ecdsa_sign(ctx, &sig2, msg, key, NULL, extra) == 1);
CHECK(!is_empty_signature(&sig2));
CHECK(memcmp(&sig, &sig2, sizeof(sig)) == 0);
/* The default nonce function changes output with different messages. */
for(i = 0; i < 256; i++) {
int j;
msg[0] = i;
CHECK(secp256k1_ecdsa_sign(ctx, &sig2, msg, key, NULL, extra) == 1);
CHECK(!is_empty_signature(&sig2));
secp256k1_ecdsa_signature_load(ctx, &sr[i], &ss, &sig2);
for (j = 0; j < i; j++) {
CHECK(!secp256k1_scalar_eq(&sr[i], &sr[j]));
}
}
msg[0] = 0;
msg[31] = 2;
/* The default nonce function changes output with different keys. */
for(i = 256; i < 512; i++) {
int j;
key[0] = i - 256;
CHECK(secp256k1_ecdsa_sign(ctx, &sig2, msg, key, NULL, extra) == 1);
CHECK(!is_empty_signature(&sig2));
secp256k1_ecdsa_signature_load(ctx, &sr[i], &ss, &sig2);
for (j = 0; j < i; j++) {
CHECK(!secp256k1_scalar_eq(&sr[i], &sr[j]));
}
}
key[0] = 0;
}
{
/* Check that optional nonce arguments do not have equivalent effect. */
const unsigned char zeros[32] = {0};
unsigned char nonce[32];
unsigned char nonce2[32];
unsigned char nonce3[32];
unsigned char nonce4[32];
VG_UNDEF(nonce,32);
VG_UNDEF(nonce2,32);
VG_UNDEF(nonce3,32);
VG_UNDEF(nonce4,32);
CHECK(nonce_function_rfc6979(nonce, zeros, zeros, NULL, NULL, 0) == 1);
VG_CHECK(nonce,32);
CHECK(nonce_function_rfc6979(nonce2, zeros, zeros, zeros, NULL, 0) == 1);
VG_CHECK(nonce2,32);
CHECK(nonce_function_rfc6979(nonce3, zeros, zeros, NULL, (void *)zeros, 0) == 1);
VG_CHECK(nonce3,32);
CHECK(nonce_function_rfc6979(nonce4, zeros, zeros, zeros, (void *)zeros, 0) == 1);
VG_CHECK(nonce4,32);
CHECK(memcmp(nonce, nonce2, 32) != 0);
CHECK(memcmp(nonce, nonce3, 32) != 0);
CHECK(memcmp(nonce, nonce4, 32) != 0);
CHECK(memcmp(nonce2, nonce3, 32) != 0);
CHECK(memcmp(nonce2, nonce4, 32) != 0);
CHECK(memcmp(nonce3, nonce4, 32) != 0);
}
/* Privkey export where pubkey is the point at infinity. */
{
unsigned char privkey[300];
unsigned char seckey[32] = {
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfe,
0xba, 0xae, 0xdc, 0xe6, 0xaf, 0x48, 0xa0, 0x3b,
0xbf, 0xd2, 0x5e, 0x8c, 0xd0, 0x36, 0x41, 0x41,
};
size_t outlen = 300;
CHECK(!ec_privkey_export_der(ctx, privkey, &outlen, seckey, 0));
outlen = 300;
CHECK(!ec_privkey_export_der(ctx, privkey, &outlen, seckey, 1));
}
}
void run_ecdsa_edge_cases(void) {
test_ecdsa_edge_cases();
}
#ifdef ENABLE_OPENSSL_TESTS
EC_KEY *get_openssl_key(const unsigned char *key32) {
unsigned char privkey[300];
size_t privkeylen;
const unsigned char* pbegin = privkey;
int compr = secp256k1_rand_bits(1);
EC_KEY *ec_key = EC_KEY_new_by_curve_name(NID_secp256k1);
CHECK(ec_privkey_export_der(ctx, privkey, &privkeylen, key32, compr));
CHECK(d2i_ECPrivateKey(&ec_key, &pbegin, privkeylen));
CHECK(EC_KEY_check_key(ec_key));
return ec_key;
}
void test_ecdsa_openssl(void) {
secp256k1_gej qj;
secp256k1_ge q;
secp256k1_scalar sigr, sigs;
secp256k1_scalar one;
secp256k1_scalar msg2;
secp256k1_scalar key, msg;
EC_KEY *ec_key;
unsigned int sigsize = 80;
size_t secp_sigsize = 80;
unsigned char message[32];
unsigned char signature[80];
unsigned char key32[32];
secp256k1_rand256_test(message);
secp256k1_scalar_set_b32(&msg, message, NULL);
random_scalar_order_test(&key);
secp256k1_scalar_get_b32(key32, &key);
secp256k1_ecmult_gen(&ctx->ecmult_gen_ctx, &qj, &key);
secp256k1_ge_set_gej(&q, &qj);
ec_key = get_openssl_key(key32);
CHECK(ec_key != NULL);
CHECK(ECDSA_sign(0, message, sizeof(message), signature, &sigsize, ec_key));
CHECK(secp256k1_ecdsa_sig_parse(&sigr, &sigs, signature, sigsize));
CHECK(secp256k1_ecdsa_sig_verify(&ctx->ecmult_ctx, &sigr, &sigs, &q, &msg));
secp256k1_scalar_set_int(&one, 1);
secp256k1_scalar_add(&msg2, &msg, &one);
CHECK(!secp256k1_ecdsa_sig_verify(&ctx->ecmult_ctx, &sigr, &sigs, &q, &msg2));
random_sign(&sigr, &sigs, &key, &msg, NULL);
CHECK(secp256k1_ecdsa_sig_serialize(signature, &secp_sigsize, &sigr, &sigs));
CHECK(ECDSA_verify(0, message, sizeof(message), signature, secp_sigsize, ec_key) == 1);
EC_KEY_free(ec_key);
}
void run_ecdsa_openssl(void) {
int i;
for (i = 0; i < 10*count; i++) {
test_ecdsa_openssl();
}
}
#endif
#ifdef ENABLE_MODULE_ECDH
# include "modules/ecdh/tests_impl.h"
#endif
#ifdef ENABLE_MODULE_RECOVERY
# include "modules/recovery/tests_impl.h"
#endif
int main(int argc, char **argv) {
unsigned char seed16[16] = {0};
unsigned char run32[32] = {0};
/* find iteration count */
if (argc > 1) {
count = strtol(argv[1], NULL, 0);
}
/* find random seed */
if (argc > 2) {
int pos = 0;
const char* ch = argv[2];
while (pos < 16 && ch[0] != 0 && ch[1] != 0) {
unsigned short sh;
if (sscanf(ch, "%2hx", &sh)) {
seed16[pos] = sh;
} else {
break;
}
ch += 2;
pos++;
}
} else {
FILE *frand = fopen("/dev/urandom", "r");
if ((frand == NULL) || !fread(&seed16, sizeof(seed16), 1, frand)) {
uint64_t t = time(NULL) * (uint64_t)1337;
seed16[0] ^= t;
seed16[1] ^= t >> 8;
seed16[2] ^= t >> 16;
seed16[3] ^= t >> 24;
seed16[4] ^= t >> 32;
seed16[5] ^= t >> 40;
seed16[6] ^= t >> 48;
seed16[7] ^= t >> 56;
}
fclose(frand);
}
secp256k1_rand_seed(seed16);
printf("test count = %i\n", count);
printf("random seed = %02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x\n", seed16[0], seed16[1], seed16[2], seed16[3], seed16[4], seed16[5], seed16[6], seed16[7], seed16[8], seed16[9], seed16[10], seed16[11], seed16[12], seed16[13], seed16[14], seed16[15]);
/* initialize */
run_context_tests();
run_scratch_tests();
ctx = secp256k1_context_create(SECP256K1_CONTEXT_SIGN | SECP256K1_CONTEXT_VERIFY);
if (secp256k1_rand_bits(1)) {
secp256k1_rand256(run32);
CHECK(secp256k1_context_randomize(ctx, secp256k1_rand_bits(1) ? run32 : NULL));
}
run_rand_bits();
run_rand_int();
run_sha256_tests();
run_hmac_sha256_tests();
run_rfc6979_hmac_sha256_tests();
#ifndef USE_NUM_NONE
/* num tests */
run_num_smalltests();
#endif
/* scalar tests */
run_scalar_tests();
/* field tests */
run_field_inv();
run_field_inv_var();
run_field_inv_all_var();
run_field_misc();
run_field_convert();
run_sqr();
run_sqrt();
/* group tests */
run_ge();
run_group_decompress();
/* ecmult tests */
run_wnaf();
run_point_times_order();
run_ecmult_chain();
run_ecmult_constants();
run_ecmult_gen_blind();
run_ecmult_const_tests();
run_ecmult_multi_tests();
run_ec_combine();
/* endomorphism tests */
#ifdef USE_ENDOMORPHISM
run_endomorphism_tests();
#endif
/* EC point parser test */
run_ec_pubkey_parse_test();
/* EC key edge cases */
run_eckey_edge_case_test();
#ifdef ENABLE_MODULE_ECDH
/* ecdh tests */
run_ecdh_tests();
#endif
/* ecdsa tests */
run_random_pubkeys();
run_ecdsa_der_parse();
run_ecdsa_sign_verify();
run_ecdsa_end_to_end();
run_ecdsa_edge_cases();
#ifdef ENABLE_OPENSSL_TESTS
run_ecdsa_openssl();
#endif
#ifdef ENABLE_MODULE_RECOVERY
/* ECDSA pubkey recovery tests */
run_recovery_tests();
#endif
secp256k1_rand256(run32);
printf("random run = %02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x\n", run32[0], run32[1], run32[2], run32[3], run32[4], run32[5], run32[6], run32[7], run32[8], run32[9], run32[10], run32[11], run32[12], run32[13], run32[14], run32[15]);
/* shutdown */
secp256k1_context_destroy(ctx);
printf("no problems found\n");
return 0;
}
|
630424.c | /*
* An rtc driver for the Dallas DS1511
*
* Copyright (C) 2006 Atsushi Nemoto <[email protected]>
* Copyright (C) 2007 Andrew Sharp <[email protected]>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* Real time clock driver for the Dallas 1511 chip, which also
* contains a watchdog timer. There is a tiny amount of code that
* platform code could use to mess with the watchdog device a little
* bit, but not a full watchdog driver.
*/
#include <linux/bcd.h>
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/gfp.h>
#include <linux/delay.h>
#include <linux/interrupt.h>
#include <linux/rtc.h>
#include <linux/platform_device.h>
#include <linux/io.h>
#include <linux/module.h>
enum ds1511reg {
DS1511_SEC = 0x0,
DS1511_MIN = 0x1,
DS1511_HOUR = 0x2,
DS1511_DOW = 0x3,
DS1511_DOM = 0x4,
DS1511_MONTH = 0x5,
DS1511_YEAR = 0x6,
DS1511_CENTURY = 0x7,
DS1511_AM1_SEC = 0x8,
DS1511_AM2_MIN = 0x9,
DS1511_AM3_HOUR = 0xa,
DS1511_AM4_DATE = 0xb,
DS1511_WD_MSEC = 0xc,
DS1511_WD_SEC = 0xd,
DS1511_CONTROL_A = 0xe,
DS1511_CONTROL_B = 0xf,
DS1511_RAMADDR_LSB = 0x10,
DS1511_RAMDATA = 0x13
};
#define DS1511_BLF1 0x80
#define DS1511_BLF2 0x40
#define DS1511_PRS 0x20
#define DS1511_PAB 0x10
#define DS1511_TDF 0x08
#define DS1511_KSF 0x04
#define DS1511_WDF 0x02
#define DS1511_IRQF 0x01
#define DS1511_TE 0x80
#define DS1511_CS 0x40
#define DS1511_BME 0x20
#define DS1511_TPE 0x10
#define DS1511_TIE 0x08
#define DS1511_KIE 0x04
#define DS1511_WDE 0x02
#define DS1511_WDS 0x01
#define DS1511_RAM_MAX 0x100
#define RTC_CMD DS1511_CONTROL_B
#define RTC_CMD1 DS1511_CONTROL_A
#define RTC_ALARM_SEC DS1511_AM1_SEC
#define RTC_ALARM_MIN DS1511_AM2_MIN
#define RTC_ALARM_HOUR DS1511_AM3_HOUR
#define RTC_ALARM_DATE DS1511_AM4_DATE
#define RTC_SEC DS1511_SEC
#define RTC_MIN DS1511_MIN
#define RTC_HOUR DS1511_HOUR
#define RTC_DOW DS1511_DOW
#define RTC_DOM DS1511_DOM
#define RTC_MON DS1511_MONTH
#define RTC_YEAR DS1511_YEAR
#define RTC_CENTURY DS1511_CENTURY
#define RTC_TIE DS1511_TIE
#define RTC_TE DS1511_TE
struct rtc_plat_data {
struct rtc_device *rtc;
void __iomem *ioaddr; /* virtual base address */
int irq;
unsigned int irqen;
int alrm_sec;
int alrm_min;
int alrm_hour;
int alrm_mday;
spinlock_t lock;
};
static DEFINE_SPINLOCK(ds1511_lock);
static __iomem char *ds1511_base;
static u32 reg_spacing = 1;
static noinline void
rtc_write(uint8_t val, uint32_t reg)
{
writeb(val, ds1511_base + (reg * reg_spacing));
}
static inline void
rtc_write_alarm(uint8_t val, enum ds1511reg reg)
{
rtc_write((val | 0x80), reg);
}
static noinline uint8_t
rtc_read(enum ds1511reg reg)
{
return readb(ds1511_base + (reg * reg_spacing));
}
static inline void
rtc_disable_update(void)
{
rtc_write((rtc_read(RTC_CMD) & ~RTC_TE), RTC_CMD);
}
static void
rtc_enable_update(void)
{
rtc_write((rtc_read(RTC_CMD) | RTC_TE), RTC_CMD);
}
/*
* #define DS1511_WDOG_RESET_SUPPORT
*
* Uncomment this if you want to use these routines in
* some platform code.
*/
#ifdef DS1511_WDOG_RESET_SUPPORT
/*
* just enough code to set the watchdog timer so that it
* will reboot the system
*/
void
ds1511_wdog_set(unsigned long deciseconds)
{
/*
* the wdog timer can take 99.99 seconds
*/
deciseconds %= 10000;
/*
* set the wdog values in the wdog registers
*/
rtc_write(bin2bcd(deciseconds % 100), DS1511_WD_MSEC);
rtc_write(bin2bcd(deciseconds / 100), DS1511_WD_SEC);
/*
* set wdog enable and wdog 'steering' bit to issue a reset
*/
rtc_write(rtc_read(RTC_CMD) | DS1511_WDE | DS1511_WDS, RTC_CMD);
}
void
ds1511_wdog_disable(void)
{
/*
* clear wdog enable and wdog 'steering' bits
*/
rtc_write(rtc_read(RTC_CMD) & ~(DS1511_WDE | DS1511_WDS), RTC_CMD);
/*
* clear the wdog counter
*/
rtc_write(0, DS1511_WD_MSEC);
rtc_write(0, DS1511_WD_SEC);
}
#endif
/*
* set the rtc chip's idea of the time.
* stupidly, some callers call with year unmolested;
* and some call with year = year - 1900. thanks.
*/
static int ds1511_rtc_set_time(struct device *dev, struct rtc_time *rtc_tm)
{
u8 mon, day, dow, hrs, min, sec, yrs, cen;
unsigned long flags;
/*
* won't have to change this for a while
*/
if (rtc_tm->tm_year < 1900)
rtc_tm->tm_year += 1900;
if (rtc_tm->tm_year < 1970)
return -EINVAL;
yrs = rtc_tm->tm_year % 100;
cen = rtc_tm->tm_year / 100;
mon = rtc_tm->tm_mon + 1; /* tm_mon starts at zero */
day = rtc_tm->tm_mday;
dow = rtc_tm->tm_wday & 0x7; /* automatic BCD */
hrs = rtc_tm->tm_hour;
min = rtc_tm->tm_min;
sec = rtc_tm->tm_sec;
if ((mon > 12) || (day == 0))
return -EINVAL;
if (day > rtc_month_days(rtc_tm->tm_mon, rtc_tm->tm_year))
return -EINVAL;
if ((hrs >= 24) || (min >= 60) || (sec >= 60))
return -EINVAL;
/*
* each register is a different number of valid bits
*/
sec = bin2bcd(sec) & 0x7f;
min = bin2bcd(min) & 0x7f;
hrs = bin2bcd(hrs) & 0x3f;
day = bin2bcd(day) & 0x3f;
mon = bin2bcd(mon) & 0x1f;
yrs = bin2bcd(yrs) & 0xff;
cen = bin2bcd(cen) & 0xff;
spin_lock_irqsave(&ds1511_lock, flags);
rtc_disable_update();
rtc_write(cen, RTC_CENTURY);
rtc_write(yrs, RTC_YEAR);
rtc_write((rtc_read(RTC_MON) & 0xe0) | mon, RTC_MON);
rtc_write(day, RTC_DOM);
rtc_write(hrs, RTC_HOUR);
rtc_write(min, RTC_MIN);
rtc_write(sec, RTC_SEC);
rtc_write(dow, RTC_DOW);
rtc_enable_update();
spin_unlock_irqrestore(&ds1511_lock, flags);
return 0;
}
static int ds1511_rtc_read_time(struct device *dev, struct rtc_time *rtc_tm)
{
unsigned int century;
unsigned long flags;
spin_lock_irqsave(&ds1511_lock, flags);
rtc_disable_update();
rtc_tm->tm_sec = rtc_read(RTC_SEC) & 0x7f;
rtc_tm->tm_min = rtc_read(RTC_MIN) & 0x7f;
rtc_tm->tm_hour = rtc_read(RTC_HOUR) & 0x3f;
rtc_tm->tm_mday = rtc_read(RTC_DOM) & 0x3f;
rtc_tm->tm_wday = rtc_read(RTC_DOW) & 0x7;
rtc_tm->tm_mon = rtc_read(RTC_MON) & 0x1f;
rtc_tm->tm_year = rtc_read(RTC_YEAR) & 0x7f;
century = rtc_read(RTC_CENTURY);
rtc_enable_update();
spin_unlock_irqrestore(&ds1511_lock, flags);
rtc_tm->tm_sec = bcd2bin(rtc_tm->tm_sec);
rtc_tm->tm_min = bcd2bin(rtc_tm->tm_min);
rtc_tm->tm_hour = bcd2bin(rtc_tm->tm_hour);
rtc_tm->tm_mday = bcd2bin(rtc_tm->tm_mday);
rtc_tm->tm_wday = bcd2bin(rtc_tm->tm_wday);
rtc_tm->tm_mon = bcd2bin(rtc_tm->tm_mon);
rtc_tm->tm_year = bcd2bin(rtc_tm->tm_year);
century = bcd2bin(century) * 100;
/*
* Account for differences between how the RTC uses the values
* and how they are defined in a struct rtc_time;
*/
century += rtc_tm->tm_year;
rtc_tm->tm_year = century - 1900;
rtc_tm->tm_mon--;
if (rtc_valid_tm(rtc_tm) < 0) {
dev_err(dev, "retrieved date/time is not valid.\n");
rtc_time_to_tm(0, rtc_tm);
}
return 0;
}
/*
* write the alarm register settings
*
* we only have the use to interrupt every second, otherwise
* known as the update interrupt, or the interrupt if the whole
* date/hours/mins/secs matches. the ds1511 has many more
* permutations, but the kernel doesn't.
*/
static void
ds1511_rtc_update_alarm(struct rtc_plat_data *pdata)
{
unsigned long flags;
spin_lock_irqsave(&pdata->lock, flags);
rtc_write(pdata->alrm_mday < 0 || (pdata->irqen & RTC_UF) ?
0x80 : bin2bcd(pdata->alrm_mday) & 0x3f,
RTC_ALARM_DATE);
rtc_write(pdata->alrm_hour < 0 || (pdata->irqen & RTC_UF) ?
0x80 : bin2bcd(pdata->alrm_hour) & 0x3f,
RTC_ALARM_HOUR);
rtc_write(pdata->alrm_min < 0 || (pdata->irqen & RTC_UF) ?
0x80 : bin2bcd(pdata->alrm_min) & 0x7f,
RTC_ALARM_MIN);
rtc_write(pdata->alrm_sec < 0 || (pdata->irqen & RTC_UF) ?
0x80 : bin2bcd(pdata->alrm_sec) & 0x7f,
RTC_ALARM_SEC);
rtc_write(rtc_read(RTC_CMD) | (pdata->irqen ? RTC_TIE : 0), RTC_CMD);
rtc_read(RTC_CMD1); /* clear interrupts */
spin_unlock_irqrestore(&pdata->lock, flags);
}
static int
ds1511_rtc_set_alarm(struct device *dev, struct rtc_wkalrm *alrm)
{
struct platform_device *pdev = to_platform_device(dev);
struct rtc_plat_data *pdata = platform_get_drvdata(pdev);
if (pdata->irq <= 0)
return -EINVAL;
pdata->alrm_mday = alrm->time.tm_mday;
pdata->alrm_hour = alrm->time.tm_hour;
pdata->alrm_min = alrm->time.tm_min;
pdata->alrm_sec = alrm->time.tm_sec;
if (alrm->enabled)
pdata->irqen |= RTC_AF;
ds1511_rtc_update_alarm(pdata);
return 0;
}
static int
ds1511_rtc_read_alarm(struct device *dev, struct rtc_wkalrm *alrm)
{
struct platform_device *pdev = to_platform_device(dev);
struct rtc_plat_data *pdata = platform_get_drvdata(pdev);
if (pdata->irq <= 0)
return -EINVAL;
alrm->time.tm_mday = pdata->alrm_mday < 0 ? 0 : pdata->alrm_mday;
alrm->time.tm_hour = pdata->alrm_hour < 0 ? 0 : pdata->alrm_hour;
alrm->time.tm_min = pdata->alrm_min < 0 ? 0 : pdata->alrm_min;
alrm->time.tm_sec = pdata->alrm_sec < 0 ? 0 : pdata->alrm_sec;
alrm->enabled = (pdata->irqen & RTC_AF) ? 1 : 0;
return 0;
}
static irqreturn_t
ds1511_interrupt(int irq, void *dev_id)
{
struct platform_device *pdev = dev_id;
struct rtc_plat_data *pdata = platform_get_drvdata(pdev);
unsigned long events = 0;
spin_lock(&pdata->lock);
/*
* read and clear interrupt
*/
if (rtc_read(RTC_CMD1) & DS1511_IRQF) {
events = RTC_IRQF;
if (rtc_read(RTC_ALARM_SEC) & 0x80)
events |= RTC_UF;
else
events |= RTC_AF;
rtc_update_irq(pdata->rtc, 1, events);
}
spin_unlock(&pdata->lock);
return events ? IRQ_HANDLED : IRQ_NONE;
}
static int ds1511_rtc_alarm_irq_enable(struct device *dev, unsigned int enabled)
{
struct platform_device *pdev = to_platform_device(dev);
struct rtc_plat_data *pdata = platform_get_drvdata(pdev);
if (pdata->irq <= 0)
return -EINVAL;
if (enabled)
pdata->irqen |= RTC_AF;
else
pdata->irqen &= ~RTC_AF;
ds1511_rtc_update_alarm(pdata);
return 0;
}
static const struct rtc_class_ops ds1511_rtc_ops = {
.read_time = ds1511_rtc_read_time,
.set_time = ds1511_rtc_set_time,
.read_alarm = ds1511_rtc_read_alarm,
.set_alarm = ds1511_rtc_set_alarm,
.alarm_irq_enable = ds1511_rtc_alarm_irq_enable,
};
static int ds1511_nvram_read(void *priv, unsigned int pos, void *buf,
size_t size)
{
int i;
rtc_write(pos, DS1511_RAMADDR_LSB);
for (i = 0; i < size; i++)
*(char *)buf++ = rtc_read(DS1511_RAMDATA);
return 0;
}
static int ds1511_nvram_write(void *priv, unsigned int pos, void *buf,
size_t size)
{
int i;
rtc_write(pos, DS1511_RAMADDR_LSB);
for (i = 0; i < size; i++)
rtc_write(*(char *)buf++, DS1511_RAMDATA);
return 0;
}
static struct nvmem_config ds1511_nvmem_cfg = {
.name = "ds1511_nvram",
.word_size = 1,
.stride = 1,
.size = DS1511_RAM_MAX,
.reg_read = ds1511_nvram_read,
.reg_write = ds1511_nvram_write,
};
static int ds1511_rtc_probe(struct platform_device *pdev)
{
struct resource *res;
struct rtc_plat_data *pdata;
int ret = 0;
pdata = devm_kzalloc(&pdev->dev, sizeof(*pdata), GFP_KERNEL);
if (!pdata)
return -ENOMEM;
res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
ds1511_base = devm_ioremap_resource(&pdev->dev, res);
if (IS_ERR(ds1511_base))
return PTR_ERR(ds1511_base);
pdata->ioaddr = ds1511_base;
pdata->irq = platform_get_irq(pdev, 0);
/*
* turn on the clock and the crystal, etc.
*/
rtc_write(DS1511_BME, RTC_CMD);
rtc_write(0, RTC_CMD1);
/*
* clear the wdog counter
*/
rtc_write(0, DS1511_WD_MSEC);
rtc_write(0, DS1511_WD_SEC);
/*
* start the clock
*/
rtc_enable_update();
/*
* check for a dying bat-tree
*/
if (rtc_read(RTC_CMD1) & DS1511_BLF1)
dev_warn(&pdev->dev, "voltage-low detected.\n");
spin_lock_init(&pdata->lock);
platform_set_drvdata(pdev, pdata);
pdata->rtc = devm_rtc_allocate_device(&pdev->dev);
if (IS_ERR(pdata->rtc))
return PTR_ERR(pdata->rtc);
pdata->rtc->ops = &ds1511_rtc_ops;
ds1511_nvmem_cfg.priv = &pdev->dev;
pdata->rtc->nvmem_config = &ds1511_nvmem_cfg;
pdata->rtc->nvram_old_abi = true;
ret = rtc_register_device(pdata->rtc);
if (ret)
return ret;
/*
* if the platform has an interrupt in mind for this device,
* then by all means, set it
*/
if (pdata->irq > 0) {
rtc_read(RTC_CMD1);
if (devm_request_irq(&pdev->dev, pdata->irq, ds1511_interrupt,
IRQF_SHARED, pdev->name, pdev) < 0) {
dev_warn(&pdev->dev, "interrupt not available.\n");
pdata->irq = 0;
}
}
return 0;
}
/* work with hotplug and coldplug */
MODULE_ALIAS("platform:ds1511");
static struct platform_driver ds1511_rtc_driver = {
.probe = ds1511_rtc_probe,
.driver = {
.name = "ds1511",
},
};
module_platform_driver(ds1511_rtc_driver);
MODULE_AUTHOR("Andrew Sharp <[email protected]>");
MODULE_DESCRIPTION("Dallas DS1511 RTC driver");
MODULE_LICENSE("GPL");
|
89961.c | /*
* =============================================================================
* HSA Runtime Conformance Release License
* =============================================================================
* The University of Illinois/NCSA
* Open Source License (NCSA)
*
* Copyright (c) 2014, Advanced Micro Devices, Inc.
* All rights reserved.
*
* Developed by:
*
* AMD Research and AMD HSA Software Development
*
* Advanced Micro Devices, Inc.
*
* www.amd.com
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal with 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:
*
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimers.
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimers in
* the documentation and/or other materials provided with the distribution.
* - Neither the names of <Name of Development Group, Name of Institution>,
* nor the names of its contributors may be used to endorse or promote
* products derived from this Software without specific prior written
* permission.
*
* 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 CONTRIBUTORS 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 WITH THE SOFTWARE.
*
*/
/*
* Test Name: queue_cas_write_index_atomic
* Scope: Conformance
*
* Purpose: Verifies that the hsa_queue_cas_write_index operations is atomic,
* and 'torn' compare and swaps do not occur when this API is executed
* concurrently.
*
* Test Description:
* 1) Create a signal, assigning it an initial value of 0.
* 2) Create 4 threads, that
* a) Call hsa_queue_cas_write_index in a loop, comparing the value
* to an expected value and then advancing the value to the
* next value in the cycle.
* b) Thread 0 will exchange value to value + 1 when value%4=0
* c) Thread 1 will exchange value to value + 1 when value%4=1
* d) Thread 2 will exchange value to value + 1 when value%4=2
* e) Thread 3 will exchange value to value + 1 when value%4=3
* 4) Run the threads for millions of iterations of exchanges, with no
* explicit synchronization between the threads.
* 5) Repeat for all versions of the hsa_queue_case_write_index APIs, i.e. acquire,
* release, relaxed and acq_rel memory ordering versions.
*
* Expected Results: The value of the write index should increase monotonically, and
* advance through all expected values.
*/
#include <hsa.h>
#include <agent_utils.h>
#include <concurrent_utils.h>
#include <framework.h>
#include <stdlib.h>
#define QUEUE_WRITE_INDEX_NUM_OF_CAS_ATOMIC 1*1024*1024
typedef struct write_index_cas_thread_data_s {
hsa_queue_t* queue;
int thread_index;
int num_threads;
uint64_t termination_value;
int memory_ordering_type;
} write_index_cas_thread_data_t;
void thread_proc_write_index_cas_atomic(void* data) {
write_index_cas_thread_data_t* thread_data = (write_index_cas_thread_data_t*)data;
int ii;
for (ii = thread_data->thread_index; ii < thread_data->termination_value; ii += thread_data->num_threads) {
switch (thread_data->memory_ordering_type) {
case 0:
while ((uint64_t)ii != hsa_queue_cas_write_index_acq_rel(thread_data->queue, ii, ii + 1))
{}
break;
case 1:
while ((uint64_t)ii != hsa_queue_cas_write_index_acquire(thread_data->queue, ii, ii + 1))
{}
break;
case 2:
while ((uint64_t)ii != hsa_queue_cas_write_index_relaxed(thread_data->queue, ii, ii + 1))
{}
break;
case 3:
while ((uint64_t)ii != hsa_queue_cas_write_index_release(thread_data->queue, ii, ii + 1))
{}
break;
}
}
}
int test_queue_write_index_cas_atomic() {
hsa_status_t status;
status = hsa_init();
ASSERT(status == HSA_STATUS_SUCCESS);
struct agent_list_s agent_list;
get_agent_list(&agent_list);
int ii;
for (ii = 0; ii < agent_list.num_agents; ++ii) {
// Check if the queue supports dispatch
uint32_t features = 0;
status = hsa_agent_get_info(agent_list.agents[ii], HSA_AGENT_INFO_FEATURE, &features);
ASSERT(HSA_STATUS_SUCCESS == status);
if (0 == (features & HSA_AGENT_FEATURE_KERNEL_DISPATCH)) {
continue;
}
// Get max number of queues
uint32_t queue_max;
status = hsa_agent_get_info(agent_list.agents[ii], HSA_AGENT_INFO_QUEUES_MAX, &queue_max);
ASSERT(HSA_STATUS_SUCCESS == status);
if (queue_max < 1) {
// This agent does not support any queues
continue;
}
// Get the queue size
uint32_t queue_size;
status = hsa_agent_get_info(agent_list.agents[ii], HSA_AGENT_INFO_QUEUE_MAX_SIZE, &queue_size);
ASSERT(HSA_STATUS_SUCCESS == status);
// Create a queue
hsa_queue_t* queue;
status = hsa_queue_create(agent_list.agents[ii], queue_size, HSA_QUEUE_TYPE_SINGLE, NULL, NULL, UINT32_MAX, UINT32_MAX, &queue);
ASSERT(HSA_STATUS_SUCCESS == status);
// Repeat for all four versions of hsa_queue_cas_write_index
int memory_ordering_type;
for (memory_ordering_type = 0; memory_ordering_type < 4; ++memory_ordering_type) {
// Thread data
const int num_threads = 4;
write_index_cas_thread_data_t thread_data[num_threads];
// Create the test group
struct test_group* tg = test_group_create(num_threads);
int jj;
for (jj = 0; jj < num_threads; ++jj) {
thread_data[jj].queue = queue;
thread_data[jj].thread_index = jj;
thread_data[jj].num_threads = num_threads;
thread_data[jj].memory_ordering_type = memory_ordering_type;
thread_data[jj].termination_value = QUEUE_WRITE_INDEX_NUM_OF_CAS_ATOMIC;
test_group_add(tg, &thread_proc_write_index_cas_atomic, thread_data + jj, 1);
}
test_group_thread_create(tg);
test_group_start(tg);
test_group_wait(tg);
test_group_exit(tg);
test_group_destroy(tg);
// Verify the write_index
uint64_t write_index = hsa_queue_load_write_index_relaxed(queue);
uint64_t expected = (uint64_t)(QUEUE_WRITE_INDEX_NUM_OF_CAS_ATOMIC);
ASSERT(expected == write_index);
// Restore the write_index of the queue
hsa_queue_store_write_index_release(queue, 0);
}
status = hsa_queue_destroy(queue);
ASSERT(HSA_STATUS_SUCCESS == status);
}
status = hsa_shut_down();
ASSERT(status == HSA_STATUS_SUCCESS);
free_agent_list(&agent_list);
return 0;
}
|