diff --git a/pool/shard010/C/0138063_exp2.c b/pool/shard010/C/0138063_exp2.c new file mode 100644 index 0000000000000000000000000000000000000000..03060f9a80a4197f07a1e49fab352b1250fe4cd6 --- /dev/null +++ b/pool/shard010/C/0138063_exp2.c @@ -0,0 +1,184 @@ +/* mpfr_exp2 -- power of 2 function 2^y + +Copyright 2001-2021 Free Software Foundation, Inc. +Contributed by the AriC and Caramba projects, INRIA. + +This file is part of the GNU MPFR Library. + +The GNU MPFR Library is free software; you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation; either version 3 of the License, or (at your +option) any later version. + +The GNU MPFR Library is distributed in the hope that it will be useful, but +WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY +or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public +License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with the GNU MPFR Library; see the file COPYING.LESSER. If not, see +https://www.gnu.org/licenses/ or write to the Free Software Foundation, Inc., +51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. */ + +#define MPFR_NEED_LONGLONG_H +#include "mpfr-impl.h" + +/* TODO: mpfr_get_exp_t is called 3 times, with 3 different directed + rounding modes. One could reduce it to only one call thanks to the + inexact flag, but is it worth? */ + +/* Convert x to an mpfr_eexp_t integer, with saturation at the minimum + and maximum values. Flags are unchanged. */ +static mpfr_eexp_t +round_to_eexp_t (mpfr_srcptr x, mpfr_rnd_t rnd_mode) +{ + mpfr_flags_t flags = __gmpfr_flags; + mpfr_eexp_t e; + + e = mpfr_get_exp_t (x, rnd_mode); + __gmpfr_flags = flags; + return e; +} + +/* The computation of y = 2^z is done by * + * y = exp(z*log(2)). The result is exact iff z is an integer. */ + +int +mpfr_exp2 (mpfr_ptr y, mpfr_srcptr x, mpfr_rnd_t rnd_mode) +{ + int inexact; + mpfr_eexp_t xint; /* note: will fit in mpfr_exp_t */ + mpfr_t xfrac; + MPFR_SAVE_EXPO_DECL (expo); + + MPFR_LOG_FUNC + (("x[%Pu]=%.*Rg rnd=%d", mpfr_get_prec(x), mpfr_log_prec, x, rnd_mode), + ("y[%Pu]=%.*Rg inexact=%d", mpfr_get_prec(y), mpfr_log_prec, y, + inexact)); + + if (MPFR_UNLIKELY (MPFR_IS_SINGULAR (x))) + { + if (MPFR_IS_NAN (x)) + { + MPFR_SET_NAN (y); + MPFR_RET_NAN; + } + else if (MPFR_IS_INF (x)) + { + if (MPFR_IS_POS (x)) + MPFR_SET_INF (y); + else + MPFR_SET_ZERO (y); + MPFR_SET_POS (y); + MPFR_RET (0); + } + else /* 2^0 = 1 */ + { + MPFR_ASSERTD (MPFR_IS_ZERO(x)); + return mpfr_set_ui (y, 1, rnd_mode); + } + } + + /* Since the smallest representable non-zero float is 1/2 * 2^emin, + if x <= emin - 2, the result is either 1/2 * 2^emin or 0. + Warning, for emin - 2 < x < emin - 1, we cannot conclude, since 2^x + might round to 2^(emin - 1) for rounding away or to nearest, and there + might be no underflow, since we consider underflow "after rounding". */ + + if (MPFR_UNLIKELY (round_to_eexp_t (x, MPFR_RNDU) <= __gmpfr_emin - 2)) + return mpfr_underflow (y, rnd_mode == MPFR_RNDN ? MPFR_RNDZ : rnd_mode, 1); + + if (MPFR_UNLIKELY (round_to_eexp_t (x, MPFR_RNDD) >= __gmpfr_emax)) + return mpfr_overflow (y, rnd_mode, 1); + + /* We now know that emin - 2 < x < emax. Note that an underflow or + overflow is still possible (we have eliminated only easy cases). */ + + MPFR_SAVE_EXPO_MARK (expo); + + /* 2^x = 1 + x*log(2) + O(x^2) for x near zero, and for |x| <= 1 we have + |2^x - 1| <= x < 2^EXP(x). If x > 0 we must round away from 0 (dir=1); + if x < 0 we must round toward 0 (dir=0). */ + MPFR_SMALL_INPUT_AFTER_SAVE_EXPO (y, __gmpfr_one, - MPFR_GET_EXP (x), 0, + MPFR_IS_POS (x), rnd_mode, expo, {}); + + xint = mpfr_get_exp_t (x, MPFR_RNDZ); + MPFR_ASSERTD (__gmpfr_emin - 2 < xint && xint < __gmpfr_emax); + + mpfr_init2 (xfrac, MPFR_PREC (x)); + MPFR_DBGRES (inexact = mpfr_frac (xfrac, x, MPFR_RNDN)); + MPFR_ASSERTD (inexact == 0); + + if (MPFR_IS_ZERO (xfrac)) + { + /* Here, emin - 1 <= x <= emax - 1, so that an underflow or overflow + will not be possible. */ + mpfr_set_ui (y, 1, MPFR_RNDN); + inexact = 0; + } + else + { + /* Declaration of the intermediary variable */ + mpfr_t t; + + /* Declaration of the size variable */ + mpfr_prec_t Ny = MPFR_PREC(y); /* target precision */ + mpfr_prec_t Nt; /* working precision */ + mpfr_exp_t err; /* error */ + MPFR_ZIV_DECL (loop); + + /* compute the precision of intermediary variable */ + /* the optimal number of bits : see algorithms.tex */ + Nt = Ny + 5 + MPFR_INT_CEIL_LOG2 (Ny); + + /* initialize of intermediary variable */ + mpfr_init2 (t, Nt); + + /* First computation */ + MPFR_ZIV_INIT (loop, Nt); + for (;;) + { + /* compute exp(x*ln(2))*/ + mpfr_const_log2 (t, MPFR_RNDU); /* ln(2) */ + mpfr_mul (t, xfrac, t, MPFR_RNDU); /* xfrac * ln(2) */ + err = Nt - (MPFR_GET_EXP (t) + 2); /* Estimate of the error */ + mpfr_exp (t, t, MPFR_RNDN); /* exp(xfrac * ln(2)) */ + + if (MPFR_LIKELY (MPFR_CAN_ROUND (t, err, Ny, rnd_mode))) + break; + + /* Actualisation of the precision */ + MPFR_ZIV_NEXT (loop, Nt); + mpfr_set_prec (t, Nt); + } + MPFR_ZIV_FREE (loop); + + inexact = mpfr_set (y, t, rnd_mode); + + mpfr_clear (t); + } + + mpfr_clear (xfrac); + + if (MPFR_UNLIKELY (rnd_mode == MPFR_RNDN && xint == __gmpfr_emin - 1 && + MPFR_GET_EXP (y) == 0 && mpfr_powerof2_raw (y))) + { + /* y was rounded down to 1/2 and the rounded value with an unbounded + exponent range would be 2^(emin-2), i.e. the midpoint between 0 + and the smallest positive FP number. This is a double rounding + problem: we should not round to 0, but to (1/2) * 2^emin. */ + MPFR_SET_EXP (y, __gmpfr_emin); + inexact = 1; + MPFR_SAVE_EXPO_UPDATE_FLAGS (expo, MPFR_FLAGS_UNDERFLOW); + } + else + { + /* The following is OK due to early overflow/underflow checking. + the exponent may be slightly out-of-range, but this will be + handled by mpfr_check_range. */ + MPFR_EXP (y) += xint; + } + + MPFR_SAVE_EXPO_FREE (expo); + return mpfr_check_range (y, inexact, rnd_mode); +} diff --git a/pool/shard010/C/0138064_dev_led_pwm.c b/pool/shard010/C/0138064_dev_led_pwm.c new file mode 100644 index 0000000000000000000000000000000000000000..6f1dad8924ba01aa46cc12d27a0698413401734e --- /dev/null +++ b/pool/shard010/C/0138064_dev_led_pwm.c @@ -0,0 +1,117 @@ +/* + * The MIT License (MIT) + * + * Copyright (c) 2016 Nels D. "Chip" Pearson (aka CmdrZin) + * + * 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. + * + * dev_led_1.c + * + * Created: 2/24/2016 0.01 ndp + * Author: Chip + */ + +#include +#include +#include + +#include "sysTimer.h" +#include "access.h" + +#include "dev_led_pwm.h" + +#define DEMO_BOARD 0 // Use for testing. Set to 0 for proto-board set up. + +bool dlp_state; +int dlp_rate; +int dlp_rateAdjust; // Controls how fast the glow cycles. + +void dev_led_pwm_init() +{ + dlp_state = false; + dlp_rate = 0; + dlp_rateAdjust = 4; + + DEV_LED_PWM_DDR |= (1< 0x03FF ) + dlp_rate = 0; + } +} + +ISR( TIMER1_OVF_vect ) +{ + OCR1A = dlp_rate; +} diff --git a/pool/shard010/C/0138065_mpc85xx_ads.c b/pool/shard010/C/0138065_mpc85xx_ads.c new file mode 100644 index 0000000000000000000000000000000000000000..8ed034aeca5f139acfac1875e6a3a19058b4c8e6 --- /dev/null +++ b/pool/shard010/C/0138065_mpc85xx_ads.c @@ -0,0 +1,290 @@ +/* + * MPC85xx setup and early boot code plus other random bits. + * + * Maintained by Kumar Gala (see MAINTAINERS for contact information) + * + * Copyright 2005 Freescale Semiconductor Inc. + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the + * Free Software Foundation; either version 2 of the License, or (at your + * option) any later version. + */ + +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include "mpc85xx.h" + +#ifdef CONFIG_CPM2 +#include +#include +#include +#include +#endif + +#ifndef CONFIG_PCI +unsigned long isa_io_base = 0; +unsigned long isa_mem_base = 0; +#endif + +#ifdef CONFIG_PCI +static int mpc85xx_exclude_device(u_char bus, u_char devfn) +{ + if (bus == 0 && PCI_SLOT(devfn) == 0) + return PCIBIOS_DEVICE_NOT_FOUND; + else + return PCIBIOS_SUCCESSFUL; +} +#endif /* CONFIG_PCI */ + +#ifdef CONFIG_CPM2 + +static void cpm2_cascade(unsigned int irq, struct irq_desc *desc) +{ + int cascade_irq; + + while ((cascade_irq = cpm2_get_irq()) >= 0) { + generic_handle_irq(cascade_irq); + } + desc->chip->eoi(irq); +} + +#endif /* CONFIG_CPM2 */ + +static void __init mpc85xx_ads_pic_init(void) +{ + struct mpic *mpic; + struct resource r; + struct device_node *np = NULL; +#ifdef CONFIG_CPM2 + int irq; +#endif + + np = of_find_node_by_type(np, "open-pic"); + + if (np == NULL) { + printk(KERN_ERR "Could not find open-pic node\n"); + return; + } + + if(of_address_to_resource(np, 0, &r)) { + printk(KERN_ERR "Could not map mpic register space\n"); + of_node_put(np); + return; + } + + mpic = mpic_alloc(np, r.start, + MPIC_PRIMARY | MPIC_WANTS_RESET | MPIC_BIG_ENDIAN, + 4, 0, " OpenPIC "); + BUG_ON(mpic == NULL); + of_node_put(np); + + mpic_assign_isu(mpic, 0, r.start + 0x10200); + mpic_assign_isu(mpic, 1, r.start + 0x10280); + mpic_assign_isu(mpic, 2, r.start + 0x10300); + mpic_assign_isu(mpic, 3, r.start + 0x10380); + mpic_assign_isu(mpic, 4, r.start + 0x10400); + mpic_assign_isu(mpic, 5, r.start + 0x10480); + mpic_assign_isu(mpic, 6, r.start + 0x10500); + mpic_assign_isu(mpic, 7, r.start + 0x10580); + + /* Unused on this platform (leave room for 8548) */ + mpic_assign_isu(mpic, 8, r.start + 0x10600); + mpic_assign_isu(mpic, 9, r.start + 0x10680); + mpic_assign_isu(mpic, 10, r.start + 0x10700); + mpic_assign_isu(mpic, 11, r.start + 0x10780); + + /* External Interrupts */ + mpic_assign_isu(mpic, 12, r.start + 0x10000); + mpic_assign_isu(mpic, 13, r.start + 0x10080); + mpic_assign_isu(mpic, 14, r.start + 0x10100); + + mpic_init(mpic); + +#ifdef CONFIG_CPM2 + /* Setup CPM2 PIC */ + np = of_find_node_by_type(NULL, "cpm-pic"); + if (np == NULL) { + printk(KERN_ERR "PIC init: can not find cpm-pic node\n"); + return; + } + irq = irq_of_parse_and_map(np, 0); + + cpm2_pic_init(np); + set_irq_chained_handler(irq, cpm2_cascade); +#endif +} + +/* + * Setup the architecture + */ +#ifdef CONFIG_CPM2 +void init_fcc_ioports(struct fs_platform_info *fpi) +{ + struct io_port *io = cpm2_map(im_ioport); + int fcc_no = fs_get_fcc_index(fpi->fs_no); + int target; + u32 tempval; + + switch(fcc_no) { + case 1: + tempval = in_be32(&io->iop_pdirb); + tempval &= ~PB2_DIRB0; + tempval |= PB2_DIRB1; + out_be32(&io->iop_pdirb, tempval); + + tempval = in_be32(&io->iop_psorb); + tempval &= ~PB2_PSORB0; + tempval |= PB2_PSORB1; + out_be32(&io->iop_psorb, tempval); + + tempval = in_be32(&io->iop_pparb); + tempval |= (PB2_DIRB0 | PB2_DIRB1); + out_be32(&io->iop_pparb, tempval); + + target = CPM_CLK_FCC2; + break; + case 2: + tempval = in_be32(&io->iop_pdirb); + tempval &= ~PB3_DIRB0; + tempval |= PB3_DIRB1; + out_be32(&io->iop_pdirb, tempval); + + tempval = in_be32(&io->iop_psorb); + tempval &= ~PB3_PSORB0; + tempval |= PB3_PSORB1; + out_be32(&io->iop_psorb, tempval); + + tempval = in_be32(&io->iop_pparb); + tempval |= (PB3_DIRB0 | PB3_DIRB1); + out_be32(&io->iop_pparb, tempval); + + tempval = in_be32(&io->iop_pdirc); + tempval |= PC3_DIRC1; + out_be32(&io->iop_pdirc, tempval); + + tempval = in_be32(&io->iop_pparc); + tempval |= PC3_DIRC1; + out_be32(&io->iop_pparc, tempval); + + target = CPM_CLK_FCC3; + break; + default: + printk(KERN_ERR "init_fcc_ioports: invalid FCC number\n"); + return; + } + + /* Port C has clocks...... */ + tempval = in_be32(&io->iop_psorc); + tempval &= ~(PC_CLK(fpi->clk_rx - 8) | PC_CLK(fpi->clk_tx - 8)); + out_be32(&io->iop_psorc, tempval); + + tempval = in_be32(&io->iop_pdirc); + tempval &= ~(PC_CLK(fpi->clk_rx - 8) | PC_CLK(fpi->clk_tx - 8)); + out_be32(&io->iop_pdirc, tempval); + tempval = in_be32(&io->iop_pparc); + tempval |= (PC_CLK(fpi->clk_rx - 8) | PC_CLK(fpi->clk_tx - 8)); + out_be32(&io->iop_pparc, tempval); + + cpm2_unmap(io); + + /* Configure Serial Interface clock routing. + * First, clear FCC bits to zero, + * then set the ones we want. + */ + cpm2_clk_setup(target, fpi->clk_rx, CPM_CLK_RX); + cpm2_clk_setup(target, fpi->clk_tx, CPM_CLK_TX); +} +#endif + +static void __init mpc85xx_ads_setup_arch(void) +{ + struct device_node *cpu; +#ifdef CONFIG_PCI + struct device_node *np; +#endif + + if (ppc_md.progress) + ppc_md.progress("mpc85xx_ads_setup_arch()", 0); + + cpu = of_find_node_by_type(NULL, "cpu"); + if (cpu != 0) { + const unsigned int *fp; + + fp = get_property(cpu, "clock-frequency", NULL); + if (fp != 0) + loops_per_jiffy = *fp / HZ; + else + loops_per_jiffy = 50000000 / HZ; + of_node_put(cpu); + } + +#ifdef CONFIG_CPM2 + cpm2_reset(); +#endif + +#ifdef CONFIG_PCI + for (np = NULL; (np = of_find_node_by_type(np, "pci")) != NULL;) + add_bridge(np); + ppc_md.pci_exclude_device = mpc85xx_exclude_device; +#endif +} + +static void mpc85xx_ads_show_cpuinfo(struct seq_file *m) +{ + uint pvid, svid, phid1; + uint memsize = total_memory; + + pvid = mfspr(SPRN_PVR); + svid = mfspr(SPRN_SVR); + + seq_printf(m, "Vendor\t\t: Freescale Semiconductor\n"); + seq_printf(m, "Machine\t\t: mpc85xx\n"); + seq_printf(m, "PVR\t\t: 0x%x\n", pvid); + seq_printf(m, "SVR\t\t: 0x%x\n", svid); + + /* Display cpu Pll setting */ + phid1 = mfspr(SPRN_HID1); + seq_printf(m, "PLL setting\t: 0x%x\n", ((phid1 >> 24) & 0x3f)); + + /* Display the amount of memory */ + seq_printf(m, "Memory\t\t: %d MB\n", memsize / (1024 * 1024)); +} + +/* + * Called very early, device-tree isn't unflattened + */ +static int __init mpc85xx_ads_probe(void) +{ + unsigned long root = of_get_flat_dt_root(); + + return of_flat_dt_is_compatible(root, "MPC85xxADS"); +} + +define_machine(mpc85xx_ads) { + .name = "MPC85xx ADS", + .probe = mpc85xx_ads_probe, + .setup_arch = mpc85xx_ads_setup_arch, + .init_IRQ = mpc85xx_ads_pic_init, + .show_cpuinfo = mpc85xx_ads_show_cpuinfo, + .get_irq = mpic_get_irq, + .restart = mpc85xx_restart, + .calibrate_decr = generic_calibrate_decr, + .progress = udbg_progress, +}; diff --git a/pool/shard010/C/0138066_gnu_java_awt_peer_gtk_GtkClipboard.c b/pool/shard010/C/0138066_gnu_java_awt_peer_gtk_GtkClipboard.c new file mode 100644 index 0000000000000000000000000000000000000000..e05185790b3e7934a09c2474feae080b7ca3c616 --- /dev/null +++ b/pool/shard010/C/0138066_gnu_java_awt_peer_gtk_GtkClipboard.c @@ -0,0 +1,183 @@ +/* gtkclipboard.c + Copyright (C) 1998, 1999 Free Software Foundation, Inc. + +This file is part of GNU Classpath. + +GNU Classpath 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, or (at your option) +any later version. + +GNU Classpath 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 GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA +02111-1307 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + + +#include "gtkpeer.h" +#include "gnu_java_awt_peer_gtk_GtkClipboard.h" + +jmethodID stringSelectionReceivedID; +jmethodID stringSelectionHandlerID; +jmethodID selectionClearID; + +void selection_received (GtkWidget *, GtkSelectionData *, guint, gpointer); +void selection_get (GtkWidget *, GtkSelectionData *, guint, guint, gpointer); +gint selection_clear (GtkWidget *, GdkEventSelection *); + +GtkWidget *clipboard; +jobject cb_obj; + +JNIEXPORT void JNICALL +Java_gnu_java_awt_peer_gtk_GtkClipboard_initNativeState (JNIEnv *env, + jobject obj) +{ + if (!stringSelectionReceivedID) + { + jclass gtkclipboard; + + gtkclipboard = (*env)->FindClass (env, + "gnu/java/awt/peer/gtk/GtkClipboard"); + stringSelectionReceivedID = (*env)->GetMethodID (env, gtkclipboard, + "stringSelectionReceived", + "(Ljava/lang/String;)V"); + stringSelectionHandlerID = (*env)->GetMethodID (env, gtkclipboard, + "stringSelectionHandler", + "()Ljava/lang/String;"); + selectionClearID = (*env)->GetMethodID (env, gtkclipboard, + "selectionClear", "()V"); + } + + cb_obj = (*env)->NewGlobalRef (env, obj); + + gdk_threads_enter (); + clipboard = gtk_window_new (GTK_WINDOW_TOPLEVEL); + + g_signal_connect (G_OBJECT(clipboard), "selection_received", + GTK_SIGNAL_FUNC (selection_received), NULL); + + g_signal_connect (G_OBJECT(clipboard), "selection_clear_event", + GTK_SIGNAL_FUNC (selection_clear), NULL); + + gtk_selection_add_target (clipboard, GDK_SELECTION_PRIMARY, + GDK_TARGET_STRING, 0); + + g_signal_connect (G_OBJECT(clipboard), "selection_get", + GTK_SIGNAL_FUNC (selection_get), NULL); + + gdk_threads_leave (); +} + +JNIEXPORT void JNICALL +Java_gnu_java_awt_peer_gtk_GtkClipboard_requestStringConversion + (JNIEnv *env __attribute__((unused)), jclass clazz __attribute__((unused))) +{ + gdk_threads_enter (); + gtk_selection_convert (clipboard, GDK_SELECTION_PRIMARY, + GDK_TARGET_STRING, GDK_CURRENT_TIME); + gdk_threads_leave (); +} + +void +selection_received (GtkWidget *widget __attribute__((unused)), + GtkSelectionData *selection_data __attribute__((unused)), + guint time __attribute__((unused)), + gpointer data __attribute__((unused))) +{ + /* Check to see if retrieval succeeded */ + if (selection_data->length < 0 + || selection_data->type != GDK_SELECTION_TYPE_STRING) + { + (*gdk_env())->CallVoidMethod (gdk_env(), cb_obj, stringSelectionReceivedID, + NULL); + } + else + { + char *str = (char *) selection_data->data; + + (*gdk_env())->CallVoidMethod (gdk_env(), cb_obj, stringSelectionReceivedID, + (*gdk_env())->NewStringUTF (gdk_env(), str)); + } + + return; +} + +void +selection_get (GtkWidget *widget __attribute__((unused)), + GtkSelectionData *selection_data, + guint info __attribute__((unused)), + guint time __attribute__((unused)), + gpointer data __attribute__((unused))) +{ + jstring jstr; + const char *utf; + jsize utflen; + + jstr = (*gdk_env())->CallObjectMethod (gdk_env(), cb_obj, + stringSelectionHandlerID); + + if (!jstr) + { + gtk_selection_data_set (selection_data, + GDK_TARGET_STRING, 8, NULL, 0); + return; + } + + utflen = (*gdk_env())->GetStringUTFLength (gdk_env(), jstr); + utf = (*gdk_env())->GetStringUTFChars (gdk_env(), jstr, NULL); + + gtk_selection_data_set (selection_data, GDK_TARGET_STRING, 8, + (const unsigned char*)utf, utflen); + + (*gdk_env())->ReleaseStringUTFChars (gdk_env(), jstr, utf); +} + +JNIEXPORT void JNICALL +Java_gnu_java_awt_peer_gtk_GtkClipboard_selectionGet + (JNIEnv *env, jclass clazz __attribute__((unused))) +{ + GdkWindow *owner; + + gdk_threads_enter (); + + /* if we already own the clipboard, we need to tell the old data object + that we're no longer going to be using him */ + owner = gdk_selection_owner_get (GDK_SELECTION_PRIMARY); + if (owner && owner == clipboard->window) + (*env)->CallVoidMethod (env, cb_obj, selectionClearID); + + gtk_selection_owner_set (clipboard, GDK_SELECTION_PRIMARY, GDK_CURRENT_TIME); + + gdk_threads_leave (); +} + +gint +selection_clear (GtkWidget *widget __attribute__((unused)), + GdkEventSelection *event __attribute__((unused))) +{ + (*gdk_env())->CallVoidMethod (gdk_env(), cb_obj, selectionClearID); + + return TRUE; +} diff --git a/pool/shard010/C/0138067_string.c b/pool/shard010/C/0138067_string.c new file mode 100644 index 0000000000000000000000000000000000000000..7ca4f582d8892fa38c73e1e84a2845cde7f70ac9 --- /dev/null +++ b/pool/shard010/C/0138067_string.c @@ -0,0 +1,277 @@ +#include +#include +#include +#include +#include +#include "util/memory.h" +#include "util/string.h" + +/* ---------------------------------------------------------------------------- + * Static functions + * ------------------------------------------------------------------------- */ +static uintptr_t +safe_strlen(const char* str) +{ + if(str) + return strlen(str); + return 0; +} + +/* ------------------------------------------------------------------------- */ +static void +safe_strcat(char* target, const char* source) +{ + assert(target); + if(source) + strcat(target, source); +} + +/* ------------------------------------------------------------------------- */ +static uintptr_t +safe_wcslen(const wchar_t* wcs) +{ + if(wcs) + return wcslen(wcs); + return 0; +} + +/* ------------------------------------------------------------------------- */ +static void +safe_wcscat(wchar_t* target, const wchar_t* source) +{ + assert(target); + if(source) + wcscat(target, source); +} + +/* ---------------------------------------------------------------------------- + * Exported functions + * ------------------------------------------------------------------------- */ +void +free_string(void* ptr) +{ + assert(ptr); + FREE(ptr); +} + +/* ------------------------------------------------------------------------- */ +char* +cat_strings(uint32_t num_strs, ...) +{ + uint32_t total_length = 0; + uint32_t i; + char* buffer; + va_list ap; + + /* compute total length of all strings combined and allocate a buffer able + * to contain all strings plus a null terminator */ + va_start(ap, num_strs); + for(i = 0; i != num_strs; ++i) + total_length += safe_strlen(va_arg(ap, char*)); + va_end(ap); + + buffer = (char*)MALLOC((total_length+1) * sizeof(char)); + if(!buffer) + { + fprintf(stderr, "malloc() failed in cat_strings() -- not enough memory\n"); + return NULL; + } + *buffer = '\0'; /* so strcat works */ + + /* concatenate all strings into the allocated buffer */ + va_start(ap, num_strs); + for(i = 0; i != num_strs; ++i) + safe_strcat(buffer, va_arg(ap, char*)); + va_end(ap); + + return buffer; +} + +/* ------------------------------------------------------------------------- */ +char* +malloc_string(const char* str) +{ + char* buffer; + assert(str); + + buffer = (char*)MALLOC((strlen(str)+1) * sizeof(char)); + if(!buffer) + { + fprintf(stderr, "malloc() failed in malloc_string() -- not enough memory\n"); + return NULL; + } + + strcpy(buffer, str); + return buffer; +} + +/* ------------------------------------------------------------------------- */ +wchar_t* +cat_wstrings(uint32_t num_strs, ...) +{ + uint32_t total_length = 0; + uint32_t i; + wchar_t* buffer; + va_list ap; + + /* compute total length of all strings combined and allocate a buffer able + * to contain all strings plus a null terminator */ + va_start(ap, num_strs); + for(i = 0; i != num_strs; ++i) + total_length += safe_wcslen(va_arg(ap, wchar_t*)); + va_end(ap); + + buffer = (wchar_t*)MALLOC((total_length+1) * sizeof(wchar_t)); + if(!buffer) + { + fprintf(stderr, "malloc() failed in cat_wstrings() -- not enough memory\n"); + return NULL; + } + *buffer = L'\0'; /* so wcscat works */ + + /* concatenate all strings into the allocated buffer */ + va_start(ap, num_strs); + for(i = 0; i != num_strs; ++i) + safe_wcscat(buffer, va_arg(ap, wchar_t*)); + va_end(ap); + + return buffer; +} + +/* ------------------------------------------------------------------------- */ +wchar_t* +malloc_wstring(const wchar_t* wcs) +{ + wchar_t* buffer; + assert(wcs); + + buffer = (wchar_t*)MALLOC((wcslen(wcs)+1) * sizeof(wchar_t)); + if(!buffer) + { + fprintf(stderr, "malloc() failed in malloc_wstring() -- not enough memory\n"); + return NULL; + } + + wcscpy(buffer, wcs); + return buffer; +} + +/* ------------------------------------------------------------------------- */ +char* +strtok_r_portable(char* str, char delimiter, char** saveptr) +{ + char* begin_ptr; + char* end_ptr; + + if(str) + *saveptr = str - 1; + + /* no more tokens */ + if(!*saveptr) + return NULL; + + /* get first occurrence of token in string */ + begin_ptr = *saveptr + 1; + end_ptr = (char*)strchr(begin_ptr, delimiter); + if(!end_ptr) + *saveptr = NULL; /* last token has been reached */ + else + { + /* update saveptr and replace delimiter with null terminator */ + *saveptr = end_ptr; + **saveptr = '\0'; + } + + /* empty tokens */ + if(*begin_ptr == '\0') + return NULL; + return begin_ptr; +} + +/* ------------------------------------------------------------------------- */ +wchar_t* +strtowcs(const char* str) +{ + wchar_t* wcs; + wchar_t* wcs_it; + uintptr_t len; + + assert(str); + + len = strlen(str); + + wcs = (wchar_t*)MALLOC((len + 1) * sizeof(wchar_t)); + if(!wcs) + { + fprintf(stderr, "malloc() failed in strtowcs() -- not enough memory\n"); + return NULL; + } + + for(wcs_it = wcs; *str; ++str) + *wcs_it++ = (wchar_t)*str; + *wcs_it = L'\0'; + return wcs; +} + +/* ------------------------------------------------------------------------- */ +char* +wcstostr(const wchar_t* wcs) +{ + char* str; + char* str_it; + uintptr_t len; + + assert(wcs); + + len = wcslen(wcs); + + str = (char*)MALLOC((len + 1) * sizeof(char)); + if(!str) + { + fprintf(stderr, "malloc() failed in wcstostr() -- not enough memory\n"); + return NULL; + } + + for(str_it = str; *wcs; ++wcs) + *str_it++ = (char)*wcs; + *str_it = '\0'; + return str; +} + +/* ------------------------------------------------------------------------- */ +void +crlf2lf(char* src) +{ + char* target; + + assert(src); + + target = src; + while(*src) + { + if(*src == '\r') /* skip any CRs */ + ++src; + *target++ = *src++; + } + + /* if at least one CR was skipped, a new null-terminator must be set. */ + if(target != src) + *target = '\0'; +} + +/* ------------------------------------------------------------------------- */ +void +string_reverse(char* str) +{ + char* end; + + assert(str); + + end = str + strlen(str) - 1; + for(; str < end; ++str, --end) + { + char tmp = *str; + *str = *end; + *end = tmp; + } +} diff --git a/pool/shard010/C/0138068_getValidInteger.c b/pool/shard010/C/0138068_getValidInteger.c new file mode 100644 index 0000000000000000000000000000000000000000..c05835911fb6a411ee7553be9408e2f89b9ea1b7 --- /dev/null +++ b/pool/shard010/C/0138068_getValidInteger.c @@ -0,0 +1,103 @@ +/* + * Filename: getValidInteger.c + * Author: Andrew Laing + * Email: parisianconnections@gmail.com + * Date: 19/08/2017. + * Description: Input an Integer + */ + +#include +#include +#include + +#define MAXLEN 9 + +int getLine( char [], int ); +int isValidIntegerString( const char * ); +int getValidInteger(); + + +int main() +{ + int num1; + + printf("Enter integer string > "); + num1 = getValidInteger(); + + printf("num1 = %d\n", num1); + + return 0; +} + + +/* Read a string into a character array and return the length of the array + * Note: this produces an error message if the user trys to overflow the + * the character array, but allows them to retype rather than crashing + */ +int getLine( char s[], int maxLength ) +{ + int c, count, i, validLine=0; + + while(validLine == 0) + { + count=0, i=0; + while( count <= maxLength && ( (c=getchar())!=EOF ) && ( c!='\n' ) ) + { + s[i++]=c; + count++; + } + + if( count > maxLength ) { + printf("Error - max line length is %d characters\n", maxLength ); + printf("Please retype line: "); + } + else validLine++; + + fflush(stdin); /* Clear any overflow*/ + } + + if(c=='\n') + s[i++]=c; + s[i] = '\0'; + + + fflush(stdin); /* Clear any overflow*/ + + return i; +} + + + +/* This method gets the user to input, then returns a valid integer + * Note: The maximum length of the integer is define as MAXLEN, and + * at the moment the method does not check that the string + * is within system integer boundaries. + + ** PROBLEM CAUSED BY SSCANF skipping SPACES + */ +int getValidInteger() +{ + char str[MAXLEN+1]; + int result = 0; + int validInt = 0; + + /* Input a string */ + getLine(str, MAXLEN); + + /* If the string is valid convert and return it */ + while(validInt == 0) + { + /* sscanf returns the number of conversions made */ + if( !isspace(str[0]) ) + validInt = sscanf(str, "%d", &result); + + if( validInt == 0 ) + { + printf("Error - Please enter a valid number: "); + getLine(str, MAXLEN); + } + } + + return result; +} + diff --git a/pool/shard010/C/0138069_H5Tdeprec.c b/pool/shard010/C/0138069_H5Tdeprec.c new file mode 100644 index 0000000000000000000000000000000000000000..c506ec101c05e61c52a2df2e96c583137e7ea551 --- /dev/null +++ b/pool/shard010/C/0138069_H5Tdeprec.c @@ -0,0 +1,205 @@ +/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * + * Copyright by The HDF Group. * + * Copyright by the Board of Trustees of the University of Illinois. * + * All rights reserved. * + * * + * This file is part of HDF5. The full HDF5 copyright notice, including * + * terms governing use, modification, and redistribution, is contained in * + * the COPYING file, which can be found at the root of the source code * + * distribution tree, or in https://support.hdfgroup.org/ftp/HDF5/releases. * + * If you do not have access to either file, you may request a copy from * + * help@hdfgroup.org. * + * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ + +/*------------------------------------------------------------------------- + * + * Created: H5Tdeprec.c + * April 5 2007 + * Quincey Koziol + * + * Purpose: Deprecated functions from the H5T interface. These + * functions are here for compatibility purposes and may be + * removed in the future. Applications should switch to the + * newer APIs. + * + *------------------------------------------------------------------------- + */ + +/****************/ +/* Module Setup */ +/****************/ + +#include "H5Tmodule.h" /* This source code file is part of the H5T module */ + + +/***********/ +/* Headers */ +/***********/ +#include "H5private.h" /* Generic Functions */ +#include "H5ACprivate.h" /* Metadata cache */ +#include "H5Eprivate.h" /* Error handling */ +#include "H5FOprivate.h" /* File objects */ +#include "H5Iprivate.h" /* IDs */ +#include "H5Ppublic.h" /* Property Lists */ +#include "H5Tpkg.h" /* Datatypes */ + + +/****************/ +/* Local Macros */ +/****************/ + + +/******************/ +/* Local Typedefs */ +/******************/ + + +/********************/ +/* Package Typedefs */ +/********************/ + + +/********************/ +/* Local Prototypes */ +/********************/ + + +/*********************/ +/* Package Variables */ +/*********************/ + + +/*****************************/ +/* Library Private Variables */ +/*****************************/ + + +/*******************/ +/* Local Variables */ +/*******************/ + + +#ifndef H5_NO_DEPRECATED_SYMBOLS + +/*------------------------------------------------------------------------- + * Function: H5Tcommit1 + * + * Purpose: Save a transient datatype to a file and turn the type handle + * into a named, immutable type. + * + * Note: Deprecated in favor of H5Tcommit2 + * + * Return: Non-negative on success/Negative on failure + * + * Programmer: Robb Matzke + * Monday, June 1, 1998 + * + *------------------------------------------------------------------------- + */ +herr_t +H5Tcommit1(hid_t loc_id, const char *name, hid_t type_id) +{ + H5G_loc_t loc; /* Location to create datatype */ + H5T_t *type; /* Datatype for ID */ + herr_t ret_value = SUCCEED; /* Return value */ + + FUNC_ENTER_API(FAIL) + H5TRACE3("e", "i*si", loc_id, name, type_id); + + /* Check arguments */ + if(H5G_loc(loc_id, &loc) < 0) + HGOTO_ERROR(H5E_ARGS, H5E_BADTYPE, FAIL, "not a location") + if(!name || !*name) + HGOTO_ERROR(H5E_ARGS, H5E_BADVALUE, FAIL, "no name") + if(NULL == (type = (H5T_t *)H5I_object_verify(type_id, H5I_DATATYPE))) + HGOTO_ERROR(H5E_ARGS, H5E_BADTYPE, FAIL, "not a datatype") + + /* Commit the datatype to the file, using default property list values */ + if(H5T__commit_named(&loc, name, type, H5P_LINK_CREATE_DEFAULT, + H5P_DATATYPE_CREATE_DEFAULT, H5P_DATATYPE_ACCESS_DEFAULT, H5AC_ind_read_dxpl_id) < 0) + HGOTO_ERROR(H5E_DATATYPE, H5E_CANTINIT, FAIL, "unable to commit datatype") + +done: + FUNC_LEAVE_API(ret_value) +} /* end H5Tcommit1() */ + + +/*------------------------------------------------------------------------- + * Function: H5Topen1 + * + * Purpose: Opens a named datatype. + * + * Note: Deprecated in favor of H5Topen2 + * + * Return: Success: Object ID of the named datatype. + * + * Failure: Negative + * + * Programmer: Robb Matzke + * Monday, June 1, 1998 + * + *------------------------------------------------------------------------- + */ +hid_t +H5Topen1(hid_t loc_id, const char *name) +{ + H5T_t *type = NULL; + H5G_loc_t loc; + H5G_name_t path; /* Datatype group hier. path */ + H5O_loc_t oloc; /* Datatype object location */ + H5O_type_t obj_type; /* Type of object at location */ + H5G_loc_t type_loc; /* Group object for datatype */ + hbool_t obj_found = FALSE; /* Object at 'name' found */ + hid_t dxpl_id = H5AC_ind_read_dxpl_id; /* dxpl to use to open datatype */ + hid_t ret_value = FAIL; + + FUNC_ENTER_API(FAIL) + H5TRACE2("i", "i*s", loc_id, name); + + /* Check args */ + if(H5G_loc(loc_id, &loc) < 0) + HGOTO_ERROR(H5E_ARGS, H5E_BADTYPE, FAIL, "not a location") + if(!name || !*name) + HGOTO_ERROR(H5E_ARGS, H5E_BADVALUE, FAIL, "no name") + + /* Set up datatype location to fill in */ + type_loc.oloc = &oloc; + type_loc.path = &path; + H5G_loc_reset(&type_loc); + + /* + * Find the named datatype object header and read the datatype message + * from it. + */ + if(H5G_loc_find(&loc, name, &type_loc/*out*/, H5P_DEFAULT, dxpl_id) < 0) + HGOTO_ERROR(H5E_DATATYPE, H5E_NOTFOUND, FAIL, "not found") + obj_found = TRUE; + + /* Check that the object found is the correct type */ + if(H5O_obj_type(&oloc, &obj_type, dxpl_id) < 0) + HGOTO_ERROR(H5E_DATATYPE, H5E_CANTGET, FAIL, "can't get object type") + if(obj_type != H5O_TYPE_NAMED_DATATYPE) + HGOTO_ERROR(H5E_DATATYPE, H5E_BADTYPE, FAIL, "not a named datatype") + + /* Open it */ + if((type = H5T_open(&type_loc, dxpl_id)) == NULL) + HGOTO_ERROR(H5E_DATATYPE, H5E_CANTOPENOBJ, FAIL, "unable to open named datatype") + + /* Register the type and return the ID */ + if((ret_value = H5I_register(H5I_DATATYPE, type, TRUE)) < 0) + HGOTO_ERROR(H5E_DATATYPE, H5E_CANTREGISTER, FAIL, "unable to register named datatype") + +done: + if(ret_value < 0) { + if(type != NULL) + H5T_close(type); + else { + if(obj_found && H5F_addr_defined(type_loc.oloc->addr)) + H5G_loc_free(&type_loc); + } /* end else */ + } /* end if */ + + FUNC_LEAVE_API(ret_value) +} /* end H5Topen1() */ +#endif /* H5_NO_DEPRECATED_SYMBOLS */ + diff --git a/pool/shard010/C/0138070_syscall.c b/pool/shard010/C/0138070_syscall.c new file mode 100644 index 0000000000000000000000000000000000000000..a4c6d8eee74c702999cc26955e250f40db30f553 --- /dev/null +++ b/pool/shard010/C/0138070_syscall.c @@ -0,0 +1,68 @@ +/* + * Copyright (C) 2000 - 2007 Jeff Dike (jdike@{addtoit,linux.intel}.com) + * Licensed under the GPL + */ + +#include "linux/file.h" +#include "linux/fs.h" +#include "linux/mm.h" +#include "linux/sched.h" +#include "linux/utsname.h" +#include "linux/syscalls.h" +#include "asm/current.h" +#include "asm/mman.h" +#include "asm/uaccess.h" +#include "asm/unistd.h" +#include "internal.h" + +long sys_fork(void) +{ + return do_fork(SIGCHLD, UPT_SP(¤t->thread.regs.regs), + ¤t->thread.regs, 0, NULL, NULL); +} + +long sys_vfork(void) +{ + return do_fork(CLONE_VFORK | CLONE_VM | SIGCHLD, + UPT_SP(¤t->thread.regs.regs), + ¤t->thread.regs, 0, NULL, NULL); +} + +long sys_clone(unsigned long clone_flags, unsigned long newsp, + void __user *parent_tid, void __user *child_tid) +{ + if (!newsp) + newsp = UPT_SP(¤t->thread.regs.regs); + + return do_fork(clone_flags, newsp, ¤t->thread.regs, 0, parent_tid, + child_tid); +} + +long old_mmap(unsigned long addr, unsigned long len, + unsigned long prot, unsigned long flags, + unsigned long fd, unsigned long offset) +{ + long err = -EINVAL; + if (offset & ~PAGE_MASK) + goto out; + + err = sys_mmap_pgoff(addr, len, prot, flags, fd, offset >> PAGE_SHIFT); + out: + return err; +} + +int kernel_execve(const char *filename, + const char *const argv[], + const char *const envp[]) +{ + mm_segment_t fs; + int ret; + + fs = get_fs(); + set_fs(KERNEL_DS); + ret = um_execve(filename, (const char __user *const __user *)argv, + (const char __user *const __user *) envp); + set_fs(fs); + + return ret; +} diff --git a/pool/shard010/C/0138071_alert.c b/pool/shard010/C/0138071_alert.c new file mode 100644 index 0000000000000000000000000000000000000000..ba61fa3a92d57b90411034f3bcb6d3b587eebaf4 --- /dev/null +++ b/pool/shard010/C/0138071_alert.c @@ -0,0 +1,217 @@ +/* + * Copyright (C) Tildeslash Ltd. All rights reserved. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License version 3. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + * + * In addition, as a special exception, the copyright holders give + * permission to link the code of portions of this program with the + * OpenSSL library under certain conditions as described in each + * individual source file, and distribute linked combinations + * including the two. + * + * You must obey the GNU Affero General Public License in all respects + * for all of the code used other than OpenSSL. + */ + +#include "config.h" + +#ifdef HAVE_STDIO_H +#include +#endif + +#ifdef HAVE_STDLIB_H +#include +#endif + +#ifdef HAVE_STDARG_H +#include +#endif + +#ifdef HAVE_STRING_H +#include +#endif + +#ifdef HAVE_UNISTD_H +#include +#endif + +#ifdef HAVE_SIGNAL_H +#include +#endif + +#include "monit.h" +#include "event.h" +#include "net.h" +#include "alert.h" + +// libmonit +#include "system/Time.h" +#include "util/Str.h" + + +/** + * Implementation of the alert module + * + * @file + */ + + +/* -------------------------------------------------------------- Prototypes */ + + +static void copy_mail(Mail_T, Mail_T); +static void escape(Mail_T); +static void substitute(Mail_T, Event_T); + + +/* ------------------------------------------------------------------ Public */ + + +/** + * Notify registred users about the event + * @param E An Event object + * @return If failed, return Handler_Alert flag or Handler_Succeeded if succeeded + */ +Handler_Type handle_alert(Event_T E) { + Handler_Type rv = Handler_Succeeded; + + ASSERT(E); + + Service_T s = Event_get_source(E); + if (! s) { + LogError("Aborting alert\n"); + return rv; + } + if (s->maillist || Run.maillist) { + Mail_T list = NULL; + /* + * Build a mail-list with local recipients that has registered interest + * for this event. + */ + for (Mail_T m = s->maillist; m; m = m->next) { + if ( + /* particular event notification type is allowed for given recipient */ + IS_EVENT_SET(m->events, Event_get_id(E)) && + ( + /* state change notification is sent always */ + E->state_changed || + /* in the case that the state is failed for more cycles we check + * whether we should send the reminder */ + (E->state && m->reminder && E->count % m->reminder == 0) + ) + ) + { + Mail_T tmp = NULL; + NEW(tmp); + copy_mail(tmp, m); + substitute(tmp, E); + escape(tmp); + tmp->next = list; + list = tmp; + DEBUG("%s notification is sent to %s\n", Event_get_description(E), m->to); + } + } + /* + * Build a mail-list with global recipients that has registered interest + * for this event. Recipients which are defined in the service localy + * overrides the same recipient events which are registered globaly. + */ + for (Mail_T m = Run.maillist; m; m = m->next) { + boolean_t skip = false; + for (Mail_T n = s->maillist; n; n = n->next) { + if (IS(m->to, n->to)) { + skip = true; + break; + } + } + if ( + /* the local service alert definition has not overrided the global one */ + ! skip && + /* particular event notification type is allowed for given recipient */ + IS_EVENT_SET(m->events, Event_get_id(E)) && + ( + /* state change notification is sent always */ + E->state_changed || + /* in the case that the state is failed for more cycles we check + * whether we should send the reminder */ + (E->state && m->reminder && E->count % m->reminder == 0) + ) + ) + { + Mail_T tmp = NULL; + NEW(tmp); + copy_mail(tmp, m); + substitute(tmp, E); + escape(tmp); + tmp->next = list; + list = tmp; + DEBUG("%s notification is sent to %s\n", Event_get_description(E), m->to); + } + } + if (list) { + if (sendmail(list)) + rv = Handler_Alert; + gc_mail_list(&list); + } + } + return rv; +} + + +static void substitute(Mail_T m, Event_T e) { + char timestamp[STRLEN]; + + ASSERT(m && e); + + Util_replaceString(&m->from, "$HOST", Run.system->name); + Util_replaceString(&m->subject, "$HOST", Run.system->name); + Util_replaceString(&m->message, "$HOST", Run.system->name); + + Time_string(e->collected.tv_sec, timestamp); + Util_replaceString(&m->subject, "$DATE", timestamp); + Util_replaceString(&m->message, "$DATE", timestamp); + + Util_replaceString(&m->subject, "$SERVICE", Event_get_source_name(e)); + Util_replaceString(&m->message, "$SERVICE", Event_get_source_name(e)); + + Util_replaceString(&m->subject, "$EVENT", Event_get_description(e)); + Util_replaceString(&m->message, "$EVENT", Event_get_description(e)); + + Util_replaceString(&m->subject, "$DESCRIPTION", NVLSTR(Event_get_message(e))); + Util_replaceString(&m->message, "$DESCRIPTION", NVLSTR(Event_get_message(e))); + + Util_replaceString(&m->subject, "$ACTION", Event_get_action_description(e)); + Util_replaceString(&m->message, "$ACTION", Event_get_action_description(e)); +} + + +static void copy_mail(Mail_T n, Mail_T o) { + ASSERT(n && o); + + n->to = Str_dup(o->to); + n->from = o->from ? Str_dup(o->from) : Run.MailFormat.from ? Str_dup(Run.MailFormat.from) : Str_dup(ALERT_FROM); + n->replyto = o->replyto ? Str_dup(o->replyto) : Run.MailFormat.replyto ? Str_dup(Run.MailFormat.replyto) : NULL; + n->subject = o->subject ? Str_dup(o->subject) : Run.MailFormat.subject ? Str_dup(Run.MailFormat.subject) : Str_dup(ALERT_SUBJECT); + n->message = o->message ? Str_dup(o->message) : Run.MailFormat.message ? Str_dup(Run.MailFormat.message) : Str_dup(ALERT_MESSAGE); +} + + +static void escape(Mail_T m) { + // replace bare linefeed + Util_replaceString(&m->message, "\r\n", "\n"); + Util_replaceString(&m->message, "\n", "\r\n"); + // escape ^. + Util_replaceString(&m->message, "\n.", "\n.."); + // drop any CR|LF from the subject + Str_chomp(m->subject); +} + diff --git a/pool/shard010/C/0138072_tty.c b/pool/shard010/C/0138072_tty.c new file mode 100644 index 0000000000000000000000000000000000000000..e9eb9e3622c4f20162a857df99079e8fb6346f3d --- /dev/null +++ b/pool/shard010/C/0138072_tty.c @@ -0,0 +1,86 @@ +/* + * Copyright (C) 2001 Jeff Dike (jdike@karaya.com) + * Licensed under the GPL + */ + +#include +#include +#include +#include +#include +#include "chan_user.h" +#include "user_util.h" +#include "user.h" +#include "os.h" + +struct tty_chan { + char *dev; + int raw; + struct termios tt; +}; + +void *tty_chan_init(char *str, int device, struct chan_opts *opts) +{ + struct tty_chan *data; + + if(*str != ':'){ + printk("tty_init : channel type 'tty' must specify " + "a device\n"); + return(NULL); + } + str++; + + if((data = um_kmalloc(sizeof(*data))) == NULL) + return(NULL); + *data = ((struct tty_chan) { .dev = str, + .raw = opts->raw }); + + return(data); +} + +int tty_open(int input, int output, int primary, void *d, char **dev_out) +{ + struct tty_chan *data = d; + int fd; + + fd = os_open_file(data->dev, of_set_rw(OPENFLAGS(), input, output), 0); + if(fd < 0) return(fd); + if(data->raw){ + tcgetattr(fd, &data->tt); + raw(fd, 0); + } + + *dev_out = data->dev; + return(fd); +} + +int tty_console_write(int fd, const char *buf, int n, void *d) +{ + struct tty_chan *data = d; + + return(generic_console_write(fd, buf, n, &data->tt)); +} + +struct chan_ops tty_ops = { + .type = "tty", + .init = tty_chan_init, + .open = tty_open, + .close = generic_close, + .read = generic_read, + .write = generic_write, + .console_write = tty_console_write, + .window_size = generic_window_size, + .free = generic_free, + .winch = 0, +}; + +/* + * Overrides for Emacs so that we follow Linus's tabbing style. + * Emacs will notice this stuff at the end of the file and automatically + * adjust the settings for this buffer only. This must remain at the end + * of the file. + * --------------------------------------------------------------------------- + * Local variables: + * c-file-style: "linux" + * End: + */ diff --git a/pool/shard010/C/0138073_igep0020.c b/pool/shard010/C/0138073_igep0020.c new file mode 100644 index 0000000000000000000000000000000000000000..971e31b5f36bb4cedeeac3e846b9518c33de57f4 --- /dev/null +++ b/pool/shard010/C/0138073_igep0020.c @@ -0,0 +1,137 @@ +/* + * (C) Copyright 2010 + * ISEE 2007 SL, + * + * See file CREDITS for list of people who contributed to this + * project. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation; either version 2 of + * the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, + * MA 02111-1307 USA + */ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "igep0020.h" + +DECLARE_GLOBAL_DATA_PTR; + +/* GPMC definitions for LAN9221 chips */ +static const u32 gpmc_lan_config[] = { + NET_LAN9221_GPMC_CONFIG1, + NET_LAN9221_GPMC_CONFIG2, + NET_LAN9221_GPMC_CONFIG3, + NET_LAN9221_GPMC_CONFIG4, + NET_LAN9221_GPMC_CONFIG5, + NET_LAN9221_GPMC_CONFIG6, +}; + +/* + * Routine: board_init + * Description: Early hardware init. + */ +int board_init(void) +{ + gpmc_init(); /* in SRAM or SDRAM, finish GPMC */ + /* boot param addr */ + gd->bd->bi_boot_params = (OMAP34XX_SDRC_CS0 + 0x100); + + return 0; +} + +/* + * Routine: setup_net_chip + * Description: Setting up the configuration GPMC registers specific to the + * Ethernet hardware. + */ +#if defined(CONFIG_CMD_NET) +static void setup_net_chip(void) +{ + struct ctrl *ctrl_base = (struct ctrl *)OMAP34XX_CTRL_BASE; + + enable_gpmc_cs_config(gpmc_lan_config, &gpmc_cfg->cs[5], 0x2C000000, + GPMC_SIZE_16M); + + /* Enable off mode for NWE in PADCONF_GPMC_NWE register */ + writew(readw(&ctrl_base->gpmc_nwe) | 0x0E00, &ctrl_base->gpmc_nwe); + /* Enable off mode for NOE in PADCONF_GPMC_NADV_ALE register */ + writew(readw(&ctrl_base->gpmc_noe) | 0x0E00, &ctrl_base->gpmc_noe); + /* Enable off mode for ALE in PADCONF_GPMC_NADV_ALE register */ + writew(readw(&ctrl_base->gpmc_nadv_ale) | 0x0E00, + &ctrl_base->gpmc_nadv_ale); + + /* Make GPIO 64 as output pin and send a magic pulse through it */ + if (!gpio_request(64, "")) { + gpio_direction_output(64, 0); + gpio_set_value(64, 1); + udelay(1); + gpio_set_value(64, 0); + udelay(1); + gpio_set_value(64, 1); + } +} +#endif + +#ifdef CONFIG_GENERIC_MMC +int board_mmc_init(bd_t *bis) +{ + omap_mmc_init(0, 0, 0); + return 0; +} +#endif + +/* + * Routine: misc_init_r + * Description: Configure board specific parts + */ +int misc_init_r(void) +{ + twl4030_power_init(); + +#if defined(CONFIG_CMD_NET) + setup_net_chip(); +#endif + + dieid_num_r(); + + return 0; +} + +/* + * Routine: set_muxconf_regs + * Description: Setting up the configuration Mux registers specific to the + * hardware. Many pins need to be moved from protect to primary + * mode. + */ +void set_muxconf_regs(void) +{ + MUX_DEFAULT(); +} + +int board_eth_init(bd_t *bis) +{ + int rc = 0; +#ifdef CONFIG_SMC911X + rc = smc911x_initialize(0, CONFIG_SMC911X_BASE); +#endif + return rc; +} diff --git a/pool/shard010/C/0138074_machvec.c b/pool/shard010/C/0138074_machvec.c new file mode 100644 index 0000000000000000000000000000000000000000..c3a04ee7f4f612764731723c396c5ef07b8ed109 --- /dev/null +++ b/pool/shard010/C/0138074_machvec.c @@ -0,0 +1,70 @@ +#include +#include + +#include +#include + +#ifdef CONFIG_IA64_GENERIC + +#include +#include + +#include + +struct ia64_machine_vector ia64_mv; +EXPORT_SYMBOL(ia64_mv); + +static struct ia64_machine_vector * +lookup_machvec (const char *name) +{ + extern struct ia64_machine_vector machvec_start[]; + extern struct ia64_machine_vector machvec_end[]; + struct ia64_machine_vector *mv; + + for (mv = machvec_start; mv < machvec_end; ++mv) + if (strcmp (mv->name, name) == 0) + return mv; + + return 0; +} + +void +machvec_init (const char *name) +{ + struct ia64_machine_vector *mv; + + mv = lookup_machvec(name); + if (!mv) { + panic("generic kernel failed to find machine vector for platform %s!", name); + } + ia64_mv = *mv; + printk(KERN_INFO "booting generic kernel on platform %s\n", name); +} + +#endif /* CONFIG_IA64_GENERIC */ + +void +machvec_setup (char **arg) +{ +} +EXPORT_SYMBOL(machvec_setup); + +void +machvec_timer_interrupt (int irq, void *dev_id, struct pt_regs *regs) +{ +} +EXPORT_SYMBOL(machvec_timer_interrupt); + +void +machvec_dma_sync_single (struct device *hwdev, dma_addr_t dma_handle, size_t size, int dir) +{ + mb(); +} +EXPORT_SYMBOL(machvec_dma_sync_single); + +void +machvec_dma_sync_sg (struct device *hwdev, struct scatterlist *sg, int n, int dir) +{ + mb(); +} +EXPORT_SYMBOL(machvec_dma_sync_sg); diff --git a/pool/shard010/C/0138075_selectionSort.c b/pool/shard010/C/0138075_selectionSort.c new file mode 100644 index 0000000000000000000000000000000000000000..f542aeb0eaae22904b447ab261d2f2491822c5be --- /dev/null +++ b/pool/shard010/C/0138075_selectionSort.c @@ -0,0 +1,55 @@ +//selection sort using a function +#include +#include +#define MAX 10 + +int minimum(int a[],int k,int size) { + int min=a[k],loc=k,j; + + for(j=k+1;ja[j]) { + min=a[j]; + loc=j; + } + } + return loc; +} + +void selectionSort(int a[],int size) { + int i,loc,temp,k; + + for(i=0;i\n",i+1); + for(k=0;k +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +static DEFINE_SPINLOCK(flash_lock); +static struct { + unsigned long read_base; /* Physical read address */ + unsigned long write_base; /* Physical write address */ + unsigned long read_size; /* Size of read area */ + unsigned long write_size; /* Size of write area */ + unsigned long busy; /* In use? */ +} flash; + +#define FLASH_MINOR 152 + +static int +flash_mmap(struct file *file, struct vm_area_struct *vma) +{ + unsigned long addr; + unsigned long size; + + spin_lock(&flash_lock); + if (flash.read_base == flash.write_base) { + addr = flash.read_base; + size = flash.read_size; + } else { + if ((vma->vm_flags & VM_READ) && + (vma->vm_flags & VM_WRITE)) { + spin_unlock(&flash_lock); + return -EINVAL; + } + if (vma->vm_flags & VM_READ) { + addr = flash.read_base; + size = flash.read_size; + } else if (vma->vm_flags & VM_WRITE) { + addr = flash.write_base; + size = flash.write_size; + } else { + spin_unlock(&flash_lock); + return -ENXIO; + } + } + spin_unlock(&flash_lock); + + if ((vma->vm_pgoff << PAGE_SHIFT) > size) + return -ENXIO; + addr = vma->vm_pgoff + (addr >> PAGE_SHIFT); + + if (vma->vm_end - (vma->vm_start + (vma->vm_pgoff << PAGE_SHIFT)) > size) + size = vma->vm_end - (vma->vm_start + (vma->vm_pgoff << PAGE_SHIFT)); + + vma->vm_page_prot = pgprot_noncached(vma->vm_page_prot); + + if (io_remap_pfn_range(vma, vma->vm_start, addr, size, vma->vm_page_prot)) + return -EAGAIN; + + return 0; +} + +static long long +flash_llseek(struct file *file, long long offset, int origin) +{ + lock_kernel(); + switch (origin) { + case 0: + file->f_pos = offset; + break; + case 1: + file->f_pos += offset; + if (file->f_pos > flash.read_size) + file->f_pos = flash.read_size; + break; + case 2: + file->f_pos = flash.read_size; + break; + default: + unlock_kernel(); + return -EINVAL; + } + unlock_kernel(); + return file->f_pos; +} + +static ssize_t +flash_read(struct file * file, char __user * buf, + size_t count, loff_t *ppos) +{ + unsigned long p = file->f_pos; + int i; + + if (count > flash.read_size - p) + count = flash.read_size - p; + + for (i = 0; i < count; i++) { + u8 data = upa_readb(flash.read_base + p + i); + if (put_user(data, buf)) + return -EFAULT; + buf++; + } + + file->f_pos += count; + return count; +} + +static int +flash_open(struct inode *inode, struct file *file) +{ + if (test_and_set_bit(0, (void *)&flash.busy) != 0) + return -EBUSY; + + return 0; +} + +static int +flash_release(struct inode *inode, struct file *file) +{ + spin_lock(&flash_lock); + flash.busy = 0; + spin_unlock(&flash_lock); + + return 0; +} + +static const struct file_operations flash_fops = { + /* no write to the Flash, use mmap + * and play flash dependent tricks. + */ + .owner = THIS_MODULE, + .llseek = flash_llseek, + .read = flash_read, + .mmap = flash_mmap, + .open = flash_open, + .release = flash_release, +}; + +static struct miscdevice flash_dev = { FLASH_MINOR, "flash", &flash_fops }; + +static int __init flash_init(void) +{ + struct sbus_bus *sbus; + struct sbus_dev *sdev = NULL; +#ifdef CONFIG_PCI + struct linux_ebus *ebus; + struct linux_ebus_device *edev = NULL; + struct linux_prom_registers regs[2]; + int len, nregs; +#endif + int err; + + for_all_sbusdev(sdev, sbus) { + if (!strcmp(sdev->prom_name, "flashprom")) { + if (sdev->reg_addrs[0].phys_addr == sdev->reg_addrs[1].phys_addr) { + flash.read_base = ((unsigned long)sdev->reg_addrs[0].phys_addr) | + (((unsigned long)sdev->reg_addrs[0].which_io)<<32UL); + flash.read_size = sdev->reg_addrs[0].reg_size; + flash.write_base = flash.read_base; + flash.write_size = flash.read_size; + } else { + flash.read_base = ((unsigned long)sdev->reg_addrs[0].phys_addr) | + (((unsigned long)sdev->reg_addrs[0].which_io)<<32UL); + flash.read_size = sdev->reg_addrs[0].reg_size; + flash.write_base = ((unsigned long)sdev->reg_addrs[1].phys_addr) | + (((unsigned long)sdev->reg_addrs[1].which_io)<<32UL); + flash.write_size = sdev->reg_addrs[1].reg_size; + } + flash.busy = 0; + break; + } + } + if (!sdev) { +#ifdef CONFIG_PCI + struct linux_prom_registers *ebus_regs; + + for_each_ebus(ebus) { + for_each_ebusdev(edev, ebus) { + if (!strcmp(edev->prom_node->name, "flashprom")) + goto ebus_done; + } + } + ebus_done: + if (!edev) + return -ENODEV; + + ebus_regs = of_get_property(edev->prom_node, "reg", &len); + if (!ebus_regs || (len % sizeof(regs[0])) != 0) { + printk("flash: Strange reg property size %d\n", len); + return -ENODEV; + } + + nregs = len / sizeof(ebus_regs[0]); + + flash.read_base = edev->resource[0].start; + flash.read_size = ebus_regs[0].reg_size; + + if (nregs == 1) { + flash.write_base = edev->resource[0].start; + flash.write_size = ebus_regs[0].reg_size; + } else if (nregs == 2) { + flash.write_base = edev->resource[1].start; + flash.write_size = ebus_regs[1].reg_size; + } else { + printk("flash: Strange number of regs %d\n", nregs); + return -ENODEV; + } + + flash.busy = 0; + +#else + return -ENODEV; +#endif + } + + printk("OBP Flash: RD %lx[%lx] WR %lx[%lx]\n", + flash.read_base, flash.read_size, + flash.write_base, flash.write_size); + + err = misc_register(&flash_dev); + if (err) { + printk(KERN_ERR "flash: unable to get misc minor\n"); + return err; + } + + return 0; +} + +static void __exit flash_cleanup(void) +{ + misc_deregister(&flash_dev); +} + +module_init(flash_init); +module_exit(flash_cleanup); +MODULE_LICENSE("GPL"); diff --git a/pool/shard010/C/0138077_eeze_disk_ls.c b/pool/shard010/C/0138077_eeze_disk_ls.c new file mode 100644 index 0000000000000000000000000000000000000000..1c1e6a2b04643043d37ed1e8b1c59a11d0ebec35 --- /dev/null +++ b/pool/shard010/C/0138077_eeze_disk_ls.c @@ -0,0 +1,58 @@ +#ifdef HAVE_CONFIG_H +# include +#endif + +#include + +#include +#include +#include + +/* simple app to print disks and their mount points */ + +int +main(void) +{ + Eina_List *disks; + const char *syspath; + + eeze_init(); + eeze_disk_function(); + + disks = eeze_udev_find_by_type(EEZE_UDEV_TYPE_DRIVE_MOUNTABLE, NULL); + printf("Found the following mountable disks:\n"); + EINA_LIST_FREE(disks, syspath) + { + Eeze_Disk *disk; + + disk = eeze_disk_new(syspath); + printf("\t%s - %s:%s\n", syspath, eeze_disk_devpath_get(disk), eeze_disk_mount_point_get(disk)); + eeze_disk_free(disk); + eina_stringshare_del(syspath); + } + + disks = eeze_udev_find_by_type(EEZE_UDEV_TYPE_DRIVE_REMOVABLE, NULL); + printf("Found the following removable drives:\n"); + EINA_LIST_FREE(disks, syspath) + { + Eeze_Disk *disk; + + disk = eeze_disk_new(syspath); + printf("\t%s - %s:%s\n", syspath, eeze_disk_devpath_get(disk), eeze_disk_mount_point_get(disk)); + eeze_disk_free(disk); + eina_stringshare_del(syspath); + } + + disks = eeze_udev_find_by_type(EEZE_UDEV_TYPE_DRIVE_INTERNAL, NULL); + printf("Found the following internal drives:\n"); + EINA_LIST_FREE(disks, syspath) + { + Eeze_Disk *disk; + + disk = eeze_disk_new(syspath); + printf("\t%s - %s\n", syspath, eeze_disk_devpath_get(disk)); + eeze_disk_free(disk); + eina_stringshare_del(syspath); + } + return 0; +} diff --git a/pool/shard010/C/0138078_mod-locale.c b/pool/shard010/C/0138078_mod-locale.c new file mode 100644 index 0000000000000000000000000000000000000000..bf956cb676817d911cb7e07d1a4f8d9c307e84bc --- /dev/null +++ b/pool/shard010/C/0138078_mod-locale.c @@ -0,0 +1,188 @@ +// +// File: %mod-locale.c +// Summary: "Native Functions for spawning and controlling processes" +// Section: Extension +// Project: "Rebol 3 Interpreter and Run-time (Ren-C branch)" +// Homepage: https://github.com/metaeducation/ren-c/ +// +//=////////////////////////////////////////////////////////////////////////=// +// +// Copyright 2012-2017 Rebol Open Source Contributors +// REBOL is a trademark of REBOL Technologies +// +// See README.md and CREDITS.md for more information. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//=////////////////////////////////////////////////////////////////////////=// +// + +#ifdef TO_WINDOWS + #include +#endif +#include + +// IS_ERROR might be defined in winerror.h and reb-types.h +#ifdef IS_ERROR +#undef IS_ERROR +#endif + +#include "sys-core.h" +#include "sys-ext.h" + +#include "tmp-mod-locale-first.h" + + +// +// locale: native/export [ +// "Get locale specific information" +// category [word!] +// {Language: English name of the language, +// Territory: English name of the country/region, +// Language*: Full localized primary name of the language +// Territory*: Full localized name of the country/region} +// ] +// new-words: [Language Language* Territory Territory*] +// new-errors: [ +// invalid-category: [{Invalid locale category:} :arg1] +// ] +// +REBNATIVE(locale) +// +{ + #ifdef TO_WINDOWS + LOCALE_INCLUDE_PARAMS_OF_LOCALE; + + REBSTR *cat = VAL_WORD_CANON(ARG(category)); + + LCTYPE type; + if (cat == LOCALE_WORD_LANGUAGE) + type = LOCALE_SENGLANGUAGE; + else if (cat == LOCALE_WORD_LANGUAGE_P) + type = LOCALE_SNATIVELANGNAME; + else if (cat == LOCALE_WORD_TERRITORY) + type = LOCALE_SENGCOUNTRY; + else if (cat == LOCALE_WORD_TERRITORY_P) + type = LOCALE_SCOUNTRY; + else + fail (Error(RE_EXT_LOCALE_INVALID_CATEGORY, ARG(category), END)); + + int len_plus_term = GetLocaleInfo(0, type, 0, 0); // fetch needed length + + WCHAR *buffer = OS_ALLOC_N(WCHAR, len_plus_term); + + int len_check = GetLocaleInfo(0, type, buffer, len_plus_term); + assert(len_check == len_plus_term); + UNUSED(len_check); + + REBVAL *str = rebSizedStringW(buffer, len_plus_term - 1); + Move_Value(D_OUT, str); + rebRelease(str); + + return R_OUT; + #else + UNUSED(frame_); + fail ("Locale not implemented for non-windows"); + #endif +} + + +// +// setlocale: native/export [ +// {Set/Get current locale, just a simple wrapper around C version} +// return: [string! blank!] +// category [word!] +// value [string!] +// ] +// new-words: [ +// all +// address +// collate +// ctype +// identification +// measurement +// messages +// monetary +// name +// numeric +// paper +// telephone +// time +// ] +// new-errors: [ +// ] +// +REBNATIVE(setlocale) +{ + LOCALE_INCLUDE_PARAMS_OF_SETLOCALE; + + struct cat_pair { + REBSTR *word; + int cat; + } ctypes [] = { + {LOCALE_WORD_ALL, LC_ALL}, +#if defined(LC_ADDRESS) // GNU extension + {LOCALE_WORD_ADDRESS, LC_ADDRESS}, +#endif + {LOCALE_WORD_COLLATE, LC_COLLATE}, + {LOCALE_WORD_CTYPE, LC_CTYPE}, +#if defined(LC_IDENTIFICATION) // GNU extension + {LOCALE_WORD_IDENTIFICATION, LC_IDENTIFICATION}, +#endif +#if defined(LC_MEASUREMENT) // GNU extension + {LOCALE_WORD_MEASUREMENT, LC_MEASUREMENT}, +#endif +#if defined(LC_MESSAGES) // GNU extension + {LOCALE_WORD_MESSAGES, LC_MESSAGES}, +#endif + {LOCALE_WORD_MONETARY, LC_MONETARY}, +#if defined(LC_NAME) // GNU extension + {LOCALE_WORD_NAME, LC_NAME}, +#endif + {LOCALE_WORD_NUMERIC, LC_NUMERIC}, +#if defined(LC_TELEPHONE) // GNU extension + {LOCALE_WORD_TELEPHONE, LC_TELEPHONE}, +#endif +#if defined(LC_PAPER) // GNU extension + {LOCALE_WORD_PAPER, LC_PAPER}, +#endif + {LOCALE_WORD_TIME, LC_TIME} + }; + + REBSTR *w_cat = VAL_WORD_CANON(ARG(category)); + + int cat = -1; // avoid possibly uninitialized warning + REBCNT i = 0; + for (; i < sizeof (ctypes) / sizeof (ctypes[0]); ++i) { + if (ctypes[i].word == w_cat) { + cat = ctypes[i].cat; + break; + } + } + if (i == sizeof (ctypes) / sizeof (ctypes[0])) + fail (Error(RE_EXT_LOCALE_INVALID_CATEGORY, ARG(category), END)); + + const char *ret = setlocale(cat, cs_cast(VAL_BIN_AT(ARG(value)))); + if (ret == NULL) { + Init_Blank(D_OUT); + } else { + REBCNT len = strlen(ret); + REBSER *ser = Make_Binary(len); + Append_Series(ser, cb_cast(ret), len); + Init_String(D_OUT, ser); + } + + return R_OUT; +} + +#include "tmp-mod-locale-last.h" diff --git a/pool/shard010/C/0138079_cam-vertex.c b/pool/shard010/C/0138079_cam-vertex.c new file mode 100644 index 0000000000000000000000000000000000000000..e99d97c8fcad21c58b40be471058e05810b8f687 --- /dev/null +++ b/pool/shard010/C/0138079_cam-vertex.c @@ -0,0 +1,30 @@ +in vec4 position; +out vec2 Texcoord; +uniform float angle; + +void main() +{ + const mat4 m_projection = mat4( + vec4(3.0 / 4.0, 0.0, 0.0, 0.0), + vec4( 0.0, 1.0, 0.0, 0.0), + vec4( 0.0, 0.0, 0.5, 0.5), + vec4( 0.0, 0.0, 0.0, 1.0) + ); + + mat4 m_rotation = mat4( + vec4(1.0, 0.0, 0.0, 0.0), + vec4(0.0, cos(radians(angle)), sin(radians(angle)), 0.0), + vec4(0.0, -sin(radians(angle)), cos(radians(angle)), 0.0), + vec4(0.0, 0.0, 0.0, 1.0) + ); + + mat4 m_scale = mat4( + vec4(4.0 / 3.0, 0.0, 0.0, 0.0), + vec4( 0.0, 1.0, 0.0, 0.0), + vec4( 0.0, 0.0, 1.0, 0.0), + vec4( 0.0, 0.0, 0.0, 1.0) + ); + + gl_Position = m_projection * m_rotation * m_scale * position; + Texcoord = position.xy * vec2(0.5) + vec2(0.5); +} diff --git a/pool/shard010/C/0138080_ems1Form.c b/pool/shard010/C/0138080_ems1Form.c new file mode 100644 index 0000000000000000000000000000000000000000..7a7b141aad843c382f878562493c2cb0e256d1b6 --- /dev/null +++ b/pool/shard010/C/0138080_ems1Form.c @@ -0,0 +1,321 @@ +/* + *+ + * Name: + * ems1Form + + * Purpose: + * Form an error message from its text and components. + + * Language: + * Starlink ANSI + + * Invocation: + * ems1Form( text, maxlen, esctokval, clean, opstr, oplen, status ) + + * Description: + * Construct the final text, OPSTR( 1 : OPLEN ), of a message + * using the text in TEXT, and available message tokens only. + + * Arguments: + * text = char* (Given) + * The input message text, with any tokens. + * maxlen = const int (Given) + * Maximum length of output string + * esctokval = Logical (Given) + * if true, token values containing % will be escaped into %% + * to enable sprintf processing to be performed on the expanded + * string subsequently. + * clean = logical (Given) + * if the string is to be 'cleaned' + * opstr = char* (Returned) + * Resultant message text, with parsed tokens. + * oplen = int* (Returned) + * The filled length of OPSTR. + * status = int* (Returned) + * The global status. + + * Algorithm: + * - Parse the message text, TEXT, and copy it into OPSTR, making + * translations for token escapes. + * - The message length is returned in OPLEN. + + * Notes: + * The code assumes "%" is the escape character to be doubled up in + * token values. This is done for simplicity and can easily be made + * generic by changing esctokval to be a const char *. + + * Copyright: + * Copyright (C) 1982 Science & Engineering Research Council. + * Copyright (C) 2001 Central Laboratory of the Research Councils. + * Copyright (C) 2006 Particle Physics & Astronomy Research Council. + * Copyright (C) 2008 Science and Technology Facilities Council. + * All Rights Reserved. + + * Licence: + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation; either version 2 of + * the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be + * useful,but WITHOUT ANY WARRANTY; without even the implied + * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + * PURPOSE. See the GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street,Fifth Floor, Boston, MA + * 02110-1301, USA + + * Authors: + * JRG: Jack Giddings (UCL) + * BDK: Dennis Kelly (ROE) + * AJC: Alan Chipperfield (STARLINK) + * PCTR: P.C.T. Rees (STARLINK) + * RTP: R.T. Platon (STARLINK) + * TIMJ: Tim Jenness (JAC, Hawaii) + * PWD: Peter W. Draper (JAC, Durham University) + * {enter_new_authors_here} + + * History: + * 3-JAN-1982 (JRG): + * Original FORTRAN version. + * 14-FEB-2001 (RTP) + * Rewritten in C based on the Fortran routine EMS1_PFORM + * 5-MAR-2001 (AJC): + * Set returned value OPLEN + * Use a temporary buffer for text amnipulation + * Use ems1Putc to append to string + * Add 'maxlen' argument + * Remove 'param' argument + * 13-AUG-2001 (AJC): + * #include stdlib.h and ems1.h + * 23-FEB-2006 (TIMJ): + * Use starMem + * 15-MAY-2008 (PWD): + * Remove ems_msgtb.h include, not needed. + * 23-DEC-2008 (TIMJ): + * use isprint() to filter out non-printable characters. Rather + * than checking for char < 32. Add argument to enable escaping + * of % characters in token values. Required for safe sprintf processing. + * {enter_further_changes_here} + + * Bugs: + * {note_any_bugs_here} + */ + +#include +#include +#include +#include + +#include "sae_par.h" /* Standard SAE constants */ +#include "ems_par.h" /* EMS_ public constants */ +#include "ems_sys.h" /* EMS_ private constants */ +#include "ems1.h" /* EMS1 function prototypes */ +#include "ems.h" +#include "star/mem.h" + +void ems1Form( const char *text, const int maxlen, Logical esctokval, + Logical clean, char *opstr, int *oplen, + int *status __attribute__((unused)) ) +{ + Logical literl; /* Whether a literal token escape */ + + int curpos; /* Current character pointer */ + int lstat; /* Local status */ + int lstpos; /* Previous value of CURPOS */ + int oppos; /* Position in OP string */ + int namlen; /* Token name length */ + int pstat; /* Local status */ + int texlen; /* TEXSTR length */ + int tkvlen; /* TOKVAL length */ + int j; + int i; + + char namstr[ EMS__SZMSG + 1 ] = ""; /* Token name string */ + char tokval[ EMS__SZTOK + 1 ] = ""; /* Token value string */ + char tstr[EMS__SZTOK + 1 ]; /* Escaped token value temp string buffer */ + const char tokescval = '%'; /* Escape value to look for in token values */ + char *texbuf; /* Ptr to temporary text buffer */ + + TRACE("ems1Form"); + + /* Initialise the returned message. */ + opstr[0] = '\0'; + *oplen = 0; + + /* Get the length of the given string. */ + if (!text) { + strcpy( opstr, "Internal malloc failure. Abort!" ); + *oplen = strlen( opstr ); + /* Clear the message token table. */ + ems1Ktok(); + return; + } + texlen = strlen( text ); + + /* Check for an empty string. */ + if ( texlen > 0 ) { + + /* Use a temporary text buffer which can be modified */ + texbuf = starMalloc( texlen + 1 ); + if (!texbuf) { + strcpy( opstr, "Internal malloc failure. Abort!" ); + *oplen = strlen( opstr ); + /* Clear the message token table. */ + ems1Ktok(); + return; + } + strcpy( texbuf, text ); + + /* Initialise the text pointers and local status. */ + literl = FALSE; + curpos = -1; + lstpos = -1; + oppos = -1; + lstat = SAI__OK; + pstat = SAI__OK; + + /* Parse and expand the message text. + * DO WHILE loop. + */ + while ( pstat == SAI__OK && curpos < texlen ) { + + /* Find the next occurrence of an escape character. */ + ems1Gesc( EMS__TOKEC, texbuf, &curpos ); + + if ( curpos == -1 ) { + + /* No more escape characters have been found, so append all + * the text that remains to the returned message text and + * exit the loop. + */ + ems1Putc( &texbuf[ lstpos+1 ], maxlen, opstr, &oppos, &pstat ); + break; + + } else { + /* A token escape has been found, so check if it is a double + * token escape. + */ + if ( literl && curpos == lstpos + 1 ) { + /* A double token escape, so do nothing except update + * CURPOS and reset the literal token escape flag. + */ + literl = FALSE; + + } else { + + /* Reset the literal token escape flag. */ + literl = FALSE; + + /* Append any text prior to the escape character. */ + /* Terminate the string to be copied at the escape */ + if ( curpos - lstpos > 0 ) { + texbuf[ curpos ] = '\0'; + (void)ems1Putc( &texbuf[ lstpos+1 ], maxlen, opstr, + &oppos, &pstat ); + + /* Overwrite the terminator - actual character + * doesn't matter */ + texbuf[ curpos ] = '^'; + } + + /* Find the token name. */ + ems1Gnam( texbuf, &curpos, namstr, &namlen, &lstat ); + + /* Check that a token name exists. */ + if ( lstat != SAI__OK ) { + + /* The name string has been over-run, so indicate + * this in the message text. */ + ems1Putc( EMS__TOKEC, maxlen, opstr, &oppos, &pstat ); + ems1Putc( "<", maxlen, opstr, &oppos, &pstat ); + ems1Putc( namstr, maxlen, opstr, &oppos, &pstat ); + ems1Putc( ">", maxlen, opstr, &oppos, &pstat ); + + /* Reset the local status. */ + lstat = SAI__OK; + + } else if ( namlen > 0 ) { + + /* There is a name, so get the token value. */ + if ( ems1Gtok( namstr, tokval, &tkvlen ) ) { + + /* if there is an escape character in the token + itself we need to double it up. This is used + to enable a % in the token to be retained + after sprintf processing */ + if ( esctokval ) { + j=0; + for ( i = 0; i < tkvlen; i++) { + /* if we have found the escape char we + insert an additional one */ + if (tokval[i] == tokescval) { + tstr[j] = tokescval; + j++; + } + /* copy the character that was tested */ + tstr[j] = tokval[i]; + j++; + } + tkvlen = j; + tstr[j] = '\0'; + } else { + strncpy( tstr, tokval, sizeof(tstr)); + tstr[tkvlen] = '\0'; + } + + /* Append the token value to the expanded message + * text. */ + ems1Putc( tstr, maxlen, opstr, &oppos, &pstat ); + + } else { + /* The message token is not defined, so indicate + * this in the message text. */ + ems1Putc( EMS__TOKEC, maxlen, opstr, &oppos, + &pstat ); + ems1Putc( "<", maxlen, opstr, &oppos, &pstat ); + ems1Putc( namstr, maxlen, opstr, &oppos, &pstat ); + ems1Putc( ">", maxlen, opstr, &oppos, &pstat ); + } + + } else { + + /* There is an isolated token escape character in the + * string, so set the literal token escape flag and + * append the character. */ + literl = TRUE; + ems1Putc( EMS__TOKEC, maxlen, opstr, &oppos, &pstat ); + } + } + + /* Update LSTPOS. */ + lstpos = curpos; + } + } + starFree( texbuf ); + } + + /* Get the length of the string and, if CLEAN is TRUE, ensure the + * returned message string contains no unprintable characters. + */ + *oplen = strlen( opstr ); + if ( clean ) { + int i; + for ( i = 0; i < *oplen; i++ ) { + if ( !isprint(opstr[ i ]) ) opstr[ i ] = ' '; + } + } + + DEBUG( "ems1Form", "Error Message: '%s'\n", opstr ); +#if PRINT_ERRMESS + fprintf( OP_STREAM, "! %s\n", opstr ); + fflush( OP_STREAM ); +#endif + + /* Clear the message token table. */ + ems1Ktok(); + + return; +} diff --git a/pool/shard010/C/0138081_sunxi_sram.c b/pool/shard010/C/0138081_sunxi_sram.c new file mode 100644 index 0000000000000000000000000000000000000000..bc52670c8f4b33a9b8181d19e89566a3c87f3c69 --- /dev/null +++ b/pool/shard010/C/0138081_sunxi_sram.c @@ -0,0 +1,284 @@ +/* + * Allwinner SoCs SRAM Controller Driver + * + * Copyright (C) 2015 Maxime Ripard + * + * Author: Maxime Ripard + * + * This file is licensed under the terms of the GNU General Public + * License version 2. This program is licensed "as is" without any + * warranty of any kind, whether express or implied. + */ + +#include +#include +#include +#include +#include +#include +#include + +#include + +struct sunxi_sram_func { + char *func; + u8 val; +}; + +struct sunxi_sram_data { + char *name; + u8 reg; + u8 offset; + u8 width; + struct sunxi_sram_func *func; + struct list_head list; +}; + +struct sunxi_sram_desc { + struct sunxi_sram_data data; + bool claimed; +}; + +#define SUNXI_SRAM_MAP(_val, _func) \ + { \ + .func = _func, \ + .val = _val, \ + } + +#define SUNXI_SRAM_DATA(_name, _reg, _off, _width, ...) \ + { \ + .name = _name, \ + .reg = _reg, \ + .offset = _off, \ + .width = _width, \ + .func = (struct sunxi_sram_func[]){ \ + __VA_ARGS__, { } }, \ + } + +static struct sunxi_sram_desc sun4i_a10_sram_a3_a4 = { + .data = SUNXI_SRAM_DATA("A3-A4", 0x4, 0x4, 2, + SUNXI_SRAM_MAP(0, "cpu"), + SUNXI_SRAM_MAP(1, "emac")), +}; + +static struct sunxi_sram_desc sun4i_a10_sram_d = { + .data = SUNXI_SRAM_DATA("D", 0x4, 0x0, 1, + SUNXI_SRAM_MAP(0, "cpu"), + SUNXI_SRAM_MAP(1, "usb-otg")), +}; + +static const struct of_device_id sunxi_sram_dt_ids[] = { + { + .compatible = "allwinner,sun4i-a10-sram-a3-a4", + .data = &sun4i_a10_sram_a3_a4.data, + }, + { + .compatible = "allwinner,sun4i-a10-sram-d", + .data = &sun4i_a10_sram_d.data, + }, + {} +}; + +static struct device *sram_dev; +static LIST_HEAD(claimed_sram); +static DEFINE_SPINLOCK(sram_lock); +static void __iomem *base; + +static int sunxi_sram_show(struct seq_file *s, void *data) +{ + struct device_node *sram_node, *section_node; + const struct sunxi_sram_data *sram_data; + const struct of_device_id *match; + struct sunxi_sram_func *func; + const __be32 *sram_addr_p, *section_addr_p; + u32 val; + + seq_puts(s, "Allwinner sunXi SRAM\n"); + seq_puts(s, "--------------------\n\n"); + + for_each_child_of_node(sram_dev->of_node, sram_node) { + sram_addr_p = of_get_address(sram_node, 0, NULL, NULL); + + seq_printf(s, "sram@%08x\n", + be32_to_cpu(*sram_addr_p)); + + for_each_child_of_node(sram_node, section_node) { + match = of_match_node(sunxi_sram_dt_ids, section_node); + if (!match) + continue; + sram_data = match->data; + + section_addr_p = of_get_address(section_node, 0, + NULL, NULL); + + seq_printf(s, "\tsection@%04x\t(%s)\n", + be32_to_cpu(*section_addr_p), + sram_data->name); + + val = readl(base + sram_data->reg); + val >>= sram_data->offset; + val &= sram_data->width; + + for (func = sram_data->func; func->func; func++) { + seq_printf(s, "\t\t%s%c\n", func->func, + func->val == val ? '*' : ' '); + } + } + + seq_puts(s, "\n"); + } + + return 0; +} + +static int sunxi_sram_open(struct inode *inode, struct file *file) +{ + return single_open(file, sunxi_sram_show, inode->i_private); +} + +static const struct file_operations sunxi_sram_fops = { + .open = sunxi_sram_open, + .read = seq_read, + .llseek = seq_lseek, + .release = single_release, +}; + +static inline struct sunxi_sram_desc *to_sram_desc(const struct sunxi_sram_data *data) +{ + return container_of(data, struct sunxi_sram_desc, data); +} + +static const struct sunxi_sram_data *sunxi_sram_of_parse(struct device_node *node, + unsigned int *value) +{ + const struct of_device_id *match; + struct of_phandle_args args; + int ret; + + ret = of_parse_phandle_with_fixed_args(node, "allwinner,sram", 1, 0, + &args); + if (ret) + return ERR_PTR(ret); + + if (!of_device_is_available(args.np)) { + ret = -EBUSY; + goto err; + } + + if (value) + *value = args.args[0]; + + match = of_match_node(sunxi_sram_dt_ids, args.np); + if (!match) { + ret = -EINVAL; + goto err; + } + + of_node_put(args.np); + return match->data; + +err: + of_node_put(args.np); + return ERR_PTR(ret); +} + +int sunxi_sram_claim(struct device *dev) +{ + const struct sunxi_sram_data *sram_data; + struct sunxi_sram_desc *sram_desc; + unsigned int device; + u32 val, mask; + + if (IS_ERR(base)) + return -EPROBE_DEFER; + + if (!dev || !dev->of_node) + return -EINVAL; + + sram_data = sunxi_sram_of_parse(dev->of_node, &device); + if (IS_ERR(sram_data)) + return PTR_ERR(sram_data); + + sram_desc = to_sram_desc(sram_data); + + spin_lock(&sram_lock); + + if (sram_desc->claimed) { + spin_unlock(&sram_lock); + return -EBUSY; + } + + mask = GENMASK(sram_data->offset + sram_data->width, sram_data->offset); + val = readl(base + sram_data->reg); + val &= ~mask; + writel(val | ((device << sram_data->offset) & mask), + base + sram_data->reg); + + spin_unlock(&sram_lock); + + return 0; +} +EXPORT_SYMBOL(sunxi_sram_claim); + +int sunxi_sram_release(struct device *dev) +{ + const struct sunxi_sram_data *sram_data; + struct sunxi_sram_desc *sram_desc; + + if (!dev || !dev->of_node) + return -EINVAL; + + sram_data = sunxi_sram_of_parse(dev->of_node, NULL); + if (IS_ERR(sram_data)) + return -EINVAL; + + sram_desc = to_sram_desc(sram_data); + + spin_lock(&sram_lock); + sram_desc->claimed = false; + spin_unlock(&sram_lock); + + return 0; +} +EXPORT_SYMBOL(sunxi_sram_release); + +static int sunxi_sram_probe(struct platform_device *pdev) +{ + struct resource *res; + struct dentry *d; + + sram_dev = &pdev->dev; + + res = platform_get_resource(pdev, IORESOURCE_MEM, 0); + base = devm_ioremap_resource(&pdev->dev, res); + if (IS_ERR(base)) + return PTR_ERR(base); + + of_platform_populate(pdev->dev.of_node, NULL, NULL, &pdev->dev); + + d = debugfs_create_file("sram", S_IRUGO, NULL, NULL, + &sunxi_sram_fops); + if (!d) + return -ENOMEM; + + return 0; +} + +static const struct of_device_id sunxi_sram_dt_match[] = { + { .compatible = "allwinner,sun4i-a10-sram-controller" }, + { }, +}; +MODULE_DEVICE_TABLE(of, sunxi_sram_dt_match); + +static struct platform_driver sunxi_sram_driver = { + .driver = { + .name = "sunxi-sram", + .of_match_table = sunxi_sram_dt_match, + }, + .probe = sunxi_sram_probe, +}; +module_platform_driver(sunxi_sram_driver); + +MODULE_AUTHOR("Maxime Ripard "); +MODULE_DESCRIPTION("Allwinner sunXi SRAM Controller Driver"); +MODULE_LICENSE("GPL"); diff --git a/pool/shard010/C/0138082_ping_test.c b/pool/shard010/C/0138082_ping_test.c new file mode 100644 index 0000000000000000000000000000000000000000..f512036295ea4b05552cc517aa115d337f328ad4 --- /dev/null +++ b/pool/shard010/C/0138082_ping_test.c @@ -0,0 +1,229 @@ +/* + * GPL HEADER START + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 2 only, + * as published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * General Public License version 2 for more details (a copy is included + * in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU General Public License + * version 2 along with this program; If not, see + * http://www.sun.com/software/products/lustre/docs/GPLv2.pdf + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + * + * GPL HEADER END + */ +/* + * Copyright (c) 2007, 2010, Oracle and/or its affiliates. All rights reserved. + * Use is subject to license terms. + * + * Copyright (c) 2012, Intel Corporation. + */ +/* + * This file is part of Lustre, http://www.lustre.org/ + * Lustre is a trademark of Sun Microsystems, Inc. + * + * lnet/selftest/conctl.c + * + * Test client & Server + * + * Author: Liang Zhen + */ + +#include "selftest.h" + +#define LST_PING_TEST_MAGIC 0xbabeface + +int ping_srv_workitems = SFW_TEST_WI_MAX; +CFS_MODULE_PARM(ping_srv_workitems, "i", int, 0644, "# PING server workitems"); + +typedef struct { + spinlock_t pnd_lock; /* serialize */ + int pnd_counter; /* sequence counter */ +} lst_ping_data_t; + +static lst_ping_data_t lst_ping_data; + +static int +ping_client_init(sfw_test_instance_t *tsi) +{ + sfw_session_t *sn = tsi->tsi_batch->bat_session; + + LASSERT(tsi->tsi_is_client); + LASSERT(sn != NULL && (sn->sn_features & ~LST_FEATS_MASK) == 0); + + spin_lock_init(&lst_ping_data.pnd_lock); + lst_ping_data.pnd_counter = 0; + + return 0; +} + +static void +ping_client_fini (sfw_test_instance_t *tsi) +{ + sfw_session_t *sn = tsi->tsi_batch->bat_session; + int errors; + + LASSERT (sn != NULL); + LASSERT (tsi->tsi_is_client); + + errors = atomic_read(&sn->sn_ping_errors); + if (errors) + CWARN ("%d pings have failed.\n", errors); + else + CDEBUG (D_NET, "Ping test finished OK.\n"); +} + +static int +ping_client_prep_rpc(sfw_test_unit_t *tsu, + lnet_process_id_t dest, srpc_client_rpc_t **rpc) +{ + srpc_ping_reqst_t *req; + sfw_test_instance_t *tsi = tsu->tsu_instance; + sfw_session_t *sn = tsi->tsi_batch->bat_session; + struct timeval tv; + int rc; + + LASSERT(sn != NULL); + LASSERT((sn->sn_features & ~LST_FEATS_MASK) == 0); + + rc = sfw_create_test_rpc(tsu, dest, sn->sn_features, 0, 0, rpc); + if (rc != 0) + return rc; + + req = &(*rpc)->crpc_reqstmsg.msg_body.ping_reqst; + + req->pnr_magic = LST_PING_TEST_MAGIC; + + spin_lock(&lst_ping_data.pnd_lock); + req->pnr_seq = lst_ping_data.pnd_counter++; + spin_unlock(&lst_ping_data.pnd_lock); + + cfs_fs_timeval(&tv); + req->pnr_time_sec = tv.tv_sec; + req->pnr_time_usec = tv.tv_usec; + + return rc; +} + +static void +ping_client_done_rpc (sfw_test_unit_t *tsu, srpc_client_rpc_t *rpc) +{ + sfw_test_instance_t *tsi = tsu->tsu_instance; + sfw_session_t *sn = tsi->tsi_batch->bat_session; + srpc_ping_reqst_t *reqst = &rpc->crpc_reqstmsg.msg_body.ping_reqst; + srpc_ping_reply_t *reply = &rpc->crpc_replymsg.msg_body.ping_reply; + struct timeval tv; + + LASSERT (sn != NULL); + + if (rpc->crpc_status != 0) { + if (!tsi->tsi_stopping) /* rpc could have been aborted */ + atomic_inc(&sn->sn_ping_errors); + CERROR ("Unable to ping %s (%d): %d\n", + libcfs_id2str(rpc->crpc_dest), + reqst->pnr_seq, rpc->crpc_status); + return; + } + + if (rpc->crpc_replymsg.msg_magic != SRPC_MSG_MAGIC) { + __swab32s(&reply->pnr_seq); + __swab32s(&reply->pnr_magic); + __swab32s(&reply->pnr_status); + } + + if (reply->pnr_magic != LST_PING_TEST_MAGIC) { + rpc->crpc_status = -EBADMSG; + atomic_inc(&sn->sn_ping_errors); + CERROR ("Bad magic %u from %s, %u expected.\n", + reply->pnr_magic, libcfs_id2str(rpc->crpc_dest), + LST_PING_TEST_MAGIC); + return; + } + + if (reply->pnr_seq != reqst->pnr_seq) { + rpc->crpc_status = -EBADMSG; + atomic_inc(&sn->sn_ping_errors); + CERROR ("Bad seq %u from %s, %u expected.\n", + reply->pnr_seq, libcfs_id2str(rpc->crpc_dest), + reqst->pnr_seq); + return; + } + + cfs_fs_timeval(&tv); + CDEBUG (D_NET, "%d reply in %u usec\n", reply->pnr_seq, + (unsigned)((tv.tv_sec - (unsigned)reqst->pnr_time_sec) * 1000000 + + (tv.tv_usec - reqst->pnr_time_usec))); + return; +} + +static int +ping_server_handle(struct srpc_server_rpc *rpc) +{ + struct srpc_service *sv = rpc->srpc_scd->scd_svc; + srpc_msg_t *reqstmsg = &rpc->srpc_reqstbuf->buf_msg; + srpc_msg_t *replymsg = &rpc->srpc_replymsg; + srpc_ping_reqst_t *req = &reqstmsg->msg_body.ping_reqst; + srpc_ping_reply_t *rep = &rpc->srpc_replymsg.msg_body.ping_reply; + + LASSERT (sv->sv_id == SRPC_SERVICE_PING); + + if (reqstmsg->msg_magic != SRPC_MSG_MAGIC) { + LASSERT (reqstmsg->msg_magic == __swab32(SRPC_MSG_MAGIC)); + + __swab32s(&req->pnr_seq); + __swab32s(&req->pnr_magic); + __swab64s(&req->pnr_time_sec); + __swab64s(&req->pnr_time_usec); + } + LASSERT (reqstmsg->msg_type == srpc_service2request(sv->sv_id)); + + if (req->pnr_magic != LST_PING_TEST_MAGIC) { + CERROR ("Unexpect magic %08x from %s\n", + req->pnr_magic, libcfs_id2str(rpc->srpc_peer)); + return -EINVAL; + } + + rep->pnr_seq = req->pnr_seq; + rep->pnr_magic = LST_PING_TEST_MAGIC; + + if ((reqstmsg->msg_ses_feats & ~LST_FEATS_MASK) != 0) { + replymsg->msg_ses_feats = LST_FEATS_MASK; + rep->pnr_status = EPROTO; + return 0; + } + + replymsg->msg_ses_feats = reqstmsg->msg_ses_feats; + + CDEBUG(D_NET, "Get ping %d from %s\n", + req->pnr_seq, libcfs_id2str(rpc->srpc_peer)); + return 0; +} + +sfw_test_client_ops_t ping_test_client; +void ping_init_test_client(void) +{ + ping_test_client.tso_init = ping_client_init; + ping_test_client.tso_fini = ping_client_fini; + ping_test_client.tso_prep_rpc = ping_client_prep_rpc; + ping_test_client.tso_done_rpc = ping_client_done_rpc; +} + +srpc_service_t ping_test_service; +void ping_init_test_service(void) +{ + ping_test_service.sv_id = SRPC_SERVICE_PING; + ping_test_service.sv_name = "ping_test"; + ping_test_service.sv_handler = ping_server_handle; + ping_test_service.sv_wi_total = ping_srv_workitems; +} diff --git a/pool/shard010/C/0138083_ltt-facility-loader-network.c b/pool/shard010/C/0138083_ltt-facility-loader-network.c new file mode 100644 index 0000000000000000000000000000000000000000..1b5ff752c06e8d7988757356ac12f157722aec06 --- /dev/null +++ b/pool/shard010/C/0138083_ltt-facility-loader-network.c @@ -0,0 +1,66 @@ +/* + * ltt-facility-loader-network.c + * + * (C) Copyright 2005 - + * Mathieu Desnoyers (mathieu.desnoyers@polymtl.ca) + * + * Contains the LTT facility loader. + * + */ + + +#include +#include +#include +#include +#include "ltt-facility-loader-network.h" + + +#ifdef CONFIG_LTT + +EXPORT_SYMBOL(LTT_FACILITY_SYMBOL); +EXPORT_SYMBOL(LTT_FACILITY_CHECKSUM_SYMBOL); + +static const char ltt_facility_name[] = LTT_FACILITY_NAME; + +#define SYMBOL_STRING(sym) #sym + +static struct ltt_facility facility = { + .name = ltt_facility_name, + .num_events = LTT_FACILITY_NUM_EVENTS, + .checksum = LTT_FACILITY_CHECKSUM, + .symbol = SYMBOL_STRING(LTT_FACILITY_SYMBOL), +}; + +static int __init facility_init(void) +{ + printk(KERN_INFO "LTT : ltt-facility-network init in kernel\n"); + + LTT_FACILITY_SYMBOL = ltt_facility_kernel_register(&facility); + LTT_FACILITY_CHECKSUM_SYMBOL = LTT_FACILITY_SYMBOL; + + return LTT_FACILITY_SYMBOL; +} + +#ifndef MODULE +__initcall(facility_init); +#else +module_init(facility_init); +static void __exit facility_exit(void) +{ + int err; + + err = ltt_facility_unregister(LTT_FACILITY_SYMBOL); + if(err != 0) + printk(KERN_ERR "LTT : Error in unregistering facility.\n"); + +} +module_exit(facility_exit) + +MODULE_LICENSE("GPL"); +MODULE_AUTHOR("Mathieu Desnoyers"); +MODULE_DESCRIPTION("Linux Trace Toolkit Facility"); + +#endif //MODULE + +#endif //CONFIG_LTT diff --git a/pool/shard010/C/0138084_t-sgn.c b/pool/shard010/C/0138084_t-sgn.c new file mode 100644 index 0000000000000000000000000000000000000000..6fb169b2c10526e85b0cafc2b97dc47f79cf4d5f --- /dev/null +++ b/pool/shard010/C/0138084_t-sgn.c @@ -0,0 +1,64 @@ +/* + Copyright (C) 2009 William Hart + + This file is part of FLINT. + + FLINT is free software: you can redistribute it and/or modify it under + the terms of the GNU Lesser General Public License (LGPL) as published + by the Free Software Foundation; either version 2.1 of the License, or + (at your option) any later version. See . +*/ + +#include +#include +#include +#include "flint.h" +#include "ulong_extras.h" +#include "fmpz.h" + +int +main(void) +{ + int i, result; + FLINT_TEST_INIT(state); + + flint_printf("sgn...."); + fflush(stdout); + + + + for (i = 0; i < 10000 * flint_test_multiplier(); i++) + { + fmpz_t a; + mpz_t b; + mp_size_t r1, r2; + + fmpz_init(a); + + mpz_init(b); + + fmpz_randtest(a, state, 200); + + fmpz_get_mpz(b, a); + + r1 = fmpz_sgn(a); + r2 = mpz_sgn(b); + result = (r1 == r2); + + if (!result) + { + flint_printf("FAIL:\n"); + gmp_printf("b = %Zd\n", b); + abort(); + } + + fmpz_clear(a); + + mpz_clear(b); + } + + FLINT_TEST_CLEANUP(state); + + flint_printf("PASS\n"); + return 0; +} diff --git a/pool/shard010/C/0138085_shichif.c b/pool/shard010/C/0138085_shichif.c new file mode 100644 index 0000000000000000000000000000000000000000..cbe37f2ffdbfbe52b315b1bccf4f49025145001e --- /dev/null +++ b/pool/shard010/C/0138085_shichif.c @@ -0,0 +1,218 @@ +/* shichif.c + * + * Hyperbolic sine and cosine integrals + * + * + * + * SYNOPSIS: + * + * float x, Chi, Shi; + * + * shichi( x, &Chi, &Shi ); + * + * + * DESCRIPTION: + * + * Approximates the integrals + * + * x + * - + * | | cosh t - 1 + * Chi(x) = eul + ln x + | ----------- dt, + * | | t + * - + * 0 + * + * x + * - + * | | sinh t + * Shi(x) = | ------ dt + * | | t + * - + * 0 + * + * where eul = 0.57721566490153286061 is Euler's constant. + * The integrals are evaluated by power series for x < 8 + * and by Chebyshev expansions for x between 8 and 88. + * For large x, both functions approach exp(x)/2x. + * Arguments greater than 88 in magnitude return MAXNUM. + * + * + * ACCURACY: + * + * Test interval 0 to 88. + * Relative error: + * arithmetic function # trials peak rms + * IEEE Shi 20000 3.5e-7 7.0e-8 + * Absolute error, except relative when |Chi| > 1: + * IEEE Chi 20000 3.8e-7 7.6e-8 + */ + +/* +Cephes Math Library Release 2.2: July, 1992 +Copyright 1984, 1987, 1992 by Stephen L. Moshier +Direct inquiries to 30 Frost Street, Cambridge, MA 02140 +*/ + + +#include "mconf.h" + +/* x exp(-x) shi(x), inverted interval 8 to 18 */ +static float S1[] = { +-3.56699611114982536845E-8, + 1.44818877384267342057E-7, + 7.82018215184051295296E-7, +-5.39919118403805073710E-6, +-3.12458202168959833422E-5, + 8.90136741950727517826E-5, + 2.02558474743846862168E-3, + 2.96064440855633256972E-2, + 1.11847751047257036625E0 +}; + +/* x exp(-x) shi(x), inverted interval 18 to 88 */ +static float S2[] = { + 1.69050228879421288846E-8, + 1.25391771228487041649E-7, + 1.16229947068677338732E-6, + 1.61038260117376323993E-5, + 3.49810375601053973070E-4, + 1.28478065259647610779E-2, + 1.03665722588798326712E0 +}; + + +/* x exp(-x) chin(x), inverted interval 8 to 18 */ +static float C1[] = { + 1.31458150989474594064E-8, +-4.75513930924765465590E-8, +-2.21775018801848880741E-7, + 1.94635531373272490962E-6, + 4.33505889257316408893E-6, +-6.13387001076494349496E-5, +-3.13085477492997465138E-4, + 4.97164789823116062801E-4, + 2.64347496031374526641E-2, + 1.11446150876699213025E0 +}; + +/* x exp(-x) chin(x), inverted interval 18 to 88 */ +static float C2[] = { +-3.00095178028681682282E-9, + 7.79387474390914922337E-8, + 1.06942765566401507066E-6, + 1.59503164802313196374E-5, + 3.49592575153777996871E-4, + 1.28475387530065247392E-2, + 1.03665693917934275131E0 +}; + + + +/* Sine and cosine integrals */ + +#define EUL 0.57721566490153286061 +extern float MACHEPF, MAXNUMF; + +#define fabsf(x) ( (x) < 0 ? -(x) : (x) ) + +#ifdef ANSIC +float logf(float ), expf(float), chbevlf(float, float *, int); +#else +float logf(), expf(), chbevlf(); +#endif + + + +#ifdef ANSIC +int shichif( float xx, float *si, float *ci ) +#else +int shichif( xx, si, ci ) +double xx; +float *si, *ci; +#endif +{ +float x, k, z, c, s, a; +short sign; + +x = xx; +if( x < 0.0 ) + { + sign = -1; + x = -x; + } +else + sign = 0; + + +if( x == 0.0 ) + { + *si = 0.0; + *ci = -MAXNUMF; + return( 0 ); + } + +if( x >= 8.0 ) + goto chb; + +z = x * x; + +/* Direct power series expansion */ + +a = 1.0; +s = 1.0; +c = 0.0; +k = 2.0; + +do + { + a *= z/k; + c += a/k; + k += 1.0; + a /= k; + s += a/k; + k += 1.0; + } +while( fabsf(a/s) > MACHEPF ); + +s *= x; +goto done; + + +chb: + +if( x < 18.0 ) + { + a = (576.0/x - 52.0)/10.0; + k = expf(x) / x; + s = k * chbevlf( a, S1, 9 ); + c = k * chbevlf( a, C1, 10 ); + goto done; + } + +if( x <= 88.0 ) + { + a = (6336.0/x - 212.0)/70.0; + k = expf(x) / x; + s = k * chbevlf( a, S2, 7 ); + c = k * chbevlf( a, C2, 7 ); + goto done; + } +else + { + if( sign ) + *si = -MAXNUMF; + else + *si = MAXNUMF; + *ci = MAXNUMF; + return(0); + } +done: +if( sign ) + s = -s; + +*si = s; + +*ci = EUL + logf(x) + c; +return(0); +} diff --git a/pool/shard010/C/0138086_dirhistory_menu.c b/pool/shard010/C/0138086_dirhistory_menu.c new file mode 100644 index 0000000000000000000000000000000000000000..68b2644a6af589f5363b1aec70aa7279e6f48591 --- /dev/null +++ b/pool/shard010/C/0138086_dirhistory_menu.c @@ -0,0 +1,132 @@ +/* vifm + * Copyright (C) 2001 Ken Steen. + * Copyright (C) 2011 xaizek. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA + */ + +#include "dirhistory_menu.h" + +#include /* NULL */ +#include /* strdup() */ + +#include "../cfg/config.h" +#include "../ui/ui.h" +#include "../utils/fs.h" +#include "../utils/str.h" +#include "../utils/string_array.h" +#include "../filelist.h" +#include "menus.h" + +static int execute_dirhistory_cb(FileView *view, menu_info *m); + +int +show_history_menu(FileView *view) +{ + int i; + int need_cleanup; + + static menu_info m; + init_menu_info(&m, strdup("Directory History"), + strdup("History disabled or empty")); + + m.execute_handler = &execute_dirhistory_cb; + + need_cleanup = 0; + for(i = 0; i < view->history_num && i < cfg.history_len; i++) + { + int j; + if(view->history[i].dir[0] == '\0') + break; + for(j = i + 1; j < view->history_num && j < cfg.history_len; j++) + if(stroscmp(view->history[i].dir, view->history[j].dir) == 0) + break; + if(j < view->history_num && j < cfg.history_len) + continue; + if(!is_valid_dir(view->history[i].dir)) + { + /* "Mark" directory as non-existent. */ + free(view->history[i].dir); + view->history[i].dir = NULL; + need_cleanup = 1; + continue; + } + + /* Change the current dir to reflect the current file. */ + if(stroscmp(view->history[i].dir, view->curr_dir) == 0) + { + (void)replace_string(&view->history[i].file, get_current_file_name(view)); + m.pos = m.len; + } + + m.len = add_to_string_array(&m.items, m.len, 1, view->history[i].dir); + } + + if(need_cleanup) + { + int i, j; + + /* Erase non existing directories from history. */ + j = 0; + for(i = 0; i < view->history_num && i < cfg.history_len; ++i) + { + if(view->history[i].dir == NULL) + { + free(view->history[i].file); + continue; + } + + if(j != i) + { + view->history[j] = view->history[i]; + + view->history[i].dir = NULL; + view->history[i].file = NULL; + view->history[i].rel_pos = -1; + } + + if(view->history_pos == i) + { + view->history_pos = j; + } + + ++j; + } + view->history_num = j; + } + + /* Reverse order in which items appear. */ + for(i = 0; i < m.len/2; i++) + { + char *t = m.items[i]; + m.items[i] = m.items[m.len - 1 - i]; + m.items[m.len - 1 - i] = t; + } + m.pos = m.len - 1 - m.pos; + + return display_menu(&m, view); +} + +/* Callback that is called when menu item is selected. Should return non-zero + * to stay in menu mode. */ +static int +execute_dirhistory_cb(FileView *view, menu_info *m) +{ + goto_selected_directory(view, m->items[m->pos]); + return 0; +} + +/* vim: set tabstop=2 softtabstop=2 shiftwidth=2 noexpandtab cinoptions-=(0 : */ +/* vim: set cinoptions+=t0 filetype=c : */ diff --git a/pool/shard010/C/0138087_20090907-1.c b/pool/shard010/C/0138087_20090907-1.c new file mode 100644 index 0000000000000000000000000000000000000000..907574c4230c83e513250ffc798f52dc68117e9c --- /dev/null +++ b/pool/shard010/C/0138087_20090907-1.c @@ -0,0 +1,84 @@ +struct platform_device; +typedef unsigned long __kernel_size_t; +typedef unsigned short __u16; +typedef unsigned int __u32; +typedef unsigned char u8; +typedef unsigned short u16; +typedef __kernel_size_t size_t; +typedef __u32 uint32_t; +static inline __attribute__ ((always_inline)) +uint32_t __attribute__ ((pure)) bfin_dspid (void) +{ + return ( { + uint32_t __v; __v;} + ); +} +struct list_head { + struct list_head *next, *prev; +}; +struct page { + union { + }; + struct list_head lru; +}; +struct device_driver { + const char *name; + struct module *owner; +}; +struct fb_info { + struct device *dev; +}; +struct platform_driver { + int (*probe) (struct platform_device *); + int (*remove) (struct platform_device *); + struct device_driver driver; +}; +struct firmware { + size_t size; + const u8 *data; +}; +struct metronomefb_par { + struct fb_info *info; +}; +struct waveform_hdr { + u8 trc; +}; +static u8 calc_cksum (int start, int end, u8 * mem) +{ + u8 tmp = 0; + int i; + for (i = start; i < end; i++) + tmp += mem[i]; + return tmp; +} +extern struct waveform_hdr *wfm_hdr; +extern int wmta; + +static int +load_waveform (u8 * mem, size_t size, int m, int t, struct metronomefb_par *par) +{ + int tta; + int trn = 0; + int i; + u8 cksum; + int cksum_idx; + struct device *dev = par->info->dev; + for (i = 0; i <= sizeof (*wfm_hdr) + wfm_hdr->trc; i++) { + if (mem[i] > t) { + trn = i - sizeof (*wfm_hdr) - 1; + } + } + tta = * (mem + wmta + m * 4) & 0x00FFFFFF; + cksum_idx = tta + trn * 4 + 3; + cksum = calc_cksum (cksum_idx - 3, cksum_idx, mem); + if (cksum != mem[cksum_idx]) { + abort(); + } +} +extern struct firmware *fw_entry; +extern struct metronomefb_par *par; + +int metronomefb_probe (struct platform_device *dev) +{ + return load_waveform ((u8 *) fw_entry->data, fw_entry->size, 3, 31, par); +} diff --git a/pool/shard010/C/0138088_msgrcv06.c b/pool/shard010/C/0138088_msgrcv06.c new file mode 100644 index 0000000000000000000000000000000000000000..e3458b9ad0d7bedf85bfb5cb9f668a4a3f7ed868 --- /dev/null +++ b/pool/shard010/C/0138088_msgrcv06.c @@ -0,0 +1,219 @@ +/* + * + * Copyright (c) International Business Machines Corp., 2001 + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See + * the GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +/* + * NAME + * msgrcv06.c + * + * DESCRIPTION + * msgrcv06 - test for EIDRM error + * + * ALGORITHM + * loop if that option was specified + * create a message queue with read/write permissions + * fork a child who sleeps on an attempted read with msgrcv() + * parent removes the queue then waits for child to complete + * check the errno value + * issue a PASS message if we get EIDRM + * otherwise, the tests fails + * issue a FAIL message + * child removes message queue if required + * parent callc cleanup + * + * USAGE: + * msgrcv06 [-c n] [-e] [-i n] [-I x] [-P x] [-t] + * where, -c n : Run n copies concurrently. + * -e : Turn on errno logging. + * -i n : Execute test n times. + * -I x : Execute test for x seconds. + * -P x : Pause for x seconds between iterations. + * -t : Turn on syscall timing. + * + * HISTORY + * 03/2001 - Written by Wayne Boyer + * 14/03/2008 Matthieu Fertré (Matthieu.Fertre@irisa.fr) + * - Fix concurrency issue. Due to the use of usleep function to + * synchronize processes, synchronization issues can occur on a loaded + * system. Fix this by using pipes to synchronize processes. + * + * + * RESTRICTIONS + * none + */ + +#include "test.h" + +#include "ipcmsg.h" + +#include +#include + +void do_child(void); +void cleanup(void); +void setup(void); +#ifdef UCLINUX +#define PIPE_NAME "msgrcv06" +void do_child_uclinux(void); +#endif + +char *TCID = "msgrcv06"; +int TST_TOTAL = 1; + +int msg_q_1 = -1; /* The message queue id created in setup */ + +MSGBUF rcv_buf; +pid_t c_pid; + +int main(int ac, char **av) +{ + int lc; + + tst_parse_opts(ac, av, NULL, NULL); + +#ifdef UCLINUX + maybe_run_child(&do_child_uclinux, "d", &msg_q_1); +#endif + + setup(); /* global setup */ + + /* The following loop checks looping state if -i option given */ + + for (lc = 0; TEST_LOOPING(lc); lc++) { + /* reset tst_count in case we are looping */ + tst_count = 0; + + /* + * set up the queue here so that multiple test iterations + * will work. + */ + msgkey = getipckey(); + + /* create a message queue with read/write permission */ + if ((msg_q_1 = msgget(msgkey, IPC_CREAT | IPC_EXCL | MSG_RW)) + == -1) { + tst_brkm(TBROK, cleanup, "Can't create message queue"); + } + + /* + * fork a child that will attempt to read a non-existent + * message from the queue + */ + if ((c_pid = FORK_OR_VFORK()) == -1) { + tst_brkm(TBROK, cleanup, "could not fork"); + } + + if (c_pid == 0) { /* child */ + /* + * Attempt to read a message without IPC_NOWAIT. + * With no message to read, the child sleeps. + */ + +#ifdef UCLINUX + if (self_exec(av[0], "d", msg_q_1) < 0) { + tst_brkm(TBROK, cleanup, "could not self_exec"); + } +#else + do_child(); +#endif + } else { + TST_PROCESS_STATE_WAIT(cleanup, c_pid, 'S'); + + /* remove the queue */ + rm_queue(msg_q_1); + + waitpid(c_pid, NULL, 0); + } + } + + tst_exit(); +} + +/* + * do_child() + */ +void do_child(void) +{ + TEST(msgrcv(msg_q_1, &rcv_buf, MSGSIZE, 1, 0)); + + if (TEST_RETURN != -1) { + tst_resm(TFAIL, "call succeeded when error expected"); + exit(-1); + } + + switch (TEST_ERRNO) { + case EIDRM: + tst_resm(TPASS, "expected failure - errno = %d : %s", + TEST_ERRNO, strerror(TEST_ERRNO)); + + /* mark the queue as invalid as it was removed */ + msg_q_1 = -1; + break; + default: + tst_resm(TFAIL, + "call failed with an unexpected error - %d : %s", + TEST_ERRNO, strerror(TEST_ERRNO)); + break; + } + + /* if it exists, remove the message queue that was created */ + rm_queue(msg_q_1); + + exit(0); +} + +#ifdef UCLINUX +/* + * do_child_uclinux() - capture signals again, then run do_child() + */ +void do_child_uclinux(void) +{ + tst_sig(FORK, SIG_IGN, cleanup); + + do_child(); +} +#endif + +/* + * setup() - performs all the ONE TIME setup for this test. + */ +void setup(void) +{ + + tst_sig(FORK, SIG_IGN, cleanup); + + TEST_PAUSE; + + /* + * Create a temporary directory and cd into it. + * This helps to ensure that a unique msgkey is created. + * See libs/libltpipc/libipc.c for more information. + */ + tst_tmpdir(); +} + +/* + * cleanup() - performs all the ONE TIME cleanup for this test at completion + * or premature exit. + */ +void cleanup(void) +{ + + tst_rmdir(); + +} diff --git a/pool/shard010/C/0138089_CWE134_Uncontrolled_Format_String__char_console_vprintf_34.c b/pool/shard010/C/0138089_CWE134_Uncontrolled_Format_String__char_console_vprintf_34.c new file mode 100644 index 0000000000000000000000000000000000000000..69c926b8d478ed9c6f0af992ed5f5f8cf28c8e9a --- /dev/null +++ b/pool/shard010/C/0138089_CWE134_Uncontrolled_Format_String__char_console_vprintf_34.c @@ -0,0 +1,193 @@ +/* TEMPLATE GENERATED TESTCASE FILE +Filename: CWE134_Uncontrolled_Format_String__char_console_vprintf_34.c +Label Definition File: CWE134_Uncontrolled_Format_String.vasinks.label.xml +Template File: sources-vasinks-34.tmpl.c +*/ +/* + * @description + * CWE: 134 Uncontrolled Format String + * BadSource: console Read input from the console + * GoodSource: Copy a fixed string into data + * Sinks: vprintf + * GoodSink: vprintf with a format string + * BadSink : vprintf without a format string + * Flow Variant: 34 Data flow: use of a union containing two methods of accessing the same data (within the same function) + * + * */ + +#include +#include "std_testcase.h" + +#ifndef _WIN32 +#include +#endif + +typedef union +{ + char * unionFirst; + char * unionSecond; +} CWE134_Uncontrolled_Format_String__char_console_vprintf_34_unionType; + +#ifndef OMITBAD + +static void badVaSink(char * data, ...) +{ + { + va_list args; + va_start(args, data); + /* POTENTIAL FLAW: Do not specify the format allowing a possible format string vulnerability */ + vprintf(data, args); + va_end(args); + } +} + +void CWE134_Uncontrolled_Format_String__char_console_vprintf_34_bad() +{ + char * data; + char dataBuffer[100] = ""; + data = dataBuffer; + { + /* Read input from the console */ + size_t dataLen = strlen(data); + /* if there is room in data, read into it from the console */ + if (100-dataLen > 1) + { + /* POTENTIAL FLAW: Read data from the console */ + if (fgets(data+dataLen, (int)(100-dataLen), stdin) != NULL) + { + /* The next few lines remove the carriage return from the string that is + * inserted by fgets() */ + dataLen = strlen(data); + if (dataLen > 0 && data[dataLen-1] == '\n') + { + data[dataLen-1] = '\0'; + } + } + else + { + printLine("fgets() failed"); + /* Restore NUL terminator if fgets fails */ + data[dataLen] = '\0'; + } + } + } + { + char * dataCopy = data; + char * data = dataCopy; + badVaSink(data, data); + } +} + +#endif /* OMITBAD */ + +#ifndef OMITGOOD + +/* goodG2B uses the GoodSource with the BadSink */ +static void goodG2BVaSink(char * data, ...) +{ + { + va_list args; + va_start(args, data); + /* POTENTIAL FLAW: Do not specify the format allowing a possible format string vulnerability */ + vprintf(data, args); + va_end(args); + } +} + +static void goodG2B() +{ + char * data; + CWE134_Uncontrolled_Format_String__char_console_vprintf_34_unionType myUnion; + char dataBuffer[100] = ""; + data = dataBuffer; + /* FIX: Use a fixed string that does not contain a format specifier */ + strcpy(data, "fixedstringtest"); + myUnion.unionFirst = data; + { + char * data = myUnion.unionSecond; + goodG2BVaSink(data, data); + } +} + +/* goodB2G uses the BadSource with the GoodSink */ +static void goodB2GVaSink(char * data, ...) +{ + { + va_list args; + va_start(args, data); + /* FIX: Specify the format disallowing a format string vulnerability */ + vprintf("%s", args); + va_end(args); + } +} + +static void goodB2G() +{ + char * data; + CWE134_Uncontrolled_Format_String__char_console_vprintf_34_unionType myUnion; + char dataBuffer[100] = ""; + data = dataBuffer; + { + /* Read input from the console */ + size_t dataLen = strlen(data); + /* if there is room in data, read into it from the console */ + if (100-dataLen > 1) + { + /* POTENTIAL FLAW: Read data from the console */ + if (fgets(data+dataLen, (int)(100-dataLen), stdin) != NULL) + { + /* The next few lines remove the carriage return from the string that is + * inserted by fgets() */ + dataLen = strlen(data); + if (dataLen > 0 && data[dataLen-1] == '\n') + { + data[dataLen-1] = '\0'; + } + } + else + { + printLine("fgets() failed"); + /* Restore NUL terminator if fgets fails */ + data[dataLen] = '\0'; + } + } + } + myUnion.unionFirst = data; + { + char * data = myUnion.unionSecond; + goodB2GVaSink(data, data); + } +} + +void CWE134_Uncontrolled_Format_String__char_console_vprintf_34_good() +{ + goodG2B(); + goodB2G(); +} + +#endif /* OMITGOOD */ + +/* Below is the main(). It is only used when building this testcase on + its own for testing or for building a binary to use in testing binary + analysis tools. It is not used when compiling all the testcases as one + application, which is how source code analysis tools are tested. */ +#ifdef INCLUDEMAIN + +int main(int argc, char * argv[]) +{ + /* seed randomness */ + srand( (unsigned)time(NULL) ); +#ifndef OMITGOOD + printLine("Calling good()..."); + CWE134_Uncontrolled_Format_String__char_console_vprintf_34_good(); + printLine("Finished good()"); +#endif /* OMITGOOD */ +#ifndef OMITBAD + printLine("Calling bad()..."); + CWE134_Uncontrolled_Format_String__char_console_vprintf_34_bad(); + printLine("Finished bad()"); +#endif /* OMITBAD */ + return 0; +} + +#endif diff --git a/pool/shard010/C/0138090_Descriptors.c b/pool/shard010/C/0138090_Descriptors.c new file mode 100644 index 0000000000000000000000000000000000000000..1a96e17a34717362188836c3f4e0ed4bb8aa4c50 --- /dev/null +++ b/pool/shard010/C/0138090_Descriptors.c @@ -0,0 +1,264 @@ +/* + LUFA Library + Copyright (C) Dean Camera, 2011. + + dean [at] fourwalledcubicle [dot] com + www.lufa-lib.org +*/ + +/* + Copyright 2011 Dean Camera (dean [at] fourwalledcubicle [dot] com) + + Permission to use, copy, modify, distribute, and sell this + software and its documentation for any purpose is hereby granted + without fee, provided that the above copyright notice appear in + all copies and that both that the copyright notice and this + permission notice and warranty disclaimer appear in supporting + documentation, and that the name of the author not be used in + advertising or publicity pertaining to distribution of the + software without specific, written prior permission. + + The author disclaim all warranties with regard to this + software, including all implied warranties of merchantability + and fitness. In no event shall the author be liable for any + special, indirect or consequential damages or any damages + whatsoever resulting from loss of use, data or profits, whether + in an action of contract, negligence or other tortious action, + arising out of or in connection with the use or performance of + this software. +*/ + +/** \file + * + * USB Device Descriptors, for library use when in USB device mode. Descriptors are special + * computer-readable structures which the host requests upon device enumeration, to determine + * the device's capabilities and functions. + */ + +#include "Descriptors.h" + +/** Device descriptor structure. This descriptor, located in SRAM memory, describes the overall + * device characteristics, including the supported USB version, control endpoint size and the + * number of device configurations. The descriptor is read out by the USB host when the enumeration + * process begins. + */ +const USB_Descriptor_Device_t DeviceDescriptor = +{ + .Header = {.Size = sizeof(USB_Descriptor_Device_t), .Type = DTYPE_Device}, + + .USBSpecification = VERSION_BCD(01.10), + .Class = CDC_CSCP_CDCClass, + .SubClass = CDC_CSCP_NoSpecificSubclass, + .Protocol = CDC_CSCP_NoSpecificProtocol, + + .Endpoint0Size = FIXED_CONTROL_ENDPOINT_SIZE, + + .VendorID = DEVICE_VID, + .ProductID = DEVICE_PID, + .ReleaseNumber = VERSION_BCD(00.01), + + .ManufacturerStrIndex = 0x02, + .ProductStrIndex = 0x01, + .SerialNumStrIndex = NO_DESCRIPTOR, + + .NumberOfConfigurations = FIXED_NUM_CONFIGURATIONS +}; + +/** Configuration descriptor structure. This descriptor, located in SRAM memory, describes the usage + * of the device in one of its supported configurations, including information about any device interfaces + * and endpoints. The descriptor is read out by the USB host during the enumeration process when selecting + * a configuration so that the host may correctly communicate with the USB device. + */ +const USB_Descriptor_Configuration_t ConfigurationDescriptor = +{ + .Config = + { + .Header = {.Size = sizeof(USB_Descriptor_Configuration_Header_t), .Type = DTYPE_Configuration}, + + .TotalConfigurationSize = sizeof(USB_Descriptor_Configuration_t), + .TotalInterfaces = 2, + + .ConfigurationNumber = 1, + .ConfigurationStrIndex = NO_DESCRIPTOR, + + .ConfigAttributes = USB_CONFIG_ATTR_BUSPOWERED, + + .MaxPowerConsumption = USB_CONFIG_POWER_MA(100) + }, + + .CDC_CCI_Interface = + { + .Header = {.Size = sizeof(USB_Descriptor_Interface_t), .Type = DTYPE_Interface}, + + .InterfaceNumber = 0, + .AlternateSetting = 0, + + .TotalEndpoints = 1, + + .Class = CDC_CSCP_CDCClass, + .SubClass = CDC_CSCP_ACMSubclass, + .Protocol = CDC_CSCP_ATCommandProtocol, + + .InterfaceStrIndex = NO_DESCRIPTOR + }, + + .CDC_Functional_Header = + { + .Header = {.Size = sizeof(USB_CDC_Descriptor_FunctionalHeader_t), .Type = DTYPE_CSInterface}, + .Subtype = 0x00, + + .CDCSpecification = VERSION_BCD(01.10), + }, + + .CDC_Functional_ACM = + { + .Header = {.Size = sizeof(USB_CDC_Descriptor_FunctionalACM_t), .Type = DTYPE_CSInterface}, + .Subtype = 0x02, + + .Capabilities = 0x04, + }, + + .CDC_Functional_Union = + { + .Header = {.Size = sizeof(USB_CDC_Descriptor_FunctionalUnion_t), .Type = DTYPE_CSInterface}, + .Subtype = 0x06, + + .MasterInterfaceNumber = 0, + .SlaveInterfaceNumber = 1, + }, + + .CDC_NotificationEndpoint = + { + .Header = {.Size = sizeof(USB_Descriptor_Endpoint_t), .Type = DTYPE_Endpoint}, + + .EndpointAddress = (ENDPOINT_DIR_IN | CDC_NOTIFICATION_EPNUM), + .Attributes = (EP_TYPE_INTERRUPT | ENDPOINT_ATTR_NO_SYNC | ENDPOINT_USAGE_DATA), + .EndpointSize = CDC_NOTIFICATION_EPSIZE, + .PollingIntervalMS = 0xFF + }, + + .CDC_DCI_Interface = + { + .Header = {.Size = sizeof(USB_Descriptor_Interface_t), .Type = DTYPE_Interface}, + + .InterfaceNumber = 1, + .AlternateSetting = 0, + + .TotalEndpoints = 2, + + .Class = CDC_CSCP_CDCDataClass, + .SubClass = CDC_CSCP_NoDataSubclass, + .Protocol = CDC_CSCP_NoDataProtocol, + + .InterfaceStrIndex = NO_DESCRIPTOR + }, + + .CDC_DataOutEndpoint = + { + .Header = {.Size = sizeof(USB_Descriptor_Endpoint_t), .Type = DTYPE_Endpoint}, + + .EndpointAddress = (ENDPOINT_DIR_OUT | CDC_RX_EPNUM), + .Attributes = (EP_TYPE_BULK | ENDPOINT_ATTR_NO_SYNC | ENDPOINT_USAGE_DATA), + .EndpointSize = CDC_TXRX_EPSIZE, + .PollingIntervalMS = 0x01 + }, + + .CDC_DataInEndpoint = + { + .Header = {.Size = sizeof(USB_Descriptor_Endpoint_t), .Type = DTYPE_Endpoint}, + + .EndpointAddress = (ENDPOINT_DIR_IN | CDC_TX_EPNUM), + .Attributes = (EP_TYPE_BULK | ENDPOINT_ATTR_NO_SYNC | ENDPOINT_USAGE_DATA), + .EndpointSize = CDC_TXRX_EPSIZE, + .PollingIntervalMS = 0x01 + } +}; + +/** Language descriptor structure. This descriptor, located in SRAM memory, is returned when the host requests + * the string descriptor with index 0 (the first index). It is actually an array of 16-bit integers, which indicate + * via the language ID table available at USB.org what languages the device supports for its string descriptors. + */ +const USB_Descriptor_String_t LanguageString = +{ + .Header = {.Size = USB_STRING_LEN(1), .Type = DTYPE_String}, + + .UnicodeString = {LANGUAGE_ID_ENG} +}; + +/** Product descriptor string. This is a Unicode string containing the product's details in human readable form, + * and is read out upon request by the host when the appropriate string ID is requested, listed in the Device + * Descriptor. + */ +const USB_Descriptor_String_t ProductString = +{ + .Header = {.Size = USB_STRING_LEN(16), .Type = DTYPE_String}, + + #if DEVICE_PID == 0x0036 + //.UnicodeString = L"Arduino Leonardo" + .UnicodeString = L"Helios Gadget" + #else + .UnicodeString = L"USB IO board " + #endif +}; + +const USB_Descriptor_String_t ManufNameString = +{ + .Header = {.Size = USB_STRING_LEN(16), .Type = DTYPE_String}, + + #if DEVICE_VID == 0x2341 + //.UnicodeString = L"Arduino LLC" + .UnicodeString = L"KITT Engineering" + #else + .UnicodeString = L"Unknown " + #endif +}; + +/** This function is called by the library when in device mode, and must be overridden (see LUFA library "USB Descriptors" + * documentation) by the application code so that the address and size of a requested descriptor can be given + * to the USB library. When the device receives a Get Descriptor request on the control endpoint, this function + * is called so that the descriptor details can be passed back and the appropriate descriptor sent back to the + * USB host. + */ +uint16_t CALLBACK_USB_GetDescriptor(const uint16_t wValue, + const uint8_t wIndex, + const void** const DescriptorAddress) +{ + const uint8_t DescriptorType = (wValue >> 8); + const uint8_t DescriptorNumber = (wValue & 0xFF); + + const void* Address = NULL; + uint16_t Size = NO_DESCRIPTOR; + + switch (DescriptorType) + { + case DTYPE_Device: + Address = &DeviceDescriptor; + Size = sizeof(USB_Descriptor_Device_t); + break; + case DTYPE_Configuration: + Address = &ConfigurationDescriptor; + Size = sizeof(USB_Descriptor_Configuration_t); + break; + case DTYPE_String: + if (!(DescriptorNumber)) + { + Address = &LanguageString; + Size = LanguageString.Header.Size; + } + else if (DescriptorNumber == DeviceDescriptor.ProductStrIndex) + { + Address = &ProductString; + Size = ProductString.Header.Size; + } else if (DescriptorNumber == DeviceDescriptor.ManufacturerStrIndex) + { + Address = &ManufNameString; + Size = ManufNameString.Header.Size; + } + + break; + } + + *DescriptorAddress = Address; + return Size; +} + diff --git a/pool/shard010/C/0138091_ipa-pta-14.c b/pool/shard010/C/0138091_ipa-pta-14.c new file mode 100644 index 0000000000000000000000000000000000000000..b62b08ff03af7f69b50bf10f7e77ad0e47fc7b46 --- /dev/null +++ b/pool/shard010/C/0138091_ipa-pta-14.c @@ -0,0 +1,32 @@ +/* { dg-do run } */ +/* { dg-options "-O2 -fipa-pta -fno-tree-fre -fno-tree-sra -fdump-ipa-pta-details" } */ + +struct X { + int i; + void *p; +}; + +static void * __attribute__((noinline,noclone)) +foo(struct X *q, void *p) +{ + struct X b; + b.p = p; + *q = b; + return q->p; +} +extern void abort (void); +int main() +{ + struct X a, c; + void *p; + a.p = (void *)&c; + p = foo(&a, &a); + /* { dg-final { scan-ipa-dump "foo.result = { NULL a\[^ \]* c\[^ \]* }" "pta" { target { ! keeps_null_pointer_checks } } } } */ + /* { dg-final { scan-ipa-dump "foo.result = { NONLOCAL a\[^ \]* c\[^ \]* }" "pta" { target { keeps_null_pointer_checks } } } } */ + ((struct X *)p)->p = (void *)0; + if (a.p != (void *)0) + abort (); + return 0; +} + +/* { dg-final { cleanup-ipa-dump "pta" } } */ diff --git a/pool/shard010/C/0138092_darken_x11.c b/pool/shard010/C/0138092_darken_x11.c new file mode 100644 index 0000000000000000000000000000000000000000..36cd660898200cd355e47036339782724faf2e8e --- /dev/null +++ b/pool/shard010/C/0138092_darken_x11.c @@ -0,0 +1,54 @@ +/* + Copyright (c) 2013, Lukas Holecek + + This file is part of TheRed. + + TheRed 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. + + TheRed 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 TheRed. If not, see . +*/ + +#include "darken.h" + +#include +#include +#include + +int darken(int r, int g, int b) +{ + int retval = -1; + int sz, i; + unsigned short *red, *green, *blue; + + Display *dpy = XOpenDisplay(NULL); + if (dpy == NULL) + return -1; + + XF86VidModeGetGammaRampSize(dpy, 0, &sz); + + red = malloc(sz * sizeof(unsigned short)); + green = malloc(sz * sizeof(unsigned short)); + blue = malloc(sz * sizeof(unsigned short)); + + XF86VidModeGetGammaRamp(dpy, 0, sz, red, green, blue); + + retval = change_colors(red, green, blue, sz, r, g, b); + + XF86VidModeSetGammaRamp(dpy, 0, sz, red, green, blue); + + free(red); + free(green); + free(blue); + XCloseDisplay(dpy); + + return retval; +} diff --git a/pool/shard010/C/0138093_pseudo_wrappers.c b/pool/shard010/C/0138093_pseudo_wrappers.c new file mode 100644 index 0000000000000000000000000000000000000000..e2f4388f3103df888bcf622edcb178abef245163 --- /dev/null +++ b/pool/shard010/C/0138093_pseudo_wrappers.c @@ -0,0 +1,229 @@ +/* shared functionality for the xattr code */ +/* Each of these functions is expecting to get an optional name, and + * a populated statbuf to use for sending messages to the server. + */ + +/* to avoid namespace pollution and such, we now duplicate the + * basic functionality of a POSIX ACL list, as used by libacl or + * the kernel. Documentation was obtained from the headers of libacl + * and from a page or two of _The Linux Programming Interface_, by + * Michael Kerrisk. + */ + +typedef struct { + uint16_t tag; + uint16_t perm; + uint32_t id; +} acl_entry; + +typedef struct { + uint32_t version; + acl_entry entries[]; +} acl_header; + +enum acl_tags { + ACL_UNDEFINED = 0x0, + ACL_USER_OBJ = 0x1, + ACL_USER = 0x2, + ACL_GROUP_OBJ = 0x4, + ACL_GROUP = 0x8, + ACL_MASK = 0x10, + ACL_OTHER = 0x20, +}; + +static const int endian_test = 1; +static const char *endian_tester = (char *) &endian_test; + +static inline int +le16(int x16) { + if (*endian_tester) { + return x16; + } else { + return ((x16 & 0xff) << 8) | ((x16 & 0xff00) >> 8); + } +} + +static inline int +le32(int x32) { + if (*endian_tester) { + return x32; + } else { + return ((x32 & 0xff) << 24) | ((x32 & 0xff00) << 8) | + ((x32 & 0xff0000) >> 8) | ((x32 & 0xff000000) >> 24); + } +} + +/* set mode to match the contents of header. Return non-zero on error. + * On a zero return, mode is a valid posix mode, and *extra is set to + * 1 if any of the entries are not reflected by that mode. On a non-zero + * return, no promises are made about *extra or *mode. + */ +static int +posix_permissions(const acl_header *header, int entries, int *extra, int *mode) { + int acl_seen = 0; + if (le32(header->version) != 2) { + pseudo_diag("Fatal: ACL support no available for header version %d.\n", + le32(header->version)); + return 1; + } + *mode = 0; + *extra = 0; + for (int i = 0; i < entries; ++i) { + const acl_entry *e = &header->entries[i]; + int tag = le16(e->tag); + int perm = le16(e->perm); + acl_seen |= tag; + switch (tag) { + case ACL_USER_OBJ: + *mode = *mode | (perm << 6); + break; + case ACL_GROUP_OBJ: + *mode = *mode | (perm << 3); + break; + case ACL_OTHER: + *mode = *mode | perm; + break; + case ACL_USER: + case ACL_GROUP: + case ACL_MASK: + *extra = *extra + 1; + break; + default: + pseudo_debug(PDBGF_XATTR, "Unknown tag in ACL: 0x%x.\n", + tag); + return 1; + } + } + return 0; +} + +#define RC_AND_BUF \ + int rc; \ + PSEUDO_STATBUF buf; \ + if (path) { \ + rc = base_lstat(path, &buf); \ + } else { \ + rc = base_fstat(fd, &buf); \ + } \ + if (rc == -1) { \ + return rc; \ + } + +static ssize_t shared_getxattr(const char *path, int fd, const char *name, void *value, size_t size) { + RC_AND_BUF + + pseudo_debug(PDBGF_XATTR, "getxattr(%s [fd %d], %s)\n", + path ? path : "", fd, name); + pseudo_msg_t *result = pseudo_client_op(OP_GET_XATTR, 0, fd, -1, path, &buf, name); + if (result->result != RESULT_SUCCEED) { + errno = ENOATTR; + return -1; + } + + if (value) { + pseudo_debug(PDBGF_XATTR, "returned attributes: '%s' (%d bytes)\n", + result->path, result->pathlen); + if (size >= result->pathlen) { + memcpy(value, result->path, result->pathlen); + } else { + memcpy(value, result->path, size); + errno = ERANGE; + } + } + return result->pathlen; +} + +static int shared_setxattr(const char *path, int fd, const char *name, const void *value, size_t size, int flags) { + RC_AND_BUF + pseudo_op_t op; + + pseudo_debug(PDBGF_XATTR, "setxattr(%s [fd %d], %s => '%.*s')\n", + path ? path : "", fd, name, (int) size, (char *) value); + + /* this may be a plain chmod */ + if (!strcmp(name, "system.posix_acl_access")) { + int extra; + int mode; + int entries = (size - sizeof(acl_header)) / sizeof(acl_entry); + if (!posix_permissions(value, entries, &extra, &mode)) { + pseudo_debug(PDBGF_XATTR, "posix_acl_access translated to mode %04o. Remaining attribute(s): %d.\n", + mode, extra); + buf.st_mode = mode; + /* we want to actually issue a corresponding chmod, + * as well, or else the file ends up 0600 on the + * host. Using the slightly-less-efficient wrap_chmod + * avoids possible misalignment. + */ + if (path) { + wrap_chmod(path, mode); + } else { + wrap_fchmod(fd, mode); + } + /* we are sneaky, and do not actually record this using + * extended attributes. */ + if (!extra) { + return 0; + } + } + } + + switch (flags) { + case XATTR_CREATE: + op = OP_CREATE_XATTR; + break; + case XATTR_REPLACE: + op = OP_REPLACE_XATTR; + break; + default: + op = OP_SET_XATTR; + break; + } + + pseudo_msg_t *result = pseudo_client_op(op, 0, fd, -1, path, &buf, name, value, size); + + /* we automatically assume success */ + if (op == OP_SET_XATTR) { + return 0; + } + + /* CREATE/REPLACE operations can report failure */ + if (!result || result->result == RESULT_FAIL) { + return -1; + } + + return 0; +} + +static ssize_t shared_listxattr(const char *path, int fd, char *list, size_t size) { + RC_AND_BUF + pseudo_msg_t *result = pseudo_client_op(OP_LIST_XATTR, 0, fd, -1, path, &buf); + if (result->result != RESULT_SUCCEED) { + pseudo_debug(PDBGF_XATTR, "listxattr: no success.\n"); + errno = ENOATTR; + return -1; + } + if (list) { + pseudo_debug(PDBGF_XATTR, "listxattr: %d bytes of names, starting '%.*s'\n", + (int) result->pathlen, (int) result->pathlen, result->path); + if (size >= result->pathlen) { + memcpy(list, result->path, result->pathlen); + } else { + memcpy(list, result->path, size); + errno = ERANGE; + } + } + return result->pathlen; +} + +static int shared_removexattr(const char *path, int fd, const char *name) { + RC_AND_BUF + pseudo_msg_t *result = pseudo_client_op(OP_REMOVE_XATTR, 0, fd, -1, path, &buf, name); + + if (result->result != RESULT_SUCCEED) { + /* docs say ENOATTR, but I don't have one */ + errno = ENOENT; + return -1; + } + return 0; +} + diff --git a/pool/shard010/C/0138094_restart_7k.c b/pool/shard010/C/0138094_restart_7k.c new file mode 100644 index 0000000000000000000000000000000000000000..6f0740e446572d7a36cf735978f1bb0bafe0bc2e --- /dev/null +++ b/pool/shard010/C/0138094_restart_7k.c @@ -0,0 +1,103 @@ +/* Copyright (c) 2012, Code Aurora Forum. 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 version 2 and + * only version 2 as published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + */ + +#include +#include +#include +#include +#include +#include +#include +#include + +#include "devices-msm7x2xa.h" + +static uint32_t restart_reason = 0x776655AA; + +static void msm_pm_power_off(void) +{ + msm_proc_comm(PCOM_POWER_DOWN, 0, 0); + for (;;) + ; +} + +static void msm_pm_restart(char str, const char *cmd) +{ + pr_debug("The reset reason is %x\n", restart_reason); + + /* Disable interrupts */ + local_irq_disable(); + local_fiq_disable(); + + /* + * Take out a flat memory mapping and will + * insert a 1:1 mapping in place of + * the user-mode pages to ensure predictable results + * This function takes care of flushing the caches + * and flushing the TLB. + */ + setup_mm_for_reboot(); + + msm_proc_comm(PCOM_RESET_CHIP, &restart_reason, 0); + + for (;;) + ; +} + +static int msm_reboot_call + (struct notifier_block *this, unsigned long code, void *_cmd) +{ + if ((code == SYS_RESTART) && _cmd) { + char *cmd = _cmd; + if (!strncmp(cmd, "bootloader", 10)) { + restart_reason = 0x77665500; + } else if (!strncmp(cmd, "recovery", 8)) { + restart_reason = 0x77665502; + } else if (!strncmp(cmd, "eraseflash", 10)) { + restart_reason = 0x776655EF; + } else if (!strncmp(cmd, "oem-", 4)) { + unsigned long code; + int res; + res = kstrtoul(cmd + 4, 16, &code); + code &= 0xff; + restart_reason = 0x6f656d00 | code; +#ifdef CONFIG_HUAWEI_KERNEL + } else if (!strcmp(cmd, "mtkupdate")) { +#define MTK_DOWNLOAD_EN 0x6d74646c + restart_reason = MTK_DOWNLOAD_EN; +#endif + } else { + restart_reason = 0x77665501; + } + } + return NOTIFY_DONE; +} + +static struct notifier_block msm_reboot_notifier = { + .notifier_call = msm_reboot_call, +}; + +static int __init msm_pm_restart_init(void) +{ + int ret; + + pm_power_off = msm_pm_power_off; + arm_pm_restart = msm_pm_restart; + + ret = register_reboot_notifier(&msm_reboot_notifier); + if (ret) + pr_err("Failed to register reboot notifier\n"); + + return ret; +} +late_initcall(msm_pm_restart_init); diff --git a/pool/shard010/C/0138095_phy-exynos-mipi-video.c b/pool/shard010/C/0138095_phy-exynos-mipi-video.c new file mode 100644 index 0000000000000000000000000000000000000000..b55a92e1249626ba7fc2aad781bd8a82ac169069 --- /dev/null +++ b/pool/shard010/C/0138095_phy-exynos-mipi-video.c @@ -0,0 +1,175 @@ +/* + * Samsung S5P/EXYNOS SoC series MIPI CSIS/DSIM DPHY driver + * + * Copyright (C) 2013 Samsung Electronics Co., Ltd. + * Author: Sylwester Nawrocki + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 2 as + * published by the Free Software Foundation. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +/* MIPI_PHYn_CONTROL register offset: n = 0..1 */ +#define EXYNOS_MIPI_PHY_CONTROL(n) ((n) * 4) +#define EXYNOS_MIPI_PHY_ENABLE (1 << 0) +#define EXYNOS_MIPI_PHY_SRESETN (1 << 1) +#define EXYNOS_MIPI_PHY_MRESETN (1 << 2) +#define EXYNOS_MIPI_PHY_RESET_MASK (3 << 1) + +enum exynos_mipi_phy_id { + EXYNOS_MIPI_PHY_ID_CSIS0, + EXYNOS_MIPI_PHY_ID_DSIM0, + EXYNOS_MIPI_PHY_ID_CSIS1, + EXYNOS_MIPI_PHY_ID_DSIM1, + EXYNOS_MIPI_PHYS_NUM +}; + +#define is_mipi_dsim_phy_id(id) \ + ((id) == EXYNOS_MIPI_PHY_ID_DSIM0 || (id) == EXYNOS_MIPI_PHY_ID_DSIM1) + +struct exynos_mipi_video_phy { + spinlock_t slock; + struct video_phy_desc { + struct phy *phy; + unsigned int index; + } phys[EXYNOS_MIPI_PHYS_NUM]; + void __iomem *regs; +}; + +static int __set_phy_state(struct exynos_mipi_video_phy *state, + enum exynos_mipi_phy_id id, unsigned int on) +{ + void __iomem *addr; + u32 reg, reset; + + addr = state->regs + EXYNOS_MIPI_PHY_CONTROL(id / 2); + + if (is_mipi_dsim_phy_id(id)) + reset = EXYNOS_MIPI_PHY_MRESETN; + else + reset = EXYNOS_MIPI_PHY_SRESETN; + + spin_lock(&state->slock); + reg = readl(addr); + if (on) + reg |= reset; + else + reg &= ~reset; + writel(reg, addr); + + /* Clear ENABLE bit only if MRESETN, SRESETN bits are not set. */ + if (on) + reg |= EXYNOS_MIPI_PHY_ENABLE; + else if (!(reg & EXYNOS_MIPI_PHY_RESET_MASK)) + reg &= ~EXYNOS_MIPI_PHY_ENABLE; + + writel(reg, addr); + spin_unlock(&state->slock); + return 0; +} + +#define to_mipi_video_phy(desc) \ + container_of((desc), struct exynos_mipi_video_phy, phys[(desc)->index]); + +static int exynos_mipi_video_phy_power_on(struct phy *phy) +{ + struct video_phy_desc *phy_desc = phy_get_drvdata(phy); + struct exynos_mipi_video_phy *state = to_mipi_video_phy(phy_desc); + + return __set_phy_state(state, phy_desc->index, 1); +} + +static int exynos_mipi_video_phy_power_off(struct phy *phy) +{ + struct video_phy_desc *phy_desc = phy_get_drvdata(phy); + struct exynos_mipi_video_phy *state = to_mipi_video_phy(phy_desc); + + return __set_phy_state(state, phy_desc->index, 0); +} + +static struct phy *exynos_mipi_video_phy_xlate(struct device *dev, + struct of_phandle_args *args) +{ + struct exynos_mipi_video_phy *state = dev_get_drvdata(dev); + + if (WARN_ON(args->args[0] >= EXYNOS_MIPI_PHYS_NUM)) + return ERR_PTR(-ENODEV); + + return state->phys[args->args[0]].phy; +} + +static struct phy_ops exynos_mipi_video_phy_ops = { + .power_on = exynos_mipi_video_phy_power_on, + .power_off = exynos_mipi_video_phy_power_off, + .owner = THIS_MODULE, +}; + +static int exynos_mipi_video_phy_probe(struct platform_device *pdev) +{ + struct exynos_mipi_video_phy *state; + struct device *dev = &pdev->dev; + struct resource *res; + struct phy_provider *phy_provider; + unsigned int i; + + state = devm_kzalloc(dev, sizeof(*state), GFP_KERNEL); + if (!state) + return -ENOMEM; + + res = platform_get_resource(pdev, IORESOURCE_MEM, 0); + + state->regs = devm_ioremap_resource(dev, res); + if (IS_ERR(state->regs)) + return PTR_ERR(state->regs); + + dev_set_drvdata(dev, state); + spin_lock_init(&state->slock); + + for (i = 0; i < EXYNOS_MIPI_PHYS_NUM; i++) { + struct phy *phy = devm_phy_create(dev, NULL, + &exynos_mipi_video_phy_ops, NULL); + if (IS_ERR(phy)) { + dev_err(dev, "failed to create PHY %d\n", i); + return PTR_ERR(phy); + } + + state->phys[i].phy = phy; + state->phys[i].index = i; + phy_set_drvdata(phy, &state->phys[i]); + } + + phy_provider = devm_of_phy_provider_register(dev, + exynos_mipi_video_phy_xlate); + + return PTR_ERR_OR_ZERO(phy_provider); +} + +static const struct of_device_id exynos_mipi_video_phy_of_match[] = { + { .compatible = "samsung,s5pv210-mipi-video-phy" }, + { }, +}; +MODULE_DEVICE_TABLE(of, exynos_mipi_video_phy_of_match); + +static struct platform_driver exynos_mipi_video_phy_driver = { + .probe = exynos_mipi_video_phy_probe, + .driver = { + .of_match_table = exynos_mipi_video_phy_of_match, + .name = "exynos-mipi-video-phy", + .owner = THIS_MODULE, + } +}; +module_platform_driver(exynos_mipi_video_phy_driver); + +MODULE_DESCRIPTION("Samsung S5P/EXYNOS SoC MIPI CSI-2/DSI PHY driver"); +MODULE_AUTHOR("Sylwester Nawrocki "); +MODULE_LICENSE("GPL v2"); diff --git a/pool/shard010/C/0138096_kfd_device_queue_manager_vi.c b/pool/shard010/C/0138096_kfd_device_queue_manager_vi.c new file mode 100644 index 0000000000000000000000000000000000000000..20553dcd257d86f0cc228c2bfa5f2e67488bacf9 --- /dev/null +++ b/pool/shard010/C/0138096_kfd_device_queue_manager_vi.c @@ -0,0 +1,64 @@ +/* + * Copyright 2014 Advanced Micro Devices, Inc. + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + * THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR + * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + * OTHER DEALINGS IN THE SOFTWARE. + * + */ + +#include "kfd_device_queue_manager.h" + +static bool set_cache_memory_policy_vi(struct device_queue_manager *dqm, + struct qcm_process_device *qpd, + enum cache_policy default_policy, + enum cache_policy alternate_policy, + void __user *alternate_aperture_base, + uint64_t alternate_aperture_size); +static int register_process_vi(struct device_queue_manager *dqm, + struct qcm_process_device *qpd); +static int initialize_cpsch_vi(struct device_queue_manager *dqm); + +void device_queue_manager_init_vi(struct device_queue_manager_ops *ops) +{ + pr_warn("amdkfd: VI DQM is not currently supported\n"); + + ops->set_cache_memory_policy = set_cache_memory_policy_vi; + ops->register_process = register_process_vi; + ops->initialize = initialize_cpsch_vi; +} + +static bool set_cache_memory_policy_vi(struct device_queue_manager *dqm, + struct qcm_process_device *qpd, + enum cache_policy default_policy, + enum cache_policy alternate_policy, + void __user *alternate_aperture_base, + uint64_t alternate_aperture_size) +{ + return false; +} + +static int register_process_vi(struct device_queue_manager *dqm, + struct qcm_process_device *qpd) +{ + return -1; +} + +static int initialize_cpsch_vi(struct device_queue_manager *dqm) +{ + return 0; +} diff --git a/pool/shard010/C/0138097_SecPlatformInformation.c b/pool/shard010/C/0138097_SecPlatformInformation.c new file mode 100644 index 0000000000000000000000000000000000000000..6265fdee67a3419d7687225416120a646e130ef2 --- /dev/null +++ b/pool/shard010/C/0138097_SecPlatformInformation.c @@ -0,0 +1,84 @@ +/** @file + Sample to provide SecPlatformInformation function. + + Copyright (c) 2014, Intel Corporation. All rights reserved.
+ This program and the accompanying materials + are licensed and made available under the terms and conditions of the BSD License + which accompanies this distribution. The full text of the license may be found at + http://opensource.org/licenses/bsd-license.php. + + THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS, + WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED. + +**/ + +#include + +#include +#include + +#include +#include + +/** + This interface conveys state information out of the Security (SEC) phase into PEI. + + @param[in] PeiServices Pointer to the PEI Services Table. + @param[in,out] StructureSize Pointer to the variable describing size of the input buffer. + @param[out] PlatformInformationRecord Pointer to the EFI_SEC_PLATFORM_INFORMATION_RECORD. + + @retval EFI_SUCCESS The data was successfully returned. + @retval EFI_BUFFER_TOO_SMALL The buffer was too small. + +**/ +EFI_STATUS +EFIAPI +SecPlatformInformation ( + IN CONST EFI_PEI_SERVICES **PeiServices, + IN OUT UINT64 *StructureSize, + OUT EFI_SEC_PLATFORM_INFORMATION_RECORD *PlatformInformationRecord + ) +{ + UINT32 *Bist; + UINT32 Size; + UINT32 Count; + UINT32 TopOfTemporaryRam; + VOID *TopOfTemporaryRamPpi; + EFI_STATUS Status; + + DEBUG ((DEBUG_INFO, "SecPlatformInformation\n")); + + Status = (*PeiServices)->LocatePpi ( + PeiServices, + &gTopOfTemporaryRamPpiGuid, + 0, + NULL, + (VOID **) &TopOfTemporaryRamPpi + ); + if (EFI_ERROR (Status)) { + return EFI_NOT_FOUND; + } + + // + // The entries of BIST information, together with the number of them, + // reside in the bottom of stack, left untouched by normal stack operation. + // This routine copies the BIST information to the buffer pointed by + // PlatformInformationRecord for output. + // + TopOfTemporaryRam = (UINT32)(UINTN)TopOfTemporaryRamPpi - sizeof (UINT32); + TopOfTemporaryRam -= sizeof(UINT32) * 2; + Count = *((UINT32 *)(UINTN) (TopOfTemporaryRam - sizeof (UINT32))); + Size = Count * sizeof (IA32_HANDOFF_STATUS); + + if ((*StructureSize) < (UINT64) Size) { + *StructureSize = Size; + return EFI_BUFFER_TOO_SMALL; + } + + *StructureSize = Size; + Bist = (UINT32 *) (TopOfTemporaryRam - sizeof (UINT32) - Size); + + CopyMem (PlatformInformationRecord, Bist, Size); + + return EFI_SUCCESS; +} diff --git a/pool/shard010/C/0138098_basic.c b/pool/shard010/C/0138098_basic.c new file mode 100644 index 0000000000000000000000000000000000000000..b6f8ab52c39615dcfd944f861620f7029c016507 --- /dev/null +++ b/pool/shard010/C/0138098_basic.c @@ -0,0 +1,24 @@ +#include +#include + +int a(void *p){ + static int counter=0; + counter+=1; + printf("a: %d\n",counter); + return counter; +} + +int b(void *p){ + printf("b\n"); + return 0; +} + +int main(){ + struct StateMachine *machine; + machine=state_newmachine(); + state_add_transition(machine,a,1,b); + state_add_transition(machine,b,0,a); + state_add_transition(machine,a,2,NULL); + state_start(machine,a,NULL); + state_free(machine); +} diff --git a/pool/shard010/C/0138099_platsmp.c b/pool/shard010/C/0138099_platsmp.c new file mode 100644 index 0000000000000000000000000000000000000000..3db7782f3afb3ed68e85eece8fec575524a08dbe --- /dev/null +++ b/pool/shard010/C/0138099_platsmp.c @@ -0,0 +1,177 @@ +/* + * Copyright (C) 2002 ARM Ltd. + * Copyright (C) 2008 STMicroelctronics. + * Copyright (C) 2009 ST-Ericsson. + * Author: Srinidhi Kasagar + * + * This file is based on arm realview platform + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 2 as + * published by the Free Software Foundation. + */ +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +/* This is called from headsmp.S to wakeup the secondary core */ +extern void u8500_secondary_startup(void); + +/* + * Write pen_release in a way that is guaranteed to be visible to all + * observers, irrespective of whether they're taking part in coherency + * or not. This is necessary for the hotplug code to work reliably. + */ +static void write_pen_release(int val) +{ + pen_release = val; + smp_wmb(); + __cpuc_flush_dcache_area((void *)&pen_release, sizeof(pen_release)); + outer_clean_range(__pa(&pen_release), __pa(&pen_release + 1)); +} + +static void __iomem *scu_base_addr(void) +{ + if (cpu_is_u8500_family() || cpu_is_ux540_family()) + return __io_address(U8500_SCU_BASE); + else + ux500_unknown_soc(); + + return NULL; +} + +static DEFINE_SPINLOCK(boot_lock); + +static void __cpuinit ux500_secondary_init(unsigned int cpu) +{ + /* + * if any interrupts are already enabled for the primary + * core (e.g. timer irq), then they will not have been enabled + * for us: do so + */ + gic_secondary_init(0); + + /* + * let the primary processor know we're out of the + * pen, then head off into the C entry point + */ + write_pen_release(-1); + + /* + * Synchronise with the boot thread. + */ + spin_lock(&boot_lock); + spin_unlock(&boot_lock); +} + +static int __cpuinit ux500_boot_secondary(unsigned int cpu, struct task_struct *idle) +{ + unsigned long timeout; + + /* + * set synchronisation state between this boot processor + * and the secondary one + */ + spin_lock(&boot_lock); + + /* + * The secondary processor is waiting to be released from + * the holding pen - release it, then wait for it to flag + * that it has been released by resetting pen_release. + */ + write_pen_release(cpu_logical_map(cpu)); + + smp_send_reschedule(cpu); + + timeout = jiffies + (1 * HZ); + while (time_before(jiffies, timeout)) { + if (pen_release == -1) + break; + } + + /* + * now the secondary core is starting up let it run its + * calibrations, then wait for it to finish + */ + spin_unlock(&boot_lock); + + return pen_release != -1 ? -ENOSYS : 0; +} + +static void __init wakeup_secondary(void) +{ + void __iomem *backupram; + + if (cpu_is_u8500_family() || cpu_is_ux540_family()) + backupram = __io_address(U8500_BACKUPRAM0_BASE); + else + ux500_unknown_soc(); + + /* + * write the address of secondary startup into the backup ram register + * at offset 0x1FF4, then write the magic number 0xA1FEED01 to the + * backup ram register at offset 0x1FF0, which is what boot rom code + * is waiting for. This would wake up the secondary core from WFE + */ +#define UX500_CPU1_JUMPADDR_OFFSET 0x1FF4 + __raw_writel(virt_to_phys(u8500_secondary_startup), + backupram + UX500_CPU1_JUMPADDR_OFFSET); + +#define UX500_CPU1_WAKEMAGIC_OFFSET 0x1FF0 + __raw_writel(0xA1FEED01, + backupram + UX500_CPU1_WAKEMAGIC_OFFSET); + + /* make sure write buffer is drained */ + mb(); +} + +/* + * Initialise the CPU possible map early - this describes the CPUs + * which may be present or become present in the system. + */ +static void __init ux500_smp_init_cpus(void) +{ + void __iomem *scu_base = scu_base_addr(); + unsigned int i, ncores; + + ncores = scu_base ? scu_get_core_count(scu_base) : 1; + + /* sanity check */ + if (ncores > nr_cpu_ids) { + pr_warn("SMP: %u cores greater than maximum (%u), clipping\n", + ncores, nr_cpu_ids); + ncores = nr_cpu_ids; + } + + for (i = 0; i < ncores; i++) + set_cpu_possible(i, true); + + set_smp_cross_call(gic_raise_softirq); +} + +static void __init ux500_smp_prepare_cpus(unsigned int max_cpus) +{ + + scu_enable(scu_base_addr()); + wakeup_secondary(); +} + +struct smp_operations ux500_smp_ops __initdata = { + .smp_init_cpus = ux500_smp_init_cpus, + .smp_prepare_cpus = ux500_smp_prepare_cpus, + .smp_secondary_init = ux500_secondary_init, + .smp_boot_secondary = ux500_boot_secondary, +#ifdef CONFIG_HOTPLUG_CPU + .cpu_die = ux500_cpu_die, +#endif +}; diff --git a/pool/shard010/C/0138100_artst.c b/pool/shard010/C/0138100_artst.c new file mode 100644 index 0000000000000000000000000000000000000000..bd3288ac57d6e64b3cfeff15157f9036a4b103c2 --- /dev/null +++ b/pool/shard010/C/0138100_artst.c @@ -0,0 +1,91 @@ +/* Quick hack to test input of non aligned data */ +/* Quickly hacked from atst */ +/* PAB 1/8/92 */ + +#include + +#if 1 /* posix version */ + +#include +#include +#include +#include + +int main(int argc, char **argv) +{ + int sz; + char *fred = "abcdefghijklmnopqrstuvwxyz" + "abcdefghijklmnopqrstuvwxyz" + "abcdefghijklmnopqrstuvwxyz" + "abcdefghijklmnopqrstuvwxyz" + + "abcdefghijklmnopqrstuvwxyz" + "abcdefghijklmnopqrstuvwxyz" + "abcdefghijklmnopqrstuvwxyz" + "abcdefghijklmnopqrstuvwxyz" + + "abcdefghijklmnopqrstuvwxyz" + "abcdefghijklmnopqrstuvwxyz" + "abcdefghijklmnopqrstuvwxyz" + "abcdefghijklmnopqrstuvwxyz"; + + /* 012345678901234567890123456789 */ + + int fd = open("/helios/lib/nucleus", O_RDONLY); + + for (sz = 1 ;sz <= 20; sz++) { + fprintf(stderr, "Read sz %d\n", sz); + read(fd, &fred[0], sz); +#if 1 + read(fd, &fred[1], sz); + read(fd, &fred[2], sz); + read(fd, &fred[3], sz); +#endif + } +} + +#else /* syslib version */ + +#include +#include +#include +#include +#include + +int main(int argc, char **argv) +{ + int sz; + char *fred = "abcdefghijklmnopqrstuvwxyz" + "abcdefghijklmnopqrstuvwxyz" + "abcdefghijklmnopqrstuvwxyz" + "abcdefghijklmnopqrstuvwxyz" + + "abcdefghijklmnopqrstuvwxyz" + "abcdefghijklmnopqrstuvwxyz" + "abcdefghijklmnopqrstuvwxyz" + "abcdefghijklmnopqrstuvwxyz" + + "abcdefghijklmnopqrstuvwxyz" + "abcdefghijklmnopqrstuvwxyz" + "abcdefghijklmnopqrstuvwxyz" + "abcdefghijklmnopqrstuvwxyz"; + + /* 012345678901234567890123456789 */ + + Object *ob = Locate(NULL, "/helios/lib/nucleus"); + Stream *fd = Open(ob, NULL, O_ReadOnly); + + for (sz = 1 ;sz <= 20; sz++) { + fprintf(stderr, "Read sz %d\n", sz); + Read(fd, &fred[0], sz, -1); +#if 1 + Read(fd, &fred[1], sz, -1); + Read(fd, &fred[2], sz, -1); + Read(fd, &fred[3], sz, -1); +#endif + } +} +#endif + + +/* end of align test */ diff --git a/pool/shard010/C/0138101_uart.c b/pool/shard010/C/0138101_uart.c new file mode 100644 index 0000000000000000000000000000000000000000..ee27f51e54c3587827f3f32116b4fc2c750497d0 --- /dev/null +++ b/pool/shard010/C/0138101_uart.c @@ -0,0 +1,219 @@ +/* + * Include processor definitions. + */ +#include "pic32mz.h" + +#define MHZ 200 /* CPU clock. */ + +/* + * Chip configuration. + */ +PIC32_DEVCFG ( + DEVCFG0_JTAG_DISABLE | /* Disable JTAG port */ + DEVCFG0_TRC_DISABLE, /* Disable trace port */ +#if 0 + /* Case #1: using internal fast RC oscillator. + * The frequency is around 8 MHz. + * PLL multiplies it to 200 MHz. */ + DEVCFG1_FNOSC_SPLL | /* System clock supplied by SPLL */ + DEVCFG1_POSCMOD_DISABLE | /* Primary oscillator disabled */ + DEVCFG1_CLKO_DISABLE, /* CLKO output disable */ + + DEVCFG2_FPLLIDIV_1 | /* PLL input divider = 1 */ + DEVCFG2_FPLLRNG_5_10 | /* PLL input range is 5-10 MHz */ + DEVCFG2_FPLLICLK_FRC | /* Select FRC as input to PLL */ + DEVCFG2_FPLLMULT(50) | /* PLL multiplier = 50x */ + DEVCFG2_FPLLODIV_2, /* PLL postscaler = 1/2 */ +#endif +#if 1 + /* Case #2: using primary oscillator with external crystal 24 MHz. + * PLL multiplies it to 200 MHz. */ + DEVCFG1_FNOSC_SPLL | /* System clock supplied by SPLL */ + DEVCFG1_POSCMOD_EXT | /* External generator */ + DEVCFG1_FCKS_ENABLE | /* Enable clock switching */ + DEVCFG1_FCKM_ENABLE | /* Enable fail-safe clock monitoring */ + DEVCFG1_IESO | /* Internal-external switch over enable */ + DEVCFG1_CLKO_DISABLE, /* CLKO output disable */ + + DEVCFG2_FPLLIDIV_3 | /* PLL input divider = 3 */ + DEVCFG2_FPLLRNG_5_10 | /* PLL input range is 5-10 MHz */ + DEVCFG2_FPLLMULT(50) | /* PLL multiplier = 50x */ + DEVCFG2_FPLLODIV_2, /* PLL postscaler = 1/2 */ +#endif + DEVCFG3_FETHIO | /* Default Ethernet pins */ + DEVCFG3_USERID(0xffff)); /* User-defined ID */ + +/* + * Boot code at bfc00000. + * Setup stack pointer and $gp registers, and jump to main(). + */ +asm (" .section .exception"); +asm (" .globl _start"); +asm (" .type _start, function"); +asm ("_start: la $sp, _estack"); +asm (" la $ra, main"); +asm (" la $gp, _gp"); +asm (" jr $ra"); +asm (" .text"); +asm ("_estack = _end + 0x1000"); + +volatile unsigned loop; + +/* + * Delay for a given number of microseconds. + * The processor has a 32-bit hardware Count register, + * which increments at half CPU rate. + * We use it to get a precise delay. + */ +void udelay (unsigned usec) +{ + unsigned now = mfc0 (C0_COUNT, 0); + unsigned final = now + usec * MHZ / 2; + + for (;;) { + now = mfc0 (C0_COUNT, 0); + + /* This comparison is valid only when using a signed type. */ + if ((int) (now - final) >= 0) + break; + } +} + +/* + * Send a byte to the UART transmitter, with interrupts disabled. + */ +void putch (unsigned char c) +{ + /* Wait for transmitter shift register empty. */ + while (! (U1STA & PIC32_USTA_TRMT)) + continue; + +again: + /* Send byte. */ + U1TXREG = c; + + /* Wait for transmitter shift register empty. */ + while (! (U1STA & PIC32_USTA_TRMT)) + continue; + + if (c == '\n') { + c = '\r'; + goto again; + } +} + +/* + * Wait for the byte to be received and return it. + */ +unsigned getch (void) +{ + unsigned c; + + for (;;) { + /* Wait until receive data available. */ + if (U1STA & PIC32_USTA_URXDA) { + c = (unsigned char) U1RXREG; + break; + } + } + return c; +} + +int hexchar (unsigned val) +{ + return "0123456789abcdef" [val & 0xf]; +} + +void printreg (const char *p, unsigned val) +{ + for (; *p; ++p) + putch (*p); + + putch ('='); + putch (' '); + putch (hexchar (val >> 28)); + putch (hexchar (val >> 24)); + putch (hexchar (val >> 20)); + putch (hexchar (val >> 16)); + putch (hexchar (val >> 12)); + putch (hexchar (val >> 8)); + putch (hexchar (val >> 4)); + putch (hexchar (val)); + putch ('\n'); +} + +int main() +{ + /* Initialize coprocessor 0. */ + mtc0 (C0_COUNT, 0, 0); + mtc0 (C0_COMPARE, 0, -1); + //mtc0 (C0_EBASE, 1, 0x9fc00000); /* Vector base */ + //mtc0 (C0_INTCTL, 1, 1 << 5); /* Vector spacing 32 bytes */ + //mtc0 (C0_CAUSE, 0, 1 << 23); /* Set IV */ + //mtc0 (C0_STATUS, 0, 0); /* Clear BEV */ + + /* Use pins PA0-PA3, PF13, PF12, PA6-PA7 as output: LED control. */ + LATACLR = 0xCF; + TRISACLR = 0xCF; + LATFCLR = 0x3000; + TRISFCLR = 0x3000; + + /* Initialize UART. */ + U1RXR = 2; /* assign UART1 receive to pin RPF4 */ + RPF5R = 1; /* assign pin RPF5 to UART1 transmit */ + + U1BRG = PIC32_BRG_BAUD (MHZ * 500000, 115200); + U1STA = 0; + U1MODE = PIC32_UMODE_PDSEL_8NPAR | /* 8-bit data, no parity */ + PIC32_UMODE_ON; /* UART Enable */ + U1STASET = PIC32_USTA_URXEN | /* Receiver Enable */ + PIC32_USTA_UTXEN; /* Transmit Enable */ + + /* + * Print initial state of control registers. + */ + putch ('-'); + putch ('\n'); + printreg ("Status ", mfc0(12, 0)); + printreg ("IntCtl ", mfc0(12, 1)); + printreg ("SRSCtl ", mfc0(12, 2)); + printreg ("Cause ", mfc0(13, 0)); + printreg ("PRId ", mfc0(15, 0)); + printreg ("EBase ", mfc0(15, 1)); + printreg ("CDMMBase", mfc0(15, 2)); + printreg ("Config ", mfc0(16, 0)); + printreg ("Config1 ", mfc0(16, 1)); + printreg ("Config2 ", mfc0(16, 2)); + printreg ("Config3 ", mfc0(16, 3)); + printreg ("Config4 ", mfc0(16, 4)); + printreg ("Config5 ", mfc0(16, 5)); + printreg ("Config7 ", mfc0(16, 7)); + printreg ("WatchHi ", mfc0(19, 0)); + printreg ("WatchHi1", mfc0(19, 1)); + printreg ("WatchHi2", mfc0(19, 2)); + printreg ("WatchHi3", mfc0(19, 3)); + printreg ("Debug ", mfc0(23, 0)); + printreg ("PerfCtl0", mfc0(25, 0)); + printreg ("PerfCtl1", mfc0(25, 2)); + printreg ("DEVID ", DEVID); + printreg ("OSCCON ", OSCCON); + printreg ("DEVCFG0 ", DEVCFG0); + printreg ("DEVCFG1 ", DEVCFG1); + printreg ("DEVCFG2 ", DEVCFG2); + printreg ("DEVCFG3 ", DEVCFG3); + + while (1) { + /* Invert pins PA7-PA0. */ + LATAINV = 1 << 0; udelay (100000); + LATAINV = 1 << 1; udelay (100000); + LATAINV = 1 << 2; udelay (100000); + LATAINV = 1 << 3; udelay (100000); + LATFINV = 1 << 13; udelay (100000); + LATFINV = 1 << 12; udelay (100000); + LATAINV = 1 << 6; udelay (100000); + LATAINV = 1 << 7; udelay (100000); + + loop++; + putch ('.'); + } +} diff --git a/pool/shard010/C/0138102_capitalize.c b/pool/shard010/C/0138102_capitalize.c new file mode 100644 index 0000000000000000000000000000000000000000..e86eb10079140677258ecf831496d2a0295c9b04 --- /dev/null +++ b/pool/shard010/C/0138102_capitalize.c @@ -0,0 +1,22 @@ +#include +#include + +int main(void) +{ + string s = GetString(); + + for (int i = 0, n = strlen(s); i < n; i++) + { + if (s[i] >= "a" && s[i] <= "z") + { + printf("%c", s[i] - ("a" - "A")); + } + else + { + printf("%c",s[i]); + } + } + printf("\n"); + return 0; +} + diff --git a/pool/shard010/C/0138103_pthread_join.c b/pool/shard010/C/0138103_pthread_join.c new file mode 100644 index 0000000000000000000000000000000000000000..76d0236630bce087b941030f0c1fcc9201140ebc --- /dev/null +++ b/pool/shard010/C/0138103_pthread_join.c @@ -0,0 +1,50 @@ +#include +#include +#include + +pthread_t threads[5]; +int done[5]; + +void *thread_main(void *); + +int main(void) +{ + int i; + int rc; + // int status; pthread_join() need to get void pointer's addr + void *status; + + for (i = 0; i < 5; i++) + { + done[i] = 0; + pthread_create(&threads[i], NULL, &thread_main, (void *)&i); + printf("thread[%d] create, %ld\n", i, threads[i]); + } + + for (i = 4; i >= 0; i--) + { + done[i] = 1; + rc = pthread_join(threads[i], status); + printf("%p\n", status); + if (rc == 0) + { + printf("Completed join with thread %d status= %p\n",i, status); + } + else + { + printf("ERROR; return code from pthread_join() is %d, thread %d\n", rc, i); + return -1; + } + } + + return 0; +} + +void *thread_main(void *arg) +{ + int i; + double result=0.0; + + printf("thread: %d\n", *((int *)arg)); +} + diff --git a/pool/shard010/C/0138104_mca_dsm.c b/pool/shard010/C/0138104_mca_dsm.c new file mode 100644 index 0000000000000000000000000000000000000000..8b57a695f0966b24278fa91a757c73c2b7a48d40 --- /dev/null +++ b/pool/shard010/C/0138104_mca_dsm.c @@ -0,0 +1,346 @@ +/****************************************************************************** + * + * Copyright (C) 2009-2012 Broadcom Corporation + * + * 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. + * + ******************************************************************************/ + +/****************************************************************************** + * + * This is the implementation file for the MCAP Data chahnel state machine. + * + ******************************************************************************/ +#include + +#include "bt_target.h" +#include "mca_api.h" +#include "mca_defs.h" +#include "mca_int.h" + +/***************************************************************************** +** data channel state machine constants and types +*****************************************************************************/ +enum +{ + MCA_DCB_TC_OPEN, + MCA_DCB_CONG, + MCA_DCB_FREE_DATA, + MCA_DCB_DEALLOC, + MCA_DCB_DO_DISCONN, + MCA_DCB_SND_DATA, + MCA_DCB_HDL_DATA, + MCA_DCB_NUM_ACTIONS +}; +#define MCA_DCB_IGNORE MCA_DCB_NUM_ACTIONS + +/* action function list */ +const tMCA_DCB_ACTION mca_dcb_action[] = { + mca_dcb_tc_open, + mca_dcb_cong, + mca_dcb_free_data, + mca_dcb_dealloc, + mca_dcb_do_disconn, + mca_dcb_snd_data, + mca_dcb_hdl_data +}; + +/* state table information */ +#define MCA_DCB_ACTIONS 1 /* number of actions */ +#define MCA_DCB_ACT_COL 0 /* position of action function */ +#define MCA_DCB_NEXT_STATE 1 /* position of next state */ +#define MCA_DCB_NUM_COLS 2 /* number of columns in state tables */ + +/* state table for opening state */ +const UINT8 mca_dcb_st_opening[][MCA_DCB_NUM_COLS] = { +/* Event Action Next State */ +/* MCA_DCB_API_CLOSE_EVT */ {MCA_DCB_DO_DISCONN, MCA_DCB_CLOSING_ST}, +/* MCA_DCB_API_WRITE_EVT */ {MCA_DCB_IGNORE, MCA_DCB_OPENING_ST}, +/* MCA_DCB_TC_OPEN_EVT */ {MCA_DCB_TC_OPEN, MCA_DCB_OPEN_ST}, +/* MCA_DCB_TC_CLOSE_EVT */ {MCA_DCB_DEALLOC, MCA_DCB_NULL_ST}, +/* MCA_DCB_TC_CONG_EVT */ {MCA_DCB_CONG, MCA_DCB_OPENING_ST}, +/* MCA_DCB_TC_DATA_EVT */ {MCA_DCB_FREE_DATA, MCA_DCB_OPENING_ST} +}; + +/* state table for open state */ +const UINT8 mca_dcb_st_open[][MCA_DCB_NUM_COLS] = { +/* Event Action Next State */ +/* MCA_DCB_API_CLOSE_EVT */ {MCA_DCB_DO_DISCONN, MCA_DCB_CLOSING_ST}, +/* MCA_DCB_API_WRITE_EVT */ {MCA_DCB_SND_DATA, MCA_DCB_OPEN_ST}, +/* MCA_DCB_TC_OPEN_EVT */ {MCA_DCB_IGNORE, MCA_DCB_OPEN_ST}, +/* MCA_DCB_TC_CLOSE_EVT */ {MCA_DCB_DEALLOC, MCA_DCB_NULL_ST}, +/* MCA_DCB_TC_CONG_EVT */ {MCA_DCB_CONG, MCA_DCB_OPEN_ST}, +/* MCA_DCB_TC_DATA_EVT */ {MCA_DCB_HDL_DATA, MCA_DCB_OPEN_ST} +}; + +/* state table for closing state */ +const UINT8 mca_dcb_st_closing[][MCA_DCB_NUM_COLS] = { +/* Event Action Next State */ +/* MCA_DCB_API_CLOSE_EVT */ {MCA_DCB_IGNORE, MCA_DCB_CLOSING_ST}, +/* MCA_DCB_API_WRITE_EVT */ {MCA_DCB_IGNORE, MCA_DCB_CLOSING_ST}, +/* MCA_DCB_TC_OPEN_EVT */ {MCA_DCB_TC_OPEN, MCA_DCB_OPEN_ST}, +/* MCA_DCB_TC_CLOSE_EVT */ {MCA_DCB_DEALLOC, MCA_DCB_NULL_ST}, +/* MCA_DCB_TC_CONG_EVT */ {MCA_DCB_IGNORE, MCA_DCB_CLOSING_ST}, +/* MCA_DCB_TC_DATA_EVT */ {MCA_DCB_FREE_DATA, MCA_DCB_CLOSING_ST} +}; + +/* type for state table */ +typedef const UINT8 (*tMCA_DCB_ST_TBL)[MCA_DCB_NUM_COLS]; + +/* state table */ +const tMCA_DCB_ST_TBL mca_dcb_st_tbl[] = { + mca_dcb_st_opening, + mca_dcb_st_open, + mca_dcb_st_closing +}; + +#if (BT_TRACE_VERBOSE == TRUE) +/* verbose event strings for trace */ +const char * const mca_dcb_evt_str[] = { + "API_CLOSE_EVT", + "API_WRITE_EVT", + "TC_OPEN_EVT", + "TC_CLOSE_EVT", + "TC_CONG_EVT", + "TC_DATA_EVT" +}; +/* verbose state strings for trace */ +const char * const mca_dcb_st_str[] = { + "NULL_ST", + "OPENING_ST", + "OPEN_ST", + "CLOSING_ST" +}; +#endif + +/******************************************************************************* +** +** Function mca_dcb_event +** +** Description This function is the DCB state machine main function. +** It uses the state and action function tables to execute +** action functions. +** +** Returns void. +** +*******************************************************************************/ +void mca_dcb_event(tMCA_DCB *p_dcb, UINT8 event, tMCA_DCB_EVT *p_data) +{ + tMCA_DCB_ST_TBL state_table; + UINT8 action; + + if (p_dcb == NULL) + return; +#if (BT_TRACE_VERBOSE == TRUE) + MCA_TRACE_EVENT("DCB dcb=%d event=%s state=%s", mca_dcb_to_hdl(p_dcb), mca_dcb_evt_str[event], mca_dcb_st_str[p_dcb->state]); +#else + MCA_TRACE_EVENT("DCB dcb=%d event=%d state=%d", mca_dcb_to_hdl(p_dcb), event, p_dcb->state); +#endif + + /* look up the state table for the current state */ + state_table = mca_dcb_st_tbl[p_dcb->state - 1]; + + /* set next state */ + p_dcb->state = state_table[event][MCA_DCB_NEXT_STATE]; + + /* execute action functions */ + if ((action = state_table[event][MCA_DCB_ACT_COL]) != MCA_DCB_IGNORE) + { + (*mca_dcb_action[action])(p_dcb, p_data); + } +} + +/******************************************************************************* +** +** Function mca_dcb_alloc +** +** Description This function is called to allocate an DCB. +** It initializes the DCB with the data passed to the function. +** +** Returns tMCA_DCB * +** +*******************************************************************************/ +tMCA_DCB *mca_dcb_alloc(tMCA_CCB*p_ccb, tMCA_DEP dep) +{ + tMCA_DCB *p_dcb = NULL, *p_dcb_tmp; + tMCA_RCB *p_rcb = p_ccb->p_rcb; + tMCA_CS *p_cs; + int i, max; + + if (dep < MCA_NUM_DEPS) + { + p_cs = &p_rcb->dep[dep]; + i = mca_ccb_to_hdl(p_ccb)-1; + p_dcb_tmp = &mca_cb.dcb[i*MCA_NUM_MDLS]; + /* make sure p_cs->max_mdl is smaller than MCA_NUM_MDLS at MCA_CreateDep */ + max = p_cs->max_mdl; + for (i=0; istate == MCA_DCB_NULL_ST) + { + p_dcb_tmp->p_ccb = p_ccb; + p_dcb_tmp->state = MCA_DCB_OPENING_ST; + p_dcb_tmp->cong = TRUE; + p_dcb_tmp->p_cs = p_cs; + p_dcb = p_dcb_tmp; + break; + } + } + } + return p_dcb; +} + +/******************************************************************************* +** +** Function mca_dep_free_mdl +** +** Description This function is called to check the number of free mdl for +** the given dep. +** +** Returns the number of free mdl for the given dep +** +*******************************************************************************/ +UINT8 mca_dep_free_mdl(tMCA_CCB *p_ccb, tMCA_DEP dep) +{ + tMCA_DCB *p_dcb; + tMCA_RCB *p_rcb = p_ccb->p_rcb; + tMCA_CS *p_cs; + int i, max; + UINT8 count = 0; + UINT8 left; + + if (dep < MCA_NUM_DEPS) + { + p_cs = &p_rcb->dep[dep]; + i = mca_ccb_to_hdl(p_ccb)-1; + p_dcb = &mca_cb.dcb[i * MCA_NUM_MDLS]; + /* make sure p_cs->max_mdl is smaller than MCA_NUM_MDLS at MCA_CreateDep */ + max = p_cs->max_mdl; + for (i=0; istate != MCA_DCB_NULL_ST) && (p_dcb->p_cs == p_cs)) + { + count++; + break; + } + } + } + else + { + max = 0; + MCA_TRACE_WARNING("Invalid Dep ID"); + } + left = max - count; + return left; +} + +/******************************************************************************* +** +** Function mca_dcb_dealloc +** +** Description This function deallocates an DCB. +** +** Returns void. +** +*******************************************************************************/ +void mca_dcb_dealloc(tMCA_DCB *p_dcb, tMCA_DCB_EVT *p_data) +{ + tMCA_CCB *p_ccb = p_dcb->p_ccb; + UINT8 event = MCA_CLOSE_IND_EVT; + tMCA_CTRL evt_data; + + MCA_TRACE_DEBUG("mca_dcb_dealloc"); + mca_free_buf ((void **)&p_dcb->p_data); + if (p_data) + { + /* non-NULL -> an action function -> report disconnect event */ + evt_data.close_cfm.mdl = mca_dcb_to_hdl(p_dcb); + evt_data.close_cfm.reason = p_data->close.reason; + evt_data.close_cfm.mdl_id = p_dcb->mdl_id; + if (p_data->close.param == MCA_INT) + event = MCA_CLOSE_CFM_EVT; + if (p_data->close.lcid) + mca_ccb_report_event(p_ccb, event, &evt_data); + } + mca_free_tc_tbl_by_lcid (p_dcb->lcid); + memset (p_dcb, 0, sizeof (tMCA_DCB)); +} + +/******************************************************************************* +** +** Function mca_dcb_to_hdl +** +** Description This function converts a pointer to an DCB to a handle (tMCA_DL). +** It returns the handle. +** +** Returns tMCA_DL. +** +*******************************************************************************/ +tMCA_DL mca_dcb_to_hdl(tMCA_DCB *p_dcb) +{ + return (UINT8) (p_dcb - mca_cb.dcb + 1); +} + +/******************************************************************************* +** +** Function mca_dcb_by_hdl +** +** Description This function finds the DCB for a handle (tMCA_DL). +** It returns a pointer to the DCB. +** If no DCB matches the handle it returns NULL. +** +** Returns tMCA_DCB * +** +*******************************************************************************/ +tMCA_DCB *mca_dcb_by_hdl(tMCA_DL hdl) +{ + tMCA_DCB * p_dcb = NULL; + if (hdl && hdl <= MCA_NUM_DCBS && mca_cb.dcb[hdl-1].state) + p_dcb = &mca_cb.dcb[hdl-1]; + return p_dcb; +} + +/******************************************************************************* +** +** Function mca_dcb_close_by_mdl_id +** +** Description This function finds the DCB for a mdl_id and +** disconnect the mdl +** +** Returns void +** +*******************************************************************************/ +void mca_dcb_close_by_mdl_id(tMCA_CCB*p_ccb, UINT16 mdl_id) +{ + tMCA_DCB *p_dcb; + int i; + + MCA_TRACE_DEBUG("mca_dcb_close_by_mdl_id mdl_id=%d", mdl_id); + i = mca_ccb_to_hdl(p_ccb)-1; + p_dcb = &mca_cb.dcb[i*MCA_NUM_MDLS]; + for (i=0; istate) + { + if (p_dcb->mdl_id == mdl_id) + { + mca_dcb_event(p_dcb, MCA_DCB_API_CLOSE_EVT, NULL); + break; + } + else if (mdl_id == MCA_ALL_MDL_ID) + { + mca_dcb_event(p_dcb, MCA_DCB_API_CLOSE_EVT, NULL); + } + } + } +} diff --git a/pool/shard010/C/0138105_thread_tcache_enabled.c b/pool/shard010/C/0138105_thread_tcache_enabled.c new file mode 100644 index 0000000000000000000000000000000000000000..0c343a6c567552a7c191c7f9b56a637327b46a9a --- /dev/null +++ b/pool/shard010/C/0138105_thread_tcache_enabled.c @@ -0,0 +1,89 @@ +#include "test/jemalloc_test.h" + +void * +thd_start(void *arg) { + bool e0, e1; + size_t sz = sizeof(bool); + assert_d_eq(mallctl("thread.tcache.enabled", (void *)&e0, &sz, NULL, + 0), 0, "Unexpected mallctl failure"); + + if (e0) { + e1 = false; + assert_d_eq(mallctl("thread.tcache.enabled", (void *)&e0, &sz, + (void *)&e1, sz), 0, "Unexpected mallctl() error"); + assert_true(e0, "tcache should be enabled"); + } + + e1 = true; + assert_d_eq(mallctl("thread.tcache.enabled", (void *)&e0, &sz, + (void *)&e1, sz), 0, "Unexpected mallctl() error"); + assert_false(e0, "tcache should be disabled"); + + e1 = true; + assert_d_eq(mallctl("thread.tcache.enabled", (void *)&e0, &sz, + (void *)&e1, sz), 0, "Unexpected mallctl() error"); + assert_true(e0, "tcache should be enabled"); + + e1 = false; + assert_d_eq(mallctl("thread.tcache.enabled", (void *)&e0, &sz, + (void *)&e1, sz), 0, "Unexpected mallctl() error"); + assert_true(e0, "tcache should be enabled"); + + e1 = false; + assert_d_eq(mallctl("thread.tcache.enabled", (void *)&e0, &sz, + (void *)&e1, sz), 0, "Unexpected mallctl() error"); + assert_false(e0, "tcache should be disabled"); + + free(malloc(1)); + e1 = true; + assert_d_eq(mallctl("thread.tcache.enabled", (void *)&e0, &sz, + (void *)&e1, sz), 0, "Unexpected mallctl() error"); + assert_false(e0, "tcache should be disabled"); + + free(malloc(1)); + e1 = true; + assert_d_eq(mallctl("thread.tcache.enabled", (void *)&e0, &sz, + (void *)&e1, sz), 0, "Unexpected mallctl() error"); + assert_true(e0, "tcache should be enabled"); + + free(malloc(1)); + e1 = false; + assert_d_eq(mallctl("thread.tcache.enabled", (void *)&e0, &sz, + (void *)&e1, sz), 0, "Unexpected mallctl() error"); + assert_true(e0, "tcache should be enabled"); + + free(malloc(1)); + e1 = false; + assert_d_eq(mallctl("thread.tcache.enabled", (void *)&e0, &sz, + (void *)&e1, sz), 0, "Unexpected mallctl() error"); + assert_false(e0, "tcache should be disabled"); + + free(malloc(1)); + return NULL; + test_skip("\"thread.tcache.enabled\" mallctl not available"); + return NULL; +} + +TEST_BEGIN(test_main_thread) { + thd_start(NULL); +} +TEST_END + +TEST_BEGIN(test_subthread) { + thd_t thd; + + thd_create(&thd, thd_start, NULL); + thd_join(thd, NULL); +} +TEST_END + +int +main(void) { + /* Run tests multiple times to check for bad interactions. */ + return test( + test_main_thread, + test_subthread, + test_main_thread, + test_subthread, + test_main_thread); +} diff --git a/pool/shard010/C/0138106_watchman.c b/pool/shard010/C/0138106_watchman.c new file mode 100644 index 0000000000000000000000000000000000000000..9acd15952bafc8450fca6096fe6a1478976d0dac --- /dev/null +++ b/pool/shard010/C/0138106_watchman.c @@ -0,0 +1,82 @@ +#include "bbs.h" + +#define DEFAULT_ADD 600 +#define CONT MY_BBS_HOME "/help/watchmanhelp" + +struct bbsinfo bbsinfo; + +void +usage(char *name) +{ + printf("%s userid userpasswd [minutes_to_delay]\n", name); +} + +int +main(int argc, char *argv[]) +{ + struct UTMPFILE *shm_utmp; + int time_add = 0; + int i; + FILE *fp, *fr; + time_t now_t; + char buf[256]; + if (argc < 3) { + usage(argv[0]); + return 0; + } + //errlog("argc:%d",argc); + if (argc > 3){ + time_add = atoi(argv[3]) * 60; + // errlog("argv[3]: %s",argv[3]); + } + if (!time_add) + time_add = DEFAULT_ADD; + for (i = 0; i < 10; i++) { + initbbsinfo(&bbsinfo); + shm_utmp = bbsinfo.utmpshm; + if (shm_utmp) + break; + sleep(10); + } + if (!shm_utmp) { + errlog("can't attach ushm!"); + return -1; + } + now_t = time(NULL); + if (shm_utmp->watchman) { + strcpy(buf, + "¡ï¡ï¡ï¡ï¡ï¾¯±¨¡ï¡ï¡ï¡ï¡ïÕþÖÎÐÔ°æÃæËø×¡ÁË¡ï¡ï¡ï¡ï¡ï"); + } else { + shm_utmp->watchman = now_t + time_add; + getrandomint(&(shm_utmp->unlock)); + snprintf(buf, sizeof (buf), "À´À´À´,µãîÁË!ÏÖÔÚÊÇ %s", + Ctime(now_t)); + } + + fp = popen("/usr/bin/mail bbs", "w"); + if (!fp) { + errlog("can't open mail!"); + return -2; + } + fr = fopen(CONT, "r"); + fprintf(fp, "#name: %s\n", argv[1]); + fprintf(fp, "#pass: %s\n", argv[2]); + fprintf(fp, "#board: deleterequest\n"); + fprintf(fp, "#title: %s\n", buf); + fprintf(fp, "#localpost:\n\n"); + if (!strncmp(buf, "À´", 2)) { + fprintf(fp, + "ÇëÔÚ%d·ÖÖÓÄÚ½øÐнâËø²Ù×÷,·ñÔò±¾BBSËùÓкÍÕþÖÎÏà¹ØµÄ°æÃ潫±»·â°æ\n" + "Ö±ÖÁÓÐÈ˽øÐÐÁ˽âËø²Ù×÷.\n" "½âËøÃÜÂë: %u\n", + time_add / 60, shm_utmp->unlock % 10000); + } + fprintf(fp, "ÒÔÏÂÊǹØÓÚ½âËø²Ù×÷µÄ˵Ã÷:\n"); + fr = fopen(CONT, "r"); + if (fr) { + while (fgets(buf, sizeof (buf), fr)) + fputs(buf, fp); + fclose(fr); + } + pclose(fp); + return 0; +} diff --git a/pool/shard010/C/0138107_p_verify.c b/pool/shard010/C/0138107_p_verify.c new file mode 100644 index 0000000000000000000000000000000000000000..8db46412f3771720b9afde5faa46a4dcfc133dc9 --- /dev/null +++ b/pool/shard010/C/0138107_p_verify.c @@ -0,0 +1,119 @@ +/* crypto/evp/p_verify.c */ +/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com) + * All rights reserved. + * + * This package is an SSL implementation written + * by Eric Young (eay@cryptsoft.com). + * The implementation was written so as to conform with Netscapes SSL. + * + * This library is free for commercial and non-commercial use as long as + * the following conditions are aheared to. The following conditions + * apply to all code found in this distribution, be it the RC4, RSA, + * lhash, DES, etc., code; not just the SSL code. The SSL documentation + * included with this distribution is covered by the same copyright terms + * except that the holder is Tim Hudson (tjh@cryptsoft.com). + * + * Copyright remains Eric Young's, and as such any Copyright notices in + * the code are not to be removed. + * If this package is used in a product, Eric Young should be given attribution + * as the author of the parts of the library used. + * This can be in the form of a textual message at program startup or + * in documentation (online or textual) provided with the package. + * + * 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 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. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * "This product includes cryptographic software written by + * Eric Young (eay@cryptsoft.com)" + * The word 'cryptographic' can be left out if the rouines from the library + * being used are not cryptographic related :-). + * 4. If you include any Windows specific code (or a derivative thereof) from + * the apps directory (application code) you must include an acknowledgement: + * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)" + * + * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``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. + * + * The licence and distribution terms for any publically available version or + * derivative of this code cannot be changed. i.e. this code cannot simply be + * copied and put under another distribution licence + * [including the GNU Public Licence.] + */ + +#include +#include "cryptlib.h" +#include +#include +#include + +int EVP_VerifyFinal(EVP_MD_CTX *ctx, const unsigned char *sigbuf, + unsigned int siglen, EVP_PKEY *pkey) + { + unsigned char m[EVP_MAX_MD_SIZE]; + unsigned int m_len; + int i,ok=0,v; + MS_STATIC EVP_MD_CTX tmp_ctx; + + EVP_MD_CTX_init(&tmp_ctx); + EVP_MD_CTX_copy_ex(&tmp_ctx,ctx); + EVP_DigestFinal_ex(&tmp_ctx,&(m[0]),&m_len); + EVP_MD_CTX_cleanup(&tmp_ctx); + + if (ctx->digest->flags & EVP_MD_FLAG_PKEY_METHOD_SIGNATURE) + { + EVP_PKEY_CTX *pkctx = NULL; + i = -1; + pkctx = EVP_PKEY_CTX_new(pkey, NULL); + if (!pkctx) + goto err; + if (EVP_PKEY_verify_init(pkctx) <= 0) + goto err; + if (EVP_PKEY_CTX_set_signature_md(pkctx, ctx->digest) <= 0) + goto err; + i = EVP_PKEY_verify(pkctx, sigbuf, siglen, m, m_len); + err: + EVP_PKEY_CTX_free(pkctx); + return i; + } + + for (i=0; i<4; i++) + { + v=ctx->digest->required_pkey_type[i]; + if (v == 0) break; + if (pkey->type == v) + { + ok=1; + break; + } + } + if (!ok) + { + EVPerr(EVP_F_EVP_VERIFYFINAL,EVP_R_WRONG_PUBLIC_KEY_TYPE); + return(-1); + } + if (ctx->digest->verify == NULL) + { + EVPerr(EVP_F_EVP_VERIFYFINAL,EVP_R_NO_VERIFY_FUNCTION_CONFIGURED); + return(0); + } + + return(ctx->digest->verify(ctx->digest->type,m,m_len, + sigbuf,siglen,pkey->pkey.ptr)); + } + diff --git a/pool/shard010/C/0138108_i915_random.c b/pool/shard010/C/0138108_i915_random.c new file mode 100644 index 0000000000000000000000000000000000000000..abdfadcf626bdfd1ef612504166751f19053c76e --- /dev/null +++ b/pool/shard010/C/0138108_i915_random.c @@ -0,0 +1,109 @@ +/* + * Copyright © 2016 Intel Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice (including the next + * paragraph) shall be included in all copies or substantial portions of the + * Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + * + */ + +#include +#include +#include +#include +#include + +#include "i915_random.h" +#include "i915_utils.h" + +u64 i915_prandom_u64_state(struct rnd_state *rnd) +{ + u64 x; + + x = prandom_u32_state(rnd); + x <<= 32; + x |= prandom_u32_state(rnd); + + return x; +} + +void i915_prandom_shuffle(void *arr, size_t elsz, size_t count, + struct rnd_state *state) +{ + char stack[128]; + + if (WARN_ON(elsz > sizeof(stack) || count > U32_MAX)) + return; + + if (!elsz || !count) + return; + + /* Fisher-Yates shuffle courtesy of Knuth */ + while (--count) { + size_t swp; + + swp = i915_prandom_u32_max_state(count + 1, state); + if (swp == count) + continue; + + memcpy(stack, arr + count * elsz, elsz); + memcpy(arr + count * elsz, arr + swp * elsz, elsz); + memcpy(arr + swp * elsz, stack, elsz); + } +} + +void i915_random_reorder(unsigned int *order, unsigned int count, + struct rnd_state *state) +{ + i915_prandom_shuffle(order, sizeof(*order), count, state); +} + +unsigned int *i915_random_order(unsigned int count, struct rnd_state *state) +{ + unsigned int *order, i; + + order = kmalloc_array(count, sizeof(*order), + GFP_KERNEL | __GFP_RETRY_MAYFAIL | __GFP_NOWARN); + if (!order) + return order; + + for (i = 0; i < count; i++) + order[i] = i; + + i915_random_reorder(order, count, state); + return order; +} + +u64 igt_random_offset(struct rnd_state *state, + u64 start, u64 end, + u64 len, u64 align) +{ + u64 range, addr; + + BUG_ON(range_overflows(start, len, end)); + BUG_ON(round_up(start, align) > round_down(end - len, align)); + + range = round_down(end - len, align) - round_up(start, align); + if (range) { + addr = i915_prandom_u64_state(state); + div64_u64_rem(addr, range, &addr); + start += addr; + } + + return round_up(start, align); +} diff --git a/pool/shard010/C/0138109_networkd-netdev-vlan.c b/pool/shard010/C/0138109_networkd-netdev-vlan.c new file mode 100644 index 0000000000000000000000000000000000000000..13c44567331565cdf72841697109ed8c9785c976 --- /dev/null +++ b/pool/shard010/C/0138109_networkd-netdev-vlan.c @@ -0,0 +1,81 @@ +/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/ + +/*** + This file is part of systemd. + + Copyright 2013 Tom Gundersen + + systemd is free software; you can redistribute it and/or modify it + under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation; either version 2.1 of the License, or + (at your option) any later version. + + systemd is distributed in the hope that it will be useful, but + WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public License + along with systemd; If not, see . +***/ + +#include + +#include "networkd-netdev-vlan.h" +#include "network-internal.h" +#include "list.h" + +static int netdev_vlan_fill_message_create(NetDev *netdev, Link *link, sd_rtnl_message *req) { + VLan *v = VLAN(netdev); + int r; + + assert(netdev); + assert(v); + assert(link); + assert(req); + + if (v->id <= VLANID_MAX) { + r = sd_rtnl_message_append_u16(req, IFLA_VLAN_ID, v->id); + if (r < 0) { + log_error_netdev(netdev, + "Could not append IFLA_VLAN_ID attribute: %s", + strerror(-r)); + return r; + } + } + + return 0; +} + +static int netdev_vlan_verify(NetDev *netdev, const char *filename) { + VLan *v = VLAN(netdev); + + assert(netdev); + assert(v); + assert(filename); + + if (v->id > VLANID_MAX) { + log_warning("VLAN without valid Id (%"PRIu64") configured in %s. Ignoring", v->id, filename); + return -EINVAL; + } + + return 0; +} + +static void vlan_init(NetDev *netdev) { + VLan *v = VLAN(netdev); + + assert(netdev); + assert(v); + + v->id = VLANID_MAX + 1; +} + +const NetDevVTable vlan_vtable = { + .object_size = sizeof(VLan), + .init = vlan_init, + .sections = "Match\0NetDev\0VLAN\0", + .fill_message_create = netdev_vlan_fill_message_create, + .create_type = NETDEV_CREATE_STACKED, + .config_verify = netdev_vlan_verify, +}; diff --git a/pool/shard010/C/0138110_main.c b/pool/shard010/C/0138110_main.c new file mode 100644 index 0000000000000000000000000000000000000000..133721c59b1b3f1747590d5ea2a67f0b43417f45 --- /dev/null +++ b/pool/shard010/C/0138110_main.c @@ -0,0 +1,298 @@ +/** + ****************************************************************************** + * @file ADC/ADC_TriggerMode/Src/main.c + * @author MCD Application Team + * @brief This example describes how to use Timer to trig ADC conversion. + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2016 STMicroelectronics

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ + +/* Includes ------------------------------------------------------------------*/ +#include "main.h" + +/** @addtogroup STM32F0xx_HAL_Examples + * @{ + */ + +/** @addtogroup ADC_TriggerMode + * @{ + */ + +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ +/* Private macro -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* ADC handler declaration */ +ADC_HandleTypeDef AdcHandle; + +/* TIM handler declaration */ +static TIM_HandleTypeDef htim; + +/* Variable used to get converted value */ +__IO uint16_t uhADCxConvertedValue = 0; + +/* Private function prototypes -----------------------------------------------*/ +static void SystemClock_Config(void); +static void Error_Handler(void); +static void ADC_Config(void); +static void TIM_Config(void); + +/* Private functions ---------------------------------------------------------*/ + +/** + * @brief Main program. + * @param None + * @retval None + */ +int main(void) +{ + /* STM32F0xx HAL library initialization: + - Configure the Flash prefetch + - Systick timer is configured by default as source of time base, but user + can eventually implement his proper time base source (a general purpose + timer for example or other time source), keeping in mind that Time base + duration should be kept 1ms since PPP_TIMEOUT_VALUEs are defined and + handled in milliseconds basis. + - Low Level Initialization + */ + HAL_Init(); + + /* Configure LED3 */ + BSP_LED_Init(LED3); + + /* Configure the system clock to 48 MHz */ + SystemClock_Config(); + + /*##-1- TIM Peripheral Configuration ######################################*/ + TIM_Config(); + + /*##-2- Configure the ADC peripheral ######################################*/ + ADC_Config(); + + /*##-4- Start the conversion process and enable interrupt ##################*/ + if (HAL_ADC_Start_IT(&AdcHandle) != HAL_OK) + { + /* Start Conversation Error */ + Error_Handler(); + } + + /*##-3- TIM counter enable ################################################*/ + if (HAL_TIM_Base_Start(&htim) != HAL_OK) + { + /* Counter Enable Error */ + Error_Handler(); + } + + /* Infinite loop */ + while (1) + { + } +} + +/** + * @brief System Clock Configuration + * The system Clock is configured as follow : + * System Clock source = PLL (HSE) + * SYSCLK(Hz) = 48000000 + * HCLK(Hz) = 48000000 + * AHB Prescaler = 1 + * APB1 Prescaler = 1 + * HSE Frequency(Hz) = 8000000 + * PREDIV = 1 + * PLLMUL = 6 + * Flash Latency(WS) = 1 + * @param None + * @retval None + */ +static void SystemClock_Config(void) +{ + RCC_ClkInitTypeDef RCC_ClkInitStruct; + RCC_OscInitTypeDef RCC_OscInitStruct; + + /* Enable HSE Oscillator and Activate PLL with HSE as source */ + RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSE; + RCC_OscInitStruct.HSEState = RCC_HSE_ON; + RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON; + RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE; + RCC_OscInitStruct.PLL.PREDIV = RCC_PREDIV_DIV1; + RCC_OscInitStruct.PLL.PLLMUL = RCC_PLL_MUL6; + if (HAL_RCC_OscConfig(&RCC_OscInitStruct)!= HAL_OK) + { + Error_Handler(); + } + + /* Select PLL as system clock source and configure the HCLK, PCLK1 clocks dividers */ + RCC_ClkInitStruct.ClockType = (RCC_CLOCKTYPE_SYSCLK | RCC_CLOCKTYPE_HCLK | RCC_CLOCKTYPE_PCLK1); + RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK; + RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1; + RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV1; + if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_1)!= HAL_OK) + { + Error_Handler(); + } +} + +/** + * @brief This function is executed in case of error occurrence. + * @param None + * @retval None + */ +static void Error_Handler(void) +{ + /* Turn LED3 on */ + BSP_LED_On(LED3); + while (1) + { + } +} + +/** + * @brief ADC configuration + * @param None + * @retval None + */ +static void ADC_Config(void) +{ + ADC_ChannelConfTypeDef sConfig; + + /* ADC Initialization */ + AdcHandle.Instance = ADCx; + + AdcHandle.Init.ClockPrescaler = ADC_CLOCK_SYNC_PCLK_DIV4; + AdcHandle.Init.Resolution = ADC_RESOLUTION_12B; + AdcHandle.Init.DataAlign = ADC_DATAALIGN_RIGHT; + AdcHandle.Init.ScanConvMode = DISABLE; /* Sequencer disabled (ADC conversion on only 1 channel: channel set on rank 1) */ + AdcHandle.Init.EOCSelection = ADC_EOC_SINGLE_CONV; + AdcHandle.Init.LowPowerAutoWait = DISABLE; + AdcHandle.Init.LowPowerAutoPowerOff = DISABLE; + AdcHandle.Init.ContinuousConvMode = DISABLE; /* Continuous mode disabled to have only 1 conversion at each conversion trig */ + AdcHandle.Init.DiscontinuousConvMode = DISABLE; /* Parameter discarded because sequencer is disabled */ + AdcHandle.Init.ExternalTrigConv = ADC_EXTERNALTRIGCONV_T2_TRGO; /* Conversion start trigged at each external event */ + AdcHandle.Init.ExternalTrigConvEdge = ADC_EXTERNALTRIGCONVEDGE_RISING; + AdcHandle.Init.DMAContinuousRequests = ENABLE; + AdcHandle.Init.Overrun = ADC_OVR_DATA_OVERWRITTEN; + + if (HAL_ADC_Init(&AdcHandle) != HAL_OK) + { + /* ADC initiliazation Error */ + Error_Handler(); + } + + /* Configure ADC regular channel */ + sConfig.Channel = ADCx_CHANNEL; + sConfig.Rank = ADC_RANK_CHANNEL_NUMBER; + sConfig.SamplingTime = ADC_SAMPLETIME_28CYCLES_5; + + if (HAL_ADC_ConfigChannel(&AdcHandle, &sConfig) != HAL_OK) + { + /* Channel Configuration Error */ + Error_Handler(); + } +} + +/** + * @brief TIM configuration + * @param None + * @retval None + */ +static void TIM_Config(void) +{ + TIM_MasterConfigTypeDef sMasterConfig; + + /* Time Base configuration */ + htim.Instance = TIMx; + + htim.Init.Period = 2400; + htim.Init.Prescaler = 0; + htim.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1; + htim.Init.CounterMode = TIM_COUNTERMODE_UP; + htim.Init.RepetitionCounter = 0x0; + htim.Init.AutoReloadPreload = TIM_AUTORELOAD_PRELOAD_DISABLE; + + if (HAL_TIM_Base_Init(&htim) != HAL_OK) + { + /* Timer Initiliazation Error */ + Error_Handler(); + } + + /* Timer TRGO selection */ + sMasterConfig.MasterOutputTrigger = TIM_TRGO_UPDATE; + sMasterConfig.MasterSlaveMode = TIM_MASTERSLAVEMODE_DISABLE; + + if (HAL_TIMEx_MasterConfigSynchronization(&htim, &sMasterConfig) != HAL_OK) + { + /* Timer TRGO selection Error */ + Error_Handler(); + } +} + +/** + * @brief Conversion complete callback in non blocking mode + * @param AdcHandle : AdcHandle handle + * @note This example shows a simple way to report end of conversion, and + * you can add your own implementation. + * @retval None + */ +void HAL_ADC_ConvCpltCallback(ADC_HandleTypeDef *AdcHandle) +{ + /* Get the converted value of regular channel */ + uhADCxConvertedValue = HAL_ADC_GetValue(AdcHandle); +} + +#ifdef USE_FULL_ASSERT + +/** + * @brief Reports the name of the source file and the source line number + * where the assert_param error has occurred. + * @param file: pointer to the source file name + * @param line: assert_param error line source number + * @retval None + */ +void assert_failed(uint8_t *file, uint32_t line) +{ + /* User can add his own implementation to report the file name and line number, + ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */ + + /* Infinite loop */ + while (1) + { + } +} + +#endif + +/** + * @} + */ + +/** + * @} + */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/pool/shard010/C/0138111_strlcpy.c b/pool/shard010/C/0138111_strlcpy.c new file mode 100644 index 0000000000000000000000000000000000000000..c919e8cd55b6d2f5a91b2fe690e6fddf221b113c --- /dev/null +++ b/pool/shard010/C/0138111_strlcpy.c @@ -0,0 +1,64 @@ +/* $Id: strlcpy.c,v 1.1 2002/04/11 16:39:59 provos Exp $ */ +/* $OpenBSD: strlcpy.c,v 1.2 1998/11/06 04:33:16 wvdputte Exp $ */ + +/* + * Copyright (c) 1998 Todd C. Miller + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, + * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY + * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL + * THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#if defined(LIBC_SCCS) && !defined(lint) +static char *rcsid = "$OpenBSD: strlcpy.c,v 1.2 1998/11/06 04:33:16 wvdputte Exp $"; +#endif /* LIBC_SCCS and not lint */ + +#include +#include + +/* + * Copy src to string dst of size siz. At most siz-1 characters + * will be copied. Always NUL terminates (unless siz == 0). + * Returns strlen(src); if retval >= siz, truncation occurred. + */ +size_t strlcpy(dst, src, siz) + char *dst; + const char *src; + size_t siz; +{ + register char *d = dst; + register const char *s = src; + register size_t n = siz; + + if (n == 0) + return(strlen(s)); + while (*s != '\0') { + if (n != 1) { + *d++ = *s; + n--; + } + s++; + } + *d = '\0'; + + return(s - src); /* count does not include NUL */ +} diff --git a/pool/shard010/C/0138112_kxsd9-spi.c b/pool/shard010/C/0138112_kxsd9-spi.c new file mode 100644 index 0000000000000000000000000000000000000000..441e6b764281c3e2c5c54188309a20e992bd9b9c --- /dev/null +++ b/pool/shard010/C/0138112_kxsd9-spi.c @@ -0,0 +1,68 @@ +// SPDX-License-Identifier: GPL-2.0-only +#include +#include +#include +#include +#include +#include +#include +#include + +#include "kxsd9.h" + +static int kxsd9_spi_probe(struct spi_device *spi) +{ + static const struct regmap_config config = { + .reg_bits = 8, + .val_bits = 8, + .max_register = 0x0e, + }; + struct regmap *regmap; + + spi->mode = SPI_MODE_0; + regmap = devm_regmap_init_spi(spi, &config); + if (IS_ERR(regmap)) { + dev_err(&spi->dev, "%s: regmap allocation failed: %ld\n", + __func__, PTR_ERR(regmap)); + return PTR_ERR(regmap); + } + + return kxsd9_common_probe(&spi->dev, + regmap, + spi_get_device_id(spi)->name); +} + +static int kxsd9_spi_remove(struct spi_device *spi) +{ + kxsd9_common_remove(&spi->dev); + + return 0; +} + +static const struct spi_device_id kxsd9_spi_id[] = { + {"kxsd9", 0}, + { }, +}; +MODULE_DEVICE_TABLE(spi, kxsd9_spi_id); + +static const struct of_device_id kxsd9_of_match[] = { + { .compatible = "kionix,kxsd9" }, + { }, +}; +MODULE_DEVICE_TABLE(of, kxsd9_of_match); + +static struct spi_driver kxsd9_spi_driver = { + .driver = { + .name = "kxsd9", + .pm = &kxsd9_dev_pm_ops, + .of_match_table = kxsd9_of_match, + }, + .probe = kxsd9_spi_probe, + .remove = kxsd9_spi_remove, + .id_table = kxsd9_spi_id, +}; +module_spi_driver(kxsd9_spi_driver); + +MODULE_AUTHOR("Jonathan Cameron "); +MODULE_DESCRIPTION("Kionix KXSD9 SPI driver"); +MODULE_LICENSE("GPL v2"); diff --git a/pool/shard010/C/0138113_test-pint-ncache.c b/pool/shard010/C/0138113_test-pint-ncache.c new file mode 100644 index 0000000000000000000000000000000000000000..ec6b5f21e68dcd52821da98f96d90fdf605925a7 --- /dev/null +++ b/pool/shard010/C/0138113_test-pint-ncache.c @@ -0,0 +1,247 @@ +/* + * (C) 2001 Clemson University and The University of Chicago + * + * See COPYING in top-level directory. + */ + +#include +#include + +#include "pvfs2.h" +#include "ncache.h" +#include "gossip.h" +#include "pvfs2-internal.h" + +/* this is a test program that exercises the ncache interface and + * demonstrates how to use it. + */ + +int main(int argc, char **argv) +{ + int ret = -1; + + PVFS_object_ref test_ref; + + PVFS_object_ref root_ref = {100,0}; + + PVFS_object_ref first_ref = {1,0}; + char first_name[] = "first"; + + PVFS_object_ref second_ref = {2,0}; + char second_name[] = "second"; + + PVFS_object_ref third_ref = {3,0}; + char third_name[] = "third"; + + /* set debugging stuff */ + gossip_enable_stderr(); + gossip_set_debug_mask(1, GOSSIP_NCACHE_DEBUG); + + /* initialize the cache */ + ret = PINT_ncache_initialize(); + if(ret < 0) + { + fprintf(stderr, "ncache_initialize() failure.\n"); + return(-1); + } + + PINT_ncache_set_info(TCACHE_TIMEOUT_MSECS,5000); + + /* try to lookup something when there is nothing in there */ + ret = PINT_ncache_get_cached_entry((const char*) "first", + &test_ref, + (const PVFS_object_ref*) &root_ref); + if (ret < 0 && ret != -PVFS_ENOENT) + { + fprintf(stderr, "ncache_lookup() failure.\n"); + return(-1); + } + if (ret == 0) + { + fprintf(stderr, "Failure: lookup succeeded when it shouldn't have.\n"); + return(-1); + } + + /* insert a few things */ + ret = PINT_ncache_update((const char*) first_name, + (const PVFS_object_ref*) &first_ref, + (const PVFS_object_ref*) &root_ref); + if(ret < 0) + { + fprintf(stderr, "Error: failed to insert entry.\n"); + return(-1); + } + ret = PINT_ncache_update((const char*) second_name, + (const PVFS_object_ref*) &second_ref, + (const PVFS_object_ref*) &first_ref); + if(ret < 0) + { + fprintf(stderr, "Error: failed to insert entry.\n"); + return(-1); + } + ret = PINT_ncache_update((const char*) third_name, + (const PVFS_object_ref*) &third_ref, + (const PVFS_object_ref*) &second_ref); + if(ret < 0) + { + fprintf(stderr, "Error: failed to insert entry.\n"); + return(-1); + } + + /* lookup a few things */ + ret = PINT_ncache_get_cached_entry((const char*) "first", + &test_ref, + (const PVFS_object_ref*) &root_ref); + if (ret < 0 && ret != -PVFS_ENOENT) + { + fprintf(stderr, "ncache_lookup() failure.\n"); + return(-1); + } + if (ret == -PVFS_ENOENT || test_ref.handle != first_ref.handle) + { + fprintf(stderr, "Failure: lookup didn't return correct " + "handle (%llu != %llu)\n", llu(test_ref.handle), + llu(first_ref.handle)); + return(-1); + } + + ret = PINT_ncache_get_cached_entry((const char*) "second", + &test_ref, + (const PVFS_object_ref*) &first_ref); + if (ret < 0 && ret != -PVFS_ENOENT) + { + fprintf(stderr, "ncache_lookup() failure.\n"); + return(-1); + } + if (ret == -PVFS_ENOENT || test_ref.handle != second_ref.handle) + { + fprintf(stderr, "Failure: lookup didn't return correct " + "handle (%llu != %llu)\n", llu(test_ref.handle), + llu(second_ref.handle)); + return(-1); + } + + ret = PINT_ncache_get_cached_entry((const char*) "third", + &test_ref, + (const PVFS_object_ref*) &second_ref); + if (ret < 0 && ret != -PVFS_ENOENT) + { + fprintf(stderr, "ncache_lookup() failure.\n"); + return(-1); + } + + if ((ret == -PVFS_ENOENT) || (test_ref.handle != third_ref.handle)) + { + fprintf(stderr, "Failure: lookup didn't return correct " + "handle (%llu != %llu)\n", llu(test_ref.handle), + llu(third_ref.handle)); + return(-1); + } + + /* sleep a little bit to let entries expire, then retry */ + printf("sleeping a few seconds before trying cache again.\n"); + sleep(7); + + ret = PINT_ncache_get_cached_entry((const char*) "second", + &test_ref, + (const PVFS_object_ref*) &first_ref); + if ((ret < 0) && (ret != -PVFS_ENOENT)) + { + fprintf(stderr, "ncache_lookup() failure.\n"); + return(-1); + } + + if (ret != -PVFS_ENOENT) + { + fprintf(stderr, "Failure: lookup didn't return correct " + "handle (%llu != %llu)\n", llu(test_ref.handle), + llu(first_ref.handle)); + fprintf(stderr, "Failure: lookup didn't return correct handle.\n"); + return(-1); + } + + ret = PINT_ncache_get_cached_entry((const char*) "first", + &test_ref, + (const PVFS_object_ref*) &root_ref); + if (ret < 0 && ret != -PVFS_ENOENT) + { + fprintf(stderr, "ncache_lookup() failure.\n"); + return(-1); + } + if (ret != -PVFS_ENOENT) + { + fprintf(stderr, "Failure: lookup didn't return correct handle.\n"); + return(-1); + } + + ret = PINT_ncache_get_cached_entry((const char*) "third", + &test_ref, + (const PVFS_object_ref*) &second_ref); + if (ret < 0 && ret != -PVFS_ENOENT) + { + fprintf(stderr, "ncache_lookup() failure.\n"); + return(-1); + } + if (ret != -PVFS_ENOENT) + { + fprintf(stderr, "Failure: lookup didn't return correct handle.\n"); + return(-1); + } + + /* try inserting twice */ + ret = PINT_ncache_update((const char*) first_name, + (const PVFS_object_ref*) &first_ref, + (const PVFS_object_ref*) &root_ref); + if(ret < 0) + { + fprintf(stderr, "Error: failed to insert entry.\n"); + return(-1); + } + ret = PINT_ncache_update(first_name, + (const PVFS_object_ref*) &first_ref, + (const PVFS_object_ref*) &root_ref); + if(ret < 0) + { + fprintf(stderr, "Error: failed to insert entry.\n"); + return(-1); + } + + /* then remove once */ + PINT_ncache_invalidate((const char*) first_name, + (const PVFS_object_ref*) &root_ref); + + /* lookup the same entry, shouldn't get it */ + ret = PINT_ncache_get_cached_entry((const char*) "first", + &test_ref, + (const PVFS_object_ref*) &root_ref); + if (ret < 0 && ret != -PVFS_ENOENT) + { + fprintf(stderr, "ncache_lookup() failure.\n"); + return(-1); + } + if (ret != -PVFS_ENOENT) + { + fprintf(stderr, "Failure: lookup didn't return correct handle.\n"); + return(-1); + } + + /* then remove again - found flag should be zero now */ + PINT_ncache_invalidate((const char*) first_name, + (const PVFS_object_ref*) &root_ref); + + /* finalize the cache */ + PINT_ncache_finalize(); + gossip_disable(); + + return(0); +} + +/* + * Local variables: + * mode: c + * c-indent-level: 4 + * c-basic-offset: 4 + * End: + * + * vim: ts=8 sts=4 sw=4 expandtab + */ diff --git a/pool/shard010/C/0138114_pr45034.c b/pool/shard010/C/0138114_pr45034.c new file mode 100644 index 0000000000000000000000000000000000000000..2d86f309cebc4405d0412d043eaa31e00240896c --- /dev/null +++ b/pool/shard010/C/0138114_pr45034.c @@ -0,0 +1,45 @@ +extern void abort (void); +static void fixnum_neg(signed char x, signed char *py, int *pv) +{ + unsigned char ux, uy; + + ux = (unsigned char)x; + uy = -ux; + *py = (uy <= 127) ? (signed char)uy : (-(signed char)(255 - uy) - 1); + *pv = (x == -128) ? 1 : 0; +} + +void __attribute__((noinline)) foo(int x, int y, int v) +{ + if (y < -128 || y > 127) + abort(); +} + +int test_neg(void) +{ + signed char x, y; + int v, err; + + err = 0; + x = -128; + for (;;) { + fixnum_neg(x, &y, &v); + foo((int)x, (int)y, v); + if ((v && x != -128) || (!v && x == -128)) + ++err; + if (x == 127) + break; + ++x; + } + return err; +} + +int main(void) +{ + if (sizeof (char) != 1) + return 0; + if (test_neg() != 0) + abort(); + return 0; +} + diff --git a/pool/shard010/C/0138115_pit.c b/pool/shard010/C/0138115_pit.c new file mode 100644 index 0000000000000000000000000000000000000000..aa15beeb36ca8b7676a49894860f66baee32c7e1 --- /dev/null +++ b/pool/shard010/C/0138115_pit.c @@ -0,0 +1,90 @@ +/***************************************************************************/ + +/* + * pit.c -- Freescale ColdFire PIT timer. Currently this type of + * hardware timer only exists in the Freescale ColdFire + * 5270/5271, 5282 and other CPUs. + * + * Copyright (C) 1999-2006, Greg Ungerer (gerg@snapgear.com) + * Copyright (C) 2001-2004, SnapGear Inc. (www.snapgear.com) + * + */ + +/***************************************************************************/ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +/***************************************************************************/ + +/* + * By default use timer1 as the system clock timer. + */ +#define TA(a) (MCF_IPSBAR + MCFPIT_BASE1 + (a)) + +/***************************************************************************/ + +void coldfire_pit_tick(void) +{ + unsigned short pcsr; + + /* Reset the ColdFire timer */ + pcsr = __raw_readw(TA(MCFPIT_PCSR)); + __raw_writew(pcsr | MCFPIT_PCSR_PIF, TA(MCFPIT_PCSR)); +} + +/***************************************************************************/ + +void coldfire_pit_init(irq_handler_t handler) +{ + volatile unsigned char *icrp; + volatile unsigned long *imrp; + + request_irq(MCFINT_VECBASE + MCFINT_PIT1, handler, IRQF_DISABLED, + "ColdFire Timer", NULL); + + icrp = (volatile unsigned char *) (MCF_IPSBAR + MCFICM_INTC0 + + MCFINTC_ICR0 + MCFINT_PIT1); + *icrp = ICR_INTRCONF; + + imrp = (volatile unsigned long *) (MCF_IPSBAR + MCFICM_INTC0 + MCFPIT_IMR); + *imrp &= ~MCFPIT_IMR_IBIT; + + /* Set up PIT timer 1 as poll clock */ + __raw_writew(MCFPIT_PCSR_DISABLE, TA(MCFPIT_PCSR)); + __raw_writew(((MCF_CLK / 2) / 64) / HZ, TA(MCFPIT_PMR)); + __raw_writew(MCFPIT_PCSR_EN | MCFPIT_PCSR_PIE | MCFPIT_PCSR_OVW | + MCFPIT_PCSR_RLD | MCFPIT_PCSR_CLK64, TA(MCFPIT_PCSR)); +} + +/***************************************************************************/ + +unsigned long coldfire_pit_offset(void) +{ + volatile unsigned long *ipr; + unsigned long pmr, pcntr, offset; + + ipr = (volatile unsigned long *) (MCF_IPSBAR + MCFICM_INTC0 + MCFPIT_IMR); + + pmr = __raw_readw(TA(MCFPIT_PMR)); + pcntr = __raw_readw(TA(MCFPIT_PCNTR)); + + /* + * If we are still in the first half of the upcount and a + * timer interupt is pending, then add on a ticks worth of time. + */ + offset = ((pmr - pcntr) * (1000000 / HZ)) / pmr; + if ((offset < (1000000 / HZ / 2)) && (*ipr & MCFPIT_IMR_IBIT)) + offset += 1000000 / HZ; + return offset; +} + +/***************************************************************************/ diff --git a/pool/shard010/C/0138116_sec_boot.c b/pool/shard010/C/0138116_sec_boot.c new file mode 100644 index 0000000000000000000000000000000000000000..765d6b3efb02b200e76533007830414dc5b60dde --- /dev/null +++ b/pool/shard010/C/0138116_sec_boot.c @@ -0,0 +1,213 @@ +/* Copyright Statement: + * + * This software/firmware and related documentation ("MediaTek Software") are + * protected under relevant copyright laws. The information contained herein is + * confidential and proprietary to MediaTek Inc. and/or its licensors. Without + * the prior written permission of MediaTek inc. and/or its licensors, any + * reproduction, modification, use or disclosure of MediaTek Software, and + * information contained herein, in whole or in part, shall be strictly + * prohibited. + * + * MediaTek Inc. (C) 2010. All rights reserved. + * + * BY OPENING THIS FILE, RECEIVER HEREBY UNEQUIVOCALLY ACKNOWLEDGES AND AGREES + * THAT THE SOFTWARE/FIRMWARE AND ITS DOCUMENTATIONS ("MEDIATEK SOFTWARE") + * RECEIVED FROM MEDIATEK AND/OR ITS REPRESENTATIVES ARE PROVIDED TO RECEIVER + * ON AN "AS-IS" BASIS ONLY. MEDIATEK EXPRESSLY DISCLAIMS ANY AND ALL + * WARRANTIES, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED + * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR + * NONINFRINGEMENT. NEITHER DOES MEDIATEK PROVIDE ANY WARRANTY WHATSOEVER WITH + * RESPECT TO THE SOFTWARE OF ANY THIRD PARTY WHICH MAY BE USED BY, + * INCORPORATED IN, OR SUPPLIED WITH THE MEDIATEK SOFTWARE, AND RECEIVER AGREES + * TO LOOK ONLY TO SUCH THIRD PARTY FOR ANY WARRANTY CLAIM RELATING THERETO. + * RECEIVER EXPRESSLY ACKNOWLEDGES THAT IT IS RECEIVER'S SOLE RESPONSIBILITY TO + * OBTAIN FROM ANY THIRD PARTY ALL PROPER LICENSES CONTAINED IN MEDIATEK + * SOFTWARE. MEDIATEK SHALL ALSO NOT BE RESPONSIBLE FOR ANY MEDIATEK SOFTWARE + * RELEASES MADE TO RECEIVER'S SPECIFICATION OR TO CONFORM TO A PARTICULAR + * STANDARD OR OPEN FORUM. RECEIVER'S SOLE AND EXCLUSIVE REMEDY AND MEDIATEK'S + * ENTIRE AND CUMULATIVE LIABILITY WITH RESPECT TO THE MEDIATEK SOFTWARE + * RELEASED HEREUNDER WILL BE, AT MEDIATEK'S OPTION, TO REVISE OR REPLACE THE + * MEDIATEK SOFTWARE AT ISSUE, OR REFUND ANY SOFTWARE LICENSE FEES OR SERVICE + * CHARGE PAID BY RECEIVER TO MEDIATEK FOR SUCH MEDIATEK SOFTWARE AT ISSUE. + * + * The following software/firmware and/or related documentation ("MediaTek + * Software") have been modified by MediaTek Inc. All revisions are subject to + * any receiver's applicable license agreements with MediaTek Inc. + */ + +/* for storage operations */ +#include "sec_platform.h" + +/* for crypto operations */ +#include "cust_sec_ctrl.h" +#include "sec_boot.h" +#include "sec_error.h" +#include "sec.h" +#include "KEY_IMAGE_AUTH.h" +#include "sec_secroimg.h" + +/* to get current boot device type */ +//#include "cust.h" + +/************************************************************************** +* MACRO +**************************************************************************/ +#define MOD "SBC" + +/****************************************************************************** + * DEBUG + ******************************************************************************/ +#define SEC_DEBUG (FALSE) +#define SMSG print +#if SEC_DEBUG +#define DMSG print +#else +#define DMSG +#endif + +/************************************************************************** + * GLOBAL VARIABLES + **************************************************************************/ +u8 g_oemkey[OEM_PUBK_SZ] = {OEM_PUBK}; + +/************************************************************************** + * LOCAL VARIABLES + **************************************************************************/ + +/************************************************************************** + * EXTERNAL VARIABLES + **************************************************************************/ +extern BOOL bDumpPartInfo; +extern AND_SECROIMG_T *secroimg; +extern unsigned int g_sec_cfg_exists; + +/************************************************************************** + * EXTERNAL FUNCTIONS + **************************************************************************/ + +/************************************************************************** + * [SECURE BOOT CHECK] + **************************************************************************/ +U32 sec_boot_img_check(BOOL sw_sboot_support, unsigned int boot_chk_img, U8* img_name) +{ + bDumpPartInfo = TRUE; + U32 ret = SEC_OK; + + if (TRUE == sw_sboot_support) + { + if (SW_SEC_BOOT_CHECK_IMAGE == boot_chk_img) + { + if (SEC_OK != (ret = seclib_image_check (img_name,TRUE))) + { + return ret; + } + } + } + else + { + if (SEC_OK != (ret = seclib_image_check (img_name,TRUE))) + { + return ret; + } + } + + return ret; +} + + + +void sec_boot_check (void) +{ + //if(CFG_STORAGE_DEVICE == NAND) + { + +#ifdef MTK_SECURITY_SW_SUPPORT + + U32 g_total_verify_time = get_timer(0); + U32 g_single_verify_time = 0; + U32 ret = 0; + BOOL sw_secure_boot_support = FALSE; + + if(FALSE == seclib_sec_boot_enabled(TRUE)) + { + SMSG("[%s] Don't check\n",MOD); + return ; + } + + if (0 == g_sec_cfg_exists) + { + SMSG("[%s] SECCFG does not exist, cannot do secure boot!\n",MOD); + ASSERT(0); + } + + if (0 != seclib_set_pubk(g_oemkey, OEM_PUBK_SZ)) { + SMSG("[%s] public key initialization failed, cannot do secure boot!\n",MOD); + ASSERT(0); + } + + /* --------------------- */ + /* init image auth key */ + /* --------------------- */ + if (SEC_OK != img_auth_init()) + { + SMSG("[%s] IMAGE Auth Key Init Fail\n",MOD); + ret = ERR_IMG_INIT_KEY_FAIL; + goto _fail; + } + + /* verification of secro image is enforced */ + /* secro must be verified first before using its content */ + g_single_verify_time = get_timer (0); + if (SEC_OK != seclib_image_check (SBOOT_PART_SECSTATIC,TRUE)) + { + goto _fail; + } + SMSG ("[%s] Consume (%d) ms\n", MOD, get_timer(g_single_verify_time)); + + sec_lib_read_secro(); + + if ((secroimg != NULL)&&(SW_SUPPORT_ENABLE == + (secroimg->m_andro.sw_sec_boot.flashtool_unlock_support))) + { + sw_secure_boot_support = TRUE; + } + + g_single_verify_time = get_timer (0);; + if (SEC_OK != sec_boot_img_check(sw_secure_boot_support, + secroimg->m_andro.sw_sec_boot.boot_chk_2nd_loader, SBOOT_PART_UBOOT)) + { + goto _fail; + } + SMSG ("[%s] Consume (%d) ms\n", MOD, get_timer(g_single_verify_time)); + + + +#if VERIFY_PART_CUST + g_single_verify_time = get_timer (0);; + if (SEC_OK != sec_boot_img_check(TRUE, SW_SEC_BOOT_CHECK_IMAGE, VERIFY_PART_CUST_NAME)) + { + goto _fail; + } + SMSG ("[%s] Consume (%d) ms\n", MOD, get_timer(g_single_verify_time)); +#endif + + seclib_cfg_print_status(); + + /* calculate verification time */ + SMSG ("\n[%s] Total Consume (%d) ms\n", MOD, get_timer (g_total_verify_time)); + return ; + +_fail : + SMSG ("[%s] Fail (0x%x)\n",MOD,ret); + ASSERT(0); + +_brom_recovery_check : + SMSG ("[%s] Fail (0x%x)\n",MOD,ret); + sec_util_brom_download_recovery_check(); + + +#endif // MTK_SECURITY_SW_SUPPORT + + } // if(CFG_STORAGE_DEVICE == NAND) + +} diff --git a/pool/shard010/C/0138117_flash_user.c b/pool/shard010/C/0138117_flash_user.c new file mode 100644 index 0000000000000000000000000000000000000000..0281b16c11753acd3edaaec6ad2a496f10a6896f --- /dev/null +++ b/pool/shard010/C/0138117_flash_user.c @@ -0,0 +1,299 @@ +/*-----------------------------------------------------------------------------*/ +/* */ +/* Copyright (c) James Pearman */ +/* 2012-2015 */ +/* All Rights Reserved */ +/* */ +/*-----------------------------------------------------------------------------*/ +/* */ +/* Module: flash_user.c */ +/* Author: James Pearman */ +/* Created: 21 Aug 2012 */ +/* */ +/* Revisions: */ +/* V1.00 4 Apr 2015 - Initial public release */ +/* */ +/*-----------------------------------------------------------------------------*/ +/* */ +/* The author is supplying this software for use with the VEX cortex */ +/* control system. this 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. */ +/* */ +/* This software 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 . */ +/* */ +/* The author can be contacted on the vex forums as jpearman */ +/* or electronic mail using jbpearman_at_mac_dot_com */ +/* Mentor for team 8888 RoboLancers, Pasadena CA. */ +/* */ +/*-----------------------------------------------------------------------------*/ +/* */ +/* Description: */ +/* */ +/* Read and write user parameters to NV storage on the cortex */ +/* ROBOTC version */ +/* */ +/*-----------------------------------------------------------------------------*/ +/* */ + +/*-----------------------------------------------------------------------------*/ +/** @file flash_user.c + * @brief Save a small number of user settings on the cortex +*//*---------------------------------------------------------------------------*/ + +// page 190 at present +#define FLASH_USER_PAGE_ADDR 0x0805F000 +#define FLASH_USER_INDEX_SIZE 64 +#define FLASH_USER_MAX_WRITE 32 +#define FLASH_USER_PAGE_SIZE 512 + + +// Number of user parameter words +// Do not change !! +#define FLASH_USER_SIZE 8 + +// Structure to hold user parameters +typedef struct _flash_user { + // storage for the NV data + unsigned char data[FLASH_USER_SIZE * sizeof(uint32_t)]; + + // useful debug data + int offset; + void *addr; + } flash_user; + +// local storage for user parameters +static flash_user params; + +// ROBOTC version 3.XX has issues with pointer calculations +// so we declare a variable that holds the page address +static long __FLASH_USER_PAGE_ADDR = FLASH_USER_PAGE_ADDR; + +/*-----------------------------------------------------------------------------*/ +/** @brief Send the contents of the user params page to the debug stream */ +/*-----------------------------------------------------------------------------*/ + +void +FlashUserDebug() +{ + unsigned char *p; + int i,j; + + p = (unsigned char *)__FLASH_USER_PAGE_ADDR; + + for(j=0;j<128;j++) + { + writeDebugStream("%08X: ", (uint32_t)p); + + for(i=0;i<16;i++) + writeDebugStream("%02X ", *p++); + + writeDebugStreamLine(""); + + // allow debugger to empty buffer + wait1Msec(25); + } +} + +/*-----------------------------------------------------------------------------*/ +/** @brief Get the offset into the user parameter block */ +/** @returns The offset (0 to 55) or -1 indicating no parameters */ +/*-----------------------------------------------------------------------------*/ + +int +FlashUserOffsetGet() +{ + uint16_t *p; + int offset = -1; + int i; + uint16_t su, sl; + + // the first 64 words (256 bytes) are used as an index + // calculate user param offset + // look for non zero half word + p = (uint16_t *)FLASH_USER_PAGE_ADDR; + + for(i=0;idata; + uint16_t i; + + // limit number of writes per run + static uint16_t flash_user_write_limit = 0; + + volatile FLASH_Status FLASHStatus = FLASH_COMPLETE; + + int ret = 1; + + // check write limit + if( flash_user_write_limit >= FLASH_USER_MAX_WRITE ) + return(FLASH_ERROR_WRITE_LIMIT); + + // one more write + flash_user_write_limit++; + + // Unlock the Flash Bank1 Program Erase controller + FLASH_UnlockBank1(); + + // Clear All pending flags + FLASH_ClearFlag(FLASH_FLAG_EOP | FLASH_FLAG_PGERR | FLASH_FLAG_WRPRTERR); + + // Get current param offset + u->offset = FlashUserOffsetGet(); + + // Next block + u->offset++; + + // did we fill the page ? + if( u->offset >= ((FLASH_USER_PAGE_SIZE - FLASH_USER_INDEX_SIZE) / FLASH_USER_SIZE) ) + { +#ifdef FFDEBUG + writeDebugStreamLine("erase, offset is %d\n", u->offset); +#endif + // Do erase here + FLASHStatus = FLASH_ErasePage(FLASH_USER_PAGE_ADDR); + + // check for error + if( FLASHStatus != FLASH_COMPLETE ) + return(FLASH_ERROR_ERASE); + + // start over + u->offset = 0; + } + + // start of area to write params + p = (uint32_t)(__FLASH_USER_PAGE_ADDR + ((FLASH_USER_INDEX_SIZE + (u->offset * FLASH_USER_SIZE)) * sizeof( uint32_t))); + + // Save addr for debug + u->addr = (uint32_t *)p; + + // Write data + for(i=0;ioffset * sizeof( uint32_t))); + + FLASHStatus = FLASH_ProgramWord( p, 0); + + // check for error + if( FLASHStatus != FLASH_COMPLETE ) + ret = (FLASH_ERROR_WRITE); + + return( ret ); +} + +/*-----------------------------------------------------------------------------*/ +/** @brief Initialize the user parameter memory */ +/** @Returns status or error code */ +/*-----------------------------------------------------------------------------*/ + +int +FlashUserInit() +{ + static int erase_done = 0; + + volatile FLASH_Status FLASHStatus = FLASH_COMPLETE; + + if( !erase_done ) + { + // only allow one init per run + erase_done = 1; + + // Unlock the Flash Bank1 Program Erase controller + FLASH_UnlockBank1(); + + // Erase user parameters + FLASHStatus = FLASH_ErasePage(FLASH_USER_PAGE_ADDR); + + // check for error + if( FLASHStatus != FLASH_COMPLETE ) + return(FLASH_ERROR_ERASE); + } + else + { + return(FLASH_ERROR_ERASE_LIMIT); + } + + return(1); +} diff --git a/pool/shard010/C/0138118_loop-gwv-1.c b/pool/shard010/C/0138118_loop-gwv-1.c new file mode 100644 index 0000000000000000000000000000000000000000..5c843012061877e5002990712e65deac7a903738 --- /dev/null +++ b/pool/shard010/C/0138118_loop-gwv-1.c @@ -0,0 +1,66 @@ +#include +#include +#include + +#define N (32*32*32+17) +int main () +{ + int ary[N]; + int ix; + int exit = 0; + int ondev = 0; + int gangsize, workersize, vectorsize; + + for (ix = 0; ix < N;ix++) + ary[ix] = -1; + +#pragma acc parallel num_gangs(32) num_workers(32) vector_length(32) \ + copy(ary) copy(ondev) copyout(gangsize, workersize, vectorsize) + { +#pragma acc loop gang worker vector + for (unsigned ix = 0; ix < N; ix++) + { + if (acc_on_device (acc_device_not_host)) + { + int g, w, v; + + g = __builtin_goacc_parlevel_id (GOMP_DIM_GANG); + w = __builtin_goacc_parlevel_id (GOMP_DIM_WORKER); + v = __builtin_goacc_parlevel_id (GOMP_DIM_VECTOR); + + ary[ix] = (g << 16) | (w << 8) | v; + ondev = 1; + } + else + ary[ix] = ix; + } + + gangsize = __builtin_goacc_parlevel_size (GOMP_DIM_GANG); + workersize = __builtin_goacc_parlevel_size (GOMP_DIM_WORKER); + vectorsize = __builtin_goacc_parlevel_size (GOMP_DIM_VECTOR); + } + + for (ix = 0; ix < N; ix++) + { + int expected = ix; + if(ondev) + { + int chunk_size = (N + gangsize * workersize * vectorsize - 1) + / (gangsize * workersize * vectorsize); + + int g = ix / (chunk_size * workersize * vectorsize); + int w = (ix / vectorsize) % workersize; + int v = ix % vectorsize; + + expected = (g << 16) | (w << 8) | v; + } + + if (ary[ix] != expected) + { + exit = 1; + printf ("ary[%d]=%x expected %x\n", ix, ary[ix], expected); + } + } + + return exit; +} diff --git a/pool/shard010/C/0138119_mf2044-pwm-lib.c b/pool/shard010/C/0138119_mf2044-pwm-lib.c new file mode 100644 index 0000000000000000000000000000000000000000..2947bf252a184ce7ae01b293467298ceeb115a56 --- /dev/null +++ b/pool/shard010/C/0138119_mf2044-pwm-lib.c @@ -0,0 +1,140 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "mf2044-pwm-lib.h" + +#define DEVICE_NAME "mf2044_pwm_drv" +#define PIN_CHECKER 0x150 +#define DUTY_INIT 0 + +#define MF2044_IOCTL_MAGIC 0x00 +#define MF2044_IOCTL_ON _IO(MF2044_IOCTL_MAGIC, 1) +#define MF2044_IOCTL_OFF _IO(MF2044_IOCTL_MAGIC, 2) +#define MF2044_IOCTL_GET_DUTY_CYCLE _IO(MF2044_IOCTL_MAGIC, 3) +#define MF2044_IOCTL_SET_DUTY_CYCLE _IO(MF2044_IOCTL_MAGIC, 4) +#define MF2044_IOCTL_GET_FREQUENCY _IO(MF2044_IOCTL_MAGIC, 5) +#define MF2044_IOCTL_SET_FREQUENCY _IO(MF2044_IOCTL_MAGIC, 6) + +static int fd = -1; + +int mf2044_pwm_open(void) +{ + fd = rt_dev_open(DEVICE_NAME, 0); + if (fd < 0) { + printf("ERROR : can't open device %s (%s)\n", + DEVICE_NAME, strerror(-fd)); + fflush(stdout); + return EXIT_FAILURE; + } +} + +int mf2044_pwm_close(void) +{ + rt_dev_close(fd); + return EXIT_SUCCESS; +} + +int mf2044_pwm_duty_cycle_get(MF2044_PWM_PINS pin) +{ + int duty, freq = -1; + int command = MF2044_IOCTL_GET_DUTY_CYCLE; + command |= pin; + + if (MF2044_PWM_PNULL>=pin || MF2044_PWM_PMAX <= pin) { + printf("param failed: pin[%d] is too high or too low.\n", pin); + return EXIT_FAILURE; + } + + if (rt_dev_ioctl(fd, command, &duty) == -1) { + printf("TIOCMGET failed: %s\n", strerror(errno)); + return EXIT_FAILURE; + } + + freq = mf2044_pwm_frequency_get(pin); + + return (duty/(freq*1.0)) * 100; +} + +int mf2044_pwm_duty_cycle_set(MF2044_PWM_PINS pin, int duty) +{ + int freq = mf2044_pwm_frequency_get(pin); + int duty_cycle = freq * (duty/100.0); + int command = MF2044_IOCTL_SET_DUTY_CYCLE; + command |= pin; + + if (0 > duty || 100 < duty) { + printf("param failed: duty[%d] should be from 0 to 100.\n", duty); + return EXIT_FAILURE; + } + if (MF2044_PWM_PNULL>=pin || MF2044_PWM_PMAX <= pin) { + printf("param failed: pin[%d] is too high or too low.\n", pin); + return EXIT_FAILURE; + } + + if (rt_dev_ioctl(fd, command, duty_cycle) == -1) { + printf("TIOCMGET failed: %s\n", strerror(errno)); + return EXIT_FAILURE; + } + return EXIT_SUCCESS; +} + +int mf2044_pwm_frequency_get(MF2044_PWM_PINS pin) +{ + int freq; + int command = MF2044_IOCTL_GET_FREQUENCY; + command |= pin; + + if (MF2044_PWM_PNULL>=pin || MF2044_PWM_PMAX <= pin) { + printf("param failed: pin[%d] is too high or too low.\n", pin); + return EXIT_FAILURE; + } + if (rt_dev_ioctl(fd, command, &freq) == -1) { + printf("TIOCMGET failed: %s\n", strerror(errno)); + return EXIT_FAILURE; + } + return freq; +} + +int mf2044_pwm_frequency_set(MF2044_PWM_PINS pin, int freq) +{ + int command = MF2044_IOCTL_SET_FREQUENCY; + command |= pin; + int duty1 = mf2044_pwm_duty_cycle_get(pin); + int duty2 = DUTY_INIT; + + if (0 > freq) { + printf("param failed: freq[%d] should be more than 0.\n", freq); + return EXIT_FAILURE; + } + if (MF2044_PWM_PNULL>=pin || MF2044_PWM_PMAX <= pin) { + printf("param failed: pin[%d] is too high or too low.\n", pin); + return EXIT_FAILURE; + } + + // Get duty cycle in same eHRPWM + if (pin == (PIN_CHECKER & pin)) { + duty2 = mf2044_pwm_duty_cycle_get(pin << 1); + } else { + duty2 = mf2044_pwm_duty_cycle_get(pin >> 1); + } + + // Check A and B duty cycles in same eHRPWM are already set or not + if (duty1 != DUTY_INIT && duty2 != DUTY_INIT) { + fprintf(stderr,"You can not change frequency after setting both duty cycle in pwmss\n"); + fprintf(stderr,"current duty cycles: A[%d] / B[%d]\n",duty1,duty2); + return EXIT_FAILURE; + } + if (rt_dev_ioctl(fd, command, freq) == -1) { + fprintf(stderr,"TIOCMGET failed: %s\n", strerror(errno)); + return EXIT_FAILURE; + } + + return EXIT_SUCCESS; +} + diff --git a/pool/shard010/C/0138120_gameboard.c b/pool/shard010/C/0138120_gameboard.c new file mode 100644 index 0000000000000000000000000000000000000000..447b95b10c358f6da0cfe8a77f5839e575ed82d0 --- /dev/null +++ b/pool/shard010/C/0138120_gameboard.c @@ -0,0 +1,59 @@ +#include "gameboard.h" + +/* Copies the master board to a local copy for each game */ +void init_gameboard(enum cell_contents board[][BOARDWIDTH]) +{ + int i, j; + for ( i = 0 ; i < BOARDWIDTH; i++) + { + for (j = 0; j < BOARDWIDTH; j++) + { + board[i][j] = master_board[i][j]; + } + } +} + +/* Prints the game board to the screen */ +void display_gameboard(enum cell_contents board[][BOARDWIDTH]) +{ + int i,j; + + printf("\n | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 |\n"); + + for (i = 0; i < BOARDWIDTH; i++) + { + printf("------------------------------------------------------\n"); + printf(" %d |", i); + for (j = 0; j < BOARDWIDTH; j++) + { + printf(" "); + + switch( board[i][j] ) + { + case EMPTY: + printf(" "); + break; + + case RED: + printf(RED_DISPLAY); + break; + + case WHITE: + printf(WHITE_DISPLAY); + break; + + case K_RED: + printf(RED_KING_DISPLAY); + break; + + case K_WHITE: + printf(WHITE_KING_DISPLAY); + break; + + } + printf(" %s|", WHITE_RESET); + } + printf("\n"); + } + printf("\n\n"); +} diff --git a/pool/shard010/C/0138121_guac_handlers.c b/pool/shard010/C/0138121_guac_handlers.c new file mode 100644 index 0000000000000000000000000000000000000000..be380df093c4be18a05659ea3acb287772952dba --- /dev/null +++ b/pool/shard010/C/0138121_guac_handlers.c @@ -0,0 +1,190 @@ +/* + * Copyright (C) 2013 Glyptodon LLC + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +#include "config.h" + +#include "client.h" +#include "guac_clipboard.h" +#include "guac_surface.h" + +#include +#include +#include +#include + +#ifdef ENABLE_COMMON_SSH +#include +#include +#include +#endif + +#ifdef ENABLE_PULSE +#include "pulse.h" +#endif + +#include + +/** + * Waits until data is available to be read from the given rfbClient, and thus + * a call to HandleRFBServerMessages() should not block. If the timeout elapses + * before data is available, zero is returned. + * + * @param rfb_client + * The rfbClient to wait for. + * + * @param timeout + * The maximum amount of time to wait, in microseconds. + * + * @returns + * A positive value if data is available, zero if the timeout elapses + * before data becomes available, or a negative value on error. + */ +static int guac_vnc_wait_for_messages(rfbClient* rfb_client, int timeout) { + + /* Do not explicitly wait while data is on the buffer */ + if (rfb_client->buffered) + return 1; + + /* If no data on buffer, wait for data on socket */ + return WaitForMessage(rfb_client, timeout); + +} + +int vnc_guac_client_handle_messages(guac_client* client) { + + vnc_guac_client_data* guac_client_data = (vnc_guac_client_data*) client->data; + rfbClient* rfb_client = guac_client_data->rfb_client; + + /* Initially wait for messages */ + int wait_result = guac_vnc_wait_for_messages(rfb_client, 1000000); + guac_timestamp frame_start = guac_timestamp_current(); + while (wait_result > 0) { + + guac_timestamp frame_end; + int frame_remaining; + + /* Handle any message received */ + if (!HandleRFBServerMessage(rfb_client)) { + guac_client_abort(client, GUAC_PROTOCOL_STATUS_UPSTREAM_ERROR, "Error handling message from VNC server."); + return 1; + } + + /* Calculate time remaining in frame */ + frame_end = guac_timestamp_current(); + frame_remaining = frame_start + GUAC_VNC_FRAME_DURATION - frame_end; + + /* Wait again if frame remaining */ + if (frame_remaining > 0) + wait_result = guac_vnc_wait_for_messages(rfb_client, + GUAC_VNC_FRAME_TIMEOUT*1000); + else + break; + + } + + /* If an error occurs, log it and fail */ + if (wait_result < 0) { + guac_client_abort(client, GUAC_PROTOCOL_STATUS_UPSTREAM_ERROR, "Connection closed."); + return 1; + } + + guac_common_surface_flush(guac_client_data->default_surface); + return 0; + +} + +int vnc_guac_client_mouse_handler(guac_client* client, int x, int y, int mask) { + + rfbClient* rfb_client = ((vnc_guac_client_data*) client->data)->rfb_client; + + SendPointerEvent(rfb_client, x, y, mask); + + return 0; +} + +int vnc_guac_client_key_handler(guac_client* client, int keysym, int pressed) { + + rfbClient* rfb_client = ((vnc_guac_client_data*) client->data)->rfb_client; + + SendKeyEvent(rfb_client, keysym, pressed); + + return 0; +} + +int vnc_guac_client_free_handler(guac_client* client) { + + vnc_guac_client_data* guac_client_data = (vnc_guac_client_data*) client->data; + rfbClient* rfb_client = guac_client_data->rfb_client; + +#ifdef ENABLE_PULSE + /* If audio enabled, stop streaming */ + if (guac_client_data->audio_enabled) + guac_pa_stop_stream(client); +#endif + +#ifdef ENABLE_COMMON_SSH + /* Free SFTP filesystem, if loaded */ + if (guac_client_data->sftp_filesystem) + guac_common_ssh_destroy_sftp_filesystem(guac_client_data->sftp_filesystem); + + /* Free SFTP session */ + if (guac_client_data->sftp_session) + guac_common_ssh_destroy_session(guac_client_data->sftp_session); + + /* Free SFTP user */ + if (guac_client_data->sftp_user) + guac_common_ssh_destroy_user(guac_client_data->sftp_user); + + guac_common_ssh_uninit(); +#endif + + /* Free encodings string, if used */ + if (guac_client_data->encodings != NULL) + free(guac_client_data->encodings); + + /* Free clipboard */ + guac_common_clipboard_free(guac_client_data->clipboard); + + /* Free surface */ + guac_common_surface_free(guac_client_data->default_surface); + + /* Free generic data struct */ + free(client->data); + + /* Free memory not free'd by libvncclient's rfbClientCleanup() */ + if (rfb_client->frameBuffer != NULL) free(rfb_client->frameBuffer); + if (rfb_client->raw_buffer != NULL) free(rfb_client->raw_buffer); + if (rfb_client->rcSource != NULL) free(rfb_client->rcSource); + + /* Free VNC rfbClientData linked list (not free'd by rfbClientCleanup()) */ + while (rfb_client->clientData != NULL) { + rfbClientData* next = rfb_client->clientData->next; + free(rfb_client->clientData); + rfb_client->clientData = next; + } + + /* Clean up VNC client*/ + rfbClientCleanup(rfb_client); + + return 0; +} + diff --git a/pool/shard010/C/0138122_digi00x-midi.c b/pool/shard010/C/0138122_digi00x-midi.c new file mode 100644 index 0000000000000000000000000000000000000000..915d2a21223e683f1f0f5fb613e0d5a8c7fb886b --- /dev/null +++ b/pool/shard010/C/0138122_digi00x-midi.c @@ -0,0 +1,219 @@ +/* + * digi00x-midi.h - a part of driver for Digidesign Digi 002/003 family + * + * Copyright (c) 2014-2015 Takashi Sakamoto + * + * Licensed under the terms of the GNU General Public License, version 2. + */ + +#include "digi00x.h" + +static int midi_phys_open(struct snd_rawmidi_substream *substream) +{ + struct snd_dg00x *dg00x = substream->rmidi->private_data; + int err; + + err = snd_dg00x_stream_lock_try(dg00x); + if (err < 0) + return err; + + mutex_lock(&dg00x->mutex); + dg00x->substreams_counter++; + err = snd_dg00x_stream_start_duplex(dg00x, 0); + mutex_unlock(&dg00x->mutex); + if (err < 0) + snd_dg00x_stream_lock_release(dg00x); + + return err; +} + +static int midi_phys_close(struct snd_rawmidi_substream *substream) +{ + struct snd_dg00x *dg00x = substream->rmidi->private_data; + + mutex_lock(&dg00x->mutex); + dg00x->substreams_counter--; + snd_dg00x_stream_stop_duplex(dg00x); + mutex_unlock(&dg00x->mutex); + + snd_dg00x_stream_lock_release(dg00x); + return 0; +} + +static void midi_phys_capture_trigger(struct snd_rawmidi_substream *substream, + int up) +{ + struct snd_dg00x *dg00x = substream->rmidi->private_data; + unsigned long flags; + + spin_lock_irqsave(&dg00x->lock, flags); + + if (up) + amdtp_dot_midi_trigger(&dg00x->tx_stream, substream->number, + substream); + else + amdtp_dot_midi_trigger(&dg00x->tx_stream, substream->number, + NULL); + + spin_unlock_irqrestore(&dg00x->lock, flags); +} + +static void midi_phys_playback_trigger(struct snd_rawmidi_substream *substream, + int up) +{ + struct snd_dg00x *dg00x = substream->rmidi->private_data; + unsigned long flags; + + spin_lock_irqsave(&dg00x->lock, flags); + + if (up) + amdtp_dot_midi_trigger(&dg00x->rx_stream, substream->number, + substream); + else + amdtp_dot_midi_trigger(&dg00x->rx_stream, substream->number, + NULL); + + spin_unlock_irqrestore(&dg00x->lock, flags); +} + +static int midi_ctl_open(struct snd_rawmidi_substream *substream) +{ + /* Do nothing. */ + return 0; +} + +static int midi_ctl_capture_close(struct snd_rawmidi_substream *substream) +{ + /* Do nothing. */ + return 0; +} + +static int midi_ctl_playback_close(struct snd_rawmidi_substream *substream) +{ + struct snd_dg00x *dg00x = substream->rmidi->private_data; + + snd_fw_async_midi_port_finish(&dg00x->out_control); + + return 0; +} + +static void midi_ctl_capture_trigger(struct snd_rawmidi_substream *substream, + int up) +{ + struct snd_dg00x *dg00x = substream->rmidi->private_data; + unsigned long flags; + + spin_lock_irqsave(&dg00x->lock, flags); + + if (up) + dg00x->in_control = substream; + else + dg00x->in_control = NULL; + + spin_unlock_irqrestore(&dg00x->lock, flags); +} + +static void midi_ctl_playback_trigger(struct snd_rawmidi_substream *substream, + int up) +{ + struct snd_dg00x *dg00x = substream->rmidi->private_data; + unsigned long flags; + + spin_lock_irqsave(&dg00x->lock, flags); + + if (up) + snd_fw_async_midi_port_run(&dg00x->out_control, substream); + + spin_unlock_irqrestore(&dg00x->lock, flags); +} + +static void set_midi_substream_names(struct snd_dg00x *dg00x, + struct snd_rawmidi_str *str, + bool is_ctl) +{ + struct snd_rawmidi_substream *subs; + + list_for_each_entry(subs, &str->substreams, list) { + if (!is_ctl) + snprintf(subs->name, sizeof(subs->name), + "%s MIDI %d", + dg00x->card->shortname, subs->number + 1); + else + /* This port is for asynchronous transaction. */ + snprintf(subs->name, sizeof(subs->name), + "%s control", + dg00x->card->shortname); + } +} + +int snd_dg00x_create_midi_devices(struct snd_dg00x *dg00x) +{ + static const struct snd_rawmidi_ops phys_capture_ops = { + .open = midi_phys_open, + .close = midi_phys_close, + .trigger = midi_phys_capture_trigger, + }; + static const struct snd_rawmidi_ops phys_playback_ops = { + .open = midi_phys_open, + .close = midi_phys_close, + .trigger = midi_phys_playback_trigger, + }; + static const struct snd_rawmidi_ops ctl_capture_ops = { + .open = midi_ctl_open, + .close = midi_ctl_capture_close, + .trigger = midi_ctl_capture_trigger, + }; + static const struct snd_rawmidi_ops ctl_playback_ops = { + .open = midi_ctl_open, + .close = midi_ctl_playback_close, + .trigger = midi_ctl_playback_trigger, + }; + struct snd_rawmidi *rmidi[2]; + struct snd_rawmidi_str *str; + unsigned int i; + int err; + + /* Add physical midi ports. */ + err = snd_rawmidi_new(dg00x->card, dg00x->card->driver, 0, + DOT_MIDI_OUT_PORTS, DOT_MIDI_IN_PORTS, &rmidi[0]); + if (err < 0) + return err; + + snprintf(rmidi[0]->name, sizeof(rmidi[0]->name), + "%s MIDI", dg00x->card->shortname); + + snd_rawmidi_set_ops(rmidi[0], SNDRV_RAWMIDI_STREAM_INPUT, + &phys_capture_ops); + snd_rawmidi_set_ops(rmidi[0], SNDRV_RAWMIDI_STREAM_OUTPUT, + &phys_playback_ops); + + /* Add a pair of control midi ports. */ + err = snd_rawmidi_new(dg00x->card, dg00x->card->driver, 1, + 1, 1, &rmidi[1]); + if (err < 0) + return err; + + snprintf(rmidi[1]->name, sizeof(rmidi[1]->name), + "%s control", dg00x->card->shortname); + + snd_rawmidi_set_ops(rmidi[1], SNDRV_RAWMIDI_STREAM_INPUT, + &ctl_capture_ops); + snd_rawmidi_set_ops(rmidi[1], SNDRV_RAWMIDI_STREAM_OUTPUT, + &ctl_playback_ops); + + for (i = 0; i < ARRAY_SIZE(rmidi); i++) { + rmidi[i]->private_data = dg00x; + + rmidi[i]->info_flags |= SNDRV_RAWMIDI_INFO_INPUT; + str = &rmidi[i]->streams[SNDRV_RAWMIDI_STREAM_INPUT]; + set_midi_substream_names(dg00x, str, i); + + rmidi[i]->info_flags |= SNDRV_RAWMIDI_INFO_OUTPUT; + str = &rmidi[i]->streams[SNDRV_RAWMIDI_STREAM_OUTPUT]; + set_midi_substream_names(dg00x, str, i); + + rmidi[i]->info_flags |= SNDRV_RAWMIDI_INFO_DUPLEX; + } + + return 0; +} diff --git a/pool/shard010/C/0138123_gpio.c b/pool/shard010/C/0138123_gpio.c new file mode 100644 index 0000000000000000000000000000000000000000..2ac36303e963cd1a14e75ea26579e0819cc98a7b --- /dev/null +++ b/pool/shard010/C/0138123_gpio.c @@ -0,0 +1,75 @@ +// SPDX-License-Identifier: Apache-2.0 +/* Copyright 2013-2014 Google Corp. */ + +#include +#include "ec/config.h" +#include "ec/gpio.h" + +int ec_gpio_setup(EcGpioPort port, uint8_t pin, + int is_output, int pullup_enable) +{ + uint8_t ddr_reg; + if (pin > 7) { + return -1; + } + + /* Set data direction */ + ec_outb(EC_GPIO_INDEX, + port * EC_GPIO_PORT_SKIP + EC_GPIO_DDR_OFFSET); + ddr_reg = ec_inb(EC_GPIO_DATA); + if (is_output) { + ddr_reg |= (1 << pin); + } else { + ddr_reg &= ~(1 << pin); + } + ec_outb(EC_GPIO_DATA, ddr_reg); + + /* Set pullup enable for output GPOs */ + if (is_output) + { + uint8_t pup_reg; + ec_outb(EC_GPIO_INDEX, + port * EC_GPIO_PORT_SKIP + EC_GPIO_PUP_OFFSET); + pup_reg = ec_inb(EC_GPIO_DATA); + if (pullup_enable) { + pup_reg |= (1 << pin); + } else { + pup_reg &= ~(1 << pin); + } + ec_outb(EC_GPIO_DATA, pup_reg); + } + + return 0; +} + +int ec_gpio_read(EcGpioPort port, uint8_t pin) +{ + uint8_t pin_reg; + if (pin > 7) { + return -1; + } + + ec_outb(EC_GPIO_INDEX, + port * EC_GPIO_PORT_SKIP + EC_GPIO_PIN_OFFSET); + pin_reg = ec_inb(EC_GPIO_DATA); + return !!(pin_reg & (1 << pin)); +} + +int ec_gpio_set(EcGpioPort port, uint8_t pin, int val) +{ + uint8_t data_reg; + if (pin > 7) { + return -1; + } + + ec_outb(EC_GPIO_INDEX, + port * EC_GPIO_PORT_SKIP + EC_GPIO_DATA_OFFSET); + data_reg = ec_inb(EC_GPIO_DATA); + if (val) { + data_reg |= (1 << pin); + } else { + data_reg &= ~(1 << pin); + } + ec_outb(EC_GPIO_DATA, data_reg); + return 0; +} diff --git a/pool/shard010/C/0138124_yamltree.c b/pool/shard010/C/0138124_yamltree.c new file mode 100644 index 0000000000000000000000000000000000000000..e63d32fe142a70311b4c80afe0161b4c9c633ec7 --- /dev/null +++ b/pool/shard010/C/0138124_yamltree.c @@ -0,0 +1,233 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +/* + * (C) Copyright Linaro, Ltd. 2018 + * (C) Copyright Arm Holdings. 2017 + * (C) Copyright David Gibson , IBM Corporation. 2005. + */ + +#include +#include +#include "dtc.h" +#include "srcpos.h" + +char *yaml_error_name[] = { + [YAML_NO_ERROR] = "no error", + [YAML_MEMORY_ERROR] = "memory error", + [YAML_READER_ERROR] = "reader error", + [YAML_SCANNER_ERROR] = "scanner error", + [YAML_PARSER_ERROR] = "parser error", + [YAML_COMPOSER_ERROR] = "composer error", + [YAML_WRITER_ERROR] = "writer error", + [YAML_EMITTER_ERROR] = "emitter error", +}; + +#define yaml_emitter_emit_or_die(emitter, event) ( \ +{ \ + if (!yaml_emitter_emit(emitter, event)) \ + die("yaml '%s': %s in %s, line %i\n", \ + yaml_error_name[(emitter)->error], \ + (emitter)->problem, __func__, __LINE__); \ +}) + +static void yaml_propval_int(yaml_emitter_t *emitter, struct marker *markers, char *data, unsigned int len, int width) +{ + yaml_event_t event; + void *tag; + unsigned int off, start_offset = markers->offset; + + switch(width) { + case 1: tag = "!u8"; break; + case 2: tag = "!u16"; break; + case 4: tag = "!u32"; break; + case 8: tag = "!u64"; break; + default: + die("Invalid width %i", width); + } + assert(len % width == 0); + + yaml_sequence_start_event_initialize(&event, NULL, + (yaml_char_t *)tag, width == 4, YAML_FLOW_SEQUENCE_STYLE); + yaml_emitter_emit_or_die(emitter, &event); + + for (off = 0; off < len; off += width) { + char buf[32]; + struct marker *m; + bool is_phandle = false; + + switch(width) { + case 1: + sprintf(buf, "0x%"PRIx8, *(uint8_t*)(data + off)); + break; + case 2: + sprintf(buf, "0x%"PRIx16, dtb_ld16(data + off)); + break; + case 4: + sprintf(buf, "0x%"PRIx32, dtb_ld32(data + off)); + m = markers; + is_phandle = false; + for_each_marker_of_type(m, REF_PHANDLE) { + if (m->offset == (start_offset + off)) { + is_phandle = true; + break; + } + } + break; + case 8: + sprintf(buf, "0x%"PRIx64, dtb_ld64(data + off)); + break; + } + + if (is_phandle) + yaml_scalar_event_initialize(&event, NULL, + (yaml_char_t*)"!phandle", (yaml_char_t *)buf, + strlen(buf), 0, 0, YAML_PLAIN_SCALAR_STYLE); + else + yaml_scalar_event_initialize(&event, NULL, + (yaml_char_t*)YAML_INT_TAG, (yaml_char_t *)buf, + strlen(buf), 1, 1, YAML_PLAIN_SCALAR_STYLE); + yaml_emitter_emit_or_die(emitter, &event); + } + + yaml_sequence_end_event_initialize(&event); + yaml_emitter_emit_or_die(emitter, &event); +} + +static void yaml_propval_string(yaml_emitter_t *emitter, char *str, int len) +{ + yaml_event_t event; + int i; + + assert(str[len-1] == '\0'); + + /* Make sure the entire string is in the lower 7-bit ascii range */ + for (i = 0; i < len; i++) + assert(isascii(str[i])); + + yaml_scalar_event_initialize(&event, NULL, + (yaml_char_t *)YAML_STR_TAG, (yaml_char_t*)str, + len-1, 0, 1, YAML_DOUBLE_QUOTED_SCALAR_STYLE); + yaml_emitter_emit_or_die(emitter, &event); +} + +static void yaml_propval(yaml_emitter_t *emitter, struct property *prop) +{ + yaml_event_t event; + unsigned int len = prop->val.len; + struct marker *m = prop->val.markers; + + /* Emit the property name */ + yaml_scalar_event_initialize(&event, NULL, + (yaml_char_t *)YAML_STR_TAG, (yaml_char_t*)prop->name, + strlen(prop->name), 1, 1, YAML_PLAIN_SCALAR_STYLE); + yaml_emitter_emit_or_die(emitter, &event); + + /* Boolean properties are easiest to deal with. Length is zero, so just emit 'true' */ + if (len == 0) { + yaml_scalar_event_initialize(&event, NULL, + (yaml_char_t *)YAML_BOOL_TAG, + (yaml_char_t*)"true", + strlen("true"), 1, 0, YAML_PLAIN_SCALAR_STYLE); + yaml_emitter_emit_or_die(emitter, &event); + return; + } + + if (!m) + die("No markers present in property '%s' value\n", prop->name); + + yaml_sequence_start_event_initialize(&event, NULL, + (yaml_char_t *)YAML_SEQ_TAG, 1, YAML_FLOW_SEQUENCE_STYLE); + yaml_emitter_emit_or_die(emitter, &event); + + for_each_marker(m) { + int chunk_len; + char *data = &prop->val.val[m->offset]; + + if (m->type < TYPE_UINT8) + continue; + + chunk_len = type_marker_length(m) ? : len; + assert(chunk_len > 0); + len -= chunk_len; + + switch(m->type) { + case TYPE_UINT16: + yaml_propval_int(emitter, m, data, chunk_len, 2); + break; + case TYPE_UINT32: + yaml_propval_int(emitter, m, data, chunk_len, 4); + break; + case TYPE_UINT64: + yaml_propval_int(emitter, m, data, chunk_len, 8); + break; + case TYPE_STRING: + yaml_propval_string(emitter, data, chunk_len); + break; + default: + yaml_propval_int(emitter, m, data, chunk_len, 1); + break; + } + } + + yaml_sequence_end_event_initialize(&event); + yaml_emitter_emit_or_die(emitter, &event); +} + + +static void yaml_tree(struct node *tree, yaml_emitter_t *emitter) +{ + struct property *prop; + struct node *child; + yaml_event_t event; + + if (tree->deleted) + return; + + yaml_mapping_start_event_initialize(&event, NULL, + (yaml_char_t *)YAML_MAP_TAG, 1, YAML_ANY_MAPPING_STYLE); + yaml_emitter_emit_or_die(emitter, &event); + + for_each_property(tree, prop) + yaml_propval(emitter, prop); + + /* Loop over all the children, emitting them into the map */ + for_each_child(tree, child) { + yaml_scalar_event_initialize(&event, NULL, + (yaml_char_t *)YAML_STR_TAG, (yaml_char_t*)child->name, + strlen(child->name), 1, 0, YAML_PLAIN_SCALAR_STYLE); + yaml_emitter_emit_or_die(emitter, &event); + yaml_tree(child, emitter); + } + + yaml_mapping_end_event_initialize(&event); + yaml_emitter_emit_or_die(emitter, &event); +} + +void dt_to_yaml(FILE *f, struct dt_info *dti) +{ + yaml_emitter_t emitter; + yaml_event_t event; + + yaml_emitter_initialize(&emitter); + yaml_emitter_set_output_file(&emitter, f); + yaml_stream_start_event_initialize(&event, YAML_UTF8_ENCODING); + yaml_emitter_emit_or_die(&emitter, &event); + + yaml_document_start_event_initialize(&event, NULL, NULL, NULL, 0); + yaml_emitter_emit_or_die(&emitter, &event); + + yaml_sequence_start_event_initialize(&event, NULL, (yaml_char_t *)YAML_SEQ_TAG, 1, YAML_ANY_SEQUENCE_STYLE); + yaml_emitter_emit_or_die(&emitter, &event); + + yaml_tree(dti->dt, &emitter); + + yaml_sequence_end_event_initialize(&event); + yaml_emitter_emit_or_die(&emitter, &event); + + yaml_document_end_event_initialize(&event, 0); + yaml_emitter_emit_or_die(&emitter, &event); + + yaml_stream_end_event_initialize(&event); + yaml_emitter_emit_or_die(&emitter, &event); + + yaml_emitter_delete(&emitter); +} diff --git a/pool/shard010/C/0138125_dd.c b/pool/shard010/C/0138125_dd.c new file mode 100644 index 0000000000000000000000000000000000000000..c27b87432cc67c572e962d557a92a0c7c81bfb33 --- /dev/null +++ b/pool/shard010/C/0138125_dd.c @@ -0,0 +1,114 @@ +/* + * ReactOS Generic Framebuffer display driver directdraw interface + * + * Copyright (C) 2006 Magnus Olsen + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +/* Here we put in all 2d api for directdraw and redirect some of them to GDI api */ + +#include "framebuf.h" + +DWORD CALLBACK +DdCanCreateSurface(LPDDHAL_CANCREATESURFACEDATA pccsd) +{ + + /* We do not support 3d buffer so we fail here */ + if ((pccsd->lpDDSurfaceDesc->ddsCaps.dwCaps & DDSCAPS_ZBUFFER) && + (pccsd->lpDDSurfaceDesc->ddsCaps.dwCaps & DDSCAPS_VIDEOMEMORY)) + { + pccsd->ddRVal = DDERR_INVALIDPIXELFORMAT; + return DDHAL_DRIVER_HANDLED; + } + + + /* Check if another pixel format or not, we fail for now */ + if (pccsd->bIsDifferentPixelFormat) + { + /* check the fourcc diffent FOURCC, but we only support BMP for now */ + //if(pccsd->lpDDSurfaceDesc->ddpfPixelFormat.dwFlags & DDPF_FOURCC) + //{ + // /* We do not support other pixel format */ + // switch (pccsd->lpDDSurfaceDesc->ddpfPixelFormat.dwFourCC) + // { + // default: + // pccsd->ddRVal = DDERR_INVALIDPIXELFORMAT; + // return DDHAL_DRIVER_HANDLED; + // } + //} + // /* check the texture support, we do not support testure for now */ + //else if((pccsd->lpDDSurfaceDesc->ddsCaps.dwCaps & DDSCAPS_TEXTURE)) + //{ + // /* We do not support texture surface */ + // pccsd->ddRVal = DDERR_INVALIDPIXELFORMAT; + // return DDHAL_DRIVER_HANDLED; + //} + + /* Fail */ + pccsd->ddRVal = DDERR_INVALIDPIXELFORMAT; + return DDHAL_DRIVER_HANDLED; + } + + pccsd->ddRVal = DD_OK; + return DDHAL_DRIVER_HANDLED; +} + +DWORD CALLBACK +DdCreateSurface(PDD_CREATESURFACEDATA pcsd) +{ + int i; + + if (pcsd->dwSCnt < 1) + { + pcsd->ddRVal = DDERR_GENERIC; + return DDHAL_DRIVER_NOTHANDLED; + } + + + for (i=0; i<(int)pcsd->dwSCnt; i++) + { + pcsd->lplpSList[i]->lpGbl->lPitch = (DWORD)(pcsd->lplpSList[i]->lpGbl->wWidth * + (pcsd->lplpSList[i]->lpGbl->ddpfSurface.dwRGBBitCount / 8)); + + pcsd->lplpSList[i]->lpGbl->dwBlockSizeX = pcsd->lplpSList[i]->lpGbl->lPitch * + (DWORD)(pcsd->lplpSList[i]->lpGbl->wHeight); + + pcsd->lplpSList[i]->lpGbl->dwBlockSizeY = 1; + + if ( pcsd->lplpSList[i] ->ddsCaps.dwCaps & DDSCAPS_PRIMARYSURFACE) + { + /* We maybe should alloc it with EngAlloc + for now we trusting ddraw alloc it */ + pcsd->lplpSList[i]->lpGbl->fpVidMem = 0; + } + else + { + + /* We maybe should alloc it with EngAlloc + for now we trusting ddraw alloc it */ + pcsd->lplpSList[i]->lpGbl->fpVidMem = DDHAL_PLEASEALLOC_BLOCKSIZE; + } + + pcsd->lpDDSurfaceDesc->lPitch = pcsd->lplpSList[i]->lpGbl->lPitch; + pcsd->lpDDSurfaceDesc->dwFlags |= DDSD_PITCH; + + } // for i + + + + pcsd->ddRVal = DD_OK; + return DDHAL_DRIVER_HANDLED; +} diff --git a/pool/shard010/C/0138126_pmem-dax.c b/pool/shard010/C/0138126_pmem-dax.c new file mode 100644 index 0000000000000000000000000000000000000000..fd65f8d0a652b75142c3807eacd3b4471fdac883 --- /dev/null +++ b/pool/shard010/C/0138126_pmem-dax.c @@ -0,0 +1,62 @@ +/* + * Copyright (c) 2014-2016, Intel Corporation. + * + * This program is free software; you can redistribute it and/or modify it + * under the terms and conditions of the GNU General Public License, + * version 2, as published by the Free Software Foundation. + * + * This program is distributed in the hope it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + */ +#include "test/nfit_test.h" +#include +#include +#include + +long pmem_direct_access(struct block_device *bdev, sector_t sector, + void **kaddr, pfn_t *pfn) +{ + struct pmem_device *pmem = bdev->bd_queue->queuedata; + resource_size_t offset = sector * 512 + pmem->data_offset; + long max_len = pmem->size - pmem->pfn_pad - offset; + sector_t first_bad; + int num_bad; + + /* If we can't even map the first page, return error */ + if (unlikely(is_bad_pmem(&pmem->bb, sector, PAGE_SIZE))) + return -EIO; + + /* + * Limit dax to a single page at a time given vmalloc()-backed + * in the nfit_test case. + */ + if (get_nfit_res(pmem->phys_addr + offset)) { + struct page *page; + + *kaddr = pmem->virt_addr + offset; + page = vmalloc_to_page(pmem->virt_addr + offset); + *pfn = page_to_pfn_t(page); + dev_dbg_ratelimited(disk_to_dev(bdev->bd_disk)->parent, + "%s: sector: %#llx pfn: %#lx\n", __func__, + (unsigned long long) sector, page_to_pfn(page)); + + return PAGE_SIZE; + } + + *kaddr = pmem->virt_addr + offset; + *pfn = phys_to_pfn_t(pmem->phys_addr + offset, pmem->pfn_flags); + + /* + * If badblocks are present, limit range to the first known + * bad block. + */ + if (unlikely(pmem->bb.count) && + badblocks_check(&pmem->bb, sector, max_len / 512, + &first_bad, &num_bad)) { + return ((first_bad - sector) * 512) & ~(PAGE_SIZE-1); + } + + return max_len; +} diff --git a/pool/shard010/C/0138127_test-irc-helper.c b/pool/shard010/C/0138127_test-irc-helper.c new file mode 100644 index 0000000000000000000000000000000000000000..82d933a7dccd398d43db8f686dfffbce5d15122a --- /dev/null +++ b/pool/shard010/C/0138127_test-irc-helper.c @@ -0,0 +1,81 @@ +#include "config.h" +#include "test-irc-helper.h" + +void +check_server (TpawIrcServer *server, + const gchar *_address, + guint _port, + gboolean _ssl) +{ + gchar *address; + guint port; + gboolean ssl; + + g_assert (server != NULL); + + g_object_get (server, + "address", &address, + "port", &port, + "ssl", &ssl, + NULL); + + g_assert (address != NULL && strcmp (address, _address) == 0); + g_assert (port == _port); + g_assert (ssl == _ssl); + + g_free (address); +} + +void +check_network (TpawIrcNetwork *network, + const gchar *_name, + const gchar *_charset, + struct server_t *_servers, + guint nb_servers) +{ + gchar *name, *charset; + GSList *servers, *l; + guint i; + + g_assert (network != NULL); + + g_object_get (network, + "name", &name, + "charset", &charset, + NULL); + + g_assert (name != NULL && strcmp (name, _name) == 0); + g_assert (charset != NULL && strcmp (charset, _charset) == 0); + + servers = tpaw_irc_network_get_servers (network); + g_assert (g_slist_length (servers) == nb_servers); + + /* Is that the right servers ? */ + for (l = servers, i = 0; l != NULL; l = g_slist_next (l), i++) + { + TpawIrcServer *server; + gchar *address; + guint port; + gboolean ssl; + + server = l->data; + + g_object_get (server, + "address", &address, + "port", &port, + "ssl", &ssl, + NULL); + + g_assert (address != NULL && strcmp (address, _servers[i].address) + == 0); + g_assert (port == _servers[i].port); + g_assert (ssl == _servers[i].ssl); + + g_free (address); + } + + g_slist_foreach (servers, (GFunc) g_object_unref, NULL); + g_slist_free (servers); + g_free (name); + g_free (charset); +} diff --git a/pool/shard010/C/0138128_speex_header.c b/pool/shard010/C/0138128_speex_header.c new file mode 100644 index 0000000000000000000000000000000000000000..de729463b62e3bedd353ffc9a7aa942a742aa4ab --- /dev/null +++ b/pool/shard010/C/0138128_speex_header.c @@ -0,0 +1,166 @@ +/* Copyright (C) 2002 Jean-Marc Valin + File: speex_header.c + Describes the Speex header + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + + - Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + - Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + - Neither the name of the Xiph.org Foundation nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR + CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +*/ + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#include "misc.h" +#include "speex_header.h" +#include "speex.h" + +#ifndef NULL +#define NULL 0 +#endif + +#define ENDIAN_SWITCH(x) {x=le_int(x);} + + +/* +typedef struct SpeexHeader { + char speex_string[8]; + char speex_version[SPEEX_HEADER_VERSION_LENGTH]; + int speex_version_id; + int header_size; + int rate; + int mode; + int mode_bitstream_version; + int nb_channels; + int bitrate; + int frame_size; + int vbr; + int frames_per_packet; + int extra_headers; + int reserved1; + int reserved2; +} SpeexHeader; +*/ + +void speex_init_header(SpeexHeader *header, int rate, int nb_channels, const SpeexMode *m) +{ + int i; + const char *h="Speex "; + /* + strncpy(header->speex_string, "Speex ", 8); + strncpy(header->speex_version, SPEEX_VERSION, SPEEX_HEADER_VERSION_LENGTH-1); + header->speex_version[SPEEX_HEADER_VERSION_LENGTH-1]=0; + */ + for (i=0;i<8;i++) + header->speex_string[i]=h[i]; + for (i=0;ispeex_version[i]=SPEEX_VERSION[i]; + for (;ispeex_version[i]=0; + + header->speex_version_id = 1; + header->header_size = sizeof(SpeexHeader); + + header->rate = rate; + header->mode = m->modeID; + header->mode_bitstream_version = m->bitstream_version; + if (m->modeID<0) + speex_warning("This mode is meant to be used alone"); + header->nb_channels = nb_channels; + header->bitrate = -1; + speex_mode_query(m, SPEEX_MODE_FRAME_SIZE, &header->frame_size); + header->vbr = 0; + + header->frames_per_packet = 0; + header->extra_headers = 0; + header->reserved1 = 0; + header->reserved2 = 0; +} + +char *speex_header_to_packet(SpeexHeader *header, int *size) +{ + SpeexHeader *le_header; + le_header = (SpeexHeader*)speex_alloc(sizeof(SpeexHeader)); + + speex_move(le_header, header, sizeof(SpeexHeader)); + + /*Make sure everything is now little-endian*/ + ENDIAN_SWITCH(le_header->speex_version_id); + ENDIAN_SWITCH(le_header->header_size); + ENDIAN_SWITCH(le_header->rate); + ENDIAN_SWITCH(le_header->mode); + ENDIAN_SWITCH(le_header->mode_bitstream_version); + ENDIAN_SWITCH(le_header->nb_channels); + ENDIAN_SWITCH(le_header->bitrate); + ENDIAN_SWITCH(le_header->frame_size); + ENDIAN_SWITCH(le_header->vbr); + ENDIAN_SWITCH(le_header->frames_per_packet); + ENDIAN_SWITCH(le_header->extra_headers); + + *size = sizeof(SpeexHeader); + return (char *)le_header; +} + +SpeexHeader *speex_packet_to_header(char *packet, int size) +{ + int i; + SpeexHeader *le_header; + const char *h = "Speex "; + for (i=0;i<8;i++) + if (packet[i]!=h[i]) + { + speex_warning ("This doesn't look like a Speex file"); + return NULL; + } + + /*FIXME: Do we allow larger headers?*/ + if (size < (int)sizeof(SpeexHeader)) + { + speex_warning("Speex header too small"); + return NULL; + } + + le_header = (SpeexHeader*)speex_alloc(sizeof(SpeexHeader)); + + speex_move(le_header, packet, sizeof(SpeexHeader)); + + /*Make sure everything is converted correctly from little-endian*/ + ENDIAN_SWITCH(le_header->speex_version_id); + ENDIAN_SWITCH(le_header->header_size); + ENDIAN_SWITCH(le_header->rate); + ENDIAN_SWITCH(le_header->mode); + ENDIAN_SWITCH(le_header->mode_bitstream_version); + ENDIAN_SWITCH(le_header->nb_channels); + ENDIAN_SWITCH(le_header->bitrate); + ENDIAN_SWITCH(le_header->frame_size); + ENDIAN_SWITCH(le_header->vbr); + ENDIAN_SWITCH(le_header->frames_per_packet); + ENDIAN_SWITCH(le_header->extra_headers); + + return le_header; + +} diff --git a/pool/shard010/C/0138129_pinmux.c b/pool/shard010/C/0138129_pinmux.c new file mode 100644 index 0000000000000000000000000000000000000000..9925019a07b6d04a038634dfafac244369d4c347 --- /dev/null +++ b/pool/shard010/C/0138129_pinmux.c @@ -0,0 +1,172 @@ +/* pinmux_board_arduino_101.c - Arduino 101 board pinmux driver */ + +/* + * Copyright (c) 2015 Intel Corporation + * + * SPDX-License-Identifier: Apache-2.0 + */ +#include +#include +#include +#include +#include +#include +#include "pinmux/pinmux.h" + +#include "pinmux_quark_mcu.h" + +/* + * This is the full pinmap that we have available on the board for configuration + * including the ball position and the various modes that can be set. In the + * _pinmux_defaults we do not spend any time setting values that are using mode + * A as the hardware brings up all devices by default in mode A. + */ + +/* pin, ball, mode A, mode B, mode C */ +/* 0 F02, gpio_0, ain_0, spi_s_cs */ /* IO10 */ +/* 1 G04, gpio_1, ain_1, spi_s_miso */ /* IO12 */ +/* 2 H05, gpio_2, ain_2, spi_s_sck */ /* IO13 */ +/* 3 J06, gpio_3, ain_3, spi_s_mosi */ /* IO11 */ +/* 4 K06, gpio_4, ain_4, NA */ +/* 5 L06, gpio_5, ain_5, NA */ +/* 6 H04, gpio_6, ain_6, NA */ +/* 7 G03, gpio_7, ain_7, NA */ +/* 8 L05, gpio_ss_0, ain_8, uart1_cts */ +/* 9 M05, gpio_ss_1, ain_9, uart1_rts */ /* AD5 */ +/* 10 K05, gpio_ss_2, ain_10 */ /* AD0 */ +/* 11 G01, gpio_ss_3, ain_11 */ /* AD1 */ +/* 12 J04, gpio_ss_4, ain_12 */ /* AD2 */ +/* 13 G02, gpio_ss_5, ain_13 */ /* AD3 */ +/* 14 F01, gpio_ss_6, ain_14 */ /* AD4 */ +/* 15 J05, gpio_ss_7, ain_15 */ +/* 16 L04, gpio_ss_8, ain_16, uart1_txd */ /* IO1 */ +/* 17 M04, gpio_ss_9, ain_17, uart1_rxd */ /* IO0 */ +/* 18 K04, uart0_rx, ain_18, NA */ +/* 19 B02, uart0_tx, gpio_31, NA */ +/* 20 C01, i2c0_scl, NA, NA */ +/* 21 C02, i2c0_sda, NA, NA */ +/* 22 D01, i2c1_scl, NA, NA */ +/* 23 D02, i2c1_sda, NA, NA */ +/* 24 E01, i2c0_ss_sda, NA, NA */ +/* 25 E02, i2c0_ss_scl, NA, NA */ +/* 26 B03, i2c1_ss_sda, NA, NA */ +/* 27 A03, i2c1_ss_scl, NA, NA */ +/* 28 C03, spi0_ss_miso, NA, NA */ +/* 29 E03, spi0_ss_mosi, NA, NA */ +/* 30 D03, spi0_ss_sck, NA, NA */ +/* 31 D04, spi0_ss_cs0, NA, NA */ +/* 32 C04, spi0_ss_cs1, NA, NA */ +/* 33 B04, spi0_ss_cs2, gpio_29, NA */ +/* 34 A04, spi0_ss_cs3, gpio_30, NA */ +/* 35 B05, spi1_ss_miso, NA, NA */ +/* 36 C05, spi1_ss_mosi, NA, NA */ +/* 37 D05, spi1_ss_sck, NA, NA */ +/* 38 E05, spi1_ss_cs0, NA, NA */ +/* 39 E04, spi1_ss_cs1, NA, NA */ +/* 40 A06, spi1_ss_cs2, uart0_cts, NA */ +/* 41 B06, spi1_ss_cs3, uart0_rts, NA */ +/* 42 C06, gpio_8, spi1_m_sck, NA */ /* IO13 */ +/* 43 D06, gpio_9, spi1_m_miso, NA */ /* IO12 */ +/* 44 E06, gpio_10, spi1_m_mosi, NA */ /* IO11 */ +/* 45 D07, gpio_11, spi1_m_cs0, NA */ +/* 46 C07, gpio_12, spi1_m_cs1, NA */ +/* 47 B07, gpio_13, spi1_m_cs2, NA */ +/* 48 A07, gpio_14, spi1_m_cs3, NA */ +/* 49 B08, gpio_15, i2s_rxd, NA */ /* IO5 */ +/* 50 A08, gpio_16, i2s_rscki, NA */ /* IO8 */ +/* 51 B09, gpio_17, i2s_rws, NA */ /* IO3 */ +/* 52 A09, gpio_18, i2s_tsck, NA */ /* IO2 */ +/* 53 C09, gpio_19, i2s_twsi, NA */ /* IO4 */ +/* 54 D09, gpio_20, i2s_txd, NA */ /* IO7 */ +/* 55 D08, gpio_21, spi0_m_sck, NA */ +/* 56 E07, gpio_22, spi0_m_miso, NA */ +/* 57 E09, gpio_23, spi0_m_mosi, NA */ +/* 58 E08, gpio_24, spi0_m_cs0, NA */ +/* 59 A10, gpio_25, spi0_m_cs1, NA */ +/* 60 B10, gpio_26, spi0_m_cs2, NA */ +/* 61 C10, gpio_27, spi0_m_cs3, NA */ +/* 62 D10, gpio_28, NA, NA */ +/* 63 E10, gpio_ss_10, pwm_0, NA */ /* IO3 */ +/* 64 D11, gpio_ss_11, pwm_1, NA */ /* IO5 */ +/* 65 C11, gpio_ss_12, pwm_2, NA */ /* IO6 */ +/* 66 B11, gpio_ss_13, pwm_3, NA */ /* IO9 */ +/* 67 D12, gpio_ss_14, clkout_32khz, NA */ +/* 68 C12, gpio_ss_15, clkout_16mhz, NA */ + +/* Note: + * 1. I2C pins on the shield are connected to i2c0_ss_sda and i2c_0_ss_scl, + * which are on the sensor subsystem. They are also tied to AD4 and AD5. + * Therefore, to use I2C, pin 9 (ain_9) and pin 14 (ain_14) both need to be set + * to PINMUX_FUNC_B, so they will not interfere with I2C operations. + * Also, there is no internal pull-up on I2c bus, and thus external + * pull-up resistors are needed. + * 2. IO3/PWM0 is connected to pin 51 and 63. + * 3. IO5/PWM1 is connected to pin 49 and 64. + */ + +/* + * On the QUARK_SE platform there are a minimum of 69 pins that can be possibly + * set. This would be a total of 5 registers to store the configuration as per + * the bit description from above + */ +#define PINMUX_MAX_REGISTERS 5 + +static void _pinmux_defaults(uint32_t base) +{ + uint32_t mux_config[PINMUX_MAX_REGISTERS] = { 0, 0, 0, 0, 0 }; + int i = 0; + +#if !defined(CONFIG_SPI_1) && !defined(CONFIG_SPI_CS_GPIO) + PIN_CONFIG(mux_config, 0, PINMUX_FUNC_B); +#endif + PIN_CONFIG(mux_config, 1, PINMUX_FUNC_B); + PIN_CONFIG(mux_config, 2, PINMUX_FUNC_B); + PIN_CONFIG(mux_config, 3, PINMUX_FUNC_B); + PIN_CONFIG(mux_config, 4, PINMUX_FUNC_B); + PIN_CONFIG(mux_config, 5, PINMUX_FUNC_B); + PIN_CONFIG(mux_config, 7, PINMUX_FUNC_B); + PIN_CONFIG(mux_config, 8, PINMUX_FUNC_C); + PIN_CONFIG(mux_config, 9, PINMUX_FUNC_B); + PIN_CONFIG(mux_config, 14, PINMUX_FUNC_B); + PIN_CONFIG(mux_config, 16, PINMUX_FUNC_C); + PIN_CONFIG(mux_config, 17, PINMUX_FUNC_C); + PIN_CONFIG(mux_config, 40, PINMUX_FUNC_B); + PIN_CONFIG(mux_config, 41, PINMUX_FUNC_B); +#ifdef CONFIG_SPI_1 + PIN_CONFIG(mux_config, 42, PINMUX_FUNC_B); + PIN_CONFIG(mux_config, 43, PINMUX_FUNC_B); + PIN_CONFIG(mux_config, 44, PINMUX_FUNC_B); +#ifndef CONFIG_SPI_CS_GPIO + PIN_CONFIG(mux_config, 45, PINMUX_FUNC_B); +#endif +#endif + PIN_CONFIG(mux_config, 55, PINMUX_FUNC_B); + PIN_CONFIG(mux_config, 56, PINMUX_FUNC_B); + PIN_CONFIG(mux_config, 57, PINMUX_FUNC_B); + PIN_CONFIG(mux_config, 63, PINMUX_FUNC_B); + PIN_CONFIG(mux_config, 64, PINMUX_FUNC_B); + PIN_CONFIG(mux_config, 65, PINMUX_FUNC_B); + PIN_CONFIG(mux_config, 66, PINMUX_FUNC_B); + + for (i = 0; i < PINMUX_MAX_REGISTERS; i++) { + sys_write32(mux_config[i], PINMUX_SELECT_REGISTER(base, i)); + } +} + +static inline void _pinmux_pullups(uint32_t base_address) +{ + _quark_mcu_set_mux(base_address + PINMUX_PULLUP_OFFSET, 104, + PINMUX_PULLUP_ENABLE); +} + +static int pinmux_initialize(struct device *port) +{ + ARG_UNUSED(port); + + _pinmux_defaults(PINMUX_BASE_ADDR); + _pinmux_pullups(PINMUX_BASE_ADDR); + + return 0; +} + +SYS_INIT(pinmux_initialize, POST_KERNEL, CONFIG_KERNEL_INIT_PRIORITY_DEFAULT); diff --git a/pool/shard010/C/0138130_child.c b/pool/shard010/C/0138130_child.c new file mode 100644 index 0000000000000000000000000000000000000000..ad6db09ebb22b15446a37d795f149bbdd887bea9 --- /dev/null +++ b/pool/shard010/C/0138130_child.c @@ -0,0 +1,23 @@ +#include +#include +#include + +int main(void) +{ + char buf[1]; + int rc; + + buf[0] = 0; + rc = write(1, buf, sizeof buf); + if (rc < 0) { + perror("write"); + exit(-1); + } + rc = read(0, buf, sizeof buf); + if (rc < 0) { + perror("read"); + exit(-1); + } + exit(0); +} + diff --git a/pool/shard010/C/0138131_cptsvx.c b/pool/shard010/C/0138131_cptsvx.c new file mode 100644 index 0000000000000000000000000000000000000000..f89f65e4229d89d40b0a0ac8cbf6f43249fd3947 --- /dev/null +++ b/pool/shard010/C/0138131_cptsvx.c @@ -0,0 +1,251 @@ +/* cptsvx.f -- translated by f2c (version 20061008). + You must link the resulting object file with libf2c: + on Microsoft Windows system, link with libf2c.lib; + on Linux or Unix systems, link with .../path/to/libf2c.a -lm + or, if you install libf2c.a in a standard place, with -lf2c -lm + -- in that order, at the end of the command line, as in + cc *.o -lf2c -lm + Source for libf2c is in /netlib/f2c/libf2c.zip, e.g., + + http://www.netlib.org/f2c/libf2c.zip +*/ + +#include "f2c.h" +#include "blaswrap.h" + +/* Table of constant values */ + +static integer c__1 = 1; + +/* Subroutine */ int cptsvx_(char *fact, integer *n, integer *nrhs, real *d__, + complex *e, real *df, complex *ef, complex *b, integer *ldb, complex + *x, integer *ldx, real *rcond, real *ferr, real *berr, complex *work, + real *rwork, integer *info) +{ + /* System generated locals */ + integer b_dim1, b_offset, x_dim1, x_offset, i__1; + + /* Local variables */ + real anorm; + logical nofact; + +/* -- LAPACK routine (version 3.2) -- */ +/* November 2006 */ + +/* Purpose */ +/* ======= */ + +/* CPTSVX uses the factorization A = L*D*L**H to compute the solution */ +/* to a complex system of linear equations A*X = B, where A is an */ +/* N-by-N Hermitian positive definite tridiagonal matrix and X and B */ +/* are N-by-NRHS matrices. */ + +/* Error bounds on the solution and a condition estimate are also */ +/* provided. */ + +/* Description */ +/* =========== */ + +/* The following steps are performed: */ + +/* 1. If FACT = 'N', the matrix A is factored as A = L*D*L**H, where L */ +/* is a unit lower bidiagonal matrix and D is diagonal. The */ +/* factorization can also be regarded as having the form */ +/* A = U**H*D*U. */ + +/* 2. If the leading i-by-i principal minor is not positive definite, */ +/* then the routine returns with INFO = i. Otherwise, the factored */ +/* form of A is used to estimate the condition number of the matrix */ +/* A. If the reciprocal of the condition number is less than machine */ +/* precision, INFO = N+1 is returned as a warning, but the routine */ +/* still goes on to solve for X and compute error bounds as */ +/* described below. */ + +/* 3. The system of equations is solved for X using the factored form */ +/* of A. */ + +/* 4. Iterative refinement is applied to improve the computed solution */ +/* matrix and calculate error bounds and backward error estimates */ +/* for it. */ + +/* Arguments */ +/* ========= */ + +/* FACT (input) CHARACTER*1 */ +/* Specifies whether or not the factored form of the matrix */ +/* A is supplied on entry. */ +/* = 'F': On entry, DF and EF contain the factored form of A. */ +/* D, E, DF, and EF will not be modified. */ +/* = 'N': The matrix A will be copied to DF and EF and */ +/* factored. */ + +/* N (input) INTEGER */ +/* The order of the matrix A. N >= 0. */ + +/* NRHS (input) INTEGER */ +/* The number of right hand sides, i.e., the number of columns */ +/* of the matrices B and X. NRHS >= 0. */ + +/* D (input) REAL array, dimension (N) */ +/* The n diagonal elements of the tridiagonal matrix A. */ + +/* E (input) COMPLEX array, dimension (N-1) */ +/* The (n-1) subdiagonal elements of the tridiagonal matrix A. */ + +/* DF (input or output) REAL array, dimension (N) */ +/* If FACT = 'F', then DF is an input argument and on entry */ +/* contains the n diagonal elements of the diagonal matrix D */ +/* from the L*D*L**H factorization of A. */ +/* If FACT = 'N', then DF is an output argument and on exit */ +/* contains the n diagonal elements of the diagonal matrix D */ +/* from the L*D*L**H factorization of A. */ + +/* EF (input or output) COMPLEX array, dimension (N-1) */ +/* If FACT = 'F', then EF is an input argument and on entry */ +/* contains the (n-1) subdiagonal elements of the unit */ +/* bidiagonal factor L from the L*D*L**H factorization of A. */ +/* If FACT = 'N', then EF is an output argument and on exit */ +/* contains the (n-1) subdiagonal elements of the unit */ +/* bidiagonal factor L from the L*D*L**H factorization of A. */ + +/* B (input) COMPLEX array, dimension (LDB,NRHS) */ +/* The N-by-NRHS right hand side matrix B. */ + +/* LDB (input) INTEGER */ +/* The leading dimension of the array B. LDB >= max(1,N). */ + +/* X (output) COMPLEX array, dimension (LDX,NRHS) */ +/* If INFO = 0 or INFO = N+1, the N-by-NRHS solution matrix X. */ + +/* LDX (input) INTEGER */ +/* The leading dimension of the array X. LDX >= max(1,N). */ + +/* RCOND (output) REAL */ +/* The reciprocal condition number of the matrix A. If RCOND */ +/* is less than the machine precision (in particular, if */ +/* RCOND = 0), the matrix is singular to working precision. */ +/* This condition is indicated by a return code of INFO > 0. */ + +/* FERR (output) REAL array, dimension (NRHS) */ +/* The forward error bound for each solution vector */ +/* X(j) (the j-th column of the solution matrix X). */ +/* If XTRUE is the true solution corresponding to X(j), FERR(j) */ +/* is an estimated upper bound for the magnitude of the largest */ +/* element in (X(j) - XTRUE) divided by the magnitude of the */ +/* largest element in X(j). */ + +/* BERR (output) REAL array, dimension (NRHS) */ +/* The componentwise relative backward error of each solution */ +/* vector X(j) (i.e., the smallest relative change in any */ +/* element of A or B that makes X(j) an exact solution). */ + +/* WORK (workspace) COMPLEX array, dimension (N) */ + +/* RWORK (workspace) REAL array, dimension (N) */ + +/* INFO (output) INTEGER */ +/* = 0: successful exit */ +/* < 0: if INFO = -i, the i-th argument had an illegal value */ +/* > 0: if INFO = i, and i is */ +/* <= N: the leading minor of order i of A is */ +/* not positive definite, so the factorization */ +/* could not be completed, and the solution has not */ +/* been computed. RCOND = 0 is returned. */ +/* = N+1: U is nonsingular, but RCOND is less than machine */ +/* precision, meaning that the matrix is singular */ +/* to working precision. Nevertheless, the */ +/* solution and error bounds are computed because */ +/* there are a number of situations where the */ +/* computed solution can be more accurate than the */ +/* value of RCOND would suggest. */ + +/* ===================================================================== */ + +/* Test the input parameters. */ + + /* Parameter adjustments */ + --d__; + --e; + --df; + --ef; + b_dim1 = *ldb; + b_offset = 1 + b_dim1; + b -= b_offset; + x_dim1 = *ldx; + x_offset = 1 + x_dim1; + x -= x_offset; + --ferr; + --berr; + --work; + --rwork; + + /* Function Body */ + *info = 0; + nofact = lsame_(fact, "N"); + if (! nofact && ! lsame_(fact, "F")) { + *info = -1; + } else if (*n < 0) { + *info = -2; + } else if (*nrhs < 0) { + *info = -3; + } else if (*ldb < max(1,*n)) { + *info = -9; + } else if (*ldx < max(1,*n)) { + *info = -11; + } + if (*info != 0) { + i__1 = -(*info); + xerbla_("CPTSVX", &i__1); + return 0; + } + + if (nofact) { + +/* Compute the L*D*L' (or U'*D*U) factorization of A. */ + + scopy_(n, &d__[1], &c__1, &df[1], &c__1); + if (*n > 1) { + i__1 = *n - 1; + ccopy_(&i__1, &e[1], &c__1, &ef[1], &c__1); + } + cpttrf_(n, &df[1], &ef[1], info); + +/* Return if INFO is non-zero. */ + + if (*info > 0) { + *rcond = 0.f; + return 0; + } + } + +/* Compute the norm of the matrix A. */ + + anorm = clanht_("1", n, &d__[1], &e[1]); + +/* Compute the reciprocal of the condition number of A. */ + + cptcon_(n, &df[1], &ef[1], &anorm, rcond, &rwork[1], info); + +/* Compute the solution vectors X. */ + + clacpy_("Full", n, nrhs, &b[b_offset], ldb, &x[x_offset], ldx); + cpttrs_("Lower", n, nrhs, &df[1], &ef[1], &x[x_offset], ldx, info); + +/* Use iterative refinement to improve the computed solutions and */ +/* compute error bounds and backward error estimates for them. */ + + cptrfs_("Lower", n, nrhs, &d__[1], &e[1], &df[1], &ef[1], &b[b_offset], + ldb, &x[x_offset], ldx, &ferr[1], &berr[1], &work[1], &rwork[1], + info); + +/* Set INFO = N+1 if the matrix is singular to working precision. */ + + if (*rcond < slamch_("Epsilon")) { + *info = *n + 1; + } + + return 0; + +/* End of CPTSVX */ + +} /* cptsvx_ */ diff --git a/pool/shard010/C/0138132_qsort.c b/pool/shard010/C/0138132_qsort.c new file mode 100644 index 0000000000000000000000000000000000000000..48c48aeb404aa59394bf475b5dcfd9edec731ea0 --- /dev/null +++ b/pool/shard010/C/0138132_qsort.c @@ -0,0 +1,235 @@ +/* qsort.c: Plug-compatible replacement for UNIX qsort. + * Copyright (C) 1989 Free Software Foundation, Inc. + * Written by Douglas C. Schmidt (schmidt@ics.uci.edu) */ +/* +This file is part of GNU CC. + +GNU QSORT 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, or (at your option) +any later version. + +GNU QSORT 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 GNU QSORT; see the file COPYING. If not, write to +the Free Software Foundation, Inc., 59 Temple Place - Suite 330, +Boston, MA 02111-1307, USA. */ + +#if defined(sparc) || defined(HAVE_ALLOCA_H) || (defined(__APPLE__) && defined(__GNUC__)) +# include +#endif /* sparc || HAVE_ALLOCA_H || (__APPLE__ && __GNUC__) */ + +/* cannot include because that could have a conflicting + * declaration for qsort() in it. + * Instead, keep the prototype here: */ +extern int qsort(char *base_ptr, int total_elems, int size, + int (*cmp)(const void *, const void *)); + +/* Invoke the comparison function, returns either 0, < 0, or > 0: */ +#define CMP(A,B) ((*cmp)((A),(B))) + +/* Byte-wise swap two items of size SIZE: */ +#define SWAP(A,B,SIZE) do {int sz = (SIZE); char *a = (A); char *b = (B); \ + do { char _temp = *a;*a++ = *b;*b++ = _temp;} while (--sz);} while (0) + +/* Copy SIZE bytes from item B to item A: */ +#define COPY(A,B,SIZE) {int sz = (SIZE); do { *(A)++ = *(B)++; } while (--sz); } + +/* This should be replaced by a standard ANSI macro: */ +#define BYTES_PER_WORD 8 + +/* The next 4 #defines implement a very fast in-line stack abstraction: */ +#define STACK_SIZE (BYTES_PER_WORD * sizeof(long)) +#define PUSH(LOW,HIGH) do {top->lo = LOW;top++->hi = HIGH;} while (0) +#define POP(LOW,HIGH) do {LOW = (--top)->lo;HIGH = top->hi;} while (0) +#define STACK_NOT_EMPTY (stack < top) + +/* Discontinue quicksort algorithm when partition gets below this size. + * This particular magic number was chosen to work best on a Sun 4/260. */ +#define MAX_THRESH 4 + +/* Stack node declarations used to store unfulfilled partition obligations: */ +typedef struct +{ + char *lo; + char *hi; +} stack_node; + +/* Order size using quicksort. This implementation incorporates + four optimizations discussed in Sedgewick: + + 1. Non-recursive, using an explicit stack of pointer that store the + next array partition to sort. To save time, this maximum amount + of space required to store an array of MAX_INT is allocated on the + stack. Assuming a 32-bit integer, this needs only 32 * + sizeof (stack_node) == 136 bits. Pretty cheap, actually. + + 2. Chose the pivot element using a median-of-three decision tree. + This reduces the probability of selecting a bad pivot value and + eliminates certain extraneous comparisons. + + 3. Only quicksorts TOTAL_ELEMS / MAX_THRESH partitions, leaving + insertion sort to order the MAX_THRESH items within each partition. + This is a big win, since insertion sort is faster for small, mostly + sorted array segments. + + 4. The larger of the two sub-partitions is always pushed onto the + stack first, with the algorithm then concentrating on the + smaller partition. This *guarantees* no more than log (n) + stack size is needed (actually O(1) in this case)! */ + +int +qsort(char *base_ptr, int total_elems, int size, + int (*cmp)(const void *, const void *)) +{ + /* Allocating SIZE bytes for a pivot buffer facilitates a better + * algorithm below since we can do comparisons directly on the pivot: */ + char *pivot_buffer = (char *)alloca(size); + int max_thresh = (MAX_THRESH * size); + + if (total_elems > MAX_THRESH) + { + char *lo = base_ptr; + char *hi = (lo + size * (total_elems - 1)); + stack_node stack[STACK_SIZE]; /* Largest size needed for 32bit int */ + stack_node *top = (stack + 1); + + while (STACK_NOT_EMPTY) + { + char *left_ptr; + char *right_ptr; + { + char *pivot = pivot_buffer; + { + /* Select median value from among LO, MID, and HI. Rearrange + LO and HI so the three values are sorted. This lowers the + probability of picking a pathological pivot value and + skips a comparison for both the LEFT_PTR and RIGHT_PTR. */ + + char *mid = (lo + size * ((hi - lo) / size >> 1)); + + if (CMP(mid, lo) < 0) + SWAP(mid, lo, size); + if (CMP(hi, mid) < 0) + SWAP(mid, hi, size); + else + goto jump_over; + if (CMP(mid, lo) < 0) + SWAP(mid, lo, size); + jump_over: + COPY(pivot, mid, size); + pivot = pivot_buffer; + } + left_ptr = (lo + size); + right_ptr = (hi - size); + + /* Here is the famous `collapse the walls' part of quicksort. + * Gotta like those tight inner loops! They are the main + * reason that this algorithm runs much faster than others: */ + do { + while (CMP(left_ptr, pivot) < 0) + left_ptr += size; + + while (CMP(pivot, right_ptr) < 0) + right_ptr -= size; + + if (left_ptr < right_ptr) + { + SWAP(left_ptr, right_ptr, size); + left_ptr += size; + right_ptr -= size; + } + else if (left_ptr == right_ptr) + { + left_ptr += size; + right_ptr -= size; + break; + } + } while (left_ptr <= right_ptr); + + } + + /* Set up pointers for next iteration. First determine whether + left and right partitions are below the threshold size. If so, + ignore one or both. Otherwise, push the larger partition's + bounds on the stack and continue sorting the smaller one. */ + + if ((right_ptr - lo) <= max_thresh) + { + if ((hi - left_ptr) <= max_thresh) /* Ignore both small partitions. */ + POP(lo, hi); + else /* Ignore small left partition. */ + lo = left_ptr; + } + else if ((hi - left_ptr) <= max_thresh) /* Ignore small right partition. */ + hi = right_ptr; + else if ((right_ptr - lo) > (hi - left_ptr)) /* Push larger left partition indices. */ + { + PUSH (lo, right_ptr); + lo = left_ptr; + } + else /* Push larger right partition indices. */ + { + PUSH(left_ptr, hi); + hi = right_ptr; + } + } + } + + /* Once the BASE_PTR array is partially sorted by quicksort the rest + is completely sorted using insertion sort, since this is efficient + for partitions below MAX_THRESH size. BASE_PTR points to the beginning + of the array to sort, and END_PTR points at the very last element in + the array (*not* one beyond it!). */ + +#define MIN(X,Y) ((X) < (Y) ? (X) : (Y)) + + { + char *end_ptr = (base_ptr + size * (total_elems - 1)); + char *run_ptr; + char *tmp_ptr = base_ptr; + char *thresh = MIN(end_ptr, base_ptr + max_thresh); + + /* Find smallest element in first threshold and place it at the + * array's beginning. This is the smallest array element, + * and the operation speeds up insertion sort's inner loop: */ + for (run_ptr = (tmp_ptr + size); run_ptr <= thresh; run_ptr += size) + if (CMP(run_ptr, tmp_ptr) < 0) + tmp_ptr = run_ptr; + + if (tmp_ptr != base_ptr) + SWAP(tmp_ptr, base_ptr, size); + + /* Insertion sort, running from left-hand-side up to `right-hand-side.' + * Pretty much straight out of the original GNU qsort routine: */ + for (run_ptr = (base_ptr + size); (tmp_ptr = run_ptr += size) <= end_ptr; ) + { + + while (CMP(run_ptr, tmp_ptr -= size) < 0) + ; + + if ((tmp_ptr += size) != run_ptr) + { + char *trav; + + for (trav = (run_ptr + size); --trav >= run_ptr;) + { + char c = *trav; + char *hi, *lo; + + for (hi = lo = trav; (lo -= size) >= tmp_ptr; hi = lo) + *hi = *lo; + *hi = c; + } + } + + } + } + return 1; +} + +/* EOF */ diff --git a/pool/shard010/C/0138133_process.c b/pool/shard010/C/0138133_process.c new file mode 100644 index 0000000000000000000000000000000000000000..ea3d83b6fb62d7e25adfe83376f003c1885099a7 --- /dev/null +++ b/pool/shard010/C/0138133_process.c @@ -0,0 +1,299 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +/* + * PARISC Architecture-dependent parts of process handling + * based on the work for i386 + * + * Copyright (C) 1999-2003 Matthew Wilcox + * Copyright (C) 2000 Martin K Petersen + * Copyright (C) 2000 John Marvin + * Copyright (C) 2000 David Huggins-Daines + * Copyright (C) 2000-2003 Paul Bame + * Copyright (C) 2000 Philipp Rumpf + * Copyright (C) 2000 David Kennedy + * Copyright (C) 2000 Richard Hirst + * Copyright (C) 2000 Grant Grundler + * Copyright (C) 2001 Alan Modra + * Copyright (C) 2001-2002 Ryan Bradetich + * Copyright (C) 2001-2014 Helge Deller + * Copyright (C) 2002 Randolph Chung + */ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +#define COMMAND_GLOBAL F_EXTEND(0xfffe0030) +#define CMD_RESET 5 /* reset any module */ + +/* +** The Wright Brothers and Gecko systems have a H/W problem +** (Lasi...'nuf said) may cause a broadcast reset to lockup +** the system. An HVERSION dependent PDC call was developed +** to perform a "safe", platform specific broadcast reset instead +** of kludging up all the code. +** +** Older machines which do not implement PDC_BROADCAST_RESET will +** return (with an error) and the regular broadcast reset can be +** issued. Obviously, if the PDC does implement PDC_BROADCAST_RESET +** the PDC call will not return (the system will be reset). +*/ +void machine_restart(char *cmd) +{ +#ifdef FASTBOOT_SELFTEST_SUPPORT + /* + ** If user has modified the Firmware Selftest Bitmap, + ** run the tests specified in the bitmap after the + ** system is rebooted w/PDC_DO_RESET. + ** + ** ftc_bitmap = 0x1AUL "Skip destructive memory tests" + ** + ** Using "directed resets" at each processor with the MEM_TOC + ** vector cleared will also avoid running destructive + ** memory self tests. (Not implemented yet) + */ + if (ftc_bitmap) { + pdc_do_firm_test_reset(ftc_bitmap); + } +#endif + /* set up a new led state on systems shipped with a LED State panel */ + pdc_chassis_send_status(PDC_CHASSIS_DIRECT_SHUTDOWN); + + /* "Normal" system reset */ + pdc_do_reset(); + + /* Nope...box should reset with just CMD_RESET now */ + gsc_writel(CMD_RESET, COMMAND_GLOBAL); + + /* Wait for RESET to lay us to rest. */ + while (1) ; + +} + +void (*chassis_power_off)(void); + +/* + * This routine is called from sys_reboot to actually turn off the + * machine + */ +void machine_power_off(void) +{ + /* If there is a registered power off handler, call it. */ + if (chassis_power_off) + chassis_power_off(); + + /* Put the soft power button back under hardware control. + * If the user had already pressed the power button, the + * following call will immediately power off. */ + pdc_soft_power_button(0); + + pdc_chassis_send_status(PDC_CHASSIS_DIRECT_SHUTDOWN); + + /* ipmi_poweroff may have been installed. */ + if (pm_power_off) + pm_power_off(); + + /* It seems we have no way to power the system off via + * software. The user has to press the button himself. */ + + printk(KERN_EMERG "System shut down completed.\n" + "Please power this system off now."); + + /* prevent soft lockup/stalled CPU messages for endless loop. */ + rcu_sysrq_start(); + lockup_detector_soft_poweroff(); + for (;;); +} + +void (*pm_power_off)(void); +EXPORT_SYMBOL(pm_power_off); + +void machine_halt(void) +{ + machine_power_off(); +} + +void flush_thread(void) +{ + /* Only needs to handle fpu stuff or perf monitors. + ** REVISIT: several arches implement a "lazy fpu state". + */ +} + +void release_thread(struct task_struct *dead_task) +{ +} + +/* + * Idle thread support + * + * Detect when running on QEMU with SeaBIOS PDC Firmware and let + * QEMU idle the host too. + */ + +int running_on_qemu __ro_after_init; +EXPORT_SYMBOL(running_on_qemu); + +void __cpuidle arch_cpu_idle_dead(void) +{ + /* nop on real hardware, qemu will offline CPU. */ + asm volatile("or %%r31,%%r31,%%r31\n":::); +} + +void __cpuidle arch_cpu_idle(void) +{ + raw_local_irq_enable(); + + /* nop on real hardware, qemu will idle sleep. */ + asm volatile("or %%r10,%%r10,%%r10\n":::); +} + +static int __init parisc_idle_init(void) +{ + if (!running_on_qemu) + cpu_idle_poll_ctrl(1); + + return 0; +} +arch_initcall(parisc_idle_init); + +/* + * Copy architecture-specific thread state + */ +int +copy_thread(unsigned long clone_flags, unsigned long usp, + unsigned long kthread_arg, struct task_struct *p, unsigned long tls) +{ + struct pt_regs *cregs = &(p->thread.regs); + void *stack = task_stack_page(p); + + /* We have to use void * instead of a function pointer, because + * function pointers aren't a pointer to the function on 64-bit. + * Make them const so the compiler knows they live in .text */ + extern void * const ret_from_kernel_thread; + extern void * const child_return; + + if (unlikely(p->flags & (PF_KTHREAD | PF_IO_WORKER))) { + /* kernel thread */ + memset(cregs, 0, sizeof(struct pt_regs)); + if (!usp) /* idle thread */ + return 0; + /* Must exit via ret_from_kernel_thread in order + * to call schedule_tail() + */ + cregs->ksp = (unsigned long) stack + FRAME_SIZE + PT_SZ_ALGN; + cregs->kpc = (unsigned long) &ret_from_kernel_thread; + /* + * Copy function and argument to be called from + * ret_from_kernel_thread. + */ +#ifdef CONFIG_64BIT + cregs->gr[27] = ((unsigned long *)usp)[3]; + cregs->gr[26] = ((unsigned long *)usp)[2]; +#else + cregs->gr[26] = usp; +#endif + cregs->gr[25] = kthread_arg; + } else { + /* user thread */ + /* usp must be word aligned. This also prevents users from + * passing in the value 1 (which is the signal for a special + * return for a kernel thread) */ + if (usp) { + usp = ALIGN(usp, 4); + if (likely(usp)) + cregs->gr[30] = usp; + } + cregs->ksp = (unsigned long) stack + FRAME_SIZE; + cregs->kpc = (unsigned long) &child_return; + + /* Setup thread TLS area */ + if (clone_flags & CLONE_SETTLS) + cregs->cr27 = tls; + } + + return 0; +} + +unsigned long +__get_wchan(struct task_struct *p) +{ + struct unwind_frame_info info; + unsigned long ip; + int count = 0; + + /* + * These bracket the sleeping functions.. + */ + + unwind_frame_init_from_blocked_task(&info, p); + do { + if (unwind_once(&info) < 0) + return 0; + if (task_is_running(p)) + return 0; + ip = info.ip; + if (!in_sched_functions(ip)) + return ip; + } while (count++ < MAX_UNWIND_ENTRIES); + return 0; +} + +#ifdef CONFIG_64BIT +void *dereference_function_descriptor(void *ptr) +{ + Elf64_Fdesc *desc = ptr; + void *p; + + if (!get_kernel_nofault(p, (void *)&desc->addr)) + ptr = p; + return ptr; +} + +void *dereference_kernel_function_descriptor(void *ptr) +{ + if (ptr < (void *)__start_opd || + ptr >= (void *)__end_opd) + return ptr; + + return dereference_function_descriptor(ptr); +} +#endif + +static inline unsigned long brk_rnd(void) +{ + return (get_random_int() & BRK_RND_MASK) << PAGE_SHIFT; +} + +unsigned long arch_randomize_brk(struct mm_struct *mm) +{ + unsigned long ret = PAGE_ALIGN(mm->brk + brk_rnd()); + + if (ret < mm->brk) + return mm->brk; + return ret; +} diff --git a/pool/shard010/C/0138134_dpio-driver.c b/pool/shard010/C/0138134_dpio-driver.c new file mode 100644 index 0000000000000000000000000000000000000000..b8479ef64c71a3c676939fb1f856464aa060a420 --- /dev/null +++ b/pool/shard010/C/0138134_dpio-driver.c @@ -0,0 +1,271 @@ +// SPDX-License-Identifier: (GPL-2.0+ OR BSD-3-Clause) +/* + * Copyright 2014-2016 Freescale Semiconductor Inc. + * Copyright NXP 2016 + * + */ + +#include +#include +#include +#include +#include +#include +#include +#include + +#include "../../include/mc.h" +#include "../../include/dpaa2-io.h" + +#include "qbman-portal.h" +#include "dpio.h" +#include "dpio-cmd.h" + +MODULE_LICENSE("Dual BSD/GPL"); +MODULE_AUTHOR("Freescale Semiconductor, Inc"); +MODULE_DESCRIPTION("DPIO Driver"); + +struct dpio_priv { + struct dpaa2_io *io; +}; + +static irqreturn_t dpio_irq_handler(int irq_num, void *arg) +{ + struct device *dev = (struct device *)arg; + struct dpio_priv *priv = dev_get_drvdata(dev); + + return dpaa2_io_irq(priv->io); +} + +static void unregister_dpio_irq_handlers(struct fsl_mc_device *dpio_dev) +{ + struct fsl_mc_device_irq *irq; + + irq = dpio_dev->irqs[0]; + + /* clear the affinity hint */ + irq_set_affinity_hint(irq->msi_desc->irq, NULL); +} + +static int register_dpio_irq_handlers(struct fsl_mc_device *dpio_dev, int cpu) +{ + struct dpio_priv *priv; + int error; + struct fsl_mc_device_irq *irq; + cpumask_t mask; + + priv = dev_get_drvdata(&dpio_dev->dev); + + irq = dpio_dev->irqs[0]; + error = devm_request_irq(&dpio_dev->dev, + irq->msi_desc->irq, + dpio_irq_handler, + 0, + dev_name(&dpio_dev->dev), + &dpio_dev->dev); + if (error < 0) { + dev_err(&dpio_dev->dev, + "devm_request_irq() failed: %d\n", + error); + return error; + } + + /* set the affinity hint */ + cpumask_clear(&mask); + cpumask_set_cpu(cpu, &mask); + if (irq_set_affinity_hint(irq->msi_desc->irq, &mask)) + dev_err(&dpio_dev->dev, + "irq_set_affinity failed irq %d cpu %d\n", + irq->msi_desc->irq, cpu); + + return 0; +} + +static int dpaa2_dpio_probe(struct fsl_mc_device *dpio_dev) +{ + struct dpio_attr dpio_attrs; + struct dpaa2_io_desc desc; + struct dpio_priv *priv; + int err = -ENOMEM; + struct device *dev = &dpio_dev->dev; + static int next_cpu = -1; + + priv = devm_kzalloc(dev, sizeof(*priv), GFP_KERNEL); + if (!priv) + goto err_priv_alloc; + + dev_set_drvdata(dev, priv); + + err = fsl_mc_portal_allocate(dpio_dev, 0, &dpio_dev->mc_io); + if (err) { + dev_dbg(dev, "MC portal allocation failed\n"); + err = -EPROBE_DEFER; + goto err_mcportal; + } + + err = dpio_open(dpio_dev->mc_io, 0, dpio_dev->obj_desc.id, + &dpio_dev->mc_handle); + if (err) { + dev_err(dev, "dpio_open() failed\n"); + goto err_open; + } + + err = dpio_get_attributes(dpio_dev->mc_io, 0, dpio_dev->mc_handle, + &dpio_attrs); + if (err) { + dev_err(dev, "dpio_get_attributes() failed %d\n", err); + goto err_get_attr; + } + desc.qman_version = dpio_attrs.qbman_version; + + err = dpio_enable(dpio_dev->mc_io, 0, dpio_dev->mc_handle); + if (err) { + dev_err(dev, "dpio_enable() failed %d\n", err); + goto err_get_attr; + } + + /* initialize DPIO descriptor */ + desc.receives_notifications = dpio_attrs.num_priorities ? 1 : 0; + desc.has_8prio = dpio_attrs.num_priorities == 8 ? 1 : 0; + desc.dpio_id = dpio_dev->obj_desc.id; + + /* get the cpu to use for the affinity hint */ + if (next_cpu == -1) + next_cpu = cpumask_first(cpu_online_mask); + else + next_cpu = cpumask_next(next_cpu, cpu_online_mask); + + if (!cpu_possible(next_cpu)) { + dev_err(dev, "probe failed. Number of DPIOs exceeds NR_CPUS.\n"); + err = -ERANGE; + goto err_allocate_irqs; + } + desc.cpu = next_cpu; + + /* + * Set the CENA regs to be the cache inhibited area of the portal to + * avoid coherency issues if a user migrates to another core. + */ + desc.regs_cena = ioremap_wc(dpio_dev->regions[1].start, + resource_size(&dpio_dev->regions[1])); + desc.regs_cinh = ioremap(dpio_dev->regions[1].start, + resource_size(&dpio_dev->regions[1])); + + err = fsl_mc_allocate_irqs(dpio_dev); + if (err) { + dev_err(dev, "fsl_mc_allocate_irqs failed. err=%d\n", err); + goto err_allocate_irqs; + } + + err = register_dpio_irq_handlers(dpio_dev, desc.cpu); + if (err) + goto err_register_dpio_irq; + + priv->io = dpaa2_io_create(&desc); + if (!priv->io) { + dev_err(dev, "dpaa2_io_create failed\n"); + goto err_dpaa2_io_create; + } + + dev_info(dev, "probed\n"); + dev_dbg(dev, " receives_notifications = %d\n", + desc.receives_notifications); + dpio_close(dpio_dev->mc_io, 0, dpio_dev->mc_handle); + fsl_mc_portal_free(dpio_dev->mc_io); + + return 0; + +err_dpaa2_io_create: + unregister_dpio_irq_handlers(dpio_dev); +err_register_dpio_irq: + fsl_mc_free_irqs(dpio_dev); +err_allocate_irqs: + dpio_disable(dpio_dev->mc_io, 0, dpio_dev->mc_handle); +err_get_attr: + dpio_close(dpio_dev->mc_io, 0, dpio_dev->mc_handle); +err_open: + fsl_mc_portal_free(dpio_dev->mc_io); +err_mcportal: + dev_set_drvdata(dev, NULL); +err_priv_alloc: + return err; +} + +/* Tear down interrupts for a given DPIO object */ +static void dpio_teardown_irqs(struct fsl_mc_device *dpio_dev) +{ + unregister_dpio_irq_handlers(dpio_dev); + fsl_mc_free_irqs(dpio_dev); +} + +static int dpaa2_dpio_remove(struct fsl_mc_device *dpio_dev) +{ + struct device *dev; + struct dpio_priv *priv; + int err; + + dev = &dpio_dev->dev; + priv = dev_get_drvdata(dev); + + dpaa2_io_down(priv->io); + + dpio_teardown_irqs(dpio_dev); + + err = fsl_mc_portal_allocate(dpio_dev, 0, &dpio_dev->mc_io); + if (err) { + dev_err(dev, "MC portal allocation failed\n"); + goto err_mcportal; + } + + err = dpio_open(dpio_dev->mc_io, 0, dpio_dev->obj_desc.id, + &dpio_dev->mc_handle); + if (err) { + dev_err(dev, "dpio_open() failed\n"); + goto err_open; + } + + dpio_disable(dpio_dev->mc_io, 0, dpio_dev->mc_handle); + + dpio_close(dpio_dev->mc_io, 0, dpio_dev->mc_handle); + + fsl_mc_portal_free(dpio_dev->mc_io); + + dev_set_drvdata(dev, NULL); + + return 0; + +err_open: + fsl_mc_portal_free(dpio_dev->mc_io); +err_mcportal: + return err; +} + +static const struct fsl_mc_device_id dpaa2_dpio_match_id_table[] = { + { + .vendor = FSL_MC_VENDOR_FREESCALE, + .obj_type = "dpio", + }, + { .vendor = 0x0 } +}; + +static struct fsl_mc_driver dpaa2_dpio_driver = { + .driver = { + .name = KBUILD_MODNAME, + .owner = THIS_MODULE, + }, + .probe = dpaa2_dpio_probe, + .remove = dpaa2_dpio_remove, + .match_id_table = dpaa2_dpio_match_id_table +}; + +static int dpio_driver_init(void) +{ + return fsl_mc_driver_register(&dpaa2_dpio_driver); +} + +static void dpio_driver_exit(void) +{ + fsl_mc_driver_unregister(&dpaa2_dpio_driver); +} +module_init(dpio_driver_init); +module_exit(dpio_driver_exit); diff --git a/pool/shard010/C/0138135_inet_pton.c b/pool/shard010/C/0138135_inet_pton.c new file mode 100644 index 0000000000000000000000000000000000000000..6cbf8cb2bdc1077f6c253d4cca00a948ae7a5d46 --- /dev/null +++ b/pool/shard010/C/0138135_inet_pton.c @@ -0,0 +1,257 @@ +/* inet_pton.c -- convert IPv4 and IPv6 addresses from text to binary form + + Copyright (C) 2006 Free Software Foundation, Inc. + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . */ + +/* + * Copyright (c) 1996,1999 by Internet Software Consortium. + * + * Permission to use, copy, modify, and distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND INTERNET SOFTWARE CONSORTIUM DISCLAIMS + * ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL INTERNET SOFTWARE + * CONSORTIUM BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL + * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR + * PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS + * ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS + * SOFTWARE. + */ + +#include + +/* Specification. */ +#include "inet_pton.h" + +#include +#include +#include + +#ifndef EAFNOSUPPORT +# define EAFNOSUPPORT EINVAL +#endif + +#define NS_INADDRSZ 4 +#define NS_IN6ADDRSZ 16 +#define NS_INT16SZ 2 + +/* + * WARNING: Don't even consider trying to compile this on a system where + * sizeof(int) < 4. sizeof(int) > 4 is fine; all the world's not a VAX. + */ + +static int inet_pton4 (const char *src, unsigned char *dst); +#if HAVE_IPV6 +static int inet_pton6 (const char *src, unsigned char *dst); +#endif + +/* int + * inet_pton(af, src, dst) + * convert from presentation format (which usually means ASCII printable) + * to network format (which is usually some kind of binary format). + * return: + * 1 if the address was valid for the specified address family + * 0 if the address wasn't valid (`dst' is untouched in this case) + * -1 if some other error occurred (`dst' is untouched in this case, too) + * author: + * Paul Vixie, 1996. + */ +int +inet_pton (int af, const char *restrict src, void *restrict dst) +{ + switch (af) + { + case AF_INET: + return (inet_pton4 (src, dst)); + +#if HAVE_IPV6 + case AF_INET6: + return (inet_pton6 (src, dst)); +#endif + + default: + errno = EAFNOSUPPORT; + return (-1); + } + /* NOTREACHED */ +} + +/* int + * inet_pton4(src, dst) + * like inet_aton() but without all the hexadecimal, octal (with the + * exception of 0) and shorthand. + * return: + * 1 if `src' is a valid dotted quad, else 0. + * notice: + * does not touch `dst' unless it's returning 1. + * author: + * Paul Vixie, 1996. + */ +static int +inet_pton4 (const char *restrict src, unsigned char *restrict dst) +{ + int saw_digit, octets, ch; + unsigned char tmp[NS_INADDRSZ], *tp; + + saw_digit = 0; + octets = 0; + *(tp = tmp) = 0; + while ((ch = *src++) != '\0') + { + + if (ch >= '0' && ch <= '9') + { + unsigned new = *tp * 10 + (ch - '0'); + + if (saw_digit && *tp == 0) + return (0); + if (new > 255) + return (0); + *tp = new; + if (!saw_digit) + { + if (++octets > 4) + return (0); + saw_digit = 1; + } + } + else if (ch == '.' && saw_digit) + { + if (octets == 4) + return (0); + *++tp = 0; + saw_digit = 0; + } + else + return (0); + } + if (octets < 4) + return (0); + memcpy (dst, tmp, NS_INADDRSZ); + return (1); +} + +#if HAVE_IPV6 + +/* int + * inet_pton6(src, dst) + * convert presentation level address to network order binary form. + * return: + * 1 if `src' is a valid [RFC1884 2.2] address, else 0. + * notice: + * (1) does not touch `dst' unless it's returning 1. + * (2) :: in a full address is silently ignored. + * credit: + * inspired by Mark Andrews. + * author: + * Paul Vixie, 1996. + */ +static int +inet_pton6 (const char *restrict src, unsigned char *restrict dst) +{ + static const char xdigits[] = "0123456789abcdef"; + unsigned char tmp[NS_IN6ADDRSZ], *tp, *endp, *colonp; + const char *curtok; + int ch, saw_xdigit; + unsigned val; + + tp = memset (tmp, '\0', NS_IN6ADDRSZ); + endp = tp + NS_IN6ADDRSZ; + colonp = NULL; + /* Leading :: requires some special handling. */ + if (*src == ':') + if (*++src != ':') + return (0); + curtok = src; + saw_xdigit = 0; + val = 0; + while ((ch = tolower (*src++)) != '\0') + { + const char *pch; + + pch = strchr (xdigits, ch); + if (pch != NULL) + { + val <<= 4; + val |= (pch - xdigits); + if (val > 0xffff) + return (0); + saw_xdigit = 1; + continue; + } + if (ch == ':') + { + curtok = src; + if (!saw_xdigit) + { + if (colonp) + return (0); + colonp = tp; + continue; + } + else if (*src == '\0') + { + return (0); + } + if (tp + NS_INT16SZ > endp) + return (0); + *tp++ = (u_char) (val >> 8) & 0xff; + *tp++ = (u_char) val & 0xff; + saw_xdigit = 0; + val = 0; + continue; + } + if (ch == '.' && ((tp + NS_INADDRSZ) <= endp) && + inet_pton4 (curtok, tp) > 0) + { + tp += NS_INADDRSZ; + saw_xdigit = 0; + break; /* '\0' was seen by inet_pton4(). */ + } + return (0); + } + if (saw_xdigit) + { + if (tp + NS_INT16SZ > endp) + return (0); + *tp++ = (u_char) (val >> 8) & 0xff; + *tp++ = (u_char) val & 0xff; + } + if (colonp != NULL) + { + /* + * Since some memmove()'s erroneously fail to handle + * overlapping regions, we'll do the shift by hand. + */ + const int n = tp - colonp; + int i; + + if (tp == endp) + return (0); + for (i = 1; i <= n; i++) + { + endp[-i] = colonp[n - i]; + colonp[n - i] = 0; + } + tp = endp; + } + if (tp != endp) + return (0); + memcpy (dst, tmp, NS_IN6ADDRSZ); + return (1); +} +#endif diff --git a/pool/shard010/C/0138136_timer.c b/pool/shard010/C/0138136_timer.c new file mode 100644 index 0000000000000000000000000000000000000000..12c7c19aa74b18c139c04787c8c988af0e3a5e20 --- /dev/null +++ b/pool/shard010/C/0138136_timer.c @@ -0,0 +1,298 @@ +/* + * This file contains driver for the Xilinx PS Timer Counter IP. + * + * Copyright (C) 2011 Xilinx + * + * based on arch/mips/kernel/time.c timer driver + * + * This software is licensed under the terms of the GNU General Public + * License version 2, as published by the Free Software Foundation, and + * may be copied, distributed, and modified under those terms. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + */ + +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include "common.h" + +#define IRQ_TIMERCOUNTER0 42 + +/* + * This driver configures the 2 16-bit count-up timers as follows: + * + * T1: Timer 1, clocksource for generic timekeeping + * T2: Timer 2, clockevent source for hrtimers + * T3: Timer 3, + * + * The input frequency to the timer module for emulation is 2.5MHz which is + * common to all the timer channels (T1, T2, and T3). With a pre-scaler of 32, + * the timers are clocked at 78.125KHz (12.8 us resolution). + * + * The input frequency to the timer module in silicon will be 200MHz. With the + * pre-scaler of 32, the timers are clocked at 6.25MHz (160ns resolution). + */ +#define XTTCPSS_CLOCKSOURCE 0 /* Timer 1 as a generic timekeeping */ +#define XTTCPSS_CLOCKEVENT 1 /* Timer 2 as a clock event */ + +#define XTTCPSS_TIMER_BASE TTC0_BASE +#define XTTCPCC_EVENT_TIMER_IRQ (IRQ_TIMERCOUNTER0 + 1) +/* + * Timer Register Offset Definitions of Timer 1, Increment base address by 4 + * and use same offsets for Timer 2 + */ +#define XTTCPSS_CLK_CNTRL_OFFSET 0x00 /* Clock Control Reg, RW */ +#define XTTCPSS_CNT_CNTRL_OFFSET 0x0C /* Counter Control Reg, RW */ +#define XTTCPSS_COUNT_VAL_OFFSET 0x18 /* Counter Value Reg, RO */ +#define XTTCPSS_INTR_VAL_OFFSET 0x24 /* Interval Count Reg, RW */ +#define XTTCPSS_MATCH_1_OFFSET 0x30 /* Match 1 Value Reg, RW */ +#define XTTCPSS_MATCH_2_OFFSET 0x3C /* Match 2 Value Reg, RW */ +#define XTTCPSS_MATCH_3_OFFSET 0x48 /* Match 3 Value Reg, RW */ +#define XTTCPSS_ISR_OFFSET 0x54 /* Interrupt Status Reg, RO */ +#define XTTCPSS_IER_OFFSET 0x60 /* Interrupt Enable Reg, RW */ + +#define XTTCPSS_CNT_CNTRL_DISABLE_MASK 0x1 + +/* Setup the timers to use pre-scaling */ + +#define TIMER_RATE (PERIPHERAL_CLOCK_RATE / 32) + +/** + * struct xttcpss_timer - This definition defines local timer structure + * + * @base_addr: Base address of timer + **/ +struct xttcpss_timer { + void __iomem *base_addr; +}; + +static struct xttcpss_timer timers[2]; +static struct clock_event_device xttcpss_clockevent; + +/** + * xttcpss_set_interval - Set the timer interval value + * + * @timer: Pointer to the timer instance + * @cycles: Timer interval ticks + **/ +static void xttcpss_set_interval(struct xttcpss_timer *timer, + unsigned long cycles) +{ + u32 ctrl_reg; + + /* Disable the counter, set the counter value and re-enable counter */ + ctrl_reg = __raw_readl(timer->base_addr + XTTCPSS_CNT_CNTRL_OFFSET); + ctrl_reg |= XTTCPSS_CNT_CNTRL_DISABLE_MASK; + __raw_writel(ctrl_reg, timer->base_addr + XTTCPSS_CNT_CNTRL_OFFSET); + + __raw_writel(cycles, timer->base_addr + XTTCPSS_INTR_VAL_OFFSET); + + /* Reset the counter (0x10) so that it starts from 0, one-shot + mode makes this needed for timing to be right. */ + ctrl_reg |= 0x10; + ctrl_reg &= ~XTTCPSS_CNT_CNTRL_DISABLE_MASK; + __raw_writel(ctrl_reg, timer->base_addr + XTTCPSS_CNT_CNTRL_OFFSET); +} + +/** + * xttcpss_clock_event_interrupt - Clock event timer interrupt handler + * + * @irq: IRQ number of the Timer + * @dev_id: void pointer to the xttcpss_timer instance + * + * returns: Always IRQ_HANDLED - success + **/ +static irqreturn_t xttcpss_clock_event_interrupt(int irq, void *dev_id) +{ + struct clock_event_device *evt = &xttcpss_clockevent; + struct xttcpss_timer *timer = dev_id; + + /* Acknowledge the interrupt and call event handler */ + __raw_writel(__raw_readl(timer->base_addr + XTTCPSS_ISR_OFFSET), + timer->base_addr + XTTCPSS_ISR_OFFSET); + + evt->event_handler(evt); + + return IRQ_HANDLED; +} + +static struct irqaction event_timer_irq = { + .name = "xttcpss clockevent", + .flags = IRQF_DISABLED | IRQF_TIMER, + .handler = xttcpss_clock_event_interrupt, +}; + +/** + * xttcpss_timer_hardware_init - Initialize the timer hardware + * + * Initialize the hardware to start the clock source, get the clock + * event timer ready to use, and hook up the interrupt. + **/ +static void __init xttcpss_timer_hardware_init(void) +{ + /* Setup the clock source counter to be an incrementing counter + * with no interrupt and it rolls over at 0xFFFF. Pre-scale + it by 32 also. Let it start running now. + */ + timers[XTTCPSS_CLOCKSOURCE].base_addr = XTTCPSS_TIMER_BASE; + + __raw_writel(0x0, timers[XTTCPSS_CLOCKSOURCE].base_addr + + XTTCPSS_IER_OFFSET); + __raw_writel(0x9, timers[XTTCPSS_CLOCKSOURCE].base_addr + + XTTCPSS_CLK_CNTRL_OFFSET); + __raw_writel(0x10, timers[XTTCPSS_CLOCKSOURCE].base_addr + + XTTCPSS_CNT_CNTRL_OFFSET); + + /* Setup the clock event timer to be an interval timer which + * is prescaled by 32 using the interval interrupt. Leave it + * disabled for now. + */ + + timers[XTTCPSS_CLOCKEVENT].base_addr = XTTCPSS_TIMER_BASE + 4; + + __raw_writel(0x23, timers[XTTCPSS_CLOCKEVENT].base_addr + + XTTCPSS_CNT_CNTRL_OFFSET); + __raw_writel(0x9, timers[XTTCPSS_CLOCKEVENT].base_addr + + XTTCPSS_CLK_CNTRL_OFFSET); + __raw_writel(0x1, timers[XTTCPSS_CLOCKEVENT].base_addr + + XTTCPSS_IER_OFFSET); + + /* Setup IRQ the clock event timer */ + event_timer_irq.dev_id = &timers[XTTCPSS_CLOCKEVENT]; + setup_irq(XTTCPCC_EVENT_TIMER_IRQ, &event_timer_irq); +} + +/** + * __raw_readl_cycles - Reads the timer counter register + * + * returns: Current timer counter register value + **/ +static cycle_t __raw_readl_cycles(struct clocksource *cs) +{ + struct xttcpss_timer *timer = &timers[XTTCPSS_CLOCKSOURCE]; + + return (cycle_t)__raw_readl(timer->base_addr + + XTTCPSS_COUNT_VAL_OFFSET); +} + + +/* + * Instantiate and initialize the clock source structure + */ +static struct clocksource clocksource_xttcpss = { + .name = "xttcpss_timer1", + .rating = 200, /* Reasonable clock source */ + .read = __raw_readl_cycles, + .mask = CLOCKSOURCE_MASK(16), + .flags = CLOCK_SOURCE_IS_CONTINUOUS, +}; + + +/** + * xttcpss_set_next_event - Sets the time interval for next event + * + * @cycles: Timer interval ticks + * @evt: Address of clock event instance + * + * returns: Always 0 - success + **/ +static int xttcpss_set_next_event(unsigned long cycles, + struct clock_event_device *evt) +{ + struct xttcpss_timer *timer = &timers[XTTCPSS_CLOCKEVENT]; + + xttcpss_set_interval(timer, cycles); + return 0; +} + +/** + * xttcpss_set_mode - Sets the mode of timer + * + * @mode: Mode to be set + * @evt: Address of clock event instance + **/ +static void xttcpss_set_mode(enum clock_event_mode mode, + struct clock_event_device *evt) +{ + struct xttcpss_timer *timer = &timers[XTTCPSS_CLOCKEVENT]; + u32 ctrl_reg; + + switch (mode) { + case CLOCK_EVT_MODE_PERIODIC: + xttcpss_set_interval(timer, TIMER_RATE / HZ); + break; + case CLOCK_EVT_MODE_ONESHOT: + case CLOCK_EVT_MODE_UNUSED: + case CLOCK_EVT_MODE_SHUTDOWN: + ctrl_reg = __raw_readl(timer->base_addr + + XTTCPSS_CNT_CNTRL_OFFSET); + ctrl_reg |= XTTCPSS_CNT_CNTRL_DISABLE_MASK; + __raw_writel(ctrl_reg, + timer->base_addr + XTTCPSS_CNT_CNTRL_OFFSET); + break; + case CLOCK_EVT_MODE_RESUME: + ctrl_reg = __raw_readl(timer->base_addr + + XTTCPSS_CNT_CNTRL_OFFSET); + ctrl_reg &= ~XTTCPSS_CNT_CNTRL_DISABLE_MASK; + __raw_writel(ctrl_reg, + timer->base_addr + XTTCPSS_CNT_CNTRL_OFFSET); + break; + } +} + +/* + * Instantiate and initialize the clock event structure + */ +static struct clock_event_device xttcpss_clockevent = { + .name = "xttcpss_timer2", + .features = CLOCK_EVT_FEAT_PERIODIC | CLOCK_EVT_FEAT_ONESHOT, + .set_next_event = xttcpss_set_next_event, + .set_mode = xttcpss_set_mode, + .rating = 200, +}; + +/** + * xttcpss_timer_init - Initialize the timer + * + * Initializes the timer hardware and register the clock source and clock event + * timers with Linux kernal timer framework + **/ +static void __init xttcpss_timer_init(void) +{ + xttcpss_timer_hardware_init(); + clocksource_register_hz(&clocksource_xttcpss, TIMER_RATE); + + /* Calculate the parameters to allow the clockevent to operate using + integer math + */ + clockevents_calc_mult_shift(&xttcpss_clockevent, TIMER_RATE, 4); + + xttcpss_clockevent.max_delta_ns = + clockevent_delta2ns(0xfffe, &xttcpss_clockevent); + xttcpss_clockevent.min_delta_ns = + clockevent_delta2ns(1, &xttcpss_clockevent); + + /* Indicate that clock event is on 1st CPU as SMP boot needs it */ + + xttcpss_clockevent.cpumask = cpumask_of(0); + clockevents_register_device(&xttcpss_clockevent); +} + +/* + * Instantiate and initialize the system timer structure + */ +struct sys_timer xttcpss_sys_timer = { + .init = xttcpss_timer_init, +}; diff --git a/pool/shard010/C/0138137_wcsunits.c b/pool/shard010/C/0138137_wcsunits.c new file mode 100644 index 0000000000000000000000000000000000000000..621b5e27904c7af4f5c6116abb1e3cf2478d6a3f --- /dev/null +++ b/pool/shard010/C/0138137_wcsunits.c @@ -0,0 +1,225 @@ +/*============================================================================ + + WCSLIB 5.16 - an implementation of the FITS WCS standard. + Copyright (C) 1995-2017, Mark Calabretta + + This file is part of WCSLIB. + + WCSLIB 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. + + WCSLIB is distributed in the hope that it will be useful, but WITHOUT ANY + WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for + more details. + + You should have received a copy of the GNU Lesser General Public License + along with WCSLIB. If not, see http://www.gnu.org/licenses. + + Direct correspondence concerning WCSLIB to mark@calabretta.id.au + + Author: Mark Calabretta, Australia Telescope National Facility, CSIRO. + http://www.atnf.csiro.au/people/Mark.Calabretta + $Id: wcsunits.c,v 5.16 2017/01/15 04:25:01 mcalabre Exp $ +*===========================================================================*/ + +#include + +#include "wcsunits.h" + +/* Map status return value to message. */ +const char *wcsunits_errmsg[] = { + "Success", + "Invalid numeric multiplier", + "Dangling binary operator", + "Invalid symbol in INITIAL context", + "Function in invalid context", + "Invalid symbol in EXPON context", + "Unbalanced bracket", + "Unbalanced parenthesis", + "Consecutive binary operators", + "Internal parser error", + "Non-conformant unit specifications", + "Non-conformant functions", + "Potentially unsafe translation"}; + + +/* Unit types. */ +const char *wcsunits_types[] = { + "plane angle", + "solid angle", + "charge", + "mole", + "temperature", + "luminous intensity", + "mass", + "length", + "time", + "beam", + "bin", + "bit", + "count", + "stellar magnitude", + "pixel", + "solar ratio", + "voxel"}; + +const char *wcsunits_units[] = { + "degree", + "steradian", + "Coulomb", + "mole", + "Kelvin", + "candela", + "kilogram", + "metre", + "second", + "", "", "", "", "", "", "", ""}; + +const char *wcsunits_funcs[] = { + "none", + "log", + "ln", + "exp"}; + +/*--------------------------------------------------------------------------*/ + +int wcsunits( + const char have[], + const char want[], + double *scale, + double *offset, + double *power) + +{ + return wcsunitse( + have, want, scale, offset, power, 0x0); +} + +/* : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : */ + +int wcsunitse( + const char have[], + const char want[], + double *scale, + double *offset, + double *power, + struct wcserr **err) + +{ + static const char *function = "wcsunitse"; + + int func1, func2, i, status; + double scale1, scale2, units1[WCSUNITS_NTYPE], units2[WCSUNITS_NTYPE]; + + if ((status = wcsulexe(have, &func1, &scale1, units1, err))) { + return status; + } + + if ((status = wcsulexe(want, &func2, &scale2, units2, err))) { + return status; + } + + /* Check conformance. */ + for (i = 0; i < WCSUNITS_NTYPE; i++) { + if (units1[i] != units2[i]) { + return wcserr_set(WCSERR_SET(UNITSERR_BAD_UNIT_SPEC), + "Mismatched units type '%s': have '%s', want '%s'", + wcsunits_types[i], have, want); + } + } + + *scale = 0.0; + *offset = 0.0; + *power = 1.0; + + switch (func1) { + case 0: + /* No function. */ + if (func2) { + return wcserr_set(WCSERR_SET(UNITSERR_BAD_FUNCS), + "Mismatched unit functions: have '%s' (%s), want '%s' (%s)", + have, wcsunits_funcs[func1], want, wcsunits_funcs[func2]); + } + + *scale = scale1 / scale2; + break; + + case 1: + /* log(). */ + if (func2 == 1) { + /* log(). */ + *scale = 1.0; + *offset = log10(scale1 / scale2); + + } else if (func2 == 2) { + /* ln(). */ + *scale = log(10.0); + *offset = log(scale1 / scale2); + + } else { + return wcserr_set(WCSERR_SET(UNITSERR_BAD_FUNCS), + "Mismatched unit functions: have '%s' (%s), want '%s' (%s)", + have, wcsunits_funcs[func1], want, wcsunits_funcs[func2]); + } + + break; + + case 2: + /* ln(). */ + if (func2 == 1) { + /* log(). */ + *scale = 1.0 / log(10.0); + *offset = log(scale1 / scale2); + + } else if (func2 == 2) { + /* ln(). */ + *scale = 1.0; + *offset = log(scale1 / scale2); + + } else { + return wcserr_set(WCSERR_SET(UNITSERR_BAD_FUNCS), + "Mismatched unit functions: have '%s' (%s), want '%s' (%s)", + have, wcsunits_funcs[func1], want, wcsunits_funcs[func2]); + } + + break; + + case 3: + /* exp(). */ + if (func2 != 3) { + return wcserr_set(WCSERR_SET(UNITSERR_BAD_FUNCS), + "Mismatched unit functions: have '%s' (%s), want '%s' (%s)", + have, wcsunits_funcs[func1], want, wcsunits_funcs[func2]); + } + + *scale = 1.0; + *power = scale1 / scale2; + break; + + default: + /* Internal parser error. */ + return wcserr_set(WCSERR_SET(UNITSERR_PARSER_ERROR), + "Internal units parser error"); + } + + return 0; +} + +/*--------------------------------------------------------------------------*/ + +int wcsutrn(int ctrl, char unitstr[]) + +{ + return wcsutrne(ctrl, unitstr, 0x0); +} + +/*--------------------------------------------------------------------------*/ + +int wcsulex(const char unitstr[], int *func, double *scale, double units[]) + +{ + return wcsulexe(unitstr, func, scale, units, 0x0); +} diff --git a/pool/shard010/C/0138138_threads.c b/pool/shard010/C/0138138_threads.c new file mode 100644 index 0000000000000000000000000000000000000000..990733a8c20100588aa915f01f9b00f4e216f9d7 --- /dev/null +++ b/pool/shard010/C/0138138_threads.c @@ -0,0 +1,284 @@ +/* threads.c + * + * This file implements threading support helpers (and maybe the thread object) + * for rsyslog. + * + * File begun on 2007-12-14 by RGerhards + * + * Copyright 2007-2012 Adiscon GmbH. + * + * This file is part of rsyslog. + * + * 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 + * -or- + * see COPYING.ASL20 in the source distribution + * + * 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 "config.h" + +#include +#include +#include +#include +#include +#include +#if HAVE_SYS_PRCTL_H +# include +#endif + +#include "rsyslog.h" +#include "dirty.h" +#include "linkedlist.h" +#include "threads.h" +#include "srUtils.h" +#include "unicode-helper.h" + +/* linked list of currently-known threads */ +static linkedList_t llThrds; + +/* methods */ + +/* Construct a new thread object + */ +static rsRetVal +thrdConstruct(thrdInfo_t **ppThis) +{ + DEFiRet; + thrdInfo_t *pThis; + + assert(ppThis != NULL); + + CHKmalloc(pThis = calloc(1, sizeof(thrdInfo_t))); + pthread_mutex_init(&pThis->mutThrd, NULL); + pthread_cond_init(&pThis->condThrdTerm, NULL); + *ppThis = pThis; + +finalize_it: + RETiRet; +} + + +/* Destructs a thread object. The object must not be linked to the + * linked list of threads. Please note that the thread should have been + * stopped before. If not, we try to do it. + */ +static rsRetVal thrdDestruct(thrdInfo_t *pThis) +{ + DEFiRet; + assert(pThis != NULL); + + if(pThis->bIsActive == 1) { + thrdTerminate(pThis); + } + pthread_mutex_destroy(&pThis->mutThrd); + pthread_cond_destroy(&pThis->condThrdTerm); + free(pThis->name); + free(pThis); + + RETiRet; +} + + +/* terminate a thread via the non-cancel interface + * This is a separate function as it involves a bit more of code. + * rgerhads, 2009-10-15 + */ +static inline rsRetVal +thrdTerminateNonCancel(thrdInfo_t *pThis) +{ + struct timespec tTimeout; + int ret; + DEFiRet; + assert(pThis != NULL); + + DBGPRINTF("request term via SIGTTIN for input thread '%s' 0x%x\n", + pThis->name, (unsigned) pThis->thrdID); + pThis->bShallStop = RSTRUE; + do { + d_pthread_mutex_lock(&pThis->mutThrd); + pthread_kill(pThis->thrdID, SIGTTIN); + timeoutComp(&tTimeout, 1000); /* a fixed 1sec timeout */ + ret = d_pthread_cond_timedwait(&pThis->condThrdTerm, &pThis->mutThrd, &tTimeout); + d_pthread_mutex_unlock(&pThis->mutThrd); + if(Debug) { + if(ret == ETIMEDOUT) { + dbgprintf("input thread term: timeout expired waiting on thread %s termination - canceling\n", pThis->name); + pthread_cancel(pThis->thrdID); + pThis->bIsActive = 0; + } else if(ret == 0) { + dbgprintf("input thread term: thread %s returned normally and is terminated\n", pThis->name); + } else { + char errStr[1024]; + int err = errno; + rs_strerror_r(err, errStr, sizeof(errStr)); + dbgprintf("input thread term: cond_wait returned with error %d: %s\n", + err, errStr); + } + } + } while(pThis->bIsActive); + DBGPRINTF("non-cancel input thread termination succeeded for thread %s 0x%x\n", + pThis->name, (unsigned) pThis->thrdID); + + RETiRet; +} + + +/* terminate a thread gracefully. + */ +rsRetVal thrdTerminate(thrdInfo_t *pThis) +{ + DEFiRet; + assert(pThis != NULL); + + if(pThis->bNeedsCancel) { + DBGPRINTF("request term via canceling for input thread 0x%x\n", (unsigned) pThis->thrdID); + pthread_cancel(pThis->thrdID); + pThis->bIsActive = 0; + } else { + thrdTerminateNonCancel(pThis); + } + pthread_join(pThis->thrdID, NULL); /* wait for input thread to complete */ + + /* call cleanup function, if any */ + if(pThis->pAfterRun != NULL) + pThis->pAfterRun(pThis); + + RETiRet; +} + + +/* terminate all known threads gracefully. + */ +rsRetVal thrdTerminateAll(void) +{ + DEFiRet; + llDestroy(&llThrds); + RETiRet; +} + + +/* This is an internal wrapper around the user thread function. Its + * purpose is to handle all the necessary housekeeping stuff so that the + * user function needs not to be aware of the threading calls. The user + * function call has just "normal", non-threading semantics. + * rgerhards, 2007-12-17 + */ +static void* thrdStarter(void *arg) +{ + DEFiRet; + thrdInfo_t *pThis = (thrdInfo_t*) arg; +# if HAVE_PRCTL && defined PR_SET_NAME + uchar thrdName[32] = "in:"; +# endif + + assert(pThis != NULL); + assert(pThis->pUsrThrdMain != NULL); + +# if HAVE_PRCTL && defined PR_SET_NAME + ustrncpy(thrdName+3, pThis->name, 20); + dbgOutputTID((char*)thrdName); + + /* set thread name - we ignore if the call fails, has no harsh consequences... */ + if(prctl(PR_SET_NAME, thrdName, 0, 0, 0) != 0) { + DBGPRINTF("prctl failed, not setting thread name for '%s'\n", pThis->name); + } else { + DBGPRINTF("set thread name to '%s'\n", thrdName); + } +# endif + + /* block all signals */ + sigset_t sigSet; + sigfillset(&sigSet); + pthread_sigmask(SIG_BLOCK, &sigSet, NULL); + + /* but ignore SIGTTN, which we (ab)use to signal the thread to shutdown -- rgerhards, 2009-07-20 */ + sigemptyset(&sigSet); + sigaddset(&sigSet, SIGTTIN); + pthread_sigmask(SIG_UNBLOCK, &sigSet, NULL); + + /* setup complete, we are now ready to execute the user code. We will not + * regain control until the user code is finished, in which case we terminate + * the thread. + */ + iRet = pThis->pUsrThrdMain(pThis); + + dbgprintf("thrdStarter: usrThrdMain %s - 0x%lx returned with iRet %d, exiting now.\n", + pThis->name, (unsigned long) pThis->thrdID, iRet); + + /* signal master control that we exit (we do the mutex lock mostly to + * keep the thread debugger happer, it would not really be necessary with + * the logic we employ...) + */ + d_pthread_mutex_lock(&pThis->mutThrd); + pThis->bIsActive = 0; + pthread_cond_signal(&pThis->condThrdTerm); + d_pthread_mutex_unlock(&pThis->mutThrd); + + ENDfunc + pthread_exit(0); +} + +/* Start a new thread and add it to the list of currently + * executing threads. It is added at the end of the list. + * rgerhards, 2007-12-14 + */ +rsRetVal thrdCreate(rsRetVal (*thrdMain)(thrdInfo_t*), rsRetVal(*afterRun)(thrdInfo_t *), sbool bNeedsCancel, uchar *name) +{ + DEFiRet; + thrdInfo_t *pThis; + + assert(thrdMain != NULL); + + CHKiRet(thrdConstruct(&pThis)); + pThis->bIsActive = 1; + pThis->pUsrThrdMain = thrdMain; + pThis->pAfterRun = afterRun; + pThis->bNeedsCancel = bNeedsCancel; + pThis->name = ustrdup(name); + pthread_create(&pThis->thrdID, +#ifdef HAVE_PTHREAD_SETSCHEDPARAM + &default_thread_attr, +#else + NULL, +#endif + thrdStarter, pThis); + CHKiRet(llAppend(&llThrds, NULL, pThis)); + +finalize_it: + RETiRet; +} + + +/* initialize the thread-support subsystem + * must be called once at the start of the program + */ +rsRetVal thrdInit(void) +{ + DEFiRet; + iRet = llInit(&llThrds, thrdDestruct, NULL, NULL); + RETiRet; +} + + +/* de-initialize the thread subsystem + * must be called once at the end of the program + */ +rsRetVal thrdExit(void) +{ + DEFiRet; + iRet = llDestroy(&llThrds); + RETiRet; +} + + +/* vi:set ai: + */ diff --git a/pool/shard010/C/0138139_usb_debug.c b/pool/shard010/C/0138139_usb_debug.c new file mode 100644 index 0000000000000000000000000000000000000000..fffebf00c691900988fcf86d4b37b5c0b86f3fa2 --- /dev/null +++ b/pool/shard010/C/0138139_usb_debug.c @@ -0,0 +1,59 @@ +/* + * This file is part of the coreboot project. + * + * Copyright (C) 2009 coresystems GmbH + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; version 2 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + */ + +// Use simple device model for this file even in ramstage +#define __SIMPLE_DEVICE__ + +#include +#include +#include +#include +#include + +pci_devfn_t pci_ehci_dbg_dev(unsigned int hcd_idx) +{ + u32 class; + pci_devfn_t dev = PCI_DEV(0, 0x1d, 0); + + class = pci_read_config32(dev, PCI_CLASS_REVISION) >> 8; + if (class != PCI_EHCI_CLASSCODE) + return 0; + + return dev; +} + +void pci_ehci_dbg_set_port(pci_devfn_t dev, unsigned int port) +{ + /* Hardcoded to physical port 1 */ +} + +void pci_ehci_dbg_enable(pci_devfn_t dev, unsigned long base) +{ + u32 tmp32; + + if (!dev) + return; + + /* Set the EHCI BAR address. */ + pci_write_config32(dev, EHCI_BAR_INDEX, base); + + /* Enable access to the EHCI memory space registers. */ + pci_write_config8(dev, PCI_COMMAND, PCI_COMMAND_MEMORY); + + /* Force ownership of hte Debug Port to the EHCI controller. */ + tmp32 = read32((void *)(base + CONFIG_EHCI_DEBUG_OFFSET)); + tmp32 |= (1 << 30); + write32((void *)(base + CONFIG_EHCI_DEBUG_OFFSET), tmp32); +} diff --git a/pool/shard010/C/0138140_rtctest_setdate.c b/pool/shard010/C/0138140_rtctest_setdate.c new file mode 100644 index 0000000000000000000000000000000000000000..2cb78489eca469b46eb99012a351265217d6be92 --- /dev/null +++ b/pool/shard010/C/0138140_rtctest_setdate.c @@ -0,0 +1,86 @@ +/* Real Time Clock Driver Test + * by: Benjamin Gaignard (benjamin.gaignard@linaro.org) + * + * To build + * gcc rtctest_setdate.c -o rtctest_setdate + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +static const char default_time[] = "00:00:00"; + +int main(int argc, char **argv) +{ + int fd, retval; + struct rtc_time new, current; + const char *rtc, *date; + const char *time = default_time; + + switch (argc) { + case 4: + time = argv[3]; + /* FALLTHROUGH */ + case 3: + date = argv[2]; + rtc = argv[1]; + break; + default: + fprintf(stderr, "usage: rtctest_setdate [HH:MM:SS]\n"); + return 1; + } + + fd = open(rtc, O_RDONLY); + if (fd == -1) { + perror(rtc); + exit(errno); + } + + sscanf(date, "%d-%d-%d", &new.tm_mday, &new.tm_mon, &new.tm_year); + new.tm_mon -= 1; + new.tm_year -= 1900; + sscanf(time, "%d:%d:%d", &new.tm_hour, &new.tm_min, &new.tm_sec); + + fprintf(stderr, "Test will set RTC date/time to %d-%d-%d, %02d:%02d:%02d.\n", + new.tm_mday, new.tm_mon + 1, new.tm_year + 1900, + new.tm_hour, new.tm_min, new.tm_sec); + + /* Write the new date in RTC */ + retval = ioctl(fd, RTC_SET_TIME, &new); + if (retval == -1) { + perror("RTC_SET_TIME ioctl"); + close(fd); + exit(errno); + } + + /* Read back */ + retval = ioctl(fd, RTC_RD_TIME, ¤t); + if (retval == -1) { + perror("RTC_RD_TIME ioctl"); + exit(errno); + } + + fprintf(stderr, "\n\nCurrent RTC date/time is %d-%d-%d, %02d:%02d:%02d.\n", + current.tm_mday, current.tm_mon + 1, current.tm_year + 1900, + current.tm_hour, current.tm_min, current.tm_sec); + + close(fd); + return 0; +} diff --git a/pool/shard010/C/0138141_xfs_error.c b/pool/shard010/C/0138141_xfs_error.c new file mode 100644 index 0000000000000000000000000000000000000000..ce653e8e1c74557dbc96ca53d7e41dfb5411e659 --- /dev/null +++ b/pool/shard010/C/0138141_xfs_error.c @@ -0,0 +1,185 @@ +/* + * Copyright (c) 2000-2001,2005 Silicon Graphics, Inc. + * 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. + * + * This program is distributed in the hope that it would be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ +#include "xfs.h" +#include "xfs_fs.h" +#include "xfs_types.h" +#include "xfs_log.h" +#include "xfs_inum.h" +#include "xfs_trans.h" +#include "xfs_sb.h" +#include "xfs_ag.h" +#include "xfs_mount.h" +#include "xfs_bmap_btree.h" +#include "xfs_dinode.h" +#include "xfs_inode.h" +#include "xfs_utils.h" +#include "xfs_error.h" + +#ifdef DEBUG + +int xfs_etrap[XFS_ERROR_NTRAP] = { + 0, +}; + +int +xfs_error_trap(int e) +{ + int i; + + if (!e) + return 0; + for (i = 0; i < XFS_ERROR_NTRAP; i++) { + if (xfs_etrap[i] == 0) + break; + if (e != xfs_etrap[i]) + continue; + xfs_notice(NULL, "%s: error %d", __func__, e); + BUG(); + break; + } + return e; +} + +int xfs_etest[XFS_NUM_INJECT_ERROR]; +int64_t xfs_etest_fsid[XFS_NUM_INJECT_ERROR]; +char * xfs_etest_fsname[XFS_NUM_INJECT_ERROR]; +int xfs_error_test_active; + +int +xfs_error_test(int error_tag, int *fsidp, char *expression, + int line, char *file, unsigned long randfactor) +{ + int i; + int64_t fsid; + + if (prandom_u32() % randfactor) + return 0; + + memcpy(&fsid, fsidp, sizeof(xfs_fsid_t)); + + for (i = 0; i < XFS_NUM_INJECT_ERROR; i++) { + if (xfs_etest[i] == error_tag && xfs_etest_fsid[i] == fsid) { + xfs_warn(NULL, + "Injecting error (%s) at file %s, line %d, on filesystem \"%s\"", + expression, file, line, xfs_etest_fsname[i]); + return 1; + } + } + + return 0; +} + +int +xfs_errortag_add(int error_tag, xfs_mount_t *mp) +{ + int i; + int len; + int64_t fsid; + + memcpy(&fsid, mp->m_fixedfsid, sizeof(xfs_fsid_t)); + + for (i = 0; i < XFS_NUM_INJECT_ERROR; i++) { + if (xfs_etest_fsid[i] == fsid && xfs_etest[i] == error_tag) { + xfs_warn(mp, "error tag #%d on", error_tag); + return 0; + } + } + + for (i = 0; i < XFS_NUM_INJECT_ERROR; i++) { + if (xfs_etest[i] == 0) { + xfs_warn(mp, "Turned on XFS error tag #%d", + error_tag); + xfs_etest[i] = error_tag; + xfs_etest_fsid[i] = fsid; + len = strlen(mp->m_fsname); + xfs_etest_fsname[i] = kmem_alloc(len + 1, KM_SLEEP); + strcpy(xfs_etest_fsname[i], mp->m_fsname); + xfs_error_test_active++; + return 0; + } + } + + xfs_warn(mp, "error tag overflow, too many turned on"); + + return 1; +} + +int +xfs_errortag_clearall(xfs_mount_t *mp, int loud) +{ + int64_t fsid; + int cleared = 0; + int i; + + memcpy(&fsid, mp->m_fixedfsid, sizeof(xfs_fsid_t)); + + + for (i = 0; i < XFS_NUM_INJECT_ERROR; i++) { + if ((fsid == 0LL || xfs_etest_fsid[i] == fsid) && + xfs_etest[i] != 0) { + cleared = 1; + xfs_warn(mp, "Clearing XFS error tag #%d", + xfs_etest[i]); + xfs_etest[i] = 0; + xfs_etest_fsid[i] = 0LL; + kmem_free(xfs_etest_fsname[i]); + xfs_etest_fsname[i] = NULL; + xfs_error_test_active--; + } + } + + if (loud || cleared) + xfs_warn(mp, "Cleared all XFS error tags for filesystem"); + + return 0; +} +#endif /* DEBUG */ + +void +xfs_error_report( + const char *tag, + int level, + struct xfs_mount *mp, + const char *filename, + int linenum, + inst_t *ra) +{ + if (level <= xfs_error_level) { + xfs_alert_tag(mp, XFS_PTAG_ERROR_REPORT, + "Internal error %s at line %d of file %s. Caller 0x%p\n", + tag, linenum, filename, ra); + + xfs_stack_trace(); + } +} + +void +xfs_corruption_error( + const char *tag, + int level, + struct xfs_mount *mp, + void *p, + const char *filename, + int linenum, + inst_t *ra) +{ + if (level <= xfs_error_level) + xfs_hex_dump(p, 16); + xfs_error_report(tag, level, mp, filename, linenum, ra); + xfs_alert(mp, "Corruption detected. Unmount and run xfs_repair"); +} diff --git a/pool/shard010/C/0138142_4-37.c b/pool/shard010/C/0138142_4-37.c new file mode 100644 index 0000000000000000000000000000000000000000..c08f2b115e87655db8881f7a318888994109c998 --- /dev/null +++ b/pool/shard010/C/0138142_4-37.c @@ -0,0 +1,85 @@ +/* + + * Copyright (c) 2002-2003, Intel Corporation. All rights reserved. + * Created by: rusty.lynch REMOVE-THIS AT intel DOT com + * This file is licensed under the GPL license. For the full content + * of this license, see the COPYING file at the top level of this + * source tree. + + Test case for assertion #4 of the sigaction system call that shows + that attempting to add SIGSTOP can not be added to the signal mask + for a signal handler. + + Steps: + 1. Fork a new process + 2. (parent) wait for child + 3. (child) Setup a signal handler for SIGQUIT with SIGSTOP added to + the signal mask + 4. (child) raise SIGQUIT + 5. (child, signal handler) raise SIGSTOP + 5. (child) If still around then return -1 + 6. (parent - returning from wait) If child was stopped then return + kill the child and return success, otherwise fail. +*/ + +#include +#include +#include +#include +#include +#include +#include "posixtest.h" + +void handler(int signo) +{ + printf("About to stop child\n"); + raise(SIGSTOP); + printf("Child has continued\n"); + exit(0); +} + +int main() +{ + pid_t pid; + if ((pid = fork()) == 0) { + /* child */ + + struct sigaction act; + + act.sa_handler = handler; + act.sa_flags = 0; + sigemptyset(&act.sa_mask); + sigaddset(&act.sa_mask, SIGSTOP); + if (sigaction(SIGQUIT, &act, 0) == -1) { + perror("Unexpected error while attempting to " + "setup test pre-conditions"); + return PTS_UNRESOLVED; + } + + if (raise(SIGQUIT) == -1) { + perror("Unexpected error while attempting to " + "setup test pre-conditions"); + } + + return PTS_UNRESOLVED; + } else { + int s; + + /* parent */ + if (waitpid(pid, &s, WUNTRACED) == -1) { + perror("Unexpected error while setting up test " + "pre-conditions"); + return PTS_UNRESOLVED; + } + + if (WIFSTOPPED(s)) { + printf("Test PASSED\n"); + kill(pid, SIGKILL); + return PTS_PASS; + } + } + + printf("Test FAILED\n"); + return PTS_FAIL; +} + diff --git a/pool/shard010/C/0138143_markdown.c b/pool/shard010/C/0138143_markdown.c new file mode 100644 index 0000000000000000000000000000000000000000..f33d58d81781956663c48018789188578d13dfda --- /dev/null +++ b/pool/shard010/C/0138143_markdown.c @@ -0,0 +1,125 @@ +#include +#include + +#include "erl_nif.h" + +#include "buffer.h" +#include "document.h" +#include "html.h" + +#define OUTPUT_UNIT 128 + +typedef struct { + ERL_NIF_TERM atom_true; + ERL_NIF_TERM atom_tables; + ERL_NIF_TERM atom_autolink; + ERL_NIF_TERM atom_fenced_code; +} markdown_priv; + +static ERL_NIF_TERM +to_html(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]) { + ErlNifBinary input; + ErlNifBinary output; + + markdown_priv* priv; + ERL_NIF_TERM options; + ERL_NIF_TERM term; + const ERL_NIF_TERM* tuple; + int tuple_size; + unsigned int extensions; + + hoedown_buffer* ob; + hoedown_document* document; + hoedown_renderer* renderer; + + if (enif_inspect_binary(env, argv[0], &input) == 0) { + return enif_make_badarg(env); + } + + if (input.size < 1) { + return argv[0]; + } + + priv = enif_priv_data(env); + options = argv[1]; + extensions = 0; + + while (enif_get_list_cell(env, options, &term, &options) != 0) { + if (enif_get_tuple(env, term, &tuple_size, &tuple) != 0) { + if (tuple_size > 1) { + if (enif_compare(tuple[0], priv->atom_tables) == 0) { + if (enif_compare(tuple[1], priv->atom_true) == 0) { + extensions |= HOEDOWN_EXT_TABLES; + continue; + } + } + + if (enif_compare(tuple[0], priv->atom_autolink) == 0) { + if (enif_compare(tuple[1], priv->atom_true) == 0) { + extensions |= HOEDOWN_EXT_AUTOLINK; + continue; + } + } + + if (enif_compare(tuple[0], priv->atom_fenced_code) == 0) { + if (enif_compare(tuple[1], priv->atom_true) == 0) { + extensions |= HOEDOWN_EXT_FENCED_CODE; + continue; + } + } + } + } + } + + ob = hoedown_buffer_new(OUTPUT_UNIT); + renderer = hoedown_html_renderer_new(0, 0); + document = hoedown_document_new(renderer, extensions, 16); + hoedown_document_render(document, ob, (uint8_t*) input.data, input.size); + + enif_release_binary(&input); + hoedown_html_renderer_free(renderer); + hoedown_document_free(document); + + enif_alloc_binary(ob->size, &output); + memcpy(output.data, ob->data, ob->size); + hoedown_buffer_free(ob); + + return enif_make_binary(env, &output); +} + +static ErlNifFunc funcs[] = { + { "to_html", 2, to_html } +}; + +static int +load(ErlNifEnv* env, void** priv, ERL_NIF_TERM info) { + markdown_priv* data = enif_alloc(sizeof(markdown_priv)); + if (data == NULL) { + return 1; + } + + data->atom_true = enif_make_atom(env, "true"); + data->atom_tables = enif_make_atom(env, "tables"); + data->atom_autolink = enif_make_atom(env, "autolink"); + data->atom_fenced_code = enif_make_atom(env, "fenced_code"); + + *priv = (void*) data; + return 0; +} + +static int +reload(ErlNifEnv* env, void** priv, ERL_NIF_TERM info) { + return 0; +} + +static int +upgrade(ErlNifEnv* env, void** priv, void** old_priv, ERL_NIF_TERM info) { + return load(env, priv, info); +} + +static void +unload(ErlNifEnv* env, void* priv) { + enif_free(priv); +} + +ERL_NIF_INIT(Elixir.Markdown, funcs, &load, &reload, &upgrade, &unload) diff --git a/pool/shard010/C/0138144_blkdev.c b/pool/shard010/C/0138144_blkdev.c new file mode 100644 index 0000000000000000000000000000000000000000..b0560ad503c36718a26ca959d952c934865857c6 --- /dev/null +++ b/pool/shard010/C/0138144_blkdev.c @@ -0,0 +1,196 @@ +/* $NetBSD: blkdev.c,v 1.1 1999/04/02 03:17:29 cgd Exp $ */ + +/* + * Copyright (c) 1999 Christopher G. Demetriou. 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. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by Christopher G. Demetriou + * for the NetBSD Project. + * 4. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +/* + * Copyright (c) 1992, 1993 + * The Regents of the University of California. All rights reserved. + * + * This code is derived from software contributed to Berkeley by + * Van Jacobson of Lawrence Berkeley Laboratory and Ralph Campbell. + * + * 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. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. 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. + * + * @(#)rz.c 8.1 (Berkeley) 6/10/93 + */ + +#include +#include + +#include +#include + +#include + +#include "stand/common/common.h" +#include "blkdev.h" + +/* + * If BOOTXX_FS_TYPE is defined, we'll try to find and use the first + * partition with that type mentioned in the disklabel, else default to + * using block 0. + * + * The old boot blocks used to look for a file system starting at block + * 0. It's not immediately obvious that change here is necessary or good, + * so for now we don't bother looking for the specific type. + */ +#undef BOOTXX_FS_TYPE + +int blkdev_is_open; +u_int32_t blkdev_part_offset; + +/* + * Since we have only one device, and want to squeeze space, we just + * short-circuit devopen() to do the disk open as well. + * + * Devopen is supposed to decode the string 'fname', open the device, + * and make 'file' point to the remaining file name. Since we don't + * do any device munging, we can just set *file to fname. + */ +int +devopen(f, fname, file) + struct open_file *f; + const char *fname; + char **file; /* out */ +{ +#if defined(BOOTXX_FS_TYPE) + int i; + size_t cnt; + char *msg, buf[DEV_BSIZE]; + struct disklabel l; +#endif /* defined(BOOTXX_FS_TYPE) */ + + if (blkdev_is_open) + return (EBUSY); + + *file = (char *)fname; + +#if 0 + f->f_devdata = NULL; /* no point */ +#endif + + /* Try to read disk label and partition table information. */ + blkdev_part_offset = 0; +#if defined(BOOTXX_FS_TYPE) + i = diskstrategy(NULL, F_READ, + (daddr_t)LABELSECTOR, DEV_BSIZE, buf, &cnt); + if (i || cnt != DEV_BSIZE) { + return (ENXIO); + } + msg = getdisklabel(buf, &l); + if (msg == NULL) { + /* + * there's a label. find the first partition of the + * type we want and use its offset. if none are + * found, we just use offset 0. + */ + for (i = 0; i < l.d_npartitions; i++) { + if (l.d_partitions[i].p_fstype == BOOTXX_FS_TYPE) { + blkdev_part_offset = l.d_partitions[i].p_offset; + break; + } + } + } else { + /* just use offset 0; it's already set that way */ + } +#endif /* defined(BOOTXX_FS_TYPE) */ + + blkdev_is_open = 1; + return (0); +} + +int +blkdevstrategy(devdata, rw, bn, reqcnt, addrvoid, cnt) + void *devdata; + int rw; + daddr_t bn; + size_t reqcnt; + void *addrvoid; + size_t *cnt; /* out: number of bytes transfered */ +{ + char *addr = addrvoid; + prom_return_t ret; + + if ((reqcnt & 0xffffff) != reqcnt || + reqcnt == 0) + asm("call_pal 0"); + + twiddle(); + + /* Partial-block transfers not handled. */ + if (reqcnt & (DEV_BSIZE - 1)) { + *cnt = 0; + return (EINVAL); + } + + ret.bits = prom_read(booted_dev_fd, reqcnt, addr, + bn + blkdev_part_offset); + if (ret.u.status) + return (EIO); + *cnt = ret.u.retval; + return (0); +} + +#if !defined(LIBSA_NO_FS_CLOSE) +int +blkdevclose(struct open_file *f) +{ + + blkdev_is_open = 0; + return (0); +} +#endif /* !defined(LIBSA_NO_FS_CLOSE) */ diff --git a/pool/shard010/C/0138145_cio_clock.c b/pool/shard010/C/0138145_cio_clock.c new file mode 100644 index 0000000000000000000000000000000000000000..25a9aa720dc19cc943120d041c2d1a22887c4d22 --- /dev/null +++ b/pool/shard010/C/0138145_cio_clock.c @@ -0,0 +1,396 @@ +/* $OpenBSD: cio_clock.c,v 1.3 2010/04/24 18:46:51 miod Exp $ */ +/* + * Copyright (c) 2006, 2007, 2009 Miodrag Vallat. + * + * 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 ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, + * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ +/* + * Copyright (c) 1998, 1999, 2000, 2001 Steve Murphree, Jr. + * Copyright (c) 1996 Nivas Madhur + * 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. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by Nivas Madhur. + * 4. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + */ +/* + * Copyright (c) 1999 Steve Murphree, Jr. + * Copyright (c) 1995 Theo de Raadt + * + * 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 ``AS IS'' AND ANY EXPRESS + * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * + * Copyright (c) 1992, 1993 + * The Regents of the University of California. All rights reserved. + * Copyright (c) 1995 Nivas Madhur + * Copyright (c) 1994 Gordon W. Ross + * Copyright (c) 1993 Adam Glass + * + * This software was developed by the Computer Systems Engineering group + * at Lawrence Berkeley Laboratory under DARPA contract BG 91-66 and + * contributed to Berkeley. + * + * All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Lawrence Berkeley Laboratory. + * + * 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. + * + * @(#)clock.c 8.1 (Berkeley) 6/11/93 + */ +/* + * Mach Operating System + * Copyright (c) 1993-1991 Carnegie Mellon University + * Copyright (c) 1991 OMRON Corporation + * All Rights Reserved. + * + * Permission to use, copy, modify and distribute this software and its + * documentation is hereby granted, provided that both the copyright + * notice and this permission notice appear in all copies of the + * software, derivative works or modified versions, and any portions + * thereof, and that both notices appear in supporting documentation. + * + */ + +#include +#include +#include +#include +#include +#include + +#include + +#include +#include +#include + +#include +#include + +/* + * Z8536 (CIO) Clock routines + */ + +void cio_clock_init(u_int); +u_int read_cio(int); +void write_cio(int, u_int); + +struct intrhand cio_clock_ih; + +int cio_clockintr(void *); +int cio_calibrateintr(void *); +u_int cio_get_timecount(struct timecounter *); + +volatile int cio_calibrate_phase = 0; +extern u_int aviion_delay_const; + +uint32_t cio_step; +uint32_t cio_refcnt; +uint32_t cio_lastcnt; + +struct mutex cio_mutex = MUTEX_INITIALIZER(IPL_CLOCK); + +struct timecounter cio_timecounter = { + .tc_get_timecount = cio_get_timecount, + .tc_counter_mask = 0xffffffff, + .tc_name = "cio", + .tc_quality = 0 +}; + +/* + * Notes on the AV400 clock usage: + * + * Unlike the MVME188 design, we only have access to three counter/timers + * in the Zilog Z8536 (since we can not receive the DUART timer interrupts). + * + * Clock is run on a Z8536 counter, kept in counter mode and retriggered + * every interrupt (when using the Z8536 in timer mode, it _seems_ that it + * resets at 0xffff instead of the initial count value...) + * + * It should be possible to run statclock on the Z8536 counter #2, but + * this would make interrupt handling more tricky, in the case both + * counters interrupt at the same time... + */ + +void +cio_init_clocks(void) +{ + u_int iter, divisor; + u_int32_t psr; + + psr = get_psr(); + set_psr(psr | PSR_IND); + +#ifdef DIAGNOSTIC + if (1000000 % hz) { + printf("cannot get %d Hz clock; using 100 Hz\n", hz); + hz = 100; + } +#endif + tick = 1000000 / hz; + + cio_clock_init(tick); + + profhz = stathz = 0; + + /* + * Calibrate delay const. + */ + cio_clock_ih.ih_fn = cio_calibrateintr; + cio_clock_ih.ih_arg = 0; + cio_clock_ih.ih_flags = INTR_WANTFRAME; + cio_clock_ih.ih_ipl = IPL_CLOCK; + sysconintr_establish(INTSRC_CLOCK, &cio_clock_ih, "clock"); + + aviion_delay_const = 1; + set_psr(psr); + while (cio_calibrate_phase == 0) + ; + + iter = 0; + while (cio_calibrate_phase == 1) { + delay(10000); + iter++; + } + + divisor = 1000000 / 10000; + aviion_delay_const = (iter * hz + divisor - 1) / divisor; + + set_psr(psr | PSR_IND); + + sysconintr_disestablish(INTSRC_CLOCK, &cio_clock_ih); + cio_clock_ih.ih_fn = cio_clockintr; + sysconintr_establish(INTSRC_CLOCK, &cio_clock_ih, "clock"); + + set_psr(psr); + + tc_init(&cio_timecounter); +} + +int +cio_calibrateintr(void *eframe) +{ + /* no need to grab the mutex, only one processor is running for now */ + /* ack the interrupt */ + write_cio(ZCIO_CT1CS, ZCIO_CTCS_GCB | ZCIO_CTCS_C_IP); + + cio_calibrate_phase++; + + return (1); +} + +int +cio_clockintr(void *eframe) +{ + mtx_enter(&cio_mutex); + /* ack the interrupt */ + write_cio(ZCIO_CT1CS, ZCIO_CTCS_GCB | ZCIO_CTCS_C_IP); + cio_refcnt += cio_step; + mtx_leave(&cio_mutex); + + hardclock(eframe); + +#ifdef MULTIPROCESSOR + /* + * Send an IPI to all other processors, so they can get their + * own ticks. + */ + m88k_broadcast_ipi(CI_IPI_HARDCLOCK); +#endif + + return (1); +} + +/* Write CIO register */ +void +write_cio(int reg, u_int val) +{ + volatile int i; + volatile u_int32_t * cio_ctrl = (volatile u_int32_t *)CIO_CTRL; + + i = *cio_ctrl; /* goto state 1 */ + *cio_ctrl = 0; /* take CIO out of RESET */ + i = *cio_ctrl; /* reset CIO state machine */ + + *cio_ctrl = (reg & 0xff); /* select register */ + *cio_ctrl = (val & 0xff); /* write the value */ +} + +/* Read CIO register */ +u_int +read_cio(int reg) +{ + int c; + volatile int i; + volatile u_int32_t * cio_ctrl = (volatile u_int32_t *)CIO_CTRL; + + /* select register */ + *cio_ctrl = (reg & 0xff); + /* delay for a short time to allow 8536 to settle */ + for (i = 0; i < 100; i++) + ; + /* read the value */ + c = *cio_ctrl; + return (c & 0xff); +} + +/* + * Initialize the CTC (8536) + * Only the counter/timers are used - the IO ports are un-comitted. + */ +void +cio_clock_init(u_int period) +{ + volatile int i; + + /* Start by forcing chip into known state */ + read_cio(ZCIO_MIC); + write_cio(ZCIO_MIC, ZCIO_MIC_RESET); /* Reset the CTC */ + for (i = 0; i < 1000; i++) /* Loop to delay */ + ; + + /* Clear reset and start init seq. */ + write_cio(ZCIO_MIC, 0x00); + + /* Wait for chip to come ready */ + while ((read_cio(ZCIO_MIC) & ZCIO_MIC_RJA) == 0) + ; + + /* Initialize the 8536 for real */ + write_cio(ZCIO_MIC, + ZCIO_MIC_MIE /* | ZCIO_MIC_NV */ | ZCIO_MIC_RJA | ZCIO_MIC_DLC); + write_cio(ZCIO_CT1MD, ZCIO_CTMD_CSC); /* Continuous count */ + write_cio(ZCIO_PBDIR, 0xff); /* set port B to input */ + + period <<= 1; /* CT#1 runs at PCLK/2, hence 2MHz */ + write_cio(ZCIO_CT1TCM, period >> 8); + write_cio(ZCIO_CT1TCL, period); + /* enable counter #1 */ + write_cio(ZCIO_MCC, ZCIO_MCC_CT1E | ZCIO_MCC_PBE); + write_cio(ZCIO_CT1CS, ZCIO_CTCS_GCB | ZCIO_CTCS_TCB | ZCIO_CTCS_S_IE); + + cio_step = period; + cio_timecounter.tc_frequency = (uint64_t)cio_step * hz; +} + +u_int +cio_get_timecount(struct timecounter *tc) +{ + u_int cmsb, clsb, counter, curcnt; + + /* + * The CIO counter is free running, but by setting the + * RCC bit in its control register, we can read a frozen + * value of the counter. + * The counter will automatically unfreeze after reading + * its LSB. + */ + + mtx_enter(&cio_mutex); + write_cio(ZCIO_CT1CS, ZCIO_CTCS_GCB | ZCIO_CTCS_RCC); + cmsb = read_cio(ZCIO_CT1CCM); + clsb = read_cio(ZCIO_CT1CCL); + curcnt = cio_refcnt; + + counter = (cmsb << 8) | clsb; +#if 0 /* this will never happen unless the period itself is 65536 */ + if (counter == 0) + counter = 65536; +#endif + + /* + * The counter counts down from its initialization value to 1. + */ + counter = cio_step - counter; + + curcnt += counter; + if (curcnt < cio_lastcnt) + curcnt += cio_step; + + cio_lastcnt = curcnt; + mtx_leave(&cio_mutex); + return curcnt; +} diff --git a/pool/shard010/C/0138146_timer.c b/pool/shard010/C/0138146_timer.c new file mode 100644 index 0000000000000000000000000000000000000000..6f1d8f677afbdf849860ba1ee7bed935421ba10b --- /dev/null +++ b/pool/shard010/C/0138146_timer.c @@ -0,0 +1,136 @@ +/* + * (C) Copyright 2004 + * DAVE Srl + * http://www.dave-tech.it + * http://www.wawnet.biz + * mailto:info@wawnet.biz + * + * See file CREDITS for list of people who contributed to this + * project. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation; either version 2 of + * the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, + * MA 02111-1307 USA + */ + +#include +#include + +/* we always count down the max. */ +#define TIMER_LOAD_VAL 0xffff + +/* macro to read the 16 bit timer */ +#define READ_TIMER (TCNTO1 & 0xffff) + +#ifdef CONFIG_USE_IRQ +#error CONFIG_USE_IRQ NOT supported +#endif + +static ulong timestamp; +static ulong lastdec; + +int timer_init (void) +{ + TCFG0 = 0x000000E9; + TCFG1 = 0x00000004; + TCON = 0x00000900; + TCNTB1 = TIMER_LOAD_VAL; + TCMPB1 = 0; + TCON = 0x00000B00; + TCON = 0x00000900; + + + lastdec = TCNTB1 = TIMER_LOAD_VAL; + timestamp = 0; + return 0; +} + +/* + * timer without interrupts + */ + +void reset_timer (void) +{ + reset_timer_masked (); +} + +ulong get_timer (ulong base) +{ + return get_timer_masked () - base; +} + +void set_timer (ulong t) +{ + timestamp = t; +} + +void __udelay (unsigned long usec) +{ + ulong tmo; + + tmo = usec / 1000; + tmo *= CONFIG_SYS_HZ; + tmo /= 8; + + tmo += get_timer (0); + + while (get_timer_masked () < tmo) + /*NOP*/; +} + +void reset_timer_masked (void) +{ + /* reset time */ + lastdec = READ_TIMER; + timestamp = 0; +} + +ulong get_timer_masked (void) +{ + ulong now = READ_TIMER; + + if (lastdec >= now) { + /* normal mode */ + timestamp += lastdec - now; + } else { + /* we have an overflow ... */ + timestamp += lastdec + TIMER_LOAD_VAL - now; + } + lastdec = now; + + return timestamp; +} + +void udelay_masked (unsigned long usec) +{ + ulong tmo; + ulong endtime; + signed long diff; + + if (usec >= 1000) { + tmo = usec / 1000; + tmo *= CONFIG_SYS_HZ; + tmo /= 8; + } else { + tmo = usec * CONFIG_SYS_HZ; + tmo /= (1000*8); + } + + endtime = get_timer(0) + tmo; + + do { + ulong now = get_timer_masked (); + diff = endtime - now; + } while (diff >= 0); +} diff --git a/pool/shard010/C/0138147_tcpClientMat.c b/pool/shard010/C/0138147_tcpClientMat.c new file mode 100644 index 0000000000000000000000000000000000000000..b003493fe94138f0bcae251f18586d9bb874a520 --- /dev/null +++ b/pool/shard010/C/0138147_tcpClientMat.c @@ -0,0 +1,189 @@ +/* + 'tcpClientMat.c' to be used with 'tcpServerMmap.py' + + 1. HOW TO COMPILE: + + 1.1 compile on Linux: + $ '/usr/local/MATLAB/R2011a/bin/mex tcpClientMat.c' + + 1.2 compile on Windows: + $ mex tcpClientMat.c wsock32.lib + + In case the code won't compile on Windows, try to add + "C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\Include" to 'INCLUDE' in your + 'mexopts.bat' file. + + + 2. HOW TO USE: + # call from matlab: 'tcpClientMat('MESSAGE', 'HOST', PORT, VERBOSE)' + # + # 'MESSAGE' must be string + # 'HOST' must be string, is hostname or IP address. + # 'PORT' is scalar + # 'VERBOSE' is scalar + # + $ tic; tcpClientMat('12', 'localhost', 9999, 1); toc + using host localhost / value 12 port 9999 + Sent: 12 + Received: OK + Elapsed time is 0.001699 seconds. + + + 3. RETURN VALUE: + # program returns 1 if server replies 'ok', and -1 otherwise. + +*/ +#if defined _WIN64 || defined _WIN32 +#include +#include +#include +#define WINSOCKVERSION MAKEWORD( 2,2 ) +#else +#include +#include +#include +#endif + +#include +#include +#include + +#define MAX_BUFFER 128 +#define HOST "127.0.0.1" + +void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray*prhs[]) +{ + + /* hostname & port */ + char* hostname = "127.0.0.1"; + int port = 9999; + + /* verbose mode? */ + int verbose = 0; + + /* setup string to send */ + char* string_to_write = "00"; + char* string_from_cmd_line; + + int connectionFd, rc, index = 0, limit = MAX_BUFFER; + struct sockaddr_in servAddr, localAddr; + char buffer[MAX_BUFFER+1]; + + /* counter variable to examine inputs to this function */ + int i; + + /* default return value from this program */ + int retVal = -1; + + #if defined _WIN64 || defined _WIN32 + /* Start up WinSock2 */ + WSADATA wsaData; + if( WSAStartup( WINSOCKVERSION, &wsaData) != 0 ) + /* no returns in mex file! + return ERROR; + */ + #endif + + /* Examine input (right-hand-side) arguments. + mexPrintf("\nThere are %d right-hand-side argument(s).", nrhs); + for (i=0; i 3) { + verbose = mxGetScalar(prhs[3]); + } + + if (verbose) { + mexPrintf("using host %s / value %s port %i \n", hostname, string_to_write, port); + } + + /* + * END assign input arguments to variables + */ + + + /* setup network parameters */ + memset(&servAddr, 0, sizeof(servAddr)); + servAddr.sin_family = AF_INET; + servAddr.sin_port = htons(port); + servAddr.sin_addr.s_addr = inet_addr(hostname); + + /* Create socket */ + connectionFd = socket(AF_INET, SOCK_STREAM, 0); + + /* bind any port number */ + localAddr.sin_family = AF_INET; + localAddr.sin_addr.s_addr = htonl(INADDR_ANY); + localAddr.sin_port = htons(0); + + rc = bind(connectionFd, + (struct sockaddr *) &localAddr, sizeof(localAddr)); + + /* Connect to Server */ + connect(connectionFd, + (struct sockaddr *)&servAddr, sizeof(servAddr)); + + /* Send request to Server */ + sprintf(buffer, "%s", string_to_write); + send(connectionFd, buffer, strlen(buffer), 0); + + if (verbose) { + printf("Sent: %s\n", buffer); + } + + /* Receive data from Server */ + sprintf(buffer, "%s", "" ); + recv(connectionFd, buffer, MAX_BUFFER, 0); + + if (verbose) { + printf("Received: %s\n", buffer); + } + + /* check if server replied 'OK' */ + if (strcmp(buffer, "OK") == 0) { + retVal = 1; + } + + /* assign return variable value of 'retVal' */ + plhs[0] = mxCreateDoubleScalar(retVal); + + /* close socket */ + #if defined _WIN64 || defined _WIN32 + closesocket(connectionFd); + #else + close(connectionFd); + #endif + +} + + diff --git a/pool/shard010/C/0138148_reply_packet_get_nth_document.c b/pool/shard010/C/0138148_reply_packet_get_nth_document.c new file mode 100644 index 0000000000000000000000000000000000000000..68d9fed6c6a787c5c0129ebc65b8dbfca6d6d7b6 --- /dev/null +++ b/pool/shard010/C/0138148_reply_packet_get_nth_document.c @@ -0,0 +1,68 @@ +#include "test.h" +#include "tap.h" +#include "mongo-wire.h" +#include "bson.h" + +#include + +void +test_mongo_wire_reply_packet_get_nth_document (void) +{ + mongo_packet *p; + bson *b, *doc; + mongo_packet_header h; + + p = mongo_wire_packet_new (); + memset (&h, 0, sizeof (mongo_packet_header)); + h.opcode = 2; + h.length = sizeof (mongo_packet_header); + mongo_wire_packet_set_header (p, &h); + + ok (mongo_wire_reply_packet_get_nth_document (NULL, 1, &doc) == FALSE, + "mongo_wire_reply_packet_get_nth_document() fails with a NULL packet"); + ok (mongo_wire_reply_packet_get_nth_document (p, 0, &doc) == FALSE, + "mongo_wire_reply_packet_get_nth_document() fails with n = 0"); + ok (mongo_wire_reply_packet_get_nth_document (p, -42, &doc) == FALSE, + "mongo_wire_reply_packet_get_nth_document() fails with n < 0"); + ok (mongo_wire_reply_packet_get_nth_document (p, 1, NULL) == FALSE, + "mongo_wire_reply_packet_get_nth_document() fails with a NULL " + "destination"); + + ok (mongo_wire_reply_packet_get_nth_document (p, 1, &doc) == FALSE, + "mongo_wire_reply_packet_get_nth_document() fails with a " + "non-reply packet"); + + h.opcode = 1; + mongo_wire_packet_set_header (p, &h); + + ok (mongo_wire_reply_packet_get_nth_document (p, 1, &doc) == FALSE, + "mongo_wire_reply_packet_get_nth_document() fails with an " + "incomplete reply packet"); + + mongo_wire_packet_free (p); + + p = test_mongo_wire_generate_reply (TRUE, 0, FALSE); + ok (mongo_wire_reply_packet_get_nth_document (p, 1, &doc) == FALSE, + "mongo_wire_reply_packet_get_nth_document() fails if there are " + "no documents to return"); + mongo_wire_packet_free (p); + + p = test_mongo_wire_generate_reply (TRUE, 2, TRUE); + ok (mongo_wire_reply_packet_get_nth_document (p, 2, &doc), + "mongo_wire_reply_packet_get_nth_document() works"); + b = test_bson_generate_full (); + bson_finish (doc); + + ok (memcmp (bson_data (b), bson_data (doc), bson_size (doc)) == 0, + "Returned document is correct"); + bson_free (doc); + bson_free (b); + + ok (mongo_wire_reply_packet_get_nth_document (p, 3, &doc) == FALSE, + "mongo_wire_reply_packet_get_nth_document() fails if the requested " + "document does not exist"); + + mongo_wire_packet_free (p); +} + +RUN_TEST (10, mongo_wire_reply_packet_get_nth_document); diff --git a/pool/shard010/C/0138149_unit.c b/pool/shard010/C/0138149_unit.c new file mode 100644 index 0000000000000000000000000000000000000000..35dcca590bd0ad38a537328dc9f6c7e1ff61bfef --- /dev/null +++ b/pool/shard010/C/0138149_unit.c @@ -0,0 +1,198 @@ +/* + * Copyright (C) 1987-2008 Sun Microsystems, Inc. All Rights Reserved. + * Copyright (C) 2008-2011 Robert Ancell. + * + * 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. See http://www.gnu.org/copyleft/gpl.html the full text of the + * license. + */ + +#include + +#include "unit.h" +#include "mp-serializer.h" +#include "mp-equation.h" +#include "currency-manager.h" // FIXME: Move out of here + +struct UnitPrivate +{ + gchar *name; + gchar *display_name; + gchar *format; + GList *symbols; + gchar *from_function; + gchar *to_function; + MpSerializer *serializer; +}; + +G_DEFINE_TYPE_WITH_PRIVATE (Unit, unit, G_TYPE_OBJECT); + +Unit * +unit_new(const gchar *name, + const gchar *display_name, + const gchar *format, + const gchar *from_function, + const gchar *to_function, + const gchar *symbols) +{ + Unit *unit = g_object_new(unit_get_type(), NULL); + gchar **symbol_names; + int i; + + unit->priv->name = g_strdup(name); + unit->priv->display_name = g_strdup(display_name); + unit->priv->format = g_strdup(format); + unit->priv->from_function = g_strdup(from_function); + unit->priv->to_function = g_strdup(to_function); + symbol_names = g_strsplit(symbols, ",", 0); + for (i = 0; symbol_names[i]; i++) + unit->priv->symbols = g_list_append(unit->priv->symbols, symbol_names[i]); + g_free(symbol_names); + + return unit; +} + +const gchar * +unit_get_name(Unit *unit) +{ + g_return_val_if_fail (unit != NULL, NULL); + return unit->priv->name; +} + +const gchar * +unit_get_display_name(Unit *unit) +{ + g_return_val_if_fail (unit != NULL, NULL); + return unit->priv->display_name; +} + +gboolean +unit_matches_symbol(Unit *unit, const gchar *symbol) +{ + GList *iter; + + g_return_val_if_fail (unit != NULL, FALSE); + g_return_val_if_fail (symbol != NULL, FALSE); + + for (iter = unit->priv->symbols; iter; iter = iter->next) { + gchar *s = iter->data; + if (strcmp(s, symbol) == 0) + return TRUE; + } + + return FALSE; +} + +const GList * +unit_get_symbols(Unit *unit) +{ + g_return_val_if_fail (unit != NULL, NULL); + return unit->priv->symbols; +} + +static int +variable_is_defined(const char *name, void *data) +{ + return TRUE; +} + +static int +get_variable(const char *name, MPNumber *z, void *data) +{ + MPNumber *x = data; + mp_set_from_mp(x, z); + return TRUE; +} + +static gboolean +solve_function(const gchar *function, const MPNumber *x, MPNumber *z) +{ + MPEquationOptions options; + int ret; + + memset(&options, 0, sizeof(options)); + options.base = 10; + options.wordlen = 32; + options.variable_is_defined = variable_is_defined; + options.get_variable = get_variable; + options.callback_data = (void *)x; + ret = mp_equation_parse(function, &options, z, NULL); + if (ret) { + g_warning("Failed to convert value: %s", function); + return FALSE; + } + + return TRUE; +} + +gboolean +unit_convert_from(Unit *unit, const MPNumber *x, MPNumber *z) +{ + g_return_val_if_fail(unit != NULL, FALSE); + g_return_val_if_fail(x != NULL, FALSE); + g_return_val_if_fail(z != NULL, FALSE); + + if (unit->priv->from_function) + return solve_function(unit->priv->from_function, x, z); + else { + // FIXME: Hack to make currency work + const MPNumber *r; + r = currency_manager_get_value(currency_manager_get_default(), unit->priv->name); + if (!r) + return FALSE; + mp_divide(x, r, z); + + return TRUE; + } +} + +gboolean +unit_convert_to(Unit *unit, const MPNumber *x, MPNumber *z) +{ + g_return_val_if_fail(unit != NULL, FALSE); + g_return_val_if_fail(x != NULL, FALSE); + g_return_val_if_fail(x != NULL, FALSE); + + if (unit->priv->from_function) + return solve_function(unit->priv->to_function, x, z); + else { + // FIXME: Hack to make currency work + const MPNumber *r; + r = currency_manager_get_value(currency_manager_get_default(), unit->priv->name); + if (!r) + return FALSE; + mp_multiply(x, r, z); + + return TRUE; + } +} + +gchar * +unit_format(Unit *unit, MPNumber *x) +{ + gchar *number_text, *text; + + g_return_val_if_fail(unit != NULL, FALSE); + g_return_val_if_fail(x != NULL, FALSE); + + number_text = mp_serializer_to_string(unit->priv->serializer, x); + text = g_strdup_printf(unit->priv->format, number_text); + g_free(number_text); + + return text; +} + +static void +unit_class_init(UnitClass *klass) +{ +} + +static void +unit_init(Unit *unit) +{ + unit->priv = unit_get_instance_private (unit); + unit->priv->serializer = mp_serializer_new(MP_DISPLAY_FORMAT_AUTOMATIC, 10, 2); + mp_serializer_set_leading_digits(unit->priv->serializer, 6); +} diff --git a/pool/shard010/C/0138150_mm_hash.c b/pool/shard010/C/0138150_mm_hash.c new file mode 100644 index 0000000000000000000000000000000000000000..5d6e05663a563506e330675b9e2110fe0bee2ead --- /dev/null +++ b/pool/shard010/C/0138150_mm_hash.c @@ -0,0 +1,145 @@ +/*- + * Copyright (c) 2004-2009 Oracle. All rights reserved. + * + * http://www.apache.org/licenses/LICENSE-2.0.txt + * + * authors: Thies C. Arntzen + * Sterling Hughes + * George Schlossnagle + */ +extern "C" +{ +#include +#include +#include "mm_hash.h" +} + +MM_Hash *mm_hash_new(MM *mm, MM_HashDtor dtor) +{ + MM_Hash *table; + + if ((table = (MM_Hash *) mm_calloc(mm, 1, sizeof(MM_Hash))) == NULL) + return NULL; + table->mm = mm; + table->dtor = dtor; + + return table; +} + +void mm_hash_free(MM_Hash *table) +{ + MM_Bucket *cur; + MM_Bucket *next; + int i; + + for (i = 0; i < MM_HASH_SIZE; i++) { + cur = table->buckets[i]; + while (cur) { + next = cur->next; + + if (table->dtor) table->dtor(cur->data); + mm_free(table->mm, cur->key); + mm_free(table->mm, cur); + + cur = next; + } + } + mm_free(table->mm, table); +} + +static unsigned int hash_hash(const char *key, int length) +{ + unsigned int hash = 0; + + while (--length) + hash = hash * 65599 + *key++; + + return hash; +} + +void *mm_hash_find(MM_Hash *table, const void *key, int length) +{ + MM_Bucket *b; + unsigned int hash = hash_hash((const char *)key, length) % MM_HASH_SIZE; + + for (b = table->buckets[ hash ]; b; b = b->next) { + if (hash != b->hash) continue; + if (length != b->length) continue; + if (memcmp(key, b->key, length)) continue; + + return b->data; + } + + return NULL; +} + +void mm_hash_update(MM_Hash *table, char *key, int length, void *data) +{ + MM_Bucket *b, p; + unsigned int hash; + + hash = hash_hash(key, length) % MM_HASH_SIZE; + + for(b = table->buckets[ hash ]; b; b = b->next) { + if (hash != b->hash) continue; + if (length != b->length) continue; + if (memcmp(key, b->key, length)) continue; + if (table->dtor) table->dtor(b->data); + b->data = data; + } + if(!b) { + if ((b = (MM_Bucket *) mm_malloc( + table->mm, sizeof(MM_Bucket))) == NULL) + return; + if ((b->key = (char *) mm_malloc( + table->mm, length + 1)) == NULL) { + free(b); + return; + } + memcpy(b->key, key, length); + b->key[length] = 0; + b->length = length; + b->hash = hash; + b->data = data; + b->next = table->buckets[ hash ]; + table->buckets[ hash ] = b; + } + table->nElements++; +} + +void mm_hash_delete(MM_Hash *table, char *key, int length) +{ + MM_Bucket *b; + MM_Bucket *prev = NULL; + unsigned int hash; + + hash = hash_hash(key, length) % MM_HASH_SIZE; + for (b = table->buckets[ hash ]; b; b = b->next) { + if (hash != b->hash || length != b->length || memcmp(key, b->key, length)) { + prev = b; + continue; + } + + /* unlink */ + if (prev) { + prev->next = b->next; + } else { + table->buckets[hash] = b->next; + } + + if (table->dtor) table->dtor(b->data); + mm_free(table->mm, b->key); + mm_free(table->mm, b); + + break; + } +} + +/* +Local variables: +tab-width: 4 +c-basic-offset: 4 +End: +vim600: noet sw=4 ts=4 fdm=marker +vim<600: noet sw=4 ts=4 +*/ diff --git a/pool/shard010/C/0138151_mali_cluster.c b/pool/shard010/C/0138151_mali_cluster.c new file mode 100644 index 0000000000000000000000000000000000000000..74ad182707d5f4067ae4b759c3f35b43ca98976d --- /dev/null +++ b/pool/shard010/C/0138151_mali_cluster.c @@ -0,0 +1,210 @@ +/* + * Copyright (C) 2010-2012 ARM Limited. All rights reserved. + * + * This program is free software and is provided to you under the terms of the GNU General Public License version 2 + * as published by the Free Software Foundation, and any use by you of this program is subject to the terms of such GNU licence. + * + * A copy of the licence is included with the program, and can also be obtained from Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ + +#include "mali_kernel_common.h" +#include "mali_cluster.h" +#include "mali_osk.h" +#include "mali_group.h" +#include "mali_l2_cache.h" + +/* id of the last job that caused the cache to be invalidated */ +static uint32_t last_invalidate_id = 0; + +static struct mali_cluster *global_clusters[MALI_MAX_NUMBER_OF_CLUSTERS] = { NULL, NULL, NULL }; +static u32 global_num_clusters = 0; + +/** + * The structure represents a render cluster + * A render cluster is defined by all the cores that share the same Mali L2 cache + */ +struct mali_cluster +{ + struct mali_l2_cache_core *l2; + u32 number_of_groups; + struct mali_group* groups[MALI_MAX_NUMBER_OF_GROUPS_PER_CLUSTER]; +}; + +struct mali_cluster *mali_cluster_create(struct mali_l2_cache_core *l2_cache) +{ + struct mali_cluster *cluster = NULL; + + cluster = _mali_osk_malloc(sizeof(struct mali_cluster)); + if (NULL != cluster) + { + _mali_osk_memset(cluster, 0, sizeof(struct mali_cluster)); + cluster->l2 = l2_cache; /* This cluster now owns this L2 cache object */ + + if(global_num_clusters < MALI_MAX_NUMBER_OF_CLUSTERS-1) + { + MALI_DEBUG_PRINT(2, ("Mali cluster: set global cluster no %d from 0x%08X to 0x%08X\n", global_num_clusters, global_clusters[global_num_clusters], cluster)); + global_clusters[global_num_clusters] = cluster; + MALI_DEBUG_PRINT(2, ("Mali cluster: global cluster no %d set to 0x%08X\n", global_num_clusters, global_clusters[global_num_clusters])); + global_num_clusters++; + } + else + { + MALI_PRINT_ERROR(("Mali cluster: Wrong number of global clusters\n")); + } + + return cluster; + } + + return NULL; +} + +void mali_cluster_add_group(struct mali_cluster *cluster, struct mali_group *group) +{ + MALI_DEBUG_ASSERT_POINTER(cluster); + + if (cluster->number_of_groups < MALI_MAX_NUMBER_OF_GROUPS_PER_CLUSTER) + { + /* This cluster now owns the group object */ + cluster->groups[cluster->number_of_groups] = group; + cluster->number_of_groups++; + } +} + +void mali_cluster_delete(struct mali_cluster *cluster) +{ + u32 i; + + MALI_DEBUG_ASSERT_POINTER(cluster); + + /* Free all the resources we own */ + for (i = 0; i < cluster->number_of_groups; i++) + { + mali_group_delete(cluster->groups[i]); + } + + if (NULL != cluster->l2) + { + mali_l2_cache_delete(cluster->l2); + } + + if(global_num_clusters > 0) + { + u32 i,j; + + for(i=0; inumber_of_groups; i++) + { + struct mali_group *group = cluster->groups[i]; + + mali_group_reset(group); + } + + if (NULL != cluster->l2) + { + mali_l2_cache_reset(cluster->l2); + } +} + +struct mali_l2_cache_core* mali_cluster_get_l2_cache_core(struct mali_cluster *cluster) +{ + MALI_DEBUG_ASSERT_POINTER(cluster); + return cluster->l2; +} + +struct mali_group *mali_cluster_get_group(struct mali_cluster *cluster, u32 index) +{ + MALI_DEBUG_ASSERT_POINTER(cluster); + + if (index < cluster->number_of_groups) + { + return cluster->groups[index]; + } + + return NULL; +} + +struct mali_cluster *mali_cluster_get_global_cluster(u32 index) +{ + if (MALI_MAX_NUMBER_OF_CLUSTERS >= index) + { + return global_clusters[index]; + } + + return NULL; +} + +u32 mali_cluster_get_glob_num_clusters(void) +{ + return global_num_clusters; +} + +void mali_cluster_set_glob_num_clusters(u32 num) +{ + global_num_clusters = num; +} + +void mali_cluster_l2_cache_invalidate_all(struct mali_cluster *cluster, u32 id) +{ + MALI_DEBUG_ASSERT_POINTER(cluster); + + if (NULL != cluster->l2) + { + /* If the last cache invalidation was done by a job with a higher id we + * don't have to flush. Since user space will store jobs w/ their + * corresponding memory in sequence (first job #0, then job #1, ...), + * we don't have to flush for job n-1 if job n has already invalidated + * the cache since we know for sure that job n-1's memory was already + * written when job n was started. */ + if (last_invalidate_id > id) + { + return; + } + else + { + last_invalidate_id = id; + } + + mali_l2_cache_invalidate_all(cluster->l2); + } +} + +void mali_cluster_l2_cache_invalidate_all_force(struct mali_cluster *cluster) +{ + MALI_DEBUG_ASSERT_POINTER(cluster); + + if (NULL != cluster->l2) + { + mali_l2_cache_invalidate_all(cluster->l2); + } +} diff --git a/pool/shard010/C/0138152_bdpandl.c b/pool/shard010/C/0138152_bdpandl.c new file mode 100644 index 0000000000000000000000000000000000000000..c95a3303feb6ce806b65a45ceb33d7fc83e0a984 --- /dev/null +++ b/pool/shard010/C/0138152_bdpandl.c @@ -0,0 +1,130 @@ +/* This is a multi-thread download tool, for pan.baidu.com + * Copyright (C) 2015 Yang Zhang + * 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 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + *************************************************************************/ +#define _POSIX_C_SOURCE 200809L +#define _GNU_SOURCE /* both for glibc version 2.10.0 before and later */ +#include +#include +#include +#include +#include +#include +#include +#include "err_handler.h" +#include "dlinfo.h" + +#if (defined(__APPLE__) && defined(__MACH__)) +# include +#endif + +static void usage(const char *progname) +{ + if (progname && *progname) + fprintf(stderr, "Usage: %s [option] url\n", progname); + fprintf(stderr, + " -d level enable debug level for ouput\n" + " -n threads specify the number of thread to download\n" + " -o filename specify the filename of output\n" + " -l file import urls from file(url may expire)\n" + " -h display the help\n\n"); + exit(EXIT_FAILURE); +} + +static void download_from_url(char *url, char *filename, int nts) +{ + struct dlinfo *dl; + + if (!(dl = dlinfo_new(url, filename, nts))) { + err_msg("failed to download from url: %s", url); + return; + } + + dl->launch(dl); + dl->delete(dl); +} + +/* we assuming will procucts the correct output filename, so here ignore it. */ +static void download_from_file(const char *listfile, int nts) +{ +#define CONFIG_LINE_MAX 4096 + FILE *list; + char *lineptr = malloc(CONFIG_LINE_MAX); + size_t max = CONFIG_LINE_MAX; + ssize_t num = 0; + + if (!(list = fopen(listfile, "r"))) + err_exit("failed to open list file: %s", listfile); + + while (1) { + errno = 0; /* ensure no effects by other calls */ + num = getline(&lineptr, &max, list); + if (num == -1) { + if (!errno) + break; /* end-of-file */ + continue; + } + if (lineptr[num - 1] == '\n') + lineptr[num - 1] = 0; + + /* when this call be down, try next to download */ + download_from_url(lineptr, NULL, nts); + } + + free(lineptr); + if (fclose(list)) + err_exit("failed to close list file: %s", listfile); +} + +int main(int argc, char *argv[]) +{ + int opt, nthreads = 100;/* defa use 100 threads */ + char *filename = NULL; + char *listfile = NULL; /* which stored the download list */ + + while ((opt = getopt(argc, argv, "d:n:o:l:h")) != -1) { + switch (opt) { + case 'd': + /* + * default debug is off, current support 1 and 2 + * debug level. + */ + err_setdebug(atoi(optarg)); + break; + case 'n': + nthreads = strtol(optarg, NULL, 10); + break; + case 'o': + filename = optarg; + break; + case 'f': + listfile = optarg; + break; + case 'h': + default: + usage(argv[0]); + } + } + + if ((!listfile && (argc != optind + 1)) || + (listfile && (argc != optind))) + usage(argv[0]); + + if (!listfile) + download_from_url(argv[optind], filename, nthreads); + else + download_from_file(listfile, nthreads); + + return 0; +} diff --git a/pool/shard010/C/0138153_uisampler.c b/pool/shard010/C/0138153_uisampler.c new file mode 100644 index 0000000000000000000000000000000000000000..f542beef88e328e2d7c0995cebc5d9e63d5feeab --- /dev/null +++ b/pool/shard010/C/0138153_uisampler.c @@ -0,0 +1,128 @@ +/* + * uisampler.c - Sampler UI interface for MS-DOS. + * + * Written by + * Marco van den Heuvel + * + * This file is part of VICE, the Versatile Commodore Emulator. + * See README for copyright notice. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA + * 02111-1307 USA. + * + */ + +#include "vice.h" + +#include + +#include "lib.h" +#include "mouse.h" +#include "resources.h" +#include "sampler.h" +#include "tui.h" +#include "tuimenu.h" +#include "uisampler.h" + +TUI_MENU_DEFINE_RADIO(SamplerDevice) +TUI_MENU_DEFINE_FILENAME(SampleName, "Sampler input media file") + +static TUI_MENU_CALLBACK(ui_set_gain_callback) +{ + if (been_activated) { + int current_gain, value; + char buf[10]; + + resources_get_int("SamplerGain", ¤t_gain); + sprintf(buf, "%d", current_gain); + + if (tui_input_string("Sampler gain", "Enter the sampler gain in % (1-200):", buf, 10) == 0) { + value = atoi(buf); + if (value > 200) { + value = 200; + } else if (value < 1) { + value = 1; + } + resources_set_int("SamplerGain", value); + } else { + return NULL; + } + } + return NULL; +} + +static TUI_MENU_CALLBACK(sampler_device_submenu_callback) +{ + int value; + char *s; + sampler_device_t *devices = sampler_get_devices(); + + resources_get_int("SamplerDevice", &value); + s = devices[value].name; + return s; +} + +static tui_menu_item_def_t sampler_device_submenu[SAMPLER_MAX_DEVICES + 1]; + +static tui_menu_item_def_t sampler_menu_items[] = { + { "Sampler device:", "Select the sampler device", + sampler_device_submenu_callback, NULL, 7, + TUI_MENU_BEH_CONTINUE, sampler_device_submenu, + "Sampler device" }, + { "Sampler gain", + "Set the sampler gain", + ui_set_gain_callback, NULL, 30, + TUI_MENU_BEH_CONTINUE, NULL, NULL }, + { "Sampler input media file:", "Select the sampler input media file", + filename_SampleName_callback, NULL, 20, + TUI_MENU_BEH_CONTINUE, NULL, NULL }, + { NULL } +}; + +void uisampler_init(struct tui_menu *parent_submenu) +{ + tui_menu_t ui_sampler_submenu; + sampler_device_t *devices = sampler_get_devices(); + int i; + + ui_sampler_submenu = tui_menu_create("Sampler settings", 1); + + for (i = 0; devices[i].name; ++i) { + sampler_device_submenu[i].label = devices[i].name; + sampler_device_submenu[i].help_string = NULL; + sampler_device_submenu[i].callback = radio_SamplerDevice_callback; + sampler_device_submenu[i].callback_param = (void *)i; + sampler_device_submenu[i].par_string_max_len = 20; + sampler_device_submenu[i].behavior = TUI_MENU_BEH_CLOSE; + sampler_device_submenu[i].submenu = NULL; + sampler_device_submenu[i].submenu_title = NULL; + } + sampler_device_submenu[i].label = NULL; + sampler_device_submenu[i].help_string = NULL; + sampler_device_submenu[i].callback = NULL; + sampler_device_submenu[i].callback_param = NULL; + sampler_device_submenu[i].par_string_max_len = 0; + sampler_device_submenu[i].behavior = 0; + sampler_device_submenu[i].submenu = NULL; + sampler_device_submenu[i].submenu_title = NULL; + + tui_menu_add(ui_sampler_submenu, sampler_menu_items); + + tui_menu_add_submenu(parent_submenu, "Sampler settings...", + "Sampler settings", + ui_sampler_submenu, + NULL, 0, + TUI_MENU_BEH_CONTINUE); +} diff --git a/pool/shard010/C/0138154_fortune-gen.c b/pool/shard010/C/0138154_fortune-gen.c new file mode 100644 index 0000000000000000000000000000000000000000..1bdba9f425e6efde37aa3233e9547c7777184489 --- /dev/null +++ b/pool/shard010/C/0138154_fortune-gen.c @@ -0,0 +1,75 @@ +#include +#include +#include +#include +#include +#include + +#include +#include + +static char buf[256]; +static int n; +static off_t off; + +static void write_record(void) +{ + uint32_t o = htonl(off); + if (fseek(stdout, 2 + 4 * n, 0) == -1) { + perror("fseek"); + exit(1); + } + if (fwrite(&o, 4, 1, stdout) != 1) { + perror("fwrite1"); + exit(1); + } + if (fseek(stdout, off, 0) == -1) { + perror("fseek"); + exit(1); + } + n++; +} + +int main(int argc, char *argv[]) +{ + uint16_t count = 0; + + while(fgets(buf, 255, stdin)) { + if (strcmp(buf, "%\n") == 0) + count++; + } + + fprintf(stderr, "%d fortunes.\n", (int)count); + + if (fseek(stdin, 0L, 0) == -1) { + perror("fseek"); + exit(1); + } + + off = 2 + 4 * count; + write_record(); + + while(fgets(buf, 255, stdin)) { + if (strcmp(buf, "%\n") == 0) { + write_record(); + } else { + if (fwrite(buf, strlen(buf), 1, stdout) != 1) { + perror("fwrite2"); + exit(1); + } + off += strlen(buf); + } + } + write_record(); + if (fseek(stdout, 0L, 0) == -1) { + perror("fseek"); + exit(1); + } + buf[0] = count & 0xff; + buf[1] = count >> 8; + if (fwrite(&buf, 2, 1, stdout) != 1) { + perror("fwrite3"); + exit(1); + } + return 0; +} diff --git a/pool/shard010/C/0138155_alarm.c b/pool/shard010/C/0138155_alarm.c new file mode 100644 index 0000000000000000000000000000000000000000..034ff902c88d0846dfba457c734f328a7a6e790d --- /dev/null +++ b/pool/shard010/C/0138155_alarm.c @@ -0,0 +1,284 @@ +/****************************************************************************** + * + * Copyright (C) 2014 Google, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ******************************************************************************/ +#include +#include +#include +#include "bt_defs.h" +#include "bt_trace.h" +#include "alarm.h" +#include "allocator.h" +#include "list.h" +#include "esp_timer.h" +#include "btc_task.h" +#include "btc_alarm.h" +#include "mutex.h" + +typedef struct alarm_t { + /* timer id point to here */ + esp_timer_handle_t alarm_hdl; + osi_alarm_callback_t cb; + void *cb_data; + int64_t deadline_us; +} osi_alarm_t; + +enum { + ALARM_STATE_IDLE, + ALARM_STATE_OPEN, +}; + +static osi_mutex_t alarm_mutex; +static int alarm_state; + +static struct alarm_t alarm_cbs[ALARM_CBS_NUM]; + +static osi_alarm_err_t alarm_free(osi_alarm_t *alarm); + +int osi_alarm_create_mux(void) +{ + if (alarm_state != ALARM_STATE_IDLE) { + LOG_WARN("%s, invalid state %d\n", __func__, alarm_state); + return -1; + } + osi_mutex_new(&alarm_mutex); + return 0; +} + +int osi_alarm_delete_mux(void) +{ + if (alarm_state != ALARM_STATE_IDLE) { + LOG_WARN("%s, invalid state %d\n", __func__, alarm_state); + return -1; + } + osi_mutex_free(&alarm_mutex); + return 0; +} + +void osi_alarm_init(void) +{ + assert(alarm_mutex != NULL); + + osi_mutex_lock(&alarm_mutex, OSI_MUTEX_MAX_TIMEOUT); + if (alarm_state != ALARM_STATE_IDLE) { + LOG_WARN("%s, invalid state %d\n", __func__, alarm_state); + goto end; + } + memset(alarm_cbs, 0x00, sizeof(alarm_cbs)); + alarm_state = ALARM_STATE_OPEN; + +end: + osi_mutex_unlock(&alarm_mutex); +} + +void osi_alarm_deinit(void) +{ + assert(alarm_mutex != NULL); + + osi_mutex_lock(&alarm_mutex, OSI_MUTEX_MAX_TIMEOUT); + if (alarm_state != ALARM_STATE_OPEN) { + LOG_WARN("%s, invalid state %d\n", __func__, alarm_state); + goto end; + } + + for (int i = 0; i < ALARM_CBS_NUM; i++) { + if (alarm_cbs[i].alarm_hdl != NULL) { + alarm_free(&alarm_cbs[i]); + } + } + alarm_state = ALARM_STATE_IDLE; + +end: + osi_mutex_unlock(&alarm_mutex); +} + +static struct alarm_t *alarm_cbs_lookfor_available(void) +{ + int i; + + for (i = 0; i < ALARM_CBS_NUM; i++) { + if (alarm_cbs[i].alarm_hdl == NULL) { //available + LOG_DEBUG("%s %d %p\n", __func__, i, &alarm_cbs[i]); + return &alarm_cbs[i]; + } + } + + return NULL; +} + +static void alarm_cb_handler(struct alarm_t *alarm) +{ + LOG_DEBUG("TimerID %p\n", alarm); + btc_msg_t msg; + btc_alarm_args_t arg; + msg.sig = BTC_SIG_API_CALL; + msg.pid = BTC_PID_ALARM; + arg.cb = alarm->cb; + arg.cb_data = alarm->cb_data; + btc_transfer_context(&msg, &arg, sizeof(btc_alarm_args_t), NULL); +} + +osi_alarm_t *osi_alarm_new(const char *alarm_name, osi_alarm_callback_t callback, void *data, period_ms_t timer_expire) +{ + assert(alarm_mutex != NULL); + + struct alarm_t *timer_id = NULL; + + osi_mutex_lock(&alarm_mutex, OSI_MUTEX_MAX_TIMEOUT); + if (alarm_state != ALARM_STATE_OPEN) { + LOG_ERROR("%s, invalid state %d\n", __func__, alarm_state); + timer_id = NULL; + goto end; + } + + timer_id = alarm_cbs_lookfor_available(); + + if (!timer_id) { + LOG_ERROR("%s alarm_cbs exhausted\n", __func__); + timer_id = NULL; + goto end; + } + + esp_timer_create_args_t tca; + tca.callback = (esp_timer_cb_t)alarm_cb_handler; + tca.arg = timer_id; + tca.dispatch_method = ESP_TIMER_TASK; + tca.name = alarm_name; + + timer_id->cb = callback; + timer_id->cb_data = data; + timer_id->deadline_us = 0; + + esp_err_t stat = esp_timer_create(&tca, &timer_id->alarm_hdl); + if (stat != ESP_OK) { + LOG_ERROR("%s failed to create timer, err 0x%x\n", __func__, stat); + timer_id = NULL; + goto end; + } + +end: + osi_mutex_unlock(&alarm_mutex); + return timer_id; +} + +static osi_alarm_err_t alarm_free(osi_alarm_t *alarm) +{ + if (!alarm || alarm->alarm_hdl == NULL) { + LOG_ERROR("%s null\n", __func__); + return OSI_ALARM_ERR_INVALID_ARG; + } + + esp_err_t stat = esp_timer_delete(alarm->alarm_hdl); + if (stat != ESP_OK) { + LOG_ERROR("%s failed to delete timer, err 0x%x\n", __func__, stat); + return OSI_ALARM_ERR_FAIL; + } + + memset(alarm, 0, sizeof(osi_alarm_t)); + return OSI_ALARM_ERR_PASS; +} + +void osi_alarm_free(osi_alarm_t *alarm) +{ + assert(alarm_mutex != NULL); + + osi_mutex_lock(&alarm_mutex, OSI_MUTEX_MAX_TIMEOUT); + if (alarm_state != ALARM_STATE_OPEN) { + LOG_ERROR("%s, invalid state %d\n", __func__, alarm_state); + goto end; + } + alarm_free(alarm); + +end: + osi_mutex_unlock(&alarm_mutex); + return; +} + +osi_alarm_err_t osi_alarm_set(osi_alarm_t *alarm, period_ms_t timeout) +{ + assert(alarm_mutex != NULL); + + osi_alarm_err_t ret = OSI_ALARM_ERR_PASS; + osi_mutex_lock(&alarm_mutex, OSI_MUTEX_MAX_TIMEOUT); + if (alarm_state != ALARM_STATE_OPEN) { + LOG_ERROR("%s, invalid state %d\n", __func__, alarm_state); + ret = OSI_ALARM_ERR_INVALID_STATE; + goto end; + } + + if (!alarm || alarm->alarm_hdl == NULL) { + LOG_ERROR("%s null\n", __func__); + ret = OSI_ALARM_ERR_INVALID_ARG; + goto end; + } + + int64_t timeout_us = 1000 * (int64_t)timeout; + esp_err_t stat = esp_timer_start_once(alarm->alarm_hdl, (uint64_t)timeout_us); + if (stat != ESP_OK) { + LOG_ERROR("%s failed to start timer, err 0x%x\n", __func__, stat); + ret = OSI_ALARM_ERR_FAIL; + goto end; + } + alarm->deadline_us = timeout_us + esp_timer_get_time(); + +end: + osi_mutex_unlock(&alarm_mutex); + return ret; +} + +osi_alarm_err_t osi_alarm_cancel(osi_alarm_t *alarm) +{ + int ret = OSI_ALARM_ERR_PASS; + osi_mutex_lock(&alarm_mutex, OSI_MUTEX_MAX_TIMEOUT); + if (alarm_state != ALARM_STATE_OPEN) { + LOG_ERROR("%s, invalid state %d\n", __func__, alarm_state); + ret = OSI_ALARM_ERR_INVALID_STATE; + goto end; + } + + if (!alarm || alarm->alarm_hdl == NULL) { + LOG_ERROR("%s null\n", __func__); + ret = OSI_ALARM_ERR_INVALID_ARG; + goto end; + } + + esp_err_t stat = esp_timer_stop(alarm->alarm_hdl); + if (stat != ESP_OK) { + LOG_DEBUG("%s failed to stop timer, err 0x%x\n", __func__, stat); + ret = OSI_ALARM_ERR_FAIL; + goto end; + } +end: + osi_mutex_unlock(&alarm_mutex); + return ret; +} + +period_ms_t osi_alarm_get_remaining_ms(const osi_alarm_t *alarm) +{ + assert(alarm_mutex != NULL); + int64_t dt_us = 0; + + osi_mutex_lock(&alarm_mutex, OSI_MUTEX_MAX_TIMEOUT); + dt_us = alarm->deadline_us - esp_timer_get_time(); + osi_mutex_unlock(&alarm_mutex); + + return (dt_us > 0) ? (period_ms_t)(dt_us / 1000) : 0; +} + +uint32_t osi_time_get_os_boottime_ms(void) +{ + return (uint32_t)(esp_timer_get_time() / 1000); +} diff --git a/pool/shard010/C/0138156_20060905-1.c b/pool/shard010/C/0138156_20060905-1.c new file mode 100644 index 0000000000000000000000000000000000000000..eac884fe5f6c9e16dd15624c29a7c2b152390621 --- /dev/null +++ b/pool/shard010/C/0138156_20060905-1.c @@ -0,0 +1,35 @@ +/* PR rtl-optimization/28386 */ +/* Origin: Volker Reichelt */ + +extern void abort(void); + +volatile char s[256][3]; + +char g; + +static void dummy(char a) +{ + g = a; +} + +static int foo(void) +{ + int i, j=0; + + for (i = 0; i < 256; i++) + if (i >= 128 && i < 256) + { + dummy (s[i - 128][0]); + ++j; + } + + return j; +} + +int main(void) +{ + if (foo () != 128) + abort (); + + return 0; +} diff --git a/pool/shard010/C/0138157_close.c b/pool/shard010/C/0138157_close.c new file mode 100644 index 0000000000000000000000000000000000000000..99bb2a248fba89b3aa5e5cddc2c460ac957d8815 --- /dev/null +++ b/pool/shard010/C/0138157_close.c @@ -0,0 +1,72 @@ +/* Copyright 2011-2018 Tyler Gilbert; + * This file is part of Stratify OS. + * + * Stratify OS 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. + * + * Stratify OS 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 Stratify OS. If not, see . + * + * + */ + +/*! \addtogroup unistd + * @{ + */ + +/*! \file + */ + +#include "sos/fs/sysfs.h" +#include "mcu/mcu.h" +#include "unistd_fs.h" +#include "mcu/debug.h" +#include "sos/sos.h" +#include "unistd_local.h" + +/*! \details This function closes the file associated + * with the specified descriptor. + * \param fildes The File descriptor \a fildes. + * \return Zero on success or -1 on error with errno (see \ref errno) set to: + * - EBADF: Invalid file descriptor + */ +int close(int fildes); + +/*! \cond */ +int _close(int fildes) { + //Close the file if it's open + int ret; + + if( FILDES_IS_SOCKET(fildes) ){ + if( sos_board_config.socket_api != 0 ){ + return sos_board_config.socket_api->close(fildes & ~FILDES_SOCKET_FLAG); + } + errno = EBADF; + return -1; + } + + fildes = u_fildes_is_bad(fildes); + if ( fildes < 0 ){ + //check to see if fildes is a socket + errno = EBADF; + return -1; + } + + ret = sysfs_file_close(get_open_file(fildes)); + + u_reset_fildes(fildes); + return ret; +} +/*! \endcond */ + + + +/*! @} */ + diff --git a/pool/shard010/C/0138158_ut_fish.c b/pool/shard010/C/0138158_ut_fish.c new file mode 100644 index 0000000000000000000000000000000000000000..3da56fa2f514d18ba2bd2f8468e055d925c94fa7 --- /dev/null +++ b/pool/shard010/C/0138158_ut_fish.c @@ -0,0 +1,31 @@ +/* j/6/fish.c +** +*/ +#include "all.h" + +u3_noun +u3wfu_fish(u3_noun cor) +{ + u3_noun sut, axe, van; + + if ( (c3n == u3r_mean(cor, u3x_sam, &axe, u3x_con, &van, 0)) || + (c3n == u3ud(axe)) || + (u3_none == (sut = u3r_at(u3x_sam, van))) ) + { + return u3m_bail(c3__fail); + } + else { + c3_m fun_m = 141 + c3__fish + ((!!u3r_at(u3qfu_van_vet, van)) << 8); + u3_noun key = u3z_key_2(fun_m, sut, axe); + u3_weak pro = u3z_find(key); + + if ( u3_none != pro ) { + u3z(key); + return pro; + } + else { + pro = u3n_nock_on(u3k(cor), u3k(u3x_at(u3x_bat, cor))); + return u3z_save(key, pro); + } + } +} diff --git a/pool/shard010/C/0138159_CWE761_Free_Pointer_Not_at_Start_of_Buffer__char_console_41.c b/pool/shard010/C/0138159_CWE761_Free_Pointer_Not_at_Start_of_Buffer__char_console_41.c new file mode 100644 index 0000000000000000000000000000000000000000..9c6fc77308f404d4466cba745ecb7a81aae4a905 --- /dev/null +++ b/pool/shard010/C/0138159_CWE761_Free_Pointer_Not_at_Start_of_Buffer__char_console_41.c @@ -0,0 +1,159 @@ +/* TEMPLATE GENERATED TESTCASE FILE +Filename: CWE761_Free_Pointer_Not_at_Start_of_Buffer__char_console_41.c +Label Definition File: CWE761_Free_Pointer_Not_at_Start_of_Buffer.label.xml +Template File: source-sinks-41.tmpl.c +*/ +/* + * @description + * CWE: 761 Free Pointer not at Start of Buffer + * BadSource: console Read input from the console + * Sinks: + * GoodSink: free() memory correctly at the start of the buffer + * BadSink : free() memory not at the start of the buffer + * Flow Variant: 41 Data flow: data passed as an argument from one function to another in the same source file + * + * */ + +#include "std_testcase.h" + +#include + +#define SEARCH_CHAR 'S' + +#ifndef OMITBAD + +static void badSink(char * data) +{ + /* FLAW: We are incrementing the pointer in the loop - this will cause us to free the + * memory block not at the start of the buffer */ + for (; *data != '\0'; data++) + { + if (*data == SEARCH_CHAR) + { + printLine("We have a match!"); + break; + } + } + free(data); +} + +void CWE761_Free_Pointer_Not_at_Start_of_Buffer__char_console_41_bad() +{ + char * data; + data = (char *)malloc(100*sizeof(char)); + data[0] = '\0'; + { + /* Read input from the console */ + size_t dataLen = strlen(data); + /* if there is room in data, read into it from the console */ + if (100-dataLen > 1) + { + /* POTENTIAL FLAW: Read data from the console */ + if (fgets(data+dataLen, (int)(100-dataLen), stdin) != NULL) + { + /* The next few lines remove the carriage return from the string that is + * inserted by fgets() */ + dataLen = strlen(data); + if (dataLen > 0 && data[dataLen-1] == '\n') + { + data[dataLen-1] = '\0'; + } + } + else + { + printLine("fgets() failed"); + /* Restore NUL terminator if fgets fails */ + data[dataLen] = '\0'; + } + } + } + badSink(data); +} + +#endif /* OMITBAD */ + +#ifndef OMITGOOD + +static void goodB2GSink(char * data) +{ + { + size_t i; + /* FIX: Use a loop variable to traverse through the string pointed to by data */ + for (i=0; i < strlen(data); i++) + { + if (data[i] == SEARCH_CHAR) + { + printLine("We have a match!"); + break; + } + } + free(data); + } +} + +/* goodB2G uses the BadSource with the GoodSink */ +static void goodB2G() +{ + char * data; + data = (char *)malloc(100*sizeof(char)); + data[0] = '\0'; + { + /* Read input from the console */ + size_t dataLen = strlen(data); + /* if there is room in data, read into it from the console */ + if (100-dataLen > 1) + { + /* POTENTIAL FLAW: Read data from the console */ + if (fgets(data+dataLen, (int)(100-dataLen), stdin) != NULL) + { + /* The next few lines remove the carriage return from the string that is + * inserted by fgets() */ + dataLen = strlen(data); + if (dataLen > 0 && data[dataLen-1] == '\n') + { + data[dataLen-1] = '\0'; + } + } + else + { + printLine("fgets() failed"); + /* Restore NUL terminator if fgets fails */ + data[dataLen] = '\0'; + } + } + } + goodB2GSink(data); +} + +void CWE761_Free_Pointer_Not_at_Start_of_Buffer__char_console_41_good() +{ + goodB2G(); +} + +#endif /* OMITGOOD */ + +/* Below is the main(). It is only used when building this testcase on + its own for testing or for building a binary to use in testing binary + analysis tools. It is not used when compiling all the testcases as one + application, which is how source code analysis tools are tested. */ + +#ifdef INCLUDEMAIN + +int main(int argc, char * argv[]) +{ + /* seed randomness */ + srand( (unsigned)time(NULL) ); +#ifndef OMITGOOD + printLine("Calling good()..."); + CWE761_Free_Pointer_Not_at_Start_of_Buffer__char_console_41_good(); + printLine("Finished good()"); +#endif /* OMITGOOD */ +#ifndef OMITBAD + printLine("Calling bad()..."); + CWE761_Free_Pointer_Not_at_Start_of_Buffer__char_console_41_bad(); + printLine("Finished bad()"); +#endif /* OMITBAD */ + return 0; +} + +#endif diff --git a/pool/shard010/C/0138160_si_drv_mhl_rgb.c b/pool/shard010/C/0138160_si_drv_mhl_rgb.c new file mode 100644 index 0000000000000000000000000000000000000000..60a7d588368a9a37d32e0c9d582dd191f98b48f9 --- /dev/null +++ b/pool/shard010/C/0138160_si_drv_mhl_rgb.c @@ -0,0 +1,93 @@ +#ifdef RGB_BOARD +#ifndef __KERNEL__ +#include +#include "hal_local.h" +#include "si_common.h" +#else +#include +#include "sii_hal.h" +#endif +#include "si_drv_ext.h" +#include "si_platform.h" +#include "si_drv_mhl_tx.h" +#include "si_mhl_tx_api.h" +static bool_t valid_input = false; +extern video_data_t video_data; +static bool_t RGBIsr (AVModeChange_t * pAVModeChange, AVMode_t * pAVMode) +{ + #if 0 + bool_t video_change = false; + video_change = CheckExtVideo(); + if (video_change) + { + video_data.inputColorSpace = GetExt_inputColorSpace(); + video_data.inputVideoCode = GetExt_inputVideoCode(); + video_data.inputcolorimetryAspectRatio = GetExt_inputcolorimetryAspectRatio(); + video_data.input_AR = GetExt_inputAR(); + } + #endif + switch(video_data.inputVideoCode) + { + case 1: + pAVMode->video_mode = VM_VGA; + break; + case 2: + case 3: + pAVMode->video_mode = VM_480P; + break; + case 4: + pAVMode->video_mode = VM_720P60; + break; + case 17: + case 18: + pAVMode->video_mode = VM_576P; + break; + case 19: + pAVMode->video_mode = VM_720P50; + break; + default: + pAVMode->video_mode = VM_INVALID; + break; + } + pAVModeChange->video_change = video_change; + if (pAVMode->video_mode == VM_INVALID) + return false; + return true; +} +static void AudioIsr (AVModeChange_t * pAVModeChange, AVMode_t * pAVMode) +{ + inAudioTypes_t newaudiomode = AUD_INVALID; + newaudiomode = GetExt_AudioType(); + if (!pinDbgSw5) + { + newaudiomode = AUD_SPDIF; + } + if (pAVMode->audio_mode != newaudiomode) + { + TX_DEBUG_PRINT(("Audio input mode change, new mode: 0x%02x, old mode: 0x%02x.\n", (int)newaudiomode, (int)pAVMode->audio_mode)); + pAVMode->audio_mode = newaudiomode; + pAVModeChange->audio_change = true; + } +} +bool_t SiiVideoInputIsValid(void) +{ + if (pinDbgSw6) + return valid_input; + else + return true; +} +void AVModeDetect(AVModeChange_t * pAVModeChange, AVMode_t * pAVMode) +{ + TX_DEBUG_PRINT(("AVModeDetect")); + valid_input = RGBIsr(pAVModeChange, pAVMode); + AudioIsr(pAVModeChange, pAVMode); +} +void SiiInitExtVideo(void) +{ + InitExtVideo(); +} +void SiiTriggerExtInt(void) +{ + TriggerExtInt(); +} +#endif diff --git a/pool/shard010/C/0138161_mpc624.c b/pool/shard010/C/0138161_mpc624.c new file mode 100644 index 0000000000000000000000000000000000000000..311b2f4fe092f7500f5a10e2728ca534eb4eff54 --- /dev/null +++ b/pool/shard010/C/0138161_mpc624.c @@ -0,0 +1,363 @@ +/* + * mpc624.c + * Hardware driver for a Micro/sys inc. MPC-624 PC/104 board + * + * COMEDI - Linux Control and Measurement Device Interface + * Copyright (C) 2000 David A. Schleef + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + */ + +/* + * Driver: mpc624 + * Description: Micro/sys MPC-624 PC/104 board + * Devices: [Micro/sys] MPC-624 (mpc624) + * Author: Stanislaw Raczynski + * Updated: Thu, 15 Sep 2005 12:01:18 +0200 + * Status: working + * + * The Micro/sys MPC-624 board is based on the LTC2440 24-bit sigma-delta + * ADC chip. + * + * Subdevices supported by the driver: + * - Analog In: supported + * - Digital I/O: not supported + * - LEDs: not supported + * - EEPROM: not supported + * + * Configuration Options: + * [0] - I/O base address + * [1] - conversion rate + * Conversion rate RMS noise Effective Number Of Bits + * 0 3.52kHz 23uV 17 + * 1 1.76kHz 3.5uV 20 + * 2 880Hz 2uV 21.3 + * 3 440Hz 1.4uV 21.8 + * 4 220Hz 1uV 22.4 + * 5 110Hz 750uV 22.9 + * 6 55Hz 510nV 23.4 + * 7 27.5Hz 375nV 24 + * 8 13.75Hz 250nV 24.4 + * 9 6.875Hz 200nV 24.6 + * [2] - voltage range + * 0 -1.01V .. +1.01V + * 1 -10.1V .. +10.1V + */ + +#include +#include "../comedidev.h" + +#include + +/* Offsets of different ports */ +#define MPC624_MASTER_CONTROL 0 /* not used */ +#define MPC624_GNMUXCH 1 /* Gain, Mux, Channel of ADC */ +#define MPC624_ADC 2 /* read/write to/from ADC */ +#define MPC624_EE 3 /* read/write to/from serial EEPROM via I2C */ +#define MPC624_LEDS 4 /* write to LEDs */ +#define MPC624_DIO 5 /* read/write to/from digital I/O ports */ +#define MPC624_IRQ_MASK 6 /* IRQ masking enable/disable */ + +/* Register bits' names */ +#define MPC624_ADBUSY BIT(5) +#define MPC624_ADSDO BIT(4) +#define MPC624_ADFO BIT(3) +#define MPC624_ADCS BIT(2) +#define MPC624_ADSCK BIT(1) +#define MPC624_ADSDI BIT(0) + +/* 32-bit output value bits' names */ +#define MPC624_EOC_BIT BIT(31) +#define MPC624_DMY_BIT BIT(30) +#define MPC624_SGN_BIT BIT(29) + +/* SDI Speed/Resolution Programming bits */ +#define MPC624_OSR(x) (((x) & 0x1f) << 27) +#define MPC624_SPEED_3_52_KHZ MPC624_OSR(0x11) +#define MPC624_SPEED_1_76_KHZ MPC624_OSR(0x12) +#define MPC624_SPEED_880_HZ MPC624_OSR(0x13) +#define MPC624_SPEED_440_HZ MPC624_OSR(0x14) +#define MPC624_SPEED_220_HZ MPC624_OSR(0x15) +#define MPC624_SPEED_110_HZ MPC624_OSR(0x16) +#define MPC624_SPEED_55_HZ MPC624_OSR(0x17) +#define MPC624_SPEED_27_5_HZ MPC624_OSR(0x18) +#define MPC624_SPEED_13_75_HZ MPC624_OSR(0x19) +#define MPC624_SPEED_6_875_HZ MPC624_OSR(0x1f) + +struct mpc624_private +{ + unsigned int ai_speed; +}; + +/* -------------------------------------------------------------------------- */ +static const struct comedi_lrange range_mpc624_bipolar1 = +{ + 1, + { + /* BIP_RANGE(1.01) this is correct, */ + /* but my MPC-624 actually seems to have a range of 2.02 */ + BIP_RANGE(2.02) + } +}; + +static const struct comedi_lrange range_mpc624_bipolar10 = +{ + 1, + { + /* BIP_RANGE(10.1) this is correct, */ + /* but my MPC-624 actually seems to have a range of 20.2 */ + BIP_RANGE(20.2) + } +}; + +static unsigned int mpc624_ai_get_sample(struct comedi_device *dev, + struct comedi_subdevice *s) +{ + struct mpc624_private *devpriv = dev->private; + unsigned int data_out = devpriv->ai_speed; + unsigned int data_in = 0; + unsigned int bit; + int i; + + /* Start reading data */ + udelay(1); + + for (i = 0; i < 32; i++) + { + /* Set the clock low */ + outb(0, dev->iobase + MPC624_ADC); + udelay(1); + + /* Set the ADSDI line for the next bit (send to MPC624) */ + bit = (data_out & BIT(31)) ? MPC624_ADSDI : 0; + outb(bit, dev->iobase + MPC624_ADC); + udelay(1); + + /* Set the clock high */ + outb(MPC624_ADSCK | bit, dev->iobase + MPC624_ADC); + udelay(1); + + /* Read ADSDO on high clock (receive from MPC624) */ + data_in <<= 1; + data_in |= (inb(dev->iobase + MPC624_ADC) & MPC624_ADSDO) >> 4; + udelay(1); + + data_out <<= 1; + } + + /* + * Received 32-bit long value consist of: + * 31: EOC - (End Of Transmission) bit - should be 0 + * 30: DMY - (Dummy) bit - should be 0 + * 29: SIG - (Sign) bit - 1 if positive, 0 if negative + * 28: MSB - (Most Significant Bit) - the first bit of the + * conversion result + * .... + * 05: LSB - (Least Significant Bit)- the last bit of the + * conversion result + * 04-00: sub-LSB - sub-LSBs are basically noise, but when + * averaged properly, they can increase + * conversion precision up to 29 bits; + * they can be discarded without loss of + * resolution. + */ + if (data_in & MPC624_EOC_BIT) + { + dev_dbg(dev->class_dev, "EOC bit is set!"); + } + + if (data_in & MPC624_DMY_BIT) + { + dev_dbg(dev->class_dev, "DMY bit is set!"); + } + + if (data_in & MPC624_SGN_BIT) + { + /* + * Voltage is positive + * + * comedi operates on unsigned numbers, so mask off EOC + * and DMY and don't clear the SGN bit + */ + data_in &= 0x3fffffff; + } + else + { + /* + * The voltage is negative + * + * data_in contains a number in 30-bit two's complement + * code and we must deal with it + */ + data_in |= MPC624_SGN_BIT; + data_in = ~data_in; + data_in += 1; + /* clear EOC and DMY bits */ + data_in &= ~(MPC624_EOC_BIT | MPC624_DMY_BIT); + data_in = 0x20000000 - data_in; + } + + return data_in; +} + +static int mpc624_ai_eoc(struct comedi_device *dev, + struct comedi_subdevice *s, + struct comedi_insn *insn, + unsigned long context) +{ + unsigned char status; + + status = inb(dev->iobase + MPC624_ADC); + + if ((status & MPC624_ADBUSY) == 0) + { + return 0; + } + + return -EBUSY; +} + +static int mpc624_ai_insn_read(struct comedi_device *dev, + struct comedi_subdevice *s, + struct comedi_insn *insn, + unsigned int *data) +{ + int ret; + int i; + + /* + * WARNING: + * We always write 0 to GNSWA bit, so the channel range is +-/10.1Vdc + */ + outb(insn->chanspec, dev->iobase + MPC624_GNMUXCH); + + for (i = 0; i < insn->n; i++) + { + /* Trigger the conversion */ + outb(MPC624_ADSCK, dev->iobase + MPC624_ADC); + udelay(1); + outb(MPC624_ADCS | MPC624_ADSCK, dev->iobase + MPC624_ADC); + udelay(1); + outb(0, dev->iobase + MPC624_ADC); + udelay(1); + + /* Wait for the conversion to end */ + ret = comedi_timeout(dev, s, insn, mpc624_ai_eoc, 0); + + if (ret) + { + return ret; + } + + data[i] = mpc624_ai_get_sample(dev, s); + } + + return insn->n; +} + +static int mpc624_attach(struct comedi_device *dev, struct comedi_devconfig *it) +{ + struct mpc624_private *devpriv; + struct comedi_subdevice *s; + int ret; + + ret = comedi_request_region(dev, it->options[0], 0x10); + + if (ret) + { + return ret; + } + + devpriv = comedi_alloc_devpriv(dev, sizeof(*devpriv)); + + if (!devpriv) + { + return -ENOMEM; + } + + switch (it->options[1]) + { + case 0: + devpriv->ai_speed = MPC624_SPEED_3_52_KHZ; + break; + + case 1: + devpriv->ai_speed = MPC624_SPEED_1_76_KHZ; + break; + + case 2: + devpriv->ai_speed = MPC624_SPEED_880_HZ; + break; + + case 3: + devpriv->ai_speed = MPC624_SPEED_440_HZ; + break; + + case 4: + devpriv->ai_speed = MPC624_SPEED_220_HZ; + break; + + case 5: + devpriv->ai_speed = MPC624_SPEED_110_HZ; + break; + + case 6: + devpriv->ai_speed = MPC624_SPEED_55_HZ; + break; + + case 7: + devpriv->ai_speed = MPC624_SPEED_27_5_HZ; + break; + + case 8: + devpriv->ai_speed = MPC624_SPEED_13_75_HZ; + break; + + case 9: + devpriv->ai_speed = MPC624_SPEED_6_875_HZ; + break; + + default: + devpriv->ai_speed = MPC624_SPEED_3_52_KHZ; + } + + ret = comedi_alloc_subdevices(dev, 1); + + if (ret) + { + return ret; + } + + /* Analog Input subdevice */ + s = &dev->subdevices[0]; + s->type = COMEDI_SUBD_AI; + s->subdev_flags = SDF_READABLE | SDF_DIFF; + s->n_chan = 4; + s->maxdata = 0x3fffffff; + s->range_table = (it->options[1] == 0) ? &range_mpc624_bipolar1 + : &range_mpc624_bipolar10; + s->insn_read = mpc624_ai_insn_read; + + return 0; +} + +static struct comedi_driver mpc624_driver = +{ + .driver_name = "mpc624", + .module = THIS_MODULE, + .attach = mpc624_attach, + .detach = comedi_legacy_detach, +}; +module_comedi_driver(mpc624_driver); + +MODULE_AUTHOR("Comedi http://www.comedi.org"); +MODULE_DESCRIPTION("Comedi driver for Micro/sys MPC-624 PC/104 board"); +MODULE_LICENSE("GPL"); diff --git a/pool/shard010/C/0138162_util.c b/pool/shard010/C/0138162_util.c new file mode 100644 index 0000000000000000000000000000000000000000..3b5b832cca16a62fb51e34bd60ff55c27e9536a2 --- /dev/null +++ b/pool/shard010/C/0138162_util.c @@ -0,0 +1,192 @@ +/* + $Id: util.c,v 1.1 2003/10/13 11:47:12 f1rmb Exp $ + + Copyright (C) 2000 Herbert Valerio Riedel + Copyright (C) 2003 Rocky Bernstein + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +*/ + +#ifdef HAVE_CONFIG_H +# include "config.h" +#endif + +#include +#include +#include +#include + +#include "cdio_assert.h" +#include + +static const char _rcsid[] = "$Id: util.c,v 1.1 2003/10/13 11:47:12 f1rmb Exp $"; + +size_t +_cdio_strlenv(char **str_array) +{ + size_t n = 0; + + cdio_assert (str_array != NULL); + + while(str_array[n]) + n++; + + return n; +} + +void +_cdio_strfreev(char **strv) +{ + int n; + + cdio_assert (strv != NULL); + + for(n = 0; strv[n]; n++) + free(strv[n]); + + free(strv); +} + +char * +_cdio_strjoin (char *strv[], unsigned count, const char delim[]) +{ + size_t len; + char *new_str; + unsigned n; + + cdio_assert (strv != NULL); + cdio_assert (delim != NULL); + + len = (count-1) * strlen (delim); + + for (n = 0;n < count;n++) + len += strlen (strv[n]); + + len++; + + new_str = _cdio_malloc (len); + new_str[0] = '\0'; + + for (n = 0;n < count;n++) + { + if (n) + strcat (new_str, delim); + strcat (new_str, strv[n]); + } + + return new_str; +} + +char ** +_cdio_strsplit(const char str[], char delim) /* fixme -- non-reentrant */ +{ + int n; + char **strv = NULL; + char *_str, *p; + char _delim[2] = { 0, 0 }; + + cdio_assert (str != NULL); + + _str = strdup(str); + _delim[0] = delim; + + cdio_assert (_str != NULL); + + n = 1; + p = _str; + while(*p) + if (*(p++) == delim) + n++; + + strv = _cdio_malloc (sizeof (char *) * (n+1)); + + n = 0; + while((p = strtok(n ? NULL : _str, _delim)) != NULL) + strv[n++] = strdup(p); + + free(_str); + + return strv; +} + +void * +_cdio_malloc (size_t size) +{ + void *new_mem = malloc (size); + + cdio_assert (new_mem != NULL); + + memset (new_mem, 0, size); + + return new_mem; +} + +void * +_cdio_memdup (const void *mem, size_t count) +{ + void *new_mem = NULL; + + if (mem) + { + new_mem = _cdio_malloc (count); + memcpy (new_mem, mem, count); + } + + return new_mem; +} + +char * +_cdio_strdup_upper (const char str[]) +{ + char *new_str = NULL; + + if (str) + { + char *p; + + p = new_str = strdup (str); + + while (*p) + { + *p = toupper (*p); + p++; + } + } + + return new_str; +} + +uint8_t +to_bcd8 (uint8_t n) +{ + cdio_assert (n < 100); + + return ((n/10)<<4) | (n%10); +} + +uint8_t +from_bcd8(uint8_t p) +{ + return (0xf & p)+(10*(p >> 4)); +} + + +/* + * Local variables: + * c-file-style: "gnu" + * tab-width: 8 + * indent-tabs-mode: nil + * End: + */ diff --git a/pool/shard010/C/0138163_sedrename.c b/pool/shard010/C/0138163_sedrename.c new file mode 100644 index 0000000000000000000000000000000000000000..439fe5f344d64a9425002f9b708ebcdab21df3e7 --- /dev/null +++ b/pool/shard010/C/0138163_sedrename.c @@ -0,0 +1,148 @@ +/*! + * \file sedrename.c + * + * \brief Sed rename plug-in for PCB. + * + * \author Copyright (C) 2008 Peter Clifton + * + * \copyright Licensed under the terms of the GNU General Public + * License, version 2 or later. + * + * Compile like this: + * + * gcc -Wall -I$HOME/pcbsrc/pcb.clean/src -I$HOME/pcbsrc/pcb.clean -O2 -shared sedrename.c -o sedrename.so + * + * The resulting sedrename.so goes in $HOME/.pcb/plugins/sedrename.so. + */ + +#include + +#include "config.h" +#include "global.h" +#include "data.h" +#include "hid.h" +#include "misc.h" +#include "create.h" +#include "error.h" +#include "change.h" +#include "rtree.h" +#include "undo.h" + +static int +sedrename (int argc, char **argv, Coord x, Coord y) +{ + FILE *fp; + int result = STATUS_OK; + char *sed_prog = "sed "; + char *sed_postfix = " > sedrename.tmp"; + char *sed_arguments; + char *sed_cmd; + + static char *last_argument = NULL; + + if (last_argument == NULL) + last_argument = strdup ("s///"); + +#if 0 + if (argc != 1) + { + Message("Usage: sedrename sed_expression"); + return 1; + } + + sed_arguments = argv[0]; +#else + if (argc != 0) + { + Message("Usage: sedrename"); + return 1; + } + + sed_arguments = gui->prompt_for ("sedrename", last_argument); + if (sed_arguments == NULL) + { + Message("Got null for sed arguments"); + return 1; + } + free (last_argument); + last_argument = sed_arguments; +#endif + + sed_cmd = (char *) malloc (strlen (sed_prog) + strlen (sed_arguments) + strlen (sed_postfix) + 1); + memcpy (sed_cmd, sed_prog, strlen (sed_prog) + 1); + strcpy (sed_cmd + strlen (sed_prog), sed_arguments); + strcpy (sed_cmd + strlen (sed_prog) + strlen (sed_arguments), sed_postfix); + + printf ("Calling sed: '%s'\n", sed_cmd); + + if ((fp = popen (sed_cmd, "w")) == NULL) + { + PopenErrorMessage (sed_cmd); + free (sed_cmd); + return STATUS_ERROR; + } + + free (sed_cmd); + + SET_FLAG (NAMEONPCBFLAG, PCB); + + ELEMENT_LOOP (PCB->Data); + { + + if (!TEST_FLAG (SELECTEDFLAG, element)) + continue; + + /* BADNESS.. IF SED DOESN'T MATCH OUTPUT LINE FOR LINE, WE STALL */ + fprintf (fp, "%s\n", element->Name[1].TextString); + } + END_LOOP; + + if (pclose (fp)) + return STATUS_ERROR; + + if ((fp = fopen ("sedrename.tmp", "rb")) == NULL) + { + Message("Cannot open sedrename.tmp for reading"); + return STATUS_ERROR; + } + + ELEMENT_LOOP (PCB->Data); + { + char *new_ref; + + if (!TEST_FLAG (SELECTEDFLAG, element)) + continue; + + if (fscanf (fp, "%as", &new_ref) != EOF) + { + printf ("Send '%s', got '%s'\n", element->Name[1].TextString, new_ref); + + AddObjectToChangeNameUndoList (ELEMENT_TYPE, NULL, NULL, + element, + NAMEONPCB_NAME (element)); + + ChangeObjectName (ELEMENT_TYPE, element, NULL, NULL, new_ref); + } + } + END_LOOP; + + gui->invalidate_all (); + + IncrementUndoSerialNumber (); + + return (fclose (fp) ? STATUS_ERROR : result); +} + +static HID_Action sedrename_action_list[] = { + {"sedrename", NULL, sedrename, + NULL, NULL} +}; + +REGISTER_ACTIONS (sedrename_action_list) + +void +pcb_plugin_init() +{ + register_sedrename_action_list(); +} + diff --git a/pool/shard010/C/0138164_empty-Seed1-RandomFuns-Type_long-ControlStructures_15-BB1-ForBound_constant-Operators_all.c b/pool/shard010/C/0138164_empty-Seed1-RandomFuns-Type_long-ControlStructures_15-BB1-ForBound_constant-Operators_all.c new file mode 100644 index 0000000000000000000000000000000000000000..926d875c56f78b6ccc3cfd249c4cd9d6fbf079a3 --- /dev/null +++ b/pool/shard010/C/0138164_empty-Seed1-RandomFuns-Type_long-ControlStructures_15-BB1-ForBound_constant-Operators_all.c @@ -0,0 +1,108 @@ +/* Generated by CIL v. 1.7.0 */ +/* print_CIL_Input is false */ + +struct _IO_FILE; +struct timeval; +extern float strtof(char const *str , char const *endptr ) ; +extern void signal(int sig , void *func ) ; +typedef struct _IO_FILE FILE; +extern int atoi(char const *s ) ; +extern double strtod(char const *str , char const *endptr ) ; +extern int fclose(void *stream ) ; +extern void *fopen(char const *filename , char const *mode ) ; +extern void abort() ; +extern void exit(int status ) ; +extern int raise(int sig ) ; +extern int fprintf(struct _IO_FILE *stream , char const *format , ...) ; +extern int strcmp(char const *a , char const *b ) ; +extern int rand() ; +extern unsigned long strtoul(char const *str , char const *endptr , int base ) ; +void RandomFunc(unsigned long input[1] , unsigned long output[1] ) ; +extern int strncmp(char const *s1 , char const *s2 , unsigned long maxlen ) ; +extern int gettimeofday(struct timeval *tv , void *tz , ...) ; +extern int printf(char const *format , ...) ; +int main(int argc , char *argv[] ) ; +void megaInit(void) ; +extern unsigned long strlen(char const *s ) ; +extern long strtol(char const *str , char const *endptr , int base ) ; +extern unsigned long strnlen(char const *s , unsigned long maxlen ) ; +extern void *memcpy(void *s1 , void const *s2 , unsigned long size ) ; +struct timeval { + long tv_sec ; + long tv_usec ; +}; +extern void *malloc(unsigned long size ) ; +extern int scanf(char const *format , ...) ; +void RandomFunc(unsigned long input[1] , unsigned long output[1] ) +{ + unsigned long state[1] ; + unsigned long local2 ; + unsigned long local1 ; + unsigned int copy11 ; + + { + state[0UL] = (input[0UL] - 51238316UL) - 339126204UL; + local1 = 0UL; + while (local1 < 1UL) { + local2 = 0UL; + while (local2 < 1UL) { + if (state[0UL] == local2 * local1) { + state[0UL] = state[local1] | state[0UL]; + } else { + copy11 = *((unsigned int *)(& state[local2]) + 1); + *((unsigned int *)(& state[local2]) + 1) = *((unsigned int *)(& state[local2]) + 0); + *((unsigned int *)(& state[local2]) + 0) = copy11; + copy11 = *((unsigned int *)(& state[local2]) + 0); + *((unsigned int *)(& state[local2]) + 0) = *((unsigned int *)(& state[local2]) + 1); + *((unsigned int *)(& state[local2]) + 1) = copy11; + } + local2 += 2UL; + } + local1 ++; + } + output[0UL] = (((state[0UL] << 9UL) | (state[0UL] >> 55UL)) << 1UL) | (((state[0UL] << 9UL) | (state[0UL] >> 55UL)) >> 63UL); +} +} +int main(int argc , char *argv[] ) +{ + unsigned long input[1] ; + unsigned long output[1] ; + int randomFuns_i5 ; + unsigned long randomFuns_value6 ; + int randomFuns_main_i7 ; + + { + megaInit(); + if (argc != 2) { + printf("Call this program with %i arguments\n", 1); + exit(-1); + } else { + + } + randomFuns_i5 = 0; + while (randomFuns_i5 < 1) { + randomFuns_value6 = strtoul(argv[randomFuns_i5 + 1], 0, 10); + input[randomFuns_i5] = randomFuns_value6; + randomFuns_i5 ++; + } + RandomFunc(input, output); + if (output[0] == 18446743673988925439UL) { + printf("You win!\n"); + } else { + + } + randomFuns_main_i7 = 0; + while (randomFuns_main_i7 < 1) { + printf("%lu\n", output[randomFuns_main_i7]); + randomFuns_main_i7 ++; + } +} +} +void megaInit(void) +{ + + + { + +} +} diff --git a/pool/shard010/C/0138165_exception.c b/pool/shard010/C/0138165_exception.c new file mode 100644 index 0000000000000000000000000000000000000000..14a69957acbb5cbb2342825fe8eccd0074bacba4 --- /dev/null +++ b/pool/shard010/C/0138165_exception.c @@ -0,0 +1,69 @@ +/** + * @file + * @brief + * + * @date 24.07.2012 + * @author Anton Bondarev + */ + +#include +#include +#include +#include + +#include + +#include + +EMBOX_UNIT_INIT(mips_exception_init); + +void mips_c_exception_handler(pt_regs_t *regs) { + regs->pc += 4; +} + +second_exception_handler_t exception_handlers[MIPS_EXCEPTIONS_QUANTITY] = {mips_c_exception_handler}; + +/* +* Copy the generic exception handlers to their final destination. +* This will be overridden later as suitable for a particular +* configuration. +*/ +static void mips_setup_exc_table(void) { + size_t i; + + /* set all exception handler */ + for (i = 0; i < MIPS_EXCEPTIONS_QUANTITY; i ++) { + exception_handlers[i] = mips_c_exception_handler; + } +} + +/* setup correct exception table and enable exceptions */ +static int mips_exception_init(void) { + unsigned int tmp; + + /* clear BEV bit */ + tmp = mips_read_c0_status(); + tmp &= ~(ST0_BEV); + mips_write_c0_status(tmp); + + /* clear CauseIV bit */ + tmp = mips_read_c0_cause(); + tmp &= ~(CAUSE_IV); + mips_write_c0_cause(tmp); + + /* copy first exception handler to correct place */ + memcpy((void *)(EBASE + 0x180), &mips_first_exception_handler, 0x80); + + mips_setup_exc_table(); + + /* clear EXL bit */ + tmp = mips_read_c0_status(); + tmp &= ~(ST0_ERL); + mips_write_c0_status(tmp); + + return 0; +} + +void mips_exception_setup(mips_exception_type_t type, second_exception_handler_t handler) { + exception_handlers[type] = handler; +} diff --git a/pool/shard010/C/0138166_hi_util_hbm.c b/pool/shard010/C/0138166_hi_util_hbm.c new file mode 100644 index 0000000000000000000000000000000000000000..5d6920ac92ce4a9b81e699b87fed3404079be04e --- /dev/null +++ b/pool/shard010/C/0138166_hi_util_hbm.c @@ -0,0 +1,155 @@ +/**************************************************************************** + * + * Copyright (C) 2014-2016 Cisco and/or its affiliates. All rights reserved. + * Copyright (C) 2003-2013 Sourcefire, Inc. + * + * 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. You may not use, modify or + * distribute this program under any other version of the GNU General + * Public License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + * + ****************************************************************************/ + +/** +** @file hi_hbm.c +** +** @author Marc Norton +** +** @brief Implementation of a Horspool method of Boyer-Moore +** +*/ + +#include + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#include "hi_util_hbm.h" +#include "util.h" + +/* +* +* Boyer-Moore-Horspool for small pattern groups +* +*/ +#ifndef WIN32 /* To avoid naming conflict, Win32 will use the hbm_prepx() in mwm.c */ +int hbm_prepx(HBM_STRUCT *p, unsigned char * pat, int m) +{ + int k; + + if( !m ) return 0; + if( !p ) return 0; + + + p->P = pat; + + p->M = m; + + /* Compute normal Boyer-Moore Bad Character Shift */ + for(k = 0; k < 256; k++) p->bcShift[k] = m; + for(k = 0; k < m; k++) p->bcShift[pat[k]] = m - k - 1; + + return 1; +} +#endif + +/* +* +*/ +#ifndef WIN32 /* To avoid naming conflict, Win32 will use the hbm_prep() in mwm.c */ +HBM_STRUCT * hbm_prep(unsigned char * pat, int m) +{ + HBM_STRUCT *p; + + p = (HBM_STRUCT*)SnortAlloc(sizeof(HBM_STRUCT)); + + if( !hbm_prepx( p, pat, m ) ) + { + FatalError("Error initializing pattern matching. Check arguments."); + } + + return p; +} +#endif + +/* +* Boyer-Moore Horspool +* Does NOT use Sentinel Byte(s) +* Scan and Match Loops are unrolled and separated +* Optimized for 1 byte patterns as well +*/ +unsigned char * hbm_match(HBM_STRUCT * px, unsigned char *text, int n) +{ + unsigned char *pat, *t, *et, *q; + int m1, k; + short *bcShift; + + m1 = px->M-1; + pat = px->P; + bcShift= px->bcShift; + + t = text + m1; + et = text + n; + + /* Handle 1 Byte patterns - it's a faster loop */ + /* + if( !m1 ) + { + for( ;t= et )return 0;; + + t += (k=bcShift[*t]); + if( t >= et )return 0; + + } while( k ); + + /* Unrolled Match Loop */ + k = m1; + q = t - m1; + while( k >= 4 ) + { + if( pat[k] != q[k] )goto NoMatch; k--; + if( pat[k] != q[k] )goto NoMatch; k--; + if( pat[k] != q[k] )goto NoMatch; k--; + if( pat[k] != q[k] )goto NoMatch; k--; + } + /* Finish Match Loop */ + while( k >= 0 ) + { + if( pat[k] != q[k] )goto NoMatch; k--; + } + /* If matched - return 1st char of pattern in text */ + return q; + +NoMatch: + + /* Shift by 1, this replaces the good suffix shift */ + t++; + } + + return 0; +} + diff --git a/pool/shard010/C/0138167_iffib.c b/pool/shard010/C/0138167_iffib.c new file mode 100644 index 0000000000000000000000000000000000000000..f3498b42e486fd310ed1f9f7c103394bda91a9a9 --- /dev/null +++ b/pool/shard010/C/0138167_iffib.c @@ -0,0 +1,103 @@ +/*- + * Copyright (c) 2011 Alexander V. Chernikov + * Copyright (c) 2011 Christian S.J. Peron + * Copyright (c) 2011 Bjoern A. Zeeb + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * + * $FreeBSD$ + */ + +#include +#include +#include +#include + +#include +#include + +#include +#include +#include +#include + +#include "ifconfig.h" + +static void +fib_status(int s) +{ + struct ifreq ifr; + + memset(&ifr, 0, sizeof(ifr)); + strncpy(ifr.ifr_name, name, sizeof(ifr.ifr_name)); + + if (ioctl(s, SIOCGIFFIB, (caddr_t)&ifr) < 0) + return; + + /* Ignore if it is the default. */ + if (ifr.ifr_fib == 0) + return; + + printf("\tfib: %u\n", ifr.ifr_fib); +} + +static void +setiffib(const char *val, int dummy __unused, int s, + const struct afswtch *afp) +{ + unsigned long fib; + char *ep; + + fib = strtoul(val, &ep, 0); + if (*ep != '\0' || fib > UINT_MAX) { + warn("fib %s not valid", val); + return; + } + + strncpy(ifr.ifr_name, name, sizeof (ifr.ifr_name)); + ifr.ifr_fib = fib; + if (ioctl(s, SIOCSIFFIB, (caddr_t)&ifr) < 0) + warn("ioctl (SIOCSIFFIB)"); +} + +static struct cmd fib_cmds[] = { + DEF_CMD_ARG("fib", setiffib), +}; + +static struct afswtch af_fib = { + .af_name = "af_fib", + .af_af = AF_UNSPEC, + .af_other_status = fib_status, +}; + +static __constructor void +fib_ctor(void) +{ +#define N(a) (sizeof(a) / sizeof(a[0])) + size_t i; + + for (i = 0; i < N(fib_cmds); i++) + cmd_register(&fib_cmds[i]); + af_register(&af_fib); +#undef N +} diff --git a/pool/shard010/C/0138168_ooaofooa_S_DT_class.c b/pool/shard010/C/0138168_ooaofooa_S_DT_class.c new file mode 100644 index 0000000000000000000000000000000000000000..37d4d1986e3f2e5deb9153d0df95634e09c9e059 --- /dev/null +++ b/pool/shard010/C/0138168_ooaofooa_S_DT_class.c @@ -0,0 +1,157 @@ +/*---------------------------------------------------------------------------- + * File: ooaofooa_S_DT_class.c + * + * Class: Data Type (S_DT) + * Component: ooaofooa + * + * your copyright statement can go here (from te_copyright.body) + *--------------------------------------------------------------------------*/ + +#include "sys_sys_types.h" +#include "LOG_bridge.h" +#include "POP_bridge.h" +#include "T_bridge.h" +#include "ooaofooa_classes.h" + +/* + * Instance Loader (from string data). + */ +Escher_iHandle_t +ooaofooa_S_DT_instanceloader( Escher_iHandle_t instance, const c_t * avlstring[] ) +{ + Escher_iHandle_t return_identifier = 0; + ooaofooa_S_DT * self = (ooaofooa_S_DT *) instance; + /* Initialize application analysis class attributes. */ + self->DT_ID = (Escher_iHandle_t) Escher_atoi( avlstring[ 1 ] ); + self->Dom_ID = (Escher_iHandle_t) Escher_atoi( avlstring[ 2 ] ); + Escher_strcpy( self->Name, avlstring[ 3 ] ); + {i_t i = avlstring[ 4 + 1 ] - avlstring[ 4 ]; + self->Descrip = ( i > 0 ) ? (c_t *) Escher_malloc( i ) : ""; + while ( --i >= 0 ) { self->Descrip[ i ] = avlstring[ 4 ][ i ]; } + } + Escher_strcpy( self->DefaultValue, avlstring[ 5 ] ); + return return_identifier; +} + +/* + * Select any where using referential/identifying attribute set. + * If not_empty, relate this instance to the selected instance. + */ +void ooaofooa_S_DT_batch_relate( Escher_iHandle_t instance ) +{ + ooaofooa_S_DT * ooaofooa_S_DT_instance = (ooaofooa_S_DT *) instance; + ooaofooa_PE_PE * ooaofooa_PE_PErelated_instance1 = (ooaofooa_PE_PE *) Escher_instance_cache[ (intptr_t) ooaofooa_S_DT_instance->DT_ID ]; + if ( ooaofooa_PE_PErelated_instance1 ) { + ooaofooa_S_DT_R8001_Link( ooaofooa_PE_PErelated_instance1, ooaofooa_S_DT_instance ); + } + { + ooaofooa_S_DOM * ooaofooa_S_DOMrelated_instance1 = (ooaofooa_S_DOM *) Escher_instance_cache[ (intptr_t) ooaofooa_S_DT_instance->Dom_ID ]; + if ( ooaofooa_S_DOMrelated_instance1 ) { + ooaofooa_S_DT_R14_Link_contains_defined( ooaofooa_S_DOMrelated_instance1, ooaofooa_S_DT_instance ); + } + } +} + +/* + * Scan the extent for a matching instance. + */ +ooaofooa_S_DT * +ooaofooa_S_DT_AnyWhere1( Escher_UniqueID_t w_DT_ID ) +{ + ooaofooa_S_DT * w; + Escher_Iterator_s iter_S_DT; + Escher_IteratorReset( &iter_S_DT, &pG_ooaofooa_S_DT_extent.active ); + while ( (w = (ooaofooa_S_DT *) Escher_IteratorNext( &iter_S_DT )) != 0 ) { + if ( w->DT_ID == w_DT_ID ) { + return w; + } + } + return 0; +} + + +/* + * RELATE S_DOM TO S_DT ACROSS R14 + */ +void +ooaofooa_S_DT_R14_Link_contains_defined( ooaofooa_S_DOM * part, ooaofooa_S_DT * form ) +{ + /* Use TagEmptyHandleDetectionOn() to detect empty handle references. */ + form->Dom_ID = part->Dom_ID; + form->S_DOM_R14_defines_types_available_within = part; + Escher_SetInsertElement( &part->S_DT_R14_contains_defined, (Escher_ObjectSet_s *) form ); +} + +/* + * UNRELATE S_DOM FROM S_DT ACROSS R14 + */ +void +ooaofooa_S_DT_R14_Unlink_contains_defined( ooaofooa_S_DOM * part, ooaofooa_S_DT * form ) +{ + /* Use TagEmptyHandleDetectionOn() to detect empty handle references. */ + form->Dom_ID = 0; + form->S_DOM_R14_defines_types_available_within = 0; + Escher_SetRemoveElement( &part->S_DT_R14_contains_defined, (Escher_ObjectSet_s *) form ); +} + +/* Accessors to S_DT[R17] subtypes */ + + +/* + * RELATE PE_PE TO S_DT ACROSS R8001 + */ +void +ooaofooa_S_DT_R8001_Link( ooaofooa_PE_PE * supertype, ooaofooa_S_DT * subtype ) +{ + /* Use TagEmptyHandleDetectionOn() to detect empty handle references. */ + subtype->DT_ID = supertype->Element_ID; + /* Optimized linkage for S_DT->PE_PE[R8001] */ + subtype->PE_PE_R8001 = supertype; + /* Optimized linkage for PE_PE->S_DT[R8001] */ + supertype->R8001_subtype = subtype; + supertype->R8001_object_id = ooaofooa_S_DT_CLASS_NUMBER; +} + + +/* + * UNRELATE PE_PE FROM S_DT ACROSS R8001 + */ +void +ooaofooa_S_DT_R8001_Unlink( ooaofooa_PE_PE * supertype, ooaofooa_S_DT * subtype ) +{ + /* Use TagEmptyHandleDetectionOn() to detect empty handle references. */ + subtype->PE_PE_R8001 = 0; + supertype->R8001_subtype = 0; + supertype->R8001_object_id = 0; +} + + +/* + * Dump instances in SQL format. + */ +void +ooaofooa_S_DT_instancedumper( Escher_iHandle_t instance ) +{ + ooaofooa_S_DT * self = (ooaofooa_S_DT *) instance; + printf( "INSERT INTO S_DT VALUES ( %ld,%ld,'%s','%s','%s' );\n", + ((long)self->DT_ID & ESCHER_IDDUMP_MASK), + ((long)self->Dom_ID & ESCHER_IDDUMP_MASK), + self->Name, + self->Descrip, + self->DefaultValue ); +} +/* + * Statically allocate space for the instance population for this class. + * Allocate space for the class instance and its attribute values. + * Depending upon the collection scheme, allocate containoids (collection + * nodes) for gathering instances into free and active extents. + */ +static Escher_SetElement_s ooaofooa_S_DT_container[ ooaofooa_S_DT_MAX_EXTENT_SIZE ]; +static ooaofooa_S_DT ooaofooa_S_DT_instances[ ooaofooa_S_DT_MAX_EXTENT_SIZE ]; +Escher_Extent_t pG_ooaofooa_S_DT_extent = { + {0,0}, {0,0}, &ooaofooa_S_DT_container[ 0 ], + (Escher_iHandle_t) &ooaofooa_S_DT_instances, + sizeof( ooaofooa_S_DT ), 0, ooaofooa_S_DT_MAX_EXTENT_SIZE + }; + + diff --git a/pool/shard010/C/0138169_main_low_power.c b/pool/shard010/C/0138169_main_low_power.c new file mode 100644 index 0000000000000000000000000000000000000000..06cab7d82a440de0f8b521c9e0f5e14dfb8dc064 --- /dev/null +++ b/pool/shard010/C/0138169_main_low_power.c @@ -0,0 +1,428 @@ +/* + FreeRTOS V7.5.3 - Copyright (C) 2013 Real Time Engineers Ltd. + All rights reserved + + VISIT http://www.FreeRTOS.org TO ENSURE YOU ARE USING THE LATEST VERSION. + + *************************************************************************** + * * + * FreeRTOS provides completely free yet professionally developed, * + * robust, strictly quality controlled, supported, and cross * + * platform software that has become a de facto standard. * + * * + * Help yourself get started quickly and support the FreeRTOS * + * project by purchasing a FreeRTOS tutorial book, reference * + * manual, or both from: http://www.FreeRTOS.org/Documentation * + * * + * Thank you! * + * * + *************************************************************************** + + This file is part of the FreeRTOS distribution. + + FreeRTOS is free software; you can redistribute it and/or modify it under + the terms of the GNU General Public License (version 2) as published by the + Free Software Foundation >>!AND MODIFIED BY!<< the FreeRTOS exception. + + >>! NOTE: The modification to the GPL is included to allow you to distribute + >>! a combined work that includes FreeRTOS without being obliged to provide + >>! the source code for proprietary components outside of the FreeRTOS + >>! kernel. + + FreeRTOS is distributed in the hope that it will be useful, but WITHOUT ANY + WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + FOR A PARTICULAR PURPOSE. Full license text is available from the following + link: http://www.freertos.org/a00114.html + + 1 tab == 4 spaces! + + *************************************************************************** + * * + * Having a problem? Start by reading the FAQ "My application does * + * not run, what could be wrong?" * + * * + * http://www.FreeRTOS.org/FAQHelp.html * + * * + *************************************************************************** + + http://www.FreeRTOS.org - Documentation, books, training, latest versions, + license and Real Time Engineers Ltd. contact details. + + http://www.FreeRTOS.org/plus - A selection of FreeRTOS ecosystem products, + including FreeRTOS+Trace - an indispensable productivity tool, a DOS + compatible FAT file system, and our tiny thread aware UDP/IP stack. + + http://www.OpenRTOS.com - Real Time Engineers ltd license FreeRTOS to High + Integrity Systems to sell under the OpenRTOS brand. Low cost OpenRTOS + licenses offer ticketed support, indemnification and middleware. + + http://www.SafeRTOS.com - High Integrity Systems also provide a safety + engineered and independently SIL3 certified version for use in safety and + mission critical applications that require provable dependability. + + 1 tab == 4 spaces! +*/ + +/* **************************************************************************** + * When configCREATE_LOW_POWER_DEMO is set to 1 in FreeRTOSConfig.h main() will + * call main_low_power(), which is defined in this file. main_low_power() + * demonstrates FreeRTOS tick suppression being used to allow the MCU to be + * placed into both the low power deep sleep mode and the low power software + * standby mode. When configCREATE_LOW_POWER_DEMO is set to 0 main will + * instead call main_full(), which is a more comprehensive RTOS demonstration. + * **************************************************************************** + * + * This application demonstrates the FreeRTOS tickless idle mode (tick + * suppression). See http://www.freertos.org/low-power-tickless-rtos.html + * The demo is configured to execute on the Renesas RX100 RSK. + * + * Functionality: + * + * + Two tasks are created, an Rx task and a Tx task. + * + * + The Rx task repeatedly blocks on a queue to wait for data. The Rx task + * toggles LED 0 each time is receives a value from the queue. + * + * + The Tx task repeatedly enters the Blocked state for an amount of time + * that is set by the position of the potentiometer. On exiting the blocked + * state the Tx task sends a value through the queue to the Rx task (causing + * the Rx task to exit the blocked state and toggle LED 0). + * + * If the value read from the potentiometer is less than or equal to + * mainSOFTWARE_STANDBY_DELAY then the Tx task blocks for the equivalent + * number of milliseconds. For example, if the sampled analog value is + * 2000, then the Tx task blocks for 2000ms. Blocking for a finite period + * allows the kernel to stop the tick interrupt and place the RX100 into + * deep sleep mode. + * + * If the value read form the potentiometer is greater than + * mainSOFTWARE_STANDBY_DELAY then the Tx task blocks on a semaphore with + * an infinite timeout. Blocking with an infinite timeout allows the kernel + * to stop the tick interrupt and place the RX100 into software standby + * mode. Pressing a button will generate an interrupt that causes the RX100 + * to exit software standby mode. The interrupt service routine 'gives' the + * semaphore to unblock the Tx task. + * + * + * Using the Demo and Observed Behaviour: + * + * 1) Turn the potentiometer completely counter clockwise. + * + * 2) Program the RX100 with the application, then disconnect the programming/ + * debugging hardware to ensure power readings are not effected by any + * connected interfaces. + * + * 3) Start the application running. LED 0 will toggle quickly because the + * potentiometer is turned to its lowest value. LED 1 will be illuminated + * when the RX100 is not in a power saving mode, but will appear to be off + * because most execution time is spent in a sleep mode. Led 2 will be + * illuminated when the RX100 is in deep sleep mode, and will appear to be + * always on, again because most execution time is spent in deep sleep mode. + * The LEDs are turned on and off by the application defined pre and post + * sleep macros (see the definitions of configPRE_SLEEP_PROCESSING() and + * configPOST_SLEEP_PROCESSING() in FreeRTOSConfig.h). + * + * 4) Slowly turn the potentiometer in the clockwise direction. This will + * increase the value read from the potentiometer, which will increase the + * time the Tx task spends in the Blocked state, which will therefore + * decrease the frequency at which the Tx task sends data to the queue (and + * the rate at which LED 0 is toggled). + * + * 5) Keep turning the potentiometer in the clockwise direction. Eventually + * the value read from the potentiometer will go above + * mainSOFTWARE_STANDBY_DELAY, causing the Tx task to block on the semaphore + * with an infinite timeout. LED 0 will stop toggling because the Tx task is + * no longer sending to the queue. LED 1 and LED 2 will both be off because + * the RX100 is neither running or in deep sleep mode (it is in software + * standby mode). + * + * 6) Turn the potentiometer counter clockwise again to ensure its value goes + * back below mainSOFTWARE_STANDBY_DELAY. + * + * 7) Press any of the three buttons to generate an interrupt. The interrupt + * will take the RX100 out of software standby mode, and the interrupt + * service routine will unblock the Tx task by 'giving' the semaphore. LED 0 + * will then start to toggle again. + * + */ + + +/* Hardware specific includes. */ +#include "platform.h" +#include "r_switches_if.h" + +/* Kernel includes. */ +#include "FreeRTOS.h" +#include "task.h" +#include "queue.h" +#include "semphr.h" + +/* Common demo includes. */ +#include "partest.h" + +/* Priorities at which the Rx and Tx tasks are created. */ +#define configQUEUE_RECEIVE_TASK_PRIORITY ( tskIDLE_PRIORITY + 1 ) +#define configQUEUE_SEND_TASK_PRIORITY ( tskIDLE_PRIORITY + 2 ) + +/* The number of items the queue can hold. This is 1 as the Rx task will +remove items as they are added so the Tx task should always find the queue +empty. */ +#define mainQUEUE_LENGTH ( 1 ) + +/* The LED used to indicate that a value has been received on the queue. */ +#define mainQUEUE_LED ( 0 ) + +/* The LED used to indicate that full power is being used (the MCU is not in +deep sleep or software standby mode). */ +#define mainFULL_POWER_LED ( 1 ) + +/* The LED used to indicate that deep sleep mode is being used. */ +#define mainDEEP_SLEEP_LED ( 2 ) + +/* The Tx task sends to the queue with a frequency that is set by the value +read from the potentiometer until the value goes above that set by the +mainSOFTWARE_STANDBY_DELAY constant - at which time the Tx task instead blocks +indefinitely on a semaphore. */ +#define mainSOFTWARE_STANDBY_DELAY ( 3000UL ) + +/* A block time of zero simply means "don't block". */ +#define mainDONT_BLOCK ( 0 ) + +/* The value that is sent from the Tx task to the Rx task on the queue. */ +#define mainQUEUED_VALUE ( 100UL ) + +/*-----------------------------------------------------------*/ + +/* + * The Rx and Tx tasks as described at the top of this file. + */ +static void prvQueueReceiveTask( void *pvParameters ); +static void prvQueueSendTask( void *pvParameters ); + +/* + * Reads and returns the value of the ADC connected to the potentiometer built + * onto the RSK. + */ +static unsigned short prvReadPOT( void ); + +/* + * The handler for the interrupt generated when any of the buttons are pressed. + */ +__interrupt void vButtonInterrupt( void ); + +/*-----------------------------------------------------------*/ + +/* The queue to pass data from the Tx task to the Rx task. */ +static xQueueHandle xQueue = NULL; + +/* The semaphore that is 'given' by interrupts generated from button pushes. */ +static xSemaphoreHandle xSemaphore = NULL; + +/*-----------------------------------------------------------*/ + +void main_low_power( void ) +{ + /* Create the queue. */ + xQueue = xQueueCreate( mainQUEUE_LENGTH, sizeof( unsigned long ) ); + configASSERT( xQueue ); + + /* Create the semaphore that is 'given' by an interrupt generated from a + button push. */ + vSemaphoreCreateBinary( xSemaphore ); + configASSERT( xSemaphore ); + + /* Make sure the semaphore starts in the expected state - no button pushes + have yet occurred. A block time of zero can be used as it is guaranteed + that the semaphore will be available because it has just been created. */ + xSemaphoreTake( xSemaphore, mainDONT_BLOCK ); + + /* Start the two tasks as described at the top of this file. */ + xTaskCreate( prvQueueReceiveTask, "Rx", configMINIMAL_STACK_SIZE, NULL, configQUEUE_RECEIVE_TASK_PRIORITY, NULL ); + xTaskCreate( prvQueueSendTask, "TX", configMINIMAL_STACK_SIZE, NULL, configQUEUE_SEND_TASK_PRIORITY, NULL ); + + /* The CPU is currently running, not sleeping, so turn on the LED that + shows the CPU is not in a sleep mode. */ + vParTestSetLED( mainFULL_POWER_LED, pdTRUE ); + + /* Start the scheduler running running. */ + vTaskStartScheduler(); + + /* If all is well the next line of code will not be reached as the + scheduler will be running. If the next line is reached then it is likely + there was insufficient FreeRTOS heap available for the idle task and/or + timer task to be created. See http://www.freertos.org/a00111.html. */ + for( ;; ); +} +/*-----------------------------------------------------------*/ + +static void prvQueueSendTask( void *pvParameters ) +{ +portTickType xDelay; +const unsigned long ulValueToSend = mainQUEUED_VALUE; + + /* Remove compiler warning about unused parameter. */ + ( void ) pvParameters; + + for( ;; ) + { + /* The delay period between successive sends to the queue is set by + the potentiometer reading. */ + xDelay = ( portTickType ) prvReadPOT(); + + /* If the block time is greater than 3000 milliseconds then block + indefinitely waiting for a button push. */ + if( xDelay > mainSOFTWARE_STANDBY_DELAY ) + { + /* As this is an indefinite delay the kernel will place the CPU + into software standby mode the next time the idle task runs. */ + xSemaphoreTake( xSemaphore, portMAX_DELAY ); + } + else + { + /* Convert a time in milliseconds to a time in ticks. */ + xDelay /= portTICK_RATE_MS; + + /* Place this task in the blocked state until it is time to run + again. As this is not an indefinite sleep the kernel will place + the CPU into the deep sleep state when the idle task next runs. */ + vTaskDelay( xDelay ); + } + + /* Send to the queue - causing the queue receive task to flash its LED. + It should not be necessary to block on the queue send because the Rx + task will have removed the last queued item. */ + xQueueSend( xQueue, &ulValueToSend, mainDONT_BLOCK ); + } +} +/*-----------------------------------------------------------*/ + +static void prvQueueReceiveTask( void *pvParameters ) +{ +unsigned long ulReceivedValue; + + /* Remove compiler warning about unused parameter. */ + ( void ) pvParameters; + + for( ;; ) + { + /* Wait until something arrives in the queue - this will block + indefinitely provided INCLUDE_vTaskSuspend is set to 1 in + FreeRTOSConfig.h. */ + xQueueReceive( xQueue, &ulReceivedValue, portMAX_DELAY ); + + /* To get here something must have arrived, but is it the expected + value? If it is, toggle the LED. */ + if( ulReceivedValue == mainQUEUED_VALUE ) + { + vParTestToggleLED( mainQUEUE_LED ); + } + } +} +/*-----------------------------------------------------------*/ + +void vPreSleepProcessing( unsigned long ulExpectedIdleTime ) +{ + /* Called by the kernel before it places the MCU into a sleep mode because + configPRE_SLEEP_PROCESSING() is #defined to vPreSleepProcessing(). + + NOTE: Additional actions can be taken here to get the power consumption + even lower. For example, the ADC input used by this demo could be turned + off here, and then back on again in the post sleep processing function. + For maximum power saving ensure all unused pins are in their lowest power + state. */ + + /* Avoid compiler warnings about the unused parameter. */ + ( void ) ulExpectedIdleTime; + + /* Is the MCU about to enter deep sleep mode or software standby mode? */ + if( SYSTEM.SBYCR.BIT.SSBY == 0 ) + { + /* Turn on the LED that indicates deep sleep mode is being entered. */ + vParTestSetLED( mainDEEP_SLEEP_LED, pdTRUE ); + } + else + { + /* Software standby mode is being used, so no LEDs are illuminated to + ensure minimum power readings are obtained. Ensure the Queue LED is + also off. */ + vParTestSetLED( mainQUEUE_LED, pdFALSE ); + } + + /* Turn off the LED that indicates full power is being used. */ + vParTestSetLED( mainFULL_POWER_LED, pdFALSE ); +} +/*-----------------------------------------------------------*/ + +void vPostSleepProcessing( unsigned long ulExpectedIdleTime ) +{ + /* Called by the kernel when the MCU exits a sleep mode because + configPOST_SLEEP_PROCESSING is #defined to vPostSleepProcessing(). */ + + /* Avoid compiler warnings about the unused parameter. */ + ( void ) ulExpectedIdleTime; + + /* Turn off the LED that indicates deep sleep mode, and turn on the LED + that indicates full power is being used. */ + vParTestSetLED( mainDEEP_SLEEP_LED, pdFALSE ); + vParTestSetLED( mainFULL_POWER_LED, pdTRUE ); +} +/*-----------------------------------------------------------*/ + +static unsigned short prvReadPOT( void ) +{ +unsigned short usADCValue; +const unsigned short usMinADCValue = 128; + + /* Start an ADC scan. */ + S12AD.ADCSR.BIT.ADST = 1; + while( S12AD.ADCSR.BIT.ADST == 1 ) + { + /* Just waiting for the ADC scan to complete. Inefficient + polling! */ + } + + usADCValue = S12AD.ADDR4; + + /* Don't let the ADC value get too small as the LED behaviour will look + erratic. */ + if( usADCValue < usMinADCValue ) + { + usADCValue = usMinADCValue; + } + + return usADCValue; +} +/*-----------------------------------------------------------*/ + +#pragma vector = VECT_ICU_IRQ0, VECT_ICU_IRQ1, VECT_ICU_IRQ4 +__interrupt void vButtonInterrupt1( void ) +{ +long lHigherPriorityTaskWoken = pdFALSE; + + /* The semaphore is only created when the build is configured to create the + low power demo. */ + if( xSemaphore != NULL ) + { + /* This interrupt will bring the CPU out of deep sleep and software + standby modes. Give the semaphore that was used to place the Tx task + into an indefinite sleep. */ + if( uxQueueMessagesWaitingFromISR( xSemaphore ) == 0 ) + { + xSemaphoreGiveFromISR( xSemaphore, &lHigherPriorityTaskWoken ); + } + else + { + /* The semaphore was already available, so the task is not blocked + on it and there is no point giving it. */ + } + + /* If giving the semaphore caused a task to leave the Blocked state, + and the task that left the Blocked state has a priority equal to or + above the priority of the task that this interrupt interrupted, then + lHigherPriorityTaskWoken will have been set to pdTRUE inside the call + to xSemaphoreGiveFromISR(), and calling portYIELD_FROM_ISR() will cause + a context switch to the unblocked task. */ + portYIELD_FROM_ISR( lHigherPriorityTaskWoken ); + } +} + diff --git a/pool/shard010/C/0138170_sysinfo_cpu.c b/pool/shard010/C/0138170_sysinfo_cpu.c new file mode 100644 index 0000000000000000000000000000000000000000..0731bcb54aeeaa868a4b5e80b3b3ea80c8fa165c --- /dev/null +++ b/pool/shard010/C/0138170_sysinfo_cpu.c @@ -0,0 +1,230 @@ +/* cpu data for xfce4-sysinfo-plugin + + Copyright (C) 2013, 2014 Jarryd Beck + +This file is part of xfce4-sysinfo-plugin. + +xfce4-sysinfo-plugin 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. + +xfce4-sysinfo-plugin 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 xfce4-sysinfo-plugin; see the file COPYING. If not see +. + +*/ + +#include +#include + +#include "xfce4-sysinfo-plugin/plugins.h" + +//data for output +#define DATA_FIELDS 5 +//what we need to record +#define RECORD_FIELDS 6 +#define TOOLTIP_SIZE 150 + +enum +{ + CPU_IDLE, + CPU_NICE, + CPU_SYS, + CPU_IOWAIT, + CPU_USER, + CPU_TOTAL +}; + +static gchar* data_names[DATA_FIELDS] = + { + "Idle", + "Nice", + "System", + "IO Wait", + "User" + }; + +typedef struct +{ + double* last; + double* current; + double* percentages; + + gchar tooltip[TOOLTIP_SIZE]; +} CPUData; + +static void +get_data(double* data) +{ + glibtop_cpu cpu; + glibtop_get_cpu(&cpu); + + data[CPU_USER] = cpu.user; + data[CPU_NICE] = cpu.nice; + data[CPU_SYS] = cpu.sys; + data[CPU_IOWAIT] = cpu.iowait; + data[CPU_TOTAL] = cpu.total; +} + +void +cpu_get_data(SysinfoPlugin* plugin, SysinfoPluginData* data) +{ + CPUData* the_data = (CPUData*)plugin->plugin_data; + + //swap the buffers + double* current = the_data->last; + double* last = the_data->current; + the_data->last = last; + the_data->current = current; + + get_data(current); + + //the percentage is the difference between the current and last divided + //by the difference in the total + + double totaldelta = + current[CPU_TOTAL] - last[CPU_TOTAL]; + + double* p = the_data->percentages; + p[CPU_USER] = (current[CPU_USER] - last[CPU_USER]) / totaldelta; + p[CPU_NICE] = (current[CPU_NICE] - last[CPU_NICE]) / totaldelta; + p[CPU_SYS] = (current[CPU_SYS] - last[CPU_SYS]) / totaldelta; + p[CPU_IOWAIT] = (current[CPU_IOWAIT] - last[CPU_IOWAIT]) / totaldelta; + + //multiply to percentage and round + //ignore background + size_t i = 1; + while (i != DATA_FIELDS) + { + p[i] = round(p[i] * 100); + ++i; + } + + data->data = p; +} + +static void +cpu_get_range +( + SysinfoPlugin* plugin, + double min, + double max, + double* display_min, + double* display_max +) +{ + //always display 0 to 100 + *display_min = 0; + *display_max = 100; +} + +static gchar* +cpu_get_tooltip(SysinfoPlugin* plugin) +{ + CPUData* data = (CPUData*)plugin->plugin_data; + gchar* tooltip = data->tooltip; + + double* p = data->percentages; + + g_snprintf( + tooltip, + TOOLTIP_SIZE, + "== CPU Usage ==\n\nUser: %d%%\nNice: %d%%\nSystem: %d%%\nIO Wait: %d%%", + (int)p[CPU_USER], + (int)p[CPU_NICE], + (int)p[CPU_SYS], + (int)p[CPU_IOWAIT] + ); + + return tooltip; +} + +static void +cpu_close(SysinfoPlugin* plugin) +{ + CPUData* data = (CPUData*)plugin->plugin_data; + + g_free(data->last); + g_free(data->current); + g_free(data->percentages); + + g_free(data); + + g_free(plugin->colors); + + g_free(plugin); +} + +static void +cpu_reset_colors(SysinfoPlugin* plugin) +{ + SysinfoColor* c = plugin->colors; + + c[CPU_IDLE].red = 0; + c[CPU_IDLE].green = 0; + c[CPU_IDLE].blue = 0; + + c[CPU_NICE].red = 0x00 / 255.; + c[CPU_NICE].green = 0xa3 / 255.; + c[CPU_NICE].blue = 0xff / 255.; + + c[CPU_SYS].red = 0x00 / 255.; + c[CPU_SYS].green = 0x92 / 255.; + c[CPU_SYS].blue = 0xe6 / 255.; + + c[CPU_IOWAIT].red = 0x00 / 255.; + c[CPU_IOWAIT].green = 0x2f / 255.; + c[CPU_IOWAIT].blue = 0x3d / 255.; + + c[CPU_USER].red = 0x00 / 255.; + c[CPU_USER].green = 0x72 / 255.; + c[CPU_USER].blue = 0xb3 / 255.; +} + +static void +init_color(SysinfoPlugin* plugin) +{ + SysinfoColor* c = g_new(SysinfoColor, DATA_FIELDS); + + plugin->colors = c; + + cpu_reset_colors(plugin); +} + +SysinfoPlugin* +sysinfo_data_plugin_init() +{ + SysinfoPlugin* plugin = g_new(SysinfoPlugin, 1); + + plugin->plugin_name = "CPU Usage"; + plugin->num_data = DATA_FIELDS; + plugin->data_names = data_names; + + init_color(plugin); + + //initialise the stats buffers + CPUData* data = g_new(CPUData, 1); + data->last = g_new(double, RECORD_FIELDS); + data->current = g_new(double, RECORD_FIELDS); + data->percentages = g_new(double, DATA_FIELDS); + + //get some data to start from + //put it in current because next round will swap it to last + get_data(data->current); + + plugin->plugin_data = data; + + plugin->get_data = &cpu_get_data; + plugin->get_range = &cpu_get_range; + plugin->get_tooltip = &cpu_get_tooltip; + plugin->reset_colors = &cpu_reset_colors; + plugin->close = &cpu_close; + + return plugin; +} diff --git a/pool/shard010/C/0138171_displaylist_depths_test10.c b/pool/shard010/C/0138171_displaylist_depths_test10.c new file mode 100644 index 0000000000000000000000000000000000000000..dc93ac1793d0530dafd422cd82831ed62d6a3082 --- /dev/null +++ b/pool/shard010/C/0138171_displaylist_depths_test10.c @@ -0,0 +1,150 @@ +/* + * Copyright (C) 2007, 2009, 2010, 2011 Free Software Foundation, Inc. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + * + */ + +/* + * Sandro Santilli, strk@keybit.net + * + * Test "Skipping frames backward" + * + * run as ./displaylist_depths_test10 + * + * Timeline: + * + * Frame | 1 | 2 | 3 | 4 | 5 | 6 | 7 | + * --------+---+---+---+---+---+---+---+ + * Event | | * | P | R | | | J | + * + * P = place (by PlaceObject2) + * R = Remove (by RemoveObject2 tag) + * J = jump + * * = jump target + * + * Description: + * + * frame3: DisplayObject placed at depth -16381 + * frame4: DisplayObject at depth -16381 removed + * frame7: jump back to frame 2 and stop + * + * Expected behaviour: + * + * A single instance have been constructed in total. + */ + +#include "ming_utils.h" + +#include +#include +#include + +#define OUTPUT_VERSION 6 +#define OUTPUT_FILENAME "displaylist_depths_test10.swf" + +SWFDisplayItem add_static_mc(SWFMovie mo, const char* name, int depth, int x, int y, int width, int height); + +SWFDisplayItem +add_static_mc(SWFMovie mo, const char* name, int depth, int x, int y, int width, int height) +{ + SWFShape sh; + SWFMovieClip mc; + SWFDisplayItem it; + + sh = make_fill_square (-(width/2), -(height/2), width, height, 255, 0, 0, 255, 0, 0); + mc = newSWFMovieClip(); + SWFMovieClip_add(mc, (SWFBlock)sh); + + SWFMovieClip_nextFrame(mc); + + it = SWFMovie_add(mo, (SWFBlock)mc); + SWFDisplayItem_setDepth(it, depth); + SWFDisplayItem_moveTo(it, x, y); + SWFDisplayItem_setName(it, name); + + return it; +} + + +int +main(int argc, char** argv) +{ + SWFMovie mo; + SWFMovieClip dejagnuclip; + SWFDisplayItem it1; + + + const char *srcdir="."; + if ( argc>1 ) + srcdir=argv[1]; + else + { + //fprintf(stderr, "Usage: %s \n", argv[0]); + //return 1; + } + + Ming_init(); + mo = newSWFMovieWithVersion(OUTPUT_VERSION); + SWFMovie_setDimension(mo, 800, 600); + SWFMovie_setRate (mo, 2); + + dejagnuclip = get_dejagnu_clip((SWFBlock)get_default_font(srcdir), 10, 0, 0, 800, 600); + SWFMovie_add(mo, (SWFBlock)dejagnuclip); + SWFMovie_nextFrame(mo); + + // Frame 2: nothing to do + SWFMovie_nextFrame(mo); + + // Frame 3: place a static DisplayObject at depth 3 (-16381) + it1 = add_static_mc(mo, "static3", 3, 10, 200, 20, 20); + SWFDisplayItem_addAction(it1, newSWFAction( + "_root.note(this+' onClipConstruct');" + " _root.check_equals(typeof(_root), 'movieclip');" + " if ( isNaN(_root.depth3Constructed) ) {" + " _root.depth3Constructed=1; " + " } else {" + " _root.depth3Constructed++;" + " }" + " _root.note('_root.depth3Constructed set to '+_root.depth3Constructed);" + ), SWFACTION_CONSTRUCT); + add_actions(mo, "check_equals(static3.getDepth(), -16381);"); + SWFMovie_nextFrame(mo); + + // Frame 4: remove DisplayObject at depth 3 (-16381) + SWFDisplayItem_remove(it1); + add_actions(mo, "check_equals(typeof(static3), 'undefined');"); + SWFMovie_nextFrame(mo); + + // Frame 5: nothing new + SWFMovie_nextFrame(mo); + + // Frame 6: nothing new + SWFMovie_nextFrame(mo); + + // Frame 7: go to frame 2 and stop + add_actions(mo, + "gotoAndStop(2); " + "check_equals(_root.depth3Constructed, 1);" + "check_equals(typeof(static3), 'undefined');" + "totals();" + ); + SWFMovie_nextFrame(mo); + + //Output movie + puts("Saving " OUTPUT_FILENAME ); + SWFMovie_save(mo, OUTPUT_FILENAME); + + return 0; +} diff --git a/pool/shard010/C/0138172_Power_Set.c b/pool/shard010/C/0138172_Power_Set.c new file mode 100644 index 0000000000000000000000000000000000000000..ae33c6cafaaf8999a6f92a027aeb9d1a15bfb16a --- /dev/null +++ b/pool/shard010/C/0138172_Power_Set.c @@ -0,0 +1,56 @@ +/* +POWER SET + +A power set of a set is the set of all possible subsets of +a given set S. +example - {a, b, c} : +Power Set = {}, {a}, {b}, {c}, {a, b}, {a, c}, {a, b}, {b, c}, + {a, b, c} + +Total elements in a power set of a set with n elements = 2^n +*/ + +#include + +void PowerSet(int a[], int b[], int n, int index) { + if (index == n) { + printf("{"); + for (int i = 0; i < n; i++) { + if (b[i] == 1) { + printf("%d ", a[i]); + } + } + printf("}\n"); + return; + } + PowerSet(a, b, n, index + 1); + b[index] = 1; + PowerSet(a, b, n, index + 1); + b[index] = 0; +} + +int main() { + int n; + scanf("%d", &n); + int a[n]; + int b[n]; + for (int i = 0; i < n; i++) { + scanf("%d", &a[i]); + b[i] = 0; + } + PowerSet(a, b, n, 0); +} + +/* +INPUT : n = 3 + a = [3, 15, 32] +OUTPUT : +{} +{32 } +{15 } +{15 32 } +{3 } +{3 32 } +{3 15 } +{3 15 32 } +*/ diff --git a/pool/shard010/C/0138173_cuddAddFind.c b/pool/shard010/C/0138173_cuddAddFind.c new file mode 100644 index 0000000000000000000000000000000000000000..77cf026feacc81d8ed34790824b0a653dd3bccf3 --- /dev/null +++ b/pool/shard010/C/0138173_cuddAddFind.c @@ -0,0 +1,316 @@ +/**CFile*********************************************************************** + + FileName [cuddAddFind.c] + + PackageName [cudd] + + Synopsis [Functions to find maximum and minimum in an ADD and to + extract the i-th bit.] + + Description [External procedures included in this module: +
    +
  • Cudd_addFindMax() +
  • Cudd_addFindMin() +
  • Cudd_addIthBit() +
+ Static functions included in this module: +
    +
  • addDoIthBit() +
] + + Author [Fabio Somenzi] + + Copyright [Copyright (c) 1995-2004, Regents of the University of Colorado + + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + + Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + Neither the name of the University of Colorado nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + POSSIBILITY OF SUCH DAMAGE.] + +******************************************************************************/ + +#include "misc/util/util_hack.h" +#include "cuddInt.h" + +ABC_NAMESPACE_IMPL_START + + + +/*---------------------------------------------------------------------------*/ +/* Constant declarations */ +/*---------------------------------------------------------------------------*/ + + +/*---------------------------------------------------------------------------*/ +/* Stucture declarations */ +/*---------------------------------------------------------------------------*/ + + +/*---------------------------------------------------------------------------*/ +/* Type declarations */ +/*---------------------------------------------------------------------------*/ + + +/*---------------------------------------------------------------------------*/ +/* Variable declarations */ +/*---------------------------------------------------------------------------*/ + +#ifndef lint +static char rcsid[] DD_UNUSED = "$Id: cuddAddFind.c,v 1.8 2004/08/13 18:04:45 fabio Exp $"; +#endif + + +/*---------------------------------------------------------------------------*/ +/* Macro declarations */ +/*---------------------------------------------------------------------------*/ + +/**AutomaticStart*************************************************************/ + +/*---------------------------------------------------------------------------*/ +/* Static function prototypes */ +/*---------------------------------------------------------------------------*/ + +static DdNode * addDoIthBit (DdManager *dd, DdNode *f, DdNode *index); + +/**AutomaticEnd***************************************************************/ + +/*---------------------------------------------------------------------------*/ +/* Definition of exported functions */ +/*---------------------------------------------------------------------------*/ + +/**Function******************************************************************** + + Synopsis [Finds the maximum discriminant of f.] + + Description [Returns a pointer to a constant ADD.] + + SideEffects [None] + +******************************************************************************/ +DdNode * +Cudd_addFindMax( + DdManager * dd, + DdNode * f) +{ + DdNode *t, *e, *res; + + statLine(dd); + if (cuddIsConstant(f)) { + return(f); + } + + res = cuddCacheLookup1(dd,Cudd_addFindMax,f); + if (res != NULL) { + return(res); + } + + t = Cudd_addFindMax(dd,cuddT(f)); + if (t == DD_PLUS_INFINITY(dd)) return(t); + + e = Cudd_addFindMax(dd,cuddE(f)); + + res = (cuddV(t) >= cuddV(e)) ? t : e; + + cuddCacheInsert1(dd,Cudd_addFindMax,f,res); + + return(res); + +} /* end of Cudd_addFindMax */ + + +/**Function******************************************************************** + + Synopsis [Finds the minimum discriminant of f.] + + Description [Returns a pointer to a constant ADD.] + + SideEffects [None] + +******************************************************************************/ +DdNode * +Cudd_addFindMin( + DdManager * dd, + DdNode * f) +{ + DdNode *t, *e, *res; + + statLine(dd); + if (cuddIsConstant(f)) { + return(f); + } + + res = cuddCacheLookup1(dd,Cudd_addFindMin,f); + if (res != NULL) { + return(res); + } + + t = Cudd_addFindMin(dd,cuddT(f)); + if (t == DD_MINUS_INFINITY(dd)) return(t); + + e = Cudd_addFindMin(dd,cuddE(f)); + + res = (cuddV(t) <= cuddV(e)) ? t : e; + + cuddCacheInsert1(dd,Cudd_addFindMin,f,res); + + return(res); + +} /* end of Cudd_addFindMin */ + + +/**Function******************************************************************** + + Synopsis [Extracts the i-th bit from an ADD.] + + Description [Produces an ADD from another ADD by replacing all + discriminants whose i-th bit is equal to 1 with 1, and all other + discriminants with 0. The i-th bit refers to the integer + representation of the leaf value. If the value is has a fractional + part, it is ignored. Repeated calls to this procedure allow one to + transform an integer-valued ADD into an array of ADDs, one for each + bit of the leaf values. Returns a pointer to the resulting ADD if + successful; NULL otherwise.] + + SideEffects [None] + + SeeAlso [Cudd_addBddIthBit] + +******************************************************************************/ +DdNode * +Cudd_addIthBit( + DdManager * dd, + DdNode * f, + int bit) +{ + DdNode *res; + DdNode *index; + + /* Use a constant node to remember the bit, so that we can use the + ** global cache. + */ + index = cuddUniqueConst(dd,(CUDD_VALUE_TYPE) bit); + if (index == NULL) return(NULL); + cuddRef(index); + + do { + dd->reordered = 0; + res = addDoIthBit(dd, f, index); + } while (dd->reordered == 1); + + if (res == NULL) { + Cudd_RecursiveDeref(dd, index); + return(NULL); + } + cuddRef(res); + Cudd_RecursiveDeref(dd, index); + cuddDeref(res); + return(res); + +} /* end of Cudd_addIthBit */ + + +/*---------------------------------------------------------------------------*/ +/* Definition of internal functions */ +/*---------------------------------------------------------------------------*/ + + +/*---------------------------------------------------------------------------*/ +/* Definition of static functions */ +/*---------------------------------------------------------------------------*/ + + +/**Function******************************************************************** + + Synopsis [Performs the recursive step for Cudd_addIthBit.] + + Description [Performs the recursive step for Cudd_addIthBit. + Returns a pointer to the BDD if successful; NULL otherwise.] + + SideEffects [None] + + SeeAlso [] + +******************************************************************************/ +static DdNode * +addDoIthBit( + DdManager * dd, + DdNode * f, + DdNode * index) +{ + DdNode *res, *T, *E; + DdNode *fv, *fvn; + int mask, value; + int v; + + statLine(dd); + /* Check terminal case. */ + if (cuddIsConstant(f)) { + mask = 1 << ((int) cuddV(index)); + value = (int) cuddV(f); + return((value & mask) == 0 ? DD_ZERO(dd) : DD_ONE(dd)); + } + + /* Check cache. */ + res = cuddCacheLookup2(dd,addDoIthBit,f,index); + if (res != NULL) return(res); + + /* Recursive step. */ + v = f->index; + fv = cuddT(f); fvn = cuddE(f); + + T = addDoIthBit(dd,fv,index); + if (T == NULL) return(NULL); + cuddRef(T); + + E = addDoIthBit(dd,fvn,index); + if (E == NULL) { + Cudd_RecursiveDeref(dd, T); + return(NULL); + } + cuddRef(E); + + res = (T == E) ? T : cuddUniqueInter(dd,v,T,E); + if (res == NULL) { + Cudd_RecursiveDeref(dd, T); + Cudd_RecursiveDeref(dd, E); + return(NULL); + } + cuddDeref(T); + cuddDeref(E); + + /* Store result. */ + cuddCacheInsert2(dd,addDoIthBit,f,index,res); + + return(res); + +} /* end of addDoIthBit */ + + +ABC_NAMESPACE_IMPL_END + + diff --git a/pool/shard010/C/0138174_xterm_kern.c b/pool/shard010/C/0138174_xterm_kern.c new file mode 100644 index 0000000000000000000000000000000000000000..1b4683fe3c4fe79be815d1dc6a6ccff601fa1e58 --- /dev/null +++ b/pool/shard010/C/0138174_xterm_kern.c @@ -0,0 +1,79 @@ +/* + * Copyright (C) 2002 Jeff Dike (jdike@karaya.com) + * Licensed under the GPL + */ + +#include "linux/errno.h" +#include "linux/slab.h" +#include "asm/semaphore.h" +#include "asm/irq.h" +#include "irq_user.h" +#include "kern_util.h" +#include "os.h" +#include "xterm.h" + +struct xterm_wait { + struct semaphore sem; + int fd; + int pid; + int new_fd; +}; + +static void xterm_interrupt(int irq, void *data, struct pt_regs *regs) +{ + struct xterm_wait *xterm = data; + int fd; + + fd = os_rcv_fd(xterm->fd, &xterm->pid); + if(fd == -EAGAIN) + return; + + xterm->new_fd = fd; + up(&xterm->sem); +} + +int xterm_fd(int socket, int *pid_out) +{ + struct xterm_wait *data; + int err, ret; + + data = kmalloc(sizeof(*data), GFP_KERNEL); + if(data == NULL){ + printk(KERN_ERR "xterm_fd : failed to allocate xterm_wait\n"); + return(-ENOMEM); + } + *data = ((struct xterm_wait) + { .sem = __SEMAPHORE_INITIALIZER(data->sem, 0), + .fd = socket, + .pid = -1, + .new_fd = -1 }); + + err = um_request_irq(XTERM_IRQ, socket, IRQ_READ, xterm_interrupt, + SA_INTERRUPT | SA_SHIRQ | SA_SAMPLE_RANDOM, + "xterm", data); + if(err){ + printk(KERN_ERR "xterm_fd : failed to get IRQ for xterm, " + "err = %d\n", err); + return(err); + } + down(&data->sem); + + free_irq(XTERM_IRQ, data); + + ret = data->new_fd; + *pid_out = data->pid; + kfree(data); + + return(ret); +} + +/* + * Overrides for Emacs so that we follow Linus's tabbing style. + * Emacs will notice this stuff at the end of the file and automatically + * adjust the settings for this buffer only. This must remain at the end + * of the file. + * --------------------------------------------------------------------------- + * Local variables: + * c-file-style: "linux" + * End: + */ diff --git a/pool/shard010/C/0138175_lapacke_dgeqrt_work.c b/pool/shard010/C/0138175_lapacke_dgeqrt_work.c new file mode 100644 index 0000000000000000000000000000000000000000..0cafdb0a854099ac109cf9e06854847cdd716bb5 --- /dev/null +++ b/pool/shard010/C/0138175_lapacke_dgeqrt_work.c @@ -0,0 +1,99 @@ +/***************************************************************************** + Copyright (c) 2014, Intel Corp. + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + * Neither the name of Intel Corporation nor the names of its contributors + may be used to endorse or promote products derived from this software + without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE + LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + THE POSSIBILITY OF SUCH DAMAGE. +****************************************************************************** +* Contents: Native middle-level C interface to LAPACK function dgeqrt +* Author: Intel Corporation +* Generated November 2015 +*****************************************************************************/ + +#include "lapacke_utils.h" + +lapack_int LAPACKE_dgeqrt_work( int matrix_layout, lapack_int m, lapack_int n, + lapack_int nb, double* a, lapack_int lda, + double* t, lapack_int ldt, double* work ) +{ + lapack_int info = 0; + if( matrix_layout == LAPACK_COL_MAJOR ) { + /* Call LAPACK function and adjust info */ + LAPACK_dgeqrt( &m, &n, &nb, a, &lda, t, &ldt, work, &info ); + if( info < 0 ) { + info = info - 1; + } + } else if( matrix_layout == LAPACK_ROW_MAJOR ) { + lapack_int lda_t = MAX(1,m); + lapack_int ldt_t = MAX(1,ldt); + double* a_t = NULL; + double* t_t = NULL; + /* Check leading dimension(s) */ + if( lda < n ) { + info = -6; + LAPACKE_xerbla( "LAPACKE_dgeqrt_work", info ); + return info; + } + if( ldt < MIN(m,n) ) { + info = -8; + LAPACKE_xerbla( "LAPACKE_dgeqrt_work", info ); + return info; + } + /* Allocate memory for temporary array(s) */ + a_t = (double*)LAPACKE_malloc( sizeof(double) * lda_t * MAX(1,n) ); + if( a_t == NULL ) { + info = LAPACK_TRANSPOSE_MEMORY_ERROR; + goto exit_level_0; + } + t_t = (double*) + LAPACKE_malloc( sizeof(double) * ldt_t * MAX(1,MIN(m,n)) ); + if( t_t == NULL ) { + info = LAPACK_TRANSPOSE_MEMORY_ERROR; + goto exit_level_1; + } + /* Transpose input matrices */ + LAPACKE_dge_trans( matrix_layout, m, n, a, lda, a_t, lda_t ); + /* Call LAPACK function and adjust info */ + LAPACK_dgeqrt( &m, &n, &nb, a_t, &lda_t, t_t, &ldt_t, work, &info ); + if( info < 0 ) { + info = info - 1; + } + /* Transpose output matrices */ + LAPACKE_dge_trans( LAPACK_COL_MAJOR, m, n, a_t, lda_t, a, lda ); + LAPACKE_dge_trans( LAPACK_COL_MAJOR, ldt, MIN(m,n), t_t, ldt_t, t, + ldt ); + /* Release memory and exit */ + LAPACKE_free( t_t ); +exit_level_1: + LAPACKE_free( a_t ); +exit_level_0: + if( info == LAPACK_TRANSPOSE_MEMORY_ERROR ) { + LAPACKE_xerbla( "LAPACKE_dgeqrt_work", info ); + } + } else { + info = -1; + LAPACKE_xerbla( "LAPACKE_dgeqrt_work", info ); + } + return info; +} diff --git a/pool/shard010/C/0138176_1e2.c b/pool/shard010/C/0138176_1e2.c new file mode 100644 index 0000000000000000000000000000000000000000..3a927866f249e42cb5fd984b23fc5eb6071c9f7b --- /dev/null +++ b/pool/shard010/C/0138176_1e2.c @@ -0,0 +1,57 @@ +#include + +int main() +{ + FILE *file = fopen("lusiadas-utf8.txt", "r"); + if(!file) + { + fprintf(stderr, "Erro a abrir ficheiro\n"); + return -1; + } + + int count[3] = {0}; + + for(;;) + { + int byte1 = getc(file); + if(byte1 == EOF) + { + break; + } + + if((byte1 & 0x80) == 0) + { + continue; + } + else if((byte1 & 0xe0) == 0xc0) + { + int byte2 = getc(file); + if(byte1 == 0xC3 && (byte2 == 0x83 || byte2 == 0xa3)) + { + ++count[0]; + } + else if(byte1 == 0xC3 && (byte2 == 0x95 || byte2 == 0xb5)) + { + ++count[1]; + } + else if(byte1 == 0xC3 && (byte2 == 0x87 || byte2 == 0xa7)) + { + ++count[2]; + } + } + else if((byte1 & 0xf0) == 0xe0) + { + getc(file); getc(file); + } + else if((byte1 & 0xf8) == 0xf0) + { + getc(file); getc(file); getc(file); + } + } + + printf("ã: %d\n", count[0]); + printf("õ: %d\n", count[1]); + printf("ç: %d\n", count[2]); + + return 0; +} diff --git a/pool/shard010/C/0138177_task01.c b/pool/shard010/C/0138177_task01.c new file mode 100644 index 0000000000000000000000000000000000000000..d2080d8d7a515cec9ba6211d317227fd7895f037 --- /dev/null +++ b/pool/shard010/C/0138177_task01.c @@ -0,0 +1,13 @@ +#include +int main (){ + float n, a, sum=0.0, avg=0.0; + scanf("%f", &n); + for(float i=0; i +#include +#include +#include + +#include "phonebook_opt_struct.h" + +/* original version */ +entry *findName(char lastName[], entry *pHead) +{ + while (pHead != NULL) { + if (strcasecmp(lastName, pHead->lastName) == 0) + return pHead; + pHead = pHead->pNext; + } + return NULL; +} + +entry *append(char lastName[], entry *e) +{ + /* allocate memory for the new entry and put lastName */ + e->pNext = (entry *) malloc(sizeof(entry)); + e = e->pNext; + strcpy(e->lastName, lastName); + e->pNext = NULL; + + return e; +} diff --git a/pool/shard010/C/0138179_htable-lookup.c b/pool/shard010/C/0138179_htable-lookup.c new file mode 100644 index 0000000000000000000000000000000000000000..d24df80a90e28aa563ced0d7d286510594793230 --- /dev/null +++ b/pool/shard010/C/0138179_htable-lookup.c @@ -0,0 +1,62 @@ +/* + * ===================================================================== + * Verze: 1.0 + * Vytvoreno: 04/27/2014 09:20:18 PM + * Autor: Tomáš Coufal + * Login: xcoufa09 + * Projekt: IJC - Projekt c. 2 - Priklad 2 + * ===================================================================== + */ + +#include "htable.h" + +/* Hledani zaznamu v tabulce + * --------------------------------------------------------------------- + * - hleda zaznam v tabulce, pokud jej nenajde, necha vytvorit novy + */ +struct htab_listitem * htab_lookup(htab_t *t, const char *key) +{ + unsigned int index = hash_function(key, t->size); + struct htab_listitem * item = (t->list)[index]; + + if (item == NULL) // na indexu neni zadny prvek + { + (t->list)[index] = htab_new(key); // pokusim se vytvorit + return t->list[index]; + } + + struct htab_listitem * itemPrev = item; + + while (item != NULL) + { + if (strcmp(item->key, key) == EXIT_SUCCESS) { return item; } + itemPrev = item; + item = item->next; + } + + return itemPrev->next = htab_new(key); +} + +/* Vytvoreni noveho zaznamu + * --------------------------------------------------------------------- + * - vytvori novy zaznam pro hash tabulku a vrati ukazatel na ni + * - zaznam obsahuje key, data = 0 a ukazatel next je NULL + * - pokud dojde k chybe (nedostatek pameti) vraci NULL + */ +struct htab_listitem * htab_new(const char *key) +{ + struct htab_listitem * item = malloc(sizeof(struct htab_listitem)); + if (item == NULL) { return NULL; } + + item->data = 0; + item->next = NULL; + + if ((item->key = malloc(sizeof(char) * (strlen(key) + 1))) == NULL) + { + free(item); + return NULL; + } + + strcpy(item->key, key); + return item; +} diff --git a/pool/shard010/C/0138180_luamariadb_close.c b/pool/shard010/C/0138180_luamariadb_close.c new file mode 100644 index 0000000000000000000000000000000000000000..56e1238ef68cb86ac4117d79c4216f54f356476c --- /dev/null +++ b/pool/shard010/C/0138180_luamariadb_close.c @@ -0,0 +1,52 @@ +LUA_API void conn_close_cont(int fd, short event, void *_userdata) +{ + DB_STATUS *bag = (DB_STATUS *)_userdata; + MYSQL *conn = (MYSQL *)bag->data; + lua_State *L = bag->L; + + int status = mysql_close_cont(conn, bag->status); + if (status) + { + wait_for_status(L, bag->ctx, conn, status, conn_close_cont, bag->extra); + } + else + { + lua_pushboolean(L, 1); + FAN_RESUME(L, NULL, 1); + UNREF_CO(bag->ctx); + } + + event_free(bag->event); + free(bag); +} + +/* +** Close a Connection object. +*/ +LUA_API int conn_close_start(lua_State *L) +{ + DB_CTX *ctx = (DB_CTX *)luaL_checkudata(L, 1, MARIADB_CONNECTION_METATABLE); + luaL_argcheck(L, ctx != NULL, 1, LUASQL_PREFIX "connection expected"); + if (ctx->closed) + { + lua_pushboolean(L, 0); + return 1; + } + else + { + ctx->closed = 1; + + int status = mysql_close_start(&ctx->my_conn); + if (status) + { + REF_CO(ctx); + wait_for_status(L, ctx, &ctx->my_conn, status, conn_close_cont, 0); + return lua_yield(L, 0); + } + else + { + lua_pushboolean(L, 1); + return 1; + } + } +} diff --git a/pool/shard010/C/0138181_slaveirq.c b/pool/shard010/C/0138181_slaveirq.c new file mode 100644 index 0000000000000000000000000000000000000000..d985c266354b190b6d0ea10014e7d6d56e414ffb --- /dev/null +++ b/pool/shard010/C/0138181_slaveirq.c @@ -0,0 +1,262 @@ +/* + $License: + Copyright (C) 2010 InvenSense Corporation, All Rights Reserved. + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. 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 . + $ + */ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "mpu.h" +#include "slaveirq.h" +#include "mldl_cfg.h" +#include "mpu-i2c.h" + + +struct slaveirq_dev_data { + struct miscdevice dev; + struct i2c_client *slave_client; + struct mpuirq_data data; + wait_queue_head_t slaveirq_wait; + int irq; + int pid; + int data_ready; + int timeout; +}; + +static int slaveirq_open(struct inode *inode, struct file *file) +{ + struct slaveirq_dev_data *data = + container_of(file->private_data, struct slaveirq_dev_data, dev); + + dev_dbg(data->dev.this_device, + "%s current->pid %d\n", __func__, current->pid); + data->pid = current->pid; + return 0; +} + +static int slaveirq_release(struct inode *inode, struct file *file) +{ + struct slaveirq_dev_data *data = + container_of(file->private_data, struct slaveirq_dev_data, dev); + dev_dbg(data->dev.this_device, "slaveirq_release\n"); + return 0; +} + +static ssize_t slaveirq_read(struct file *file, + char *buf, size_t count, loff_t *ppos) +{ + int len, err; + struct slaveirq_dev_data *data = + container_of(file->private_data, struct slaveirq_dev_data, dev); + + if (!data->data_ready) { + wait_event_interruptible_timeout(data->slaveirq_wait, + data->data_ready, + data->timeout); + } + + if (data->data_ready && NULL != buf + && count >= sizeof(data->data)) { + err = copy_to_user(buf, &data->data, sizeof(data->data)); + data->data.data_type = 0; + } else { + return 0; + } + if (err != 0) { + dev_err(data->dev.this_device, + "Copy to user returned %d\n", err); + return -EFAULT; + } + data->data_ready = 0; + len = sizeof(data->data); + return len; +} + +unsigned int slaveirq_poll(struct file *file, struct poll_table_struct *poll) +{ + int mask = 0; + struct slaveirq_dev_data *data = + container_of(file->private_data, struct slaveirq_dev_data, dev); + + poll_wait(file, &data->slaveirq_wait, poll); + if (data->data_ready) + mask |= POLLIN | POLLRDNORM; + return mask; +} + +static long slaveirq_ioctl(struct file *file, + unsigned int cmd, unsigned long arg) +{ + int retval = 0; + int tmp; + struct slaveirq_dev_data *data = + container_of(file->private_data, struct slaveirq_dev_data, dev); + + switch (cmd) { + case SLAVEIRQ_SET_TIMEOUT: + data->timeout = arg; + break; + + case SLAVEIRQ_GET_INTERRUPT_CNT: + tmp = data->data.interruptcount - 1; + if (data->data.interruptcount > 1) + data->data.interruptcount = 1; + + if (copy_to_user((int *) arg, &tmp, sizeof(int))) + return -EFAULT; + break; + case SLAVEIRQ_GET_IRQ_TIME: + if (copy_to_user((int *) arg, &data->data.irqtime, + sizeof(data->data.irqtime))) + return -EFAULT; + data->data.irqtime = 0; + break; + default: + retval = -EINVAL; + } + return retval; +} + +static irqreturn_t slaveirq_handler(int irq, void *dev_id) +{ + struct slaveirq_dev_data *data = (struct slaveirq_dev_data *)dev_id; + static int mycount; + struct timeval irqtime; + mycount++; + + data->data.interruptcount++; + + + + data->data_ready = 1; + + do_gettimeofday(&irqtime); + data->data.irqtime = (((long long) irqtime.tv_sec) << 32); + data->data.irqtime += irqtime.tv_usec; + data->data.data_type |= 1; + + wake_up_interruptible(&data->slaveirq_wait); + + return IRQ_HANDLED; + +} + +static const struct file_operations slaveirq_fops = { + .owner = THIS_MODULE, + .read = slaveirq_read, + .poll = slaveirq_poll, + +#if HAVE_COMPAT_IOCTL + .compat_ioctl = slaveirq_ioctl, +#endif +#if HAVE_UNLOCKED_IOCTL + .unlocked_ioctl = slaveirq_ioctl, +#endif + .open = slaveirq_open, + .release = slaveirq_release, +}; + +int slaveirq_init(struct i2c_adapter *slave_adapter, + struct ext_slave_platform_data *pdata, + char *name) +{ + + int res; + struct slaveirq_dev_data *data; + + if (!pdata->irq) + return -EINVAL; + + pdata->irq_data = kzalloc(sizeof(*data), + GFP_KERNEL); + data = (struct slaveirq_dev_data *) pdata->irq_data; + if (!data) + return -ENOMEM; + + data->dev.minor = MISC_DYNAMIC_MINOR; + data->dev.name = name; + data->dev.fops = &slaveirq_fops; + data->irq = pdata->irq; + data->pid = 0; + data->data_ready = 0; + data->timeout = 0; + + init_waitqueue_head(&data->slaveirq_wait); + + res = request_irq(data->irq, slaveirq_handler, IRQF_TRIGGER_RISING, + data->dev.name, data); + + if (res) { + dev_err(&slave_adapter->dev, + "myirqtest: cannot register IRQ %d\n", + data->irq); + goto out_request_irq; + } + + res = misc_register(&data->dev); + if (res < 0) { + dev_err(&slave_adapter->dev, + "misc_register returned %d\n", + res); + goto out_misc_register; + } + + return res; + +out_misc_register: + free_irq(data->irq, data); +out_request_irq: + kfree(pdata->irq_data); + pdata->irq_data = NULL; + + return res; +} + +void slaveirq_exit(struct ext_slave_platform_data *pdata) +{ + struct slaveirq_dev_data *data = pdata->irq_data; + + if (!pdata->irq_data || data->irq <= 0) + return; + + dev_info(data->dev.this_device, "Unregistering %s\n", + data->dev.name); + + free_irq(data->irq, data); + misc_deregister(&data->dev); + kfree(pdata->irq_data); + pdata->irq_data = NULL; +} diff --git a/pool/shard010/C/0138182_main.c b/pool/shard010/C/0138182_main.c new file mode 100644 index 0000000000000000000000000000000000000000..011d9c65bcfc57e506e7e86d9e9bd5b9ca6c2849 --- /dev/null +++ b/pool/shard010/C/0138182_main.c @@ -0,0 +1,200 @@ +/* + * Copyright (c) 2018 STMicroelectronics + * + * SPDX-License-Identifier: Apache-2.0 + */ + +#include +#include +#include + +#include +#include + +#include