content
stringlengths
12
2.72M
<reponame>junlon2006/adpcm-parse<filename>test.c #include <stdio.h> #include <string.h> #include <stdlib.h> #include <dirent.h> #include <sys/stat.h> #include <unistd.h> #include <sys/types.h> #include <iostream> using namespace std; static void listDir(char *path) { DIR *pDir; struct dirent *ent; int i=0; char childpath[512]; static int cnt = 0; pDir = opendir(path); memset(childpath, 0, sizeof(childpath)); while ((ent=readdir(pDir))!= NULL) { if (ent->d_type & DT_DIR) { if (strcmp(ent->d_name,".") == 0 || strcmp(ent->d_name,"..") == 0) { continue; } sprintf(childpath,"%s/%s",path,ent->d_name); printf("path:%s/n", childpath); listDir(childpath); } else { cnt++; cout<<cnt<<"hhh"<<ent->d_name<<endl; char name[512] = {0}; char buf[512] = {0}; int index = 0; while (ent->d_name) { if (ent->d_name[index] == '.') { break; } name[index] = ent->d_name[index]; index++; } sprintf(buf, "bin/adpcm -d -i audio/%s -o out/%s.pcm", ent->d_name, name); cout<<buf<<endl; system(buf); } } } int main(int argc,char *argv[]) { listDir(argv[1]); return 0; }
#import <Foundation/Foundation.h> #import <UIKit/UIKit.h> #import <UIKit/UIApplication.h> @interface AnimationView : UIView { id table_; NSArray* animationNames_; } @end
<gh_stars>10-100 #include <stdint.h> #include "global.h" #include "stc15.h" #include "display.h" #include "utility.h" #include "ds1302.h" #include "sound.h" #if HAS_NY3P_SPEECH void speakTime() { uint8_t h,m; if (Select_12){ h = bcdToDec(clockRam.hr & 0x1F); m = bcdToDec(clockRam.min); if ( m == 0 ){ // just speak hour and AM/PM speakItem(h); speakAM_PM(); } else if ( m >= 1 & m <= 9){ // hour + "oh" + "nine" + am/pm speakItem(h); speakItem(sndOh); speakItem(m); speakAM_PM(); } else if ( m >= 10 & m <= 20){ // hour + minute + am/pm speakItem(h); speakItem(m); speakAM_PM(); } else {//if ( m >= 21 & m <= 59) // hour + minuteTems + minute + am/pm speakItem(h); speakItem(m/10+sndTwenty-2); speakItem(m % 10); speakAM_PM(); } } if (!Select_12){ // 24 hour time here h = bcdToDec(clockRam.hr); m = bcdToDec(clockRam.min); if ( m == 0 ){ // just speak hour and ohClock speakItem(h); speakItem(sndOhClock); } else if ( m >= 1 & m <= 9){ // hour + "oh" + "nine" speakItem(h); speakItem(sndOh); speakItem(m); } else if ( m >= 10 & m <= 20){ // hour + minute speakItem(h); speakItem(m); } else {//if ( m >= 21 & m <= 59) // hour + minuteTems + minute speakItem(h); speakItem(m/10+sndTwenty-2); speakItem(m % 10); } } } void speakAM_PM() { if (AM_PM) speakItem(sndPM); else speakItem(sndAM); } void speakItem(uint8_t bitCount) { uint8_t i; resetSound(); for( i = 0; i < bitCount; i++ ) sendOneBit(); while (NY3P_BZY) updateClock(); resetSound(); } void sendOneBit() { NY3P_DAT = 1; waitS1Clk(); NY3P_DAT = 0; waitS1Clk(); } void waitS1Clk() { soundTimer = 5; // 250us pulses while( soundTimer ) ; } void resetSound() { NY3P_RST = 0; // should be at zero but force anyway waitS1Clk(); NY3P_RST = 1; // =1 is the actual reset waitS1Clk(); NY3P_RST = 0; // and exit with =0 waitS1Clk(); } #endif
/** * This header is generated by class-dump-z 0.2-0. * class-dump-z is Copyright (C) 2009 by KennyTM~, licensed under GPLv3. * * Source: /System/Library/PrivateFrameworks/Symbolication.framework/Symbolication */ #import "Symbolication-Structs.h" #import "VMURangeArray.h" @interface VMUNonOverlappingRangeArray : VMURangeArray { } -(void)mergeRange:(VMURange)range; -(void)mergeRange:(VMURange)range excludingRanges:(id)ranges; -(void)mergeRanges:(id)ranges excludingRanges:(id)ranges2; // inherited: -(unsigned long long)sumLengths; -(void)_mergeAllBitsOfRange:(VMURange)range excludingRanges:(id)ranges; -(id)subtract:(id)subtract; -(VMURange)largestUnusedWithInUse:(id)use; @end
#pragma once #include "xo/xo_types.h" #include "sphere.h" #include "box.h" #include "cylinder.h" #include "capsule.h" #include "cone.h" #include "plane.h" #include "aabb.h" #include <variant> namespace xo { using shape = std::variant< sphere, box, cylinder, capsule, cone, plane >; XO_API bool from_prop_node( const prop_node& pn, sphere& s ); XO_API bool from_prop_node( const prop_node& pn, box& s ); XO_API bool from_prop_node( const prop_node& pn, cylinder& s ); XO_API bool from_prop_node( const prop_node& pn, capsule& s ); XO_API bool from_prop_node( const prop_node& pn, cone& s ); XO_API bool from_prop_node( const prop_node& pn, plane& s ); XO_API bool from_prop_node( const prop_node& pn, shape& s ); XO_API prop_node to_prop_node( const sphere& s ); XO_API prop_node to_prop_node( const box& s ); XO_API prop_node to_prop_node( const cylinder& s ); XO_API prop_node to_prop_node( const capsule& s ); XO_API prop_node to_prop_node( const cone& s ); XO_API prop_node to_prop_node( const plane& s ); XO_API prop_node to_prop_node( const shape& s ); XO_API float volume( const shape& s ); XO_API vec3f dim( const shape& s ); XO_API aabbf aabb( const shape& s, const transformf& t ); XO_API vec3f inertia( const shape& s, float density ); XO_API void scale( shape& s, float f ); }
<reponame>suda-morris/SUDA_3518E<filename>kernel/linux-3.4.y/drivers/spi/spidev_info.c<gh_stars>1-10 /* linux/drivers/spi/spidev_info.c * * HISILICON SPI Controller driver * * Copyright (c) 2014 Hisilicon Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * History: * 26-September-2014 create this file * 31-July-2015 modify */ #include <linux/init.h> #include <linux/module.h> #include <linux/ioctl.h> #include <linux/fs.h> #include <linux/device.h> #include <linux/err.h> #include <linux/list.h> #include <linux/errno.h> #include <linux/mutex.h> #include <linux/slab.h> #include <linux/compat.h> #include <linux/spi/spi.h> #define DEFAULT_SPEED_HZ 2000000 /* #define HI_SPIDEV_INFO_DEBUG */ #ifdef HI_SPIDEV_INFO_DEBUG #define hi_msg(x...) \ do { \ printk(KERN_NOTICE "%s->%d: ", __func__, __LINE__); \ printk(KERN_NOTICE x); \ } while (0) #else #define hi_msg(x...) do { } while (0) #endif /*--------------------------------------------------------*/ int hi_spidev_get_info(struct spi_board_info **info); /* * SPI device information */ static struct spi_board_info *spidev_info; static struct spi_device **spidev; /*--------------------------------------------------------*/ static int __init spidev_info_init(void) { int i, num; struct spi_master *master; hi_msg("compile time:%s %s, %s\n" , __DATE__, __TIME__, __func__); num = hi_spidev_get_info(&spidev_info); if (num <= 0) { dev_err(NULL, "%s: num of spidev is %d\n", __func__, num); return -ENXIO; } spidev = kzalloc(sizeof(struct spi_device *) * num, GFP_KERNEL); if (!spidev) { dev_err(NULL, "%s: kzalloc error!\n", __func__); return -ENOMEM; } for (i = 0; i < num; i++) { master = spi_busnum_to_master(spidev_info[i].bus_num); if (master) { spidev[i] = spi_new_device(master, &spidev_info[i]); if (!spidev[i]) { dev_err(NULL, "%s: spi_new_device() error!\n", __func__); while (--i >= 0) spi_unregister_device(spidev[i]); kfree(spidev); return -ENXIO; } } else { dev_err(NULL, "%s: spi_busnum_to_master() error!\n", __func__); while (--i >= 0) spi_unregister_device(spidev[i]); kfree(spidev); return -ENXIO; } } return 0; } module_init(spidev_info_init); static void __exit spidev_info_exit(void) { unsigned int num; hi_msg("\n"); num = hi_spidev_get_info(&spidev_info); while (--num >= 0) spi_unregister_device(spidev[num]); kfree(spidev); } module_exit(spidev_info_exit); MODULE_AUTHOR("BVT OSDRV"); MODULE_DESCRIPTION("User mode SPI device info"); MODULE_LICENSE("GPL");
<reponame>afeng11/tomato-arm /* * iio/adc/max1363.c * Copyright (C) 2008-2010 <NAME> * * based on linux/drivers/i2c/chips/max123x * Copyright (C) 2002-2004 <NAME> * * based on linux/drivers/acron/char/pcf8583.c * Copyright (C) 2000 <NAME> * * 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. * * max1363.c * * Partial support for max1363 and similar chips. * * Not currently implemented. * * - Control of internal reference. */ #include <linux/interrupt.h> #include <linux/workqueue.h> #include <linux/device.h> #include <linux/kernel.h> #include <linux/sysfs.h> #include <linux/list.h> #include <linux/i2c.h> #include <linux/regulator/consumer.h> #include <linux/slab.h> #include <linux/err.h> #include "../iio.h" #include "../sysfs.h" #include "../ring_generic.h" #include "adc.h" #include "max1363.h" /* Here we claim all are 16 bits. This currently does no harm and saves * us a lot of scan element listings */ #define MAX1363_SCAN_EL(number) \ IIO_SCAN_EL_C(in##number, number, IIO_UNSIGNED(16), 0, NULL); #define MAX1363_SCAN_EL_D(p, n, number) \ IIO_SCAN_NAMED_EL_C(in##p##m##in##n, in##p-in##n, \ number, IIO_SIGNED(16), 0, NULL); static MAX1363_SCAN_EL(0); static MAX1363_SCAN_EL(1); static MAX1363_SCAN_EL(2); static MAX1363_SCAN_EL(3); static MAX1363_SCAN_EL(4); static MAX1363_SCAN_EL(5); static MAX1363_SCAN_EL(6); static MAX1363_SCAN_EL(7); static MAX1363_SCAN_EL(8); static MAX1363_SCAN_EL(9); static MAX1363_SCAN_EL(10); static MAX1363_SCAN_EL(11); static MAX1363_SCAN_EL_D(0, 1, 12); static MAX1363_SCAN_EL_D(2, 3, 13); static MAX1363_SCAN_EL_D(4, 5, 14); static MAX1363_SCAN_EL_D(6, 7, 15); static MAX1363_SCAN_EL_D(8, 9, 16); static MAX1363_SCAN_EL_D(10, 11, 17); static MAX1363_SCAN_EL_D(1, 0, 18); static MAX1363_SCAN_EL_D(3, 2, 19); static MAX1363_SCAN_EL_D(5, 4, 20); static MAX1363_SCAN_EL_D(7, 6, 21); static MAX1363_SCAN_EL_D(9, 8, 22); static MAX1363_SCAN_EL_D(11, 10, 23); static const struct max1363_mode max1363_mode_table[] = { /* All of the single channel options first */ MAX1363_MODE_SINGLE(0, 1 << 0), MAX1363_MODE_SINGLE(1, 1 << 1), MAX1363_MODE_SINGLE(2, 1 << 2), MAX1363_MODE_SINGLE(3, 1 << 3), MAX1363_MODE_SINGLE(4, 1 << 4), MAX1363_MODE_SINGLE(5, 1 << 5), MAX1363_MODE_SINGLE(6, 1 << 6), MAX1363_MODE_SINGLE(7, 1 << 7), MAX1363_MODE_SINGLE(8, 1 << 8), MAX1363_MODE_SINGLE(9, 1 << 9), MAX1363_MODE_SINGLE(10, 1 << 10), MAX1363_MODE_SINGLE(11, 1 << 11), MAX1363_MODE_DIFF_SINGLE(0, 1, 1 << 12), MAX1363_MODE_DIFF_SINGLE(2, 3, 1 << 13), MAX1363_MODE_DIFF_SINGLE(4, 5, 1 << 14), MAX1363_MODE_DIFF_SINGLE(6, 7, 1 << 15), MAX1363_MODE_DIFF_SINGLE(8, 9, 1 << 16), MAX1363_MODE_DIFF_SINGLE(10, 11, 1 << 17), MAX1363_MODE_DIFF_SINGLE(1, 0, 1 << 18), MAX1363_MODE_DIFF_SINGLE(3, 2, 1 << 19), MAX1363_MODE_DIFF_SINGLE(5, 4, 1 << 20), MAX1363_MODE_DIFF_SINGLE(7, 6, 1 << 21), MAX1363_MODE_DIFF_SINGLE(9, 8, 1 << 22), MAX1363_MODE_DIFF_SINGLE(11, 10, 1 << 23), /* The multichannel scans next */ MAX1363_MODE_SCAN_TO_CHANNEL(1, 0x003), MAX1363_MODE_SCAN_TO_CHANNEL(2, 0x007), MAX1236_MODE_SCAN_MID_TO_CHANNEL(2, 3, 0x00C), MAX1363_MODE_SCAN_TO_CHANNEL(3, 0x00F), MAX1363_MODE_SCAN_TO_CHANNEL(4, 0x01F), MAX1363_MODE_SCAN_TO_CHANNEL(5, 0x03F), MAX1363_MODE_SCAN_TO_CHANNEL(6, 0x07F), MAX1236_MODE_SCAN_MID_TO_CHANNEL(6, 7, 0x0C0), MAX1363_MODE_SCAN_TO_CHANNEL(7, 0x0FF), MAX1236_MODE_SCAN_MID_TO_CHANNEL(6, 8, 0x1C0), MAX1363_MODE_SCAN_TO_CHANNEL(8, 0x1FF), MAX1236_MODE_SCAN_MID_TO_CHANNEL(6, 9, 0x3C0), MAX1363_MODE_SCAN_TO_CHANNEL(9, 0x3FF), MAX1236_MODE_SCAN_MID_TO_CHANNEL(6, 10, 0x7C0), MAX1363_MODE_SCAN_TO_CHANNEL(10, 0x7FF), MAX1236_MODE_SCAN_MID_TO_CHANNEL(6, 11, 0xFC0), MAX1363_MODE_SCAN_TO_CHANNEL(11, 0xFFF), MAX1363_MODE_DIFF_SCAN_TO_CHANNEL(2, 2, 0x003000), MAX1363_MODE_DIFF_SCAN_TO_CHANNEL(4, 3, 0x007000), MAX1363_MODE_DIFF_SCAN_TO_CHANNEL(6, 4, 0x00F000), MAX1236_MODE_DIFF_SCAN_MID_TO_CHANNEL(8, 2, 0x018000), MAX1363_MODE_DIFF_SCAN_TO_CHANNEL(8, 5, 0x01F000), MAX1236_MODE_DIFF_SCAN_MID_TO_CHANNEL(10, 3, 0x038000), MAX1363_MODE_DIFF_SCAN_TO_CHANNEL(10, 6, 0x3F000), MAX1363_MODE_DIFF_SCAN_TO_CHANNEL(3, 2, 0x0C0000), MAX1363_MODE_DIFF_SCAN_TO_CHANNEL(5, 3, 0x1C0000), MAX1363_MODE_DIFF_SCAN_TO_CHANNEL(7, 4, 0x3C0000), MAX1236_MODE_DIFF_SCAN_MID_TO_CHANNEL(9, 2, 0x600000), MAX1363_MODE_DIFF_SCAN_TO_CHANNEL(9, 5, 0x7C0000), MAX1236_MODE_DIFF_SCAN_MID_TO_CHANNEL(11, 3, 0xE00000), MAX1363_MODE_DIFF_SCAN_TO_CHANNEL(11, 6, 0xFC0000), }; const struct max1363_mode *max1363_match_mode(u32 mask, const struct max1363_chip_info *ci) { int i; if (mask) for (i = 0; i < ci->num_modes; i++) if (!((~max1363_mode_table[ci->mode_list[i]].modemask) & mask)) return &max1363_mode_table[ci->mode_list[i]]; return NULL; } static ssize_t max1363_show_precision(struct device *dev, struct device_attribute *attr, char *buf) { struct iio_dev *dev_info = dev_get_drvdata(dev); struct max1363_state *st = iio_dev_get_devdata(dev_info); return sprintf(buf, "%d\n", st->chip_info->bits); } static IIO_DEVICE_ATTR(in_precision, S_IRUGO, max1363_show_precision, NULL, 0); static int max1363_write_basic_config(struct i2c_client *client, unsigned char d1, unsigned char d2) { int ret; u8 *tx_buf = kmalloc(2, GFP_KERNEL); if (!tx_buf) return -ENOMEM; tx_buf[0] = d1; tx_buf[1] = d2; ret = i2c_master_send(client, tx_buf, 2); kfree(tx_buf); return (ret > 0) ? 0 : ret; } int max1363_set_scan_mode(struct max1363_state *st) { st->configbyte &= ~(MAX1363_CHANNEL_SEL_MASK | MAX1363_SCAN_MASK | MAX1363_SE_DE_MASK); st->configbyte |= st->current_mode->conf; return max1363_write_basic_config(st->client, st->setupbyte, st->configbyte); } static ssize_t max1363_read_single_channel(struct device *dev, struct device_attribute *attr, char *buf) { struct iio_dev *dev_info = dev_get_drvdata(dev); struct max1363_state *st = iio_dev_get_devdata(dev_info); struct iio_dev_attr *this_attr = to_iio_dev_attr(attr); struct i2c_client *client = st->client; int ret = 0, len = 0; s32 data ; char rxbuf[2]; long mask; mutex_lock(&dev_info->mlock); /* * If monitor mode is enabled, the method for reading a single * channel will have to be rather different and has not yet * been implemented. */ if (st->monitor_on) { ret = -EBUSY; goto error_ret; } /* If ring buffer capture is occuring, query the buffer */ if (iio_ring_enabled(dev_info)) { mask = max1363_mode_table[this_attr->address].modemask; data = max1363_single_channel_from_ring(mask, st); if (data < 0) { ret = data; goto error_ret; } } else { /* Check to see if current scan mode is correct */ if (st->current_mode != &max1363_mode_table[this_attr->address]) { /* Update scan mode if needed */ st->current_mode = &max1363_mode_table[this_attr->address]; ret = max1363_set_scan_mode(st); if (ret) goto error_ret; } if (st->chip_info->bits != 8) { /* Get reading */ data = i2c_master_recv(client, rxbuf, 2); if (data < 0) { ret = data; goto error_ret; } data = (s32)(rxbuf[1]) | ((s32)(rxbuf[0] & 0x0F)) << 8; } else { /* Get reading */ data = i2c_master_recv(client, rxbuf, 1); if (data < 0) { ret = data; goto error_ret; } data = rxbuf[0]; } } /* Pretty print the result */ len = sprintf(buf, "%u\n", data); error_ret: mutex_unlock(&dev_info->mlock); return ret ? ret : len; } /* Direct read attribtues */ static IIO_DEV_ATTR_IN_RAW(0, max1363_read_single_channel, _s0); static IIO_DEV_ATTR_IN_RAW(1, max1363_read_single_channel, _s1); static IIO_DEV_ATTR_IN_RAW(2, max1363_read_single_channel, _s2); static IIO_DEV_ATTR_IN_RAW(3, max1363_read_single_channel, _s3); static IIO_DEV_ATTR_IN_RAW(4, max1363_read_single_channel, _s4); static IIO_DEV_ATTR_IN_RAW(5, max1363_read_single_channel, _s5); static IIO_DEV_ATTR_IN_RAW(6, max1363_read_single_channel, _s6); static IIO_DEV_ATTR_IN_RAW(7, max1363_read_single_channel, _s7); static IIO_DEV_ATTR_IN_RAW(8, max1363_read_single_channel, _s8); static IIO_DEV_ATTR_IN_RAW(9, max1363_read_single_channel, _s9); static IIO_DEV_ATTR_IN_RAW(10, max1363_read_single_channel, _s10); static IIO_DEV_ATTR_IN_RAW(11, max1363_read_single_channel, _s11); static IIO_DEV_ATTR_IN_DIFF_RAW(0, 1, max1363_read_single_channel, d0m1); static IIO_DEV_ATTR_IN_DIFF_RAW(2, 3, max1363_read_single_channel, d2m3); static IIO_DEV_ATTR_IN_DIFF_RAW(4, 5, max1363_read_single_channel, d4m5); static IIO_DEV_ATTR_IN_DIFF_RAW(6, 7, max1363_read_single_channel, d6m7); static IIO_DEV_ATTR_IN_DIFF_RAW(8, 9, max1363_read_single_channel, d8m9); static IIO_DEV_ATTR_IN_DIFF_RAW(10, 11, max1363_read_single_channel, d10m11); static IIO_DEV_ATTR_IN_DIFF_RAW(1, 0, max1363_read_single_channel, d1m0); static IIO_DEV_ATTR_IN_DIFF_RAW(3, 2, max1363_read_single_channel, d3m2); static IIO_DEV_ATTR_IN_DIFF_RAW(5, 4, max1363_read_single_channel, d5m4); static IIO_DEV_ATTR_IN_DIFF_RAW(7, 6, max1363_read_single_channel, d7m6); static IIO_DEV_ATTR_IN_DIFF_RAW(9, 8, max1363_read_single_channel, d9m8); static IIO_DEV_ATTR_IN_DIFF_RAW(11, 10, max1363_read_single_channel, d11m10); static ssize_t max1363_show_scale(struct device *dev, struct device_attribute *attr, char *buf) { /* Driver currently only support internal vref */ struct iio_dev *dev_info = dev_get_drvdata(dev); struct max1363_state *st = iio_dev_get_devdata(dev_info); /* Corresponds to Vref / 2^(bits) */ if ((1 << (st->chip_info->bits + 1)) > st->chip_info->int_vref_mv) return sprintf(buf, "0.5\n"); else return sprintf(buf, "%d\n", st->chip_info->int_vref_mv >> st->chip_info->bits); } static IIO_DEVICE_ATTR(in_scale, S_IRUGO, max1363_show_scale, NULL, 0); static ssize_t max1363_show_name(struct device *dev, struct device_attribute *attr, char *buf) { struct iio_dev *dev_info = dev_get_drvdata(dev); struct max1363_state *st = iio_dev_get_devdata(dev_info); return sprintf(buf, "%s\n", st->client->name); } static IIO_DEVICE_ATTR(name, S_IRUGO, max1363_show_name, NULL, 0); /* Applies to max1363 */ static const enum max1363_modes max1363_mode_list[] = { _s0, _s1, _s2, _s3, s0to1, s0to2, s0to3, d0m1, d2m3, d1m0, d3m2, d0m1to2m3, d1m0to3m2, }; static struct attribute *max1363_device_attrs[] = { &iio_dev_attr_in0_raw.dev_attr.attr, &iio_dev_attr_in1_raw.dev_attr.attr, &iio_dev_attr_in2_raw.dev_attr.attr, &iio_dev_attr_in3_raw.dev_attr.attr, &iio_dev_attr_in0min1_raw.dev_attr.attr, &iio_dev_attr_in2min3_raw.dev_attr.attr, &iio_dev_attr_in1min0_raw.dev_attr.attr, &iio_dev_attr_in3min2_raw.dev_attr.attr, &iio_dev_attr_name.dev_attr.attr, &iio_dev_attr_in_scale.dev_attr.attr, NULL }; static struct attribute_group max1363_dev_attr_group = { .attrs = max1363_device_attrs, }; static struct attribute *max1363_scan_el_attrs[] = { &iio_scan_el_in0.dev_attr.attr, &iio_scan_el_in1.dev_attr.attr, &iio_scan_el_in2.dev_attr.attr, &iio_scan_el_in3.dev_attr.attr, &iio_scan_el_in0min1.dev_attr.attr, &iio_scan_el_in2min3.dev_attr.attr, &iio_scan_el_in1min0.dev_attr.attr, &iio_scan_el_in3min2.dev_attr.attr, &iio_dev_attr_in_precision.dev_attr.attr, NULL, }; static struct attribute_group max1363_scan_el_group = { .name = "scan_elements", .attrs = max1363_scan_el_attrs, }; /* Appies to max1236, max1237 */ static const enum max1363_modes max1236_mode_list[] = { _s0, _s1, _s2, _s3, s0to1, s0to2, s0to3, d0m1, d2m3, d1m0, d3m2, d0m1to2m3, d1m0to3m2, s2to3, }; /* Applies to max1238, max1239 */ static const enum max1363_modes max1238_mode_list[] = { _s0, _s1, _s2, _s3, _s4, _s5, _s6, _s7, _s8, _s9, _s10, _s11, s0to1, s0to2, s0to3, s0to4, s0to5, s0to6, s0to7, s0to8, s0to9, s0to10, s0to11, d0m1, d2m3, d4m5, d6m7, d8m9, d10m11, d1m0, d3m2, d5m4, d7m6, d9m8, d11m10, d0m1to2m3, d0m1to4m5, d0m1to6m7, d0m1to8m9, d0m1to10m11, d1m0to3m2, d1m0to5m4, d1m0to7m6, d1m0to9m8, d1m0to11m10, s6to7, s6to8, s6to9, s6to10, s6to11, d6m7to8m9, d6m7to10m11, d7m6to9m8, d7m6to11m10, }; static struct attribute *max1238_device_attrs[] = { &iio_dev_attr_in0_raw.dev_attr.attr, &iio_dev_attr_in1_raw.dev_attr.attr, &iio_dev_attr_in2_raw.dev_attr.attr, &iio_dev_attr_in3_raw.dev_attr.attr, &iio_dev_attr_in4_raw.dev_attr.attr, &iio_dev_attr_in5_raw.dev_attr.attr, &iio_dev_attr_in6_raw.dev_attr.attr, &iio_dev_attr_in7_raw.dev_attr.attr, &iio_dev_attr_in8_raw.dev_attr.attr, &iio_dev_attr_in9_raw.dev_attr.attr, &iio_dev_attr_in10_raw.dev_attr.attr, &iio_dev_attr_in11_raw.dev_attr.attr, &iio_dev_attr_in0min1_raw.dev_attr.attr, &iio_dev_attr_in2min3_raw.dev_attr.attr, &iio_dev_attr_in4min5_raw.dev_attr.attr, &iio_dev_attr_in6min7_raw.dev_attr.attr, &iio_dev_attr_in8min9_raw.dev_attr.attr, &iio_dev_attr_in10min11_raw.dev_attr.attr, &iio_dev_attr_in1min0_raw.dev_attr.attr, &iio_dev_attr_in3min2_raw.dev_attr.attr, &iio_dev_attr_in5min4_raw.dev_attr.attr, &iio_dev_attr_in7min6_raw.dev_attr.attr, &iio_dev_attr_in9min8_raw.dev_attr.attr, &iio_dev_attr_in11min10_raw.dev_attr.attr, &iio_dev_attr_name.dev_attr.attr, &iio_dev_attr_in_scale.dev_attr.attr, NULL }; static struct attribute_group max1238_dev_attr_group = { .attrs = max1238_device_attrs, }; static struct attribute *max1238_scan_el_attrs[] = { &iio_scan_el_in0.dev_attr.attr, &iio_scan_el_in1.dev_attr.attr, &iio_scan_el_in2.dev_attr.attr, &iio_scan_el_in3.dev_attr.attr, &iio_scan_el_in4.dev_attr.attr, &iio_scan_el_in5.dev_attr.attr, &iio_scan_el_in6.dev_attr.attr, &iio_scan_el_in7.dev_attr.attr, &iio_scan_el_in8.dev_attr.attr, &iio_scan_el_in9.dev_attr.attr, &iio_scan_el_in10.dev_attr.attr, &iio_scan_el_in11.dev_attr.attr, &iio_scan_el_in0min1.dev_attr.attr, &iio_scan_el_in2min3.dev_attr.attr, &iio_scan_el_in4min5.dev_attr.attr, &iio_scan_el_in6min7.dev_attr.attr, &iio_scan_el_in8min9.dev_attr.attr, &iio_scan_el_in10min11.dev_attr.attr, &iio_scan_el_in1min0.dev_attr.attr, &iio_scan_el_in3min2.dev_attr.attr, &iio_scan_el_in5min4.dev_attr.attr, &iio_scan_el_in7min6.dev_attr.attr, &iio_scan_el_in9min8.dev_attr.attr, &iio_scan_el_in11min10.dev_attr.attr, &iio_dev_attr_in_precision.dev_attr.attr, NULL, }; static struct attribute_group max1238_scan_el_group = { .name = "scan_elements", .attrs = max1238_scan_el_attrs, }; static const enum max1363_modes max11607_mode_list[] = { _s0, _s1, _s2, _s3, s0to1, s0to2, s0to3, s2to3, d0m1, d2m3, d1m0, d3m2, d0m1to2m3, d1m0to3m2, }; static const enum max1363_modes max11608_mode_list[] = { _s0, _s1, _s2, _s3, _s4, _s5, _s6, _s7, s0to1, s0to2, s0to3, s0to4, s0to5, s0to6, s0to7, s6to7, d0m1, d2m3, d4m5, d6m7, d1m0, d3m2, d5m4, d7m6, d0m1to2m3, d0m1to4m5, d0m1to6m7, d1m0to3m2, d1m0to5m4, d1m0to7m6, }; static struct attribute *max11608_device_attrs[] = { &iio_dev_attr_in0_raw.dev_attr.attr, &iio_dev_attr_in1_raw.dev_attr.attr, &iio_dev_attr_in2_raw.dev_attr.attr, &iio_dev_attr_in3_raw.dev_attr.attr, &iio_dev_attr_in4_raw.dev_attr.attr, &iio_dev_attr_in5_raw.dev_attr.attr, &iio_dev_attr_in6_raw.dev_attr.attr, &iio_dev_attr_in7_raw.dev_attr.attr, &iio_dev_attr_in0min1_raw.dev_attr.attr, &iio_dev_attr_in2min3_raw.dev_attr.attr, &iio_dev_attr_in4min5_raw.dev_attr.attr, &iio_dev_attr_in6min7_raw.dev_attr.attr, &iio_dev_attr_in1min0_raw.dev_attr.attr, &iio_dev_attr_in3min2_raw.dev_attr.attr, &iio_dev_attr_in5min4_raw.dev_attr.attr, &iio_dev_attr_in7min6_raw.dev_attr.attr, &iio_dev_attr_name.dev_attr.attr, &iio_dev_attr_in_scale.dev_attr.attr, NULL }; static struct attribute_group max11608_dev_attr_group = { .attrs = max11608_device_attrs, }; static struct attribute *max11608_scan_el_attrs[] = { &iio_scan_el_in0.dev_attr.attr, &iio_scan_el_in1.dev_attr.attr, &iio_scan_el_in2.dev_attr.attr, &iio_scan_el_in3.dev_attr.attr, &iio_scan_el_in4.dev_attr.attr, &iio_scan_el_in5.dev_attr.attr, &iio_scan_el_in6.dev_attr.attr, &iio_scan_el_in7.dev_attr.attr, &iio_scan_el_in0min1.dev_attr.attr, &iio_scan_el_in2min3.dev_attr.attr, &iio_scan_el_in4min5.dev_attr.attr, &iio_scan_el_in6min7.dev_attr.attr, &iio_scan_el_in1min0.dev_attr.attr, &iio_scan_el_in3min2.dev_attr.attr, &iio_scan_el_in5min4.dev_attr.attr, &iio_scan_el_in7min6.dev_attr.attr, &iio_dev_attr_in_precision.dev_attr.attr, }; static struct attribute_group max11608_scan_el_group = { .name = "scan_elements", .attrs = max11608_scan_el_attrs, }; enum { max1361, max1362, max1363, max1364, max1036, max1037, max1038, max1039, max1136, max1137, max1138, max1139, max1236, max1237, max1238, max1239, max11600, max11601, max11602, max11603, max11604, max11605, max11606, max11607, max11608, max11609, max11610, max11611, max11612, max11613, max11614, max11615, max11616, max11617, }; /* max1363 and max1368 tested - rest from data sheet */ static const struct max1363_chip_info max1363_chip_info_tbl[] = { [max1361] = { .num_inputs = 4, .bits = 10, .int_vref_mv = 2048, .monitor_mode = 1, .mode_list = max1363_mode_list, .num_modes = ARRAY_SIZE(max1363_mode_list), .default_mode = s0to3, .dev_attrs = &max1363_dev_attr_group, .scan_attrs = &max1363_scan_el_group, }, [max1362] = { .num_inputs = 4, .bits = 10, .int_vref_mv = 4096, .monitor_mode = 1, .mode_list = max1363_mode_list, .num_modes = ARRAY_SIZE(max1363_mode_list), .default_mode = s0to3, .dev_attrs = &max1363_dev_attr_group, .scan_attrs = &max1363_scan_el_group, }, [max1363] = { .num_inputs = 4, .bits = 12, .int_vref_mv = 2048, .monitor_mode = 1, .mode_list = max1363_mode_list, .num_modes = ARRAY_SIZE(max1363_mode_list), .default_mode = s0to3, .dev_attrs = &max1363_dev_attr_group, .scan_attrs = &max1363_scan_el_group, }, [max1364] = { .num_inputs = 4, .bits = 12, .int_vref_mv = 4096, .monitor_mode = 1, .mode_list = max1363_mode_list, .num_modes = ARRAY_SIZE(max1363_mode_list), .default_mode = s0to3, .dev_attrs = &max1363_dev_attr_group, .scan_attrs = &max1363_scan_el_group, }, [max1036] = { .num_inputs = 4, .bits = 8, .int_vref_mv = 4096, .mode_list = max1236_mode_list, .num_modes = ARRAY_SIZE(max1236_mode_list), .default_mode = s0to3, .dev_attrs = &max1363_dev_attr_group, .scan_attrs = &max1363_scan_el_group, }, [max1037] = { .num_inputs = 4, .bits = 8, .int_vref_mv = 2048, .mode_list = max1236_mode_list, .num_modes = ARRAY_SIZE(max1236_mode_list), .default_mode = s0to3, .dev_attrs = &max1363_dev_attr_group, .scan_attrs = &max1363_scan_el_group, }, [max1038] = { .num_inputs = 12, .bits = 8, .int_vref_mv = 4096, .mode_list = max1238_mode_list, .num_modes = ARRAY_SIZE(max1238_mode_list), .default_mode = s0to11, .dev_attrs = &max1238_dev_attr_group, .scan_attrs = &max1238_scan_el_group, }, [max1039] = { .num_inputs = 12, .bits = 8, .int_vref_mv = 2048, .mode_list = max1238_mode_list, .num_modes = ARRAY_SIZE(max1238_mode_list), .default_mode = s0to11, .dev_attrs = &max1238_dev_attr_group, .scan_attrs = &max1238_scan_el_group, }, [max1136] = { .num_inputs = 4, .bits = 10, .int_vref_mv = 4096, .mode_list = max1236_mode_list, .num_modes = ARRAY_SIZE(max1236_mode_list), .default_mode = s0to3, .dev_attrs = &max1363_dev_attr_group, .scan_attrs = &max1363_scan_el_group, }, [max1137] = { .num_inputs = 4, .bits = 10, .int_vref_mv = 2048, .mode_list = max1236_mode_list, .num_modes = ARRAY_SIZE(max1236_mode_list), .default_mode = s0to3, .dev_attrs = &max1363_dev_attr_group, .scan_attrs = &max1363_scan_el_group, }, [max1138] = { .num_inputs = 12, .bits = 10, .int_vref_mv = 4096, .mode_list = max1238_mode_list, .num_modes = ARRAY_SIZE(max1238_mode_list), .default_mode = s0to11, .dev_attrs = &max1238_dev_attr_group, .scan_attrs = &max1238_scan_el_group, }, [max1139] = { .num_inputs = 12, .bits = 10, .int_vref_mv = 2048, .mode_list = max1238_mode_list, .num_modes = ARRAY_SIZE(max1238_mode_list), .default_mode = s0to11, .dev_attrs = &max1238_dev_attr_group, .scan_attrs = &max1238_scan_el_group, }, [max1236] = { .num_inputs = 4, .bits = 12, .int_vref_mv = 4096, .mode_list = max1236_mode_list, .num_modes = ARRAY_SIZE(max1236_mode_list), .default_mode = s0to3, .dev_attrs = &max1363_dev_attr_group, .scan_attrs = &max1363_scan_el_group, }, [max1237] = { .num_inputs = 4, .bits = 12, .int_vref_mv = 2048, .mode_list = max1236_mode_list, .num_modes = ARRAY_SIZE(max1236_mode_list), .default_mode = s0to3, .dev_attrs = &max1363_dev_attr_group, .scan_attrs = &max1363_scan_el_group, }, [max1238] = { .num_inputs = 12, .bits = 12, .int_vref_mv = 4096, .mode_list = max1238_mode_list, .num_modes = ARRAY_SIZE(max1238_mode_list), .default_mode = s0to11, .dev_attrs = &max1238_dev_attr_group, .scan_attrs = &max1238_scan_el_group, }, [max1239] = { .num_inputs = 12, .bits = 12, .int_vref_mv = 2048, .mode_list = max1238_mode_list, .num_modes = ARRAY_SIZE(max1238_mode_list), .default_mode = s0to11, .dev_attrs = &max1238_dev_attr_group, .scan_attrs = &max1238_scan_el_group, }, [max11600] = { .num_inputs = 4, .bits = 8, .int_vref_mv = 4096, .mode_list = max11607_mode_list, .num_modes = ARRAY_SIZE(max11607_mode_list), .default_mode = s0to3, .dev_attrs = &max1363_dev_attr_group, .scan_attrs = &max1363_scan_el_group, }, [max11601] = { .num_inputs = 4, .bits = 8, .int_vref_mv = 2048, .mode_list = max11607_mode_list, .num_modes = ARRAY_SIZE(max11607_mode_list), .default_mode = s0to3, .dev_attrs = &max1363_dev_attr_group, .scan_attrs = &max1363_scan_el_group, }, [max11602] = { .num_inputs = 8, .bits = 8, .int_vref_mv = 4096, .mode_list = max11608_mode_list, .num_modes = ARRAY_SIZE(max11608_mode_list), .default_mode = s0to7, .dev_attrs = &max11608_dev_attr_group, .scan_attrs = &max11608_scan_el_group, }, [max11603] = { .num_inputs = 8, .bits = 8, .int_vref_mv = 2048, .mode_list = max11608_mode_list, .num_modes = ARRAY_SIZE(max11608_mode_list), .default_mode = s0to7, .dev_attrs = &max11608_dev_attr_group, .scan_attrs = &max11608_scan_el_group, }, [max11604] = { .num_inputs = 12, .bits = 8, .int_vref_mv = 4098, .mode_list = max1238_mode_list, .num_modes = ARRAY_SIZE(max1238_mode_list), .default_mode = s0to11, .dev_attrs = &max1238_dev_attr_group, .scan_attrs = &max1238_scan_el_group, }, [max11605] = { .num_inputs = 12, .bits = 8, .int_vref_mv = 2048, .mode_list = max1238_mode_list, .num_modes = ARRAY_SIZE(max1238_mode_list), .default_mode = s0to11, .dev_attrs = &max1238_dev_attr_group, .scan_attrs = &max1238_scan_el_group, }, [max11606] = { .num_inputs = 4, .bits = 10, .int_vref_mv = 4096, .mode_list = max11607_mode_list, .num_modes = ARRAY_SIZE(max11607_mode_list), .default_mode = s0to3, .dev_attrs = &max1363_dev_attr_group, .scan_attrs = &max1363_scan_el_group, }, [max11607] = { .num_inputs = 4, .bits = 10, .int_vref_mv = 2048, .mode_list = max11607_mode_list, .num_modes = ARRAY_SIZE(max11607_mode_list), .default_mode = s0to3, .dev_attrs = &max1363_dev_attr_group, .scan_attrs = &max1363_scan_el_group, }, [max11608] = { .num_inputs = 8, .bits = 10, .int_vref_mv = 4096, .mode_list = max11608_mode_list, .num_modes = ARRAY_SIZE(max11608_mode_list), .default_mode = s0to7, .dev_attrs = &max11608_dev_attr_group, .scan_attrs = &max11608_scan_el_group, }, [max11609] = { .num_inputs = 8, .bits = 10, .int_vref_mv = 2048, .mode_list = max11608_mode_list, .num_modes = ARRAY_SIZE(max11608_mode_list), .default_mode = s0to7, .dev_attrs = &max11608_dev_attr_group, .scan_attrs = &max11608_scan_el_group, }, [max11610] = { .num_inputs = 12, .bits = 10, .int_vref_mv = 4098, .mode_list = max1238_mode_list, .num_modes = ARRAY_SIZE(max1238_mode_list), .default_mode = s0to11, .dev_attrs = &max1238_dev_attr_group, .scan_attrs = &max1238_scan_el_group, }, [max11611] = { .num_inputs = 12, .bits = 10, .int_vref_mv = 2048, .mode_list = max1238_mode_list, .num_modes = ARRAY_SIZE(max1238_mode_list), .default_mode = s0to11, .dev_attrs = &max1238_dev_attr_group, .scan_attrs = &max1238_scan_el_group, }, [max11612] = { .num_inputs = 4, .bits = 12, .int_vref_mv = 4096, .mode_list = max11607_mode_list, .num_modes = ARRAY_SIZE(max11607_mode_list), .default_mode = s0to3, .dev_attrs = &max1363_dev_attr_group, .scan_attrs = &max1363_scan_el_group, }, [max11613] = { .num_inputs = 4, .bits = 12, .int_vref_mv = 2048, .mode_list = max11607_mode_list, .num_modes = ARRAY_SIZE(max11607_mode_list), .default_mode = s0to3, .dev_attrs = &max1363_dev_attr_group, .scan_attrs = &max1363_scan_el_group, }, [max11614] = { .num_inputs = 8, .bits = 12, .int_vref_mv = 4096, .mode_list = max11608_mode_list, .num_modes = ARRAY_SIZE(max11608_mode_list), .default_mode = s0to7, .dev_attrs = &max11608_dev_attr_group, .scan_attrs = &max11608_scan_el_group, }, [max11615] = { .num_inputs = 8, .bits = 12, .int_vref_mv = 2048, .mode_list = max11608_mode_list, .num_modes = ARRAY_SIZE(max11608_mode_list), .default_mode = s0to7, .dev_attrs = &max11608_dev_attr_group, .scan_attrs = &max11608_scan_el_group, }, [max11616] = { .num_inputs = 12, .bits = 12, .int_vref_mv = 4098, .mode_list = max1238_mode_list, .num_modes = ARRAY_SIZE(max1238_mode_list), .default_mode = s0to11, .dev_attrs = &max1238_dev_attr_group, .scan_attrs = &max1238_scan_el_group, }, [max11617] = { .num_inputs = 12, .bits = 12, .int_vref_mv = 2048, .mode_list = max1238_mode_list, .num_modes = ARRAY_SIZE(max1238_mode_list), .default_mode = s0to11, .dev_attrs = &max1238_dev_attr_group, .scan_attrs = &max1238_scan_el_group, } }; static const int max1363_monitor_speeds[] = { 133000, 665000, 33300, 16600, 8300, 4200, 2000, 1000 }; static ssize_t max1363_monitor_show_freq(struct device *dev, struct device_attribute *attr, char *buf) { struct iio_dev *dev_info = dev_get_drvdata(dev); struct max1363_state *st = iio_dev_get_devdata(dev_info); return sprintf(buf, "%d\n", max1363_monitor_speeds[st->monitor_speed]); } static ssize_t max1363_monitor_store_freq(struct device *dev, struct device_attribute *attr, const char *buf, size_t len) { struct iio_dev *dev_info = dev_get_drvdata(dev); struct max1363_state *st = iio_dev_get_devdata(dev_info); int i, ret; unsigned long val; bool found = false; ret = strict_strtoul(buf, 10, &val); if (ret) return -EINVAL; for (i = 0; i < ARRAY_SIZE(max1363_monitor_speeds); i++) if (val == max1363_monitor_speeds[i]) { found = true; break; } if (!found) return -EINVAL; mutex_lock(&dev_info->mlock); st->monitor_speed = i; mutex_unlock(&dev_info->mlock); return 0; } static IIO_DEV_ATTR_SAMP_FREQ(S_IRUGO | S_IWUSR, max1363_monitor_show_freq, max1363_monitor_store_freq); static IIO_CONST_ATTR(sampling_frequency_available, "133000 665000 33300 16600 8300 4200 2000 1000"); static ssize_t max1363_show_thresh(struct device *dev, struct device_attribute *attr, char *buf, bool high) { struct iio_dev *dev_info = dev_get_drvdata(dev); struct max1363_state *st = iio_dev_get_devdata(dev_info); struct iio_dev_attr *this_attr = to_iio_dev_attr(attr); if (high) return sprintf(buf, "%d\n", st->thresh_high[this_attr->address]); else return sprintf(buf, "%d\n", st->thresh_low[this_attr->address & 0x7]); } static ssize_t max1363_show_thresh_low(struct device *dev, struct device_attribute *attr, char *buf) { return max1363_show_thresh(dev, attr, buf, false); } static ssize_t max1363_show_thresh_high(struct device *dev, struct device_attribute *attr, char *buf) { return max1363_show_thresh(dev, attr, buf, true); } static ssize_t max1363_store_thresh_unsigned(struct device *dev, struct device_attribute *attr, const char *buf, size_t len, bool high) { struct iio_dev *dev_info = dev_get_drvdata(dev); struct max1363_state *st = iio_dev_get_devdata(dev_info); struct iio_dev_attr *this_attr = to_iio_dev_attr(attr); unsigned long val; int ret; ret = strict_strtoul(buf, 10, &val); if (ret) return -EINVAL; switch (st->chip_info->bits) { case 10: if (val > 0x3FF) return -EINVAL; break; case 12: if (val > 0xFFF) return -EINVAL; break; } switch (high) { case 1: st->thresh_high[this_attr->address] = val; break; case 0: st->thresh_low[this_attr->address & 0x7] = val; break; } return len; } static ssize_t max1363_store_thresh_high_unsigned(struct device *dev, struct device_attribute *attr, const char *buf, size_t len) { return max1363_store_thresh_unsigned(dev, attr, buf, len, true); } static ssize_t max1363_store_thresh_low_unsigned(struct device *dev, struct device_attribute *attr, const char *buf, size_t len) { return max1363_store_thresh_unsigned(dev, attr, buf, len, false); } static ssize_t max1363_store_thresh_signed(struct device *dev, struct device_attribute *attr, const char *buf, size_t len, bool high) { struct iio_dev *dev_info = dev_get_drvdata(dev); struct max1363_state *st = iio_dev_get_devdata(dev_info); struct iio_dev_attr *this_attr = to_iio_dev_attr(attr); long val; int ret; ret = strict_strtol(buf, 10, &val); if (ret) return -EINVAL; switch (st->chip_info->bits) { case 10: if (val < -512 || val > 511) return -EINVAL; break; case 12: if (val < -2048 || val > 2047) return -EINVAL; break; } switch (high) { case 1: st->thresh_high[this_attr->address] = val; break; case 0: st->thresh_low[this_attr->address & 0x7] = val; break; } return len; } static ssize_t max1363_store_thresh_high_signed(struct device *dev, struct device_attribute *attr, const char *buf, size_t len) { return max1363_store_thresh_signed(dev, attr, buf, len, true); } static ssize_t max1363_store_thresh_low_signed(struct device *dev, struct device_attribute *attr, const char *buf, size_t len) { return max1363_store_thresh_signed(dev, attr, buf, len, false); } static IIO_DEVICE_ATTR(in0_thresh_high_value, S_IRUGO | S_IWUSR, max1363_show_thresh_high, max1363_store_thresh_high_unsigned, 0); static IIO_DEVICE_ATTR(in0_thresh_low_value, S_IRUGO | S_IWUSR, max1363_show_thresh_low, max1363_store_thresh_low_unsigned, 0); static IIO_DEVICE_ATTR(in1_thresh_high_value, S_IRUGO | S_IWUSR, max1363_show_thresh_high, max1363_store_thresh_high_unsigned, 1); static IIO_DEVICE_ATTR(in1_thresh_low_value, S_IRUGO | S_IWUSR, max1363_show_thresh_low, max1363_store_thresh_low_unsigned, 1); static IIO_DEVICE_ATTR(in2_thresh_high_value, S_IRUGO | S_IWUSR, max1363_show_thresh_high, max1363_store_thresh_high_unsigned, 2); static IIO_DEVICE_ATTR(in2_thresh_low_value, S_IRUGO | S_IWUSR, max1363_show_thresh_low, max1363_store_thresh_low_unsigned, 2); static IIO_DEVICE_ATTR(in3_thresh_high_value, S_IRUGO | S_IWUSR, max1363_show_thresh_high, max1363_store_thresh_high_unsigned, 3); static IIO_DEVICE_ATTR(in3_thresh_low_value, S_IRUGO | S_IWUSR, max1363_show_thresh_low, max1363_store_thresh_low_unsigned, 3); static IIO_DEVICE_ATTR_NAMED(in0min1_thresh_high_value, in0-in1_thresh_high_value, S_IRUGO | S_IWUSR, max1363_show_thresh_high, max1363_store_thresh_high_signed, 4); static IIO_DEVICE_ATTR_NAMED(in0min1_thresh_low_value, in0-in1_thresh_low_value, S_IRUGO | S_IWUSR, max1363_show_thresh_low, max1363_store_thresh_low_signed, 4); static IIO_DEVICE_ATTR_NAMED(in2min3_thresh_high_value, in2-in3_thresh_high_value, S_IRUGO | S_IWUSR, max1363_show_thresh_high, max1363_store_thresh_high_signed, 5); static IIO_DEVICE_ATTR_NAMED(in2min3_thresh_low_value, in2-in3_thresh_low_value, S_IRUGO | S_IWUSR, max1363_show_thresh_low, max1363_store_thresh_low_signed, 5); static IIO_DEVICE_ATTR_NAMED(in1min0_thresh_high_value, in1-in0_thresh_high_value, S_IRUGO | S_IWUSR, max1363_show_thresh_high, max1363_store_thresh_high_signed, 6); static IIO_DEVICE_ATTR_NAMED(in1min0_thresh_low_value, in1-in0_thresh_low_value, S_IRUGO | S_IWUSR, max1363_show_thresh_low, max1363_store_thresh_low_signed, 6); static IIO_DEVICE_ATTR_NAMED(in3min2_thresh_high_value, in3-in2_thresh_high_value, S_IRUGO | S_IWUSR, max1363_show_thresh_high, max1363_store_thresh_high_signed, 7); static IIO_DEVICE_ATTR_NAMED(in3min2_thresh_low_value, in3-in2_thresh_low_value, S_IRUGO | S_IWUSR, max1363_show_thresh_low, max1363_store_thresh_low_signed, 7); static int max1363_int_th(struct iio_dev *dev_info, int index, s64 timestamp, int not_test) { struct max1363_state *st = dev_info->dev_data; st->last_timestamp = timestamp; schedule_work(&st->thresh_work); return 0; } static void max1363_thresh_handler_bh(struct work_struct *work_s) { struct max1363_state *st = container_of(work_s, struct max1363_state, thresh_work); u8 rx; u8 tx[2] = { st->setupbyte, MAX1363_MON_INT_ENABLE | (st->monitor_speed << 1) | 0xF0 }; i2c_master_recv(st->client, &rx, 1); if (rx & (1 << 0)) iio_push_event(st->indio_dev, 0, IIO_EVENT_CODE_IN_LOW_THRESH(3), st->last_timestamp); if (rx & (1 << 1)) iio_push_event(st->indio_dev, 0, IIO_EVENT_CODE_IN_HIGH_THRESH(3), st->last_timestamp); if (rx & (1 << 2)) iio_push_event(st->indio_dev, 0, IIO_EVENT_CODE_IN_LOW_THRESH(2), st->last_timestamp); if (rx & (1 << 3)) iio_push_event(st->indio_dev, 0, IIO_EVENT_CODE_IN_HIGH_THRESH(2), st->last_timestamp); if (rx & (1 << 4)) iio_push_event(st->indio_dev, 0, IIO_EVENT_CODE_IN_LOW_THRESH(1), st->last_timestamp); if (rx & (1 << 5)) iio_push_event(st->indio_dev, 0, IIO_EVENT_CODE_IN_HIGH_THRESH(1), st->last_timestamp); if (rx & (1 << 6)) iio_push_event(st->indio_dev, 0, IIO_EVENT_CODE_IN_LOW_THRESH(0), st->last_timestamp); if (rx & (1 << 7)) iio_push_event(st->indio_dev, 0, IIO_EVENT_CODE_IN_HIGH_THRESH(0), st->last_timestamp); enable_irq(st->client->irq); i2c_master_send(st->client, tx, 2); } static ssize_t max1363_read_interrupt_config(struct device *dev, struct device_attribute *attr, char *buf) { struct iio_dev *dev_info = dev_get_drvdata(dev); struct max1363_state *st = iio_dev_get_devdata(dev_info); struct iio_event_attr *this_attr = to_iio_event_attr(attr); int val; mutex_lock(&dev_info->mlock); if (this_attr->mask & 0x8) val = (1 << (this_attr->mask & 0x7)) & st->mask_low; else val = (1 << this_attr->mask) & st->mask_high; mutex_unlock(&dev_info->mlock); return sprintf(buf, "%d\n", !!val); } static int max1363_monitor_mode_update(struct max1363_state *st, int enabled) { u8 *tx_buf; int ret, i = 3, j; unsigned long numelements; int len; long modemask; if (!enabled) { /* transition to ring capture is not currently supported */ st->setupbyte &= ~MAX1363_SETUP_MONITOR_SETUP; st->configbyte &= ~MAX1363_SCAN_MASK; st->monitor_on = false; return max1363_write_basic_config(st->client, st->setupbyte, st->configbyte); } /* Ensure we are in the relevant mode */ st->setupbyte |= MAX1363_SETUP_MONITOR_SETUP; st->configbyte &= ~(MAX1363_CHANNEL_SEL_MASK | MAX1363_SCAN_MASK | MAX1363_SE_DE_MASK); st->configbyte |= MAX1363_CONFIG_SCAN_MONITOR_MODE; if ((st->mask_low | st->mask_high) & 0x0F) { st->configbyte |= max1363_mode_table[s0to3].conf; modemask = max1363_mode_table[s0to3].modemask; } else if ((st->mask_low | st->mask_high) & 0x30) { st->configbyte |= max1363_mode_table[d0m1to2m3].conf; modemask = max1363_mode_table[d0m1to2m3].modemask; } else { st->configbyte |= max1363_mode_table[d1m0to3m2].conf; modemask = max1363_mode_table[d1m0to3m2].modemask; } numelements = hweight_long(modemask); len = 3 * numelements + 3; tx_buf = kmalloc(len, GFP_KERNEL); if (!tx_buf) { ret = -ENOMEM; goto error_ret; } tx_buf[0] = st->configbyte; tx_buf[1] = st->setupbyte; tx_buf[2] = (st->monitor_speed << 1); /* * So we need to do yet another bit of nefarious scan mode * setup to match what we need. */ for (j = 0; j < 8; j++) if (modemask & (1 << j)) { /* Establish the mode is in the scan */ if (st->mask_low & (1 << j)) { tx_buf[i] = (st->thresh_low[j] >> 4) & 0xFF; tx_buf[i + 1] = (st->thresh_low[j] << 4) & 0xF0; } else if (j < 4) { tx_buf[i] = 0; tx_buf[i + 1] = 0; } else { tx_buf[i] = 0x80; tx_buf[i + 1] = 0; } if (st->mask_high & (1 << j)) { tx_buf[i + 1] |= (st->thresh_high[j] >> 8) & 0x0F; tx_buf[i + 2] = st->thresh_high[j] & 0xFF; } else if (j < 4) { tx_buf[i + 1] |= 0x0F; tx_buf[i + 2] = 0xFF; } else { tx_buf[i + 1] |= 0x07; tx_buf[i + 2] = 0xFF; } i += 3; } ret = i2c_master_send(st->client, tx_buf, len); if (ret < 0) goto error_ret; if (ret != len) { ret = -EIO; goto error_ret; } /* * Now that we hopefully have sensible thresholds in place it is * time to turn the interrupts on. * It is unclear from the data sheet if this should be necessary * (i.e. whether monitor mode setup is atomic) but it appears to * be in practice. */ tx_buf[0] = st->setupbyte; tx_buf[1] = MAX1363_MON_INT_ENABLE | (st->monitor_speed << 1) | 0xF0; ret = i2c_master_send(st->client, tx_buf, 2); if (ret < 0) goto error_ret; if (ret != 2) { ret = -EIO; goto error_ret; } ret = 0; st->monitor_on = true; error_ret: kfree(tx_buf); return ret; } /* * To keep this managable we always use one of 3 scan modes. * Scan 0...3, 0-1,2-3 and 1-0,3-2 */ static inline int __max1363_check_event_mask(int thismask, int checkmask) { int ret = 0; /* Is it unipolar */ if (thismask < 4) { if (checkmask & ~0x0F) { ret = -EBUSY; goto error_ret; } } else if (thismask < 6) { if (checkmask & ~0x30) { ret = -EBUSY; goto error_ret; } } else if (checkmask & ~0xC0) ret = -EBUSY; error_ret: return ret; } static ssize_t max1363_write_interrupt_config(struct device *dev, struct device_attribute *attr, const char *buf, size_t len) { struct iio_dev *dev_info = dev_get_drvdata(dev); struct max1363_state *st = iio_dev_get_devdata(dev_info); struct iio_event_attr *this_attr = to_iio_event_attr(attr); unsigned long val; int ret; u16 unifiedmask; ret = strict_strtoul(buf, 10, &val); if (ret) return -EINVAL; mutex_lock(&st->indio_dev->mlock); unifiedmask = st->mask_low | st->mask_high; if (this_attr->mask & 0x08) { /* If we are disabling no need to test */ if (val == 0) st->mask_low &= ~(1 << (this_attr->mask & 0x7)); else { ret = __max1363_check_event_mask(this_attr->mask & 0x7, unifiedmask); if (ret) goto error_ret; st->mask_low |= (1 << (this_attr->mask & 0x7)); } } else { if (val == 0) st->mask_high &= ~(1 << (this_attr->mask)); else { ret = __max1363_check_event_mask(this_attr->mask, unifiedmask); if (ret) goto error_ret; st->mask_high |= (1 << this_attr->mask); } } if (st->monitor_on && !st->mask_high && !st->mask_low) iio_remove_event_from_list(this_attr->listel, &dev_info->interrupts[0]->ev_list); if (!st->monitor_on && val) iio_add_event_to_list(this_attr->listel, &dev_info->interrupts[0]->ev_list); max1363_monitor_mode_update(st, !!(st->mask_high | st->mask_low)); error_ret: mutex_unlock(&st->indio_dev->mlock); return len; } IIO_EVENT_SH(max1363_thresh, max1363_int_th); #define MAX1363_HIGH_THRESH(a) a #define MAX1363_LOW_THRESH(a) (a | 0x8) IIO_EVENT_ATTR_SH(in0_thresh_high_en, iio_event_max1363_thresh, max1363_read_interrupt_config, max1363_write_interrupt_config, MAX1363_HIGH_THRESH(0)); IIO_EVENT_ATTR_SH(in0_thresh_low_en, iio_event_max1363_thresh, max1363_read_interrupt_config, max1363_write_interrupt_config, MAX1363_LOW_THRESH(0)); IIO_EVENT_ATTR_SH(in1_thresh_high_en, iio_event_max1363_thresh, max1363_read_interrupt_config, max1363_write_interrupt_config, MAX1363_HIGH_THRESH(1)); IIO_EVENT_ATTR_SH(in1_thresh_low_en, iio_event_max1363_thresh, max1363_read_interrupt_config, max1363_write_interrupt_config, MAX1363_LOW_THRESH(1)); IIO_EVENT_ATTR_SH(in2_thresh_high_en, iio_event_max1363_thresh, max1363_read_interrupt_config, max1363_write_interrupt_config, MAX1363_HIGH_THRESH(2)); IIO_EVENT_ATTR_SH(in2_thresh_low_en, iio_event_max1363_thresh, max1363_read_interrupt_config, max1363_write_interrupt_config, MAX1363_LOW_THRESH(2)); IIO_EVENT_ATTR_SH(in3_thresh_high_en, iio_event_max1363_thresh, max1363_read_interrupt_config, max1363_write_interrupt_config, MAX1363_HIGH_THRESH(3)); IIO_EVENT_ATTR_SH(in3_thresh_low_en, iio_event_max1363_thresh, max1363_read_interrupt_config, max1363_write_interrupt_config, MAX1363_LOW_THRESH(3)); IIO_EVENT_ATTR_NAMED_SH(in0min1_thresh_high_en, in0-in1_thresh_high_en, iio_event_max1363_thresh, max1363_read_interrupt_config, max1363_write_interrupt_config, MAX1363_HIGH_THRESH(4)); IIO_EVENT_ATTR_NAMED_SH(in0min1_thresh_low_en, in0-in1_thresh_low_en, iio_event_max1363_thresh, max1363_read_interrupt_config, max1363_write_interrupt_config, MAX1363_LOW_THRESH(4)); IIO_EVENT_ATTR_NAMED_SH(in3min2_thresh_high_en, in3-in2_thresh_high_en, iio_event_max1363_thresh, max1363_read_interrupt_config, max1363_write_interrupt_config, MAX1363_HIGH_THRESH(5)); IIO_EVENT_ATTR_NAMED_SH(in3min2_thresh_low_en, in3-in2_thresh_low_en, iio_event_max1363_thresh, max1363_read_interrupt_config, max1363_write_interrupt_config, MAX1363_LOW_THRESH(5)); IIO_EVENT_ATTR_NAMED_SH(in1min0_thresh_high_en, in1-in0_thresh_high_en, iio_event_max1363_thresh, max1363_read_interrupt_config, max1363_write_interrupt_config, MAX1363_HIGH_THRESH(6)); IIO_EVENT_ATTR_NAMED_SH(in1min0_thresh_low_en, in1-in0_thresh_low_en, iio_event_max1363_thresh, max1363_read_interrupt_config, max1363_write_interrupt_config, MAX1363_LOW_THRESH(6)); IIO_EVENT_ATTR_NAMED_SH(in2min3_thresh_high_en, in2-in3_thresh_high_en, iio_event_max1363_thresh, max1363_read_interrupt_config, max1363_write_interrupt_config, MAX1363_HIGH_THRESH(7)); IIO_EVENT_ATTR_NAMED_SH(in2min3_thresh_low_en, in2-in3_thresh_low_en, iio_event_max1363_thresh, max1363_read_interrupt_config, max1363_write_interrupt_config, MAX1363_LOW_THRESH(7)); /* * As with scan_elements, only certain sets of these can * be combined. */ static struct attribute *max1363_event_attributes[] = { &iio_dev_attr_in0_thresh_high_value.dev_attr.attr, &iio_dev_attr_in0_thresh_low_value.dev_attr.attr, &iio_dev_attr_in1_thresh_high_value.dev_attr.attr, &iio_dev_attr_in1_thresh_low_value.dev_attr.attr, &iio_dev_attr_in2_thresh_high_value.dev_attr.attr, &iio_dev_attr_in2_thresh_low_value.dev_attr.attr, &iio_dev_attr_in3_thresh_high_value.dev_attr.attr, &iio_dev_attr_in3_thresh_low_value.dev_attr.attr, &iio_dev_attr_in0min1_thresh_high_value.dev_attr.attr, &iio_dev_attr_in0min1_thresh_low_value.dev_attr.attr, &iio_dev_attr_in2min3_thresh_high_value.dev_attr.attr, &iio_dev_attr_in2min3_thresh_low_value.dev_attr.attr, &iio_dev_attr_in1min0_thresh_high_value.dev_attr.attr, &iio_dev_attr_in1min0_thresh_low_value.dev_attr.attr, &iio_dev_attr_in3min2_thresh_high_value.dev_attr.attr, &iio_dev_attr_in3min2_thresh_low_value.dev_attr.attr, &iio_dev_attr_sampling_frequency.dev_attr.attr, &iio_const_attr_sampling_frequency_available.dev_attr.attr, &iio_event_attr_in0_thresh_high_en.dev_attr.attr, &iio_event_attr_in0_thresh_low_en.dev_attr.attr, &iio_event_attr_in1_thresh_high_en.dev_attr.attr, &iio_event_attr_in1_thresh_low_en.dev_attr.attr, &iio_event_attr_in2_thresh_high_en.dev_attr.attr, &iio_event_attr_in2_thresh_low_en.dev_attr.attr, &iio_event_attr_in3_thresh_high_en.dev_attr.attr, &iio_event_attr_in3_thresh_low_en.dev_attr.attr, &iio_event_attr_in0min1_thresh_high_en.dev_attr.attr, &iio_event_attr_in0min1_thresh_low_en.dev_attr.attr, &iio_event_attr_in3min2_thresh_high_en.dev_attr.attr, &iio_event_attr_in3min2_thresh_low_en.dev_attr.attr, &iio_event_attr_in1min0_thresh_high_en.dev_attr.attr, &iio_event_attr_in1min0_thresh_low_en.dev_attr.attr, &iio_event_attr_in2min3_thresh_high_en.dev_attr.attr, &iio_event_attr_in2min3_thresh_low_en.dev_attr.attr, NULL, }; static struct attribute_group max1363_event_attribute_group = { .attrs = max1363_event_attributes, }; static int max1363_initial_setup(struct max1363_state *st) { st->setupbyte = MAX1363_SETUP_AIN3_IS_AIN3_REF_IS_VDD | MAX1363_SETUP_POWER_UP_INT_REF | MAX1363_SETUP_INT_CLOCK | MAX1363_SETUP_UNIPOLAR | MAX1363_SETUP_NORESET; /* Set scan mode writes the config anyway so wait until then*/ st->setupbyte = MAX1363_SETUP_BYTE(st->setupbyte); st->current_mode = &max1363_mode_table[st->chip_info->default_mode]; st->configbyte = MAX1363_CONFIG_BYTE(st->configbyte); return max1363_set_scan_mode(st); } static int __devinit max1363_probe(struct i2c_client *client, const struct i2c_device_id *id) { int ret, i, regdone = 0; struct max1363_state *st = kzalloc(sizeof(*st), GFP_KERNEL); if (st == NULL) { ret = -ENOMEM; goto error_ret; } /* this is only used for device removal purposes */ i2c_set_clientdata(client, st); atomic_set(&st->protect_ring, 0); st->chip_info = &max1363_chip_info_tbl[id->driver_data]; st->reg = regulator_get(&client->dev, "vcc"); if (!IS_ERR(st->reg)) { ret = regulator_enable(st->reg); if (ret) goto error_put_reg; } st->client = client; st->indio_dev = iio_allocate_device(); if (st->indio_dev == NULL) { ret = -ENOMEM; goto error_disable_reg; } st->indio_dev->available_scan_masks = kzalloc(sizeof(*st->indio_dev->available_scan_masks)* (st->chip_info->num_modes + 1), GFP_KERNEL); if (!st->indio_dev->available_scan_masks) { ret = -ENOMEM; goto error_free_device; } for (i = 0; i < st->chip_info->num_modes; i++) st->indio_dev->available_scan_masks[i] = max1363_mode_table[st->chip_info->mode_list[i]] .modemask; /* Estabilish that the iio_dev is a child of the i2c device */ st->indio_dev->dev.parent = &client->dev; st->indio_dev->attrs = st->chip_info->dev_attrs; /* Todo: this shouldn't be here. */ st->indio_dev->scan_el_attrs = st->chip_info->scan_attrs; st->indio_dev->dev_data = (void *)(st); st->indio_dev->driver_module = THIS_MODULE; st->indio_dev->modes = INDIO_DIRECT_MODE; if (st->chip_info->monitor_mode && client->irq) { st->indio_dev->num_interrupt_lines = 1; st->indio_dev->event_attrs = &max1363_event_attribute_group; } ret = max1363_initial_setup(st); if (ret) goto error_free_available_scan_masks; ret = max1363_register_ring_funcs_and_init(st->indio_dev); if (ret) goto error_free_available_scan_masks; ret = iio_device_register(st->indio_dev); if (ret) goto error_cleanup_ring; regdone = 1; ret = iio_ring_buffer_register(st->indio_dev->ring, 0); if (ret) goto error_cleanup_ring; if (st->chip_info->monitor_mode && client->irq) { ret = iio_register_interrupt_line(client->irq, st->indio_dev, 0, IRQF_TRIGGER_RISING, client->name); if (ret) goto error_uninit_ring; INIT_WORK(&st->thresh_work, max1363_thresh_handler_bh); } return 0; error_uninit_ring: iio_ring_buffer_unregister(st->indio_dev->ring); error_cleanup_ring: max1363_ring_cleanup(st->indio_dev); error_free_available_scan_masks: kfree(st->indio_dev->available_scan_masks); error_free_device: if (!regdone) iio_free_device(st->indio_dev); else iio_device_unregister(st->indio_dev); error_disable_reg: if (!IS_ERR(st->reg)) regulator_disable(st->reg); error_put_reg: if (!IS_ERR(st->reg)) regulator_put(st->reg); kfree(st); error_ret: return ret; } static int max1363_remove(struct i2c_client *client) { struct max1363_state *st = i2c_get_clientdata(client); struct iio_dev *indio_dev = st->indio_dev; if (st->chip_info->monitor_mode && client->irq) iio_unregister_interrupt_line(st->indio_dev, 0); iio_ring_buffer_unregister(indio_dev->ring); max1363_ring_cleanup(indio_dev); kfree(st->indio_dev->available_scan_masks); iio_device_unregister(indio_dev); if (!IS_ERR(st->reg)) { regulator_disable(st->reg); regulator_put(st->reg); } kfree(st); return 0; } static const struct i2c_device_id max1363_id[] = { { "max1361", max1361 }, { "max1362", max1362 }, { "max1363", max1363 }, { "max1364", max1364 }, { "max1036", max1036 }, { "max1037", max1037 }, { "max1038", max1038 }, { "max1039", max1039 }, { "max1136", max1136 }, { "max1137", max1137 }, { "max1138", max1138 }, { "max1139", max1139 }, { "max1236", max1236 }, { "max1237", max1237 }, { "max1238", max1238 }, { "max1239", max1239 }, { "max11600", max11600 }, { "max11601", max11601 }, { "max11602", max11602 }, { "max11603", max11603 }, { "max11604", max11604 }, { "max11605", max11605 }, { "max11606", max11606 }, { "max11607", max11607 }, { "max11608", max11608 }, { "max11609", max11609 }, { "max11610", max11610 }, { "max11611", max11611 }, { "max11612", max11612 }, { "max11613", max11613 }, { "max11614", max11614 }, { "max11615", max11615 }, { "max11616", max11616 }, { "max11617", max11617 }, {} }; MODULE_DEVICE_TABLE(i2c, max1363_id); static struct i2c_driver max1363_driver = { .driver = { .name = "max1363", }, .probe = max1363_probe, .remove = max1363_remove, .id_table = max1363_id, }; static __init int max1363_init(void) { return i2c_add_driver(&max1363_driver); } static __exit void max1363_exit(void) { i2c_del_driver(&max1363_driver); } MODULE_AUTHOR("<NAME> <<EMAIL>>"); MODULE_DESCRIPTION("Maxim 1363 ADC"); MODULE_LICENSE("GPL v2"); module_init(max1363_init); module_exit(max1363_exit);
<reponame>machste/masc #include <stdlib.h> #include <strings.h> #include <masc/datetime.h> #include <masc/regex.h> bool datetime_parse(DateTime *self, const char *date) { self->ts.tv_sec = 0; self->ts.tv_nsec = 0; self->valid = false; Regex re = init(Regex, "([0-9]{1,4})-([0-9]{1,2})-([0-9]{1,2})" "(\\s+([0-9]{1,2}):([0-9]{2})(:([0-9]{2})(\\.([0-9]{6}))?)?)?"); Array *match = regex_search(&re, date); if (match != NULL) { struct tm t; bzero(&t, sizeof(t)); t.tm_year = atoi(str_cstr((Str *)array_get_at(match, 1))) - 1900; t.tm_mon = atoi(str_cstr((Str *)array_get_at(match, 2))) - 1; if (t.tm_mon < 0 || t.tm_mon > 11) { goto error; } t.tm_mday = atoi(str_cstr((Str *)array_get_at(match, 3))); if (t.tm_mday < 1 || t.tm_mday > 31) { goto error; } Str *hour = array_get_at(match, 5); if (isinstance(hour, Str)) { t.tm_hour = atoi(str_cstr(hour)); if (t.tm_hour < 0 || t.tm_hour > 23) { goto error; } t.tm_min = atoi(str_cstr((Str *)array_get_at(match, 6))); if (t.tm_min < 0 || t.tm_min > 59) { goto error; } Str *sec = array_get_at(match, 8); if (isinstance(sec, Str)) { t.tm_sec = atoi(str_cstr(sec)); if (t.tm_sec < 0 || t.tm_sec > 59) { goto error; } Str *nsec = array_get_at(match, 10); if (isinstance(nsec, Str)) { self->ts.tv_nsec = atoi(str_cstr(nsec)) * 1000; } } } t.tm_isdst = -1; self->ts.tv_sec = mktime(&t); self->valid = true; error: delete(match); } destroy(&re); return datetime_is_valid(self); }
<filename>Pods/MSProgress/MSProgress/Classes/UIView+UIViewUtils.h // // UIView+UIViewUtils.h // HZProgress // // Created by 王会洲 on 16/4/8. // Copyright © 2016年 王会洲. All rights reserved. // #define hudViewTag 0x98751235 #import <UIKit/UIKit.h> #import "MSProgressHUD.h" typedef enum : NSUInteger { HUDCaseDefault, //在头部有圆圈显示 HUDCaseSucErr, //显示的时候有状态图片 HUDCaseLabel, //只显示文字内容 HUDCaseIndeterminate, //菊花转圈 HUDCaseWhiteLabe, //白底黑字 HUDCaseETax, //e税客等待转圈 } HUDCaseEnum; @interface UIView (UIViewUtils) /**枚举状态*/ @property (nonatomic, assign) HUDCaseEnum HUDCase; /**显示错误信息带角标提示-自动消失*/ -(void)showHUDIndicatorViewSuccessAtCenter:(NSString *)success; /**显示正确提示带角标提示-自动消失*/ -(void)showHUDIndicatorViewErrorAtCenter:(NSString *)error; /**显示文字,不带任何图标-自动消失*/ -(void)showHUDIndicatorLabelAtCenter:(NSString *)indiTitle; /**菊花转,背景为黑色透明*/ -(void)showHUDIndicatorAtCenter:(NSString *)indiTitle; /*! 白底黑字----自动消失---提示文案 */ -(MSProgressHUD *)showHUDWitheColorAtCenter:(NSString *)title; //******************************************************************** /** 网络请求相关提示,网络加载中.... @param indiTitle 提示标题 */ - (void)showHUDIndicatorViewAtCenter:(NSString *)indiTitle; /**隐藏弹层*/ - (void)hideHUDIndicatorViewAtCenter; - (void)showHUDIndicatorViewAtCenter:(NSString *)indiTitle yOffset:(CGFloat)y; @end
/* * NiuTrans.Tensor - an open-source tensor library * Copyright (C) 2016-2021 * Natural Language Processing Lab, Northeastern University * and * NiuTrans Research * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * The worker of running the neural network. * * $Created by: <NAME> (<EMAIL>) 2021-02-24 * My son had new glasses yesterday. */ #ifndef __XWORDERJOB_H__ #define __XWORDERJOB_H__ #include "XWorker.h" #include "XModel.h" #include "XNNRecord.h" #include "XBaseTemplate.h" #include "../tensor/XList.h" namespace nts { // namespace nts(NiuTrans.Tensor) /* a model template for training */ class XWorkerJob : public XWorker { protected: /* the model */ XModel * model; /* the input tensors of the model */ XList inputs; /* the output tensors of the model */ XList outputs; /* the gold standard */ XList golds; /* the loss */ XList losses; /* record the information in running the neural network */ XNNRecord record; public: /* constructor */ XWorkerJob(); /* de-constructor */ ~XWorkerJob(); /* set the parameter keeper */ void SetModel(XModel * myModel); /* get the parameter keeper */ XModel * GetModel(); /* set the state of the worker */ void SetState(XWORKER_STATE myState); /* clear the worker */ void Clear(); /* get the input list */ XList * GetInput(); /* get the output list */ XList * GetOutput(); /* get the gold standard */ XList * GetGold(); /* get the loss */ XList * GetLoss(); /* get the record of the run */ XNNRecord * GetRecord(); /* record some stuff */ void RecordMe(); /* get the sum of losses over samples */ float GetLossAll(); /* get the number of samples */ int GetSampleNum(); /* get the number of outputs (predictoins) */ int GetPredictNum(); /* add a new job of model refreshment */ bool AddJobRefresh(XModel * myModel); /* add a new job of neural network forward and backward computation (with the input) */ bool AddJobNeuralNet(XModel * myModel, XList * inputs, XList * outputs, XList * golds, XList * losses); /* add a new job of recording the running of the nerual network */ bool AddJobRecord(XNNRecord * serverRecord); private: /* wrapper of RecordMe */ static void RecordMeStatic(XList * args); }; } #endif
<gh_stars>0 // // SKTextView.h // 1234123 // // Created by 阿汤哥 on 2019/3/16. // Copyright © 2019 aze. All rights reserved. // #import <UIKit/UIKit.h> NS_ASSUME_NONNULL_BEGIN @interface SKTextView : UITextView @end NS_ASSUME_NONNULL_END
/* * Copyright 2016 <NAME> * Copyright 2011-2016 by <NAME>. FNET Community. * Copyright 2008-2010 by <NAME>. Freescale Semiconductor, Inc. * Copyright 2003 by <NAME>. Motorola SPS. * * 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. */ #ifndef _NETIPV6_HEADER_H_ #define _NETIPV6_HEADER_H_ #include <netstd/stdint.h> #include <netstd/packing.h> #include <netipv6/ipv6.h> /********************************************************************* * IP packet header ********************************************************************** * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * |Version| Traffic Class | Flow Label | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | Payload Length | Next Header | Hop Limit | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | | * + + * | | * + Source Address + * | | * + + * | | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | | * + + * | | * + Destination Address + * | | * + + * | | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ **********************************************************************/ typedef struct NETSTD_PACKED { uint8_t version__tclass ; /* 4-bit Internet Protocol version number = 6, 8-bit traffic class field. */ uint8_t tclass__flowl ; /* 20-bit flow label. */ uint16_t flowl ; uint16_t length ; /* Length of the IPv6 * payload, i.e., the rest of the packet following * this IPv6 header, in octets. */ uint8_t next_header ; /* Identifies the type of header * immediately following the IPv6 header. Uses the * same values as the IPv4 Protocol field [RFC-1700 * et seq.].*/ uint8_t hop_limit ; /* Decremented by 1 by * each node that forwards the packet. The packet * is discarded if Hop Limit is decremented to * zero. */ ipv6_addr_t source_addr ; /* 128-bit address of the originator of the packet. */ ipv6_addr_t destination_addr ; /* 128-bit address of the intended recipient of the * packet (possibly not the ultimate recipient, if * a Routing header is present). */ } fnet_ip6_header_t; /* * Offset of the next_header field inside the IPv6 header. */ #define NETIPV6_IP6HDR_OFFSETOF_NEXT_HEADER 6 #define FNET_IP6_HEADER_GET_VERSION(x) (((x)->version__tclass & 0xF0u)>>4) /****************************************************************** * Extension header types *******************************************************************/ #define FNET_IP6_TYPE_HOP_BY_HOP_OPTIONS (0U) #define FNET_IP6_TYPE_DESTINATION_OPTIONS (60U) #define FNET_IP6_TYPE_ROUTING_HEADER (43U) #define FNET_IP6_TYPE_FRAGMENT_HEADER (44U) #define FNET_IP6_TYPE_AUTHENTICATION_HEADER (51U) #define FNET_IP6_TYPE_ENCAPSULATION_SECURITY_PAYLOAD_HEADER (50U) #define FNET_IP6_TYPE_MOBILITY_HEADER (135U) #define FNET_IP6_TYPE_NO_NEXT_HEADER (59U) /* RFC 2460: The value 59 in the Next Header field of an IPv6 header or any * extension header indicates that there is nothing following that * header. If the Payload Length field of the IPv6 header indicates the * presence of octets past the end of a header whose Next Header field * contains 59, those octets must be ignored.*/ /*********************************************************************** * This header format is used by the following extension headers: * - Hop-by-Hop Options Header (next_header=0) * - Routing Header (next_header=43) * - Destination Options Header (next_header=60) * * The Hop-by-Hop Options header is used to carry optional information * that must be examined by every node along a packet's delivery path. *********************************************************************** * RFC 2460 4.3, 4.4 and 4.6: * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | Next Header | Hdr Ext Len | | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + * | | * . . * . . . . . . . . . . * . . * | | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ ***********************************************************************/ typedef struct NETSTD_PACKED { uint8_t next_header ; /* 8-bit selector. Identifies the type of header * immediately following the Options * header. */ uint8_t hdr_ext_length ; /* 8-bit unsigned integer. Length of the Hop-by- * Hop Options header in 8-octet units, not * including the first 8 octets. */ } netipv6_ext_generic_t; /*********************************************************************** * Options (used in op-by-Hop Options Header & Destination Options Header) *********************************************************************** * RFC 2460 4.2: * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+- - - - - - - - - * | Option Type | Opt Data Len | Option Data * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+- - - - - - - - - ***********************************************************************/ typedef struct NETSTD_PACKED { uint8_t type ; /* 8-bit identifier of the type of option. */ uint8_t data_length ; /* 8-bit unsigned integer. Length of the Option * Data field of this option, in octets. */ } fnet_ip6_option_header_t; #define FNET_IP6_OPTION_TYPE_PAD1 (0x00u) /* The Pad1 option is used to insert * one octet of padding into the Options area of a header.*/ #define FNET_IP6_OPTION_TYPE_PADN (0x01u) /* The PadN option is used to insert two or more octets of padding * into the Options area of a header. For N octets of padding, the * Opt Data Len field contains the value N-2, and the Option Data * consists of N-2 zero-valued octets. */ /* RFC 2460: The Option Type identifiers are internally encoded such that their * highest-order two bits specify the action that must be taken if the * processing IPv6 node does not recognize the Option Type:*/ #define FNET_IP6_OPTION_TYPE_UNRECOGNIZED_MASK (0xC0u) #define FNET_IP6_OPTION_TYPE_UNRECOGNIZED_SKIP (0x00u) /* 00 - skip over this option and continue processing the header.*/ #define FNET_IP6_OPTION_TYPE_UNRECOGNIZED_DISCARD (0x40u) /* 01 - discard the packet. */ #define FNET_IP6_OPTION_TYPE_UNRECOGNIZED_DISCARD_ICMP (0x80u) /* 10 - discard the packet and, regardless of whether or not the * packet’s Destination Address was a multicast address, send an * ICMP Parameter Problem, Code 2, message to the packet’s * Source Address, pointing to the unrecognized Option Type.*/ #define FNET_IP6_OPTION_TYPE_UNRECOGNIZED_DISCARD_UICMP (0xC0u) /* 11 - discard the packet and, only if the packet’s Destination * Address was not a multicast address, send an ICMP Parameter * Problem, Code 2, message to the packet’s Source Address, * pointing to the unrecognized Option Type.*/ #endif
<reponame>kupl/starlab-benchmarks<filename>Benchmarks_with_Safety_Bugs/C/inetutils-1.9.4/src/telnet/tn3270.c /* Copyright (C) 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015 Free Software Foundation, Inc. This file is part of GNU Inetutils. GNU Inetutils is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. GNU Inetutils 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/'. */ /* * Copyright (c) 1988, 1993 * The Regents of the University of California. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include <config.h> #include <sys/types.h> #include <arpa/telnet.h> #include "general.h" #include "defines.h" #include "ring.h" #include "externs.h" #if defined TN3270 # include "../ctlr/screen.h" # include "../general/globals.h" # include "../sys_curses/telextrn.h" # include "../ctlr/externs.h" # if defined unix || defined __unix || defined __unix__ int HaveInput, /* There is input available to scan */ cursesdata, /* Do we dump curses data? */ sigiocount; /* Number of times we got a SIGIO */ char tline[200]; char *transcom = 0; /* transparent mode command (default: none) */ # endif /* unix || __unix || __unix__ */ char Ibuf[8 * BUFSIZ], *Ifrontp, *Ibackp; static char sb_terminal[] = { IAC, SB, TELOPT_TTYPE, TELQUAL_IS, 'I', 'B', 'M', '-', '3', '2', '7', '8', '-', '2', IAC, SE }; # define SBTERMMODEL 13 static int Sent3270TerminalType; /* Have we said we are a 3270? */ #endif /* defined(TN3270) */ void init_3270 (void) { #if defined TN3270 # if defined unix || defined __unix || defined __unix__ HaveInput = 0; sigiocount = 0; # endif /* unix || __unix || __unix__ */ Sent3270TerminalType = 0; Ifrontp = Ibackp = Ibuf; init_ctlr (); /* Initialize some things */ init_keyboard (); init_screen (); init_system (); #endif /* defined(TN3270) */ } #if defined TN3270 /* * DataToNetwork - queue up some data to go to network. If "done" is set, * then when last byte is queued, we add on an IAC EOR sequence (so, * don't call us with "done" until you want that done...) * * We actually do send all the data to the network buffer, since our * only client needs for us to do that. */ /*register char *buffer; where the data is */ /* register int count; how much to send */ /* int done; is this the last of a logical block */ int DataToNetwork (register char *buffer, register int count, int done) { register int loop, c; int origCount; origCount = count; while (count) { /* If not enough room for EORs, IACs, etc., wait */ if (NETROOM () < 6) { fd_set o; FD_ZERO (&o); netflush (); while (NETROOM () < 6) { FD_SET (net, &o); select (net + 1, (fd_set *) 0, &o, (fd_set *) 0, (struct timeval *) 0); netflush (); } } c = ring_empty_count (&netoring); if (c > count) { c = count; } loop = c; while (loop) { if (((unsigned char) *buffer) == IAC) { break; } buffer++; loop--; } if ((c = c - loop)) { ring_supply_data (&netoring, buffer - c, c); count -= c; } if (loop) { NET2ADD (IAC, IAC); count--; buffer++; } } if (done) { NET2ADD (IAC, EOR); netflush (); /* try to move along as quickly as ... */ } return (origCount - count); } # if defined unix || defined __unix || defined __unix__ void inputAvailable (int signo) { HaveInput = 1; sigiocount++; } # endif /* unix || __unix || __unix__ */ void outputPurge () { ttyflush (1); } /* * The following routines are places where the various tn3270 * routines make calls into telnet.c. */ /* * DataToTerminal - queue up some data to go to terminal. * * Note: there are people who call us and depend on our processing * *all* the data at one time (thus the select). */ /* register char *buffer;where the data is */ /* register int count; how much to send */ int DataToTerminal (register char *buffer, register int count) { register int c; int origCount; origCount = count; while (count) { if (TTYROOM () == 0) { # if defined unix || defined __unix || defined __unix__ fd_set o; FD_ZERO (&o); # endif /* unix || __unix || __unix__ */ ttyflush (0); while (TTYROOM () == 0) { # if defined unix || defined __unix || defined __unix__ FD_SET (tout, &o); select (tout + 1, (fd_set *) 0, &o, (fd_set *) 0, (struct timeval *) 0); # endif /* unix || __unix || __unix__ */ ttyflush (0); } } c = TTYROOM (); if (c > count) { c = count; } ring_supply_data (&ttyoring, buffer, c); count -= c; buffer += c; } return (origCount); } /* * Push3270 - Try to send data along the 3270 output (to screen) direction. */ int Push3270 () { int save = ring_full_count (&netiring); if (save) { if (Ifrontp + save > Ibuf + sizeof Ibuf) { if (Ibackp != Ibuf) { memmove (Ibuf, Ibackp, Ifrontp - Ibackp); Ifrontp -= (Ibackp - Ibuf); Ibackp = Ibuf; } } if (Ifrontp + save < Ibuf + sizeof Ibuf) { telrcv (); } } return save != ring_full_count (&netiring); } /* * Finish3270 - get the last dregs of 3270 data out to the terminal * before quitting. */ void Finish3270 () { while (Push3270 () || !DoTerminalOutput ()) { # if defined unix || defined __unix || defined __unix__ HaveInput = 0; # endif /* unix || __unix || __unix__ */ ; } } /* StringToTerminal - output a null terminated string to the terminal */ void StringToTerminal (char *s) { int count; count = strlen (s); if (count) { DataToTerminal (s, count); /* we know it always goes... */ } } # if !defined NOT43 || defined PUTCHAR /* _putchar - output a single character to the terminal. This name is so that * curses(3x) can call us to send out data. */ void _putchar (char c) { # if defined sun /* SunOS 4.0 bug */ c &= 0x7f; # endif /* defined(sun) */ if (cursesdata) { Dump ('>', &c, 1); } if (!TTYROOM ()) { DataToTerminal (&c, 1); } else { TTYADD (c); } } # endif /* ((!defined(NOT43)) || defined(PUTCHAR)) */ void SetIn3270 () { if (Sent3270TerminalType && my_want_state_is_will (TELOPT_BINARY) && my_want_state_is_do (TELOPT_BINARY) && !donebinarytoggle) { if (!In3270) { In3270 = 1; Init3270 (); /* Initialize 3270 functions */ /* initialize terminal key mapping */ InitTerminal (); /* Start terminal going */ setconnmode (0); } } else { if (In3270) { StopScreen (1); In3270 = 0; Stop3270 (); /* Tell 3270 we aren't here anymore */ setconnmode (0); } } } /* * tn3270_ttype() * * Send a response to a terminal type negotiation. * * Return '0' if no more responses to send; '1' if a response sent. */ int tn3270_ttype () { /* * Try to send a 3270 type terminal name. Decide which one based * on the format of our screen, and (in the future) color * capaiblities. */ InitTerminal (); /* Sets MaxNumberColumns, MaxNumberLines */ if ((MaxNumberLines >= 24) && (MaxNumberColumns >= 80)) { Sent3270TerminalType = 1; if ((MaxNumberLines >= 27) && (MaxNumberColumns >= 132)) { MaxNumberLines = 27; MaxNumberColumns = 132; sb_terminal[SBTERMMODEL] = '5'; } else if (MaxNumberLines >= 43) { MaxNumberLines = 43; MaxNumberColumns = 80; sb_terminal[SBTERMMODEL] = '4'; } else if (MaxNumberLines >= 32) { MaxNumberLines = 32; MaxNumberColumns = 80; sb_terminal[SBTERMMODEL] = '3'; } else { MaxNumberLines = 24; MaxNumberColumns = 80; sb_terminal[SBTERMMODEL] = '2'; } NumberLines = 24; /* before we start out... */ NumberColumns = 80; ScreenSize = NumberLines * NumberColumns; if ((MaxNumberLines * MaxNumberColumns) > MAXSCREENSIZE) { ExitString ("Programming error: MAXSCREENSIZE too small.\n", 1); } printsub ('>', sb_terminal + 2, sizeof sb_terminal - 2); ring_supply_data (&netoring, sb_terminal, sizeof sb_terminal); return 1; } else { return 0; } } # if defined unix || defined __unix || defined __unix__ int settranscom (int argc, char *argv[]) { int i; if (argc == 1 && transcom) { transcom = 0; } if (argc == 1) { return 1; } transcom = tline; strcpy (transcom, argv[1]); for (i = 2; i < argc; ++i) { strcat (transcom, " "); strcat (transcom, argv[i]); } return 1; } # endif /* unix || __unix || __unix__ */ #endif /* defined(TN3270) */
#ifndef __UDP_REQUEST_H_P__ #define __UDP_REQUEST_H_P__ 1 #include <sys/types.h> #include <stdint.h> #include <event2/event.h> #include "dnscrypt.h" #include "queue.h" typedef struct UDPRequestStatus_ { _Bool is_dying : 1; _Bool is_in_queue : 1; } UDPRequestStatus; typedef struct UDPRequest_ { uint8_t client_nonce[crypto_box_HALF_NONCEBYTES]; TAILQ_ENTRY(UDPRequest_) queue; struct sockaddr_storage client_sockaddr; ProxyContext *proxy_context; struct event *sendto_retry_timer; struct event *timeout_timer; evutil_socket_t client_proxy_handle; ev_socklen_t client_sockaddr_len; UDPRequestStatus status; unsigned char retries; } UDPRequest; typedef struct SendtoWithRetryCtx_ { void (*cb) (UDPRequest *udp_request); const void *buffer; UDPRequest *udp_request; const struct sockaddr *dest_addr; evutil_socket_t handle; size_t length; ev_socklen_t dest_len; int flags; } SendtoWithRetryCtx; #endif
/*Crie um programa em C que recebe um vetor de caracteres de tamanho 20 do usu�rio e imprime o caractere com mais ocorr�ncias no vetor seguido da quantidade de ocorr�ncias deste.*/ /*a b c a b c a a a a a a a b c a a b v r*/ #include<stdio.h> #include<stdlib.h> #include<string.h> int main() { char string[20],letras[20]; int i,j,quant_letras=0,cont[20],achou,maior=0; printf("Digite os caracteres:\n"); for(i=0; i<20; i++) //lendo os elementos { scanf("%c",&string[i]); getchar(); } for(i=0; i<20; i++)//para cada { achou = 0; for(j=0; j<quant_letras; j++) { if(string[i] == letras[j]) { achou = 1; cont[j] ++; } } if(!achou) //se n�o achou { letras[quant_letras] = string[i]; cont[quant_letras] = 1; quant_letras ++; } } printf("Quantidade de elementos:\n"); for(i=0; i<quant_letras; i++)//letras encontradas e quantidade de letras { printf("%c = %d\n",letras[i],cont[i]); } //maior elemento for(i=1; i<quant_letras; i++) { if(cont[i] > cont[maior]) { maior = i; } } printf("\nO caracter com mais ocorrencia e: %c = %d\n",letras[maior],cont[maior]); return 0; }
<filename>C_WIN32/ZigZag/ZigZag/Plumbing.c #define WIN32_LEAN_AND_MEAN #include <windows.h> static HINSTANCE hInst = NULL; static const WCHAR* szWindowClass = L"PlumbingWindowClass"; static ATOM MyRegisterClass(HINSTANCE hInstance, WNDPROC WndProc) { WNDCLASSEXW wcex; wcex.cbSize = sizeof(WNDCLASSEX); wcex.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC; wcex.lpfnWndProc = WndProc; wcex.cbClsExtra = 0; wcex.cbWndExtra = 0; wcex.hInstance = hInstance; wcex.hIcon = NULL; wcex.hCursor = LoadCursor(NULL, IDC_ARROW); wcex.hbrBackground = GetSysColorBrush(BLACK_BRUSH); wcex.lpszMenuName = NULL; wcex.lpszClassName = szWindowClass; wcex.hIconSm = NULL; return RegisterClassExW(&wcex); } static BOOL InitInstance(HINSTANCE hInstance, int nCmdShow, LPCWSTR title, int width, int height) { hInst = hInstance; RECT rcWindow; SetRect(&rcWindow, 0, 0, width, height); AdjustWindowRectEx(&rcWindow, WS_POPUPWINDOW | WS_CAPTION, FALSE, 0); HWND hWnd = CreateWindowW(szWindowClass, title, WS_POPUPWINDOW | WS_CAPTION, CW_USEDEFAULT, CW_USEDEFAULT, rcWindow.right - rcWindow.left, rcWindow.bottom - rcWindow.top, NULL, NULL, hInstance, NULL); if (!hWnd) { return FALSE; } ShowWindow(hWnd, nCmdShow); UpdateWindow(hWnd); return TRUE; } int Plumbing_run(HINSTANCE hInstance, WNDPROC WndProc, int nCmdShow, LPCWSTR title, int width, int height) { MyRegisterClass(hInstance, WndProc); if (!InitInstance(hInstance, nCmdShow, title, width, height)) { return FALSE; } MSG msg; while (GetMessage(&msg, NULL, 0, 0)) { TranslateMessage(&msg); DispatchMessage(&msg); } return (int)msg.wParam; } LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM); extern LPCWSTR gameTitle; extern int gameClientWidth; extern int gameClientHeight; int APIENTRY WinMain(_In_ HINSTANCE hInstance, _In_opt_ HINSTANCE hPrevInstance, _In_ LPTSTR lpCmdLine, _In_ int nCmdShow) { UNREFERENCED_PARAMETER(hPrevInstance); UNREFERENCED_PARAMETER(lpCmdLine); return Plumbing_run(hInstance, WndProc, nCmdShow, gameTitle, gameClientWidth, gameClientHeight); }
// // Generated by class-dump 3.5 (64 bit) (Debug version compiled Sep 17 2017 16:24:48). // // class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2015 by <NAME>. // #import <objc/NSObject.h> @class CSMutableDictionary, CSWorkers, NSMapTable, NSString; @protocol OS_dispatch_semaphore; @interface CardSDKTemplateCenter : NSObject { NSString *_downloadTemplatePath; NSString *_localTemplatePath; NSObject<OS_dispatch_semaphore> *_templateMapLock; int _reqId; CSWorkers *_worker; double _downloadStart; double _downloadEnd; NSString *_bizCode; NSString *_tplEntrance; NSMapTable *_templateMap; CSMutableDictionary *_nativeTemplateMap; } @property(retain, nonatomic) CSMutableDictionary *nativeTemplateMap; // @synthesize nativeTemplateMap=_nativeTemplateMap; @property(retain, nonatomic) NSMapTable *templateMap; // @synthesize templateMap=_templateMap; @property(copy, nonatomic) NSString *tplEntrance; // @synthesize tplEntrance=_tplEntrance; @property(copy, nonatomic) NSString *bizCode; // @synthesize bizCode=_bizCode; - (void).cxx_destruct; - (void)addTask:(CDUnknownBlockType)arg1; - (id)makeCSTemplateFromFileName:(struct _TemplateFileNameBody)arg1; - (_Bool)checkInvalid:(struct _TemplateFileNameBody)arg1; - (struct _TemplateFileNameBody)getTemplateInfo:(id)arg1; - (id)localTemplatePath; - (id)downloadPath; - (id)templateMapkey:(id)arg1 version:(id)arg2; - (int)downloadRequestId; - (Class)nativeCardClassForID_version:(id)arg1; - (void)setNativeCardsMap:(id)arg1; - (void)downloadTemplate:(id)arg1 onResult:(CDUnknownBlockType)arg2; - (_Bool)checkNeedUpdate:(id)arg1; - (void)startFetchCloudTemplate:(id)arg1 onResult:(CDUnknownBlockType)arg2; - (void)loadTemplateResource; - (id)requestTemplate:(id)arg1 onResult:(CDUnknownBlockType)arg2; - (id)queryLocalTemplate:(id)arg1; - (void)dealloc; - (void)setTaskWorker:(id)arg1; - (id)initWithBizCode:(id)arg1 templatePath:(id)arg2; @end
<gh_stars>0 // // UISlider+SliderTouchPoint.h // Situate // // Created by <NAME> on 09/06/2015. // Copyright (c) 2015 Llamadigital. All rights reserved. // #import <UIKit/UIKit.h> @interface UISlider (SliderTouchPoint) - (BOOL)pointInside:(CGPoint)point withDX:(float)dX andDY:(float)dY andwithEvent:(UIEvent*)event; @end
<reponame>topiolli/into /* This file is part of Into. * Copyright (C) Intopii 2013. * All rights reserved. * * Licensees holding a commercial Into license may use this file in * accordance with the commercial license agreement. Please see * LICENSE.commercial for commercial licensing terms. * * Alternatively, this file may be used under the terms of the GNU * Affero General Public License version 3 as published by the Free * Software Foundation. In addition, Intopii gives you special rights * to use Into as a part of open source software projects. Please * refer to LICENSE.AGPL3 for details. */ #ifndef _PIIYDINUTIL_H #define _PIIYDINUTIL_H #include "PiiYdin.h" #include "PiiOperationCompound.h" #include <QString> namespace PiiYdin { enum IllustrationFlag { ShowOnlyOperation = 0x0, ShowInputQueues = 0x1, ShowOutputStates = 0x2, ShowState = 0x3, ShowAll = -1 }; Q_DECLARE_FLAGS(IllustrationFlags, IllustrationFlag); Q_DECLARE_OPERATORS_FOR_FLAGS(IllustrationFlags); /** * Creates an ascii-graphics illustration of an operation. The * result can be printed on a console. This function is mainly * useful for debugging purposes. */ PII_YDIN_EXPORT QString illustrateOperation(PiiOperation* op, IllustrationFlags flags = ShowAll); /** * Prints out an illustration of *op* and its child operations (if * any). * * @param op the operation to dump to debug output * * @param flags options that control the appearance of dumped * operations * * @param level nesting level, used in recursive calls */ PII_YDIN_EXPORT void dumpOperation(PiiOperation *op, IllustrationFlags flags = ShowAll, int level = 0); /** * Dumps the state of an operation and its child operations. This * function is mainly useful for debugging purposes. * * @param stream write state information to this stream * * @param op the operation whose state is to be dumped * * @param indent indentation depth */ template <class Stream> void dumpState(Stream stream, PiiOperation* op, int indent = 0) { for (int i=indent; i--; ) stream << ' '; stream << op->metaObject()->className() << "(" << op->objectName() << "): " << PiiOperation::stateName(op->state()) << "\n"; PiiOperationCompound* compound = qobject_cast<PiiOperationCompound*>(op); if (compound != 0) { QList<PiiOperation*> children = compound->childOperations(); ++indent; for (int i=0; i<children.size(); ++i) dumpState(stream, children[i], indent); } } } #endif //_PIIYDINUTIL_H
<filename>drivers/flash/flash_handlers.c DECL|Z_SYSCALL_HANDLER|function|Z_SYSCALL_HANDLER(flash_get_page_count, dev) DECL|Z_SYSCALL_HANDLER|function|Z_SYSCALL_HANDLER(flash_get_page_info_by_idx, dev, idx, info) DECL|Z_SYSCALL_HANDLER|function|Z_SYSCALL_HANDLER(flash_get_page_info_by_offs, dev, offs, info) DECL|Z_SYSCALL_HANDLER|function|Z_SYSCALL_HANDLER(flash_read, dev, offset, data, len) DECL|Z_SYSCALL_HANDLER|function|Z_SYSCALL_HANDLER(flash_write, dev, offset, data, len) DECL|Z_SYSCALL_HANDLER|function|Z_SYSCALL_HANDLER(flash_write_protection_set, dev, enable)
<gh_stars>0 /***************************************************************************//** * @file * @brief Clock management unit (CMU) API ******************************************************************************* * # License * <b>Copyright 2018 Silicon Laboratories Inc. www.silabs.com</b> ******************************************************************************* * * SPDX-License-Identifier: Zlib * * The licensor of this software is Silicon Laboratories Inc. * * 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. * ******************************************************************************/ #ifndef EM_CMU_H #define EM_CMU_H #include "em_device.h" #if defined(CMU_PRESENT) #include <stdbool.h> #include "em_assert.h" #include "em_bus.h" #include "em_gpio.h" #include "em_common.h" #ifdef __cplusplus extern "C" { #endif /***************************************************************************//** * @addtogroup emlib * @{ ******************************************************************************/ /***************************************************************************//** * @addtogroup CMU * @{ ******************************************************************************/ #if defined(_SILICON_LABS_32B_SERIES_2) /** @cond DO_NOT_INCLUDE_WITH_DOXYGEN */ #if defined(_SILICON_LABS_32B_SERIES_2_CONFIG_2) /* Enable register bit positions, for internal use. */ #define CMU_EN_BIT_POS 0U #define CMU_EN_BIT_MASK 0x1FU /* Enable register ID's for internal use. */ #define CMU_NO_EN_REG 0 #define CMU_CLKEN0_EN_REG 1 #define CMU_CLKEN1_EN_REG 2 #define CMU_CRYPTOACCCLKCTRL_EN_REG 3 #define CMU_EN_REG_POS 5U #define CMU_EN_REG_MASK 0x3U /* Clock branch ID's internal use. */ #define CMU_CORE_BRANCH 0 #define CMU_SYSCLK_BRANCH 1 #define CMU_SYSTICK_BRANCH 2 #define CMU_HCLK_BRANCH 3 #define CMU_EXPCLK_BRANCH 4 #define CMU_PCLK_BRANCH 5 #define CMU_LSPCLK_BRANCH 6 #define CMU_TRACECLK_BRANCH 7 #define CMU_EM01GRPACLK_BRANCH 8 #define CMU_EM01GRPBCLK_BRANCH 9 #define CMU_EUART0CLK_BRANCH 10 #define CMU_IADCCLK_BRANCH 11 #define CMU_EM23GRPACLK_BRANCH 12 #define CMU_WDOG0CLK_BRANCH 13 #define CMU_RTCCCLK_BRANCH 14 #define CMU_EM4GRPACLK_BRANCH 15 #define CMU_PDMREF_BRANCH 16 #define CMU_DPLLREFCLK_BRANCH 17 #define CMU_CLK_BRANCH_POS 7U #define CMU_CLK_BRANCH_MASK 0x1FU #endif // defined(_SILICON_LABS_32B_SERIES_2_CONFIG_2) #if defined(_EMU_CMD_EM01VSCALE1_MASK) /* Maximum clock frequency for VSCALE voltages. */ #define CMU_VSCALEEM01_LOWPOWER_VOLTAGE_CLOCK_MAX 40000000UL #endif /* Macros for VSCALE for use with the CMU_UpdateWaitStates(freq, vscale) API. * NOTE: The values must align with the values in EMU_VScaleEM01_TypeDef for * Series1 parts (highest VSCALE voltage = lowest numerical value). */ #define VSCALE_EM01_LOW_POWER 1 #define VSCALE_EM01_HIGH_PERFORMANCE 0 #if defined(LFRCO_PRECISION_MODE) && LFRCO_PRECISION_MODE #define PLFRCO_PRESENT #endif /** @endcond */ /******************************************************************************* ******************************** ENUMS ************************************ ******************************************************************************/ /** Clock divider configuration */ typedef uint32_t CMU_ClkDiv_TypeDef; /** HFRCODPLL frequency bands */ typedef enum { cmuHFRCODPLLFreq_1M0Hz = 1000000U, /**< 1MHz RC band. */ cmuHFRCODPLLFreq_2M0Hz = 2000000U, /**< 2MHz RC band. */ cmuHFRCODPLLFreq_4M0Hz = 4000000U, /**< 4MHz RC band. */ cmuHFRCODPLLFreq_7M0Hz = 7000000U, /**< 7MHz RC band. */ cmuHFRCODPLLFreq_13M0Hz = 13000000U, /**< 13MHz RC band. */ cmuHFRCODPLLFreq_16M0Hz = 16000000U, /**< 16MHz RC band. */ cmuHFRCODPLLFreq_19M0Hz = 19000000U, /**< 19MHz RC band. */ cmuHFRCODPLLFreq_26M0Hz = 26000000U, /**< 26MHz RC band. */ cmuHFRCODPLLFreq_32M0Hz = 32000000U, /**< 32MHz RC band. */ cmuHFRCODPLLFreq_38M0Hz = 38000000U, /**< 38MHz RC band. */ cmuHFRCODPLLFreq_48M0Hz = 48000000U, /**< 48MHz RC band. */ cmuHFRCODPLLFreq_56M0Hz = 56000000U, /**< 56MHz RC band. */ cmuHFRCODPLLFreq_64M0Hz = 64000000U, /**< 64MHz RC band. */ cmuHFRCODPLLFreq_80M0Hz = 80000000U, /**< 80MHz RC band. */ cmuHFRCODPLLFreq_UserDefined = 0, } CMU_HFRCODPLLFreq_TypeDef; /** HFRCODPLL maximum frequency */ #define CMU_HFRCODPLL_MIN cmuHFRCODPLLFreq_1M0Hz /** HFRCODPLL minimum frequency */ #define CMU_HFRCODPLL_MAX cmuHFRCODPLLFreq_80M0Hz #if defined(_SILICON_LABS_32B_SERIES_2_CONFIG_1) /** HFRCOEM23 frequency bands */ typedef enum { cmuHFRCOEM23Freq_1M0Hz = 1000000U, /**< 1MHz RC band. */ cmuHFRCOEM23Freq_2M0Hz = 2000000U, /**< 2MHz RC band. */ cmuHFRCOEM23Freq_4M0Hz = 4000000U, /**< 4MHz RC band. */ cmuHFRCOEM23Freq_13M0Hz = 13000000U, /**< 13MHz RC band. */ cmuHFRCOEM23Freq_16M0Hz = 16000000U, /**< 16MHz RC band. */ cmuHFRCOEM23Freq_19M0Hz = 19000000U, /**< 19MHz RC band. */ cmuHFRCOEM23Freq_26M0Hz = 26000000U, /**< 26MHz RC band. */ cmuHFRCOEM23Freq_32M0Hz = 32000000U, /**< 32MHz RC band. */ cmuHFRCOEM23Freq_40M0Hz = 40000000U, /**< 40MHz RC band. */ cmuHFRCOEM23Freq_UserDefined = 0, } CMU_HFRCOEM23Freq_TypeDef; /** HFRCOEM23 maximum frequency */ #define CMU_HFRCOEM23_MIN cmuHFRCOEM23Freq_1M0Hz /** HFRCOEM23 minimum frequency */ #define CMU_HFRCOEM23_MAX cmuHFRCOEM23Freq_40M0Hz #endif // defined(_SILICON_LABS_32B_SERIES_2_CONFIG_1) #if defined(_SILICON_LABS_32B_SERIES_2_CONFIG_1) /** Clock points in CMU clock-tree. */ typedef enum { /*******************/ /* Clock branches */ /*******************/ cmuClock_SYSCLK, /**< System clock. */ cmuClock_HCLK, /**< Core and AHB bus interface clock. */ cmuClock_EXPCLK, /**< Export clock. */ cmuClock_PCLK, /**< Peripheral APB bus interface clock. */ cmuClock_LSPCLK, /**< Low speed peripheral APB bus interface clock. */ cmuClock_IADCCLK, /**< IADC clock. */ cmuClock_EM01GRPACLK, /**< EM01GRPA clock. */ cmuClock_EM23GRPACLK, /**< EM23GRPA clock. */ cmuClock_EM4GRPACLK, /**< EM4GRPA clock. */ cmuClock_WDOG0CLK, /**< WDOG0 clock. */ cmuClock_WDOG1CLK, /**< WDOG1 clock. */ cmuClock_DPLLREFCLK, /**< DPLL reference clock. */ cmuClock_TRACECLK, /**< Debug trace clock. */ cmuClock_RTCCCLK, /**< RTCC clock. */ /*********************/ /* Peripheral clocks */ /*********************/ cmuClock_CORE, /**< Cortex-M33 core clock. */ cmuClock_SYSTICK, /**< Optional Cortex-M33 SYSTICK clock. */ cmuClock_ACMP0, /**< ACMP0 clock. */ cmuClock_ACMP1, /**< ACMP1 clock. */ cmuClock_BURTC, /**< BURTC clock. */ cmuClock_GPCRC, /**< GPCRC clock. */ cmuClock_GPIO, /**< GPIO clock. */ cmuClock_I2C0, /**< I2C0 clock. */ cmuClock_I2C1, /**< I2C1 clock. */ cmuClock_IADC0, /**< IADC clock. */ cmuClock_LDMA, /**< RTCC clock. */ cmuClock_LETIMER0, /**< LETIMER clock. */ cmuClock_PRS, /**< PRS clock. */ cmuClock_RTCC, /**< RTCC clock. */ cmuClock_TIMER0, /**< TIMER0 clock. */ cmuClock_TIMER1, /**< TIMER1 clock. */ cmuClock_TIMER2, /**< TIMER2 clock. */ cmuClock_TIMER3, /**< TIMER3 clock. */ cmuClock_USART0, /**< USART0 clock. */ cmuClock_USART1, /**< USART1 clock. */ cmuClock_USART2, /**< USART2 clock. */ cmuClock_WDOG0, /**< WDOG0 clock. */ cmuClock_WDOG1, /**< WDOG1 clock. */ cmuClock_PDM /**< PDM clock. */ } CMU_Clock_TypeDef; #endif // defined(_SILICON_LABS_32B_SERIES_2_CONFIG_1) #if defined(_SILICON_LABS_32B_SERIES_2_CONFIG_2) typedef enum { /*******************/ /* Clock branches */ /*******************/ cmuClock_SYSCLK = (CMU_SYSCLK_BRANCH << CMU_CLK_BRANCH_POS), cmuClock_SYSTICK = (CMU_SYSTICK_BRANCH << CMU_CLK_BRANCH_POS), cmuClock_HCLK = (CMU_HCLK_BRANCH << CMU_CLK_BRANCH_POS), cmuClock_EXPCLK = (CMU_EXPCLK_BRANCH << CMU_CLK_BRANCH_POS), cmuClock_PCLK = (CMU_PCLK_BRANCH << CMU_CLK_BRANCH_POS), cmuClock_LSPCLK = (CMU_LSPCLK_BRANCH << CMU_CLK_BRANCH_POS), cmuClock_TRACECLK = (CMU_TRACECLK_BRANCH << CMU_CLK_BRANCH_POS), cmuClock_EM01GRPACLK = (CMU_EM01GRPACLK_BRANCH << CMU_CLK_BRANCH_POS), cmuClock_EM01GRPBCLK = (CMU_EM01GRPBCLK_BRANCH << CMU_CLK_BRANCH_POS), cmuClock_EUART0CLK = (CMU_EUART0CLK_BRANCH << CMU_CLK_BRANCH_POS), cmuClock_IADCCLK = (CMU_IADCCLK_BRANCH << CMU_CLK_BRANCH_POS), cmuClock_EM23GRPACLK = (CMU_EM23GRPACLK_BRANCH << CMU_CLK_BRANCH_POS), cmuClock_WDOG0CLK = (CMU_WDOG0CLK_BRANCH << CMU_CLK_BRANCH_POS), cmuClock_RTCCCLK = (CMU_RTCCCLK_BRANCH << CMU_CLK_BRANCH_POS), cmuClock_EM4GRPACLK = (CMU_EM4GRPACLK_BRANCH << CMU_CLK_BRANCH_POS), cmuClock_DPLLREFCLK = (CMU_DPLLREFCLK_BRANCH << CMU_CLK_BRANCH_POS), cmuClock_CRYPTOAES = (CMU_CRYPTOACCCLKCTRL_EN_REG << CMU_EN_REG_POS) | (_CMU_CRYPTOACCCLKCTRL_AESEN_SHIFT << CMU_EN_BIT_POS), cmuClock_CRYPTOPK = (CMU_CRYPTOACCCLKCTRL_EN_REG << CMU_EN_REG_POS) | (_CMU_CRYPTOACCCLKCTRL_PKEN_SHIFT << CMU_EN_BIT_POS), /*********************/ /* Peripheral clocks */ /*********************/ cmuClock_CORE = (CMU_CORE_BRANCH << CMU_CLK_BRANCH_POS), cmuClock_PDMREF = (CMU_PDMREF_BRANCH << CMU_CLK_BRANCH_POS), cmuClock_LDMA = (CMU_CLKEN0_EN_REG << CMU_EN_REG_POS) | (_CMU_CLKEN0_LDMA_SHIFT << CMU_EN_BIT_POS), cmuClock_LDMAXBAR = (CMU_CLKEN0_EN_REG << CMU_EN_REG_POS) | (_CMU_CLKEN0_LDMAXBAR_SHIFT << CMU_EN_BIT_POS), cmuClock_RADIOAES = (CMU_CLKEN0_EN_REG << CMU_EN_REG_POS) | (_CMU_CLKEN0_RADIOAES_SHIFT << CMU_EN_BIT_POS), cmuClock_GPCRC = (CMU_CLKEN0_EN_REG << CMU_EN_REG_POS) | (_CMU_CLKEN0_GPCRC_SHIFT << CMU_EN_BIT_POS), cmuClock_TIMER0 = (CMU_CLKEN0_EN_REG << CMU_EN_REG_POS) | (_CMU_CLKEN0_TIMER0_SHIFT << CMU_EN_BIT_POS), cmuClock_TIMER1 = (CMU_CLKEN0_EN_REG << CMU_EN_REG_POS) | (_CMU_CLKEN0_TIMER1_SHIFT << CMU_EN_BIT_POS), cmuClock_TIMER2 = (CMU_CLKEN0_EN_REG << CMU_EN_REG_POS) | (_CMU_CLKEN0_TIMER2_SHIFT << CMU_EN_BIT_POS), cmuClock_TIMER3 = (CMU_CLKEN0_EN_REG << CMU_EN_REG_POS) | (_CMU_CLKEN0_TIMER3_SHIFT << CMU_EN_BIT_POS), cmuClock_USART0 = (CMU_CLKEN0_EN_REG << CMU_EN_REG_POS) | (_CMU_CLKEN0_USART0_SHIFT << CMU_EN_BIT_POS), cmuClock_USART1 = (CMU_CLKEN0_EN_REG << CMU_EN_REG_POS) | (_CMU_CLKEN0_USART1_SHIFT << CMU_EN_BIT_POS), cmuClock_IADC0 = (CMU_CLKEN0_EN_REG << CMU_EN_REG_POS) | (_CMU_CLKEN0_IADC0_SHIFT << CMU_EN_BIT_POS), cmuClock_AMUXCP0 = (CMU_CLKEN0_EN_REG << CMU_EN_REG_POS) | (_CMU_CLKEN0_AMUXCP0_SHIFT << CMU_EN_BIT_POS), cmuClock_LETIMER0 = (CMU_CLKEN0_EN_REG << CMU_EN_REG_POS) | (_CMU_CLKEN0_LETIMER0_SHIFT << CMU_EN_BIT_POS), cmuClock_WDOG0 = (CMU_CLKEN0_EN_REG << CMU_EN_REG_POS) | (_CMU_CLKEN0_WDOG0_SHIFT << CMU_EN_BIT_POS), cmuClock_I2C0 = (CMU_CLKEN0_EN_REG << CMU_EN_REG_POS) | (_CMU_CLKEN0_I2C0_SHIFT << CMU_EN_BIT_POS), cmuClock_I2C1 = (CMU_CLKEN0_EN_REG << CMU_EN_REG_POS) | (_CMU_CLKEN0_I2C1_SHIFT << CMU_EN_BIT_POS), cmuClock_SYSCFG = (CMU_CLKEN0_EN_REG << CMU_EN_REG_POS) | (_CMU_CLKEN0_SYSCFG_SHIFT << CMU_EN_BIT_POS), cmuClock_DPLL0 = (CMU_CLKEN0_EN_REG << CMU_EN_REG_POS) | (_CMU_CLKEN0_DPLL0_SHIFT << CMU_EN_BIT_POS), cmuClock_HFRCO0 = (CMU_CLKEN0_EN_REG << CMU_EN_REG_POS) | (_CMU_CLKEN0_HFRCO0_SHIFT << CMU_EN_BIT_POS), cmuClock_HFXO = (CMU_CLKEN0_EN_REG << CMU_EN_REG_POS) | (_CMU_CLKEN0_HFXO0_SHIFT << CMU_EN_BIT_POS), cmuClock_FSRCO = (CMU_CLKEN0_EN_REG << CMU_EN_REG_POS) | (_CMU_CLKEN0_FSRCO_SHIFT << CMU_EN_BIT_POS), cmuClock_LFRCO = (CMU_CLKEN0_EN_REG << CMU_EN_REG_POS) | (_CMU_CLKEN0_LFRCO_SHIFT << CMU_EN_BIT_POS), cmuClock_LFXO = (CMU_CLKEN0_EN_REG << CMU_EN_REG_POS) | (_CMU_CLKEN0_LFXO_SHIFT << CMU_EN_BIT_POS), cmuClock_ULFRCO = (CMU_CLKEN0_EN_REG << CMU_EN_REG_POS) | (_CMU_CLKEN0_ULFRCO_SHIFT << CMU_EN_BIT_POS), cmuClock_EUART0 = (CMU_CLKEN0_EN_REG << CMU_EN_REG_POS) | (_CMU_CLKEN0_EUART0_SHIFT << CMU_EN_BIT_POS), cmuClock_PDM = (CMU_CLKEN0_EN_REG << CMU_EN_REG_POS) | (_CMU_CLKEN0_PDM_SHIFT << CMU_EN_BIT_POS), cmuClock_GPIO = (CMU_CLKEN0_EN_REG << CMU_EN_REG_POS) | (_CMU_CLKEN0_GPIO_SHIFT << CMU_EN_BIT_POS), cmuClock_PRS = (CMU_CLKEN0_EN_REG << CMU_EN_REG_POS) | (_CMU_CLKEN0_PRS_SHIFT << CMU_EN_BIT_POS), cmuClock_BURAM = (CMU_CLKEN0_EN_REG << CMU_EN_REG_POS) | (_CMU_CLKEN0_BURAM_SHIFT << CMU_EN_BIT_POS), cmuClock_BURTC = (CMU_CLKEN0_EN_REG << CMU_EN_REG_POS) | (_CMU_CLKEN0_BURTC_SHIFT << CMU_EN_BIT_POS), cmuClock_RTCC = (CMU_CLKEN0_EN_REG << CMU_EN_REG_POS) | (_CMU_CLKEN0_RTCC_SHIFT << CMU_EN_BIT_POS), cmuClock_DCDC = (CMU_CLKEN0_EN_REG << CMU_EN_REG_POS) | (_CMU_CLKEN0_DCDC_SHIFT << CMU_EN_BIT_POS), cmuClock_IFADCDEBUG = (CMU_CLKEN1_EN_REG << CMU_EN_REG_POS) | (_CMU_CLKEN1_IFADCDEBUG_SHIFT << CMU_EN_BIT_POS), cmuClock_CRYPTOACC = (CMU_CLKEN1_EN_REG << CMU_EN_REG_POS) | (_CMU_CLKEN1_CRYPTOACC_SHIFT << CMU_EN_BIT_POS), cmuClock_SMU = (CMU_CLKEN1_EN_REG << CMU_EN_REG_POS) | (_CMU_CLKEN1_SMU_SHIFT << CMU_EN_BIT_POS), cmuClock_ICACHE = (CMU_CLKEN1_EN_REG << CMU_EN_REG_POS) | (_CMU_CLKEN1_ICACHE0_SHIFT << CMU_EN_BIT_POS), cmuClock_MSC = (CMU_CLKEN1_EN_REG << CMU_EN_REG_POS) | (_CMU_CLKEN1_MSC_SHIFT << CMU_EN_BIT_POS), cmuClock_TIMER4 = (CMU_CLKEN1_EN_REG << CMU_EN_REG_POS) | (_CMU_CLKEN1_TIMER4_SHIFT << CMU_EN_BIT_POS) } CMU_Clock_TypeDef; #endif // defined(_SILICON_LABS_32B_SERIES_2_CONFIG_2) /** Oscillator types. */ typedef enum { cmuOsc_LFXO, /**< Low frequency crystal oscillator. */ cmuOsc_LFRCO, /**< Low frequency RC oscillator. */ cmuOsc_FSRCO, /**< Fast startup fixed frequency RC oscillator. */ cmuOsc_HFXO, /**< High frequency crystal oscillator. */ cmuOsc_HFRCODPLL, /**< High frequency RC and DPLL oscillator. */ #if defined(_SILICON_LABS_32B_SERIES_2_CONFIG_1) cmuOsc_HFRCOEM23, /**< High frequency deep sleep RC oscillator. */ #endif cmuOsc_ULFRCO, /**< Ultra low frequency RC oscillator. */ } CMU_Osc_TypeDef; #if defined(_SILICON_LABS_32B_SERIES_2_CONFIG_1) /** Selectable clock sources. */ typedef enum { cmuSelect_Error, /**< Usage error. */ cmuSelect_Disabled, /**< Clock selector disabled. */ cmuSelect_FSRCO, /**< Fast startup fixed frequency RC oscillator. */ cmuSelect_HFXO, /**< High frequency crystal oscillator. */ cmuSelect_HFRCODPLL, /**< High frequency RC and DPLL oscillator. */ cmuSelect_HFRCOEM23, /**< High frequency deep sleep RC oscillator. */ cmuSelect_CLKIN0, /**< External clock input. */ cmuSelect_LFXO, /**< Low frequency crystal oscillator. */ cmuSelect_LFRCO, /**< Low frequency RC oscillator. */ cmuSelect_ULFRCO, /**< Ultra low frequency RC oscillator. */ cmuSelect_PCLK, /**< Peripheral APB bus interface clock. */ cmuSelect_HCLK, /**< Core and AHB bus interface clock. */ cmuSelect_HCLKDIV1024, /**< Prescaled HCLK frequency clock. */ cmuSelect_EM01GRPACLK, /**< EM01GRPA clock. */ cmuSelect_EXPCLK, /**< Pin export clock. */ cmuSelect_PRS /**< PRS input as clock. */ } CMU_Select_TypeDef; #endif // defined(_SILICON_LABS_32B_SERIES_2_CONFIG_1) #if defined(_SILICON_LABS_32B_SERIES_2_CONFIG_2) /** Selectable clock sources. */ typedef enum { cmuSelect_Error, /**< Usage error. */ cmuSelect_Disabled, /**< Clock selector disabled. */ cmuSelect_FSRCO, /**< Fast startup fixed frequency RC oscillator. */ cmuSelect_HFXO, /**< High frequency crystal oscillator. */ cmuSelect_HFXORT, /**< Re-timed high frequency crystal oscillator. */ cmuSelect_HFRCODPLL, /**< High frequency RC and DPLL oscillator. */ cmuSelect_HFRCODPLLRT, /**< Re-timed high frequency RC and DPLL oscillator. */ cmuSelect_CLKIN0, /**< External clock input. */ cmuSelect_LFXO, /**< Low frequency crystal oscillator. */ cmuSelect_LFRCO, /**< Low frequency RC oscillator. */ cmuSelect_ULFRCO, /**< Ultra low frequency RC oscillator. */ cmuSelect_HCLK, /**< Core and AHB bus interface clock. */ cmuSelect_HCLKDIV1024, /**< Prescaled HCLK frequency clock. */ cmuSelect_EM01GRPACLK, /**< EM01GRPA clock. */ cmuSelect_EM23GRPACLK, /**< EM23GRPA clock. */ cmuSelect_EXPCLK, /**< Pin export clock. */ cmuSelect_PRS, /**< PRS input as clock. */ cmuSelect_TEMPOSC, /**< Temperatur oscillator. */ cmuSelect_PFMOSC, /**< PFM oscillator. */ cmuSelect_BIASOSC /**< BIAS oscillator. */ } CMU_Select_TypeDef; #endif // defined(_SILICON_LABS_32B_SERIES_2_CONFIG_2) /** DPLL reference clock edge detect selector. */ typedef enum { cmuDPLLEdgeSel_Fall = 0, /**< Detect falling edge of reference clock. */ cmuDPLLEdgeSel_Rise = 1 /**< Detect rising edge of reference clock. */ } CMU_DPLLEdgeSel_TypeDef; /** DPLL lock mode selector. */ typedef enum { cmuDPLLLockMode_Freq = _DPLL_CFG_MODE_FLL, /**< Frequency lock mode. */ cmuDPLLLockMode_Phase = _DPLL_CFG_MODE_PLL /**< Phase lock mode. */ } CMU_DPLLLockMode_TypeDef; /** LFXO oscillator modes. */ typedef enum { cmuLfxoOscMode_Crystal = _LFXO_CFG_MODE_XTAL, /**< Crystal oscillator. */ cmuLfxoOscMode_AcCoupledSine = _LFXO_CFG_MODE_BUFEXTCLK, /**< External AC coupled sine. */ cmuLfxoOscMode_External = _LFXO_CFG_MODE_DIGEXTCLK, /**< External digital clock. */ } CMU_LfxoOscMode_TypeDef; /** LFXO start-up timeout delay. */ typedef enum { cmuLfxoStartupDelay_2Cycles = _LFXO_CFG_TIMEOUT_CYCLES2, /**< 2 cycles start-up delay. */ cmuLfxoStartupDelay_256Cycles = _LFXO_CFG_TIMEOUT_CYCLES256, /**< 256 cycles start-up delay. */ cmuLfxoStartupDelay_1KCycles = _LFXO_CFG_TIMEOUT_CYCLES1K, /**< 1K cycles start-up delay. */ cmuLfxoStartupDelay_2KCycles = _LFXO_CFG_TIMEOUT_CYCLES2K, /**< 2K cycles start-up delay. */ cmuLfxoStartupDelay_4KCycles = _LFXO_CFG_TIMEOUT_CYCLES4K, /**< 4K cycles start-up delay. */ cmuLfxoStartupDelay_8KCycles = _LFXO_CFG_TIMEOUT_CYCLES8K, /**< 8K cycles start-up delay. */ cmuLfxoStartupDelay_16KCycles = _LFXO_CFG_TIMEOUT_CYCLES16K, /**< 16K cycles start-up delay. */ cmuLfxoStartupDelay_32KCycles = _LFXO_CFG_TIMEOUT_CYCLES32K, /**< 32K cycles start-up delay. */ } CMU_LfxoStartupDelay_TypeDef; /** HFXO oscillator modes. */ typedef enum { cmuHfxoOscMode_Crystal = _HFXO_CFG_MODE_XTAL, /**< Crystal oscillator. */ cmuHfxoOscMode_ExternalSine = _HFXO_CFG_MODE_EXTCLK, /**< External digital clock. */ } CMU_HfxoOscMode_TypeDef; /** HFXO core bias LSB change timeout. */ typedef enum { cmuHfxoCbLsbTimeout_8us = _HFXO_XTALCFG_TIMEOUTCBLSB_T8US, /**< 8 us timeout. */ cmuHfxoCbLsbTimeout_20us = _HFXO_XTALCFG_TIMEOUTCBLSB_T20US, /**< 20 us timeout. */ cmuHfxoCbLsbTimeout_41us = _HFXO_XTALCFG_TIMEOUTCBLSB_T41US, /**< 41 us timeout. */ cmuHfxoCbLsbTimeout_62us = _HFXO_XTALCFG_TIMEOUTCBLSB_T62US, /**< 62 us timeout. */ cmuHfxoCbLsbTimeout_83us = _HFXO_XTALCFG_TIMEOUTCBLSB_T83US, /**< 83 us timeout. */ cmuHfxoCbLsbTimeout_104us = _HFXO_XTALCFG_TIMEOUTCBLSB_T104US, /**< 104 us timeout. */ cmuHfxoCbLsbTimeout_125us = _HFXO_XTALCFG_TIMEOUTCBLSB_T125US, /**< 125 us timeout. */ cmuHfxoCbLsbTimeout_166us = _HFXO_XTALCFG_TIMEOUTCBLSB_T166US, /**< 166 us timeout. */ cmuHfxoCbLsbTimeout_208us = _HFXO_XTALCFG_TIMEOUTCBLSB_T208US, /**< 208 us timeout. */ cmuHfxoCbLsbTimeout_250us = _HFXO_XTALCFG_TIMEOUTCBLSB_T250US, /**< 250 us timeout. */ cmuHfxoCbLsbTimeout_333us = _HFXO_XTALCFG_TIMEOUTCBLSB_T333US, /**< 333 us timeout. */ cmuHfxoCbLsbTimeout_416us = _HFXO_XTALCFG_TIMEOUTCBLSB_T416US, /**< 416 us timeout. */ cmuHfxoCbLsbTimeout_833us = _HFXO_XTALCFG_TIMEOUTCBLSB_T833US, /**< 833 us timeout. */ cmuHfxoCbLsbTimeout_1250us = _HFXO_XTALCFG_TIMEOUTCBLSB_T1250US, /**< 1250 us timeout. */ cmuHfxoCbLsbTimeout_2083us = _HFXO_XTALCFG_TIMEOUTCBLSB_T2083US, /**< 2083 us timeout. */ cmuHfxoCbLsbTimeout_3750us = _HFXO_XTALCFG_TIMEOUTCBLSB_T3750US, /**< 3750 us timeout. */ } CMU_HfxoCbLsbTimeout_TypeDef; /** HFXO steady state timeout. */ typedef enum { cmuHfxoSteadyStateTimeout_16us = _HFXO_XTALCFG_TIMEOUTSTEADY_T16US, /**< 16 us timeout. */ cmuHfxoSteadyStateTimeout_41us = _HFXO_XTALCFG_TIMEOUTSTEADY_T41US, /**< 41 us timeout. */ cmuHfxoSteadyStateTimeout_83us = _HFXO_XTALCFG_TIMEOUTSTEADY_T83US, /**< 83 us timeout. */ cmuHfxoSteadyStateTimeout_125us = _HFXO_XTALCFG_TIMEOUTSTEADY_T125US, /**< 125 us timeout. */ cmuHfxoSteadyStateTimeout_166us = _HFXO_XTALCFG_TIMEOUTSTEADY_T166US, /**< 166 us timeout. */ cmuHfxoSteadyStateTimeout_208us = _HFXO_XTALCFG_TIMEOUTSTEADY_T208US, /**< 208 us timeout. */ cmuHfxoSteadyStateTimeout_250us = _HFXO_XTALCFG_TIMEOUTSTEADY_T250US, /**< 250 us timeout. */ cmuHfxoSteadyStateTimeout_333us = _HFXO_XTALCFG_TIMEOUTSTEADY_T333US, /**< 333 us timeout. */ cmuHfxoSteadyStateTimeout_416us = _HFXO_XTALCFG_TIMEOUTSTEADY_T416US, /**< 416 us timeout. */ cmuHfxoSteadyStateTimeout_500us = _HFXO_XTALCFG_TIMEOUTSTEADY_T500US, /**< 500 us timeout. */ cmuHfxoSteadyStateTimeout_666us = _HFXO_XTALCFG_TIMEOUTSTEADY_T666US, /**< 666 us timeout. */ cmuHfxoSteadyStateTimeout_833us = _HFXO_XTALCFG_TIMEOUTSTEADY_T833US, /**< 833 us timeout. */ cmuHfxoSteadyStateTimeout_1666us = _HFXO_XTALCFG_TIMEOUTSTEADY_T1666US, /**< 1666 us timeout. */ cmuHfxoSteadyStateTimeout_2500us = _HFXO_XTALCFG_TIMEOUTSTEADY_T2500US, /**< 2500 us timeout. */ cmuHfxoSteadyStateTimeout_4166us = _HFXO_XTALCFG_TIMEOUTSTEADY_T4166US, /**< 4166 us timeout. */ cmuHfxoSteadyStateTimeout_7500us = _HFXO_XTALCFG_TIMEOUTSTEADY_T7500US, /**< 7500 us timeout. */ } CMU_HfxoSteadyStateTimeout_TypeDef; /** HFXO core degeneration control. */ typedef enum { cmuHfxoCoreDegen_None = _HFXO_XTALCTRL_COREDGENANA_NONE, /**< No core degeneration. */ cmuHfxoCoreDegen_33 = _HFXO_XTALCTRL_COREDGENANA_DGEN33, /**< Core degeneration control 33. */ cmuHfxoCoreDegen_50 = _HFXO_XTALCTRL_COREDGENANA_DGEN50, /**< Core degeneration control 50. */ cmuHfxoCoreDegen_100 = _HFXO_XTALCTRL_COREDGENANA_DGEN100, /**< Core degeneration control 100. */ } CMU_HfxoCoreDegen_TypeDef; /** HFXO XI and XO pin fixed capacitor control. */ typedef enum { cmuHfxoCtuneFixCap_None = _HFXO_XTALCTRL_CTUNEFIXANA_NONE, /**< No fixed capacitors. */ cmuHfxoCtuneFixCap_Xi = _HFXO_XTALCTRL_CTUNEFIXANA_XI, /**< Fixed capacitor on XI pin. */ cmuHfxoCtuneFixCap_Xo = _HFXO_XTALCTRL_CTUNEFIXANA_XO, /**< Fixed capacitor on XO pin. */ cmuHfxoCtuneFixCap_Both = _HFXO_XTALCTRL_CTUNEFIXANA_BOTH, /**< Fixed capacitor on both pins. */ } CMU_HfxoCtuneFixCap_TypeDef; /* Oscillator precision modes. */ typedef enum { cmuPrecisionDefault, /**< Default precision mode. */ cmuPrecisionHigh, /**< High precision mode. */ } CMU_Precision_TypeDef; /******************************************************************************* ******************************* STRUCTS *********************************** ******************************************************************************/ /** LFXO initialization structure. Init values should be obtained from a configuration tool, app. note or xtal datasheet. */ typedef struct { uint8_t gain; /**< Startup gain. */ uint8_t capTune; /**< Internal capacitance tuning. */ CMU_LfxoStartupDelay_TypeDef timeout; /**< Startup delay. */ CMU_LfxoOscMode_TypeDef mode; /**< Oscillator mode. */ bool highAmplitudeEn; /**< High amplitude enable. */ bool agcEn; /**< AGC enable. */ bool failDetEM4WUEn; /**< EM4 wakeup on failure enable. */ bool failDetEn; /**< Oscillator failure detection enable. */ bool disOnDemand; /**< Disable on-demand requests. */ bool forceEn; /**< Force oscillator enable. */ bool regLock; /**< Lock register access. */ } CMU_LFXOInit_TypeDef; /** Default LFXO initialization values for XTAL mode. */ #define CMU_LFXOINIT_DEFAULT \ { \ 1, \ 38, \ cmuLfxoStartupDelay_4KCycles, \ cmuLfxoOscMode_Crystal, \ false, /* highAmplitudeEn */ \ true, /* agcEn */ \ false, /* failDetEM4WUEn */ \ false, /* failDetEn */ \ false, /* DisOndemand */ \ false, /* ForceEn */ \ false /* Lock registers */ \ } /** Default LFXO initialization values for external clock mode. */ #define CMU_LFXOINIT_EXTERNAL_CLOCK \ { \ 0U, \ 0U, \ cmuLfxoStartupDelay_2Cycles, \ cmuLfxoOscMode_External, \ false, /* highAmplitudeEn */ \ false, /* agcEn */ \ false, /* failDetEM4WUEn */ \ false, /* failDetEn */ \ false, /* DisOndemand */ \ false, /* ForceEn */ \ false /* Lock registers */ \ } /** Default LFXO initialization values for external sine mode. */ #define CMU_LFXOINIT_EXTERNAL_SINE \ { \ 0U, \ 0U, \ cmuLfxoStartupDelay_2Cycles, \ cmuLfxoOscMode_AcCoupledSine, \ false, /* highAmplitudeEn */ \ false, /* agcEn */ \ false, /* failDetEM4WUEn */ \ false, /* failDetEn */ \ false, /* DisOndemand */ \ false, /* ForceEn */ \ false /* Lock registers */ \ } /** HFXO initialization structure. Init values should be obtained from a configuration tool, app. note or xtal datasheet. */ typedef struct { CMU_HfxoCbLsbTimeout_TypeDef timeoutCbLsb; /**< Core bias change timeout. */ CMU_HfxoSteadyStateTimeout_TypeDef timeoutSteadyFirstLock; /**< Steady state timeout duration for first lock. */ CMU_HfxoSteadyStateTimeout_TypeDef timeoutSteady; /**< Steady state timeout duration. */ uint8_t ctuneXoStartup; /**< XO pin startup tuning capacitance. */ uint8_t ctuneXiStartup; /**< XI pin startup tuning capacitance. */ uint8_t coreBiasStartup; /**< Core bias startup current. */ uint8_t imCoreBiasStartup; /**< Core bias intermediate startup current. */ CMU_HfxoCoreDegen_TypeDef coreDegenAna; /**< Core degeneration control. */ CMU_HfxoCtuneFixCap_TypeDef ctuneFixAna; /**< Fixed tuning capacitance on XI/XO. */ uint8_t ctuneXoAna; /**< Tuning capacitance on XO. */ uint8_t ctuneXiAna; /**< Tuning capacitance on XI. */ uint8_t coreBiasAna; /**< Core bias current. */ bool enXiDcBiasAna; /**< Enable XI internal DC bias. */ CMU_HfxoOscMode_TypeDef mode; /**< Oscillator mode. */ bool forceXo2GndAna; /**< Force XO pin to ground. */ bool forceXi2GndAna; /**< Force XI pin to ground. */ bool disOnDemand; /**< Disable on-demand requests. */ bool forceEn; /**< Force oscillator enable. */ bool regLock; /**< Lock register access. */ } CMU_HFXOInit_TypeDef; /** Default HFXO initialization values for XTAL mode. */ #define CMU_HFXOINIT_DEFAULT \ { \ cmuHfxoCbLsbTimeout_416us, \ cmuHfxoSteadyStateTimeout_833us, /* First lock */ \ cmuHfxoSteadyStateTimeout_83us, /* Subsequent locks */ \ 0U, /* ctuneXoStartup */ \ 0U, /* ctuneXiStartup */ \ 32U, /* coreBiasStartup */ \ 32U, /* imCoreBiasStartup */ \ cmuHfxoCoreDegen_None, \ cmuHfxoCtuneFixCap_Both, \ _HFXO_XTALCTRL_CTUNEXOANA_DEFAULT, /* ctuneXoAna */ \ _HFXO_XTALCTRL_CTUNEXIANA_DEFAULT, /* ctuneXiAna */ \ 60U, /* coreBiasAna */ \ false, /* enXiDcBiasAna */ \ cmuHfxoOscMode_Crystal, \ false, /* forceXo2GndAna */ \ false, /* forceXi2GndAna */ \ false, /* DisOndemand */ \ false, /* ForceEn */ \ false /* Lock registers */ \ } /** Default HFXO initialization values for external sine mode. */ #define CMU_HFXOINIT_EXTERNAL_SINE \ { \ (CMU_HfxoCbLsbTimeout_TypeDef)0, /* timeoutCbLsb */ \ (CMU_HfxoSteadyStateTimeout_TypeDef)0, /* timeoutSteady, first lock */ \ (CMU_HfxoSteadyStateTimeout_TypeDef)0, /* timeoutSteady, subseq. locks */ \ 0U, /* ctuneXoStartup */ \ 0U, /* ctuneXiStartup */ \ 0U, /* coreBiasStartup */ \ 0U, /* imCoreBiasStartup */ \ cmuHfxoCoreDegen_None, \ cmuHfxoCtuneFixCap_None, \ 0U, /* ctuneXoAna */ \ 0U, /* ctuneXiAna */ \ 0U, /* coreBiasAna */ \ false, /* enXiDcBiasAna, false=DC true=AC coupling of signal */ \ cmuHfxoOscMode_ExternalSine, \ false, /* forceXo2GndAna */ \ false, /* forceXi2GndAna */ \ false, /* DisOndemand */ \ false, /* ForceEn */ \ false /* Lock registers */ \ } /** DPLL initialization structure. Frequency will be Fref*(N+1)/(M+1). */ typedef struct { uint32_t frequency; /**< PLL frequency value, max 80 MHz. */ uint16_t n; /**< Factor N. 300 <= N <= 4095 */ uint16_t m; /**< Factor M. M <= 4095 */ CMU_Select_TypeDef refClk; /**< Reference clock selector. */ CMU_DPLLEdgeSel_TypeDef edgeSel; /**< Reference clock edge detect selector. */ CMU_DPLLLockMode_TypeDef lockMode; /**< DPLL lock mode selector. */ bool autoRecover; /**< Enable automatic lock recovery. */ bool ditherEn; /**< Enable dither functionalityery. */ } CMU_DPLLInit_TypeDef; /** * DPLL initialization values for 39,998,805 Hz using LFXO as reference * clock, M=2 and N=3661. */ #define CMU_DPLL_LFXO_TO_40MHZ \ { \ 39998805, /* Target frequency. */ \ 3661, /* Factor N. */ \ 2, /* Factor M. */ \ cmuSelect_LFXO, /* Select LFXO as reference clock. */ \ cmuDPLLEdgeSel_Fall, /* Select falling edge of ref clock. */ \ cmuDPLLLockMode_Freq, /* Use frequency lock mode. */ \ true, /* Enable automatic lock recovery. */ \ false /* Don't enable dither function. */ \ } /** * DPLL initialization values for 76,800,000 Hz using HFXO as reference * clock, M = 1919, N = 3839 */ #define CMU_DPLL_HFXO_TO_76_8MHZ \ { \ 76800000, /* Target frequency. */ \ 3839, /* Factor N. */ \ 1919, /* Factor M. */ \ cmuSelect_HFXO, /* Select HFXO as reference clock. */ \ cmuDPLLEdgeSel_Fall, /* Select falling edge of ref clock. */ \ cmuDPLLLockMode_Freq, /* Use frequency lock mode. */ \ true, /* Enable automatic lock recovery. */ \ false /* Don't enable dither function. */ \ } /** * DPLL initialization values for 80,000,000 Hz using HFXO as reference * clock, M = 1919, N = 3999. */ #define CMU_DPLL_HFXO_TO_80MHZ \ { \ 80000000, /* Target frequency. */ \ (4000 - 1), /* Factor N. */ \ (1920 - 1), /* Factor M. */ \ cmuSelect_HFXO, /* Select HFXO as reference clock. */ \ cmuDPLLEdgeSel_Fall, /* Select falling edge of ref clock. */ \ cmuDPLLLockMode_Freq, /* Use frequency lock mode. */ \ true, /* Enable automatic lock recovery. */ \ false /* Don't enable dither function. */ \ } /** * Default configurations for DPLL initialization. When using this macro * you need to modify the N and M factor and the desired frequency to match * the components placed on the board. */ #define CMU_DPLLINIT_DEFAULT \ { \ 80000000, /* Target frequency. */ \ (4000 - 1), /* Factor N. */ \ (1920 - 1), /* Factor M. */ \ cmuSelect_HFXO, /* Select HFXO as reference clock. */ \ cmuDPLLEdgeSel_Fall, /* Select falling edge of ref clock. */ \ cmuDPLLLockMode_Freq, /* Use frequency lock mode. */ \ true, /* Enable automatic lock recovery. */ \ false /* Don't enable dither function. */ \ } /******************************************************************************* ***************************** PROTOTYPES ********************************** ******************************************************************************/ uint32_t CMU_Calibrate(uint32_t cycles, CMU_Select_TypeDef reference); void CMU_CalibrateConfig(uint32_t downCycles, CMU_Select_TypeDef downSel, CMU_Select_TypeDef upSel); uint32_t CMU_CalibrateCountGet(void); void CMU_ClkOutPinConfig(uint32_t clkno, CMU_Select_TypeDef sel, CMU_ClkDiv_TypeDef clkdiv, GPIO_Port_TypeDef port, unsigned int pin); CMU_ClkDiv_TypeDef CMU_ClockDivGet(CMU_Clock_TypeDef clock); void CMU_ClockDivSet(CMU_Clock_TypeDef clock, CMU_ClkDiv_TypeDef div); uint32_t CMU_ClockFreqGet(CMU_Clock_TypeDef clock); CMU_Select_TypeDef CMU_ClockSelectGet(CMU_Clock_TypeDef clock); void CMU_ClockSelectSet(CMU_Clock_TypeDef clock, CMU_Select_TypeDef ref); CMU_HFRCODPLLFreq_TypeDef CMU_HFRCODPLLBandGet(void); void CMU_HFRCODPLLBandSet(CMU_HFRCODPLLFreq_TypeDef freq); bool CMU_DPLLLock(const CMU_DPLLInit_TypeDef *init); void CMU_HFXOInit(const CMU_HFXOInit_TypeDef *hfxoInit); void CMU_LFXOInit(const CMU_LFXOInit_TypeDef *lfxoInit); uint32_t CMU_OscillatorTuningGet(CMU_Osc_TypeDef osc); void CMU_OscillatorTuningSet(CMU_Osc_TypeDef osc, uint32_t val); void CMU_UpdateWaitStates(uint32_t freq, int vscale); #if defined(_SILICON_LABS_32B_SERIES_2_CONFIG_2) void CMU_ClockEnable(CMU_Clock_TypeDef clock, bool enable); #endif #if defined(_SILICON_LABS_32B_SERIES_2_CONFIG_1) CMU_HFRCOEM23Freq_TypeDef CMU_HFRCOEM23BandGet(void); void CMU_HFRCOEM23BandSet(CMU_HFRCOEM23Freq_TypeDef freq); #endif #if defined(PLFRCO_PRESENT) void CMU_LFRCOSetPrecision(CMU_Precision_TypeDef precision); #endif #if defined(_SILICON_LABS_32B_SERIES_2_CONFIG_1) /***************************************************************************//** * @brief * Enable/disable a clock. * * @note * This is a dummy function to solve backward compatibility issues. * * @param[in] clock * The clock to enable/disable. * * @param[in] enable * @li true - enable specified clock. * @li false - disable specified clock. ******************************************************************************/ __STATIC_INLINE void CMU_ClockEnable(CMU_Clock_TypeDef clock, bool enable) { (void)clock; (void)enable; } #endif /***************************************************************************//** * @brief * Configures continuous calibration mode. * @param[in] enable * If true, enables continuous calibration, if false disables continuous * calibration. ******************************************************************************/ __STATIC_INLINE void CMU_CalibrateCont(bool enable) { BUS_RegBitWrite(&CMU->CALCTRL, _CMU_CALCTRL_CONT_SHIFT, (uint32_t)enable); } /***************************************************************************//** * @brief * Starts calibration. * @note * This call is usually invoked after @ref CMU_CalibrateConfig() and possibly * @ref CMU_CalibrateCont(). ******************************************************************************/ __STATIC_INLINE void CMU_CalibrateStart(void) { CMU->CALCMD = CMU_CALCMD_CALSTART; } /***************************************************************************//** * @brief * Stop calibration counters. ******************************************************************************/ __STATIC_INLINE void CMU_CalibrateStop(void) { CMU->CALCMD = CMU_CALCMD_CALSTOP; } /***************************************************************************//** * @brief * Unlock the DPLL. * @note * The HFRCODPLL oscillator is not turned off. ******************************************************************************/ __STATIC_INLINE void CMU_DPLLUnlock(void) { DPLL0->EN_CLR = DPLL_EN_EN; } /***************************************************************************//** * @brief * Clear one or more pending CMU interrupt flags. * * @param[in] flags * CMU interrupt sources to clear. ******************************************************************************/ __STATIC_INLINE void CMU_IntClear(uint32_t flags) { CMU->IF_CLR = flags; } /***************************************************************************//** * @brief * Disable one or more CMU interrupt sources. * * @param[in] flags * CMU interrupt sources to disable. ******************************************************************************/ __STATIC_INLINE void CMU_IntDisable(uint32_t flags) { CMU->IEN_CLR = flags; } /***************************************************************************//** * @brief * Enable one or more CMU interrupt sources. * * @note * Depending on the use, a pending interrupt may already be set prior to * enabling the interrupt. Consider using @ref CMU_IntClear() prior to * enabling if such a pending interrupt should be ignored. * * @param[in] flags * CMU interrupt sources to enable. ******************************************************************************/ __STATIC_INLINE void CMU_IntEnable(uint32_t flags) { CMU->IEN_SET = flags; } /***************************************************************************//** * @brief * Get pending CMU interrupt sources. * * @return * CMU interrupt sources pending. ******************************************************************************/ __STATIC_INLINE uint32_t CMU_IntGet(void) { return CMU->IF; } /***************************************************************************//** * @brief * Get enabled and pending CMU interrupt flags. * * @details * Useful for handling more interrupt sources in the same interrupt handler. * * @note * The event bits are not cleared by the use of this function. * * @return * Pending and enabled CMU interrupt sources. * The return value is the bitwise AND of * - the enabled interrupt sources in CMU_IEN and * - the pending interrupt flags CMU_IF ******************************************************************************/ __STATIC_INLINE uint32_t CMU_IntGetEnabled(void) { uint32_t ien; ien = CMU->IEN; return CMU->IF & ien; } /**************************************************************************//** * @brief * Set one or more pending CMU interrupt sources. * * @param[in] flags * CMU interrupt sources to set to pending. *****************************************************************************/ __STATIC_INLINE void CMU_IntSet(uint32_t flags) { CMU->IF_SET = flags; } /***************************************************************************//** * @brief * Lock CMU register access in order to protect registers contents against * unintended modification. * * @details * Please refer to the reference manual for CMU registers that will be * locked. * * @note * If locking the CMU registers, they must be unlocked prior to using any * CMU API functions modifying CMU registers protected by the lock. ******************************************************************************/ __STATIC_INLINE void CMU_Lock(void) { CMU->LOCK = ~CMU_LOCK_LOCKKEY_UNLOCK; } /***************************************************************************//** * @brief * Enable/disable oscillator. * * @note * This is a dummy function to solve backward compatibility issues. * * @param[in] osc * The oscillator to enable/disable. * * @param[in] enable * @li true - enable specified oscillator. * @li false - disable specified oscillator. * * @param[in] wait * Only used if @p enable is true. * @li true - wait for oscillator start-up time to timeout before returning. * @li false - do not wait for oscillator start-up time to timeout before * returning. ******************************************************************************/ __STATIC_INLINE void CMU_OscillatorEnable(CMU_Osc_TypeDef osc, bool enable, bool wait) { (void)osc; (void)enable; (void)wait; } /***************************************************************************//** * @brief * Unlock CMU register access so that writing to registers is possible. ******************************************************************************/ __STATIC_INLINE void CMU_Unlock(void) { CMU->LOCK = CMU_LOCK_LOCKKEY_UNLOCK; } /***************************************************************************//** * @brief * Lock WDOG register access in order to protect registers contents against * unintended modification. * * @note * If locking the WDOG registers, they must be unlocked prior to using any * emlib API functions modifying registers protected by the lock. ******************************************************************************/ __STATIC_INLINE void CMU_WdogLock(void) { CMU->WDOGLOCK = ~CMU_WDOGLOCK_LOCKKEY_UNLOCK; } /***************************************************************************//** * @brief * Unlock WDOG register access so that writing to registers is possible. ******************************************************************************/ __STATIC_INLINE void CMU_WdogUnlock(void) { CMU->WDOGLOCK = CMU_WDOGLOCK_LOCKKEY_UNLOCK; } #else // defined(_SILICON_LABS_32B_SERIES_2) /** @cond DO_NOT_INCLUDE_WITH_DOXYGEN */ /* Select register IDs for internal use. */ #define CMU_NOSEL_REG 0 #define CMU_HFCLKSEL_REG 1 #define CMU_LFACLKSEL_REG 2 #define CMU_LFBCLKSEL_REG 3 #define CMU_LFCCLKSEL_REG 4 #define CMU_LFECLKSEL_REG 5 #define CMU_DBGCLKSEL_REG 6 #define CMU_USBCCLKSEL_REG 7 #define CMU_ADC0ASYNCSEL_REG 8 #define CMU_ADC1ASYNCSEL_REG 9 #define CMU_SDIOREFSEL_REG 10 #define CMU_QSPI0REFSEL_REG 11 #define CMU_USBRCLKSEL_REG 12 #define CMU_PDMREFSEL_REG 13 #define CMU_SEL_REG_POS 0U #define CMU_SEL_REG_MASK 0xfU /* Divisor/prescaler register IDs for internal use. */ #define CMU_NODIV_REG 0 #define CMU_NOPRESC_REG 0 #define CMU_HFPRESC_REG 1 #define CMU_HFCLKDIV_REG 1 #define CMU_HFEXPPRESC_REG 2 #define CMU_HFCLKLEPRESC_REG 3 #define CMU_HFPERPRESC_REG 4 #define CMU_HFPERCLKDIV_REG 4 #define CMU_HFPERPRESCB_REG 5 #define CMU_HFPERPRESCC_REG 6 #define CMU_HFCOREPRESC_REG 7 #define CMU_HFCORECLKDIV_REG 7 #define CMU_LFAPRESC0_REG 8 #define CMU_LFBPRESC0_REG 9 #define CMU_LFEPRESC0_REG 10 #define CMU_ADCASYNCDIV_REG 11 #define CMU_HFBUSPRESC_REG 12 #define CMU_HFCORECLKLEDIV_REG 13 #define CMU_PRESC_REG_POS 4U #define CMU_DIV_REG_POS CMU_PRESC_REG_POS #define CMU_PRESC_REG_MASK 0xfU #define CMU_DIV_REG_MASK CMU_PRESC_REG_MASK /* Enable register IDs for internal use. */ #define CMU_NO_EN_REG 0 #define CMU_CTRL_EN_REG 1 #define CMU_HFPERCLKDIV_EN_REG 1 #define CMU_HFPERCLKEN0_EN_REG 2 #define CMU_HFCORECLKEN0_EN_REG 3 #define CMU_PDMREF_EN_REG 4 #define CMU_HFBUSCLKEN0_EN_REG 5 #define CMU_LFACLKEN0_EN_REG 6 #define CMU_LFBCLKEN0_EN_REG 7 #define CMU_LFCCLKEN0_EN_REG 8 #define CMU_LFECLKEN0_EN_REG 9 #define CMU_PCNT_EN_REG 10 #define CMU_SDIOREF_EN_REG 11 #define CMU_QSPI0REF_EN_REG 12 #define CMU_QSPI1REF_EN_REG 13 #define CMU_HFPERCLKEN1_EN_REG 14 #define CMU_USBRCLK_EN_REG 15 #define CMU_EN_REG_POS 8U #define CMU_EN_REG_MASK 0xfU /* Enable register bit positions, for internal use. */ #define CMU_EN_BIT_POS 12U #define CMU_EN_BIT_MASK 0x1fU /* Clock branch bitfield positions, for internal use. */ #define CMU_HF_CLK_BRANCH 0 #define CMU_HFCORE_CLK_BRANCH 1 #define CMU_HFPER_CLK_BRANCH 2 #define CMU_HFPERB_CLK_BRANCH 3 #define CMU_HFPERC_CLK_BRANCH 4 #define CMU_HFBUS_CLK_BRANCH 5 #define CMU_HFEXP_CLK_BRANCH 6 #define CMU_DBG_CLK_BRANCH 7 #define CMU_AUX_CLK_BRANCH 8 #define CMU_RTC_CLK_BRANCH 9 #define CMU_RTCC_CLK_BRANCH 10 #define CMU_LETIMER0_CLK_BRANCH 11 #define CMU_LETIMER1_CLK_BRANCH 12 #define CMU_LEUART0_CLK_BRANCH 13 #define CMU_LEUART1_CLK_BRANCH 14 #define CMU_LFA_CLK_BRANCH 15 #define CMU_LFB_CLK_BRANCH 16 #define CMU_LFC_CLK_BRANCH 17 #define CMU_LFE_CLK_BRANCH 18 #define CMU_USBC_CLK_BRANCH 19 #define CMU_USBLE_CLK_BRANCH 20 #define CMU_LCDPRE_CLK_BRANCH 21 #define CMU_LCD_CLK_BRANCH 22 #define CMU_LESENSE_CLK_BRANCH 23 #define CMU_CSEN_LF_CLK_BRANCH 24 #define CMU_ADC0ASYNC_CLK_BRANCH 25 #define CMU_ADC1ASYNC_CLK_BRANCH 26 #define CMU_SDIOREF_CLK_BRANCH 27 #define CMU_QSPI0REF_CLK_BRANCH 28 #define CMU_USBR_CLK_BRANCH 29 #define CMU_PDMREF_CLK_BRANCH 30 #define CMU_HFLE_CLK_BRANCH 31 #define CMU_CLK_BRANCH_POS 17U #define CMU_CLK_BRANCH_MASK 0x1fU #if defined(_EMU_CMD_EM01VSCALE0_MASK) /* Maximum clock frequency for VSCALE voltages. */ #define CMU_VSCALEEM01_LOWPOWER_VOLTAGE_CLOCK_MAX 20000000UL #endif /* Macros for VSCALE for use with the CMU_UpdateWaitStates(freq, vscale) API. * NOTE: The values must align with the values in EMU_VScaleEM01_TypeDef for * Series1 parts (highest VSCALE voltage = lowest numerical value). */ #define VSCALE_EM01_LOW_POWER 2 #define VSCALE_EM01_HIGH_PERFORMANCE 0 #if defined(USB_PRESENT) && defined(_CMU_HFCORECLKEN0_USBC_MASK) #define USBC_CLOCK_PRESENT #endif #if defined(USB_PRESENT) && defined(_CMU_USBCTRL_MASK) #define USBR_CLOCK_PRESENT #endif #if defined(CMU_OSCENCMD_PLFRCOEN) #define PLFRCO_PRESENT #endif /** @endcond */ /******************************************************************************* ******************************** ENUMS ************************************ ******************************************************************************/ /** Clock divisors. These values are valid for prescalers. */ #define cmuClkDiv_1 1 /**< Divide clock by 1. */ #define cmuClkDiv_2 2 /**< Divide clock by 2. */ #define cmuClkDiv_4 4 /**< Divide clock by 4. */ #define cmuClkDiv_8 8 /**< Divide clock by 8. */ #define cmuClkDiv_16 16 /**< Divide clock by 16. */ #define cmuClkDiv_32 32 /**< Divide clock by 32. */ #define cmuClkDiv_64 64 /**< Divide clock by 64. */ #define cmuClkDiv_128 128 /**< Divide clock by 128. */ #define cmuClkDiv_256 256 /**< Divide clock by 256. */ #define cmuClkDiv_512 512 /**< Divide clock by 512. */ #define cmuClkDiv_1024 1024 /**< Divide clock by 1024. */ #define cmuClkDiv_2048 2048 /**< Divide clock by 2048. */ #define cmuClkDiv_4096 4096 /**< Divide clock by 4096. */ #define cmuClkDiv_8192 8192 /**< Divide clock by 8192. */ #define cmuClkDiv_16384 16384 /**< Divide clock by 16384. */ #define cmuClkDiv_32768 32768 /**< Divide clock by 32768. */ /** Clock divider configuration */ typedef uint32_t CMU_ClkDiv_TypeDef; #if defined(_SILICON_LABS_32B_SERIES_1) /** Clockprescaler configuration */ typedef uint32_t CMU_ClkPresc_TypeDef; #endif #if defined(_CMU_HFRCOCTRL_BAND_MASK) /** High-frequency system RCO bands */ typedef enum { cmuHFRCOBand_1MHz = _CMU_HFRCOCTRL_BAND_1MHZ, /**< 1 MHz HFRCO band */ cmuHFRCOBand_7MHz = _CMU_HFRCOCTRL_BAND_7MHZ, /**< 7 MHz HFRCO band */ cmuHFRCOBand_11MHz = _CMU_HFRCOCTRL_BAND_11MHZ, /**< 11 MHz HFRCO band */ cmuHFRCOBand_14MHz = _CMU_HFRCOCTRL_BAND_14MHZ, /**< 14 MHz HFRCO band */ cmuHFRCOBand_21MHz = _CMU_HFRCOCTRL_BAND_21MHZ, /**< 21 MHz HFRCO band */ #if defined(CMU_HFRCOCTRL_BAND_28MHZ) cmuHFRCOBand_28MHz = _CMU_HFRCOCTRL_BAND_28MHZ, /**< 28 MHz HFRCO band */ #endif } CMU_HFRCOBand_TypeDef; #endif /* _CMU_HFRCOCTRL_BAND_MASK */ #if defined(_CMU_AUXHFRCOCTRL_BAND_MASK) /** AUX high-frequency RCO bands */ typedef enum { cmuAUXHFRCOBand_1MHz = _CMU_AUXHFRCOCTRL_BAND_1MHZ, /**< 1 MHz RC band */ cmuAUXHFRCOBand_7MHz = _CMU_AUXHFRCOCTRL_BAND_7MHZ, /**< 7 MHz RC band */ cmuAUXHFRCOBand_11MHz = _CMU_AUXHFRCOCTRL_BAND_11MHZ, /**< 11 MHz RC band */ cmuAUXHFRCOBand_14MHz = _CMU_AUXHFRCOCTRL_BAND_14MHZ, /**< 14 MHz RC band */ cmuAUXHFRCOBand_21MHz = _CMU_AUXHFRCOCTRL_BAND_21MHZ, /**< 21 MHz RC band */ #if defined(CMU_AUXHFRCOCTRL_BAND_28MHZ) cmuAUXHFRCOBand_28MHz = _CMU_AUXHFRCOCTRL_BAND_28MHZ, /**< 28 MHz RC band */ #endif } CMU_AUXHFRCOBand_TypeDef; #endif #if defined(_CMU_USHFRCOCONF_BAND_MASK) /** Universal serial high-frequency RC bands */ typedef enum { /** 24 MHz RC band. */ cmuUSHFRCOBand_24MHz = _CMU_USHFRCOCONF_BAND_24MHZ, /** 48 MHz RC band. */ cmuUSHFRCOBand_48MHz = _CMU_USHFRCOCONF_BAND_48MHZ, } CMU_USHFRCOBand_TypeDef; #endif #if defined(_CMU_USHFRCOCTRL_FREQRANGE_MASK) /** High-USHFRCO bands */ typedef enum { cmuUSHFRCOFreq_16M0Hz = 16000000U, /**< 16 MHz RC band */ cmuUSHFRCOFreq_32M0Hz = 32000000U, /**< 32 MHz RC band */ cmuUSHFRCOFreq_48M0Hz = 48000000U, /**< 48 MHz RC band */ cmuUSHFRCOFreq_50M0Hz = 50000000U, /**< 50 MHz RC band */ cmuUSHFRCOFreq_UserDefined = 0, } CMU_USHFRCOFreq_TypeDef; #define CMU_USHFRCO_MIN cmuUSHFRCOFreq_16M0Hz #define CMU_USHFRCO_MAX cmuUSHFRCOFreq_50M0Hz #endif #if defined(_CMU_HFRCOCTRL_FREQRANGE_MASK) /** High-frequency system RCO bands */ typedef enum { cmuHFRCOFreq_1M0Hz = 1000000U, /**< 1 MHz RC band */ cmuHFRCOFreq_2M0Hz = 2000000U, /**< 2 MHz RC band */ cmuHFRCOFreq_4M0Hz = 4000000U, /**< 4 MHz RC band */ cmuHFRCOFreq_7M0Hz = 7000000U, /**< 7 MHz RC band */ cmuHFRCOFreq_13M0Hz = 13000000U, /**< 13 MHz RC band */ cmuHFRCOFreq_16M0Hz = 16000000U, /**< 16 MHz RC band */ cmuHFRCOFreq_19M0Hz = 19000000U, /**< 19 MHz RC band */ cmuHFRCOFreq_26M0Hz = 26000000U, /**< 26 MHz RC band */ cmuHFRCOFreq_32M0Hz = 32000000U, /**< 32 MHz RC band */ cmuHFRCOFreq_38M0Hz = 38000000U, /**< 38 MHz RC band */ #if defined(_DEVINFO_HFRCOCAL13_MASK) cmuHFRCOFreq_48M0Hz = 48000000U, /**< 48 MHz RC band */ #endif #if defined(_DEVINFO_HFRCOCAL14_MASK) cmuHFRCOFreq_56M0Hz = 56000000U, /**< 56 MHz RC band */ #endif #if defined(_DEVINFO_HFRCOCAL15_MASK) cmuHFRCOFreq_64M0Hz = 64000000U, /**< 64 MHz RC band */ #endif #if defined(_DEVINFO_HFRCOCAL16_MASK) cmuHFRCOFreq_72M0Hz = 72000000U, /**< 72 MHz RC band */ #endif cmuHFRCOFreq_UserDefined = 0, } CMU_HFRCOFreq_TypeDef; #define CMU_HFRCO_MIN cmuHFRCOFreq_1M0Hz #if defined(_DEVINFO_HFRCOCAL16_MASK) #define CMU_HFRCO_MAX cmuHFRCOFreq_72M0Hz #elif defined(_DEVINFO_HFRCOCAL15_MASK) #define CMU_HFRCO_MAX cmuHFRCOFreq_64M0Hz #elif defined(_DEVINFO_HFRCOCAL14_MASK) #define CMU_HFRCO_MAX cmuHFRCOFreq_56M0Hz #elif defined(_DEVINFO_HFRCOCAL13_MASK) #define CMU_HFRCO_MAX cmuHFRCOFreq_48M0Hz #else #define CMU_HFRCO_MAX cmuHFRCOFreq_38M0Hz #endif #endif #if defined(_CMU_AUXHFRCOCTRL_FREQRANGE_MASK) /** AUX high-frequency RCO bands */ typedef enum { cmuAUXHFRCOFreq_1M0Hz = 1000000U, /**< 1 MHz RC band */ cmuAUXHFRCOFreq_2M0Hz = 2000000U, /**< 2 MHz RC band */ cmuAUXHFRCOFreq_4M0Hz = 4000000U, /**< 4 MHz RC band */ cmuAUXHFRCOFreq_7M0Hz = 7000000U, /**< 7 MHz RC band */ cmuAUXHFRCOFreq_13M0Hz = 13000000U, /**< 13 MHz RC band */ cmuAUXHFRCOFreq_16M0Hz = 16000000U, /**< 16 MHz RC band */ cmuAUXHFRCOFreq_19M0Hz = 19000000U, /**< 19 MHz RC band */ cmuAUXHFRCOFreq_26M0Hz = 26000000U, /**< 26 MHz RC band */ cmuAUXHFRCOFreq_32M0Hz = 32000000U, /**< 32 MHz RC band */ cmuAUXHFRCOFreq_38M0Hz = 38000000U, /**< 38 MHz RC band */ #if defined(_DEVINFO_AUXHFRCOCAL13_MASK) cmuAUXHFRCOFreq_48M0Hz = 48000000U, /**< 48 MHz RC band */ #endif #if defined(_DEVINFO_AUXHFRCOCAL14_MASK) cmuAUXHFRCOFreq_50M0Hz = 50000000U, /**< 50 MHz RC band */ #endif cmuAUXHFRCOFreq_UserDefined = 0, } CMU_AUXHFRCOFreq_TypeDef; #define CMU_AUXHFRCO_MIN cmuAUXHFRCOFreq_1M0Hz #if defined(_DEVINFO_AUXHFRCOCAL14_MASK) #define CMU_AUXHFRCO_MAX cmuAUXHFRCOFreq_50M0Hz #elif defined(_DEVINFO_AUXHFRCOCAL13_MASK) #define CMU_AUXHFRCO_MAX cmuAUXHFRCOFreq_48M0Hz #else #define CMU_AUXHFRCO_MAX cmuAUXHFRCOFreq_38M0Hz #endif #endif /** Clock points in CMU. See CMU overview in the reference manual. */ typedef enum { /*******************/ /* HF clock branch */ /*******************/ /** High-frequency clock */ #if defined(_CMU_CTRL_HFCLKDIV_MASK) \ || defined(_CMU_HFPRESC_MASK) cmuClock_HF = (CMU_HFCLKDIV_REG << CMU_DIV_REG_POS) | (CMU_HFCLKSEL_REG << CMU_SEL_REG_POS) | (CMU_NO_EN_REG << CMU_EN_REG_POS) | (0 << CMU_EN_BIT_POS) | (CMU_HF_CLK_BRANCH << CMU_CLK_BRANCH_POS), #else cmuClock_HF = (CMU_NODIV_REG << CMU_DIV_REG_POS) | (CMU_HFCLKSEL_REG << CMU_SEL_REG_POS) | (CMU_NO_EN_REG << CMU_EN_REG_POS) | (0 << CMU_EN_BIT_POS) | (CMU_HF_CLK_BRANCH << CMU_CLK_BRANCH_POS), #endif /** Debug clock */ cmuClock_DBG = (CMU_NODIV_REG << CMU_DIV_REG_POS) | (CMU_DBGCLKSEL_REG << CMU_SEL_REG_POS) | (CMU_NO_EN_REG << CMU_EN_REG_POS) | (0 << CMU_EN_BIT_POS) | (CMU_DBG_CLK_BRANCH << CMU_CLK_BRANCH_POS), /** AUX clock */ cmuClock_AUX = (CMU_NODIV_REG << CMU_DIV_REG_POS) | (CMU_NOSEL_REG << CMU_SEL_REG_POS) | (CMU_NO_EN_REG << CMU_EN_REG_POS) | (0 << CMU_EN_BIT_POS) | (CMU_AUX_CLK_BRANCH << CMU_CLK_BRANCH_POS), #if defined(_CMU_HFEXPPRESC_MASK) /**********************/ /* HF export sub-branch */ /**********************/ /** Export clock */ cmuClock_EXPORT = (CMU_HFEXPPRESC_REG << CMU_PRESC_REG_POS) | (CMU_NOSEL_REG << CMU_SEL_REG_POS) | (CMU_NO_EN_REG << CMU_EN_REG_POS) | (0 << CMU_EN_BIT_POS) | (CMU_HFEXP_CLK_BRANCH << CMU_CLK_BRANCH_POS), #endif #if defined(_CMU_HFBUSCLKEN0_MASK) /**********************************/ /* HF bus clock sub-branch */ /**********************************/ /** High-frequency bus clock */ #if defined(_CMU_HFBUSPRESC_MASK) cmuClock_BUS = (CMU_HFBUSPRESC_REG << CMU_PRESC_REG_POS) | (CMU_NOSEL_REG << CMU_SEL_REG_POS) | (CMU_NO_EN_REG << CMU_EN_REG_POS) | (0 << CMU_EN_BIT_POS) | (CMU_HFBUS_CLK_BRANCH << CMU_CLK_BRANCH_POS), #else cmuClock_BUS = (CMU_NOPRESC_REG << CMU_PRESC_REG_POS) | (CMU_NOSEL_REG << CMU_SEL_REG_POS) | (CMU_NO_EN_REG << CMU_EN_REG_POS) | (0 << CMU_EN_BIT_POS) | (CMU_HFBUS_CLK_BRANCH << CMU_CLK_BRANCH_POS), #endif #if defined(CMU_HFBUSCLKEN0_CRYPTO) /** Cryptography accelerator clock */ cmuClock_CRYPTO = (CMU_NOPRESC_REG << CMU_PRESC_REG_POS) | (CMU_NOSEL_REG << CMU_SEL_REG_POS) | (CMU_HFBUSCLKEN0_EN_REG << CMU_EN_REG_POS) | (_CMU_HFBUSCLKEN0_CRYPTO_SHIFT << CMU_EN_BIT_POS) | (CMU_HFBUS_CLK_BRANCH << CMU_CLK_BRANCH_POS), #endif #if defined(CMU_HFBUSCLKEN0_CRYPTO0) /** Cryptography accelerator 0 clock */ cmuClock_CRYPTO0 = (CMU_NOPRESC_REG << CMU_PRESC_REG_POS) | (CMU_NOSEL_REG << CMU_SEL_REG_POS) | (CMU_HFBUSCLKEN0_EN_REG << CMU_EN_REG_POS) | (_CMU_HFBUSCLKEN0_CRYPTO0_SHIFT << CMU_EN_BIT_POS) | (CMU_HFBUS_CLK_BRANCH << CMU_CLK_BRANCH_POS), #endif #if defined(CMU_HFBUSCLKEN0_CRYPTO1) /** Cryptography accelerator 1 clock */ cmuClock_CRYPTO1 = (CMU_NOPRESC_REG << CMU_PRESC_REG_POS) | (CMU_NOSEL_REG << CMU_SEL_REG_POS) | (CMU_HFBUSCLKEN0_EN_REG << CMU_EN_REG_POS) | (_CMU_HFBUSCLKEN0_CRYPTO1_SHIFT << CMU_EN_BIT_POS) | (CMU_HFBUS_CLK_BRANCH << CMU_CLK_BRANCH_POS), #endif #if defined(CMU_HFBUSCLKEN0_LDMA) /** Direct-memory access controller clock */ cmuClock_LDMA = (CMU_NOPRESC_REG << CMU_PRESC_REG_POS) | (CMU_NOSEL_REG << CMU_SEL_REG_POS) | (CMU_HFBUSCLKEN0_EN_REG << CMU_EN_REG_POS) | (_CMU_HFBUSCLKEN0_LDMA_SHIFT << CMU_EN_BIT_POS) | (CMU_HF_CLK_BRANCH << CMU_CLK_BRANCH_POS), #endif #if defined(CMU_HFBUSCLKEN0_QSPI0) /** Quad SPI clock */ cmuClock_QSPI0 = (CMU_NOPRESC_REG << CMU_PRESC_REG_POS) | (CMU_NOSEL_REG << CMU_SEL_REG_POS) | (CMU_HFBUSCLKEN0_EN_REG << CMU_EN_REG_POS) | (_CMU_HFBUSCLKEN0_QSPI0_SHIFT << CMU_EN_BIT_POS) | (CMU_HFBUS_CLK_BRANCH << CMU_CLK_BRANCH_POS), #endif #if defined(CMU_HFBUSCLKEN0_GPCRC) /** General-purpose cyclic redundancy checksum clock */ cmuClock_GPCRC = (CMU_NOPRESC_REG << CMU_PRESC_REG_POS) | (CMU_NOSEL_REG << CMU_SEL_REG_POS) | (CMU_HFBUSCLKEN0_EN_REG << CMU_EN_REG_POS) | (_CMU_HFBUSCLKEN0_GPCRC_SHIFT << CMU_EN_BIT_POS) | (CMU_HFBUS_CLK_BRANCH << CMU_CLK_BRANCH_POS), #endif #if defined(CMU_HFBUSCLKEN0_GPIO) /** General-purpose input/output clock */ cmuClock_GPIO = (CMU_NOPRESC_REG << CMU_PRESC_REG_POS) | (CMU_NOSEL_REG << CMU_SEL_REG_POS) | (CMU_HFBUSCLKEN0_EN_REG << CMU_EN_REG_POS) | (_CMU_HFBUSCLKEN0_GPIO_SHIFT << CMU_EN_BIT_POS) | (CMU_HFBUS_CLK_BRANCH << CMU_CLK_BRANCH_POS), #endif /** Low-energy clock divided down from HFCLK */ cmuClock_HFLE = (CMU_HFCLKLEPRESC_REG << CMU_PRESC_REG_POS) | (CMU_NOSEL_REG << CMU_SEL_REG_POS) | (CMU_HFBUSCLKEN0_EN_REG << CMU_EN_REG_POS) | (_CMU_HFBUSCLKEN0_LE_SHIFT << CMU_EN_BIT_POS) | (CMU_HFLE_CLK_BRANCH << CMU_CLK_BRANCH_POS), #if defined(CMU_HFBUSCLKEN0_PRS) /** Peripheral reflex system clock */ cmuClock_PRS = (CMU_NOPRESC_REG << CMU_PRESC_REG_POS) | (CMU_NOSEL_REG << CMU_SEL_REG_POS) | (CMU_HFBUSCLKEN0_EN_REG << CMU_EN_REG_POS) | (_CMU_HFBUSCLKEN0_PRS_SHIFT << CMU_EN_BIT_POS) | (CMU_HF_CLK_BRANCH << CMU_CLK_BRANCH_POS), #endif #endif /**********************************/ /* HF peripheral clock sub-branch */ /**********************************/ /** High-frequency peripheral clock */ #if defined(_CMU_HFPRESC_MASK) cmuClock_HFPER = (CMU_HFPERPRESC_REG << CMU_PRESC_REG_POS) | (CMU_NOSEL_REG << CMU_SEL_REG_POS) | (CMU_CTRL_EN_REG << CMU_EN_REG_POS) | (_CMU_CTRL_HFPERCLKEN_SHIFT << CMU_EN_BIT_POS) | (CMU_HFPER_CLK_BRANCH << CMU_CLK_BRANCH_POS), #else cmuClock_HFPER = (CMU_HFPERCLKDIV_REG << CMU_DIV_REG_POS) | (CMU_NOSEL_REG << CMU_SEL_REG_POS) | (CMU_HFPERCLKDIV_EN_REG << CMU_EN_REG_POS) | (_CMU_HFPERCLKDIV_HFPERCLKEN_SHIFT << CMU_EN_BIT_POS) | (CMU_HFPER_CLK_BRANCH << CMU_CLK_BRANCH_POS), #endif #if defined(_CMU_HFPERPRESCB_MASK) /** Branch B figh-frequency peripheral clock */ cmuClock_HFPERB = (CMU_HFPERPRESCB_REG << CMU_PRESC_REG_POS) | (CMU_NOSEL_REG << CMU_SEL_REG_POS) | (CMU_CTRL_EN_REG << CMU_EN_REG_POS) | (_CMU_CTRL_HFPERCLKEN_SHIFT << CMU_EN_BIT_POS) | (CMU_HFPERB_CLK_BRANCH << CMU_CLK_BRANCH_POS), #endif #if defined(_CMU_HFPERPRESCC_MASK) /** Branch C figh-frequency peripheral clock */ cmuClock_HFPERC = (CMU_HFPERPRESCC_REG << CMU_PRESC_REG_POS) | (CMU_NOSEL_REG << CMU_SEL_REG_POS) | (CMU_CTRL_EN_REG << CMU_EN_REG_POS) | (_CMU_CTRL_HFPERCLKEN_SHIFT << CMU_EN_BIT_POS) | (CMU_HFPERC_CLK_BRANCH << CMU_CLK_BRANCH_POS), #endif #if defined(CMU_HFPERCLKEN0_PDM) /** PDM clock */ cmuClock_PDM = (CMU_NOPRESC_REG << CMU_PRESC_REG_POS) | (CMU_NOSEL_REG << CMU_SEL_REG_POS) | (CMU_HFPERCLKEN0_EN_REG << CMU_EN_REG_POS) | (_CMU_HFPERCLKEN0_PDM_SHIFT << CMU_EN_BIT_POS) | (CMU_HFPER_CLK_BRANCH << CMU_CLK_BRANCH_POS), #endif #if defined(CMU_HFPERCLKEN0_USART0) /** Universal sync/async receiver/transmitter 0 clock */ cmuClock_USART0 = (CMU_NODIV_REG << CMU_DIV_REG_POS) | (CMU_NOSEL_REG << CMU_SEL_REG_POS) | (CMU_HFPERCLKEN0_EN_REG << CMU_EN_REG_POS) | (_CMU_HFPERCLKEN0_USART0_SHIFT << CMU_EN_BIT_POS) | (CMU_HFPER_CLK_BRANCH << CMU_CLK_BRANCH_POS), #endif #if defined(CMU_HFPERCLKEN0_USARTRF0) /** Universal sync/async receiver/transmitter 0 clock */ cmuClock_USARTRF0 = (CMU_NODIV_REG << CMU_DIV_REG_POS) | (CMU_NOSEL_REG << CMU_SEL_REG_POS) | (CMU_HFPERCLKEN0_EN_REG << CMU_EN_REG_POS) | (_CMU_HFPERCLKEN0_USARTRF0_SHIFT << CMU_EN_BIT_POS) | (CMU_HFPER_CLK_BRANCH << CMU_CLK_BRANCH_POS), #endif #if defined(CMU_HFPERCLKEN0_USARTRF1) /** Universal sync/async receiver/transmitter 0 clock */ cmuClock_USARTRF1 = (CMU_NODIV_REG << CMU_DIV_REG_POS) | (CMU_NOSEL_REG << CMU_SEL_REG_POS) | (CMU_HFPERCLKEN0_EN_REG << CMU_EN_REG_POS) | (_CMU_HFPERCLKEN0_USARTRF1_SHIFT << CMU_EN_BIT_POS) | (CMU_HFPER_CLK_BRANCH << CMU_CLK_BRANCH_POS), #endif #if defined(CMU_HFPERCLKEN0_USART1) /** Universal sync/async receiver/transmitter 1 clock */ cmuClock_USART1 = (CMU_NODIV_REG << CMU_DIV_REG_POS) | (CMU_NOSEL_REG << CMU_SEL_REG_POS) | (CMU_HFPERCLKEN0_EN_REG << CMU_EN_REG_POS) | (_CMU_HFPERCLKEN0_USART1_SHIFT << CMU_EN_BIT_POS) | (CMU_HFPER_CLK_BRANCH << CMU_CLK_BRANCH_POS), #endif #if defined(CMU_HFPERCLKEN0_USART2) /** Universal sync/async receiver/transmitter 2 clock */ cmuClock_USART2 = (CMU_NODIV_REG << CMU_DIV_REG_POS) | (CMU_NOSEL_REG << CMU_SEL_REG_POS) | (CMU_HFPERCLKEN0_EN_REG << CMU_EN_REG_POS) | (_CMU_HFPERCLKEN0_USART2_SHIFT << CMU_EN_BIT_POS) #if defined(_CMU_HFPERPRESCB_MASK) | (CMU_HFPERB_CLK_BRANCH << CMU_CLK_BRANCH_POS), #else | (CMU_HFPER_CLK_BRANCH << CMU_CLK_BRANCH_POS), #endif #endif #if defined(CMU_HFPERCLKEN0_USART3) /** Universal sync/async receiver/transmitter 3 clock */ cmuClock_USART3 = (CMU_NOPRESC_REG << CMU_PRESC_REG_POS) | (CMU_NOSEL_REG << CMU_SEL_REG_POS) | (CMU_HFPERCLKEN0_EN_REG << CMU_EN_REG_POS) | (_CMU_HFPERCLKEN0_USART3_SHIFT << CMU_EN_BIT_POS) | (CMU_HFPER_CLK_BRANCH << CMU_CLK_BRANCH_POS), #endif #if defined(CMU_HFPERCLKEN0_USART4) /** Universal sync/async receiver/transmitter 4 clock */ cmuClock_USART4 = (CMU_NOPRESC_REG << CMU_PRESC_REG_POS) | (CMU_NOSEL_REG << CMU_SEL_REG_POS) | (CMU_HFPERCLKEN0_EN_REG << CMU_EN_REG_POS) | (_CMU_HFPERCLKEN0_USART4_SHIFT << CMU_EN_BIT_POS) | (CMU_HFPER_CLK_BRANCH << CMU_CLK_BRANCH_POS), #endif #if defined(CMU_HFPERCLKEN0_USART5) /** Universal sync/async receiver/transmitter 5 clock */ cmuClock_USART5 = (CMU_NOPRESC_REG << CMU_PRESC_REG_POS) | (CMU_NOSEL_REG << CMU_SEL_REG_POS) | (CMU_HFPERCLKEN0_EN_REG << CMU_EN_REG_POS) | (_CMU_HFPERCLKEN0_USART5_SHIFT << CMU_EN_BIT_POS) | (CMU_HFPER_CLK_BRANCH << CMU_CLK_BRANCH_POS), #endif #if defined(CMU_HFPERCLKEN0_UART0) /** Universal async receiver/transmitter 0 clock */ cmuClock_UART0 = (CMU_NODIV_REG << CMU_DIV_REG_POS) | (CMU_NOSEL_REG << CMU_SEL_REG_POS) | (CMU_HFPERCLKEN0_EN_REG << CMU_EN_REG_POS) | (_CMU_HFPERCLKEN0_UART0_SHIFT << CMU_EN_BIT_POS) | (CMU_HFPER_CLK_BRANCH << CMU_CLK_BRANCH_POS), #elif defined(_CMU_HFPERCLKEN1_UART0_MASK) /** Universal async receiver/transmitter 0 clock */ cmuClock_UART0 = (CMU_NOPRESC_REG << CMU_PRESC_REG_POS) | (CMU_NOSEL_REG << CMU_SEL_REG_POS) | (CMU_HFPERCLKEN1_EN_REG << CMU_EN_REG_POS) | (_CMU_HFPERCLKEN1_UART0_SHIFT << CMU_EN_BIT_POS) | (CMU_HFPER_CLK_BRANCH << CMU_CLK_BRANCH_POS), #endif #if defined(CMU_HFPERCLKEN0_UART1) /** Universal async receiver/transmitter 1 clock */ cmuClock_UART1 = (CMU_NODIV_REG << CMU_DIV_REG_POS) | (CMU_NOSEL_REG << CMU_SEL_REG_POS) | (CMU_HFPERCLKEN0_EN_REG << CMU_EN_REG_POS) | (_CMU_HFPERCLKEN0_UART1_SHIFT << CMU_EN_BIT_POS) | (CMU_HFPER_CLK_BRANCH << CMU_CLK_BRANCH_POS), #elif defined(_CMU_HFPERCLKEN1_UART1_MASK) /** Universal async receiver/transmitter 1 clock */ cmuClock_UART1 = (CMU_NOPRESC_REG << CMU_PRESC_REG_POS) | (CMU_NOSEL_REG << CMU_SEL_REG_POS) | (CMU_HFPERCLKEN1_EN_REG << CMU_EN_REG_POS) | (_CMU_HFPERCLKEN1_UART1_SHIFT << CMU_EN_BIT_POS) | (CMU_HFPER_CLK_BRANCH << CMU_CLK_BRANCH_POS), #endif #if defined(CMU_HFPERCLKEN0_TIMER0) /** Timer 0 clock */ cmuClock_TIMER0 = (CMU_NODIV_REG << CMU_DIV_REG_POS) | (CMU_NOSEL_REG << CMU_SEL_REG_POS) | (CMU_HFPERCLKEN0_EN_REG << CMU_EN_REG_POS) | (_CMU_HFPERCLKEN0_TIMER0_SHIFT << CMU_EN_BIT_POS) #if defined(_CMU_HFPERPRESCB_MASK) | (CMU_HFPERB_CLK_BRANCH << CMU_CLK_BRANCH_POS), #else | (CMU_HFPER_CLK_BRANCH << CMU_CLK_BRANCH_POS), #endif #endif #if defined(CMU_HFPERCLKEN0_TIMER1) /** Timer 1 clock */ cmuClock_TIMER1 = (CMU_NODIV_REG << CMU_DIV_REG_POS) | (CMU_NOSEL_REG << CMU_SEL_REG_POS) | (CMU_HFPERCLKEN0_EN_REG << CMU_EN_REG_POS) | (_CMU_HFPERCLKEN0_TIMER1_SHIFT << CMU_EN_BIT_POS) | (CMU_HFPER_CLK_BRANCH << CMU_CLK_BRANCH_POS), #endif #if defined(CMU_HFPERCLKEN0_TIMER2) /** Timer 2 clock */ cmuClock_TIMER2 = (CMU_NODIV_REG << CMU_DIV_REG_POS) | (CMU_NOSEL_REG << CMU_SEL_REG_POS) | (CMU_HFPERCLKEN0_EN_REG << CMU_EN_REG_POS) | (_CMU_HFPERCLKEN0_TIMER2_SHIFT << CMU_EN_BIT_POS) | (CMU_HFPER_CLK_BRANCH << CMU_CLK_BRANCH_POS), #endif #if defined(CMU_HFPERCLKEN0_TIMER3) /** Timer 3 clock */ cmuClock_TIMER3 = (CMU_NODIV_REG << CMU_DIV_REG_POS) | (CMU_NOSEL_REG << CMU_SEL_REG_POS) | (CMU_HFPERCLKEN0_EN_REG << CMU_EN_REG_POS) | (_CMU_HFPERCLKEN0_TIMER3_SHIFT << CMU_EN_BIT_POS) | (CMU_HFPER_CLK_BRANCH << CMU_CLK_BRANCH_POS), #endif #if defined(CMU_HFPERCLKEN0_TIMER4) /** Timer 4 clock */ cmuClock_TIMER4 = (CMU_NODIV_REG << CMU_DIV_REG_POS) | (CMU_NOSEL_REG << CMU_SEL_REG_POS) | (CMU_HFPERCLKEN0_EN_REG << CMU_EN_REG_POS) | (_CMU_HFPERCLKEN0_TIMER4_SHIFT << CMU_EN_BIT_POS) | (CMU_HFPER_CLK_BRANCH << CMU_CLK_BRANCH_POS), #endif #if defined(CMU_HFPERCLKEN0_TIMER5) /** Timer 5 clock */ cmuClock_TIMER5 = (CMU_NODIV_REG << CMU_DIV_REG_POS) | (CMU_NOSEL_REG << CMU_SEL_REG_POS) | (CMU_HFPERCLKEN0_EN_REG << CMU_EN_REG_POS) | (_CMU_HFPERCLKEN0_TIMER5_SHIFT << CMU_EN_BIT_POS) | (CMU_HFPER_CLK_BRANCH << CMU_CLK_BRANCH_POS), #endif #if defined(CMU_HFPERCLKEN0_TIMER6) /** Timer 6 clock */ cmuClock_TIMER6 = (CMU_NODIV_REG << CMU_DIV_REG_POS) | (CMU_NOSEL_REG << CMU_SEL_REG_POS) | (CMU_HFPERCLKEN0_EN_REG << CMU_EN_REG_POS) | (_CMU_HFPERCLKEN0_TIMER6_SHIFT << CMU_EN_BIT_POS) | (CMU_HFPER_CLK_BRANCH << CMU_CLK_BRANCH_POS), #endif #if defined(CMU_HFPERCLKEN0_WTIMER0) /** Wide-timer 0 clock */ cmuClock_WTIMER0 = (CMU_NODIV_REG << CMU_DIV_REG_POS) | (CMU_NOSEL_REG << CMU_SEL_REG_POS) | (CMU_HFPERCLKEN0_EN_REG << CMU_EN_REG_POS) | (_CMU_HFPERCLKEN0_WTIMER0_SHIFT << CMU_EN_BIT_POS) | (CMU_HFPER_CLK_BRANCH << CMU_CLK_BRANCH_POS), #elif defined(CMU_HFPERCLKEN1_WTIMER0) /** Wide-timer 0 clock */ cmuClock_WTIMER0 = (CMU_NODIV_REG << CMU_DIV_REG_POS) | (CMU_NOSEL_REG << CMU_SEL_REG_POS) | (CMU_HFPERCLKEN1_EN_REG << CMU_EN_REG_POS) | (_CMU_HFPERCLKEN1_WTIMER0_SHIFT << CMU_EN_BIT_POS) | (CMU_HFPER_CLK_BRANCH << CMU_CLK_BRANCH_POS), #endif #if defined(CMU_HFPERCLKEN0_WTIMER1) /** Wide-timer 1 clock */ cmuClock_WTIMER1 = (CMU_NODIV_REG << CMU_DIV_REG_POS) | (CMU_NOSEL_REG << CMU_SEL_REG_POS) | (CMU_HFPERCLKEN0_EN_REG << CMU_EN_REG_POS) | (_CMU_HFPERCLKEN0_WTIMER1_SHIFT << CMU_EN_BIT_POS) | (CMU_HFPER_CLK_BRANCH << CMU_CLK_BRANCH_POS), #elif defined(CMU_HFPERCLKEN1_WTIMER1) /** Wide-timer 1 clock */ cmuClock_WTIMER1 = (CMU_NODIV_REG << CMU_DIV_REG_POS) | (CMU_NOSEL_REG << CMU_SEL_REG_POS) | (CMU_HFPERCLKEN1_EN_REG << CMU_EN_REG_POS) | (_CMU_HFPERCLKEN1_WTIMER1_SHIFT << CMU_EN_BIT_POS) | (CMU_HFPER_CLK_BRANCH << CMU_CLK_BRANCH_POS), #endif #if defined(CMU_HFPERCLKEN1_WTIMER2) /** Wide-timer 2 clock */ cmuClock_WTIMER2 = (CMU_NODIV_REG << CMU_DIV_REG_POS) | (CMU_NOSEL_REG << CMU_SEL_REG_POS) | (CMU_HFPERCLKEN1_EN_REG << CMU_EN_REG_POS) | (_CMU_HFPERCLKEN1_WTIMER2_SHIFT << CMU_EN_BIT_POS) | (CMU_HFPER_CLK_BRANCH << CMU_CLK_BRANCH_POS), #endif #if defined(CMU_HFPERCLKEN1_WTIMER3) /** Wide-timer 3 clock */ cmuClock_WTIMER3 = (CMU_NODIV_REG << CMU_DIV_REG_POS) | (CMU_NOSEL_REG << CMU_SEL_REG_POS) | (CMU_HFPERCLKEN1_EN_REG << CMU_EN_REG_POS) | (_CMU_HFPERCLKEN1_WTIMER3_SHIFT << CMU_EN_BIT_POS) | (CMU_HFPER_CLK_BRANCH << CMU_CLK_BRANCH_POS), #endif #if defined(CMU_HFPERCLKEN0_CRYOTIMER) /** CRYOtimer clock */ cmuClock_CRYOTIMER = (CMU_NOPRESC_REG << CMU_PRESC_REG_POS) | (CMU_NOSEL_REG << CMU_SEL_REG_POS) | (CMU_HFPERCLKEN0_EN_REG << CMU_EN_REG_POS) | (_CMU_HFPERCLKEN0_CRYOTIMER_SHIFT << CMU_EN_BIT_POS) #if defined(_CMU_HFPERPRESCC_MASK) | (CMU_HFPERC_CLK_BRANCH << CMU_CLK_BRANCH_POS), #else | (CMU_HFPER_CLK_BRANCH << CMU_CLK_BRANCH_POS), #endif #endif #if defined(CMU_HFPERCLKEN0_ACMP0) /** Analog comparator 0 clock */ cmuClock_ACMP0 = (CMU_NODIV_REG << CMU_DIV_REG_POS) | (CMU_NOSEL_REG << CMU_SEL_REG_POS) | (CMU_HFPERCLKEN0_EN_REG << CMU_EN_REG_POS) | (_CMU_HFPERCLKEN0_ACMP0_SHIFT << CMU_EN_BIT_POS) #if defined(_CMU_HFPERPRESCC_MASK) | (CMU_HFPERC_CLK_BRANCH << CMU_CLK_BRANCH_POS), #else | (CMU_HFPER_CLK_BRANCH << CMU_CLK_BRANCH_POS), #endif #endif #if defined(CMU_HFPERCLKEN0_ACMP1) /** Analog comparator 1 clock */ cmuClock_ACMP1 = (CMU_NODIV_REG << CMU_DIV_REG_POS) | (CMU_NOSEL_REG << CMU_SEL_REG_POS) | (CMU_HFPERCLKEN0_EN_REG << CMU_EN_REG_POS) | (_CMU_HFPERCLKEN0_ACMP1_SHIFT << CMU_EN_BIT_POS) #if defined(_CMU_HFPERPRESCC_MASK) | (CMU_HFPERC_CLK_BRANCH << CMU_CLK_BRANCH_POS), #else | (CMU_HFPER_CLK_BRANCH << CMU_CLK_BRANCH_POS), #endif #endif #if defined(CMU_HFPERCLKEN0_ACMP2) /** Analog comparator 2 clock */ cmuClock_ACMP2 = (CMU_NODIV_REG << CMU_DIV_REG_POS) | (CMU_NOSEL_REG << CMU_SEL_REG_POS) | (CMU_HFPERCLKEN0_EN_REG << CMU_EN_REG_POS) | (_CMU_HFPERCLKEN0_ACMP2_SHIFT << CMU_EN_BIT_POS) | (CMU_HFPERC_CLK_BRANCH << CMU_CLK_BRANCH_POS), #endif #if defined(CMU_HFPERCLKEN0_ACMP3) /** Analog comparator 3 clock */ cmuClock_ACMP3 = (CMU_NODIV_REG << CMU_DIV_REG_POS) | (CMU_NOSEL_REG << CMU_SEL_REG_POS) | (CMU_HFPERCLKEN0_EN_REG << CMU_EN_REG_POS) | (_CMU_HFPERCLKEN0_ACMP3_SHIFT << CMU_EN_BIT_POS) | (CMU_HFPERC_CLK_BRANCH << CMU_CLK_BRANCH_POS), #endif #if defined(CMU_HFPERCLKEN0_PRS) /** Peripheral-reflex system clock */ cmuClock_PRS = (CMU_NODIV_REG << CMU_DIV_REG_POS) | (CMU_NOSEL_REG << CMU_SEL_REG_POS) | (CMU_HFPERCLKEN0_EN_REG << CMU_EN_REG_POS) | (_CMU_HFPERCLKEN0_PRS_SHIFT << CMU_EN_BIT_POS) | (CMU_HFPER_CLK_BRANCH << CMU_CLK_BRANCH_POS), #endif #if defined(CMU_HFPERCLKEN0_DAC0) /** Digital-to-analog converter 0 clock */ cmuClock_DAC0 = (CMU_NODIV_REG << CMU_DIV_REG_POS) | (CMU_NOSEL_REG << CMU_SEL_REG_POS) | (CMU_HFPERCLKEN0_EN_REG << CMU_EN_REG_POS) | (_CMU_HFPERCLKEN0_DAC0_SHIFT << CMU_EN_BIT_POS) | (CMU_HFPER_CLK_BRANCH << CMU_CLK_BRANCH_POS), #endif #if defined(CMU_HFPERCLKEN0_VDAC0) /** Voltage digital-to-analog converter 0 clock */ cmuClock_VDAC0 = (CMU_NODIV_REG << CMU_DIV_REG_POS) | (CMU_NOSEL_REG << CMU_SEL_REG_POS) | (CMU_HFPERCLKEN0_EN_REG << CMU_EN_REG_POS) | (_CMU_HFPERCLKEN0_VDAC0_SHIFT << CMU_EN_BIT_POS) | (CMU_HFPER_CLK_BRANCH << CMU_CLK_BRANCH_POS), #elif defined(CMU_HFPERCLKEN1_VDAC0) /** Voltage digital-to-analog converter 0 clock */ cmuClock_VDAC0 = (CMU_NODIV_REG << CMU_DIV_REG_POS) | (CMU_NOSEL_REG << CMU_SEL_REG_POS) | (CMU_HFPERCLKEN1_EN_REG << CMU_EN_REG_POS) | (_CMU_HFPERCLKEN1_VDAC0_SHIFT << CMU_EN_BIT_POS) #if defined(_CMU_HFPERPRESCC_MASK) | (CMU_HFPERC_CLK_BRANCH << CMU_CLK_BRANCH_POS), #else | (CMU_HFPER_CLK_BRANCH << CMU_CLK_BRANCH_POS), #endif #endif #if defined(CMU_HFPERCLKEN0_IDAC0) /** Current digital-to-analog converter 0 clock */ cmuClock_IDAC0 = (CMU_NODIV_REG << CMU_DIV_REG_POS) | (CMU_NOSEL_REG << CMU_SEL_REG_POS) | (CMU_HFPERCLKEN0_EN_REG << CMU_EN_REG_POS) | (_CMU_HFPERCLKEN0_IDAC0_SHIFT << CMU_EN_BIT_POS) #if defined(_CMU_HFPERPRESCC_MASK) | (CMU_HFPERC_CLK_BRANCH << CMU_CLK_BRANCH_POS), #else | (CMU_HFPER_CLK_BRANCH << CMU_CLK_BRANCH_POS), #endif #endif #if defined(CMU_HFPERCLKEN0_GPIO) /** General-purpose input/output clock */ cmuClock_GPIO = (CMU_NODIV_REG << CMU_DIV_REG_POS) | (CMU_NOSEL_REG << CMU_SEL_REG_POS) | (CMU_HFPERCLKEN0_EN_REG << CMU_EN_REG_POS) | (_CMU_HFPERCLKEN0_GPIO_SHIFT << CMU_EN_BIT_POS) | (CMU_HFPER_CLK_BRANCH << CMU_CLK_BRANCH_POS), #endif #if defined(CMU_HFPERCLKEN0_VCMP) /** Voltage comparator clock */ cmuClock_VCMP = (CMU_NODIV_REG << CMU_DIV_REG_POS) | (CMU_NOSEL_REG << CMU_SEL_REG_POS) | (CMU_HFPERCLKEN0_EN_REG << CMU_EN_REG_POS) | (_CMU_HFPERCLKEN0_VCMP_SHIFT << CMU_EN_BIT_POS) | (CMU_HFPER_CLK_BRANCH << CMU_CLK_BRANCH_POS), #endif #if defined(CMU_HFPERCLKEN0_ADC0) /** Analog-to-digital converter 0 clock */ cmuClock_ADC0 = (CMU_NODIV_REG << CMU_DIV_REG_POS) | (CMU_NOSEL_REG << CMU_SEL_REG_POS) | (CMU_HFPERCLKEN0_EN_REG << CMU_EN_REG_POS) | (_CMU_HFPERCLKEN0_ADC0_SHIFT << CMU_EN_BIT_POS) #if defined(_CMU_HFPERPRESCC_MASK) | (CMU_HFPERC_CLK_BRANCH << CMU_CLK_BRANCH_POS), #else | (CMU_HFPER_CLK_BRANCH << CMU_CLK_BRANCH_POS), #endif #endif #if defined(CMU_HFPERCLKEN0_ADC1) /** Analog-to-digital converter 1 clock */ cmuClock_ADC1 = (CMU_NODIV_REG << CMU_DIV_REG_POS) | (CMU_NOSEL_REG << CMU_SEL_REG_POS) | (CMU_HFPERCLKEN0_EN_REG << CMU_EN_REG_POS) | (_CMU_HFPERCLKEN0_ADC1_SHIFT << CMU_EN_BIT_POS) | (CMU_HFPERC_CLK_BRANCH << CMU_CLK_BRANCH_POS), #endif #if defined(CMU_HFPERCLKEN0_I2C0) /** I2C 0 clock */ cmuClock_I2C0 = (CMU_NODIV_REG << CMU_DIV_REG_POS) | (CMU_NOSEL_REG << CMU_SEL_REG_POS) | (CMU_HFPERCLKEN0_EN_REG << CMU_EN_REG_POS) | (_CMU_HFPERCLKEN0_I2C0_SHIFT << CMU_EN_BIT_POS) #if defined(_CMU_HFPERPRESCC_MASK) | (CMU_HFPERC_CLK_BRANCH << CMU_CLK_BRANCH_POS), #else | (CMU_HFPER_CLK_BRANCH << CMU_CLK_BRANCH_POS), #endif #endif #if defined(CMU_HFPERCLKEN0_I2C1) /** I2C 1 clock */ cmuClock_I2C1 = (CMU_NODIV_REG << CMU_DIV_REG_POS) | (CMU_NOSEL_REG << CMU_SEL_REG_POS) | (CMU_HFPERCLKEN0_EN_REG << CMU_EN_REG_POS) | (_CMU_HFPERCLKEN0_I2C1_SHIFT << CMU_EN_BIT_POS) #if defined(_CMU_HFPERPRESCC_MASK) | (CMU_HFPERC_CLK_BRANCH << CMU_CLK_BRANCH_POS), #else | (CMU_HFPER_CLK_BRANCH << CMU_CLK_BRANCH_POS), #endif #endif #if defined(CMU_HFPERCLKEN0_I2C2) /** I2C 2 clock */ cmuClock_I2C2 = (CMU_NODIV_REG << CMU_DIV_REG_POS) | (CMU_NOSEL_REG << CMU_SEL_REG_POS) | (CMU_HFPERCLKEN0_EN_REG << CMU_EN_REG_POS) | (_CMU_HFPERCLKEN0_I2C2_SHIFT << CMU_EN_BIT_POS) | (CMU_HFPERC_CLK_BRANCH << CMU_CLK_BRANCH_POS), #endif #if defined(CMU_HFPERCLKEN0_CSEN) /** Capacitive Sense HF clock */ cmuClock_CSEN_HF = (CMU_NODIV_REG << CMU_DIV_REG_POS) | (CMU_NOSEL_REG << CMU_SEL_REG_POS) | (CMU_HFPERCLKEN0_EN_REG << CMU_EN_REG_POS) | (_CMU_HFPERCLKEN0_CSEN_SHIFT << CMU_EN_BIT_POS) | (CMU_HFPER_CLK_BRANCH << CMU_CLK_BRANCH_POS), #elif defined(CMU_HFPERCLKEN1_CSEN) /** Capacitive Sense HF clock */ cmuClock_CSEN_HF = (CMU_NODIV_REG << CMU_DIV_REG_POS) | (CMU_NOSEL_REG << CMU_SEL_REG_POS) | (CMU_HFPERCLKEN1_EN_REG << CMU_EN_REG_POS) | (_CMU_HFPERCLKEN1_CSEN_SHIFT << CMU_EN_BIT_POS) | (CMU_HFPERC_CLK_BRANCH << CMU_CLK_BRANCH_POS), #endif #if defined(CMU_HFPERCLKEN0_TRNG0) /** True random number generator clock */ cmuClock_TRNG0 = (CMU_NODIV_REG << CMU_DIV_REG_POS) | (CMU_NOSEL_REG << CMU_SEL_REG_POS) | (CMU_HFPERCLKEN0_EN_REG << CMU_EN_REG_POS) | (_CMU_HFPERCLKEN0_TRNG0_SHIFT << CMU_EN_BIT_POS) | (CMU_HFPER_CLK_BRANCH << CMU_CLK_BRANCH_POS), #endif #if defined(_CMU_HFPERCLKEN1_CAN0_MASK) /** Controller Area Network 0 clock */ cmuClock_CAN0 = (CMU_NOPRESC_REG << CMU_PRESC_REG_POS) | (CMU_NOSEL_REG << CMU_SEL_REG_POS) | (CMU_HFPERCLKEN1_EN_REG << CMU_EN_REG_POS) | (_CMU_HFPERCLKEN1_CAN0_SHIFT << CMU_EN_BIT_POS) | (CMU_HFPER_CLK_BRANCH << CMU_CLK_BRANCH_POS), #endif #if defined(_CMU_HFPERCLKEN1_CAN1_MASK) /** Controller Area Network 1 clock. */ cmuClock_CAN1 = (CMU_NOPRESC_REG << CMU_PRESC_REG_POS) | (CMU_NOSEL_REG << CMU_SEL_REG_POS) | (CMU_HFPERCLKEN1_EN_REG << CMU_EN_REG_POS) | (_CMU_HFPERCLKEN1_CAN1_SHIFT << CMU_EN_BIT_POS) | (CMU_HFPER_CLK_BRANCH << CMU_CLK_BRANCH_POS), #endif /**********************/ /* HF core sub-branch */ /**********************/ /** Core clock */ cmuClock_CORE = (CMU_HFCORECLKDIV_REG << CMU_DIV_REG_POS) | (CMU_NOSEL_REG << CMU_SEL_REG_POS) | (CMU_NO_EN_REG << CMU_EN_REG_POS) | (0 << CMU_EN_BIT_POS) | (CMU_HFCORE_CLK_BRANCH << CMU_CLK_BRANCH_POS), #if defined(CMU_HFCORECLKEN0_AES) /** Advanced encryption standard accelerator clock */ cmuClock_AES = (CMU_NODIV_REG << CMU_DIV_REG_POS) | (CMU_NOSEL_REG << CMU_SEL_REG_POS) | (CMU_HFCORECLKEN0_EN_REG << CMU_EN_REG_POS) | (_CMU_HFCORECLKEN0_AES_SHIFT << CMU_EN_BIT_POS) | (CMU_HFCORE_CLK_BRANCH << CMU_CLK_BRANCH_POS), #endif #if defined(CMU_HFCORECLKEN0_DMA) /** Direct memory access controller clock */ cmuClock_DMA = (CMU_NODIV_REG << CMU_DIV_REG_POS) | (CMU_NOSEL_REG << CMU_SEL_REG_POS) | (CMU_HFCORECLKEN0_EN_REG << CMU_EN_REG_POS) | (_CMU_HFCORECLKEN0_DMA_SHIFT << CMU_EN_BIT_POS) | (CMU_HFCORE_CLK_BRANCH << CMU_CLK_BRANCH_POS), #endif #if defined(CMU_HFCORECLKEN0_LE) /** Low-energy clock divided down from HFCORECLK */ cmuClock_HFLE = (CMU_HFCORECLKLEDIV_REG << CMU_DIV_REG_POS) | (CMU_NOSEL_REG << CMU_SEL_REG_POS) | (CMU_HFCORECLKEN0_EN_REG << CMU_EN_REG_POS) | (_CMU_HFCORECLKEN0_LE_SHIFT << CMU_EN_BIT_POS) | (CMU_HFLE_CLK_BRANCH << CMU_CLK_BRANCH_POS), #endif #if defined(CMU_HFCORECLKEN0_EBI) /** External bus interface clock */ cmuClock_EBI = (CMU_NODIV_REG << CMU_DIV_REG_POS) | (CMU_NOSEL_REG << CMU_SEL_REG_POS) | (CMU_HFCORECLKEN0_EN_REG << CMU_EN_REG_POS) | (_CMU_HFCORECLKEN0_EBI_SHIFT << CMU_EN_BIT_POS) | (CMU_HFCORE_CLK_BRANCH << CMU_CLK_BRANCH_POS), #elif defined(_CMU_HFBUSCLKEN0_EBI_MASK) /** External bus interface clock */ cmuClock_EBI = (CMU_NOPRESC_REG << CMU_PRESC_REG_POS) | (CMU_NOSEL_REG << CMU_SEL_REG_POS) | (CMU_HFBUSCLKEN0_EN_REG << CMU_EN_REG_POS) | (_CMU_HFBUSCLKEN0_EBI_SHIFT << CMU_EN_BIT_POS) | (CMU_HFCORE_CLK_BRANCH << CMU_CLK_BRANCH_POS), #endif #if defined(_CMU_HFBUSCLKEN0_ETH_MASK) /** Ethernet clock */ cmuClock_ETH = (CMU_NOPRESC_REG << CMU_PRESC_REG_POS) | (CMU_NOSEL_REG << CMU_SEL_REG_POS) | (CMU_HFBUSCLKEN0_EN_REG << CMU_EN_REG_POS) | (_CMU_HFBUSCLKEN0_ETH_SHIFT << CMU_EN_BIT_POS) | (CMU_HFCORE_CLK_BRANCH << CMU_CLK_BRANCH_POS), #endif #if defined(_CMU_HFBUSCLKEN0_SDIO_MASK) /** SDIO clock */ cmuClock_SDIO = (CMU_NOPRESC_REG << CMU_PRESC_REG_POS) | (CMU_NOSEL_REG << CMU_SEL_REG_POS) | (CMU_HFBUSCLKEN0_EN_REG << CMU_EN_REG_POS) | (_CMU_HFBUSCLKEN0_SDIO_SHIFT << CMU_EN_BIT_POS) | (CMU_HFCORE_CLK_BRANCH << CMU_CLK_BRANCH_POS), #endif #if defined(USBC_CLOCK_PRESENT) /** USB Core clock */ cmuClock_USBC = (CMU_NODIV_REG << CMU_DIV_REG_POS) | (CMU_USBCCLKSEL_REG << CMU_SEL_REG_POS) | (CMU_HFCORECLKEN0_EN_REG << CMU_EN_REG_POS) | (_CMU_HFCORECLKEN0_USBC_SHIFT << CMU_EN_BIT_POS) | (CMU_USBC_CLK_BRANCH << CMU_CLK_BRANCH_POS), #endif #if defined (USBR_CLOCK_PRESENT) /** USB Rate clock */ cmuClock_USBR = (CMU_NODIV_REG << CMU_DIV_REG_POS) | (CMU_USBRCLKSEL_REG << CMU_SEL_REG_POS) | (CMU_USBRCLK_EN_REG << CMU_EN_REG_POS) | (_CMU_USBCTRL_USBCLKEN_SHIFT << CMU_EN_BIT_POS) | (CMU_USBR_CLK_BRANCH << CMU_CLK_BRANCH_POS), #endif #if defined(CMU_HFCORECLKEN0_USB) /** USB clock */ cmuClock_USB = (CMU_NODIV_REG << CMU_DIV_REG_POS) | (CMU_NOSEL_REG << CMU_SEL_REG_POS) | (CMU_HFCORECLKEN0_EN_REG << CMU_EN_REG_POS) | (_CMU_HFCORECLKEN0_USB_SHIFT << CMU_EN_BIT_POS) | (CMU_HFCORE_CLK_BRANCH << CMU_CLK_BRANCH_POS), #elif defined(CMU_HFBUSCLKEN0_USB) /** USB clock */ cmuClock_USB = (CMU_NOPRESC_REG << CMU_PRESC_REG_POS) | (CMU_NOSEL_REG << CMU_SEL_REG_POS) | (CMU_HFBUSCLKEN0_EN_REG << CMU_EN_REG_POS) | (_CMU_HFBUSCLKEN0_USB_SHIFT << CMU_EN_BIT_POS) | (CMU_HFCORE_CLK_BRANCH << CMU_CLK_BRANCH_POS), #endif /***************/ /* LF A branch */ /***************/ /** Low-frequency A clock */ cmuClock_LFA = (CMU_NODIV_REG << CMU_DIV_REG_POS) | (CMU_LFACLKSEL_REG << CMU_SEL_REG_POS) | (CMU_NO_EN_REG << CMU_EN_REG_POS) | (0 << CMU_EN_BIT_POS) | (CMU_LFA_CLK_BRANCH << CMU_CLK_BRANCH_POS), #if defined(CMU_LFACLKEN0_RTC) /** Real time counter clock */ cmuClock_RTC = (CMU_LFAPRESC0_REG << CMU_DIV_REG_POS) | (CMU_NOSEL_REG << CMU_SEL_REG_POS) | (CMU_LFACLKEN0_EN_REG << CMU_EN_REG_POS) | (_CMU_LFACLKEN0_RTC_SHIFT << CMU_EN_BIT_POS) | (CMU_RTC_CLK_BRANCH << CMU_CLK_BRANCH_POS), #endif #if defined(CMU_LFACLKEN0_LETIMER0) /** Low-energy timer 0 clock */ cmuClock_LETIMER0 = (CMU_LFAPRESC0_REG << CMU_DIV_REG_POS) | (CMU_NOSEL_REG << CMU_SEL_REG_POS) | (CMU_LFACLKEN0_EN_REG << CMU_EN_REG_POS) | (_CMU_LFACLKEN0_LETIMER0_SHIFT << CMU_EN_BIT_POS) | (CMU_LETIMER0_CLK_BRANCH << CMU_CLK_BRANCH_POS), #endif #if defined(CMU_LFACLKEN0_LETIMER1) /** Low-energy timer 1 clock */ cmuClock_LETIMER1 = (CMU_LFAPRESC0_REG << CMU_DIV_REG_POS) | (CMU_NOSEL_REG << CMU_SEL_REG_POS) | (CMU_LFACLKEN0_EN_REG << CMU_EN_REG_POS) | (_CMU_LFACLKEN0_LETIMER1_SHIFT << CMU_EN_BIT_POS) | (CMU_LETIMER1_CLK_BRANCH << CMU_CLK_BRANCH_POS), #endif #if defined(CMU_LFACLKEN0_LCD) /** Liquid crystal display, pre FDIV clock */ cmuClock_LCDpre = (CMU_LFAPRESC0_REG << CMU_DIV_REG_POS) | (CMU_NOSEL_REG << CMU_SEL_REG_POS) | (CMU_NO_EN_REG << CMU_EN_REG_POS) | (0 << CMU_EN_BIT_POS) | (CMU_LCDPRE_CLK_BRANCH << CMU_CLK_BRANCH_POS), /** Liquid crystal display clock. Note that FDIV prescaler * must be set by special API. */ cmuClock_LCD = (CMU_NODIV_REG << CMU_DIV_REG_POS) | (CMU_NOSEL_REG << CMU_SEL_REG_POS) | (CMU_LFACLKEN0_EN_REG << CMU_EN_REG_POS) | (_CMU_LFACLKEN0_LCD_SHIFT << CMU_EN_BIT_POS) | (CMU_LCD_CLK_BRANCH << CMU_CLK_BRANCH_POS), #endif #if defined(CMU_PCNTCTRL_PCNT0CLKEN) /** Pulse counter 0 clock */ cmuClock_PCNT0 = (CMU_NODIV_REG << CMU_DIV_REG_POS) | (CMU_NOSEL_REG << CMU_SEL_REG_POS) | (CMU_PCNT_EN_REG << CMU_EN_REG_POS) | (_CMU_PCNTCTRL_PCNT0CLKEN_SHIFT << CMU_EN_BIT_POS) | (CMU_LFA_CLK_BRANCH << CMU_CLK_BRANCH_POS), #endif #if defined(CMU_PCNTCTRL_PCNT1CLKEN) /** Pulse counter 1 clock */ cmuClock_PCNT1 = (CMU_NODIV_REG << CMU_DIV_REG_POS) | (CMU_NOSEL_REG << CMU_SEL_REG_POS) | (CMU_PCNT_EN_REG << CMU_EN_REG_POS) | (_CMU_PCNTCTRL_PCNT1CLKEN_SHIFT << CMU_EN_BIT_POS) | (CMU_LFA_CLK_BRANCH << CMU_CLK_BRANCH_POS), #endif #if defined(CMU_PCNTCTRL_PCNT2CLKEN) /** Pulse counter 2 clock */ cmuClock_PCNT2 = (CMU_NODIV_REG << CMU_DIV_REG_POS) | (CMU_NOSEL_REG << CMU_SEL_REG_POS) | (CMU_PCNT_EN_REG << CMU_EN_REG_POS) | (_CMU_PCNTCTRL_PCNT2CLKEN_SHIFT << CMU_EN_BIT_POS) | (CMU_LFA_CLK_BRANCH << CMU_CLK_BRANCH_POS), #endif #if defined(CMU_LFACLKEN0_LESENSE) /** LESENSE clock */ cmuClock_LESENSE = (CMU_LFAPRESC0_REG << CMU_DIV_REG_POS) | (CMU_NOSEL_REG << CMU_SEL_REG_POS) | (CMU_LFACLKEN0_EN_REG << CMU_EN_REG_POS) | (_CMU_LFACLKEN0_LESENSE_SHIFT << CMU_EN_BIT_POS) | (CMU_LESENSE_CLK_BRANCH << CMU_CLK_BRANCH_POS), #endif /***************/ /* LF B branch */ /***************/ /** Low-frequency B clock */ cmuClock_LFB = (CMU_NODIV_REG << CMU_DIV_REG_POS) | (CMU_LFBCLKSEL_REG << CMU_SEL_REG_POS) | (CMU_NO_EN_REG << CMU_EN_REG_POS) | (0 << CMU_EN_BIT_POS) | (CMU_LFB_CLK_BRANCH << CMU_CLK_BRANCH_POS), #if defined(CMU_LFBCLKEN0_LEUART0) /** Low-energy universal asynchronous receiver/transmitter 0 clock */ cmuClock_LEUART0 = (CMU_LFBPRESC0_REG << CMU_DIV_REG_POS) | (CMU_NOSEL_REG << CMU_SEL_REG_POS) | (CMU_LFBCLKEN0_EN_REG << CMU_EN_REG_POS) | (_CMU_LFBCLKEN0_LEUART0_SHIFT << CMU_EN_BIT_POS) | (CMU_LEUART0_CLK_BRANCH << CMU_CLK_BRANCH_POS), #endif #if defined(CMU_LFBCLKEN0_CSEN) /** Capacitive Sense LF clock */ cmuClock_CSEN_LF = (CMU_LFBPRESC0_REG << CMU_DIV_REG_POS) | (CMU_NOSEL_REG << CMU_SEL_REG_POS) | (CMU_LFBCLKEN0_EN_REG << CMU_EN_REG_POS) | (_CMU_LFBCLKEN0_CSEN_SHIFT << CMU_EN_BIT_POS) | (CMU_CSEN_LF_CLK_BRANCH << CMU_CLK_BRANCH_POS), #endif #if defined(CMU_LFBCLKEN0_LEUART1) /** Low-energy universal asynchronous receiver/transmitter 1 clock */ cmuClock_LEUART1 = (CMU_LFBPRESC0_REG << CMU_DIV_REG_POS) | (CMU_NOSEL_REG << CMU_SEL_REG_POS) | (CMU_LFBCLKEN0_EN_REG << CMU_EN_REG_POS) | (_CMU_LFBCLKEN0_LEUART1_SHIFT << CMU_EN_BIT_POS) | (CMU_LEUART1_CLK_BRANCH << CMU_CLK_BRANCH_POS), #endif #if defined(CMU_LFBCLKEN0_SYSTICK) /** Cortex SYSTICK LF clock */ cmuClock_SYSTICK = (CMU_LFBPRESC0_REG << CMU_DIV_REG_POS) | (CMU_NOSEL_REG << CMU_SEL_REG_POS) | (CMU_LFBCLKEN0_EN_REG << CMU_EN_REG_POS) | (_CMU_LFBCLKEN0_SYSTICK_SHIFT << CMU_EN_BIT_POS) | (CMU_LEUART0_CLK_BRANCH << CMU_CLK_BRANCH_POS), #endif #if defined(_CMU_LFCCLKEN0_MASK) /***************/ /* LF C branch */ /***************/ /** Low-frequency C clock */ cmuClock_LFC = (CMU_NODIV_REG << CMU_DIV_REG_POS) | (CMU_LFCCLKSEL_REG << CMU_SEL_REG_POS) | (CMU_NO_EN_REG << CMU_EN_REG_POS) | (0 << CMU_EN_BIT_POS) | (CMU_LFC_CLK_BRANCH << CMU_CLK_BRANCH_POS), #if defined(CMU_LFCCLKEN0_USBLE) /** USB LE clock */ cmuClock_USBLE = (CMU_NODIV_REG << CMU_DIV_REG_POS) | (CMU_LFCCLKSEL_REG << CMU_SEL_REG_POS) | (CMU_LFCCLKEN0_EN_REG << CMU_EN_REG_POS) | (_CMU_LFCCLKEN0_USBLE_SHIFT << CMU_EN_BIT_POS) | (CMU_USBLE_CLK_BRANCH << CMU_CLK_BRANCH_POS), #elif defined(CMU_LFCCLKEN0_USB) /** USB LE clock */ cmuClock_USBLE = (CMU_NODIV_REG << CMU_DIV_REG_POS) | (CMU_LFCCLKSEL_REG << CMU_SEL_REG_POS) | (CMU_LFCCLKEN0_EN_REG << CMU_EN_REG_POS) | (_CMU_LFCCLKEN0_USB_SHIFT << CMU_EN_BIT_POS) | (CMU_USBLE_CLK_BRANCH << CMU_CLK_BRANCH_POS), #endif #endif #if defined(_CMU_LFECLKEN0_MASK) /***************/ /* LF E branch */ /***************/ /** Low-frequency E clock */ cmuClock_LFE = (CMU_NOPRESC_REG << CMU_PRESC_REG_POS) | (CMU_LFECLKSEL_REG << CMU_SEL_REG_POS) | (CMU_NO_EN_REG << CMU_EN_REG_POS) | (0 << CMU_EN_BIT_POS) | (CMU_LFE_CLK_BRANCH << CMU_CLK_BRANCH_POS), /** Real-time counter and calendar clock */ #if defined (CMU_LFECLKEN0_RTCC) cmuClock_RTCC = (CMU_LFEPRESC0_REG << CMU_PRESC_REG_POS) | (CMU_NOSEL_REG << CMU_SEL_REG_POS) | (CMU_LFECLKEN0_EN_REG << CMU_EN_REG_POS) | (_CMU_LFECLKEN0_RTCC_SHIFT << CMU_EN_BIT_POS) | (CMU_RTCC_CLK_BRANCH << CMU_CLK_BRANCH_POS), #endif #endif /**********************************/ /* Asynchronous peripheral clocks */ /**********************************/ #if defined(_CMU_ADCCTRL_ADC0CLKSEL_MASK) /** ADC0 asynchronous clock */ cmuClock_ADC0ASYNC = (CMU_ADCASYNCDIV_REG << CMU_DIV_REG_POS) | (CMU_ADC0ASYNCSEL_REG << CMU_SEL_REG_POS) | (CMU_NO_EN_REG << CMU_EN_REG_POS) | (0 << CMU_EN_BIT_POS) | (CMU_ADC0ASYNC_CLK_BRANCH << CMU_CLK_BRANCH_POS), #endif #if defined(_CMU_ADCCTRL_ADC1CLKSEL_MASK) /** ADC1 asynchronous clock */ cmuClock_ADC1ASYNC = (CMU_ADCASYNCDIV_REG << CMU_DIV_REG_POS) | (CMU_ADC1ASYNCSEL_REG << CMU_SEL_REG_POS) | (CMU_NO_EN_REG << CMU_EN_REG_POS) | (0 << CMU_EN_BIT_POS) | (CMU_ADC1ASYNC_CLK_BRANCH << CMU_CLK_BRANCH_POS), #endif #if defined(_CMU_SDIOCTRL_SDIOCLKDIS_MASK) /** SDIO reference clock */ cmuClock_SDIOREF = (CMU_NODIV_REG << CMU_DIV_REG_POS) | (CMU_SDIOREFSEL_REG << CMU_SEL_REG_POS) | (CMU_SDIOREF_EN_REG << CMU_EN_REG_POS) | (_CMU_SDIOCTRL_SDIOCLKDIS_SHIFT << CMU_EN_BIT_POS) | (CMU_SDIOREF_CLK_BRANCH << CMU_CLK_BRANCH_POS), #endif #if defined(_CMU_QSPICTRL_QSPI0CLKDIS_MASK) /** QSPI0 reference clock */ cmuClock_QSPI0REF = (CMU_NODIV_REG << CMU_DIV_REG_POS) | (CMU_QSPI0REFSEL_REG << CMU_SEL_REG_POS) | (CMU_QSPI0REF_EN_REG << CMU_EN_REG_POS) | (_CMU_QSPICTRL_QSPI0CLKDIS_SHIFT << CMU_EN_BIT_POS) | (CMU_QSPI0REF_CLK_BRANCH << CMU_CLK_BRANCH_POS), #endif #if defined(_CMU_PDMCTRL_PDMCLKEN_MASK) /** PDM reference clock */ cmuClock_PDMREF = (CMU_NODIV_REG << CMU_DIV_REG_POS) | (CMU_PDMREFSEL_REG << CMU_SEL_REG_POS) | (CMU_PDMREF_EN_REG << CMU_EN_REG_POS) | (_CMU_PDMCTRL_PDMCLKEN_SHIFT << CMU_EN_BIT_POS) | (CMU_PDMREF_CLK_BRANCH << CMU_CLK_BRANCH_POS), #endif } CMU_Clock_TypeDef; /** @cond DO_NOT_INCLUDE_WITH_DOXYGEN */ /* Deprecated CMU_Clock_TypeDef member */ #define cmuClock_CORELE cmuClock_HFLE /** @endcond */ /** Oscillator types. */ typedef enum { cmuOsc_LFXO, /**< Low-frequency crystal oscillator. */ cmuOsc_LFRCO, /**< Low-frequency RC oscillator. */ cmuOsc_HFXO, /**< High-frequency crystal oscillator. */ cmuOsc_HFRCO, /**< High-frequency RC oscillator. */ cmuOsc_AUXHFRCO, /**< Auxiliary high-frequency RC oscillator. */ #if defined(_CMU_STATUS_USHFRCOENS_MASK) cmuOsc_USHFRCO, /**< Universal serial high-frequency RC oscillator */ #endif #if defined(CMU_LFCLKSEL_LFAE_ULFRCO) || defined(CMU_LFACLKSEL_LFA_ULFRCO) cmuOsc_ULFRCO, /**< Ultra low-frequency RC oscillator. */ #endif #if defined(CMU_HFCLKSTATUS_SELECTED_CLKIN0) cmuOsc_CLKIN0, /**< External oscillator. */ #endif #if defined(PLFRCO_PRESENT) cmuOsc_PLFRCO, /**< Precision Low Frequency Oscillator. */ #endif } CMU_Osc_TypeDef; /** Oscillator modes. */ typedef enum { cmuOscMode_Crystal, /**< Crystal oscillator. */ cmuOscMode_AcCoupled, /**< AC-coupled buffer. */ cmuOscMode_External, /**< External digital clock. */ } CMU_OscMode_TypeDef; /** Selectable clock sources. */ typedef enum { cmuSelect_Error, /**< Usage error. */ cmuSelect_Disabled, /**< Clock selector disabled. */ cmuSelect_LFXO, /**< Low-frequency crystal oscillator. */ cmuSelect_LFRCO, /**< Low-frequency RC oscillator. */ cmuSelect_HFXO, /**< High-frequency crystal oscillator. */ cmuSelect_HFRCO, /**< High-frequency RC oscillator. */ cmuSelect_HFCLKLE, /**< High-frequency LE clock divided by 2 or 4. */ cmuSelect_AUXHFRCO, /**< Auxilliary clock source can be used for debug clock. */ cmuSelect_HFSRCCLK, /**< High-frequency source clock. */ cmuSelect_HFCLK, /**< Divided HFCLK on Giant for debug clock, undivided on Tiny Gecko and for USBC (not used on Gecko). */ #if defined(CMU_STATUS_USHFRCOENS) cmuSelect_USHFRCO, /**< Universal serial high-frequency RC oscillator. */ #endif #if defined(CMU_CMD_HFCLKSEL_USHFRCODIV2) cmuSelect_USHFRCODIV2, /**< Universal serial high-frequency RC oscillator / 2. */ #endif #if defined(CMU_HFXOCTRL_HFXOX2EN) cmuSelect_HFXOX2, /**< High-frequency crystal oscillator x 2. */ #endif #if defined(CMU_LFCLKSEL_LFAE_ULFRCO) || defined(CMU_LFACLKSEL_LFA_ULFRCO) cmuSelect_ULFRCO, /**< Ultra low-frequency RC oscillator. */ #endif #if defined(CMU_HFCLKSTATUS_SELECTED_HFRCODIV2) cmuSelect_HFRCODIV2, /**< High-frequency RC oscillator divided by 2. */ #endif #if defined(CMU_HFCLKSTATUS_SELECTED_CLKIN0) cmuSelect_CLKIN0, /**< External clock input. */ #endif #if defined(PLFRCO_PRESENT) cmuSelect_PLFRCO, /**< Precision Low Frequency Oscillator. */ #endif } CMU_Select_TypeDef; #if defined(CMU_HFCORECLKEN0_LE) /** @cond DO_NOT_INCLUDE_WITH_DOXYGEN */ /* Deprecated CMU_Select_TypeDef member */ #define cmuSelect_CORELEDIV2 cmuSelect_HFCLKLE /** @endcond */ #endif #if defined(_CMU_HFXOCTRL_PEAKDETSHUNTOPTMODE_MASK) || defined(_CMU_HFXOCTRL_PEAKDETMODE_MASK) /** HFXO tuning modes */ typedef enum { cmuHFXOTuningMode_Auto = 0, cmuHFXOTuningMode_PeakDetectCommand = CMU_CMD_HFXOPEAKDETSTART, /**< Run peak detect optimization only. */ #if defined(CMU_CMD_HFXOSHUNTOPTSTART) cmuHFXOTuningMode_ShuntCommand = CMU_CMD_HFXOSHUNTOPTSTART, /**< Run shunt current optimization only. */ cmuHFXOTuningMode_PeakShuntCommand = CMU_CMD_HFXOPEAKDETSTART /**< Run peak and shunt current optimization. */ | CMU_CMD_HFXOSHUNTOPTSTART, #endif } CMU_HFXOTuningMode_TypeDef; #endif #if defined(_CMU_CTRL_LFXOBOOST_MASK) /** LFXO Boost values. */ typedef enum { cmuLfxoBoost70 = 0x0, cmuLfxoBoost100 = 0x2, #if defined(_EMU_AUXCTRL_REDLFXOBOOST_MASK) cmuLfxoBoost70Reduced = 0x1, cmuLfxoBoost100Reduced = 0x3, #endif } CMU_LFXOBoost_TypeDef; #endif #if defined(CMU_OSCENCMD_DPLLEN) /** DPLL reference clock selector. */ typedef enum { cmuDPLLClkSel_Hfxo = _CMU_DPLLCTRL_REFSEL_HFXO, /**< HFXO is DPLL reference clock. */ cmuDPLLClkSel_Lfxo = _CMU_DPLLCTRL_REFSEL_LFXO, /**< LFXO is DPLL reference clock. */ cmuDPLLClkSel_Clkin0 = _CMU_DPLLCTRL_REFSEL_CLKIN0 /**< CLKIN0 is DPLL reference clock. */ } CMU_DPLLClkSel_TypeDef; /** DPLL reference clock edge detect selector. */ typedef enum { cmuDPLLEdgeSel_Fall = _CMU_DPLLCTRL_EDGESEL_FALL, /**< Detect falling edge of reference clock. */ cmuDPLLEdgeSel_Rise = _CMU_DPLLCTRL_EDGESEL_RISE /**< Detect rising edge of reference clock. */ } CMU_DPLLEdgeSel_TypeDef; /** DPLL lock mode selector. */ typedef enum { cmuDPLLLockMode_Freq = _CMU_DPLLCTRL_MODE_FREQLL, /**< Frequency lock mode. */ cmuDPLLLockMode_Phase = _CMU_DPLLCTRL_MODE_PHASELL /**< Phase lock mode. */ } CMU_DPLLLockMode_TypeDef; #endif // CMU_OSCENCMD_DPLLEN /******************************************************************************* ******************************* STRUCTS *********************************** ******************************************************************************/ /** LFXO initialization structure. Initialization values should be obtained from a configuration tool, app note, or xtal data sheet. */ typedef struct { #if defined(_CMU_LFXOCTRL_MASK) uint8_t ctune; /**< CTUNE (load capacitance) value */ uint8_t gain; /**< Gain/max startup margin */ #else CMU_LFXOBoost_TypeDef boost; /**< LFXO boost */ #endif uint8_t timeout; /**< Startup delay */ CMU_OscMode_TypeDef mode; /**< Oscillator mode */ } CMU_LFXOInit_TypeDef; #if defined(_CMU_LFXOCTRL_MASK) /** Default LFXO initialization values for platform 2 devices, which contain a * separate LFXOCTRL register. */ #define CMU_LFXOINIT_DEFAULT \ { \ _CMU_LFXOCTRL_TUNING_DEFAULT, /* Default CTUNE value, 0 */ \ _CMU_LFXOCTRL_GAIN_DEFAULT, /* Default gain, 2 */ \ _CMU_LFXOCTRL_TIMEOUT_DEFAULT, /* Default start-up delay, 32 K cycles */ \ cmuOscMode_Crystal, /* Crystal oscillator */ \ } #define CMU_LFXOINIT_EXTERNAL_CLOCK \ { \ 0, /* No CTUNE value needed */ \ 0, /* No LFXO startup gain */ \ _CMU_LFXOCTRL_TIMEOUT_2CYCLES, /* Minimal lfxo start-up delay, 2 cycles */ \ cmuOscMode_External, /* External digital clock */ \ } #else /** Default LFXO initialization values for platform 1 devices. */ #define CMU_LFXOINIT_DEFAULT \ { \ cmuLfxoBoost70, \ _CMU_CTRL_LFXOTIMEOUT_DEFAULT, \ cmuOscMode_Crystal, \ } #define CMU_LFXOINIT_EXTERNAL_CLOCK \ { \ cmuLfxoBoost70, \ _CMU_CTRL_LFXOTIMEOUT_8CYCLES, \ cmuOscMode_External, \ } #endif /** HFXO initialization structure. Initialization values should be obtained from a configuration tool, app note, or xtal data sheet. */ typedef struct { #if defined(_SILICON_LABS_32B_SERIES_1) && (_SILICON_LABS_GECKO_INTERNAL_SDID >= 100) uint16_t ctuneStartup; /**< Startup phase CTUNE (load capacitance) value */ uint16_t ctuneSteadyState; /**< Steady-state phase CTUNE (load capacitance) value */ uint16_t xoCoreBiasTrimStartup; /**< Startup XO core bias current trim */ uint16_t xoCoreBiasTrimSteadyState; /**< Steady-state XO core bias current trim */ uint8_t timeoutPeakDetect; /**< Timeout - peak detection */ uint8_t timeoutSteady; /**< Timeout - steady-state */ uint8_t timeoutStartup; /**< Timeout - startup */ #elif defined(_CMU_HFXOCTRL_MASK) bool lowPowerMode; /**< Enable low-power mode */ bool autoStartEm01; /**< @deprecated Use @ref CMU_HFXOAutostartEnable instead. */ bool autoSelEm01; /**< @deprecated Use @ref CMU_HFXOAutostartEnable instead. */ bool autoStartSelOnRacWakeup; /**< @deprecated Use @ref CMU_HFXOAutostartEnable instead. */ uint16_t ctuneStartup; /**< Startup phase CTUNE (load capacitance) value */ uint16_t ctuneSteadyState; /**< Steady-state phase CTUNE (load capacitance) value */ uint8_t regIshSteadyState; /**< Shunt steady-state current */ uint8_t xoCoreBiasTrimStartup; /**< Startup XO core bias current trim */ uint8_t xoCoreBiasTrimSteadyState; /**< Steady-state XO core bias current trim */ uint8_t thresholdPeakDetect; /**< Peak detection threshold */ uint8_t timeoutShuntOptimization; /**< Timeout - shunt optimization */ uint8_t timeoutPeakDetect; /**< Timeout - peak detection */ uint8_t timeoutSteady; /**< Timeout - steady-state */ uint8_t timeoutStartup; /**< Timeout - startup */ #else uint8_t boost; /**< HFXO Boost, 0=50% 1=70%, 2=80%, 3=100% */ uint8_t timeout; /**< Startup delay */ bool glitchDetector; /**< Enable/disable glitch detector */ #endif CMU_OscMode_TypeDef mode; /**< Oscillator mode */ } CMU_HFXOInit_TypeDef; #if defined(_SILICON_LABS_32B_SERIES_1) && (_SILICON_LABS_GECKO_INTERNAL_SDID >= 100) #define CMU_HFXOINIT_DEFAULT \ { \ _CMU_HFXOSTARTUPCTRL_CTUNE_DEFAULT, \ _CMU_HFXOSTEADYSTATECTRL_CTUNE_DEFAULT, \ _CMU_HFXOSTARTUPCTRL_IBTRIMXOCORE_DEFAULT, \ _CMU_HFXOSTEADYSTATECTRL_IBTRIMXOCORE_DEFAULT, \ _CMU_HFXOTIMEOUTCTRL_PEAKDETTIMEOUT_DEFAULT, \ _CMU_HFXOTIMEOUTCTRL_STEADYTIMEOUT_DEFAULT, \ _CMU_HFXOTIMEOUTCTRL_STARTUPTIMEOUT_DEFAULT, \ cmuOscMode_Crystal, \ } #define CMU_HFXOINIT_EXTERNAL_CLOCK \ { \ _CMU_HFXOSTARTUPCTRL_CTUNE_DEFAULT, \ _CMU_HFXOSTEADYSTATECTRL_CTUNE_DEFAULT, \ _CMU_HFXOSTARTUPCTRL_IBTRIMXOCORE_DEFAULT, \ _CMU_HFXOSTEADYSTATECTRL_IBTRIMXOCORE_DEFAULT, \ _CMU_HFXOTIMEOUTCTRL_PEAKDETTIMEOUT_DEFAULT, \ _CMU_HFXOTIMEOUTCTRL_STEADYTIMEOUT_DEFAULT, \ _CMU_HFXOTIMEOUTCTRL_STARTUPTIMEOUT_DEFAULT, \ cmuOscMode_External, \ } #elif defined(_CMU_HFXOCTRL_MASK) /** * Default HFXO initialization values for Platform 2 devices, which contain a * separate HFXOCTRL register. */ #if defined(_EFR_DEVICE) #define CMU_HFXOINIT_DEFAULT \ { \ false, /* Low-noise mode for EFR32 */ \ false, /* @deprecated no longer in use */ \ false, /* @deprecated no longer in use */ \ false, /* @deprecated no longer in use */ \ _CMU_HFXOSTARTUPCTRL_CTUNE_DEFAULT, \ _CMU_HFXOSTEADYSTATECTRL_CTUNE_DEFAULT, \ 0xA, /* Default Shunt steady-state current */ \ 0x20, /* Matching errata fix in @ref CHIP_Init() */ \ 0x7, /* Recommended steady-state XO core bias current */ \ 0x6, /* Recommended peak detection threshold */ \ 0x2, /* Recommended shunt optimization timeout */ \ 0xA, /* Recommended peak detection timeout */ \ 0x4, /* Recommended steady timeout */ \ _CMU_HFXOTIMEOUTCTRL_STARTUPTIMEOUT_DEFAULT, \ cmuOscMode_Crystal, \ } #else /* EFM32 device */ #define CMU_HFXOINIT_DEFAULT \ { \ true, /* Low-power mode for EFM32 */ \ false, /* @deprecated no longer in use */ \ false, /* @deprecated no longer in use */ \ false, /* @deprecated no longer in use */ \ _CMU_HFXOSTARTUPCTRL_CTUNE_DEFAULT, \ _CMU_HFXOSTEADYSTATECTRL_CTUNE_DEFAULT, \ 0xA, /* Default shunt steady-state current */ \ 0x20, /* Matching errata fix in @ref CHIP_Init() */ \ 0x7, /* Recommended steady-state osc core bias current */ \ 0x6, /* Recommended peak detection threshold */ \ 0x2, /* Recommended shunt optimization timeout */ \ 0xA, /* Recommended peak detection timeout */ \ 0x4, /* Recommended steady timeout */ \ _CMU_HFXOTIMEOUTCTRL_STARTUPTIMEOUT_DEFAULT, \ cmuOscMode_Crystal, \ } #endif /* _EFR_DEVICE */ #define CMU_HFXOINIT_EXTERNAL_CLOCK \ { \ true, /* Low-power mode */ \ false, /* @deprecated no longer in use */ \ false, /* @deprecated no longer in use */ \ false, /* @deprecated no longer in use */ \ 0, /* Startup CTUNE=0 recommended for external clock */ \ 0, /* Steady CTUNE=0 recommended for external clock */ \ 0xA, /* Default shunt steady-state current */ \ 0, /* Startup IBTRIMXOCORE=0 recommended for external clock */ \ 0, /* Steady IBTRIMXOCORE=0 recommended for external clock */ \ 0x6, /* Recommended peak detection threshold */ \ 0x2, /* Recommended shunt optimization timeout */ \ 0x0, /* Peak-detect not recommended for external clock usage */ \ _CMU_HFXOTIMEOUTCTRL_STEADYTIMEOUT_2CYCLES, /* Minimal steady timeout */ \ _CMU_HFXOTIMEOUTCTRL_STARTUPTIMEOUT_2CYCLES, /* Minimal startup timeout */ \ cmuOscMode_External, \ } #else /* _CMU_HFXOCTRL_MASK */ /** * Default HFXO initialization values for Platform 1 devices. */ #define CMU_HFXOINIT_DEFAULT \ { \ _CMU_CTRL_HFXOBOOST_DEFAULT, /* 100% HFXO boost */ \ _CMU_CTRL_HFXOTIMEOUT_DEFAULT, /* 16 K startup delay */ \ false, /* Disable glitch detector */ \ cmuOscMode_Crystal, /* Crystal oscillator */ \ } #define CMU_HFXOINIT_EXTERNAL_CLOCK \ { \ 0, /* Minimal HFXO boost, 50% */ \ _CMU_CTRL_HFXOTIMEOUT_8CYCLES, /* Minimal startup delay, 8 cycles */ \ false, /* Disable glitch detector */ \ cmuOscMode_External, /* External digital clock */ \ } #endif /* _CMU_HFXOCTRL_MASK */ #if defined(CMU_OSCENCMD_DPLLEN) /** DPLL initialization structure. Frequency will be Fref*(N+1)/(M+1). */ typedef struct { uint32_t frequency; /**< PLL frequency value, max 40 MHz. */ uint16_t n; /**< Factor N. 300 <= N <= 4095 */ uint16_t m; /**< Factor M. M <= 4095 */ uint8_t ssInterval; /**< Spread spectrum update interval. */ uint8_t ssAmplitude; /**< Spread spectrum amplitude. */ CMU_DPLLClkSel_TypeDef refClk; /**< Reference clock selector. */ CMU_DPLLEdgeSel_TypeDef edgeSel; /**< Reference clock edge detect selector. */ CMU_DPLLLockMode_TypeDef lockMode; /**< DPLL lock mode selector. */ bool autoRecover; /**< Enable automatic lock recovery. */ } CMU_DPLLInit_TypeDef; /** * DPLL initialization values for 39,998,805 Hz using LFXO as reference * clock, M=2 and N=3661. */ #define CMU_DPLL_LFXO_TO_40MHZ \ { \ 39998805, /* Target frequency. */ \ 3661, /* Factor N. */ \ 2, /* Factor M. */ \ 0, /* No spread spectrum clocking. */ \ 0, /* No spread spectrum clocking. */ \ cmuDPLLClkSel_Lfxo, /* Select LFXO as reference clock. */ \ cmuDPLLEdgeSel_Fall, /* Select falling edge of ref clock. */ \ cmuDPLLLockMode_Freq, /* Use frequency lock mode. */ \ true /* Enable automatic lock recovery. */ \ } #endif // CMU_OSCENCMD_DPLLEN /******************************************************************************* ***************************** PROTOTYPES ********************************** ******************************************************************************/ #if defined(_CMU_AUXHFRCOCTRL_BAND_MASK) CMU_AUXHFRCOBand_TypeDef CMU_AUXHFRCOBandGet(void); void CMU_AUXHFRCOBandSet(CMU_AUXHFRCOBand_TypeDef band); #elif defined(_CMU_AUXHFRCOCTRL_FREQRANGE_MASK) CMU_AUXHFRCOFreq_TypeDef CMU_AUXHFRCOBandGet(void); void CMU_AUXHFRCOBandSet(CMU_AUXHFRCOFreq_TypeDef setFreq); #endif uint32_t CMU_Calibrate(uint32_t HFCycles, CMU_Osc_TypeDef reference); #if defined(_CMU_CALCTRL_UPSEL_MASK) && defined(_CMU_CALCTRL_DOWNSEL_MASK) void CMU_CalibrateConfig(uint32_t downCycles, CMU_Osc_TypeDef downSel, CMU_Osc_TypeDef upSel); #endif uint32_t CMU_CalibrateCountGet(void); void CMU_ClockEnable(CMU_Clock_TypeDef clock, bool enable); CMU_ClkDiv_TypeDef CMU_ClockDivGet(CMU_Clock_TypeDef clock); void CMU_ClockDivSet(CMU_Clock_TypeDef clock, CMU_ClkDiv_TypeDef div); uint32_t CMU_ClockFreqGet(CMU_Clock_TypeDef clock); #if defined(_SILICON_LABS_32B_SERIES_1) void CMU_ClockPrescSet(CMU_Clock_TypeDef clock, CMU_ClkPresc_TypeDef presc); uint32_t CMU_ClockPrescGet(CMU_Clock_TypeDef clock); #endif void CMU_ClockSelectSet(CMU_Clock_TypeDef clock, CMU_Select_TypeDef ref); CMU_Select_TypeDef CMU_ClockSelectGet(CMU_Clock_TypeDef clock); #if defined(CMU_OSCENCMD_DPLLEN) bool CMU_DPLLLock(const CMU_DPLLInit_TypeDef *init); #endif void CMU_FreezeEnable(bool enable); #if defined(_CMU_HFRCOCTRL_BAND_MASK) CMU_HFRCOBand_TypeDef CMU_HFRCOBandGet(void); void CMU_HFRCOBandSet(CMU_HFRCOBand_TypeDef band); #elif defined(_CMU_HFRCOCTRL_FREQRANGE_MASK) CMU_HFRCOFreq_TypeDef CMU_HFRCOBandGet(void); void CMU_HFRCOBandSet(CMU_HFRCOFreq_TypeDef setFreq); #endif #if defined(_CMU_HFRCOCTRL_SUDELAY_MASK) uint32_t CMU_HFRCOStartupDelayGet(void); void CMU_HFRCOStartupDelaySet(uint32_t delay); #endif #if defined(_CMU_USHFRCOCTRL_FREQRANGE_MASK) CMU_USHFRCOFreq_TypeDef CMU_USHFRCOBandGet(void); void CMU_USHFRCOBandSet(CMU_USHFRCOFreq_TypeDef setFreq); uint32_t CMU_USHFRCOFreqGet(void); #endif #if defined(_CMU_HFXOCTRL_AUTOSTARTEM0EM1_MASK) void CMU_HFXOAutostartEnable(uint32_t userSel, bool enEM0EM1Start, bool enEM0EM1StartSel); #endif void CMU_HFXOInit(const CMU_HFXOInit_TypeDef *hfxoInit); uint32_t CMU_LCDClkFDIVGet(void); void CMU_LCDClkFDIVSet(uint32_t div); void CMU_LFXOInit(const CMU_LFXOInit_TypeDef *lfxoInit); void CMU_OscillatorEnable(CMU_Osc_TypeDef osc, bool enable, bool wait); uint32_t CMU_OscillatorTuningGet(CMU_Osc_TypeDef osc); void CMU_OscillatorTuningSet(CMU_Osc_TypeDef osc, uint32_t val); #if defined(_CMU_HFXOCTRL_PEAKDETSHUNTOPTMODE_MASK) || defined(_CMU_HFXOCTRL_PEAKDETMODE_MASK) bool CMU_OscillatorTuningWait(CMU_Osc_TypeDef osc, CMU_HFXOTuningMode_TypeDef mode); bool CMU_OscillatorTuningOptimize(CMU_Osc_TypeDef osc, CMU_HFXOTuningMode_TypeDef mode, bool wait); #endif #if (_SILICON_LABS_32B_SERIES < 2) bool CMU_PCNTClockExternalGet(unsigned int instance); void CMU_PCNTClockExternalSet(unsigned int instance, bool external); #endif #if defined(_CMU_USHFRCOCONF_BAND_MASK) CMU_USHFRCOBand_TypeDef CMU_USHFRCOBandGet(void); void CMU_USHFRCOBandSet(CMU_USHFRCOBand_TypeDef band); uint32_t CMU_USHFRCOFreqGet(void); #endif void CMU_UpdateWaitStates(uint32_t freq, int vscale); #if defined(CMU_CALCTRL_CONT) /***************************************************************************//** * @brief * Configure continuous calibration mode. * @param[in] enable * If true, enables continuous calibration, if false disables continuous * calibration. ******************************************************************************/ __STATIC_INLINE void CMU_CalibrateCont(bool enable) { BUS_RegBitWrite(&CMU->CALCTRL, _CMU_CALCTRL_CONT_SHIFT, (uint32_t)enable); } #endif /***************************************************************************//** * @brief * Start calibration. * @note * This call is usually invoked after @ref CMU_CalibrateConfig() and possibly * @ref CMU_CalibrateCont(). ******************************************************************************/ __STATIC_INLINE void CMU_CalibrateStart(void) { CMU->CMD = CMU_CMD_CALSTART; } #if defined(CMU_CMD_CALSTOP) /***************************************************************************//** * @brief * Stop the calibration counters. ******************************************************************************/ __STATIC_INLINE void CMU_CalibrateStop(void) { CMU->CMD = CMU_CMD_CALSTOP; } #endif /***************************************************************************//** * @brief * Convert dividend to logarithmic value. It only works for even * numbers equal to 2^n. * * @param[in] div * An unscaled dividend. * * @return * Logarithm of 2, as used by fixed prescalers. ******************************************************************************/ __STATIC_INLINE uint32_t CMU_DivToLog2(CMU_ClkDiv_TypeDef div) { uint32_t log2; /* Fixed 2^n prescalers take argument of 32768 or less. */ EFM_ASSERT((div > 0U) && (div <= 32768U)); /* Count leading zeroes and "reverse" result */ log2 = 31UL - __CLZ(div); return log2; } #if defined(CMU_OSCENCMD_DPLLEN) /***************************************************************************//** * @brief * Unlock DPLL. * @note * HFRCO is not turned off. ******************************************************************************/ __STATIC_INLINE void CMU_DPLLUnlock(void) { CMU->OSCENCMD = CMU_OSCENCMD_DPLLDIS; } #endif /***************************************************************************//** * @brief * Clear one or more pending CMU interrupts. * * @param[in] flags * CMU interrupt sources to clear. ******************************************************************************/ __STATIC_INLINE void CMU_IntClear(uint32_t flags) { CMU->IFC = flags; } /***************************************************************************//** * @brief * Disable one or more CMU interrupts. * * @param[in] flags * CMU interrupt sources to disable. ******************************************************************************/ __STATIC_INLINE void CMU_IntDisable(uint32_t flags) { CMU->IEN &= ~flags; } /***************************************************************************//** * @brief * Enable one or more CMU interrupts. * * @note * Depending on use case, a pending interrupt may already be set prior to * enabling the interrupt. Consider using @ref CMU_IntClear() prior to enabling * if the pending interrupt should be ignored. * * @param[in] flags * CMU interrupt sources to enable. ******************************************************************************/ __STATIC_INLINE void CMU_IntEnable(uint32_t flags) { CMU->IEN |= flags; } /***************************************************************************//** * @brief * Get pending CMU interrupts. * * @return * CMU interrupt sources pending. ******************************************************************************/ __STATIC_INLINE uint32_t CMU_IntGet(void) { return CMU->IF; } /***************************************************************************//** * @brief * Get enabled and pending CMU interrupt flags. * * @details * Useful for handling more interrupt sources in the same interrupt handler. * * @note * This function does not clear event bits. * * @return * Pending and enabled CMU interrupt sources. * The return value is the bitwise AND of * - the enabled interrupt sources in CMU_IEN and * - the pending interrupt flags CMU_IF ******************************************************************************/ __STATIC_INLINE uint32_t CMU_IntGetEnabled(void) { uint32_t ien; ien = CMU->IEN; return CMU->IF & ien; } /**************************************************************************//** * @brief * Set one or more pending CMU interrupts. * * @param[in] flags * CMU interrupt sources to set to pending. *****************************************************************************/ __STATIC_INLINE void CMU_IntSet(uint32_t flags) { CMU->IFS = flags; } /***************************************************************************//** * @brief * Lock the CMU to protect some of its registers against unintended * modification. * * @details * See the reference manual for CMU registers that will be * locked. * * @note * If locking the CMU registers, they must be unlocked prior to using any * CMU API functions modifying CMU registers protected by the lock. ******************************************************************************/ __STATIC_INLINE void CMU_Lock(void) { CMU->LOCK = CMU_LOCK_LOCKKEY_LOCK; } /***************************************************************************//** * @brief * Convert logarithm of 2 prescaler to division factor. * @deprecated * Deprecated and marked for removal in a later release. It will be replaced * by SL_Log2ToDiv. * @param[in] log2 * Logarithm of 2, as used by fixed prescalers. * * @return * Dividend. ******************************************************************************/ __STATIC_INLINE uint32_t CMU_Log2ToDiv(uint32_t log2) { return SL_Log2ToDiv(log2); } /***************************************************************************//** * @brief * Unlock the CMU so that writing to locked registers again is possible. ******************************************************************************/ __STATIC_INLINE void CMU_Unlock(void) { CMU->LOCK = CMU_LOCK_LOCKKEY_UNLOCK; } #if defined(_CMU_HFRCOCTRL_FREQRANGE_MASK) /***************************************************************************//** * @brief * Get the current HFRCO frequency. * * @deprecated * A deprecated function. New code should use @ref CMU_HFRCOBandGet(). * * @return * HFRCO frequency. ******************************************************************************/ __STATIC_INLINE CMU_HFRCOFreq_TypeDef CMU_HFRCOFreqGet(void) { return CMU_HFRCOBandGet(); } /***************************************************************************//** * @brief * Set HFRCO calibration for the selected target frequency. * * @deprecated * A deprecated function. New code should use @ref CMU_HFRCOBandSet(). * * @param[in] setFreq * HFRCO frequency to set. ******************************************************************************/ __STATIC_INLINE void CMU_HFRCOFreqSet(CMU_HFRCOFreq_TypeDef setFreq) { CMU_HFRCOBandSet(setFreq); } #endif #if defined(_CMU_AUXHFRCOCTRL_FREQRANGE_MASK) /***************************************************************************//** * @brief * Get the current AUXHFRCO frequency. * * @deprecated * A deprecated function. New code should use @ref CMU_AUXHFRCOBandGet(). * * @return * AUXHFRCO frequency. ******************************************************************************/ __STATIC_INLINE CMU_AUXHFRCOFreq_TypeDef CMU_AUXHFRCOFreqGet(void) { return CMU_AUXHFRCOBandGet(); } /***************************************************************************//** * @brief * Set AUXHFRCO calibration for the selected target frequency. * * @deprecated * A deprecated function. New code should use @ref CMU_AUXHFRCOBandSet(). * * @param[in] setFreq * AUXHFRCO frequency to set. ******************************************************************************/ __STATIC_INLINE void CMU_AUXHFRCOFreqSet(CMU_AUXHFRCOFreq_TypeDef setFreq) { CMU_AUXHFRCOBandSet(setFreq); } #endif #endif // defined(_SILICON_LABS_32B_SERIES_2) #if !defined(_SILICON_LABS_32B_SERIES_0) /***************************************************************************//** * @brief * Convert prescaler dividend to a logarithmic value. It only works for even * numbers equal to 2^n. * * @param[in] presc * An unscaled dividend (dividend = presc + 1). * * @return * Logarithm of 2, as used by fixed 2^n prescalers. ******************************************************************************/ __STATIC_INLINE uint32_t CMU_PrescToLog2(uint32_t presc) { uint32_t log2; /* Integer prescalers take argument less than 32768. */ EFM_ASSERT(presc < 32768U); /* Count leading zeroes and "reverse" result. */ log2 = 31UL - __CLZ(presc + (uint32_t) 1); /* Check that prescaler is a 2^n number. */ EFM_ASSERT(presc == (SL_Log2ToDiv(log2) - 1U)); return log2; } #endif // !defined(_SILICON_LABS_32B_SERIES_0) /** @} (end addtogroup CMU) */ /** @} (end addtogroup emlib) */ #ifdef __cplusplus } #endif #endif /* defined(CMU_PRESENT) */ #endif /* EM_CMU_H */
<gh_stars>0 double relax(double *y,double *f,double *a_x,double *a_y,int mesh_tracker) { double error=0.0; //printf("At level %d\n",mesh_tracker); //============================================================================// //solving the equation for the even update only(see "even_red_black_solver.c") even_rb_solve(y,f,a_x,a_y,&error,mesh_tracker); //===========================================================================// //============================================================================// //solving the equation for the odd update only(see "odd_red_black_solver.c") odd_rb_solve(y,f,a_x,a_y,&error,mesh_tracker); //===========================================================================// //===========================================================================// error=sqrt(error*d_sp[mesh_tracker].x*d_sp[mesh_tracker].y); //===========================================================================// return error; }
<gh_stars>1000+ #ifndef DLGELEVIMPORT_H #define DLGELEVIMPORT_H #include "elv_io.h" #include <QDialog> namespace Ui { class DlgElevImport; } class tileedit; class ElevTileBlock; class DlgElevImport : public QDialog { Q_OBJECT public: DlgElevImport(tileedit *parent); public slots: void onOpenFileDialog(); void onOpenMetaFileDialog(); void onMetaFileChanged(const QString&); void onSelectAllTiles(); void onSelectTileRange(); void onPropagateChanges(int); void accept(); protected: bool scanMetaFile(const char *fname, ElevPatchMetaInfo &meta); private: Ui::DlgElevImport *ui; tileedit *m_tileedit; bool m_pathEdited, m_metaEdited; bool m_haveMeta; int m_propagationLevel; ElevPatchMetaInfo m_metaInfo; }; #endif // !DLGELEVIMPORT_H
//============================================================================== // Copyright (c) 2017-2019 Advanced Micro Devices, Inc. All rights reserved. /// \author AMD Developer Tools Team /// \file /// \brief THIS CODE WAS HANDGENERATED //============================================================================== #ifndef _ROCM_SMI_MODULE_DECLS_H_ #define _ROCM_SMI_MODULE_DECLS_H_ #include <rocm_smi.h> typedef decltype(rsmi_init)* rsmi_init_fn_t; typedef decltype(rsmi_shut_down)* rsmi_shut_down_fn_t; typedef decltype(rsmi_num_monitor_devices)* rsmi_num_monitor_devices_fn_t; typedef decltype(rsmi_dev_id_get)* rsmi_dev_id_get_fn_t; typedef decltype(rsmi_dev_vendor_id_get)* rsmi_dev_vendor_id_get_fn_t; typedef decltype(rsmi_dev_name_get)* rsmi_dev_name_get_fn_t; typedef decltype(rsmi_dev_vendor_name_get)* rsmi_dev_vendor_name_get_fn_t; typedef decltype(rsmi_dev_subsystem_id_get)* rsmi_dev_subsystem_id_get_fn_t; typedef decltype(rsmi_dev_subsystem_name_get)* rsmi_dev_subsystem_name_get_fn_t; typedef decltype(rsmi_dev_subsystem_vendor_id_get)* rsmi_dev_subsystem_vendor_id_get_fn_t; typedef decltype(rsmi_dev_pci_bandwidth_get)* rsmi_dev_pci_bandwidth_get_fn_t; typedef decltype(rsmi_dev_pci_id_get)* rsmi_dev_pci_id_get_fn_t; typedef decltype(rsmi_dev_pci_throughput_get)* rsmi_dev_pci_throughput_get_fn_t; typedef decltype(rsmi_dev_pci_bandwidth_set)* rsmi_dev_pci_bandwidth_set_fn_t; typedef decltype(rsmi_dev_power_ave_get)* rsmi_dev_power_ave_get_fn_t; typedef decltype(rsmi_dev_power_cap_get)* rsmi_dev_power_cap_get_fn_t; typedef decltype(rsmi_dev_power_cap_range_get)* rsmi_dev_power_cap_range_get_fn_t; typedef decltype(rsmi_dev_power_cap_set)* rsmi_dev_power_cap_set_fn_t; typedef decltype(rsmi_dev_power_profile_set)* rsmi_dev_power_profile_set_fn_t; typedef decltype(rsmi_dev_memory_total_get)* rsmi_dev_memory_total_get_fn_t; typedef decltype(rsmi_dev_memory_usage_get)* rsmi_dev_memory_usage_get_fn_t; typedef decltype(rsmi_dev_fan_rpms_get)* rsmi_dev_fan_rpms_get_fn_t; typedef decltype(rsmi_dev_fan_speed_get)* rsmi_dev_fan_speed_get_fn_t; typedef decltype(rsmi_dev_fan_speed_max_get)* rsmi_dev_fan_speed_max_get_fn_t; typedef decltype(rsmi_dev_temp_metric_get)* rsmi_dev_temp_metric_get_fn_t; typedef decltype(rsmi_dev_fan_reset)* rsmi_dev_fan_reset_fn_t; typedef decltype(rsmi_dev_fan_speed_set)* rsmi_dev_fan_speed_set_fn_t; typedef decltype(rsmi_dev_busy_percent_get)* rsmi_dev_busy_percent_get_fn_t; typedef decltype(rsmi_dev_perf_level_get)* rsmi_dev_perf_level_get_fn_t; typedef decltype(rsmi_dev_overdrive_level_get)* rsmi_dev_overdrive_level_get_fn_t; typedef decltype(rsmi_dev_gpu_clk_freq_get)* rsmi_dev_gpu_clk_freq_get_fn_t; typedef decltype(rsmi_dev_od_volt_info_get)* rsmi_dev_od_volt_info_get_fn_t; typedef decltype(rsmi_dev_od_volt_curve_regions_get)* rsmi_dev_od_volt_curve_regions_get_fn_t; typedef decltype(rsmi_dev_power_profile_presets_get)* rsmi_dev_power_profile_presets_get_fn_t; typedef decltype(rsmi_dev_perf_level_set)* rsmi_dev_perf_level_set_fn_t; typedef decltype(rsmi_dev_overdrive_level_set)* rsmi_dev_overdrive_level_set_fn_t; typedef decltype(rsmi_dev_gpu_clk_freq_set)* rsmi_dev_gpu_clk_freq_set_fn_t; typedef decltype(rsmi_dev_od_freq_range_set)* rsmi_dev_od_freq_range_set_fn_t; typedef decltype(rsmi_version_get)* rsmi_version_get_fn_t; typedef decltype(rsmi_dev_vbios_version_get)* rsmi_dev_vbios_version_get_fn_t; typedef decltype(rsmi_dev_ecc_count_get)* rsmi_dev_ecc_count_get_fn_t; typedef decltype(rsmi_dev_ecc_enabled_get)* rsmi_dev_ecc_enabled_get_fn_t; typedef decltype(rsmi_dev_ecc_status_get)* rsmi_dev_ecc_status_get_fn_t; typedef decltype(rsmi_status_string)* rsmi_status_string_fn_t; #endif
<reponame>Big-Theta/DynamicHistogram<filename>DynamicHistogram.h // MIT License // // Copyright (c) 2021 <NAME> // // 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. #pragma once #include <google/protobuf/util/time_util.h> #include <algorithm> #include <cstddef> #include <cstdint> #include <map> #include <vector> #include "DensityMapBase.h" #include "DensityMapDescription.h" #include "DensityMapServer.h" #include "DynamicDensity.pb.h" #include "LocklessInsertionBuffer.h" namespace dyden { using ::dynamic_density::DensityMap; class Bucket { public: // Represents data in the half-open interval [min, max). Bucket(double min, double max, double count) : min_(min), max_(max), count_(count) {} double diameter() const { return max() - min(); } double min() const { return min_; } double max() const { return max_; } double count() const { return count_; } private: double min_; double max_; double count_; }; class DynamicHistogramOpts { public: DynamicHistogramOpts() : num_buckets_(100), decay_rate_(0.0), refresh_interval_(512), title_("title"), label_("label"), register_with_server_(false) {} DynamicHistogramOpts& setNumBuckets(size_t num_buckets) { num_buckets_ = num_buckets; return *this; } size_t numBuckets() const { return num_buckets_; } DynamicHistogramOpts& setDecayRate(double decay_rate) { decay_rate_ = decay_rate; return *this; } double decayRate() const { return decay_rate_; } DynamicHistogramOpts& setRefreshInterval(size_t refresh_interval) { refresh_interval_ = refresh_interval; return *this; } size_t refreshInterval() const { return refresh_interval_; } DynamicHistogramOpts& setTitle(std::string title) { title_ = title; return *this; } std::string title() const { return title_; } DynamicHistogramOpts& setLabel(std::string label) { label_ = label; return *this; } std::string label() const { return label_; } DynamicHistogramOpts& setRegisterWithServer(bool register_with_server) { register_with_server_ = register_with_server; return *this; } bool registerWithServer() const { return register_with_server_; } private: size_t num_buckets_; double decay_rate_; size_t refresh_interval_; std::string title_; std::string label_; bool register_with_server_; }; class DynamicHistogram : public DensityMapBase { public: DynamicHistogram(const DynamicHistogramOpts& opts); virtual ~DynamicHistogram() {} void addValue(double val); size_t getNumBuckets() const { return counts_.size(); } Bucket getBucketByIndex(size_t bx); double computeTotalCount(); double getMin(); double getMax(); double getMean(); // quantile is in [0, 1] double getQuantileEstimate(double quantile); double getQuantileOfValue(double value); std::string debugString(); std::string json(); DensityMap asProto() override; void toProto(DensityMap* proto) override; void registerWithServer() override; protected: uint64_t generation_; uint64_t refresh_generation_; double total_count_; double split_threshold_; LocklessInsertionBuffer<double> insertion_buffer_; // ubounds_ records the upper bound of a bucket. There isn't an upper bound // for the last bucket, so the length of counts_ will generally be one greater // than the length of counts_. std::vector<double> ubounds_; std::vector<double> counts_; std::vector<uint64_t> bucket_generation_; double splitThreshold() const; double decayRate() const; double getMinNoLock() const; double getMaxNoLock() const; double getUpperBound(int i) const; void flush(LockedFlushIterator<double>* flush_it); void flushValue(double val); void decay(size_t bx); void refresh(); // Adjust bounds and add. // Returns: // The index of the bucket that the new value landed in. size_t insertValue(double val); void split(size_t bx); void merge(); }; } // namespace dyden
<filename>standalone/pruntime/rizin/librz/util/x509.h // SPDX-FileCopyrightText: 2017-2018 deroad <<EMAIL>> // SPDX-License-Identifier: LGPL-3.0-only #ifndef RZ_X509_INTERNAL_H #define RZ_X509_INTERNAL_H RZ_API bool rz_x509_parse_algorithmidentifier(RX509AlgorithmIdentifier *ai, RASN1Object *object); RZ_API void rz_x509_free_algorithmidentifier(RX509AlgorithmIdentifier *ai); RZ_API bool rz_x509_parse_subjectpublickeyinfo(RX509SubjectPublicKeyInfo *spki, RASN1Object *object); RZ_API void rz_x509_free_subjectpublickeyinfo(RX509SubjectPublicKeyInfo *spki); RZ_API bool rz_x509_parse_name(RX509Name *name, RASN1Object *object); RZ_API void rz_x509_free_name(RX509Name *name); RZ_API bool rz_x509_parse_extension(RX509Extension *ext, RASN1Object *object); RZ_API void rz_x509_free_extension(RX509Extension *ex); RZ_API bool rz_x509_parse_extensions(RX509Extensions *ext, RASN1Object *object); RZ_API void rz_x509_free_extensions(RX509Extensions *ex); RZ_API bool rz_x509_parse_tbscertificate(RX509TBSCertificate *tbsc, RASN1Object *object); RZ_API void rz_x509_free_tbscertificate(RX509TBSCertificate *tbsc); RZ_API RX509CRLEntry *rz_x509_parse_crlentry(RASN1Object *object); RZ_API void rz_x509_name_dump(RX509Name *name, const char *pad, RzStrBuf *sb); #endif /* RZ_X509_INTERNAL_H */
<reponame>npocmaka/Windows-Server-2003 /* * Copyright (c) 1989,90 Microsoft Corporation */ /* * --------------------------------------------------------------------- * FILE: GEIerr.h * * HISTORY: * 09/13/90 byou created. * 01/07/91 billlwo rename GEIseterror to GESseterror * --------------------------------------------------------------------- */ #ifndef _GEIERR_H_ #define _GEIERR_H_ #ifdef UNIX #define volatile #endif /* UNIX */ /* * --- * Error Code List * --- */ #define EZERO 0 #define EPERM 1 #define ENOENT 2 #define ESRCH 3 #define EINTR 4 #define EIO 5 #define ENXIO 6 #define E2BIG 7 #define ENOEXEC 8 #define EBADF 9 #define ECHILD 10 #define EAGAIN 11 #define ENOMEM 12 #define EACCES 13 #define EFAULT 14 #define ENOTBLK 15 #define EBUSY 16 #define EEXIST 17 #define EXDEV 18 #define ENODEV 19 #define ENOTDIR 20 #define EISDIR 21 #define EINVAL 22 #define ENFILE 23 #define EMFILE 24 #define ENOTTY 25 #define ETXTBSY 26 #define EFBIG 27 #define ENOSPC 28 #define ESPIPE 29 #define EROFS 30 #define EMLINK 31 #define EPIPE 32 #define EDOM 33 #define ERANGE 34 #define EUCLEAN 35 #define EDEADLOCK 36 #define ENAMETOOLONG 63 #define ETIME 73 #define ENOSR 74 #define ENOSYS 90 /* * --- * Interface Routines * --- */ volatile extern int GEIerrno; #define GEIerror() ( GEIerrno ) #define GESseterror(e) ( GEIerrno = (e) ) #define GEIclearerr() (void)( GEIerrno = EZERO ) #endif /* !_GEIERR_H_ */ 
#include <stdio.h> void swap(char *,char *); void rev(char *); main() { char *name="ravindra"; char x='a',y='b'; swap(name+1,name+3); printf("name is %s\n",name); fflush(stdout); exit(1); rev(name); name[7]='\0'; rev(name); printf("name is %s\n",name); } void swap(char *x,char *y) { char tmp; tmp = *x; *x = *y; *y = tmp; return; } void rev(char *s) { int i,n; printf("inside rev\n"); n=strlen(s); for(i=0;i< n/2 ; i++) { swap(&s[i],&s[n-1-i]); } return; }
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <assert.h> #include <zlib.h> #if defined(MSDOS) || defined(OS2) || defined(WIN32) || defined(__CYGWIN__) #include <fcntl.h> #include <io.h> #define SET_BINARY_MODE(file) setmode(fileno(file), O_BINARY) #else #define SET_BINARY_MODE(file) #endif #define CHUNK 256 * 1024 /* * Compress from src to dest until EOF is encountered in src. * Returns zlib-defined values for the same reasons defined in * the official zlib usage guide (https://zlib.net/zlib_how.html) */ int def(FILE *src, FILE *dest, int level); /* * Decompresses from src to dest until EOF is encountered in src. * As with def(), returns the zlib-defined values for the reasons * defined in https://zlib.net/zlib_how.html. */ int inf(FILE *src, FILE *dest); /* Prints an error message based on the return value passed */ void get_zlib_err(int ret, char *prog_name); int main(int argc, char *argv[]) { int ret, i, j; /* Prevent Microsoft's dumb conventions from messing up the data */ SET_BINARY_MODE(stdin); SET_BINARY_MODE(stdout); /* Handle commandline stuff */ if (argc == 2 && strcmp(argv[1], "-c") == 0) {/* Compress stdin to stdout */ ret = def(stdin, stdout, Z_DEFAULT_COMPRESSION); if (ret != Z_OK) get_zlib_err(ret, argv[0]); return ret; } else if (argc == 2 && strcmp(argv[1], "-d") == 0) { /* Decompress stdin to stdout */ ret = inf(stdin, stdout); if (ret != Z_OK) get_zlib_err(ret, argv[0]); return ret; } else { /* Print usage */ /* Print an arrow with '[DE]COMPRESSION' over it pointing to the '[-c|-d]' part of the usage message */ for (i = 0; i < (strlen(argv[0]) + strlen("Usage:") + 5) - (strlen("[DE]COMPRESSION") / 2); i++) printf(" "); printf("[DE]COMPRESSION\n"); for (i = 0; i < 3; i++) { for (j = 0; j < (strlen(argv[0]) + strlen("Usage:") + 5); j++) printf(" "); if (i <= 1) printf("|\n"); else printf("V\n\n"); } printf("Usage: %s [-c|-d] < source > dest\n", argv[0]); return 1; } return 0; } int def(FILE *src, FILE *dest, int level) { int ret, flush; unsigned int have; z_stream stream; unsigned char in[CHUNK]; unsigned char out[CHUNK]; /* Set up the zlib state */ stream.zalloc = Z_NULL; stream.zfree = Z_NULL; stream.opaque = Z_NULL; /* Initialize and return an error code in the event that initialization fails */ ret = deflateInit(&stream, level); if (ret != Z_OK) return ret; /* Compress to the end of the file */ do { /* Read the current chunk of the file */ stream.avail_in = fread(in, 1, CHUNK, src); /* Return cleanly in the event of an error */ if (ferror(src)) { (void)deflateEnd(&stream); return Z_ERRNO; } /* Tell zlib whether this is the end of the input */ flush = (feof(src)) ? Z_FINISH : Z_NO_FLUSH; /* Hand the buffer to zlib now that it's ready */ stream.next_in = in; /* * Call deflate() on the input buffer until it stops producing output, * finish if all of the source has been read in */ do { /* Tell zlib where to store its output and how much space is there */ stream.avail_out = CHUNK; stream.next_out = out; ret = deflate(&stream, flush); /* Actually deflate the data */ assert(ret != Z_STREAM_ERROR); /* Make sure the zlib state is intact */ have = CHUNK - stream.avail_out; /* Calculate how much data we have */ /* Write the data, and avoid a memory leak and return if that fails */ if (fwrite(out, 1, have, dest) != have || ferror(dest)) { (void)deflateEnd(&stream); return Z_ERRNO; } } while (stream.avail_out == 0); assert(stream.avail_in == 0); /* All input will be used */ } while (flush != Z_FINISH); /* Finish when all data is processed */ assert(ret == Z_STREAM_END); /* Stream will be complete */ /* Prevent a (as put in the official zlib guide) memory hemorrhage, then clean up */ (void)deflateEnd(&stream); return Z_OK; } int inf(FILE *src, FILE *dest) { int ret; unsigned int have; z_stream stream; unsigned char in[CHUNK]; unsigned char out[CHUNK]; /* Set up the zlib state */ stream.zalloc = Z_NULL; stream.zfree = Z_NULL; stream.opaque = Z_NULL; stream.avail_in = 0; stream.next_in = Z_NULL; ret = inflateInit(&stream); if (ret != Z_OK) return ret; /* Decompress until the stream ends or EOF */ do { /* Read the current chunk of the file */ stream.avail_in = fread(in, 1, CHUNK, src); /* Avoid a memory leak and return in the event of an error */ if (ferror(src)) { (void)inflateEnd(&stream); return Z_ERRNO; } /* Break if no input is available */ if (stream.avail_in == 0) break; /* Hand zlib the buffer now that it's ready */ stream.next_in = in; /* Run inflate() on the input until the output buffer is only partially full */ do { /* Tell zlib where to store its output and how much space is there */ stream.avail_out = CHUNK; stream.next_out = out; ret = inflate(&stream, Z_NO_FLUSH); /* Actually inflate the data */ assert(ret != Z_STREAM_ERROR); /* Make sure the zlib state is intact */ /* Return cleanly if there's an error */ switch (ret) { case Z_NEED_DICT: ret = Z_DATA_ERROR; /* If a dictionary is needed, say the data is invalid */ case Z_DATA_ERROR: case Z_MEM_ERROR: (void)inflateEnd(&stream); } /* Calculate the amount of data we have */ have = CHUNK - stream.avail_out; /* Write the data and clean up if there's an error */ if (fwrite(out, 1, have, dest) != have || ferror(dest)) { (void)inflateEnd(&stream); return Z_ERRNO; } /* Finish when the out buffer is only partially full */ } while (stream.avail_out == 0); /* Finish when inflate() says it's done */ } while (ret != Z_STREAM_END); /* Clean up and return */ (void)inflateEnd(&stream); return (ret == Z_STREAM_END) ? Z_OK : Z_DATA_ERROR; } void get_zlib_err(int ret, char *prog_name) { /* Print the name of the program for clarity */ fprintf(stderr, "%s: ", prog_name); /* Now print a message to indicate what kind of error occured */ switch (ret) { case Z_ERRNO: fprintf(stderr, "I/O error"); break; case Z_STREAM_ERROR: fprintf(stderr, "zlib state invalid, likely caused by" " an invalid decompression level (should be -1-9)"); break; case Z_DATA_ERROR: fprintf(stderr, "invalid or incomplete deflate data"); break; case Z_MEM_ERROR: fprintf(stderr, "out of memory"); break; case Z_VERSION_ERROR: fprintf(stderr, "zlib version mismatch"); } /* Print a newline once instead of typing it at the end of each message */ fprintf(stderr, "\n"); }
// Copyright 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CC_RESOURCES_PRIORITIZED_RESOURCE_H_ #define CC_RESOURCES_PRIORITIZED_RESOURCE_H_ #include "base/basictypes.h" #include "base/logging.h" #include "base/memory/scoped_ptr.h" #include "cc/base/cc_export.h" #include "cc/resources/priority_calculator.h" #include "cc/resources/resource.h" #include "cc/resources/resource_provider.h" #include "ui/gfx/rect.h" #include "ui/gfx/size.h" #include "ui/gfx/vector2d.h" namespace cc { class PrioritizedResourceManager; class Proxy; class CC_EXPORT PrioritizedResource { public: static scoped_ptr<PrioritizedResource> Create( PrioritizedResourceManager* manager, gfx::Size size, ResourceFormat format) { return make_scoped_ptr(new PrioritizedResource(manager, size, format)); } static scoped_ptr<PrioritizedResource> Create( PrioritizedResourceManager* manager) { return make_scoped_ptr( new PrioritizedResource(manager, gfx::Size(), RGBA_8888)); } ~PrioritizedResource(); // Texture properties. Changing these causes the backing texture to be lost. // Setting these to the same value is a no-op. void SetTextureManager(PrioritizedResourceManager* manager); PrioritizedResourceManager* resource_manager() { return manager_; } void SetDimensions(gfx::Size size, ResourceFormat format); ResourceFormat format() const { return format_; } gfx::Size size() const { return size_; } size_t bytes() const { return bytes_; } bool contents_swizzled() const { return contents_swizzled_; } // Set priority for the requested texture. void set_request_priority(int priority) { priority_ = priority; } int request_priority() const { return priority_; } // After PrioritizedResource::PrioritizeTextures() is called, this returns // if the the request succeeded and this texture can be acquired for use. bool can_acquire_backing_texture() const { return is_above_priority_cutoff_; } // This returns whether we still have a backing texture. This can continue // to be true even after CanAcquireBackingTexture() becomes false. In this // case the texture can be used but shouldn't be updated since it will get // taken away "soon". bool have_backing_texture() const { return !!backing(); } bool BackingResourceWasEvicted() const; // If CanAcquireBackingTexture() is true AcquireBackingTexture() will acquire // a backing texture for use. Call this whenever the texture is actually // needed. void AcquireBackingTexture(ResourceProvider* resource_provider); // TODO(epenner): Request late is really a hack for when we are totally out of // memory (all textures are visible) but we can still squeeze into the limit // by not painting occluded textures. In this case the manager refuses all // visible textures and RequestLate() will enable CanAcquireBackingTexture() // on a call-order basis. We might want to just remove this in the future // (carefully) and just make sure we don't regress OOMs situations. bool RequestLate(); // Update pixels of backing resource from image. This functions will aquire // the backing if needed. void SetPixels(ResourceProvider* resource_provider, const uint8_t* image, gfx::Rect image_rect, gfx::Rect source_rect, gfx::Vector2d dest_offset); ResourceProvider::ResourceId resource_id() const { return backing_ ? backing_->id() : 0; } // Self-managed textures are accounted for when prioritizing other textures, // but they are not allocated/recycled/deleted, so this needs to be done // externally. CanAcquireBackingTexture() indicates if the texture would have // been allowed given its priority. void set_is_self_managed(bool is_self_managed) { is_self_managed_ = is_self_managed; } bool is_self_managed() { return is_self_managed_; } void SetToSelfManagedMemoryPlaceholder(size_t bytes); void ReturnBackingTexture(); private: friend class PrioritizedResourceManager; friend class PrioritizedResourceTest; class Backing : public Resource { public: Backing(unsigned id, ResourceProvider* resource_provider, gfx::Size size, ResourceFormat format); ~Backing(); void UpdatePriority(); void UpdateState(ResourceProvider* resource_provider); PrioritizedResource* owner() { return owner_; } bool CanBeRecycled() const; int request_priority_at_last_priority_update() const { return priority_at_last_priority_update_; } bool was_above_priority_cutoff_at_last_priority_update() const { return was_above_priority_cutoff_at_last_priority_update_; } bool in_drawing_impl_tree() const { return in_drawing_impl_tree_; } bool in_parent_compositor() const { return in_parent_compositor_; } void DeleteResource(ResourceProvider* resource_provider); bool ResourceHasBeenDeleted() const; private: const Proxy* proxy() const; friend class PrioritizedResource; friend class PrioritizedResourceManager; PrioritizedResource* owner_; int priority_at_last_priority_update_; bool was_above_priority_cutoff_at_last_priority_update_; // Set if this is currently-drawing impl tree. bool in_drawing_impl_tree_; // Set if this is in the parent compositor. bool in_parent_compositor_; bool resource_has_been_deleted_; #ifndef NDEBUG ResourceProvider* resource_provider_; #endif DISALLOW_COPY_AND_ASSIGN(Backing); }; PrioritizedResource(PrioritizedResourceManager* resource_manager, gfx::Size size, ResourceFormat format); bool is_above_priority_cutoff() { return is_above_priority_cutoff_; } void set_above_priority_cutoff(bool is_above_priority_cutoff) { is_above_priority_cutoff_ = is_above_priority_cutoff; } void set_manager_internal(PrioritizedResourceManager* manager) { manager_ = manager; } Backing* backing() const { return backing_; } void Link(Backing* backing); void Unlink(); gfx::Size size_; ResourceFormat format_; size_t bytes_; bool contents_swizzled_; int priority_; bool is_above_priority_cutoff_; bool is_self_managed_; Backing* backing_; PrioritizedResourceManager* manager_; DISALLOW_COPY_AND_ASSIGN(PrioritizedResource); }; } // namespace cc #endif // CC_RESOURCES_PRIORITIZED_RESOURCE_H_
#include <stdio.h> #define win(COMP,WIN) ((long long)(COMP) < (long long)(((M + (WIN)) * (long long)100) / (long long)(N + (WIN)))) #define MAX ((long long)2000000000) long long N, M; int main(void) { int tc, T; long long low, high, middle; long long comp, answer; // freopen("sample_input.txt", "r", stdin); setbuf(stdout, NULL); scanf("%d", &T); for (tc = 0; tc < T; ++tc) { scanf("%lld %lld\n", &N, &M); if (N != M) { comp = (long long)(M * (long long)100) / (long long)N; for (low = 1, high = MAX; low < high;) { middle = (high + low) / 2; if (middle == low) { if (win(comp, low)) answer = low; else if (win(comp, high)) answer = high; else answer = -1; break; } else if (win(comp, low)) { answer = low; break; } else if (win(comp, middle)) { high = middle; } else if (win(comp, high)) { low = middle; } else { answer = -1; break; } } printf("%lld\n", answer); } else { printf("-1\n"); } } return 0; }
// ***************************************************************************************** // // File description: // // Author: <NAME> // Purpose: Common declarations for a generic buffer type // // ***************************************************************************************** #ifndef OSAPI_COMMON_TYPES_BUFFER_H_ #define OSAPI_COMMON_TYPES_BUFFER_H_ // ***************************************************************************************** // // Section: Import headers // // ***************************************************************************************** // Import OSAPI headers #include "general/general_types.h" // Include own headers #include "common/types/common_types_memory.h" // ***************************************************************************************** // // Section: Type definitions // // ***************************************************************************************** /// Structure supporting a self describing memory/buffer /// The reasoning is that naked memory handling is more error prone and encapsulation of /// memory supported by a "buffer" type can provided more robust code. struct osapi_buffer_S { t_size size; ///< Current capacity usage, i.e. how many bytes are you using of the allocated capacity t_memory mem; ///< Allocated memory }; typedef struct osapi_buffer_S t_buffer; #endif /* OSAPI_COMMON_TYPES_BUFFER_H_ */
<reponame>umogSlayer/portable_concurrency #pragma once #if defined(_MSC_VER) #define PC_NODISCARD _Check_return_ #elif defined(__has_cpp_attribute) #if __has_cpp_attribute(gnu::warn_unused_result) #define PC_NODISCARD [[gnu::warn_unused_result]] #endif #endif #if !defined(PC_NODISCARD) #define PC_NODISCARD #endif
/* * Copyright (c) 2019, NVIDIA CORPORATION. All rights reserved. * * SPDX-License-Identifier: BSD-3-Clause */ #include <arch.h> #include <arch_helpers.h> #include <assert.h> #include <common/bl_common.h> #include <lib/el3_runtime/context_mgmt.h> #include <common/debug.h> #include <errno.h> #include <mce.h> #include <memctrl.h> #include <common/runtime_svc.h> #include <tegra_private.h> #include <tegra_platform.h> #include <stdbool.h> extern bool tegra_fake_system_suspend; /******************************************************************************* * Tegra194 SiP SMCs ******************************************************************************/ #define TEGRA_SIP_ENABLE_FAKE_SYSTEM_SUSPEND 0xC2FFFE03U /******************************************************************************* * This function is responsible for handling all T194 SiP calls ******************************************************************************/ int32_t plat_sip_handler(uint32_t smc_fid, uint64_t x1, uint64_t x2, uint64_t x3, uint64_t x4, const void *cookie, void *handle, uint64_t flags) { int32_t ret = -ENOTSUP; (void)x1; (void)x4; (void)cookie; (void)flags; if (smc_fid == TEGRA_SIP_ENABLE_FAKE_SYSTEM_SUSPEND) { /* * System suspend mode is set if the platform ATF is * running on VDK and there is a debug SIP call. This mode * ensures that the debug path is exercised, instead of * regular code path to suit the pre-silicon platform needs. * This includes replacing the call to WFI, with calls to * system suspend exit procedures. */ if (tegra_platform_is_virt_dev_kit()) { tegra_fake_system_suspend = true; ret = 0; } } return ret; }
#pragma once #include <cstdint> #include <functional> #include "../../temple_enums.h" enum class ObjectFieldType : uint32_t { None = 0, BeginSection = 1, EndSection = 2, Int32 = 3, Int64 = 4, AbilityArray = 5, UnkArray = 6, // Not used by anything in ToEE Int32Array = 7, Int64Array = 8, ScriptArray = 9, Unk2Array = 10, // Not used by anything in ToEE String = 11, Obj = 12, ObjArray = 13, SpellArray = 14, Float32 = 15 }; struct ObjectFieldDef { // Name of this field const char* name = nullptr; // The index of this field in the property // collection of prototype objects int protoPropIdx = -1; // The idx of this array field (starting at 0 for the first array) or -1 if this is // not an array field int arrayIdx = -1; // The idx of the bitmap 32-bit block that contains the bit indicating whether // an object instance has this field or not int bitmapBlockIdx = -1; // The bit within the bitmap block identified by bitmapBlockIdx int bitmapBitIdx = 0; // A bitmask to easily test for the bit identified by bitmapBitIdx uint32_t bitmapMask = 0; // Number of entries in the properties collection for this field size_t storedInPropColl = 0; ObjectFieldType type = ObjectFieldType::None; }; class ObjectFields { public: ObjectFields(); const ObjectFieldDef &GetFieldDef(obj_f field) const { return mFieldDefs[field]; } const std::array<ObjectFieldDef, 430> &GetFieldDefs() const { return mFieldDefs; } bool DoesTypeSupportField(ObjectType type, obj_f field); const char *GetFieldName(obj_f field) const; // Gets the type of the given field ObjectFieldType GetType(obj_f field) const { return mFieldDefs[field].type; } bool IsTransient(obj_f field) const { return field > obj_f_transient_begin && field < obj_f_transient_end; } /** * Returns the number of bitmap blocks needed for the given type. */ size_t GetBitmapBlockCount(ObjectType type) const { return mBitmapBlocksPerType[type]; } /** * Returns the number of properties supported by the given type. */ size_t GetSupportedFieldCount(ObjectType type) const { return mPropCollSizePerType[type]; } bool IterateTypeFields(ObjectType type, std::function<bool(obj_f)> callback); bool IsArrayType(ObjectFieldType type); private: std::array<ObjectFieldDef, 430> mFieldDefs; // The number of bitmap blocks needed to be allocated by type std::array<size_t, ObjectTypeCount> mBitmapBlocksPerType; // The number of possible property storage locations per type std::array<size_t, ObjectTypeCount> mPropCollSizePerType; const char *GetTypeName(ObjectFieldType type); static size_t GetPropCollSize(obj_f field, ObjectFieldType type); bool IterateFieldRange(obj_f rangeStart, obj_f rangeEnd, std::function<bool(obj_f)> callback); }; extern ObjectFields objectFields;
<reponame>TheSledgeHammer/2.11BSD<gh_stars>1-10 /* Common hooks for DEC Alpha. Copyright (C) 1992-2020 Free Software Foundation, Inc. This file is part of GCC. GCC 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, or (at your option) any later version. GCC 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 GCC; see the file COPYING3. If not see <http://www.gnu.org/licenses/>. */ #include "config.h" #include "system.h" #include "coretypes.h" #include "diagnostic-core.h" #include "tm.h" #include "common/common-target.h" #include "common/common-target-def.h" #include "opts.h" #include "flags.h" /* Implement TARGET_OPTION_OPTIMIZATION_TABLE. */ static const struct default_options alpha_option_optimization_table[] = { /* Enable redundant extension instructions removal at -O2 and higher. */ { OPT_LEVELS_2_PLUS, OPT_free, NULL, 1 }, { OPT_LEVELS_NONE, 0, NULL, 0 } }; /* Implement TARGET_OPTION_INIT_STRUCT. */ static void alpha_option_init_struct (struct gcc_options *opts ATTRIBUTE_UNUSED) { #if TARGET_ABI_OPEN_VMS /* Enable section anchors by default. */ opts->x_flag_section_anchors = 1; #endif } /* Implement TARGET_HANDLE_OPTION. */ static bool alpha_handle_option (struct gcc_options *opts, struct gcc_options *opts_set ATTRIBUTE_UNUSED, const struct cl_decoded_option *decoded, location_t loc) { size_t code = decoded->opt_index; const char *arg = decoded->arg; int value = decoded->value; switch (code) { case OPT_mfp_regs: if (value == 0) opts->x_target_flags |= MASK_SOFT_FP; break; case OPT_mieee: case OPT_mieee_with_inexact: opts->x_target_flags |= MASK_IEEE_CONFORMANT; break; case OPT_mtls_size_: if (value != 16 && value != 32 && value != 64) error_at (loc, "bad value %qs for %<-mtls-size%> switch", arg); break; } return true; } #undef TARGET_DEFAULT_TARGET_FLAGS #define TARGET_DEFAULT_TARGET_FLAGS \ (TARGET_DEFAULT | TARGET_CPU_DEFAULT | TARGET_DEFAULT_EXPLICIT_RELOCS) #undef TARGET_HANDLE_OPTION #define TARGET_HANDLE_OPTION alpha_handle_option #undef TARGET_OPTION_INIT_STRUCT #define TARGET_OPTION_INIT_STRUCT alpha_option_init_struct #undef TARGET_OPTION_OPTIMIZATION_TABLE #define TARGET_OPTION_OPTIMIZATION_TABLE alpha_option_optimization_table struct gcc_targetm_common targetm_common = TARGETM_COMMON_INITIALIZER;
<filename>src/engine/maths/Matrix4.h #ifndef MATHS_MATRIX4_H #define MATHS_MATRIX4_H #include <memory> #include "Vector4.h" #include <array> #include "Quaternion.h" using std::array; // Col major order 4*4 matrix class Matrix4 { public: array<float, 16> mat; Matrix4() { *this = Matrix4::identity; } Matrix4(const array<float, 16>& that) { for(int n = 0; n < 16; ++n) { mat[n] = that[n]; } } const float* getAsFloatPtr() const { return reinterpret_cast<const float*>(&mat[0]); } inline float& operator()(const int i, const int j) { return mat[i * 4 + j]; } inline Matrix4& operator=(const Matrix4& that) { for(int n = 0; n < 16; ++n) { mat[n] = that.mat[n]; } return *this; } inline Matrix4 operator+(const Matrix4& that) const { Matrix4 result; int n; for (n = 0; n < 16; n++) result.mat[n] = mat[n] + that.mat[n]; return result; } inline Matrix4& operator+=(const Matrix4& that) { return (*this = *this + that); } inline Matrix4 operator-(const Matrix4& that) const { Matrix4 result; int n; for (n = 0; n < 16; n++) result.mat[n] = mat[n] - that.mat[n]; return result; } inline Matrix4& operator-=(const Matrix4& that) { return (*this = *this - that); } // Matrix multiplication (a * b) friend Matrix4 operator*(Matrix4& a, Matrix4& b) { Matrix4 retVal; retVal(0, 0) = a(0,0) * b(0,0) + a(1,0) * b(0,1) + a(2,0) * b(0,2) + a(3,0) * b(0,3); retVal(0, 1) = a(0,1) * b(0,0) + a(1,1) * b(0,1) + a(2,1) * b(0,2) + a(3,1) * b(0,3); retVal(0, 2) = a(0,2) * b(0,0) + a(1,2) * b(0,1) + a(2,2) * b(0,2) + a(3,2) * b(0,3); retVal(0, 3) = a(0,3) * b(0,0) + a(1,3) * b(0,1) + a(2,3) * b(0,2) + a(3,3) * b(0,3); retVal(1, 0) = a(0,0) * b(1,0) + a(1,0) * b(1,1) + a(2,0) * b(1,2) + a(3,0) * b(1,3); retVal(1, 1) = a(0,1) * b(1,0) + a(1,1) * b(1,1) + a(2,1) * b(1,2) + a(3,1) * b(1,3); retVal(1, 2) = a(0,2) * b(1,0) + a(1,2) * b(1,1) + a(2,2) * b(1,2) + a(3,2) * b(1,3); retVal(1, 3) = a(0,3) * b(1,0) + a(1,3) * b(1,1) + a(2,3) * b(1,2) + a(3,3) * b(1,3); retVal(2, 0) = a(0,0) * b(2,0) + a(1,0) * b(2,1) + a(2,0) * b(2,2) + a(3,0) * b(2,3); retVal(2, 1) = a(0,1) * b(2,0) + a(1,1) * b(2,1) + a(2,1) * b(2,2) + a(3,1) * b(2,3); retVal(2, 2) = a(0,2) * b(2,0) + a(1,2) * b(2,1) + a(2,2) * b(2,2) + a(3,2) * b(2,3); retVal(2, 3) = a(0,3) * b(2,0) + a(1,3) * b(2,1) + a(2,3) * b(2,2) + a(3,3) * b(2,3); retVal(3, 0) = a(0,0) * b(3,0) + a(1,0) * b(3,1) + a(2,0) * b(3,2) + a(3,0) * b(3,3); retVal(3, 1) = a(0,1) * b(3,0) + a(1,1) * b(3,1) + a(2,1) * b(3,2) + a(3,1) * b(3,3); retVal(3, 2) = a(0,2) * b(3,0) + a(1,2) * b(3,1) + a(2,2) * b(3,2) + a(3,2) * b(3,3); retVal(3, 3) = a(0,3) * b(3,0) + a(1,3) * b(3,1) + a(2,3) * b(3,2) + a(3,3) * b(3,3); return retVal; } Matrix4& operator*=(Matrix4& right) { *this = *this * right; return *this; } // Invert the matrix - super slow void invert(); Vector3 getTranslation() const { return Vector3(mat[12], mat[13], mat[14]); } Vector3 getXAxis() const { return Vector3::normalize(Vector3(mat[0], mat[1], mat[2])); } Vector3 getYAxis() const { return Vector3::normalize(Vector3(mat[4], mat[5], mat[6])); } Vector3 getZAxis() const { return Vector3::normalize(Vector3(mat[8], mat[9], mat[10])); } Vector3 getScale() const { Vector3 retVal; retVal.x = Vector3(mat[0], mat[1], mat[2]).length(); retVal.y = Vector3(mat[4], mat[5], mat[6]).length(); retVal.z = Vector3(mat[8], mat[9], mat[10]).length(); return retVal; } static Matrix4 createScale(float xScale, float yScale, float zScale) { array<float, 16> temp = { xScale, 0.0f, 0.0f, 0.0f, 0.0f, yScale, 0.0f, 0.0f, 0.0f, 0.0f, zScale, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f }; return Matrix4(temp); } static Matrix4 createScale(const Vector3& scaleVector) { return createScale(scaleVector.x, scaleVector.y, scaleVector.z); } static Matrix4 createScale(float scale) { return createScale(scale, scale, scale); } static Matrix4 createRotationX(float theta) { array<float, 16> temp = { 1.0f, 0.0f, 0.0f , 0.0f, 0.0f, Maths::cos(theta), -Maths::sin(theta), 0.0f, 0.0f, Maths::sin(theta), Maths::cos(theta), 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, }; return Matrix4(temp); } static Matrix4 createRotationY(float theta) { array<float, 16> temp = { Maths::cos(theta), 0.0f, Maths::sin(theta), 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, -Maths::sin(theta), 0.0f, Maths::cos(theta), 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, }; return Matrix4(temp); } static Matrix4 createRotationZ(float theta) { array<float, 16> temp = { Maths::cos(theta), -Maths::sin(theta), 0.0f, 0.0f, Maths::sin(theta), Maths::cos(theta), 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, }; return Matrix4(temp); } static Matrix4 createTranslation(const Vector3& trans) { array<float, 16> temp = { 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, trans.x, trans.y, trans.z, 1.0f }; return Matrix4(temp); } static Matrix4 createSimpleViewProj(float width, float height) { array<float, 16> temp = { 2.0f / width, 0.0f, 0.0f, 0.0f, 0.0f, 2.0f / height, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f }; return Matrix4(temp); } static Matrix4 createFromQuaternion(const Quaternion& q) { array<float, 16> temp; temp[0] = 1.0f - 2.0f * q.y * q.y - 2.0f * q.z * q.z; temp[1] = 2.0f * q.x * q.y - 2.0f * q.w * q.z; temp[2] = 2.0f * q.x * q.z + 2.0f * q.w * q.y; temp[3] = 0.0f; temp[4] = 2.0f * q.x * q.y + 2.0f * q.w * q.z; temp[5] = 1.0f - 2.0f * q.x * q.x - 2.0f * q.z * q.z; temp[6] = 2.0f * q.y * q.z - 2.0f * q.w * q.x; temp[7] = 0.0f; temp[8] = 2.0f * q.x * q.z - 2.0f * q.w * q.y; temp[9] = 2.0f * q.y * q.z - 2.0f * q.w * q.x; temp[10] = 1.0f - 2.0f * q.x * q.x - 2.0f * q.y * q.y; temp[11] = 0.0f; temp[12] = 0.0f; temp[13] = 0.0f; temp[14] = 0.0f; temp[15] = 1.0f; return Matrix4(temp); } static Matrix4 createLookAt(const Vector3& eye, const Vector3& target, const Vector3& up) { Vector3 zaxis = Vector3::normalize(eye - target); Vector3 normalizedUp = Vector3::normalize(up); Vector3 xaxis = Vector3::normalize(Vector3::cross(normalizedUp, zaxis)); Vector3 yaxis = Vector3::normalize(Vector3::cross(zaxis, xaxis)); array<float, 16> temp = { xaxis.x, yaxis.x, zaxis.x, 0.0f, xaxis.y, yaxis.y, zaxis.y, 0.0f, xaxis.z, yaxis.z, zaxis.z, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f }; return Matrix4(temp) * Matrix4::createTranslation(Vector3(-eye.x, -eye.y, -eye.z)); } static Matrix4 createOrtho(float width, float height, float near, float far) { array<float, 16> temp = { 2.0f / width, 0.0f, 0.0f, 0.0f, 0.0f, 2.0f / height, 0.0f, 0.0f, 0.0f, 0.0f, 2.0f / (near - far), 0.0f, 0.0f, 0.0f, (far + near) / (far - far), 1.0f }; return Matrix4(temp); } static Matrix4 createPerspectiveFOV(float fovY, float width, float height, float near, float far) { float yScale = Maths::cot(fovY / 2.0f); float xScale = yScale * height / width; array<float, 16> temp = { xScale, 0.0f, 0.0f, 0.0f, 0.0f, yScale, 0.0f, 0.0f, 0.0f, 0.0f, near + far / (near - far), -1.0f, 0.0f, 0.0f, 2.0f * near * far / (near - far), 0.0f }; return Matrix4(temp); } static Matrix4 createPerspective(float left, float right, float bottom, float top, float near, float far) { array<float, 16> temp = { 2 * near / (right - left), 0.0f, 0.0f, 0.0f, 0.0f, 2 * near / (top - bottom), 0.0f, 0.0f, (right + left) / (right - left), (top + bottom) / (top - bottom), (far + near) / (near - far), -1.0f, 0.0f, 0.0f, 2 * near * far / (near - far), 0.0f }; return Matrix4(temp); } static const Matrix4 identity; }; #endif
<filename>Pod/Headers/CMAField.h<gh_stars>1-10 // // CMAField.h // Pods // // Created by <NAME> on 29/07/14. // // #import <ContentfulDeliveryAPI/CDANullabilityStubs.h> #import <ContentfulManagementAPI/ContentfulManagementAPI.h> NS_ASSUME_NONNULL_BEGIN @class CMAValidation; /** * Management extensions for fields. */ @interface CMAField : CDAField /** * Create a new field, locally. This API should be used to create fields for creating and updating * content types. * * @param name The name of the new field. * @param type The type of the new field. * * @return A new field instance. */ +(instancetype)fieldWithName:(NSString*)name type:(CDAFieldType)type; /** Field type of items if the field is an Array, `CDAFieldTypeNone` otherwise. */ @property (nonatomic) CDAFieldType itemType; /** List of currently active validations for the receiver. */ @property (nonatomic, readonly) NSArray* validations; /** Whether or not this field will be omitted from delivery API responses. */ @property (nonatomic) BOOL omitted; /** * Add a validation for the receiver. It will be applied whenever a value of that field is set. * * @param validation A validation to apply to values of the receiver. */ -(void)addValidation:(CMAValidation*)validation; @end NS_ASSUME_NONNULL_END
// // C++ Interface: PluginBase // // Description: Sets the basis for the definition of a Plugin. // // // Author: <NAME> // // Copyright: See COPYING file that comes with this distribution // #ifndef PluginBase_H #define PluginBase_H #include "AMILabEngineConfig.h" //-------------------------------------------------- // Definition of macros to determine the mode of use // of the Plugin. //-------------------------------------------------- #define PLUGIN_IN_CONSOLE_MODE 0 #define PLUGIN_IN_GRAPHIC_MODE 1 #include <string> #include "PluginInterface.h" //-------------------------------------------------- // Specified how export functions from DLL or // shared library. //-------------------------------------------------- #ifdef WIN32 #if defined (_MSC_VER) || defined (__BORLANDC__) #define PLUGIN_AMILAB_DLLEXPORT __declspec( dllexport ) //#else //# error "don't know how export functions from DLL with this compiler" #endif #else #define PLUGIN_AMILAB_DLLEXPORT #endif /** * @brief Class that sets the basis for the definition of a Plugin. **/ class //WXEXPORT PluginBase: public PluginInterface { public: virtual ~PluginBase() { } /** * @brief Get the plugin name. * * @return return a std::string with the plugin name **/ virtual std::string GetName(void) const { return m_Name; } /** * @brief Get the plugin description. * * @return return a std::string with the plugin description **/ virtual std::string GetDescription(void) const { return m_Description; } /** * @brief Get the plugin version. * * @return return a std::string with the plugin version **/ virtual std::string GetVersion(void) const { return m_Version; } /** * @brief Get the plugin author. * * @return return a std::string with the plugin author **/ virtual std::string GetAuthor(void) const { return m_Author; } /** * @brief Set the plugin name. * * @param Name A std::string with the plugin name **/ virtual void SetName(const std::string &Name) { m_Name = Name; } /** * @brief Set the plugin description. * * @param Description A std::string with the plugin description **/ virtual void SetDescription(const std::string &Description) { m_Description = Description; } /** * @brief Set the plugin version. * * @param Version A std::string with the plugin version **/ virtual void SetVersion(const std::string &Version) { m_Version = Version; } /** * @brief Set the plugin author. * * @param Author A std::string with the plugin author **/ virtual void SetAuthor(const std::string &Author) { m_Author = Author; } /** * @brief Set that the plugin executes in mode console. * * The plugin does not require the graphical environment(wxWindow) to work. **/ virtual void SetConsoleMode(void) { m_plugin_mode = PLUGIN_IN_CONSOLE_MODE; } /** * @brief Set that the plugin executes in mode graphic. * * The plugin requires the graphical environment(wxWindow) to work. **/ virtual void SetGraphicMode(void) { m_plugin_mode = PLUGIN_IN_GRAPHIC_MODE; } /** * @brief Checks if this in console mode. * * @return Returns true if this in console mode. **/ virtual bool IsConsoleMode(void) const { return (m_plugin_mode == PLUGIN_IN_CONSOLE_MODE); } /** * @brief Checks if this in graphic mode. * * @return Returns true if this in graphic mode. **/ virtual bool IsGraphicMode(void) const { return (m_plugin_mode == PLUGIN_IN_GRAPHIC_MODE); } /** * @brief Execute the plugin. * * @return return true if the plugin executes correctly **/ virtual bool Execute (void) { //TODO return true; } virtual void Destroy () { //std::cout << "Destroy() {}" << std::endl; } private: unsigned char m_plugin_mode; // Determines the mode in which the plugin is executed. std::string m_Name, // The plugin name m_Description, // The plugin description m_Version, // The plugin version m_Author; // The plugin Author // wxWindow* m_win; // The plugin wxWindow. }; // PluginBase /** @name This is the API that each AMILAB shared lib must implement. */ //@{ extern "C" { /** Each module DLL must implement a function CreatePlugin of this type which will be called to initialise it. That function must return the new object representing this module. */ typedef PluginBase* ( *CreatePlugin_function)(); } //@} // ---------------------------------------------------------------------------- // macros for module declaration/implementation. // // This macros must be used inside the class declaration for any module class. // ---------------------------------------------------------------------------- #define PLUGIN_DEFINE() \ public: \ virtual bool Execute (void); \ virtual void Destroy(); #define PLUGIN_ENTRY_FUNCTION(name) \ extern "C" PLUGIN_AMILAB_DLLEXPORT PluginBase* CreatePlugin() \ { \ return new name(); \ }; #endif // PluginBase_H
/* Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: <NAME> */ #pragma once #include "kernel/environment.h" namespace lean { /** \brief Erase irrelevant terms (e.g., proofs, types, eq.rec, subtypes, etc). The parameters, motive and indices are also erased from cases_on applications. \remark The resultant term cannot be type checked. So, any preprocessing step that requires type inference cannot be applied after this transformation. \remark This procedure also replace occurrences of rec_fn_macro with constants. The rec_fn_macro is only used to make sure the result type checks. So, since the result will not type check anyway, there is no point in using them. */ expr erase_irrelevant(environment const & env, expr const & e); /** \brief Neutral auxiliary term. */ bool is_neutral_expr(expr const & e); bool is_unreachable_expr(expr const & e); expr mk_neutral_expr(); expr mk_unreachable_expr(); void initialize_erase_irrelevant(); void finalize_erase_irrelevant(); }
#ifndef ISPN_HOTROD_REMOTECACHEMANAGERIMPL_H #define ISPN_HOTROD_REMOTECACHEMANAGERIMPL_H #include "infinispan/hotrod/ImportExport.h" #include "infinispan/hotrod/Handle.h" #include "infinispan/hotrod/RemoteCache.h" #include "hotrod/impl/configuration/Configuration.h" #include "hotrod/impl/protocol/Codec.h" #include "hotrod/impl/transport/TransportFactory.h" #include <map> namespace infinispan { namespace hotrod { class RemoteCacheManagerImpl { public: RemoteCacheManagerImpl(bool start = true); //RemoteCacheManagerImpl(const Configuration& configuration, bool start = true); RemoteCacheManagerImpl(const std::map<std::string,std::string>& properties, bool start = true); void start(); void stop(); bool isStarted(); const Configuration& getConfiguration(); void initCache(RemoteCacheImpl& cache, bool forceReturnValue); private: transport::TransportFactory* transportFactory; // TODO: volatile bool started; Configuration configuration; protocol::Codec* codec; // TODO: atomic, initialized to 1 int64_t topologyId; }; }} // namespace infinispan::hotrod #endif /* ISPN_HOTROD_REMOTECACHEMANAGERIMPL_H */
#include <stdlib.h> /* #include <jack/jack.h> */ #include <stdio.h> #include <soundpipe.h> #include <sporth.h> #include <time.h> #include "patchwerk.h" #include "audio.h" #include "wavout.h" #include "pwsporth.h" #include "glitch.h" #include "add.h" /* static void jack_shutdown (void *arg) */ /* { */ /* exit (1); */ /* } */ void node_chooser(pw_node *node, plumber_data *pd); /* void tz_run_audio(tz_audio *audio, void *ud, int (*callback)(jack_nframes_t, void *)) */ /* { */ /* /\* const char *client_name = "tiziku"; *\/ */ /* /\* const char *server_name = NULL; *\/ */ /* /\* int chan; *\/ */ /* /\* int *nchan = &audio->nchan; *\/ */ /* /\* *nchan = MY_CHANNELS_OUT; *\/ */ /* /\* jack_options_t options = JackNullOption; *\/ */ /* /\* jack_status_t status; *\/ */ /* /\* audio->output_port = malloc(sizeof(jack_port_t *) * *nchan); *\/ */ /* /\* audio->client = malloc(sizeof(jack_client_t *)); *\/ */ /* /\* audio->client[0] = jack_client_open (client_name, options, &status, server_name); *\/ */ /* /\* if (audio->client[0] == NULL) { *\/ */ /* /\* fprintf (stderr, "jack_client_open() failed, " *\/ */ /* /\* "status = 0x%2.0x\n", status); *\/ */ /* /\* if (status & JackServerFailed) { *\/ */ /* /\* fprintf (stderr, "Unable to connect to JACK server\n"); *\/ */ /* /\* } *\/ */ /* /\* exit (1); *\/ */ /* /\* } *\/ */ /* /\* if (status & JackServerStarted) { *\/ */ /* /\* fprintf (stderr, "JACK server started\n"); *\/ */ /* /\* } *\/ */ /* /\* if (status & JackNameNotUnique) { *\/ */ /* /\* client_name = jack_get_client_name(audio->client[0]); *\/ */ /* /\* fprintf (stderr, "unique name `%s' assigned\n", client_name); *\/ */ /* /\* } *\/ */ /* /\* jack_set_process_callback (audio->client[0], callback, ud); *\/ */ /* /\* jack_on_shutdown (audio->client[0], jack_shutdown, 0); *\/ */ /* /\* char chan_name[50]; *\/ */ /* /\* for(chan = 0; chan < *nchan; chan++) { *\/ */ /* /\* sprintf(chan_name, "output_%d", chan); *\/ */ /* /\* printf("registering %s\n", chan_name); *\/ */ /* /\* audio->output_port[chan] = jack_port_register (audio->client[0], chan_name, *\/ */ /* /\* JACK_DEFAULT_AUDIO_TYPE, *\/ */ /* /\* JackPortIsOutput, chan); *\/ */ /* /\* if (audio->output_port[chan] == NULL) { *\/ */ /* /\* fprintf(stderr, "no more JACK ports available\n"); *\/ */ /* /\* exit (1); *\/ */ /* /\* } *\/ */ /* /\* if (jack_activate (audio->client[0])) { *\/ */ /* /\* fprintf (stderr, "cannot activate client"); *\/ */ /* /\* exit (1); *\/ */ /* /\* } *\/ */ /* /\* } *\/ */ /* /\* audio->ports = jack_get_ports (audio->client[0], NULL, NULL, *\/ */ /* /\* JackPortIsPhysical|JackPortIsInput); *\/ */ /* /\* if (audio->ports == NULL) { *\/ */ /* /\* fprintf(stderr, "no physical playback ports\n"); *\/ */ /* /\* exit (1); *\/ */ /* /\* } *\/ */ /* /\* for(chan = 0; chan < *nchan; chan++) { *\/ */ /* /\* if (jack_connect (audio->client[0], jack_port_name (audio->output_port[chan]), audio->ports[chan])) { *\/ */ /* /\* fprintf (stderr, "cannot connect output ports\n"); *\/ */ /* /\* } *\/ */ /* /\* } *\/ */ /* } */ /* void tz_stop_audio(tz_audio* audio) */ /* { */ /* /\* free (audio->ports); *\/ */ /* /\* jack_client_close (audio->client[0]); *\/ */ /* /\* free(audio->output_port); *\/ */ /* /\* free(audio->client); *\/ */ /* } */ void tz_pw_init(tz_audio *audio) { sp_data *sp; audio->patch = malloc(pw_patch_size()); pw_patch_init(audio->patch, 64); pw_patch_alloc(audio->patch, 8, 10); sp_create(&sp); sp->sr = pw_patch_srate_get(audio->patch); /* seed soundpipe RNG */ sp_srand(sp, time(NULL)); /* seed regular RNG too */ srand(time(NULL)); pw_patch_data_set(audio->patch, sp); } void tz_pw_del(tz_audio *audio) { sp_data *sp; sp = pw_patch_data_get(audio->patch); pw_patch_destroy(audio->patch); pw_patch_free_nodes(audio->patch); free(audio->patch); sp_destroy(&sp); } /* global instance of Sporth. it was easier this way */ plumber_data the_pd; void tz_sporth_init(tz_audio *audio) { plumber_data *pd; sp_data *sp; int rc; pd = &the_pd; sp = pw_patch_data_get(audio->patch); plumber_register(pd); plumber_init(pd); pd->sp = sp; plumber_open_file(pd, "drone.sp"); rc = plumber_parse(pd); if (rc != PLUMBER_OK) { exit(1); } plumber_compute(pd, PLUMBER_INIT); plumber_close_file(pd); } void tz_sporth_del(tz_audio *audio) { plumber_clean(&the_pd); } void tz_pw_mkpatch(tz_audio *audio) { pw_patch *patch; sp_data *sp; pw_node *node; pw_stack *stack; wavout_d *wavout; pwsporth *sporth; add_d *adder[2]; glitch_d *glitch[4]; patch = audio->patch; stack = pw_patch_stack(patch); sp = pw_patch_data_get(patch); /* create chooser (no outputs/inputs) */ pw_patch_new_node(patch, &node); node_chooser(node, &the_pd); /* glitch 0 */ pw_patch_new_node(patch, &node); glitch[0] = node_glitch(node, 0); /* glitch 1 */ pw_patch_new_node(patch, &node); glitch[1] = node_glitch(node, 1); /* glitch0 + glitch 1 -> add0 */ pw_stack_pop(stack, NULL); pw_stack_pop(stack, NULL); pw_patch_new_node(patch, &node); node_add(node); pw_node_setup(node); adder[0] = pw_node_get_data(node); pw_cable_connect(glitch[0]->out, adder[0]->in1); pw_cable_connect(glitch[1]->out, adder[0]->in2); /* glitch2 */ pw_patch_new_node(patch, &node); glitch[2] = node_glitch(node, 2); /* add0 + glitch2 -> add1*/ pw_stack_pop(stack, NULL); pw_stack_pop(stack, NULL); pw_patch_new_node(patch, &node); node_add(node); pw_node_setup(node); adder[1] = pw_node_get_data(node); pw_cable_connect(adder[0]->out, adder[1]->in1); pw_cable_connect(glitch[2]->out, adder[1]->in2); /* glitch3 */ pw_patch_new_node(patch, &node); glitch[3] = node_glitch(node, 3); /* add1 + glitch3 -> add0 */ pw_stack_pop(stack, NULL); pw_stack_pop(stack, NULL); pw_patch_new_node(patch, &node); node_add(node); pw_node_setup(node); adder[0] = pw_node_get_data(node); pw_cable_connect(adder[1]->out, adder[0]->in1); pw_cable_connect(glitch[3]->out, adder[0]->in2); /* sporth patch */ pw_patch_new_node(patch, &node); sporth = node_pwsporth(node, &the_pd); /* add0 + sporth -> add1 */ pw_stack_pop(stack, NULL); pw_stack_pop(stack, NULL); pw_patch_new_node(patch, &node); node_add(node); pw_node_setup(node); adder[1] = pw_node_get_data(node); pw_cable_connect(adder[0]->out, adder[1]->in2); pw_cable_connect(sporth->out, adder[1]->in1); /* add1 -> wavout */ pw_stack_pop(stack, NULL); pw_patch_new_node(patch, &node); node_wavout(sp, node, "tiziku.wav"); wavout = pw_node_get_data(node); pw_cable_connect(adder[1]->out, wavout->in); pw_stack_pop(stack, NULL); }
// // Generated by class-dump 3.5 (64 bit). // // class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2013 by <NAME>. // #import "NSObject.h" @class NSMutableArray, NSMutableDictionary; @interface ICURLRequestRegistry : NSObject { NSMutableArray *_activeRequests; NSMutableDictionary *_requestHandlers; } + (id)sharedRegistry; @property(retain, nonatomic) NSMutableDictionary *requestHandlers; // @synthesize requestHandlers=_requestHandlers; @property(retain, nonatomic) NSMutableArray *activeRequests; // @synthesize activeRequests=_activeRequests; - (void).cxx_destruct; - (id)popRequestWithUUID:(id)arg1; - (id)popActiveRequest; - (id)popRequest:(id)arg1; - (void)registerOutgoingRequest:(id)arg1; - (CDUnknownBlockType)handlerForIncomingRequestWithAction:(id)arg1 scheme:(id)arg2; - (void)removeHandlerForIncomingRequestsWithAction:(id)arg1 scheme:(id)arg2; - (void)registerHandler:(CDUnknownBlockType)arg1 forIncomingRequestsWithAction:(id)arg2 scheme:(id)arg3; @end
<filename>iis2dh_STdC/driver/iis2dh_reg.h /* ****************************************************************************** * @file iis2dh_reg.h * @author Sensors Software Solution Team * @brief This file contains all the functions prototypes for the * iis2dh_reg.c driver. ****************************************************************************** * @attention * * <h2><center>&copy; Copyright (c) 2020 STMicroelectronics. * All rights reserved.</center></h2> * * This software component is licensed by ST under BSD 3-Clause license, * the "License"; You may not use this file except in compliance with the * License. You may obtain a copy of the License at: * opensource.org/licenses/BSD-3-Clause * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef IIS2DH_REGS_H #define IIS2DH_REGS_H #ifdef __cplusplus extern "C" { #endif /* Includes ------------------------------------------------------------------*/ #include <stdint.h> #include <math.h> /** @addtogroup IIS2DH * @{ * */ /** @defgroup Endianness definitions * @{ * */ #ifndef DRV_BYTE_ORDER #ifndef __BYTE_ORDER__ #define DRV_LITTLE_ENDIAN 1234 #define DRV_BIG_ENDIAN 4321 /** if _BYTE_ORDER is not defined, choose the endianness of your architecture * by uncommenting the define which fits your platform endianness */ //#define DRV_BYTE_ORDER DRV_BIG_ENDIAN #define DRV_BYTE_ORDER DRV_LITTLE_ENDIAN #else /* defined __BYTE_ORDER__ */ #define DRV_LITTLE_ENDIAN __ORDER_LITTLE_ENDIAN__ #define DRV_BIG_ENDIAN __ORDER_BIG_ENDIAN__ #define DRV_BYTE_ORDER __BYTE_ORDER__ #endif /* __BYTE_ORDER__*/ #endif /* DRV_BYTE_ORDER */ /** * @} * */ /** @defgroup STMicroelectronics sensors common types * @{ * */ #ifndef MEMS_SHARED_TYPES #define MEMS_SHARED_TYPES typedef struct { #if DRV_BYTE_ORDER == DRV_LITTLE_ENDIAN uint8_t bit0 : 1; uint8_t bit1 : 1; uint8_t bit2 : 1; uint8_t bit3 : 1; uint8_t bit4 : 1; uint8_t bit5 : 1; uint8_t bit6 : 1; uint8_t bit7 : 1; #elif DRV_BYTE_ORDER == DRV_BIG_ENDIAN uint8_t bit7 : 1; uint8_t bit6 : 1; uint8_t bit5 : 1; uint8_t bit4 : 1; uint8_t bit3 : 1; uint8_t bit2 : 1; uint8_t bit1 : 1; uint8_t bit0 : 1; #endif /* DRV_BYTE_ORDER */ } bitwise_t; #define PROPERTY_DISABLE (0U) #define PROPERTY_ENABLE (1U) /** @addtogroup Interfaces_Functions * @brief This section provide a set of functions used to read and * write a generic register of the device. * MANDATORY: return 0 -> no Error. * @{ * */ typedef int32_t (*stmdev_write_ptr)(void *, uint8_t, uint8_t *, uint16_t); typedef int32_t (*stmdev_read_ptr) (void *, uint8_t, uint8_t *, uint16_t); typedef struct { /** Component mandatory fields **/ stmdev_write_ptr write_reg; stmdev_read_ptr read_reg; /** Customizable optional pointer **/ void *handle; } stmdev_ctx_t; /** * @} * */ #endif /* MEMS_SHARED_TYPES */ #ifndef MEMS_UCF_SHARED_TYPES #define MEMS_UCF_SHARED_TYPES /** @defgroup Generic address-data structure definition * @brief This structure is useful to load a predefined configuration * of a sensor. * You can create a sensor configuration by your own or using * Unico / Unicleo tools available on STMicroelectronics * web site. * * @{ * */ typedef struct { uint8_t address; uint8_t data; } ucf_line_t; /** * @} * */ #endif /* MEMS_UCF_SHARED_TYPES */ /** * @} * */ /** @defgroup IIS2DH_Infos * @{ * */ /** I2C Device Address 8 bit format if SA0=0 -> 31 if SA0=1 -> 33 **/ #define IIS2DH_I2C_ADD_L 0x31U #define IIS2DH_I2C_ADD_H 0x33U /** Device Identification (Who am I) **/ #define IIS2DH_ID 0x33U /** * @} * */ #define IIS2DH_STATUS_REG_AUX 0x07U typedef struct { #if DRV_BYTE_ORDER == DRV_LITTLE_ENDIAN uint8_t not_used_01 : 2; uint8_t tda : 1; uint8_t not_used_02 : 3; uint8_t tor : 1; uint8_t not_used_03 : 1; #elif DRV_BYTE_ORDER == DRV_BIG_ENDIAN uint8_t not_used_03 : 1; uint8_t tor : 1; uint8_t not_used_02 : 3; uint8_t tda : 1; uint8_t not_used_01 : 2; #endif /* DRV_BYTE_ORDER */ } iis2dh_status_reg_aux_t; #define IIS2DH_OUT_TEMP_L 0x0CU #define IIS2DH_OUT_TEMP_H 0x0DU #define IIS2DH_INT_COUNTER_REG 0x0EU #define IIS2DH_WHO_AM_I 0x0FU #define IIS2DH_TEMP_CFG_REG 0x1FU typedef struct { #if DRV_BYTE_ORDER == DRV_LITTLE_ENDIAN uint8_t not_used_01 : 6; uint8_t temp_en : 2; #elif DRV_BYTE_ORDER == DRV_BIG_ENDIAN uint8_t temp_en : 2; uint8_t not_used_01 : 6; #endif /* DRV_BYTE_ORDER */ } iis2dh_temp_cfg_reg_t; #define IIS2DH_CTRL_REG1 0x20U typedef struct { #if DRV_BYTE_ORDER == DRV_LITTLE_ENDIAN uint8_t xen : 1; uint8_t yen : 1; uint8_t zen : 1; uint8_t lpen : 1; uint8_t odr : 4; #elif DRV_BYTE_ORDER == DRV_BIG_ENDIAN uint8_t odr : 4; uint8_t lpen : 1; uint8_t zen : 1; uint8_t yen : 1; uint8_t xen : 1; #endif /* DRV_BYTE_ORDER */ } iis2dh_ctrl_reg1_t; #define IIS2DH_CTRL_REG2 0x21U typedef struct { #if DRV_BYTE_ORDER == DRV_LITTLE_ENDIAN uint8_t hp : 3; /* HPCLICK + HPIS2 + HPIS1 -> HP */ uint8_t fds : 1; uint8_t hpcf : 2; uint8_t hpm : 2; #elif DRV_BYTE_ORDER == DRV_BIG_ENDIAN uint8_t hpm : 2; uint8_t hpcf : 2; uint8_t fds : 1; uint8_t hp : 3; /* HPCLICK + HPIS2 + HPIS1 -> HP */ #endif /* DRV_BYTE_ORDER */ } iis2dh_ctrl_reg2_t; #define IIS2DH_CTRL_REG3 0x22U typedef struct { #if DRV_BYTE_ORDER == DRV_LITTLE_ENDIAN uint8_t not_used_01 : 1; uint8_t i1_overrun : 1; uint8_t i1_wtm : 1; uint8_t i1_drdy2 : 1; uint8_t i1_drdy1 : 1; uint8_t i1_aoi2 : 1; uint8_t i1_aoi1 : 1; uint8_t i1_click : 1; #elif DRV_BYTE_ORDER == DRV_BIG_ENDIAN uint8_t i1_click : 1; uint8_t i1_aoi1 : 1; uint8_t i1_aoi2 : 1; uint8_t i1_drdy1 : 1; uint8_t i1_drdy2 : 1; uint8_t i1_wtm : 1; uint8_t i1_overrun : 1; uint8_t not_used_01 : 1; #endif /* DRV_BYTE_ORDER */ } iis2dh_ctrl_reg3_t; #define IIS2DH_CTRL_REG4 0x23U typedef struct { #if DRV_BYTE_ORDER == DRV_LITTLE_ENDIAN uint8_t sim : 1; uint8_t st : 2; uint8_t hr : 1; uint8_t fs : 2; uint8_t ble : 1; uint8_t bdu : 1; #elif DRV_BYTE_ORDER == DRV_BIG_ENDIAN uint8_t bdu : 1; uint8_t ble : 1; uint8_t fs : 2; uint8_t hr : 1; uint8_t st : 2; uint8_t sim : 1; #endif /* DRV_BYTE_ORDER */ } iis2dh_ctrl_reg4_t; #define IIS2DH_CTRL_REG5 0x24U typedef struct { #if DRV_BYTE_ORDER == DRV_LITTLE_ENDIAN uint8_t d4d_int2 : 1; uint8_t lir_int2 : 1; uint8_t d4d_int1 : 1; uint8_t lir_int1 : 1; uint8_t not_used_01 : 2; uint8_t fifo_en : 1; uint8_t boot : 1; #elif DRV_BYTE_ORDER == DRV_BIG_ENDIAN uint8_t boot : 1; uint8_t fifo_en : 1; uint8_t not_used_01 : 2; uint8_t lir_int1 : 1; uint8_t d4d_int1 : 1; uint8_t lir_int2 : 1; uint8_t d4d_int2 : 1; #endif /* DRV_BYTE_ORDER */ } iis2dh_ctrl_reg5_t; #define IIS2DH_CTRL_REG6 0x25U typedef struct { #if DRV_BYTE_ORDER == DRV_LITTLE_ENDIAN uint8_t not_used_01 : 1; uint8_t h_lactive : 1; uint8_t not_used_02 : 1; uint8_t p2_act : 1; uint8_t boot_i2 : 1; uint8_t i2_int2 : 1; uint8_t i2_int1 : 1; uint8_t i2_clicken : 1; #elif DRV_BYTE_ORDER == DRV_BIG_ENDIAN uint8_t i2_clicken : 1; uint8_t i2_int1 : 1; uint8_t i2_int2 : 1; uint8_t boot_i2 : 1; uint8_t p2_act : 1; uint8_t not_used_02 : 1; uint8_t h_lactive : 1; uint8_t not_used_01 : 1; #endif /* DRV_BYTE_ORDER */ } iis2dh_ctrl_reg6_t; #define IIS2DH_REFERENCE 0x26U #define IIS2DH_STATUS_REG 0x27U typedef struct { #if DRV_BYTE_ORDER == DRV_LITTLE_ENDIAN uint8_t xda : 1; uint8_t yda : 1; uint8_t zda : 1; uint8_t zyxda : 1; uint8_t _xor : 1; uint8_t yor : 1; uint8_t zor : 1; uint8_t zyxor : 1; #elif DRV_BYTE_ORDER == DRV_BIG_ENDIAN uint8_t zyxor : 1; uint8_t zor : 1; uint8_t yor : 1; uint8_t _xor : 1; uint8_t zyxda : 1; uint8_t zda : 1; uint8_t yda : 1; uint8_t xda : 1; #endif /* DRV_BYTE_ORDER */ } iis2dh_status_reg_t; #define IIS2DH_OUT_X_L 0x28U #define IIS2DH_OUT_X_H 0x29U #define IIS2DH_OUT_Y_L 0x2AU #define IIS2DH_OUT_Y_H 0x2BU #define IIS2DH_OUT_Z_L 0x2CU #define IIS2DH_OUT_Z_H 0x2DU #define IIS2DH_FIFO_CTRL_REG 0x2EU typedef struct { #if DRV_BYTE_ORDER == DRV_LITTLE_ENDIAN uint8_t fth : 5; uint8_t tr : 1; uint8_t fm : 2; #elif DRV_BYTE_ORDER == DRV_BIG_ENDIAN uint8_t fm : 2; uint8_t tr : 1; uint8_t fth : 5; #endif /* DRV_BYTE_ORDER */ } iis2dh_fifo_ctrl_reg_t; #define IIS2DH_FIFO_SRC_REG 0x2FU typedef struct { #if DRV_BYTE_ORDER == DRV_LITTLE_ENDIAN uint8_t fss : 5; uint8_t empty : 1; uint8_t ovrn_fifo : 1; uint8_t wtm : 1; #elif DRV_BYTE_ORDER == DRV_BIG_ENDIAN uint8_t wtm : 1; uint8_t ovrn_fifo : 1; uint8_t empty : 1; uint8_t fss : 5; #endif /* DRV_BYTE_ORDER */ } iis2dh_fifo_src_reg_t; #define IIS2DH_INT1_CFG 0x30U typedef struct { #if DRV_BYTE_ORDER == DRV_LITTLE_ENDIAN uint8_t xlie : 1; uint8_t xhie : 1; uint8_t ylie : 1; uint8_t yhie : 1; uint8_t zlie : 1; uint8_t zhie : 1; uint8_t _6d : 1; uint8_t aoi : 1; #elif DRV_BYTE_ORDER == DRV_BIG_ENDIAN uint8_t aoi : 1; uint8_t _6d : 1; uint8_t zhie : 1; uint8_t zlie : 1; uint8_t yhie : 1; uint8_t ylie : 1; uint8_t xhie : 1; uint8_t xlie : 1; #endif /* DRV_BYTE_ORDER */ } iis2dh_int1_cfg_t; #define IIS2DH_INT1_SRC 0x31U typedef struct { #if DRV_BYTE_ORDER == DRV_LITTLE_ENDIAN uint8_t xl : 1; uint8_t xh : 1; uint8_t yl : 1; uint8_t yh : 1; uint8_t zl : 1; uint8_t zh : 1; uint8_t ia : 1; uint8_t not_used_01 : 1; #elif DRV_BYTE_ORDER == DRV_BIG_ENDIAN uint8_t not_used_01 : 1; uint8_t ia : 1; uint8_t zh : 1; uint8_t zl : 1; uint8_t yh : 1; uint8_t yl : 1; uint8_t xh : 1; uint8_t xl : 1; #endif /* DRV_BYTE_ORDER */ } iis2dh_int1_src_t; #define IIS2DH_INT1_THS 0x32U typedef struct { #if DRV_BYTE_ORDER == DRV_LITTLE_ENDIAN uint8_t ths : 7; uint8_t not_used_01 : 1; #elif DRV_BYTE_ORDER == DRV_BIG_ENDIAN uint8_t not_used_01 : 1; uint8_t ths : 7; #endif /* DRV_BYTE_ORDER */ } iis2dh_int1_ths_t; #define IIS2DH_INT1_DURATION 0x33U typedef struct { #if DRV_BYTE_ORDER == DRV_LITTLE_ENDIAN uint8_t d : 7; uint8_t not_used_01 : 1; #elif DRV_BYTE_ORDER == DRV_BIG_ENDIAN uint8_t not_used_01 : 1; uint8_t d : 7; #endif /* DRV_BYTE_ORDER */ } iis2dh_int1_duration_t; #define IIS2DH_INT2_CFG 0x34U typedef struct { #if DRV_BYTE_ORDER == DRV_LITTLE_ENDIAN uint8_t xlie : 1; uint8_t xhie : 1; uint8_t ylie : 1; uint8_t yhie : 1; uint8_t zlie : 1; uint8_t zhie : 1; uint8_t _6d : 1; uint8_t aoi : 1; #elif DRV_BYTE_ORDER == DRV_BIG_ENDIAN uint8_t aoi : 1; uint8_t _6d : 1; uint8_t zhie : 1; uint8_t zlie : 1; uint8_t yhie : 1; uint8_t ylie : 1; uint8_t xhie : 1; uint8_t xlie : 1; #endif /* DRV_BYTE_ORDER */ } iis2dh_int2_cfg_t; #define IIS2DH_INT2_SRC 0x35U typedef struct { #if DRV_BYTE_ORDER == DRV_LITTLE_ENDIAN uint8_t xl : 1; uint8_t xh : 1; uint8_t yl : 1; uint8_t yh : 1; uint8_t zl : 1; uint8_t zh : 1; uint8_t ia : 1; uint8_t not_used_01 : 1; #elif DRV_BYTE_ORDER == DRV_BIG_ENDIAN uint8_t not_used_01 : 1; uint8_t ia : 1; uint8_t zh : 1; uint8_t zl : 1; uint8_t yh : 1; uint8_t yl : 1; uint8_t xh : 1; uint8_t xl : 1; #endif /* DRV_BYTE_ORDER */ } iis2dh_int2_src_t; #define IIS2DH_INT2_THS 0x36U typedef struct { #if DRV_BYTE_ORDER == DRV_LITTLE_ENDIAN uint8_t ths : 7; uint8_t not_used_01 : 1; #elif DRV_BYTE_ORDER == DRV_BIG_ENDIAN uint8_t not_used_01 : 1; uint8_t ths : 7; #endif /* DRV_BYTE_ORDER */ } iis2dh_int2_ths_t; #define IIS2DH_INT2_DURATION 0x37U typedef struct { #if DRV_BYTE_ORDER == DRV_LITTLE_ENDIAN uint8_t d : 7; uint8_t not_used_01 : 1; #elif DRV_BYTE_ORDER == DRV_BIG_ENDIAN #endif /* DRV_BYTE_ORDER */ } iis2dh_int2_duration_t; #define IIS2DH_CLICK_CFG 0x38U typedef struct { #if DRV_BYTE_ORDER == DRV_LITTLE_ENDIAN uint8_t xs : 1; uint8_t xd : 1; uint8_t ys : 1; uint8_t yd : 1; uint8_t zs : 1; uint8_t zd : 1; uint8_t not_used_01 : 2; #elif DRV_BYTE_ORDER == DRV_BIG_ENDIAN uint8_t not_used_01 : 2; uint8_t zd : 1; uint8_t zs : 1; uint8_t yd : 1; uint8_t ys : 1; uint8_t xd : 1; uint8_t xs : 1; #endif /* DRV_BYTE_ORDER */ } iis2dh_click_cfg_t; #define IIS2DH_CLICK_SRC 0x39U typedef struct { #if DRV_BYTE_ORDER == DRV_LITTLE_ENDIAN uint8_t x : 1; uint8_t y : 1; uint8_t z : 1; uint8_t sign : 1; uint8_t sclick : 1; uint8_t dclick : 1; uint8_t ia : 1; uint8_t not_used_01 : 1; #elif DRV_BYTE_ORDER == DRV_BIG_ENDIAN uint8_t not_used_01 : 1; uint8_t ia : 1; uint8_t dclick : 1; uint8_t sclick : 1; uint8_t sign : 1; uint8_t z : 1; uint8_t y : 1; uint8_t x : 1; #endif /* DRV_BYTE_ORDER */ } iis2dh_click_src_t; #define IIS2DH_CLICK_THS 0x3AU typedef struct { #if DRV_BYTE_ORDER == DRV_LITTLE_ENDIAN uint8_t ths : 7; uint8_t not_used_01 : 1; #elif DRV_BYTE_ORDER == DRV_BIG_ENDIAN uint8_t not_used_01 : 1; uint8_t ths : 7; #endif /* DRV_BYTE_ORDER */ } iis2dh_click_ths_t; #define IIS2DH_TIME_LIMIT 0x3BU typedef struct { #if DRV_BYTE_ORDER == DRV_LITTLE_ENDIAN uint8_t tli : 7; uint8_t not_used_01 : 1; #elif DRV_BYTE_ORDER == DRV_BIG_ENDIAN uint8_t not_used_01 : 1; uint8_t tli : 7; #endif /* DRV_BYTE_ORDER */ } iis2dh_time_limit_t; #define IIS2DH_TIME_LATENCY 0x3CU typedef struct { uint8_t tla : 8; } iis2dh_time_latency_t; #define IIS2DH_TIME_WINDOW 0x3DU typedef struct { uint8_t tw : 8; } iis2dh_time_window_t; #define IIS2DH_ACT_THS 0x3EU typedef struct { #if DRV_BYTE_ORDER == DRV_LITTLE_ENDIAN uint8_t acth : 7; uint8_t not_used_01 : 1; #elif DRV_BYTE_ORDER == DRV_BIG_ENDIAN uint8_t not_used_01 : 1; uint8_t acth : 7; #endif /* DRV_BYTE_ORDER */ } iis2dh_act_ths_t; #define IIS2DH_ACT_DUR 0x3FU typedef struct { uint8_t actd : 8; } iis2dh_act_dur_t; /** * @defgroup IIS2DH_Register_Union * @brief This union group all the registers that has a bitfield * description. * This union is useful but not need by the driver. * * REMOVING this union you are compliant with: * MISRA-C 2012 [Rule 19.2] -> " Union are not allowed " * * @{ * */ typedef union { iis2dh_status_reg_aux_t status_reg_aux; iis2dh_temp_cfg_reg_t temp_cfg_reg; iis2dh_ctrl_reg1_t ctrl_reg1; iis2dh_ctrl_reg2_t ctrl_reg2; iis2dh_ctrl_reg3_t ctrl_reg3; iis2dh_ctrl_reg4_t ctrl_reg4; iis2dh_ctrl_reg5_t ctrl_reg5; iis2dh_ctrl_reg6_t ctrl_reg6; iis2dh_status_reg_t status_reg; iis2dh_fifo_ctrl_reg_t fifo_ctrl_reg; iis2dh_fifo_src_reg_t fifo_src_reg; iis2dh_int1_cfg_t int1_cfg; iis2dh_int1_src_t int1_src; iis2dh_int1_ths_t int1_ths; iis2dh_int1_duration_t int1_duration; iis2dh_int2_cfg_t int2_cfg; iis2dh_int2_src_t int2_src; iis2dh_int2_ths_t int2_ths; iis2dh_int2_duration_t int2_duration; iis2dh_click_cfg_t click_cfg; iis2dh_click_src_t click_src; iis2dh_click_ths_t click_ths; iis2dh_time_limit_t time_limit; iis2dh_time_latency_t time_latency; iis2dh_time_window_t time_window; iis2dh_act_ths_t act_ths; iis2dh_act_dur_t act_dur; bitwise_t bitwise; uint8_t byte; } iis2dh_reg_t; /** * @} * */ int32_t iis2dh_read_reg(stmdev_ctx_t *ctx, uint8_t reg, uint8_t *data, uint16_t len); int32_t iis2dh_write_reg(stmdev_ctx_t *ctx, uint8_t reg, uint8_t *data, uint16_t len); float_t iis2dh_from_fs2_hr_to_mg(int16_t lsb); float_t iis2dh_from_fs4_hr_to_mg(int16_t lsb); float_t iis2dh_from_fs8_hr_to_mg(int16_t lsb); float_t iis2dh_from_fs16_hr_to_mg(int16_t lsb); float_t iis2dh_from_lsb_hr_to_celsius(int16_t lsb); float_t iis2dh_from_fs2_nm_to_mg(int16_t lsb); float_t iis2dh_from_fs4_nm_to_mg(int16_t lsb); float_t iis2dh_from_fs8_nm_to_mg(int16_t lsb); float_t iis2dh_from_fs16_nm_to_mg(int16_t lsb); float_t iis2dh_from_lsb_nm_to_celsius(int16_t lsb); float_t iis2dh_from_fs2_lp_to_mg(int16_t lsb); float_t iis2dh_from_fs4_lp_to_mg(int16_t lsb); float_t iis2dh_from_fs8_lp_to_mg(int16_t lsb); float_t iis2dh_from_fs16_lp_to_mg(int16_t lsb); float_t iis2dh_from_lsb_lp_to_celsius(int16_t lsb); int32_t iis2dh_temp_status_reg_get(stmdev_ctx_t *ctx, uint8_t *buff); int32_t iis2dh_temp_data_ready_get(stmdev_ctx_t *ctx, uint8_t *val); int32_t iis2dh_temp_data_ovr_get(stmdev_ctx_t *ctx, uint8_t *val); int32_t iis2dh_temperature_raw_get(stmdev_ctx_t *ctx, int16_t *val); typedef enum { IIS2DH_TEMP_DISABLE = 0, IIS2DH_TEMP_ENABLE = 3, } iis2dh_temp_en_t; int32_t iis2dh_temperature_meas_set(stmdev_ctx_t *ctx, iis2dh_temp_en_t val); int32_t iis2dh_temperature_meas_get(stmdev_ctx_t *ctx, iis2dh_temp_en_t *val); typedef enum { IIS2DH_HR_12bit = 0, IIS2DH_NM_10bit = 1, IIS2DH_LP_8bit = 2, } iis2dh_op_md_t; int32_t iis2dh_operating_mode_set(stmdev_ctx_t *ctx, iis2dh_op_md_t val); int32_t iis2dh_operating_mode_get(stmdev_ctx_t *ctx, iis2dh_op_md_t *val); typedef enum { IIS2DH_POWER_DOWN = 0x00, IIS2DH_ODR_1Hz = 0x01, IIS2DH_ODR_10Hz = 0x02, IIS2DH_ODR_25Hz = 0x03, IIS2DH_ODR_50Hz = 0x04, IIS2DH_ODR_100Hz = 0x05, IIS2DH_ODR_200Hz = 0x06, IIS2DH_ODR_400Hz = 0x07, IIS2DH_ODR_1kHz620_LP = 0x08, IIS2DH_ODR_5kHz376_LP_1kHz344_NM_HP = 0x09, } iis2dh_odr_t; int32_t iis2dh_data_rate_set(stmdev_ctx_t *ctx, iis2dh_odr_t val); int32_t iis2dh_data_rate_get(stmdev_ctx_t *ctx, iis2dh_odr_t *val); int32_t iis2dh_high_pass_on_outputs_set(stmdev_ctx_t *ctx, uint8_t val); int32_t iis2dh_high_pass_on_outputs_get(stmdev_ctx_t *ctx, uint8_t *val); typedef enum { IIS2DH_AGGRESSIVE = 0, IIS2DH_STRONG = 1, IIS2DH_MEDIUM = 2, IIS2DH_LIGHT = 3, } iis2dh_hpcf_t; int32_t iis2dh_high_pass_bandwidth_set(stmdev_ctx_t *ctx, iis2dh_hpcf_t val); int32_t iis2dh_high_pass_bandwidth_get(stmdev_ctx_t *ctx, iis2dh_hpcf_t *val); typedef enum { IIS2DH_NORMAL_WITH_RST = 0, IIS2DH_REFERENCE_MODE = 1, IIS2DH_NORMAL = 2, IIS2DH_AUTORST_ON_INT = 3, } iis2dh_hpm_t; int32_t iis2dh_high_pass_mode_set(stmdev_ctx_t *ctx, iis2dh_hpm_t val); int32_t iis2dh_high_pass_mode_get(stmdev_ctx_t *ctx, iis2dh_hpm_t *val); typedef enum { IIS2DH_2g = 0, IIS2DH_4g = 1, IIS2DH_8g = 2, IIS2DH_16g = 3, } iis2dh_fs_t; int32_t iis2dh_full_scale_set(stmdev_ctx_t *ctx, iis2dh_fs_t val); int32_t iis2dh_full_scale_get(stmdev_ctx_t *ctx, iis2dh_fs_t *val); int32_t iis2dh_block_data_update_set(stmdev_ctx_t *ctx, uint8_t val); int32_t iis2dh_block_data_update_get(stmdev_ctx_t *ctx, uint8_t *val); int32_t iis2dh_filter_reference_set(stmdev_ctx_t *ctx, uint8_t *buff); int32_t iis2dh_filter_reference_get(stmdev_ctx_t *ctx, uint8_t *buff); int32_t iis2dh_xl_data_ready_get(stmdev_ctx_t *ctx, uint8_t *val); int32_t iis2dh_xl_data_ovr_get(stmdev_ctx_t *ctx, uint8_t *val); int32_t iis2dh_acceleration_raw_get(stmdev_ctx_t *ctx, int16_t *val); int32_t iis2dh_device_id_get(stmdev_ctx_t *ctx, uint8_t *buff); typedef enum { IIS2DH_ST_DISABLE = 0, IIS2DH_ST_POSITIVE = 1, IIS2DH_ST_NEGATIVE = 2, } iis2dh_st_t; int32_t iis2dh_self_test_set(stmdev_ctx_t *ctx, iis2dh_st_t val); int32_t iis2dh_self_test_get(stmdev_ctx_t *ctx, iis2dh_st_t *val); typedef enum { IIS2DH_LSB_AT_LOW_ADD = 0, IIS2DH_MSB_AT_LOW_ADD = 1, } iis2dh_ble_t; int32_t iis2dh_data_format_set(stmdev_ctx_t *ctx, iis2dh_ble_t val); int32_t iis2dh_data_format_get(stmdev_ctx_t *ctx, iis2dh_ble_t *val); int32_t iis2dh_boot_set(stmdev_ctx_t *ctx, uint8_t val); int32_t iis2dh_boot_get(stmdev_ctx_t *ctx, uint8_t *val); int32_t iis2dh_int_occurrencies_get(stmdev_ctx_t *ctx, uint8_t *val); int32_t iis2dh_status_get(stmdev_ctx_t *ctx, iis2dh_status_reg_t *val); int32_t iis2dh_int1_gen_conf_set(stmdev_ctx_t *ctx, iis2dh_int1_cfg_t *val); int32_t iis2dh_int1_gen_conf_get(stmdev_ctx_t *ctx, iis2dh_int1_cfg_t *val); int32_t iis2dh_int1_gen_source_get(stmdev_ctx_t *ctx, iis2dh_int1_src_t *val); int32_t iis2dh_int1_gen_threshold_set(stmdev_ctx_t *ctx, uint8_t val); int32_t iis2dh_int1_gen_threshold_get(stmdev_ctx_t *ctx, uint8_t *val); int32_t iis2dh_int1_gen_duration_set(stmdev_ctx_t *ctx, uint8_t val); int32_t iis2dh_int1_gen_duration_get(stmdev_ctx_t *ctx, uint8_t *val); int32_t iis2dh_int2_gen_conf_set(stmdev_ctx_t *ctx, iis2dh_int2_cfg_t *val); int32_t iis2dh_int2_gen_conf_get(stmdev_ctx_t *ctx, iis2dh_int2_cfg_t *val); int32_t iis2dh_int2_gen_source_get(stmdev_ctx_t *ctx, iis2dh_int2_src_t *val); int32_t iis2dh_int2_gen_threshold_set(stmdev_ctx_t *ctx, uint8_t val); int32_t iis2dh_int2_gen_threshold_get(stmdev_ctx_t *ctx, uint8_t *val); int32_t iis2dh_int2_gen_duration_set(stmdev_ctx_t *ctx, uint8_t val); int32_t iis2dh_int2_gen_duration_get(stmdev_ctx_t *ctx, uint8_t *val); typedef enum { IIS2DH_DISC_FROM_INT_GENERATOR = 0, IIS2DH_ON_INT1_GEN = 1, IIS2DH_ON_INT2_GEN = 2, IIS2DH_ON_TAP_GEN = 4, IIS2DH_ON_INT1_INT2_GEN = 3, IIS2DH_ON_INT1_TAP_GEN = 5, IIS2DH_ON_INT2_TAP_GEN = 6, IIS2DH_ON_INT1_INT2_TAP_GEN = 7, } iis2dh_hp_t; int32_t iis2dh_high_pass_int_conf_set(stmdev_ctx_t *ctx, iis2dh_hp_t val); int32_t iis2dh_high_pass_int_conf_get(stmdev_ctx_t *ctx, iis2dh_hp_t *val); int32_t iis2dh_pin_int1_config_set(stmdev_ctx_t *ctx, iis2dh_ctrl_reg3_t *val); int32_t iis2dh_pin_int1_config_get(stmdev_ctx_t *ctx, iis2dh_ctrl_reg3_t *val); int32_t iis2dh_int2_pin_detect_4d_set(stmdev_ctx_t *ctx, uint8_t val); int32_t iis2dh_int2_pin_detect_4d_get(stmdev_ctx_t *ctx, uint8_t *val); typedef enum { IIS2DH_INT2_PULSED = 0, IIS2DH_INT2_LATCHED = 1, } iis2dh_lir_int2_t; int32_t iis2dh_int2_pin_notification_mode_set(stmdev_ctx_t *ctx, iis2dh_lir_int2_t val); int32_t iis2dh_int2_pin_notification_mode_get(stmdev_ctx_t *ctx, iis2dh_lir_int2_t *val); int32_t iis2dh_int1_pin_detect_4d_set(stmdev_ctx_t *ctx, uint8_t val); int32_t iis2dh_int1_pin_detect_4d_get(stmdev_ctx_t *ctx, uint8_t *val); typedef enum { IIS2DH_INT1_PULSED = 0, IIS2DH_INT1_LATCHED = 1, } iis2dh_lir_int1_t; int32_t iis2dh_int1_pin_notification_mode_set(stmdev_ctx_t *ctx, iis2dh_lir_int1_t val); int32_t iis2dh_int1_pin_notification_mode_get(stmdev_ctx_t *ctx, iis2dh_lir_int1_t *val); int32_t iis2dh_pin_int2_config_set(stmdev_ctx_t *ctx, iis2dh_ctrl_reg6_t *val); int32_t iis2dh_pin_int2_config_get(stmdev_ctx_t *ctx, iis2dh_ctrl_reg6_t *val); int32_t iis2dh_fifo_set(stmdev_ctx_t *ctx, uint8_t val); int32_t iis2dh_fifo_get(stmdev_ctx_t *ctx, uint8_t *val); int32_t iis2dh_fifo_watermark_set(stmdev_ctx_t *ctx, uint8_t val); int32_t iis2dh_fifo_watermark_get(stmdev_ctx_t *ctx, uint8_t *val); typedef enum { IIS2DH_INT1_GEN = 0, IIS2DH_INT2_GEN = 1, } iis2dh_tr_t; int32_t iis2dh_fifo_trigger_event_set(stmdev_ctx_t *ctx, iis2dh_tr_t val); int32_t iis2dh_fifo_trigger_event_get(stmdev_ctx_t *ctx, iis2dh_tr_t *val); typedef enum { IIS2DH_BYPASS_MODE = 0, IIS2DH_FIFO_MODE = 1, IIS2DH_DYNAMIC_STREAM_MODE = 2, IIS2DH_STREAM_TO_FIFO_MODE = 3, } iis2dh_fm_t; int32_t iis2dh_fifo_mode_set(stmdev_ctx_t *ctx, iis2dh_fm_t val); int32_t iis2dh_fifo_mode_get(stmdev_ctx_t *ctx, iis2dh_fm_t *val); int32_t iis2dh_fifo_status_get(stmdev_ctx_t *ctx, iis2dh_fifo_src_reg_t *val); int32_t iis2dh_fifo_data_level_get(stmdev_ctx_t *ctx, uint8_t *val); int32_t iis2dh_fifo_empty_flag_get(stmdev_ctx_t *ctx, uint8_t *val); int32_t iis2dh_fifo_ovr_flag_get(stmdev_ctx_t *ctx, uint8_t *val); int32_t iis2dh_fifo_fth_flag_get(stmdev_ctx_t *ctx, uint8_t *val); int32_t iis2dh_tap_conf_set(stmdev_ctx_t *ctx, iis2dh_click_cfg_t *val); int32_t iis2dh_tap_conf_get(stmdev_ctx_t *ctx, iis2dh_click_cfg_t *val); int32_t iis2dh_tap_source_get(stmdev_ctx_t *ctx, iis2dh_click_src_t *val); int32_t iis2dh_tap_threshold_set(stmdev_ctx_t *ctx, uint8_t val); int32_t iis2dh_tap_threshold_get(stmdev_ctx_t *ctx, uint8_t *val); typedef enum { IIS2DH_TAP_PULSED = 0, IIS2DH_TAP_LATCHED = 1, } iis2dh_lir_click_t; int32_t iis2dh_tap_notification_mode_set(stmdev_ctx_t *ctx, iis2dh_lir_click_t val); int32_t iis2dh_tap_notification_mode_get(stmdev_ctx_t *ctx, iis2dh_lir_click_t *val); int32_t iis2dh_shock_dur_set(stmdev_ctx_t *ctx, uint8_t val); int32_t iis2dh_shock_dur_get(stmdev_ctx_t *ctx, uint8_t *val); int32_t iis2dh_quiet_dur_set(stmdev_ctx_t *ctx, uint8_t val); int32_t iis2dh_quiet_dur_get(stmdev_ctx_t *ctx, uint8_t *val); int32_t iis2dh_double_tap_timeout_set(stmdev_ctx_t *ctx, uint8_t val); int32_t iis2dh_double_tap_timeout_get(stmdev_ctx_t *ctx, uint8_t *val); int32_t iis2dh_act_threshold_set(stmdev_ctx_t *ctx, uint8_t val); int32_t iis2dh_act_threshold_get(stmdev_ctx_t *ctx, uint8_t *val); int32_t iis2dh_act_timeout_set(stmdev_ctx_t *ctx, uint8_t val); int32_t iis2dh_act_timeout_get(stmdev_ctx_t *ctx, uint8_t *val); typedef enum { IIS2DH_PULL_UP_DISCONNECT = 0, IIS2DH_PULL_UP_CONNECT = 1, } iis2dh_sdo_pu_disc_t; int32_t iis2dh_pin_sdo_sa0_mode_set(stmdev_ctx_t *ctx, iis2dh_sdo_pu_disc_t val); int32_t iis2dh_pin_sdo_sa0_mode_get(stmdev_ctx_t *ctx, iis2dh_sdo_pu_disc_t *val); typedef enum { IIS2DH_SPI_4_WIRE = 0, IIS2DH_SPI_3_WIRE = 1, } iis2dh_sim_t; int32_t iis2dh_spi_mode_set(stmdev_ctx_t *ctx, iis2dh_sim_t val); int32_t iis2dh_spi_mode_get(stmdev_ctx_t *ctx, iis2dh_sim_t *val); /** * @} * */ #ifdef __cplusplus } #endif #endif /* IIS2DH_REGS_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
<filename>nudg++/trunk/Include/FaceData3D.h // FaceData3D.h // // 2007/10/04 //--------------------------------------------------------- #ifndef NDG__FaceData3D_H__INCLUDED #define NDG__FaceData3D_H__INCLUDED #include "Poly3D.h" #include "VecObj_Type.h" #include "MatObj_Type.h" const int MAXfd = 20; //--------------------------------------------------------- class FaceData3D //--------------------------------------------------------- { public: FaceData3D(); ~FaceData3D(); void reset(); FaceData3D& operator=(const FaceData3D& B); public: IV neighs; // ids of neighbor faces DV *fx[MAXfd], *fy[MAXfd], *fz[MAXfd]; // {x,y,z} for all points of each face //DM fxyz[MAXfd]; // {x,y,z} for all points of each face DM *mmM[MAXfd], *mmP[MAXfd]; // internal,external mass matrices Poly3D *polys[MAXfd]; DV *weights[MAXfd]; int bcflag; }; // define FaceMat typedef MatObj<FaceData3D*> FaceMat; #endif // NDG__FaceData3D_H__INCLUDED
#ifndef KERNEL_MAIN_H #define KERNEL_MAIN_H void kmain(); int kmain_ii(); #endif /* KERNEL_MAIN_H */
// @@@LICENSE // // Copyright (c) 2010-2013 LG Electronics, 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. // // LICENSE@@@ /* * @file Rfc3901Tokenizer.h */ #ifndef RFC3501TOKENIZER_H_ #define RFC3501TOKENIZER_H_ #include <string.h> #include "core/MojRefCount.h" #include "parser/Parser.h" class Rfc3501TokenizerException : public std::exception { std::string m_message; public: Rfc3501TokenizerException(std::string msg) : m_message(msg) { } virtual ~Rfc3501TokenizerException() throw() {} }; /* * This is a tokenizer to be used when parsing responses as specified in rfc3501. */ class Rfc3501Tokenizer : public MojRefCounted { public: inline Rfc3501Tokenizer(const std::string& str, bool braces = false) : brace_is_token(braces), bytesNeeded(-1) { reset(str); } void pushBinaryData() { tokenType = TK_LITERAL_BYTES; bytesNeeded = -1; } inline void reset(const std::string& str) { pos = 0; cp = 0; tokenType = TK_ERROR; bytesNeeded = -1; chars.assign(str); len = chars.size(); } inline void append(const std::string& str) { cp = pos; chars.append(str); len = chars.size(); } // Erase everything before the current token inline void compact() { chars.erase(0, pos); // pos is the start of the current token cp = 0; pos = 0; len = chars.size(); } inline const std::string& value() const { return token; } // Get the text in the buffer const std::string& getAllText() const { return chars; } std::string produceDebugText(); std::string getConsumedText() { return chars.substr(0,cp); } std::string getRemainingText() { return chars.substr(cp); } bool numberValue(long int& result); std::string valueUpper(); bool match(const std::string& strchr); TokenType next(); bool startAt(std::string key); // Only valid in brace_is_token = false mode bool needsLiteralBytes() { return bytesNeeded >= 0; } int getBytesNeeded() { return bytesNeeded; } static const std::string KEYWORD_BODYSTRUCTURE; static const std::string KEYWORD_ENVELOPE; static const std::string KEYWORD_EXISTS; static const std::string KEYWORD_FLAGS; static const std::string KEYWORD_INTERNALDATE; static const std::string KEYWORD_LIST; static const std::string KEYWORD_UIDVALIDITY; static const std::string KEYWORD_UID; static const std::string NIL_STRING; static const std::string NAMESPACE_STRING; public: std::string token; TokenType tokenType; protected: TokenType throwError(const char* msg); static bool isAtomSpecial(char c); std::string chars; int pos; int len; int cp; std::string m_error; bool brace_is_token; int bytesNeeded; }; #endif /* RFC3501TOKENIZER_H_ */
<gh_stars>0 #include <assert.h> #include <bitcoin/chainparams.h> #include <bitcoin/privkey.h> #include <bitcoin/pubkey.h> #include <common/node_id.h> #include <common/private_channel_announcement.h> #include <wire/peer_wiregen.h> const u8 *private_channel_announcement(const tal_t *ctx, const struct short_channel_id *scid, const struct node_id *local_node_id, const struct node_id *remote_node_id, const u8 *features) { struct pubkey dummy_pubkey; const struct node_id *node[2]; struct secret not_a_secret; /* Make an all-zero sig. */ static const u8 zeros[64]; size_t zlen = sizeof(zeros); const u8 *zerop = zeros; secp256k1_ecdsa_signature zerosig; fromwire_secp256k1_ecdsa_signature(&zerop, &zlen, &zerosig); assert(zerop != NULL); memset(&not_a_secret, 1, sizeof(not_a_secret)); if (!pubkey_from_secret(&not_a_secret, &dummy_pubkey)) abort(); /* node ids are in ascending order. */ if (node_id_cmp(remote_node_id, local_node_id) > 0) { node[0] = local_node_id; node[1] = remote_node_id; } else { node[0] = remote_node_id; node[1] = local_node_id; } return towire_channel_announcement(ctx, &zerosig, &zerosig, &zerosig, &zerosig, features, &chainparams->genesis_blockhash, scid, node[0], node[1], &dummy_pubkey, &dummy_pubkey); }
<gh_stars>1000+ #ifndef CODE_ParametersSolo #define CODE_ParametersSolo #include <array> #include "IncludeDefine.h" #include "SoloBarcode.h" #include "SoloFeatureTypes.h" class Parameters; class ParametersSolo; class UMIdedup { public: const static uint32 tN = 6; array<string,tN> typeNames { {"NoDedup", "Exact", "1MM_All", "1MM_Directional", "1MM_CR", "1MM_Directional_UMItools"} }; enum typeI : int32 { NoDedup=0, Exact=1, All=2, Directional=3, CR=4, Directional_UMItools=5 }; struct { uint32_t N; array<bool,tN> B; bool &NoDedup=B[0], &Exact=B[1], &All=B[2], &Directional=B[3], &CR=B[4], &Directional_UMItools=B[5]; } yes; struct { //uint32_t N; array<uint32_t,tN> I; uint32_t &NoDedup=I[0], &Exact=I[1], &All=I[2], &Directional=I[3], &CR=I[4], &Directional_UMItools=I[5]; uint32_t main; //index for SAM/stats/filtering output } countInd; //index in the countCellGennUMI vector<string> typesIn; //UMIdedup types from user options vector<int32> types; //the above converted to typeI numbers int32 typeMain; //the type to be used in SAM/stats/filtering output - for now just types[0] void initialize(ParametersSolo *pS); //protected: // int it; }; class MultiMappers { public: const static uint32 tN = 5; array<string,tN> typeNames { {"Unique", "Uniform", "Rescue", "PropUnique", "EM"} }; enum typeI : int32 { Unique=0, Uniform=1, Rescue=2, PropUnique=3, EM=4 }; struct { bool multi; //if multimappers are requested uint32_t N; array<bool,tN> B; bool &Unique=B[0], &Uniform=B[1], &Rescue=B[2], &PropUnique=B[3], &EM=B[4] ; } yes; struct { //uint32_t N; array<uint32_t,tN> I; uint32_t &Unique=I[0], &Uniform=I[1], &Rescue=I[2], &PropUnique=I[3], &EM=I[4]; uint32_t main; //index for SAM/stats/filtering output } countInd; //index in the countCellGennUMI vector<string> typesIn; //UMIdedup types from user options vector<int32> types; //the above converted to typeI numbers int32 typeMain; //the type to be used in SAM/stats/filtering output - for now just types[0] void initialize(ParametersSolo *pS); }; class ParametersSolo { public: Parameters *pP; bool yes; //chemistry, library etc string typeStr; enum SoloTypes : int32 {None=0, CB_UMI_Simple=1, CB_UMI_Complex=2, CB_samTagOut=3, SmartSeq=4}; SoloTypes type; string strandStr; int32 strand; uint32 barcodeRead, barcodeReadIn;//which read is the barcode read = 0,1,2? uint32 barcodeStart, barcodeEnd;//start/end of barcode sequence on barcodeRead bool barcodeReadSeparate; //simple barcodes uint32 cbS, cbL; //cell barcode start,length uint32 umiS, umiL; //umi start,length uint32 bL, cbumiL; //total barcode sequene length, CB+UMI length. Former does may not be equal to the latter vector<string> cbPositionStr; string umiPositionStr; //complex barcodes vector<SoloBarcode> cbV; SoloBarcode umiV; //single UMI bool adapterYes; //anchor? string adapterSeq; //anchor sequence uint32 adapterMismatchesNmax;//max number of mismatches in the anchor //input from SAM files vector<string> samAtrrBarcodeSeq, samAtrrBarcodeQual; //whitelist - general uint64 cbWLsize; bool cbWLyes; vector<string> soloCBwhitelist; vector <uint64> cbWL; vector<string> cbWLstr; MultiMappers multiMap; //features vector<string> featureIn;//string of requested features vector<uint32> features; uint32 nFeatures;//=features.size(), number of requested features array<bool,SoloFeatureTypes::N> featureYes; //which features are requested array<bool,SoloFeatureTypes::N> readInfoYes;//which features will need readInfo (for now only Gene and GeneFull) array<bool,SoloFeatureTypes::N> readIndexYes;//which features will need recording of readIndex (for now only Gene and GeneFull, for multimappers) array<int32,SoloFeatureTypes::N> featureInd;//index of each feature - skips unrequested features //filtering char QSbase,QSmax;//quality score base and cutoff #ifdef MATCH_CellRanger double cbMinP;//for CBs with non-exact matching to WL, min posterior probability #else float cbMinP;//for CBs with non-exact matching to WL, min posterior probability #endif //cell filtering struct { vector<string> type; uint32 topCells; struct { double nExpectedCells; double maxPercentile; double maxMinRatio; } knee; struct { uint32 indMin, indMax; //min/max cell index, sorted by UMI counts,for empty cells uint32 umiMin; double umiMinFracMedian; uint32 candMaxN; double FDR; uint32 simN; } eDcr;//EmptyDrops-CellRanger } cellFilter; //CB match struct { string type; bool mm1; //1 mismatch allowed bool mm1_multi; //1 mismatch, multiple matches to WL allowed bool oneExact; //CBs require at least one exact match bool mm1_multi_pc; //use psedocounts while calculating probabilities of multi-matches bool mm1_multi_Nbase; //allow multimatching to WL for CBs with N-bases } CBmatchWL; //UMIdedup UMIdedup umiDedup; //multi-gene umi struct { vector<string> type; bool MultiGeneUMI = false; bool MultiGeneUMI_All = false; bool yes = false; //true for non-CR bool MultiGeneUMI_CR = false; } umiFiltering; //clusters string clusterCBfile; //output vector<string> outFileNames; struct { string featuresGeneField3; } outFormat; bool samAttrYes;//post-processed SAM attributes: error-corrected CB and UMI int32 samAttrFeature;//which feature to use for error correction //processing uint32 redistrReadsNfiles; //numer of files to resditribute reads into //constants uint32 umiMaskLow, umiMaskHigh; //low/high half bit-mask or UMIs void initialize(Parameters *pPin); void umiSwapHalves(uint32 &umi); void complexWLstrings(); void cellFiltering(); }; #endif
// ATMEL Microcontroller Software Support - Colorado Springs, CO - // ---------------------------------------------------------------------------- // DISCLAIMER: THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR // IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE // DISCLAIMED. IN NO EVENT SHALL ATMEL 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. // ---------------------------------------------------------------------------- /** \file * \brief AES132 Helper Functions * \author <NAME>, Atmel Bali Team * \date June 12, 2013 */ #include <stdio.h> #include <stdint.h> #include <string.h> #include "aes132_helper.h" #include "aes132_impl.h" #include "aes132_comm_marshaling.h" // Include the AES engine header here #include "ataes.h" //--------------------------- // Static function prototype //--------------------------- static uint8_t aes132crypt_generate_encrypt(struct aes132crypt_in_out *param); static uint8_t aes132crypt_decrypt_verify(struct aes132crypt_in_out *param); static uint8_t aes132crypt_nonce(struct aes132crypt_nonce_in_out *param); static void aes132crypt_aes_engine_encrypt(uint8_t *data, uint8_t *key, uint8_t init_flag); static void aes132crypt_cbc_block(struct aes132crypt_in_out *param, uint8_t *output); static void aes132crypt_ctr_block(struct aes132crypt_ctr_block_in_out *param); //---------------------- // Function definitions //---------------------- uint8_t aes132_rng(uint8_t rnd[16]) { uint8_t tx[256] = {0}, rx[256] = {0}; uint8_t ret = aes132m_execute(AES132_OPCODE_RANDOM, 0, 0, 0, 0, NULL, 0, NULL, 0, NULL, 0, NULL, tx, rx); if(ret == AES132_FUNCTION_RETCODE_SUCCESS) { memcpy(rnd, rx + 2, 16); } return ret; } /** \brief This is a wrapper function for AES-ECB encryption. User can modify this function depending on their implementation of AES engine. * * 128-bit (16-byte) input cleartext and output encrypted data are passed using pointer "data", and 128-bit (16-byte) AES key are passed using pointer "key". * This AES wrapper function is the building block for cryptographic calculation functions. * * Depending on the AES engine used, the parameter "init_flag" is used to initialize AES context. * Note that AES context (implementation-dependent) should be defined as static variable inside this function. * If the AES engine does not have initialization step (e.g. uses on-the-fly keying), code portion for init_flag = TRUE can be left blank. * * \param [in,out] data" Pointer to 16-byte input and output data. * \param [in] key" Pointer to 16-byte encryption key. * \param [in] init_flag" A flag to indicate initialization step. Set to TRUE to initialize, FALSE to encrypt. */ static void aes132crypt_aes_engine_encrypt(uint8_t *data, uint8_t *key, uint8_t init_flag) { // ------------------------------------------------------------ // This is an example of AES engine using precomputed RoundKey // ------------------------------------------------------------ // Declare AES context here. // Declare as static so the context is saved for next calculation with the same key static aes_context ctx; if (init_flag == TRUE) { // Call AES context initialization (RoundKey calculation) here aes_set_key(key, 16, &ctx); } else { // Call AES encryption calculation here // Input and output are passed in the pointer "data" at_aes_encrypt(data, data, &ctx); } /* // ----------------------------------------------------------- // This is an example of AES engine using on-the-fly RoundKey // ----------------------------------------------------------- // This is the output key generated by the engine, discard it uint8_t o_key[16]; if (init_flag == TRUE) { // No context initialization for engine with on the fly keying } else { // Call AES encryption calculation here // Input and output are passed in the pointer "data" aes_encrypt_128(data, data, key, o_key); } */ } /** \brief This function does the Generation-Encryption Process as described in NIST Special Publication 800-38C, section 6.1. * * The input data to this function are "nonce", "payload", and "associated_data". * These inputs are processed using AES-CCM with the key passed in parameter "key". * The outputs are authentication value "auth_value" and encrypted data "ciphertext". * * This function is used in majority of ATAES132 commands which uses "MAC Generation" and/or "Data Encryption". * For commands that do not encrypt data (for example Auth), "payload" can be set to NULL and "plen_bytes" set to 0. * The InMac or OutMac for ATAES132 commands is returned in "auth_value", while the encrypted InData or OutData is returned in "ciphertext". * * Example for Auth command, Outbound, with optional authenticate field SerialNum[0:7] : * - "nonce" contains concatenation of 12-byte Nonce and 1-byte MacCount * - "payload" is set to NULL * - "plen_bytes" is set to 0 * - "associated_data" contains 30-byte authenticate-only data specified in ATAES132 datasheet (Section I.6 in 8760A-CRYPTO-5/11). * For this example, this is concatenation of: * 2-byte ManufacturingID, 1-byte Opcode (0x03), 1-byte Mode, 2-byte Param1, 2-byte Param2, 1-byte MacFlag, 4-byte 0x00, 1-byte 0x00, * 4-byte 0x00, 8-byte SerialNum[0:7], 4-byte 0x00. * - "alen_bytes" is set to 30 * - "key" contains key used in the computation * - The 16-byte OutMac will be returned in "auth_value" * * Example for EncWrite command with 16 bytes data: * - "nonce" contains concatenation of 12-byte Nonce and 1-byte MacCount * - "payload" contains the cleartext data to be written * - "plen_bytes" is set to 16 * - "associated_data" contains 14-byte authenticate-only data specified in ATAES132 datasheet (Section I.20 in 8760A-CRYPTO-5/11). * For this example, this is concatenation of: * 2-byte ManufacturingID, 1-byte Opcode (0x05), 1-byte Mode, 2-byte Param1, 2-byte Param2, 1-byte MacFlag, 5-byte 0x00. * - "alen_bytes" is set to 14 * - "key" contains key used in the computation * - The 16-byte InMac will be returned in "auth_value", and 16-byte InData will be returned in "ciphertext" * * \param [in,out] param Pointer to structure for input/output parameters. Refer to aes132crypt_in_out. * \return status of the operation. */ uint8_t aes132crypt_generate_encrypt(struct aes132crypt_in_out *param) { // Local variables uint8_t temp1[16]; struct aes132crypt_ctr_block_in_out ctr_param; // Initialize AES engine aes132crypt_aes_engine_encrypt(NULL, param->key, TRUE); // Perform CBC blocks aes132crypt_cbc_block(param, temp1); // Perform CTR blocks ctr_param.auth_value_in = temp1; ctr_param.data_in = param->payload; ctr_param.plen_bytes = param->plen_bytes; ctr_param.nonce = param->nonce; ctr_param.key = param->key; ctr_param.auth_value_out = param->auth_value; ctr_param.data_out = param->ciphertext; aes132crypt_ctr_block(&ctr_param); return AES132_FUNCTION_RETCODE_SUCCESS; } /** \brief This function does the Decryption-Verification Process as described in NIST Special Publication 800-38C, section 6.1. * * The input data to this function are "nonce", "auth_value", "ciphertext", and "associated_data". * These inputs are processed using AES-CCM with the key passed in parameter "key". * The output is the decrypted cleartext data, "payload". * * This function is used in ATAES132 commands which uses "MAC Generation" and "Data Decryption". * The InMac or OutMac for ATAES132 commands is passed in "auth_value", while the decrypted InData or OutData is returned in "payload". * * Example for EncRead command with 32 bytes data, * - "nonce" contains concatenation of 12-byte Nonce and 1-byte MacCount * - "auth_value" contains OutMac from the EncRead command * - "ciphertext" contains OutData from the EncRead command * - "plen_bytes" is set to 32 (32 bytes of data) * - "associated_data" contains 14-byte authenticate-only data specified in ATAES132 datasheet (Section I.16 in 8760A-CRYPTO-5/11). * For this example, this is concatenation of: * 2-byte ManufacturingID, 1-byte Opcode (0x04), 1-byte Mode, 2-byte Param1, 2-byte Param2, 1-byte MacFlag, 5-byte 0x00. * - "alen_bytes" is set to 14 * - "key" contains key used in the computation * - The cleartext data will be returned in "payload" * * \param [in,out] param Pointer to structure for input/output parameters. Refer to aes132crypt_in_out. * \return status of the operation. */ uint8_t aes132crypt_decrypt_verify(struct aes132crypt_in_out *param) { // Local variables uint8_t temp1[16]; uint8_t temp2[16]; struct aes132crypt_ctr_block_in_out ctr_param; // Initialize AES engine aes132crypt_aes_engine_encrypt(NULL, param->key, TRUE); // Perform CTR blocks ctr_param.auth_value_in = param->auth_value; ctr_param.data_in = param->ciphertext; ctr_param.plen_bytes = param->plen_bytes; ctr_param.nonce = param->nonce; ctr_param.key = param->key; ctr_param.auth_value_out = temp2; ctr_param.data_out = param->payload; aes132crypt_ctr_block(&ctr_param); // Perform CBC blocks aes132crypt_cbc_block(param, temp1); // Verify the cleartext MAC T temp2[] against calculated temp1[] if (memcmp(temp2, temp1, 16) == 0) { return AES132_FUNCTION_RETCODE_SUCCESS; } else { // As mandated by NIST Special Publication 800-38C, section 6.2, // if verification fails, the payload shall not be revealed. // We reset the payload to all 0's memset(param->payload, 0, param->plen_bytes); return AES132_DEVICE_RETCODE_MAC_ERROR; } } /** \brief This function does one pass of Matyas-Meyer-Oseas compression function. * * The function can be used to generate random nonce for Nonce and NonceCompute commands in ATAES132. * These are described in ATAES132 datasheet (Appendix I.31 and I.32 in 8760A-CRYPTO-5/11). * Please refer to ATAES132 datasheet for data_in (block A in datasheet) and key (block B in datasheet) formatting. * * All inputs are 16-byte, and output is also 16-byte. * To be used as Nonce for ATAES132 device, the output must be truncated to the first 12 bytes. * * \param [in,out] param Pointer to structure for input/output parameters. Refer to aes132crypt_nonce_in_out. * \return status of the operation. */ uint8_t aes132crypt_nonce(struct aes132crypt_nonce_in_out *param) { // Local variables uint8_t i; // Initialize AES engine aes132crypt_aes_engine_encrypt(NULL, param->key, TRUE); // Run AES for input data memcpy(param->data_out, param->data_in, 16); aes132crypt_aes_engine_encrypt(param->data_out, param->key, FALSE); // XOR the result with input data for (i = 0; i < 16; i++) { param->data_out[i] ^= param->data_in[i]; } return AES132_FUNCTION_RETCODE_SUCCESS; } /** \brief This function implements CBC blocks for AES-CCM computation used by ATAES132 device. * * The formatting function for input data is included in this function. * * \param [in] param Pointer to structure for input/output parameters. Refer to aes132crypt_in_out. * \param [out] output Pointer to 16-byte MAC (called T in NIST Special Publication 800-38C, or "cleartext MAC" in ATAES132 datasheet). */ static void aes132crypt_cbc_block(struct aes132crypt_in_out *param, uint8_t *output) { // Local variables uint8_t temporary[16]; uint8_t *p_input; uint8_t alen_remaining; uint8_t plen_remaining; uint8_t pass; uint8_t i; //----------------------------- // CBC block // output[] (provided by caller) is used to hold Y_n // temporary[] is used to hold B_n //----------------------------- // Initialize values memset(output, 0x00, 16); alen_remaining = param->alen_bytes; plen_remaining = param->plen_bytes; pass = 0; // To save memory space, the CBC mode operations (block B) are done serially // pass is used to indicate the index of B (B_pass) do { // Input is initialized to point to temporary array for filling p_input = temporary; if (pass == 0) { // First block B_0 // See table 2 app A.2.1 NIST SP800-38C // Byte 0: Flag // The flag consists of: // Bit 7 Reserved = 0 // 6 Adata, = 1 if there is associated data, = 0 otherwise // 5:3 Encoding of tag length t: (t-2)/2. For AES132 t=16, (t-2)/2= 7 // 2:0 Encoding of length of Q (encoding of payload length) q: (q-1). For AES132 q=2, (q-1)= 1 if (param->alen_bytes > 0) { *p_input++ = (1 << 6) | (7 << 3) | (1); } else { *p_input++ = (7 << 3) | (1); } // Byte 1 to 15-2 (13): N (13-byte nonce) memcpy(p_input, param->nonce, 13); p_input += 13; // Byte 13 to 15: Q (message/payload length) // For AES132, Q <= 32, so MSByte always zero *p_input++ = 0x00; *p_input++ = param->plen_bytes; // Point input back to the temporary array p_input = temporary; } else if (alen_remaining > 0) { if (pass == 1) { // Second block B_1 // Byte 0 to 1: encoding of a (length of associated data) // For AES132, a <= 30, so MSByte always zero. Max 255 bytes of associated data. *p_input++ = 0x00; *p_input++ = param->alen_bytes; // Byte 2 to 15: first 14 bytes of associated data if (alen_remaining < 14) { memcpy(p_input, param->associated_data, alen_remaining); p_input += alen_remaining; // If associated data is 14 bytes or less, pad with 0x00's memset(p_input, 0x00, (14 - alen_remaining)); alen_remaining = 0; } else { memcpy(p_input, param->associated_data, 14); alen_remaining -= 14; } // Point input back to the temporary array p_input = temporary; } else { // Next blocks (B_2 ... B_u) // Byte 0 to 15: next 16 bytes of associated data if (alen_remaining < 16) { memcpy(p_input, &param->associated_data[(param->alen_bytes)-alen_remaining], alen_remaining); p_input += alen_remaining; // If associated data is less than 16 bytes, pad with 0x00's memset(p_input, 0x00, (16 - alen_remaining)); // Point input back to the temporary array p_input = temporary; alen_remaining = 0; } else { // Point input directly to the data p_input = &param->associated_data[(param->alen_bytes)-alen_remaining]; alen_remaining -= 16; } } } else if (plen_remaining > 0) { // Next blocks (B_u+1 ... B_r) // Byte 0 to 15: next 16 bytes of payload if (plen_remaining < 16) { memcpy(p_input, &param->payload[(param->plen_bytes)-plen_remaining], plen_remaining); p_input += plen_remaining; // If payload is less than 16 bytes, pad with 0x00's memset(p_input, 0x00, (16 - plen_remaining)); // Point input back to the temporary array p_input = temporary; plen_remaining = 0; } else { // Point input directly to the data p_input = &param->payload[(param->plen_bytes)-plen_remaining]; plen_remaining -= 16; } } // XOR B_i with Y_i and put in Y_i for (i = 0; i < 16; i++) { output[i] ^= *p_input++; } // Run AES aes132crypt_aes_engine_encrypt(output, param->key, FALSE); // Y_i is now in array output // Increment pass pass++; } while ((alen_remaining > 0) || (plen_remaining > 0)); // T (Y_r) is now in output[] // Because t is fixed to 16, T = MSB_t_bytes(Y_r) = Y_r } /** \brief This function implements CTR blocks for AES-CCM computation used by ATAES132 device. * * The formatting function for counter blocks is included in this function. * The encryption and decryption process is the same using CTR. * For encryption, auth_value_in and data_in are set to cleartext MAC (T) and payload (cleartext data), respectively. * The encrypted MAC and ciphertext are returned in auth_value_out and data_out, respectively. * For decryption, auth_value_in and data_in are set to encrypted MAC and ciphertext, respectively. * The cleartext MAC and payload (cleartext data) are returned in auth_value_out and data_out, respectively. * * \param [in, out] param Pointer to structure for input/output parameters. Refer to aes132crypt_ctr_block_in_out. */ static void aes132crypt_ctr_block(struct aes132crypt_ctr_block_in_out *param) { // Local variables uint8_t *p_ctr; uint8_t *p_data_in; uint8_t *p_data_out; uint8_t plen_remaining; uint8_t ctr_enc[16]; uint8_t ctr[16]; uint8_t i; //----------------------------- // Counter blocks //----------------------------- // Prepare first counter block Ctr_0 // ctr[] is used to hold Ctr_j p_ctr = ctr; // Byte 0: flag, bit 7:3 = 0, bit 2:0 = (q-1) = 1 *p_ctr++ = (1); // Byte 1 to 13: N (13-byte nonce) memcpy(p_ctr, param->nonce, 13); p_ctr += 13; // Byte 14 to 15: i (counter) *p_ctr++ = 0x00; *p_ctr++ = 0x00; // Point to first payload p_data_in = param->data_in; p_data_out = param->data_out; plen_remaining = param->plen_bytes; do { // Copy Ctr_j to S_j for encryption memcpy(ctr_enc, ctr, 16); // Run AES aes132crypt_aes_engine_encrypt(ctr_enc, param->key, FALSE); // S_j is now in array ctr_enc[] // If counter byte = 0, it is the first pass, encrypt/decrypt auth_value // Otherwise, it is second and subsequent pass, encrypt/decrypt payload if (ctr[15] == 0) { // XOR input auth value with S_j and put in output auth value for (i = 0; i < 16; i++) { param->auth_value_out[i] = param->auth_value_in[i] ^ ctr_enc[i]; } } else { // XOR input data with S_j and put in output if (plen_remaining < 16) { // Encrypt/decrypt only the remaining bytes for (i = 0; i < plen_remaining; i++) { *p_data_out++ = *p_data_in++ ^ ctr_enc[i]; } // Pad with 0x00's to fill 16-byte block for (; i < 16; i++) { *p_data_out++ = 0x00 ^ ctr_enc[i]; } plen_remaining = 0; } else { // Encrypt/decrypt 16 bytes (one block) for (i = 0; i < 16; i++) { *p_data_out++ = *p_data_in++ ^ ctr_enc[i]; } plen_remaining -= 16; } } // Increment the counter. Counter is in block Ctr byte 14 and 15. // We only use the LSByte, so payload is max 255 blocks ctr[15]++; } while (plen_remaining > 0); } /** \brief This function generates or store a 12-byte nonce for use by the helper functions. * * Upon successful execution, the "nonce" struct is updated by this function: * - The value (nonce[0] to nonce[11]) is filled by the nonce * - MacCount (nonce[12]) is reset to zero * - Valid flag is set * The two modes are supported, random nonce and inbound nonce, determined by mode parameter. * If using inbound nonce, "random" parameter is not used and can take NULL value. * * \param [in,out] param Pointer to structure for input/output parameters. Refer to aes132h_nonce_in_out. * \return status of the operation. */ uint8_t aes132h_nonce(struct aes132h_nonce_in_out *param) { uint8_t ret_code; struct aes132crypt_nonce_in_out aes132crypt_nonce_param; uint8_t block_a[16]; uint8_t block_b[16]; uint8_t data_out[16]; // Check parameters if ( ((param->mode & ~0x03) != 0) || (!param->random && ((param->mode & 0x01) != 0)) || (!param->in_seed) || (!param->nonce) ) return AES132_FUNCTION_RETCODE_BAD_PARAM; // Check mode parameter bit 0 (Random/Inbound) and do appropriate operations if (param->mode & 0x01) { // Assemble block A and B block_a[0] = AES132_OPCODE_NONCE; block_a[1] = param->mode; block_a[2] = 0x00; block_a[3] = 0x00; memcpy(&block_a[4], param->in_seed, 12); block_b[0] = AES132_MANUFACTURING_ID >> 8; block_b[1] = AES132_MANUFACTURING_ID & 0xFF; block_b[2] = 0x00; block_b[3] = 0x00; memcpy(&block_b[4], param->random, 12); // Execute cryptographic algorithm aes132crypt_nonce_param.data_in = block_a; aes132crypt_nonce_param.key = block_b; aes132crypt_nonce_param.data_out = data_out; ret_code = aes132crypt_nonce(&aes132crypt_nonce_param); if (ret_code != AES132_FUNCTION_RETCODE_SUCCESS) return ret_code; // Copy the first 12-byte as a nonce value memcpy(param->nonce->value, data_out, 12); // Set the random flag to TRUE (Random nonce) param->nonce->random = TRUE; } else { // Copy the InSeed as a nonce value memcpy(param->nonce->value, param->in_seed, 12); // Set the random flag to FALSE (Inbound nonce) param->nonce->random = FALSE; } // Reset the MacCount, set the valid flag param->nonce->value[12] = 0x00; param->nonce->valid = TRUE; return AES132_FUNCTION_RETCODE_SUCCESS; } /** \brief This function converts 4-byte CountValue output from Counter command to integer counts. * * "count_integer" will take value between 0 to 2097151. * Bad parameter error is returned if count_value has illegal value. * * \param [in] count_value Pointer to 4-byte CountValue. * \param [out] count_integer Pointer to 32-bit integer representing current value of the counter. * \return status of the operation. */ uint8_t aes132h_decode_count_value(uint8_t *count_value, uint32_t *count_integer) { uint8_t lin_count; uint8_t count_flag; uint16_t bin_count; uint8_t int_lin_count; // Check parameters if (!count_value || !count_integer) return AES132_FUNCTION_RETCODE_BAD_PARAM; // Extract LinCount, CountFlag, and BinCount from CountValue byte 0 lin_count = count_value[0]; count_flag = count_value[1]; bin_count = (count_value[2] << 8) + count_value[3]; // Check CountFlag and LinCount validity // CountFlag can only take values 0, 2, 4, 6. So, check by masking with 00000110b. // 2's complement of LinCount must be power of 2. Check if it's the case, based on trick from // http://graphics.stanford.edu/~seander/bithacks.html#DetermineIfPowerOf2 if ( ((count_flag & ~(0x06)) != 0) || (lin_count == 0) || ((((uint8_t) ~lin_count) + 1) & ((uint8_t) ~lin_count)) ) return AES132_FUNCTION_RETCODE_BAD_PARAM; // Convert LinCount to integer int_lin_count = 7; while (lin_count <<= 1) { int_lin_count--; } // Calculate the result, which is: BinCount*32 + (CountFlag/2)*8 + integer(LinCount) *count_integer = (bin_count << 5) + (count_flag << 2) + int_lin_count; return AES132_FUNCTION_RETCODE_SUCCESS; } /** \brief This function converts integer counts to a 8-byte value to be written to Counter field in ATAES132 configuration memory. * * "count_integer" input is maximum 2097151. * Bad parameter error is returned if count_integer takes value higher than this maximum. * User must provide enough space for "counter". * * \param [in] count_integer 32-bit integer representing the desired value of the counter. * \param [out] counter_field Pointer to 8-byte Counter field to be written to Configuration Area. * \return status of the operation. */ uint8_t aes132h_encode_counter_field(uint32_t count_integer, uint8_t *counter_field) { uint8_t lin_count; uint8_t count_flag; uint16_t bin_count; // Check parameters if ((!counter_field) || (count_integer > AES132_COUNTER_MAX)) return AES132_FUNCTION_RETCODE_BAD_PARAM; // Extract BinCount, CountFlag, and LinCount from intended integer counter bin_count = count_integer >> 5; // count_integer / 32; count_integer %= 32; count_flag = (count_integer >> 3) << 1; // (count_integer / 8) << 1; count_integer %= 8; lin_count = 0xFF << count_integer; // Reset all LinCount to zero first counter_field[0] = 0x00; counter_field[1] = 0x00; counter_field[2] = 0x00; counter_field[3] = 0x00; // Put BinCount on both BinCountA and BinCountB counter_field[4] = bin_count & 0xFF; counter_field[5] = bin_count >> 8; counter_field[6] = bin_count & 0xFF; counter_field[7] = bin_count >> 8; // Update the fields depending on CountFlag switch (count_flag) { case 0: // LSB of LinCountA = LinCount, MSB of LinCountA = 0 // LinCountB = 0 // BinCountB = BinCount - 1, clip to 0 // BinCountA = BinCount counter_field[0] = lin_count; counter_field[1] = 0xFF; if (bin_count != 0) { counter_field[4] = ((bin_count - 1) & 0xFF); counter_field[5] = ((bin_count - 1) >> 8); } break; case 2: // LSB of LinCountA = 0, MSB of LinCountA = LinCount // LinCountB = 0 // BinCountB = BinCount - 1, clip to 0 // BinCountA = BinCount counter_field[1] = lin_count; if (bin_count != 0) { counter_field[4] = ((bin_count - 1) & 0xFF); counter_field[5] = ((bin_count - 1) >> 8); } break; case 4: // LinCountA = 0 // LSB of LinCountB = LinCount, MSB of LinCountB = 0xFF // BinCountB = BinCount, BinCountA = BinCount counter_field[2] = lin_count; counter_field[3] = 0xFF; break; case 6: // LinCountA = 0 // LSB of LinCountB = LinCount, MSB of LinCountB = 0 // BinCountB = BinCount, BinCountA = BinCount counter_field[3] = lin_count; break; } return AES132_FUNCTION_RETCODE_SUCCESS; } /** \brief This function assembles FirstBlock and SecondBlock for use in ATAES132 host commands. * * It is used when application uses second ATAES132 for host functionality, instead of the helper functions. * The blocks are assembled according to input parameters, which is passed using "aes132h_build_auth_block_in_out" struct. All unused pointer parameters can take NULL value. * In addition, user must also provide a random flag, which indicates whether the client (first ATAES132 device) uses random or inbound nonce when running its command. * * Host commands supported: * - AuthCheck, first_block is 11 bytes * For use with commands: Auth Outbound, Auth Mutual, Counter Read * - AuthCompute, first_block is 11 bytes * For use with commands: Auth Inbound, Auth Mutual, Counter Increment * - DecRead, first_block is 6 bytes * For use with command: EncRead * - KeyExport, first_block is 6 bytes * For use with command: KeyLoad * - KeyImport, first_block is 6 bytes * For use with commands: KeyCreate, KeyExport (Mode:0 = 0) * - WriteCompute, first_block is 6 bytes * For use with command: EncWrite * * first_block is always built, regardless of mode parameter. * second_block is built if any one of optional authenticate fields are selected in mode bit 7-5 (usage_counter, serial_num, small_zone). second_block is 16 bytes for all commands. * * User must provide enough space for first_block (always used) and second_block (if used). * * \param [in,out] param Pointer to structure for input/output parameters. Refer to aes132h_build_auth_block_in_out. * \return status of the operation. */ uint8_t aes132h_build_auth_block(struct aes132h_build_auth_block_in_out *param) { uint8_t *p_first_block; // Check parameters if ( (!param->first_block) || ((param->mode & 0x20) && !param->usage_counter) || ((param->mode & 0x40) && !param->serial_num) || ((param->mode & 0x80) && !param->small_zone) || ((param->mode & 0xE0) && !param->second_block) || ((param->opcode == AES132_OPCODE_COUNTER) && !param->count_value) ) return AES132_FUNCTION_RETCODE_BAD_PARAM; // Fill in the FirstBlock p_first_block = param->first_block; // First byte is the Opcode for AuthCompute and AuthCheck, Mode for other commands if ( (param->host_opcode == AES132_OPCODE_AUTH_COMPUTE) || (param->host_opcode == AES132_OPCODE_AUTH_CHECK)) { *p_first_block++ = param->opcode; } *p_first_block++ = param->mode; *p_first_block++ = param->param1 >> 8; *p_first_block++ = param->param1 & 0xFF; *p_first_block++ = param->param2 >> 8; *p_first_block++ = param->param2 & 0xFF; // Check whether the MAC is used as input or output if ( (param->host_opcode == AES132_OPCODE_AUTH_COMPUTE) || (param->host_opcode == AES132_OPCODE_WRITE_COMPUTE) || (param->host_opcode == AES132_OPCODE_KEY_EXPORT)) { // MAC used as input to device, Input bit (bit 1) always 1 *p_first_block++ = (param->random)? (AES132_MAC_FLAG_RANDOM | AES132_MAC_FLAG_INPUT): AES132_MAC_FLAG_INPUT; } else { // MAC is output from device, Input bit (bit 1) always 0 *p_first_block++ = (param->random)? AES132_MAC_FLAG_RANDOM: 0x00; } // For Counter command, fill with the CountValue if ( (param->host_opcode == AES132_OPCODE_AUTH_COMPUTE) || (param->host_opcode == AES132_OPCODE_AUTH_CHECK)) { if (param->opcode == AES132_OPCODE_COUNTER) { memcpy(p_first_block, param->count_value, 4); } else { memset(p_first_block, 0x00, 4); } } // Append additional data to SecondBlock if specified by mode parameter if (param->mode & 0xE0) { if (param->mode & 0x20) { memcpy(&param->second_block[0], param->usage_counter, 4); } else { memset(&param->second_block[0], 0x00, 4); } if (param->mode & 0x40) { memcpy(&param->second_block[4], param->serial_num, 8); } else { memset(&param->second_block[4], 0x00, 8); } if (param->mode & 0x80) { memcpy(&param->second_block[12], param->small_zone, 4); } else { memset(&param->second_block[12], 0x00, 4); } } return AES132_FUNCTION_RETCODE_SUCCESS; } /** \brief This function generates authentication/integrity MAC and encrypts data for use in ATAES132 commands. * * Operations supported by this function: * - Generate InMac for Auth, Inbound-only (Mode[1:0] = 01b) * - Generate InMac for Auth, Mutual (Mode[1:0] = 11b) * - Generate InMac for Counter increment (Mode[1:0] = 10b) * - Encrypt InData and generate InMac for EncWrite * - Encrypt InData and generate InMac for Decrypt * - Encrypt InData and generate InMac for KeyLoad * - Generate InMac for Lock ZoneConfig[Zone].ReadOnly (Mode[1:0] = 11b) * * All unused pointer in parameter struct can take NULL value. * The use of second authentication blocks (usage_counter, serial_num, small_zone) is determined by mode bit 7-5. * count_value is used only for Counter command, and not used for other commands. * in_mac is never used for this function. * * The "nonce" struct has to be passed with valid member set to TRUE, otherwise the function returns with error. * The "nonce" struct is updated by this function: * - If MacCount has reached maximum value (255), valid flag is cleared * - MacCount (nonce[12]) is incremented * * The function returns with bad parameter error if: * - Passed with opcode/mode combination that is not supported * - At least one of used pointer parameters has NULL value * * User must provide enough space for output parameters (out_mac and out_data). * * \param [in,out] param Pointer to structure for input/output parameters. Refer to aes132h_in_out. * \return status of the operation. */ uint8_t aes132h_mac_compute_encrypt(struct aes132h_in_out *param) { uint8_t ret_code; struct aes132crypt_in_out aes132crypt_param; uint8_t associated_data[30]; // Check parameters if ( (!param->key) || (!param->nonce) || (!param->out_mac) || ((param->mode & 0x20) && !param->usage_counter) || ((param->mode & 0x40) && !param->serial_num) || ((param->mode & 0x80) && !param->small_zone) || ((param->opcode == AES132_OPCODE_COUNTER) && !param->count_value) || (((param->opcode == AES132_OPCODE_ENC_WRITE) || (param->opcode == AES132_OPCODE_DECRYPT) || (param->opcode == AES132_OPCODE_KEY_LOAD)) && (!param->in_data || !param->out_data)) ) return AES132_FUNCTION_RETCODE_BAD_PARAM; // Check nonce validity if (param->nonce->valid == FALSE) return AES132_DEVICE_RETCODE_NONCE_ERROR; // Arrange associated_data (see ATAES132 datasheet appendix I) associated_data[0] = AES132_MANUFACTURING_ID >> 8; associated_data[1] = AES132_MANUFACTURING_ID & 0xFF; associated_data[2] = param->opcode; associated_data[3] = param->mode; associated_data[4] = param->param1 >> 8; associated_data[5] = param->param1 & 0xFF; associated_data[6] = param->param2 >> 8; associated_data[7] = param->param2 & 0xFF; associated_data[8] = (param->nonce->random)? (AES132_MAC_FLAG_RANDOM | AES132_MAC_FLAG_INPUT): AES132_MAC_FLAG_INPUT; // Input bit (bit 1) always 1 if (param->opcode == AES132_OPCODE_COUNTER) { memcpy(&associated_data[9], param->count_value, 4); } else { memset(&associated_data[9], 0x00, 4); } associated_data[13] = 0x00; // Append additional associated_data if specified by mode parameter if (param->mode & 0x20) { memcpy(&associated_data[14], param->usage_counter, 4); } else { memset(&associated_data[14], 0x00, 4); } if (param->mode & 0x40) { memcpy(&associated_data[18], param->serial_num, 8); } else { memset(&associated_data[18], 0x00, 8); } if (param->mode & 0x80) { memcpy(&associated_data[26], param->small_zone, 4); } else { memset(&associated_data[26], 0x00, 4); } // Check if Client Decryption mode, set MacCount to EMacCount, adjust associated_data to suit if ((param->opcode == AES132_OPCODE_DECRYPT) && (param->param2 & 0xFF00)) { param->nonce->value[12] = (uint8_t) (param->param2 >> 8); associated_data[2] = AES132_OPCODE_ENCRYPT; // Use Encrypt opcode associated_data[4] = 0x00; // Upper byte of Param1 is 0 associated_data[6] = 0x00; // Upper byte of Param2 is 0 associated_data[8] &= ~AES132_MAC_FLAG_INPUT; // MacFlag:Input is 0 } // Increment MacCount before operation. Invalidate nonce if MacCount has reached max if (param->nonce->value[12] == 255) { param->nonce->valid = FALSE; } param->nonce->value[12]++; // Do the cryptographic calculation // Check if additional auth-only field is used aes132crypt_param.alen_bytes = (param->mode & 0xE0)? 30: 14; // The length is passed in "Param2" for encryption commands, and 16 for KeyLoad if ((param->opcode == AES132_OPCODE_ENC_WRITE) || (param->opcode == AES132_OPCODE_DECRYPT)) { aes132crypt_param.plen_bytes = param->param2 & 0xFF; } else if (param->opcode == AES132_OPCODE_KEY_LOAD) { aes132crypt_param.plen_bytes = 16; } else { aes132crypt_param.plen_bytes = 0; } // Fill in the rest of parameters aes132crypt_param.nonce = param->nonce->value; aes132crypt_param.associated_data = associated_data; aes132crypt_param.key = param->key; aes132crypt_param.payload = param->in_data; aes132crypt_param.auth_value = param->out_mac; aes132crypt_param.ciphertext = param->out_data; // Execute... ret_code = aes132crypt_generate_encrypt(&aes132crypt_param); if (ret_code) { return ret_code; } return AES132_FUNCTION_RETCODE_SUCCESS; } /** \brief This function checks authentication/integrity MAC and decrypts data from ATAES132 commands. * * Operations supported by this function: * - Check OutMac from Auth, Outbound-only (Mode[1:0] = 10b) * - Check OutMac from Auth, Mutual (Mode[1:0] = 11b) * - Check OutMac from Counter read (Mode[1:0] = 11b) * - Decrypt OutData and check OutMac from EncRead * - Decrypt OutData and check OutMac from Encrypt * - Decrypt OutData and check OutMac from KeyCreate * - Decrypt OutData and check OutMac from KeyExport (Mode[0] = 0b) * * This function does _not_ support: * - EncRead command configuration memory signature MAC (Appendix I.17) * - EncRead command key memory signature MAC (Appendix I.18) * * All unused pointer in parameter struct can take NULL value. * The use of second authentication blocks (usage_counter, serial_num, small_zone) is determined by mode bit 7-5. * count_value is used only for Counter command, and not used for other commands. * out_mac is never used for this function. * * User must provide enough space for output parameters (out_data). * * The "nonce" struct has to be passed with valid member set to TRUE, otherwise the function returns with error. * The "nonce" struct is checked and updated by this function: * - If MacCount has reached maximum value (255), valid flag is cleared * - MacCount (nonce[12]) is incremented * - If MAC compare fails, valid flag is cleared, and MacCount is set to zero * * The function returns with bad parameter error if: * - Passed with opcode/mode combination that is not supported * - At least one of used pointer parameters has NULL value * * \param [in,out] param Pointer to structure for input/output parameters. Refer to aes132h_in_out. * \return status of the operation. */ uint8_t aes132h_mac_check_decrypt(struct aes132h_in_out *param) { uint8_t ret_code; struct aes132crypt_in_out aes132crypt_param; uint8_t associated_data[30]; // Check parameters if ( (!param->key) || (!param->nonce) || (!param->in_mac) || ((param->mode & 0x20) && !param->usage_counter) || ((param->mode & 0x40) && !param->serial_num) || ((param->mode & 0x80) && !param->small_zone) || ((param->opcode == AES132_OPCODE_COUNTER) && !param->count_value) || (((param->opcode == AES132_OPCODE_ENC_READ) || (param->opcode == AES132_OPCODE_ENCRYPT) || (param->opcode == AES132_OPCODE_KEY_CREATE) || (param->opcode == AES132_OPCODE_KEY_EXPORT)) && (!param->in_data || !param->out_data)) ) return AES132_FUNCTION_RETCODE_BAD_PARAM; // Check nonce validity if (param->nonce->valid == FALSE) return AES132_DEVICE_RETCODE_NONCE_ERROR; // Arrange associated_data (see ATAES132 datasheet appendix I) associated_data[0] = AES132_MANUFACTURING_ID >> 8; associated_data[1] = AES132_MANUFACTURING_ID & 0xFF; associated_data[2] = param->opcode; associated_data[3] = param->mode; associated_data[4] = param->param1 >> 8; associated_data[5] = param->param1 & 0xFF; associated_data[6] = param->param2 >> 8; associated_data[7] = param->param2 & 0xFF; associated_data[8] = (param->nonce->random)? AES132_MAC_FLAG_RANDOM: 0x00; // Input bit (bit 1) always 0 if (param->opcode == AES132_OPCODE_COUNTER) { memcpy(&associated_data[9], param->count_value, 4); } else { memset(&associated_data[9], 0x00, 4); } associated_data[13] = 0x00; // Append additional associated_data if specified by mode parameter if (param->mode & 0x20) { memcpy(&associated_data[14], param->usage_counter, 4); } else { memset(&associated_data[14], 0x00, 4); } if (param->mode & 0x40) { memcpy(&associated_data[18], param->serial_num, 8); } else { memset(&associated_data[18], 0x00, 8); } if (param->mode & 0x80) { memcpy(&associated_data[26], param->small_zone, 4); } else { memset(&associated_data[26], 0x00, 4); } // Increment MacCount before operation. Invalidate nonce if MacCount has reached max if (param->nonce->value[12] == 255) { param->nonce->valid = FALSE; } param->nonce->value[12]++; // Do the cryptographic calculation // Check if additional auth-only field is used aes132crypt_param.alen_bytes = (param->mode & 0xE0)? 30: 14; // The length is passed in "Param2" for encryption commands, and 16 for KeyCreate/KeyExport if ((param->opcode == AES132_OPCODE_ENC_READ) || (param->opcode == AES132_OPCODE_ENCRYPT)) { aes132crypt_param.plen_bytes = param->param2 & 0xFF; } else if ((param->opcode == AES132_OPCODE_KEY_CREATE) || (param->opcode == AES132_OPCODE_KEY_EXPORT)) { aes132crypt_param.plen_bytes = 16; } else { aes132crypt_param.plen_bytes = 0; } // Fill in the rest of parameters aes132crypt_param.nonce = param->nonce->value; aes132crypt_param.associated_data = associated_data; aes132crypt_param.key = param->key; aes132crypt_param.payload = param->out_data; aes132crypt_param.auth_value = param->in_mac; aes132crypt_param.ciphertext = param->in_data; // Execute... ret_code = aes132crypt_decrypt_verify(&aes132crypt_param); if (ret_code == AES132_DEVICE_RETCODE_MAC_ERROR) { // Invalidate nonce on MAC mismatch param->nonce->valid = FALSE; param->nonce->value[12] = 0; } return ret_code; } void aes_print_buffer(uint8_t *buff, uint8_t size){ ((void) buff); for(uint8_t i = 0; i < size;i++){ //printf("0x%02X ", buff[i]); } //printf("\n\r"); } void aes_print_rc(int ret_value) { printf(" Return Code ("); switch (ret_value) { case 0: printf("SUCCESS"); break; case 0x02: printf("BOUNDRY_ERROR"); break; case 0x04: printf("RW_CONFING"); break; case 0x08: printf("BAD_ADDRESS"); break; case 0x10: printf("COUNT_ERROR"); break; case 0x20: printf("NONCE_ERROR"); break; case 0x40: printf("MAC_ERROR"); break; case 0x50: printf("PARSE_ERROR"); break; case 0x60: printf("DARA_MATCH"); break; case 0x70: printf("LOCK_ERROR"); break; case 0x80: printf("KEY_ERROR"); break; case 0xE2: printf("INVALID PARAM"); break; default: printf("unknown error %d \n\r", ret_value); break; } printf(")\n"); } void aes132_print_zone_addresses(){ for(int i = 0; i < 16; i++){ //printf("(%i)\tZONE CONFIG ADDRESS: 0x%02X\n\r", i, AES132_ZONE_CONFIG_ADDR(i)); } for(int i = 0; i < 16; i++){ //printf("(%i)\tUSER ZONE ADDRESS: 0x%02X\n\r", i, AES132_USER_ZONE_ADDR(i)); } for(int i = 0; i < 16; i++){ //printf("(%i)\tKEY CONFIG ADDRESS: 0x%02X\n\r",i, AES132_KEY_CONFIG_ADDR(i)); } for(int i = 0; i < 16; i++){ //printf("(%i)\tKEY ADDRESS: 0x%02X\n\r",i, AES132_KEY_ADDR(i)); } for(int i = 0; i < 16; i++){ //printf("(%i)\tCOUNTER CONFIG ADDRESS: 0x%02X\n\r", i,AES132_COUNTER_CONFIG_ADDR(i)); } for(int i = 0; i < 16; i++){ //printf("(%i)\tCOUNTER ADDRESS: 0x%02X\n\r", i,AES132_COUNTER_ADDR(i)); } } uint8_t aes132_read_from_user_zone(uint32_t location, uint8_t *data, uint8_t size) { uint8_t aes132_lib_return; aes132_lib_return = aes132_read_size(data, location, size); if (aes132_lib_return != AES132_FUNCTION_RETCODE_SUCCESS) { return 1; } return 0; } uint8_t aes132_write_to_user_zone(uint32_t location, uint8_t *data, uint8_t size) { uint8_t verify[32] = {0}; uint8_t aes132_lib_return; aes132_lib_return = aes132m_write_memory(size, location, data); if (aes132_lib_return != AES132_FUNCTION_RETCODE_SUCCESS) { return 1; } aes132_lib_return = aes132_read_size(verify, location, size); if (aes132_lib_return != AES132_FUNCTION_RETCODE_SUCCESS) { return 1; } return memcmp(data, verify, size); }
<filename>WorkflowSchema/Code/WFSFormView.h // // WFSFormView.h // WFSWorkflow // // Created by <NAME> on 15/10/2012. // Copyright (c) 2012 CRedit360. All rights reserved. // #import "WFSHostView.h" @interface WFSFormView : WFSHostView @end
<reponame>amenoyoya/old-project #ifndef INCLUDED_openfl_media_Sound #define INCLUDED_openfl_media_Sound #ifndef HXCPP_H #include <hxcpp.h> #endif #include <openfl/events/EventDispatcher.h> HX_DECLARE_CLASS2(haxe,io,Bytes) HX_DECLARE_CLASS2(lime,audio,AudioBuffer) HX_DECLARE_CLASS2(lime,utils,ByteArray) HX_DECLARE_CLASS2(lime,utils,IDataInput) HX_DECLARE_CLASS2(lime,utils,IMemoryRange) HX_DECLARE_CLASS2(openfl,events,EventDispatcher) HX_DECLARE_CLASS2(openfl,events,IEventDispatcher) HX_DECLARE_CLASS2(openfl,media,ID3Info) HX_DECLARE_CLASS2(openfl,media,Sound) HX_DECLARE_CLASS2(openfl,media,SoundChannel) HX_DECLARE_CLASS2(openfl,media,SoundLoaderContext) HX_DECLARE_CLASS2(openfl,media,SoundTransform) HX_DECLARE_CLASS2(openfl,net,URLRequest) namespace openfl{ namespace media{ class HXCPP_CLASS_ATTRIBUTES Sound_obj : public ::openfl::events::EventDispatcher_obj{ public: typedef ::openfl::events::EventDispatcher_obj super; typedef Sound_obj OBJ_; Sound_obj(); Void __construct(::openfl::net::URLRequest stream,::openfl::media::SoundLoaderContext context); public: inline void *operator new( size_t inSize, bool inContainer=true) { return hx::Object::operator new(inSize,inContainer); } static hx::ObjectPtr< Sound_obj > __new(::openfl::net::URLRequest stream,::openfl::media::SoundLoaderContext context); static Dynamic __CreateEmpty(); static Dynamic __Create(hx::DynamicArray inArgs); //~Sound_obj(); HX_DO_RTTI; static void __boot(); static void __register(); void __Mark(HX_MARK_PARAMS); void __Visit(HX_VISIT_PARAMS); ::String __ToString() const { return HX_CSTRING("Sound"); } int bytesLoaded; int bytesTotal; ::openfl::media::ID3Info id3; bool isBuffering; Float length; ::String url; ::lime::audio::AudioBuffer __buffer; virtual Void close( ); Dynamic close_dyn(); virtual Void load( ::openfl::net::URLRequest stream,::openfl::media::SoundLoaderContext context); Dynamic load_dyn(); virtual Void loadCompressedDataFromByteArray( ::lime::utils::ByteArray bytes,int bytesLength,hx::Null< bool > forcePlayAsMusic); Dynamic loadCompressedDataFromByteArray_dyn(); virtual Void loadPCMFromByteArray( ::lime::utils::ByteArray bytes,int samples,::String format,hx::Null< bool > stereo,hx::Null< Float > sampleRate); Dynamic loadPCMFromByteArray_dyn(); virtual ::openfl::media::SoundChannel play( hx::Null< Float > startTime,hx::Null< int > loops,::openfl::media::SoundTransform sndTransform); Dynamic play_dyn(); virtual ::openfl::media::ID3Info get_id3( ); Dynamic get_id3_dyn(); virtual Void AudioBuffer_onURLLoad( ::lime::audio::AudioBuffer buffer); Dynamic AudioBuffer_onURLLoad_dyn(); static ::openfl::media::Sound fromAudioBuffer( ::lime::audio::AudioBuffer buffer); static Dynamic fromAudioBuffer_dyn(); static ::openfl::media::Sound fromFile( ::String path); static Dynamic fromFile_dyn(); }; } // end namespace openfl } // end namespace media #endif /* INCLUDED_openfl_media_Sound */
<gh_stars>0 #ifndef _COMPAT_PROC_FS_H #define _COMPAT_PROC_FS_H #include <linux/version.h> #include_next <linux/proc_fs.h> #if (LINUX_VERSION_CODE > KERNEL_VERSION(2,1,0)) #if (LINUX_VERSION_CODE < KERNEL_VERSION(2,3,25)) extern inline struct proc_dir_entry * create_proc_read_entry(const char *name, mode_t mode, struct proc_dir_entry *base, read_proc_t *read_proc, void *data) { struct proc_dir_entry *res = create_proc_entry(name, mode, base); if (res) { res->read_proc = read_proc; res->data = data; } return res; } #endif #if (LINUX_VERSION_CODE < KERNEL_VERSION(2,3,29)) #ifndef proc_mkdir #define proc_mkdir(name, root) create_proc_entry(name, S_IFDIR, root) #endif #endif #endif #endif /* _COMPAT_PROC_FS_H */
<gh_stars>0 /* Includes ------------------------------------------------------------------*/ #include "usb_lib.h" #include "usb_desc.h" #include "usb_mem.h" #include "hw_config.h" #include "usb_istr.h" #include "usb_pwr.h" #include "cdcio.h" /* Interval between sending IN packets in frame number (1 frame = 1ms) */ #define VCOMPORT_IN_FRAME_INTERVAL 5 uint8_t USB_Rx_Buffer[VIRTUAL_COM_PORT_DATA_SIZE]; uint8_t USB_Tx_Buffer[VIRTUAL_COM_PORT_DATA_SIZE]; uint8_t USB_Tx_State = 0; void stdout_to_usb(); /******************************************************************************* * Function Name : EP1_IN_Callback * Description : * Input : None. * Output : None. * Return : None. *******************************************************************************/ void EP1_IN_Callback (void) { if (USB_Tx_State == 1) stdout_to_usb(); } /******************************************************************************* * Function Name : EP3_OUT_Callback * Description : * Input : None. * Output : None. * Return : None. *******************************************************************************/ void EP3_OUT_Callback(void) { uint16_t USB_Rx_Cnt; /* Get the received data buffer and update the counter */ USB_Rx_Cnt = USB_SIL_Read(EP3_OUT, USB_Rx_Buffer); cdc_write_buf(&cdc_in, USB_Rx_Buffer, USB_Rx_Cnt, 0); SetEPRxValid(ENDP3); } /******************************************************************************* * Function Name : Handle_USBAsynchXfer. * Description : send data to USB. * Input : None. * Return : none. *******************************************************************************/ void Handle_USBAsynchXfer (void) { if(USB_Tx_State != 1){ USB_Tx_State = 1; stdout_to_usb(); } } void stdout_to_usb(){ uint16_t USB_Tx_length; USB_Tx_length = cdc_read_buf(&cdc_out, USB_Tx_Buffer, VIRTUAL_COM_PORT_DATA_SIZE); if (USB_Tx_length){ UserToPMABufferCopy(USB_Tx_Buffer, ENDP1_TXADDR, USB_Tx_length); SetEPTxCount(ENDP1, USB_Tx_length); SetEPTxValid(ENDP1); } else{ USB_Tx_State = 0; } } /******************************************************************************* * Function Name : SOF_Callback / INTR_SOFINTR_Callback * Description : * Input : None. * Output : None. * Return : None. *******************************************************************************/ #ifdef STM32F10X_CL void INTR_SOFINTR_Callback(void) #else void SOF_Callback(void) #endif /* STM32F10X_CL */ { static uint32_t FrameCount = 0; if(bDeviceState == CONFIGURED) { if (FrameCount++ == VCOMPORT_IN_FRAME_INTERVAL) { /* Reset the frame counter */ FrameCount = 0; /* Check the data to be sent through IN pipe */ Handle_USBAsynchXfer(); } } }
#define UNIT #define TRANSA #define ASMNAME dtpmv_TLU #define ASMFNAME dtpmv_TLU_ #define NAME dtpmv_TLU_ #define CNAME dtpmv_TLU #define CHAR_NAME "dtpmv_TLU_" #define CHAR_CNAME "dtpmv_TLU" #define DOUBLE #include "/lustre/scratch3/turquoise/rvangara/RD100/distnnmfkcpp_Src/install_dependencies/xianyi-OpenBLAS-6d2da63/driver/level2/tpmv_U.c"
#pragma ident "$Id: read.c,v 1.6 2006/09/29 19:45:39 dechavez Exp $" /*====================================================================== * * Read one frame, returning one of the following * * ISI_OK - when frame was read OK * ISI_ERROR - when read failed * ISI_DONE - when server disconnected normally * ISI_BREAK - when server disconnected, isi->alert has cause code * * *====================================================================*/ #include "isi.h" int isiReadFrame(ISI *isi, BOOL SkipHeartbeats) { static char *fid = "isiReadFrame"; if (isi == NULL) return ISI_EINVAL; while (iacpRecvFrame(isi->iacp, &isi->frame, isi->buf, ISI_INTERNAL_BUFLEN)) { switch (isi->frame.payload.type) { case IACP_TYPE_NOP: isiLogMsg(isi, LOG_DEBUG, "HEARTBEAT received"); if (!SkipHeartbeats) return ISI_OK; break; case IACP_TYPE_ALERT: isi->alert = iacpAlertCauseCode(&isi->frame); return (isi->alert == IACP_ALERT_REQUEST_COMPLETE) ? ISI_DONE : ISI_BREAK; default: return ISI_OK; } } if (isi->iacp->recv.error == ETIMEDOUT) { return ISI_TIMEDOUT; } else if (isi->iacp->recv.error == ECONNRESET) { return ISI_CONNRESET; } else if (isi->iacp->recv.error == EBADMSG) { return ISI_BADMSG; } logioMsg(isi->lp, LOG_INFO, "%s: unexpected IACP receive error code %d", fid, isi->iacp->recv.error); logioMsg(isi->lp, LOG_INFO, "%s: seqno=%lu, type=%lu, len=%lu", fid, isi->frame.seqno, isi->frame.payload.type, isi->frame.payload.len); if (isi->frame.payload.len > 0) logioMsg(isi->lp, LOG_INFO, isi->frame.payload.data, isi->frame.payload.len); return ISI_ERROR; } /* Revision History * * $Log: read.c,v $ * Revision 1.6 2006/09/29 19:45:39 dechavez * added test for EBADMSG * * Revision 1.5 2006/06/26 22:37:35 dechavez * check for and return ISI_TIMEDOUT and ISI_CONNRESET conditions * * Revision 1.4 2005/10/10 23:43:31 dechavez * debug tracers removed * * Revision 1.3 2005/09/30 22:54:39 dechavez * debug tracers added * * Revision 1.2 2005/06/30 01:29:07 dechavez * debugged isiReadFrame() * * Revision 1.1 2005/06/10 15:45:13 dechavez * initial release * */
<gh_stars>10-100 // // ALMenuItem.h // ALButtonMenu // // Copyright © 2016 <NAME>. All rights reserved. // #import <Foundation/Foundation.h> #import <UIKit/UIKit.h> NS_ASSUME_NONNULL_BEGIN @protocol ALMenuItem; @protocol ALMenuItemDelegate <NSObject> - (void)buttonWasTapped:(UIView<ALMenuItem> *)button; @end @protocol ALMenuItem <NSObject> @property (nullable, nonatomic, weak) id<ALMenuItemDelegate> delegate; @end NS_ASSUME_NONNULL_END
#pragma once #include <vector> #include "Engine/Models/Plugins/Interfaces/IChannel.h" #include "Engine/Models/Plugins/Interfaces/IConnectedComponent.h" #include "Engine/Types/Enums.h" namespace bv { namespace model { class IPlugin; class IConnectedComponent; class IVertexAttributesChannelDescriptor; class IVertexAttributesChannel; DEFINE_PTR_TYPE(IVertexAttributesChannel) DEFINE_CONST_PTR_TYPE(IVertexAttributesChannel) class IVertexAttributesChannel : public IChannel { public: virtual const IVertexAttributesChannelDescriptor * GetDescriptor () const = 0; virtual PrimitiveType GetPrimitiveType () const = 0; virtual int GetNumPrimitives ( IConnectedComponentPtr cc ) const = 0; virtual std::vector< IConnectedComponentPtr > GetComponents () const = 0; //virtual void AddConnectedComponent ( IConnectedComponent * cc ) = 0; virtual bool IsTimeInvariant () const = 0; virtual UInt64 GetAttributesUpdateID () const = 0; virtual UInt64 GetTopologyUpdateID () const = 0; virtual unsigned int TotalNumVertices () const = 0; //FIXME: implement via plugin when its interface is known //virtual bool CanBeConnectedTo ( IPlugin * plugin ) const = 0; virtual bool CanBeConnectedTo ( IVertexAttributesChannelPtr channel ) const = 0; virtual ~IVertexAttributesChannel (){}; }; } // model } // bv
/********************************************** * * Author : <NAME> * Mail : <EMAIL> * Date : 2013/8/10 * Last : * Notes : ADC12 * Tool : ADC12 for MSP430X2XX **********************************************/ #ifndef __ADC12_H__ #define __ADC12_H__ #define VREF 1500 //配置ADC12的参考电压VR+, 放大1000倍,即单位mv. #define VREF_ 0 //配置ADC12的参考电压VR- #define VREF_DIFF (VREF - VREF_) //将ADC的采样值转换为电压值, 单位mv. 使用条件: 2.5V 0V的参考电压,精度高 #define ADC12_Result_2_5(NADC) (((((NADC) * 10) >> 6) * 39) / 10) // Vin = (nadc * 10 / 64) * ((2500 - 0) / 64); #define ADC12_Result_1_5(NADC) ((NADC * 15 / 41)) // VREF+ = 1.5, VREF- = AVSS时的高精度算法 #define ADC12_ON (ADC12CTL0 |= ADC12ON) // ADC12 on #define ADC12_OVIE (ADC12CTL0 |= ADC12OVIE) //ADC12MEMx overflow-interrupt. #define ADC12_TOVIE (ADC12CTL0 |= ADC12TOIE) //ADC12 Conversion-time-overflow #define ADC12_ENC (ADC12CTL0 |= ENC) //Enable Conversion #define ADC12_SC (ADC12CTL0 |= ADC12SC) //Start Conversion. #define ADC12_INVERT_SH (ADC12CTL0 |= ISSH) //invert signal sample-and-hold #define ADC12_ISBUSY (ADC12CTL1 & ADC12BUSY) /*********ADC12使用指南******************* ADC12_Init(3,1,0,3); //初始化,选择时钟,分频,模式,采样保持时间 ADC12_Sample_Source(0, 1); //选择采样模块的时钟来源, 采样方式(脉冲采样shp = 1, 拓展采样0) ADC12_Set_Address(1); //采样值存放的首地址. ADC12_MCTL(15, 0, 1); //内存单元配置, 在此单元配置后的采样值不一定在此单元存放. //没有内存单元配置,则默认通道A0采样存放地址0. //没有地址设置,则默认存放在地址0 ADC12_Enable((BIT0)); //内存单元中断,存放值以后是否中断. ADC12_ENC; P6DIR &= BIT1; // 开启IO的AD采样功能 P6SEL |= BIT1; // ******************************************/ // 选择时钟, 分频, 方式, 采样保持时间 void ADC12_Init(unsigned char clk, unsigned char div, unsigned char mode, unsigned char shtime); // ADC初始化 void ADC12_Sample_Source(unsigned char shs, unsigned char shp); // Sample-and-hold source select //选择内存单元ADC12MCTL0~ADC12MCTL15,选择参考,选择通道, 需另行配置ADC12_Enable(),ENC以及配置必要的IO SEL. void ADC12_MCTL(unsigned char mctl, unsigned char svref, unsigned char channel); /***************************************************************************//** * @brief Initialize the ADC sysyem - configure adc clock source, clock divider, * sample signal channel, sample mode, sample and hold time , and set the VREF; * @param * parameter *----------------------------------------------------------------------------- * clk = 0 ADC12OSC * 1 ACLK * 2 MCLK * 3 SMCLK *----------------------------------------------------------------------------- * div = 1 /1 * 2 /2 * 3 /3 * 4 /4 * 5 /5 * 6 /6 * 7 /7 * 8 /8 *----------------------------------------------------------------------------- * channel 0 A0 * 1 A1 * 2 A2 * x Ax * 7 A7 * 8 VeREF+ * 9 VREF-/VeREF- * 10 Temperature * 11 (AVcc - AVss) / 2 * 12 GND *----------------------------------------------------------------------------- * shtime= 1 4 ADCCLK cycles * 2 8 * 3 16 * 4 32 * 5 64 * 6 96 * 7 128 * 8 192 * 9 256 * 10 384 * 11 512 * 12 768 * 13 1024 *----------------------------------------------------------------------------- * mode = 0 single-channel, single-conversion * 1 sequence-of-channels * 2 Repeat-single-channel * 3 Repeat-sequence-of-channels *----------------------------------------------------------------------------- * svref = 0 VR+ = AVCC and VR- = AVSS * 1 VR+ = VREF+ and VR- = AVSS * 2 VR+ = VeREF+ and VR- = AVSS * 3 VR+ = VeREF+ and VR- = AVSS * 4 VR+ = AVCC and VR- = VREF-/ VeREF- * 5 VR+ = VREF+ and VR- = VREF-/ VeREF- * 6 VR+ = VeREF+ and VR- = VREF-/ VeREF- * 7 VR+ = VeREF+ and VR- = VREF-/ VeREFINCHx *----------------------------------------------------------------------------- * shs = 0 ADC12SC bit * 1 Timer_A.OUT1 * 2 Timer_B.OUT0 * 3 Timer_B.OUT1 *----------------------------------------------------------------------------- * shp = 0 采样信号 控制SAMPCON信号 * 1 采样定时器 控制SAMPCON信号 *----------------------------------------------------------------------------- *----------------------------------------------------------------------------- *----------------------------------------------------------------------------- *----------------------------------------------------------------------------- * @return none ******************************************************************************/ void ADC12_Set_VREF2_5(); // 配置ADC Reference generator voltage = 2.5V void ADC12_Set_VREF1_5(); // 配置ADC REF = 1.5V // address 0~0FH void ADC12_Set_Address(unsigned char address); // 配置ADC Conversion Start address. 用于序列采样情况 void ADC12_Set_Mode(unsigned char mode); void ADC12_Set_CLK(unsigned char clk, unsigned char div); //使能ADC12中15个中断源的某个中断 void ADC12_Enable(unsigned int adc12ie); unsigned int ADC12_T(unsigned int vtemp); //输入ADC12温度传感器采样出来的毫伏级电压,转化为温度的100倍显示出来. /*************ADC12中断模板************************ #pragma vector=ADC12_VECTOR __interrupt void ADC12_ISR (void) { switch(ADC12IV) { case 2: //ADC12MEMx overflow break; case 4: //Conversion time overflow break; case 6: //ADC12MEM0 interrupt flag break; case 8: //ADC12MEM1 break; case 10: //ADC12MEM2 break; case 12: //ADC12MEM3 break; case 14: //ADC12MEM4 break; case 16: //ADC12MEM5 break; case 18: //ADC12MEM6 break; case 20: //ADC12MEM7 break; case 22: //ADC12MEM8 break; case 24: //ADC12MEM9 break; case 26: //ADC12MEM10 break; case 28: //ADC12MEM11 break; case 30: //ADC12MEM12 break; case 32: //ADC12MEM13 break; case 34: //ADC12MEM14 break; case 36: //ADC12MEM15 break; } } **************************************************/ #endif /* __ADC12_H__ */
<reponame>Tairy/tjvm // // Created by tairy on 2020/11/25. // #ifndef TJVMSRC_OBJECT_MARK_H #define TJVMSRC_OBJECT_MARK_H #endif //TJVMSRC_OBJECT_MARK_H
// Copyright 2019 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef THIRD_PARTY_BLINK_RENDERER_PLATFORM_TESTING_IO_TASK_RUNNER_TESTING_PLATFORM_SUPPORT_H_ #define THIRD_PARTY_BLINK_RENDERER_PLATFORM_TESTING_IO_TASK_RUNNER_TESTING_PLATFORM_SUPPORT_H_ #include "third_party/blink/renderer/platform/testing/testing_platform_support.h" #include "base/memory/scoped_refptr.h" #include "third_party/blink/renderer/platform/scheduler/public/thread.h" namespace base { class SingleThreadTaskRunner; } namespace blink { class IOTaskRunnerTestingPlatformSupport : public TestingPlatformSupport { public: IOTaskRunnerTestingPlatformSupport(); scoped_refptr<base::SingleThreadTaskRunner> GetIOTaskRunner() const override; private: std::unique_ptr<Thread> io_thread_; }; } // namespace blink #endif // THIRD_PARTY_BLINK_RENDERER_PLATFORM_TESTING_IO_TASK_RUNNER_TESTING_PLATFORM_SUPPORT_H_
// This file is part of Eigen, a lightweight C++ template library // for linear algebra. Eigen itself is part of the KDE project. // // Copyright (C) 2008 <NAME> <<EMAIL>> // // Eigen 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 3 of the License, or (at your option) any later version. // // Alternatively, 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. // // Eigen 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 or the // GNU General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License and a copy of the GNU General Public License along with // Eigen. If not, see <http://www.gnu.org/licenses/>. #ifndef EIGEN_CWISE_NULLARY_OP_H #define EIGEN_CWISE_NULLARY_OP_H /** \class CwiseNullaryOp * * \brief Generic expression of a matrix where all coefficients are defined by a functor * * \param NullaryOp template functor implementing the operator * * This class represents an expression of a generic nullary operator. * It is the return type of the Ones(), Zero(), Constant(), Identity() and Random() functions, * and most of the time this is the only way it is used. * * However, if you want to write a function returning such an expression, you * will need to use this class. * * \sa class CwiseUnaryOp, class CwiseBinaryOp, MatrixBase::NullaryExpr() */ template<typename NullaryOp, typename MatrixType> struct ei_traits<CwiseNullaryOp<NullaryOp, MatrixType> > : ei_traits<MatrixType> { enum { Flags = (ei_traits<MatrixType>::Flags & ( HereditaryBits | (ei_functor_has_linear_access<NullaryOp>::ret ? LinearAccessBit : 0) | (ei_functor_traits<NullaryOp>::PacketAccess ? PacketAccessBit : 0))) | (ei_functor_traits<NullaryOp>::IsRepeatable ? 0 : EvalBeforeNestingBit), CoeffReadCost = ei_functor_traits<NullaryOp>::Cost }; }; template<typename NullaryOp, typename MatrixType> class CwiseNullaryOp : ei_no_assignment_operator, public MatrixBase<CwiseNullaryOp<NullaryOp, MatrixType> > { public: EIGEN_GENERIC_PUBLIC_INTERFACE(CwiseNullaryOp) CwiseNullaryOp(int rows, int cols, const NullaryOp& func = NullaryOp()) : m_rows(rows), m_cols(cols), m_functor(func) { ei_assert(rows > 0 && (RowsAtCompileTime == Dynamic || RowsAtCompileTime == rows) && cols > 0 && (ColsAtCompileTime == Dynamic || ColsAtCompileTime == cols)); } EIGEN_STRONG_INLINE int rows() const { return m_rows.value(); } EIGEN_STRONG_INLINE int cols() const { return m_cols.value(); } EIGEN_STRONG_INLINE const Scalar coeff(int rows, int cols) const { return m_functor(rows, cols); } template<int LoadMode> EIGEN_STRONG_INLINE PacketScalar packet(int, int) const { return m_functor.packetOp(); } EIGEN_STRONG_INLINE const Scalar coeff(int index) const { if(RowsAtCompileTime == 1) return m_functor(0, index); else return m_functor(index, 0); } template<int LoadMode> EIGEN_STRONG_INLINE PacketScalar packet(int) const { return m_functor.packetOp(); } protected: const ei_int_if_dynamic<RowsAtCompileTime> m_rows; const ei_int_if_dynamic<ColsAtCompileTime> m_cols; const NullaryOp m_functor; }; /** \returns an expression of a matrix defined by a custom functor \a func * * The parameters \a rows and \a cols are the number of rows and of columns of * the returned matrix. Must be compatible with this MatrixBase type. * * This variant is meant to be used for dynamic-size matrix types. For fixed-size types, * it is redundant to pass \a rows and \a cols as arguments, so Zero() should be used * instead. * * The template parameter \a CustomNullaryOp is the type of the functor. * * \sa class CwiseNullaryOp */ template<typename Derived> template<typename CustomNullaryOp> EIGEN_STRONG_INLINE const CwiseNullaryOp<CustomNullaryOp, Derived> MatrixBase<Derived>::NullaryExpr(int rows, int cols, const CustomNullaryOp& func) { return CwiseNullaryOp<CustomNullaryOp, Derived>(rows, cols, func); } /** \returns an expression of a matrix defined by a custom functor \a func * * The parameter \a size is the size of the returned vector. * Must be compatible with this MatrixBase type. * * \only_for_vectors * * This variant is meant to be used for dynamic-size vector types. For fixed-size types, * it is redundant to pass \a size as argument, so Zero() should be used * instead. * * The template parameter \a CustomNullaryOp is the type of the functor. * * \sa class CwiseNullaryOp */ template<typename Derived> template<typename CustomNullaryOp> EIGEN_STRONG_INLINE const CwiseNullaryOp<CustomNullaryOp, Derived> MatrixBase<Derived>::NullaryExpr(int size, const CustomNullaryOp& func) { EIGEN_STATIC_ASSERT_VECTOR_ONLY(Derived) ei_assert(IsVectorAtCompileTime); if(RowsAtCompileTime == 1) return CwiseNullaryOp<CustomNullaryOp, Derived>(1, size, func); else return CwiseNullaryOp<CustomNullaryOp, Derived>(size, 1, func); } /** \returns an expression of a matrix defined by a custom functor \a func * * This variant is only for fixed-size MatrixBase types. For dynamic-size types, you * need to use the variants taking size arguments. * * The template parameter \a CustomNullaryOp is the type of the functor. * * \sa class CwiseNullaryOp */ template<typename Derived> template<typename CustomNullaryOp> EIGEN_STRONG_INLINE const CwiseNullaryOp<CustomNullaryOp, Derived> MatrixBase<Derived>::NullaryExpr(const CustomNullaryOp& func) { return CwiseNullaryOp<CustomNullaryOp, Derived>(RowsAtCompileTime, ColsAtCompileTime, func); } /** \returns an expression of a constant matrix of value \a value * * The parameters \a rows and \a cols are the number of rows and of columns of * the returned matrix. Must be compatible with this MatrixBase type. * * This variant is meant to be used for dynamic-size matrix types. For fixed-size types, * it is redundant to pass \a rows and \a cols as arguments, so Zero() should be used * instead. * * The template parameter \a CustomNullaryOp is the type of the functor. * * \sa class CwiseNullaryOp */ template<typename Derived> EIGEN_STRONG_INLINE const typename MatrixBase<Derived>::ConstantReturnType MatrixBase<Derived>::Constant(int rows, int cols, const Scalar& value) { return NullaryExpr(rows, cols, ei_scalar_constant_op<Scalar>(value)); } /** \returns an expression of a constant matrix of value \a value * * The parameter \a size is the size of the returned vector. * Must be compatible with this MatrixBase type. * * \only_for_vectors * * This variant is meant to be used for dynamic-size vector types. For fixed-size types, * it is redundant to pass \a size as argument, so Zero() should be used * instead. * * The template parameter \a CustomNullaryOp is the type of the functor. * * \sa class CwiseNullaryOp */ template<typename Derived> EIGEN_STRONG_INLINE const typename MatrixBase<Derived>::ConstantReturnType MatrixBase<Derived>::Constant(int size, const Scalar& value) { return NullaryExpr(size, ei_scalar_constant_op<Scalar>(value)); } /** \returns an expression of a constant matrix of value \a value * * This variant is only for fixed-size MatrixBase types. For dynamic-size types, you * need to use the variants taking size arguments. * * The template parameter \a CustomNullaryOp is the type of the functor. * * \sa class CwiseNullaryOp */ template<typename Derived> EIGEN_STRONG_INLINE const typename MatrixBase<Derived>::ConstantReturnType MatrixBase<Derived>::Constant(const Scalar& value) { EIGEN_STATIC_ASSERT_FIXED_SIZE(Derived) return NullaryExpr(RowsAtCompileTime, ColsAtCompileTime, ei_scalar_constant_op<Scalar>(value)); } /** \returns true if all coefficients in this matrix are approximately equal to \a value, to within precision \a prec */ template<typename Derived> bool MatrixBase<Derived>::isApproxToConstant (const Scalar& value, RealScalar prec) const { for(int j = 0; j < cols(); ++j) for(int i = 0; i < rows(); ++i) if(!ei_isApprox(coeff(i, j), value, prec)) return false; return true; } /** This is just an alias for isApproxToConstant(). * * \returns true if all coefficients in this matrix are approximately equal to \a value, to within precision \a prec */ template<typename Derived> bool MatrixBase<Derived>::isConstant (const Scalar& value, RealScalar prec) const { return isApproxToConstant(value, prec); } /** Alias for setConstant(): sets all coefficients in this expression to \a value. * * \sa setConstant(), Constant(), class CwiseNullaryOp */ template<typename Derived> EIGEN_STRONG_INLINE void MatrixBase<Derived>::fill(const Scalar& value) { setConstant(value); } /** Sets all coefficients in this expression to \a value. * * \sa fill(), setConstant(int,const Scalar&), setConstant(int,int,const Scalar&), setZero(), setOnes(), Constant(), class CwiseNullaryOp, setZero(), setOnes() */ template<typename Derived> EIGEN_STRONG_INLINE Derived& MatrixBase<Derived>::setConstant(const Scalar& value) { return derived() = Constant(rows(), cols(), value); } /** Resizes to the given \a size, and sets all coefficients in this expression to the given \a value. * * \only_for_vectors * * Example: \include Matrix_set_int.cpp * Output: \verbinclude Matrix_setConstant_int.out * * \sa MatrixBase::setConstant(const Scalar&), setConstant(int,int,const Scalar&), class CwiseNullaryOp, MatrixBase::Constant(const Scalar&) */ template<typename _Scalar, int _Rows, int _Cols, int _Options, int _MaxRows, int _MaxCols> EIGEN_STRONG_INLINE Matrix<_Scalar, _Rows, _Cols, _Options, _MaxRows, _MaxCols>& Matrix<_Scalar, _Rows, _Cols, _Options, _MaxRows, _MaxCols>::setConstant(int size, const Scalar& value) { resize(size); return setConstant(value); } /** Resizes to the given size, and sets all coefficients in this expression to the given \a value. * * \param rows the new number of rows * \param cols the new number of columns * * Example: \include Matrix_setConstant_int_int.cpp * Output: \verbinclude Matrix_setConstant_int_int.out * * \sa MatrixBase::setConstant(const Scalar&), setConstant(int,const Scalar&), class CwiseNullaryOp, MatrixBase::Constant(const Scalar&) */ template<typename _Scalar, int _Rows, int _Cols, int _Options, int _MaxRows, int _MaxCols> EIGEN_STRONG_INLINE Matrix<_Scalar, _Rows, _Cols, _Options, _MaxRows, _MaxCols>& Matrix<_Scalar, _Rows, _Cols, _Options, _MaxRows, _MaxCols>::setConstant(int rows, int cols, const Scalar& value) { resize(rows, cols); return setConstant(value); } // zero: /** \returns an expression of a zero matrix. * * The parameters \a rows and \a cols are the number of rows and of columns of * the returned matrix. Must be compatible with this MatrixBase type. * * This variant is meant to be used for dynamic-size matrix types. For fixed-size types, * it is redundant to pass \a rows and \a cols as arguments, so Zero() should be used * instead. * * \addexample Zero \label How to take get a zero matrix * * Example: \include MatrixBase_zero_int_int.cpp * Output: \verbinclude MatrixBase_zero_int_int.out * * \sa Zero(), Zero(int) */ template<typename Derived> EIGEN_STRONG_INLINE const typename MatrixBase<Derived>::ConstantReturnType MatrixBase<Derived>::Zero(int rows, int cols) { return Constant(rows, cols, Scalar(0)); } /** \returns an expression of a zero vector. * * The parameter \a size is the size of the returned vector. * Must be compatible with this MatrixBase type. * * \only_for_vectors * * This variant is meant to be used for dynamic-size vector types. For fixed-size types, * it is redundant to pass \a size as argument, so Zero() should be used * instead. * * Example: \include MatrixBase_zero_int.cpp * Output: \verbinclude MatrixBase_zero_int.out * * \sa Zero(), Zero(int,int) */ template<typename Derived> EIGEN_STRONG_INLINE const typename MatrixBase<Derived>::ConstantReturnType MatrixBase<Derived>::Zero(int size) { return Constant(size, Scalar(0)); } /** \returns an expression of a fixed-size zero matrix or vector. * * This variant is only for fixed-size MatrixBase types. For dynamic-size types, you * need to use the variants taking size arguments. * * Example: \include MatrixBase_zero.cpp * Output: \verbinclude MatrixBase_zero.out * * \sa Zero(int), Zero(int,int) */ template<typename Derived> EIGEN_STRONG_INLINE const typename MatrixBase<Derived>::ConstantReturnType MatrixBase<Derived>::Zero() { return Constant(Scalar(0)); } /** \returns true if *this is approximately equal to the zero matrix, * within the precision given by \a prec. * * Example: \include MatrixBase_isZero.cpp * Output: \verbinclude MatrixBase_isZero.out * * \sa class CwiseNullaryOp, Zero() */ template<typename Derived> bool MatrixBase<Derived>::isZero(RealScalar prec) const { for(int j = 0; j < cols(); ++j) for(int i = 0; i < rows(); ++i) if(!ei_isMuchSmallerThan(coeff(i, j), static_cast<Scalar>(1), prec)) return false; return true; } /** Sets all coefficients in this expression to zero. * * Example: \include MatrixBase_setZero.cpp * Output: \verbinclude MatrixBase_setZero.out * * \sa class CwiseNullaryOp, Zero() */ template<typename Derived> EIGEN_STRONG_INLINE Derived& MatrixBase<Derived>::setZero() { return setConstant(Scalar(0)); } /** Resizes to the given \a size, and sets all coefficients in this expression to zero. * * \only_for_vectors * * Example: \include Matrix_setZero_int.cpp * Output: \verbinclude Matrix_setZero_int.out * * \sa MatrixBase::setZero(), setZero(int,int), class CwiseNullaryOp, MatrixBase::Zero() */ template<typename _Scalar, int _Rows, int _Cols, int _Options, int _MaxRows, int _MaxCols> EIGEN_STRONG_INLINE Matrix<_Scalar, _Rows, _Cols, _Options, _MaxRows, _MaxCols>& Matrix<_Scalar, _Rows, _Cols, _Options, _MaxRows, _MaxCols>::setZero(int size) { resize(size); return setConstant(Scalar(0)); } /** Resizes to the given size, and sets all coefficients in this expression to zero. * * \param rows the new number of rows * \param cols the new number of columns * * Example: \include Matrix_setZero_int_int.cpp * Output: \verbinclude Matrix_setZero_int_int.out * * \sa MatrixBase::setZero(), setZero(int), class CwiseNullaryOp, MatrixBase::Zero() */ template<typename _Scalar, int _Rows, int _Cols, int _Options, int _MaxRows, int _MaxCols> EIGEN_STRONG_INLINE Matrix<_Scalar, _Rows, _Cols, _Options, _MaxRows, _MaxCols>& Matrix<_Scalar, _Rows, _Cols, _Options, _MaxRows, _MaxCols>::setZero(int rows, int cols) { resize(rows, cols); return setConstant(Scalar(0)); } // ones: /** \returns an expression of a matrix where all coefficients equal one. * * The parameters \a rows and \a cols are the number of rows and of columns of * the returned matrix. Must be compatible with this MatrixBase type. * * This variant is meant to be used for dynamic-size matrix types. For fixed-size types, * it is redundant to pass \a rows and \a cols as arguments, so Ones() should be used * instead. * * \addexample One \label How to get a matrix with all coefficients equal one * * Example: \include MatrixBase_ones_int_int.cpp * Output: \verbinclude MatrixBase_ones_int_int.out * * \sa Ones(), Ones(int), isOnes(), class Ones */ template<typename Derived> EIGEN_STRONG_INLINE const typename MatrixBase<Derived>::ConstantReturnType MatrixBase<Derived>::Ones(int rows, int cols) { return Constant(rows, cols, Scalar(1)); } /** \returns an expression of a vector where all coefficients equal one. * * The parameter \a size is the size of the returned vector. * Must be compatible with this MatrixBase type. * * \only_for_vectors * * This variant is meant to be used for dynamic-size vector types. For fixed-size types, * it is redundant to pass \a size as argument, so Ones() should be used * instead. * * Example: \include MatrixBase_ones_int.cpp * Output: \verbinclude MatrixBase_ones_int.out * * \sa Ones(), Ones(int,int), isOnes(), class Ones */ template<typename Derived> EIGEN_STRONG_INLINE const typename MatrixBase<Derived>::ConstantReturnType MatrixBase<Derived>::Ones(int size) { return Constant(size, Scalar(1)); } /** \returns an expression of a fixed-size matrix or vector where all coefficients equal one. * * This variant is only for fixed-size MatrixBase types. For dynamic-size types, you * need to use the variants taking size arguments. * * Example: \include MatrixBase_ones.cpp * Output: \verbinclude MatrixBase_ones.out * * \sa Ones(int), Ones(int,int), isOnes(), class Ones */ template<typename Derived> EIGEN_STRONG_INLINE const typename MatrixBase<Derived>::ConstantReturnType MatrixBase<Derived>::Ones() { return Constant(Scalar(1)); } /** \returns true if *this is approximately equal to the matrix where all coefficients * are equal to 1, within the precision given by \a prec. * * Example: \include MatrixBase_isOnes.cpp * Output: \verbinclude MatrixBase_isOnes.out * * \sa class CwiseNullaryOp, Ones() */ template<typename Derived> bool MatrixBase<Derived>::isOnes (RealScalar prec) const { return isApproxToConstant(Scalar(1), prec); } /** Sets all coefficients in this expression to one. * * Example: \include MatrixBase_setOnes.cpp * Output: \verbinclude MatrixBase_setOnes.out * * \sa class CwiseNullaryOp, Ones() */ template<typename Derived> EIGEN_STRONG_INLINE Derived& MatrixBase<Derived>::setOnes() { return setConstant(Scalar(1)); } /** Resizes to the given \a size, and sets all coefficients in this expression to one. * * \only_for_vectors * * Example: \include Matrix_setOnes_int.cpp * Output: \verbinclude Matrix_setOnes_int.out * * \sa MatrixBase::setOnes(), setOnes(int,int), class CwiseNullaryOp, MatrixBase::Ones() */ template<typename _Scalar, int _Rows, int _Cols, int _Options, int _MaxRows, int _MaxCols> EIGEN_STRONG_INLINE Matrix<_Scalar, _Rows, _Cols, _Options, _MaxRows, _MaxCols>& Matrix<_Scalar, _Rows, _Cols, _Options, _MaxRows, _MaxCols>::setOnes(int size) { resize(size); return setConstant(Scalar(1)); } /** Resizes to the given size, and sets all coefficients in this expression to one. * * \param rows the new number of rows * \param cols the new number of columns * * Example: \include Matrix_setOnes_int_int.cpp * Output: \verbinclude Matrix_setOnes_int_int.out * * \sa MatrixBase::setOnes(), setOnes(int), class CwiseNullaryOp, MatrixBase::Ones() */ template<typename _Scalar, int _Rows, int _Cols, int _Options, int _MaxRows, int _MaxCols> EIGEN_STRONG_INLINE Matrix<_Scalar, _Rows, _Cols, _Options, _MaxRows, _MaxCols>& Matrix<_Scalar, _Rows, _Cols, _Options, _MaxRows, _MaxCols>::setOnes(int rows, int cols) { resize(rows, cols); return setConstant(Scalar(1)); } // Identity: /** \returns an expression of the identity matrix (not necessarily square). * * The parameters \a rows and \a cols are the number of rows and of columns of * the returned matrix. Must be compatible with this MatrixBase type. * * This variant is meant to be used for dynamic-size matrix types. For fixed-size types, * it is redundant to pass \a rows and \a cols as arguments, so Identity() should be used * instead. * * \addexample Identity \label How to get an identity matrix * * Example: \include MatrixBase_identity_int_int.cpp * Output: \verbinclude MatrixBase_identity_int_int.out * * \sa Identity(), setIdentity(), isIdentity() */ template<typename Derived> EIGEN_STRONG_INLINE const typename MatrixBase<Derived>::IdentityReturnType MatrixBase<Derived>::Identity(int rows, int cols) { return NullaryExpr(rows, cols, ei_scalar_identity_op<Scalar>()); } /** \returns an expression of the identity matrix (not necessarily square). * * This variant is only for fixed-size MatrixBase types. For dynamic-size types, you * need to use the variant taking size arguments. * * Example: \include MatrixBase_identity.cpp * Output: \verbinclude MatrixBase_identity.out * * \sa Identity(int,int), setIdentity(), isIdentity() */ template<typename Derived> EIGEN_STRONG_INLINE const typename MatrixBase<Derived>::IdentityReturnType MatrixBase<Derived>::Identity() { EIGEN_STATIC_ASSERT_FIXED_SIZE(Derived) return NullaryExpr(RowsAtCompileTime, ColsAtCompileTime, ei_scalar_identity_op<Scalar>()); } /** \returns true if *this is approximately equal to the identity matrix * (not necessarily square), * within the precision given by \a prec. * * Example: \include MatrixBase_isIdentity.cpp * Output: \verbinclude MatrixBase_isIdentity.out * * \sa class CwiseNullaryOp, Identity(), Identity(int,int), setIdentity() */ template<typename Derived> bool MatrixBase<Derived>::isIdentity (RealScalar prec) const { for(int j = 0; j < cols(); ++j) { for(int i = 0; i < rows(); ++i) { if(i == j) { if(!ei_isApprox(coeff(i, j), static_cast<Scalar>(1), prec)) return false; } else { if(!ei_isMuchSmallerThan(coeff(i, j), static_cast<RealScalar>(1), prec)) return false; } } } return true; } template<typename Derived, bool Big = (Derived::SizeAtCompileTime>=16)> struct ei_setIdentity_impl { static EIGEN_STRONG_INLINE Derived& run(Derived& m) { return m = Derived::Identity(m.rows(), m.cols()); } }; template<typename Derived> struct ei_setIdentity_impl<Derived, true> { static EIGEN_STRONG_INLINE Derived& run(Derived& m) { m.setZero(); const int size = std::min(m.rows(), m.cols()); for(int i = 0; i < size; ++i) m.coeffRef(i,i) = typename Derived::Scalar(1); return m; } }; /** Writes the identity expression (not necessarily square) into *this. * * Example: \include MatrixBase_setIdentity.cpp * Output: \verbinclude MatrixBase_setIdentity.out * * \sa class CwiseNullaryOp, Identity(), Identity(int,int), isIdentity() */ template<typename Derived> EIGEN_STRONG_INLINE Derived& MatrixBase<Derived>::setIdentity() { return ei_setIdentity_impl<Derived>::run(derived()); } /** Resizes to the given size, and writes the identity expression (not necessarily square) into *this. * * \param rows the new number of rows * \param cols the new number of columns * * Example: \include Matrix_setIdentity_int_int.cpp * Output: \verbinclude Matrix_setIdentity_int_int.out * * \sa MatrixBase::setIdentity(), class CwiseNullaryOp, MatrixBase::Identity() */ template<typename _Scalar, int _Rows, int _Cols, int _Options, int _MaxRows, int _MaxCols> EIGEN_STRONG_INLINE Matrix<_Scalar, _Rows, _Cols, _Options, _MaxRows, _MaxCols>& Matrix<_Scalar, _Rows, _Cols, _Options, _MaxRows, _MaxCols>::setIdentity(int rows, int cols) { resize(rows, cols); return setIdentity(); } /** \returns an expression of the i-th unit (basis) vector. * * \only_for_vectors * * \sa MatrixBase::Unit(int), MatrixBase::UnitX(), MatrixBase::UnitY(), MatrixBase::UnitZ(), MatrixBase::UnitW() */ template<typename Derived> EIGEN_STRONG_INLINE const typename MatrixBase<Derived>::BasisReturnType MatrixBase<Derived>::Unit(int size, int i) { EIGEN_STATIC_ASSERT_VECTOR_ONLY(Derived) return BasisReturnType(SquareMatrixType::Identity(size,size), i); } /** \returns an expression of the i-th unit (basis) vector. * * \only_for_vectors * * This variant is for fixed-size vector only. * * \sa MatrixBase::Unit(int,int), MatrixBase::UnitX(), MatrixBase::UnitY(), MatrixBase::UnitZ(), MatrixBase::UnitW() */ template<typename Derived> EIGEN_STRONG_INLINE const typename MatrixBase<Derived>::BasisReturnType MatrixBase<Derived>::Unit(int i) { EIGEN_STATIC_ASSERT_VECTOR_ONLY(Derived) return BasisReturnType(SquareMatrixType::Identity(),i); } /** \returns an expression of the X axis unit vector (1{,0}^*) * * \only_for_vectors * * \sa MatrixBase::Unit(int,int), MatrixBase::Unit(int), MatrixBase::UnitY(), MatrixBase::UnitZ(), MatrixBase::UnitW() */ template<typename Derived> EIGEN_STRONG_INLINE const typename MatrixBase<Derived>::BasisReturnType MatrixBase<Derived>::UnitX() { return Derived::Unit(0); } /** \returns an expression of the Y axis unit vector (0,1{,0}^*) * * \only_for_vectors * * \sa MatrixBase::Unit(int,int), MatrixBase::Unit(int), MatrixBase::UnitY(), MatrixBase::UnitZ(), MatrixBase::UnitW() */ template<typename Derived> EIGEN_STRONG_INLINE const typename MatrixBase<Derived>::BasisReturnType MatrixBase<Derived>::UnitY() { return Derived::Unit(1); } /** \returns an expression of the Z axis unit vector (0,0,1{,0}^*) * * \only_for_vectors * * \sa MatrixBase::Unit(int,int), MatrixBase::Unit(int), MatrixBase::UnitY(), MatrixBase::UnitZ(), MatrixBase::UnitW() */ template<typename Derived> EIGEN_STRONG_INLINE const typename MatrixBase<Derived>::BasisReturnType MatrixBase<Derived>::UnitZ() { return Derived::Unit(2); } /** \returns an expression of the W axis unit vector (0,0,0,1) * * \only_for_vectors * * \sa MatrixBase::Unit(int,int), MatrixBase::Unit(int), MatrixBase::UnitY(), MatrixBase::UnitZ(), MatrixBase::UnitW() */ template<typename Derived> EIGEN_STRONG_INLINE const typename MatrixBase<Derived>::BasisReturnType MatrixBase<Derived>::UnitW() { return Derived::Unit(3); } #endif // EIGEN_CWISE_NULLARY_OP_H
#pragma once namespace Fangame { ////////////////////////////////////////////////////////////////////////// // Game engine that concedes the thread time portion if the step time is not due. class CLazyFixedStepEngine : public CEngine { public: explicit CLazyFixedStepEngine( int fpsCount ); virtual CFrameInformation AdvanceFrame() override final; private: CFixedStepEngine baseEngine; }; ////////////////////////////////////////////////////////////////////////// } // namespace Fangame.
#include <stdlib.h> #include <string.h> #include <stdio.h> #include "v1_config_map_node_config_source.h" v1_config_map_node_config_source_t *v1_config_map_node_config_source_create( char *kubelet_config_key, char *name, char *namespace, char *resource_version, char *uid ) { v1_config_map_node_config_source_t *v1_config_map_node_config_source_local_var = malloc(sizeof(v1_config_map_node_config_source_t)); if (!v1_config_map_node_config_source_local_var) { return NULL; } v1_config_map_node_config_source_local_var->kubelet_config_key = kubelet_config_key; v1_config_map_node_config_source_local_var->name = name; v1_config_map_node_config_source_local_var->namespace = namespace; v1_config_map_node_config_source_local_var->resource_version = resource_version; v1_config_map_node_config_source_local_var->uid = uid; return v1_config_map_node_config_source_local_var; } void v1_config_map_node_config_source_free(v1_config_map_node_config_source_t *v1_config_map_node_config_source) { if(NULL == v1_config_map_node_config_source){ return ; } listEntry_t *listEntry; free(v1_config_map_node_config_source->kubelet_config_key); free(v1_config_map_node_config_source->name); free(v1_config_map_node_config_source->namespace); free(v1_config_map_node_config_source->resource_version); free(v1_config_map_node_config_source->uid); free(v1_config_map_node_config_source); } cJSON *v1_config_map_node_config_source_convertToJSON(v1_config_map_node_config_source_t *v1_config_map_node_config_source) { cJSON *item = cJSON_CreateObject(); // v1_config_map_node_config_source->kubelet_config_key if (!v1_config_map_node_config_source->kubelet_config_key) { goto fail; } if(cJSON_AddStringToObject(item, "kubeletConfigKey", v1_config_map_node_config_source->kubelet_config_key) == NULL) { goto fail; //String } // v1_config_map_node_config_source->name if (!v1_config_map_node_config_source->name) { goto fail; } if(cJSON_AddStringToObject(item, "name", v1_config_map_node_config_source->name) == NULL) { goto fail; //String } // v1_config_map_node_config_source->namespace if (!v1_config_map_node_config_source->namespace) { goto fail; } if(cJSON_AddStringToObject(item, "namespace", v1_config_map_node_config_source->namespace) == NULL) { goto fail; //String } // v1_config_map_node_config_source->resource_version if(v1_config_map_node_config_source->resource_version) { if(cJSON_AddStringToObject(item, "resourceVersion", v1_config_map_node_config_source->resource_version) == NULL) { goto fail; //String } } // v1_config_map_node_config_source->uid if(v1_config_map_node_config_source->uid) { if(cJSON_AddStringToObject(item, "uid", v1_config_map_node_config_source->uid) == NULL) { goto fail; //String } } return item; fail: if (item) { cJSON_Delete(item); } return NULL; } v1_config_map_node_config_source_t *v1_config_map_node_config_source_parseFromJSON(cJSON *v1_config_map_node_config_sourceJSON){ v1_config_map_node_config_source_t *v1_config_map_node_config_source_local_var = NULL; // v1_config_map_node_config_source->kubelet_config_key cJSON *kubelet_config_key = cJSON_GetObjectItemCaseSensitive(v1_config_map_node_config_sourceJSON, "kubeletConfigKey"); if (!kubelet_config_key) { goto end; } if(!cJSON_IsString(kubelet_config_key)) { goto end; //String } // v1_config_map_node_config_source->name cJSON *name = cJSON_GetObjectItemCaseSensitive(v1_config_map_node_config_sourceJSON, "name"); if (!name) { goto end; } if(!cJSON_IsString(name)) { goto end; //String } // v1_config_map_node_config_source->namespace cJSON *namespace = cJSON_GetObjectItemCaseSensitive(v1_config_map_node_config_sourceJSON, "namespace"); if (!namespace) { goto end; } if(!cJSON_IsString(namespace)) { goto end; //String } // v1_config_map_node_config_source->resource_version cJSON *resource_version = cJSON_GetObjectItemCaseSensitive(v1_config_map_node_config_sourceJSON, "resourceVersion"); if (resource_version) { if(!cJSON_IsString(resource_version)) { goto end; //String } } // v1_config_map_node_config_source->uid cJSON *uid = cJSON_GetObjectItemCaseSensitive(v1_config_map_node_config_sourceJSON, "uid"); if (uid) { if(!cJSON_IsString(uid)) { goto end; //String } } v1_config_map_node_config_source_local_var = v1_config_map_node_config_source_create ( strdup(kubelet_config_key->valuestring), strdup(name->valuestring), strdup(namespace->valuestring), resource_version ? strdup(resource_version->valuestring) : NULL, uid ? strdup(uid->valuestring) : NULL ); return v1_config_map_node_config_source_local_var; end: return NULL; }
<gh_stars>1-10 // Copyright (C) Microsoft Corporation. All rights reserved. // // This program is free software; you can redistribute it // and/or modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; either version 2 // of the License, or (at your option) any later version. #define APPNAME "ocs-gpio" #define OCSPORTONTIME_FILE "/tmp/ocsgpio_ontime_%d.log" #define MAX_PORT_GPIOCOUNT 48 #define MAX_RELAY_GPIOCOUNT 4 #define MAX_DBGLED_GPIOCOUNT 4 #define MAX_BOARDID_GPIOCOUNT 3 #define MAX_PCBREVID_GPIOCOUNT 3 #define MAX_ROWTHSTAT_GPIOCOUNT 4 #define BLADE_STARTTIME_DELAY_SEC 40 #define PARAM_ALL 0 #define PORT_ONTIME_UPDATE_ID 2 typedef enum { FALSE = 0, TRUE = 1 } bool_t; enum { IDTYPE_MODEID = 0, IDTYPE_PCBREVID = 1, IDTYPE_MAX } BoardIDType; enum { THSTATTYPE_ALL = 0, THSTATTYPE_ROWTH = 1, THSTATTYPE_DCTH = 2, THSTATTYPE_ROWPRESENT = 3, THSTATTYPE_DCPRESENT = 4, THSTATTYPE_MAX } RowThStatType; #define RMMODE_PIB 0 #define RMMODE_ROWMGR 1 #define RMMODE_MTETFB 2 #define PCBREVID_EV 0 #define PCBREVID_DV 1 #define PCBREVID_PV 2 #define P12VAGOOD 1 #define P12VBGOOD 2 #define VERSION_MAKEWORD(maj, min, rev, bld) ( ((maj & 0xFF) << 24) | \ ((min & 0x0F) << 20) | \ ((rev & 0x0F) << 16) | \ (bld & 0xFFFF) ) #define VERSION_GET_MAJOR(ver) ( (ver >> 24) & 0xFF ) #define VERSION_GET_MINOR(ver) ( (ver >> 20) & 0x0F ) #define VERSION_GET_REVISION(ver) ( (ver >> 16) & 0x0F ) #define VERSION_GET_BUILD(ver) ( ver & 0xFFFF )
// COMPILE-FLAGS: -O2 int a(void) { return 1; } GLOBAL_ASM( glabel foo addiu $a0, $a0, 1 addiu $a0, $a0, 2 addiu $a0, $a0, 3 jr $ra addiu $a0, $a0, 4 ) float b(void) { return 1.2f; } GLOBAL_ASM( .late_rodata glabel float1 .float 12.34 .text glabel bar addiu $a0, $a0, 5 addiu $a0, $a0, 6 lui $v0, %hi(float1 + 1) jr $ra addiu $v0, $v0, %lo(float1 + 1) ) float c(void) { return 1.3f; }
double funcx_math(double x); double funcx_math_x(double x); double funcx_math_number(double x); double funcx_math_func(double funcx_return_func, double x); double funcx_math_trig(double funcx_return_trig, double x); double funcx_math_values(double funcx_return_values, double x); double funcx_math(double x) { double funcx_return = 0; while (true) { fc_getline(); if (active_script[line-1]=="x") { if (isnan(funcx_return)==false) { funcx_return = x; } else { funcx_return = funcx_return*x; } } else if ((active_script[line-1]=="^")or (active_script[line-1]=="_power")) { funcx_return = pow(funcx_return, funcx_math_number(x)); } else if (active_script[line-1]=="*") { funcx_return = funcx_return * funcx_math_number(x); } else if (active_script[line-1]=="+") { funcx_return = funcx_return + funcx_math_number(x); } else if (active_script[line-1]=="-") { funcx_return = funcx_return - funcx_math_number(x); } else if ((active_script[line-1]=="/")or(active_script[line-1]=="÷")) { funcx_return = funcx_return / funcx_math_number(x); } else if (active_script[line-1]=="(") { funcx_return = funcx_return * funcx_math(x); } else if (active_script[line-1]=="_var") { funcx_return = funcx_return * external_using_allnumbers(); } else if (active_script[line-1]=="_index") { scan_stream(); } else if (active_script[line-1]=="_values") { funcx_return = funcx_math_values(funcx_return, x); } else if (active_script[line-1]=="_func") { funcx_return = funcx_math_func(funcx_return, x); } else if (active_script[line-1]=="_trig") { funcx_return = funcx_math_trig(funcx_return, x); } else if ((active_script[line-1]=="]")or(active_script[line-1]==")")) { return funcx_return; } else if (active_script[line-1]=="_hyper") { } else if ((active_script[line-1]=="_exp")or(active_script[line-1]=="_log")) { } else { funcx_return = funcx_return + atof(active_script[line-1].c_str()); } } return funcx_return; } double funcx_math_number(double x) { fc_getline(); if (active_script[line-1]=="x") { return x; } else if (active_script[line-1]=="(") { return funcx_math(x); } else if (active_script[line-1]=="_var") { return external_using_allnumbers(); } else { return atof(active_script[line-1].c_str()); } } double funcx_math_x(double x) { return x; } void funcx_math_add() { } void funcx_math_sub() { } void funcx_math_mult() { } void funcx_math_div() { } void funcx_math_power() { } void funcx_math_bracket() { } double funcx_math_values(double funcx_return_values, double x) { fc_getline(); if ((active_script[line-1]=="_pi")or(active_script[line-1]=="π")) { funcx_return_values = 3.14159265359; } else if ((active_script[line-1]=="e")) { funcx_return_values = 2.71828182845; } else if (active_script[line-1]=="x") { funcx_return_values = x; } else if (active_script[line-1]=="y") { funcx_return_values = funcx_return_values; } else if ((active_script[line-1]=="_gr")or(active_script[line-1]=="φ")) { funcx_return_values = 1.61803398874; } else if ((active_script[line-1]=="_theta")or(active_script[line-1]=="θ")) { funcx_return_values = x; } else if ((active_script[line-1]=="Sn")or(active_script[line-1]=="_ratios")) { funcx_return_values = funcx_return_values; } else if (active_script[line-1]=="q") { funcx_return_values = 1.787231650; } else if (active_script[line-1]=="c") { funcx_return_values = 0.64341054629; } else if (active_script[line-1]=="G") { funcx_return_values = 0.8346268; } else if ((active_script[line-1]=="_omega")or(active_script[line-1]=="Ω")) { funcx_return_values = 0.56714329040; } else if ((active_script[line-1]=="_inf")or(active_script[line-1]=="∞")) { funcx_return_values = numeric_limits<double>::infinity(); } else if (active_script[line-1]=="_nan") { funcx_return_values = NAN; } else { funcx_return_values = funcx_return_values * atof(active_script[line-1].c_str()); } return funcx_return_values; } double funcx_math_func(double funcx_return_func, double x) { fc_getline(); if ((active_script[line-1]=="_power")or(active_script[line-1]=="^")) { funcx_return_func = pow(funcx_math_number(x),funcx_math_number(x)); } else if ((active_script[line-1]=="_sqrt")or(active_script[line-1]=="√")) { funcx_return_func = sqrt(funcx_math_number(x)); } else if ((active_script[line-1]=="_cbrt")or(active_script[line-1]=="3√")) { funcx_return_func = cbrt(funcx_math_number(x)); } else if (active_script[line-1]=="_hypot") { funcx_return_func = hypot(funcx_math_number(x),funcx_math_number(x)); } else if ((active_script[line-1]=="_ln")or(active_script[line-1]=="_loge")) { funcx_return_func = log(funcx_math_number(x)); } else if ((active_script[line-1]=="_log")or(active_script[line-1]=="_log10")) { funcx_return_func = log10(funcx_math_number(x)); } else if ((active_script[line-1]=="_abs")or(active_script[line-1]=="|")) { funcx_return_func = abs(funcx_math_number(x)); } else { funcx_return_func = funcx_return_func * atof(active_script[line-1].c_str()); } return funcx_return_func; } double funcx_math_trig(double funcx_return_trig, double x) { fc_getline(); if (active_script[line-1]=="_sin") { funcx_return_trig = sin(funcx_math_number(x)); } else if (active_script[line-1]=="_cos") { funcx_return_trig = cos(funcx_math_number(x)); } else if (active_script[line-1]=="_tan") { funcx_return_trig = tan(funcx_math_number(x)); } else if (active_script[line-1]=="_arcsin") { funcx_return_trig = asin(funcx_math_number(x)); } else if (active_script[line-1]=="_arccos") { funcx_return_trig = acos(funcx_math_number(x)); } else if (active_script[line-1]=="_arctan") { funcx_return_trig = atan(funcx_math_number(x)); } else { funcx_return_trig = funcx_return_trig * atof(active_script[line-1].c_str()); } return funcx_return_trig; } void funcx_math_trig_cos() { } void funcx_math_trig_arccos() { } void funcx_math_trig_sin() { } void funcx_math_trig_arcsin() { } void funcx_math_trig_tan() { } void funcx_math_trig_arctan() { } void funcx_math_trig_arctan2() { } void funcx_math_hyper() { } void funcx_math_hyper_cosh() { } void funcx_math_hyper_sinh() { } void funcx_math_hyper_tan() { } void funcx_math_hyper_acosh() { } void funcx_math_hyper_asinh() { } void funcx_math_hyper_atanh() { }
// // PodViewController.h // Pods // // Created by THIRUVADISAMY_P on 25/01/16. // // #import <UIKit/UIKit.h> @interface PodViewController : UIViewController // Method to Update the FadeOut View - (void) fadeOut:(UIView *)animationView timeInterval:(NSTimeInterval)timeDuration timeDelay:(NSTimeInterval)timeDelay fadeOutValue:(CGFloat) fadeOutOpacity; // Method to Update the FadeIn View - (void) fadeIn:(UIView *)animationView timeInterval:(NSTimeInterval)timeDuration timeDelay:(NSTimeInterval)timeDelay fadeOutValue:(CGFloat) fadeOutOpacity; // Method to Perform FadeOut Operations -(void) fadeOperation:(UIView *) animationView WithTimeInterval:(NSTimeInterval) timeDuration WithTImeDelay:(NSTimeInterval) timeDelay fadeOutStartingValue:(CGFloat ) fadeOutStartingOpacity fadeOutEndingValue:(CGFloat) fadeOutEndingOpacity; @end
/* SPDX-License-Identifier: BSD-2-Clause */ /******************************************************************************* * Copyright 2017, Fraunhofer SIT sponsored by Infineon Technologies AG * All rights reserved. *******************************************************************************/ #ifdef HAVE_CONFIG_H #include <config.h> #endif #include <stdbool.h> #include <stdlib.h> #include <string.h> #include "tss2_esys.h" #include "test-esapi.h" #include "test-options.h" #include "context-util.h" #include "tss2-esys/esys_int.h" #define LOGMODULE test #include "util/log.h" /** Define a proxy tcti that returns yielded on every second invocation * thus the corresponding handling code in ESAPI can be tested. * The first invocation will be Tss2_Sys_StartUp. */ TSS2_RC (*transmit_hook) (const uint8_t *command_buffer, size_t command_size) = NULL; #define TCTI_PROXY_MAGIC 0x5250584f0a000000ULL /* 'PROXY\0\0\0' */ #define TCTI_PROXY_VERSION 0x1 enum state { forwarding, intercepting }; typedef struct { uint64_t magic; uint32_t version; TSS2_TCTI_TRANSMIT_FCN transmit; TSS2_TCTI_RECEIVE_FCN receive; TSS2_RC (*finalize) (TSS2_TCTI_CONTEXT *tctiContext); TSS2_RC (*cancel) (TSS2_TCTI_CONTEXT *tctiContext); TSS2_RC (*getPollHandles) (TSS2_TCTI_CONTEXT *tctiContext, TSS2_TCTI_POLL_HANDLE *handles, size_t *num_handles); TSS2_RC (*setLocality) (TSS2_TCTI_CONTEXT *tctiContext, uint8_t locality); TSS2_TCTI_CONTEXT *tctiInner; enum state state; } TSS2_TCTI_CONTEXT_PROXY; static TSS2_TCTI_CONTEXT_PROXY* tcti_proxy_cast (TSS2_TCTI_CONTEXT *ctx) { TSS2_TCTI_CONTEXT_PROXY *ctxi = (TSS2_TCTI_CONTEXT_PROXY*)ctx; if (ctxi == NULL || ctxi->magic != TCTI_PROXY_MAGIC) { LOG_ERROR("Bad tcti passed."); return NULL; } return ctxi; } static TSS2_RC tcti_proxy_transmit( TSS2_TCTI_CONTEXT *tctiContext, size_t command_size, const uint8_t *command_buffer ) { TSS2_RC rval; TSS2_TCTI_CONTEXT_PROXY *tcti_proxy = tcti_proxy_cast(tctiContext); if (tcti_proxy->state == intercepting) { return TSS2_RC_SUCCESS; } if (transmit_hook != NULL) { rval = transmit_hook(command_buffer, command_size); if (rval != TSS2_RC_SUCCESS) { LOG_ERROR("transmit hook requested error"); return rval; } } rval = Tss2_Tcti_Transmit(tcti_proxy->tctiInner, command_size, command_buffer); if (rval != TSS2_RC_SUCCESS) { LOG_ERROR("Calling TCTI Transmit"); return rval; } return rval; } uint8_t yielded_response[] = { 0x80, 0x01, /* TPM_ST_NO_SESSION */ 0x00, 0x00, 0x00, 0x0A, /* Response Size 10 */ 0x00, 0x00, 0x09, 0x08 /* TPM_RC_YIELDED */ }; static TSS2_RC tcti_proxy_receive( TSS2_TCTI_CONTEXT *tctiContext, size_t *response_size, uint8_t *response_buffer, int32_t timeout ) { TSS2_RC rval; TSS2_TCTI_CONTEXT_PROXY *tcti_proxy = tcti_proxy_cast(tctiContext); if (tcti_proxy->state == intercepting) { *response_size = sizeof(yielded_response); if (response_buffer != NULL) { memcpy(response_buffer, &yielded_response[0], sizeof(yielded_response)); tcti_proxy->state = forwarding; } return TSS2_RC_SUCCESS; } rval = Tss2_Tcti_Receive(tcti_proxy->tctiInner, response_size, response_buffer, timeout); if (rval != TSS2_RC_SUCCESS) { LOG_ERROR("Calling TCTI Transmit"); return rval; } /* First read with response buffer == NULL is to get the size of the * response. The subsequent read needs to be forwarded also */ if (response_buffer != NULL) tcti_proxy->state = intercepting; return rval; } static void tcti_proxy_finalize( TSS2_TCTI_CONTEXT *tctiContext) { memset(tctiContext, 0, sizeof(TSS2_TCTI_CONTEXT_PROXY)); } static TSS2_RC tcti_proxy_initialize( TSS2_TCTI_CONTEXT *tctiContext, size_t *contextSize, TSS2_TCTI_CONTEXT *tctiInner) { TSS2_TCTI_CONTEXT_PROXY *tcti_proxy = (TSS2_TCTI_CONTEXT_PROXY*) tctiContext; if (tctiContext == NULL && contextSize == NULL) { return TSS2_TCTI_RC_BAD_VALUE; } else if (tctiContext == NULL) { *contextSize = sizeof(*tcti_proxy); return TSS2_RC_SUCCESS; } /* Init TCTI context */ memset(tcti_proxy, 0, sizeof(*tcti_proxy)); TSS2_TCTI_MAGIC (tctiContext) = TCTI_PROXY_MAGIC; TSS2_TCTI_VERSION (tctiContext) = TCTI_PROXY_VERSION; TSS2_TCTI_TRANSMIT (tctiContext) = tcti_proxy_transmit; TSS2_TCTI_RECEIVE (tctiContext) = tcti_proxy_receive; TSS2_TCTI_FINALIZE (tctiContext) = tcti_proxy_finalize; TSS2_TCTI_CANCEL (tctiContext) = NULL; TSS2_TCTI_GET_POLL_HANDLES (tctiContext) = NULL; TSS2_TCTI_SET_LOCALITY (tctiContext) = NULL; tcti_proxy->tctiInner = tctiInner; tcti_proxy->state = forwarding; return TSS2_RC_SUCCESS; } /** * This program is a template for integration tests (ones that use the TCTI * and the ESAPI contexts / API directly). It does nothing more than parsing * command line options that allow the caller (likely a script) to specify * which TCTI to use for the test. */ int main(int argc, char *argv[]) { TSS2_RC rc; size_t tcti_size; TSS2_TCTI_CONTEXT *tcti_context; TSS2_TCTI_CONTEXT *tcti_inner; ESYS_CONTEXT *esys_context; TSS2_ABI_VERSION abiVersion = { TSSWG_INTEROP, TSS_SAPI_FIRST_FAMILY, TSS_SAPI_FIRST_LEVEL, TSS_SAPI_FIRST_VERSION }; int ret; test_opts_t opts = { .tcti_type = TCTI_DEFAULT, .device_file = DEVICE_PATH_DEFAULT, .socket_address = HOSTNAME_DEFAULT, .socket_port = PORT_DEFAULT, }; get_test_opts_from_env(&opts); if (sanity_check_test_opts(&opts) != 0) { LOG_ERROR("TPM Startup FAILED! Error in sanity check"); exit(1); } tcti_inner = tcti_init_from_opts(&opts); if (tcti_inner == NULL) { LOG_ERROR("TPM Startup FAILED! Error tcti init"); exit(1); } rc = tcti_proxy_initialize(NULL, &tcti_size, tcti_inner); if (rc != TSS2_RC_SUCCESS) { LOG_ERROR("tcti initialization FAILED! Response Code : 0x%x", rc); return 1; } tcti_context = calloc(1, tcti_size); if (tcti_inner == NULL) { LOG_ERROR("TPM Startup FAILED! Error tcti init"); exit(1); } rc = tcti_proxy_initialize(tcti_context, &tcti_size, tcti_inner); if (rc != TSS2_RC_SUCCESS) { LOG_ERROR("tcti initialization FAILED! Response Code : 0x%x", rc); return 1; } rc = Esys_Initialize(&esys_context, tcti_context, &abiVersion); if (rc != TSS2_RC_SUCCESS) { LOG_ERROR("Esys_Initialize FAILED! Response Code : 0x%x", rc); return 1; } rc = Esys_Startup(esys_context, TPM2_SU_CLEAR); if (rc != TSS2_RC_SUCCESS && rc != TPM2_RC_INITIALIZE) { LOG_ERROR("Esys_Startup FAILED! Response Code : 0x%x", rc); return 1; } rc = Esys_SetTimeout(esys_context, TSS2_TCTI_TIMEOUT_BLOCK); if (rc != TSS2_RC_SUCCESS) { LOG_ERROR("Esys_SetTimeout FAILED! Response Code : 0x%x", rc); return 1; } ret = test_invoke_esapi(esys_context); Esys_Finalize(&esys_context); tcti_teardown(tcti_inner); tcti_teardown(tcti_context); return ret; }
<reponame>lassik/leapsecondtable<gh_stars>0 #include "example.h" static int64_t * update(size_t *n) { int64_t *leap; int64_t *newleap; size_t cap; leap = 0; for (cap = 16; cap <= 256; cap *= 2) { newleap = realloc(leap, sizeof(*leap) * cap); if (newleap == NULL) panic_errno("realloc"); leap = newleap; memset(leap, 0, sizeof(*leap) * cap); *n = cap; if (getleapsecondtable(leap, n) == 0) { return leap; } if (errno != ENOMEM) panic_errno("getleapsecondtable"); } free(leap); panic("too many"); return NULL; } int main(void) { int64_t *leap; size_t n; leap = update(&n); print_table(leap, n); return 0; }
#include <stddef.h> #define ODEINT_INTEGRATOR_DEFAULT_RTOL 1e-6 #define ODEINT_INTEGRATOR_DEFAULT_ATOL 1e-8 typedef enum _OdeIntMethod { ODEINT_METHOD_EULER, ODEINT_METHOD_HEUNS, ODEINT_METHOD_HEUNS_EULER, ODEINT_METHOD_BOGACKI_SHAMPINE, ODEINT_METHOD_RUNGE_KUTTA, ODEINT_METHOD_RUNGE_KUTTA_FELHBERG, ODEINT_METHOD_CASH_KARP, ODEINT_METHOD_DORMAND_PRINCE } OdeIntMethod; typedef struct _OdeIntIntegrator OdeIntIntegrator; /** * @t: The timestep * @y: The state of the ODE * @F: dy/dt */ typedef void (*OdeIntFunc) (double t, const double *y, double *F, void *user_data); OdeIntIntegrator * odeint_integrator_new (OdeIntMethod method, double *t0, double *y0, size_t n, double rtol, double atol); void odeint_integrator_integrate (OdeIntIntegrator *self, OdeIntFunc func, void* user_data, double tw); void odeint_integrator_free (OdeIntIntegrator *self);
// // APIBaseRequest.h // #import <Foundation/Foundation.h> #import "AFURLRequestSerialization.h" @class AFHTTPRequestOperation; @class AFDownloadRequestOperation; typedef NS_ENUM(NSInteger , APIRequestMethod) { APIRequestMethodGet = 0, APIRequestMethodPost, APIRequestMethodHead, APIRequestMethodPut, APIRequestMethodDelete, APIRequestMethodPatch, }; typedef NS_ENUM(NSInteger , APIRequestSerializerType) { APIRequestSerializerTypeHTTP = 0, APIRequestSerializerTypeJSON, }; typedef NS_ENUM(NSInteger , APIRequestPriority) { APIRequestPriorityLow = -4L, APIRequestPriorityDefault = 0, APIRequestPriorityHigh = 4, }; typedef void (^AFConstructingBlock)(id<AFMultipartFormData> formData); typedef void (^AFDownloadProgressBlock)(AFDownloadRequestOperation *operation, NSInteger bytesRead, long long totalBytesRead, long long totalBytesExpected, long long totalBytesReadForFile, long long totalBytesExpectedToReadForFile); @class APIBaseRequest; typedef void(^APIRequestCompletionBlock)(__kindof APIBaseRequest *request); @protocol APIRequestDelegate <NSObject> @optional - (void)requestFinished:(APIBaseRequest *)request; - (void)requestFailed:(APIBaseRequest *)request; - (void)clearRequest; @end @protocol APIRequestAccessory <NSObject> @optional - (void)requestWillStart:(id)request; - (void)requestWillStop:(id)request; - (void)requestDidStop:(id)request; @end @interface APIBaseRequest : NSObject /// Tag @property (nonatomic) NSInteger tag; /// User info @property (nonatomic, strong) NSDictionary *userInfo; @property (nonatomic, strong) AFHTTPRequestOperation *requestOperation; /// request delegate object @property (nonatomic, weak) id<APIRequestDelegate> delegate; @property (nonatomic, strong, readonly) NSDictionary *responseHeaders; @property (nonatomic, strong, readonly) NSData *responseData; @property (nonatomic, strong, readonly) NSString *responseString; @property (nonatomic, strong, readonly) id responseJSONObject; @property (nonatomic, readonly) NSInteger responseStatusCode; @property (nonatomic, strong, readonly) NSError *requestOperationError; @property (nonatomic, copy) APIRequestCompletionBlock successCompletionBlock; @property (nonatomic, copy) APIRequestCompletionBlock failureCompletionBlock; @property (nonatomic, strong) NSMutableArray *requestAccessories; /// 请求的优先级, 优先级高的请求会从请求队列中优先出列 @property (nonatomic) APIRequestPriority requestPriority; /// Return cancelled state of request operation @property (nonatomic, readonly, getter=isCancelled) BOOL cancelled; /// append self to request queue - (void)start; /// remove self from request queue - (void)stop; - (BOOL)isExecuting; /// block回调 - (void)startWithCompletionBlockWithSuccess:(APIRequestCompletionBlock)success failure:(APIRequestCompletionBlock)failure; - (void)setCompletionBlockWithSuccess:(APIRequestCompletionBlock)success failure:(APIRequestCompletionBlock)failure; /// 把block置nil来打破循环引用 - (void)clearCompletionBlock; /// Request Accessory,可以hook Request的start和stop - (void)addAccessory:(id<APIRequestAccessory>)accessory; /// 以下方法由子类继承来覆盖默认值 /// 请求成功的回调 - (void)requestCompleteFilter; /// 请求失败的回调 - (void)requestFailedFilter; /// 请求的URL - (NSString *)requestUrl; /// 请求的CdnURL - (NSString *)cdnUrl; /// 请求的BaseURL - (NSString *)baseUrl; /// 请求的连接超时时间,默认为60秒 - (NSTimeInterval)requestTimeoutInterval; /// 请求的参数列表 - (id)requestArgument; /// 用于在cache结果,计算cache文件名时,忽略掉一些指定的参数 - (id)cacheFileNameFilterForRequestArgument:(id)argument; /// Http请求的方法 - (APIRequestMethod)requestMethod; /// 请求的SerializerType - (APIRequestSerializerType)requestSerializerType; /// 请求的Server用户名和密码 - (NSArray *)requestAuthorizationHeaderFieldArray; /// 在HTTP报头添加的自定义参数 - (NSDictionary *)requestHeaderFieldValueDictionary; /// 构建自定义的UrlRequest, /// 若这个方法返回非nil对象,会忽略requestUrl, requestArgument, requestMethod, requestSerializerType - (NSURLRequest *)buildCustomUrlRequest; /// 是否使用CDN的host地址 - (BOOL)useCDN; /// 用于检查JSON是否合法的对象 - (id)jsonValidator; /// 用于检查Status Code是否正常的方法 - (BOOL)statusCodeValidator; /// 当POST的内容带有文件等富文本时使用 - (AFConstructingBlock)constructingBodyBlock; /// 当需要断点续传时,指定续传的地址 - (NSString *)resumableDownloadPath; /// 当需要断点续传时,获得下载进度的回调 - (AFDownloadProgressBlock)resumableDownloadProgressBlock; @end
// // HCDWorkSoftWare.h // 17桥接模式 // // Created by huangchengdu on 17/5/18. // Copyright © 2017年 黄成都. All rights reserved. // #import <Foundation/Foundation.h> #import "HCDSoftware.h" @interface HCDWorkSoftWare : NSObject<HCDSoftware> @end
<filename>ADC/scheduler/scheduler.h #ifndef __SCHEDULER_H_ #define __SCHEDULER_H_ /** * @file scheduler.h * @brief Creating and Implemnting scheduler task executer. * * @details Implemented task timing and execution machine. the scheduler API * allows these functionality: * 1)Adding a task to the executor specifying its period * 2)Run the executor - this call will start the periodic execution of the * tasks. * 3)Pause the execution. * @author <NAME> (<EMAIL>) * * @bug No known bugs. */ #include "ADTDefs.h" #include <stddef.h> typedef struct Scheduler Scheduler; /** * @brief Creating pointer for tasks scheduler and executer. * @param[in] Void * @return scheduler pointer - On success / NULL on fail */ Scheduler* SchedulerCreate(void); /** * @brief Destroying periodic task executer and scheduler completely and setting * user pointer to NULL. * @param[in] user scheduler pointer address. * @return Void */ void SchedulerDestroy(Scheduler** _scheduler); /** * @brief adding new task for scheduler. user can add anew task by calling this * function and paasing pointer to Created task. * @param[in] pointer to manager, period time and function pointer. * @return ADT status * @retval SUCCESS on success * @retval UNINITIALIZED_ERROR if the manager is not initialized * @retval ENVALID_FUNCTION_PARAMETER if NULL function pointer was passed or * task period=0 */ /*ADTStatus SchedulerAppendNewTask(Scheduler* _scheduler, void* _newTask);*/ ADTStatus SchedulerAppendNewTask(Scheduler* _scheduler, size_t _taskPeriod , int (*TaskFunction)(void *context), void *context); /** * @brief Starting Execution process. * @param[in] pointer to scheduler * @return ADT status * @retval SUCCESS on success * @retval UNINITIALIZED_ERROR if the manager is not initialized * @retval * task period=0 */ ADTStatus SchedulerStartExecution(Scheduler* _scheduler); size_t SchedulerSize(Scheduler* _scheduler); /** * @brief Pausing Execution process. * @param[in] pointer to scheduler * @return ADT status * @retval SUCCESS on success * @retval UNINITIALIZED_ERROR if the manager is not initialized * @retval * task period=0 */ ADTStatus SchedulerPauseExecution(Scheduler* _scheduler); #endif /*__SCHEDULER_H_*/
#include <std.h> inherit MONSTER; void create() { ::create(); set_name("guardian"); set_id(({ "demon", "guardian" })); set_short("A Demonic Guardian"); set_long( "This monstrosity stands guard over the gateway. He looks like something\n"+ "you would not want to meet under ANY circumstances."); set_race("demon"); set_class("mage"); set_stats("strength", 18); set_stats("constitution", 16); set_stats("dexterity", 10); set_stats("intelligence", 18); set_stats("wisdom", 12); set_stats("charisma", 8); set_body_type("demon"); set_level(30); set_hp(100+random(100)); set_max_mp(query_hp()); set_mp(query_hp()); set_max_sp(query_hp()); set_sp(query_hp()); set_max_hp(query_hp()); set_spells(({ "magic missile", "armor", "fireball", "scorcher", "lightning bolt", "burning hands" })); set_spell_chance(35); set_gender("male"); set_wielding_limbs(({ "right hand", "left hand" })); set_ac(1); set_exp(10000+random(1000)); add_money("platinum", random(100)); new("/d/sands/obj/staff")->move(this_object()); command("wield staff in left hand"); }
/** * This header is generated by class-dump-z 0.2b. * * Source: /System/Library/PrivateFrameworks/GMM.framework/GMM */ #import <GMM/GMM-Structs.h> #import <GMM/XXUnknownSuperclass.h> @class NSMutableArray; __attribute__((visibility("hidden"))) @interface GMMTrafficTile : XXUnknownSuperclass { BOOL empty; // 4 = 0x4 double expirationTime; // 8 = 0x8 NSMutableArray *roadsAtSpeed[4]; // 16 = 0x10 } @property(readonly, assign, nonatomic) double expirationTime; // G=0x3dc1; @property(readonly, assign, nonatomic, getter=isEmpty) BOOL empty; // G=0x43e5; @synthesize + (double)defaultExpirationTime; // 0x3cdd // declared property getter: - (BOOL)isEmpty; // 0x43e5 - (void)invalidate; // 0x4385 - (BOOL)readFromStream:(InputDataStream *)stream tilePath:(const XXStruct_j8inqB *)path; // 0x3ded - (id)getRoadsAtSpeed:(int)speed; // 0x3dd9 // declared property getter: - (double)expirationTime; // 0x3dc1 - (void)dealloc; // 0x3d5d - (id)init; // 0x3cf1 @end
<filename>IrisLangLibrary/include/IrisComponents/IrisExpressions/IrisCastExpression.h #ifndef _H_IRISCASTEXPRESSION_ #define _H_IRISCASTEXPRESSION_ #include "IrisExpression.h" class IrisCastExpression : public IrisExpression { public: virtual bool Generate(); IrisCastExpression(); ~IrisCastExpression(); bool Validate() override; }; #endif // !_H_IRISCASTEXPRESSION_
<gh_stars>1-10 #include "pch.h" #include "main_renderer_interface.h" #include "window_environment.h" #include "device_resources.h" #include "sampling_renderer.h" #include "residency_manager.h" #include "free_camera.h" //Main renderer of the app namespace sample { class MainRenderer : public IMainRenderer { public: void Initialize() override; void Uninitialize() override; void Load() override; void Run() override; void OnWindowSizeChanged(const sample::window_environment& envrionment) override; void SetWindow(::IUnknown* w, const sample::window_environment& envrionment) override; private: void WaitForIdleGpu(); std::unique_ptr<sample::DeviceResources> m_deviceResources; //gpu, swapchain, queues, heaps for rtv std::unique_ptr<sample::SamplingRenderer> m_samplingRenderer; //render targets for residency std::unique_ptr<sample::ResidencyManager> m_residencyManager; //updates physical data std::mutex m_blockRendering; //block render thread for the swap chain resizes winrt::com_ptr <ID3D12CommandAllocator> m_command_allocator[2]; //one per frame winrt::com_ptr <ID3D12GraphicsCommandList1> m_command_list[2]; //one per frame uint32_t m_frame_index = 0; uint64_t m_fence_value[2] = { 1, 1 }; uint64_t m_frame_number = 0; //count frames //Rendering winrt::com_ptr< ID3D12RootSignature> m_root_signature; winrt::com_ptr< ID3D12PipelineState> m_sampling_renderer_state; //responsible for output of the parts that we want winrt::com_ptr< ID3D12PipelineState> m_terrain_renderer_state; //responsible to renderer the terrain winrt::com_ptr <ID3D12Resource1> m_geometry_vertex_buffer; //planet geometry winrt::com_ptr <ID3D12Resource1> m_geometry_index_buffer; //planet indices uint32_t m_diffuse_srv = 0; //pointers to the shader resource heap to be used in the shaders uint32_t m_normal_srv = 1; uint32_t m_diffuse_residency_srv = 2; uint32_t m_normal_residency_srv = 3; //view concepts D3D12_VERTEX_BUFFER_VIEW m_planet_vertex_view; //vertices for render D3D12_INDEX_BUFFER_VIEW m_planet_index_view; //indices for render FreeCamera m_camera; }; }
//做為確認 UITableViewCell 的編輯狀態之用, 以方便在不同的 Editing mode 下進行 TableViewCell 的 layout 設定 enum{ kFNCCellStateDefaultMask = 1, kFNCCellStateShowingEditControlMask = 2, kFNCCellStateShowingDeleteConfirmationMask = 3, kFNCCellStateNone = 4 }; typedef NSInteger FNCCellState; //This enumration contains the possiblity factor //設定不同的機率代號 enum { kFNCPossibilityLow = 1, kFNCPossibilityMedium = 2, kFNCPossibilityHigh = 4 }; typedef NSInteger FNCPossibility; //用以區別所要擷取的色彩單元為何? 依據傳入的色彩單元,再回傳 R G B 的 CGFloat 數值 enum { kFNCUserDefaultColorComponetRed = 0, kFNCUserDefaultColorComponetGreen, kFNCUserDefaultColorComponetBlue }; typedef NSInteger FNCUserDefaultColorComponet; //用以決定指針旋轉是逆時針還是順時針旋轉 enum { kFNCCounterClockwiseRotation = 1, kFNCClockwiseRotation = 2 }; typedef NSInteger FNCRotationType; //用來決定轉盤動畫更新方式 enum { kFNCPieGraphNoActionMask = -1, //預設的 Action case, 不提供任何作用 kFNCPieGraphNormalMask = 1, //當使用者有選擇項目時,而前目前圓盤是使用者圓盤 kFNCPieGraphToDefaultMask = 2, //當使用者沒有選擇時,而且目前是使用者圓盤 (此項設定也使用於 沒有任何選擇而且目前是預設圓盤) kFNCDefaultToPieGraphMask = 3 //當使用者有選擇項目時,而且目前是預設圓盤 }; typedef NSInteger FNCPieGraphMask; #define kHidesAndRevealImageView @"hidesAndRevealImageView" //進入 editing mode 的時候,隱藏 UITableView 左方的選擇鍵 #define kCleanAllUserDefaults @"cleanAllUserDefaults" //通知 UITableViewCell 清除選項 #define kSelectAllUserDefaults @"selectAllUserDefaults" #define kNoUserSelection @"noUserSelection"//當使用者沒有任何預先選擇而觸碰指針時,使用通知 AnimatingViewController show BackListViewController #define kHideADBannerView @"hideADBannerViewOnScreen" #define kRevealADBannerView @"revealADBannerViewOnScreen" #define kFNCRotationGameDidStart @"FNCRotationGameDidStart" //發出轉盤遊戲開始的通知 #define kFNCRotationGameDidStop @"FNCRotationGameDidStop" //發出轉盤遊戲結束的通知 //NSUserDefaultKey #define kFNCVersionKey @"Version" #define kFNCFirstTimeStartUpKey @"FirstTime" //修改此處以決定是否為付費版本 ,Free or Paid #define kFNCVersion @"Paid" //此為第二版本的Key, second version is 101. #define kFNCSoftwareVersion @"101" #define MAX_USER_SELECTION_COUNT 1e100f //修改此處以決定最大可選擇數目
#ifndef RGBA_COLOR_OPS_H #define RGBA_COLOR_OPS_H #include "rgbamodulebase.h" namespace anl { enum EColorOperations { COLORMULTIPLY, COLORADD, SCREEN, OVERLAY, SOFTLIGHT, HARDLIGHT, DODGE, BURN, LINEARDODGE, LINEARBURN }; class CRGBAColorOps : public CRGBAModuleBase { public: CRGBAColorOps(); CRGBAColorOps(int op); ~CRGBAColorOps(); void setOperation(int op); void setSource1(float r, float g, float b, float a); void setSource1(CRGBAModuleBase *m); void setSource2(float r, float g, float b, float a); void setSource2(CRGBAModuleBase *m); SRGBA get(double x, double y); SRGBA get(double x, double y, double z); SRGBA get(double x, double y, double z, double w); SRGBA get(double x, double y, double z, double w, double u, double v); protected: CRGBAParameter m_source1, m_source2; int m_op; SRGBA multiply(SRGBA &s1, SRGBA &s2); SRGBA add(SRGBA &s1, SRGBA &s2); SRGBA screen(SRGBA &s1, SRGBA &s2); SRGBA overlay(SRGBA &s1, SRGBA &s2); SRGBA softLight(SRGBA &s1, SRGBA &s2); SRGBA hardLight(SRGBA &s1, SRGBA &s2); SRGBA dodge(SRGBA &s1, SRGBA &s2); SRGBA burn(SRGBA &s1, SRGBA &s2); SRGBA linearDodge(SRGBA &s1, SRGBA &s2); SRGBA linearBurn(SRGBA &s1, SRGBA &s2); }; }; #endif
#include<stdio.h> #include<string.h> #include<stdlib.h> int main(int argc, char** argv){ if(argc==2&&strcmp("-h",argv[1])==0){ printf("This string is built with some simple math operations, 123+123=246, on chars converted to ints, 0x32->2.\n"); }else if(argc!=3){ printf("Usage: ./prog input input\n"); printf("Hint: ./prog -h\n"); }else{ int x=1012; int y=325; int a=atoi(argv[1]); int b=atoi(argv[2]); a-b==x+y?printf("Score!\n"):printf("Fail!\n"); } return 0; }
<reponame>scofieldzhu/blackconfigurator #ifndef __BLACK_CONFIGURATOR_FACTORY_H__ #define __BLACK_CONFIGURATOR_FACTORY_H__ #include "common.h" __BCONF_BEGIN__ // {D2952CBD-3AD8-4130-83F6-6FEA9973E76E} //const GUID CLSID_BlackConfigurator; class BlackConfiguratorFactory : public IClassFactory { public: HRESULT __stdcall QueryInterface(const IID& iid, void **ppv); ULONG __stdcall AddRef(); ULONG __stdcall Release(); HRESULT __stdcall CreateInstance(IUnknown *, const IID& iid, void **ppv); HRESULT __stdcall LockServer(BOOL); BlackConfiguratorFactory(); ~BlackConfiguratorFactory(); protected: ULONG ref_num_; }; __BCONF_END__ #endif
#include "swv.h" #include "stm32f1xx.h" __UNUSED static char buffer[SWO_BUFFER_SIZE] = {'\0'}; __STATIC_INLINE uint32_t ITM_SendChar_C(uint32_t ch, size_t const port) { if (((ITM->TCR & ITM_TCR_ITMENA_Msk) != 0UL) && /* ITM enabled */ ((ITM->TER & (port + 1)) != 0UL)) /* ITM Port enabled */ { while (ITM->PORT[port].u32 == 0UL) { __NOP(); } ITM->PORT[port].u8 = (uint8_t)ch; } return (ch); } uint32_t plotSWO(__UNUSED uint32_t ch, __UNUSED PORT_SWO_t port) { #ifdef DEBUG #ifdef PLOT_SWO #ifndef PRINT_SWO return ITM_SendChar_C(ch, port); #endif #endif #endif return 0; } void printSWO(__UNUSED const char *format, ...) { #ifdef DEBUG #ifdef PRINT_SWO #ifndef PLOT_SWO va_list arg; va_start(arg, format); uint32_t len = vsnprintf((char *)buffer,SWO_BUFFER_SIZE, format, arg); va_end(arg); for (uint32_t i = 0; i < len; i++) { ITM_SendChar_C((char)buffer[i], 0); } #endif #endif #endif }
#if defined(ARDUINO_ARCH_ESP32) || defined(ARDUINO_ARCH_AVR) || defined(ESP_PLATFORM) #include <Arduino.h> #else #include <assert.h> #endif #include <stdint.h> #include "FastAccelStepper.h" #include "common.h" // Here are the global variables to interface with the interrupts #if defined(TEST) #define NUM_QUEUES 2 #define fas_queue_A fas_queue[0] #define fas_queue_B fas_queue[1] #define QUEUE_LEN 16 #elif defined(ARDUINO_ARCH_AVR) #if defined(__AVR_ATmega328P__) #define NUM_QUEUES 2 #define fas_queue_A fas_queue[0] #define fas_queue_B fas_queue[1] #define QUEUE_LEN 16 enum channels { channelA, channelB }; #elif defined(__AVR_ATmega2560__) #define NUM_QUEUES 3 #define fas_queue_A fas_queue[0] #define fas_queue_B fas_queue[1] #define fas_queue_C fas_queue[2] #define QUEUE_LEN 16 enum channels { channelA, channelB, channelC }; #else #error "Unsupported derivate" #endif #elif defined(ARDUINO_ARCH_ESP32) || defined(ESP_PLATFORM) #define NUM_QUEUES 6 #define QUEUE_LEN 32 #else #define NUM_QUEUES 6 #define QUEUE_LEN 32 #endif // These variables control the stepper timing behaviour #define QUEUE_LEN_MASK (QUEUE_LEN - 1) #ifndef TEST #define inject_fill_interrupt(x) #endif #define TICKS_FOR_STOPPED_MOTOR 0xffffffff #if defined(ARDUINO_ARCH_ESP32) || defined(ESP_PLATFORM) #include <driver/gpio.h> #include <driver/mcpwm.h> #include <driver/pcnt.h> #include <soc/mcpwm_reg.h> #include <soc/mcpwm_struct.h> #include <soc/pcnt_reg.h> #include <soc/pcnt_struct.h> struct mapping_s { mcpwm_unit_t mcpwm_unit; uint8_t timer; mcpwm_io_signals_t pwm_output_pin; pcnt_unit_t pcnt_unit; uint8_t input_sig_index; uint32_t cmpr_tea_int_clr; uint32_t cmpr_tea_int_ena; uint32_t cmpr_tea_int_raw; }; bool _esp32_attachToPulseCounter(uint8_t pcnt_unit, FastAccelStepper* stepper, int16_t low_value, int16_t high_value); void _esp32_clearPulseCounter(uint8_t pcnt_unit); int16_t _esp32_readPulseCounter(uint8_t pcnt_unit); #endif struct queue_entry { uint8_t steps; // if 0, then the command only adds a delay uint8_t toggle_dir : 1; uint8_t countUp : 1; uint8_t moreThanOneStep : 1; uint8_t hasSteps : 1; uint16_t ticks; }; class StepperQueue { public: struct queue_entry entry[QUEUE_LEN]; uint8_t read_idx; // ISR stops if readptr == next_writeptr uint8_t next_write_idx; bool dirHighCountsUp; uint8_t dirPin; #if defined(ARDUINO_ARCH_ESP32) || defined(ESP_PLATFORM) volatile uint32_t* _dirPinPort; uint32_t _dirPinMask; volatile bool _hasISRactive; bool _nextCommandIsPrepared; bool isRunning(); const struct mapping_s* mapping; #elif defined(ARDUINO_ARCH_AVR) volatile uint8_t* _dirPinPort; uint8_t _dirPinMask; volatile bool _prepareForStop; volatile bool _isRunning; bool isRunning() { return _isRunning; } enum channels channel; #else volatile bool _isRunning; bool isRunning() { return _isRunning; } #endif #if (TEST_CREATE_QUEUE_CHECKSUM == 1) uint8_t checksum; #endif struct queue_end_s queue_end; void init(uint8_t queue_num, uint8_t step_pin); inline uint8_t queueEntries() { noInterrupts(); uint8_t rp = read_idx; uint8_t wp = next_write_idx; interrupts(); inject_fill_interrupt(0); return (uint8_t)(wp - rp); } inline bool isQueueFull() { return queueEntries() == QUEUE_LEN; } inline bool isQueueEmpty() { return queueEntries() == 0; } int8_t addQueueEntry(const struct stepper_command_s* cmd, bool start) { // Just to check if, if the struct has the correct size // if (sizeof(entry) != 6 * QUEUE_LEN) { // return -1; //} if (cmd == NULL) { if (start) { return startPreparedQueue(); } return AQE_OK; } if (isQueueFull()) { return AQE_QUEUE_FULL; } uint16_t period = cmd->ticks; uint8_t steps = cmd->steps; // Serial.print(period); // Serial.print(" "); // Serial.println(steps); uint32_t command_rate_ticks = period; if (steps > 1) { command_rate_ticks *= steps; } if (command_rate_ticks < MIN_CMD_TICKS) { return AQE_ERROR_TICKS_TOO_LOW; } uint8_t wp = next_write_idx; struct queue_entry* e = &entry[wp & QUEUE_LEN_MASK]; queue_end.pos += cmd->count_up ? steps : -steps; bool dir = (cmd->count_up == dirHighCountsUp); bool toggle_dir = false; if (dirPin != PIN_UNDEFINED) { if (isQueueEmpty()) { // set the dirPin here. Necessary with shared direction pins digitalWrite(dirPin, dir); queue_end.dir = dir; } else { toggle_dir = (dir != queue_end.dir) ? true : false; } } e->steps = steps; e->toggle_dir = toggle_dir; e->countUp = cmd->count_up ? 1 : 0; e->moreThanOneStep = steps > 1 ? 1 : 0; e->hasSteps = steps > 0 ? 1 : 0; e->ticks = period; queue_end.dir = dir; queue_end.count_up = cmd->count_up; #if (TEST_CREATE_QUEUE_CHECKSUM == 1) { // checksum is in the struct and will updated here unsigned char* x = (unsigned char*)e; for (uint8_t i = 0; i < sizeof(struct queue_entry); i++) { if (checksum & 0x80) { checksum <<= 1; checksum ^= 0xde; } else { checksum <<= 1; } checksum ^= *x++; } } #endif commandAddedToQueue(start); return AQE_OK; } int32_t getCurrentPosition() { noInterrupts(); int32_t pos = queue_end.pos; uint8_t wp = next_write_idx; uint8_t rp = read_idx; #if defined(ARDUINO_ARCH_ESP32) || defined(ESP_PLATFORM) // pulse counter should go max up to 255 with perhaps few pulses overrun, so // this conversion is safe int16_t done_p = (int16_t)_getPerformedPulses(); #endif interrupts(); #if defined(ARDUINO_ARCH_ESP32) || defined(ESP_PLATFORM) int16_t adjust = 0; #endif while (rp != wp) { wp--; struct queue_entry* e = &entry[wp & QUEUE_LEN_MASK]; if (e->countUp) { pos -= e->steps; #if defined(ARDUINO_ARCH_ESP32) || defined(ESP_PLATFORM) adjust = e->toggle_dir ? -done_p : done_p; #endif } else { pos += e->steps; #if defined(ARDUINO_ARCH_ESP32) || defined(ESP_PLATFORM) adjust = e->toggle_dir ? done_p : -done_p; #endif } } #if defined(ARDUINO_ARCH_ESP32) || defined(ESP_PLATFORM) pos += adjust; #endif return pos; } uint32_t ticksInQueue() { noInterrupts(); uint8_t rp = read_idx; uint8_t wp = next_write_idx; interrupts(); if (wp == rp) { return 0; } uint32_t ticks = 0; rp++; // ignore currently processed entry while (wp != rp) { struct queue_entry* e = &entry[rp++ & QUEUE_LEN_MASK]; ticks += e->ticks; uint8_t steps = e->steps; if (steps > 1) { uint32_t tmp = e->ticks; tmp *= steps - 1; ticks += tmp; } } return ticks; } bool hasTicksInQueue(uint32_t min_ticks) { noInterrupts(); uint8_t rp = read_idx; uint8_t wp = next_write_idx; interrupts(); if (wp == rp) { return false; } rp++; // ignore currently processed entry while (wp != rp) { struct queue_entry* e = &entry[rp & QUEUE_LEN_MASK]; uint32_t tmp = e->ticks; uint8_t steps = max(e->steps, 1); tmp *= steps; if (tmp >= min_ticks) { return true; } min_ticks -= tmp; rp++; } return false; } uint16_t getActualTicks() { // Retrieve current step rate from the current view. // This is valid only, if the command describes more than one step noInterrupts(); uint8_t rp = read_idx; uint8_t wp = next_write_idx; interrupts(); if (wp == rp) { return 0; } struct queue_entry* e = &entry[rp & QUEUE_LEN_MASK]; if (e->hasSteps) { if (e->moreThanOneStep) { return e->ticks; } if (wp != ++rp) { if (entry[rp & QUEUE_LEN_MASK].hasSteps) { return e->ticks; } } } return 0; } // startQueue is always called void commandAddedToQueue(bool start); int8_t startPreparedQueue(); void forceStop(); void _initVars() { dirPin = PIN_UNDEFINED; read_idx = 0; next_write_idx = 0; queue_end.dir = true; queue_end.count_up = true; queue_end.pos = 0; dirHighCountsUp = true; #if defined(ARDUINO_ARCH_AVR) _isRunning = false; _prepareForStop = false; #elif defined(ARDUINO_ARCH_ESP32) || defined(ESP_PLATFORM) _hasISRactive = false; _nextCommandIsPrepared = false; #else _isRunning = false; #endif #if (TEST_CREATE_QUEUE_CHECKSUM == 1) checksum = 0; #endif } #if defined(ARDUINO_ARCH_ESP32) || defined(ESP_PLATFORM) uint8_t _step_pin; uint16_t _getPerformedPulses(); #endif void connect(); void disconnect(); void setDirPin(uint8_t dir_pin, bool _dirHighCountsUp) { dirPin = dir_pin; dirHighCountsUp = _dirHighCountsUp; #if defined(ARDUINO_ARCH_ESP32) || defined(ARDUINO_ARCH_AVR) if (dir_pin != PIN_UNDEFINED) { _dirPinPort = portOutputRegister(digitalPinToPort(dir_pin)); _dirPinMask = digitalPinToBitMask(dir_pin); } #elif defined(ESP_PLATFORM) if (dir_pin != PIN_UNDEFINED) { _dirPinPort = (volatile uint32_t*) (dir_pin > 31 ? GPIO_OUT1_REG : GPIO_OUT_REG); _dirPinMask = dir_pin > 31 ? (1UL << (dir_pin - 32)) : (1UL << (dir_pin)); } #endif } static bool isValidStepPin(uint8_t step_pin); static int8_t queueNumForStepPin(uint8_t step_pin); }; extern StepperQueue fas_queue[NUM_QUEUES];
/* * Copyright (c) 1986 Regents of the University of California. * All rights reserved. The Berkeley software License Agreement * specifies the terms and conditions for redistribution. * * @(#)kern_fork.c 1.6 (2.11BSD) 1999/8/11 */ #include <sys/cdefs.h> #include <sys/param.h> #include <sys/systm.h> #include <sys/map.h> #include <sys/filedesc.h> #include <sys/kernel.h> #include <sys/malloc.h> #include <sys/proc.h> #include <sys/user.h> #include <sys/resourcevar.h> #include <sys/vnode.h> #include <sys/acct.h> #include <sys/ktrace.h> #include <vm/include/vm_systm.h> /* * fork -- * fork system call */ void fork() { fork1(0); } /* * vfork -- * vfork system call, fast version of fork */ void vfork() { fork1(1); } int nproc = 1; /* process 0 */ static void fork1(isvfork) int isvfork; { register int a; register struct proc *p1, *p2; register uid_t uid; int count; register_t *retval; a = 0; if (u->u_uid != 0) { for (p1 = allproc; p1; p1 = p1->p_nxt) if (p1->p_uid == u->u_uid) a++; for (p1 = zombproc; p1; p1 = p1->p_nxt) if (p1->p_uid == u->u_uid) a++; } /* * Disallow if * No processes at all; * not su and too many procs owned; or * not su and would take last slot. */ p2 = freeproc; uid = p1->p_cred->p_ruid; if (p2 == NULL || (nproc >= maxproc - 1 && uid != 0) || nproc >= maxproc) { tablefull("proc"); u->u_error = EAGAIN; goto out; } count = chgproccnt(u->u_uid, 1); if (u->u_uid != 0 && count > p1->p_rlimit[RLIMIT_NPROC].rlim_cur) { (void)chgproccnt(u->u_uid, -1); u->u_error = EAGAIN; goto out; } if (p2==NULL || (u->u_uid!=0 && (p2->p_nxt == NULL || a > MAXUPRC))) { u->u_error = EAGAIN; goto out; } p1 = u->u_procp; if (newproc(isvfork)) { u->u_r.r_val1 = p1->p_pid; u->u_r.r_val2 = 1; /* child */ u->u_start = p1->p_rtime->tv_sec; /* set forked but preserve suid/gid state */ u->u_acflag = AFORK | (u->u_acflag & ASUGID); bzero(&u->u_ru, sizeof(u->u_ru)); bzero(&u->u_cru, sizeof(u->u_cru)); return; } u->u_r.r_val1 = p2->p_pid; out: u->u_r.r_val2 = 0; } /* * newproc -- * Create a new process -- the internal version of system call fork. * It returns 1 in the new process, 0 in the old. */ int newproc(isvfork) int isvfork; { register struct proc *rip, *rpp; struct proc *newproc; static int mpid, pidchecked = 0; register_t *retval; mpid++; retry: if(mpid >= PID_MAX) { mpid = 100; pidchecked = 0; } if (mpid >= pidchecked) { int doingzomb = 0; pidchecked = PID_MAX; rpp = allproc; again: for (; rpp != NULL; rpp = rpp->p_nxt) { while (rpp->p_pid == mpid || rpp->p_pgrp->pg_id == mpid) { mpid++; if (mpid >= pidchecked) goto retry; } if (rpp->p_pid > mpid && pidchecked > rpp->p_pid) pidchecked = rpp->p_pid; if (rpp->p_pgrp->pg_id > mpid && pidchecked > rpp->p_pgrp->pg_id) pidchecked = rpp->p_pgrp->pg_id; } if (!doingzomb) { doingzomb = 1; rpp = zombproc; goto again; } } if ((rpp = freeproc) == NULL) panic("no procs"); freeproc = rpp->p_nxt; /* off freeproc */ /* * Make a proc table entry for the new process. */ nproc++; rip = u->u_procp; rpp->p_stat = SIDL; rpp->p_pid = mpid; rpp->p_realtimer.it_value = 0; rpp->p_flag = P_SLOAD; rpp->p_uid = rip->p_uid; rpp->p_pgrp = rip->p_pgrp; rpp->p_nice = rip->p_nice; rpp->p_ppid = rip->p_pid; rpp->p_pptr = rip; rpp->p_rtime = 0; rpp->p_cpu = 0; rpp->p_sigmask = rip->p_sigmask; rpp->p_sigcatch = rip->p_sigcatch; rpp->p_sigignore = rip->p_sigignore; /* take along any pending signals like stops? */ if (isvfork) { forkstat.cntvfork++; forkstat.sizvfork += rip->p_dsize + rip->p_ssize; } else { forkstat.cntfork++; forkstat.sizfork += rip->p_dsize + rip->p_ssize; } rpp->p_wchan = 0; rpp->p_slptime = 0; LIST_INSERT_HEAD(PIDHASH(rpp->p_pid), rpp, p_hash); rpp->p_nxt = allproc; /* onto allproc */ rpp->p_nxt->p_prev = &rpp->p_nxt; /* (allproc is never NULL) */ rpp->p_prev = &allproc; allproc = rpp; /* * Make a proc table entry for the new process. * Start by zeroing the section of proc that is zero-initialized, * then copy the section that is copied directly from the parent. */ bzero(&rpp->p_startzero, (unsigned) ((caddr_t)&rpp->p_endzero - (caddr_t)&rpp->p_startzero)); bzero(&rip->p_startzero, (unsigned) ((caddr_t)&rpp->p_endzero - (caddr_t)&rpp->p_startzero)); rpp->p_flag = P_INMEM; MALLOC(rpp->p_cred, struct pcred *, sizeof(struct pcred), M_SUBPROC, M_WAITOK); bcopy(rip->p_cred, rpp->p_cred, sizeof(*rpp->p_cred)); rpp->p_cred->p_refcnt = 1; crhold(rip->p_ucred); /* bump references to the text vnode (for procfs) */ rpp->p_textvp = rip->p_textvp; if(rpp->p_textvp) VREF(rpp->p_textvp); rpp->p_fd = fdcopy(rip); /* * If p_limit is still copy-on-write, bump refcnt, * otherwise get a copy that won't be modified. * (If PL_SHAREMOD is clear, the structure is shared * copy-on-write.) */ if (rip->p_limit->p_lflags & PL_SHAREMOD) rpp->p_limit = limcopy(rip->p_limit); else { rpp->p_limit = rip->p_limit; rpp->p_limit->p_refcnt++; } if (rip->p_session->s_ttyvp != NULL && (rip->p_flag & P_CONTROLT)) rpp->p_flag |= P_CONTROLT; if (isvfork) rpp->p_flag |= P_PPWAIT; rpp->p_pgrpnxt = rip->p_pgrpnxt; rip->p_pgrpnxt = rpp; rpp->p_pptr = rip; rpp->p_osptr = rip->p_cptr; if (rip->p_cptr) rip->p_cptr->p_ysptr = rpp; rip->p_cptr = rpp; rpp->p_dsize = rip->p_dsize; rpp->p_ssize = rip->p_ssize; rpp->p_daddr = rip->p_daddr; rpp->p_saddr = rip->p_saddr; /* * Partially simulate the environment of the new process so that * when it is actually created (by copying) it will look right. */ u->u_procp = rpp; /* * set priority of child to be that of parent */ rpp->p_estcpu = rip->p_estcpu; #ifdef KTRACE if (rip->p_traceflag & KTRFAC_INHERIT) { rpp->p_traceflag = rip->p_traceflag; if ((rpp->p_tracep = rip->p_tracep) != NULL) { VREF(rpp->p_tracep); } } #endif /* * This begins the section where we must prevent the parent * from being swapped. */ rip->p_flag |= P_NOSWAP; /* * Set return values for child before vm_fork, * so they can be copied to child stack. * We return parent pid, and mark as child in retval[1]. * NOTE: the kernel stack may be at a different location in the child * process, and thus addresses of automatic variables (including retval) * may be invalid after vm_fork returns in the child process. */ retval[0] = rip->p_pid; retval[1] = 1; if(vm_fork(rip, rpp, isvfork)) { /* * Child process. Set start time and get to work. */ (void) splclock(); rpp->p_stats->p_start = time; (void) spl0(); rpp->p_acflag = AFORK; return (0); } /* * Make child runnable and add to run queue. */ (void) splhigh(); rpp->p_stat = SRUN; setrq(rpp); (void) spl0(); /* * Now can be swapped. */ rip->p_flag |= P_NOSWAP; /* * Preserve synchronization semantics of vfork. If waiting for * child to exec or exit, set P_PPWAIT on child, and sleep on our * proc (in case of exit). */ if (isvfork) while (rpp->p_flag & P_PPWAIT) tsleep(rip, PWAIT, "ppwait", 0); /* * Return child pid to parent process, * marking us as parent via retval[1]. */ retval[0] = rpp->p_pid; retval[1] = 0; return (0); } /* 2.11BSD Modified Original newproc */ int copyproc(rip, rpp, isvfork) register struct proc *rpp, *rip; int isvfork; { register int n; struct file *fp; int a1, s; size_t a[3]; /* * Increase reference counts on shared objects. */ for (n = 0; n <= u->u_lastfile; n++) { fp = u->u_ofile[n]; if (fp == NULL) continue; fp->f_count++; } rpp->p_dsize = rip->p_dsize; rpp->p_ssize = rip->p_ssize; rpp->p_daddr = rip->p_daddr; rpp->p_saddr = rip->p_saddr; a1 = rip->p_addr; if (isvfork) { a[2] = rmalloc(coremap, USIZE); } else { a[2] = rmalloc3(coremap, rip->p_dsize, rip->p_ssize, USIZE, a); } /* * Partially simulate the environment of the new process so that * when it is actually created (by copying) it will look right. */ u->u_procp = rpp; /* * If there is not enough core for the new process, swap out the * current process to generate the copy. */ if (a[2] == NULL) { rip->p_stat = SIDL; rpp->p_addr = a1; rpp->p_stat = SRUN; swapout(rpp); rip->p_stat = SRUN; u->u_procp = rip; } else { /* * There is core, so just copy. */ rpp->p_addr = a[2]; copy(a1, rpp->p_addr, USIZE); u->u_procp = rip; if (isvfork == 0) { rpp->p_daddr = a[0]; copy(rip->p_daddr, rpp->p_daddr, rpp->p_dsize); rpp->p_saddr = a[1]; copy(rip->p_saddr, rpp->p_saddr, rpp->p_ssize); } s = splhigh(); rpp->p_stat = SRUN; setrq(rpp); splx(s); splhigh(); } rpp->p_flag |= P_SSWAP; if (isvfork) { /* * Set the parent's sizes to 0, since the child now * has the data and stack. * (If we had to swap, just free parent resources.) * Then wait for the child to finish with it. */ rip->p_dsize = 0; rip->p_ssize = 0; rip->p_textvp = NULL; rpp->p_flag |= P_SVFORK; rip->p_flag |= P_SVFPRNT; if (a[2] == NULL) { mfree(coremap, rip->p_dsize, rip->p_daddr); mfree(coremap, rip->p_ssize, rip->p_saddr); } while (rpp->p_flag & P_SVFORK) sleep((caddr_t)rpp, PSWP + 1); if ((rpp->p_flag & P_SLOAD) == 0) panic("newproc vfork"); u->u_dsize = rip->p_dsize = rpp->p_dsize; rip->p_daddr = rpp->p_daddr; rpp->p_dsize = 0; u->u_ssize = rip->p_ssize = rpp->p_ssize; rip->p_saddr = rpp->p_saddr; rpp->p_ssize = 0; rpp->p_flag |= P_SVFDONE; wakeup((caddr_t)rip); rip->p_flag &= ~P_SVFPRNT; } return (0); }
//############################################################################# // // FILENAME: RasterGM.h // // CLASSIFICATION: Unclassified // // DESCRIPTION: // // Header for abstract class that is to provide a common interface from // which CSM raster geometric models will inherit. It is derived from the // GeometricModel class. // // LIMITATIONS: None // // // SOFTWARE HISTORY: // Date Author Comment // ----------- ------ ------- // 27-Jun-2003 LMT Initial version. // 01-Jul-2003 LMT Remove constants, error/warning // and make methods pure virtual. // CharType enum. // 31-Jul-2003 LMT Change calls with a "&" to a "*", // combined CharType with ParamType // to create Param_CharType, //reordered // methods to match API order, added // systematic error methods. // 06-Aug-2003 LMT Removed all Characteristic calls. // 08-Oct 2003 LMT Added getImageSize calls // 06-Feb-2004 KRW Incorporates changes approved by // January and February 2004 // configuration control board. // 30-Jul-2004 PW Initail API 3.1 version // 01-Nov-2004 PW October 2004 CCB // 22 Oct 2010 DSL CCB Change add getCurrentCrossCovarianceMatrix // and getOriginalCrossCovarianceMatrix // 22 Oct 2010 DSL CCB Change add getCurrentCrossCovarianceMatrix // and getOriginalCrossCovarianceMatrix // 25 Oct 2010 DSL CCB Change add getNumGeometricCorrectionSwitches, // getGeometricCorrectionName, // getCurrentGeometricCorrectionSwitch, // and setCurrentGeometricCorrectionSwitch // 25 Oct 2010 DSL CCB Change add getNumGeometricCorrectionSwitches, // getGeometricCorrectionName, // getCurrentGeometricCorrectionSwitch, // and setCurrentGeometricCorrectionSwitch // 02-Mar-2012 SCM Refactored interface. // 02-Jul-2012 SCM Made getUnmodeledError() be implemented inline. // 26-Sep-2012 JPK Split SensorModel class into GeometricModel and // RasterGM classes. RasterGM is now the // equivalent class to the previous SensorModel class. // 26-Sep-2012 SCM Moved all sensor partials to this class. // 30-Oct-2012 SCM Renamed to RasterGM.h // 31-Oct-2012 SCM Moved getTrajectoryIdentifier() to Model. Moved // unmodeled error methods to GeometricModel. Made // compute partial methods const. // 01-Nov-2012 SCM Moved unmodeled error methods back to RasterGM. // 27-Nov-2012 JPK Cleaned up some comments, variable names and // changed return type for getCovarianceModel() from // pointer to const reference. Removed unused // testAPIVersionSubclass(). // 29-Nov-2012 JPK Modified computeAllSensorPartials to return // results for a specified ParamSet. // 06-Dec-2012 JPK Changed ParamSet to param::Set. De-inlined // destructor and getFamily() methods. // Replaced vector<double> with EcefLocus for // imageTo*Locus methods. Added inline method // getCovarianceMatrix(). Provided reference // implementations for computeAllSensorPartials() // methods. Made getCovarianceModel() pure // virtual. // 17-Dec-2012 BAH Documentation updates. // 12-Feb-2013 JPK Renamed CovarianceModel to CorrelationModel. // // NOTES: // //############################################################################# #ifndef __CSM_RASTERGM_H #define __CSM_RASTERGM_H #include "GeometricModel.h" #define CSM_RASTER_FAMILY "Raster" namespace csm { class CorrelationModel; class CSM_EXPORT_API RasterGM : public GeometricModel { public: RasterGM() {} virtual ~RasterGM(); virtual std::string getFamily() const; //> This method returns the Family ID for the current model. //< //--- // Core Photogrammetry //--- virtual ImageCoord groundToImage(const EcefCoord& groundPt, double desiredPrecision = 0.001, double* achievedPrecision = NULL, WarningList* warnings = NULL) const = 0; //> This method converts the given groundPt (x,y,z in ECEF meters) to a // returned image coordinate (line, sample in full image space pixels). // // Iterative algorithms will use desiredPrecision, in meters, as the // convergence criterion, otherwise it will be ignored. // // If a non-NULL achievedPrecision argument is received, it will be // populated with the actual precision, in meters, achieved by iterative // algorithms and 0.0 for deterministic algorithms. // // If a non-NULL warnings argument is received, it will be populated // as applicable. //< virtual ImageCoordCovar groundToImage(const EcefCoordCovar& groundPt, double desiredPrecision = 0.001, double* achievedPrecision = NULL, WarningList* warnings = NULL) const = 0; //> This method converts the given groundPt (x,y,z in ECEF meters and // corresponding 3x3 covariance in ECEF meters squared) to a returned // image coordinate with covariance (line, sample in full image space // pixels and corresponding 2x2 covariance in pixels squared). // // Iterative algorithms will use desiredPrecision, in meters, as the // convergence criterion, otherwise it will be ignored. // // If a non-NULL achievedPrecision argument is received, it will be // populated with the actual precision, in meters, achieved by iterative // algorithms and 0.0 for deterministic algorithms. // // If a non-NULL warnings argument is received, it will be populated // as applicable. //< virtual EcefCoord imageToGround(const ImageCoord& imagePt, double height, double desiredPrecision = 0.001, double* achievedPrecision = NULL, WarningList* warnings = NULL) const = 0; //> This method converts the given imagePt (line,sample in full image // space pixels) and given height (in meters relative to the WGS-84 // ellipsoid) to a returned ground coordinate (x,y,z in ECEF meters). // // Iterative algorithms will use desiredPrecision, in meters, as the // convergence criterion, otherwise it will be ignored. // // If a non-NULL achievedPrecision argument is received, it will be // populated with the actual precision, in meters, achieved by iterative // algorithms and 0.0 for deterministic algorithms. // // If a non-NULL warnings argument is received, it will be populated // as applicable. //< virtual EcefCoordCovar imageToGround(const ImageCoordCovar& imagePt, double height, double heightVariance, double desiredPrecision = 0.001, double* achievedPrecision = NULL, WarningList* warnings = NULL) const = 0; //> This method converts the given imagePt (line, sample in full image // space pixels and corresponding 2x2 covariance in pixels squared) // and given height (in meters relative to the WGS-84 ellipsoid) and // corresponding heightVariance (in meters) to a returned ground // coordinate with covariance (x,y,z in ECEF meters and corresponding // 3x3 covariance in ECEF meters squared). // // Iterative algorithms will use desiredPrecision, in meters, as the // convergence criterion, otherwise it will be ignored. // // If a non-NULL achievedPrecision argument is received, it will be // populated with the actual precision, in meters, achieved by iterative // algorithms and 0.0 for deterministic algorithms. // // If a non-NULL warnings argument is received, it will be populated // as applicable. //< virtual EcefLocus imageToProximateImagingLocus( const ImageCoord& imagePt, const EcefCoord& groundPt, double desiredPrecision = 0.001, double* achievedPrecision = NULL, WarningList* warnings = NULL) const = 0; //> This method, for the given imagePt (line, sample in full image space // pixels), returns the position and direction of the imaging locus // nearest the given groundPt (x,y,z in ECEF meters). // // Note that there are two opposite directions possible. Both are // valid, so either can be returned; the calling application can convert // to the other as necessary. // // Iterative algorithms will use desiredPrecision, in meters, as the // convergence criterion for the locus position, otherwise it will be // ignored. // // If a non-NULL achievedPrecision argument is received, it will be // populated with the actual precision, in meters, achieved by iterative // algorithms and 0.0 for deterministic algorithms. // // If a non-NULL warnings argument is received, it will be populated // as applicable. //< virtual EcefLocus imageToRemoteImagingLocus( const ImageCoord& imagePt, double desiredPrecision = 0.001, double* achievedPrecision = NULL, WarningList* warnings = NULL) const = 0; //> This method, for the given imagePt (line, sample in full image space // pixels), returns the position and direction of the imaging locus // at the sensor. // // Note that there are two opposite directions possible. Both are // valid, so either can be returned; the calling application can convert // to the other as necessary. // // Iterative algorithms will use desiredPrecision, in meters, as the // convergence criterion for the locus position, otherwise it will be // ignored. // // If a non-NULL achievedPrecision argument is received, it will be // populated with the actual precision, in meters, achieved by iterative // algorithms and 0.0 for deterministic algorithms. // // If a non-NULL warnings argument is received, it will be populated // as applicable. // // Notes: // // The remote imaging locus is only well-defined for optical sensors. // It is undefined for SAR sensors and might not be available for // polynomial and other non-physical models. The // imageToProximateImagingLocus method should be used instead where // possible. //< //--- // Monoscopic Mensuration //--- virtual ImageCoord getImageStart() const = 0; //> This method returns the starting coordinate (line, sample in full // image space pixels) for the imaging operation. Typically (0,0). //< virtual ImageVector getImageSize() const = 0; //> This method returns the number of lines and samples in full image // space pixels for the imaging operation. // // Note that the model might not be valid over the entire imaging // operation. Use getValidImageRange() to get the valid range of image // coordinates. //< virtual std::pair<ImageCoord,ImageCoord> getValidImageRange() const = 0; //> This method returns the minimum and maximum image coordinates // (line, sample in full image space pixels), respectively, over which // the current model is valid. The image coordinates define opposite // corners of a rectangle whose sides are parallel to the line and // sample axes. // // The valid image range does not always match the full image // coverage as returned by the getImageStart and getImageSize methods. // // Used in conjunction with the getValidHeightRange method, it is // possible to determine the full range of ground coordinates over which // the model is valid. //< virtual std::pair<double,double> getValidHeightRange() const = 0; //> This method returns the minimum and maximum heights (in meters // relative to WGS-84 ellipsoid), respectively, over which the model is // valid. For example, a model for an airborne platform might not be // designed to return valid coordinates for heights above the aircraft. // // If there are no limits defined for the model, (-99999.0,99999.0) // will be returned. //< virtual EcefVector getIlluminationDirection(const EcefCoord& groundPt) const = 0; //> This method returns a vector defining the direction of // illumination at the given groundPt (x,y,z in ECEF meters). // Note that there are two opposite directions possible. Both are // valid, so either can be returned; the calling application can convert // to the other as necessary. //< //--- // Time and Trajectory //--- virtual double getImageTime(const ImageCoord& imagePt) const = 0; //> This method returns the time in seconds at which the pixel at the // given imagePt (line, sample in full image space pixels) was captured // // The time provided is relative to the reference date and time given // by the Model::getReferenceDateAndTime method. //< virtual EcefCoord getSensorPosition(const ImageCoord& imagePt) const = 0; //> This method returns the position of the physical sensor // (x,y,z in ECEF meters) when the pixel at the given imagePt // (line, sample in full image space pixels) was captured. // // A csm::Error will be thrown if the sensor position is not available. //< virtual EcefCoord getSensorPosition(double time) const = 0; //> This method returns the position of the physical sensor // (x,y,z meters ECEF) at the given time relative to the reference date // and time given by the Model::getReferenceDateAndTime method. //< virtual EcefVector getSensorVelocity(const ImageCoord& imagePt) const = 0; //> This method returns the velocity of the physical sensor // (x,y,z in ECEF meters per second) when the pixel at the given imagePt // (line, sample in full image space pixels) was captured. //< virtual EcefVector getSensorVelocity(double time) const = 0; //> This method returns the velocity of the physical sensor // (x,y,z in ECEF meters per second ) at the given time relative to the // reference date and time given by the Model::getReferenceDateAndTime // method. //< //--- // Uncertainty Propagation //--- typedef std::pair<double,double> SensorPartials; //> This type is used to hold the partial derivatives of line and // sample, respectively, with respect to a model parameter. // The units are pixels per the model parameter units. //< virtual SensorPartials computeSensorPartials( int index, const EcefCoord& groundPt, double desiredPrecision = 0.001, double* achievedPrecision = NULL, WarningList* warnings = NULL) const = 0; //> This is one of two overloaded methods. This method takes only // the necessary inputs. Some efficiency can be obtained by using the // other method. Even more efficiency can be obtained by using the // computeAllSensorPartials method. // // This method returns the partial derivatives of line and sample // (in pixels per the applicable model parameter units), respectively, // with respect to the model parameter given by index at the given // groundPt (x,y,z in ECEF meters). // // Derived model implementations may wish to implement this method by // calling the groundToImage method and passing the resulting image // coordinate to the other computeSensorPartials method. // // If a non-NULL achievedPrecision argument is received, it will be // populated with the highest actual precision, in meters, achieved by // iterative algorithms and 0.0 for deterministic algorithms. // // If a non-NULL achievedPrecision argument is received, it will be // populated with the actual precision, in meters, achieved by iterative // algorithms and 0.0 for deterministic algorithms. // // If a non-NULL warnings argument is received, it will be populated // as applicable. //< virtual SensorPartials computeSensorPartials( int index, const ImageCoord& imagePt, const EcefCoord& groundPt, double desiredPrecision = 0.001, double* achievedPrecision = NULL, WarningList* warnings = NULL) const = 0; //> This is one of two overloaded methods. This method takes // an input image coordinate for efficiency. Even more efficiency can // be obtained by using the computeAllSensorPartials method. // // This method returns the partial derivatives of line and sample // (in pixels per the applicable model parameter units), respectively, // with respect to the model parameter given by index at the given // groundPt (x,y,z in ECEF meters). // // The imagePt, corresponding to the groundPt, is given so that it does // not need to be computed by the method. Results are unpredictable if // the imagePt provided does not correspond to the result of calling the // groundToImage method with the given groundPt. // // Implementations with iterative algorithms (typically ground-to-image // calls) will use desiredPrecision, in meters, as the convergence // criterion, otherwise it will be ignored. // // If a non-NULL achievedPrecision argument is received, it will be // populated with the highest actual precision, in meters, achieved by // iterative algorithms and 0.0 for deterministic algorithms. // // If a non-NULL warnings argument is received, it will be populated // as applicable. //< virtual std::vector<SensorPartials> computeAllSensorPartials( const EcefCoord& groundPt, param::Set pSet = param::VALID, double desiredPrecision = 0.001, double* achievedPrecision = NULL, WarningList* warnings = NULL) const; //> This is one of two overloaded methods. This method takes only // the necessary inputs. Some efficiency can be obtained by using the // other method. // // This method returns the partial derivatives of line and sample // (in pixels per the applicable model parameter units), respectively, // with respect to to each of the desired model parameters at the given // groundPt (x,y,z in ECEF meters). Desired model parameters are // indicated by the given pSet. // // Implementations with iterative algorithms (typically ground-to-image // calls) will use desiredPrecision, in meters, as the convergence // criterion, otherwise it will be ignored. // // If a non-NULL achievedPrecision argument is received, it will be // populated with the highest actual precision, in meters, achieved by // iterative algorithms and 0.0 for deterministic algorithms. // // If a non-NULL warnings argument is received, it will be populated // as applicable. // // The value returned is a vector of pairs with line and sample partials // for one model parameter in each pair. The indices of the // corresponding model parameters can be found by calling the // getParameterSetIndices method for the given pSet. // // Derived models may wish to implement this directly for efficiency, // but an implementation is provided here that calls the // computeSensorPartials method for each desired parameter index. //< virtual std::vector<SensorPartials> computeAllSensorPartials( const ImageCoord& imagePt, const EcefCoord& groundPt, param::Set pSet = param::VALID, double desiredPrecision = 0.001, double* achievedPrecision = NULL, WarningList* warnings = NULL) const; //> This is one of two overloaded methods. This method takes // an input image coordinate for efficiency. // // This method returns the partial derivatives of line and sample // (in pixels per the applicable model parameter units), respectively, // with respect to to each of the desired model parameters at the given // groundPt (x,y,z in ECEF meters). Desired model parameters are // indicated by the given pSet. // // The imagePt, corresponding to the groundPt, is given so that it does // not need to be computed by the method. Results are unpredictable if // the imagePt provided does not correspond to the result of calling the // groundToImage method with the given groundPt. // // Implementations with iterative algorithms (typically ground-to-image // calls) will use desiredPrecision, in meters, as the convergence // criterion, otherwise it will be ignored. // // If a non-NULL achievedPrecision argument is received, it will be // populated with the highest actual precision, in meters, achieved by // iterative algorithms and 0.0 for deterministic algorithms. // // If a non-NULL warnings argument is received, it will be populated // as applicable. // // The value returned is a vector of pairs with line and sample partials // for one model parameter in each pair. The indices of the // corresponding model parameters can be found by calling the // getParameterSetIndices method for the given pSet. // // Derived models may wish to implement this directly for efficiency, // but an implementation is provided here that calls the // computeSensorPartials method for each desired parameter index. //< virtual std::vector<double> computeGroundPartials(const EcefCoord& groundPt) const = 0; //> This method returns the partial derivatives of line and sample // (in pixels per meter) with respect to the given groundPt // (x,y,z in ECEF meters). // // The value returned is a vector with six elements as follows: // //- [0] = line wrt x //- [1] = line wrt y //- [2] = line wrt z //- [3] = sample wrt x //- [4] = sample wrt y //- [5] = sample wrt z //< virtual const CorrelationModel& getCorrelationModel() const = 0; //> This method returns a reference to a CorrelationModel. // The CorrelationModel is used to determine the correlation between // the model parameters of different models of the same type. // These correlations are used to establish the "a priori" cross-covariance // between images. While some applications (such as generation of a // replacement sensor model) may wish to call this method directly, // it is reccommended that the inherited method // GeometricModel::getCrossCovarianceMatrix() be called instead. //< inline std::vector<double> getUnmodeledError(const ImageCoord& imagePt) const { return getUnmodeledCrossCovariance(imagePt, imagePt); } //> This method returns the 2x2 line and sample covariance (in pixels // squared) at the given imagePt for any model error not accounted for // by the model parameters. // // The value returned is a vector of four elements as follows: // //- [0] = line variance //- [1] = line/sample covariance //- [2] = sample/line covariance //- [3] = sample variance //< virtual std::vector<double> getUnmodeledCrossCovariance( const ImageCoord& pt1, const ImageCoord& pt2) const = 0; //> This method returns the 2x2 line and sample cross covariance // (in pixels squared) between the given imagePt1 and imagePt2 for any // model error not accounted for by the model parameters. The error is // reported as the four terms of a 2x2 matrix, returned as a 4 element // vector. //< }; } // namespace csm #endif
<gh_stars>10-100 // SPDX-License-Identifier: GPL-2.0-or-later /* * PowerNV OPAL in-memory console interface * * Copyright 2014 IBM Corp. */ #include <asm/io.h> #include <asm/opal.h> #include <linux/debugfs.h> #include <linux/of.h> #include <linux/types.h> #include <asm/barrier.h> /* OPAL in-memory console. Defined in OPAL source at core/console.c */ struct memcons { __be64 magic; #define MEMCONS_MAGIC 0x6630696567726173L __be64 obuf_phys; __be64 ibuf_phys; __be32 obuf_size; __be32 ibuf_size; __be32 out_pos; #define MEMCONS_OUT_POS_WRAP 0x80000000u #define MEMCONS_OUT_POS_MASK 0x00ffffffu __be32 in_prod; __be32 in_cons; }; static struct memcons *opal_memcons = NULL; ssize_t memcons_copy(struct memcons *mc, char *to, loff_t pos, size_t count) { const char *conbuf; ssize_t ret; size_t first_read = 0; uint32_t out_pos, avail; if (!mc) return -ENODEV; out_pos = be32_to_cpu(READ_ONCE(mc->out_pos)); /* Now we've read out_pos, put a barrier in before reading the new * data it points to in conbuf. */ smp_rmb(); conbuf = phys_to_virt(be64_to_cpu(mc->obuf_phys)); /* When the buffer has wrapped, read from the out_pos marker to the end * of the buffer, and then read the remaining data as in the un-wrapped * case. */ if (out_pos & MEMCONS_OUT_POS_WRAP) { out_pos &= MEMCONS_OUT_POS_MASK; avail = be32_to_cpu(mc->obuf_size) - out_pos; ret = memory_read_from_buffer(to, count, &pos, conbuf + out_pos, avail); if (ret < 0) goto out; first_read = ret; to += first_read; count -= first_read; pos -= avail; if (count <= 0) goto out; } /* Sanity check. The firmware should not do this to us. */ if (out_pos > be32_to_cpu(mc->obuf_size)) { pr_err("OPAL: memory console corruption. Aborting read.\n"); return -EINVAL; } ret = memory_read_from_buffer(to, count, &pos, conbuf, out_pos); if (ret < 0) goto out; ret += first_read; out: return ret; } ssize_t opal_msglog_copy(char *to, loff_t pos, size_t count) { return memcons_copy(opal_memcons, to, pos, count); } static ssize_t opal_msglog_read(struct file *file, struct kobject *kobj, struct bin_attribute *bin_attr, char *to, loff_t pos, size_t count) { return opal_msglog_copy(to, pos, count); } static struct bin_attribute opal_msglog_attr = { .attr = {.name = "msglog", .mode = 0400}, .read = opal_msglog_read }; struct memcons *memcons_init(struct device_node *node, const char *mc_prop_name) { u64 mcaddr; struct memcons *mc; if (of_property_read_u64(node, mc_prop_name, &mcaddr)) { pr_warn("%s property not found, no message log\n", mc_prop_name); goto out_err; } mc = phys_to_virt(mcaddr); if (!mc) { pr_warn("memory console address is invalid\n"); goto out_err; } if (be64_to_cpu(mc->magic) != MEMCONS_MAGIC) { pr_warn("memory console version is invalid\n"); goto out_err; } return mc; out_err: return NULL; } u32 memcons_get_size(struct memcons *mc) { return be32_to_cpu(mc->ibuf_size) + be32_to_cpu(mc->obuf_size); } void __init opal_msglog_init(void) { opal_memcons = memcons_init(opal_node, "ibm,opal-memcons"); if (!opal_memcons) { pr_warn("OPAL: memcons failed to load from ibm,opal-memcons\n"); return; } opal_msglog_attr.size = memcons_get_size(opal_memcons); } void __init opal_msglog_sysfs_init(void) { if (!opal_memcons) { pr_warn("OPAL: message log initialisation failed, not creating sysfs entry\n"); return; } if (sysfs_create_bin_file(opal_kobj, &opal_msglog_attr) != 0) pr_warn("OPAL: sysfs file creation failed\n"); }
<reponame>alphaKAI/hvm #ifndef __UTIL_HEADER_INCLUDED__ #define __UTIL_HEADER_INCLUDED__ #include "sds/sds.h" #include <limits.h> typedef void (*ELEM_DESTRUCTOR)(void *); typedef int (*ELEM_COMPARE)(void *, void *); typedef char *(*ELEM_PRINTER)(void *); void *xmalloc(size_t); void xfree(void *); void *xrealloc(void *ptr, size_t size); double parseDouble(sds); #define xnew(T) (xmalloc(sizeof(T))) #define xnewN(T, N) (xmalloc(sizeof(T) * N)) #define INT_TO_VoPTR(i) ((void *)(intptr_t)i) #define VoPTR_TO_INT(ptr) ((int)(intptr_t)ptr) #define GenParseNumberProtWithName(T, Name) T parse_##Name(sds str); #define GenParseNumberProt(T) GenParseNumberProtWithName(T, T) GenParseNumberProt(int); GenParseNumberProt(size_t); #include "hvm.h" sds vecstrjoin(Vector *strs, sds sep); size_t checked_size_sub(size_t a, size_t b); size_t checked_size_add(size_t a, size_t b); typedef struct { void *data; size_t size; } SizedData; sds readText(const sds file_name); #define GenNumericToLowers(T, R, T_NAME, R_NAME, R_MAX) \ static inline R *T_NAME##_to_##R_NAME##s(T v) { \ size_t T_size = sizeof(T); \ size_t R_size = sizeof(R); \ size_t rets_length = T_size / R_size; \ R *rets = xmalloc(sizeof(R) * rets_length); \ \ for (size_t i = 0; i < rets_length; i++) { \ R t = (v >> (R_size * 8 * i)) & R_MAX; \ rets[i] = t; \ } \ \ return rets; \ } #define GenLowersToNumeric(T, R, T_NAME, R_NAME) \ static inline R T_NAME##s_to_##R_NAME(T *inputs) { \ R v = 0; \ size_t T_size = sizeof(T); \ size_t R_size = sizeof(R); \ size_t iter_end = R_size / T_size; \ \ for (size_t i = 0; i < iter_end; i++) { \ v |= ((R)inputs[i]) << (T_size * 8 * i); \ } \ \ return v; \ } // int <-> unsigned char GenNumericToLowers(int, unsigned char, int, uchar, UCHAR_MAX); GenLowersToNumeric(unsigned char, int, uchar, int); // unsigned iong long int <-> unsigned char GenNumericToLowers(unsigned long long int, unsigned char, ulli, uchar, UCHAR_MAX); GenLowersToNumeric(unsigned char, unsigned long long int, uchar, ulli); #define PNULL_CHECK(ptr, msg) \ if (ptr == NULL) { \ fprintf(stderr, "[%d] %s\n", __LINE__, msg); \ exit(EXIT_FAILURE); \ } #define PNULL_CHECK_DEFAULT(ptr) \ PNULL_CHECK(ptr, "given a null pointer - " #ptr); #define container_of(ptr, type, member) \ ({ \ const typeof(((type *)0)->member) *__mptr = (ptr); \ (type *)((char *)__mptr - offsetof(type, member)); \ }) #include <assert.h> #include <stdio.h> static inline void unimplemented_msg(char *file_path, int line, char *msg) { if (msg == NULL) { fprintf(stderr, "unimplemented! [File: %s, Line: %d]\n", file_path, line); } else { fprintf(stderr, "unimplemented! [File: %s, Line: %d] msg : %s\n", file_path, line, msg); } assert(0); } #define unimplemented() unimplemented_msg(__FILE__, __LINE__, NULL) void write_llis_to_file(const char *file_name, Vector *vec); Vector *read_file_from_llis(const char *file_name); #define THROW_SEGV \ do { \ int *i = 1; \ --i; \ *i = 0; \ } while (0) #endif
<filename>node_modules/openvg-canvas/src/v8_helpers.h #ifndef V8_HELPERS_H_ #define V8_HELPERS_H_ // SCOPE_DECL_* defined in bindings.gyp #ifdef SCOPE_DECL_PRE_0_11 #define ISOLATE_DECL(isolate) #define ISOLATE(isolate) #define ISOLATE_INIT(isolate) #define SCOPE(isolate) HandleScope scope #else #define ISOLATE_DECL(isolate) extern v8::Isolate* isolate; #define ISOLATE(isolate) v8::Isolate* isolate; #define ISOLATE_INIT(isolate) isolate = Isolate::GetCurrent(); #define SCOPE(isolate) HandleScope scope(isolate) #endif // V8_CALLBACK_STYLE_* defined in bindings.gyp #ifdef V8_CALLBACK_STYLE_PRE_3_20 #define V8_METHOD(method) v8::Handle<v8::Value> method(const v8::Arguments& args) #define V8_PERSISTENT(value) value->handle_ #define V8_RETURN(result) return result #define V8_RETURN_UNDEFINED return Undefined() #define HANDLE handle_ #define SET_TEMPLATE(template, isolate, constructor) template = Persistent<FunctionTemplate>::New(constructor) #define NEW_INSTANCE(isolate, template) template->GetFunction()->NewInstance() #else #define V8_METHOD(method) void method(const v8::FunctionCallbackInfo<v8::Value>& args) #define V8_PERSISTENT(value) value->persistent() #define V8_RETURN(result) do { args.GetReturnValue().Set(result);return; } while(0) #define V8_RETURN_UNDEFINED return #define HANDLE handle() #define SET_TEMPLATE(template, isolate, constructor) template.Reset(isolate, constructor) #define NEW_INSTANCE(isolate, template) Local<FunctionTemplate>::New(isolate, template)->GetFunction()->NewInstance(); #endif #define V8_METHOD_DECL(method) static V8_METHOD(method) #define V8_FUNCTION_DECL(function) V8_METHOD(function) #define V8_FUNCTION(function) static V8_METHOD(function) #define V8_THROW(exception) V8_RETURN(ThrowException(exception)) // TYPED_ARRAY_TYPE_* defined in bindings.gyp #ifdef TYPED_ARRAY_TYPE_PRE_0_11 template<class C> class TypedArrayWrapper { private: v8::Local<v8::Object> array; v8::Handle<v8::Object> buffer; int byteOffset; public: inline __attribute__((always_inline)) TypedArrayWrapper(const v8::Local<v8::Value>& arg) : array(arg->ToObject()), buffer(array->Get(v8::String::New("buffer"))->ToObject()), byteOffset(array->Get(v8::String::New("byteOffset"))->Int32Value()) { } inline __attribute__((always_inline)) C* pointer(int offset = 0) { return (C*) &((char*) buffer->GetIndexedPropertiesExternalArrayData())[byteOffset + offset]; } inline __attribute__((always_inline)) int length() { return array->Get(v8::String::New("length"))->Uint32Value(); } }; #else template<class C> class TypedArrayWrapper { private: v8::Local<v8::TypedArray> array; public: inline __attribute__((always_inline)) TypedArrayWrapper(const v8::Local<v8::Value>& arg) : array(v8::Handle<v8::TypedArray>::Cast(arg->ToObject())) { } inline __attribute__((always_inline)) C* pointer(int offset = 0) { return (C*) &((char*) array->BaseAddress())[offset]; } inline __attribute__((always_inline)) int length() { return array->Length(); } }; #endif #endif
<filename>output/codeview.c /* ----------------------------------------------------------------------- * * * Copyright 1996-2016 The NASM Authors - All Rights Reserved * See the file AUTHORS included with the NASM distribution for * the specific copyright holders. * * 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 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. * * ----------------------------------------------------------------------- */ /* * codeview.c Codeview Debug Format support for COFF */ #include "version.h" #include "compiler.h" #include <stdio.h> #include <stddef.h> #include <stdlib.h> #include "nasm.h" #include "nasmlib.h" #include "saa.h" #include "output/outlib.h" #include "output/pecoff.h" #include "md5.h" static void cv8_init(void); static void cv8_linenum(const char *filename, int32_t linenumber, int32_t segto); static void cv8_deflabel(char *name, int32_t segment, int64_t offset, int is_global, char *special); static void cv8_typevalue(int32_t type); static void cv8_output(int type, void *param); static void cv8_cleanup(void); const struct dfmt df_cv8 = { "Codeview 8", /* .fullname */ "cv8", /* .shortname */ cv8_init, /* .init */ cv8_linenum, /* .linenum */ cv8_deflabel, /* .debug_deflabel */ null_debug_directive, /* .debug_directive */ cv8_typevalue, /* .debug_typevalue */ cv8_output, /* .debug_output */ cv8_cleanup, /* .cleanup */ }; /******************************************************************************* * dfmt callbacks ******************************************************************************/ struct source_file { char *name; unsigned char md5sum[MD5_HASHBYTES]; }; struct linepair { uint32_t file_offset; uint32_t linenumber; }; enum symbol_type { SYMTYPE_CODE, SYMTYPE_PROC, SYMTYPE_LDATA, SYMTYPE_GDATA, SYMTYPE_MAX }; struct cv8_symbol { enum symbol_type type; char *name; uint32_t secrel; uint16_t section; uint32_t size; uint32_t typeindex; enum symtype { TYPE_UNREGISTERED = 0x0000, /* T_NOTYPE */ TYPE_BYTE = 0x0020, TYPE_WORD = 0x0021, TYPE_DWORD= 0x0022, TYPE_QUAD = 0x0023, TYPE_REAL32 = 0x0040, TYPE_REAL64 = 0x0041, TYPE_REAL80 = 0x0042, TYPE_REAL128= 0x0043, TYPE_REAL256= 0x0044, TYPE_REAL512= 0x0045 } symtype; }; struct cv8_state { int symbol_sect; int type_sect; uint32_t text_offset; struct source_file source_file; struct SAA *lines; uint32_t num_lines; struct SAA *symbols; struct cv8_symbol *last_sym; unsigned num_syms[SYMTYPE_MAX]; unsigned symbol_lengths; unsigned total_syms; char *cwd; }; struct cv8_state cv8_state; static void cv8_init(void) { const uint32_t sect_flags = IMAGE_SCN_MEM_READ | IMAGE_SCN_MEM_DISCARDABLE | IMAGE_SCN_CNT_INITIALIZED_DATA | IMAGE_SCN_ALIGN_1BYTES; cv8_state.symbol_sect = coff_make_section(".debug$S", sect_flags); cv8_state.type_sect = coff_make_section(".debug$T", sect_flags); cv8_state.text_offset = 0; cv8_state.lines = saa_init(sizeof(struct linepair)); cv8_state.num_lines = 0; cv8_state.symbols = saa_init(sizeof(struct cv8_symbol)); cv8_state.last_sym = NULL; cv8_state.cwd = nasm_realpath("."); } static void register_file(const char *filename); static struct coff_Section *find_section(int32_t segto); static void cv8_linenum(const char *filename, int32_t linenumber, int32_t segto) { struct coff_Section *s; struct linepair *li; if (cv8_state.source_file.name == NULL) register_file(filename); s = find_section(segto); if (s == NULL) return; if ((s->flags & IMAGE_SCN_MEM_EXECUTE) == 0) return; li = saa_wstruct(cv8_state.lines); li->file_offset = cv8_state.text_offset; li->linenumber = linenumber; cv8_state.num_lines++; } static void cv8_deflabel(char *name, int32_t segment, int64_t offset, int is_global, char *special) { struct cv8_symbol *sym; struct coff_Section *s; (void)special; s = find_section(segment); if (s == NULL) return; sym = saa_wstruct(cv8_state.symbols); if (s->flags & IMAGE_SCN_MEM_EXECUTE) sym->type = is_global ? SYMTYPE_PROC : SYMTYPE_CODE; else sym->type = is_global ? SYMTYPE_GDATA : SYMTYPE_LDATA; cv8_state.num_syms[sym->type]++; cv8_state.total_syms++; sym->section = segment; sym->secrel = offset; sym->symtype = TYPE_UNREGISTERED; sym->size = 0; sym->typeindex = 0; sym->name = nasm_strdup(name); cv8_state.symbol_lengths += strlen(sym->name) + 1; if (cv8_state.last_sym && cv8_state.last_sym->section == segment) cv8_state.last_sym->size = offset - cv8_state.last_sym->secrel; cv8_state.last_sym = sym; } static void cv8_typevalue(int32_t type) { if (!cv8_state.last_sym) return; if (cv8_state.last_sym->symtype != TYPE_UNREGISTERED) return; switch (TYM_TYPE(type)) { case TY_BYTE: cv8_state.last_sym->symtype = TYPE_BYTE; break; case TY_WORD: cv8_state.last_sym->symtype = TYPE_WORD; break; case TY_DWORD: cv8_state.last_sym->symtype = TYPE_DWORD; break; case TY_QWORD: cv8_state.last_sym->symtype = TYPE_QUAD; break; case TY_FLOAT: cv8_state.last_sym->symtype = TYPE_REAL32; break; case TY_TBYTE: cv8_state.last_sym->symtype = TYPE_REAL80; break; case TY_OWORD: cv8_state.last_sym->symtype = TYPE_REAL128; break; case TY_YWORD: cv8_state.last_sym->symtype = TYPE_REAL256; break; case TY_UNKNOWN: break; case TY_LABEL: break; } } static void cv8_output(int type, void *param) { struct coff_DebugInfo *dinfo = param; (void)type; if (dinfo->section && dinfo->section->name && !strncmp(dinfo->section->name, ".text", 5)) cv8_state.text_offset += dinfo->size; } static void build_symbol_table(struct coff_Section *const sect); static void build_type_table(struct coff_Section *const sect); static void cv8_cleanup(void) { struct cv8_symbol *sym; struct coff_Section *symbol_sect = coff_sects[cv8_state.symbol_sect]; struct coff_Section *type_sect = coff_sects[cv8_state.type_sect]; build_symbol_table(symbol_sect); build_type_table(type_sect); if (cv8_state.source_file.name != NULL) free(cv8_state.source_file.name); if (cv8_state.cwd != NULL) free(cv8_state.cwd); saa_free(cv8_state.lines); saa_rewind(cv8_state.symbols); while ((sym = saa_rstruct(cv8_state.symbols))) free(sym->name); saa_free(cv8_state.symbols); } /******************************************************************************* * implementation ******************************************************************************/ static void calc_md5(const char *const filename, unsigned char sum[MD5_HASHBYTES]) { int success = 0; unsigned char *file_buf; FILE *f; MD5_CTX ctx; f = fopen(filename, "r"); if (!f) goto done; file_buf = nasm_zalloc(BUFSIZ); MD5Init(&ctx); while (!feof(f)) { size_t i = fread(file_buf, 1, BUFSIZ, f); if (ferror(f)) goto done_0; else if (i == 0) break; MD5Update(&ctx, file_buf, i); } MD5Final(sum, &ctx); success = 1; done_0: nasm_free(file_buf); fclose(f); done: if (!success) { nasm_error(ERR_NONFATAL, "unable to hash file %s. " "Debug information may be unavailable.\n", filename); } return; } static void register_file(const char *filename) { cv8_state.source_file.name = nasm_realpath(filename); memset(cv8_state.source_file.md5sum, 0, MD5_HASHBYTES); calc_md5(filename, cv8_state.source_file.md5sum); } static struct coff_Section *find_section(int32_t segto) { int i; for (i = 0; i < coff_nsects; i++) { struct coff_Section *sec; sec = coff_sects[i]; if (segto == sec->index) return sec; } return NULL; } static void register_reloc(struct coff_Section *const sect, char *sym, uint32_t addr, uint16_t type) { struct coff_Reloc *r; struct coff_Section *sec; r = *sect->tail = nasm_malloc(sizeof(struct coff_Reloc)); sect->tail = &r->next; r->next = NULL; sect->nrelocs++; r->address = addr; r->symbase = SECT_SYMBOLS; r->type = type; r->symbol = 0; for (int i = 0; i < coff_nsects; i++) { sec = coff_sects[i]; if (!strcmp(sym, sec->name)) { return; } r->symbol += 2; } saa_rewind(coff_syms); for (uint32_t i = 0; i < coff_nsyms; i++) { struct coff_Symbol *s = saa_rstruct(coff_syms); r->symbol++; if (s->strpos == -1 && !strcmp(sym, s->name)) { return; } else if (s->strpos != -1) { int res; char *symname; symname = nasm_malloc(s->namlen + 1); saa_fread(coff_strs, s->strpos-4, symname, s->namlen); symname[s->namlen] = '\0'; res = strcmp(sym, symname); nasm_free(symname); if (!res) return; } } nasm_panic(0, "codeview: relocation for unregistered symbol: %s", sym); } static inline void section_write32(struct coff_Section *sect, uint32_t val) { saa_write32(sect->data, val); sect->len += 4; } static inline void section_write16(struct coff_Section *sect, uint16_t val) { saa_write16(sect->data, val); sect->len += 2; } static inline void section_write8(struct coff_Section *sect, uint8_t val) { saa_write8(sect->data, val); sect->len++; } static inline void section_wbytes(struct coff_Section *sect, const void *buf, size_t len) { saa_wbytes(sect->data, buf, len); sect->len += len; } static void write_filename_table(struct coff_Section *const sect) { uint32_t field_length = 0; size_t filename_len = strlen(cv8_state.source_file.name); field_length = 1 + filename_len + 1; section_write32(sect, 0x000000F3); section_write32(sect, field_length); section_write8(sect, 0); section_wbytes(sect, cv8_state.source_file.name, filename_len + 1); } static void write_sourcefile_table(struct coff_Section *const sect) { uint32_t field_length = 0; field_length = 4 + 2 + MD5_HASHBYTES + 2; section_write32(sect, 0x000000F4); section_write32(sect, field_length); section_write32(sect, 1); /* offset of filename in filename str table */ section_write16(sect, 0x0110); section_wbytes(sect, cv8_state.source_file.md5sum, MD5_HASHBYTES); section_write16(sect, 0); } static void write_linenumber_table(struct coff_Section *const sect) { int i; uint32_t field_length = 0; size_t field_base; struct coff_Section *s; struct linepair *li; for (i = 0; i < coff_nsects; i++) { if (!strncmp(coff_sects[i]->name, ".text", 5)) break; } if (i == coff_nsects) return; s = coff_sects[i]; field_length = 12 + 12 + (cv8_state.num_lines * 8); section_write32(sect, 0x000000F2); section_write32(sect, field_length); field_base = sect->len; section_write32(sect, 0); /* SECREL, updated by relocation */ section_write16(sect, 0); /* SECTION, updated by relocation*/ section_write16(sect, 0); /* pad */ section_write32(sect, s->len); register_reloc(sect, ".text", field_base, win64 ? IMAGE_REL_AMD64_SECREL : IMAGE_REL_I386_SECREL); register_reloc(sect, ".text", field_base + 4, win64 ? IMAGE_REL_AMD64_SECTION : IMAGE_REL_I386_SECTION); /* 1 or more source mappings (we assume only 1) */ section_write32(sect, 0); section_write32(sect, cv8_state.num_lines); section_write32(sect, 12 + (cv8_state.num_lines * 8)); /* the pairs */ saa_rewind(cv8_state.lines); while ((li = saa_rstruct(cv8_state.lines))) { section_write32(sect, li->file_offset); section_write32(sect, li->linenumber |= 0x80000000); } } static uint16_t write_symbolinfo_obj(struct coff_Section *sect, const char sep) { uint16_t obj_len; obj_len = 2 + 4 + strlen(cv8_state.cwd)+ 1 + strlen(coff_outfile) +1; section_write16(sect, obj_len); section_write16(sect, 0x1101); section_write32(sect, 0); /* ASM language */ section_wbytes(sect, cv8_state.cwd, strlen(cv8_state.cwd)); section_write8(sect, sep); section_wbytes(sect, coff_outfile, strlen(coff_outfile)+1); return obj_len; } static uint16_t write_symbolinfo_properties(struct coff_Section *sect, const char *const creator_str) { uint16_t creator_len; creator_len = 2 + 4 + 4 + 4 + 4 + strlen(creator_str)+1 + 2; section_write16(sect, creator_len); section_write16(sect, 0x1116); section_write32(sect, 3); /* language */ if (win64) section_write32(sect, 0x000000D0); else if (win32) section_write32(sect, 0x00000006); else nasm_assert(!"neither win32 nor win64 are set!"); section_write32(sect, 0); /* flags*/ section_write32(sect, 8); /* version */ section_wbytes(sect, creator_str, strlen(creator_str)+1); /* * normally there would be key/value pairs here, but they aren't * necessary. They are terminated by 2B */ section_write16(sect, 0); return creator_len; } static uint16_t write_symbolinfo_symbols(struct coff_Section *sect) { uint16_t len = 0, field_len; uint32_t field_base; struct cv8_symbol *sym; saa_rewind(cv8_state.symbols); while ((sym = saa_rstruct(cv8_state.symbols))) { switch (sym->type) { case SYMTYPE_LDATA: case SYMTYPE_GDATA: field_len = 12 + strlen(sym->name) + 1; len += field_len - 2; section_write16(sect, field_len); if (sym->type == SYMTYPE_LDATA) section_write16(sect, 0x110C); else section_write16(sect, 0x110D); section_write32(sect, sym->symtype); field_base = sect->len; section_write32(sect, 0); /* SECREL */ section_write16(sect, 0); /* SECTION */ break; case SYMTYPE_PROC: case SYMTYPE_CODE: field_len = 9 + strlen(sym->name) + 1; len += field_len - 2; section_write16(sect, field_len); section_write16(sect, 0x1105); field_base = sect->len; section_write32(sect, 0); /* SECREL */ section_write16(sect, 0); /* SECTION */ section_write8(sect, 0); /* FLAG */ break; default: nasm_assert(!"unknown symbol type"); } section_wbytes(sect, sym->name, strlen(sym->name) + 1); register_reloc(sect, sym->name, field_base, win64 ? IMAGE_REL_AMD64_SECREL : IMAGE_REL_I386_SECREL); register_reloc(sect, sym->name, field_base + 4, win64 ? IMAGE_REL_AMD64_SECTION : IMAGE_REL_I386_SECTION); } return len; } static void write_symbolinfo_table(struct coff_Section *const sect) { const char sep = '\\'; const char *creator_str = "The Netwide Assembler " NASM_VER; uint16_t obj_length, creator_length, sym_length; uint32_t field_length = 0, out_len; /* signature, language, workingdir / coff_outfile NULL */ obj_length = 2 + 4 + strlen(cv8_state.cwd)+ 1 + strlen(coff_outfile) +1; creator_length = 2 + 4 + 4 + 4 + 4 + strlen(creator_str)+1 + 2; sym_length = ( cv8_state.num_syms[SYMTYPE_CODE] * 7) + ( cv8_state.num_syms[SYMTYPE_PROC] * 7) + ( cv8_state.num_syms[SYMTYPE_LDATA] * 10) + ( cv8_state.num_syms[SYMTYPE_GDATA] * 10) + cv8_state.symbol_lengths; field_length = 2 + obj_length + 2 + creator_length + (4 * cv8_state.total_syms) + sym_length; section_write32(sect, 0x000000F1); section_write32(sect, field_length); /* for sub fields, length preceeds type */ out_len = write_symbolinfo_obj(sect, sep); nasm_assert(out_len == obj_length); out_len = write_symbolinfo_properties(sect, creator_str); nasm_assert(out_len == creator_length); out_len = write_symbolinfo_symbols(sect); nasm_assert(out_len == sym_length); } static inline void align4_table(struct coff_Section *const sect) { unsigned diff; uint32_t zero = 0; struct SAA *data = sect->data; if (data->wptr % 4 == 0) return; diff = 4 - (data->wptr % 4); if (diff) section_wbytes(sect, &zero, diff); } static void build_symbol_table(struct coff_Section *const sect) { section_write32(sect, 0x00000004); write_filename_table(sect); align4_table(sect); write_sourcefile_table(sect); align4_table(sect); write_linenumber_table(sect); align4_table(sect); write_symbolinfo_table(sect); align4_table(sect); } static void build_type_table(struct coff_Section *const sect) { uint16_t field_len; struct cv8_symbol *sym; section_write32(sect, 0x00000004); saa_rewind(cv8_state.symbols); while ((sym = saa_rstruct(cv8_state.symbols))) { if (sym->type != SYMTYPE_PROC) continue; /* proc leaf */ field_len = 2 + 4 + 4 + 4 + 2; section_write16(sect, field_len); section_write16(sect, 0x1008); /* PROC type */ section_write32(sect, 0x00000003); /* return type */ section_write32(sect, 0); /* calling convention (default) */ section_write32(sect, sym->typeindex); section_write16(sect, 0); /* # params */ /* arglist */ field_len = 2 + 4; section_write16(sect, field_len); section_write16(sect, 0x1201); /* ARGLIST */ section_write32(sect, 0); /*num params */ } }
<reponame>reels-research/iOS-Private-Frameworks<filename>HealthUI.framework/HKAxisLabelDimensionMinuteSecond.h /* Generated by RuntimeBrowser Image: /System/Library/PrivateFrameworks/HealthUI.framework/HealthUI */ @interface HKAxisLabelDimensionMinuteSecond : HKAxisLabelDimensionScalar { NSDateFormatter * _dateFormatter; NSDate * _startDate; } @property (nonatomic, retain) NSDateFormatter *dateFormatter; @property (nonatomic, retain) NSDate *startDate; - (void).cxx_destruct; - (id)dateFormatter; - (id)initWithStartDate:(id)arg1; - (void)setDateFormatter:(id)arg1; - (void)setStartDate:(id)arg1; - (id)startDate; - (id)stringForLocation:(id)arg1; @end
<filename>src/bwamem.c #include <stdlib.h> #include <string.h> #include <stdio.h> #include <assert.h> #include <limits.h> #include <math.h> #ifdef HAVE_PTHREAD #include <pthread.h> #endif #include "kstring.h" #include "bwamem.h" #include "bntseq.h" #include "ksw.h" #include "kvec.h" #include "ksort.h" #include "utils.h" #include "vector_filter.h" #ifdef USE_MALLOC_WRAPPERS # include "malloc_wrap.h" #endif /* Theory on probability and scoring *ungapped* alignment * * s'(a,b) = log[P(b|a)/P(b)] = log[4P(b|a)], assuming uniform base distribution * s'(a,a) = log(4), s'(a,b) = log(4e/3), where e is the error rate * * Scale s'(a,b) to s(a,a) s.t. s(a,a)=x. Then s(a,b) = x*s'(a,b)/log(4), or conversely: s'(a,b)=s(a,b)*log(4)/x * * If the matching score is x and mismatch penalty is -y, we can compute error rate e: * e = .75 * exp[-log(4) * y/x] * * log P(seq) = \sum_i log P(b_i|a_i) = \sum_i {s'(a,b) - log(4)} * = \sum_i { s(a,b)*log(4)/x - log(4) } = log(4) * (S/x - l) * * where S=\sum_i s(a,b) is the alignment score. Converting to the phred scale: * Q(seq) = -10/log(10) * log P(seq) = 10*log(4)/log(10) * (l - S/x) = 6.02 * (l - S/x) * * * Gap open (zero gap): q' = log[P(gap-open)], r' = log[P(gap-ext)] (see Durbin et al. (1998) Section 4.1) * Then q = x*log[P(gap-open)]/log(4), r = x*log[P(gap-ext)]/log(4) * * When there are gaps, l should be the length of alignment matches (i.e. the M operator in CIGAR) */ static const bntseq_t *global_bns = 0; // for debugging only mem_opt_t *mem_opt_init() { mem_opt_t *o; o = calloc(1, sizeof(mem_opt_t)); o->flag = 0; o->a = 1; o->b = 4; o->o_del = o->o_ins = 6; o->e_del = o->e_ins = 1; o->w = 100; o->T = 30; o->zdrop = 100; //o->zdrop = 0; o->pen_unpaired = 17; o->pen_clip5 = o->pen_clip3 = 5; o->max_mem_intv = 20; o->min_seed_len = 19; o->split_width = 10; o->max_occ = 500; o->max_chain_gap = 10000; o->max_ins = 10000; o->mask_level = 0.50; o->drop_ratio = 0.50; o->XA_drop_ratio = 0.80; o->split_factor = 1.5; o->chunk_size = 10000000; o->n_threads = 1; o->max_XA_hits = 5; o->max_XA_hits_alt = 200; o->max_matesw = 50; o->mask_level_redun = 0.95; o->min_chain_weight = 0; o->max_chain_extend = 1 << 30; o->mapQ_coef_len = 50; o->mapQ_coef_fac = log(o->mapQ_coef_len); o->seed_type = 1; o->seed_intv = o->min_seed_len; o->dp_type = 0; o->opt_ext = 0; o->re_seed = 0; o->use_avx2 = 0; o->read_len = 0; o->shd_filter = 0; bwa_fill_scmat(o->a, o->b, o->mat); return o; } /*************************** * Collection SA invervals * ***************************/ #define intv_lt(a, b) ((a).info < (b).info) KSORT_INIT(mem_intv, bwtintv_t, intv_lt) typedef struct { bwtintv_v mem, mem1, *tmpv[2]; } smem_aux_t; static smem_aux_t *smem_aux_init() { smem_aux_t *a; a = calloc(1, sizeof(smem_aux_t)); a->tmpv[0] = calloc(1, sizeof(bwtintv_v)); a->tmpv[1] = calloc(1, sizeof(bwtintv_v)); return a; } static void smem_aux_destroy(smem_aux_t *a) { free(a->tmpv[0]->a); free(a->tmpv[0]); free(a->tmpv[1]->a); free(a->tmpv[1]); free(a->mem.a); free(a->mem1.a); free(a); } typedef struct { bwtint_t w; int bid; } bwt_mem_width_t; int bwt_mem_cal_width(const bwt_t *bwt, int len, const uint8_t *str, bwt_mem_width_t *width) { bwtint_t k, l, ok, ol; int i, bid; bid = 0; k = 0; l = bwt->seq_len; for (i = 0; i < len; ++i) { uint8_t c = str[i]; if (c < 4) { bwt_2occ(bwt, k - 1, l, c, &ok, &ol); k = bwt->L2[c] + ok + 1; l = bwt->L2[c] + ol; } if (k > l || c > 3) { // then restart k = 0; l = bwt->seq_len; ++bid; i--; } width[i].w = l - k + 1; width[i].bid = bid; } //width[len].w = 0; //width[len].bid = ++bid; return bid; } typedef struct { bwtint_t w; int bid; } bwt_width_t; static void mem_collect_intv(mem_opt_t *opt, const bwt_t *bwt, int len, const uint8_t *seq, smem_aux_t *a) { int i, k, x = 0, old_n, max, max_i; int start_width = 1; int split_len = (int) (opt->min_seed_len * opt->split_factor + .499); int min_miss_match = 0; bwt_mem_width_t *w; /*if (opt->seed_type == 4) { w = calloc(len, sizeof(bwt_mem_width_t)); min_miss_match = bwt_mem_cal_width(bwt, len, seq, w); }*/ //int bowtie_seed_len = 0; //if (opt->seed_type == 1) bowtie_seed_len = 0; //else if (opt->seed_type == 2) bowtie_seed_len = opt->bowtie_seed_len; //else if (opt->seed_type == 3) bowtie_seed_len = 0; //else bowtie_seed_len = 0; a->mem.n = 0; // first pass: find all SMEMs //extern __thread unsigned long int bwt_extend_call_1_local, bwt_extend_call_2_local, bwt_extend_call_3_local, bwt_extend_call_4_local, bwt_extend_call_5_local, bwt_extend_call_6_local; //bwt_extend_call_1_local = 0, bwt_extend_call_2_local = 0, bwt_extend_call_3_local = 0, bwt_extend_call_4_local = 0, bwt_extend_call_5_local = 0, bwt_extend_call_6_local = 0; while (x < len) { if (seq[x] < 4) { if (opt->seed_type == 1) { x = bwt_smem1(bwt, len, seq, x, start_width, &a->mem1, a->tmpv); } else if (opt->seed_type == 2) { if (x + opt->min_seed_len <= len) { bwt_bowtie_seed(bwt, len, seq, x, start_width, 0, &a->mem1, opt->min_seed_len); x = x + opt->seed_intv; } else break; } else if (opt->seed_type == 3) { x = bwt_fwd_mem(bwt, len, seq, x, start_width, 0, &a->mem1); } else if (opt->seed_type == 4) { if (x + opt->min_seed_len <= len) { bwt_bowtie_seed_inexact(bwt, len, seq, x, start_width, 0, &a->mem1, 1, opt->min_seed_len); x = x + opt->seed_intv; } else break; } else x = bwt_smem1(bwt, len, seq, x, start_width, &a->mem1, a->tmpv); for (i = 0; i < a->mem1.n; ++i) { bwtintv_t *p = &a->mem1.a[i]; int slen = (uint32_t) p->info - (p->info >> 32); // seed length if (slen /*- (opt->seed_type == 4 ? (p->n_miss_match * opt->b) : 0))*/ >= opt->min_seed_len) kv_push(bwtintv_t, a->mem, *p); } } else ++x; } if (opt->seed_type == 1 && opt->re_seed == 1) { old_n = a->mem.n; for (k = 0; k < old_n; ++k) { bwtintv_t *p = &a->mem.a[k]; int start = p->info >> 32, end = (int32_t) p->info; if (end - start < split_len || p->x[2] > opt->split_width) continue; bwt_smem1(bwt, len, seq, (start + end) >> 1, p->x[2] + 1, &a->mem1, a->tmpv); for (i = 0; i < a->mem1.n; ++i) if ((uint32_t) a->mem1.a[i].info - (a->mem1.a[i].info >> 32) >= opt->min_seed_len) kv_push(bwtintv_t, a->mem, a->mem1.a[i]); } // third pass: LAST-like if (opt->max_mem_intv > 0) { x = 0; while (x < len) { if (seq[x] < 4) { if (1) { bwtintv_t m; x = bwt_seed_strategy1(bwt, len, seq, x, opt->min_seed_len, opt->max_mem_intv, &m); if (m.x[2] > 0) kv_push(bwtintv_t, a->mem, m); } else { // for now, we never come to this block which is slower x = bwt_smem1a(bwt, len, seq, x, start_width, opt->max_mem_intv, &a->mem1, a->tmpv); for (i = 0; i < a->mem1.n; ++i) kv_push(bwtintv_t, a->mem, a->mem1.a[i]); } } else ++x; } } } /*for (i = 0; i < a->mem1.n; ++i) if ((uint32_t)a->mem1.a[i].info - (a->mem1.a[i].info>>32) >= opt->min_seed_len) kv_push(bwtintv_t, a->mem, a->mem1.a[i]);*/ // second pass: find MEMs inside a long SMEM /*old_n = a->mem.n; for (k = 0; k < old_n; ++k) { bwtintv_t *p = &a->mem.a[k]; int start = p->info>>32, end = (int32_t)p->info; if (end - start < split_len || p->x[2] > opt->split_width) continue; bwt_smem1(bwt, len, seq, (start + end)>>1, p->x[2]+1, &a->mem1, a->tmpv); for (i = 0; i < a->mem1.n; ++i) if ((uint32_t)a->mem1.a[i].info - (a->mem1.a[i].info>>32) >= opt->min_seed_len) kv_push(bwtintv_t, a->mem, a->mem1.a[i]); } // third pass: LAST-like if (opt->max_mem_intv > 0) { x = 0; while (x < len) { if (seq[x] < 4) { if (1) { bwtintv_t m; x = bwt_seed_strategy1(bwt, len, seq, x, opt->min_seed_len, opt->max_mem_intv, &m); if (m.x[2] > 0) kv_push(bwtintv_t, a->mem, m); } else { // for now, we never come to this block which is slower x = bwt_smem1a(bwt, len, seq, x, start_width, opt->max_mem_intv, &a->mem1, a->tmpv); for (i = 0; i < a->mem1.n; ++i) kv_push(bwtintv_t, a->mem, a->mem1.a[i]); } } else ++x; } }*/ //sort ks_introsort(mem_intv, a->mem.n, a->mem.a); } /*static void mem_collect_intv(const mem_opt_t *opt, const bwt_t *bwt, int len, const uint8_t *seq, smem_aux_t *a) { int i, k, x = 0, old_n; int start_width = 1; int split_len = (int)(opt->min_seed_len * opt->split_factor + .499); a->mem.n = 0; // first pass: find all SMEMs while (x < len) { if (seq[x] < 4) { x = bwt_smem1(bwt, len, seq, x, start_width, &a->mem1, a->tmpv); for (i = 0; i < a->mem1.n; ++i) { bwtintv_t *p = &a->mem1.a[i]; int slen = (uint32_t)p->info - (p->info>>32); // seed length if (slen >= opt->min_seed_len) kv_push(bwtintv_t, a->mem, *p); } } else ++x; } // second pass: find MEMs inside a long SMEM old_n = a->mem.n; for (k = 0; k < old_n; ++k) { bwtintv_t *p = &a->mem.a[k]; int start = p->info>>32, end = (int32_t)p->info; if (end - start < split_len || p->x[2] > opt->split_width) continue; bwt_smem1(bwt, len, seq, (start + end)>>1, p->x[2]+1, &a->mem1, a->tmpv); for (i = 0; i < a->mem1.n; ++i) if ((uint32_t)a->mem1.a[i].info - (a->mem1.a[i].info>>32) >= opt->min_seed_len) kv_push(bwtintv_t, a->mem, a->mem1.a[i]); } // third pass: LAST-like if (opt->max_mem_intv > 0) { x = 0; while (x < len) { if (seq[x] < 4) { if (1) { bwtintv_t m; x = bwt_seed_strategy1(bwt, len, seq, x, opt->min_seed_len, opt->max_mem_intv, &m); if (m.x[2] > 0) kv_push(bwtintv_t, a->mem, m); } else { // for now, we never come to this block which is slower x = bwt_smem1a(bwt, len, seq, x, start_width, opt->max_mem_intv, &a->mem1, a->tmpv); for (i = 0; i < a->mem1.n; ++i) kv_push(bwtintv_t, a->mem, a->mem1.a[i]); } } else ++x; } } // sort ks_introsort(mem_intv, a->mem.n, a->mem.a); }*/ /************ * Chaining * ************/ typedef struct { int64_t rbeg; int32_t qbeg, len; int score; } mem_seed_t; // unaligned memory typedef struct { int n, m, first, rid; uint32_t w :29, kept :2, is_alt :1; float frac_rep; int64_t pos; mem_seed_t *seeds; } mem_chain_t; typedef struct { size_t n, m; mem_chain_t *a; } mem_chain_v; #include "kbtree.h" #define chain_cmp(a, b) (((b).pos < (a).pos) - ((a).pos < (b).pos)) KBTREE_INIT(chn, mem_chain_t, chain_cmp) // return 1 if the seed is merged into the chain static int test_and_merge(const mem_opt_t *opt, int64_t l_pac, mem_chain_t *c, const mem_seed_t *p, int seed_rid) { int64_t qend, rend, x, y; const mem_seed_t *last = &c->seeds[c->n - 1]; qend = last->qbeg + last->len; rend = last->rbeg + last->len; if (seed_rid != c->rid) return 0; // different chr; request a new chain if (p->qbeg >= c->seeds[0].qbeg && p->qbeg + p->len <= qend && p->rbeg >= c->seeds[0].rbeg && p->rbeg + p->len <= rend) return 1; // contained seed; do nothing if ((last->rbeg < l_pac || c->seeds[0].rbeg < l_pac) && p->rbeg >= l_pac) return 0; // don't chain if on different strand x = p->qbeg - last->qbeg; // always non-negtive y = p->rbeg - last->rbeg; if (y >= 0 && x - y <= opt->w && y - x <= opt->w && x - last->len < opt->max_chain_gap && y - last->len < opt->max_chain_gap) { // grow the chain if (c->n == c->m) { c->m <<= 1; c->seeds = realloc(c->seeds, c->m * sizeof(mem_seed_t)); } c->seeds[c->n++] = *p; return 1; } return 0; // request to add a new chain } int mem_chain_weight(const mem_chain_t *c) { int64_t end; int j, w = 0, tmp; for (j = 0, end = 0; j < c->n; ++j) { const mem_seed_t *s = &c->seeds[j]; if (s->qbeg >= end) w += s->len; else if (s->qbeg + s->len > end) w += s->qbeg + s->len - end; end = end > s->qbeg + s->len ? end : s->qbeg + s->len; } tmp = w; w = 0; for (j = 0, end = 0; j < c->n; ++j) { const mem_seed_t *s = &c->seeds[j]; if (s->rbeg >= end) w += s->len; else if (s->rbeg + s->len > end) w += s->rbeg + s->len - end; end = end > s->rbeg + s->len ? end : s->rbeg + s->len; } w = w < tmp ? w : tmp; return w < 1 << 30 ? w : (1 << 30) - 1; } void mem_print_chain(const bntseq_t *bns, mem_chain_v *chn) { int i, j; for (i = 0; i < chn->n; ++i) { mem_chain_t *p = &chn->a[i]; err_printf("* Found CHAIN(%d): n=%d; weight=%d", i, p->n, mem_chain_weight(p)); for (j = 0; j < p->n; ++j) { bwtint_t pos; int is_rev; pos = bns_depos(bns, p->seeds[j].rbeg, &is_rev); if (is_rev) pos -= p->seeds[j].len - 1; err_printf("\t%d;%d;%d,%ld(%s:%c%ld)", p->seeds[j].score, p->seeds[j].len, p->seeds[j].qbeg, (long) p->seeds[j].rbeg, bns->anns[p->rid].name, "+-"[is_rev], (long) (pos - bns->anns[p->rid].offset) + 1); } err_putchar('\n'); } } mem_chain_v mem_chain(const mem_opt_t *opt, const bwt_t *bwt, const bntseq_t *bns, int len, const uint8_t *seq, void *buf) { int i, b, e, l_rep; int64_t l_pac = bns->l_pac; mem_chain_v chain; kbtree_t(chn) *tree; smem_aux_t *aux; kv_init(chain); if (len < opt->min_seed_len) return chain; // if the query is shorter than the seed length, no match tree = kb_init(chn, KB_DEFAULT_SIZE); aux = buf ? (smem_aux_t*) buf : smem_aux_init(); mem_collect_intv(opt, bwt, len, seq, aux); for (i = 0, b = e = l_rep = 0; i < aux->mem.n; ++i) { // compute frac_rep bwtintv_t *p = &aux->mem.a[i]; int sb = (p->info >> 32), se = (uint32_t) p->info; if (p->x[2] <= opt->max_occ) continue; if (sb > e) l_rep += e - b, b = sb, e = se; else e = e > se ? e : se; } l_rep += e - b; for (i = 0; i < aux->mem.n; ++i) { bwtintv_t *p = &aux->mem.a[i]; int step, count, slen = (uint32_t) p->info - (p->info >> 32); // seed length int64_t k; // if (slen < opt->min_seed_len) continue; // ignore if too short or too repetitive step = p->x[2] > opt->max_occ ? p->x[2] / opt->max_occ : 1; for (k = count = 0; k < p->x[2] && count < opt->max_occ; k += step, ++count) { mem_chain_t tmp, *lower, *upper; mem_seed_t s; int rid, to_add = 0; s.rbeg = tmp.pos = bwt_sa(bwt, p->x[0] + k); // this is the base coordinate in the forward-reverse reference s.qbeg = p->info >> 32; s.len = slen; s.score = slen - ((opt->seed_type == 4) ? (p->n_miss_match * opt->b) : 0); rid = bns_intv2rid(bns, s.rbeg, s.rbeg + s.len); if (rid < 0) continue; // bridging multiple reference sequences or the forward-reverse boundary; TODO: split the seed; don't discard it!!! if (kb_size(tree)) { kb_intervalp(chn, tree, &tmp, &lower, &upper); // find the closest chain if (!lower || !test_and_merge(opt, l_pac, lower, &s, rid)) to_add = 1; } else to_add = 1; if (to_add) { // add the seed as a new chain tmp.n = 1; tmp.m = 4; tmp.seeds = calloc(tmp.m, sizeof(mem_seed_t)); tmp.seeds[0] = s; tmp.rid = rid; tmp.is_alt = !!bns->anns[rid].is_alt; kb_putp(chn, tree, &tmp); } } } if (buf == 0) smem_aux_destroy(aux); kv_resize(mem_chain_t, chain, kb_size(tree)); #define traverse_func(p_) (chain.a[chain.n++] = *(p_)) __kb_traverse(mem_chain_t, tree, traverse_func); #undef traverse_func for (i = 0; i < chain.n; ++i) chain.a[i].frac_rep = (float) l_rep / len; if (bwa_verbose >= 4) printf("* fraction of repetitive seeds: %.3f\n", (float) l_rep / len); kb_destroy(chn, tree); return chain; } /******************** * Filtering chains * ********************/ #define chn_beg(ch) ((ch).seeds->qbeg) #define chn_end(ch) ((ch).seeds[(ch).n-1].qbeg + (ch).seeds[(ch).n-1].len) #define flt_lt(a, b) ((a).w > (b).w) KSORT_INIT(mem_flt, mem_chain_t, flt_lt) int mem_chain_flt(const mem_opt_t *opt, int n_chn, mem_chain_t *a) { int i, k; kvec_t(int) chains = { 0, 0, 0 }; // this keeps int indices of the non-overlapping chains if (n_chn == 0) return 0; // no need to filter // compute the weight of each chain and drop chains with small weight for (i = k = 0; i < n_chn; ++i) { mem_chain_t *c = &a[i]; c->first = -1; c->kept = 0; c->w = mem_chain_weight(c); if (c->w < opt->min_chain_weight) free(c->seeds); else a[k++] = *c; } n_chn = k; ks_introsort(mem_flt, n_chn, a); // pairwise chain comparisons a[0].kept = 3; kv_push(int, chains, 0); for (i = 1; i < n_chn; ++i) { int large_ovlp = 0; for (k = 0; k < chains.n; ++k) { int j = chains.a[k]; int b_max = chn_beg(a[j]) > chn_beg(a[i]) ? chn_beg(a[j]) : chn_beg(a[i]); int e_min = chn_end(a[j]) < chn_end(a[i]) ? chn_end(a[j]) : chn_end(a[i]); if (e_min > b_max && (!a[j].is_alt || a[i].is_alt)) { // have overlap; don't consider ovlp where the kept chain is ALT while the current chain is primary int li = chn_end(a[i]) - chn_beg(a[i]); int lj = chn_end(a[j]) - chn_beg(a[j]); int min_l = li < lj ? li : lj; if (e_min - b_max >= min_l * opt->mask_level && min_l < opt->max_chain_gap) { // significant overlap large_ovlp = 1; if (a[j].first < 0) a[j].first = i; // keep the first shadowed hit s.t. mapq can be more accurate if (a[i].w < a[j].w * opt->drop_ratio && a[j].w - a[i].w >= opt->min_seed_len << 1) break; } } } if (k == chains.n) { kv_push(int, chains, i); a[i].kept = large_ovlp ? 2 : 3; } } for (i = 0; i < chains.n; ++i) { mem_chain_t *c = &a[chains.a[i]]; if (c->first >= 0) a[c->first].kept = 1; } free(chains.a); for (i = k = 0; i < n_chn; ++i) { // don't extend more than opt->max_chain_extend .kept=1/2 chains if (a[i].kept == 0 || a[i].kept == 3) continue; if (++k >= opt->max_chain_extend) break; } for (; i < n_chn; ++i) if (a[i].kept < 3) a[i].kept = 0; for (i = k = 0; i < n_chn; ++i) { // free discarded chains mem_chain_t *c = &a[i]; if (c->kept == 0) free(c->seeds); else a[k++] = a[i]; } return k; } /****************************** * De-overlap single-end hits * ******************************/ #define alnreg_slt2(a, b) ((a).re < (b).re) KSORT_INIT(mem_ars2, mem_alnreg_t, alnreg_slt2) #define alnreg_slt(a, b) ((a).score > (b).score || ((a).score == (b).score && ((a).rb < (b).rb || ((a).rb == (b).rb && (a).qb < (b).qb)))) KSORT_INIT(mem_ars, mem_alnreg_t, alnreg_slt) #define alnreg_hlt(a, b) ((a).score > (b).score || ((a).score == (b).score && ((a).is_alt < (b).is_alt || ((a).is_alt == (b).is_alt && (a).hash < (b).hash)))) KSORT_INIT(mem_ars_hash, mem_alnreg_t, alnreg_hlt) #define alnreg_hlt2(a, b) ((a).is_alt < (b).is_alt || ((a).is_alt == (b).is_alt && ((a).score > (b).score || ((a).score == (b).score && (a).hash < (b).hash)))) KSORT_INIT(mem_ars_hash2, mem_alnreg_t, alnreg_hlt2) #define PATCH_MAX_R_BW 0.05f #define PATCH_MIN_SC_RATIO 0.90f int mem_patch_reg(const mem_opt_t *opt, const bntseq_t *bns, const uint8_t *pac, uint8_t *query, const mem_alnreg_t *a, const mem_alnreg_t *b, int *_w) { int w, score, q_s, r_s; double r; if (bns == 0 || pac == 0 || query == 0) return 0; assert(a->rid == b->rid && a->rb <= b->rb); if (a->rb < bns->l_pac && b->rb >= bns->l_pac) return 0; // on different strands if (a->qb >= b->qb || a->qe >= b->qe || a->re >= b->re) return 0; // not colinear w = (a->re - b->rb) - (a->qe - b->qb); // required bandwidth w = w > 0 ? w : -w; // l = abs(l) r = (double) (a->re - b->rb) / (b->re - a->rb) - (double) (a->qe - b->qb) / (b->qe - a->qb); // relative bandwidth r = r > 0. ? r : -r; // r = fabs(r) if (bwa_verbose >= 4) printf("* potential hit merge between [%d,%d)<=>[%ld,%ld) and [%d,%d)<=>[%ld,%ld), @ %s; w=%d, r=%.4g\n", a->qb, a->qe, (long) a->rb, (long) a->re, b->qb, b->qe, (long) b->rb, (long) b->re, bns->anns[a->rid].name, w, r); if (a->re < b->rb || a->qe < b->qb) { // no overlap on query or on ref if (w > opt->w << 1 || r >= PATCH_MAX_R_BW) return 0; // the bandwidth or the relative bandwidth is too large } else if (w > opt->w << 2 || r >= PATCH_MAX_R_BW * 2) return 0; // more permissive if overlapping on both ref and query // global alignment w += a->w + b->w; w = w < opt->w << 2 ? w : opt->w << 2; if (bwa_verbose >= 4) printf("* test potential hit merge with global alignment; w=%d\n", w); bwa_gen_cigar2(opt->mat, opt->o_del, opt->e_del, opt->o_ins, opt->e_ins, w, bns->l_pac, pac, b->qe - a->qb, query + a->qb, a->rb, b->re, &score, 0, 0); q_s = (int) ((double) (b->qe - a->qb) / ((b->qe - b->qb) + (a->qe - a->qb)) * (b->score + a->score) + .499); // predicted score from query r_s = (int) ((double) (b->re - a->rb) / ((b->re - b->rb) + (a->re - a->rb)) * (b->score + a->score) + .499); // predicted score from ref if (bwa_verbose >= 4) printf("* score=%d;(%d,%d)\n", score, q_s, r_s); if ((double) score / (q_s > r_s ? q_s : r_s) < PATCH_MIN_SC_RATIO) return 0; *_w = w; return score; } int mem_sort_dedup_patch(const mem_opt_t *opt, const bntseq_t *bns, const uint8_t *pac, uint8_t *query, int n, mem_alnreg_t *a) { int m, i, j; if (n <= 1) return n; ks_introsort(mem_ars2, n, a); // sort by the END position, not START! for (i = 0; i < n; ++i) a[i].n_comp = 1; for (i = 1; i < n; ++i) { mem_alnreg_t *p = &a[i]; if (p->rid != a[i - 1].rid || p->rb >= a[i - 1].re + opt->max_chain_gap) continue; // then no need to go into the loop below for (j = i - 1; j >= 0 && p->rid == a[j].rid && p->rb < a[j].re + opt->max_chain_gap; --j) { mem_alnreg_t *q = &a[j]; int64_t or, oq, mr, mq; int score, w; if (q->qe == q->qb) continue; // a[j] has been excluded or = q->re - p->rb; // overlap length on the reference oq = q->qb < p->qb ? q->qe - p->qb : p->qe - q->qb; // overlap length on the query mr = q->re - q->rb < p->re - p->rb ? q->re - q->rb : p->re - p->rb; // min ref len in alignment mq = q->qe - q->qb < p->qe - p->qb ? q->qe - q->qb : p->qe - p->qb; // min qry len in alignment if (or > opt->mask_level_redun * mr && oq > opt->mask_level_redun * mq) { // one of the hits is redundant if (p->score < q->score) { p->qe = p->qb; break; } else q->qe = q->qb; } else if (q->rb < p->rb && (score = mem_patch_reg(opt, bns, pac, query, q, p, &w)) > 0) { // then merge q into p p->n_comp += q->n_comp + 1; p->seedcov = p->seedcov > q->seedcov ? p->seedcov : q->seedcov; p->sub = p->sub > q->sub ? p->sub : q->sub; p->csub = p->csub > q->csub ? p->csub : q->csub; p->qb = q->qb, p->rb = q->rb; p->truesc = p->score = score; p->w = w; q->qb = q->qe; } } } for (i = 0, m = 0; i < n; ++i) // exclude identical hits if (a[i].qe > a[i].qb) { if (m != i) a[m++] = a[i]; else ++m; } n = m; ks_introsort(mem_ars, n, a); for (i = 1; i < n; ++i) { // mark identical hits if (a[i].score == a[i - 1].score && a[i].rb == a[i - 1].rb && a[i].qb == a[i - 1].qb) a[i].qe = a[i].qb; } for (i = 1, m = 1; i < n; ++i) // exclude identical hits if (a[i].qe > a[i].qb) { if (m != i) a[m++] = a[i]; else ++m; } return m; } typedef kvec_t(int) int_v; static void mem_mark_primary_se_core(const mem_opt_t *opt, int n, mem_alnreg_t *a, int_v *z) { // similar to the loop in mem_chain_flt() int i, k, tmp; tmp = opt->a + opt->b; tmp = opt->o_del + opt->e_del > tmp ? opt->o_del + opt->e_del : tmp; tmp = opt->o_ins + opt->e_ins > tmp ? opt->o_ins + opt->e_ins : tmp; z->n = 0; kv_push(int, *z, 0); for (i = 1; i < n; ++i) { for (k = 0; k < z->n; ++k) { int j = z->a[k]; int b_max = a[j].qb > a[i].qb ? a[j].qb : a[i].qb; int e_min = a[j].qe < a[i].qe ? a[j].qe : a[i].qe; if (e_min > b_max) { // have overlap int min_l = a[i].qe - a[i].qb < a[j].qe - a[j].qb ? a[i].qe - a[i].qb : a[j].qe - a[j].qb; if (e_min - b_max >= min_l * opt->mask_level) { // significant overlap if (a[j].sub == 0) a[j].sub = a[i].score; if (a[j].score - a[i].score <= tmp && (a[j].is_alt || !a[i].is_alt)) ++a[j].sub_n; break; } } } if (k == z->n) kv_push(int, *z, i); else a[i].secondary = z->a[k]; } } int mem_mark_primary_se(const mem_opt_t *opt, int n, mem_alnreg_t *a, int64_t id) { int i, n_pri; int_v z = { 0, 0, 0 }; if (n == 0) return 0; for (i = n_pri = 0; i < n; ++i) { a[i].sub = a[i].alt_sc = 0, a[i].secondary = a[i].secondary_all = -1, a[i].hash = hash_64(id + i); if (!a[i].is_alt) ++n_pri; } ks_introsort(mem_ars_hash, n, a); mem_mark_primary_se_core(opt, n, a, &z); for (i = 0; i < n; ++i) { mem_alnreg_t *p = &a[i]; p->secondary_all = i; // keep the rank in the first round if (!p->is_alt && p->secondary >= 0 && a[p->secondary].is_alt) { fprintf(stderr, "I am here 1"); p->alt_sc = a[p->secondary].score; } } if (n_pri >= 0 && n_pri < n) { fprintf(stderr, "I am here 2"); kv_resize(int, z, n); if (n_pri > 0) ks_introsort(mem_ars_hash2, n, a); for (i = 0; i < n; ++i) z.a[a[i].secondary_all] = i; for (i = 0; i < n; ++i) { if (a[i].secondary >= 0) { a[i].secondary_all = z.a[a[i].secondary]; if (a[i].is_alt) a[i].secondary = INT_MAX; } else a[i].secondary_all = -1; } if (n_pri > 0) { // mark primary for hits to the primary assembly only for (i = 0; i < n_pri; ++i) a[i].sub = 0, a[i].secondary = -1; mem_mark_primary_se_core(opt, n_pri, a, &z); } } else { for (i = 0; i < n; ++i) a[i].secondary_all = a[i].secondary; } free(z.a); return n_pri; } /********************************* * Test if a seed is good enough * *********************************/ #define MEM_SHORT_EXT 50 #define MEM_SHORT_LEN 200 #define MEM_HSP_COEF 1.1f #define MEM_MINSC_COEF 5.5f #define MEM_SEEDSW_COEF 0.05f int mem_seed_sw(const mem_opt_t *opt, const bntseq_t *bns, const uint8_t *pac, int l_query, const uint8_t *query, const mem_seed_t *s) { int qb, qe, rid; int64_t rb, re, mid, l_pac = bns->l_pac; uint8_t *rseq = 0; kswr_t x; if (s->len >= MEM_SHORT_LEN) return -1; // the seed is longer than the max-extend; no need to do SW qb = s->qbeg, qe = s->qbeg + s->len; rb = s->rbeg, re = s->rbeg + s->len; mid = (rb + re) >> 1; qb -= MEM_SHORT_EXT; qb = qb > 0 ? qb : 0; qe += MEM_SHORT_EXT; qe = qe < l_query ? qe : l_query; rb -= MEM_SHORT_EXT; rb = rb > 0 ? rb : 0; re += MEM_SHORT_EXT; re = re < l_pac << 1 ? re : l_pac << 1; if (rb < l_pac && l_pac < re) { if (mid < l_pac) re = l_pac; else rb = l_pac; } if (qe - qb >= MEM_SHORT_LEN || re - rb >= MEM_SHORT_LEN) return -1; // the seed seems good enough; no need to do SW rseq = bns_fetch_seq(bns, pac, &rb, mid, &re, &rid); x = ksw_align2(qe - qb, (uint8_t*) query + qb, re - rb, rseq, 5, opt->mat, opt->o_del, opt->e_del, opt->o_ins, opt->e_ins, KSW_XSTART, 0, opt->use_avx2); free(rseq); return x.score; } void mem_shd_flt_chained_seeds(const mem_opt_t *opt, const bntseq_t *bns, const uint8_t *pac, int l_query, const uint8_t *query, int n_chn, mem_chain_t *a) { int i, j, k; for (i = 0; i < n_chn; ++i) { mem_chain_t *c = &a[i]; for (j = k = 0; j < c->n; ++j) { mem_seed_t *s = &c->seeds[j]; int qb, qe, is_right_pass = 1, is_left_pass = 1, right_len = 0, left_len = 0; int64_t rb, re, l_pac = bns->l_pac; qb = s->qbeg, qe = s->qbeg + s->len; rb = s->rbeg, re = s->rbeg + s->len; uint8_t seed2bit[s->len]; memcpy(seed2bit, query + qb, s->len); int l; char seed[s->len+1]; for (l=0; l < s->len; l++){ seed[l] = "ACGTN"[(int) seed2bit[l]]; } seed[l] = '\0'; if (qe < l_query) { uint8_t *rseq = 0; int rid; int qbeg = (qe - 5) > 0 ? (qe - 5) : 0; int qend = (qbeg + 128) <= l_query ? (qbeg + 128) : l_query; char read_display[320] __aligned__; { int q, f; for (q = qbeg, f = 0; f < 320; q++, f++) { if (q < qend) read_display[f] = "ACGTN"[(int) query[q]]; else read_display[f] = '\0'; } } char read_t[320] __aligned__; //strcpy(read_t, "TCCTCCAAGAAGATATGTAGTTGGTAAATAAACATAAGAAAAGATGCTCAAAACAATATGTTATTAGGGAACTTCAAATTAACATGATGAGATACCATTATACACCAATTAGAATGTCTAATATCTGA"); int q, f; for (q = qbeg, f = 0; f < 320; q++, f++) { if (q < qend) read_t[f] = "ACGTN"[(int) query[q]]; else read_t[f] = '\0'; } int64_t rbeg = (re - 5) > 0 ? (re - 5) : 0; int64_t rend = (rbeg + 128) < (l_pac << 1) ? rbeg + 128 : (l_pac << 1); int64_t mid = (rbeg + rend) >> 1; if (rbeg < l_pac && l_pac < rend) { if (mid < l_pac) rend = l_pac; else rbeg = l_pac; } rseq = bns_fetch_seq(bns, pac, &rbeg, mid, &rend, &rid); char ref_display[320] __aligned__; { int r, f; for (r = 0, f = 0; f < 320; r++, f++) { if (r < (rend - rbeg)) { //fprintf(stderr, "%d, ", r); //fflush(stderr); ref_display[f] = "ACGTN"[(int) rseq[r]]; } else ref_display[f] = '\0'; } } char ref_t[320] __aligned__; //strcpy(ref_t, "TCCTCAAAGAAGATATGTAGTTGGTAAATAAACATAAGAAAAGATGCTCAAAACAATATGTTATTAGGGAACTTCAAATTAACATGATGAGATACCATTATACACCAATTAGAATGTCTAATATCTGA"); int r; for (r = 0, f = 0; f < 320; r++, f++) { if (r < (rend - rbeg)) { //fprintf(stderr, "%d, ", r); //fflush(stderr); ref_t[f] = "ACGTN"[(int) rseq[r]]; } else ref_t[f] = '\0'; } //fprintf(stderr, "\n"); right_len = qend - qbeg; //int max_err = (int) ceil(0.1 * (double) right_len); is_right_pass = bit_vec_filter_sse1(read_t, ref_t, (rend - rbeg), 7); /*if (!is_right_pass){ fprintf(stderr, "%d, %d, %s, %s, %s\n", max_err, rend - rbeg, seed, read_display, ref_display); //fprintf(stderr, "%d, %d, %s, %s, %s\n", qb, qe, seed, read_t, ref_t); //fprintf(stderr, "fail\n"); }*/ free(rseq); } if (qb > 0) { uint8_t *rseq = 0; int rid; int qend = (qb + 5) < l_query ? (qb + 5) : l_query; int qbeg = (qend - 128) > 0 ? (qend - 128) : 0; char read_display[320] __aligned__; { int q, f; for (q = qend - 1, f = 0; f < 320; q--, f++) { if (q >= qbeg) read_display[f] = "ACGTN"[(int) query[q]]; else read_display[f] = '\0'; } } char read_t[320] __aligned__; int q, f; for (q = qend - 1, f = 0; f < 320; q--, f++) { if (q >= qbeg) read_t[f] = "ACGTN"[(int) query[q]]; else read_t[f] = '\0'; } int64_t rend = (rb + 5) < (l_pac << 1) ? (rb + 5) : (l_pac << 1); int64_t rbeg = (rend - 128) > 0 ? rend - 128 : 0; int64_t mid = (rbeg + rend) >> 1; if (rbeg < l_pac && l_pac < rend) { if (mid < l_pac) rend = l_pac; else rbeg = l_pac; } rseq = bns_fetch_seq(bns, pac, &rbeg, mid, &rend, &rid); char ref_display[320] __aligned__; { int r, f; for (r = (rend - rbeg) - 1, f = 0; f < 320; r--, f++) { if (r >= 0) ref_display[f] = "ACGTN"[(int) rseq[r]]; else ref_display[f] = '\0'; } } char ref_t[320] __aligned__; int r; for (r = (rend - rbeg) - 1, f = 0; f < 320; r--, f++) { if (r >= 0) ref_t[f] = "ACGTN"[(int) rseq[r]]; else ref_t[f] = '\0'; } left_len = qend - qbeg; //int max_err = (int) ceil(0.1 * (double) left_len); is_left_pass = bit_vec_filter_sse1(read_t, ref_t, (rend - rbeg), 7); /*if (!is_left_pass) { fprintf(stderr, "%d, %d, %s, %s, %s\n", max_err, rend - rbeg, seed, read_display, ref_display); //fprintf(stderr, "%d, %d, %s, %s, %s\n", qb, qe, seed, read_t, ref_t); //fprintf(stderr, "fail\n"); }*/ free(rseq); } //s->score = mem_seed_sw(opt, bns, pac, l_query, query, s); if (is_left_pass || is_right_pass) { //s->score = s->score < 0 ? s->len * opt->a : s->score; c->seeds[k++] = *s; } //fprintf(stderr, "(%d,%d,%d) ", total_len, total_err,(int) ceil(0.05 * (double) total_len)); } c->n = k; } //fprintf(stderr, "\n"); } void mem_flt_chained_seeds(const mem_opt_t *opt, const bntseq_t *bns, const uint8_t *pac, int l_query, const uint8_t *query, int n_chn, mem_chain_t *a) { double min_l = opt->min_chain_weight ? MEM_HSP_COEF * opt->min_chain_weight : MEM_MINSC_COEF * log(l_query); int i, j, k, min_HSP_score = (int) (opt->a * min_l + .499); if (min_l > MEM_SEEDSW_COEF * l_query) return; // don't run the following for short reads for (i = 0; i < n_chn; ++i) { mem_chain_t *c = &a[i]; for (j = k = 0; j < c->n; ++j) { mem_seed_t *s = &c->seeds[j]; s->score = mem_seed_sw(opt, bns, pac, l_query, query, s); if (s->score < 0 || s->score >= min_HSP_score) { s->score = s->score < 0 ? s->len * opt->a : s->score; c->seeds[k++] = *s; } } c->n = k; } } /**************************************** * Construct the alignment from a chain * ****************************************/ static inline int cal_max_gap(const mem_opt_t *opt, int qlen) { int l_del = (int) ((double) (qlen * opt->a - opt->o_del) / opt->e_del + 1.); int l_ins = (int) ((double) (qlen * opt->a - opt->o_ins) / opt->e_ins + 1.); int l = l_del > l_ins ? l_del : l_ins; l = l > 1 ? l : 1; return l < opt->w << 1 ? l : opt->w << 1; } #define MAX_BAND_TRY 2 typedef kvec_t(uint8_t*) seq_ptr_arr; typedef kvec_t(int) seq_lens; typedef kvec_t(uint8_t) seq_batch; typedef kvec_t(int) seq_offsets; //typedef struct { // gasal_gpu_storage_t *gpu_storage; // int batch_size; // int batch_start; // int is_active; // int no_extend; // //int32_t *max_score, *read_start, *read_end, *ref_start, *ref_end; // int n_query_batch, n_target_batch, n_seqs; // }gpu_batch; //typedef kvec_t(int) aln_pair; void mem_chain2aln(const mem_opt_t *opt, const bntseq_t *bns, const uint8_t *pac, int l_query, const uint8_t *query, const mem_chain_t *c, mem_alnreg_v *av, int *curr_read_offset, int *curr_ref_offset, gpu_batch *curr_gpu_batch) { int i, k; uint64_t *srt; if (c->n == 0) return; //extern uint64_t *no_of_extensions; // get the max possible span /*rmax[0] = l_pac<<1; rmax[1] = 0; for (i = 0; i < c->n; ++i) { int64_t b, e; const mem_seed_t *t = &c->seeds[i]; b = t->rbeg - (t->qbeg + cal_max_gap(opt, t->qbeg)); e = t->rbeg + t->len + ((l_query - t->qbeg - t->len) + cal_max_gap(opt, l_query - t->qbeg - t->len)); rmax[0] = rmax[0] < b? rmax[0] : b; rmax[1] = rmax[1] > e? rmax[1] : e; if (t->len > max) max = t->len; } rmax[0] = rmax[0] > 0? rmax[0] : 0; rmax[1] = rmax[1] < l_pac<<1? rmax[1] : l_pac<<1; if (rmax[0] < l_pac && l_pac < rmax[1]) { // crossing the forward-reverse boundary; then choose one side if (c->seeds[0].rbeg < l_pac) rmax[1] = l_pac; // this works because all seeds are guaranteed to be on the same strand else rmax[0] = l_pac; } // retrieve the reference sequence rseq = bns_fetch_seq(bns, pac, &rmax[0], c->seeds[0].rbeg, &rmax[1], &rid); assert(c->rid == rid);*/ srt = malloc(c->n * 8); for (i = 0; i < c->n; ++i) srt[i] = (uint64_t)c->seeds[i].score<<32 | i; ks_introsort_64(c->n, srt); for (k = c->n - 1; k >= 0; --k) { mem_alnreg_t *a; int64_t l_pac = bns->l_pac, tmp, max = 0; const mem_seed_t *s; s = &c->seeds[(uint32_t)srt[k]]; int max_off[2], aw[2]; for (i = 0; i < av->n; ++i) { // test whether extension has been made before mem_alnreg_t *p = &av->a[i]; int64_t rd; int qd, w, max_gap; if (s->rbeg < p->rb_est || s->rbeg + s->len > p->re_est || s->qbeg < p->qb_est || s->qbeg + s->len > p->qe_est) continue; // not fully contained if (s->len - p->seedlen0 > .1 * l_query) continue; // this seed may give a better alignment // qd: distance ahead of the seed on query; rd: on reference qd = s->qbeg - p->qb_est; rd = s->rbeg - p->rb_est; max_gap = cal_max_gap(opt, qd < rd? qd : rd); // the maximal gap allowed in regions ahead of the seed w = max_gap < p->w? max_gap : p->w; // bounded by the band width if (qd - rd < w && rd - qd < w) break; // the seed is "around" a previous hit // similar to the previous four lines, but this time we look at the region behind qd = p->qe_est - (s->qbeg + s->len); rd = p->re_est - (s->rbeg + s->len); max_gap = cal_max_gap(opt, qd < rd? qd : rd); w = max_gap < p->w? max_gap : p->w; if (qd - rd < w && rd - qd < w) break; } if (i < av->n) { // the seed is (almost) contained in an existing alignment; further testing is needed to confirm it is not leading to a different aln if (bwa_verbose >= 4) printf("** Seed(%d) [%ld;%ld,%ld] is almost contained in an existing alignment [%d,%d) <=> [%ld,%ld)\n", k, (long)s->len, (long)s->qbeg, (long)s->rbeg, av->a[i].qb, av->a[i].qe, (long)av->a[i].rb, (long)av->a[i].re); for (i = k + 1; i < c->n; ++i) { // check overlapping seeds in the same chain const mem_seed_t *t; if (srt[i] == 0) continue; t = &c->seeds[(uint32_t)srt[i]]; if (t->len < s->len * .95) continue; // only check overlapping if t is long enough; TODO: more efficient by early stopping if (s->qbeg <= t->qbeg && s->qbeg + s->len - t->qbeg >= s->len>>2 && t->qbeg - s->qbeg != t->rbeg - s->rbeg) break; if (t->qbeg <= s->qbeg && t->qbeg + t->len - s->qbeg >= s->len>>2 && s->qbeg - t->qbeg != s->rbeg - t->rbeg) break; } if (i == c->n) { // no overlapping seeds; then skip extension srt[k] = 0; // mark that seed extension has not been performed continue; } if (bwa_verbose >= 4) printf("** Seed(%d) might lead to a different alignment even though it is contained. Extension will be performed.\n", k); } a = kv_pushp(mem_alnreg_t, *av); memset(a, 0, sizeof(mem_alnreg_t)); a->w = aw[0] = aw[1] = opt->w; a->score = a->truesc = -1; a->rid = c->rid; int fwd = 0.85*(l_query - (s->qbeg + s->len)); a->qe_est = ((s->qbeg + s->len) + fwd) < l_query ? ((s->qbeg + s->len) + fwd) : l_query; a->re_est = ((s->rbeg + s->len) + fwd) < l_pac << 1 ? ((s->rbeg + s->len) + fwd) : l_pac << 1; int back = 0.85*(s->qbeg + 1); a->qb_est = (s->qbeg - back) > 0 ? (s->qbeg - back) : 0; a->rb_est = (s->rbeg - back) > 0 ? (s->rbeg - back) : 0; if (a->rb_est < l_pac && l_pac < a->qe_est) { // crossing the forward-reverse boundary; then choose one side if (s->rbeg < l_pac) a->re_est = l_pac; // this works because all seeds are guaranteed to be on the same strand else a->rb_est = l_pac; } // rmax[0] = l_pac<<1; rmax[1] = 0; // rmax[0] = s->rbeg - (s->qbeg + cal_max_gap(opt, s->qbeg)); // rmax[1] = s->rbeg + s->len + ((l_query - s->qbeg - s->len) + cal_max_gap(opt, l_query - s->qbeg - s->len)); // if (s->len > max) max = s->len; // rmax[0] = rmax[0] > 0? rmax[0] : 0; // rmax[1] = rmax[1] < l_pac<<1? rmax[1] : l_pac<<1; // if (rmax[0] < l_pac && l_pac < rmax[1]) { // crossing the forward-reverse boundary; then choose one side // if (s->rbeg < l_pac) rmax[1] = l_pac; // this works because all seeds are guaranteed to be on the same strand // else rmax[0] = l_pac; // } // // retrieve the reference sequence // rseq = bns_fetch_seq(bns, pac, &rmax[0], s->rbeg, &rmax[1], &rid); // assert(c->rid == rid); if(s->len != l_query) { int64_t rmax[2]; uint8_t *rseq = 0; int rid; rmax[0] = l_pac<<1; rmax[1] = 0; rmax[0] = s->rbeg - (s->qbeg + cal_max_gap(opt, s->qbeg)); rmax[1] = s->rbeg + s->len + ((l_query - s->qbeg - s->len) + cal_max_gap(opt, l_query - s->qbeg - s->len)); rmax[0] = rmax[0] > 0? rmax[0] : 0; rmax[1] = rmax[1] < l_pac<<1? rmax[1] : l_pac<<1; if (rmax[0] < l_pac && l_pac < rmax[1]) { // crossing the forward-reverse boundary; then choose one side if (s->rbeg < l_pac) rmax[1] = l_pac; // this works because all seeds are guaranteed to be on the same strand else rmax[0] = l_pac; } // retrieve the reference sequence /*rseq = */bns_fetch_seq_gpu(bns, pac, &rmax[0], s->rbeg, &rmax[1], &rid, curr_gpu_batch); assert(c->rid == rid); /*int rseq_beg, rseq_end; rseq_beg = s->rbeg - (s->qbeg + cal_max_gap(opt, s->qbeg)) - rmax[0]; rseq_end = s->rbeg + s->len + ((l_query - s->qbeg - s->len) + cal_max_gap(opt, l_query - s->qbeg - s->len)) - rmax[0]; rseq_beg = rseq_beg > 0 ? rseq_beg : 0; rseq_end = rseq_end < (rmax[1] - rmax[0]) ? rseq_end : (rmax[1] - rmax[0]);*/ //uint8_t* rs = malloc(rseq_end - rseq_beg); int ref_l_seq_with_p = ((rmax[1] - rmax[0])%8) ? (rmax[1] - rmax[0]) + (8 - ((rmax[1] - rmax[0])%8)) : (rmax[1] - rmax[0]) ; int j; // for (i = 0, j = 0; i < (rmax[1] - rmax[0]) && j < MAX_SEQ_LEN; ++i, ++j) { // //rs[j] = rseq[i]; // //kv_push(uint8_t, *ref_seq_batch, rseq[i]); // if (curr_gpu_batch->n_target_batch < curr_gpu_batch->gpu_storage->host_max_target_batch_bytes) curr_gpu_batch->gpu_storage->host_unpacked_target_batch[curr_gpu_batch->n_target_batch++] = rseq[i]; // else { // fprintf(stderr, "The size of host target_batch (%d) exceeds the allocation (%d)\n", curr_gpu_batch->n_target_batch + 1, curr_gpu_batch->gpu_storage->host_max_target_batch_bytes); // exit(EXIT_FAILURE); // } // } int ref_l_seq = rmax[1] - rmax[0]; while (ref_l_seq < ref_l_seq_with_p) { //kv_push(uint8_t, *ref_seq_batch, 0); if (curr_gpu_batch->n_target_batch < curr_gpu_batch->gpu_storage->host_max_target_batch_bytes) curr_gpu_batch->gpu_storage->host_unpacked_target_batch[curr_gpu_batch->n_target_batch++] = 4; else { fprintf(stderr, "The size of host target_batch (%d) exceeds the allocation (%d)\n", curr_gpu_batch->n_target_batch + 1, curr_gpu_batch->gpu_storage->host_max_target_batch_bytes); exit(EXIT_FAILURE); } ref_l_seq++; } a->rseq_beg = rmax[0] /*+ rseq_beg*/; if (bwa_verbose >= 4) err_printf("** ---> Extending from seed(%d) [%ld;%ld,%ld] @ %s <---\n", k, (long) s->len, (long) s->qbeg, (long) s->rbeg, bns->anns[c->rid].name); //kv_push(uint8_t*, *read_seqns, query); //kv_push(uint8_t*, *ref_seqns, rs); //kv_push(int, *read_seq_lens, l_query); //kv_push(int, *read_seq_lens, l_query); if (curr_gpu_batch->n_seqs < curr_gpu_batch->gpu_storage->host_max_n_alns) curr_gpu_batch->gpu_storage->host_query_batch_lens[curr_gpu_batch->n_seqs] = l_query; else { fprintf(stderr, "The size of host lens1 (%d) exceeds the allocation (%d)\n", curr_gpu_batch->n_seqs + 1, curr_gpu_batch->gpu_storage->host_max_n_alns); exit(EXIT_FAILURE); } //kv_push(int, *read_seq_offsets, *curr_read_offset); if (curr_gpu_batch->n_seqs < curr_gpu_batch->gpu_storage->host_max_n_alns) curr_gpu_batch->gpu_storage->host_query_batch_offsets[curr_gpu_batch->n_seqs] = *curr_read_offset; else { fprintf(stderr, "The size of host offsets1 (%d) exceeds the allocation (%d)\n", curr_gpu_batch->n_seqs + 1, curr_gpu_batch->gpu_storage->host_max_n_alns); exit(EXIT_FAILURE); } //kv_push(int, *ref_seq_lens, (rmax[1] - rmax[0])); if (curr_gpu_batch->n_seqs < curr_gpu_batch->gpu_storage->host_max_n_alns) curr_gpu_batch->gpu_storage->host_target_batch_lens[curr_gpu_batch->n_seqs] = rmax[1] - rmax[0]; else { fprintf(stderr, "The size of host lens2 (%d) exceeds the allocation (%d)\n", curr_gpu_batch->n_seqs + 1, curr_gpu_batch->gpu_storage->host_max_n_alns); exit(EXIT_FAILURE); } //kv_push(int, *ref_seq_offsets, *curr_ref_offset); if (curr_gpu_batch->n_seqs < curr_gpu_batch->gpu_storage->host_max_n_alns) curr_gpu_batch->gpu_storage->host_target_batch_offsets[curr_gpu_batch->n_seqs] = *curr_ref_offset; else { fprintf(stderr, "The size of host offsets2 (%d) exceeds the allocation (%d)\n", curr_gpu_batch->n_seqs + 1, curr_gpu_batch->gpu_storage->host_max_n_alns); exit(EXIT_FAILURE); } *curr_ref_offset += ref_l_seq_with_p; curr_gpu_batch->n_seqs++; free(rseq); } else { a->score = a->truesc = s->score, a->qb = 0, a->rb = s->rbeg, a->qe = l_query, a->re = s->rbeg + s->len; } //kv_push(int, *read_idx_vec, read_idx); /*if(opt->seed_type == 2) { uint8_t *rs, *qs; int qle, tle, gtle, gscore; int qe = s->qbeg + s->len; int re = s->rbeg + s->len - rmax[0]; // qs = malloc(s->qbeg); //for (i = 0; i < s->qbeg; ++i) qs[i] = query[s->qbeg - 1 - i]; //tmp = s->rbeg - rmax[0]; //rs = malloc(tmp); //for (i = 0; i < tmp; ++i) rs[i] = rseq[tmp - 1 - i]; for (i = 0; i < MAX_BAND_TRY; ++i) { int prev = a->score; aw[0] = opt->w << i; if (bwa_verbose >= 4) { int j; printf("*** Left ref: "); for (j = 0; j < tmp; ++j) putchar("ACGTN"[(int)rs[j]]); putchar('\n'); printf("*** Left query: "); for (j = 0; j < s->qbeg; ++j) putchar("ACGTN"[(int)qs[j]]); putchar('\n'); } a->score = ksw_extend2(l_query, query, rmax[1] - rmax[0], rseq, 5, opt->mat, opt->o_del, opt->e_del, opt->o_ins, opt->e_ins, aw[0], opt->pen_clip5, opt->zdrop, s->len * opt->as->score, &qle, &tle, &gtle, &gscore, &max_off[0]); if (bwa_verbose >= 4) { printf("*** Left extension: prev_score=%d; score=%d; bandwidth=%d; max_off_diagonal_dist=%d\n", prev, a->score, aw[0], max_off[0]); fflush(stdout); } if (a->score == prev || max_off[0] < (aw[0]>>1) + (aw[0]>>2)) break; } // check whether we prefer to reach the end of the query if (gscore <= 0 || gscore <= a->score - opt->pen_clip5) { // local extension a->qb = qle, a->rb = rmax[0] + tle; a->qe = qe + qle, a->re = rmax[0] + re + tle; a->truesc = a->score; } else { // to-end extension a->qb = 0, a->rb = s->rbeg - gtle; a->qe = l_query, a->re = rmax[0] + re + gtle; a->truesc = gscore; } free(qs); free(rs); }*/ //else{ // if (opt->dp_type == 1) { //global alignment // if (s->len != l_query) { // uint8_t *rs; // int rbeg, rend, rseq_beg, rseq_end; // rseq_beg = s->rbeg - (s->qbeg + cal_max_gap(opt, s->qbeg)) - rmax[0]; // rseq_end = s->rbeg + s->len + ((l_query - s->qbeg - s->len) + cal_max_gap(opt, l_query - s->qbeg - s->len)) - rmax[0]; // rseq_beg = rseq_beg > 0 ? rseq_beg : 0; // rseq_end = rseq_end < (rmax[1] - rmax[0]) ? rseq_end : (rmax[1] - rmax[0]); // rs = malloc(rseq_end - rseq_beg); // int j; // for (i = rseq_beg, j = 0; i < rseq_end; ++i, ++j) { // rs[j] = rseq[i]; // } // a->score = ksw_global_ext(l_query, query, rseq_end - rseq_beg, rs, 5, opt->mat, opt->o_del, opt->e_del, opt->o_ins, opt->e_ins, &rbeg, // &rend); // // a->qb = 0, a->qe = l_query, a->rb = rbeg + rseq_beg + rmax[0], a->re = rend + rseq_beg + rmax[0] + 1, a->truesc = a->score; // assert(a->re > a->rb); // if (bwa_verbose >= 4) { // int j; // printf("*** Ref: "); // for (j = rbeg; j <= rend; ++j) // putchar("ACGTN"[(int) rs[j]]); // putchar('\n'); // printf("*** Query: "); // for (j = 0; j < l_query; ++j) // putchar("ACGTN"[(int) query[j]]); // putchar('\n'); // } // free(rs); // // } else { // a->score = a->truesc = s->score, a->qb = 0, a->rb = s->rbeg, a->qe = l_query, a->re = s->rbeg + s->len; // } // // } else if (opt->dp_type == 2) { // if (s->len != l_query) { // uint8_t *rs; // kswr_t x; // x.score = -1, x.te = -1, x.qe = -1, x.qb = -1, x.tb = -1, x.score2 = -1, x.te2 = -1; // int rbeg, rend, qbeg, qend, rseq_beg, rseq_end; // rseq_beg = s->rbeg - (s->qbeg + cal_max_gap(opt, s->qbeg)) - rmax[0]; // rseq_end = s->rbeg + s->len + ((l_query - s->qbeg - s->len) + cal_max_gap(opt, l_query - s->qbeg - s->len)) - rmax[0]; // rseq_beg = rseq_beg > 0 ? rseq_beg : 0; // rseq_end = rseq_end < (rmax[1] - rmax[0]) ? rseq_end : (rmax[1] - rmax[0]); // rs = malloc(rseq_end - rseq_beg); // int j; // for (i = rseq_beg, j = 0; i < rseq_end; ++i, ++j) { // rs[j] = rseq[i]; // } // if (opt->opt_ext) { // x = ksw_align2(l_query, query, rseq_end - rseq_beg, rs, 5, opt->mat, opt->o_del, opt->e_del, opt->o_ins, opt->e_ins, KSW_XSTART, 0, // opt->use_avx2); // if (x.score != -1 && x.te != -1 && x.qe != -1 && x.qb != -1 && x.tb != -1) { // a->score = x.score, a->qb = x.qb, a->qe = x.qe + 1, a->rb = x.tb + rseq_beg + rmax[0], a->re = x.te + rseq_beg + rmax[0] + 1, a->truesc = // x.score; // } else { // fprintf(stderr, "SIMD implementation not working\n"); // exit(EXIT_FAILURE); // } // } else { // a->score = ksw_local_ext(l_query, query, rseq_end - rseq_beg, rs, 5, opt->mat, opt->o_del, opt->e_del, opt->o_ins, opt->e_ins, 0, // &rbeg, &rend, &qbeg, &qend); // a->qb = qbeg, a->qe = qend + 1, a->rb = rbeg + rseq_beg + rmax[0], a->re = rend + rseq_beg + rmax[0] + 1, a->truesc = a->score; // } // assert(a->re > a->rb); // if (bwa_verbose >= 4) { // int j; // printf("*** Ref: "); // for (j = rbeg; j <= rend; ++j) // putchar("ACGTN"[(int) rs[j]]); // putchar('\n'); // printf("*** Query: "); // for (j = 0; j < l_query; ++j) // putchar("ACGTN"[(int) query[j]]); // putchar('\n'); // } // free(rs); // // } else { // a->score = a->truesc = s->score, a->qb = 0, a->rb = s->rbeg, a->qe = l_query, a->re = s->rbeg + s->len; // } // // } else { // if (s->qbeg) { // left extension // uint8_t *rs, *qs; // int qle, tle, gtle, gscore; // qs = malloc(s->qbeg); // for (i = 0; i < s->qbeg; ++i) // qs[i] = query[s->qbeg - 1 - i]; // /*int rseq_beg, rseq_end; // rseq_beg = s->rbeg - (s->qbeg + cal_max_gap(opt, s->qbeg)) - rmax[0]; // rseq_end = s->rbeg - rmax[0]; // rseq_beg = rseq_beg > 0 ? rseq_beg : 0; // rseq_end = rseq_end < (rmax[1] - rmax[0]) ? rseq_end : (rmax[1] - rmax[0]); // rs = malloc(rseq_end - rseq_beg); // int j; // for (i = 0; i < rseq_end - rseq_beg; ++i) { // rs[i] = rseq[rseq_end - 1 - i]; // }*/ // tmp = s->rbeg - rmax[0]; // rs = malloc(tmp); // for (i = 0; i < tmp; ++i) // rs[i] = rseq[tmp - 1 - i]; // for (i = 0; i < (opt->opt_ext ? MAX_BAND_TRY : 1); ++i) { // int prev = a->score; // aw[0] = opt->w << i; // if (bwa_verbose >= 4) { // int j; // printf("*** Left ref: "); // for (j = 0; j < tmp; ++j) // putchar("ACGTN"[(int) rs[j]]); // putchar('\n'); // printf("*** Left query: "); // for (j = 0; j < s->qbeg; ++j) // putchar("ACGTN"[(int) qs[j]]); // putchar('\n'); // } // a->score = ksw_extend2(s->qbeg, qs, tmp, rs, 5, opt->mat, opt->o_del, opt->e_del, opt->o_ins, opt->e_ins, aw[0], opt->pen_clip5, // opt->zdrop, /*s->len * opt->a*/s->score, &qle, &tle, &gtle, &gscore, &max_off[0], opt->opt_ext); // //a->score = ksw_extend2(s->qbeg, qs, rseq_end - rseq_beg, rs, 5, opt->mat, opt->o_del, opt->e_del, opt->o_ins, opt->e_ins, aw[0], // // opt->pen_clip5, opt->zdrop, /*s->len * opt->a*/ // // s->score, &qle, &tle, &gtle, &gscore, &max_off[0], opt->opt_ext); // if (bwa_verbose >= 4) { // printf("*** Left extension: prev_score=%d; score=%d; bandwidth=%d; max_off_diagonal_dist=%d\n", prev, a->score, aw[0], max_off[0]); // fflush(stdout); // } // if (a->score == prev || max_off[0] < (aw[0] >> 1) + (aw[0] >> 2)) // break; // } // // check whether we prefer to reach the end of the query // if (gscore <= 0 || gscore <= a->score - opt->pen_clip5) { // local extension // a->qb = s->qbeg - qle, a->rb = s->rbeg - tle; // a->truesc = a->score; // } else { // to-end extension // a->qb = 0, a->rb = s->rbeg - gtle; // a->truesc = gscore; // } // free(qs); // free(rs); // } else // a->score = a->truesc = s->score/*s->len * opt->a*/, a->qb = 0, a->rb = s->rbeg; // // if (s->qbeg + s->len != l_query) { // right extension // int qle, tle, qe, re, gtle, gscore, sc0 = a->score; // qe = s->qbeg + s->len; // re = s->rbeg + s->len - rmax[0]; // assert(re >= 0); // //uint8_t *rs; // /*int rseq_beg, rseq_end; // rseq_beg = s->rbeg + s->len - rmax[0]; // rseq_end = s->rbeg + s->len + ((l_query - s->qbeg - s->len) + cal_max_gap(opt, l_query - s->qbeg - s->len)) - rmax[0]; // rseq_beg = rseq_beg > 0 ? rseq_beg : 0; // rseq_end = rseq_end < (rmax[1] - rmax[0]) ? rseq_end : (rmax[1] - rmax[0]); // rs = malloc(rseq_end - rseq_beg); // int j; // for (i = rseq_beg, j = 0; i < rseq_end; ++i, ++j) { // rs[j] = rseq[i]; // }*/ // for (i = 0; i < (opt->opt_ext ? MAX_BAND_TRY : 1); ++i) { // int prev = a->score; // aw[1] = opt->w << i; // if (bwa_verbose >= 4) { // int j; // printf("*** Right ref: "); // for (j = 0; j < rmax[1] - rmax[0] - re; ++j) // putchar("ACGTN"[(int) rseq[re + j]]); // putchar('\n'); // printf("*** Right query: "); // for (j = 0; j < l_query - qe; ++j) // putchar("ACGTN"[(int) query[qe + j]]); // putchar('\n'); // } // a->score = ksw_extend2(l_query - qe, query + qe, rmax[1] - rmax[0] - re, rseq + re, 5, opt->mat, opt->o_del, opt->e_del, opt->o_ins, // opt->e_ins, aw[1], opt->pen_clip3, opt->zdrop, sc0, &qle, &tle, &gtle, &gscore, &max_off[1], opt->opt_ext); // //a->score = ksw_extend2(l_query - qe, query + qe, rseq_end - rseq_beg, rs, 5, opt->mat, opt->o_del, opt->e_del, opt->o_ins, opt->e_ins, // // aw[1], opt->pen_clip3, opt->zdrop, sc0, &qle, &tle, &gtle, &gscore, &max_off[1], opt->opt_ext); // if (bwa_verbose >= 4) { // printf("*** Right extension: prev_score=%d; score=%d; bandwidth=%d; max_off_diagonal_dist=%d\n", prev, a->score, aw[1], max_off[1]); // fflush(stdout); // } // if (a->score == prev || max_off[1] < (aw[1] >> 1) + (aw[1] >> 2)) // break; // } // // similar to the above // if (gscore <= 0 || gscore <= a->score - opt->pen_clip3) { // local extension // a->qe = qe + qle; // a->re = rmax[0] + re + tle; // //a->re = rmax[0] + rseq_beg + tle; // a->truesc += a->score - sc0; // } else { // to-end extension // a->qe = l_query; // a->re = rmax[0] + re + gtle; // //a->re = rmax[0] + rseq_beg + gtle; // a->truesc += gscore - sc0; // } // //free(rs); // } else // a->qe = l_query, a->re = s->rbeg + s->len; // } // if (bwa_verbose >= 4) // printf("*** Added alignment region: [%d,%d) <=> [%ld,%ld); score=%d; {left,right}_bandwidth={%d,%d}\n", a->qb, a->qe, (long) a->rb, // (long) a->re, a->score, aw[0], aw[1]); // // // compute seedcov for (i = 0, a->seedcov = 0; i < c->n; ++i) { const mem_seed_t *t = &c->seeds[i]; if (t->qbeg >= a->qb && t->qbeg + t->len <= a->qe && t->rbeg >= a->rb && t->rbeg + t->len <= a->re) // seed fully contained a->seedcov += t->len; // this is not very accurate, but for approx. mapQ, this is good enough } a->w = aw[0] > aw[1] ? aw[0] : aw[1]; a->seedlen0 = s->len; a->frac_rep = c->frac_rep; } free(srt); } //void mem_chain2aln(const mem_opt_t *opt, const bntseq_t *bns, const uint8_t *pac, int l_query, const uint8_t *query, const mem_chain_t *c, mem_alnreg_v *av, seq_lens *read_seq_lens, seq_offsets *read_seq_offsets, int *curr_read_offset, seq_batch *ref_seq_batch, seq_lens *ref_seq_lens, seq_offsets *ref_seq_offsets, int *curr_ref_offset) //{ // int i, k; // uint64_t *srt; // if (c->n == 0) return; // //extern uint64_t *no_of_extensions; // // get the max possible span // /*rmax[0] = l_pac<<1; rmax[1] = 0; // for (i = 0; i < c->n; ++i) { // int64_t b, e; // const mem_seed_t *t = &c->seeds[i]; // b = t->rbeg - (t->qbeg + cal_max_gap(opt, t->qbeg)); // e = t->rbeg + t->len + ((l_query - t->qbeg - t->len) + cal_max_gap(opt, l_query - t->qbeg - t->len)); // rmax[0] = rmax[0] < b? rmax[0] : b; // rmax[1] = rmax[1] > e? rmax[1] : e; // if (t->len > max) max = t->len; // } // rmax[0] = rmax[0] > 0? rmax[0] : 0; // rmax[1] = rmax[1] < l_pac<<1? rmax[1] : l_pac<<1; // if (rmax[0] < l_pac && l_pac < rmax[1]) { // crossing the forward-reverse boundary; then choose one side // if (c->seeds[0].rbeg < l_pac) rmax[1] = l_pac; // this works because all seeds are guaranteed to be on the same strand // else rmax[0] = l_pac; // } // // retrieve the reference sequence // rseq = bns_fetch_seq(bns, pac, &rmax[0], c->seeds[0].rbeg, &rmax[1], &rid); // assert(c->rid == rid);*/ // // srt = malloc(c->n * 8); // for (i = 0; i < c->n; ++i) // srt[i] = (uint64_t)c->seeds[i].score<<32 | i; // ks_introsort_64(c->n, srt); // // for (k = c->n - 1; k >= 0; --k) { // mem_alnreg_t *a; // int64_t l_pac = bns->l_pac, tmp, max = 0; // const mem_seed_t *s; // s = &c->seeds[(uint32_t)srt[k]]; // int max_off[2], aw[2]; // for (i = 0; i < av->n; ++i) { // test whether extension has been made before // mem_alnreg_t *p = &av->a[i]; // int64_t rd; // int qd, w, max_gap; // if (s->rbeg < p->rb_est || s->rbeg + s->len > p->re_est || s->qbeg < p->qb_est || s->qbeg + s->len > p->qe_est) continue; // not fully contained // if (s->len - p->seedlen0 > .1 * l_query) continue; // this seed may give a better alignment // // qd: distance ahead of the seed on query; rd: on reference // qd = s->qbeg - p->qb_est; rd = s->rbeg - p->rb_est; // max_gap = cal_max_gap(opt, qd < rd? qd : rd); // the maximal gap allowed in regions ahead of the seed // w = max_gap < p->w? max_gap : p->w; // bounded by the band width // if (qd - rd < w && rd - qd < w) break; // the seed is "around" a previous hit // // similar to the previous four lines, but this time we look at the region behind // qd = p->qe_est - (s->qbeg + s->len); rd = p->re_est - (s->rbeg + s->len); // max_gap = cal_max_gap(opt, qd < rd? qd : rd); // w = max_gap < p->w? max_gap : p->w; // if (qd - rd < w && rd - qd < w) break; // } // if (i < av->n) { // the seed is (almost) contained in an existing alignment; further testing is needed to confirm it is not leading to a different aln // if (bwa_verbose >= 4) // printf("** Seed(%d) [%ld;%ld,%ld] is almost contained in an existing alignment [%d,%d) <=> [%ld,%ld)\n", // k, (long)s->len, (long)s->qbeg, (long)s->rbeg, av->a[i].qb, av->a[i].qe, (long)av->a[i].rb, (long)av->a[i].re); // for (i = k + 1; i < c->n; ++i) { // check overlapping seeds in the same chain // const mem_seed_t *t; // if (srt[i] == 0) continue; // t = &c->seeds[(uint32_t)srt[i]]; // if (t->len < s->len * .95) continue; // only check overlapping if t is long enough; TODO: more efficient by early stopping // if (s->qbeg <= t->qbeg && s->qbeg + s->len - t->qbeg >= s->len>>2 && t->qbeg - s->qbeg != t->rbeg - s->rbeg) break; // if (t->qbeg <= s->qbeg && t->qbeg + t->len - s->qbeg >= s->len>>2 && s->qbeg - t->qbeg != s->rbeg - t->rbeg) break; // } // if (i == c->n) { // no overlapping seeds; then skip extension // srt[k] = 0; // mark that seed extension has not been performed // continue; // } // if (bwa_verbose >= 4) // printf("** Seed(%d) might lead to a different alignment even though it is contained. Extension will be performed.\n", k); // } // // a = kv_pushp(mem_alnreg_t, *av); // memset(a, 0, sizeof(mem_alnreg_t)); // a->w = aw[0] = aw[1] = opt->w; // a->score = a->truesc = -1; // a->rid = c->rid; // int fwd = 0.85*(l_query - (s->qbeg + s->len)); // a->qe_est = ((s->qbeg + s->len) + fwd) < l_query ? ((s->qbeg + s->len) + fwd) : l_query; // a->re_est = ((s->rbeg + s->len) + fwd) < l_pac << 1 ? ((s->rbeg + s->len) + fwd) : l_pac << 1; // int back = 0.85*(s->qbeg + 1); // a->qb_est = (s->qbeg - back) > 0 ? (s->qbeg - back) : 0; // a->rb_est = (s->rbeg - back) > 0 ? (s->rbeg - back) : 0; // if (a->rb_est < l_pac && l_pac < a->qe_est) { // crossing the forward-reverse boundary; then choose one side // if (s->rbeg < l_pac) // a->re_est = l_pac; // this works because all seeds are guaranteed to be on the same strand // else // a->rb_est = l_pac; // } //// rmax[0] = l_pac<<1; rmax[1] = 0; //// rmax[0] = s->rbeg - (s->qbeg + cal_max_gap(opt, s->qbeg)); //// rmax[1] = s->rbeg + s->len + ((l_query - s->qbeg - s->len) + cal_max_gap(opt, l_query - s->qbeg - s->len)); //// if (s->len > max) max = s->len; //// rmax[0] = rmax[0] > 0? rmax[0] : 0; //// rmax[1] = rmax[1] < l_pac<<1? rmax[1] : l_pac<<1; //// if (rmax[0] < l_pac && l_pac < rmax[1]) { // crossing the forward-reverse boundary; then choose one side //// if (s->rbeg < l_pac) rmax[1] = l_pac; // this works because all seeds are guaranteed to be on the same strand //// else rmax[0] = l_pac; //// } //// // retrieve the reference sequence //// rseq = bns_fetch_seq(bns, pac, &rmax[0], s->rbeg, &rmax[1], &rid); //// assert(c->rid == rid); // if(s->len != l_query) { // int64_t rmax[2]; // uint8_t *rseq = 0; // int rid; // rmax[0] = l_pac<<1; rmax[1] = 0; // rmax[0] = s->rbeg - (s->qbeg + cal_max_gap(opt, s->qbeg)); // rmax[1] = s->rbeg + s->len + ((l_query - s->qbeg - s->len) + cal_max_gap(opt, l_query - s->qbeg - s->len)); // rmax[0] = rmax[0] > 0? rmax[0] : 0; // rmax[1] = rmax[1] < l_pac<<1? rmax[1] : l_pac<<1; // if (rmax[0] < l_pac && l_pac < rmax[1]) { // crossing the forward-reverse boundary; then choose one side // if (s->rbeg < l_pac) rmax[1] = l_pac; // this works because all seeds are guaranteed to be on the same strand // else rmax[0] = l_pac; // } // // retrieve the reference sequence // rseq = bns_fetch_seq(bns, pac, &rmax[0], s->rbeg, &rmax[1], &rid); // assert(c->rid == rid); // /*int rseq_beg, rseq_end; // rseq_beg = s->rbeg - (s->qbeg + cal_max_gap(opt, s->qbeg)) - rmax[0]; // rseq_end = s->rbeg + s->len + ((l_query - s->qbeg - s->len) + cal_max_gap(opt, l_query - s->qbeg - s->len)) - rmax[0]; // rseq_beg = rseq_beg > 0 ? rseq_beg : 0; // rseq_end = rseq_end < (rmax[1] - rmax[0]) ? rseq_end : (rmax[1] - rmax[0]);*/ // //uint8_t* rs = malloc(rseq_end - rseq_beg); // int ref_l_seq_with_p = ((rmax[1] - rmax[0])%8) ? (rmax[1] - rmax[0]) + (8 - ((rmax[1] - rmax[0])%8)) : (rmax[1] - rmax[0]) ; // int j; // for (i = 0, j = 0; i < (rmax[1] - rmax[0]) && j < MAX_BATCH2_LEN; ++i, ++j) { // //rs[j] = rseq[i]; // kv_push(uint8_t, *ref_seq_batch, rseq[i]); // } // int ref_l_seq = rmax[1] - rmax[0]; // while (ref_l_seq < ref_l_seq_with_p) { // kv_push(uint8_t, *ref_seq_batch, 0); // ref_l_seq++; // } // a->rseq_beg = rmax[0] /*+ rseq_beg*/; // if (bwa_verbose >= 4) // err_printf("** ---> Extending from seed(%d) [%ld;%ld,%ld] @ %s <---\n", k, (long) s->len, (long) s->qbeg, (long) s->rbeg, // bns->anns[c->rid].name); // //kv_push(uint8_t*, *read_seqns, query); // //kv_push(uint8_t*, *ref_seqns, rs); // //kv_push(int, *read_seq_lens, l_query); // kv_push(int, *read_seq_lens, l_query); // kv_push(int, *read_seq_offsets, *curr_read_offset); // kv_push(int, *ref_seq_lens, (rmax[1] - rmax[0])); // kv_push(int, *ref_seq_offsets, *curr_ref_offset); // *curr_ref_offset += ref_l_seq_with_p; // free(rseq); // } // else { // a->score = a->truesc = s->score, a->qb = 0, a->rb = s->rbeg, a->qe = l_query, a->re = s->rbeg + s->len; // } // //kv_push(int, *read_idx_vec, read_idx); // /*if(opt->seed_type == 2) { // uint8_t *rs, *qs; // int qle, tle, gtle, gscore; // int qe = s->qbeg + s->len; // int re = s->rbeg + s->len - rmax[0]; // // qs = malloc(s->qbeg); // //for (i = 0; i < s->qbeg; ++i) qs[i] = query[s->qbeg - 1 - i]; // //tmp = s->rbeg - rmax[0]; // //rs = malloc(tmp); // //for (i = 0; i < tmp; ++i) rs[i] = rseq[tmp - 1 - i]; // for (i = 0; i < MAX_BAND_TRY; ++i) { // int prev = a->score; // aw[0] = opt->w << i; // if (bwa_verbose >= 4) { // int j; // printf("*** Left ref: "); for (j = 0; j < tmp; ++j) putchar("ACGTN"[(int)rs[j]]); putchar('\n'); // printf("*** Left query: "); for (j = 0; j < s->qbeg; ++j) putchar("ACGTN"[(int)qs[j]]); putchar('\n'); // } // a->score = ksw_extend2(l_query, query, rmax[1] - rmax[0], rseq, 5, opt->mat, opt->o_del, opt->e_del, opt->o_ins, opt->e_ins, aw[0], opt->pen_clip5, opt->zdrop, s->len * opt->as->score, &qle, &tle, &gtle, &gscore, &max_off[0]); // if (bwa_verbose >= 4) { printf("*** Left extension: prev_score=%d; score=%d; bandwidth=%d; max_off_diagonal_dist=%d\n", prev, a->score, aw[0], max_off[0]); fflush(stdout); } // if (a->score == prev || max_off[0] < (aw[0]>>1) + (aw[0]>>2)) break; // } // // check whether we prefer to reach the end of the query // if (gscore <= 0 || gscore <= a->score - opt->pen_clip5) { // local extension // a->qb = qle, a->rb = rmax[0] + tle; // a->qe = qe + qle, a->re = rmax[0] + re + tle; // a->truesc = a->score; // } else { // to-end extension // a->qb = 0, a->rb = s->rbeg - gtle; // a->qe = l_query, a->re = rmax[0] + re + gtle; // a->truesc = gscore; // } // free(qs); free(rs); // }*/ // //else{ //// if (opt->dp_type == 1) { //global alignment //// if (s->len != l_query) { //// uint8_t *rs; //// int rbeg, rend, rseq_beg, rseq_end; //// rseq_beg = s->rbeg - (s->qbeg + cal_max_gap(opt, s->qbeg)) - rmax[0]; //// rseq_end = s->rbeg + s->len + ((l_query - s->qbeg - s->len) + cal_max_gap(opt, l_query - s->qbeg - s->len)) - rmax[0]; //// rseq_beg = rseq_beg > 0 ? rseq_beg : 0; //// rseq_end = rseq_end < (rmax[1] - rmax[0]) ? rseq_end : (rmax[1] - rmax[0]); //// rs = malloc(rseq_end - rseq_beg); //// int j; //// for (i = rseq_beg, j = 0; i < rseq_end; ++i, ++j) { //// rs[j] = rseq[i]; //// } //// a->score = ksw_global_ext(l_query, query, rseq_end - rseq_beg, rs, 5, opt->mat, opt->o_del, opt->e_del, opt->o_ins, opt->e_ins, &rbeg, //// &rend); //// //// a->qb = 0, a->qe = l_query, a->rb = rbeg + rseq_beg + rmax[0], a->re = rend + rseq_beg + rmax[0] + 1, a->truesc = a->score; //// assert(a->re > a->rb); //// if (bwa_verbose >= 4) { //// int j; //// printf("*** Ref: "); //// for (j = rbeg; j <= rend; ++j) //// putchar("ACGTN"[(int) rs[j]]); //// putchar('\n'); //// printf("*** Query: "); //// for (j = 0; j < l_query; ++j) //// putchar("ACGTN"[(int) query[j]]); //// putchar('\n'); //// } //// free(rs); //// //// } else { //// a->score = a->truesc = s->score, a->qb = 0, a->rb = s->rbeg, a->qe = l_query, a->re = s->rbeg + s->len; //// } //// //// } else if (opt->dp_type == 2) { //// if (s->len != l_query) { //// uint8_t *rs; //// kswr_t x; //// x.score = -1, x.te = -1, x.qe = -1, x.qb = -1, x.tb = -1, x.score2 = -1, x.te2 = -1; //// int rbeg, rend, qbeg, qend, rseq_beg, rseq_end; //// rseq_beg = s->rbeg - (s->qbeg + cal_max_gap(opt, s->qbeg)) - rmax[0]; //// rseq_end = s->rbeg + s->len + ((l_query - s->qbeg - s->len) + cal_max_gap(opt, l_query - s->qbeg - s->len)) - rmax[0]; //// rseq_beg = rseq_beg > 0 ? rseq_beg : 0; //// rseq_end = rseq_end < (rmax[1] - rmax[0]) ? rseq_end : (rmax[1] - rmax[0]); //// rs = malloc(rseq_end - rseq_beg); //// int j; //// for (i = rseq_beg, j = 0; i < rseq_end; ++i, ++j) { //// rs[j] = rseq[i]; //// } //// if (opt->opt_ext) { //// x = ksw_align2(l_query, query, rseq_end - rseq_beg, rs, 5, opt->mat, opt->o_del, opt->e_del, opt->o_ins, opt->e_ins, KSW_XSTART, 0, //// opt->use_avx2); //// if (x.score != -1 && x.te != -1 && x.qe != -1 && x.qb != -1 && x.tb != -1) { //// a->score = x.score, a->qb = x.qb, a->qe = x.qe + 1, a->rb = x.tb + rseq_beg + rmax[0], a->re = x.te + rseq_beg + rmax[0] + 1, a->truesc = //// x.score; //// } else { //// fprintf(stderr, "SIMD implementation not working\n"); //// exit(EXIT_FAILURE); //// } //// } else { //// a->score = ksw_local_ext(l_query, query, rseq_end - rseq_beg, rs, 5, opt->mat, opt->o_del, opt->e_del, opt->o_ins, opt->e_ins, 0, //// &rbeg, &rend, &qbeg, &qend); //// a->qb = qbeg, a->qe = qend + 1, a->rb = rbeg + rseq_beg + rmax[0], a->re = rend + rseq_beg + rmax[0] + 1, a->truesc = a->score; //// } //// assert(a->re > a->rb); //// if (bwa_verbose >= 4) { //// int j; //// printf("*** Ref: "); //// for (j = rbeg; j <= rend; ++j) //// putchar("ACGTN"[(int) rs[j]]); //// putchar('\n'); //// printf("*** Query: "); //// for (j = 0; j < l_query; ++j) //// putchar("ACGTN"[(int) query[j]]); //// putchar('\n'); //// } //// free(rs); //// //// } else { //// a->score = a->truesc = s->score, a->qb = 0, a->rb = s->rbeg, a->qe = l_query, a->re = s->rbeg + s->len; //// } //// //// } else { //// if (s->qbeg) { // left extension //// uint8_t *rs, *qs; //// int qle, tle, gtle, gscore; //// qs = malloc(s->qbeg); //// for (i = 0; i < s->qbeg; ++i) //// qs[i] = query[s->qbeg - 1 - i]; //// /*int rseq_beg, rseq_end; //// rseq_beg = s->rbeg - (s->qbeg + cal_max_gap(opt, s->qbeg)) - rmax[0]; //// rseq_end = s->rbeg - rmax[0]; //// rseq_beg = rseq_beg > 0 ? rseq_beg : 0; //// rseq_end = rseq_end < (rmax[1] - rmax[0]) ? rseq_end : (rmax[1] - rmax[0]); //// rs = malloc(rseq_end - rseq_beg); //// int j; //// for (i = 0; i < rseq_end - rseq_beg; ++i) { //// rs[i] = rseq[rseq_end - 1 - i]; //// }*/ //// tmp = s->rbeg - rmax[0]; //// rs = malloc(tmp); //// for (i = 0; i < tmp; ++i) //// rs[i] = rseq[tmp - 1 - i]; //// for (i = 0; i < (opt->opt_ext ? MAX_BAND_TRY : 1); ++i) { //// int prev = a->score; //// aw[0] = opt->w << i; //// if (bwa_verbose >= 4) { //// int j; //// printf("*** Left ref: "); //// for (j = 0; j < tmp; ++j) //// putchar("ACGTN"[(int) rs[j]]); //// putchar('\n'); //// printf("*** Left query: "); //// for (j = 0; j < s->qbeg; ++j) //// putchar("ACGTN"[(int) qs[j]]); //// putchar('\n'); //// } //// a->score = ksw_extend2(s->qbeg, qs, tmp, rs, 5, opt->mat, opt->o_del, opt->e_del, opt->o_ins, opt->e_ins, aw[0], opt->pen_clip5, //// opt->zdrop, /*s->len * opt->a*/s->score, &qle, &tle, &gtle, &gscore, &max_off[0], opt->opt_ext); //// //a->score = ksw_extend2(s->qbeg, qs, rseq_end - rseq_beg, rs, 5, opt->mat, opt->o_del, opt->e_del, opt->o_ins, opt->e_ins, aw[0], //// // opt->pen_clip5, opt->zdrop, /*s->len * opt->a*/ //// // s->score, &qle, &tle, &gtle, &gscore, &max_off[0], opt->opt_ext); //// if (bwa_verbose >= 4) { //// printf("*** Left extension: prev_score=%d; score=%d; bandwidth=%d; max_off_diagonal_dist=%d\n", prev, a->score, aw[0], max_off[0]); //// fflush(stdout); //// } //// if (a->score == prev || max_off[0] < (aw[0] >> 1) + (aw[0] >> 2)) //// break; //// } //// // check whether we prefer to reach the end of the query //// if (gscore <= 0 || gscore <= a->score - opt->pen_clip5) { // local extension //// a->qb = s->qbeg - qle, a->rb = s->rbeg - tle; //// a->truesc = a->score; //// } else { // to-end extension //// a->qb = 0, a->rb = s->rbeg - gtle; //// a->truesc = gscore; //// } //// free(qs); //// free(rs); //// } else //// a->score = a->truesc = s->score/*s->len * opt->a*/, a->qb = 0, a->rb = s->rbeg; //// //// if (s->qbeg + s->len != l_query) { // right extension //// int qle, tle, qe, re, gtle, gscore, sc0 = a->score; //// qe = s->qbeg + s->len; //// re = s->rbeg + s->len - rmax[0]; //// assert(re >= 0); //// //uint8_t *rs; //// /*int rseq_beg, rseq_end; //// rseq_beg = s->rbeg + s->len - rmax[0]; //// rseq_end = s->rbeg + s->len + ((l_query - s->qbeg - s->len) + cal_max_gap(opt, l_query - s->qbeg - s->len)) - rmax[0]; //// rseq_beg = rseq_beg > 0 ? rseq_beg : 0; //// rseq_end = rseq_end < (rmax[1] - rmax[0]) ? rseq_end : (rmax[1] - rmax[0]); //// rs = malloc(rseq_end - rseq_beg); //// int j; //// for (i = rseq_beg, j = 0; i < rseq_end; ++i, ++j) { //// rs[j] = rseq[i]; //// }*/ //// for (i = 0; i < (opt->opt_ext ? MAX_BAND_TRY : 1); ++i) { //// int prev = a->score; //// aw[1] = opt->w << i; //// if (bwa_verbose >= 4) { //// int j; //// printf("*** Right ref: "); //// for (j = 0; j < rmax[1] - rmax[0] - re; ++j) //// putchar("ACGTN"[(int) rseq[re + j]]); //// putchar('\n'); //// printf("*** Right query: "); //// for (j = 0; j < l_query - qe; ++j) //// putchar("ACGTN"[(int) query[qe + j]]); //// putchar('\n'); //// } //// a->score = ksw_extend2(l_query - qe, query + qe, rmax[1] - rmax[0] - re, rseq + re, 5, opt->mat, opt->o_del, opt->e_del, opt->o_ins, //// opt->e_ins, aw[1], opt->pen_clip3, opt->zdrop, sc0, &qle, &tle, &gtle, &gscore, &max_off[1], opt->opt_ext); //// //a->score = ksw_extend2(l_query - qe, query + qe, rseq_end - rseq_beg, rs, 5, opt->mat, opt->o_del, opt->e_del, opt->o_ins, opt->e_ins, //// // aw[1], opt->pen_clip3, opt->zdrop, sc0, &qle, &tle, &gtle, &gscore, &max_off[1], opt->opt_ext); //// if (bwa_verbose >= 4) { //// printf("*** Right extension: prev_score=%d; score=%d; bandwidth=%d; max_off_diagonal_dist=%d\n", prev, a->score, aw[1], max_off[1]); //// fflush(stdout); //// } //// if (a->score == prev || max_off[1] < (aw[1] >> 1) + (aw[1] >> 2)) //// break; //// } //// // similar to the above //// if (gscore <= 0 || gscore <= a->score - opt->pen_clip3) { // local extension //// a->qe = qe + qle; //// a->re = rmax[0] + re + tle; //// //a->re = rmax[0] + rseq_beg + tle; //// a->truesc += a->score - sc0; //// } else { // to-end extension //// a->qe = l_query; //// a->re = rmax[0] + re + gtle; //// //a->re = rmax[0] + rseq_beg + gtle; //// a->truesc += gscore - sc0; //// } //// //free(rs); //// } else //// a->qe = l_query, a->re = s->rbeg + s->len; //// } //// if (bwa_verbose >= 4) //// printf("*** Added alignment region: [%d,%d) <=> [%ld,%ld); score=%d; {left,right}_bandwidth={%d,%d}\n", a->qb, a->qe, (long) a->rb, //// (long) a->re, a->score, aw[0], aw[1]); //// //// // compute seedcov // for (i = 0, a->seedcov = 0; i < c->n; ++i) { // const mem_seed_t *t = &c->seeds[i]; // if (t->qbeg >= a->qb && t->qbeg + t->len <= a->qe && t->rbeg >= a->rb && t->rbeg + t->len <= a->re) // seed fully contained // a->seedcov += t->len; // this is not very accurate, but for approx. mapQ, this is good enough // } // a->w = aw[0] > aw[1] ? aw[0] : aw[1]; // a->seedlen0 = s->len; // // a->frac_rep = c->frac_rep; // } // free(srt); //} /***************************** * Basic hit->SAM conversion * *****************************/ static inline int infer_bw(int l1, int l2, int score, int a, int q, int r) { int w; if (l1 == l2 && l1 * a - score < (q + r - a) << 1) return 0; // to get equal alignment length, we need at least two gaps w = ((double) ((l1 < l2 ? l1 : l2) * a - score - q) / r + 2.); if (w < abs(l1 - l2)) w = abs(l1 - l2); return w; } static inline int get_rlen(int n_cigar, const uint32_t *cigar) { int k, l; for (k = l = 0; k < n_cigar; ++k) { int op = cigar[k] & 0xf; if (op == 0 || op == 2) l += cigar[k] >> 4; } return l; } void mem_aln2sam(const mem_opt_t *opt, const bntseq_t *bns, kstring_t *str, bseq1_t *s, int n, const mem_aln_t *list, int which, const mem_aln_t *m_) { int i, l_name; mem_aln_t ptmp = list[which], *p = &ptmp, mtmp, *m = 0; // make a copy of the alignment to convert if (m_) mtmp = *m_, m = &mtmp; // set flag p->flag |= m ? 0x1 : 0; // is paired in sequencing p->flag |= p->rid < 0 ? 0x4 : 0; // is mapped p->flag |= m && m->rid < 0 ? 0x8 : 0; // is mate mapped if (p->rid < 0 && m && m->rid >= 0) // copy mate to alignment p->rid = m->rid, p->pos = m->pos, p->is_rev = m->is_rev, p->n_cigar = 0; if (m && m->rid < 0 && p->rid >= 0) // copy alignment to mate m->rid = p->rid, m->pos = p->pos, m->is_rev = p->is_rev, m->n_cigar = 0; p->flag |= p->is_rev ? 0x10 : 0; // is on the reverse strand p->flag |= m && m->is_rev ? 0x20 : 0; // is mate on the reverse strand // print up to CIGAR l_name = strlen(s->name); ks_resize(str, str->l + s->l_seq + l_name + (s->qual ? s->l_seq : 0) + 20); kputsn(s->name, l_name, str); kputc('\t', str); // QNAME kputw((p->flag & 0xffff) | (p->flag & 0x10000 ? 0x100 : 0), str); kputc('\t', str); // FLAG if (p->rid >= 0) { // with coordinate kputs(bns->anns[p->rid].name, str); kputc('\t', str); // RNAME kputl(p->pos + 1, str); kputc('\t', str); // POS kputw(p->mapq, str); kputc('\t', str); // MAPQ if (p->n_cigar) { // aligned for (i = 0; i < p->n_cigar; ++i) { int c = p->cigar[i] & 0xf; if (!(opt->flag & MEM_F_SOFTCLIP) && !p->is_alt && (c == 3 || c == 4)) c = which ? 4 : 3; // use hard clipping for supplementary alignments kputw(p->cigar[i] >> 4, str); kputc("MIDSH"[c], str); } } else kputc('*', str); // having a coordinate but unaligned (e.g. when copy_mate is true) } else kputsn("*\t0\t0\t*", 7, str); // without coordinte kputc('\t', str); // print the mate position if applicable if (m && m->rid >= 0) { if (p->rid == m->rid) kputc('=', str); else kputs(bns->anns[m->rid].name, str); kputc('\t', str); kputl(m->pos + 1, str); kputc('\t', str); if (p->rid == m->rid) { int64_t p0 = p->pos + (p->is_rev ? get_rlen(p->n_cigar, p->cigar) - 1 : 0); int64_t p1 = m->pos + (m->is_rev ? get_rlen(m->n_cigar, m->cigar) - 1 : 0); if (m->n_cigar == 0 || p->n_cigar == 0) kputc('0', str); else kputl(-(p0 - p1 + (p0 > p1 ? 1 : p0 < p1 ? -1 : 0)), str); } else kputc('0', str); } else kputsn("*\t0\t0", 5, str); kputc('\t', str); // print SEQ and QUAL if (p->flag & 0x100) { // for secondary alignments, don't write SEQ and QUAL kputsn("*\t*", 3, str); } else if (!p->is_rev) { // the forward strand int i, qb = 0, qe = s->l_seq; if (p->n_cigar && which && !(opt->flag & MEM_F_SOFTCLIP) && !p->is_alt) { // have cigar && not the primary alignment && not softclip all if ((p->cigar[0] & 0xf) == 4 || (p->cigar[0] & 0xf) == 3) qb += p->cigar[0] >> 4; if ((p->cigar[p->n_cigar - 1] & 0xf) == 4 || (p->cigar[p->n_cigar - 1] & 0xf) == 3) qe -= p->cigar[p->n_cigar - 1] >> 4; } ks_resize(str, str->l + (qe - qb) + 1); for (i = qb; i < qe; ++i) str->s[str->l++] = "ACGTN"[(int) s->seq[i]]; kputc('\t', str); if (s->qual) { // printf qual ks_resize(str, str->l + (qe - qb) + 1); for (i = qb; i < qe; ++i) str->s[str->l++] = s->qual[i]; str->s[str->l] = 0; } else kputc('*', str); } else { // the reverse strand int i, qb = 0, qe = s->l_seq; if (p->n_cigar && which && !(opt->flag & MEM_F_SOFTCLIP) && !p->is_alt) { if ((p->cigar[0] & 0xf) == 4 || (p->cigar[0] & 0xf) == 3) qe -= p->cigar[0] >> 4; if ((p->cigar[p->n_cigar - 1] & 0xf) == 4 || (p->cigar[p->n_cigar - 1] & 0xf) == 3) qb += p->cigar[p->n_cigar - 1] >> 4; } ks_resize(str, str->l + (qe - qb) + 1); for (i = qe - 1; i >= qb; --i) str->s[str->l++] = "TGCAN"[(int) s->seq[i]]; kputc('\t', str); if (s->qual) { // printf qual ks_resize(str, str->l + (qe - qb) + 1); for (i = qe - 1; i >= qb; --i) str->s[str->l++] = s->qual[i]; str->s[str->l] = 0; } else kputc('*', str); } // print optional tags if (p->n_cigar) { kputsn("\tNM:i:", 6, str); kputw(p->NM, str); kputsn("\tMD:Z:", 6, str); kputs((char*) (p->cigar + p->n_cigar), str); } if (p->score >= 0) { kputsn("\tAS:i:", 6, str); kputw(p->score, str); } if (p->sub >= 0) { kputsn("\tXS:i:", 6, str); kputw(p->sub, str); } if (bwa_rg_id[0]) { kputsn("\tRG:Z:", 6, str); kputs(bwa_rg_id, str); } if (!(p->flag & 0x100)) { // not multi-hit for (i = 0; i < n; ++i) if (i != which && !(list[i].flag & 0x100)) break; if (i < n) { // there are other primary hits; output them kputsn("\tSA:Z:", 6, str); for (i = 0; i < n; ++i) { const mem_aln_t *r = &list[i]; int k; if (i == which || (r->flag & 0x100)) continue; // proceed if: 1) different from the current; 2) not shadowed multi hit kputs(bns->anns[r->rid].name, str); kputc(',', str); kputl(r->pos + 1, str); kputc(',', str); kputc("+-"[r->is_rev], str); kputc(',', str); for (k = 0; k < r->n_cigar; ++k) { kputw(r->cigar[k] >> 4, str); kputc("MIDSH"[r->cigar[k] & 0xf], str); } kputc(',', str); kputw(r->mapq, str); kputc(',', str); kputw(r->NM, str); kputc(';', str); } } if (p->alt_sc > 0) ksprintf(str, "\tpa:f:%.3f", (double) p->score / p->alt_sc); } if (p->XA) { kputsn("\tXA:Z:", 6, str); kputs(p->XA, str); } if (s->comment) { kputc('\t', str); kputs(s->comment, str); } if ((opt->flag & MEM_F_REF_HDR) && p->rid >= 0 && bns->anns[p->rid].anno != 0 && bns->anns[p->rid].anno[0] != 0) { int tmp; kputsn("\tXR:Z:", 6, str); tmp = str->l; kputs(bns->anns[p->rid].anno, str); for (i = tmp; i < str->l; ++i) // replace TAB in the comment to SPACE if (str->s[i] == '\t') str->s[i] = ' '; } kputc('\n', str); } /************************ * Integrated interface * ************************/ int mem_approx_mapq_se(const mem_opt_t *opt, const mem_alnreg_t *a) { int mapq, l, sub = a->sub ? a->sub : opt->min_seed_len * opt->a; double identity; sub = a->csub > sub ? a->csub : sub; if (sub >= a->score) return 0; l = a->qe - a->qb > a->re - a->rb ? a->qe - a->qb : a->re - a->rb; identity = 1. - (double) (l * opt->a - a->score) / (opt->a + opt->b) / l; if (a->score == 0) { mapq = 0; } else if (opt->mapQ_coef_len > 0) { double tmp; tmp = l < opt->mapQ_coef_len ? 1. : opt->mapQ_coef_fac / log(l); tmp *= identity * identity; mapq = (int) (6.02 * (a->score - sub) / opt->a * tmp * tmp + .499); } else { mapq = (int) (MEM_MAPQ_COEF * (1. - (double) sub / a->score) * log(a->seedcov) + .499); mapq = identity < 0.95 ? (int) (mapq * identity * identity + .499) : mapq; } if (a->sub_n > 0) mapq -= (int) (4.343 * log(a->sub_n + 1) + .499); if (mapq > 60) mapq = 60; if (mapq < 0) mapq = 0; mapq = (int) (mapq * (1. - a->frac_rep) + .499); return mapq; } // TODO (future plan): group hits into a uint64_t[] array. This will be cleaner and more flexible int read_no = 0; void mem_reg2sam(const mem_opt_t *opt, const bntseq_t *bns, const uint8_t *pac, bseq1_t *s, mem_alnreg_v *a, int extra_flag, const mem_aln_t *m) { extern char **mem_gen_alt(const mem_opt_t *opt, const bntseq_t *bns, const uint8_t *pac, mem_alnreg_v *a, int l_query, const char *query); kstring_t str; kvec_t(mem_aln_t) aa; int k, l; char **XA = 0; //read_no++; //fprintf(stderr, "%d\n", read_no); //fflush(stderr); if (!(opt->flag & MEM_F_ALL)) XA = mem_gen_alt(opt, bns, pac, a, s->l_seq, s->seq); kv_init(aa); str.l = str.m = 0; str.s = 0; for (k = l = 0; k < a->n; ++k) { mem_alnreg_t *p = &a->a[k]; mem_aln_t *q; if (p->score < opt->T) continue; if (p->secondary >= 0 && (p->is_alt || !(opt->flag & MEM_F_ALL))) continue; if (p->secondary >= 0 && p->secondary < INT_MAX && p->score < a->a[p->secondary].score * opt->drop_ratio) continue; q = kv_pushp(mem_aln_t, aa); *q = mem_reg2aln(opt, bns, pac, s->l_seq, s->seq, p); assert(q->rid >= 0); // this should not happen with the new code q->XA = XA ? XA[k] : 0; q->flag |= extra_flag; // flag secondary if (p->secondary >= 0) q->sub = -1; // don't output sub-optimal score if (l && p->secondary < 0) // if supplementary q->flag |= (opt->flag & MEM_F_NO_MULTI) ? 0x10000 : 0x800; if (l && !p->is_alt && q->mapq > aa.a[0].mapq) q->mapq = aa.a[0].mapq; ++l; } if (aa.n == 0) { // no alignments good enough; then write an unaligned record mem_aln_t t; t = mem_reg2aln(opt, bns, pac, s->l_seq, s->seq, 0); t.flag |= extra_flag; mem_aln2sam(opt, bns, &str, s, 1, &t, 0, m); } else { for (k = 0; k < aa.n; ++k) mem_aln2sam(opt, bns, &str, s, aa.n, aa.a, k, m); for (k = 0; k < aa.n; ++k) free(aa.a[k].cigar); free(aa.a); } s->sam = str.s; if (XA) { for (k = 0; k < a->n; ++k) free(XA[k]); free(XA); } } void print_seq(int length, uint8_t* seq){ int i; fprintf(stderr,"seq length = %d: ", length); for (i = 0; i < length; ++i) { putc("ACGTN"[(int)seq[i]], stderr); } fprintf(stderr,"\n"); } //#define GPU_READ_BATCH_SIZE 1000 void mem_align1_core(const mem_opt_t *opt, const bwt_t *bwt, const bntseq_t *bns, const uint8_t *pac, bseq1_t *seq, void *buf, int batch_size, int batch_start_idx, mem_alnreg_v *w_regs, int tid, gasal_gpu_storage_v *gpu_storage_vec) { int j, r; //extern double *extension_time; extern time_struct *extension_time; extern uint64_t *no_of_extensions; kvec_t(mem_alnreg_v) regs_vec; kv_init(regs_vec); kv_resize(mem_alnreg_v, regs_vec, batch_size); // gasal_gpu_storage **gpu_storage_arr = (gasal_gpu_storage*)calloc(10*sizeof(*gasal_gpu_storage)); // struct gpu_batch{ // gasal_gpu_storage_t *gpu_storage; // int batch_size; // int batch_start; // int is_active; // int no_extend; // }; int GPU_READ_BATCH_SIZE; if (batch_size >= 4000) GPU_READ_BATCH_SIZE = 1000; else { GPU_READ_BATCH_SIZE = (int)ceil((double)batch_size/(double)4) % 2 ? (int)ceil((double)batch_size/(double)4) + 1: (int)ceil((double)batch_size/(double)4); } int internal_batch_count = (int)ceil((double)batch_size/(double)(GPU_READ_BATCH_SIZE)); gpu_batch gpu_batch_arr[gpu_storage_vec->n]; for(j = 0; j < gpu_storage_vec->n; j++) { gpu_batch_arr[j].gpu_storage = &(gpu_storage_vec->a[j]); } int internal_batch_done = 0; int batch_processed = 0; //int total_internal_batches = 0; int internal_batch_no = 0; double time_extend; //int internal_batch_size = 1000;//batch_size - batch_processed >= 4000 ? 4000 : batch_size - batch_processed; //cudaStream_t streams[internal_batch_count]; //fprintf(stderr, "thread no %d with batch size %d and batch count %d\n", tid, batch_size, internal_batch_count); //extern uint64_t *no_of_extensions; //seq_ptr_arr read_seqns; //seq_ptr_arr ref_seqns; //aln_pair read_idx_vec; //kv_init(read_seqns); //kv_resize(uint8_t*, read_seqns, 10*batch_size); //kv_init(ref_seqns); //kv_resize(uint8_t*, ref_seqns, batch_size*10); //seq_lens read_seq_lens; //seq_lens ref_seq_lens; //kv_init(read_seq_lens); //kv_resize(int, read_seq_lens, 10*batch_size); //kv_init(ref_seq_lens); //kv_resize(int, ref_seq_lens, batch_size*10); //kv_init(read_idx_vec); //kv_resize(int, read_idx_vec, n_reads*10); while (internal_batch_done < internal_batch_count) { int gpu_batch_arr_idx = 0; while(gpu_batch_arr_idx != gpu_storage_vec->n && gpu_batch_arr[gpu_batch_arr_idx].gpu_storage->is_free != 1) { gpu_batch_arr_idx++; } // if (gpu_batch_arr_idx == gpu_storage_vec->n && batch_processed < batch_size) { // no_of_extensions[tid]++; // } int internal_batch_start_idx = batch_processed; if (internal_batch_start_idx < batch_size && gpu_batch_arr_idx < gpu_storage_vec->n) { // kvec_t(mem_chain_v) mem_chain_v_vec; // kv_init(mem_chain_v_vec); // kv_resize(mem_chain_v, mem_chain_v_vec, n_reads); //read_no++; //fprintf(stderr, "%d\n", read_no); //fflush(stderr); gpu_batch_arr[gpu_batch_arr_idx].n_query_batch = 0; gpu_batch_arr[gpu_batch_arr_idx].n_target_batch = 0; gpu_batch_arr[gpu_batch_arr_idx].n_seqs = 0; int curr_read_offset = 0; int curr_ref_offset = 0; int internal_batch_size = batch_size - batch_processed >= GPU_READ_BATCH_SIZE ? GPU_READ_BATCH_SIZE : batch_size - batch_processed; //fprintf(stderr, "\tthread no %d with internal_batch_size %d\n", tid, internal_batch_size); //gpu_batch_arr[gpu_batch_arr_idx].gpu_storage = (gasal_gpu_storage_t*)calloc(1, sizeof(gasal_gpu_storage_t)); // seq_batch read_seq_batch; // kv_init(read_seq_batch); // kv_resize(uint8_t, read_seq_batch, MAX_BATCH1_LEN * internal_batch_size * 40); // seq_lens read_seq_lens; // kv_init(read_seq_lens); // kv_resize(uint32_t, read_seq_lens, 40*internal_batch_size); // seq_offsets read_seq_offsets; // kv_init(read_seq_offsets); // kv_resize(uint32_t, read_seq_offsets, 40*internal_batch_size); // // seq_batch ref_seq_batch; // kv_init(ref_seq_batch); // kv_resize(uint8_t, ref_seq_batch, MAX_BATCH2_LEN * internal_batch_size * 40); // seq_lens ref_seq_lens; // kv_init(ref_seq_lens); // kv_resize(uint32_t, ref_seq_lens, 40*internal_batch_size); // seq_offsets ref_seq_offsets; // kv_init(ref_seq_offsets); // kv_resize(uint32_t, ref_seq_offsets, 40*internal_batch_size); for (j = batch_start_idx + internal_batch_start_idx; j < (batch_start_idx + internal_batch_start_idx) + internal_batch_size; ++j) { mem_chain_v chn; mem_alnreg_v regs; int i; char *read_seq = seq[j].seq; int read_l_seq_with_p = (seq[j].l_seq%8) ? seq[j].l_seq + (8 - (seq[j].l_seq%8)) : seq[j].l_seq ; //uint8_t *read_seq_with_p = (uin8_t*)malloc(read_l_seq_with_p); // for (i = 0; i < seq[j].l_seq; ++i){ // convert to 2-bit encoding if we have not done so // read_seq[i] = read_seq[i] < 4 ? read_seq[i] : nst_nt4_table[(int) read_seq[i]]; // kv_push(uint8_t, read_seq_batch, read_seq[i]); // } // int read_l_seq = seq[j].l_seq; // while(read_l_seq < read_l_seq_with_p) { // kv_push(uint8_t, read_seq_batch, 0); // read_l_seq++; // } for (i = 0; i < seq[j].l_seq; ++i){ // convert to 2-bit encoding if we have not done so read_seq[i] = read_seq[i] < 4 ? read_seq[i] : nst_nt4_table[(int) read_seq[i]]; if (gpu_batch_arr[gpu_batch_arr_idx].n_query_batch < gpu_batch_arr[gpu_batch_arr_idx].gpu_storage->host_max_query_batch_bytes) gpu_batch_arr[gpu_batch_arr_idx].gpu_storage->host_unpacked_query_batch[gpu_batch_arr[gpu_batch_arr_idx].n_query_batch++]=read_seq[i]; else { fprintf(stderr, "The size of host query_batch (%d) exceeds the allocation (%d)\n", gpu_batch_arr[gpu_batch_arr_idx].n_query_batch + 1, gpu_batch_arr[gpu_batch_arr_idx].gpu_storage->host_max_query_batch_bytes); exit(EXIT_FAILURE); } //kv_push(uint8_t, read_seq_batch, read_seq[i]); } int read_l_seq = seq[j].l_seq; while(read_l_seq < read_l_seq_with_p) { //kv_push(uint8_t, read_seq_batch, 0); if (gpu_batch_arr[gpu_batch_arr_idx].n_query_batch < gpu_batch_arr[gpu_batch_arr_idx].gpu_storage->host_max_query_batch_bytes)gpu_batch_arr[gpu_batch_arr_idx].gpu_storage->host_unpacked_query_batch[gpu_batch_arr[gpu_batch_arr_idx].n_query_batch++]= 4; else { fprintf(stderr, "The size of host query_batch (%d) exceeds the allocation (%d)\n", gpu_batch_arr[gpu_batch_arr_idx].n_query_batch + 1, gpu_batch_arr[gpu_batch_arr_idx].gpu_storage->host_max_query_batch_bytes); exit(EXIT_FAILURE); } read_l_seq++; } //kv_push(int, read_seq_lens, read_l_seq); //kv_push(int, read_seq_offsets, curr_read_offset); //print_seq(read_l_seq, read_seq); //fflush(stderr); //fprintf(stderr, "%d,", j); chn = mem_chain(opt, bwt, bns, seq[j].l_seq, (uint8_t*)(read_seq), buf); chn.n = mem_chain_flt(opt, chn.n, chn.a); if (opt->shd_filter) mem_shd_flt_chained_seeds(opt, bns, pac, seq[j].l_seq, (uint8_t*)(read_seq), chn.n, chn.a); else mem_flt_chained_seeds(opt, bns, pac, seq[j].l_seq, (uint8_t*)(read_seq), chn.n, chn.a); if (bwa_verbose >= 4) mem_print_chain(bns, &chn); /*for (i = 0; i < chn.n; ++i) { mem_chain_t *c = &chn.a[i]; if (c->n == 0) continue; uint64_t *srt; srt = malloc(c->n * 8); for (i = 0; i < c->n; ++i) srt[i] = (uint64_t)c->seeds[i].score<<32 | i; ks_introsort_64(c->n, srt);*/ kv_init(regs); for (i = 0; i < chn.n; ++i) { mem_chain_t *p = &chn.a[i]; if (bwa_verbose >= 4) err_printf("* ---> Processing chain(%d) <---\n", i); //mem_chain2aln(opt, bns, pac, seq[j].l_seq, (uint8_t*)(read_seq), p, &regs, &read_seq_lens, &read_seq_offsets, &curr_read_offset, &ref_seq_batch, &ref_seq_lens, &ref_seq_offsets, &curr_ref_offset); mem_chain2aln(opt, bns, pac, seq[j].l_seq, (uint8_t*)(read_seq), p, &regs, &curr_read_offset, &curr_ref_offset, &gpu_batch_arr[gpu_batch_arr_idx]); free(chn.a[i].seeds); } curr_read_offset += read_l_seq_with_p; free(chn.a); kv_push(mem_alnreg_v, regs_vec, regs); //smem_aux_destroy((smem_aux_t*)buf); //buf = smem_aux_init(); } if (/*kv_size(ref_seq_lens)*/ gpu_batch_arr[gpu_batch_arr_idx].n_seqs > 0) { //fprintf(stderr, "n_alns on GPU=%d\n", kv_size(ref_seq_lens)); //no_of_extensions[tid] += kv_size(ref_seq_lens); no_of_extensions[tid] += gpu_batch_arr[gpu_batch_arr_idx].n_seqs; // gasal_host_malloc_int32(&(gpu_batch_arr[gpu_batch_arr_idx].max_score), kv_size(ref_seq_lens) * sizeof(int32_t)); // gasal_host_malloc_int32(&(gpu_batch_arr[gpu_batch_arr_idx].read_start), kv_size(ref_seq_lens) * sizeof(int32_t)); // gasal_host_malloc_int32(&(gpu_batch_arr[gpu_batch_arr_idx].read_end), kv_size(ref_seq_lens) * sizeof(int32_t)); // gasal_host_malloc_int32(&(gpu_batch_arr[gpu_batch_arr_idx].ref_start), kv_size(ref_seq_lens) * sizeof(int32_t)); // gasal_host_malloc_int32(&(gpu_batch_arr[gpu_batch_arr_idx].ref_end), kv_size(ref_seq_lens) * sizeof(int32_t)); //time_extend = realtime(); //gasal_host_malloc_int32(&(gpu_batch_arr[gpu_batch_arr_idx].gpu_storage->host_results), 5 * kv_size(ref_seq_lens) * sizeof(int32_t)); //extension_time[tid].host_mem_alloc += (realtime() - time_extend); // gpu_batch_arr[gpu_batch_arr_idx].gpu_storage->host_unpacked_query_batch = read_seq_batch.a; // gpu_batch_arr[gpu_batch_arr_idx].gpu_storage->host_unpacked_target_batch = ref_seq_batch.a; // gpu_batch_arr[gpu_batch_arr_idx].gpu_storage->host_query_batch_offsets = read_seq_offsets.a; // gpu_batch_arr[gpu_batch_arr_idx].gpu_storage->host_target_batch_offsets = ref_seq_offsets.a; // gpu_batch_arr[gpu_batch_arr_idx].gpu_storage->host_query_batch_lens = read_seq_lens.a; // gpu_batch_arr[gpu_batch_arr_idx].gpu_storage->host_target_batch_lens = ref_seq_lens.a; // //gpu_batch_arr[gpu_batch_arr_idx].gpu_storage->host_aln_score = (int32_t*) malloc(5 * kv_size(ref_seq_lens) * sizeof(int32_t)); // gpu_batch_arr[gpu_batch_arr_idx].gpu_storage->host_aln_score = (int32_t*) malloc(kv_size(ref_seq_lens) * sizeof(int32_t)); // gpu_batch_arr[gpu_batch_arr_idx].gpu_storage->host_query_batch_start = (int32_t*) malloc(kv_size(ref_seq_lens) * sizeof(int32_t)); // gpu_batch_arr[gpu_batch_arr_idx].gpu_storage->host_query_batch_end = (int32_t*) malloc(kv_size(ref_seq_lens) * sizeof(int32_t)); // gpu_batch_arr[gpu_batch_arr_idx].gpu_storage->host_target_batch_start = (int32_t*) malloc(kv_size(ref_seq_lens) * sizeof(int32_t)); // gpu_batch_arr[gpu_batch_arr_idx].gpu_storage->host_target_batch_end = (int32_t*) malloc(kv_size(ref_seq_lens) * sizeof(int32_t)); //extension_time[tid] += (realtime() - time_extend); // gasal_aln(const uint8_t *query_batch, const uint32_t *query_batch_offsets, const uint32_t *query_batch_lens, const uint8_t *target_batch, const uint32_t *target_batch_offsets, const uint32_t *target_batch_lens, const uint32_t query_batch_bytes, const uint32_t target_batch_bytes, const uint32_t n_alns, int32_t *host_aln_score, int32_t *host_query_batch_start, int32_t *host_target_batch_start, int32_t *host_query_batch_end, int32_t *host_target_batch_end, int algo, int start) // gasal_aln_imp(read_seq_batch.a, read_seq_offsets.a, read_seq_lens.a, ref_seq_batch.a, ref_seq_offsets.a, ref_seq_lens.a , kv_size(read_seq_batch), kv_size(ref_seq_batch), kv_size(ref_seq_lens), max_score, read_start, ref_start, read_end, ref_end, LOCAL, WITH_START, gpu_storage); //time_extend = realtime(); //gasal_gpu_mem_alloc(gpu_batch_arr[gpu_batch_arr_idx].gpu_storage, kv_size(read_seq_batch), kv_size(ref_seq_batch), kv_size(ref_seq_lens), LOCAL, WITH_START); //extension_time[tid].gpu_mem_alloc += (realtime() - time_extend); time_extend = realtime(); //gasal_aln_async_new(gpu_batch_arr[gpu_batch_arr_idx].gpu_storage, kv_size(read_seq_batch), kv_size(ref_seq_batch), kv_size(ref_seq_lens), LOCAL, WITH_START); gasal_aln_async(gpu_batch_arr[gpu_batch_arr_idx].gpu_storage, gpu_batch_arr[gpu_batch_arr_idx].n_query_batch, gpu_batch_arr[gpu_batch_arr_idx].n_target_batch, gpu_batch_arr[gpu_batch_arr_idx].n_seqs, LOCAL, WITH_START); extension_time[tid].aln_kernel += (realtime() - time_extend); gpu_batch_arr[gpu_batch_arr_idx].no_extend = 0; } else { gpu_batch_arr[gpu_batch_arr_idx].no_extend = 1; //fprintf(stderr, "I am here\n"); mem_alnreg_v regs = kv_A(regs_vec, kv_size(regs_vec) - 1); //fprintf(stderr, "Thread no. %d is here with internal batch size %d, regs.n %d \n", tid, internal_batch_size, regs.n); } batch_processed += internal_batch_size; gpu_batch_arr[gpu_batch_arr_idx].batch_size = internal_batch_size; gpu_batch_arr[gpu_batch_arr_idx].batch_start = internal_batch_start_idx; gpu_batch_arr[gpu_batch_arr_idx].is_active = 1; //total_internal_batches++; //gpu_batch_arr_idx++; // kv_destroy(read_seq_batch); // kv_destroy(ref_seq_batch); // kv_destroy(read_seq_lens); // kv_destroy(ref_seq_lens); // kv_destroy(read_seq_offsets); // kv_destroy(ref_seq_offsets); assert(kv_size(regs_vec) == batch_processed); internal_batch_no++; //fprintf(stderr, "internal batch %d launched\n", internal_batch_no++); } //fprintf(stderr, "Current extension time of %d seeds on GPU by thread no. %d is %.3f usec\n", kv_size(ref_seq_lens), tid, extension_time[tid]*1e6); int internal_batch_idx = 0; while (internal_batch_idx != gpu_storage_vec->n) { time_extend = realtime(); int x = 0; if (gpu_batch_arr[internal_batch_idx].gpu_storage->is_free != 1) { x = (gasal_is_aln_async_done(gpu_batch_arr[internal_batch_idx].gpu_storage) == 0); //fprintf(stderr, "Thread no. %d stuck here with batch size %d and batch count %d. internal batch idx is %d \n", tid, batch_size, internal_batch_count, internal_batch_idx); } if (x) extension_time[tid].get_results_actual += (realtime() - time_extend); else if (gpu_batch_arr[internal_batch_idx].gpu_storage->is_free != 1 && x == 0) extension_time[tid].get_results_wasted += (realtime() - time_extend); //fprintf(stderr, "Thread no. %d stuck here with batch size %d and batch count %d. internal batch idx is %d, batches launched=%d, batches done=%d \n", tid, batch_size, internal_batch_count, internal_batch_idx, internal_batch_no, internal_batch_done); //fprintf(stderr, "Thread no. %d stuck here with batch size %d and batch count %d. internal batch idx is \n"); if ((x == 1 || gpu_batch_arr[internal_batch_idx].no_extend == 1) && gpu_batch_arr[internal_batch_idx].is_active == 1){ int32_t *max_score = gpu_batch_arr[internal_batch_idx].gpu_storage->host_aln_score; int32_t *read_start = gpu_batch_arr[internal_batch_idx].gpu_storage->host_query_batch_start; int32_t *read_end = gpu_batch_arr[internal_batch_idx].gpu_storage->host_query_batch_end; int32_t *ref_start = gpu_batch_arr[internal_batch_idx].gpu_storage->host_target_batch_start; int32_t *ref_end = gpu_batch_arr[internal_batch_idx].gpu_storage->host_target_batch_end; // int32_t *max_score = gpu_batch_arr[internal_batch_idx].gpu_storage->host_aln_score; // int32_t *read_start = &(gpu_batch_arr[internal_batch_idx].gpu_storage->host_aln_score[gpu_batch_arr[internal_batch_idx].gpu_storage->n_alns]); // int32_t *ref_start = &(gpu_batch_arr[internal_batch_idx].gpu_storage->host_aln_score[2*(gpu_batch_arr[internal_batch_idx].gpu_storage->n_alns)]); // int32_t *read_end = &(gpu_batch_arr[internal_batch_idx].gpu_storage->host_aln_score[3*(gpu_batch_arr[internal_batch_idx].gpu_storage->n_alns)]); // int32_t *ref_end = &(gpu_batch_arr[internal_batch_idx].gpu_storage->host_aln_score[4*(gpu_batch_arr[internal_batch_idx].gpu_storage->n_alns)]); int seq_idx=0; for(j = 0, r = gpu_batch_arr[internal_batch_idx].batch_start; j < gpu_batch_arr[internal_batch_idx].batch_size; ++j, ++r){ int i; mem_alnreg_v regs = kv_A(regs_vec, r); //int read_pos = kv_A(read_seq_offsets, j); //int read_len = kv_A(read_seq_lens, j); //uint8_t* read_seq = &(kv_A(read_seq_batch, read_pos)); if (gpu_batch_arr[internal_batch_idx].no_extend == 1) fprintf(stderr, "I am here too as well with regs.n %d\n", regs.n); for(i = 0; i < regs.n; ++i){ mem_alnreg_t *a = &regs.a[i]; //fprintf(stderr, "I am here before\n"); //fprintf(stderr, "r=%d, seq[r].l_seq=%d\n", r, seq[r].l_seq); //fprintf(stderr, "I am here after\n"); if (a->seedlen0 != seq[r].l_seq/*kv_A(read_seq_lens, seq_idx)*/) { //if (gpu_batch_arr[internal_batch_idx].no_extend == 1) fprintf(stderr, "I am here too as well\n"); a->score = max_score[seq_idx]; a->qb = read_start[seq_idx]; a->qe = read_end[seq_idx] + 1; a->rb = ref_start[seq_idx] + a->rseq_beg; a->re = ref_end[seq_idx] + a->rseq_beg + 1; a->truesc = max_score[seq_idx]; //fprintf(stderr, "seq_set=%d\tscore=%d\tread_end=%d\tref_end=%d\tread_start=%d\tref_start=%d\n", seq_idx, max_score[seq_idx], //read_end[seq_idx], ref_end[seq_idx], read_start[seq_idx], ref_start[seq_idx]); // uint8_t *rs; // kswr_t x; // no_of_extensions[tid]++; // int read_pos = kv_A(read_seq_offsets, seq_idx); // int read_len = kv_A(read_seq_lens, seq_idx); // uint8_t* read_seq = &(kv_A(read_seq_batch, read_pos)); // int ref_pos = kv_A(ref_seq_offsets, seq_idx); // int ref_len = kv_A(ref_seq_lens, seq_idx); // uint8_t* ref_seq = &(kv_A(ref_seq_batch, ref_pos)); // x.score = -1, x.te = -1, x.qe = -1, x.qb = -1, x.tb = -1, x.score2 = -1, x.te2 = -1; // //print_seq(kv_A(read_seq_lens, seq_idx), kv_A(read_seqns, seq_idx)); // //print_seq(kv_A(ref_seq_lens, seq_idx), kv_A(ref_seqns, seq_idx)); // //fflush(stderr); // // //x = ksw_align2(kv_A(read_seq_lens, seq_idx), kv_A(read_seqns, seq_idx), kv_A(ref_seq_lens, seq_idx), kv_A(ref_seqns, seq_idx), 5, opt->mat, opt->o_del, opt->e_del, opt->o_ins, opt->e_ins, KSW_XSTART, 0, // // opt->use_avx2); // x = ksw_align2(read_len, read_seq, ref_len, ref_seq, 5, opt->mat, opt->o_del, opt->e_del, opt->o_ins, opt->e_ins, KSW_XSTART, 0, // opt->use_avx2); // if (x.score != -1 && x.te != -1 && x.qe != -1 && x.qb != -1 && x.tb != -1) { // a->score = x.score, a->qb = x.qb, a->qe = x.qe + 1, a->rb = x.tb + a->rseq_beg, a->re = x.te + a->rseq_beg + 1, a->truesc = // x.score; // } // else { // fprintf(stderr, "SIMD implementation not working\n"); // print_seq(read_len, read_seq); // print_seq(ref_len, ref_seq); // fprintf(stderr, "read_no in the batch = %d with seq_idx = %d but number of read_lens = %d", j, seq_idx, kv_size(ref_seq_lens)); // fflush(stderr); // exit(EXIT_FAILURE); // } seq_idx++; } //if((a->qe - a->qb) == 865350) { // print_seq(read_len, read_seq); // print_seq(ref_len, ref_seq); // fflush(stderr); //} //free(kv_A(ref_seqns, seq_idx)); } regs.n = mem_sort_dedup_patch(opt, bns, pac,(uint8_t*)(seq[r].seq), regs.n, regs.a); if (bwa_verbose >= 4) { err_printf("* %ld chains remain after removing duplicated chains\n", regs.n); for (i = 0; i < regs.n; ++i) { mem_alnreg_t *p = &regs.a[i]; printf("** %d, [%d,%d) <=> [%ld,%ld)\n", p->score, p->qb, p->qe, (long)p->rb, (long)p->re); } } for (i = 0; i < regs.n; ++i) { mem_alnreg_t *p = &regs.a[i]; if (p->rid >= 0 && bns->anns[p->rid].is_alt) p->is_alt = 1; //free(kv_A(read_seqns, i)); } w_regs[r + batch_start_idx] = regs; //free(regs.a); } //kv_destroy(read_seqns); //kv_destroy(ref_seqns); //double time_extend = realtime(); //fprintf(stderr, "I am before error\n"); //fprintf(stderr, "internal batch %d done\n", internal_batch_done - 1); //if (gpu_batch_arr[internal_batch_idx].no_extend == 0) free(max_score); //free(read_start); free(read_end); free(ref_start); free(ref_end); //fprintf(stderr, "I am after error\n"); // //time_extend = realtime(); //gasal_host_free_int32(gpu_batch_arr[internal_batch_idx].gpu_storage->host_results); //extension_time[tid].host_mem_free += (realtime() - time_extend); //free(gpu_batch_arr[internal_batch_idx].gpu_storage); //gasal_host_free_int32(max_score); gasal_host_free_int32(read_start); gasal_host_free_int32(read_end); gasal_host_free_int32(ref_start); gasal_host_free_int32(ref_end); //extension_time[tid] += (realtime() - time_extend); gpu_batch_arr[internal_batch_idx].is_active = 0; internal_batch_done++; //fprintf(stderr, "internal batch %d done\n", internal_batch_done - 1); } internal_batch_idx++; } } kv_destroy(regs_vec); //fprintf(stderr, "--------------------------------------"); } mem_aln_t mem_reg2aln(const mem_opt_t *opt, const bntseq_t *bns, const uint8_t *pac, int l_query, const char *query_, const mem_alnreg_t *ar) { mem_aln_t a; int i, w2, tmp, qb, qe, NM, score, is_rev, last_sc = -(1 << 30), l_MD; int64_t pos, rb, re; uint8_t *query; memset(&a, 0, sizeof(mem_aln_t)); if (ar == 0 || ar->rb < 0 || ar->re < 0) { // generate an unmapped record a.rid = -1; a.pos = -1; a.flag |= 0x4; return a; } qb = ar->qb, qe = ar->qe; rb = ar->rb, re = ar->re; query = malloc(l_query); for (i = 0; i < l_query; ++i) // convert to the nt4 encoding query[i] = query_[i] < 5 ? query_[i] : nst_nt4_table[(int) query_[i]]; a.mapq = ar->secondary < 0 ? mem_approx_mapq_se(opt, ar) : 0; if (ar->secondary >= 0) a.flag |= 0x100; // secondary alignment tmp = infer_bw(qe - qb, re - rb, ar->truesc, opt->a, opt->o_del, opt->e_del); w2 = infer_bw(qe - qb, re - rb, ar->truesc, opt->a, opt->o_ins, opt->e_ins); w2 = w2 > tmp ? w2 : tmp; if (bwa_verbose >= 4) printf("* Band width: inferred=%d, cmd_opt=%d, alnreg=%d\n", w2, opt->w, ar->w); if (w2 > opt->w) w2 = w2 < ar->w ? w2 : ar->w; i = 0; a.cigar = 0; do { free(a.cigar); w2 = w2 < opt->w << 2 ? w2 : opt->w << 2; a.cigar = bwa_gen_cigar2(opt->mat, opt->o_del, opt->e_del, opt->o_ins, opt->e_ins, w2, bns->l_pac, pac, qe - qb, (uint8_t*) &query[qb], rb, re, &score, &a.n_cigar, &NM); if (bwa_verbose >= 4) printf("* Final alignment: w2=%d, global_sc=%d, local_sc=%d\n", w2, score, ar->truesc); if (score == last_sc || w2 == opt->w << 2) break; // it is possible that global alignment and local alignment give different scores last_sc = score; w2 <<= 1; } while (++i < 3 && score < ar->truesc - opt->a); //a.cigar = bwa_gen_cigar2(opt->mat, opt->o_del, opt->e_del, opt->o_ins, opt->e_ins, w2, bns->l_pac, pac, qe - qb, (uint8_t*) &query[qb], rb, re, // &score, &a.n_cigar, &NM); if (bwa_verbose >= 4) fprintf(stderr, "* Final alignment: w2=%d, global_sc=%d, local_sc=%d\n", w2, score, ar->truesc); //fflush(stderr); l_MD = strlen((char*) (a.cigar + a.n_cigar)) + 1; a.NM = NM; pos = bns_depos(bns, rb < bns->l_pac ? rb : re - 1, &is_rev); a.is_rev = is_rev; if (a.n_cigar > 0) { // squeeze out leading or trailing deletions if ((a.cigar[0] & 0xf) == 2) { pos += a.cigar[0] >> 4; --a.n_cigar; memmove(a.cigar, a.cigar + 1, a.n_cigar * 4 + l_MD); } else if ((a.cigar[a.n_cigar - 1] & 0xf) == 2) { --a.n_cigar; memmove(a.cigar + a.n_cigar, a.cigar + a.n_cigar + 1, l_MD); // MD needs to be moved accordingly } } if (qb != 0 || qe != l_query) { // add clipping to CIGAR int clip5, clip3; clip5 = is_rev ? l_query - qe : qb; clip3 = is_rev ? qb : l_query - qe; a.cigar = realloc(a.cigar, 4 * (a.n_cigar + 2) + l_MD); if (clip5) { memmove(a.cigar + 1, a.cigar, a.n_cigar * 4 + l_MD); // make room for 5'-end clipping a.cigar[0] = clip5 << 4 | 3; ++a.n_cigar; } if (clip3) { memmove(a.cigar + a.n_cigar + 1, a.cigar + a.n_cigar, l_MD); // make room for 3'-end clipping a.cigar[a.n_cigar++] = clip3 << 4 | 3; } } a.rid = bns_pos2rid(bns, pos); assert(a.rid == ar->rid); a.pos = pos - bns->anns[a.rid].offset; a.score = ar->score; a.sub = ar->sub > ar->csub ? ar->sub : ar->csub; a.is_alt = ar->is_alt; a.alt_sc = ar->alt_sc; free(query); return a; } typedef struct { const mem_opt_t *opt; const bwt_t *bwt; const bntseq_t *bns; const uint8_t *pac; const mem_pestat_t *pes; smem_aux_t **aux; bseq1_t *seqs; mem_alnreg_v *regs; int64_t n_processed; } worker_t; void worker1(void *data, int i, int tid, int batch_size, int total_reads, gasal_gpu_storage_v *gpu_storage_vec) { worker_t *w = (worker_t*) data; //if (!(w->opt->flag & MEM_F_PE)) { if (bwa_verbose >= 4) printf("=====> Processing read '%s' <=====\n", w->seqs[i].name); //if(i + batch_size >= total_reads) batch_size = total_reads - i; mem_align1_core(w->opt, w->bwt, w->bns, w->pac, w->seqs, w->aux[tid], batch_size, i, w->regs, tid, gpu_storage_vec); // } else { // if (bwa_verbose >= 4) // printf("=====> Processing read '%s'/1 <=====\n", w->seqs[i << 1 | 0].name); // w->regs[i << 1 | 0] = mem_align1_core(w->opt, w->bwt, w->bns, w->pac, w->seqs[i << 1 | 0].l_seq, w->seqs[i << 1 | 0].seq, w->aux[tid]); // if (bwa_verbose >= 4) // printf("=====> Processing read '%s'/2 <=====\n", w->seqs[i << 1 | 1].name); // w->regs[i << 1 | 1] = mem_align1_core(w->opt, w->bwt, w->bns, w->pac, w->seqs[i << 1 | 1].l_seq, w->seqs[i << 1 | 1].seq, w->aux[tid]); //} } static void worker2(void *data, int i, int tid, int batch_size, int n_reads, gasal_gpu_storage_v *gpu_storage_vec) { extern int mem_sam_pe(const mem_opt_t *opt, const bntseq_t *bns, const uint8_t *pac, const mem_pestat_t pes[4], uint64_t id, bseq1_t s[2], mem_alnreg_v a[2]); extern void mem_reg2ovlp(const mem_opt_t *opt, const bntseq_t *bns, const uint8_t *pac, bseq1_t *s, mem_alnreg_v *a); worker_t *w = (worker_t*) data; if (!(w->opt->flag & MEM_F_PE)) { if (bwa_verbose >= 4) printf("=====> Finalizing read '%s' <=====\n", w->seqs[i].name); mem_mark_primary_se(w->opt, w->regs[i].n, w->regs[i].a, w->n_processed + i); mem_reg2sam(w->opt, w->bns, w->pac, &w->seqs[i], &w->regs[i], 0, 0); free(w->regs[i].a); } else { if (bwa_verbose >= 4) printf("=====> Finalizing read pair '%s' <=====\n", w->seqs[i << 1 | 0].name); mem_sam_pe(w->opt, w->bns, w->pac, w->pes, (w->n_processed >> 1) + i, &w->seqs[i << 1], &w->regs[i << 1]); free(w->regs[i << 1 | 0].a); free(w->regs[i << 1 | 1].a); } } void mem_process_seqs(const mem_opt_t *opt, const bwt_t *bwt, const bntseq_t *bns, const uint8_t *pac, int64_t n_processed, int n, bseq1_t *seqs, const mem_pestat_t *pes0) { extern void kt_for(int n_threads, void (*func)(void*, int, int, int, int), void *data, int n); worker_t w; mem_pestat_t pes[4]; double ctime, rtime; int i; extern double *load_balance_waste_time; extern double total_load_balance_waste_time; ctime = cputime(); rtime = realtime(); global_bns = bns; w.regs = malloc(n * sizeof(mem_alnreg_v)); w.opt = opt; w.bwt = bwt; w.bns = bns; w.pac = pac; w.seqs = seqs; w.n_processed = n_processed; w.pes = &pes[0]; w.aux = malloc(opt->n_threads * sizeof(smem_aux_t)); for (i = 0; i < opt->n_threads; ++i) w.aux[i] = smem_aux_init(); kt_for(opt->n_threads, worker1, &w, /*(opt->flag & MEM_F_PE) ? n >> 1 : */n); // find mapping positions double min_exit_time = load_balance_waste_time[0]; double max_exit_time = load_balance_waste_time[0]; for (i = 1; i < opt->n_threads; i++) { if (load_balance_waste_time[i] < min_exit_time) min_exit_time = load_balance_waste_time[i]; if (load_balance_waste_time[i] > max_exit_time) max_exit_time = load_balance_waste_time[i]; } total_load_balance_waste_time += (max_exit_time - min_exit_time); for (i = 0; i < opt->n_threads; ++i) smem_aux_destroy(w.aux[i]); free(w.aux); if (opt->flag & MEM_F_PE) { // infer insert sizes if not provided if (pes0) memcpy(pes, pes0, 4 * sizeof(mem_pestat_t)); // if pes0 != NULL, set the insert-size distribution as pes0 else mem_pestat(opt, bns->l_pac, n, w.regs, pes); // otherwise, infer the insert size distribution from data } kt_for(opt->n_threads, worker2, &w, (opt->flag & MEM_F_PE) ? n >> 1 : n); // generate alignment // min_exit_time = load_balance_waste_time[0]; // max_exit_time = load_balance_waste_time[0]; // // for (i = 1; i < opt->n_threads; i++) { // if (load_balance_waste_time[i] < min_exit_time) min_exit_time = load_balance_waste_time[i]; // if (load_balance_waste_time[i] > max_exit_time) max_exit_time = load_balance_waste_time[i]; // } // // total_load_balance_waste_time += (max_exit_time - min_exit_time); free(w.regs); if (bwa_verbose >= 3) fprintf(stderr, "[M::%s] Processed %d reads in %.3f CPU sec, %.3f real sec\n", __func__, n, cputime() - ctime, realtime() - rtime); }
/* Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "httpd.h" #include "http_config.h" #include "http_log.h" module agent_log_module; static int xfer_flags = (O_WRONLY | O_APPEND | O_CREAT); #ifdef OS2 /* OS/2 dosen't support users and groups */ static mode_t xfer_mode = (S_IREAD | S_IWRITE); #else static mode_t xfer_mode = (S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH); #endif typedef struct { char *fname; int agent_fd; } agent_log_state; static void *make_agent_log_state(pool *p, server_rec *s) { agent_log_state *cls = (agent_log_state *) ap_palloc(p, sizeof(agent_log_state)); cls->fname = ""; cls->agent_fd = -1; return (void *) cls; } static const char *set_agent_log(cmd_parms *parms, void *dummy, char *arg) { agent_log_state *cls = ap_get_module_config(parms->server->module_config, &agent_log_module); cls->fname = arg; return NULL; } static const command_rec agent_log_cmds[] = { {"AgentLog", set_agent_log, NULL, RSRC_CONF, TAKE1, "the filename of the agent log"}, {NULL} }; static void open_agent_log(server_rec *s, pool *p) { agent_log_state *cls = ap_get_module_config(s->module_config, &agent_log_module); char *fname = ap_server_root_relative(p, cls->fname); if (cls->agent_fd > 0) return; /* virtual log shared w/main server */ if (*cls->fname == '|') { piped_log *pl; pl = ap_open_piped_log(p, cls->fname + 1); if (pl == NULL) { ap_log_error(APLOG_MARK, APLOG_ERR, s, "couldn't spawn agent log pipe"); exit(1); } cls->agent_fd = ap_piped_log_write_fd(pl); } else if (*cls->fname != '\0') { if ((cls->agent_fd = ap_popenf_ex(p, fname, xfer_flags, xfer_mode, 1)) < 0) { ap_log_error(APLOG_MARK, APLOG_ERR, s, "could not open agent log file %s.", fname); exit(1); } } } static void init_agent_log(server_rec *s, pool *p) { for (; s; s = s->next) open_agent_log(s, p); } static int agent_log_transaction(request_rec *orig) { agent_log_state *cls = ap_get_module_config(orig->server->module_config, &agent_log_module); char str[HUGE_STRING_LEN]; const char *agent; request_rec *r; if (cls->agent_fd < 0) return OK; for (r = orig; r->next; r = r->next) continue; if (*cls->fname == '\0') /* Don't log agent */ return DECLINED; agent = ap_table_get(orig->headers_in, "User-Agent"); if (agent != NULL) { ap_snprintf(str, sizeof(str), "%s\n", agent); write(cls->agent_fd, str, strlen(str)); } return OK; } module agent_log_module = { STANDARD_MODULE_STUFF, init_agent_log, /* initializer */ NULL, /* create per-dir config */ NULL, /* merge per-dir config */ make_agent_log_state, /* server config */ NULL, /* merge server config */ agent_log_cmds, /* command table */ NULL, /* handlers */ NULL, /* filename translation */ NULL, /* check_user_id */ NULL, /* check auth */ NULL, /* check access */ NULL, /* type_checker */ NULL, /* fixups */ agent_log_transaction, /* logger */ NULL, /* header parser */ NULL, /* child_init */ NULL, /* child_exit */ NULL /* post read-request */ };
<filename>platforms/cc3200/src/cc3200_vfs_dev_slfs_container_meta.h #ifndef CS_FW_PLATFORMS_CC32XX_SRC_CC32XX_VFS_DEV_SLFS_CONTAINER_META_H_ #define CS_FW_PLATFORMS_CC32XX_SRC_CC32XX_VFS_DEV_SLFS_CONTAINER_META_H_ #include <stdint.h> #define MAX_FS_CONTAINER_PREFIX_LEN 50 #define MAX_FS_CONTAINER_FNAME_LEN (MAX_FS_CONTAINER_PREFIX_LEN + 3) struct fs_container_info { uint64_t seq; uint32_t fs_size; /* These are no longer actually used, left for backward compat. */ uint32_t fs_block_size; uint32_t fs_page_size; uint32_t fs_erase_size; } info; #define FS_INITIAL_SEQ (~(0ULL) - 1ULL) union fs_container_meta { struct fs_container_info info; uint8_t padding[64]; }; #endif /* CS_FW_PLATFORMS_CC32XX_SRC_CC32XX_VFS_DEV_SLFS_CONTAINER_META_H_ */
#pragma once #include "allocator.h" #include "atom.h" #include "ast.h" #include "array.h" #include "command_line_parser.h" #include "zodiac_error.h" #define zodiac_disable_msvc_mc_warnings() \ __pragma(warning(push)) \ __pragma(warning(disable:4189)) \ __pragma(warning(disable:4244)) \ __pragma(warning(disable:4267)) \ __pragma(warning(disable:4456)) #ifdef WIN32 #ifdef _MSC_VER zodiac_disable_msvc_mc_warnings() #endif // _MSC_VER #include "microsoft_craziness.h" #ifdef _MSC_VER #pragma warning(pop) #endif // _MSC_VER #endif // WIN32 namespace Zodiac { struct BC_Function; struct Build_Data { Options *options = nullptr; Atom_Table atom_table = {}; Array<Atom> kw_atoms = {}; Array<AST_Type*> type_table = {}; AST_Module *entry_module = nullptr; BC_Function *bc_entry_function = nullptr; BC_Function *bc_bytecode_entry_function = nullptr; BC_Function *pre_main_func = nullptr; Allocator *err_allocator = nullptr; Array<Zodiac_Error> errors = {}; bool redeclaration_error = true; bool link_error = false; uint64_t bytecode_instruction_count = 0; #ifdef WIN32 Windows_SDK_Info sdk_info = {}; #endif }; void build_data_init(Allocator *allocator, Build_Data *build_data, Allocator *err_allocator, Options *options); AST_Type *build_data_find_or_create_pointer_type(Allocator *allocator, Build_Data *build_data, AST_Type *base_type); AST_Type *build_data_find_array_type(Build_Data *build_data, AST_Type *elem_type, int64_t element_count); AST_Type *build_data_create_array_type(Allocator *allocator, Build_Data *build_data, AST_Type *elem_type, int64_t element_count); AST_Type *build_data_find_or_create_array_type(Allocator *allocator, Build_Data *build_data, AST_Type *elem_type, int64_t element_count); AST_Type *build_data_find_function_type(Build_Data *build_data, Array<AST_Type*> param_types, AST_Type *return_type); AST_Type *build_data_find_or_create_function_type(Allocator *allocator, Build_Data *build_data, Array<AST_Type *> param_types, AST_Type *return_type); AST_Type *build_data_find_enum_type(Build_Data *build_data, AST_Declaration *enum_decl); }
#pragma once #include <stdint.h> union CSubFld { struct { char m_sa : 1; char m_sb : 3; char m_sc : 2; }; char m_s; }; struct CGVar { uint8_t m_a; short m_b[2]; CSubFld m_c[3]; uint32_t m_d; uint64_t m_e[12]; };
<gh_stars>1-10 // // UICollectionView+JQTPrivate.h // JQTrack // // Created by jqoo on 2019/7/11. // #import <UIKit/UIKit.h> NS_ASSUME_NONNULL_BEGIN @interface UICollectionView (JQTPrivate) @end NS_ASSUME_NONNULL_END
<gh_stars>1-10 /** \file crc_ccitt.h * \brief CRC-CCITT integrity checking algorithm used by Nexus internally. * \author Angaza * \copyright 2020 Angaza, Inc. * \license This file is released under the MIT license * * The above copyright notice and license shall be included in all copies * or substantial portions of the Software. * * By default, the implementation of this header is included within * `common/crc_ccitt.h`. The header is provided at this 'top level' so that * product-side code may also use the same CRC functionality (if required), * and so that the CRC functionality is usable by other Nexus modules * (such as Nexus Channel) without duplicating code. */ #ifndef __NEXUS__COMMON__INC__CRC_CCITT_H_ #define __NEXUS__COMMON__INC__CRC_CCITT_H_ #include <stdint.h> #ifdef __cplusplus extern "C" { #endif /* Returns the 16-bit CRC CCITT value for an arbitrary * length of bytes. Assumptions: * * CRC Polynomial = 0x1021 * Initial CRC Value = 0xffff * Final XOR value = 0 * * Sample Input Data: * {0x31,0x32,0x33,0x34,0x35,0x36,0x37,0x38,0x39} (1-9 in ASCII) * Sample Output CRC: 0x29B1 */ uint16_t compute_crc_ccitt(void* bytes, uint8_t bytes_length); #ifdef __cplusplus } #endif #endif
<filename>src/include/panda/parsers/parser_big.h /* SPDX-License-Identifier: BSD-2-Clause-FreeBSD * * Copyright (c) 2020,2021 SiPanda Inc. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #ifndef __PANDA_PARSER_BIG_H__ #define __PANDA_PARSER_BIG_H__ /* Big parser definitions * * Big parser attempts to parse the and retrieve metadata for all of the * common PANDA protocol and metadata extractions. */ #include <linux/types.h> #include <unistd.h> #include "panda/parser_metadata.h" /* Meta data structure for multiple frames (i.e. to retrieve metadata * for multiple levels of encapsulation) */ struct panda_parser_big_metadata { struct panda_metadata panda_data; struct panda_metadata_all frame[0]; }; /* Meta data structure for just one frame */ struct panda_parser_big_metadata_one { struct panda_metadata panda_data; struct panda_metadata_all frame; }; /* Externs for parsers defined by big parsers. Note there are two parser, * one to parse a packet containing an Ethernet header, and one containing * and IP header. */ PANDA_PARSER_EXTERN(panda_parser_big_ether); PANDA_PARSER_EXTERN(panda_parser_big_ip); /* Externs for optimized parsers defined by big parsers */ PANDA_PARSER_EXTERN(panda_parser_big_ether_opt); PANDA_PARSER_EXTERN(panda_parser_big_ip_opt); void panda_parser_big_print_frame(struct panda_metadata_all *frame); void panda_parser_big_print_hash_input(struct panda_metadata_all *frame); #define PANDA_PARSER_BIG_ENCAP_DEPTH 4 /* Utility functions for various ways to parse packets and compute packet * hashes using the parsers for big parser */ /* Parse packet starting with Ethernet header */ static inline bool panda_parser_big_parse_ether(void *p, size_t len, struct panda_parser_big_metadata *mdata) { return (panda_parse(panda_parser_big_ether, p, len, &mdata->panda_data, 0, PANDA_PARSER_BIG_ENCAP_DEPTH) == PANDA_STOP_OKAY); } /* Parse packet starting with a known layer 3 protocol. Determine start * node by performing a protocol look up on the root node of the Ethernet * parser (i.e. get the start node by looking up the Ethertype in the * Ethernet protocol table) */ bool panda_parser_big_parse_l3(void *p, size_t len, __be16 proto, struct panda_parser_big_metadata *mdata); /* Parse packet starting with IP header. Root node distinguished based * on IP version number */ static inline bool panda_parser_big_parse_ip(void *p, size_t len, struct panda_parser_big_metadata *mdata) { return (panda_parse(panda_parser_big_ip, p, len, &mdata->panda_data, 0, PANDA_PARSER_BIG_ENCAP_DEPTH) == PANDA_STOP_OKAY); } /* Produce canonical hash from frame contents */ static inline __u32 panda_parser_big_hash_frame( struct panda_metadata_all *frame) { PANDA_HASH_CONSISTENTIFY(frame); return PANDA_COMMON_COMPUTE_HASH(frame, PANDA_HASH_START_FIELD_ALL); } /* Return hash for packet starting with Ethernet header */ static inline __u32 panda_parser_big_hash_ether(void *p, size_t len) { struct panda_parser_big_metadata_one mdata; memset(&mdata, 0, sizeof(mdata)); if (panda_parser_big_parse_ether(p, len, (struct panda_parser_big_metadata *)&mdata)) return panda_parser_big_hash_frame(&mdata.frame); return 0; } /* Return hash for a packet starting with the indicated layer 3 protocols * (i.e. an EtherType) */ static inline __u32 panda_parser_big_hash_l3(void *p, size_t len, __be16 proto) { struct panda_parser_big_metadata_one mdata; memset(&mdata, 0, sizeof(mdata)); mdata.frame.eth_proto = proto; if (panda_parser_big_parse_l3(p, len, proto, (struct panda_parser_big_metadata *)&mdata)) return panda_parser_big_hash_frame(&mdata.frame); return 0; } /* Return hash for packet starting with in IP header header (IPv4 or * IPv6 distinguished by inspecting IP version number */ static inline __u32 panda_parser_big_hash_ip(void *p, size_t len) { struct panda_parser_big_metadata_one mdata; memset(&mdata, 0, sizeof(mdata)); if (panda_parser_big_parse_ip(p, len, (struct panda_parser_big_metadata *)&mdata)) return panda_parser_big_hash_frame(&mdata.frame); return 0; } #endif /* __PANDA_PARSER_BIG_H__ */
/* Generated by RuntimeBrowser Image: /System/Library/PrivateFrameworks/Network.framework/Network */ @interface NWEndpoint : NSObject <NSCopying, NSSecureCoding, NWPrettyDescription> { NSObject<OS_nw_endpoint> * _internalEndpoint; } @property (nonatomic, retain) NWInterface *interface; @property (nonatomic, retain) NSObject<OS_nw_endpoint> *internalEndpoint; @property (nonatomic, retain) NSString *parentEndpointDomain; @property (nonatomic, readonly, copy) NSString *privateDescription; @property (nonatomic, retain) NSData *txtRecord; + (Class)classForEndpointType:(int)arg1; + (unsigned int)endpointType; + (id)endpointWithCEndpoint:(id)arg1; + (id)endpointWithInternalEndpoint:(id)arg1; + (bool)supportsResolverCallback; + (bool)supportsSecureCoding; - (void).cxx_destruct; - (id)copyCEndpoint; - (id)copyWithZone:(struct _NSZone { }*)arg1; - (id)description; - (id)descriptionWithIndent:(int)arg1 showFullContent:(bool)arg2; - (void)encodeWithCoder:(id)arg1; - (id)encodedData; - (id)initWithCoder:(id)arg1; - (id)initWithEncodedData:(id)arg1; - (id)initWithEndpoint:(id)arg1; - (id)interface; - (id)internalEndpoint; - (id)parentEndpointDomain; - (id)privateDescription; - (void)resolveEndpointWithCompletionHandler:(id /* block */)arg1; - (void)setInterface:(id)arg1; - (void)setInternalEndpoint:(id)arg1; - (void)setParentEndpointDomain:(id)arg1; - (void)setTxtRecord:(id)arg1; - (id)txtRecord; @end