hexsha stringlengths 40 40 | size int64 5 1.05M | ext stringclasses 588
values | lang stringclasses 305
values | max_stars_repo_path stringlengths 3 363 | max_stars_repo_name stringlengths 5 118 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 10 | max_stars_count float64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringdate 2015-01-01 00:00:35 2022-03-31 23:43:49 ⌀ | max_stars_repo_stars_event_max_datetime stringdate 2015-01-01 12:37:38 2022-03-31 23:59:52 ⌀ | max_issues_repo_path stringlengths 3 363 | max_issues_repo_name stringlengths 5 118 | max_issues_repo_head_hexsha stringlengths 40 40 | max_issues_repo_licenses listlengths 1 10 | max_issues_count float64 1 134k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 3 363 | max_forks_repo_name stringlengths 5 135 | max_forks_repo_head_hexsha stringlengths 40 40 | max_forks_repo_licenses listlengths 1 10 | max_forks_count float64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringdate 2015-01-01 00:01:02 2022-03-31 23:27:27 ⌀ | max_forks_repo_forks_event_max_datetime stringdate 2015-01-03 08:55:07 2022-03-31 23:59:24 ⌀ | content stringlengths 5 1.05M | avg_line_length float64 1.13 1.04M | max_line_length int64 1 1.05M | alphanum_fraction float64 0 1 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
30a4f10f0e8e0d345bd48c8866022b41c923ce6b | 42,534 | c | C | sys/vfs/hammer2/hammer2_xops.c | raJeev-M/DragonFlyBSD | 2f9f168a13010344973c10c56a71514a10643642 | [
"BSD-3-Clause"
] | 1 | 2019-12-22T07:21:10.000Z | 2019-12-22T07:21:10.000Z | sys/vfs/hammer2/hammer2_xops.c | raJeev-M/DragonFlyBSD | 2f9f168a13010344973c10c56a71514a10643642 | [
"BSD-3-Clause"
] | null | null | null | sys/vfs/hammer2/hammer2_xops.c | raJeev-M/DragonFlyBSD | 2f9f168a13010344973c10c56a71514a10643642 | [
"BSD-3-Clause"
] | null | null | null | /*
* Copyright (c) 2011-2018 The DragonFly Project. All rights reserved.
*
* This code is derived from software contributed to The DragonFly Project
* by Matthew Dillon <dillon@dragonflybsd.org>
* by Venkatesh Srinivas <vsrinivas@dragonflybsd.org>
* by Daniel Flores (GSOC 2013 - mentored by Matthew Dillon, compression)
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* 3. Neither the name of The DragonFly Project 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 HOLDERS 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.
*/
/*
* Per-node backend for kernel filesystem interface.
*
* This executes a VOP concurrently on multiple nodes, each node via its own
* thread, and competes to advance the original request. The original
* request is retired the moment all requirements are met, even if the
* operation is still in-progress on some nodes.
*/
#include <sys/param.h>
#include <sys/systm.h>
#include <sys/kernel.h>
#include <sys/fcntl.h>
#include <sys/buf.h>
#include <sys/proc.h>
#include <sys/namei.h>
#include <sys/mount.h>
#include <sys/vnode.h>
#include <sys/mountctl.h>
#include <sys/dirent.h>
#include <sys/uio.h>
#include <sys/objcache.h>
#include <sys/event.h>
#include <sys/file.h>
#include <vfs/fifofs/fifo.h>
#include "hammer2.h"
/*
* Determine if the specified directory is empty.
*
* Returns 0 on success.
*
* Returns HAMMER_ERROR_EAGAIN if caller must re-lookup the entry and
* retry. (occurs if we race a ripup on oparent or ochain).
*
* Or returns a permanent HAMMER2_ERROR_* error mask.
*
* The caller must pass in an exclusively locked oparent and ochain. This
* function will handle the case where the chain is a directory entry or
* the inode itself. The original oparent,ochain will be locked upon return.
*
* This function will unlock the underlying oparent,ochain temporarily when
* doing an inode lookup to avoid deadlocks. The caller MUST handle the EAGAIN
* result as this means that oparent is no longer the parent of ochain, or
* that ochain was destroyed while it was unlocked.
*/
static
int
checkdirempty(hammer2_chain_t *oparent, hammer2_chain_t *ochain, int clindex)
{
hammer2_chain_t *parent;
hammer2_chain_t *chain;
hammer2_key_t key_next;
hammer2_key_t inum;
int error;
int didunlock;
error = 0;
didunlock = 0;
/*
* Find the inode, set it up as a locked 'chain'. ochain can be the
* inode itself, or it can be a directory entry.
*/
if (ochain->bref.type == HAMMER2_BREF_TYPE_DIRENT) {
inum = ochain->bref.embed.dirent.inum;
hammer2_chain_unlock(ochain);
hammer2_chain_unlock(oparent);
parent = NULL;
chain = NULL;
error = hammer2_chain_inode_find(ochain->pmp, inum,
clindex, 0,
&parent, &chain);
if (parent) {
hammer2_chain_unlock(parent);
hammer2_chain_drop(parent);
}
didunlock = 1;
} else {
/*
* The directory entry *is* the directory inode
*/
chain = hammer2_chain_lookup_init(ochain, 0);
}
/*
* Determine if the directory is empty or not by checking its
* visible namespace (the area which contains directory entries).
*/
if (error == 0) {
parent = chain;
chain = NULL;
if (parent) {
chain = hammer2_chain_lookup(&parent, &key_next,
HAMMER2_DIRHASH_VISIBLE,
HAMMER2_KEY_MAX,
&error, 0);
}
if (chain) {
error = HAMMER2_ERROR_ENOTEMPTY;
hammer2_chain_unlock(chain);
hammer2_chain_drop(chain);
}
hammer2_chain_lookup_done(parent);
}
if (didunlock) {
hammer2_chain_lock(oparent, HAMMER2_RESOLVE_ALWAYS);
hammer2_chain_lock(ochain, HAMMER2_RESOLVE_ALWAYS);
if ((ochain->flags & HAMMER2_CHAIN_DELETED) ||
(oparent->flags & HAMMER2_CHAIN_DELETED) ||
ochain->parent != oparent) {
kprintf("hammer2: debug: CHECKDIR inum %jd RETRY\n",
inum);
error = HAMMER2_ERROR_EAGAIN;
}
}
return error;
}
/*
* Backend for hammer2_vfs_root()
*
* This is called when a newly mounted PFS has not yet synchronized
* to the inode_tid and modify_tid.
*/
void
hammer2_xop_ipcluster(hammer2_xop_t *arg, void *scratch, int clindex)
{
hammer2_xop_ipcluster_t *xop = &arg->xop_ipcluster;
hammer2_chain_t *chain;
int error;
chain = hammer2_inode_chain(xop->head.ip1, clindex,
HAMMER2_RESOLVE_ALWAYS |
HAMMER2_RESOLVE_SHARED);
if (chain)
error = chain->error;
else
error = HAMMER2_ERROR_EIO;
hammer2_xop_feed(&xop->head, chain, clindex, error);
if (chain) {
hammer2_chain_unlock(chain);
hammer2_chain_drop(chain);
}
}
/*
* Backend for hammer2_vop_readdir()
*/
void
hammer2_xop_readdir(hammer2_xop_t *arg, void *scratch, int clindex)
{
hammer2_xop_readdir_t *xop = &arg->xop_readdir;
hammer2_chain_t *parent;
hammer2_chain_t *chain;
hammer2_key_t key_next;
hammer2_key_t lkey;
int error = 0;
lkey = xop->lkey;
if (hammer2_debug & 0x0020)
kprintf("xop_readdir %p lkey=%016jx\n", xop, lkey);
/*
* The inode's chain is the iterator. If we cannot acquire it our
* contribution ends here.
*/
parent = hammer2_inode_chain(xop->head.ip1, clindex,
HAMMER2_RESOLVE_ALWAYS |
HAMMER2_RESOLVE_SHARED);
if (parent == NULL) {
kprintf("xop_readdir: NULL parent\n");
goto done;
}
/*
* Directory scan [re]start and loop, the feed inherits the chain's
* lock so do not unlock it on the iteration.
*/
chain = hammer2_chain_lookup(&parent, &key_next, lkey, lkey,
&error, HAMMER2_LOOKUP_SHARED);
if (chain == NULL) {
chain = hammer2_chain_lookup(&parent, &key_next,
lkey, HAMMER2_KEY_MAX,
&error, HAMMER2_LOOKUP_SHARED);
}
while (chain) {
error = hammer2_xop_feed(&xop->head, chain, clindex, 0);
if (error)
goto break2;
chain = hammer2_chain_next(&parent, chain, &key_next,
key_next, HAMMER2_KEY_MAX,
&error, HAMMER2_LOOKUP_SHARED);
}
break2:
if (chain) {
hammer2_chain_unlock(chain);
hammer2_chain_drop(chain);
}
hammer2_chain_unlock(parent);
hammer2_chain_drop(parent);
done:
hammer2_xop_feed(&xop->head, NULL, clindex, error);
}
/*
* Backend for hammer2_vop_nresolve()
*/
void
hammer2_xop_nresolve(hammer2_xop_t *arg, void *scratch, int clindex)
{
hammer2_xop_nresolve_t *xop = &arg->xop_nresolve;
hammer2_chain_t *parent;
hammer2_chain_t *chain;
const char *name;
size_t name_len;
hammer2_key_t key_next;
hammer2_key_t lhc;
int error;
parent = hammer2_inode_chain(xop->head.ip1, clindex,
HAMMER2_RESOLVE_ALWAYS |
HAMMER2_RESOLVE_SHARED);
if (parent == NULL) {
kprintf("xop_nresolve: NULL parent\n");
chain = NULL;
error = HAMMER2_ERROR_EIO;
goto done;
}
name = xop->head.name1;
name_len = xop->head.name1_len;
/*
* Lookup the directory entry
*/
lhc = hammer2_dirhash(name, name_len);
chain = hammer2_chain_lookup(&parent, &key_next,
lhc, lhc + HAMMER2_DIRHASH_LOMASK,
&error,
HAMMER2_LOOKUP_ALWAYS |
HAMMER2_LOOKUP_SHARED);
while (chain) {
if (hammer2_chain_dirent_test(chain, name, name_len))
break;
chain = hammer2_chain_next(&parent, chain, &key_next,
key_next,
lhc + HAMMER2_DIRHASH_LOMASK,
&error,
HAMMER2_LOOKUP_ALWAYS |
HAMMER2_LOOKUP_SHARED);
}
/*
* Locate the target inode for a directory entry
*/
if (chain && chain->error == 0) {
if (chain->bref.type == HAMMER2_BREF_TYPE_DIRENT) {
lhc = chain->bref.embed.dirent.inum;
error = hammer2_chain_inode_find(chain->pmp,
lhc,
clindex,
HAMMER2_LOOKUP_SHARED,
&parent,
&chain);
}
} else if (chain && error == 0) {
error = chain->error;
}
done:
error = hammer2_xop_feed(&xop->head, chain, clindex, error);
if (chain) {
hammer2_chain_unlock(chain);
hammer2_chain_drop(chain);
}
if (parent) {
hammer2_chain_unlock(parent);
hammer2_chain_drop(parent);
}
}
/*
* Backend for hammer2_vop_nremove(), hammer2_vop_nrmdir(), and
* backend for pfs_delete.
*
* This function locates and removes a directory entry, and will lookup
* and return the underlying inode. For directory entries the underlying
* inode is not removed. If the directory entry is the actual inode itself,
* it may be conditonally removed and returned.
*
* WARNING! Any target inode's nlinks may not be synchronized to the
* in-memory inode. The frontend's hammer2_inode_unlink_finisher()
* is responsible for the final disposition of the actual inode.
*/
void
hammer2_xop_unlink(hammer2_xop_t *arg, void *scratch, int clindex)
{
hammer2_xop_unlink_t *xop = &arg->xop_unlink;
hammer2_chain_t *parent;
hammer2_chain_t *chain;
const char *name;
size_t name_len;
hammer2_key_t key_next;
hammer2_key_t lhc;
int error;
again:
/*
* Requires exclusive lock
*/
parent = hammer2_inode_chain(xop->head.ip1, clindex,
HAMMER2_RESOLVE_ALWAYS);
chain = NULL;
if (parent == NULL) {
kprintf("xop_nresolve: NULL parent\n");
error = HAMMER2_ERROR_EIO;
goto done;
}
name = xop->head.name1;
name_len = xop->head.name1_len;
/*
* Lookup the directory entry
*/
lhc = hammer2_dirhash(name, name_len);
chain = hammer2_chain_lookup(&parent, &key_next,
lhc, lhc + HAMMER2_DIRHASH_LOMASK,
&error, HAMMER2_LOOKUP_ALWAYS);
while (chain) {
if (hammer2_chain_dirent_test(chain, name, name_len))
break;
chain = hammer2_chain_next(&parent, chain, &key_next,
key_next,
lhc + HAMMER2_DIRHASH_LOMASK,
&error, HAMMER2_LOOKUP_ALWAYS);
}
/*
* The directory entry will either be a BREF_TYPE_DIRENT or a
* BREF_TYPE_INODE. We always permanently delete DIRENTs, but
* must go by xop->dopermanent for BREF_TYPE_INODE.
*
* Note that the target chain's nlinks may not be synchronized with
* the in-memory hammer2_inode_t structure, so we don't try to do
* anything fancy here. The frontend deals with nlinks
* synchronization.
*/
if (chain && chain->error == 0) {
int dopermanent = xop->dopermanent & H2DOPERM_PERMANENT;
int doforce = xop->dopermanent & H2DOPERM_FORCE;
uint8_t type;
/*
* If the directory entry is the actual inode then use its
* type for the directory typing tests, otherwise if it is
* a directory entry, pull the type field from the entry.
*
* Directory entries are always permanently deleted
* (because they aren't the actual inode).
*/
if (chain->bref.type == HAMMER2_BREF_TYPE_DIRENT) {
type = chain->bref.embed.dirent.type;
dopermanent |= HAMMER2_DELETE_PERMANENT;
} else {
type = chain->data->ipdata.meta.type;
}
/*
* Check directory typing and delete the entry. Note that
* nlinks adjustments are made on the real inode by the
* frontend, not here.
*
* Unfortunately, checkdirempty() may have to unlock (parent).
* If it no longer matches chain->parent after re-locking,
* EAGAIN is returned.
*/
if (type == HAMMER2_OBJTYPE_DIRECTORY && doforce) {
/*
* If doforce then execute the operation even if
* the directory is not empty or errored. We
* ignore chain->error here, allowing an errored
* chain (aka directory entry) to still be deleted.
*/
error = hammer2_chain_delete(parent, chain,
xop->head.mtid, dopermanent);
} else if (type == HAMMER2_OBJTYPE_DIRECTORY &&
xop->isdir == 0) {
error = HAMMER2_ERROR_EISDIR;
} else if (type == HAMMER2_OBJTYPE_DIRECTORY &&
(error = checkdirempty(parent, chain, clindex)) != 0) {
/*
* error may be EAGAIN or ENOTEMPTY
*/
if (error == HAMMER2_ERROR_EAGAIN) {
hammer2_chain_unlock(chain);
hammer2_chain_drop(chain);
hammer2_chain_unlock(parent);
hammer2_chain_drop(parent);
goto again;
}
} else if (type != HAMMER2_OBJTYPE_DIRECTORY &&
xop->isdir >= 1) {
error = HAMMER2_ERROR_ENOTDIR;
} else {
/*
* Delete the directory entry. chain might also
* be a directly-embedded inode.
*
* Allow the deletion to proceed even if the chain
* is errored. Give priority to error-on-delete over
* chain->error.
*/
error = hammer2_chain_delete(parent, chain,
xop->head.mtid,
dopermanent);
if (error == 0)
error = chain->error;
}
} else {
if (chain && error == 0)
error = chain->error;
}
/*
* If chain is a directory entry we must resolve it. We do not try
* to manipulate the contents as it might not be synchronized with
* the frontend hammer2_inode_t, nor do we try to lookup the
* frontend hammer2_inode_t here (we are the backend!).
*/
if (chain && chain->bref.type == HAMMER2_BREF_TYPE_DIRENT &&
(xop->dopermanent & H2DOPERM_IGNINO) == 0) {
int error2;
lhc = chain->bref.embed.dirent.inum;
error2 = hammer2_chain_inode_find(chain->pmp, lhc,
clindex, 0,
&parent, &chain);
if (error2) {
kprintf("inode_find: %016jx %p failed\n",
lhc, chain);
error2 = 0; /* silently ignore */
}
if (error == 0)
error = error2;
}
/*
* Return the inode target for further action. Typically used by
* hammer2_inode_unlink_finisher().
*/
done:
hammer2_xop_feed(&xop->head, chain, clindex, error);
if (chain) {
hammer2_chain_unlock(chain);
hammer2_chain_drop(chain);
chain = NULL;
}
if (parent) {
hammer2_chain_unlock(parent);
hammer2_chain_drop(parent);
parent = NULL;
}
}
/*
* Backend for hammer2_vop_nrename()
*
* This handles the backend rename operation. Typically this renames
* directory entries but can also be used to rename embedded inodes.
*
* NOTE! The frontend is responsible for updating the inode meta-data in
* the file being renamed and for decrementing the target-replaced
* inode's nlinks, if present.
*/
void
hammer2_xop_nrename(hammer2_xop_t *arg, void *scratch, int clindex)
{
hammer2_xop_nrename_t *xop = &arg->xop_nrename;
hammer2_pfs_t *pmp;
hammer2_chain_t *parent;
hammer2_chain_t *chain;
hammer2_chain_t *tmp;
hammer2_inode_t *ip;
hammer2_key_t key_next;
int error;
/*
* We need the precise parent chain to issue the deletion.
*
* If this is a directory entry we must locate the underlying
* inode. If it is an embedded inode we can act directly on it.
*/
ip = xop->head.ip2;
pmp = ip->pmp;
chain = NULL;
error = 0;
if (xop->ip_key & HAMMER2_DIRHASH_VISIBLE) {
/*
* Find ip's direct parent chain.
*/
chain = hammer2_inode_chain(ip, clindex,
HAMMER2_RESOLVE_ALWAYS);
if (chain == NULL) {
error = HAMMER2_ERROR_EIO;
parent = NULL;
goto done;
}
if (ip->flags & HAMMER2_INODE_CREATING) {
parent = NULL;
} else {
parent = hammer2_chain_getparent(chain,
HAMMER2_RESOLVE_ALWAYS);
if (parent == NULL) {
error = HAMMER2_ERROR_EIO;
goto done;
}
}
} else {
/*
* The directory entry for the head.ip1 inode
* is in fdip, do a namespace search.
*/
hammer2_key_t lhc;
const char *name;
size_t name_len;
parent = hammer2_inode_chain(xop->head.ip1, clindex,
HAMMER2_RESOLVE_ALWAYS);
if (parent == NULL) {
kprintf("xop_nrename: NULL parent\n");
error = HAMMER2_ERROR_EIO;
goto done;
}
name = xop->head.name1;
name_len = xop->head.name1_len;
/*
* Lookup the directory entry
*/
lhc = hammer2_dirhash(name, name_len);
chain = hammer2_chain_lookup(&parent, &key_next,
lhc, lhc + HAMMER2_DIRHASH_LOMASK,
&error, HAMMER2_LOOKUP_ALWAYS);
while (chain) {
if (hammer2_chain_dirent_test(chain, name, name_len))
break;
chain = hammer2_chain_next(&parent, chain, &key_next,
key_next,
lhc + HAMMER2_DIRHASH_LOMASK,
&error,
HAMMER2_LOOKUP_ALWAYS);
}
}
if (chain == NULL) {
/* XXX shouldn't happen, but does under fsstress */
kprintf("hammer2_xop_rename: \"%s\" -> \"%s\" ENOENT\n",
xop->head.name1,
xop->head.name2);
if (error == 0)
error = HAMMER2_ERROR_ENOENT;
goto done;
}
if (chain->error) {
error = chain->error;
goto done;
}
/*
* Delete it, then create it in the new namespace.
*
* An error can occur if the chain being deleted requires
* modification and the media is full.
*/
error = hammer2_chain_delete(parent, chain, xop->head.mtid, 0);
hammer2_chain_unlock(parent);
hammer2_chain_drop(parent);
parent = NULL; /* safety */
if (error)
goto done;
/*
* Adjust fields in the deleted chain appropriate for the rename
* operation.
*
* NOTE! For embedded inodes, the frontend will officially replicate
* the field adjustments, but we also do it here to maintain
* consistency in case of a crash.
*/
if (chain->bref.key != xop->lhc ||
xop->head.name1_len != xop->head.name2_len ||
bcmp(xop->head.name1, xop->head.name2, xop->head.name1_len) != 0) {
if (chain->bref.type == HAMMER2_BREF_TYPE_INODE) {
hammer2_inode_data_t *wipdata;
error = hammer2_chain_modify(chain, xop->head.mtid,
0, 0);
if (error == 0) {
wipdata = &chain->data->ipdata;
bzero(wipdata->filename,
sizeof(wipdata->filename));
bcopy(xop->head.name2,
wipdata->filename,
xop->head.name2_len);
wipdata->meta.name_key = xop->lhc;
wipdata->meta.name_len = xop->head.name2_len;
}
}
if (chain->bref.type == HAMMER2_BREF_TYPE_DIRENT) {
if (xop->head.name2_len <=
sizeof(chain->bref.check.buf)) {
/*
* Remove any related data buffer, we can
* embed the filename in the bref itself.
*/
error = hammer2_chain_resize(
chain, xop->head.mtid, 0, 0, 0);
if (error == 0) {
error = hammer2_chain_modify(
chain, xop->head.mtid,
0, 0);
}
if (error == 0) {
bzero(chain->bref.check.buf,
sizeof(chain->bref.check.buf));
bcopy(xop->head.name2,
chain->bref.check.buf,
xop->head.name2_len);
}
} else {
/*
* Associate a data buffer with the bref.
* Zero it for consistency. Note that the
* data buffer is not 64KB so use chain->bytes
* instead of sizeof().
*/
error = hammer2_chain_resize(
chain, xop->head.mtid, 0,
hammer2_getradix(HAMMER2_ALLOC_MIN), 0);
if (error == 0) {
error = hammer2_chain_modify(
chain, xop->head.mtid,
0, 0);
}
if (error == 0) {
bzero(chain->data->buf, chain->bytes);
bcopy(xop->head.name2,
chain->data->buf,
xop->head.name2_len);
}
}
if (error == 0) {
chain->bref.embed.dirent.namlen =
xop->head.name2_len;
}
}
}
/*
* The frontend will replicate this operation and is the real final
* authority, but adjust the inode's iparent field too if the inode
* is embedded in the directory.
*/
if (chain->bref.type == HAMMER2_BREF_TYPE_INODE &&
chain->data->ipdata.meta.iparent != xop->head.ip3->meta.inum) {
hammer2_inode_data_t *wipdata;
error = hammer2_chain_modify(chain, xop->head.mtid, 0, 0);
if (error == 0) {
wipdata = &chain->data->ipdata;
wipdata->meta.iparent = xop->head.ip3->meta.inum;
}
}
/*
* Destroy any matching target(s) before creating the new entry.
* This will result in some ping-ponging of the directory key
* iterator but that is ok.
*/
parent = hammer2_inode_chain(xop->head.ip3, clindex,
HAMMER2_RESOLVE_ALWAYS);
if (parent == NULL) {
error = HAMMER2_ERROR_EIO;
goto done;
}
/*
* Delete all matching directory entries. That is, get rid of
* multiple duplicates if present, as a self-healing mechanism.
*/
if (error == 0) {
tmp = hammer2_chain_lookup(&parent, &key_next,
xop->lhc & ~HAMMER2_DIRHASH_LOMASK,
xop->lhc | HAMMER2_DIRHASH_LOMASK,
&error,
HAMMER2_LOOKUP_ALWAYS);
while (tmp) {
int e2;
if (hammer2_chain_dirent_test(tmp, xop->head.name2,
xop->head.name2_len)) {
e2 = hammer2_chain_delete(parent, tmp,
xop->head.mtid, 0);
if (error == 0 && e2)
error = e2;
}
tmp = hammer2_chain_next(&parent, tmp, &key_next,
key_next,
xop->lhc |
HAMMER2_DIRHASH_LOMASK,
&error,
HAMMER2_LOOKUP_ALWAYS);
}
}
if (error == 0) {
/*
* A relookup is required before the create to properly
* position the parent chain.
*/
tmp = hammer2_chain_lookup(&parent, &key_next,
xop->lhc, xop->lhc,
&error, 0);
KKASSERT(tmp == NULL);
error = hammer2_chain_create(&parent, &chain, NULL, pmp,
HAMMER2_METH_DEFAULT,
xop->lhc, 0,
HAMMER2_BREF_TYPE_INODE,
HAMMER2_INODE_BYTES,
xop->head.mtid, 0, 0);
}
done:
hammer2_xop_feed(&xop->head, NULL, clindex, error);
if (parent) {
hammer2_chain_unlock(parent);
hammer2_chain_drop(parent);
}
if (chain) {
hammer2_chain_unlock(chain);
hammer2_chain_drop(chain);
}
}
/*
* Directory collision resolver scan helper (backend, threaded).
*
* Used by the inode create code to locate an unused lhc.
*/
void
hammer2_xop_scanlhc(hammer2_xop_t *arg, void *scratch, int clindex)
{
hammer2_xop_scanlhc_t *xop = &arg->xop_scanlhc;
hammer2_chain_t *parent;
hammer2_chain_t *chain;
hammer2_key_t key_next;
int error = 0;
parent = hammer2_inode_chain(xop->head.ip1, clindex,
HAMMER2_RESOLVE_ALWAYS |
HAMMER2_RESOLVE_SHARED);
if (parent == NULL) {
kprintf("xop_nresolve: NULL parent\n");
chain = NULL;
error = HAMMER2_ERROR_EIO;
goto done;
}
/*
* Lookup all possibly conflicting directory entries, the feed
* inherits the chain's lock so do not unlock it on the iteration.
*/
chain = hammer2_chain_lookup(&parent, &key_next,
xop->lhc,
xop->lhc + HAMMER2_DIRHASH_LOMASK,
&error,
HAMMER2_LOOKUP_ALWAYS |
HAMMER2_LOOKUP_SHARED);
while (chain) {
error = hammer2_xop_feed(&xop->head, chain, clindex, 0);
if (error) {
hammer2_chain_unlock(chain);
hammer2_chain_drop(chain);
chain = NULL; /* safety */
goto done;
}
chain = hammer2_chain_next(&parent, chain, &key_next,
key_next,
xop->lhc + HAMMER2_DIRHASH_LOMASK,
&error,
HAMMER2_LOOKUP_ALWAYS |
HAMMER2_LOOKUP_SHARED);
}
done:
hammer2_xop_feed(&xop->head, NULL, clindex, error);
if (parent) {
hammer2_chain_unlock(parent);
hammer2_chain_drop(parent);
}
}
/*
* Generic lookup of a specific key.
*/
void
hammer2_xop_lookup(hammer2_xop_t *arg, void *scratch, int clindex)
{
hammer2_xop_scanlhc_t *xop = &arg->xop_scanlhc;
hammer2_chain_t *parent;
hammer2_chain_t *chain;
hammer2_key_t key_next;
int error = 0;
parent = hammer2_inode_chain(xop->head.ip1, clindex,
HAMMER2_RESOLVE_ALWAYS |
HAMMER2_RESOLVE_SHARED);
chain = NULL;
if (parent == NULL) {
error = HAMMER2_ERROR_EIO;
goto done;
}
/*
* Lookup all possibly conflicting directory entries, the feed
* inherits the chain's lock so do not unlock it on the iteration.
*/
chain = hammer2_chain_lookup(&parent, &key_next,
xop->lhc, xop->lhc,
&error,
HAMMER2_LOOKUP_ALWAYS |
HAMMER2_LOOKUP_SHARED);
if (error == 0) {
if (chain)
error = chain->error;
else
error = HAMMER2_ERROR_ENOENT;
}
hammer2_xop_feed(&xop->head, chain, clindex, error);
done:
if (chain) {
hammer2_chain_unlock(chain);
hammer2_chain_drop(chain);
}
if (parent) {
hammer2_chain_unlock(parent);
hammer2_chain_drop(parent);
}
}
void
hammer2_xop_delete(hammer2_xop_t *arg, void *scratch, int clindex)
{
hammer2_xop_scanlhc_t *xop = &arg->xop_scanlhc;
hammer2_chain_t *parent;
hammer2_chain_t *chain;
hammer2_key_t key_next;
int error = 0;
parent = hammer2_inode_chain(xop->head.ip1, clindex,
HAMMER2_RESOLVE_ALWAYS);
chain = NULL;
if (parent == NULL) {
error = HAMMER2_ERROR_EIO;
goto done;
}
/*
* Lookup all possibly conflicting directory entries, the feed
* inherits the chain's lock so do not unlock it on the iteration.
*/
chain = hammer2_chain_lookup(&parent, &key_next,
xop->lhc, xop->lhc,
&error,
HAMMER2_LOOKUP_NODATA);
if (error == 0) {
if (chain)
error = chain->error;
else
error = HAMMER2_ERROR_ENOENT;
}
if (chain) {
error = hammer2_chain_delete(parent, chain, xop->head.mtid,
HAMMER2_DELETE_PERMANENT);
}
hammer2_xop_feed(&xop->head, NULL, clindex, error);
done:
if (chain) {
hammer2_chain_unlock(chain);
hammer2_chain_drop(chain);
}
if (parent) {
hammer2_chain_unlock(parent);
hammer2_chain_drop(parent);
}
}
/*
* Generic scan
*
* WARNING! Fed chains must be locked shared so ownership can be transfered
* and to prevent frontend/backend stalls that would occur with an
* exclusive lock. The shared lock also allows chain->data to be
* retained.
*/
void
hammer2_xop_scanall(hammer2_xop_t *arg, void *scratch, int clindex)
{
hammer2_xop_scanall_t *xop = &arg->xop_scanall;
hammer2_chain_t *parent;
hammer2_chain_t *chain;
hammer2_key_t key_next;
int error = 0;
/*
* Assert required flags.
*/
KKASSERT(xop->resolve_flags & HAMMER2_RESOLVE_SHARED);
KKASSERT(xop->lookup_flags & HAMMER2_LOOKUP_SHARED);
/*
* The inode's chain is the iterator. If we cannot acquire it our
* contribution ends here.
*/
parent = hammer2_inode_chain(xop->head.ip1, clindex,
xop->resolve_flags);
if (parent == NULL) {
kprintf("xop_readdir: NULL parent\n");
goto done;
}
/*
* Generic scan of exact records. Note that indirect blocks are
* automatically recursed and will not be returned.
*/
chain = hammer2_chain_lookup(&parent, &key_next,
xop->key_beg, xop->key_end,
&error, xop->lookup_flags);
while (chain) {
error = hammer2_xop_feed(&xop->head, chain, clindex, 0);
if (error)
goto break2;
chain = hammer2_chain_next(&parent, chain, &key_next,
key_next, xop->key_end,
&error, xop->lookup_flags);
}
break2:
if (chain) {
hammer2_chain_unlock(chain);
hammer2_chain_drop(chain);
}
hammer2_chain_unlock(parent);
hammer2_chain_drop(parent);
done:
hammer2_xop_feed(&xop->head, NULL, clindex, error);
}
/************************************************************************
* INODE LAYER XOPS *
************************************************************************
*
*/
/*
* Helper to create a directory entry.
*/
void
hammer2_xop_inode_mkdirent(hammer2_xop_t *arg, void *scratch, int clindex)
{
hammer2_xop_mkdirent_t *xop = &arg->xop_mkdirent;
hammer2_chain_t *parent;
hammer2_chain_t *chain;
hammer2_key_t key_next;
size_t data_len;
int error;
if (hammer2_debug & 0x0001)
kprintf("dirent_create lhc %016jx clindex %d\n",
xop->lhc, clindex);
parent = hammer2_inode_chain(xop->head.ip1, clindex,
HAMMER2_RESOLVE_ALWAYS);
if (parent == NULL) {
error = HAMMER2_ERROR_EIO;
chain = NULL;
goto fail;
}
chain = hammer2_chain_lookup(&parent, &key_next,
xop->lhc, xop->lhc,
&error, 0);
if (chain) {
error = HAMMER2_ERROR_EEXIST;
goto fail;
}
/*
* We may be able to embed the directory entry directly in the
* blockref.
*/
if (xop->dirent.namlen <= sizeof(chain->bref.check.buf))
data_len = 0;
else
data_len = HAMMER2_ALLOC_MIN;
error = hammer2_chain_create(&parent, &chain, NULL, xop->head.ip1->pmp,
HAMMER2_METH_DEFAULT,
xop->lhc, 0,
HAMMER2_BREF_TYPE_DIRENT,
data_len,
xop->head.mtid, 0, 0);
if (error == 0) {
/*
* WARNING: chain->data->buf is sized to chain->bytes,
* do not use sizeof(chain->data->buf), which
* will be much larger.
*/
error = hammer2_chain_modify(chain, xop->head.mtid, 0, 0);
if (error == 0) {
chain->bref.embed.dirent = xop->dirent;
if (xop->dirent.namlen <= sizeof(chain->bref.check.buf))
bcopy(xop->head.name1, chain->bref.check.buf,
xop->dirent.namlen);
else
bcopy(xop->head.name1, chain->data->buf,
xop->dirent.namlen);
}
}
fail:
if (parent) {
hammer2_chain_unlock(parent);
hammer2_chain_drop(parent);
}
hammer2_xop_feed(&xop->head, chain, clindex, error);
if (chain) {
hammer2_chain_unlock(chain);
hammer2_chain_drop(chain);
}
}
/*
* Inode create helper (threaded, backend)
*
* Used by ncreate, nmknod, nsymlink, nmkdir.
* Used by nlink and rename to create HARDLINK pointers.
*
* Frontend holds the parent directory ip locked exclusively. We
* create the inode and feed the exclusively locked chain to the
* frontend.
*/
void
hammer2_xop_inode_create(hammer2_xop_t *arg, void *scratch, int clindex)
{
hammer2_xop_create_t *xop = &arg->xop_create;
hammer2_chain_t *parent;
hammer2_chain_t *chain;
hammer2_key_t key_next;
int error;
if (hammer2_debug & 0x0001)
kprintf("inode_create lhc %016jx clindex %d\n",
xop->lhc, clindex);
parent = hammer2_inode_chain(xop->head.ip1, clindex,
HAMMER2_RESOLVE_ALWAYS);
if (parent == NULL) {
error = HAMMER2_ERROR_EIO;
chain = NULL;
goto fail;
}
chain = hammer2_chain_lookup(&parent, &key_next,
xop->lhc, xop->lhc,
&error, 0);
if (chain) {
error = HAMMER2_ERROR_EEXIST;
goto fail;
}
error = hammer2_chain_create(&parent, &chain, NULL, xop->head.ip1->pmp,
HAMMER2_METH_DEFAULT,
xop->lhc, 0,
HAMMER2_BREF_TYPE_INODE,
HAMMER2_INODE_BYTES,
xop->head.mtid, 0, xop->flags);
if (error == 0) {
error = hammer2_chain_modify(chain, xop->head.mtid, 0, 0);
if (error == 0) {
chain->data->ipdata.meta = xop->meta;
if (xop->head.name1) {
bcopy(xop->head.name1,
chain->data->ipdata.filename,
xop->head.name1_len);
chain->data->ipdata.meta.name_len =
xop->head.name1_len;
}
chain->data->ipdata.meta.name_key = xop->lhc;
}
}
fail:
if (parent) {
hammer2_chain_unlock(parent);
hammer2_chain_drop(parent);
}
hammer2_xop_feed(&xop->head, chain, clindex, error);
if (chain) {
hammer2_chain_unlock(chain);
hammer2_chain_drop(chain);
}
}
/*
* Create inode as above but leave it detached from the hierarchy.
*/
void
hammer2_xop_inode_create_det(hammer2_xop_t *arg, void *scratch, int clindex)
{
hammer2_xop_create_t *xop = &arg->xop_create;
hammer2_chain_t *parent;
hammer2_chain_t *chain;
hammer2_chain_t *null_parent;
hammer2_key_t key_next;
hammer2_inode_t *pip;
hammer2_inode_t *iroot;
int error;
if (hammer2_debug & 0x0001)
kprintf("inode_create_det lhc %016jx clindex %d\n",
xop->lhc, clindex);
pip = xop->head.ip1;
iroot = pip->pmp->iroot;
parent = hammer2_inode_chain(iroot, clindex, HAMMER2_RESOLVE_ALWAYS);
if (parent == NULL) {
error = HAMMER2_ERROR_EIO;
chain = NULL;
goto fail;
}
chain = hammer2_chain_lookup(&parent, &key_next,
xop->lhc, xop->lhc,
&error, 0);
if (chain) {
error = HAMMER2_ERROR_EEXIST;
goto fail;
}
/*
* Create as a detached chain with no parent. We must specify
* methods
*/
null_parent = NULL;
error = hammer2_chain_create(&null_parent, &chain,
parent->hmp, pip->pmp,
HAMMER2_ENC_COMP(pip->meta.comp_algo) +
HAMMER2_ENC_CHECK(pip->meta.check_algo),
xop->lhc, 0,
HAMMER2_BREF_TYPE_INODE,
HAMMER2_INODE_BYTES,
xop->head.mtid, 0, xop->flags);
if (error == 0) {
error = hammer2_chain_modify(chain, xop->head.mtid, 0, 0);
if (error == 0) {
chain->data->ipdata.meta = xop->meta;
if (xop->head.name1) {
bcopy(xop->head.name1,
chain->data->ipdata.filename,
xop->head.name1_len);
chain->data->ipdata.meta.name_len =
xop->head.name1_len;
}
chain->data->ipdata.meta.name_key = xop->lhc;
}
}
fail:
if (parent) {
hammer2_chain_unlock(parent);
hammer2_chain_drop(parent);
}
hammer2_xop_feed(&xop->head, chain, clindex, error);
if (chain) {
hammer2_chain_unlock(chain);
hammer2_chain_drop(chain);
}
}
/*
* Take a detached chain and insert it into the topology
*/
void
hammer2_xop_inode_create_ins(hammer2_xop_t *arg, void *scratch, int clindex)
{
hammer2_xop_create_t *xop = &arg->xop_create;
hammer2_chain_t *parent;
hammer2_chain_t *chain;
hammer2_key_t key_next;
int error;
if (hammer2_debug & 0x0001)
kprintf("inode_create_ins lhc %016jx clindex %d\n",
xop->lhc, clindex);
/*
* (parent) will be the insertion point for inode under iroot
*/
parent = hammer2_inode_chain(xop->head.ip1->pmp->iroot, clindex,
HAMMER2_RESOLVE_ALWAYS);
if (parent == NULL) {
error = HAMMER2_ERROR_EIO;
chain = NULL;
goto fail;
}
chain = hammer2_chain_lookup(&parent, &key_next,
xop->lhc, xop->lhc,
&error, 0);
if (chain) {
error = HAMMER2_ERROR_EEXIST;
goto fail;
}
/*
* (chain) is the detached inode that is being inserted
*/
chain = hammer2_inode_chain(xop->head.ip1, clindex,
HAMMER2_RESOLVE_ALWAYS);
if (chain == NULL) {
error = HAMMER2_ERROR_EIO;
chain = NULL;
goto fail;
}
/*
* This create call will insert the non-NULL chain into parent.
* Most of the auxillary fields are ignored since the chain already
* exists.
*/
error = hammer2_chain_create(&parent, &chain, NULL, xop->head.ip1->pmp,
HAMMER2_METH_DEFAULT,
xop->lhc, 0,
HAMMER2_BREF_TYPE_INODE,
HAMMER2_INODE_BYTES,
xop->head.mtid, 0, xop->flags);
#if 0
if (error == 0) {
error = hammer2_chain_modify(chain, xop->head.mtid, 0, 0);
if (error == 0) {
chain->data->ipdata.meta = xop->meta;
if (xop->head.name1) {
bcopy(xop->head.name1,
chain->data->ipdata.filename,
xop->head.name1_len);
chain->data->ipdata.meta.name_len =
xop->head.name1_len;
}
chain->data->ipdata.meta.name_key = xop->lhc;
}
}
#endif
fail:
if (parent) {
hammer2_chain_unlock(parent);
hammer2_chain_drop(parent);
}
hammer2_xop_feed(&xop->head, chain, clindex, error);
if (chain) {
hammer2_chain_unlock(chain);
hammer2_chain_drop(chain);
}
}
/*
* Inode delete helper (backend, threaded)
*
* Generally used by hammer2_run_sideq()
*/
void
hammer2_xop_inode_destroy(hammer2_xop_t *arg, void *scratch, int clindex)
{
hammer2_xop_destroy_t *xop = &arg->xop_destroy;
hammer2_pfs_t *pmp;
hammer2_chain_t *parent;
hammer2_chain_t *chain;
hammer2_inode_t *ip;
int error;
/*
* We need the precise parent chain to issue the deletion.
*/
ip = xop->head.ip1;
pmp = ip->pmp;
chain = hammer2_inode_chain(ip, clindex, HAMMER2_RESOLVE_ALWAYS);
if (chain == NULL) {
parent = NULL;
error = HAMMER2_ERROR_EIO;
goto done;
}
if (ip->flags & HAMMER2_INODE_CREATING) {
/*
* Inode's chains are not linked into the media topology
* because it is a new inode (which is now being destroyed).
*/
parent = NULL;
} else {
/*
* Inode's chains are linked into the media topology
*/
parent = hammer2_chain_getparent(chain, HAMMER2_RESOLVE_ALWAYS);
if (parent == NULL) {
error = HAMMER2_ERROR_EIO;
goto done;
}
}
KKASSERT(chain->parent == parent);
/*
* We have the correct parent, we can issue the deletion.
*/
hammer2_chain_delete(parent, chain, xop->head.mtid, 0);
error = 0;
done:
hammer2_xop_feed(&xop->head, NULL, clindex, error);
if (parent) {
hammer2_chain_unlock(parent);
hammer2_chain_drop(parent);
}
if (chain) {
hammer2_chain_unlock(chain);
hammer2_chain_drop(chain);
}
}
void
hammer2_xop_inode_unlinkall(hammer2_xop_t *arg, void *scratch, int clindex)
{
hammer2_xop_unlinkall_t *xop = &arg->xop_unlinkall;
hammer2_chain_t *parent;
hammer2_chain_t *chain;
hammer2_key_t key_next;
int error;
/*
* We need the precise parent chain to issue the deletion.
*/
parent = hammer2_inode_chain(xop->head.ip1, clindex,
HAMMER2_RESOLVE_ALWAYS);
chain = NULL;
if (parent == NULL) {
error = 0;
goto done;
}
chain = hammer2_chain_lookup(&parent, &key_next,
xop->key_beg, xop->key_end,
&error, HAMMER2_LOOKUP_ALWAYS);
while (chain) {
hammer2_chain_delete(parent, chain,
xop->head.mtid, HAMMER2_DELETE_PERMANENT);
hammer2_xop_feed(&xop->head, chain, clindex, chain->error);
/* depend on function to unlock the shared lock */
chain = hammer2_chain_next(&parent, chain, &key_next,
key_next, xop->key_end,
&error,
HAMMER2_LOOKUP_ALWAYS);
}
done:
if (error == 0)
error = HAMMER2_ERROR_ENOENT;
hammer2_xop_feed(&xop->head, NULL, clindex, error);
if (parent) {
hammer2_chain_unlock(parent);
hammer2_chain_drop(parent);
}
if (chain) {
hammer2_chain_unlock(chain);
hammer2_chain_drop(chain);
}
}
void
hammer2_xop_inode_connect(hammer2_xop_t *arg, void *scratch, int clindex)
{
hammer2_xop_connect_t *xop = &arg->xop_connect;
hammer2_inode_data_t *wipdata;
hammer2_chain_t *parent;
hammer2_chain_t *chain;
hammer2_pfs_t *pmp;
hammer2_key_t key_dummy;
int error;
/*
* Get directory, then issue a lookup to prime the parent chain
* for the create. The lookup is expected to fail.
*/
pmp = xop->head.ip1->pmp;
parent = hammer2_inode_chain(xop->head.ip1, clindex,
HAMMER2_RESOLVE_ALWAYS);
if (parent == NULL) {
chain = NULL;
error = HAMMER2_ERROR_EIO;
goto fail;
}
chain = hammer2_chain_lookup(&parent, &key_dummy,
xop->lhc, xop->lhc,
&error, 0);
if (chain) {
hammer2_chain_unlock(chain);
hammer2_chain_drop(chain);
chain = NULL;
error = HAMMER2_ERROR_EEXIST;
goto fail;
}
if (error)
goto fail;
/*
* Adjust the filename in the inode, set the name key.
*
* NOTE: Frontend must also adjust ip2->meta on success, we can't
* do it here.
*/
chain = hammer2_inode_chain(xop->head.ip2, clindex,
HAMMER2_RESOLVE_ALWAYS);
error = hammer2_chain_modify(chain, xop->head.mtid, 0, 0);
if (error)
goto fail;
wipdata = &chain->data->ipdata;
hammer2_inode_modify(xop->head.ip2);
if (xop->head.name1) {
bzero(wipdata->filename, sizeof(wipdata->filename));
bcopy(xop->head.name1, wipdata->filename, xop->head.name1_len);
wipdata->meta.name_len = xop->head.name1_len;
}
wipdata->meta.name_key = xop->lhc;
/*
* Reconnect the chain to the new parent directory
*/
error = hammer2_chain_create(&parent, &chain, NULL, pmp,
HAMMER2_METH_DEFAULT,
xop->lhc, 0,
HAMMER2_BREF_TYPE_INODE,
HAMMER2_INODE_BYTES,
xop->head.mtid, 0, 0);
/*
* Feed result back.
*/
fail:
hammer2_xop_feed(&xop->head, NULL, clindex, error);
if (parent) {
hammer2_chain_unlock(parent);
hammer2_chain_drop(parent);
}
if (chain) {
hammer2_chain_unlock(chain);
hammer2_chain_drop(chain);
}
}
/*
* Synchronize the in-memory inode with the chain. This does not flush
* the chain to disk. Instead, it makes front-end inode changes visible
* in the chain topology, thus visible to the backend. This is done in an
* ad-hoc manner outside of the filesystem vfs_sync, and in a controlled
* manner inside the vfs_sync.
*/
void
hammer2_xop_inode_chain_sync(hammer2_xop_t *arg, void *scratch, int clindex)
{
hammer2_xop_fsync_t *xop = &arg->xop_fsync;
hammer2_chain_t *parent;
hammer2_chain_t *chain;
int error;
parent = hammer2_inode_chain(xop->head.ip1, clindex,
HAMMER2_RESOLVE_ALWAYS);
chain = NULL;
if (parent == NULL) {
error = HAMMER2_ERROR_EIO;
goto done;
}
if (parent->error) {
error = parent->error;
goto done;
}
error = 0;
if ((xop->ipflags & HAMMER2_INODE_RESIZED) == 0) {
/* osize must be ignored */
} else if (xop->meta.size < xop->osize) {
/*
* We must delete any chains beyond the EOF. The chain
* straddling the EOF will be pending in the bioq.
*/
hammer2_key_t lbase;
hammer2_key_t key_next;
lbase = (xop->meta.size + HAMMER2_PBUFMASK64) &
~HAMMER2_PBUFMASK64;
chain = hammer2_chain_lookup(&parent, &key_next,
lbase, HAMMER2_KEY_MAX,
&error,
HAMMER2_LOOKUP_NODATA |
HAMMER2_LOOKUP_NODIRECT);
while (chain) {
/*
* Degenerate embedded case, nothing to loop on
*/
switch (chain->bref.type) {
case HAMMER2_BREF_TYPE_DIRENT:
case HAMMER2_BREF_TYPE_INODE:
KKASSERT(0);
break;
case HAMMER2_BREF_TYPE_DATA:
hammer2_chain_delete(parent, chain,
xop->head.mtid,
HAMMER2_DELETE_PERMANENT);
break;
}
chain = hammer2_chain_next(&parent, chain, &key_next,
key_next, HAMMER2_KEY_MAX,
&error,
HAMMER2_LOOKUP_NODATA |
HAMMER2_LOOKUP_NODIRECT);
}
/*
* Reset to point at inode for following code, if necessary.
*/
if (parent->bref.type != HAMMER2_BREF_TYPE_INODE) {
hammer2_chain_unlock(parent);
hammer2_chain_drop(parent);
parent = hammer2_inode_chain(xop->head.ip1,
clindex,
HAMMER2_RESOLVE_ALWAYS);
kprintf("hammer2: TRUNCATE RESET on '%s'\n",
parent->data->ipdata.filename);
}
}
/*
* Sync the inode meta-data, potentially clear the blockset area
* of direct data so it can be used for blockrefs.
*/
if (error == 0) {
error = hammer2_chain_modify(parent, xop->head.mtid, 0, 0);
if (error == 0) {
parent->data->ipdata.meta = xop->meta;
if (xop->clear_directdata) {
bzero(&parent->data->ipdata.u.blockset,
sizeof(parent->data->ipdata.u.blockset));
}
}
}
done:
if (chain) {
hammer2_chain_unlock(chain);
hammer2_chain_drop(chain);
}
if (parent) {
hammer2_chain_unlock(parent);
hammer2_chain_drop(parent);
}
hammer2_xop_feed(&xop->head, NULL, clindex, error);
}
| 26.467953 | 79 | 0.67419 |
30f2e23fa6796c43694a07aece8c14f1e2381949 | 1,013 | h | C | Game/Source/Particle.h | Montuuh/LosPanasGame | 6884216355b1b6e0e1d6ac371e2e48ad25c833ec | [
"MIT"
] | null | null | null | Game/Source/Particle.h | Montuuh/LosPanasGame | 6884216355b1b6e0e1d6ac371e2e48ad25c833ec | [
"MIT"
] | null | null | null | Game/Source/Particle.h | Montuuh/LosPanasGame | 6884216355b1b6e0e1d6ac371e2e48ad25c833ec | [
"MIT"
] | null | null | null | #include "Animation.h"
#include "Point.h"
struct Collider;
struct Particle
{
public:
// Constructor
Particle();
// Copy constructor
Particle(const Particle& p);
// Destructor
~Particle();
// Called in ModuleParticles' Update
// Handles the logic of the particle
// Returns false when the particle reaches its lifetime
bool Update(float dt);
public:
// Defines the position in the screen
fPoint position;
// Defines the speed at which the particle will move (pixels per second)
fPoint speed;
// A set of rectangle sprites
Animation anim;
// Defines wether the particle is alive or not
// Particles will be set to not alive until "spawnTime" is reached
bool isAlive = false;
// Defines the amout of frames this particle has been active
// Negative values mean the particle is waiting to be activated
int frameCount = 0;
// Defines the total amount of frames during which the particle will be active
uint lifetime = 0;
// The particle's collider
Collider* collider = nullptr;
}; | 22.021739 | 79 | 0.733465 |
801f4ede5640de99259898da3c2b0e22cbb9e336 | 3,606 | h | C | chromium/extensions/browser/external_provider_interface.h | wedataintelligence/vivaldi-source | 22a46f2c969f6a0b7ca239a05575d1ea2738768c | [
"BSD-3-Clause"
] | null | null | null | chromium/extensions/browser/external_provider_interface.h | wedataintelligence/vivaldi-source | 22a46f2c969f6a0b7ca239a05575d1ea2738768c | [
"BSD-3-Clause"
] | null | null | null | chromium/extensions/browser/external_provider_interface.h | wedataintelligence/vivaldi-source | 22a46f2c969f6a0b7ca239a05575d1ea2738768c | [
"BSD-3-Clause"
] | 2 | 2020-04-04T13:34:56.000Z | 2020-11-04T07:17:52.000Z | // Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef EXTENSIONS_BROWSER_EXTERNAL_PROVIDER_INTERFACE_H_
#define EXTENSIONS_BROWSER_EXTERNAL_PROVIDER_INTERFACE_H_
#include <vector>
#include "base/memory/linked_ptr.h"
#include "extensions/common/manifest.h"
class GURL;
namespace base {
class FilePath;
class Version;
}
namespace extensions {
// This class is an abstract class for implementing external extensions
// providers.
class ExternalProviderInterface {
public:
// ExternalProvider uses this interface to communicate back to the
// caller what extensions are registered, and which |id|, |version| and |path|
// they have. See also VisitRegisteredExtension below. Ownership of |version|
// is not transferred to the visitor. Callers of the methods below must
// ensure that |id| is a valid extension id (use
// crx_file::id_util::IdIsValid(id)).
class VisitorInterface {
public:
// Return true if the extension install will proceed. Install will not
// proceed if the extension is already installed from a higher priority
// location.
virtual bool OnExternalExtensionFileFound(
const std::string& id,
const base::Version* version,
const base::FilePath& path,
Manifest::Location location,
int creation_flags,
bool mark_acknowledged,
bool install_immediately) = 0;
// Return true if the extension install will proceed. Install might not
// proceed if the extension is already installed from a higher priority
// location.
virtual bool OnExternalExtensionUpdateUrlFound(
const std::string& id,
const std::string& install_parameter,
const GURL& update_url,
Manifest::Location location,
int creation_flags,
bool mark_acknowledged) = 0;
// Called after all the external extensions have been reported
// through the above two methods. |provider| is a pointer to the
// provider that is now ready (typically this), and the
// implementation of OnExternalProviderReady() should be able to
// safely assert that provider->IsReady().
virtual void OnExternalProviderReady(
const ExternalProviderInterface* provider) = 0;
protected:
virtual ~VisitorInterface() {}
};
virtual ~ExternalProviderInterface() {}
// The visitor (ExtensionsService) calls this function before it goes away.
virtual void ServiceShutdown() = 0;
// Enumerate registered extensions, calling
// OnExternalExtension(File|UpdateUrl)Found on the |visitor| object for each
// registered extension found.
virtual void VisitRegisteredExtension() = 0;
// Test if this provider has an extension with id |id| registered.
virtual bool HasExtension(const std::string& id) const = 0;
// Gets details of an extension by its id. Output params will be set only
// if they are not NULL. If an output parameter is not specified by the
// provider type, it will not be changed.
// This function is no longer used outside unit tests.
virtual bool GetExtensionDetails(
const std::string& id,
Manifest::Location* location,
scoped_ptr<base::Version>* version) const = 0;
// Determines if this provider had loaded the list of external extensions
// from its source.
virtual bool IsReady() const = 0;
};
typedef std::vector<linked_ptr<ExternalProviderInterface> >
ProviderCollection;
} // namespace extensions
#endif // EXTENSIONS_BROWSER_EXTERNAL_PROVIDER_INTERFACE_H_
| 35.352941 | 80 | 0.727676 |
802ab2c96bf45130c6b6ad05d4ec24152b4f69f4 | 391 | h | C | Coding_iOS/Controllers/ProjectToChooseListViewController.h | awesome-archive/Coding-iOS | 6b480857b9058a99d7c2f8720d91747a84a31861 | [
"MIT"
] | 4,345 | 2015-09-09T10:38:03.000Z | 2022-03-26T10:30:09.000Z | Coding_iOS/Controllers/ProjectToChooseListViewController.h | Vesentanger/Coding-iOS-master | 48a91310966926c1bafe1fea722d71c4e749f0ea | [
"MIT"
] | 21 | 2016-09-22T07:37:19.000Z | 2019-10-05T23:15:02.000Z | Coding_iOS/Controllers/ProjectToChooseListViewController.h | Vesentanger/Coding-iOS-master | 48a91310966926c1bafe1fea722d71c4e749f0ea | [
"MIT"
] | 1,743 | 2015-09-09T11:56:54.000Z | 2022-02-10T13:53:45.000Z | //
// ProjectToChooseListViewController.h
// Coding_iOS
//
// Created by Ease on 15/7/1.
// Copyright (c) 2015年 Coding. All rights reserved.
//
#import "BaseViewController.h"
#import "Project.h"
@interface ProjectToChooseListViewController : BaseViewController
@property (copy, nonatomic) void(^projectChoosedBlock)(ProjectToChooseListViewController *chooseVC, Project *project);
@end
| 26.066667 | 118 | 0.772379 |
80527c71f2a2d9b7394bf0a86615395a170d2325 | 295 | h | C | XRRouter/Classes/XRRouterProtocol.h | wangshuwen1107/XRouter-iOS | 6f25351051cb0a7d61b176c3f4dff3d2c9417e51 | [
"MIT"
] | null | null | null | XRRouter/Classes/XRRouterProtocol.h | wangshuwen1107/XRouter-iOS | 6f25351051cb0a7d61b176c3f4dff3d2c9417e51 | [
"MIT"
] | null | null | null | XRRouter/Classes/XRRouterProtocol.h | wangshuwen1107/XRouter-iOS | 6f25351051cb0a7d61b176c3f4dff3d2c9417e51 | [
"MIT"
] | null | null | null | //
// Created by 王书文 on 2020/9/17.
// Copyright (c) 2020 cn.cheney. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "XRRouterModule.h"
@protocol XRRouterProtocol <NSObject>
+ (NSString *_Nonnull)moduleName;
+ (void)registerMethod:(nonnull XRRouterModule *) module;
@end
| 16.388889 | 57 | 0.725424 |
2c2f6cc559bcc80c6b9a29e9d77b74e8d7d6acee | 346 | h | C | includes/mathematica++/mathematica++.h | DominikLindorfer/mathematicapp | ce9de342501d803ccd115533d19c7e3ace51e475 | [
"BSD-2-Clause-FreeBSD"
] | 8 | 2019-10-04T16:27:33.000Z | 2022-01-30T22:28:51.000Z | includes/mathematica++/mathematica++.h | DominikLindorfer/mathematicapp | ce9de342501d803ccd115533d19c7e3ace51e475 | [
"BSD-2-Clause-FreeBSD"
] | null | null | null | includes/mathematica++/mathematica++.h | DominikLindorfer/mathematicapp | ce9de342501d803ccd115533d19c7e3ace51e475 | [
"BSD-2-Clause-FreeBSD"
] | 2 | 2020-02-22T03:33:50.000Z | 2020-09-17T07:10:21.000Z | #include "mathematica++/tokens.h"
#include "mathematica++/accessor.h"
#include "mathematica++/connector.h"
#include "mathematica++/variant.h"
#include "mathematica++/m.h"
#include "mathematica++/io.h"
#include "mathematica++/rules.h"
#include "mathematica++/operators.h"
#include "mathematica++/declares.h"
#include "mathematica++/association.h"
| 31.454545 | 38 | 0.739884 |
26242a217c2155f17d42ae022bcbf178da004349 | 638 | h | C | IRQHack64/Software/Arduino/IRQHack64/DirFunction.h | ozayturay/EagleProjects | a0bfeedb2d148938293e1e1c00d5c4e4d3c8c070 | [
"MIT"
] | 12 | 2016-03-04T06:03:40.000Z | 2021-01-30T06:17:15.000Z | IRQHack64/Software/Arduino/IRQHack64/DirFunction.h | ozayturay/EagleProjects | a0bfeedb2d148938293e1e1c00d5c4e4d3c8c070 | [
"MIT"
] | 1 | 2020-07-13T09:22:05.000Z | 2020-10-06T15:02:25.000Z | IRQHack64/Software/Arduino/IRQHack64/DirFunction.h | ozayturay/EagleProjects | a0bfeedb2d148938293e1e1c00d5c4e4d3c8c070 | [
"MIT"
] | 5 | 2018-03-09T19:11:55.000Z | 2020-12-01T10:45:48.000Z | #ifndef _DIR_FUNCTION_H
#define _DIR_FUNCTION_H
#include <SdFat.h>
#include <SdFatUtil.h>
#include "StringPrint.h"
#include "CharStack.h"
class DirFunction {
protected:
SdFat* sd;
SdFile file;
StringStack stack;
unsigned int count;
unsigned int currentIndex;
public:
void SetSd(SdFat* sdFat);
void ToRoot();
void GoBack();
void Rewind();
void Prepare();
void ChangeDirectory(char * directory);
unsigned int GetCount();
int Iterate();
StringPrint CurrentFileName;
int IsDirectory;
int IsFinished;
int IsHidden;
int InSubDir;
};
#endif _DIR_FUNCTION_H
| 18.228571 | 43 | 0.669279 |
267b68140eacad3c948319b8995aa027fb5d6dad | 199 | h | C | C++/LAB2/tasks.h | KHYehor/UniversityPractice | c1b0a8c4bd9a029a53cfacb4e13fde32f5fd5f48 | [
"MIT"
] | null | null | null | C++/LAB2/tasks.h | KHYehor/UniversityPractice | c1b0a8c4bd9a029a53cfacb4e13fde32f5fd5f48 | [
"MIT"
] | null | null | null | C++/LAB2/tasks.h | KHYehor/UniversityPractice | c1b0a8c4bd9a029a53cfacb4e13fde32f5fd5f48 | [
"MIT"
] | null | null | null | #ifndef tasks_h
#define tasks_h
#include <iostream>
#include <limits.h>
#include <cassert>
#include <cmath>
#include <list>
#include <cstdlib>
#include "ClassTree.h"
using namespace std;
#endif
| 12.4375 | 22 | 0.728643 |
6462095759b4132a622d61d897ebe7d4b21237de | 462 | h | C | src/api/z3_logger.h | jar-ben/z3 | 7baa4f88b0cb4458461596d147e1f71853d77126 | [
"MIT"
] | 7,746 | 2015-03-26T18:59:33.000Z | 2022-03-31T15:34:48.000Z | src/api/z3_logger.h | jar-ben/z3 | 7baa4f88b0cb4458461596d147e1f71853d77126 | [
"MIT"
] | 5,162 | 2015-03-27T01:12:48.000Z | 2022-03-31T14:56:16.000Z | src/api/z3_logger.h | jar-ben/z3 | 7baa4f88b0cb4458461596d147e1f71853d77126 | [
"MIT"
] | 1,529 | 2015-03-26T18:45:30.000Z | 2022-03-31T15:35:16.000Z | /*++
Copyright (c) 2011 Microsoft Corporation
Module Name:
z3_logger.h
Abstract:
Goodies for log generation
Author:
Leonardo de Moura (leonardo) 2011-09-22
Notes:
--*/
#include "util/symbol.h"
void R();
void P(void * obj);
void I(int64_t i);
void U(uint64_t u);
void D(double d);
void S(Z3_string str);
void Sy(Z3_symbol sym);
void Ap(unsigned sz);
void Au(unsigned sz);
void Ai(unsigned sz);
void Asy(unsigned sz);
void C(unsigned id);
| 14 | 43 | 0.683983 |
03a0cef0469d49066907d6a70072232389f528ee | 3,262 | h | C | hardware/kit/common/bsp/thunderboard/bap.h | lmnotran/gecko_sdk | 2e82050dc8823c9fe0e8908c1b2666fb83056230 | [
"Zlib"
] | 82 | 2016-06-29T17:24:43.000Z | 2021-04-16T06:49:17.000Z | hardware/kit/common/bsp/thunderboard/bap.h | lmnotran/gecko_sdk | 2e82050dc8823c9fe0e8908c1b2666fb83056230 | [
"Zlib"
] | 7 | 2020-08-25T02:41:16.000Z | 2022-03-21T19:55:46.000Z | hardware/kit/common/bsp/thunderboard/bap.h | lmnotran/gecko_sdk | 2e82050dc8823c9fe0e8908c1b2666fb83056230 | [
"Zlib"
] | 56 | 2016-08-02T10:50:50.000Z | 2021-07-19T08:57:34.000Z | /***************************************************************************//**
* @file
* @brief Driver for the Bosch Sensortec BMP280 barometric pressure sensor
*******************************************************************************
* # License
* <b>Copyright 2018 Silicon Laboratories Inc. www.silabs.com</b>
*******************************************************************************
*
* SPDX-License-Identifier: Zlib
*
* The licensor of this software is Silicon Laboratories Inc.
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*
******************************************************************************/
#ifndef BAP_H
#define BAP_H
/***************************************************************************//**
* @addtogroup BAP
* @{
******************************************************************************/
#include "bap_config.h"
/**************************************************************************//**
* @name Error Codes
* @{
******************************************************************************/
#define BAP_OK 0x0000 /**< No errors */
#define BAP_ERROR_DRIVER_NOT_INITIALIZED 0x0001 /**< The driver is not initialized */
#define BAP_ERROR_I2C_TRANSACTION_FAILED 0x0002 /**< I2C transaction failed */
#define BAP_ERROR_DEVICE_ID_MISMATCH 0x0003 /**< The device ID does not match the expected value */
/**@}*/
/** @cond DO_NOT_INCLUDE_WITH_DOXYGEN */
#define BAP_DEVICE_ID_BMP280 0x58 /**< Device ID of the BMP280 chip */
/** @endcond */
/***************************************************************************//**
* @brief
* Structure to configure the BMP280 device
******************************************************************************/
typedef struct __BAP_Config {
uint8_t oversampling; /**< Oversampling value */
uint8_t powerMode; /**< SLEEP, FORCED or NORMAL power mode setting */
uint8_t standbyTime; /**< Standby time setting */
} BAP_Config;
uint32_t BAP_init (uint8_t *deviceId);
void BAP_deInit (void);
uint32_t BAP_config (BAP_Config *cfg);
uint32_t BAP_getTemperature (float *temperature);
uint32_t BAP_getPressure (float *pressure);
/** @} */
/** @} */
#endif // BMP_H
| 43.493333 | 107 | 0.493256 |
ea86ec729486b77d86bd2b3f13cc55d2568540ea | 562 | h | C | examples/epoll/server/keyboard.h | caoziyao/server.c | 5e45521f68de5c8ad836a1c40891595f8552966e | [
"Apache-2.0"
] | null | null | null | examples/epoll/server/keyboard.h | caoziyao/server.c | 5e45521f68de5c8ad836a1c40891595f8552966e | [
"Apache-2.0"
] | null | null | null | examples/epoll/server/keyboard.h | caoziyao/server.c | 5e45521f68de5c8ad836a1c40891595f8552966e | [
"Apache-2.0"
] | null | null | null | //
// keyboard.h
// server
//
// Created by working on 2018/3/12.
// Copyright © 2018年 working. All rights reserved.
// select
#ifndef keyboard_h
#define keyboard_h
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <stdbool.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <sys/event.h>
#include <sys/types.h>
#include <sys/time.h>
#include <sys/select.h>
#include <sys/ioctl.h>
#include <sys/socket.h>
#include <arpa/inet.h>
void
keyBoardSelect();
#endif /* keyboard_h */
| 16.529412 | 51 | 0.688612 |
d81245587f1ce99e5cff8737a9542eeea9426dc4 | 247 | h | C | Eleven/Models/BaseObject.h | tanglei11/meitu_copy | 9a8b93f4bb9a7e0e9dfb8b40743b99e32100b0d7 | [
"MIT"
] | 3 | 2019-12-14T05:59:43.000Z | 2021-09-30T03:25:10.000Z | Eleven/Models/BaseObject.h | tanglei11/meitu_copy | 9a8b93f4bb9a7e0e9dfb8b40743b99e32100b0d7 | [
"MIT"
] | null | null | null | Eleven/Models/BaseObject.h | tanglei11/meitu_copy | 9a8b93f4bb9a7e0e9dfb8b40743b99e32100b0d7 | [
"MIT"
] | null | null | null | //
// BaseObject.h
// Eleven
//
// Created by Peanut on 2019/1/29.
// Copyright © 2019 coderyi. All rights reserved.
//
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
@interface BaseObject : NSObject
@end
NS_ASSUME_NONNULL_END
| 13.722222 | 50 | 0.724696 |
88609a352d64f12049234ff30f86f5a2fa311fb0 | 1,163 | h | C | main.h | kajusz/atemTally | 819a538cac6ccdb680d08c2cd763de3d4a5dabb1 | [
"BSD-2-Clause"
] | 1 | 2016-09-03T15:30:08.000Z | 2016-09-03T15:30:08.000Z | main.h | kajusz/atemTally | 819a538cac6ccdb680d08c2cd763de3d4a5dabb1 | [
"BSD-2-Clause"
] | null | null | null | main.h | kajusz/atemTally | 819a538cac6ccdb680d08c2cd763de3d4a5dabb1 | [
"BSD-2-Clause"
] | 1 | 2018-08-14T10:00:45.000Z | 2018-08-14T10:00:45.000Z | #pragma once
// Uncomment this if you want debug feedback in the serial port
//#define DEBUG
// Arduino stuff
#include <Arduino.h>
#include <SPI.h>
// easier to write, it's for toggling the led
#define LED(x, y) { digitalWrite(7, x); digitalWrite(8, y); }
// debugging stuff
#ifdef DEBUG
# include <MemoryFree.h>
# define DBGOUT(x) Serial.print(F(x))
# define DBGOUTLN(x) Serial.println(F(x))
#else
# define DBGOUT(x)
# define DBGOUTLN(x)
#endif
// Cameron's favourite number.
#define MAGIC_NUMBER 0x69
// templates for reading/writing to eeprom
#include <EEPROM.h>
template <class T> int EEPROM_writeT(int ee, const T& value)
{
const byte* p = (const byte*)(const void*)&value;
unsigned int i;
for (i = 0; i < sizeof(value); i++)
EEPROM.write(ee++, *p++);
return i;
}
template <class T> int EEPROM_readT(int ee, T& value)
{
byte* p = (byte*)(void*)&value;
unsigned int i;
for (i = 0; i < sizeof(value); i++)
*p++ = EEPROM.read(ee++);
return i;
}
// Networking
#include <Ethernet.h>
// GPIO Expander
#include <gpio_expander.h>
#include <mcp23s17.h>
// define functions
void prodSetup();
void prodLoop();
void cfgSetup();
void cfgLoop();
| 20.051724 | 63 | 0.674979 |
154d6b358953e154350b7ee25a8806bb4d7091b6 | 2,001 | h | C | aliyun-api-oms/2015-02-12/include/ali_oms.h | zcy421593/aliyun-openapi-cpp-sdk | 8af0a59dedf303fa6c6911a61c356237fa6105a1 | [
"Apache-2.0"
] | 1 | 2015-11-28T16:46:56.000Z | 2015-11-28T16:46:56.000Z | aliyun-api-oms/2015-02-12/include/ali_oms.h | zcy421593/aliyun-openapi-cpp-sdk | 8af0a59dedf303fa6c6911a61c356237fa6105a1 | [
"Apache-2.0"
] | null | null | null | aliyun-api-oms/2015-02-12/include/ali_oms.h | zcy421593/aliyun-openapi-cpp-sdk | 8af0a59dedf303fa6c6911a61c356237fa6105a1 | [
"Apache-2.0"
] | null | null | null | #ifndef ALI_OMSH
#define ALI_OMSH
#include <string>
#include <string.h>
#include <stdlib.h>
#include "ali_oms_get_product_define_types.h"
#include "ali_oms_get_user_data_types.h"
#ifdef WIN32
#ifdef aliyun_api_oms_2015_02_12_EXPORTS
#define ALIYUN_API_OMS_2015_02_12_DLL_EXPORT_IMPORT __declspec(dllexport)
#else
#define ALIYUN_API_OMS_2015_02_12_DLL_EXPORT_IMPORT
#endif
#else
#define ALIYUN_API_OMS_2015_02_12_DLL_EXPORT_IMPORT
#endif
namespace aliyun {
struct OmsErrorInfo {
std::string request_id;
std::string code;
std::string message;
std::string host_id;
};
class ALIYUN_API_OMS_2015_02_12_DLL_EXPORT_IMPORT Oms {
public:
static Oms* CreateOmsClient(std::string endpoint, std::string appid, std::string secret);
~Oms();
private:
Oms(std::string host, std::string appid, std::string secret);
public:
void SetUseTls(bool use_tls = true) { if(support_tls_) use_tls_ = use_tls; }
bool GetUseTls() { return use_tls_; }
bool GetSupportTls() { return support_tls_; }
void SetProxyHost(std::string proxy_host) {
if(this->proxy_host_) {
free(this->proxy_host_);
}
this->proxy_host_ = strdup(proxy_host.c_str());
}
std::string GetProxyHost() { return this->proxy_host_; }
void SetRegionId(std::string region_id) {
if(this->region_id_) {
free(this->region_id_);
}
this->region_id_ = strdup(region_id.c_str());
}
std::string GetRegionId() { return this->region_id_; }
int GetProductDefine(const OmsGetProductDefineRequestType& req,
OmsGetProductDefineResponseType* resp,
OmsErrorInfo* error_info);
int GetUserData(const OmsGetUserDataRequestType& req,
OmsGetUserDataResponseType* resp,
OmsErrorInfo* error_info);
private:
char* appid_;
char* secret_;
char* version_;
char* host_;
char* proxy_host_;
bool support_tls_;
bool use_tls_;
char* region_id_;
}; //end class
} // end namespace
#endif
| 29.426471 | 92 | 0.706647 |
29eb9dee0925b3ba7054c4c9eed300aae9e910ec | 2,005 | h | C | igl/flip_avoiding_line_search.h | aviadtzemah/animation2 | 9a3f980fbe27672fe71f8f61f73b5713f2af5089 | [
"Apache-2.0"
] | 2,392 | 2016-12-17T14:14:12.000Z | 2022-03-30T19:40:40.000Z | igl/flip_avoiding_line_search.h | aviadtzemah/animation2 | 9a3f980fbe27672fe71f8f61f73b5713f2af5089 | [
"Apache-2.0"
] | 106 | 2018-04-19T17:47:31.000Z | 2022-03-01T19:44:11.000Z | igl/flip_avoiding_line_search.h | aviadtzemah/animation2 | 9a3f980fbe27672fe71f8f61f73b5713f2af5089 | [
"Apache-2.0"
] | 184 | 2017-11-15T09:55:37.000Z | 2022-02-21T16:30:46.000Z | // This file is part of libigl, a simple c++ geometry processing library.
//
// Copyright (C) 2016 Michael Rabinovich
//
// 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/.
#ifndef IGL_FLIP_AVOIDING_LINE_SEARCH_H
#define IGL_FLIP_AVOIDING_LINE_SEARCH_H
#include "igl_inline.h"
#include "PI.h"
#include <Eigen/Dense>
namespace igl
{
// A bisection line search for a mesh based energy that avoids triangle flips as suggested in
// "Bijective Parameterization with Free Boundaries" (Smith J. and Schaefer S., 2015).
//
// The user specifies an initial vertices position (that has no flips) and target one (that my have flipped triangles).
// This method first computes the largest step in direction of the destination vertices that does not incur flips,
// and then minimizes a given energy using this maximal step and a bisection linesearch (see igl::line_search).
//
// Supports both triangle and tet meshes.
//
// Inputs:
// F #F by 3/4 list of mesh faces or tets
// cur_v #V by dim list of variables
// dst_v #V by dim list of target vertices. This mesh may have flipped triangles
// energy A function to compute the mesh-based energy (return an energy that is bigger than 0)
// cur_energy(OPTIONAL) The energy at the given point. Helps save redundant computations.
// This is optional. If not specified, the function will compute it.
// Outputs:
// cur_v #V by dim list of variables at the new location
// Returns the energy at the new point
IGL_INLINE double flip_avoiding_line_search(
const Eigen::MatrixXi F,
Eigen::MatrixXd& cur_v,
Eigen::MatrixXd& dst_v,
std::function<double(Eigen::MatrixXd&)> energy,
double cur_energy = -1);
}
#ifndef IGL_STATIC_LIBRARY
# include "flip_avoiding_line_search.cpp"
#endif
#endif
| 40.1 | 121 | 0.709227 |
49ee273090a1f6421d2e830ec8fa5c9711c0df77 | 293 | c | C | nattybear/language-coder/pointer/621.c | nattybear/jungol | d7e1bd01156cad538e3cbb7fa091154b661e28b2 | [
"MIT"
] | 3 | 2021-12-26T06:40:53.000Z | 2021-12-28T13:02:08.000Z | nattybear/language-coder/pointer/621.c | nattybear/jungol | d7e1bd01156cad538e3cbb7fa091154b661e28b2 | [
"MIT"
] | 9 | 2021-12-26T01:39:21.000Z | 2022-02-12T02:02:38.000Z | nattybear/language-coder/pointer/621.c | nattybear/jungol | d7e1bd01156cad538e3cbb7fa091154b661e28b2 | [
"MIT"
] | 2 | 2021-12-26T00:50:57.000Z | 2022-01-24T13:40:26.000Z | #include <stdio.h>
int main()
{
int n, m;
int *p = &n;
int *q = &m;
scanf("%i %i", p, q);
printf("%i + %i = %i\n", *p, *q, *p + *q);
printf("%i - %i = %i\n", *p, *q, *p - *q);
printf("%i * %i = %i\n", *p, *q, *p * *q);
printf("%i / %i = %i\n", *p, *q, *p / *q);
return 0;
}
| 19.533333 | 44 | 0.365188 |
0ac81938ae73f72ff8a71ee13212c9aa802ec8c3 | 3,364 | c | C | amuxctl/amuxctl.c | repk/amux | 3992a2af5ad3bbb99b47f5987ccbff4d4f82fcf7 | [
"Beerware"
] | 3 | 2018-04-13T21:36:47.000Z | 2020-12-28T06:45:04.000Z | amuxctl/amuxctl.c | repk/amux | 3992a2af5ad3bbb99b47f5987ccbff4d4f82fcf7 | [
"Beerware"
] | 1 | 2020-04-16T12:35:40.000Z | 2020-04-16T12:35:40.000Z | amuxctl/amuxctl.c | repk/amux | 3992a2af5ad3bbb99b47f5987ccbff4d4f82fcf7 | [
"Beerware"
] | 1 | 2019-04-07T16:53:21.000Z | 2019-04-07T16:53:21.000Z | #include <stdlib.h>
#include <stdio.h>
#include <sys/file.h>
#include <alsa/asoundlib.h>
#include "amuxctl.h"
#include "pcmlist.h"
struct amux_ctx {
snd_config_t *top;
char const *file;
struct pcmlst plst;
};
/*
* Add stub for missing snd_config_{ref,unref} added in 1.1.2
*/
#if (SND_LIB_VERSION < ((1 << 16) | (1 << 8) | (2 << 8)))
void snd_config_ref(snd_config_t *top)
{
(void)top;
}
void snd_config_unref(snd_config_t *top)
{
(void)top;
}
#endif
static char const *cfg_get_str(snd_config_t *cfg, char const *key)
{
char const *str = NULL;
snd_config_t *entry;
int ret;
ret = snd_config_search(cfg, key, &entry);
if(ret < 0) {
fprintf(stderr, "Cannot get default cfg node for %s\n", key);
goto out;
}
ret = snd_config_get_string(entry, &str);
if(ret < 0) {
fprintf(stderr, "Cannot get default cfg value for %s\n", key);
str = NULL;
goto out;
}
out:
return str;
}
static int amux_cfg_parse(struct amux_ctx *ctx)
{
snd_config_t *dft;
char const *str;
int ret;
ctx->top = snd_config;
snd_config_ref(ctx->top);
ret = snd_config_search(ctx->top, "pcm.default", &dft);
if(ret < 0) {
fprintf(stderr, "Cannot get default config\n");
goto err;
}
ret = -EINVAL;
str = cfg_get_str(dft, "type");
if((str == NULL) || (strcmp(str, "amux") != 0)) {
fprintf(stderr, "Cannot find config for amux plugin\n");
goto unref;
}
str = cfg_get_str(dft, "file");
if(str == NULL)
goto unref;
ctx->file = str;
return 0;
unref:
snd_config_unref(ctx->top);
snd_config_update_free_global();
err:
return ret;
}
void amux_pcmlst_dump(struct amux_ctx *actx)
{
pcmlst_dump(&actx->plst);
}
int amux_pcm_set(struct amux_ctx *actx, char const *pcm)
{
size_t totsz, cursz;
ssize_t sz;
int fd = -1, ret;
ret = open(actx->file, O_WRONLY);
if(ret < 0)
goto out;
fd = ret;
totsz = strlen(pcm);
cursz = 0;
ret = flock(fd, LOCK_EX);
if(ret < 0) {
ret = -errno;
goto close;
}
while(cursz < totsz) {
sz = write(fd, pcm + cursz, totsz - cursz);
if(sz <= 0) {
ret = (int)sz;
goto unlock;
}
cursz += sz;
}
ret = ftruncate(fd, totsz);
unlock:
flock(fd, LOCK_UN);
close:
close(fd);
out:
return ret;
}
int amux_pcm_get(struct amux_ctx *actx, char *pcm, size_t len)
{
size_t cursz;
ssize_t sz;
int fd = -1, ret;
ret = open(actx->file, O_RDONLY);
if(ret < 0)
goto out;
fd = ret;
cursz = 0;
ret = flock(fd, LOCK_SH);
if(ret < 0) {
ret = -errno;
goto close;
}
sz = 1;
while(sz != 0) {
sz = read(fd, pcm + cursz, len - cursz);
if(sz < 0) {
ret = (int)sz;
goto unlock;
}
cursz += sz;
}
ret = cursz;
unlock:
flock(fd, LOCK_UN);
close:
close(fd);
out:
return ret;
}
struct amux_ctx *amux_ctx_new() {
struct amux_ctx *actx = NULL;
actx = calloc(1, sizeof(*actx));
return actx;
}
int amux_ctx_init(struct amux_ctx *actx)
{
int ret;
ret = pcmlst_init(&actx->plst);
if(ret != 0) {
fprintf(stderr, "Cannot initialize PCM list\n");
goto err;
}
ret = amux_cfg_parse(actx);
if(ret != 0) {
fprintf(stderr, "Cannot parse config\n");
goto clean;
}
return 0;
clean:
pcmlst_cleanup(&actx->plst);
err:
return ret;
}
void amux_ctx_cleanup(struct amux_ctx *actx)
{
snd_config_unref(actx->top);
/* Cleanup alsalib mess */
snd_config_update_free_global();
pcmlst_cleanup(&actx->plst);
}
void amux_ctx_free(struct amux_ctx *actx) {
free(actx);
}
| 15.867925 | 66 | 0.640309 |
ebd15ba4b76e2dec2bb7f3d2701040dd970dd22a | 5,189 | c | C | src/windows/win-controls.c | codezero1010/multi-timer | 8d49ea1b9a87c6ea155eaea6005cf0d4e32354f6 | [
"MIT"
] | 53 | 2015-01-01T09:34:33.000Z | 2022-03-24T06:17:20.000Z | src/windows/win-controls.c | codezero1010/multi-timer | 8d49ea1b9a87c6ea155eaea6005cf0d4e32354f6 | [
"MIT"
] | 18 | 2015-01-06T20:28:59.000Z | 2020-11-06T19:14:57.000Z | src/windows/win-controls.c | codezero1010/multi-timer | 8d49ea1b9a87c6ea155eaea6005cf0d4e32354f6 | [
"MIT"
] | 26 | 2015-01-08T10:37:07.000Z | 2020-11-02T22:25:46.000Z | /*
Multi Timer v3.4
http://matthewtole.com/pebble/multi-timer/
----------------------
The MIT License (MIT)
Copyright © 2013 - 2015 Matthew Tole
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
--------------------
src/windows/win-controls.c
*/
#include <pebble.h>
#include <pebble-assist.h>
#include <bitmap-loader.h>
#include "win-controls.h"
#include "../timers.h"
#include "../timer.h"
#include "../icons.h"
#include "../common.h"
#define MENU_ROW_RESUME 0
#define MENU_ROW_PAUSE 1
#define MENU_ROW_RESET 2
#define MENU_ROW_DELETE 3
static void window_load(Window* window);
static void window_unload(Window* window);
static uint16_t menu_num_sections(struct MenuLayer* menu, void* callback_context);
static uint16_t menu_num_rows(struct MenuLayer* menu, uint16_t section_index, void* callback_context);
static int16_t menu_cell_height(struct MenuLayer *menu, MenuIndex *cell_index, void *callback_context);
static void menu_draw_row(GContext* ctx, const Layer* cell_layer, MenuIndex* cell_index, void* callback_context);
static void menu_select(struct MenuLayer* menu, MenuIndex* cell_index, void* callback_context);
static Window* s_window;
static MenuLayer* s_menu;
void win_controls_init(void) {
s_window = window_create();
window_set_window_handlers(s_window, (WindowHandlers) {
.load = window_load,
.unload = window_unload
});
}
void win_controls_show(void) {
window_stack_push(s_window, true);
}
static void window_load(Window* window) {
s_menu = menu_layer_create_fullscreen(s_window);
menu_layer_set_callbacks(s_menu, NULL, (MenuLayerCallbacks) {
.get_num_sections = menu_num_sections,
.get_num_rows = menu_num_rows,
.get_cell_height = menu_cell_height,
.draw_row = menu_draw_row,
.select_click = menu_select,
});
menu_layer_add_to_window(s_menu, s_window);
}
static void window_unload(Window* window) {
menu_layer_destroy(s_menu);
}
static uint16_t menu_num_sections(struct MenuLayer* menu, void* callback_context) {
return 1;
}
static uint16_t menu_num_rows(struct MenuLayer* menu, uint16_t section_index, void* callback_context) {
return 4;
}
static int16_t menu_cell_height(struct MenuLayer *menu, MenuIndex *cell_index, void *callback_context) {
return 32;
}
static void menu_draw_row(GContext* ctx, const Layer* cell_layer, MenuIndex* cell_index, void* callback_context) {
switch (cell_index->row) {
case MENU_ROW_RESUME:
menu_draw_row_icon_text(ctx, "Resume All", bitmaps_get_sub_bitmap(RESOURCE_ID_ICONS_16, ICON_RECT_PLAY));
break;
case MENU_ROW_PAUSE:
menu_draw_row_icon_text(ctx, "Pause All", bitmaps_get_sub_bitmap(RESOURCE_ID_ICONS_16, ICON_RECT_PAUSE));
break;
case MENU_ROW_RESET:
menu_draw_row_icon_text(ctx, "Reset All", bitmaps_get_sub_bitmap(RESOURCE_ID_ICONS_16, ICON_RECT_RESET));
break;
case MENU_ROW_DELETE:
menu_draw_row_icon_text(ctx, "Delete All", bitmaps_get_sub_bitmap(RESOURCE_ID_ICONS_16, ICON_RECT_DELETE));
break;
}
}
static void menu_select(struct MenuLayer* menu, MenuIndex* cell_index, void* callback_context) {
uint8_t num_timers = timers_count();
switch (cell_index->row) {
case MENU_ROW_RESUME:
for (uint8_t t = 0; t < num_timers; t += 1) {
Timer* timer = timers_get(t);
switch (timer->status) {
case TIMER_STATUS_RUNNING:
break;
case TIMER_STATUS_PAUSED:
timer_resume(timer);
break;
case TIMER_STATUS_DONE:
timer_reset(timer);
timer_start(timer);
break;
case TIMER_STATUS_STOPPED:
timer_start(timer);
break;
}
}
break;
case MENU_ROW_PAUSE:
for (uint8_t t = 0; t < num_timers; t += 1) {
Timer* timer = timers_get(t);
if (timer->status == TIMER_STATUS_RUNNING) {
timer_pause(timer);
}
}
break;
case MENU_ROW_RESET:
for (uint8_t t = 0; t < num_timers; t += 1) {
timer_reset(timers_get(t));
}
break;
case MENU_ROW_DELETE:
for (uint8_t t = 0; t < num_timers; t += 1) {
timers_remove(0);
}
break;
}
window_stack_pop(true);
}
| 33.050955 | 114 | 0.71613 |
a54aa03f2f3d3abf7a0e8ef914e76ca5093d5986 | 1,324 | h | C | src/usr/include/stdio.h | DreamPearl/FuzzyOS | e287bf139511b59abe9e2a0e7ce49444c6a5299e | [
"Apache-2.0"
] | null | null | null | src/usr/include/stdio.h | DreamPearl/FuzzyOS | e287bf139511b59abe9e2a0e7ce49444c6a5299e | [
"Apache-2.0"
] | null | null | null | src/usr/include/stdio.h | DreamPearl/FuzzyOS | e287bf139511b59abe9e2a0e7ce49444c6a5299e | [
"Apache-2.0"
] | null | null | null | #pragma once
#include <stddef.h>
#ifdef __cplusplus
extern "C" {
namespace std {
#endif
#define SYSCALL_CONSOLE_SUB_CLRSCR 0
#define SYSCALL_CONSOLE_SUB_PUTCHAR 1
#define SYSCALL_CONSOLE_SUB_PUTS_BUFFER 2
int putchar(int c);
int puts(const char *s);
int snprintf(char *s, size_t n, const char *fmt, ...);
int printf(const char *strfmt, ...);
char* gets (char *s);
typedef struct FILE {
// in user space.
int file_handler_id;
// in kernel/filesystem space
int file_id;
// 0 => start of file
int cursor;
// store last error code
int err;
} FILE;
// TODO: Add API for reading list of files.
// Only readonly mode is supported.
#define SYSCALL_FILE_SUB_OPEN 0
#define SYSCALL_FILE_SUB_READBUFFER 1
#define SYSCALL_FILE_SUB_READ_DIR 2
// We are allocating FILE handler as global because we
// don't have heap memory manager yet.
#define LIMIT_MAX_FILE_OPEN 10
// same as sector size for better performance
#define FILEIO_BUFFER_SIZE 512
#define EOF (-1)
FILE *fopen(char *filename, char *mode);
int fgetc(FILE *file);
char *fgets(char *buf, size_t n, FILE *file);
int fclose(FILE *file);
int ferror(FILE *file);
void clearerror(FILE *file);
#ifdef __cplusplus
} // namespace std end
} // extern C end
#endif
| 21.704918 | 55 | 0.680514 |
cbd332a54d0044d99347b035735cb0ecd8e7500a | 952 | h | C | BitCleaner - Source/filemanager.h | lukasz50018/BitCleaner | 0ace3fae40f8b3810de3b7082b456a9e826a4229 | [
"MIT"
] | null | null | null | BitCleaner - Source/filemanager.h | lukasz50018/BitCleaner | 0ace3fae40f8b3810de3b7082b456a9e826a4229 | [
"MIT"
] | null | null | null | BitCleaner - Source/filemanager.h | lukasz50018/BitCleaner | 0ace3fae40f8b3810de3b7082b456a9e826a4229 | [
"MIT"
] | null | null | null | #ifndef FILEMANAGER_H
#define FILEMANAGER_H
#include <QString>
#include <QSet>
#include <QList>
#include <QFileInfo>
#include <QTableWidget>
class FileManager
{
public:
FileManager();
QList <QString> fileList;
void standardOrganize();
void noStandardOrganize(QString);
void customOrganize(QString, QString, bool);
void standardClean(bool,bool,bool);
void customClean(QString);
void changeWhiteToHardSpaces();
void changeHardToWhiteSpaces();
void removeWhiteSpaces();
void removeHardSpaces();
void exchange(QTableWidget *);
void toUpperCases();
void toLowerCases();
void firstCaseUpper();
void firstCaseLower();
void everyWordStartsLowerCase();
void everyWordStartsUpperCase();
QString getFileExt(QString);
QString getFileNameWithoutExt(QString);
QString getFilePath(QString);
private:
};
#endif // FILEMANAGER_H
| 20.695652 | 49 | 0.683824 |
cbef395e120445e7c1272ff26704c9111216066f | 1,339 | c | C | cellml-benchmarks/c/tentusscher_noble_noble_panfilov_2004_a/Tentusscher2004McellNetwork/SodiumCalciumExchangerCurrent/sodium_calcium_exchanger_current.c | nallen01/phd-thesis-benchmarks | bbeb1ec2f9079b36015693717b0ef99a8a276119 | [
"MIT"
] | null | null | null | cellml-benchmarks/c/tentusscher_noble_noble_panfilov_2004_a/Tentusscher2004McellNetwork/SodiumCalciumExchangerCurrent/sodium_calcium_exchanger_current.c | nallen01/phd-thesis-benchmarks | bbeb1ec2f9079b36015693717b0ef99a8a276119 | [
"MIT"
] | null | null | null | cellml-benchmarks/c/tentusscher_noble_noble_panfilov_2004_a/Tentusscher2004McellNetwork/SodiumCalciumExchangerCurrent/sodium_calcium_exchanger_current.c | nallen01/phd-thesis-benchmarks | bbeb1ec2f9079b36015693717b0ef99a8a276119 | [
"MIT"
] | null | null | null | #include "sodium_calcium_exchanger_current.h"
// sodium_calcium_exchanger_current Initialisation function
void SodiumCalciumExchangerCurrentInit(SodiumCalciumExchangerCurrent* me) {
// Initialise State
me->state = SODIUM_CALCIUM_EXCHANGER_CURRENT_Q0;
// Initialise Outputs
me->i_naca = 0.0;
}
// sodium_calcium_exchanger_current Execution function
void SodiumCalciumExchangerCurrentRun(SodiumCalciumExchangerCurrent* me) {
// Create intermediary variables
enum SodiumCalciumExchangerCurrentStates state_u = me->state;
double i_naca_u = me->i_naca;
// Run the state machine for transition logic
switch(me->state) {
case SODIUM_CALCIUM_EXCHANGER_CURRENT_Q0: // Logic for state q0
if(true) {
i_naca_u = (1000.0 * (exp((0.35 * me->v * me->f) / (me->r * me->t)) * (pow(me->na_i, 3.0)) * me->ca_o - exp(((0.35 - 1.0) * me->v * me->f) / (me->r * me->t)) * (pow(me->na_o, 3.0)) * me->ca_i * 2.5)) / ((pow(87.5, 3.0) + pow(me->na_o, 3.0)) * (1.38 + me->ca_o) * (1.0 + 0.1 * exp(((0.35 - 1.0) * me->v * me->f) / (me->r * me->t))));
// Remain in this state
state_u = SODIUM_CALCIUM_EXCHANGER_CURRENT_Q0;
}
break;
}
// Update from intermediary variables
me->state = state_u;
me->i_naca = i_naca_u;
} | 38.257143 | 348 | 0.625093 |
ae19064169e388f0d3fe60eba0870f4cb0477797 | 11,434 | c | C | base/wow64/wow64/callback.c | npocmaka/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 17 | 2020-11-13T13:42:52.000Z | 2021-09-16T09:13:13.000Z | base/wow64/wow64/callback.c | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 2 | 2020-10-19T08:02:06.000Z | 2020-10-19T08:23:18.000Z | base/wow64/wow64/callback.c | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 14 | 2020-11-14T09:43:20.000Z | 2021-08-28T08:59:57.000Z | /*++
Copyright (c) 1998-2000 Microsoft Corporation
Module Name:
callback.c
Abstract:
Provides generic 64-to-32 transfer routines.
Author:
20-May-1998 BarryBo
Revision History:
2-Sept-1999 [askhalid] Removing some 32bit alpha specific code and using right context.
--*/
#define _WOW64DLLAPI_
#include <nt.h>
#include <ntrtl.h>
#include <nturtl.h>
#include "wow64p.h"
#include "wow64cpu.h"
ASSERTNAME;
VOID
WOW64DLLAPI
Wow64ApcRoutine(
ULONG_PTR ApcContext,
ULONG_PTR Arg2,
ULONG_PTR Arg3
)
/*++
Routine Description:
Call a 32-bit APC function.
Arguments:
ApcContext - wow64 APC context data
Arg2 - second arg to APC routine
Arg3 - third arg to APC routine
Return Value:
None. Returns contrl back to NTDLL's APC handler, which will
call native NtContinue to resume execution.
--*/
{
CONTEXT32 NewContext32;
ULONG SP;
PULONG Ptr;
USER_APC_ENTRY UserApcEntry;
//
// Grab the current 32-bit context
//
NewContext32.ContextFlags = CONTEXT32_INTEGER|CONTEXT32_CONTROL;
CpuGetContext(NtCurrentThread(),
NtCurrentProcess(),
NtCurrentTeb(),
&NewContext32);
//
// Build up the APC callback state in NewContext32
//
SP = CpuGetStackPointer() & (~3);
SP -= 4*sizeof(ULONG)+sizeof(CONTEXT32);
Ptr = (PULONG)SP;
Ptr[0] = (ULONG)(ApcContext >> 32); // NormalRoutine
Ptr[1] = (ULONG)ApcContext; // NormalContext
Ptr[2] = (ULONG)Arg2; // SystemArgument1
Ptr[3] = (ULONG)Arg3; // SystemArgument2
((PCONTEXT32)(&Ptr[4]))->ContextFlags = CONTEXT32_FULL;
CpuGetContext(NtCurrentThread(),
NtCurrentProcess(),
NtCurrentTeb(),
(PCONTEXT32)&Ptr[4]); // ContinueContext (BYVAL!)
CpuSetStackPointer(SP);
CpuSetInstructionPointer(Ntdll32KiUserApcDispatcher);
//
// Link this APC into the list of outstanding APCs
//
UserApcEntry.Next = (PUSER_APC_ENTRY)Wow64TlsGetValue(WOW64_TLS_APCLIST);
UserApcEntry.pContext32 = (PCONTEXT32)&Ptr[4];
Wow64TlsSetValue(WOW64_TLS_APCLIST, &UserApcEntry);
//
// Call the 32-bit APC function. 32-bit NtContinue will longjmp
// back when the APC function is done.
//
if (setjmp(UserApcEntry.JumpBuffer) == 0) {
RunCpuSimulation();
}
//
// If we get here, Wow64NtContinue has done a longjmp back, so
// return back to the caller (in ntdll.dll), which will do a
// native NtContinue and restore the native stack pointer and
// context back.
//
// This is critical to do. The x86 CONTEXT above has an out-of-date
// value for EAX. It still contains the system-service number for
// whatever kernel call was made that allowed the APC to run. On
// an x86 machine, the x86 CONTEXT above would have had STATUS_USER_APC
// or some other code like it, but on WOW64 we don't know what value
// to use. The correct value is sitting in the 64-bit CONTEXT up
// the stack from where we are. So... by returning here via longjmp,
// native ntdll.dll will do an NtContinue to resume execution in the
// native Nt* API that allowed the native APC to fire. It will load
// the return register with the right NTSTATUS code, so the whNt*
// thunk will see the correct code, and reflect it into EAX.
//
}
NTSTATUS
WOW64DLLAPI
Wow64WrapApcProc(
PVOID *pApcRoutine,
PVOID *pApcContext
)
/*++
Routine Description:
Thunk a 32-bit ApcRoutine/ApcContext pair to 64-bit
Arguments:
pApcRoutine - pointer to pointer to APC routine. IN is the 32-bit
routine. OUT is the 64-bit wow64 thunk
pApcContext - pointer to pointer to APC context. IN is the 32-bit
context. OUT is the 64-bit wow64 thunk
Return Value:
NTSTATUS
--*/
{
NTSTATUS NtStatus = STATUS_SUCCESS;
if (*pApcRoutine) {
//
// Dispatch the call to the jacket routine inside Wow64
//
*pApcContext = (PVOID)((ULONG_PTR)*pApcContext | ((ULONG_PTR)*pApcRoutine << 32));
*pApcRoutine = Wow64ApcRoutine;
} else {
NtStatus = STATUS_INVALID_PARAMETER;
}
return NtStatus;
}
ULONG
Wow64KiUserCallbackDispatcher(
PUSERCALLBACKDATA pUserCallbackData,
ULONG ApiNumber,
ULONG ApiArgument,
ULONG ApiSize
)
/*++
Routine Description:
Make a call from a 64-to-32 user callback thunk into 32-bit code.
This function calls ntdll32's KiUserCallbackDispatcher, and returns
when 32-bit code calls NtCallbackReturn/ZwCallbackReturn.
Arguments:
pUserCallbackData - OUT struct to use for tracking this callback
ApiNumber - index of API to call
ApiArgument - 32-bit pointer to 32-bit argument to the API
ApiSize - size of *ApiArgument
Return Value:
Return value from the API call
--*/
{
CONTEXT32 OldContext;
ULONG ExceptionList;
PTEB32 Teb32;
ULONG NewStack;
//
// Handle nested callbacks
//
pUserCallbackData->PreviousUserCallbackData = Wow64TlsGetValue(WOW64_TLS_USERCALLBACKDATA);
//
// Store the callback data in the TEB. whNtCallbackReturn will
// use this pointer to pass information back here via a longjmp.
//
Wow64TlsSetValue(WOW64_TLS_USERCALLBACKDATA, pUserCallbackData);
if (!setjmp(pUserCallbackData->JumpBuffer)) {
//
// Make the call to ntdll32. whNtCallbackReturn will
// longjmp back to this routine when it is called.
//
OldContext.ContextFlags = CONTEXT32_FULL;
CpuGetContext(NtCurrentThread(),
NtCurrentProcess(),
NtCurrentTeb(),
&OldContext);
NewStack = OldContext.Esp - ApiSize;
RtlCopyMemory((PVOID)NewStack, (PVOID)ApiArgument, ApiSize);
*(PULONG)(NewStack - 4) = 0; // InputLength
*(PULONG)(NewStack - 8) = NewStack;
*(PULONG)(NewStack - 12) = ApiNumber;
*(PULONG)(NewStack - 16) = 0;
NewStack -= 16;
CpuSetStackPointer(NewStack);
CpuSetInstructionPointer(Ntdll32KiUserCallbackDispatcher);
//
// Save the exception list in case another handler is defined during
// the callout.
//
Teb32 = NtCurrentTeb32();
ExceptionList = Teb32->NtTib.ExceptionList;
//
// Execte the callback
//
RunCpuSimulation();
//
// This never returns. When 32-bit code is done, it calls
// NtCallbackReturn. The thunk does a longjmp back to this
// routine and lands in the 'else' clause below:
//
} else {
//
// Made it back from the NtCallbackReturn thunk. Restore the
// 32-bit context as it was before the callback, and return
// back to our caller. Our caller will call 64-bit
// NtCallbackReturn to finish blowing off the 64-bit stack.
//
CpuSetContext(NtCurrentThread(),
NtCurrentProcess(),
NtCurrentTeb(),
&OldContext);
//
// Restore exception list.
//
NtCurrentTeb32()->NtTib.ExceptionList = ExceptionList;
return pUserCallbackData->Status;
}
//
// Should never get here.
//
WOWASSERT(FALSE);
return STATUS_UNSUCCESSFUL;
}
NTSTATUS
Wow64NtCallbackReturn(
PVOID OutputBuffer,
ULONG OutputLength,
NTSTATUS Status
)
{
PUSERCALLBACKDATA pUserCallbackData;
//
// Find the callback data stuffed in TLS by Wow64KiUserCallbackDispatcher
//
pUserCallbackData = (PUSERCALLBACKDATA)Wow64TlsGetValue(WOW64_TLS_USERCALLBACKDATA);
if (pUserCallbackData) {
//
// Restore previous User Callback context
//
Wow64TlsSetValue(WOW64_TLS_USERCALLBACKDATA, pUserCallbackData->PreviousUserCallbackData);
//
// Jump back to Wow64KiUserCallbackDispatcher
//
pUserCallbackData->UserBuffer = NULL;
pUserCallbackData->OutputBuffer = OutputBuffer;
//
// Realign the buffer
//
if (((SIZE_T)OutputBuffer & (sizeof(ULONGLONG)-1)) != 0) {
pUserCallbackData->OutputBuffer = Wow64AllocateHeap ( OutputLength );
if (pUserCallbackData->OutputBuffer == NULL) {
pUserCallbackData->OutputBuffer = OutputBuffer;
pUserCallbackData->Status = STATUS_NO_MEMORY;
} else {
RtlCopyMemory (pUserCallbackData->OutputBuffer, OutputBuffer, OutputLength );
pUserCallbackData->UserBuffer = OutputBuffer; // works as a flag
}
}
pUserCallbackData->OutputLength = OutputLength;
pUserCallbackData->Status = Status;
longjmp(pUserCallbackData->JumpBuffer, 1);
//
// We would never come here
//
}
//
// No callback data. Probably a non-nested NtCallbackReturn call.
// The kernel fails these with this return value.
//
return STATUS_NO_CALLBACK_ACTIVE;
}
WOW64DLLAPI
NTSTATUS
Wow64NtContinue(
IN PCONTEXT ContextRecord, // really a PCONTEXT32
IN BOOLEAN TestAlert
)
/*++
Routine Description:
32-bit wrapper for NtContinue. Loads the new CONTEXT32 into the CPU
and optionally allows usermode APCs to run.
Arguments:
ContextRecord - new 32-bit CONTEXT to use
TestAlert - TRUE if usermode APCs may be fired
Return Value:
NTSTATUS.
--*/
{
PCONTEXT32 Context32 = (PCONTEXT32)ContextRecord;
PUSER_APC_ENTRY pApcEntry;
PUSER_APC_ENTRY pApcEntryPrev;
CpuSetContext(NtCurrentThread(),
NtCurrentProcess(),
NtCurrentTeb(),
Context32);
pApcEntryPrev = NULL;
pApcEntry = (PUSER_APC_ENTRY)Wow64TlsGetValue(WOW64_TLS_APCLIST);
while (pApcEntry) {
if (pApcEntry->pContext32 == Context32) {
//
// Found an outstanding usermode APC on this thread, and this
// NtContinue call matches it. Unwind back to the right place
// on the native stack and have it do an NtContinue too.
//
if (pApcEntryPrev) {
pApcEntryPrev->Next = pApcEntry->Next;
} else {
Wow64TlsSetValue(WOW64_TLS_APCLIST, pApcEntry->Next);
}
longjmp(pApcEntry->JumpBuffer, 1);
}
pApcEntryPrev = pApcEntry;
pApcEntry = pApcEntry->Next;
}
//
// No usermode APC is outstanding for this context record. Don't
// unwind the native stack because there is no place to go... just
// continue the simulation.
//
if (TestAlert) {
NtTestAlert();
}
return Context32->Eax;
}
| 28.372208 | 99 | 0.601364 |
3e85fa86dee995d2b6a7f517d063b3970e10d75c | 3,714 | c | C | mc/model/com.mentor.nucleus.bp.core/src4110/ooaofooa_TE_FUNCTION_class.c | NDGuthrie/bposs | 2c47abf74a3e6fadb174b08e57aa66a209400606 | [
"Apache-2.0"
] | 1 | 2018-01-24T16:28:01.000Z | 2018-01-24T16:28:01.000Z | mc/model/com.mentor.nucleus.bp.core/src418/ooaofooa_TE_FUNCTION_class.c | NDGuthrie/bposs | 2c47abf74a3e6fadb174b08e57aa66a209400606 | [
"Apache-2.0"
] | null | null | null | mc/model/com.mentor.nucleus.bp.core/src418/ooaofooa_TE_FUNCTION_class.c | NDGuthrie/bposs | 2c47abf74a3e6fadb174b08e57aa66a209400606 | [
"Apache-2.0"
] | null | null | null | /*----------------------------------------------------------------------------
* File: ooaofooa_TE_FUNCTION_class.c
*
* Class: OAL function (TE_FUNCTION)
* Component: ooaofooa
*
* your copyright statement can go here (from te_copyright.body)
*--------------------------------------------------------------------------*/
#include "sys_sys_types.h"
#include "LOG_bridge.h"
#include "POP_bridge.h"
#include "T_bridge.h"
#include "ooaofooa_classes.h"
/*
* Instance Loader (from string data).
*/
Escher_iHandle_t
ooaofooa_TE_FUNCTION_instanceloader( Escher_iHandle_t instance, const c_t * avlstring[] )
{
Escher_iHandle_t return_identifier = 0;
ooaofooa_TE_FUNCTION * self = (ooaofooa_TE_FUNCTION *) instance;
/* Initialize application analysis class attributes. */
self->method = Escher_strcpy( self->method, avlstring[ 1 ] );
self->parameters = Escher_strcpy( self->parameters, avlstring[ 2 ] );
self->Statement_ID = (Escher_iHandle_t) Escher_atoi( avlstring[ 3 ] );
return return_identifier;
}
/*
* Select any where using referential/identifying attribute set.
* If not_empty, relate this instance to the selected instance.
*/
void ooaofooa_TE_FUNCTION_batch_relate( Escher_iHandle_t instance )
{
ooaofooa_TE_FUNCTION * ooaofooa_TE_FUNCTION_instance = (ooaofooa_TE_FUNCTION *) instance;
ooaofooa_TE_SMT * ooaofooa_TE_SMTrelated_instance1 = ooaofooa_TE_SMT_AnyWhere1( ooaofooa_TE_FUNCTION_instance->Statement_ID );
if ( ooaofooa_TE_SMTrelated_instance1 ) {
ooaofooa_TE_FUNCTION_R2069_Link( ooaofooa_TE_SMTrelated_instance1, ooaofooa_TE_FUNCTION_instance );
}
}
/*
* RELATE TE_SMT TO TE_FUNCTION ACROSS R2069
*/
void
ooaofooa_TE_FUNCTION_R2069_Link( ooaofooa_TE_SMT * supertype, ooaofooa_TE_FUNCTION * subtype )
{
/* Use TagEmptyHandleDetectionOn() to detect empty handle references. */
subtype->Statement_ID = supertype->Statement_ID;
/* Optimized linkage for TE_FUNCTION->TE_SMT[R2069] */
subtype->TE_SMT_R2069 = supertype;
/* Optimized linkage for TE_SMT->TE_FUNCTION[R2069] */
supertype->R2069_subtype = subtype;
supertype->R2069_object_id = ooaofooa_TE_FUNCTION_CLASS_NUMBER;
}
/*
* UNRELATE TE_SMT FROM TE_FUNCTION ACROSS R2069
*/
void
ooaofooa_TE_FUNCTION_R2069_Unlink( ooaofooa_TE_SMT * supertype, ooaofooa_TE_FUNCTION * subtype )
{
/* Use TagEmptyHandleDetectionOn() to detect empty handle references. */
subtype->TE_SMT_R2069 = 0;
supertype->R2069_subtype = 0;
supertype->R2069_object_id = 0;
}
/*
* Dump instances in SQL format.
*/
void
ooaofooa_TE_FUNCTION_instancedumper( Escher_iHandle_t instance )
{
ooaofooa_TE_FUNCTION * self = (ooaofooa_TE_FUNCTION *) instance;
printf( "INSERT INTO TE_FUNCTION VALUES ( '%s','%s',%ld );\n",
( 0 != self->method ) ? self->method : "",
( 0 != self->parameters ) ? self->parameters : "",
((long)self->Statement_ID & ESCHER_IDDUMP_MASK) );
}
/*
* Statically allocate space for the instance population for this class.
* Allocate space for the class instance and its attribute values.
* Depending upon the collection scheme, allocate containoids (collection
* nodes) for gathering instances into free and active extents.
*/
static Escher_SetElement_s ooaofooa_TE_FUNCTION_container[ ooaofooa_TE_FUNCTION_MAX_EXTENT_SIZE ];
static ooaofooa_TE_FUNCTION ooaofooa_TE_FUNCTION_instances[ ooaofooa_TE_FUNCTION_MAX_EXTENT_SIZE ];
Escher_Extent_t pG_ooaofooa_TE_FUNCTION_extent = {
{0,0}, {0,0}, &ooaofooa_TE_FUNCTION_container[ 0 ],
(Escher_iHandle_t) &ooaofooa_TE_FUNCTION_instances,
sizeof( ooaofooa_TE_FUNCTION ), 0, ooaofooa_TE_FUNCTION_MAX_EXTENT_SIZE
};
| 36.772277 | 129 | 0.713786 |
16431581b96704d6e0cdb122f0be5dc01d844035 | 4,313 | h | C | boot/rpi/arch/x86/dts/include/dt-bindings/clock/stm32mp1-clks.h | yodaos-project/yodaos | d0d7bbc277c0fc1c64e2e0a1c82fe6e63f6eb954 | [
"Apache-2.0"
] | 1,144 | 2018-12-18T09:46:47.000Z | 2022-03-07T14:51:46.000Z | boot/rpi/arch/xtensa/dts/include/dt-bindings/clock/stm32mp1-clks.h | Rokid/YodaOS | d0d7bbc277c0fc1c64e2e0a1c82fe6e63f6eb954 | [
"Apache-2.0"
] | 16 | 2019-01-28T06:08:40.000Z | 2019-12-04T10:26:41.000Z | boot/rpi/arch/xtensa/dts/include/dt-bindings/clock/stm32mp1-clks.h | Rokid/YodaOS | d0d7bbc277c0fc1c64e2e0a1c82fe6e63f6eb954 | [
"Apache-2.0"
] | 129 | 2018-12-18T09:46:50.000Z | 2022-03-30T07:30:13.000Z | /* SPDX-License-Identifier: GPL-2.0 or BSD-3-Clause */
/*
* Copyright (C) STMicroelectronics 2017 - All Rights Reserved
* Author: Gabriel Fernandez <gabriel.fernandez@st.com> for STMicroelectronics.
*/
/* OSCILLATOR clocks */
#define CK_HSE 0
#define CK_CSI 1
#define CK_LSI 2
#define CK_LSE 3
#define CK_HSI 4
#define CK_HSE_DIV2 5
/* Bus clocks */
#define TIM2 6
#define TIM3 7
#define TIM4 8
#define TIM5 9
#define TIM6 10
#define TIM7 11
#define TIM12 12
#define TIM13 13
#define TIM14 14
#define LPTIM1 15
#define SPI2 16
#define SPI3 17
#define USART2 18
#define USART3 19
#define UART4 20
#define UART5 21
#define UART7 22
#define UART8 23
#define I2C1 24
#define I2C2 25
#define I2C3 26
#define I2C5 27
#define SPDIF 28
#define CEC 29
#define DAC12 30
#define MDIO 31
#define TIM1 32
#define TIM8 33
#define TIM15 34
#define TIM16 35
#define TIM17 36
#define SPI1 37
#define SPI4 38
#define SPI5 39
#define USART6 40
#define SAI1 41
#define SAI2 42
#define SAI3 43
#define DFSDM 44
#define FDCAN 45
#define LPTIM2 46
#define LPTIM3 47
#define LPTIM4 48
#define LPTIM5 49
#define SAI4 50
#define SYSCFG 51
#define VREF 52
#define TMPSENS 53
#define PMBCTRL 54
#define HDP 55
#define LTDC 56
#define DSI 57
#define IWDG2 58
#define USBPHY 59
#define STGENRO 60
#define SPI6 61
#define I2C4 62
#define I2C6 63
#define USART1 64
#define RTCAPB 65
#define TZC 66
#define TZPC 67
#define IWDG1 68
#define BSEC 69
#define STGEN 70
#define DMA1 71
#define DMA2 72
#define DMAMUX 73
#define ADC12 74
#define USBO 75
#define SDMMC3 76
#define DCMI 77
#define CRYP2 78
#define HASH2 79
#define RNG2 80
#define CRC2 81
#define HSEM 82
#define IPCC 83
#define GPIOA 84
#define GPIOB 85
#define GPIOC 86
#define GPIOD 87
#define GPIOE 88
#define GPIOF 89
#define GPIOG 90
#define GPIOH 91
#define GPIOI 92
#define GPIOJ 93
#define GPIOK 94
#define GPIOZ 95
#define CRYP1 96
#define HASH1 97
#define RNG1 98
#define BKPSRAM 99
#define MDMA 100
#define DMA2D 101
#define GPU 102
#define ETHCK 103
#define ETHTX 104
#define ETHRX 105
#define ETHMAC 106
#define FMC 107
#define QSPI 108
#define SDMMC1 109
#define SDMMC2 110
#define CRC1 111
#define USBH 112
#define ETHSTP 113
/* Kernel clocks */
#define SDMMC1_K 114
#define SDMMC2_K 115
#define SDMMC3_K 116
#define FMC_K 117
#define QSPI_K 118
#define ETHMAC_K 119
#define RNG1_K 120
#define RNG2_K 121
#define GPU_K 122
#define USBPHY_K 123
#define STGEN_K 124
#define SPDIF_K 125
#define SPI1_K 126
#define SPI2_K 127
#define SPI3_K 128
#define SPI4_K 129
#define SPI5_K 130
#define SPI6_K 131
#define CEC_K 132
#define I2C1_K 133
#define I2C2_K 134
#define I2C3_K 135
#define I2C4_K 136
#define I2C5_K 137
#define I2C6_K 138
#define LPTIM1_K 139
#define LPTIM2_K 140
#define LPTIM3_K 141
#define LPTIM4_K 142
#define LPTIM5_K 143
#define USART1_K 144
#define USART2_K 145
#define USART3_K 146
#define UART4_K 147
#define UART5_K 148
#define USART6_K 149
#define UART7_K 150
#define UART8_K 151
#define DFSDM_K 152
#define FDCAN_K 153
#define SAI1_K 154
#define SAI2_K 155
#define SAI3_K 156
#define SAI4_K 157
#define ADC12_K 158
#define DSI_K 159
#define ADFSDM_K 160
#define USBO_K 161
#define LTDC_K 162
/* PLL */
#define PLL1 163
#define PLL2 164
#define PLL3 165
#define PLL4 166
/* ODF */
#define PLL1_P 167
#define PLL1_Q 168
#define PLL1_R 169
#define PLL2_P 170
#define PLL2_Q 171
#define PLL2_R 172
#define PLL3_P 173
#define PLL3_Q 174
#define PLL3_R 175
#define PLL4_P 176
#define PLL4_Q 177
#define PLL4_R 178
/* AUX */
#define RTC 179
/* MCLK */
#define CK_PER 180
#define CK_MPU 181
#define CK_AXI 182
#define CK_MCU 183
/* Time base */
#define TIM2_K 184
#define TIM3_K 185
#define TIM4_K 186
#define TIM5_K 187
#define TIM6_K 188
#define TIM7_K 189
#define TIM12_K 190
#define TIM13_K 191
#define TIM14_K 192
#define TIM1_K 193
#define TIM8_K 194
#define TIM15_K 195
#define TIM16_K 196
#define TIM17_K 197
/* MCO clocks */
#define CK_MCO1 198
#define CK_MCO2 199
/* TRACE & DEBUG clocks */
#define DBG 200
#define CK_DBG 201
#define CK_TRACE 202
/* DDR */
#define DDRC1 203
#define DDRC1LP 204
#define DDRC2 205
#define DDRC2LP 206
#define DDRPHYC 207
#define DDRPHYCLP 208
#define DDRCAPB 209
#define DDRCAPBLP 210
#define AXIDCG 211
#define DDRPHYCAPB 212
#define DDRPHYCAPBLP 213
#define DDRPERFM 214
#define STM32MP1_LAST_CLK 215
| 17.67623 | 79 | 0.764665 |
8ba38f30a8eb8a8e5435ccf98478117959486edd | 611 | h | C | Q-municate/Scenes/Base/QMTableViewCell/QMTableViewCell.h | GoodyIT/social-app-iOS | 1484feea3e2ebabe88feefe418d8ef49ea9dce76 | [
"Apache-2.0"
] | 2 | 2017-11-05T01:28:54.000Z | 2019-10-17T09:56:46.000Z | Q-municate/Scenes/Base/QMTableViewCell/QMTableViewCell.h | GoodyIT/social-app-iOS | 1484feea3e2ebabe88feefe418d8ef49ea9dce76 | [
"Apache-2.0"
] | null | null | null | Q-municate/Scenes/Base/QMTableViewCell/QMTableViewCell.h | GoodyIT/social-app-iOS | 1484feea3e2ebabe88feefe418d8ef49ea9dce76 | [
"Apache-2.0"
] | 1 | 2019-08-05T19:45:06.000Z | 2019-08-05T19:45:06.000Z | //
// QMTableViewCell.h
// Q-municate
//
// Created by Andrey Ivanov on 23.03.15.
// Copyright (c) 2015 Quickblox. All rights reserved.
//
#import <UIKit/UIKit.h>
#import <QMImageView.h>
@interface QMTableViewCell : UITableViewCell
@property (weak, nonatomic) IBOutlet QMImageView *avatarImage;
+ (void)registerForReuseInTableView:(UITableView *)tableView;
+ (NSString *)cellIdentifier;
+ (CGFloat)height;
- (void)setTitle:(NSString *)title
placeholderID:(NSUInteger)placeholderID
avatarUrl:(NSString *)avatarUrl;
- (void)setTitle:(NSString *)title;
- (void)setBody:(NSString *)body;
@end
| 21.068966 | 62 | 0.725041 |
e9682822785b79cf567d04fd93bd50100d84fe7e | 2,619 | h | C | chrome/browser/ui/webui/signin/dice_turn_sync_on_helper_delegate_impl.h | Ron423c/chromium | 2edf7b980065b648f8b2a6e52193d83832fe36b7 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 575 | 2015-06-18T23:58:20.000Z | 2022-03-23T09:32:39.000Z | chrome/browser/ui/webui/signin/dice_turn_sync_on_helper_delegate_impl.h | Ron423c/chromium | 2edf7b980065b648f8b2a6e52193d83832fe36b7 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 113 | 2015-05-04T09:58:14.000Z | 2022-01-31T19:35:03.000Z | chrome/browser/ui/webui/signin/dice_turn_sync_on_helper_delegate_impl.h | DamieFC/chromium | 54ce2d3c77723697efd22cfdb02aea38f9dfa25c | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 52 | 2015-07-14T10:40:50.000Z | 2022-03-15T01:11:49.000Z | // Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef CHROME_BROWSER_UI_WEBUI_SIGNIN_DICE_TURN_SYNC_ON_HELPER_DELEGATE_IMPL_H_
#define CHROME_BROWSER_UI_WEBUI_SIGNIN_DICE_TURN_SYNC_ON_HELPER_DELEGATE_IMPL_H_
#include "base/callback_forward.h"
#include "base/macros.h"
#include "base/scoped_observation.h"
#include "chrome/browser/ui/browser_list_observer.h"
#include "chrome/browser/ui/sync/profile_signin_confirmation_helper.h"
#include "chrome/browser/ui/webui/signin/dice_turn_sync_on_helper.h"
#include "chrome/browser/ui/webui/signin/login_ui_service.h"
class Browser;
class Profile;
class SigninUIError;
// Default implementation for DiceTurnSyncOnHelper::Delegate.
class DiceTurnSyncOnHelperDelegateImpl : public DiceTurnSyncOnHelper::Delegate,
public BrowserListObserver,
public LoginUIService::Observer {
public:
explicit DiceTurnSyncOnHelperDelegateImpl(Browser* browser);
~DiceTurnSyncOnHelperDelegateImpl() override;
private:
// DiceTurnSyncOnHelper::Delegate:
void ShowLoginError(const SigninUIError& error) override;
void ShowMergeSyncDataConfirmation(
const std::string& previous_email,
const std::string& new_email,
DiceTurnSyncOnHelper::SigninChoiceCallback callback) override;
void ShowEnterpriseAccountConfirmation(
const std::string& email,
DiceTurnSyncOnHelper::SigninChoiceCallback callback) override;
void ShowSyncConfirmation(
base::OnceCallback<void(LoginUIService::SyncConfirmationUIClosedResult)>
callback) override;
void ShowSyncDisabledConfirmation(
bool is_managed_account,
base::OnceCallback<void(LoginUIService::SyncConfirmationUIClosedResult)>
callback) override;
void ShowSyncSettings() override;
void SwitchToProfile(Profile* new_profile) override;
// LoginUIService::Observer:
void OnSyncConfirmationUIClosed(
LoginUIService::SyncConfirmationUIClosedResult result) override;
// BrowserListObserver:
void OnBrowserRemoved(Browser* browser) override;
Browser* browser_;
Profile* profile_;
base::OnceCallback<void(LoginUIService::SyncConfirmationUIClosedResult)>
sync_confirmation_callback_;
base::ScopedObservation<LoginUIService, LoginUIService::Observer>
scoped_login_ui_service_observation_{this};
DISALLOW_COPY_AND_ASSIGN(DiceTurnSyncOnHelperDelegateImpl);
};
#endif // CHROME_BROWSER_UI_WEBUI_SIGNIN_DICE_TURN_SYNC_ON_HELPER_DELEGATE_IMPL_H_
| 39.681818 | 83 | 0.785414 |
b1ce070d0966d519719dc35a9d77ff802714d6b7 | 329 | h | C | nexusapp/nexusapp/DocNoteEditorViewController.h | nexuspad/NexusApp | 9123f10402287a4073a167f471d9352f37bda2ab | [
"MIT"
] | 1 | 2015-08-06T11:45:20.000Z | 2015-08-06T11:45:20.000Z | nexusapp/nexusapp/DocNoteEditorViewController.h | nexuspad/NexusApp | 9123f10402287a4073a167f471d9352f37bda2ab | [
"MIT"
] | null | null | null | nexusapp/nexusapp/DocNoteEditorViewController.h | nexuspad/NexusApp | 9123f10402287a4073a167f471d9352f37bda2ab | [
"MIT"
] | null | null | null | //
// DocNoteEditorViewController.h
// nexusapp
//
// Created by Ren Liu on 8/15/13.
//
//
#import "EntryEditorViewController.h"
#import "NPDoc.h"
@interface DocNoteEditorViewController : EntryEditorViewController <UIPopoverControllerDelegate>
@property (nonatomic, strong) NPDoc *doc;
- (IBAction)saveDoc:(id)sender;
@end
| 19.352941 | 96 | 0.75076 |
751ef9d22832c51765edca5daa117fe480e2add3 | 732 | h | C | src/lib/nhcss/Interfaces/StyleSheet.h | netzhautproject/Netzhaut | a80cf764f768a4af79663ca851b23928f0375023 | [
"MIT"
] | 11 | 2021-04-19T14:48:09.000Z | 2022-03-11T18:52:06.000Z | src/lib/nhcss/Interfaces/StyleSheet.h | netzhautproject/netzhaut | a80cf764f768a4af79663ca851b23928f0375023 | [
"MIT"
] | 1 | 2022-03-10T00:01:29.000Z | 2022-03-10T00:08:28.000Z | src/lib/nhcss/Interfaces/StyleSheet.h | netzhautproject/netzhaut | a80cf764f768a4af79663ca851b23928f0375023 | [
"MIT"
] | 3 | 2021-09-20T10:28:20.000Z | 2021-12-26T19:48:00.000Z | #ifndef NH_CSS_STYLE_SHEET_H
#define NH_CSS_STYLE_SHEET_H
#ifndef DOXYGEN_SHOULD_SKIP_THIS
/**
* netzhaut - Web Browser Engine
* Copyright (C) 2020 The netzhaut Authors
* Published under MIT
*/
#include "../Common/Private.h"
#endif
/** @addtogroup lib_nhcss_functions
* @{
*/
nh_css_StyleSheetObject *nh_css_getStyleSheet(
nh_webidl_Object *Object_p
);
nh_css_RuleListObject *nh_css_getRuleList(
nh_css_StyleSheetObject *StyleSheet_p
);
void nh_css_setStyleSheetTokens(
nh_css_StyleSheetObject *StyleSheet_p, nh_Array Tokens
);
nh_webidl_Object *nh_css_findCounterStyleRule(
nh_css_StyleSheetObject *StyleSheet_p, NH_BYTE *name_p
);
/** @} */
#endif
| 18.769231 | 62 | 0.718579 |
0de07ea442ac5efd52fed3448b2cd456ac897c6d | 56 | h | C | Arduino files/ReflowOvenController/WebServer.h | hjf/ReflowOven | 3b6b51d68b942abfb547d18db6da71d8c339375b | [
"MIT"
] | 1 | 2021-07-21T02:02:59.000Z | 2021-07-21T02:02:59.000Z | Arduino files/ReflowOvenController/WebServer.h | hjf/ReflowOven | 3b6b51d68b942abfb547d18db6da71d8c339375b | [
"MIT"
] | null | null | null | Arduino files/ReflowOvenController/WebServer.h | hjf/ReflowOven | 3b6b51d68b942abfb547d18db6da71d8c339375b | [
"MIT"
] | 1 | 2021-02-19T15:31:27.000Z | 2021-02-19T15:31:27.000Z | void webserver_init(void);
void webserver_handle(void);
| 18.666667 | 28 | 0.821429 |
d4c9da5777e58b9a85b78760ddd6ae7d89693a49 | 1,194 | c | C | srcs/ft_memcmp.c | Wildos/libft | 6797edddb3f23d7ba5b1203e170e167e80e38003 | [
"MIT"
] | null | null | null | srcs/ft_memcmp.c | Wildos/libft | 6797edddb3f23d7ba5b1203e170e167e80e38003 | [
"MIT"
] | null | null | null | srcs/ft_memcmp.c | Wildos/libft | 6797edddb3f23d7ba5b1203e170e167e80e38003 | [
"MIT"
] | null | null | null | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_memcmp.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: tfernand <tfernand@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2018/04/11 17:29:10 by tfernand #+# #+# */
/* Updated: 2018/04/11 17:29:10 by tfernand ### ########.fr */
/* */
/* ************************************************************************** */
#include <string.h>
int ft_memcmp(const void *s1, const void *s2, size_t n)
{
unsigned char *ptr1;
unsigned char *ptr2;
ptr1 = (unsigned char *)s1;
ptr2 = (unsigned char *)s2;
while (n > 0)
{
if (*ptr1 != *ptr2)
return ((int)(*ptr1 - *ptr2));
n--;
ptr1++;
ptr2++;
}
return (0);
}
| 37.3125 | 80 | 0.231156 |
1db1754830a3f485fcc9a0796397c0bae44e8fa3 | 1,260 | h | C | AliPayForDebug/AliPayForDebug/AlipayWallet_Headers/ASAutoTaskManager.h | ceekay1991/AliPayForDebug | 5795e5db31e5b649d4758469b752585e63e84d94 | [
"MIT"
] | 5 | 2020-03-29T12:08:37.000Z | 2021-05-26T05:20:11.000Z | AliPayForDebug/AliPayForDebug/AlipayWallet_Headers/ASAutoTaskManager.h | ceekay1991/AliPayForDebug | 5795e5db31e5b649d4758469b752585e63e84d94 | [
"MIT"
] | null | null | null | AliPayForDebug/AliPayForDebug/AlipayWallet_Headers/ASAutoTaskManager.h | ceekay1991/AliPayForDebug | 5795e5db31e5b649d4758469b752585e63e84d94 | [
"MIT"
] | 5 | 2020-04-17T03:24:04.000Z | 2022-03-30T05:42:17.000Z | //
// Generated by class-dump 3.5 (64 bit) (Debug version compiled Sep 17 2017 16:24:48).
//
// class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2015 by Steve Nygard.
//
#import <objc/NSObject.h>
@class NSDictionary, NSMutableDictionary;
@protocol ASAutoTaskManagerDelegate;
@interface ASAutoTaskManager : NSObject
{
id <ASAutoTaskManagerDelegate> _delegate;
NSMutableDictionary *_taskList;
NSDictionary *_autoTaskDic;
NSDictionary *_behviorTaskDic;
long long _usabilityTaskNum;
}
@property(nonatomic) long long usabilityTaskNum; // @synthesize usabilityTaskNum=_usabilityTaskNum;
@property(retain, nonatomic) NSDictionary *behviorTaskDic; // @synthesize behviorTaskDic=_behviorTaskDic;
@property(retain, nonatomic) NSDictionary *autoTaskDic; // @synthesize autoTaskDic=_autoTaskDic;
@property(retain, nonatomic) NSMutableDictionary *taskList; // @synthesize taskList=_taskList;
@property(nonatomic) __weak id <ASAutoTaskManagerDelegate> delegate; // @synthesize delegate=_delegate;
- (void).cxx_destruct;
- (void)taskMangerDeletTask:(id)arg1;
- (id)getCurrentTask:(id)arg1 homePage:(id)arg2 withInfoDic:(id)arg3;
- (void)addTaskWithHomeName:(id)arg1 andHomeViewController:(id)arg2 andInfoDic:(id)arg3;
- (id)init;
@end
| 37.058824 | 105 | 0.773016 |
8a7babd06e5198cc23fbc45e0754d579dcf91039 | 335 | h | C | src/GHWP/GHWPSoundLoader.h | GoldenHammerSoftware/GH | 757213f479c0fc80ed1a0f59972bf3e9d92b7526 | [
"MIT"
] | null | null | null | src/GHWP/GHWPSoundLoader.h | GoldenHammerSoftware/GH | 757213f479c0fc80ed1a0f59972bf3e9d92b7526 | [
"MIT"
] | null | null | null | src/GHWP/GHWPSoundLoader.h | GoldenHammerSoftware/GH | 757213f479c0fc80ed1a0f59972bf3e9d92b7526 | [
"MIT"
] | null | null | null | // Copyright 2010 Golden Hammer Software
#pragma once
#include "GHResourceLoader.h"
class GHFileOpener;
class GHWPSoundLoader : public GHResourceLoader
{
public:
GHWPSoundLoader(GHFileOpener& fileOpener);
virtual GHResource* loadFile(const char* filename, GHPropertyContainer* extraData);
private:
GHFileOpener& mFileOpener;
}; | 19.705882 | 84 | 0.802985 |
e1cb203dbb887e63c7a570a5d330726345081b0a | 7,006 | c | C | v4-cokapi/backends/c_cpp/valgrind-3.11.0/none/tests/s390x/clcl.c | ambadhan/OnlinePythonTutor | 857bab941fbde20f1f020b05b7723094ddead62a | [
"MIT"
] | 17 | 2021-12-09T11:31:44.000Z | 2021-12-29T03:07:14.000Z | v4-cokapi/backends/c_cpp/valgrind-3.11.0/none/tests/s390x/clcl.c | heysachin/OnlinePythonTutor | 0dcdacc7ff5be504dd6a47236ebc69dc0069f991 | [
"MIT"
] | 8 | 2020-02-04T20:23:26.000Z | 2020-02-17T00:23:37.000Z | v4-cokapi/backends/c_cpp/valgrind-3.11.0/none/tests/s390x/clcl.c | heysachin/OnlinePythonTutor | 0dcdacc7ff5be504dd6a47236ebc69dc0069f991 | [
"MIT"
] | 12 | 2021-12-09T11:31:46.000Z | 2022-01-07T03:14:46.000Z | #include <stdio.h>
#include <stdint.h>
#include <inttypes.h>
#include <assert.h>
/* The golden logs were obtained by running this test natively. */
/* The abstracted result of a CLCL insn */
typedef struct {
uint64_t addr1;
uint32_t len1;
uint64_t addr2;
uint32_t len2;
uint8_t pad;
uint32_t cc;
} clcl_t;
/* Register contents after CLCL insn */
typedef struct {
uint64_t r1;
uint64_t r1p1;
uint64_t r2;
uint64_t r2p1;
uint64_t cc;
} clcl_regs;
/* Run a single CLCL insn and return its raw result. */
static clcl_regs
do_clcl(uint64_t r1, uint64_t r1p1, uint64_t r2, uint64_t r2p1)
{
clcl_regs regs;
register uint64_t a1 asm ("2") = r1;
register uint64_t l1 asm ("3") = r1p1;
register uint64_t a2 asm ("4") = r2;
register uint64_t l2 asm ("5") = r2p1;
register uint32_t cc asm ("7");
asm volatile( "0: clcl 2,4\n\t"
"jo 0b\n\t"
"ipm %0\n\t"
"srl %0,28\n\t"
:"=d" (cc), "+d" (a1),"+d" (l1), "+d" (a2), "+d" (l2)
: : "memory", "cc");
regs.r1 = a1;
regs.r1p1 = l1;
regs.r2 = a2;
regs.r2p1 = l2;
regs.cc = cc;
return regs;
}
clcl_t
result_from_regs(clcl_regs regs)
{
clcl_t result;
result.addr1 = regs.r1;
result.len1 = regs.r1p1 & 0xFFFFFF;
result.addr2 = regs.r2;
result.len2 = regs.r2p1 & 0xFFFFFF;
result.pad = (regs.r2p1 & 0xFF000000u) >> 24;
result.cc = regs.cc;
return result;
}
/* Run CLCL twice using different fill bits for unused register bits.
Results ought to be the same */
static clcl_t
clcl(void *addr1, uint32_t len1,
void *addr2, uint32_t len2, uint32_t pad)
{
clcl_t result1, result2;
clcl_regs regs;
uint64_t r1, r1p1, r2, r2p1;
/* Check input arguments */
assert((pad & 0xFF) == pad); /* an 8-byte value */
assert((len1 & 0xFFFFFF) == len1);
assert((len2 & 0xFFFFFF) == len2);
/* Build up register contents setting unused bits to 0 */
r1 = (uint64_t)addr1;
r1p1 = len1;
r2 = (uint64_t)addr2;
r2p1 = len2 | (pad << 24);
/* Run clcl */
regs = do_clcl(r1, r1p1, r2, r2p1);
result1 = result_from_regs(regs);
/* Check unused bits */
if ((regs.r1p1 >> 24) != 0)
printf("FAIL: r1[0:39] modified (unused bits 0)\n");
if ((regs.r2p1 >> 32) != 0)
printf("FAIL: r2[0:31] modified (unused bits 0)\n");
/* Check pad value */
if (result1.pad != pad)
printf("FAIL: pad byte modified (unused bits 0)\n");
/* Build up register contents setting unused bits to 1 */
r1p1 |= 0xFFFFFFFFFFull << 24;
r2p1 |= ((uint64_t)0xFFFFFFFF) << 32;
/* Run clcl again */
regs = do_clcl(r1, r1p1, r2, r2p1);
result2 = result_from_regs(regs);
/* Check unused bits */
if ((regs.r1p1 >> 24) != 0xFFFFFFFFFFull)
printf("FAIL: r1[0:39] modified (unused bits 1)\n");
if ((regs.r2p1 >> 32) != 0xFFFFFFFFu)
printf("FAIL: r2[0:31] modified (unused bits 1)\n");
/* Check pad value */
if (result2.pad != pad)
printf("FAIL: pad byte modified (unused bits 1)\n");
/* Compare results */
if (result1.addr1 != result2.addr1)
printf("FAIL: addr1 result is different\n");
if (result1.addr2 != result2.addr2)
printf("FAIL: addr2 result is different\n");
if (result1.len1 != result2.len1)
printf("FAIL: len1 result is different\n");
if (result1.len2 != result2.len2)
printf("FAIL: len2 result is different\n");
if (result1.pad != result2.pad)
printf("FAIL: pad result is different\n");
if (result1.cc != result2.cc)
printf("FAIL: cc result is different\n");
return result1;
}
void
run_test(void *addr1, uint32_t len1, void *addr2, uint32_t len2, uint32_t pad)
{
clcl_t result;
result = clcl(addr1, len1, addr2, len2, pad);
printf("cc: %"PRIu32", len1: %"PRIu32", len2: %"PRIu32
", addr1 diff: %"PRId64", addr2 diff: %"PRId64"\n", result.cc,
result.len1, result.len2, (int64_t)result.addr1 - (int64_t)addr1,
(int64_t)result.addr2 - (int64_t)addr2);
}
int main()
{
uint8_t byte, byte1, byte2;
/* Test 1: both lengths are 0; nothing loaded from memory */
printf("--- test 1 ---\n");
run_test(NULL, 0, NULL, 0, 0x00);
run_test(NULL, 0, NULL, 0, 0xff);
/* Test 2: Compare two single bytes */
printf("--- test 2 ---\n");
byte1 = 10;
byte2 = 20;
run_test(&byte1, 1, &byte2, 1, 0x00); // first operand low
run_test(&byte1, 1, &byte1, 1, 0x00); // equal
run_test(&byte2, 1, &byte1, 1, 0x00); // first operand high
run_test(&byte1, 1, &byte2, 1, 0xFF); // first operand low
run_test(&byte1, 1, &byte1, 1, 0xFF); // equal
run_test(&byte2, 1, &byte1, 1, 0xFF); // first operand high
/* Test 3: Compare a single byte against the pad byte */
printf("--- test 3 ---\n");
byte = 10;
run_test(NULL, 0, &byte, 1, 10); // equal
run_test(NULL, 0, &byte, 1, 9); // first operand low
run_test(NULL, 0, &byte, 1, 11); // first operand high
/* Swap operands */
run_test(&byte, 1, NULL, 0, 10); // equal
run_test(&byte, 1, NULL, 0, 9); // first operand high
run_test(&byte, 1, NULL, 0, 11); // first operand low
/* Test 4: Make sure pad byte is interpreted as unsigned value */
printf("--- test 4 ---\n");
byte = 10;
run_test(&byte, 1, NULL, 0, 0xFF); // first operand low
byte = 0xFF;
run_test(&byte, 1, NULL, 0, 0xFF); // equal
/* Test 5: Compare a buffer against the pad byte */
printf("--- test 5 ---\n");
uint8_t buf1[4] = "yyyy";
run_test(buf1, 4, NULL, 0, 'y'); // equal
run_test(buf1, 4, NULL, 0, 'x'); // greater
run_test(buf1, 4, NULL, 0, 'z'); // less
/* Test 6: Compare two buffers of same size (difference in 1st byte) */
{
printf("--- test 6 ---\n");
uint8_t x[5] = "pqrst";
uint8_t y[5] = "abcde";
uint8_t z[5] = "abcde";
run_test(x, 5, y, 5, 'a'); // first operand low
run_test(y, 5, x, 5, 'a'); // first operand high
run_test(y, 5, z, 5, 'q'); // equal
}
/* Test 7: Compare two buffers of same size (difference in last byte) */
{
printf("--- test 7 ---\n");
uint8_t x[5] = "abcdd";
uint8_t y[5] = "abcde";
uint8_t z[5] = "abcdf";
run_test(x, 5, y, 5, 'a'); // first operand low
run_test(z, 5, z, 5, 'a'); // first operand high
}
/* Test 8: Compare two buffers of different size. The difference
is past the end of the shorter string. */
{
printf("--- test 8 ---\n");
uint8_t x[5] = "abcde";
uint8_t y[7] = "abcdeff";
run_test(x, 5, y, 7, 0); // first operand low
run_test(y, 7, x, 5, 0); // first operand high
run_test(x, 5, y, 7, 'f'); // equal
run_test(y, 7, x, 5, 'f'); // equal
}
/* Test 9: Compare two buffers of different size. The difference
is before the end of the shorter string. */
{
printf("--- test 9 ---\n");
uint8_t x[5] = "abcab";
uint8_t y[7] = "abcdeff";
run_test(x, 5, y, 7, 0); // first operand low
run_test(y, 7, x, 5, 0); // first operand high
run_test(x, 5, y, 7, 'f'); // first operand low
run_test(y, 7, x, 5, 'f'); // first operand high
}
return 0;
}
| 28.595918 | 78 | 0.599343 |
c08e130c6d8bd1cbdd6392338ad0eb216427b2bb | 3,574 | h | C | src/test/function_test/utils.h | empiredan/pegasus | a095172ad1559cc0e65c7807a2baedc607cde50c | [
"Apache-2.0"
] | 1,352 | 2017-10-16T03:24:54.000Z | 2020-08-18T04:44:23.000Z | src/test/function_test/utils.h | empiredan/pegasus | a095172ad1559cc0e65c7807a2baedc607cde50c | [
"Apache-2.0"
] | 299 | 2017-10-19T05:33:32.000Z | 2020-08-17T09:03:39.000Z | src/test/function_test/utils.h | empiredan/pegasus | a095172ad1559cc0e65c7807a2baedc607cde50c | [
"Apache-2.0"
] | 240 | 2017-10-16T05:57:04.000Z | 2020-08-18T10:02:36.000Z | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
#pragma once
#include <dsn/utility/rand.h>
#include <dsn/c/api_utilities.h>
#include <dsn/dist/fmt_logging.h>
#define RETRY_OPERATION(CLIENT_FUNCTION, RESULT) \
do { \
for (int i = 0; i < 60; ++i) { \
RESULT = CLIENT_FUNCTION; \
if (RESULT == 0) { \
break; \
} else { \
std::this_thread::sleep_for(std::chrono::milliseconds(500)); \
} \
} \
} while (0)
inline std::string generate_random_string(uint32_t str_len = 20)
{
static const std::string chars("abcdefghijklmnopqrstuvwxyz"
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"1234567890");
std::string result;
for (int i = 0; i < str_len; i++) {
result += chars[dsn::rand::next_u32(chars.size())];
}
return result;
}
inline std::string generate_hotkey(bool is_hotkey, int probability = 100, uint32_t str_len = 20)
{
if (is_hotkey && (dsn::rand::next_u32(100) < probability)) {
return "ThisisahotkeyThisisahotkey";
}
return generate_random_string(str_len);
}
inline std::vector<std::string> generate_str_vector_by_random(uint32_t single_str_len,
uint32_t arr_len,
bool random_value_size = false)
{
std::vector<std::string> result;
result.reserve(arr_len);
for (int i = 0; i < arr_len; i++) {
result.emplace_back(generate_random_string(
random_value_size ? dsn::rand::next_u32(single_str_len) : single_str_len));
}
return result;
}
inline std::map<std::string, std::string>
generate_sortkey_value_map(const std::vector<std::string> sortkeys,
const std::vector<std::string> values)
{
std::map<std::string, std::string> result;
dcheck_eq(sortkeys.size(), values.size());
int len = sortkeys.size();
for (int i = 0; i < len; i++) {
result.emplace(std::make_pair(sortkeys[i], values[i]));
}
return result;
}
| 43.060241 | 100 | 0.501399 |
0e1cc8f2d617872ebed1a48890dbd3889b0ccc69 | 6,022 | h | C | src/media/codec/codecs/sw/aac/codec_adapter_aac_encoder.h | opensource-assist/fuschia | 66646c55b3d0b36aae90a4b6706b87f1a6261935 | [
"BSD-3-Clause"
] | 3 | 2020-08-02T04:46:18.000Z | 2020-08-07T10:10:53.000Z | src/media/codec/codecs/sw/aac/codec_adapter_aac_encoder.h | opensource-assist/fuschia | 66646c55b3d0b36aae90a4b6706b87f1a6261935 | [
"BSD-3-Clause"
] | null | null | null | src/media/codec/codecs/sw/aac/codec_adapter_aac_encoder.h | opensource-assist/fuschia | 66646c55b3d0b36aae90a4b6706b87f1a6261935 | [
"BSD-3-Clause"
] | 1 | 2020-08-07T10:11:49.000Z | 2020-08-07T10:11:49.000Z | // Copyright 2019 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef SRC_MEDIA_CODEC_CODECS_SW_AAC_CODEC_ADAPTER_AAC_ENCODER_H_
#define SRC_MEDIA_CODEC_CODECS_SW_AAC_CODEC_ADAPTER_AAC_ENCODER_H_
#include <lib/async-loop/cpp/loop.h>
#include <lib/async-loop/default.h>
#include <lib/fit/result.h>
#include <lib/media/codec_impl/codec_adapter.h>
#include <lib/zx/bti.h>
#include <atomic>
#include <variant>
#include <third_party/android/platform/external/aac/libAACenc/include/aacenc_lib.h>
#include "chunk_input_stream.h"
#include "output_sink.h"
#include "src/lib/fxl/macros.h"
#include "src/lib/fxl/synchronization/thread_annotations.h"
class CodecAdapterAacEncoder : public CodecAdapter {
public:
explicit CodecAdapterAacEncoder(std::mutex& lock, CodecAdapterEvents* codec_adapter_events);
~CodecAdapterAacEncoder();
bool IsCoreCodecRequiringOutputConfigForFormatDetection() override;
bool IsCoreCodecMappedBufferUseful(CodecPort port) override;
bool IsCoreCodecHwBased() override;
void CoreCodecInit(const fuchsia::media::FormatDetails& initial_input_format_details) override;
void CoreCodecStartStream() override;
void CoreCodecStopStream() override;
void CoreCodecQueueInputFormatDetails(
const fuchsia::media::FormatDetails& per_stream_override_format_details) override;
void CoreCodecQueueInputPacket(CodecPacket* packet) override;
void CoreCodecQueueInputEndOfStream() override;
void CoreCodecAddBuffer(CodecPort port, const CodecBuffer* buffer) override;
void CoreCodecConfigureBuffers(CodecPort port,
const std::vector<std::unique_ptr<CodecPacket>>& packets) override;
void CoreCodecRecycleOutputPacket(CodecPacket* packet) override;
void CoreCodecEnsureBuffersNotConfigured(CodecPort port) override;
std::unique_ptr<const fuchsia::media::StreamOutputConstraints> CoreCodecBuildNewOutputConstraints(
uint64_t stream_lifetime_ordinal, uint64_t new_output_buffer_constraints_version_ordinal,
bool buffer_constraints_action_required) override;
fuchsia::sysmem::BufferCollectionConstraints CoreCodecGetBufferCollectionConstraints(
CodecPort port, const fuchsia::media::StreamBufferConstraints& stream_buffer_constraints,
const fuchsia::media::StreamBufferPartialSettings& partial_settings) override;
void CoreCodecSetBufferCollectionInfo(
CodecPort port,
const fuchsia::sysmem::BufferCollectionInfo_2& buffer_collection_info) override;
fuchsia::media::StreamOutputFormat CoreCodecGetOutputFormat(
uint64_t stream_lifetime_ordinal,
uint64_t new_output_format_details_version_ordinal) override;
void CoreCodecMidStreamOutputBufferReConfigPrepare() override;
void CoreCodecMidStreamOutputBufferReConfigFinish() override;
private:
using Encoder = std::unique_ptr<AACENCODER, fit::function<void(AACENCODER*)>>;
enum InputError {
kNotAudio,
kNotPcm,
kNot16Bit,
kNotLinear,
kCompressed,
};
enum SettingsError {
kSettingsMissing,
kUnsupportedObjectType,
kUnsupportedChannelMode,
kUnsupportedTransport,
};
using Error = std::variant<AACENC_ERROR, InputError, SettingsError>;
struct FormatConfiguration {
std::vector<uint8_t> oob_bytes;
size_t recommended_output_buffer_size;
};
struct EncodeResult {
size_t bytes_written;
bool is_end_of_stream;
};
// This struct contains data who live the lifetime of a stream.
struct Stream {
Stream(size_t chunk_size, TimestampExtrapolator&& timestamp_extrapolator,
ChunkInputStream::InputBlockProcessor&& input_block_processor, Encoder in_encoder,
uint64_t in_format_details_version_ordinal, size_t in_output_buffer_size)
: encoder(std::move(in_encoder)),
chunk_input_stream(chunk_size, std::move(timestamp_extrapolator),
std::move(input_block_processor)),
format_details_version_ordinal(in_format_details_version_ordinal),
output_buffer_size(in_output_buffer_size) {}
Encoder encoder;
ChunkInputStream chunk_input_stream;
uint64_t format_details_version_ordinal;
size_t output_buffer_size;
};
void ProcessInput(CodecInputItem input_item);
fit::result<void, CodecAdapterAacEncoder::Error> BuildStreamFromFormatDetails(
const fuchsia::media::FormatDetails& format_details);
fit::result<fuchsia::media::PcmFormat, InputError> ValidateInputFormat(
const fuchsia::media::FormatDetails& format_details);
fit::result<Encoder, Error> CreateEncoder(
const fuchsia::media::PcmFormat& pcm_format,
const fuchsia::media::AacEncoderSettings& encoder_settings);
ChunkInputStream::ControlFlow ProcessInputBlock(ChunkInputStream::InputBlock input_block);
fit::result<EncodeResult, AACENC_ERROR> Encode(ChunkInputStream::InputBlock input_block,
OutputSink::OutputBlock output_block);
fit::result<EncodeResult, AACENC_ERROR> Flush(OutputSink::OutputBlock output_block);
fit::result<EncodeResult, AACENC_ERROR> CallEncoder(AACENC_InArgs* in_args,
AACENC_BufDesc* in_buffer,
OutputSink::OutputBlock output_block);
void ReportError(Error error);
void ReportOutputSinkError(OutputSink::Status status);
std::optional<OutputSink> output_sink_;
std::optional<Stream> stream_;
// Should only be changed atomically.
bool stream_active_ FXL_GUARDED_BY(lock_) = false;
std::optional<FormatConfiguration> format_configuration_ FXL_GUARDED_BY(lock_);
// Buffers the user is in the process of adding.
// TODO(turnage): Remove when manual buffer additions are removed in favor
// of sysmem.
MpscQueue<const CodecBuffer*> staged_buffers_;
async::Loop input_processing_loop_;
};
#endif // SRC_MEDIA_CODEC_CODECS_SW_AAC_CODEC_ADAPTER_AAC_ENCODER_H_
| 39.880795 | 100 | 0.766357 |
dbcf31250f804fc9840d933f64f7340327eb71f1 | 129,382 | c | C | vswitchd/bridge.c | nwxufo/ovs_ofamp | 1ed684fda19dac897eba76e83b0f5c020099622c | [
"Apache-2.0"
] | null | null | null | vswitchd/bridge.c | nwxufo/ovs_ofamp | 1ed684fda19dac897eba76e83b0f5c020099622c | [
"Apache-2.0"
] | null | null | null | vswitchd/bridge.c | nwxufo/ovs_ofamp | 1ed684fda19dac897eba76e83b0f5c020099622c | [
"Apache-2.0"
] | null | null | null | /* Copyright (c) 2008, 2009 Nicira Networks
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <config.h>
#include "bridge.h"
#include <assert.h>
#include <errno.h>
#include <arpa/inet.h>
#include <ctype.h>
#include <inttypes.h>
#include <net/if.h>
#include <openflow/openflow.h>
#include <signal.h>
#include <stdlib.h>
#include <strings.h>
#include <sys/stat.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <unistd.h>
#include "bitmap.h"
#include "cfg.h"
#include "coverage.h"
#include "dirs.h"
#include "dpif.h"
#include "dynamic-string.h"
#include "flow.h"
#include "hash.h"
#include "list.h"
#include "mac-learning.h"
#include "netdev.h"
#include "odp-util.h"
#include "ofp-print.h"
#include "ofpbuf.h"
#include "ofproto/netflow.h"
#include "ofproto/ofproto.h"
#include "packets.h"
#include "poll-loop.h"
#include "port-array.h"
#include "proc-net-compat.h"
#include "process.h"
#include "shash.h"
#include "socket-util.h"
#include "stp.h"
#include "svec.h"
#include "timeval.h"
#include "util.h"
#include "unixctl.h"
#include "vconn.h"
#include "vconn-ssl.h"
#include "xenserver.h"
#include "xtoxll.h"
#define THIS_MODULE VLM_bridge
#include "vlog.h"
struct dst {
uint16_t vlan;
uint16_t dp_ifidx;
};
extern uint64_t mgmt_id;
struct iface {
/* These members are always valid. */
struct port *port; /* Containing port. */
size_t port_ifidx; /* Index within containing port. */
char *name; /* Host network device name. */
tag_type tag; /* Tag associated with this interface. */
long long delay_expires; /* Time after which 'enabled' may change. */
/* These members are valid only after bridge_reconfigure() causes them to
* be initialized.*/
int dp_ifidx; /* Index within kernel datapath. */
struct netdev *netdev; /* Network device. */
bool enabled; /* May be chosen for flows? */
};
#define BOND_MASK 0xff
struct bond_entry {
int iface_idx; /* Index of assigned iface, or -1 if none. */
uint64_t tx_bytes; /* Count of bytes recently transmitted. */
tag_type iface_tag; /* Tag associated with iface_idx. */
};
#define MAX_MIRRORS 32
typedef uint32_t mirror_mask_t;
#define MIRROR_MASK_C(X) UINT32_C(X)
BUILD_ASSERT_DECL(sizeof(mirror_mask_t) * CHAR_BIT >= MAX_MIRRORS);
struct mirror {
struct bridge *bridge;
size_t idx;
char *name;
/* Selection criteria. */
struct svec src_ports;
struct svec dst_ports;
int *vlans;
size_t n_vlans;
/* Output. */
struct port *out_port;
int out_vlan;
};
#define FLOOD_PORT ((struct port *) 1) /* The 'flood' output port. */
struct port {
struct bridge *bridge;
size_t port_idx;
int vlan; /* -1=trunk port, else a 12-bit VLAN ID. */
unsigned long *trunks; /* Bitmap of trunked VLANs, if 'vlan' == -1. */
char *name;
/* An ordinary bridge port has 1 interface.
* A bridge port for bonding has at least 2 interfaces. */
struct iface **ifaces;
size_t n_ifaces, allocated_ifaces;
/* Bonding info. */
struct bond_entry *bond_hash; /* An array of (BOND_MASK + 1) elements. */
int active_iface; /* Ifidx on which bcasts accepted, or -1. */
tag_type active_iface_tag; /* Tag for bcast flows. */
tag_type no_ifaces_tag; /* Tag for flows when all ifaces disabled. */
int updelay, downdelay; /* Delay before iface goes up/down, in ms. */
bool bond_compat_is_stale; /* Need to call port_update_bond_compat()? */
/* Port mirroring info. */
mirror_mask_t src_mirrors; /* Mirrors triggered when packet received. */
mirror_mask_t dst_mirrors; /* Mirrors triggered when packet sent. */
bool is_mirror_output_port; /* Does port mirroring send frames here? */
/* Spanning tree info. */
enum stp_state stp_state; /* Always STP_FORWARDING if STP not in use. */
tag_type stp_state_tag; /* Tag for STP state change. */
};
#define DP_MAX_PORTS 255
struct bridge {
struct list node; /* Node in global list of bridges. */
char *name; /* User-specified arbitrary name. */
struct mac_learning *ml; /* MAC learning table. */
bool sent_config_request; /* Successfully sent config request? */
uint8_t default_ea[ETH_ADDR_LEN]; /* Default MAC. */
/* Support for remote controllers. */
char *controller; /* NULL if there is no remote controller;
* "discover" to do controller discovery;
* otherwise a vconn name. */
/* OpenFlow switch processing. */
struct ofproto *ofproto; /* OpenFlow switch. */
/* Kernel datapath information. */
struct dpif *dpif; /* Datapath. */
struct port_array ifaces; /* Indexed by kernel datapath port number. */
/* Bridge ports. */
struct port **ports;
size_t n_ports, allocated_ports;
/* Bonding. */
bool has_bonded_ports;
long long int bond_next_rebalance;
/* Flow tracking. */
bool flush;
/* Flow statistics gathering. */
time_t next_stats_request;
/* Port mirroring. */
struct mirror *mirrors[MAX_MIRRORS];
/* Spanning tree. */
struct stp *stp;
long long int stp_last_tick;
};
/* List of all bridges. */
static struct list all_bridges = LIST_INITIALIZER(&all_bridges);
/* Maximum number of datapaths. */
enum { DP_MAX = 256 };
static struct bridge *bridge_create(const char *name);
static void bridge_destroy(struct bridge *);
static struct bridge *bridge_lookup(const char *name);
static void bridge_unixctl_dump_flows(struct unixctl_conn *, const char *);
static int bridge_run_one(struct bridge *);
static void bridge_reconfigure_one(struct bridge *);
static void bridge_reconfigure_controller(struct bridge *);
static void bridge_get_all_ifaces(const struct bridge *, struct svec *ifaces);
static void bridge_fetch_dp_ifaces(struct bridge *);
static void bridge_flush(struct bridge *);
static void bridge_pick_local_hw_addr(struct bridge *,
uint8_t ea[ETH_ADDR_LEN],
struct iface **hw_addr_iface);
static uint64_t bridge_pick_datapath_id(struct bridge *,
const uint8_t bridge_ea[ETH_ADDR_LEN],
struct iface *hw_addr_iface);
static struct iface *bridge_get_local_iface(struct bridge *);
static uint64_t dpid_from_hash(const void *, size_t nbytes);
static void bridge_unixctl_fdb_show(struct unixctl_conn *, const char *args);
static void bond_init(void);
static void bond_run(struct bridge *);
static void bond_wait(struct bridge *);
static void bond_rebalance_port(struct port *);
static void bond_send_learning_packets(struct port *);
static void bond_enable_slave(struct iface *iface, bool enable);
static void port_create(struct bridge *, const char *name);
static void port_reconfigure(struct port *);
static void port_destroy(struct port *);
static struct port *port_lookup(const struct bridge *, const char *name);
static struct iface *port_lookup_iface(const struct port *, const char *name);
static struct port *port_from_dp_ifidx(const struct bridge *,
uint16_t dp_ifidx);
static void port_update_bond_compat(struct port *);
static void port_update_vlan_compat(struct port *);
static void port_update_bonding(struct port *);
static void mirror_create(struct bridge *, const char *name);
static void mirror_destroy(struct mirror *);
static void mirror_reconfigure(struct bridge *);
static void mirror_reconfigure_one(struct mirror *);
static bool vlan_is_mirrored(const struct mirror *, int vlan);
static void brstp_reconfigure(struct bridge *);
static void brstp_adjust_timers(struct bridge *);
static void brstp_run(struct bridge *);
static void brstp_wait(struct bridge *);
static void iface_create(struct port *, const char *name);
static void iface_destroy(struct iface *);
static struct iface *iface_lookup(const struct bridge *, const char *name);
static struct iface *iface_from_dp_ifidx(const struct bridge *,
uint16_t dp_ifidx);
static bool iface_is_internal(const struct bridge *, const char *name);
static void iface_set_mac(struct iface *);
/* Hooks into ofproto processing. */
static struct ofhooks bridge_ofhooks;
/* Public functions. */
/* Adds the name of each interface used by a bridge, including local and
* internal ports, to 'svec'. */
void
bridge_get_ifaces(struct svec *svec)
{
struct bridge *br, *next;
size_t i, j;
LIST_FOR_EACH_SAFE (br, next, struct bridge, node, &all_bridges) {
for (i = 0; i < br->n_ports; i++) {
struct port *port = br->ports[i];
for (j = 0; j < port->n_ifaces; j++) {
struct iface *iface = port->ifaces[j];
if (iface->dp_ifidx < 0) {
VLOG_ERR("%s interface not in datapath %s, ignoring",
iface->name, dpif_name(br->dpif));
} else {
if (iface->dp_ifidx != ODPP_LOCAL) {
svec_add(svec, iface->name);
}
}
}
}
}
}
/* The caller must already have called cfg_read(). */
void
bridge_init(void)
{
struct svec dpif_names;
size_t i;
unixctl_command_register("fdb/show", bridge_unixctl_fdb_show);
svec_init(&dpif_names);
dp_enumerate(&dpif_names);
for (i = 0; i < dpif_names.n; i++) {
const char *dpif_name = dpif_names.names[i];
struct dpif *dpif;
int retval;
retval = dpif_open(dpif_name, &dpif);
if (!retval) {
struct svec all_names;
size_t j;
svec_init(&all_names);
dpif_get_all_names(dpif, &all_names);
for (j = 0; j < all_names.n; j++) {
if (cfg_has("bridge.%s.port", all_names.names[j])) {
goto found;
}
}
dpif_delete(dpif);
found:
svec_destroy(&all_names);
dpif_close(dpif);
}
}
svec_destroy(&dpif_names);
unixctl_command_register("bridge/dump-flows", bridge_unixctl_dump_flows);
bond_init();
bridge_reconfigure();
}
#ifdef HAVE_OPENSSL
static bool
config_string_change(const char *key, char **valuep)
{
const char *value = cfg_get_string(0, "%s", key);
if (value && (!*valuep || strcmp(value, *valuep))) {
free(*valuep);
*valuep = xstrdup(value);
return true;
} else {
return false;
}
}
static void
bridge_configure_ssl(void)
{
/* XXX SSL should be configurable on a per-bridge basis.
* XXX should be possible to de-configure SSL. */
static char *private_key_file;
static char *certificate_file;
static char *cacert_file;
struct stat s;
if (config_string_change("ssl.private-key", &private_key_file)) {
vconn_ssl_set_private_key_file(private_key_file);
}
if (config_string_change("ssl.certificate", &certificate_file)) {
vconn_ssl_set_certificate_file(certificate_file);
}
/* We assume that even if the filename hasn't changed, if the CA cert
* file has been removed, that we want to move back into
* boot-strapping mode. This opens a small security hole, because
* the old certificate will still be trusted until vSwitch is
* restarted. We may want to address this in vconn's SSL library. */
if (config_string_change("ssl.ca-cert", &cacert_file)
|| (cacert_file && stat(cacert_file, &s) && errno == ENOENT)) {
vconn_ssl_set_ca_cert_file(cacert_file,
cfg_get_bool(0, "ssl.bootstrap-ca-cert"));
}
}
#endif
/* Attempt to create the network device 'iface_name' through the netdev
* library. */
static int
set_up_iface(const char *iface_name, bool create)
{
const char *type;
const char *arg;
struct svec arg_svec;
struct shash args;
int error;
size_t i;
/* If a type is not explicitly declared, then assume it's an existing
* "system" device. */
type = cfg_get_string(0, "iface.%s.type", iface_name);
if (!type || !strcmp(type, "system")) {
return 0;
}
svec_init(&arg_svec);
cfg_get_subsections(&arg_svec, "iface.%s.args", iface_name);
shash_init(&args);
SVEC_FOR_EACH (i, arg, &arg_svec) {
const char *value;
value = cfg_get_string(0, "iface.%s.args.%s", iface_name, arg);
if (value) {
shash_add(&args, arg, xstrdup(value));
}
}
if (create) {
error = netdev_create(iface_name, type, &args);
} else {
/* xxx Check to make sure that the type hasn't changed. */
error = netdev_reconfigure(iface_name, &args);
}
svec_destroy(&arg_svec);
shash_destroy(&args);
return error;
}
static int
create_iface(const char *iface_name)
{
return set_up_iface(iface_name, true);
}
static int
reconfigure_iface(const char *iface_name)
{
return set_up_iface(iface_name, false);
}
static void
destroy_iface(const char *iface_name)
{
netdev_destroy(iface_name);
}
/* iterate_and_prune_ifaces() callback function that opens the network device
* for 'iface', if it is not already open, and retrieves the interface's MAC
* address and carrier status. */
static bool
init_iface_netdev(struct bridge *br UNUSED, struct iface *iface,
void *aux UNUSED)
{
if (iface->netdev) {
return true;
} else if (!netdev_open(iface->name, NETDEV_ETH_TYPE_NONE,
&iface->netdev)) {
netdev_get_carrier(iface->netdev, &iface->enabled);
return true;
} else {
/* If the network device can't be opened, then we're not going to try
* to do anything with this interface. */
return false;
}
}
static bool
check_iface_dp_ifidx(struct bridge *br, struct iface *iface, void *aux UNUSED)
{
if (iface->dp_ifidx >= 0) {
VLOG_DBG("%s has interface %s on port %d",
dpif_name(br->dpif),
iface->name, iface->dp_ifidx);
return true;
} else {
VLOG_ERR("%s interface not in %s, dropping",
iface->name, dpif_name(br->dpif));
return false;
}
}
static bool
set_iface_properties(struct bridge *br UNUSED, struct iface *iface,
void *aux UNUSED)
{
int rate, burst;
/* Set policing attributes. */
rate = cfg_get_int(0, "port.%s.ingress.policing-rate", iface->name);
burst = cfg_get_int(0, "port.%s.ingress.policing-burst", iface->name);
netdev_set_policing(iface->netdev, rate, burst);
/* Set MAC address of internal interfaces other than the local
* interface. */
if (iface->dp_ifidx != ODPP_LOCAL
&& iface_is_internal(br, iface->name)) {
iface_set_mac(iface);
}
return true;
}
/* Calls 'cb' for each interfaces in 'br', passing along the 'aux' argument.
* Deletes from 'br' all the interfaces for which 'cb' returns false, and then
* deletes from 'br' any ports that no longer have any interfaces. */
static void
iterate_and_prune_ifaces(struct bridge *br,
bool (*cb)(struct bridge *, struct iface *,
void *aux),
void *aux)
{
size_t i, j;
for (i = 0; i < br->n_ports; ) {
struct port *port = br->ports[i];
for (j = 0; j < port->n_ifaces; ) {
struct iface *iface = port->ifaces[j];
if (cb(br, iface, aux)) {
j++;
} else {
iface_destroy(iface);
}
}
if (port->n_ifaces) {
i++;
} else {
VLOG_ERR("%s port has no interfaces, dropping", port->name);
port_destroy(port);
}
}
}
void
bridge_reconfigure(void)
{
struct svec old_br, new_br;
struct bridge *br, *next;
size_t i;
COVERAGE_INC(bridge_reconfigure);
/* Collect old and new bridges. */
svec_init(&old_br);
svec_init(&new_br);
LIST_FOR_EACH (br, struct bridge, node, &all_bridges) {
svec_add(&old_br, br->name);
}
cfg_get_subsections(&new_br, "bridge");
/* Get rid of deleted bridges and add new bridges. */
svec_sort(&old_br);
svec_sort(&new_br);
assert(svec_is_unique(&old_br));
assert(svec_is_unique(&new_br));
LIST_FOR_EACH_SAFE (br, next, struct bridge, node, &all_bridges) {
if (!svec_contains(&new_br, br->name)) {
bridge_destroy(br);
}
}
for (i = 0; i < new_br.n; i++) {
const char *name = new_br.names[i];
if (!svec_contains(&old_br, name)) {
bridge_create(name);
}
}
svec_destroy(&old_br);
svec_destroy(&new_br);
#ifdef HAVE_OPENSSL
/* Configure SSL. */
bridge_configure_ssl();
#endif
/* Reconfigure all bridges. */
LIST_FOR_EACH (br, struct bridge, node, &all_bridges) {
bridge_reconfigure_one(br);
}
/* Add and delete ports on all datapaths.
*
* The kernel will reject any attempt to add a given port to a datapath if
* that port already belongs to a different datapath, so we must do all
* port deletions before any port additions. */
LIST_FOR_EACH (br, struct bridge, node, &all_bridges) {
struct odp_port *dpif_ports;
size_t n_dpif_ports;
struct svec want_ifaces;
dpif_port_list(br->dpif, &dpif_ports, &n_dpif_ports);
bridge_get_all_ifaces(br, &want_ifaces);
for (i = 0; i < n_dpif_ports; i++) {
const struct odp_port *p = &dpif_ports[i];
if (!svec_contains(&want_ifaces, p->devname)
&& strcmp(p->devname, br->name)) {
int retval = dpif_port_del(br->dpif, p->port);
if (retval) {
VLOG_ERR("failed to remove %s interface from %s: %s",
p->devname, dpif_name(br->dpif),
strerror(retval));
}
destroy_iface(p->devname);
}
}
svec_destroy(&want_ifaces);
free(dpif_ports);
}
LIST_FOR_EACH (br, struct bridge, node, &all_bridges) {
struct odp_port *dpif_ports;
size_t n_dpif_ports;
struct svec cur_ifaces, want_ifaces, add_ifaces;
dpif_port_list(br->dpif, &dpif_ports, &n_dpif_ports);
svec_init(&cur_ifaces);
for (i = 0; i < n_dpif_ports; i++) {
svec_add(&cur_ifaces, dpif_ports[i].devname);
}
free(dpif_ports);
svec_sort_unique(&cur_ifaces);
bridge_get_all_ifaces(br, &want_ifaces);
svec_diff(&want_ifaces, &cur_ifaces, &add_ifaces, NULL, NULL);
for (i = 0; i < cur_ifaces.n; i++) {
const char *if_name = cur_ifaces.names[i];
reconfigure_iface(if_name);
}
for (i = 0; i < add_ifaces.n; i++) {
const char *if_name = add_ifaces.names[i];
bool internal;
int error;
/* Attempt to create the network interface in case it
* doesn't exist yet. */
error = create_iface(if_name);
if (error) {
VLOG_WARN("could not create iface %s: %s\n", if_name,
strerror(error));
continue;
}
/* Add to datapath. */
internal = iface_is_internal(br, if_name);
error = dpif_port_add(br->dpif, if_name,
internal ? ODP_PORT_INTERNAL : 0, NULL);
if (error == EFBIG) {
VLOG_ERR("ran out of valid port numbers on %s",
dpif_name(br->dpif));
break;
} else if (error) {
VLOG_ERR("failed to add %s interface to %s: %s",
if_name, dpif_name(br->dpif), strerror(error));
}
}
svec_destroy(&cur_ifaces);
svec_destroy(&want_ifaces);
svec_destroy(&add_ifaces);
}
LIST_FOR_EACH (br, struct bridge, node, &all_bridges) {
uint8_t ea[8];
uint64_t dpid;
struct iface *local_iface;
struct iface *hw_addr_iface;
struct netflow_options nf_options;
bridge_fetch_dp_ifaces(br);
iterate_and_prune_ifaces(br, init_iface_netdev, NULL);
iterate_and_prune_ifaces(br, check_iface_dp_ifidx, NULL);
/* Pick local port hardware address, datapath ID. */
bridge_pick_local_hw_addr(br, ea, &hw_addr_iface);
local_iface = bridge_get_local_iface(br);
if (local_iface) {
int error = netdev_set_etheraddr(local_iface->netdev, ea);
if (error) {
static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
VLOG_ERR_RL(&rl, "bridge %s: failed to set bridge "
"Ethernet address: %s",
br->name, strerror(error));
}
}
dpid = bridge_pick_datapath_id(br, ea, hw_addr_iface);
ofproto_set_datapath_id(br->ofproto, dpid);
/* Set NetFlow configuration on this bridge. */
memset(&nf_options, 0, sizeof nf_options);
dpif_get_netflow_ids(br->dpif, &nf_options.engine_type,
&nf_options.engine_id);
nf_options.active_timeout = -1;
if (cfg_has("netflow.%s.engine-type", br->name)) {
nf_options.engine_type = cfg_get_int(0, "netflow.%s.engine-type",
br->name);
}
if (cfg_has("netflow.%s.engine-id", br->name)) {
nf_options.engine_id = cfg_get_int(0, "netflow.%s.engine-id",
br->name);
}
if (cfg_has("netflow.%s.active-timeout", br->name)) {
nf_options.active_timeout = cfg_get_int(0,
"netflow.%s.active-timeout",
br->name);
}
if (cfg_has("netflow.%s.add-id-to-iface", br->name)) {
nf_options.add_id_to_iface = cfg_get_bool(0,
"netflow.%s.add-id-to-iface",
br->name);
}
if (nf_options.add_id_to_iface && nf_options.engine_id > 0x7f) {
VLOG_WARN("bridge %s: netflow port mangling may conflict with "
"another vswitch, choose an engine id less than 128",
br->name);
}
if (nf_options.add_id_to_iface && br->n_ports > 508) {
VLOG_WARN("bridge %s: netflow port mangling will conflict with "
"another port when more than 508 ports are used",
br->name);
}
svec_init(&nf_options.collectors);
cfg_get_all_keys(&nf_options.collectors, "netflow.%s.host", br->name);
if (ofproto_set_netflow(br->ofproto, &nf_options)) {
VLOG_ERR("bridge %s: problem setting netflow collectors",
br->name);
}
svec_destroy(&nf_options.collectors);
/* Update the controller and related settings. It would be more
* straightforward to call this from bridge_reconfigure_one(), but we
* can't do it there for two reasons. First, and most importantly, at
* that point we don't know the dp_ifidx of any interfaces that have
* been added to the bridge (because we haven't actually added them to
* the datapath). Second, at that point we haven't set the datapath ID
* yet; when a controller is configured, resetting the datapath ID will
* immediately disconnect from the controller, so it's better to set
* the datapath ID before the controller. */
bridge_reconfigure_controller(br);
}
LIST_FOR_EACH (br, struct bridge, node, &all_bridges) {
for (i = 0; i < br->n_ports; i++) {
struct port *port = br->ports[i];
port_update_vlan_compat(port);
port_update_bonding(port);
}
}
LIST_FOR_EACH (br, struct bridge, node, &all_bridges) {
brstp_reconfigure(br);
iterate_and_prune_ifaces(br, set_iface_properties, NULL);
}
}
static void
bridge_pick_local_hw_addr(struct bridge *br, uint8_t ea[ETH_ADDR_LEN],
struct iface **hw_addr_iface)
{
uint64_t requested_ea;
size_t i, j;
int error;
*hw_addr_iface = NULL;
/* Did the user request a particular MAC? */
requested_ea = cfg_get_mac(0, "bridge.%s.mac", br->name);
if (requested_ea) {
eth_addr_from_uint64(requested_ea, ea);
if (eth_addr_is_multicast(ea)) {
VLOG_ERR("bridge %s: cannot set MAC address to multicast "
"address "ETH_ADDR_FMT, br->name, ETH_ADDR_ARGS(ea));
} else if (eth_addr_is_zero(ea)) {
VLOG_ERR("bridge %s: cannot set MAC address to zero", br->name);
} else {
return;
}
}
/* Otherwise choose the minimum MAC address among all of the interfaces.
* (Xen uses FE:FF:FF:FF:FF:FF for virtual interfaces so this will get the
* MAC of the physical interface in such an environment.) */
memset(ea, 0xff, sizeof ea);
for (i = 0; i < br->n_ports; i++) {
struct port *port = br->ports[i];
uint8_t iface_ea[ETH_ADDR_LEN];
uint64_t iface_ea_u64;
struct iface *iface;
/* Mirror output ports don't participate. */
if (port->is_mirror_output_port) {
continue;
}
/* Choose the MAC address to represent the port. */
iface_ea_u64 = cfg_get_mac(0, "port.%s.mac", port->name);
if (iface_ea_u64) {
/* User specified explicitly. */
eth_addr_from_uint64(iface_ea_u64, iface_ea);
/* Find the interface with this Ethernet address (if any) so that
* we can provide the correct devname to the caller. */
iface = NULL;
for (j = 0; j < port->n_ifaces; j++) {
struct iface *candidate = port->ifaces[j];
uint8_t candidate_ea[ETH_ADDR_LEN];
if (!netdev_get_etheraddr(candidate->netdev, candidate_ea)
&& eth_addr_equals(iface_ea, candidate_ea)) {
iface = candidate;
}
}
} else {
/* Choose the interface whose MAC address will represent the port.
* The Linux kernel bonding code always chooses the MAC address of
* the first slave added to a bond, and the Fedora networking
* scripts always add slaves to a bond in alphabetical order, so
* for compatibility we choose the interface with the name that is
* first in alphabetical order. */
iface = port->ifaces[0];
for (j = 1; j < port->n_ifaces; j++) {
struct iface *candidate = port->ifaces[j];
if (strcmp(candidate->name, iface->name) < 0) {
iface = candidate;
}
}
/* The local port doesn't count (since we're trying to choose its
* MAC address anyway). Other internal ports don't count because
* we really want a physical MAC if we can get it, and internal
* ports typically have randomly generated MACs. */
if (iface->dp_ifidx == ODPP_LOCAL
|| cfg_get_bool(0, "iface.%s.internal", iface->name)) {
continue;
}
/* Grab MAC. */
error = netdev_get_etheraddr(iface->netdev, iface_ea);
if (error) {
static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
VLOG_ERR_RL(&rl, "failed to obtain Ethernet address of %s: %s",
iface->name, strerror(error));
continue;
}
}
/* Compare against our current choice. */
if (!eth_addr_is_multicast(iface_ea) &&
!eth_addr_is_reserved(iface_ea) &&
!eth_addr_is_zero(iface_ea) &&
memcmp(iface_ea, ea, ETH_ADDR_LEN) < 0)
{
memcpy(ea, iface_ea, ETH_ADDR_LEN);
*hw_addr_iface = iface;
}
}
if (eth_addr_is_multicast(ea) || eth_addr_is_vif(ea)) {
memcpy(ea, br->default_ea, ETH_ADDR_LEN);
*hw_addr_iface = NULL;
VLOG_WARN("bridge %s: using default bridge Ethernet "
"address "ETH_ADDR_FMT, br->name, ETH_ADDR_ARGS(ea));
} else {
VLOG_DBG("bridge %s: using bridge Ethernet address "ETH_ADDR_FMT,
br->name, ETH_ADDR_ARGS(ea));
}
}
/* Choose and returns the datapath ID for bridge 'br' given that the bridge
* Ethernet address is 'bridge_ea'. If 'bridge_ea' is the Ethernet address of
* an interface on 'br', then that interface must be passed in as
* 'hw_addr_iface'; if 'bridge_ea' was derived some other way, then
* 'hw_addr_iface' must be passed in as a null pointer. */
static uint64_t
bridge_pick_datapath_id(struct bridge *br,
const uint8_t bridge_ea[ETH_ADDR_LEN],
struct iface *hw_addr_iface)
{
/*
* The procedure for choosing a bridge MAC address will, in the most
* ordinary case, also choose a unique MAC that we can use as a datapath
* ID. In some special cases, though, multiple bridges will end up with
* the same MAC address. This is OK for the bridges, but it will confuse
* the OpenFlow controller, because each datapath needs a unique datapath
* ID.
*
* Datapath IDs must be unique. It is also very desirable that they be
* stable from one run to the next, so that policy set on a datapath
* "sticks".
*/
uint64_t dpid;
dpid = cfg_get_dpid(0, "bridge.%s.datapath-id", br->name);
if (dpid) {
return dpid;
}
if (hw_addr_iface) {
int vlan;
if (!netdev_get_vlan_vid(hw_addr_iface->netdev, &vlan)) {
/*
* A bridge whose MAC address is taken from a VLAN network device
* (that is, a network device created with vconfig(8) or similar
* tool) will have the same MAC address as a bridge on the VLAN
* device's physical network device.
*
* Handle this case by hashing the physical network device MAC
* along with the VLAN identifier.
*/
uint8_t buf[ETH_ADDR_LEN + 2];
memcpy(buf, bridge_ea, ETH_ADDR_LEN);
buf[ETH_ADDR_LEN] = vlan >> 8;
buf[ETH_ADDR_LEN + 1] = vlan;
return dpid_from_hash(buf, sizeof buf);
} else {
/*
* Assume that this bridge's MAC address is unique, since it
* doesn't fit any of the cases we handle specially.
*/
}
} else {
/*
* A purely internal bridge, that is, one that has no non-virtual
* network devices on it at all, is more difficult because it has no
* natural unique identifier at all.
*
* When the host is a XenServer, we handle this case by hashing the
* host's UUID with the name of the bridge. Names of bridges are
* persistent across XenServer reboots, although they can be reused if
* an internal network is destroyed and then a new one is later
* created, so this is fairly effective.
*
* When the host is not a XenServer, we punt by using a random MAC
* address on each run.
*/
const char *host_uuid = xenserver_get_host_uuid();
if (host_uuid) {
char *combined = xasprintf("%s,%s", host_uuid, br->name);
dpid = dpid_from_hash(combined, strlen(combined));
free(combined);
return dpid;
}
}
return eth_addr_to_uint64(bridge_ea);
}
static uint64_t
dpid_from_hash(const void *data, size_t n)
{
uint8_t hash[SHA1_DIGEST_SIZE];
BUILD_ASSERT_DECL(sizeof hash >= ETH_ADDR_LEN);
sha1_bytes(data, n, hash);
eth_addr_mark_random(hash);
return eth_addr_to_uint64(hash);
}
int
bridge_run(void)
{
struct bridge *br, *next;
int retval;
retval = 0;
LIST_FOR_EACH_SAFE (br, next, struct bridge, node, &all_bridges) {
int error = bridge_run_one(br);
if (error) {
static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
VLOG_ERR_RL(&rl, "bridge %s: datapath was destroyed externally, "
"forcing reconfiguration", br->name);
if (!retval) {
retval = error;
}
}
}
return retval;
}
void
bridge_wait(void)
{
struct bridge *br;
LIST_FOR_EACH (br, struct bridge, node, &all_bridges) {
ofproto_wait(br->ofproto);
if (br->controller) {
continue;
}
mac_learning_wait(br->ml);
bond_wait(br);
brstp_wait(br);
}
}
/* Forces 'br' to revalidate all of its flows. This is appropriate when 'br''s
* configuration changes. */
static void
bridge_flush(struct bridge *br)
{
COVERAGE_INC(bridge_flush);
br->flush = true;
mac_learning_flush(br->ml);
}
/* Returns the 'br' interface for the ODPP_LOCAL port, or null if 'br' has no
* such interface. */
static struct iface *
bridge_get_local_iface(struct bridge *br)
{
size_t i, j;
for (i = 0; i < br->n_ports; i++) {
struct port *port = br->ports[i];
for (j = 0; j < port->n_ifaces; j++) {
struct iface *iface = port->ifaces[j];
if (iface->dp_ifidx == ODPP_LOCAL) {
return iface;
}
}
}
return NULL;
}
/* Bridge unixctl user interface functions. */
static void
bridge_unixctl_fdb_show(struct unixctl_conn *conn, const char *args)
{
struct ds ds = DS_EMPTY_INITIALIZER;
const struct bridge *br;
const struct mac_entry *e;
br = bridge_lookup(args);
if (!br) {
unixctl_command_reply(conn, 501, "no such bridge");
return;
}
ds_put_cstr(&ds, " port VLAN MAC Age\n");
LIST_FOR_EACH (e, struct mac_entry, lru_node, &br->ml->lrus) {
if (e->port < 0 || e->port >= br->n_ports) {
continue;
}
ds_put_format(&ds, "%5d %4d "ETH_ADDR_FMT" %3d\n",
br->ports[e->port]->ifaces[0]->dp_ifidx,
e->vlan, ETH_ADDR_ARGS(e->mac), mac_entry_age(e));
}
unixctl_command_reply(conn, 200, ds_cstr(&ds));
ds_destroy(&ds);
}
/* Bridge reconfiguration functions. */
static struct bridge *
bridge_create(const char *name)
{
struct bridge *br;
int error;
assert(!bridge_lookup(name));
br = xcalloc(1, sizeof *br);
error = dpif_create_and_open(name, &br->dpif);
if (error) {
free(br);
return NULL;
}
dpif_flow_flush(br->dpif);
error = ofproto_create(name, &bridge_ofhooks, br, &br->ofproto);
if (error) {
VLOG_ERR("failed to create switch %s: %s", name, strerror(error));
dpif_delete(br->dpif);
dpif_close(br->dpif);
free(br);
return NULL;
}
br->name = xstrdup(name);
br->ml = mac_learning_create();
br->sent_config_request = false;
eth_addr_random(br->default_ea);
port_array_init(&br->ifaces);
br->flush = false;
br->bond_next_rebalance = time_msec() + 10000;
list_push_back(&all_bridges, &br->node);
VLOG_INFO("created bridge %s on %s", br->name, dpif_name(br->dpif));
return br;
}
static void
bridge_destroy(struct bridge *br)
{
if (br) {
int error;
while (br->n_ports > 0) {
port_destroy(br->ports[br->n_ports - 1]);
}
list_remove(&br->node);
error = dpif_delete(br->dpif);
if (error && error != ENOENT) {
VLOG_ERR("failed to delete %s: %s",
dpif_name(br->dpif), strerror(error));
}
dpif_close(br->dpif);
ofproto_destroy(br->ofproto);
free(br->controller);
mac_learning_destroy(br->ml);
port_array_destroy(&br->ifaces);
free(br->ports);
free(br->name);
free(br);
}
}
static struct bridge *
bridge_lookup(const char *name)
{
struct bridge *br;
LIST_FOR_EACH (br, struct bridge, node, &all_bridges) {
if (!strcmp(br->name, name)) {
return br;
}
}
return NULL;
}
bool
bridge_exists(const char *name)
{
return bridge_lookup(name) ? true : false;
}
uint64_t
bridge_get_datapathid(const char *name)
{
struct bridge *br = bridge_lookup(name);
return br ? ofproto_get_datapath_id(br->ofproto) : 0;
}
/* Handle requests for a listing of all flows known by the OpenFlow
* stack, including those normally hidden. */
static void
bridge_unixctl_dump_flows(struct unixctl_conn *conn, const char *args)
{
struct bridge *br;
struct ds results;
br = bridge_lookup(args);
if (!br) {
unixctl_command_reply(conn, 501, "Unknown bridge");
return;
}
ds_init(&results);
ofproto_get_all_flows(br->ofproto, &results);
unixctl_command_reply(conn, 200, ds_cstr(&results));
ds_destroy(&results);
}
static int
bridge_run_one(struct bridge *br)
{
int error;
error = ofproto_run1(br->ofproto);
if (error) {
return error;
}
mac_learning_run(br->ml, ofproto_get_revalidate_set(br->ofproto));
bond_run(br);
brstp_run(br);
error = ofproto_run2(br->ofproto, br->flush);
br->flush = false;
return error;
}
static const char *
bridge_get_controller(const struct bridge *br)
{
const char *controller;
controller = cfg_get_string(0, "bridge.%s.controller", br->name);
if (!controller) {
controller = cfg_get_string(0, "mgmt.controller");
}
return controller && controller[0] ? controller : NULL;
}
static bool
check_duplicate_ifaces(struct bridge *br, struct iface *iface, void *ifaces_)
{
struct svec *ifaces = ifaces_;
if (!svec_contains(ifaces, iface->name)) {
svec_add(ifaces, iface->name);
svec_sort(ifaces);
return true;
} else {
VLOG_ERR("bridge %s: %s interface is on multiple ports, "
"removing from %s",
br->name, iface->name, iface->port->name);
return false;
}
}
static void
bridge_reconfigure_one(struct bridge *br)
{
struct svec old_ports, new_ports, ifaces;
struct svec listeners, old_listeners;
struct svec snoops, old_snoops;
size_t i;
/* Collect old ports. */
svec_init(&old_ports);
for (i = 0; i < br->n_ports; i++) {
svec_add(&old_ports, br->ports[i]->name);
}
svec_sort(&old_ports);
assert(svec_is_unique(&old_ports));
/* Collect new ports. */
svec_init(&new_ports);
cfg_get_all_keys(&new_ports, "bridge.%s.port", br->name);
svec_sort(&new_ports);
if (bridge_get_controller(br)) {
char local_name[IF_NAMESIZE];
int error;
error = dpif_port_get_name(br->dpif, ODPP_LOCAL,
local_name, sizeof local_name);
if (!error && !svec_contains(&new_ports, local_name)) {
svec_add(&new_ports, local_name);
svec_sort(&new_ports);
}
}
if (!svec_is_unique(&new_ports)) {
VLOG_WARN("bridge %s: %s specified twice as bridge port",
br->name, svec_get_duplicate(&new_ports));
svec_unique(&new_ports);
}
ofproto_set_mgmt_id(br->ofproto, mgmt_id);
/* Get rid of deleted ports and add new ports. */
for (i = 0; i < br->n_ports; ) {
struct port *port = br->ports[i];
if (!svec_contains(&new_ports, port->name)) {
port_destroy(port);
} else {
i++;
}
}
for (i = 0; i < new_ports.n; i++) {
const char *name = new_ports.names[i];
if (!svec_contains(&old_ports, name)) {
port_create(br, name);
}
}
svec_destroy(&old_ports);
svec_destroy(&new_ports);
/* Reconfigure all ports. */
for (i = 0; i < br->n_ports; i++) {
port_reconfigure(br->ports[i]);
}
/* Check and delete duplicate interfaces. */
svec_init(&ifaces);
iterate_and_prune_ifaces(br, check_duplicate_ifaces, &ifaces);
svec_destroy(&ifaces);
/* Delete all flows if we're switching from connected to standalone or vice
* versa. (XXX Should we delete all flows if we are switching from one
* controller to another?) */
/* Configure OpenFlow management listeners. */
svec_init(&listeners);
cfg_get_all_strings(&listeners, "bridge.%s.openflow.listeners", br->name);
if (!listeners.n) {
svec_add_nocopy(&listeners, xasprintf("punix:%s/%s.mgmt",
ovs_rundir, br->name));
} else if (listeners.n == 1 && !strcmp(listeners.names[0], "none")) {
svec_clear(&listeners);
}
svec_sort_unique(&listeners);
svec_init(&old_listeners);
ofproto_get_listeners(br->ofproto, &old_listeners);
svec_sort_unique(&old_listeners);
if (!svec_equal(&listeners, &old_listeners)) {
ofproto_set_listeners(br->ofproto, &listeners);
}
svec_destroy(&listeners);
svec_destroy(&old_listeners);
/* Configure OpenFlow controller connection snooping. */
svec_init(&snoops);
cfg_get_all_strings(&snoops, "bridge.%s.openflow.snoops", br->name);
if (!snoops.n) {
svec_add_nocopy(&snoops, xasprintf("punix:%s/%s.snoop",
ovs_rundir, br->name));
} else if (snoops.n == 1 && !strcmp(snoops.names[0], "none")) {
svec_clear(&snoops);
}
svec_sort_unique(&snoops);
svec_init(&old_snoops);
ofproto_get_snoops(br->ofproto, &old_snoops);
svec_sort_unique(&old_snoops);
if (!svec_equal(&snoops, &old_snoops)) {
ofproto_set_snoops(br->ofproto, &snoops);
}
svec_destroy(&snoops);
svec_destroy(&old_snoops);
mirror_reconfigure(br);
}
static void
bridge_reconfigure_controller(struct bridge *br)
{
char *pfx = xasprintf("bridge.%s.controller", br->name);
const char *controller;
controller = bridge_get_controller(br);
if ((br->controller != NULL) != (controller != NULL)) {
ofproto_flush_flows(br->ofproto);
}
free(br->controller);
br->controller = controller ? xstrdup(controller) : NULL;
if (controller) {
const char *fail_mode;
int max_backoff, probe;
int rate_limit, burst_limit;
if (!strcmp(controller, "discover")) {
bool update_resolv_conf = true;
if (cfg_has("%s.update-resolv.conf", pfx)) {
update_resolv_conf = cfg_get_bool(0, "%s.update-resolv.conf",
pfx);
}
ofproto_set_discovery(br->ofproto, true,
cfg_get_string(0, "%s.accept-regex", pfx),
update_resolv_conf);
} else {
struct iface *local_iface;
bool in_band;
in_band = (!cfg_is_valid(CFG_BOOL | CFG_REQUIRED,
"%s.in-band", pfx)
|| cfg_get_bool(0, "%s.in-band", pfx));
ofproto_set_discovery(br->ofproto, false, NULL, NULL);
ofproto_set_in_band(br->ofproto, in_band);
local_iface = bridge_get_local_iface(br);
if (local_iface
&& cfg_is_valid(CFG_IP | CFG_REQUIRED, "%s.ip", pfx)) {
struct netdev *netdev = local_iface->netdev;
struct in_addr ip, mask, gateway;
ip.s_addr = cfg_get_ip(0, "%s.ip", pfx);
mask.s_addr = cfg_get_ip(0, "%s.netmask", pfx);
gateway.s_addr = cfg_get_ip(0, "%s.gateway", pfx);
netdev_turn_flags_on(netdev, NETDEV_UP, true);
if (!mask.s_addr) {
mask.s_addr = guess_netmask(ip.s_addr);
}
if (!netdev_set_in4(netdev, ip, mask)) {
VLOG_INFO("bridge %s: configured IP address "IP_FMT", "
"netmask "IP_FMT,
br->name, IP_ARGS(&ip.s_addr),
IP_ARGS(&mask.s_addr));
}
if (gateway.s_addr) {
if (!netdev_add_router(netdev, gateway)) {
VLOG_INFO("bridge %s: configured gateway "IP_FMT,
br->name, IP_ARGS(&gateway.s_addr));
}
}
}
}
fail_mode = cfg_get_string(0, "%s.fail-mode", pfx);
if (!fail_mode) {
fail_mode = cfg_get_string(0, "mgmt.fail-mode");
}
ofproto_set_failure(br->ofproto,
(!fail_mode
|| !strcmp(fail_mode, "standalone")
|| !strcmp(fail_mode, "open")));
probe = cfg_get_int(0, "%s.inactivity-probe", pfx);
if (probe < 5) {
probe = cfg_get_int(0, "mgmt.inactivity-probe");
if (probe < 5) {
probe = 5;
}
}
ofproto_set_probe_interval(br->ofproto, probe);
max_backoff = cfg_get_int(0, "%s.max-backoff", pfx);
if (!max_backoff) {
max_backoff = cfg_get_int(0, "mgmt.max-backoff");
if (!max_backoff) {
max_backoff = 8;
}
}
ofproto_set_max_backoff(br->ofproto, max_backoff);
rate_limit = cfg_get_int(0, "%s.rate-limit", pfx);
if (!rate_limit) {
rate_limit = cfg_get_int(0, "mgmt.rate-limit");
}
burst_limit = cfg_get_int(0, "%s.burst-limit", pfx);
if (!burst_limit) {
burst_limit = cfg_get_int(0, "mgmt.burst-limit");
}
ofproto_set_rate_limit(br->ofproto, rate_limit, burst_limit);
ofproto_set_stp(br->ofproto, cfg_get_bool(0, "%s.stp", pfx));
if (cfg_has("%s.commands.acl", pfx)) {
struct svec command_acls;
char *command_acl;
svec_init(&command_acls);
cfg_get_all_strings(&command_acls, "%s.commands.acl", pfx);
command_acl = svec_join(&command_acls, ",", "");
ofproto_set_remote_execution(br->ofproto, command_acl,
cfg_get_string(0, "%s.commands.dir",
pfx));
svec_destroy(&command_acls);
free(command_acl);
} else {
ofproto_set_remote_execution(br->ofproto, NULL, NULL);
}
} else {
union ofp_action action;
flow_t flow;
/* Set up a flow that matches every packet and directs them to
* OFPP_NORMAL (which goes to us). */
memset(&action, 0, sizeof action);
action.type = htons(OFPAT_OUTPUT);
action.output.len = htons(sizeof action);
action.output.port = htons(OFPP_NORMAL);
memset(&flow, 0, sizeof flow);
ofproto_add_flow(br->ofproto, &flow, OFPFW_ALL, 0,
&action, 1, 0);
ofproto_set_in_band(br->ofproto, false);
ofproto_set_max_backoff(br->ofproto, 1);
ofproto_set_probe_interval(br->ofproto, 5);
ofproto_set_failure(br->ofproto, false);
ofproto_set_stp(br->ofproto, false);
}
free(pfx);
ofproto_set_controller(br->ofproto, br->controller);
}
static void
bridge_get_all_ifaces(const struct bridge *br, struct svec *ifaces)
{
size_t i, j;
svec_init(ifaces);
for (i = 0; i < br->n_ports; i++) {
struct port *port = br->ports[i];
for (j = 0; j < port->n_ifaces; j++) {
struct iface *iface = port->ifaces[j];
svec_add(ifaces, iface->name);
}
if (port->n_ifaces > 1
&& cfg_get_bool(0, "bonding.%s.fake-iface", port->name)) {
svec_add(ifaces, port->name);
}
}
svec_sort_unique(ifaces);
}
/* For robustness, in case the administrator moves around datapath ports behind
* our back, we re-check all the datapath port numbers here.
*
* This function will set the 'dp_ifidx' members of interfaces that have
* disappeared to -1, so only call this function from a context where those
* 'struct iface's will be removed from the bridge. Otherwise, the -1
* 'dp_ifidx'es will cause trouble later when we try to send them to the
* datapath, which doesn't support UINT16_MAX+1 ports. */
static void
bridge_fetch_dp_ifaces(struct bridge *br)
{
struct odp_port *dpif_ports;
size_t n_dpif_ports;
size_t i, j;
/* Reset all interface numbers. */
for (i = 0; i < br->n_ports; i++) {
struct port *port = br->ports[i];
for (j = 0; j < port->n_ifaces; j++) {
struct iface *iface = port->ifaces[j];
iface->dp_ifidx = -1;
}
}
port_array_clear(&br->ifaces);
dpif_port_list(br->dpif, &dpif_ports, &n_dpif_ports);
for (i = 0; i < n_dpif_ports; i++) {
struct odp_port *p = &dpif_ports[i];
struct iface *iface = iface_lookup(br, p->devname);
if (iface) {
if (iface->dp_ifidx >= 0) {
VLOG_WARN("%s reported interface %s twice",
dpif_name(br->dpif), p->devname);
} else if (iface_from_dp_ifidx(br, p->port)) {
VLOG_WARN("%s reported interface %"PRIu16" twice",
dpif_name(br->dpif), p->port);
} else {
port_array_set(&br->ifaces, p->port, iface);
iface->dp_ifidx = p->port;
}
}
}
free(dpif_ports);
}
/* Bridge packet processing functions. */
static int
bond_hash(const uint8_t mac[ETH_ADDR_LEN])
{
return hash_bytes(mac, ETH_ADDR_LEN, 0) & BOND_MASK;
}
static struct bond_entry *
lookup_bond_entry(const struct port *port, const uint8_t mac[ETH_ADDR_LEN])
{
return &port->bond_hash[bond_hash(mac)];
}
static int
bond_choose_iface(const struct port *port)
{
static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(5, 20);
size_t i, best_down_slave = -1;
long long next_delay_expiration = LLONG_MAX;
for (i = 0; i < port->n_ifaces; i++) {
struct iface *iface = port->ifaces[i];
if (iface->enabled) {
return i;
} else if (iface->delay_expires < next_delay_expiration) {
best_down_slave = i;
next_delay_expiration = iface->delay_expires;
}
}
if (best_down_slave != -1) {
struct iface *iface = port->ifaces[best_down_slave];
VLOG_INFO_RL(&rl, "interface %s: skipping remaining %lli ms updelay "
"since no other interface is up", iface->name,
iface->delay_expires - time_msec());
bond_enable_slave(iface, true);
}
return best_down_slave;
}
static bool
choose_output_iface(const struct port *port, const uint8_t *dl_src,
uint16_t *dp_ifidx, tag_type *tags)
{
struct iface *iface;
assert(port->n_ifaces);
if (port->n_ifaces == 1) {
iface = port->ifaces[0];
} else {
struct bond_entry *e = lookup_bond_entry(port, dl_src);
if (e->iface_idx < 0 || e->iface_idx >= port->n_ifaces
|| !port->ifaces[e->iface_idx]->enabled) {
/* XXX select interface properly. The current interface selection
* is only good for testing the rebalancing code. */
e->iface_idx = bond_choose_iface(port);
if (e->iface_idx < 0) {
*tags |= port->no_ifaces_tag;
return false;
}
e->iface_tag = tag_create_random();
((struct port *) port)->bond_compat_is_stale = true;
}
*tags |= e->iface_tag;
iface = port->ifaces[e->iface_idx];
}
*dp_ifidx = iface->dp_ifidx;
*tags |= iface->tag; /* Currently only used for bonding. */
return true;
}
static void
bond_link_status_update(struct iface *iface, bool carrier)
{
static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(5, 20);
struct port *port = iface->port;
if ((carrier == iface->enabled) == (iface->delay_expires == LLONG_MAX)) {
/* Nothing to do. */
return;
}
VLOG_INFO_RL(&rl, "interface %s: carrier %s",
iface->name, carrier ? "detected" : "dropped");
if (carrier == iface->enabled) {
iface->delay_expires = LLONG_MAX;
VLOG_INFO_RL(&rl, "interface %s: will not be %s",
iface->name, carrier ? "disabled" : "enabled");
} else if (carrier && port->active_iface < 0) {
bond_enable_slave(iface, true);
if (port->updelay) {
VLOG_INFO_RL(&rl, "interface %s: skipping %d ms updelay since no "
"other interface is up", iface->name, port->updelay);
}
} else {
int delay = carrier ? port->updelay : port->downdelay;
iface->delay_expires = time_msec() + delay;
if (delay) {
VLOG_INFO_RL(&rl,
"interface %s: will be %s if it stays %s for %d ms",
iface->name,
carrier ? "enabled" : "disabled",
carrier ? "up" : "down",
delay);
}
}
}
static void
bond_choose_active_iface(struct port *port)
{
static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(5, 20);
port->active_iface = bond_choose_iface(port);
port->active_iface_tag = tag_create_random();
if (port->active_iface >= 0) {
VLOG_INFO_RL(&rl, "port %s: active interface is now %s",
port->name, port->ifaces[port->active_iface]->name);
} else {
VLOG_WARN_RL(&rl, "port %s: all ports disabled, no active interface",
port->name);
}
}
static void
bond_enable_slave(struct iface *iface, bool enable)
{
struct port *port = iface->port;
struct bridge *br = port->bridge;
/* This acts as a recursion check. If the act of disabling a slave
* causes a different slave to be enabled, the flag will allow us to
* skip redundant work when we reenter this function. It must be
* cleared on exit to keep things safe with multiple bonds. */
static bool moving_active_iface = false;
iface->delay_expires = LLONG_MAX;
if (enable == iface->enabled) {
return;
}
iface->enabled = enable;
if (!iface->enabled) {
VLOG_WARN("interface %s: disabled", iface->name);
ofproto_revalidate(br->ofproto, iface->tag);
if (iface->port_ifidx == port->active_iface) {
ofproto_revalidate(br->ofproto,
port->active_iface_tag);
/* Disabling a slave can lead to another slave being immediately
* enabled if there will be no active slaves but one is waiting
* on an updelay. In this case we do not need to run most of the
* code for the newly enabled slave since there was no period
* without an active slave and it is redundant with the disabling
* path. */
moving_active_iface = true;
bond_choose_active_iface(port);
}
bond_send_learning_packets(port);
} else {
VLOG_WARN("interface %s: enabled", iface->name);
if (port->active_iface < 0 && !moving_active_iface) {
ofproto_revalidate(br->ofproto, port->no_ifaces_tag);
bond_choose_active_iface(port);
bond_send_learning_packets(port);
}
iface->tag = tag_create_random();
}
moving_active_iface = false;
port->bond_compat_is_stale = true;
}
static void
bond_run(struct bridge *br)
{
size_t i, j;
for (i = 0; i < br->n_ports; i++) {
struct port *port = br->ports[i];
if (port->n_ifaces >= 2) {
for (j = 0; j < port->n_ifaces; j++) {
struct iface *iface = port->ifaces[j];
if (time_msec() >= iface->delay_expires) {
bond_enable_slave(iface, !iface->enabled);
}
}
}
if (port->bond_compat_is_stale) {
port->bond_compat_is_stale = false;
port_update_bond_compat(port);
}
}
}
static void
bond_wait(struct bridge *br)
{
size_t i, j;
for (i = 0; i < br->n_ports; i++) {
struct port *port = br->ports[i];
if (port->n_ifaces < 2) {
continue;
}
for (j = 0; j < port->n_ifaces; j++) {
struct iface *iface = port->ifaces[j];
if (iface->delay_expires != LLONG_MAX) {
poll_timer_wait(iface->delay_expires - time_msec());
}
}
}
}
static bool
set_dst(struct dst *p, const flow_t *flow,
const struct port *in_port, const struct port *out_port,
tag_type *tags)
{
/* STP handling.
*
* XXX This uses too many tags: any broadcast flow will get one tag per
* destination port, and thus a broadcast on a switch of any size is likely
* to have all tag bits set. We should figure out a way to be smarter.
*
* This is OK when STP is disabled, because stp_state_tag is 0 then. */
*tags |= out_port->stp_state_tag;
if (!(out_port->stp_state & (STP_DISABLED | STP_FORWARDING))) {
return false;
}
p->vlan = (out_port->vlan >= 0 ? OFP_VLAN_NONE
: in_port->vlan >= 0 ? in_port->vlan
: ntohs(flow->dl_vlan));
return choose_output_iface(out_port, flow->dl_src, &p->dp_ifidx, tags);
}
static void
swap_dst(struct dst *p, struct dst *q)
{
struct dst tmp = *p;
*p = *q;
*q = tmp;
}
/* Moves all the dsts with vlan == 'vlan' to the front of the 'n_dsts' in
* 'dsts'. (This may help performance by reducing the number of VLAN changes
* that we push to the datapath. We could in fact fully sort the array by
* vlan, but in most cases there are at most two different vlan tags so that's
* possibly overkill.) */
static void
partition_dsts(struct dst *dsts, size_t n_dsts, int vlan)
{
struct dst *first = dsts;
struct dst *last = dsts + n_dsts;
while (first != last) {
/* Invariants:
* - All dsts < first have vlan == 'vlan'.
* - All dsts >= last have vlan != 'vlan'.
* - first < last. */
while (first->vlan == vlan) {
if (++first == last) {
return;
}
}
/* Same invariants, plus one additional:
* - first->vlan != vlan.
*/
while (last[-1].vlan != vlan) {
if (--last == first) {
return;
}
}
/* Same invariants, plus one additional:
* - last[-1].vlan == vlan.*/
swap_dst(first++, --last);
}
}
static int
mirror_mask_ffs(mirror_mask_t mask)
{
BUILD_ASSERT_DECL(sizeof(unsigned int) >= sizeof(mask));
return ffs(mask);
}
static bool
dst_is_duplicate(const struct dst *dsts, size_t n_dsts,
const struct dst *test)
{
size_t i;
for (i = 0; i < n_dsts; i++) {
if (dsts[i].vlan == test->vlan && dsts[i].dp_ifidx == test->dp_ifidx) {
return true;
}
}
return false;
}
static bool
port_trunks_vlan(const struct port *port, uint16_t vlan)
{
return port->vlan < 0 && bitmap_is_set(port->trunks, vlan);
}
static bool
port_includes_vlan(const struct port *port, uint16_t vlan)
{
return vlan == port->vlan || port_trunks_vlan(port, vlan);
}
static size_t
compose_dsts(const struct bridge *br, const flow_t *flow, uint16_t vlan,
const struct port *in_port, const struct port *out_port,
struct dst dsts[], tag_type *tags, uint16_t *nf_output_iface)
{
mirror_mask_t mirrors = in_port->src_mirrors;
struct dst *dst = dsts;
size_t i;
*tags |= in_port->stp_state_tag;
if (out_port == FLOOD_PORT) {
/* XXX use ODP_FLOOD if no vlans or bonding. */
/* XXX even better, define each VLAN as a datapath port group */
for (i = 0; i < br->n_ports; i++) {
struct port *port = br->ports[i];
if (port != in_port && port_includes_vlan(port, vlan)
&& !port->is_mirror_output_port
&& set_dst(dst, flow, in_port, port, tags)) {
mirrors |= port->dst_mirrors;
dst++;
}
}
*nf_output_iface = NF_OUT_FLOOD;
} else if (out_port && set_dst(dst, flow, in_port, out_port, tags)) {
*nf_output_iface = dst->dp_ifidx;
mirrors |= out_port->dst_mirrors;
dst++;
}
while (mirrors) {
struct mirror *m = br->mirrors[mirror_mask_ffs(mirrors) - 1];
if (!m->n_vlans || vlan_is_mirrored(m, vlan)) {
if (m->out_port) {
if (set_dst(dst, flow, in_port, m->out_port, tags)
&& !dst_is_duplicate(dsts, dst - dsts, dst)) {
dst++;
}
} else {
for (i = 0; i < br->n_ports; i++) {
struct port *port = br->ports[i];
if (port_includes_vlan(port, m->out_vlan)
&& set_dst(dst, flow, in_port, port, tags))
{
int flow_vlan;
if (port->vlan < 0) {
dst->vlan = m->out_vlan;
}
if (dst_is_duplicate(dsts, dst - dsts, dst)) {
continue;
}
/* Use the vlan tag on the original flow instead of
* the one passed in the vlan parameter. This ensures
* that we compare the vlan from before any implicit
* tagging tags place. This is necessary because
* dst->vlan is the final vlan, after removing implicit
* tags. */
flow_vlan = ntohs(flow->dl_vlan);
if (flow_vlan == 0) {
flow_vlan = OFP_VLAN_NONE;
}
if (port == in_port && dst->vlan == flow_vlan) {
/* Don't send out input port on same VLAN. */
continue;
}
dst++;
}
}
}
}
mirrors &= mirrors - 1;
}
partition_dsts(dsts, dst - dsts, ntohs(flow->dl_vlan));
return dst - dsts;
}
static void UNUSED
print_dsts(const struct dst *dsts, size_t n)
{
for (; n--; dsts++) {
printf(">p%"PRIu16, dsts->dp_ifidx);
if (dsts->vlan != OFP_VLAN_NONE) {
printf("v%"PRIu16, dsts->vlan);
}
}
}
static void
compose_actions(struct bridge *br, const flow_t *flow, uint16_t vlan,
const struct port *in_port, const struct port *out_port,
tag_type *tags, struct odp_actions *actions,
uint16_t *nf_output_iface)
{
struct dst dsts[DP_MAX_PORTS * (MAX_MIRRORS + 1)];
size_t n_dsts;
const struct dst *p;
uint16_t cur_vlan;
n_dsts = compose_dsts(br, flow, vlan, in_port, out_port, dsts, tags,
nf_output_iface);
cur_vlan = ntohs(flow->dl_vlan);
for (p = dsts; p < &dsts[n_dsts]; p++) {
union odp_action *a;
if (p->vlan != cur_vlan) {
if (p->vlan == OFP_VLAN_NONE) {
odp_actions_add(actions, ODPAT_STRIP_VLAN);
} else {
a = odp_actions_add(actions, ODPAT_SET_VLAN_VID);
a->vlan_vid.vlan_vid = htons(p->vlan);
}
cur_vlan = p->vlan;
}
a = odp_actions_add(actions, ODPAT_OUTPUT);
a->output.port = p->dp_ifidx;
}
}
/* Returns the effective vlan of a packet, taking into account both the
* 802.1Q header and implicitly tagged ports. A value of 0 indicates that
* the packet is untagged and -1 indicates it has an invalid header and
* should be dropped. */
static int flow_get_vlan(struct bridge *br, const flow_t *flow,
struct port *in_port, bool have_packet)
{
/* Note that dl_vlan of 0 and of OFP_VLAN_NONE both mean that the packet
* belongs to VLAN 0, so we should treat both cases identically. (In the
* former case, the packet has an 802.1Q header that specifies VLAN 0,
* presumably to allow a priority to be specified. In the latter case, the
* packet does not have any 802.1Q header.) */
int vlan = ntohs(flow->dl_vlan);
if (vlan == OFP_VLAN_NONE) {
vlan = 0;
}
if (in_port->vlan >= 0) {
if (vlan) {
/* XXX support double tagging? */
if (have_packet) {
static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
VLOG_WARN_RL(&rl, "bridge %s: dropping VLAN %"PRIu16" tagged "
"packet received on port %s configured with "
"implicit VLAN %"PRIu16,
br->name, ntohs(flow->dl_vlan),
in_port->name, in_port->vlan);
}
return -1;
}
vlan = in_port->vlan;
} else {
if (!port_includes_vlan(in_port, vlan)) {
if (have_packet) {
static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
VLOG_WARN_RL(&rl, "bridge %s: dropping VLAN %d tagged "
"packet received on port %s not configured for "
"trunking VLAN %d",
br->name, vlan, in_port->name, vlan);
}
return -1;
}
}
return vlan;
}
static void
update_learning_table(struct bridge *br, const flow_t *flow, int vlan,
struct port *in_port)
{
tag_type rev_tag = mac_learning_learn(br->ml, flow->dl_src,
vlan, in_port->port_idx);
if (rev_tag) {
/* The log messages here could actually be useful in debugging,
* so keep the rate limit relatively high. */
static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(30,
300);
VLOG_DBG_RL(&rl, "bridge %s: learned that "ETH_ADDR_FMT" is "
"on port %s in VLAN %d",
br->name, ETH_ADDR_ARGS(flow->dl_src),
in_port->name, vlan);
ofproto_revalidate(br->ofproto, rev_tag);
}
}
static bool
is_bcast_arp_reply(const flow_t *flow)
{
return (flow->dl_type == htons(ETH_TYPE_ARP)
&& flow->nw_proto == ARP_OP_REPLY
&& eth_addr_is_broadcast(flow->dl_dst));
}
/* If the composed actions may be applied to any packet in the given 'flow',
* returns true. Otherwise, the actions should only be applied to 'packet', or
* not at all, if 'packet' was NULL. */
static bool
process_flow(struct bridge *br, const flow_t *flow,
const struct ofpbuf *packet, struct odp_actions *actions,
tag_type *tags, uint16_t *nf_output_iface)
{
struct iface *in_iface;
struct port *in_port;
struct port *out_port = NULL; /* By default, drop the packet/flow. */
int vlan;
int out_port_idx;
/* Find the interface and port structure for the received packet. */
in_iface = iface_from_dp_ifidx(br, flow->in_port);
if (!in_iface) {
/* No interface? Something fishy... */
if (packet != NULL) {
/* Odd. A few possible reasons here:
*
* - We deleted an interface but there are still a few packets
* queued up from it.
*
* - Someone externally added an interface (e.g. with "ovs-dpctl
* add-if") that we don't know about.
*
* - Packet arrived on the local port but the local port is not
* one of our bridge ports.
*/
static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
VLOG_WARN_RL(&rl, "bridge %s: received packet on unknown "
"interface %"PRIu16, br->name, flow->in_port);
}
/* Return without adding any actions, to drop packets on this flow. */
return true;
}
in_port = in_iface->port;
vlan = flow_get_vlan(br, flow, in_port, !!packet);
if (vlan < 0) {
goto done;
}
/* Drop frames for ports that STP wants entirely killed (both for
* forwarding and for learning). Later, after we do learning, we'll drop
* the frames that STP wants to do learning but not forwarding on. */
if (in_port->stp_state & (STP_LISTENING | STP_BLOCKING)) {
goto done;
}
/* Drop frames for reserved multicast addresses. */
if (eth_addr_is_reserved(flow->dl_dst)) {
goto done;
}
/* Drop frames on ports reserved for mirroring. */
if (in_port->is_mirror_output_port) {
static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
VLOG_WARN_RL(&rl, "bridge %s: dropping packet received on port %s, "
"which is reserved exclusively for mirroring",
br->name, in_port->name);
goto done;
}
/* Packets received on bonds need special attention to avoid duplicates. */
if (in_port->n_ifaces > 1) {
int src_idx;
if (eth_addr_is_multicast(flow->dl_dst)) {
*tags |= in_port->active_iface_tag;
if (in_port->active_iface != in_iface->port_ifidx) {
/* Drop all multicast packets on inactive slaves. */
goto done;
}
}
/* Drop all packets for which we have learned a different input
* port, because we probably sent the packet on one slave and got
* it back on the other. Broadcast ARP replies are an exception
* to this rule: the host has moved to another switch. */
src_idx = mac_learning_lookup(br->ml, flow->dl_src, vlan);
if (src_idx != -1 && src_idx != in_port->port_idx &&
!is_bcast_arp_reply(flow)) {
goto done;
}
}
/* MAC learning. */
out_port = FLOOD_PORT;
/* Learn source MAC (but don't try to learn from revalidation). */
if (packet) {
update_learning_table(br, flow, vlan, in_port);
}
/* Determine output port. */
out_port_idx = mac_learning_lookup_tag(br->ml, flow->dl_dst, vlan,
tags);
if (out_port_idx >= 0 && out_port_idx < br->n_ports) {
out_port = br->ports[out_port_idx];
} else if (!packet && !eth_addr_is_multicast(flow->dl_dst)) {
/* If we are revalidating but don't have a learning entry then
* eject the flow. Installing a flow that floods packets opens
* up a window of time where we could learn from a packet reflected
* on a bond and blackhole packets before the learning table is
* updated to reflect the correct port. */
return false;
}
/* Don't send packets out their input ports. Don't forward frames that STP
* wants us to discard. */
if (in_port == out_port || in_port->stp_state == STP_LEARNING) {
out_port = NULL;
}
done:
compose_actions(br, flow, vlan, in_port, out_port, tags, actions,
nf_output_iface);
return true;
}
/* Careful: 'opp' is in host byte order and opp->port_no is an OFP port
* number. */
static void
bridge_port_changed_ofhook_cb(enum ofp_port_reason reason,
const struct ofp_phy_port *opp,
void *br_)
{
struct bridge *br = br_;
struct iface *iface;
struct port *port;
iface = iface_from_dp_ifidx(br, ofp_port_to_odp_port(opp->port_no));
if (!iface) {
return;
}
port = iface->port;
if (reason == OFPPR_DELETE) {
VLOG_WARN("bridge %s: interface %s deleted unexpectedly",
br->name, iface->name);
iface_destroy(iface);
if (!port->n_ifaces) {
VLOG_WARN("bridge %s: port %s has no interfaces, dropping",
br->name, port->name);
port_destroy(port);
}
bridge_flush(br);
} else {
if (port->n_ifaces > 1) {
bool up = !(opp->state & OFPPS_LINK_DOWN);
bond_link_status_update(iface, up);
port_update_bond_compat(port);
}
}
}
static bool
bridge_normal_ofhook_cb(const flow_t *flow, const struct ofpbuf *packet,
struct odp_actions *actions, tag_type *tags,
uint16_t *nf_output_iface, void *br_)
{
struct bridge *br = br_;
#if 0
if (flow->dl_type == htons(OFP_DL_TYPE_NOT_ETH_TYPE)
&& eth_addr_equals(flow->dl_dst, stp_eth_addr)) {
brstp_receive(br, flow, payload);
return true;
}
#endif
COVERAGE_INC(bridge_process_flow);
return process_flow(br, flow, packet, actions, tags, nf_output_iface);
}
static void
bridge_account_flow_ofhook_cb(const flow_t *flow,
const union odp_action *actions,
size_t n_actions, unsigned long long int n_bytes,
void *br_)
{
struct bridge *br = br_;
struct port *in_port;
const union odp_action *a;
/* Feed information from the active flows back into the learning table
* to ensure that table is always in sync with what is actually flowing
* through the datapath. */
in_port = port_from_dp_ifidx(br, flow->in_port);
if (in_port) {
int vlan = flow_get_vlan(br, flow, in_port, false);
if (vlan >= 0) {
update_learning_table(br, flow, vlan, in_port);
}
}
if (!br->has_bonded_ports) {
return;
}
for (a = actions; a < &actions[n_actions]; a++) {
if (a->type == ODPAT_OUTPUT) {
struct port *out_port = port_from_dp_ifidx(br, a->output.port);
if (out_port && out_port->n_ifaces >= 2) {
struct bond_entry *e = lookup_bond_entry(out_port,
flow->dl_src);
e->tx_bytes += n_bytes;
}
}
}
}
static void
bridge_account_checkpoint_ofhook_cb(void *br_)
{
struct bridge *br = br_;
size_t i;
if (!br->has_bonded_ports) {
return;
}
/* The current ofproto implementation calls this callback at least once a
* second, so this timer implementation is sufficient. */
if (time_msec() < br->bond_next_rebalance) {
return;
}
br->bond_next_rebalance = time_msec() + 10000;
for (i = 0; i < br->n_ports; i++) {
struct port *port = br->ports[i];
if (port->n_ifaces > 1) {
bond_rebalance_port(port);
}
}
}
static struct ofhooks bridge_ofhooks = {
bridge_port_changed_ofhook_cb,
bridge_normal_ofhook_cb,
bridge_account_flow_ofhook_cb,
bridge_account_checkpoint_ofhook_cb,
};
/* Bonding functions. */
/* Statistics for a single interface on a bonded port, used for load-based
* bond rebalancing. */
struct slave_balance {
struct iface *iface; /* The interface. */
uint64_t tx_bytes; /* Sum of hashes[*]->tx_bytes. */
/* All the "bond_entry"s that are assigned to this interface, in order of
* increasing tx_bytes. */
struct bond_entry **hashes;
size_t n_hashes;
};
/* Sorts pointers to pointers to bond_entries in ascending order by the
* interface to which they are assigned, and within a single interface in
* ascending order of bytes transmitted. */
static int
compare_bond_entries(const void *a_, const void *b_)
{
const struct bond_entry *const *ap = a_;
const struct bond_entry *const *bp = b_;
const struct bond_entry *a = *ap;
const struct bond_entry *b = *bp;
if (a->iface_idx != b->iface_idx) {
return a->iface_idx > b->iface_idx ? 1 : -1;
} else if (a->tx_bytes != b->tx_bytes) {
return a->tx_bytes > b->tx_bytes ? 1 : -1;
} else {
return 0;
}
}
/* Sorts slave_balances so that enabled ports come first, and otherwise in
* *descending* order by number of bytes transmitted. */
static int
compare_slave_balance(const void *a_, const void *b_)
{
const struct slave_balance *a = a_;
const struct slave_balance *b = b_;
if (a->iface->enabled != b->iface->enabled) {
return a->iface->enabled ? -1 : 1;
} else if (a->tx_bytes != b->tx_bytes) {
return a->tx_bytes > b->tx_bytes ? -1 : 1;
} else {
return 0;
}
}
static void
swap_bals(struct slave_balance *a, struct slave_balance *b)
{
struct slave_balance tmp = *a;
*a = *b;
*b = tmp;
}
/* Restores the 'n_bals' slave_balance structures in 'bals' to sorted order
* given that 'p' (and only 'p') might be in the wrong location.
*
* This function invalidates 'p', since it might now be in a different memory
* location. */
static void
resort_bals(struct slave_balance *p,
struct slave_balance bals[], size_t n_bals)
{
if (n_bals > 1) {
for (; p > bals && p->tx_bytes > p[-1].tx_bytes; p--) {
swap_bals(p, p - 1);
}
for (; p < &bals[n_bals - 1] && p->tx_bytes < p[1].tx_bytes; p++) {
swap_bals(p, p + 1);
}
}
}
static void
log_bals(const struct slave_balance *bals, size_t n_bals, struct port *port)
{
if (VLOG_IS_DBG_ENABLED()) {
struct ds ds = DS_EMPTY_INITIALIZER;
const struct slave_balance *b;
for (b = bals; b < bals + n_bals; b++) {
size_t i;
if (b > bals) {
ds_put_char(&ds, ',');
}
ds_put_format(&ds, " %s %"PRIu64"kB",
b->iface->name, b->tx_bytes / 1024);
if (!b->iface->enabled) {
ds_put_cstr(&ds, " (disabled)");
}
if (b->n_hashes > 0) {
ds_put_cstr(&ds, " (");
for (i = 0; i < b->n_hashes; i++) {
const struct bond_entry *e = b->hashes[i];
if (i > 0) {
ds_put_cstr(&ds, " + ");
}
ds_put_format(&ds, "h%td: %"PRIu64"kB",
e - port->bond_hash, e->tx_bytes / 1024);
}
ds_put_cstr(&ds, ")");
}
}
VLOG_DBG("bond %s:%s", port->name, ds_cstr(&ds));
ds_destroy(&ds);
}
}
/* Shifts 'hash' from 'from' to 'to' within 'port'. */
static void
bond_shift_load(struct slave_balance *from, struct slave_balance *to,
int hash_idx)
{
struct bond_entry *hash = from->hashes[hash_idx];
struct port *port = from->iface->port;
uint64_t delta = hash->tx_bytes;
VLOG_INFO("bond %s: shift %"PRIu64"kB of load (with hash %td) "
"from %s to %s (now carrying %"PRIu64"kB and "
"%"PRIu64"kB load, respectively)",
port->name, delta / 1024, hash - port->bond_hash,
from->iface->name, to->iface->name,
(from->tx_bytes - delta) / 1024,
(to->tx_bytes + delta) / 1024);
/* Delete element from from->hashes.
*
* We don't bother to add the element to to->hashes because not only would
* it require more work, the only purpose it would be to allow that hash to
* be migrated to another slave in this rebalancing run, and there is no
* point in doing that. */
if (hash_idx == 0) {
from->hashes++;
} else {
memmove(from->hashes + hash_idx, from->hashes + hash_idx + 1,
(from->n_hashes - (hash_idx + 1)) * sizeof *from->hashes);
}
from->n_hashes--;
/* Shift load away from 'from' to 'to'. */
from->tx_bytes -= delta;
to->tx_bytes += delta;
/* Arrange for flows to be revalidated. */
ofproto_revalidate(port->bridge->ofproto, hash->iface_tag);
hash->iface_idx = to->iface->port_ifidx;
hash->iface_tag = tag_create_random();
}
static void
bond_rebalance_port(struct port *port)
{
struct slave_balance bals[DP_MAX_PORTS];
size_t n_bals;
struct bond_entry *hashes[BOND_MASK + 1];
struct slave_balance *b, *from, *to;
struct bond_entry *e;
size_t i;
/* Sets up 'bals' to describe each of the port's interfaces, sorted in
* descending order of tx_bytes, so that bals[0] represents the most
* heavily loaded slave and bals[n_bals - 1] represents the least heavily
* loaded slave.
*
* The code is a bit tricky: to avoid dynamically allocating a 'hashes'
* array for each slave_balance structure, we sort our local array of
* hashes in order by slave, so that all of the hashes for a given slave
* become contiguous in memory, and then we point each 'hashes' members of
* a slave_balance structure to the start of a contiguous group. */
n_bals = port->n_ifaces;
for (b = bals; b < &bals[n_bals]; b++) {
b->iface = port->ifaces[b - bals];
b->tx_bytes = 0;
b->hashes = NULL;
b->n_hashes = 0;
}
for (i = 0; i <= BOND_MASK; i++) {
hashes[i] = &port->bond_hash[i];
}
qsort(hashes, BOND_MASK + 1, sizeof *hashes, compare_bond_entries);
for (i = 0; i <= BOND_MASK; i++) {
e = hashes[i];
if (e->iface_idx >= 0 && e->iface_idx < port->n_ifaces) {
b = &bals[e->iface_idx];
b->tx_bytes += e->tx_bytes;
if (!b->hashes) {
b->hashes = &hashes[i];
}
b->n_hashes++;
}
}
qsort(bals, n_bals, sizeof *bals, compare_slave_balance);
log_bals(bals, n_bals, port);
/* Discard slaves that aren't enabled (which were sorted to the back of the
* array earlier). */
while (!bals[n_bals - 1].iface->enabled) {
n_bals--;
if (!n_bals) {
return;
}
}
/* Shift load from the most-loaded slaves to the least-loaded slaves. */
to = &bals[n_bals - 1];
for (from = bals; from < to; ) {
uint64_t overload = from->tx_bytes - to->tx_bytes;
if (overload < to->tx_bytes >> 5 || overload < 100000) {
/* The extra load on 'from' (and all less-loaded slaves), compared
* to that of 'to' (the least-loaded slave), is less than ~3%, or
* it is less than ~1Mbps. No point in rebalancing. */
break;
} else if (from->n_hashes == 1) {
/* 'from' only carries a single MAC hash, so we can't shift any
* load away from it, even though we want to. */
from++;
} else {
/* 'from' is carrying significantly more load than 'to', and that
* load is split across at least two different hashes. Pick a hash
* to migrate to 'to' (the least-loaded slave), given that doing so
* must decrease the ratio of the load on the two slaves by at
* least 0.1.
*
* The sort order we use means that we prefer to shift away the
* smallest hashes instead of the biggest ones. There is little
* reason behind this decision; we could use the opposite sort
* order to shift away big hashes ahead of small ones. */
size_t i;
bool order_swapped;
for (i = 0; i < from->n_hashes; i++) {
double old_ratio, new_ratio;
uint64_t delta = from->hashes[i]->tx_bytes;
if (delta == 0 || from->tx_bytes - delta == 0) {
/* Pointless move. */
continue;
}
order_swapped = from->tx_bytes - delta < to->tx_bytes + delta;
if (to->tx_bytes == 0) {
/* Nothing on the new slave, move it. */
break;
}
old_ratio = (double)from->tx_bytes / to->tx_bytes;
new_ratio = (double)(from->tx_bytes - delta) /
(to->tx_bytes + delta);
if (new_ratio == 0) {
/* Should already be covered but check to prevent division
* by zero. */
continue;
}
if (new_ratio < 1) {
new_ratio = 1 / new_ratio;
}
if (old_ratio - new_ratio > 0.1) {
/* Would decrease the ratio, move it. */
break;
}
}
if (i < from->n_hashes) {
bond_shift_load(from, to, i);
port->bond_compat_is_stale = true;
/* If the result of the migration changed the relative order of
* 'from' and 'to' swap them back to maintain invariants. */
if (order_swapped) {
swap_bals(from, to);
}
/* Re-sort 'bals'. Note that this may make 'from' and 'to'
* point to different slave_balance structures. It is only
* valid to do these two operations in a row at all because we
* know that 'from' will not move past 'to' and vice versa. */
resort_bals(from, bals, n_bals);
resort_bals(to, bals, n_bals);
} else {
from++;
}
}
}
/* Implement exponentially weighted moving average. A weight of 1/2 causes
* historical data to decay to <1% in 7 rebalancing runs. */
for (e = &port->bond_hash[0]; e <= &port->bond_hash[BOND_MASK]; e++) {
e->tx_bytes /= 2;
}
}
static void
bond_send_learning_packets(struct port *port)
{
struct bridge *br = port->bridge;
struct mac_entry *e;
struct ofpbuf packet;
int error, n_packets, n_errors;
if (!port->n_ifaces || port->active_iface < 0) {
return;
}
ofpbuf_init(&packet, 128);
error = n_packets = n_errors = 0;
LIST_FOR_EACH (e, struct mac_entry, lru_node, &br->ml->lrus) {
union ofp_action actions[2], *a;
uint16_t dp_ifidx;
tag_type tags = 0;
flow_t flow;
int retval;
if (e->port == port->port_idx
|| !choose_output_iface(port, e->mac, &dp_ifidx, &tags)) {
continue;
}
/* Compose actions. */
memset(actions, 0, sizeof actions);
a = actions;
if (e->vlan) {
a->vlan_vid.type = htons(OFPAT_SET_VLAN_VID);
a->vlan_vid.len = htons(sizeof *a);
a->vlan_vid.vlan_vid = htons(e->vlan);
a++;
}
a->output.type = htons(OFPAT_OUTPUT);
a->output.len = htons(sizeof *a);
a->output.port = htons(odp_port_to_ofp_port(dp_ifidx));
a++;
/* Send packet. */
n_packets++;
compose_benign_packet(&packet, "Open vSwitch Bond Failover", 0xf177,
e->mac);
flow_extract(&packet, ODPP_NONE, &flow);
retval = ofproto_send_packet(br->ofproto, &flow, actions, a - actions,
&packet);
if (retval) {
error = retval;
n_errors++;
}
}
ofpbuf_uninit(&packet);
if (n_errors) {
static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
VLOG_WARN_RL(&rl, "bond %s: %d errors sending %d gratuitous learning "
"packets, last error was: %s",
port->name, n_errors, n_packets, strerror(error));
} else {
VLOG_DBG("bond %s: sent %d gratuitous learning packets",
port->name, n_packets);
}
}
/* Bonding unixctl user interface functions. */
static void
bond_unixctl_list(struct unixctl_conn *conn, const char *args UNUSED)
{
struct ds ds = DS_EMPTY_INITIALIZER;
const struct bridge *br;
ds_put_cstr(&ds, "bridge\tbond\tslaves\n");
LIST_FOR_EACH (br, struct bridge, node, &all_bridges) {
size_t i;
for (i = 0; i < br->n_ports; i++) {
const struct port *port = br->ports[i];
if (port->n_ifaces > 1) {
size_t j;
ds_put_format(&ds, "%s\t%s\t", br->name, port->name);
for (j = 0; j < port->n_ifaces; j++) {
const struct iface *iface = port->ifaces[j];
if (j) {
ds_put_cstr(&ds, ", ");
}
ds_put_cstr(&ds, iface->name);
}
ds_put_char(&ds, '\n');
}
}
}
unixctl_command_reply(conn, 200, ds_cstr(&ds));
ds_destroy(&ds);
}
static struct port *
bond_find(const char *name)
{
const struct bridge *br;
LIST_FOR_EACH (br, struct bridge, node, &all_bridges) {
size_t i;
for (i = 0; i < br->n_ports; i++) {
struct port *port = br->ports[i];
if (!strcmp(port->name, name) && port->n_ifaces > 1) {
return port;
}
}
}
return NULL;
}
static void
bond_unixctl_show(struct unixctl_conn *conn, const char *args)
{
struct ds ds = DS_EMPTY_INITIALIZER;
const struct port *port;
size_t j;
port = bond_find(args);
if (!port) {
unixctl_command_reply(conn, 501, "no such bond");
return;
}
ds_put_format(&ds, "updelay: %d ms\n", port->updelay);
ds_put_format(&ds, "downdelay: %d ms\n", port->downdelay);
ds_put_format(&ds, "next rebalance: %lld ms\n",
port->bridge->bond_next_rebalance - time_msec());
for (j = 0; j < port->n_ifaces; j++) {
const struct iface *iface = port->ifaces[j];
struct bond_entry *be;
/* Basic info. */
ds_put_format(&ds, "slave %s: %s\n",
iface->name, iface->enabled ? "enabled" : "disabled");
if (j == port->active_iface) {
ds_put_cstr(&ds, "\tactive slave\n");
}
if (iface->delay_expires != LLONG_MAX) {
ds_put_format(&ds, "\t%s expires in %lld ms\n",
iface->enabled ? "downdelay" : "updelay",
iface->delay_expires - time_msec());
}
/* Hashes. */
for (be = port->bond_hash; be <= &port->bond_hash[BOND_MASK]; be++) {
int hash = be - port->bond_hash;
struct mac_entry *me;
if (be->iface_idx != j) {
continue;
}
ds_put_format(&ds, "\thash %d: %"PRIu64" kB load\n",
hash, be->tx_bytes / 1024);
/* MACs. */
LIST_FOR_EACH (me, struct mac_entry, lru_node,
&port->bridge->ml->lrus) {
uint16_t dp_ifidx;
tag_type tags = 0;
if (bond_hash(me->mac) == hash
&& me->port != port->port_idx
&& choose_output_iface(port, me->mac, &dp_ifidx, &tags)
&& dp_ifidx == iface->dp_ifidx)
{
ds_put_format(&ds, "\t\t"ETH_ADDR_FMT"\n",
ETH_ADDR_ARGS(me->mac));
}
}
}
}
unixctl_command_reply(conn, 200, ds_cstr(&ds));
ds_destroy(&ds);
}
static void
bond_unixctl_migrate(struct unixctl_conn *conn, const char *args_)
{
char *args = (char *) args_;
char *save_ptr = NULL;
char *bond_s, *hash_s, *slave_s;
uint8_t mac[ETH_ADDR_LEN];
struct port *port;
struct iface *iface;
struct bond_entry *entry;
int hash;
bond_s = strtok_r(args, " ", &save_ptr);
hash_s = strtok_r(NULL, " ", &save_ptr);
slave_s = strtok_r(NULL, " ", &save_ptr);
if (!slave_s) {
unixctl_command_reply(conn, 501,
"usage: bond/migrate BOND HASH SLAVE");
return;
}
port = bond_find(bond_s);
if (!port) {
unixctl_command_reply(conn, 501, "no such bond");
return;
}
if (sscanf(hash_s, ETH_ADDR_SCAN_FMT, ETH_ADDR_SCAN_ARGS(mac))
== ETH_ADDR_SCAN_COUNT) {
hash = bond_hash(mac);
} else if (strspn(hash_s, "0123456789") == strlen(hash_s)) {
hash = atoi(hash_s) & BOND_MASK;
} else {
unixctl_command_reply(conn, 501, "bad hash");
return;
}
iface = port_lookup_iface(port, slave_s);
if (!iface) {
unixctl_command_reply(conn, 501, "no such slave");
return;
}
if (!iface->enabled) {
unixctl_command_reply(conn, 501, "cannot migrate to disabled slave");
return;
}
entry = &port->bond_hash[hash];
ofproto_revalidate(port->bridge->ofproto, entry->iface_tag);
entry->iface_idx = iface->port_ifidx;
entry->iface_tag = tag_create_random();
port->bond_compat_is_stale = true;
unixctl_command_reply(conn, 200, "migrated");
}
static void
bond_unixctl_set_active_slave(struct unixctl_conn *conn, const char *args_)
{
char *args = (char *) args_;
char *save_ptr = NULL;
char *bond_s, *slave_s;
struct port *port;
struct iface *iface;
bond_s = strtok_r(args, " ", &save_ptr);
slave_s = strtok_r(NULL, " ", &save_ptr);
if (!slave_s) {
unixctl_command_reply(conn, 501,
"usage: bond/set-active-slave BOND SLAVE");
return;
}
port = bond_find(bond_s);
if (!port) {
unixctl_command_reply(conn, 501, "no such bond");
return;
}
iface = port_lookup_iface(port, slave_s);
if (!iface) {
unixctl_command_reply(conn, 501, "no such slave");
return;
}
if (!iface->enabled) {
unixctl_command_reply(conn, 501, "cannot make disabled slave active");
return;
}
if (port->active_iface != iface->port_ifidx) {
ofproto_revalidate(port->bridge->ofproto, port->active_iface_tag);
port->active_iface = iface->port_ifidx;
port->active_iface_tag = tag_create_random();
VLOG_INFO("port %s: active interface is now %s",
port->name, iface->name);
bond_send_learning_packets(port);
unixctl_command_reply(conn, 200, "done");
} else {
unixctl_command_reply(conn, 200, "no change");
}
}
static void
enable_slave(struct unixctl_conn *conn, const char *args_, bool enable)
{
char *args = (char *) args_;
char *save_ptr = NULL;
char *bond_s, *slave_s;
struct port *port;
struct iface *iface;
bond_s = strtok_r(args, " ", &save_ptr);
slave_s = strtok_r(NULL, " ", &save_ptr);
if (!slave_s) {
unixctl_command_reply(conn, 501,
"usage: bond/enable/disable-slave BOND SLAVE");
return;
}
port = bond_find(bond_s);
if (!port) {
unixctl_command_reply(conn, 501, "no such bond");
return;
}
iface = port_lookup_iface(port, slave_s);
if (!iface) {
unixctl_command_reply(conn, 501, "no such slave");
return;
}
bond_enable_slave(iface, enable);
unixctl_command_reply(conn, 501, enable ? "enabled" : "disabled");
}
static void
bond_unixctl_enable_slave(struct unixctl_conn *conn, const char *args)
{
enable_slave(conn, args, true);
}
static void
bond_unixctl_disable_slave(struct unixctl_conn *conn, const char *args)
{
enable_slave(conn, args, false);
}
static void
bond_unixctl_hash(struct unixctl_conn *conn, const char *args)
{
uint8_t mac[ETH_ADDR_LEN];
uint8_t hash;
char *hash_cstr;
if (sscanf(args, ETH_ADDR_SCAN_FMT, ETH_ADDR_SCAN_ARGS(mac))
== ETH_ADDR_SCAN_COUNT) {
hash = bond_hash(mac);
hash_cstr = xasprintf("%u", hash);
unixctl_command_reply(conn, 200, hash_cstr);
free(hash_cstr);
} else {
unixctl_command_reply(conn, 501, "invalid mac");
}
}
static void
bond_init(void)
{
unixctl_command_register("bond/list", bond_unixctl_list);
unixctl_command_register("bond/show", bond_unixctl_show);
unixctl_command_register("bond/migrate", bond_unixctl_migrate);
unixctl_command_register("bond/set-active-slave",
bond_unixctl_set_active_slave);
unixctl_command_register("bond/enable-slave", bond_unixctl_enable_slave);
unixctl_command_register("bond/disable-slave", bond_unixctl_disable_slave);
unixctl_command_register("bond/hash", bond_unixctl_hash);
}
/* Port functions. */
static void
port_create(struct bridge *br, const char *name)
{
struct port *port;
port = xcalloc(1, sizeof *port);
port->bridge = br;
port->port_idx = br->n_ports;
port->vlan = -1;
port->trunks = NULL;
port->name = xstrdup(name);
port->active_iface = -1;
port->stp_state = STP_DISABLED;
port->stp_state_tag = 0;
if (br->n_ports >= br->allocated_ports) {
br->ports = x2nrealloc(br->ports, &br->allocated_ports,
sizeof *br->ports);
}
br->ports[br->n_ports++] = port;
VLOG_INFO("created port %s on bridge %s", port->name, br->name);
bridge_flush(br);
}
static void
port_reconfigure(struct port *port)
{
bool bonded = cfg_has_section("bonding.%s", port->name);
struct svec old_ifaces, new_ifaces;
unsigned long *trunks;
int vlan;
size_t i;
/* Collect old and new interfaces. */
svec_init(&old_ifaces);
svec_init(&new_ifaces);
for (i = 0; i < port->n_ifaces; i++) {
svec_add(&old_ifaces, port->ifaces[i]->name);
}
svec_sort(&old_ifaces);
if (bonded) {
cfg_get_all_keys(&new_ifaces, "bonding.%s.slave", port->name);
if (!new_ifaces.n) {
VLOG_ERR("port %s: no interfaces specified for bonded port",
port->name);
} else if (new_ifaces.n == 1) {
VLOG_WARN("port %s: only 1 interface specified for bonded port",
port->name);
}
port->updelay = cfg_get_int(0, "bonding.%s.updelay", port->name);
if (port->updelay < 0) {
port->updelay = 0;
}
port->downdelay = cfg_get_int(0, "bonding.%s.downdelay", port->name);
if (port->downdelay < 0) {
port->downdelay = 0;
}
} else {
svec_init(&new_ifaces);
svec_add(&new_ifaces, port->name);
}
/* Get rid of deleted interfaces and add new interfaces. */
for (i = 0; i < port->n_ifaces; i++) {
struct iface *iface = port->ifaces[i];
if (!svec_contains(&new_ifaces, iface->name)) {
iface_destroy(iface);
} else {
i++;
}
}
for (i = 0; i < new_ifaces.n; i++) {
const char *name = new_ifaces.names[i];
if (!svec_contains(&old_ifaces, name)) {
iface_create(port, name);
}
}
/* Get VLAN tag. */
vlan = -1;
if (cfg_has("vlan.%s.tag", port->name)) {
if (!bonded) {
vlan = cfg_get_vlan(0, "vlan.%s.tag", port->name);
if (vlan >= 0 && vlan <= 4095) {
VLOG_DBG("port %s: assigning VLAN tag %d", port->name, vlan);
}
} else {
/* It's possible that bonded, VLAN-tagged ports make sense. Maybe
* they even work as-is. But they have not been tested. */
VLOG_WARN("port %s: VLAN tags not supported on bonded ports",
port->name);
}
}
if (port->vlan != vlan) {
port->vlan = vlan;
bridge_flush(port->bridge);
}
/* Get trunked VLANs. */
trunks = NULL;
if (vlan < 0) {
size_t n_trunks, n_errors;
size_t i;
trunks = bitmap_allocate(4096);
n_trunks = cfg_count("vlan.%s.trunks", port->name);
n_errors = 0;
for (i = 0; i < n_trunks; i++) {
int trunk = cfg_get_vlan(i, "vlan.%s.trunks", port->name);
if (trunk >= 0) {
bitmap_set1(trunks, trunk);
} else {
n_errors++;
}
}
if (n_errors) {
VLOG_ERR("port %s: invalid values for %zu trunk VLANs",
port->name, n_trunks);
}
if (n_errors == n_trunks) {
if (n_errors) {
VLOG_ERR("port %s: no valid trunks, trunking all VLANs",
port->name);
}
bitmap_set_multiple(trunks, 0, 4096, 1);
}
} else {
if (cfg_has("vlan.%s.trunks", port->name)) {
VLOG_ERR("ignoring vlan.%s.trunks in favor of vlan.%s.vlan",
port->name, port->name);
}
}
if (trunks == NULL
? port->trunks != NULL
: port->trunks == NULL || !bitmap_equal(trunks, port->trunks, 4096)) {
bridge_flush(port->bridge);
}
bitmap_free(port->trunks);
port->trunks = trunks;
svec_destroy(&old_ifaces);
svec_destroy(&new_ifaces);
}
static void
port_destroy(struct port *port)
{
if (port) {
struct bridge *br = port->bridge;
struct port *del;
size_t i;
proc_net_compat_update_vlan(port->name, NULL, 0);
proc_net_compat_update_bond(port->name, NULL);
for (i = 0; i < MAX_MIRRORS; i++) {
struct mirror *m = br->mirrors[i];
if (m && m->out_port == port) {
mirror_destroy(m);
}
}
while (port->n_ifaces > 0) {
iface_destroy(port->ifaces[port->n_ifaces - 1]);
}
del = br->ports[port->port_idx] = br->ports[--br->n_ports];
del->port_idx = port->port_idx;
free(port->ifaces);
bitmap_free(port->trunks);
free(port->name);
free(port);
bridge_flush(br);
}
}
static struct port *
port_from_dp_ifidx(const struct bridge *br, uint16_t dp_ifidx)
{
struct iface *iface = iface_from_dp_ifidx(br, dp_ifidx);
return iface ? iface->port : NULL;
}
static struct port *
port_lookup(const struct bridge *br, const char *name)
{
size_t i;
for (i = 0; i < br->n_ports; i++) {
struct port *port = br->ports[i];
if (!strcmp(port->name, name)) {
return port;
}
}
return NULL;
}
static struct iface *
port_lookup_iface(const struct port *port, const char *name)
{
size_t j;
for (j = 0; j < port->n_ifaces; j++) {
struct iface *iface = port->ifaces[j];
if (!strcmp(iface->name, name)) {
return iface;
}
}
return NULL;
}
static void
port_update_bonding(struct port *port)
{
if (port->n_ifaces < 2) {
/* Not a bonded port. */
if (port->bond_hash) {
free(port->bond_hash);
port->bond_hash = NULL;
port->bond_compat_is_stale = true;
}
} else {
if (!port->bond_hash) {
size_t i;
port->bond_hash = xcalloc(BOND_MASK + 1, sizeof *port->bond_hash);
for (i = 0; i <= BOND_MASK; i++) {
struct bond_entry *e = &port->bond_hash[i];
e->iface_idx = -1;
e->tx_bytes = 0;
}
port->no_ifaces_tag = tag_create_random();
bond_choose_active_iface(port);
}
port->bond_compat_is_stale = true;
}
}
static void
port_update_bond_compat(struct port *port)
{
struct compat_bond_hash compat_hashes[BOND_MASK + 1];
struct compat_bond bond;
size_t i;
if (port->n_ifaces < 2) {
proc_net_compat_update_bond(port->name, NULL);
return;
}
bond.up = false;
bond.updelay = port->updelay;
bond.downdelay = port->downdelay;
bond.n_hashes = 0;
bond.hashes = compat_hashes;
if (port->bond_hash) {
const struct bond_entry *e;
for (e = port->bond_hash; e <= &port->bond_hash[BOND_MASK]; e++) {
if (e->iface_idx >= 0 && e->iface_idx < port->n_ifaces) {
struct compat_bond_hash *cbh = &bond.hashes[bond.n_hashes++];
cbh->hash = e - port->bond_hash;
cbh->netdev_name = port->ifaces[e->iface_idx]->name;
}
}
}
bond.n_slaves = port->n_ifaces;
bond.slaves = xmalloc(port->n_ifaces * sizeof *bond.slaves);
for (i = 0; i < port->n_ifaces; i++) {
struct iface *iface = port->ifaces[i];
struct compat_bond_slave *slave = &bond.slaves[i];
slave->name = iface->name;
/* We need to make the same determination as the Linux bonding
* code to determine whether a slave should be consider "up".
* The Linux function bond_miimon_inspect() supports four
* BOND_LINK_* states:
*
* - BOND_LINK_UP: carrier detected, updelay has passed.
* - BOND_LINK_FAIL: carrier lost, downdelay in progress.
* - BOND_LINK_DOWN: carrier lost, downdelay has passed.
* - BOND_LINK_BACK: carrier detected, updelay in progress.
*
* The function bond_info_show_slave() only considers BOND_LINK_UP
* to be "up" and anything else to be "down".
*/
slave->up = iface->enabled && iface->delay_expires == LLONG_MAX;
if (slave->up) {
bond.up = true;
}
netdev_get_etheraddr(iface->netdev, slave->mac);
}
if (cfg_get_bool(0, "bonding.%s.fake-iface", port->name)) {
struct netdev *bond_netdev;
if (!netdev_open(port->name, NETDEV_ETH_TYPE_NONE, &bond_netdev)) {
if (bond.up) {
netdev_turn_flags_on(bond_netdev, NETDEV_UP, true);
} else {
netdev_turn_flags_off(bond_netdev, NETDEV_UP, true);
}
netdev_close(bond_netdev);
}
}
proc_net_compat_update_bond(port->name, &bond);
free(bond.slaves);
}
static void
port_update_vlan_compat(struct port *port)
{
struct bridge *br = port->bridge;
char *vlandev_name = NULL;
if (port->vlan > 0) {
/* Figure out the name that the VLAN device should actually have, if it
* existed. This takes some work because the VLAN device would not
* have port->name in its name; rather, it would have the trunk port's
* name, and 'port' would be attached to a bridge that also had the
* VLAN device one of its ports. So we need to find a trunk port that
* includes port->vlan.
*
* There might be more than one candidate. This doesn't happen on
* XenServer, so if it happens we just pick the first choice in
* alphabetical order instead of creating multiple VLAN devices. */
size_t i;
for (i = 0; i < br->n_ports; i++) {
struct port *p = br->ports[i];
if (port_trunks_vlan(p, port->vlan)
&& p->n_ifaces
&& (!vlandev_name || strcmp(p->name, vlandev_name) <= 0))
{
uint8_t ea[ETH_ADDR_LEN];
netdev_get_etheraddr(p->ifaces[0]->netdev, ea);
if (!eth_addr_is_multicast(ea) &&
!eth_addr_is_reserved(ea) &&
!eth_addr_is_zero(ea)) {
vlandev_name = p->name;
}
}
}
}
proc_net_compat_update_vlan(port->name, vlandev_name, port->vlan);
}
/* Interface functions. */
static void
iface_create(struct port *port, const char *name)
{
struct iface *iface;
iface = xcalloc(1, sizeof *iface);
iface->port = port;
iface->port_ifidx = port->n_ifaces;
iface->name = xstrdup(name);
iface->dp_ifidx = -1;
iface->tag = tag_create_random();
iface->delay_expires = LLONG_MAX;
iface->netdev = NULL;
if (port->n_ifaces >= port->allocated_ifaces) {
port->ifaces = x2nrealloc(port->ifaces, &port->allocated_ifaces,
sizeof *port->ifaces);
}
port->ifaces[port->n_ifaces++] = iface;
if (port->n_ifaces > 1) {
port->bridge->has_bonded_ports = true;
}
VLOG_DBG("attached network device %s to port %s", iface->name, port->name);
bridge_flush(port->bridge);
}
static void
iface_destroy(struct iface *iface)
{
if (iface) {
struct port *port = iface->port;
struct bridge *br = port->bridge;
bool del_active = port->active_iface == iface->port_ifidx;
struct iface *del;
if (iface->dp_ifidx >= 0) {
port_array_set(&br->ifaces, iface->dp_ifidx, NULL);
}
del = port->ifaces[iface->port_ifidx] = port->ifaces[--port->n_ifaces];
del->port_ifidx = iface->port_ifidx;
netdev_close(iface->netdev);
free(iface->name);
free(iface);
if (del_active) {
ofproto_revalidate(port->bridge->ofproto, port->active_iface_tag);
bond_choose_active_iface(port);
bond_send_learning_packets(port);
}
bridge_flush(port->bridge);
}
}
static struct iface *
iface_lookup(const struct bridge *br, const char *name)
{
size_t i, j;
for (i = 0; i < br->n_ports; i++) {
struct port *port = br->ports[i];
for (j = 0; j < port->n_ifaces; j++) {
struct iface *iface = port->ifaces[j];
if (!strcmp(iface->name, name)) {
return iface;
}
}
}
return NULL;
}
static struct iface *
iface_from_dp_ifidx(const struct bridge *br, uint16_t dp_ifidx)
{
return port_array_get(&br->ifaces, dp_ifidx);
}
/* Returns true if 'iface' is the name of an "internal" interface on bridge
* 'br', that is, an interface that is entirely simulated within the datapath.
* The local port (ODPP_LOCAL) is always an internal interface. Other local
* interfaces are created by setting "iface.<iface>.internal = true".
*
* In addition, we have a kluge-y feature that creates an internal port with
* the name of a bonded port if "bonding.<bondname>.fake-iface = true" is set.
* This feature needs to go away in the long term. Until then, this is one
* reason why this function takes a name instead of a struct iface: the fake
* interfaces created this way do not have a struct iface. */
static bool
iface_is_internal(const struct bridge *br, const char *iface)
{
if (!strcmp(iface, br->name)
|| cfg_get_bool(0, "iface.%s.internal", iface)) {
return true;
}
if (cfg_get_bool(0, "bonding.%s.fake-iface", iface)) {
struct port *port = port_lookup(br, iface);
if (port && port->n_ifaces > 1) {
return true;
}
}
return false;
}
/* Set Ethernet address of 'iface', if one is specified in the configuration
* file. */
static void
iface_set_mac(struct iface *iface)
{
uint64_t mac = cfg_get_mac(0, "iface.%s.mac", iface->name);
if (mac) {
static uint8_t ea[ETH_ADDR_LEN];
eth_addr_from_uint64(mac, ea);
if (eth_addr_is_multicast(ea)) {
VLOG_ERR("interface %s: cannot set MAC to multicast address",
iface->name);
} else if (iface->dp_ifidx == ODPP_LOCAL) {
VLOG_ERR("ignoring iface.%s.mac; use bridge.%s.mac instead",
iface->name, iface->name);
} else {
int error = netdev_set_etheraddr(iface->netdev, ea);
if (error) {
VLOG_ERR("interface %s: setting MAC failed (%s)",
iface->name, strerror(error));
}
}
}
}
/* Port mirroring. */
static void
mirror_reconfigure(struct bridge *br)
{
struct svec old_mirrors, new_mirrors;
size_t i, n_rspan_vlans;
unsigned long *rspan_vlans;
/* Collect old and new mirrors. */
svec_init(&old_mirrors);
svec_init(&new_mirrors);
cfg_get_subsections(&new_mirrors, "mirror.%s", br->name);
for (i = 0; i < MAX_MIRRORS; i++) {
if (br->mirrors[i]) {
svec_add(&old_mirrors, br->mirrors[i]->name);
}
}
/* Get rid of deleted mirrors and add new mirrors. */
svec_sort(&old_mirrors);
assert(svec_is_unique(&old_mirrors));
svec_sort(&new_mirrors);
assert(svec_is_unique(&new_mirrors));
for (i = 0; i < MAX_MIRRORS; i++) {
struct mirror *m = br->mirrors[i];
if (m && !svec_contains(&new_mirrors, m->name)) {
mirror_destroy(m);
}
}
for (i = 0; i < new_mirrors.n; i++) {
const char *name = new_mirrors.names[i];
if (!svec_contains(&old_mirrors, name)) {
mirror_create(br, name);
}
}
svec_destroy(&old_mirrors);
svec_destroy(&new_mirrors);
/* Reconfigure all mirrors. */
for (i = 0; i < MAX_MIRRORS; i++) {
if (br->mirrors[i]) {
mirror_reconfigure_one(br->mirrors[i]);
}
}
/* Update port reserved status. */
for (i = 0; i < br->n_ports; i++) {
br->ports[i]->is_mirror_output_port = false;
}
for (i = 0; i < MAX_MIRRORS; i++) {
struct mirror *m = br->mirrors[i];
if (m && m->out_port) {
m->out_port->is_mirror_output_port = true;
}
}
/* Update learning disabled vlans (for RSPAN). */
rspan_vlans = NULL;
n_rspan_vlans = cfg_count("vlan.%s.disable-learning", br->name);
if (n_rspan_vlans) {
rspan_vlans = bitmap_allocate(4096);
for (i = 0; i < n_rspan_vlans; i++) {
int vlan = cfg_get_vlan(i, "vlan.%s.disable-learning", br->name);
if (vlan >= 0) {
bitmap_set1(rspan_vlans, vlan);
VLOG_INFO("bridge %s: disabling learning on vlan %d\n",
br->name, vlan);
} else {
VLOG_ERR("bridge %s: invalid value '%s' for learning disabled "
"VLAN", br->name,
cfg_get_string(i, "vlan.%s.disable-learning", br->name));
}
}
}
if (mac_learning_set_disabled_vlans(br->ml, rspan_vlans)) {
bridge_flush(br);
}
}
static void
mirror_create(struct bridge *br, const char *name)
{
struct mirror *m;
size_t i;
for (i = 0; ; i++) {
if (i >= MAX_MIRRORS) {
VLOG_WARN("bridge %s: maximum of %d port mirrors reached, "
"cannot create %s", br->name, MAX_MIRRORS, name);
return;
}
if (!br->mirrors[i]) {
break;
}
}
VLOG_INFO("created port mirror %s on bridge %s", name, br->name);
bridge_flush(br);
br->mirrors[i] = m = xcalloc(1, sizeof *m);
m->bridge = br;
m->idx = i;
m->name = xstrdup(name);
svec_init(&m->src_ports);
svec_init(&m->dst_ports);
m->vlans = NULL;
m->n_vlans = 0;
m->out_vlan = -1;
m->out_port = NULL;
}
static void
mirror_destroy(struct mirror *m)
{
if (m) {
struct bridge *br = m->bridge;
size_t i;
for (i = 0; i < br->n_ports; i++) {
br->ports[i]->src_mirrors &= ~(MIRROR_MASK_C(1) << m->idx);
br->ports[i]->dst_mirrors &= ~(MIRROR_MASK_C(1) << m->idx);
}
svec_destroy(&m->src_ports);
svec_destroy(&m->dst_ports);
free(m->vlans);
m->bridge->mirrors[m->idx] = NULL;
free(m);
bridge_flush(br);
}
}
static void
prune_ports(struct mirror *m, struct svec *ports)
{
struct svec tmp;
size_t i;
svec_sort_unique(ports);
svec_init(&tmp);
for (i = 0; i < ports->n; i++) {
const char *name = ports->names[i];
if (port_lookup(m->bridge, name)) {
svec_add(&tmp, name);
} else {
VLOG_WARN("mirror.%s.%s: cannot match on nonexistent port %s",
m->bridge->name, m->name, name);
}
}
svec_swap(ports, &tmp);
svec_destroy(&tmp);
}
static size_t
prune_vlans(struct mirror *m, struct svec *vlan_strings, int **vlans)
{
size_t n_vlans, i;
/* This isn't perfect: it won't combine "0" and "00", and the textual sort
* order won't give us numeric sort order. But that's good enough for what
* we need right now. */
svec_sort_unique(vlan_strings);
*vlans = xmalloc(sizeof *vlans * vlan_strings->n);
n_vlans = 0;
for (i = 0; i < vlan_strings->n; i++) {
const char *name = vlan_strings->names[i];
int vlan;
if (!str_to_int(name, 10, &vlan) || vlan < 0 || vlan > 4095) {
VLOG_WARN("mirror.%s.%s.select.vlan: ignoring invalid VLAN %s",
m->bridge->name, m->name, name);
} else {
(*vlans)[n_vlans++] = vlan;
}
}
return n_vlans;
}
static bool
vlan_is_mirrored(const struct mirror *m, int vlan)
{
size_t i;
for (i = 0; i < m->n_vlans; i++) {
if (m->vlans[i] == vlan) {
return true;
}
}
return false;
}
static bool
port_trunks_any_mirrored_vlan(const struct mirror *m, const struct port *p)
{
size_t i;
for (i = 0; i < m->n_vlans; i++) {
if (port_trunks_vlan(p, m->vlans[i])) {
return true;
}
}
return false;
}
static void
mirror_reconfigure_one(struct mirror *m)
{
char *pfx = xasprintf("mirror.%s.%s", m->bridge->name, m->name);
struct svec src_ports, dst_ports, ports;
struct svec vlan_strings;
mirror_mask_t mirror_bit;
const char *out_port_name;
struct port *out_port;
int out_vlan;
size_t n_vlans;
int *vlans;
size_t i;
bool mirror_all_ports;
bool any_ports_specified;
/* Get output port. */
out_port_name = cfg_get_key(0, "mirror.%s.%s.output.port",
m->bridge->name, m->name);
if (out_port_name) {
out_port = port_lookup(m->bridge, out_port_name);
if (!out_port) {
VLOG_ERR("%s.output.port: bridge %s does not have a port "
"named %s", pfx, m->bridge->name, out_port_name);
mirror_destroy(m);
free(pfx);
return;
}
out_vlan = -1;
if (cfg_has("%s.output.vlan", pfx)) {
VLOG_ERR("%s.output.port and %s.output.vlan both specified; "
"ignoring %s.output.vlan", pfx, pfx, pfx);
}
} else if (cfg_has("%s.output.vlan", pfx)) {
out_port = NULL;
out_vlan = cfg_get_vlan(0, "%s.output.vlan", pfx);
} else {
VLOG_ERR("%s: neither %s.output.port nor %s.output.vlan specified, "
"but exactly one is required; disabling port mirror %s",
pfx, pfx, pfx, pfx);
mirror_destroy(m);
free(pfx);
return;
}
/* Get all the ports, and drop duplicates and ports that don't exist. */
svec_init(&src_ports);
svec_init(&dst_ports);
svec_init(&ports);
cfg_get_all_keys(&src_ports, "%s.select.src-port", pfx);
cfg_get_all_keys(&dst_ports, "%s.select.dst-port", pfx);
cfg_get_all_keys(&ports, "%s.select.port", pfx);
any_ports_specified = src_ports.n || dst_ports.n || ports.n;
svec_append(&src_ports, &ports);
svec_append(&dst_ports, &ports);
svec_destroy(&ports);
prune_ports(m, &src_ports);
prune_ports(m, &dst_ports);
if (any_ports_specified && !src_ports.n && !dst_ports.n) {
VLOG_ERR("%s: none of the specified ports exist; "
"disabling port mirror %s", pfx, pfx);
mirror_destroy(m);
goto exit;
}
/* Get all the vlans, and drop duplicate and invalid vlans. */
svec_init(&vlan_strings);
cfg_get_all_keys(&vlan_strings, "%s.select.vlan", pfx);
n_vlans = prune_vlans(m, &vlan_strings, &vlans);
svec_destroy(&vlan_strings);
/* Update mirror data. */
if (!svec_equal(&m->src_ports, &src_ports)
|| !svec_equal(&m->dst_ports, &dst_ports)
|| m->n_vlans != n_vlans
|| memcmp(m->vlans, vlans, sizeof *vlans * n_vlans)
|| m->out_port != out_port
|| m->out_vlan != out_vlan) {
bridge_flush(m->bridge);
}
svec_swap(&m->src_ports, &src_ports);
svec_swap(&m->dst_ports, &dst_ports);
free(m->vlans);
m->vlans = vlans;
m->n_vlans = n_vlans;
m->out_port = out_port;
m->out_vlan = out_vlan;
/* If no selection criteria have been given, mirror for all ports. */
mirror_all_ports = (!m->src_ports.n) && (!m->dst_ports.n) && (!m->n_vlans);
/* Update ports. */
mirror_bit = MIRROR_MASK_C(1) << m->idx;
for (i = 0; i < m->bridge->n_ports; i++) {
struct port *port = m->bridge->ports[i];
if (mirror_all_ports
|| svec_contains(&m->src_ports, port->name)
|| (m->n_vlans
&& (!port->vlan
? port_trunks_any_mirrored_vlan(m, port)
: vlan_is_mirrored(m, port->vlan)))) {
port->src_mirrors |= mirror_bit;
} else {
port->src_mirrors &= ~mirror_bit;
}
if (mirror_all_ports || svec_contains(&m->dst_ports, port->name)) {
port->dst_mirrors |= mirror_bit;
} else {
port->dst_mirrors &= ~mirror_bit;
}
}
/* Clean up. */
exit:
svec_destroy(&src_ports);
svec_destroy(&dst_ports);
free(pfx);
}
/* Spanning tree protocol. */
static void brstp_update_port_state(struct port *);
static void
brstp_send_bpdu(struct ofpbuf *pkt, int port_no, void *br_)
{
struct bridge *br = br_;
static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
struct iface *iface = iface_from_dp_ifidx(br, port_no);
if (!iface) {
VLOG_WARN_RL(&rl, "%s: cannot send BPDU on unknown port %d",
br->name, port_no);
} else {
struct eth_header *eth = pkt->l2;
netdev_get_etheraddr(iface->netdev, eth->eth_src);
if (eth_addr_is_zero(eth->eth_src)) {
VLOG_WARN_RL(&rl, "%s: cannot send BPDU on port %d "
"with unknown MAC", br->name, port_no);
} else {
union ofp_action action;
flow_t flow;
memset(&action, 0, sizeof action);
action.type = htons(OFPAT_OUTPUT);
action.output.len = htons(sizeof action);
action.output.port = htons(port_no);
flow_extract(pkt, ODPP_NONE, &flow);
ofproto_send_packet(br->ofproto, &flow, &action, 1, pkt);
}
}
ofpbuf_delete(pkt);
}
static void
brstp_reconfigure(struct bridge *br)
{
size_t i;
if (!cfg_get_bool(0, "stp.%s.enabled", br->name)) {
if (br->stp) {
stp_destroy(br->stp);
br->stp = NULL;
bridge_flush(br);
}
} else {
uint64_t bridge_address, bridge_id;
int bridge_priority;
bridge_address = cfg_get_mac(0, "stp.%s.address", br->name);
if (!bridge_address) {
if (br->stp) {
bridge_address = (stp_get_bridge_id(br->stp)
& ((UINT64_C(1) << 48) - 1));
} else {
uint8_t mac[ETH_ADDR_LEN];
eth_addr_random(mac);
bridge_address = eth_addr_to_uint64(mac);
}
}
if (cfg_is_valid(CFG_INT | CFG_REQUIRED, "stp.%s.priority",
br->name)) {
bridge_priority = cfg_get_int(0, "stp.%s.priority", br->name);
} else {
bridge_priority = STP_DEFAULT_BRIDGE_PRIORITY;
}
bridge_id = bridge_address | ((uint64_t) bridge_priority << 48);
if (!br->stp) {
br->stp = stp_create(br->name, bridge_id, brstp_send_bpdu, br);
br->stp_last_tick = time_msec();
bridge_flush(br);
} else {
if (bridge_id != stp_get_bridge_id(br->stp)) {
stp_set_bridge_id(br->stp, bridge_id);
bridge_flush(br);
}
}
for (i = 0; i < br->n_ports; i++) {
struct port *p = br->ports[i];
int dp_ifidx;
struct stp_port *sp;
int path_cost, priority;
bool enable;
if (!p->n_ifaces) {
continue;
}
dp_ifidx = p->ifaces[0]->dp_ifidx;
if (dp_ifidx < 0 || dp_ifidx >= STP_MAX_PORTS) {
continue;
}
sp = stp_get_port(br->stp, dp_ifidx);
enable = (!cfg_is_valid(CFG_BOOL | CFG_REQUIRED,
"stp.%s.port.%s.enabled",
br->name, p->name)
|| cfg_get_bool(0, "stp.%s.port.%s.enabled",
br->name, p->name));
if (p->is_mirror_output_port) {
enable = false;
}
if (enable != (stp_port_get_state(sp) != STP_DISABLED)) {
bridge_flush(br); /* Might not be necessary. */
if (enable) {
stp_port_enable(sp);
} else {
stp_port_disable(sp);
}
}
path_cost = cfg_get_int(0, "stp.%s.port.%s.path-cost",
br->name, p->name);
stp_port_set_path_cost(sp, path_cost ? path_cost : 19 /* XXX */);
priority = (cfg_is_valid(CFG_INT | CFG_REQUIRED,
"stp.%s.port.%s.priority",
br->name, p->name)
? cfg_get_int(0, "stp.%s.port.%s.priority",
br->name, p->name)
: STP_DEFAULT_PORT_PRIORITY);
stp_port_set_priority(sp, priority);
}
brstp_adjust_timers(br);
}
for (i = 0; i < br->n_ports; i++) {
brstp_update_port_state(br->ports[i]);
}
}
static void
brstp_update_port_state(struct port *p)
{
struct bridge *br = p->bridge;
enum stp_state state;
/* Figure out new state. */
state = STP_DISABLED;
if (br->stp && p->n_ifaces > 0) {
int dp_ifidx = p->ifaces[0]->dp_ifidx;
if (dp_ifidx >= 0 && dp_ifidx < STP_MAX_PORTS) {
state = stp_port_get_state(stp_get_port(br->stp, dp_ifidx));
}
}
/* Update state. */
if (p->stp_state != state) {
static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(10, 10);
VLOG_INFO_RL(&rl, "port %s: STP state changed from %s to %s",
p->name, stp_state_name(p->stp_state),
stp_state_name(state));
if (p->stp_state == STP_DISABLED) {
bridge_flush(br);
} else {
ofproto_revalidate(p->bridge->ofproto, p->stp_state_tag);
}
p->stp_state = state;
p->stp_state_tag = (p->stp_state == STP_DISABLED ? 0
: tag_create_random());
}
}
static void
brstp_adjust_timers(struct bridge *br)
{
int hello_time = cfg_get_int(0, "stp.%s.hello-time", br->name);
int max_age = cfg_get_int(0, "stp.%s.max-age", br->name);
int forward_delay = cfg_get_int(0, "stp.%s.forward-delay", br->name);
stp_set_hello_time(br->stp, hello_time ? hello_time : 2000);
stp_set_max_age(br->stp, max_age ? max_age : 20000);
stp_set_forward_delay(br->stp, forward_delay ? forward_delay : 15000);
}
static void
brstp_run(struct bridge *br)
{
if (br->stp) {
long long int now = time_msec();
long long int elapsed = now - br->stp_last_tick;
struct stp_port *sp;
if (elapsed > 0) {
stp_tick(br->stp, MIN(INT_MAX, elapsed));
br->stp_last_tick = now;
}
while (stp_get_changed_port(br->stp, &sp)) {
struct port *p = port_from_dp_ifidx(br, stp_port_no(sp));
if (p) {
brstp_update_port_state(p);
}
}
}
}
static void
brstp_wait(struct bridge *br)
{
if (br->stp) {
poll_timer_wait(1000);
}
}
| 32.475402 | 80 | 0.566864 |
dbda4450ff9972fe610d83cbf733f34bea832267 | 2,445 | h | C | include/sys_dependencies.h | williamcroberts/swtpm | eeb87a86739d704b26082a74c80df620e8e898a8 | [
"BSD-3-Clause"
] | null | null | null | include/sys_dependencies.h | williamcroberts/swtpm | eeb87a86739d704b26082a74c80df620e8e898a8 | [
"BSD-3-Clause"
] | null | null | null | include/sys_dependencies.h | williamcroberts/swtpm | eeb87a86739d704b26082a74c80df620e8e898a8 | [
"BSD-3-Clause"
] | null | null | null | /*
* sys_dependencies.h -- system specific includes and #defines
*
* (c) Copyright IBM Corporation 2018.
*
* Author: Stefan Berger <stefanb@us.ibm.com>
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* Neither the names of the IBM 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
* HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef SWTPM_SYS_DEPENDENCIES_H
#define SWTPM_SYS_DEPENDENCIES_H
#if !defined __OpenBSD__ && !defined __FreeBSD__ && !defined __NetBSD__ \
&& !defined __APPLE__ && !defined __DragonFly__
#define _GNU_SOURCE
#include <features.h>
#endif
#if defined __FreeBSD__ || defined __NetBSD__ || defined __DragonFly__
# include <sys/endian.h>
# include <netinet/in.h>
#elif defined __APPLE__
# include <libkern/OSByteOrder.h>
# define be16toh(x) OSSwapBigToHostInt16(x)
# define be32toh(x) OSSwapBigToHostInt32(x)
# define be64toh(x) OSSwapBigToHostInt64(x)
# define htobe16(x) OSSwapHostToBigInt16(x)
# define htobe32(x) OSSwapHostToBigInt32(x)
# define htobe64(x) OSSwapHostToBigInt64(x)
#else
# include <endian.h>
#endif
#endif /* SWTPM_SYS_DEPENDENCIES_H */ | 37.615385 | 73 | 0.769734 |
986d48bbf969a46c0e55903aa5085a1672a39f79 | 5,186 | c | C | test/unit/get_g.c | ggouaillardet/SOS | 1d3e9dce0fe9243df50c563fe79e67614b931eb5 | [
"BSD-3-Clause-Open-MPI"
] | 40 | 2016-02-10T20:15:47.000Z | 2021-12-10T20:22:42.000Z | test/unit/get_g.c | ggouaillardet/SOS | 1d3e9dce0fe9243df50c563fe79e67614b931eb5 | [
"BSD-3-Clause-Open-MPI"
] | 754 | 2016-02-10T22:01:40.000Z | 2022-03-25T17:32:51.000Z | test/unit/get_g.c | ggouaillardet/SOS | 1d3e9dce0fe9243df50c563fe79e67614b931eb5 | [
"BSD-3-Clause-Open-MPI"
] | 45 | 2016-02-27T19:22:11.000Z | 2021-11-20T17:33:42.000Z | /*
* Copyright 2011 Sandia Corporation. Under the terms of Contract
* DE-AC04-94AL85000 with Sandia Corporation, the U.S. Government
* retains certain rights in this software.
*
* Copyright (c) 2017 Intel Corporation. All rights reserved.
* This software is available to you under the BSD license below:
*
* 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.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include <shmem.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
static short *src_short;
static int *src_int;
static float *src_float;
static double *src_double;
static long *src_long;
static short dst_short;
static int dst_int;
static float dst_float;
static double dst_double;
static long dst_long;
static int loops = 100;
int
main(int argc, char* argv[])
{
int me, num_pes, pe, l;
int Verbose = 0;
char *pgm;
if ((pgm=strrchr(argv[0],'/'))) {
pgm++;
} else {
pgm = argv[0];
}
if (argc > 1) {
if (strncmp(argv[1],"-v",3) == 0) {
Verbose=1;
} else if (strncmp(argv[1],"-h",3) == 0) {
fprintf(stderr,"usage: %s {-v(verbose)|h(help)}\n",pgm);
shmem_finalize();
exit(1);
}
}
shmem_init();
me = shmem_my_pe();
num_pes = shmem_n_pes();
// be a bit sane with total number of gets issued
loops = loops / num_pes;
if (loops < 5) loops = 5;
for (l = 0 ; l < loops ; ++l) {
if ((src_short = shmem_malloc(sizeof(short))) == NULL) {
printf("PE-%d short shmem_malloc() failed?\n", me);
shmem_global_exit(1);
}
*src_short = 2;
if ((src_int = shmem_malloc(sizeof(int))) == NULL) {
printf("PE-%d int shmem_malloc() failed?\n", me);
shmem_global_exit(1);
}
*src_int = 4;
if ((src_float = shmem_malloc(sizeof(float))) == NULL) {
printf("PE-%d float shmem_malloc() failed?\n", me);
shmem_global_exit(1);
}
*src_float = 4.0;
if ((src_double = shmem_malloc(sizeof(double))) == NULL) {
printf("PE-%d double shmem_malloc() failed?\n", me);
shmem_global_exit(1);
}
*src_double = 8.0;
if ((src_long = shmem_malloc(sizeof(long))) == NULL) {
printf("PE-%d long shmem_malloc() failed?\n", me);
shmem_global_exit(1);
}
*src_long = 8;
shmem_barrier_all();
for (pe=0 ; pe < num_pes; ++pe) {
if (!shmem_addr_accessible(src_short,pe)) {
printf("PE-%d local addr %p not accessible from PE-%d?\n",
me, (void*)src_short, pe);
shmem_global_exit(1);
}
dst_short = 0;
dst_short = shmem_short_g(src_short,pe);
if (dst_short != 2) {
printf("PE-%d dst_short %hd != 2?\n",me,dst_short);
shmem_global_exit(1);
}
dst_int = 0;
dst_int = shmem_int_g(src_int,pe);
if (dst_int != 4) {
printf("PE-%d dst_int %d != 4?\n",me,dst_int);
shmem_global_exit(1);
}
dst_float = 0.0;
dst_float = shmem_float_g(src_float,pe);
if (dst_float != 4.0) {
printf("PE-%d dst_float %f != 4.0?\n",me,dst_float);
shmem_global_exit(1);
}
dst_double = 0.0;
dst_double = shmem_double_g(src_double,pe);
if (dst_double != 8.0) {
printf("PE-%d dst_double %f != 8.0?\n",me,dst_double);
shmem_global_exit(1);
}
dst_long = 0;
dst_long = shmem_long_g(src_long,pe);
if (dst_long != 8.0) {
printf("PE-%d dst_long %ld != 8?\n",me,dst_long);
shmem_global_exit(1);
}
}
shmem_barrier_all();
shmem_free(src_short);
shmem_free(src_int);
shmem_free(src_float);
shmem_free(src_double);
shmem_free(src_long);
}
if (Verbose)
fprintf(stderr,"[%d] exit\n",shmem_my_pe());
shmem_finalize();
return 0;
}
| 30.505882 | 74 | 0.56209 |
727cd51f199f127502e5ebbbf4d74b3a6784aa80 | 3,356 | c | C | watchapps/pebble_arcade/src/game.c | JasonReyValdez/pebble-sdk-examples | 005df89232c419143a3703604b1b00185ef8656c | [
"Unlicense",
"MIT"
] | 2 | 2015-05-02T06:07:05.000Z | 2015-05-02T06:07:10.000Z | watchapps/pebble_arcade/src/game.c | Pebble2014/pebble-sdk-examples | 005df89232c419143a3703604b1b00185ef8656c | [
"Unlicense",
"MIT"
] | null | null | null | watchapps/pebble_arcade/src/game.c | Pebble2014/pebble-sdk-examples | 005df89232c419143a3703604b1b00185ef8656c | [
"Unlicense",
"MIT"
] | null | null | null | #include <pebble.h>
#include "game.h"
#include "score.h"
// Time always in ms
#define MAX_TIME 5000
#define TIME_INTERVAL 10
static struct GameUi {
Window *window;
TextLayer *score_text;
TextLayer *time_text;
} ui;
static struct GameState {
unsigned score;
unsigned time; // Elapsed time in ms
uint16_t prev_ms;
AppTimer *timer;
} state;
static void finish(void) {
high_score_show();
high_score_add_score(state.score);
}
static void update_time_text(unsigned seconds, unsigned fraction) {
static char buf[16];
snprintf(buf, 16, "%u.%02u", seconds, fraction);
text_layer_set_text(ui.time_text, buf);
}
static void timer_callback(void *data) {
uint16_t c_ms = time_ms(NULL, NULL);
uint16_t elapsed;
if (c_ms < state.prev_ms)
elapsed = (c_ms+1000) - state.prev_ms;
else
elapsed = c_ms - state.prev_ms;
state.prev_ms = c_ms;
state.time += elapsed;
unsigned seconds_remaining = (MAX_TIME - state.time) / 1000;
unsigned fraction_remaining = ((MAX_TIME - state.time) % 1000) / 10;
update_time_text(seconds_remaining, fraction_remaining);
if (state.time < MAX_TIME)
state.timer = app_timer_register(TIME_INTERVAL - (elapsed % TIME_INTERVAL),
timer_callback, NULL);
else
finish();
}
static void select_click_handler(ClickRecognizerRef recognizer, void *context) {
if (!state.timer) {
state.prev_ms = time_ms(NULL, NULL);
state.timer = app_timer_register(TIME_INTERVAL, timer_callback, NULL);
}
static char buf[32];
++state.score;
snprintf(buf, 32, "Score: %u", state.score);
text_layer_set_text(ui.score_text, buf);
}
static void click_config_provider(void *context) {
window_single_click_subscribe(BUTTON_ID_SELECT, select_click_handler);
}
static void window_load(Window *window) {
Layer *window_layer = window_get_root_layer(ui.window);
GRect bounds = layer_get_bounds(window_layer);
ui.score_text = text_layer_create((GRect) {
.origin = { 0, 72 },
.size = { bounds.size.w, 20 }
});
text_layer_set_text_alignment(ui.score_text, GTextAlignmentCenter);
layer_add_child(window_layer, text_layer_get_layer(ui.score_text));
ui.time_text = text_layer_create((GRect) {
.origin = { 0, 0 },
.size = { bounds.size.w, 64 }
});
text_layer_set_text_alignment(ui.time_text, GTextAlignmentCenter);
text_layer_set_font(ui.time_text,
fonts_get_system_font(FONT_KEY_BITHAM_42_BOLD));
layer_add_child(window_layer, text_layer_get_layer(ui.time_text));
}
static void window_appear(Window *window) {
// When the game window appears, reset the game
state.score = 0;
state.time = 0;
state.timer = NULL;
update_time_text(MAX_TIME/1000, (MAX_TIME % 1000) / 10);
text_layer_set_text(ui.score_text, "Press Select to Start");
}
static void window_unload(Window *window) {
text_layer_destroy(ui.time_text);
text_layer_destroy(ui.score_text);
}
void game_init(void) {
ui.window = window_create();
window_set_click_config_provider(ui.window, click_config_provider);
window_set_window_handlers(ui.window, (WindowHandlers) {
.load = window_load,
.unload = window_unload,
.appear = window_appear
});
const bool animated = true;
window_stack_push(ui.window, animated);
}
void game_deinit(void) {
window_destroy(ui.window);
}
| 27.508197 | 80 | 0.710667 |
902e0e191022a03b874648c5d555ceaf99c401f6 | 563 | h | C | freehand drawing/freehand drawing/AccessoryView/ToolBarView.h | lamborghini290/FreeHandDrawing | c0e442cc8b3cac1f24090ad0518de4b8f0cfa0f8 | [
"MIT"
] | 2 | 2017-02-20T10:28:48.000Z | 2017-02-20T10:28:50.000Z | freehand drawing/freehand drawing/AccessoryView/ToolBarView.h | lamborghini290/FreeHandDrawing | c0e442cc8b3cac1f24090ad0518de4b8f0cfa0f8 | [
"MIT"
] | null | null | null | freehand drawing/freehand drawing/AccessoryView/ToolBarView.h | lamborghini290/FreeHandDrawing | c0e442cc8b3cac1f24090ad0518de4b8f0cfa0f8 | [
"MIT"
] | null | null | null | //
// ToolBarView.h
// freehand drawing
//
// Created by lm-zz on 13/01/2017.
// Copyright © 2017 lm-zz. All rights reserved.
//
#import <UIKit/UIKit.h>
typedef NS_ENUM(NSUInteger, ToolBarViewMessageType) {
UIToolbarMessageTypeInputMethod = 0,
UIToolbarMessageTypeSpace,
UIToolbarMessageTypeEnter,
UIToolbarMessageTypeDelete,
};
@protocol ToolBarViewDelegate <NSObject>
- (void)passMessageOutside:(ToolBarViewMessageType)msg_type;
@end
@interface ToolBarView : UIView
@property (nonatomic, weak) id<ToolBarViewDelegate> delegate;
@end
| 19.413793 | 61 | 0.753108 |
e6f1d8d6baab05c1dda1f0c3733d5b4cad43c013 | 2,155 | h | C | hydrogenbuf.h | carpentry-org/hydrogen.carp | bd03f74f41b528ad2902064b1ebd5681132a161b | [
"MIT"
] | 1 | 2019-10-15T07:46:12.000Z | 2019-10-15T07:46:12.000Z | hydrogenbuf.h | carpentry-org/hydrogen.carp | bd03f74f41b528ad2902064b1ebd5681132a161b | [
"MIT"
] | 1 | 2019-10-15T07:48:38.000Z | 2019-10-15T14:43:18.000Z | hydrogenbuf.h | carpentry-org/hydrogen.carp | bd03f74f41b528ad2902064b1ebd5681132a161b | [
"MIT"
] | null | null | null | #include <stdint.h>
#include <stdlib.h>
#include "libhydrogen/hydrogen.h"
typedef hydro_hash_state HydroHashState;
typedef hydro_sign_state HydroSignState;
typedef hydro_sign_keypair HydroSignKeyPair;
typedef hydro_kx_state HydroKXState;
typedef hydro_kx_keypair HydroKXKeyPair;
typedef hydro_kx_session_keypair HydroKXSessionKeyPair;
uint8_t* Hydro_raw(Array* buf) {
return buf->data;
}
HydroSignKeyPair HydroSign_keypair() {
hydro_sign_keypair pair = {};
return pair;
}
uint8_t* HydroSign_pk(hydro_sign_keypair* pair) {
return pair->pk;
}
uint8_t* HydroSign_sk(hydro_sign_keypair* pair) {
return pair->sk;
}
hydro_hash_state HydroHash_state() {
hydro_hash_state state = {};
return state;
}
hydro_sign_state HydroSign_state() {
hydro_sign_state state = {};
return state;
}
hydro_kx_keypair HydroKX_keypair() {
hydro_kx_keypair pair = {};
return pair;
}
hydro_kx_session_keypair HydroKX_session_MINUS_keypair() {
hydro_kx_session_keypair pair = {};
return pair;
}
hydro_kx_state HydroKX_state() {
hydro_kx_state state = {};
return state;
}
uint8_t* HydroKX_pk(hydro_kx_keypair* pair) {
return pair->pk;
}
Array HydroKX_rx(hydro_kx_session_keypair* pair) {
Array res;
res.data = CARP_MALLOC(hydro_kx_SESSIONKEYBYTES);
res.len = hydro_kx_SESSIONKEYBYTES;
res.capacity = hydro_kx_SESSIONKEYBYTES;
memcpy(res.data, pair->rx, hydro_kx_SESSIONKEYBYTES);
return res;
}
Array HydroKX_tx(hydro_kx_session_keypair* pair) {
Array res;
res.data = CARP_MALLOC(hydro_kx_SESSIONKEYBYTES);
res.len = hydro_kx_SESSIONKEYBYTES;
res.capacity = hydro_kx_SESSIONKEYBYTES;
memcpy(res.data, pair->tx, hydro_kx_SESSIONKEYBYTES);
return res;
}
Array Hydro_make_x_array(uint8_t e[hydro_kx_SESSIONKEYBYTES]) {
Array res;
res.len = hydro_kx_SESSIONKEYBYTES;
res.capacity = hydro_kx_SESSIONKEYBYTES;
res.data = CARP_MALLOC(hydro_kx_SESSIONKEYBYTES);
memcpy(res.data, e, hydro_kx_SESSIONKEYBYTES);
return res;
}
Array HydroSign_tx(hydro_kx_session_keypair* pair) {
return Hydro_make_x_array(pair->tx);
}
Array HydroSign_rx(hydro_kx_session_keypair* pair) {
return Hydro_make_x_array(pair->rx);
}
| 23.172043 | 63 | 0.775406 |
11ca04d6bfaba538798a60446255d4c04620054e | 1,069 | h | C | Hardware/Inc/voltage_monitor.h | bf2799/gpr_bot | f6d2a463f16e1aa4365e437b3382ca4b5ab9761b | [
"Apache-2.0"
] | null | null | null | Hardware/Inc/voltage_monitor.h | bf2799/gpr_bot | f6d2a463f16e1aa4365e437b3382ca4b5ab9761b | [
"Apache-2.0"
] | null | null | null | Hardware/Inc/voltage_monitor.h | bf2799/gpr_bot | f6d2a463f16e1aa4365e437b3382ca4b5ab9761b | [
"Apache-2.0"
] | null | null | null | /*
* voltage_monitor.h
*
* Driver for monitoring battery voltage via ADC
*/
#ifndef INC_VOLTAGE_MONITOR_H_
#define INC_VOLTAGE_MONITOR_H_
#include <stdbool.h>
#include "stm32f7xx_hal.h"
typedef struct voltage_monitor_t {
ADC_HandleTypeDef* hadc;
double volts_per_adc_inc;
uint32_t adc_val;
} voltage_monitor_t;
/**
* @brief Initialize voltage monitor
* @param[in, out] dev: Voltage monitor device
* @param[in] hadc: ADC handle to map to voltage monitor
*/
void voltage_monitor_init(voltage_monitor_t* dev, ADC_HandleTypeDef* hadc);
/**
* @brief Start read from voltage monitor
* @param[in] dev: Voltage monitor device
*
* This conversion takes time, so separating from getting the value increases flexibility
*/
void voltage_monitor_start_read(voltage_monitor_t* dev);
/**
* @brief Gets voltage from the voltage monitor
* @param[in] dev: Voltage monitor device
* @param[out] voltage: Voltage that was received from the monitor
*/
bool voltage_monitor_get_voltage(voltage_monitor_t* dev, double* voltage);
#endif /* INC_VOLTAGE_MONITOR_H_ */
| 24.860465 | 89 | 0.76333 |
e636fc60b7eec6467d61d6e1289cda7ad2cf2997 | 12,150 | c | C | proyectos/3/GuadarramaEdgar/Proyecto3.c | Edgalejandro23/sistop-2019-1 | f076b7ee87f6edc402c262ef81698a6eed61ffdf | [
"CC-BY-4.0"
] | 1 | 2018-09-27T09:39:26.000Z | 2018-09-27T09:39:26.000Z | proyectos/3/GuadarramaEdgar/Proyecto3.c | Edgalejandro23/sistop-2019-1 | f076b7ee87f6edc402c262ef81698a6eed61ffdf | [
"CC-BY-4.0"
] | 46 | 2018-08-13T16:18:22.000Z | 2018-11-25T04:39:34.000Z | proyectos/3/GuadarramaEdgar/Proyecto3.c | Edgalejandro23/sistop-2019-1 | f076b7ee87f6edc402c262ef81698a6eed61ffdf | [
"CC-BY-4.0"
] | 24 | 2018-08-12T23:15:54.000Z | 2018-08-30T07:01:05.000Z | /*
El microsistema de archivos funciona en base a un archivo binario con el siguiente formato para separar los archivos.
|longitudNombreArchivo1(4 bytes)|NombreArchivo1(lonNombArch1 bytes)|longitudContenidoArchivo1(4 bytes)|ContenidoArchivo1(lonContArch1 bytes)|LNA2|NA2|LCA2|CA2|LNA3|NA3|LCA3|CA3|...
*/
#include <stdio.h>
#include <string.h>
#include <unistd.h>
//#include <windows.h> //para windows
#define MAX_CONTENT 515
#define MAX_FILENAME 64
#define NOMBRE_ARCHIVO "microsistema.bin"
FILE * pFile;
long lSize;//variable de apoyo para saber si hay almenos 1 archivo en nuestro sistema de archivos
void limpiarPantalla()
{
printf("\e[2J\e[H");
//("@cls||clear"); //Para windows y se limpie la pantalla cada que terminamos una instruccion
}
int obtenerOpcion()
{
int respuesta;
scanf("%i", &respuesta);
getchar();//se utiliza getchar adicional para que no proceso la tecla Enter
return respuesta;
}
void obtenerContenido(char *destino, int maxSize)
{
fgets(destino, maxSize, stdin);//se utiliza para obtener un texto incluyendo espacios hasta que se presione enter
int len=strlen(destino);
destino[len-1]='\0';
}
int cargarSistema()
{
pFile = fopen(NOMBRE_ARCHIVO,"a+b");//se abre el archivo en modo apertura binaria para agregar contenido(nuevos archivos) y guardar variables en modo binario
if(pFile==NULL)
{
printf("Error al tratar de abrir el archivo principal!\n");
fclose (pFile);
return 1;
}
fseek(pFile, 0, SEEK_END);//se posiciona al final del archivo para cuando se cree un nuevo archivo se coloque hasta el final
lSize = ftell(pFile);
return 0;
}
void despliegaMenu()
{
printf("Microsistema de archivos\n");
printf("Opciones:\n1.Crear nuevo archivo\n");
if(lSize>0)
printf("2.Borrar archivo\n3.Abrir archivo\n4.Listar Archivos\n0.Guardar y salir.\n");
return;
}
void guardarArchivo(char *Archivo, char *Contenido)
{
fseek(pFile, 0, SEEK_END);
int lenFile = strlen(Archivo);
int lenContent = strlen(Contenido);
fwrite(&lenFile, sizeof(int), 1, pFile);//se guardan en 4 bytes la longitud del nombre del archivo
fwrite(Archivo, sizeof(char), lenFile, pFile);//se guarda el nombre del archivo
fwrite(&lenContent, sizeof(int), 1, pFile);//se guarda en 4 byte la longitud del contenido
fwrite(Contenido, sizeof(char), lenContent, pFile);//se guarda el contenido del archivo
lSize = ftell(pFile);
}
int buscarArchivo(char *Archivo)
{/*para buscar un archivo en especifico empezamos a recorrer nuestro archivo binario
buscando que la longitud del nombre de archivo que buscamos coincida con la longitud del nombre de alguno de nuestros archivos guardados.
En caso que coincida entonces se lee el nombre del archivo y se compara con el que buscamos.
Si coinciden los nombres es porque encontramos el archivo y la funcion retorna la posicion de nuestro .bin en la cual se encuentra el archivo.
De lo contrario retorna -1 en señal de que no se encontro.
*/
int lenFile = strlen(Archivo);
int lenTmp=0;
char fileName[MAX_FILENAME];
fseek(pFile, 0, SEEK_SET);
while(!feof(pFile))
{
fread(&lenTmp, sizeof(int), 1, pFile);
if(feof(pFile))
break;
if(lenTmp!=lenFile){
fseek(pFile, lenTmp, SEEK_CUR);
fread(&lenTmp, sizeof(int), 1, pFile);
fseek(pFile, lenTmp, SEEK_CUR);
continue;
}
else
{
fread(fileName, sizeof(char), lenTmp, pFile);
fileName[lenTmp]='\0';
if(!strcmp(fileName,Archivo))
{
return ftell(pFile)-lenTmp-4;
}
fread(&lenTmp, sizeof(int), 1, pFile);
fseek(pFile, lenTmp, SEEK_CUR);
}
}
return -1;
}
void borrarArchivo(char *Archivo)//Crea un duplicado del microsistema pero sin el Archivo que se quiere borrar
{/* Se podria usar un sistema como en la tarea2 manejando la memoria, buscar huecos, comparar, compactar, etc... Pero se volveria muy complejo
y requeriria bastante tiempo el desarrollarlo. Por lo que se opto por la manera mas sencilla (duplicar omitiendo el archivo que se quiere borrar).
*/
FILE * pNuevoArchivo;
char bufferNuevoArchivo[512];
int posicionDeCorte = buscarArchivo(Archivo);
int posicionActual=0;
if(posicionDeCorte==-1)
{
printf("No se encontro el archivo '%s'.\n", Archivo);
return;
}
pNuevoArchivo = fopen("microsistemaTMP.bin","wb");
if(pNuevoArchivo==NULL)
{
printf("Error al tratar de borrar archivo! (no se pudo crear el archivo temporal)\n");
fclose(pNuevoArchivo);
return;
}
fseek(pFile, 0, SEEK_SET);
while(!feof(pFile))//el duplicado se crea copiando 512 bytes por cada ciclo del while hasta que se llegue al final del archivo.
{
posicionActual+=512;
if(posicionDeCorte<posicionActual)//si la posicion del archivo que queremos borrar se encuentra en el bloque de 512 bytes actual, entonces leemos hasta donde comienza este
{//y continuamos n bytes despues (donde terminan los datos del archivo que queremos borrar) (n=4bytes+longitudNombre+4bytes+longitudContenido)
int lenTmp=0;
posicionActual=ftell(pFile);
fread(bufferNuevoArchivo, sizeof(char), posicionDeCorte-posicionActual, pFile);
fwrite(bufferNuevoArchivo, sizeof(char), posicionDeCorte-posicionActual, pNuevoArchivo);
fread(&lenTmp, sizeof(int), 1, pFile);
fseek(pFile, lenTmp, SEEK_CUR);
fread(&lenTmp, sizeof(int), 1, pFile);
fseek(pFile, lenTmp, SEEK_CUR);
posicionDeCorte=99999999;//una vez que nos saltamos el archivo borrado, ya no comparamos el resto y nos dedicamos a solo copiar el resto de nuestro microsistema.
}
int bytesReaded = fread(bufferNuevoArchivo, sizeof(char), 512, pFile);
fwrite(bufferNuevoArchivo, sizeof(char), bytesReaded, pNuevoArchivo);
}
fclose(pNuevoArchivo);
fclose(pFile);
if(remove(NOMBRE_ARCHIVO) != 0)
printf("Error al tratar de borrar archivo!(no se pudo borrar el archivo original)\n");
else if(rename("microsistemaTMP.bin", NOMBRE_ARCHIVO) != 0){
printf("Error al tratar de borrar archivo!(no se pudo renombrar el archivo temporal)\n");
perror("Error");
}
else{
printf("Archivo '%s' borrado!\n", Archivo);
cargarSistema();
}
return;
}
void listarArchivos()
{/*para listar los archivos: leemos 4 bytes, leemos el nombre del archivo con la longitud obtenida, leemos 4 bytes,
saltamos la longitud que nos dieron estos ultimos 4 bytes y repetimos hasta el final del microsistema*/
int lenTmp=0;
char fileName[MAX_FILENAME];
limpiarPantalla();
printf("****** Listado de archivos ******\n\n");
fseek(pFile, 0, SEEK_SET);
while(!feof(pFile))
{
fread(&lenTmp, sizeof(int), 1, pFile);
if(feof(pFile))
break;
fread(fileName, sizeof(char), lenTmp, pFile);
fileName[lenTmp]='\0';
printf("%s\n", fileName);
fread(&lenTmp, sizeof(int), 1, pFile);
fseek(pFile, lenTmp, SEEK_CUR);
}
printf("\n****** Fin del listado de archivos ******\nPresione enter para regresar al menu principal.");
getchar();
return;
}
int main ()
{
int respuesta=0;
if(cargarSistema())
return 1;
regresa:
despliegaMenu();
respuesta=obtenerOpcion();
if((respuesta != 1 && respuesta != 0 && lSize==0) || respuesta < 0 || respuesta > 4)//si no tenemos archivos en nuestro microsistema entonces solo mostraremos la opcion 1 (crear nuevo archivo)
{
printf("No existe esa opcion.");
despliegaMenu();
}
else if(respuesta==1)//la siguientes 2 opciones se sobreentienden en el codigo
{
char sArchivo[MAX_FILENAME];
char sContenido[MAX_CONTENT];
char sOpcion[16];
printf("Escriba el nombre del archivo que desee crear:\n");
do{
obtenerContenido(sArchivo,MAX_FILENAME);
} while(sArchivo[0]=='\0');
while(buscarArchivo(sArchivo)!=-1){
printf("Ese archivo ya existe, elija otro nombre:\n");
obtenerContenido(sArchivo,MAX_FILENAME);
}
printf("Desea escribirlo en este momento?\n1.Si\n2.No\n");
respuesta=obtenerOpcion();
sContenido[0]='\0';
if(respuesta==1)
{
limpiarPantalla();
obtenerContenido(sContenido,MAX_CONTENT);
strcpy(sOpcion, "escrito");
}
else
strcpy(sOpcion, "creado");
guardarArchivo(sArchivo, sContenido);
limpiarPantalla();
printf("Archivo %s con exito!\n", sOpcion);
goto regresa;
}
else if(respuesta==2)
{
char sArchivo[MAX_FILENAME];
printf("Escriba el nombre del archivo que desee borrar:\n");
obtenerContenido(sArchivo,MAX_FILENAME);
limpiarPantalla();
borrarArchivo(sArchivo);
goto regresa;
}
else if(respuesta==3)//si selecciona abrir el archivo:
{
char sArchivo[MAX_FILENAME];
printf("Escriba el nombre del archivo que desee abrir:\n");
obtenerContenido(sArchivo,MAX_FILENAME);
int addressFile = buscarArchivo(sArchivo);
if(addressFile!=-1)
{
printf("Opciones:\n1.Mostrar contenido\n2.Agregar contenido\n3.Sobreescribir contenido\n");//mostramos las opciones que se pueden hacer con ese archivo
respuesta=obtenerOpcion();
int lenTmp=0;
char sContenido[MAX_CONTENT];//leemos el contenido por anticipado (lo utilizaremos independientemente de la opcion seleccionada).
fseek(pFile, addressFile, SEEK_SET);
fread(&lenTmp, sizeof(int), 1, pFile);
fseek(pFile, lenTmp, SEEK_CUR);
fread(&lenTmp, sizeof(int), 1, pFile);
fread(sContenido, sizeof(char), lenTmp, pFile);
sContenido[lenTmp]='\0';
limpiarPantalla();
if(respuesta==1)//la mas facil. Solo mostramos el contenido
{
printf("<<%s>>\n%s\n\nPresiona enter para regresar al menu principal.", sArchivo, sContenido);
getchar();
limpiarPantalla();
}
else if(respuesta==2)//Se puede hacer algo mas elaborado pero por simplicidad:
{//ya tenemos el contenido, entonces borramos el archivo, agregamos lo que el usuario escribio y lo guardamos como si fuera un nuevo archivo
borrarArchivo(sArchivo);
limpiarPantalla();
printf("Escribe el contenido que deseas agregar:\n");
obtenerContenido(sContenido+lenTmp,MAX_CONTENT-lenTmp);
guardarArchivo(sArchivo, sContenido);
limpiarPantalla();
printf("Contenido agregado con exito!\n");
}
else if(respuesta==3)//En caso de querer sobreescribir se hace lo mismo. Borra el archivo y lo vuelve a crear pero con el nuevo contenido.
{
borrarArchivo(sArchivo);
limpiarPantalla();
printf("Escribe el contenido que deseas sobreescribir:\n");
obtenerContenido(sContenido,MAX_CONTENT);
guardarArchivo(sArchivo, sContenido);
limpiarPantalla();
printf("Contenido sobreescrito con exito!\n");
}
goto regresa;
}
else
{
limpiarPantalla();
printf("El archivo %s no existe!\n", sArchivo);
}
goto regresa;
}
else if(respuesta==4)//Opcion de mostrar la lista de archivos en nuestro microsistema
{
listarArchivos();
limpiarPantalla();
goto regresa;
}
else if(respuesta==0)//con esta opcion entonces ya podemos cerrar el archivo .bin que tenemos abierto.
{
printf("Guardando microsistema de archivos y saliendo...\n");
fclose(pFile);
return 9;
}
return 0;
}
| 39.576547 | 196 | 0.641152 |
520e6f2fb39f26969a341722eaf61d7842466638 | 1,964 | h | C | p2core/pel/pel_lexer.h | declarativitydotnet/p2 | 59fa258b222a5ff0e6930da4f08acd6155cd378e | [
"BSD-3-Clause"
] | 3 | 2016-01-26T22:19:12.000Z | 2019-07-10T02:12:38.000Z | p2core/pel/pel_lexer.h | declarativitydotnet/p2 | 59fa258b222a5ff0e6930da4f08acd6155cd378e | [
"BSD-3-Clause"
] | null | null | null | p2core/pel/pel_lexer.h | declarativitydotnet/p2 | 59fa258b222a5ff0e6930da4f08acd6155cd378e | [
"BSD-3-Clause"
] | null | null | null | /*
* @(#)$Id: pel_lexer.h 1213 2007-03-10 05:38:10Z maniatis $
*
* This file is distributed under the terms in the attached LICENSE file.
* If you do not find this file, copies can be found by writing to:
* Intel Research Berkeley, 2150 Shattuck Avenue, Suite 1300,
* Berkeley, CA, 94704. Attention: Intel License Inquiry.
* Or
* UC Berkeley EECS Computer Science Division, 387 Soda Hall #1776,
* Berkeley, CA, 94707. Attention: P2 Group.
*
* DESCRIPTION:
*
*/
#ifndef __PEL_LEXER_H__
#define __PEL_LEXER_H__
#include <sstream>
#include "pel_program.h"
#include "pel_vm.h"
#include "loop.h"
#include "val_str.h"
#include "val_double.h"
#include "val_null.h"
#include "val_list.h"
#include "val_id.h"
#include "val_int64.h"
#ifndef yyFlexLexer
#define yyFlexLexer PelBaseFlexLexer
#include <FlexLexer.h>
#endif
class Pel_Lexer : public PelBaseFlexLexer {
private:
struct opcode_token {
const char *name;
u_int32_t code;
};
static opcode_token tokens[];
static const uint32_t num_tokens;
yy_buffer_state *bufstate;
std::istringstream strb;
boost::shared_ptr< Pel_Program > result;
const char* _programText;
virtual int yylex();
void add_const_int(int64_t v) { add_const(Val_Int64::mk(v));};
void add_const_str(string s) { add_const(Val_Str::mk(s));};
void add_const_dbl(double d) { add_const(Val_Double::mk(d));};
void add_const(ValuePtr f);
void add_tuple_load(int f);
void add_opcode(u_int32_t op);
Pel_Lexer(const char *prog);
virtual ~Pel_Lexer() { yy_delete_buffer(bufstate); };
public:
//
// Take a string and compile into a PEL program
//
static boost::shared_ptr< Pel_Program > compile(const char *prog);
//
// Decompile a PEL program back into a string
//
static string decompile(Pel_Program &prog);
//
// Translate a PEL opcode into a mnemonic for the instruction
//
static const char *opcode_mnemonic(u_int32_t opcode);
};
#endif /* __PEL_LEXER_H_ */
| 22.837209 | 73 | 0.711303 |
f84ec8fb57f603e0d7f48ceff3ac230354951bfb | 6,842 | c | C | platform/lpc/lpc43xx/usb_base.c | stxent/lpclib | d1190bbacd68d72d9f04b71a1e208702aa838986 | [
"MIT"
] | 3 | 2015-06-06T18:37:13.000Z | 2021-01-29T15:51:45.000Z | platform/lpc/lpc43xx/usb_base.c | stxent/lpclib | d1190bbacd68d72d9f04b71a1e208702aa838986 | [
"MIT"
] | null | null | null | platform/lpc/lpc43xx/usb_base.c | stxent/lpclib | d1190bbacd68d72d9f04b71a1e208702aa838986 | [
"MIT"
] | null | null | null | /*
* usb_base.c
* Copyright (C) 2016 xent
* Project is distributed under the terms of the MIT License
*/
#include <halm/platform/lpc/lpc43xx/system_defs.h>
#include <halm/platform/lpc/lpc43xx/usb_base.h>
#include <halm/platform/lpc/lpc43xx/usb_defs.h>
#include <halm/platform/lpc/system.h>
#include <assert.h>
#include <malloc.h>
#include <stdlib.h>
/*----------------------------------------------------------------------------*/
#define ENDPOINT_REQUESTS CONFIG_PLATFORM_USB_DEVICE_POOL_SIZE
#define USB0_ENDPOINT_NUMBER 12
#define USB1_ENDPOINT_NUMBER 8
/*----------------------------------------------------------------------------*/
static void configPins(struct UsbBase *, const struct UsbBaseConfig *);
static bool setInstance(uint8_t, struct UsbBase *);
/*----------------------------------------------------------------------------*/
static enum Result devInit(void *, const void *);
#ifndef CONFIG_PLATFORM_USB_NO_DEINIT
static void devDeinit(void *);
#else
#define devDeinit deletedDestructorTrap
#endif
/*----------------------------------------------------------------------------*/
const struct EntityClass * const UsbBase = &(const struct EntityClass){
.size = 0, /* Abstract class */
.init = devInit,
.deinit = devDeinit
};
/*----------------------------------------------------------------------------*/
const struct PinEntry usbPins[] = {
{
.key = PIN(PORT_1, 5), /* USB0_PWR_FAULT */
.channel = 0,
.value = 4
}, {
.key = PIN(PORT_1, 7), /* USB0_PPWR */
.channel = 0,
.value = 4
}, {
.key = PIN(PORT_2, 0), /* USB0_PPWR */
.channel = 0,
.value = 3
}, {
.key = PIN(PORT_2, 1), /* USB0_PWR_FAULT */
.channel = 0,
.value = 3
}, {
.key = PIN(PORT_2, 3), /* USB0_PPWR */
.channel = 0,
.value = 7
}, {
.key = PIN(PORT_2, 4), /* USB0_PWR_FAULT */
.channel = 0,
.value = 7
}, {
.key = PIN(PORT_6, 3), /* USB0_PPWR */
.channel = 0,
.value = 1
}, {
.key = PIN(PORT_6, 6), /* USB0_PWR_FAULT */
.channel = 0,
.value = 3
}, {
.key = PIN(PORT_8, 0), /* USB0_PWR_FAULT */
.channel = 0,
.value = 1
}, {
.key = PIN(PORT_USB, PIN_USB0_DM), /* USB0_DM */
.channel = 0,
.value = 0
}, {
.key = PIN(PORT_USB, PIN_USB0_DP), /* USB0_DP */
.channel = 0,
.value = 0
}, {
.key = PIN(PORT_USB, PIN_USB0_ID), /* USB0_ID */
.channel = 0,
.value = 0
}, {
.key = PIN(PORT_USB, PIN_USB0_VBUS), /* USB0_VBUS */
.channel = 0,
.value = 0
}, {
.key = PIN(PORT_2, 5), /* USB1_VBUS1 */
.channel = 1,
.value = 2
}, {
.key = PIN(PORT_9, 5), /* USB1_PPWR */
.channel = 1,
.value = 2
}, {
.key = PIN(PORT_9, 6), /* USB1_PWR_FAULT */
.channel = 1,
.value = 2
}, {
.key = PIN(PORT_USB, PIN_USB1_DM), /* USB1_DM */
.channel = 1,
.value = 0
}, {
.key = PIN(PORT_USB, PIN_USB1_DP), /* USB1_DP */
.channel = 1,
.value = 0
}, {
.key = 0 /* End of pin function association list */
}
};
/*----------------------------------------------------------------------------*/
static struct UsbBase *instances[2] = {0};
/*----------------------------------------------------------------------------*/
static void configPins(struct UsbBase *device,
const struct UsbBaseConfig *config)
{
const PinNumber pinArray[] = {
config->dm, config->dp, config->connect, config->vbus
};
for (size_t index = 0; index < ARRAY_SIZE(pinArray); ++index)
{
if (pinArray[index])
{
const struct PinEntry * const pinEntry = pinFind(usbPins, pinArray[index],
device->channel);
assert(pinEntry);
const struct Pin pin = pinInit(pinArray[index]);
pinInput(pin);
pinSetFunction(pin, pinEntry->value);
}
}
}
/*----------------------------------------------------------------------------*/
static bool setInstance(uint8_t channel, struct UsbBase *object)
{
assert(channel < ARRAY_SIZE(instances));
if (!instances[channel])
{
instances[channel] = object;
return true;
}
else
return false;
}
/*----------------------------------------------------------------------------*/
void USB0_ISR(void)
{
instances[0]->handler(instances[0]);
}
/*----------------------------------------------------------------------------*/
void USB1_ISR(void)
{
instances[1]->handler(instances[1]);
}
/*----------------------------------------------------------------------------*/
static enum Result devInit(void *object, const void *configBase)
{
const struct UsbBaseConfig * const config = configBase;
struct UsbBase * const device = object;
device->channel = config->channel;
device->handler = 0;
device->queueHeads = 0;
if (!setInstance(device->channel, device))
return E_BUSY;
if (!pointerArrayInit(&device->descriptorPool, ENDPOINT_REQUESTS))
return E_MEMORY;
configPins(device, configBase);
if (!device->channel)
{
sysClockEnable(CLK_M4_USB0);
sysClockEnable(CLK_USB0);
sysResetEnable(RST_USB0);
device->irq = USB0_IRQ;
device->reg = LPC_USB0;
device->numberOfEndpoints = USB0_ENDPOINT_NUMBER;
LPC_CREG->CREG0 &= ~CREG0_USB0PHY;
LPC_USB0->OTGSC = OTGSC_VD | OTGSC_OT;
}
else
{
sysClockEnable(CLK_M4_USB1);
sysClockEnable(CLK_USB1);
sysResetEnable(RST_USB1);
device->irq = USB1_IRQ;
device->reg = LPC_USB1;
device->numberOfEndpoints = USB1_ENDPOINT_NUMBER;
LPC_SCU->SFSUSB = SFSUSB_ESEA | SFSUSB_EPWR | SFSUSB_VBUS;
}
device->queueHeads = memalign(2048, sizeof(struct QueueHead)
* device->numberOfEndpoints);
if (!device->queueHeads)
return E_MEMORY;
device->descriptorMemory = memalign(32, sizeof(struct TransferDescriptor)
* ENDPOINT_REQUESTS);
if (!device->descriptorMemory)
return E_MEMORY;
for (size_t index = 0; index < ENDPOINT_REQUESTS; ++index)
{
pointerArrayPushBack(&device->descriptorPool,
device->descriptorMemory + index);
}
return E_OK;
}
/*----------------------------------------------------------------------------*/
#ifndef CONFIG_PLATFORM_USB_NO_DEINIT
static void devDeinit(void *object)
{
struct UsbBase * const device = object;
free(device->descriptorMemory);
free(device->queueHeads);
if (!device->channel)
{
LPC_CREG->CREG0 |= CREG0_USB0PHY;
sysClockDisable(CLK_USB0);
sysClockDisable(CLK_M4_USB0);
}
else
{
LPC_SCU->SFSUSB &= ~(SFSUSB_EPWR | SFSUSB_VBUS);
sysClockDisable(CLK_USB1);
sysClockDisable(CLK_M4_USB1);
}
instances[device->channel] = 0;
}
#endif
| 27.368 | 80 | 0.520023 |
f8cfd03a145143c20fff53716ac82635b1c8627a | 568 | h | C | arl-hourglass/arl-hourglass/HourglassSimulation.h | bernhardrieder/Hourglass-Simulation | 737c756fc283859bb89d9c670b67a0be7aa979d6 | [
"Unlicense"
] | null | null | null | arl-hourglass/arl-hourglass/HourglassSimulation.h | bernhardrieder/Hourglass-Simulation | 737c756fc283859bb89d9c670b67a0be7aa979d6 | [
"Unlicense"
] | null | null | null | arl-hourglass/arl-hourglass/HourglassSimulation.h | bernhardrieder/Hourglass-Simulation | 737c756fc283859bb89d9c670b67a0be7aa979d6 | [
"Unlicense"
] | null | null | null | #pragma once
#include <SFML/Graphics.hpp>
class HourglassSimulation
{
public:
HourglassSimulation();
~HourglassSimulation();
int Execute(int argc, char* argv[]) const;
private:
enum AppInputResult
{
Error = 0,
CPU_Usage,
GPU_Usage
};
static AppInputResult parseCmdLine(int argc, char* argv[]);
static void showUsage(const char* name);
void colorizePixelAtPosition(sf::Image& inOutImage, const sf::Vector2i& position, const float& radius, const sf::Color& newColor, const sf::Color& restrictedColor, const sf::Vector2u& windowDimensions) const;
};
| 21.846154 | 209 | 0.746479 |
92c00730404ac6db869a1c88d0ea1801e2de13db | 2,268 | h | C | include/USBMtpInterface.h | nadrino/mtp-server-nx | 6dda12d7d8c734aa6a516ca167abe010aeb7fc7a | [
"Apache-2.0"
] | 171 | 2019-09-02T11:56:13.000Z | 2022-03-20T18:10:10.000Z | include/USBMtpInterface.h | nadrino/mtp-server-nx | 6dda12d7d8c734aa6a516ca167abe010aeb7fc7a | [
"Apache-2.0"
] | 13 | 2019-09-02T20:46:03.000Z | 2021-11-22T18:31:06.000Z | include/USBMtpInterface.h | nadrino/mtp-server-nx | 6dda12d7d8c734aa6a516ca167abe010aeb7fc7a | [
"Apache-2.0"
] | 19 | 2019-09-03T03:03:20.000Z | 2022-02-21T14:40:58.000Z | /*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef __USB_MTP_INTERFACE_H
#define __USB_MTP_INTERFACE_H
#include "usb.h"
class USBMtpInterface {
private:
int interface_index;
struct usb_interface_descriptor mtp_interface_descriptor = {
.bLength = USB_DT_INTERFACE_SIZE,
.bDescriptorType = USB_DT_INTERFACE,
.bNumEndpoints = 3,
.bInterfaceClass = 6,
.bInterfaceSubClass = 1,
.bInterfaceProtocol = 1,
};
struct usb_endpoint_descriptor mtp_endpoint_descriptor_in = {
.bLength = USB_DT_ENDPOINT_SIZE,
.bDescriptorType = USB_DT_ENDPOINT,
.bEndpointAddress = USB_ENDPOINT_IN,
.bmAttributes = USB_TRANSFER_TYPE_BULK,
.wMaxPacketSize = 0x200,
};
struct usb_endpoint_descriptor mtp_endpoint_descriptor_out = {
.bLength = USB_DT_ENDPOINT_SIZE,
.bDescriptorType = USB_DT_ENDPOINT,
.bEndpointAddress = USB_ENDPOINT_OUT,
.bmAttributes = USB_TRANSFER_TYPE_BULK,
.wMaxPacketSize = 0x200,
};
struct usb_endpoint_descriptor mtp_endpoint_descriptor_interrupt = {
.bLength = USB_DT_ENDPOINT_SIZE,
.bDescriptorType = USB_DT_ENDPOINT,
.bEndpointAddress = USB_ENDPOINT_IN,
.bmAttributes = USB_TRANSFER_TYPE_INTERRUPT,
.wMaxPacketSize = 0x1c,
.bInterval = 6,
};
const char * mtp_string_descriptor = "MTP";
public:
USBMtpInterface(int index, UsbInterfaceDesc *info);
virtual ~USBMtpInterface();
ssize_t read(char *ptr, size_t len);
ssize_t write(const char *ptr, size_t len);
ssize_t sendEvent(const char *ptr, size_t len);
};
#endif /* __USB_MTP_INTERFACE_H */
| 31.943662 | 75 | 0.699295 |
92d999d9f41786b4f655d43b22ac484e0c405d4d | 1,698 | h | C | PrivateFrameworks/SafariShared/WBSTabDialogManager.h | phatblat/macOSPrivateFrameworks | 9047371eb80f925642c8a7c4f1e00095aec66044 | [
"MIT"
] | 17 | 2018-11-13T04:02:58.000Z | 2022-01-20T09:27:13.000Z | PrivateFrameworks/SafariShared/WBSTabDialogManager.h | phatblat/macOSPrivateFrameworks | 9047371eb80f925642c8a7c4f1e00095aec66044 | [
"MIT"
] | 3 | 2018-04-06T02:02:27.000Z | 2018-10-02T01:12:10.000Z | PrivateFrameworks/SafariShared/WBSTabDialogManager.h | phatblat/macOSPrivateFrameworks | 9047371eb80f925642c8a7c4f1e00095aec66044 | [
"MIT"
] | 1 | 2018-09-28T13:54:23.000Z | 2018-09-28T13:54:23.000Z | //
// Generated by class-dump 3.5 (64 bit).
//
// class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2013 by Steve Nygard.
//
#import "NSObject.h"
@class NSMutableDictionary;
@interface WBSTabDialogManager : NSObject
{
NSMutableDictionary *_webProcessIDToDialogSetMapping;
NSMutableDictionary *_tabIDToDialogQueueMapping;
unsigned long long _queueCapacity;
}
- (void).cxx_destruct;
- (id)_dialogBlockingWebProcessID:(int)arg1;
- (id)_dialogBlockingSlot:(CDStruct_497cfc99)arg1;
- (void)_dismissDialog:(id)arg1 withResponse:(id)arg2;
- (long long)_enqueueDialog:(id)arg1;
- (struct NSMutableSet *)_setForWebProcessID:(int)arg1 createIfNeeded:(BOOL)arg2;
- (struct NSMutableArray *)_queueForTabID:(unsigned long long)arg1 createIfNeeded:(BOOL)arg2;
- (void)cancelAllDialogsWithContext:(id)arg1;
- (void)_cancelDialogsInQueue:(struct NSMutableArray *)arg1 tabID:(unsigned long long)arg2 context:(id)arg3;
- (void)cancelAllDialogsForTabID:(unsigned long long)arg1 context:(id)arg2;
- (void)cancelAllDialogsForTabID:(unsigned long long)arg1 reason:(id)arg2;
- (void)cancelAllDialogsForTabID:(unsigned long long)arg1;
- (void)cancelAllDialogsBlockingWebProcessID:(int)arg1;
- (void)cancelAllDialogsBlockingSlot:(CDStruct_497cfc99)arg1;
- (void)dismissCurrentDialogForTabID:(unsigned long long)arg1 withResponse:(id)arg2;
- (void)presentNextDialogForSlot:(CDStruct_497cfc99)arg1;
- (void)enqueueOrPresentDialogInSlot:(CDStruct_497cfc99)arg1 presentationBlock:(CDUnknownBlockType)arg2 dismissalBlock:(CDUnknownBlockType)arg3 blocksWebProcessUntilDismissed:(BOOL)arg4;
- (void)enqueueOrPresentDialog:(id)arg1 inSlot:(CDStruct_497cfc99)arg2;
- (id)description;
- (id)init;
@end
| 41.414634 | 186 | 0.795053 |
a1f2369c4e9e30d8cdebc6c3851200b1455e5c27 | 3,962 | c | C | codegen.c | yuji314159/mycc | bb539a7e2c31166f72c7ad4d28fe03cfcd111b1e | [
"MIT"
] | null | null | null | codegen.c | yuji314159/mycc | bb539a7e2c31166f72c7ad4d28fe03cfcd111b1e | [
"MIT"
] | null | null | null | codegen.c | yuji314159/mycc | bb539a7e2c31166f72c7ad4d28fe03cfcd111b1e | [
"MIT"
] | null | null | null | #include <stdio.h>
#include "mycc.h"
int label;
void gen_lval(Node *node) {
if (node->type != ND_LVAR) {
error("代入の左辺値が変数ではありません");
}
printf(" mov rax, rbp\n");
printf(" sub rax, %d\n", node->offset);
printf(" push rax\n");
}
void gen(Node *node) {
switch (node->type) {
case ND_NUM:
printf(" push %d\n", node->val);
return;
case ND_LVAR:
gen_lval(node);
printf(" pop rax\n");
printf(" mov rax, [rax]\n");
printf(" push rax\n");
return;
case ND_ASSIGN:
gen_lval(node->lhs);
gen(node->rhs);
printf(" pop rdi\n");
printf(" pop rax\n");
printf(" mov [rax], rdi\n");
printf(" push rdi\n");
return;
case ND_RETURN:
gen(node->lhs);
printf(" pop rax\n");
printf(" mov rsp, rbp\n");
printf(" pop rbp\n");
printf(" ret\n");
return;
case ND_IF: {
int l = label++;
gen(node->cond);
printf(" pop rax\n");
printf(" cmp rax, 0\n");
if (node->els == NULL) {
printf(" je .Lend%03d\n", l);
gen(node->then);
} else {
printf(" je .Lelse%03d\n", l);
gen(node->then);
printf(" jmp .Lend%03d\n", l);
printf(".Lelse%03d:\n", l);
gen(node->els);
}
printf(".Lend%03d:\n", l);
printf(" push rax\n");
return;
}
case ND_WHILE: {
int l = label++;
printf(".Lbegin%03d:\n", l);
gen(node->cond);
printf(" pop rax\n");
printf(" cmp rax, 0\n");
printf(" je .Lend%03d\n", l);
gen(node->then);
printf(" jmp .Lbegin%03d\n", l);
printf(".Lend%03d:\n", l);
printf(" push rax\n");
return;
}
case ND_FOR: {
int l = label++;
if (node->init != NULL) {
gen(node->init);
}
printf(".Lbegin%03d:\n", l);
if (node->cond != NULL) {
gen(node->cond);
}
printf(" pop rax\n");
printf(" cmp rax, 0\n");
printf(" je .Lend%03d\n", l);
gen(node->then);
if (node->inc != NULL) {
gen(node->inc);
}
printf(" jmp .Lbegin%03d\n", l);
printf(".Lend%03d:\n", l);
printf(" push rax\n");
return;
}
}
gen(node->lhs);
gen(node->rhs);
printf(" pop rdi\n");
printf(" pop rax\n");
switch (node->type) {
case ND_ADD:
printf(" add rax, rdi\n");
break;
case ND_SUB:
printf(" sub rax, rdi\n");
break;
case ND_MUL:
printf(" imul rax, rdi\n");
break;
case ND_DIV:
printf(" cqo\n");
printf(" idiv rdi\n");
break;
case ND_EQ:
printf(" cmp rax, rdi\n");
printf(" sete al\n");
printf(" movzb rax, al\n");
break;
case ND_NE:
printf(" cmp rax, rdi\n");
printf(" setne al\n");
printf(" movzb rax, al\n");
break;
case ND_LT:
printf(" cmp rax, rdi\n");
printf(" setl al\n");
printf(" movzb rax, al\n");
break;
case ND_LE:
printf(" cmp rax, rdi\n");
printf(" setle al\n");
printf(" movzb rax, al\n");
break;
}
printf(" push rax\n");
}
| 27.901408 | 49 | 0.378092 |
dd03d343fc75fde133aab2a226e7571d1176a229 | 1,069 | c | C | libft/ft_strclr.c | amnotme/42_Libft | 192707488954b8083802ba45cde07bdbbd6fefdb | [
"MIT"
] | 4 | 2018-07-28T00:15:23.000Z | 2020-11-29T11:28:02.000Z | libft/ft_strclr.c | amnotme/42_Libft | 192707488954b8083802ba45cde07bdbbd6fefdb | [
"MIT"
] | null | null | null | libft/ft_strclr.c | amnotme/42_Libft | 192707488954b8083802ba45cde07bdbbd6fefdb | [
"MIT"
] | null | null | null | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_strclr.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: lhernand <lhernand@student.us.org> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2017/10/17 21:58:13 by lhernand #+# #+# */
/* Updated: 2017/11/09 13:49:42 by lhernand ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
/*
** Sets every character of the string to the value ’\0’.
*/
void ft_strclr(char *s)
{
int i;
i = 0;
if (s)
{
while (s[i])
s[i++] = '\0';
}
}
| 35.633333 | 80 | 0.181478 |
97be4138be26be7b2fc1af228f44642b78689fb4 | 21,240 | c | C | kernel/msm-4.14/drivers/platform/msm/ipa/test/ipa_test_hw_stats.c | clovadevice/clockplus2 | c347c3e1bf20dbb93ab533c58c2ce11367aa80cd | [
"Apache-2.0"
] | null | null | null | kernel/msm-4.14/drivers/platform/msm/ipa/test/ipa_test_hw_stats.c | clovadevice/clockplus2 | c347c3e1bf20dbb93ab533c58c2ce11367aa80cd | [
"Apache-2.0"
] | null | null | null | kernel/msm-4.14/drivers/platform/msm/ipa/test/ipa_test_hw_stats.c | clovadevice/clockplus2 | c347c3e1bf20dbb93ab533c58c2ce11367aa80cd | [
"Apache-2.0"
] | 1 | 2021-06-29T01:29:23.000Z | 2021-06-29T01:29:23.000Z | /* Copyright (c) 2017-2019, The Linux Foundation. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 and
* only version 2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
#include "ipa_ut_framework.h"
#include "../ipa_v3/ipa_i.h"
#include <linux/netdevice.h>
struct ipa_test_hw_stats_ctx {
u32 odu_prod_hdl;
u32 odu_cons_hdl;
u32 rt4_usb;
u32 rt4_usb_cnt_id;
u32 rt6_usb;
u32 rt6_usb_cnt_id;
u32 rt4_odu_cons;
u32 rt4_odu_cnt_id;
u32 rt6_odu_cons;
u32 rt6_odu_cnt_id;
u32 flt4_usb_cnt_id;
u32 flt6_usb_cnt_id;
u32 flt4_odu_cnt_id;
u32 flt6_odu_cnt_id;
atomic_t odu_pending;
};
static struct ipa_test_hw_stats_ctx *ctx;
static int ipa_test_hw_stats_suite_setup(void **ppriv)
{
IPA_UT_DBG("Start Setup\n");
if (!ctx)
ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
return 0;
}
static int ipa_test_hw_stats_suite_teardown(void *priv)
{
IPA_UT_DBG("Start Teardown\n");
return 0;
}
static void odu_prod_notify(void *priv, enum ipa_dp_evt_type evt,
unsigned long data)
{
struct sk_buff *skb = (struct sk_buff *)data;
switch (evt) {
case IPA_RECEIVE:
dev_kfree_skb_any(skb);
break;
case IPA_WRITE_DONE:
atomic_dec(&ctx->odu_pending);
dev_kfree_skb_any(skb);
break;
default:
IPA_UT_ERR("unexpected evt %d\n", evt);
}
}
static void odu_cons_notify(void *priv, enum ipa_dp_evt_type evt,
unsigned long data)
{
struct sk_buff *skb = (struct sk_buff *)data;
int ret;
switch (evt) {
case IPA_RECEIVE:
if (atomic_read(&ctx->odu_pending) >= 64)
msleep(20);
atomic_inc(&ctx->odu_pending);
skb_put(skb, 100);
ret = ipa_tx_dp(IPA_CLIENT_ODU_PROD, skb, NULL);
while (ret) {
msleep(100);
ret = ipa_tx_dp(IPA_CLIENT_ODU_PROD, skb, NULL);
}
break;
case IPA_WRITE_DONE:
dev_kfree_skb_any(skb);
break;
default:
IPA_UT_ERR("unexpected evt %d\n", evt);
}
}
static int ipa_test_hw_stats_configure(void *priv)
{
struct ipa_sys_connect_params odu_prod_params;
struct ipa_sys_connect_params odu_emb_cons_params;
int res;
/* first connect all additional pipe */
memset(&odu_prod_params, 0, sizeof(odu_prod_params));
memset(&odu_emb_cons_params, 0, sizeof(odu_emb_cons_params));
odu_prod_params.client = IPA_CLIENT_ODU_PROD;
odu_prod_params.desc_fifo_sz = 0x1000;
odu_prod_params.priv = NULL;
odu_prod_params.notify = odu_prod_notify;
res = ipa_setup_sys_pipe(&odu_prod_params,
&ctx->odu_prod_hdl);
if (res) {
IPA_UT_ERR("fail to setup sys pipe ODU_PROD %d\n", res);
return res;
}
odu_emb_cons_params.client = IPA_CLIENT_ODU_EMB_CONS;
odu_emb_cons_params.desc_fifo_sz = 0x1000;
odu_emb_cons_params.priv = NULL;
odu_emb_cons_params.notify = odu_cons_notify;
res = ipa_setup_sys_pipe(&odu_emb_cons_params,
&ctx->odu_cons_hdl);
if (res) {
IPA_UT_ERR("fail to setup sys pipe ODU_EMB_CONS %d\n", res);
ipa_teardown_sys_pipe(ctx->odu_prod_hdl);
return res;
}
IPA_UT_INFO("Configured. Please connect USB RNDIS now\n");
return 0;
}
static int ipa_test_hw_stats_add_FnR(void *priv)
{
struct ipa_ioc_add_rt_rule_v2 *rt_rule;
struct ipa_ioc_add_flt_rule_v2 *flt_rule;
struct ipa_ioc_get_rt_tbl rt_lookup;
struct ipa_ioc_flt_rt_counter_alloc *counter = NULL;
struct ipa_ioc_flt_rt_query *query;
int pyld_size = 0;
int ret;
rt_rule = kzalloc(sizeof(*rt_rule), GFP_KERNEL);
if (!rt_rule) {
IPA_UT_DBG("no mem\n");
return -ENOMEM;
}
rt_rule->rules = (uint64_t)kzalloc(1 *
sizeof(struct ipa_rt_rule_add_v2), GFP_KERNEL);
if (!rt_rule->rules) {
IPA_UT_DBG("no mem\n");
ret = -ENOMEM;
goto free_rt;
}
flt_rule = kzalloc(sizeof(*flt_rule), GFP_KERNEL);
if (!flt_rule) {
IPA_UT_DBG("no mem\n");
ret = -ENOMEM;
goto free_rt;
}
flt_rule->rules = (uint64_t)kzalloc(1 *
sizeof(struct ipa_flt_rule_add_v2), GFP_KERNEL);
if (!flt_rule->rules) {
IPA_UT_DBG("no mem\n");
ret = -ENOMEM;
goto free_flt;
}
counter = kzalloc(sizeof(struct ipa_ioc_flt_rt_counter_alloc),
GFP_KERNEL);
if (!counter) {
IPA_UT_DBG("no mem\n");
ret = -ENOMEM;
goto free_flt;
}
counter->hw_counter.num_counters = 8;
counter->sw_counter.num_counters = 1;
/* allocate counters */
ret = ipa3_alloc_counter_id(counter);
if (ret < 0) {
IPA_UT_DBG("ipa3_alloc_counter_id fails\n");
ret = -ENOMEM;
goto free_counter;
}
/* initially clean all allocated counters */
query = kzalloc(sizeof(struct ipa_ioc_flt_rt_query),
GFP_KERNEL);
if (!query) {
IPA_UT_DBG("no mem\n");
ret = -ENOMEM;
goto free_counter;
}
query->start_id = counter->hw_counter.start_id;
query->end_id = counter->hw_counter.start_id +
counter->hw_counter.num_counters - 1;
query->reset = true;
query->stats_size = sizeof(struct ipa_flt_rt_stats);
pyld_size = IPA_MAX_FLT_RT_CNT_INDEX *
sizeof(struct ipa_flt_rt_stats);
query->stats = (uint64_t)kzalloc(pyld_size, GFP_KERNEL);
if (!query->stats) {
IPA_UT_DBG("no mem\n");
ret = -ENOMEM;
goto free_query;
}
ipa_get_flt_rt_stats(query);
query->start_id = counter->sw_counter.start_id;
query->end_id = counter->sw_counter.start_id +
counter->sw_counter.num_counters - 1;
query->reset = true;
query->stats_size = sizeof(struct ipa_flt_rt_stats);
ipa_get_flt_rt_stats(query);
rt_rule->commit = 1;
rt_rule->ip = IPA_IP_v4;
rt_lookup.ip = rt_rule->ip;
strlcpy(rt_rule->rt_tbl_name, "V4_RT_TO_USB_CONS",
IPA_RESOURCE_NAME_MAX);
strlcpy(rt_lookup.name, rt_rule->rt_tbl_name, IPA_RESOURCE_NAME_MAX);
rt_rule->num_rules = 1;
((struct ipa_rt_rule_add_v2 *)
rt_rule->rules)[0].rule.dst = IPA_CLIENT_USB_CONS;
((struct ipa_rt_rule_add_v2 *)
rt_rule->rules)[0].rule.attrib.attrib_mask = IPA_FLT_DST_PORT;
((struct ipa_rt_rule_add_v2 *)
rt_rule->rules)[0].rule.attrib.dst_port = 5002;
((struct ipa_rt_rule_add_v2 *)
rt_rule->rules)[0].rule.hashable = true;
ctx->rt4_usb_cnt_id = counter->hw_counter.start_id;
IPA_UT_INFO("rt4_usb_cnt_id %u\n", ctx->rt4_usb_cnt_id);
((struct ipa_rt_rule_add_v2 *)
rt_rule->rules)[0].rule.cnt_idx = ctx->rt4_usb_cnt_id;
((struct ipa_rt_rule_add_v2 *)
rt_rule->rules)[0].rule.enable_stats = true;
if (ipa_add_rt_rule_v2(rt_rule) || ((struct ipa_rt_rule_add_v2 *)
rt_rule->rules)[0].status) {
IPA_UT_ERR("failed to install V4 rules\n");
ret = -EFAULT;
goto free_query;
}
if (ipa_get_rt_tbl(&rt_lookup)) {
IPA_UT_ERR("failed to query V4 rules\n");
ret = -EFAULT;
goto free_query;
}
ctx->rt4_usb = rt_lookup.hdl;
rt_rule->commit = 1;
rt_rule->ip = IPA_IP_v6;
rt_lookup.ip = rt_rule->ip;
strlcpy(rt_rule->rt_tbl_name, "V6_RT_TO_USB_CONS",
IPA_RESOURCE_NAME_MAX);
strlcpy(rt_lookup.name, rt_rule->rt_tbl_name, IPA_RESOURCE_NAME_MAX);
rt_rule->num_rules = 1;
((struct ipa_rt_rule_add_v2 *)
rt_rule->rules)[0].rule.dst = IPA_CLIENT_USB_CONS;
((struct ipa_rt_rule_add_v2 *)
rt_rule->rules)[0].rule.attrib.attrib_mask = IPA_FLT_DST_PORT;
((struct ipa_rt_rule_add_v2 *)
rt_rule->rules)[0].rule.attrib.dst_port = 5002;
((struct ipa_rt_rule_add_v2 *)
rt_rule->rules)[0].rule.hashable = true;
ctx->rt6_usb_cnt_id = counter->hw_counter.start_id + 1;
IPA_UT_INFO("rt6_usb_cnt_id %u\n", ctx->rt6_usb_cnt_id);
((struct ipa_rt_rule_add_v2 *)
rt_rule->rules)[0].rule.cnt_idx = ctx->rt6_usb_cnt_id;
((struct ipa_rt_rule_add_v2 *)
rt_rule->rules)[0].rule.enable_stats = true;
if (ipa_add_rt_rule_v2(rt_rule) || ((struct ipa_rt_rule_add_v2 *)
rt_rule->rules)[0].status) {
IPA_UT_ERR("failed to install V4 rules\n");
ret = -EFAULT;
goto free_query;
}
if (ipa_get_rt_tbl(&rt_lookup)) {
IPA_UT_ERR("failed to query V4 rules\n");
ret = -EFAULT;
goto free_query;
}
ctx->rt6_usb = rt_lookup.hdl;
rt_rule->commit = 1;
rt_rule->ip = IPA_IP_v4;
rt_lookup.ip = rt_rule->ip;
strlcpy(rt_rule->rt_tbl_name, "V4_RT_TO_ODU_CONS",
IPA_RESOURCE_NAME_MAX);
strlcpy(rt_lookup.name, rt_rule->rt_tbl_name, IPA_RESOURCE_NAME_MAX);
rt_rule->num_rules = 1;
((struct ipa_rt_rule_add_v2 *)
rt_rule->rules)[0].rule.dst = IPA_CLIENT_ODU_EMB_CONS;
((struct ipa_rt_rule_add_v2 *)
rt_rule->rules)[0].rule.attrib.attrib_mask = IPA_FLT_DST_PORT;
((struct ipa_rt_rule_add_v2 *)
rt_rule->rules)[0].rule.attrib.dst_port = 5002;
((struct ipa_rt_rule_add_v2 *)
rt_rule->rules)[0].rule.hashable = true;
ctx->rt4_odu_cnt_id = counter->hw_counter.start_id + 2;
IPA_UT_INFO("rt4_odu_cnt_id %u\n", ctx->rt4_odu_cnt_id);
((struct ipa_rt_rule_add_v2 *)
rt_rule->rules)[0].rule.cnt_idx = ctx->rt4_odu_cnt_id;
((struct ipa_rt_rule_add_v2 *)
rt_rule->rules)[0].rule.enable_stats = true;
if (ipa_add_rt_rule_v2(rt_rule) || ((struct ipa_rt_rule_add_v2 *)
rt_rule->rules)[0].status) {
IPA_UT_ERR("failed to install V4 rules\n");
ret = -EFAULT;
goto free_query;
}
if (ipa_get_rt_tbl(&rt_lookup)) {
IPA_UT_ERR("failed to query V4 rules\n");
ret = -EFAULT;
goto free_query;
}
ctx->rt4_odu_cons = rt_lookup.hdl;
rt_rule->commit = 1;
rt_rule->ip = IPA_IP_v6;
rt_lookup.ip = rt_rule->ip;
strlcpy(rt_rule->rt_tbl_name, "V6_RT_TO_ODU_CONS",
IPA_RESOURCE_NAME_MAX);
strlcpy(rt_lookup.name, rt_rule->rt_tbl_name, IPA_RESOURCE_NAME_MAX);
rt_rule->num_rules = 1;
((struct ipa_rt_rule_add_v2 *)
rt_rule->rules)[0].rule.dst = IPA_CLIENT_ODU_EMB_CONS;
((struct ipa_rt_rule_add_v2 *)
rt_rule->rules)[0].rule.attrib.attrib_mask = IPA_FLT_DST_PORT;
((struct ipa_rt_rule_add_v2 *)
rt_rule->rules)[0].rule.attrib.dst_port = 5002;
((struct ipa_rt_rule_add_v2 *)
rt_rule->rules)[0].rule.hashable = true;
ctx->rt6_odu_cnt_id = counter->hw_counter.start_id + 3;
IPA_UT_INFO("rt6_odu_cnt_id %u\n", ctx->rt6_odu_cnt_id);
((struct ipa_rt_rule_add_v2 *)
rt_rule->rules)[0].rule.cnt_idx = ctx->rt6_odu_cnt_id;
((struct ipa_rt_rule_add_v2 *)
rt_rule->rules)[0].rule.enable_stats = true;
if (ipa_add_rt_rule_v2(rt_rule) || ((struct ipa_rt_rule_add_v2 *)
rt_rule->rules)[0].status) {
IPA_UT_ERR("failed to install V4 rules\n");
ret = -EFAULT;
goto free_query;
}
if (ipa_get_rt_tbl(&rt_lookup)) {
IPA_UT_ERR("failed to query V4 rules\n");
ret = -EFAULT;
goto free_query;
}
ctx->rt6_odu_cons = rt_lookup.hdl;
flt_rule->commit = 1;
flt_rule->ip = IPA_IP_v4;
flt_rule->ep = IPA_CLIENT_USB_PROD;
flt_rule->num_rules = 1;
((struct ipa_flt_rule_add_v2 *)
flt_rule->rules)[0].at_rear = 0;
((struct ipa_flt_rule_add_v2 *)
flt_rule->rules)[0].rule.action = IPA_PASS_TO_ROUTING;
((struct ipa_flt_rule_add_v2 *)
flt_rule->rules)[0].rule.attrib.attrib_mask = IPA_FLT_DST_PORT;
((struct ipa_flt_rule_add_v2 *)
flt_rule->rules)[0].rule.attrib.dst_port = 5002;
((struct ipa_flt_rule_add_v2 *)
flt_rule->rules)[0].rule.rt_tbl_hdl = ctx->rt4_odu_cons;
((struct ipa_flt_rule_add_v2 *)
flt_rule->rules)[0].rule.hashable = 1;
ctx->flt4_usb_cnt_id = counter->hw_counter.start_id + 4;
IPA_UT_INFO("flt4_usb_cnt_id %u\n", ctx->flt4_usb_cnt_id);
((struct ipa_flt_rule_add_v2 *)
flt_rule->rules)[0].rule.cnt_idx = ctx->flt4_usb_cnt_id;
((struct ipa_flt_rule_add_v2 *)
flt_rule->rules)[0].rule.enable_stats = true;
if (ipa_add_flt_rule_v2(flt_rule) || ((struct ipa_flt_rule_add_v2 *)
flt_rule->rules)[0].status) {
IPA_UT_ERR("failed to install V4 rules\n");
ret = -EFAULT;
goto free_query;
}
flt_rule->commit = 1;
flt_rule->ip = IPA_IP_v6;
flt_rule->ep = IPA_CLIENT_USB_PROD;
flt_rule->num_rules = 1;
((struct ipa_flt_rule_add_v2 *)
flt_rule->rules)[0].at_rear = 0;
((struct ipa_flt_rule_add_v2 *)
flt_rule->rules)[0].rule.action = IPA_PASS_TO_ROUTING;
((struct ipa_flt_rule_add_v2 *)
flt_rule->rules)[0].rule.attrib.attrib_mask = IPA_FLT_DST_PORT;
((struct ipa_flt_rule_add_v2 *)
flt_rule->rules)[0].rule.attrib.dst_port = 5002;
((struct ipa_flt_rule_add_v2 *)
flt_rule->rules)[0].rule.rt_tbl_hdl = ctx->rt6_odu_cons;
((struct ipa_flt_rule_add_v2 *)
flt_rule->rules)[0].rule.hashable = 1;
ctx->flt6_usb_cnt_id = counter->hw_counter.start_id + 5;
IPA_UT_INFO("flt6_usb_cnt_id %u\n", ctx->flt6_usb_cnt_id);
((struct ipa_flt_rule_add_v2 *)
flt_rule->rules)[0].rule.cnt_idx = ctx->flt6_usb_cnt_id;
((struct ipa_flt_rule_add_v2 *)
flt_rule->rules)[0].rule.enable_stats = true;
if (ipa_add_flt_rule_v2(flt_rule) || ((struct ipa_flt_rule_add_v2 *)
flt_rule->rules)[0].status) {
IPA_UT_ERR("failed to install V6 rules\n");
ret = -EFAULT;
goto free_query;
}
flt_rule->commit = 1;
flt_rule->ip = IPA_IP_v4;
flt_rule->ep = IPA_CLIENT_ODU_PROD;
flt_rule->num_rules = 1;
((struct ipa_flt_rule_add_v2 *)
flt_rule->rules)[0].at_rear = 0;
((struct ipa_flt_rule_add_v2 *)
flt_rule->rules)[0].rule.action = IPA_PASS_TO_ROUTING;
((struct ipa_flt_rule_add_v2 *)
flt_rule->rules)[0].rule.attrib.attrib_mask = IPA_FLT_DST_PORT;
((struct ipa_flt_rule_add_v2 *)
flt_rule->rules)[0].rule.attrib.dst_port = 5002;
((struct ipa_flt_rule_add_v2 *)
flt_rule->rules)[0].rule.rt_tbl_hdl = ctx->rt4_usb;
((struct ipa_flt_rule_add_v2 *)
flt_rule->rules)[0].rule.hashable = 1;
ctx->flt4_odu_cnt_id = counter->hw_counter.start_id + 6;
IPA_UT_INFO("flt4_odu_cnt_id %u\n", ctx->flt4_odu_cnt_id);
((struct ipa_flt_rule_add_v2 *)
flt_rule->rules)[0].rule.cnt_idx = ctx->flt4_odu_cnt_id;
((struct ipa_flt_rule_add_v2 *)
flt_rule->rules)[0].rule.enable_stats = true;
if (ipa_add_flt_rule_v2(flt_rule) || ((struct ipa_flt_rule_add_v2 *)
flt_rule->rules)[0].status) {
IPA_UT_ERR("failed to install V4 rules\n");
ret = -EFAULT;
goto free_query;
}
flt_rule->commit = 1;
flt_rule->ip = IPA_IP_v6;
flt_rule->ep = IPA_CLIENT_ODU_PROD;
flt_rule->num_rules = 1;
((struct ipa_flt_rule_add_v2 *)
flt_rule->rules)[0].at_rear = 0;
((struct ipa_flt_rule_add_v2 *)
flt_rule->rules)[0].rule.action = IPA_PASS_TO_ROUTING;
((struct ipa_flt_rule_add_v2 *)
flt_rule->rules)[0].rule.attrib.attrib_mask = IPA_FLT_DST_PORT;
((struct ipa_flt_rule_add_v2 *)
flt_rule->rules)[0].rule.attrib.dst_port = 5002;
((struct ipa_flt_rule_add_v2 *)
flt_rule->rules)[0].rule.rt_tbl_hdl = ctx->rt6_usb;
((struct ipa_flt_rule_add_v2 *)
flt_rule->rules)[0].rule.hashable = 1;
ctx->flt6_odu_cnt_id = counter->hw_counter.start_id + 7;
IPA_UT_INFO("flt4_odu_cnt_id %u\n", ctx->flt6_odu_cnt_id);
((struct ipa_flt_rule_add_v2 *)
flt_rule->rules)[0].rule.cnt_idx = ctx->flt6_odu_cnt_id;
((struct ipa_flt_rule_add_v2 *)
flt_rule->rules)[0].rule.enable_stats = true;
if (ipa_add_flt_rule_v2(flt_rule) || ((struct ipa_flt_rule_add_v2 *)
flt_rule->rules)[0].status) {
IPA_UT_ERR("failed to install V6 rules\n");
ret = -EFAULT;
goto free_query;
}
IPA_UT_INFO(
"Rules added. Please start data transfer on ports 5001/5002\n");
ret = 0;
free_query:
if (query->stats)
kfree((void *)(query->stats));
kfree(query);
free_counter:
kfree(counter);
free_flt:
if (flt_rule->rules)
kfree((void *)(flt_rule->rules));
kfree(flt_rule);
free_rt:
if (rt_rule->rules)
kfree((void *)(rt_rule->rules));
kfree(rt_rule);
return ret;
}
static int ipa_test_hw_stats_query_FnR_one_by_one(void *priv)
{
int ret;
struct ipa_ioc_flt_rt_query *query;
int pyld_size = 0;
query = kzalloc(sizeof(struct ipa_ioc_flt_rt_query), GFP_KERNEL);
if (!query) {
IPA_UT_DBG("no mem\n");
return -ENOMEM;
}
pyld_size = IPA_MAX_FLT_RT_CNT_INDEX *
sizeof(struct ipa_flt_rt_stats);
query->stats = (uint64_t)kzalloc(pyld_size, GFP_KERNEL);
if (!query->stats) {
kfree(query);
return -ENOMEM;
}
/* query 1 by 1 */
IPA_UT_INFO("========query 1 by 1========\n");
query->start_id = ctx->rt4_usb_cnt_id;
query->end_id = ctx->rt4_usb_cnt_id;
ipa_get_flt_rt_stats(query);
IPA_UT_INFO(
"usb v4 route counter %u pkt_cnt %u bytes cnt %llu\n",
ctx->rt4_usb_cnt_id, ((struct ipa_flt_rt_stats *)
query->stats)[0].num_pkts,
((struct ipa_flt_rt_stats *)
query->stats)[0].num_bytes);
query->start_id = ctx->rt6_usb_cnt_id;
query->end_id = ctx->rt6_usb_cnt_id;
ipa_get_flt_rt_stats(query);
IPA_UT_INFO(
"usb v6 route counter %u pkt_cnt %u bytes cnt %llu\n",
ctx->rt6_usb_cnt_id, ((struct ipa_flt_rt_stats *)
query->stats)[0].num_pkts,
((struct ipa_flt_rt_stats *)
query->stats)[0].num_bytes);
query->start_id = ctx->rt4_odu_cnt_id;
query->end_id = ctx->rt4_odu_cnt_id;
ipa_get_flt_rt_stats(query);
IPA_UT_INFO(
"odu v4 route counter %u pkt_cnt %u bytes cnt %llu\n",
ctx->rt4_odu_cnt_id, ((struct ipa_flt_rt_stats *)
query->stats)[0].num_pkts,
((struct ipa_flt_rt_stats *)
query->stats)[0].num_bytes);
query->start_id = ctx->rt6_odu_cnt_id;
query->end_id = ctx->rt6_odu_cnt_id;
ipa_get_flt_rt_stats(query);
IPA_UT_INFO(
"odu v6 route counter %u pkt_cnt %u bytes cnt %llu\n",
ctx->rt6_odu_cnt_id, ((struct ipa_flt_rt_stats *)
query->stats)[0].num_pkts,
((struct ipa_flt_rt_stats *)
query->stats)[0].num_bytes);
query->start_id = ctx->flt4_usb_cnt_id;
query->end_id = ctx->flt4_usb_cnt_id;
ipa_get_flt_rt_stats(query);
IPA_UT_INFO(
"usb v4 filter counter %u pkt_cnt %u bytes cnt %llu\n",
ctx->flt4_usb_cnt_id, ((struct ipa_flt_rt_stats *)
query->stats)[0].num_pkts,
((struct ipa_flt_rt_stats *)
query->stats)[0].num_bytes);
query->start_id = ctx->flt6_usb_cnt_id;
query->end_id = ctx->flt6_usb_cnt_id;
ipa_get_flt_rt_stats(query);
IPA_UT_INFO(
"usb v6 filter counter %u pkt_cnt %u bytes cnt %llu\n",
ctx->flt6_usb_cnt_id, ((struct ipa_flt_rt_stats *)
query->stats)[0].num_pkts,
((struct ipa_flt_rt_stats *)
query->stats)[0].num_bytes);
query->start_id = ctx->flt4_odu_cnt_id;
query->end_id = ctx->flt4_odu_cnt_id;
ipa_get_flt_rt_stats(query);
IPA_UT_INFO(
"odu v4 filter counter %u pkt_cnt %u bytes cnt %llu\n",
ctx->flt4_odu_cnt_id, ((struct ipa_flt_rt_stats *)
query->stats)[0].num_pkts,
((struct ipa_flt_rt_stats *)
query->stats)[0].num_bytes);
query->start_id = ctx->flt6_odu_cnt_id;
query->end_id = ctx->flt6_odu_cnt_id;
ipa_get_flt_rt_stats(query);
IPA_UT_INFO(
"odu v6 filter counter %u pkt_cnt %u bytes cnt %llu\n",
ctx->flt6_odu_cnt_id, ((struct ipa_flt_rt_stats *)
query->stats)[0].num_pkts,
((struct ipa_flt_rt_stats *)
query->stats)[0].num_bytes);
IPA_UT_INFO("================ done ============\n");
ret = 0;
kfree(query);
return ret;
}
static int ipa_test_hw_stats_query_FnR_one_shot(void *priv)
{
int ret, i, start = 0;
struct ipa_ioc_flt_rt_query *query;
int pyld_size = 0;
query = kzalloc(sizeof(struct ipa_ioc_flt_rt_query), GFP_KERNEL);
if (!query) {
IPA_UT_DBG("no mem\n");
return -ENOMEM;
}
pyld_size = IPA_MAX_FLT_RT_CNT_INDEX *
sizeof(struct ipa_flt_rt_stats);
query->stats = (uint64_t)kzalloc(pyld_size, GFP_KERNEL);
if (!query->stats) {
kfree(query);
return -ENOMEM;
}
/* query all together */
IPA_UT_INFO("========query all together========\n");
query->start_id = ctx->rt4_usb_cnt_id;
query->end_id = ctx->flt6_odu_cnt_id;
ipa_get_flt_rt_stats(query);
start = 0;
for (i = ctx->rt4_usb_cnt_id;
i <= ctx->flt6_odu_cnt_id; i++) {
IPA_UT_INFO(
"counter %u pkt_cnt %u bytes cnt %llu\n",
i, ((struct ipa_flt_rt_stats *)
query->stats)[start].num_pkts,
((struct ipa_flt_rt_stats *)
query->stats)[start].num_bytes);
start++;
}
IPA_UT_INFO("================ done ============\n");
ret = 0;
kfree((void *)(query->stats));
kfree(query);
return ret;
}
static int ipa_test_hw_stats_query_FnR_clean(void *priv)
{
int ret, i, start = 0;
struct ipa_ioc_flt_rt_query *query;
int pyld_size = 0;
query = kzalloc(sizeof(struct ipa_ioc_flt_rt_query), GFP_KERNEL);
if (!query) {
IPA_UT_DBG("no mem\n");
return -ENOMEM;
}
pyld_size = IPA_MAX_FLT_RT_CNT_INDEX *
sizeof(struct ipa_flt_rt_stats);
query->stats = (uint64_t)kzalloc(pyld_size, GFP_KERNEL);
if (!query->stats) {
kfree(query);
return -ENOMEM;
}
/* query and reset */
IPA_UT_INFO("========query and reset========\n");
query->start_id = ctx->rt4_usb_cnt_id;
query->reset = true;
query->end_id = ctx->flt6_odu_cnt_id;
start = 0;
ipa_get_flt_rt_stats(query);
for (i = ctx->rt4_usb_cnt_id;
i <= ctx->flt6_odu_cnt_id; i++) {
IPA_UT_INFO(
"counter %u pkt_cnt %u bytes cnt %llu\n",
i, ((struct ipa_flt_rt_stats *)
query->stats)[start].num_pkts,
((struct ipa_flt_rt_stats *)
query->stats)[start].num_bytes);
start++;
}
IPA_UT_INFO("================ done ============\n");
ret = 0;
kfree((void *)(query->stats));
kfree(query);
return ret;
}
/* Suite definition block */
IPA_UT_DEFINE_SUITE_START(hw_stats, "HW stats test",
ipa_test_hw_stats_suite_setup, ipa_test_hw_stats_suite_teardown)
{
IPA_UT_ADD_TEST(configure, "Configure the setup",
ipa_test_hw_stats_configure, false, IPA_HW_v4_0, IPA_HW_MAX),
IPA_UT_ADD_TEST(add_rules, "Add FLT and RT rules",
ipa_test_hw_stats_add_FnR, false, IPA_HW_v4_5, IPA_HW_MAX),
IPA_UT_ADD_TEST(query_stats_one_by_one, "Query one by one",
ipa_test_hw_stats_query_FnR_one_by_one, false,
IPA_HW_v4_5, IPA_HW_MAX),
IPA_UT_ADD_TEST(query_stats_one_shot, "Query one shot",
ipa_test_hw_stats_query_FnR_one_shot, false,
IPA_HW_v4_5, IPA_HW_MAX),
IPA_UT_ADD_TEST(query_stats_one_shot_clean, "Query and clean",
ipa_test_hw_stats_query_FnR_clean, false,
IPA_HW_v4_5, IPA_HW_MAX),
} IPA_UT_DEFINE_SUITE_END(hw_stats);
| 30.042433 | 71 | 0.724388 |
de16baf69fe9bd1de1c4b857d17945bad182f4b3 | 743 | h | C | include/il2cpp/Dpr/UI/UIPokeStatusSelectPanel.h | martmists-gh/BDSP | d6326c5d3ad9697ea65269ed47aa0b63abac2a0a | [
"MIT"
] | 1 | 2022-01-15T20:20:27.000Z | 2022-01-15T20:20:27.000Z | include/il2cpp/Dpr/UI/UIPokeStatusSelectPanel.h | martmists-gh/BDSP | d6326c5d3ad9697ea65269ed47aa0b63abac2a0a | [
"MIT"
] | null | null | null | include/il2cpp/Dpr/UI/UIPokeStatusSelectPanel.h | martmists-gh/BDSP | d6326c5d3ad9697ea65269ed47aa0b63abac2a0a | [
"MIT"
] | null | null | null | #pragma once
#include "il2cpp.h"
void Dpr_UI_UIPokeStatusSelectPanel__Setup (Dpr_UI_UIPokeStatusSelectPanel_o* __this, Pml_PokePara_PokemonParam_o* pokemonParam, const MethodInfo* method_info);
void Dpr_UI_UIPokeStatusSelectPanel__SetInfoStatusRootActive (Dpr_UI_UIPokeStatusSelectPanel_o* __this, bool active, const MethodInfo* method_info);
void Dpr_UI_UIPokeStatusSelectPanel__SetArrowAcitve (Dpr_UI_UIPokeStatusSelectPanel_o* __this, bool active, const MethodInfo* method_info);
void Dpr_UI_UIPokeStatusSelectPanel__PlayAnimArrow (Dpr_UI_UIPokeStatusSelectPanel_o* __this, int32_t move, const MethodInfo* method_info);
void Dpr_UI_UIPokeStatusSelectPanel___ctor (Dpr_UI_UIPokeStatusSelectPanel_o* __this, const MethodInfo* method_info);
| 74.3 | 160 | 0.880215 |
6e25b58074dffc42e0cb123542d6f182347a8233 | 45,767 | c | C | software/linux/driver/xrawdata1/sguser.c | tmatsuya/k7_connectivity_trd_2014.3 | adafcb9048ee0dc58e2e7b95af4c8103dcfd6447 | [
"TCL",
"DOC",
"Unlicense"
] | 2 | 2017-08-20T22:43:03.000Z | 2019-02-20T19:38:20.000Z | software/linux/driver/xrawdata1/sguser.c | tmatsuya/k7_connectivity_trd_2014.3 | adafcb9048ee0dc58e2e7b95af4c8103dcfd6447 | [
"TCL",
"DOC",
"Unlicense"
] | null | null | null | software/linux/driver/xrawdata1/sguser.c | tmatsuya/k7_connectivity_trd_2014.3 | adafcb9048ee0dc58e2e7b95af4c8103dcfd6447 | [
"TCL",
"DOC",
"Unlicense"
] | null | null | null |
/*******************************************************************************
** © Copyright 2012 - 2013 Xilinx, Inc. All rights reserved.
** This file contains confidential and proprietary information of Xilinx, Inc. and
** is protected under U.S. and international copyright and other intellectual property laws.
*******************************************************************************
** ____ ____
** / /\/ /
** /___/ \ / Vendor: Xilinx
** \ \ \/
** \ \
** / /
** /___/ \
** \ \ / \ Kintex-7 PCIe-DMA-DDR3-10GMAC-10GBASER Targeted Reference Design
** \___\/\___\
**
** Device: xc7k325t
** Version: 1.0
** Reference: UG927
**
*******************************************************************************
**
** Disclaimer:
**
** This disclaimer is not a license and does not grant any rights to the materials
** distributed herewith. Except as otherwise provided in a valid license issued to you
** by Xilinx, and to the maximum extent permitted by applicable law:
** (1) THESE MATERIALS ARE MADE AVAILABLE "AS IS" AND WITH ALL FAULTS,
** AND XILINX HEREBY DISCLAIMS ALL WARRANTIES AND CONDITIONS, EXPRESS, IMPLIED, OR STATUTORY,
** INCLUDING BUT NOT LIMITED TO WARRANTIES OF MERCHANTABILITY, NON-INFRINGEMENT, OR
** FITNESS FOR ANY PARTICULAR PURPOSE; and (2) Xilinx shall not be liable (whether in contract
** or tort, including negligence, or under any other theory of liability) for any loss or damage
** of any kind or nature related to, arising under or in connection with these materials,
** including for any direct, or any indirect, special, incidental, or consequential loss
** or damage (including loss of data, profits, goodwill, or any type of loss or damage suffered
** as a result of any action brought by a third party) even if such damage or loss was
** reasonably foreseeable or Xilinx had been advised of the possibility of the same.
** Critical Applications:
**
** Xilinx products are not designed or intended to be fail-safe, or for use in any application
** requiring fail-safe performance, such as life-support or safety devices or systems,
** Class III medical devices, nuclear facilities, applications related to the deployment of airbags,
** or any other applications that could lead to death, personal injury, or severe property or
** environmental damage (individually and collectively, "Critical Applications"). Customer assumes
** the sole risk and liability of any use of Xilinx products in Critical Applications, subject only
** to applicable laws and regulations governing limitations on product liability.
** THIS COPYRIGHT NOTICE AND DISCLAIMER MUST BE RETAINED AS PART OF THIS FILE AT ALL TIMES.
*******************************************************************************/
/*****************************************************************************/
/**
*
* @file sguser.c
*
* This is the Application driver which registers with XDMA driver with private interface.
* This Application driver creates an charracter driver interface with user Application.
*
* Author: Xilinx, Inc.
*
* 2011-2011 (c) Xilinx, Inc. This file is licensed uner the terms of the GNU
* General Public License version 2.1. This program is licensed "as is" without
* any warranty of any kind, whether express or implied.
*
* MODIFICATION HISTORY:
*
* Ver Date Changes
* ----- -------- -------------------------------------------------------
* 1.0 05/15/12 First release
*
*****************************************************************************/
#include <linux/version.h>
#include <linux/module.h>
#include <linux/delay.h>
#include <linux/spinlock.h>
#include <linux/fs.h>
#include <linux/kdev_t.h>
#include <linux/cdev.h>
#include <linux/mm.h>
#include <linux/spinlock.h>
#include <linux/pagemap.h>
#include <linux/slab.h>
#include <asm/uaccess.h>
#include <xpmon_be.h>
#include <xdma_user.h>
#include "xdebug.h"
#include "xio.h"
/* Driver states */
#define UNINITIALIZED 0 /* Not yet come up */
#define INITIALIZED 1 /* But not yet set up for polling */
#define UNREGISTERED 2 /* Unregistering with DMA */
#define POLLING 3 /* But not yet registered with DMA */
#define REGISTERED 4 /* Registered with DMA */
#define CLOSED 5 /* Driver is being brought down */
/* DMA characteristics */
#define MYBAR 0
#ifdef XRAWDATA0
#define MYHANDLE HANDLE_0
#else
#define MYHANDLE HANDLE_1
#endif
#ifdef XRAWDATA0
#define MYNAME "Raw Data 0"
#define DEV_NAME "xraw_data0"
#else
#define MYNAME "Raw Data 1"
#define DEV_NAME "xraw_data1"
#endif
#define DESIGN_MODE_ADDRESS 0x9004 /* Used to configure HW for different modes */
#ifdef RAW_ETH
#define PERF_DESIGN_MODE 0x00000000
#else
#define PERF_DESIGN_MODE 0x00000003
#endif
#ifdef RAW_ETH
#define WRBURST_0 0x9308
#define WRBURST_1 0x9318
#define WRBURST_2 0x9328
#define WRBURST_3 0x9338
#define RDBURST_0 0x930C
#define RDBURST_1 0x931C
#define RDBURST_2 0x932C
#define RDBURST_3 0x933C
#define BURST_SIZE 256
#define MDIO_ConfigWord_0 0x500 /* MDIO Config Word 0 */
#define MDIO_ConfigWord_1 0x504 /* MDIO Config Word 1 */
#define MDIO_TX_DATA 0x508 /* MDIO TX Data */
#define MDIO_RX_DATA 0x50C /* MDIO RX Data */
#define YES 1
#define MDIO_READY(X) ((XIo_In32(X + MDIO_ConfigWord_1 ) >> 7 ) & 0x00000001)
#define MDIO_LINK_STATUS_UP(X) ((XIo_In32(X + MDIO_RX_DATA ) >> 12) & 0x00000001)
#define XXGE_RCW0_OFFSET 0x00000400 /**< Rx Configuration Word 0 */
#define XXGE_RCW1_OFFSET 0x00000404 /**< Rx Configuration Word 1 */
#define XXGE_TC_OFFSET 0x00000408 /**< Tx Configuration */
#endif
#ifdef XRAWDATA0
#define TX_CONFIG_ADDRESS 0x9108
#define RX_CONFIG_ADDRESS 0x9100
#define PKT_SIZE_ADDRESS 0x9104
#define STATUS_ADDRESS 0x910C
#ifndef RAW_ETH
#define SEQNO_WRAP_REG 0x9110
#endif
/* Test start / stop conditions */
#define LOOPBACK 0x00000002 /* Enable TX data loopback onto RX */
#else
#define TX_CONFIG_ADDRESS 0x9208 /* Reg for controlling TX data */
#define RX_CONFIG_ADDRESS 0x9200 /* Reg for controlling RX pkt generator */
#define PKT_SIZE_ADDRESS 0x9204 /* Reg for programming packet size */
#define STATUS_ADDRESS 0x920C /* Reg for checking TX pkt checker status */
#ifndef RAW_ETH
#define SEQNO_WRAP_REG 0x9210 /* Reg for sequence number wrap around */
#endif
/* Test start / stop conditions */
#define LOOPBACK 0x00000002 /* Enable TX data loopback onto RX */
#endif
/* Test start / stop conditions */
#define PKTCHKR 0x00000001 /* Enable TX packet checker */
#define PKTGENR 0x00000001 /* Enable RX packet generator */
#define CHKR_MISMATCH 0x00000001 /* TX checker reported data mismatch */
#ifdef XRAWDATA0
#define ENGINE_TX 0
#define ENGINE_RX 32
#ifdef RAW_ETH
#define NW_PATH_OFFSET 0xB000
#define NW_PATH_OFFSET_OTHER 0xC000
#endif
#else
#define ENGINE_TX 1
#define ENGINE_RX 33
#ifdef RAW_ETH
#define NW_PATH_OFFSET 0xC000
#define NW_PATH_OFFSET_OTHER 0xB000
#endif
#endif
/* Packet characteristics */
#define BUFSIZE (PAGE_SIZE)
#ifdef RAW_ETH
#define MAXPKTSIZE (4*PAGE_SIZE - 1)
#else
#define MAXPKTSIZE (8*PAGE_SIZE)
#endif
#define MINPKTSIZE (64)
#define NUM_BUFS 2000
#define BUFALIGN 8
#define BYTEMULTIPLE 8 /**< Lowest sub-multiple of memory path */
struct cdev *xrawCdev = NULL;
int xraw_DriverState = UNINITIALIZED;
int xraw_UserOpen = 0;
void *handle[4] = { NULL, NULL, NULL, NULL };
#ifdef X86_64
u64 TXbarbase, RXbarbase;
#else
u32 TXbarbase, RXbarbase;
#endif
u32 RawTestMode = TEST_STOP;
u32 RawMinPktSize = MINPKTSIZE, RawMaxPktSize = MAXPKTSIZE;
#ifdef BACK_PRESSURE
#define NO_BP 1
#define YES_BP 2
#define MAX_QUEUE_THRESHOLD 12288
#define MIN_QUEUE_THRESHOLD 8192
u8 impl_bp = NO_BP;/*back pressure implementation flag */
#endif
typedef struct
{
int TotalNum;
int AllocNum;
int FirstBuf;
int LastBuf;
int FreePtr;
int AllocPtr;
unsigned char *origVA[NUM_BUFS];
} Buffer;
Buffer TxBufs;
Buffer RxBufs;
char xrawTrans[4096];
/* For exclusion */
spinlock_t RawLock;
#ifdef XRAWDATA0
#define DRIVER_NAME "xrawdata0_driver"
#define DRIVER_DESCRIPTION "Xilinx Raw Data0 Driver "
#else
#define DRIVER_NAME "xrawdata1_driver"
#define DRIVER_DESCRIPTION "Xilinx Raw Data1 Driver"
#endif
/* bufferInfo queue implementation.
*
* the variables declared here are only used by either putBufferInfo or getBufferInfo.
* These should always be guarded by QUpdateLock.
*
*/
#define MAX_BUFF_INFO 16384
static int TestStop=0;
typedef struct BufferInfoQ
{
spinlock_t iLock; /** < will be init to unlock by default */
BufferInfo iList[MAX_BUFF_INFO]; /** < Buffer Queue implimented in driver for storing incoming Pkts */
unsigned int iPutIndex; /** < Index to put the packets in Queue */
unsigned int iGetIndex; /** < Index to get the packets in Queue */
unsigned int iPendingDone; /** < Indicates number of packets to read */
} BufferInfoQue;
BufferInfoQue TxDoneQ; // assuming everything to be initialized to 0 as these are global
BufferInfoQue RxDoneQ; // assuming everything to be initialized to 0 as these are global
// routines use for queue manipulation.
/*
putBuffInfo is used for adding an buffer element to the queue.
it updates the queue parameters (by holding QUpdateLock).
Returns: 0 for success / -1 for failure
*/
int putBuffInfo (BufferInfoQue * bQue, BufferInfo buff);
/*
getBuffInfo is used for fetching the oldest buffer info from the queue.
it updates the queue parameters (by holding QUpdateLock).
Returns: 0 for success / -1 for failure
*/
int getBuffInfo (BufferInfoQue * bQue, BufferInfo * buff);
#ifdef X86_64
int myInit (u64, unsigned int);
#else
int myInit (unsigned int, unsigned int);
#endif
int myFreePkt (void *, unsigned int *, int, unsigned int);
static int DmaSetupTransmit (void *, int, const char __user *, size_t);
static int DmaSetupReceive(void * , int ,const char __user * , size_t );
int myGetRxPkt (void *, PktBuf *, unsigned int, int, unsigned int);
int myPutTxPkt (void *, PktBuf *, int, unsigned int);
int myPutRxPkt (void *, PktBuf *, int, unsigned int);
int mySetState (void *hndl, UserState * ustate, unsigned int privdata);
int myGetState (void *hndl, UserState * ustate, unsigned int privdata);
/* For checking data integrity */
unsigned int TxBufCnt = 0;
unsigned int RxBufCnt = 0;
unsigned int ErrCnt = 0;
static inline void
PrintSummary (void)
{
#if 0
u32 val;
printk ("---------------------------------------------------\n");
printk ("%s Driver results Summary:-\n", MYNAME);
printk ("Current Run Min Packet Size = %d, Max Packet Size = %d\n",
RawMinPktSize, RawMaxPktSize);
printk
("Buffers Transmitted = %u, Buffers Received = %u, Error Count = %u\n",
TxBufCnt, RxBufCnt, ErrCnt);
val = XIo_In32 (TXbarbase + STATUS_ADDRESS);
printk ("Data Mismatch Status = %x\n", val);
#ifdef RAW_ETH
printk("XGEMAC TX Bytes 0 = %x\t", XIo_In32(TXbarbase+NW_PATH_OFFSET+0x208));
printk("XGEMAC TX Bytes 1 = %x\n", XIo_In32(TXbarbase+NW_PATH_OFFSET+0x20C));
printk("XGEMAC RX Bytes 0 = %x\t", XIo_In32(TXbarbase+NW_PATH_OFFSET+0x200));
printk("XGEMAC RX Bytes 1 = %x\n", XIo_In32(TXbarbase+NW_PATH_OFFSET+0x204));
#endif
printk ("---------------------------------------------------\n");
#endif
}
#ifdef X86_64
int
myInit (u64 barbase, unsigned int privdata)
{
#else
int
myInit (unsigned int barbase, unsigned int privdata)
{
#endif
log_normal ("Reached myInit with barbase %x and privdata %x\n",
barbase, privdata);
spin_lock_bh (&RawLock);
if (privdata == 0x54545454) // So that this is done only once
{
TXbarbase = barbase;
}
else if (privdata == 0x54545456) // So that this is done only once
{
RXbarbase = barbase;
}
TxBufCnt = 0;
RxBufCnt = 0;
ErrCnt = 0;
/* Stop any running tests. The driver could have been unloaded without
* stopping running tests the last time. Hence, good to reset everything.
*/
XIo_Out32 (TXbarbase + TX_CONFIG_ADDRESS, 0);
XIo_Out32 (TXbarbase + RX_CONFIG_ADDRESS, 0);
spin_unlock_bh (&RawLock);
return 0;
}
int
myPutRxPkt (void *hndl, PktBuf * vaddr, int numpkts, unsigned int privdata)
{
int i;
unsigned int flags;
PktBuf *pbuf = vaddr;
static int pktSize;
unsigned char *usrAddr = NULL;
BufferInfo tempBuffInfo;
static int noPages;
/* Check driver state */
if (xraw_DriverState != REGISTERED)
{
printk ("Driver does not seem to be ready\n");
return -1;
}
/* Check handle value */
if (hndl != handle[2])
{
log_normal ("Came with wrong handle %x\n", (u32) hndl);
return -1;
}
for (i = 0; i < numpkts; i++)
{
flags = vaddr->flags;
pbuf = vaddr;
/*release the page lock*/
page_cache_release( (struct page *)pbuf->pageAddr);
pktSize = pktSize + pbuf->size;
if (flags & PKT_SOP)
{
usrAddr = pbuf->bufInfo;
pktSize = pbuf->size;
}
noPages++;
if (flags & PKT_EOP)
{
tempBuffInfo.bufferAddress = usrAddr;
tempBuffInfo.buffSize = pktSize;
tempBuffInfo.noPages= noPages ;
tempBuffInfo.endAddress= pbuf->bufInfo;
tempBuffInfo.endSize=pbuf->size;
/* put the packet in driver queue*/
putBuffInfo (&RxDoneQ, tempBuffInfo);
pktSize = 0;
noPages=0;
usrAddr = NULL;
}
vaddr++;
}
/* Return packet buffers to free pool */
return 0;
}
int
myGetRxPkt (void *hndl, PktBuf * vaddr, unsigned int size, int numpkts,
unsigned int privdata)
{
#ifdef USE_LATER
unsigned char *bufVA;
PktBuf *pbuf;
int i;
log_verbose(KERN_INFO "myGetRxPkt: Came with handle %p size %d privdata %x\n",
hndl, size, privdata);
/* Check driver state */
if (xraw_DriverState != REGISTERED)
{
printk ("Driver does not seem to be ready\n");
return 0;
}
/* Check handle value */
if (hndl != handle[2])
{
printk ("Came with wrong handle\n");
return 0;
}
/* Check size value */
if (size != BUFSIZE)
printk ("myGetRxPkt: Requested size %d does not match expected %d\n",
size, (u32) BUFSIZE);
spin_lock_bh (&RawLock);
for (i = 0; i < numpkts; i++)
{
pbuf = &(vaddr[i]);
/* Allocate a buffer. DMA driver will map to PCI space. */
bufVA = AllocBuf (&RxBufs);
log_verbose (KERN_INFO
"myGetRxPkt: The buffer after alloc is at address %x size %d\n",
(u32) bufVA, (u32) BUFSIZE);
if (bufVA == NULL)
{
log_normal (KERN_ERR "RX: AllocBuf failed\n");
break;
}
pbuf->pktBuf = bufVA;
pbuf->bufInfo = bufVA;
pbuf->size = BUFSIZE;
}
spin_unlock_bh (&RawLock);
log_verbose (KERN_INFO "Requested %d, allocated %d buffers\n", numpkts, i);
return i;
#endif
return 0;
}
int
myPutTxPkt (void *hndl, PktBuf * vaddr, int numpkts, unsigned int privdata)
{
int i;
unsigned int flags;
PktBuf *pbuf = vaddr;
static int pktSize;
unsigned char *usrAddr = NULL;
BufferInfo tempBuffInfo;
log_verbose (KERN_INFO
"Reached myPutTxPkt with handle %p, numpkts %d, privdata %x\n",
hndl, numpkts, privdata);
/* Check driver state */
if (xraw_DriverState != REGISTERED)
{
printk ("Driver does not seem to be ready\n");
return -1;
}
/* Check handle value */
if (hndl != handle[0])
{
printk ("Came with wrong handle\n");
return -1;
}
/* Just check if we are on the way out */
// spin_lock_bh(&RawLock);
for (i = 0; i < numpkts; i++)
{
flags = vaddr->flags;
pbuf = vaddr;
if(pbuf->pageAddr)
page_cache_release( (struct page *)pbuf->pageAddr);
pktSize = pktSize + pbuf->size;
if (flags & PKT_SOP)
{
usrAddr = pbuf->bufInfo;
pktSize = pbuf->size;
}
if (flags & PKT_EOP)
{
tempBuffInfo.bufferAddress = usrAddr;
tempBuffInfo.buffSize = pktSize;
putBuffInfo (&TxDoneQ, tempBuffInfo);
pktSize = 0;
usrAddr = NULL;
}
vaddr++;
}
return 0;
}
int
mySetState (void *hndl, UserState * ustate, unsigned int privdata)
{
int val;
#ifndef RAW_ETH
int seqno;
#endif
static unsigned int testmode;
log_verbose (KERN_INFO "Reached mySetState with privdata %x\n", privdata);
/* Check driver state */
if (xraw_DriverState != REGISTERED)
{
printk ("Driver does not seem to be ready\n");
return EFAULT;
}
/* Check handle value */
if ((hndl != handle[0]) && (hndl != handle[2]))
{
printk ("Came with wrong handle\n");
return EBADF;
}
/* Valid only for TX engine */
if (privdata == 0x54545454)
{
spin_lock_bh (&RawLock);
/* Set up the value to be written into the register */
RawTestMode = ustate->TestMode;
if (RawTestMode & TEST_START)
{
testmode = 0;
TestStop=0;
if (RawTestMode & ENABLE_LOOPBACK)
testmode |= LOOPBACK;
if (RawTestMode & ENABLE_PKTCHK)
testmode |= PKTCHKR;
if (RawTestMode & ENABLE_PKTGEN)
testmode |= PKTGENR;
}
else
{
/* Deliberately not clearing the loopback bit, incase a
* loopback test was going on - allows the loopback path
* to drain off packets. Just stopping the source of packets.
*/
if (RawTestMode & ENABLE_PKTCHK)
testmode &= ~PKTCHKR;
if (RawTestMode & ENABLE_PKTGEN)
testmode &= ~PKTGENR;
TestStop=1;
/* enable this if we need to Disable loop back also */
#ifdef USE_LATER
if (RawTestMode & ENABLE_LOOPBACK)
testmode &= ~LOOPBACK;
#endif
}
log_verbose("SetState TX with RawTestMode %x, reg value %x\n",
RawTestMode, testmode);
/* Now write the registers */
if (RawTestMode & TEST_START)
{
if (!
(RawTestMode &
(ENABLE_PKTCHK | ENABLE_PKTGEN | ENABLE_LOOPBACK)))
{
printk ("%s Driver: TX Test Start called with wrong mode %x\n",
MYNAME, testmode);
RawTestMode = 0;
spin_unlock_bh (&RawLock);
return EBADRQC;
}
log_verbose("%s Driver: Starting the test - mode %x, reg %x\n",
MYNAME, RawTestMode, testmode);
/* Next, set packet sizes. Ensure they don't exceed PKTSIZEs */
RawMinPktSize = ustate->MinPktSize;
RawMaxPktSize = ustate->MaxPktSize;
/* Set RX packet size for memory path */
val = RawMaxPktSize;
log_verbose("Reg %x = %x\n", PKT_SIZE_ADDRESS, val);
RawMinPktSize = RawMaxPktSize = val;
/* Now ensure the sizes remain within bounds */
if (RawMaxPktSize > MAXPKTSIZE)
RawMinPktSize = RawMaxPktSize = MAXPKTSIZE;
if (RawMinPktSize < MINPKTSIZE)
RawMinPktSize = RawMaxPktSize = MINPKTSIZE;
if (RawMinPktSize > RawMaxPktSize)
RawMinPktSize = RawMaxPktSize;
val = RawMaxPktSize;
#ifndef RAW_ETH
log_verbose("========Reg %x = %d\n",DESIGN_MODE_ADDRESS, PERF_DESIGN_MODE);
XIo_Out32 (TXbarbase + DESIGN_MODE_ADDRESS,PERF_DESIGN_MODE);
log_verbose("DESIGN MODE %d\n",PERF_DESIGN_MODE );
#endif
log_verbose("========Reg %x = %d\n", PKT_SIZE_ADDRESS, val);
XIo_Out32 (TXbarbase + PKT_SIZE_ADDRESS, val);
log_verbose("RxPktSize %d\n", val);
#ifndef RAW_ETH
seqno= TX_CONFIG_SEQNO;
log_verbose("========Reg %x = %d\n",SEQNO_WRAP_REG, seqno);
XIo_Out32 (TXbarbase + SEQNO_WRAP_REG , seqno);
log_verbose("SeqNo Wrap around %d\n", seqno);
#endif
#ifdef RAW_ETH
#ifdef XRAWDATA0
XIo_Out32(TXbarbase+WRBURST_0, BURST_SIZE );
XIo_Out32(TXbarbase+RDBURST_0, BURST_SIZE );
XIo_Out32(TXbarbase+WRBURST_1, BURST_SIZE );
XIo_Out32(TXbarbase+RDBURST_1, BURST_SIZE );
#else
XIo_Out32(TXbarbase+WRBURST_2, BURST_SIZE );
XIo_Out32(TXbarbase+RDBURST_2, BURST_SIZE );
XIo_Out32(TXbarbase+WRBURST_3, BURST_SIZE );
XIo_Out32(TXbarbase+RDBURST_3, BURST_SIZE );
#endif
#endif
mdelay(1);
/* Incase the last test was a loopback test, that bit may not be cleared. */
XIo_Out32 (TXbarbase + TX_CONFIG_ADDRESS, 0);
if (RawTestMode & (ENABLE_PKTCHK | ENABLE_LOOPBACK))
{
log_verbose("========Reg %x = %x\n", TX_CONFIG_ADDRESS, testmode);
XIo_Out32 (TXbarbase + TX_CONFIG_ADDRESS, testmode);
#ifdef RAW_ETH
log_verbose("Reg[DESIGN_MODE] = %x\n", XIo_In32(TXbarbase+DESIGN_MODE_ADDRESS));
XIo_Out32(TXbarbase+DESIGN_MODE_ADDRESS,PERF_DESIGN_MODE);
log_verbose("Disable performance mode....\nReg[DESIGN_MODE] = %x\n", XIo_In32(TXbarbase+DESIGN_MODE_ADDRESS));
if(RawTestMode & ENABLE_CRISCROSS)
{
printk("XGEMAC-RCW1 = %x\n", XIo_In32(TXbarbase + NW_PATH_OFFSET_OTHER + XXGE_RCW1_OFFSET));
XIo_Out32(TXbarbase+NW_PATH_OFFSET_OTHER+XXGE_RCW1_OFFSET, 0x50000000);
printk("XGEMAC-RCW1 = %x\n", XIo_In32(TXbarbase + NW_PATH_OFFSET_OTHER + XXGE_RCW1_OFFSET));
}
else
{
printk("XGEMAC-RCW1 = %x\n", XIo_In32(TXbarbase + NW_PATH_OFFSET + XXGE_RCW1_OFFSET));//mrinals
XIo_Out32(TXbarbase+NW_PATH_OFFSET+XXGE_RCW1_OFFSET, 0x50000000);
printk("XGEMAC-RCW1 = %x\n", XIo_In32(TXbarbase + NW_PATH_OFFSET + XXGE_RCW1_OFFSET));//mrinals
}
printk("XGEMAC-TC = %x\n", XIo_In32(TXbarbase + NW_PATH_OFFSET + XXGE_TC_OFFSET));//mrinals
XIo_Out32(TXbarbase+NW_PATH_OFFSET+XXGE_TC_OFFSET, 0x50000000);
printk("XGEMAC-TC = %x\n", XIo_In32(TXbarbase + NW_PATH_OFFSET + XXGE_TC_OFFSET)); //mrinalsi
printk("XGEMAC 0 TX Bytes 1 = %x\n", XIo_In32(TXbarbase+NW_PATH_OFFSET+0x20C));
printk("XGEMAC 0 RX Bytes 0 = %x\t", XIo_In32(TXbarbase+NW_PATH_OFFSET+0x200));
printk("XGEMAC 0 RX Bytes 1 = %x\n", XIo_In32(TXbarbase+NW_PATH_OFFSET+0x204));
printk("XGEMAC 0 Frames Transmitted OK 0 = %x\n", XIo_In32(TXbarbase+NW_PATH_OFFSET+0x2D8));
printk("XGEMAC 0 Frames Transmitted OK 1 = %x\n", XIo_In32(TXbarbase+NW_PATH_OFFSET+0x2DC));
printk("XGEMAC 0 Frames Received OK 0 = %x\n", XIo_In32(TXbarbase+NW_PATH_OFFSET+0x290));
printk("XGEMAC 0 Frames Received OK 1 = %x\n", XIo_In32(TXbarbase+NW_PATH_OFFSET+0x294));
printk("XGEMAC 1 TX Bytes 0 = %x\t", XIo_In32(TXbarbase+NW_PATH_OFFSET_OTHER+0x208));
printk("XGEMAC 1 TX Bytes 1 = %x\n", XIo_In32(TXbarbase+NW_PATH_OFFSET_OTHER+0x20C));
printk("XGEMAC 1 RX Bytes 0 = %x\t", XIo_In32(TXbarbase+NW_PATH_OFFSET_OTHER+0x200));
printk("XGEMAC 1 RX Bytes 1 = %x\n", XIo_In32(TXbarbase+NW_PATH_OFFSET_OTHER+0x204));
printk("XGEMAC 1 Frames Transmitted OK 0 = %x\n", XIo_In32(TXbarbase+NW_PATH_OFFSET_OTHER+0x2D8));
printk("XGEMAC 1 Frames Transmitted OK 1 = %x\n", XIo_In32(TXbarbase+NW_PATH_OFFSET_OTHER+0x2DC));
printk("XGEMAC 1 Frames Received OK 0 = %x\n", XIo_In32(TXbarbase+NW_PATH_OFFSET_OTHER+0x290));
printk("XGEMAC 1 Frames Received OK 1 = %x\n", XIo_In32(TXbarbase+NW_PATH_OFFSET_OTHER+0x294));
#endif
}
if (RawTestMode & ENABLE_PKTGEN)
{
log_verbose("========Reg %x = %x\n", RX_CONFIG_ADDRESS, testmode);
XIo_Out32 (TXbarbase + RX_CONFIG_ADDRESS, testmode);
}
}
/* Else, stop the test. Do not remove any loopback here because
* the DMA queues and hardware FIFOs must drain first.
*/
else
{
log_verbose("%s Driver: Stopping the test, mode %x\n", MYNAME,
testmode);
log_verbose("========Reg %x = %x\n", TX_CONFIG_ADDRESS, testmode)
XIo_Out32 (TXbarbase + TX_CONFIG_ADDRESS, testmode);
log_verbose ("========Reg %x = %x\n", RX_CONFIG_ADDRESS, testmode);
XIo_Out32 (TXbarbase + RX_CONFIG_ADDRESS, testmode);
mdelay(200);
}
PrintSummary ();
spin_unlock_bh (&RawLock);
}
return 0;
}
int
myGetState (void *hndl, UserState * ustate, unsigned int privdata)
{
static int iter = 0;
/* Same state is being returned for both engines */
ustate->LinkState = LINK_UP;
ustate->DataMismatch= XIo_In32 (TXbarbase + STATUS_ADDRESS);
ustate->MinPktSize = RawMinPktSize;
ustate->MaxPktSize = RawMaxPktSize;
ustate->TestMode = RawTestMode;
if (privdata == 0x54545454)
ustate->Buffers = TxBufs.TotalNum;
else
ustate->Buffers = RxBufs.TotalNum;
if (iter++ >= 4)
{
PrintSummary ();
iter = 0;
}
return 0;
}
#define QSUCCESS 0
#define QFAILURE -1
/*
putBuffInfo is used for adding an buffer element to the queue.
it updates the queue parameters (by holding QUpdateLock).
Returns: 0 for success / -1 for failure
*/
int
putBuffInfo (BufferInfoQue * bQue, BufferInfo buff)
{
// assert (bQue != NULL)
int currentIndex = 0;
spin_lock_bh (&(bQue->iLock));
currentIndex = (bQue->iPutIndex + 1) % MAX_BUFF_INFO;
if (currentIndex == bQue->iGetIndex)
{
spin_unlock_bh (&(bQue->iLock));
printk (KERN_ERR "%s: BufferInfo Q is FULL in %s , drop the incoming buffers",
__func__,__FILE__);
return QFAILURE; // array full
}
bQue->iPutIndex = currentIndex;
bQue->iList[bQue->iPutIndex] = buff;
bQue->iPendingDone++;
#ifdef BACK_PRESSURE
if(bQue == &RxDoneQ)
{
if((impl_bp == NO_BP)&& ( bQue->iPendingDone > MAX_QUEUE_THRESHOLD))
{
impl_bp = YES_BP;
printk(KERN_ERR "XXXXXX Maximum Queue Threshold reached.Turning on BACK PRESSURE XRAW0 %d \n",bQue->iPendingDone);
}
}
#endif
spin_unlock_bh (&(bQue->iLock));
return QSUCCESS;
}
/*
getBuffInfo is used for fetching the oldest buffer info from the queue.
it updates the queue parameters (by holding QUpdateLock).
Returns: 0 for success / -1 for failure
*/
int
getBuffInfo (BufferInfoQue * bQue, BufferInfo * buff)
{
// assert if bQue is NULL
if (!buff || !bQue)
{
printk (KERN_ERR "%s: BAD BufferInfo pointer", __func__);
return QFAILURE;
}
spin_lock_bh (&(bQue->iLock));
// assuming we get the right buffer
if (!bQue->iPendingDone)
{
spin_unlock_bh (&(bQue->iLock));
log_verbose(KERN_ERR "%s: BufferInfo Q is Empty",__func__);
return QFAILURE;
}
bQue->iGetIndex++;
bQue->iGetIndex %= MAX_BUFF_INFO;
*buff = bQue->iList[bQue->iGetIndex];
bQue->iPendingDone--;
#ifdef BACK_PRESSURE
if(bQue == &RxDoneQ)
{
if((impl_bp == YES_BP) && (bQue->iPendingDone < MIN_QUEUE_THRESHOLD))
{
impl_bp = NO_BP;
printk(KERN_ERR "XXXXXXX Minimum Queue Threshold reached.Turning off Back Pressure at %d %s\n",__LINE__,__FILE__);
}
}
#endif
spin_unlock_bh (&(bQue->iLock));
return QSUCCESS;
}
#define WRITE_TO_CARD 0
#define READ_FROM_CARD 1
static int DmaSetupReceive(void * hndl, int num ,const char __user * buffer, size_t length)
{
int j;
int total, result;
PktBuf * pbuf;
int status;
int offset;
unsigned int allocPages;
unsigned long first, last;
struct page** cachePages;
PktBuf **pkts;
/* Check driver state */
if(xraw_DriverState != REGISTERED)
{
printk("Driver does not seem to be ready\n");
return 0;
}
/* Check handle value */
if(hndl != handle[2])
{
printk("Came with wrong handle\n");
return 0;
}
/* Check number of packets */
if(!num)
{
printk("Came with 0 packets for sending\n");
return 0;
}
total = 0;
/****************************************************************/
// SECTION 1: generate CACHE PAGES for USER BUFFER
//
offset = offset_in_page(buffer);
first = ((unsigned long)buffer & PAGE_MASK) >> PAGE_SHIFT;
last = (((unsigned long)buffer + length-1) & PAGE_MASK) >> PAGE_SHIFT;
allocPages = (last-first)+1;
pkts = kmalloc( allocPages * (sizeof(PktBuf*)), GFP_KERNEL);
if(pkts == NULL)
{
printk(KERN_ERR "Error: unable to allocate memory for pkts\n");
return -1;
}
cachePages = kmalloc( (allocPages * (sizeof(struct page*))), GFP_KERNEL );
if( cachePages == NULL )
{
printk(KERN_ERR "Error: unable to allocate memory for cachePages\n");
kfree(pkts);
return -1;
}
memset(cachePages, 0, sizeof(allocPages * sizeof(struct page*)) );
down_read(&(current->mm->mmap_sem));
status = get_user_pages(current, // current process id
current->mm, // mm of current process
(unsigned long)buffer, // user buffer
allocPages,
READ_FROM_CARD,
0, /* don't force */
cachePages,
NULL);
up_read(¤t->mm->mmap_sem);
if( status < allocPages) {
printk(KERN_ERR ".... Error: requested pages=%d, granted pages=%d ....\n", allocPages, status);
for(j=0; j<status; j++)
page_cache_release(cachePages[j]);
kfree(pkts);
kfree(cachePages);
return -1;
}
allocPages = status; // actual number of pages system gave
for(j=0; j< allocPages; j++) /* Packet fragments loop */
{
pbuf = kmalloc( (sizeof(PktBuf)), GFP_KERNEL);
if(pbuf == NULL) {
printk(KERN_ERR "Insufficient Memory !!\n");
for(j--; j>=0; j--)
kfree(pkts[j]);
for(j=0; j<allocPages; j++)
page_cache_release(cachePages[j]);
kfree(pkts);
kfree(cachePages);
return -1;
}
//spin_lock_bh(&RawLock);
pkts[j] = pbuf;
// first buffer would start at some offset, need not be on page boundary
if(j==0) {
pbuf->size = ((PAGE_SIZE)-offset);
}
else {
if(j == (allocPages-1)) {
pbuf->size = length-total;
}
else pbuf->size = (PAGE_SIZE);
}
pbuf->pktBuf = (unsigned char*)cachePages[j];
pbuf->bufInfo = (unsigned char *) buffer + total;
pbuf->pageAddr= (unsigned char*)cachePages[j];
pbuf->flags = PKT_ALL;
total += pbuf->size;
//spin_unlock_bh(&RawLock);
}
/****************************************************************/
allocPages = j; // actually used pages
result = DmaSendPages(hndl, pkts, allocPages);
if(result == -1)
{
for(j=0; j<allocPages; j++) {
page_cache_release(cachePages[j]);
}
total = 0;
}
kfree(cachePages);
for(j=0; j<allocPages; j++) {
kfree(pkts[j]);
}
kfree(pkts);
return total;
}
static int DmaSetupTransmit(void * hndl, int num ,const char __user * buffer, size_t length)
{
int j;
int total, result;
PktBuf * pbuf;
int status;
int offset;
unsigned int allocPages;
unsigned long first, last;
struct page** cachePages;
PktBuf **pkts;
/* Check driver state */
if(xraw_DriverState != REGISTERED)
{
printk("Driver does not seem to be ready\n");
return 0;
}
/* Check handle value */
if(hndl != handle[0])
{
printk("Came with wrong handle\n");
return 0;
}
/* Check number of packets */
if(!num)
{
printk("Came with 0 packets for sending\n");
return 0;
}
total = 0;
/****************************************************************/
// SECTION 1: generate CACHE PAGES for USER BUFFER
//
offset = offset_in_page(buffer);
first = ((unsigned long)buffer & PAGE_MASK) >> PAGE_SHIFT;
last = (((unsigned long)buffer + length-1) & PAGE_MASK) >> PAGE_SHIFT;
allocPages = (last-first)+1;
pkts = kmalloc( allocPages * (sizeof(PktBuf*)), GFP_KERNEL);
if(pkts == NULL)
{
printk(KERN_ERR "Error: unable to allocate memory for packets\n");
return -1;
}
cachePages = kmalloc( (allocPages * (sizeof(struct page*))), GFP_KERNEL );
if( cachePages == NULL )
{
printk(KERN_ERR "Error: unable to allocate memory for cachePages\n");
kfree(pkts);
return -1;
}
memset(cachePages, 0, sizeof(allocPages * sizeof(struct page*)) );
down_read(&(current->mm->mmap_sem));
status = get_user_pages(current, // current process id
current->mm, // mm of current process
(unsigned long)buffer, // user buffer
allocPages,
WRITE_TO_CARD,
0, /* don't force */
cachePages,
NULL);
up_read(¤t->mm->mmap_sem);
if( status < allocPages) {
printk(KERN_ERR ".... Error: requested pages=%d, granted pages=%d ....\n", allocPages, status);
for(j=0; j<status; j++)
page_cache_release(cachePages[j]);
kfree(pkts);
kfree(cachePages);
return -1;
}
allocPages = status; // actual number of pages system gave
for(j=0; j< allocPages; j++) /* Packet fragments loop */
{
pbuf = kmalloc( (sizeof(PktBuf)), GFP_KERNEL);
if(pbuf == NULL) {
printk(KERN_ERR "Insufficient Memory !!\n");
for(j--; j>=0; j--)
kfree(pkts[j]);
for(j=0; j<allocPages; j++)
page_cache_release(cachePages[j]);
kfree(pkts);
kfree(cachePages);
return -1;
}
//spin_lock_bh(&RawLock);
pkts[j] = pbuf;
// first buffer would start at some offset, need not be on page boundary
if(j==0) {
if(j == (allocPages-1)) {
pbuf->size = length;
}
else
pbuf->size = ((PAGE_SIZE)-offset);
}
else {
if(j == (allocPages-1)) {
pbuf->size = length-total;
}
else pbuf->size = (PAGE_SIZE);
}
pbuf->pktBuf = (unsigned char*)cachePages[j];
pbuf->pageOffset = (j == 0) ? offset : 0; // try pci_page_map
pbuf->bufInfo = (unsigned char *) buffer + total;
pbuf->pageAddr= (unsigned char*)cachePages[j];
pbuf->userInfo = length;
pbuf->flags = PKT_ALL;
if(j == 0)
{
pbuf->flags |= PKT_SOP;
}
if(j == (allocPages - 1) )
{
pbuf->flags |= PKT_EOP;
}
total += pbuf->size;
//spin_unlock_bh(&RawLock);
}
/****************************************************************/
allocPages = j; // actually used pages
result = DmaSendPages_Tx (hndl, pkts,allocPages);
if(result == -1)
{
for(j=0; j<allocPages; j++) {
page_cache_release(cachePages[j]);
}
total = 0;
}
kfree(cachePages);
for(j=0; j<allocPages; j++) {
kfree(pkts[j]);
}
kfree(pkts);
return total;
}
static int CPU_LOADED[16] =
{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
static int
xraw_dev_open (struct inode *in, struct file *filp)
{
int cpu_id = 0;
if (xraw_DriverState < INITIALIZED)
{
printk ("Driver not yet ready!\n");
return -1;
}
cpu_id = get_cpu ();
if (CPU_LOADED[cpu_id] == 0)
{
CPU_LOADED[cpu_id] = 1;
}
else
{
log_verbose(KERN_ERR "CPU %d is already loaded, exit this process\n",
cpu_id);
//return -1;
}
log_verbose(KERN_ERR "$$$$$$ CPU ID %d $$$$$$\n", cpu_id);
/* Allowing more than one Application accesing the driver */
#if 0
if (xraw_UserOpen)
{ /* To prevent more than one GUI */
printk ("Device already in use\n");
return -EBUSY;
}
#endif
//spin_lock_bh(&DmaStatsLock);
xraw_UserOpen++;
//spin_unlock_bh(&DmaStatsLock);
// printk ("========>>>>> XDMA driver instance %d \n", xraw_UserOpen);
return 0;
}
static int
xraw_dev_release (struct inode *in, struct file *filp)
{
int cpu_id = 0;
if (!xraw_UserOpen)
{
/* Should not come here */
printk ("Device not in use\n");
return -EFAULT;
}
// spin_lock_bh(&DmaStatsLock);
xraw_UserOpen--;
// spin_unlock_bh(&DmaStatsLock);
cpu_id = get_cpu ();
CPU_LOADED[cpu_id] = 0;
log_verbose(KERN_ERR "CPU %d is released\n", cpu_id);
return 0;
}
static long
xraw_dev_ioctl (struct file *filp,
unsigned int cmd, unsigned long arg)
{
int retval = 0;
if (xraw_DriverState < INITIALIZED)
{
/* Should not come here */
printk ("Driver not yet ready!\n");
return -1;
}
/* Check cmd type and value */
if (_IOC_TYPE (cmd) != XPMON_MAGIC)
return -ENOTTY;
if (_IOC_NR (cmd) > XPMON_MAX_CMD)
return -ENOTTY;
/* Check read/write and corresponding argument */
if (_IOC_DIR (cmd) & _IOC_READ)
if (!access_ok (VERIFY_WRITE, (void *) arg, _IOC_SIZE (cmd)))
return -EFAULT;
if (_IOC_DIR (cmd) & _IOC_WRITE)
if (!access_ok (VERIFY_READ, (void *) arg, _IOC_SIZE (cmd)))
return -EFAULT;
switch (cmd)
{
case IGET_TRN_TXUSRINFO:
{
int count = 0;
int expect_count;
if(copy_from_user(&expect_count,&(((FreeInfo *)arg)->expected),sizeof(int)) != 0)
{
printk ("##### ERROR in copy from usr #####");
break;
}
while (count < expect_count)
{
BufferInfo buff;
if (0 != getBuffInfo (&TxDoneQ, &buff))
{
break;
}
if (copy_to_user
(((BufferInfo *) (((FreeInfo *)arg)->buffList) + count), &buff,
sizeof (BufferInfo)))
{
printk ("##### ERROR in copy to usr #####");
}
// log_verbose(" %s:bufferAddr %x PktSize %d", __func__, usrArgument->buffList[count].bufferAddress, usrArgument->buffList[count].buffSize);
count++;
}
if(copy_to_user(&(((FreeInfo *)arg)->expected),&count,(sizeof(int))) != 0)
{
printk ("##### ERROR in copy to usr #####");
}
break;
}
case IGET_TRN_RXUSRINFO:
{
int count = 0;
int expect_count;
if(copy_from_user(&expect_count,&(((FreeInfo *)arg)->expected),sizeof(int)) != 0)
{
printk ("##### ERROR in copy from usr #####");
break;
}
while (count < expect_count)
{
BufferInfo buff;
if (0 != getBuffInfo (&RxDoneQ, &buff))
{
break;
}
if (copy_to_user
(((BufferInfo *) (((FreeInfo *)arg)->buffList) + count), &buff,
sizeof (BufferInfo)))
{
printk ("##### ERROR in copy to usr #####");
}
// log_verbose(" %s:bufferAddr %x PktSize %d", __func__, usrArgument->buffList[count].bufferAddress, usrArgument->buffList[count].buffSize);
count++;
}
if(copy_to_user(&(((FreeInfo *)arg)->expected),&count,(sizeof(int))) != 0)
{
printk ("##### ERROR in copy to usr #####");
}
break;
}
default:
printk ("Invalid command %d\n", cmd);
retval = -1;
break;
}
return retval;
}
/*
* This function is called when somebody tries to
* write into our device file.
*/
static ssize_t
xraw_dev_write (struct file *file,
const char __user * buffer, size_t length, loff_t * offset)
{
int ret_pack=0;
if ((RawTestMode & TEST_START) &&
(RawTestMode & (ENABLE_PKTCHK | ENABLE_LOOPBACK)))
ret_pack = DmaSetupTransmit(handle[0], 1, buffer, length);
/*
* return the number of bytes sent , currently one or none
*/
return ret_pack;
}
static ssize_t
xraw_dev_read (struct file *file,
char __user * buffer, size_t length, loff_t * offset)
{
int ret_pack=0;
#ifdef BACK_PRESSURE
if(impl_bp == NO_BP)
#endif
ret_pack = DmaSetupReceive(handle[2],1,buffer,length);
/*
* return the number of bytes sent , currently one or none
*/
return ret_pack;
}
static int __init
rawdata_init (void)
{
int chrRet;
dev_t xrawDev;
UserPtrs ufuncs;
static struct file_operations xrawDevFileOps;
/* Just register the driver. No kernel boot options used. */
printk (KERN_INFO "%s Init: Inserting Xilinx driver in kernel.\n", MYNAME);
xraw_DriverState = INITIALIZED;
spin_lock_init (&RawLock);
spin_lock_init (&(TxDoneQ.iLock));
spin_lock_init (&(RxDoneQ.iLock));
msleep (5);
/* First allocate a major/minor number. */
chrRet = alloc_chrdev_region (&xrawDev, 0, 1, DEV_NAME);
if (IS_ERR ((int *) chrRet))
{
log_normal (KERN_ERR "Error allocating char device region\n");
return -1;
}
else
{
/* Register our character device */
xrawCdev = cdev_alloc ();
if (IS_ERR (xrawCdev))
{
log_normal (KERN_ERR "Alloc error registering device driver\n");
unregister_chrdev_region (xrawDev, 1);
return -1;
}
else
{
xrawDevFileOps.owner = THIS_MODULE;
xrawDevFileOps.open = xraw_dev_open;
xrawDevFileOps.release = xraw_dev_release;
xrawDevFileOps.unlocked_ioctl = xraw_dev_ioctl;
xrawDevFileOps.write = xraw_dev_write;
xrawDevFileOps.read = xraw_dev_read;
xrawCdev->owner = THIS_MODULE;
xrawCdev->ops = &xrawDevFileOps;
xrawCdev->dev = xrawDev;
chrRet = cdev_add (xrawCdev, xrawDev, 1);
if (chrRet < 0)
{
log_normal (KERN_ERR "Add error registering device driver\n");
cdev_del(xrawCdev);
unregister_chrdev_region (xrawDev, 1);
return -1;
}
}
}
if (!IS_ERR ((int *) chrRet))
{
printk (KERN_INFO "Device registered with major number %d\n",
MAJOR (xrawDev));
}
xraw_DriverState = INITIALIZED;
/* Register with DMA incase not already done so */
if (xraw_DriverState < POLLING)
{
spin_lock_bh (&RawLock);
printk ("Calling DmaRegister on engine %d and %d\n",
ENGINE_TX, ENGINE_RX);
xraw_DriverState = REGISTERED;
ufuncs.UserInit = myInit;
ufuncs.UserPutPkt = myPutTxPkt;
ufuncs.UserSetState = mySetState;
ufuncs.UserGetState = myGetState;
#ifdef PM_SUPPORT
ufuncs.UserSuspend_Early = NULL;
ufuncs.UserSuspend_Late = NULL;
ufuncs.UserResume = NULL;
#endif
ufuncs.privData = 0x54545454;
#ifdef RAW_ETH
ufuncs.mode = RAWETHERNET_MODE;
#else
ufuncs.mode = PERFORMANCE_MODE;
#endif
spin_unlock_bh (&RawLock);
if ((handle[0] =
DmaRegister (ENGINE_TX, MYBAR, &ufuncs, BUFSIZE)) == NULL)
{
printk ("Register for engine %d failed. Stopping.\n", ENGINE_TX);
spin_lock_bh (&RawLock);
xraw_DriverState = UNREGISTERED;
spin_unlock_bh (&RawLock);
cdev_del(xrawCdev);
unregister_chrdev_region (xrawDev, 1);
return -1;
}
printk ("Handle for engine %d is %p\n", ENGINE_TX, handle[0]);
spin_lock_bh (&RawLock);
ufuncs.UserInit = myInit;
ufuncs.UserPutPkt = myPutRxPkt;
ufuncs.UserGetPkt = myGetRxPkt;
ufuncs.UserSetState = mySetState;
ufuncs.UserGetState = myGetState;
#ifdef PM_SUPPORT
ufuncs.UserSuspend_Early = NULL;
ufuncs.UserSuspend_Late = NULL;
ufuncs.UserResume = NULL;
#endif
ufuncs.privData = 0x54545456;
#ifdef RAW_ETH
ufuncs.mode = RAWETHERNET_MODE;
#else
ufuncs.mode = PERFORMANCE_MODE;
#endif
spin_unlock_bh (&RawLock);
if ((handle[2] =
DmaRegister (ENGINE_RX, MYBAR, &ufuncs, BUFSIZE)) == NULL)
{
printk ("Register for engine %d failed. Stopping.\n", ENGINE_RX);
spin_lock_bh (&RawLock);
xraw_DriverState = UNREGISTERED;
spin_unlock_bh (&RawLock);
cdev_del(xrawCdev);
unregister_chrdev_region (xrawDev, 1);
return -1;
}
printk ("Handle for engine %d is %p\n", ENGINE_RX, handle[2]);
}
return 0;
}
static void __exit
rawdata_cleanup (void)
{
int i;
/* Stop any running tests, else the hardware's packet checker &
* generator will continue to run.
*/
XIo_Out32 (TXbarbase + TX_CONFIG_ADDRESS, 0);
XIo_Out32 (TXbarbase + RX_CONFIG_ADDRESS, 0);
#ifdef RAW_ETH
mdelay(1);
XIo_Out32(TXbarbase+(u32)(NW_PATH_OFFSET+XXGE_TC_OFFSET), 0x80000000);
mdelay(1);
XIo_Out32(TXbarbase+(u32)(NW_PATH_OFFSET+XXGE_RCW1_OFFSET), 0x80000000);
mdelay(1);
#endif
printk (KERN_INFO "%s: Unregistering Xilinx driver from kernel.\n", MYNAME);
if (TxBufCnt != RxBufCnt)
{
printk ("%s: Buffers Transmitted %u Received %u\n", MYNAME, TxBufCnt,
RxBufCnt);
mdelay (1);
}
#ifdef FIFO_EMPTY_CHECK
DmaFifoEmptyWait(MYHANDLE,DIR_TYPE_S2C);
// wait for appropriate time to stabalize
mdelay(STABILITY_WAIT_TIME);
#endif
DmaUnregister (handle[0]);
#ifdef FIFO_EMPTY_CHECK
DmaFifoEmptyWait(MYHANDLE,DIR_TYPE_C2S);
// wait for appropriate time to stabalize
mdelay(STABILITY_WAIT_TIME);
#endif
DmaUnregister (handle[2]);
PrintSummary ();
/*Unregistering the char driver */
if (xrawCdev != NULL)
{
printk ("Unregistering char device driver\n");
cdev_del (xrawCdev);
unregister_chrdev_region (xrawCdev->dev, 1);
}
mdelay (1000);
/* Not sure if free_page() sleeps or not. */
spin_lock_bh (&RawLock);
printk ("Freeing user buffers\n");
for (i = 0; i < TxBufs.TotalNum; i++)
//kfree(TxBufs.origVA[i]);
free_page ((unsigned long) (TxBufs.origVA[i]));
for (i = 0; i < RxBufs.TotalNum; i++)
//kfree(RxBufs.origVA[i]);
free_page ((unsigned long) (RxBufs.origVA[i]));
spin_unlock_bh (&RawLock);
}
module_init (rawdata_init);
module_exit (rawdata_cleanup);
MODULE_AUTHOR ("Xilinx, Inc.");
MODULE_DESCRIPTION (DRIVER_DESCRIPTION);
MODULE_LICENSE ("GPL");
| 27.923734 | 146 | 0.618524 |
6e73ccf9fb2606c9941e3bcf800c3e4d83024d6c | 685 | h | C | Classes/BusinessDb.h | wiiplay/cop4655 | c35c83f36a69749fb27899f777beec90ede10d41 | [
"MIT"
] | null | null | null | Classes/BusinessDb.h | wiiplay/cop4655 | c35c83f36a69749fb27899f777beec90ede10d41 | [
"MIT"
] | null | null | null | Classes/BusinessDb.h | wiiplay/cop4655 | c35c83f36a69749fb27899f777beec90ede10d41 | [
"MIT"
] | null | null | null | //
// Business.h
// iVending
//
// Created by Manuel Pino on 4/18/15.
// Copyright (c) 2015 student. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "Business.h"
#import "sqlDB.h"
@interface BusinessDb : NSObject
@property (strong, nonatomic) Business *business;
- (BusinessDb *) getBusinessByName: (NSString *) name andDb: (sqlDB *) connection;
- (BusinessDb *) getBusinessByID: (int) businessId andProd: (sqlDB *) connection;
- (NSMutableDictionary *) getBusinessList: (sqlDB *) connection;
- (BOOL) insertBusiness: (BusinessDb *) business andProd: (sqlDB *) connection;
- (BOOL) deleteBusiness: (BusinessDb *) business andProd: (sqlDB *) connection;
@end
| 28.541667 | 82 | 0.712409 |
bcffd6d919aaf5399c08d81412ce2a69b031ed84 | 666 | h | C | test/performance-regression/full-apps/qmcpack/src/QMCTools/GamesXmlParser.h | FeiyangJin/hclib | d23c850dce914e2d80cae733670820812a1edeee | [
"BSD-3-Clause"
] | 55 | 2015-07-28T01:32:58.000Z | 2022-02-27T16:27:46.000Z | test/performance-regression/full-apps/qmcpack/src/QMCTools/GamesXmlParser.h | FeiyangJin/hclib | d23c850dce914e2d80cae733670820812a1edeee | [
"BSD-3-Clause"
] | 66 | 2015-06-15T20:38:19.000Z | 2020-08-26T00:11:43.000Z | test/performance-regression/full-apps/qmcpack/src/QMCTools/GamesXmlParser.h | FeiyangJin/hclib | d23c850dce914e2d80cae733670820812a1edeee | [
"BSD-3-Clause"
] | 26 | 2015-10-26T22:11:51.000Z | 2021-03-02T22:09:15.000Z | #ifndef QMCPLUSPLUS_TOOLS_GAMESS_XML_PARSER_H
#define QMCPLUSPLUS_TOOLS_GAMESS_XML_PARSER_H
#include "QMCTools/QMCGaussianParserBase.h"
#include <iostream>
#include <sstream>
#include <iomanip>
#include <vector>
#include "OhmmsPETE/TinyVector.h"
#include "OhmmsData/OhmmsElementBase.h"
class GamesXmlParser: public QMCGaussianParserBase,
public OhmmsAsciiParser
{
void getGeometry(vector<xmlNodePtr>&);
void getGaussianCenters(vector<xmlNodePtr>&);
void getEigVectors(vector<xmlNodePtr>&);
void getControlParameters(xmlNodePtr);
public:
GamesXmlParser();
GamesXmlParser(int argc, char** argv);
void parse(const std::string& fname);
};
#endif
| 21.483871 | 51 | 0.788288 |
3cbf4aa5b0a47aee773f0982a6635f9471089e7e | 607 | h | C | Sputnik/Modules/Settings/Notifications/View/BUNotificationsViewControllerInput.h | vvlkv/Sputnik-iOS | 502d38dec243fb73be05d85090e22fbf77188604 | [
"MIT"
] | null | null | null | Sputnik/Modules/Settings/Notifications/View/BUNotificationsViewControllerInput.h | vvlkv/Sputnik-iOS | 502d38dec243fb73be05d85090e22fbf77188604 | [
"MIT"
] | null | null | null | Sputnik/Modules/Settings/Notifications/View/BUNotificationsViewControllerInput.h | vvlkv/Sputnik-iOS | 502d38dec243fb73be05d85090e22fbf77188604 | [
"MIT"
] | null | null | null | //
// BUNotificationsViewControllerInput.h
// Sputnik
//
// Created by Виктор on 06/02/2019.
// Copyright © 2019 Viktor. All rights reserved.
//
#ifndef BUNotificationsViewControllerInput_h
#define BUNotificationsViewControllerInput_h
@protocol UITableViewDataSource;
@protocol BUNotificationsViewControllerInput <NSObject>
- (void)insertSections;
- (void)deleteSections;
- (void)reloadSectionsInSet:(NSIndexSet *)set;
//- (void)reloadData;
- (void)dataSource:(id <UITableViewDataSource>)dataSource;
- (void)showNeedGrantNotificationsMessage;
@end
#endif /* BUNotificationsViewControllerInput_h */
| 24.28 | 58 | 0.790774 |
3cea3abea72d05221be453c1e5584c8197df1d58 | 527 | h | C | T23Kit-Colour/Swift/Colour-Swift.h | thirteen23/T23Kit-Colour | 9c8ca18cc81041c3b6ee07d3f9e5f80e45f6ba9b | [
"MIT"
] | 11 | 2015-01-10T18:52:44.000Z | 2021-01-07T18:17:10.000Z | T23Kit-Colour/Swift/Colour-Swift.h | thirteen23/T23Kit-Colour | 9c8ca18cc81041c3b6ee07d3f9e5f80e45f6ba9b | [
"MIT"
] | 1 | 2016-05-22T20:30:01.000Z | 2016-05-22T20:30:01.000Z | T23Kit-Colour/Swift/Colour-Swift.h | thirteen23/T23Kit-Colour | 9c8ca18cc81041c3b6ee07d3f9e5f80e45f6ba9b | [
"MIT"
] | 1 | 2016-03-10T01:31:39.000Z | 2016-03-10T01:31:39.000Z | //
// Colour-Swift.h
// Colour-Swift
//
// Created by Michael Van Milligan on 12/15/14.
// Copyright (c) 2014 Thirteen23. All rights reserved.
//
#import <UIKit/UIKit.h>
//! Project version number for Colour-Swift.
FOUNDATION_EXPORT double Colour_SwiftVersionNumber;
//! Project version string for Colour-Swift.
FOUNDATION_EXPORT const unsigned char Colour_SwiftVersionString[];
// In this header, you should import all the public headers of your framework using statements like #import <Colour_Swift/PublicHeader.h>
| 26.35 | 137 | 0.762808 |
42a95ec5c1d785fcbc6a7d2b3d9e6e189e621797 | 1,505 | h | C | include/sysdeps/powerpc/powerpc64/tls-macros.h | abhijeetviswam/libucresolv | f4911dcf4d9b5410a423970d698ac98ac071a413 | [
"Apache-2.0"
] | 12 | 2018-09-18T19:51:27.000Z | 2022-01-18T15:31:41.000Z | include/sysdeps/powerpc/powerpc64/tls-macros.h | DalavanCloud/libucresolv | 04a4827aa44c47556f425a4eed5e0ab4a5c0d25a | [
"Apache-2.0"
] | 3 | 2017-10-05T20:52:56.000Z | 2019-02-26T23:05:29.000Z | include/sysdeps/powerpc/powerpc64/tls-macros.h | DalavanCloud/libucresolv | 04a4827aa44c47556f425a4eed5e0ab4a5c0d25a | [
"Apache-2.0"
] | 7 | 2017-07-04T10:52:39.000Z | 2019-02-28T08:37:16.000Z | /* Include sysdeps/powerpc/tls-macros.h for __TLS_CALL_CLOBBERS */
#include_next "tls-macros.h"
/* PowerPC64 Local Exec TLS access. */
#define TLS_LE(x) \
({ int * __result; \
asm ("addis %0,13," #x "@tprel@ha\n\t" \
"addi %0,%0," #x "@tprel@l" \
: "=b" (__result) ); \
__result; \
})
/* PowerPC64 Initial Exec TLS access. */
#define TLS_IE(x) \
({ int * __result; \
asm ("ld %0," #x "@got@tprel(2)\n\t" \
"add %0,%0," #x "@tls" \
: "=r" (__result) ); \
__result; \
})
#define __TLS_GET_ADDR "__tls_get_addr"
/* PowerPC64 Local Dynamic TLS access. */
#define TLS_LD(x) \
({ int * __result; \
asm ("addi 3,2," #x "@got@tlsld\n\t" \
"bl " __TLS_GET_ADDR "\n\t" \
"nop \n\t" \
"addis %0,3," #x "@dtprel@ha\n\t" \
"addi %0,%0," #x "@dtprel@l" \
: "=b" (__result) : \
: "3", __TLS_CALL_CLOBBERS); \
__result; \
})
/* PowerPC64 General Dynamic TLS access. */
#define TLS_GD(x) \
({ register int *__result __asm__ ("r3"); \
asm ("addi 3,2," #x "@got@tlsgd\n\t" \
"bl " __TLS_GET_ADDR "\n\t" \
"nop " \
: "=r" (__result) : \
: __TLS_CALL_CLOBBERS); \
__result; \
})
| 33.444444 | 67 | 0.414618 |
515ce688e334fcd6b09e9a0ab9c89f23d923004a | 1,579 | h | C | DocumentManagerCore.framework/DOCTag.h | reels-research/iOS-Private-Frameworks | 9a4f4534939310a51fdbf5a439dd22487efb0f01 | [
"MIT"
] | 4 | 2021-10-06T12:15:26.000Z | 2022-02-21T02:26:00.000Z | DocumentManagerCore.framework/DOCTag.h | reels-research/iOS-Private-Frameworks | 9a4f4534939310a51fdbf5a439dd22487efb0f01 | [
"MIT"
] | null | null | null | DocumentManagerCore.framework/DOCTag.h | reels-research/iOS-Private-Frameworks | 9a4f4534939310a51fdbf5a439dd22487efb0f01 | [
"MIT"
] | 1 | 2021-10-08T07:40:53.000Z | 2021-10-08T07:40:53.000Z | /* Generated by RuntimeBrowser
Image: /System/Library/PrivateFrameworks/DocumentManagerCore.framework/DocumentManagerCore
*/
@interface DOCTag : NSObject <NSCopying, NSSecureCoding> {
NSString * _displayName;
long long _itemCount;
long long _labelIndex;
NSNumber * _sidebarPinned;
NSNumber * _sidebarVisible;
long long _type;
}
@property (nonatomic, readonly) UIColor *displayColor;
@property (nonatomic, readonly) NSString *displayName;
@property (nonatomic, readonly) long long itemCount;
@property (nonatomic, readonly) long long labelIndex;
@property (nonatomic, readonly) NSNumber *sidebarPinned;
@property (nonatomic, readonly) NSNumber *sidebarVisible;
@property (nonatomic, readonly) long long type;
+ (bool)supportsSecureCoding;
+ (id)tagColorWithLabelIndex:(long long)arg1;
- (void).cxx_destruct;
- (id)copyWithZone:(struct _NSZone { }*)arg1;
- (id)description;
- (id)displayColor;
- (id)displayName;
- (void)encodeWithCoder:(id)arg1;
- (unsigned long long)hash;
- (id)iCloudTagAttributes;
- (id)initWithCoder:(id)arg1;
- (id)initWithDisplayName:(id)arg1 labelIndex:(long long)arg2 type:(long long)arg3;
- (id)initWithDisplayName:(id)arg1 labelIndex:(long long)arg2 type:(long long)arg3 itemCount:(long long)arg4 sidebarVisible:(id)arg5 sidebarPinned:(id)arg6;
- (id)initWithICloudTagAttributes:(id)arg1;
- (bool)isEqual:(id)arg1;
- (bool)isEqualToTag:(id)arg1;
- (long long)itemCount;
- (long long)labelIndex;
- (void)mergeWithTag:(id)arg1 options:(long long)arg2;
- (id)sidebarPinned;
- (id)sidebarVisible;
- (long long)type;
@end
| 33.595745 | 156 | 0.754275 |
9985160b0194251d888d7e10c2cfb7ac56f03e80 | 181 | c | C | pattern/aritraroy24.c | saurabh3235/HACKTOBERFEST2020_pattern | 2d203f67ea276099d8c7f467fe838932f1fdc9cb | [
"MIT"
] | null | null | null | pattern/aritraroy24.c | saurabh3235/HACKTOBERFEST2020_pattern | 2d203f67ea276099d8c7f467fe838932f1fdc9cb | [
"MIT"
] | null | null | null | pattern/aritraroy24.c | saurabh3235/HACKTOBERFEST2020_pattern | 2d203f67ea276099d8c7f467fe838932f1fdc9cb | [
"MIT"
] | null | null | null | #include<stdio.h>
#include<conio.h>
// program for printing the pattern
void main()
{
int i=0,j=0;
for(i=1;i<=5;i++)
{
for(j=1;j<=i;j++)
printf("%d",j);
printf("\n");
}
}
| 12.928571 | 35 | 0.552486 |
394c4dbf7c929189b09dc76ab0a02b259ae39e72 | 770 | h | C | Systems Programming (C)/src/hnccom.h | PFigs/portfolio | 26d3d005b62af50a5f708930105fe506ec186d24 | [
"MIT"
] | null | null | null | Systems Programming (C)/src/hnccom.h | PFigs/portfolio | 26d3d005b62af50a5f708930105fe506ec186d24 | [
"MIT"
] | null | null | null | Systems Programming (C)/src/hnccom.h | PFigs/portfolio | 26d3d005b62af50a5f708930105fe506ec186d24 | [
"MIT"
] | 1 | 2018-09-07T09:27:18.000Z | 2018-09-07T09:27:18.000Z | /*
* INSTITUTO SUPERIOR TECNICO
* PROGRAMACAO DE SISTEMAS
* PROJECTO HIGH NOON
*
* Semestre Inverno 09/10
*
* Realizado Por:
* Eduardo Santos (58008)
* Pedro Neves (58011)
* Pedro Silva(58035)
*
*/
struct sockaddr_in resolve_nome(char* trackername, int trackerport);
void ligacao(unsigned int porto, int *escrita, char *nome_servidor, struct sockaddr_in *dservidor);
void estabelece_sessao(int *sock, struct sockaddr_in server);
void cria_socket(int *sock);
char *escreve_mensagens(char *game, char *player, char *P_ID, char *cmd, char *mensagem, int mode);
int envia_mensagem_cliente(int *sock, char *buffer);
char **recebe_campos(char *id, char **fields, int *fd, int *codigo);
char **espera_resposta(int *fd, char **resposta, int *codigo);
| 33.478261 | 99 | 0.724675 |
79c2572455b3bbb4153288522eefa98b01fec075 | 3,169 | h | C | Pendulum.h | Sgw32/R3E | 8a55dd137d9e102cf4c9c2fee3d89901bdefa3cd | [
"MIT"
] | 7 | 2017-11-27T15:15:08.000Z | 2021-03-29T16:53:22.000Z | Pendulum.h | Sgw32/R3E | 8a55dd137d9e102cf4c9c2fee3d89901bdefa3cd | [
"MIT"
] | null | null | null | Pendulum.h | Sgw32/R3E | 8a55dd137d9e102cf4c9c2fee3d89901bdefa3cd | [
"MIT"
] | 4 | 2017-11-28T02:53:19.000Z | 2021-01-29T10:37:52.000Z | /////////////////////////////////////////////////////////////////////
///////////////Original file by:Fyodor Zagumennov aka Sgw32//////////
///////////////Copyright(c) 2010 Fyodor Zagumennov //////////
/////////////////////////////////////////////////////////////////////
#pragma once
#include <Ogre.h>
//#include "DefaultAEnt.h"
//#include "PlayerCollisionForceAdder.h"
#include "Run3SoundRuntime.h"
#include "global.h"
#include <OgreNewt.h>
#include "Timeshift.h"
class Pendulum
{
public:
Pendulum();
~Pendulum();
void init(Ogre::SceneManager* mSceneMgr)
{
positionPend=Vector3::ZERO;
this->mSceneMgr=mSceneMgr;
}
void transformToFuncRot()
{
funcrot=true;
}
void setRotateDoor(Vector3 axis,Real angle)
{
mAxis=axis;
rotDoor=true;
mAngle=angle;
mQuatAngle=Quaternion(Radian(Degree(mAngle)),axis);
mTime=angle/mspeed;
}
void setRotateDoor(Real pitch,Real yaw, Real roll,Real speed)
{
mQuatAngle = get_orientation();
/*mp=quat.getPitch().valueDegrees();
my=quat.getYaw().valueDegrees();
mr=quat.getRoll().valueDegrees();*/
mp=pitch;
my=yaw;
mr=roll;
mp1=0;
my1=0;
mr1=0;
rotSpeed=speed;
rotDoor=true;
}
void setRotateDoor(Real pitch,Real yaw, Real roll,Real speed,Vector3 pend)
{
mQuatAngle = get_orientation();
/*mp=quat.getPitch().valueDegrees();
my=quat.getYaw().valueDegrees();
mr=quat.getRoll().valueDegrees();*/
mp=pitch;
my=yaw;
mr=roll;
mp1=0;
my1=0;
mr1=0;
rotSpeed=speed;
rotDoor=true;
positionPend=pend;
}
void setup(Ogre::SceneNode* door_node);
void setup(Ogre::SceneNode* door_node,bool box);
void addParticleSystem(String name, Vector3 pos, Vector3 scale)
{
LogManager::getSingleton().logMessage("Pendulum: creating attached particle");
ParticleSystem *pParticles = global::getSingleton().getSceneManager()->createParticleSystem(mNode->getName()+"particle", name);
particleNode = mNode->createChildSceneNode(pos);
particleNode->setScale(scale);
particleNode->attachObject(pParticles);
}
void setname(String name);
void set_position(Vector3 pos);
void set_orientation(Quaternion quat);
Quaternion get_orientation()
{
Quaternion quat;
Vector3 pos;
door_bod->getPositionOrientation(pos,quat);
return quat;
}
void rotateBody(Quaternion quat);
Vector3 get_position();
String getname();
void unload();
void Fire(String event);
void setUseInteract(bool interact)
{
mInteract=interact;
}
virtual bool frameStarted(const Ogre::FrameEvent &evt);
private:
bool funcrot;
Ogre::SceneNode* mNode;
Ogre::SceneNode* particleNode;
Ogre::AxisAlignedBox aab;
OgreNewt::Body* door_bod;
Ogre::Real dist;
Ogre::Real mspeed,time,mTime;
Ogre::Real velocity;
Ogre::Vector3 vDirection,fPosition,sPosition;
Ogre::Vector3 direction;
Ogre::Vector3 positionPend;
String mName,cur_event,mOnOpen,mOnClose;
bool nowfire,opened,closed,sop,scl;
bool rotDoor;
bool mInteract;
Real mAngle;
Real mp,my,mr,mp1,my1,mr1;
Real rotSpeed;
Vector3 mAxis;
Real mCurAngle;
Quaternion mQuatAngle;
Quaternion mStartAngle;
Vector3 basePos;
Ogre::SceneManager* mSceneMgr;
unsigned int sound;
SoundManager* sMgr;
String lDoorFopened,lDoorFclosed,lDoorS;
}; | 24.376923 | 128 | 0.694225 |
792961a392d1af0571f3d13e5c9bd2a04ef59f20 | 101 | c | C | src/api/thread_metadata_pages.c | mit-enclaves/security_monitor | eb06e489a624ffe9c1773dfd03ee1940929a18eb | [
"MIT"
] | 2 | 2020-04-23T19:36:53.000Z | 2020-05-10T01:56:12.000Z | src/api/thread_metadata_pages.c | mit-enclaves/security_monitor | eb06e489a624ffe9c1773dfd03ee1940929a18eb | [
"MIT"
] | null | null | null | src/api/thread_metadata_pages.c | mit-enclaves/security_monitor | eb06e489a624ffe9c1773dfd03ee1940929a18eb | [
"MIT"
] | 1 | 2022-02-28T14:24:31.000Z | 2022-02-28T14:24:31.000Z | #include <sm.h>
uint64_t sm_internal_thread_metadata_pages () {
return thread_metadata_pages();
}
| 16.833333 | 47 | 0.772277 |
b2f302d67e8dc875c3279edd55d184db3b0ba8fe | 816 | c | C | src/mainE.c | orlandoenrico/MaxWeightedIndependentSet | ea65233c31221995beac1a64641ee38f4a572876 | [
"MIT"
] | null | null | null | src/mainE.c | orlandoenrico/MaxWeightedIndependentSet | ea65233c31221995beac1a64641ee38f4a572876 | [
"MIT"
] | null | null | null | src/mainE.c | orlandoenrico/MaxWeightedIndependentSet | ea65233c31221995beac1a64641ee38f4a572876 | [
"MIT"
] | null | null | null | /*
mainE.c
Autor: Orlando Enrico Liz Silvério Silva
Data: 17/11/17
*/
#include <stdio.h>
#include <stdlib.h>
#include "exato.h"
int main(){
unsigned int M, N, i;
//ńúmero de esquinas e números de pares de esquinas vizinhas
if(scanf("%u %u", &N, &M)!=2) printf("erro\n");
esquina *e = (esquina *) malloc(N*sizeof(esquina));
inicializaVizinhas(N, e);
for(i=0; i<N; i++)
if(scanf("%u", &e[i].peso)!=1) printf("erro\n");
for (i = 0; i < M; i++){
unsigned int x, y;
if(scanf("%u %u", &x, &y)!=2) printf("erro\n");
//marca os vizinhos de um vértice com bitmask
e[x-1].vizinhas |= 1<<(y-1);
e[y-1].vizinhas |= 1<<(x-1);
}
//função que encontra o conjunto independente com peso máximo
MWIS(N, e);
free(e);
return 0;
} | 23.314286 | 65 | 0.550245 |
05bc9f31e647c57bddd5153b50699a56ce43d7ce | 573 | h | C | leetcodeInXcode/Solution/Palindrome Number.h | thats2ez/leetcode-in-Xcode | 6a9cd577276908d1186002d8c365ad2fe84347f0 | [
"MIT"
] | 1 | 2019-08-11T08:47:53.000Z | 2019-08-11T08:47:53.000Z | leetcodeInXcode/Solution/Palindrome Number.h | thats2ez/leetcode-in-Xcode | 6a9cd577276908d1186002d8c365ad2fe84347f0 | [
"MIT"
] | null | null | null | leetcodeInXcode/Solution/Palindrome Number.h | thats2ez/leetcode-in-Xcode | 6a9cd577276908d1186002d8c365ad2fe84347f0 | [
"MIT"
] | 1 | 2021-07-21T09:03:43.000Z | 2021-07-21T09:03:43.000Z | //
// Palindrome Number.h
// leetcodeInXcode
//
// Created by Kaiqi on 12/17/14.
// Copyright (c) 2014 edu.self. All rights reserved.
//
class Solution {
public:
bool isPalindrome(int x) {
if (x < 0) {
return false;
}
int d = 1;
while (d <= x/10) {
d *= 10;
}
while (x > 0) {
int q = x / d;
int r = x % 10;
if (q != r) {
return false;
}
x = (x % d) / 10;
d /= 100;
}
return true;
}
}; | 19.1 | 53 | 0.378709 |
e80eac168f180d7a9b7ad08a78d025d68dbff827 | 90 | c | C | NCGB/Compile/src/OBSOLETE2009/PolyGenerator.c | mcdeoliveira/NC | 54b2a81ebda9e5260328f88f83f56fe8cf472ac3 | [
"BSD-3-Clause"
] | 103 | 2016-09-21T06:01:23.000Z | 2022-03-27T06:52:10.000Z | NCGB/Compile/src/OBSOLETE2009/PolyGenerator.c | albinjames/NC | 157a55458931a18dd1f42478872c9df0de5cc450 | [
"BSD-3-Clause"
] | 11 | 2017-03-27T13:11:42.000Z | 2022-03-08T13:46:14.000Z | NCGB/Compile/src/OBSOLETE2009/PolyGenerator.c | albinjames/NC | 157a55458931a18dd1f42478872c9df0de5cc450 | [
"BSD-3-Clause"
] | 21 | 2017-06-23T09:01:21.000Z | 2022-02-18T06:24:00.000Z | // PolyGenerator.c
#include "PolyGenerator.hpp"
PolyGenerator::~PolyGenerator(){};
| 15 | 35 | 0.7 |
9f9a1d3fceb371d9020bda3121788294b6784265 | 607 | h | C | include/alloc.h | neolibc/neolibc-interface | 919ed73d7b2ea91d2c7559e0674ff0131355c957 | [
"MIT"
] | null | null | null | include/alloc.h | neolibc/neolibc-interface | 919ed73d7b2ea91d2c7559e0674ff0131355c957 | [
"MIT"
] | null | null | null | include/alloc.h | neolibc/neolibc-interface | 919ed73d7b2ea91d2c7559e0674ff0131355c957 | [
"MIT"
] | null | null | null | #include "types.h"
typedef struct {
void *(*allocate)(size_t size);
void *(*clear_allocate)(size_t num_elements, size_t size);
void *(*reallocate)(void *ptr, size_t size);
void (*deallocate)(void *ptr);
} Allocator;
typedef void (*OutOfMemoryHandler)(void);
void set_global_allocator(Allocator alloc);
void restore_default_allocator(void);
void set_oom_handler(OutOfMemoryHandler callback);
void restore_default_oom_handler(void);
void *allocate(size_t size);
void *clear_allocate(size_t num_elements, size_t size);
void *reallocate(void *ptr, size_t size);
void deallocate(void *ptr);
| 27.590909 | 62 | 0.756178 |
9f9c788621de2c499da7bd532b6530fdc7cb2603 | 279 | h | C | ZCSelfUSE/Tools/Image/Categories/UIImage+SplitImageIntoTwoParts.h | xiaowu2016/ZCSelfUSE | 996dd569f492290e80b5940e036231030e9b7a35 | [
"MIT"
] | 4 | 2016-06-29T08:53:39.000Z | 2016-10-21T03:25:48.000Z | ZCSelfUSE/Tools/Image/Categories/UIImage+SplitImageIntoTwoParts.h | xiaowu2016/ZCSelfUSE | 996dd569f492290e80b5940e036231030e9b7a35 | [
"MIT"
] | null | null | null | ZCSelfUSE/Tools/Image/Categories/UIImage+SplitImageIntoTwoParts.h | xiaowu2016/ZCSelfUSE | 996dd569f492290e80b5940e036231030e9b7a35 | [
"MIT"
] | null | null | null | //
// UIImage+SplitImageIntoTwoParts.h
// ZCSelfUSE
//
// Created by zhangchao on 16/6/2.
// Copyright © 2016年 zhangchao. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface UIImage (SplitImageIntoTwoParts)
+ (NSArray *)splitImageIntoTwoParts:(UIImage *)image;
@end
| 19.928571 | 53 | 0.724014 |
c335986d6227ed2b90ed679ae3b7c0fd984a2176 | 1,697 | h | C | FKUtility/FKOSType.h | FajraKatviro/FKFramework2 | 0b55b402c255b50fe07ee568bbf46acd6617a6e4 | [
"MIT"
] | 2 | 2015-10-01T07:25:36.000Z | 2015-11-02T23:14:10.000Z | FKUtility/FKOSType.h | FajraKatviro/FKFramework2 | 0b55b402c255b50fe07ee568bbf46acd6617a6e4 | [
"MIT"
] | 13 | 2015-11-02T22:15:14.000Z | 2015-11-03T21:08:51.000Z | FKUtility/FKOSType.h | FajraKatviro/FKFramework2 | 0b55b402c255b50fe07ee568bbf46acd6617a6e4 | [
"MIT"
] | null | null | null | #ifndef FKOSTYPE_H
#define FKOSTYPE_H
#include <QtGlobal>
#include <QString>
#include <QMap>
namespace FKOSType{
const qint8 common=0;
const qint8 nix=1;
const qint8 ard=2;
const qint8 mac=3;
const qint8 ios=4;
const qint8 win=5;
#if defined(Q_OS_WIN)
const qint8 current=win;
#elif defined(Q_OS_IOS)
const qint8 current=ios;
#elif defined(Q_OS_MAC)
const qint8 current=mac;
#elif defined(Q_OS_ANDROID)
const qint8 current=ard;
#elif defined(Q_OS_UNIX)
const qint8 current=nix;
#endif
}
namespace FKOSDir{
const QString common=QStringLiteral("data");
const QString uncknown=QStringLiteral("uncknownData");
const QString nix=QStringLiteral("bin_nix");
const QString ard=QStringLiteral("bin_and");
const QString mac=QStringLiteral("bin_mac");
const QString ios=QStringLiteral("bin_ios");
const QString win=QStringLiteral("bin_win");
#if defined(Q_OS_WIN)
const QString current=win;
#elif defined(Q_OS_IOS)
const QString current=ios;
#elif defined(Q_OS_MAC)
const QString current=mac;
#elif defined(Q_OS_ANDROID)
const QString current=ard;
#elif defined(Q_OS_UNIX)
const QString current=nix;
#endif
static QMap<qint8,QString> getPlatformFolders(){
QMap<qint8,QString> map;
map.insert(FKOSType::common,FKOSDir::common);
map.insert(FKOSType::ard,FKOSDir::ard);
map.insert(FKOSType::ios,FKOSDir::ios);
map.insert(FKOSType::mac,FKOSDir::mac);
map.insert(FKOSType::nix,FKOSDir::nix);
map.insert(FKOSType::win,FKOSDir::win);
return map;
}
static const QMap<qint8,QString> platformFolders=getPlatformFolders();
}
#endif // FKOSTYPE_H
| 27.370968 | 74 | 0.706541 |
6686cc54f6defe51389d0770990150a33fd772cc | 52,558 | h | C | dependancies/include/gtkmm/giomm/application.h | Illation/synthesizer | da77d55c1c69829bbad76d0c14b9c56a5261b642 | [
"MIT"
] | 2 | 2020-03-24T09:46:35.000Z | 2020-06-16T01:42:46.000Z | dependancies/include/gtkmm/giomm/application.h | Illation/synthesizer | da77d55c1c69829bbad76d0c14b9c56a5261b642 | [
"MIT"
] | null | null | null | dependancies/include/gtkmm/giomm/application.h | Illation/synthesizer | da77d55c1c69829bbad76d0c14b9c56a5261b642 | [
"MIT"
] | null | null | null | // Generated by gmmproc 2.52.1 -- DO NOT MODIFY!
#ifndef _GIOMM_APPLICATION_H
#define _GIOMM_APPLICATION_H
#include <giommconfig.h>
#include <glibmm/ustring.h>
#include <sigc++/sigc++.h>
/* Copyright (C) 2007 The gtkmm Development Team
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library. If not, see <http://www.gnu.org/licenses/>.
*/
#include <giomm/actiongroup.h>
#include <giomm/actionmap.h>
#include <giomm/applicationcommandline.h>
#include <giomm/file.h>
#include <glibmm/object.h>
#include <glibmm/optionentry.h>
#include <glibmm/optiongroup.h>
#include <glibmm/variant.h>
#include <glibmm/variantdict.h>
#include <giomm/dbusconnection.h>
#include <giomm/notification.h>
#ifndef DOXYGEN_SHOULD_SKIP_THIS
using GApplication = struct _GApplication;
using GApplicationClass = struct _GApplicationClass;
#endif /* DOXYGEN_SHOULD_SKIP_THIS */
#ifndef DOXYGEN_SHOULD_SKIP_THIS
namespace Gio
{ class Application_Class; } // namespace Gio
#endif //DOXYGEN_SHOULD_SKIP_THIS
namespace Gio
{
/** @addtogroup giommEnums giomm Enums and Flags */
/**
* @var ApplicationFlags APPLICATION_FLAGS_NONE
* Default.
*
* @var ApplicationFlags APPLICATION_IS_SERVICE
* Run as a service. In this mode, registration
* fails if the service is already running, and the application
* will initially wait up to 10 seconds for an initial activation
* message to arrive.
*
* @var ApplicationFlags APPLICATION_IS_LAUNCHER
* Don't try to become the primary instance.
*
* @var ApplicationFlags APPLICATION_HANDLES_OPEN
* This application handles opening files (in
* the primary instance). Note that this flag only affects the default
* implementation of local_command_line(), and has no effect if
* APPLICATION_HANDLES_COMMAND_LINE is given.
* See g_application_run() for details.
*
* @var ApplicationFlags APPLICATION_HANDLES_COMMAND_LINE
* This application handles command line
* arguments (in the primary instance). Note that this flag only affect
* the default implementation of local_command_line().
* See g_application_run() for details.
*
* @var ApplicationFlags APPLICATION_SEND_ENVIRONMENT
* Send the environment of the
* launching process to the primary instance. Set this flag if your
* application is expected to behave differently depending on certain
* environment variables. For instance, an editor might be expected
* to use the `GIT_COMMITTER_NAME` environment variable
* when editing a git commit message. The environment is available
* to the Application::signal_command_line() signal handler, via
* g_application_command_line_getenv().
*
* @var ApplicationFlags APPLICATION_NON_UNIQUE
* Make no attempts to do any of the typical
* single-instance application negotiation, even if the application
* ID is given. The application neither attempts to become the
* owner of the application ID nor does it check if an existing
* owner already exists. Everything occurs in the local process.
* @newin{2,30}
*
* @var ApplicationFlags APPLICATION_CAN_OVERRIDE_APP_ID
* Allow users to override the
* application ID from the command line with `--gapplication-app-id`.
* @newin{2,48}
*
* @enum ApplicationFlags
*
* Flags used to define the behaviour of a Application.
*
* @newin{2,28}
*
* @ingroup giommEnums
* @par Bitwise operators:
* <tt>%ApplicationFlags operator|(ApplicationFlags, ApplicationFlags)</tt><br>
* <tt>%ApplicationFlags operator&(ApplicationFlags, ApplicationFlags)</tt><br>
* <tt>%ApplicationFlags operator^(ApplicationFlags, ApplicationFlags)</tt><br>
* <tt>%ApplicationFlags operator~(ApplicationFlags)</tt><br>
* <tt>%ApplicationFlags& operator|=(ApplicationFlags&, ApplicationFlags)</tt><br>
* <tt>%ApplicationFlags& operator&=(ApplicationFlags&, ApplicationFlags)</tt><br>
* <tt>%ApplicationFlags& operator^=(ApplicationFlags&, ApplicationFlags)</tt><br>
*/
enum ApplicationFlags
{
APPLICATION_FLAGS_NONE = 0x0,
APPLICATION_IS_SERVICE = (1 << 0),
APPLICATION_IS_LAUNCHER = (1 << 1),
APPLICATION_HANDLES_OPEN = (1 << 2),
APPLICATION_HANDLES_COMMAND_LINE = (1 << 3),
APPLICATION_SEND_ENVIRONMENT = (1 << 4),
APPLICATION_NON_UNIQUE = (1 << 5),
APPLICATION_CAN_OVERRIDE_APP_ID = (1 << 6)
};
/** @ingroup giommEnums */
inline ApplicationFlags operator|(ApplicationFlags lhs, ApplicationFlags rhs)
{ return static_cast<ApplicationFlags>(static_cast<unsigned>(lhs) | static_cast<unsigned>(rhs)); }
/** @ingroup giommEnums */
inline ApplicationFlags operator&(ApplicationFlags lhs, ApplicationFlags rhs)
{ return static_cast<ApplicationFlags>(static_cast<unsigned>(lhs) & static_cast<unsigned>(rhs)); }
/** @ingroup giommEnums */
inline ApplicationFlags operator^(ApplicationFlags lhs, ApplicationFlags rhs)
{ return static_cast<ApplicationFlags>(static_cast<unsigned>(lhs) ^ static_cast<unsigned>(rhs)); }
/** @ingroup giommEnums */
inline ApplicationFlags operator~(ApplicationFlags flags)
{ return static_cast<ApplicationFlags>(~static_cast<unsigned>(flags)); }
/** @ingroup giommEnums */
inline ApplicationFlags& operator|=(ApplicationFlags& lhs, ApplicationFlags rhs)
{ return (lhs = static_cast<ApplicationFlags>(static_cast<unsigned>(lhs) | static_cast<unsigned>(rhs))); }
/** @ingroup giommEnums */
inline ApplicationFlags& operator&=(ApplicationFlags& lhs, ApplicationFlags rhs)
{ return (lhs = static_cast<ApplicationFlags>(static_cast<unsigned>(lhs) & static_cast<unsigned>(rhs))); }
/** @ingroup giommEnums */
inline ApplicationFlags& operator^=(ApplicationFlags& lhs, ApplicationFlags rhs)
{ return (lhs = static_cast<ApplicationFlags>(static_cast<unsigned>(lhs) ^ static_cast<unsigned>(rhs))); }
/** Application - Core application class.
* An Application is the foundation of an application, unique for a given
* application identifier. The Application class wraps some low-level
* platform-specific services and is intended to act as the foundation for
* higher-level application classes such as Gtk::Application or MxApplication.
* In general, you should not use this class outside of a higher level
* framework.
*
* One of the core features that Application provides is process uniqueness,
* in the context of a "session". The session concept is platform-dependent,
* but corresponds roughly to a graphical desktop login. When your application
* is launched again, its arguments are passed through platform communication
* to the already running program. The already running instance of the program
* is called the <i>primary instance</i>.
*
* Before using Application, you must choose an "application identifier". The
* expected form of an application identifier is very close to that of of a
* <a href="
* http://dbus.freedesktop.org/doc/dbus-specification.html#message-protocol-names-interface">DBus
* bus name</a>. Examples include: "com.example.MyApp",
* "org.example.internal-apps.Calculator". For details on valid application
* identifiers, see id_is_valid().
*
* Application provides convenient life cycle management by maintaining a
* <i>use count</i> for the primary application instance. The use count can be
* changed using hold() and release(). If it drops to zero, the application
* exits.
*
* Application also implements the ActionGroup and ActionMap
* interfaces and lets you easily export actions by adding them with
* Gio::ActionMap::add_action(). When invoking an action by calling
* Gio::ActionGroup::activate_action() on the application, it is always
* invoked in the primary instance.
*
* There is a number of different entry points into an Application:
*
* - via 'Activate' (i.e. just starting the application)
* - via 'Open' (i.e. opening some files)
* - via activating an action
*
* The signal_startup() signal lets you handle the application initialization
* for all of these in a single place.
*
* See the C API docs for an example.
*
* @newin{2,32}
*/
class Application : public Glib::Object, public ActionGroup, public ActionMap
{
#ifndef DOXYGEN_SHOULD_SKIP_THIS
public:
using CppObjectType = Application;
using CppClassType = Application_Class;
using BaseObjectType = GApplication;
using BaseClassType = GApplicationClass;
// noncopyable
Application(const Application&) = delete;
Application& operator=(const Application&) = delete;
private: friend class Application_Class;
static CppClassType application_class_;
protected:
explicit Application(const Glib::ConstructParams& construct_params);
explicit Application(GApplication* castitem);
#endif /* DOXYGEN_SHOULD_SKIP_THIS */
public:
Application(Application&& src) noexcept;
Application& operator=(Application&& src) noexcept;
~Application() noexcept override;
/** Get the GType for this class, for use with the underlying GObject type system.
*/
static GType get_type() G_GNUC_CONST;
#ifndef DOXYGEN_SHOULD_SKIP_THIS
static GType get_base_type() G_GNUC_CONST;
#endif
///Provides access to the underlying C GObject.
GApplication* gobj() { return reinterpret_cast<GApplication*>(gobject_); }
///Provides access to the underlying C GObject.
const GApplication* gobj() const { return reinterpret_cast<GApplication*>(gobject_); }
///Provides access to the underlying C instance. The caller is responsible for unrefing it. Use when directly setting fields in structs.
GApplication* gobj_copy();
private:
protected:
/** Constructs an application instance.
* If no application ID is given then some features (most notably application uniqueness) will be disabled.
*
* @param application_id The application ID.
* @param flags The application flags.
*/
explicit Application(const Glib::ustring& application_id = Glib::ustring(), ApplicationFlags flags = APPLICATION_FLAGS_NONE);
public:
/** The OptionType enum values determine the expected type of a command line option.
* If an option expects an extra argument, it can be specified in several ways;
* with a short option: "-x arg", with a long option: "--name arg" or combined
* in a single argument: "--name=arg". All option types except OPTION_TYPE_BOOL
* expect an extra argument. OPTION_TYPE_STRING_VECTOR and
* OPTION_TYPE_FILENAME_VECTOR accept more than one extra argument.
*
* The descriptions of the enum values show what type of Glib::Variant<>
* is stored in a Glib::VariantDict.
*
* @newin{2,42}
*
* @ingroup glibmmEnums
*/
enum OptionType
{
OPTION_TYPE_BOOL, ///< bool
OPTION_TYPE_STRING, ///< Glib::ustring
OPTION_TYPE_INT, ///< gint32
//OPTION_TYPE_CALLBACK,
OPTION_TYPE_FILENAME = OPTION_TYPE_INT+2, ///< std::string
OPTION_TYPE_STRING_VECTOR, ///< std::vector<Glib::ustring>
OPTION_TYPE_FILENAME_VECTOR, ///< std::vector<std::string>
OPTION_TYPE_DOUBLE, ///< double
OPTION_TYPE_INT64 ///< gint64
};
/** Creates an application instance.
* If no application ID is given then some features (most notably application uniqueness) will be disabled.
*
* @param application_id The application ID.
* @param flags The application flags.
*/
static Glib::RefPtr<Application> create(const Glib::ustring& application_id = Glib::ustring(), ApplicationFlags flags = APPLICATION_FLAGS_NONE);
/** Checks if @a application_id is a valid application identifier.
*
* A valid ID is required for calls to g_application_new() and
* g_application_set_application_id().
*
* For convenience, the restrictions on application identifiers are
* reproduced here:
*
* - Application identifiers must contain only the ASCII characters
* "[A-Z][a-z][0-9]_-." and must not begin with a digit.
*
* - Application identifiers must contain at least one '.' (period)
* character (and thus at least three elements).
*
* - Application identifiers must not begin or end with a '.' (period)
* character.
*
* - Application identifiers must not contain consecutive '.' (period)
* characters.
*
* - Application identifiers must not exceed 255 characters.
*
* @param application_id A potential application identifier.
* @return <tt>true</tt> if @a application_id is valid.
*/
static bool id_is_valid(const Glib::ustring& application_id);
/** Gets the unique identifier for @a application.
*
* @newin{2,28}
*
* @return The identifier for @a application, owned by @a application.
*/
Glib::ustring get_id() const;
/** Sets the unique identifier for @a application.
*
* The application id can only be modified if @a application has not yet
* been registered.
*
* If non-<tt>nullptr</tt>, the application id must be valid. See
* g_application_id_is_valid().
*
* @newin{2,28}
*
* @param application_id The identifier for @a application.
*/
void set_id(const Glib::ustring& application_id);
/** Gets the DBusConnection being used by the application, or <tt>nullptr</tt>.
*
* If Application is using its D-Bus backend then this function will
* return the DBusConnection being used for uniqueness and
* communication with the desktop environment and other instances of the
* application.
*
* If Application is not using D-Bus then this function will return
* <tt>nullptr</tt>. This includes the situation where the D-Bus backend would
* normally be in use but we were unable to connect to the bus.
*
* This function must not be called before the application has been
* registered. See g_application_get_is_registered().
*
* @newin{2,34}
*
* @return A DBusConnection, or <tt>nullptr</tt>.
*/
Glib::RefPtr<DBus::Connection> get_dbus_connection();
/** Gets the DBusConnection being used by the application, or <tt>nullptr</tt>.
*
* If Application is using its D-Bus backend then this function will
* return the DBusConnection being used for uniqueness and
* communication with the desktop environment and other instances of the
* application.
*
* If Application is not using D-Bus then this function will return
* <tt>nullptr</tt>. This includes the situation where the D-Bus backend would
* normally be in use but we were unable to connect to the bus.
*
* This function must not be called before the application has been
* registered. See g_application_get_is_registered().
*
* @newin{2,34}
*
* @return A DBusConnection, or <tt>nullptr</tt>.
*/
Glib::RefPtr<const DBus::Connection> get_dbus_connection() const;
/** Gets the D-Bus object path being used by the application, or <tt>nullptr</tt>.
*
* If Application is using its D-Bus backend then this function will
* return the D-Bus object path that Application is using. If the
* application is the primary instance then there is an object published
* at this path. If the application is not the primary instance then
* the result of this function is undefined.
*
* If Application is not using D-Bus then this function will return
* <tt>nullptr</tt>. This includes the situation where the D-Bus backend would
* normally be in use but we were unable to connect to the bus.
*
* This function must not be called before the application has been
* registered. See g_application_get_is_registered().
*
* @newin{2,34}
*
* @return The object path, or <tt>nullptr</tt>.
*/
Glib::ustring get_dbus_object_path() const;
/** Gets the current inactivity timeout for the application.
*
* This is the amount of time (in milliseconds) after the last call to
* g_application_release() before the application stops running.
*
* @newin{2,28}
*
* @return The timeout, in milliseconds.
*/
guint get_inactivity_timeout() const;
/** Sets the current inactivity timeout for the application.
*
* This is the amount of time (in milliseconds) after the last call to
* g_application_release() before the application stops running.
*
* This call has no side effects of its own. The value set here is only
* used for next time g_application_release() drops the use count to
* zero. Any timeouts currently in progress are not impacted.
*
* @newin{2,28}
*
* @param inactivity_timeout The timeout, in milliseconds.
*/
void set_inactivity_timeout(guint inactivity_timeout);
/** Gets the flags for @a application.
*
* See ApplicationFlags.
*
* @newin{2,28}
*
* @return The flags for @a application.
*/
ApplicationFlags get_flags() const;
/** Sets the flags for @a application.
*
* The flags can only be modified if @a application has not yet been
* registered.
*
* See ApplicationFlags.
*
* @newin{2,28}
*
* @param flags The flags for @a application.
*/
void set_flags(ApplicationFlags flags);
/** Gets the resource base path of @a application.
*
* See g_application_set_resource_base_path() for more information.
*
* @newin{2,44}
*
* @return The base resource path, if one is set.
*/
std::string get_resource_base_path() const;
/** Sets (or unsets) the base resource path of @a application.
*
* The path is used to automatically load various [application
* resources][gresource] such as menu layouts and action descriptions.
* The various types of resources will be found at fixed names relative
* to the given base path.
*
* By default, the resource base path is determined from the application
* ID by prefixing '/' and replacing each '.' with '/'. This is done at
* the time that the Application object is constructed. Changes to
* the application ID after that point will not have an impact on the
* resource base path.
*
* As an example, if the application has an ID of "org.example.app" then
* the default resource base path will be "/org/example/app". If this
* is a Gtk::Application (and you have not manually changed the path)
* then Gtk will then search for the menus of the application at
* "/org/example/app/gtk/menus.ui".
*
* See Resource for more information about adding resources to your
* application.
*
* You can disable automatic resource loading functionality by setting
* the path to <tt>nullptr</tt>.
*
* Changing the resource base path once the application is running is
* not recommended. The point at which the resource path is consulted
* for forming paths for various purposes is unspecified. When writing
* a sub-class of Application you should either set the
* Application::property_resource_base_path() property at construction time, or call
* this function during the instance initialization. Alternatively, you
* can call this function in the ApplicationClass.startup virtual function,
* before chaining up to the parent implementation.
*
* @newin{2,44}
*
* @param resource_path The resource path to use.
*/
void set_resource_base_path(const std::string& resource_path);
/** Disable automatic resource loading functionality.
* See set_resource_base_path().
* @newin{2,44}
*/
void unset_resource_base_path();
#ifndef GIOMM_DISABLE_DEPRECATED
/** This used to be how actions were associated with a Application.
* Now there is ActionMap for that.
*
* @newin{2,28}
*
* Deprecated:2.32:Use the ActionMap interface instead. Never ever
* mix use of this API with use of ActionMap on the same @a application
* or things will go very badly wrong. This function is known to
* introduce buggy behaviour (ie: signals not emitted on changes to the
* action group), so you should really use ActionMap instead.
*
* @deprecated Use the Gio::ActionMap interface instead.
*
* @param action_group A ActionGroup, or <tt>nullptr</tt>.
*/
void set_action_group(const Glib::RefPtr<ActionGroup>& action_group);
#endif // GIOMM_DISABLE_DEPRECATED
//Note: We would like to add a group, not just some entries,
//so we can do pre and post parsing. See https://bugzilla.gnome.org/show_bug.cgi?id=727602
//but instead we need to use the VariantDict passed to the handle_local_options signal
//and provided by ApplicationCommandLine::get_options_dict() in on_command_line().
/** Adds a main option entry to be handled by the Application.
*
* This function is comparable to Glib::OptionGroup::add_entry() +
* Glib::OptionContext::set_main_group().
*
* After the commandline arguments are parsed, the
* signal_handle_local_options() signal will be emitted. At this
* point, the application can inspect the parsed values.
*
* Unlike OptionGroup + OptionContext, Application packs the arguments
* into a Glib::VariantDict which is passed to the
* signal_handle_local_options() handler, where it can be
* inspected and modified. If Gio::APPLICATION_HANDLES_COMMAND_LINE is
* set, then the resulting dictionary is sent to the primary instance,
* where Gio::ApplicationCommandLine::get_options_dict() will return it.
* This "packing" is done according to the type of the argument --
* booleans for normal flags, Glib::ustring's for strings, std::string's for
* filenames, etc. The packing only occurs if the flag is given (ie: we
* do not pack a "false" Variant in the case that a flag is missing).
*
* In general, it is recommended that all commandline arguments are
* parsed locally. The options dictionary should then be used to
* transmit the result of the parsing to the primary instance, where
* Glib::VariantDict::lookup_value() can be used. For local options, it is
* possible to consult (and potentially remove) the option from the options dictionary.
*
* This function is new in GLib 2.40. Before then, the only real choice
* was to send all of the commandline arguments (options and all) to the
* primary instance for handling. Application ignored them completely
* on the local side. Calling this function "opts in" to the new
* behaviour, and in particular, means that unrecognised options will be
* treated as errors. Unrecognised options have never been ignored when
* Gio::APPLICATION_HANDLES_COMMAND_LINE is unset.
*
* If signal_handle_local_options() needs to see the list of
* filenames, then the use of G_OPTION_REMAINING as @a long_name is recommended.
* G_OPTION_REMAINING can be used as a key into
* the options dictionary. If you do use G_OPTION_REMAINING then you
* need to handle these arguments for yourself because once they are
* consumed, they will no longer be visible to the default handling
* (which treats them as filenames to be opened).
*
* @newin{2,42}
*
* @param arg_type A Gio::Application::OptionType.
* @param long_name The long name of an option can be used to specify it
* in a commandline as `--long_name`. Every option must have a
* long name.
* @param short_name If an option has a short name, it can be specified
* `-short_name` in a commandline. @a short_name must be a printable
* ASCII character different from '-', or '\0' if the option has no
* short name.
* @param description The description for the option in `--help` output.
* @param arg_description The placeholder to use for the extra argument parsed
* by the option in `--help` output.
* @param flags Flags from Glib::OptionEntry::Flags. Do not set FLAG_FILENAME.
* Character encoding is chosen with @a arg_type.
*/
void add_main_option_entry(OptionType arg_type, const Glib::ustring& long_name,
gchar short_name = '\0', const Glib::ustring& description = Glib::ustring(),
const Glib::ustring& arg_description = Glib::ustring(), int flags = 0);
//g_application_add_main_option() seems to be just a new convenience function,
//TODO: Use it for some of our add_main_option_entry(without slot) implementation.
/** Adds a main option entry to be handled by the Application.
*
* Adds a string option entry, but lets the callback @a slot parse the extra
* argument instead of having it packed in a Glib::VariantDict.
*
* If you create more than one Application instance (unusual),
* one Application instance can't add an option with the same name as
* another instance adds. This restriction does not apply to the
* add_main_option_entry() that takes an OptionType parameter.
*
* @newin{2,42}
*
* @see add_main_option_entry(OptionType, const Glib::ustring&,
* gchar, const Glib::ustring&, const Glib::ustring&, int)
*/
void add_main_option_entry(const Glib::OptionGroup::SlotOptionArgString& slot,
const Glib::ustring& long_name,
gchar short_name = '\0', const Glib::ustring& description = Glib::ustring(),
const Glib::ustring& arg_description = Glib::ustring(), int flags = 0);
/** Adds a main option entry to be handled by the Application.
*
* Adds a filename option entry, but lets the callback @a slot parse the extra
* argument instead of having it packed in a Glib::VariantDict.
*
* If you create more than one Application instance (unusual),
* one Application instance can't add an option with the same name as
* another instance adds. This restriction does not apply to the
* add_main_option_entry() that takes an OptionType parameter.
*
* @newin{2,42}
*
* @see add_main_option_entry(OptionType, const Glib::ustring&,
* gchar, const Glib::ustring&, const Glib::ustring&, int)
*/
void add_main_option_entry_filename(const Glib::OptionGroup::SlotOptionArgFilename& slot,
const Glib::ustring& long_name,
gchar short_name = '\0', const Glib::ustring& description = Glib::ustring(),
const Glib::ustring& arg_description = Glib::ustring(), int flags = 0);
// _WRAP_METHOD(void add_option_group(Glib::OptionGroup& group), g_application_add_option_group)
// add_option_group() is probably not very useful. If implemented, it must probably
// be custom-implemented. See https://bugzilla.gnome.org/show_bug.cgi?id=727822#c10
/** Checks if @a application is registered.
*
* An application is registered if g_application_register() has been
* successfully called.
*
* @newin{2,28}
*
* @return <tt>true</tt> if @a application is registered.
*/
bool is_registered() const;
/** Checks if @a application is remote.
*
* If @a application is remote then it means that another instance of
* application already exists (the 'primary' instance). Calls to
* perform actions on @a application will result in the actions being
* performed by the primary instance.
*
* The value of this property cannot be accessed before
* g_application_register() has been called. See
* g_application_get_is_registered().
*
* @newin{2,28}
*
* @return <tt>true</tt> if @a application is remote.
*/
bool is_remote() const;
//Renamed from register() because that is a C++ keyword.
/** Attempts registration of the application.
*
* This is the point at which the application discovers if it is the
* primary instance or merely acting as a remote for an already-existing
* primary instance. This is implemented by attempting to acquire the
* application identifier as a unique bus name on the session bus using
* GDBus.
*
* If there is no application ID or if APPLICATION_NON_UNIQUE was
* given, then this process will always become the primary instance.
*
* Due to the internal architecture of GDBus, method calls can be
* dispatched at any time (even if a main loop is not running). For
* this reason, you must ensure that any object paths that you wish to
* register are registered before calling this function.
*
* If the application has already been registered then <tt>true</tt> is
* returned with no work performed.
*
* The Application::signal_startup() signal is emitted if registration succeeds
* and @a application is the primary instance (including the non-unique
* case).
*
* In the event of an error (such as @a cancellable being cancelled, or a
* failure to connect to the session bus), <tt>false</tt> is returned and @a error
* is set appropriately.
*
* @note the return value of this function is not an indicator that this
* instance is or is not the primary instance of the application. See
* g_application_get_is_remote() for that.
*
* @newin{2,28}
*
* @param cancellable A Cancellable, or <tt>nullptr</tt>.
* @return <tt>true</tt> if registration succeeded.
*/
bool register_application(const Glib::RefPtr<Gio::Cancellable>& cancellable);
/// A register_application() convenience overload.
bool register_application();
/** Increases the use count of @a application.
*
* Use this function to indicate that the application has a reason to
* continue to run. For example, g_application_hold() is called by GTK+
* when a toplevel window is on the screen.
*
* To cancel the hold, call g_application_release().
*/
void hold();
/** Decrease the use count of @a application.
*
* When the use count reaches zero, the application will stop running.
*
* Never call this function except to cancel the effect of a previous
* call to g_application_hold().
*/
void release();
/** Activates the application.
*
* In essence, this results in the Application::signal_activate() signal being
* emitted in the primary instance.
*
* The application must be registered before calling this function.
*
* @newin{2,28}
*/
void activate();
using type_vec_files = std::vector< Glib::RefPtr<File> >;
/* Opens the given files.
*
* In essence, this results in the open signal being emitted
* in the primary instance.
*
* @a hint is simply passed through to the open signal. It is
* intended to be used by applications that have multiple modes for
* opening files (eg: "view" vs "edit", etc).
*
* The application must be registered before calling this method
* and it must have the APPLICATION_HANDLES_OPEN flag set.
*
* @param files The files to open. This must be non-empty.
* @param hint A hint.
*
* @newin{2,32}
*/
void open(const type_vec_files& files, const Glib::ustring& hint = Glib::ustring());
/* Opens the given file.
*
* In essence, this results in the open signal being emitted
* in the primary instance.
*
* @a hint is simply passed through to the open signal. It is
* intended to be used by applications that have multiple modes for
* opening files (eg: "view" vs "edit", etc).
*
* The application must be registered before calling this method
* and it must have the APPLICATION_HANDLES_OPEN flag set.
*
* @param file The file to open. This must be non-empty.
* @param hint A hint.
*
* @newin{2,32}
*/
void open(const Glib::RefPtr<Gio::File>& file, const Glib::ustring& hint = Glib::ustring());
/** Runs the application.
*
* This function is intended to be run from main() and its return value
* is intended to be returned by main(). Although you are expected to pass
* the @a argc, @a argv parameters from main() to this function, it is possible
* to pass <tt>nullptr</tt> if @a argv is not available or commandline handling is not
* required. Note that on Windows, @a argc and @a argv are ignored, and
* Glib::win32_get_command_line() is called internally (for proper support
* of Unicode commandline arguments).
*
* Application will attempt to parse the commandline arguments. You
* can add commandline flags to the list of recognised options by way of
* g_application_add_main_option_entries(). After this, the
* Application::signal_handle_local_options() signal is emitted, from which the
* application can inspect the values of its OptionEntrys.
*
* Application::signal_handle_local_options() is a good place to handle options
* such as `--version`, where an immediate reply from the local process is
* desired (instead of communicating with an already-running instance).
* A Application::signal_handle_local_options() handler can stop further processing
* by returning a non-negative value, which then becomes the exit status of
* the process.
*
* What happens next depends on the flags: if
* APPLICATION_HANDLES_COMMAND_LINE was specified then the remaining
* commandline arguments are sent to the primary instance, where a
* Application::signal_command_line() signal is emitted. Otherwise, the
* remaining commandline arguments are assumed to be a list of files.
* If there are no files listed, the application is activated via the
* Application::signal_activate() signal. If there are one or more files, and
* APPLICATION_HANDLES_OPEN was specified then the files are opened
* via the Application::signal_open() signal.
*
* If you are interested in doing more complicated local handling of the
* commandline then you should implement your own Application subclass
* and override local_command_line(). In this case, you most likely want
* to return <tt>true</tt> from your local_command_line() implementation to
* suppress the default handling. See
* [gapplication-example-cmdline2.c][gapplication-example-cmdline2]
* for an example.
*
* If, after the above is done, the use count of the application is zero
* then the exit status is returned immediately. If the use count is
* non-zero then the default main context is iterated until the use count
* falls to zero, at which point 0 is returned.
*
* If the APPLICATION_IS_SERVICE flag is set, then the service will
* run for as much as 10 seconds with a use count of zero while waiting
* for the message that caused the activation to arrive. After that,
* if the use count falls to zero the application will exit immediately,
* except in the case that g_application_set_inactivity_timeout() is in
* use.
*
* This function sets the prgname (Glib::set_prgname()), if not already set,
* to the basename of argv[0].
*
* Much like Glib::main_loop_run(), this function will acquire the main context
* for the duration that the application is running.
*
* Since 2.40, applications that are not explicitly flagged as services
* or launchers (ie: neither APPLICATION_IS_SERVICE or
* APPLICATION_IS_LAUNCHER are given as flags) will check (from the
* default handler for local_command_line) if "--gapplication-service"
* was given in the command line. If this flag is present then normal
* commandline processing is interrupted and the
* APPLICATION_IS_SERVICE flag is set. This provides a "compromise"
* solution whereby running an application directly from the commandline
* will invoke it in the normal way (which can be useful for debugging)
* while still allowing applications to be D-Bus activated in service
* mode. The D-Bus service file should invoke the executable with
* "--gapplication-service" as the sole commandline argument. This
* approach is suitable for use by most graphical applications but
* should not be used from applications like editors that need precise
* control over when processes invoked via the commandline will exit and
* what their exit status will be.
*
* @newin{2,28}
*
* @param argc The argc from main() (or 0 if @a argv is <tt>nullptr</tt>).
* @param argv The argv from main(), or <tt>nullptr</tt>.
* @return The exit status.
*/
int run(int argc, char** argv);
/** Immediately quits the application.
*
* Upon return to the mainloop, g_application_run() will return,
* calling only the 'shutdown' function before doing so.
*
* The hold count is ignored.
*
* The result of calling g_application_run() again after it returns is
* unspecified.
*
* @newin{2,32}
*/
void quit();
/** Sets or unsets the default application for the process, as returned
* by g_application_get_default().
*
* This function does not take its own reference on @a application. If
* @a application is destroyed then the default application will revert
* back to <tt>nullptr</tt>.
*
* @newin{2,32}
*
* @param application The application to set as default, or <tt>nullptr</tt>.
*/
static void set_default(const Glib::RefPtr<Application>& application);
/// Unsets any existing default application.
static void unset_default();
/** Returns the default Application instance for this process.
*
* Normally there is only one Application per process and it becomes
* the default when it is created. You can exercise more control over
* this by using g_application_set_default().
*
* If there is no default application then <tt>nullptr</tt> is returned.
*
* @newin{2,32}
*
* @return The default application for this process, or <tt>nullptr</tt>.
*/
static Glib::RefPtr<Application> get_default();
/** Increases the busy count of @a application.
*
* Use this function to indicate that the application is busy, for instance
* while a long running operation is pending.
*
* The busy state will be exposed to other processes, so a session shell will
* use that information to indicate the state to the user (e.g. with a
* spinner).
*
* To cancel the busy indication, use g_application_unmark_busy().
*
* @newin{2,38}
*/
void mark_busy();
/** Decreases the busy count of @a application.
*
* When the busy count reaches zero, the new state will be propagated
* to other processes.
*
* This function must only be called to cancel the effect of a previous
* call to g_application_mark_busy().
*
* @newin{2,38}
*/
void unmark_busy();
/** Gets the application's current busy state, as set through
* g_application_mark_busy() or g_application_bind_busy_property().
*
* @newin{2,44}
*
* @return <tt>true</tt> if @a application is currenty marked as busy.
*/
bool get_is_busy() const;
/** Sends a notification on behalf of @a application to the desktop shell.
* There is no guarantee that the notification is displayed immediately,
* or even at all.
*
* Notifications may persist after the application exits. It will be
* D-Bus-activated when the notification or one of its actions is
* activated.
*
* Modifying @a notification after this call has no effect. However, the
* object can be reused for a later call to this function.
*
* @a id may be any string that uniquely identifies the event for the
* application. It does not need to be in any special format. For
* example, "new-message" might be appropriate for a notification about
* new messages.
*
* If a previous notification was sent with the same @a id, it will be
* replaced with @a notification and shown again as if it was a new
* notification. This works even for notifications sent from a previous
* execution of the application, as long as @a id is the same string.
*
* @a id may be <tt>nullptr</tt>, but it is impossible to replace or withdraw
* notifications without an id.
*
* If @a notification is no longer relevant, it can be withdrawn with
* g_application_withdraw_notification().
*
* @newin{2,40}
*
* @param id Id of the notification, or <tt>nullptr</tt>.
* @param notification The Notification to send.
*/
void send_notification(const Glib::ustring& id, const Glib::RefPtr<Notification>& notification);
/// A send_notification() convenience overload.
void send_notification(const Glib::RefPtr<Notification>& notification);
/** Withdraws a notification that was sent with
* g_application_send_notification().
*
* This call does nothing if a notification with @a id doesn't exist or
* the notification was never sent.
*
* This function works even for notifications sent in previous
* executions of this application, as long @a id is the same as it was for
* the sent notification.
*
* Note that notifications are dismissed when the user clicks on one
* of the buttons in a notification or triggers its default action, so
* there is no need to explicitly withdraw the notification in that case.
*
* @newin{2,40}
*
* @param id Id of a previously sent notification.
*/
void withdraw_notification(const Glib::ustring& id);
//TODO: Glib::RefPtr<Glib::ObjectBase>, Glib::ObjectBase, or both?
//#m4 __CONVERSION(`const Glib::RefPtr<Glib::ObjectBase>&', `gpointer', `($3)->gobj()')
// _WRAP_METHOD(void bind_busy_property(const Glib::RefPtr<Glib::ObjectBase>& object, const Glib::ustring& property), g_application_bind_busy_property)
// _WRAP_METHOD(void unbind_busy_property(const Glib::RefPtr<Glib::ObjectBase>& object, const Glib::ustring& property), g_application_unbind_busy_property)
#ifndef GIOMM_DISABLE_DEPRECATED
/** The group of actions that the application exports.
* @deprecated Use the Gio::ActionMap interface instead.
*
* @return A PropertyProxy_WriteOnly that allows you to set the value of the property,
* or receive notification when the value of the property changes.
*/
Glib::PropertyProxy_WriteOnly< Glib::RefPtr<ActionGroup> > property_action_group() ;
#endif // GIOMM_DISABLE_DEPRECATED
/** The unique identifier for the application.
*
* @return A PropertyProxy that allows you to get or set the value of the property,
* or receive notification when the value of the property changes.
*/
Glib::PropertyProxy< Glib::ustring > property_application_id() ;
/** The unique identifier for the application.
*
* @return A PropertyProxy_ReadOnly that allows you to get the value of the property,
* or receive notification when the value of the property changes.
*/
Glib::PropertyProxy_ReadOnly< Glib::ustring > property_application_id() const;
/** Flags specifying the behaviour of the application.
*
* @return A PropertyProxy that allows you to get or set the value of the property,
* or receive notification when the value of the property changes.
*/
Glib::PropertyProxy< ApplicationFlags > property_flags() ;
/** Flags specifying the behaviour of the application.
*
* @return A PropertyProxy_ReadOnly that allows you to get the value of the property,
* or receive notification when the value of the property changes.
*/
Glib::PropertyProxy_ReadOnly< ApplicationFlags > property_flags() const;
/** Time (ms) to stay alive after becoming idle.
*
* @return A PropertyProxy that allows you to get or set the value of the property,
* or receive notification when the value of the property changes.
*/
Glib::PropertyProxy< guint > property_inactivity_timeout() ;
/** Time (ms) to stay alive after becoming idle.
*
* @return A PropertyProxy_ReadOnly that allows you to get the value of the property,
* or receive notification when the value of the property changes.
*/
Glib::PropertyProxy_ReadOnly< guint > property_inactivity_timeout() const;
/** If g_application_register() has been called.
*
* @return A PropertyProxy_ReadOnly that allows you to get the value of the property,
* or receive notification when the value of the property changes.
*/
Glib::PropertyProxy_ReadOnly< bool > property_is_registered() const;
/** If this application instance is remote.
*
* @return A PropertyProxy_ReadOnly that allows you to get the value of the property,
* or receive notification when the value of the property changes.
*/
Glib::PropertyProxy_ReadOnly< bool > property_is_remote() const;
/** The base resource path for the application.
*
* @newin{2,44}
*
* @return A PropertyProxy that allows you to get or set the value of the property,
* or receive notification when the value of the property changes.
*/
Glib::PropertyProxy< bool > property_resource_base_path() ;
/** The base resource path for the application.
*
* @newin{2,44}
*
* @return A PropertyProxy_ReadOnly that allows you to get the value of the property,
* or receive notification when the value of the property changes.
*/
Glib::PropertyProxy_ReadOnly< bool > property_resource_base_path() const;
/** Whether the application is currently marked as busy through
* g_application_mark_busy() or g_application_bind_busy_property().
*
* @newin{2,44}
*
* @return A PropertyProxy_ReadOnly that allows you to get the value of the property,
* or receive notification when the value of the property changes.
*/
Glib::PropertyProxy_ReadOnly< bool > property_is_busy() const;
//#m4 __CONVERSION(`const gchar*', `const Glib::ustring&', `Glib::ustring($3)')
//#m4 __CONVERSION(`GVariant*', `const Glib::VariantBase&', `Glib::wrap($3, true)')
/**
* @par Slot Prototype:
* <tt>void on_my_%startup()</tt>
*
* The signal_startup() signal is emitted on the primary instance immediately
* after registration. See g_application_register().
*/
Glib::SignalProxy< void > signal_startup();
//TODO: Remove no_default_handler when we can break ABI
/**
* @par Slot Prototype:
* <tt>void on_my_%shutdown()</tt>
*
* The signal_shutdown() signal is emitted only on the registered primary instance
* immediately after the main loop terminates.
*
* @newin{2,46}
*/
Glib::SignalProxy< void > signal_shutdown();
/**
* @par Slot Prototype:
* <tt>void on_my_%activate()</tt>
*
* The signal_activate() signal is emitted on the primary instance when an
* activation occurs. See g_application_activate().
*/
Glib::SignalProxy< void > signal_activate();
//We wrap the open signal without _WRAP_SIGNAL(), because we need to change its parameters.
//See bug https://bugzilla.gnome.org/show_bug.cgi?id=637457
Glib::SignalProxy< void, const type_vec_files&, const Glib::ustring& > signal_open();
/**
* @par Slot Prototype:
* <tt>int on_my_%command_line(const Glib::RefPtr<ApplicationCommandLine>& command_line)</tt>
*
* The signal_command_line() signal is emitted on the primary instance when
* a commandline is not handled locally. See g_application_run() and
* the ApplicationCommandLine documentation for more information.
*
* @param command_line A ApplicationCommandLine representing the
* passed commandline.
* @return An integer that is set as the exit status for the calling
* process. See g_application_command_line_set_exit_status().
*/
Glib::SignalProxy< int,const Glib::RefPtr<ApplicationCommandLine>& > signal_command_line();
//TODO: Remove no_default_handler when we can break ABI
//TODO: Avoid the use of the Variants in the VariantDict?
//options must be non-const. The handler is meant to modify it. See the description
//of add_main_option_entry(OptionType, ...).
/**
* @par Slot Prototype:
* <tt>int on_my_%handle_local_options(const Glib::RefPtr<Glib::VariantDict>& options)</tt>
*
* The signal_handle_local_options() signal is emitted on the local instance
* after the parsing of the commandline options has occurred.
*
* You can add options to be recognised during commandline option
* parsing using g_application_add_main_option_entries() and
* g_application_add_option_group().
*
* Signal handlers can inspect @a options (along with values pointed to
* from the @a arg_data of an installed OptionEntrys) in order to
* decide to perform certain actions, including direct local handling
* (which may be useful for options like --version).
*
* In the event that the application is marked
* APPLICATION_HANDLES_COMMAND_LINE the "normal processing" will
* send the @a options dictionary to the primary instance where it can be
* read with g_application_command_line_get_options_dict(). The signal
* handler can modify the dictionary before returning, and the
* modified dictionary will be sent.
*
* In the event that APPLICATION_HANDLES_COMMAND_LINE is not set,
* "normal processing" will treat the remaining uncollected command
* line arguments as filenames or URIs. If there are no arguments,
* the application is activated by g_application_activate(). One or
* more arguments results in a call to g_application_open().
*
* If you want to handle the local commandline arguments for yourself
* by converting them to calls to g_application_open() or
* g_action_group_activate_action() then you must be sure to register
* the application first. You should probably not call
* g_application_activate() for yourself, however: just return -1 and
* allow the default handler to do it for you. This will ensure that
* the `--gapplication-service` switch works properly (i.e. no activation
* in that case).
*
* Note that this signal is emitted from the default implementation of
* local_command_line(). If you override that function and don't
* chain up then this signal will never be emitted.
*
* You can override local_command_line() if you need more powerful
* capabilities than what is provided here, but this should not
* normally be required.
*
* @newin{2,40}
*
* @param options The options dictionary.
* @return An exit code. If you have handled your options and want
* to exit the process, return a non-negative option, 0 for success,
* and a positive value for failure. To continue, return -1 to let
* the default option processing continue.
*/
Glib::SignalProxy< int,const Glib::RefPtr<Glib::VariantDict>& > signal_handle_local_options();
protected:
virtual void on_open(const type_vec_files& files, const Glib::ustring& hint);
virtual bool local_command_line_vfunc(char**& arguments, int& exit_status);
virtual void before_emit_vfunc(const Glib::VariantBase& platform_data);
virtual void after_emit_vfunc(const Glib::VariantBase& platform_data);
//TODO: File a bug about GVariantBuilder not being registered with the GType system first:
//_WRAP_VFUNC(void add_platform_data(Glib::VariantBuilder* builder), "add_platform_data")
virtual void quit_mainloop_vfunc();
virtual void run_mainloop_vfunc();
private:
/** This is just a way to call Glib::init() (which calls g_type_init()) before
* calling application_class_.init(), so that
* g_application_get_type() will always succeed.
* See https://bugzilla.gnome.org/show_bug.cgi?id=639925
*/
const Glib::Class& custom_class_init();
// Code, common to the public add_main_option_entry*() methods.
void add_main_option_entry_private(GOptionArg arg, const Glib::ustring& long_name,
gchar short_name, const Glib::ustring& description,
const Glib::ustring& arg_description, int flags);
public:
public:
//C++ methods used to invoke GTK+ virtual functions:
protected:
//GTK+ Virtual Functions (override these to change behaviour):
//Default Signal Handlers::
/// This is a default handler for the signal signal_startup().
virtual void on_startup();
/// This is a default handler for the signal signal_activate().
virtual void on_activate();
/// This is a default handler for the signal signal_command_line().
virtual int on_command_line(const Glib::RefPtr<ApplicationCommandLine>& command_line);
};
} // namespace Gio
namespace Glib
{
/** A Glib::wrap() method for this object.
*
* @param object The C instance.
* @param take_copy False if the result should take ownership of the C instance. True if it should take a new copy or ref.
* @result A C++ instance that wraps this C instance.
*
* @relates Gio::Application
*/
Glib::RefPtr<Gio::Application> wrap(GApplication* object, bool take_copy = false);
}
#endif /* _GIOMM_APPLICATION_H */
| 38.960712 | 156 | 0.717874 |
6879da897e9055dae6d41dccf0c190bf9b12b133 | 2,239 | c | C | rw.c | fpeder/fgh | 388a14241426b0b8bad52c50cd88582ac7c8efde | [
"BSD-2-Clause"
] | 2 | 2020-08-24T18:32:30.000Z | 2022-02-12T13:31:52.000Z | rw.c | fpeder/fgh | 388a14241426b0b8bad52c50cd88582ac7c8efde | [
"BSD-2-Clause"
] | null | null | null | rw.c | fpeder/fgh | 388a14241426b0b8bad52c50cd88582ac7c8efde | [
"BSD-2-Clause"
] | null | null | null | #include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <assert.h>
void bin_print(uint64_t x)
{
int i;
for (i=63; i>=0; i--)
printf("%d", (x>>i) &1ULL);
}
void bwi_print(uint64_t *bmp, int H, int W)
{
int i, j;
for (i=0; i<H; i++) {
for (j=0; j<W; j++)
bin_print(bmp[i*W+j]);
printf("\n");
}
}
void bmp_print(uint8_t *bmp, int H, int W)
{
int i, j;
for (i=0; i<H; i++) {
for (j=0; j<W; j++)
printf("%d ", bmp[i*W+j]);
printf("\n");
}
}
void bmp_write(char *dst, uint8_t *bmp, int H, int W)
{
int i;
FILE *pf = fopen(dst, "wb");
assert(pf);
fwrite(&H, sizeof(int), 1, pf);
fwrite(&W, sizeof(int), 1, pf);
for (i=0; i<H*W; i++)
fwrite(bmp+i, sizeof(uint8_t), 1, pf);
fclose(pf);
}
uint8_t *bmp_read(char *src, int *H, int *W, int *count)
{
int i;
uint8_t *bmp;
FILE *pf = fopen(src, "rb");
assert(pf);
fread(H, sizeof(int), 1, pf);
fread(W, sizeof(int), 1, pf);
bmp = malloc(sizeof(uint8_t)*(*H)*(*W));
for (i=0; i<(*W)*(*H); i++) {
fread(bmp+i, sizeof(uint8_t), 1, pf);
if (bmp[i] == 1) (*count)++;
}
fclose(pf);
return bmp;
}
void bwi_write(char *file, uint64_t *bmp, int H, int W)
{
int i, j, w = W*64;
uint8_t c;
FILE *pf = fopen(file, "wb");
assert(pf);
fwrite(&H, sizeof(int), 1, pf);
fwrite(&w, sizeof(int), 1, pf);
for (i=0; i<H*W; i++)
for (j=63; j>=0; j--) {
c = (bmp[i] >> j) & 1;
fwrite(&c, sizeof(uint8_t), 1, pf);
}
fclose(pf);
}
int bit_count(uint64_t n)
{
int count;
for (count=0; n; count++)
n &= n-1;
return count;
}
uint64_t *bwi_read(char *file, int *H, int *W, int *count)
{
int i=0, j, w, k;
uint8_t c;
uint64_t num, *bmp;
FILE *pf = fopen(file, "rb");
assert(pf);
fread(H, sizeof(int), 1, pf);
fread(&w, sizeof(int), 1, pf); *W = w/64;
bmp = malloc(sizeof(uint64_t)*(*H)*(*W));
for (i=0; i<(*H); i++) {
fseek(pf, 8+i*w, SEEK_SET);
for (j=0; j<(*W); j++) {
k=63; num=0;
while (k >= 0) {
fread(&c, sizeof(uint8_t), 1, pf);
if (c&1) num |= 1ULL << k;
k--;
}
(*count) += bit_count(num);
bmp[i*(*W) + j] = num;
}
}
fclose(pf);
return bmp;
}
| 19.991071 | 58 | 0.498437 |
67fbdfa11b9a712a5f91db9e100fed34de16b5b2 | 1,313 | h | C | GamePlay/PIIClearSelection.h | TaylorClark/PrimeTime | 3c62f6c53e0494146a95be1412273de3cf05bcd2 | [
"MIT"
] | null | null | null | GamePlay/PIIClearSelection.h | TaylorClark/PrimeTime | 3c62f6c53e0494146a95be1412273de3cf05bcd2 | [
"MIT"
] | null | null | null | GamePlay/PIIClearSelection.h | TaylorClark/PrimeTime | 3c62f6c53e0494146a95be1412273de3cf05bcd2 | [
"MIT"
] | null | null | null | //=================================================================================================
/*!
\file PIIClearSelection.h
Game Play Library
Player Input Instruction Clear Selection Header
\author Taylor Clark
\date September 26, 2007
This header contains the definition for the block select game field instruction.
*/
//=================================================================================================
#pragma once
#ifndef __PIIClearSelection_h
#define __PIIClearSelection_h
#include "GameFieldInstruction.h"
#include <list>
class GameFieldBlock;
//-------------------------------------------------------------------------------------------------
/*!
\class PIIClearSelection
\brief The player input instruction that unselects all selected blocks
*/
//-------------------------------------------------------------------------------------------------
class PIIClearSelection : public GameFieldInstruction
{
private:
/// Serialize the instructions to a memory stream
virtual void SubclassSerialize( Serializer& ){}
public:
/// The blocks that lost selection
std::list<uint32> DeselectedBlockIDs;
/// Get the type of instruction this object represents
virtual EGameFieldInstruction GetType() const
{
return GFI_ClearSelection;
}
};
#endif // __PIIClearSelection_h | 27.354167 | 99 | 0.544554 |
d56e526e196f3f3712c5a92cc8f267bbe7cc8cbb | 489 | h | C | Odin/Src/Develop/Odin.Gungnir/Domain/Models/Customer.h | davidgjy/cpp-lib | 7ca654549d135f9dd39f4b7040787ef18006d60c | [
"BSD-3-Clause"
] | null | null | null | Odin/Src/Develop/Odin.Gungnir/Domain/Models/Customer.h | davidgjy/cpp-lib | 7ca654549d135f9dd39f4b7040787ef18006d60c | [
"BSD-3-Clause"
] | null | null | null | Odin/Src/Develop/Odin.Gungnir/Domain/Models/Customer.h | davidgjy/cpp-lib | 7ca654549d135f9dd39f4b7040787ef18006d60c | [
"BSD-3-Clause"
] | null | null | null | #ifndef _Domain_Models_Customer_H_
#define _Domain_Models_Customer_H_
#include <string>
using namespace std;
class Customer
{
private:
string fname;
string lname;
long no;
public:
Customer(const string& fn, const string& ln, long n)
: fname(fn), lname(ln), no(n) {}
friend ostream& operator << (ostream& strm, const Customer& c) {
return strm << "[" << c.fname << "," << c.lname << ","
<< c.no << "]";
}
friend class CustomerHash;
friend class CustomerEqual;
};
#endif | 20.375 | 65 | 0.668712 |
843e4ad22c020753afd1fa5438d5610a30a1e073 | 908 | h | C | beamformer.h | lacker/seticore | 953f24080acc9bd02c06e4625f3b81b12ee9c454 | [
"MIT"
] | null | null | null | beamformer.h | lacker/seticore | 953f24080acc9bd02c06e4625f3b81b12ee9c454 | [
"MIT"
] | null | null | null | beamformer.h | lacker/seticore | 953f24080acc9bd02c06e4625f3b81b12ee9c454 | [
"MIT"
] | null | null | null | #pragma once
using namespace std;
class Beamformer {
public:
// Number of antennas
const int nants;
// Number of beams to form
const int nbeams;
// Number of frequency channels
const int nchans;
// Number of polarities
const int npol;
// Number of timesteps
const int nsamp;
Beamformer(int nants, int nbeams, int nchans, int npol, int nsamp);
~Beamformer();
// The input array is unified to the GPU, used to accept data from the previous step
// in the data processing pipeline.
//
// Its format is row-major:
// input[antenna][frequency][time][polarity]
//
// TODO: explain what each signed char of input actually is. Some weird raw-file-format thing
signed char *input;
// Beamforming coefficients, formatted by row-major:
// coefficients[frequency][beam][polarity][antenna]
float *coefficients;
private:
// TODO: put more buffers here
};
| 21.619048 | 95 | 0.693833 |
84496556a15bdccda95d02a7880fa6dfac70d89c | 3,218 | c | C | trunk/plf/bx2400/src/patch_list/tx_test_end.c | HESUPING/JmeshBLE-StaticLib | cf0900f004026c7e2e3448ffde07e21d4af8e387 | [
"Apache-2.0"
] | null | null | null | trunk/plf/bx2400/src/patch_list/tx_test_end.c | HESUPING/JmeshBLE-StaticLib | cf0900f004026c7e2e3448ffde07e21d4af8e387 | [
"Apache-2.0"
] | null | null | null | trunk/plf/bx2400/src/patch_list/tx_test_end.c | HESUPING/JmeshBLE-StaticLib | cf0900f004026c7e2e3448ffde07e21d4af8e387 | [
"Apache-2.0"
] | 3 | 2019-08-27T17:11:42.000Z | 2021-02-04T06:38:35.000Z | #include <string.h>
#include "compiler.h"
#include "co_endian.h"
#include "co_error.h"
#include "ke_mem.h"
#include "reg_ble_em_rx_desc.h"
#include "reg_ble_em_tx_desc.h"
#include "reg_ble_em_cs.h"
#include "reg_blecore.h"
#include "llm.h"
#include "lld.h"
#if (HCI_PRESENT)
#include "hci.h"
#endif //(HCI_PRESENT)
#include "patch.h"
#include "bx_dbg.h"
void llm_util_chk_tst_mode_patch(void)
{
//if the current state is not IDLE
if((llm_le_env.test_mode.directtesttype != TEST_END) && (llm_le_env.test_mode.end_of_tst == true))
{
// structure type for the complete command event
struct hci_test_end_cmd_cmp_evt *event;
// allocate the complete event message
event = KE_MSG_ALLOC(HCI_CMD_CMP_EVENT, 0, HCI_LE_TEST_END_CMD_OPCODE, hci_test_end_cmd_cmp_evt);
llm_le_env.test_mode.end_of_tst = false;
// enable the whitening
ble_whit_dsb_setf(0);
// Number_Of_Packets for a transmitter test is reported as NULL.
if (llm_le_env.test_mode.directtesttype == TEST_TX)
{
event->nb_packet_received = ble_rftesttxstat_get();
}
else
{
event->nb_packet_received = ble_rxccmpktcnt0_get(LLD_ADV_HDL);
}
// set the env variable,
llm_le_env.test_mode.directtesttype = TEST_END;
// update the status
event->status = CO_ERROR_NO_ERROR;
// send the message
hci_send_2_host(event);
ke_msg_send_basic(LLM_STOP_IND, TASK_LLM, TASK_LLM);
}
}
//#define PATCH_ON_V3
//#define PATCH_ON_V4
#define PATCH_ON_V5
#ifdef PATCH_ON_V3
void patch_tx_test_mode()
{
uint32_t code = cal_patch_bl(0x00018f5c,(uint32_t)llm_util_chk_tst_mode_patch - 1);
uint32_t *src_low = (uint32_t *)0x00018f5c;
// uint32_t *src_high = (uint32_t *)0x191e8;
uint8_t patch_no;
if(patch_alloc(&patch_no)==false)
{
BX_ASSERT(0);
}
patch_entrance_exit_addr(patch_no,(uint32_t)src_low,code);
// patch_entrance_exit_addr(1,(uint32_t)src_high,code&0xffff0000|*src_high&0xffff);
patch_enable_set(1<<patch_no);
}
#elif defined PATCH_ON_V4
void patch_tx_test_mode()
{
uint32_t code = cal_patch_bl(0x191e6,(uint32_t)llm_util_chk_tst_mode_patch - 1);
uint32_t *src_low = (uint32_t *)0x191e4;
uint32_t *src_high = (uint32_t *)0x191e8;
uint8_t patch_no[2];
if(patch_alloc(&patch_no[0])==false)
{
BX_ASSERT(0);
}
if(patch_alloc(&patch_no[1])==false)
{
BX_ASSERT(0);
}
patch_entrance_exit_addr(patch_no[0],(uint32_t)src_low,(code&0xffff)<<16|*src_low&0xffff);
patch_entrance_exit_addr(patch_no[1],(uint32_t)src_high,(code&0xffff0000)>>16|*src_high&0xffff0000);
patch_enable_set((1<<patch_no[0])|(1<<patch_no[1]));
}
#elif defined PATCH_ON_V5
void patch_tx_test_mode()
{
uint32_t code = cal_patch_bl(0x19be6,(uint32_t)llm_util_chk_tst_mode_patch - 1);
uint32_t *src_low = (uint32_t *)0x19be4;
uint32_t *src_high = (uint32_t *)0x19be8;
patch_entrance_exit_addr(0,(uint32_t)src_low,(code&0xffff)<<16|*src_low&0xffff);
patch_entrance_exit_addr(1,(uint32_t)src_high,(code&0xffff0000)>>16|*src_high&0xffff0000);
patch_enable_set(0x3);
}
#endif
| 32.18 | 105 | 0.695774 |
41819baca7d3d666550c64cb749f69ac49f5c76f | 37,534 | c | C | Sample/Universal/UserInterface/UefiSetupBrowser/Dxe/DriverSample/DriverSample.c | bitcrystal/edk | 321b15a55b946372eb21b3e95d323be245c31021 | [
"BSD-3-Clause"
] | 14 | 2016-09-25T02:27:49.000Z | 2021-09-22T15:39:44.000Z | Sample/Universal/UserInterface/UefiSetupBrowser/Dxe/DriverSample/DriverSample.c | bitcrystal/edk | 321b15a55b946372eb21b3e95d323be245c31021 | [
"BSD-3-Clause"
] | 1 | 2015-12-04T20:53:47.000Z | 2015-12-04T20:53:47.000Z | Sample/Universal/UserInterface/UefiSetupBrowser/Dxe/DriverSample/DriverSample.c | bitcrystal/edk | 321b15a55b946372eb21b3e95d323be245c31021 | [
"BSD-3-Clause"
] | 17 | 2015-07-21T10:18:21.000Z | 2021-11-22T17:36:53.000Z | /*++
Copyright (c) 2004 - 2010, Intel Corporation
All rights reserved. This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution. The full text of the license may be found at
http://opensource.org/licenses/bsd-license.php
THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
Module Name:
DriverSample.c
Abstract:
This is an example of how a driver might export data to the HII protocol to be
later utilized by the Setup Protocol
--*/
#include "DriverSample.h"
#define DISPLAY_ONLY_MY_ITEM 0x0000
EFI_GUID mFormSetGuid = FORMSET_GUID;
EFI_GUID mInventoryGuid = INVENTORY_GUID;
CHAR16 VariableName[] = L"MyIfrNVData";
EFI_DRIVER_ENTRY_POINT (DriverSampleInit)
VOID
EncodePassword (
IN CHAR16 *Password,
IN UINT8 MaxSize
)
{
UINTN Index;
UINTN Loop;
CHAR16 *Buffer;
CHAR16 *Key;
Key = L"MAR10648567";
Buffer = EfiLibAllocateZeroPool (MaxSize);
ASSERT (Buffer != NULL);
for (Index = 0; Key[Index] != 0; Index++) {
for (Loop = 0; Loop < (UINT8) (MaxSize / 2); Loop++) {
Buffer[Loop] = (CHAR16) (Password[Loop] ^ Key[Index]);
}
}
EfiCopyMem (Password, Buffer, MaxSize);
gBS->FreePool (Buffer);
return ;
}
EFI_STATUS
ValidatePassword (
DRIVER_SAMPLE_PRIVATE_DATA *PrivateData,
EFI_STRING_ID StringId
)
{
EFI_STATUS Status;
UINTN Index;
UINTN BufferSize;
CHAR16 *Password;
CHAR16 *EncodedPassword;
BOOLEAN OldPassword;
//
// Get encoded password first
//
BufferSize = sizeof (DRIVER_SAMPLE_CONFIGURATION);
Status = gRT->GetVariable (
VariableName,
&mFormSetGuid,
NULL,
&BufferSize,
&PrivateData->Configuration
);
if (EFI_ERROR (Status)) {
//
// Old password not exist, prompt for new password
//
return EFI_SUCCESS;
}
OldPassword = FALSE;
//
// Check whether we have any old password set
//
for (Index = 0; Index < 20; Index++) {
if (PrivateData->Configuration.WhatIsThePassword2[Index] != 0) {
OldPassword = TRUE;
break;
}
}
if (!OldPassword) {
//
// Old password not exist, return EFI_SUCCESS to prompt for new password
//
return EFI_SUCCESS;
}
//
// Get user input password
//
BufferSize = 21 * sizeof (CHAR16);
Password = EfiLibAllocateZeroPool (BufferSize);
ASSERT (Password != NULL);
Status = IfrLibGetString (PrivateData->HiiHandle[0], StringId, Password, &BufferSize);
if (EFI_ERROR (Status)) {
gBS->FreePool (Password);
return Status;
}
//
// Validate old password
//
EncodedPassword = EfiLibAllocateCopyPool (21 * sizeof (CHAR16), Password);
ASSERT (EncodedPassword != NULL);
EncodePassword (EncodedPassword, 20 * sizeof (CHAR16));
if (EfiCompareMem (EncodedPassword, PrivateData->Configuration.WhatIsThePassword2, 20 * sizeof (CHAR16)) != 0) {
//
// Old password mismatch, return EFI_NOT_READY to prompt for error message
//
Status = EFI_NOT_READY;
} else {
Status = EFI_SUCCESS;
}
gBS->FreePool (Password);
gBS->FreePool (EncodedPassword);
return Status;
}
EFI_STATUS
SetPassword (
DRIVER_SAMPLE_PRIVATE_DATA *PrivateData,
EFI_STRING_ID StringId
)
{
EFI_STATUS Status;
UINTN BufferSize;
CHAR16 *Password;
DRIVER_SAMPLE_CONFIGURATION *Configuration;
//
// Get Buffer Storage data from EFI variable
//
BufferSize = sizeof (DRIVER_SAMPLE_CONFIGURATION);
Status = gRT->GetVariable (
VariableName,
&mFormSetGuid,
NULL,
&BufferSize,
&PrivateData->Configuration
);
if (EFI_ERROR (Status)) {
return Status;
}
//
// Get user input password
//
Password = &PrivateData->Configuration.WhatIsThePassword2[0];
EfiZeroMem (Password, 20 * sizeof (CHAR16));
Status = IfrLibGetString (PrivateData->HiiHandle[0], StringId, Password, &BufferSize);
if (EFI_ERROR (Status)) {
return Status;
}
//
// Retrive uncommitted data from Browser
//
BufferSize = sizeof (DRIVER_SAMPLE_CONFIGURATION);
Configuration = EfiLibAllocateZeroPool (sizeof (DRIVER_SAMPLE_PRIVATE_DATA));
ASSERT (Configuration != NULL);
Status = GetBrowserData (&mFormSetGuid, VariableName, &BufferSize, (UINT8 *) Configuration);
if (!EFI_ERROR (Status)) {
//
// Update password's clear text in the screen
//
EfiCopyMem (Configuration->PasswordClearText, Password, 20 * sizeof (CHAR16));
//
// Update uncommitted data of Browser
//
BufferSize = sizeof (DRIVER_SAMPLE_CONFIGURATION);
Status = SetBrowserData (
&mFormSetGuid,
VariableName,
BufferSize,
(UINT8 *) Configuration,
NULL
);
}
gBS->FreePool (Configuration);
//
// Set password
//
EncodePassword (Password, 20 * sizeof (CHAR16));
Status = gRT->SetVariable(
VariableName,
&mFormSetGuid,
EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_BOOTSERVICE_ACCESS,
sizeof (DRIVER_SAMPLE_CONFIGURATION),
&PrivateData->Configuration
);
return Status;
}
EFI_STATUS
LoadNameValueNames (
IN DRIVER_SAMPLE_PRIVATE_DATA *PrivateData
)
/*++
Routine Description:
Update names of Name/Value storage to current language.
Arguments:
PrivateData - Points to the driver private data.
Returns:
EFI_SUCCESS - All names are successfully updated.
Others - Failed to get Name from HII database.
--*/
{
UINTN Index;
UINTN BufferSize;
EFI_STATUS Status;
//
// Get Name/Value name string of current language
//
for (Index = 0; Index < NAME_VALUE_NAME_NUMBER; Index++) {
BufferSize = NAME_VALUE_MAX_STRING_LEN * sizeof (CHAR16);
Status = IfrLibGetString (
PrivateData->HiiHandle[0],
PrivateData->NameStringId[Index],
PrivateData->NameValueName[Index],
&BufferSize
);
if (EFI_ERROR (Status)) {
return Status;
}
}
return EFI_SUCCESS;
}
EFI_STATUS
EFIAPI
ExtractConfig (
IN CONST EFI_HII_CONFIG_ACCESS_PROTOCOL *This,
IN CONST EFI_STRING Request,
OUT EFI_STRING *Progress,
OUT EFI_STRING *Results
)
/*++
Routine Description:
This function allows a caller to extract the current configuration for one
or more named elements from the target driver.
Arguments:
This - Points to the EFI_HII_CONFIG_ACCESS_PROTOCOL.
Request - A null-terminated Unicode string in <ConfigRequest> format.
Progress - On return, points to a character in the Request string.
Points to the string's null terminator if request was successful.
Points to the most recent '&' before the first failing name/value
pair (or the beginning of the string if the failure is in the
first name/value pair) if the request was not successful.
Results - A null-terminated Unicode string in <ConfigAltResp> format which
has all values filled in for the names in the Request string.
String to be allocated by the called function.
Returns:
EFI_SUCCESS - The Results is filled with the requested values.
EFI_OUT_OF_RESOURCES - Not enough memory to store the results.
EFI_INVALID_PARAMETER - Request is NULL, illegal syntax, or unknown name.
EFI_NOT_FOUND - Routing data doesn't match any storage in this driver.
--*/
{
EFI_STATUS Status;
UINTN BufferSize;
DRIVER_SAMPLE_PRIVATE_DATA *PrivateData;
EFI_HII_CONFIG_ROUTING_PROTOCOL *HiiConfigRouting;
EFI_STRING Value;
UINTN ValueStrLen;
CHAR16 BackupChar;
PrivateData = DRIVER_SAMPLE_PRIVATE_FROM_THIS (This);
HiiConfigRouting = PrivateData->HiiConfigRouting;
//
// Get Buffer Storage data from EFI variable
//
BufferSize = sizeof (DRIVER_SAMPLE_CONFIGURATION);
Status = gRT->GetVariable (
VariableName,
&mFormSetGuid,
NULL,
&BufferSize,
&PrivateData->Configuration
);
if (EFI_ERROR (Status)) {
return Status;
}
if (Request == NULL) {
//
// Request is set to NULL, return all configurable elements together with ALTCFG
//
Status = ConstructConfigAltResp (
NULL,
NULL,
Results,
&mFormSetGuid,
VariableName,
PrivateData->DriverHandle[0],
&PrivateData->Configuration,
BufferSize,
VfrMyIfrNVDataBlockName,
2,
STRING_TOKEN (STR_STANDARD_DEFAULT_PROMPT),
VfrMyIfrNVDataDefault0000,
STRING_TOKEN (STR_MANUFACTURE_DEFAULT_PROMPT),
VfrMyIfrNVDataDefault0001
);
return Status;
}
//
// Check if requesting Name/Value storage
//
if (EfiStrStr (Request, L"OFFSET") == NULL) {
//
// Check routing data in <ConfigHdr>.
// Note: there is no name for Name/Value storage, only GUID will be checked
//
if (!IsConfigHdrMatch (Request, &mFormSetGuid, NULL)) {
*Progress = Request;
return EFI_NOT_FOUND;
}
//
// Update Name/Value storage Names
//
Status = LoadNameValueNames (PrivateData);
if (EFI_ERROR (Status)) {
*Progress = Request;
return Status;
}
//
// Allocate memory for <ConfigResp>, e.g. Name0=0x11, Name1=0x1234, Name2="ABCD"
// <Request> ::=<ConfigHdr>&Name0&Name1&Name2
// <ConfigResp>::=<ConfigHdr>&Name0=11&Name1=1234&Name2=0041004200430044
//
BufferSize = (EfiStrLen (Request) +
1 + sizeof (PrivateData->Configuration.NameValueVar0) * 2 +
1 + sizeof (PrivateData->Configuration.NameValueVar1) * 2 +
1 + sizeof (PrivateData->Configuration.NameValueVar2) * 2 + 1) * sizeof (CHAR16);
*Results = EfiLibAllocateZeroPool (BufferSize);
ASSERT (*Results != NULL);
EfiStrCpy (*Results, Request);
Value = *Results;
//
// Append value of NameValueVar0, type is UINT8
//
if ((Value = EfiStrStr (*Results, PrivateData->NameValueName[0])) != NULL) {
Value += EfiStrLen (PrivateData->NameValueName[0]);
ValueStrLen = ((sizeof (PrivateData->Configuration.NameValueVar0) * 2) + 1);
EfiCopyMem (Value + ValueStrLen, Value, EfiStrSize (Value));
*Value++ = L'=';
BufferSize = 16;
BackupChar = Value[ValueStrLen - 1];
BufToHexString (Value, &BufferSize, (UINT8 *) &PrivateData->Configuration.NameValueVar0, sizeof (PrivateData->Configuration.NameValueVar0));
Value[ValueStrLen - 1] = BackupChar;
}
//
// Append value of NameValueVar1, type is UINT16
//
if ((Value = EfiStrStr (*Results, PrivateData->NameValueName[1])) != NULL) {
Value += EfiStrLen (PrivateData->NameValueName[1]);
ValueStrLen = ((sizeof (PrivateData->Configuration.NameValueVar1) * 2) + 1);
EfiCopyMem (Value + ValueStrLen, Value, EfiStrSize (Value));
*Value++ = L'=';
BufferSize = 16;
BackupChar = Value[ValueStrLen - 1];
BufToHexString (Value, &BufferSize, (UINT8 *) &PrivateData->Configuration.NameValueVar1, sizeof (PrivateData->Configuration.NameValueVar1));
Value[ValueStrLen - 1] = BackupChar;
}
//
// Append value of NameValueVar2, type is CHAR16 *
//
if ((Value = EfiStrStr (*Results, PrivateData->NameValueName[2])) != NULL) {
Value += EfiStrLen (PrivateData->NameValueName[2]);
ValueStrLen = EfiStrLen (PrivateData->Configuration.NameValueVar2) * 4 + 1;
EfiCopyMem (Value + ValueStrLen, Value, EfiStrSize (Value));
*Value++ = L'=';
//
// Convert Unicode String to Config String, e.g. "ABCD" => "0041004200430044"
//
ValueStrLen = ValueStrLen * sizeof (CHAR16);
Status = UnicodeToConfigString (Value, &ValueStrLen, PrivateData->Configuration.NameValueVar2);
}
Progress = (EFI_STRING *) Request + EfiStrLen (Request);
return EFI_SUCCESS;
}
//
// Check routing data in <ConfigHdr>.
// Note: if only one Storage is used, then this checking could be skipped.
//
if (!IsConfigHdrMatch (Request, &mFormSetGuid, VariableName)) {
*Progress = Request;
return EFI_NOT_FOUND;
}
//
// Convert buffer data to <ConfigResp> by helper function BlockToConfig()
//
Status = HiiConfigRouting->BlockToConfig (
HiiConfigRouting,
Request,
(UINT8 *) &PrivateData->Configuration,
BufferSize,
Results,
Progress
);
return Status;
}
EFI_STATUS
EFIAPI
RouteConfig (
IN EFI_HII_CONFIG_ACCESS_PROTOCOL *This,
IN CONST EFI_STRING Configuration,
OUT EFI_STRING *Progress
)
/*++
Routine Description:
This function processes the results of changes in configuration.
Arguments:
This - Points to the EFI_HII_CONFIG_ACCESS_PROTOCOL.
Configuration - A null-terminated Unicode string in <ConfigResp> format.
Progress - A pointer to a string filled in with the offset of the most
recent '&' before the first failing name/value pair (or the
beginning of the string if the failure is in the first
name/value pair) or the terminating NULL if all was successful.
Returns:
EFI_SUCCESS - The Results is processed successfully.
EFI_INVALID_PARAMETER - Configuration is NULL.
EFI_NOT_FOUND - Routing data doesn't match any storage in this driver.
--*/
{
EFI_STATUS Status;
UINTN BufferSize;
DRIVER_SAMPLE_PRIVATE_DATA *PrivateData;
EFI_HII_CONFIG_ROUTING_PROTOCOL *HiiConfigRouting;
CHAR16 *Value;
CHAR16 *StrPtr;
CHAR16 BackupChar;
UINTN Length;
if (Configuration == NULL) {
return EFI_INVALID_PARAMETER;
}
PrivateData = DRIVER_SAMPLE_PRIVATE_FROM_THIS (This);
HiiConfigRouting = PrivateData->HiiConfigRouting;
//
// Get Buffer Storage data from EFI variable
//
BufferSize = sizeof (DRIVER_SAMPLE_CONFIGURATION);
Status = gRT->GetVariable (
VariableName,
&mFormSetGuid,
NULL,
&BufferSize,
&PrivateData->Configuration
);
if (EFI_ERROR (Status)) {
return Status;
}
//
// Check if configuring Name/Value storage
//
if (EfiStrStr (Configuration, L"OFFSET") == NULL) {
//
// Check routing data in <ConfigHdr>.
// Note: there is no name for Name/Value storage, only GUID will be checked
//
if (!IsConfigHdrMatch (Configuration, &mFormSetGuid, NULL)) {
*Progress = Configuration;
return EFI_NOT_FOUND;
}
//
// Update Name/Value storage Names
//
Status = LoadNameValueNames (PrivateData);
if (EFI_ERROR (Status)) {
*Progress = Configuration;
return Status;
}
//
// Convert value for NameValueVar0
//
if ((Value = EfiStrStr (Configuration, PrivateData->NameValueName[0])) != NULL) {
//
// Skip "Name="
//
Value += EfiStrLen (PrivateData->NameValueName[0]);
Value++;
StrPtr = EfiStrStr (Value, L"&");
if (StrPtr == NULL) {
StrPtr = Value + EfiStrLen (Value);
}
BackupChar = *StrPtr;
*StrPtr = L'\0';
BufferSize = sizeof (PrivateData->Configuration.NameValueVar0);
Status = HexStringToBuf ((UINT8 *) &PrivateData->Configuration.NameValueVar0, &BufferSize, Value, NULL);
*StrPtr = BackupChar;
}
//
// Convert value for NameValueVar1
//
if ((Value = EfiStrStr (Configuration, PrivateData->NameValueName[1])) != NULL) {
//
// Skip "Name="
//
Value += EfiStrLen (PrivateData->NameValueName[1]);
Value++;
StrPtr = EfiStrStr (Value, L"&");
if (StrPtr == NULL) {
StrPtr = Value + EfiStrLen (Value);
}
BackupChar = *StrPtr;
*StrPtr = L'\0';
BufferSize = sizeof (PrivateData->Configuration.NameValueVar1);
Status = HexStringToBuf ((UINT8 *) &PrivateData->Configuration.NameValueVar1, &BufferSize, Value, NULL);
*StrPtr = BackupChar;
}
//
// Convert value for NameValueVar2
//
if ((Value = EfiStrStr (Configuration, PrivateData->NameValueName[2])) != NULL) {
//
// Skip "Name="
//
Value += EfiStrLen (PrivateData->NameValueName[2]);
Value++;
StrPtr = EfiStrStr (Value, L"&");
if (StrPtr == NULL) {
StrPtr = Value + EfiStrLen (Value);
}
BackupChar = *StrPtr;
*StrPtr = L'\0';
//
// Convert Config String to Unicode String, e.g "0041004200430044" => "ABCD"
//
Length = sizeof (PrivateData->Configuration.NameValueVar2);
Status = ConfigStringToUnicode (PrivateData->Configuration.NameValueVar2, &Length, Value);
*StrPtr = BackupChar;
}
//
// Store Buffer Storage back to EFI variable
//
Status = gRT->SetVariable(
VariableName,
&mFormSetGuid,
EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_BOOTSERVICE_ACCESS,
sizeof (DRIVER_SAMPLE_CONFIGURATION),
&PrivateData->Configuration
);
return Status;
}
//
// Check routing data in <ConfigHdr>.
// Note: if only one Storage is used, then this checking could be skipped.
//
if (!IsConfigHdrMatch (Configuration, &mFormSetGuid, VariableName)) {
*Progress = Configuration;
return EFI_NOT_FOUND;
}
//
// Convert <ConfigResp> to buffer data by helper function ConfigToBlock()
//
BufferSize = sizeof (DRIVER_SAMPLE_CONFIGURATION);
Status = HiiConfigRouting->ConfigToBlock (
HiiConfigRouting,
Configuration,
(UINT8 *) &PrivateData->Configuration,
&BufferSize,
Progress
);
if (EFI_ERROR (Status)) {
return Status;
}
//
// Store Buffer Storage back to EFI variable
//
Status = gRT->SetVariable(
VariableName,
&mFormSetGuid,
EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_BOOTSERVICE_ACCESS,
sizeof (DRIVER_SAMPLE_CONFIGURATION),
&PrivateData->Configuration
);
return Status;
}
EFI_STATUS
EFIAPI
DriverCallback (
IN CONST EFI_HII_CONFIG_ACCESS_PROTOCOL *This,
IN EFI_BROWSER_ACTION Action,
IN EFI_QUESTION_ID QuestionId,
IN UINT8 Type,
IN EFI_IFR_TYPE_VALUE *Value,
OUT EFI_BROWSER_ACTION_REQUEST *ActionRequest
)
/*++
Routine Description:
This function processes the results of changes in configuration.
Arguments:
This - Points to the EFI_HII_CONFIG_ACCESS_PROTOCOL.
Action - Specifies the type of action taken by the browser.
QuestionId - A unique value which is sent to the original exporting driver
so that it can identify the type of data to expect.
Type - The type of value for the question.
Value - A pointer to the data being sent to the original exporting driver.
ActionRequest - On return, points to the action requested by the callback function.
Returns:
EFI_SUCCESS - The callback successfully handled the action.
EFI_OUT_OF_RESOURCES - Not enough storage is available to hold the variable and its data.
EFI_DEVICE_ERROR - The variable could not be saved.
EFI_UNSUPPORTED - The specified Action is not supported by the callback.
--*/
{
DRIVER_SAMPLE_PRIVATE_DATA *PrivateData;
EFI_STATUS Status;
EFI_HII_UPDATE_DATA UpdateData;
IFR_OPTION *IfrOptionList;
UINT8 MyVar;
UINTN BufferSize;
DRIVER_SAMPLE_CONFIGURATION *Configuration;
if ((Value == NULL) || (ActionRequest == NULL)) {
return EFI_INVALID_PARAMETER;
}
Status = EFI_SUCCESS;
PrivateData = DRIVER_SAMPLE_PRIVATE_FROM_THIS (This);
switch (QuestionId) {
case 0x1234:
//
// Initialize the container for dynamic opcodes
//
IfrLibInitUpdateData (&UpdateData, 0x1000);
IfrOptionList = EfiLibAllocatePool (2 * sizeof (IFR_OPTION));
ASSERT (IfrOptionList != NULL);
IfrOptionList[0].Flags = 0;
IfrOptionList[0].StringToken = STRING_TOKEN (STR_BOOT_OPTION1);
IfrOptionList[0].Value.u8 = 1;
IfrOptionList[1].Flags = EFI_IFR_OPTION_DEFAULT;
IfrOptionList[1].StringToken = STRING_TOKEN (STR_BOOT_OPTION2);
IfrOptionList[1].Value.u8 = 2;
CreateActionOpCode (
0x1237, // Question ID
STRING_TOKEN(STR_EXIT_TEXT), // Prompt text
STRING_TOKEN(STR_EXIT_TEXT), // Help text
EFI_IFR_FLAG_CALLBACK, // Question flag
0, // Action String ID
&UpdateData // Container for dynamic created opcodes
);
//
// Prepare initial value for the dynamic created oneof Question
//
PrivateData->Configuration.DynamicOneof = 2;
Status = gRT->SetVariable(
VariableName,
&mFormSetGuid,
EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_BOOTSERVICE_ACCESS,
sizeof (DRIVER_SAMPLE_CONFIGURATION),
&PrivateData->Configuration
);
//
// Set initial vlaue of dynamic created oneof Question in Form Browser
//
BufferSize = sizeof (DRIVER_SAMPLE_CONFIGURATION);
Configuration = EfiLibAllocateZeroPool (sizeof (DRIVER_SAMPLE_CONFIGURATION));
ASSERT (Configuration != NULL);
Status = GetBrowserData (&mFormSetGuid, VariableName, &BufferSize, (UINT8 *) Configuration);
if (!EFI_ERROR (Status)) {
Configuration->DynamicOneof = 2;
//
// Update uncommitted data of Browser
//
SetBrowserData (
&mFormSetGuid,
VariableName,
sizeof (DRIVER_SAMPLE_CONFIGURATION),
(UINT8 *) Configuration,
NULL
);
}
gBS->FreePool (Configuration);
CreateOneOfOpCode (
0x8001, // Question ID (or call it "key")
CONFIGURATION_VARSTORE_ID, // VarStore ID
DYNAMIC_ONE_OF_VAR_OFFSET, // Offset in Buffer Storage
STRING_TOKEN (STR_ONE_OF_PROMPT), // Question prompt text
STRING_TOKEN (STR_ONE_OF_HELP), // Question help text
EFI_IFR_FLAG_CALLBACK, // Question flag
EFI_IFR_NUMERIC_SIZE_1, // Data type of Question Value
IfrOptionList, // Option list
2, // Number of options in Option list
&UpdateData // Container for dynamic created opcodes
);
CreateOrderedListOpCode (
0x8002, // Question ID
CONFIGURATION_VARSTORE_ID, // VarStore ID
DYNAMIC_ORDERED_LIST_VAR_OFFSET, // Offset in Buffer Storage
STRING_TOKEN (STR_BOOT_OPTIONS), // Question prompt text
STRING_TOKEN (STR_BOOT_OPTIONS), // Question help text
EFI_IFR_FLAG_RESET_REQUIRED, // Question flag
0, // Ordered list flag, e.g. EFI_IFR_UNIQUE_SET
EFI_IFR_NUMERIC_SIZE_1, // Data type of Question value
5, // Maximum container
IfrOptionList, // Option list
2, // Number of options in Option list
&UpdateData // Container for dynamic created opcodes
);
CreateGotoOpCode (
1, // Target Form ID
STRING_TOKEN (STR_GOTO_FORM1), // Prompt text
STRING_TOKEN (STR_GOTO_HELP), // Help text
0, // Question flag
0x8003, // Question ID
&UpdateData // Container for dynamic created opcodes
);
Status = IfrLibUpdateForm (
PrivateData->HiiHandle[0], // HII handle
&mFormSetGuid, // Formset GUID
0x1234, // Form ID
0x1234, // Label for where to insert opcodes
TRUE, // Append or replace
&UpdateData // Dynamic created opcodes
);
gBS->FreePool (IfrOptionList);
IfrLibFreeUpdateData (&UpdateData);
break;
case 0x5678:
//
// We will reach here once the Question is refreshed
//
IfrLibInitUpdateData (&UpdateData, 0x1000);
IfrOptionList = EfiLibAllocatePool (2 * sizeof (IFR_OPTION));
ASSERT (IfrOptionList != NULL);
CreateActionOpCode (
0x1237, // Question ID
STRING_TOKEN(STR_EXIT_TEXT), // Prompt text
STRING_TOKEN(STR_EXIT_TEXT), // Help text
EFI_IFR_FLAG_CALLBACK, // Question flag
0, // Action String ID
&UpdateData // Container for dynamic created opcodes
);
Status = IfrLibUpdateForm (
PrivateData->HiiHandle[0], // HII handle
&mFormSetGuid, // Formset GUID
3, // Form ID
0x2234, // Label for where to insert opcodes
TRUE, // Append or replace
&UpdateData // Dynamic created opcodes
);
IfrLibFreeUpdateData (&UpdateData);
//
// Refresh the Question value
//
PrivateData->Configuration.DynamicRefresh++;
Status = gRT->SetVariable(
VariableName,
&mFormSetGuid,
EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_BOOTSERVICE_ACCESS,
sizeof (DRIVER_SAMPLE_CONFIGURATION),
&PrivateData->Configuration
);
//
// Change an EFI Variable storage (MyEfiVar) asynchronous, this will cause
// the first statement in Form 3 be suppressed
//
MyVar = 111;
Status = gRT->SetVariable(
L"MyVar",
&mFormSetGuid,
EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_BOOTSERVICE_ACCESS,
1,
&MyVar
);
break;
case 0x1237:
//
// User press "Exit now", request Browser to exit
//
*ActionRequest = EFI_BROWSER_ACTION_REQUEST_EXIT;
break;
case 0x2000:
//
// When try to set a new password, user will be chanlleged with old password.
// The Callback is responsible for validating old password input by user,
// If Callback return EFI_SUCCESS, it indicates validation pass.
//
switch (PrivateData->PasswordState) {
case BROWSER_STATE_VALIDATE_PASSWORD:
Status = ValidatePassword (PrivateData, Value->string);
if (Status == EFI_SUCCESS) {
PrivateData->PasswordState = BROWSER_STATE_SET_PASSWORD;
}
break;
case BROWSER_STATE_SET_PASSWORD:
Status = SetPassword (PrivateData, Value->string);
PrivateData->PasswordState = BROWSER_STATE_VALIDATE_PASSWORD;
break;
default:
break;
}
break;
default:
break;
}
return Status;
}
EFI_STATUS
EFIAPI
DriverSampleInit (
IN EFI_HANDLE ImageHandle,
IN EFI_SYSTEM_TABLE *SystemTable
)
{
EFI_STATUS Status;
EFI_STATUS SavedStatus;
EFI_HII_PACKAGE_LIST_HEADER *PackageList;
EFI_HII_HANDLE HiiHandle[2];
EFI_HANDLE DriverHandle[2];
DRIVER_SAMPLE_PRIVATE_DATA *PrivateData;
EFI_SCREEN_DESCRIPTOR Screen;
EFI_HII_DATABASE_PROTOCOL *HiiDatabase;
EFI_HII_STRING_PROTOCOL *HiiString;
EFI_FORM_BROWSER2_PROTOCOL *FormBrowser2;
EFI_HII_CONFIG_ROUTING_PROTOCOL *HiiConfigRouting;
CHAR16 *NewString;
UINTN BufferSize;
DRIVER_SAMPLE_CONFIGURATION *Configuration;
BOOLEAN ExtractIfrDefault;
//
// Initialize the library and our protocol.
//
EfiInitializeDriverLib (ImageHandle, SystemTable);
//
// Initialize screen dimensions for SendForm().
// Remove 3 characters from top and bottom
//
EfiZeroMem (&Screen, sizeof (EFI_SCREEN_DESCRIPTOR));
gST->ConOut->QueryMode (gST->ConOut, gST->ConOut->Mode->Mode, &Screen.RightColumn, &Screen.BottomRow);
Screen.TopRow = 3;
Screen.BottomRow = Screen.BottomRow - 3;
//
// Initialize driver private data
//
PrivateData = EfiLibAllocatePool (sizeof (DRIVER_SAMPLE_PRIVATE_DATA));
if (PrivateData == NULL) {
return EFI_OUT_OF_RESOURCES;
}
PrivateData->Signature = DRIVER_SAMPLE_PRIVATE_SIGNATURE;
PrivateData->ConfigAccess.ExtractConfig = ExtractConfig;
PrivateData->ConfigAccess.RouteConfig = RouteConfig;
PrivateData->ConfigAccess.Callback = DriverCallback;
PrivateData->PasswordState = BROWSER_STATE_VALIDATE_PASSWORD;
//
// Locate Hii Database protocol
//
Status = gBS->LocateProtocol (&gEfiHiiDatabaseProtocolGuid, NULL, &HiiDatabase);
if (EFI_ERROR (Status)) {
return Status;
}
PrivateData->HiiDatabase = HiiDatabase;
//
// Locate HiiString protocol
//
Status = gBS->LocateProtocol (&gEfiHiiStringProtocolGuid, NULL, &HiiString);
if (EFI_ERROR (Status)) {
return Status;
}
PrivateData->HiiString = HiiString;
//
// Locate Formbrowser2 protocol
//
Status = gBS->LocateProtocol (&gEfiFormBrowser2ProtocolGuid, NULL, &FormBrowser2);
if (EFI_ERROR (Status)) {
return Status;
}
PrivateData->FormBrowser2 = FormBrowser2;
//
// Locate ConfigRouting protocol
//
Status = gBS->LocateProtocol (&gEfiHiiConfigRoutingProtocolGuid, NULL, &HiiConfigRouting);
if (EFI_ERROR (Status)) {
return Status;
}
PrivateData->HiiConfigRouting = HiiConfigRouting;
//
// Install Config Access protocol
//
Status = CreateHiiDriverHandle (&DriverHandle[0]);
if (EFI_ERROR (Status)) {
return Status;
}
PrivateData->DriverHandle[0] = DriverHandle[0];
Status = gBS->InstallProtocolInterface (
&DriverHandle[0],
&gEfiHiiConfigAccessProtocolGuid,
EFI_NATIVE_INTERFACE,
&PrivateData->ConfigAccess
);
ASSERT_EFI_ERROR (Status);
//
// Publish our HII data
//
PackageList = PreparePackageList (
2,
&mFormSetGuid,
DriverSampleStrings,
VfrBin
);
if (PackageList == NULL) {
return EFI_OUT_OF_RESOURCES;
}
Status = HiiDatabase->NewPackageList (
HiiDatabase,
PackageList,
DriverHandle[0],
&HiiHandle[0]
);
gBS->FreePool (PackageList);
if (EFI_ERROR (Status)) {
return Status;
}
PrivateData->HiiHandle[0] = HiiHandle[0];
//
// Publish another Fromset
//
Status = CreateHiiDriverHandle (&DriverHandle[1]);
if (EFI_ERROR (Status)) {
return Status;
}
PrivateData->DriverHandle[1] = DriverHandle[1];
PackageList = PreparePackageList (
2,
&mInventoryGuid,
DriverSampleStrings,
InventoryBin
);
if (PackageList == NULL) {
return EFI_OUT_OF_RESOURCES;
}
Status = HiiDatabase->NewPackageList (
HiiDatabase,
PackageList,
DriverHandle[1],
&HiiHandle[1]
);
gBS->FreePool (PackageList);
if (EFI_ERROR (Status)) {
return Status;
}
PrivateData->HiiHandle[1] = HiiHandle[1];
//
// Very simple example of how one would update a string that is already
// in the HII database
//
NewString = L"700 Mhz";
Status = IfrLibSetString (HiiHandle[0], STRING_TOKEN (STR_CPU_STRING2), NewString);
if (EFI_ERROR (Status)) {
return Status;
}
//
// Initialize Name/Value name String ID
//
PrivateData->NameStringId[0] = STR_NAME_VALUE_VAR_NAME0;
PrivateData->NameStringId[1] = STR_NAME_VALUE_VAR_NAME1;
PrivateData->NameStringId[2] = STR_NAME_VALUE_VAR_NAME2;
//
// Initialize configuration data
//
Configuration = &PrivateData->Configuration;
EfiZeroMem (Configuration, sizeof (DRIVER_SAMPLE_CONFIGURATION));
//
// Try to read NV config EFI variable first
//
ExtractIfrDefault = TRUE;
BufferSize = sizeof (DRIVER_SAMPLE_CONFIGURATION);
Status = gRT->GetVariable (VariableName, &mFormSetGuid, NULL, &BufferSize, Configuration);
if (!EFI_ERROR (Status) && (BufferSize == sizeof (DRIVER_SAMPLE_CONFIGURATION))) {
ExtractIfrDefault = FALSE;
}
if (ExtractIfrDefault) {
//
// EFI variable for NV config doesn't exit, we should build this variable
// based on default values stored in IFR
//
BufferSize = sizeof (DRIVER_SAMPLE_CONFIGURATION);
Status = ExtractDefault (Configuration, &BufferSize, 1, VfrMyIfrNVDataDefault0000);
if (!EFI_ERROR (Status)) {
gRT->SetVariable(
VariableName,
&mFormSetGuid,
EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_BOOTSERVICE_ACCESS,
sizeof (DRIVER_SAMPLE_CONFIGURATION),
Configuration
);
}
}
//
// Example of how to display only the item we sent to HII
//
if (DISPLAY_ONLY_MY_ITEM == 0x0001) {
//
// Have the browser pull out our copy of the data, and only display our data
//
// Status = FormConfig->SendForm (FormConfig, TRUE, HiiHandle, NULL, NULL, NULL, &Screen, NULL);
//
Status = FormBrowser2->SendForm (
FormBrowser2,
HiiHandle,
1,
NULL,
0,
NULL,
NULL
);
SavedStatus = Status;
Status = HiiDatabase->RemovePackageList (HiiDatabase, HiiHandle[0]);
if (EFI_ERROR (Status)) {
return Status;
}
Status = HiiDatabase->RemovePackageList (HiiDatabase, HiiHandle[1]);
if (EFI_ERROR (Status)) {
return Status;
}
return SavedStatus;
} else {
//
// Have the browser pull out all the data in the HII Database and display it.
//
// Status = FormConfig->SendForm (FormConfig, TRUE, 0, NULL, NULL, NULL, NULL, NULL);
//
}
return EFI_SUCCESS;
}
| 32.440795 | 147 | 0.573453 |
b95b33fb824231be3e29f37e701aabcb408dcb2f | 251 | h | C | src/crypto/pobh.h | criptolot/estatero | 20df006e76297b8ba750ad81980d893867e45752 | [
"MIT"
] | 63 | 2017-07-25T21:57:21.000Z | 2022-02-05T02:58:03.000Z | src/crypto/pobh.h | coinsinspect/biblepay-evolution | c9795a9b9eed0db6d2a1b4719d5e517e46d6e2cc | [
"MIT"
] | 105 | 2017-09-04T00:52:17.000Z | 2021-05-22T13:58:37.000Z | src/crypto/pobh.h | coinsinspect/biblepay-evolution | c9795a9b9eed0db6d2a1b4719d5e517e46d6e2cc | [
"MIT"
] | 62 | 2017-08-04T19:48:40.000Z | 2021-07-07T12:21:12.000Z | #ifndef _POBH_H
#define _POBH_H
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
extern void initpobh();
void POBH2(unsigned char *x11, uint8_t theHash[], unsigned char *x12);
#endif /* _POBH_H_ */
| 17.928571 | 70 | 0.713147 |
3b71eff8348d39339deb222442f237e0f3b6bc74 | 1,043 | h | C | dart-impl/shmem/test/utils.h | RuhanDev/dash | c56193149c334e552df6f8439c3fb1510048b7f1 | [
"BSD-3-Clause"
] | 1 | 2019-05-19T20:31:20.000Z | 2019-05-19T20:31:20.000Z | dart-impl/shmem/test/utils.h | RuhanDev/dash | c56193149c334e552df6f8439c3fb1510048b7f1 | [
"BSD-3-Clause"
] | null | null | null | dart-impl/shmem/test/utils.h | RuhanDev/dash | c56193149c334e552df6f8439c3fb1510048b7f1 | [
"BSD-3-Clause"
] | 2 | 2019-10-02T23:19:22.000Z | 2020-06-27T09:23:31.000Z |
#ifndef UTILS_H_INCLUDED
#define UTILS_H_INCLUDED
#include <sys/time.h>
#include <time.h>
#include <stdio.h>
#define MYTIMEVAL( tv_ ) \
((tv_.tv_sec)+(tv_.tv_usec)*1.0e-6)
#define TIMESTAMP( time_ ) \
{ \
static struct timeval tv; \
gettimeofday( &tv, NULL ); \
time_=MYTIMEVAL(tv); \
}
#define GPTR_SPRINTF(buf_, gptr_) \
sprintf(buf_, "(unit=%d,seg=%d,flags=%d,addr=%p)", \
gptr_.unitid, gptr_.segid, gptr_.flags, \
gptr_.addr_or_offs.addr);
#define CHECK(fncall) do { \
int _retval; \
if ((_retval = fncall) != DART_OK) { \
fprintf(stderr, "ERROR %d calling: %s" \
" at: %s:%i", \
_retval, #fncall, __FILE__, __LINE__); \
fflush(stderr); \
} \
} while(0)
#endif /* UTILS_H_INCLUDED */
| 28.189189 | 70 | 0.441035 |
3bf85c8309faeeee3c4043c5dd77fbc2014a01c0 | 4,409 | h | C | Component/Classes/XKRouter.h | HPTears/Router | 902a51379f0f41c527c39b7bc79e60d9d8deb325 | [
"MIT"
] | null | null | null | Component/Classes/XKRouter.h | HPTears/Router | 902a51379f0f41c527c39b7bc79e60d9d8deb325 | [
"MIT"
] | null | null | null | Component/Classes/XKRouter.h | HPTears/Router | 902a51379f0f41c527c39b7bc79e60d9d8deb325 | [
"MIT"
] | null | null | null | /*******************************************************************************
# File : XKRouter.h
# Project : xk
# Author : Jamesholy
# Created : 12/6/17
# Corporation : xk
# Description :
项目路由,负责分发页面跳转
-------------------------------------------------------------------------------
# Date : <#Change Date#>
# Author : <#Change Author#>
# Notes :
<#Change Logs#>
******************************************************************************/
#import <UIKit/UIKit.h>
static NSString * const kRouterAdapter = @"RAdapter";
static NSString * const kRouterStoryboard = @"storyboard";
static NSString * const kRouterIdentifier = @"identifier";
static NSString * const kRouterXibName = @"nibname";
static NSString * const kRouterTargetClass= @"targetclass";
static NSString * const kRouterObjectType = @"ObjectType";
static NSString * const kRouterBoolType = @"BoolType";
static NSString * const kRouterIntegerType = @"IntegerType";
static NSString * const kRouterFolatType = @"FolatType";
static NSString * const kRouterBoolTrue = @"true";
static NSString * const kRouterBoolFalse = @"false";
NS_ASSUME_NONNULL_BEGIN
// xk使用. 其他app可使用 scheme 属性读取
extern NSString * const kOpenRouteSchmem;
#pragma mark - XKRouterProtrol
@protocol XKRouterProtrol<NSObject>
@required
/**
远程调用 跳转
@param params NSDictionary
@param vc 响应根控制器
*/
+ (void)jumpRemoteWithParams:(NSDictionary *)params Parent:(UIViewController *)vc;
@end
#pragma mark - XKRouter
@interface XKRouter : NSObject
/**
scheme
*/
@property (nonatomic, copy, readonly) NSString *scheme;
/**
路由单例对象
@return 实例
*/
+ (instancetype)sharedInstance;
/**
配置路由scheme default: xksquare:
@desc: 在 didFinishLaunchingWithOptions: 中设置 或者 在mian.m 中设置,
保证程序刚启动就已经配置完成。
在《晓可》app 中可以不设置,使用默认选项即可,其他项目app则必须参考上述设置。
*/
- (void)configRouteScheme:(NSString *)scheme;
/**
处理 远程 open Url 中文请进行url编码(uft-8)
@param urlStr 例如:xk://house.detail?caseId=6632361&caseType=1&bizType=1
@param vc 响应跳转的根视图
@return bool
@desc:
当 vc = nil,内部会将这次的路由跳转缓存起来,在能够处理响应的时候,调用 handleCacheOpenURL。
query 支持 数组 字典类型。例如: xksquare://com.abc?city[0]=beijing&city[2]=shanghai&city[3]=hangzhou&person[name]=li&person[age]=21&id=53278
@use scene:
例如: apns推送,app 收到推送,需要处理url跳转,但是此刻app,可能刚被唤醒,所以可以当app 启动完成,进入第一个vc之后,再去处理响应。
*/
- (BOOL)runRemoteUrl:(nullable NSString *)urlStr ParentVC:(nullable UIViewController *)vc;
/**
调用 本地 native 方法
@desc: 使用于 组件化跨模块的方式 调用,基本不会在业务层直接调用,该方法主要用于组件化解耦,采用 target-action 模式,
具体组件化实际调用流程: 1. 每个组件内部,有两个文件( HFTRouter+ModuleName.h Target_ModuleName.h)
这两个文件是组件内部的通信子module,组件内部的跳转也可以使用这两个文件.
2. 跨越组件通信的时候,以 HFTRouter 为底层通信处理,以内部通信组件为对接。
@param targetName 目标类名(字符串)
@param actionName 方法名 (字符串)
@param params 传递参数 (k-v)
@return id 类型
*/
- (nullable id)runNativeTarget:(NSString *)targetName Action:(NSString *)actionName Params:(nullable NSDictionary *)params;
/**
处理缓存 url
*/
- (void)handleCacheRemoteURL;
/**
获取参数
@param urlStr 路由URL
@return 参数
*/
- (NSDictionary *)getParamsWithParseURL:(NSString *)urlStr;
@end
#pragma mark - XKRouter (Host)
@interface XKRouter (Host)
/**
生成 远程 url
@param host host 例如:im.detail
@param params 参数
@return url
*/
- (NSString *)urlRemoteHost:(NSString *)host Params:(nullable NSDictionary *)params;
/**
生成 动态调用的远程 url
@param targetClass 目标类名
@param storyname storyname 非storyname启动,则为nil
@param identifier identifier
@param xibName xib文件名
@param params 参数
@return url
@desc:
示例
NSString *url = [XKRouter urlDynamicTargetClassName:@"SosoDetailInfoViewController" Storyboard:@"SosoDetailInfoViewController" Identifier:@"SosoDetailInfoViewController" Params:@{@"houseId":@"1011097221",@"houseInfoState":@"0",@"isFromHome":@"1"}];
获取到 xk://com.dynamic?storyboard=SosoDetailInfoViewController&targetclass=SosoDetailInfoViewController&houseInfoState=0&identifier=SosoDetailInfoViewController&houseId=1011097221&isFromHome=1
*/
- (NSString *)urlDynamicTargetClassName:(NSString *)targetClass Storyboard:(nullable NSString *)storyname Identifier:(nullable NSString *)identifier XibName:(nullable NSString *)xibName Params:(nullable NSDictionary *)params;
@end
@interface XKRouter (method)
+ (NSArray *)propertyListByClass:(Class)clasS propertyClassMap:(NSDictionary **)map;
@end
NS_ASSUME_NONNULL_END
| 25.33908 | 249 | 0.687911 |
b3efad73c5622063e5334c3ba75e2129f90e6461 | 7,169 | h | C | indra/newview/noise.h | humbletim/archived-casviewer | 3b51b1baae7e7cebf1c7dca62d9c02751709ee57 | [
"Unlicense"
] | 1 | 2022-01-29T07:10:03.000Z | 2022-01-29T07:10:03.000Z | indra/newview/noise.h | bloomsirenix/Firestorm-manikineko | 67e1bb03b2d05ab16ab98097870094a8cc9de2e7 | [
"Unlicense"
] | null | null | null | indra/newview/noise.h | bloomsirenix/Firestorm-manikineko | 67e1bb03b2d05ab16ab98097870094a8cc9de2e7 | [
"Unlicense"
] | 1 | 2021-10-01T22:22:27.000Z | 2021-10-01T22:22:27.000Z | /**
* @file noise.h
* @brief Perlin noise routines for procedural textures, etc
*
* $LicenseInfo:firstyear=2000&license=viewerlgpl$
* Second Life Viewer Source Code
* Copyright (C) 2010, Linden Research, Inc.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation;
* version 2.1 of the License only.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
* Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA
* $/LicenseInfo$
*/
#ifndef LL_NOISE_H
#define LL_NOISE_H
#include "llmath.h"
F32 turbulence2(F32 *v, F32 freq);
F32 turbulence3(float *v, float freq);
F32 clouds3(float *v, float freq);
F32 noise2(float *vec);
F32 noise3(float *vec);
inline F32 bias(F32 a, F32 b)
{
return (F32)pow(a, (F32)(log(b) / log(0.5f)));
}
inline F32 gain(F32 a, F32 b)
{
F32 p = (F32) (log(1.f - b) / log(0.5f));
if (a < .001f)
return 0.f;
else if (a > .999f)
return 1.f;
if (a < 0.5f)
return (F32)(pow(2 * a, p) / 2.f);
else
return (F32)(1.f - pow(2 * (1.f - a), p) / 2.f);
}
inline F32 turbulence2(F32 *v, F32 freq)
{
F32 t, vec[2];
for (t = 0.f ; freq >= 1.f ; freq *= 0.5f) {
vec[0] = freq * v[0];
vec[1] = freq * v[1];
t += noise2(vec)/freq;
}
return t;
}
inline F32 turbulence3(F32 *v, F32 freq)
{
F32 t, vec[3];
for (t = 0.f ; freq >= 1.f ; freq *= 0.5f) {
vec[0] = freq * v[0];
vec[1] = freq * v[1];
vec[2] = freq * v[2];
t += noise3(vec)/freq;
// t += fabs(noise3(vec)) / freq; // Like snow - bubbly at low frequencies
// t += sqrt(fabs(noise3(vec))) / freq; // Better at low freq
// t += (noise3(vec)*noise3(vec)) / freq;
}
return t;
}
inline F32 clouds3(F32 *v, F32 freq)
{
F32 t, vec[3];
for (t = 0.f ; freq >= 1.f ; freq *= 0.5f) {
vec[0] = freq * v[0];
vec[1] = freq * v[1];
vec[2] = freq * v[2];
//t += noise3(vec)/freq;
// t += fabs(noise3(vec)) / freq; // Like snow - bubbly at low frequencies
// t += sqrt(fabs(noise3(vec))) / freq; // Better at low freq
t += (noise3(vec)*noise3(vec)) / freq;
}
return t;
}
/* noise functions over 1, 2, and 3 dimensions */
#define B 0x100
#define BM 0xff
#define N 0x1000
#define NF32 (4096.f)
#define NP 12 /* 2^N */
#define NM 0xfff
extern S32 p[B + B + 2];
extern F32 g3[B + B + 2][3];
extern F32 g2[B + B + 2][2];
extern F32 g1[B + B + 2];
extern S32 gNoiseStart;
static void init(void);
#define s_curve(t) ( t * t * (3.f - 2.f * t) )
#define lerp_m(t, a, b) ( a + t * (b - a) )
#define setup_noise(i,b0,b1,r0,r1)\
t = vec[i] + N;\
b0 = (lltrunc(t)) & BM;\
b1 = (b0+1) & BM;\
r0 = t - lltrunc(t);\
r1 = r0 - 1.f;
inline void fast_setup(F32 vec, U8 &b0, U8 &b1, F32 &r0, F32 &r1)
{
S32 t_S32;
r1 = vec + NF32;
t_S32 = lltrunc(r1);
b0 = (U8)t_S32;
b1 = b0 + 1;
r0 = r1 - t_S32;
r1 = r0 - 1.f;
}
inline F32 noise1(const F32 arg)
{
int bx0, bx1;
F32 rx0, rx1, sx, t, u, v, vec[1];
vec[0] = arg;
if (gNoiseStart) {
gNoiseStart = 0;
init();
}
setup_noise(0, bx0,bx1, rx0,rx1);
sx = s_curve(rx0);
u = rx0 * g1[ p[ bx0 ] ];
v = rx1 * g1[ p[ bx1 ] ];
return lerp_m(sx, u, v);
}
inline F32 fast_at2(F32 rx, F32 ry, F32 *q)
{
return rx * (*q) + ry * (*(q + 1));
}
inline F32 fast_at3(F32 rx, F32 ry, F32 rz, F32 *q)
{
return rx * (*q) + ry * (*(q + 1)) + rz * (*(q + 2));
}
inline F32 noise3(F32 *vec)
{
U8 bx0, bx1, by0, by1, bz0, bz1;
S32 b00, b10, b01, b11;
F32 rx0, rx1, ry0, ry1, rz0, rz1, *q, sy, sz, a, b, c, d, t, u, v;
S32 i, j;
if (gNoiseStart) {
gNoiseStart = 0;
init();
}
fast_setup(*vec, bx0,bx1, rx0,rx1);
fast_setup(*(vec + 1), by0,by1, ry0,ry1);
fast_setup(*(vec + 2), bz0,bz1, rz0,rz1);
i = p[ bx0 ];
j = p[ bx1 ];
b00 = p[ i + by0 ];
b10 = p[ j + by0 ];
b01 = p[ i + by1 ];
b11 = p[ j + by1 ];
t = s_curve(rx0);
sy = s_curve(ry0);
sz = s_curve(rz0);
q = g3[ b00 + bz0 ];
u = fast_at3(rx0,ry0,rz0,q);
q = g3[ b10 + bz0 ];
v = fast_at3(rx1,ry0,rz0,q);
a = lerp_m(t, u, v);
q = g3[ b01 + bz0 ];
u = fast_at3(rx0,ry1,rz0,q);
q = g3[ b11 + bz0 ];
v = fast_at3(rx1,ry1,rz0,q);
b = lerp_m(t, u, v);
c = lerp_m(sy, a, b);
q = g3[ b00 + bz1 ];
u = fast_at3(rx0,ry0,rz1,q);
q = g3[ b10 + bz1 ];
v = fast_at3(rx1,ry0,rz1,q);
a = lerp_m(t, u, v);
q = g3[ b01 + bz1 ];
u = fast_at3(rx0,ry1,rz1,q);
q = g3[ b11 + bz1 ];
v = fast_at3(rx1,ry1,rz1,q);
b = lerp_m(t, u, v);
d = lerp_m(sy, a, b);
return lerp_m(sz, c, d);
}
/*
F32 noise3(F32 *vec)
{
int bx0, bx1, by0, by1, bz0, bz1, b00, b10, b01, b11;
F32 rx0, rx1, ry0, ry1, rz0, rz1, *q, sy, sz, a, b, c, d, t, u, v;
S32 i, j;
if (gNoiseStart) {
gNoiseStart = 0;
init();
}
setup_noise(0, bx0,bx1, rx0,rx1);
setup_noise(1, by0,by1, ry0,ry1);
setup_noise(2, bz0,bz1, rz0,rz1);
i = p[ bx0 ];
j = p[ bx1 ];
b00 = p[ i + by0 ];
b10 = p[ j + by0 ];
b01 = p[ i + by1 ];
b11 = p[ j + by1 ];
t = s_curve(rx0);
sy = s_curve(ry0);
sz = s_curve(rz0);
#define at3(rx,ry,rz) ( rx * q[0] + ry * q[1] + rz * q[2] )
q = g3[ b00 + bz0 ] ; u = at3(rx0,ry0,rz0);
q = g3[ b10 + bz0 ] ; v = at3(rx1,ry0,rz0);
a = lerp_m(t, u, v);
q = g3[ b01 + bz0 ] ; u = at3(rx0,ry1,rz0);
q = g3[ b11 + bz0 ] ; v = at3(rx1,ry1,rz0);
b = lerp_m(t, u, v);
c = lerp_m(sy, a, b);
q = g3[ b00 + bz1 ] ; u = at3(rx0,ry0,rz1);
q = g3[ b10 + bz1 ] ; v = at3(rx1,ry0,rz1);
a = lerp_m(t, u, v);
q = g3[ b01 + bz1 ] ; u = at3(rx0,ry1,rz1);
q = g3[ b11 + bz1 ] ; v = at3(rx1,ry1,rz1);
b = lerp_m(t, u, v);
d = lerp_m(sy, a, b);
return lerp_m(sz, c, d);
}
*/
static void normalize2(F32 v[2])
{
F32 s;
s = 1.f/(F32)sqrt(v[0] * v[0] + v[1] * v[1]);
v[0] = v[0] * s;
v[1] = v[1] * s;
}
static void normalize3(F32 v[3])
{
F32 s;
s = 1.f/(F32)sqrt(v[0] * v[0] + v[1] * v[1] + v[2] * v[2]);
v[0] = v[0] * s;
v[1] = v[1] * s;
v[2] = v[2] * s;
}
static void init(void)
{
// we want repeatable noise (e.g. for stable terrain texturing), so seed with known value
srand(42);
int i, j, k;
for (i = 0 ; i < B ; i++) {
p[i] = i;
g1[i] = (F32)((rand() % (B + B)) - B) / B;
for (j = 0 ; j < 2 ; j++)
g2[i][j] = (F32)((rand() % (B + B)) - B) / B;
normalize2(g2[i]);
for (j = 0 ; j < 3 ; j++)
g3[i][j] = (F32)((rand() % (B + B)) - B) / B;
normalize3(g3[i]);
}
while (--i) {
k = p[i];
p[i] = p[j = rand() % B];
p[j] = k;
}
for (i = 0 ; i < B + 2 ; i++) {
p[B + i] = p[i];
g1[B + i] = g1[i];
for (j = 0 ; j < 2 ; j++)
g2[B + i][j] = g2[i][j];
for (j = 0 ; j < 3 ; j++)
g3[B + i][j] = g3[i][j];
}
// reintroduce entropy
srand(time(NULL)); // Flawfinder: ignore
}
#undef B
#undef BM
#undef N
#undef NF32
#undef NP
#undef NM
#endif // LL_NOISE_
| 20.02514 | 90 | 0.545125 |
df9db0ca2ec740780d0d48e85906c81642db7eeb | 961 | h | C | main/src/application.h | abdes/asap_app_imgui | 0b33f477ae46ca2c140f463088b6652abe370ea5 | [
"BSD-3-Clause"
] | 70 | 2018-11-21T13:01:57.000Z | 2022-03-17T23:31:00.000Z | main/src/application.h | fromasmtodisasm/asap_app_imgui | 68953de0c24429c15dfd32b97f748e442dc64efb | [
"BSD-3-Clause"
] | 1 | 2018-11-21T15:48:50.000Z | 2018-11-25T15:14:43.000Z | main/src/application.h | fromasmtodisasm/asap_app_imgui | 68953de0c24429c15dfd32b97f748e442dc64efb | [
"BSD-3-Clause"
] | 25 | 2018-12-20T06:54:13.000Z | 2022-03-20T14:55:04.000Z | // Copyright The Authors 2018.
// Distributed under the 3-Clause BSD License.
// (See accompanying file LICENSE or copy at
// https://opensource.org/licenses/BSD-3-Clause)
#pragma once
#include <glad/gl.h>
#include <ui/application_base.h>
class Shader;
namespace asap {
class Application final : public asap::ui::ApplicationBase {
public:
Application() : asap::ui::ApplicationBase() {}
/// Not move constructible
Application(Application &&) = delete;
/// Not move assignable
Application &operator=(Application &&) = delete;
~Application() override = default;
bool Draw() final;
protected:
void AfterInit() override;
void DrawInsideMainMenu() override {}
void DrawInsideStatusBar(float /*width*/, float /*height*/) override {}
void BeforeShutDown() override;
private:
GLuint VBO = 0, VAO = 0;
GLuint frameBuffer_ = 0;
GLuint texColorBuffer_ = 0;
Shader *ourShader_{nullptr};
};
} // namespace asap
| 22.348837 | 73 | 0.691988 |
2acfd62430462bb92a54f071ea2447f2059bd0c1 | 2,156 | h | C | src/platform/platform_macosx.h | swingflip/C64_mini_VICE | 7a6d9d41ae60409a2bb985bb8d6324a7269a0daa | [
"Apache-2.0"
] | 2 | 2018-11-15T19:52:34.000Z | 2022-01-17T19:45:01.000Z | src/platform/platform_macosx.h | Classicmods/C64_mini_VICE | 7a6d9d41ae60409a2bb985bb8d6324a7269a0daa | [
"Apache-2.0"
] | null | null | null | src/platform/platform_macosx.h | Classicmods/C64_mini_VICE | 7a6d9d41ae60409a2bb985bb8d6324a7269a0daa | [
"Apache-2.0"
] | 3 | 2019-06-30T05:37:04.000Z | 2021-12-04T17:12:35.000Z | /*
* platform_macosx.h - Mac OS X Platform detection
*
* Written by
* Christian Vogelgsang <chris@vogelgsang.org>
*
* Based on Code by
* http://www.cocoadev.com/index.pl?DeterminingOSVersion
*
* This file is part of VICE, the Versatile Commodore Emulator.
* See README for copyright notice.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
* 02111-1307 USA.
*
*/
#ifndef VICE_PLATFORM_MACOSX_H
#define VICE_PLATFORM_MACOSX_H
#include "AvailabilityMacros.h"
/* determine compile-time OS */
#ifdef MAC_OS_X_VERSION_10_7
#define PLATFORM_OS "Mac OS X 10.7"
#else
#ifdef MAC_OS_X_VERSION_10_6
#define PLATFORM_OS "Mac OS X 10.6"
#else
#ifdef MAC_OS_X_VERSION_10_5
#define PLATFORM_OS "Mac OS X 10.5"
#else
#ifdef MAC_OS_X_VERSION_10_4
#define PLATFORM_OS "Mac OS X 10.4"
#else
#ifdef MAC_OS_X_VERSION_10_3
#define PLATFORM_OS "Mac OS X 10.3"
#else
#ifdef MAC_OS_X_VERSION_10_2
#define PLATFORM_OS "Mac OS X 10.2"
#else
#ifdef MAC_OS_X_VERSION_10_1
#define PLATFORM_OS "Mac OS X 10.1"
#else
#ifdef MAC_OS_X_VERSION_10_0
#define PLATFORM_OS "Mac OS X 10.0"
#else
#define PLATFORM_OS "Mac OS X"
#endif /* 10.0 */
#endif /* 10.1 */
#endif /* 10.2 */
#endif /* 10.3 */
#endif /* 10.4 */
#endif /* 10.5 */
#endif /* 10.6 */
#endif /* 10.7 */
/* detrmine compile-time CPU */
#ifdef __POWERPC__
# define PLATFORM_CPU "ppc"
#else
# ifdef __x86_64
# define PLATFORM_CPU "x86_64"
# else
# define PLATFORM_CPU "i386"
# endif
#endif
#endif /* VICE_PLATFORM_MACOSX_H */
| 26.292683 | 72 | 0.723098 |
4a2093816c6c2fd97ad8b14d77c83a45dd9ea48d | 251 | h | C | SampleADBalloon/SampleADBalloon/SampleADBalloon/EX_ABInterstitial_ViewController.h | ADballoon/adballoon-ios-sdk | c2828f4c09a5d5bcebbe5895847b62ca953c22da | [
"Apache-2.0"
] | null | null | null | SampleADBalloon/SampleADBalloon/SampleADBalloon/EX_ABInterstitial_ViewController.h | ADballoon/adballoon-ios-sdk | c2828f4c09a5d5bcebbe5895847b62ca953c22da | [
"Apache-2.0"
] | null | null | null | SampleADBalloon/SampleADBalloon/SampleADBalloon/EX_ABInterstitial_ViewController.h | ADballoon/adballoon-ios-sdk | c2828f4c09a5d5bcebbe5895847b62ca953c22da | [
"Apache-2.0"
] | null | null | null | //
// EX_ABInterstitial_ViewController.h
// ADballoonExample
//
// Created by Hang on 5/12/14.
// Copyright (c) 2014 ADballoon. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface EX_ABInterstitial_ViewController : UIViewController
@end
| 17.928571 | 62 | 0.741036 |
4a5ebaa516d76efa4e234286fe66d12b14a1b42c | 602 | h | C | unsorted_include_todo/JPAFieldVortex.h | projectPiki/pikmin2 | a431d992acde856d092889a515ecca0e07a3ea7c | [
"Unlicense"
] | 33 | 2021-12-08T11:10:59.000Z | 2022-03-26T19:59:37.000Z | unsorted_include_todo/JPAFieldVortex.h | projectPiki/pikmin2 | a431d992acde856d092889a515ecca0e07a3ea7c | [
"Unlicense"
] | 6 | 2021-12-22T17:54:31.000Z | 2022-01-07T21:43:18.000Z | unsorted_include_todo/JPAFieldVortex.h | projectPiki/pikmin2 | a431d992acde856d092889a515ecca0e07a3ea7c | [
"Unlicense"
] | 2 | 2022-01-04T06:00:49.000Z | 2022-01-26T07:27:28.000Z | #ifndef _JPAFIELDVORTEX_H
#define _JPAFIELDVORTEX_H
/*
__vt__14JPAFieldVortex:
.4byte 0
.4byte 0
.4byte __dt__14JPAFieldVortexFv
.4byte prepare__14JPAFieldVortexFP18JPAEmitterWorkDataP13JPAFieldBlock
.4byte
calc__14JPAFieldVortexFP18JPAEmitterWorkDataP13JPAFieldBlockP15JPABaseParticle
*/
struct JPAFieldVortex {
virtual ~JPAFieldVortex(); // _00
virtual void prepare(JPAEmitterWorkData*, JPAFieldBlock*); // _04
virtual void calc(JPAEmitterWorkData*, JPAFieldBlock*,
JPABaseParticle*); // _08
// _00 VTBL
};
#endif
| 25.083333 | 81 | 0.717608 |
048b8501846e5878bd4e308e01667e112f940f88 | 3,388 | c | C | file_operations/file_operations_toolkit.c | straceX/cprogrammingtoolkit | 20434348731800da0289757880aa13e395c76068 | [
"Apache-2.0"
] | null | null | null | file_operations/file_operations_toolkit.c | straceX/cprogrammingtoolkit | 20434348731800da0289757880aa13e395c76068 | [
"Apache-2.0"
] | null | null | null | file_operations/file_operations_toolkit.c | straceX/cprogrammingtoolkit | 20434348731800da0289757880aa13e395c76068 | [
"Apache-2.0"
] | null | null | null |
#ifdef OS_WINDOWS
#else
stream_info *learn_buffer_inf(FILE *fp)
{
stream_info *si = NULL;
if( !(si = (stream_info *) malloc(sizeof(stream_info)) ) )
return NULL;
else
{
if (fp->_flags & _IONBF)
si->buff_type = "Unbuffered";
else if (fp->_flags & _IOLBF)
si->buff_type = "Line buffered";
else
si->buff_type = "Fully buffered";
si->buff_size = __fbufsize(fp);
return si;
}
}
void getAllFilesList(const char *path)
{
struct stat fd;
struct dirent *ent;
DIR *dir;
if (chdir(path) < 0)
return;
if ((dir = opendir(".")) == NULL)
{
chdir("..");
return;
}
while ((ent = readdir(dir)) != NULL)
{
if (!strcmp(ent->d_name, ".") || !strcmp(ent->d_name, ".."))
continue;
if(ent->d_type != DT_DIR)
printf("%s\n", ent->d_name);
if (stat(ent->d_name, &fd) < 0)
goto EXIT;
if (S_ISDIR(fd.st_mode))
getAllFiles(ent->d_name);
}
EXIT:
closedir(dir);
chdir("..");
return;
}
#endif
int merge_file(const char *ofilename,const size_t filecount,const char **files,unsigned long ofsize)
{
if(!strlen(ofilename))
{
fprintf(stderr, "invalid output filename\n");
return -1;
}
size_t iter;
size_t n;
FILE *fdest;
FILE *fsource;
char buf[BLOCK_SIZE];
long size, leftSize;
char *zeroBlock;
if ((fdest = fopen(ofilename, "wb")) == NULL)
{
fprintf(stderr, "cannot open file: %s\n", ofilename);
return -1;
}
for (iter = 0; iter < filecount; ++iter)
{
if ((fsource = fopen(files[iter], "rb")) == NULL)
{
fprintf(stderr, "cannot open file: %s\n", files[iter]);
exit(EXIT_FAILURE);
}
while ((n = fread(buf, 1, BLOCK_SIZE, fsource)) > 0)
{
if (!fwrite(buf, 1, n, fdest))
{
fprintf(stderr, "cannot write file!\n");
return -1;
}
if (ferror(fsource))
{
fprintf(stderr, "cannot read file!\n");
return -1;
}
fclose(fsource);
}
}
size = ftell(fdest);
if(ofsize)
{
if(size > ofsize)
{
fprintf(stderr, "output file size is wrong!\n");
fclose(fdest);
return -1;
}
leftSize = ofsize - size;
if ((zeroBlock = (char *) calloc(BLOCK_SIZE, 1)) == NULL) {
fprintf(stderr, "cannot allocate mmeory!\n");
return -1;
}
while (leftSize > 0) {
if (!fwrite(zeroBlock, 1, leftSize >= BLOCK_SIZE ? BLOCK_SIZE : leftSize, fdest)) {
fprintf(stderr, "cannot write file!\n");
return -1;
}
leftSize -= BLOCK_SIZE;
}
}
fclose(fdest);
return 0;
}
char *extractFileContents(const char *filePath,char *dest)
{
FILE *file = fopen(filePath, "r");
int iter = 0;
char c;
if(file != NULL)
{
while((c = fgetc(file)) != EOF) {
dest[iter++] = (char) c;
}
dest[iter] = '\0';
fclose(file);
}
return dest;
}
| 19.697674 | 100 | 0.471074 |
cc6a20b678758b2fc65a21a1491b697cf11297c6 | 7,063 | c | C | base/boot/lib/i386/input.c | npocmaka/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 17 | 2020-11-13T13:42:52.000Z | 2021-09-16T09:13:13.000Z | base/boot/lib/i386/input.c | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 2 | 2020-10-19T08:02:06.000Z | 2020-10-19T08:23:18.000Z | base/boot/lib/i386/input.c | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 14 | 2020-11-14T09:43:20.000Z | 2021-08-28T08:59:57.000Z | /*++
Copyright (c) 1997 Microsoft Corporation
Module Name:
input.c
Author:
Ken Reneris Oct-2-1997
Abstract:
--*/
#include "bootx86.h"
#include "displayp.h"
#include "stdio.h"
//
// Takes any pending input and converts it into a KEY value. Non-blocking, returning 0 if no input available.
//
ULONG
BlGetKey()
{
ULONG Key = 0;
UCHAR Ch;
ULONG Count;
if (ArcGetReadStatus(BlConsoleInDeviceId) == ESUCCESS) {
ArcRead(BlConsoleInDeviceId, &Ch, sizeof(Ch), &Count);
if (Ch == ASCI_CSI_IN) {
if (ArcGetReadStatus(BlConsoleInDeviceId) == ESUCCESS) {
ArcRead(BlConsoleInDeviceId, &Ch, sizeof(Ch), &Count);
//
// All the function keys start with ESC-O
//
switch (Ch) {
case 'O':
ArcRead(BlConsoleInDeviceId, &Ch, sizeof(Ch), &Count); // will not or block, as the buffer is already filled
switch (Ch) {
case 'P':
Key = F1_KEY;
break;
case 'Q':
Key = F2_KEY;
break;
case 'w':
Key = F3_KEY;
break;
case 'x':
Key = F4_KEY;
break;
case 't':
Key = F5_KEY;
break;
case 'u':
Key = F6_KEY;
break;
case 'r':
Key = F8_KEY;
break;
case 'M':
Key = F10_KEY;
break;
case 'A':
Key = F11_KEY;
break;
case 'B':
Key = F12_KEY;
break;
}
break;
case 'A':
Key = UP_ARROW;
break;
case 'B':
Key = DOWN_ARROW;
break;
case 'C':
Key = RIGHT_KEY;
break;
case 'D':
Key = LEFT_KEY;
break;
case 'H':
Key = HOME_KEY;
break;
case 'K':
Key = END_KEY;
break;
case '@':
Key = INS_KEY;
break;
case 'P':
Key = DEL_KEY;
break;
case TAB_KEY:
Key = BACKTAB_KEY;
break;
}
} else { // Single escape key, as no input is waiting.
Key = ESCAPE_KEY;
}
} else if (Ch == 0x8) {
Key = BKSP_KEY;
} else {
Key = (ULONG)Ch;
}
}
return Key;
}
VOID
BlInputString(
IN ULONG Prompt,
IN ULONG CursorX,
IN ULONG PosY,
IN PUCHAR String,
IN ULONG MaxLength
)
{
PTCHAR PromptString;
ULONG TextX, TextY;
ULONG Length, Index;
UCHAR CursorChar[2];
ULONG Key;
PUCHAR p;
ULONG i;
ULONG Count;
PromptString = BlFindMessage(Prompt);
Length = strlen((PCHAR)String);
CursorChar[1] = 0;
//
// Print prompt
//
ARC_DISPLAY_POSITION_CURSOR(CursorX, PosY);
ArcWrite(BlConsoleOutDeviceId, PromptString, _tcslen(PromptString), &Count);
//
// Indent cursor to right of prompt
//
CursorX += _tcslen(PromptString);
TextX = CursorX;
Key = 0;
for (; ;) {
TextY = TextX + Length;
if (CursorX > TextY) {
CursorX = TextY;
}
if (CursorX < TextX) {
CursorX = TextX;
}
Index = CursorX - TextX;
String[Length] = 0;
//
// Display current string
//
ARC_DISPLAY_POSITION_CURSOR(TextX, PosY);
ArcWrite(BlConsoleOutDeviceId, String, strlen((PCHAR)String), &Count);
ArcWrite(BlConsoleOutDeviceId, " ", sizeof(" "), &Count);
if (Key == 0x0d) { // enter key?
break ;
}
//
// Display cursor
//
ARC_DISPLAY_POSITION_CURSOR(CursorX, PosY);
ARC_DISPLAY_INVERSE_VIDEO();
CursorChar[0] = String[Index] ? String[Index] : ' ';
ArcWrite(BlConsoleOutDeviceId, CursorChar, sizeof(UCHAR), &Count);
ARC_DISPLAY_ATTRIBUTES_OFF();
ARC_DISPLAY_POSITION_CURSOR(CursorX, PosY);
//
// Get key and process it
//
while ((Key = BlGetKey()) == 0) {
}
switch (Key) {
case HOME_KEY:
CursorX = TextX;
break;
case END_KEY:
CursorX = TextY;
break;
case LEFT_KEY:
CursorX -= 1;
break;
case RIGHT_KEY:
CursorX += 1;
break;
case BKSP_KEY:
if (!Index) {
break;
}
CursorX -= 1;
String[Index-1] = CursorChar[0];
// fallthough to DEL_KEY
case DEL_KEY:
if (Length) {
p = String+Index;
i = Length-Index+1;
while (i) {
p[0] = p[1];
p += 1;
i -= 1;
}
Length -= 1;
}
break;
case INS_KEY:
if (Length < MaxLength) {
p = String+Length;
i = Length-Index+1;
while (i) {
p[1] = p[0];
p -= 1;
i -= 1;
}
String[Index] = ' ';
Length += 1;
}
break;
default:
Key = Key & 0xff;
if (Key >= ' ' && Key <= 'z') {
if (CursorX == TextY && Length < MaxLength) {
Length += 1;
}
String[Index] = (UCHAR)Key;
String[MaxLength] = 0;
CursorX += 1;
}
break;
}
}
}
| 23.701342 | 130 | 0.352117 |
288348d96dc15b0419c7220327c9080f6a80964f | 4,984 | h | C | 2-eciot-agentlite-oceanconnect/miniprojects/include/hw_errcode.h | softbaddog/iot-codelabs | 36b7b4b3d35949e0223bf4e4d92d7995fcc832c9 | [
"MIT"
] | 28 | 2017-07-17T14:25:27.000Z | 2020-05-10T00:12:51.000Z | 2-eciot-agentlite-oceanconnect/miniprojects/include/hw_errcode.h | softbaddog/iot-codelabs | 36b7b4b3d35949e0223bf4e4d92d7995fcc832c9 | [
"MIT"
] | null | null | null | 2-eciot-agentlite-oceanconnect/miniprojects/include/hw_errcode.h | softbaddog/iot-codelabs | 36b7b4b3d35949e0223bf4e4d92d7995fcc832c9 | [
"MIT"
] | 35 | 2017-07-18T13:34:43.000Z | 2019-11-29T03:36:48.000Z | /**
* @file hw_errcode.h
*/
#ifndef _HW_ERRCODE_H_
#define _HW_ERRCODE_H_
#ifdef __cplusplus
extern "C" {
#endif
#define HW_OK 0 /**< Indicates ok */
#define HW_ERR 1 /**< Indicates err */
#define HW_ERR_PTR 2 /**< Indicates error ptr */
#define HW_ERR_ID 3 /**< Indicates error id */
#define HW_ERR_PARA 4 /**< Indicates error para */
#define HW_ERR_KEY 5 /**< Indicates error key */
#define HW_ERR_NOMEM 6 /**< Indicates no mem*/
#define HW_ERR_MAGIC 7 /**< Indicates error magic*/
#define HW_ERR_OVERFLOW 8 /**< Indicates overflow */
#define HW_ERR_GVAR 9 /**< Indicates error gvar*/
#define HW_ERR_POOL 10 /**< Indicates error pool*/
#define HW_ERR_NO_MUTEX 11 /**< Indicates no mutex */
#define HW_ERR_PID 12 /**< Indicates error pid*/
#define HW_ERR_FILEOPEN 13 /**< Indicates open file failed */
#define HW_ERR_FD 14 /**< Indicates file descriptor err*/
#define HW_ERR_SOCKET 15 /**< Indicates socket err*/
#define HW_ERR_NOTSUPPORT 16 /**< Indicates not support*/
#define HW_ERR_NOTLOAD 17 /**< Indicates not load*/
#define HW_ERR_ENCODE 18 /**< Indicates encode err*/
#define HW_ERR_DECODE 19 /**< Indicates decode err*/
#define HW_ERR_CALLBACK 22 /**< Indicates callback err*/
#define HW_ERR_STATE 23 /**< Indicates state err*/
#define HW_ERR_OVERTIMES 24 /**< Indicates retry overtimes*/
#define HW_ERR_ENDOVER 25 /**< reserved*/
#define HW_ERR_ENDLINE 26 /**< reserved*/
#define HW_ERR_NUMBER 27 /**< Indicates error number*/
#define HW_ERR_NOMATCH 28 /**< Indicates not match*/
#define HW_ERR_NOSTART 29 /**< Indicates not start*/
#define HW_ERR_NOEND 30 /**< Indicates not end*/
#define HW_ERR_OVERLAP 31 /**< reserved*/
#define HW_ERR_DROP 32 /**< Indicates drop*/
#define HW_ERR_NODATA 33 /**< Indicates nodata*/
#define HW_ERR_CRC_CHK 34 /**< Indicates crc check failed*/
#define HW_ERR_AUTH 35 /**< Indicates authentication failed*/
#define HW_ERR_LENGTH 36 /**< Indicates invalid length*/
#define HW_ERR_NOTALLOW 37 /**< Indicates Not allowed to operate*/
#define HW_ERR_TOKEN 38 /**< Indicates token err*/
#define HW_ERR_NOTIPV4 39 /**< Indicates not support IPV4*/
#define HW_ERR_NOTIPV6 40 /**< Indicates not support IPV6*/
#define HW_ERR_IELOST 41 /**< reserved*/
#define HW_ERR_IELOST1 42 /**< reserved*/
#define HW_ERR_IELOST2 43 /**< reserved*/
#define HW_ERR_AUDIO 44 /**< reserved*/
#define HW_ERR_VIDEO 45 /**< reserved*/
#define HW_ERR_MD5 46 /**< reserved*/
#define HW_ERR_MD5_HA1 47 /**< reserved*/
#define HW_ERR_MD5_RES 48 /**< reserved*/
#define HW_ERR_DIALOG 49 /**< Indicates error dialog*/
#define HW_ERR_OBJ 50 /**< Indicates error object*/
#ifdef __cplusplus
}
#endif
#endif
| 76.676923 | 116 | 0.381421 |
931a44c7a33efdcc77118910a84a309aca0d6459 | 1,342 | h | C | src/hooks.h | zahidaliayub/emercoin-EMC | feb048e19e31886259f75347968f164bc702bc33 | [
"MIT"
] | 34 | 2015-01-18T22:55:52.000Z | 2020-09-11T13:23:12.000Z | src/hooks.h | zahidaliayub/emercoin-EMC | feb048e19e31886259f75347968f164bc702bc33 | [
"MIT"
] | 7 | 2015-03-21T09:04:41.000Z | 2016-07-24T04:19:36.000Z | src/hooks.h | zahidaliayub/emercoin-EMC | feb048e19e31886259f75347968f164bc702bc33 | [
"MIT"
] | 14 | 2015-05-10T09:59:02.000Z | 2020-08-18T11:25:10.000Z | // Copyright (c) 2010-2011 Vincent Durham
// Distributed under the MIT/X11 software license, see the accompanying
// file license.txt or http://www.opensource.org/licenses/mit-license.php.
#ifndef BITCOIN_HOOKS_H
#define BITCOIN_HOOKS_H
class CScript;
class CTransaction;
class CBlockIndex;
class CTxOut;
struct nameTempProxy;
#include <map>
#include <vector>
#include <string>
using namespace std;
class CHooks
{
public:
virtual bool IsNameFeeEnough(const CTransaction& tx, const CAmount& txFee) = 0;
virtual bool CheckInputs(const CTransaction& tx, const CBlockIndex* pindexBlock, std::vector<nameTempProxy> &vName, const CDiskTxPos& pos, const CAmount& txFee) = 0;
virtual bool DisconnectInputs(const CTransaction& tx) = 0;
virtual bool ConnectBlock(CBlockIndex* pindex, const std::vector<nameTempProxy> &vName) = 0;
virtual bool ExtractAddress(const CScript& script, std::string& address) = 0;
virtual void AddToPendingNames(const CTransaction& tx) = 0;
virtual bool RemoveNameScriptPrefix(const CScript& scriptIn, CScript& scriptOut) = 0;
virtual bool IsNameScript(CScript scr) = 0;
virtual bool getNameValue(const string& sName, string& sValue) = 0;
virtual bool DumpToTextFile() = 0;
};
extern CHooks* InitHook();
extern std::string GetDefaultDataDirSuffix();
extern CHooks* hooks;
#endif
| 34.410256 | 169 | 0.757824 |
d1fca30fd712f8eca3cf4658fc9e6175e9e17a3c | 1,803 | h | C | Applications/Podcasts/MTSetPlaybackQueueUtil.h | lechium/tvOS124Headers | 11d1b56dd4c0ffd88b9eac43f87a5fd6f7228475 | [
"MIT"
] | 4 | 2019-08-27T18:03:47.000Z | 2021-09-18T06:29:00.000Z | Applications/Podcasts/MTSetPlaybackQueueUtil.h | lechium/tvOS124Headers | 11d1b56dd4c0ffd88b9eac43f87a5fd6f7228475 | [
"MIT"
] | null | null | null | Applications/Podcasts/MTSetPlaybackQueueUtil.h | lechium/tvOS124Headers | 11d1b56dd4c0ffd88b9eac43f87a5fd6f7228475 | [
"MIT"
] | null | null | null | //
// Generated by class-dump 3.5 (64 bit).
//
// class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2013 by Steve Nygard.
//
#import "NSObject.h"
@interface MTSetPlaybackQueueUtil : NSObject
{
}
+ (long long)_automaticCommandStatusForRequestStatus:(long long)arg1; // IMP=0x0000000100087a00
+ (_Bool)_setPlaybackQueueForPodcastAdamId:(id)arg1 siriAssetInfo:(id)arg2 playbackOrder:(long long)arg3 startPlayback:(_Bool)arg4 reason:(unsigned long long)arg5 interactive:(_Bool)arg6 enqueuedByAnotherUser:(_Bool)arg7 completion:(CDUnknownBlockType)arg8; // IMP=0x00000001000874d0
+ (_Bool)_setManifest:(id)arg1 queueType:(long long)arg2 startPlayback:(_Bool)arg3 forceLocal:(_Bool)arg4 reason:(unsigned long long)arg5 interactive:(_Bool)arg6 completion:(CDUnknownBlockType)arg7; // IMP=0x0000000100087384
+ (_Bool)_setPlaybackQueueForMyPodcastsWithOrder:(long long)arg1 startPlayback:(_Bool)arg2 forceLocal:(_Bool)arg3 reason:(unsigned long long)arg4 interactive:(_Bool)arg5 completion:(CDUnknownBlockType)arg6; // IMP=0x00000001000870d8
+ (long long)subscribeCommandStatusForErrorCode:(long long)arg1; // IMP=0x00000001000870b8
+ (long long)queueCommandStatusForRequestStatus:(long long)arg1 queueType:(long long)arg2; // IMP=0x0000000100087098
+ (_Bool)setAutoResumePlaybackQueueAndStartPlayback:(_Bool)arg1 forceLocal:(_Bool)arg2 reason:(unsigned long long)arg3 interactive:(_Bool)arg4 completion:(CDUnknownBlockType)arg5; // IMP=0x0000000100087070
+ (_Bool)subscribeWithCommandURL:(id)arg1 siriAssetInfo:(id)arg2 completion:(CDUnknownBlockType)arg3; // IMP=0x0000000100086c8c
+ (_Bool)setPlaybackQueueForRequest:(id)arg1 siriAssetInfo:(id)arg2 enqueuerDSID:(id)arg3 startPlayback:(_Bool)arg4 isMagicMoment:(_Bool)arg5 completion:(CDUnknownBlockType)arg6; // IMP=0x0000000100085fc0
@end
| 72.12 | 283 | 0.811425 |
3073c52108ed1a80672074521df61d7b84820b9d | 1,899 | h | C | eftl-c-sdk/src/msg.h | TIBCOSoftware/TIBCO-Messaging | 9dba9178e69fc97665436534d57511b8740c132b | [
"BSD-3-Clause"
] | 11 | 2018-06-08T19:58:17.000Z | 2021-11-18T09:28:46.000Z | eftl-c-sdk/src/msg.h | TIBCOSoftware/TIBCO-Messaging | 9dba9178e69fc97665436534d57511b8740c132b | [
"BSD-3-Clause"
] | 8 | 2019-06-18T23:49:51.000Z | 2020-11-10T01:06:38.000Z | eftl-c-sdk/src/msg.h | TIBCOSoftware/TIBCO-Messaging | 9dba9178e69fc97665436534d57511b8740c132b | [
"BSD-3-Clause"
] | 4 | 2019-04-22T21:06:37.000Z | 2021-02-04T07:47:16.000Z | /*
* Copyright (c) 2021 TIBCO Software Inc.
* Licensed under a BSD-style license. Refer to [LICENSE]
* For more information, please contact:
* TIBCO Software Inc., Palo Alto, California, USA
*
* $Id: msg.h 128828 2020-09-25 15:29:03Z $
*
*/
#ifndef INCLUDED_TIBEFTL_MSG_H
#define INCLUDED_TIBEFTL_MSG_H
#include "cJSON.h"
typedef struct tibeftlMessageListStruct
tibeftlMessageListRec,
*tibeftlMessageList;
tibeftlMessageList
tibeftlMessageList_Create(void);
void
tibeftlMessageList_Destroy(
tibeftlMessageList list);
void
tibeftlMessageList_Close(
tibeftlMessageList list);
bool
tibeftlMessageList_Add(
tibeftlMessageList list,
tibeftlMessage message);
tibeftlMessage
tibeftlMessageList_Next(
tibeftlMessageList list);
tibeftlMessage
tibeftlMessage_CreateWithJSON(
_cJSON* json);
_cJSON*
tibeftlMessage_GetJSON(
tibeftlMessage message);
void
tibeftlMessage_SetReceipt(
tibeftlMessage message,
int64_t seqNum,
const char* subId);
void
tibeftlMessage_GetReceipt(
tibeftlMessage message,
int64_t* seqNum,
const char** subId);
void
tibeftlMessage_SetReplyTo(
tibeftlMessage message,
const char* replyTo,
int64_t reqId);
void
tibeftlMessage_GetReplyTo(
tibeftlMessage message,
const char** replyTo,
int64_t* reqId);
void
tibeftlMessage_SetStoreMessageId(
tibeftlMessage message,
int64_t msgId);
void
tibeftlMessage_SetDeliveryCount(
tibeftlMessage message,
int64_t deliveryCount);
#endif /* INCLUDED_TIBEFTL_MSG_H */
| 22.879518 | 57 | 0.61822 |
ca64e0ac5d9d5878a21962c7961fb7cdabd26e25 | 4,548 | h | C | src/sysc/scc/observer.h | minres/SC-Snippets | 7bbef20f1d1dcb2404e4d9ad48029bd04cfc5c20 | [
"Apache-2.0"
] | null | null | null | src/sysc/scc/observer.h | minres/SC-Snippets | 7bbef20f1d1dcb2404e4d9ad48029bd04cfc5c20 | [
"Apache-2.0"
] | null | null | null | src/sysc/scc/observer.h | minres/SC-Snippets | 7bbef20f1d1dcb2404e4d9ad48029bd04cfc5c20 | [
"Apache-2.0"
] | null | null | null | /*******************************************************************************
* Copyright 2018-2021 MINRES Technologies GmbH
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
#ifndef _SCC_OBSERVER_H_
#define _SCC_OBSERVER_H_
#include <string>
//needed for typedefs like sc_dt::int64
#include "sysc/datatypes/int/sc_nbdefs.h"
// Some forward declarations
namespace sc_dt {
class sc_bit;
class sc_logic;
class sc_bv_base;
class sc_lv_base;
class sc_signed;
class sc_unsigned;
class sc_int_base;
class sc_uint_base;
class sc_fxval;
class sc_fxval_fast;
class sc_fxnum;
class sc_fxnum_fast;
}
namespace scc {
/**
* @brief The interface defining an observer.
*/
struct observer {
/**
* @brief A handle to be used be the observed object to notify the observer about a change
*/
struct notification_handle{
virtual void notify() = 0;
virtual ~notification_handle(){}
};
#define DECL_REGISTER_METHOD_A(tp) virtual notification_handle* observe(tp const& o, std::string const& nm) = 0;
#define DECL_REGISTER_METHOD_B(tp) virtual notification_handle* observe(tp const& o, std::string const& nm, int width) = 0;
DECL_REGISTER_METHOD_A( bool )
DECL_REGISTER_METHOD_A( sc_dt::sc_bit )
DECL_REGISTER_METHOD_A( sc_dt::sc_logic )
DECL_REGISTER_METHOD_B( unsigned char )
DECL_REGISTER_METHOD_B( unsigned short )
DECL_REGISTER_METHOD_B( unsigned int )
DECL_REGISTER_METHOD_B( unsigned long )
DECL_REGISTER_METHOD_B( char )
DECL_REGISTER_METHOD_B( short )
DECL_REGISTER_METHOD_B( int )
DECL_REGISTER_METHOD_B( long )
DECL_REGISTER_METHOD_B( sc_dt::int64 )
DECL_REGISTER_METHOD_B( sc_dt::uint64 )
DECL_REGISTER_METHOD_A( float )
DECL_REGISTER_METHOD_A( double )
DECL_REGISTER_METHOD_A( sc_dt::sc_int_base )
DECL_REGISTER_METHOD_A( sc_dt::sc_uint_base )
DECL_REGISTER_METHOD_A( sc_dt::sc_signed )
DECL_REGISTER_METHOD_A( sc_dt::sc_unsigned )
DECL_REGISTER_METHOD_A( sc_dt::sc_fxval )
DECL_REGISTER_METHOD_A( sc_dt::sc_fxval_fast )
DECL_REGISTER_METHOD_A( sc_dt::sc_fxnum )
DECL_REGISTER_METHOD_A( sc_dt::sc_fxnum_fast )
DECL_REGISTER_METHOD_A( sc_dt::sc_bv_base )
DECL_REGISTER_METHOD_A( sc_dt::sc_lv_base )
#undef DECL_REGISTER_METHOD_A
#undef DECL_REGISTER_METHOD_B
virtual ~observer(){}
};
#define DECL_REGISTER_METHOD_A(tp) inline observer::notification_handle* observe(observer* obs, tp const& o, std::string const& nm){\
return obs->observe(o, nm); }
#define DECL_REGISTER_METHOD_B(tp) inline observer::notification_handle* observe(observer* obs, tp const& o, std::string const& nm, int width = 8 * sizeof( tp )){\
return obs->observe(o, nm, width); }
DECL_REGISTER_METHOD_A( bool )
DECL_REGISTER_METHOD_A( sc_dt::sc_bit )
DECL_REGISTER_METHOD_A( sc_dt::sc_logic )
DECL_REGISTER_METHOD_B( unsigned char )
DECL_REGISTER_METHOD_B( unsigned short )
DECL_REGISTER_METHOD_B( unsigned int )
DECL_REGISTER_METHOD_B( unsigned long )
DECL_REGISTER_METHOD_B( char )
DECL_REGISTER_METHOD_B( short )
DECL_REGISTER_METHOD_B( int )
DECL_REGISTER_METHOD_B( long )
DECL_REGISTER_METHOD_B( sc_dt::int64 )
DECL_REGISTER_METHOD_B( sc_dt::uint64 )
DECL_REGISTER_METHOD_A( float )
DECL_REGISTER_METHOD_A( double )
DECL_REGISTER_METHOD_A( sc_dt::sc_int_base )
DECL_REGISTER_METHOD_A( sc_dt::sc_uint_base )
DECL_REGISTER_METHOD_A( sc_dt::sc_signed )
DECL_REGISTER_METHOD_A( sc_dt::sc_unsigned )
DECL_REGISTER_METHOD_A( sc_dt::sc_fxval )
DECL_REGISTER_METHOD_A( sc_dt::sc_fxval_fast )
DECL_REGISTER_METHOD_A( sc_dt::sc_fxnum )
DECL_REGISTER_METHOD_A( sc_dt::sc_fxnum_fast )
DECL_REGISTER_METHOD_A( sc_dt::sc_bv_base )
DECL_REGISTER_METHOD_A( sc_dt::sc_lv_base )
#undef DECL_REGISTER_METHOD_A
#undef DECL_REGISTER_METHOD_B
} /* namespace scc */
#endif /* _SCC_OBSERVER_H_ */
| 34.454545 | 163 | 0.716799 |
aa86a735f7ece988cc2dd4f16247159e08001448 | 423 | h | C | Source/FSD/Public/ResourceReward.h | Dr-Turtle/DRG_ModPresetManager | abd7ff98a820969504491a1fe68cf2f9302410dc | [
"MIT"
] | 8 | 2021-07-10T20:06:05.000Z | 2022-03-04T19:03:50.000Z | Source/FSD/Public/ResourceReward.h | Dr-Turtle/DRG_ModPresetManager | abd7ff98a820969504491a1fe68cf2f9302410dc | [
"MIT"
] | 9 | 2022-01-13T20:49:44.000Z | 2022-03-27T22:56:48.000Z | Source/FSD/Public/ResourceReward.h | Dr-Turtle/DRG_ModPresetManager | abd7ff98a820969504491a1fe68cf2f9302410dc | [
"MIT"
] | 2 | 2021-07-10T20:05:42.000Z | 2022-03-14T17:05:35.000Z | #pragma once
#include "CoreMinimal.h"
#include "Reward.h"
#include "ResourceReward.generated.h"
class UResourceData;
UCLASS(BlueprintType, EditInlineNew)
class UResourceReward : public UReward {
GENERATED_BODY()
public:
protected:
UPROPERTY(BlueprintReadOnly, EditAnywhere)
UResourceData* Resource;
UPROPERTY(BlueprintReadOnly, EditAnywhere)
int32 Amount;
public:
UResourceReward();
};
| 18.391304 | 46 | 0.744681 |
801f93794768785079852c82462cde35168e0a20 | 27,657 | h | C | lib/Headers/veintrin2.h | SXAuroraTSUBASAResearch/clang | 80201efedf1a82bf4a411e3688e84bf8bc401dbd | [
"Apache-2.0"
] | 1 | 2018-07-11T07:58:56.000Z | 2018-07-11T07:58:56.000Z | lib/Headers/veintrin2.h | sx-aurora-dev/clang | 80201efedf1a82bf4a411e3688e84bf8bc401dbd | [
"Apache-2.0"
] | 1 | 2019-01-16T05:22:21.000Z | 2019-01-16T05:22:21.000Z | lib/Headers/veintrin2.h | sx-aurora-dev/clang | 80201efedf1a82bf4a411e3688e84bf8bc401dbd | [
"Apache-2.0"
] | 2 | 2018-07-11T10:15:30.000Z | 2019-01-15T13:51:00.000Z | #define _ve_vld_vss __builtin_ve_vld_vss
#define _ve_vldu_vss __builtin_ve_vldu_vss
#define _ve_vldlsx_vss __builtin_ve_vldlsx_vss
#define _ve_vldlzx_vss __builtin_ve_vldlzx_vss
#define _ve_vld2d_vss __builtin_ve_vld2d_vss
#define _ve_vldu2d_vss __builtin_ve_vldu2d_vss
#define _ve_vldl2dsx_vss __builtin_ve_vldl2dsx_vss
#define _ve_vldl2dzx_vss __builtin_ve_vldl2dzx_vss
#define _ve_vst_vss __builtin_ve_vst_vss
#define _ve_vstot_vss __builtin_ve_vstot_vss
#define _ve_vstu_vss __builtin_ve_vstu_vss
#define _ve_vstuot_vss __builtin_ve_vstuot_vss
#define _ve_vstl_vss __builtin_ve_vstl_vss
#define _ve_vstlot_vss __builtin_ve_vstlot_vss
#define _ve_vst2d_vss __builtin_ve_vst2d_vss
#define _ve_vst2dot_vss __builtin_ve_vst2dot_vss
#define _ve_vstu2d_vss __builtin_ve_vstu2d_vss
#define _ve_vstu2dot_vss __builtin_ve_vstu2dot_vss
#define _ve_vstl2d_vss __builtin_ve_vstl2d_vss
#define _ve_vstl2dot_vss __builtin_ve_vstl2dot_vss
#define _ve_pfchv_ss __builtin_ve_pfchv_ss
#define _ve_lsv_vvss __builtin_ve_lsv_vvss
#define _ve_lvs_svs_u64 __builtin_ve_lvs_svs_u64
#define _ve_lvs_svs_f64 __builtin_ve_lvs_svs_f64
#define _ve_lvs_svs_f32 __builtin_ve_lvs_svs_f32
#define _ve_lvm_mmss __builtin_ve_lvm_mmss
#define _ve_lvm_MMss __builtin_ve_lvm_MMss
#define _ve_svm_sms __builtin_ve_svm_sms
#define _ve_svm_sMs __builtin_ve_svm_sMs
#define _ve_vbrd_vs_f64 __builtin_ve_vbrd_vs_f64
#define _ve_vbrd_vsmv_f64 __builtin_ve_vbrd_vsmv_f64
#define _ve_vbrd_vs_i64 __builtin_ve_vbrd_vs_i64
#define _ve_vbrd_vsmv_i64 __builtin_ve_vbrd_vsmv_i64
#define _ve_vbrdu_vs_f32 __builtin_ve_vbrdu_vs_f32
#define _ve_vbrdu_vsmv_f32 __builtin_ve_vbrdu_vsmv_f32
#define _ve_vbrdl_vs_i32 __builtin_ve_vbrdl_vs_i32
#define _ve_vbrdl_vsmv_i32 __builtin_ve_vbrdl_vsmv_i32
#define _ve_pvbrd_vs_i64 __builtin_ve_pvbrd_vs_i64
#define _ve_pvbrd_vsMv_i64 __builtin_ve_pvbrd_vsMv_i64
#define _ve_vmv_vsv __builtin_ve_vmv_vsv
#define _ve_vaddul_vvv __builtin_ve_vaddul_vvv
#define _ve_vaddul_vsv __builtin_ve_vaddul_vsv
#define _ve_vaddul_vvvmv __builtin_ve_vaddul_vvvmv
#define _ve_vaddul_vsvmv __builtin_ve_vaddul_vsvmv
#define _ve_vadduw_vvv __builtin_ve_vadduw_vvv
#define _ve_vadduw_vsv __builtin_ve_vadduw_vsv
#define _ve_vadduw_vvvmv __builtin_ve_vadduw_vvvmv
#define _ve_vadduw_vsvmv __builtin_ve_vadduw_vsvmv
#define _ve_pvaddu_vvv __builtin_ve_pvaddu_vvv
#define _ve_pvaddu_vsv __builtin_ve_pvaddu_vsv
#define _ve_pvaddu_vvvMv __builtin_ve_pvaddu_vvvMv
#define _ve_pvaddu_vsvMv __builtin_ve_pvaddu_vsvMv
#define _ve_vaddswsx_vvv __builtin_ve_vaddswsx_vvv
#define _ve_vaddswsx_vsv __builtin_ve_vaddswsx_vsv
#define _ve_vaddswsx_vvvmv __builtin_ve_vaddswsx_vvvmv
#define _ve_vaddswsx_vsvmv __builtin_ve_vaddswsx_vsvmv
#define _ve_vaddswzx_vvv __builtin_ve_vaddswzx_vvv
#define _ve_vaddswzx_vsv __builtin_ve_vaddswzx_vsv
#define _ve_vaddswzx_vvvmv __builtin_ve_vaddswzx_vvvmv
#define _ve_vaddswzx_vsvmv __builtin_ve_vaddswzx_vsvmv
#define _ve_pvadds_vvv __builtin_ve_pvadds_vvv
#define _ve_pvadds_vsv __builtin_ve_pvadds_vsv
#define _ve_pvadds_vvvMv __builtin_ve_pvadds_vvvMv
#define _ve_pvadds_vsvMv __builtin_ve_pvadds_vsvMv
#define _ve_vaddsl_vvv __builtin_ve_vaddsl_vvv
#define _ve_vaddsl_vsv __builtin_ve_vaddsl_vsv
#define _ve_vaddsl_vvvmv __builtin_ve_vaddsl_vvvmv
#define _ve_vaddsl_vsvmv __builtin_ve_vaddsl_vsvmv
#define _ve_vsubul_vvv __builtin_ve_vsubul_vvv
#define _ve_vsubul_vsv __builtin_ve_vsubul_vsv
#define _ve_vsubul_vvvmv __builtin_ve_vsubul_vvvmv
#define _ve_vsubul_vsvmv __builtin_ve_vsubul_vsvmv
#define _ve_vsubuw_vvv __builtin_ve_vsubuw_vvv
#define _ve_vsubuw_vsv __builtin_ve_vsubuw_vsv
#define _ve_vsubuw_vvvmv __builtin_ve_vsubuw_vvvmv
#define _ve_vsubuw_vsvmv __builtin_ve_vsubuw_vsvmv
#define _ve_pvsubu_vvv __builtin_ve_pvsubu_vvv
#define _ve_pvsubu_vsv __builtin_ve_pvsubu_vsv
#define _ve_pvsubu_vvvMv __builtin_ve_pvsubu_vvvMv
#define _ve_pvsubu_vsvMv __builtin_ve_pvsubu_vsvMv
#define _ve_vsubswsx_vvv __builtin_ve_vsubswsx_vvv
#define _ve_vsubswsx_vsv __builtin_ve_vsubswsx_vsv
#define _ve_vsubswsx_vvvmv __builtin_ve_vsubswsx_vvvmv
#define _ve_vsubswsx_vsvmv __builtin_ve_vsubswsx_vsvmv
#define _ve_vsubswzx_vvv __builtin_ve_vsubswzx_vvv
#define _ve_vsubswzx_vsv __builtin_ve_vsubswzx_vsv
#define _ve_vsubswzx_vvvmv __builtin_ve_vsubswzx_vvvmv
#define _ve_vsubswzx_vsvmv __builtin_ve_vsubswzx_vsvmv
#define _ve_pvsubs_vvv __builtin_ve_pvsubs_vvv
#define _ve_pvsubs_vsv __builtin_ve_pvsubs_vsv
#define _ve_pvsubs_vvvMv __builtin_ve_pvsubs_vvvMv
#define _ve_pvsubs_vsvMv __builtin_ve_pvsubs_vsvMv
#define _ve_vsubsl_vvv __builtin_ve_vsubsl_vvv
#define _ve_vsubsl_vsv __builtin_ve_vsubsl_vsv
#define _ve_vsubsl_vvvmv __builtin_ve_vsubsl_vvvmv
#define _ve_vsubsl_vsvmv __builtin_ve_vsubsl_vsvmv
#define _ve_vmulul_vvv __builtin_ve_vmulul_vvv
#define _ve_vmulul_vsv __builtin_ve_vmulul_vsv
#define _ve_vmulul_vvvmv __builtin_ve_vmulul_vvvmv
#define _ve_vmulul_vsvmv __builtin_ve_vmulul_vsvmv
#define _ve_vmuluw_vvv __builtin_ve_vmuluw_vvv
#define _ve_vmuluw_vsv __builtin_ve_vmuluw_vsv
#define _ve_vmuluw_vvvmv __builtin_ve_vmuluw_vvvmv
#define _ve_vmuluw_vsvmv __builtin_ve_vmuluw_vsvmv
#define _ve_vmulswsx_vvv __builtin_ve_vmulswsx_vvv
#define _ve_vmulswsx_vsv __builtin_ve_vmulswsx_vsv
#define _ve_vmulswsx_vvvmv __builtin_ve_vmulswsx_vvvmv
#define _ve_vmulswsx_vsvmv __builtin_ve_vmulswsx_vsvmv
#define _ve_vmulswzx_vvv __builtin_ve_vmulswzx_vvv
#define _ve_vmulswzx_vsv __builtin_ve_vmulswzx_vsv
#define _ve_vmulswzx_vvvmv __builtin_ve_vmulswzx_vvvmv
#define _ve_vmulswzx_vsvmv __builtin_ve_vmulswzx_vsvmv
#define _ve_vmulsl_vvv __builtin_ve_vmulsl_vvv
#define _ve_vmulsl_vsv __builtin_ve_vmulsl_vsv
#define _ve_vmulsl_vvvmv __builtin_ve_vmulsl_vvvmv
#define _ve_vmulsl_vsvmv __builtin_ve_vmulsl_vsvmv
#define _ve_vmulslw_vvv __builtin_ve_vmulslw_vvv
#define _ve_vmulslw_vsv __builtin_ve_vmulslw_vsv
#define _ve_vdivul_vvv __builtin_ve_vdivul_vvv
#define _ve_vdivul_vsv __builtin_ve_vdivul_vsv
#define _ve_vdivul_vvvmv __builtin_ve_vdivul_vvvmv
#define _ve_vdivul_vsvmv __builtin_ve_vdivul_vsvmv
#define _ve_vdivuw_vvv __builtin_ve_vdivuw_vvv
#define _ve_vdivuw_vsv __builtin_ve_vdivuw_vsv
#define _ve_vdivuw_vvvmv __builtin_ve_vdivuw_vvvmv
#define _ve_vdivuw_vsvmv __builtin_ve_vdivuw_vsvmv
#define _ve_vdivul_vvs __builtin_ve_vdivul_vvs
#define _ve_vdivul_vvsmv __builtin_ve_vdivul_vvsmv
#define _ve_vdivuw_vvs __builtin_ve_vdivuw_vvs
#define _ve_vdivuw_vvsmv __builtin_ve_vdivuw_vvsmv
#define _ve_vdivswsx_vvv __builtin_ve_vdivswsx_vvv
#define _ve_vdivswsx_vsv __builtin_ve_vdivswsx_vsv
#define _ve_vdivswsx_vvvmv __builtin_ve_vdivswsx_vvvmv
#define _ve_vdivswsx_vsvmv __builtin_ve_vdivswsx_vsvmv
#define _ve_vdivswzx_vvv __builtin_ve_vdivswzx_vvv
#define _ve_vdivswzx_vsv __builtin_ve_vdivswzx_vsv
#define _ve_vdivswzx_vvvmv __builtin_ve_vdivswzx_vvvmv
#define _ve_vdivswzx_vsvmv __builtin_ve_vdivswzx_vsvmv
#define _ve_vdivswsx_vvs __builtin_ve_vdivswsx_vvs
#define _ve_vdivswsx_vvsmv __builtin_ve_vdivswsx_vvsmv
#define _ve_vdivswzx_vvs __builtin_ve_vdivswzx_vvs
#define _ve_vdivswzx_vvsmv __builtin_ve_vdivswzx_vvsmv
#define _ve_vdivsl_vvv __builtin_ve_vdivsl_vvv
#define _ve_vdivsl_vsv __builtin_ve_vdivsl_vsv
#define _ve_vdivsl_vvvmv __builtin_ve_vdivsl_vvvmv
#define _ve_vdivsl_vsvmv __builtin_ve_vdivsl_vsvmv
#define _ve_vdivsl_vvs __builtin_ve_vdivsl_vvs
#define _ve_vdivsl_vvsmv __builtin_ve_vdivsl_vvsmv
#define _ve_vcmpul_vvv __builtin_ve_vcmpul_vvv
#define _ve_vcmpul_vsv __builtin_ve_vcmpul_vsv
#define _ve_vcmpul_vvvmv __builtin_ve_vcmpul_vvvmv
#define _ve_vcmpul_vsvmv __builtin_ve_vcmpul_vsvmv
#define _ve_vcmpuw_vvv __builtin_ve_vcmpuw_vvv
#define _ve_vcmpuw_vsv __builtin_ve_vcmpuw_vsv
#define _ve_vcmpuw_vvvmv __builtin_ve_vcmpuw_vvvmv
#define _ve_vcmpuw_vsvmv __builtin_ve_vcmpuw_vsvmv
#define _ve_pvcmpu_vvv __builtin_ve_pvcmpu_vvv
#define _ve_pvcmpu_vsv __builtin_ve_pvcmpu_vsv
#define _ve_pvcmpu_vvvMv __builtin_ve_pvcmpu_vvvMv
#define _ve_pvcmpu_vsvMv __builtin_ve_pvcmpu_vsvMv
#define _ve_vcmpswsx_vvv __builtin_ve_vcmpswsx_vvv
#define _ve_vcmpswsx_vsv __builtin_ve_vcmpswsx_vsv
#define _ve_vcmpswsx_vvvmv __builtin_ve_vcmpswsx_vvvmv
#define _ve_vcmpswsx_vsvmv __builtin_ve_vcmpswsx_vsvmv
#define _ve_vcmpswzx_vvv __builtin_ve_vcmpswzx_vvv
#define _ve_vcmpswzx_vsv __builtin_ve_vcmpswzx_vsv
#define _ve_vcmpswzx_vvvmv __builtin_ve_vcmpswzx_vvvmv
#define _ve_vcmpswzx_vsvmv __builtin_ve_vcmpswzx_vsvmv
#define _ve_pvcmps_vvv __builtin_ve_pvcmps_vvv
#define _ve_pvcmps_vsv __builtin_ve_pvcmps_vsv
#define _ve_pvcmps_vvvMv __builtin_ve_pvcmps_vvvMv
#define _ve_pvcmps_vsvMv __builtin_ve_pvcmps_vsvMv
#define _ve_vcmpsl_vvv __builtin_ve_vcmpsl_vvv
#define _ve_vcmpsl_vsv __builtin_ve_vcmpsl_vsv
#define _ve_vcmpsl_vvvmv __builtin_ve_vcmpsl_vvvmv
#define _ve_vcmpsl_vsvmv __builtin_ve_vcmpsl_vsvmv
#define _ve_vmaxswsx_vvv __builtin_ve_vmaxswsx_vvv
#define _ve_vmaxswsx_vsv __builtin_ve_vmaxswsx_vsv
#define _ve_vmaxswsx_vvvmv __builtin_ve_vmaxswsx_vvvmv
#define _ve_vmaxswsx_vsvmv __builtin_ve_vmaxswsx_vsvmv
#define _ve_vmaxswzx_vvv __builtin_ve_vmaxswzx_vvv
#define _ve_vmaxswzx_vsv __builtin_ve_vmaxswzx_vsv
#define _ve_vmaxswzx_vvvmv __builtin_ve_vmaxswzx_vvvmv
#define _ve_vmaxswzx_vsvmv __builtin_ve_vmaxswzx_vsvmv
#define _ve_pvmaxs_vvv __builtin_ve_pvmaxs_vvv
#define _ve_pvmaxs_vsv __builtin_ve_pvmaxs_vsv
#define _ve_pvmaxs_vvvMv __builtin_ve_pvmaxs_vvvMv
#define _ve_pvmaxs_vsvMv __builtin_ve_pvmaxs_vsvMv
#define _ve_vminswsx_vvv __builtin_ve_vminswsx_vvv
#define _ve_vminswsx_vsv __builtin_ve_vminswsx_vsv
#define _ve_vminswsx_vvvmv __builtin_ve_vminswsx_vvvmv
#define _ve_vminswsx_vsvmv __builtin_ve_vminswsx_vsvmv
#define _ve_vminswzx_vvv __builtin_ve_vminswzx_vvv
#define _ve_vminswzx_vsv __builtin_ve_vminswzx_vsv
#define _ve_vminswzx_vvvmv __builtin_ve_vminswzx_vvvmv
#define _ve_vminswzx_vsvmv __builtin_ve_vminswzx_vsvmv
#define _ve_pvmins_vvv __builtin_ve_pvmins_vvv
#define _ve_pvmins_vsv __builtin_ve_pvmins_vsv
#define _ve_pvmins_vvvMv __builtin_ve_pvmins_vvvMv
#define _ve_pvmins_vsvMv __builtin_ve_pvmins_vsvMv
#define _ve_vmaxsl_vvv __builtin_ve_vmaxsl_vvv
#define _ve_vmaxsl_vsv __builtin_ve_vmaxsl_vsv
#define _ve_vmaxsl_vvvmv __builtin_ve_vmaxsl_vvvmv
#define _ve_vmaxsl_vsvmv __builtin_ve_vmaxsl_vsvmv
#define _ve_vminsl_vvv __builtin_ve_vminsl_vvv
#define _ve_vminsl_vsv __builtin_ve_vminsl_vsv
#define _ve_vminsl_vvvmv __builtin_ve_vminsl_vvvmv
#define _ve_vminsl_vsvmv __builtin_ve_vminsl_vsvmv
#define _ve_vand_vvv __builtin_ve_vand_vvv
#define _ve_vand_vsv __builtin_ve_vand_vsv
#define _ve_vand_vvvmv __builtin_ve_vand_vvvmv
#define _ve_vand_vsvmv __builtin_ve_vand_vsvmv
#define _ve_pvand_vvv __builtin_ve_pvand_vvv
#define _ve_pvand_vsv __builtin_ve_pvand_vsv
#define _ve_pvand_vvvMv __builtin_ve_pvand_vvvMv
#define _ve_pvand_vsvMv __builtin_ve_pvand_vsvMv
#define _ve_vor_vvv __builtin_ve_vor_vvv
#define _ve_vor_vsv __builtin_ve_vor_vsv
#define _ve_vor_vvvmv __builtin_ve_vor_vvvmv
#define _ve_vor_vsvmv __builtin_ve_vor_vsvmv
#define _ve_pvor_vvv __builtin_ve_pvor_vvv
#define _ve_pvor_vsv __builtin_ve_pvor_vsv
#define _ve_pvor_vvvMv __builtin_ve_pvor_vvvMv
#define _ve_pvor_vsvMv __builtin_ve_pvor_vsvMv
#define _ve_vxor_vvv __builtin_ve_vxor_vvv
#define _ve_vxor_vsv __builtin_ve_vxor_vsv
#define _ve_vxor_vvvmv __builtin_ve_vxor_vvvmv
#define _ve_vxor_vsvmv __builtin_ve_vxor_vsvmv
#define _ve_pvxor_vvv __builtin_ve_pvxor_vvv
#define _ve_pvxor_vsv __builtin_ve_pvxor_vsv
#define _ve_pvxor_vvvMv __builtin_ve_pvxor_vvvMv
#define _ve_pvxor_vsvMv __builtin_ve_pvxor_vsvMv
#define _ve_veqv_vvv __builtin_ve_veqv_vvv
#define _ve_veqv_vsv __builtin_ve_veqv_vsv
#define _ve_veqv_vvvmv __builtin_ve_veqv_vvvmv
#define _ve_veqv_vsvmv __builtin_ve_veqv_vsvmv
#define _ve_pveqv_vvv __builtin_ve_pveqv_vvv
#define _ve_pveqv_vsv __builtin_ve_pveqv_vsv
#define _ve_pveqv_vvvMv __builtin_ve_pveqv_vvvMv
#define _ve_pveqv_vsvMv __builtin_ve_pveqv_vsvMv
#define _ve_vseq_v __builtin_ve_vseq_v
#define _ve_pvseqlo_v __builtin_ve_pvseqlo_v
#define _ve_pvsequp_v __builtin_ve_pvsequp_v
#define _ve_pvseq_v __builtin_ve_pvseq_v
#define _ve_vsll_vvv __builtin_ve_vsll_vvv
#define _ve_vsll_vvs __builtin_ve_vsll_vvs
#define _ve_vsll_vvvmv __builtin_ve_vsll_vvvmv
#define _ve_vsll_vvsmv __builtin_ve_vsll_vvsmv
#define _ve_pvsll_vvv __builtin_ve_pvsll_vvv
#define _ve_pvsll_vvs __builtin_ve_pvsll_vvs
#define _ve_pvsll_vvvMv __builtin_ve_pvsll_vvvMv
#define _ve_pvsll_vvsMv __builtin_ve_pvsll_vvsMv
#define _ve_vsrl_vvv __builtin_ve_vsrl_vvv
#define _ve_vsrl_vvs __builtin_ve_vsrl_vvs
#define _ve_vsrl_vvvmv __builtin_ve_vsrl_vvvmv
#define _ve_vsrl_vvsmv __builtin_ve_vsrl_vvsmv
#define _ve_pvsrl_vvv __builtin_ve_pvsrl_vvv
#define _ve_pvsrl_vvs __builtin_ve_pvsrl_vvs
#define _ve_pvsrl_vvvMv __builtin_ve_pvsrl_vvvMv
#define _ve_pvsrl_vvsMv __builtin_ve_pvsrl_vvsMv
#define _ve_vslaw_vvv __builtin_ve_vslaw_vvv
#define _ve_vslaw_vvs __builtin_ve_vslaw_vvs
#define _ve_vslaw_vvvmv __builtin_ve_vslaw_vvvmv
#define _ve_vslaw_vvsmv __builtin_ve_vslaw_vvsmv
#define _ve_pvsla_vvv __builtin_ve_pvsla_vvv
#define _ve_pvsla_vvs __builtin_ve_pvsla_vvs
#define _ve_pvsla_vvvMv __builtin_ve_pvsla_vvvMv
#define _ve_pvsla_vvsMv __builtin_ve_pvsla_vvsMv
#define _ve_vslal_vvv __builtin_ve_vslal_vvv
#define _ve_vslal_vvs __builtin_ve_vslal_vvs
#define _ve_vslal_vvvmv __builtin_ve_vslal_vvvmv
#define _ve_vslal_vvsmv __builtin_ve_vslal_vvsmv
#define _ve_vsraw_vvv __builtin_ve_vsraw_vvv
#define _ve_vsraw_vvs __builtin_ve_vsraw_vvs
#define _ve_vsraw_vvvmv __builtin_ve_vsraw_vvvmv
#define _ve_vsraw_vvsmv __builtin_ve_vsraw_vvsmv
#define _ve_pvsra_vvv __builtin_ve_pvsra_vvv
#define _ve_pvsra_vvs __builtin_ve_pvsra_vvs
#define _ve_pvsra_vvvMv __builtin_ve_pvsra_vvvMv
#define _ve_pvsra_vvsMv __builtin_ve_pvsra_vvsMv
#define _ve_vsral_vvv __builtin_ve_vsral_vvv
#define _ve_vsral_vvs __builtin_ve_vsral_vvs
#define _ve_vsral_vvvmv __builtin_ve_vsral_vvvmv
#define _ve_vsral_vvsmv __builtin_ve_vsral_vvsmv
#define _ve_vsfa_vvss __builtin_ve_vsfa_vvss
#define _ve_vsfa_vvssmv __builtin_ve_vsfa_vvssmv
#define _ve_vfaddd_vvv __builtin_ve_vfaddd_vvv
#define _ve_vfaddd_vsv __builtin_ve_vfaddd_vsv
#define _ve_vfaddd_vvvmv __builtin_ve_vfaddd_vvvmv
#define _ve_vfaddd_vsvmv __builtin_ve_vfaddd_vsvmv
#define _ve_vfadds_vvv __builtin_ve_vfadds_vvv
#define _ve_vfadds_vsv __builtin_ve_vfadds_vsv
#define _ve_vfadds_vvvmv __builtin_ve_vfadds_vvvmv
#define _ve_vfadds_vsvmv __builtin_ve_vfadds_vsvmv
#define _ve_pvfadd_vvv __builtin_ve_pvfadd_vvv
#define _ve_pvfadd_vsv __builtin_ve_pvfadd_vsv
#define _ve_pvfadd_vvvMv __builtin_ve_pvfadd_vvvMv
#define _ve_pvfadd_vsvMv __builtin_ve_pvfadd_vsvMv
#define _ve_vfsubd_vvv __builtin_ve_vfsubd_vvv
#define _ve_vfsubd_vsv __builtin_ve_vfsubd_vsv
#define _ve_vfsubd_vvvmv __builtin_ve_vfsubd_vvvmv
#define _ve_vfsubd_vsvmv __builtin_ve_vfsubd_vsvmv
#define _ve_vfsubs_vvv __builtin_ve_vfsubs_vvv
#define _ve_vfsubs_vsv __builtin_ve_vfsubs_vsv
#define _ve_vfsubs_vvvmv __builtin_ve_vfsubs_vvvmv
#define _ve_vfsubs_vsvmv __builtin_ve_vfsubs_vsvmv
#define _ve_pvfsub_vvv __builtin_ve_pvfsub_vvv
#define _ve_pvfsub_vsv __builtin_ve_pvfsub_vsv
#define _ve_pvfsub_vvvMv __builtin_ve_pvfsub_vvvMv
#define _ve_pvfsub_vsvMv __builtin_ve_pvfsub_vsvMv
#define _ve_vfmuld_vvv __builtin_ve_vfmuld_vvv
#define _ve_vfmuld_vsv __builtin_ve_vfmuld_vsv
#define _ve_vfmuld_vvvmv __builtin_ve_vfmuld_vvvmv
#define _ve_vfmuld_vsvmv __builtin_ve_vfmuld_vsvmv
#define _ve_vfmuls_vvv __builtin_ve_vfmuls_vvv
#define _ve_vfmuls_vsv __builtin_ve_vfmuls_vsv
#define _ve_vfmuls_vvvmv __builtin_ve_vfmuls_vvvmv
#define _ve_vfmuls_vsvmv __builtin_ve_vfmuls_vsvmv
#define _ve_pvfmul_vvv __builtin_ve_pvfmul_vvv
#define _ve_pvfmul_vsv __builtin_ve_pvfmul_vsv
#define _ve_pvfmul_vvvMv __builtin_ve_pvfmul_vvvMv
#define _ve_pvfmul_vsvMv __builtin_ve_pvfmul_vsvMv
#define _ve_vfdivd_vvv __builtin_ve_vfdivd_vvv
#define _ve_vfdivd_vsv __builtin_ve_vfdivd_vsv
#define _ve_vfdivd_vvvmv __builtin_ve_vfdivd_vvvmv
#define _ve_vfdivd_vsvmv __builtin_ve_vfdivd_vsvmv
#define _ve_vfdivs_vvv __builtin_ve_vfdivs_vvv
#define _ve_vfdivs_vsv __builtin_ve_vfdivs_vsv
#define _ve_vfdivs_vvvmv __builtin_ve_vfdivs_vvvmv
#define _ve_vfdivs_vsvmv __builtin_ve_vfdivs_vsvmv
#define _ve_vfdivsA_vvv __builtin_ve_vfdivsA_vvv
#define _ve_vfdivsA_vsv __builtin_ve_vfdivsA_vsv
#define _ve_pvfdivA_vvv __builtin_ve_pvfdivA_vvv
#define _ve_vfsqrtd_vv __builtin_ve_vfsqrtd_vv
#define _ve_vfsqrts_vv __builtin_ve_vfsqrts_vv
#define _ve_vfcmpd_vvv __builtin_ve_vfcmpd_vvv
#define _ve_vfcmpd_vsv __builtin_ve_vfcmpd_vsv
#define _ve_vfcmpd_vvvmv __builtin_ve_vfcmpd_vvvmv
#define _ve_vfcmpd_vsvmv __builtin_ve_vfcmpd_vsvmv
#define _ve_vfcmps_vvv __builtin_ve_vfcmps_vvv
#define _ve_vfcmps_vsv __builtin_ve_vfcmps_vsv
#define _ve_vfcmps_vvvmv __builtin_ve_vfcmps_vvvmv
#define _ve_vfcmps_vsvmv __builtin_ve_vfcmps_vsvmv
#define _ve_pvfcmp_vvv __builtin_ve_pvfcmp_vvv
#define _ve_pvfcmp_vsv __builtin_ve_pvfcmp_vsv
#define _ve_pvfcmp_vvvMv __builtin_ve_pvfcmp_vvvMv
#define _ve_pvfcmp_vsvMv __builtin_ve_pvfcmp_vsvMv
#define _ve_vfmaxd_vvv __builtin_ve_vfmaxd_vvv
#define _ve_vfmaxd_vsv __builtin_ve_vfmaxd_vsv
#define _ve_vfmaxd_vvvmv __builtin_ve_vfmaxd_vvvmv
#define _ve_vfmaxd_vsvmv __builtin_ve_vfmaxd_vsvmv
#define _ve_vfmaxs_vvv __builtin_ve_vfmaxs_vvv
#define _ve_vfmaxs_vsv __builtin_ve_vfmaxs_vsv
#define _ve_vfmaxs_vvvmv __builtin_ve_vfmaxs_vvvmv
#define _ve_vfmaxs_vsvmv __builtin_ve_vfmaxs_vsvmv
#define _ve_pvfmax_vvv __builtin_ve_pvfmax_vvv
#define _ve_pvfmax_vsv __builtin_ve_pvfmax_vsv
#define _ve_pvfmax_vvvMv __builtin_ve_pvfmax_vvvMv
#define _ve_pvfmax_vsvMv __builtin_ve_pvfmax_vsvMv
#define _ve_vfmind_vvv __builtin_ve_vfmind_vvv
#define _ve_vfmind_vsv __builtin_ve_vfmind_vsv
#define _ve_vfmind_vvvmv __builtin_ve_vfmind_vvvmv
#define _ve_vfmind_vsvmv __builtin_ve_vfmind_vsvmv
#define _ve_vfmins_vvv __builtin_ve_vfmins_vvv
#define _ve_vfmins_vsv __builtin_ve_vfmins_vsv
#define _ve_vfmins_vvvmv __builtin_ve_vfmins_vvvmv
#define _ve_vfmins_vsvmv __builtin_ve_vfmins_vsvmv
#define _ve_pvfmin_vvv __builtin_ve_pvfmin_vvv
#define _ve_pvfmin_vsv __builtin_ve_pvfmin_vsv
#define _ve_pvfmin_vvvMv __builtin_ve_pvfmin_vvvMv
#define _ve_pvfmin_vsvMv __builtin_ve_pvfmin_vsvMv
#define _ve_vfmadd_vvvv __builtin_ve_vfmadd_vvvv
#define _ve_vfmadd_vsvv __builtin_ve_vfmadd_vsvv
#define _ve_vfmadd_vvsv __builtin_ve_vfmadd_vvsv
#define _ve_vfmadd_vvvvmv __builtin_ve_vfmadd_vvvvmv
#define _ve_vfmadd_vsvvmv __builtin_ve_vfmadd_vsvvmv
#define _ve_vfmadd_vvsvmv __builtin_ve_vfmadd_vvsvmv
#define _ve_vfmads_vvvv __builtin_ve_vfmads_vvvv
#define _ve_vfmads_vsvv __builtin_ve_vfmads_vsvv
#define _ve_vfmads_vvsv __builtin_ve_vfmads_vvsv
#define _ve_vfmads_vvvvmv __builtin_ve_vfmads_vvvvmv
#define _ve_vfmads_vsvvmv __builtin_ve_vfmads_vsvvmv
#define _ve_vfmads_vvsvmv __builtin_ve_vfmads_vvsvmv
#define _ve_pvfmad_vvvv __builtin_ve_pvfmad_vvvv
#define _ve_pvfmad_vsvv __builtin_ve_pvfmad_vsvv
#define _ve_pvfmad_vvsv __builtin_ve_pvfmad_vvsv
#define _ve_pvfmad_vvvvMv __builtin_ve_pvfmad_vvvvMv
#define _ve_pvfmad_vsvvMv __builtin_ve_pvfmad_vsvvMv
#define _ve_pvfmad_vvsvMv __builtin_ve_pvfmad_vvsvMv
#define _ve_vfmsbd_vvvv __builtin_ve_vfmsbd_vvvv
#define _ve_vfmsbd_vsvv __builtin_ve_vfmsbd_vsvv
#define _ve_vfmsbd_vvsv __builtin_ve_vfmsbd_vvsv
#define _ve_vfmsbd_vvvvmv __builtin_ve_vfmsbd_vvvvmv
#define _ve_vfmsbd_vsvvmv __builtin_ve_vfmsbd_vsvvmv
#define _ve_vfmsbd_vvsvmv __builtin_ve_vfmsbd_vvsvmv
#define _ve_vfmsbs_vvvv __builtin_ve_vfmsbs_vvvv
#define _ve_vfmsbs_vsvv __builtin_ve_vfmsbs_vsvv
#define _ve_vfmsbs_vvsv __builtin_ve_vfmsbs_vvsv
#define _ve_vfmsbs_vvvvmv __builtin_ve_vfmsbs_vvvvmv
#define _ve_vfmsbs_vsvvmv __builtin_ve_vfmsbs_vsvvmv
#define _ve_vfmsbs_vvsvmv __builtin_ve_vfmsbs_vvsvmv
#define _ve_pvfmsb_vvvv __builtin_ve_pvfmsb_vvvv
#define _ve_pvfmsb_vsvv __builtin_ve_pvfmsb_vsvv
#define _ve_pvfmsb_vvsv __builtin_ve_pvfmsb_vvsv
#define _ve_pvfmsb_vvvvMv __builtin_ve_pvfmsb_vvvvMv
#define _ve_pvfmsb_vsvvMv __builtin_ve_pvfmsb_vsvvMv
#define _ve_pvfmsb_vvsvMv __builtin_ve_pvfmsb_vvsvMv
#define _ve_vfnmadd_vvvv __builtin_ve_vfnmadd_vvvv
#define _ve_vfnmadd_vsvv __builtin_ve_vfnmadd_vsvv
#define _ve_vfnmadd_vvsv __builtin_ve_vfnmadd_vvsv
#define _ve_vfnmadd_vvvvmv __builtin_ve_vfnmadd_vvvvmv
#define _ve_vfnmadd_vsvvmv __builtin_ve_vfnmadd_vsvvmv
#define _ve_vfnmadd_vvsvmv __builtin_ve_vfnmadd_vvsvmv
#define _ve_vfnmads_vvvv __builtin_ve_vfnmads_vvvv
#define _ve_vfnmads_vsvv __builtin_ve_vfnmads_vsvv
#define _ve_vfnmads_vvsv __builtin_ve_vfnmads_vvsv
#define _ve_vfnmads_vvvvmv __builtin_ve_vfnmads_vvvvmv
#define _ve_vfnmads_vsvvmv __builtin_ve_vfnmads_vsvvmv
#define _ve_vfnmads_vvsvmv __builtin_ve_vfnmads_vvsvmv
#define _ve_pvfnmad_vvvv __builtin_ve_pvfnmad_vvvv
#define _ve_pvfnmad_vsvv __builtin_ve_pvfnmad_vsvv
#define _ve_pvfnmad_vvsv __builtin_ve_pvfnmad_vvsv
#define _ve_pvfnmad_vvvvMv __builtin_ve_pvfnmad_vvvvMv
#define _ve_pvfnmad_vsvvMv __builtin_ve_pvfnmad_vsvvMv
#define _ve_pvfnmad_vvsvMv __builtin_ve_pvfnmad_vvsvMv
#define _ve_vfnmsbd_vvvv __builtin_ve_vfnmsbd_vvvv
#define _ve_vfnmsbd_vsvv __builtin_ve_vfnmsbd_vsvv
#define _ve_vfnmsbd_vvsv __builtin_ve_vfnmsbd_vvsv
#define _ve_vfnmsbd_vvvvmv __builtin_ve_vfnmsbd_vvvvmv
#define _ve_vfnmsbd_vsvvmv __builtin_ve_vfnmsbd_vsvvmv
#define _ve_vfnmsbd_vvsvmv __builtin_ve_vfnmsbd_vvsvmv
#define _ve_vfnmsbs_vvvv __builtin_ve_vfnmsbs_vvvv
#define _ve_vfnmsbs_vsvv __builtin_ve_vfnmsbs_vsvv
#define _ve_vfnmsbs_vvsv __builtin_ve_vfnmsbs_vvsv
#define _ve_vfnmsbs_vvvvmv __builtin_ve_vfnmsbs_vvvvmv
#define _ve_vfnmsbs_vsvvmv __builtin_ve_vfnmsbs_vsvvmv
#define _ve_vfnmsbs_vvsvmv __builtin_ve_vfnmsbs_vvsvmv
#define _ve_pvfnmsb_vvvv __builtin_ve_pvfnmsb_vvvv
#define _ve_pvfnmsb_vsvv __builtin_ve_pvfnmsb_vsvv
#define _ve_pvfnmsb_vvsv __builtin_ve_pvfnmsb_vvsv
#define _ve_pvfnmsb_vvvvMv __builtin_ve_pvfnmsb_vvvvMv
#define _ve_pvfnmsb_vsvvMv __builtin_ve_pvfnmsb_vsvvMv
#define _ve_pvfnmsb_vvsvMv __builtin_ve_pvfnmsb_vvsvMv
#define _ve_vrcpd_vv __builtin_ve_vrcpd_vv
#define _ve_vrcps_vv __builtin_ve_vrcps_vv
#define _ve_pvrcp_vv __builtin_ve_pvrcp_vv
#define _ve_vrsqrtd_vv __builtin_ve_vrsqrtd_vv
#define _ve_vrsqrts_vv __builtin_ve_vrsqrts_vv
#define _ve_pvrsqrt_vv __builtin_ve_pvrsqrt_vv
#define _ve_vcvtwdsx_vv __builtin_ve_vcvtwdsx_vv
#define _ve_vcvtwdsx_vvmv __builtin_ve_vcvtwdsx_vvmv
#define _ve_vcvtwdsxrz_vv __builtin_ve_vcvtwdsxrz_vv
#define _ve_vcvtwdsxrz_vvmv __builtin_ve_vcvtwdsxrz_vvmv
#define _ve_vcvtwdzx_vv __builtin_ve_vcvtwdzx_vv
#define _ve_vcvtwdzx_vvmv __builtin_ve_vcvtwdzx_vvmv
#define _ve_vcvtwdzxrz_vv __builtin_ve_vcvtwdzxrz_vv
#define _ve_vcvtwdzxrz_vvmv __builtin_ve_vcvtwdzxrz_vvmv
#define _ve_vcvtwssx_vv __builtin_ve_vcvtwssx_vv
#define _ve_vcvtwssx_vvmv __builtin_ve_vcvtwssx_vvmv
#define _ve_vcvtwssxrz_vv __builtin_ve_vcvtwssxrz_vv
#define _ve_vcvtwssxrz_vvmv __builtin_ve_vcvtwssxrz_vvmv
#define _ve_vcvtwszx_vv __builtin_ve_vcvtwszx_vv
#define _ve_vcvtwszx_vvmv __builtin_ve_vcvtwszx_vvmv
#define _ve_vcvtwszxrz_vv __builtin_ve_vcvtwszxrz_vv
#define _ve_vcvtwszxrz_vvmv __builtin_ve_vcvtwszxrz_vvmv
#define _ve_pvcvtws_vv __builtin_ve_pvcvtws_vv
#define _ve_pvcvtws_vvMv __builtin_ve_pvcvtws_vvMv
#define _ve_pvcvtwsrz_vv __builtin_ve_pvcvtwsrz_vv
#define _ve_pvcvtwsrz_vvMv __builtin_ve_pvcvtwsrz_vvMv
#define _ve_vcvtld_vv __builtin_ve_vcvtld_vv
#define _ve_vcvtld_vvmv __builtin_ve_vcvtld_vvmv
#define _ve_vcvtldrz_vv __builtin_ve_vcvtldrz_vv
#define _ve_vcvtldrz_vvmv __builtin_ve_vcvtldrz_vvmv
#define _ve_vcvtdw_vv __builtin_ve_vcvtdw_vv
#define _ve_vcvtsw_vv __builtin_ve_vcvtsw_vv
#define _ve_pvcvtsw_vv __builtin_ve_pvcvtsw_vv
#define _ve_vcvtdl_vv __builtin_ve_vcvtdl_vv
#define _ve_vcvtds_vv __builtin_ve_vcvtds_vv
#define _ve_vcvtsd_vv __builtin_ve_vcvtsd_vv
#define _ve_vmrg_vvvm __builtin_ve_vmrg_vvvm
#define _ve_vmrgw_vvvM __builtin_ve_vmrgw_vvvM
#define _ve_vshf_vvvs __builtin_ve_vshf_vvvs
#define _ve_vcp_vvmv __builtin_ve_vcp_vvmv
#define _ve_vex_vvmv __builtin_ve_vex_vvmv
#define _ve_vfmkl_mcv __builtin_ve_vfmkl_mcv
#define _ve_vfmkl_mcvm __builtin_ve_vfmkl_mcvm
#define _ve_vfmkat_m __builtin_ve_vfmkat_m
#define _ve_vfmkaf_m __builtin_ve_vfmkaf_m
#define _ve_pvfmkat_M __builtin_ve_pvfmkat_M
#define _ve_pvfmkaf_M __builtin_ve_pvfmkaf_M
#define _ve_vfmkw_mcv __builtin_ve_vfmkw_mcv
#define _ve_vfmkw_mcvm __builtin_ve_vfmkw_mcvm
#define _ve_pvfmkw_Mcv __builtin_ve_pvfmkw_Mcv
#define _ve_pvfmkw_McvM __builtin_ve_pvfmkw_McvM
#define _ve_vfmkd_mcv __builtin_ve_vfmkd_mcv
#define _ve_vfmkd_mcvm __builtin_ve_vfmkd_mcvm
#define _ve_vfmks_mcv __builtin_ve_vfmks_mcv
#define _ve_vfmks_mcvm __builtin_ve_vfmks_mcvm
#define _ve_pvfmks_Mcv __builtin_ve_pvfmks_Mcv
#define _ve_pvfmks_McvM __builtin_ve_pvfmks_McvM
#define _ve_vsumwsx_vv __builtin_ve_vsumwsx_vv
#define _ve_vsumwsx_vvm __builtin_ve_vsumwsx_vvm
#define _ve_vsumwzx_vv __builtin_ve_vsumwzx_vv
#define _ve_vsumwzx_vvm __builtin_ve_vsumwzx_vvm
#define _ve_vsuml_vv __builtin_ve_vsuml_vv
#define _ve_vsuml_vvm __builtin_ve_vsuml_vvm
#define _ve_vfsumd_vv __builtin_ve_vfsumd_vv
#define _ve_vfsumd_vvm __builtin_ve_vfsumd_vvm
#define _ve_vfsums_vv __builtin_ve_vfsums_vv
#define _ve_vfsums_vvm __builtin_ve_vfsums_vvm
#define _ve_vrmaxswfstsx_vv __builtin_ve_vrmaxswfstsx_vv
#define _ve_vrmaxswlstsx_vv __builtin_ve_vrmaxswlstsx_vv
#define _ve_vrmaxswfstzx_vv __builtin_ve_vrmaxswfstzx_vv
#define _ve_vrmaxswlstzx_vv __builtin_ve_vrmaxswlstzx_vv
#define _ve_vrminswfstsx_vv __builtin_ve_vrminswfstsx_vv
#define _ve_vrminswlstsx_vv __builtin_ve_vrminswlstsx_vv
#define _ve_vrminswfstzx_vv __builtin_ve_vrminswfstzx_vv
#define _ve_vrminswlstzx_vv __builtin_ve_vrminswlstzx_vv
#define _ve_vrmaxslfst_vv __builtin_ve_vrmaxslfst_vv
#define _ve_vrmaxsllst_vv __builtin_ve_vrmaxsllst_vv
#define _ve_vrminslfst_vv __builtin_ve_vrminslfst_vv
#define _ve_vrminsllst_vv __builtin_ve_vrminsllst_vv
#define _ve_vfrmaxdfst_vv __builtin_ve_vfrmaxdfst_vv
#define _ve_vfrmaxdlst_vv __builtin_ve_vfrmaxdlst_vv
#define _ve_vfrmaxsfst_vv __builtin_ve_vfrmaxsfst_vv
#define _ve_vfrmaxslst_vv __builtin_ve_vfrmaxslst_vv
#define _ve_vfrmindfst_vv __builtin_ve_vfrmindfst_vv
#define _ve_vfrmindlst_vv __builtin_ve_vfrmindlst_vv
#define _ve_vfrminsfst_vv __builtin_ve_vfrminsfst_vv
#define _ve_vfrminslst_vv __builtin_ve_vfrminslst_vv
#define _ve_vgt_vv __builtin_ve_vgt_vv
#define _ve_vgt_vvm __builtin_ve_vgt_vvm
#define _ve_vgtu_vv __builtin_ve_vgtu_vv
#define _ve_vgtu_vvm __builtin_ve_vgtu_vvm
#define _ve_vgtlsx_vv __builtin_ve_vgtlsx_vv
#define _ve_vgtlsx_vvm __builtin_ve_vgtlsx_vvm
#define _ve_vgtlzx_vv __builtin_ve_vgtlzx_vv
#define _ve_vgtlzx_vvm __builtin_ve_vgtlzx_vvm
#define _ve_vsc_vv __builtin_ve_vsc_vv
#define _ve_vsc_vvm __builtin_ve_vsc_vvm
#define _ve_vscot_vv __builtin_ve_vscot_vv
#define _ve_vscot_vvm __builtin_ve_vscot_vvm
#define _ve_vscu_vv __builtin_ve_vscu_vv
#define _ve_vscu_vvm __builtin_ve_vscu_vvm
#define _ve_vscuot_vv __builtin_ve_vscuot_vv
#define _ve_vscuot_vvm __builtin_ve_vscuot_vvm
#define _ve_vscl_vv __builtin_ve_vscl_vv
#define _ve_vscl_vvm __builtin_ve_vscl_vvm
#define _ve_vsclot_vv __builtin_ve_vsclot_vv
#define _ve_vsclot_vvm __builtin_ve_vsclot_vvm
#define _ve_andm_mmm __builtin_ve_andm_mmm
#define _ve_andm_MMM __builtin_ve_andm_MMM
#define _ve_orm_mmm __builtin_ve_orm_mmm
#define _ve_orm_MMM __builtin_ve_orm_MMM
#define _ve_xorm_mmm __builtin_ve_xorm_mmm
#define _ve_xorm_MMM __builtin_ve_xorm_MMM
#define _ve_eqvm_mmm __builtin_ve_eqvm_mmm
#define _ve_eqvm_MMM __builtin_ve_eqvm_MMM
#define _ve_nndm_mmm __builtin_ve_nndm_mmm
#define _ve_nndm_MMM __builtin_ve_nndm_MMM
#define _ve_negm_mm __builtin_ve_negm_mm
#define _ve_negm_MM __builtin_ve_negm_MM
#define _ve_pcvm_sm __builtin_ve_pcvm_sm
#define _ve_lzvm_sm __builtin_ve_lzvm_sm
#define _ve_tovm_sm __builtin_ve_tovm_sm
| 48.863958 | 56 | 0.918285 |
45ecd0e935ae0c630945f00ff3fab49c21b41ddd | 724 | c | C | test/cases/scope/age.c | bocke/ucc | d95c0014dfc555c3eb6e9fdf909e0460bf2a0060 | [
"MIT"
] | 55 | 2015-02-07T12:31:13.000Z | 2022-02-19T15:25:02.000Z | test/cases/scope/age.c | bocke/ucc | d95c0014dfc555c3eb6e9fdf909e0460bf2a0060 | [
"MIT"
] | null | null | null | test/cases/scope/age.c | bocke/ucc | d95c0014dfc555c3eb6e9fdf909e0460bf2a0060 | [
"MIT"
] | 9 | 2015-08-06T21:26:33.000Z | 2022-01-14T03:44:40.000Z | // RUN: %ucc -o %t %s
// RUN: [ `%t | grep '^#' | wc -l` -eq 1 ]
// RUN: %t | grep -F '# 35 53'
char * strpbrk(const char *s, const char *charset);
int snprintf(char * restrict str, unsigned long size, const char * restrict format, ...);
int printf(const char *, ...) __attribute__((format(printf, 1, 2)));
strcmpany(char *a, char *b)
{
return (a[0] == b[0] && a[1] == b[1])
|| (a[0] == b[1] && a[1] == b[0]);
}
main()
{
printf("hex dec\n");
for(int i = 10; i < 100; i++){
char buf[2][4];
snprintf(buf[0], sizeof buf[0], "%x", i);
if(strpbrk(buf[0], "abcdef"))
continue;
snprintf(buf[1], sizeof buf[1], "%d", i);
printf("%c %s %s\n",
"-#"[strcmpany(buf[0], buf[1])],
buf[0], buf[1]);
}
}
| 22.625 | 89 | 0.516575 |
a11a51ae7e49ab0b0e1c57ac2e0a1e2d76dfee56 | 7,020 | h | C | librtt/Rtt_MPlatform.h | pouwelsjochem/corona | 86ffe9002e42721b4bb2c386024111d995e7b27c | [
"MIT"
] | null | null | null | librtt/Rtt_MPlatform.h | pouwelsjochem/corona | 86ffe9002e42721b4bb2c386024111d995e7b27c | [
"MIT"
] | null | null | null | librtt/Rtt_MPlatform.h | pouwelsjochem/corona | 86ffe9002e42721b4bb2c386024111d995e7b27c | [
"MIT"
] | null | null | null | //////////////////////////////////////////////////////////////////////////////
//
// This file is part of the Corona game engine.
// For overview and more information on licensing please refer to README.md
// Home page: https://github.com/coronalabs/corona
// Contact: support@coronalabs.com
//
//////////////////////////////////////////////////////////////////////////////
#ifndef _Rtt_Platform_H__
#define _Rtt_Platform_H__
#include "Core/Rtt_Types.h"
#include "Display/Rtt_PlatformBitmap.h"
#include "Core/Rtt_Data.h"
#include "Core/Rtt_ResourceHandle.h"
#include "Rtt_PlatformReachability.h" // needed because of enum type
#include "Rtt_Preference.h"
#include <map>
#include <string>
// ----------------------------------------------------------------------------
struct lua_State;
struct ALmixer_Data;
namespace Rtt
{
class LuaResource;
class MCallback;
class MCrypto;
class MPlatformDevice;
class RenderingStream;
class PlatformBitmap;
class PlatformDisplayObject;
class PlatformExitCallback;
class PlatformFBConnect;
class PlatformOpenALPlayer;
class PlatformStoreProvider;
class PlatformWebPopup;
class PlatformSurface;
class PlatformTimer;
class PreferenceCollection;
class Runtime;
struct Rect;
class String;
// ----------------------------------------------------------------------------
typedef void *NativeAlertRef;
// TODO: Separate this into 2 interfaces:
// (1) MPlatform: All non-UI api's
// (2) MPlatformInterface: All UI-related api's
class MPlatform
{
public:
typedef enum _Error
{
kOutOfMemoryError,
kEGLContextInitError,
//kRuntimeInitError,
//kPlatformInitError,
kNumError
}
Error;
/*
* The distinction between kResourceDir and kSystemResourceDir is:
*
* On the simulator, we need to distinguish between resource files in the app bundle
* (system resources) vs project files (plain resources).
* On the simulator, load a resource.car file that lives in the app bundle (system resource dir).
* It contains the compiled lua for each device skin and the remdebug.engine.
*
* On the device, there's no distinction.
*/
typedef enum _Directory
{
kResourceDir = 0,
kDocumentsDir,
kTmpDir,
kSystemResourceDir,
kCachesDir,
kSystemCachesDir,
kPluginsDir,
kVirtualTexturesDir,
kApplicationSupportDir,
kNumDirs,
kUnknownDir = -1
}
Directory;
static bool IsVirtualDirectory(Directory directory)
{
return kVirtualTexturesDir == directory;
}
typedef enum _Category
{
kLocaleIdentifier = 0,
kLocaleLanguage,
kLocaleCountry,
kUILanguage,
kNumCategories,
kUnknownCategory = -1
}
Category;
public:
// Factory methods
virtual Rtt_Allocator& GetAllocator() const = 0;
virtual MPlatformDevice& GetDevice() const = 0;
virtual RenderingStream* CreateRenderingStream() const = 0;
virtual PlatformSurface* CreateScreenSurface() const = 0;
virtual PlatformSurface* CreateOffscreenSurface( const PlatformSurface& parent ) const = 0;
virtual PlatformTimer* CreateTimerWithCallback( MCallback& callback ) const = 0;
virtual PlatformBitmap* CreateBitmap( const char *filePath, bool convertToGrayscale ) const = 0;
virtual void SaveBitmap( PlatformBitmap* bitmap, Rtt::Data<const char> & pngBytes ) const = 0;
virtual bool OpenURL( const char* url ) const = 0;
// Return values of CanOpenURL: -1 Unknown; 0 No; 1 Yes
virtual int CanOpenURL( const char* url ) const = 0;
virtual const MCrypto& GetCrypto() const = 0;
virtual void GetPreference( Category category, Rtt::String * value ) const = 0;
virtual Preference::ReadValueResult GetPreference(const char* categoryName, const char* keyName) const = 0;
virtual OperationResult SetPreferences( const char* categoryName, const PreferenceCollection& collection ) const = 0;
virtual OperationResult DeletePreferences( const char* categoryName, const char** keyNameArray, U32 keyNameCount ) const = 0;
virtual PlatformStoreProvider* GetStoreProvider( const ResourceHandle<lua_State>& handle ) const = 0;
virtual void GetSafeAreaInsetsPixels(Rtt_Real &top, Rtt_Real &left, Rtt_Real &bottom, Rtt_Real &right) const = 0;
virtual NativeAlertRef ShowNativeAlert(
const char *title,
const char *msg,
const char **buttonLabels,
U32 numButtons,
LuaResource* resource ) const = 0;
// index is the (0-based) index of the button pressed
virtual void CancelNativeAlert( NativeAlertRef alert, S32 index ) const = 0;
virtual PlatformWebPopup* GetWebPopup() const = 0;
// Show modal-like native interfaces that pop up above the Corona view
// E.g. mail composers, etc.
virtual bool CanShowPopup( const char *name ) const = 0;
virtual bool ShowPopup( lua_State *L, const char *name, int optionsIndex ) const = 0;
virtual bool HidePopup( const char *name ) const = 0;
virtual PlatformDisplayObject* CreateNativeWebView( const Rect& bounds ) const = 0;
virtual PlatformFBConnect* GetFBConnect() const = 0;
public:
// Creates notification based on table at 'index'. Returns notificationId
virtual void* CreateAndScheduleNotification( lua_State *L, int index ) const = 0;
// Creates notification based on table at 'index'. Returns notificationId
virtual void ReleaseNotification( void *notificationId ) const = 0;
// Pass "NULL" to cancel all pending notifications
virtual void CancelNotification( void *notificationId ) const = 0;
public:
virtual void RuntimeErrorNotification( const char *errorType, const char *message, const char *stacktrace ) const = 0;
#ifdef Rtt_AUTHORING_SIMULATOR
virtual void SetCursorForRect(const char *cursorName, int x, int y, int width, int height) const = 0;
#endif
public:
virtual void SetNativeProperty( lua_State *L, const char *key, int valueIndex ) const = 0;
virtual int PushNativeProperty( lua_State *L, const char *key ) const = 0;
virtual int PushSystemInfo( lua_State *L, const char *key ) const = 0;
public:
virtual void RaiseError( Error e, const char* reason ) const = 0;
enum PathBitFlags
{
kDefaultPathFlags = 0x0,
kResultOwnedByCaller = 0x1,
kTestFileExists = 0x2
};
virtual void PathForFile( const char* filename, Directory baseDir, U32 flags, String & result ) const = 0;
virtual bool FileExists( const char * filename ) const = 0;
virtual int SetSync( lua_State* L ) const = 0;
virtual int GetSync( lua_State* L ) const = 0;
public:
virtual void BeginRuntime( const Runtime& runtime ) const = 0;
virtual void EndRuntime( const Runtime& runtime ) const = 0;
virtual PlatformExitCallback* GetExitCallback() = 0;
virtual bool RequestSystem( lua_State *L, const char *actionName, int optionsIndex ) const = 0;
virtual void Suspend() const = 0;
virtual void Resume() const = 0;
};
// ----------------------------------------------------------------------------
} // namespace Rtt
// ----------------------------------------------------------------------------
#endif // _Rtt_Platform_H__
| 32.201835 | 127 | 0.687892 |
a2816e40230d5d05ddb1cd8532e4cd70d8b0ffec | 25,406 | h | C | cocos3d/cocos3d/Nodes/CC3UtilityMeshNodes.h | LaudateCorpus1/cocos3d | d71dba7d3d38eac81b68ef18035d5adaf9e6927d | [
"MIT"
] | 228 | 2015-01-06T16:39:26.000Z | 2022-02-24T14:46:58.000Z | cocos3d/cocos3d/Nodes/CC3UtilityMeshNodes.h | xgqelite/cocos3d | 2384b4be410eea7262233ee126c9685c405b4d54 | [
"MIT"
] | 7 | 2015-01-19T06:30:29.000Z | 2019-12-21T22:53:38.000Z | cocos3d/cocos3d/Nodes/CC3UtilityMeshNodes.h | xgqelite/cocos3d | 2384b4be410eea7262233ee126c9685c405b4d54 | [
"MIT"
] | 85 | 2015-01-13T02:46:28.000Z | 2022-02-19T21:09:57.000Z | /*
* CC3UtilityMeshNodes.h
*
* Cocos3D 2.0.2
* Author: Bill Hollings
* Copyright (c) 2010-2014 The Brenwill Workshop Ltd. All rights reserved.
* http://www.brenwill.com
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* http://en.wikipedia.org/wiki/MIT_License
*/
/** @file */ // Doxygen marker
#import "CC3ParametricMeshNodes.h"
#pragma mark -
#pragma mark CC3PlaneNode
/**
* CC3PlaneNode is a type of CC3MeshNode that is specialized to display planes and
* simple rectanglular meshes.
*
* Since a plane is a mesh like any other mesh, the functionality required to create
* and manipulate plane meshes is present in the CC3MeshNode class, and if you choose,
* you can create and manage plane meshes using that class alone. Some plane-specific
* functionality is defined within this class.
*
* Several convenience methods exist in the CC3MeshNode class to aid in constructing a
* CC3PlaneNode instance:
* - populateAsCenteredRectangleWithSize:
* - populateAsRectangleWithSize:andPivot:
*/
@interface CC3PlaneNode : CC3MeshNode
/**
* Returns a CC3Plane structure corresponding to this plane.
*
* This structure is built from the location vertices of three of the corners
* of the bounding box of the mesh.
*/
@property(nonatomic, readonly) CC3Plane plane;
@end
#pragma mark -
#pragma mark CC3LineNode
/**
* CC3LineNode is a type of CC3MeshNode that is specialized to display lines.
*
* Since lines are a mesh like any other mesh, the functionality required to create and manipulate
* line meshes is present in the CC3MeshNode class, and if you choose, you can create and manage line
* meshes using that class alone. At present, CC3LineNode exists for the most part simply to identify
* box meshes as such. However, in future, additional state or behaviour may be added to this class.
*
* To draw lines, you must make sure that the drawingMode property is set to one of GL_LINES,
* GL_LINE_STRIP or GL_LINE_LOOP. This property must be set after the mesh is attached.
* Other than that, you configure the mesh node and its mesh as you would with any mesh node.
*
* Several convenience methods exist in the CC3MeshNode class to aid in constructing a
* CC3LineNode instance:
* - populateAsLineStripWith:vertices:andRetain:
* - populateAsWireBox: - a simple wire box
*/
@interface CC3LineNode : CC3MeshNode
/** @deprecated Property renamed to lineSmoothingHint on CC3MeshNode. */
@property(nonatomic, assign) GLenum performanceHint __deprecated;
@end
#pragma mark -
#pragma mark CC3SimpleLineNode
/**
* CC3SimpleLineNode simplifies the creation of a simple two-point straight line.
*
* You can create a single simple straight line model by instantiating an instance of this
* class and then setting either or both of the lineStart and lineEnd properties.
*
* The mesh underlying this node is automatically populated as a simple two-vertex line.
* When using this class, you do not need to use any of the populateAs... methods to generate
* and populate the mesh.
*/
@interface CC3SimpleLineNode : CC3LineNode {
CC3Vector _lineVertices[2];
}
/**
* Indicates the start of the line in the local coordinate system of this node.
*
* The initial value is kCC3VectorZero, indicating that the line starts at the origin of
* the local coordinate system.
*/
@property(nonatomic, assign) CC3Vector lineStart;
/**
* Indicates the end of the line in the local coordinate system of this node.
*
* The initial value is kCC3VectorZero, indicating that the line ends at the origin of
* the local coordinate system.
*/
@property(nonatomic, assign) CC3Vector lineEnd;
@end
#pragma mark -
#pragma mark CC3BoxNode
/**
* CC3BoxNode is a type of CC3MeshNode that is specialized to display simple box or cube meshes.
*
* Since a cube or box is a mesh like any other mesh, the functionality required to create and
* manipulate box meshes is present in the CC3MeshNode class, and if you choose, you can create
* and manage box meshes using that class alone. At present, CC3BoxNode exists for the most part
* simply to identify box meshes as such. However, in future, additional state or behaviour may
* be added to this class.
*
* You can use one of the following convenience methods to aid in constructing a CC3BoxNode instance:
* - populateAsSolidBox:
* - populateAsSolidBox:withCorner:
* - populateAsWireBox:
*/
@interface CC3BoxNode : CC3MeshNode
@end
#pragma mark -
#pragma mark CC3TouchBox
/**
* CC3TouchBox is a specialized node that creates an invisible box mesh that can be used to
* define a 3D region for touch activity.
*
* If you do not set the box property explicitly, when you add an instance of this class as a child
* of another CC3Node, this node will automatically be populated as a box the same size as the
* bounding box of that parent. If the parent node contains other nodes, its bounding box will
* include its descendants, resulting in this mesh being populated to encapsulate all descendant
* nodes of its parent. The effect is to define a box-shaped touch region around a composite node
* that might be comprised of a number of smaller nodes with space in between them.
*
* If the parent node contains descendants that are moving around, the bounding box of the parent
* node may be dynamic and constantly changing. If you want the touch box to track changes to the
* parent bounding box, set the shouldAlwaysMeasureParentBoundingBox property to YES.
*
* You can also set the box property directly to create a box that is shaped differently than the
* bounding box of the parent. For example, you might want to do this if you want the touch box to
* be larger than the actual visible nodes, in order to make it easier to touch.
*
* The mesh underlying this node is automatically populated when you set the box property, or when
* you add this node to a parent. You do not need to invoke any of the populateAs... methods directly.
*
* Since this node is intended to be used as an invisible touch pad, the visible property of this node
* is initially set to NO, and the shouldAllowTouchableWhenInvisible property is initially set to YES.
* In addition, the bounding box of this mesh will not contribute to the bounding box of the parent.
*/
@interface CC3TouchBox : CC3BoxNode {
BOOL _shouldAlwaysMeasureParentBoundingBox : 1;
}
/**
* Indicates the size of the touch box.
*
* Setting this property populates this node with a box mesh of the specified extent.
*
* Instead of setting this property directly, you can automatically create the box mesh by simply
* adding this node to a parent CC3Node. If this property has not already been set when this node
* is added to a parent, the value of this property will automatically be set to the value of the
* boundingBox property of the parent.
*
* If the parent node contains descendants that are moving around, the bounding box of the parent
* node may be dynamic and constantly changing. If you want the touch box to track changes to the
* parent bounding box, set the shouldAlwaysMeasureParentBoundingBox property to YES.
*
* If you set this property directly, and then subsequently add this node to a parent, the value
* of this property will not change, and the underlying mesh will not be repopulated. By setting
* the value of this property directly, you can create a mesh box that is of a different size
* than the parent bounding box.
*
* Setting this property to kCC3BoxNull will remove the underlying mesh.
*
* The initial value of this property is kCC3BoxNull.
*/
@property(nonatomic, assign) CC3Box box;
/**
* Indicates whether the dimensions of this node should automatically be remeasured on each update pass.
*
* If this property is set to YES, the box will automatically be resized to account for movements by
* any descendant nodes of the parent node. To create a dynamic touch box that automatically adjusts
* as the descendants of the parent node move around, this property should be set to YES.
*
* It is not necessary to set this property to YES to account for changes in the transform properties
* of the parent node itself.
*
* When setting this property, be aware that dynamically measuring the bounding box of the parent node
* can be an expensive operation if the parent contains a number of descendant nodes.
*
* The initial value of this property is NO.
*/
@property(nonatomic, assign) BOOL shouldAlwaysMeasureParentBoundingBox;
@end
#pragma mark -
#pragma mark CC3SphereNode
/**
* CC3SphereNode is a type of CC3MeshNode that is specialized to display a simple sphere mesh.
*
* Since a sphere is a mesh like any other mesh, the functionality required to create and
* manipulate sphere meshes is present in the CC3MeshNode class, and if you choose, you can
* create and manage sphere meshes using that class alone.
*
* However, when using bounding volumes, CC3SphereNode returns a spherical bounding volume
* from the defaultBoundingVolume method, instead of the default bounding volume for a
* standard mesh node. This provides a better fit of the bounding volume around the mesh.
*
* You can use the following convenience method to aid in constructing a CC3SphereNode instance:
* - populateAsSphereWithRadius:andTessellation:
*/
@interface CC3SphereNode : CC3MeshNode
@end
#pragma mark -
#pragma mark CC3ClipSpaceNode
/**
* CC3ClipSpaceNode simplifies the creation of a simple rectangular node that can be used
* in the clip-space of the view in order to cover the view with a rectangular image. This
* provides an easy and convenient mechanism for creating backdrops and post-processing effects.
*
* Any mesh node can be configured for rendeirng in the clip-space by setting the shouldDrawInClipSpace
* property is set to YES. This subclass is a convenience class that sets that property to YES during
* instance initialization.
*
* See the notes of the shouldDrawInClipSpace property for further information about drawing
* a node in clip-space.
*/
@interface CC3ClipSpaceNode : CC3MeshNode
/**
* Allocates and initializes and autoreleased instance covered with the specified texture.
*
* This is a convenience method for a common use of this class.
*/
+(id) nodeWithTexture: (CC3Texture*) texture;
/**
* Allocates and initializes and autoreleased instance covered with the specified color.
*
* This is a convenience method for a common use of this class.
*/
+(id) nodeWithColor: (ccColor4F) color;
/**
* Allocates and initializes and autoreleased instance covered with the specified texture.
*
* The name property will be set to the specified name.
*
* This is a convenience method for a common use of this class.
*/
+(id) nodeWithName: (NSString*) name withTexture: (CC3Texture*) texture;
/**
* Allocates and initializes and autoreleased instance covered with the specified color.
*
* The name property will be set to the specified name.
*
* This is a convenience method for a common use of this class.
*/
+(id) nodeWithName: (NSString*) name withColor: (ccColor4F) color;
@end
#pragma mark -
#pragma mark CC3Backdrop
/**
* CC3Backdrop represents a simple full-view static backdrop that is rendered in clip-space.
* The backdrop can be created as a solid color, or a texture, by using either the nodeWithColor:
* or nodeWithTexture: method inherited from the CC3ClipSpaceNode superclass.
*
* See the class notes for the CC3ClipSpaceNode superclass, and the notes of the
* shouldDrawInClipSpace property for further information about drawing a node in clip-space.
*/
@interface CC3Backdrop : CC3ClipSpaceNode
@end
#pragma mark -
#pragma mark CC3WireframeBoundingBoxNode
/**
* CC3WireframeBoundingBoxNode is a type of CC3LineNode specialized for drawing
* a wireframe bounding box around another node. A CC3WireframeBoundingBoxNode
* is typically added as a child node to the node whose bounding box is to
* be displayed.
*
* The CC3WireframeBoundingBoxNode node can be set to automatically track
* the dynamic nature of the boundingBox of the parent node by setting
* the shouldAlwaysMeasureParentBoundingBox property to YES.
*
* Since we don't want to add descriptor labels or wireframe boxes to
* wireframe nodes, the shouldDrawDescriptor, shouldDrawWireframeBox,
* and shouldDrawLocalContentWireframeBox properties are overridden to
* do nothing when set, and to always return YES.
*
* Similarly, CC3WireframeBoundingBoxNode node does not participate in calculating
* the bounding box of the node whose bounding box it is drawing, since, as a child
* of that node, it would interfere with accurate measurement of the bounding box.
*
* The shouldIncludeInDeepCopy property returns NO, so that the CC3WireframeBoundingBoxNode
* will not be copied when the parent node is copied. A bounding box node for the copy
* will be created automatically when each of the shouldDrawLocalContentWireframeBox
* and shouldDrawWireframeBox properties are copied, if they are set to YES on the
* original node that is copied.
*
* A CC3WireframeBoundingBoxNode will continue to be visible even when its ancestor
* nodes are invisible, unless the CC3WireframeBoundingBoxNode itself is made invisible.
*/
@interface CC3WireframeBoundingBoxNode : CC3LineNode {
BOOL _shouldAlwaysMeasureParentBoundingBox : 1;
}
/**
* Indicates whether the dimensions of this node should automatically be
* remeasured on each update pass.
*
* If this property is set to YES, the box will automatically be resized
* to account for movements by any descendant nodes of the parent node.
* For bounding box nodes that track the overall boundingBox of a parent
* node, this property should be set to YES.
*
* It is not necessary to set this property to YES to account for changes in
* the transform properties of the parent node itself, or if this node is
* tracking the bounding box of local content of the parent node. Generally,
* changes to that will automatically be handled by the transform updates.
*
* When setting this property, be aware that measuring the bounding box of
* the parent node can be an expensive operation.
*
* The initial value of this property is NO.
*/
@property(nonatomic, assign) BOOL shouldAlwaysMeasureParentBoundingBox;
#pragma mark Updating
/**
* Updates this wireframe box from the bounding box of the parent node.
*
* The extent of the wireframe box is usually set automatically when first created, and is not
* automatically updated if the parent bounding box changes. If you want this wireframe to update
* automatically on each update frame, set the shouldAlwaysMeasureParentBoundingBox property to YES.
*
* However, updating on each frame can be a drag on performance, so if the parent bounding box
* changes under app control, you can invoke this method whenever the bounding box of the parent
* node changes to keep the wireframe box synchronized with its parent.
*/
-(void) updateFromParentBoundingBox;
@end
#pragma mark -
#pragma mark CC3WireframeLocalContentBoundingBoxNode
/**
* CC3WireframeLocalContentBoundingBoxNode is a CC3WireframeBoundingBoxNode that
* further specializes in drawing a bounding box around the local content of another
* node with local content. A CC3WireframeLocalContentBoundingBoxNode is typically
* added as a child node to the node whose bounding box is to be displayed.
*
* Since for almost all nodes, the local content generally does not change, the
* shouldAlwaysMeasureParentBoundingBox property is usually left at NO, to avoid
* unnecessary remeasuring of the bounding box of the local content of the parent
* node when we know it will not be changing. However, this property can be set to
* YES when adding a CC3WireframeLocalContentBoundingBoxNode to a node whose local
* content does change frequently.
*/
@interface CC3WireframeLocalContentBoundingBoxNode : CC3WireframeBoundingBoxNode
@end
#pragma mark -
#pragma mark CC3DirectionMarkerNode
/**
* CC3DirectionMarkerNode is a type of CC3LineNode specialized for drawing a line from the origin
* of its parent node to a point outside the bounding box of the parent node, in a particular
* direction. A CC3DirectionMarkerNode is typically added as a child node to the node to visibly
* indicate the orientation of the parent node.
*
* The CC3DirectionMarkerNode node can be set to automatically track the dynamic nature of the
* boundingBox of the parent node by setting the shouldAlwaysMeasureParentBoundingBox property to YES.
*
* Since we don't want to add descriptor labels or wireframe boxes to direction marker nodes, the
* shouldDrawDescriptor, shouldDrawWireframeBox, and shouldDrawLocalContentWireframeBox properties
* are overridden to do nothing when set, and to always return YES.
*
* Similarly, CC3DirectionMarkerNode node does not participate in calculating the bounding box of
* the node whose bounding box it is drawing, since, as a child of that node, it would interfere
* with accurate measurement of the bounding box.
*
* The shouldIncludeInDeepCopy property returns YES by default, so that the
* CC3DirectionMarkerNode will be copied when the parent node is copied.
*
* A CC3DirectionMarkerNode will continue to be visible even when its ancestor
* nodes are invisible, unless the CC3DirectionMarkerNode itself is made invisible.
*/
@interface CC3DirectionMarkerNode : CC3WireframeBoundingBoxNode {
CC3Vector _markerDirection;
}
/**
* Indicates the unit direction towards which this line marker will point from
* the origin of the parent node.
*
* When setting the value of this property, the incoming vector will be normalized to a unit vector.
*
* The value of this property defaults to kCC3VectorUnitZNegative, a unit vector
* in the direction of the negative Z-axis, which is the OpenGL ES default direction.
*/
@property(nonatomic, assign) CC3Vector markerDirection;
/**
* Returns the proportional distance that the direction marker line should protrude from the parent
* node. This is measured in proportion to the distance from the origin of the parent node to the
* side of the bounding box through which the line is protruding.
*
* The initial value of this property is 1.5.
*/
+(GLfloat) directionMarkerScale;
/**
* Sets the proportional distance that the direction marker line should protrude from the parent node.
* This is measured in proportion to the distance from the origin of the parent node to the side of
* the bounding box through which the line is protruding.
*
* The initial value of this property is 1.5.
*/
+(void) setDirectionMarkerScale: (GLfloat) scale;
/**
* Returns the minimum length of a direction marker line, expressed in the global
* coordinate system.
*
* Setting a value for this property can be useful for adding direction markers
* to very small nodes, or nodes that do not have volume, such as a camera or light.
*
* The initial value of this property is zero.
*/
+(GLfloat) directionMarkerMinimumLength;
/**
* Sets the minimum length of a direction marker line, expressed in the global
* coordinate system.
*
* Setting a value for this property can be useful for adding direction markers
* to very small nodes, or nodes that do not have volume, such as a camera or light.
*
* The initial value of this property is zero.
*/
+(void) setDirectionMarkerMinimumLength: (GLfloat) len;
@end
#pragma mark -
#pragma mark CC3BoundingVolumeDisplayNode
/**
* CC3BoundingVolumeDisplayNode is a type of CC3MeshNode specialized for displaying
* the bounding volume of its parent node. A CC3BoundingVolumeDisplayNode is typically
* added as a child node to the node whose bounding volume is to be displayed.
*/
@interface CC3BoundingVolumeDisplayNode : CC3MeshNode
@end
#pragma mark -
#pragma mark CC3Fog
/**
* CC3Fog is a mesh node that can render fog in the 3D scene.
*
* Typically, instances of this class are not generally used within the node assembly of a
* scene. Instead, a single instance of this class is used in the fog property of the CC3Scene.
*
* Fog color is controlled by the diffuseColor property.
*
* The style of attenuation imposed by the fog is set by the attenuationMode property.
* See the notes of that property for information about how fog attenuates visibility.
*
* Using the performanceHint property, you can direct the GL engine to trade off between
* faster or nicer rendering quality.
*
* Under OpenGL ES 1.1, fog is implemented as a direct feature of the GL engine, and this
* class establishes the GL state for that fog.
*
* Under OpenGL versions that support GLSL, fog is rendered as a post-processing effect,
* typically by rendering the scene to a surface that has both color and depth textures.
* Add the color and depth textures from the scene-rendering surface to this node, and a
* shader program that can render the node in clip-space, and provide fog effects. A good
* choice is the combination of the CC3ClipSpaceTexturable.vsh vertex shader and the
* CC3Fog.fsh fragment shader.
*/
@interface CC3Fog : CC3MeshNode {
GLenum _attenuationMode;
GLenum _performanceHint;
GLfloat _density;
GLfloat _startDistance;
GLfloat _endDistance;
}
/**
* Indicates how the fog attenuates visibility with distance.
*
* The value of this property must be one of the following sybolic constants:
* GL_LINEAR, GL_EXP or GL_EXP2.
*
* When the value of this property is GL_LINEAR, the relative visibility of an object
* in the fog will be determined by the linear function ((e - z) / (e - s)), where
* s is the value of the start property, e is the value of the end property, and z is
* the distance of the object from the camera
*
* When the value of this property is GL_EXP, the relative visibility of an object in
* the fog will be determined by the exponential function e^(-(d - z)), where d is the
* value of the density property and z is the distance of the object from the camera.
*
* When the value of this property is GL_EXP2, the relative visibility of an object in
* the fog will be determined by the exponential function e^(-(d - z)^2), where d is the
* value of the density property and z is the distance of the object from the camera.
*
* The initial value of this property is GL_EXP2.
*/
@property(nonatomic, assign) GLenum attenuationMode;
/**
* Indicates how the GL engine should trade off between rendering quality and speed.
* The value of this property should be one of GL_FASTEST, GL_NICEST, or GL_DONT_CARE.
*
* The initial value of this property is GL_DONT_CARE.
*/
@property(nonatomic, assign) GLenum performanceHint;
/**
* The density value used in the exponential functions. This property is only used
* when the attenuationMode property is set to GL_EXP or GL_EXP2.
*
* See the description of the attenuationMode for a discussion of how the exponential
* functions determine visibility.
*
* The initial value of this property is 1.0.
*/
@property(nonatomic, assign) GLfloat density;
/**
* The distance from the camera, at which linear attenuation starts. Objects between
* this distance and the near clipping plane of the camera will be completly visible.
*
* This property is only used when the attenuationMode property is set to GL_LINEAR.
*
* See the description of the attenuationMode for a discussion of how the linear
* function determine visibility.
*
* The initial value of this property is 0.0.
*/
@property(nonatomic, assign) GLfloat startDistance;
/**
* The distance from the camera, at which linear attenuation ends. Objects between
* this distance and the far clipping plane of the camera will be completely obscured.
*
* This property is only used when the attenuationMode property is set to GL_LINEAR.
*
* See the description of the attenuationMode for a discussion of how the linear
* function determine visibility.
*
* The initial value of this property is 1.0.
*/
@property(nonatomic, assign) GLfloat endDistance;
#pragma mark Allocation and initialization
/** Allocates and initializes an autoreleased instance. */
+(id) fog;
#pragma mark Deprecated functionality
/** @deprecated Use diffuseColor property instead. */
@property(nonatomic, assign) ccColor4F floatColor __deprecated;
/** @deprecated Use CCActions to control the fog characteristics. */
-(void) update: (CCTime)dt __deprecated;
@end
| 40.391097 | 104 | 0.76907 |
a2a267287268668c219033e00b0649b895189452 | 296 | h | C | build/msvc9/config.h | dornhege/quarter | 44f9db64d507c997ca7e51bb568ff7adc4a7cd68 | [
"BSD-3-Clause"
] | 17 | 2019-12-27T16:39:22.000Z | 2022-02-27T13:38:08.000Z | build/msvc9/config.h | dornhege/quarter | 44f9db64d507c997ca7e51bb568ff7adc4a7cd68 | [
"BSD-3-Clause"
] | 19 | 2019-12-25T18:42:26.000Z | 2022-03-16T22:06:01.000Z | build/msvc9/config.h | dornhege/quarter | 44f9db64d507c997ca7e51bb568ff7adc4a7cd68 | [
"BSD-3-Clause"
] | 19 | 2020-01-01T15:23:45.000Z | 2022-02-14T12:10:51.000Z | #ifndef QUARTER_DEBUG
#error The define QUARTER_DEBUG needs to be defined to true or false
#endif
#ifndef QUARTER_INTERNAL
#error this is a private header file
#endif
#if QUARTER_DEBUG
#include "config-debug.h"
#else /* !QUARTER_DEBUG */
#include "config-release.h"
#endif /* !QUARTER_DEBUG */
| 21.142857 | 68 | 0.763514 |
a2d0c157c96af77b616e95c81c87137d98a64834 | 749 | h | C | System/Library/PrivateFrameworks/GameCenterUI.framework/GKDetachedContentView.h | lechium/tvOS130Headers | 6b47cdcd4a6f453b399aa9d742b5d0f7e3f732fd | [
"MIT"
] | 11 | 2019-11-06T04:48:48.000Z | 2022-02-09T17:48:15.000Z | System/Library/PrivateFrameworks/GameCenterUI.framework/GKDetachedContentView.h | lechium/tvOS130Headers | 6b47cdcd4a6f453b399aa9d742b5d0f7e3f732fd | [
"MIT"
] | 1 | 2020-04-16T01:41:56.000Z | 2020-04-16T04:32:00.000Z | System/Library/PrivateFrameworks/GameCenterUI.framework/GKDetachedContentView.h | lechium/tvOS130Headers | 6b47cdcd4a6f453b399aa9d742b5d0f7e3f732fd | [
"MIT"
] | 3 | 2019-12-22T20:17:53.000Z | 2021-01-25T09:47:49.000Z | /*
* This header is generated by classdump-dyld 1.0
* on Tuesday, November 5, 2019 at 2:40:54 AM Mountain Standard Time
* Operating System: Version 13.0 (Build 17J586)
* Image Source: /System/Library/PrivateFrameworks/GameCenterUI.framework/GameCenterUI
* classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by Elias Limneos.
*/
#import <UIKitCore/UIView.h>
@class GKStaticRenderContentView;
@interface GKDetachedContentView : UIView {
GKStaticRenderContentView* _renderView;
}
@property (assign,nonatomic) GKStaticRenderContentView * renderView; //@synthesize renderView=_renderView - In the implementation block
-(GKStaticRenderContentView *)renderView;
-(void)setRenderView:(GKStaticRenderContentView *)arg1 ;
@end
| 31.208333 | 148 | 0.779706 |
ec959298197a2c46b72b1e8778e1ed50ca075bcb | 2,331 | h | C | src/logger.h | pmswga/suspicious-scanner | 5ec29c7619981c8de67a221c00a33db335667eae | [
"Unlicense"
] | null | null | null | src/logger.h | pmswga/suspicious-scanner | 5ec29c7619981c8de67a221c00a33db335667eae | [
"Unlicense"
] | null | null | null | src/logger.h | pmswga/suspicious-scanner | 5ec29c7619981c8de67a221c00a33db335667eae | [
"Unlicense"
] | null | null | null | #ifndef LOGGER_H
#define LOGGER_H
#include <chrono>
#include <vector>
#include <string>
#include <map>
#include "logger_entry.h"
#include "validator_code.h"
using LoggerEntries = std::vector<LoggerEntry*>;
using LoggerDetections = std::map<std::string, int>;
class Logger
{
LoggerEntries logs;
LoggerDetections detections;
public:
explicit Logger()
{
}
virtual ~Logger()
{
if (!logs.empty())
{
for (auto log : this->logs)
{
if (log)
{
delete log;
}
}
}
}
void addLog(LoggerEntry *log)
{
if (log)
{
this->logs.push_back(log);
}
}
void addDetection(std::string rule_name)
{
if (this->detections.count(rule_name) == 1)
{
this->detections.at(rule_name)++;
} else {
this->detections.insert(std::pair(rule_name, 1));
}
}
auto getDetectionLogs() const -> LoggerEntries
{
LoggerEntries detectionLogs;
if (!this->logs.empty())
{
for (const auto &log : this->logs)
{
if (log->getValidationRuleId() > 0)
{
detectionLogs.push_back(log);
}
}
}
return detectionLogs;
}
auto getErrorLogs() const -> LoggerEntries
{
LoggerEntries errorLogs;
if (!this->logs.empty())
{
for (const auto &log : this->logs)
{
if (!log->getErrors().empty())
{
errorLogs.push_back(log);
}
}
}
return errorLogs;
}
auto getValidatedLogs() const -> LoggerEntries
{
LoggerEntries validatedLogs;
if (!this->logs.empty())
{
for (const auto &log : this->logs)
{
if (log->getValidationCode() == FILE_VALIDATED && log->getValidationRuleId() == 0)
{
validatedLogs.push_back(log);
}
}
}
return validatedLogs;
}
auto getLogs() const -> LoggerEntries
{
return this->logs;
}
};
#endif // LOGGER_H
| 19.106557 | 98 | 0.466323 |
ece37d3cbd94a07ef3def5565c1bda9dbd3c76c8 | 1,090 | c | C | lib/libft/src/ft_sqrt.c | W2Codam/MiniRT | 4a98cc8f2d620a980a4fabd9a42270b7be9a7720 | [
"MIT"
] | null | null | null | lib/libft/src/ft_sqrt.c | W2Codam/MiniRT | 4a98cc8f2d620a980a4fabd9a42270b7be9a7720 | [
"MIT"
] | null | null | null | lib/libft/src/ft_sqrt.c | W2Codam/MiniRT | 4a98cc8f2d620a980a4fabd9a42270b7be9a7720 | [
"MIT"
] | null | null | null | /* ************************************************************************** */
/* */
/* :::::::: */
/* ft_sqrt.c :+: :+: */
/* +:+ */
/* By: lde-la-h <lde-la-h@student.codam.nl> +#+ */
/* +#+ */
/* Created: 2021/10/05 10:46:35 by lde-la-h #+# #+# */
/* Updated: 2022/03/28 14:19:48 by lde-la-h ######## odam.nl */
/* */
/* ************************************************************************** */
#include "libft.h"
int32_t ft_sqrt(int32_t num)
{
int32_t sqrt;
sqrt = 0;
while ((sqrt * sqrt) <= num && sqrt <= 46340)
{
if ((sqrt * sqrt) == num)
break ;
sqrt++;
}
return (sqrt);
}
| 38.928571 | 80 | 0.192661 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.