content
stringlengths
19
48.2k
// waits for a connection to be made for the specified socket int accept_connection(int fd) { struct sockaddr_in ca; socklen_t sz = sizeof(ca); int client; if ((client = accept(fd, (struct sockaddr *)&ca, &sz)) == -1) epicfail("accept"); return client; }
/* * Search the lowest free LUN ID if the LUN ID is default, or check if the LUN ID is free otherwise, * and also return the LUN which comes just before where we want to insert an new LUN. */ static int scsi_dev_find_free_lun(struct spdk_scsi_dev *dev, int lun_id, struct spdk_scsi_lun **prev_lun) { struct spdk_scsi_lun *lun, *_prev_lun = NULL; if (prev_lun == NULL) { return -EINVAL; } if (lun_id == -1) { lun_id = 0; TAILQ_FOREACH(lun, &dev->luns, tailq) { if (lun->id > lun_id) { break; } lun_id = lun->id + 1; _prev_lun = lun; } if (lun_id >= SPDK_SCSI_DEV_MAX_LUN) { return -ENOSPC; } } else { TAILQ_FOREACH(lun, &dev->luns, tailq) { if (lun->id == lun_id) { return -EEXIST; } else if (lun->id > lun_id) { break; } _prev_lun = lun; } } *prev_lun = _prev_lun; return 0; }
/* Crap function, but does the job - assumes that if the first char matches * for the rest not to match is an error */ static int skip_string(FILE *file, const char *string) { int c; do { c = get_uncommented_char(file); } while (isspace(c)); if (c != *string++) { ungetc(c, file); return 0; } while (*string) { c = fgetc(file); if (c != *string++) { ungetc(c, file); return 0; } } return 1; }
/* ----------------------------------------------------------------------------------------------------------- Name: update_databases Description: Updates the databases Return: 0 if an error has occured, 1 if successfull ----------------------------------------------------------------------------------------------------------- */ int update_databases(void) { char data[BUFFER_SIZE_NETWORK_BLOCK_DATA]; size_t count; #define UPDATE_DATABASE_ERROR(settings) \ memcpy(error_message.function[error_message.total],"update_databases",16); \ memcpy(error_message.data[error_message.total],settings,sizeof(settings)-1); \ error_message.total++; \ return 0; memset(data,0,sizeof(data)); sscanf(current_block_height, "%zu", &count); if (count < XCASH_PROOF_OF_STAKE_BLOCK_HEIGHT-1) { UPDATE_DATABASE_ERROR("Could not get the current block height"); } count--; snprintf(data,sizeof(data)-1,"%zu",count); if (add_block_verifiers_round_statistics((const char*)data) == 0) { UPDATE_DATABASE_ERROR("Could not update the block verifiers round statistics"); } if (add_round_statistics() == 0) { UPDATE_DATABASE_ERROR("Could not update the round statistics"); } return 1; #undef UPDATE_DATABASE_ERROR }
/** * Convert BIGNUM to bytea to BIGNUM */ BIGNUM * bytea_to_bignum(bytea *raw) { BIGNUM *bn = BN_new(); if (VARSIZE(raw) == VARHDRSZ) { BN_zero(bn); } else { bn = BN_bin2bn((const unsigned char *) VARDATA(raw) + 1, VARSIZE(raw) - VARHDRSZ - 1, NULL); BN_set_negative(bn, (*VARDATA(raw) & 0x01) == 0x01); } return bn; }
/* * Copyright (C) 2016 UC Berkeley * * This file is subject to the terms and conditions of the GNU Lesser * General Public License v2.1. See the file LICENSE in the top level * directory for more details. */ /** * @ingroup boards_hamilton * @brief Support for the HamiltonIoT Hamilton board. * @{ * * @file * @brief Board specific definitions for the Hamilton board * * @author Michael Andersen <m.andersen@cs.berkeley.edu> * @author Hyung-Sin Kim <hs.kim@cs.berkeley.edu> */ #ifndef BOARD_H #define BOARD_H #include "cpu.h" #include "periph_conf.h" #include "periph_cpu.h" #ifdef __cplusplus extern "C" { #endif /** * @name xtimer configuration * @{ */ #define XTIMER_DEV TIMER_DEV(1) #define XTIMER_CHAN (0) /** @} */ /** * @name AT86RF233 configuration * @{ */ #define AT86RF2XX_PARAM_SPI SPI_DEV(0) #define AT86RF2XX_PARAM_SPI_CLK SPI_CLK_5MHZ #define AT86RF2XX_PARAM_CS GPIO_PIN(PB, 31) #define AT86RF2XX_PARAM_INT GPIO_PIN(PB, 0) #define AT86RF2XX_PARAM_SLEEP GPIO_PIN(PA, 20) #define AT86RF2XX_PARAM_RESET GPIO_PIN(PB, 15) /** @} */ /** * @name LED pin definitions and handlers * @{ */ #define LED0_PIN GPIO_PIN(0, 19) #define LED0_PORT PORT->Group[0] #define LED0_MASK (1 << 19) #define LED0_ON (LED0_PORT.OUTCLR.reg = LED0_MASK) #define LED0_OFF (LED0_PORT.OUTSET.reg = LED0_MASK) #define LED0_TOGGLE (LED0_PORT.OUTTGL.reg = LED0_MASK) /** @} */ /** * @name Button pin definitions * @{ */ #define BTN0_PIN GPIO_PIN(0, 18) #define BTN0_MODE GPIO_IN_PU /** @} */ /** * @name FXOS8700 configuration * Note that another fxos8700 operation option, CONFIG_FXOS8700_USE_ACC_RAW_VALUES, * need to be set according to the application purposes * @{ */ #define FXOS8700_PARAM_I2C I2C_DEV(0) #define FXOS8700_PARAM_ADDR (0x1E) #define FXOS8700_PARAM_RENEW_INTERVAL (1000000ul) /** @} */ /** * @name HDC1080 configuration * @{ */ #define HDC1000_PARAM_I2C I2C_DEV(0) #define HDC1000_PARAM_ADDR (0x40) #define HDC1000_PARAM_RES HDC1000_14BIT #define HDC1000_PARAM_RENEW_INTERVAL (1000000ul) /** @} */ /** * @name EKMB (PIR motion sensor) configuration * @{ */ #define PIR_PARAM_GPIO GPIO_PIN(PA, 6) #define PIR_PARAM_ACTIVE_HIGH (1) /** @} */ /** * @name PULSE_COUNTER configuration * @{ */ #define PULSE_COUNTER_GPIO BTN0_PIN #define PULSE_COUNTER_GPIO_FLANK GPIO_FALLING /** @} */ /** * @name TMP00X configuration * Note that two other tmp006 operation options, TMP00X_USE_LOW_POWER and * TMP00X_USE_RAW_VALUES, need to be set according to the application purpose * @{ */ #define TMP00X_PARAM_I2C I2C_DEV(0) #define TMP00X_PARAM_ADDR (0x44) #define TMP00X_PARAM_RATE TMP00X_CONFIG_CR_AS2 /** @} */ /** * @name ToDo: APDS9007 configuration * @{ */ /** @} */ #ifdef __cplusplus } #endif #endif /* BOARD_H */ /** @} */
/* a callback for the GC (marking active objects) */ static void registry_mark(void *ignore) { (void)ignore; #if RUBY_REG_DBG == 1 Registry.print(); #endif lock_registry(); obj_s *obj; fio_ht_for_each(obj_s, node, obj, registry.store) rb_gc_mark(obj->obj); unlock_registry(); }
/********************************** SimulateSignatureISMforSite ***********************************/ /* Simulates genetic signatures under an infinite sites model (ISM) for a given site. The branch where this mutation is placed is chosen according to its length. */ void SimulateSignatureISMforSite (TreeNode *p, int genome, int site, int newState, long int *seed) { static double cumBranchLength, uniform; int cell, anccell, ancState; if (p != NULL) { cell = p->label; if (p->isHealthyRoot == YES) { cumBranchLength = 0; uniform = RandomUniform(seed) * totalTreeLength; } else { anccell = p->anc->label; ancState = data[genome][anccell][site]; cumBranchLength += p->branchLength; if (cumBranchLength < uniform || allSites[site].numMutations > 0) { data[genome][cell][site] = ancState; } else { data[genome][cell][site] = newState; if (genome == MATERNAL) allSites[site].numMutationsMaternal++; else if (genome == PATERNAL) allSites[site].numMutationsPaternal++; allSites[site].numMutations++; numMU++; } } SimulateSignatureISMforSite (p->left, genome, site, newState, seed); SimulateSignatureISMforSite (p->right, genome, site, newState, seed); } }
#include<stdio.h> #include<math.h> int snt(int n) { for(int i=2;i<n;i++) { if(n%i==0) return 0; } return 1; } int chiahet(int n) { printf("%d\n",n); fflush(stdout); char s[4]; scanf("%s",s); if(s[0]=='y') return 1; return 0; } int main() { int dem=0; for(int i=2;i<50;i++) { if(snt(i)==1) { if(chiahet(i)==1) { dem++; if(i*i<=100 && chiahet(i*i)==1) dem++; } if (dem>1) break; } } if(dem<=1) printf("prime"); else printf("composite"); }
//============================================================================================== //Function to read board layout and count number of Openings and Islands //============================================================================================== void init_board() { int i; int r,c; openings=0; for(r=0;r<h;++r) { for(c=0;c<w;++c) { int index=c*h+r; board[index].rb = r?r-1:r; board[index].re = r==h-1?r:r+1; board[index].cb = c?c-1:c; board[index].ce = c==w-1?c:c+1; } } for(i=0;i<size;++i) { board[i].premium= -(board[i].number=getnumber(i))-2; } for(i=0;i<size;++i) if(!board[i].number && !board[i].opening) { if(++openings>MAXOPS) error("Too many openings"); size_ops[openings]=0; process_opening(openings,i); } for(i=0;i<size;++i) if(!board[i].opening && !board[i].island && !board[i].mine) { if(++islands>MAXISLS) error("Too many islands"); size_isls[islands]=0; process_island(islands,i); } }
/* comedi/drivers/ke_counter.c Comedi driver for Kolter-Electronic PCI Counter 1 Card COMEDI - Linux Control and Measurement Device Interface Copyright (C) 2000 David A. Schleef <ds@schleef.org> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ /* Driver: ke_counter Description: Driver for Kolter Electronic Counter Card Devices: [Kolter Electronic] PCI Counter Card (ke_counter) Author: Michael Hillmann Updated: Mon, 14 Apr 2008 15:42:42 +0100 Status: tested Configuration Options: [0] - PCI bus of device (optional) [1] - PCI slot of device (optional) If bus/slot is not specified, the first supported PCI device found will be used. This driver is a simple driver to read the counter values from Kolter Electronic PCI Counter Card. */ #include "../comedidev.h" #include "comedi_pci.h" #define CNT_DRIVER_NAME "ke_counter" #define PCI_VENDOR_ID_KOLTER 0x1001 #define CNT_CARD_DEVICE_ID 0x0014 /*-- function prototypes ----------------------------------------------------*/ static int cnt_attach(struct comedi_device *dev, struct comedi_devconfig *it); static int cnt_detach(struct comedi_device *dev); static DEFINE_PCI_DEVICE_TABLE(cnt_pci_table) = { { PCI_VENDOR_ID_KOLTER, CNT_CARD_DEVICE_ID, PCI_ANY_ID, PCI_ANY_ID, 0, 0, 0}, { 0} }; MODULE_DEVICE_TABLE(pci, cnt_pci_table); /*-- board specification structure ------------------------------------------*/ struct cnt_board_struct { const char *name; int device_id; int cnt_channel_nbr; int cnt_bits; }; static const struct cnt_board_struct cnt_boards[] = { { .name = CNT_DRIVER_NAME, .device_id = CNT_CARD_DEVICE_ID, .cnt_channel_nbr = 3, .cnt_bits = 24} }; #define cnt_board_nbr (sizeof(cnt_boards)/sizeof(struct cnt_board_struct)) /*-- device private structure -----------------------------------------------*/ struct cnt_device_private { struct pci_dev *pcidev; }; #define devpriv ((struct cnt_device_private *)dev->private) static struct comedi_driver cnt_driver = { .driver_name = CNT_DRIVER_NAME, .module = THIS_MODULE, .attach = cnt_attach, .detach = cnt_detach, }; static int __devinit cnt_driver_pci_probe(struct pci_dev *dev, const struct pci_device_id *ent) { return comedi_pci_auto_config(dev, cnt_driver.driver_name); } static void __devexit cnt_driver_pci_remove(struct pci_dev *dev) { comedi_pci_auto_unconfig(dev); } static struct pci_driver cnt_driver_pci_driver = { .id_table = cnt_pci_table, .probe = &cnt_driver_pci_probe, .remove = __devexit_p(&cnt_driver_pci_remove) }; static int __init cnt_driver_init_module(void) { int retval; retval = comedi_driver_register(&cnt_driver); if (retval < 0) return retval; cnt_driver_pci_driver.name = (char *)cnt_driver.driver_name; return pci_register_driver(&cnt_driver_pci_driver); } static void __exit cnt_driver_cleanup_module(void) { pci_unregister_driver(&cnt_driver_pci_driver); comedi_driver_unregister(&cnt_driver); } module_init(cnt_driver_init_module); module_exit(cnt_driver_cleanup_module); /*-- counter write ----------------------------------------------------------*/ /* This should be used only for resetting the counters; maybe it is better to make a special command 'reset'. */ static int cnt_winsn(struct comedi_device *dev, struct comedi_subdevice *s, struct comedi_insn *insn, unsigned int *data) { int chan = CR_CHAN(insn->chanspec); outb((unsigned char)((data[0] >> 24) & 0xff), dev->iobase + chan * 0x20 + 0x10); outb((unsigned char)((data[0] >> 16) & 0xff), dev->iobase + chan * 0x20 + 0x0c); outb((unsigned char)((data[0] >> 8) & 0xff), dev->iobase + chan * 0x20 + 0x08); outb((unsigned char)((data[0] >> 0) & 0xff), dev->iobase + chan * 0x20 + 0x04); /* return the number of samples written */ return 1; } /*-- counter read -----------------------------------------------------------*/ static int cnt_rinsn(struct comedi_device *dev, struct comedi_subdevice *s, struct comedi_insn *insn, unsigned int *data) { unsigned char a0, a1, a2, a3, a4; int chan = CR_CHAN(insn->chanspec); int result; a0 = inb(dev->iobase + chan * 0x20); a1 = inb(dev->iobase + chan * 0x20 + 0x04); a2 = inb(dev->iobase + chan * 0x20 + 0x08); a3 = inb(dev->iobase + chan * 0x20 + 0x0c); a4 = inb(dev->iobase + chan * 0x20 + 0x10); result = (a1 + (a2 * 256) + (a3 * 65536)); if (a4 > 0) result = result - s->maxdata; *data = (unsigned int)result; /* return the number of samples read */ return 1; } /*-- attach -----------------------------------------------------------------*/ static int cnt_attach(struct comedi_device *dev, struct comedi_devconfig *it) { struct comedi_subdevice *subdevice; struct pci_dev *pci_device = NULL; struct cnt_board_struct *board; unsigned long io_base; int error, i; /* allocate device private structure */ error = alloc_private(dev, sizeof(struct cnt_device_private)); if (error < 0) return error; /* Probe the device to determine what device in the series it is. */ for_each_pci_dev(pci_device) { if (pci_device->vendor == PCI_VENDOR_ID_KOLTER) { for (i = 0; i < cnt_board_nbr; i++) { if (cnt_boards[i].device_id == pci_device->device) { /* was a particular bus/slot requested? */ if ((it->options[0] != 0) || (it->options[1] != 0)) { /* are we on the wrong bus/slot? */ if (pci_device->bus->number != it->options[0] || PCI_SLOT(pci_device->devfn) != it->options[1]) { continue; } } dev->board_ptr = cnt_boards + i; board = (struct cnt_board_struct *) dev->board_ptr; goto found; } } } } printk(KERN_WARNING "comedi%d: no supported board found! (req. bus/slot: %d/%d)\n", dev->minor, it->options[0], it->options[1]); return -EIO; found: printk(KERN_INFO "comedi%d: found %s at PCI bus %d, slot %d\n", dev->minor, board->name, pci_device->bus->number, PCI_SLOT(pci_device->devfn)); devpriv->pcidev = pci_device; dev->board_name = board->name; /* enable PCI device and request regions */ error = comedi_pci_enable(pci_device, CNT_DRIVER_NAME); if (error < 0) { printk(KERN_WARNING "comedi%d: " "failed to enable PCI device and request regions!\n", dev->minor); return error; } /* read register base address [PCI_BASE_ADDRESS #0] */ io_base = pci_resource_start(pci_device, 0); dev->iobase = io_base; /* allocate the subdevice structures */ error = alloc_subdevices(dev, 1); if (error < 0) return error; subdevice = dev->subdevices + 0; dev->read_subdev = subdevice; subdevice->type = COMEDI_SUBD_COUNTER; subdevice->subdev_flags = SDF_READABLE /* | SDF_COMMON */ ; subdevice->n_chan = board->cnt_channel_nbr; subdevice->maxdata = (1 << board->cnt_bits) - 1; subdevice->insn_read = cnt_rinsn; subdevice->insn_write = cnt_winsn; /* select 20MHz clock */ outb(3, dev->iobase + 248); /* reset all counters */ outb(0, dev->iobase); outb(0, dev->iobase + 0x20); outb(0, dev->iobase + 0x40); printk(KERN_INFO "comedi%d: " CNT_DRIVER_NAME " attached.\n", dev->minor); return 0; } /*-- detach -----------------------------------------------------------------*/ static int cnt_detach(struct comedi_device *dev) { if (devpriv && devpriv->pcidev) { if (dev->iobase) comedi_pci_disable(devpriv->pcidev); pci_dev_put(devpriv->pcidev); } printk(KERN_INFO "comedi%d: " CNT_DRIVER_NAME " remove\n", dev->minor); return 0; } MODULE_AUTHOR("Comedi http://www.comedi.org"); MODULE_DESCRIPTION("Comedi low-level driver"); MODULE_LICENSE("GPL");
#ifndef TrajectoryStateTransform_H #define TrajectoryStateTransform_H #include "DataFormats/TrajectoryState/interface/PTrajectoryStateOnDet.h" #include "DataFormats/TrackReco/interface/TrackFwd.h" #include "DataFormats/L1TrackTrigger/interface/TTTrack.h" #include "DataFormats/L1TrackTrigger/interface/TTTypes.h" class TrajectoryStateOnSurface; class FreeTrajectoryState; class TrackingGeometry; class Surface; class MagneticField; namespace trajectoryStateTransform { PTrajectoryStateOnDet persistentState(const TrajectoryStateOnSurface& ts, unsigned int detid); TrajectoryStateOnSurface transientState(const PTrajectoryStateOnDet& ts, const Surface* surface, const MagneticField* field); /// Construct a FreeTrajectoryState from the reco::Track innermost or outermost state, /// does not require access to tracking geometry FreeTrajectoryState initialFreeState(const reco::Track& tk, const MagneticField* field, bool withErr = true); FreeTrajectoryState initialFreeStateL1TTrack(const TTTrack<Ref_Phase2TrackerDigi_>& tk, const MagneticField* field, bool withErr = false); FreeTrajectoryState innerFreeState(const reco::Track& tk, const MagneticField* field, bool withErr = true); FreeTrajectoryState outerFreeState(const reco::Track& tk, const MagneticField* field, bool withErr = true); /// Construct a TrajectoryStateOnSurface from the reco::Track innermost or outermost state, /// requires access to tracking geometry TrajectoryStateOnSurface innerStateOnSurface(const reco::Track& tk, const TrackingGeometry& geom, const MagneticField* field, bool withErr = true); TrajectoryStateOnSurface outerStateOnSurface(const reco::Track& tk, const TrackingGeometry& geom, const MagneticField* field, bool withErr = true); } // namespace trajectoryStateTransform // backward compatibility struct TrajectoryStateTransform {}; #endif
/* The two main Key parser entry point. */ http_key_parse_status http_key_parse(void *buffer, size_t buffer_size, const char *key_string, size_t key_string_len, http_key_params_t *params, size_t *num_params) { key_arena_t *arena; assert(buffer); assert(buffer_size > HTTP_KEY_MIN_ARENA); arena = key_arena_create(NULL, buffer, buffer_size); return key_parse_arena(arena, key_string, key_string_len, params, num_params); }
/* * This function is used by qsort to sort a T2P_PAGE* array of page structures * by page number. If the page numbers are the same, we fall back to comparing * directory numbers to preserve the order of the input file. */ int t2p_cmp_t2p_page(const void* e1, const void* e2){ int d; d = (int32)(((T2P_PAGE*)e1)->page_number) - (int32)(((T2P_PAGE*)e2)->page_number); if(d == 0){ d = (int32)(((T2P_PAGE*)e1)->page_directory) - (int32)(((T2P_PAGE*)e2)->page_directory); } return d; }
/* just set the position, don't flag it. all that's handled later.*/ void isp_set_sprite_xy(ISPRITESYS *iss, ISPID id, coord_t x, coord_t y) { if(id < ISP_MAX_SPRITES) { iss->list[id].sp_buf.x = x + iss->list[id].xoffs; iss->list[id].sp_buf.y = y + iss->list[id].yoffs; } }
// NOTE: API changed to pass nStrBufLen (total buffer size including terminator) // instead of nStrBufMax (max index value) bool gslc_ElemXKeyPadValGet(gslc_tsGui* pGui, gslc_tsElemRef* pElemRef, char* pStrBuf, uint8_t nStrBufLen) { gslc_tsXKeyPad* pKeyPad = (gslc_tsXKeyPad*)gslc_GetXDataFromRef(pGui, pElemRef, GSLC_TYPEX_KEYPAD, __LINE__); if (!pKeyPad) return false; char* pBufPtr = pStrBuf; uint8_t nMaxCopyLen = nStrBufLen - 1; if (!pKeyPad->bValPositive) { *pBufPtr = KEYPAD_DISP_NEGATIVE; pBufPtr++; nMaxCopyLen--; } strncpy(pBufPtr, pKeyPad->acValStr, nMaxCopyLen); pStrBuf[nStrBufLen-1] = '\0'; return true; }
#include<stdio.h> int main() { long long int a,b; int A[100],B[100],C[100]; scanf("%lld %lld",&a,&b); int ka=0; while(a>0) { A[ka++]=a%3; a=a/3; } int kb=0; while(b>0) { B[kb++]=b%3; b=b/3; } while(ka<kb) A[ka++]=0; while(kb<ka) B[kb++]=0; int i; for(i=0;i<ka;i++) { C[i]=B[i]-A[i]; if(C[i]<0) C[i]+=3; } int kc=i; long long int c=0; long long int prod=1; for(i=0;i<kc;i++) { c = c + prod*C[i]; prod*=3; } printf("%lld\n",c); return 0; }
/* Initialise the condition attribute to use the monotonic clock. This means we * shouldn't have problems if the real time clock starts dancing about. */ void pwait_initialise(pthread_cond_t *signal) { pthread_condattr_t attr; ASSERT_PTHREAD(pthread_condattr_init(&attr)); ASSERT_PTHREAD(pthread_condattr_setclock(&attr, CLOCK_MONOTONIC)); ASSERT_PTHREAD(pthread_cond_init(signal, &attr)); }
/* the all-in-one tick function */ uint64_t m6581_tick(m6581_t* sid, uint64_t pins) { CHIPS_ASSERT(sid); pins = _m6581_tick(sid, pins); if (pins & M6581_CS) { if (pins & M6581_RW) { pins = _m6581_read(sid, pins); } else { _m6581_write(sid, pins); } } sid->pins = pins; return pins; }
// Function to be executed in the parent process context void execute_parent_process(pid_t cpid, int write_fd) { int count = 0; const int length = 512; char buffer[length]; printf("Parent - Process Id: %d\n", getpid()); printf("Parent - Process Id (Parent): %d\n", getppid()); printf("fork - Process Id: %d\n", cpid); FILE *fp = fdopen(write_fd, "w"); while (count < message_limit) { sprintf(buffer, "%d -- %s", count, test_msg); fprintf(fp, "%s\n", buffer); fflush(fp); ++count; } printf("******* Parent process is ending ***** \n"); printf("Parent - Wait for child process\n"); wait_for_child(cpid); }
/* * gmpr_get_intf_hosts * * Get a list of all active hosts on the specified interface. Returns a * pointer to a host entry, to which other host entries are linked. * Returns NULL* if there are no active hosts on the interface. * * The pointer should be returned via gmpr_destroy_host_group() when the * caller is done. * * This could be heinous and does not scale if there are lots of hosts * on the interface. */ gmpr_intf_host_entry * gmpr_get_intf_hosts (gmp_instance_id instance_id, gmpx_intf_id intf_id) { gmpr_instance *instance; gmpr_host *host; gmpr_intf *intf; gmpr_intf_host_entry *host_list; gmpr_intf_host_entry *cur_host; gmpx_patnode *host_node; instance = gmpr_get_instance(instance_id); intf = gmpr_intf_lookup(instance, intf_id); if (!intf) return NULL; host_list = NULL; host_node = NULL; while (TRUE) { host_node = gmpx_patricia_get_next(intf->rintf_host_root, host_node); host = gmpr_patnode_to_host(host_node); if (!host) break; if (!gmpr_host_is_active(host)) { continue; } cur_host = gmpx_malloc_block(gmpr_intf_host_tag); if (!cur_host) break; memmove(cur_host->gih_host_addr.gmp_addr, host->rhost_addr.gmp_addr, instance->rinst_addrlen); if (host_list) cur_host->gih_next = host_list; host_list = cur_host; } return host_list; }
// Returns results similar to HLSL's lit(), but uses Toksvig's math to calculate // a more appealing specular value based on mip'ing normal maps that approach // perfect mirrors for higher mip levels. Use this instead of oLit when using // normal maps with a mip chain. inline float4 oLitToksvig(oIN(float3, _UnnormalizedSurfaceNormalVector), oIN(float3, _LightVector), oIN(float3, _EyeVector), float _SpecularExponent) { float NLen = length(_UnnormalizedSurfaceNormalVector); float NDotL = dot(_UnnormalizedSurfaceNormalVector / NLen, _LightVector); float Kd = max(0.0f, NDotL); float Ks = oPhongSpecularToksvig(NDotL, _UnnormalizedSurfaceNormalVector, NLen, _LightVector, _EyeVector, _SpecularExponent); return float4(1.0f, Kd, Ks, 1.0f); }
//************************************************************************* // jerase_brute_recovery - Does a brute force attempt to recover the data // Since we don't have clue which device is bad we use 1 device as a control // to detect correctness. This means we can only correct n_parity_devs-1 failures. //************************************************************************** int jerase_brute_recovery(lio_erasure_plan_t *plan, int chunk_size, int n_devs, int n_parity_devs, int *badmap, char **ptr, char **eptr, char **pwork, char *magic) { int i, ncheck; int index[n_parity_devs]; if (jerase_control_check(plan, chunk_size, n_devs, n_parity_devs, badmap, ptr, eptr, pwork, magic) == 0) return(0); memset(badmap, 0, sizeof(int)*n_devs); ncheck = (magic != NULL) ? n_parity_devs+1 : n_parity_devs; for (i=1; i<ncheck; i++) { memset(index, 0, sizeof(int)*n_parity_devs); if (jerase_brute_recurse(0, index, plan, chunk_size, n_devs, n_parity_devs, i, badmap, ptr, eptr, pwork, magic) == 0) return(0); } return(1); }
//***************************************************************************** // // I'm kinda annoyed, but the built-in atol doesn't seem to handle the number // zero properly. It also seems to SUCK. So this catches that case. WTF. // I'm a terrible coder and this is probably the worst way to do this. // TI, I am disappoint. // // \param ulVal The unsigned long value to convert to a hex string. // \param cBuff A character buffer to placed the formatted hex string into. // \param iLength The minimum length of the string to print out. Note this is // ONLY a minimum! Make sure the buffer is large enough. // //***************************************************************************** void myLong2Hex(unsigned long ulVal, char *cBuff, int iLength) { unsigned long ulTest; int jj; int offset = 0; for(jj = 0; jj < 8; jj++) { ulTest = (ulVal & 0xF0000000) >> 28; if (offset > 1 || ulTest > 0 || jj >= (8-iLength)) { if (ulTest < 10) { cBuff[offset] = (char) (ulTest + 48); } else { cBuff[offset] = (char) (ulTest + 55); } offset++; } ulVal = ulVal << 4; } cBuff[offset] = '\0'; return; }
/*------------------------------------------------------------------------- OMPI change: Per http://www.gnu.org/software/libc/manual/html_mono/libc.html#Hooks-for-Malloc, we can define the __malloc_initialize_hook variable to be a function that is invoked before the first allocation is ever performed. We use this hook to wholly replace the underlying allocator to our own allocator if a few conditions are met. Remember that this hook is called probably at the very very very beginning of the process. MCA parameters haven't been setup yet -- darn near nothing has been setup yet. Indeed, we're effectively in signal context because we can't call anything that calls malloc. So we can basically have some hard-coded tests for things to see if we want to setup to use our internal ptmalloc2 or not. */ static void *opal_memory_linux_malloc_hook(size_t sz, const __malloc_ptr_t caller) { return public_mALLOc(sz); }
/* Attempt to match parallel work. Return ADLB_NOTHING if couldn't redirect, ADLB_SUCCESS on successful redirect, ADLB_ERROR on error. inline_data: non-null if we already have task body */ static adlb_code attempt_match_par_work(int type, int answer, const void *payload, int length, int parallelism) { ADLB_CHECK_MSG(parallelism <= xlb_s.layout.my_workers, "Task with parallelism %i can never execute: " "server has %i workers!\n", parallelism, xlb_s.layout.my_workers); adlb_code code; int parallel_workers[parallelism]; if (xlb_requestqueue_parallel_workers(type, parallelism, parallel_workers)) { code = send_parallel_work(parallel_workers, XLB_WORK_UNIT_ID_NULL, type, answer, payload, length, parallelism); ADLB_CHECK(code); if (xlb_s.perfc_enabled) { xlb_task_bypass_count(type, false, true); } return ADLB_SUCCESS; } return ADLB_NOTHING; }
/** Interval widen f by g. Assume that f and g are cubes, and f is term-contained in g */ LddNode * lddIntervalWidenRecur (LddManager *ldd, LddNode *f, LddNode *g) { DdNode *one, *zero, *res, *F, *G; DdNode *fv, *fnv, *gv, *gnv; DdNode *rest, *gVar; lincons_t fCons, gCons; one = DD_ONE(CUDD); zero = Cudd_Not (one); if (g == one) return g; if (f == zero) return g; F = Cudd_Regular (f); G = Cudd_Regular (g); fCons = lddC (ldd, F->index); gCons = lddC (ldd, G->index); fv = Cudd_NotCond (cuddT (F), f != F); fnv = Cudd_NotCond (cuddE (F), f != F); if (! (THEORY->term_equals (THEORY->get_term (fCons), THEORY->get_term (gCons)))) return lddIntervalWidenRecur (ldd, (fv != zero ? fv : fnv), g); gv = Cudd_NotCond (cuddT (G), g != G); gnv = Cudd_NotCond (cuddE (G), g != G); if (gv == zero) { assert (fv == zero); rest = lddIntervalWidenRecur (ldd, fnv, gnv); } else if (fv == zero) return lddIntervalWidenRecur (ldd, fnv, g); else { assert (gnv == zero); assert (fnv == zero); rest = lddIntervalWidenRecur (ldd, fv, gv); } if (F->index != G->index) return rest; if (rest == NULL) return NULL; cuddRef (rest); gVar = Cudd_bddIthVar (CUDD, G->index); if (gVar == NULL) { Cudd_IterDerefBdd (CUDD, rest); return NULL; } cuddRef (gVar); gVar = Cudd_NotCond (gVar, gv == zero); res = lddAndRecur (ldd, gVar, rest); cuddRef (res); Cudd_IterDerefBdd (CUDD, gVar); Cudd_IterDerefBdd (CUDD, rest); cuddDeref (res); return res; }
/* Calculate an expression into an X86RI operand. As with iselIntExpr_R, the expression can have type 32, 16 or 8 bits. */ static X86RI* iselIntExpr_RI ( ISelEnv* env, IRExpr* e ) { X86RI* ri = iselIntExpr_RI_wrk(env, e); switch (ri->tag) { case Xri_Imm: return ri; case Xri_Reg: vassert(hregClass(ri->Xri.Reg.reg) == HRcInt32); vassert(hregIsVirtual(ri->Xri.Reg.reg)); return ri; default: vpanic("iselIntExpr_RI: unknown x86 RI tag"); } }
/* string_break *********************************************************************************/ /** * @brief Returns the index of the next delimiter in the string. If no delimiter was found, * returns the length of the string. * @param[in] s: the string to search for delimiters. * @param[in] delim: null terminated string of delimiters to search for. * @return The index of the first instance of a character in delim. Returns the length of the * string if no delimiters were found. */ static const char* string_break(const String* s, const char* delim) { const char* i; const char* j; for(i = string_start(s); i < string_end(s); i++) { for(j = delim; *j != 0; j++) { if(*i == *j) { return i; } } } return i; }
i;main(a,b,c,d){ for(scanf("%1d%1d%1d%d",&a,&b,&c,&d);i<8;i++){ if(a+(i&1?b:-b)+(i&2?c:-c)+(i&4?d:-d)==7) return!printf("%d%+d%+d%+d=7",a,i&1?b:-b,i&2?c:-c,i&4?d:-d); } }
/* * Test whether there is some accumulated payload to send. */ static inline int br_ssl_engine_has_pld_to_send(const br_ssl_engine_context *rc) { return rc->oxa != rc->oxb && rc->oxa != rc->oxc; }
/* * Handle interrupts on GUS devices until there aren't any left. */ static void gusc_intr(void *arg) { sc_p scp = (sc_p)arg; int did_something; do { did_something = 0; if (scp->pcm_intr.intr != NULL && (port_rd(scp->io[2], 2) & 1)) { (*scp->pcm_intr.intr)(scp->pcm_intr.arg); did_something = 1; } if (scp->midi_intr.intr != NULL && (port_rd(scp->io[1], 0) & 0x80)) { (*scp->midi_intr.intr)(scp->midi_intr.arg); did_something = 1; } } while (did_something != 0); }
/*! * \brief Determine whether two entries have same key values. * * This function extracts the key fields values from the entry buffer, and * compare whether they are identical. * * \param [in] entry_a Entry a to be compared. * \param [in] entry_b Entry b to be compared. * \param [in] key_fields Pointer to bcmlrd_hw_field_list_t structure * corresponding to a LT. * * \retval TRUE The two entries have same key values. * \retval FALSE The two entries have different key values. */ static bool rm_hash_key_is_identical(const uint32_t *entry_a, const uint32_t *entry_b, const bcmlrd_hw_field_list_t *key_fields) { uint8_t idx; int sbit, ebit; uint32_t field_a[BCMPTM_MAX_PT_FIELD_WORDS]; uint32_t field_b[BCMPTM_MAX_PT_FIELD_WORDS]; for (idx = 0; idx < key_fields->num_fields; idx++) { uint16_t num_words, word; num_words = (key_fields->field_width[idx] + 31) / 32; field_a[num_words - 1] = 0; field_b[num_words - 1] = 0; sbit = key_fields->field_start_bit[idx]; ebit = key_fields->field_start_bit[idx] + key_fields->field_width[idx] - 1; bcmdrd_field_get(entry_a, sbit, ebit, field_a); bcmdrd_field_get(entry_b, sbit, ebit, field_b); for (word = 0; word < num_words; word++) { if (field_a[word] != field_b[word]) { return FALSE; } } } return TRUE; }
/** * @brief Expands the array list to the needed size and finds the chunk * requested by the index * * \param al Pointer to the Pointer of the array list struct * \param idx Index of the array list * * \return Requested chunk */ struct array_list *expand_list(struct array_list **al, int idx) { struct array_list *temp = *al; int arc = 0; int i = 0; do { if (temp == NULL) { arc = pow(2, ARRAY_LIST_INITIAL_CAPACITY_EXPONENT); temp = malloc(sizeof(struct array_list) + sizeof(void *) * arc); temp->next = NULL; temp->arc = arc; for (int j = 0; j < temp->arc; j++) { temp->arv[j] = NULL; } *al = temp; } else if (temp->next == NULL) { arc = pow(2, ARRAY_LIST_INITIAL_CAPACITY_EXPONENT + (i == 0 ? 0 : i)); temp->next = malloc(sizeof(struct array_list) + sizeof(void *) * arc); temp->next->next = NULL; temp->next->arc = arc; for (int j = 0; j < temp->next->arc; j++) { temp->next->arv[j] = NULL; } temp = temp->next; } else { temp = temp->next; } } while (++i < chunk(idx)); return temp; }
/* * VmbusChannelSetEvent - Trigger an event notification on the specified * channel. */ static void VmbusChannelSetEvent(struct vmbus_channel *Channel) { struct hv_monitor_page *monitorPage; DPRINT_ENTER(VMBUS); if (Channel->OfferMsg.MonitorAllocated) { set_bit(Channel->OfferMsg.ChildRelId & 31, (unsigned long *) gVmbusConnection.SendInterruptPage + (Channel->OfferMsg.ChildRelId >> 5)); monitorPage = gVmbusConnection.MonitorPages; monitorPage++; set_bit(Channel->MonitorBit, (unsigned long *)&monitorPage->TriggerGroup [Channel->MonitorGroup].Pending); } else { VmbusSetEvent(Channel->OfferMsg.ChildRelId); } DPRINT_EXIT(VMBUS); }
/** * g_menu_attribute_iter_get_value: * @iter: a #GMenuAttributeIter * * Gets the value of the attribute at the current iterator position. * * The iterator is not advanced. * * Returns: (transfer full): the value of the current attribute * * Since: 2.32 */ GVariant * g_menu_attribute_iter_get_value (GMenuAttributeIter *iter) { g_return_val_if_fail (iter->priv->valid, NULL); return g_variant_ref (iter->priv->value); }
/** * @brief Export the current session information to a known_hosts string. * * This exports the current information of a session which is connected so a * ssh server into an entry line which can be added to a known_hosts file. * * @param[in] session The session with information to export. * * @param[in] pentry_string A pointer to a string to store the alloocated * line of the entry. The user must free it using * ssh_string_free_char(). * * @return SSH_OK on succcess, SSH_ERROR otherwise. */ int ssh_session_export_known_hosts_entry(ssh_session session, char **pentry_string) { ssh_key server_pubkey = NULL; char *host = NULL; char entry_buf[4096] = {0}; char *b64_key = NULL; int rc; if (pentry_string == NULL) { ssh_set_error_invalid(session); return SSH_ERROR; } if (session->opts.host == NULL) { ssh_set_error(session, SSH_FATAL, "Can't create known_hosts entry - hostname unknown"); return SSH_ERROR; } host = ssh_session_get_host_port(session); if (host == NULL) { return SSH_ERROR; } if (session->current_crypto == NULL) { ssh_set_error(session, SSH_FATAL, "No current crypto context, please connect first"); SAFE_FREE(host); return SSH_ERROR; } server_pubkey = ssh_dh_get_current_server_publickey(session); if (server_pubkey == NULL){ ssh_set_error(session, SSH_FATAL, "No public key present"); SAFE_FREE(host); return SSH_ERROR; } rc = ssh_pki_export_pubkey_base64(server_pubkey, &b64_key); if (rc < 0) { SAFE_FREE(host); return SSH_ERROR; } snprintf(entry_buf, sizeof(entry_buf), "%s %s %s\n", host, server_pubkey->type_c, b64_key); SAFE_FREE(host); SAFE_FREE(b64_key); *pentry_string = strdup(entry_buf); if (*pentry_string == NULL) { return SSH_ERROR; } return SSH_OK; }
#include<stdio.h> #include<string.h> int H,W=5,B[11][5],i,j,R; int del() { int i,j,k,t,r=0; for(i=0;i<H;i++) for(j=0;j<W;j++) { if(B[i][j]!=-1) { for(k=j+1;k<W&&B[i][j]==B[i][k];k++); if(k-j>=3) { r+=B[i][j]*(k-j); for(t=j;t<k;t++)B[i][t]=-1; } } } R+=r; return r; } void fall() { int i,j,k,t; for(i=0;i<W;i++) for(j=H-1;j>=0;j--) if(B[j][i]!=-1) { for(k=j+1;k<H&&B[k][i]==-1;k++); k--; t=B[k][i]; B[k][i]=B[j][i]; B[j][i]=t; } } int main() { for(;scanf("%d",&H),H;) { R=0; memset(B,-1,sizeof(B)); for(i=0;i<H;i++) for(j=0;j<5;j++) scanf("%d",&B[i][j]); while(del()!=0) { fall(); } printf("%d\n",R); } return 0; }
/* * Extract the offset from the beginning of a function from the probe definition * assuming the following format: "function+0xDEADBEEF" * If no offset is specified, we set the offset to zero */ int extract_target_offset(char *def, unsigned long *offs) { int ret, nb_matches; char *offs_str; offs_str = malloc(BUFF_SIZE * sizeof(char)); if (!offs_str) { fprintf(stderr,"Error allocating array for probe offset"); return -1; } nb_matches = sscanf(def, "%*[^+]+%s", offs_str); if (nb_matches == 0) { *offs= 0; } else if (nb_matches == 1) { errno = 0; *offs = strtol(offs_str, NULL, 16); if (errno == ERANGE && (*offs == LONG_MAX || *offs == LONG_MIN)) { perror("offset out of range"); ret = -1; } if (errno != 0 && *offs == 0) { perror("No digits detected"); ret = -1; } } else { fprintf(stderr,"Error parsing probe definition, more than one '+' found"); ret = -1; } free(offs_str); return ret; }
/* SPDX-License-Identifier: BSD-3-Clause * Copyright(c) 2022 Nvidia Inc. All rights reserved. */ #include <stddef.h> #include <rte_eal_paging.h> #include "mlx5_utils.h" #include "mlx5_flow.h" #if defined(HAVE_IBV_FLOW_DV_SUPPORT) || !defined(HAVE_INFINIBAND_VERBS_H) typedef void (*quota_wqe_cmd_t)(volatile struct mlx5_aso_wqe *restrict, struct mlx5_quota_ctx *, uint32_t, uint32_t, void *); #define MLX5_ASO_MTR1_INIT_MASK 0xffffffffULL #define MLX5_ASO_MTR0_INIT_MASK ((MLX5_ASO_MTR1_INIT_MASK) << 32) static __rte_always_inline bool is_aso_mtr1_obj(uint32_t qix) { return (qix & 1) != 0; } static __rte_always_inline bool is_quota_sync_queue(const struct mlx5_priv *priv, uint32_t queue) { return queue >= priv->nb_queue - 1; } static __rte_always_inline uint32_t quota_sync_queue(const struct mlx5_priv *priv) { return priv->nb_queue - 1; } static __rte_always_inline uint32_t mlx5_quota_wqe_read_offset(uint32_t qix, uint32_t sq_index) { return 2 * sq_index + (qix & 1); } static int32_t mlx5_quota_fetch_tokens(const struct mlx5_aso_mtr_dseg *rd_buf) { int c_tok = (int)rte_be_to_cpu_32(rd_buf->c_tokens); int e_tok = (int)rte_be_to_cpu_32(rd_buf->e_tokens); int result; DRV_LOG(DEBUG, "c_tokens %d e_tokens %d\n", rte_be_to_cpu_32(rd_buf->c_tokens), rte_be_to_cpu_32(rd_buf->e_tokens)); /* Query after SET ignores negative E tokens */ if (c_tok >= 0 && e_tok < 0) result = c_tok; /** * If number of tokens in Meter bucket is zero or above, * Meter hardware will use that bucket and can set number of tokens to * negative value. * Quota can discard negative C tokens in query report. * That is a known hardware limitation. * Use case example: * * C E Result * 250 250 500 * 50 250 300 * -150 250 100 * -150 50 50 * * -150 -150 -300 * */ else if (c_tok < 0 && e_tok >= 0 && (c_tok + e_tok) < 0) result = e_tok; else result = c_tok + e_tok; return result; } static void mlx5_quota_query_update_async_cmpl(struct mlx5_hw_q_job *job) { struct rte_flow_query_quota *query = job->query.user; query->quota = mlx5_quota_fetch_tokens(job->query.hw); } void mlx5_quota_async_completion(struct rte_eth_dev *dev, uint32_t queue, struct mlx5_hw_q_job *job) { struct mlx5_priv *priv = dev->data->dev_private; struct mlx5_quota_ctx *qctx = &priv->quota_ctx; uint32_t qix = MLX5_INDIRECT_ACTION_IDX_GET(job->action); struct mlx5_quota *qobj = mlx5_ipool_get(qctx->quota_ipool, qix); RTE_SET_USED(queue); qobj->state = MLX5_QUOTA_STATE_READY; switch (job->type) { case MLX5_HW_Q_JOB_TYPE_CREATE: break; case MLX5_HW_Q_JOB_TYPE_QUERY: case MLX5_HW_Q_JOB_TYPE_UPDATE_QUERY: mlx5_quota_query_update_async_cmpl(job); break; default: break; } } static __rte_always_inline void mlx5_quota_wqe_set_aso_read(volatile struct mlx5_aso_wqe *restrict wqe, struct mlx5_quota_ctx *qctx, uint32_t queue) { struct mlx5_aso_sq *sq = qctx->sq + queue; uint32_t sq_mask = (1 << sq->log_desc_n) - 1; uint32_t sq_head = sq->head & sq_mask; uint64_t rd_addr = (uint64_t)(qctx->read_buf[queue] + 2 * sq_head); wqe->aso_cseg.lkey = rte_cpu_to_be_32(qctx->mr.lkey); wqe->aso_cseg.va_h = rte_cpu_to_be_32((uint32_t)(rd_addr >> 32)); wqe->aso_cseg.va_l_r = rte_cpu_to_be_32(((uint32_t)rd_addr) | MLX5_ASO_CSEG_READ_ENABLE); } #define MLX5_ASO_MTR1_ADD_MASK 0x00000F00ULL #define MLX5_ASO_MTR1_SET_MASK 0x000F0F00ULL #define MLX5_ASO_MTR0_ADD_MASK ((MLX5_ASO_MTR1_ADD_MASK) << 32) #define MLX5_ASO_MTR0_SET_MASK ((MLX5_ASO_MTR1_SET_MASK) << 32) static __rte_always_inline void mlx5_quota_wqe_set_mtr_tokens(volatile struct mlx5_aso_wqe *restrict wqe, uint32_t qix, void *arg) { volatile struct mlx5_aso_mtr_dseg *mtr_dseg; const struct rte_flow_update_quota *conf = arg; bool set_op = (conf->op == RTE_FLOW_UPDATE_QUOTA_SET); if (is_aso_mtr1_obj(qix)) { wqe->aso_cseg.data_mask = set_op ? RTE_BE64(MLX5_ASO_MTR1_SET_MASK) : RTE_BE64(MLX5_ASO_MTR1_ADD_MASK); mtr_dseg = wqe->aso_dseg.mtrs + 1; } else { wqe->aso_cseg.data_mask = set_op ? RTE_BE64(MLX5_ASO_MTR0_SET_MASK) : RTE_BE64(MLX5_ASO_MTR0_ADD_MASK); mtr_dseg = wqe->aso_dseg.mtrs; } if (set_op) { /* prevent using E tokens when C tokens exhausted */ mtr_dseg->e_tokens = -1; mtr_dseg->c_tokens = rte_cpu_to_be_32(conf->quota); } else { mtr_dseg->e_tokens = rte_cpu_to_be_32(conf->quota); } } static __rte_always_inline void mlx5_quota_wqe_query(volatile struct mlx5_aso_wqe *restrict wqe, struct mlx5_quota_ctx *qctx, __rte_unused uint32_t qix, uint32_t queue, __rte_unused void *arg) { mlx5_quota_wqe_set_aso_read(wqe, qctx, queue); wqe->aso_cseg.data_mask = 0ull; /* clear MTR ASO data modification */ } static __rte_always_inline void mlx5_quota_wqe_update(volatile struct mlx5_aso_wqe *restrict wqe, __rte_unused struct mlx5_quota_ctx *qctx, uint32_t qix, __rte_unused uint32_t queue, void *arg) { mlx5_quota_wqe_set_mtr_tokens(wqe, qix, arg); wqe->aso_cseg.va_l_r = 0; /* clear READ flag */ } static __rte_always_inline void mlx5_quota_wqe_query_update(volatile struct mlx5_aso_wqe *restrict wqe, struct mlx5_quota_ctx *qctx, uint32_t qix, uint32_t queue, void *arg) { mlx5_quota_wqe_set_aso_read(wqe, qctx, queue); mlx5_quota_wqe_set_mtr_tokens(wqe, qix, arg); } static __rte_always_inline void mlx5_quota_set_init_wqe(volatile struct mlx5_aso_wqe *restrict wqe, __rte_unused struct mlx5_quota_ctx *qctx, uint32_t qix, __rte_unused uint32_t queue, void *arg) { volatile struct mlx5_aso_mtr_dseg *mtr_dseg; const struct rte_flow_action_quota *conf = arg; const struct mlx5_quota *qobj = mlx5_ipool_get(qctx->quota_ipool, qix + 1); if (is_aso_mtr1_obj(qix)) { wqe->aso_cseg.data_mask = rte_cpu_to_be_64(MLX5_ASO_MTR1_INIT_MASK); mtr_dseg = wqe->aso_dseg.mtrs + 1; } else { wqe->aso_cseg.data_mask = rte_cpu_to_be_64(MLX5_ASO_MTR0_INIT_MASK); mtr_dseg = wqe->aso_dseg.mtrs; } mtr_dseg->e_tokens = -1; mtr_dseg->c_tokens = rte_cpu_to_be_32(conf->quota); mtr_dseg->v_bo_sc_bbog_mm |= rte_cpu_to_be_32 (qobj->mode << ASO_DSEG_MTR_MODE); } static __rte_always_inline void mlx5_quota_cmd_completed_status(struct mlx5_aso_sq *sq, uint16_t n) { uint16_t i, mask = (1 << sq->log_desc_n) - 1; for (i = 0; i < n; i++) { uint8_t state = MLX5_QUOTA_STATE_WAIT; struct mlx5_quota *quota_obj = sq->elts[(sq->tail + i) & mask].quota_obj; __atomic_compare_exchange_n(&quota_obj->state, &state, MLX5_QUOTA_STATE_READY, false, __ATOMIC_RELAXED, __ATOMIC_RELAXED); } } static void mlx5_quota_cmd_completion_handle(struct mlx5_aso_sq *sq) { struct mlx5_aso_cq *cq = &sq->cq; volatile struct mlx5_cqe *restrict cqe; const unsigned int cq_size = 1 << cq->log_desc_n; const unsigned int mask = cq_size - 1; uint32_t idx; uint32_t next_idx = cq->cq_ci & mask; uint16_t max; uint16_t n = 0; int ret; MLX5_ASSERT(rte_spinlock_is_locked(&sq->sqsl)); max = (uint16_t)(sq->head - sq->tail); if (unlikely(!max)) return; do { idx = next_idx; next_idx = (cq->cq_ci + 1) & mask; rte_prefetch0(&cq->cq_obj.cqes[next_idx]); cqe = &cq->cq_obj.cqes[idx]; ret = check_cqe(cqe, cq_size, cq->cq_ci); /* * Be sure owner read is done before any other cookie field or * opaque field. */ rte_io_rmb(); if (ret != MLX5_CQE_STATUS_SW_OWN) { if (likely(ret == MLX5_CQE_STATUS_HW_OWN)) break; mlx5_aso_cqe_err_handle(sq); } else { n++; } cq->cq_ci++; } while (1); if (likely(n)) { mlx5_quota_cmd_completed_status(sq, n); sq->tail += n; rte_io_wmb(); cq->cq_obj.db_rec[0] = rte_cpu_to_be_32(cq->cq_ci); } } static int mlx5_quota_cmd_wait_cmpl(struct mlx5_aso_sq *sq, struct mlx5_quota *quota_obj) { uint32_t poll_cqe_times = MLX5_MTR_POLL_WQE_CQE_TIMES; do { rte_spinlock_lock(&sq->sqsl); mlx5_quota_cmd_completion_handle(sq); rte_spinlock_unlock(&sq->sqsl); if (__atomic_load_n(&quota_obj->state, __ATOMIC_RELAXED) == MLX5_QUOTA_STATE_READY) return 0; } while (poll_cqe_times -= MLX5_ASO_WQE_CQE_RESPONSE_DELAY); DRV_LOG(ERR, "QUOTA: failed to poll command CQ"); return -1; } static int mlx5_quota_cmd_wqe(struct rte_eth_dev *dev, struct mlx5_quota *quota_obj, quota_wqe_cmd_t wqe_cmd, uint32_t qix, uint32_t queue, struct mlx5_hw_q_job *job, bool push, void *arg) { struct mlx5_priv *priv = dev->data->dev_private; struct mlx5_dev_ctx_shared *sh = priv->sh; struct mlx5_quota_ctx *qctx = &priv->quota_ctx; struct mlx5_aso_sq *sq = qctx->sq + queue; uint32_t head, sq_mask = (1 << sq->log_desc_n) - 1; bool sync_queue = is_quota_sync_queue(priv, queue); volatile struct mlx5_aso_wqe *restrict wqe; int ret = 0; if (sync_queue) rte_spinlock_lock(&sq->sqsl); head = sq->head & sq_mask; wqe = &sq->sq_obj.aso_wqes[head]; wqe_cmd(wqe, qctx, qix, queue, arg); wqe->general_cseg.misc = rte_cpu_to_be_32(qctx->devx_obj->id + (qix >> 1)); wqe->general_cseg.opcode = rte_cpu_to_be_32 (ASO_OPC_MOD_POLICER << WQE_CSEG_OPC_MOD_OFFSET | sq->pi << WQE_CSEG_WQE_INDEX_OFFSET | MLX5_OPCODE_ACCESS_ASO); sq->head++; sq->pi += 2; /* Each WQE contains 2 WQEBB */ if (push) { mlx5_doorbell_ring(&sh->tx_uar.bf_db, *(volatile uint64_t *)wqe, sq->pi, &sq->sq_obj.db_rec[MLX5_SND_DBR], !sh->tx_uar.dbnc); sq->db_pi = sq->pi; } sq->db = wqe; job->query.hw = qctx->read_buf[queue] + mlx5_quota_wqe_read_offset(qix, head); sq->elts[head].quota_obj = sync_queue ? quota_obj : (typeof(quota_obj))job; if (sync_queue) { rte_spinlock_unlock(&sq->sqsl); ret = mlx5_quota_cmd_wait_cmpl(sq, quota_obj); } return ret; } static void mlx5_quota_destroy_sq(struct mlx5_priv *priv) { struct mlx5_quota_ctx *qctx = &priv->quota_ctx; uint32_t i, nb_queues = priv->nb_queue; if (!qctx->sq) return; for (i = 0; i < nb_queues; i++) mlx5_aso_destroy_sq(qctx->sq + i); mlx5_free(qctx->sq); } static __rte_always_inline void mlx5_quota_wqe_init_common(struct mlx5_aso_sq *sq, volatile struct mlx5_aso_wqe *restrict wqe) { #define ASO_MTR_DW0 RTE_BE32(1 << ASO_DSEG_VALID_OFFSET | \ MLX5_FLOW_COLOR_GREEN << ASO_DSEG_SC_OFFSET) memset((void *)(uintptr_t)wqe, 0, sizeof(*wqe)); wqe->general_cseg.sq_ds = rte_cpu_to_be_32((sq->sqn << 8) | (sizeof(*wqe) >> 4)); wqe->aso_cseg.operand_masks = RTE_BE32 (0u | (ASO_OPER_LOGICAL_OR << ASO_CSEG_COND_OPER_OFFSET) | (ASO_OP_ALWAYS_TRUE << ASO_CSEG_COND_1_OPER_OFFSET) | (ASO_OP_ALWAYS_TRUE << ASO_CSEG_COND_0_OPER_OFFSET) | (BYTEWISE_64BYTE << ASO_CSEG_DATA_MASK_MODE_OFFSET)); wqe->general_cseg.flags = RTE_BE32 (MLX5_COMP_ALWAYS << MLX5_COMP_MODE_OFFSET); wqe->aso_dseg.mtrs[0].v_bo_sc_bbog_mm = ASO_MTR_DW0; /** * ASO Meter tokens auto-update must be disabled in quota action. * Tokens auto-update is disabled when Meter when *IR values set to * ((0x1u << 16) | (0x1Eu << 24)) **NOT** 0x00 */ wqe->aso_dseg.mtrs[0].cbs_cir = RTE_BE32((0x1u << 16) | (0x1Eu << 24)); wqe->aso_dseg.mtrs[0].ebs_eir = RTE_BE32((0x1u << 16) | (0x1Eu << 24)); wqe->aso_dseg.mtrs[1].v_bo_sc_bbog_mm = ASO_MTR_DW0; wqe->aso_dseg.mtrs[1].cbs_cir = RTE_BE32((0x1u << 16) | (0x1Eu << 24)); wqe->aso_dseg.mtrs[1].ebs_eir = RTE_BE32((0x1u << 16) | (0x1Eu << 24)); #undef ASO_MTR_DW0 } static void mlx5_quota_init_sq(struct mlx5_aso_sq *sq) { uint32_t i, size = 1 << sq->log_desc_n; for (i = 0; i < size; i++) mlx5_quota_wqe_init_common(sq, sq->sq_obj.aso_wqes + i); } static int mlx5_quota_alloc_sq(struct mlx5_priv *priv) { struct mlx5_dev_ctx_shared *sh = priv->sh; struct mlx5_quota_ctx *qctx = &priv->quota_ctx; uint32_t i, nb_queues = priv->nb_queue; qctx->sq = mlx5_malloc(MLX5_MEM_ZERO, sizeof(qctx->sq[0]) * nb_queues, 0, SOCKET_ID_ANY); if (!qctx->sq) { DRV_LOG(DEBUG, "QUOTA: failed to allocate SQ pool"); return -ENOMEM; } for (i = 0; i < nb_queues; i++) { int ret = mlx5_aso_sq_create (sh->cdev, qctx->sq + i, sh->tx_uar.obj, rte_log2_u32(priv->hw_q[i].size)); if (ret) { DRV_LOG(DEBUG, "QUOTA: failed to allocate SQ[%u]", i); return -ENOMEM; } mlx5_quota_init_sq(qctx->sq + i); } return 0; } static void mlx5_quota_destroy_read_buf(struct mlx5_priv *priv) { struct mlx5_dev_ctx_shared *sh = priv->sh; struct mlx5_quota_ctx *qctx = &priv->quota_ctx; if (qctx->mr.lkey) { void *addr = qctx->mr.addr; sh->cdev->mr_scache.dereg_mr_cb(&qctx->mr); mlx5_free(addr); } if (qctx->read_buf) mlx5_free(qctx->read_buf); } static int mlx5_quota_alloc_read_buf(struct mlx5_priv *priv) { struct mlx5_dev_ctx_shared *sh = priv->sh; struct mlx5_quota_ctx *qctx = &priv->quota_ctx; uint32_t i, nb_queues = priv->nb_queue; uint32_t sq_size_sum; size_t page_size = rte_mem_page_size(); struct mlx5_aso_mtr_dseg *buf; size_t rd_buf_size; int ret; for (i = 0, sq_size_sum = 0; i < nb_queues; i++) sq_size_sum += priv->hw_q[i].size; /* ACCESS MTR ASO WQE reads 2 MTR objects */ rd_buf_size = 2 * sq_size_sum * sizeof(buf[0]); buf = mlx5_malloc(MLX5_MEM_ANY | MLX5_MEM_ZERO, rd_buf_size, page_size, SOCKET_ID_ANY); if (!buf) { DRV_LOG(DEBUG, "QUOTA: failed to allocate MTR ASO READ buffer [1]"); return -ENOMEM; } ret = sh->cdev->mr_scache.reg_mr_cb(sh->cdev->pd, buf, rd_buf_size, &qctx->mr); if (ret) { DRV_LOG(DEBUG, "QUOTA: failed to register MTR ASO READ MR"); return -errno; } qctx->read_buf = mlx5_malloc(MLX5_MEM_ZERO, sizeof(qctx->read_buf[0]) * nb_queues, 0, SOCKET_ID_ANY); if (!qctx->read_buf) { DRV_LOG(DEBUG, "QUOTA: failed to allocate MTR ASO READ buffer [2]"); return -ENOMEM; } for (i = 0; i < nb_queues; i++) { qctx->read_buf[i] = buf; buf += 2 * priv->hw_q[i].size; } return 0; } static __rte_always_inline int mlx5_quota_check_ready(struct mlx5_quota *qobj, struct rte_flow_error *error) { uint8_t state = MLX5_QUOTA_STATE_READY; bool verdict = __atomic_compare_exchange_n (&qobj->state, &state, MLX5_QUOTA_STATE_WAIT, false, __ATOMIC_RELAXED, __ATOMIC_RELAXED); if (!verdict) return rte_flow_error_set(error, EBUSY, RTE_FLOW_ERROR_TYPE_ACTION, NULL, "action is busy"); return 0; } int mlx5_quota_query(struct rte_eth_dev *dev, uint32_t queue, const struct rte_flow_action_handle *handle, struct rte_flow_query_quota *query, struct mlx5_hw_q_job *async_job, bool push, struct rte_flow_error *error) { struct mlx5_priv *priv = dev->data->dev_private; struct mlx5_quota_ctx *qctx = &priv->quota_ctx; uint32_t work_queue = !is_quota_sync_queue(priv, queue) ? queue : quota_sync_queue(priv); uint32_t id = MLX5_INDIRECT_ACTION_IDX_GET(handle); uint32_t qix = id - 1; struct mlx5_quota *qobj = mlx5_ipool_get(qctx->quota_ipool, id); struct mlx5_hw_q_job sync_job; int ret; if (!qobj) return rte_flow_error_set(error, EINVAL, RTE_FLOW_ERROR_TYPE_HANDLE, NULL, "invalid query handle"); ret = mlx5_quota_check_ready(qobj, error); if (ret) return ret; ret = mlx5_quota_cmd_wqe(dev, qobj, mlx5_quota_wqe_query, qix, work_queue, async_job ? async_job : &sync_job, push, NULL); if (ret) { __atomic_store_n(&qobj->state, MLX5_QUOTA_STATE_READY, __ATOMIC_RELAXED); return rte_flow_error_set(error, EAGAIN, RTE_FLOW_ERROR_TYPE_ACTION, NULL, "try again"); } if (is_quota_sync_queue(priv, queue)) query->quota = mlx5_quota_fetch_tokens(sync_job.query.hw); return 0; } int mlx5_quota_query_update(struct rte_eth_dev *dev, uint32_t queue, struct rte_flow_action_handle *handle, const struct rte_flow_action *update, struct rte_flow_query_quota *query, struct mlx5_hw_q_job *async_job, bool push, struct rte_flow_error *error) { struct mlx5_priv *priv = dev->data->dev_private; struct mlx5_quota_ctx *qctx = &priv->quota_ctx; const struct rte_flow_update_quota *conf = update->conf; uint32_t work_queue = !is_quota_sync_queue(priv, queue) ? queue : quota_sync_queue(priv); uint32_t id = MLX5_INDIRECT_ACTION_IDX_GET(handle); uint32_t qix = id - 1; struct mlx5_quota *qobj = mlx5_ipool_get(qctx->quota_ipool, id); struct mlx5_hw_q_job sync_job; quota_wqe_cmd_t wqe_cmd = query ? mlx5_quota_wqe_query_update : mlx5_quota_wqe_update; int ret; if (conf->quota > MLX5_MTR_MAX_TOKEN_VALUE) return rte_flow_error_set(error, E2BIG, RTE_FLOW_ERROR_TYPE_ACTION, NULL, "update value too big"); if (!qobj) return rte_flow_error_set(error, EINVAL, RTE_FLOW_ERROR_TYPE_HANDLE, NULL, "invalid query_update handle"); if (conf->op == RTE_FLOW_UPDATE_QUOTA_ADD && qobj->last_update == RTE_FLOW_UPDATE_QUOTA_ADD) return rte_flow_error_set(error, EINVAL, RTE_FLOW_ERROR_TYPE_ACTION, NULL, "cannot add twice"); ret = mlx5_quota_check_ready(qobj, error); if (ret) return ret; ret = mlx5_quota_cmd_wqe(dev, qobj, wqe_cmd, qix, work_queue, async_job ? async_job : &sync_job, push, (void *)(uintptr_t)update->conf); if (ret) { __atomic_store_n(&qobj->state, MLX5_QUOTA_STATE_READY, __ATOMIC_RELAXED); return rte_flow_error_set(error, EAGAIN, RTE_FLOW_ERROR_TYPE_ACTION, NULL, "try again"); } qobj->last_update = conf->op; if (query && is_quota_sync_queue(priv, queue)) query->quota = mlx5_quota_fetch_tokens(sync_job.query.hw); return 0; } struct rte_flow_action_handle * mlx5_quota_alloc(struct rte_eth_dev *dev, uint32_t queue, const struct rte_flow_action_quota *conf, struct mlx5_hw_q_job *job, bool push, struct rte_flow_error *error) { struct mlx5_priv *priv = dev->data->dev_private; struct mlx5_quota_ctx *qctx = &priv->quota_ctx; uint32_t id; struct mlx5_quota *qobj; uintptr_t handle = (uintptr_t)MLX5_INDIRECT_ACTION_TYPE_QUOTA << MLX5_INDIRECT_ACTION_TYPE_OFFSET; uint32_t work_queue = !is_quota_sync_queue(priv, queue) ? queue : quota_sync_queue(priv); struct mlx5_hw_q_job sync_job; uint8_t state = MLX5_QUOTA_STATE_FREE; bool verdict; int ret; qobj = mlx5_ipool_malloc(qctx->quota_ipool, &id); if (!qobj) { rte_flow_error_set(error, EINVAL, RTE_FLOW_ERROR_TYPE_ACTION, NULL, "quota: failed to allocate quota object"); return NULL; } verdict = __atomic_compare_exchange_n (&qobj->state, &state, MLX5_QUOTA_STATE_WAIT, false, __ATOMIC_RELAXED, __ATOMIC_RELAXED); if (!verdict) { rte_flow_error_set(error, EINVAL, RTE_FLOW_ERROR_TYPE_ACTION, NULL, "quota: new quota object has invalid state"); return NULL; } switch (conf->mode) { case RTE_FLOW_QUOTA_MODE_L2: qobj->mode = MLX5_METER_MODE_L2_LEN; break; case RTE_FLOW_QUOTA_MODE_PACKET: qobj->mode = MLX5_METER_MODE_PKT; break; default: qobj->mode = MLX5_METER_MODE_IP_LEN; } ret = mlx5_quota_cmd_wqe(dev, qobj, mlx5_quota_set_init_wqe, id - 1, work_queue, job ? job : &sync_job, push, (void *)(uintptr_t)conf); if (ret) { mlx5_ipool_free(qctx->quota_ipool, id); __atomic_store_n(&qobj->state, MLX5_QUOTA_STATE_FREE, __ATOMIC_RELAXED); rte_flow_error_set(error, EINVAL, RTE_FLOW_ERROR_TYPE_ACTION, NULL, "quota: WR failure"); return 0; } return (struct rte_flow_action_handle *)(handle | id); } int mlx5_flow_quota_destroy(struct rte_eth_dev *dev) { struct mlx5_priv *priv = dev->data->dev_private; struct mlx5_quota_ctx *qctx = &priv->quota_ctx; int ret; if (qctx->quota_ipool) mlx5_ipool_destroy(qctx->quota_ipool); mlx5_quota_destroy_sq(priv); mlx5_quota_destroy_read_buf(priv); if (qctx->dr_action) { ret = mlx5dr_action_destroy(qctx->dr_action); if (ret) DRV_LOG(ERR, "QUOTA: failed to destroy DR action"); } if (qctx->devx_obj) { ret = mlx5_devx_cmd_destroy(qctx->devx_obj); if (ret) DRV_LOG(ERR, "QUOTA: failed to destroy MTR ASO object"); } memset(qctx, 0, sizeof(*qctx)); return 0; } #define MLX5_QUOTA_IPOOL_TRUNK_SIZE (1u << 12) #define MLX5_QUOTA_IPOOL_CACHE_SIZE (1u << 13) int mlx5_flow_quota_init(struct rte_eth_dev *dev, uint32_t nb_quotas) { struct mlx5_priv *priv = dev->data->dev_private; struct mlx5_dev_ctx_shared *sh = priv->sh; struct mlx5_quota_ctx *qctx = &priv->quota_ctx; int reg_id = mlx5_flow_get_reg_id(dev, MLX5_MTR_COLOR, 0, NULL); uint32_t flags = MLX5DR_ACTION_FLAG_HWS_RX | MLX5DR_ACTION_FLAG_HWS_TX; struct mlx5_indexed_pool_config quota_ipool_cfg = { .size = sizeof(struct mlx5_quota), .trunk_size = RTE_MIN(nb_quotas, MLX5_QUOTA_IPOOL_TRUNK_SIZE), .need_lock = 1, .release_mem_en = !!priv->sh->config.reclaim_mode, .malloc = mlx5_malloc, .max_idx = nb_quotas, .free = mlx5_free, .type = "mlx5_flow_quota_index_pool" }; int ret; if (!nb_quotas) { DRV_LOG(DEBUG, "QUOTA: cannot create quota with 0 objects"); return -EINVAL; } if (!priv->mtr_en || !sh->meter_aso_en) { DRV_LOG(DEBUG, "QUOTA: no MTR support"); return -ENOTSUP; } if (reg_id < 0) { DRV_LOG(DEBUG, "QUOTA: MRT register not available"); return -ENOTSUP; } qctx->devx_obj = mlx5_devx_cmd_create_flow_meter_aso_obj (sh->cdev->ctx, sh->cdev->pdn, rte_log2_u32(nb_quotas >> 1)); if (!qctx->devx_obj) { DRV_LOG(DEBUG, "QUOTA: cannot allocate MTR ASO objects"); return -ENOMEM; } if (sh->config.dv_esw_en && priv->master) flags |= MLX5DR_ACTION_FLAG_HWS_FDB; qctx->dr_action = mlx5dr_action_create_aso_meter (priv->dr_ctx, (struct mlx5dr_devx_obj *)qctx->devx_obj, reg_id - REG_C_0, flags); if (!qctx->dr_action) { DRV_LOG(DEBUG, "QUOTA: failed to create DR action"); ret = -ENOMEM; goto err; } ret = mlx5_quota_alloc_read_buf(priv); if (ret) goto err; ret = mlx5_quota_alloc_sq(priv); if (ret) goto err; if (nb_quotas < MLX5_QUOTA_IPOOL_TRUNK_SIZE) quota_ipool_cfg.per_core_cache = 0; else if (nb_quotas < MLX5_HW_IPOOL_SIZE_THRESHOLD) quota_ipool_cfg.per_core_cache = MLX5_HW_IPOOL_CACHE_MIN; else quota_ipool_cfg.per_core_cache = MLX5_QUOTA_IPOOL_CACHE_SIZE; qctx->quota_ipool = mlx5_ipool_create(&quota_ipool_cfg); if (!qctx->quota_ipool) { DRV_LOG(DEBUG, "QUOTA: failed to allocate quota pool"); ret = -ENOMEM; goto err; } qctx->nb_quotas = nb_quotas; return 0; err: mlx5_flow_quota_destroy(dev); return ret; } #endif /* defined(HAVE_IBV_FLOW_DV_SUPPORT) || !defined(HAVE_INFINIBAND_VERBS_H) */
/* Get the currently used lto_out_decl_state structure. */ struct lto_out_decl_state * lto_get_out_decl_state (void) { return decl_state_stack.last (); }
//reads data value from register with address regAdd //return data value read on success, -1 on failure int read_reg(int regAdd){ int data; I2C_start(ADDR_BYTE | TW_WRITE); I2C_write(TA_POINTER); I2C_start(ADDR_BYTE | TW_READ); data = I2C_read_ack() & 0x0F; data <<= 8; data |= I2C_read_nack(); I2C_stop(); return data; }
/* * Intel Wireless Multicomm 3200 WiFi driver * * Copyright (C) 2009 Intel Corporation. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * Neither the name of Intel Corporation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * * Intel Corporation <ilw@linux.intel.com> * Samuel Ortiz <samuel.ortiz@intel.com> * Zhu Yi <yi.zhu@intel.com> * */ #include <linux/kernel.h> #include <linux/netdevice.h> #include <linux/sched.h> #include <linux/ieee80211.h> #include <linux/wireless.h> #include <linux/slab.h> #include "iwm.h" #include "debug.h" #include "bus.h" #include "umac.h" #include "commands.h" #include "hal.h" #include "fw.h" #include "rx.h" static struct iwm_conf def_iwm_conf = { .sdio_ior_timeout = 5000, .calib_map = BIT(CALIB_CFG_DC_IDX) | BIT(CALIB_CFG_LO_IDX) | BIT(CALIB_CFG_TX_IQ_IDX) | BIT(CALIB_CFG_RX_IQ_IDX) | BIT(SHILOH_PHY_CALIBRATE_BASE_BAND_CMD), .expected_calib_map = BIT(PHY_CALIBRATE_DC_CMD) | BIT(PHY_CALIBRATE_LO_CMD) | BIT(PHY_CALIBRATE_TX_IQ_CMD) | BIT(PHY_CALIBRATE_RX_IQ_CMD) | BIT(SHILOH_PHY_CALIBRATE_BASE_BAND_CMD), .ct_kill_entry = 110, .ct_kill_exit = 110, .reset_on_fatal_err = 1, .auto_connect = 1, .enable_qos = 1, .mode = UMAC_MODE_BSS, /* UMAC configuration */ .power_index = 0, .frag_threshold = IEEE80211_MAX_FRAG_THRESHOLD, .rts_threshold = IEEE80211_MAX_RTS_THRESHOLD, .cts_to_self = 0, .assoc_timeout = 2, .roam_timeout = 10, .wireless_mode = WIRELESS_MODE_11A | WIRELESS_MODE_11G | WIRELESS_MODE_11N, /* IBSS */ .ibss_band = UMAC_BAND_2GHZ, .ibss_channel = 1, .mac_addr = {0x00, 0x02, 0xb3, 0x01, 0x02, 0x03}, }; static int modparam_reset; module_param_named(reset, modparam_reset, bool, 0644); MODULE_PARM_DESC(reset, "reset on firmware errors (default 0 [not reset])"); static int modparam_wimax_enable = 1; module_param_named(wimax_enable, modparam_wimax_enable, bool, 0644); MODULE_PARM_DESC(wimax_enable, "Enable wimax core (default 1 [wimax enabled])"); int iwm_mode_to_nl80211_iftype(int mode) { switch (mode) { case UMAC_MODE_BSS: return NL80211_IFTYPE_STATION; case UMAC_MODE_IBSS: return NL80211_IFTYPE_ADHOC; default: return NL80211_IFTYPE_UNSPECIFIED; } return 0; } static void iwm_statistics_request(struct work_struct *work) { struct iwm_priv *iwm = container_of(work, struct iwm_priv, stats_request.work); iwm_send_umac_stats_req(iwm, 0); } static void iwm_disconnect_work(struct work_struct *work) { struct iwm_priv *iwm = container_of(work, struct iwm_priv, disconnect.work); if (iwm->umac_profile_active) iwm_invalidate_mlme_profile(iwm); clear_bit(IWM_STATUS_ASSOCIATED, &iwm->status); iwm->umac_profile_active = 0; memset(iwm->bssid, 0, ETH_ALEN); iwm->channel = 0; iwm_link_off(iwm); wake_up_interruptible(&iwm->mlme_queue); cfg80211_disconnected(iwm_to_ndev(iwm), 0, NULL, 0, GFP_KERNEL); } static void iwm_ct_kill_work(struct work_struct *work) { struct iwm_priv *iwm = container_of(work, struct iwm_priv, ct_kill_delay.work); struct wiphy *wiphy = iwm_to_wiphy(iwm); IWM_INFO(iwm, "CT kill delay timeout\n"); wiphy_rfkill_set_hw_state(wiphy, false); } static int __iwm_up(struct iwm_priv *iwm); static int __iwm_down(struct iwm_priv *iwm); static void iwm_reset_worker(struct work_struct *work) { struct iwm_priv *iwm; struct iwm_umac_profile *profile = NULL; int uninitialized_var(ret), retry = 0; iwm = container_of(work, struct iwm_priv, reset_worker); /* * XXX: The iwm->mutex is introduced purely for this reset work, * because the other users for iwm_up and iwm_down are only netdev * ndo_open and ndo_stop which are already protected by rtnl. * Please remove iwm->mutex together if iwm_reset_worker() is not * required in the future. */ if (!mutex_trylock(&iwm->mutex)) { IWM_WARN(iwm, "We are in the middle of interface bringing " "UP/DOWN. Skip driver resetting.\n"); return; } if (iwm->umac_profile_active) { profile = kmalloc(sizeof(struct iwm_umac_profile), GFP_KERNEL); if (profile) memcpy(profile, iwm->umac_profile, sizeof(*profile)); else IWM_ERR(iwm, "Couldn't alloc memory for profile\n"); } __iwm_down(iwm); while (retry++ < 3) { ret = __iwm_up(iwm); if (!ret) break; schedule_timeout_uninterruptible(10 * HZ); } if (ret) { IWM_WARN(iwm, "iwm_up() failed: %d\n", ret); kfree(profile); goto out; } if (profile) { IWM_DBG_MLME(iwm, DBG, "Resend UMAC profile\n"); memcpy(iwm->umac_profile, profile, sizeof(*profile)); iwm_send_mlme_profile(iwm); kfree(profile); } else clear_bit(IWM_STATUS_RESETTING, &iwm->status); out: mutex_unlock(&iwm->mutex); } static void iwm_auth_retry_worker(struct work_struct *work) { struct iwm_priv *iwm; int i, ret; iwm = container_of(work, struct iwm_priv, auth_retry_worker); if (iwm->umac_profile_active) { ret = iwm_invalidate_mlme_profile(iwm); if (ret < 0) return; } iwm->umac_profile->sec.auth_type = UMAC_AUTH_TYPE_LEGACY_PSK; ret = iwm_send_mlme_profile(iwm); if (ret < 0) return; for (i = 0; i < IWM_NUM_KEYS; i++) if (iwm->keys[i].key_len) iwm_set_key(iwm, 0, &iwm->keys[i]); iwm_set_tx_key(iwm, iwm->default_key); } static void iwm_watchdog(unsigned long data) { struct iwm_priv *iwm = (struct iwm_priv *)data; IWM_WARN(iwm, "Watchdog expired: UMAC stalls!\n"); if (modparam_reset) iwm_resetting(iwm); } int iwm_priv_init(struct iwm_priv *iwm) { int i, j; char name[32]; iwm->status = 0; INIT_LIST_HEAD(&iwm->pending_notif); init_waitqueue_head(&iwm->notif_queue); init_waitqueue_head(&iwm->nonwifi_queue); init_waitqueue_head(&iwm->wifi_ntfy_queue); init_waitqueue_head(&iwm->mlme_queue); memcpy(&iwm->conf, &def_iwm_conf, sizeof(struct iwm_conf)); spin_lock_init(&iwm->tx_credit.lock); INIT_LIST_HEAD(&iwm->wifi_pending_cmd); INIT_LIST_HEAD(&iwm->nonwifi_pending_cmd); iwm->wifi_seq_num = UMAC_WIFI_SEQ_NUM_BASE; iwm->nonwifi_seq_num = UMAC_NONWIFI_SEQ_NUM_BASE; spin_lock_init(&iwm->cmd_lock); iwm->scan_id = 1; INIT_DELAYED_WORK(&iwm->stats_request, iwm_statistics_request); INIT_DELAYED_WORK(&iwm->disconnect, iwm_disconnect_work); INIT_DELAYED_WORK(&iwm->ct_kill_delay, iwm_ct_kill_work); INIT_WORK(&iwm->reset_worker, iwm_reset_worker); INIT_WORK(&iwm->auth_retry_worker, iwm_auth_retry_worker); INIT_LIST_HEAD(&iwm->bss_list); skb_queue_head_init(&iwm->rx_list); INIT_LIST_HEAD(&iwm->rx_tickets); spin_lock_init(&iwm->ticket_lock); for (i = 0; i < IWM_RX_ID_HASH; i++) { INIT_LIST_HEAD(&iwm->rx_packets[i]); spin_lock_init(&iwm->packet_lock[i]); } INIT_WORK(&iwm->rx_worker, iwm_rx_worker); iwm->rx_wq = create_singlethread_workqueue(KBUILD_MODNAME "_rx"); if (!iwm->rx_wq) return -EAGAIN; for (i = 0; i < IWM_TX_QUEUES; i++) { INIT_WORK(&iwm->txq[i].worker, iwm_tx_worker); snprintf(name, 32, KBUILD_MODNAME "_tx_%d", i); iwm->txq[i].id = i; iwm->txq[i].wq = create_singlethread_workqueue(name); if (!iwm->txq[i].wq) return -EAGAIN; skb_queue_head_init(&iwm->txq[i].queue); skb_queue_head_init(&iwm->txq[i].stopped_queue); spin_lock_init(&iwm->txq[i].lock); } for (i = 0; i < IWM_NUM_KEYS; i++) memset(&iwm->keys[i], 0, sizeof(struct iwm_key)); iwm->default_key = -1; for (i = 0; i < IWM_STA_TABLE_NUM; i++) for (j = 0; j < IWM_UMAC_TID_NR; j++) { mutex_init(&iwm->sta_table[i].tid_info[j].mutex); iwm->sta_table[i].tid_info[j].stopped = false; } init_timer(&iwm->watchdog); iwm->watchdog.function = iwm_watchdog; iwm->watchdog.data = (unsigned long)iwm; mutex_init(&iwm->mutex); iwm->last_fw_err = kzalloc(sizeof(struct iwm_fw_error_hdr), GFP_KERNEL); if (iwm->last_fw_err == NULL) return -ENOMEM; return 0; } void iwm_priv_deinit(struct iwm_priv *iwm) { int i; for (i = 0; i < IWM_TX_QUEUES; i++) destroy_workqueue(iwm->txq[i].wq); destroy_workqueue(iwm->rx_wq); kfree(iwm->last_fw_err); } /* * We reset all the structures, and we reset the UMAC. * After calling this routine, you're expected to reload * the firmware. */ void iwm_reset(struct iwm_priv *iwm) { struct iwm_notif *notif, *next; if (test_bit(IWM_STATUS_READY, &iwm->status)) iwm_target_reset(iwm); if (test_bit(IWM_STATUS_RESETTING, &iwm->status)) { iwm->status = 0; set_bit(IWM_STATUS_RESETTING, &iwm->status); } else iwm->status = 0; iwm->scan_id = 1; list_for_each_entry_safe(notif, next, &iwm->pending_notif, pending) { list_del(&notif->pending); kfree(notif->buf); kfree(notif); } iwm_cmd_flush(iwm); flush_workqueue(iwm->rx_wq); iwm_link_off(iwm); } void iwm_resetting(struct iwm_priv *iwm) { set_bit(IWM_STATUS_RESETTING, &iwm->status); schedule_work(&iwm->reset_worker); } /* * Notification code: * * We're faced with the following issue: Any host command can * have an answer or not, and if there's an answer to expect, * it can be treated synchronously or asynchronously. * To work around the synchronous answer case, we implemented * our notification mechanism. * When a code path needs to wait for a command response * synchronously, it calls notif_handle(), which waits for the * right notification to show up, and then process it. Before * starting to wait, it registered as a waiter for this specific * answer (by toggling a bit in on of the handler_map), so that * the rx code knows that it needs to send a notification to the * waiting processes. It does so by calling iwm_notif_send(), * which adds the notification to the pending notifications list, * and then wakes the waiting processes up. */ int iwm_notif_send(struct iwm_priv *iwm, struct iwm_wifi_cmd *cmd, u8 cmd_id, u8 source, u8 *buf, unsigned long buf_size) { struct iwm_notif *notif; notif = kzalloc(sizeof(struct iwm_notif), GFP_KERNEL); if (!notif) { IWM_ERR(iwm, "Couldn't alloc memory for notification\n"); return -ENOMEM; } INIT_LIST_HEAD(&notif->pending); notif->cmd = cmd; notif->cmd_id = cmd_id; notif->src = source; notif->buf = kzalloc(buf_size, GFP_KERNEL); if (!notif->buf) { IWM_ERR(iwm, "Couldn't alloc notification buffer\n"); kfree(notif); return -ENOMEM; } notif->buf_size = buf_size; memcpy(notif->buf, buf, buf_size); list_add_tail(&notif->pending, &iwm->pending_notif); wake_up_interruptible(&iwm->notif_queue); return 0; } static struct iwm_notif *iwm_notif_find(struct iwm_priv *iwm, u32 cmd, u8 source) { struct iwm_notif *notif; list_for_each_entry(notif, &iwm->pending_notif, pending) { if ((notif->cmd_id == cmd) && (notif->src == source)) { list_del(&notif->pending); return notif; } } return NULL; } static struct iwm_notif *iwm_notif_wait(struct iwm_priv *iwm, u32 cmd, u8 source, long timeout) { int ret; struct iwm_notif *notif; unsigned long *map = NULL; switch (source) { case IWM_SRC_LMAC: map = &iwm->lmac_handler_map[0]; break; case IWM_SRC_UMAC: map = &iwm->umac_handler_map[0]; break; case IWM_SRC_UDMA: map = &iwm->udma_handler_map[0]; break; } set_bit(cmd, map); ret = wait_event_interruptible_timeout(iwm->notif_queue, ((notif = iwm_notif_find(iwm, cmd, source)) != NULL), timeout); clear_bit(cmd, map); if (!ret) return NULL; return notif; } int iwm_notif_handle(struct iwm_priv *iwm, u32 cmd, u8 source, long timeout) { int ret; struct iwm_notif *notif; notif = iwm_notif_wait(iwm, cmd, source, timeout); if (!notif) return -ETIME; ret = iwm_rx_handle_resp(iwm, notif->buf, notif->buf_size, notif->cmd); kfree(notif->buf); kfree(notif); return ret; } static int iwm_config_boot_params(struct iwm_priv *iwm) { struct iwm_udma_nonwifi_cmd target_cmd; int ret; /* check Wimax is off and config debug monitor */ if (!modparam_wimax_enable) { u32 data1 = 0x1f; u32 addr1 = 0x606BE258; u32 data2_set = 0x0; u32 data2_clr = 0x1; u32 addr2 = 0x606BE100; u32 data3 = 0x1; u32 addr3 = 0x606BEC00; target_cmd.resp = 0; target_cmd.handle_by_hw = 0; target_cmd.eop = 1; target_cmd.opcode = UMAC_HDI_OUT_OPCODE_WRITE; target_cmd.addr = cpu_to_le32(addr1); target_cmd.op1_sz = cpu_to_le32(sizeof(u32)); target_cmd.op2 = 0; ret = iwm_hal_send_target_cmd(iwm, &target_cmd, &data1); if (ret < 0) { IWM_ERR(iwm, "iwm_hal_send_target_cmd failed\n"); return ret; } target_cmd.opcode = UMAC_HDI_OUT_OPCODE_READ_MODIFY_WRITE; target_cmd.addr = cpu_to_le32(addr2); target_cmd.op1_sz = cpu_to_le32(data2_set); target_cmd.op2 = cpu_to_le32(data2_clr); ret = iwm_hal_send_target_cmd(iwm, &target_cmd, &data1); if (ret < 0) { IWM_ERR(iwm, "iwm_hal_send_target_cmd failed\n"); return ret; } target_cmd.opcode = UMAC_HDI_OUT_OPCODE_WRITE; target_cmd.addr = cpu_to_le32(addr3); target_cmd.op1_sz = cpu_to_le32(sizeof(u32)); target_cmd.op2 = 0; ret = iwm_hal_send_target_cmd(iwm, &target_cmd, &data3); if (ret < 0) { IWM_ERR(iwm, "iwm_hal_send_target_cmd failed\n"); return ret; } } return 0; } void iwm_init_default_profile(struct iwm_priv *iwm, struct iwm_umac_profile *profile) { memset(profile, 0, sizeof(struct iwm_umac_profile)); profile->sec.auth_type = UMAC_AUTH_TYPE_OPEN; profile->sec.flags = UMAC_SEC_FLG_LEGACY_PROFILE; profile->sec.ucast_cipher = UMAC_CIPHER_TYPE_NONE; profile->sec.mcast_cipher = UMAC_CIPHER_TYPE_NONE; if (iwm->conf.enable_qos) profile->flags |= cpu_to_le16(UMAC_PROFILE_QOS_ALLOWED); profile->wireless_mode = iwm->conf.wireless_mode; profile->mode = cpu_to_le32(iwm->conf.mode); profile->ibss.atim = 0; profile->ibss.beacon_interval = 100; profile->ibss.join_only = 0; profile->ibss.band = iwm->conf.ibss_band; profile->ibss.channel = iwm->conf.ibss_channel; } void iwm_link_on(struct iwm_priv *iwm) { netif_carrier_on(iwm_to_ndev(iwm)); netif_tx_wake_all_queues(iwm_to_ndev(iwm)); iwm_send_umac_stats_req(iwm, 0); } void iwm_link_off(struct iwm_priv *iwm) { struct iw_statistics *wstats = &iwm->wstats; int i; netif_tx_stop_all_queues(iwm_to_ndev(iwm)); netif_carrier_off(iwm_to_ndev(iwm)); for (i = 0; i < IWM_TX_QUEUES; i++) { skb_queue_purge(&iwm->txq[i].queue); skb_queue_purge(&iwm->txq[i].stopped_queue); iwm->txq[i].concat_count = 0; iwm->txq[i].concat_ptr = iwm->txq[i].concat_buf; flush_workqueue(iwm->txq[i].wq); } iwm_rx_free(iwm); cancel_delayed_work_sync(&iwm->stats_request); memset(wstats, 0, sizeof(struct iw_statistics)); wstats->qual.updated = IW_QUAL_ALL_INVALID; kfree(iwm->req_ie); iwm->req_ie = NULL; iwm->req_ie_len = 0; kfree(iwm->resp_ie); iwm->resp_ie = NULL; iwm->resp_ie_len = 0; del_timer_sync(&iwm->watchdog); } static void iwm_bss_list_clean(struct iwm_priv *iwm) { struct iwm_bss_info *bss, *next; list_for_each_entry_safe(bss, next, &iwm->bss_list, node) { list_del(&bss->node); kfree(bss->bss); kfree(bss); } } static int iwm_channels_init(struct iwm_priv *iwm) { int ret; ret = iwm_send_umac_channel_list(iwm); if (ret) { IWM_ERR(iwm, "Send channel list failed\n"); return ret; } ret = iwm_notif_handle(iwm, UMAC_CMD_OPCODE_GET_CHAN_INFO_LIST, IWM_SRC_UMAC, WAIT_NOTIF_TIMEOUT); if (ret) { IWM_ERR(iwm, "Didn't get a channel list notification\n"); return ret; } return 0; } static int __iwm_up(struct iwm_priv *iwm) { int ret; struct iwm_notif *notif_reboot, *notif_ack = NULL; struct wiphy *wiphy = iwm_to_wiphy(iwm); u32 wireless_mode; ret = iwm_bus_enable(iwm); if (ret) { IWM_ERR(iwm, "Couldn't enable function\n"); return ret; } iwm_rx_setup_handlers(iwm); /* Wait for initial BARKER_REBOOT from hardware */ notif_reboot = iwm_notif_wait(iwm, IWM_BARKER_REBOOT_NOTIFICATION, IWM_SRC_UDMA, 2 * HZ); if (!notif_reboot) { IWM_ERR(iwm, "Wait for REBOOT_BARKER timeout\n"); goto err_disable; } /* We send the barker back */ ret = iwm_bus_send_chunk(iwm, notif_reboot->buf, 16); if (ret) { IWM_ERR(iwm, "REBOOT barker response failed\n"); kfree(notif_reboot); goto err_disable; } kfree(notif_reboot->buf); kfree(notif_reboot); /* Wait for ACK_BARKER from hardware */ notif_ack = iwm_notif_wait(iwm, IWM_ACK_BARKER_NOTIFICATION, IWM_SRC_UDMA, 2 * HZ); if (!notif_ack) { IWM_ERR(iwm, "Wait for ACK_BARKER timeout\n"); goto err_disable; } kfree(notif_ack->buf); kfree(notif_ack); /* We start to config static boot parameters */ ret = iwm_config_boot_params(iwm); if (ret) { IWM_ERR(iwm, "Config boot parameters failed\n"); goto err_disable; } ret = iwm_read_mac(iwm, iwm_to_ndev(iwm)->dev_addr); if (ret) { IWM_ERR(iwm, "MAC reading failed\n"); goto err_disable; } memcpy(iwm_to_ndev(iwm)->perm_addr, iwm_to_ndev(iwm)->dev_addr, ETH_ALEN); /* We can load the FWs */ ret = iwm_load_fw(iwm); if (ret) { IWM_ERR(iwm, "FW loading failed\n"); goto err_disable; } ret = iwm_eeprom_fat_channels(iwm); if (ret) { IWM_ERR(iwm, "Couldnt read HT channels EEPROM entries\n"); goto err_fw; } /* * Read our SKU capabilities. * If it's valid, we AND the configured wireless mode with the * device EEPROM value as the current profile wireless mode. */ wireless_mode = iwm_eeprom_wireless_mode(iwm); if (wireless_mode) { iwm->conf.wireless_mode &= wireless_mode; if (iwm->umac_profile) iwm->umac_profile->wireless_mode = iwm->conf.wireless_mode; } else IWM_ERR(iwm, "Wrong SKU capabilities: 0x%x\n", *((u16 *)iwm_eeprom_access(iwm, IWM_EEPROM_SKU_CAP))); snprintf(wiphy->fw_version, sizeof(wiphy->fw_version), "L%s_U%s", iwm->lmac_version, iwm->umac_version); /* We configure the UMAC and enable the wifi module */ ret = iwm_send_umac_config(iwm, cpu_to_le32(UMAC_RST_CTRL_FLG_WIFI_CORE_EN) | cpu_to_le32(UMAC_RST_CTRL_FLG_WIFI_LINK_EN) | cpu_to_le32(UMAC_RST_CTRL_FLG_WIFI_MLME_EN)); if (ret) { IWM_ERR(iwm, "UMAC config failed\n"); goto err_fw; } ret = iwm_notif_handle(iwm, UMAC_NOTIFY_OPCODE_WIFI_CORE_STATUS, IWM_SRC_UMAC, WAIT_NOTIF_TIMEOUT); if (ret) { IWM_ERR(iwm, "Didn't get a wifi core status notification\n"); goto err_fw; } if (iwm->core_enabled != (UMAC_NTFY_WIFI_CORE_STATUS_LINK_EN | UMAC_NTFY_WIFI_CORE_STATUS_MLME_EN)) { IWM_DBG_BOOT(iwm, DBG, "Not all cores enabled:0x%x\n", iwm->core_enabled); ret = iwm_notif_handle(iwm, UMAC_NOTIFY_OPCODE_WIFI_CORE_STATUS, IWM_SRC_UMAC, WAIT_NOTIF_TIMEOUT); if (ret) { IWM_ERR(iwm, "Didn't get a core status notification\n"); goto err_fw; } if (iwm->core_enabled != (UMAC_NTFY_WIFI_CORE_STATUS_LINK_EN | UMAC_NTFY_WIFI_CORE_STATUS_MLME_EN)) { IWM_ERR(iwm, "Not all cores enabled: 0x%x\n", iwm->core_enabled); goto err_fw; } else { IWM_INFO(iwm, "All cores enabled\n"); } } ret = iwm_channels_init(iwm); if (ret < 0) { IWM_ERR(iwm, "Couldn't init channels\n"); goto err_fw; } /* Set the READY bit to indicate interface is brought up successfully */ set_bit(IWM_STATUS_READY, &iwm->status); return 0; err_fw: iwm_eeprom_exit(iwm); err_disable: ret = iwm_bus_disable(iwm); if (ret < 0) IWM_ERR(iwm, "Couldn't disable function\n"); return -EIO; } int iwm_up(struct iwm_priv *iwm) { int ret; mutex_lock(&iwm->mutex); ret = __iwm_up(iwm); mutex_unlock(&iwm->mutex); return ret; } static int __iwm_down(struct iwm_priv *iwm) { int ret; /* The interface is already down */ if (!test_bit(IWM_STATUS_READY, &iwm->status)) return 0; if (iwm->scan_request) { cfg80211_scan_done(iwm->scan_request, true); iwm->scan_request = NULL; } clear_bit(IWM_STATUS_READY, &iwm->status); iwm_eeprom_exit(iwm); iwm_bss_list_clean(iwm); iwm_init_default_profile(iwm, iwm->umac_profile); iwm->umac_profile_active = false; iwm->default_key = -1; iwm->core_enabled = 0; ret = iwm_bus_disable(iwm); if (ret < 0) { IWM_ERR(iwm, "Couldn't disable function\n"); return ret; } return 0; } int iwm_down(struct iwm_priv *iwm) { int ret; mutex_lock(&iwm->mutex); ret = __iwm_down(iwm); mutex_unlock(&iwm->mutex); return ret; }
/* * Throw the VM-spec-mandated error when an exception is thrown during * class initialization. * * The safest way to do this is to call the ExceptionInInitializerError * constructor that takes a Throwable. * * [Do we want to wrap it if the original is an Error rather than * an Exception?] */ static void throwClinitError(void) { Thread* self = dvmThreadSelf(); Object* exception; Object* eiie; exception = dvmGetException(self); dvmAddTrackedAlloc(exception, self); dvmClearException(self); if (gDvm.classJavaLangExceptionInInitializerError == NULL) { gDvm.classJavaLangExceptionInInitializerError = dvmFindSystemClass( "Ljava/lang/ExceptionInInitializerError;"); if (gDvm.classJavaLangExceptionInInitializerError == NULL) { LOGE("Unable to prep java/lang/ExceptionInInitializerError\n"); goto fail; } gDvm.methJavaLangExceptionInInitializerError_init = dvmFindDirectMethodByDescriptor(gDvm.classJavaLangExceptionInInitializerError, "<init>", "(Ljava/lang/Throwable;)V"); if (gDvm.methJavaLangExceptionInInitializerError_init == NULL) { LOGE("Unable to prep java/lang/ExceptionInInitializerError\n"); goto fail; } } eiie = dvmAllocObject(gDvm.classJavaLangExceptionInInitializerError, ALLOC_DEFAULT); if (eiie == NULL) goto fail; JValue unused; dvmCallMethod(self, gDvm.methJavaLangExceptionInInitializerError_init, eiie, &unused, exception); dvmSetException(self, eiie); dvmReleaseTrackedAlloc(eiie, NULL); dvmReleaseTrackedAlloc(exception, self); return; fail: dvmSetException(self, exception); dvmReleaseTrackedAlloc(exception, self); return; }
/* Get's the length of an IPv6 extension header */ static int32_t ext_hdr_len(struct pico_ipv6_exthdr *ext, uint8_t hdr, uint8_t *dispatch) { int32_t len = 0; switch (hdr) { case PICO_IPV6_EXTHDR_HOPBYHOP: *dispatch |= (uint8_t)EXT_HOPBYHOP; len = IPV6_OPTLEN(ext->ext.destopt.len); ext->ext.destopt.len = (uint8_t)(len - 2); return (int32_t)len; case PICO_IPV6_EXTHDR_ROUTING: *dispatch |= (uint8_t)EXT_ROUTING; len = IPV6_OPTLEN(ext->ext.destopt.len); ext->ext.destopt.len = (uint8_t)(len - 2); return (int32_t)len; case PICO_IPV6_EXTHDR_DESTOPT: *dispatch |= (uint8_t)EXT_DSTOPT; len = IPV6_OPTLEN(ext->ext.destopt.len); ext->ext.destopt.len = (uint8_t)(len - 2); return (int32_t)len; case PICO_IPV6_EXTHDR_FRAG: *dispatch |= (uint8_t)EXT_FRAG; return (int32_t)8; default: return -1; } }
#include<stdio.h> int main(){ int unused __attribute__((unused)); char N[5]; unused = scanf("%s", N); if(N[0]==N[1] && N[0]==N[2]) printf("Yes"); else if(N[1]==N[2] && N[1]==N[3]) printf("Yes"); else printf("No"); return 0; }
/** * Interrupt service routine. * * @returns Whether the interrupt was from VMMDev. * @param pvState Opaque pointer to the device state. */ static int vgdrvFreeBSDISR(void *pvState) { LogFlow(("vgdrvFreeBSDISR: pvState=%p\n", pvState)); bool fOurIRQ = VGDrvCommonISR(&g_DevExt); return fOurIRQ ? 0 : 1; }
/* Convenience function to fill audio and mix at the specified volume This is called from many music player's GetAudio callback. */ int music_pcm_getaudio(void *context, void *data, int bytes, int volume, int (*GetSome)(void *context, void *data, int bytes, SDL_bool *done)) { Uint8 *snd = (Uint8 *)data; Uint8 *dst; int len = bytes; SDL_bool done = SDL_FALSE; if (volume == MIX_MAX_VOLUME) { dst = snd; } else { dst = SDL_stack_alloc(Uint8, (size_t)bytes); } while (len > 0 && !done) { int consumed = GetSome(context, dst, len, &done); if (consumed < 0) { break; } if (volume == MIX_MAX_VOLUME) { dst += consumed; } else { SDL_MixAudioFormat(snd, dst, music_spec.format, (Uint32)consumed, volume); snd += consumed; } len -= consumed; } if (volume != MIX_MAX_VOLUME) { SDL_stack_free(dst); } return len; }
/* * Custom exponential computation. * * If |x| >= 512*log(2) then this function returns exactly 0 (this is * meant to avoid subnormals or infinites, which are not necessarily * supported by the underlying 'fpr' implementation). */ static fpr approximate_exp(fpr x) { static fpr RANGE_MIN, RANGE_MAX, P1, P2, P3, P4, P5; static int init = 0; if (!init) { RANGE_MIN = make_fpr(-6243314768165359, -54); RANGE_MAX = make_fpr(6243314768165359, -54); P1 = make_fpr(6004799503160638, -55); P2 = make_fpr(-6405119469862291, -61); P3 = make_fpr(4880090809097772, -66); P4 = make_fpr(-7807914560613361, -72); P5 = make_fpr(6253375523824848, -77); init = 1; } int k; fpr t, c; k = 0; for (;;) { if (fpr_lt(RANGE_MIN, x) && fpr_lt(x, RANGE_MAX)) { break; } x = fpr_half(x); k ++; } if (k > 10) { return fpr_zero; } t = fpr_sqr(x); c = fpr_sub(x, fpr_mul(t, fpr_add(P1, fpr_mul(t, fpr_add(P2, fpr_mul(t, fpr_add(P3, fpr_mul(t, fpr_add(P4, fpr_mul(t, P5)))))))))); x = fpr_sub(fpr_one, fpr_sub( fpr_div(fpr_mul(x, c), fpr_sub(c, fpr_two)), x)); while (k -- > 0) { x = fpr_sqr(x); } return x; }
#include<stdio.h> #include<stdlib.h> int main() { int n,k,d,dist=0,i,j,ara[200],min=200,ara1[200],t,ara2[200],q; scanf("%d",&t); for(j=0; j<t; j++) { scanf("%d%d%d",&n,&k,&d); for(i=0; i<=k; i++) { ara2[i]=0; } for(i=0; i<n; i++) { scanf("%d",&ara[i]); } for(i=0; i<d; i++) { ara2[ara[i]]++; } for(q=0; q<=k; q++) { if(ara2[q]>0) { dist++; } } if(dist<min) { min=dist; } dist=0; for(i=1; i<=(n-d); i++) { ara2[ara[i-1]]--; ara2[ara[i+d-1]]++; for(q=0; q<=k; q++) { if(ara2[q]>0) { dist++; } } if(dist<min) { min=dist; } dist=0; } ara1[j]=min; min=200; } for(j=0; j<t; j++) { printf("%d\n",ara1[j]); } //printf("%d",min); return 0; }
#include<stdio.h> #include<string.h> int main() { char a[102],b[102]; scanf("%s",a); scanf("%s",b); int i=0; for(i=0;i<(strlen(a));++i) { int x=a[i]; int y=b[i]; if (x<='Z') x=(x-'A'+'a'); if (y<='Z') y=(y-'A'+'a'); a[i]=(char)x; b[i]=(char)y;} int k=strcmp(a,b); if (k<0) k=-1; if(k>0) k=1; printf("%d",k); return 0;}
/* * Set up the I2C interface, * configure the codec, * and shut down I2C. */ void ConfigureCodec() { I2CConfigure( EEPROM_I2C_BUS, 0 ); I2CSetFrequency( EEPROM_I2C_BUS, GetPeripheralClock(), I2C_CLOCK_FREQ ); I2CEnable( EEPROM_I2C_BUS, TRUE ); UINT8 i2cData[10]; I2C_7_BIT_ADDRESS SlaveAddress; Initialize the data buffer I2C_FORMAT_7_BIT_ADDRESS(SlaveAddress, 0x46, I2C_WRITE); i2cData[0] = SlaveAddress.byte; i2cData[1] = 0x40; register 64 i2cData[2] = 0xC0; turn off power save SendPacket( i2cData, 3 ); i2cData[1] = 73; register 73 i2cData[2] = 0x0C; inverted phase, no HPF SendPacket( i2cData, 3 ); I2CEnable( EEPROM_I2C_BUS, FALSE ); }
// SPDX-License-Identifier: GPL-2.0-or-later /* * Glue Code for SSE2 assembler versions of Serpent Cipher * * Copyright (c) 2011 Jussi Kivilinna <jussi.kivilinna@mbnet.fi> * * Glue code based on aesni-intel_glue.c by: * Copyright (C) 2008, Intel Corp. * Author: Huang Ying <ying.huang@intel.com> * * CBC & ECB parts based on code (crypto/cbc.c,ecb.c) by: * Copyright (c) 2006 Herbert Xu <herbert@gondor.apana.org.au> */ #include <linux/module.h> #include <linux/types.h> #include <linux/crypto.h> #include <linux/err.h> #include <crypto/algapi.h> #include <crypto/b128ops.h> #include <crypto/internal/simd.h> #include <crypto/serpent.h> #include "serpent-sse2.h" #include "ecb_cbc_helpers.h" static int serpent_setkey_skcipher(struct crypto_skcipher *tfm, const u8 *key, unsigned int keylen) { return __serpent_setkey(crypto_skcipher_ctx(tfm), key, keylen); } static void serpent_decrypt_cbc_xway(const void *ctx, u8 *dst, const u8 *src) { u8 buf[SERPENT_PARALLEL_BLOCKS - 1][SERPENT_BLOCK_SIZE]; const u8 *s = src; if (dst == src) s = memcpy(buf, src, sizeof(buf)); serpent_dec_blk_xway(ctx, dst, src); crypto_xor(dst + SERPENT_BLOCK_SIZE, s, sizeof(buf)); } static int ecb_encrypt(struct skcipher_request *req) { ECB_WALK_START(req, SERPENT_BLOCK_SIZE, SERPENT_PARALLEL_BLOCKS); ECB_BLOCK(SERPENT_PARALLEL_BLOCKS, serpent_enc_blk_xway); ECB_BLOCK(1, __serpent_encrypt); ECB_WALK_END(); } static int ecb_decrypt(struct skcipher_request *req) { ECB_WALK_START(req, SERPENT_BLOCK_SIZE, SERPENT_PARALLEL_BLOCKS); ECB_BLOCK(SERPENT_PARALLEL_BLOCKS, serpent_dec_blk_xway); ECB_BLOCK(1, __serpent_decrypt); ECB_WALK_END(); } static int cbc_encrypt(struct skcipher_request *req) { CBC_WALK_START(req, SERPENT_BLOCK_SIZE, -1); CBC_ENC_BLOCK(__serpent_encrypt); CBC_WALK_END(); } static int cbc_decrypt(struct skcipher_request *req) { CBC_WALK_START(req, SERPENT_BLOCK_SIZE, SERPENT_PARALLEL_BLOCKS); CBC_DEC_BLOCK(SERPENT_PARALLEL_BLOCKS, serpent_decrypt_cbc_xway); CBC_DEC_BLOCK(1, __serpent_decrypt); CBC_WALK_END(); } static struct skcipher_alg serpent_algs[] = { { .base.cra_name = "__ecb(serpent)", .base.cra_driver_name = "__ecb-serpent-sse2", .base.cra_priority = 400, .base.cra_flags = CRYPTO_ALG_INTERNAL, .base.cra_blocksize = SERPENT_BLOCK_SIZE, .base.cra_ctxsize = sizeof(struct serpent_ctx), .base.cra_module = THIS_MODULE, .min_keysize = SERPENT_MIN_KEY_SIZE, .max_keysize = SERPENT_MAX_KEY_SIZE, .setkey = serpent_setkey_skcipher, .encrypt = ecb_encrypt, .decrypt = ecb_decrypt, }, { .base.cra_name = "__cbc(serpent)", .base.cra_driver_name = "__cbc-serpent-sse2", .base.cra_priority = 400, .base.cra_flags = CRYPTO_ALG_INTERNAL, .base.cra_blocksize = SERPENT_BLOCK_SIZE, .base.cra_ctxsize = sizeof(struct serpent_ctx), .base.cra_module = THIS_MODULE, .min_keysize = SERPENT_MIN_KEY_SIZE, .max_keysize = SERPENT_MAX_KEY_SIZE, .ivsize = SERPENT_BLOCK_SIZE, .setkey = serpent_setkey_skcipher, .encrypt = cbc_encrypt, .decrypt = cbc_decrypt, }, }; static struct simd_skcipher_alg *serpent_simd_algs[ARRAY_SIZE(serpent_algs)]; static int __init serpent_sse2_init(void) { if (!boot_cpu_has(X86_FEATURE_XMM2)) { printk(KERN_INFO "SSE2 instructions are not detected.\n"); return -ENODEV; } return simd_register_skciphers_compat(serpent_algs, ARRAY_SIZE(serpent_algs), serpent_simd_algs); } static void __exit serpent_sse2_exit(void) { simd_unregister_skciphers(serpent_algs, ARRAY_SIZE(serpent_algs), serpent_simd_algs); } module_init(serpent_sse2_init); module_exit(serpent_sse2_exit); MODULE_DESCRIPTION("Serpent Cipher Algorithm, SSE2 optimized"); MODULE_LICENSE("GPL"); MODULE_ALIAS_CRYPTO("serpent");
/* * push fs: 2 bytes * Pushes FS register to stack. * 2 bytes: op (0F A0) */ void push_fs(Emulator *emu) { push_segment_register(emu, FS); emu->eip += 2; }
/** Print rIDL welcome message if not quiet. */ void ridl_welcome(void) { if (!(ridl_options & IDL_INIT_QUIET)) { ridl_printridlversion(); } }
/* * Returns a number with the char value of the string at the index given as parameter * for example: * log "Abcdefg":charAt(0) = 65 */ RaelValue *string_method_charAt(RaelStringValue *self, RaelArgumentList *args, RaelInterpreter *interpreter) { size_t length, idx; RaelValue *arg1; char c; (void)interpreter; if (arguments_amount(args) != 1) { return BLAME_NEW_CSTR("Expected one argument"); } arg1 = arguments_get(args, 0); if (arg1->type != &RaelNumberType) { return BLAME_NEW_CSTR_ST("Expected a number", *arguments_state(args, 0)); } if (!number_is_whole((RaelNumberValue*)arg1)) { return BLAME_NEW_CSTR_ST("Expected a whole number", *arguments_state(args, 0)); } if (!number_positive((RaelNumberValue*)arg1)) { return BLAME_NEW_CSTR_ST("Expected a positive number", *arguments_state(args, 0)); } length = string_length(self); idx = (size_t)number_to_int((RaelNumberValue*)arg1); if (idx >= length) { return BLAME_NEW_CSTR_ST("Index out of range", *arguments_state(args, 0)); } c = self->source[idx]; return number_newi((RaelInt)c); }
/*****************************************************************************/ // Set display of default-status in sbview ON or OFF /*****************************************************************************/ void txwDefaultStatusShow ( BOOL show ) { if (txwa->sbview) { txwa->defaultStatus = show; } }
#ifndef WIRECELLSIGPROC_RESPONSE #define WIRECELLSIGPROC_RESPONSE #include "WireCellUtil/Waveform.h" #include "WireCellUtil/Binning.h" #include "WireCellUtil/Units.h" #include "WireCellUtil/Array.h" #include "WireCellUtil/Point.h" namespace WireCell { namespace Response { //// Units notice: all quantities are expressed in the WCT //// system of unis. In particular, time is not seconds. // These objects correspond to those defined in the Wire Cell // field response transfer file format schema. namespace Schema { // FIXME: this schema is very specific to Garfield 2D // results. The namespace should reflect that and a more // generic interface should hide it. /// Hold information about the induced current response /// due to passage of a charge along one drift path. struct PathResponse { /// An array holding the induced current for the path on the wire-of-interest. WireCell::Waveform::realseq_t current; /// The position in the pitch direction to the starting point of the path. double pitchpos; /// The position along the wire direction to the starting point of the path. double wirepos; PathResponse() : pitchpos(0.0) , wirepos(-99999.0) { } PathResponse(const WireCell::Waveform::realseq_t& c, double p, double w) : current(c) , pitchpos(p) , wirepos(w) { } ~PathResponse(); }; /// Hold information about the collection of induced /// current responses on one wire plane. struct PlaneResponse { /// List of PathResponse objects. std::vector<PathResponse> paths; /// A numerical identifier for the plane. int planeid; /// location, in direction of drift, of this plane (in /// same coordinate system as used by /// FieldResponse::origin). double location; /// The pitch distance between neighboring wires. double pitch; PlaneResponse() : planeid(-1) , location(0.0) , pitch(0.0) { } PlaneResponse(const std::vector<PathResponse>& paths, int pid, double l, double p) : paths(paths) , planeid(pid) , location(l) , pitch(p) { } ~PlaneResponse(); }; /// Hold info about multiple plane responses in the detector. struct FieldResponse { /// List of PlaneResponse objects. std::vector<PlaneResponse> planes; /// A normalized 3-vector giving direction of axis /// (anti)parallel to nominal drift direction. WireCell::Vector axis; /// The location on the X-axis where drift paths /// begin. See PlaneResponse::location. double origin; /// Time at which drift paths begin. double tstart; /// The sampling period of the response function. double period; /// The nominal drift speed. double speed; PlaneResponse* plane(int ident) { for (auto& pr : planes) { if (pr.planeid == ident) { return &pr; } } return nullptr; } const PlaneResponse* plane(int ident) const { for (auto& pr : planes) { if (pr.planeid == ident) { return &pr; } } return nullptr; } FieldResponse() : origin(-999.0) , tstart(-999.0) , period(0.0) , speed(0.0) { } FieldResponse(const std::vector<PlaneResponse>& planes, const WireCell::Vector& adir, double o, double t, double p, double s) : planes(planes) , axis(adir) , origin(o) , tstart(t) , period(p) , speed(s) { } ~FieldResponse(); }; FieldResponse load(const char* filename); void dump(const char* filename, const FieldResponse& fr); } // namespace Schema /// Return a reduced FieldResponse structure where the /// Path::Response::current arrays are reduced by averaging /// over each wire region. Schema::FieldResponse wire_region_average(const Schema::FieldResponse& fr); Schema::FieldResponse average_1D(const Schema::FieldResponse& fr); /// Return the plane's response as a 2D array. This is a /// straight copy of the plane's current vectors into rows of /// the returned array. The first "path" will be in row 0. /// Each column thus contains the same sample (aka tick) /// across all current waveforms. Column 0 is first sample. /// The plane response input data is taken at face value an /// not attempt to resolve any implicit symmetries is made. Array::array_xxf as_array(const Schema::PlaneResponse& pr); Array::array_xxf as_array(const Schema::PlaneResponse& pr, int set_nrows, int set_ncols); /// The cold electronics response function. double coldelec(double time, double gain = 7.8, double shaping = 1.0 * units::us); /// The warm electronics response function. double warmelec(double time, double gain = 30, double shaping = 1.3 * units::us); // HF filter format double hf_filter(double freq, double sigma = 1, double power = 2, bool zero_freq_removal = true); // LF filter format double lf_filter(double freq, double tau = 0.02); class Generator { public: virtual ~Generator(); virtual double operator()(double time) const = 0; /// FIXME: eradicate Domain in favor of Binning. WireCell::Waveform::realseq_t generate(const WireCell::Waveform::Domain& domain, int nsamples); /// Lay down the function into a binned waveform. WireCell::Waveform::realseq_t generate(const WireCell::Binning& tbins); }; /// A functional object caching gain and shape. class ColdElec : public Generator { const double _g, _s; public: // Create cold electronics response function. Gain is an // arbitrary scale, typically in [voltage/charge], and // shaping time in WCT system of units. ColdElec(double gain = 14 * units::mV / units::fC, double shaping = 1.0 * units::us); virtual ~ColdElec(); // Return the response at given time. Time is in WCT // system of units. virtual double operator()(double time) const; }; /// A functional object caching gain and shape. /// ICARUS warm electronics class WarmElec : public Generator { const double _g, _s; public: // Create warm electronics response function. Gain is an // arbitrary scale, typically in [voltage/charge], and // shaping time in WCT system of units. WarmElec(double gain = 30 * units::mV / units::fC, double shaping = 1.3 * units::us); virtual ~WarmElec(); // Return the response at given time. Time is in WCT // system of units. virtual double operator()(double time) const; }; /// A functional object giving the response as a function of /// time to a simple RC circuit. class SimpleRC : public Generator { const double _width, _offset, _tick; public: // Create (current) response function for a simple RC // circuit where a unit of charge is placed on the cap at // time offset and circuit has RC time constant of given // width. Time is in WCT system of units. SimpleRC(double width = 1.0 * units::ms, double tick = 0.5 * units::us, double offset = 0.0); virtual ~SimpleRC(); // Return the response at a given time. Time in WCT // system of units. Warning: to get the delta function, // one must call *exactly* at the offset time. virtual double operator()(double time) const; }; class SysResp : public Generator { const double _tick, _mag, _smear, _offset; public: SysResp(double tick = 0.5 * units::us, double magnitude = 1.0, double smear = 0.0 * units::us, double offset = 0.0 * units::us); virtual ~SysResp(); virtual double operator()(double time) const; }; class LfFilter : public Generator { const double _tau; public: LfFilter(double tau); virtual ~LfFilter(); virtual double operator()(double freq) const; }; class HfFilter : public Generator { const double _sigma, _power; const bool _flag; public: HfFilter(double sigma, double power, bool flag); virtual ~HfFilter(); virtual double operator()(double freq) const; }; } // namespace Response } // namespace WireCell #endif
/** compute the next matrix with the weight off all the longest paths with exactly narcs and store it in * adjacencymatrix[narcs - 1]. For this, simply compute * \f{align*}{ d^{k}(currentnode,successor) = max_{l=1,\ldots,n} \{d^{k-1}(currentnode,l) + d^1(l,successor) \} \f}. */ static SCIP_Bool computeNextAdjacency ( SCIP* scip, SCIP_Real*** adjacencymatrix, SCIP_DIGRAPH* adjacencygraph, int narcs ) { int* intermediates; int nintermediates; int currentnode; int intermediate; int successor; int l; int nnodes; SCIP_Bool foundviolation; foundviolation = FALSE; nnodes = SCIPdigraphGetNNodes(adjacencygraph); for( currentnode = 0; currentnode < nnodes; ++currentnode ) { intermediates = SCIPdigraphGetSuccessors(adjacencygraph, currentnode); nintermediates = SCIPdigraphGetNSuccessors(adjacencygraph, currentnode); for( l = 0; l < nintermediates; ++l ) { intermediate = intermediates[l]; assert(0 <= intermediate && intermediate < nnodes); for( successor = 0; successor < nnodes; ++successor ) { if( SCIPisPositive(scip, getDist(adjacencymatrix, 0, currentnode, intermediate)) && SCIPisPositive(scip, getDist(adjacencymatrix, narcs - 2, intermediate, successor)) ) { if( SCIPisGT(scip, getDist(adjacencymatrix, 0, currentnode, intermediate) + getDist(adjacencymatrix, narcs - 2, intermediate, successor), getDist(adjacencymatrix, narcs - 1, currentnode, successor)) ) { adjacencymatrix[narcs - 1][currentnode][successor] = getDist(adjacencymatrix, 0, currentnode, intermediate) + getDist(adjacencymatrix, narcs - 2, intermediate, successor); } } } } } for( currentnode = 0; currentnode < nnodes; ++currentnode ) { if( SCIPisGT(scip, getDist(adjacencymatrix, narcs - 1, currentnode, currentnode), narcs - 1.0) ) foundviolation = TRUE; } return foundviolation; }
/* * Make sure we have a unique name space in attribute name definition */ static BOOLEAN _VmDirSchemaVerifyATNameUnique( PVDIR_SCHEMA_AT_COLLECTION pATCollection ) { int dwCnt = 0; for (dwCnt = 0; dwCnt < pATCollection->usNumATs - 1; dwCnt++) { if (VmDirStringCompareA(pATCollection->pATSortName[dwCnt ].pszName, pATCollection->pATSortName[dwCnt+1].pszName, FALSE) == 0) { VmDirLog( LDAP_DEBUG_ANY, "schemaVerifyATNameUnique:(%s).", VDIR_SAFE_STRING(pATCollection->pATSortName[dwCnt ].pszName)); return FALSE; } } return TRUE; }
/* to be called when the Rom is loaded and byteswapped */ void PicoPatchPrepare(void) { int i; for (i = 0; i < PicoPatchCount; i++) { PicoPatches[i].addr &= ~1; if (PicoPatches[i].addr < Pico.romsize) PicoPatches[i].data_old = *(unsigned short *)(Pico.rom + PicoPatches[i].addr); if (strstr(PicoPatches[i].name, "AUTO")) PicoPatches[i].active = 1; } }
/** * Display the authenticated payload timeout event * * @param evdata * @param len */ static void ble_hs_dbg_auth_pyld_tmo_disp(uint8_t *evdata, uint8_t len) { uint16_t handle; if (len != sizeof(uint16_t)) { BLE_HS_LOG(DEBUG, "ERR: AuthPyldTmoEvent bad length %u\n", len); return; } handle = get_le16(evdata); BLE_HS_LOG(DEBUG, "AuthPyldTmo: handle=%u\n", handle); }
/* * Read and return #unigrams, #bigrams, #trigrams as stated in input file. */ static void ReadNgramCounts (FILE *fp, int32 *n_ug, int32 *n_bg, int32 *n_tg) { char string[256]; int32 ngram, ngram_cnt; do fgets (string, sizeof (string), fp); while ( (strcmp (string, "\\data\\\n") != 0) && (! feof (fp)) ); if (strcmp (string, "\\data\\\n") != 0) QUIT((stderr, "%s(%d): No \\data\\ mark in LM file\n", __FILE__, __LINE__)); *n_ug = *n_bg = *n_tg = 0; while (fgets (string, sizeof (string), fp) != NULL) { if (sscanf (string, "ngram %d=%d", &ngram, &ngram_cnt) != 2) break; switch (ngram) { case 1: *n_ug = ngram_cnt; break; case 2: *n_bg = ngram_cnt; break; case 3: *n_tg = ngram_cnt; break; default: QUIT((stderr, "%s(%d): Unknown ngram (%d)\n", __FILE__, __LINE__, ngram)); break; } } while ( (strcmp (string, "\\1-grams:\n") != 0) && (! feof (fp)) ) fgets (string, sizeof (string), fp); if ((*n_ug <= 0) || (*n_bg <= 0) || (*n_tg < 0)) QUIT((stderr, "%s(%d): Bad or missing ngram count\n", __FILE__, __LINE__)); }
#include<stdio.h> #include<string.h> struct pp{ char name[100]; int t; }; int main(void){ int q,head,tail,n; int st=0; int i=0; scanf("%d %d", &n, &q); int c=n; struct pp P[n+1]; while(c--) { scanf("%s %d",&P[i].name,&P[i].t); i++; } for ( head=0,tail=n;head!=tail;head=(head+1)%(n+1)) { i=head; if(P[i].t>q) { st+=q; P[tail].t=P[i].t-q; strcpy(P[tail].name,P[i].name); tail=(tail+1)%(n+1); } else { st+=P[i].t; printf("%s %d\n",P[i].name,st); P[i].t=0; } } return 0; }
/* * Copyright 2020 Broadcom * * SPDX-License-Identifier: Apache-2.0 */ #include <zephyr/devicetree.h> #include <zephyr/sys/util.h> #include <zephyr/arch/arm64/arm_mmu.h> #define PCIE_OB_HIGHMEM_ADDR DT_REG_ADDR_BY_NAME(DT_NODELABEL(pcie0_ep), \ map_highmem) #define PCIE_OB_HIGHMEM_SIZE DT_REG_SIZE_BY_NAME(DT_NODELABEL(pcie0_ep), \ map_highmem) static const struct arm_mmu_region mmu_regions[] = { MMU_REGION_FLAT_ENTRY("DEVICE_REGION", 0x40000000, MB(512), MT_DEVICE_nGnRnE | MT_P_RW_U_NA | MT_SECURE), MMU_REGION_FLAT_ENTRY("PCIE_HIGH_OBMEM", PCIE_OB_HIGHMEM_ADDR, PCIE_OB_HIGHMEM_SIZE, MT_DEVICE_nGnRnE | MT_P_RW_U_NA | MT_SECURE), MMU_REGION_FLAT_ENTRY("DRAM0_S0", 0x60000000, MB(512), MT_NORMAL | MT_P_RW_U_NA | MT_SECURE), }; const struct arm_mmu_config mmu_config = { .num_regions = ARRAY_SIZE(mmu_regions), .mmu_regions = mmu_regions, };
#include<stdio.h> #include<stdlib.h> #define string(num,c) \ for(i = 0;i < num;i++){ \ printf("%s",c); \ } \ int main(void){ int sx,sy,tx,ty,i,dx,dy; scanf("%d %d %d %d",&sx,&sy,&tx,&ty); dx = tx - sx; dy = ty - sy; string(dy,"U"); string(dx,"R"); string(dy,"D"); string(dx,"L"); printf("L"); string(dy+1,"U"); string(dx+1,"R"); printf("D"); printf("R"); string(dy+1,"D"); string(dx+1,"L"); printf("U\n"); return 0; }
/* * Custom key pg.checkpoint_avg_interval * * Returns the average interval in seconds between all checkpoints that have * run since statistics were reset. * * Parameters: * 0: connection string * 1: connection database * * Returns: d */ int PG_BG_AVG_INTERVAL(AGENT_REQUEST *request, AGENT_RESULT *result) { int ret = SYSINFO_RET_FAIL; const char *__function_name = "PG_BG_AVG_INTERVAL"; const char *pgsql_bg_avg_interval = "\ SELECT \ CASE checkpoints_timed + checkpoints_req \ WHEN 0 THEN 0 \ ELSE EXTRACT(EPOCH FROM (NOW() - stats_reset)) / (checkpoints_timed + checkpoints_req) \ END \ FROM pg_stat_bgwriter;"; zabbix_log(LOG_LEVEL_DEBUG, "In %s()", __function_name); ret = pg_get_dbl(request, result, pgsql_bg_avg_interval, NULL); zabbix_log(LOG_LEVEL_DEBUG, "End of %s()", __function_name); return ret; }
/** * SECTION:liboilrandom * @title: Random Number Generation * @short_description: Random number generation */ static void _oil_random_bits (void *dest, int n) { int i; uint8_t *d = dest; for(i=0;i<n;i++){ d[i] = (rand()>>16); } }
/* * Get next entry in opened directory structure. * Copies fields into the dirent structure, updates dirinfo. Note that it is * the _caller's_ responsibility to handle the '.' and '..' entries. * A deleted file will be returned as a NULL entry (first char of filename=0) * by this code. Filenames beginning with 0x05 will be translated to 0xE5 * automatically. Long file name entries will be returned as NULL. * returns DFS_EOF if there are no more entries, DFS_OK if this entry is valid, * or DFS_ERRMISC for a media error */ uint32_t fat_get_next(struct dirinfo *dir, struct fat_dirent *dirent) { struct fat_dirent *dirent_src; uint32_t tmp; dirent->name[0] = '\0'; log_debug("dir->currententry %d", dir->currententry); if (DFS_OK != (tmp = fat_fetch_dir(dir))) { if (tmp == DFS_ALLOCNEW) { if (DFS_OK != (tmp = fat_dir_extend(dir))) { return tmp; } } else { return tmp; } } dirent_src = &((struct fat_dirent *) dir->p_scratch)[dir->currententry]; memcpy(dirent, dirent_src, sizeof(struct fat_dirent)); log_debug("dir: p_scratch = %p, currententry = %d",dir->p_scratch, dir->currententry); log_debug("dirent->name (%s), dirent->name[0]=0x%x", dirent->name, dirent->name[0]); if (dirent->name[0] == '\0') { if (dir->flags & DFS_DI_BLANKENT) { dir->currententry++; return DFS_OK; } else { return DFS_EOF; } } if (dirent->name[0] == 0xe5) { memset(dirent, 0, sizeof(*dirent)); } else if (dirent->name[0] == 0x05) dirent->name[0] = 0xe5; dir->currententry++; return DFS_OK; }
/* * arch/arm/mach-kirkwood/netspace_v2-setup.c * * LaCie Network Space v2 board setup * * Copyright (C) 2009 Simon Guinot <sguinot@lacie.com> * Copyright (C) 2009 Benoît Canet <benoit.canet@gmail.com> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include <linux/kernel.h> #include <linux/init.h> #include <linux/platform_device.h> #include <linux/ata_platform.h> #include <linux/mv643xx_eth.h> #include <linux/input.h> #include <linux/gpio.h> #include <linux/gpio_keys.h> #include <linux/leds.h> #include <linux/gpio-fan.h> #include <asm/mach-types.h> #include <asm/mach/arch.h> #include <mach/kirkwood.h> #include <mach/leds-ns2.h> #include "common.h" #include "mpp.h" #include "lacie_v2-common.h" /***************************************************************************** * Ethernet ****************************************************************************/ static struct mv643xx_eth_platform_data netspace_v2_ge00_data = { .phy_addr = MV643XX_ETH_PHY_ADDR(8), }; /***************************************************************************** * SATA ****************************************************************************/ static struct mv_sata_platform_data netspace_v2_sata_data = { .n_ports = 2, }; /***************************************************************************** * GPIO keys ****************************************************************************/ #define NETSPACE_V2_PUSH_BUTTON 32 static struct gpio_keys_button netspace_v2_buttons[] = { [0] = { .code = KEY_POWER, .gpio = NETSPACE_V2_PUSH_BUTTON, .desc = "Power push button", .active_low = 0, }, }; static struct gpio_keys_platform_data netspace_v2_button_data = { .buttons = netspace_v2_buttons, .nbuttons = ARRAY_SIZE(netspace_v2_buttons), }; static struct platform_device netspace_v2_gpio_buttons = { .name = "gpio-keys", .id = -1, .dev = { .platform_data = &netspace_v2_button_data, }, }; /***************************************************************************** * GPIO LEDs ****************************************************************************/ #define NETSPACE_V2_GPIO_RED_LED 12 static struct gpio_led netspace_v2_gpio_led_pins[] = { { .name = "ns_v2:red:fail", .gpio = NETSPACE_V2_GPIO_RED_LED, }, }; static struct gpio_led_platform_data netspace_v2_gpio_leds_data = { .num_leds = ARRAY_SIZE(netspace_v2_gpio_led_pins), .leds = netspace_v2_gpio_led_pins, }; static struct platform_device netspace_v2_gpio_leds = { .name = "leds-gpio", .id = -1, .dev = { .platform_data = &netspace_v2_gpio_leds_data, }, }; /***************************************************************************** * Dual-GPIO CPLD LEDs ****************************************************************************/ #define NETSPACE_V2_GPIO_BLUE_LED_SLOW 29 #define NETSPACE_V2_GPIO_BLUE_LED_CMD 30 static struct ns2_led netspace_v2_led_pins[] = { { .name = "ns_v2:blue:sata", .cmd = NETSPACE_V2_GPIO_BLUE_LED_CMD, .slow = NETSPACE_V2_GPIO_BLUE_LED_SLOW, }, }; static struct ns2_led_platform_data netspace_v2_leds_data = { .num_leds = ARRAY_SIZE(netspace_v2_led_pins), .leds = netspace_v2_led_pins, }; static struct platform_device netspace_v2_leds = { .name = "leds-ns2", .id = -1, .dev = { .platform_data = &netspace_v2_leds_data, }, }; /***************************************************************************** * GPIO fan ****************************************************************************/ /* Designed for fan 40x40x16: ADDA AD0412LB-D50 6000rpm@12v */ static struct gpio_fan_speed netspace_max_v2_fan_speed[] = { { 0, 0 }, { 1500, 15 }, { 1700, 14 }, { 1800, 13 }, { 2100, 12 }, { 3100, 11 }, { 3300, 10 }, { 4300, 9 }, { 5500, 8 }, }; static unsigned netspace_max_v2_fan_ctrl[] = { 22, 7, 33, 23 }; static struct gpio_fan_alarm netspace_max_v2_fan_alarm = { .gpio = 25, .active_low = 1, }; static struct gpio_fan_platform_data netspace_max_v2_fan_data = { .num_ctrl = ARRAY_SIZE(netspace_max_v2_fan_ctrl), .ctrl = netspace_max_v2_fan_ctrl, .alarm = &netspace_max_v2_fan_alarm, .num_speed = ARRAY_SIZE(netspace_max_v2_fan_speed), .speed = netspace_max_v2_fan_speed, }; static struct platform_device netspace_max_v2_gpio_fan = { .name = "gpio-fan", .id = -1, .dev = { .platform_data = &netspace_max_v2_fan_data, }, }; /***************************************************************************** * General Setup ****************************************************************************/ static unsigned int netspace_v2_mpp_config[] __initdata = { MPP0_SPI_SCn, MPP1_SPI_MOSI, MPP2_SPI_SCK, MPP3_SPI_MISO, MPP4_NF_IO6, MPP5_NF_IO7, MPP6_SYSRST_OUTn, MPP7_GPO, /* Fan speed (bit 1) */ MPP8_TW0_SDA, MPP9_TW0_SCK, MPP10_UART0_TXD, MPP11_UART0_RXD, MPP12_GPO, /* Red led */ MPP14_GPIO, /* USB fuse */ MPP16_GPIO, /* SATA 0 power */ MPP17_GPIO, /* SATA 1 power */ MPP18_NF_IO0, MPP19_NF_IO1, MPP20_SATA1_ACTn, MPP21_SATA0_ACTn, MPP22_GPIO, /* Fan speed (bit 0) */ MPP23_GPIO, /* Fan power */ MPP24_GPIO, /* USB mode select */ MPP25_GPIO, /* Fan rotation fail */ MPP26_GPIO, /* USB device vbus */ MPP28_GPIO, /* USB enable host vbus */ MPP29_GPIO, /* Blue led (slow register) */ MPP30_GPIO, /* Blue led (command register) */ MPP31_GPIO, /* Board power off */ MPP32_GPIO, /* Power button (0 = Released, 1 = Pushed) */ MPP33_GPO, /* Fan speed (bit 2) */ 0 }; #define NETSPACE_V2_GPIO_POWER_OFF 31 static void netspace_v2_power_off(void) { gpio_set_value(NETSPACE_V2_GPIO_POWER_OFF, 1); } static void __init netspace_v2_init(void) { /* * Basic setup. Needs to be called early. */ kirkwood_init(); kirkwood_mpp_conf(netspace_v2_mpp_config); if (machine_is_netspace_max_v2()) lacie_v2_hdd_power_init(2); else lacie_v2_hdd_power_init(1); kirkwood_ehci_init(); kirkwood_ge00_init(&netspace_v2_ge00_data); kirkwood_sata_init(&netspace_v2_sata_data); kirkwood_uart0_init(); lacie_v2_register_flash(); lacie_v2_register_i2c_devices(); platform_device_register(&netspace_v2_leds); platform_device_register(&netspace_v2_gpio_leds); platform_device_register(&netspace_v2_gpio_buttons); if (machine_is_netspace_max_v2()) platform_device_register(&netspace_max_v2_gpio_fan); if (gpio_request(NETSPACE_V2_GPIO_POWER_OFF, "power-off") == 0 && gpio_direction_output(NETSPACE_V2_GPIO_POWER_OFF, 0) == 0) pm_power_off = netspace_v2_power_off; else pr_err("netspace_v2: failed to configure power-off GPIO\n"); } #ifdef CONFIG_MACH_NETSPACE_V2 MACHINE_START(NETSPACE_V2, "LaCie Network Space v2") .boot_params = 0x00000100, .init_machine = netspace_v2_init, .map_io = kirkwood_map_io, .init_early = kirkwood_init_early, .init_irq = kirkwood_init_irq, .timer = &kirkwood_timer, MACHINE_END #endif #ifdef CONFIG_MACH_INETSPACE_V2 MACHINE_START(INETSPACE_V2, "LaCie Internet Space v2") .boot_params = 0x00000100, .init_machine = netspace_v2_init, .map_io = kirkwood_map_io, .init_early = kirkwood_init_early, .init_irq = kirkwood_init_irq, .timer = &kirkwood_timer, MACHINE_END #endif #ifdef CONFIG_MACH_NETSPACE_MAX_V2 MACHINE_START(NETSPACE_MAX_V2, "LaCie Network Space Max v2") .boot_params = 0x00000100, .init_machine = netspace_v2_init, .map_io = kirkwood_map_io, .init_early = kirkwood_init_early, .init_irq = kirkwood_init_irq, .timer = &kirkwood_timer, MACHINE_END #endif
/* ---------------------------------------------------------------------------- * Copyright 2017, Massachusetts Institute of Technology, * Cambridge, MA 02139 * All Rights Reserved * Authors: Luca Carlone, et al. (see THANKS for the full author list) * See LICENSE for the license information * -------------------------------------------------------------------------- */ /** * @file Tracker-definitions.h * @brief Definitions for Tracker * @author Antoni Rosinol */ #pragma once #include <string> #include <glog/logging.h> #include <gtsam/geometry/Pose3.h> #include <gtsam/base/Matrix.h> // OpenGV for Ransac // TODO clean this includes!! some are only needed in cpp of tracker. #include <opengv/sac/Ransac.hpp> #include <opengv/sac_problems/relative_pose/TranslationOnlySacProblem.hpp> #include <opengv/sac_problems/relative_pose/CentralRelativePoseSacProblem.hpp> #include <opengv/relative_pose/methods.hpp> #include <opengv/relative_pose/CentralRelativeAdapter.hpp> #include <opengv/triangulation/methods.hpp> #include <opengv/sac_problems/point_cloud/PointCloudSacProblem.hpp> #include <opengv/point_cloud/methods.hpp> #include <opengv/point_cloud/PointCloudAdapter.hpp> #include "kimera-vio/common/vio_types.h" namespace VIO { // Mono // 5-point ransac using ProblemMono = opengv::sac_problems::relative_pose::CentralRelativePoseSacProblem; using AdapterMono = opengv::relative_pose::CentralRelativeAdapter; // MonoTranslationOnly: TranslationOnlySacProblem // 2-point ransac using ProblemMonoGivenRot = opengv::sac_problems::relative_pose::TranslationOnlySacProblem; using AdapterMonoGivenRot = opengv::relative_pose::CentralRelativeAdapter; // Stereo // Arun's problem (3-point ransac) using ProblemStereo = opengv::sac_problems::point_cloud::PointCloudSacProblem; using AdapterStereo = opengv::point_cloud::PointCloudAdapter; //////////////////////////////////////////////////////////////////////////////// class DebugTrackerInfo { public: // Info about feature detection, tracking and ransac. size_t nrDetectedFeatures_ = 0, nrTrackerFeatures_ = 0, nrMonoInliers_ = 0; size_t nrMonoPutatives_ = 0, nrStereoInliers_ = 0, nrStereoPutatives_ = 0; size_t monoRansacIters_ = 0, stereoRansacIters_ = 0; // Info about performance of sparse stereo matching (and ransac): // RPK = right keypoints size_t nrValidRKP_ = 0, nrNoLeftRectRKP_ = 0, nrNoRightRectRKP_ = 0; size_t nrNoDepthRKP_ = 0, nrFailedArunRKP_ = 0; // Info about timing. double featureDetectionTime_ = 0, featureTrackingTime_ = 0; double monoRansacTime_ = 0, stereoRansacTime_ = 0; // Info about feature selector. double featureSelectionTime_ = 0; size_t extracted_corners_ = 0, need_n_corners_ = 0; void printTimes() const { LOG(INFO) << "featureDetectionTime_: " << featureDetectionTime_ << " s\n" << "featureSelectionTime_: " << featureSelectionTime_ << " s\n" << "featureTrackingTime_: " << featureTrackingTime_ << " s\n" << "monoRansacTime_: " << monoRansacTime_ << " s\n" << "stereoRansacTime_: " << stereoRansacTime_ << " s"; } void print() const { LOG(INFO) << "nrDetectedFeatures_: " << nrDetectedFeatures_ << "\n" << "nrTrackerFeatures_: " << nrTrackerFeatures_ << "\n" << "nrMonoInliers_: " << nrMonoInliers_ << "\n" << "nrMonoPutatives_: " << nrMonoPutatives_ << "\n" << "nrStereoInliers_: " << nrStereoInliers_ << "\n" << "nrStereoPutatives_: " << nrStereoPutatives_ << "\n" << "monoRansacIters_: " << monoRansacIters_ << "\n" << "stereoRansacIters_: " << stereoRansacIters_ << "\n" << "nrValidRKP_: " << nrValidRKP_ << "\n" << "nrNoLeftRectRKP_: " << nrNoLeftRectRKP_ << "\n" << "nrNoRightRectRKP_: " << nrNoRightRectRKP_ << "\n" << "nrNoDepthRKP_: " << nrNoDepthRKP_ << "\n" << "nrFailedArunRKP_: " << nrFailedArunRKP_; } }; enum class TrackingStatus { VALID, LOW_DISPARITY, FEW_MATCHES, INVALID, DISABLED }; typedef std::pair<TrackingStatus, gtsam::Pose3> TrackingStatusPose; //////////////////////////////////////////////////////////////////////////////// class TrackerStatusSummary { public: TrackerStatusSummary() : kfTrackingStatus_mono_(TrackingStatus::INVALID), kfTrackingStatus_stereo_(TrackingStatus::INVALID), lkf_T_k_mono_(gtsam::Pose3::identity()), lkf_T_k_stereo_(gtsam::Pose3::identity()), infoMatStereoTranslation_(gtsam::Matrix3::Zero()) {} /* ------------------------------------------------------------------------ */ // Returns the tracking status as a string for debugging static std::string asString( const TrackingStatus& status) { std::string status_str = ""; switch(status) { case TrackingStatus::VALID: {status_str = "VALID"; break;} case TrackingStatus::INVALID: {status_str = "INVALID"; break;} case TrackingStatus::DISABLED: {status_str = "DISABLED"; break;} case TrackingStatus::FEW_MATCHES: {status_str = "FEW_MATCHES"; break;} case TrackingStatus::LOW_DISPARITY: {status_str = "LOW_DISPARITY"; break;} } return status_str; } public: TrackingStatus kfTrackingStatus_mono_; TrackingStatus kfTrackingStatus_stereo_; gtsam::Pose3 lkf_T_k_mono_; gtsam::Pose3 lkf_T_k_stereo_; gtsam::Matrix3 infoMatStereoTranslation_; }; typedef double KeypointScore; typedef std::vector<double> KeypointScores; typedef std::pair<KeypointsCV, KeypointScores> KeypointsWithScores; typedef std::pair<size_t, size_t> KeypointMatch; typedef std::vector<std::pair<size_t, size_t>> KeypointMatches; } // End of VIO namespace.
/* * 'External' SCS function. Handles leftover data from any previous, * incomplete SCS record. */ enum pds process_scs(unsigned char *buf, int buflen) { enum pds r; if (scs_leftover_len) { unsigned char *contig = Malloc(scs_leftover_len + buflen); int total_len; (void) memcpy(contig, scs_leftover_buf, scs_leftover_len); (void) memcpy(contig + scs_leftover_len, buf, buflen); total_len = scs_leftover_len + buflen; scs_leftover_len = 0; r = process_scs_contig(contig, total_len); Free(contig); } else { r = process_scs_contig(buf, buflen); } return r; }
// Copyright (c) 2019 Computer Vision Center (CVC) at the Universitat Autonoma // de Barcelona (UAB). // // This work is licensed under the terms of the MIT license. // For a copy, see <https://opensource.org/licenses/MIT>. #pragma once #include "Carla/OpenDrive/OpenDriveActor.h" #include "Commandlets/Commandlet.h" #include "Runtime/Engine/Classes/Engine/ObjectLibrary.h" #if WITH_EDITORONLY_DATA #include "AssetRegistry/Public/AssetRegistryModule.h" #include "Developer/AssetTools/Public/AssetToolsModule.h" #endif // WITH_EDITORONLY_DATA #include "MoveAssetsCommandlet.generated.h" /// Struct containing Package Params, used for storing the parsed arguments when /// invoking this commandlet USTRUCT() struct CARLA_API FMovePackageParams { GENERATED_USTRUCT_BODY() FString Name; TArray<FString> MapNames; }; UCLASS() class UMoveAssetsCommandlet : public UCommandlet { GENERATED_BODY() public: /// Default constructor. UMoveAssetsCommandlet(); #if WITH_EDITORONLY_DATA /// Parses the command line parameters provided through @a InParams The /// arguments to parse are the package name and a list of map names /// concatenated in a string. FMovePackageParams ParseParams(const FString &InParams) const; /// Moves all the assets contained in a map from @a SrcPath to @a DestPath void MoveAssetsFromMapForSemanticSegmentation(const FString &PackageName, const FString &MapName); /// Moves the meshes of all maps listed in a @PackageParams void MoveAssets(const FMovePackageParams &PackageParams); public: /// Main method and entry of the commandlet, taking as input parameters @a /// Params. virtual int32 Main(const FString &Params) override; #endif // WITH_EDITORONLY_DATA private: /// The following data structures are declared as class members and with /// UPROPERTY macro to avoid UE4 to garbage collect them. /// Loaded assets from any object library UPROPERTY() TArray<FAssetData> AssetDatas; /// Loaded maps from any object library UPROPERTY() TArray<FAssetData> MapContents; /// Used for loading assets in object library. Loaded Data is stored in /// AssetDatas. UPROPERTY() UObjectLibrary *AssetsObjectLibrary; };
/* Print a usage message and exit */ static void usage(int status, char *msg) { if (msg) fprintf(stderr, "%s: %s\n", argv0, msg); fprintf(stderr, "Usage: %s [options] [file]\n", argv0); fprintf(stderr, " -Pxxx Set print options:\n"); fprintf(stderr, " B = Print backup system header (if any)\n"); fprintf(stderr, " H = Print AFS dump header\n"); fprintf(stderr, " V = Print AFS volume header\n"); fprintf(stderr, " v = List vnodes\n"); fprintf(stderr, " p = Include path to each vnode\n"); fprintf(stderr, " i = Include info for each vnode\n"); fprintf(stderr, " d = List directory contents\n"); fprintf(stderr, " a = List access control lists\n"); fprintf(stderr, " g = Print debugging info\n"); fprintf(stderr, " -Rxxx Set repair options:\n"); fprintf(stderr, " 0 = Skip null tags\n"); fprintf(stderr, " b = Seek backward to find skipped tags\n"); fprintf(stderr, " d = Resync after vnode data\n"); fprintf(stderr, " v = Resync after corrupted vnodes\n"); fprintf(stderr, " -Annn Add all rights for ID nnn to every directory\n"); fprintf(stderr, " -h Print this help message\n"); fprintf(stderr, " -gxxx Generate a new dump in file xxx\n"); fprintf(stderr, " -q Quiet mode (don't print errors)\n"); fprintf(stderr, " -v Verbose mode\n"); exit(status); }
#include <stdio.h> #include <string.h> struct String { char string[100]; int size; }; int main(void) { struct String original, translated, check; int yep; yep = 1; scanf("%s", &original.string); scanf("%s", &translated.string); original.size = strlen(original.string); for (int i = 0; i <= original.size; i++) { check.string[i] = original.string[(original.size - (i + 1))]; } for (int i = 0; i < original.size; i++) { if (translated.string[i] != check.string[i]) { yep = 0; break; } else { yep = 1; } } if (yep == 1) { printf("YES"); } else { printf("NO"); } return 0; }
/* We use a single fixed TCE table for all PSI interfaces */ static void fsp_init_tce_table(void) { fsp_tce_table = (__be64 *)PSI_TCE_TABLE_BASE; memset(fsp_tce_table, 0, PSI_TCE_TABLE_SIZE); }
/** * gtk_editable_delete_text: (virtual do_delete_text) * @editable: a `GtkEditable` * @start_pos: start position * @end_pos: end position * * Deletes a sequence of characters. * * The characters that are deleted are those characters at positions * from @start_pos up to, but not including @end_pos. If @end_pos is * negative, then the characters deleted are those from @start_pos to * the end of the text. * * Note that the positions are specified in characters, not bytes. */ void gtk_editable_delete_text (GtkEditable *editable, int start_pos, int end_pos) { g_return_if_fail (GTK_IS_EDITABLE (editable)); GTK_EDITABLE_GET_IFACE (editable)->do_delete_text (editable, start_pos, end_pos); }
/* Return the current file name and line number. */ const char * as_where (unsigned int *linep) { if (logical_input_file != NULL && (linep == NULL || logical_input_line >= 0)) { if (linep != NULL) *linep = logical_input_line; return logical_input_file; } else if (physical_input_file != NULL) { if (linep != NULL) *linep = physical_input_line; return physical_input_file; } else { if (linep != NULL) *linep = 0; return NULL; } }
//Pone el footer segun lo que corresponda, si primer mensaje o segundo mensaje activo void autoselect_options_put_footer(void) { if (tape_options_set_first_message_counter!=0) { menu_putstring_footer(0,2," ",WINDOW_FOOTER_INK,WINDOW_FOOTER_PAPER); menu_putstring_footer(0,2,mostrar_footer_first_message_mostrado,WINDOW_FOOTER_PAPER,WINDOW_FOOTER_INK); return; } if (tape_options_set_second_message_counter!=0) { menu_putstring_footer(0,2," ",WINDOW_FOOTER_INK,WINDOW_FOOTER_PAPER); menu_putstring_footer(0,2,mostrar_footer_second_message_mostrado,WINDOW_FOOTER_PAPER,WINDOW_FOOTER_INK); return; } }
/** * Assumes that the given element is not empty or deleted. */ static UHashTok _uhash_internalRemoveElement(UHashtable *hash, UHashElement* e) { UHashTok empty; U_ASSERT(!IS_EMPTY_OR_DELETED(e->hashcode)); --hash->count; empty.pointer = NULL; empty.integer = 0; return _uhash_setElement(hash, e, HASH_DELETED, empty, empty, 0); }
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include "signtool.h" #include "secoid.h" #include "cryptohi.h" #include "certdb.h" static char *GetSubjectFromUser(unsigned long serial); static CERTCertificate *GenerateSelfSignedObjectSigningCert(char *nickname, CERTCertDBHandle *db, char *subject, unsigned long serial, int keysize, char *token); static SECStatus ChangeTrustAttributes(CERTCertDBHandle *db, CERTCertificate *cert, char *trusts); static SECStatus set_cert_type(CERTCertificate *cert, unsigned int type); static SECItem *sign_cert(CERTCertificate *cert, SECKEYPrivateKey *privk); static CERTCertificate *install_cert(CERTCertDBHandle *db, SECItem *derCert, char *nickname); static SECStatus GenerateKeyPair(PK11SlotInfo *slot, SECKEYPublicKey **pubk, SECKEYPrivateKey **privk, int keysize); static CERTCertificateRequest *make_cert_request(char *subject, SECKEYPublicKey *pubk); static CERTCertificate *make_cert(CERTCertificateRequest *req, unsigned long serial, CERTName *ca_subject); static void output_ca_cert(CERTCertificate *cert, CERTCertDBHandle *db); /*********************************************************************** * * G e n e r a t e C e r t * * Runs the whole process of creating a new cert, getting info from the * user, etc. */ int GenerateCert(char *nickname, int keysize, char *token) { CERTCertDBHandle *db; CERTCertificate *cert; char *subject; unsigned long serial; char stdinbuf[160]; /* Print warning about having the browser open */ PR_fprintf(PR_STDOUT /*always go to console*/, "\nWARNING: Performing this operation while the browser is running could cause" "\ncorruption of your security databases. If the browser is currently running," "\nyou should exit the browser before continuing this operation. Enter " "\n\"y\" to continue, or anything else to abort: "); pr_fgets(stdinbuf, 160, PR_STDIN); PR_fprintf(PR_STDOUT, "\n"); if (tolower(stdinbuf[0]) != 'y') { PR_fprintf(errorFD, "Operation aborted at user's request.\n"); errorCount++; return -1; } db = CERT_GetDefaultCertDB(); if (!db) { FatalError("Unable to open certificate database"); } if (PK11_FindCertFromNickname(nickname, &pwdata)) { PR_fprintf(errorFD, "ERROR: Certificate with nickname \"%s\" already exists in database. You\n" "must choose a different nickname.\n", nickname); errorCount++; exit(ERRX); } LL_L2UI(serial, PR_Now()); subject = GetSubjectFromUser(serial); if (!subject) { FatalError("Unable to get subject from user"); } cert = GenerateSelfSignedObjectSigningCert(nickname, db, subject, serial, keysize, token); if (cert) { output_ca_cert(cert, db); CERT_DestroyCertificate(cert); } PORT_Free(subject); return 0; } #undef VERBOSE_PROMPTS /*********************************************************************8 * G e t S u b j e c t F r o m U s e r * * Construct the subject information line for a certificate by querying * the user on stdin. */ static char * GetSubjectFromUser(unsigned long serial) { char buf[STDIN_BUF_SIZE]; char common_name_buf[STDIN_BUF_SIZE]; char *common_name, *state, *orgunit, *country, *org, *locality; char *email, *uid; char *subject; char *cp; int subjectlen = 0; common_name = state = orgunit = country = org = locality = email = uid = subject = NULL; /* Get subject information */ PR_fprintf(PR_STDOUT, "\nEnter certificate information. All fields are optional. Acceptable\n" "characters are numbers, letters, spaces, and apostrophes.\n"); #ifdef VERBOSE_PROMPTS PR_fprintf(PR_STDOUT, "\nCOMMON NAME\n" "Enter the full name you want to give your certificate. (Example: Test-Only\n" "Object Signing Certificate)\n" "-->"); #else PR_fprintf(PR_STDOUT, "certificate common name: "); #endif if (!fgets(buf, STDIN_BUF_SIZE, stdin)) { return NULL; } cp = chop(buf); if (*cp == '\0') { snprintf(common_name_buf, sizeof(common_name_buf), "%s (%lu)", DEFAULT_COMMON_NAME, serial); cp = common_name_buf; } common_name = PORT_ZAlloc(strlen(cp) + 6); if (!common_name) { out_of_memory(); } snprintf(common_name, strlen(cp) + 6, "CN=%s, ", cp); subjectlen += strlen(common_name); #ifdef VERBOSE_PROMPTS PR_fprintf(PR_STDOUT, "\nORGANIZATION NAME\n" "Enter the name of your organization. For example, this could be the name\n" "of your company.\n" "-->"); #else PR_fprintf(PR_STDOUT, "organization: "); #endif if (!fgets(buf, STDIN_BUF_SIZE, stdin)) { return NULL; } cp = chop(buf); if (*cp != '\0') { org = PORT_ZAlloc(strlen(cp) + 5); if (!org) { out_of_memory(); } snprintf(org, strlen(cp) + 5, "O=%s, ", cp); subjectlen += strlen(org); } #ifdef VERBOSE_PROMPTS PR_fprintf(PR_STDOUT, "\nORGANIZATION UNIT\n" "Enter the name of your organization unit. For example, this could be the\n" "name of your department.\n" "-->"); #else PR_fprintf(PR_STDOUT, "organization unit: "); #endif if (!fgets(buf, STDIN_BUF_SIZE, stdin)) { return NULL; } cp = chop(buf); if (*cp != '\0') { orgunit = PORT_ZAlloc(strlen(cp) + 6); if (!orgunit) { out_of_memory(); } snprintf(orgunit, strlen(cp) + 6, "OU=%s, ", cp); subjectlen += strlen(orgunit); } #ifdef VERBOSE_PROMPTS PR_fprintf(PR_STDOUT, "\nSTATE\n" "Enter the name of your state or province.\n" "-->"); #else PR_fprintf(PR_STDOUT, "state or province: "); #endif if (!fgets(buf, STDIN_BUF_SIZE, stdin)) { return NULL; } cp = chop(buf); if (*cp != '\0') { state = PORT_ZAlloc(strlen(cp) + 6); if (!state) { out_of_memory(); } snprintf(state, strlen(cp) + 6, "ST=%s, ", cp); subjectlen += strlen(state); } #ifdef VERBOSE_PROMPTS PR_fprintf(PR_STDOUT, "\nCOUNTRY\n" "Enter the 2-character abbreviation for the name of your country.\n" "-->"); #else PR_fprintf(PR_STDOUT, "country (must be exactly 2 characters): "); #endif if (!fgets(buf, STDIN_BUF_SIZE, stdin)) { return NULL; } cp = chop(cp); if (strlen(cp) != 2) { *cp = '\0'; /* country code must be 2 chars */ } if (*cp != '\0') { country = PORT_ZAlloc(strlen(cp) + 5); if (!country) { out_of_memory(); } snprintf(country, strlen(cp) + 5, "C=%s, ", cp); subjectlen += strlen(country); } #ifdef VERBOSE_PROMPTS PR_fprintf(PR_STDOUT, "\nUSERNAME\n" "Enter your system username or UID\n" "-->"); #else PR_fprintf(PR_STDOUT, "username: "); #endif if (!fgets(buf, STDIN_BUF_SIZE, stdin)) { return NULL; } cp = chop(buf); if (*cp != '\0') { uid = PORT_ZAlloc(strlen(cp) + 7); if (!uid) { out_of_memory(); } snprintf(uid, strlen(cp) + 7, "UID=%s, ", cp); subjectlen += strlen(uid); } #ifdef VERBOSE_PROMPTS PR_fprintf(PR_STDOUT, "\nEMAIL ADDRESS\n" "Enter your email address.\n" "-->"); #else PR_fprintf(PR_STDOUT, "email address: "); #endif if (!fgets(buf, STDIN_BUF_SIZE, stdin)) { return NULL; } cp = chop(buf); if (*cp != '\0') { email = PORT_ZAlloc(strlen(cp) + 5); if (!email) { out_of_memory(); } snprintf(email, strlen(cp) + 5, "E=%s,", cp); subjectlen += strlen(email); } subjectlen++; subject = PORT_ZAlloc(subjectlen); if (!subject) { out_of_memory(); } snprintf(subject, subjectlen, "%s%s%s%s%s%s%s", common_name ? common_name : "", org ? org : "", orgunit ? orgunit : "", state ? state : "", country ? country : "", uid ? uid : "", email ? email : ""); if ((strlen(subject) > 1) && (subject[strlen(subject) - 1] == ' ')) { subject[strlen(subject) - 2] = '\0'; } PORT_Free(common_name); PORT_Free(org); PORT_Free(orgunit); PORT_Free(state); PORT_Free(country); PORT_Free(uid); PORT_Free(email); return subject; } /************************************************************************** * * G e n e r a t e S e l f S i g n e d O b j e c t S i g n i n g C e r t * *phew*^ * */ static CERTCertificate * GenerateSelfSignedObjectSigningCert(char *nickname, CERTCertDBHandle *db, char *subject, unsigned long serial, int keysize, char *token) { CERTCertificate *cert, *temp_cert; SECItem *derCert; CERTCertificateRequest *req; PK11SlotInfo *slot = NULL; SECKEYPrivateKey *privk = NULL; SECKEYPublicKey *pubk = NULL; if (token) { slot = PK11_FindSlotByName(token); } else { slot = PK11_GetInternalKeySlot(); } if (slot == NULL) { PR_fprintf(errorFD, "Can't find PKCS11 slot %s\n", token ? token : ""); errorCount++; exit(ERRX); } if (GenerateKeyPair(slot, &pubk, &privk, keysize) != SECSuccess) { FatalError("Error generating keypair."); } req = make_cert_request(subject, pubk); temp_cert = make_cert(req, serial, &req->subject); if (set_cert_type(temp_cert, NS_CERT_TYPE_OBJECT_SIGNING | NS_CERT_TYPE_OBJECT_SIGNING_CA) != SECSuccess) { FatalError("Unable to set cert type"); } derCert = sign_cert(temp_cert, privk); cert = install_cert(db, derCert, nickname); if (ChangeTrustAttributes(db, cert, ",,uC") != SECSuccess) { FatalError("Unable to change trust on generated certificate"); } /* !!! Free memory ? !!! */ PK11_FreeSlot(slot); SECKEY_DestroyPrivateKey(privk); SECKEY_DestroyPublicKey(pubk); CERT_DestroyCertificate(temp_cert); CERT_DestroyCertificateRequest(req); return cert; } /************************************************************************** * * C h a n g e T r u s t A t t r i b u t e s */ static SECStatus ChangeTrustAttributes(CERTCertDBHandle *db, CERTCertificate *cert, char *trusts) { CERTCertTrust *trust; if (!db || !cert || !trusts) { PR_fprintf(errorFD, "ChangeTrustAttributes got incomplete arguments.\n"); errorCount++; return SECFailure; } trust = (CERTCertTrust *)PORT_ZAlloc(sizeof(CERTCertTrust)); if (!trust) { PR_fprintf(errorFD, "ChangeTrustAttributes unable to allocate " "CERTCertTrust\n"); errorCount++; return SECFailure; } if (CERT_DecodeTrustString(trust, trusts)) { return SECFailure; } if (CERT_ChangeCertTrust(db, cert, trust)) { PR_fprintf(errorFD, "unable to modify trust attributes for cert %s\n", cert->nickname ? cert->nickname : ""); errorCount++; return SECFailure; } PORT_Free(trust); return SECSuccess; } /************************************************************************* * * s e t _ c e r t _ t y p e */ static SECStatus set_cert_type(CERTCertificate *cert, unsigned int type) { void *context; SECStatus status = SECSuccess; SECItem certType; char ctype; context = CERT_StartCertExtensions(cert); certType.type = siBuffer; certType.data = (unsigned char *)&ctype; certType.len = 1; ctype = (unsigned char)type; if (CERT_EncodeAndAddBitStrExtension(context, SEC_OID_NS_CERT_EXT_CERT_TYPE, &certType, PR_TRUE /*critical*/) != SECSuccess) { status = SECFailure; } if (CERT_FinishExtensions(context) != SECSuccess) { status = SECFailure; } return status; } /******************************************************************** * * s i g n _ c e r t */ static SECItem * sign_cert(CERTCertificate *cert, SECKEYPrivateKey *privk) { SECStatus rv; SECItem der2; SECItem *result2; SECOidTag alg = SEC_OID_UNKNOWN; alg = SEC_GetSignatureAlgorithmOidTag(privk->keyType, SEC_OID_UNKNOWN); if (alg == SEC_OID_UNKNOWN) { FatalError("Unknown key type"); } rv = SECOID_SetAlgorithmID(cert->arena, &cert->signature, alg, 0); if (rv != SECSuccess) { PR_fprintf(errorFD, "%s: unable to set signature alg id\n", PROGRAM_NAME); errorCount++; exit(ERRX); } der2.len = 0; der2.data = NULL; (void)SEC_ASN1EncodeItem(cert->arena, &der2, cert, SEC_ASN1_GET(CERT_CertificateTemplate)); if (rv != SECSuccess) { PR_fprintf(errorFD, "%s: error encoding cert\n", PROGRAM_NAME); errorCount++; exit(ERRX); } result2 = (SECItem *)PORT_ArenaZAlloc(cert->arena, sizeof(SECItem)); if (result2 == NULL) out_of_memory(); rv = SEC_DerSignData(cert->arena, result2, der2.data, der2.len, privk, alg); if (rv != SECSuccess) { PR_fprintf(errorFD, "can't sign encoded certificate data\n"); errorCount++; exit(ERRX); } else if (verbosity >= 0) { PR_fprintf(outputFD, "certificate has been signed\n"); } cert->derCert = *result2; return result2; } /********************************************************************* * * i n s t a l l _ c e r t * * Installs the cert in the permanent database. */ static CERTCertificate * install_cert(CERTCertDBHandle *db, SECItem *derCert, char *nickname) { CERTCertificate *newcert; PK11SlotInfo *newSlot; newSlot = PK11_ImportDERCertForKey(derCert, nickname, &pwdata); if (newSlot == NULL) { PR_fprintf(errorFD, "Unable to install certificate\n"); errorCount++; exit(ERRX); } newcert = PK11_FindCertFromDERCertItem(newSlot, derCert, &pwdata); PK11_FreeSlot(newSlot); if (newcert == NULL) { PR_fprintf(errorFD, "%s: can't find new certificate\n", PROGRAM_NAME); errorCount++; exit(ERRX); } if (verbosity >= 0) { PR_fprintf(outputFD, "certificate \"%s\" added to database\n", nickname); } return newcert; } /****************************************************************** * * G e n e r a t e K e y P a i r */ static SECStatus GenerateKeyPair(PK11SlotInfo *slot, SECKEYPublicKey **pubk, SECKEYPrivateKey **privk, int keysize) { PK11RSAGenParams rsaParams; if (keysize == -1) { rsaParams.keySizeInBits = DEFAULT_RSA_KEY_SIZE; } else { rsaParams.keySizeInBits = keysize; } rsaParams.pe = 0x10001; if (PK11_Authenticate(slot, PR_FALSE /*loadCerts*/, &pwdata) != SECSuccess) { SECU_PrintError(progName, "failure authenticating to key database.\n"); exit(ERRX); } *privk = PK11_GenerateKeyPair(slot, CKM_RSA_PKCS_KEY_PAIR_GEN, &rsaParams, pubk, PR_TRUE /*isPerm*/, PR_TRUE /*isSensitive*/, &pwdata); if (*privk != NULL && *pubk != NULL) { if (verbosity >= 0) { PR_fprintf(outputFD, "generated public/private key pair\n"); } } else { SECU_PrintError(progName, "failure generating key pair\n"); exit(ERRX); } return SECSuccess; } /****************************************************************** * * m a k e _ c e r t _ r e q u e s t */ static CERTCertificateRequest * make_cert_request(char *subject, SECKEYPublicKey *pubk) { CERTName *subj; CERTSubjectPublicKeyInfo *spki; CERTCertificateRequest *req; /* Create info about public key */ spki = SECKEY_CreateSubjectPublicKeyInfo(pubk); if (!spki) { SECU_PrintError(progName, "unable to create subject public key"); exit(ERRX); } subj = CERT_AsciiToName(subject); if (subj == NULL) { FatalError("Invalid data in certificate description"); } /* Generate certificate request */ req = CERT_CreateCertificateRequest(subj, spki, 0); if (!req) { SECU_PrintError(progName, "unable to make certificate request"); exit(ERRX); } SECKEY_DestroySubjectPublicKeyInfo(spki); CERT_DestroyName(subj); if (verbosity >= 0) { PR_fprintf(outputFD, "certificate request generated\n"); } return req; } /****************************************************************** * * m a k e _ c e r t */ static CERTCertificate * make_cert(CERTCertificateRequest *req, unsigned long serial, CERTName *ca_subject) { CERTCertificate *cert; CERTValidity *validity = NULL; PRTime now, after; PRExplodedTime printableTime; now = PR_Now(); PR_ExplodeTime(now, PR_GMTParameters, &printableTime); printableTime.tm_month += 3; after = PR_ImplodeTime(&printableTime); validity = CERT_CreateValidity(now, after); if (validity == NULL) { PR_fprintf(errorFD, "%s: error creating certificate validity\n", PROGRAM_NAME); errorCount++; exit(ERRX); } cert = CERT_CreateCertificate(serial, ca_subject, validity, req); CERT_DestroyValidity(validity); if (cert == NULL) { /* should probably be more precise here */ PR_fprintf(errorFD, "%s: error while generating certificate\n", PROGRAM_NAME); errorCount++; exit(ERRX); } return cert; } /************************************************************************* * * o u t p u t _ c a _ c e r t */ static void output_ca_cert(CERTCertificate *cert, CERTCertDBHandle *db) { FILE *out; SECItem *encodedCertChain; SEC_PKCS7ContentInfo *certChain; char *filename, *certData; /* the raw */ filename = PORT_ZAlloc(strlen(DEFAULT_X509_BASENAME) + 8); if (!filename) out_of_memory(); snprintf(filename, strlen(DEFAULT_X509_BASENAME) + 8, "%s.raw", DEFAULT_X509_BASENAME); if ((out = fopen(filename, "wb")) == NULL) { PR_fprintf(errorFD, "%s: Can't open %s output file\n", PROGRAM_NAME, filename); errorCount++; exit(ERRX); } certChain = SEC_PKCS7CreateCertsOnly(cert, PR_TRUE, db); encodedCertChain = SEC_PKCS7EncodeItem(NULL, NULL, certChain, NULL, NULL, NULL); SEC_PKCS7DestroyContentInfo(certChain); if (encodedCertChain) { fprintf(out, "Content-type: application/x-x509-ca-cert\n\n"); fwrite(encodedCertChain->data, 1, encodedCertChain->len, out); SECITEM_FreeItem(encodedCertChain, PR_TRUE); } else { PR_fprintf(errorFD, "%s: Can't DER encode this certificate\n", PROGRAM_NAME); errorCount++; exit(ERRX); } fclose(out); /* and the cooked */ snprintf(filename, strlen(DEFAULT_X509_BASENAME) + 8, "%s.cacert", DEFAULT_X509_BASENAME); if ((out = fopen(filename, "wb")) == NULL) { PR_fprintf(errorFD, "%s: Can't open %s output file\n", PROGRAM_NAME, filename); errorCount++; return; } certData = BTOA_DataToAscii(cert->derCert.data, cert->derCert.len); fprintf(out, "%s\n%s\n%s\n", NS_CERT_HEADER, certData, NS_CERT_TRAILER); PORT_Free(certData); PORT_Free(filename); fclose(out); if (verbosity >= 0) { PR_fprintf(outputFD, "Exported certificate to %s.raw and %s.cacert.\n", DEFAULT_X509_BASENAME, DEFAULT_X509_BASENAME); } }
/* Create a new table of names and push it on stack, * count the present nesting depth, and resize stack if it is full */ static void push_scope ( void ) { if ( scopes == NULL ) scopes = malloc ( n_scopes * sizeof(tlhash_t *) ); tlhash_t *new_scope = malloc ( sizeof(tlhash_t) ); tlhash_init ( new_scope, 32 ); scopes[scope_depth] = new_scope; scope_depth += 1; if ( scope_depth >= n_scopes ) { n_scopes *= 2; scopes = realloc ( scopes, n_scopes*sizeof(tlhash_t **) ); } }
/** Fill block of memory. * * Fill cnt words at dst address with the value val. The filling * is done word-by-word. * * @param dst Destination address to fill. * @param cnt Number of words to fill. * @param val Value to fill. * */ void memsetw(void *dst, size_t cnt, uint16_t val) { size_t i; uint16_t *ptr = (uint16_t *) dst; for (i = 0; i < cnt; i++) ptr[i] = val; }
/** * pci_lost_interrupt - reports a lost PCI interrupt * @pdev: device whose interrupt is lost * * The primary function of this routine is to report a lost interrupt * in a standard way which users can recognise (instead of blaming the * driver). * * Returns: * a suggestion for fixing it (although the driver is not required to * act on this). */ enum pci_lost_interrupt_reason pci_lost_interrupt(struct pci_dev *pdev) { if (pdev->msi_enabled || pdev->msix_enabled) { enum pci_lost_interrupt_reason ret; if (pdev->msix_enabled) { pci_note_irq_problem(pdev, "MSIX routing failure"); ret = PCI_LOST_IRQ_DISABLE_MSIX; } else { pci_note_irq_problem(pdev, "MSI routing failure"); ret = PCI_LOST_IRQ_DISABLE_MSI; } return ret; } #ifdef CONFIG_ACPI if (!(acpi_disabled || acpi_noirq)) { pci_note_irq_problem(pdev, "Potential ACPI misrouting please reboot with acpi=noirq"); return PCI_LOST_IRQ_DISABLE_ACPI; } #endif pci_note_irq_problem(pdev, "unknown cause (not MSI or ACPI)"); return PCI_LOST_IRQ_NO_INFORMATION; }
#include <stdio.h> int main(void) { int j,i,min=0,N,M,C[12],A[12][12],X,d[12]={0,0,0,0,0,0,0,0,0,0,0,0},z=1,s[12],total=0; scanf("%d",&N); scanf("%d",&M); scanf("%d",&X); for(i=0;i<N;i++){ scanf("%d",&C[i]); for(j=0;j<M;j++){ scanf("%d",&A[i][j]); d[j]+=A[i][j]; } min+=C[i]; z*=2; } for(j=0;j<M;j++){ if(d[j]<X){ printf("-1"); return 0; } } for(s[0]=0;s[0]<2;s[0]++){ for(s[1]=0;s[1]<2;s[1]++){ for(s[2]=0;s[2]<2;s[2]++){ for(s[3]=0;s[3]<2;s[3]++){ for(s[4]=0;s[4]<2;s[4]++){ for(s[5]=0;s[5]<2;s[5]++){ for(s[6]=0;s[6]<2;s[6]++){ for(s[7]=0;s[7]<2;s[7]++){ for(s[8]=0;s[8]<2;s[8]++){ for(s[9]=0;s[9]<2;s[9]++){ for(s[10]=0;s[10]<2;s[10]++){ for(s[11]=0;s[11]<2;s[11]++){ for(j=0;j<M;j++){ d[j]=0; for(i=0;i<N;i++){ d[j]+=s[i]*A[i][j]; } } for(j=0;j<M;j++){ if(d[j]<X){ break; } } if(j==M){ total=0; for(i=0;i<N;i++){ total+=s[i]*C[i]; } if(total<min)min=total; } } } } } } } } } } } } } printf("%d",min); return 0; }
/* Handle the INIT_CUMULATIVE_ARGS macro. Initialize a variable CUM of type CUMULATIVE_ARGS for a call to a function whose data type is FNTYPE. For a library call, FNTYPE is 0. */ void init_cumulative_args (struct sparc_args *cum, tree fntype, rtx, tree) { cum->words = 0; cum->prototype_p = fntype && prototype_p (fntype); cum->libcall_p = !fntype; }
/* * Checks whether the number of elements received actually matches the * amount expected. */ static inline void mpi_recv_check(const MPI_Status *const status, MPI_Datatype datatype, const int count) { int received = 0; if (NULL == status || 0 > count) { MPI_Abort(MPI_COMM_WORLD, EXIT_FAILURE); } MPI_Get_count(status, datatype, &received); if (received != count) { MPI_Abort(MPI_COMM_WORLD, EXIT_FAILURE); } }
/* * Copyright (C) 2012,2013 - ARM Ltd * Author: Marc Zyngier <marc.zyngier@arm.com> * * 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. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef __ARM64_KVM_MMU_H__ #define __ARM64_KVM_MMU_H__ #include <asm/page.h> #include <asm/memory.h> #include <asm/cpufeature.h> /* * As ARMv8.0 only has the TTBR0_EL2 register, we cannot express * "negative" addresses. This makes it impossible to directly share * mappings with the kernel. * * Instead, give the HYP mode its own VA region at a fixed offset from * the kernel by just masking the top bits (which are all ones for a * kernel address). We need to find out how many bits to mask. * * We want to build a set of page tables that cover both parts of the * idmap (the trampoline page used to initialize EL2), and our normal * runtime VA space, at the same time. * * Given that the kernel uses VA_BITS for its entire address space, * and that half of that space (VA_BITS - 1) is used for the linear * mapping, we can also limit the EL2 space to (VA_BITS - 1). * * The main question is "Within the VA_BITS space, does EL2 use the * top or the bottom half of that space to shadow the kernel's linear * mapping?". As we need to idmap the trampoline page, this is * determined by the range in which this page lives. * * If the page is in the bottom half, we have to use the top half. If * the page is in the top half, we have to use the bottom half: * * T = __pa_symbol(__hyp_idmap_text_start) * if (T & BIT(VA_BITS - 1)) * HYP_VA_MIN = 0 //idmap in upper half * else * HYP_VA_MIN = 1 << (VA_BITS - 1) * HYP_VA_MAX = HYP_VA_MIN + (1 << (VA_BITS - 1)) - 1 * * This of course assumes that the trampoline page exists within the * VA_BITS range. If it doesn't, then it means we're in the odd case * where the kernel idmap (as well as HYP) uses more levels than the * kernel runtime page tables (as seen when the kernel is configured * for 4k pages, 39bits VA, and yet memory lives just above that * limit, forcing the idmap to use 4 levels of page tables while the * kernel itself only uses 3). In this particular case, it doesn't * matter which side of VA_BITS we use, as we're guaranteed not to * conflict with anything. * * When using VHE, there are no separate hyp mappings and all KVM * functionality is already mapped as part of the main kernel * mappings, and none of this applies in that case. */ #define HYP_PAGE_OFFSET_HIGH_MASK ((UL(1) << VA_BITS) - 1) #define HYP_PAGE_OFFSET_LOW_MASK ((UL(1) << (VA_BITS - 1)) - 1) #ifdef __ASSEMBLY__ #include <asm/alternative.h> #include <asm/cpufeature.h> /* * Convert a kernel VA into a HYP VA. * reg: VA to be converted. * * This generates the following sequences: * - High mask: * and x0, x0, #HYP_PAGE_OFFSET_HIGH_MASK * nop * - Low mask: * and x0, x0, #HYP_PAGE_OFFSET_HIGH_MASK * and x0, x0, #HYP_PAGE_OFFSET_LOW_MASK * - VHE: * nop * nop * * The "low mask" version works because the mask is a strict subset of * the "high mask", hence performing the first mask for nothing. * Should be completely invisible on any viable CPU. */ .macro kern_hyp_va reg alternative_if_not ARM64_HAS_VIRT_HOST_EXTN and \reg, \reg, #HYP_PAGE_OFFSET_HIGH_MASK alternative_else_nop_endif alternative_if ARM64_HYP_OFFSET_LOW and \reg, \reg, #HYP_PAGE_OFFSET_LOW_MASK alternative_else_nop_endif .endm #else #include <asm/pgalloc.h> #include <asm/cache.h> #include <asm/cacheflush.h> #include <asm/mmu_context.h> #include <asm/pgtable.h> static inline unsigned long __kern_hyp_va(unsigned long v) { asm volatile(ALTERNATIVE("and %0, %0, %1", "nop", ARM64_HAS_VIRT_HOST_EXTN) : "+r" (v) : "i" (HYP_PAGE_OFFSET_HIGH_MASK)); asm volatile(ALTERNATIVE("nop", "and %0, %0, %1", ARM64_HYP_OFFSET_LOW) : "+r" (v) : "i" (HYP_PAGE_OFFSET_LOW_MASK)); return v; } #define kern_hyp_va(v) ((typeof(v))(__kern_hyp_va((unsigned long)(v)))) /* * We currently only support a 40bit IPA. */ #define KVM_PHYS_SHIFT (40) #define KVM_PHYS_SIZE (1UL << KVM_PHYS_SHIFT) #define KVM_PHYS_MASK (KVM_PHYS_SIZE - 1UL) #include <asm/stage2_pgtable.h> int create_hyp_mappings(void *from, void *to, pgprot_t prot); int create_hyp_io_mappings(void *from, void *to, phys_addr_t); void free_hyp_pgds(void); void stage2_unmap_vm(struct kvm *kvm); int kvm_alloc_stage2_pgd(struct kvm *kvm); void kvm_free_stage2_pgd(struct kvm *kvm); int kvm_phys_addr_ioremap(struct kvm *kvm, phys_addr_t guest_ipa, phys_addr_t pa, unsigned long size, bool writable); int kvm_handle_guest_abort(struct kvm_vcpu *vcpu, struct kvm_run *run); void kvm_mmu_free_memory_caches(struct kvm_vcpu *vcpu); phys_addr_t kvm_mmu_get_httbr(void); phys_addr_t kvm_get_idmap_vector(void); int kvm_mmu_init(void); void kvm_clear_hyp_idmap(void); #define kvm_set_pte(ptep, pte) set_pte(ptep, pte) #define kvm_set_pmd(pmdp, pmd) set_pmd(pmdp, pmd) static inline pte_t kvm_s2pte_mkwrite(pte_t pte) { pte_val(pte) |= PTE_S2_RDWR; return pte; } static inline pmd_t kvm_s2pmd_mkwrite(pmd_t pmd) { pmd_val(pmd) |= PMD_S2_RDWR; return pmd; } static inline void kvm_set_s2pte_readonly(pte_t *pte) { pteval_t pteval; unsigned long tmp; asm volatile("// kvm_set_s2pte_readonly\n" " prfm pstl1strm, %2\n" "1: ldxr %0, %2\n" " and %0, %0, %3 // clear PTE_S2_RDWR\n" " orr %0, %0, %4 // set PTE_S2_RDONLY\n" " stxr %w1, %0, %2\n" " cbnz %w1, 1b\n" : "=&r" (pteval), "=&r" (tmp), "+Q" (pte_val(*pte)) : "L" (~PTE_S2_RDWR), "L" (PTE_S2_RDONLY)); } static inline bool kvm_s2pte_readonly(pte_t *pte) { return (pte_val(*pte) & PTE_S2_RDWR) == PTE_S2_RDONLY; } static inline void kvm_set_s2pmd_readonly(pmd_t *pmd) { kvm_set_s2pte_readonly((pte_t *)pmd); } static inline bool kvm_s2pmd_readonly(pmd_t *pmd) { return kvm_s2pte_readonly((pte_t *)pmd); } static inline bool kvm_page_empty(void *ptr) { struct page *ptr_page = virt_to_page(ptr); return page_count(ptr_page) == 1; } #define hyp_pte_table_empty(ptep) kvm_page_empty(ptep) #ifdef __PAGETABLE_PMD_FOLDED #define hyp_pmd_table_empty(pmdp) (0) #else #define hyp_pmd_table_empty(pmdp) kvm_page_empty(pmdp) #endif #ifdef __PAGETABLE_PUD_FOLDED #define hyp_pud_table_empty(pudp) (0) #else #define hyp_pud_table_empty(pudp) kvm_page_empty(pudp) #endif struct kvm; #define kvm_flush_dcache_to_poc(a,l) __flush_dcache_area((a), (l)) static inline bool vcpu_has_cache_enabled(struct kvm_vcpu *vcpu) { return (vcpu_sys_reg(vcpu, SCTLR_EL1) & 0b101) == 0b101; } static inline void __coherent_cache_guest_page(struct kvm_vcpu *vcpu, kvm_pfn_t pfn, unsigned long size) { void *va = page_address(pfn_to_page(pfn)); kvm_flush_dcache_to_poc(va, size); if (icache_is_aliasing()) { /* any kind of VIPT cache */ __flush_icache_all(); } else if (is_kernel_in_hyp_mode() || !icache_is_vpipt()) { /* PIPT or VPIPT at EL2 (see comment in __kvm_tlb_flush_vmid_ipa) */ flush_icache_range((unsigned long)va, (unsigned long)va + size); } } static inline void __kvm_flush_dcache_pte(pte_t pte) { struct page *page = pte_page(pte); kvm_flush_dcache_to_poc(page_address(page), PAGE_SIZE); } static inline void __kvm_flush_dcache_pmd(pmd_t pmd) { struct page *page = pmd_page(pmd); kvm_flush_dcache_to_poc(page_address(page), PMD_SIZE); } static inline void __kvm_flush_dcache_pud(pud_t pud) { struct page *page = pud_page(pud); kvm_flush_dcache_to_poc(page_address(page), PUD_SIZE); } #define kvm_virt_to_phys(x) __pa_symbol(x) void kvm_set_way_flush(struct kvm_vcpu *vcpu); void kvm_toggle_cache(struct kvm_vcpu *vcpu, bool was_enabled); static inline bool __kvm_cpu_uses_extended_idmap(void) { return __cpu_uses_extended_idmap(); } static inline void __kvm_extend_hypmap(pgd_t *boot_hyp_pgd, pgd_t *hyp_pgd, pgd_t *merged_hyp_pgd, unsigned long hyp_idmap_start) { int idmap_idx; /* * Use the first entry to access the HYP mappings. It is * guaranteed to be free, otherwise we wouldn't use an * extended idmap. */ VM_BUG_ON(pgd_val(merged_hyp_pgd[0])); merged_hyp_pgd[0] = __pgd(__pa(hyp_pgd) | PMD_TYPE_TABLE); /* * Create another extended level entry that points to the boot HYP map, * which contains an ID mapping of the HYP init code. We essentially * merge the boot and runtime HYP maps by doing so, but they don't * overlap anyway, so this is fine. */ idmap_idx = hyp_idmap_start >> VA_BITS; VM_BUG_ON(pgd_val(merged_hyp_pgd[idmap_idx])); merged_hyp_pgd[idmap_idx] = __pgd(__pa(boot_hyp_pgd) | PMD_TYPE_TABLE); } static inline unsigned int kvm_get_vmid_bits(void) { int reg = read_sanitised_ftr_reg(SYS_ID_AA64MMFR1_EL1); return (cpuid_feature_extract_unsigned_field(reg, ID_AA64MMFR1_VMIDBITS_SHIFT) == 2) ? 16 : 8; } #endif /* __ASSEMBLY__ */ #endif /* __ARM64_KVM_MMU_H__ */
// global variable for normalized pulse width to send // background thread to send pulses at 60hz to servo static void* __send_servo_pulses(__attribute__ ((unused)) void *params) { while(P_RUNNING){ rc_servo_send_pulse_normalized(1, ESC_TURN); rc_servo_send_pulse_normalized(2, SERVO_TURN); rc_usleep(16666); } return 0; }
/* Helper which announces our readiness to supply clipboard data in a single format (such as CF_TEXT) to the RDP side. To announce more than one format at a time, use cliprdr_send_native_format_announce. */ void cliprdr_send_simple_native_format_announce(uint32 format) { uint8 buffer[36]; DEBUG_CLIPBOARD(("cliprdr_send_simple_native_format_announce\n")); buf_out_uint32(buffer, format); memset(buffer + 4, 0, sizeof(buffer) - 4); cliprdr_send_native_format_announce(buffer, sizeof(buffer)); }
/** Return true if agg1 and agg2 are pointers to the same memory block */ bool pointToSameMemoryBlock(Expression *agg1, Expression *agg2) { if (agg1 == agg2) return true; if (agg1->op == TOKint64 && agg2->op == TOKint64 && agg1->toInteger() == agg2->toInteger()) { return true; } if (agg1->op == TOKvar && agg2->op == TOKvar && ((VarExp *)agg1)->var == ((VarExp *)agg2)->var) { return true; } if (agg1->op == TOKsymoff && agg2->op == TOKsymoff && ((SymOffExp *)agg1)->var == ((SymOffExp *)agg2)->var) { return true; } return false; }
/* Checks if flag passed to the CLI is a valid flag or not. @param flag: command line flag to be checked @return : true if [flag] is a valid command line flag for this program */ bool is_valid_flag(const char* flag) { bool check = false; for (size_t i = 0; i < 8; i++) { if (strcmp(flag, VALID_FLAGS[i]) == 0) { check = true; } } return check; }
/* * ant_get_int -- * * Nothing subtle here. Consumes an entire line of input, * but that line better not be too long or the function will * reject it! */ int ant_get_int (int *status, int base) { unsigned int i; long int val; char buf [MAX_LINE_LEN]; char *end_ptr; int dummy; if (status == NULL) { status = &dummy; } if (NULL == fgets (buf, MAX_LINE_LEN, stdin)) { *status = 1; return (0); } if ((strlen (buf) == 0) || (buf [strlen (buf) - 1] != '\n')) { *status = 2; return (0); } val = strtol (buf, &end_ptr, base); for (i = 0; i < strlen (end_ptr); i++) { if (!isspace ((unsigned) end_ptr [i])) { *status = 3; return (0); } } *status = 0; return (val); }
#include <stdio.h> #include <string.h> #include <stdlib.h> #include <stdint.h> // uint64_t #define max(a,b) ((a) > (b) ? (a) : (b)) #define min(a,b) ((a) > (b) ? (b) : (a)) int get_int(void) { int num; scanf("%d", &num); return num; } static int map[10]; static int valid[3] = {3, 5, 7}; int traverse(int64_t cur, int64_t limit) { if(cur > limit) return 0; int ans = 0; int i; int flag = 1; for(i = 0; i < 3; i++) { int d = valid[i]; if(!map[d]) flag = 0; map[d]++; ans += traverse(cur*10 + d, limit); map[d]--; } return ans + flag; } int main(void) { int num = get_int(); int ans = traverse(0, num); printf("%d\n", ans); return 0; }
#include<stdio.h> #include<string.h> int main() { int i,j,k,l,m,n,s,t1,t2; while(scanf("%d",&l)!=EOF){ for(i=1;i<=l;i++){ char a[300000]; scanf("%s",&a); m=strlen(a);t1=0;t2=0;s=0; for(j=0;j<m;j++){ if(a[j]=='('){ t1=t1+1; } if(a[j]==')'){ if(t1>0){ s=s+1; t1=t1-1; } } if(a[j]=='['){ t2=t2+1; } if(a[j]==']'){ if(t2>0){ s=s+1; t2=t2-1; } } }printf("%d\n",s);s=0; } } return 0; }
//---------------------------------------------------------------------------- // // Function: GetSelectedItemFromListView // // Purpose: searches through the List View specified by controlID // returns the found item in the lvI parameter // // Arguments: // // Returns: function returns TRUE if there was an item selected and it // found it, // FALSE if there was no item selected // //---------------------------------------------------------------------------- BOOL GetSelectedItemFromListView( HWND hwndDlg, WORD controlID, LVITEM* lvI ) { INT i; INT iCount; HWND hListView = GetDlgItem( hwndDlg, controlID ); UINT uMask = LVIS_SELECTED | LVIS_FOCUSED; UINT uState; BOOL bSelectedItemFound = FALSE; iCount = ListView_GetItemCount( hListView ); i = 0; while( !bSelectedItemFound && i < iCount ) { uState = ListView_GetItemState( hListView, i, uMask ); if( uState == uMask ) { bSelectedItemFound = TRUE; memset( lvI, 0, sizeof( LVITEM ) ); lvI->iItem = i; lvI->mask = LVIF_PARAM; ListView_GetItem( hListView, lvI ); return( TRUE ); } i++; } return( FALSE ); }
// Function to calculate pairwise differences between chromosomes int pairDiffs(int n, int s, int *config, char **dna, int *d) { int i, j, k; int idx; int e1, e2; if (config) { memset(d, 0, (size_t)(config[0] * config[1]) * sizeof(int)); e1 = config[0]; } else { memset(d, 0, (size_t)BINOM(n) * sizeof(int)); e1 = n - 1; } for (i = 0, idx = 0; i < e1; ++i) { if (config) e2 = config[0]; else e2 = i + 1; for (j = e2; j < n; ++j) { for (k = 0; k < s; ++k) if ( dna[i][k] != dna[j][k] ) ++d[idx]; ++idx; } } return 0; }
//***************************************************************************** // //! Configures a non-blocking read transaction. //! //! \param ui32Base is the EPI module base address. //! \param ui32Channel is the read channel (0 or 1). //! \param ui32DataSize is the size of the data items to read. //! \param ui32Address is the starting address to read. //! //! This function is used to configure a non-blocking read channel for a //! transaction. Two channels are available that can be used in a ping-pong //! method for continuous reading. It is not necessary to use both channels //! to perform a non-blocking read. //! //! The parameter \e ui8DataSize is one of \b EPI_NBCONFIG_SIZE_8, //! \b EPI_NBCONFIG_SIZE_16, or \b EPI_NBCONFIG_SIZE_32 for 8-bit, 16-bit, //! or 32-bit sized data transfers. //! //! The parameter \e ui32Address is the starting address for the read, relative //! to the external device. The start of the device is address 0. //! //! Once configured, the non-blocking read is started by calling //! EPINonBlockingReadStart(). If the addresses to be read from the device //! are in a sequence, it is not necessary to call this function multiple //! times. Until it is changed, the EPI module stores the last address //! that was used for a non-blocking read (per channel). //! //! \return None. // //***************************************************************************** void EPINonBlockingReadConfigure(uint32_t ui32Base, uint32_t ui32Channel, uint32_t ui32DataSize, uint32_t ui32Address) { uint32_t ui32Offset; Check the arguments. ASSERT(ui32Base == EPI0_BASE); ASSERT(ui32Channel < 2); ASSERT(ui32DataSize < 4); ASSERT(ui32Address < 0x20000000); Compute the offset needed to select the correct channel regs. ui32Offset = ui32Channel * (EPI_O_RSIZE1 - EPI_O_RSIZE0); Write the data size register for the channel. HWREG(ui32Base + EPI_O_RSIZE0 + ui32Offset) = ui32DataSize; Write the starting address register for the channel. HWREG(ui32Base + EPI_O_RADDR0 + ui32Offset) = ui32Address; }
/* * Fetch a value from the database. The datum returned needs its val.data * free()ing after use. If val.data is NULL, no value was found for the * given key. */ qdb_datum qdb_fetch(qdb_t db, qdb_datum key) { qdb_datum keycopy; if (db == NULL) { qdb_datum val; val.data = NULL; val.size = 0; return val; } if (key.data == NULL) { qdb_datum val; val.data = NULL; val.size = 0; return val; } keycopy = key; qdb__lastbackend = db->typeindex; return db->type->_fetch(db->data, keycopy); }
#include<stdio.h> int main(){ int vp,vd,t,f,c; int i; scanf("%d\n%d\n%d\n%d\n%d",&vp,&vd,&t,&f,&c); if(vp>=vd){printf("0"); return 0;} double a = c/(vp+0.0); double dist=vp*t; double curr = t; int ruby=0; for(i=0;;i++){ curr = curr+(dist/(vd-vp+0.0)); if(curr>=a){break;} ruby++; curr = curr+(dist/(vd-vp+0.0))+f; dist = curr*vp; } printf("%d\n",ruby); return 0; }